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 path_dir = realpath(argv[0], NULL);
837 if (path_dir == NULL) {
838 error = got_error_from_errno2("realpath", argv[0]);
839 goto done;
841 got_path_strip_trailing_slashes(path_dir);
843 error = get_editor(&editor);
844 if (error)
845 goto done;
847 if (unveil(path_dir, "r") != 0) {
848 error = got_error_from_errno2("unveil", path_dir);
849 goto done;
851 if (unveil(editor, "x") != 0) {
852 error = got_error_from_errno2("unveil", editor);
853 goto done;
855 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
856 if (error)
857 goto done;
859 error = get_author(&author, repo, NULL);
860 if (error)
861 return error;
863 /*
864 * Don't let the user create a branch name with a leading '-'.
865 * While technically a valid reference name, this case is usually
866 * an unintended typo.
867 */
868 if (branch_name && branch_name[0] == '-')
869 return got_error_path(branch_name, GOT_ERR_REF_NAME_MINUS);
871 error = got_ref_open(&head_ref, repo, GOT_REF_HEAD, 0);
872 if (error && error->code != GOT_ERR_NOT_REF)
873 goto done;
875 if (branch_name)
876 n = strlcat(refname, branch_name, sizeof(refname));
877 else if (head_ref && got_ref_is_symbolic(head_ref))
878 n = strlcpy(refname, got_ref_get_symref_target(head_ref),
879 sizeof(refname));
880 else
881 n = strlcat(refname, "main", sizeof(refname));
882 if (n >= sizeof(refname)) {
883 error = got_error(GOT_ERR_NO_SPACE);
884 goto done;
887 error = got_ref_open(&branch_ref, repo, refname, 0);
888 if (error) {
889 if (error->code != GOT_ERR_NOT_REF)
890 goto done;
891 } else {
892 error = got_error_msg(GOT_ERR_BRANCH_EXISTS,
893 "import target branch already exists");
894 goto done;
897 if (logmsg == NULL || *logmsg == '\0') {
898 free(logmsg);
899 error = collect_import_msg(&logmsg, &logmsg_path, editor,
900 path_dir, refname);
901 if (error) {
902 if (error->code != GOT_ERR_COMMIT_MSG_EMPTY &&
903 logmsg_path != NULL)
904 preserve_logmsg = 1;
905 goto done;
909 error = got_repo_import(&new_commit_id, path_dir, logmsg,
910 author, &ignores, repo, import_progress, NULL);
911 if (error) {
912 if (logmsg_path)
913 preserve_logmsg = 1;
914 goto done;
917 error = got_ref_alloc(&branch_ref, refname, new_commit_id);
918 if (error) {
919 if (logmsg_path)
920 preserve_logmsg = 1;
921 goto done;
924 error = got_ref_write(branch_ref, repo);
925 if (error) {
926 if (logmsg_path)
927 preserve_logmsg = 1;
928 goto done;
931 error = got_object_id_str(&id_str, new_commit_id);
932 if (error) {
933 if (logmsg_path)
934 preserve_logmsg = 1;
935 goto done;
938 error = got_ref_open(&head_ref, repo, GOT_REF_HEAD, 0);
939 if (error) {
940 if (error->code != GOT_ERR_NOT_REF) {
941 if (logmsg_path)
942 preserve_logmsg = 1;
943 goto done;
946 error = got_ref_alloc_symref(&head_ref, GOT_REF_HEAD,
947 branch_ref);
948 if (error) {
949 if (logmsg_path)
950 preserve_logmsg = 1;
951 goto done;
954 error = got_ref_write(head_ref, repo);
955 if (error) {
956 if (logmsg_path)
957 preserve_logmsg = 1;
958 goto done;
962 printf("Created branch %s with commit %s\n",
963 got_ref_get_name(branch_ref), id_str);
964 done:
965 if (pack_fds) {
966 const struct got_error *pack_err =
967 got_repo_pack_fds_close(pack_fds);
968 if (error == NULL)
969 error = pack_err;
971 if (repo) {
972 const struct got_error *close_err = got_repo_close(repo);
973 if (error == NULL)
974 error = close_err;
976 if (preserve_logmsg) {
977 fprintf(stderr, "%s: log message preserved in %s\n",
978 getprogname(), logmsg_path);
979 } else if (logmsg_path && unlink(logmsg_path) == -1 && error == NULL)
980 error = got_error_from_errno2("unlink", logmsg_path);
981 free(logmsg);
982 free(logmsg_path);
983 free(repo_path);
984 free(editor);
985 free(new_commit_id);
986 free(id_str);
987 free(author);
988 free(gitconfig_path);
989 if (branch_ref)
990 got_ref_close(branch_ref);
991 if (head_ref)
992 got_ref_close(head_ref);
993 return error;
996 __dead static void
997 usage_clone(void)
999 fprintf(stderr, "usage: %s clone [-almqv] [-b branch] [-R reference] "
1000 "repository-URL [directory]\n", getprogname());
1001 exit(1);
1004 struct got_fetch_progress_arg {
1005 char last_scaled_size[FMT_SCALED_STRSIZE];
1006 int last_p_indexed;
1007 int last_p_resolved;
1008 int verbosity;
1010 struct got_repository *repo;
1012 int create_configs;
1013 int configs_created;
1014 struct {
1015 struct got_pathlist_head *symrefs;
1016 struct got_pathlist_head *wanted_branches;
1017 struct got_pathlist_head *wanted_refs;
1018 const char *proto;
1019 const char *host;
1020 const char *port;
1021 const char *remote_repo_path;
1022 const char *git_url;
1023 int fetch_all_branches;
1024 int mirror_references;
1025 } config_info;
1028 /* XXX forward declaration */
1029 static const struct got_error *
1030 create_config_files(const char *proto, const char *host, const char *port,
1031 const char *remote_repo_path, const char *git_url, int fetch_all_branches,
1032 int mirror_references, struct got_pathlist_head *symrefs,
1033 struct got_pathlist_head *wanted_branches,
1034 struct got_pathlist_head *wanted_refs, struct got_repository *repo);
1036 static const struct got_error *
1037 fetch_progress(void *arg, const char *message, off_t packfile_size,
1038 int nobj_total, int nobj_indexed, int nobj_loose, int nobj_resolved)
1040 const struct got_error *err = NULL;
1041 struct got_fetch_progress_arg *a = arg;
1042 char scaled_size[FMT_SCALED_STRSIZE];
1043 int p_indexed, p_resolved;
1044 int print_size = 0, print_indexed = 0, print_resolved = 0;
1047 * In order to allow a failed clone to be resumed with 'got fetch'
1048 * we try to create configuration files as soon as possible.
1049 * Once the server has sent information about its default branch
1050 * we have all required information.
1052 if (a->create_configs && !a->configs_created &&
1053 !TAILQ_EMPTY(a->config_info.symrefs)) {
1054 err = create_config_files(a->config_info.proto,
1055 a->config_info.host, a->config_info.port,
1056 a->config_info.remote_repo_path,
1057 a->config_info.git_url,
1058 a->config_info.fetch_all_branches,
1059 a->config_info.mirror_references,
1060 a->config_info.symrefs,
1061 a->config_info.wanted_branches,
1062 a->config_info.wanted_refs, a->repo);
1063 if (err)
1064 return err;
1065 a->configs_created = 1;
1068 if (a->verbosity < 0)
1069 return NULL;
1071 if (message && message[0] != '\0') {
1072 printf("\rserver: %s", message);
1073 fflush(stdout);
1074 return NULL;
1077 if (packfile_size > 0 || nobj_indexed > 0) {
1078 if (fmt_scaled(packfile_size, scaled_size) == 0 &&
1079 (a->last_scaled_size[0] == '\0' ||
1080 strcmp(scaled_size, a->last_scaled_size)) != 0) {
1081 print_size = 1;
1082 if (strlcpy(a->last_scaled_size, scaled_size,
1083 FMT_SCALED_STRSIZE) >= FMT_SCALED_STRSIZE)
1084 return got_error(GOT_ERR_NO_SPACE);
1086 if (nobj_indexed > 0) {
1087 p_indexed = (nobj_indexed * 100) / nobj_total;
1088 if (p_indexed != a->last_p_indexed) {
1089 a->last_p_indexed = p_indexed;
1090 print_indexed = 1;
1091 print_size = 1;
1094 if (nobj_resolved > 0) {
1095 p_resolved = (nobj_resolved * 100) /
1096 (nobj_total - nobj_loose);
1097 if (p_resolved != a->last_p_resolved) {
1098 a->last_p_resolved = p_resolved;
1099 print_resolved = 1;
1100 print_indexed = 1;
1101 print_size = 1;
1106 if (print_size || print_indexed || print_resolved)
1107 printf("\r");
1108 if (print_size)
1109 printf("%*s fetched", FMT_SCALED_STRSIZE - 2, scaled_size);
1110 if (print_indexed)
1111 printf("; indexing %d%%", p_indexed);
1112 if (print_resolved)
1113 printf("; resolving deltas %d%%", p_resolved);
1114 if (print_size || print_indexed || print_resolved)
1115 fflush(stdout);
1117 return NULL;
1120 static const struct got_error *
1121 create_symref(const char *refname, struct got_reference *target_ref,
1122 int verbosity, struct got_repository *repo)
1124 const struct got_error *err;
1125 struct got_reference *head_symref;
1127 err = got_ref_alloc_symref(&head_symref, refname, target_ref);
1128 if (err)
1129 return err;
1131 err = got_ref_write(head_symref, repo);
1132 if (err == NULL && verbosity > 0) {
1133 printf("Created reference %s: %s\n", GOT_REF_HEAD,
1134 got_ref_get_name(target_ref));
1136 got_ref_close(head_symref);
1137 return err;
1140 static const struct got_error *
1141 list_remote_refs(struct got_pathlist_head *symrefs,
1142 struct got_pathlist_head *refs)
1144 const struct got_error *err;
1145 struct got_pathlist_entry *pe;
1147 TAILQ_FOREACH(pe, symrefs, entry) {
1148 const char *refname = pe->path;
1149 const char *targetref = pe->data;
1151 printf("%s: %s\n", refname, targetref);
1154 TAILQ_FOREACH(pe, refs, entry) {
1155 const char *refname = pe->path;
1156 struct got_object_id *id = pe->data;
1157 char *id_str;
1159 err = got_object_id_str(&id_str, id);
1160 if (err)
1161 return err;
1162 printf("%s: %s\n", refname, id_str);
1163 free(id_str);
1166 return NULL;
1169 static const struct got_error *
1170 create_ref(const char *refname, struct got_object_id *id,
1171 int verbosity, struct got_repository *repo)
1173 const struct got_error *err = NULL;
1174 struct got_reference *ref;
1175 char *id_str;
1177 err = got_object_id_str(&id_str, id);
1178 if (err)
1179 return err;
1181 err = got_ref_alloc(&ref, refname, id);
1182 if (err)
1183 goto done;
1185 err = got_ref_write(ref, repo);
1186 got_ref_close(ref);
1188 if (err == NULL && verbosity >= 0)
1189 printf("Created reference %s: %s\n", refname, id_str);
1190 done:
1191 free(id_str);
1192 return err;
1195 static int
1196 match_wanted_ref(const char *refname, const char *wanted_ref)
1198 if (strncmp(refname, "refs/", 5) != 0)
1199 return 0;
1200 refname += 5;
1203 * Prevent fetching of references that won't make any
1204 * sense outside of the remote repository's context.
1206 if (strncmp(refname, "got/", 4) == 0)
1207 return 0;
1208 if (strncmp(refname, "remotes/", 8) == 0)
1209 return 0;
1211 if (strncmp(wanted_ref, "refs/", 5) == 0)
1212 wanted_ref += 5;
1214 /* Allow prefix match. */
1215 if (got_path_is_child(refname, wanted_ref, strlen(wanted_ref)))
1216 return 1;
1218 /* Allow exact match. */
1219 return (strcmp(refname, wanted_ref) == 0);
1222 static int
1223 is_wanted_ref(struct got_pathlist_head *wanted_refs, const char *refname)
1225 struct got_pathlist_entry *pe;
1227 TAILQ_FOREACH(pe, wanted_refs, entry) {
1228 if (match_wanted_ref(refname, pe->path))
1229 return 1;
1232 return 0;
1235 static const struct got_error *
1236 create_wanted_ref(const char *refname, struct got_object_id *id,
1237 const char *remote_repo_name, int verbosity, struct got_repository *repo)
1239 const struct got_error *err;
1240 char *remote_refname;
1242 if (strncmp("refs/", refname, 5) == 0)
1243 refname += 5;
1245 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
1246 remote_repo_name, refname) == -1)
1247 return got_error_from_errno("asprintf");
1249 err = create_ref(remote_refname, id, verbosity, repo);
1250 free(remote_refname);
1251 return err;
1254 static const struct got_error *
1255 create_gotconfig(const char *proto, const char *host, const char *port,
1256 const char *remote_repo_path, const char *default_branch,
1257 int fetch_all_branches, struct got_pathlist_head *wanted_branches,
1258 struct got_pathlist_head *wanted_refs, int mirror_references,
1259 struct got_repository *repo)
1261 const struct got_error *err = NULL;
1262 char *gotconfig_path = NULL;
1263 char *gotconfig = NULL;
1264 FILE *gotconfig_file = NULL;
1265 const char *branchname = NULL;
1266 char *branches = NULL, *refs = NULL;
1267 ssize_t n;
1269 if (!fetch_all_branches && !TAILQ_EMPTY(wanted_branches)) {
1270 struct got_pathlist_entry *pe;
1271 TAILQ_FOREACH(pe, wanted_branches, entry) {
1272 char *s;
1273 branchname = pe->path;
1274 if (strncmp(branchname, "refs/heads/", 11) == 0)
1275 branchname += 11;
1276 if (asprintf(&s, "%s\"%s\" ",
1277 branches ? branches : "", branchname) == -1) {
1278 err = got_error_from_errno("asprintf");
1279 goto done;
1281 free(branches);
1282 branches = s;
1284 } else if (!fetch_all_branches && default_branch) {
1285 branchname = default_branch;
1286 if (strncmp(branchname, "refs/heads/", 11) == 0)
1287 branchname += 11;
1288 if (asprintf(&branches, "\"%s\" ", branchname) == -1) {
1289 err = got_error_from_errno("asprintf");
1290 goto done;
1293 if (!TAILQ_EMPTY(wanted_refs)) {
1294 struct got_pathlist_entry *pe;
1295 TAILQ_FOREACH(pe, wanted_refs, entry) {
1296 char *s;
1297 const char *refname = pe->path;
1298 if (strncmp(refname, "refs/", 5) == 0)
1299 branchname += 5;
1300 if (asprintf(&s, "%s\"%s\" ",
1301 refs ? refs : "", refname) == -1) {
1302 err = got_error_from_errno("asprintf");
1303 goto done;
1305 free(refs);
1306 refs = s;
1310 /* Create got.conf(5). */
1311 gotconfig_path = got_repo_get_path_gotconfig(repo);
1312 if (gotconfig_path == NULL) {
1313 err = got_error_from_errno("got_repo_get_path_gotconfig");
1314 goto done;
1316 gotconfig_file = fopen(gotconfig_path, "ae");
1317 if (gotconfig_file == NULL) {
1318 err = got_error_from_errno2("fopen", gotconfig_path);
1319 goto done;
1321 if (asprintf(&gotconfig,
1322 "remote \"%s\" {\n"
1323 "\tserver %s\n"
1324 "\tprotocol %s\n"
1325 "%s%s%s"
1326 "\trepository \"%s\"\n"
1327 "%s%s%s"
1328 "%s%s%s"
1329 "%s"
1330 "%s"
1331 "}\n",
1332 GOT_FETCH_DEFAULT_REMOTE_NAME, host, proto,
1333 port ? "\tport " : "", port ? port : "", port ? "\n" : "",
1334 remote_repo_path, branches ? "\tbranch { " : "",
1335 branches ? branches : "", branches ? "}\n" : "",
1336 refs ? "\treference { " : "", refs ? refs : "", refs ? "}\n" : "",
1337 mirror_references ? "\tmirror_references yes\n" : "",
1338 fetch_all_branches ? "\tfetch_all_branches yes\n" : "") == -1) {
1339 err = got_error_from_errno("asprintf");
1340 goto done;
1342 n = fwrite(gotconfig, 1, strlen(gotconfig), gotconfig_file);
1343 if (n != strlen(gotconfig)) {
1344 err = got_ferror(gotconfig_file, GOT_ERR_IO);
1345 goto done;
1348 done:
1349 if (gotconfig_file && fclose(gotconfig_file) == EOF && err == NULL)
1350 err = got_error_from_errno2("fclose", gotconfig_path);
1351 free(gotconfig_path);
1352 free(branches);
1353 return err;
1356 static const struct got_error *
1357 create_gitconfig(const char *git_url, const char *default_branch,
1358 int fetch_all_branches, struct got_pathlist_head *wanted_branches,
1359 struct got_pathlist_head *wanted_refs, int mirror_references,
1360 struct got_repository *repo)
1362 const struct got_error *err = NULL;
1363 char *gitconfig_path = NULL;
1364 char *gitconfig = NULL;
1365 FILE *gitconfig_file = NULL;
1366 char *branches = NULL, *refs = NULL;
1367 const char *branchname;
1368 ssize_t n;
1370 /* Create a config file Git can understand. */
1371 gitconfig_path = got_repo_get_path_gitconfig(repo);
1372 if (gitconfig_path == NULL) {
1373 err = got_error_from_errno("got_repo_get_path_gitconfig");
1374 goto done;
1376 gitconfig_file = fopen(gitconfig_path, "ae");
1377 if (gitconfig_file == NULL) {
1378 err = got_error_from_errno2("fopen", gitconfig_path);
1379 goto done;
1381 if (fetch_all_branches) {
1382 if (mirror_references) {
1383 if (asprintf(&branches,
1384 "\tfetch = refs/heads/*:refs/heads/*\n") == -1) {
1385 err = got_error_from_errno("asprintf");
1386 goto done;
1388 } else if (asprintf(&branches,
1389 "\tfetch = refs/heads/*:refs/remotes/%s/*\n",
1390 GOT_FETCH_DEFAULT_REMOTE_NAME) == -1) {
1391 err = got_error_from_errno("asprintf");
1392 goto done;
1394 } else if (!TAILQ_EMPTY(wanted_branches)) {
1395 struct got_pathlist_entry *pe;
1396 TAILQ_FOREACH(pe, wanted_branches, entry) {
1397 char *s;
1398 branchname = pe->path;
1399 if (strncmp(branchname, "refs/heads/", 11) == 0)
1400 branchname += 11;
1401 if (mirror_references) {
1402 if (asprintf(&s,
1403 "%s\tfetch = refs/heads/%s:refs/heads/%s\n",
1404 branches ? branches : "",
1405 branchname, branchname) == -1) {
1406 err = got_error_from_errno("asprintf");
1407 goto done;
1409 } else if (asprintf(&s,
1410 "%s\tfetch = refs/heads/%s:refs/remotes/%s/%s\n",
1411 branches ? branches : "",
1412 branchname, GOT_FETCH_DEFAULT_REMOTE_NAME,
1413 branchname) == -1) {
1414 err = got_error_from_errno("asprintf");
1415 goto done;
1417 free(branches);
1418 branches = s;
1420 } else {
1422 * If the server specified a default branch, use just that one.
1423 * Otherwise fall back to fetching all branches on next fetch.
1425 if (default_branch) {
1426 branchname = default_branch;
1427 if (strncmp(branchname, "refs/heads/", 11) == 0)
1428 branchname += 11;
1429 } else
1430 branchname = "*"; /* fall back to all branches */
1431 if (mirror_references) {
1432 if (asprintf(&branches,
1433 "\tfetch = refs/heads/%s:refs/heads/%s\n",
1434 branchname, branchname) == -1) {
1435 err = got_error_from_errno("asprintf");
1436 goto done;
1438 } else if (asprintf(&branches,
1439 "\tfetch = refs/heads/%s:refs/remotes/%s/%s\n",
1440 branchname, GOT_FETCH_DEFAULT_REMOTE_NAME,
1441 branchname) == -1) {
1442 err = got_error_from_errno("asprintf");
1443 goto done;
1446 if (!TAILQ_EMPTY(wanted_refs)) {
1447 struct got_pathlist_entry *pe;
1448 TAILQ_FOREACH(pe, wanted_refs, entry) {
1449 char *s;
1450 const char *refname = pe->path;
1451 if (strncmp(refname, "refs/", 5) == 0)
1452 refname += 5;
1453 if (mirror_references) {
1454 if (asprintf(&s,
1455 "%s\tfetch = refs/%s:refs/%s\n",
1456 refs ? refs : "", refname, refname) == -1) {
1457 err = got_error_from_errno("asprintf");
1458 goto done;
1460 } else if (asprintf(&s,
1461 "%s\tfetch = refs/%s:refs/remotes/%s/%s\n",
1462 refs ? refs : "",
1463 refname, GOT_FETCH_DEFAULT_REMOTE_NAME,
1464 refname) == -1) {
1465 err = got_error_from_errno("asprintf");
1466 goto done;
1468 free(refs);
1469 refs = s;
1473 if (asprintf(&gitconfig,
1474 "[remote \"%s\"]\n"
1475 "\turl = %s\n"
1476 "%s"
1477 "%s"
1478 "\tfetch = refs/tags/*:refs/tags/*\n",
1479 GOT_FETCH_DEFAULT_REMOTE_NAME, git_url, branches ? branches : "",
1480 refs ? refs : "") == -1) {
1481 err = got_error_from_errno("asprintf");
1482 goto done;
1484 n = fwrite(gitconfig, 1, strlen(gitconfig), gitconfig_file);
1485 if (n != strlen(gitconfig)) {
1486 err = got_ferror(gitconfig_file, GOT_ERR_IO);
1487 goto done;
1489 done:
1490 if (gitconfig_file && fclose(gitconfig_file) == EOF && err == NULL)
1491 err = got_error_from_errno2("fclose", gitconfig_path);
1492 free(gitconfig_path);
1493 free(branches);
1494 return err;
1497 static const struct got_error *
1498 create_config_files(const char *proto, const char *host, const char *port,
1499 const char *remote_repo_path, const char *git_url, int fetch_all_branches,
1500 int mirror_references, struct got_pathlist_head *symrefs,
1501 struct got_pathlist_head *wanted_branches,
1502 struct got_pathlist_head *wanted_refs, struct got_repository *repo)
1504 const struct got_error *err = NULL;
1505 const char *default_branch = NULL;
1506 struct got_pathlist_entry *pe;
1509 * If we asked for a set of wanted branches then use the first
1510 * one of those.
1512 if (!TAILQ_EMPTY(wanted_branches)) {
1513 pe = TAILQ_FIRST(wanted_branches);
1514 default_branch = pe->path;
1515 } else {
1516 /* First HEAD ref listed by server is the default branch. */
1517 TAILQ_FOREACH(pe, symrefs, entry) {
1518 const char *refname = pe->path;
1519 const char *target = pe->data;
1521 if (strcmp(refname, GOT_REF_HEAD) != 0)
1522 continue;
1524 default_branch = target;
1525 break;
1529 /* Create got.conf(5). */
1530 err = create_gotconfig(proto, host, port, remote_repo_path,
1531 default_branch, fetch_all_branches, wanted_branches,
1532 wanted_refs, mirror_references, repo);
1533 if (err)
1534 return err;
1536 /* Create a config file Git can understand. */
1537 return create_gitconfig(git_url, default_branch, fetch_all_branches,
1538 wanted_branches, wanted_refs, mirror_references, repo);
1541 static const struct got_error *
1542 cmd_clone(int argc, char *argv[])
1544 const struct got_error *error = NULL;
1545 const char *uri, *dirname;
1546 char *proto, *host, *port, *repo_name, *server_path;
1547 char *default_destdir = NULL, *id_str = NULL;
1548 const char *repo_path;
1549 struct got_repository *repo = NULL;
1550 struct got_pathlist_head refs, symrefs, wanted_branches, wanted_refs;
1551 struct got_pathlist_entry *pe;
1552 struct got_object_id *pack_hash = NULL;
1553 int ch, fetchfd = -1, fetchstatus;
1554 pid_t fetchpid = -1;
1555 struct got_fetch_progress_arg fpa;
1556 char *git_url = NULL;
1557 int verbosity = 0, fetch_all_branches = 0, mirror_references = 0;
1558 int bflag = 0, list_refs_only = 0;
1559 int *pack_fds = NULL;
1561 TAILQ_INIT(&refs);
1562 TAILQ_INIT(&symrefs);
1563 TAILQ_INIT(&wanted_branches);
1564 TAILQ_INIT(&wanted_refs);
1566 while ((ch = getopt(argc, argv, "ab:lmqR:v")) != -1) {
1567 switch (ch) {
1568 case 'a':
1569 fetch_all_branches = 1;
1570 break;
1571 case 'b':
1572 error = got_pathlist_append(&wanted_branches,
1573 optarg, NULL);
1574 if (error)
1575 return error;
1576 bflag = 1;
1577 break;
1578 case 'l':
1579 list_refs_only = 1;
1580 break;
1581 case 'm':
1582 mirror_references = 1;
1583 break;
1584 case 'q':
1585 verbosity = -1;
1586 break;
1587 case 'R':
1588 error = got_pathlist_append(&wanted_refs,
1589 optarg, NULL);
1590 if (error)
1591 return error;
1592 break;
1593 case 'v':
1594 if (verbosity < 0)
1595 verbosity = 0;
1596 else if (verbosity < 3)
1597 verbosity++;
1598 break;
1599 default:
1600 usage_clone();
1601 break;
1604 argc -= optind;
1605 argv += optind;
1607 if (fetch_all_branches && !TAILQ_EMPTY(&wanted_branches))
1608 option_conflict('a', 'b');
1609 if (list_refs_only) {
1610 if (!TAILQ_EMPTY(&wanted_branches))
1611 option_conflict('l', 'b');
1612 if (fetch_all_branches)
1613 option_conflict('l', 'a');
1614 if (mirror_references)
1615 option_conflict('l', 'm');
1616 if (!TAILQ_EMPTY(&wanted_refs))
1617 option_conflict('l', 'R');
1620 uri = argv[0];
1622 if (argc == 1)
1623 dirname = NULL;
1624 else if (argc == 2)
1625 dirname = argv[1];
1626 else
1627 usage_clone();
1629 error = got_dial_parse_uri(&proto, &host, &port, &server_path,
1630 &repo_name, uri);
1631 if (error)
1632 goto done;
1634 if (asprintf(&git_url, "%s://%s%s%s%s%s", proto,
1635 host, port ? ":" : "", port ? port : "",
1636 server_path[0] != '/' ? "/" : "", server_path) == -1) {
1637 error = got_error_from_errno("asprintf");
1638 goto done;
1641 if (strcmp(proto, "git") == 0) {
1642 #ifndef PROFILE
1643 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
1644 "sendfd dns inet unveil", NULL) == -1)
1645 err(1, "pledge");
1646 #endif
1647 } else if (strcmp(proto, "git+ssh") == 0 ||
1648 strcmp(proto, "ssh") == 0 ||
1649 strcmp(proto, "git+http") == 0 ||
1650 strcmp(proto, "http") == 0 ||
1651 strcmp(proto, "git+https") == 0 ||
1652 strcmp(proto, "https") == 0) {
1653 #ifndef PROFILE
1654 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
1655 "sendfd unveil", NULL) == -1)
1656 err(1, "pledge");
1657 #endif
1658 } else {
1659 error = got_error_path(proto, GOT_ERR_BAD_PROTO);
1660 goto done;
1662 if (dirname == NULL) {
1663 if (asprintf(&default_destdir, "%s.git", repo_name) == -1) {
1664 error = got_error_from_errno("asprintf");
1665 goto done;
1667 repo_path = default_destdir;
1668 } else
1669 repo_path = dirname;
1671 if (!list_refs_only) {
1672 error = got_path_mkdir(repo_path);
1673 if (error &&
1674 (!(error->code == GOT_ERR_ERRNO && errno == EISDIR) &&
1675 !(error->code == GOT_ERR_ERRNO && errno == EEXIST)))
1676 goto done;
1677 if (!got_path_dir_is_empty(repo_path)) {
1678 error = got_error_path(repo_path,
1679 GOT_ERR_DIR_NOT_EMPTY);
1680 goto done;
1684 error = got_dial_apply_unveil(proto);
1685 if (error)
1686 goto done;
1688 error = apply_unveil(repo_path, 0, NULL);
1689 if (error)
1690 goto done;
1692 if (verbosity >= 0)
1693 printf("Connecting to %s\n", git_url);
1695 error = got_fetch_connect(&fetchpid, &fetchfd, proto, host, port,
1696 server_path, verbosity);
1697 if (error)
1698 goto done;
1700 #ifndef PROFILE
1701 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd",
1702 NULL) == -1)
1703 err(1, "pledge");
1704 #endif
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 strcmp(proto, "git+http") == 0 ||
2532 strcmp(proto, "http") == 0 ||
2533 strcmp(proto, "git+https") == 0 ||
2534 strcmp(proto, "https") == 0) {
2535 #ifndef PROFILE
2536 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
2537 "sendfd unveil", NULL) == -1)
2538 err(1, "pledge");
2539 #endif
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;
2576 #ifndef PROFILE
2577 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd",
2578 NULL) == -1)
2579 err(1, "pledge");
2580 #endif
2581 if (!have_bflag) {
2583 * If set, get this remote's HEAD ref target so
2584 * if it has changed on the server we can fetch it.
2586 error = got_ref_list(&remote_refs, repo, "refs/remotes",
2587 got_ref_cmp_by_name, repo);
2588 if (error)
2589 goto done;
2591 TAILQ_FOREACH(re, &remote_refs, entry) {
2592 const char *remote_refname, *remote_target;
2593 size_t remote_name_len;
2595 if (!got_ref_is_symbolic(re->ref))
2596 continue;
2598 remote_name_len = strlen(remote->name);
2599 remote_refname = got_ref_get_name(re->ref);
2601 /* we only want refs/remotes/$remote->name/HEAD */
2602 if (strncmp(remote_refname + 13, remote->name,
2603 remote_name_len) != 0)
2604 continue;
2606 if (strcmp(remote_refname + remote_name_len + 14,
2607 GOT_REF_HEAD) != 0)
2608 continue;
2611 * Take the name itself because we already
2612 * only match with refs/heads/ in fetch_pack().
2614 remote_target = got_ref_get_symref_target(re->ref);
2615 remote_head = remote_target + remote_name_len + 14;
2616 break;
2619 if (head_refname &&
2620 strncmp(head_refname, "refs/heads/", 11) == 0)
2621 worktree_branch = head_refname;
2624 fpa.last_scaled_size[0] = '\0';
2625 fpa.last_p_indexed = -1;
2626 fpa.last_p_resolved = -1;
2627 fpa.verbosity = verbosity;
2628 fpa.repo = repo;
2629 fpa.create_configs = 0;
2630 fpa.configs_created = 0;
2631 memset(&fpa.config_info, 0, sizeof(fpa.config_info));
2633 error = got_fetch_pack(&pack_hash, &refs, &symrefs, remote->name,
2634 remote->mirror_references, fetch_all_branches, &wanted_branches,
2635 &wanted_refs, list_refs_only, verbosity, fetchfd, repo,
2636 worktree_branch, remote_head, have_bflag, fetch_progress, &fpa);
2637 if (error)
2638 goto done;
2640 if (list_refs_only) {
2641 error = list_remote_refs(&symrefs, &refs);
2642 goto done;
2645 if (pack_hash == NULL) {
2646 if (verbosity >= 0)
2647 printf("Already up-to-date\n");
2648 } else if (verbosity >= 0) {
2649 error = got_object_id_str(&id_str, pack_hash);
2650 if (error)
2651 goto done;
2652 printf("\nFetched %s.pack\n", id_str);
2653 free(id_str);
2654 id_str = NULL;
2657 /* Update references provided with the pack file. */
2658 TAILQ_FOREACH(pe, &refs, entry) {
2659 const char *refname = pe->path;
2660 struct got_object_id *id = pe->data;
2661 struct got_reference *ref;
2662 char *remote_refname;
2664 if (is_wanted_ref(&wanted_refs, refname) &&
2665 !remote->mirror_references) {
2666 error = update_wanted_ref(refname, id,
2667 remote->name, verbosity, repo);
2668 if (error)
2669 goto done;
2670 continue;
2673 if (remote->mirror_references ||
2674 strncmp("refs/tags/", refname, 10) == 0) {
2675 error = got_ref_open(&ref, repo, refname, 1);
2676 if (error) {
2677 if (error->code != GOT_ERR_NOT_REF)
2678 goto done;
2679 error = create_ref(refname, id, verbosity,
2680 repo);
2681 if (error)
2682 goto done;
2683 } else {
2684 error = update_ref(ref, id, replace_tags,
2685 verbosity, repo);
2686 unlock_err = got_ref_unlock(ref);
2687 if (unlock_err && error == NULL)
2688 error = unlock_err;
2689 got_ref_close(ref);
2690 if (error)
2691 goto done;
2693 } else if (strncmp("refs/heads/", refname, 11) == 0) {
2694 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
2695 remote_name, refname + 11) == -1) {
2696 error = got_error_from_errno("asprintf");
2697 goto done;
2700 error = got_ref_open(&ref, repo, remote_refname, 1);
2701 if (error) {
2702 if (error->code != GOT_ERR_NOT_REF)
2703 goto done;
2704 error = create_ref(remote_refname, id,
2705 verbosity, repo);
2706 if (error)
2707 goto done;
2708 } else {
2709 error = update_ref(ref, id, replace_tags,
2710 verbosity, repo);
2711 unlock_err = got_ref_unlock(ref);
2712 if (unlock_err && error == NULL)
2713 error = unlock_err;
2714 got_ref_close(ref);
2715 if (error)
2716 goto done;
2719 /* Also create a local branch if none exists yet. */
2720 error = got_ref_open(&ref, repo, refname, 1);
2721 if (error) {
2722 if (error->code != GOT_ERR_NOT_REF)
2723 goto done;
2724 error = create_ref(refname, id, verbosity,
2725 repo);
2726 if (error)
2727 goto done;
2728 } else {
2729 unlock_err = got_ref_unlock(ref);
2730 if (unlock_err && error == NULL)
2731 error = unlock_err;
2732 got_ref_close(ref);
2736 if (delete_refs) {
2737 error = delete_missing_refs(&refs, &symrefs, remote,
2738 verbosity, repo);
2739 if (error)
2740 goto done;
2743 if (!remote->mirror_references) {
2744 /* Update remote HEAD reference if the server provided one. */
2745 TAILQ_FOREACH(pe, &symrefs, entry) {
2746 struct got_reference *target_ref;
2747 const char *refname = pe->path;
2748 const char *target = pe->data;
2749 char *remote_refname = NULL, *remote_target = NULL;
2751 if (strcmp(refname, GOT_REF_HEAD) != 0)
2752 continue;
2754 if (strncmp("refs/heads/", target, 11) != 0)
2755 continue;
2757 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
2758 remote->name, refname) == -1) {
2759 error = got_error_from_errno("asprintf");
2760 goto done;
2762 if (asprintf(&remote_target, "refs/remotes/%s/%s",
2763 remote->name, target + 11) == -1) {
2764 error = got_error_from_errno("asprintf");
2765 free(remote_refname);
2766 goto done;
2769 error = got_ref_open(&target_ref, repo, remote_target,
2770 0);
2771 if (error) {
2772 free(remote_refname);
2773 free(remote_target);
2774 if (error->code == GOT_ERR_NOT_REF) {
2775 error = NULL;
2776 continue;
2778 goto done;
2780 error = update_symref(remote_refname, target_ref,
2781 verbosity, repo);
2782 free(remote_refname);
2783 free(remote_target);
2784 got_ref_close(target_ref);
2785 if (error)
2786 goto done;
2789 done:
2790 if (fetchpid > 0) {
2791 if (kill(fetchpid, SIGTERM) == -1)
2792 error = got_error_from_errno("kill");
2793 if (waitpid(fetchpid, &fetchstatus, 0) == -1 && error == NULL)
2794 error = got_error_from_errno("waitpid");
2796 if (fetchfd != -1 && close(fetchfd) == -1 && error == NULL)
2797 error = got_error_from_errno("close");
2798 if (repo) {
2799 const struct got_error *close_err = got_repo_close(repo);
2800 if (error == NULL)
2801 error = close_err;
2803 if (worktree)
2804 got_worktree_close(worktree);
2805 if (pack_fds) {
2806 const struct got_error *pack_err =
2807 got_repo_pack_fds_close(pack_fds);
2808 if (error == NULL)
2809 error = pack_err;
2811 got_pathlist_free(&refs, GOT_PATHLIST_FREE_ALL);
2812 got_pathlist_free(&symrefs, GOT_PATHLIST_FREE_ALL);
2813 got_pathlist_free(&wanted_branches, GOT_PATHLIST_FREE_NONE);
2814 got_pathlist_free(&wanted_refs, GOT_PATHLIST_FREE_NONE);
2815 got_ref_list_free(&remote_refs);
2816 got_repo_free_remote_repo_data(remote);
2817 free(remote);
2818 free(head_refname);
2819 free(id_str);
2820 free(cwd);
2821 free(repo_path);
2822 free(pack_hash);
2823 free(proto);
2824 free(host);
2825 free(port);
2826 free(server_path);
2827 free(repo_name);
2828 return error;
2832 __dead static void
2833 usage_checkout(void)
2835 fprintf(stderr, "usage: %s checkout [-Eq] [-b branch] [-c commit] "
2836 "[-p path-prefix] repository-path [work-tree-path]\n",
2837 getprogname());
2838 exit(1);
2841 static void
2842 show_worktree_base_ref_warning(void)
2844 fprintf(stderr, "%s: warning: could not create a reference "
2845 "to the work tree's base commit; the commit could be "
2846 "garbage-collected by Git or 'gotadmin cleanup'; making the "
2847 "repository writable and running 'got update' will prevent this\n",
2848 getprogname());
2851 struct got_checkout_progress_arg {
2852 const char *worktree_path;
2853 int had_base_commit_ref_error;
2854 int verbosity;
2857 static const struct got_error *
2858 checkout_progress(void *arg, unsigned char status, const char *path)
2860 struct got_checkout_progress_arg *a = arg;
2862 /* Base commit bump happens silently. */
2863 if (status == GOT_STATUS_BUMP_BASE)
2864 return NULL;
2866 if (status == GOT_STATUS_BASE_REF_ERR) {
2867 a->had_base_commit_ref_error = 1;
2868 return NULL;
2871 while (path[0] == '/')
2872 path++;
2874 if (a->verbosity >= 0)
2875 printf("%c %s/%s\n", status, a->worktree_path, path);
2877 return NULL;
2880 static const struct got_error *
2881 check_cancelled(void *arg)
2883 if (sigint_received || sigpipe_received)
2884 return got_error(GOT_ERR_CANCELLED);
2885 return NULL;
2888 static const struct got_error *
2889 check_linear_ancestry(struct got_object_id *commit_id,
2890 struct got_object_id *base_commit_id, int allow_forwards_in_time_only,
2891 struct got_repository *repo)
2893 const struct got_error *err = NULL;
2894 struct got_object_id *yca_id;
2896 err = got_commit_graph_find_youngest_common_ancestor(&yca_id,
2897 commit_id, base_commit_id, 1, 0, repo, check_cancelled, NULL);
2898 if (err)
2899 return err;
2901 if (yca_id == NULL)
2902 return got_error(GOT_ERR_ANCESTRY);
2905 * Require a straight line of history between the target commit
2906 * and the work tree's base commit.
2908 * Non-linear situations such as this require a rebase:
2910 * (commit) D F (base_commit)
2911 * \ /
2912 * C E
2913 * \ /
2914 * B (yca)
2915 * |
2916 * A
2918 * 'got update' only handles linear cases:
2919 * Update forwards in time: A (base/yca) - B - C - D (commit)
2920 * Update backwards in time: D (base) - C - B - A (commit/yca)
2922 if (allow_forwards_in_time_only) {
2923 if (got_object_id_cmp(base_commit_id, yca_id) != 0)
2924 return got_error(GOT_ERR_ANCESTRY);
2925 } else if (got_object_id_cmp(commit_id, yca_id) != 0 &&
2926 got_object_id_cmp(base_commit_id, yca_id) != 0)
2927 return got_error(GOT_ERR_ANCESTRY);
2929 free(yca_id);
2930 return NULL;
2933 static const struct got_error *
2934 check_same_branch(struct got_object_id *commit_id,
2935 struct got_reference *head_ref, struct got_repository *repo)
2937 const struct got_error *err = NULL;
2938 struct got_commit_graph *graph = NULL;
2939 struct got_object_id *head_commit_id = NULL;
2941 err = got_ref_resolve(&head_commit_id, repo, head_ref);
2942 if (err)
2943 goto done;
2945 if (got_object_id_cmp(head_commit_id, commit_id) == 0)
2946 goto done;
2948 err = got_commit_graph_open(&graph, "/", 1);
2949 if (err)
2950 goto done;
2952 err = got_commit_graph_bfsort(graph, head_commit_id, repo,
2953 check_cancelled, NULL);
2954 if (err)
2955 goto done;
2957 for (;;) {
2958 struct got_object_id id;
2960 err = got_commit_graph_iter_next(&id, graph, repo,
2961 check_cancelled, NULL);
2962 if (err) {
2963 if (err->code == GOT_ERR_ITER_COMPLETED)
2964 err = got_error(GOT_ERR_ANCESTRY);
2965 break;
2968 if (got_object_id_cmp(&id, commit_id) == 0)
2969 break;
2971 done:
2972 if (graph)
2973 got_commit_graph_close(graph);
2974 free(head_commit_id);
2975 return err;
2978 static const struct got_error *
2979 checkout_ancestry_error(struct got_reference *ref, const char *commit_id_str)
2981 static char msg[512];
2982 const char *branch_name;
2984 if (got_ref_is_symbolic(ref))
2985 branch_name = got_ref_get_symref_target(ref);
2986 else
2987 branch_name = got_ref_get_name(ref);
2989 if (strncmp("refs/heads/", branch_name, 11) == 0)
2990 branch_name += 11;
2992 snprintf(msg, sizeof(msg),
2993 "target commit is not contained in branch '%s'; "
2994 "the branch to use must be specified with -b; "
2995 "if necessary a new branch can be created for "
2996 "this commit with 'got branch -c %s BRANCH_NAME'",
2997 branch_name, commit_id_str);
2999 return got_error_msg(GOT_ERR_ANCESTRY, msg);
3002 static const struct got_error *
3003 cmd_checkout(int argc, char *argv[])
3005 const struct got_error *close_err, *error = NULL;
3006 struct got_repository *repo = NULL;
3007 struct got_reference *head_ref = NULL, *ref = NULL;
3008 struct got_worktree *worktree = NULL;
3009 char *repo_path = NULL;
3010 char *worktree_path = NULL;
3011 const char *path_prefix = "";
3012 const char *branch_name = GOT_REF_HEAD, *refname = NULL;
3013 char *commit_id_str = NULL, *keyword_idstr = NULL;
3014 struct got_object_id *commit_id = NULL;
3015 char *cwd = NULL;
3016 int ch, same_path_prefix, allow_nonempty = 0, verbosity = 0;
3017 struct got_pathlist_head paths;
3018 struct got_checkout_progress_arg cpa;
3019 int *pack_fds = NULL;
3021 TAILQ_INIT(&paths);
3023 #ifndef PROFILE
3024 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
3025 "unveil", NULL) == -1)
3026 err(1, "pledge");
3027 #endif
3029 while ((ch = getopt(argc, argv, "b:c:Ep:q")) != -1) {
3030 switch (ch) {
3031 case 'b':
3032 branch_name = optarg;
3033 break;
3034 case 'c':
3035 commit_id_str = strdup(optarg);
3036 if (commit_id_str == NULL)
3037 return got_error_from_errno("strdup");
3038 break;
3039 case 'E':
3040 allow_nonempty = 1;
3041 break;
3042 case 'p':
3043 path_prefix = optarg;
3044 break;
3045 case 'q':
3046 verbosity = -1;
3047 break;
3048 default:
3049 usage_checkout();
3050 /* NOTREACHED */
3054 argc -= optind;
3055 argv += optind;
3057 if (argc == 1) {
3058 char *base, *dotgit;
3059 const char *path;
3060 repo_path = realpath(argv[0], NULL);
3061 if (repo_path == NULL)
3062 return got_error_from_errno2("realpath", argv[0]);
3063 cwd = getcwd(NULL, 0);
3064 if (cwd == NULL) {
3065 error = got_error_from_errno("getcwd");
3066 goto done;
3068 if (path_prefix[0])
3069 path = path_prefix;
3070 else
3071 path = repo_path;
3072 error = got_path_basename(&base, path);
3073 if (error)
3074 goto done;
3075 dotgit = strstr(base, ".git");
3076 if (dotgit)
3077 *dotgit = '\0';
3078 if (asprintf(&worktree_path, "%s/%s", cwd, base) == -1) {
3079 error = got_error_from_errno("asprintf");
3080 free(base);
3081 goto done;
3083 free(base);
3084 } else if (argc == 2) {
3085 repo_path = realpath(argv[0], NULL);
3086 if (repo_path == NULL) {
3087 error = got_error_from_errno2("realpath", argv[0]);
3088 goto done;
3090 worktree_path = realpath(argv[1], NULL);
3091 if (worktree_path == NULL) {
3092 if (errno != ENOENT) {
3093 error = got_error_from_errno2("realpath",
3094 argv[1]);
3095 goto done;
3097 worktree_path = strdup(argv[1]);
3098 if (worktree_path == NULL) {
3099 error = got_error_from_errno("strdup");
3100 goto done;
3103 } else
3104 usage_checkout();
3106 got_path_strip_trailing_slashes(repo_path);
3107 got_path_strip_trailing_slashes(worktree_path);
3109 if (got_path_is_child(worktree_path, repo_path, strlen(repo_path)) ||
3110 got_path_is_child(repo_path, worktree_path,
3111 strlen(worktree_path))) {
3112 error = got_error_fmt(GOT_ERR_BAD_PATH,
3113 "work tree and repository paths may not overlap: %s",
3114 worktree_path);
3115 goto done;
3118 error = got_repo_pack_fds_open(&pack_fds);
3119 if (error != NULL)
3120 goto done;
3122 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
3123 if (error != NULL)
3124 goto done;
3126 /* Pre-create work tree path for unveil(2) */
3127 error = got_path_mkdir(worktree_path);
3128 if (error) {
3129 if (!(error->code == GOT_ERR_ERRNO && errno == EISDIR) &&
3130 !(error->code == GOT_ERR_ERRNO && errno == EEXIST))
3131 goto done;
3132 if (!allow_nonempty &&
3133 !got_path_dir_is_empty(worktree_path)) {
3134 error = got_error_path(worktree_path,
3135 GOT_ERR_DIR_NOT_EMPTY);
3136 goto done;
3140 error = apply_unveil(got_repo_get_path(repo), 0, worktree_path);
3141 if (error)
3142 goto done;
3144 error = got_ref_open(&head_ref, repo, branch_name, 0);
3145 if (error != NULL)
3146 goto done;
3148 error = got_worktree_init(worktree_path, head_ref, path_prefix,
3149 GOT_WORKTREE_GOT_DIR, repo);
3150 if (error != NULL && !(error->code == GOT_ERR_ERRNO && errno == EEXIST))
3151 goto done;
3153 error = got_worktree_open(&worktree, worktree_path,
3154 GOT_WORKTREE_GOT_DIR);
3155 if (error != NULL)
3156 goto done;
3158 error = got_worktree_match_path_prefix(&same_path_prefix, worktree,
3159 path_prefix);
3160 if (error != NULL)
3161 goto done;
3162 if (!same_path_prefix) {
3163 error = got_error(GOT_ERR_PATH_PREFIX);
3164 goto done;
3167 if (commit_id_str) {
3168 struct got_reflist_head refs;
3169 TAILQ_INIT(&refs);
3170 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
3171 NULL);
3172 if (error)
3173 goto done;
3175 error = got_keyword_to_idstr(&keyword_idstr, commit_id_str,
3176 repo, worktree);
3177 if (error != NULL)
3178 goto done;
3179 if (keyword_idstr != NULL) {
3180 free(commit_id_str);
3181 commit_id_str = keyword_idstr;
3184 error = got_repo_match_object_id(&commit_id, NULL,
3185 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
3186 got_ref_list_free(&refs);
3187 if (error)
3188 goto done;
3189 error = check_linear_ancestry(commit_id,
3190 got_worktree_get_base_commit_id(worktree), 0, repo);
3191 if (error != NULL) {
3192 if (error->code == GOT_ERR_ANCESTRY) {
3193 error = checkout_ancestry_error(
3194 head_ref, commit_id_str);
3196 goto done;
3198 error = check_same_branch(commit_id, head_ref, repo);
3199 if (error) {
3200 if (error->code == GOT_ERR_ANCESTRY) {
3201 error = checkout_ancestry_error(
3202 head_ref, commit_id_str);
3204 goto done;
3206 error = got_worktree_set_base_commit_id(worktree, repo,
3207 commit_id);
3208 if (error)
3209 goto done;
3210 /* Expand potentially abbreviated commit ID string. */
3211 free(commit_id_str);
3212 error = got_object_id_str(&commit_id_str, commit_id);
3213 if (error)
3214 goto done;
3215 } else {
3216 commit_id = got_object_id_dup(
3217 got_worktree_get_base_commit_id(worktree));
3218 if (commit_id == NULL) {
3219 error = got_error_from_errno("got_object_id_dup");
3220 goto done;
3222 error = got_object_id_str(&commit_id_str, commit_id);
3223 if (error)
3224 goto done;
3227 error = got_pathlist_append(&paths, "", NULL);
3228 if (error)
3229 goto done;
3230 cpa.worktree_path = worktree_path;
3231 cpa.had_base_commit_ref_error = 0;
3232 cpa.verbosity = verbosity;
3233 error = got_worktree_checkout_files(worktree, &paths, repo,
3234 checkout_progress, &cpa, check_cancelled, NULL);
3235 if (error != NULL)
3236 goto done;
3238 if (got_ref_is_symbolic(head_ref)) {
3239 error = got_ref_resolve_symbolic(&ref, repo, head_ref);
3240 if (error)
3241 goto done;
3242 refname = got_ref_get_name(ref);
3243 } else
3244 refname = got_ref_get_name(head_ref);
3245 printf("Checked out %s: %s\n", refname, commit_id_str);
3246 printf("Now shut up and hack\n");
3247 if (cpa.had_base_commit_ref_error)
3248 show_worktree_base_ref_warning();
3249 done:
3250 if (pack_fds) {
3251 const struct got_error *pack_err =
3252 got_repo_pack_fds_close(pack_fds);
3253 if (error == NULL)
3254 error = pack_err;
3256 if (head_ref)
3257 got_ref_close(head_ref);
3258 if (ref)
3259 got_ref_close(ref);
3260 if (repo) {
3261 close_err = got_repo_close(repo);
3262 if (error == NULL)
3263 error = close_err;
3265 if (worktree != NULL) {
3266 close_err = got_worktree_close(worktree);
3267 if (error == NULL)
3268 error = close_err;
3270 got_pathlist_free(&paths, GOT_PATHLIST_FREE_NONE);
3271 free(commit_id_str);
3272 free(commit_id);
3273 free(repo_path);
3274 free(worktree_path);
3275 free(cwd);
3276 return error;
3279 struct got_update_progress_arg {
3280 int did_something;
3281 int conflicts;
3282 int obstructed;
3283 int not_updated;
3284 int missing;
3285 int not_deleted;
3286 int unversioned;
3287 int verbosity;
3290 static void
3291 print_update_progress_stats(struct got_update_progress_arg *upa)
3293 if (!upa->did_something)
3294 return;
3296 if (upa->conflicts > 0)
3297 printf("Files with new merge conflicts: %d\n", upa->conflicts);
3298 if (upa->obstructed > 0)
3299 printf("File paths obstructed by a non-regular file: %d\n",
3300 upa->obstructed);
3301 if (upa->not_updated > 0)
3302 printf("Files not updated because of existing merge "
3303 "conflicts: %d\n", upa->not_updated);
3307 * The meaning of some status codes differs between merge-style operations and
3308 * update operations. For example, the ! status code means "file was missing"
3309 * if changes were merged into the work tree, and "missing file was restored"
3310 * if the work tree was updated. This function should be used by any operation
3311 * which merges changes into the work tree without updating the work tree.
3313 static void
3314 print_merge_progress_stats(struct got_update_progress_arg *upa)
3316 if (!upa->did_something)
3317 return;
3319 if (upa->conflicts > 0)
3320 printf("Files with new merge conflicts: %d\n", upa->conflicts);
3321 if (upa->obstructed > 0)
3322 printf("File paths obstructed by a non-regular file: %d\n",
3323 upa->obstructed);
3324 if (upa->missing > 0)
3325 printf("Files which had incoming changes but could not be "
3326 "found in the work tree: %d\n", upa->missing);
3327 if (upa->not_deleted > 0)
3328 printf("Files not deleted due to differences in deleted "
3329 "content: %d\n", upa->not_deleted);
3330 if (upa->unversioned > 0)
3331 printf("Files not merged because an unversioned file was "
3332 "found in the work tree: %d\n", upa->unversioned);
3335 __dead static void
3336 usage_update(void)
3338 fprintf(stderr, "usage: %s update [-q] [-b branch] [-c commit] "
3339 "[path ...]\n", getprogname());
3340 exit(1);
3343 static const struct got_error *
3344 update_progress(void *arg, unsigned char status, const char *path)
3346 struct got_update_progress_arg *upa = arg;
3348 if (status == GOT_STATUS_EXISTS ||
3349 status == GOT_STATUS_BASE_REF_ERR)
3350 return NULL;
3352 upa->did_something = 1;
3354 /* Base commit bump happens silently. */
3355 if (status == GOT_STATUS_BUMP_BASE)
3356 return NULL;
3358 if (status == GOT_STATUS_CONFLICT)
3359 upa->conflicts++;
3360 if (status == GOT_STATUS_OBSTRUCTED)
3361 upa->obstructed++;
3362 if (status == GOT_STATUS_CANNOT_UPDATE)
3363 upa->not_updated++;
3364 if (status == GOT_STATUS_MISSING)
3365 upa->missing++;
3366 if (status == GOT_STATUS_CANNOT_DELETE)
3367 upa->not_deleted++;
3368 if (status == GOT_STATUS_UNVERSIONED)
3369 upa->unversioned++;
3371 while (path[0] == '/')
3372 path++;
3373 if (upa->verbosity >= 0)
3374 printf("%c %s\n", status, path);
3376 return NULL;
3379 static const struct got_error *
3380 switch_head_ref(struct got_reference *head_ref,
3381 struct got_object_id *commit_id, struct got_worktree *worktree,
3382 struct got_repository *repo)
3384 const struct got_error *err = NULL;
3385 char *base_id_str;
3386 int ref_has_moved = 0;
3388 /* Trivial case: switching between two different references. */
3389 if (strcmp(got_ref_get_name(head_ref),
3390 got_worktree_get_head_ref_name(worktree)) != 0) {
3391 printf("Switching work tree from %s to %s\n",
3392 got_worktree_get_head_ref_name(worktree),
3393 got_ref_get_name(head_ref));
3394 return got_worktree_set_head_ref(worktree, head_ref);
3397 err = check_linear_ancestry(commit_id,
3398 got_worktree_get_base_commit_id(worktree), 0, repo);
3399 if (err) {
3400 if (err->code != GOT_ERR_ANCESTRY)
3401 return err;
3402 ref_has_moved = 1;
3404 if (!ref_has_moved)
3405 return NULL;
3407 /* Switching to a rebased branch with the same reference name. */
3408 err = got_object_id_str(&base_id_str,
3409 got_worktree_get_base_commit_id(worktree));
3410 if (err)
3411 return err;
3412 printf("Reference %s now points at a different branch\n",
3413 got_worktree_get_head_ref_name(worktree));
3414 printf("Switching work tree from %s to %s\n", base_id_str,
3415 got_worktree_get_head_ref_name(worktree));
3416 return NULL;
3419 static const struct got_error *
3420 check_rebase_or_histedit_in_progress(struct got_worktree *worktree)
3422 const struct got_error *err;
3423 int in_progress;
3425 err = got_worktree_rebase_in_progress(&in_progress, worktree);
3426 if (err)
3427 return err;
3428 if (in_progress)
3429 return got_error(GOT_ERR_REBASING);
3431 err = got_worktree_histedit_in_progress(&in_progress, worktree);
3432 if (err)
3433 return err;
3434 if (in_progress)
3435 return got_error(GOT_ERR_HISTEDIT_BUSY);
3437 return NULL;
3440 static const struct got_error *
3441 check_merge_in_progress(struct got_worktree *worktree,
3442 struct got_repository *repo)
3444 const struct got_error *err;
3445 int in_progress;
3447 err = got_worktree_merge_in_progress(&in_progress, worktree, repo);
3448 if (err)
3449 return err;
3450 if (in_progress)
3451 return got_error(GOT_ERR_MERGE_BUSY);
3453 return NULL;
3456 static const struct got_error *
3457 get_worktree_paths_from_argv(struct got_pathlist_head *paths, int argc,
3458 char *argv[], struct got_worktree *worktree)
3460 const struct got_error *err = NULL;
3461 char *path;
3462 struct got_pathlist_entry *new;
3463 int i;
3465 if (argc == 0) {
3466 path = strdup("");
3467 if (path == NULL)
3468 return got_error_from_errno("strdup");
3469 return got_pathlist_append(paths, path, NULL);
3472 for (i = 0; i < argc; i++) {
3473 err = got_worktree_resolve_path(&path, worktree, argv[i]);
3474 if (err)
3475 break;
3476 err = got_pathlist_insert(&new, paths, path, NULL);
3477 if (err || new == NULL /* duplicate */) {
3478 free(path);
3479 if (err)
3480 break;
3484 return err;
3487 static const struct got_error *
3488 wrap_not_worktree_error(const struct got_error *orig_err,
3489 const char *cmdname, const char *path)
3491 const struct got_error *err;
3492 struct got_repository *repo;
3493 static char msg[512];
3494 int *pack_fds = NULL;
3496 err = got_repo_pack_fds_open(&pack_fds);
3497 if (err)
3498 return err;
3500 err = got_repo_open(&repo, path, NULL, pack_fds);
3501 if (err)
3502 return orig_err;
3504 snprintf(msg, sizeof(msg),
3505 "'got %s' needs a work tree in addition to a git repository\n"
3506 "Work trees can be checked out from this Git repository with "
3507 "'got checkout'.\n"
3508 "The got(1) manual page contains more information.", cmdname);
3509 err = got_error_msg(GOT_ERR_NOT_WORKTREE, msg);
3510 if (repo) {
3511 const struct got_error *close_err = got_repo_close(repo);
3512 if (err == NULL)
3513 err = close_err;
3515 if (pack_fds) {
3516 const struct got_error *pack_err =
3517 got_repo_pack_fds_close(pack_fds);
3518 if (err == NULL)
3519 err = pack_err;
3521 return err;
3524 static const struct got_error *
3525 cmd_update(int argc, char *argv[])
3527 const struct got_error *close_err, *error = NULL;
3528 struct got_repository *repo = NULL;
3529 struct got_worktree *worktree = NULL;
3530 char *worktree_path = NULL;
3531 struct got_object_id *commit_id = NULL;
3532 char *commit_id_str = NULL;
3533 const char *branch_name = NULL;
3534 struct got_reference *head_ref = NULL;
3535 struct got_pathlist_head paths;
3536 struct got_pathlist_entry *pe;
3537 int ch, verbosity = 0;
3538 struct got_update_progress_arg upa;
3539 int *pack_fds = NULL;
3541 TAILQ_INIT(&paths);
3543 #ifndef PROFILE
3544 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
3545 "unveil", NULL) == -1)
3546 err(1, "pledge");
3547 #endif
3549 while ((ch = getopt(argc, argv, "b:c:q")) != -1) {
3550 switch (ch) {
3551 case 'b':
3552 branch_name = optarg;
3553 break;
3554 case 'c':
3555 commit_id_str = strdup(optarg);
3556 if (commit_id_str == NULL)
3557 return got_error_from_errno("strdup");
3558 break;
3559 case 'q':
3560 verbosity = -1;
3561 break;
3562 default:
3563 usage_update();
3564 /* NOTREACHED */
3568 argc -= optind;
3569 argv += optind;
3571 worktree_path = getcwd(NULL, 0);
3572 if (worktree_path == NULL) {
3573 error = got_error_from_errno("getcwd");
3574 goto done;
3577 error = got_repo_pack_fds_open(&pack_fds);
3578 if (error != NULL)
3579 goto done;
3581 error = got_worktree_open(&worktree, worktree_path,
3582 GOT_WORKTREE_GOT_DIR);
3583 if (error) {
3584 if (error->code == GOT_ERR_NOT_WORKTREE)
3585 error = wrap_not_worktree_error(error, "update",
3586 worktree_path);
3587 goto done;
3590 error = check_rebase_or_histedit_in_progress(worktree);
3591 if (error)
3592 goto done;
3594 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
3595 NULL, pack_fds);
3596 if (error != NULL)
3597 goto done;
3599 error = apply_unveil(got_repo_get_path(repo), 0,
3600 got_worktree_get_root_path(worktree));
3601 if (error)
3602 goto done;
3604 error = check_merge_in_progress(worktree, repo);
3605 if (error)
3606 goto done;
3608 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
3609 if (error)
3610 goto done;
3612 error = got_ref_open(&head_ref, repo, branch_name ? branch_name :
3613 got_worktree_get_head_ref_name(worktree), 0);
3614 if (error != NULL)
3615 goto done;
3616 if (commit_id_str == NULL) {
3617 error = got_ref_resolve(&commit_id, repo, head_ref);
3618 if (error != NULL)
3619 goto done;
3620 error = got_object_id_str(&commit_id_str, commit_id);
3621 if (error != NULL)
3622 goto done;
3623 } else {
3624 struct got_reflist_head refs;
3625 char *keyword_idstr = NULL;
3627 TAILQ_INIT(&refs);
3629 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
3630 NULL);
3631 if (error)
3632 goto done;
3634 error = got_keyword_to_idstr(&keyword_idstr, commit_id_str,
3635 repo, worktree);
3636 if (error != NULL)
3637 goto done;
3638 if (keyword_idstr != NULL) {
3639 free(commit_id_str);
3640 commit_id_str = keyword_idstr;
3643 error = got_repo_match_object_id(&commit_id, NULL,
3644 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
3645 got_ref_list_free(&refs);
3646 free(commit_id_str);
3647 commit_id_str = NULL;
3648 if (error)
3649 goto done;
3650 error = got_object_id_str(&commit_id_str, commit_id);
3651 if (error)
3652 goto done;
3655 if (branch_name) {
3656 struct got_object_id *head_commit_id;
3657 TAILQ_FOREACH(pe, &paths, entry) {
3658 if (pe->path_len == 0)
3659 continue;
3660 error = got_error_msg(GOT_ERR_BAD_PATH,
3661 "switching between branches requires that "
3662 "the entire work tree gets updated");
3663 goto done;
3665 error = got_ref_resolve(&head_commit_id, repo, head_ref);
3666 if (error)
3667 goto done;
3668 error = check_linear_ancestry(commit_id, head_commit_id, 0,
3669 repo);
3670 free(head_commit_id);
3671 if (error != NULL)
3672 goto done;
3673 error = check_same_branch(commit_id, head_ref, repo);
3674 if (error)
3675 goto done;
3676 error = switch_head_ref(head_ref, commit_id, worktree, repo);
3677 if (error)
3678 goto done;
3679 } else {
3680 error = check_linear_ancestry(commit_id,
3681 got_worktree_get_base_commit_id(worktree), 0, repo);
3682 if (error != NULL) {
3683 if (error->code == GOT_ERR_ANCESTRY)
3684 error = got_error(GOT_ERR_BRANCH_MOVED);
3685 goto done;
3687 error = check_same_branch(commit_id, head_ref, repo);
3688 if (error)
3689 goto done;
3692 if (got_object_id_cmp(got_worktree_get_base_commit_id(worktree),
3693 commit_id) != 0) {
3694 error = got_worktree_set_base_commit_id(worktree, repo,
3695 commit_id);
3696 if (error)
3697 goto done;
3700 memset(&upa, 0, sizeof(upa));
3701 upa.verbosity = verbosity;
3702 error = got_worktree_checkout_files(worktree, &paths, repo,
3703 update_progress, &upa, check_cancelled, NULL);
3704 if (error != NULL)
3705 goto done;
3707 if (upa.did_something) {
3708 printf("Updated to %s: %s\n",
3709 got_worktree_get_head_ref_name(worktree), commit_id_str);
3710 } else
3711 printf("Already up-to-date\n");
3713 print_update_progress_stats(&upa);
3714 done:
3715 if (pack_fds) {
3716 const struct got_error *pack_err =
3717 got_repo_pack_fds_close(pack_fds);
3718 if (error == NULL)
3719 error = pack_err;
3721 if (repo) {
3722 close_err = got_repo_close(repo);
3723 if (error == NULL)
3724 error = close_err;
3726 if (worktree != NULL) {
3727 close_err = got_worktree_close(worktree);
3728 if (error == NULL)
3729 error = close_err;
3731 if (head_ref != NULL)
3732 got_ref_close(head_ref);
3733 free(worktree_path);
3734 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
3735 free(commit_id);
3736 free(commit_id_str);
3737 return error;
3740 static const struct got_error *
3741 diff_blobs(struct got_object_id *blob_id1, struct got_object_id *blob_id2,
3742 const char *path, int diff_context, int ignore_whitespace,
3743 int force_text_diff, struct got_diffstat_cb_arg *dsa,
3744 struct got_repository *repo, FILE *outfile)
3746 const struct got_error *err = NULL;
3747 struct got_blob_object *blob1 = NULL, *blob2 = NULL;
3748 FILE *f1 = NULL, *f2 = NULL;
3749 int fd1 = -1, fd2 = -1;
3751 fd1 = got_opentempfd();
3752 if (fd1 == -1)
3753 return got_error_from_errno("got_opentempfd");
3754 fd2 = got_opentempfd();
3755 if (fd2 == -1) {
3756 err = got_error_from_errno("got_opentempfd");
3757 goto done;
3760 if (blob_id1) {
3761 err = got_object_open_as_blob(&blob1, repo, blob_id1, 8192,
3762 fd1);
3763 if (err)
3764 goto done;
3767 err = got_object_open_as_blob(&blob2, repo, blob_id2, 8192, fd2);
3768 if (err)
3769 goto done;
3771 f1 = got_opentemp();
3772 if (f1 == NULL) {
3773 err = got_error_from_errno("got_opentemp");
3774 goto done;
3776 f2 = got_opentemp();
3777 if (f2 == NULL) {
3778 err = got_error_from_errno("got_opentemp");
3779 goto done;
3782 while (path[0] == '/')
3783 path++;
3784 err = got_diff_blob(NULL, NULL, blob1, blob2, f1, f2, path, path,
3785 GOT_DIFF_ALGORITHM_PATIENCE, diff_context, ignore_whitespace,
3786 force_text_diff, dsa, outfile);
3787 done:
3788 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
3789 err = got_error_from_errno("close");
3790 if (blob1)
3791 got_object_blob_close(blob1);
3792 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
3793 err = got_error_from_errno("close");
3794 if (blob2)
3795 got_object_blob_close(blob2);
3796 if (f1 && fclose(f1) == EOF && err == NULL)
3797 err = got_error_from_errno("fclose");
3798 if (f2 && fclose(f2) == EOF && err == NULL)
3799 err = got_error_from_errno("fclose");
3800 return err;
3803 static const struct got_error *
3804 diff_trees(struct got_object_id *tree_id1, struct got_object_id *tree_id2,
3805 const char *path, int diff_context, int ignore_whitespace,
3806 int force_text_diff, struct got_diffstat_cb_arg *dsa,
3807 struct got_repository *repo, FILE *outfile)
3809 const struct got_error *err = NULL;
3810 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
3811 struct got_diff_blob_output_unidiff_arg arg;
3812 FILE *f1 = NULL, *f2 = NULL;
3813 int fd1 = -1, fd2 = -1;
3815 if (tree_id1) {
3816 err = got_object_open_as_tree(&tree1, repo, tree_id1);
3817 if (err)
3818 goto done;
3819 fd1 = got_opentempfd();
3820 if (fd1 == -1) {
3821 err = got_error_from_errno("got_opentempfd");
3822 goto done;
3826 err = got_object_open_as_tree(&tree2, repo, tree_id2);
3827 if (err)
3828 goto done;
3830 f1 = got_opentemp();
3831 if (f1 == NULL) {
3832 err = got_error_from_errno("got_opentemp");
3833 goto done;
3836 f2 = got_opentemp();
3837 if (f2 == NULL) {
3838 err = got_error_from_errno("got_opentemp");
3839 goto done;
3841 fd2 = got_opentempfd();
3842 if (fd2 == -1) {
3843 err = got_error_from_errno("got_opentempfd");
3844 goto done;
3846 arg.diff_context = diff_context;
3847 arg.ignore_whitespace = ignore_whitespace;
3848 arg.force_text_diff = force_text_diff;
3849 arg.diffstat = dsa;
3850 arg.diff_algo = GOT_DIFF_ALGORITHM_PATIENCE;
3851 arg.outfile = outfile;
3852 arg.lines = NULL;
3853 arg.nlines = 0;
3854 while (path[0] == '/')
3855 path++;
3856 err = got_diff_tree(tree1, tree2, f1, f2, fd1, fd2, path, path, repo,
3857 got_diff_blob_output_unidiff, &arg, 1);
3858 done:
3859 if (tree1)
3860 got_object_tree_close(tree1);
3861 if (tree2)
3862 got_object_tree_close(tree2);
3863 if (f1 && fclose(f1) == EOF && err == NULL)
3864 err = got_error_from_errno("fclose");
3865 if (f2 && fclose(f2) == EOF && err == NULL)
3866 err = got_error_from_errno("fclose");
3867 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
3868 err = got_error_from_errno("close");
3869 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
3870 err = got_error_from_errno("close");
3871 return err;
3874 static const struct got_error *
3875 get_changed_paths(struct got_pathlist_head *paths,
3876 struct got_commit_object *commit, struct got_repository *repo,
3877 struct got_diffstat_cb_arg *dsa)
3879 const struct got_error *err = NULL;
3880 struct got_object_id *tree_id1 = NULL, *tree_id2 = NULL;
3881 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
3882 struct got_object_qid *qid;
3883 got_diff_blob_cb cb = got_diff_tree_collect_changed_paths;
3884 FILE *f1 = NULL, *f2 = NULL;
3885 int fd1 = -1, fd2 = -1;
3887 if (dsa) {
3888 cb = got_diff_tree_compute_diffstat;
3890 f1 = got_opentemp();
3891 if (f1 == NULL) {
3892 err = got_error_from_errno("got_opentemp");
3893 goto done;
3895 f2 = got_opentemp();
3896 if (f2 == NULL) {
3897 err = got_error_from_errno("got_opentemp");
3898 goto done;
3900 fd1 = got_opentempfd();
3901 if (fd1 == -1) {
3902 err = got_error_from_errno("got_opentempfd");
3903 goto done;
3905 fd2 = got_opentempfd();
3906 if (fd2 == -1) {
3907 err = got_error_from_errno("got_opentempfd");
3908 goto done;
3912 qid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
3913 if (qid != NULL) {
3914 struct got_commit_object *pcommit;
3915 err = got_object_open_as_commit(&pcommit, repo,
3916 &qid->id);
3917 if (err)
3918 return err;
3920 tree_id1 = got_object_id_dup(
3921 got_object_commit_get_tree_id(pcommit));
3922 if (tree_id1 == NULL) {
3923 got_object_commit_close(pcommit);
3924 return got_error_from_errno("got_object_id_dup");
3926 got_object_commit_close(pcommit);
3930 if (tree_id1) {
3931 err = got_object_open_as_tree(&tree1, repo, tree_id1);
3932 if (err)
3933 goto done;
3936 tree_id2 = got_object_commit_get_tree_id(commit);
3937 err = got_object_open_as_tree(&tree2, repo, tree_id2);
3938 if (err)
3939 goto done;
3941 err = got_diff_tree(tree1, tree2, f1, f2, fd1, fd2, "", "", repo,
3942 cb, dsa ? (void *)dsa : paths, dsa ? 1 : 0);
3943 done:
3944 if (tree1)
3945 got_object_tree_close(tree1);
3946 if (tree2)
3947 got_object_tree_close(tree2);
3948 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
3949 err = got_error_from_errno("close");
3950 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
3951 err = got_error_from_errno("close");
3952 if (f1 && fclose(f1) == EOF && err == NULL)
3953 err = got_error_from_errno("fclose");
3954 if (f2 && fclose(f2) == EOF && err == NULL)
3955 err = got_error_from_errno("fclose");
3956 free(tree_id1);
3957 return err;
3960 static const struct got_error *
3961 print_patch(struct got_commit_object *commit, struct got_object_id *id,
3962 const char *path, int diff_context, struct got_diffstat_cb_arg *dsa,
3963 struct got_repository *repo, FILE *outfile)
3965 const struct got_error *err = NULL;
3966 struct got_commit_object *pcommit = NULL;
3967 char *id_str1 = NULL, *id_str2 = NULL;
3968 struct got_object_id *obj_id1 = NULL, *obj_id2 = NULL;
3969 struct got_object_qid *qid;
3971 qid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
3972 if (qid != NULL) {
3973 err = got_object_open_as_commit(&pcommit, repo,
3974 &qid->id);
3975 if (err)
3976 return err;
3977 err = got_object_id_str(&id_str1, &qid->id);
3978 if (err)
3979 goto done;
3982 err = got_object_id_str(&id_str2, id);
3983 if (err)
3984 goto done;
3986 if (path && path[0] != '\0') {
3987 int obj_type;
3988 err = got_object_id_by_path(&obj_id2, repo, commit, path);
3989 if (err)
3990 goto done;
3991 if (pcommit) {
3992 err = got_object_id_by_path(&obj_id1, repo,
3993 pcommit, path);
3994 if (err) {
3995 if (err->code != GOT_ERR_NO_TREE_ENTRY) {
3996 free(obj_id2);
3997 goto done;
4001 err = got_object_get_type(&obj_type, repo, obj_id2);
4002 if (err) {
4003 free(obj_id2);
4004 goto done;
4006 fprintf(outfile,
4007 "diff %s %s\n", id_str1 ? id_str1 : "/dev/null", id_str2);
4008 fprintf(outfile, "commit - %s\n",
4009 id_str1 ? id_str1 : "/dev/null");
4010 fprintf(outfile, "commit + %s\n", id_str2);
4011 switch (obj_type) {
4012 case GOT_OBJ_TYPE_BLOB:
4013 err = diff_blobs(obj_id1, obj_id2, path, diff_context,
4014 0, 0, dsa, repo, outfile);
4015 break;
4016 case GOT_OBJ_TYPE_TREE:
4017 err = diff_trees(obj_id1, obj_id2, path, diff_context,
4018 0, 0, dsa, repo, outfile);
4019 break;
4020 default:
4021 err = got_error(GOT_ERR_OBJ_TYPE);
4022 break;
4024 free(obj_id1);
4025 free(obj_id2);
4026 } else {
4027 obj_id2 = got_object_commit_get_tree_id(commit);
4028 if (pcommit)
4029 obj_id1 = got_object_commit_get_tree_id(pcommit);
4030 fprintf(outfile,
4031 "diff %s %s\n", id_str1 ? id_str1 : "/dev/null", id_str2);
4032 fprintf(outfile, "commit - %s\n",
4033 id_str1 ? id_str1 : "/dev/null");
4034 fprintf(outfile, "commit + %s\n", id_str2);
4035 err = diff_trees(obj_id1, obj_id2, "", diff_context, 0, 0,
4036 dsa, repo, outfile);
4038 done:
4039 free(id_str1);
4040 free(id_str2);
4041 if (pcommit)
4042 got_object_commit_close(pcommit);
4043 return err;
4046 static char *
4047 get_datestr(time_t *time, char *datebuf)
4049 struct tm mytm, *tm;
4050 char *p, *s;
4052 tm = gmtime_r(time, &mytm);
4053 if (tm == NULL)
4054 return NULL;
4055 s = asctime_r(tm, datebuf);
4056 if (s == NULL)
4057 return NULL;
4058 p = strchr(s, '\n');
4059 if (p)
4060 *p = '\0';
4061 return s;
4064 static const struct got_error *
4065 match_commit(int *have_match, struct got_object_id *id,
4066 struct got_commit_object *commit, regex_t *regex)
4068 const struct got_error *err = NULL;
4069 regmatch_t regmatch;
4070 char *id_str = NULL, *logmsg = NULL;
4072 *have_match = 0;
4074 err = got_object_id_str(&id_str, id);
4075 if (err)
4076 return err;
4078 err = got_object_commit_get_logmsg(&logmsg, commit);
4079 if (err)
4080 goto done;
4082 if (regexec(regex, got_object_commit_get_author(commit), 1,
4083 &regmatch, 0) == 0 ||
4084 regexec(regex, got_object_commit_get_committer(commit), 1,
4085 &regmatch, 0) == 0 ||
4086 regexec(regex, id_str, 1, &regmatch, 0) == 0 ||
4087 regexec(regex, logmsg, 1, &regmatch, 0) == 0)
4088 *have_match = 1;
4089 done:
4090 free(id_str);
4091 free(logmsg);
4092 return err;
4095 static void
4096 match_changed_paths(int *have_match, struct got_pathlist_head *changed_paths,
4097 regex_t *regex)
4099 regmatch_t regmatch;
4100 struct got_pathlist_entry *pe;
4102 *have_match = 0;
4104 TAILQ_FOREACH(pe, changed_paths, entry) {
4105 if (regexec(regex, pe->path, 1, &regmatch, 0) == 0) {
4106 *have_match = 1;
4107 break;
4112 static const struct got_error *
4113 match_patch(int *have_match, struct got_commit_object *commit,
4114 struct got_object_id *id, const char *path, int diff_context,
4115 struct got_repository *repo, regex_t *regex, FILE *f)
4117 const struct got_error *err = NULL;
4118 char *line = NULL;
4119 size_t linesize = 0;
4120 regmatch_t regmatch;
4122 *have_match = 0;
4124 err = got_opentemp_truncate(f);
4125 if (err)
4126 return err;
4128 err = print_patch(commit, id, path, diff_context, NULL, repo, f);
4129 if (err)
4130 goto done;
4132 if (fseeko(f, 0L, SEEK_SET) == -1) {
4133 err = got_error_from_errno("fseeko");
4134 goto done;
4137 while (getline(&line, &linesize, f) != -1) {
4138 if (regexec(regex, line, 1, &regmatch, 0) == 0) {
4139 *have_match = 1;
4140 break;
4143 done:
4144 free(line);
4145 return err;
4148 #define GOT_COMMIT_SEP_STR "-----------------------------------------------\n"
4150 static const struct got_error*
4151 build_refs_str(char **refs_str, struct got_reflist_head *refs,
4152 struct got_object_id *id, struct got_repository *repo,
4153 int local_only)
4155 static const struct got_error *err = NULL;
4156 struct got_reflist_entry *re;
4157 char *s;
4158 const char *name;
4160 *refs_str = NULL;
4162 TAILQ_FOREACH(re, refs, entry) {
4163 struct got_tag_object *tag = NULL;
4164 struct got_object_id *ref_id;
4165 int cmp;
4167 name = got_ref_get_name(re->ref);
4168 if (strcmp(name, GOT_REF_HEAD) == 0)
4169 continue;
4170 if (strncmp(name, "refs/", 5) == 0)
4171 name += 5;
4172 if (strncmp(name, "got/", 4) == 0)
4173 continue;
4174 if (strncmp(name, "heads/", 6) == 0)
4175 name += 6;
4176 if (strncmp(name, "remotes/", 8) == 0) {
4177 if (local_only)
4178 continue;
4179 name += 8;
4180 s = strstr(name, "/" GOT_REF_HEAD);
4181 if (s != NULL && strcmp(s, "/" GOT_REF_HEAD) == 0)
4182 continue;
4184 err = got_ref_resolve(&ref_id, repo, re->ref);
4185 if (err)
4186 break;
4187 if (strncmp(name, "tags/", 5) == 0) {
4188 err = got_object_open_as_tag(&tag, repo, ref_id);
4189 if (err) {
4190 if (err->code != GOT_ERR_OBJ_TYPE) {
4191 free(ref_id);
4192 break;
4194 /* Ref points at something other than a tag. */
4195 err = NULL;
4196 tag = NULL;
4199 cmp = got_object_id_cmp(tag ?
4200 got_object_tag_get_object_id(tag) : ref_id, id);
4201 free(ref_id);
4202 if (tag)
4203 got_object_tag_close(tag);
4204 if (cmp != 0)
4205 continue;
4206 s = *refs_str;
4207 if (asprintf(refs_str, "%s%s%s", s ? s : "",
4208 s ? ", " : "", name) == -1) {
4209 err = got_error_from_errno("asprintf");
4210 free(s);
4211 *refs_str = NULL;
4212 break;
4214 free(s);
4217 return err;
4220 static const struct got_error *
4221 print_commit_oneline(struct got_commit_object *commit, struct got_object_id *id,
4222 struct got_repository *repo, struct got_reflist_object_id_map *refs_idmap)
4224 const struct got_error *err = NULL;
4225 char *ref_str = NULL, *id_str = NULL, *logmsg0 = NULL;
4226 char *comma, *s, *nl;
4227 struct got_reflist_head *refs;
4228 char datebuf[12]; /* YYYY-MM-DD + SPACE + NUL */
4229 struct tm tm;
4230 time_t committer_time;
4232 refs = got_reflist_object_id_map_lookup(refs_idmap, id);
4233 if (refs) {
4234 err = build_refs_str(&ref_str, refs, id, repo, 1);
4235 if (err)
4236 return err;
4238 /* Display the first matching ref only. */
4239 if (ref_str && (comma = strchr(ref_str, ',')) != NULL)
4240 *comma = '\0';
4243 if (ref_str == NULL) {
4244 err = got_object_id_str(&id_str, id);
4245 if (err)
4246 return err;
4249 committer_time = got_object_commit_get_committer_time(commit);
4250 if (gmtime_r(&committer_time, &tm) == NULL) {
4251 err = got_error_from_errno("gmtime_r");
4252 goto done;
4254 if (strftime(datebuf, sizeof(datebuf), "%F ", &tm) == 0) {
4255 err = got_error(GOT_ERR_NO_SPACE);
4256 goto done;
4259 err = got_object_commit_get_logmsg(&logmsg0, commit);
4260 if (err)
4261 goto done;
4263 s = logmsg0;
4264 while (isspace((unsigned char)s[0]))
4265 s++;
4267 nl = strchr(s, '\n');
4268 if (nl) {
4269 *nl = '\0';
4272 if (ref_str)
4273 printf("%s%-7s %s\n", datebuf, ref_str, s);
4274 else
4275 printf("%s%.7s %s\n", datebuf, id_str, s);
4277 if (fflush(stdout) != 0 && err == NULL)
4278 err = got_error_from_errno("fflush");
4279 done:
4280 free(id_str);
4281 free(ref_str);
4282 free(logmsg0);
4283 return err;
4286 static const struct got_error *
4287 print_diffstat(struct got_diffstat_cb_arg *dsa, const char *header)
4289 struct got_pathlist_entry *pe;
4291 if (header != NULL)
4292 printf("%s\n", header);
4294 TAILQ_FOREACH(pe, dsa->paths, entry) {
4295 struct got_diff_changed_path *cp = pe->data;
4296 int pad = dsa->max_path_len - pe->path_len + 1;
4298 printf(" %c %s%*c | %*d+ %*d-\n", cp->status, pe->path, pad,
4299 ' ', dsa->add_cols + 1, cp->add, dsa->rm_cols + 1, cp->rm);
4301 printf("\n%d file%s changed, %d insertion%s(+), %d deletion%s(-)\n\n",
4302 dsa->nfiles, dsa->nfiles > 1 ? "s" : "", dsa->ins,
4303 dsa->ins != 1 ? "s" : "", dsa->del, dsa->del != 1 ? "s" : "");
4305 if (fflush(stdout) != 0)
4306 return got_error_from_errno("fflush");
4308 return NULL;
4311 static const struct got_error *
4312 printfile(FILE *f)
4314 char buf[8192];
4315 size_t r;
4317 if (fseeko(f, 0L, SEEK_SET) == -1)
4318 return got_error_from_errno("fseek");
4320 for (;;) {
4321 r = fread(buf, 1, sizeof(buf), f);
4322 if (r == 0) {
4323 if (ferror(f))
4324 return got_error_from_errno("fread");
4325 if (feof(f))
4326 break;
4328 if (fwrite(buf, 1, r, stdout) != r)
4329 return got_ferror(stdout, GOT_ERR_IO);
4332 return NULL;
4335 static const struct got_error *
4336 print_commit(struct got_commit_object *commit, struct got_object_id *id,
4337 struct got_repository *repo, const char *path,
4338 struct got_pathlist_head *changed_paths,
4339 struct got_diffstat_cb_arg *diffstat, int show_patch, int diff_context,
4340 struct got_reflist_object_id_map *refs_idmap, const char *custom_refs_str,
4341 const char *prefix)
4343 const struct got_error *err = NULL;
4344 FILE *f = NULL;
4345 char *id_str, *datestr, *logmsg0, *logmsg, *line;
4346 char datebuf[26];
4347 time_t committer_time;
4348 const char *author, *committer;
4349 char *refs_str = NULL;
4351 err = got_object_id_str(&id_str, id);
4352 if (err)
4353 return err;
4355 if (custom_refs_str == NULL) {
4356 struct got_reflist_head *refs;
4357 refs = got_reflist_object_id_map_lookup(refs_idmap, id);
4358 if (refs) {
4359 err = build_refs_str(&refs_str, refs, id, repo, 0);
4360 if (err)
4361 goto done;
4365 printf(GOT_COMMIT_SEP_STR);
4366 if (custom_refs_str)
4367 printf("%s %s (%s)\n", prefix ? prefix : "commit", id_str,
4368 custom_refs_str);
4369 else
4370 printf("%s %s%s%s%s\n", prefix ? prefix : "commit", id_str,
4371 refs_str ? " (" : "", refs_str ? refs_str : "",
4372 refs_str ? ")" : "");
4373 free(id_str);
4374 id_str = NULL;
4375 free(refs_str);
4376 refs_str = NULL;
4377 printf("from: %s\n", got_object_commit_get_author(commit));
4378 author = got_object_commit_get_author(commit);
4379 committer = got_object_commit_get_committer(commit);
4380 if (strcmp(author, committer) != 0)
4381 printf("via: %s\n", committer);
4382 committer_time = got_object_commit_get_committer_time(commit);
4383 datestr = get_datestr(&committer_time, datebuf);
4384 if (datestr)
4385 printf("date: %s UTC\n", datestr);
4386 if (got_object_commit_get_nparents(commit) > 1) {
4387 const struct got_object_id_queue *parent_ids;
4388 struct got_object_qid *qid;
4389 int n = 1;
4390 parent_ids = got_object_commit_get_parent_ids(commit);
4391 STAILQ_FOREACH(qid, parent_ids, entry) {
4392 err = got_object_id_str(&id_str, &qid->id);
4393 if (err)
4394 goto done;
4395 printf("parent %d: %s\n", n++, id_str);
4396 free(id_str);
4397 id_str = NULL;
4401 err = got_object_commit_get_logmsg(&logmsg0, commit);
4402 if (err)
4403 goto done;
4405 logmsg = logmsg0;
4406 do {
4407 line = strsep(&logmsg, "\n");
4408 if (line)
4409 printf(" %s\n", line);
4410 } while (line);
4411 free(logmsg0);
4413 if (changed_paths && diffstat == NULL) {
4414 struct got_pathlist_entry *pe;
4416 TAILQ_FOREACH(pe, changed_paths, entry) {
4417 struct got_diff_changed_path *cp = pe->data;
4419 printf(" %c %s\n", cp->status, pe->path);
4421 printf("\n");
4423 if (show_patch) {
4424 if (diffstat) {
4425 f = got_opentemp();
4426 if (f == NULL) {
4427 err = got_error_from_errno("got_opentemp");
4428 goto done;
4432 err = print_patch(commit, id, path, diff_context, diffstat,
4433 repo, diffstat == NULL ? stdout : f);
4434 if (err)
4435 goto done;
4437 if (diffstat) {
4438 err = print_diffstat(diffstat, NULL);
4439 if (err)
4440 goto done;
4441 if (show_patch) {
4442 err = printfile(f);
4443 if (err)
4444 goto done;
4447 if (show_patch)
4448 printf("\n");
4450 if (fflush(stdout) != 0 && err == NULL)
4451 err = got_error_from_errno("fflush");
4452 done:
4453 if (f && fclose(f) == EOF && err == NULL)
4454 err = got_error_from_errno("fclose");
4455 free(id_str);
4456 free(refs_str);
4457 return err;
4460 static const struct got_error *
4461 print_commits(struct got_object_id *root_id, struct got_object_id *end_id,
4462 struct got_repository *repo, const char *path, int show_changed_paths,
4463 int show_diffstat, int show_patch, const char *search_pattern,
4464 int diff_context, int limit, int log_branches, int reverse_display_order,
4465 struct got_reflist_object_id_map *refs_idmap, int one_line, int toposort,
4466 FILE *tmpfile)
4468 const struct got_error *err;
4469 struct got_commit_graph *graph;
4470 regex_t regex;
4471 int have_match;
4472 struct got_object_id_queue reversed_commits;
4473 struct got_object_qid *qid;
4474 struct got_commit_object *commit;
4475 struct got_pathlist_head changed_paths;
4477 STAILQ_INIT(&reversed_commits);
4478 TAILQ_INIT(&changed_paths);
4480 if (search_pattern && regcomp(&regex, search_pattern,
4481 REG_EXTENDED | REG_NOSUB | REG_NEWLINE))
4482 return got_error_msg(GOT_ERR_REGEX, search_pattern);
4484 err = got_commit_graph_open(&graph, path, !log_branches);
4485 if (err)
4486 return err;
4487 if (log_branches && toposort) {
4488 err = got_commit_graph_toposort(graph, root_id, repo,
4489 check_cancelled, NULL);
4490 } else {
4491 err = got_commit_graph_bfsort(graph, root_id, repo,
4492 check_cancelled, NULL);
4494 if (err)
4495 goto done;
4496 for (;;) {
4497 struct got_object_id id;
4498 struct got_diffstat_cb_arg dsa = { 0, 0, 0, 0, 0, 0,
4499 &changed_paths, 0, 0, GOT_DIFF_ALGORITHM_PATIENCE };
4501 if (sigint_received || sigpipe_received)
4502 break;
4504 err = got_commit_graph_iter_next(&id, graph, repo,
4505 check_cancelled, NULL);
4506 if (err) {
4507 if (err->code == GOT_ERR_ITER_COMPLETED)
4508 err = NULL;
4509 break;
4512 err = got_object_open_as_commit(&commit, repo, &id);
4513 if (err)
4514 break;
4516 if (((show_changed_paths && !show_diffstat) ||
4517 (show_diffstat && !show_patch))
4518 && !reverse_display_order) {
4519 err = get_changed_paths(&changed_paths, commit, repo,
4520 show_diffstat ? &dsa : NULL);
4521 if (err)
4522 break;
4525 if (search_pattern) {
4526 err = match_commit(&have_match, &id, commit, &regex);
4527 if (err) {
4528 got_object_commit_close(commit);
4529 break;
4531 if (have_match == 0 && show_changed_paths)
4532 match_changed_paths(&have_match,
4533 &changed_paths, &regex);
4534 if (have_match == 0 && show_patch) {
4535 err = match_patch(&have_match, commit, &id,
4536 path, diff_context, repo, &regex, tmpfile);
4537 if (err)
4538 break;
4540 if (have_match == 0) {
4541 got_object_commit_close(commit);
4542 got_pathlist_free(&changed_paths,
4543 GOT_PATHLIST_FREE_ALL);
4544 continue;
4548 if (reverse_display_order) {
4549 err = got_object_qid_alloc(&qid, &id);
4550 if (err)
4551 break;
4552 STAILQ_INSERT_HEAD(&reversed_commits, qid, entry);
4553 got_object_commit_close(commit);
4554 } else {
4555 if (one_line)
4556 err = print_commit_oneline(commit, &id,
4557 repo, refs_idmap);
4558 else
4559 err = print_commit(commit, &id, repo, path,
4560 (show_changed_paths || show_diffstat) ?
4561 &changed_paths : NULL,
4562 show_diffstat ? &dsa : NULL, show_patch,
4563 diff_context, refs_idmap, NULL, NULL);
4564 got_object_commit_close(commit);
4565 if (err)
4566 break;
4568 if ((limit && --limit == 0) ||
4569 (end_id && got_object_id_cmp(&id, end_id) == 0))
4570 break;
4572 got_pathlist_free(&changed_paths, GOT_PATHLIST_FREE_ALL);
4574 if (reverse_display_order) {
4575 STAILQ_FOREACH(qid, &reversed_commits, entry) {
4576 struct got_diffstat_cb_arg dsa = { 0, 0, 0, 0, 0, 0,
4577 &changed_paths, 0, 0, GOT_DIFF_ALGORITHM_PATIENCE };
4579 err = got_object_open_as_commit(&commit, repo,
4580 &qid->id);
4581 if (err)
4582 break;
4583 if ((show_changed_paths && !show_diffstat) ||
4584 (show_diffstat && !show_patch)) {
4585 err = get_changed_paths(&changed_paths, commit,
4586 repo, show_diffstat ? &dsa : NULL);
4587 if (err)
4588 break;
4590 if (one_line)
4591 err = print_commit_oneline(commit, &qid->id,
4592 repo, refs_idmap);
4593 else
4594 err = print_commit(commit, &qid->id, repo, path,
4595 (show_changed_paths || show_diffstat) ?
4596 &changed_paths : NULL,
4597 show_diffstat ? &dsa : NULL, show_patch,
4598 diff_context, refs_idmap, NULL, NULL);
4599 got_object_commit_close(commit);
4600 if (err)
4601 break;
4602 got_pathlist_free(&changed_paths, GOT_PATHLIST_FREE_ALL);
4605 done:
4606 while (!STAILQ_EMPTY(&reversed_commits)) {
4607 qid = STAILQ_FIRST(&reversed_commits);
4608 STAILQ_REMOVE_HEAD(&reversed_commits, entry);
4609 got_object_qid_free(qid);
4611 got_pathlist_free(&changed_paths, GOT_PATHLIST_FREE_ALL);
4612 if (search_pattern)
4613 regfree(&regex);
4614 got_commit_graph_close(graph);
4615 return err;
4618 __dead static void
4619 usage_log(void)
4621 fprintf(stderr, "usage: %s log [-bdPpRst] [-C number] [-c commit] "
4622 "[-l N] [-r repository-path] [-S search-pattern] [-x commit] "
4623 "[path]\n", getprogname());
4624 exit(1);
4627 static int
4628 get_default_log_limit(void)
4630 const char *got_default_log_limit;
4631 long long n;
4632 const char *errstr;
4634 got_default_log_limit = getenv("GOT_LOG_DEFAULT_LIMIT");
4635 if (got_default_log_limit == NULL)
4636 return 0;
4637 n = strtonum(got_default_log_limit, 0, INT_MAX, &errstr);
4638 if (errstr != NULL)
4639 return 0;
4640 return n;
4643 static const struct got_error *
4644 cmd_log(int argc, char *argv[])
4646 const struct got_error *error;
4647 struct got_repository *repo = NULL;
4648 struct got_worktree *worktree = NULL;
4649 struct got_object_id *start_id = NULL, *end_id = NULL;
4650 char *repo_path = NULL, *path = NULL, *cwd = NULL, *in_repo_path = NULL;
4651 char *keyword_idstr = NULL;
4652 const char *start_commit = NULL, *end_commit = NULL;
4653 const char *search_pattern = NULL;
4654 int diff_context = -1, ch;
4655 int show_changed_paths = 0, show_patch = 0, limit = 0, log_branches = 0;
4656 int show_diffstat = 0, reverse_display_order = 0, one_line = 0;
4657 int toposort = 0;
4658 const char *errstr;
4659 struct got_reflist_head refs;
4660 struct got_reflist_object_id_map *refs_idmap = NULL;
4661 FILE *tmpfile = NULL;
4662 int *pack_fds = NULL;
4664 TAILQ_INIT(&refs);
4666 #ifndef PROFILE
4667 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
4668 NULL)
4669 == -1)
4670 err(1, "pledge");
4671 #endif
4673 limit = get_default_log_limit();
4675 while ((ch = getopt(argc, argv, "bC:c:dl:PpRr:S:stx:")) != -1) {
4676 switch (ch) {
4677 case 'b':
4678 log_branches = 1;
4679 break;
4680 case 'C':
4681 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
4682 &errstr);
4683 if (errstr != NULL)
4684 errx(1, "number of context lines is %s: %s",
4685 errstr, optarg);
4686 break;
4687 case 'c':
4688 start_commit = optarg;
4689 break;
4690 case 'd':
4691 show_diffstat = 1;
4692 break;
4693 case 'l':
4694 limit = strtonum(optarg, 0, INT_MAX, &errstr);
4695 if (errstr != NULL)
4696 errx(1, "number of commits is %s: %s",
4697 errstr, optarg);
4698 break;
4699 case 'P':
4700 show_changed_paths = 1;
4701 break;
4702 case 'p':
4703 show_patch = 1;
4704 break;
4705 case 'R':
4706 reverse_display_order = 1;
4707 break;
4708 case 'r':
4709 repo_path = realpath(optarg, NULL);
4710 if (repo_path == NULL)
4711 return got_error_from_errno2("realpath",
4712 optarg);
4713 got_path_strip_trailing_slashes(repo_path);
4714 break;
4715 case 'S':
4716 search_pattern = optarg;
4717 break;
4718 case 's':
4719 one_line = 1;
4720 break;
4721 case 't':
4722 toposort = 1;
4723 break;
4724 case 'x':
4725 end_commit = optarg;
4726 break;
4727 default:
4728 usage_log();
4729 /* NOTREACHED */
4733 argc -= optind;
4734 argv += optind;
4736 if (diff_context == -1)
4737 diff_context = 3;
4738 else if (!show_patch)
4739 errx(1, "-C requires -p");
4741 if (one_line && (show_patch || show_changed_paths || show_diffstat))
4742 errx(1, "cannot use -s with -d, -p or -P");
4744 cwd = getcwd(NULL, 0);
4745 if (cwd == NULL) {
4746 error = got_error_from_errno("getcwd");
4747 goto done;
4750 error = got_repo_pack_fds_open(&pack_fds);
4751 if (error != NULL)
4752 goto done;
4754 if (repo_path == NULL) {
4755 error = got_worktree_open(&worktree, cwd,
4756 GOT_WORKTREE_GOT_DIR);
4757 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4758 goto done;
4759 error = NULL;
4762 if (argc == 1) {
4763 if (worktree) {
4764 error = got_worktree_resolve_path(&path, worktree,
4765 argv[0]);
4766 if (error)
4767 goto done;
4768 } else {
4769 path = strdup(argv[0]);
4770 if (path == NULL) {
4771 error = got_error_from_errno("strdup");
4772 goto done;
4775 } else if (argc != 0)
4776 usage_log();
4778 if (repo_path == NULL) {
4779 repo_path = worktree ?
4780 strdup(got_worktree_get_repo_path(worktree)) : strdup(cwd);
4782 if (repo_path == NULL) {
4783 error = got_error_from_errno("strdup");
4784 goto done;
4787 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
4788 if (error != NULL)
4789 goto done;
4791 error = apply_unveil(got_repo_get_path(repo), 1,
4792 worktree ? got_worktree_get_root_path(worktree) : NULL);
4793 if (error)
4794 goto done;
4796 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
4797 if (error)
4798 goto done;
4800 error = got_reflist_object_id_map_create(&refs_idmap, &refs, repo);
4801 if (error)
4802 goto done;
4804 if (start_commit == NULL) {
4805 struct got_reference *head_ref;
4806 struct got_commit_object *commit = NULL;
4807 error = got_ref_open(&head_ref, repo,
4808 worktree ? got_worktree_get_head_ref_name(worktree)
4809 : GOT_REF_HEAD, 0);
4810 if (error != NULL)
4811 goto done;
4812 error = got_ref_resolve(&start_id, repo, head_ref);
4813 got_ref_close(head_ref);
4814 if (error != NULL)
4815 goto done;
4816 error = got_object_open_as_commit(&commit, repo,
4817 start_id);
4818 if (error != NULL)
4819 goto done;
4820 got_object_commit_close(commit);
4821 } else {
4822 error = got_keyword_to_idstr(&keyword_idstr, start_commit,
4823 repo, worktree);
4824 if (error != NULL)
4825 goto done;
4826 if (keyword_idstr != NULL)
4827 start_commit = keyword_idstr;
4829 error = got_repo_match_object_id(&start_id, NULL,
4830 start_commit, GOT_OBJ_TYPE_COMMIT, &refs, repo);
4831 if (error != NULL)
4832 goto done;
4834 if (end_commit != NULL) {
4835 error = got_keyword_to_idstr(&keyword_idstr, end_commit,
4836 repo, worktree);
4837 if (error != NULL)
4838 goto done;
4839 if (keyword_idstr != NULL)
4840 end_commit = keyword_idstr;
4842 error = got_repo_match_object_id(&end_id, NULL,
4843 end_commit, GOT_OBJ_TYPE_COMMIT, &refs, repo);
4844 if (error != NULL)
4845 goto done;
4848 if (worktree) {
4850 * If a path was specified on the command line it was resolved
4851 * to a path in the work tree above. Prepend the work tree's
4852 * path prefix to obtain the corresponding in-repository path.
4854 if (path) {
4855 const char *prefix;
4856 prefix = got_worktree_get_path_prefix(worktree);
4857 if (asprintf(&in_repo_path, "%s%s%s", prefix,
4858 (path[0] != '\0') ? "/" : "", path) == -1) {
4859 error = got_error_from_errno("asprintf");
4860 goto done;
4863 } else
4864 error = got_repo_map_path(&in_repo_path, repo,
4865 path ? path : "");
4866 if (error != NULL)
4867 goto done;
4868 if (in_repo_path) {
4869 free(path);
4870 path = in_repo_path;
4873 if (worktree) {
4874 /* Release work tree lock. */
4875 got_worktree_close(worktree);
4876 worktree = NULL;
4879 if (search_pattern && show_patch) {
4880 tmpfile = got_opentemp();
4881 if (tmpfile == NULL) {
4882 error = got_error_from_errno("got_opentemp");
4883 goto done;
4887 error = print_commits(start_id, end_id, repo, path ? path : "",
4888 show_changed_paths, show_diffstat, show_patch, search_pattern,
4889 diff_context, limit, log_branches, reverse_display_order,
4890 refs_idmap, one_line, toposort, tmpfile);
4891 done:
4892 free(path);
4893 free(repo_path);
4894 free(cwd);
4895 free(start_id);
4896 free(end_id);
4897 free(keyword_idstr);
4898 if (worktree)
4899 got_worktree_close(worktree);
4900 if (repo) {
4901 const struct got_error *close_err = got_repo_close(repo);
4902 if (error == NULL)
4903 error = close_err;
4905 if (pack_fds) {
4906 const struct got_error *pack_err =
4907 got_repo_pack_fds_close(pack_fds);
4908 if (error == NULL)
4909 error = pack_err;
4911 if (refs_idmap)
4912 got_reflist_object_id_map_free(refs_idmap);
4913 if (tmpfile && fclose(tmpfile) == EOF && error == NULL)
4914 error = got_error_from_errno("fclose");
4915 got_ref_list_free(&refs);
4916 return error;
4919 __dead static void
4920 usage_diff(void)
4922 fprintf(stderr, "usage: %s diff [-adPsw] [-C number] [-c commit] "
4923 "[-r repository-path] [object1 object2 | path ...]\n",
4924 getprogname());
4925 exit(1);
4928 struct print_diff_arg {
4929 struct got_repository *repo;
4930 struct got_worktree *worktree;
4931 struct got_diffstat_cb_arg *diffstat;
4932 int diff_context;
4933 const char *id_str;
4934 int header_shown;
4935 int diff_staged;
4936 enum got_diff_algorithm diff_algo;
4937 int ignore_whitespace;
4938 int force_text_diff;
4939 FILE *f1;
4940 FILE *f2;
4941 FILE *outfile;
4945 * Create a file which contains the target path of a symlink so we can feed
4946 * it as content to the diff engine.
4948 static const struct got_error *
4949 get_symlink_target_file(int *fd, int dirfd, const char *de_name,
4950 const char *abspath)
4952 const struct got_error *err = NULL;
4953 char target_path[PATH_MAX];
4954 ssize_t target_len, outlen;
4956 *fd = -1;
4958 if (dirfd != -1) {
4959 target_len = readlinkat(dirfd, de_name, target_path, PATH_MAX);
4960 if (target_len == -1)
4961 return got_error_from_errno2("readlinkat", abspath);
4962 } else {
4963 target_len = readlink(abspath, target_path, PATH_MAX);
4964 if (target_len == -1)
4965 return got_error_from_errno2("readlink", abspath);
4968 *fd = got_opentempfd();
4969 if (*fd == -1)
4970 return got_error_from_errno("got_opentempfd");
4972 outlen = write(*fd, target_path, target_len);
4973 if (outlen == -1) {
4974 err = got_error_from_errno("got_opentempfd");
4975 goto done;
4978 if (lseek(*fd, 0, SEEK_SET) == -1) {
4979 err = got_error_from_errno2("lseek", abspath);
4980 goto done;
4982 done:
4983 if (err) {
4984 close(*fd);
4985 *fd = -1;
4987 return err;
4990 static const struct got_error *
4991 print_diff(void *arg, unsigned char status, unsigned char staged_status,
4992 const char *path, struct got_object_id *blob_id,
4993 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
4994 int dirfd, const char *de_name)
4996 struct print_diff_arg *a = arg;
4997 const struct got_error *err = NULL;
4998 struct got_blob_object *blob1 = NULL;
4999 int fd = -1, fd1 = -1, fd2 = -1;
5000 FILE *f2 = NULL;
5001 char *abspath = NULL, *label1 = NULL;
5002 struct stat sb;
5003 off_t size1 = 0;
5004 int f2_exists = 0;
5006 memset(&sb, 0, sizeof(sb));
5008 if (a->diff_staged) {
5009 if (staged_status != GOT_STATUS_MODIFY &&
5010 staged_status != GOT_STATUS_ADD &&
5011 staged_status != GOT_STATUS_DELETE)
5012 return NULL;
5013 } else {
5014 if (staged_status == GOT_STATUS_DELETE)
5015 return NULL;
5016 if (status == GOT_STATUS_NONEXISTENT)
5017 return got_error_set_errno(ENOENT, path);
5018 if (status != GOT_STATUS_MODIFY &&
5019 status != GOT_STATUS_ADD &&
5020 status != GOT_STATUS_DELETE &&
5021 status != GOT_STATUS_CONFLICT)
5022 return NULL;
5025 err = got_opentemp_truncate(a->f1);
5026 if (err)
5027 return got_error_from_errno("got_opentemp_truncate");
5028 err = got_opentemp_truncate(a->f2);
5029 if (err)
5030 return got_error_from_errno("got_opentemp_truncate");
5032 if (!a->header_shown) {
5033 if (fprintf(a->outfile, "diff %s%s\n",
5034 a->diff_staged ? "-s " : "",
5035 got_worktree_get_root_path(a->worktree)) < 0) {
5036 err = got_error_from_errno("fprintf");
5037 goto done;
5039 if (fprintf(a->outfile, "commit - %s\n", a->id_str) < 0) {
5040 err = got_error_from_errno("fprintf");
5041 goto done;
5043 if (fprintf(a->outfile, "path + %s%s\n",
5044 got_worktree_get_root_path(a->worktree),
5045 a->diff_staged ? " (staged changes)" : "") < 0) {
5046 err = got_error_from_errno("fprintf");
5047 goto done;
5049 a->header_shown = 1;
5052 if (a->diff_staged) {
5053 const char *label1 = NULL, *label2 = NULL;
5054 switch (staged_status) {
5055 case GOT_STATUS_MODIFY:
5056 label1 = path;
5057 label2 = path;
5058 break;
5059 case GOT_STATUS_ADD:
5060 label2 = path;
5061 break;
5062 case GOT_STATUS_DELETE:
5063 label1 = path;
5064 break;
5065 default:
5066 return got_error(GOT_ERR_FILE_STATUS);
5068 fd1 = got_opentempfd();
5069 if (fd1 == -1) {
5070 err = got_error_from_errno("got_opentempfd");
5071 goto done;
5073 fd2 = got_opentempfd();
5074 if (fd2 == -1) {
5075 err = got_error_from_errno("got_opentempfd");
5076 goto done;
5078 err = got_diff_objects_as_blobs(NULL, NULL, a->f1, a->f2,
5079 fd1, fd2, blob_id, staged_blob_id, label1, label2,
5080 a->diff_algo, a->diff_context, a->ignore_whitespace,
5081 a->force_text_diff, a->diffstat, a->repo, a->outfile);
5082 goto done;
5085 fd1 = got_opentempfd();
5086 if (fd1 == -1) {
5087 err = got_error_from_errno("got_opentempfd");
5088 goto done;
5091 if (staged_status == GOT_STATUS_ADD ||
5092 staged_status == GOT_STATUS_MODIFY) {
5093 char *id_str;
5094 err = got_object_open_as_blob(&blob1, a->repo, staged_blob_id,
5095 8192, fd1);
5096 if (err)
5097 goto done;
5098 err = got_object_id_str(&id_str, staged_blob_id);
5099 if (err)
5100 goto done;
5101 if (asprintf(&label1, "%s (staged)", id_str) == -1) {
5102 err = got_error_from_errno("asprintf");
5103 free(id_str);
5104 goto done;
5106 free(id_str);
5107 } else if (status != GOT_STATUS_ADD) {
5108 err = got_object_open_as_blob(&blob1, a->repo, blob_id, 8192,
5109 fd1);
5110 if (err)
5111 goto done;
5114 if (status != GOT_STATUS_DELETE) {
5115 if (asprintf(&abspath, "%s/%s",
5116 got_worktree_get_root_path(a->worktree), path) == -1) {
5117 err = got_error_from_errno("asprintf");
5118 goto done;
5121 if (dirfd != -1) {
5122 fd = openat(dirfd, de_name,
5123 O_RDONLY | O_NOFOLLOW | O_CLOEXEC);
5124 if (fd == -1) {
5125 if (!got_err_open_nofollow_on_symlink()) {
5126 err = got_error_from_errno2("openat",
5127 abspath);
5128 goto done;
5130 err = get_symlink_target_file(&fd, dirfd,
5131 de_name, abspath);
5132 if (err)
5133 goto done;
5135 } else {
5136 fd = open(abspath, O_RDONLY | O_NOFOLLOW | O_CLOEXEC);
5137 if (fd == -1) {
5138 if (!got_err_open_nofollow_on_symlink()) {
5139 err = got_error_from_errno2("open",
5140 abspath);
5141 goto done;
5143 err = get_symlink_target_file(&fd, dirfd,
5144 de_name, abspath);
5145 if (err)
5146 goto done;
5149 if (fstatat(fd, abspath, &sb, AT_SYMLINK_NOFOLLOW) == -1) {
5150 err = got_error_from_errno2("fstatat", abspath);
5151 goto done;
5153 f2 = fdopen(fd, "r");
5154 if (f2 == NULL) {
5155 err = got_error_from_errno2("fdopen", abspath);
5156 goto done;
5158 fd = -1;
5159 f2_exists = 1;
5162 if (blob1) {
5163 err = got_object_blob_dump_to_file(&size1, NULL, NULL,
5164 a->f1, blob1);
5165 if (err)
5166 goto done;
5169 err = got_diff_blob_file(blob1, a->f1, size1, label1, f2 ? f2 : a->f2,
5170 f2_exists, &sb, path, GOT_DIFF_ALGORITHM_PATIENCE, a->diff_context,
5171 a->ignore_whitespace, a->force_text_diff, a->diffstat, a->outfile);
5172 done:
5173 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
5174 err = got_error_from_errno("close");
5175 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
5176 err = got_error_from_errno("close");
5177 if (blob1)
5178 got_object_blob_close(blob1);
5179 if (fd != -1 && close(fd) == -1 && err == NULL)
5180 err = got_error_from_errno("close");
5181 if (f2 && fclose(f2) == EOF && err == NULL)
5182 err = got_error_from_errno("fclose");
5183 free(abspath);
5184 return err;
5187 static const struct got_error *
5188 cmd_diff(int argc, char *argv[])
5190 const struct got_error *error;
5191 struct got_repository *repo = NULL;
5192 struct got_worktree *worktree = NULL;
5193 char *cwd = NULL, *repo_path = NULL;
5194 const char *commit_args[2] = { NULL, NULL };
5195 int ncommit_args = 0;
5196 struct got_object_id *ids[2] = { NULL, NULL };
5197 char *labels[2] = { NULL, NULL };
5198 int type1 = GOT_OBJ_TYPE_ANY, type2 = GOT_OBJ_TYPE_ANY;
5199 int diff_context = 3, diff_staged = 0, ignore_whitespace = 0, ch, i;
5200 int force_text_diff = 0, force_path = 0, rflag = 0, show_diffstat = 0;
5201 const char *errstr;
5202 struct got_reflist_head refs;
5203 struct got_pathlist_head diffstat_paths, paths;
5204 FILE *f1 = NULL, *f2 = NULL, *outfile = NULL;
5205 int fd1 = -1, fd2 = -1;
5206 int *pack_fds = NULL;
5207 struct got_diffstat_cb_arg dsa;
5209 memset(&dsa, 0, sizeof(dsa));
5211 TAILQ_INIT(&refs);
5212 TAILQ_INIT(&paths);
5213 TAILQ_INIT(&diffstat_paths);
5215 #ifndef PROFILE
5216 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
5217 NULL) == -1)
5218 err(1, "pledge");
5219 #endif
5221 while ((ch = getopt(argc, argv, "aC:c:dPr:sw")) != -1) {
5222 switch (ch) {
5223 case 'a':
5224 force_text_diff = 1;
5225 break;
5226 case 'C':
5227 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
5228 &errstr);
5229 if (errstr != NULL)
5230 errx(1, "number of context lines is %s: %s",
5231 errstr, optarg);
5232 break;
5233 case 'c':
5234 if (ncommit_args >= 2)
5235 errx(1, "too many -c options used");
5236 commit_args[ncommit_args++] = optarg;
5237 break;
5238 case 'd':
5239 show_diffstat = 1;
5240 break;
5241 case 'P':
5242 force_path = 1;
5243 break;
5244 case 'r':
5245 repo_path = realpath(optarg, NULL);
5246 if (repo_path == NULL)
5247 return got_error_from_errno2("realpath",
5248 optarg);
5249 got_path_strip_trailing_slashes(repo_path);
5250 rflag = 1;
5251 break;
5252 case 's':
5253 diff_staged = 1;
5254 break;
5255 case 'w':
5256 ignore_whitespace = 1;
5257 break;
5258 default:
5259 usage_diff();
5260 /* NOTREACHED */
5264 argc -= optind;
5265 argv += optind;
5267 cwd = getcwd(NULL, 0);
5268 if (cwd == NULL) {
5269 error = got_error_from_errno("getcwd");
5270 goto done;
5273 error = got_repo_pack_fds_open(&pack_fds);
5274 if (error != NULL)
5275 goto done;
5277 if (repo_path == NULL) {
5278 error = got_worktree_open(&worktree, cwd,
5279 GOT_WORKTREE_GOT_DIR);
5280 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5281 goto done;
5282 else
5283 error = NULL;
5284 if (worktree) {
5285 repo_path =
5286 strdup(got_worktree_get_repo_path(worktree));
5287 if (repo_path == NULL) {
5288 error = got_error_from_errno("strdup");
5289 goto done;
5291 } else {
5292 repo_path = strdup(cwd);
5293 if (repo_path == NULL) {
5294 error = got_error_from_errno("strdup");
5295 goto done;
5300 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
5301 free(repo_path);
5302 if (error != NULL)
5303 goto done;
5305 if (show_diffstat) {
5306 dsa.paths = &diffstat_paths;
5307 dsa.force_text = force_text_diff;
5308 dsa.ignore_ws = ignore_whitespace;
5309 dsa.diff_algo = GOT_DIFF_ALGORITHM_PATIENCE;
5312 if (rflag || worktree == NULL || ncommit_args > 0) {
5313 if (force_path) {
5314 error = got_error_msg(GOT_ERR_NOT_IMPL,
5315 "-P option can only be used when diffing "
5316 "a work tree");
5317 goto done;
5319 if (diff_staged) {
5320 error = got_error_msg(GOT_ERR_NOT_IMPL,
5321 "-s option can only be used when diffing "
5322 "a work tree");
5323 goto done;
5327 error = apply_unveil(got_repo_get_path(repo), 1,
5328 worktree ? got_worktree_get_root_path(worktree) : NULL);
5329 if (error)
5330 goto done;
5332 if ((!force_path && argc == 2) || ncommit_args > 0) {
5333 int obj_type = (ncommit_args > 0 ?
5334 GOT_OBJ_TYPE_COMMIT : GOT_OBJ_TYPE_ANY);
5335 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
5336 NULL);
5337 if (error)
5338 goto done;
5339 for (i = 0; i < (ncommit_args > 0 ? ncommit_args : argc); i++) {
5340 const char *arg;
5341 char *keyword_idstr = NULL;
5343 if (ncommit_args > 0)
5344 arg = commit_args[i];
5345 else
5346 arg = argv[i];
5348 error = got_keyword_to_idstr(&keyword_idstr, arg,
5349 repo, worktree);
5350 if (error != NULL)
5351 goto done;
5352 if (keyword_idstr != NULL)
5353 arg = keyword_idstr;
5355 error = got_repo_match_object_id(&ids[i], &labels[i],
5356 arg, obj_type, &refs, repo);
5357 free(keyword_idstr);
5358 if (error) {
5359 if (error->code != GOT_ERR_NOT_REF &&
5360 error->code != GOT_ERR_NO_OBJ)
5361 goto done;
5362 if (ncommit_args > 0)
5363 goto done;
5364 error = NULL;
5365 break;
5370 f1 = got_opentemp();
5371 if (f1 == NULL) {
5372 error = got_error_from_errno("got_opentemp");
5373 goto done;
5376 f2 = got_opentemp();
5377 if (f2 == NULL) {
5378 error = got_error_from_errno("got_opentemp");
5379 goto done;
5382 outfile = got_opentemp();
5383 if (outfile == NULL) {
5384 error = got_error_from_errno("got_opentemp");
5385 goto done;
5388 if (ncommit_args == 0 && (ids[0] == NULL || ids[1] == NULL)) {
5389 struct print_diff_arg arg;
5390 char *id_str;
5392 if (worktree == NULL) {
5393 if (argc == 2 && ids[0] == NULL) {
5394 error = got_error_path(argv[0], GOT_ERR_NO_OBJ);
5395 goto done;
5396 } else if (argc == 2 && ids[1] == NULL) {
5397 error = got_error_path(argv[1], GOT_ERR_NO_OBJ);
5398 goto done;
5399 } else if (argc > 0) {
5400 error = got_error_fmt(GOT_ERR_NOT_WORKTREE,
5401 "%s", "specified paths cannot be resolved");
5402 goto done;
5403 } else {
5404 error = got_error(GOT_ERR_NOT_WORKTREE);
5405 goto done;
5409 error = get_worktree_paths_from_argv(&paths, argc, argv,
5410 worktree);
5411 if (error)
5412 goto done;
5414 error = got_object_id_str(&id_str,
5415 got_worktree_get_base_commit_id(worktree));
5416 if (error)
5417 goto done;
5418 arg.repo = repo;
5419 arg.worktree = worktree;
5420 arg.diff_algo = GOT_DIFF_ALGORITHM_PATIENCE;
5421 arg.diff_context = diff_context;
5422 arg.id_str = id_str;
5423 arg.header_shown = 0;
5424 arg.diff_staged = diff_staged;
5425 arg.ignore_whitespace = ignore_whitespace;
5426 arg.force_text_diff = force_text_diff;
5427 arg.diffstat = show_diffstat ? &dsa : NULL;
5428 arg.f1 = f1;
5429 arg.f2 = f2;
5430 arg.outfile = outfile;
5432 error = got_worktree_status(worktree, &paths, repo, 0,
5433 print_diff, &arg, check_cancelled, NULL);
5434 free(id_str);
5435 if (error)
5436 goto done;
5438 if (show_diffstat && dsa.nfiles > 0) {
5439 char *header;
5441 if (asprintf(&header, "diffstat %s%s",
5442 diff_staged ? "-s " : "",
5443 got_worktree_get_root_path(worktree)) == -1) {
5444 error = got_error_from_errno("asprintf");
5445 goto done;
5448 error = print_diffstat(&dsa, header);
5449 free(header);
5450 if (error)
5451 goto done;
5454 error = printfile(outfile);
5455 goto done;
5458 if (ncommit_args == 1) {
5459 struct got_commit_object *commit;
5460 error = got_object_open_as_commit(&commit, repo, ids[0]);
5461 if (error)
5462 goto done;
5464 labels[1] = labels[0];
5465 ids[1] = ids[0];
5466 if (got_object_commit_get_nparents(commit) > 0) {
5467 const struct got_object_id_queue *pids;
5468 struct got_object_qid *pid;
5469 pids = got_object_commit_get_parent_ids(commit);
5470 pid = STAILQ_FIRST(pids);
5471 ids[0] = got_object_id_dup(&pid->id);
5472 if (ids[0] == NULL) {
5473 error = got_error_from_errno(
5474 "got_object_id_dup");
5475 got_object_commit_close(commit);
5476 goto done;
5478 error = got_object_id_str(&labels[0], ids[0]);
5479 if (error) {
5480 got_object_commit_close(commit);
5481 goto done;
5483 } else {
5484 ids[0] = NULL;
5485 labels[0] = strdup("/dev/null");
5486 if (labels[0] == NULL) {
5487 error = got_error_from_errno("strdup");
5488 got_object_commit_close(commit);
5489 goto done;
5493 got_object_commit_close(commit);
5496 if (ncommit_args == 0 && argc > 2) {
5497 error = got_error_msg(GOT_ERR_BAD_PATH,
5498 "path arguments cannot be used when diffing two objects");
5499 goto done;
5502 if (ids[0]) {
5503 error = got_object_get_type(&type1, repo, ids[0]);
5504 if (error)
5505 goto done;
5508 error = got_object_get_type(&type2, repo, ids[1]);
5509 if (error)
5510 goto done;
5511 if (type1 != GOT_OBJ_TYPE_ANY && type1 != type2) {
5512 error = got_error(GOT_ERR_OBJ_TYPE);
5513 goto done;
5515 if (type1 == GOT_OBJ_TYPE_BLOB && argc > 2) {
5516 error = got_error_msg(GOT_ERR_OBJ_TYPE,
5517 "path arguments cannot be used when diffing blobs");
5518 goto done;
5521 for (i = 0; ncommit_args > 0 && i < argc; i++) {
5522 char *in_repo_path;
5523 struct got_pathlist_entry *new;
5524 if (worktree) {
5525 const char *prefix;
5526 char *p;
5527 error = got_worktree_resolve_path(&p, worktree,
5528 argv[i]);
5529 if (error)
5530 goto done;
5531 prefix = got_worktree_get_path_prefix(worktree);
5532 while (prefix[0] == '/')
5533 prefix++;
5534 if (asprintf(&in_repo_path, "%s%s%s", prefix,
5535 (p[0] != '\0' && prefix[0] != '\0') ? "/" : "",
5536 p) == -1) {
5537 error = got_error_from_errno("asprintf");
5538 free(p);
5539 goto done;
5541 free(p);
5542 } else {
5543 char *mapped_path, *s;
5544 error = got_repo_map_path(&mapped_path, repo, argv[i]);
5545 if (error)
5546 goto done;
5547 s = mapped_path;
5548 while (s[0] == '/')
5549 s++;
5550 in_repo_path = strdup(s);
5551 if (in_repo_path == NULL) {
5552 error = got_error_from_errno("asprintf");
5553 free(mapped_path);
5554 goto done;
5556 free(mapped_path);
5559 error = got_pathlist_insert(&new, &paths, in_repo_path, NULL);
5560 if (error || new == NULL /* duplicate */)
5561 free(in_repo_path);
5562 if (error)
5563 goto done;
5566 if (worktree) {
5567 /* Release work tree lock. */
5568 got_worktree_close(worktree);
5569 worktree = NULL;
5572 fd1 = got_opentempfd();
5573 if (fd1 == -1) {
5574 error = got_error_from_errno("got_opentempfd");
5575 goto done;
5578 fd2 = got_opentempfd();
5579 if (fd2 == -1) {
5580 error = got_error_from_errno("got_opentempfd");
5581 goto done;
5584 switch (type1 == GOT_OBJ_TYPE_ANY ? type2 : type1) {
5585 case GOT_OBJ_TYPE_BLOB:
5586 error = got_diff_objects_as_blobs(NULL, NULL, f1, f2,
5587 fd1, fd2, ids[0], ids[1], NULL, NULL,
5588 GOT_DIFF_ALGORITHM_PATIENCE, diff_context,
5589 ignore_whitespace, force_text_diff,
5590 show_diffstat ? &dsa : NULL, repo, outfile);
5591 break;
5592 case GOT_OBJ_TYPE_TREE:
5593 error = got_diff_objects_as_trees(NULL, NULL, f1, f2, fd1, fd2,
5594 ids[0], ids[1], &paths, "", "",
5595 GOT_DIFF_ALGORITHM_PATIENCE, diff_context,
5596 ignore_whitespace, force_text_diff,
5597 show_diffstat ? &dsa : NULL, repo, outfile);
5598 break;
5599 case GOT_OBJ_TYPE_COMMIT:
5600 fprintf(outfile, "diff %s %s\n", labels[0], labels[1]);
5601 error = got_diff_objects_as_commits(NULL, NULL, f1, f2,
5602 fd1, fd2, ids[0], ids[1], &paths,
5603 GOT_DIFF_ALGORITHM_PATIENCE, diff_context,
5604 ignore_whitespace, force_text_diff,
5605 show_diffstat ? &dsa : NULL, repo, outfile);
5606 break;
5607 default:
5608 error = got_error(GOT_ERR_OBJ_TYPE);
5610 if (error)
5611 goto done;
5613 if (show_diffstat && dsa.nfiles > 0) {
5614 char *header = NULL;
5616 if (asprintf(&header, "diffstat %s %s",
5617 labels[0], labels[1]) == -1) {
5618 error = got_error_from_errno("asprintf");
5619 goto done;
5622 error = print_diffstat(&dsa, header);
5623 free(header);
5624 if (error)
5625 goto done;
5628 error = printfile(outfile);
5630 done:
5631 free(labels[0]);
5632 free(labels[1]);
5633 free(ids[0]);
5634 free(ids[1]);
5635 if (worktree)
5636 got_worktree_close(worktree);
5637 if (repo) {
5638 const struct got_error *close_err = got_repo_close(repo);
5639 if (error == NULL)
5640 error = close_err;
5642 if (pack_fds) {
5643 const struct got_error *pack_err =
5644 got_repo_pack_fds_close(pack_fds);
5645 if (error == NULL)
5646 error = pack_err;
5648 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
5649 got_pathlist_free(&diffstat_paths, GOT_PATHLIST_FREE_ALL);
5650 got_ref_list_free(&refs);
5651 if (outfile && fclose(outfile) == EOF && error == NULL)
5652 error = got_error_from_errno("fclose");
5653 if (f1 && fclose(f1) == EOF && error == NULL)
5654 error = got_error_from_errno("fclose");
5655 if (f2 && fclose(f2) == EOF && error == NULL)
5656 error = got_error_from_errno("fclose");
5657 if (fd1 != -1 && close(fd1) == -1 && error == NULL)
5658 error = got_error_from_errno("close");
5659 if (fd2 != -1 && close(fd2) == -1 && error == NULL)
5660 error = got_error_from_errno("close");
5661 return error;
5664 __dead static void
5665 usage_blame(void)
5667 fprintf(stderr,
5668 "usage: %s blame [-c commit] [-r repository-path] path\n",
5669 getprogname());
5670 exit(1);
5673 struct blame_line {
5674 int annotated;
5675 char *id_str;
5676 char *committer;
5677 char datebuf[11]; /* YYYY-MM-DD + NUL */
5680 struct blame_cb_args {
5681 struct blame_line *lines;
5682 int nlines;
5683 int nlines_prec;
5684 int lineno_cur;
5685 off_t *line_offsets;
5686 FILE *f;
5687 struct got_repository *repo;
5690 static const struct got_error *
5691 blame_cb(void *arg, int nlines, int lineno,
5692 struct got_commit_object *commit, struct got_object_id *id)
5694 const struct got_error *err = NULL;
5695 struct blame_cb_args *a = arg;
5696 struct blame_line *bline;
5697 char *line = NULL;
5698 size_t linesize = 0;
5699 off_t offset;
5700 struct tm tm;
5701 time_t committer_time;
5703 if (nlines != a->nlines ||
5704 (lineno != -1 && lineno < 1) || lineno > a->nlines)
5705 return got_error(GOT_ERR_RANGE);
5707 if (sigint_received)
5708 return got_error(GOT_ERR_ITER_COMPLETED);
5710 if (lineno == -1)
5711 return NULL; /* no change in this commit */
5713 /* Annotate this line. */
5714 bline = &a->lines[lineno - 1];
5715 if (bline->annotated)
5716 return NULL;
5717 err = got_object_id_str(&bline->id_str, id);
5718 if (err)
5719 return err;
5721 bline->committer = strdup(got_object_commit_get_committer(commit));
5722 if (bline->committer == NULL) {
5723 err = got_error_from_errno("strdup");
5724 goto done;
5727 committer_time = got_object_commit_get_committer_time(commit);
5728 if (gmtime_r(&committer_time, &tm) == NULL)
5729 return got_error_from_errno("gmtime_r");
5730 if (strftime(bline->datebuf, sizeof(bline->datebuf), "%F", &tm) == 0) {
5731 err = got_error(GOT_ERR_NO_SPACE);
5732 goto done;
5734 bline->annotated = 1;
5736 /* Print lines annotated so far. */
5737 bline = &a->lines[a->lineno_cur - 1];
5738 if (!bline->annotated)
5739 goto done;
5741 offset = a->line_offsets[a->lineno_cur - 1];
5742 if (fseeko(a->f, offset, SEEK_SET) == -1) {
5743 err = got_error_from_errno("fseeko");
5744 goto done;
5747 while (a->lineno_cur <= a->nlines && bline->annotated) {
5748 char *smallerthan, *at, *nl, *committer;
5749 size_t len;
5751 if (getline(&line, &linesize, a->f) == -1) {
5752 if (ferror(a->f))
5753 err = got_error_from_errno("getline");
5754 break;
5757 committer = bline->committer;
5758 smallerthan = strchr(committer, '<');
5759 if (smallerthan && smallerthan[1] != '\0')
5760 committer = smallerthan + 1;
5761 at = strchr(committer, '@');
5762 if (at)
5763 *at = '\0';
5764 len = strlen(committer);
5765 if (len >= 9)
5766 committer[8] = '\0';
5768 nl = strchr(line, '\n');
5769 if (nl)
5770 *nl = '\0';
5771 printf("%.*d) %.8s %s %-8s %s\n", a->nlines_prec, a->lineno_cur,
5772 bline->id_str, bline->datebuf, committer, line);
5774 a->lineno_cur++;
5775 bline = &a->lines[a->lineno_cur - 1];
5777 done:
5778 free(line);
5779 return err;
5782 static const struct got_error *
5783 cmd_blame(int argc, char *argv[])
5785 const struct got_error *error;
5786 struct got_repository *repo = NULL;
5787 struct got_worktree *worktree = NULL;
5788 char *path, *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
5789 char *link_target = NULL;
5790 struct got_object_id *obj_id = NULL;
5791 struct got_object_id *commit_id = NULL;
5792 struct got_commit_object *commit = NULL;
5793 struct got_blob_object *blob = NULL;
5794 char *commit_id_str = NULL, *keyword_idstr = NULL;
5795 struct blame_cb_args bca;
5796 int ch, obj_type, i, fd1 = -1, fd2 = -1, fd3 = -1;
5797 off_t filesize;
5798 int *pack_fds = NULL;
5799 FILE *f1 = NULL, *f2 = NULL;
5801 fd1 = got_opentempfd();
5802 if (fd1 == -1)
5803 return got_error_from_errno("got_opentempfd");
5805 memset(&bca, 0, sizeof(bca));
5807 #ifndef PROFILE
5808 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
5809 NULL) == -1)
5810 err(1, "pledge");
5811 #endif
5813 while ((ch = getopt(argc, argv, "c:r:")) != -1) {
5814 switch (ch) {
5815 case 'c':
5816 commit_id_str = optarg;
5817 break;
5818 case 'r':
5819 repo_path = realpath(optarg, NULL);
5820 if (repo_path == NULL)
5821 return got_error_from_errno2("realpath",
5822 optarg);
5823 got_path_strip_trailing_slashes(repo_path);
5824 break;
5825 default:
5826 usage_blame();
5827 /* NOTREACHED */
5831 argc -= optind;
5832 argv += optind;
5834 if (argc == 1)
5835 path = argv[0];
5836 else
5837 usage_blame();
5839 cwd = getcwd(NULL, 0);
5840 if (cwd == NULL) {
5841 error = got_error_from_errno("getcwd");
5842 goto done;
5845 error = got_repo_pack_fds_open(&pack_fds);
5846 if (error != NULL)
5847 goto done;
5849 if (repo_path == NULL) {
5850 error = got_worktree_open(&worktree, cwd,
5851 GOT_WORKTREE_GOT_DIR);
5852 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5853 goto done;
5854 else
5855 error = NULL;
5856 if (worktree) {
5857 repo_path =
5858 strdup(got_worktree_get_repo_path(worktree));
5859 if (repo_path == NULL) {
5860 error = got_error_from_errno("strdup");
5861 if (error)
5862 goto done;
5864 } else {
5865 repo_path = strdup(cwd);
5866 if (repo_path == NULL) {
5867 error = got_error_from_errno("strdup");
5868 goto done;
5873 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
5874 if (error != NULL)
5875 goto done;
5877 if (worktree) {
5878 const char *prefix = got_worktree_get_path_prefix(worktree);
5879 char *p;
5881 error = got_worktree_resolve_path(&p, worktree, path);
5882 if (error)
5883 goto done;
5884 if (asprintf(&in_repo_path, "%s%s%s", prefix,
5885 (p[0] != '\0' && !got_path_is_root_dir(prefix)) ? "/" : "",
5886 p) == -1) {
5887 error = got_error_from_errno("asprintf");
5888 free(p);
5889 goto done;
5891 free(p);
5892 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5893 } else {
5894 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5895 if (error)
5896 goto done;
5897 error = got_repo_map_path(&in_repo_path, repo, path);
5899 if (error)
5900 goto done;
5902 if (commit_id_str == NULL) {
5903 struct got_reference *head_ref;
5904 error = got_ref_open(&head_ref, repo, worktree ?
5905 got_worktree_get_head_ref_name(worktree) : GOT_REF_HEAD, 0);
5906 if (error != NULL)
5907 goto done;
5908 error = got_ref_resolve(&commit_id, repo, head_ref);
5909 got_ref_close(head_ref);
5910 if (error != NULL)
5911 goto done;
5912 } else {
5913 struct got_reflist_head refs;
5915 TAILQ_INIT(&refs);
5916 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
5917 NULL);
5918 if (error)
5919 goto done;
5921 error = got_keyword_to_idstr(&keyword_idstr, commit_id_str,
5922 repo, worktree);
5923 if (error != NULL)
5924 goto done;
5925 if (keyword_idstr != NULL)
5926 commit_id_str = keyword_idstr;
5928 error = got_repo_match_object_id(&commit_id, NULL,
5929 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
5930 got_ref_list_free(&refs);
5931 if (error)
5932 goto done;
5935 if (worktree) {
5936 /* Release work tree lock. */
5937 got_worktree_close(worktree);
5938 worktree = NULL;
5941 error = got_object_open_as_commit(&commit, repo, commit_id);
5942 if (error)
5943 goto done;
5945 error = got_object_resolve_symlinks(&link_target, in_repo_path,
5946 commit, repo);
5947 if (error)
5948 goto done;
5950 error = got_object_id_by_path(&obj_id, repo, commit,
5951 link_target ? link_target : in_repo_path);
5952 if (error)
5953 goto done;
5955 error = got_object_get_type(&obj_type, repo, obj_id);
5956 if (error)
5957 goto done;
5959 if (obj_type != GOT_OBJ_TYPE_BLOB) {
5960 error = got_error_path(link_target ? link_target : in_repo_path,
5961 GOT_ERR_OBJ_TYPE);
5962 goto done;
5965 error = got_object_open_as_blob(&blob, repo, obj_id, 8192, fd1);
5966 if (error)
5967 goto done;
5968 bca.f = got_opentemp();
5969 if (bca.f == NULL) {
5970 error = got_error_from_errno("got_opentemp");
5971 goto done;
5973 error = got_object_blob_dump_to_file(&filesize, &bca.nlines,
5974 &bca.line_offsets, bca.f, blob);
5975 if (error || bca.nlines == 0)
5976 goto done;
5978 /* Don't include \n at EOF in the blame line count. */
5979 if (bca.line_offsets[bca.nlines - 1] == filesize)
5980 bca.nlines--;
5982 bca.lines = calloc(bca.nlines, sizeof(*bca.lines));
5983 if (bca.lines == NULL) {
5984 error = got_error_from_errno("calloc");
5985 goto done;
5987 bca.lineno_cur = 1;
5988 bca.nlines_prec = 0;
5989 i = bca.nlines;
5990 while (i > 0) {
5991 i /= 10;
5992 bca.nlines_prec++;
5994 bca.repo = repo;
5996 fd2 = got_opentempfd();
5997 if (fd2 == -1) {
5998 error = got_error_from_errno("got_opentempfd");
5999 goto done;
6001 fd3 = got_opentempfd();
6002 if (fd3 == -1) {
6003 error = got_error_from_errno("got_opentempfd");
6004 goto done;
6006 f1 = got_opentemp();
6007 if (f1 == NULL) {
6008 error = got_error_from_errno("got_opentemp");
6009 goto done;
6011 f2 = got_opentemp();
6012 if (f2 == NULL) {
6013 error = got_error_from_errno("got_opentemp");
6014 goto done;
6016 error = got_blame(link_target ? link_target : in_repo_path, commit_id,
6017 repo, GOT_DIFF_ALGORITHM_PATIENCE, blame_cb, &bca,
6018 check_cancelled, NULL, fd2, fd3, f1, f2);
6019 done:
6020 free(keyword_idstr);
6021 free(in_repo_path);
6022 free(link_target);
6023 free(repo_path);
6024 free(cwd);
6025 free(commit_id);
6026 free(obj_id);
6027 if (commit)
6028 got_object_commit_close(commit);
6030 if (fd1 != -1 && close(fd1) == -1 && error == NULL)
6031 error = got_error_from_errno("close");
6032 if (fd2 != -1 && close(fd2) == -1 && error == NULL)
6033 error = got_error_from_errno("close");
6034 if (fd3 != -1 && close(fd3) == -1 && error == NULL)
6035 error = got_error_from_errno("close");
6036 if (f1 && fclose(f1) == EOF && error == NULL)
6037 error = got_error_from_errno("fclose");
6038 if (f2 && fclose(f2) == EOF && error == NULL)
6039 error = got_error_from_errno("fclose");
6041 if (blob)
6042 got_object_blob_close(blob);
6043 if (worktree)
6044 got_worktree_close(worktree);
6045 if (repo) {
6046 const struct got_error *close_err = got_repo_close(repo);
6047 if (error == NULL)
6048 error = close_err;
6050 if (pack_fds) {
6051 const struct got_error *pack_err =
6052 got_repo_pack_fds_close(pack_fds);
6053 if (error == NULL)
6054 error = pack_err;
6056 if (bca.lines) {
6057 for (i = 0; i < bca.nlines; i++) {
6058 struct blame_line *bline = &bca.lines[i];
6059 free(bline->id_str);
6060 free(bline->committer);
6062 free(bca.lines);
6064 free(bca.line_offsets);
6065 if (bca.f && fclose(bca.f) == EOF && error == NULL)
6066 error = got_error_from_errno("fclose");
6067 return error;
6070 __dead static void
6071 usage_tree(void)
6073 fprintf(stderr, "usage: %s tree [-iR] [-c commit] [-r repository-path] "
6074 "[path]\n", getprogname());
6075 exit(1);
6078 static const struct got_error *
6079 print_entry(struct got_tree_entry *te, const char *id, const char *path,
6080 const char *root_path, struct got_repository *repo)
6082 const struct got_error *err = NULL;
6083 int is_root_path = (strcmp(path, root_path) == 0);
6084 const char *modestr = "";
6085 mode_t mode = got_tree_entry_get_mode(te);
6086 char *link_target = NULL;
6088 path += strlen(root_path);
6089 while (path[0] == '/')
6090 path++;
6092 if (got_object_tree_entry_is_submodule(te))
6093 modestr = "$";
6094 else if (S_ISLNK(mode)) {
6095 int i;
6097 err = got_tree_entry_get_symlink_target(&link_target, te, repo);
6098 if (err)
6099 return err;
6100 for (i = 0; link_target[i] != '\0'; i++) {
6101 if (!isprint((unsigned char)link_target[i]))
6102 link_target[i] = '?';
6105 modestr = "@";
6107 else if (S_ISDIR(mode))
6108 modestr = "/";
6109 else if (mode & S_IXUSR)
6110 modestr = "*";
6112 printf("%s%s%s%s%s%s%s\n", id ? id : "", path,
6113 is_root_path ? "" : "/", got_tree_entry_get_name(te), modestr,
6114 link_target ? " -> ": "", link_target ? link_target : "");
6116 free(link_target);
6117 return NULL;
6120 static const struct got_error *
6121 print_tree(const char *path, struct got_commit_object *commit,
6122 int show_ids, int recurse, const char *root_path,
6123 struct got_repository *repo)
6125 const struct got_error *err = NULL;
6126 struct got_object_id *tree_id = NULL;
6127 struct got_tree_object *tree = NULL;
6128 int nentries, i;
6130 err = got_object_id_by_path(&tree_id, repo, commit, path);
6131 if (err)
6132 goto done;
6134 err = got_object_open_as_tree(&tree, repo, tree_id);
6135 if (err)
6136 goto done;
6137 nentries = got_object_tree_get_nentries(tree);
6138 for (i = 0; i < nentries; i++) {
6139 struct got_tree_entry *te;
6140 char *id = NULL;
6142 if (sigint_received || sigpipe_received)
6143 break;
6145 te = got_object_tree_get_entry(tree, i);
6146 if (show_ids) {
6147 char *id_str;
6148 err = got_object_id_str(&id_str,
6149 got_tree_entry_get_id(te));
6150 if (err)
6151 goto done;
6152 if (asprintf(&id, "%s ", id_str) == -1) {
6153 err = got_error_from_errno("asprintf");
6154 free(id_str);
6155 goto done;
6157 free(id_str);
6159 err = print_entry(te, id, path, root_path, repo);
6160 free(id);
6161 if (err)
6162 goto done;
6164 if (recurse && S_ISDIR(got_tree_entry_get_mode(te))) {
6165 char *child_path;
6166 if (asprintf(&child_path, "%s%s%s", path,
6167 path[0] == '/' && path[1] == '\0' ? "" : "/",
6168 got_tree_entry_get_name(te)) == -1) {
6169 err = got_error_from_errno("asprintf");
6170 goto done;
6172 err = print_tree(child_path, commit, show_ids, 1,
6173 root_path, repo);
6174 free(child_path);
6175 if (err)
6176 goto done;
6179 done:
6180 if (tree)
6181 got_object_tree_close(tree);
6182 free(tree_id);
6183 return err;
6186 static const struct got_error *
6187 cmd_tree(int argc, char *argv[])
6189 const struct got_error *error;
6190 struct got_repository *repo = NULL;
6191 struct got_worktree *worktree = NULL;
6192 const char *path, *refname = NULL;
6193 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
6194 struct got_object_id *commit_id = NULL;
6195 struct got_commit_object *commit = NULL;
6196 char *commit_id_str = NULL, *keyword_idstr = NULL;
6197 int show_ids = 0, recurse = 0;
6198 int ch;
6199 int *pack_fds = NULL;
6201 #ifndef PROFILE
6202 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
6203 NULL) == -1)
6204 err(1, "pledge");
6205 #endif
6207 while ((ch = getopt(argc, argv, "c:iRr:")) != -1) {
6208 switch (ch) {
6209 case 'c':
6210 commit_id_str = optarg;
6211 break;
6212 case 'i':
6213 show_ids = 1;
6214 break;
6215 case 'R':
6216 recurse = 1;
6217 break;
6218 case 'r':
6219 repo_path = realpath(optarg, NULL);
6220 if (repo_path == NULL)
6221 return got_error_from_errno2("realpath",
6222 optarg);
6223 got_path_strip_trailing_slashes(repo_path);
6224 break;
6225 default:
6226 usage_tree();
6227 /* NOTREACHED */
6231 argc -= optind;
6232 argv += optind;
6234 if (argc == 1)
6235 path = argv[0];
6236 else if (argc > 1)
6237 usage_tree();
6238 else
6239 path = NULL;
6241 cwd = getcwd(NULL, 0);
6242 if (cwd == NULL) {
6243 error = got_error_from_errno("getcwd");
6244 goto done;
6247 error = got_repo_pack_fds_open(&pack_fds);
6248 if (error != NULL)
6249 goto done;
6251 if (repo_path == NULL) {
6252 error = got_worktree_open(&worktree, cwd,
6253 GOT_WORKTREE_GOT_DIR);
6254 if (error && error->code != GOT_ERR_NOT_WORKTREE)
6255 goto done;
6256 else
6257 error = NULL;
6258 if (worktree) {
6259 repo_path =
6260 strdup(got_worktree_get_repo_path(worktree));
6261 if (repo_path == NULL)
6262 error = got_error_from_errno("strdup");
6263 if (error)
6264 goto done;
6265 } else {
6266 repo_path = strdup(cwd);
6267 if (repo_path == NULL) {
6268 error = got_error_from_errno("strdup");
6269 goto done;
6274 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
6275 if (error != NULL)
6276 goto done;
6278 if (worktree) {
6279 const char *prefix = got_worktree_get_path_prefix(worktree);
6280 char *p;
6282 if (path == NULL || got_path_is_root_dir(path))
6283 path = "";
6284 error = got_worktree_resolve_path(&p, worktree, path);
6285 if (error)
6286 goto done;
6287 if (asprintf(&in_repo_path, "%s%s%s", prefix,
6288 (p[0] != '\0' && !got_path_is_root_dir(prefix)) ? "/" : "",
6289 p) == -1) {
6290 error = got_error_from_errno("asprintf");
6291 free(p);
6292 goto done;
6294 free(p);
6295 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
6296 if (error)
6297 goto done;
6298 } else {
6299 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
6300 if (error)
6301 goto done;
6302 if (path == NULL)
6303 path = "/";
6304 error = got_repo_map_path(&in_repo_path, repo, path);
6305 if (error != NULL)
6306 goto done;
6309 if (commit_id_str == NULL) {
6310 struct got_reference *head_ref;
6311 if (worktree)
6312 refname = got_worktree_get_head_ref_name(worktree);
6313 else
6314 refname = GOT_REF_HEAD;
6315 error = got_ref_open(&head_ref, repo, refname, 0);
6316 if (error != NULL)
6317 goto done;
6318 error = got_ref_resolve(&commit_id, repo, head_ref);
6319 got_ref_close(head_ref);
6320 if (error != NULL)
6321 goto done;
6322 } else {
6323 struct got_reflist_head refs;
6325 TAILQ_INIT(&refs);
6326 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
6327 NULL);
6328 if (error)
6329 goto done;
6331 error = got_keyword_to_idstr(&keyword_idstr, commit_id_str,
6332 repo, worktree);
6333 if (error != NULL)
6334 goto done;
6335 if (keyword_idstr != NULL)
6336 commit_id_str = keyword_idstr;
6338 error = got_repo_match_object_id(&commit_id, NULL,
6339 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
6340 got_ref_list_free(&refs);
6341 if (error)
6342 goto done;
6345 if (worktree) {
6346 /* Release work tree lock. */
6347 got_worktree_close(worktree);
6348 worktree = NULL;
6351 error = got_object_open_as_commit(&commit, repo, commit_id);
6352 if (error)
6353 goto done;
6355 error = print_tree(in_repo_path, commit, show_ids, recurse,
6356 in_repo_path, repo);
6357 done:
6358 free(keyword_idstr);
6359 free(in_repo_path);
6360 free(repo_path);
6361 free(cwd);
6362 free(commit_id);
6363 if (commit)
6364 got_object_commit_close(commit);
6365 if (worktree)
6366 got_worktree_close(worktree);
6367 if (repo) {
6368 const struct got_error *close_err = got_repo_close(repo);
6369 if (error == NULL)
6370 error = close_err;
6372 if (pack_fds) {
6373 const struct got_error *pack_err =
6374 got_repo_pack_fds_close(pack_fds);
6375 if (error == NULL)
6376 error = pack_err;
6378 return error;
6381 __dead static void
6382 usage_status(void)
6384 fprintf(stderr, "usage: %s status [-I] [-S status-codes] "
6385 "[-s status-codes] [path ...]\n", getprogname());
6386 exit(1);
6389 struct got_status_arg {
6390 char *status_codes;
6391 int suppress;
6394 static const struct got_error *
6395 print_status(void *arg, unsigned char status, unsigned char staged_status,
6396 const char *path, struct got_object_id *blob_id,
6397 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
6398 int dirfd, const char *de_name)
6400 struct got_status_arg *st = arg;
6402 if (status == staged_status && (status == GOT_STATUS_DELETE))
6403 status = GOT_STATUS_NO_CHANGE;
6404 if (st != NULL && st->status_codes) {
6405 size_t ncodes = strlen(st->status_codes);
6406 int i, j = 0;
6408 for (i = 0; i < ncodes ; i++) {
6409 if (st->suppress) {
6410 if (status == st->status_codes[i] ||
6411 staged_status == st->status_codes[i]) {
6412 j++;
6413 continue;
6415 } else {
6416 if (status == st->status_codes[i] ||
6417 staged_status == st->status_codes[i])
6418 break;
6422 if (st->suppress && j == 0)
6423 goto print;
6425 if (i == ncodes)
6426 return NULL;
6428 print:
6429 printf("%c%c %s\n", status, staged_status, path);
6430 return NULL;
6433 static const struct got_error *
6434 show_operation_in_progress(struct got_worktree *worktree,
6435 struct got_repository *repo)
6437 const struct got_error *err;
6438 char *new_base_branch_name = NULL;
6439 char *branch_name = NULL;
6440 int rebase_in_progress, histedit_in_progress, merge_in_progress;
6442 err = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
6443 if (err)
6444 return err;
6445 if (rebase_in_progress) {
6446 err = got_worktree_rebase_info(&new_base_branch_name,
6447 &branch_name, worktree, repo);
6448 if (err)
6449 return err;
6450 printf("Work tree is rebasing %s onto %s\n",
6451 branch_name, new_base_branch_name);
6454 err = got_worktree_histedit_in_progress(&histedit_in_progress,
6455 worktree);
6456 if (err)
6457 return err;
6458 if (histedit_in_progress) {
6459 err = got_worktree_histedit_info(&branch_name, worktree, repo);
6460 if (err)
6461 return err;
6462 printf("Work tree is editing the history of %s\n", branch_name);
6465 err = got_worktree_merge_in_progress(&merge_in_progress,
6466 worktree, repo);
6467 if (err)
6468 return err;
6469 if (merge_in_progress) {
6470 err = got_worktree_merge_info(&branch_name, worktree,
6471 repo);
6472 if (err)
6473 return err;
6474 printf("Work tree is merging %s into %s\n", branch_name,
6475 got_worktree_get_head_ref_name(worktree));
6478 free(new_base_branch_name);
6479 free(branch_name);
6480 return NULL;
6483 static const struct got_error *
6484 cmd_status(int argc, char *argv[])
6486 const struct got_error *close_err, *error = NULL;
6487 struct got_repository *repo = NULL;
6488 struct got_worktree *worktree = NULL;
6489 struct got_status_arg st;
6490 char *cwd = NULL;
6491 struct got_pathlist_head paths;
6492 int ch, i, no_ignores = 0;
6493 int *pack_fds = NULL;
6495 TAILQ_INIT(&paths);
6497 memset(&st, 0, sizeof(st));
6498 st.status_codes = NULL;
6499 st.suppress = 0;
6501 #ifndef PROFILE
6502 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
6503 NULL) == -1)
6504 err(1, "pledge");
6505 #endif
6507 while ((ch = getopt(argc, argv, "IS:s:")) != -1) {
6508 switch (ch) {
6509 case 'I':
6510 no_ignores = 1;
6511 break;
6512 case 'S':
6513 if (st.status_codes != NULL && st.suppress == 0)
6514 option_conflict('S', 's');
6515 st.suppress = 1;
6516 /* fallthrough */
6517 case 's':
6518 for (i = 0; optarg[i] != '\0'; i++) {
6519 switch (optarg[i]) {
6520 case GOT_STATUS_MODIFY:
6521 case GOT_STATUS_ADD:
6522 case GOT_STATUS_DELETE:
6523 case GOT_STATUS_CONFLICT:
6524 case GOT_STATUS_MISSING:
6525 case GOT_STATUS_OBSTRUCTED:
6526 case GOT_STATUS_UNVERSIONED:
6527 case GOT_STATUS_MODE_CHANGE:
6528 case GOT_STATUS_NONEXISTENT:
6529 break;
6530 default:
6531 errx(1, "invalid status code '%c'",
6532 optarg[i]);
6535 if (ch == 's' && st.suppress)
6536 option_conflict('s', 'S');
6537 st.status_codes = optarg;
6538 break;
6539 default:
6540 usage_status();
6541 /* NOTREACHED */
6545 argc -= optind;
6546 argv += optind;
6548 cwd = getcwd(NULL, 0);
6549 if (cwd == NULL) {
6550 error = got_error_from_errno("getcwd");
6551 goto done;
6554 error = got_repo_pack_fds_open(&pack_fds);
6555 if (error != NULL)
6556 goto done;
6558 error = got_worktree_open(&worktree, cwd,
6559 GOT_WORKTREE_GOT_DIR);
6560 if (error) {
6561 if (error->code == GOT_ERR_NOT_WORKTREE)
6562 error = wrap_not_worktree_error(error, "status", cwd);
6563 goto done;
6566 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
6567 NULL, pack_fds);
6568 if (error != NULL)
6569 goto done;
6571 error = apply_unveil(got_repo_get_path(repo), 1,
6572 got_worktree_get_root_path(worktree));
6573 if (error)
6574 goto done;
6576 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
6577 if (error)
6578 goto done;
6580 error = got_worktree_status(worktree, &paths, repo, no_ignores,
6581 print_status, &st, check_cancelled, NULL);
6582 if (error)
6583 goto done;
6585 error = show_operation_in_progress(worktree, repo);
6586 done:
6587 if (pack_fds) {
6588 const struct got_error *pack_err =
6589 got_repo_pack_fds_close(pack_fds);
6590 if (error == NULL)
6591 error = pack_err;
6593 if (repo) {
6594 close_err = got_repo_close(repo);
6595 if (error == NULL)
6596 error = close_err;
6598 if (worktree != NULL) {
6599 close_err = got_worktree_close(worktree);
6600 if (error == NULL)
6601 error = close_err;
6604 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
6605 free(cwd);
6606 return error;
6609 __dead static void
6610 usage_ref(void)
6612 fprintf(stderr, "usage: %s ref [-dlt] [-c object] [-r repository-path] "
6613 "[-s reference] [name]\n", getprogname());
6614 exit(1);
6617 static const struct got_error *
6618 list_refs(struct got_repository *repo, const char *refname, int sort_by_time)
6620 static const struct got_error *err = NULL;
6621 struct got_reflist_head refs;
6622 struct got_reflist_entry *re;
6624 TAILQ_INIT(&refs);
6625 err = got_ref_list(&refs, repo, refname, sort_by_time ?
6626 got_ref_cmp_by_commit_timestamp_descending : got_ref_cmp_by_name,
6627 repo);
6628 if (err)
6629 return err;
6631 TAILQ_FOREACH(re, &refs, entry) {
6632 char *refstr;
6633 refstr = got_ref_to_str(re->ref);
6634 if (refstr == NULL) {
6635 err = got_error_from_errno("got_ref_to_str");
6636 break;
6638 printf("%s: %s\n", got_ref_get_name(re->ref), refstr);
6639 free(refstr);
6642 got_ref_list_free(&refs);
6643 return err;
6646 static const struct got_error *
6647 delete_ref_by_name(struct got_repository *repo, const char *refname)
6649 const struct got_error *err;
6650 struct got_reference *ref;
6652 err = got_ref_open(&ref, repo, refname, 0);
6653 if (err)
6654 return err;
6656 err = delete_ref(repo, ref);
6657 got_ref_close(ref);
6658 return err;
6661 static const struct got_error *
6662 add_ref(struct got_repository *repo, const char *refname, const char *target)
6664 const struct got_error *err = NULL;
6665 struct got_object_id *id = NULL;
6666 struct got_reference *ref = NULL;
6667 struct got_reflist_head refs;
6670 * Don't let the user create a reference name with a leading '-'.
6671 * While technically a valid reference name, this case is usually
6672 * an unintended typo.
6674 if (refname[0] == '-')
6675 return got_error_path(refname, GOT_ERR_REF_NAME_MINUS);
6677 TAILQ_INIT(&refs);
6678 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
6679 if (err)
6680 goto done;
6681 err = got_repo_match_object_id(&id, NULL, target, GOT_OBJ_TYPE_ANY,
6682 &refs, repo);
6683 got_ref_list_free(&refs);
6684 if (err)
6685 goto done;
6687 err = got_ref_alloc(&ref, refname, id);
6688 if (err)
6689 goto done;
6691 err = got_ref_write(ref, repo);
6692 done:
6693 if (ref)
6694 got_ref_close(ref);
6695 free(id);
6696 return err;
6699 static const struct got_error *
6700 add_symref(struct got_repository *repo, const char *refname, const char *target)
6702 const struct got_error *err = NULL;
6703 struct got_reference *ref = NULL;
6704 struct got_reference *target_ref = NULL;
6707 * Don't let the user create a reference name with a leading '-'.
6708 * While technically a valid reference name, this case is usually
6709 * an unintended typo.
6711 if (refname[0] == '-')
6712 return got_error_path(refname, GOT_ERR_REF_NAME_MINUS);
6714 err = got_ref_open(&target_ref, repo, target, 0);
6715 if (err)
6716 return err;
6718 err = got_ref_alloc_symref(&ref, refname, target_ref);
6719 if (err)
6720 goto done;
6722 err = got_ref_write(ref, repo);
6723 done:
6724 if (target_ref)
6725 got_ref_close(target_ref);
6726 if (ref)
6727 got_ref_close(ref);
6728 return err;
6731 static const struct got_error *
6732 cmd_ref(int argc, char *argv[])
6734 const struct got_error *error = NULL;
6735 struct got_repository *repo = NULL;
6736 struct got_worktree *worktree = NULL;
6737 char *cwd = NULL, *repo_path = NULL;
6738 int ch, do_list = 0, do_delete = 0, sort_by_time = 0;
6739 const char *obj_arg = NULL, *symref_target= NULL;
6740 char *refname = NULL, *keyword_idstr = NULL;
6741 int *pack_fds = NULL;
6743 #ifndef PROFILE
6744 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
6745 "sendfd unveil", NULL) == -1)
6746 err(1, "pledge");
6747 #endif
6749 while ((ch = getopt(argc, argv, "c:dlr:s:t")) != -1) {
6750 switch (ch) {
6751 case 'c':
6752 obj_arg = optarg;
6753 break;
6754 case 'd':
6755 do_delete = 1;
6756 break;
6757 case 'l':
6758 do_list = 1;
6759 break;
6760 case 'r':
6761 repo_path = realpath(optarg, NULL);
6762 if (repo_path == NULL)
6763 return got_error_from_errno2("realpath",
6764 optarg);
6765 got_path_strip_trailing_slashes(repo_path);
6766 break;
6767 case 's':
6768 symref_target = optarg;
6769 break;
6770 case 't':
6771 sort_by_time = 1;
6772 break;
6773 default:
6774 usage_ref();
6775 /* NOTREACHED */
6779 if (obj_arg && do_list)
6780 option_conflict('c', 'l');
6781 if (obj_arg && do_delete)
6782 option_conflict('c', 'd');
6783 if (obj_arg && symref_target)
6784 option_conflict('c', 's');
6785 if (symref_target && do_delete)
6786 option_conflict('s', 'd');
6787 if (symref_target && do_list)
6788 option_conflict('s', 'l');
6789 if (do_delete && do_list)
6790 option_conflict('d', 'l');
6791 if (sort_by_time && !do_list)
6792 errx(1, "-t option requires -l option");
6794 argc -= optind;
6795 argv += optind;
6797 if (do_list) {
6798 if (argc != 0 && argc != 1)
6799 usage_ref();
6800 if (argc == 1) {
6801 refname = strdup(argv[0]);
6802 if (refname == NULL) {
6803 error = got_error_from_errno("strdup");
6804 goto done;
6807 } else {
6808 if (argc != 1)
6809 usage_ref();
6810 refname = strdup(argv[0]);
6811 if (refname == NULL) {
6812 error = got_error_from_errno("strdup");
6813 goto done;
6817 if (refname)
6818 got_path_strip_trailing_slashes(refname);
6820 cwd = getcwd(NULL, 0);
6821 if (cwd == NULL) {
6822 error = got_error_from_errno("getcwd");
6823 goto done;
6826 error = got_repo_pack_fds_open(&pack_fds);
6827 if (error != NULL)
6828 goto done;
6830 if (repo_path == NULL) {
6831 error = got_worktree_open(&worktree, cwd,
6832 GOT_WORKTREE_GOT_DIR);
6833 if (error && error->code != GOT_ERR_NOT_WORKTREE)
6834 goto done;
6835 else
6836 error = NULL;
6837 if (worktree) {
6838 repo_path =
6839 strdup(got_worktree_get_repo_path(worktree));
6840 if (repo_path == NULL)
6841 error = got_error_from_errno("strdup");
6842 if (error)
6843 goto done;
6844 } else {
6845 repo_path = strdup(cwd);
6846 if (repo_path == NULL) {
6847 error = got_error_from_errno("strdup");
6848 goto done;
6853 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
6854 if (error != NULL)
6855 goto done;
6857 #ifndef PROFILE
6858 if (do_list) {
6859 /* Remove "cpath" promise. */
6860 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
6861 NULL) == -1)
6862 err(1, "pledge");
6864 #endif
6866 error = apply_unveil(got_repo_get_path(repo), do_list,
6867 worktree ? got_worktree_get_root_path(worktree) : NULL);
6868 if (error)
6869 goto done;
6871 if (do_list)
6872 error = list_refs(repo, refname, sort_by_time);
6873 else if (do_delete)
6874 error = delete_ref_by_name(repo, refname);
6875 else if (symref_target)
6876 error = add_symref(repo, refname, symref_target);
6877 else {
6878 if (obj_arg == NULL)
6879 usage_ref();
6881 error = got_keyword_to_idstr(&keyword_idstr, obj_arg,
6882 repo, worktree);
6883 if (error != NULL)
6884 goto done;
6885 if (keyword_idstr != NULL)
6886 obj_arg = keyword_idstr;
6888 error = add_ref(repo, refname, obj_arg);
6890 done:
6891 free(refname);
6892 if (repo) {
6893 const struct got_error *close_err = got_repo_close(repo);
6894 if (error == NULL)
6895 error = close_err;
6897 if (worktree)
6898 got_worktree_close(worktree);
6899 if (pack_fds) {
6900 const struct got_error *pack_err =
6901 got_repo_pack_fds_close(pack_fds);
6902 if (error == NULL)
6903 error = pack_err;
6905 free(cwd);
6906 free(repo_path);
6907 free(keyword_idstr);
6908 return error;
6911 __dead static void
6912 usage_branch(void)
6914 fprintf(stderr, "usage: %s branch [-lnt] [-c commit] [-d name] "
6915 "[-r repository-path] [name]\n", getprogname());
6916 exit(1);
6919 static const struct got_error *
6920 list_branch(struct got_repository *repo, struct got_worktree *worktree,
6921 struct got_reference *ref)
6923 const struct got_error *err = NULL;
6924 const char *refname;
6925 char *refstr;
6926 char marker = ' ';
6928 refname = got_ref_get_name(ref);
6929 if (worktree && strcmp(refname,
6930 got_worktree_get_head_ref_name(worktree)) == 0) {
6931 err = got_worktree_get_state(&marker, repo, worktree,
6932 check_cancelled, NULL);
6933 if (err != NULL)
6934 return err;
6937 if (strncmp(refname, "refs/heads/", 11) == 0)
6938 refname += 11;
6939 if (strncmp(refname, "refs/got/worktree/", 18) == 0)
6940 refname += 18;
6941 if (strncmp(refname, "refs/remotes/", 13) == 0)
6942 refname += 13;
6944 refstr = got_ref_to_str(ref);
6945 if (refstr == NULL)
6946 return got_error_from_errno("got_ref_to_str");
6948 printf("%c %s: %s\n", marker, refname, refstr);
6949 free(refstr);
6950 return NULL;
6953 static const struct got_error *
6954 show_current_branch(struct got_repository *repo, struct got_worktree *worktree)
6956 const char *refname;
6958 if (worktree == NULL)
6959 return got_error(GOT_ERR_NOT_WORKTREE);
6961 refname = got_worktree_get_head_ref_name(worktree);
6963 if (strncmp(refname, "refs/heads/", 11) == 0)
6964 refname += 11;
6965 if (strncmp(refname, "refs/got/worktree/", 18) == 0)
6966 refname += 18;
6968 printf("%s\n", refname);
6970 return NULL;
6973 static const struct got_error *
6974 list_branches(struct got_repository *repo, struct got_worktree *worktree,
6975 int sort_by_time)
6977 static const struct got_error *err = NULL;
6978 struct got_reflist_head refs;
6979 struct got_reflist_entry *re;
6980 struct got_reference *temp_ref = NULL;
6981 int rebase_in_progress, histedit_in_progress;
6983 TAILQ_INIT(&refs);
6985 if (worktree) {
6986 err = got_worktree_rebase_in_progress(&rebase_in_progress,
6987 worktree);
6988 if (err)
6989 return err;
6991 err = got_worktree_histedit_in_progress(&histedit_in_progress,
6992 worktree);
6993 if (err)
6994 return err;
6996 if (rebase_in_progress || histedit_in_progress) {
6997 err = got_ref_open(&temp_ref, repo,
6998 got_worktree_get_head_ref_name(worktree), 0);
6999 if (err)
7000 return err;
7001 list_branch(repo, worktree, temp_ref);
7002 got_ref_close(temp_ref);
7006 err = got_ref_list(&refs, repo, "refs/heads", sort_by_time ?
7007 got_ref_cmp_by_commit_timestamp_descending : got_ref_cmp_by_name,
7008 repo);
7009 if (err)
7010 return err;
7012 TAILQ_FOREACH(re, &refs, entry)
7013 list_branch(repo, worktree, re->ref);
7015 got_ref_list_free(&refs);
7017 err = got_ref_list(&refs, repo, "refs/remotes", sort_by_time ?
7018 got_ref_cmp_by_commit_timestamp_descending : got_ref_cmp_by_name,
7019 repo);
7020 if (err)
7021 return err;
7023 TAILQ_FOREACH(re, &refs, entry)
7024 list_branch(repo, worktree, re->ref);
7026 got_ref_list_free(&refs);
7028 return NULL;
7031 static const struct got_error *
7032 delete_branch(struct got_repository *repo, struct got_worktree *worktree,
7033 const char *branch_name)
7035 const struct got_error *err = NULL;
7036 struct got_reference *ref = NULL;
7037 char *refname, *remote_refname = NULL;
7039 if (strncmp(branch_name, "refs/", 5) == 0)
7040 branch_name += 5;
7041 if (strncmp(branch_name, "heads/", 6) == 0)
7042 branch_name += 6;
7043 else if (strncmp(branch_name, "remotes/", 8) == 0)
7044 branch_name += 8;
7046 if (asprintf(&refname, "refs/heads/%s", branch_name) == -1)
7047 return got_error_from_errno("asprintf");
7049 if (asprintf(&remote_refname, "refs/remotes/%s",
7050 branch_name) == -1) {
7051 err = got_error_from_errno("asprintf");
7052 goto done;
7055 err = got_ref_open(&ref, repo, refname, 0);
7056 if (err) {
7057 const struct got_error *err2;
7058 if (err->code != GOT_ERR_NOT_REF)
7059 goto done;
7061 * Keep 'err' intact such that if neither branch exists
7062 * we report "refs/heads" rather than "refs/remotes" in
7063 * our error message.
7065 err2 = got_ref_open(&ref, repo, remote_refname, 0);
7066 if (err2)
7067 goto done;
7068 err = NULL;
7071 if (worktree &&
7072 strcmp(got_worktree_get_head_ref_name(worktree),
7073 got_ref_get_name(ref)) == 0) {
7074 err = got_error_msg(GOT_ERR_SAME_BRANCH,
7075 "will not delete this work tree's current branch");
7076 goto done;
7079 err = delete_ref(repo, ref);
7080 done:
7081 if (ref)
7082 got_ref_close(ref);
7083 free(refname);
7084 free(remote_refname);
7085 return err;
7088 static const struct got_error *
7089 add_branch(struct got_repository *repo, const char *branch_name,
7090 struct got_object_id *base_commit_id)
7092 const struct got_error *err = NULL;
7093 struct got_reference *ref = NULL;
7094 char *refname = NULL;
7097 * Don't let the user create a branch name with a leading '-'.
7098 * While technically a valid reference name, this case is usually
7099 * an unintended typo.
7101 if (branch_name[0] == '-')
7102 return got_error_path(branch_name, GOT_ERR_REF_NAME_MINUS);
7104 if (strncmp(branch_name, "refs/heads/", 11) == 0)
7105 branch_name += 11;
7107 if (asprintf(&refname, "refs/heads/%s", branch_name) == -1) {
7108 err = got_error_from_errno("asprintf");
7109 goto done;
7112 err = got_ref_open(&ref, repo, refname, 0);
7113 if (err == NULL) {
7114 err = got_error(GOT_ERR_BRANCH_EXISTS);
7115 goto done;
7116 } else if (err->code != GOT_ERR_NOT_REF)
7117 goto done;
7119 err = got_ref_alloc(&ref, refname, base_commit_id);
7120 if (err)
7121 goto done;
7123 err = got_ref_write(ref, repo);
7124 done:
7125 if (ref)
7126 got_ref_close(ref);
7127 free(refname);
7128 return err;
7131 static const struct got_error *
7132 cmd_branch(int argc, char *argv[])
7134 const struct got_error *error = NULL;
7135 struct got_repository *repo = NULL;
7136 struct got_worktree *worktree = NULL;
7137 char *cwd = NULL, *repo_path = NULL;
7138 int ch, do_list = 0, do_show = 0, do_update = 1, sort_by_time = 0;
7139 const char *delref = NULL, *commit_id_arg = NULL;
7140 struct got_reference *ref = NULL;
7141 struct got_pathlist_head paths;
7142 struct got_object_id *commit_id = NULL;
7143 char *commit_id_str = NULL, *keyword_idstr = NULL;;
7144 int *pack_fds = NULL;
7146 TAILQ_INIT(&paths);
7148 #ifndef PROFILE
7149 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
7150 "sendfd unveil", NULL) == -1)
7151 err(1, "pledge");
7152 #endif
7154 while ((ch = getopt(argc, argv, "c:d:lnr:t")) != -1) {
7155 switch (ch) {
7156 case 'c':
7157 commit_id_arg = optarg;
7158 break;
7159 case 'd':
7160 delref = optarg;
7161 break;
7162 case 'l':
7163 do_list = 1;
7164 break;
7165 case 'n':
7166 do_update = 0;
7167 break;
7168 case 'r':
7169 repo_path = realpath(optarg, NULL);
7170 if (repo_path == NULL)
7171 return got_error_from_errno2("realpath",
7172 optarg);
7173 got_path_strip_trailing_slashes(repo_path);
7174 break;
7175 case 't':
7176 sort_by_time = 1;
7177 break;
7178 default:
7179 usage_branch();
7180 /* NOTREACHED */
7184 if (do_list && delref)
7185 option_conflict('l', 'd');
7186 if (sort_by_time && !do_list)
7187 errx(1, "-t option requires -l option");
7189 argc -= optind;
7190 argv += optind;
7192 if (!do_list && !delref && argc == 0)
7193 do_show = 1;
7195 if ((do_list || delref || do_show) && commit_id_arg != NULL)
7196 errx(1, "-c option can only be used when creating a branch");
7198 if (do_list || delref) {
7199 if (argc > 0)
7200 usage_branch();
7201 } else if (!do_show && argc != 1)
7202 usage_branch();
7204 cwd = getcwd(NULL, 0);
7205 if (cwd == NULL) {
7206 error = got_error_from_errno("getcwd");
7207 goto done;
7210 error = got_repo_pack_fds_open(&pack_fds);
7211 if (error != NULL)
7212 goto done;
7214 if (repo_path == NULL) {
7215 error = got_worktree_open(&worktree, cwd,
7216 GOT_WORKTREE_GOT_DIR);
7217 if (error && error->code != GOT_ERR_NOT_WORKTREE)
7218 goto done;
7219 else
7220 error = NULL;
7221 if (worktree) {
7222 repo_path =
7223 strdup(got_worktree_get_repo_path(worktree));
7224 if (repo_path == NULL)
7225 error = got_error_from_errno("strdup");
7226 if (error)
7227 goto done;
7228 } else {
7229 repo_path = strdup(cwd);
7230 if (repo_path == NULL) {
7231 error = got_error_from_errno("strdup");
7232 goto done;
7237 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
7238 if (error != NULL)
7239 goto done;
7241 #ifndef PROFILE
7242 if (do_list || do_show) {
7243 /* Remove "cpath" promise. */
7244 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
7245 NULL) == -1)
7246 err(1, "pledge");
7248 #endif
7250 error = apply_unveil(got_repo_get_path(repo), do_list,
7251 worktree ? got_worktree_get_root_path(worktree) : NULL);
7252 if (error)
7253 goto done;
7255 if (do_show)
7256 error = show_current_branch(repo, worktree);
7257 else if (do_list)
7258 error = list_branches(repo, worktree, sort_by_time);
7259 else if (delref)
7260 error = delete_branch(repo, worktree, delref);
7261 else {
7262 struct got_reflist_head refs;
7263 TAILQ_INIT(&refs);
7264 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
7265 NULL);
7266 if (error)
7267 goto done;
7268 if (commit_id_arg == NULL)
7269 commit_id_arg = worktree ?
7270 got_worktree_get_head_ref_name(worktree) :
7271 GOT_REF_HEAD;
7272 else {
7273 error = got_keyword_to_idstr(&keyword_idstr,
7274 commit_id_arg, repo, worktree);
7275 if (error != NULL)
7276 goto done;
7277 if (keyword_idstr != NULL)
7278 commit_id_arg = keyword_idstr;
7280 error = got_repo_match_object_id(&commit_id, NULL,
7281 commit_id_arg, GOT_OBJ_TYPE_COMMIT, &refs, repo);
7282 got_ref_list_free(&refs);
7283 if (error)
7284 goto done;
7285 error = add_branch(repo, argv[0], commit_id);
7286 if (error)
7287 goto done;
7288 if (worktree && do_update) {
7289 struct got_update_progress_arg upa;
7290 char *branch_refname = NULL;
7292 error = got_object_id_str(&commit_id_str, commit_id);
7293 if (error)
7294 goto done;
7295 error = get_worktree_paths_from_argv(&paths, 0, NULL,
7296 worktree);
7297 if (error)
7298 goto done;
7299 if (asprintf(&branch_refname, "refs/heads/%s", argv[0])
7300 == -1) {
7301 error = got_error_from_errno("asprintf");
7302 goto done;
7304 error = got_ref_open(&ref, repo, branch_refname, 0);
7305 free(branch_refname);
7306 if (error)
7307 goto done;
7308 error = switch_head_ref(ref, commit_id, worktree,
7309 repo);
7310 if (error)
7311 goto done;
7312 error = got_worktree_set_base_commit_id(worktree, repo,
7313 commit_id);
7314 if (error)
7315 goto done;
7316 memset(&upa, 0, sizeof(upa));
7317 error = got_worktree_checkout_files(worktree, &paths,
7318 repo, update_progress, &upa, check_cancelled,
7319 NULL);
7320 if (error)
7321 goto done;
7322 if (upa.did_something) {
7323 printf("Updated to %s: %s\n",
7324 got_worktree_get_head_ref_name(worktree),
7325 commit_id_str);
7327 print_update_progress_stats(&upa);
7330 done:
7331 free(keyword_idstr);
7332 if (ref)
7333 got_ref_close(ref);
7334 if (repo) {
7335 const struct got_error *close_err = got_repo_close(repo);
7336 if (error == NULL)
7337 error = close_err;
7339 if (worktree)
7340 got_worktree_close(worktree);
7341 if (pack_fds) {
7342 const struct got_error *pack_err =
7343 got_repo_pack_fds_close(pack_fds);
7344 if (error == NULL)
7345 error = pack_err;
7347 free(cwd);
7348 free(repo_path);
7349 free(commit_id);
7350 free(commit_id_str);
7351 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
7352 return error;
7356 __dead static void
7357 usage_tag(void)
7359 fprintf(stderr, "usage: %s tag [-lVv] [-c commit] [-m message] "
7360 "[-r repository-path] [-s signer-id] name\n", getprogname());
7361 exit(1);
7364 #if 0
7365 static const struct got_error *
7366 sort_tags(struct got_reflist_head *sorted, struct got_reflist_head *tags)
7368 const struct got_error *err = NULL;
7369 struct got_reflist_entry *re, *se, *new;
7370 struct got_object_id *re_id, *se_id;
7371 struct got_tag_object *re_tag, *se_tag;
7372 time_t re_time, se_time;
7374 STAILQ_FOREACH(re, tags, entry) {
7375 se = STAILQ_FIRST(sorted);
7376 if (se == NULL) {
7377 err = got_reflist_entry_dup(&new, re);
7378 if (err)
7379 return err;
7380 STAILQ_INSERT_HEAD(sorted, new, entry);
7381 continue;
7382 } else {
7383 err = got_ref_resolve(&re_id, repo, re->ref);
7384 if (err)
7385 break;
7386 err = got_object_open_as_tag(&re_tag, repo, re_id);
7387 free(re_id);
7388 if (err)
7389 break;
7390 re_time = got_object_tag_get_tagger_time(re_tag);
7391 got_object_tag_close(re_tag);
7394 while (se) {
7395 err = got_ref_resolve(&se_id, repo, re->ref);
7396 if (err)
7397 break;
7398 err = got_object_open_as_tag(&se_tag, repo, se_id);
7399 free(se_id);
7400 if (err)
7401 break;
7402 se_time = got_object_tag_get_tagger_time(se_tag);
7403 got_object_tag_close(se_tag);
7405 if (se_time > re_time) {
7406 err = got_reflist_entry_dup(&new, re);
7407 if (err)
7408 return err;
7409 STAILQ_INSERT_AFTER(sorted, se, new, entry);
7410 break;
7412 se = STAILQ_NEXT(se, entry);
7413 continue;
7416 done:
7417 return err;
7419 #endif
7421 static const struct got_error *
7422 get_tag_refname(char **refname, const char *tag_name)
7424 const struct got_error *err;
7426 if (strncmp("refs/tags/", tag_name, 10) == 0) {
7427 *refname = strdup(tag_name);
7428 if (*refname == NULL)
7429 return got_error_from_errno("strdup");
7430 } else if (asprintf(refname, "refs/tags/%s", tag_name) == -1) {
7431 err = got_error_from_errno("asprintf");
7432 *refname = NULL;
7433 return err;
7436 return NULL;
7439 static const struct got_error *
7440 list_tags(struct got_repository *repo, const char *tag_name, int verify_tags,
7441 const char *allowed_signers, const char *revoked_signers, int verbosity)
7443 static const struct got_error *err = NULL;
7444 struct got_reflist_head refs;
7445 struct got_reflist_entry *re;
7446 char *wanted_refname = NULL;
7447 int bad_sigs = 0;
7449 TAILQ_INIT(&refs);
7451 err = got_ref_list(&refs, repo, "refs/tags", got_ref_cmp_tags, repo);
7452 if (err)
7453 return err;
7455 if (tag_name) {
7456 struct got_reference *ref;
7457 err = get_tag_refname(&wanted_refname, tag_name);
7458 if (err)
7459 goto done;
7460 /* Wanted tag reference should exist. */
7461 err = got_ref_open(&ref, repo, wanted_refname, 0);
7462 if (err)
7463 goto done;
7464 got_ref_close(ref);
7467 TAILQ_FOREACH(re, &refs, entry) {
7468 const char *refname;
7469 char *refstr, *tagmsg0, *tagmsg, *line, *id_str, *datestr;
7470 char datebuf[26];
7471 const char *tagger, *ssh_sig = NULL;
7472 char *sig_msg = NULL;
7473 time_t tagger_time;
7474 struct got_object_id *id;
7475 struct got_tag_object *tag;
7476 struct got_commit_object *commit = NULL;
7478 refname = got_ref_get_name(re->ref);
7479 if (strncmp(refname, "refs/tags/", 10) != 0 ||
7480 (wanted_refname && strcmp(refname, wanted_refname) != 0))
7481 continue;
7482 refname += 10;
7483 refstr = got_ref_to_str(re->ref);
7484 if (refstr == NULL) {
7485 err = got_error_from_errno("got_ref_to_str");
7486 break;
7489 err = got_ref_resolve(&id, repo, re->ref);
7490 if (err)
7491 break;
7492 err = got_object_open_as_tag(&tag, repo, id);
7493 if (err) {
7494 if (err->code != GOT_ERR_OBJ_TYPE) {
7495 free(id);
7496 break;
7498 /* "lightweight" tag */
7499 err = got_object_open_as_commit(&commit, repo, id);
7500 if (err) {
7501 free(id);
7502 break;
7504 tagger = got_object_commit_get_committer(commit);
7505 tagger_time =
7506 got_object_commit_get_committer_time(commit);
7507 err = got_object_id_str(&id_str, id);
7508 free(id);
7509 if (err)
7510 break;
7511 } else {
7512 free(id);
7513 tagger = got_object_tag_get_tagger(tag);
7514 tagger_time = got_object_tag_get_tagger_time(tag);
7515 err = got_object_id_str(&id_str,
7516 got_object_tag_get_object_id(tag));
7517 if (err)
7518 break;
7521 if (tag && verify_tags) {
7522 ssh_sig = got_sigs_get_tagmsg_ssh_signature(
7523 got_object_tag_get_message(tag));
7524 if (ssh_sig && allowed_signers == NULL) {
7525 err = got_error_msg(
7526 GOT_ERR_VERIFY_TAG_SIGNATURE,
7527 "SSH signature verification requires "
7528 "setting allowed_signers in "
7529 "got.conf(5)");
7530 break;
7534 printf("%stag %s %s\n", GOT_COMMIT_SEP_STR, refname, refstr);
7535 free(refstr);
7536 printf("from: %s\n", tagger);
7537 datestr = get_datestr(&tagger_time, datebuf);
7538 if (datestr)
7539 printf("date: %s UTC\n", datestr);
7540 if (commit)
7541 printf("object: %s %s\n", GOT_OBJ_LABEL_COMMIT, id_str);
7542 else {
7543 switch (got_object_tag_get_object_type(tag)) {
7544 case GOT_OBJ_TYPE_BLOB:
7545 printf("object: %s %s\n", GOT_OBJ_LABEL_BLOB,
7546 id_str);
7547 break;
7548 case GOT_OBJ_TYPE_TREE:
7549 printf("object: %s %s\n", GOT_OBJ_LABEL_TREE,
7550 id_str);
7551 break;
7552 case GOT_OBJ_TYPE_COMMIT:
7553 printf("object: %s %s\n", GOT_OBJ_LABEL_COMMIT,
7554 id_str);
7555 break;
7556 case GOT_OBJ_TYPE_TAG:
7557 printf("object: %s %s\n", GOT_OBJ_LABEL_TAG,
7558 id_str);
7559 break;
7560 default:
7561 break;
7564 free(id_str);
7566 if (ssh_sig) {
7567 err = got_sigs_verify_tag_ssh(&sig_msg, tag, ssh_sig,
7568 allowed_signers, revoked_signers, verbosity);
7569 if (err && err->code == GOT_ERR_BAD_TAG_SIGNATURE)
7570 bad_sigs = 1;
7571 else if (err)
7572 break;
7573 printf("signature: %s", sig_msg);
7574 free(sig_msg);
7575 sig_msg = NULL;
7578 if (commit) {
7579 err = got_object_commit_get_logmsg(&tagmsg0, commit);
7580 if (err)
7581 break;
7582 got_object_commit_close(commit);
7583 } else {
7584 tagmsg0 = strdup(got_object_tag_get_message(tag));
7585 got_object_tag_close(tag);
7586 if (tagmsg0 == NULL) {
7587 err = got_error_from_errno("strdup");
7588 break;
7592 tagmsg = tagmsg0;
7593 do {
7594 line = strsep(&tagmsg, "\n");
7595 if (line)
7596 printf(" %s\n", line);
7597 } while (line);
7598 free(tagmsg0);
7600 done:
7601 got_ref_list_free(&refs);
7602 free(wanted_refname);
7604 if (err == NULL && bad_sigs)
7605 err = got_error(GOT_ERR_BAD_TAG_SIGNATURE);
7606 return err;
7609 static const struct got_error *
7610 get_tag_message(char **tagmsg, char **tagmsg_path, const char *commit_id_str,
7611 const char *tag_name, const char *editor, const char *repo_path)
7613 const struct got_error *err = NULL;
7614 char *template = NULL, *initial_content = NULL;
7615 int initial_content_len;
7616 int fd = -1;
7618 if (asprintf(&template, GOT_TMPDIR_STR "/got-tagmsg") == -1) {
7619 err = got_error_from_errno("asprintf");
7620 goto done;
7623 initial_content_len = asprintf(&initial_content,
7624 "\n# tagging commit %s as %s\n",
7625 commit_id_str, tag_name);
7626 if (initial_content_len == -1) {
7627 err = got_error_from_errno("asprintf");
7628 goto done;
7631 err = got_opentemp_named_fd(tagmsg_path, &fd, template, "");
7632 if (err)
7633 goto done;
7635 if (write(fd, initial_content, initial_content_len) == -1) {
7636 err = got_error_from_errno2("write", *tagmsg_path);
7637 goto done;
7639 if (close(fd) == -1) {
7640 err = got_error_from_errno2("close", *tagmsg_path);
7641 goto done;
7643 fd = -1;
7645 err = edit_logmsg(tagmsg, editor, *tagmsg_path, initial_content,
7646 initial_content_len, 1);
7647 done:
7648 free(initial_content);
7649 free(template);
7651 if (fd != -1 && close(fd) == -1 && err == NULL)
7652 err = got_error_from_errno2("close", *tagmsg_path);
7654 if (err) {
7655 free(*tagmsg);
7656 *tagmsg = NULL;
7658 return err;
7661 static const struct got_error *
7662 add_tag(struct got_repository *repo, const char *tagger,
7663 const char *tag_name, const char *commit_arg, const char *tagmsg_arg,
7664 const char *signer_id, const char *editor, int verbosity)
7666 const struct got_error *err = NULL;
7667 struct got_object_id *commit_id = NULL, *tag_id = NULL;
7668 char *label = NULL, *commit_id_str = NULL;
7669 struct got_reference *ref = NULL;
7670 char *refname = NULL, *tagmsg = NULL;
7671 char *tagmsg_path = NULL, *tag_id_str = NULL;
7672 int preserve_tagmsg = 0;
7673 struct got_reflist_head refs;
7675 TAILQ_INIT(&refs);
7678 * Don't let the user create a tag name with a leading '-'.
7679 * While technically a valid reference name, this case is usually
7680 * an unintended typo.
7682 if (tag_name[0] == '-')
7683 return got_error_path(tag_name, GOT_ERR_REF_NAME_MINUS);
7685 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
7686 if (err)
7687 goto done;
7689 err = got_repo_match_object_id(&commit_id, &label, commit_arg,
7690 GOT_OBJ_TYPE_COMMIT, &refs, repo);
7691 if (err)
7692 goto done;
7694 err = got_object_id_str(&commit_id_str, commit_id);
7695 if (err)
7696 goto done;
7698 err = get_tag_refname(&refname, tag_name);
7699 if (err)
7700 goto done;
7701 if (strncmp("refs/tags/", tag_name, 10) == 0)
7702 tag_name += 10;
7704 err = got_ref_open(&ref, repo, refname, 0);
7705 if (err == NULL) {
7706 err = got_error(GOT_ERR_TAG_EXISTS);
7707 goto done;
7708 } else if (err->code != GOT_ERR_NOT_REF)
7709 goto done;
7711 if (tagmsg_arg == NULL) {
7712 err = get_tag_message(&tagmsg, &tagmsg_path, commit_id_str,
7713 tag_name, editor, got_repo_get_path(repo));
7714 if (err) {
7715 if (err->code != GOT_ERR_COMMIT_MSG_EMPTY &&
7716 tagmsg_path != NULL)
7717 preserve_tagmsg = 1;
7718 goto done;
7722 err = got_object_tag_create(&tag_id, tag_name, commit_id,
7723 tagger, time(NULL), tagmsg ? tagmsg : tagmsg_arg, signer_id, repo,
7724 verbosity);
7725 if (err) {
7726 if (tagmsg_path)
7727 preserve_tagmsg = 1;
7728 goto done;
7731 err = got_ref_alloc(&ref, refname, tag_id);
7732 if (err) {
7733 if (tagmsg_path)
7734 preserve_tagmsg = 1;
7735 goto done;
7738 err = got_ref_write(ref, repo);
7739 if (err) {
7740 if (tagmsg_path)
7741 preserve_tagmsg = 1;
7742 goto done;
7745 err = got_object_id_str(&tag_id_str, tag_id);
7746 if (err) {
7747 if (tagmsg_path)
7748 preserve_tagmsg = 1;
7749 goto done;
7751 printf("Created tag %s\n", tag_id_str);
7752 done:
7753 if (preserve_tagmsg) {
7754 fprintf(stderr, "%s: tag message preserved in %s\n",
7755 getprogname(), tagmsg_path);
7756 } else if (tagmsg_path && unlink(tagmsg_path) == -1 && err == NULL)
7757 err = got_error_from_errno2("unlink", tagmsg_path);
7758 free(tag_id_str);
7759 if (ref)
7760 got_ref_close(ref);
7761 free(commit_id);
7762 free(commit_id_str);
7763 free(refname);
7764 free(tagmsg);
7765 free(tagmsg_path);
7766 got_ref_list_free(&refs);
7767 return err;
7770 static const struct got_error *
7771 cmd_tag(int argc, char *argv[])
7773 const struct got_error *error = NULL;
7774 struct got_repository *repo = NULL;
7775 struct got_worktree *worktree = NULL;
7776 char *cwd = NULL, *repo_path = NULL, *commit_id_str = NULL;
7777 char *gitconfig_path = NULL, *tagger = NULL, *keyword_idstr = NULL;
7778 char *allowed_signers = NULL, *revoked_signers = NULL, *editor = NULL;
7779 const char *signer_id = NULL;
7780 const char *tag_name = NULL, *commit_id_arg = NULL, *tagmsg = NULL;
7781 int ch, do_list = 0, verify_tags = 0, verbosity = 0;
7782 int *pack_fds = NULL;
7784 #ifndef PROFILE
7785 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
7786 "sendfd unveil", NULL) == -1)
7787 err(1, "pledge");
7788 #endif
7790 while ((ch = getopt(argc, argv, "c:lm:r:s:Vv")) != -1) {
7791 switch (ch) {
7792 case 'c':
7793 commit_id_arg = optarg;
7794 break;
7795 case 'l':
7796 do_list = 1;
7797 break;
7798 case 'm':
7799 tagmsg = optarg;
7800 break;
7801 case 'r':
7802 repo_path = realpath(optarg, NULL);
7803 if (repo_path == NULL) {
7804 error = got_error_from_errno2("realpath",
7805 optarg);
7806 goto done;
7808 got_path_strip_trailing_slashes(repo_path);
7809 break;
7810 case 's':
7811 signer_id = optarg;
7812 break;
7813 case 'V':
7814 verify_tags = 1;
7815 break;
7816 case 'v':
7817 if (verbosity < 0)
7818 verbosity = 0;
7819 else if (verbosity < 3)
7820 verbosity++;
7821 break;
7822 default:
7823 usage_tag();
7824 /* NOTREACHED */
7828 argc -= optind;
7829 argv += optind;
7831 if (do_list || verify_tags) {
7832 if (commit_id_arg != NULL)
7833 errx(1,
7834 "-c option can only be used when creating a tag");
7835 if (tagmsg) {
7836 if (do_list)
7837 option_conflict('l', 'm');
7838 else
7839 option_conflict('V', 'm');
7841 if (signer_id) {
7842 if (do_list)
7843 option_conflict('l', 's');
7844 else
7845 option_conflict('V', 's');
7847 if (argc > 1)
7848 usage_tag();
7849 } else if (argc != 1)
7850 usage_tag();
7852 if (argc == 1)
7853 tag_name = argv[0];
7855 cwd = getcwd(NULL, 0);
7856 if (cwd == NULL) {
7857 error = got_error_from_errno("getcwd");
7858 goto done;
7861 error = got_repo_pack_fds_open(&pack_fds);
7862 if (error != NULL)
7863 goto done;
7865 if (repo_path == NULL) {
7866 error = got_worktree_open(&worktree, cwd,
7867 GOT_WORKTREE_GOT_DIR);
7868 if (error && error->code != GOT_ERR_NOT_WORKTREE)
7869 goto done;
7870 else
7871 error = NULL;
7872 if (worktree) {
7873 repo_path =
7874 strdup(got_worktree_get_repo_path(worktree));
7875 if (repo_path == NULL)
7876 error = got_error_from_errno("strdup");
7877 if (error)
7878 goto done;
7879 } else {
7880 repo_path = strdup(cwd);
7881 if (repo_path == NULL) {
7882 error = got_error_from_errno("strdup");
7883 goto done;
7888 if (do_list || verify_tags) {
7889 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
7890 if (error != NULL)
7891 goto done;
7892 error = get_allowed_signers(&allowed_signers, repo, worktree);
7893 if (error)
7894 goto done;
7895 error = get_revoked_signers(&revoked_signers, repo, worktree);
7896 if (error)
7897 goto done;
7898 if (worktree) {
7899 /* Release work tree lock. */
7900 got_worktree_close(worktree);
7901 worktree = NULL;
7905 * Remove "cpath" promise unless needed for signature tmpfile
7906 * creation.
7908 if (verify_tags)
7909 got_sigs_apply_unveil();
7910 else {
7911 #ifndef PROFILE
7912 if (pledge("stdio rpath wpath flock proc exec sendfd "
7913 "unveil", NULL) == -1)
7914 err(1, "pledge");
7915 #endif
7917 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
7918 if (error)
7919 goto done;
7920 error = list_tags(repo, tag_name, verify_tags, allowed_signers,
7921 revoked_signers, verbosity);
7922 } else {
7923 error = get_gitconfig_path(&gitconfig_path);
7924 if (error)
7925 goto done;
7926 error = got_repo_open(&repo, repo_path, gitconfig_path,
7927 pack_fds);
7928 if (error != NULL)
7929 goto done;
7931 error = get_author(&tagger, repo, worktree);
7932 if (error)
7933 goto done;
7934 if (signer_id == NULL)
7935 signer_id = get_signer_id(repo, worktree);
7937 if (tagmsg == NULL) {
7938 error = get_editor(&editor);
7939 if (error)
7940 goto done;
7941 if (unveil(editor, "x") != 0) {
7942 error = got_error_from_errno2("unveil", editor);
7943 goto done;
7946 if (signer_id) {
7947 error = got_sigs_apply_unveil();
7948 if (error)
7949 goto done;
7951 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
7952 if (error)
7953 goto done;
7955 if (commit_id_arg == NULL) {
7956 struct got_reference *head_ref;
7957 struct got_object_id *commit_id;
7958 error = got_ref_open(&head_ref, repo,
7959 worktree ? got_worktree_get_head_ref_name(worktree)
7960 : GOT_REF_HEAD, 0);
7961 if (error)
7962 goto done;
7963 error = got_ref_resolve(&commit_id, repo, head_ref);
7964 got_ref_close(head_ref);
7965 if (error)
7966 goto done;
7967 error = got_object_id_str(&commit_id_str, commit_id);
7968 free(commit_id);
7969 if (error)
7970 goto done;
7971 } else {
7972 error = got_keyword_to_idstr(&keyword_idstr,
7973 commit_id_arg, repo, worktree);
7974 if (error != NULL)
7975 goto done;
7976 commit_id_str = keyword_idstr;
7979 if (worktree) {
7980 /* Release work tree lock. */
7981 got_worktree_close(worktree);
7982 worktree = NULL;
7985 error = add_tag(repo, tagger, tag_name,
7986 commit_id_str ? commit_id_str : commit_id_arg, tagmsg,
7987 signer_id, editor, verbosity);
7989 done:
7990 if (repo) {
7991 const struct got_error *close_err = got_repo_close(repo);
7992 if (error == NULL)
7993 error = close_err;
7995 if (worktree)
7996 got_worktree_close(worktree);
7997 if (pack_fds) {
7998 const struct got_error *pack_err =
7999 got_repo_pack_fds_close(pack_fds);
8000 if (error == NULL)
8001 error = pack_err;
8003 free(cwd);
8004 free(editor);
8005 free(repo_path);
8006 free(gitconfig_path);
8007 free(commit_id_str);
8008 free(tagger);
8009 free(allowed_signers);
8010 free(revoked_signers);
8011 return error;
8014 __dead static void
8015 usage_add(void)
8017 fprintf(stderr, "usage: %s add [-IR] path ...\n", getprogname());
8018 exit(1);
8021 static const struct got_error *
8022 add_progress(void *arg, unsigned char status, const char *path)
8024 while (path[0] == '/')
8025 path++;
8026 printf("%c %s\n", status, path);
8027 return NULL;
8030 static const struct got_error *
8031 cmd_add(int argc, char *argv[])
8033 const struct got_error *error = NULL;
8034 struct got_repository *repo = NULL;
8035 struct got_worktree *worktree = NULL;
8036 char *cwd = NULL;
8037 struct got_pathlist_head paths;
8038 struct got_pathlist_entry *pe;
8039 int ch, can_recurse = 0, no_ignores = 0;
8040 int *pack_fds = NULL;
8042 TAILQ_INIT(&paths);
8044 #ifndef PROFILE
8045 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
8046 NULL) == -1)
8047 err(1, "pledge");
8048 #endif
8050 while ((ch = getopt(argc, argv, "IR")) != -1) {
8051 switch (ch) {
8052 case 'I':
8053 no_ignores = 1;
8054 break;
8055 case 'R':
8056 can_recurse = 1;
8057 break;
8058 default:
8059 usage_add();
8060 /* NOTREACHED */
8064 argc -= optind;
8065 argv += optind;
8067 if (argc < 1)
8068 usage_add();
8070 cwd = getcwd(NULL, 0);
8071 if (cwd == NULL) {
8072 error = got_error_from_errno("getcwd");
8073 goto done;
8076 error = got_repo_pack_fds_open(&pack_fds);
8077 if (error != NULL)
8078 goto done;
8080 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
8081 if (error) {
8082 if (error->code == GOT_ERR_NOT_WORKTREE)
8083 error = wrap_not_worktree_error(error, "add", cwd);
8084 goto done;
8087 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
8088 NULL, pack_fds);
8089 if (error != NULL)
8090 goto done;
8092 error = apply_unveil(got_repo_get_path(repo), 1,
8093 got_worktree_get_root_path(worktree));
8094 if (error)
8095 goto done;
8097 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
8098 if (error)
8099 goto done;
8101 if (!can_recurse) {
8102 char *ondisk_path;
8103 struct stat sb;
8104 TAILQ_FOREACH(pe, &paths, entry) {
8105 if (asprintf(&ondisk_path, "%s/%s",
8106 got_worktree_get_root_path(worktree),
8107 pe->path) == -1) {
8108 error = got_error_from_errno("asprintf");
8109 goto done;
8111 if (lstat(ondisk_path, &sb) == -1) {
8112 if (errno == ENOENT) {
8113 free(ondisk_path);
8114 continue;
8116 error = got_error_from_errno2("lstat",
8117 ondisk_path);
8118 free(ondisk_path);
8119 goto done;
8121 free(ondisk_path);
8122 if (S_ISDIR(sb.st_mode)) {
8123 error = got_error_msg(GOT_ERR_BAD_PATH,
8124 "adding directories requires -R option");
8125 goto done;
8130 error = got_worktree_schedule_add(worktree, &paths, add_progress,
8131 NULL, repo, no_ignores);
8132 done:
8133 if (repo) {
8134 const struct got_error *close_err = got_repo_close(repo);
8135 if (error == NULL)
8136 error = close_err;
8138 if (worktree)
8139 got_worktree_close(worktree);
8140 if (pack_fds) {
8141 const struct got_error *pack_err =
8142 got_repo_pack_fds_close(pack_fds);
8143 if (error == NULL)
8144 error = pack_err;
8146 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
8147 free(cwd);
8148 return error;
8151 __dead static void
8152 usage_remove(void)
8154 fprintf(stderr, "usage: %s remove [-fkR] [-s status-codes] path ...\n",
8155 getprogname());
8156 exit(1);
8159 static const struct got_error *
8160 print_remove_status(void *arg, unsigned char status,
8161 unsigned char staged_status, const char *path)
8163 while (path[0] == '/')
8164 path++;
8165 if (status == GOT_STATUS_NONEXISTENT)
8166 return NULL;
8167 if (status == staged_status && (status == GOT_STATUS_DELETE))
8168 status = GOT_STATUS_NO_CHANGE;
8169 printf("%c%c %s\n", status, staged_status, path);
8170 return NULL;
8173 static const struct got_error *
8174 cmd_remove(int argc, char *argv[])
8176 const struct got_error *error = NULL;
8177 struct got_worktree *worktree = NULL;
8178 struct got_repository *repo = NULL;
8179 const char *status_codes = NULL;
8180 char *cwd = NULL;
8181 struct got_pathlist_head paths;
8182 struct got_pathlist_entry *pe;
8183 int ch, delete_local_mods = 0, can_recurse = 0, keep_on_disk = 0, i;
8184 int ignore_missing_paths = 0;
8185 int *pack_fds = NULL;
8187 TAILQ_INIT(&paths);
8189 #ifndef PROFILE
8190 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
8191 NULL) == -1)
8192 err(1, "pledge");
8193 #endif
8195 while ((ch = getopt(argc, argv, "fkRs:")) != -1) {
8196 switch (ch) {
8197 case 'f':
8198 delete_local_mods = 1;
8199 ignore_missing_paths = 1;
8200 break;
8201 case 'k':
8202 keep_on_disk = 1;
8203 break;
8204 case 'R':
8205 can_recurse = 1;
8206 break;
8207 case 's':
8208 for (i = 0; optarg[i] != '\0'; i++) {
8209 switch (optarg[i]) {
8210 case GOT_STATUS_MODIFY:
8211 delete_local_mods = 1;
8212 break;
8213 case GOT_STATUS_MISSING:
8214 ignore_missing_paths = 1;
8215 break;
8216 default:
8217 errx(1, "invalid status code '%c'",
8218 optarg[i]);
8221 status_codes = optarg;
8222 break;
8223 default:
8224 usage_remove();
8225 /* NOTREACHED */
8229 argc -= optind;
8230 argv += optind;
8232 if (argc < 1)
8233 usage_remove();
8235 cwd = getcwd(NULL, 0);
8236 if (cwd == NULL) {
8237 error = got_error_from_errno("getcwd");
8238 goto done;
8241 error = got_repo_pack_fds_open(&pack_fds);
8242 if (error != NULL)
8243 goto done;
8245 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
8246 if (error) {
8247 if (error->code == GOT_ERR_NOT_WORKTREE)
8248 error = wrap_not_worktree_error(error, "remove", cwd);
8249 goto done;
8252 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
8253 NULL, pack_fds);
8254 if (error)
8255 goto done;
8257 error = apply_unveil(got_repo_get_path(repo), 1,
8258 got_worktree_get_root_path(worktree));
8259 if (error)
8260 goto done;
8262 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
8263 if (error)
8264 goto done;
8266 if (!can_recurse) {
8267 char *ondisk_path;
8268 struct stat sb;
8269 TAILQ_FOREACH(pe, &paths, entry) {
8270 if (asprintf(&ondisk_path, "%s/%s",
8271 got_worktree_get_root_path(worktree),
8272 pe->path) == -1) {
8273 error = got_error_from_errno("asprintf");
8274 goto done;
8276 if (lstat(ondisk_path, &sb) == -1) {
8277 if (errno == ENOENT) {
8278 free(ondisk_path);
8279 continue;
8281 error = got_error_from_errno2("lstat",
8282 ondisk_path);
8283 free(ondisk_path);
8284 goto done;
8286 free(ondisk_path);
8287 if (S_ISDIR(sb.st_mode)) {
8288 error = got_error_msg(GOT_ERR_BAD_PATH,
8289 "removing directories requires -R option");
8290 goto done;
8295 error = got_worktree_schedule_delete(worktree, &paths,
8296 delete_local_mods, status_codes, print_remove_status, NULL,
8297 repo, keep_on_disk, ignore_missing_paths);
8298 done:
8299 if (repo) {
8300 const struct got_error *close_err = got_repo_close(repo);
8301 if (error == NULL)
8302 error = close_err;
8304 if (worktree)
8305 got_worktree_close(worktree);
8306 if (pack_fds) {
8307 const struct got_error *pack_err =
8308 got_repo_pack_fds_close(pack_fds);
8309 if (error == NULL)
8310 error = pack_err;
8312 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
8313 free(cwd);
8314 return error;
8317 __dead static void
8318 usage_patch(void)
8320 fprintf(stderr, "usage: %s patch [-nR] [-c commit] [-p strip-count] "
8321 "[patchfile]\n", getprogname());
8322 exit(1);
8325 static const struct got_error *
8326 patch_from_stdin(int *patchfd)
8328 const struct got_error *err = NULL;
8329 ssize_t r;
8330 char buf[BUFSIZ];
8331 sig_t sighup, sigint, sigquit;
8333 *patchfd = got_opentempfd();
8334 if (*patchfd == -1)
8335 return got_error_from_errno("got_opentempfd");
8337 sighup = signal(SIGHUP, SIG_DFL);
8338 sigint = signal(SIGINT, SIG_DFL);
8339 sigquit = signal(SIGQUIT, SIG_DFL);
8341 for (;;) {
8342 r = read(0, buf, sizeof(buf));
8343 if (r == -1) {
8344 err = got_error_from_errno("read");
8345 break;
8347 if (r == 0)
8348 break;
8349 if (write(*patchfd, buf, r) == -1) {
8350 err = got_error_from_errno("write");
8351 break;
8355 signal(SIGHUP, sighup);
8356 signal(SIGINT, sigint);
8357 signal(SIGQUIT, sigquit);
8359 if (err == NULL && lseek(*patchfd, 0, SEEK_SET) == -1)
8360 err = got_error_from_errno("lseek");
8362 if (err != NULL) {
8363 close(*patchfd);
8364 *patchfd = -1;
8367 return err;
8370 struct got_patch_progress_arg {
8371 int did_something;
8372 int conflicts;
8373 int rejects;
8376 static const struct got_error *
8377 patch_progress(void *arg, const char *old, const char *new,
8378 unsigned char status, const struct got_error *error, int old_from,
8379 int old_lines, int new_from, int new_lines, int offset,
8380 int ws_mangled, const struct got_error *hunk_err)
8382 const char *path = new == NULL ? old : new;
8383 struct got_patch_progress_arg *a = arg;
8385 while (*path == '/')
8386 path++;
8388 if (status != GOT_STATUS_NO_CHANGE &&
8389 status != 0 /* per-hunk progress */) {
8390 printf("%c %s\n", status, path);
8391 a->did_something = 1;
8394 if (hunk_err == NULL) {
8395 if (status == GOT_STATUS_CANNOT_UPDATE)
8396 a->rejects++;
8397 else if (status == GOT_STATUS_CONFLICT)
8398 a->conflicts++;
8401 if (error != NULL)
8402 fprintf(stderr, "%s: %s\n", getprogname(), error->msg);
8404 if (offset != 0 || hunk_err != NULL || ws_mangled) {
8405 printf("@@ -%d,%d +%d,%d @@ ", old_from,
8406 old_lines, new_from, new_lines);
8407 if (hunk_err != NULL)
8408 printf("%s\n", hunk_err->msg);
8409 else if (offset != 0)
8410 printf("applied with offset %d\n", offset);
8411 else
8412 printf("hunk contains mangled whitespace\n");
8415 return NULL;
8418 static void
8419 print_patch_progress_stats(struct got_patch_progress_arg *ppa)
8421 if (!ppa->did_something)
8422 return;
8424 if (ppa->conflicts > 0)
8425 printf("Files with merge conflicts: %d\n", ppa->conflicts);
8427 if (ppa->rejects > 0) {
8428 printf("Files where patch failed to apply: %d\n",
8429 ppa->rejects);
8433 static const struct got_error *
8434 cmd_patch(int argc, char *argv[])
8436 const struct got_error *error = NULL, *close_error = NULL;
8437 struct got_worktree *worktree = NULL;
8438 struct got_repository *repo = NULL;
8439 struct got_reflist_head refs;
8440 struct got_object_id *commit_id = NULL;
8441 const char *commit_id_str = NULL;
8442 struct stat sb;
8443 const char *errstr;
8444 char *cwd = NULL, *keyword_idstr = NULL;
8445 int ch, nop = 0, strip = -1, reverse = 0;
8446 int patchfd;
8447 int *pack_fds = NULL;
8448 struct got_patch_progress_arg ppa;
8450 TAILQ_INIT(&refs);
8452 #ifndef PROFILE
8453 if (pledge("stdio rpath wpath cpath fattr proc exec sendfd flock "
8454 "unveil", NULL) == -1)
8455 err(1, "pledge");
8456 #endif
8458 while ((ch = getopt(argc, argv, "c:np:R")) != -1) {
8459 switch (ch) {
8460 case 'c':
8461 commit_id_str = optarg;
8462 break;
8463 case 'n':
8464 nop = 1;
8465 break;
8466 case 'p':
8467 strip = strtonum(optarg, 0, INT_MAX, &errstr);
8468 if (errstr != NULL)
8469 errx(1, "pathname strip count is %s: %s",
8470 errstr, optarg);
8471 break;
8472 case 'R':
8473 reverse = 1;
8474 break;
8475 default:
8476 usage_patch();
8477 /* NOTREACHED */
8481 argc -= optind;
8482 argv += optind;
8484 if (argc == 0) {
8485 error = patch_from_stdin(&patchfd);
8486 if (error)
8487 return error;
8488 } else if (argc == 1) {
8489 patchfd = open(argv[0], O_RDONLY);
8490 if (patchfd == -1) {
8491 error = got_error_from_errno2("open", argv[0]);
8492 return error;
8494 if (fstat(patchfd, &sb) == -1) {
8495 error = got_error_from_errno2("fstat", argv[0]);
8496 goto done;
8498 if (!S_ISREG(sb.st_mode)) {
8499 error = got_error_path(argv[0], GOT_ERR_BAD_FILETYPE);
8500 goto done;
8502 } else
8503 usage_patch();
8505 if ((cwd = getcwd(NULL, 0)) == NULL) {
8506 error = got_error_from_errno("getcwd");
8507 goto done;
8510 error = got_repo_pack_fds_open(&pack_fds);
8511 if (error != NULL)
8512 goto done;
8514 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
8515 if (error != NULL)
8516 goto done;
8518 const char *repo_path = got_worktree_get_repo_path(worktree);
8519 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
8520 if (error != NULL)
8521 goto done;
8523 error = apply_unveil(got_repo_get_path(repo), 0,
8524 got_worktree_get_root_path(worktree));
8525 if (error != NULL)
8526 goto done;
8528 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
8529 if (error)
8530 goto done;
8532 if (commit_id_str != NULL) {
8533 error = got_keyword_to_idstr(&keyword_idstr, commit_id_str,
8534 repo, worktree);
8535 if (error != NULL)
8536 goto done;
8538 error = got_repo_match_object_id(&commit_id, NULL,
8539 keyword_idstr != NULL ? keyword_idstr : commit_id_str,
8540 GOT_OBJ_TYPE_COMMIT, &refs, repo);
8541 if (error)
8542 goto done;
8545 memset(&ppa, 0, sizeof(ppa));
8546 error = got_patch(patchfd, worktree, repo, nop, strip, reverse,
8547 commit_id, patch_progress, &ppa, check_cancelled, NULL);
8548 print_patch_progress_stats(&ppa);
8549 done:
8550 got_ref_list_free(&refs);
8551 free(keyword_idstr);
8552 free(commit_id);
8553 if (repo) {
8554 close_error = got_repo_close(repo);
8555 if (error == NULL)
8556 error = close_error;
8558 if (worktree != NULL) {
8559 close_error = got_worktree_close(worktree);
8560 if (error == NULL)
8561 error = close_error;
8563 if (pack_fds) {
8564 const struct got_error *pack_err =
8565 got_repo_pack_fds_close(pack_fds);
8566 if (error == NULL)
8567 error = pack_err;
8569 free(cwd);
8570 return error;
8573 __dead static void
8574 usage_revert(void)
8576 fprintf(stderr, "usage: %s revert [-pR] [-F response-script] path ...\n",
8577 getprogname());
8578 exit(1);
8581 static const struct got_error *
8582 revert_progress(void *arg, unsigned char status, const char *path)
8584 if (status == GOT_STATUS_UNVERSIONED)
8585 return NULL;
8587 while (path[0] == '/')
8588 path++;
8589 printf("%c %s\n", status, path);
8590 return NULL;
8593 struct choose_patch_arg {
8594 FILE *patch_script_file;
8595 const char *action;
8598 static const struct got_error *
8599 show_change(unsigned char status, const char *path, FILE *patch_file, int n,
8600 int nchanges, const char *action)
8602 const struct got_error *err;
8603 char *line = NULL;
8604 size_t linesize = 0;
8605 ssize_t linelen;
8607 switch (status) {
8608 case GOT_STATUS_ADD:
8609 printf("A %s\n%s this addition? [y/n] ", path, action);
8610 break;
8611 case GOT_STATUS_DELETE:
8612 printf("D %s\n%s this deletion? [y/n] ", path, action);
8613 break;
8614 case GOT_STATUS_MODIFY:
8615 if (fseek(patch_file, 0L, SEEK_SET) == -1)
8616 return got_error_from_errno("fseek");
8617 printf(GOT_COMMIT_SEP_STR);
8618 while ((linelen = getline(&line, &linesize, patch_file)) != -1)
8619 printf("%s", line);
8620 if (linelen == -1 && ferror(patch_file)) {
8621 err = got_error_from_errno("getline");
8622 free(line);
8623 return err;
8625 free(line);
8626 printf(GOT_COMMIT_SEP_STR);
8627 printf("M %s (change %d of %d)\n%s this change? [y/n/q] ",
8628 path, n, nchanges, action);
8629 break;
8630 default:
8631 return got_error_path(path, GOT_ERR_FILE_STATUS);
8634 fflush(stdout);
8635 return NULL;
8638 static const struct got_error *
8639 choose_patch(int *choice, void *arg, unsigned char status, const char *path,
8640 FILE *patch_file, int n, int nchanges)
8642 const struct got_error *err = NULL;
8643 char *line = NULL;
8644 size_t linesize = 0;
8645 ssize_t linelen;
8646 int resp = ' ';
8647 struct choose_patch_arg *a = arg;
8649 *choice = GOT_PATCH_CHOICE_NONE;
8651 if (a->patch_script_file) {
8652 char *nl;
8653 err = show_change(status, path, patch_file, n, nchanges,
8654 a->action);
8655 if (err)
8656 return err;
8657 linelen = getline(&line, &linesize, a->patch_script_file);
8658 if (linelen == -1) {
8659 if (ferror(a->patch_script_file))
8660 return got_error_from_errno("getline");
8661 return NULL;
8663 nl = strchr(line, '\n');
8664 if (nl)
8665 *nl = '\0';
8666 if (strcmp(line, "y") == 0) {
8667 *choice = GOT_PATCH_CHOICE_YES;
8668 printf("y\n");
8669 } else if (strcmp(line, "n") == 0) {
8670 *choice = GOT_PATCH_CHOICE_NO;
8671 printf("n\n");
8672 } else if (strcmp(line, "q") == 0 &&
8673 status == GOT_STATUS_MODIFY) {
8674 *choice = GOT_PATCH_CHOICE_QUIT;
8675 printf("q\n");
8676 } else
8677 printf("invalid response '%s'\n", line);
8678 free(line);
8679 return NULL;
8682 while (resp != 'y' && resp != 'n' && resp != 'q') {
8683 err = show_change(status, path, patch_file, n, nchanges,
8684 a->action);
8685 if (err)
8686 return err;
8687 resp = getchar();
8688 if (resp == '\n')
8689 resp = getchar();
8690 if (status == GOT_STATUS_MODIFY) {
8691 if (resp != 'y' && resp != 'n' && resp != 'q') {
8692 printf("invalid response '%c'\n", resp);
8693 resp = ' ';
8695 } else if (resp != 'y' && resp != 'n') {
8696 printf("invalid response '%c'\n", resp);
8697 resp = ' ';
8701 if (resp == 'y')
8702 *choice = GOT_PATCH_CHOICE_YES;
8703 else if (resp == 'n')
8704 *choice = GOT_PATCH_CHOICE_NO;
8705 else if (resp == 'q' && status == GOT_STATUS_MODIFY)
8706 *choice = GOT_PATCH_CHOICE_QUIT;
8708 return NULL;
8711 struct wt_commitable_path_arg {
8712 struct got_pathlist_head *commit_paths;
8713 int *has_changes;
8717 * Shortcut work tree status callback to determine if the set of paths scanned
8718 * has at least one versioned path that is being modified and, if not NULL, is
8719 * in the arg->commit_paths list. Set arg and return GOT_ERR_FILE_MODIFIED as
8720 * soon as a path is passed with a status that satisfies this criteria.
8722 static const struct got_error *
8723 worktree_has_commitable_path(void *arg, unsigned char status,
8724 unsigned char staged_status, const char *path,
8725 struct got_object_id *blob_id, struct got_object_id *staged_blob_id,
8726 struct got_object_id *commit_id, int dirfd, const char *de_name)
8728 struct wt_commitable_path_arg *a = arg;
8730 if (status == staged_status && (status == GOT_STATUS_DELETE))
8731 status = GOT_STATUS_NO_CHANGE;
8733 if (!(status == GOT_STATUS_NO_CHANGE ||
8734 status == GOT_STATUS_UNVERSIONED) ||
8735 staged_status != GOT_STATUS_NO_CHANGE) {
8736 if (a->commit_paths != NULL) {
8737 struct got_pathlist_entry *pe;
8739 TAILQ_FOREACH(pe, a->commit_paths, entry) {
8740 if (strncmp(path, pe->path,
8741 pe->path_len) == 0) {
8742 *a->has_changes = 1;
8743 break;
8746 } else
8747 *a->has_changes = 1;
8749 if (*a->has_changes)
8750 return got_error(GOT_ERR_FILE_MODIFIED);
8753 return NULL;
8757 * Check that the changeset of the commit identified by id is
8758 * comprised of at least one modified path that is being committed.
8760 static const struct got_error *
8761 commit_path_changed_in_worktree(struct wt_commitable_path_arg *wcpa,
8762 struct got_object_id *id, struct got_worktree *worktree,
8763 struct got_repository *repo)
8765 const struct got_error *err;
8766 struct got_pathlist_head paths;
8767 struct got_commit_object *commit = NULL, *pcommit = NULL;
8768 struct got_tree_object *tree = NULL, *ptree = NULL;
8769 struct got_object_qid *pid;
8771 TAILQ_INIT(&paths);
8773 err = got_object_open_as_commit(&commit, repo, id);
8774 if (err)
8775 goto done;
8777 err = got_object_open_as_tree(&tree, repo,
8778 got_object_commit_get_tree_id(commit));
8779 if (err)
8780 goto done;
8782 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
8783 if (pid != NULL) {
8784 err = got_object_open_as_commit(&pcommit, repo, &pid->id);
8785 if (err)
8786 goto done;
8788 err = got_object_open_as_tree(&ptree, repo,
8789 got_object_commit_get_tree_id(pcommit));
8790 if (err)
8791 goto done;
8794 err = got_diff_tree(ptree, tree, NULL, NULL, -1, -1, "", "", repo,
8795 got_diff_tree_collect_changed_paths, &paths, 0);
8796 if (err)
8797 goto done;
8799 err = got_worktree_status(worktree, &paths, repo, 0,
8800 worktree_has_commitable_path, wcpa, check_cancelled, NULL);
8801 if (err && err->code == GOT_ERR_FILE_MODIFIED) {
8803 * At least one changed path in the referenced commit is
8804 * modified in the work tree, that's all we need to know!
8806 err = NULL;
8809 done:
8810 got_pathlist_free(&paths, GOT_PATHLIST_FREE_ALL);
8811 if (commit)
8812 got_object_commit_close(commit);
8813 if (pcommit)
8814 got_object_commit_close(pcommit);
8815 if (tree)
8816 got_object_tree_close(tree);
8817 if (ptree)
8818 got_object_tree_close(ptree);
8819 return err;
8823 * Remove any "logmsg" reference comprised entirely of paths that have
8824 * been reverted in this work tree. If any path in the logmsg ref changeset
8825 * remains in a changed state in the worktree, do not remove the reference.
8827 static const struct got_error *
8828 rm_logmsg_ref(struct got_worktree *worktree, struct got_repository *repo)
8830 const struct got_error *err;
8831 struct got_reflist_head refs;
8832 struct got_reflist_entry *re;
8833 struct got_commit_object *commit = NULL;
8834 struct got_object_id *commit_id = NULL;
8835 struct wt_commitable_path_arg wcpa;
8836 char *uuidstr = NULL;
8838 TAILQ_INIT(&refs);
8840 err = got_worktree_get_uuid(&uuidstr, worktree);
8841 if (err)
8842 goto done;
8844 err = got_ref_list(&refs, repo, "refs/got/worktree",
8845 got_ref_cmp_by_name, repo);
8846 if (err)
8847 goto done;
8849 TAILQ_FOREACH(re, &refs, entry) {
8850 const char *refname;
8851 int has_changes = 0;
8853 refname = got_ref_get_name(re->ref);
8855 if (!strncmp(refname, GOT_WORKTREE_CHERRYPICK_REF_PREFIX,
8856 GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN))
8857 refname += GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN + 1;
8858 else if (!strncmp(refname, GOT_WORKTREE_BACKOUT_REF_PREFIX,
8859 GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN))
8860 refname += GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN + 1;
8861 else
8862 continue;
8864 if (strncmp(refname, uuidstr, GOT_WORKTREE_UUID_STRLEN) == 0)
8865 refname += GOT_WORKTREE_UUID_STRLEN + 1; /* skip '-' */
8866 else
8867 continue;
8869 err = got_repo_match_object_id(&commit_id, NULL, refname,
8870 GOT_OBJ_TYPE_COMMIT, NULL, repo);
8871 if (err)
8872 goto done;
8874 err = got_object_open_as_commit(&commit, repo, commit_id);
8875 if (err)
8876 goto done;
8878 wcpa.commit_paths = NULL;
8879 wcpa.has_changes = &has_changes;
8881 err = commit_path_changed_in_worktree(&wcpa, commit_id,
8882 worktree, repo);
8883 if (err)
8884 goto done;
8886 if (!has_changes) {
8887 err = got_ref_delete(re->ref, repo);
8888 if (err)
8889 goto done;
8892 got_object_commit_close(commit);
8893 commit = NULL;
8894 free(commit_id);
8895 commit_id = NULL;
8898 done:
8899 free(uuidstr);
8900 free(commit_id);
8901 got_ref_list_free(&refs);
8902 if (commit)
8903 got_object_commit_close(commit);
8904 return err;
8907 static const struct got_error *
8908 cmd_revert(int argc, char *argv[])
8910 const struct got_error *error = NULL;
8911 struct got_worktree *worktree = NULL;
8912 struct got_repository *repo = NULL;
8913 char *cwd = NULL, *path = NULL;
8914 struct got_pathlist_head paths;
8915 struct got_pathlist_entry *pe;
8916 int ch, can_recurse = 0, pflag = 0;
8917 FILE *patch_script_file = NULL;
8918 const char *patch_script_path = NULL;
8919 struct choose_patch_arg cpa;
8920 int *pack_fds = NULL;
8922 TAILQ_INIT(&paths);
8924 #ifndef PROFILE
8925 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
8926 "unveil", NULL) == -1)
8927 err(1, "pledge");
8928 #endif
8930 while ((ch = getopt(argc, argv, "F:pR")) != -1) {
8931 switch (ch) {
8932 case 'F':
8933 patch_script_path = optarg;
8934 break;
8935 case 'p':
8936 pflag = 1;
8937 break;
8938 case 'R':
8939 can_recurse = 1;
8940 break;
8941 default:
8942 usage_revert();
8943 /* NOTREACHED */
8947 argc -= optind;
8948 argv += optind;
8950 if (argc < 1)
8951 usage_revert();
8952 if (patch_script_path && !pflag)
8953 errx(1, "-F option can only be used together with -p option");
8955 cwd = getcwd(NULL, 0);
8956 if (cwd == NULL) {
8957 error = got_error_from_errno("getcwd");
8958 goto done;
8961 error = got_repo_pack_fds_open(&pack_fds);
8962 if (error != NULL)
8963 goto done;
8965 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
8966 if (error) {
8967 if (error->code == GOT_ERR_NOT_WORKTREE)
8968 error = wrap_not_worktree_error(error, "revert", cwd);
8969 goto done;
8972 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
8973 NULL, pack_fds);
8974 if (error != NULL)
8975 goto done;
8977 if (patch_script_path) {
8978 patch_script_file = fopen(patch_script_path, "re");
8979 if (patch_script_file == NULL) {
8980 error = got_error_from_errno2("fopen",
8981 patch_script_path);
8982 goto done;
8987 * XXX "c" perm needed on repo dir to delete merge references.
8989 error = apply_unveil(got_repo_get_path(repo), 0,
8990 got_worktree_get_root_path(worktree));
8991 if (error)
8992 goto done;
8994 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
8995 if (error)
8996 goto done;
8998 if (!can_recurse) {
8999 char *ondisk_path;
9000 struct stat sb;
9001 TAILQ_FOREACH(pe, &paths, entry) {
9002 if (asprintf(&ondisk_path, "%s/%s",
9003 got_worktree_get_root_path(worktree),
9004 pe->path) == -1) {
9005 error = got_error_from_errno("asprintf");
9006 goto done;
9008 if (lstat(ondisk_path, &sb) == -1) {
9009 if (errno == ENOENT) {
9010 free(ondisk_path);
9011 continue;
9013 error = got_error_from_errno2("lstat",
9014 ondisk_path);
9015 free(ondisk_path);
9016 goto done;
9018 free(ondisk_path);
9019 if (S_ISDIR(sb.st_mode)) {
9020 error = got_error_msg(GOT_ERR_BAD_PATH,
9021 "reverting directories requires -R option");
9022 goto done;
9027 cpa.patch_script_file = patch_script_file;
9028 cpa.action = "revert";
9029 error = got_worktree_revert(worktree, &paths, revert_progress, NULL,
9030 pflag ? choose_patch : NULL, &cpa, repo);
9032 error = rm_logmsg_ref(worktree, repo);
9033 done:
9034 if (patch_script_file && fclose(patch_script_file) == EOF &&
9035 error == NULL)
9036 error = got_error_from_errno2("fclose", patch_script_path);
9037 if (repo) {
9038 const struct got_error *close_err = got_repo_close(repo);
9039 if (error == NULL)
9040 error = close_err;
9042 if (worktree)
9043 got_worktree_close(worktree);
9044 if (pack_fds) {
9045 const struct got_error *pack_err =
9046 got_repo_pack_fds_close(pack_fds);
9047 if (error == NULL)
9048 error = pack_err;
9050 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
9051 free(path);
9052 free(cwd);
9053 return error;
9056 __dead static void
9057 usage_commit(void)
9059 fprintf(stderr, "usage: %s commit [-CNnS] [-A author] [-F path] "
9060 "[-m message] [path ...]\n", getprogname());
9061 exit(1);
9064 struct collect_commit_logmsg_arg {
9065 const char *cmdline_log;
9066 const char *prepared_log;
9067 const char *merged_log;
9068 int non_interactive;
9069 const char *editor;
9070 const char *worktree_path;
9071 const char *branch_name;
9072 const char *repo_path;
9073 char *logmsg_path;
9077 static const struct got_error *
9078 read_prepared_logmsg(char **logmsg, const char *path)
9080 const struct got_error *err = NULL;
9081 FILE *f = NULL;
9082 struct stat sb;
9083 size_t r;
9085 *logmsg = NULL;
9086 memset(&sb, 0, sizeof(sb));
9088 f = fopen(path, "re");
9089 if (f == NULL)
9090 return got_error_from_errno2("fopen", path);
9092 if (fstat(fileno(f), &sb) == -1) {
9093 err = got_error_from_errno2("fstat", path);
9094 goto done;
9096 if (sb.st_size == 0) {
9097 err = got_error(GOT_ERR_COMMIT_MSG_EMPTY);
9098 goto done;
9101 *logmsg = malloc(sb.st_size + 1);
9102 if (*logmsg == NULL) {
9103 err = got_error_from_errno("malloc");
9104 goto done;
9107 r = fread(*logmsg, 1, sb.st_size, f);
9108 if (r != sb.st_size) {
9109 if (ferror(f))
9110 err = got_error_from_errno2("fread", path);
9111 else
9112 err = got_error(GOT_ERR_IO);
9113 goto done;
9115 (*logmsg)[sb.st_size] = '\0';
9116 done:
9117 if (fclose(f) == EOF && err == NULL)
9118 err = got_error_from_errno2("fclose", path);
9119 if (err) {
9120 free(*logmsg);
9121 *logmsg = NULL;
9123 return err;
9126 static const struct got_error *
9127 collect_commit_logmsg(struct got_pathlist_head *commitable_paths,
9128 const char *diff_path, char **logmsg, void *arg)
9130 char *initial_content = NULL;
9131 struct got_pathlist_entry *pe;
9132 const struct got_error *err = NULL;
9133 char *template = NULL;
9134 char *prepared_msg = NULL, *merged_msg = NULL;
9135 struct collect_commit_logmsg_arg *a = arg;
9136 int initial_content_len;
9137 int fd = -1;
9138 size_t len;
9140 /* if a message was specified on the command line, just use it */
9141 if (a->cmdline_log != NULL && *a->cmdline_log != '\0') {
9142 len = strlen(a->cmdline_log) + 1;
9143 *logmsg = malloc(len + 1);
9144 if (*logmsg == NULL)
9145 return got_error_from_errno("malloc");
9146 strlcpy(*logmsg, a->cmdline_log, len);
9147 return NULL;
9148 } else if (a->prepared_log != NULL && a->non_interactive)
9149 return read_prepared_logmsg(logmsg, a->prepared_log);
9151 if (asprintf(&template, "%s/logmsg", a->worktree_path) == -1)
9152 return got_error_from_errno("asprintf");
9154 err = got_opentemp_named_fd(&a->logmsg_path, &fd, template, "");
9155 if (err)
9156 goto done;
9158 if (a->prepared_log) {
9159 err = read_prepared_logmsg(&prepared_msg, a->prepared_log);
9160 if (err)
9161 goto done;
9162 } else if (a->merged_log) {
9163 err = read_prepared_logmsg(&merged_msg, a->merged_log);
9164 if (err)
9165 goto done;
9168 initial_content_len = asprintf(&initial_content,
9169 "%s%s\n# changes to be committed on branch %s:\n",
9170 prepared_msg ? prepared_msg : "",
9171 merged_msg ? merged_msg : "", a->branch_name);
9172 if (initial_content_len == -1) {
9173 err = got_error_from_errno("asprintf");
9174 goto done;
9177 if (write(fd, initial_content, initial_content_len) == -1) {
9178 err = got_error_from_errno2("write", a->logmsg_path);
9179 goto done;
9182 TAILQ_FOREACH(pe, commitable_paths, entry) {
9183 struct got_commitable *ct = pe->data;
9184 dprintf(fd, "# %c %s\n",
9185 got_commitable_get_status(ct),
9186 got_commitable_get_path(ct));
9189 if (diff_path) {
9190 dprintf(fd, "# detailed changes can be viewed in %s\n",
9191 diff_path);
9194 if (close(fd) == -1) {
9195 err = got_error_from_errno2("close", a->logmsg_path);
9196 goto done;
9198 fd = -1;
9200 err = edit_logmsg(logmsg, a->editor, a->logmsg_path, initial_content,
9201 initial_content_len, a->prepared_log ? 0 : 1);
9202 done:
9203 free(initial_content);
9204 free(template);
9205 free(prepared_msg);
9206 free(merged_msg);
9208 if (fd != -1 && close(fd) == -1 && err == NULL)
9209 err = got_error_from_errno2("close", a->logmsg_path);
9210 if (err) {
9211 free(*logmsg);
9212 *logmsg = NULL;
9214 return err;
9217 static const struct got_error *
9218 cat_logmsg(FILE *f, struct got_commit_object *commit, const char *idstr,
9219 const char *type, int has_content)
9221 const struct got_error *err = NULL;
9222 char *logmsg = NULL;
9224 err = got_object_commit_get_logmsg(&logmsg, commit);
9225 if (err)
9226 return err;
9228 if (fprintf(f, "%s# log message of %s commit %s:%s",
9229 has_content ? "\n" : "", type, idstr, logmsg) < 0)
9230 err = got_ferror(f, GOT_ERR_IO);
9232 free(logmsg);
9233 return err;
9237 * Lookup "logmsg" references of backed-out and cherrypicked commits
9238 * belonging to the current work tree. If found, and the worktree has
9239 * at least one modified file that was changed in the referenced commit,
9240 * add its log message to a new temporary file at *logmsg_path.
9241 * Add all refs found to matched_refs to be scheduled for removal on
9242 * successful commit.
9244 static const struct got_error *
9245 lookup_logmsg_ref(char **logmsg_path, struct got_pathlist_head *paths,
9246 struct got_reflist_head *matched_refs, struct got_worktree *worktree,
9247 struct got_repository *repo)
9249 const struct got_error *err;
9250 struct got_commit_object *commit = NULL;
9251 struct got_object_id *id = NULL;
9252 struct got_reflist_head refs;
9253 struct got_reflist_entry *re, *re_match;
9254 FILE *f = NULL;
9255 char *uuidstr = NULL;
9256 int added_logmsg = 0;
9258 TAILQ_INIT(&refs);
9260 *logmsg_path = NULL;
9262 err = got_worktree_get_uuid(&uuidstr, worktree);
9263 if (err)
9264 goto done;
9266 err = got_ref_list(&refs, repo, "refs/got/worktree",
9267 got_ref_cmp_by_name, repo);
9268 if (err)
9269 goto done;
9271 TAILQ_FOREACH(re, &refs, entry) {
9272 const char *refname, *type;
9273 struct wt_commitable_path_arg wcpa;
9274 int add_logmsg = 0;
9276 refname = got_ref_get_name(re->ref);
9278 if (strncmp(refname, GOT_WORKTREE_CHERRYPICK_REF_PREFIX,
9279 GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN) == 0) {
9280 refname += GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN + 1;
9281 type = "cherrypicked";
9282 } else if (strncmp(refname, GOT_WORKTREE_BACKOUT_REF_PREFIX,
9283 GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN) == 0) {
9284 refname += GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN + 1;
9285 type = "backed-out";
9286 } else
9287 continue;
9289 if (strncmp(refname, uuidstr, GOT_WORKTREE_UUID_STRLEN) == 0)
9290 refname += GOT_WORKTREE_UUID_STRLEN + 1; /* skip '-' */
9291 else
9292 continue;
9294 err = got_repo_match_object_id(&id, NULL, refname,
9295 GOT_OBJ_TYPE_COMMIT, NULL, repo);
9296 if (err)
9297 goto done;
9299 err = got_object_open_as_commit(&commit, repo, id);
9300 if (err)
9301 goto done;
9303 wcpa.commit_paths = paths;
9304 wcpa.has_changes = &add_logmsg;
9306 err = commit_path_changed_in_worktree(&wcpa, id,
9307 worktree, repo);
9308 if (err)
9309 goto done;
9311 if (add_logmsg) {
9312 if (f == NULL) {
9313 err = got_opentemp_named(logmsg_path, &f,
9314 "got-commit-logmsg", "");
9315 if (err)
9316 goto done;
9318 err = cat_logmsg(f, commit, refname, type,
9319 added_logmsg);
9320 if (err)
9321 goto done;
9322 if (!added_logmsg)
9323 ++added_logmsg;
9325 err = got_reflist_entry_dup(&re_match, re);
9326 if (err)
9327 goto done;
9328 TAILQ_INSERT_HEAD(matched_refs, re_match, entry);
9331 got_object_commit_close(commit);
9332 commit = NULL;
9333 free(id);
9334 id = NULL;
9337 done:
9338 free(id);
9339 free(uuidstr);
9340 got_ref_list_free(&refs);
9341 if (commit)
9342 got_object_commit_close(commit);
9343 if (f && fclose(f) == EOF && err == NULL)
9344 err = got_error_from_errno("fclose");
9345 if (!added_logmsg) {
9346 if (*logmsg_path && unlink(*logmsg_path) != 0 && err == NULL)
9347 err = got_error_from_errno2("unlink", *logmsg_path);
9348 *logmsg_path = NULL;
9350 return err;
9353 static const struct got_error *
9354 cmd_commit(int argc, char *argv[])
9356 const struct got_error *error = NULL;
9357 struct got_worktree *worktree = NULL;
9358 struct got_repository *repo = NULL;
9359 char *cwd = NULL, *id_str = NULL;
9360 struct got_object_id *id = NULL;
9361 const char *logmsg = NULL;
9362 char *prepared_logmsg = NULL, *merged_logmsg = NULL;
9363 struct collect_commit_logmsg_arg cl_arg;
9364 const char *author = NULL;
9365 char *gitconfig_path = NULL, *editor = NULL, *committer = NULL;
9366 int ch, rebase_in_progress, histedit_in_progress, preserve_logmsg = 0;
9367 int allow_bad_symlinks = 0, non_interactive = 0, merge_in_progress = 0;
9368 int show_diff = 1, commit_conflicts = 0;
9369 struct got_pathlist_head paths;
9370 struct got_reflist_head refs;
9371 struct got_reflist_entry *re;
9372 int *pack_fds = NULL;
9374 TAILQ_INIT(&refs);
9375 TAILQ_INIT(&paths);
9376 cl_arg.logmsg_path = NULL;
9378 #ifndef PROFILE
9379 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
9380 "unveil", NULL) == -1)
9381 err(1, "pledge");
9382 #endif
9384 while ((ch = getopt(argc, argv, "A:CF:m:NnS")) != -1) {
9385 switch (ch) {
9386 case 'A':
9387 author = optarg;
9388 error = valid_author(author);
9389 if (error)
9390 return error;
9391 break;
9392 case 'C':
9393 commit_conflicts = 1;
9394 break;
9395 case 'F':
9396 if (logmsg != NULL)
9397 option_conflict('F', 'm');
9398 prepared_logmsg = realpath(optarg, NULL);
9399 if (prepared_logmsg == NULL)
9400 return got_error_from_errno2("realpath",
9401 optarg);
9402 break;
9403 case 'm':
9404 if (prepared_logmsg)
9405 option_conflict('m', 'F');
9406 logmsg = optarg;
9407 break;
9408 case 'N':
9409 non_interactive = 1;
9410 break;
9411 case 'n':
9412 show_diff = 0;
9413 break;
9414 case 'S':
9415 allow_bad_symlinks = 1;
9416 break;
9417 default:
9418 usage_commit();
9419 /* NOTREACHED */
9423 argc -= optind;
9424 argv += optind;
9426 cwd = getcwd(NULL, 0);
9427 if (cwd == NULL) {
9428 error = got_error_from_errno("getcwd");
9429 goto done;
9432 error = got_repo_pack_fds_open(&pack_fds);
9433 if (error != NULL)
9434 goto done;
9436 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
9437 if (error) {
9438 if (error->code == GOT_ERR_NOT_WORKTREE)
9439 error = wrap_not_worktree_error(error, "commit", cwd);
9440 goto done;
9443 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
9444 if (error)
9445 goto done;
9446 if (rebase_in_progress) {
9447 error = got_error(GOT_ERR_REBASING);
9448 goto done;
9451 error = got_worktree_histedit_in_progress(&histedit_in_progress,
9452 worktree);
9453 if (error)
9454 goto done;
9456 error = get_gitconfig_path(&gitconfig_path);
9457 if (error)
9458 goto done;
9459 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
9460 gitconfig_path, pack_fds);
9461 if (error != NULL)
9462 goto done;
9464 error = got_worktree_merge_in_progress(&merge_in_progress, worktree, repo);
9465 if (error)
9466 goto done;
9467 if (merge_in_progress) {
9468 error = got_error(GOT_ERR_MERGE_BUSY);
9469 goto done;
9472 error = get_author(&committer, repo, worktree);
9473 if (error)
9474 goto done;
9476 if (author == NULL)
9477 author = committer;
9479 if (logmsg == NULL || strlen(logmsg) == 0) {
9480 error = get_editor(&editor);
9481 if (error)
9482 goto done;
9483 if (unveil(editor, "x") != 0) {
9484 error = got_error_from_errno2("unveil", editor);
9485 goto done;
9488 if (prepared_logmsg) {
9489 if (unveil(prepared_logmsg, "r") != 0) {
9490 error = got_error_from_errno2("unveil",
9491 prepared_logmsg);
9492 goto done;
9496 error = apply_unveil(got_repo_get_path(repo), 0,
9497 got_worktree_get_root_path(worktree));
9498 if (error)
9499 goto done;
9501 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
9502 if (error)
9503 goto done;
9505 if (prepared_logmsg == NULL) {
9506 error = lookup_logmsg_ref(&merged_logmsg,
9507 argc > 0 ? &paths : NULL, &refs, worktree, repo);
9508 if (error)
9509 goto done;
9512 cl_arg.editor = editor;
9513 cl_arg.cmdline_log = logmsg;
9514 cl_arg.prepared_log = prepared_logmsg;
9515 cl_arg.merged_log = merged_logmsg;
9516 cl_arg.non_interactive = non_interactive;
9517 cl_arg.worktree_path = got_worktree_get_root_path(worktree);
9518 cl_arg.branch_name = got_worktree_get_head_ref_name(worktree);
9519 if (!histedit_in_progress) {
9520 if (strncmp(cl_arg.branch_name, "refs/heads/", 11) != 0) {
9521 error = got_error(GOT_ERR_COMMIT_BRANCH);
9522 goto done;
9524 cl_arg.branch_name += 11;
9526 cl_arg.repo_path = got_repo_get_path(repo);
9527 error = got_worktree_commit(&id, worktree, &paths, author, committer,
9528 allow_bad_symlinks, show_diff, commit_conflicts,
9529 collect_commit_logmsg, &cl_arg, print_status, NULL, repo);
9530 if (error) {
9531 if (error->code != GOT_ERR_COMMIT_MSG_EMPTY &&
9532 cl_arg.logmsg_path != NULL)
9533 preserve_logmsg = 1;
9534 goto done;
9537 error = got_object_id_str(&id_str, id);
9538 if (error)
9539 goto done;
9540 printf("Created commit %s\n", id_str);
9542 TAILQ_FOREACH(re, &refs, entry) {
9543 error = got_ref_delete(re->ref, repo);
9544 if (error)
9545 goto done;
9548 done:
9549 if (preserve_logmsg) {
9550 fprintf(stderr, "%s: log message preserved in %s\n",
9551 getprogname(), cl_arg.logmsg_path);
9552 } else if (cl_arg.logmsg_path && unlink(cl_arg.logmsg_path) == -1 &&
9553 error == NULL)
9554 error = got_error_from_errno2("unlink", cl_arg.logmsg_path);
9555 free(cl_arg.logmsg_path);
9556 if (merged_logmsg && unlink(merged_logmsg) == -1 && error == NULL)
9557 error = got_error_from_errno2("unlink", merged_logmsg);
9558 free(merged_logmsg);
9559 if (repo) {
9560 const struct got_error *close_err = got_repo_close(repo);
9561 if (error == NULL)
9562 error = close_err;
9564 if (worktree)
9565 got_worktree_close(worktree);
9566 if (pack_fds) {
9567 const struct got_error *pack_err =
9568 got_repo_pack_fds_close(pack_fds);
9569 if (error == NULL)
9570 error = pack_err;
9572 got_ref_list_free(&refs);
9573 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
9574 free(cwd);
9575 free(id_str);
9576 free(gitconfig_path);
9577 free(editor);
9578 free(committer);
9579 free(prepared_logmsg);
9580 return error;
9583 __dead static void
9584 usage_send(void)
9586 fprintf(stderr, "usage: %s send [-afqTv] [-b branch] [-d branch] "
9587 "[-r repository-path] [-t tag] [remote-repository]\n",
9588 getprogname());
9589 exit(1);
9592 static void
9593 print_load_info(int print_colored, int print_found, int print_trees,
9594 int ncolored, int nfound, int ntrees)
9596 if (print_colored) {
9597 printf("%d commit%s colored", ncolored,
9598 ncolored == 1 ? "" : "s");
9600 if (print_found) {
9601 printf("%s%d object%s found",
9602 ncolored > 0 ? "; " : "",
9603 nfound, nfound == 1 ? "" : "s");
9605 if (print_trees) {
9606 printf("; %d tree%s scanned", ntrees,
9607 ntrees == 1 ? "" : "s");
9611 struct got_send_progress_arg {
9612 char last_scaled_packsize[FMT_SCALED_STRSIZE];
9613 int verbosity;
9614 int last_ncolored;
9615 int last_nfound;
9616 int last_ntrees;
9617 int loading_done;
9618 int last_ncommits;
9619 int last_nobj_total;
9620 int last_p_deltify;
9621 int last_p_written;
9622 int last_p_sent;
9623 int printed_something;
9624 int sent_something;
9625 struct got_pathlist_head *delete_branches;
9628 static const struct got_error *
9629 send_progress(void *arg, int ncolored, int nfound, int ntrees,
9630 off_t packfile_size, int ncommits, int nobj_total, int nobj_deltify,
9631 int nobj_written, off_t bytes_sent, const char *refname,
9632 const char *errmsg, int success)
9634 struct got_send_progress_arg *a = arg;
9635 char scaled_packsize[FMT_SCALED_STRSIZE];
9636 char scaled_sent[FMT_SCALED_STRSIZE];
9637 int p_deltify = 0, p_written = 0, p_sent = 0;
9638 int print_colored = 0, print_found = 0, print_trees = 0;
9639 int print_searching = 0, print_total = 0;
9640 int print_deltify = 0, print_written = 0, print_sent = 0;
9642 if (a->verbosity < 0)
9643 return NULL;
9645 if (refname) {
9646 const char *status = success ? "accepted" : "rejected";
9648 if (success) {
9649 struct got_pathlist_entry *pe;
9650 TAILQ_FOREACH(pe, a->delete_branches, entry) {
9651 const char *branchname = pe->path;
9652 if (got_path_cmp(branchname, refname,
9653 strlen(branchname), strlen(refname)) == 0) {
9654 status = "deleted";
9655 a->sent_something = 1;
9656 break;
9661 if (a->printed_something)
9662 putchar('\n');
9663 printf("Server has %s %s", status, refname);
9664 if (errmsg)
9665 printf(": %s", errmsg);
9666 a->printed_something = 1;
9667 return NULL;
9670 if (a->last_ncolored != ncolored) {
9671 print_colored = 1;
9672 a->last_ncolored = ncolored;
9675 if (a->last_nfound != nfound) {
9676 print_colored = 1;
9677 print_found = 1;
9678 a->last_nfound = nfound;
9681 if (a->last_ntrees != ntrees) {
9682 print_colored = 1;
9683 print_found = 1;
9684 print_trees = 1;
9685 a->last_ntrees = ntrees;
9688 if ((print_colored || print_found || print_trees) &&
9689 !a->loading_done) {
9690 printf("\r");
9691 print_load_info(print_colored, print_found, print_trees,
9692 ncolored, nfound, ntrees);
9693 a->printed_something = 1;
9694 fflush(stdout);
9695 return NULL;
9696 } else if (!a->loading_done) {
9697 printf("\r");
9698 print_load_info(1, 1, 1, ncolored, nfound, ntrees);
9699 printf("\n");
9700 a->loading_done = 1;
9703 if (fmt_scaled(packfile_size, scaled_packsize) == -1)
9704 return got_error_from_errno("fmt_scaled");
9705 if (fmt_scaled(bytes_sent, scaled_sent) == -1)
9706 return got_error_from_errno("fmt_scaled");
9708 if (a->last_ncommits != ncommits) {
9709 print_searching = 1;
9710 a->last_ncommits = ncommits;
9713 if (a->last_nobj_total != nobj_total) {
9714 print_searching = 1;
9715 print_total = 1;
9716 a->last_nobj_total = nobj_total;
9719 if (packfile_size > 0 && (a->last_scaled_packsize[0] == '\0' ||
9720 strcmp(scaled_packsize, a->last_scaled_packsize)) != 0) {
9721 if (strlcpy(a->last_scaled_packsize, scaled_packsize,
9722 FMT_SCALED_STRSIZE) >= FMT_SCALED_STRSIZE)
9723 return got_error(GOT_ERR_NO_SPACE);
9726 if (nobj_deltify > 0 || nobj_written > 0) {
9727 if (nobj_deltify > 0) {
9728 p_deltify = (nobj_deltify * 100) / nobj_total;
9729 if (p_deltify != a->last_p_deltify) {
9730 a->last_p_deltify = p_deltify;
9731 print_searching = 1;
9732 print_total = 1;
9733 print_deltify = 1;
9736 if (nobj_written > 0) {
9737 p_written = (nobj_written * 100) / nobj_total;
9738 if (p_written != a->last_p_written) {
9739 a->last_p_written = p_written;
9740 print_searching = 1;
9741 print_total = 1;
9742 print_deltify = 1;
9743 print_written = 1;
9748 if (bytes_sent > 0) {
9749 p_sent = (bytes_sent * 100) / packfile_size;
9750 if (p_sent != a->last_p_sent) {
9751 a->last_p_sent = p_sent;
9752 print_searching = 1;
9753 print_total = 1;
9754 print_deltify = 1;
9755 print_written = 1;
9756 print_sent = 1;
9758 a->sent_something = 1;
9761 if (print_searching || print_total || print_deltify || print_written ||
9762 print_sent)
9763 printf("\r");
9764 if (print_searching)
9765 printf("packing %d reference%s", ncommits,
9766 ncommits == 1 ? "" : "s");
9767 if (print_total)
9768 printf("; %d object%s", nobj_total,
9769 nobj_total == 1 ? "" : "s");
9770 if (print_deltify)
9771 printf("; deltify: %d%%", p_deltify);
9772 if (print_sent)
9773 printf("; uploading pack: %*s %d%%", FMT_SCALED_STRSIZE - 2,
9774 scaled_packsize, p_sent);
9775 else if (print_written)
9776 printf("; writing pack: %*s %d%%", FMT_SCALED_STRSIZE - 2,
9777 scaled_packsize, p_written);
9778 if (print_searching || print_total || print_deltify ||
9779 print_written || print_sent) {
9780 a->printed_something = 1;
9781 fflush(stdout);
9783 return NULL;
9786 static const struct got_error *
9787 cmd_send(int argc, char *argv[])
9789 const struct got_error *error = NULL;
9790 char *cwd = NULL, *repo_path = NULL;
9791 const char *remote_name;
9792 char *proto = NULL, *host = NULL, *port = NULL;
9793 char *repo_name = NULL, *server_path = NULL;
9794 const struct got_remote_repo *remotes;
9795 struct got_remote_repo *remote = NULL;
9796 int nremotes, nbranches = 0, ndelete_branches = 0;
9797 struct got_repository *repo = NULL;
9798 struct got_worktree *worktree = NULL;
9799 const struct got_gotconfig *repo_conf = NULL, *worktree_conf = NULL;
9800 struct got_pathlist_head branches;
9801 struct got_pathlist_head tags;
9802 struct got_reflist_head all_branches;
9803 struct got_reflist_head all_tags;
9804 struct got_pathlist_head delete_args;
9805 struct got_pathlist_head delete_branches;
9806 struct got_reflist_entry *re;
9807 struct got_pathlist_entry *pe;
9808 int i, ch, sendfd = -1, sendstatus;
9809 pid_t sendpid = -1;
9810 struct got_send_progress_arg spa;
9811 int verbosity = 0, overwrite_refs = 0;
9812 int send_all_branches = 0, send_all_tags = 0;
9813 struct got_reference *ref = NULL;
9814 int *pack_fds = NULL;
9816 TAILQ_INIT(&branches);
9817 TAILQ_INIT(&tags);
9818 TAILQ_INIT(&all_branches);
9819 TAILQ_INIT(&all_tags);
9820 TAILQ_INIT(&delete_args);
9821 TAILQ_INIT(&delete_branches);
9823 while ((ch = getopt(argc, argv, "ab:d:fqr:Tt:v")) != -1) {
9824 switch (ch) {
9825 case 'a':
9826 send_all_branches = 1;
9827 break;
9828 case 'b':
9829 error = got_pathlist_append(&branches, optarg, NULL);
9830 if (error)
9831 return error;
9832 nbranches++;
9833 break;
9834 case 'd':
9835 error = got_pathlist_append(&delete_args, optarg, NULL);
9836 if (error)
9837 return error;
9838 break;
9839 case 'f':
9840 overwrite_refs = 1;
9841 break;
9842 case 'q':
9843 verbosity = -1;
9844 break;
9845 case 'r':
9846 repo_path = realpath(optarg, NULL);
9847 if (repo_path == NULL)
9848 return got_error_from_errno2("realpath",
9849 optarg);
9850 got_path_strip_trailing_slashes(repo_path);
9851 break;
9852 case 'T':
9853 send_all_tags = 1;
9854 break;
9855 case 't':
9856 error = got_pathlist_append(&tags, optarg, NULL);
9857 if (error)
9858 return error;
9859 break;
9860 case 'v':
9861 if (verbosity < 0)
9862 verbosity = 0;
9863 else if (verbosity < 3)
9864 verbosity++;
9865 break;
9866 default:
9867 usage_send();
9868 /* NOTREACHED */
9871 argc -= optind;
9872 argv += optind;
9874 if (send_all_branches && !TAILQ_EMPTY(&branches))
9875 option_conflict('a', 'b');
9876 if (send_all_tags && !TAILQ_EMPTY(&tags))
9877 option_conflict('T', 't');
9880 if (argc == 0)
9881 remote_name = GOT_SEND_DEFAULT_REMOTE_NAME;
9882 else if (argc == 1)
9883 remote_name = argv[0];
9884 else
9885 usage_send();
9887 cwd = getcwd(NULL, 0);
9888 if (cwd == NULL) {
9889 error = got_error_from_errno("getcwd");
9890 goto done;
9893 error = got_repo_pack_fds_open(&pack_fds);
9894 if (error != NULL)
9895 goto done;
9897 if (repo_path == NULL) {
9898 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
9899 if (error && error->code != GOT_ERR_NOT_WORKTREE)
9900 goto done;
9901 else
9902 error = NULL;
9903 if (worktree) {
9904 repo_path =
9905 strdup(got_worktree_get_repo_path(worktree));
9906 if (repo_path == NULL)
9907 error = got_error_from_errno("strdup");
9908 if (error)
9909 goto done;
9910 } else {
9911 repo_path = strdup(cwd);
9912 if (repo_path == NULL) {
9913 error = got_error_from_errno("strdup");
9914 goto done;
9919 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
9920 if (error)
9921 goto done;
9923 if (worktree) {
9924 worktree_conf = got_worktree_get_gotconfig(worktree);
9925 if (worktree_conf) {
9926 got_gotconfig_get_remotes(&nremotes, &remotes,
9927 worktree_conf);
9928 for (i = 0; i < nremotes; i++) {
9929 if (strcmp(remotes[i].name, remote_name) == 0) {
9930 error = got_repo_remote_repo_dup(&remote,
9931 &remotes[i]);
9932 if (error)
9933 goto done;
9934 break;
9939 if (remote == NULL) {
9940 repo_conf = got_repo_get_gotconfig(repo);
9941 if (repo_conf) {
9942 got_gotconfig_get_remotes(&nremotes, &remotes,
9943 repo_conf);
9944 for (i = 0; i < nremotes; i++) {
9945 if (strcmp(remotes[i].name, remote_name) == 0) {
9946 error = got_repo_remote_repo_dup(&remote,
9947 &remotes[i]);
9948 if (error)
9949 goto done;
9950 break;
9955 if (remote == NULL) {
9956 got_repo_get_gitconfig_remotes(&nremotes, &remotes, repo);
9957 for (i = 0; i < nremotes; i++) {
9958 if (strcmp(remotes[i].name, remote_name) == 0) {
9959 error = got_repo_remote_repo_dup(&remote,
9960 &remotes[i]);
9961 if (error)
9962 goto done;
9963 break;
9967 if (remote == NULL) {
9968 error = got_error_path(remote_name, GOT_ERR_NO_REMOTE);
9969 goto done;
9972 error = got_dial_parse_uri(&proto, &host, &port, &server_path,
9973 &repo_name, remote->send_url);
9974 if (error)
9975 goto done;
9977 if (strcmp(proto, "git") == 0) {
9978 #ifndef PROFILE
9979 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
9980 "sendfd dns inet unveil", NULL) == -1)
9981 err(1, "pledge");
9982 #endif
9983 } else if (strcmp(proto, "git+ssh") == 0 ||
9984 strcmp(proto, "ssh") == 0) {
9985 #ifndef PROFILE
9986 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
9987 "sendfd unveil", NULL) == -1)
9988 err(1, "pledge");
9989 #endif
9990 } else if (strcmp(proto, "http") == 0 ||
9991 strcmp(proto, "git+http") == 0) {
9992 error = got_error_path(proto, GOT_ERR_NOT_IMPL);
9993 goto done;
9994 } else {
9995 error = got_error_path(proto, GOT_ERR_BAD_PROTO);
9996 goto done;
9999 error = got_dial_apply_unveil(proto);
10000 if (error)
10001 goto done;
10003 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
10004 if (error)
10005 goto done;
10007 if (send_all_branches) {
10008 error = got_ref_list(&all_branches, repo, "refs/heads",
10009 got_ref_cmp_by_name, NULL);
10010 if (error)
10011 goto done;
10012 TAILQ_FOREACH(re, &all_branches, entry) {
10013 const char *branchname = got_ref_get_name(re->ref);
10014 error = got_pathlist_append(&branches,
10015 branchname, NULL);
10016 if (error)
10017 goto done;
10018 nbranches++;
10020 } else if (nbranches == 0) {
10021 for (i = 0; i < remote->nsend_branches; i++) {
10022 error = got_pathlist_append(&branches,
10023 remote->send_branches[i], NULL);
10024 if (error)
10025 goto done;
10029 if (send_all_tags) {
10030 error = got_ref_list(&all_tags, repo, "refs/tags",
10031 got_ref_cmp_by_name, NULL);
10032 if (error)
10033 goto done;
10034 TAILQ_FOREACH(re, &all_tags, entry) {
10035 const char *tagname = got_ref_get_name(re->ref);
10036 error = got_pathlist_append(&tags,
10037 tagname, NULL);
10038 if (error)
10039 goto done;
10044 * To prevent accidents only branches in refs/heads/ can be deleted
10045 * with 'got send -d'.
10046 * Deleting anything else requires local repository access or Git.
10048 TAILQ_FOREACH(pe, &delete_args, entry) {
10049 const char *branchname = pe->path;
10050 char *s;
10051 struct got_pathlist_entry *new;
10052 if (strncmp(branchname, "refs/heads/", 11) == 0) {
10053 s = strdup(branchname);
10054 if (s == NULL) {
10055 error = got_error_from_errno("strdup");
10056 goto done;
10058 } else {
10059 if (asprintf(&s, "refs/heads/%s", branchname) == -1) {
10060 error = got_error_from_errno("asprintf");
10061 goto done;
10064 error = got_pathlist_insert(&new, &delete_branches, s, NULL);
10065 if (error || new == NULL /* duplicate */)
10066 free(s);
10067 if (error)
10068 goto done;
10069 ndelete_branches++;
10072 if (nbranches == 0 && ndelete_branches == 0) {
10073 struct got_reference *head_ref;
10074 if (worktree)
10075 error = got_ref_open(&head_ref, repo,
10076 got_worktree_get_head_ref_name(worktree), 0);
10077 else
10078 error = got_ref_open(&head_ref, repo, GOT_REF_HEAD, 0);
10079 if (error)
10080 goto done;
10081 if (got_ref_is_symbolic(head_ref)) {
10082 error = got_ref_resolve_symbolic(&ref, repo, head_ref);
10083 got_ref_close(head_ref);
10084 if (error)
10085 goto done;
10086 } else
10087 ref = head_ref;
10088 error = got_pathlist_append(&branches, got_ref_get_name(ref),
10089 NULL);
10090 if (error)
10091 goto done;
10092 nbranches++;
10095 if (worktree) {
10096 /* Release work tree lock. */
10097 got_worktree_close(worktree);
10098 worktree = NULL;
10101 if (verbosity >= 0) {
10102 printf("Connecting to \"%s\" %s://%s%s%s%s%s\n",
10103 remote->name, proto, host,
10104 port ? ":" : "", port ? port : "",
10105 *server_path == '/' ? "" : "/", server_path);
10108 error = got_send_connect(&sendpid, &sendfd, proto, host, port,
10109 server_path, verbosity);
10110 if (error)
10111 goto done;
10113 memset(&spa, 0, sizeof(spa));
10114 spa.last_scaled_packsize[0] = '\0';
10115 spa.last_p_deltify = -1;
10116 spa.last_p_written = -1;
10117 spa.verbosity = verbosity;
10118 spa.delete_branches = &delete_branches;
10119 error = got_send_pack(remote_name, &branches, &tags, &delete_branches,
10120 verbosity, overwrite_refs, sendfd, repo, send_progress, &spa,
10121 check_cancelled, NULL);
10122 if (spa.printed_something)
10123 putchar('\n');
10124 if (error)
10125 goto done;
10126 if (!spa.sent_something && verbosity >= 0)
10127 printf("Already up-to-date\n");
10128 done:
10129 if (sendpid > 0) {
10130 if (kill(sendpid, SIGTERM) == -1)
10131 error = got_error_from_errno("kill");
10132 if (waitpid(sendpid, &sendstatus, 0) == -1 && error == NULL)
10133 error = got_error_from_errno("waitpid");
10135 if (sendfd != -1 && close(sendfd) == -1 && error == NULL)
10136 error = got_error_from_errno("close");
10137 if (repo) {
10138 const struct got_error *close_err = got_repo_close(repo);
10139 if (error == NULL)
10140 error = close_err;
10142 if (worktree)
10143 got_worktree_close(worktree);
10144 if (pack_fds) {
10145 const struct got_error *pack_err =
10146 got_repo_pack_fds_close(pack_fds);
10147 if (error == NULL)
10148 error = pack_err;
10150 if (ref)
10151 got_ref_close(ref);
10152 got_repo_free_remote_repo_data(remote);
10153 free(remote);
10154 got_pathlist_free(&branches, GOT_PATHLIST_FREE_NONE);
10155 got_pathlist_free(&tags, GOT_PATHLIST_FREE_NONE);
10156 got_ref_list_free(&all_branches);
10157 got_ref_list_free(&all_tags);
10158 got_pathlist_free(&delete_args, GOT_PATHLIST_FREE_NONE);
10159 got_pathlist_free(&delete_branches, GOT_PATHLIST_FREE_PATH);
10160 free(cwd);
10161 free(repo_path);
10162 free(proto);
10163 free(host);
10164 free(port);
10165 free(server_path);
10166 free(repo_name);
10167 return error;
10171 * Print and if delete is set delete all ref_prefix references.
10172 * If wanted_ref is not NULL, only print or delete this reference.
10174 static const struct got_error *
10175 process_logmsg_refs(const char *ref_prefix, size_t prefix_len,
10176 const char *wanted_ref, int delete, struct got_worktree *worktree,
10177 struct got_repository *repo)
10179 const struct got_error *err;
10180 struct got_pathlist_head paths;
10181 struct got_reflist_head refs;
10182 struct got_reflist_entry *re;
10183 struct got_reflist_object_id_map *refs_idmap = NULL;
10184 struct got_commit_object *commit = NULL;
10185 struct got_object_id *id = NULL;
10186 const char *header_prefix;
10187 char *uuidstr = NULL;
10188 int found = 0;
10190 TAILQ_INIT(&refs);
10191 TAILQ_INIT(&paths);
10193 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, repo);
10194 if (err)
10195 goto done;
10197 err = got_reflist_object_id_map_create(&refs_idmap, &refs, repo);
10198 if (err)
10199 goto done;
10201 if (worktree != NULL) {
10202 err = got_worktree_get_uuid(&uuidstr, worktree);
10203 if (err)
10204 goto done;
10207 if (wanted_ref) {
10208 if (strncmp(wanted_ref, "refs/heads/", 11) == 0)
10209 wanted_ref += 11;
10212 if (strcmp(ref_prefix, GOT_WORKTREE_BACKOUT_REF_PREFIX) == 0)
10213 header_prefix = "backout";
10214 else
10215 header_prefix = "cherrypick";
10217 TAILQ_FOREACH(re, &refs, entry) {
10218 const char *refname, *wt;
10220 refname = got_ref_get_name(re->ref);
10222 err = check_cancelled(NULL);
10223 if (err)
10224 goto done;
10226 if (strncmp(refname, ref_prefix, prefix_len) == 0)
10227 refname += prefix_len + 1; /* skip '-' delimiter */
10228 else
10229 continue;
10231 wt = refname;
10233 if (worktree == NULL || strncmp(refname, uuidstr,
10234 GOT_WORKTREE_UUID_STRLEN) == 0)
10235 refname += GOT_WORKTREE_UUID_STRLEN + 1; /* skip '-' */
10236 else
10237 continue;
10239 err = got_repo_match_object_id(&id, NULL, refname,
10240 GOT_OBJ_TYPE_COMMIT, NULL, repo);
10241 if (err)
10242 goto done;
10244 err = got_object_open_as_commit(&commit, repo, id);
10245 if (err)
10246 goto done;
10248 if (wanted_ref)
10249 found = strncmp(wanted_ref, refname,
10250 strlen(wanted_ref)) == 0;
10251 if (wanted_ref && !found) {
10252 struct got_reflist_head *ci_refs;
10254 ci_refs = got_reflist_object_id_map_lookup(refs_idmap,
10255 id);
10257 if (ci_refs) {
10258 char *refs_str = NULL;
10259 char const *r = NULL;
10261 err = build_refs_str(&refs_str, ci_refs, id,
10262 repo, 1);
10263 if (err)
10264 goto done;
10266 r = refs_str;
10267 while (r) {
10268 if (strncmp(r, wanted_ref,
10269 strlen(wanted_ref)) == 0) {
10270 found = 1;
10271 break;
10273 r = strchr(r, ' ');
10274 if (r)
10275 ++r;
10277 free(refs_str);
10281 if (wanted_ref == NULL || found) {
10282 if (delete) {
10283 err = got_ref_delete(re->ref, repo);
10284 if (err)
10285 goto done;
10286 printf("Deleted: ");
10287 err = print_commit_oneline(commit, id, repo,
10288 refs_idmap);
10289 } else {
10291 * Print paths modified by commit to help
10292 * associate commits with worktree changes.
10294 err = get_changed_paths(&paths, commit,
10295 repo, NULL);
10296 if (err)
10297 goto done;
10299 err = print_commit(commit, id, repo, NULL,
10300 &paths, NULL, 0, 0, refs_idmap, NULL,
10301 header_prefix);
10302 got_pathlist_free(&paths,
10303 GOT_PATHLIST_FREE_ALL);
10305 if (worktree == NULL)
10306 printf("work tree: %.*s\n\n",
10307 GOT_WORKTREE_UUID_STRLEN, wt);
10309 if (err || found)
10310 goto done;
10313 got_object_commit_close(commit);
10314 commit = NULL;
10315 free(id);
10316 id = NULL;
10319 if (wanted_ref != NULL && !found)
10320 err = got_error_fmt(GOT_ERR_NOT_REF, "%s", wanted_ref);
10322 done:
10323 free(id);
10324 free(uuidstr);
10325 got_ref_list_free(&refs);
10326 got_pathlist_free(&paths, GOT_PATHLIST_FREE_ALL);
10327 if (refs_idmap)
10328 got_reflist_object_id_map_free(refs_idmap);
10329 if (commit)
10330 got_object_commit_close(commit);
10331 return err;
10335 * Create new temp "logmsg" ref of the backed-out or cherrypicked commit
10336 * identified by id for log messages to prepopulate the editor on commit.
10338 static const struct got_error *
10339 logmsg_ref(struct got_object_id *id, const char *prefix,
10340 struct got_worktree *worktree, struct got_repository *repo)
10342 const struct got_error *err = NULL;
10343 char *idstr, *ref = NULL, *refname = NULL;
10344 int histedit_in_progress;
10345 int rebase_in_progress, merge_in_progress;
10348 * Silenty refuse to create merge reference if any histedit, merge,
10349 * or rebase operation is in progress.
10351 err = got_worktree_histedit_in_progress(&histedit_in_progress,
10352 worktree);
10353 if (err)
10354 return err;
10355 if (histedit_in_progress)
10356 return NULL;
10358 err = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
10359 if (err)
10360 return err;
10361 if (rebase_in_progress)
10362 return NULL;
10364 err = got_worktree_merge_in_progress(&merge_in_progress, worktree,
10365 repo);
10366 if (err)
10367 return err;
10368 if (merge_in_progress)
10369 return NULL;
10371 err = got_object_id_str(&idstr, id);
10372 if (err)
10373 return err;
10375 err = got_worktree_get_logmsg_ref_name(&refname, worktree, prefix);
10376 if (err)
10377 goto done;
10379 if (asprintf(&ref, "%s-%s", refname, idstr) == -1) {
10380 err = got_error_from_errno("asprintf");
10381 goto done;
10384 err = create_ref(ref, got_worktree_get_base_commit_id(worktree),
10385 -1, repo);
10386 done:
10387 free(ref);
10388 free(idstr);
10389 free(refname);
10390 return err;
10393 __dead static void
10394 usage_cherrypick(void)
10396 fprintf(stderr, "usage: %s cherrypick [-lX] [commit-id]\n",
10397 getprogname());
10398 exit(1);
10401 static const struct got_error *
10402 cmd_cherrypick(int argc, char *argv[])
10404 const struct got_error *error = NULL;
10405 struct got_worktree *worktree = NULL;
10406 struct got_repository *repo = NULL;
10407 char *cwd = NULL, *commit_id_str = NULL, *keyword_idstr = NULL;
10408 struct got_object_id *commit_id = NULL;
10409 struct got_commit_object *commit = NULL;
10410 struct got_object_qid *pid;
10411 int ch, list_refs = 0, remove_refs = 0;
10412 struct got_update_progress_arg upa;
10413 int *pack_fds = NULL;
10415 #ifndef PROFILE
10416 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
10417 "unveil", NULL) == -1)
10418 err(1, "pledge");
10419 #endif
10421 while ((ch = getopt(argc, argv, "lX")) != -1) {
10422 switch (ch) {
10423 case 'l':
10424 list_refs = 1;
10425 break;
10426 case 'X':
10427 remove_refs = 1;
10428 break;
10429 default:
10430 usage_cherrypick();
10431 /* NOTREACHED */
10435 argc -= optind;
10436 argv += optind;
10438 if (list_refs || remove_refs) {
10439 if (argc != 0 && argc != 1)
10440 usage_cherrypick();
10441 } else if (argc != 1)
10442 usage_cherrypick();
10443 if (list_refs && remove_refs)
10444 option_conflict('l', 'X');
10446 cwd = getcwd(NULL, 0);
10447 if (cwd == NULL) {
10448 error = got_error_from_errno("getcwd");
10449 goto done;
10452 error = got_repo_pack_fds_open(&pack_fds);
10453 if (error != NULL)
10454 goto done;
10456 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
10457 if (error) {
10458 if (list_refs || remove_refs) {
10459 if (error->code != GOT_ERR_NOT_WORKTREE)
10460 goto done;
10461 } else {
10462 if (error->code == GOT_ERR_NOT_WORKTREE)
10463 error = wrap_not_worktree_error(error,
10464 "cherrypick", cwd);
10465 goto done;
10469 error = got_repo_open(&repo,
10470 worktree ? got_worktree_get_repo_path(worktree) : cwd,
10471 NULL, pack_fds);
10472 if (error != NULL)
10473 goto done;
10475 error = apply_unveil(got_repo_get_path(repo), 0,
10476 worktree ? got_worktree_get_root_path(worktree) : NULL);
10477 if (error)
10478 goto done;
10480 if (list_refs || remove_refs) {
10481 error = process_logmsg_refs(GOT_WORKTREE_CHERRYPICK_REF_PREFIX,
10482 GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN,
10483 argc == 1 ? argv[0] : NULL, remove_refs, worktree, repo);
10484 goto done;
10487 error = got_keyword_to_idstr(&keyword_idstr, argv[0], repo, worktree);
10488 if (error != NULL)
10489 goto done;
10491 error = got_repo_match_object_id(&commit_id, NULL,
10492 keyword_idstr != NULL ? keyword_idstr : argv[0],
10493 GOT_OBJ_TYPE_COMMIT, NULL, repo);
10494 if (error)
10495 goto done;
10496 error = got_object_id_str(&commit_id_str, commit_id);
10497 if (error)
10498 goto done;
10500 error = got_object_open_as_commit(&commit, repo, commit_id);
10501 if (error)
10502 goto done;
10503 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
10504 memset(&upa, 0, sizeof(upa));
10505 error = got_worktree_merge_files(worktree, pid ? &pid->id : NULL,
10506 commit_id, repo, update_progress, &upa, check_cancelled,
10507 NULL);
10508 if (error != NULL)
10509 goto done;
10511 if (upa.did_something) {
10512 error = logmsg_ref(commit_id,
10513 GOT_WORKTREE_CHERRYPICK_REF_PREFIX, worktree, repo);
10514 if (error)
10515 goto done;
10516 printf("Merged commit %s\n", commit_id_str);
10518 print_merge_progress_stats(&upa);
10519 done:
10520 free(cwd);
10521 free(keyword_idstr);
10522 if (commit)
10523 got_object_commit_close(commit);
10524 free(commit_id_str);
10525 if (worktree)
10526 got_worktree_close(worktree);
10527 if (repo) {
10528 const struct got_error *close_err = got_repo_close(repo);
10529 if (error == NULL)
10530 error = close_err;
10532 if (pack_fds) {
10533 const struct got_error *pack_err =
10534 got_repo_pack_fds_close(pack_fds);
10535 if (error == NULL)
10536 error = pack_err;
10539 return error;
10542 __dead static void
10543 usage_backout(void)
10545 fprintf(stderr, "usage: %s backout [-lX] [commit-id]\n", getprogname());
10546 exit(1);
10549 static const struct got_error *
10550 cmd_backout(int argc, char *argv[])
10552 const struct got_error *error = NULL;
10553 struct got_worktree *worktree = NULL;
10554 struct got_repository *repo = NULL;
10555 char *cwd = NULL, *commit_id_str = NULL, *keyword_idstr = NULL;
10556 struct got_object_id *commit_id = NULL;
10557 struct got_commit_object *commit = NULL;
10558 struct got_object_qid *pid;
10559 int ch, list_refs = 0, remove_refs = 0;
10560 struct got_update_progress_arg upa;
10561 int *pack_fds = NULL;
10563 #ifndef PROFILE
10564 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
10565 "unveil", NULL) == -1)
10566 err(1, "pledge");
10567 #endif
10569 while ((ch = getopt(argc, argv, "lX")) != -1) {
10570 switch (ch) {
10571 case 'l':
10572 list_refs = 1;
10573 break;
10574 case 'X':
10575 remove_refs = 1;
10576 break;
10577 default:
10578 usage_backout();
10579 /* NOTREACHED */
10583 argc -= optind;
10584 argv += optind;
10586 if (list_refs || remove_refs) {
10587 if (argc != 0 && argc != 1)
10588 usage_backout();
10589 } else if (argc != 1)
10590 usage_backout();
10591 if (list_refs && remove_refs)
10592 option_conflict('l', 'X');
10594 cwd = getcwd(NULL, 0);
10595 if (cwd == NULL) {
10596 error = got_error_from_errno("getcwd");
10597 goto done;
10600 error = got_repo_pack_fds_open(&pack_fds);
10601 if (error != NULL)
10602 goto done;
10604 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
10605 if (error) {
10606 if (list_refs || remove_refs) {
10607 if (error->code != GOT_ERR_NOT_WORKTREE)
10608 goto done;
10609 } else {
10610 if (error->code == GOT_ERR_NOT_WORKTREE)
10611 error = wrap_not_worktree_error(error,
10612 "backout", cwd);
10613 goto done;
10617 error = got_repo_open(&repo,
10618 worktree ? got_worktree_get_repo_path(worktree) : cwd,
10619 NULL, pack_fds);
10620 if (error != NULL)
10621 goto done;
10623 error = apply_unveil(got_repo_get_path(repo), 0,
10624 worktree ? got_worktree_get_root_path(worktree) : NULL);
10625 if (error)
10626 goto done;
10628 if (list_refs || remove_refs) {
10629 error = process_logmsg_refs(GOT_WORKTREE_BACKOUT_REF_PREFIX,
10630 GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN,
10631 argc == 1 ? argv[0] : NULL, remove_refs, worktree, repo);
10632 goto done;
10635 error = got_keyword_to_idstr(&keyword_idstr, argv[0], repo, worktree);
10636 if (error != NULL)
10637 goto done;
10639 error = got_repo_match_object_id(&commit_id, NULL,
10640 keyword_idstr != NULL ? keyword_idstr : argv[0],
10641 GOT_OBJ_TYPE_COMMIT, NULL, repo);
10642 if (error)
10643 goto done;
10644 error = got_object_id_str(&commit_id_str, commit_id);
10645 if (error)
10646 goto done;
10648 error = got_object_open_as_commit(&commit, repo, commit_id);
10649 if (error)
10650 goto done;
10651 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
10652 if (pid == NULL) {
10653 error = got_error(GOT_ERR_ROOT_COMMIT);
10654 goto done;
10657 memset(&upa, 0, sizeof(upa));
10658 error = got_worktree_merge_files(worktree, commit_id, &pid->id,
10659 repo, update_progress, &upa, check_cancelled, NULL);
10660 if (error != NULL)
10661 goto done;
10663 if (upa.did_something) {
10664 error = logmsg_ref(commit_id, GOT_WORKTREE_BACKOUT_REF_PREFIX,
10665 worktree, repo);
10666 if (error)
10667 goto done;
10668 printf("Backed out commit %s\n", commit_id_str);
10670 print_merge_progress_stats(&upa);
10671 done:
10672 free(cwd);
10673 free(keyword_idstr);
10674 if (commit)
10675 got_object_commit_close(commit);
10676 free(commit_id_str);
10677 if (worktree)
10678 got_worktree_close(worktree);
10679 if (repo) {
10680 const struct got_error *close_err = got_repo_close(repo);
10681 if (error == NULL)
10682 error = close_err;
10684 if (pack_fds) {
10685 const struct got_error *pack_err =
10686 got_repo_pack_fds_close(pack_fds);
10687 if (error == NULL)
10688 error = pack_err;
10690 return error;
10693 __dead static void
10694 usage_rebase(void)
10696 fprintf(stderr, "usage: %s rebase [-aCclX] [branch]\n", getprogname());
10697 exit(1);
10700 static void
10701 trim_logmsg(char *logmsg, int limit)
10703 char *nl;
10704 size_t len;
10706 len = strlen(logmsg);
10707 if (len > limit)
10708 len = limit;
10709 logmsg[len] = '\0';
10710 nl = strchr(logmsg, '\n');
10711 if (nl)
10712 *nl = '\0';
10715 static const struct got_error *
10716 get_short_logmsg(char **logmsg, int limit, struct got_commit_object *commit)
10718 const struct got_error *err;
10719 char *logmsg0 = NULL;
10720 const char *s;
10722 err = got_object_commit_get_logmsg(&logmsg0, commit);
10723 if (err)
10724 return err;
10726 s = logmsg0;
10727 while (isspace((unsigned char)s[0]))
10728 s++;
10730 *logmsg = strdup(s);
10731 if (*logmsg == NULL) {
10732 err = got_error_from_errno("strdup");
10733 goto done;
10736 trim_logmsg(*logmsg, limit);
10737 done:
10738 free(logmsg0);
10739 return err;
10742 static const struct got_error *
10743 show_rebase_merge_conflict(struct got_object_id *id,
10744 struct got_repository *repo)
10746 const struct got_error *err;
10747 struct got_commit_object *commit = NULL;
10748 char *id_str = NULL, *logmsg = NULL;
10750 err = got_object_open_as_commit(&commit, repo, id);
10751 if (err)
10752 return err;
10754 err = got_object_id_str(&id_str, id);
10755 if (err)
10756 goto done;
10758 id_str[12] = '\0';
10760 err = get_short_logmsg(&logmsg, 42, commit);
10761 if (err)
10762 goto done;
10764 printf("%s -> merge conflict: %s\n", id_str, logmsg);
10765 done:
10766 free(id_str);
10767 got_object_commit_close(commit);
10768 free(logmsg);
10769 return err;
10772 static const struct got_error *
10773 show_rebase_progress(struct got_commit_object *commit,
10774 struct got_object_id *old_id, struct got_object_id *new_id)
10776 const struct got_error *err;
10777 char *old_id_str = NULL, *new_id_str = NULL, *logmsg = NULL;
10779 err = got_object_id_str(&old_id_str, old_id);
10780 if (err)
10781 goto done;
10783 if (new_id) {
10784 err = got_object_id_str(&new_id_str, new_id);
10785 if (err)
10786 goto done;
10789 old_id_str[12] = '\0';
10790 if (new_id_str)
10791 new_id_str[12] = '\0';
10793 err = get_short_logmsg(&logmsg, 42, commit);
10794 if (err)
10795 goto done;
10797 printf("%s -> %s: %s\n", old_id_str,
10798 new_id_str ? new_id_str : "no-op change", logmsg);
10799 done:
10800 free(old_id_str);
10801 free(new_id_str);
10802 free(logmsg);
10803 return err;
10806 static const struct got_error *
10807 rebase_complete(struct got_worktree *worktree, struct got_fileindex *fileindex,
10808 struct got_reference *branch, struct got_reference *tmp_branch,
10809 struct got_repository *repo, int create_backup)
10811 printf("Switching work tree to %s\n", got_ref_get_name(branch));
10812 return got_worktree_rebase_complete(worktree, fileindex,
10813 tmp_branch, branch, repo, create_backup);
10816 static const struct got_error *
10817 rebase_commit(struct got_pathlist_head *merged_paths,
10818 struct got_worktree *worktree, struct got_fileindex *fileindex,
10819 struct got_reference *tmp_branch, const char *committer,
10820 struct got_object_id *commit_id, int allow_conflict,
10821 struct got_repository *repo)
10823 const struct got_error *error;
10824 struct got_commit_object *commit;
10825 struct got_object_id *new_commit_id;
10827 error = got_object_open_as_commit(&commit, repo, commit_id);
10828 if (error)
10829 return error;
10831 error = got_worktree_rebase_commit(&new_commit_id, merged_paths,
10832 worktree, fileindex, tmp_branch, committer, commit, commit_id,
10833 allow_conflict, repo);
10834 if (error) {
10835 if (error->code != GOT_ERR_COMMIT_NO_CHANGES)
10836 goto done;
10837 error = show_rebase_progress(commit, commit_id, NULL);
10838 } else {
10839 error = show_rebase_progress(commit, commit_id, new_commit_id);
10840 free(new_commit_id);
10842 done:
10843 got_object_commit_close(commit);
10844 return error;
10847 struct check_path_prefix_arg {
10848 const char *path_prefix;
10849 size_t len;
10850 int errcode;
10853 static const struct got_error *
10854 check_path_prefix_in_diff(void *arg, struct got_blob_object *blob1,
10855 struct got_blob_object *blob2, FILE *f1, FILE *f2,
10856 struct got_object_id *id1, struct got_object_id *id2,
10857 const char *path1, const char *path2,
10858 mode_t mode1, mode_t mode2, struct got_repository *repo)
10860 struct check_path_prefix_arg *a = arg;
10862 if ((path1 && !got_path_is_child(path1, a->path_prefix, a->len)) ||
10863 (path2 && !got_path_is_child(path2, a->path_prefix, a->len)))
10864 return got_error(a->errcode);
10866 return NULL;
10869 static const struct got_error *
10870 check_path_prefix(struct got_object_id *parent_id,
10871 struct got_object_id *commit_id, const char *path_prefix,
10872 int errcode, struct got_repository *repo)
10874 const struct got_error *err;
10875 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
10876 struct got_commit_object *commit = NULL, *parent_commit = NULL;
10877 struct check_path_prefix_arg cpp_arg;
10879 if (got_path_is_root_dir(path_prefix))
10880 return NULL;
10882 err = got_object_open_as_commit(&commit, repo, commit_id);
10883 if (err)
10884 goto done;
10886 err = got_object_open_as_commit(&parent_commit, repo, parent_id);
10887 if (err)
10888 goto done;
10890 err = got_object_open_as_tree(&tree1, repo,
10891 got_object_commit_get_tree_id(parent_commit));
10892 if (err)
10893 goto done;
10895 err = got_object_open_as_tree(&tree2, repo,
10896 got_object_commit_get_tree_id(commit));
10897 if (err)
10898 goto done;
10900 cpp_arg.path_prefix = path_prefix;
10901 while (cpp_arg.path_prefix[0] == '/')
10902 cpp_arg.path_prefix++;
10903 cpp_arg.len = strlen(cpp_arg.path_prefix);
10904 cpp_arg.errcode = errcode;
10905 err = got_diff_tree(tree1, tree2, NULL, NULL, -1, -1, "", "", repo,
10906 check_path_prefix_in_diff, &cpp_arg, 0);
10907 done:
10908 if (tree1)
10909 got_object_tree_close(tree1);
10910 if (tree2)
10911 got_object_tree_close(tree2);
10912 if (commit)
10913 got_object_commit_close(commit);
10914 if (parent_commit)
10915 got_object_commit_close(parent_commit);
10916 return err;
10919 static const struct got_error *
10920 collect_commits(struct got_object_id_queue *commits,
10921 struct got_object_id *initial_commit_id,
10922 struct got_object_id *iter_start_id, struct got_object_id *iter_stop_id,
10923 const char *path_prefix, int path_prefix_errcode,
10924 struct got_repository *repo)
10926 const struct got_error *err = NULL;
10927 struct got_commit_graph *graph = NULL;
10928 struct got_object_id parent_id, commit_id;
10929 struct got_object_qid *qid;
10931 err = got_commit_graph_open(&graph, "/", 1);
10932 if (err)
10933 return err;
10935 err = got_commit_graph_bfsort(graph, iter_start_id, repo,
10936 check_cancelled, NULL);
10937 if (err)
10938 goto done;
10940 memcpy(&commit_id, initial_commit_id, sizeof(commit_id));
10941 while (got_object_id_cmp(&commit_id, iter_stop_id) != 0) {
10942 err = got_commit_graph_iter_next(&parent_id, graph, repo,
10943 check_cancelled, NULL);
10944 if (err) {
10945 if (err->code == GOT_ERR_ITER_COMPLETED) {
10946 err = got_error_msg(GOT_ERR_ANCESTRY,
10947 "ran out of commits to rebase before "
10948 "youngest common ancestor commit has "
10949 "been reached?!?");
10951 goto done;
10952 } else {
10953 err = check_path_prefix(&parent_id, &commit_id,
10954 path_prefix, path_prefix_errcode, repo);
10955 if (err)
10956 goto done;
10958 err = got_object_qid_alloc(&qid, &commit_id);
10959 if (err)
10960 goto done;
10961 STAILQ_INSERT_HEAD(commits, qid, entry);
10963 memcpy(&commit_id, &parent_id, sizeof(commit_id));
10966 done:
10967 got_commit_graph_close(graph);
10968 return err;
10971 static const struct got_error *
10972 get_commit_brief_str(char **brief_str, struct got_commit_object *commit)
10974 const struct got_error *err = NULL;
10975 time_t committer_time;
10976 struct tm tm;
10977 char datebuf[11]; /* YYYY-MM-DD + NUL */
10978 char *author0 = NULL, *author, *smallerthan;
10979 char *logmsg0 = NULL, *logmsg, *newline;
10981 committer_time = got_object_commit_get_committer_time(commit);
10982 if (gmtime_r(&committer_time, &tm) == NULL)
10983 return got_error_from_errno("gmtime_r");
10984 if (strftime(datebuf, sizeof(datebuf), "%F", &tm) == 0)
10985 return got_error(GOT_ERR_NO_SPACE);
10987 author0 = strdup(got_object_commit_get_author(commit));
10988 if (author0 == NULL)
10989 return got_error_from_errno("strdup");
10990 author = author0;
10991 smallerthan = strchr(author, '<');
10992 if (smallerthan && smallerthan[1] != '\0')
10993 author = smallerthan + 1;
10994 author[strcspn(author, "@>")] = '\0';
10996 err = got_object_commit_get_logmsg(&logmsg0, commit);
10997 if (err)
10998 goto done;
10999 logmsg = logmsg0;
11000 while (*logmsg == '\n')
11001 logmsg++;
11002 newline = strchr(logmsg, '\n');
11003 if (newline)
11004 *newline = '\0';
11006 if (asprintf(brief_str, "%s %s %s",
11007 datebuf, author, logmsg) == -1)
11008 err = got_error_from_errno("asprintf");
11009 done:
11010 free(author0);
11011 free(logmsg0);
11012 return err;
11015 static const struct got_error *
11016 delete_backup_ref(struct got_reference *ref, struct got_object_id *id,
11017 struct got_repository *repo)
11019 const struct got_error *err;
11020 char *id_str;
11022 err = got_object_id_str(&id_str, id);
11023 if (err)
11024 return err;
11026 err = got_ref_delete(ref, repo);
11027 if (err)
11028 goto done;
11030 printf("Deleted %s: %s\n", got_ref_get_name(ref), id_str);
11031 done:
11032 free(id_str);
11033 return err;
11036 static const struct got_error *
11037 print_backup_ref(const char *branch_name, const char *new_id_str,
11038 struct got_object_id *old_commit_id, struct got_commit_object *old_commit,
11039 struct got_reflist_object_id_map *refs_idmap,
11040 struct got_repository *repo)
11042 const struct got_error *err = NULL;
11043 struct got_reflist_head *refs;
11044 char *refs_str = NULL;
11045 struct got_object_id *new_commit_id = NULL;
11046 struct got_commit_object *new_commit = NULL;
11047 char *new_commit_brief_str = NULL;
11048 struct got_object_id *yca_id = NULL;
11049 struct got_commit_object *yca_commit = NULL;
11050 char *yca_id_str = NULL, *yca_brief_str = NULL;
11051 char *custom_refs_str;
11053 if (asprintf(&custom_refs_str, "formerly %s", branch_name) == -1)
11054 return got_error_from_errno("asprintf");
11056 err = print_commit(old_commit, old_commit_id, repo, NULL, NULL, NULL,
11057 0, 0, refs_idmap, custom_refs_str, NULL);
11058 if (err)
11059 goto done;
11061 err = got_object_resolve_id_str(&new_commit_id, repo, new_id_str);
11062 if (err)
11063 goto done;
11065 refs = got_reflist_object_id_map_lookup(refs_idmap, new_commit_id);
11066 if (refs) {
11067 err = build_refs_str(&refs_str, refs, new_commit_id, repo, 0);
11068 if (err)
11069 goto done;
11072 err = got_object_open_as_commit(&new_commit, repo, new_commit_id);
11073 if (err)
11074 goto done;
11076 err = get_commit_brief_str(&new_commit_brief_str, new_commit);
11077 if (err)
11078 goto done;
11080 err = got_commit_graph_find_youngest_common_ancestor(&yca_id,
11081 old_commit_id, new_commit_id, 1, 0, repo, check_cancelled, NULL);
11082 if (err)
11083 goto done;
11085 printf("has become commit %s%s%s%s\n %s\n", new_id_str,
11086 refs_str ? " (" : "", refs_str ? refs_str : "",
11087 refs_str ? ")" : "", new_commit_brief_str);
11088 if (yca_id && got_object_id_cmp(yca_id, new_commit_id) != 0 &&
11089 got_object_id_cmp(yca_id, old_commit_id) != 0) {
11090 free(refs_str);
11091 refs_str = NULL;
11093 err = got_object_open_as_commit(&yca_commit, repo, yca_id);
11094 if (err)
11095 goto done;
11097 err = get_commit_brief_str(&yca_brief_str, yca_commit);
11098 if (err)
11099 goto done;
11101 err = got_object_id_str(&yca_id_str, yca_id);
11102 if (err)
11103 goto done;
11105 refs = got_reflist_object_id_map_lookup(refs_idmap, yca_id);
11106 if (refs) {
11107 err = build_refs_str(&refs_str, refs, yca_id, repo, 0);
11108 if (err)
11109 goto done;
11111 printf("history forked at %s%s%s%s\n %s\n",
11112 yca_id_str,
11113 refs_str ? " (" : "", refs_str ? refs_str : "",
11114 refs_str ? ")" : "", yca_brief_str);
11116 done:
11117 free(custom_refs_str);
11118 free(new_commit_id);
11119 free(refs_str);
11120 free(yca_id);
11121 free(yca_id_str);
11122 free(yca_brief_str);
11123 if (new_commit)
11124 got_object_commit_close(new_commit);
11125 if (yca_commit)
11126 got_object_commit_close(yca_commit);
11128 return err;
11131 static const struct got_error *
11132 worktree_has_logmsg_ref(const char *caller, struct got_worktree *worktree,
11133 struct got_repository *repo)
11135 const struct got_error *err;
11136 struct got_reflist_head refs;
11137 struct got_reflist_entry *re;
11138 char *uuidstr = NULL;
11139 static char msg[160];
11141 TAILQ_INIT(&refs);
11143 err = got_worktree_get_uuid(&uuidstr, worktree);
11144 if (err)
11145 goto done;
11147 err = got_ref_list(&refs, repo, "refs/got/worktree",
11148 got_ref_cmp_by_name, repo);
11149 if (err)
11150 goto done;
11152 TAILQ_FOREACH(re, &refs, entry) {
11153 const char *cmd, *refname, *type;
11155 refname = got_ref_get_name(re->ref);
11157 if (strncmp(refname, GOT_WORKTREE_CHERRYPICK_REF_PREFIX,
11158 GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN) == 0) {
11159 refname += GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN + 1;
11160 cmd = "cherrypick";
11161 type = "cherrypicked";
11162 } else if (strncmp(refname, GOT_WORKTREE_BACKOUT_REF_PREFIX,
11163 GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN) == 0) {
11164 refname += GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN + 1;
11165 cmd = "backout";
11166 type = "backed-out";
11167 } else
11168 continue;
11170 if (strncmp(refname, uuidstr, GOT_WORKTREE_UUID_STRLEN) != 0)
11171 continue;
11173 snprintf(msg, sizeof(msg),
11174 "work tree has references created by %s commits which "
11175 "must be removed with 'got %s -X' before running the %s "
11176 "command", type, cmd, caller);
11177 err = got_error_msg(GOT_ERR_WORKTREE_META, msg);
11178 goto done;
11181 done:
11182 free(uuidstr);
11183 got_ref_list_free(&refs);
11184 return err;
11187 static const struct got_error *
11188 process_backup_refs(const char *backup_ref_prefix,
11189 const char *wanted_branch_name,
11190 int delete, struct got_repository *repo)
11192 const struct got_error *err;
11193 struct got_reflist_head refs, backup_refs;
11194 struct got_reflist_entry *re;
11195 const size_t backup_ref_prefix_len = strlen(backup_ref_prefix);
11196 struct got_object_id *old_commit_id = NULL;
11197 char *branch_name = NULL;
11198 struct got_commit_object *old_commit = NULL;
11199 struct got_reflist_object_id_map *refs_idmap = NULL;
11200 int wanted_branch_found = 0;
11202 TAILQ_INIT(&refs);
11203 TAILQ_INIT(&backup_refs);
11205 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
11206 if (err)
11207 return err;
11209 err = got_reflist_object_id_map_create(&refs_idmap, &refs, repo);
11210 if (err)
11211 goto done;
11213 if (wanted_branch_name) {
11214 if (strncmp(wanted_branch_name, "refs/heads/", 11) == 0)
11215 wanted_branch_name += 11;
11218 err = got_ref_list(&backup_refs, repo, backup_ref_prefix,
11219 got_ref_cmp_by_commit_timestamp_descending, repo);
11220 if (err)
11221 goto done;
11223 TAILQ_FOREACH(re, &backup_refs, entry) {
11224 const char *refname = got_ref_get_name(re->ref);
11225 char *slash;
11227 err = check_cancelled(NULL);
11228 if (err)
11229 break;
11231 err = got_ref_resolve(&old_commit_id, repo, re->ref);
11232 if (err)
11233 break;
11235 err = got_object_open_as_commit(&old_commit, repo,
11236 old_commit_id);
11237 if (err)
11238 break;
11240 if (strncmp(backup_ref_prefix, refname,
11241 backup_ref_prefix_len) == 0)
11242 refname += backup_ref_prefix_len;
11244 while (refname[0] == '/')
11245 refname++;
11247 branch_name = strdup(refname);
11248 if (branch_name == NULL) {
11249 err = got_error_from_errno("strdup");
11250 break;
11252 slash = strrchr(branch_name, '/');
11253 if (slash) {
11254 *slash = '\0';
11255 refname += strlen(branch_name) + 1;
11258 if (wanted_branch_name == NULL ||
11259 strcmp(wanted_branch_name, branch_name) == 0) {
11260 wanted_branch_found = 1;
11261 if (delete) {
11262 err = delete_backup_ref(re->ref,
11263 old_commit_id, repo);
11264 } else {
11265 err = print_backup_ref(branch_name, refname,
11266 old_commit_id, old_commit, refs_idmap,
11267 repo);
11269 if (err)
11270 break;
11273 free(old_commit_id);
11274 old_commit_id = NULL;
11275 free(branch_name);
11276 branch_name = NULL;
11277 got_object_commit_close(old_commit);
11278 old_commit = NULL;
11281 if (wanted_branch_name && !wanted_branch_found) {
11282 err = got_error_fmt(GOT_ERR_NOT_REF,
11283 "%s/%s/", backup_ref_prefix, wanted_branch_name);
11285 done:
11286 if (refs_idmap)
11287 got_reflist_object_id_map_free(refs_idmap);
11288 got_ref_list_free(&refs);
11289 got_ref_list_free(&backup_refs);
11290 free(old_commit_id);
11291 free(branch_name);
11292 if (old_commit)
11293 got_object_commit_close(old_commit);
11294 return err;
11297 static const struct got_error *
11298 abort_progress(void *arg, unsigned char status, const char *path)
11301 * Unversioned files should not clutter progress output when
11302 * an operation is aborted.
11304 if (status == GOT_STATUS_UNVERSIONED)
11305 return NULL;
11307 return update_progress(arg, status, path);
11310 static const struct got_error *
11311 find_merge_commit_yca(struct got_object_id **new_yca_id,
11312 struct got_object_id *branch_head_commit_id,
11313 struct got_object_id *yca_id,
11314 struct got_object_id *base_commit_id,
11315 struct got_repository *repo)
11317 const struct got_error *err = NULL;
11318 struct got_commit_graph *graph = NULL;
11319 struct got_commit_object *commit = NULL;
11321 *new_yca_id = NULL;
11323 err = got_commit_graph_open(&graph, "/", 1);
11324 if (err)
11325 return err;
11327 err = got_commit_graph_bfsort(graph, base_commit_id,
11328 repo, check_cancelled, NULL);
11329 if (err)
11330 goto done;
11332 for (;;) {
11333 struct got_object_id id;
11335 err = got_commit_graph_iter_next(&id, graph, repo,
11336 check_cancelled, NULL);
11337 if (err) {
11338 if (err->code == GOT_ERR_ITER_COMPLETED)
11339 err = NULL;
11340 break;
11343 err = got_object_open_as_commit(&commit, repo, &id);
11344 if (err)
11345 break;
11347 if (got_object_commit_get_nparents(commit) > 1) {
11348 /* Search for a better YCA using toposort. */
11349 err = got_commit_graph_find_youngest_common_ancestor(
11350 new_yca_id, base_commit_id, branch_head_commit_id,
11351 0, 1, repo, check_cancelled, NULL);
11352 break;
11355 if (got_object_id_cmp(&id, yca_id) == 0)
11356 break;
11357 got_object_commit_close(commit);
11358 commit = NULL;
11360 done:
11361 got_commit_graph_close(graph);
11362 if (commit)
11363 got_object_commit_close(commit);
11364 return err;
11367 static const struct got_error *
11368 cmd_rebase(int argc, char *argv[])
11370 const struct got_error *error = NULL;
11371 struct got_worktree *worktree = NULL;
11372 struct got_repository *repo = NULL;
11373 struct got_fileindex *fileindex = NULL;
11374 char *cwd = NULL, *committer = NULL, *gitconfig_path = NULL;
11375 struct got_reference *branch = NULL;
11376 struct got_reference *new_base_branch = NULL, *tmp_branch = NULL;
11377 struct got_object_id *commit_id = NULL, *parent_id = NULL;
11378 struct got_object_id *resume_commit_id = NULL;
11379 struct got_object_id *branch_head_commit_id = NULL, *yca_id = NULL;
11380 struct got_object_id *head_commit_id = NULL;
11381 struct got_reference *head_ref = NULL;
11382 struct got_commit_object *commit = NULL;
11383 int ch, rebase_in_progress = 0, abort_rebase = 0, continue_rebase = 0;
11384 int histedit_in_progress = 0, merge_in_progress = 0;
11385 int create_backup = 1, list_backups = 0, delete_backups = 0;
11386 int allow_conflict = 0;
11387 struct got_object_id_queue commits;
11388 struct got_pathlist_head merged_paths;
11389 const struct got_object_id_queue *parent_ids;
11390 struct got_object_qid *qid, *pid;
11391 struct got_update_progress_arg upa;
11392 int *pack_fds = NULL;
11394 STAILQ_INIT(&commits);
11395 TAILQ_INIT(&merged_paths);
11396 memset(&upa, 0, sizeof(upa));
11398 #ifndef PROFILE
11399 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
11400 "unveil", NULL) == -1)
11401 err(1, "pledge");
11402 #endif
11404 while ((ch = getopt(argc, argv, "aCclX")) != -1) {
11405 switch (ch) {
11406 case 'a':
11407 abort_rebase = 1;
11408 break;
11409 case 'C':
11410 allow_conflict = 1;
11411 break;
11412 case 'c':
11413 continue_rebase = 1;
11414 break;
11415 case 'l':
11416 list_backups = 1;
11417 break;
11418 case 'X':
11419 delete_backups = 1;
11420 break;
11421 default:
11422 usage_rebase();
11423 /* NOTREACHED */
11427 argc -= optind;
11428 argv += optind;
11430 if (list_backups) {
11431 if (abort_rebase)
11432 option_conflict('l', 'a');
11433 if (allow_conflict)
11434 option_conflict('l', 'C');
11435 if (continue_rebase)
11436 option_conflict('l', 'c');
11437 if (delete_backups)
11438 option_conflict('l', 'X');
11439 if (argc != 0 && argc != 1)
11440 usage_rebase();
11441 } else if (delete_backups) {
11442 if (abort_rebase)
11443 option_conflict('X', 'a');
11444 if (allow_conflict)
11445 option_conflict('X', 'C');
11446 if (continue_rebase)
11447 option_conflict('X', 'c');
11448 if (list_backups)
11449 option_conflict('l', 'X');
11450 if (argc != 0 && argc != 1)
11451 usage_rebase();
11452 } else if (allow_conflict) {
11453 if (abort_rebase)
11454 option_conflict('C', 'a');
11455 if (!continue_rebase)
11456 errx(1, "-C option requires -c");
11457 } else {
11458 if (abort_rebase && continue_rebase)
11459 usage_rebase();
11460 else if (abort_rebase || continue_rebase) {
11461 if (argc != 0)
11462 usage_rebase();
11463 } else if (argc != 1)
11464 usage_rebase();
11467 cwd = getcwd(NULL, 0);
11468 if (cwd == NULL) {
11469 error = got_error_from_errno("getcwd");
11470 goto done;
11473 error = got_repo_pack_fds_open(&pack_fds);
11474 if (error != NULL)
11475 goto done;
11477 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
11478 if (error) {
11479 if (list_backups || delete_backups) {
11480 if (error->code != GOT_ERR_NOT_WORKTREE)
11481 goto done;
11482 } else {
11483 if (error->code == GOT_ERR_NOT_WORKTREE)
11484 error = wrap_not_worktree_error(error,
11485 "rebase", cwd);
11486 goto done;
11490 error = get_gitconfig_path(&gitconfig_path);
11491 if (error)
11492 goto done;
11493 error = got_repo_open(&repo,
11494 worktree ? got_worktree_get_repo_path(worktree) : cwd,
11495 gitconfig_path, pack_fds);
11496 if (error != NULL)
11497 goto done;
11499 if (worktree != NULL && !list_backups && !delete_backups) {
11500 error = worktree_has_logmsg_ref("rebase", worktree, repo);
11501 if (error)
11502 goto done;
11505 error = get_author(&committer, repo, worktree);
11506 if (error && error->code != GOT_ERR_COMMIT_NO_AUTHOR)
11507 goto done;
11509 error = apply_unveil(got_repo_get_path(repo), 0,
11510 worktree ? got_worktree_get_root_path(worktree) : NULL);
11511 if (error)
11512 goto done;
11514 if (list_backups || delete_backups) {
11515 error = process_backup_refs(
11516 GOT_WORKTREE_REBASE_BACKUP_REF_PREFIX,
11517 argc == 1 ? argv[0] : NULL, delete_backups, repo);
11518 goto done; /* nothing else to do */
11521 error = got_worktree_histedit_in_progress(&histedit_in_progress,
11522 worktree);
11523 if (error)
11524 goto done;
11525 if (histedit_in_progress) {
11526 error = got_error(GOT_ERR_HISTEDIT_BUSY);
11527 goto done;
11530 error = got_worktree_merge_in_progress(&merge_in_progress,
11531 worktree, repo);
11532 if (error)
11533 goto done;
11534 if (merge_in_progress) {
11535 error = got_error(GOT_ERR_MERGE_BUSY);
11536 goto done;
11539 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
11540 if (error)
11541 goto done;
11543 if (abort_rebase) {
11544 if (!rebase_in_progress) {
11545 error = got_error(GOT_ERR_NOT_REBASING);
11546 goto done;
11548 error = got_worktree_rebase_continue(&resume_commit_id,
11549 &new_base_branch, &tmp_branch, &branch, &fileindex,
11550 worktree, repo);
11551 if (error)
11552 goto done;
11553 printf("Switching work tree to %s\n",
11554 got_ref_get_symref_target(new_base_branch));
11555 error = got_worktree_rebase_abort(worktree, fileindex, repo,
11556 new_base_branch, abort_progress, &upa);
11557 if (error)
11558 goto done;
11559 printf("Rebase of %s aborted\n", got_ref_get_name(branch));
11560 print_merge_progress_stats(&upa);
11561 goto done; /* nothing else to do */
11564 if (continue_rebase) {
11565 if (!rebase_in_progress) {
11566 error = got_error(GOT_ERR_NOT_REBASING);
11567 goto done;
11569 error = got_worktree_rebase_continue(&resume_commit_id,
11570 &new_base_branch, &tmp_branch, &branch, &fileindex,
11571 worktree, repo);
11572 if (error)
11573 goto done;
11575 error = rebase_commit(NULL, worktree, fileindex, tmp_branch,
11576 committer, resume_commit_id, allow_conflict, repo);
11577 if (error)
11578 goto done;
11580 yca_id = got_object_id_dup(resume_commit_id);
11581 if (yca_id == NULL) {
11582 error = got_error_from_errno("got_object_id_dup");
11583 goto done;
11585 } else {
11586 error = got_ref_open(&branch, repo, argv[0], 0);
11587 if (error != NULL)
11588 goto done;
11589 if (strncmp(got_ref_get_name(branch), "refs/heads/", 11) != 0) {
11590 error = got_error_msg(GOT_ERR_COMMIT_BRANCH,
11591 "will not rebase a branch which lives outside "
11592 "the \"refs/heads/\" reference namespace");
11593 goto done;
11597 error = got_ref_resolve(&branch_head_commit_id, repo, branch);
11598 if (error)
11599 goto done;
11601 if (!continue_rebase) {
11602 struct got_object_id *base_commit_id;
11604 error = got_ref_open(&head_ref, repo,
11605 got_worktree_get_head_ref_name(worktree), 0);
11606 if (error)
11607 goto done;
11608 error = got_ref_resolve(&head_commit_id, repo, head_ref);
11609 if (error)
11610 goto done;
11611 base_commit_id = got_worktree_get_base_commit_id(worktree);
11612 if (got_object_id_cmp(base_commit_id, head_commit_id) != 0) {
11613 error = got_error(GOT_ERR_REBASE_OUT_OF_DATE);
11614 goto done;
11617 error = got_commit_graph_find_youngest_common_ancestor(&yca_id,
11618 base_commit_id, branch_head_commit_id, 1, 0,
11619 repo, check_cancelled, NULL);
11620 if (error) {
11621 if (error->code == GOT_ERR_ANCESTRY) {
11622 error = got_error_msg(GOT_ERR_ANCESTRY,
11623 "specified branch shares no common "
11624 "ancestry with work tree's branch");
11626 goto done;
11630 * If a merge commit appears between the new base branch tip
11631 * and a YCA found via first-parent traversal then we might
11632 * find a better YCA using topologically sorted commits.
11634 if (got_object_id_cmp(base_commit_id, yca_id) != 0) {
11635 struct got_object_id *better_yca_id;
11636 error = find_merge_commit_yca(&better_yca_id,
11637 branch_head_commit_id, yca_id,
11638 base_commit_id, repo);
11639 if (error)
11640 goto done;
11641 if (better_yca_id) {
11642 free(yca_id);
11643 yca_id = better_yca_id;
11647 if (got_object_id_cmp(base_commit_id, yca_id) == 0) {
11648 struct got_pathlist_head paths;
11649 printf("%s is already based on %s\n",
11650 got_ref_get_name(branch),
11651 got_worktree_get_head_ref_name(worktree));
11652 error = switch_head_ref(branch, branch_head_commit_id,
11653 worktree, repo);
11654 if (error)
11655 goto done;
11656 error = got_worktree_set_base_commit_id(worktree, repo,
11657 branch_head_commit_id);
11658 if (error)
11659 goto done;
11660 TAILQ_INIT(&paths);
11661 error = got_pathlist_append(&paths, "", NULL);
11662 if (error)
11663 goto done;
11664 error = got_worktree_checkout_files(worktree,
11665 &paths, repo, update_progress, &upa,
11666 check_cancelled, NULL);
11667 got_pathlist_free(&paths, GOT_PATHLIST_FREE_NONE);
11668 if (error)
11669 goto done;
11670 if (upa.did_something) {
11671 char *id_str;
11672 error = got_object_id_str(&id_str,
11673 branch_head_commit_id);
11674 if (error)
11675 goto done;
11676 printf("Updated to %s: %s\n",
11677 got_worktree_get_head_ref_name(worktree),
11678 id_str);
11679 free(id_str);
11680 } else
11681 printf("Already up-to-date\n");
11682 print_update_progress_stats(&upa);
11683 goto done;
11687 commit_id = branch_head_commit_id;
11688 error = got_object_open_as_commit(&commit, repo, commit_id);
11689 if (error)
11690 goto done;
11692 parent_ids = got_object_commit_get_parent_ids(commit);
11693 pid = STAILQ_FIRST(parent_ids);
11694 if (pid) {
11695 error = collect_commits(&commits, commit_id, &pid->id,
11696 yca_id, got_worktree_get_path_prefix(worktree),
11697 GOT_ERR_REBASE_PATH, repo);
11698 if (error)
11699 goto done;
11702 got_object_commit_close(commit);
11703 commit = NULL;
11705 if (!continue_rebase) {
11706 error = got_worktree_rebase_prepare(&new_base_branch,
11707 &tmp_branch, &fileindex, worktree, branch, repo);
11708 if (error)
11709 goto done;
11712 if (STAILQ_EMPTY(&commits)) {
11713 if (continue_rebase) {
11714 error = rebase_complete(worktree, fileindex,
11715 branch, tmp_branch, repo, create_backup);
11716 goto done;
11717 } else {
11718 /* Fast-forward the reference of the branch. */
11719 struct got_object_id *new_head_commit_id;
11720 char *id_str;
11721 error = got_ref_resolve(&new_head_commit_id, repo,
11722 new_base_branch);
11723 if (error)
11724 goto done;
11725 error = got_object_id_str(&id_str, new_head_commit_id);
11726 if (error)
11727 goto done;
11728 printf("Forwarding %s to commit %s\n",
11729 got_ref_get_name(branch), id_str);
11730 free(id_str);
11731 error = got_ref_change_ref(branch,
11732 new_head_commit_id);
11733 if (error)
11734 goto done;
11735 /* No backup needed since objects did not change. */
11736 create_backup = 0;
11740 pid = NULL;
11741 STAILQ_FOREACH(qid, &commits, entry) {
11743 commit_id = &qid->id;
11744 parent_id = pid ? &pid->id : yca_id;
11745 pid = qid;
11747 memset(&upa, 0, sizeof(upa));
11748 error = got_worktree_rebase_merge_files(&merged_paths,
11749 worktree, fileindex, parent_id, commit_id, repo,
11750 update_progress, &upa, check_cancelled, NULL);
11751 if (error)
11752 goto done;
11754 print_merge_progress_stats(&upa);
11755 if (upa.conflicts > 0 || upa.missing > 0 ||
11756 upa.not_deleted > 0 || upa.unversioned > 0) {
11757 if (upa.conflicts > 0) {
11758 error = show_rebase_merge_conflict(&qid->id,
11759 repo);
11760 if (error)
11761 goto done;
11763 got_pathlist_free(&merged_paths, GOT_PATHLIST_FREE_PATH);
11764 break;
11767 error = rebase_commit(&merged_paths, worktree, fileindex,
11768 tmp_branch, committer, commit_id, 0, repo);
11769 got_pathlist_free(&merged_paths, GOT_PATHLIST_FREE_PATH);
11770 if (error)
11771 goto done;
11774 if (upa.conflicts > 0 || upa.missing > 0 ||
11775 upa.not_deleted > 0 || upa.unversioned > 0) {
11776 error = got_worktree_rebase_postpone(worktree, fileindex);
11777 if (error)
11778 goto done;
11779 if (upa.conflicts > 0 && upa.missing == 0 &&
11780 upa.not_deleted == 0 && upa.unversioned == 0) {
11781 error = got_error_msg(GOT_ERR_CONFLICTS,
11782 "conflicts must be resolved before rebasing "
11783 "can continue");
11784 } else if (upa.conflicts > 0) {
11785 error = got_error_msg(GOT_ERR_CONFLICTS,
11786 "conflicts must be resolved before rebasing "
11787 "can continue; changes destined for some "
11788 "files were not yet merged and should be "
11789 "merged manually if required before the "
11790 "rebase operation is continued");
11791 } else {
11792 error = got_error_msg(GOT_ERR_CONFLICTS,
11793 "changes destined for some files were not "
11794 "yet merged and should be merged manually "
11795 "if required before the rebase operation "
11796 "is continued");
11798 } else
11799 error = rebase_complete(worktree, fileindex, branch,
11800 tmp_branch, repo, create_backup);
11801 done:
11802 free(cwd);
11803 free(committer);
11804 free(gitconfig_path);
11805 got_object_id_queue_free(&commits);
11806 free(branch_head_commit_id);
11807 free(resume_commit_id);
11808 free(head_commit_id);
11809 free(yca_id);
11810 if (commit)
11811 got_object_commit_close(commit);
11812 if (branch)
11813 got_ref_close(branch);
11814 if (new_base_branch)
11815 got_ref_close(new_base_branch);
11816 if (tmp_branch)
11817 got_ref_close(tmp_branch);
11818 if (head_ref)
11819 got_ref_close(head_ref);
11820 if (worktree)
11821 got_worktree_close(worktree);
11822 if (repo) {
11823 const struct got_error *close_err = got_repo_close(repo);
11824 if (error == NULL)
11825 error = close_err;
11827 if (pack_fds) {
11828 const struct got_error *pack_err =
11829 got_repo_pack_fds_close(pack_fds);
11830 if (error == NULL)
11831 error = pack_err;
11833 return error;
11836 __dead static void
11837 usage_histedit(void)
11839 fprintf(stderr, "usage: %s histedit [-aCcdeflmX] [-F histedit-script] "
11840 "[branch]\n", getprogname());
11841 exit(1);
11844 #define GOT_HISTEDIT_PICK 'p'
11845 #define GOT_HISTEDIT_EDIT 'e'
11846 #define GOT_HISTEDIT_FOLD 'f'
11847 #define GOT_HISTEDIT_DROP 'd'
11848 #define GOT_HISTEDIT_MESG 'm'
11850 static const struct got_histedit_cmd {
11851 unsigned char code;
11852 const char *name;
11853 const char *desc;
11854 } got_histedit_cmds[] = {
11855 { GOT_HISTEDIT_PICK, "pick", "use commit" },
11856 { GOT_HISTEDIT_EDIT, "edit", "use commit but stop for amending" },
11857 { GOT_HISTEDIT_FOLD, "fold", "combine with next commit that will "
11858 "be used" },
11859 { GOT_HISTEDIT_DROP, "drop", "remove commit from history" },
11860 { GOT_HISTEDIT_MESG, "mesg", "open editor to edit the log message" },
11863 struct got_histedit_list_entry {
11864 TAILQ_ENTRY(got_histedit_list_entry) entry;
11865 struct got_object_id *commit_id;
11866 const struct got_histedit_cmd *cmd;
11867 char *logmsg;
11869 TAILQ_HEAD(got_histedit_list, got_histedit_list_entry);
11871 static const struct got_error *
11872 histedit_write_commit(struct got_object_id *commit_id, const char *cmdname,
11873 FILE *f, struct got_repository *repo)
11875 const struct got_error *err = NULL;
11876 char *logmsg = NULL, *id_str = NULL;
11877 struct got_commit_object *commit = NULL;
11878 int n;
11880 err = got_object_open_as_commit(&commit, repo, commit_id);
11881 if (err)
11882 goto done;
11884 err = get_short_logmsg(&logmsg, 34, commit);
11885 if (err)
11886 goto done;
11888 err = got_object_id_str(&id_str, commit_id);
11889 if (err)
11890 goto done;
11892 n = fprintf(f, "%s %s %s\n", cmdname, id_str, logmsg);
11893 if (n < 0)
11894 err = got_ferror(f, GOT_ERR_IO);
11895 done:
11896 if (commit)
11897 got_object_commit_close(commit);
11898 free(id_str);
11899 free(logmsg);
11900 return err;
11903 static const struct got_error *
11904 histedit_write_commit_list(struct got_object_id_queue *commits,
11905 FILE *f, int edit_logmsg_only, int fold_only, int drop_only,
11906 int edit_only, struct got_repository *repo)
11908 const struct got_error *err = NULL;
11909 struct got_object_qid *qid;
11910 const char *histedit_cmd = NULL;
11912 if (STAILQ_EMPTY(commits))
11913 return got_error(GOT_ERR_EMPTY_HISTEDIT);
11915 STAILQ_FOREACH(qid, commits, entry) {
11916 histedit_cmd = got_histedit_cmds[0].name;
11917 if (drop_only)
11918 histedit_cmd = "drop";
11919 else if (edit_only)
11920 histedit_cmd = "edit";
11921 else if (fold_only && STAILQ_NEXT(qid, entry) != NULL)
11922 histedit_cmd = "fold";
11923 else if (edit_logmsg_only)
11924 histedit_cmd = "mesg";
11925 err = histedit_write_commit(&qid->id, histedit_cmd, f, repo);
11926 if (err)
11927 break;
11930 return err;
11933 static const struct got_error *
11934 write_cmd_list(FILE *f, const char *branch_name,
11935 struct got_object_id_queue *commits)
11937 const struct got_error *err = NULL;
11938 size_t i;
11939 int n;
11940 char *id_str;
11941 struct got_object_qid *qid;
11943 qid = STAILQ_FIRST(commits);
11944 err = got_object_id_str(&id_str, &qid->id);
11945 if (err)
11946 return err;
11948 n = fprintf(f,
11949 "# Editing the history of branch '%s' starting at\n"
11950 "# commit %s\n"
11951 "# Commits will be processed in order from top to "
11952 "bottom of this file.\n", branch_name, id_str);
11953 if (n < 0) {
11954 err = got_ferror(f, GOT_ERR_IO);
11955 goto done;
11958 n = fprintf(f, "# Available histedit commands:\n");
11959 if (n < 0) {
11960 err = got_ferror(f, GOT_ERR_IO);
11961 goto done;
11964 for (i = 0; i < nitems(got_histedit_cmds); i++) {
11965 const struct got_histedit_cmd *cmd = &got_histedit_cmds[i];
11966 n = fprintf(f, "# %s (%c): %s\n", cmd->name, cmd->code,
11967 cmd->desc);
11968 if (n < 0) {
11969 err = got_ferror(f, GOT_ERR_IO);
11970 break;
11973 done:
11974 free(id_str);
11975 return err;
11978 static const struct got_error *
11979 histedit_syntax_error(int lineno)
11981 static char msg[42];
11982 int ret;
11984 ret = snprintf(msg, sizeof(msg), "histedit syntax error on line %d",
11985 lineno);
11986 if (ret < 0 || (size_t)ret >= sizeof(msg))
11987 return got_error(GOT_ERR_HISTEDIT_SYNTAX);
11989 return got_error_msg(GOT_ERR_HISTEDIT_SYNTAX, msg);
11992 static const struct got_error *
11993 append_folded_commit_msg(char **new_msg, struct got_histedit_list_entry *hle,
11994 char *logmsg, struct got_repository *repo)
11996 const struct got_error *err;
11997 struct got_commit_object *folded_commit = NULL;
11998 char *id_str, *folded_logmsg = NULL;
12000 err = got_object_id_str(&id_str, hle->commit_id);
12001 if (err)
12002 return err;
12004 err = got_object_open_as_commit(&folded_commit, repo, hle->commit_id);
12005 if (err)
12006 goto done;
12008 err = got_object_commit_get_logmsg(&folded_logmsg, folded_commit);
12009 if (err)
12010 goto done;
12011 if (asprintf(new_msg, "%s%s# log message of folded commit %s: %s",
12012 logmsg ? logmsg : "", logmsg ? "\n" : "", id_str,
12013 folded_logmsg) == -1) {
12014 err = got_error_from_errno("asprintf");
12016 done:
12017 if (folded_commit)
12018 got_object_commit_close(folded_commit);
12019 free(id_str);
12020 free(folded_logmsg);
12021 return err;
12024 static struct got_histedit_list_entry *
12025 get_folded_commits(struct got_histedit_list_entry *hle)
12027 struct got_histedit_list_entry *prev, *folded = NULL;
12029 prev = TAILQ_PREV(hle, got_histedit_list, entry);
12030 while (prev && (prev->cmd->code == GOT_HISTEDIT_FOLD ||
12031 prev->cmd->code == GOT_HISTEDIT_DROP)) {
12032 if (prev->cmd->code == GOT_HISTEDIT_FOLD)
12033 folded = prev;
12034 prev = TAILQ_PREV(prev, got_histedit_list, entry);
12037 return folded;
12040 static const struct got_error *
12041 histedit_edit_logmsg(struct got_histedit_list_entry *hle,
12042 const char *editor, struct got_repository *repo)
12044 char *logmsg_path = NULL, *id_str = NULL, *orig_logmsg = NULL;
12045 char *logmsg = NULL, *new_msg = NULL;
12046 const struct got_error *err = NULL;
12047 struct got_commit_object *commit = NULL;
12048 int logmsg_len;
12049 int fd = -1;
12050 struct got_histedit_list_entry *folded = NULL;
12052 err = got_object_open_as_commit(&commit, repo, hle->commit_id);
12053 if (err)
12054 return err;
12056 folded = get_folded_commits(hle);
12057 if (folded) {
12058 while (folded != hle) {
12059 if (folded->cmd->code == GOT_HISTEDIT_DROP) {
12060 folded = TAILQ_NEXT(folded, entry);
12061 continue;
12063 err = append_folded_commit_msg(&new_msg, folded,
12064 logmsg, repo);
12065 if (err)
12066 goto done;
12067 free(logmsg);
12068 logmsg = new_msg;
12069 folded = TAILQ_NEXT(folded, entry);
12073 err = got_object_id_str(&id_str, hle->commit_id);
12074 if (err)
12075 goto done;
12076 err = got_object_commit_get_logmsg(&orig_logmsg, commit);
12077 if (err)
12078 goto done;
12079 logmsg_len = asprintf(&new_msg,
12080 "%s\n# original log message of commit %s: %s",
12081 logmsg ? logmsg : "", id_str, orig_logmsg);
12082 if (logmsg_len == -1) {
12083 err = got_error_from_errno("asprintf");
12084 goto done;
12086 free(logmsg);
12087 logmsg = new_msg;
12089 err = got_object_id_str(&id_str, hle->commit_id);
12090 if (err)
12091 goto done;
12093 err = got_opentemp_named_fd(&logmsg_path, &fd,
12094 GOT_TMPDIR_STR "/got-logmsg", "");
12095 if (err)
12096 goto done;
12098 if (write(fd, logmsg, logmsg_len) == -1) {
12099 err = got_error_from_errno2("write", logmsg_path);
12100 goto done;
12102 if (close(fd) == -1) {
12103 err = got_error_from_errno2("close", logmsg_path);
12104 goto done;
12106 fd = -1;
12108 err = edit_logmsg(&hle->logmsg, editor, logmsg_path, logmsg,
12109 logmsg_len, 0);
12110 if (err) {
12111 if (err->code != GOT_ERR_COMMIT_MSG_EMPTY)
12112 goto done;
12113 err = NULL;
12114 hle->logmsg = strdup(new_msg);
12115 if (hle->logmsg == NULL)
12116 err = got_error_from_errno("strdup");
12118 done:
12119 if (fd != -1 && close(fd) == -1 && err == NULL)
12120 err = got_error_from_errno2("close", logmsg_path);
12121 if (logmsg_path && unlink(logmsg_path) != 0 && err == NULL)
12122 err = got_error_from_errno2("unlink", logmsg_path);
12123 free(logmsg_path);
12124 free(logmsg);
12125 free(orig_logmsg);
12126 if (commit)
12127 got_object_commit_close(commit);
12128 return err;
12131 static const struct got_error *
12132 histedit_parse_list(struct got_histedit_list *histedit_cmds,
12133 FILE *f, struct got_repository *repo)
12135 const struct got_error *err = NULL;
12136 char *line = NULL, *p, *end;
12137 size_t i, linesize = 0;
12138 ssize_t linelen;
12139 int lineno = 0;
12140 const struct got_histedit_cmd *cmd;
12141 struct got_object_id *commit_id = NULL;
12142 struct got_histedit_list_entry *hle = NULL;
12144 for (;;) {
12145 linelen = getline(&line, &linesize, f);
12146 if (linelen == -1) {
12147 const struct got_error *getline_err;
12148 if (feof(f))
12149 break;
12150 getline_err = got_error_from_errno("getline");
12151 err = got_ferror(f, getline_err->code);
12152 break;
12154 lineno++;
12155 p = line;
12156 while (isspace((unsigned char)p[0]))
12157 p++;
12158 if (p[0] == '#' || p[0] == '\0')
12159 continue;
12160 cmd = NULL;
12161 for (i = 0; i < nitems(got_histedit_cmds); i++) {
12162 cmd = &got_histedit_cmds[i];
12163 if (strncmp(cmd->name, p, strlen(cmd->name)) == 0 &&
12164 isspace((unsigned char)p[strlen(cmd->name)])) {
12165 p += strlen(cmd->name);
12166 break;
12168 if (p[0] == cmd->code && isspace((unsigned char)p[1])) {
12169 p++;
12170 break;
12173 if (i == nitems(got_histedit_cmds)) {
12174 err = histedit_syntax_error(lineno);
12175 break;
12177 while (isspace((unsigned char)p[0]))
12178 p++;
12179 end = p;
12180 while (end[0] && !isspace((unsigned char)end[0]))
12181 end++;
12182 *end = '\0';
12183 err = got_object_resolve_id_str(&commit_id, repo, p);
12184 if (err) {
12185 /* override error code */
12186 err = histedit_syntax_error(lineno);
12187 break;
12189 hle = malloc(sizeof(*hle));
12190 if (hle == NULL) {
12191 err = got_error_from_errno("malloc");
12192 break;
12194 hle->cmd = cmd;
12195 hle->commit_id = commit_id;
12196 hle->logmsg = NULL;
12197 commit_id = NULL;
12198 TAILQ_INSERT_TAIL(histedit_cmds, hle, entry);
12201 free(line);
12202 free(commit_id);
12203 return err;
12206 static const struct got_error *
12207 histedit_check_script(struct got_histedit_list *histedit_cmds,
12208 struct got_object_id_queue *commits, struct got_repository *repo)
12210 const struct got_error *err = NULL;
12211 struct got_object_qid *qid;
12212 struct got_histedit_list_entry *hle;
12213 static char msg[92];
12214 char *id_str;
12216 if (TAILQ_EMPTY(histedit_cmds))
12217 return got_error_msg(GOT_ERR_EMPTY_HISTEDIT,
12218 "histedit script contains no commands");
12219 if (STAILQ_EMPTY(commits))
12220 return got_error(GOT_ERR_EMPTY_HISTEDIT);
12222 TAILQ_FOREACH(hle, histedit_cmds, entry) {
12223 struct got_histedit_list_entry *hle2;
12224 TAILQ_FOREACH(hle2, histedit_cmds, entry) {
12225 if (hle == hle2)
12226 continue;
12227 if (got_object_id_cmp(hle->commit_id,
12228 hle2->commit_id) != 0)
12229 continue;
12230 err = got_object_id_str(&id_str, hle->commit_id);
12231 if (err)
12232 return err;
12233 snprintf(msg, sizeof(msg), "commit %s is listed "
12234 "more than once in histedit script", id_str);
12235 free(id_str);
12236 return got_error_msg(GOT_ERR_HISTEDIT_CMD, msg);
12240 STAILQ_FOREACH(qid, commits, entry) {
12241 TAILQ_FOREACH(hle, histedit_cmds, entry) {
12242 if (got_object_id_cmp(&qid->id, hle->commit_id) == 0)
12243 break;
12245 if (hle == NULL) {
12246 err = got_object_id_str(&id_str, &qid->id);
12247 if (err)
12248 return err;
12249 snprintf(msg, sizeof(msg),
12250 "commit %s missing from histedit script", id_str);
12251 free(id_str);
12252 return got_error_msg(GOT_ERR_HISTEDIT_CMD, msg);
12256 hle = TAILQ_LAST(histedit_cmds, got_histedit_list);
12257 if (hle && hle->cmd->code == GOT_HISTEDIT_FOLD)
12258 return got_error_msg(GOT_ERR_HISTEDIT_CMD,
12259 "last commit in histedit script cannot be folded");
12261 return NULL;
12264 static const struct got_error *
12265 histedit_run_editor(struct got_histedit_list *histedit_cmds,
12266 const char *editor, const char *path,
12267 struct got_object_id_queue *commits, struct got_repository *repo)
12269 const struct got_error *err = NULL;
12270 struct stat st, st2;
12271 struct timespec timeout;
12272 FILE *f = NULL;
12274 if (stat(path, &st) == -1) {
12275 err = got_error_from_errno2("stat", path);
12276 goto done;
12279 if (spawn_editor(editor, path) == -1) {
12280 err = got_error_from_errno("failed spawning editor");
12281 goto done;
12284 timeout.tv_sec = 0;
12285 timeout.tv_nsec = 1;
12286 nanosleep(&timeout, NULL);
12288 if (stat(path, &st2) == -1) {
12289 err = got_error_from_errno2("stat", path);
12290 goto done;
12293 if (st.st_size == st2.st_size &&
12294 timespeccmp(&st.st_mtim, &st2.st_mtim, ==)) {
12295 err = got_error_msg(GOT_ERR_EMPTY_HISTEDIT,
12296 "no changes made to histedit script, aborting");
12297 goto done;
12300 f = fopen(path, "re");
12301 if (f == NULL) {
12302 err = got_error_from_errno("fopen");
12303 goto done;
12305 err = histedit_parse_list(histedit_cmds, f, repo);
12306 if (err)
12307 goto done;
12309 err = histedit_check_script(histedit_cmds, commits, repo);
12310 done:
12311 if (f && fclose(f) == EOF && err == NULL)
12312 err = got_error_from_errno("fclose");
12313 return err;
12316 static const struct got_error *
12317 histedit_edit_list_retry(struct got_histedit_list *, const struct got_error *,
12318 struct got_object_id_queue *, const char *, const char *, const char *,
12319 struct got_repository *);
12321 static const struct got_error *
12322 histedit_edit_script(struct got_histedit_list *histedit_cmds,
12323 struct got_object_id_queue *commits, const char *branch_name,
12324 int edit_logmsg_only, int fold_only, int drop_only, int edit_only,
12325 const char *editor, struct got_repository *repo)
12327 const struct got_error *err;
12328 FILE *f = NULL;
12329 char *path = NULL;
12331 err = got_opentemp_named(&path, &f, "got-histedit", "");
12332 if (err)
12333 return err;
12335 err = write_cmd_list(f, branch_name, commits);
12336 if (err)
12337 goto done;
12339 err = histedit_write_commit_list(commits, f, edit_logmsg_only,
12340 fold_only, drop_only, edit_only, repo);
12341 if (err)
12342 goto done;
12344 if (drop_only || edit_logmsg_only || fold_only || edit_only) {
12345 rewind(f);
12346 err = histedit_parse_list(histedit_cmds, f, repo);
12347 } else {
12348 if (fclose(f) == EOF) {
12349 err = got_error_from_errno("fclose");
12350 goto done;
12352 f = NULL;
12353 err = histedit_run_editor(histedit_cmds, editor, path,
12354 commits, repo);
12355 if (err) {
12356 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
12357 err->code != GOT_ERR_HISTEDIT_CMD)
12358 goto done;
12359 err = histedit_edit_list_retry(histedit_cmds, err,
12360 commits, editor, path, branch_name, repo);
12363 done:
12364 if (f && fclose(f) == EOF && err == NULL)
12365 err = got_error_from_errno("fclose");
12366 if (path && unlink(path) != 0 && err == NULL)
12367 err = got_error_from_errno2("unlink", path);
12368 free(path);
12369 return err;
12372 static const struct got_error *
12373 histedit_save_list(struct got_histedit_list *histedit_cmds,
12374 struct got_worktree *worktree, struct got_repository *repo)
12376 const struct got_error *err = NULL;
12377 char *path = NULL;
12378 FILE *f = NULL;
12379 struct got_histedit_list_entry *hle;
12381 err = got_worktree_get_histedit_script_path(&path, worktree);
12382 if (err)
12383 return err;
12385 f = fopen(path, "we");
12386 if (f == NULL) {
12387 err = got_error_from_errno2("fopen", path);
12388 goto done;
12390 TAILQ_FOREACH(hle, histedit_cmds, entry) {
12391 err = histedit_write_commit(hle->commit_id, hle->cmd->name, f,
12392 repo);
12393 if (err)
12394 break;
12396 done:
12397 if (f && fclose(f) == EOF && err == NULL)
12398 err = got_error_from_errno("fclose");
12399 free(path);
12400 return err;
12403 static void
12404 histedit_free_list(struct got_histedit_list *histedit_cmds)
12406 struct got_histedit_list_entry *hle;
12408 while ((hle = TAILQ_FIRST(histedit_cmds))) {
12409 TAILQ_REMOVE(histedit_cmds, hle, entry);
12410 free(hle);
12414 static const struct got_error *
12415 histedit_load_list(struct got_histedit_list *histedit_cmds,
12416 const char *path, struct got_repository *repo)
12418 const struct got_error *err = NULL;
12419 FILE *f = NULL;
12421 f = fopen(path, "re");
12422 if (f == NULL) {
12423 err = got_error_from_errno2("fopen", path);
12424 goto done;
12427 err = histedit_parse_list(histedit_cmds, f, repo);
12428 done:
12429 if (f && fclose(f) == EOF && err == NULL)
12430 err = got_error_from_errno("fclose");
12431 return err;
12434 static const struct got_error *
12435 histedit_edit_list_retry(struct got_histedit_list *histedit_cmds,
12436 const struct got_error *edit_err, struct got_object_id_queue *commits,
12437 const char *editor, const char *path, const char *branch_name,
12438 struct got_repository *repo)
12440 const struct got_error *err = NULL, *prev_err = edit_err;
12441 int resp = ' ';
12443 while (resp != 'c' && resp != 'r' && resp != 'a') {
12444 printf("%s: %s\n(c)ontinue editing, (r)estart editing, "
12445 "or (a)bort: ", getprogname(), prev_err->msg);
12446 resp = getchar();
12447 if (resp == '\n')
12448 resp = getchar();
12449 if (resp == 'c') {
12450 histedit_free_list(histedit_cmds);
12451 err = histedit_run_editor(histedit_cmds, editor, path,
12452 commits, repo);
12453 if (err) {
12454 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
12455 err->code != GOT_ERR_HISTEDIT_CMD)
12456 break;
12457 prev_err = err;
12458 resp = ' ';
12459 continue;
12461 break;
12462 } else if (resp == 'r') {
12463 histedit_free_list(histedit_cmds);
12464 err = histedit_edit_script(histedit_cmds,
12465 commits, branch_name, 0, 0, 0, 0, editor, repo);
12466 if (err) {
12467 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
12468 err->code != GOT_ERR_HISTEDIT_CMD)
12469 break;
12470 prev_err = err;
12471 resp = ' ';
12472 continue;
12474 break;
12475 } else if (resp == 'a') {
12476 err = got_error(GOT_ERR_HISTEDIT_CANCEL);
12477 break;
12478 } else
12479 printf("invalid response '%c'\n", resp);
12482 return err;
12485 static const struct got_error *
12486 histedit_complete(struct got_worktree *worktree,
12487 struct got_fileindex *fileindex, struct got_reference *tmp_branch,
12488 struct got_reference *branch, struct got_repository *repo)
12490 printf("Switching work tree to %s\n",
12491 got_ref_get_symref_target(branch));
12492 return got_worktree_histedit_complete(worktree, fileindex, tmp_branch,
12493 branch, repo);
12496 static const struct got_error *
12497 show_histedit_progress(struct got_commit_object *commit,
12498 struct got_histedit_list_entry *hle, struct got_object_id *new_id)
12500 const struct got_error *err;
12501 char *old_id_str = NULL, *new_id_str = NULL, *logmsg = NULL;
12503 err = got_object_id_str(&old_id_str, hle->commit_id);
12504 if (err)
12505 goto done;
12507 if (new_id) {
12508 err = got_object_id_str(&new_id_str, new_id);
12509 if (err)
12510 goto done;
12513 old_id_str[12] = '\0';
12514 if (new_id_str)
12515 new_id_str[12] = '\0';
12517 if (hle->logmsg) {
12518 logmsg = strdup(hle->logmsg);
12519 if (logmsg == NULL) {
12520 err = got_error_from_errno("strdup");
12521 goto done;
12523 trim_logmsg(logmsg, 42);
12524 } else {
12525 err = get_short_logmsg(&logmsg, 42, commit);
12526 if (err)
12527 goto done;
12530 switch (hle->cmd->code) {
12531 case GOT_HISTEDIT_PICK:
12532 case GOT_HISTEDIT_EDIT:
12533 case GOT_HISTEDIT_MESG:
12534 printf("%s -> %s: %s\n", old_id_str,
12535 new_id_str ? new_id_str : "no-op change", logmsg);
12536 break;
12537 case GOT_HISTEDIT_DROP:
12538 case GOT_HISTEDIT_FOLD:
12539 printf("%s -> %s commit: %s\n", old_id_str, hle->cmd->name,
12540 logmsg);
12541 break;
12542 default:
12543 break;
12545 done:
12546 free(old_id_str);
12547 free(new_id_str);
12548 return err;
12551 static const struct got_error *
12552 histedit_commit(struct got_pathlist_head *merged_paths,
12553 struct got_worktree *worktree, struct got_fileindex *fileindex,
12554 struct got_reference *tmp_branch, struct got_histedit_list_entry *hle,
12555 const char *committer, int allow_conflict, const char *editor,
12556 struct got_repository *repo)
12558 const struct got_error *err;
12559 struct got_commit_object *commit;
12560 struct got_object_id *new_commit_id;
12562 if ((hle->cmd->code == GOT_HISTEDIT_EDIT || get_folded_commits(hle))
12563 && hle->logmsg == NULL) {
12564 err = histedit_edit_logmsg(hle, editor, repo);
12565 if (err)
12566 return err;
12569 err = got_object_open_as_commit(&commit, repo, hle->commit_id);
12570 if (err)
12571 return err;
12573 err = got_worktree_histedit_commit(&new_commit_id, merged_paths,
12574 worktree, fileindex, tmp_branch, committer, commit, hle->commit_id,
12575 hle->logmsg, allow_conflict, repo);
12576 if (err) {
12577 if (err->code != GOT_ERR_COMMIT_NO_CHANGES)
12578 goto done;
12579 err = show_histedit_progress(commit, hle, NULL);
12580 } else {
12581 err = show_histedit_progress(commit, hle, new_commit_id);
12582 free(new_commit_id);
12584 done:
12585 got_object_commit_close(commit);
12586 return err;
12589 static const struct got_error *
12590 histedit_skip_commit(struct got_histedit_list_entry *hle,
12591 struct got_worktree *worktree, struct got_repository *repo)
12593 const struct got_error *error;
12594 struct got_commit_object *commit;
12596 error = got_worktree_histedit_skip_commit(worktree, hle->commit_id,
12597 repo);
12598 if (error)
12599 return error;
12601 error = got_object_open_as_commit(&commit, repo, hle->commit_id);
12602 if (error)
12603 return error;
12605 error = show_histedit_progress(commit, hle, NULL);
12606 got_object_commit_close(commit);
12607 return error;
12610 static const struct got_error *
12611 check_local_changes(void *arg, unsigned char status,
12612 unsigned char staged_status, const char *path,
12613 struct got_object_id *blob_id, struct got_object_id *staged_blob_id,
12614 struct got_object_id *commit_id, int dirfd, const char *de_name)
12616 int *have_local_changes = arg;
12618 switch (status) {
12619 case GOT_STATUS_ADD:
12620 case GOT_STATUS_DELETE:
12621 case GOT_STATUS_MODIFY:
12622 case GOT_STATUS_CONFLICT:
12623 *have_local_changes = 1;
12624 return got_error(GOT_ERR_CANCELLED);
12625 default:
12626 break;
12629 switch (staged_status) {
12630 case GOT_STATUS_ADD:
12631 case GOT_STATUS_DELETE:
12632 case GOT_STATUS_MODIFY:
12633 *have_local_changes = 1;
12634 return got_error(GOT_ERR_CANCELLED);
12635 default:
12636 break;
12639 return NULL;
12642 static const struct got_error *
12643 cmd_histedit(int argc, char *argv[])
12645 const struct got_error *error = NULL;
12646 struct got_worktree *worktree = NULL;
12647 struct got_fileindex *fileindex = NULL;
12648 struct got_repository *repo = NULL;
12649 char *cwd = NULL, *committer = NULL, *gitconfig_path = NULL;
12650 struct got_reference *branch = NULL;
12651 struct got_reference *tmp_branch = NULL;
12652 struct got_object_id *resume_commit_id = NULL;
12653 struct got_object_id *base_commit_id = NULL;
12654 struct got_object_id *head_commit_id = NULL;
12655 struct got_commit_object *commit = NULL;
12656 int ch, rebase_in_progress = 0, merge_in_progress = 0;
12657 struct got_update_progress_arg upa;
12658 int edit_in_progress = 0, abort_edit = 0, continue_edit = 0;
12659 int drop_only = 0, edit_logmsg_only = 0, fold_only = 0, edit_only = 0;
12660 int allow_conflict = 0, list_backups = 0, delete_backups = 0;
12661 const char *edit_script_path = NULL;
12662 char *editor = NULL;
12663 struct got_object_id_queue commits;
12664 struct got_pathlist_head merged_paths;
12665 const struct got_object_id_queue *parent_ids;
12666 struct got_object_qid *pid;
12667 struct got_histedit_list histedit_cmds;
12668 struct got_histedit_list_entry *hle;
12669 int *pack_fds = NULL;
12671 STAILQ_INIT(&commits);
12672 TAILQ_INIT(&histedit_cmds);
12673 TAILQ_INIT(&merged_paths);
12674 memset(&upa, 0, sizeof(upa));
12676 #ifndef PROFILE
12677 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
12678 "unveil", NULL) == -1)
12679 err(1, "pledge");
12680 #endif
12682 while ((ch = getopt(argc, argv, "aCcdeF:flmX")) != -1) {
12683 switch (ch) {
12684 case 'a':
12685 abort_edit = 1;
12686 break;
12687 case 'C':
12688 allow_conflict = 1;
12689 break;
12690 case 'c':
12691 continue_edit = 1;
12692 break;
12693 case 'd':
12694 drop_only = 1;
12695 break;
12696 case 'e':
12697 edit_only = 1;
12698 break;
12699 case 'F':
12700 edit_script_path = optarg;
12701 break;
12702 case 'f':
12703 fold_only = 1;
12704 break;
12705 case 'l':
12706 list_backups = 1;
12707 break;
12708 case 'm':
12709 edit_logmsg_only = 1;
12710 break;
12711 case 'X':
12712 delete_backups = 1;
12713 break;
12714 default:
12715 usage_histedit();
12716 /* NOTREACHED */
12720 argc -= optind;
12721 argv += optind;
12723 if (abort_edit && allow_conflict)
12724 option_conflict('a', 'C');
12725 if (abort_edit && continue_edit)
12726 option_conflict('a', 'c');
12727 if (edit_script_path && allow_conflict)
12728 option_conflict('F', 'C');
12729 if (edit_script_path && edit_logmsg_only)
12730 option_conflict('F', 'm');
12731 if (abort_edit && edit_logmsg_only)
12732 option_conflict('a', 'm');
12733 if (edit_logmsg_only && allow_conflict)
12734 option_conflict('m', 'C');
12735 if (continue_edit && edit_logmsg_only)
12736 option_conflict('c', 'm');
12737 if (abort_edit && fold_only)
12738 option_conflict('a', 'f');
12739 if (fold_only && allow_conflict)
12740 option_conflict('f', 'C');
12741 if (continue_edit && fold_only)
12742 option_conflict('c', 'f');
12743 if (fold_only && edit_logmsg_only)
12744 option_conflict('f', 'm');
12745 if (edit_script_path && fold_only)
12746 option_conflict('F', 'f');
12747 if (abort_edit && edit_only)
12748 option_conflict('a', 'e');
12749 if (continue_edit && edit_only)
12750 option_conflict('c', 'e');
12751 if (edit_only && edit_logmsg_only)
12752 option_conflict('e', 'm');
12753 if (edit_script_path && edit_only)
12754 option_conflict('F', 'e');
12755 if (fold_only && edit_only)
12756 option_conflict('f', 'e');
12757 if (drop_only && abort_edit)
12758 option_conflict('d', 'a');
12759 if (drop_only && allow_conflict)
12760 option_conflict('d', 'C');
12761 if (drop_only && continue_edit)
12762 option_conflict('d', 'c');
12763 if (drop_only && edit_logmsg_only)
12764 option_conflict('d', 'm');
12765 if (drop_only && edit_only)
12766 option_conflict('d', 'e');
12767 if (drop_only && edit_script_path)
12768 option_conflict('d', 'F');
12769 if (drop_only && fold_only)
12770 option_conflict('d', 'f');
12771 if (list_backups) {
12772 if (abort_edit)
12773 option_conflict('l', 'a');
12774 if (allow_conflict)
12775 option_conflict('l', 'C');
12776 if (continue_edit)
12777 option_conflict('l', 'c');
12778 if (edit_script_path)
12779 option_conflict('l', 'F');
12780 if (edit_logmsg_only)
12781 option_conflict('l', 'm');
12782 if (drop_only)
12783 option_conflict('l', 'd');
12784 if (fold_only)
12785 option_conflict('l', 'f');
12786 if (edit_only)
12787 option_conflict('l', 'e');
12788 if (delete_backups)
12789 option_conflict('l', 'X');
12790 if (argc != 0 && argc != 1)
12791 usage_histedit();
12792 } else if (delete_backups) {
12793 if (abort_edit)
12794 option_conflict('X', 'a');
12795 if (allow_conflict)
12796 option_conflict('X', 'C');
12797 if (continue_edit)
12798 option_conflict('X', 'c');
12799 if (drop_only)
12800 option_conflict('X', 'd');
12801 if (edit_script_path)
12802 option_conflict('X', 'F');
12803 if (edit_logmsg_only)
12804 option_conflict('X', 'm');
12805 if (fold_only)
12806 option_conflict('X', 'f');
12807 if (edit_only)
12808 option_conflict('X', 'e');
12809 if (list_backups)
12810 option_conflict('X', 'l');
12811 if (argc != 0 && argc != 1)
12812 usage_histedit();
12813 } else if (allow_conflict && !continue_edit)
12814 errx(1, "-C option requires -c");
12815 else if (argc != 0)
12816 usage_histedit();
12818 cwd = getcwd(NULL, 0);
12819 if (cwd == NULL) {
12820 error = got_error_from_errno("getcwd");
12821 goto done;
12824 error = got_repo_pack_fds_open(&pack_fds);
12825 if (error != NULL)
12826 goto done;
12828 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
12829 if (error) {
12830 if (list_backups || delete_backups) {
12831 if (error->code != GOT_ERR_NOT_WORKTREE)
12832 goto done;
12833 } else {
12834 if (error->code == GOT_ERR_NOT_WORKTREE)
12835 error = wrap_not_worktree_error(error,
12836 "histedit", cwd);
12837 goto done;
12841 if (list_backups || delete_backups) {
12842 error = got_repo_open(&repo,
12843 worktree ? got_worktree_get_repo_path(worktree) : cwd,
12844 NULL, pack_fds);
12845 if (error != NULL)
12846 goto done;
12847 error = apply_unveil(got_repo_get_path(repo), 0,
12848 worktree ? got_worktree_get_root_path(worktree) : NULL);
12849 if (error)
12850 goto done;
12851 error = process_backup_refs(
12852 GOT_WORKTREE_HISTEDIT_BACKUP_REF_PREFIX,
12853 argc == 1 ? argv[0] : NULL, delete_backups, repo);
12854 goto done; /* nothing else to do */
12855 } else {
12856 error = get_gitconfig_path(&gitconfig_path);
12857 if (error)
12858 goto done;
12859 error = got_repo_open(&repo,
12860 got_worktree_get_repo_path(worktree), gitconfig_path,
12861 pack_fds);
12862 if (error != NULL)
12863 goto done;
12864 error = get_editor(&editor);
12865 if (error)
12866 goto done;
12867 if (unveil(editor, "x") != 0) {
12868 error = got_error_from_errno2("unveil", editor);
12869 goto done;
12871 if (edit_script_path) {
12872 if (unveil(edit_script_path, "r") != 0) {
12873 error = got_error_from_errno2("unveil",
12874 edit_script_path);
12875 goto done;
12878 error = apply_unveil(got_repo_get_path(repo), 0,
12879 got_worktree_get_root_path(worktree));
12880 if (error)
12881 goto done;
12884 if (worktree != NULL && !list_backups && !delete_backups) {
12885 error = worktree_has_logmsg_ref("histedit", worktree, repo);
12886 if (error)
12887 goto done;
12890 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
12891 if (error)
12892 goto done;
12893 if (rebase_in_progress) {
12894 error = got_error(GOT_ERR_REBASING);
12895 goto done;
12898 error = got_worktree_merge_in_progress(&merge_in_progress, worktree,
12899 repo);
12900 if (error)
12901 goto done;
12902 if (merge_in_progress) {
12903 error = got_error(GOT_ERR_MERGE_BUSY);
12904 goto done;
12907 error = got_worktree_histedit_in_progress(&edit_in_progress, worktree);
12908 if (error)
12909 goto done;
12911 if (edit_in_progress && edit_logmsg_only) {
12912 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
12913 "histedit operation is in progress in this "
12914 "work tree and must be continued or aborted "
12915 "before the -m option can be used");
12916 goto done;
12918 if (edit_in_progress && drop_only) {
12919 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
12920 "histedit operation is in progress in this "
12921 "work tree and must be continued or aborted "
12922 "before the -d option can be used");
12923 goto done;
12925 if (edit_in_progress && fold_only) {
12926 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
12927 "histedit operation is in progress in this "
12928 "work tree and must be continued or aborted "
12929 "before the -f option can be used");
12930 goto done;
12932 if (edit_in_progress && edit_only) {
12933 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
12934 "histedit operation is in progress in this "
12935 "work tree and must be continued or aborted "
12936 "before the -e option can be used");
12937 goto done;
12940 if (edit_in_progress && abort_edit) {
12941 error = got_worktree_histedit_continue(&resume_commit_id,
12942 &tmp_branch, &branch, &base_commit_id, &fileindex,
12943 worktree, repo);
12944 if (error)
12945 goto done;
12946 printf("Switching work tree to %s\n",
12947 got_ref_get_symref_target(branch));
12948 error = got_worktree_histedit_abort(worktree, fileindex, repo,
12949 branch, base_commit_id, abort_progress, &upa);
12950 if (error)
12951 goto done;
12952 printf("Histedit of %s aborted\n",
12953 got_ref_get_symref_target(branch));
12954 print_merge_progress_stats(&upa);
12955 goto done; /* nothing else to do */
12956 } else if (abort_edit) {
12957 error = got_error(GOT_ERR_NOT_HISTEDIT);
12958 goto done;
12961 error = get_author(&committer, repo, worktree);
12962 if (error)
12963 goto done;
12965 if (continue_edit) {
12966 char *path;
12968 if (!edit_in_progress) {
12969 error = got_error(GOT_ERR_NOT_HISTEDIT);
12970 goto done;
12973 error = got_worktree_get_histedit_script_path(&path, worktree);
12974 if (error)
12975 goto done;
12977 error = histedit_load_list(&histedit_cmds, path, repo);
12978 free(path);
12979 if (error)
12980 goto done;
12982 error = got_worktree_histedit_continue(&resume_commit_id,
12983 &tmp_branch, &branch, &base_commit_id, &fileindex,
12984 worktree, repo);
12985 if (error)
12986 goto done;
12988 error = got_ref_resolve(&head_commit_id, repo, branch);
12989 if (error)
12990 goto done;
12992 error = got_object_open_as_commit(&commit, repo,
12993 head_commit_id);
12994 if (error)
12995 goto done;
12996 parent_ids = got_object_commit_get_parent_ids(commit);
12997 pid = STAILQ_FIRST(parent_ids);
12998 if (pid == NULL) {
12999 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
13000 goto done;
13002 error = collect_commits(&commits, head_commit_id, &pid->id,
13003 base_commit_id, got_worktree_get_path_prefix(worktree),
13004 GOT_ERR_HISTEDIT_PATH, repo);
13005 got_object_commit_close(commit);
13006 commit = NULL;
13007 if (error)
13008 goto done;
13009 } else {
13010 if (edit_in_progress) {
13011 error = got_error(GOT_ERR_HISTEDIT_BUSY);
13012 goto done;
13015 error = got_ref_open(&branch, repo,
13016 got_worktree_get_head_ref_name(worktree), 0);
13017 if (error != NULL)
13018 goto done;
13020 if (strncmp(got_ref_get_name(branch), "refs/heads/", 11) != 0) {
13021 error = got_error_msg(GOT_ERR_COMMIT_BRANCH,
13022 "will not edit commit history of a branch outside "
13023 "the \"refs/heads/\" reference namespace");
13024 goto done;
13027 error = got_ref_resolve(&head_commit_id, repo, branch);
13028 got_ref_close(branch);
13029 branch = NULL;
13030 if (error)
13031 goto done;
13033 error = got_object_open_as_commit(&commit, repo,
13034 head_commit_id);
13035 if (error)
13036 goto done;
13037 parent_ids = got_object_commit_get_parent_ids(commit);
13038 pid = STAILQ_FIRST(parent_ids);
13039 if (pid == NULL) {
13040 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
13041 goto done;
13043 error = collect_commits(&commits, head_commit_id, &pid->id,
13044 got_worktree_get_base_commit_id(worktree),
13045 got_worktree_get_path_prefix(worktree),
13046 GOT_ERR_HISTEDIT_PATH, repo);
13047 got_object_commit_close(commit);
13048 commit = NULL;
13049 if (error)
13050 goto done;
13052 if (STAILQ_EMPTY(&commits)) {
13053 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
13054 goto done;
13057 error = got_worktree_histedit_prepare(&tmp_branch, &branch,
13058 &base_commit_id, &fileindex, worktree, repo);
13059 if (error)
13060 goto done;
13062 if (edit_script_path) {
13063 error = histedit_load_list(&histedit_cmds,
13064 edit_script_path, repo);
13065 if (error) {
13066 got_worktree_histedit_abort(worktree, fileindex,
13067 repo, branch, base_commit_id,
13068 abort_progress, &upa);
13069 print_merge_progress_stats(&upa);
13070 goto done;
13072 } else {
13073 const char *branch_name;
13074 branch_name = got_ref_get_symref_target(branch);
13075 if (strncmp(branch_name, "refs/heads/", 11) == 0)
13076 branch_name += 11;
13077 error = histedit_edit_script(&histedit_cmds, &commits,
13078 branch_name, edit_logmsg_only, fold_only,
13079 drop_only, edit_only, editor, repo);
13080 if (error) {
13081 got_worktree_histedit_abort(worktree, fileindex,
13082 repo, branch, base_commit_id,
13083 abort_progress, &upa);
13084 print_merge_progress_stats(&upa);
13085 goto done;
13090 error = histedit_save_list(&histedit_cmds, worktree,
13091 repo);
13092 if (error) {
13093 got_worktree_histedit_abort(worktree, fileindex,
13094 repo, branch, base_commit_id,
13095 abort_progress, &upa);
13096 print_merge_progress_stats(&upa);
13097 goto done;
13102 error = histedit_check_script(&histedit_cmds, &commits, repo);
13103 if (error)
13104 goto done;
13106 TAILQ_FOREACH(hle, &histedit_cmds, entry) {
13107 if (resume_commit_id) {
13108 if (got_object_id_cmp(hle->commit_id,
13109 resume_commit_id) != 0)
13110 continue;
13112 resume_commit_id = NULL;
13113 if (hle->cmd->code == GOT_HISTEDIT_DROP ||
13114 hle->cmd->code == GOT_HISTEDIT_FOLD) {
13115 error = histedit_skip_commit(hle, worktree,
13116 repo);
13117 if (error)
13118 goto done;
13119 } else {
13120 struct got_pathlist_head paths;
13121 int have_changes = 0;
13123 TAILQ_INIT(&paths);
13124 error = got_pathlist_append(&paths, "", NULL);
13125 if (error)
13126 goto done;
13127 error = got_worktree_status(worktree, &paths,
13128 repo, 0, check_local_changes, &have_changes,
13129 check_cancelled, NULL);
13130 got_pathlist_free(&paths,
13131 GOT_PATHLIST_FREE_NONE);
13132 if (error) {
13133 if (error->code != GOT_ERR_CANCELLED)
13134 goto done;
13135 if (sigint_received || sigpipe_received)
13136 goto done;
13138 if (have_changes) {
13139 error = histedit_commit(NULL, worktree,
13140 fileindex, tmp_branch, hle,
13141 committer, allow_conflict, editor,
13142 repo);
13143 if (error)
13144 goto done;
13145 } else {
13146 error = got_object_open_as_commit(
13147 &commit, repo, hle->commit_id);
13148 if (error)
13149 goto done;
13150 error = show_histedit_progress(commit,
13151 hle, NULL);
13152 got_object_commit_close(commit);
13153 commit = NULL;
13154 if (error)
13155 goto done;
13158 continue;
13161 if (hle->cmd->code == GOT_HISTEDIT_DROP) {
13162 error = histedit_skip_commit(hle, worktree, repo);
13163 if (error)
13164 goto done;
13165 continue;
13167 error = got_object_open_as_commit(&commit, repo,
13168 hle->commit_id);
13169 if (error)
13170 goto done;
13171 parent_ids = got_object_commit_get_parent_ids(commit);
13172 pid = STAILQ_FIRST(parent_ids);
13174 error = got_worktree_histedit_merge_files(&merged_paths,
13175 worktree, fileindex, &pid->id, hle->commit_id, repo,
13176 update_progress, &upa, check_cancelled, NULL);
13177 if (error)
13178 goto done;
13179 got_object_commit_close(commit);
13180 commit = NULL;
13182 print_merge_progress_stats(&upa);
13183 if (upa.conflicts > 0 || upa.missing > 0 ||
13184 upa.not_deleted > 0 || upa.unversioned > 0) {
13185 if (upa.conflicts > 0) {
13186 error = show_rebase_merge_conflict(
13187 hle->commit_id, repo);
13188 if (error)
13189 goto done;
13191 got_pathlist_free(&merged_paths, GOT_PATHLIST_FREE_PATH);
13192 break;
13195 if (hle->cmd->code == GOT_HISTEDIT_EDIT) {
13196 char *id_str;
13197 error = got_object_id_str(&id_str, hle->commit_id);
13198 if (error)
13199 goto done;
13200 printf("Stopping histedit for amending commit %s\n",
13201 id_str);
13202 free(id_str);
13203 got_pathlist_free(&merged_paths, GOT_PATHLIST_FREE_PATH);
13204 error = got_worktree_histedit_postpone(worktree,
13205 fileindex);
13206 goto done;
13207 } else if (hle->cmd->code == GOT_HISTEDIT_FOLD) {
13208 error = histedit_skip_commit(hle, worktree, repo);
13209 if (error)
13210 goto done;
13211 continue;
13212 } else if (hle->cmd->code == GOT_HISTEDIT_MESG) {
13213 error = histedit_edit_logmsg(hle, editor, repo);
13214 if (error)
13215 goto done;
13218 error = histedit_commit(&merged_paths, worktree, fileindex,
13219 tmp_branch, hle, committer, allow_conflict, editor, repo);
13220 got_pathlist_free(&merged_paths, GOT_PATHLIST_FREE_PATH);
13221 if (error)
13222 goto done;
13225 if (upa.conflicts > 0 || upa.missing > 0 ||
13226 upa.not_deleted > 0 || upa.unversioned > 0) {
13227 error = got_worktree_histedit_postpone(worktree, fileindex);
13228 if (error)
13229 goto done;
13230 if (upa.conflicts > 0 && upa.missing == 0 &&
13231 upa.not_deleted == 0 && upa.unversioned == 0) {
13232 error = got_error_msg(GOT_ERR_CONFLICTS,
13233 "conflicts must be resolved before histedit "
13234 "can continue");
13235 } else if (upa.conflicts > 0) {
13236 error = got_error_msg(GOT_ERR_CONFLICTS,
13237 "conflicts must be resolved before histedit "
13238 "can continue; changes destined for some "
13239 "files were not yet merged and should be "
13240 "merged manually if required before the "
13241 "histedit operation is continued");
13242 } else {
13243 error = got_error_msg(GOT_ERR_CONFLICTS,
13244 "changes destined for some files were not "
13245 "yet merged and should be merged manually "
13246 "if required before the histedit operation "
13247 "is continued");
13249 } else
13250 error = histedit_complete(worktree, fileindex, tmp_branch,
13251 branch, repo);
13252 done:
13253 free(cwd);
13254 free(editor);
13255 free(committer);
13256 free(gitconfig_path);
13257 got_object_id_queue_free(&commits);
13258 histedit_free_list(&histedit_cmds);
13259 free(head_commit_id);
13260 free(base_commit_id);
13261 free(resume_commit_id);
13262 if (commit)
13263 got_object_commit_close(commit);
13264 if (branch)
13265 got_ref_close(branch);
13266 if (tmp_branch)
13267 got_ref_close(tmp_branch);
13268 if (worktree)
13269 got_worktree_close(worktree);
13270 if (repo) {
13271 const struct got_error *close_err = got_repo_close(repo);
13272 if (error == NULL)
13273 error = close_err;
13275 if (pack_fds) {
13276 const struct got_error *pack_err =
13277 got_repo_pack_fds_close(pack_fds);
13278 if (error == NULL)
13279 error = pack_err;
13281 return error;
13284 __dead static void
13285 usage_integrate(void)
13287 fprintf(stderr, "usage: %s integrate branch\n", getprogname());
13288 exit(1);
13291 static const struct got_error *
13292 cmd_integrate(int argc, char *argv[])
13294 const struct got_error *error = NULL;
13295 struct got_repository *repo = NULL;
13296 struct got_worktree *worktree = NULL;
13297 char *cwd = NULL, *refname = NULL, *base_refname = NULL;
13298 const char *branch_arg = NULL;
13299 struct got_reference *branch_ref = NULL, *base_branch_ref = NULL;
13300 struct got_fileindex *fileindex = NULL;
13301 struct got_object_id *commit_id = NULL, *base_commit_id = NULL;
13302 int ch;
13303 struct got_update_progress_arg upa;
13304 int *pack_fds = NULL;
13306 #ifndef PROFILE
13307 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
13308 "unveil", NULL) == -1)
13309 err(1, "pledge");
13310 #endif
13312 while ((ch = getopt(argc, argv, "")) != -1) {
13313 switch (ch) {
13314 default:
13315 usage_integrate();
13316 /* NOTREACHED */
13320 argc -= optind;
13321 argv += optind;
13323 if (argc != 1)
13324 usage_integrate();
13325 branch_arg = argv[0];
13327 cwd = getcwd(NULL, 0);
13328 if (cwd == NULL) {
13329 error = got_error_from_errno("getcwd");
13330 goto done;
13333 error = got_repo_pack_fds_open(&pack_fds);
13334 if (error != NULL)
13335 goto done;
13337 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
13338 if (error) {
13339 if (error->code == GOT_ERR_NOT_WORKTREE)
13340 error = wrap_not_worktree_error(error, "integrate",
13341 cwd);
13342 goto done;
13345 error = check_rebase_or_histedit_in_progress(worktree);
13346 if (error)
13347 goto done;
13349 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
13350 NULL, pack_fds);
13351 if (error != NULL)
13352 goto done;
13354 error = apply_unveil(got_repo_get_path(repo), 0,
13355 got_worktree_get_root_path(worktree));
13356 if (error)
13357 goto done;
13359 error = check_merge_in_progress(worktree, repo);
13360 if (error)
13361 goto done;
13363 if (asprintf(&refname, "refs/heads/%s", branch_arg) == -1) {
13364 error = got_error_from_errno("asprintf");
13365 goto done;
13368 error = got_worktree_integrate_prepare(&fileindex, &branch_ref,
13369 &base_branch_ref, worktree, refname, repo);
13370 if (error)
13371 goto done;
13373 refname = strdup(got_ref_get_name(branch_ref));
13374 if (refname == NULL) {
13375 error = got_error_from_errno("strdup");
13376 got_worktree_integrate_abort(worktree, fileindex, repo,
13377 branch_ref, base_branch_ref);
13378 goto done;
13380 base_refname = strdup(got_ref_get_name(base_branch_ref));
13381 if (base_refname == NULL) {
13382 error = got_error_from_errno("strdup");
13383 got_worktree_integrate_abort(worktree, fileindex, repo,
13384 branch_ref, base_branch_ref);
13385 goto done;
13387 if (strncmp(base_refname, "refs/heads/", 11) != 0) {
13388 error = got_error(GOT_ERR_INTEGRATE_BRANCH);
13389 got_worktree_integrate_abort(worktree, fileindex, repo,
13390 branch_ref, base_branch_ref);
13391 goto done;
13394 error = got_ref_resolve(&commit_id, repo, branch_ref);
13395 if (error)
13396 goto done;
13398 error = got_ref_resolve(&base_commit_id, repo, base_branch_ref);
13399 if (error)
13400 goto done;
13402 if (got_object_id_cmp(commit_id, base_commit_id) == 0) {
13403 error = got_error_msg(GOT_ERR_SAME_BRANCH,
13404 "specified branch has already been integrated");
13405 got_worktree_integrate_abort(worktree, fileindex, repo,
13406 branch_ref, base_branch_ref);
13407 goto done;
13410 error = check_linear_ancestry(commit_id, base_commit_id, 1, repo);
13411 if (error) {
13412 if (error->code == GOT_ERR_ANCESTRY)
13413 error = got_error(GOT_ERR_REBASE_REQUIRED);
13414 got_worktree_integrate_abort(worktree, fileindex, repo,
13415 branch_ref, base_branch_ref);
13416 goto done;
13419 memset(&upa, 0, sizeof(upa));
13420 error = got_worktree_integrate_continue(worktree, fileindex, repo,
13421 branch_ref, base_branch_ref, update_progress, &upa,
13422 check_cancelled, NULL);
13423 if (error)
13424 goto done;
13426 printf("Integrated %s into %s\n", refname, base_refname);
13427 print_update_progress_stats(&upa);
13428 done:
13429 if (repo) {
13430 const struct got_error *close_err = got_repo_close(repo);
13431 if (error == NULL)
13432 error = close_err;
13434 if (worktree)
13435 got_worktree_close(worktree);
13436 if (pack_fds) {
13437 const struct got_error *pack_err =
13438 got_repo_pack_fds_close(pack_fds);
13439 if (error == NULL)
13440 error = pack_err;
13442 free(cwd);
13443 free(base_commit_id);
13444 free(commit_id);
13445 free(refname);
13446 free(base_refname);
13447 return error;
13450 __dead static void
13451 usage_merge(void)
13453 fprintf(stderr, "usage: %s merge [-aCcn] [branch]\n", getprogname());
13454 exit(1);
13457 static const struct got_error *
13458 cmd_merge(int argc, char *argv[])
13460 const struct got_error *error = NULL;
13461 struct got_worktree *worktree = NULL;
13462 struct got_repository *repo = NULL;
13463 struct got_fileindex *fileindex = NULL;
13464 char *cwd = NULL, *id_str = NULL, *author = NULL;
13465 char *gitconfig_path = NULL;
13466 struct got_reference *branch = NULL, *wt_branch = NULL;
13467 struct got_object_id *branch_tip = NULL, *yca_id = NULL;
13468 struct got_object_id *wt_branch_tip = NULL;
13469 int ch, merge_in_progress = 0, abort_merge = 0, continue_merge = 0;
13470 int allow_conflict = 0, prefer_fast_forward = 1, interrupt_merge = 0;
13471 struct got_update_progress_arg upa;
13472 struct got_object_id *merge_commit_id = NULL;
13473 char *branch_name = NULL;
13474 int *pack_fds = NULL;
13476 memset(&upa, 0, sizeof(upa));
13478 #ifndef PROFILE
13479 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
13480 "unveil", NULL) == -1)
13481 err(1, "pledge");
13482 #endif
13484 while ((ch = getopt(argc, argv, "aCcMn")) != -1) {
13485 switch (ch) {
13486 case 'a':
13487 abort_merge = 1;
13488 break;
13489 case 'C':
13490 allow_conflict = 1;
13491 break;
13492 case 'c':
13493 continue_merge = 1;
13494 break;
13495 case 'M':
13496 prefer_fast_forward = 0;
13497 break;
13498 case 'n':
13499 interrupt_merge = 1;
13500 break;
13501 default:
13502 usage_merge();
13503 /* NOTREACHED */
13507 argc -= optind;
13508 argv += optind;
13510 if (abort_merge) {
13511 if (continue_merge)
13512 option_conflict('a', 'c');
13513 if (!prefer_fast_forward)
13514 option_conflict('a', 'M');
13515 if (interrupt_merge)
13516 option_conflict('a', 'n');
13517 } else if (continue_merge) {
13518 if (!prefer_fast_forward)
13519 option_conflict('c', 'M');
13520 if (interrupt_merge)
13521 option_conflict('c', 'n');
13523 if (allow_conflict) {
13524 if (!continue_merge)
13525 errx(1, "-C option requires -c");
13527 if (abort_merge || continue_merge) {
13528 if (argc != 0)
13529 usage_merge();
13530 } else if (argc != 1)
13531 usage_merge();
13533 cwd = getcwd(NULL, 0);
13534 if (cwd == NULL) {
13535 error = got_error_from_errno("getcwd");
13536 goto done;
13539 error = got_repo_pack_fds_open(&pack_fds);
13540 if (error != NULL)
13541 goto done;
13543 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
13544 if (error) {
13545 if (error->code == GOT_ERR_NOT_WORKTREE)
13546 error = wrap_not_worktree_error(error,
13547 "merge", cwd);
13548 goto done;
13551 error = get_gitconfig_path(&gitconfig_path);
13552 if (error)
13553 goto done;
13554 error = got_repo_open(&repo,
13555 worktree ? got_worktree_get_repo_path(worktree) : cwd,
13556 gitconfig_path, pack_fds);
13557 if (error != NULL)
13558 goto done;
13560 if (worktree != NULL) {
13561 error = worktree_has_logmsg_ref("merge", worktree, repo);
13562 if (error)
13563 goto done;
13566 error = apply_unveil(got_repo_get_path(repo), 0,
13567 worktree ? got_worktree_get_root_path(worktree) : NULL);
13568 if (error)
13569 goto done;
13571 error = check_rebase_or_histedit_in_progress(worktree);
13572 if (error)
13573 goto done;
13575 error = got_worktree_merge_in_progress(&merge_in_progress, worktree,
13576 repo);
13577 if (error)
13578 goto done;
13580 if (merge_in_progress && !(abort_merge || continue_merge)) {
13581 error = got_error(GOT_ERR_MERGE_BUSY);
13582 goto done;
13585 if (!merge_in_progress && (abort_merge || continue_merge)) {
13586 error = got_error(GOT_ERR_NOT_MERGING);
13587 goto done;
13590 if (abort_merge) {
13591 error = got_worktree_merge_continue(&branch_name,
13592 &branch_tip, &fileindex, worktree, repo);
13593 if (error)
13594 goto done;
13595 error = got_worktree_merge_abort(worktree, fileindex, repo,
13596 abort_progress, &upa);
13597 if (error)
13598 goto done;
13599 printf("Merge of %s aborted\n", branch_name);
13600 goto done; /* nothing else to do */
13603 if (strncmp(got_worktree_get_head_ref_name(worktree),
13604 "refs/heads/", 11) != 0) {
13605 error = got_error_fmt(GOT_ERR_COMMIT_BRANCH,
13606 "work tree's current branch %s is outside the "
13607 "\"refs/heads/\" reference namespace; "
13608 "update -b required",
13609 got_worktree_get_head_ref_name(worktree));
13610 goto done;
13613 error = get_author(&author, repo, worktree);
13614 if (error)
13615 goto done;
13617 error = got_ref_open(&wt_branch, repo,
13618 got_worktree_get_head_ref_name(worktree), 0);
13619 if (error)
13620 goto done;
13621 error = got_ref_resolve(&wt_branch_tip, repo, wt_branch);
13622 if (error)
13623 goto done;
13625 if (continue_merge) {
13626 struct got_object_id *base_commit_id;
13627 base_commit_id = got_worktree_get_base_commit_id(worktree);
13628 if (got_object_id_cmp(wt_branch_tip, base_commit_id) != 0) {
13629 error = got_error(GOT_ERR_MERGE_COMMIT_OUT_OF_DATE);
13630 goto done;
13632 error = got_worktree_merge_continue(&branch_name,
13633 &branch_tip, &fileindex, worktree, repo);
13634 if (error)
13635 goto done;
13636 } else {
13637 error = got_ref_open(&branch, repo, argv[0], 0);
13638 if (error != NULL)
13639 goto done;
13640 branch_name = strdup(got_ref_get_name(branch));
13641 if (branch_name == NULL) {
13642 error = got_error_from_errno("strdup");
13643 goto done;
13645 error = got_ref_resolve(&branch_tip, repo, branch);
13646 if (error)
13647 goto done;
13650 error = got_commit_graph_find_youngest_common_ancestor(&yca_id,
13651 wt_branch_tip, branch_tip, 0, 0, repo,
13652 check_cancelled, NULL);
13653 if (error && error->code != GOT_ERR_ANCESTRY)
13654 goto done;
13656 if (!continue_merge) {
13657 error = check_path_prefix(wt_branch_tip, branch_tip,
13658 got_worktree_get_path_prefix(worktree),
13659 GOT_ERR_MERGE_PATH, repo);
13660 if (error)
13661 goto done;
13662 error = got_worktree_merge_prepare(&fileindex, worktree, repo);
13663 if (error)
13664 goto done;
13665 if (prefer_fast_forward && yca_id &&
13666 got_object_id_cmp(wt_branch_tip, yca_id) == 0) {
13667 struct got_pathlist_head paths;
13668 if (interrupt_merge) {
13669 error = got_error_fmt(GOT_ERR_BAD_OPTION,
13670 "there are no changes to merge since %s "
13671 "is already based on %s; merge cannot be "
13672 "interrupted for amending; -n",
13673 branch_name, got_ref_get_name(wt_branch));
13674 goto done;
13676 printf("Forwarding %s to %s\n",
13677 got_ref_get_name(wt_branch), branch_name);
13678 error = got_ref_change_ref(wt_branch, branch_tip);
13679 if (error)
13680 goto done;
13681 error = got_ref_write(wt_branch, repo);
13682 if (error)
13683 goto done;
13684 error = got_worktree_set_base_commit_id(worktree, repo,
13685 branch_tip);
13686 if (error)
13687 goto done;
13688 TAILQ_INIT(&paths);
13689 error = got_pathlist_append(&paths, "", NULL);
13690 if (error)
13691 goto done;
13692 error = got_worktree_checkout_files(worktree,
13693 &paths, repo, update_progress, &upa,
13694 check_cancelled, NULL);
13695 got_pathlist_free(&paths, GOT_PATHLIST_FREE_NONE);
13696 if (error)
13697 goto done;
13698 if (upa.did_something) {
13699 char *id_str;
13700 error = got_object_id_str(&id_str, branch_tip);
13701 if (error)
13702 goto done;
13703 printf("Updated to commit %s\n", id_str);
13704 free(id_str);
13705 } else
13706 printf("Already up-to-date\n");
13707 print_update_progress_stats(&upa);
13708 goto done;
13710 error = got_worktree_merge_write_refs(worktree, branch, repo);
13711 if (error)
13712 goto done;
13714 error = got_worktree_merge_branch(worktree, fileindex,
13715 yca_id, branch_tip, repo, update_progress, &upa,
13716 check_cancelled, NULL);
13717 if (error)
13718 goto done;
13719 print_merge_progress_stats(&upa);
13720 if (!upa.did_something) {
13721 error = got_worktree_merge_abort(worktree, fileindex,
13722 repo, abort_progress, &upa);
13723 if (error)
13724 goto done;
13725 printf("Already up-to-date\n");
13726 goto done;
13730 if (interrupt_merge) {
13731 error = got_worktree_merge_postpone(worktree, fileindex);
13732 if (error)
13733 goto done;
13734 printf("Merge of %s interrupted on request\n", branch_name);
13735 } else if (upa.conflicts > 0 || upa.missing > 0 ||
13736 upa.not_deleted > 0 || upa.unversioned > 0) {
13737 error = got_worktree_merge_postpone(worktree, fileindex);
13738 if (error)
13739 goto done;
13740 if (upa.conflicts > 0 && upa.missing == 0 &&
13741 upa.not_deleted == 0 && upa.unversioned == 0) {
13742 error = got_error_msg(GOT_ERR_CONFLICTS,
13743 "conflicts must be resolved before merging "
13744 "can continue");
13745 } else if (upa.conflicts > 0) {
13746 error = got_error_msg(GOT_ERR_CONFLICTS,
13747 "conflicts must be resolved before merging "
13748 "can continue; changes destined for some "
13749 "files were not yet merged and "
13750 "should be merged manually if required before the "
13751 "merge operation is continued");
13752 } else {
13753 error = got_error_msg(GOT_ERR_CONFLICTS,
13754 "changes destined for some "
13755 "files were not yet merged and should be "
13756 "merged manually if required before the "
13757 "merge operation is continued");
13759 goto done;
13760 } else {
13761 error = got_worktree_merge_commit(&merge_commit_id, worktree,
13762 fileindex, author, NULL, 1, branch_tip, branch_name,
13763 allow_conflict, repo, continue_merge ? print_status : NULL,
13764 NULL);
13765 if (error)
13766 goto done;
13767 error = got_worktree_merge_complete(worktree, fileindex, repo);
13768 if (error)
13769 goto done;
13770 error = got_object_id_str(&id_str, merge_commit_id);
13771 if (error)
13772 goto done;
13773 printf("Merged %s into %s: %s\n", branch_name,
13774 got_worktree_get_head_ref_name(worktree),
13775 id_str);
13778 done:
13779 free(gitconfig_path);
13780 free(id_str);
13781 free(merge_commit_id);
13782 free(author);
13783 free(branch_tip);
13784 free(branch_name);
13785 free(yca_id);
13786 if (branch)
13787 got_ref_close(branch);
13788 if (wt_branch)
13789 got_ref_close(wt_branch);
13790 if (worktree)
13791 got_worktree_close(worktree);
13792 if (repo) {
13793 const struct got_error *close_err = got_repo_close(repo);
13794 if (error == NULL)
13795 error = close_err;
13797 if (pack_fds) {
13798 const struct got_error *pack_err =
13799 got_repo_pack_fds_close(pack_fds);
13800 if (error == NULL)
13801 error = pack_err;
13803 return error;
13806 __dead static void
13807 usage_stage(void)
13809 fprintf(stderr, "usage: %s stage [-lpS] [-F response-script] "
13810 "[path ...]\n", getprogname());
13811 exit(1);
13814 static const struct got_error *
13815 print_stage(void *arg, unsigned char status, unsigned char staged_status,
13816 const char *path, struct got_object_id *blob_id,
13817 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
13818 int dirfd, const char *de_name)
13820 const struct got_error *err = NULL;
13821 char *id_str = NULL;
13823 if (staged_status != GOT_STATUS_ADD &&
13824 staged_status != GOT_STATUS_MODIFY &&
13825 staged_status != GOT_STATUS_DELETE)
13826 return NULL;
13828 if (staged_status == GOT_STATUS_ADD ||
13829 staged_status == GOT_STATUS_MODIFY)
13830 err = got_object_id_str(&id_str, staged_blob_id);
13831 else
13832 err = got_object_id_str(&id_str, blob_id);
13833 if (err)
13834 return err;
13836 printf("%s %c %s\n", id_str, staged_status, path);
13837 free(id_str);
13838 return NULL;
13841 static const struct got_error *
13842 cmd_stage(int argc, char *argv[])
13844 const struct got_error *error = NULL;
13845 struct got_repository *repo = NULL;
13846 struct got_worktree *worktree = NULL;
13847 char *cwd = NULL;
13848 struct got_pathlist_head paths;
13849 int ch, list_stage = 0, pflag = 0, allow_bad_symlinks = 0;
13850 FILE *patch_script_file = NULL;
13851 const char *patch_script_path = NULL;
13852 struct choose_patch_arg cpa;
13853 int *pack_fds = NULL;
13855 TAILQ_INIT(&paths);
13857 #ifndef PROFILE
13858 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
13859 "unveil", NULL) == -1)
13860 err(1, "pledge");
13861 #endif
13863 while ((ch = getopt(argc, argv, "F:lpS")) != -1) {
13864 switch (ch) {
13865 case 'F':
13866 patch_script_path = optarg;
13867 break;
13868 case 'l':
13869 list_stage = 1;
13870 break;
13871 case 'p':
13872 pflag = 1;
13873 break;
13874 case 'S':
13875 allow_bad_symlinks = 1;
13876 break;
13877 default:
13878 usage_stage();
13879 /* NOTREACHED */
13883 argc -= optind;
13884 argv += optind;
13886 if (list_stage && (pflag || patch_script_path))
13887 errx(1, "-l option cannot be used with other options");
13888 if (patch_script_path && !pflag)
13889 errx(1, "-F option can only be used together with -p option");
13891 cwd = getcwd(NULL, 0);
13892 if (cwd == NULL) {
13893 error = got_error_from_errno("getcwd");
13894 goto done;
13897 error = got_repo_pack_fds_open(&pack_fds);
13898 if (error != NULL)
13899 goto done;
13901 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
13902 if (error) {
13903 if (error->code == GOT_ERR_NOT_WORKTREE)
13904 error = wrap_not_worktree_error(error, "stage", cwd);
13905 goto done;
13908 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
13909 NULL, pack_fds);
13910 if (error != NULL)
13911 goto done;
13913 if (patch_script_path) {
13914 patch_script_file = fopen(patch_script_path, "re");
13915 if (patch_script_file == NULL) {
13916 error = got_error_from_errno2("fopen",
13917 patch_script_path);
13918 goto done;
13921 error = apply_unveil(got_repo_get_path(repo), 0,
13922 got_worktree_get_root_path(worktree));
13923 if (error)
13924 goto done;
13926 error = check_merge_in_progress(worktree, repo);
13927 if (error)
13928 goto done;
13930 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
13931 if (error)
13932 goto done;
13934 if (list_stage)
13935 error = got_worktree_status(worktree, &paths, repo, 0,
13936 print_stage, NULL, check_cancelled, NULL);
13937 else {
13938 cpa.patch_script_file = patch_script_file;
13939 cpa.action = "stage";
13940 error = got_worktree_stage(worktree, &paths,
13941 pflag ? NULL : print_status, NULL,
13942 pflag ? choose_patch : NULL, &cpa,
13943 allow_bad_symlinks, repo);
13945 done:
13946 if (patch_script_file && fclose(patch_script_file) == EOF &&
13947 error == NULL)
13948 error = got_error_from_errno2("fclose", patch_script_path);
13949 if (repo) {
13950 const struct got_error *close_err = got_repo_close(repo);
13951 if (error == NULL)
13952 error = close_err;
13954 if (worktree)
13955 got_worktree_close(worktree);
13956 if (pack_fds) {
13957 const struct got_error *pack_err =
13958 got_repo_pack_fds_close(pack_fds);
13959 if (error == NULL)
13960 error = pack_err;
13962 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
13963 free(cwd);
13964 return error;
13967 __dead static void
13968 usage_unstage(void)
13970 fprintf(stderr, "usage: %s unstage [-p] [-F response-script] "
13971 "[path ...]\n", getprogname());
13972 exit(1);
13976 static const struct got_error *
13977 cmd_unstage(int argc, char *argv[])
13979 const struct got_error *error = NULL;
13980 struct got_repository *repo = NULL;
13981 struct got_worktree *worktree = NULL;
13982 char *cwd = NULL;
13983 struct got_pathlist_head paths;
13984 int ch, pflag = 0;
13985 struct got_update_progress_arg upa;
13986 FILE *patch_script_file = NULL;
13987 const char *patch_script_path = NULL;
13988 struct choose_patch_arg cpa;
13989 int *pack_fds = NULL;
13991 TAILQ_INIT(&paths);
13993 #ifndef PROFILE
13994 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
13995 "unveil", NULL) == -1)
13996 err(1, "pledge");
13997 #endif
13999 while ((ch = getopt(argc, argv, "F:p")) != -1) {
14000 switch (ch) {
14001 case 'F':
14002 patch_script_path = optarg;
14003 break;
14004 case 'p':
14005 pflag = 1;
14006 break;
14007 default:
14008 usage_unstage();
14009 /* NOTREACHED */
14013 argc -= optind;
14014 argv += optind;
14016 if (patch_script_path && !pflag)
14017 errx(1, "-F option can only be used together with -p option");
14019 cwd = getcwd(NULL, 0);
14020 if (cwd == NULL) {
14021 error = got_error_from_errno("getcwd");
14022 goto done;
14025 error = got_repo_pack_fds_open(&pack_fds);
14026 if (error != NULL)
14027 goto done;
14029 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
14030 if (error) {
14031 if (error->code == GOT_ERR_NOT_WORKTREE)
14032 error = wrap_not_worktree_error(error, "unstage", cwd);
14033 goto done;
14036 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
14037 NULL, pack_fds);
14038 if (error != NULL)
14039 goto done;
14041 if (patch_script_path) {
14042 patch_script_file = fopen(patch_script_path, "re");
14043 if (patch_script_file == NULL) {
14044 error = got_error_from_errno2("fopen",
14045 patch_script_path);
14046 goto done;
14050 error = apply_unveil(got_repo_get_path(repo), 0,
14051 got_worktree_get_root_path(worktree));
14052 if (error)
14053 goto done;
14055 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
14056 if (error)
14057 goto done;
14059 cpa.patch_script_file = patch_script_file;
14060 cpa.action = "unstage";
14061 memset(&upa, 0, sizeof(upa));
14062 error = got_worktree_unstage(worktree, &paths, update_progress,
14063 &upa, pflag ? choose_patch : NULL, &cpa, repo);
14064 if (!error)
14065 print_merge_progress_stats(&upa);
14066 done:
14067 if (patch_script_file && fclose(patch_script_file) == EOF &&
14068 error == NULL)
14069 error = got_error_from_errno2("fclose", patch_script_path);
14070 if (repo) {
14071 const struct got_error *close_err = got_repo_close(repo);
14072 if (error == NULL)
14073 error = close_err;
14075 if (worktree)
14076 got_worktree_close(worktree);
14077 if (pack_fds) {
14078 const struct got_error *pack_err =
14079 got_repo_pack_fds_close(pack_fds);
14080 if (error == NULL)
14081 error = pack_err;
14083 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
14084 free(cwd);
14085 return error;
14088 __dead static void
14089 usage_cat(void)
14091 fprintf(stderr, "usage: %s cat [-P] [-c commit] [-r repository-path] "
14092 "arg ...\n", getprogname());
14093 exit(1);
14096 static const struct got_error *
14097 cat_blob(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
14099 const struct got_error *err;
14100 struct got_blob_object *blob;
14101 int fd = -1;
14103 fd = got_opentempfd();
14104 if (fd == -1)
14105 return got_error_from_errno("got_opentempfd");
14107 err = got_object_open_as_blob(&blob, repo, id, 8192, fd);
14108 if (err)
14109 goto done;
14111 err = got_object_blob_dump_to_file(NULL, NULL, NULL, outfile, blob);
14112 done:
14113 if (fd != -1 && close(fd) == -1 && err == NULL)
14114 err = got_error_from_errno("close");
14115 if (blob)
14116 got_object_blob_close(blob);
14117 return err;
14120 static const struct got_error *
14121 cat_tree(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
14123 const struct got_error *err;
14124 struct got_tree_object *tree;
14125 int nentries, i;
14127 err = got_object_open_as_tree(&tree, repo, id);
14128 if (err)
14129 return err;
14131 nentries = got_object_tree_get_nentries(tree);
14132 for (i = 0; i < nentries; i++) {
14133 struct got_tree_entry *te;
14134 char *id_str;
14135 if (sigint_received || sigpipe_received)
14136 break;
14137 te = got_object_tree_get_entry(tree, i);
14138 err = got_object_id_str(&id_str, got_tree_entry_get_id(te));
14139 if (err)
14140 break;
14141 fprintf(outfile, "%s %.7o %s\n", id_str,
14142 got_tree_entry_get_mode(te),
14143 got_tree_entry_get_name(te));
14144 free(id_str);
14147 got_object_tree_close(tree);
14148 return err;
14151 static const struct got_error *
14152 cat_commit(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
14154 const struct got_error *err;
14155 struct got_commit_object *commit;
14156 const struct got_object_id_queue *parent_ids;
14157 struct got_object_qid *pid;
14158 char *id_str = NULL;
14159 const char *logmsg = NULL;
14160 char gmtoff[6];
14162 err = got_object_open_as_commit(&commit, repo, id);
14163 if (err)
14164 return err;
14166 err = got_object_id_str(&id_str, got_object_commit_get_tree_id(commit));
14167 if (err)
14168 goto done;
14170 fprintf(outfile, "%s%s\n", GOT_COMMIT_LABEL_TREE, id_str);
14171 parent_ids = got_object_commit_get_parent_ids(commit);
14172 fprintf(outfile, "numparents %d\n",
14173 got_object_commit_get_nparents(commit));
14174 STAILQ_FOREACH(pid, parent_ids, entry) {
14175 char *pid_str;
14176 err = got_object_id_str(&pid_str, &pid->id);
14177 if (err)
14178 goto done;
14179 fprintf(outfile, "%s%s\n", GOT_COMMIT_LABEL_PARENT, pid_str);
14180 free(pid_str);
14182 got_date_format_gmtoff(gmtoff, sizeof(gmtoff),
14183 got_object_commit_get_author_gmtoff(commit));
14184 fprintf(outfile, "%s%s %lld %s\n", GOT_COMMIT_LABEL_AUTHOR,
14185 got_object_commit_get_author(commit),
14186 (long long)got_object_commit_get_author_time(commit),
14187 gmtoff);
14189 got_date_format_gmtoff(gmtoff, sizeof(gmtoff),
14190 got_object_commit_get_committer_gmtoff(commit));
14191 fprintf(outfile, "%s%s %lld %s\n", GOT_COMMIT_LABEL_COMMITTER,
14192 got_object_commit_get_committer(commit),
14193 (long long)got_object_commit_get_committer_time(commit),
14194 gmtoff);
14196 logmsg = got_object_commit_get_logmsg_raw(commit);
14197 fprintf(outfile, "messagelen %zd\n", strlen(logmsg));
14198 fprintf(outfile, "%s", logmsg);
14199 done:
14200 free(id_str);
14201 got_object_commit_close(commit);
14202 return err;
14205 static const struct got_error *
14206 cat_tag(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
14208 const struct got_error *err;
14209 struct got_tag_object *tag;
14210 char *id_str = NULL;
14211 const char *tagmsg = NULL;
14212 char gmtoff[6];
14214 err = got_object_open_as_tag(&tag, repo, id);
14215 if (err)
14216 return err;
14218 err = got_object_id_str(&id_str, got_object_tag_get_object_id(tag));
14219 if (err)
14220 goto done;
14222 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_OBJECT, id_str);
14224 switch (got_object_tag_get_object_type(tag)) {
14225 case GOT_OBJ_TYPE_BLOB:
14226 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
14227 GOT_OBJ_LABEL_BLOB);
14228 break;
14229 case GOT_OBJ_TYPE_TREE:
14230 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
14231 GOT_OBJ_LABEL_TREE);
14232 break;
14233 case GOT_OBJ_TYPE_COMMIT:
14234 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
14235 GOT_OBJ_LABEL_COMMIT);
14236 break;
14237 case GOT_OBJ_TYPE_TAG:
14238 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
14239 GOT_OBJ_LABEL_TAG);
14240 break;
14241 default:
14242 break;
14245 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TAG,
14246 got_object_tag_get_name(tag));
14248 got_date_format_gmtoff(gmtoff, sizeof(gmtoff),
14249 got_object_tag_get_tagger_gmtoff(tag));
14250 fprintf(outfile, "%s%s %lld %s\n", GOT_TAG_LABEL_TAGGER,
14251 got_object_tag_get_tagger(tag),
14252 (long long)got_object_tag_get_tagger_time(tag),
14253 gmtoff);
14255 tagmsg = got_object_tag_get_message(tag);
14256 fprintf(outfile, "messagelen %zd\n", strlen(tagmsg));
14257 fprintf(outfile, "%s", tagmsg);
14258 done:
14259 free(id_str);
14260 got_object_tag_close(tag);
14261 return err;
14264 static const struct got_error *
14265 cmd_cat(int argc, char *argv[])
14267 const struct got_error *error;
14268 struct got_repository *repo = NULL;
14269 struct got_worktree *worktree = NULL;
14270 char *cwd = NULL, *repo_path = NULL, *label = NULL;
14271 char *keyword_idstr = NULL;
14272 const char *commit_id_str = NULL;
14273 struct got_object_id *id = NULL, *commit_id = NULL;
14274 struct got_commit_object *commit = NULL;
14275 int ch, obj_type, i, force_path = 0;
14276 struct got_reflist_head refs;
14277 int *pack_fds = NULL;
14279 TAILQ_INIT(&refs);
14281 #ifndef PROFILE
14282 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
14283 NULL) == -1)
14284 err(1, "pledge");
14285 #endif
14287 while ((ch = getopt(argc, argv, "c:Pr:")) != -1) {
14288 switch (ch) {
14289 case 'c':
14290 commit_id_str = optarg;
14291 break;
14292 case 'P':
14293 force_path = 1;
14294 break;
14295 case 'r':
14296 repo_path = realpath(optarg, NULL);
14297 if (repo_path == NULL)
14298 return got_error_from_errno2("realpath",
14299 optarg);
14300 got_path_strip_trailing_slashes(repo_path);
14301 break;
14302 default:
14303 usage_cat();
14304 /* NOTREACHED */
14308 argc -= optind;
14309 argv += optind;
14311 cwd = getcwd(NULL, 0);
14312 if (cwd == NULL) {
14313 error = got_error_from_errno("getcwd");
14314 goto done;
14317 error = got_repo_pack_fds_open(&pack_fds);
14318 if (error != NULL)
14319 goto done;
14321 if (repo_path == NULL) {
14322 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
14323 if (error && error->code != GOT_ERR_NOT_WORKTREE)
14324 goto done;
14325 if (worktree) {
14326 repo_path = strdup(
14327 got_worktree_get_repo_path(worktree));
14328 if (repo_path == NULL) {
14329 error = got_error_from_errno("strdup");
14330 goto done;
14333 if (commit_id_str == NULL) {
14334 /* Release work tree lock. */
14335 got_worktree_close(worktree);
14336 worktree = NULL;
14341 if (repo_path == NULL) {
14342 repo_path = strdup(cwd);
14343 if (repo_path == NULL)
14344 return got_error_from_errno("strdup");
14347 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
14348 free(repo_path);
14349 if (error != NULL)
14350 goto done;
14352 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
14353 if (error)
14354 goto done;
14356 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
14357 if (error)
14358 goto done;
14360 if (commit_id_str != NULL) {
14361 error = got_keyword_to_idstr(&keyword_idstr, commit_id_str,
14362 repo, worktree);
14363 if (error != NULL)
14364 goto done;
14365 if (keyword_idstr != NULL)
14366 commit_id_str = keyword_idstr;
14367 if (worktree != NULL) {
14368 got_worktree_close(worktree);
14369 worktree = NULL;
14371 } else
14372 commit_id_str = GOT_REF_HEAD;
14373 error = got_repo_match_object_id(&commit_id, NULL,
14374 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
14375 if (error)
14376 goto done;
14378 error = got_object_open_as_commit(&commit, repo, commit_id);
14379 if (error)
14380 goto done;
14382 for (i = 0; i < argc; i++) {
14383 if (force_path) {
14384 error = got_object_id_by_path(&id, repo, commit,
14385 argv[i]);
14386 if (error)
14387 break;
14388 } else {
14389 error = got_repo_match_object_id(&id, &label, argv[i],
14390 GOT_OBJ_TYPE_ANY, NULL /* do not resolve tags */,
14391 repo);
14392 if (error) {
14393 if (error->code != GOT_ERR_BAD_OBJ_ID_STR &&
14394 error->code != GOT_ERR_NOT_REF)
14395 break;
14396 error = got_object_id_by_path(&id, repo,
14397 commit, argv[i]);
14398 if (error)
14399 break;
14403 error = got_object_get_type(&obj_type, repo, id);
14404 if (error)
14405 break;
14407 switch (obj_type) {
14408 case GOT_OBJ_TYPE_BLOB:
14409 error = cat_blob(id, repo, stdout);
14410 break;
14411 case GOT_OBJ_TYPE_TREE:
14412 error = cat_tree(id, repo, stdout);
14413 break;
14414 case GOT_OBJ_TYPE_COMMIT:
14415 error = cat_commit(id, repo, stdout);
14416 break;
14417 case GOT_OBJ_TYPE_TAG:
14418 error = cat_tag(id, repo, stdout);
14419 break;
14420 default:
14421 error = got_error(GOT_ERR_OBJ_TYPE);
14422 break;
14424 if (error)
14425 break;
14426 free(label);
14427 label = NULL;
14428 free(id);
14429 id = NULL;
14431 done:
14432 free(label);
14433 free(id);
14434 free(commit_id);
14435 free(keyword_idstr);
14436 if (commit)
14437 got_object_commit_close(commit);
14438 if (worktree)
14439 got_worktree_close(worktree);
14440 if (repo) {
14441 const struct got_error *close_err = got_repo_close(repo);
14442 if (error == NULL)
14443 error = close_err;
14445 if (pack_fds) {
14446 const struct got_error *pack_err =
14447 got_repo_pack_fds_close(pack_fds);
14448 if (error == NULL)
14449 error = pack_err;
14452 got_ref_list_free(&refs);
14453 return error;
14456 __dead static void
14457 usage_info(void)
14459 fprintf(stderr, "usage: %s info [path ...]\n",
14460 getprogname());
14461 exit(1);
14464 static const struct got_error *
14465 print_path_info(void *arg, const char *path, mode_t mode, time_t mtime,
14466 struct got_object_id *blob_id, struct got_object_id *staged_blob_id,
14467 struct got_object_id *commit_id)
14469 const struct got_error *err = NULL;
14470 char *id_str = NULL;
14471 char datebuf[128];
14472 struct tm mytm, *tm;
14473 struct got_pathlist_head *paths = arg;
14474 struct got_pathlist_entry *pe;
14477 * Clear error indication from any of the path arguments which
14478 * would cause this file index entry to be displayed.
14480 TAILQ_FOREACH(pe, paths, entry) {
14481 if (got_path_cmp(path, pe->path, strlen(path),
14482 pe->path_len) == 0 ||
14483 got_path_is_child(path, pe->path, pe->path_len))
14484 pe->data = NULL; /* no error */
14487 printf(GOT_COMMIT_SEP_STR);
14488 if (S_ISLNK(mode))
14489 printf("symlink: %s\n", path);
14490 else if (S_ISREG(mode)) {
14491 printf("file: %s\n", path);
14492 printf("mode: %o\n", mode & (S_IRWXU | S_IRWXG | S_IRWXO));
14493 } else if (S_ISDIR(mode))
14494 printf("directory: %s\n", path);
14495 else
14496 printf("something: %s\n", path);
14498 tm = localtime_r(&mtime, &mytm);
14499 if (tm == NULL)
14500 return NULL;
14501 if (strftime(datebuf, sizeof(datebuf), "%c %Z", tm) == 0)
14502 return got_error(GOT_ERR_NO_SPACE);
14503 printf("timestamp: %s\n", datebuf);
14505 if (blob_id) {
14506 err = got_object_id_str(&id_str, blob_id);
14507 if (err)
14508 return err;
14509 printf("based on blob: %s\n", id_str);
14510 free(id_str);
14513 if (staged_blob_id) {
14514 err = got_object_id_str(&id_str, staged_blob_id);
14515 if (err)
14516 return err;
14517 printf("based on staged blob: %s\n", id_str);
14518 free(id_str);
14521 if (commit_id) {
14522 err = got_object_id_str(&id_str, commit_id);
14523 if (err)
14524 return err;
14525 printf("based on commit: %s\n", id_str);
14526 free(id_str);
14529 return NULL;
14532 static const struct got_error *
14533 cmd_info(int argc, char *argv[])
14535 const struct got_error *error = NULL;
14536 struct got_worktree *worktree = NULL;
14537 char *cwd = NULL, *id_str = NULL;
14538 struct got_pathlist_head paths;
14539 char *uuidstr = NULL;
14540 int ch, show_files = 0;
14542 TAILQ_INIT(&paths);
14544 #ifndef PROFILE
14545 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
14546 NULL) == -1)
14547 err(1, "pledge");
14548 #endif
14550 while ((ch = getopt(argc, argv, "")) != -1) {
14551 switch (ch) {
14552 default:
14553 usage_info();
14554 /* NOTREACHED */
14558 argc -= optind;
14559 argv += optind;
14561 cwd = getcwd(NULL, 0);
14562 if (cwd == NULL) {
14563 error = got_error_from_errno("getcwd");
14564 goto done;
14567 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
14568 if (error) {
14569 if (error->code == GOT_ERR_NOT_WORKTREE)
14570 error = wrap_not_worktree_error(error, "info", cwd);
14571 goto done;
14574 #ifndef PROFILE
14575 /* Remove "wpath cpath proc exec sendfd" promises. */
14576 if (pledge("stdio rpath flock unveil", NULL) == -1)
14577 err(1, "pledge");
14578 #endif
14579 error = apply_unveil(NULL, 0, got_worktree_get_root_path(worktree));
14580 if (error)
14581 goto done;
14583 if (argc >= 1) {
14584 error = get_worktree_paths_from_argv(&paths, argc, argv,
14585 worktree);
14586 if (error)
14587 goto done;
14588 show_files = 1;
14591 error = got_object_id_str(&id_str,
14592 got_worktree_get_base_commit_id(worktree));
14593 if (error)
14594 goto done;
14596 error = got_worktree_get_uuid(&uuidstr, worktree);
14597 if (error)
14598 goto done;
14600 printf("work tree: %s\n", got_worktree_get_root_path(worktree));
14601 printf("work tree base commit: %s\n", id_str);
14602 printf("work tree path prefix: %s\n",
14603 got_worktree_get_path_prefix(worktree));
14604 printf("work tree branch reference: %s\n",
14605 got_worktree_get_head_ref_name(worktree));
14606 printf("work tree UUID: %s\n", uuidstr);
14607 printf("repository: %s\n", got_worktree_get_repo_path(worktree));
14609 if (show_files) {
14610 struct got_pathlist_entry *pe;
14611 TAILQ_FOREACH(pe, &paths, entry) {
14612 if (pe->path_len == 0)
14613 continue;
14615 * Assume this path will fail. This will be corrected
14616 * in print_path_info() in case the path does suceeed.
14618 pe->data = (void *)got_error(GOT_ERR_BAD_PATH);
14620 error = got_worktree_path_info(worktree, &paths,
14621 print_path_info, &paths, check_cancelled, NULL);
14622 if (error)
14623 goto done;
14624 TAILQ_FOREACH(pe, &paths, entry) {
14625 if (pe->data != NULL) {
14626 const struct got_error *perr;
14628 perr = pe->data;
14629 error = got_error_fmt(perr->code, "%s",
14630 pe->path);
14631 break;
14635 done:
14636 if (worktree)
14637 got_worktree_close(worktree);
14638 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
14639 free(cwd);
14640 free(id_str);
14641 free(uuidstr);
14642 return error;