Blob


1 /*
2 * Copyright (c) 2017 Martin Pieuchot <mpi@openbsd.org>
3 * Copyright (c) 2018, 2019, 2020 Stefan Sperling <stsp@openbsd.org>
4 * Copyright (c) 2020 Ori Bernstein <ori@openbsd.org>
5 *
6 * Permission to use, copy, modify, and distribute this software for any
7 * purpose with or without fee is hereby granted, provided that the above
8 * copyright notice and this permission notice appear in all copies.
9 *
10 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
11 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
12 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
13 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
14 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
15 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
16 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
17 */
19 #include "got_compat.h"
21 #include <sys/queue.h>
22 #include <sys/time.h>
23 #include <sys/types.h>
24 #include <sys/stat.h>
25 #include <sys/wait.h>
27 #include <err.h>
28 #include <errno.h>
29 #include <fcntl.h>
30 #include <limits.h>
31 #include <locale.h>
32 #include <ctype.h>
33 #include <signal.h>
34 #include <stdio.h>
35 #include <stdlib.h>
36 #include <string.h>
37 #include <unistd.h>
38 #include <libgen.h>
39 #include <time.h>
40 #include <paths.h>
41 #include <regex.h>
42 #include <getopt.h>
44 #include "got_version.h"
45 #include "got_error.h"
46 #include "got_object.h"
47 #include "got_reference.h"
48 #include "got_repository.h"
49 #include "got_path.h"
50 #include "got_cancel.h"
51 #include "got_worktree.h"
52 #include "got_diff.h"
53 #include "got_commit_graph.h"
54 #include "got_fetch.h"
55 #include "got_send.h"
56 #include "got_blame.h"
57 #include "got_privsep.h"
58 #include "got_opentemp.h"
59 #include "got_gotconfig.h"
60 #include "got_dial.h"
61 #include "got_patch.h"
62 #include "got_sigs.h"
63 #include "got_date.h"
64 #include "got_keyword.h"
66 #ifndef nitems
67 #define nitems(_a) (sizeof((_a)) / sizeof((_a)[0]))
68 #endif
70 #ifndef GOT_DEFAULT_EDITOR
71 #define GOT_DEFAULT_EDITOR "/usr/bin/vi"
72 #endif
74 static volatile sig_atomic_t sigint_received;
75 static volatile sig_atomic_t sigpipe_received;
77 static void
78 catch_sigint(int signo)
79 {
80 sigint_received = 1;
81 }
83 static void
84 catch_sigpipe(int signo)
85 {
86 sigpipe_received = 1;
87 }
90 struct got_cmd {
91 const char *cmd_name;
92 const struct got_error *(*cmd_main)(int, char *[]);
93 void (*cmd_usage)(void);
94 const char *cmd_alias;
95 };
97 __dead static void usage(int, int);
98 __dead static void usage_import(void);
99 __dead static void usage_clone(void);
100 __dead static void usage_fetch(void);
101 __dead static void usage_checkout(void);
102 __dead static void usage_update(void);
103 __dead static void usage_log(void);
104 __dead static void usage_diff(void);
105 __dead static void usage_blame(void);
106 __dead static void usage_tree(void);
107 __dead static void usage_status(void);
108 __dead static void usage_ref(void);
109 __dead static void usage_branch(void);
110 __dead static void usage_tag(void);
111 __dead static void usage_add(void);
112 __dead static void usage_remove(void);
113 __dead static void usage_patch(void);
114 __dead static void usage_revert(void);
115 __dead static void usage_commit(void);
116 __dead static void usage_send(void);
117 __dead static void usage_cherrypick(void);
118 __dead static void usage_backout(void);
119 __dead static void usage_rebase(void);
120 __dead static void usage_histedit(void);
121 __dead static void usage_integrate(void);
122 __dead static void usage_merge(void);
123 __dead static void usage_stage(void);
124 __dead static void usage_unstage(void);
125 __dead static void usage_cat(void);
126 __dead static void usage_info(void);
128 static const struct got_error* cmd_import(int, char *[]);
129 static const struct got_error* cmd_clone(int, char *[]);
130 static const struct got_error* cmd_fetch(int, char *[]);
131 static const struct got_error* cmd_checkout(int, char *[]);
132 static const struct got_error* cmd_update(int, char *[]);
133 static const struct got_error* cmd_log(int, char *[]);
134 static const struct got_error* cmd_diff(int, char *[]);
135 static const struct got_error* cmd_blame(int, char *[]);
136 static const struct got_error* cmd_tree(int, char *[]);
137 static const struct got_error* cmd_status(int, char *[]);
138 static const struct got_error* cmd_ref(int, char *[]);
139 static const struct got_error* cmd_branch(int, char *[]);
140 static const struct got_error* cmd_tag(int, char *[]);
141 static const struct got_error* cmd_add(int, char *[]);
142 static const struct got_error* cmd_remove(int, char *[]);
143 static const struct got_error* cmd_patch(int, char *[]);
144 static const struct got_error* cmd_revert(int, char *[]);
145 static const struct got_error* cmd_commit(int, char *[]);
146 static const struct got_error* cmd_send(int, char *[]);
147 static const struct got_error* cmd_cherrypick(int, char *[]);
148 static const struct got_error* cmd_backout(int, char *[]);
149 static const struct got_error* cmd_rebase(int, char *[]);
150 static const struct got_error* cmd_histedit(int, char *[]);
151 static const struct got_error* cmd_integrate(int, char *[]);
152 static const struct got_error* cmd_merge(int, char *[]);
153 static const struct got_error* cmd_stage(int, char *[]);
154 static const struct got_error* cmd_unstage(int, char *[]);
155 static const struct got_error* cmd_cat(int, char *[]);
156 static const struct got_error* cmd_info(int, char *[]);
158 static const struct got_cmd got_commands[] = {
159 { "import", cmd_import, usage_import, "im" },
160 { "clone", cmd_clone, usage_clone, "cl" },
161 { "fetch", cmd_fetch, usage_fetch, "fe" },
162 { "checkout", cmd_checkout, usage_checkout, "co" },
163 { "update", cmd_update, usage_update, "up" },
164 { "log", cmd_log, usage_log, "" },
165 { "diff", cmd_diff, usage_diff, "di" },
166 { "blame", cmd_blame, usage_blame, "bl" },
167 { "tree", cmd_tree, usage_tree, "tr" },
168 { "status", cmd_status, usage_status, "st" },
169 { "ref", cmd_ref, usage_ref, "" },
170 { "branch", cmd_branch, usage_branch, "br" },
171 { "tag", cmd_tag, usage_tag, "" },
172 { "add", cmd_add, usage_add, "" },
173 { "remove", cmd_remove, usage_remove, "rm" },
174 { "patch", cmd_patch, usage_patch, "pa" },
175 { "revert", cmd_revert, usage_revert, "rv" },
176 { "commit", cmd_commit, usage_commit, "ci" },
177 { "send", cmd_send, usage_send, "se" },
178 { "cherrypick", cmd_cherrypick, usage_cherrypick, "cy" },
179 { "backout", cmd_backout, usage_backout, "bo" },
180 { "rebase", cmd_rebase, usage_rebase, "rb" },
181 { "histedit", cmd_histedit, usage_histedit, "he" },
182 { "integrate", cmd_integrate, usage_integrate,"ig" },
183 { "merge", cmd_merge, usage_merge, "mg" },
184 { "stage", cmd_stage, usage_stage, "sg" },
185 { "unstage", cmd_unstage, usage_unstage, "ug" },
186 { "cat", cmd_cat, usage_cat, "" },
187 { "info", cmd_info, usage_info, "" },
188 };
190 static void
191 list_commands(FILE *fp)
193 size_t i;
195 fprintf(fp, "commands:");
196 for (i = 0; i < nitems(got_commands); i++) {
197 const struct got_cmd *cmd = &got_commands[i];
198 fprintf(fp, " %s", cmd->cmd_name);
200 fputc('\n', fp);
203 __dead static void
204 option_conflict(char a, char b)
206 errx(1, "-%c and -%c options are mutually exclusive", a, b);
209 int
210 main(int argc, char *argv[])
212 const struct got_cmd *cmd;
213 size_t i;
214 int ch;
215 int hflag = 0, Vflag = 0;
216 static const struct option longopts[] = {
217 { "version", no_argument, NULL, 'V' },
218 { NULL, 0, NULL, 0 }
219 };
221 setlocale(LC_CTYPE, "");
223 while ((ch = getopt_long(argc, argv, "+hV", longopts, NULL)) != -1) {
224 switch (ch) {
225 case 'h':
226 hflag = 1;
227 break;
228 case 'V':
229 Vflag = 1;
230 break;
231 default:
232 usage(hflag, 1);
233 /* NOTREACHED */
237 argc -= optind;
238 argv += optind;
239 optind = 1;
240 optreset = 1;
242 if (Vflag) {
243 got_version_print_str();
244 return 0;
247 if (argc <= 0)
248 usage(hflag, hflag ? 0 : 1);
250 signal(SIGINT, catch_sigint);
251 signal(SIGPIPE, catch_sigpipe);
253 for (i = 0; i < nitems(got_commands); i++) {
254 const struct got_error *error;
256 cmd = &got_commands[i];
258 if (strcmp(cmd->cmd_name, argv[0]) != 0 &&
259 strcmp(cmd->cmd_alias, argv[0]) != 0)
260 continue;
262 if (hflag)
263 cmd->cmd_usage();
265 error = cmd->cmd_main(argc, argv);
266 if (error && error->code != GOT_ERR_CANCELLED &&
267 error->code != GOT_ERR_PRIVSEP_EXIT &&
268 !(sigpipe_received &&
269 error->code == GOT_ERR_ERRNO && errno == EPIPE) &&
270 !(sigint_received &&
271 error->code == GOT_ERR_ERRNO && errno == EINTR)) {
272 fflush(stdout);
273 fprintf(stderr, "%s: %s\n", getprogname(), error->msg);
274 return 1;
277 return 0;
280 fprintf(stderr, "%s: unknown command '%s'\n", getprogname(), argv[0]);
281 list_commands(stderr);
282 return 1;
285 __dead static void
286 usage(int hflag, int status)
288 FILE *fp = (status == 0) ? stdout : stderr;
290 fprintf(fp, "usage: %s [-hV] command [arg ...]\n",
291 getprogname());
292 if (hflag)
293 list_commands(fp);
294 exit(status);
297 static const struct got_error *
298 get_editor(char **abspath)
300 const struct got_error *err = NULL;
301 const char *editor;
303 *abspath = NULL;
305 editor = getenv("VISUAL");
306 if (editor == NULL)
307 editor = getenv("EDITOR");
309 if (editor) {
310 err = got_path_find_prog(abspath, editor);
311 if (err)
312 return err;
315 if (*abspath == NULL) {
316 *abspath = strdup(GOT_DEFAULT_EDITOR);
317 if (*abspath == NULL)
318 return got_error_from_errno("strdup");
321 return NULL;
324 static const struct got_error *
325 apply_unveil(const char *repo_path, int repo_read_only,
326 const char *worktree_path)
328 const struct got_error *err;
330 #ifdef PROFILE
331 if (unveil("gmon.out", "rwc") != 0)
332 return got_error_from_errno2("unveil", "gmon.out");
333 #endif
334 if (repo_path && unveil(repo_path, repo_read_only ? "r" : "rwc") != 0)
335 return got_error_from_errno2("unveil", repo_path);
337 if (worktree_path && unveil(worktree_path, "rwc") != 0)
338 return got_error_from_errno2("unveil", worktree_path);
340 if (unveil(GOT_TMPDIR_STR, "rwc") != 0)
341 return got_error_from_errno2("unveil", GOT_TMPDIR_STR);
343 err = got_privsep_unveil_exec_helpers();
344 if (err != NULL)
345 return err;
347 if (unveil(NULL, NULL) != 0)
348 return got_error_from_errno("unveil");
350 return NULL;
353 __dead static void
354 usage_import(void)
356 fprintf(stderr, "usage: %s import [-b branch] [-I pattern] [-m message] "
357 "[-r repository-path] directory\n", getprogname());
358 exit(1);
361 static int
362 spawn_editor(const char *editor, const char *file)
364 pid_t pid;
365 sig_t sighup, sigint, sigquit;
366 int st = -1;
368 sighup = signal(SIGHUP, SIG_IGN);
369 sigint = signal(SIGINT, SIG_IGN);
370 sigquit = signal(SIGQUIT, SIG_IGN);
372 switch (pid = fork()) {
373 case -1:
374 goto doneediting;
375 case 0:
376 execl(editor, editor, file, (char *)NULL);
377 _exit(127);
380 while (waitpid(pid, &st, 0) == -1)
381 if (errno != EINTR)
382 break;
384 doneediting:
385 (void)signal(SIGHUP, sighup);
386 (void)signal(SIGINT, sigint);
387 (void)signal(SIGQUIT, sigquit);
389 if (!WIFEXITED(st)) {
390 errno = EINTR;
391 return -1;
394 return WEXITSTATUS(st);
397 static const struct got_error *
398 read_logmsg(char **logmsg, size_t *len, FILE *fp, size_t filesize)
400 const struct got_error *err = NULL;
401 char *line = NULL;
402 size_t linesize = 0;
404 *logmsg = NULL;
405 *len = 0;
407 if (fseeko(fp, 0L, SEEK_SET) == -1)
408 return got_error_from_errno("fseeko");
410 *logmsg = malloc(filesize + 1);
411 if (*logmsg == NULL)
412 return got_error_from_errno("malloc");
413 (*logmsg)[0] = '\0';
415 while (getline(&line, &linesize, fp) != -1) {
416 if (line[0] == '#' || (*len == 0 && line[0] == '\n'))
417 continue; /* remove comments and leading empty lines */
418 *len = strlcat(*logmsg, line, filesize + 1);
419 if (*len >= filesize + 1) {
420 err = got_error(GOT_ERR_NO_SPACE);
421 goto done;
424 if (ferror(fp)) {
425 err = got_ferror(fp, GOT_ERR_IO);
426 goto done;
429 while (*len > 0 && (*logmsg)[*len - 1] == '\n') {
430 (*logmsg)[*len - 1] = '\0';
431 (*len)--;
433 done:
434 free(line);
435 if (err) {
436 free(*logmsg);
437 *logmsg = NULL;
438 *len = 0;
440 return err;
443 static const struct got_error *
444 edit_logmsg(char **logmsg, const char *editor, const char *logmsg_path,
445 const char *initial_content, size_t initial_content_len,
446 int require_modification)
448 const struct got_error *err = NULL;
449 struct stat st, st2;
450 FILE *fp = NULL;
451 size_t logmsg_len;
453 *logmsg = NULL;
455 if (stat(logmsg_path, &st) == -1)
456 return got_error_from_errno2("stat", logmsg_path);
458 if (spawn_editor(editor, logmsg_path) == -1)
459 return got_error_from_errno("failed spawning editor");
461 if (require_modification) {
462 struct timespec timeout;
464 timeout.tv_sec = 0;
465 timeout.tv_nsec = 1;
466 nanosleep(&timeout, NULL);
469 if (stat(logmsg_path, &st2) == -1)
470 return got_error_from_errno2("stat", logmsg_path);
472 if (require_modification && st.st_size == st2.st_size &&
473 timespeccmp(&st.st_mtim, &st2.st_mtim, ==))
474 return got_error_msg(GOT_ERR_COMMIT_MSG_EMPTY,
475 "no changes made to commit message, aborting");
477 fp = fopen(logmsg_path, "re");
478 if (fp == NULL) {
479 err = got_error_from_errno("fopen");
480 goto done;
483 /* strip comments and leading/trailing newlines */
484 err = read_logmsg(logmsg, &logmsg_len, fp, st2.st_size);
485 if (err)
486 goto done;
487 if (logmsg_len == 0) {
488 err = got_error_msg(GOT_ERR_COMMIT_MSG_EMPTY,
489 "commit message cannot be empty, aborting");
490 goto done;
492 done:
493 if (fp && fclose(fp) == EOF && err == NULL)
494 err = got_error_from_errno("fclose");
495 if (err) {
496 free(*logmsg);
497 *logmsg = NULL;
499 return err;
502 static const struct got_error *
503 collect_import_msg(char **logmsg, char **logmsg_path, const char *editor,
504 const char *path_dir, const char *branch_name)
506 char *initial_content = NULL;
507 const struct got_error *err = NULL;
508 int initial_content_len;
509 int fd = -1;
511 initial_content_len = asprintf(&initial_content,
512 "\n# %s to be imported to branch %s\n", path_dir,
513 branch_name);
514 if (initial_content_len == -1)
515 return got_error_from_errno("asprintf");
517 err = got_opentemp_named_fd(logmsg_path, &fd,
518 GOT_TMPDIR_STR "/got-importmsg", "");
519 if (err)
520 goto done;
522 if (write(fd, initial_content, initial_content_len) == -1) {
523 err = got_error_from_errno2("write", *logmsg_path);
524 goto done;
526 if (close(fd) == -1) {
527 err = got_error_from_errno2("close", *logmsg_path);
528 goto done;
530 fd = -1;
532 err = edit_logmsg(logmsg, editor, *logmsg_path, initial_content,
533 initial_content_len, 1);
534 done:
535 if (fd != -1 && close(fd) == -1 && err == NULL)
536 err = got_error_from_errno2("close", *logmsg_path);
537 free(initial_content);
538 if (err) {
539 free(*logmsg_path);
540 *logmsg_path = NULL;
542 return err;
545 static const struct got_error *
546 import_progress(void *arg, const char *path)
548 printf("A %s\n", path);
549 return NULL;
552 static const struct got_error *
553 valid_author(const char *author)
555 const char *email = author;
557 /*
558 * Git' expects the author (or committer) to be in the form
559 * "name <email>", which are mostly free form (see the
560 * "committer" description in git-fast-import(1)). We're only
561 * doing this to avoid git's object parser breaking on commits
562 * we create.
563 */
565 while (*author && *author != '\n' && *author != '<' && *author != '>')
566 author++;
567 if (author != email && *author == '<' && *(author - 1) != ' ')
568 return got_error_fmt(GOT_ERR_COMMIT_BAD_AUTHOR, "%s: space "
569 "between author name and email required", email);
570 if (*author++ != '<')
571 return got_error_fmt(GOT_ERR_COMMIT_NO_EMAIL, "%s", email);
572 while (*author && *author != '\n' && *author != '<' && *author != '>')
573 author++;
574 if (strcmp(author, ">") != 0)
575 return got_error_fmt(GOT_ERR_COMMIT_NO_EMAIL, "%s", email);
576 return NULL;
579 static const struct got_error *
580 get_author(char **author, struct got_repository *repo,
581 struct got_worktree *worktree)
583 const struct got_error *err = NULL;
584 const char *got_author = NULL, *name, *email;
585 const struct got_gotconfig *worktree_conf = NULL, *repo_conf = NULL;
587 *author = NULL;
589 if (worktree)
590 worktree_conf = got_worktree_get_gotconfig(worktree);
591 repo_conf = got_repo_get_gotconfig(repo);
593 /*
594 * Priority of potential author information sources, from most
595 * significant to least significant:
596 * 1) work tree's .got/got.conf file
597 * 2) repository's got.conf file
598 * 3) repository's git config file
599 * 4) environment variables
600 * 5) global git config files (in user's home directory or /etc)
601 */
603 if (worktree_conf)
604 got_author = got_gotconfig_get_author(worktree_conf);
605 if (got_author == NULL)
606 got_author = got_gotconfig_get_author(repo_conf);
607 if (got_author == NULL) {
608 name = got_repo_get_gitconfig_author_name(repo);
609 email = got_repo_get_gitconfig_author_email(repo);
610 if (name && email) {
611 if (asprintf(author, "%s <%s>", name, email) == -1)
612 return got_error_from_errno("asprintf");
613 return NULL;
616 got_author = getenv("GOT_AUTHOR");
617 if (got_author == NULL) {
618 name = got_repo_get_global_gitconfig_author_name(repo);
619 email = got_repo_get_global_gitconfig_author_email(
620 repo);
621 if (name && email) {
622 if (asprintf(author, "%s <%s>", name, email)
623 == -1)
624 return got_error_from_errno("asprintf");
625 return NULL;
627 /* TODO: Look up user in password database? */
628 return got_error(GOT_ERR_COMMIT_NO_AUTHOR);
632 *author = strdup(got_author);
633 if (*author == NULL)
634 return got_error_from_errno("strdup");
636 err = valid_author(*author);
637 if (err) {
638 free(*author);
639 *author = NULL;
641 return err;
644 static const struct got_error *
645 get_allowed_signers(char **allowed_signers, struct got_repository *repo,
646 struct got_worktree *worktree)
648 const char *got_allowed_signers = NULL;
649 const struct got_gotconfig *worktree_conf = NULL, *repo_conf = NULL;
651 *allowed_signers = NULL;
653 if (worktree)
654 worktree_conf = got_worktree_get_gotconfig(worktree);
655 repo_conf = got_repo_get_gotconfig(repo);
657 /*
658 * Priority of potential author information sources, from most
659 * significant to least significant:
660 * 1) work tree's .got/got.conf file
661 * 2) repository's got.conf file
662 */
664 if (worktree_conf)
665 got_allowed_signers = got_gotconfig_get_allowed_signers_file(
666 worktree_conf);
667 if (got_allowed_signers == NULL)
668 got_allowed_signers = got_gotconfig_get_allowed_signers_file(
669 repo_conf);
671 if (got_allowed_signers) {
672 *allowed_signers = strdup(got_allowed_signers);
673 if (*allowed_signers == NULL)
674 return got_error_from_errno("strdup");
676 return NULL;
679 static const struct got_error *
680 get_revoked_signers(char **revoked_signers, struct got_repository *repo,
681 struct got_worktree *worktree)
683 const char *got_revoked_signers = NULL;
684 const struct got_gotconfig *worktree_conf = NULL, *repo_conf = NULL;
686 *revoked_signers = NULL;
688 if (worktree)
689 worktree_conf = got_worktree_get_gotconfig(worktree);
690 repo_conf = got_repo_get_gotconfig(repo);
692 /*
693 * Priority of potential author information sources, from most
694 * significant to least significant:
695 * 1) work tree's .got/got.conf file
696 * 2) repository's got.conf file
697 */
699 if (worktree_conf)
700 got_revoked_signers = got_gotconfig_get_revoked_signers_file(
701 worktree_conf);
702 if (got_revoked_signers == NULL)
703 got_revoked_signers = got_gotconfig_get_revoked_signers_file(
704 repo_conf);
706 if (got_revoked_signers) {
707 *revoked_signers = strdup(got_revoked_signers);
708 if (*revoked_signers == NULL)
709 return got_error_from_errno("strdup");
711 return NULL;
714 static const char *
715 get_signer_id(struct got_repository *repo, struct got_worktree *worktree)
717 const char *got_signer_id = NULL;
718 const struct got_gotconfig *worktree_conf = NULL, *repo_conf = NULL;
720 if (worktree)
721 worktree_conf = got_worktree_get_gotconfig(worktree);
722 repo_conf = got_repo_get_gotconfig(repo);
724 /*
725 * Priority of potential author information sources, from most
726 * significant to least significant:
727 * 1) work tree's .got/got.conf file
728 * 2) repository's got.conf file
729 */
731 if (worktree_conf)
732 got_signer_id = got_gotconfig_get_signer_id(worktree_conf);
733 if (got_signer_id == NULL)
734 got_signer_id = got_gotconfig_get_signer_id(repo_conf);
736 return got_signer_id;
739 static const struct got_error *
740 get_gitconfig_path(char **gitconfig_path)
742 const char *homedir = getenv("HOME");
744 *gitconfig_path = NULL;
745 if (homedir) {
746 if (asprintf(gitconfig_path, "%s/.gitconfig", homedir) == -1)
747 return got_error_from_errno("asprintf");
750 return NULL;
753 static const struct got_error *
754 cmd_import(int argc, char *argv[])
756 const struct got_error *error = NULL;
757 char *path_dir = NULL, *repo_path = NULL, *logmsg = NULL;
758 char *gitconfig_path = NULL, *editor = NULL, *author = NULL;
759 const char *branch_name = NULL;
760 char *id_str = NULL, *logmsg_path = NULL;
761 char refname[PATH_MAX] = "refs/heads/";
762 struct got_repository *repo = NULL;
763 struct got_reference *branch_ref = NULL, *head_ref = NULL;
764 struct got_object_id *new_commit_id = NULL;
765 int ch, n = 0;
766 struct got_pathlist_head ignores;
767 struct got_pathlist_entry *pe;
768 int preserve_logmsg = 0;
769 int *pack_fds = NULL;
771 TAILQ_INIT(&ignores);
773 #ifndef PROFILE
774 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
775 "unveil",
776 NULL) == -1)
777 err(1, "pledge");
778 #endif
780 while ((ch = getopt(argc, argv, "b:I:m:r:")) != -1) {
781 switch (ch) {
782 case 'b':
783 branch_name = optarg;
784 break;
785 case 'I':
786 if (optarg[0] == '\0')
787 break;
788 error = got_pathlist_insert(&pe, &ignores, optarg,
789 NULL);
790 if (error)
791 goto done;
792 break;
793 case 'm':
794 logmsg = strdup(optarg);
795 if (logmsg == NULL) {
796 error = got_error_from_errno("strdup");
797 goto done;
799 break;
800 case 'r':
801 repo_path = realpath(optarg, NULL);
802 if (repo_path == NULL) {
803 error = got_error_from_errno2("realpath",
804 optarg);
805 goto done;
807 break;
808 default:
809 usage_import();
810 /* NOTREACHED */
814 argc -= optind;
815 argv += optind;
817 if (argc != 1)
818 usage_import();
820 if (repo_path == NULL) {
821 repo_path = getcwd(NULL, 0);
822 if (repo_path == NULL)
823 return got_error_from_errno("getcwd");
825 got_path_strip_trailing_slashes(repo_path);
826 error = get_gitconfig_path(&gitconfig_path);
827 if (error)
828 goto done;
829 error = got_repo_pack_fds_open(&pack_fds);
830 if (error != NULL)
831 goto done;
832 error = got_repo_open(&repo, repo_path, gitconfig_path, pack_fds);
833 if (error)
834 goto done;
836 error = get_author(&author, repo, NULL);
837 if (error)
838 return error;
840 /*
841 * Don't let the user create a branch name with a leading '-'.
842 * While technically a valid reference name, this case is usually
843 * an unintended typo.
844 */
845 if (branch_name && branch_name[0] == '-')
846 return got_error_path(branch_name, GOT_ERR_REF_NAME_MINUS);
848 error = got_ref_open(&head_ref, repo, GOT_REF_HEAD, 0);
849 if (error && error->code != GOT_ERR_NOT_REF)
850 goto done;
852 if (branch_name)
853 n = strlcat(refname, branch_name, sizeof(refname));
854 else if (head_ref && got_ref_is_symbolic(head_ref))
855 n = strlcpy(refname, got_ref_get_symref_target(head_ref),
856 sizeof(refname));
857 else
858 n = strlcat(refname, "main", sizeof(refname));
859 if (n >= sizeof(refname)) {
860 error = got_error(GOT_ERR_NO_SPACE);
861 goto done;
864 error = got_ref_open(&branch_ref, repo, refname, 0);
865 if (error) {
866 if (error->code != GOT_ERR_NOT_REF)
867 goto done;
868 } else {
869 error = got_error_msg(GOT_ERR_BRANCH_EXISTS,
870 "import target branch already exists");
871 goto done;
874 path_dir = realpath(argv[0], NULL);
875 if (path_dir == NULL) {
876 error = got_error_from_errno2("realpath", argv[0]);
877 goto done;
879 got_path_strip_trailing_slashes(path_dir);
881 /*
882 * unveil(2) traverses exec(2); if an editor is used we have
883 * to apply unveil after the log message has been written.
884 */
885 if (logmsg == NULL || *logmsg == '\0') {
886 error = get_editor(&editor);
887 if (error)
888 goto done;
889 free(logmsg);
890 error = collect_import_msg(&logmsg, &logmsg_path, editor,
891 path_dir, refname);
892 if (error) {
893 if (error->code != GOT_ERR_COMMIT_MSG_EMPTY &&
894 logmsg_path != NULL)
895 preserve_logmsg = 1;
896 goto done;
900 if (unveil(path_dir, "r") != 0) {
901 error = got_error_from_errno2("unveil", path_dir);
902 if (logmsg_path)
903 preserve_logmsg = 1;
904 goto done;
907 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
908 if (error) {
909 if (logmsg_path)
910 preserve_logmsg = 1;
911 goto done;
914 error = got_repo_import(&new_commit_id, path_dir, logmsg,
915 author, &ignores, repo, import_progress, NULL);
916 if (error) {
917 if (logmsg_path)
918 preserve_logmsg = 1;
919 goto done;
922 error = got_ref_alloc(&branch_ref, refname, new_commit_id);
923 if (error) {
924 if (logmsg_path)
925 preserve_logmsg = 1;
926 goto done;
929 error = got_ref_write(branch_ref, repo);
930 if (error) {
931 if (logmsg_path)
932 preserve_logmsg = 1;
933 goto done;
936 error = got_object_id_str(&id_str, new_commit_id);
937 if (error) {
938 if (logmsg_path)
939 preserve_logmsg = 1;
940 goto done;
943 error = got_ref_open(&head_ref, repo, GOT_REF_HEAD, 0);
944 if (error) {
945 if (error->code != GOT_ERR_NOT_REF) {
946 if (logmsg_path)
947 preserve_logmsg = 1;
948 goto done;
951 error = got_ref_alloc_symref(&head_ref, GOT_REF_HEAD,
952 branch_ref);
953 if (error) {
954 if (logmsg_path)
955 preserve_logmsg = 1;
956 goto done;
959 error = got_ref_write(head_ref, repo);
960 if (error) {
961 if (logmsg_path)
962 preserve_logmsg = 1;
963 goto done;
967 printf("Created branch %s with commit %s\n",
968 got_ref_get_name(branch_ref), id_str);
969 done:
970 if (pack_fds) {
971 const struct got_error *pack_err =
972 got_repo_pack_fds_close(pack_fds);
973 if (error == NULL)
974 error = pack_err;
976 if (repo) {
977 const struct got_error *close_err = got_repo_close(repo);
978 if (error == NULL)
979 error = close_err;
981 if (preserve_logmsg) {
982 fprintf(stderr, "%s: log message preserved in %s\n",
983 getprogname(), logmsg_path);
984 } else if (logmsg_path && unlink(logmsg_path) == -1 && error == NULL)
985 error = got_error_from_errno2("unlink", logmsg_path);
986 free(logmsg);
987 free(logmsg_path);
988 free(repo_path);
989 free(editor);
990 free(new_commit_id);
991 free(id_str);
992 free(author);
993 free(gitconfig_path);
994 if (branch_ref)
995 got_ref_close(branch_ref);
996 if (head_ref)
997 got_ref_close(head_ref);
998 return error;
1001 __dead static void
1002 usage_clone(void)
1004 fprintf(stderr, "usage: %s clone [-almqv] [-b branch] [-R reference] "
1005 "repository-URL [directory]\n", getprogname());
1006 exit(1);
1009 struct got_fetch_progress_arg {
1010 char last_scaled_size[FMT_SCALED_STRSIZE];
1011 int last_p_indexed;
1012 int last_p_resolved;
1013 int verbosity;
1015 struct got_repository *repo;
1017 int create_configs;
1018 int configs_created;
1019 struct {
1020 struct got_pathlist_head *symrefs;
1021 struct got_pathlist_head *wanted_branches;
1022 struct got_pathlist_head *wanted_refs;
1023 const char *proto;
1024 const char *host;
1025 const char *port;
1026 const char *remote_repo_path;
1027 const char *git_url;
1028 int fetch_all_branches;
1029 int mirror_references;
1030 } config_info;
1033 /* XXX forward declaration */
1034 static const struct got_error *
1035 create_config_files(const char *proto, const char *host, const char *port,
1036 const char *remote_repo_path, const char *git_url, int fetch_all_branches,
1037 int mirror_references, struct got_pathlist_head *symrefs,
1038 struct got_pathlist_head *wanted_branches,
1039 struct got_pathlist_head *wanted_refs, struct got_repository *repo);
1041 static const struct got_error *
1042 fetch_progress(void *arg, const char *message, off_t packfile_size,
1043 int nobj_total, int nobj_indexed, int nobj_loose, int nobj_resolved)
1045 const struct got_error *err = NULL;
1046 struct got_fetch_progress_arg *a = arg;
1047 char scaled_size[FMT_SCALED_STRSIZE];
1048 int p_indexed, p_resolved;
1049 int print_size = 0, print_indexed = 0, print_resolved = 0;
1052 * In order to allow a failed clone to be resumed with 'got fetch'
1053 * we try to create configuration files as soon as possible.
1054 * Once the server has sent information about its default branch
1055 * we have all required information.
1057 if (a->create_configs && !a->configs_created &&
1058 !TAILQ_EMPTY(a->config_info.symrefs)) {
1059 err = create_config_files(a->config_info.proto,
1060 a->config_info.host, a->config_info.port,
1061 a->config_info.remote_repo_path,
1062 a->config_info.git_url,
1063 a->config_info.fetch_all_branches,
1064 a->config_info.mirror_references,
1065 a->config_info.symrefs,
1066 a->config_info.wanted_branches,
1067 a->config_info.wanted_refs, a->repo);
1068 if (err)
1069 return err;
1070 a->configs_created = 1;
1073 if (a->verbosity < 0)
1074 return NULL;
1076 if (message && message[0] != '\0') {
1077 printf("\rserver: %s", message);
1078 fflush(stdout);
1079 return NULL;
1082 if (packfile_size > 0 || nobj_indexed > 0) {
1083 if (fmt_scaled(packfile_size, scaled_size) == 0 &&
1084 (a->last_scaled_size[0] == '\0' ||
1085 strcmp(scaled_size, a->last_scaled_size)) != 0) {
1086 print_size = 1;
1087 if (strlcpy(a->last_scaled_size, scaled_size,
1088 FMT_SCALED_STRSIZE) >= FMT_SCALED_STRSIZE)
1089 return got_error(GOT_ERR_NO_SPACE);
1091 if (nobj_indexed > 0) {
1092 p_indexed = (nobj_indexed * 100) / nobj_total;
1093 if (p_indexed != a->last_p_indexed) {
1094 a->last_p_indexed = p_indexed;
1095 print_indexed = 1;
1096 print_size = 1;
1099 if (nobj_resolved > 0) {
1100 p_resolved = (nobj_resolved * 100) /
1101 (nobj_total - nobj_loose);
1102 if (p_resolved != a->last_p_resolved) {
1103 a->last_p_resolved = p_resolved;
1104 print_resolved = 1;
1105 print_indexed = 1;
1106 print_size = 1;
1111 if (print_size || print_indexed || print_resolved)
1112 printf("\r");
1113 if (print_size)
1114 printf("%*s fetched", FMT_SCALED_STRSIZE - 2, scaled_size);
1115 if (print_indexed)
1116 printf("; indexing %d%%", p_indexed);
1117 if (print_resolved)
1118 printf("; resolving deltas %d%%", p_resolved);
1119 if (print_size || print_indexed || print_resolved)
1120 fflush(stdout);
1122 return NULL;
1125 static const struct got_error *
1126 create_symref(const char *refname, struct got_reference *target_ref,
1127 int verbosity, struct got_repository *repo)
1129 const struct got_error *err;
1130 struct got_reference *head_symref;
1132 err = got_ref_alloc_symref(&head_symref, refname, target_ref);
1133 if (err)
1134 return err;
1136 err = got_ref_write(head_symref, repo);
1137 if (err == NULL && verbosity > 0) {
1138 printf("Created reference %s: %s\n", GOT_REF_HEAD,
1139 got_ref_get_name(target_ref));
1141 got_ref_close(head_symref);
1142 return err;
1145 static const struct got_error *
1146 list_remote_refs(struct got_pathlist_head *symrefs,
1147 struct got_pathlist_head *refs)
1149 const struct got_error *err;
1150 struct got_pathlist_entry *pe;
1152 TAILQ_FOREACH(pe, symrefs, entry) {
1153 const char *refname = pe->path;
1154 const char *targetref = pe->data;
1156 printf("%s: %s\n", refname, targetref);
1159 TAILQ_FOREACH(pe, refs, entry) {
1160 const char *refname = pe->path;
1161 struct got_object_id *id = pe->data;
1162 char *id_str;
1164 err = got_object_id_str(&id_str, id);
1165 if (err)
1166 return err;
1167 printf("%s: %s\n", refname, id_str);
1168 free(id_str);
1171 return NULL;
1174 static const struct got_error *
1175 create_ref(const char *refname, struct got_object_id *id,
1176 int verbosity, struct got_repository *repo)
1178 const struct got_error *err = NULL;
1179 struct got_reference *ref;
1180 char *id_str;
1182 err = got_object_id_str(&id_str, id);
1183 if (err)
1184 return err;
1186 err = got_ref_alloc(&ref, refname, id);
1187 if (err)
1188 goto done;
1190 err = got_ref_write(ref, repo);
1191 got_ref_close(ref);
1193 if (err == NULL && verbosity >= 0)
1194 printf("Created reference %s: %s\n", refname, id_str);
1195 done:
1196 free(id_str);
1197 return err;
1200 static int
1201 match_wanted_ref(const char *refname, const char *wanted_ref)
1203 if (strncmp(refname, "refs/", 5) != 0)
1204 return 0;
1205 refname += 5;
1208 * Prevent fetching of references that won't make any
1209 * sense outside of the remote repository's context.
1211 if (strncmp(refname, "got/", 4) == 0)
1212 return 0;
1213 if (strncmp(refname, "remotes/", 8) == 0)
1214 return 0;
1216 if (strncmp(wanted_ref, "refs/", 5) == 0)
1217 wanted_ref += 5;
1219 /* Allow prefix match. */
1220 if (got_path_is_child(refname, wanted_ref, strlen(wanted_ref)))
1221 return 1;
1223 /* Allow exact match. */
1224 return (strcmp(refname, wanted_ref) == 0);
1227 static int
1228 is_wanted_ref(struct got_pathlist_head *wanted_refs, const char *refname)
1230 struct got_pathlist_entry *pe;
1232 TAILQ_FOREACH(pe, wanted_refs, entry) {
1233 if (match_wanted_ref(refname, pe->path))
1234 return 1;
1237 return 0;
1240 static const struct got_error *
1241 create_wanted_ref(const char *refname, struct got_object_id *id,
1242 const char *remote_repo_name, int verbosity, struct got_repository *repo)
1244 const struct got_error *err;
1245 char *remote_refname;
1247 if (strncmp("refs/", refname, 5) == 0)
1248 refname += 5;
1250 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
1251 remote_repo_name, refname) == -1)
1252 return got_error_from_errno("asprintf");
1254 err = create_ref(remote_refname, id, verbosity, repo);
1255 free(remote_refname);
1256 return err;
1259 static const struct got_error *
1260 create_gotconfig(const char *proto, const char *host, const char *port,
1261 const char *remote_repo_path, const char *default_branch,
1262 int fetch_all_branches, struct got_pathlist_head *wanted_branches,
1263 struct got_pathlist_head *wanted_refs, int mirror_references,
1264 struct got_repository *repo)
1266 const struct got_error *err = NULL;
1267 char *gotconfig_path = NULL;
1268 char *gotconfig = NULL;
1269 FILE *gotconfig_file = NULL;
1270 const char *branchname = NULL;
1271 char *branches = NULL, *refs = NULL;
1272 ssize_t n;
1274 if (!fetch_all_branches && !TAILQ_EMPTY(wanted_branches)) {
1275 struct got_pathlist_entry *pe;
1276 TAILQ_FOREACH(pe, wanted_branches, entry) {
1277 char *s;
1278 branchname = pe->path;
1279 if (strncmp(branchname, "refs/heads/", 11) == 0)
1280 branchname += 11;
1281 if (asprintf(&s, "%s\"%s\" ",
1282 branches ? branches : "", branchname) == -1) {
1283 err = got_error_from_errno("asprintf");
1284 goto done;
1286 free(branches);
1287 branches = s;
1289 } else if (!fetch_all_branches && default_branch) {
1290 branchname = default_branch;
1291 if (strncmp(branchname, "refs/heads/", 11) == 0)
1292 branchname += 11;
1293 if (asprintf(&branches, "\"%s\" ", branchname) == -1) {
1294 err = got_error_from_errno("asprintf");
1295 goto done;
1298 if (!TAILQ_EMPTY(wanted_refs)) {
1299 struct got_pathlist_entry *pe;
1300 TAILQ_FOREACH(pe, wanted_refs, entry) {
1301 char *s;
1302 const char *refname = pe->path;
1303 if (strncmp(refname, "refs/", 5) == 0)
1304 branchname += 5;
1305 if (asprintf(&s, "%s\"%s\" ",
1306 refs ? refs : "", refname) == -1) {
1307 err = got_error_from_errno("asprintf");
1308 goto done;
1310 free(refs);
1311 refs = s;
1315 /* Create got.conf(5). */
1316 gotconfig_path = got_repo_get_path_gotconfig(repo);
1317 if (gotconfig_path == NULL) {
1318 err = got_error_from_errno("got_repo_get_path_gotconfig");
1319 goto done;
1321 gotconfig_file = fopen(gotconfig_path, "ae");
1322 if (gotconfig_file == NULL) {
1323 err = got_error_from_errno2("fopen", gotconfig_path);
1324 goto done;
1326 if (asprintf(&gotconfig,
1327 "remote \"%s\" {\n"
1328 "\tserver %s\n"
1329 "\tprotocol %s\n"
1330 "%s%s%s"
1331 "\trepository \"%s\"\n"
1332 "%s%s%s"
1333 "%s%s%s"
1334 "%s"
1335 "%s"
1336 "}\n",
1337 GOT_FETCH_DEFAULT_REMOTE_NAME, host, proto,
1338 port ? "\tport " : "", port ? port : "", port ? "\n" : "",
1339 remote_repo_path, branches ? "\tbranch { " : "",
1340 branches ? branches : "", branches ? "}\n" : "",
1341 refs ? "\treference { " : "", refs ? refs : "", refs ? "}\n" : "",
1342 mirror_references ? "\tmirror_references yes\n" : "",
1343 fetch_all_branches ? "\tfetch_all_branches yes\n" : "") == -1) {
1344 err = got_error_from_errno("asprintf");
1345 goto done;
1347 n = fwrite(gotconfig, 1, strlen(gotconfig), gotconfig_file);
1348 if (n != strlen(gotconfig)) {
1349 err = got_ferror(gotconfig_file, GOT_ERR_IO);
1350 goto done;
1353 done:
1354 if (gotconfig_file && fclose(gotconfig_file) == EOF && err == NULL)
1355 err = got_error_from_errno2("fclose", gotconfig_path);
1356 free(gotconfig_path);
1357 free(branches);
1358 return err;
1361 static const struct got_error *
1362 create_gitconfig(const char *git_url, const char *default_branch,
1363 int fetch_all_branches, struct got_pathlist_head *wanted_branches,
1364 struct got_pathlist_head *wanted_refs, int mirror_references,
1365 struct got_repository *repo)
1367 const struct got_error *err = NULL;
1368 char *gitconfig_path = NULL;
1369 char *gitconfig = NULL;
1370 FILE *gitconfig_file = NULL;
1371 char *branches = NULL, *refs = NULL;
1372 const char *branchname;
1373 ssize_t n;
1375 /* Create a config file Git can understand. */
1376 gitconfig_path = got_repo_get_path_gitconfig(repo);
1377 if (gitconfig_path == NULL) {
1378 err = got_error_from_errno("got_repo_get_path_gitconfig");
1379 goto done;
1381 gitconfig_file = fopen(gitconfig_path, "ae");
1382 if (gitconfig_file == NULL) {
1383 err = got_error_from_errno2("fopen", gitconfig_path);
1384 goto done;
1386 if (fetch_all_branches) {
1387 if (mirror_references) {
1388 if (asprintf(&branches,
1389 "\tfetch = refs/heads/*:refs/heads/*\n") == -1) {
1390 err = got_error_from_errno("asprintf");
1391 goto done;
1393 } else if (asprintf(&branches,
1394 "\tfetch = refs/heads/*:refs/remotes/%s/*\n",
1395 GOT_FETCH_DEFAULT_REMOTE_NAME) == -1) {
1396 err = got_error_from_errno("asprintf");
1397 goto done;
1399 } else if (!TAILQ_EMPTY(wanted_branches)) {
1400 struct got_pathlist_entry *pe;
1401 TAILQ_FOREACH(pe, wanted_branches, entry) {
1402 char *s;
1403 branchname = pe->path;
1404 if (strncmp(branchname, "refs/heads/", 11) == 0)
1405 branchname += 11;
1406 if (mirror_references) {
1407 if (asprintf(&s,
1408 "%s\tfetch = refs/heads/%s:refs/heads/%s\n",
1409 branches ? branches : "",
1410 branchname, branchname) == -1) {
1411 err = got_error_from_errno("asprintf");
1412 goto done;
1414 } else if (asprintf(&s,
1415 "%s\tfetch = refs/heads/%s:refs/remotes/%s/%s\n",
1416 branches ? branches : "",
1417 branchname, GOT_FETCH_DEFAULT_REMOTE_NAME,
1418 branchname) == -1) {
1419 err = got_error_from_errno("asprintf");
1420 goto done;
1422 free(branches);
1423 branches = s;
1425 } else {
1427 * If the server specified a default branch, use just that one.
1428 * Otherwise fall back to fetching all branches on next fetch.
1430 if (default_branch) {
1431 branchname = default_branch;
1432 if (strncmp(branchname, "refs/heads/", 11) == 0)
1433 branchname += 11;
1434 } else
1435 branchname = "*"; /* fall back to all branches */
1436 if (mirror_references) {
1437 if (asprintf(&branches,
1438 "\tfetch = refs/heads/%s:refs/heads/%s\n",
1439 branchname, branchname) == -1) {
1440 err = got_error_from_errno("asprintf");
1441 goto done;
1443 } else if (asprintf(&branches,
1444 "\tfetch = refs/heads/%s:refs/remotes/%s/%s\n",
1445 branchname, GOT_FETCH_DEFAULT_REMOTE_NAME,
1446 branchname) == -1) {
1447 err = got_error_from_errno("asprintf");
1448 goto done;
1451 if (!TAILQ_EMPTY(wanted_refs)) {
1452 struct got_pathlist_entry *pe;
1453 TAILQ_FOREACH(pe, wanted_refs, entry) {
1454 char *s;
1455 const char *refname = pe->path;
1456 if (strncmp(refname, "refs/", 5) == 0)
1457 refname += 5;
1458 if (mirror_references) {
1459 if (asprintf(&s,
1460 "%s\tfetch = refs/%s:refs/%s\n",
1461 refs ? refs : "", refname, refname) == -1) {
1462 err = got_error_from_errno("asprintf");
1463 goto done;
1465 } else if (asprintf(&s,
1466 "%s\tfetch = refs/%s:refs/remotes/%s/%s\n",
1467 refs ? refs : "",
1468 refname, GOT_FETCH_DEFAULT_REMOTE_NAME,
1469 refname) == -1) {
1470 err = got_error_from_errno("asprintf");
1471 goto done;
1473 free(refs);
1474 refs = s;
1478 if (asprintf(&gitconfig,
1479 "[remote \"%s\"]\n"
1480 "\turl = %s\n"
1481 "%s"
1482 "%s"
1483 "\tfetch = refs/tags/*:refs/tags/*\n",
1484 GOT_FETCH_DEFAULT_REMOTE_NAME, git_url, branches ? branches : "",
1485 refs ? refs : "") == -1) {
1486 err = got_error_from_errno("asprintf");
1487 goto done;
1489 n = fwrite(gitconfig, 1, strlen(gitconfig), gitconfig_file);
1490 if (n != strlen(gitconfig)) {
1491 err = got_ferror(gitconfig_file, GOT_ERR_IO);
1492 goto done;
1494 done:
1495 if (gitconfig_file && fclose(gitconfig_file) == EOF && err == NULL)
1496 err = got_error_from_errno2("fclose", gitconfig_path);
1497 free(gitconfig_path);
1498 free(branches);
1499 return err;
1502 static const struct got_error *
1503 create_config_files(const char *proto, const char *host, const char *port,
1504 const char *remote_repo_path, const char *git_url, int fetch_all_branches,
1505 int mirror_references, struct got_pathlist_head *symrefs,
1506 struct got_pathlist_head *wanted_branches,
1507 struct got_pathlist_head *wanted_refs, struct got_repository *repo)
1509 const struct got_error *err = NULL;
1510 const char *default_branch = NULL;
1511 struct got_pathlist_entry *pe;
1514 * If we asked for a set of wanted branches then use the first
1515 * one of those.
1517 if (!TAILQ_EMPTY(wanted_branches)) {
1518 pe = TAILQ_FIRST(wanted_branches);
1519 default_branch = pe->path;
1520 } else {
1521 /* First HEAD ref listed by server is the default branch. */
1522 TAILQ_FOREACH(pe, symrefs, entry) {
1523 const char *refname = pe->path;
1524 const char *target = pe->data;
1526 if (strcmp(refname, GOT_REF_HEAD) != 0)
1527 continue;
1529 default_branch = target;
1530 break;
1534 /* Create got.conf(5). */
1535 err = create_gotconfig(proto, host, port, remote_repo_path,
1536 default_branch, fetch_all_branches, wanted_branches,
1537 wanted_refs, mirror_references, repo);
1538 if (err)
1539 return err;
1541 /* Create a config file Git can understand. */
1542 return create_gitconfig(git_url, default_branch, fetch_all_branches,
1543 wanted_branches, wanted_refs, mirror_references, repo);
1546 static const struct got_error *
1547 cmd_clone(int argc, char *argv[])
1549 const struct got_error *error = NULL;
1550 const char *uri, *dirname;
1551 char *proto, *host, *port, *repo_name, *server_path;
1552 char *default_destdir = NULL, *id_str = NULL;
1553 const char *repo_path;
1554 struct got_repository *repo = NULL;
1555 struct got_pathlist_head refs, symrefs, wanted_branches, wanted_refs;
1556 struct got_pathlist_entry *pe;
1557 struct got_object_id *pack_hash = NULL;
1558 int ch, fetchfd = -1, fetchstatus;
1559 pid_t fetchpid = -1;
1560 struct got_fetch_progress_arg fpa;
1561 char *git_url = NULL;
1562 int verbosity = 0, fetch_all_branches = 0, mirror_references = 0;
1563 int bflag = 0, list_refs_only = 0;
1564 int *pack_fds = NULL;
1566 TAILQ_INIT(&refs);
1567 TAILQ_INIT(&symrefs);
1568 TAILQ_INIT(&wanted_branches);
1569 TAILQ_INIT(&wanted_refs);
1571 while ((ch = getopt(argc, argv, "ab:lmqR:v")) != -1) {
1572 switch (ch) {
1573 case 'a':
1574 fetch_all_branches = 1;
1575 break;
1576 case 'b':
1577 error = got_pathlist_append(&wanted_branches,
1578 optarg, NULL);
1579 if (error)
1580 return error;
1581 bflag = 1;
1582 break;
1583 case 'l':
1584 list_refs_only = 1;
1585 break;
1586 case 'm':
1587 mirror_references = 1;
1588 break;
1589 case 'q':
1590 verbosity = -1;
1591 break;
1592 case 'R':
1593 error = got_pathlist_append(&wanted_refs,
1594 optarg, NULL);
1595 if (error)
1596 return error;
1597 break;
1598 case 'v':
1599 if (verbosity < 0)
1600 verbosity = 0;
1601 else if (verbosity < 3)
1602 verbosity++;
1603 break;
1604 default:
1605 usage_clone();
1606 break;
1609 argc -= optind;
1610 argv += optind;
1612 if (fetch_all_branches && !TAILQ_EMPTY(&wanted_branches))
1613 option_conflict('a', 'b');
1614 if (list_refs_only) {
1615 if (!TAILQ_EMPTY(&wanted_branches))
1616 option_conflict('l', 'b');
1617 if (fetch_all_branches)
1618 option_conflict('l', 'a');
1619 if (mirror_references)
1620 option_conflict('l', 'm');
1621 if (!TAILQ_EMPTY(&wanted_refs))
1622 option_conflict('l', 'R');
1625 uri = argv[0];
1627 if (argc == 1)
1628 dirname = NULL;
1629 else if (argc == 2)
1630 dirname = argv[1];
1631 else
1632 usage_clone();
1634 error = got_dial_parse_uri(&proto, &host, &port, &server_path,
1635 &repo_name, uri);
1636 if (error)
1637 goto done;
1639 if (asprintf(&git_url, "%s://%s%s%s%s%s", proto,
1640 host, port ? ":" : "", port ? port : "",
1641 server_path[0] != '/' ? "/" : "", server_path) == -1) {
1642 error = got_error_from_errno("asprintf");
1643 goto done;
1646 if (strcmp(proto, "git") == 0) {
1647 #ifndef PROFILE
1648 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
1649 "sendfd dns inet unveil", NULL) == -1)
1650 err(1, "pledge");
1651 #endif
1652 } else if (strcmp(proto, "git+ssh") == 0 ||
1653 strcmp(proto, "ssh") == 0) {
1654 #ifndef PROFILE
1655 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
1656 "sendfd unveil", NULL) == -1)
1657 err(1, "pledge");
1658 #endif
1659 } else if (strcmp(proto, "http") == 0 ||
1660 strcmp(proto, "git+http") == 0) {
1661 error = got_error_path(proto, GOT_ERR_NOT_IMPL);
1662 goto done;
1663 } else {
1664 error = got_error_path(proto, GOT_ERR_BAD_PROTO);
1665 goto done;
1667 if (dirname == NULL) {
1668 if (asprintf(&default_destdir, "%s.git", repo_name) == -1) {
1669 error = got_error_from_errno("asprintf");
1670 goto done;
1672 repo_path = default_destdir;
1673 } else
1674 repo_path = dirname;
1676 if (!list_refs_only) {
1677 error = got_path_mkdir(repo_path);
1678 if (error &&
1679 (!(error->code == GOT_ERR_ERRNO && errno == EISDIR) &&
1680 !(error->code == GOT_ERR_ERRNO && errno == EEXIST)))
1681 goto done;
1682 if (!got_path_dir_is_empty(repo_path)) {
1683 error = got_error_path(repo_path,
1684 GOT_ERR_DIR_NOT_EMPTY);
1685 goto done;
1689 error = got_dial_apply_unveil(proto);
1690 if (error)
1691 goto done;
1693 error = apply_unveil(repo_path, 0, NULL);
1694 if (error)
1695 goto done;
1697 if (verbosity >= 0)
1698 printf("Connecting to %s\n", git_url);
1700 error = got_fetch_connect(&fetchpid, &fetchfd, proto, host, port,
1701 server_path, verbosity);
1702 if (error)
1703 goto done;
1705 if (!list_refs_only) {
1706 error = got_repo_init(repo_path, NULL);
1707 if (error)
1708 goto done;
1709 error = got_repo_pack_fds_open(&pack_fds);
1710 if (error != NULL)
1711 goto done;
1712 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
1713 if (error)
1714 goto done;
1717 fpa.last_scaled_size[0] = '\0';
1718 fpa.last_p_indexed = -1;
1719 fpa.last_p_resolved = -1;
1720 fpa.verbosity = verbosity;
1721 fpa.create_configs = 1;
1722 fpa.configs_created = 0;
1723 fpa.repo = repo;
1724 fpa.config_info.symrefs = &symrefs;
1725 fpa.config_info.wanted_branches = &wanted_branches;
1726 fpa.config_info.wanted_refs = &wanted_refs;
1727 fpa.config_info.proto = proto;
1728 fpa.config_info.host = host;
1729 fpa.config_info.port = port;
1730 fpa.config_info.remote_repo_path = server_path;
1731 fpa.config_info.git_url = git_url;
1732 fpa.config_info.fetch_all_branches = fetch_all_branches;
1733 fpa.config_info.mirror_references = mirror_references;
1734 error = got_fetch_pack(&pack_hash, &refs, &symrefs,
1735 GOT_FETCH_DEFAULT_REMOTE_NAME, mirror_references,
1736 fetch_all_branches, &wanted_branches, &wanted_refs,
1737 list_refs_only, verbosity, fetchfd, repo, NULL, NULL, bflag,
1738 fetch_progress, &fpa);
1739 if (error)
1740 goto done;
1742 if (list_refs_only) {
1743 error = list_remote_refs(&symrefs, &refs);
1744 goto done;
1747 if (pack_hash == NULL) {
1748 error = got_error_fmt(GOT_ERR_FETCH_FAILED, "%s",
1749 "server sent an empty pack file");
1750 goto done;
1752 error = got_object_id_str(&id_str, pack_hash);
1753 if (error)
1754 goto done;
1755 if (verbosity >= 0)
1756 printf("\nFetched %s.pack\n", id_str);
1757 free(id_str);
1759 /* Set up references provided with the pack file. */
1760 TAILQ_FOREACH(pe, &refs, entry) {
1761 const char *refname = pe->path;
1762 struct got_object_id *id = pe->data;
1763 char *remote_refname;
1765 if (is_wanted_ref(&wanted_refs, refname) &&
1766 !mirror_references) {
1767 error = create_wanted_ref(refname, id,
1768 GOT_FETCH_DEFAULT_REMOTE_NAME,
1769 verbosity - 1, repo);
1770 if (error)
1771 goto done;
1772 continue;
1775 error = create_ref(refname, id, verbosity - 1, repo);
1776 if (error)
1777 goto done;
1779 if (mirror_references)
1780 continue;
1782 if (strncmp("refs/heads/", refname, 11) != 0)
1783 continue;
1785 if (asprintf(&remote_refname,
1786 "refs/remotes/%s/%s", GOT_FETCH_DEFAULT_REMOTE_NAME,
1787 refname + 11) == -1) {
1788 error = got_error_from_errno("asprintf");
1789 goto done;
1791 error = create_ref(remote_refname, id, verbosity - 1, repo);
1792 free(remote_refname);
1793 if (error)
1794 goto done;
1797 /* Set the HEAD reference if the server provided one. */
1798 TAILQ_FOREACH(pe, &symrefs, entry) {
1799 struct got_reference *target_ref;
1800 const char *refname = pe->path;
1801 const char *target = pe->data;
1802 char *remote_refname = NULL, *remote_target = NULL;
1804 if (strcmp(refname, GOT_REF_HEAD) != 0)
1805 continue;
1807 error = got_ref_open(&target_ref, repo, target, 0);
1808 if (error) {
1809 if (error->code == GOT_ERR_NOT_REF) {
1810 error = NULL;
1811 continue;
1813 goto done;
1816 error = create_symref(refname, target_ref, verbosity, repo);
1817 got_ref_close(target_ref);
1818 if (error)
1819 goto done;
1821 if (mirror_references)
1822 continue;
1824 if (strncmp("refs/heads/", target, 11) != 0)
1825 continue;
1827 if (asprintf(&remote_refname,
1828 "refs/remotes/%s/%s", GOT_FETCH_DEFAULT_REMOTE_NAME,
1829 refname) == -1) {
1830 error = got_error_from_errno("asprintf");
1831 goto done;
1833 if (asprintf(&remote_target,
1834 "refs/remotes/%s/%s", GOT_FETCH_DEFAULT_REMOTE_NAME,
1835 target + 11) == -1) {
1836 error = got_error_from_errno("asprintf");
1837 free(remote_refname);
1838 goto done;
1840 error = got_ref_open(&target_ref, repo, remote_target, 0);
1841 if (error) {
1842 free(remote_refname);
1843 free(remote_target);
1844 if (error->code == GOT_ERR_NOT_REF) {
1845 error = NULL;
1846 continue;
1848 goto done;
1850 error = create_symref(remote_refname, target_ref,
1851 verbosity - 1, repo);
1852 free(remote_refname);
1853 free(remote_target);
1854 got_ref_close(target_ref);
1855 if (error)
1856 goto done;
1858 if (pe == NULL) {
1860 * We failed to set the HEAD reference. If we asked for
1861 * a set of wanted branches use the first of one of those
1862 * which could be fetched instead.
1864 TAILQ_FOREACH(pe, &wanted_branches, entry) {
1865 const char *target = pe->path;
1866 struct got_reference *target_ref;
1868 error = got_ref_open(&target_ref, repo, target, 0);
1869 if (error) {
1870 if (error->code == GOT_ERR_NOT_REF) {
1871 error = NULL;
1872 continue;
1874 goto done;
1877 error = create_symref(GOT_REF_HEAD, target_ref,
1878 verbosity, repo);
1879 got_ref_close(target_ref);
1880 if (error)
1881 goto done;
1882 break;
1885 if (!fpa.configs_created && pe != NULL) {
1886 error = create_config_files(fpa.config_info.proto,
1887 fpa.config_info.host, fpa.config_info.port,
1888 fpa.config_info.remote_repo_path,
1889 fpa.config_info.git_url,
1890 fpa.config_info.fetch_all_branches,
1891 fpa.config_info.mirror_references,
1892 fpa.config_info.symrefs,
1893 fpa.config_info.wanted_branches,
1894 fpa.config_info.wanted_refs, fpa.repo);
1895 if (error)
1896 goto done;
1900 if (verbosity >= 0)
1901 printf("Created %s repository '%s'\n",
1902 mirror_references ? "mirrored" : "cloned", repo_path);
1903 done:
1904 if (pack_fds) {
1905 const struct got_error *pack_err =
1906 got_repo_pack_fds_close(pack_fds);
1907 if (error == NULL)
1908 error = pack_err;
1910 if (fetchpid > 0) {
1911 if (kill(fetchpid, SIGTERM) == -1)
1912 error = got_error_from_errno("kill");
1913 if (waitpid(fetchpid, &fetchstatus, 0) == -1 && error == NULL)
1914 error = got_error_from_errno("waitpid");
1916 if (fetchfd != -1 && close(fetchfd) == -1 && error == NULL)
1917 error = got_error_from_errno("close");
1918 if (repo) {
1919 const struct got_error *close_err = got_repo_close(repo);
1920 if (error == NULL)
1921 error = close_err;
1923 got_pathlist_free(&refs, GOT_PATHLIST_FREE_ALL);
1924 got_pathlist_free(&symrefs, GOT_PATHLIST_FREE_ALL);
1925 got_pathlist_free(&wanted_branches, GOT_PATHLIST_FREE_NONE);
1926 got_pathlist_free(&wanted_refs, GOT_PATHLIST_FREE_NONE);
1927 free(pack_hash);
1928 free(proto);
1929 free(host);
1930 free(port);
1931 free(server_path);
1932 free(repo_name);
1933 free(default_destdir);
1934 free(git_url);
1935 return error;
1938 static const struct got_error *
1939 update_ref(struct got_reference *ref, struct got_object_id *new_id,
1940 int replace_tags, int verbosity, struct got_repository *repo)
1942 const struct got_error *err = NULL;
1943 char *new_id_str = NULL;
1944 struct got_object_id *old_id = NULL;
1946 err = got_object_id_str(&new_id_str, new_id);
1947 if (err)
1948 goto done;
1950 if (!replace_tags &&
1951 strncmp(got_ref_get_name(ref), "refs/tags/", 10) == 0) {
1952 err = got_ref_resolve(&old_id, repo, ref);
1953 if (err)
1954 goto done;
1955 if (got_object_id_cmp(old_id, new_id) == 0)
1956 goto done;
1957 if (verbosity >= 0) {
1958 printf("Rejecting update of existing tag %s: %s\n",
1959 got_ref_get_name(ref), new_id_str);
1961 goto done;
1964 if (got_ref_is_symbolic(ref)) {
1965 if (verbosity >= 0) {
1966 printf("Replacing reference %s: %s\n",
1967 got_ref_get_name(ref),
1968 got_ref_get_symref_target(ref));
1970 err = got_ref_change_symref_to_ref(ref, new_id);
1971 if (err)
1972 goto done;
1973 err = got_ref_write(ref, repo);
1974 if (err)
1975 goto done;
1976 } else {
1977 err = got_ref_resolve(&old_id, repo, ref);
1978 if (err)
1979 goto done;
1980 if (got_object_id_cmp(old_id, new_id) == 0)
1981 goto done;
1983 err = got_ref_change_ref(ref, new_id);
1984 if (err)
1985 goto done;
1986 err = got_ref_write(ref, repo);
1987 if (err)
1988 goto done;
1991 if (verbosity >= 0)
1992 printf("Updated %s: %s\n", got_ref_get_name(ref),
1993 new_id_str);
1994 done:
1995 free(old_id);
1996 free(new_id_str);
1997 return err;
2000 static const struct got_error *
2001 update_symref(const char *refname, struct got_reference *target_ref,
2002 int verbosity, struct got_repository *repo)
2004 const struct got_error *err = NULL, *unlock_err;
2005 struct got_reference *symref;
2006 int symref_is_locked = 0;
2008 err = got_ref_open(&symref, repo, refname, 1);
2009 if (err) {
2010 if (err->code != GOT_ERR_NOT_REF)
2011 return err;
2012 err = got_ref_alloc_symref(&symref, refname, target_ref);
2013 if (err)
2014 goto done;
2016 err = got_ref_write(symref, repo);
2017 if (err)
2018 goto done;
2020 if (verbosity >= 0)
2021 printf("Created reference %s: %s\n",
2022 got_ref_get_name(symref),
2023 got_ref_get_symref_target(symref));
2024 } else {
2025 symref_is_locked = 1;
2027 if (strcmp(got_ref_get_symref_target(symref),
2028 got_ref_get_name(target_ref)) == 0)
2029 goto done;
2031 err = got_ref_change_symref(symref,
2032 got_ref_get_name(target_ref));
2033 if (err)
2034 goto done;
2036 err = got_ref_write(symref, repo);
2037 if (err)
2038 goto done;
2040 if (verbosity >= 0)
2041 printf("Updated %s: %s\n", got_ref_get_name(symref),
2042 got_ref_get_symref_target(symref));
2045 done:
2046 if (symref_is_locked) {
2047 unlock_err = got_ref_unlock(symref);
2048 if (unlock_err && err == NULL)
2049 err = unlock_err;
2051 got_ref_close(symref);
2052 return err;
2055 __dead static void
2056 usage_fetch(void)
2058 fprintf(stderr, "usage: %s fetch [-adlqtvX] [-b branch] "
2059 "[-R reference] [-r repository-path] [remote-repository]\n",
2060 getprogname());
2061 exit(1);
2064 static const struct got_error *
2065 delete_missing_ref(struct got_reference *ref,
2066 int verbosity, struct got_repository *repo)
2068 const struct got_error *err = NULL;
2069 struct got_object_id *id = NULL;
2070 char *id_str = NULL;
2072 if (got_ref_is_symbolic(ref)) {
2073 err = got_ref_delete(ref, repo);
2074 if (err)
2075 return err;
2076 if (verbosity >= 0) {
2077 printf("Deleted %s: %s\n",
2078 got_ref_get_name(ref),
2079 got_ref_get_symref_target(ref));
2081 } else {
2082 err = got_ref_resolve(&id, repo, ref);
2083 if (err)
2084 return err;
2085 err = got_object_id_str(&id_str, id);
2086 if (err)
2087 goto done;
2089 err = got_ref_delete(ref, repo);
2090 if (err)
2091 goto done;
2092 if (verbosity >= 0) {
2093 printf("Deleted %s: %s\n",
2094 got_ref_get_name(ref), id_str);
2097 done:
2098 free(id);
2099 free(id_str);
2100 return err;
2103 static const struct got_error *
2104 delete_missing_refs(struct got_pathlist_head *their_refs,
2105 struct got_pathlist_head *their_symrefs,
2106 const struct got_remote_repo *remote,
2107 int verbosity, struct got_repository *repo)
2109 const struct got_error *err = NULL, *unlock_err;
2110 struct got_reflist_head my_refs;
2111 struct got_reflist_entry *re;
2112 struct got_pathlist_entry *pe;
2113 char *remote_namespace = NULL;
2114 char *local_refname = NULL;
2116 TAILQ_INIT(&my_refs);
2118 if (asprintf(&remote_namespace, "refs/remotes/%s/", remote->name)
2119 == -1)
2120 return got_error_from_errno("asprintf");
2122 err = got_ref_list(&my_refs, repo, NULL, got_ref_cmp_by_name, NULL);
2123 if (err)
2124 goto done;
2126 TAILQ_FOREACH(re, &my_refs, entry) {
2127 const char *refname = got_ref_get_name(re->ref);
2128 const char *their_refname;
2130 if (remote->mirror_references) {
2131 their_refname = refname;
2132 } else {
2133 if (strncmp(refname, remote_namespace,
2134 strlen(remote_namespace)) == 0) {
2135 if (strcmp(refname + strlen(remote_namespace),
2136 GOT_REF_HEAD) == 0)
2137 continue;
2138 if (asprintf(&local_refname, "refs/heads/%s",
2139 refname + strlen(remote_namespace)) == -1) {
2140 err = got_error_from_errno("asprintf");
2141 goto done;
2143 } else if (strncmp(refname, "refs/tags/", 10) != 0)
2144 continue;
2146 their_refname = local_refname;
2149 TAILQ_FOREACH(pe, their_refs, entry) {
2150 if (strcmp(their_refname, pe->path) == 0)
2151 break;
2153 if (pe != NULL)
2154 continue;
2156 TAILQ_FOREACH(pe, their_symrefs, entry) {
2157 if (strcmp(their_refname, pe->path) == 0)
2158 break;
2160 if (pe != NULL)
2161 continue;
2163 err = delete_missing_ref(re->ref, verbosity, repo);
2164 if (err)
2165 break;
2167 if (local_refname) {
2168 struct got_reference *ref;
2169 err = got_ref_open(&ref, repo, local_refname, 1);
2170 if (err) {
2171 if (err->code != GOT_ERR_NOT_REF)
2172 break;
2173 free(local_refname);
2174 local_refname = NULL;
2175 continue;
2177 err = delete_missing_ref(ref, verbosity, repo);
2178 if (err)
2179 break;
2180 unlock_err = got_ref_unlock(ref);
2181 got_ref_close(ref);
2182 if (unlock_err && err == NULL) {
2183 err = unlock_err;
2184 break;
2187 free(local_refname);
2188 local_refname = NULL;
2191 done:
2192 got_ref_list_free(&my_refs);
2193 free(remote_namespace);
2194 free(local_refname);
2195 return err;
2198 static const struct got_error *
2199 update_wanted_ref(const char *refname, struct got_object_id *id,
2200 const char *remote_repo_name, int verbosity, struct got_repository *repo)
2202 const struct got_error *err, *unlock_err;
2203 char *remote_refname;
2204 struct got_reference *ref;
2206 if (strncmp("refs/", refname, 5) == 0)
2207 refname += 5;
2209 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
2210 remote_repo_name, refname) == -1)
2211 return got_error_from_errno("asprintf");
2213 err = got_ref_open(&ref, repo, remote_refname, 1);
2214 if (err) {
2215 if (err->code != GOT_ERR_NOT_REF)
2216 goto done;
2217 err = create_ref(remote_refname, id, verbosity, repo);
2218 } else {
2219 err = update_ref(ref, id, 0, verbosity, repo);
2220 unlock_err = got_ref_unlock(ref);
2221 if (unlock_err && err == NULL)
2222 err = unlock_err;
2223 got_ref_close(ref);
2225 done:
2226 free(remote_refname);
2227 return err;
2230 static const struct got_error *
2231 delete_ref(struct got_repository *repo, struct got_reference *ref)
2233 const struct got_error *err = NULL;
2234 struct got_object_id *id = NULL;
2235 char *id_str = NULL;
2236 const char *target;
2238 if (got_ref_is_symbolic(ref)) {
2239 target = got_ref_get_symref_target(ref);
2240 } else {
2241 err = got_ref_resolve(&id, repo, ref);
2242 if (err)
2243 goto done;
2244 err = got_object_id_str(&id_str, id);
2245 if (err)
2246 goto done;
2247 target = id_str;
2250 err = got_ref_delete(ref, repo);
2251 if (err)
2252 goto done;
2254 printf("Deleted %s: %s\n", got_ref_get_name(ref), target);
2255 done:
2256 free(id);
2257 free(id_str);
2258 return err;
2261 static const struct got_error *
2262 delete_refs_for_remote(struct got_repository *repo, const char *remote_name)
2264 const struct got_error *err = NULL;
2265 struct got_reflist_head refs;
2266 struct got_reflist_entry *re;
2267 char *prefix;
2269 TAILQ_INIT(&refs);
2271 if (asprintf(&prefix, "refs/remotes/%s", remote_name) == -1) {
2272 err = got_error_from_errno("asprintf");
2273 goto done;
2275 err = got_ref_list(&refs, repo, prefix, got_ref_cmp_by_name, NULL);
2276 if (err)
2277 goto done;
2279 TAILQ_FOREACH(re, &refs, entry)
2280 delete_ref(repo, re->ref);
2281 done:
2282 got_ref_list_free(&refs);
2283 return err;
2286 static const struct got_error *
2287 cmd_fetch(int argc, char *argv[])
2289 const struct got_error *error = NULL, *unlock_err;
2290 char *cwd = NULL, *repo_path = NULL;
2291 const char *remote_name;
2292 char *proto = NULL, *host = NULL, *port = NULL;
2293 char *repo_name = NULL, *server_path = NULL;
2294 const struct got_remote_repo *remotes;
2295 struct got_remote_repo *remote = NULL;
2296 int nremotes;
2297 char *id_str = NULL;
2298 struct got_repository *repo = NULL;
2299 struct got_worktree *worktree = NULL;
2300 const struct got_gotconfig *repo_conf = NULL, *worktree_conf = NULL;
2301 struct got_pathlist_head refs, symrefs, wanted_branches, wanted_refs;
2302 char *head_refname = NULL;
2303 struct got_pathlist_entry *pe;
2304 struct got_reflist_head remote_refs;
2305 struct got_reflist_entry *re;
2306 struct got_object_id *pack_hash = NULL;
2307 int i, ch, fetchfd = -1, fetchstatus;
2308 pid_t fetchpid = -1;
2309 struct got_fetch_progress_arg fpa;
2310 int verbosity = 0, fetch_all_branches = 0, list_refs_only = 0;
2311 int delete_refs = 0, replace_tags = 0, delete_remote = 0;
2312 int *pack_fds = NULL, have_bflag = 0;
2313 const char *remote_head = NULL, *worktree_branch = NULL;
2315 TAILQ_INIT(&refs);
2316 TAILQ_INIT(&symrefs);
2317 TAILQ_INIT(&remote_refs);
2318 TAILQ_INIT(&wanted_branches);
2319 TAILQ_INIT(&wanted_refs);
2321 while ((ch = getopt(argc, argv, "ab:dlqR:r:tvX")) != -1) {
2322 switch (ch) {
2323 case 'a':
2324 fetch_all_branches = 1;
2325 break;
2326 case 'b':
2327 error = got_pathlist_append(&wanted_branches,
2328 optarg, NULL);
2329 if (error)
2330 return error;
2331 have_bflag = 1;
2332 break;
2333 case 'd':
2334 delete_refs = 1;
2335 break;
2336 case 'l':
2337 list_refs_only = 1;
2338 break;
2339 case 'q':
2340 verbosity = -1;
2341 break;
2342 case 'R':
2343 error = got_pathlist_append(&wanted_refs,
2344 optarg, NULL);
2345 if (error)
2346 return error;
2347 break;
2348 case 'r':
2349 repo_path = realpath(optarg, NULL);
2350 if (repo_path == NULL)
2351 return got_error_from_errno2("realpath",
2352 optarg);
2353 got_path_strip_trailing_slashes(repo_path);
2354 break;
2355 case 't':
2356 replace_tags = 1;
2357 break;
2358 case 'v':
2359 if (verbosity < 0)
2360 verbosity = 0;
2361 else if (verbosity < 3)
2362 verbosity++;
2363 break;
2364 case 'X':
2365 delete_remote = 1;
2366 break;
2367 default:
2368 usage_fetch();
2369 break;
2372 argc -= optind;
2373 argv += optind;
2375 if (fetch_all_branches && !TAILQ_EMPTY(&wanted_branches))
2376 option_conflict('a', 'b');
2377 if (list_refs_only) {
2378 if (!TAILQ_EMPTY(&wanted_branches))
2379 option_conflict('l', 'b');
2380 if (fetch_all_branches)
2381 option_conflict('l', 'a');
2382 if (delete_refs)
2383 option_conflict('l', 'd');
2384 if (delete_remote)
2385 option_conflict('l', 'X');
2387 if (delete_remote) {
2388 if (fetch_all_branches)
2389 option_conflict('X', 'a');
2390 if (!TAILQ_EMPTY(&wanted_branches))
2391 option_conflict('X', 'b');
2392 if (delete_refs)
2393 option_conflict('X', 'd');
2394 if (replace_tags)
2395 option_conflict('X', 't');
2396 if (!TAILQ_EMPTY(&wanted_refs))
2397 option_conflict('X', 'R');
2400 if (argc == 0) {
2401 if (delete_remote)
2402 errx(1, "-X option requires a remote name");
2403 remote_name = GOT_FETCH_DEFAULT_REMOTE_NAME;
2404 } else if (argc == 1)
2405 remote_name = argv[0];
2406 else
2407 usage_fetch();
2409 cwd = getcwd(NULL, 0);
2410 if (cwd == NULL) {
2411 error = got_error_from_errno("getcwd");
2412 goto done;
2415 error = got_repo_pack_fds_open(&pack_fds);
2416 if (error != NULL)
2417 goto done;
2419 if (repo_path == NULL) {
2420 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
2421 if (error && error->code != GOT_ERR_NOT_WORKTREE)
2422 goto done;
2423 else
2424 error = NULL;
2425 if (worktree) {
2426 repo_path =
2427 strdup(got_worktree_get_repo_path(worktree));
2428 if (repo_path == NULL)
2429 error = got_error_from_errno("strdup");
2430 if (error)
2431 goto done;
2432 } else {
2433 repo_path = strdup(cwd);
2434 if (repo_path == NULL) {
2435 error = got_error_from_errno("strdup");
2436 goto done;
2441 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
2442 if (error)
2443 goto done;
2445 if (delete_remote) {
2446 error = delete_refs_for_remote(repo, remote_name);
2447 goto done; /* nothing else to do */
2450 if (worktree) {
2451 worktree_conf = got_worktree_get_gotconfig(worktree);
2452 if (worktree_conf) {
2453 got_gotconfig_get_remotes(&nremotes, &remotes,
2454 worktree_conf);
2455 for (i = 0; i < nremotes; i++) {
2456 if (strcmp(remotes[i].name, remote_name) == 0) {
2457 error = got_repo_remote_repo_dup(&remote,
2458 &remotes[i]);
2459 if (error)
2460 goto done;
2461 break;
2466 if (remote == NULL) {
2467 repo_conf = got_repo_get_gotconfig(repo);
2468 if (repo_conf) {
2469 got_gotconfig_get_remotes(&nremotes, &remotes,
2470 repo_conf);
2471 for (i = 0; i < nremotes; i++) {
2472 if (strcmp(remotes[i].name, remote_name) == 0) {
2473 error = got_repo_remote_repo_dup(&remote,
2474 &remotes[i]);
2475 if (error)
2476 goto done;
2477 break;
2482 if (remote == NULL) {
2483 got_repo_get_gitconfig_remotes(&nremotes, &remotes, repo);
2484 for (i = 0; i < nremotes; i++) {
2485 if (strcmp(remotes[i].name, remote_name) == 0) {
2486 error = got_repo_remote_repo_dup(&remote,
2487 &remotes[i]);
2488 if (error)
2489 goto done;
2490 break;
2494 if (remote == NULL) {
2495 error = got_error_path(remote_name, GOT_ERR_NO_REMOTE);
2496 goto done;
2499 if (TAILQ_EMPTY(&wanted_branches)) {
2500 if (!fetch_all_branches)
2501 fetch_all_branches = remote->fetch_all_branches;
2502 for (i = 0; i < remote->nfetch_branches; i++) {
2503 error = got_pathlist_append(&wanted_branches,
2504 remote->fetch_branches[i], NULL);
2505 if (error)
2506 goto done;
2509 if (TAILQ_EMPTY(&wanted_refs)) {
2510 for (i = 0; i < remote->nfetch_refs; i++) {
2511 error = got_pathlist_append(&wanted_refs,
2512 remote->fetch_refs[i], NULL);
2513 if (error)
2514 goto done;
2518 error = got_dial_parse_uri(&proto, &host, &port, &server_path,
2519 &repo_name, remote->fetch_url);
2520 if (error)
2521 goto done;
2523 if (strcmp(proto, "git") == 0) {
2524 #ifndef PROFILE
2525 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
2526 "sendfd dns inet unveil", NULL) == -1)
2527 err(1, "pledge");
2528 #endif
2529 } else if (strcmp(proto, "git+ssh") == 0 ||
2530 strcmp(proto, "ssh") == 0) {
2531 #ifndef PROFILE
2532 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
2533 "sendfd unveil", NULL) == -1)
2534 err(1, "pledge");
2535 #endif
2536 } else if (strcmp(proto, "http") == 0 ||
2537 strcmp(proto, "git+http") == 0) {
2538 error = got_error_path(proto, GOT_ERR_NOT_IMPL);
2539 goto done;
2540 } else {
2541 error = got_error_path(proto, GOT_ERR_BAD_PROTO);
2542 goto done;
2545 error = got_dial_apply_unveil(proto);
2546 if (error)
2547 goto done;
2549 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
2550 if (error)
2551 goto done;
2553 if (worktree) {
2554 head_refname = strdup(got_worktree_get_head_ref_name(worktree));
2555 if (head_refname == NULL) {
2556 error = got_error_from_errno("strdup");
2557 goto done;
2560 /* Release work tree lock. */
2561 got_worktree_close(worktree);
2562 worktree = NULL;
2565 if (verbosity >= 0) {
2566 printf("Connecting to \"%s\" %s://%s%s%s%s%s\n",
2567 remote->name, proto, host,
2568 port ? ":" : "", port ? port : "",
2569 *server_path == '/' ? "" : "/", server_path);
2572 error = got_fetch_connect(&fetchpid, &fetchfd, proto, host, port,
2573 server_path, verbosity);
2574 if (error)
2575 goto done;
2577 if (!have_bflag) {
2579 * If set, get this remote's HEAD ref target so
2580 * if it has changed on the server we can fetch it.
2582 error = got_ref_list(&remote_refs, repo, "refs/remotes",
2583 got_ref_cmp_by_name, repo);
2584 if (error)
2585 goto done;
2587 TAILQ_FOREACH(re, &remote_refs, entry) {
2588 const char *remote_refname, *remote_target;
2589 size_t remote_name_len;
2591 if (!got_ref_is_symbolic(re->ref))
2592 continue;
2594 remote_name_len = strlen(remote->name);
2595 remote_refname = got_ref_get_name(re->ref);
2597 /* we only want refs/remotes/$remote->name/HEAD */
2598 if (strncmp(remote_refname + 13, remote->name,
2599 remote_name_len) != 0)
2600 continue;
2602 if (strcmp(remote_refname + remote_name_len + 14,
2603 GOT_REF_HEAD) != 0)
2604 continue;
2607 * Take the name itself because we already
2608 * only match with refs/heads/ in fetch_pack().
2610 remote_target = got_ref_get_symref_target(re->ref);
2611 remote_head = remote_target + remote_name_len + 14;
2612 break;
2615 if (head_refname &&
2616 strncmp(head_refname, "refs/heads/", 11) == 0)
2617 worktree_branch = head_refname;
2620 fpa.last_scaled_size[0] = '\0';
2621 fpa.last_p_indexed = -1;
2622 fpa.last_p_resolved = -1;
2623 fpa.verbosity = verbosity;
2624 fpa.repo = repo;
2625 fpa.create_configs = 0;
2626 fpa.configs_created = 0;
2627 memset(&fpa.config_info, 0, sizeof(fpa.config_info));
2629 error = got_fetch_pack(&pack_hash, &refs, &symrefs, remote->name,
2630 remote->mirror_references, fetch_all_branches, &wanted_branches,
2631 &wanted_refs, list_refs_only, verbosity, fetchfd, repo,
2632 worktree_branch, remote_head, have_bflag, fetch_progress, &fpa);
2633 if (error)
2634 goto done;
2636 if (list_refs_only) {
2637 error = list_remote_refs(&symrefs, &refs);
2638 goto done;
2641 if (pack_hash == NULL) {
2642 if (verbosity >= 0)
2643 printf("Already up-to-date\n");
2644 } else if (verbosity >= 0) {
2645 error = got_object_id_str(&id_str, pack_hash);
2646 if (error)
2647 goto done;
2648 printf("\nFetched %s.pack\n", id_str);
2649 free(id_str);
2650 id_str = NULL;
2653 /* Update references provided with the pack file. */
2654 TAILQ_FOREACH(pe, &refs, entry) {
2655 const char *refname = pe->path;
2656 struct got_object_id *id = pe->data;
2657 struct got_reference *ref;
2658 char *remote_refname;
2660 if (is_wanted_ref(&wanted_refs, refname) &&
2661 !remote->mirror_references) {
2662 error = update_wanted_ref(refname, id,
2663 remote->name, verbosity, repo);
2664 if (error)
2665 goto done;
2666 continue;
2669 if (remote->mirror_references ||
2670 strncmp("refs/tags/", refname, 10) == 0) {
2671 error = got_ref_open(&ref, repo, refname, 1);
2672 if (error) {
2673 if (error->code != GOT_ERR_NOT_REF)
2674 goto done;
2675 error = create_ref(refname, id, verbosity,
2676 repo);
2677 if (error)
2678 goto done;
2679 } else {
2680 error = update_ref(ref, id, replace_tags,
2681 verbosity, repo);
2682 unlock_err = got_ref_unlock(ref);
2683 if (unlock_err && error == NULL)
2684 error = unlock_err;
2685 got_ref_close(ref);
2686 if (error)
2687 goto done;
2689 } else if (strncmp("refs/heads/", refname, 11) == 0) {
2690 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
2691 remote_name, refname + 11) == -1) {
2692 error = got_error_from_errno("asprintf");
2693 goto done;
2696 error = got_ref_open(&ref, repo, remote_refname, 1);
2697 if (error) {
2698 if (error->code != GOT_ERR_NOT_REF)
2699 goto done;
2700 error = create_ref(remote_refname, id,
2701 verbosity, repo);
2702 if (error)
2703 goto done;
2704 } else {
2705 error = update_ref(ref, id, replace_tags,
2706 verbosity, repo);
2707 unlock_err = got_ref_unlock(ref);
2708 if (unlock_err && error == NULL)
2709 error = unlock_err;
2710 got_ref_close(ref);
2711 if (error)
2712 goto done;
2715 /* Also create a local branch if none exists yet. */
2716 error = got_ref_open(&ref, repo, refname, 1);
2717 if (error) {
2718 if (error->code != GOT_ERR_NOT_REF)
2719 goto done;
2720 error = create_ref(refname, id, verbosity,
2721 repo);
2722 if (error)
2723 goto done;
2724 } else {
2725 unlock_err = got_ref_unlock(ref);
2726 if (unlock_err && error == NULL)
2727 error = unlock_err;
2728 got_ref_close(ref);
2732 if (delete_refs) {
2733 error = delete_missing_refs(&refs, &symrefs, remote,
2734 verbosity, repo);
2735 if (error)
2736 goto done;
2739 if (!remote->mirror_references) {
2740 /* Update remote HEAD reference if the server provided one. */
2741 TAILQ_FOREACH(pe, &symrefs, entry) {
2742 struct got_reference *target_ref;
2743 const char *refname = pe->path;
2744 const char *target = pe->data;
2745 char *remote_refname = NULL, *remote_target = NULL;
2747 if (strcmp(refname, GOT_REF_HEAD) != 0)
2748 continue;
2750 if (strncmp("refs/heads/", target, 11) != 0)
2751 continue;
2753 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
2754 remote->name, refname) == -1) {
2755 error = got_error_from_errno("asprintf");
2756 goto done;
2758 if (asprintf(&remote_target, "refs/remotes/%s/%s",
2759 remote->name, target + 11) == -1) {
2760 error = got_error_from_errno("asprintf");
2761 free(remote_refname);
2762 goto done;
2765 error = got_ref_open(&target_ref, repo, remote_target,
2766 0);
2767 if (error) {
2768 free(remote_refname);
2769 free(remote_target);
2770 if (error->code == GOT_ERR_NOT_REF) {
2771 error = NULL;
2772 continue;
2774 goto done;
2776 error = update_symref(remote_refname, target_ref,
2777 verbosity, repo);
2778 free(remote_refname);
2779 free(remote_target);
2780 got_ref_close(target_ref);
2781 if (error)
2782 goto done;
2785 done:
2786 if (fetchpid > 0) {
2787 if (kill(fetchpid, SIGTERM) == -1)
2788 error = got_error_from_errno("kill");
2789 if (waitpid(fetchpid, &fetchstatus, 0) == -1 && error == NULL)
2790 error = got_error_from_errno("waitpid");
2792 if (fetchfd != -1 && close(fetchfd) == -1 && error == NULL)
2793 error = got_error_from_errno("close");
2794 if (repo) {
2795 const struct got_error *close_err = got_repo_close(repo);
2796 if (error == NULL)
2797 error = close_err;
2799 if (worktree)
2800 got_worktree_close(worktree);
2801 if (pack_fds) {
2802 const struct got_error *pack_err =
2803 got_repo_pack_fds_close(pack_fds);
2804 if (error == NULL)
2805 error = pack_err;
2807 got_pathlist_free(&refs, GOT_PATHLIST_FREE_ALL);
2808 got_pathlist_free(&symrefs, GOT_PATHLIST_FREE_ALL);
2809 got_pathlist_free(&wanted_branches, GOT_PATHLIST_FREE_NONE);
2810 got_pathlist_free(&wanted_refs, GOT_PATHLIST_FREE_NONE);
2811 got_ref_list_free(&remote_refs);
2812 got_repo_free_remote_repo_data(remote);
2813 free(remote);
2814 free(head_refname);
2815 free(id_str);
2816 free(cwd);
2817 free(repo_path);
2818 free(pack_hash);
2819 free(proto);
2820 free(host);
2821 free(port);
2822 free(server_path);
2823 free(repo_name);
2824 return error;
2828 __dead static void
2829 usage_checkout(void)
2831 fprintf(stderr, "usage: %s checkout [-Eq] [-b branch] [-c commit] "
2832 "[-p path-prefix] repository-path [work-tree-path]\n",
2833 getprogname());
2834 exit(1);
2837 static void
2838 show_worktree_base_ref_warning(void)
2840 fprintf(stderr, "%s: warning: could not create a reference "
2841 "to the work tree's base commit; the commit could be "
2842 "garbage-collected by Git or 'gotadmin cleanup'; making the "
2843 "repository writable and running 'got update' will prevent this\n",
2844 getprogname());
2847 struct got_checkout_progress_arg {
2848 const char *worktree_path;
2849 int had_base_commit_ref_error;
2850 int verbosity;
2853 static const struct got_error *
2854 checkout_progress(void *arg, unsigned char status, const char *path)
2856 struct got_checkout_progress_arg *a = arg;
2858 /* Base commit bump happens silently. */
2859 if (status == GOT_STATUS_BUMP_BASE)
2860 return NULL;
2862 if (status == GOT_STATUS_BASE_REF_ERR) {
2863 a->had_base_commit_ref_error = 1;
2864 return NULL;
2867 while (path[0] == '/')
2868 path++;
2870 if (a->verbosity >= 0)
2871 printf("%c %s/%s\n", status, a->worktree_path, path);
2873 return NULL;
2876 static const struct got_error *
2877 check_cancelled(void *arg)
2879 if (sigint_received || sigpipe_received)
2880 return got_error(GOT_ERR_CANCELLED);
2881 return NULL;
2884 static const struct got_error *
2885 check_linear_ancestry(struct got_object_id *commit_id,
2886 struct got_object_id *base_commit_id, int allow_forwards_in_time_only,
2887 struct got_repository *repo)
2889 const struct got_error *err = NULL;
2890 struct got_object_id *yca_id;
2892 err = got_commit_graph_find_youngest_common_ancestor(&yca_id,
2893 commit_id, base_commit_id, 1, 0, repo, check_cancelled, NULL);
2894 if (err)
2895 return err;
2897 if (yca_id == NULL)
2898 return got_error(GOT_ERR_ANCESTRY);
2901 * Require a straight line of history between the target commit
2902 * and the work tree's base commit.
2904 * Non-linear situations such as this require a rebase:
2906 * (commit) D F (base_commit)
2907 * \ /
2908 * C E
2909 * \ /
2910 * B (yca)
2911 * |
2912 * A
2914 * 'got update' only handles linear cases:
2915 * Update forwards in time: A (base/yca) - B - C - D (commit)
2916 * Update backwards in time: D (base) - C - B - A (commit/yca)
2918 if (allow_forwards_in_time_only) {
2919 if (got_object_id_cmp(base_commit_id, yca_id) != 0)
2920 return got_error(GOT_ERR_ANCESTRY);
2921 } else if (got_object_id_cmp(commit_id, yca_id) != 0 &&
2922 got_object_id_cmp(base_commit_id, yca_id) != 0)
2923 return got_error(GOT_ERR_ANCESTRY);
2925 free(yca_id);
2926 return NULL;
2929 static const struct got_error *
2930 check_same_branch(struct got_object_id *commit_id,
2931 struct got_reference *head_ref, struct got_repository *repo)
2933 const struct got_error *err = NULL;
2934 struct got_commit_graph *graph = NULL;
2935 struct got_object_id *head_commit_id = NULL;
2937 err = got_ref_resolve(&head_commit_id, repo, head_ref);
2938 if (err)
2939 goto done;
2941 if (got_object_id_cmp(head_commit_id, commit_id) == 0)
2942 goto done;
2944 err = got_commit_graph_open(&graph, "/", 1);
2945 if (err)
2946 goto done;
2948 err = got_commit_graph_iter_start(graph, head_commit_id, repo,
2949 check_cancelled, NULL);
2950 if (err)
2951 goto done;
2953 for (;;) {
2954 struct got_object_id id;
2956 err = got_commit_graph_iter_next(&id, graph, repo,
2957 check_cancelled, NULL);
2958 if (err) {
2959 if (err->code == GOT_ERR_ITER_COMPLETED)
2960 err = got_error(GOT_ERR_ANCESTRY);
2961 break;
2964 if (got_object_id_cmp(&id, commit_id) == 0)
2965 break;
2967 done:
2968 if (graph)
2969 got_commit_graph_close(graph);
2970 free(head_commit_id);
2971 return err;
2974 static const struct got_error *
2975 checkout_ancestry_error(struct got_reference *ref, const char *commit_id_str)
2977 static char msg[512];
2978 const char *branch_name;
2980 if (got_ref_is_symbolic(ref))
2981 branch_name = got_ref_get_symref_target(ref);
2982 else
2983 branch_name = got_ref_get_name(ref);
2985 if (strncmp("refs/heads/", branch_name, 11) == 0)
2986 branch_name += 11;
2988 snprintf(msg, sizeof(msg),
2989 "target commit is not contained in branch '%s'; "
2990 "the branch to use must be specified with -b; "
2991 "if necessary a new branch can be created for "
2992 "this commit with 'got branch -c %s BRANCH_NAME'",
2993 branch_name, commit_id_str);
2995 return got_error_msg(GOT_ERR_ANCESTRY, msg);
2998 static const struct got_error *
2999 cmd_checkout(int argc, char *argv[])
3001 const struct got_error *close_err, *error = NULL;
3002 struct got_repository *repo = NULL;
3003 struct got_reference *head_ref = NULL, *ref = NULL;
3004 struct got_worktree *worktree = NULL;
3005 char *repo_path = NULL;
3006 char *worktree_path = NULL;
3007 const char *path_prefix = "";
3008 const char *branch_name = GOT_REF_HEAD, *refname = NULL;
3009 char *commit_id_str = NULL, *keyword_idstr = NULL;
3010 struct got_object_id *commit_id = NULL;
3011 char *cwd = NULL;
3012 int ch, same_path_prefix, allow_nonempty = 0, verbosity = 0;
3013 struct got_pathlist_head paths;
3014 struct got_checkout_progress_arg cpa;
3015 int *pack_fds = NULL;
3017 TAILQ_INIT(&paths);
3019 #ifndef PROFILE
3020 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
3021 "unveil", NULL) == -1)
3022 err(1, "pledge");
3023 #endif
3025 while ((ch = getopt(argc, argv, "b:c:Ep:q")) != -1) {
3026 switch (ch) {
3027 case 'b':
3028 branch_name = optarg;
3029 break;
3030 case 'c':
3031 commit_id_str = strdup(optarg);
3032 if (commit_id_str == NULL)
3033 return got_error_from_errno("strdup");
3034 break;
3035 case 'E':
3036 allow_nonempty = 1;
3037 break;
3038 case 'p':
3039 path_prefix = optarg;
3040 break;
3041 case 'q':
3042 verbosity = -1;
3043 break;
3044 default:
3045 usage_checkout();
3046 /* NOTREACHED */
3050 argc -= optind;
3051 argv += optind;
3053 if (argc == 1) {
3054 char *base, *dotgit;
3055 const char *path;
3056 repo_path = realpath(argv[0], NULL);
3057 if (repo_path == NULL)
3058 return got_error_from_errno2("realpath", argv[0]);
3059 cwd = getcwd(NULL, 0);
3060 if (cwd == NULL) {
3061 error = got_error_from_errno("getcwd");
3062 goto done;
3064 if (path_prefix[0])
3065 path = path_prefix;
3066 else
3067 path = repo_path;
3068 error = got_path_basename(&base, path);
3069 if (error)
3070 goto done;
3071 dotgit = strstr(base, ".git");
3072 if (dotgit)
3073 *dotgit = '\0';
3074 if (asprintf(&worktree_path, "%s/%s", cwd, base) == -1) {
3075 error = got_error_from_errno("asprintf");
3076 free(base);
3077 goto done;
3079 free(base);
3080 } else if (argc == 2) {
3081 repo_path = realpath(argv[0], NULL);
3082 if (repo_path == NULL) {
3083 error = got_error_from_errno2("realpath", argv[0]);
3084 goto done;
3086 worktree_path = realpath(argv[1], NULL);
3087 if (worktree_path == NULL) {
3088 if (errno != ENOENT) {
3089 error = got_error_from_errno2("realpath",
3090 argv[1]);
3091 goto done;
3093 worktree_path = strdup(argv[1]);
3094 if (worktree_path == NULL) {
3095 error = got_error_from_errno("strdup");
3096 goto done;
3099 } else
3100 usage_checkout();
3102 got_path_strip_trailing_slashes(repo_path);
3103 got_path_strip_trailing_slashes(worktree_path);
3105 if (got_path_is_child(worktree_path, repo_path, strlen(repo_path)) ||
3106 got_path_is_child(repo_path, worktree_path,
3107 strlen(worktree_path))) {
3108 error = got_error_fmt(GOT_ERR_BAD_PATH,
3109 "work tree and repository paths may not overlap: %s",
3110 worktree_path);
3111 goto done;
3114 error = got_repo_pack_fds_open(&pack_fds);
3115 if (error != NULL)
3116 goto done;
3118 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
3119 if (error != NULL)
3120 goto done;
3122 /* Pre-create work tree path for unveil(2) */
3123 error = got_path_mkdir(worktree_path);
3124 if (error) {
3125 if (!(error->code == GOT_ERR_ERRNO && errno == EISDIR) &&
3126 !(error->code == GOT_ERR_ERRNO && errno == EEXIST))
3127 goto done;
3128 if (!allow_nonempty &&
3129 !got_path_dir_is_empty(worktree_path)) {
3130 error = got_error_path(worktree_path,
3131 GOT_ERR_DIR_NOT_EMPTY);
3132 goto done;
3136 error = apply_unveil(got_repo_get_path(repo), 0, worktree_path);
3137 if (error)
3138 goto done;
3140 error = got_ref_open(&head_ref, repo, branch_name, 0);
3141 if (error != NULL)
3142 goto done;
3144 error = got_worktree_init(worktree_path, head_ref, path_prefix,
3145 GOT_WORKTREE_GOT_DIR, repo);
3146 if (error != NULL && !(error->code == GOT_ERR_ERRNO && errno == EEXIST))
3147 goto done;
3149 error = got_worktree_open(&worktree, worktree_path,
3150 GOT_WORKTREE_GOT_DIR);
3151 if (error != NULL)
3152 goto done;
3154 error = got_worktree_match_path_prefix(&same_path_prefix, worktree,
3155 path_prefix);
3156 if (error != NULL)
3157 goto done;
3158 if (!same_path_prefix) {
3159 error = got_error(GOT_ERR_PATH_PREFIX);
3160 goto done;
3163 if (commit_id_str) {
3164 struct got_reflist_head refs;
3165 TAILQ_INIT(&refs);
3166 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
3167 NULL);
3168 if (error)
3169 goto done;
3171 error = got_keyword_to_idstr(&keyword_idstr, commit_id_str,
3172 repo, worktree);
3173 if (error != NULL)
3174 goto done;
3175 if (keyword_idstr != NULL) {
3176 free(commit_id_str);
3177 commit_id_str = keyword_idstr;
3180 error = got_repo_match_object_id(&commit_id, NULL,
3181 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
3182 got_ref_list_free(&refs);
3183 if (error)
3184 goto done;
3185 error = check_linear_ancestry(commit_id,
3186 got_worktree_get_base_commit_id(worktree), 0, repo);
3187 if (error != NULL) {
3188 if (error->code == GOT_ERR_ANCESTRY) {
3189 error = checkout_ancestry_error(
3190 head_ref, commit_id_str);
3192 goto done;
3194 error = check_same_branch(commit_id, head_ref, repo);
3195 if (error) {
3196 if (error->code == GOT_ERR_ANCESTRY) {
3197 error = checkout_ancestry_error(
3198 head_ref, commit_id_str);
3200 goto done;
3202 error = got_worktree_set_base_commit_id(worktree, repo,
3203 commit_id);
3204 if (error)
3205 goto done;
3206 /* Expand potentially abbreviated commit ID string. */
3207 free(commit_id_str);
3208 error = got_object_id_str(&commit_id_str, commit_id);
3209 if (error)
3210 goto done;
3211 } else {
3212 commit_id = got_object_id_dup(
3213 got_worktree_get_base_commit_id(worktree));
3214 if (commit_id == NULL) {
3215 error = got_error_from_errno("got_object_id_dup");
3216 goto done;
3218 error = got_object_id_str(&commit_id_str, commit_id);
3219 if (error)
3220 goto done;
3223 error = got_pathlist_append(&paths, "", NULL);
3224 if (error)
3225 goto done;
3226 cpa.worktree_path = worktree_path;
3227 cpa.had_base_commit_ref_error = 0;
3228 cpa.verbosity = verbosity;
3229 error = got_worktree_checkout_files(worktree, &paths, repo,
3230 checkout_progress, &cpa, check_cancelled, NULL);
3231 if (error != NULL)
3232 goto done;
3234 if (got_ref_is_symbolic(head_ref)) {
3235 error = got_ref_resolve_symbolic(&ref, repo, head_ref);
3236 if (error)
3237 goto done;
3238 refname = got_ref_get_name(ref);
3239 } else
3240 refname = got_ref_get_name(head_ref);
3241 printf("Checked out %s: %s\n", refname, commit_id_str);
3242 printf("Now shut up and hack\n");
3243 if (cpa.had_base_commit_ref_error)
3244 show_worktree_base_ref_warning();
3245 done:
3246 if (pack_fds) {
3247 const struct got_error *pack_err =
3248 got_repo_pack_fds_close(pack_fds);
3249 if (error == NULL)
3250 error = pack_err;
3252 if (head_ref)
3253 got_ref_close(head_ref);
3254 if (ref)
3255 got_ref_close(ref);
3256 if (repo) {
3257 close_err = got_repo_close(repo);
3258 if (error == NULL)
3259 error = close_err;
3261 if (worktree != NULL) {
3262 close_err = got_worktree_close(worktree);
3263 if (error == NULL)
3264 error = close_err;
3266 got_pathlist_free(&paths, GOT_PATHLIST_FREE_NONE);
3267 free(commit_id_str);
3268 free(commit_id);
3269 free(repo_path);
3270 free(worktree_path);
3271 free(cwd);
3272 return error;
3275 struct got_update_progress_arg {
3276 int did_something;
3277 int conflicts;
3278 int obstructed;
3279 int not_updated;
3280 int missing;
3281 int not_deleted;
3282 int unversioned;
3283 int verbosity;
3286 static void
3287 print_update_progress_stats(struct got_update_progress_arg *upa)
3289 if (!upa->did_something)
3290 return;
3292 if (upa->conflicts > 0)
3293 printf("Files with new merge conflicts: %d\n", upa->conflicts);
3294 if (upa->obstructed > 0)
3295 printf("File paths obstructed by a non-regular file: %d\n",
3296 upa->obstructed);
3297 if (upa->not_updated > 0)
3298 printf("Files not updated because of existing merge "
3299 "conflicts: %d\n", upa->not_updated);
3303 * The meaning of some status codes differs between merge-style operations and
3304 * update operations. For example, the ! status code means "file was missing"
3305 * if changes were merged into the work tree, and "missing file was restored"
3306 * if the work tree was updated. This function should be used by any operation
3307 * which merges changes into the work tree without updating the work tree.
3309 static void
3310 print_merge_progress_stats(struct got_update_progress_arg *upa)
3312 if (!upa->did_something)
3313 return;
3315 if (upa->conflicts > 0)
3316 printf("Files with new merge conflicts: %d\n", upa->conflicts);
3317 if (upa->obstructed > 0)
3318 printf("File paths obstructed by a non-regular file: %d\n",
3319 upa->obstructed);
3320 if (upa->missing > 0)
3321 printf("Files which had incoming changes but could not be "
3322 "found in the work tree: %d\n", upa->missing);
3323 if (upa->not_deleted > 0)
3324 printf("Files not deleted due to differences in deleted "
3325 "content: %d\n", upa->not_deleted);
3326 if (upa->unversioned > 0)
3327 printf("Files not merged because an unversioned file was "
3328 "found in the work tree: %d\n", upa->unversioned);
3331 __dead static void
3332 usage_update(void)
3334 fprintf(stderr, "usage: %s update [-q] [-b branch] [-c commit] "
3335 "[path ...]\n", getprogname());
3336 exit(1);
3339 static const struct got_error *
3340 update_progress(void *arg, unsigned char status, const char *path)
3342 struct got_update_progress_arg *upa = arg;
3344 if (status == GOT_STATUS_EXISTS ||
3345 status == GOT_STATUS_BASE_REF_ERR)
3346 return NULL;
3348 upa->did_something = 1;
3350 /* Base commit bump happens silently. */
3351 if (status == GOT_STATUS_BUMP_BASE)
3352 return NULL;
3354 if (status == GOT_STATUS_CONFLICT)
3355 upa->conflicts++;
3356 if (status == GOT_STATUS_OBSTRUCTED)
3357 upa->obstructed++;
3358 if (status == GOT_STATUS_CANNOT_UPDATE)
3359 upa->not_updated++;
3360 if (status == GOT_STATUS_MISSING)
3361 upa->missing++;
3362 if (status == GOT_STATUS_CANNOT_DELETE)
3363 upa->not_deleted++;
3364 if (status == GOT_STATUS_UNVERSIONED)
3365 upa->unversioned++;
3367 while (path[0] == '/')
3368 path++;
3369 if (upa->verbosity >= 0)
3370 printf("%c %s\n", status, path);
3372 return NULL;
3375 static const struct got_error *
3376 switch_head_ref(struct got_reference *head_ref,
3377 struct got_object_id *commit_id, struct got_worktree *worktree,
3378 struct got_repository *repo)
3380 const struct got_error *err = NULL;
3381 char *base_id_str;
3382 int ref_has_moved = 0;
3384 /* Trivial case: switching between two different references. */
3385 if (strcmp(got_ref_get_name(head_ref),
3386 got_worktree_get_head_ref_name(worktree)) != 0) {
3387 printf("Switching work tree from %s to %s\n",
3388 got_worktree_get_head_ref_name(worktree),
3389 got_ref_get_name(head_ref));
3390 return got_worktree_set_head_ref(worktree, head_ref);
3393 err = check_linear_ancestry(commit_id,
3394 got_worktree_get_base_commit_id(worktree), 0, repo);
3395 if (err) {
3396 if (err->code != GOT_ERR_ANCESTRY)
3397 return err;
3398 ref_has_moved = 1;
3400 if (!ref_has_moved)
3401 return NULL;
3403 /* Switching to a rebased branch with the same reference name. */
3404 err = got_object_id_str(&base_id_str,
3405 got_worktree_get_base_commit_id(worktree));
3406 if (err)
3407 return err;
3408 printf("Reference %s now points at a different branch\n",
3409 got_worktree_get_head_ref_name(worktree));
3410 printf("Switching work tree from %s to %s\n", base_id_str,
3411 got_worktree_get_head_ref_name(worktree));
3412 return NULL;
3415 static const struct got_error *
3416 check_rebase_or_histedit_in_progress(struct got_worktree *worktree)
3418 const struct got_error *err;
3419 int in_progress;
3421 err = got_worktree_rebase_in_progress(&in_progress, worktree);
3422 if (err)
3423 return err;
3424 if (in_progress)
3425 return got_error(GOT_ERR_REBASING);
3427 err = got_worktree_histedit_in_progress(&in_progress, worktree);
3428 if (err)
3429 return err;
3430 if (in_progress)
3431 return got_error(GOT_ERR_HISTEDIT_BUSY);
3433 return NULL;
3436 static const struct got_error *
3437 check_merge_in_progress(struct got_worktree *worktree,
3438 struct got_repository *repo)
3440 const struct got_error *err;
3441 int in_progress;
3443 err = got_worktree_merge_in_progress(&in_progress, worktree, repo);
3444 if (err)
3445 return err;
3446 if (in_progress)
3447 return got_error(GOT_ERR_MERGE_BUSY);
3449 return NULL;
3452 static const struct got_error *
3453 get_worktree_paths_from_argv(struct got_pathlist_head *paths, int argc,
3454 char *argv[], struct got_worktree *worktree)
3456 const struct got_error *err = NULL;
3457 char *path;
3458 struct got_pathlist_entry *new;
3459 int i;
3461 if (argc == 0) {
3462 path = strdup("");
3463 if (path == NULL)
3464 return got_error_from_errno("strdup");
3465 return got_pathlist_append(paths, path, NULL);
3468 for (i = 0; i < argc; i++) {
3469 err = got_worktree_resolve_path(&path, worktree, argv[i]);
3470 if (err)
3471 break;
3472 err = got_pathlist_insert(&new, paths, path, NULL);
3473 if (err || new == NULL /* duplicate */) {
3474 free(path);
3475 if (err)
3476 break;
3480 return err;
3483 static const struct got_error *
3484 wrap_not_worktree_error(const struct got_error *orig_err,
3485 const char *cmdname, const char *path)
3487 const struct got_error *err;
3488 struct got_repository *repo;
3489 static char msg[512];
3490 int *pack_fds = NULL;
3492 err = got_repo_pack_fds_open(&pack_fds);
3493 if (err)
3494 return err;
3496 err = got_repo_open(&repo, path, NULL, pack_fds);
3497 if (err)
3498 return orig_err;
3500 snprintf(msg, sizeof(msg),
3501 "'got %s' needs a work tree in addition to a git repository\n"
3502 "Work trees can be checked out from this Git repository with "
3503 "'got checkout'.\n"
3504 "The got(1) manual page contains more information.", cmdname);
3505 err = got_error_msg(GOT_ERR_NOT_WORKTREE, msg);
3506 if (repo) {
3507 const struct got_error *close_err = got_repo_close(repo);
3508 if (err == NULL)
3509 err = close_err;
3511 if (pack_fds) {
3512 const struct got_error *pack_err =
3513 got_repo_pack_fds_close(pack_fds);
3514 if (err == NULL)
3515 err = pack_err;
3517 return err;
3520 static const struct got_error *
3521 cmd_update(int argc, char *argv[])
3523 const struct got_error *close_err, *error = NULL;
3524 struct got_repository *repo = NULL;
3525 struct got_worktree *worktree = NULL;
3526 char *worktree_path = NULL;
3527 struct got_object_id *commit_id = NULL;
3528 char *commit_id_str = NULL;
3529 const char *branch_name = NULL;
3530 struct got_reference *head_ref = NULL;
3531 struct got_pathlist_head paths;
3532 struct got_pathlist_entry *pe;
3533 int ch, verbosity = 0;
3534 struct got_update_progress_arg upa;
3535 int *pack_fds = NULL;
3537 TAILQ_INIT(&paths);
3539 #ifndef PROFILE
3540 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
3541 "unveil", NULL) == -1)
3542 err(1, "pledge");
3543 #endif
3545 while ((ch = getopt(argc, argv, "b:c:q")) != -1) {
3546 switch (ch) {
3547 case 'b':
3548 branch_name = optarg;
3549 break;
3550 case 'c':
3551 commit_id_str = strdup(optarg);
3552 if (commit_id_str == NULL)
3553 return got_error_from_errno("strdup");
3554 break;
3555 case 'q':
3556 verbosity = -1;
3557 break;
3558 default:
3559 usage_update();
3560 /* NOTREACHED */
3564 argc -= optind;
3565 argv += optind;
3567 worktree_path = getcwd(NULL, 0);
3568 if (worktree_path == NULL) {
3569 error = got_error_from_errno("getcwd");
3570 goto done;
3573 error = got_repo_pack_fds_open(&pack_fds);
3574 if (error != NULL)
3575 goto done;
3577 error = got_worktree_open(&worktree, worktree_path,
3578 GOT_WORKTREE_GOT_DIR);
3579 if (error) {
3580 if (error->code == GOT_ERR_NOT_WORKTREE)
3581 error = wrap_not_worktree_error(error, "update",
3582 worktree_path);
3583 goto done;
3586 error = check_rebase_or_histedit_in_progress(worktree);
3587 if (error)
3588 goto done;
3590 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
3591 NULL, pack_fds);
3592 if (error != NULL)
3593 goto done;
3595 error = apply_unveil(got_repo_get_path(repo), 0,
3596 got_worktree_get_root_path(worktree));
3597 if (error)
3598 goto done;
3600 error = check_merge_in_progress(worktree, repo);
3601 if (error)
3602 goto done;
3604 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
3605 if (error)
3606 goto done;
3608 error = got_ref_open(&head_ref, repo, branch_name ? branch_name :
3609 got_worktree_get_head_ref_name(worktree), 0);
3610 if (error != NULL)
3611 goto done;
3612 if (commit_id_str == NULL) {
3613 error = got_ref_resolve(&commit_id, repo, head_ref);
3614 if (error != NULL)
3615 goto done;
3616 error = got_object_id_str(&commit_id_str, commit_id);
3617 if (error != NULL)
3618 goto done;
3619 } else {
3620 struct got_reflist_head refs;
3621 char *keyword_idstr = NULL;
3623 TAILQ_INIT(&refs);
3625 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
3626 NULL);
3627 if (error)
3628 goto done;
3630 error = got_keyword_to_idstr(&keyword_idstr, commit_id_str,
3631 repo, worktree);
3632 if (error != NULL)
3633 goto done;
3634 if (keyword_idstr != NULL) {
3635 free(commit_id_str);
3636 commit_id_str = keyword_idstr;
3639 error = got_repo_match_object_id(&commit_id, NULL,
3640 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
3641 got_ref_list_free(&refs);
3642 free(commit_id_str);
3643 commit_id_str = NULL;
3644 if (error)
3645 goto done;
3646 error = got_object_id_str(&commit_id_str, commit_id);
3647 if (error)
3648 goto done;
3651 if (branch_name) {
3652 struct got_object_id *head_commit_id;
3653 TAILQ_FOREACH(pe, &paths, entry) {
3654 if (pe->path_len == 0)
3655 continue;
3656 error = got_error_msg(GOT_ERR_BAD_PATH,
3657 "switching between branches requires that "
3658 "the entire work tree gets updated");
3659 goto done;
3661 error = got_ref_resolve(&head_commit_id, repo, head_ref);
3662 if (error)
3663 goto done;
3664 error = check_linear_ancestry(commit_id, head_commit_id, 0,
3665 repo);
3666 free(head_commit_id);
3667 if (error != NULL)
3668 goto done;
3669 error = check_same_branch(commit_id, head_ref, repo);
3670 if (error)
3671 goto done;
3672 error = switch_head_ref(head_ref, commit_id, worktree, repo);
3673 if (error)
3674 goto done;
3675 } else {
3676 error = check_linear_ancestry(commit_id,
3677 got_worktree_get_base_commit_id(worktree), 0, repo);
3678 if (error != NULL) {
3679 if (error->code == GOT_ERR_ANCESTRY)
3680 error = got_error(GOT_ERR_BRANCH_MOVED);
3681 goto done;
3683 error = check_same_branch(commit_id, head_ref, repo);
3684 if (error)
3685 goto done;
3688 if (got_object_id_cmp(got_worktree_get_base_commit_id(worktree),
3689 commit_id) != 0) {
3690 error = got_worktree_set_base_commit_id(worktree, repo,
3691 commit_id);
3692 if (error)
3693 goto done;
3696 memset(&upa, 0, sizeof(upa));
3697 upa.verbosity = verbosity;
3698 error = got_worktree_checkout_files(worktree, &paths, repo,
3699 update_progress, &upa, check_cancelled, NULL);
3700 if (error != NULL)
3701 goto done;
3703 if (upa.did_something) {
3704 printf("Updated to %s: %s\n",
3705 got_worktree_get_head_ref_name(worktree), commit_id_str);
3706 } else
3707 printf("Already up-to-date\n");
3709 print_update_progress_stats(&upa);
3710 done:
3711 if (pack_fds) {
3712 const struct got_error *pack_err =
3713 got_repo_pack_fds_close(pack_fds);
3714 if (error == NULL)
3715 error = pack_err;
3717 if (repo) {
3718 close_err = got_repo_close(repo);
3719 if (error == NULL)
3720 error = close_err;
3722 if (worktree != NULL) {
3723 close_err = got_worktree_close(worktree);
3724 if (error == NULL)
3725 error = close_err;
3727 if (head_ref != NULL)
3728 got_ref_close(head_ref);
3729 free(worktree_path);
3730 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
3731 free(commit_id);
3732 free(commit_id_str);
3733 return error;
3736 static const struct got_error *
3737 diff_blobs(struct got_object_id *blob_id1, struct got_object_id *blob_id2,
3738 const char *path, int diff_context, int ignore_whitespace,
3739 int force_text_diff, struct got_diffstat_cb_arg *dsa,
3740 struct got_repository *repo, FILE *outfile)
3742 const struct got_error *err = NULL;
3743 struct got_blob_object *blob1 = NULL, *blob2 = NULL;
3744 FILE *f1 = NULL, *f2 = NULL;
3745 int fd1 = -1, fd2 = -1;
3747 fd1 = got_opentempfd();
3748 if (fd1 == -1)
3749 return got_error_from_errno("got_opentempfd");
3750 fd2 = got_opentempfd();
3751 if (fd2 == -1) {
3752 err = got_error_from_errno("got_opentempfd");
3753 goto done;
3756 if (blob_id1) {
3757 err = got_object_open_as_blob(&blob1, repo, blob_id1, 8192,
3758 fd1);
3759 if (err)
3760 goto done;
3763 err = got_object_open_as_blob(&blob2, repo, blob_id2, 8192, fd2);
3764 if (err)
3765 goto done;
3767 f1 = got_opentemp();
3768 if (f1 == NULL) {
3769 err = got_error_from_errno("got_opentemp");
3770 goto done;
3772 f2 = got_opentemp();
3773 if (f2 == NULL) {
3774 err = got_error_from_errno("got_opentemp");
3775 goto done;
3778 while (path[0] == '/')
3779 path++;
3780 err = got_diff_blob(NULL, NULL, blob1, blob2, f1, f2, path, path,
3781 GOT_DIFF_ALGORITHM_PATIENCE, diff_context, ignore_whitespace,
3782 force_text_diff, dsa, outfile);
3783 done:
3784 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
3785 err = got_error_from_errno("close");
3786 if (blob1)
3787 got_object_blob_close(blob1);
3788 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
3789 err = got_error_from_errno("close");
3790 if (blob2)
3791 got_object_blob_close(blob2);
3792 if (f1 && fclose(f1) == EOF && err == NULL)
3793 err = got_error_from_errno("fclose");
3794 if (f2 && fclose(f2) == EOF && err == NULL)
3795 err = got_error_from_errno("fclose");
3796 return err;
3799 static const struct got_error *
3800 diff_trees(struct got_object_id *tree_id1, struct got_object_id *tree_id2,
3801 const char *path, int diff_context, int ignore_whitespace,
3802 int force_text_diff, struct got_diffstat_cb_arg *dsa,
3803 struct got_repository *repo, FILE *outfile)
3805 const struct got_error *err = NULL;
3806 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
3807 struct got_diff_blob_output_unidiff_arg arg;
3808 FILE *f1 = NULL, *f2 = NULL;
3809 int fd1 = -1, fd2 = -1;
3811 if (tree_id1) {
3812 err = got_object_open_as_tree(&tree1, repo, tree_id1);
3813 if (err)
3814 goto done;
3815 fd1 = got_opentempfd();
3816 if (fd1 == -1) {
3817 err = got_error_from_errno("got_opentempfd");
3818 goto done;
3822 err = got_object_open_as_tree(&tree2, repo, tree_id2);
3823 if (err)
3824 goto done;
3826 f1 = got_opentemp();
3827 if (f1 == NULL) {
3828 err = got_error_from_errno("got_opentemp");
3829 goto done;
3832 f2 = got_opentemp();
3833 if (f2 == NULL) {
3834 err = got_error_from_errno("got_opentemp");
3835 goto done;
3837 fd2 = got_opentempfd();
3838 if (fd2 == -1) {
3839 err = got_error_from_errno("got_opentempfd");
3840 goto done;
3842 arg.diff_context = diff_context;
3843 arg.ignore_whitespace = ignore_whitespace;
3844 arg.force_text_diff = force_text_diff;
3845 arg.diffstat = dsa;
3846 arg.diff_algo = GOT_DIFF_ALGORITHM_PATIENCE;
3847 arg.outfile = outfile;
3848 arg.lines = NULL;
3849 arg.nlines = 0;
3850 while (path[0] == '/')
3851 path++;
3852 err = got_diff_tree(tree1, tree2, f1, f2, fd1, fd2, path, path, repo,
3853 got_diff_blob_output_unidiff, &arg, 1);
3854 done:
3855 if (tree1)
3856 got_object_tree_close(tree1);
3857 if (tree2)
3858 got_object_tree_close(tree2);
3859 if (f1 && fclose(f1) == EOF && err == NULL)
3860 err = got_error_from_errno("fclose");
3861 if (f2 && fclose(f2) == EOF && err == NULL)
3862 err = got_error_from_errno("fclose");
3863 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
3864 err = got_error_from_errno("close");
3865 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
3866 err = got_error_from_errno("close");
3867 return err;
3870 static const struct got_error *
3871 get_changed_paths(struct got_pathlist_head *paths,
3872 struct got_commit_object *commit, struct got_repository *repo,
3873 struct got_diffstat_cb_arg *dsa)
3875 const struct got_error *err = NULL;
3876 struct got_object_id *tree_id1 = NULL, *tree_id2 = NULL;
3877 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
3878 struct got_object_qid *qid;
3879 got_diff_blob_cb cb = got_diff_tree_collect_changed_paths;
3880 FILE *f1 = NULL, *f2 = NULL;
3881 int fd1 = -1, fd2 = -1;
3883 if (dsa) {
3884 cb = got_diff_tree_compute_diffstat;
3886 f1 = got_opentemp();
3887 if (f1 == NULL) {
3888 err = got_error_from_errno("got_opentemp");
3889 goto done;
3891 f2 = got_opentemp();
3892 if (f2 == NULL) {
3893 err = got_error_from_errno("got_opentemp");
3894 goto done;
3896 fd1 = got_opentempfd();
3897 if (fd1 == -1) {
3898 err = got_error_from_errno("got_opentempfd");
3899 goto done;
3901 fd2 = got_opentempfd();
3902 if (fd2 == -1) {
3903 err = got_error_from_errno("got_opentempfd");
3904 goto done;
3908 qid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
3909 if (qid != NULL) {
3910 struct got_commit_object *pcommit;
3911 err = got_object_open_as_commit(&pcommit, repo,
3912 &qid->id);
3913 if (err)
3914 return err;
3916 tree_id1 = got_object_id_dup(
3917 got_object_commit_get_tree_id(pcommit));
3918 if (tree_id1 == NULL) {
3919 got_object_commit_close(pcommit);
3920 return got_error_from_errno("got_object_id_dup");
3922 got_object_commit_close(pcommit);
3926 if (tree_id1) {
3927 err = got_object_open_as_tree(&tree1, repo, tree_id1);
3928 if (err)
3929 goto done;
3932 tree_id2 = got_object_commit_get_tree_id(commit);
3933 err = got_object_open_as_tree(&tree2, repo, tree_id2);
3934 if (err)
3935 goto done;
3937 err = got_diff_tree(tree1, tree2, f1, f2, fd1, fd2, "", "", repo,
3938 cb, dsa ? (void *)dsa : paths, dsa ? 1 : 0);
3939 done:
3940 if (tree1)
3941 got_object_tree_close(tree1);
3942 if (tree2)
3943 got_object_tree_close(tree2);
3944 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
3945 err = got_error_from_errno("close");
3946 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
3947 err = got_error_from_errno("close");
3948 if (f1 && fclose(f1) == EOF && err == NULL)
3949 err = got_error_from_errno("fclose");
3950 if (f2 && fclose(f2) == EOF && err == NULL)
3951 err = got_error_from_errno("fclose");
3952 free(tree_id1);
3953 return err;
3956 static const struct got_error *
3957 print_patch(struct got_commit_object *commit, struct got_object_id *id,
3958 const char *path, int diff_context, struct got_diffstat_cb_arg *dsa,
3959 struct got_repository *repo, FILE *outfile)
3961 const struct got_error *err = NULL;
3962 struct got_commit_object *pcommit = NULL;
3963 char *id_str1 = NULL, *id_str2 = NULL;
3964 struct got_object_id *obj_id1 = NULL, *obj_id2 = NULL;
3965 struct got_object_qid *qid;
3967 qid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
3968 if (qid != NULL) {
3969 err = got_object_open_as_commit(&pcommit, repo,
3970 &qid->id);
3971 if (err)
3972 return err;
3973 err = got_object_id_str(&id_str1, &qid->id);
3974 if (err)
3975 goto done;
3978 err = got_object_id_str(&id_str2, id);
3979 if (err)
3980 goto done;
3982 if (path && path[0] != '\0') {
3983 int obj_type;
3984 err = got_object_id_by_path(&obj_id2, repo, commit, path);
3985 if (err)
3986 goto done;
3987 if (pcommit) {
3988 err = got_object_id_by_path(&obj_id1, repo,
3989 pcommit, path);
3990 if (err) {
3991 if (err->code != GOT_ERR_NO_TREE_ENTRY) {
3992 free(obj_id2);
3993 goto done;
3997 err = got_object_get_type(&obj_type, repo, obj_id2);
3998 if (err) {
3999 free(obj_id2);
4000 goto done;
4002 fprintf(outfile,
4003 "diff %s %s\n", id_str1 ? id_str1 : "/dev/null", id_str2);
4004 fprintf(outfile, "commit - %s\n",
4005 id_str1 ? id_str1 : "/dev/null");
4006 fprintf(outfile, "commit + %s\n", id_str2);
4007 switch (obj_type) {
4008 case GOT_OBJ_TYPE_BLOB:
4009 err = diff_blobs(obj_id1, obj_id2, path, diff_context,
4010 0, 0, dsa, repo, outfile);
4011 break;
4012 case GOT_OBJ_TYPE_TREE:
4013 err = diff_trees(obj_id1, obj_id2, path, diff_context,
4014 0, 0, dsa, repo, outfile);
4015 break;
4016 default:
4017 err = got_error(GOT_ERR_OBJ_TYPE);
4018 break;
4020 free(obj_id1);
4021 free(obj_id2);
4022 } else {
4023 obj_id2 = got_object_commit_get_tree_id(commit);
4024 if (pcommit)
4025 obj_id1 = got_object_commit_get_tree_id(pcommit);
4026 fprintf(outfile,
4027 "diff %s %s\n", id_str1 ? id_str1 : "/dev/null", id_str2);
4028 fprintf(outfile, "commit - %s\n",
4029 id_str1 ? id_str1 : "/dev/null");
4030 fprintf(outfile, "commit + %s\n", id_str2);
4031 err = diff_trees(obj_id1, obj_id2, "", diff_context, 0, 0,
4032 dsa, repo, outfile);
4034 done:
4035 free(id_str1);
4036 free(id_str2);
4037 if (pcommit)
4038 got_object_commit_close(pcommit);
4039 return err;
4042 static char *
4043 get_datestr(time_t *time, char *datebuf)
4045 struct tm mytm, *tm;
4046 char *p, *s;
4048 tm = gmtime_r(time, &mytm);
4049 if (tm == NULL)
4050 return NULL;
4051 s = asctime_r(tm, datebuf);
4052 if (s == NULL)
4053 return NULL;
4054 p = strchr(s, '\n');
4055 if (p)
4056 *p = '\0';
4057 return s;
4060 static const struct got_error *
4061 match_commit(int *have_match, struct got_object_id *id,
4062 struct got_commit_object *commit, regex_t *regex)
4064 const struct got_error *err = NULL;
4065 regmatch_t regmatch;
4066 char *id_str = NULL, *logmsg = NULL;
4068 *have_match = 0;
4070 err = got_object_id_str(&id_str, id);
4071 if (err)
4072 return err;
4074 err = got_object_commit_get_logmsg(&logmsg, commit);
4075 if (err)
4076 goto done;
4078 if (regexec(regex, got_object_commit_get_author(commit), 1,
4079 &regmatch, 0) == 0 ||
4080 regexec(regex, got_object_commit_get_committer(commit), 1,
4081 &regmatch, 0) == 0 ||
4082 regexec(regex, id_str, 1, &regmatch, 0) == 0 ||
4083 regexec(regex, logmsg, 1, &regmatch, 0) == 0)
4084 *have_match = 1;
4085 done:
4086 free(id_str);
4087 free(logmsg);
4088 return err;
4091 static void
4092 match_changed_paths(int *have_match, struct got_pathlist_head *changed_paths,
4093 regex_t *regex)
4095 regmatch_t regmatch;
4096 struct got_pathlist_entry *pe;
4098 *have_match = 0;
4100 TAILQ_FOREACH(pe, changed_paths, entry) {
4101 if (regexec(regex, pe->path, 1, &regmatch, 0) == 0) {
4102 *have_match = 1;
4103 break;
4108 static const struct got_error *
4109 match_patch(int *have_match, struct got_commit_object *commit,
4110 struct got_object_id *id, const char *path, int diff_context,
4111 struct got_repository *repo, regex_t *regex, FILE *f)
4113 const struct got_error *err = NULL;
4114 char *line = NULL;
4115 size_t linesize = 0;
4116 regmatch_t regmatch;
4118 *have_match = 0;
4120 err = got_opentemp_truncate(f);
4121 if (err)
4122 return err;
4124 err = print_patch(commit, id, path, diff_context, NULL, repo, f);
4125 if (err)
4126 goto done;
4128 if (fseeko(f, 0L, SEEK_SET) == -1) {
4129 err = got_error_from_errno("fseeko");
4130 goto done;
4133 while (getline(&line, &linesize, f) != -1) {
4134 if (regexec(regex, line, 1, &regmatch, 0) == 0) {
4135 *have_match = 1;
4136 break;
4139 done:
4140 free(line);
4141 return err;
4144 #define GOT_COMMIT_SEP_STR "-----------------------------------------------\n"
4146 static const struct got_error*
4147 build_refs_str(char **refs_str, struct got_reflist_head *refs,
4148 struct got_object_id *id, struct got_repository *repo,
4149 int local_only)
4151 static const struct got_error *err = NULL;
4152 struct got_reflist_entry *re;
4153 char *s;
4154 const char *name;
4156 *refs_str = NULL;
4158 TAILQ_FOREACH(re, refs, entry) {
4159 struct got_tag_object *tag = NULL;
4160 struct got_object_id *ref_id;
4161 int cmp;
4163 name = got_ref_get_name(re->ref);
4164 if (strcmp(name, GOT_REF_HEAD) == 0)
4165 continue;
4166 if (strncmp(name, "refs/", 5) == 0)
4167 name += 5;
4168 if (strncmp(name, "got/", 4) == 0)
4169 continue;
4170 if (strncmp(name, "heads/", 6) == 0)
4171 name += 6;
4172 if (strncmp(name, "remotes/", 8) == 0) {
4173 if (local_only)
4174 continue;
4175 name += 8;
4176 s = strstr(name, "/" GOT_REF_HEAD);
4177 if (s != NULL && strcmp(s, "/" GOT_REF_HEAD) == 0)
4178 continue;
4180 err = got_ref_resolve(&ref_id, repo, re->ref);
4181 if (err)
4182 break;
4183 if (strncmp(name, "tags/", 5) == 0) {
4184 err = got_object_open_as_tag(&tag, repo, ref_id);
4185 if (err) {
4186 if (err->code != GOT_ERR_OBJ_TYPE) {
4187 free(ref_id);
4188 break;
4190 /* Ref points at something other than a tag. */
4191 err = NULL;
4192 tag = NULL;
4195 cmp = got_object_id_cmp(tag ?
4196 got_object_tag_get_object_id(tag) : ref_id, id);
4197 free(ref_id);
4198 if (tag)
4199 got_object_tag_close(tag);
4200 if (cmp != 0)
4201 continue;
4202 s = *refs_str;
4203 if (asprintf(refs_str, "%s%s%s", s ? s : "",
4204 s ? ", " : "", name) == -1) {
4205 err = got_error_from_errno("asprintf");
4206 free(s);
4207 *refs_str = NULL;
4208 break;
4210 free(s);
4213 return err;
4216 static const struct got_error *
4217 print_commit_oneline(struct got_commit_object *commit, struct got_object_id *id,
4218 struct got_repository *repo, struct got_reflist_object_id_map *refs_idmap)
4220 const struct got_error *err = NULL;
4221 char *ref_str = NULL, *id_str = NULL, *logmsg0 = NULL;
4222 char *comma, *s, *nl;
4223 struct got_reflist_head *refs;
4224 char datebuf[12]; /* YYYY-MM-DD + SPACE + NUL */
4225 struct tm tm;
4226 time_t committer_time;
4228 refs = got_reflist_object_id_map_lookup(refs_idmap, id);
4229 if (refs) {
4230 err = build_refs_str(&ref_str, refs, id, repo, 1);
4231 if (err)
4232 return err;
4234 /* Display the first matching ref only. */
4235 if (ref_str && (comma = strchr(ref_str, ',')) != NULL)
4236 *comma = '\0';
4239 if (ref_str == NULL) {
4240 err = got_object_id_str(&id_str, id);
4241 if (err)
4242 return err;
4245 committer_time = got_object_commit_get_committer_time(commit);
4246 if (gmtime_r(&committer_time, &tm) == NULL) {
4247 err = got_error_from_errno("gmtime_r");
4248 goto done;
4250 if (strftime(datebuf, sizeof(datebuf), "%G-%m-%d ", &tm) == 0) {
4251 err = got_error(GOT_ERR_NO_SPACE);
4252 goto done;
4255 err = got_object_commit_get_logmsg(&logmsg0, commit);
4256 if (err)
4257 goto done;
4259 s = logmsg0;
4260 while (isspace((unsigned char)s[0]))
4261 s++;
4263 nl = strchr(s, '\n');
4264 if (nl) {
4265 *nl = '\0';
4268 if (ref_str)
4269 printf("%s%-7s %s\n", datebuf, ref_str, s);
4270 else
4271 printf("%s%.7s %s\n", datebuf, id_str, s);
4273 if (fflush(stdout) != 0 && err == NULL)
4274 err = got_error_from_errno("fflush");
4275 done:
4276 free(id_str);
4277 free(ref_str);
4278 free(logmsg0);
4279 return err;
4282 static const struct got_error *
4283 print_diffstat(struct got_diffstat_cb_arg *dsa, const char *header)
4285 struct got_pathlist_entry *pe;
4287 if (header != NULL)
4288 printf("%s\n", header);
4290 TAILQ_FOREACH(pe, dsa->paths, entry) {
4291 struct got_diff_changed_path *cp = pe->data;
4292 int pad = dsa->max_path_len - pe->path_len + 1;
4294 printf(" %c %s%*c | %*d+ %*d-\n", cp->status, pe->path, pad,
4295 ' ', dsa->add_cols + 1, cp->add, dsa->rm_cols + 1, cp->rm);
4297 printf("\n%d file%s changed, %d insertion%s(+), %d deletion%s(-)\n\n",
4298 dsa->nfiles, dsa->nfiles > 1 ? "s" : "", dsa->ins,
4299 dsa->ins != 1 ? "s" : "", dsa->del, dsa->del != 1 ? "s" : "");
4301 if (fflush(stdout) != 0)
4302 return got_error_from_errno("fflush");
4304 return NULL;
4307 static const struct got_error *
4308 printfile(FILE *f)
4310 char buf[8192];
4311 size_t r;
4313 if (fseeko(f, 0L, SEEK_SET) == -1)
4314 return got_error_from_errno("fseek");
4316 for (;;) {
4317 r = fread(buf, 1, sizeof(buf), f);
4318 if (r == 0) {
4319 if (ferror(f))
4320 return got_error_from_errno("fread");
4321 if (feof(f))
4322 break;
4324 if (fwrite(buf, 1, r, stdout) != r)
4325 return got_ferror(stdout, GOT_ERR_IO);
4328 return NULL;
4331 static const struct got_error *
4332 print_commit(struct got_commit_object *commit, struct got_object_id *id,
4333 struct got_repository *repo, const char *path,
4334 struct got_pathlist_head *changed_paths,
4335 struct got_diffstat_cb_arg *diffstat, int show_patch, int diff_context,
4336 struct got_reflist_object_id_map *refs_idmap, const char *custom_refs_str,
4337 const char *prefix)
4339 const struct got_error *err = NULL;
4340 FILE *f = NULL;
4341 char *id_str, *datestr, *logmsg0, *logmsg, *line;
4342 char datebuf[26];
4343 time_t committer_time;
4344 const char *author, *committer;
4345 char *refs_str = NULL;
4347 err = got_object_id_str(&id_str, id);
4348 if (err)
4349 return err;
4351 if (custom_refs_str == NULL) {
4352 struct got_reflist_head *refs;
4353 refs = got_reflist_object_id_map_lookup(refs_idmap, id);
4354 if (refs) {
4355 err = build_refs_str(&refs_str, refs, id, repo, 0);
4356 if (err)
4357 goto done;
4361 printf(GOT_COMMIT_SEP_STR);
4362 if (custom_refs_str)
4363 printf("%s %s (%s)\n", prefix ? prefix : "commit", id_str,
4364 custom_refs_str);
4365 else
4366 printf("%s %s%s%s%s\n", prefix ? prefix : "commit", id_str,
4367 refs_str ? " (" : "", refs_str ? refs_str : "",
4368 refs_str ? ")" : "");
4369 free(id_str);
4370 id_str = NULL;
4371 free(refs_str);
4372 refs_str = NULL;
4373 printf("from: %s\n", got_object_commit_get_author(commit));
4374 author = got_object_commit_get_author(commit);
4375 committer = got_object_commit_get_committer(commit);
4376 if (strcmp(author, committer) != 0)
4377 printf("via: %s\n", committer);
4378 committer_time = got_object_commit_get_committer_time(commit);
4379 datestr = get_datestr(&committer_time, datebuf);
4380 if (datestr)
4381 printf("date: %s UTC\n", datestr);
4382 if (got_object_commit_get_nparents(commit) > 1) {
4383 const struct got_object_id_queue *parent_ids;
4384 struct got_object_qid *qid;
4385 int n = 1;
4386 parent_ids = got_object_commit_get_parent_ids(commit);
4387 STAILQ_FOREACH(qid, parent_ids, entry) {
4388 err = got_object_id_str(&id_str, &qid->id);
4389 if (err)
4390 goto done;
4391 printf("parent %d: %s\n", n++, id_str);
4392 free(id_str);
4393 id_str = NULL;
4397 err = got_object_commit_get_logmsg(&logmsg0, commit);
4398 if (err)
4399 goto done;
4401 logmsg = logmsg0;
4402 do {
4403 line = strsep(&logmsg, "\n");
4404 if (line)
4405 printf(" %s\n", line);
4406 } while (line);
4407 free(logmsg0);
4409 if (changed_paths && diffstat == NULL) {
4410 struct got_pathlist_entry *pe;
4412 TAILQ_FOREACH(pe, changed_paths, entry) {
4413 struct got_diff_changed_path *cp = pe->data;
4415 printf(" %c %s\n", cp->status, pe->path);
4417 printf("\n");
4419 if (show_patch) {
4420 if (diffstat) {
4421 f = got_opentemp();
4422 if (f == NULL) {
4423 err = got_error_from_errno("got_opentemp");
4424 goto done;
4428 err = print_patch(commit, id, path, diff_context, diffstat,
4429 repo, diffstat == NULL ? stdout : f);
4430 if (err)
4431 goto done;
4433 if (diffstat) {
4434 err = print_diffstat(diffstat, NULL);
4435 if (err)
4436 goto done;
4437 if (show_patch) {
4438 err = printfile(f);
4439 if (err)
4440 goto done;
4443 if (show_patch)
4444 printf("\n");
4446 if (fflush(stdout) != 0 && err == NULL)
4447 err = got_error_from_errno("fflush");
4448 done:
4449 if (f && fclose(f) == EOF && err == NULL)
4450 err = got_error_from_errno("fclose");
4451 free(id_str);
4452 free(refs_str);
4453 return err;
4456 static const struct got_error *
4457 print_commits(struct got_object_id *root_id, struct got_object_id *end_id,
4458 struct got_repository *repo, const char *path, int show_changed_paths,
4459 int show_diffstat, int show_patch, const char *search_pattern,
4460 int diff_context, int limit, int log_branches, int reverse_display_order,
4461 struct got_reflist_object_id_map *refs_idmap, int one_line, int toposort,
4462 FILE *tmpfile)
4464 const struct got_error *err;
4465 struct got_commit_graph *graph;
4466 regex_t regex;
4467 int have_match;
4468 struct got_object_id_queue reversed_commits;
4469 struct got_object_qid *qid;
4470 struct got_commit_object *commit;
4471 struct got_pathlist_head changed_paths;
4473 STAILQ_INIT(&reversed_commits);
4474 TAILQ_INIT(&changed_paths);
4476 if (search_pattern && regcomp(&regex, search_pattern,
4477 REG_EXTENDED | REG_NOSUB | REG_NEWLINE))
4478 return got_error_msg(GOT_ERR_REGEX, search_pattern);
4480 err = got_commit_graph_open(&graph, path, !log_branches);
4481 if (err)
4482 return err;
4483 if (log_branches && toposort) {
4484 err = got_commit_graph_toposort(graph, root_id, repo,
4485 check_cancelled, NULL);
4486 } else {
4487 err = got_commit_graph_iter_start(graph, root_id, repo,
4488 check_cancelled, NULL);
4490 if (err)
4491 goto done;
4492 for (;;) {
4493 struct got_object_id id;
4494 struct got_diffstat_cb_arg dsa = { 0, 0, 0, 0, 0, 0,
4495 &changed_paths, 0, 0, GOT_DIFF_ALGORITHM_PATIENCE };
4497 if (sigint_received || sigpipe_received)
4498 break;
4500 err = got_commit_graph_iter_next(&id, graph, repo,
4501 check_cancelled, NULL);
4502 if (err) {
4503 if (err->code == GOT_ERR_ITER_COMPLETED)
4504 err = NULL;
4505 break;
4508 err = got_object_open_as_commit(&commit, repo, &id);
4509 if (err)
4510 break;
4512 if (((show_changed_paths && !show_diffstat) ||
4513 (show_diffstat && !show_patch))
4514 && !reverse_display_order) {
4515 err = get_changed_paths(&changed_paths, commit, repo,
4516 show_diffstat ? &dsa : NULL);
4517 if (err)
4518 break;
4521 if (search_pattern) {
4522 err = match_commit(&have_match, &id, commit, &regex);
4523 if (err) {
4524 got_object_commit_close(commit);
4525 break;
4527 if (have_match == 0 && show_changed_paths)
4528 match_changed_paths(&have_match,
4529 &changed_paths, &regex);
4530 if (have_match == 0 && show_patch) {
4531 err = match_patch(&have_match, commit, &id,
4532 path, diff_context, repo, &regex, tmpfile);
4533 if (err)
4534 break;
4536 if (have_match == 0) {
4537 got_object_commit_close(commit);
4538 got_pathlist_free(&changed_paths,
4539 GOT_PATHLIST_FREE_ALL);
4540 continue;
4544 if (reverse_display_order) {
4545 err = got_object_qid_alloc(&qid, &id);
4546 if (err)
4547 break;
4548 STAILQ_INSERT_HEAD(&reversed_commits, qid, entry);
4549 got_object_commit_close(commit);
4550 } else {
4551 if (one_line)
4552 err = print_commit_oneline(commit, &id,
4553 repo, refs_idmap);
4554 else
4555 err = print_commit(commit, &id, repo, path,
4556 (show_changed_paths || show_diffstat) ?
4557 &changed_paths : NULL,
4558 show_diffstat ? &dsa : NULL, show_patch,
4559 diff_context, refs_idmap, NULL, NULL);
4560 got_object_commit_close(commit);
4561 if (err)
4562 break;
4564 if ((limit && --limit == 0) ||
4565 (end_id && got_object_id_cmp(&id, end_id) == 0))
4566 break;
4568 got_pathlist_free(&changed_paths, GOT_PATHLIST_FREE_ALL);
4570 if (reverse_display_order) {
4571 STAILQ_FOREACH(qid, &reversed_commits, entry) {
4572 struct got_diffstat_cb_arg dsa = { 0, 0, 0, 0, 0, 0,
4573 &changed_paths, 0, 0, GOT_DIFF_ALGORITHM_PATIENCE };
4575 err = got_object_open_as_commit(&commit, repo,
4576 &qid->id);
4577 if (err)
4578 break;
4579 if ((show_changed_paths && !show_diffstat) ||
4580 (show_diffstat && !show_patch)) {
4581 err = get_changed_paths(&changed_paths, commit,
4582 repo, show_diffstat ? &dsa : NULL);
4583 if (err)
4584 break;
4586 if (one_line)
4587 err = print_commit_oneline(commit, &qid->id,
4588 repo, refs_idmap);
4589 else
4590 err = print_commit(commit, &qid->id, repo, path,
4591 (show_changed_paths || show_diffstat) ?
4592 &changed_paths : NULL,
4593 show_diffstat ? &dsa : NULL, show_patch,
4594 diff_context, refs_idmap, NULL, NULL);
4595 got_object_commit_close(commit);
4596 if (err)
4597 break;
4598 got_pathlist_free(&changed_paths, GOT_PATHLIST_FREE_ALL);
4601 done:
4602 while (!STAILQ_EMPTY(&reversed_commits)) {
4603 qid = STAILQ_FIRST(&reversed_commits);
4604 STAILQ_REMOVE_HEAD(&reversed_commits, entry);
4605 got_object_qid_free(qid);
4607 got_pathlist_free(&changed_paths, GOT_PATHLIST_FREE_ALL);
4608 if (search_pattern)
4609 regfree(&regex);
4610 got_commit_graph_close(graph);
4611 return err;
4614 __dead static void
4615 usage_log(void)
4617 fprintf(stderr, "usage: %s log [-bdPpRst] [-C number] [-c commit] "
4618 "[-l N] [-r repository-path] [-S search-pattern] [-x commit] "
4619 "[path]\n", getprogname());
4620 exit(1);
4623 static int
4624 get_default_log_limit(void)
4626 const char *got_default_log_limit;
4627 long long n;
4628 const char *errstr;
4630 got_default_log_limit = getenv("GOT_LOG_DEFAULT_LIMIT");
4631 if (got_default_log_limit == NULL)
4632 return 0;
4633 n = strtonum(got_default_log_limit, 0, INT_MAX, &errstr);
4634 if (errstr != NULL)
4635 return 0;
4636 return n;
4639 static const struct got_error *
4640 cmd_log(int argc, char *argv[])
4642 const struct got_error *error;
4643 struct got_repository *repo = NULL;
4644 struct got_worktree *worktree = NULL;
4645 struct got_object_id *start_id = NULL, *end_id = NULL;
4646 char *repo_path = NULL, *path = NULL, *cwd = NULL, *in_repo_path = NULL;
4647 char *keyword_idstr = NULL;
4648 const char *start_commit = NULL, *end_commit = NULL;
4649 const char *search_pattern = NULL;
4650 int diff_context = -1, ch;
4651 int show_changed_paths = 0, show_patch = 0, limit = 0, log_branches = 0;
4652 int show_diffstat = 0, reverse_display_order = 0, one_line = 0;
4653 int toposort = 0;
4654 const char *errstr;
4655 struct got_reflist_head refs;
4656 struct got_reflist_object_id_map *refs_idmap = NULL;
4657 FILE *tmpfile = NULL;
4658 int *pack_fds = NULL;
4660 TAILQ_INIT(&refs);
4662 #ifndef PROFILE
4663 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
4664 NULL)
4665 == -1)
4666 err(1, "pledge");
4667 #endif
4669 limit = get_default_log_limit();
4671 while ((ch = getopt(argc, argv, "bC:c:dl:PpRr:S:stx:")) != -1) {
4672 switch (ch) {
4673 case 'b':
4674 log_branches = 1;
4675 break;
4676 case 'C':
4677 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
4678 &errstr);
4679 if (errstr != NULL)
4680 errx(1, "number of context lines is %s: %s",
4681 errstr, optarg);
4682 break;
4683 case 'c':
4684 start_commit = optarg;
4685 break;
4686 case 'd':
4687 show_diffstat = 1;
4688 break;
4689 case 'l':
4690 limit = strtonum(optarg, 0, INT_MAX, &errstr);
4691 if (errstr != NULL)
4692 errx(1, "number of commits is %s: %s",
4693 errstr, optarg);
4694 break;
4695 case 'P':
4696 show_changed_paths = 1;
4697 break;
4698 case 'p':
4699 show_patch = 1;
4700 break;
4701 case 'R':
4702 reverse_display_order = 1;
4703 break;
4704 case 'r':
4705 repo_path = realpath(optarg, NULL);
4706 if (repo_path == NULL)
4707 return got_error_from_errno2("realpath",
4708 optarg);
4709 got_path_strip_trailing_slashes(repo_path);
4710 break;
4711 case 'S':
4712 search_pattern = optarg;
4713 break;
4714 case 's':
4715 one_line = 1;
4716 break;
4717 case 't':
4718 toposort = 1;
4719 break;
4720 case 'x':
4721 end_commit = optarg;
4722 break;
4723 default:
4724 usage_log();
4725 /* NOTREACHED */
4729 argc -= optind;
4730 argv += optind;
4732 if (diff_context == -1)
4733 diff_context = 3;
4734 else if (!show_patch)
4735 errx(1, "-C requires -p");
4737 if (one_line && (show_patch || show_changed_paths || show_diffstat))
4738 errx(1, "cannot use -s with -d, -p or -P");
4740 cwd = getcwd(NULL, 0);
4741 if (cwd == NULL) {
4742 error = got_error_from_errno("getcwd");
4743 goto done;
4746 error = got_repo_pack_fds_open(&pack_fds);
4747 if (error != NULL)
4748 goto done;
4750 if (repo_path == NULL) {
4751 error = got_worktree_open(&worktree, cwd,
4752 GOT_WORKTREE_GOT_DIR);
4753 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4754 goto done;
4755 error = NULL;
4758 if (argc == 1) {
4759 if (worktree) {
4760 error = got_worktree_resolve_path(&path, worktree,
4761 argv[0]);
4762 if (error)
4763 goto done;
4764 } else {
4765 path = strdup(argv[0]);
4766 if (path == NULL) {
4767 error = got_error_from_errno("strdup");
4768 goto done;
4771 } else if (argc != 0)
4772 usage_log();
4774 if (repo_path == NULL) {
4775 repo_path = worktree ?
4776 strdup(got_worktree_get_repo_path(worktree)) : strdup(cwd);
4778 if (repo_path == NULL) {
4779 error = got_error_from_errno("strdup");
4780 goto done;
4783 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
4784 if (error != NULL)
4785 goto done;
4787 error = apply_unveil(got_repo_get_path(repo), 1,
4788 worktree ? got_worktree_get_root_path(worktree) : NULL);
4789 if (error)
4790 goto done;
4792 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
4793 if (error)
4794 goto done;
4796 error = got_reflist_object_id_map_create(&refs_idmap, &refs, repo);
4797 if (error)
4798 goto done;
4800 if (start_commit == NULL) {
4801 struct got_reference *head_ref;
4802 struct got_commit_object *commit = NULL;
4803 error = got_ref_open(&head_ref, repo,
4804 worktree ? got_worktree_get_head_ref_name(worktree)
4805 : GOT_REF_HEAD, 0);
4806 if (error != NULL)
4807 goto done;
4808 error = got_ref_resolve(&start_id, repo, head_ref);
4809 got_ref_close(head_ref);
4810 if (error != NULL)
4811 goto done;
4812 error = got_object_open_as_commit(&commit, repo,
4813 start_id);
4814 if (error != NULL)
4815 goto done;
4816 got_object_commit_close(commit);
4817 } else {
4818 error = got_keyword_to_idstr(&keyword_idstr, start_commit,
4819 repo, worktree);
4820 if (error != NULL)
4821 goto done;
4822 if (keyword_idstr != NULL)
4823 start_commit = keyword_idstr;
4825 error = got_repo_match_object_id(&start_id, NULL,
4826 start_commit, GOT_OBJ_TYPE_COMMIT, &refs, repo);
4827 if (error != NULL)
4828 goto done;
4830 if (end_commit != NULL) {
4831 error = got_keyword_to_idstr(&keyword_idstr, end_commit,
4832 repo, worktree);
4833 if (error != NULL)
4834 goto done;
4835 if (keyword_idstr != NULL)
4836 end_commit = keyword_idstr;
4838 error = got_repo_match_object_id(&end_id, NULL,
4839 end_commit, GOT_OBJ_TYPE_COMMIT, &refs, repo);
4840 if (error != NULL)
4841 goto done;
4844 if (worktree) {
4846 * If a path was specified on the command line it was resolved
4847 * to a path in the work tree above. Prepend the work tree's
4848 * path prefix to obtain the corresponding in-repository path.
4850 if (path) {
4851 const char *prefix;
4852 prefix = got_worktree_get_path_prefix(worktree);
4853 if (asprintf(&in_repo_path, "%s%s%s", prefix,
4854 (path[0] != '\0') ? "/" : "", path) == -1) {
4855 error = got_error_from_errno("asprintf");
4856 goto done;
4859 } else
4860 error = got_repo_map_path(&in_repo_path, repo,
4861 path ? path : "");
4862 if (error != NULL)
4863 goto done;
4864 if (in_repo_path) {
4865 free(path);
4866 path = in_repo_path;
4869 if (worktree) {
4870 /* Release work tree lock. */
4871 got_worktree_close(worktree);
4872 worktree = NULL;
4875 if (search_pattern && show_patch) {
4876 tmpfile = got_opentemp();
4877 if (tmpfile == NULL) {
4878 error = got_error_from_errno("got_opentemp");
4879 goto done;
4883 error = print_commits(start_id, end_id, repo, path ? path : "",
4884 show_changed_paths, show_diffstat, show_patch, search_pattern,
4885 diff_context, limit, log_branches, reverse_display_order,
4886 refs_idmap, one_line, toposort, tmpfile);
4887 done:
4888 free(path);
4889 free(repo_path);
4890 free(cwd);
4891 free(start_id);
4892 free(end_id);
4893 free(keyword_idstr);
4894 if (worktree)
4895 got_worktree_close(worktree);
4896 if (repo) {
4897 const struct got_error *close_err = got_repo_close(repo);
4898 if (error == NULL)
4899 error = close_err;
4901 if (pack_fds) {
4902 const struct got_error *pack_err =
4903 got_repo_pack_fds_close(pack_fds);
4904 if (error == NULL)
4905 error = pack_err;
4907 if (refs_idmap)
4908 got_reflist_object_id_map_free(refs_idmap);
4909 if (tmpfile && fclose(tmpfile) == EOF && error == NULL)
4910 error = got_error_from_errno("fclose");
4911 got_ref_list_free(&refs);
4912 return error;
4915 __dead static void
4916 usage_diff(void)
4918 fprintf(stderr, "usage: %s diff [-adPsw] [-C number] [-c commit] "
4919 "[-r repository-path] [object1 object2 | path ...]\n",
4920 getprogname());
4921 exit(1);
4924 struct print_diff_arg {
4925 struct got_repository *repo;
4926 struct got_worktree *worktree;
4927 struct got_diffstat_cb_arg *diffstat;
4928 int diff_context;
4929 const char *id_str;
4930 int header_shown;
4931 int diff_staged;
4932 enum got_diff_algorithm diff_algo;
4933 int ignore_whitespace;
4934 int force_text_diff;
4935 FILE *f1;
4936 FILE *f2;
4937 FILE *outfile;
4941 * Create a file which contains the target path of a symlink so we can feed
4942 * it as content to the diff engine.
4944 static const struct got_error *
4945 get_symlink_target_file(int *fd, int dirfd, const char *de_name,
4946 const char *abspath)
4948 const struct got_error *err = NULL;
4949 char target_path[PATH_MAX];
4950 ssize_t target_len, outlen;
4952 *fd = -1;
4954 if (dirfd != -1) {
4955 target_len = readlinkat(dirfd, de_name, target_path, PATH_MAX);
4956 if (target_len == -1)
4957 return got_error_from_errno2("readlinkat", abspath);
4958 } else {
4959 target_len = readlink(abspath, target_path, PATH_MAX);
4960 if (target_len == -1)
4961 return got_error_from_errno2("readlink", abspath);
4964 *fd = got_opentempfd();
4965 if (*fd == -1)
4966 return got_error_from_errno("got_opentempfd");
4968 outlen = write(*fd, target_path, target_len);
4969 if (outlen == -1) {
4970 err = got_error_from_errno("got_opentempfd");
4971 goto done;
4974 if (lseek(*fd, 0, SEEK_SET) == -1) {
4975 err = got_error_from_errno2("lseek", abspath);
4976 goto done;
4978 done:
4979 if (err) {
4980 close(*fd);
4981 *fd = -1;
4983 return err;
4986 static const struct got_error *
4987 print_diff(void *arg, unsigned char status, unsigned char staged_status,
4988 const char *path, struct got_object_id *blob_id,
4989 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
4990 int dirfd, const char *de_name)
4992 struct print_diff_arg *a = arg;
4993 const struct got_error *err = NULL;
4994 struct got_blob_object *blob1 = NULL;
4995 int fd = -1, fd1 = -1, fd2 = -1;
4996 FILE *f2 = NULL;
4997 char *abspath = NULL, *label1 = NULL;
4998 struct stat sb;
4999 off_t size1 = 0;
5000 int f2_exists = 0;
5002 memset(&sb, 0, sizeof(sb));
5004 if (a->diff_staged) {
5005 if (staged_status != GOT_STATUS_MODIFY &&
5006 staged_status != GOT_STATUS_ADD &&
5007 staged_status != GOT_STATUS_DELETE)
5008 return NULL;
5009 } else {
5010 if (staged_status == GOT_STATUS_DELETE)
5011 return NULL;
5012 if (status == GOT_STATUS_NONEXISTENT)
5013 return got_error_set_errno(ENOENT, path);
5014 if (status != GOT_STATUS_MODIFY &&
5015 status != GOT_STATUS_ADD &&
5016 status != GOT_STATUS_DELETE &&
5017 status != GOT_STATUS_CONFLICT)
5018 return NULL;
5021 err = got_opentemp_truncate(a->f1);
5022 if (err)
5023 return got_error_from_errno("got_opentemp_truncate");
5024 err = got_opentemp_truncate(a->f2);
5025 if (err)
5026 return got_error_from_errno("got_opentemp_truncate");
5028 if (!a->header_shown) {
5029 if (fprintf(a->outfile, "diff %s%s\n",
5030 a->diff_staged ? "-s " : "",
5031 got_worktree_get_root_path(a->worktree)) < 0) {
5032 err = got_error_from_errno("fprintf");
5033 goto done;
5035 if (fprintf(a->outfile, "commit - %s\n", a->id_str) < 0) {
5036 err = got_error_from_errno("fprintf");
5037 goto done;
5039 if (fprintf(a->outfile, "path + %s%s\n",
5040 got_worktree_get_root_path(a->worktree),
5041 a->diff_staged ? " (staged changes)" : "") < 0) {
5042 err = got_error_from_errno("fprintf");
5043 goto done;
5045 a->header_shown = 1;
5048 if (a->diff_staged) {
5049 const char *label1 = NULL, *label2 = NULL;
5050 switch (staged_status) {
5051 case GOT_STATUS_MODIFY:
5052 label1 = path;
5053 label2 = path;
5054 break;
5055 case GOT_STATUS_ADD:
5056 label2 = path;
5057 break;
5058 case GOT_STATUS_DELETE:
5059 label1 = path;
5060 break;
5061 default:
5062 return got_error(GOT_ERR_FILE_STATUS);
5064 fd1 = got_opentempfd();
5065 if (fd1 == -1) {
5066 err = got_error_from_errno("got_opentempfd");
5067 goto done;
5069 fd2 = got_opentempfd();
5070 if (fd2 == -1) {
5071 err = got_error_from_errno("got_opentempfd");
5072 goto done;
5074 err = got_diff_objects_as_blobs(NULL, NULL, a->f1, a->f2,
5075 fd1, fd2, blob_id, staged_blob_id, label1, label2,
5076 a->diff_algo, a->diff_context, a->ignore_whitespace,
5077 a->force_text_diff, a->diffstat, a->repo, a->outfile);
5078 goto done;
5081 fd1 = got_opentempfd();
5082 if (fd1 == -1) {
5083 err = got_error_from_errno("got_opentempfd");
5084 goto done;
5087 if (staged_status == GOT_STATUS_ADD ||
5088 staged_status == GOT_STATUS_MODIFY) {
5089 char *id_str;
5090 err = got_object_open_as_blob(&blob1, a->repo, staged_blob_id,
5091 8192, fd1);
5092 if (err)
5093 goto done;
5094 err = got_object_id_str(&id_str, staged_blob_id);
5095 if (err)
5096 goto done;
5097 if (asprintf(&label1, "%s (staged)", id_str) == -1) {
5098 err = got_error_from_errno("asprintf");
5099 free(id_str);
5100 goto done;
5102 free(id_str);
5103 } else if (status != GOT_STATUS_ADD) {
5104 err = got_object_open_as_blob(&blob1, a->repo, blob_id, 8192,
5105 fd1);
5106 if (err)
5107 goto done;
5110 if (status != GOT_STATUS_DELETE) {
5111 if (asprintf(&abspath, "%s/%s",
5112 got_worktree_get_root_path(a->worktree), path) == -1) {
5113 err = got_error_from_errno("asprintf");
5114 goto done;
5117 if (dirfd != -1) {
5118 fd = openat(dirfd, de_name,
5119 O_RDONLY | O_NOFOLLOW | O_CLOEXEC);
5120 if (fd == -1) {
5121 if (!got_err_open_nofollow_on_symlink()) {
5122 err = got_error_from_errno2("openat",
5123 abspath);
5124 goto done;
5126 err = get_symlink_target_file(&fd, dirfd,
5127 de_name, abspath);
5128 if (err)
5129 goto done;
5131 } else {
5132 fd = open(abspath, O_RDONLY | O_NOFOLLOW | O_CLOEXEC);
5133 if (fd == -1) {
5134 if (!got_err_open_nofollow_on_symlink()) {
5135 err = got_error_from_errno2("open",
5136 abspath);
5137 goto done;
5139 err = get_symlink_target_file(&fd, dirfd,
5140 de_name, abspath);
5141 if (err)
5142 goto done;
5145 if (fstatat(fd, abspath, &sb, AT_SYMLINK_NOFOLLOW) == -1) {
5146 err = got_error_from_errno2("fstatat", abspath);
5147 goto done;
5149 f2 = fdopen(fd, "r");
5150 if (f2 == NULL) {
5151 err = got_error_from_errno2("fdopen", abspath);
5152 goto done;
5154 fd = -1;
5155 f2_exists = 1;
5158 if (blob1) {
5159 err = got_object_blob_dump_to_file(&size1, NULL, NULL,
5160 a->f1, blob1);
5161 if (err)
5162 goto done;
5165 err = got_diff_blob_file(blob1, a->f1, size1, label1, f2 ? f2 : a->f2,
5166 f2_exists, &sb, path, GOT_DIFF_ALGORITHM_PATIENCE, a->diff_context,
5167 a->ignore_whitespace, a->force_text_diff, a->diffstat, a->outfile);
5168 done:
5169 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
5170 err = got_error_from_errno("close");
5171 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
5172 err = got_error_from_errno("close");
5173 if (blob1)
5174 got_object_blob_close(blob1);
5175 if (fd != -1 && close(fd) == -1 && err == NULL)
5176 err = got_error_from_errno("close");
5177 if (f2 && fclose(f2) == EOF && err == NULL)
5178 err = got_error_from_errno("fclose");
5179 free(abspath);
5180 return err;
5183 static const struct got_error *
5184 cmd_diff(int argc, char *argv[])
5186 const struct got_error *error;
5187 struct got_repository *repo = NULL;
5188 struct got_worktree *worktree = NULL;
5189 char *cwd = NULL, *repo_path = NULL;
5190 const char *commit_args[2] = { NULL, NULL };
5191 int ncommit_args = 0;
5192 struct got_object_id *ids[2] = { NULL, NULL };
5193 char *labels[2] = { NULL, NULL };
5194 int type1 = GOT_OBJ_TYPE_ANY, type2 = GOT_OBJ_TYPE_ANY;
5195 int diff_context = 3, diff_staged = 0, ignore_whitespace = 0, ch, i;
5196 int force_text_diff = 0, force_path = 0, rflag = 0, show_diffstat = 0;
5197 const char *errstr;
5198 struct got_reflist_head refs;
5199 struct got_pathlist_head diffstat_paths, paths;
5200 FILE *f1 = NULL, *f2 = NULL, *outfile = NULL;
5201 int fd1 = -1, fd2 = -1;
5202 int *pack_fds = NULL;
5203 struct got_diffstat_cb_arg dsa;
5205 memset(&dsa, 0, sizeof(dsa));
5207 TAILQ_INIT(&refs);
5208 TAILQ_INIT(&paths);
5209 TAILQ_INIT(&diffstat_paths);
5211 #ifndef PROFILE
5212 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
5213 NULL) == -1)
5214 err(1, "pledge");
5215 #endif
5217 while ((ch = getopt(argc, argv, "aC:c:dPr:sw")) != -1) {
5218 switch (ch) {
5219 case 'a':
5220 force_text_diff = 1;
5221 break;
5222 case 'C':
5223 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
5224 &errstr);
5225 if (errstr != NULL)
5226 errx(1, "number of context lines is %s: %s",
5227 errstr, optarg);
5228 break;
5229 case 'c':
5230 if (ncommit_args >= 2)
5231 errx(1, "too many -c options used");
5232 commit_args[ncommit_args++] = optarg;
5233 break;
5234 case 'd':
5235 show_diffstat = 1;
5236 break;
5237 case 'P':
5238 force_path = 1;
5239 break;
5240 case 'r':
5241 repo_path = realpath(optarg, NULL);
5242 if (repo_path == NULL)
5243 return got_error_from_errno2("realpath",
5244 optarg);
5245 got_path_strip_trailing_slashes(repo_path);
5246 rflag = 1;
5247 break;
5248 case 's':
5249 diff_staged = 1;
5250 break;
5251 case 'w':
5252 ignore_whitespace = 1;
5253 break;
5254 default:
5255 usage_diff();
5256 /* NOTREACHED */
5260 argc -= optind;
5261 argv += optind;
5263 cwd = getcwd(NULL, 0);
5264 if (cwd == NULL) {
5265 error = got_error_from_errno("getcwd");
5266 goto done;
5269 error = got_repo_pack_fds_open(&pack_fds);
5270 if (error != NULL)
5271 goto done;
5273 if (repo_path == NULL) {
5274 error = got_worktree_open(&worktree, cwd,
5275 GOT_WORKTREE_GOT_DIR);
5276 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5277 goto done;
5278 else
5279 error = NULL;
5280 if (worktree) {
5281 repo_path =
5282 strdup(got_worktree_get_repo_path(worktree));
5283 if (repo_path == NULL) {
5284 error = got_error_from_errno("strdup");
5285 goto done;
5287 } else {
5288 repo_path = strdup(cwd);
5289 if (repo_path == NULL) {
5290 error = got_error_from_errno("strdup");
5291 goto done;
5296 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
5297 free(repo_path);
5298 if (error != NULL)
5299 goto done;
5301 if (show_diffstat) {
5302 dsa.paths = &diffstat_paths;
5303 dsa.force_text = force_text_diff;
5304 dsa.ignore_ws = ignore_whitespace;
5305 dsa.diff_algo = GOT_DIFF_ALGORITHM_PATIENCE;
5308 if (rflag || worktree == NULL || ncommit_args > 0) {
5309 if (force_path) {
5310 error = got_error_msg(GOT_ERR_NOT_IMPL,
5311 "-P option can only be used when diffing "
5312 "a work tree");
5313 goto done;
5315 if (diff_staged) {
5316 error = got_error_msg(GOT_ERR_NOT_IMPL,
5317 "-s option can only be used when diffing "
5318 "a work tree");
5319 goto done;
5323 error = apply_unveil(got_repo_get_path(repo), 1,
5324 worktree ? got_worktree_get_root_path(worktree) : NULL);
5325 if (error)
5326 goto done;
5328 if ((!force_path && argc == 2) || ncommit_args > 0) {
5329 int obj_type = (ncommit_args > 0 ?
5330 GOT_OBJ_TYPE_COMMIT : GOT_OBJ_TYPE_ANY);
5331 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
5332 NULL);
5333 if (error)
5334 goto done;
5335 for (i = 0; i < (ncommit_args > 0 ? ncommit_args : argc); i++) {
5336 const char *arg;
5337 char *keyword_idstr = NULL;
5339 if (ncommit_args > 0)
5340 arg = commit_args[i];
5341 else
5342 arg = argv[i];
5344 error = got_keyword_to_idstr(&keyword_idstr, arg,
5345 repo, worktree);
5346 if (error != NULL)
5347 goto done;
5348 if (keyword_idstr != NULL)
5349 arg = keyword_idstr;
5351 error = got_repo_match_object_id(&ids[i], &labels[i],
5352 arg, obj_type, &refs, repo);
5353 free(keyword_idstr);
5354 if (error) {
5355 if (error->code != GOT_ERR_NOT_REF &&
5356 error->code != GOT_ERR_NO_OBJ)
5357 goto done;
5358 if (ncommit_args > 0)
5359 goto done;
5360 error = NULL;
5361 break;
5366 f1 = got_opentemp();
5367 if (f1 == NULL) {
5368 error = got_error_from_errno("got_opentemp");
5369 goto done;
5372 f2 = got_opentemp();
5373 if (f2 == NULL) {
5374 error = got_error_from_errno("got_opentemp");
5375 goto done;
5378 outfile = got_opentemp();
5379 if (outfile == NULL) {
5380 error = got_error_from_errno("got_opentemp");
5381 goto done;
5384 if (ncommit_args == 0 && (ids[0] == NULL || ids[1] == NULL)) {
5385 struct print_diff_arg arg;
5386 char *id_str;
5388 if (worktree == NULL) {
5389 if (argc == 2 && ids[0] == NULL) {
5390 error = got_error_path(argv[0], GOT_ERR_NO_OBJ);
5391 goto done;
5392 } else if (argc == 2 && ids[1] == NULL) {
5393 error = got_error_path(argv[1], GOT_ERR_NO_OBJ);
5394 goto done;
5395 } else if (argc > 0) {
5396 error = got_error_fmt(GOT_ERR_NOT_WORKTREE,
5397 "%s", "specified paths cannot be resolved");
5398 goto done;
5399 } else {
5400 error = got_error(GOT_ERR_NOT_WORKTREE);
5401 goto done;
5405 error = get_worktree_paths_from_argv(&paths, argc, argv,
5406 worktree);
5407 if (error)
5408 goto done;
5410 error = got_object_id_str(&id_str,
5411 got_worktree_get_base_commit_id(worktree));
5412 if (error)
5413 goto done;
5414 arg.repo = repo;
5415 arg.worktree = worktree;
5416 arg.diff_algo = GOT_DIFF_ALGORITHM_PATIENCE;
5417 arg.diff_context = diff_context;
5418 arg.id_str = id_str;
5419 arg.header_shown = 0;
5420 arg.diff_staged = diff_staged;
5421 arg.ignore_whitespace = ignore_whitespace;
5422 arg.force_text_diff = force_text_diff;
5423 arg.diffstat = show_diffstat ? &dsa : NULL;
5424 arg.f1 = f1;
5425 arg.f2 = f2;
5426 arg.outfile = outfile;
5428 error = got_worktree_status(worktree, &paths, repo, 0,
5429 print_diff, &arg, check_cancelled, NULL);
5430 free(id_str);
5431 if (error)
5432 goto done;
5434 if (show_diffstat && dsa.nfiles > 0) {
5435 char *header;
5437 if (asprintf(&header, "diffstat %s%s",
5438 diff_staged ? "-s " : "",
5439 got_worktree_get_root_path(worktree)) == -1) {
5440 error = got_error_from_errno("asprintf");
5441 goto done;
5444 error = print_diffstat(&dsa, header);
5445 free(header);
5446 if (error)
5447 goto done;
5450 error = printfile(outfile);
5451 goto done;
5454 if (ncommit_args == 1) {
5455 struct got_commit_object *commit;
5456 error = got_object_open_as_commit(&commit, repo, ids[0]);
5457 if (error)
5458 goto done;
5460 labels[1] = labels[0];
5461 ids[1] = ids[0];
5462 if (got_object_commit_get_nparents(commit) > 0) {
5463 const struct got_object_id_queue *pids;
5464 struct got_object_qid *pid;
5465 pids = got_object_commit_get_parent_ids(commit);
5466 pid = STAILQ_FIRST(pids);
5467 ids[0] = got_object_id_dup(&pid->id);
5468 if (ids[0] == NULL) {
5469 error = got_error_from_errno(
5470 "got_object_id_dup");
5471 got_object_commit_close(commit);
5472 goto done;
5474 error = got_object_id_str(&labels[0], ids[0]);
5475 if (error) {
5476 got_object_commit_close(commit);
5477 goto done;
5479 } else {
5480 ids[0] = NULL;
5481 labels[0] = strdup("/dev/null");
5482 if (labels[0] == NULL) {
5483 error = got_error_from_errno("strdup");
5484 got_object_commit_close(commit);
5485 goto done;
5489 got_object_commit_close(commit);
5492 if (ncommit_args == 0 && argc > 2) {
5493 error = got_error_msg(GOT_ERR_BAD_PATH,
5494 "path arguments cannot be used when diffing two objects");
5495 goto done;
5498 if (ids[0]) {
5499 error = got_object_get_type(&type1, repo, ids[0]);
5500 if (error)
5501 goto done;
5504 error = got_object_get_type(&type2, repo, ids[1]);
5505 if (error)
5506 goto done;
5507 if (type1 != GOT_OBJ_TYPE_ANY && type1 != type2) {
5508 error = got_error(GOT_ERR_OBJ_TYPE);
5509 goto done;
5511 if (type1 == GOT_OBJ_TYPE_BLOB && argc > 2) {
5512 error = got_error_msg(GOT_ERR_OBJ_TYPE,
5513 "path arguments cannot be used when diffing blobs");
5514 goto done;
5517 for (i = 0; ncommit_args > 0 && i < argc; i++) {
5518 char *in_repo_path;
5519 struct got_pathlist_entry *new;
5520 if (worktree) {
5521 const char *prefix;
5522 char *p;
5523 error = got_worktree_resolve_path(&p, worktree,
5524 argv[i]);
5525 if (error)
5526 goto done;
5527 prefix = got_worktree_get_path_prefix(worktree);
5528 while (prefix[0] == '/')
5529 prefix++;
5530 if (asprintf(&in_repo_path, "%s%s%s", prefix,
5531 (p[0] != '\0' && prefix[0] != '\0') ? "/" : "",
5532 p) == -1) {
5533 error = got_error_from_errno("asprintf");
5534 free(p);
5535 goto done;
5537 free(p);
5538 } else {
5539 char *mapped_path, *s;
5540 error = got_repo_map_path(&mapped_path, repo, argv[i]);
5541 if (error)
5542 goto done;
5543 s = mapped_path;
5544 while (s[0] == '/')
5545 s++;
5546 in_repo_path = strdup(s);
5547 if (in_repo_path == NULL) {
5548 error = got_error_from_errno("asprintf");
5549 free(mapped_path);
5550 goto done;
5552 free(mapped_path);
5555 error = got_pathlist_insert(&new, &paths, in_repo_path, NULL);
5556 if (error || new == NULL /* duplicate */)
5557 free(in_repo_path);
5558 if (error)
5559 goto done;
5562 if (worktree) {
5563 /* Release work tree lock. */
5564 got_worktree_close(worktree);
5565 worktree = NULL;
5568 fd1 = got_opentempfd();
5569 if (fd1 == -1) {
5570 error = got_error_from_errno("got_opentempfd");
5571 goto done;
5574 fd2 = got_opentempfd();
5575 if (fd2 == -1) {
5576 error = got_error_from_errno("got_opentempfd");
5577 goto done;
5580 switch (type1 == GOT_OBJ_TYPE_ANY ? type2 : type1) {
5581 case GOT_OBJ_TYPE_BLOB:
5582 error = got_diff_objects_as_blobs(NULL, NULL, f1, f2,
5583 fd1, fd2, ids[0], ids[1], NULL, NULL,
5584 GOT_DIFF_ALGORITHM_PATIENCE, diff_context,
5585 ignore_whitespace, force_text_diff,
5586 show_diffstat ? &dsa : NULL, repo, outfile);
5587 break;
5588 case GOT_OBJ_TYPE_TREE:
5589 error = got_diff_objects_as_trees(NULL, NULL, f1, f2, fd1, fd2,
5590 ids[0], ids[1], &paths, "", "",
5591 GOT_DIFF_ALGORITHM_PATIENCE, diff_context,
5592 ignore_whitespace, force_text_diff,
5593 show_diffstat ? &dsa : NULL, repo, outfile);
5594 break;
5595 case GOT_OBJ_TYPE_COMMIT:
5596 fprintf(outfile, "diff %s %s\n", labels[0], labels[1]);
5597 error = got_diff_objects_as_commits(NULL, NULL, f1, f2,
5598 fd1, fd2, ids[0], ids[1], &paths,
5599 GOT_DIFF_ALGORITHM_PATIENCE, diff_context,
5600 ignore_whitespace, force_text_diff,
5601 show_diffstat ? &dsa : NULL, repo, outfile);
5602 break;
5603 default:
5604 error = got_error(GOT_ERR_OBJ_TYPE);
5606 if (error)
5607 goto done;
5609 if (show_diffstat && dsa.nfiles > 0) {
5610 char *header = NULL;
5612 if (asprintf(&header, "diffstat %s %s",
5613 labels[0], labels[1]) == -1) {
5614 error = got_error_from_errno("asprintf");
5615 goto done;
5618 error = print_diffstat(&dsa, header);
5619 free(header);
5620 if (error)
5621 goto done;
5624 error = printfile(outfile);
5626 done:
5627 free(labels[0]);
5628 free(labels[1]);
5629 free(ids[0]);
5630 free(ids[1]);
5631 if (worktree)
5632 got_worktree_close(worktree);
5633 if (repo) {
5634 const struct got_error *close_err = got_repo_close(repo);
5635 if (error == NULL)
5636 error = close_err;
5638 if (pack_fds) {
5639 const struct got_error *pack_err =
5640 got_repo_pack_fds_close(pack_fds);
5641 if (error == NULL)
5642 error = pack_err;
5644 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
5645 got_pathlist_free(&diffstat_paths, GOT_PATHLIST_FREE_ALL);
5646 got_ref_list_free(&refs);
5647 if (outfile && fclose(outfile) == EOF && error == NULL)
5648 error = got_error_from_errno("fclose");
5649 if (f1 && fclose(f1) == EOF && error == NULL)
5650 error = got_error_from_errno("fclose");
5651 if (f2 && fclose(f2) == EOF && error == NULL)
5652 error = got_error_from_errno("fclose");
5653 if (fd1 != -1 && close(fd1) == -1 && error == NULL)
5654 error = got_error_from_errno("close");
5655 if (fd2 != -1 && close(fd2) == -1 && error == NULL)
5656 error = got_error_from_errno("close");
5657 return error;
5660 __dead static void
5661 usage_blame(void)
5663 fprintf(stderr,
5664 "usage: %s blame [-c commit] [-r repository-path] path\n",
5665 getprogname());
5666 exit(1);
5669 struct blame_line {
5670 int annotated;
5671 char *id_str;
5672 char *committer;
5673 char datebuf[11]; /* YYYY-MM-DD + NUL */
5676 struct blame_cb_args {
5677 struct blame_line *lines;
5678 int nlines;
5679 int nlines_prec;
5680 int lineno_cur;
5681 off_t *line_offsets;
5682 FILE *f;
5683 struct got_repository *repo;
5686 static const struct got_error *
5687 blame_cb(void *arg, int nlines, int lineno,
5688 struct got_commit_object *commit, struct got_object_id *id)
5690 const struct got_error *err = NULL;
5691 struct blame_cb_args *a = arg;
5692 struct blame_line *bline;
5693 char *line = NULL;
5694 size_t linesize = 0;
5695 off_t offset;
5696 struct tm tm;
5697 time_t committer_time;
5699 if (nlines != a->nlines ||
5700 (lineno != -1 && lineno < 1) || lineno > a->nlines)
5701 return got_error(GOT_ERR_RANGE);
5703 if (sigint_received)
5704 return got_error(GOT_ERR_ITER_COMPLETED);
5706 if (lineno == -1)
5707 return NULL; /* no change in this commit */
5709 /* Annotate this line. */
5710 bline = &a->lines[lineno - 1];
5711 if (bline->annotated)
5712 return NULL;
5713 err = got_object_id_str(&bline->id_str, id);
5714 if (err)
5715 return err;
5717 bline->committer = strdup(got_object_commit_get_committer(commit));
5718 if (bline->committer == NULL) {
5719 err = got_error_from_errno("strdup");
5720 goto done;
5723 committer_time = got_object_commit_get_committer_time(commit);
5724 if (gmtime_r(&committer_time, &tm) == NULL)
5725 return got_error_from_errno("gmtime_r");
5726 if (strftime(bline->datebuf, sizeof(bline->datebuf), "%G-%m-%d",
5727 &tm) == 0) {
5728 err = got_error(GOT_ERR_NO_SPACE);
5729 goto done;
5731 bline->annotated = 1;
5733 /* Print lines annotated so far. */
5734 bline = &a->lines[a->lineno_cur - 1];
5735 if (!bline->annotated)
5736 goto done;
5738 offset = a->line_offsets[a->lineno_cur - 1];
5739 if (fseeko(a->f, offset, SEEK_SET) == -1) {
5740 err = got_error_from_errno("fseeko");
5741 goto done;
5744 while (a->lineno_cur <= a->nlines && bline->annotated) {
5745 char *smallerthan, *at, *nl, *committer;
5746 size_t len;
5748 if (getline(&line, &linesize, a->f) == -1) {
5749 if (ferror(a->f))
5750 err = got_error_from_errno("getline");
5751 break;
5754 committer = bline->committer;
5755 smallerthan = strchr(committer, '<');
5756 if (smallerthan && smallerthan[1] != '\0')
5757 committer = smallerthan + 1;
5758 at = strchr(committer, '@');
5759 if (at)
5760 *at = '\0';
5761 len = strlen(committer);
5762 if (len >= 9)
5763 committer[8] = '\0';
5765 nl = strchr(line, '\n');
5766 if (nl)
5767 *nl = '\0';
5768 printf("%.*d) %.8s %s %-8s %s\n", a->nlines_prec, a->lineno_cur,
5769 bline->id_str, bline->datebuf, committer, line);
5771 a->lineno_cur++;
5772 bline = &a->lines[a->lineno_cur - 1];
5774 done:
5775 free(line);
5776 return err;
5779 static const struct got_error *
5780 cmd_blame(int argc, char *argv[])
5782 const struct got_error *error;
5783 struct got_repository *repo = NULL;
5784 struct got_worktree *worktree = NULL;
5785 char *path, *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
5786 char *link_target = NULL;
5787 struct got_object_id *obj_id = NULL;
5788 struct got_object_id *commit_id = NULL;
5789 struct got_commit_object *commit = NULL;
5790 struct got_blob_object *blob = NULL;
5791 char *commit_id_str = NULL, *keyword_idstr = NULL;
5792 struct blame_cb_args bca;
5793 int ch, obj_type, i, fd1 = -1, fd2 = -1, fd3 = -1;
5794 off_t filesize;
5795 int *pack_fds = NULL;
5796 FILE *f1 = NULL, *f2 = NULL;
5798 fd1 = got_opentempfd();
5799 if (fd1 == -1)
5800 return got_error_from_errno("got_opentempfd");
5802 memset(&bca, 0, sizeof(bca));
5804 #ifndef PROFILE
5805 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
5806 NULL) == -1)
5807 err(1, "pledge");
5808 #endif
5810 while ((ch = getopt(argc, argv, "c:r:")) != -1) {
5811 switch (ch) {
5812 case 'c':
5813 commit_id_str = optarg;
5814 break;
5815 case 'r':
5816 repo_path = realpath(optarg, NULL);
5817 if (repo_path == NULL)
5818 return got_error_from_errno2("realpath",
5819 optarg);
5820 got_path_strip_trailing_slashes(repo_path);
5821 break;
5822 default:
5823 usage_blame();
5824 /* NOTREACHED */
5828 argc -= optind;
5829 argv += optind;
5831 if (argc == 1)
5832 path = argv[0];
5833 else
5834 usage_blame();
5836 cwd = getcwd(NULL, 0);
5837 if (cwd == NULL) {
5838 error = got_error_from_errno("getcwd");
5839 goto done;
5842 error = got_repo_pack_fds_open(&pack_fds);
5843 if (error != NULL)
5844 goto done;
5846 if (repo_path == NULL) {
5847 error = got_worktree_open(&worktree, cwd,
5848 GOT_WORKTREE_GOT_DIR);
5849 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5850 goto done;
5851 else
5852 error = NULL;
5853 if (worktree) {
5854 repo_path =
5855 strdup(got_worktree_get_repo_path(worktree));
5856 if (repo_path == NULL) {
5857 error = got_error_from_errno("strdup");
5858 if (error)
5859 goto done;
5861 } else {
5862 repo_path = strdup(cwd);
5863 if (repo_path == NULL) {
5864 error = got_error_from_errno("strdup");
5865 goto done;
5870 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
5871 if (error != NULL)
5872 goto done;
5874 if (worktree) {
5875 const char *prefix = got_worktree_get_path_prefix(worktree);
5876 char *p;
5878 error = got_worktree_resolve_path(&p, worktree, path);
5879 if (error)
5880 goto done;
5881 if (asprintf(&in_repo_path, "%s%s%s", prefix,
5882 (p[0] != '\0' && !got_path_is_root_dir(prefix)) ? "/" : "",
5883 p) == -1) {
5884 error = got_error_from_errno("asprintf");
5885 free(p);
5886 goto done;
5888 free(p);
5889 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5890 } else {
5891 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5892 if (error)
5893 goto done;
5894 error = got_repo_map_path(&in_repo_path, repo, path);
5896 if (error)
5897 goto done;
5899 if (commit_id_str == NULL) {
5900 struct got_reference *head_ref;
5901 error = got_ref_open(&head_ref, repo, worktree ?
5902 got_worktree_get_head_ref_name(worktree) : GOT_REF_HEAD, 0);
5903 if (error != NULL)
5904 goto done;
5905 error = got_ref_resolve(&commit_id, repo, head_ref);
5906 got_ref_close(head_ref);
5907 if (error != NULL)
5908 goto done;
5909 } else {
5910 struct got_reflist_head refs;
5912 TAILQ_INIT(&refs);
5913 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
5914 NULL);
5915 if (error)
5916 goto done;
5918 error = got_keyword_to_idstr(&keyword_idstr, commit_id_str,
5919 repo, worktree);
5920 if (error != NULL)
5921 goto done;
5922 if (keyword_idstr != NULL)
5923 commit_id_str = keyword_idstr;
5925 error = got_repo_match_object_id(&commit_id, NULL,
5926 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
5927 got_ref_list_free(&refs);
5928 if (error)
5929 goto done;
5932 if (worktree) {
5933 /* Release work tree lock. */
5934 got_worktree_close(worktree);
5935 worktree = NULL;
5938 error = got_object_open_as_commit(&commit, repo, commit_id);
5939 if (error)
5940 goto done;
5942 error = got_object_resolve_symlinks(&link_target, in_repo_path,
5943 commit, repo);
5944 if (error)
5945 goto done;
5947 error = got_object_id_by_path(&obj_id, repo, commit,
5948 link_target ? link_target : in_repo_path);
5949 if (error)
5950 goto done;
5952 error = got_object_get_type(&obj_type, repo, obj_id);
5953 if (error)
5954 goto done;
5956 if (obj_type != GOT_OBJ_TYPE_BLOB) {
5957 error = got_error_path(link_target ? link_target : in_repo_path,
5958 GOT_ERR_OBJ_TYPE);
5959 goto done;
5962 error = got_object_open_as_blob(&blob, repo, obj_id, 8192, fd1);
5963 if (error)
5964 goto done;
5965 bca.f = got_opentemp();
5966 if (bca.f == NULL) {
5967 error = got_error_from_errno("got_opentemp");
5968 goto done;
5970 error = got_object_blob_dump_to_file(&filesize, &bca.nlines,
5971 &bca.line_offsets, bca.f, blob);
5972 if (error || bca.nlines == 0)
5973 goto done;
5975 /* Don't include \n at EOF in the blame line count. */
5976 if (bca.line_offsets[bca.nlines - 1] == filesize)
5977 bca.nlines--;
5979 bca.lines = calloc(bca.nlines, sizeof(*bca.lines));
5980 if (bca.lines == NULL) {
5981 error = got_error_from_errno("calloc");
5982 goto done;
5984 bca.lineno_cur = 1;
5985 bca.nlines_prec = 0;
5986 i = bca.nlines;
5987 while (i > 0) {
5988 i /= 10;
5989 bca.nlines_prec++;
5991 bca.repo = repo;
5993 fd2 = got_opentempfd();
5994 if (fd2 == -1) {
5995 error = got_error_from_errno("got_opentempfd");
5996 goto done;
5998 fd3 = got_opentempfd();
5999 if (fd3 == -1) {
6000 error = got_error_from_errno("got_opentempfd");
6001 goto done;
6003 f1 = got_opentemp();
6004 if (f1 == NULL) {
6005 error = got_error_from_errno("got_opentemp");
6006 goto done;
6008 f2 = got_opentemp();
6009 if (f2 == NULL) {
6010 error = got_error_from_errno("got_opentemp");
6011 goto done;
6013 error = got_blame(link_target ? link_target : in_repo_path, commit_id,
6014 repo, GOT_DIFF_ALGORITHM_PATIENCE, blame_cb, &bca,
6015 check_cancelled, NULL, fd2, fd3, f1, f2);
6016 done:
6017 free(keyword_idstr);
6018 free(in_repo_path);
6019 free(link_target);
6020 free(repo_path);
6021 free(cwd);
6022 free(commit_id);
6023 free(obj_id);
6024 if (commit)
6025 got_object_commit_close(commit);
6027 if (fd1 != -1 && close(fd1) == -1 && error == NULL)
6028 error = got_error_from_errno("close");
6029 if (fd2 != -1 && close(fd2) == -1 && error == NULL)
6030 error = got_error_from_errno("close");
6031 if (fd3 != -1 && close(fd3) == -1 && error == NULL)
6032 error = got_error_from_errno("close");
6033 if (f1 && fclose(f1) == EOF && error == NULL)
6034 error = got_error_from_errno("fclose");
6035 if (f2 && fclose(f2) == EOF && error == NULL)
6036 error = got_error_from_errno("fclose");
6038 if (blob)
6039 got_object_blob_close(blob);
6040 if (worktree)
6041 got_worktree_close(worktree);
6042 if (repo) {
6043 const struct got_error *close_err = got_repo_close(repo);
6044 if (error == NULL)
6045 error = close_err;
6047 if (pack_fds) {
6048 const struct got_error *pack_err =
6049 got_repo_pack_fds_close(pack_fds);
6050 if (error == NULL)
6051 error = pack_err;
6053 if (bca.lines) {
6054 for (i = 0; i < bca.nlines; i++) {
6055 struct blame_line *bline = &bca.lines[i];
6056 free(bline->id_str);
6057 free(bline->committer);
6059 free(bca.lines);
6061 free(bca.line_offsets);
6062 if (bca.f && fclose(bca.f) == EOF && error == NULL)
6063 error = got_error_from_errno("fclose");
6064 return error;
6067 __dead static void
6068 usage_tree(void)
6070 fprintf(stderr, "usage: %s tree [-iR] [-c commit] [-r repository-path] "
6071 "[path]\n", getprogname());
6072 exit(1);
6075 static const struct got_error *
6076 print_entry(struct got_tree_entry *te, const char *id, const char *path,
6077 const char *root_path, struct got_repository *repo)
6079 const struct got_error *err = NULL;
6080 int is_root_path = (strcmp(path, root_path) == 0);
6081 const char *modestr = "";
6082 mode_t mode = got_tree_entry_get_mode(te);
6083 char *link_target = NULL;
6085 path += strlen(root_path);
6086 while (path[0] == '/')
6087 path++;
6089 if (got_object_tree_entry_is_submodule(te))
6090 modestr = "$";
6091 else if (S_ISLNK(mode)) {
6092 int i;
6094 err = got_tree_entry_get_symlink_target(&link_target, te, repo);
6095 if (err)
6096 return err;
6097 for (i = 0; link_target[i] != '\0'; i++) {
6098 if (!isprint((unsigned char)link_target[i]))
6099 link_target[i] = '?';
6102 modestr = "@";
6104 else if (S_ISDIR(mode))
6105 modestr = "/";
6106 else if (mode & S_IXUSR)
6107 modestr = "*";
6109 printf("%s%s%s%s%s%s%s\n", id ? id : "", path,
6110 is_root_path ? "" : "/", got_tree_entry_get_name(te), modestr,
6111 link_target ? " -> ": "", link_target ? link_target : "");
6113 free(link_target);
6114 return NULL;
6117 static const struct got_error *
6118 print_tree(const char *path, struct got_commit_object *commit,
6119 int show_ids, int recurse, const char *root_path,
6120 struct got_repository *repo)
6122 const struct got_error *err = NULL;
6123 struct got_object_id *tree_id = NULL;
6124 struct got_tree_object *tree = NULL;
6125 int nentries, i;
6127 err = got_object_id_by_path(&tree_id, repo, commit, path);
6128 if (err)
6129 goto done;
6131 err = got_object_open_as_tree(&tree, repo, tree_id);
6132 if (err)
6133 goto done;
6134 nentries = got_object_tree_get_nentries(tree);
6135 for (i = 0; i < nentries; i++) {
6136 struct got_tree_entry *te;
6137 char *id = NULL;
6139 if (sigint_received || sigpipe_received)
6140 break;
6142 te = got_object_tree_get_entry(tree, i);
6143 if (show_ids) {
6144 char *id_str;
6145 err = got_object_id_str(&id_str,
6146 got_tree_entry_get_id(te));
6147 if (err)
6148 goto done;
6149 if (asprintf(&id, "%s ", id_str) == -1) {
6150 err = got_error_from_errno("asprintf");
6151 free(id_str);
6152 goto done;
6154 free(id_str);
6156 err = print_entry(te, id, path, root_path, repo);
6157 free(id);
6158 if (err)
6159 goto done;
6161 if (recurse && S_ISDIR(got_tree_entry_get_mode(te))) {
6162 char *child_path;
6163 if (asprintf(&child_path, "%s%s%s", path,
6164 path[0] == '/' && path[1] == '\0' ? "" : "/",
6165 got_tree_entry_get_name(te)) == -1) {
6166 err = got_error_from_errno("asprintf");
6167 goto done;
6169 err = print_tree(child_path, commit, show_ids, 1,
6170 root_path, repo);
6171 free(child_path);
6172 if (err)
6173 goto done;
6176 done:
6177 if (tree)
6178 got_object_tree_close(tree);
6179 free(tree_id);
6180 return err;
6183 static const struct got_error *
6184 cmd_tree(int argc, char *argv[])
6186 const struct got_error *error;
6187 struct got_repository *repo = NULL;
6188 struct got_worktree *worktree = NULL;
6189 const char *path, *refname = NULL;
6190 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
6191 struct got_object_id *commit_id = NULL;
6192 struct got_commit_object *commit = NULL;
6193 char *commit_id_str = NULL, *keyword_idstr = NULL;
6194 int show_ids = 0, recurse = 0;
6195 int ch;
6196 int *pack_fds = NULL;
6198 #ifndef PROFILE
6199 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
6200 NULL) == -1)
6201 err(1, "pledge");
6202 #endif
6204 while ((ch = getopt(argc, argv, "c:iRr:")) != -1) {
6205 switch (ch) {
6206 case 'c':
6207 commit_id_str = optarg;
6208 break;
6209 case 'i':
6210 show_ids = 1;
6211 break;
6212 case 'R':
6213 recurse = 1;
6214 break;
6215 case 'r':
6216 repo_path = realpath(optarg, NULL);
6217 if (repo_path == NULL)
6218 return got_error_from_errno2("realpath",
6219 optarg);
6220 got_path_strip_trailing_slashes(repo_path);
6221 break;
6222 default:
6223 usage_tree();
6224 /* NOTREACHED */
6228 argc -= optind;
6229 argv += optind;
6231 if (argc == 1)
6232 path = argv[0];
6233 else if (argc > 1)
6234 usage_tree();
6235 else
6236 path = NULL;
6238 cwd = getcwd(NULL, 0);
6239 if (cwd == NULL) {
6240 error = got_error_from_errno("getcwd");
6241 goto done;
6244 error = got_repo_pack_fds_open(&pack_fds);
6245 if (error != NULL)
6246 goto done;
6248 if (repo_path == NULL) {
6249 error = got_worktree_open(&worktree, cwd,
6250 GOT_WORKTREE_GOT_DIR);
6251 if (error && error->code != GOT_ERR_NOT_WORKTREE)
6252 goto done;
6253 else
6254 error = NULL;
6255 if (worktree) {
6256 repo_path =
6257 strdup(got_worktree_get_repo_path(worktree));
6258 if (repo_path == NULL)
6259 error = got_error_from_errno("strdup");
6260 if (error)
6261 goto done;
6262 } else {
6263 repo_path = strdup(cwd);
6264 if (repo_path == NULL) {
6265 error = got_error_from_errno("strdup");
6266 goto done;
6271 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
6272 if (error != NULL)
6273 goto done;
6275 if (worktree) {
6276 const char *prefix = got_worktree_get_path_prefix(worktree);
6277 char *p;
6279 if (path == NULL || got_path_is_root_dir(path))
6280 path = "";
6281 error = got_worktree_resolve_path(&p, worktree, path);
6282 if (error)
6283 goto done;
6284 if (asprintf(&in_repo_path, "%s%s%s", prefix,
6285 (p[0] != '\0' && !got_path_is_root_dir(prefix)) ? "/" : "",
6286 p) == -1) {
6287 error = got_error_from_errno("asprintf");
6288 free(p);
6289 goto done;
6291 free(p);
6292 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
6293 if (error)
6294 goto done;
6295 } else {
6296 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
6297 if (error)
6298 goto done;
6299 if (path == NULL)
6300 path = "/";
6301 error = got_repo_map_path(&in_repo_path, repo, path);
6302 if (error != NULL)
6303 goto done;
6306 if (commit_id_str == NULL) {
6307 struct got_reference *head_ref;
6308 if (worktree)
6309 refname = got_worktree_get_head_ref_name(worktree);
6310 else
6311 refname = GOT_REF_HEAD;
6312 error = got_ref_open(&head_ref, repo, refname, 0);
6313 if (error != NULL)
6314 goto done;
6315 error = got_ref_resolve(&commit_id, repo, head_ref);
6316 got_ref_close(head_ref);
6317 if (error != NULL)
6318 goto done;
6319 } else {
6320 struct got_reflist_head refs;
6322 TAILQ_INIT(&refs);
6323 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
6324 NULL);
6325 if (error)
6326 goto done;
6328 error = got_keyword_to_idstr(&keyword_idstr, commit_id_str,
6329 repo, worktree);
6330 if (error != NULL)
6331 goto done;
6332 if (keyword_idstr != NULL)
6333 commit_id_str = keyword_idstr;
6335 error = got_repo_match_object_id(&commit_id, NULL,
6336 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
6337 got_ref_list_free(&refs);
6338 if (error)
6339 goto done;
6342 if (worktree) {
6343 /* Release work tree lock. */
6344 got_worktree_close(worktree);
6345 worktree = NULL;
6348 error = got_object_open_as_commit(&commit, repo, commit_id);
6349 if (error)
6350 goto done;
6352 error = print_tree(in_repo_path, commit, show_ids, recurse,
6353 in_repo_path, repo);
6354 done:
6355 free(keyword_idstr);
6356 free(in_repo_path);
6357 free(repo_path);
6358 free(cwd);
6359 free(commit_id);
6360 if (commit)
6361 got_object_commit_close(commit);
6362 if (worktree)
6363 got_worktree_close(worktree);
6364 if (repo) {
6365 const struct got_error *close_err = got_repo_close(repo);
6366 if (error == NULL)
6367 error = close_err;
6369 if (pack_fds) {
6370 const struct got_error *pack_err =
6371 got_repo_pack_fds_close(pack_fds);
6372 if (error == NULL)
6373 error = pack_err;
6375 return error;
6378 __dead static void
6379 usage_status(void)
6381 fprintf(stderr, "usage: %s status [-I] [-S status-codes] "
6382 "[-s status-codes] [path ...]\n", getprogname());
6383 exit(1);
6386 struct got_status_arg {
6387 char *status_codes;
6388 int suppress;
6391 static const struct got_error *
6392 print_status(void *arg, unsigned char status, unsigned char staged_status,
6393 const char *path, struct got_object_id *blob_id,
6394 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
6395 int dirfd, const char *de_name)
6397 struct got_status_arg *st = arg;
6399 if (status == staged_status && (status == GOT_STATUS_DELETE))
6400 status = GOT_STATUS_NO_CHANGE;
6401 if (st != NULL && st->status_codes) {
6402 size_t ncodes = strlen(st->status_codes);
6403 int i, j = 0;
6405 for (i = 0; i < ncodes ; i++) {
6406 if (st->suppress) {
6407 if (status == st->status_codes[i] ||
6408 staged_status == st->status_codes[i]) {
6409 j++;
6410 continue;
6412 } else {
6413 if (status == st->status_codes[i] ||
6414 staged_status == st->status_codes[i])
6415 break;
6419 if (st->suppress && j == 0)
6420 goto print;
6422 if (i == ncodes)
6423 return NULL;
6425 print:
6426 printf("%c%c %s\n", status, staged_status, path);
6427 return NULL;
6430 static const struct got_error *
6431 cmd_status(int argc, char *argv[])
6433 const struct got_error *close_err, *error = NULL;
6434 struct got_repository *repo = NULL;
6435 struct got_worktree *worktree = NULL;
6436 struct got_status_arg st;
6437 char *cwd = NULL;
6438 struct got_pathlist_head paths;
6439 int ch, i, no_ignores = 0;
6440 int *pack_fds = NULL;
6442 TAILQ_INIT(&paths);
6444 memset(&st, 0, sizeof(st));
6445 st.status_codes = NULL;
6446 st.suppress = 0;
6448 #ifndef PROFILE
6449 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
6450 NULL) == -1)
6451 err(1, "pledge");
6452 #endif
6454 while ((ch = getopt(argc, argv, "IS:s:")) != -1) {
6455 switch (ch) {
6456 case 'I':
6457 no_ignores = 1;
6458 break;
6459 case 'S':
6460 if (st.status_codes != NULL && st.suppress == 0)
6461 option_conflict('S', 's');
6462 st.suppress = 1;
6463 /* fallthrough */
6464 case 's':
6465 for (i = 0; optarg[i] != '\0'; i++) {
6466 switch (optarg[i]) {
6467 case GOT_STATUS_MODIFY:
6468 case GOT_STATUS_ADD:
6469 case GOT_STATUS_DELETE:
6470 case GOT_STATUS_CONFLICT:
6471 case GOT_STATUS_MISSING:
6472 case GOT_STATUS_OBSTRUCTED:
6473 case GOT_STATUS_UNVERSIONED:
6474 case GOT_STATUS_MODE_CHANGE:
6475 case GOT_STATUS_NONEXISTENT:
6476 break;
6477 default:
6478 errx(1, "invalid status code '%c'",
6479 optarg[i]);
6482 if (ch == 's' && st.suppress)
6483 option_conflict('s', 'S');
6484 st.status_codes = optarg;
6485 break;
6486 default:
6487 usage_status();
6488 /* NOTREACHED */
6492 argc -= optind;
6493 argv += optind;
6495 cwd = getcwd(NULL, 0);
6496 if (cwd == NULL) {
6497 error = got_error_from_errno("getcwd");
6498 goto done;
6501 error = got_repo_pack_fds_open(&pack_fds);
6502 if (error != NULL)
6503 goto done;
6505 error = got_worktree_open(&worktree, cwd,
6506 GOT_WORKTREE_GOT_DIR);
6507 if (error) {
6508 if (error->code == GOT_ERR_NOT_WORKTREE)
6509 error = wrap_not_worktree_error(error, "status", cwd);
6510 goto done;
6513 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
6514 NULL, pack_fds);
6515 if (error != NULL)
6516 goto done;
6518 error = apply_unveil(got_repo_get_path(repo), 1,
6519 got_worktree_get_root_path(worktree));
6520 if (error)
6521 goto done;
6523 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
6524 if (error)
6525 goto done;
6527 error = got_worktree_status(worktree, &paths, repo, no_ignores,
6528 print_status, &st, check_cancelled, NULL);
6529 done:
6530 if (pack_fds) {
6531 const struct got_error *pack_err =
6532 got_repo_pack_fds_close(pack_fds);
6533 if (error == NULL)
6534 error = pack_err;
6536 if (repo) {
6537 close_err = got_repo_close(repo);
6538 if (error == NULL)
6539 error = close_err;
6541 if (worktree != NULL) {
6542 close_err = got_worktree_close(worktree);
6543 if (error == NULL)
6544 error = close_err;
6547 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
6548 free(cwd);
6549 return error;
6552 __dead static void
6553 usage_ref(void)
6555 fprintf(stderr, "usage: %s ref [-dlt] [-c object] [-r repository-path] "
6556 "[-s reference] [name]\n", getprogname());
6557 exit(1);
6560 static const struct got_error *
6561 list_refs(struct got_repository *repo, const char *refname, int sort_by_time)
6563 static const struct got_error *err = NULL;
6564 struct got_reflist_head refs;
6565 struct got_reflist_entry *re;
6567 TAILQ_INIT(&refs);
6568 err = got_ref_list(&refs, repo, refname, sort_by_time ?
6569 got_ref_cmp_by_commit_timestamp_descending : got_ref_cmp_by_name,
6570 repo);
6571 if (err)
6572 return err;
6574 TAILQ_FOREACH(re, &refs, entry) {
6575 char *refstr;
6576 refstr = got_ref_to_str(re->ref);
6577 if (refstr == NULL) {
6578 err = got_error_from_errno("got_ref_to_str");
6579 break;
6581 printf("%s: %s\n", got_ref_get_name(re->ref), refstr);
6582 free(refstr);
6585 got_ref_list_free(&refs);
6586 return err;
6589 static const struct got_error *
6590 delete_ref_by_name(struct got_repository *repo, const char *refname)
6592 const struct got_error *err;
6593 struct got_reference *ref;
6595 err = got_ref_open(&ref, repo, refname, 0);
6596 if (err)
6597 return err;
6599 err = delete_ref(repo, ref);
6600 got_ref_close(ref);
6601 return err;
6604 static const struct got_error *
6605 add_ref(struct got_repository *repo, const char *refname, const char *target)
6607 const struct got_error *err = NULL;
6608 struct got_object_id *id = NULL;
6609 struct got_reference *ref = NULL;
6610 struct got_reflist_head refs;
6613 * Don't let the user create a reference name with a leading '-'.
6614 * While technically a valid reference name, this case is usually
6615 * an unintended typo.
6617 if (refname[0] == '-')
6618 return got_error_path(refname, GOT_ERR_REF_NAME_MINUS);
6620 TAILQ_INIT(&refs);
6621 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
6622 if (err)
6623 goto done;
6624 err = got_repo_match_object_id(&id, NULL, target, GOT_OBJ_TYPE_ANY,
6625 &refs, repo);
6626 got_ref_list_free(&refs);
6627 if (err)
6628 goto done;
6630 err = got_ref_alloc(&ref, refname, id);
6631 if (err)
6632 goto done;
6634 err = got_ref_write(ref, repo);
6635 done:
6636 if (ref)
6637 got_ref_close(ref);
6638 free(id);
6639 return err;
6642 static const struct got_error *
6643 add_symref(struct got_repository *repo, const char *refname, const char *target)
6645 const struct got_error *err = NULL;
6646 struct got_reference *ref = NULL;
6647 struct got_reference *target_ref = NULL;
6650 * Don't let the user create a reference name with a leading '-'.
6651 * While technically a valid reference name, this case is usually
6652 * an unintended typo.
6654 if (refname[0] == '-')
6655 return got_error_path(refname, GOT_ERR_REF_NAME_MINUS);
6657 err = got_ref_open(&target_ref, repo, target, 0);
6658 if (err)
6659 return err;
6661 err = got_ref_alloc_symref(&ref, refname, target_ref);
6662 if (err)
6663 goto done;
6665 err = got_ref_write(ref, repo);
6666 done:
6667 if (target_ref)
6668 got_ref_close(target_ref);
6669 if (ref)
6670 got_ref_close(ref);
6671 return err;
6674 static const struct got_error *
6675 cmd_ref(int argc, char *argv[])
6677 const struct got_error *error = NULL;
6678 struct got_repository *repo = NULL;
6679 struct got_worktree *worktree = NULL;
6680 char *cwd = NULL, *repo_path = NULL;
6681 int ch, do_list = 0, do_delete = 0, sort_by_time = 0;
6682 const char *obj_arg = NULL, *symref_target= NULL;
6683 char *refname = NULL, *keyword_idstr = NULL;
6684 int *pack_fds = NULL;
6686 #ifndef PROFILE
6687 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
6688 "sendfd unveil", NULL) == -1)
6689 err(1, "pledge");
6690 #endif
6692 while ((ch = getopt(argc, argv, "c:dlr:s:t")) != -1) {
6693 switch (ch) {
6694 case 'c':
6695 obj_arg = optarg;
6696 break;
6697 case 'd':
6698 do_delete = 1;
6699 break;
6700 case 'l':
6701 do_list = 1;
6702 break;
6703 case 'r':
6704 repo_path = realpath(optarg, NULL);
6705 if (repo_path == NULL)
6706 return got_error_from_errno2("realpath",
6707 optarg);
6708 got_path_strip_trailing_slashes(repo_path);
6709 break;
6710 case 's':
6711 symref_target = optarg;
6712 break;
6713 case 't':
6714 sort_by_time = 1;
6715 break;
6716 default:
6717 usage_ref();
6718 /* NOTREACHED */
6722 if (obj_arg && do_list)
6723 option_conflict('c', 'l');
6724 if (obj_arg && do_delete)
6725 option_conflict('c', 'd');
6726 if (obj_arg && symref_target)
6727 option_conflict('c', 's');
6728 if (symref_target && do_delete)
6729 option_conflict('s', 'd');
6730 if (symref_target && do_list)
6731 option_conflict('s', 'l');
6732 if (do_delete && do_list)
6733 option_conflict('d', 'l');
6734 if (sort_by_time && !do_list)
6735 errx(1, "-t option requires -l option");
6737 argc -= optind;
6738 argv += optind;
6740 if (do_list) {
6741 if (argc != 0 && argc != 1)
6742 usage_ref();
6743 if (argc == 1) {
6744 refname = strdup(argv[0]);
6745 if (refname == NULL) {
6746 error = got_error_from_errno("strdup");
6747 goto done;
6750 } else {
6751 if (argc != 1)
6752 usage_ref();
6753 refname = strdup(argv[0]);
6754 if (refname == NULL) {
6755 error = got_error_from_errno("strdup");
6756 goto done;
6760 if (refname)
6761 got_path_strip_trailing_slashes(refname);
6763 cwd = getcwd(NULL, 0);
6764 if (cwd == NULL) {
6765 error = got_error_from_errno("getcwd");
6766 goto done;
6769 error = got_repo_pack_fds_open(&pack_fds);
6770 if (error != NULL)
6771 goto done;
6773 if (repo_path == NULL) {
6774 error = got_worktree_open(&worktree, cwd,
6775 GOT_WORKTREE_GOT_DIR);
6776 if (error && error->code != GOT_ERR_NOT_WORKTREE)
6777 goto done;
6778 else
6779 error = NULL;
6780 if (worktree) {
6781 repo_path =
6782 strdup(got_worktree_get_repo_path(worktree));
6783 if (repo_path == NULL)
6784 error = got_error_from_errno("strdup");
6785 if (error)
6786 goto done;
6787 } else {
6788 repo_path = strdup(cwd);
6789 if (repo_path == NULL) {
6790 error = got_error_from_errno("strdup");
6791 goto done;
6796 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
6797 if (error != NULL)
6798 goto done;
6800 #ifndef PROFILE
6801 if (do_list) {
6802 /* Remove "cpath" promise. */
6803 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
6804 NULL) == -1)
6805 err(1, "pledge");
6807 #endif
6809 error = apply_unveil(got_repo_get_path(repo), do_list,
6810 worktree ? got_worktree_get_root_path(worktree) : NULL);
6811 if (error)
6812 goto done;
6814 if (do_list)
6815 error = list_refs(repo, refname, sort_by_time);
6816 else if (do_delete)
6817 error = delete_ref_by_name(repo, refname);
6818 else if (symref_target)
6819 error = add_symref(repo, refname, symref_target);
6820 else {
6821 if (obj_arg == NULL)
6822 usage_ref();
6824 error = got_keyword_to_idstr(&keyword_idstr, obj_arg,
6825 repo, worktree);
6826 if (error != NULL)
6827 goto done;
6828 if (keyword_idstr != NULL)
6829 obj_arg = keyword_idstr;
6831 error = add_ref(repo, refname, obj_arg);
6833 done:
6834 free(refname);
6835 if (repo) {
6836 const struct got_error *close_err = got_repo_close(repo);
6837 if (error == NULL)
6838 error = close_err;
6840 if (worktree)
6841 got_worktree_close(worktree);
6842 if (pack_fds) {
6843 const struct got_error *pack_err =
6844 got_repo_pack_fds_close(pack_fds);
6845 if (error == NULL)
6846 error = pack_err;
6848 free(cwd);
6849 free(repo_path);
6850 free(keyword_idstr);
6851 return error;
6854 __dead static void
6855 usage_branch(void)
6857 fprintf(stderr, "usage: %s branch [-lnt] [-c commit] [-d name] "
6858 "[-r repository-path] [name]\n", getprogname());
6859 exit(1);
6862 static const struct got_error *
6863 list_branch(struct got_repository *repo, struct got_worktree *worktree,
6864 struct got_reference *ref)
6866 const struct got_error *err = NULL;
6867 const char *refname;
6868 char *refstr;
6869 char marker = ' ';
6871 refname = got_ref_get_name(ref);
6872 if (worktree && strcmp(refname,
6873 got_worktree_get_head_ref_name(worktree)) == 0) {
6874 err = got_worktree_get_state(&marker, repo, worktree,
6875 check_cancelled, NULL);
6876 if (err != NULL)
6877 return err;
6880 if (strncmp(refname, "refs/heads/", 11) == 0)
6881 refname += 11;
6882 if (strncmp(refname, "refs/got/worktree/", 18) == 0)
6883 refname += 18;
6884 if (strncmp(refname, "refs/remotes/", 13) == 0)
6885 refname += 13;
6887 refstr = got_ref_to_str(ref);
6888 if (refstr == NULL)
6889 return got_error_from_errno("got_ref_to_str");
6891 printf("%c %s: %s\n", marker, refname, refstr);
6892 free(refstr);
6893 return NULL;
6896 static const struct got_error *
6897 show_current_branch(struct got_repository *repo, struct got_worktree *worktree)
6899 const char *refname;
6901 if (worktree == NULL)
6902 return got_error(GOT_ERR_NOT_WORKTREE);
6904 refname = got_worktree_get_head_ref_name(worktree);
6906 if (strncmp(refname, "refs/heads/", 11) == 0)
6907 refname += 11;
6908 if (strncmp(refname, "refs/got/worktree/", 18) == 0)
6909 refname += 18;
6911 printf("%s\n", refname);
6913 return NULL;
6916 static const struct got_error *
6917 list_branches(struct got_repository *repo, struct got_worktree *worktree,
6918 int sort_by_time)
6920 static const struct got_error *err = NULL;
6921 struct got_reflist_head refs;
6922 struct got_reflist_entry *re;
6923 struct got_reference *temp_ref = NULL;
6924 int rebase_in_progress, histedit_in_progress;
6926 TAILQ_INIT(&refs);
6928 if (worktree) {
6929 err = got_worktree_rebase_in_progress(&rebase_in_progress,
6930 worktree);
6931 if (err)
6932 return err;
6934 err = got_worktree_histedit_in_progress(&histedit_in_progress,
6935 worktree);
6936 if (err)
6937 return err;
6939 if (rebase_in_progress || histedit_in_progress) {
6940 err = got_ref_open(&temp_ref, repo,
6941 got_worktree_get_head_ref_name(worktree), 0);
6942 if (err)
6943 return err;
6944 list_branch(repo, worktree, temp_ref);
6945 got_ref_close(temp_ref);
6949 err = got_ref_list(&refs, repo, "refs/heads", sort_by_time ?
6950 got_ref_cmp_by_commit_timestamp_descending : got_ref_cmp_by_name,
6951 repo);
6952 if (err)
6953 return err;
6955 TAILQ_FOREACH(re, &refs, entry)
6956 list_branch(repo, worktree, re->ref);
6958 got_ref_list_free(&refs);
6960 err = got_ref_list(&refs, repo, "refs/remotes", sort_by_time ?
6961 got_ref_cmp_by_commit_timestamp_descending : got_ref_cmp_by_name,
6962 repo);
6963 if (err)
6964 return err;
6966 TAILQ_FOREACH(re, &refs, entry)
6967 list_branch(repo, worktree, re->ref);
6969 got_ref_list_free(&refs);
6971 return NULL;
6974 static const struct got_error *
6975 delete_branch(struct got_repository *repo, struct got_worktree *worktree,
6976 const char *branch_name)
6978 const struct got_error *err = NULL;
6979 struct got_reference *ref = NULL;
6980 char *refname, *remote_refname = NULL;
6982 if (strncmp(branch_name, "refs/", 5) == 0)
6983 branch_name += 5;
6984 if (strncmp(branch_name, "heads/", 6) == 0)
6985 branch_name += 6;
6986 else if (strncmp(branch_name, "remotes/", 8) == 0)
6987 branch_name += 8;
6989 if (asprintf(&refname, "refs/heads/%s", branch_name) == -1)
6990 return got_error_from_errno("asprintf");
6992 if (asprintf(&remote_refname, "refs/remotes/%s",
6993 branch_name) == -1) {
6994 err = got_error_from_errno("asprintf");
6995 goto done;
6998 err = got_ref_open(&ref, repo, refname, 0);
6999 if (err) {
7000 const struct got_error *err2;
7001 if (err->code != GOT_ERR_NOT_REF)
7002 goto done;
7004 * Keep 'err' intact such that if neither branch exists
7005 * we report "refs/heads" rather than "refs/remotes" in
7006 * our error message.
7008 err2 = got_ref_open(&ref, repo, remote_refname, 0);
7009 if (err2)
7010 goto done;
7011 err = NULL;
7014 if (worktree &&
7015 strcmp(got_worktree_get_head_ref_name(worktree),
7016 got_ref_get_name(ref)) == 0) {
7017 err = got_error_msg(GOT_ERR_SAME_BRANCH,
7018 "will not delete this work tree's current branch");
7019 goto done;
7022 err = delete_ref(repo, ref);
7023 done:
7024 if (ref)
7025 got_ref_close(ref);
7026 free(refname);
7027 free(remote_refname);
7028 return err;
7031 static const struct got_error *
7032 add_branch(struct got_repository *repo, const char *branch_name,
7033 struct got_object_id *base_commit_id)
7035 const struct got_error *err = NULL;
7036 struct got_reference *ref = NULL;
7037 char *refname = NULL;
7040 * Don't let the user create a branch name with a leading '-'.
7041 * While technically a valid reference name, this case is usually
7042 * an unintended typo.
7044 if (branch_name[0] == '-')
7045 return got_error_path(branch_name, GOT_ERR_REF_NAME_MINUS);
7047 if (strncmp(branch_name, "refs/heads/", 11) == 0)
7048 branch_name += 11;
7050 if (asprintf(&refname, "refs/heads/%s", 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 == NULL) {
7057 err = got_error(GOT_ERR_BRANCH_EXISTS);
7058 goto done;
7059 } else if (err->code != GOT_ERR_NOT_REF)
7060 goto done;
7062 err = got_ref_alloc(&ref, refname, base_commit_id);
7063 if (err)
7064 goto done;
7066 err = got_ref_write(ref, repo);
7067 done:
7068 if (ref)
7069 got_ref_close(ref);
7070 free(refname);
7071 return err;
7074 static const struct got_error *
7075 cmd_branch(int argc, char *argv[])
7077 const struct got_error *error = NULL;
7078 struct got_repository *repo = NULL;
7079 struct got_worktree *worktree = NULL;
7080 char *cwd = NULL, *repo_path = NULL;
7081 int ch, do_list = 0, do_show = 0, do_update = 1, sort_by_time = 0;
7082 const char *delref = NULL, *commit_id_arg = NULL;
7083 struct got_reference *ref = NULL;
7084 struct got_pathlist_head paths;
7085 struct got_object_id *commit_id = NULL;
7086 char *commit_id_str = NULL, *keyword_idstr = NULL;;
7087 int *pack_fds = NULL;
7089 TAILQ_INIT(&paths);
7091 #ifndef PROFILE
7092 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
7093 "sendfd unveil", NULL) == -1)
7094 err(1, "pledge");
7095 #endif
7097 while ((ch = getopt(argc, argv, "c:d:lnr:t")) != -1) {
7098 switch (ch) {
7099 case 'c':
7100 commit_id_arg = optarg;
7101 break;
7102 case 'd':
7103 delref = optarg;
7104 break;
7105 case 'l':
7106 do_list = 1;
7107 break;
7108 case 'n':
7109 do_update = 0;
7110 break;
7111 case 'r':
7112 repo_path = realpath(optarg, NULL);
7113 if (repo_path == NULL)
7114 return got_error_from_errno2("realpath",
7115 optarg);
7116 got_path_strip_trailing_slashes(repo_path);
7117 break;
7118 case 't':
7119 sort_by_time = 1;
7120 break;
7121 default:
7122 usage_branch();
7123 /* NOTREACHED */
7127 if (do_list && delref)
7128 option_conflict('l', 'd');
7129 if (sort_by_time && !do_list)
7130 errx(1, "-t option requires -l option");
7132 argc -= optind;
7133 argv += optind;
7135 if (!do_list && !delref && argc == 0)
7136 do_show = 1;
7138 if ((do_list || delref || do_show) && commit_id_arg != NULL)
7139 errx(1, "-c option can only be used when creating a branch");
7141 if (do_list || delref) {
7142 if (argc > 0)
7143 usage_branch();
7144 } else if (!do_show && argc != 1)
7145 usage_branch();
7147 cwd = getcwd(NULL, 0);
7148 if (cwd == NULL) {
7149 error = got_error_from_errno("getcwd");
7150 goto done;
7153 error = got_repo_pack_fds_open(&pack_fds);
7154 if (error != NULL)
7155 goto done;
7157 if (repo_path == NULL) {
7158 error = got_worktree_open(&worktree, cwd,
7159 GOT_WORKTREE_GOT_DIR);
7160 if (error && error->code != GOT_ERR_NOT_WORKTREE)
7161 goto done;
7162 else
7163 error = NULL;
7164 if (worktree) {
7165 repo_path =
7166 strdup(got_worktree_get_repo_path(worktree));
7167 if (repo_path == NULL)
7168 error = got_error_from_errno("strdup");
7169 if (error)
7170 goto done;
7171 } else {
7172 repo_path = strdup(cwd);
7173 if (repo_path == NULL) {
7174 error = got_error_from_errno("strdup");
7175 goto done;
7180 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
7181 if (error != NULL)
7182 goto done;
7184 #ifndef PROFILE
7185 if (do_list || do_show) {
7186 /* Remove "cpath" promise. */
7187 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
7188 NULL) == -1)
7189 err(1, "pledge");
7191 #endif
7193 error = apply_unveil(got_repo_get_path(repo), do_list,
7194 worktree ? got_worktree_get_root_path(worktree) : NULL);
7195 if (error)
7196 goto done;
7198 if (do_show)
7199 error = show_current_branch(repo, worktree);
7200 else if (do_list)
7201 error = list_branches(repo, worktree, sort_by_time);
7202 else if (delref)
7203 error = delete_branch(repo, worktree, delref);
7204 else {
7205 struct got_reflist_head refs;
7206 TAILQ_INIT(&refs);
7207 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
7208 NULL);
7209 if (error)
7210 goto done;
7211 if (commit_id_arg == NULL)
7212 commit_id_arg = worktree ?
7213 got_worktree_get_head_ref_name(worktree) :
7214 GOT_REF_HEAD;
7215 else {
7216 error = got_keyword_to_idstr(&keyword_idstr,
7217 commit_id_arg, repo, worktree);
7218 if (error != NULL)
7219 goto done;
7220 if (keyword_idstr != NULL)
7221 commit_id_arg = keyword_idstr;
7223 error = got_repo_match_object_id(&commit_id, NULL,
7224 commit_id_arg, GOT_OBJ_TYPE_COMMIT, &refs, repo);
7225 got_ref_list_free(&refs);
7226 if (error)
7227 goto done;
7228 error = add_branch(repo, argv[0], commit_id);
7229 if (error)
7230 goto done;
7231 if (worktree && do_update) {
7232 struct got_update_progress_arg upa;
7233 char *branch_refname = NULL;
7235 error = got_object_id_str(&commit_id_str, commit_id);
7236 if (error)
7237 goto done;
7238 error = get_worktree_paths_from_argv(&paths, 0, NULL,
7239 worktree);
7240 if (error)
7241 goto done;
7242 if (asprintf(&branch_refname, "refs/heads/%s", argv[0])
7243 == -1) {
7244 error = got_error_from_errno("asprintf");
7245 goto done;
7247 error = got_ref_open(&ref, repo, branch_refname, 0);
7248 free(branch_refname);
7249 if (error)
7250 goto done;
7251 error = switch_head_ref(ref, commit_id, worktree,
7252 repo);
7253 if (error)
7254 goto done;
7255 error = got_worktree_set_base_commit_id(worktree, repo,
7256 commit_id);
7257 if (error)
7258 goto done;
7259 memset(&upa, 0, sizeof(upa));
7260 error = got_worktree_checkout_files(worktree, &paths,
7261 repo, update_progress, &upa, check_cancelled,
7262 NULL);
7263 if (error)
7264 goto done;
7265 if (upa.did_something) {
7266 printf("Updated to %s: %s\n",
7267 got_worktree_get_head_ref_name(worktree),
7268 commit_id_str);
7270 print_update_progress_stats(&upa);
7273 done:
7274 free(keyword_idstr);
7275 if (ref)
7276 got_ref_close(ref);
7277 if (repo) {
7278 const struct got_error *close_err = got_repo_close(repo);
7279 if (error == NULL)
7280 error = close_err;
7282 if (worktree)
7283 got_worktree_close(worktree);
7284 if (pack_fds) {
7285 const struct got_error *pack_err =
7286 got_repo_pack_fds_close(pack_fds);
7287 if (error == NULL)
7288 error = pack_err;
7290 free(cwd);
7291 free(repo_path);
7292 free(commit_id);
7293 free(commit_id_str);
7294 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
7295 return error;
7299 __dead static void
7300 usage_tag(void)
7302 fprintf(stderr, "usage: %s tag [-lVv] [-c commit] [-m message] "
7303 "[-r repository-path] [-s signer-id] name\n", getprogname());
7304 exit(1);
7307 #if 0
7308 static const struct got_error *
7309 sort_tags(struct got_reflist_head *sorted, struct got_reflist_head *tags)
7311 const struct got_error *err = NULL;
7312 struct got_reflist_entry *re, *se, *new;
7313 struct got_object_id *re_id, *se_id;
7314 struct got_tag_object *re_tag, *se_tag;
7315 time_t re_time, se_time;
7317 STAILQ_FOREACH(re, tags, entry) {
7318 se = STAILQ_FIRST(sorted);
7319 if (se == NULL) {
7320 err = got_reflist_entry_dup(&new, re);
7321 if (err)
7322 return err;
7323 STAILQ_INSERT_HEAD(sorted, new, entry);
7324 continue;
7325 } else {
7326 err = got_ref_resolve(&re_id, repo, re->ref);
7327 if (err)
7328 break;
7329 err = got_object_open_as_tag(&re_tag, repo, re_id);
7330 free(re_id);
7331 if (err)
7332 break;
7333 re_time = got_object_tag_get_tagger_time(re_tag);
7334 got_object_tag_close(re_tag);
7337 while (se) {
7338 err = got_ref_resolve(&se_id, repo, re->ref);
7339 if (err)
7340 break;
7341 err = got_object_open_as_tag(&se_tag, repo, se_id);
7342 free(se_id);
7343 if (err)
7344 break;
7345 se_time = got_object_tag_get_tagger_time(se_tag);
7346 got_object_tag_close(se_tag);
7348 if (se_time > re_time) {
7349 err = got_reflist_entry_dup(&new, re);
7350 if (err)
7351 return err;
7352 STAILQ_INSERT_AFTER(sorted, se, new, entry);
7353 break;
7355 se = STAILQ_NEXT(se, entry);
7356 continue;
7359 done:
7360 return err;
7362 #endif
7364 static const struct got_error *
7365 get_tag_refname(char **refname, const char *tag_name)
7367 const struct got_error *err;
7369 if (strncmp("refs/tags/", tag_name, 10) == 0) {
7370 *refname = strdup(tag_name);
7371 if (*refname == NULL)
7372 return got_error_from_errno("strdup");
7373 } else if (asprintf(refname, "refs/tags/%s", tag_name) == -1) {
7374 err = got_error_from_errno("asprintf");
7375 *refname = NULL;
7376 return err;
7379 return NULL;
7382 static const struct got_error *
7383 list_tags(struct got_repository *repo, const char *tag_name, int verify_tags,
7384 const char *allowed_signers, const char *revoked_signers, int verbosity)
7386 static const struct got_error *err = NULL;
7387 struct got_reflist_head refs;
7388 struct got_reflist_entry *re;
7389 char *wanted_refname = NULL;
7390 int bad_sigs = 0;
7392 TAILQ_INIT(&refs);
7394 err = got_ref_list(&refs, repo, "refs/tags", got_ref_cmp_tags, repo);
7395 if (err)
7396 return err;
7398 if (tag_name) {
7399 struct got_reference *ref;
7400 err = get_tag_refname(&wanted_refname, tag_name);
7401 if (err)
7402 goto done;
7403 /* Wanted tag reference should exist. */
7404 err = got_ref_open(&ref, repo, wanted_refname, 0);
7405 if (err)
7406 goto done;
7407 got_ref_close(ref);
7410 TAILQ_FOREACH(re, &refs, entry) {
7411 const char *refname;
7412 char *refstr, *tagmsg0, *tagmsg, *line, *id_str, *datestr;
7413 char datebuf[26];
7414 const char *tagger, *ssh_sig = NULL;
7415 char *sig_msg = NULL;
7416 time_t tagger_time;
7417 struct got_object_id *id;
7418 struct got_tag_object *tag;
7419 struct got_commit_object *commit = NULL;
7421 refname = got_ref_get_name(re->ref);
7422 if (strncmp(refname, "refs/tags/", 10) != 0 ||
7423 (wanted_refname && strcmp(refname, wanted_refname) != 0))
7424 continue;
7425 refname += 10;
7426 refstr = got_ref_to_str(re->ref);
7427 if (refstr == NULL) {
7428 err = got_error_from_errno("got_ref_to_str");
7429 break;
7432 err = got_ref_resolve(&id, repo, re->ref);
7433 if (err)
7434 break;
7435 err = got_object_open_as_tag(&tag, repo, id);
7436 if (err) {
7437 if (err->code != GOT_ERR_OBJ_TYPE) {
7438 free(id);
7439 break;
7441 /* "lightweight" tag */
7442 err = got_object_open_as_commit(&commit, repo, id);
7443 if (err) {
7444 free(id);
7445 break;
7447 tagger = got_object_commit_get_committer(commit);
7448 tagger_time =
7449 got_object_commit_get_committer_time(commit);
7450 err = got_object_id_str(&id_str, id);
7451 free(id);
7452 if (err)
7453 break;
7454 } else {
7455 free(id);
7456 tagger = got_object_tag_get_tagger(tag);
7457 tagger_time = got_object_tag_get_tagger_time(tag);
7458 err = got_object_id_str(&id_str,
7459 got_object_tag_get_object_id(tag));
7460 if (err)
7461 break;
7464 if (tag && verify_tags) {
7465 ssh_sig = got_sigs_get_tagmsg_ssh_signature(
7466 got_object_tag_get_message(tag));
7467 if (ssh_sig && allowed_signers == NULL) {
7468 err = got_error_msg(
7469 GOT_ERR_VERIFY_TAG_SIGNATURE,
7470 "SSH signature verification requires "
7471 "setting allowed_signers in "
7472 "got.conf(5)");
7473 break;
7477 printf("%stag %s %s\n", GOT_COMMIT_SEP_STR, refname, refstr);
7478 free(refstr);
7479 printf("from: %s\n", tagger);
7480 datestr = get_datestr(&tagger_time, datebuf);
7481 if (datestr)
7482 printf("date: %s UTC\n", datestr);
7483 if (commit)
7484 printf("object: %s %s\n", GOT_OBJ_LABEL_COMMIT, id_str);
7485 else {
7486 switch (got_object_tag_get_object_type(tag)) {
7487 case GOT_OBJ_TYPE_BLOB:
7488 printf("object: %s %s\n", GOT_OBJ_LABEL_BLOB,
7489 id_str);
7490 break;
7491 case GOT_OBJ_TYPE_TREE:
7492 printf("object: %s %s\n", GOT_OBJ_LABEL_TREE,
7493 id_str);
7494 break;
7495 case GOT_OBJ_TYPE_COMMIT:
7496 printf("object: %s %s\n", GOT_OBJ_LABEL_COMMIT,
7497 id_str);
7498 break;
7499 case GOT_OBJ_TYPE_TAG:
7500 printf("object: %s %s\n", GOT_OBJ_LABEL_TAG,
7501 id_str);
7502 break;
7503 default:
7504 break;
7507 free(id_str);
7509 if (ssh_sig) {
7510 err = got_sigs_verify_tag_ssh(&sig_msg, tag, ssh_sig,
7511 allowed_signers, revoked_signers, verbosity);
7512 if (err && err->code == GOT_ERR_BAD_TAG_SIGNATURE)
7513 bad_sigs = 1;
7514 else if (err)
7515 break;
7516 printf("signature: %s", sig_msg);
7517 free(sig_msg);
7518 sig_msg = NULL;
7521 if (commit) {
7522 err = got_object_commit_get_logmsg(&tagmsg0, commit);
7523 if (err)
7524 break;
7525 got_object_commit_close(commit);
7526 } else {
7527 tagmsg0 = strdup(got_object_tag_get_message(tag));
7528 got_object_tag_close(tag);
7529 if (tagmsg0 == NULL) {
7530 err = got_error_from_errno("strdup");
7531 break;
7535 tagmsg = tagmsg0;
7536 do {
7537 line = strsep(&tagmsg, "\n");
7538 if (line)
7539 printf(" %s\n", line);
7540 } while (line);
7541 free(tagmsg0);
7543 done:
7544 got_ref_list_free(&refs);
7545 free(wanted_refname);
7547 if (err == NULL && bad_sigs)
7548 err = got_error(GOT_ERR_BAD_TAG_SIGNATURE);
7549 return err;
7552 static const struct got_error *
7553 get_tag_message(char **tagmsg, char **tagmsg_path, const char *commit_id_str,
7554 const char *tag_name, const char *repo_path)
7556 const struct got_error *err = NULL;
7557 char *template = NULL, *initial_content = NULL;
7558 char *editor = NULL;
7559 int initial_content_len;
7560 int fd = -1;
7562 if (asprintf(&template, GOT_TMPDIR_STR "/got-tagmsg") == -1) {
7563 err = got_error_from_errno("asprintf");
7564 goto done;
7567 initial_content_len = asprintf(&initial_content,
7568 "\n# tagging commit %s as %s\n",
7569 commit_id_str, tag_name);
7570 if (initial_content_len == -1) {
7571 err = got_error_from_errno("asprintf");
7572 goto done;
7575 err = got_opentemp_named_fd(tagmsg_path, &fd, template, "");
7576 if (err)
7577 goto done;
7579 if (write(fd, initial_content, initial_content_len) == -1) {
7580 err = got_error_from_errno2("write", *tagmsg_path);
7581 goto done;
7583 if (close(fd) == -1) {
7584 err = got_error_from_errno2("close", *tagmsg_path);
7585 goto done;
7587 fd = -1;
7589 err = get_editor(&editor);
7590 if (err)
7591 goto done;
7592 err = edit_logmsg(tagmsg, editor, *tagmsg_path, initial_content,
7593 initial_content_len, 1);
7594 done:
7595 free(initial_content);
7596 free(template);
7597 free(editor);
7599 if (fd != -1 && close(fd) == -1 && err == NULL)
7600 err = got_error_from_errno2("close", *tagmsg_path);
7602 if (err) {
7603 free(*tagmsg);
7604 *tagmsg = NULL;
7606 return err;
7609 static const struct got_error *
7610 add_tag(struct got_repository *repo, const char *tagger,
7611 const char *tag_name, const char *commit_arg, const char *tagmsg_arg,
7612 const char *signer_id, int verbosity)
7614 const struct got_error *err = NULL;
7615 struct got_object_id *commit_id = NULL, *tag_id = NULL;
7616 char *label = NULL, *commit_id_str = NULL;
7617 struct got_reference *ref = NULL;
7618 char *refname = NULL, *tagmsg = NULL;
7619 char *tagmsg_path = NULL, *tag_id_str = NULL;
7620 int preserve_tagmsg = 0;
7621 struct got_reflist_head refs;
7623 TAILQ_INIT(&refs);
7626 * Don't let the user create a tag name with a leading '-'.
7627 * While technically a valid reference name, this case is usually
7628 * an unintended typo.
7630 if (tag_name[0] == '-')
7631 return got_error_path(tag_name, GOT_ERR_REF_NAME_MINUS);
7633 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
7634 if (err)
7635 goto done;
7637 err = got_repo_match_object_id(&commit_id, &label, commit_arg,
7638 GOT_OBJ_TYPE_COMMIT, &refs, repo);
7639 if (err)
7640 goto done;
7642 err = got_object_id_str(&commit_id_str, commit_id);
7643 if (err)
7644 goto done;
7646 err = get_tag_refname(&refname, tag_name);
7647 if (err)
7648 goto done;
7649 if (strncmp("refs/tags/", tag_name, 10) == 0)
7650 tag_name += 10;
7652 err = got_ref_open(&ref, repo, refname, 0);
7653 if (err == NULL) {
7654 err = got_error(GOT_ERR_TAG_EXISTS);
7655 goto done;
7656 } else if (err->code != GOT_ERR_NOT_REF)
7657 goto done;
7659 if (tagmsg_arg == NULL) {
7660 err = get_tag_message(&tagmsg, &tagmsg_path, commit_id_str,
7661 tag_name, got_repo_get_path(repo));
7662 if (err) {
7663 if (err->code != GOT_ERR_COMMIT_MSG_EMPTY &&
7664 tagmsg_path != NULL)
7665 preserve_tagmsg = 1;
7666 goto done;
7668 /* Editor is done; we can now apply unveil(2) */
7669 err = got_sigs_apply_unveil();
7670 if (err)
7671 goto done;
7672 err = apply_unveil(got_repo_get_path(repo), 0, NULL);
7673 if (err)
7674 goto done;
7677 err = got_object_tag_create(&tag_id, tag_name, commit_id,
7678 tagger, time(NULL), tagmsg ? tagmsg : tagmsg_arg, signer_id, repo,
7679 verbosity);
7680 if (err) {
7681 if (tagmsg_path)
7682 preserve_tagmsg = 1;
7683 goto done;
7686 err = got_ref_alloc(&ref, refname, tag_id);
7687 if (err) {
7688 if (tagmsg_path)
7689 preserve_tagmsg = 1;
7690 goto done;
7693 err = got_ref_write(ref, repo);
7694 if (err) {
7695 if (tagmsg_path)
7696 preserve_tagmsg = 1;
7697 goto done;
7700 err = got_object_id_str(&tag_id_str, tag_id);
7701 if (err) {
7702 if (tagmsg_path)
7703 preserve_tagmsg = 1;
7704 goto done;
7706 printf("Created tag %s\n", tag_id_str);
7707 done:
7708 if (preserve_tagmsg) {
7709 fprintf(stderr, "%s: tag message preserved in %s\n",
7710 getprogname(), tagmsg_path);
7711 } else if (tagmsg_path && unlink(tagmsg_path) == -1 && err == NULL)
7712 err = got_error_from_errno2("unlink", tagmsg_path);
7713 free(tag_id_str);
7714 if (ref)
7715 got_ref_close(ref);
7716 free(commit_id);
7717 free(commit_id_str);
7718 free(refname);
7719 free(tagmsg);
7720 free(tagmsg_path);
7721 got_ref_list_free(&refs);
7722 return err;
7725 static const struct got_error *
7726 cmd_tag(int argc, char *argv[])
7728 const struct got_error *error = NULL;
7729 struct got_repository *repo = NULL;
7730 struct got_worktree *worktree = NULL;
7731 char *cwd = NULL, *repo_path = NULL, *commit_id_str = NULL;
7732 char *gitconfig_path = NULL, *tagger = NULL, *keyword_idstr = NULL;
7733 char *allowed_signers = NULL, *revoked_signers = NULL;
7734 const char *signer_id = NULL;
7735 const char *tag_name = NULL, *commit_id_arg = NULL, *tagmsg = NULL;
7736 int ch, do_list = 0, verify_tags = 0, verbosity = 0;
7737 int *pack_fds = NULL;
7739 #ifndef PROFILE
7740 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
7741 "sendfd unveil", NULL) == -1)
7742 err(1, "pledge");
7743 #endif
7745 while ((ch = getopt(argc, argv, "c:lm:r:s:Vv")) != -1) {
7746 switch (ch) {
7747 case 'c':
7748 commit_id_arg = optarg;
7749 break;
7750 case 'l':
7751 do_list = 1;
7752 break;
7753 case 'm':
7754 tagmsg = optarg;
7755 break;
7756 case 'r':
7757 repo_path = realpath(optarg, NULL);
7758 if (repo_path == NULL) {
7759 error = got_error_from_errno2("realpath",
7760 optarg);
7761 goto done;
7763 got_path_strip_trailing_slashes(repo_path);
7764 break;
7765 case 's':
7766 signer_id = optarg;
7767 break;
7768 case 'V':
7769 verify_tags = 1;
7770 break;
7771 case 'v':
7772 if (verbosity < 0)
7773 verbosity = 0;
7774 else if (verbosity < 3)
7775 verbosity++;
7776 break;
7777 default:
7778 usage_tag();
7779 /* NOTREACHED */
7783 argc -= optind;
7784 argv += optind;
7786 if (do_list || verify_tags) {
7787 if (commit_id_arg != NULL)
7788 errx(1,
7789 "-c option can only be used when creating a tag");
7790 if (tagmsg) {
7791 if (do_list)
7792 option_conflict('l', 'm');
7793 else
7794 option_conflict('V', 'm');
7796 if (signer_id) {
7797 if (do_list)
7798 option_conflict('l', 's');
7799 else
7800 option_conflict('V', 's');
7802 if (argc > 1)
7803 usage_tag();
7804 } else if (argc != 1)
7805 usage_tag();
7807 if (argc == 1)
7808 tag_name = argv[0];
7810 cwd = getcwd(NULL, 0);
7811 if (cwd == NULL) {
7812 error = got_error_from_errno("getcwd");
7813 goto done;
7816 error = got_repo_pack_fds_open(&pack_fds);
7817 if (error != NULL)
7818 goto done;
7820 if (repo_path == NULL) {
7821 error = got_worktree_open(&worktree, cwd,
7822 GOT_WORKTREE_GOT_DIR);
7823 if (error && error->code != GOT_ERR_NOT_WORKTREE)
7824 goto done;
7825 else
7826 error = NULL;
7827 if (worktree) {
7828 repo_path =
7829 strdup(got_worktree_get_repo_path(worktree));
7830 if (repo_path == NULL)
7831 error = got_error_from_errno("strdup");
7832 if (error)
7833 goto done;
7834 } else {
7835 repo_path = strdup(cwd);
7836 if (repo_path == NULL) {
7837 error = got_error_from_errno("strdup");
7838 goto done;
7843 if (do_list || verify_tags) {
7844 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
7845 if (error != NULL)
7846 goto done;
7847 error = get_allowed_signers(&allowed_signers, repo, worktree);
7848 if (error)
7849 goto done;
7850 error = get_revoked_signers(&revoked_signers, repo, worktree);
7851 if (error)
7852 goto done;
7853 if (worktree) {
7854 /* Release work tree lock. */
7855 got_worktree_close(worktree);
7856 worktree = NULL;
7860 * Remove "cpath" promise unless needed for signature tmpfile
7861 * creation.
7863 if (verify_tags)
7864 got_sigs_apply_unveil();
7865 else {
7866 #ifndef PROFILE
7867 if (pledge("stdio rpath wpath flock proc exec sendfd "
7868 "unveil", NULL) == -1)
7869 err(1, "pledge");
7870 #endif
7872 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
7873 if (error)
7874 goto done;
7875 error = list_tags(repo, tag_name, verify_tags, allowed_signers,
7876 revoked_signers, verbosity);
7877 } else {
7878 error = get_gitconfig_path(&gitconfig_path);
7879 if (error)
7880 goto done;
7881 error = got_repo_open(&repo, repo_path, gitconfig_path,
7882 pack_fds);
7883 if (error != NULL)
7884 goto done;
7886 error = get_author(&tagger, repo, worktree);
7887 if (error)
7888 goto done;
7889 if (signer_id == NULL)
7890 signer_id = get_signer_id(repo, worktree);
7892 if (tagmsg) {
7893 if (signer_id) {
7894 error = got_sigs_apply_unveil();
7895 if (error)
7896 goto done;
7898 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
7899 if (error)
7900 goto done;
7903 if (commit_id_arg == NULL) {
7904 struct got_reference *head_ref;
7905 struct got_object_id *commit_id;
7906 error = got_ref_open(&head_ref, repo,
7907 worktree ? got_worktree_get_head_ref_name(worktree)
7908 : GOT_REF_HEAD, 0);
7909 if (error)
7910 goto done;
7911 error = got_ref_resolve(&commit_id, repo, head_ref);
7912 got_ref_close(head_ref);
7913 if (error)
7914 goto done;
7915 error = got_object_id_str(&commit_id_str, commit_id);
7916 free(commit_id);
7917 if (error)
7918 goto done;
7919 } else {
7920 error = got_keyword_to_idstr(&keyword_idstr,
7921 commit_id_arg, repo, worktree);
7922 if (error != NULL)
7923 goto done;
7924 commit_id_str = keyword_idstr;
7927 if (worktree) {
7928 /* Release work tree lock. */
7929 got_worktree_close(worktree);
7930 worktree = NULL;
7933 error = add_tag(repo, tagger, tag_name,
7934 commit_id_str ? commit_id_str : commit_id_arg, tagmsg,
7935 signer_id, verbosity);
7937 done:
7938 if (repo) {
7939 const struct got_error *close_err = got_repo_close(repo);
7940 if (error == NULL)
7941 error = close_err;
7943 if (worktree)
7944 got_worktree_close(worktree);
7945 if (pack_fds) {
7946 const struct got_error *pack_err =
7947 got_repo_pack_fds_close(pack_fds);
7948 if (error == NULL)
7949 error = pack_err;
7951 free(cwd);
7952 free(repo_path);
7953 free(gitconfig_path);
7954 free(commit_id_str);
7955 free(tagger);
7956 free(allowed_signers);
7957 free(revoked_signers);
7958 return error;
7961 __dead static void
7962 usage_add(void)
7964 fprintf(stderr, "usage: %s add [-IR] path ...\n", getprogname());
7965 exit(1);
7968 static const struct got_error *
7969 add_progress(void *arg, unsigned char status, const char *path)
7971 while (path[0] == '/')
7972 path++;
7973 printf("%c %s\n", status, path);
7974 return NULL;
7977 static const struct got_error *
7978 cmd_add(int argc, char *argv[])
7980 const struct got_error *error = NULL;
7981 struct got_repository *repo = NULL;
7982 struct got_worktree *worktree = NULL;
7983 char *cwd = NULL;
7984 struct got_pathlist_head paths;
7985 struct got_pathlist_entry *pe;
7986 int ch, can_recurse = 0, no_ignores = 0;
7987 int *pack_fds = NULL;
7989 TAILQ_INIT(&paths);
7991 #ifndef PROFILE
7992 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
7993 NULL) == -1)
7994 err(1, "pledge");
7995 #endif
7997 while ((ch = getopt(argc, argv, "IR")) != -1) {
7998 switch (ch) {
7999 case 'I':
8000 no_ignores = 1;
8001 break;
8002 case 'R':
8003 can_recurse = 1;
8004 break;
8005 default:
8006 usage_add();
8007 /* NOTREACHED */
8011 argc -= optind;
8012 argv += optind;
8014 if (argc < 1)
8015 usage_add();
8017 cwd = getcwd(NULL, 0);
8018 if (cwd == NULL) {
8019 error = got_error_from_errno("getcwd");
8020 goto done;
8023 error = got_repo_pack_fds_open(&pack_fds);
8024 if (error != NULL)
8025 goto done;
8027 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
8028 if (error) {
8029 if (error->code == GOT_ERR_NOT_WORKTREE)
8030 error = wrap_not_worktree_error(error, "add", cwd);
8031 goto done;
8034 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
8035 NULL, pack_fds);
8036 if (error != NULL)
8037 goto done;
8039 error = apply_unveil(got_repo_get_path(repo), 1,
8040 got_worktree_get_root_path(worktree));
8041 if (error)
8042 goto done;
8044 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
8045 if (error)
8046 goto done;
8048 if (!can_recurse) {
8049 char *ondisk_path;
8050 struct stat sb;
8051 TAILQ_FOREACH(pe, &paths, entry) {
8052 if (asprintf(&ondisk_path, "%s/%s",
8053 got_worktree_get_root_path(worktree),
8054 pe->path) == -1) {
8055 error = got_error_from_errno("asprintf");
8056 goto done;
8058 if (lstat(ondisk_path, &sb) == -1) {
8059 if (errno == ENOENT) {
8060 free(ondisk_path);
8061 continue;
8063 error = got_error_from_errno2("lstat",
8064 ondisk_path);
8065 free(ondisk_path);
8066 goto done;
8068 free(ondisk_path);
8069 if (S_ISDIR(sb.st_mode)) {
8070 error = got_error_msg(GOT_ERR_BAD_PATH,
8071 "adding directories requires -R option");
8072 goto done;
8077 error = got_worktree_schedule_add(worktree, &paths, add_progress,
8078 NULL, repo, no_ignores);
8079 done:
8080 if (repo) {
8081 const struct got_error *close_err = got_repo_close(repo);
8082 if (error == NULL)
8083 error = close_err;
8085 if (worktree)
8086 got_worktree_close(worktree);
8087 if (pack_fds) {
8088 const struct got_error *pack_err =
8089 got_repo_pack_fds_close(pack_fds);
8090 if (error == NULL)
8091 error = pack_err;
8093 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
8094 free(cwd);
8095 return error;
8098 __dead static void
8099 usage_remove(void)
8101 fprintf(stderr, "usage: %s remove [-fkR] [-s status-codes] path ...\n",
8102 getprogname());
8103 exit(1);
8106 static const struct got_error *
8107 print_remove_status(void *arg, unsigned char status,
8108 unsigned char staged_status, const char *path)
8110 while (path[0] == '/')
8111 path++;
8112 if (status == GOT_STATUS_NONEXISTENT)
8113 return NULL;
8114 if (status == staged_status && (status == GOT_STATUS_DELETE))
8115 status = GOT_STATUS_NO_CHANGE;
8116 printf("%c%c %s\n", status, staged_status, path);
8117 return NULL;
8120 static const struct got_error *
8121 cmd_remove(int argc, char *argv[])
8123 const struct got_error *error = NULL;
8124 struct got_worktree *worktree = NULL;
8125 struct got_repository *repo = NULL;
8126 const char *status_codes = NULL;
8127 char *cwd = NULL;
8128 struct got_pathlist_head paths;
8129 struct got_pathlist_entry *pe;
8130 int ch, delete_local_mods = 0, can_recurse = 0, keep_on_disk = 0, i;
8131 int ignore_missing_paths = 0;
8132 int *pack_fds = NULL;
8134 TAILQ_INIT(&paths);
8136 #ifndef PROFILE
8137 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
8138 NULL) == -1)
8139 err(1, "pledge");
8140 #endif
8142 while ((ch = getopt(argc, argv, "fkRs:")) != -1) {
8143 switch (ch) {
8144 case 'f':
8145 delete_local_mods = 1;
8146 ignore_missing_paths = 1;
8147 break;
8148 case 'k':
8149 keep_on_disk = 1;
8150 break;
8151 case 'R':
8152 can_recurse = 1;
8153 break;
8154 case 's':
8155 for (i = 0; optarg[i] != '\0'; i++) {
8156 switch (optarg[i]) {
8157 case GOT_STATUS_MODIFY:
8158 delete_local_mods = 1;
8159 break;
8160 case GOT_STATUS_MISSING:
8161 ignore_missing_paths = 1;
8162 break;
8163 default:
8164 errx(1, "invalid status code '%c'",
8165 optarg[i]);
8168 status_codes = optarg;
8169 break;
8170 default:
8171 usage_remove();
8172 /* NOTREACHED */
8176 argc -= optind;
8177 argv += optind;
8179 if (argc < 1)
8180 usage_remove();
8182 cwd = getcwd(NULL, 0);
8183 if (cwd == NULL) {
8184 error = got_error_from_errno("getcwd");
8185 goto done;
8188 error = got_repo_pack_fds_open(&pack_fds);
8189 if (error != NULL)
8190 goto done;
8192 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
8193 if (error) {
8194 if (error->code == GOT_ERR_NOT_WORKTREE)
8195 error = wrap_not_worktree_error(error, "remove", cwd);
8196 goto done;
8199 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
8200 NULL, pack_fds);
8201 if (error)
8202 goto done;
8204 error = apply_unveil(got_repo_get_path(repo), 1,
8205 got_worktree_get_root_path(worktree));
8206 if (error)
8207 goto done;
8209 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
8210 if (error)
8211 goto done;
8213 if (!can_recurse) {
8214 char *ondisk_path;
8215 struct stat sb;
8216 TAILQ_FOREACH(pe, &paths, entry) {
8217 if (asprintf(&ondisk_path, "%s/%s",
8218 got_worktree_get_root_path(worktree),
8219 pe->path) == -1) {
8220 error = got_error_from_errno("asprintf");
8221 goto done;
8223 if (lstat(ondisk_path, &sb) == -1) {
8224 if (errno == ENOENT) {
8225 free(ondisk_path);
8226 continue;
8228 error = got_error_from_errno2("lstat",
8229 ondisk_path);
8230 free(ondisk_path);
8231 goto done;
8233 free(ondisk_path);
8234 if (S_ISDIR(sb.st_mode)) {
8235 error = got_error_msg(GOT_ERR_BAD_PATH,
8236 "removing directories requires -R option");
8237 goto done;
8242 error = got_worktree_schedule_delete(worktree, &paths,
8243 delete_local_mods, status_codes, print_remove_status, NULL,
8244 repo, keep_on_disk, ignore_missing_paths);
8245 done:
8246 if (repo) {
8247 const struct got_error *close_err = got_repo_close(repo);
8248 if (error == NULL)
8249 error = close_err;
8251 if (worktree)
8252 got_worktree_close(worktree);
8253 if (pack_fds) {
8254 const struct got_error *pack_err =
8255 got_repo_pack_fds_close(pack_fds);
8256 if (error == NULL)
8257 error = pack_err;
8259 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
8260 free(cwd);
8261 return error;
8264 __dead static void
8265 usage_patch(void)
8267 fprintf(stderr, "usage: %s patch [-nR] [-c commit] [-p strip-count] "
8268 "[patchfile]\n", getprogname());
8269 exit(1);
8272 static const struct got_error *
8273 patch_from_stdin(int *patchfd)
8275 const struct got_error *err = NULL;
8276 ssize_t r;
8277 char buf[BUFSIZ];
8278 sig_t sighup, sigint, sigquit;
8280 *patchfd = got_opentempfd();
8281 if (*patchfd == -1)
8282 return got_error_from_errno("got_opentempfd");
8284 sighup = signal(SIGHUP, SIG_DFL);
8285 sigint = signal(SIGINT, SIG_DFL);
8286 sigquit = signal(SIGQUIT, SIG_DFL);
8288 for (;;) {
8289 r = read(0, buf, sizeof(buf));
8290 if (r == -1) {
8291 err = got_error_from_errno("read");
8292 break;
8294 if (r == 0)
8295 break;
8296 if (write(*patchfd, buf, r) == -1) {
8297 err = got_error_from_errno("write");
8298 break;
8302 signal(SIGHUP, sighup);
8303 signal(SIGINT, sigint);
8304 signal(SIGQUIT, sigquit);
8306 if (err == NULL && lseek(*patchfd, 0, SEEK_SET) == -1)
8307 err = got_error_from_errno("lseek");
8309 if (err != NULL) {
8310 close(*patchfd);
8311 *patchfd = -1;
8314 return err;
8317 struct got_patch_progress_arg {
8318 int did_something;
8319 int conflicts;
8320 int rejects;
8323 static const struct got_error *
8324 patch_progress(void *arg, const char *old, const char *new,
8325 unsigned char status, const struct got_error *error, int old_from,
8326 int old_lines, int new_from, int new_lines, int offset,
8327 int ws_mangled, const struct got_error *hunk_err)
8329 const char *path = new == NULL ? old : new;
8330 struct got_patch_progress_arg *a = arg;
8332 while (*path == '/')
8333 path++;
8335 if (status != GOT_STATUS_NO_CHANGE &&
8336 status != 0 /* per-hunk progress */) {
8337 printf("%c %s\n", status, path);
8338 a->did_something = 1;
8341 if (hunk_err == NULL) {
8342 if (status == GOT_STATUS_CANNOT_UPDATE)
8343 a->rejects++;
8344 else if (status == GOT_STATUS_CONFLICT)
8345 a->conflicts++;
8348 if (error != NULL)
8349 fprintf(stderr, "%s: %s\n", getprogname(), error->msg);
8351 if (offset != 0 || hunk_err != NULL || ws_mangled) {
8352 printf("@@ -%d,%d +%d,%d @@ ", old_from,
8353 old_lines, new_from, new_lines);
8354 if (hunk_err != NULL)
8355 printf("%s\n", hunk_err->msg);
8356 else if (offset != 0)
8357 printf("applied with offset %d\n", offset);
8358 else
8359 printf("hunk contains mangled whitespace\n");
8362 return NULL;
8365 static void
8366 print_patch_progress_stats(struct got_patch_progress_arg *ppa)
8368 if (!ppa->did_something)
8369 return;
8371 if (ppa->conflicts > 0)
8372 printf("Files with merge conflicts: %d\n", ppa->conflicts);
8374 if (ppa->rejects > 0) {
8375 printf("Files where patch failed to apply: %d\n",
8376 ppa->rejects);
8380 static const struct got_error *
8381 cmd_patch(int argc, char *argv[])
8383 const struct got_error *error = NULL, *close_error = NULL;
8384 struct got_worktree *worktree = NULL;
8385 struct got_repository *repo = NULL;
8386 struct got_reflist_head refs;
8387 struct got_object_id *commit_id = NULL;
8388 const char *commit_id_str = NULL;
8389 struct stat sb;
8390 const char *errstr;
8391 char *cwd = NULL, *keyword_idstr = NULL;
8392 int ch, nop = 0, strip = -1, reverse = 0;
8393 int patchfd;
8394 int *pack_fds = NULL;
8395 struct got_patch_progress_arg ppa;
8397 TAILQ_INIT(&refs);
8399 #ifndef PROFILE
8400 if (pledge("stdio rpath wpath cpath fattr proc exec sendfd flock "
8401 "unveil", NULL) == -1)
8402 err(1, "pledge");
8403 #endif
8405 while ((ch = getopt(argc, argv, "c:np:R")) != -1) {
8406 switch (ch) {
8407 case 'c':
8408 commit_id_str = optarg;
8409 break;
8410 case 'n':
8411 nop = 1;
8412 break;
8413 case 'p':
8414 strip = strtonum(optarg, 0, INT_MAX, &errstr);
8415 if (errstr != NULL)
8416 errx(1, "pathname strip count is %s: %s",
8417 errstr, optarg);
8418 break;
8419 case 'R':
8420 reverse = 1;
8421 break;
8422 default:
8423 usage_patch();
8424 /* NOTREACHED */
8428 argc -= optind;
8429 argv += optind;
8431 if (argc == 0) {
8432 error = patch_from_stdin(&patchfd);
8433 if (error)
8434 return error;
8435 } else if (argc == 1) {
8436 patchfd = open(argv[0], O_RDONLY);
8437 if (patchfd == -1) {
8438 error = got_error_from_errno2("open", argv[0]);
8439 return error;
8441 if (fstat(patchfd, &sb) == -1) {
8442 error = got_error_from_errno2("fstat", argv[0]);
8443 goto done;
8445 if (!S_ISREG(sb.st_mode)) {
8446 error = got_error_path(argv[0], GOT_ERR_BAD_FILETYPE);
8447 goto done;
8449 } else
8450 usage_patch();
8452 if ((cwd = getcwd(NULL, 0)) == NULL) {
8453 error = got_error_from_errno("getcwd");
8454 goto done;
8457 error = got_repo_pack_fds_open(&pack_fds);
8458 if (error != NULL)
8459 goto done;
8461 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
8462 if (error != NULL)
8463 goto done;
8465 const char *repo_path = got_worktree_get_repo_path(worktree);
8466 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
8467 if (error != NULL)
8468 goto done;
8470 error = apply_unveil(got_repo_get_path(repo), 0,
8471 got_worktree_get_root_path(worktree));
8472 if (error != NULL)
8473 goto done;
8475 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
8476 if (error)
8477 goto done;
8479 if (commit_id_str != NULL) {
8480 error = got_keyword_to_idstr(&keyword_idstr, commit_id_str,
8481 repo, worktree);
8482 if (error != NULL)
8483 goto done;
8485 error = got_repo_match_object_id(&commit_id, NULL,
8486 keyword_idstr != NULL ? keyword_idstr : commit_id_str,
8487 GOT_OBJ_TYPE_COMMIT, &refs, repo);
8488 if (error)
8489 goto done;
8492 memset(&ppa, 0, sizeof(ppa));
8493 error = got_patch(patchfd, worktree, repo, nop, strip, reverse,
8494 commit_id, patch_progress, &ppa, check_cancelled, NULL);
8495 print_patch_progress_stats(&ppa);
8496 done:
8497 got_ref_list_free(&refs);
8498 free(keyword_idstr);
8499 free(commit_id);
8500 if (repo) {
8501 close_error = got_repo_close(repo);
8502 if (error == NULL)
8503 error = close_error;
8505 if (worktree != NULL) {
8506 close_error = got_worktree_close(worktree);
8507 if (error == NULL)
8508 error = close_error;
8510 if (pack_fds) {
8511 const struct got_error *pack_err =
8512 got_repo_pack_fds_close(pack_fds);
8513 if (error == NULL)
8514 error = pack_err;
8516 free(cwd);
8517 return error;
8520 __dead static void
8521 usage_revert(void)
8523 fprintf(stderr, "usage: %s revert [-pR] [-F response-script] path ...\n",
8524 getprogname());
8525 exit(1);
8528 static const struct got_error *
8529 revert_progress(void *arg, unsigned char status, const char *path)
8531 if (status == GOT_STATUS_UNVERSIONED)
8532 return NULL;
8534 while (path[0] == '/')
8535 path++;
8536 printf("%c %s\n", status, path);
8537 return NULL;
8540 struct choose_patch_arg {
8541 FILE *patch_script_file;
8542 const char *action;
8545 static const struct got_error *
8546 show_change(unsigned char status, const char *path, FILE *patch_file, int n,
8547 int nchanges, const char *action)
8549 const struct got_error *err;
8550 char *line = NULL;
8551 size_t linesize = 0;
8552 ssize_t linelen;
8554 switch (status) {
8555 case GOT_STATUS_ADD:
8556 printf("A %s\n%s this addition? [y/n] ", path, action);
8557 break;
8558 case GOT_STATUS_DELETE:
8559 printf("D %s\n%s this deletion? [y/n] ", path, action);
8560 break;
8561 case GOT_STATUS_MODIFY:
8562 if (fseek(patch_file, 0L, SEEK_SET) == -1)
8563 return got_error_from_errno("fseek");
8564 printf(GOT_COMMIT_SEP_STR);
8565 while ((linelen = getline(&line, &linesize, patch_file)) != -1)
8566 printf("%s", line);
8567 if (linelen == -1 && ferror(patch_file)) {
8568 err = got_error_from_errno("getline");
8569 free(line);
8570 return err;
8572 free(line);
8573 printf(GOT_COMMIT_SEP_STR);
8574 printf("M %s (change %d of %d)\n%s this change? [y/n/q] ",
8575 path, n, nchanges, action);
8576 break;
8577 default:
8578 return got_error_path(path, GOT_ERR_FILE_STATUS);
8581 fflush(stdout);
8582 return NULL;
8585 static const struct got_error *
8586 choose_patch(int *choice, void *arg, unsigned char status, const char *path,
8587 FILE *patch_file, int n, int nchanges)
8589 const struct got_error *err = NULL;
8590 char *line = NULL;
8591 size_t linesize = 0;
8592 ssize_t linelen;
8593 int resp = ' ';
8594 struct choose_patch_arg *a = arg;
8596 *choice = GOT_PATCH_CHOICE_NONE;
8598 if (a->patch_script_file) {
8599 char *nl;
8600 err = show_change(status, path, patch_file, n, nchanges,
8601 a->action);
8602 if (err)
8603 return err;
8604 linelen = getline(&line, &linesize, a->patch_script_file);
8605 if (linelen == -1) {
8606 if (ferror(a->patch_script_file))
8607 return got_error_from_errno("getline");
8608 return NULL;
8610 nl = strchr(line, '\n');
8611 if (nl)
8612 *nl = '\0';
8613 if (strcmp(line, "y") == 0) {
8614 *choice = GOT_PATCH_CHOICE_YES;
8615 printf("y\n");
8616 } else if (strcmp(line, "n") == 0) {
8617 *choice = GOT_PATCH_CHOICE_NO;
8618 printf("n\n");
8619 } else if (strcmp(line, "q") == 0 &&
8620 status == GOT_STATUS_MODIFY) {
8621 *choice = GOT_PATCH_CHOICE_QUIT;
8622 printf("q\n");
8623 } else
8624 printf("invalid response '%s'\n", line);
8625 free(line);
8626 return NULL;
8629 while (resp != 'y' && resp != 'n' && resp != 'q') {
8630 err = show_change(status, path, patch_file, n, nchanges,
8631 a->action);
8632 if (err)
8633 return err;
8634 resp = getchar();
8635 if (resp == '\n')
8636 resp = getchar();
8637 if (status == GOT_STATUS_MODIFY) {
8638 if (resp != 'y' && resp != 'n' && resp != 'q') {
8639 printf("invalid response '%c'\n", resp);
8640 resp = ' ';
8642 } else if (resp != 'y' && resp != 'n') {
8643 printf("invalid response '%c'\n", resp);
8644 resp = ' ';
8648 if (resp == 'y')
8649 *choice = GOT_PATCH_CHOICE_YES;
8650 else if (resp == 'n')
8651 *choice = GOT_PATCH_CHOICE_NO;
8652 else if (resp == 'q' && status == GOT_STATUS_MODIFY)
8653 *choice = GOT_PATCH_CHOICE_QUIT;
8655 return NULL;
8658 struct wt_commitable_path_arg {
8659 struct got_pathlist_head *commit_paths;
8660 int *has_changes;
8664 * Shortcut work tree status callback to determine if the set of paths scanned
8665 * has at least one versioned path that is being modified and, if not NULL, is
8666 * in the arg->commit_paths list. Set arg and return GOT_ERR_FILE_MODIFIED as
8667 * soon as a path is passed with a status that satisfies this criteria.
8669 static const struct got_error *
8670 worktree_has_commitable_path(void *arg, unsigned char status,
8671 unsigned char staged_status, const char *path,
8672 struct got_object_id *blob_id, struct got_object_id *staged_blob_id,
8673 struct got_object_id *commit_id, int dirfd, const char *de_name)
8675 struct wt_commitable_path_arg *a = arg;
8677 if (status == staged_status && (status == GOT_STATUS_DELETE))
8678 status = GOT_STATUS_NO_CHANGE;
8680 if (!(status == GOT_STATUS_NO_CHANGE ||
8681 status == GOT_STATUS_UNVERSIONED) ||
8682 staged_status != GOT_STATUS_NO_CHANGE) {
8683 if (a->commit_paths != NULL) {
8684 struct got_pathlist_entry *pe;
8686 TAILQ_FOREACH(pe, a->commit_paths, entry) {
8687 if (strncmp(path, pe->path,
8688 pe->path_len) == 0) {
8689 *a->has_changes = 1;
8690 break;
8693 } else
8694 *a->has_changes = 1;
8696 if (*a->has_changes)
8697 return got_error(GOT_ERR_FILE_MODIFIED);
8700 return NULL;
8704 * Check that the changeset of the commit identified by id is
8705 * comprised of at least one modified path that is being committed.
8707 static const struct got_error *
8708 commit_path_changed_in_worktree(struct wt_commitable_path_arg *wcpa,
8709 struct got_object_id *id, struct got_worktree *worktree,
8710 struct got_repository *repo)
8712 const struct got_error *err;
8713 struct got_pathlist_head paths;
8714 struct got_commit_object *commit = NULL, *pcommit = NULL;
8715 struct got_tree_object *tree = NULL, *ptree = NULL;
8716 struct got_object_qid *pid;
8718 TAILQ_INIT(&paths);
8720 err = got_object_open_as_commit(&commit, repo, id);
8721 if (err)
8722 goto done;
8724 err = got_object_open_as_tree(&tree, repo,
8725 got_object_commit_get_tree_id(commit));
8726 if (err)
8727 goto done;
8729 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
8730 if (pid != NULL) {
8731 err = got_object_open_as_commit(&pcommit, repo, &pid->id);
8732 if (err)
8733 goto done;
8735 err = got_object_open_as_tree(&ptree, repo,
8736 got_object_commit_get_tree_id(pcommit));
8737 if (err)
8738 goto done;
8741 err = got_diff_tree(ptree, tree, NULL, NULL, -1, -1, "", "", repo,
8742 got_diff_tree_collect_changed_paths, &paths, 0);
8743 if (err)
8744 goto done;
8746 err = got_worktree_status(worktree, &paths, repo, 0,
8747 worktree_has_commitable_path, wcpa, check_cancelled, NULL);
8748 if (err && err->code == GOT_ERR_FILE_MODIFIED) {
8750 * At least one changed path in the referenced commit is
8751 * modified in the work tree, that's all we need to know!
8753 err = NULL;
8756 done:
8757 got_pathlist_free(&paths, GOT_PATHLIST_FREE_ALL);
8758 if (commit)
8759 got_object_commit_close(commit);
8760 if (pcommit)
8761 got_object_commit_close(pcommit);
8762 if (tree)
8763 got_object_tree_close(tree);
8764 if (ptree)
8765 got_object_tree_close(ptree);
8766 return err;
8770 * Remove any "logmsg" reference comprised entirely of paths that have
8771 * been reverted in this work tree. If any path in the logmsg ref changeset
8772 * remains in a changed state in the worktree, do not remove the reference.
8774 static const struct got_error *
8775 rm_logmsg_ref(struct got_worktree *worktree, struct got_repository *repo)
8777 const struct got_error *err;
8778 struct got_reflist_head refs;
8779 struct got_reflist_entry *re;
8780 struct got_commit_object *commit = NULL;
8781 struct got_object_id *commit_id = NULL;
8782 struct wt_commitable_path_arg wcpa;
8783 char *uuidstr = NULL;
8785 TAILQ_INIT(&refs);
8787 err = got_worktree_get_uuid(&uuidstr, worktree);
8788 if (err)
8789 goto done;
8791 err = got_ref_list(&refs, repo, "refs/got/worktree",
8792 got_ref_cmp_by_name, repo);
8793 if (err)
8794 goto done;
8796 TAILQ_FOREACH(re, &refs, entry) {
8797 const char *refname;
8798 int has_changes = 0;
8800 refname = got_ref_get_name(re->ref);
8802 if (!strncmp(refname, GOT_WORKTREE_CHERRYPICK_REF_PREFIX,
8803 GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN))
8804 refname += GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN + 1;
8805 else if (!strncmp(refname, GOT_WORKTREE_BACKOUT_REF_PREFIX,
8806 GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN))
8807 refname += GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN + 1;
8808 else
8809 continue;
8811 if (strncmp(refname, uuidstr, GOT_WORKTREE_UUID_STRLEN) == 0)
8812 refname += GOT_WORKTREE_UUID_STRLEN + 1; /* skip '-' */
8813 else
8814 continue;
8816 err = got_repo_match_object_id(&commit_id, NULL, refname,
8817 GOT_OBJ_TYPE_COMMIT, NULL, repo);
8818 if (err)
8819 goto done;
8821 err = got_object_open_as_commit(&commit, repo, commit_id);
8822 if (err)
8823 goto done;
8825 wcpa.commit_paths = NULL;
8826 wcpa.has_changes = &has_changes;
8828 err = commit_path_changed_in_worktree(&wcpa, commit_id,
8829 worktree, repo);
8830 if (err)
8831 goto done;
8833 if (!has_changes) {
8834 err = got_ref_delete(re->ref, repo);
8835 if (err)
8836 goto done;
8839 got_object_commit_close(commit);
8840 commit = NULL;
8841 free(commit_id);
8842 commit_id = NULL;
8845 done:
8846 free(uuidstr);
8847 free(commit_id);
8848 got_ref_list_free(&refs);
8849 if (commit)
8850 got_object_commit_close(commit);
8851 return err;
8854 static const struct got_error *
8855 cmd_revert(int argc, char *argv[])
8857 const struct got_error *error = NULL;
8858 struct got_worktree *worktree = NULL;
8859 struct got_repository *repo = NULL;
8860 char *cwd = NULL, *path = NULL;
8861 struct got_pathlist_head paths;
8862 struct got_pathlist_entry *pe;
8863 int ch, can_recurse = 0, pflag = 0;
8864 FILE *patch_script_file = NULL;
8865 const char *patch_script_path = NULL;
8866 struct choose_patch_arg cpa;
8867 int *pack_fds = NULL;
8869 TAILQ_INIT(&paths);
8871 #ifndef PROFILE
8872 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
8873 "unveil", NULL) == -1)
8874 err(1, "pledge");
8875 #endif
8877 while ((ch = getopt(argc, argv, "F:pR")) != -1) {
8878 switch (ch) {
8879 case 'F':
8880 patch_script_path = optarg;
8881 break;
8882 case 'p':
8883 pflag = 1;
8884 break;
8885 case 'R':
8886 can_recurse = 1;
8887 break;
8888 default:
8889 usage_revert();
8890 /* NOTREACHED */
8894 argc -= optind;
8895 argv += optind;
8897 if (argc < 1)
8898 usage_revert();
8899 if (patch_script_path && !pflag)
8900 errx(1, "-F option can only be used together with -p option");
8902 cwd = getcwd(NULL, 0);
8903 if (cwd == NULL) {
8904 error = got_error_from_errno("getcwd");
8905 goto done;
8908 error = got_repo_pack_fds_open(&pack_fds);
8909 if (error != NULL)
8910 goto done;
8912 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
8913 if (error) {
8914 if (error->code == GOT_ERR_NOT_WORKTREE)
8915 error = wrap_not_worktree_error(error, "revert", cwd);
8916 goto done;
8919 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
8920 NULL, pack_fds);
8921 if (error != NULL)
8922 goto done;
8924 if (patch_script_path) {
8925 patch_script_file = fopen(patch_script_path, "re");
8926 if (patch_script_file == NULL) {
8927 error = got_error_from_errno2("fopen",
8928 patch_script_path);
8929 goto done;
8934 * XXX "c" perm needed on repo dir to delete merge references.
8936 error = apply_unveil(got_repo_get_path(repo), 0,
8937 got_worktree_get_root_path(worktree));
8938 if (error)
8939 goto done;
8941 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
8942 if (error)
8943 goto done;
8945 if (!can_recurse) {
8946 char *ondisk_path;
8947 struct stat sb;
8948 TAILQ_FOREACH(pe, &paths, entry) {
8949 if (asprintf(&ondisk_path, "%s/%s",
8950 got_worktree_get_root_path(worktree),
8951 pe->path) == -1) {
8952 error = got_error_from_errno("asprintf");
8953 goto done;
8955 if (lstat(ondisk_path, &sb) == -1) {
8956 if (errno == ENOENT) {
8957 free(ondisk_path);
8958 continue;
8960 error = got_error_from_errno2("lstat",
8961 ondisk_path);
8962 free(ondisk_path);
8963 goto done;
8965 free(ondisk_path);
8966 if (S_ISDIR(sb.st_mode)) {
8967 error = got_error_msg(GOT_ERR_BAD_PATH,
8968 "reverting directories requires -R option");
8969 goto done;
8974 cpa.patch_script_file = patch_script_file;
8975 cpa.action = "revert";
8976 error = got_worktree_revert(worktree, &paths, revert_progress, NULL,
8977 pflag ? choose_patch : NULL, &cpa, repo);
8979 error = rm_logmsg_ref(worktree, repo);
8980 done:
8981 if (patch_script_file && fclose(patch_script_file) == EOF &&
8982 error == NULL)
8983 error = got_error_from_errno2("fclose", patch_script_path);
8984 if (repo) {
8985 const struct got_error *close_err = got_repo_close(repo);
8986 if (error == NULL)
8987 error = close_err;
8989 if (worktree)
8990 got_worktree_close(worktree);
8991 if (pack_fds) {
8992 const struct got_error *pack_err =
8993 got_repo_pack_fds_close(pack_fds);
8994 if (error == NULL)
8995 error = pack_err;
8997 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
8998 free(path);
8999 free(cwd);
9000 return error;
9003 __dead static void
9004 usage_commit(void)
9006 fprintf(stderr, "usage: %s commit [-CNnS] [-A author] [-F path] "
9007 "[-m message] [path ...]\n", getprogname());
9008 exit(1);
9011 struct collect_commit_logmsg_arg {
9012 const char *cmdline_log;
9013 const char *prepared_log;
9014 const char *merged_log;
9015 int non_interactive;
9016 const char *editor;
9017 const char *worktree_path;
9018 const char *branch_name;
9019 const char *repo_path;
9020 char *logmsg_path;
9024 static const struct got_error *
9025 read_prepared_logmsg(char **logmsg, const char *path)
9027 const struct got_error *err = NULL;
9028 FILE *f = NULL;
9029 struct stat sb;
9030 size_t r;
9032 *logmsg = NULL;
9033 memset(&sb, 0, sizeof(sb));
9035 f = fopen(path, "re");
9036 if (f == NULL)
9037 return got_error_from_errno2("fopen", path);
9039 if (fstat(fileno(f), &sb) == -1) {
9040 err = got_error_from_errno2("fstat", path);
9041 goto done;
9043 if (sb.st_size == 0) {
9044 err = got_error(GOT_ERR_COMMIT_MSG_EMPTY);
9045 goto done;
9048 *logmsg = malloc(sb.st_size + 1);
9049 if (*logmsg == NULL) {
9050 err = got_error_from_errno("malloc");
9051 goto done;
9054 r = fread(*logmsg, 1, sb.st_size, f);
9055 if (r != sb.st_size) {
9056 if (ferror(f))
9057 err = got_error_from_errno2("fread", path);
9058 else
9059 err = got_error(GOT_ERR_IO);
9060 goto done;
9062 (*logmsg)[sb.st_size] = '\0';
9063 done:
9064 if (fclose(f) == EOF && err == NULL)
9065 err = got_error_from_errno2("fclose", path);
9066 if (err) {
9067 free(*logmsg);
9068 *logmsg = NULL;
9070 return err;
9073 static const struct got_error *
9074 collect_commit_logmsg(struct got_pathlist_head *commitable_paths,
9075 const char *diff_path, char **logmsg, void *arg)
9077 char *initial_content = NULL;
9078 struct got_pathlist_entry *pe;
9079 const struct got_error *err = NULL;
9080 char *template = NULL;
9081 char *prepared_msg = NULL, *merged_msg = NULL;
9082 struct collect_commit_logmsg_arg *a = arg;
9083 int initial_content_len;
9084 int fd = -1;
9085 size_t len;
9087 /* if a message was specified on the command line, just use it */
9088 if (a->cmdline_log != NULL && *a->cmdline_log != '\0') {
9089 len = strlen(a->cmdline_log) + 1;
9090 *logmsg = malloc(len + 1);
9091 if (*logmsg == NULL)
9092 return got_error_from_errno("malloc");
9093 strlcpy(*logmsg, a->cmdline_log, len);
9094 return NULL;
9095 } else if (a->prepared_log != NULL && a->non_interactive)
9096 return read_prepared_logmsg(logmsg, a->prepared_log);
9098 if (asprintf(&template, "%s/logmsg", a->worktree_path) == -1)
9099 return got_error_from_errno("asprintf");
9101 err = got_opentemp_named_fd(&a->logmsg_path, &fd, template, "");
9102 if (err)
9103 goto done;
9105 if (a->prepared_log) {
9106 err = read_prepared_logmsg(&prepared_msg, a->prepared_log);
9107 if (err)
9108 goto done;
9109 } else if (a->merged_log) {
9110 err = read_prepared_logmsg(&merged_msg, a->merged_log);
9111 if (err)
9112 goto done;
9115 initial_content_len = asprintf(&initial_content,
9116 "%s%s\n# changes to be committed on branch %s:\n",
9117 prepared_msg ? prepared_msg : "",
9118 merged_msg ? merged_msg : "", a->branch_name);
9119 if (initial_content_len == -1) {
9120 err = got_error_from_errno("asprintf");
9121 goto done;
9124 if (write(fd, initial_content, initial_content_len) == -1) {
9125 err = got_error_from_errno2("write", a->logmsg_path);
9126 goto done;
9129 TAILQ_FOREACH(pe, commitable_paths, entry) {
9130 struct got_commitable *ct = pe->data;
9131 dprintf(fd, "# %c %s\n",
9132 got_commitable_get_status(ct),
9133 got_commitable_get_path(ct));
9136 if (diff_path) {
9137 dprintf(fd, "# detailed changes can be viewed in %s\n",
9138 diff_path);
9141 if (close(fd) == -1) {
9142 err = got_error_from_errno2("close", a->logmsg_path);
9143 goto done;
9145 fd = -1;
9147 err = edit_logmsg(logmsg, a->editor, a->logmsg_path, initial_content,
9148 initial_content_len, a->prepared_log ? 0 : 1);
9149 done:
9150 free(initial_content);
9151 free(template);
9152 free(prepared_msg);
9153 free(merged_msg);
9155 if (fd != -1 && close(fd) == -1 && err == NULL)
9156 err = got_error_from_errno2("close", a->logmsg_path);
9158 /* Editor is done; we can now apply unveil(2) */
9159 if (err == NULL)
9160 err = apply_unveil(a->repo_path, 0, a->worktree_path);
9161 if (err) {
9162 free(*logmsg);
9163 *logmsg = NULL;
9165 return err;
9168 static const struct got_error *
9169 cat_logmsg(FILE *f, struct got_commit_object *commit, const char *idstr,
9170 const char *type, int has_content)
9172 const struct got_error *err = NULL;
9173 char *logmsg = NULL;
9175 err = got_object_commit_get_logmsg(&logmsg, commit);
9176 if (err)
9177 return err;
9179 if (fprintf(f, "%s# log message of %s commit %s:%s",
9180 has_content ? "\n" : "", type, idstr, logmsg) < 0)
9181 err = got_ferror(f, GOT_ERR_IO);
9183 free(logmsg);
9184 return err;
9188 * Lookup "logmsg" references of backed-out and cherrypicked commits
9189 * belonging to the current work tree. If found, and the worktree has
9190 * at least one modified file that was changed in the referenced commit,
9191 * add its log message to a new temporary file at *logmsg_path.
9192 * Add all refs found to matched_refs to be scheduled for removal on
9193 * successful commit.
9195 static const struct got_error *
9196 lookup_logmsg_ref(char **logmsg_path, struct got_pathlist_head *paths,
9197 struct got_reflist_head *matched_refs, struct got_worktree *worktree,
9198 struct got_repository *repo)
9200 const struct got_error *err;
9201 struct got_commit_object *commit = NULL;
9202 struct got_object_id *id = NULL;
9203 struct got_reflist_head refs;
9204 struct got_reflist_entry *re, *re_match;
9205 FILE *f = NULL;
9206 char *uuidstr = NULL;
9207 int added_logmsg = 0;
9209 TAILQ_INIT(&refs);
9211 *logmsg_path = NULL;
9213 err = got_worktree_get_uuid(&uuidstr, worktree);
9214 if (err)
9215 goto done;
9217 err = got_ref_list(&refs, repo, "refs/got/worktree",
9218 got_ref_cmp_by_name, repo);
9219 if (err)
9220 goto done;
9222 TAILQ_FOREACH(re, &refs, entry) {
9223 const char *refname, *type;
9224 struct wt_commitable_path_arg wcpa;
9225 int add_logmsg = 0;
9227 refname = got_ref_get_name(re->ref);
9229 if (strncmp(refname, GOT_WORKTREE_CHERRYPICK_REF_PREFIX,
9230 GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN) == 0) {
9231 refname += GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN + 1;
9232 type = "cherrypicked";
9233 } else if (strncmp(refname, GOT_WORKTREE_BACKOUT_REF_PREFIX,
9234 GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN) == 0) {
9235 refname += GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN + 1;
9236 type = "backed-out";
9237 } else
9238 continue;
9240 if (strncmp(refname, uuidstr, GOT_WORKTREE_UUID_STRLEN) == 0)
9241 refname += GOT_WORKTREE_UUID_STRLEN + 1; /* skip '-' */
9242 else
9243 continue;
9245 err = got_repo_match_object_id(&id, NULL, refname,
9246 GOT_OBJ_TYPE_COMMIT, NULL, repo);
9247 if (err)
9248 goto done;
9250 err = got_object_open_as_commit(&commit, repo, id);
9251 if (err)
9252 goto done;
9254 wcpa.commit_paths = paths;
9255 wcpa.has_changes = &add_logmsg;
9257 err = commit_path_changed_in_worktree(&wcpa, id,
9258 worktree, repo);
9259 if (err)
9260 goto done;
9262 if (add_logmsg) {
9263 if (f == NULL) {
9264 err = got_opentemp_named(logmsg_path, &f,
9265 "got-commit-logmsg", "");
9266 if (err)
9267 goto done;
9269 err = cat_logmsg(f, commit, refname, type,
9270 added_logmsg);
9271 if (err)
9272 goto done;
9273 if (!added_logmsg)
9274 ++added_logmsg;
9276 err = got_reflist_entry_dup(&re_match, re);
9277 if (err)
9278 goto done;
9279 TAILQ_INSERT_HEAD(matched_refs, re_match, entry);
9282 got_object_commit_close(commit);
9283 commit = NULL;
9284 free(id);
9285 id = NULL;
9288 done:
9289 free(id);
9290 free(uuidstr);
9291 got_ref_list_free(&refs);
9292 if (commit)
9293 got_object_commit_close(commit);
9294 if (f && fclose(f) == EOF && err == NULL)
9295 err = got_error_from_errno("fclose");
9296 if (!added_logmsg) {
9297 if (*logmsg_path && unlink(*logmsg_path) != 0 && err == NULL)
9298 err = got_error_from_errno2("unlink", *logmsg_path);
9299 *logmsg_path = NULL;
9301 return err;
9304 static const struct got_error *
9305 cmd_commit(int argc, char *argv[])
9307 const struct got_error *error = NULL;
9308 struct got_worktree *worktree = NULL;
9309 struct got_repository *repo = NULL;
9310 char *cwd = NULL, *id_str = NULL;
9311 struct got_object_id *id = NULL;
9312 const char *logmsg = NULL;
9313 char *prepared_logmsg = NULL, *merged_logmsg = NULL;
9314 struct collect_commit_logmsg_arg cl_arg;
9315 const char *author = NULL;
9316 char *gitconfig_path = NULL, *editor = NULL, *committer = NULL;
9317 int ch, rebase_in_progress, histedit_in_progress, preserve_logmsg = 0;
9318 int allow_bad_symlinks = 0, non_interactive = 0, merge_in_progress = 0;
9319 int show_diff = 1, commit_conflicts = 0;
9320 struct got_pathlist_head paths;
9321 struct got_reflist_head refs;
9322 struct got_reflist_entry *re;
9323 int *pack_fds = NULL;
9325 TAILQ_INIT(&refs);
9326 TAILQ_INIT(&paths);
9327 cl_arg.logmsg_path = NULL;
9329 #ifndef PROFILE
9330 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
9331 "unveil", NULL) == -1)
9332 err(1, "pledge");
9333 #endif
9335 while ((ch = getopt(argc, argv, "A:CF:m:NnS")) != -1) {
9336 switch (ch) {
9337 case 'A':
9338 author = optarg;
9339 error = valid_author(author);
9340 if (error)
9341 return error;
9342 break;
9343 case 'C':
9344 commit_conflicts = 1;
9345 break;
9346 case 'F':
9347 if (logmsg != NULL)
9348 option_conflict('F', 'm');
9349 prepared_logmsg = realpath(optarg, NULL);
9350 if (prepared_logmsg == NULL)
9351 return got_error_from_errno2("realpath",
9352 optarg);
9353 break;
9354 case 'm':
9355 if (prepared_logmsg)
9356 option_conflict('m', 'F');
9357 logmsg = optarg;
9358 break;
9359 case 'N':
9360 non_interactive = 1;
9361 break;
9362 case 'n':
9363 show_diff = 0;
9364 break;
9365 case 'S':
9366 allow_bad_symlinks = 1;
9367 break;
9368 default:
9369 usage_commit();
9370 /* NOTREACHED */
9374 argc -= optind;
9375 argv += optind;
9377 cwd = getcwd(NULL, 0);
9378 if (cwd == NULL) {
9379 error = got_error_from_errno("getcwd");
9380 goto done;
9383 error = got_repo_pack_fds_open(&pack_fds);
9384 if (error != NULL)
9385 goto done;
9387 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
9388 if (error) {
9389 if (error->code == GOT_ERR_NOT_WORKTREE)
9390 error = wrap_not_worktree_error(error, "commit", cwd);
9391 goto done;
9394 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
9395 if (error)
9396 goto done;
9397 if (rebase_in_progress) {
9398 error = got_error(GOT_ERR_REBASING);
9399 goto done;
9402 error = got_worktree_histedit_in_progress(&histedit_in_progress,
9403 worktree);
9404 if (error)
9405 goto done;
9407 error = get_gitconfig_path(&gitconfig_path);
9408 if (error)
9409 goto done;
9410 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
9411 gitconfig_path, pack_fds);
9412 if (error != NULL)
9413 goto done;
9415 error = got_worktree_merge_in_progress(&merge_in_progress, worktree, repo);
9416 if (error)
9417 goto done;
9418 if (merge_in_progress) {
9419 error = got_error(GOT_ERR_MERGE_BUSY);
9420 goto done;
9423 error = get_author(&committer, repo, worktree);
9424 if (error)
9425 goto done;
9427 if (author == NULL)
9428 author = committer;
9431 * unveil(2) traverses exec(2); if an editor is used we have
9432 * to apply unveil after the log message has been written.
9434 if (logmsg == NULL || strlen(logmsg) == 0)
9435 error = get_editor(&editor);
9436 else
9437 error = apply_unveil(got_repo_get_path(repo), 0,
9438 got_worktree_get_root_path(worktree));
9439 if (error)
9440 goto done;
9442 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
9443 if (error)
9444 goto done;
9446 if (prepared_logmsg == NULL) {
9447 error = lookup_logmsg_ref(&merged_logmsg,
9448 argc > 0 ? &paths : NULL, &refs, worktree, repo);
9449 if (error)
9450 goto done;
9453 cl_arg.editor = editor;
9454 cl_arg.cmdline_log = logmsg;
9455 cl_arg.prepared_log = prepared_logmsg;
9456 cl_arg.merged_log = merged_logmsg;
9457 cl_arg.non_interactive = non_interactive;
9458 cl_arg.worktree_path = got_worktree_get_root_path(worktree);
9459 cl_arg.branch_name = got_worktree_get_head_ref_name(worktree);
9460 if (!histedit_in_progress) {
9461 if (strncmp(cl_arg.branch_name, "refs/heads/", 11) != 0) {
9462 error = got_error(GOT_ERR_COMMIT_BRANCH);
9463 goto done;
9465 cl_arg.branch_name += 11;
9467 cl_arg.repo_path = got_repo_get_path(repo);
9468 error = got_worktree_commit(&id, worktree, &paths, author, committer,
9469 allow_bad_symlinks, show_diff, commit_conflicts,
9470 collect_commit_logmsg, &cl_arg, print_status, NULL, repo);
9471 if (error) {
9472 if (error->code != GOT_ERR_COMMIT_MSG_EMPTY &&
9473 cl_arg.logmsg_path != NULL)
9474 preserve_logmsg = 1;
9475 goto done;
9478 error = got_object_id_str(&id_str, id);
9479 if (error)
9480 goto done;
9481 printf("Created commit %s\n", id_str);
9483 TAILQ_FOREACH(re, &refs, entry) {
9484 error = got_ref_delete(re->ref, repo);
9485 if (error)
9486 goto done;
9489 done:
9490 if (preserve_logmsg) {
9491 fprintf(stderr, "%s: log message preserved in %s\n",
9492 getprogname(), cl_arg.logmsg_path);
9493 } else if (cl_arg.logmsg_path && unlink(cl_arg.logmsg_path) == -1 &&
9494 error == NULL)
9495 error = got_error_from_errno2("unlink", cl_arg.logmsg_path);
9496 free(cl_arg.logmsg_path);
9497 if (merged_logmsg && unlink(merged_logmsg) == -1 && error == NULL)
9498 error = got_error_from_errno2("unlink", merged_logmsg);
9499 free(merged_logmsg);
9500 if (repo) {
9501 const struct got_error *close_err = got_repo_close(repo);
9502 if (error == NULL)
9503 error = close_err;
9505 if (worktree)
9506 got_worktree_close(worktree);
9507 if (pack_fds) {
9508 const struct got_error *pack_err =
9509 got_repo_pack_fds_close(pack_fds);
9510 if (error == NULL)
9511 error = pack_err;
9513 got_ref_list_free(&refs);
9514 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
9515 free(cwd);
9516 free(id_str);
9517 free(gitconfig_path);
9518 free(editor);
9519 free(committer);
9520 free(prepared_logmsg);
9521 return error;
9524 __dead static void
9525 usage_send(void)
9527 fprintf(stderr, "usage: %s send [-afqTv] [-b branch] [-d branch] "
9528 "[-r repository-path] [-t tag] [remote-repository]\n",
9529 getprogname());
9530 exit(1);
9533 static void
9534 print_load_info(int print_colored, int print_found, int print_trees,
9535 int ncolored, int nfound, int ntrees)
9537 if (print_colored) {
9538 printf("%d commit%s colored", ncolored,
9539 ncolored == 1 ? "" : "s");
9541 if (print_found) {
9542 printf("%s%d object%s found",
9543 ncolored > 0 ? "; " : "",
9544 nfound, nfound == 1 ? "" : "s");
9546 if (print_trees) {
9547 printf("; %d tree%s scanned", ntrees,
9548 ntrees == 1 ? "" : "s");
9552 struct got_send_progress_arg {
9553 char last_scaled_packsize[FMT_SCALED_STRSIZE];
9554 int verbosity;
9555 int last_ncolored;
9556 int last_nfound;
9557 int last_ntrees;
9558 int loading_done;
9559 int last_ncommits;
9560 int last_nobj_total;
9561 int last_p_deltify;
9562 int last_p_written;
9563 int last_p_sent;
9564 int printed_something;
9565 int sent_something;
9566 struct got_pathlist_head *delete_branches;
9569 static const struct got_error *
9570 send_progress(void *arg, int ncolored, int nfound, int ntrees,
9571 off_t packfile_size, int ncommits, int nobj_total, int nobj_deltify,
9572 int nobj_written, off_t bytes_sent, const char *refname,
9573 const char *errmsg, int success)
9575 struct got_send_progress_arg *a = arg;
9576 char scaled_packsize[FMT_SCALED_STRSIZE];
9577 char scaled_sent[FMT_SCALED_STRSIZE];
9578 int p_deltify = 0, p_written = 0, p_sent = 0;
9579 int print_colored = 0, print_found = 0, print_trees = 0;
9580 int print_searching = 0, print_total = 0;
9581 int print_deltify = 0, print_written = 0, print_sent = 0;
9583 if (a->verbosity < 0)
9584 return NULL;
9586 if (refname) {
9587 const char *status = success ? "accepted" : "rejected";
9589 if (success) {
9590 struct got_pathlist_entry *pe;
9591 TAILQ_FOREACH(pe, a->delete_branches, entry) {
9592 const char *branchname = pe->path;
9593 if (got_path_cmp(branchname, refname,
9594 strlen(branchname), strlen(refname)) == 0) {
9595 status = "deleted";
9596 a->sent_something = 1;
9597 break;
9602 if (a->printed_something)
9603 putchar('\n');
9604 printf("Server has %s %s", status, refname);
9605 if (errmsg)
9606 printf(": %s", errmsg);
9607 a->printed_something = 1;
9608 return NULL;
9611 if (a->last_ncolored != ncolored) {
9612 print_colored = 1;
9613 a->last_ncolored = ncolored;
9616 if (a->last_nfound != nfound) {
9617 print_colored = 1;
9618 print_found = 1;
9619 a->last_nfound = nfound;
9622 if (a->last_ntrees != ntrees) {
9623 print_colored = 1;
9624 print_found = 1;
9625 print_trees = 1;
9626 a->last_ntrees = ntrees;
9629 if ((print_colored || print_found || print_trees) &&
9630 !a->loading_done) {
9631 printf("\r");
9632 print_load_info(print_colored, print_found, print_trees,
9633 ncolored, nfound, ntrees);
9634 a->printed_something = 1;
9635 fflush(stdout);
9636 return NULL;
9637 } else if (!a->loading_done) {
9638 printf("\r");
9639 print_load_info(1, 1, 1, ncolored, nfound, ntrees);
9640 printf("\n");
9641 a->loading_done = 1;
9644 if (fmt_scaled(packfile_size, scaled_packsize) == -1)
9645 return got_error_from_errno("fmt_scaled");
9646 if (fmt_scaled(bytes_sent, scaled_sent) == -1)
9647 return got_error_from_errno("fmt_scaled");
9649 if (a->last_ncommits != ncommits) {
9650 print_searching = 1;
9651 a->last_ncommits = ncommits;
9654 if (a->last_nobj_total != nobj_total) {
9655 print_searching = 1;
9656 print_total = 1;
9657 a->last_nobj_total = nobj_total;
9660 if (packfile_size > 0 && (a->last_scaled_packsize[0] == '\0' ||
9661 strcmp(scaled_packsize, a->last_scaled_packsize)) != 0) {
9662 if (strlcpy(a->last_scaled_packsize, scaled_packsize,
9663 FMT_SCALED_STRSIZE) >= FMT_SCALED_STRSIZE)
9664 return got_error(GOT_ERR_NO_SPACE);
9667 if (nobj_deltify > 0 || nobj_written > 0) {
9668 if (nobj_deltify > 0) {
9669 p_deltify = (nobj_deltify * 100) / nobj_total;
9670 if (p_deltify != a->last_p_deltify) {
9671 a->last_p_deltify = p_deltify;
9672 print_searching = 1;
9673 print_total = 1;
9674 print_deltify = 1;
9677 if (nobj_written > 0) {
9678 p_written = (nobj_written * 100) / nobj_total;
9679 if (p_written != a->last_p_written) {
9680 a->last_p_written = p_written;
9681 print_searching = 1;
9682 print_total = 1;
9683 print_deltify = 1;
9684 print_written = 1;
9689 if (bytes_sent > 0) {
9690 p_sent = (bytes_sent * 100) / packfile_size;
9691 if (p_sent != a->last_p_sent) {
9692 a->last_p_sent = p_sent;
9693 print_searching = 1;
9694 print_total = 1;
9695 print_deltify = 1;
9696 print_written = 1;
9697 print_sent = 1;
9699 a->sent_something = 1;
9702 if (print_searching || print_total || print_deltify || print_written ||
9703 print_sent)
9704 printf("\r");
9705 if (print_searching)
9706 printf("packing %d reference%s", ncommits,
9707 ncommits == 1 ? "" : "s");
9708 if (print_total)
9709 printf("; %d object%s", nobj_total,
9710 nobj_total == 1 ? "" : "s");
9711 if (print_deltify)
9712 printf("; deltify: %d%%", p_deltify);
9713 if (print_sent)
9714 printf("; uploading pack: %*s %d%%", FMT_SCALED_STRSIZE - 2,
9715 scaled_packsize, p_sent);
9716 else if (print_written)
9717 printf("; writing pack: %*s %d%%", FMT_SCALED_STRSIZE - 2,
9718 scaled_packsize, p_written);
9719 if (print_searching || print_total || print_deltify ||
9720 print_written || print_sent) {
9721 a->printed_something = 1;
9722 fflush(stdout);
9724 return NULL;
9727 static const struct got_error *
9728 cmd_send(int argc, char *argv[])
9730 const struct got_error *error = NULL;
9731 char *cwd = NULL, *repo_path = NULL;
9732 const char *remote_name;
9733 char *proto = NULL, *host = NULL, *port = NULL;
9734 char *repo_name = NULL, *server_path = NULL;
9735 const struct got_remote_repo *remotes;
9736 struct got_remote_repo *remote = NULL;
9737 int nremotes, nbranches = 0, ndelete_branches = 0;
9738 struct got_repository *repo = NULL;
9739 struct got_worktree *worktree = NULL;
9740 const struct got_gotconfig *repo_conf = NULL, *worktree_conf = NULL;
9741 struct got_pathlist_head branches;
9742 struct got_pathlist_head tags;
9743 struct got_reflist_head all_branches;
9744 struct got_reflist_head all_tags;
9745 struct got_pathlist_head delete_args;
9746 struct got_pathlist_head delete_branches;
9747 struct got_reflist_entry *re;
9748 struct got_pathlist_entry *pe;
9749 int i, ch, sendfd = -1, sendstatus;
9750 pid_t sendpid = -1;
9751 struct got_send_progress_arg spa;
9752 int verbosity = 0, overwrite_refs = 0;
9753 int send_all_branches = 0, send_all_tags = 0;
9754 struct got_reference *ref = NULL;
9755 int *pack_fds = NULL;
9757 TAILQ_INIT(&branches);
9758 TAILQ_INIT(&tags);
9759 TAILQ_INIT(&all_branches);
9760 TAILQ_INIT(&all_tags);
9761 TAILQ_INIT(&delete_args);
9762 TAILQ_INIT(&delete_branches);
9764 while ((ch = getopt(argc, argv, "ab:d:fqr:Tt:v")) != -1) {
9765 switch (ch) {
9766 case 'a':
9767 send_all_branches = 1;
9768 break;
9769 case 'b':
9770 error = got_pathlist_append(&branches, optarg, NULL);
9771 if (error)
9772 return error;
9773 nbranches++;
9774 break;
9775 case 'd':
9776 error = got_pathlist_append(&delete_args, optarg, NULL);
9777 if (error)
9778 return error;
9779 break;
9780 case 'f':
9781 overwrite_refs = 1;
9782 break;
9783 case 'q':
9784 verbosity = -1;
9785 break;
9786 case 'r':
9787 repo_path = realpath(optarg, NULL);
9788 if (repo_path == NULL)
9789 return got_error_from_errno2("realpath",
9790 optarg);
9791 got_path_strip_trailing_slashes(repo_path);
9792 break;
9793 case 'T':
9794 send_all_tags = 1;
9795 break;
9796 case 't':
9797 error = got_pathlist_append(&tags, optarg, NULL);
9798 if (error)
9799 return error;
9800 break;
9801 case 'v':
9802 if (verbosity < 0)
9803 verbosity = 0;
9804 else if (verbosity < 3)
9805 verbosity++;
9806 break;
9807 default:
9808 usage_send();
9809 /* NOTREACHED */
9812 argc -= optind;
9813 argv += optind;
9815 if (send_all_branches && !TAILQ_EMPTY(&branches))
9816 option_conflict('a', 'b');
9817 if (send_all_tags && !TAILQ_EMPTY(&tags))
9818 option_conflict('T', 't');
9821 if (argc == 0)
9822 remote_name = GOT_SEND_DEFAULT_REMOTE_NAME;
9823 else if (argc == 1)
9824 remote_name = argv[0];
9825 else
9826 usage_send();
9828 cwd = getcwd(NULL, 0);
9829 if (cwd == NULL) {
9830 error = got_error_from_errno("getcwd");
9831 goto done;
9834 error = got_repo_pack_fds_open(&pack_fds);
9835 if (error != NULL)
9836 goto done;
9838 if (repo_path == NULL) {
9839 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
9840 if (error && error->code != GOT_ERR_NOT_WORKTREE)
9841 goto done;
9842 else
9843 error = NULL;
9844 if (worktree) {
9845 repo_path =
9846 strdup(got_worktree_get_repo_path(worktree));
9847 if (repo_path == NULL)
9848 error = got_error_from_errno("strdup");
9849 if (error)
9850 goto done;
9851 } else {
9852 repo_path = strdup(cwd);
9853 if (repo_path == NULL) {
9854 error = got_error_from_errno("strdup");
9855 goto done;
9860 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
9861 if (error)
9862 goto done;
9864 if (worktree) {
9865 worktree_conf = got_worktree_get_gotconfig(worktree);
9866 if (worktree_conf) {
9867 got_gotconfig_get_remotes(&nremotes, &remotes,
9868 worktree_conf);
9869 for (i = 0; i < nremotes; i++) {
9870 if (strcmp(remotes[i].name, remote_name) == 0) {
9871 error = got_repo_remote_repo_dup(&remote,
9872 &remotes[i]);
9873 if (error)
9874 goto done;
9875 break;
9880 if (remote == NULL) {
9881 repo_conf = got_repo_get_gotconfig(repo);
9882 if (repo_conf) {
9883 got_gotconfig_get_remotes(&nremotes, &remotes,
9884 repo_conf);
9885 for (i = 0; i < nremotes; i++) {
9886 if (strcmp(remotes[i].name, remote_name) == 0) {
9887 error = got_repo_remote_repo_dup(&remote,
9888 &remotes[i]);
9889 if (error)
9890 goto done;
9891 break;
9896 if (remote == NULL) {
9897 got_repo_get_gitconfig_remotes(&nremotes, &remotes, repo);
9898 for (i = 0; i < nremotes; i++) {
9899 if (strcmp(remotes[i].name, remote_name) == 0) {
9900 error = got_repo_remote_repo_dup(&remote,
9901 &remotes[i]);
9902 if (error)
9903 goto done;
9904 break;
9908 if (remote == NULL) {
9909 error = got_error_path(remote_name, GOT_ERR_NO_REMOTE);
9910 goto done;
9913 error = got_dial_parse_uri(&proto, &host, &port, &server_path,
9914 &repo_name, remote->send_url);
9915 if (error)
9916 goto done;
9918 if (strcmp(proto, "git") == 0) {
9919 #ifndef PROFILE
9920 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
9921 "sendfd dns inet unveil", NULL) == -1)
9922 err(1, "pledge");
9923 #endif
9924 } else if (strcmp(proto, "git+ssh") == 0 ||
9925 strcmp(proto, "ssh") == 0) {
9926 #ifndef PROFILE
9927 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
9928 "sendfd unveil", NULL) == -1)
9929 err(1, "pledge");
9930 #endif
9931 } else if (strcmp(proto, "http") == 0 ||
9932 strcmp(proto, "git+http") == 0) {
9933 error = got_error_path(proto, GOT_ERR_NOT_IMPL);
9934 goto done;
9935 } else {
9936 error = got_error_path(proto, GOT_ERR_BAD_PROTO);
9937 goto done;
9940 error = got_dial_apply_unveil(proto);
9941 if (error)
9942 goto done;
9944 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
9945 if (error)
9946 goto done;
9948 if (send_all_branches) {
9949 error = got_ref_list(&all_branches, repo, "refs/heads",
9950 got_ref_cmp_by_name, NULL);
9951 if (error)
9952 goto done;
9953 TAILQ_FOREACH(re, &all_branches, entry) {
9954 const char *branchname = got_ref_get_name(re->ref);
9955 error = got_pathlist_append(&branches,
9956 branchname, NULL);
9957 if (error)
9958 goto done;
9959 nbranches++;
9961 } else if (nbranches == 0) {
9962 for (i = 0; i < remote->nsend_branches; i++) {
9963 error = got_pathlist_append(&branches,
9964 remote->send_branches[i], NULL);
9965 if (error)
9966 goto done;
9970 if (send_all_tags) {
9971 error = got_ref_list(&all_tags, repo, "refs/tags",
9972 got_ref_cmp_by_name, NULL);
9973 if (error)
9974 goto done;
9975 TAILQ_FOREACH(re, &all_tags, entry) {
9976 const char *tagname = got_ref_get_name(re->ref);
9977 error = got_pathlist_append(&tags,
9978 tagname, NULL);
9979 if (error)
9980 goto done;
9985 * To prevent accidents only branches in refs/heads/ can be deleted
9986 * with 'got send -d'.
9987 * Deleting anything else requires local repository access or Git.
9989 TAILQ_FOREACH(pe, &delete_args, entry) {
9990 const char *branchname = pe->path;
9991 char *s;
9992 struct got_pathlist_entry *new;
9993 if (strncmp(branchname, "refs/heads/", 11) == 0) {
9994 s = strdup(branchname);
9995 if (s == NULL) {
9996 error = got_error_from_errno("strdup");
9997 goto done;
9999 } else {
10000 if (asprintf(&s, "refs/heads/%s", branchname) == -1) {
10001 error = got_error_from_errno("asprintf");
10002 goto done;
10005 error = got_pathlist_insert(&new, &delete_branches, s, NULL);
10006 if (error || new == NULL /* duplicate */)
10007 free(s);
10008 if (error)
10009 goto done;
10010 ndelete_branches++;
10013 if (nbranches == 0 && ndelete_branches == 0) {
10014 struct got_reference *head_ref;
10015 if (worktree)
10016 error = got_ref_open(&head_ref, repo,
10017 got_worktree_get_head_ref_name(worktree), 0);
10018 else
10019 error = got_ref_open(&head_ref, repo, GOT_REF_HEAD, 0);
10020 if (error)
10021 goto done;
10022 if (got_ref_is_symbolic(head_ref)) {
10023 error = got_ref_resolve_symbolic(&ref, repo, head_ref);
10024 got_ref_close(head_ref);
10025 if (error)
10026 goto done;
10027 } else
10028 ref = head_ref;
10029 error = got_pathlist_append(&branches, got_ref_get_name(ref),
10030 NULL);
10031 if (error)
10032 goto done;
10033 nbranches++;
10036 if (worktree) {
10037 /* Release work tree lock. */
10038 got_worktree_close(worktree);
10039 worktree = NULL;
10042 if (verbosity >= 0) {
10043 printf("Connecting to \"%s\" %s://%s%s%s%s%s\n",
10044 remote->name, proto, host,
10045 port ? ":" : "", port ? port : "",
10046 *server_path == '/' ? "" : "/", server_path);
10049 error = got_send_connect(&sendpid, &sendfd, proto, host, port,
10050 server_path, verbosity);
10051 if (error)
10052 goto done;
10054 memset(&spa, 0, sizeof(spa));
10055 spa.last_scaled_packsize[0] = '\0';
10056 spa.last_p_deltify = -1;
10057 spa.last_p_written = -1;
10058 spa.verbosity = verbosity;
10059 spa.delete_branches = &delete_branches;
10060 error = got_send_pack(remote_name, &branches, &tags, &delete_branches,
10061 verbosity, overwrite_refs, sendfd, repo, send_progress, &spa,
10062 check_cancelled, NULL);
10063 if (spa.printed_something)
10064 putchar('\n');
10065 if (error)
10066 goto done;
10067 if (!spa.sent_something && verbosity >= 0)
10068 printf("Already up-to-date\n");
10069 done:
10070 if (sendpid > 0) {
10071 if (kill(sendpid, SIGTERM) == -1)
10072 error = got_error_from_errno("kill");
10073 if (waitpid(sendpid, &sendstatus, 0) == -1 && error == NULL)
10074 error = got_error_from_errno("waitpid");
10076 if (sendfd != -1 && close(sendfd) == -1 && error == NULL)
10077 error = got_error_from_errno("close");
10078 if (repo) {
10079 const struct got_error *close_err = got_repo_close(repo);
10080 if (error == NULL)
10081 error = close_err;
10083 if (worktree)
10084 got_worktree_close(worktree);
10085 if (pack_fds) {
10086 const struct got_error *pack_err =
10087 got_repo_pack_fds_close(pack_fds);
10088 if (error == NULL)
10089 error = pack_err;
10091 if (ref)
10092 got_ref_close(ref);
10093 got_repo_free_remote_repo_data(remote);
10094 free(remote);
10095 got_pathlist_free(&branches, GOT_PATHLIST_FREE_NONE);
10096 got_pathlist_free(&tags, GOT_PATHLIST_FREE_NONE);
10097 got_ref_list_free(&all_branches);
10098 got_ref_list_free(&all_tags);
10099 got_pathlist_free(&delete_args, GOT_PATHLIST_FREE_NONE);
10100 got_pathlist_free(&delete_branches, GOT_PATHLIST_FREE_PATH);
10101 free(cwd);
10102 free(repo_path);
10103 free(proto);
10104 free(host);
10105 free(port);
10106 free(server_path);
10107 free(repo_name);
10108 return error;
10112 * Print and if delete is set delete all ref_prefix references.
10113 * If wanted_ref is not NULL, only print or delete this reference.
10115 static const struct got_error *
10116 process_logmsg_refs(const char *ref_prefix, size_t prefix_len,
10117 const char *wanted_ref, int delete, struct got_worktree *worktree,
10118 struct got_repository *repo)
10120 const struct got_error *err;
10121 struct got_pathlist_head paths;
10122 struct got_reflist_head refs;
10123 struct got_reflist_entry *re;
10124 struct got_reflist_object_id_map *refs_idmap = NULL;
10125 struct got_commit_object *commit = NULL;
10126 struct got_object_id *id = NULL;
10127 const char *header_prefix;
10128 char *uuidstr = NULL;
10129 int found = 0;
10131 TAILQ_INIT(&refs);
10132 TAILQ_INIT(&paths);
10134 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, repo);
10135 if (err)
10136 goto done;
10138 err = got_reflist_object_id_map_create(&refs_idmap, &refs, repo);
10139 if (err)
10140 goto done;
10142 if (worktree != NULL) {
10143 err = got_worktree_get_uuid(&uuidstr, worktree);
10144 if (err)
10145 goto done;
10148 if (wanted_ref) {
10149 if (strncmp(wanted_ref, "refs/heads/", 11) == 0)
10150 wanted_ref += 11;
10153 if (strcmp(ref_prefix, GOT_WORKTREE_BACKOUT_REF_PREFIX) == 0)
10154 header_prefix = "backout";
10155 else
10156 header_prefix = "cherrypick";
10158 TAILQ_FOREACH(re, &refs, entry) {
10159 const char *refname, *wt;
10161 refname = got_ref_get_name(re->ref);
10163 err = check_cancelled(NULL);
10164 if (err)
10165 goto done;
10167 if (strncmp(refname, ref_prefix, prefix_len) == 0)
10168 refname += prefix_len + 1; /* skip '-' delimiter */
10169 else
10170 continue;
10172 wt = refname;
10174 if (worktree == NULL || strncmp(refname, uuidstr,
10175 GOT_WORKTREE_UUID_STRLEN) == 0)
10176 refname += GOT_WORKTREE_UUID_STRLEN + 1; /* skip '-' */
10177 else
10178 continue;
10180 err = got_repo_match_object_id(&id, NULL, refname,
10181 GOT_OBJ_TYPE_COMMIT, NULL, repo);
10182 if (err)
10183 goto done;
10185 err = got_object_open_as_commit(&commit, repo, id);
10186 if (err)
10187 goto done;
10189 if (wanted_ref)
10190 found = strncmp(wanted_ref, refname,
10191 strlen(wanted_ref)) == 0;
10192 if (wanted_ref && !found) {
10193 struct got_reflist_head *ci_refs;
10195 ci_refs = got_reflist_object_id_map_lookup(refs_idmap,
10196 id);
10198 if (ci_refs) {
10199 char *refs_str = NULL;
10200 char const *r = NULL;
10202 err = build_refs_str(&refs_str, ci_refs, id,
10203 repo, 1);
10204 if (err)
10205 goto done;
10207 r = refs_str;
10208 while (r) {
10209 if (strncmp(r, wanted_ref,
10210 strlen(wanted_ref)) == 0) {
10211 found = 1;
10212 break;
10214 r = strchr(r, ' ');
10215 if (r)
10216 ++r;
10218 free(refs_str);
10222 if (wanted_ref == NULL || found) {
10223 if (delete) {
10224 err = got_ref_delete(re->ref, repo);
10225 if (err)
10226 goto done;
10227 printf("Deleted: ");
10228 err = print_commit_oneline(commit, id, repo,
10229 refs_idmap);
10230 } else {
10232 * Print paths modified by commit to help
10233 * associate commits with worktree changes.
10235 err = get_changed_paths(&paths, commit,
10236 repo, NULL);
10237 if (err)
10238 goto done;
10240 err = print_commit(commit, id, repo, NULL,
10241 &paths, NULL, 0, 0, refs_idmap, NULL,
10242 header_prefix);
10243 got_pathlist_free(&paths,
10244 GOT_PATHLIST_FREE_ALL);
10246 if (worktree == NULL)
10247 printf("work tree: %.*s\n\n",
10248 GOT_WORKTREE_UUID_STRLEN, wt);
10250 if (err || found)
10251 goto done;
10254 got_object_commit_close(commit);
10255 commit = NULL;
10256 free(id);
10257 id = NULL;
10260 if (wanted_ref != NULL && !found)
10261 err = got_error_fmt(GOT_ERR_NOT_REF, "%s", wanted_ref);
10263 done:
10264 free(id);
10265 free(uuidstr);
10266 got_ref_list_free(&refs);
10267 got_pathlist_free(&paths, GOT_PATHLIST_FREE_ALL);
10268 if (refs_idmap)
10269 got_reflist_object_id_map_free(refs_idmap);
10270 if (commit)
10271 got_object_commit_close(commit);
10272 return err;
10276 * Create new temp "logmsg" ref of the backed-out or cherrypicked commit
10277 * identified by id for log messages to prepopulate the editor on commit.
10279 static const struct got_error *
10280 logmsg_ref(struct got_object_id *id, const char *prefix,
10281 struct got_worktree *worktree, struct got_repository *repo)
10283 const struct got_error *err = NULL;
10284 char *idstr, *ref = NULL, *refname = NULL;
10285 int histedit_in_progress;
10286 int rebase_in_progress, merge_in_progress;
10289 * Silenty refuse to create merge reference if any histedit, merge,
10290 * or rebase operation is in progress.
10292 err = got_worktree_histedit_in_progress(&histedit_in_progress,
10293 worktree);
10294 if (err)
10295 return err;
10296 if (histedit_in_progress)
10297 return NULL;
10299 err = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
10300 if (err)
10301 return err;
10302 if (rebase_in_progress)
10303 return NULL;
10305 err = got_worktree_merge_in_progress(&merge_in_progress, worktree,
10306 repo);
10307 if (err)
10308 return err;
10309 if (merge_in_progress)
10310 return NULL;
10312 err = got_object_id_str(&idstr, id);
10313 if (err)
10314 return err;
10316 err = got_worktree_get_logmsg_ref_name(&refname, worktree, prefix);
10317 if (err)
10318 goto done;
10320 if (asprintf(&ref, "%s-%s", refname, idstr) == -1) {
10321 err = got_error_from_errno("asprintf");
10322 goto done;
10325 err = create_ref(ref, got_worktree_get_base_commit_id(worktree),
10326 -1, repo);
10327 done:
10328 free(ref);
10329 free(idstr);
10330 free(refname);
10331 return err;
10334 __dead static void
10335 usage_cherrypick(void)
10337 fprintf(stderr, "usage: %s cherrypick [-lX] [commit-id]\n",
10338 getprogname());
10339 exit(1);
10342 static const struct got_error *
10343 cmd_cherrypick(int argc, char *argv[])
10345 const struct got_error *error = NULL;
10346 struct got_worktree *worktree = NULL;
10347 struct got_repository *repo = NULL;
10348 char *cwd = NULL, *commit_id_str = NULL, *keyword_idstr = NULL;
10349 struct got_object_id *commit_id = NULL;
10350 struct got_commit_object *commit = NULL;
10351 struct got_object_qid *pid;
10352 int ch, list_refs = 0, remove_refs = 0;
10353 struct got_update_progress_arg upa;
10354 int *pack_fds = NULL;
10356 #ifndef PROFILE
10357 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
10358 "unveil", NULL) == -1)
10359 err(1, "pledge");
10360 #endif
10362 while ((ch = getopt(argc, argv, "lX")) != -1) {
10363 switch (ch) {
10364 case 'l':
10365 list_refs = 1;
10366 break;
10367 case 'X':
10368 remove_refs = 1;
10369 break;
10370 default:
10371 usage_cherrypick();
10372 /* NOTREACHED */
10376 argc -= optind;
10377 argv += optind;
10379 if (list_refs || remove_refs) {
10380 if (argc != 0 && argc != 1)
10381 usage_cherrypick();
10382 } else if (argc != 1)
10383 usage_cherrypick();
10384 if (list_refs && remove_refs)
10385 option_conflict('l', 'X');
10387 cwd = getcwd(NULL, 0);
10388 if (cwd == NULL) {
10389 error = got_error_from_errno("getcwd");
10390 goto done;
10393 error = got_repo_pack_fds_open(&pack_fds);
10394 if (error != NULL)
10395 goto done;
10397 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
10398 if (error) {
10399 if (list_refs || remove_refs) {
10400 if (error->code != GOT_ERR_NOT_WORKTREE)
10401 goto done;
10402 } else {
10403 if (error->code == GOT_ERR_NOT_WORKTREE)
10404 error = wrap_not_worktree_error(error,
10405 "cherrypick", cwd);
10406 goto done;
10410 error = got_repo_open(&repo,
10411 worktree ? got_worktree_get_repo_path(worktree) : cwd,
10412 NULL, pack_fds);
10413 if (error != NULL)
10414 goto done;
10416 error = apply_unveil(got_repo_get_path(repo), 0,
10417 worktree ? got_worktree_get_root_path(worktree) : NULL);
10418 if (error)
10419 goto done;
10421 if (list_refs || remove_refs) {
10422 error = process_logmsg_refs(GOT_WORKTREE_CHERRYPICK_REF_PREFIX,
10423 GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN,
10424 argc == 1 ? argv[0] : NULL, remove_refs, worktree, repo);
10425 goto done;
10428 error = got_keyword_to_idstr(&keyword_idstr, argv[0], repo, worktree);
10429 if (error != NULL)
10430 goto done;
10432 error = got_repo_match_object_id(&commit_id, NULL,
10433 keyword_idstr != NULL ? keyword_idstr : argv[0],
10434 GOT_OBJ_TYPE_COMMIT, NULL, repo);
10435 if (error)
10436 goto done;
10437 error = got_object_id_str(&commit_id_str, commit_id);
10438 if (error)
10439 goto done;
10441 error = got_object_open_as_commit(&commit, repo, commit_id);
10442 if (error)
10443 goto done;
10444 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
10445 memset(&upa, 0, sizeof(upa));
10446 error = got_worktree_merge_files(worktree, pid ? &pid->id : NULL,
10447 commit_id, repo, update_progress, &upa, check_cancelled,
10448 NULL);
10449 if (error != NULL)
10450 goto done;
10452 if (upa.did_something) {
10453 error = logmsg_ref(commit_id,
10454 GOT_WORKTREE_CHERRYPICK_REF_PREFIX, worktree, repo);
10455 if (error)
10456 goto done;
10457 printf("Merged commit %s\n", commit_id_str);
10459 print_merge_progress_stats(&upa);
10460 done:
10461 free(cwd);
10462 free(keyword_idstr);
10463 if (commit)
10464 got_object_commit_close(commit);
10465 free(commit_id_str);
10466 if (worktree)
10467 got_worktree_close(worktree);
10468 if (repo) {
10469 const struct got_error *close_err = got_repo_close(repo);
10470 if (error == NULL)
10471 error = close_err;
10473 if (pack_fds) {
10474 const struct got_error *pack_err =
10475 got_repo_pack_fds_close(pack_fds);
10476 if (error == NULL)
10477 error = pack_err;
10480 return error;
10483 __dead static void
10484 usage_backout(void)
10486 fprintf(stderr, "usage: %s backout [-lX] [commit-id]\n", getprogname());
10487 exit(1);
10490 static const struct got_error *
10491 cmd_backout(int argc, char *argv[])
10493 const struct got_error *error = NULL;
10494 struct got_worktree *worktree = NULL;
10495 struct got_repository *repo = NULL;
10496 char *cwd = NULL, *commit_id_str = NULL, *keyword_idstr = NULL;
10497 struct got_object_id *commit_id = NULL;
10498 struct got_commit_object *commit = NULL;
10499 struct got_object_qid *pid;
10500 int ch, list_refs = 0, remove_refs = 0;
10501 struct got_update_progress_arg upa;
10502 int *pack_fds = NULL;
10504 #ifndef PROFILE
10505 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
10506 "unveil", NULL) == -1)
10507 err(1, "pledge");
10508 #endif
10510 while ((ch = getopt(argc, argv, "lX")) != -1) {
10511 switch (ch) {
10512 case 'l':
10513 list_refs = 1;
10514 break;
10515 case 'X':
10516 remove_refs = 1;
10517 break;
10518 default:
10519 usage_backout();
10520 /* NOTREACHED */
10524 argc -= optind;
10525 argv += optind;
10527 if (list_refs || remove_refs) {
10528 if (argc != 0 && argc != 1)
10529 usage_backout();
10530 } else if (argc != 1)
10531 usage_backout();
10532 if (list_refs && remove_refs)
10533 option_conflict('l', 'X');
10535 cwd = getcwd(NULL, 0);
10536 if (cwd == NULL) {
10537 error = got_error_from_errno("getcwd");
10538 goto done;
10541 error = got_repo_pack_fds_open(&pack_fds);
10542 if (error != NULL)
10543 goto done;
10545 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
10546 if (error) {
10547 if (list_refs || remove_refs) {
10548 if (error->code != GOT_ERR_NOT_WORKTREE)
10549 goto done;
10550 } else {
10551 if (error->code == GOT_ERR_NOT_WORKTREE)
10552 error = wrap_not_worktree_error(error,
10553 "backout", cwd);
10554 goto done;
10558 error = got_repo_open(&repo,
10559 worktree ? got_worktree_get_repo_path(worktree) : cwd,
10560 NULL, pack_fds);
10561 if (error != NULL)
10562 goto done;
10564 error = apply_unveil(got_repo_get_path(repo), 0,
10565 worktree ? got_worktree_get_root_path(worktree) : NULL);
10566 if (error)
10567 goto done;
10569 if (list_refs || remove_refs) {
10570 error = process_logmsg_refs(GOT_WORKTREE_BACKOUT_REF_PREFIX,
10571 GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN,
10572 argc == 1 ? argv[0] : NULL, remove_refs, worktree, repo);
10573 goto done;
10576 error = got_keyword_to_idstr(&keyword_idstr, argv[0], repo, worktree);
10577 if (error != NULL)
10578 goto done;
10580 error = got_repo_match_object_id(&commit_id, NULL,
10581 keyword_idstr != NULL ? keyword_idstr : argv[0],
10582 GOT_OBJ_TYPE_COMMIT, NULL, repo);
10583 if (error)
10584 goto done;
10585 error = got_object_id_str(&commit_id_str, commit_id);
10586 if (error)
10587 goto done;
10589 error = got_object_open_as_commit(&commit, repo, commit_id);
10590 if (error)
10591 goto done;
10592 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
10593 if (pid == NULL) {
10594 error = got_error(GOT_ERR_ROOT_COMMIT);
10595 goto done;
10598 memset(&upa, 0, sizeof(upa));
10599 error = got_worktree_merge_files(worktree, commit_id, &pid->id,
10600 repo, update_progress, &upa, check_cancelled, NULL);
10601 if (error != NULL)
10602 goto done;
10604 if (upa.did_something) {
10605 error = logmsg_ref(commit_id, GOT_WORKTREE_BACKOUT_REF_PREFIX,
10606 worktree, repo);
10607 if (error)
10608 goto done;
10609 printf("Backed out commit %s\n", commit_id_str);
10611 print_merge_progress_stats(&upa);
10612 done:
10613 free(cwd);
10614 free(keyword_idstr);
10615 if (commit)
10616 got_object_commit_close(commit);
10617 free(commit_id_str);
10618 if (worktree)
10619 got_worktree_close(worktree);
10620 if (repo) {
10621 const struct got_error *close_err = got_repo_close(repo);
10622 if (error == NULL)
10623 error = close_err;
10625 if (pack_fds) {
10626 const struct got_error *pack_err =
10627 got_repo_pack_fds_close(pack_fds);
10628 if (error == NULL)
10629 error = pack_err;
10631 return error;
10634 __dead static void
10635 usage_rebase(void)
10637 fprintf(stderr, "usage: %s rebase [-aCclX] [branch]\n", getprogname());
10638 exit(1);
10641 static void
10642 trim_logmsg(char *logmsg, int limit)
10644 char *nl;
10645 size_t len;
10647 len = strlen(logmsg);
10648 if (len > limit)
10649 len = limit;
10650 logmsg[len] = '\0';
10651 nl = strchr(logmsg, '\n');
10652 if (nl)
10653 *nl = '\0';
10656 static const struct got_error *
10657 get_short_logmsg(char **logmsg, int limit, struct got_commit_object *commit)
10659 const struct got_error *err;
10660 char *logmsg0 = NULL;
10661 const char *s;
10663 err = got_object_commit_get_logmsg(&logmsg0, commit);
10664 if (err)
10665 return err;
10667 s = logmsg0;
10668 while (isspace((unsigned char)s[0]))
10669 s++;
10671 *logmsg = strdup(s);
10672 if (*logmsg == NULL) {
10673 err = got_error_from_errno("strdup");
10674 goto done;
10677 trim_logmsg(*logmsg, limit);
10678 done:
10679 free(logmsg0);
10680 return err;
10683 static const struct got_error *
10684 show_rebase_merge_conflict(struct got_object_id *id,
10685 struct got_repository *repo)
10687 const struct got_error *err;
10688 struct got_commit_object *commit = NULL;
10689 char *id_str = NULL, *logmsg = NULL;
10691 err = got_object_open_as_commit(&commit, repo, id);
10692 if (err)
10693 return err;
10695 err = got_object_id_str(&id_str, id);
10696 if (err)
10697 goto done;
10699 id_str[12] = '\0';
10701 err = get_short_logmsg(&logmsg, 42, commit);
10702 if (err)
10703 goto done;
10705 printf("%s -> merge conflict: %s\n", id_str, logmsg);
10706 done:
10707 free(id_str);
10708 got_object_commit_close(commit);
10709 free(logmsg);
10710 return err;
10713 static const struct got_error *
10714 show_rebase_progress(struct got_commit_object *commit,
10715 struct got_object_id *old_id, struct got_object_id *new_id)
10717 const struct got_error *err;
10718 char *old_id_str = NULL, *new_id_str = NULL, *logmsg = NULL;
10720 err = got_object_id_str(&old_id_str, old_id);
10721 if (err)
10722 goto done;
10724 if (new_id) {
10725 err = got_object_id_str(&new_id_str, new_id);
10726 if (err)
10727 goto done;
10730 old_id_str[12] = '\0';
10731 if (new_id_str)
10732 new_id_str[12] = '\0';
10734 err = get_short_logmsg(&logmsg, 42, commit);
10735 if (err)
10736 goto done;
10738 printf("%s -> %s: %s\n", old_id_str,
10739 new_id_str ? new_id_str : "no-op change", logmsg);
10740 done:
10741 free(old_id_str);
10742 free(new_id_str);
10743 free(logmsg);
10744 return err;
10747 static const struct got_error *
10748 rebase_complete(struct got_worktree *worktree, struct got_fileindex *fileindex,
10749 struct got_reference *branch, struct got_reference *tmp_branch,
10750 struct got_repository *repo, int create_backup)
10752 printf("Switching work tree to %s\n", got_ref_get_name(branch));
10753 return got_worktree_rebase_complete(worktree, fileindex,
10754 tmp_branch, branch, repo, create_backup);
10757 static const struct got_error *
10758 rebase_commit(struct got_pathlist_head *merged_paths,
10759 struct got_worktree *worktree, struct got_fileindex *fileindex,
10760 struct got_reference *tmp_branch, const char *committer,
10761 struct got_object_id *commit_id, int allow_conflict,
10762 struct got_repository *repo)
10764 const struct got_error *error;
10765 struct got_commit_object *commit;
10766 struct got_object_id *new_commit_id;
10768 error = got_object_open_as_commit(&commit, repo, commit_id);
10769 if (error)
10770 return error;
10772 error = got_worktree_rebase_commit(&new_commit_id, merged_paths,
10773 worktree, fileindex, tmp_branch, committer, commit, commit_id,
10774 allow_conflict, repo);
10775 if (error) {
10776 if (error->code != GOT_ERR_COMMIT_NO_CHANGES)
10777 goto done;
10778 error = show_rebase_progress(commit, commit_id, NULL);
10779 } else {
10780 error = show_rebase_progress(commit, commit_id, new_commit_id);
10781 free(new_commit_id);
10783 done:
10784 got_object_commit_close(commit);
10785 return error;
10788 struct check_path_prefix_arg {
10789 const char *path_prefix;
10790 size_t len;
10791 int errcode;
10794 static const struct got_error *
10795 check_path_prefix_in_diff(void *arg, struct got_blob_object *blob1,
10796 struct got_blob_object *blob2, FILE *f1, FILE *f2,
10797 struct got_object_id *id1, struct got_object_id *id2,
10798 const char *path1, const char *path2,
10799 mode_t mode1, mode_t mode2, struct got_repository *repo)
10801 struct check_path_prefix_arg *a = arg;
10803 if ((path1 && !got_path_is_child(path1, a->path_prefix, a->len)) ||
10804 (path2 && !got_path_is_child(path2, a->path_prefix, a->len)))
10805 return got_error(a->errcode);
10807 return NULL;
10810 static const struct got_error *
10811 check_path_prefix(struct got_object_id *parent_id,
10812 struct got_object_id *commit_id, const char *path_prefix,
10813 int errcode, struct got_repository *repo)
10815 const struct got_error *err;
10816 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
10817 struct got_commit_object *commit = NULL, *parent_commit = NULL;
10818 struct check_path_prefix_arg cpp_arg;
10820 if (got_path_is_root_dir(path_prefix))
10821 return NULL;
10823 err = got_object_open_as_commit(&commit, repo, commit_id);
10824 if (err)
10825 goto done;
10827 err = got_object_open_as_commit(&parent_commit, repo, parent_id);
10828 if (err)
10829 goto done;
10831 err = got_object_open_as_tree(&tree1, repo,
10832 got_object_commit_get_tree_id(parent_commit));
10833 if (err)
10834 goto done;
10836 err = got_object_open_as_tree(&tree2, repo,
10837 got_object_commit_get_tree_id(commit));
10838 if (err)
10839 goto done;
10841 cpp_arg.path_prefix = path_prefix;
10842 while (cpp_arg.path_prefix[0] == '/')
10843 cpp_arg.path_prefix++;
10844 cpp_arg.len = strlen(cpp_arg.path_prefix);
10845 cpp_arg.errcode = errcode;
10846 err = got_diff_tree(tree1, tree2, NULL, NULL, -1, -1, "", "", repo,
10847 check_path_prefix_in_diff, &cpp_arg, 0);
10848 done:
10849 if (tree1)
10850 got_object_tree_close(tree1);
10851 if (tree2)
10852 got_object_tree_close(tree2);
10853 if (commit)
10854 got_object_commit_close(commit);
10855 if (parent_commit)
10856 got_object_commit_close(parent_commit);
10857 return err;
10860 static const struct got_error *
10861 collect_commits(struct got_object_id_queue *commits,
10862 struct got_object_id *initial_commit_id,
10863 struct got_object_id *iter_start_id, struct got_object_id *iter_stop_id,
10864 const char *path_prefix, int path_prefix_errcode,
10865 struct got_repository *repo)
10867 const struct got_error *err = NULL;
10868 struct got_commit_graph *graph = NULL;
10869 struct got_object_id parent_id, commit_id;
10870 struct got_object_qid *qid;
10872 err = got_commit_graph_open(&graph, "/", 1);
10873 if (err)
10874 return err;
10876 err = got_commit_graph_iter_start(graph, iter_start_id, repo,
10877 check_cancelled, NULL);
10878 if (err)
10879 goto done;
10881 memcpy(&commit_id, initial_commit_id, sizeof(commit_id));
10882 while (got_object_id_cmp(&commit_id, iter_stop_id) != 0) {
10883 err = got_commit_graph_iter_next(&parent_id, graph, repo,
10884 check_cancelled, NULL);
10885 if (err) {
10886 if (err->code == GOT_ERR_ITER_COMPLETED) {
10887 err = got_error_msg(GOT_ERR_ANCESTRY,
10888 "ran out of commits to rebase before "
10889 "youngest common ancestor commit has "
10890 "been reached?!?");
10892 goto done;
10893 } else {
10894 err = check_path_prefix(&parent_id, &commit_id,
10895 path_prefix, path_prefix_errcode, repo);
10896 if (err)
10897 goto done;
10899 err = got_object_qid_alloc(&qid, &commit_id);
10900 if (err)
10901 goto done;
10902 STAILQ_INSERT_HEAD(commits, qid, entry);
10904 memcpy(&commit_id, &parent_id, sizeof(commit_id));
10907 done:
10908 got_commit_graph_close(graph);
10909 return err;
10912 static const struct got_error *
10913 get_commit_brief_str(char **brief_str, struct got_commit_object *commit)
10915 const struct got_error *err = NULL;
10916 time_t committer_time;
10917 struct tm tm;
10918 char datebuf[11]; /* YYYY-MM-DD + NUL */
10919 char *author0 = NULL, *author, *smallerthan;
10920 char *logmsg0 = NULL, *logmsg, *newline;
10922 committer_time = got_object_commit_get_committer_time(commit);
10923 if (gmtime_r(&committer_time, &tm) == NULL)
10924 return got_error_from_errno("gmtime_r");
10925 if (strftime(datebuf, sizeof(datebuf), "%G-%m-%d", &tm) == 0)
10926 return got_error(GOT_ERR_NO_SPACE);
10928 author0 = strdup(got_object_commit_get_author(commit));
10929 if (author0 == NULL)
10930 return got_error_from_errno("strdup");
10931 author = author0;
10932 smallerthan = strchr(author, '<');
10933 if (smallerthan && smallerthan[1] != '\0')
10934 author = smallerthan + 1;
10935 author[strcspn(author, "@>")] = '\0';
10937 err = got_object_commit_get_logmsg(&logmsg0, commit);
10938 if (err)
10939 goto done;
10940 logmsg = logmsg0;
10941 while (*logmsg == '\n')
10942 logmsg++;
10943 newline = strchr(logmsg, '\n');
10944 if (newline)
10945 *newline = '\0';
10947 if (asprintf(brief_str, "%s %s %s",
10948 datebuf, author, logmsg) == -1)
10949 err = got_error_from_errno("asprintf");
10950 done:
10951 free(author0);
10952 free(logmsg0);
10953 return err;
10956 static const struct got_error *
10957 delete_backup_ref(struct got_reference *ref, struct got_object_id *id,
10958 struct got_repository *repo)
10960 const struct got_error *err;
10961 char *id_str;
10963 err = got_object_id_str(&id_str, id);
10964 if (err)
10965 return err;
10967 err = got_ref_delete(ref, repo);
10968 if (err)
10969 goto done;
10971 printf("Deleted %s: %s\n", got_ref_get_name(ref), id_str);
10972 done:
10973 free(id_str);
10974 return err;
10977 static const struct got_error *
10978 print_backup_ref(const char *branch_name, const char *new_id_str,
10979 struct got_object_id *old_commit_id, struct got_commit_object *old_commit,
10980 struct got_reflist_object_id_map *refs_idmap,
10981 struct got_repository *repo)
10983 const struct got_error *err = NULL;
10984 struct got_reflist_head *refs;
10985 char *refs_str = NULL;
10986 struct got_object_id *new_commit_id = NULL;
10987 struct got_commit_object *new_commit = NULL;
10988 char *new_commit_brief_str = NULL;
10989 struct got_object_id *yca_id = NULL;
10990 struct got_commit_object *yca_commit = NULL;
10991 char *yca_id_str = NULL, *yca_brief_str = NULL;
10992 char *custom_refs_str;
10994 if (asprintf(&custom_refs_str, "formerly %s", branch_name) == -1)
10995 return got_error_from_errno("asprintf");
10997 err = print_commit(old_commit, old_commit_id, repo, NULL, NULL, NULL,
10998 0, 0, refs_idmap, custom_refs_str, NULL);
10999 if (err)
11000 goto done;
11002 err = got_object_resolve_id_str(&new_commit_id, repo, new_id_str);
11003 if (err)
11004 goto done;
11006 refs = got_reflist_object_id_map_lookup(refs_idmap, new_commit_id);
11007 if (refs) {
11008 err = build_refs_str(&refs_str, refs, new_commit_id, repo, 0);
11009 if (err)
11010 goto done;
11013 err = got_object_open_as_commit(&new_commit, repo, new_commit_id);
11014 if (err)
11015 goto done;
11017 err = get_commit_brief_str(&new_commit_brief_str, new_commit);
11018 if (err)
11019 goto done;
11021 err = got_commit_graph_find_youngest_common_ancestor(&yca_id,
11022 old_commit_id, new_commit_id, 1, 0, repo, check_cancelled, NULL);
11023 if (err)
11024 goto done;
11026 printf("has become commit %s%s%s%s\n %s\n", new_id_str,
11027 refs_str ? " (" : "", refs_str ? refs_str : "",
11028 refs_str ? ")" : "", new_commit_brief_str);
11029 if (yca_id && got_object_id_cmp(yca_id, new_commit_id) != 0 &&
11030 got_object_id_cmp(yca_id, old_commit_id) != 0) {
11031 free(refs_str);
11032 refs_str = NULL;
11034 err = got_object_open_as_commit(&yca_commit, repo, yca_id);
11035 if (err)
11036 goto done;
11038 err = get_commit_brief_str(&yca_brief_str, yca_commit);
11039 if (err)
11040 goto done;
11042 err = got_object_id_str(&yca_id_str, yca_id);
11043 if (err)
11044 goto done;
11046 refs = got_reflist_object_id_map_lookup(refs_idmap, yca_id);
11047 if (refs) {
11048 err = build_refs_str(&refs_str, refs, yca_id, repo, 0);
11049 if (err)
11050 goto done;
11052 printf("history forked at %s%s%s%s\n %s\n",
11053 yca_id_str,
11054 refs_str ? " (" : "", refs_str ? refs_str : "",
11055 refs_str ? ")" : "", yca_brief_str);
11057 done:
11058 free(custom_refs_str);
11059 free(new_commit_id);
11060 free(refs_str);
11061 free(yca_id);
11062 free(yca_id_str);
11063 free(yca_brief_str);
11064 if (new_commit)
11065 got_object_commit_close(new_commit);
11066 if (yca_commit)
11067 got_object_commit_close(yca_commit);
11069 return err;
11072 static const struct got_error *
11073 worktree_has_logmsg_ref(const char *caller, struct got_worktree *worktree,
11074 struct got_repository *repo)
11076 const struct got_error *err;
11077 struct got_reflist_head refs;
11078 struct got_reflist_entry *re;
11079 char *uuidstr = NULL;
11080 static char msg[160];
11082 TAILQ_INIT(&refs);
11084 err = got_worktree_get_uuid(&uuidstr, worktree);
11085 if (err)
11086 goto done;
11088 err = got_ref_list(&refs, repo, "refs/got/worktree",
11089 got_ref_cmp_by_name, repo);
11090 if (err)
11091 goto done;
11093 TAILQ_FOREACH(re, &refs, entry) {
11094 const char *cmd, *refname, *type;
11096 refname = got_ref_get_name(re->ref);
11098 if (strncmp(refname, GOT_WORKTREE_CHERRYPICK_REF_PREFIX,
11099 GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN) == 0) {
11100 refname += GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN + 1;
11101 cmd = "cherrypick";
11102 type = "cherrypicked";
11103 } else if (strncmp(refname, GOT_WORKTREE_BACKOUT_REF_PREFIX,
11104 GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN) == 0) {
11105 refname += GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN + 1;
11106 cmd = "backout";
11107 type = "backed-out";
11108 } else
11109 continue;
11111 if (strncmp(refname, uuidstr, GOT_WORKTREE_UUID_STRLEN) != 0)
11112 continue;
11114 snprintf(msg, sizeof(msg),
11115 "work tree has references created by %s commits which "
11116 "must be removed with 'got %s -X' before running the %s "
11117 "command", type, cmd, caller);
11118 err = got_error_msg(GOT_ERR_WORKTREE_META, msg);
11119 goto done;
11122 done:
11123 free(uuidstr);
11124 got_ref_list_free(&refs);
11125 return err;
11128 static const struct got_error *
11129 process_backup_refs(const char *backup_ref_prefix,
11130 const char *wanted_branch_name,
11131 int delete, struct got_repository *repo)
11133 const struct got_error *err;
11134 struct got_reflist_head refs, backup_refs;
11135 struct got_reflist_entry *re;
11136 const size_t backup_ref_prefix_len = strlen(backup_ref_prefix);
11137 struct got_object_id *old_commit_id = NULL;
11138 char *branch_name = NULL;
11139 struct got_commit_object *old_commit = NULL;
11140 struct got_reflist_object_id_map *refs_idmap = NULL;
11141 int wanted_branch_found = 0;
11143 TAILQ_INIT(&refs);
11144 TAILQ_INIT(&backup_refs);
11146 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
11147 if (err)
11148 return err;
11150 err = got_reflist_object_id_map_create(&refs_idmap, &refs, repo);
11151 if (err)
11152 goto done;
11154 if (wanted_branch_name) {
11155 if (strncmp(wanted_branch_name, "refs/heads/", 11) == 0)
11156 wanted_branch_name += 11;
11159 err = got_ref_list(&backup_refs, repo, backup_ref_prefix,
11160 got_ref_cmp_by_commit_timestamp_descending, repo);
11161 if (err)
11162 goto done;
11164 TAILQ_FOREACH(re, &backup_refs, entry) {
11165 const char *refname = got_ref_get_name(re->ref);
11166 char *slash;
11168 err = check_cancelled(NULL);
11169 if (err)
11170 break;
11172 err = got_ref_resolve(&old_commit_id, repo, re->ref);
11173 if (err)
11174 break;
11176 err = got_object_open_as_commit(&old_commit, repo,
11177 old_commit_id);
11178 if (err)
11179 break;
11181 if (strncmp(backup_ref_prefix, refname,
11182 backup_ref_prefix_len) == 0)
11183 refname += backup_ref_prefix_len;
11185 while (refname[0] == '/')
11186 refname++;
11188 branch_name = strdup(refname);
11189 if (branch_name == NULL) {
11190 err = got_error_from_errno("strdup");
11191 break;
11193 slash = strrchr(branch_name, '/');
11194 if (slash) {
11195 *slash = '\0';
11196 refname += strlen(branch_name) + 1;
11199 if (wanted_branch_name == NULL ||
11200 strcmp(wanted_branch_name, branch_name) == 0) {
11201 wanted_branch_found = 1;
11202 if (delete) {
11203 err = delete_backup_ref(re->ref,
11204 old_commit_id, repo);
11205 } else {
11206 err = print_backup_ref(branch_name, refname,
11207 old_commit_id, old_commit, refs_idmap,
11208 repo);
11210 if (err)
11211 break;
11214 free(old_commit_id);
11215 old_commit_id = NULL;
11216 free(branch_name);
11217 branch_name = NULL;
11218 got_object_commit_close(old_commit);
11219 old_commit = NULL;
11222 if (wanted_branch_name && !wanted_branch_found) {
11223 err = got_error_fmt(GOT_ERR_NOT_REF,
11224 "%s/%s/", backup_ref_prefix, wanted_branch_name);
11226 done:
11227 if (refs_idmap)
11228 got_reflist_object_id_map_free(refs_idmap);
11229 got_ref_list_free(&refs);
11230 got_ref_list_free(&backup_refs);
11231 free(old_commit_id);
11232 free(branch_name);
11233 if (old_commit)
11234 got_object_commit_close(old_commit);
11235 return err;
11238 static const struct got_error *
11239 abort_progress(void *arg, unsigned char status, const char *path)
11242 * Unversioned files should not clutter progress output when
11243 * an operation is aborted.
11245 if (status == GOT_STATUS_UNVERSIONED)
11246 return NULL;
11248 return update_progress(arg, status, path);
11251 static const struct got_error *
11252 find_merge_commit_yca(struct got_object_id **new_yca_id,
11253 struct got_object_id *branch_head_commit_id,
11254 struct got_object_id *yca_id,
11255 struct got_object_id *base_commit_id,
11256 struct got_repository *repo)
11258 const struct got_error *err = NULL;
11259 struct got_commit_graph *graph = NULL;
11260 struct got_commit_object *commit = NULL;
11262 *new_yca_id = NULL;
11264 err = got_commit_graph_open(&graph, "/", 1);
11265 if (err)
11266 return err;
11268 err = got_commit_graph_iter_start(graph, base_commit_id,
11269 repo, check_cancelled, NULL);
11270 if (err)
11271 goto done;
11273 for (;;) {
11274 struct got_object_id id;
11276 err = got_commit_graph_iter_next(&id, graph, repo,
11277 check_cancelled, NULL);
11278 if (err) {
11279 if (err->code == GOT_ERR_ITER_COMPLETED)
11280 err = NULL;
11281 break;
11284 err = got_object_open_as_commit(&commit, repo, &id);
11285 if (err)
11286 break;
11288 if (got_object_commit_get_nparents(commit) > 1) {
11289 /* Search for a better YCA using toposort. */
11290 err = got_commit_graph_find_youngest_common_ancestor(
11291 new_yca_id, base_commit_id, branch_head_commit_id,
11292 0, 1, repo, check_cancelled, NULL);
11293 break;
11296 if (got_object_id_cmp(&id, yca_id) == 0)
11297 break;
11298 got_object_commit_close(commit);
11299 commit = NULL;
11301 done:
11302 got_commit_graph_close(graph);
11303 if (commit)
11304 got_object_commit_close(commit);
11305 return err;
11308 static const struct got_error *
11309 cmd_rebase(int argc, char *argv[])
11311 const struct got_error *error = NULL;
11312 struct got_worktree *worktree = NULL;
11313 struct got_repository *repo = NULL;
11314 struct got_fileindex *fileindex = NULL;
11315 char *cwd = NULL, *committer = NULL, *gitconfig_path = NULL;
11316 struct got_reference *branch = NULL;
11317 struct got_reference *new_base_branch = NULL, *tmp_branch = NULL;
11318 struct got_object_id *commit_id = NULL, *parent_id = NULL;
11319 struct got_object_id *resume_commit_id = NULL;
11320 struct got_object_id *branch_head_commit_id = NULL, *yca_id = NULL;
11321 struct got_object_id *head_commit_id = NULL;
11322 struct got_reference *head_ref = NULL;
11323 struct got_commit_object *commit = NULL;
11324 int ch, rebase_in_progress = 0, abort_rebase = 0, continue_rebase = 0;
11325 int histedit_in_progress = 0, merge_in_progress = 0;
11326 int create_backup = 1, list_backups = 0, delete_backups = 0;
11327 int allow_conflict = 0;
11328 struct got_object_id_queue commits;
11329 struct got_pathlist_head merged_paths;
11330 const struct got_object_id_queue *parent_ids;
11331 struct got_object_qid *qid, *pid;
11332 struct got_update_progress_arg upa;
11333 int *pack_fds = NULL;
11335 STAILQ_INIT(&commits);
11336 TAILQ_INIT(&merged_paths);
11337 memset(&upa, 0, sizeof(upa));
11339 #ifndef PROFILE
11340 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
11341 "unveil", NULL) == -1)
11342 err(1, "pledge");
11343 #endif
11345 while ((ch = getopt(argc, argv, "aCclX")) != -1) {
11346 switch (ch) {
11347 case 'a':
11348 abort_rebase = 1;
11349 break;
11350 case 'C':
11351 allow_conflict = 1;
11352 break;
11353 case 'c':
11354 continue_rebase = 1;
11355 break;
11356 case 'l':
11357 list_backups = 1;
11358 break;
11359 case 'X':
11360 delete_backups = 1;
11361 break;
11362 default:
11363 usage_rebase();
11364 /* NOTREACHED */
11368 argc -= optind;
11369 argv += optind;
11371 if (list_backups) {
11372 if (abort_rebase)
11373 option_conflict('l', 'a');
11374 if (allow_conflict)
11375 option_conflict('l', 'C');
11376 if (continue_rebase)
11377 option_conflict('l', 'c');
11378 if (delete_backups)
11379 option_conflict('l', 'X');
11380 if (argc != 0 && argc != 1)
11381 usage_rebase();
11382 } else if (delete_backups) {
11383 if (abort_rebase)
11384 option_conflict('X', 'a');
11385 if (allow_conflict)
11386 option_conflict('X', 'C');
11387 if (continue_rebase)
11388 option_conflict('X', 'c');
11389 if (list_backups)
11390 option_conflict('l', 'X');
11391 if (argc != 0 && argc != 1)
11392 usage_rebase();
11393 } else if (allow_conflict) {
11394 if (abort_rebase)
11395 option_conflict('C', 'a');
11396 if (!continue_rebase)
11397 errx(1, "-C option requires -c");
11398 } else {
11399 if (abort_rebase && continue_rebase)
11400 usage_rebase();
11401 else if (abort_rebase || continue_rebase) {
11402 if (argc != 0)
11403 usage_rebase();
11404 } else if (argc != 1)
11405 usage_rebase();
11408 cwd = getcwd(NULL, 0);
11409 if (cwd == NULL) {
11410 error = got_error_from_errno("getcwd");
11411 goto done;
11414 error = got_repo_pack_fds_open(&pack_fds);
11415 if (error != NULL)
11416 goto done;
11418 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
11419 if (error) {
11420 if (list_backups || delete_backups) {
11421 if (error->code != GOT_ERR_NOT_WORKTREE)
11422 goto done;
11423 } else {
11424 if (error->code == GOT_ERR_NOT_WORKTREE)
11425 error = wrap_not_worktree_error(error,
11426 "rebase", cwd);
11427 goto done;
11431 error = get_gitconfig_path(&gitconfig_path);
11432 if (error)
11433 goto done;
11434 error = got_repo_open(&repo,
11435 worktree ? got_worktree_get_repo_path(worktree) : cwd,
11436 gitconfig_path, pack_fds);
11437 if (error != NULL)
11438 goto done;
11440 if (worktree != NULL && !list_backups && !delete_backups) {
11441 error = worktree_has_logmsg_ref("rebase", worktree, repo);
11442 if (error)
11443 goto done;
11446 error = get_author(&committer, repo, worktree);
11447 if (error && error->code != GOT_ERR_COMMIT_NO_AUTHOR)
11448 goto done;
11450 error = apply_unveil(got_repo_get_path(repo), 0,
11451 worktree ? got_worktree_get_root_path(worktree) : NULL);
11452 if (error)
11453 goto done;
11455 if (list_backups || delete_backups) {
11456 error = process_backup_refs(
11457 GOT_WORKTREE_REBASE_BACKUP_REF_PREFIX,
11458 argc == 1 ? argv[0] : NULL, delete_backups, repo);
11459 goto done; /* nothing else to do */
11462 error = got_worktree_histedit_in_progress(&histedit_in_progress,
11463 worktree);
11464 if (error)
11465 goto done;
11466 if (histedit_in_progress) {
11467 error = got_error(GOT_ERR_HISTEDIT_BUSY);
11468 goto done;
11471 error = got_worktree_merge_in_progress(&merge_in_progress,
11472 worktree, repo);
11473 if (error)
11474 goto done;
11475 if (merge_in_progress) {
11476 error = got_error(GOT_ERR_MERGE_BUSY);
11477 goto done;
11480 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
11481 if (error)
11482 goto done;
11484 if (abort_rebase) {
11485 if (!rebase_in_progress) {
11486 error = got_error(GOT_ERR_NOT_REBASING);
11487 goto done;
11489 error = got_worktree_rebase_continue(&resume_commit_id,
11490 &new_base_branch, &tmp_branch, &branch, &fileindex,
11491 worktree, repo);
11492 if (error)
11493 goto done;
11494 printf("Switching work tree to %s\n",
11495 got_ref_get_symref_target(new_base_branch));
11496 error = got_worktree_rebase_abort(worktree, fileindex, repo,
11497 new_base_branch, abort_progress, &upa);
11498 if (error)
11499 goto done;
11500 printf("Rebase of %s aborted\n", got_ref_get_name(branch));
11501 print_merge_progress_stats(&upa);
11502 goto done; /* nothing else to do */
11505 if (continue_rebase) {
11506 if (!rebase_in_progress) {
11507 error = got_error(GOT_ERR_NOT_REBASING);
11508 goto done;
11510 error = got_worktree_rebase_continue(&resume_commit_id,
11511 &new_base_branch, &tmp_branch, &branch, &fileindex,
11512 worktree, repo);
11513 if (error)
11514 goto done;
11516 error = rebase_commit(NULL, worktree, fileindex, tmp_branch,
11517 committer, resume_commit_id, allow_conflict, repo);
11518 if (error)
11519 goto done;
11521 yca_id = got_object_id_dup(resume_commit_id);
11522 if (yca_id == NULL) {
11523 error = got_error_from_errno("got_object_id_dup");
11524 goto done;
11526 } else {
11527 error = got_ref_open(&branch, repo, argv[0], 0);
11528 if (error != NULL)
11529 goto done;
11530 if (strncmp(got_ref_get_name(branch), "refs/heads/", 11) != 0) {
11531 error = got_error_msg(GOT_ERR_COMMIT_BRANCH,
11532 "will not rebase a branch which lives outside "
11533 "the \"refs/heads/\" reference namespace");
11534 goto done;
11538 error = got_ref_resolve(&branch_head_commit_id, repo, branch);
11539 if (error)
11540 goto done;
11542 if (!continue_rebase) {
11543 struct got_object_id *base_commit_id;
11545 error = got_ref_open(&head_ref, repo,
11546 got_worktree_get_head_ref_name(worktree), 0);
11547 if (error)
11548 goto done;
11549 error = got_ref_resolve(&head_commit_id, repo, head_ref);
11550 if (error)
11551 goto done;
11552 base_commit_id = got_worktree_get_base_commit_id(worktree);
11553 if (got_object_id_cmp(base_commit_id, head_commit_id) != 0) {
11554 error = got_error(GOT_ERR_REBASE_OUT_OF_DATE);
11555 goto done;
11558 error = got_commit_graph_find_youngest_common_ancestor(&yca_id,
11559 base_commit_id, branch_head_commit_id, 1, 0,
11560 repo, check_cancelled, NULL);
11561 if (error) {
11562 if (error->code == GOT_ERR_ANCESTRY) {
11563 error = got_error_msg(GOT_ERR_ANCESTRY,
11564 "specified branch shares no common "
11565 "ancestry with work tree's branch");
11567 goto done;
11571 * If a merge commit appears between the new base branch tip
11572 * and a YCA found via first-parent traversal then we might
11573 * find a better YCA using topologically sorted commits.
11575 if (got_object_id_cmp(base_commit_id, yca_id) != 0) {
11576 struct got_object_id *better_yca_id;
11577 error = find_merge_commit_yca(&better_yca_id,
11578 branch_head_commit_id, yca_id,
11579 base_commit_id, repo);
11580 if (error)
11581 goto done;
11582 if (better_yca_id) {
11583 free(yca_id);
11584 yca_id = better_yca_id;
11588 if (got_object_id_cmp(base_commit_id, yca_id) == 0) {
11589 struct got_pathlist_head paths;
11590 printf("%s is already based on %s\n",
11591 got_ref_get_name(branch),
11592 got_worktree_get_head_ref_name(worktree));
11593 error = switch_head_ref(branch, branch_head_commit_id,
11594 worktree, repo);
11595 if (error)
11596 goto done;
11597 error = got_worktree_set_base_commit_id(worktree, repo,
11598 branch_head_commit_id);
11599 if (error)
11600 goto done;
11601 TAILQ_INIT(&paths);
11602 error = got_pathlist_append(&paths, "", NULL);
11603 if (error)
11604 goto done;
11605 error = got_worktree_checkout_files(worktree,
11606 &paths, repo, update_progress, &upa,
11607 check_cancelled, NULL);
11608 got_pathlist_free(&paths, GOT_PATHLIST_FREE_NONE);
11609 if (error)
11610 goto done;
11611 if (upa.did_something) {
11612 char *id_str;
11613 error = got_object_id_str(&id_str,
11614 branch_head_commit_id);
11615 if (error)
11616 goto done;
11617 printf("Updated to %s: %s\n",
11618 got_worktree_get_head_ref_name(worktree),
11619 id_str);
11620 free(id_str);
11621 } else
11622 printf("Already up-to-date\n");
11623 print_update_progress_stats(&upa);
11624 goto done;
11628 commit_id = branch_head_commit_id;
11629 error = got_object_open_as_commit(&commit, repo, commit_id);
11630 if (error)
11631 goto done;
11633 parent_ids = got_object_commit_get_parent_ids(commit);
11634 pid = STAILQ_FIRST(parent_ids);
11635 if (pid) {
11636 error = collect_commits(&commits, commit_id, &pid->id,
11637 yca_id, got_worktree_get_path_prefix(worktree),
11638 GOT_ERR_REBASE_PATH, repo);
11639 if (error)
11640 goto done;
11643 got_object_commit_close(commit);
11644 commit = NULL;
11646 if (!continue_rebase) {
11647 error = got_worktree_rebase_prepare(&new_base_branch,
11648 &tmp_branch, &fileindex, worktree, branch, repo);
11649 if (error)
11650 goto done;
11653 if (STAILQ_EMPTY(&commits)) {
11654 if (continue_rebase) {
11655 error = rebase_complete(worktree, fileindex,
11656 branch, tmp_branch, repo, create_backup);
11657 goto done;
11658 } else {
11659 /* Fast-forward the reference of the branch. */
11660 struct got_object_id *new_head_commit_id;
11661 char *id_str;
11662 error = got_ref_resolve(&new_head_commit_id, repo,
11663 new_base_branch);
11664 if (error)
11665 goto done;
11666 error = got_object_id_str(&id_str, new_head_commit_id);
11667 if (error)
11668 goto done;
11669 printf("Forwarding %s to commit %s\n",
11670 got_ref_get_name(branch), id_str);
11671 free(id_str);
11672 error = got_ref_change_ref(branch,
11673 new_head_commit_id);
11674 if (error)
11675 goto done;
11676 /* No backup needed since objects did not change. */
11677 create_backup = 0;
11681 pid = NULL;
11682 STAILQ_FOREACH(qid, &commits, entry) {
11684 commit_id = &qid->id;
11685 parent_id = pid ? &pid->id : yca_id;
11686 pid = qid;
11688 memset(&upa, 0, sizeof(upa));
11689 error = got_worktree_rebase_merge_files(&merged_paths,
11690 worktree, fileindex, parent_id, commit_id, repo,
11691 update_progress, &upa, check_cancelled, NULL);
11692 if (error)
11693 goto done;
11695 print_merge_progress_stats(&upa);
11696 if (upa.conflicts > 0 || upa.missing > 0 ||
11697 upa.not_deleted > 0 || upa.unversioned > 0) {
11698 if (upa.conflicts > 0) {
11699 error = show_rebase_merge_conflict(&qid->id,
11700 repo);
11701 if (error)
11702 goto done;
11704 got_pathlist_free(&merged_paths, GOT_PATHLIST_FREE_PATH);
11705 break;
11708 error = rebase_commit(&merged_paths, worktree, fileindex,
11709 tmp_branch, committer, commit_id, 0, repo);
11710 got_pathlist_free(&merged_paths, GOT_PATHLIST_FREE_PATH);
11711 if (error)
11712 goto done;
11715 if (upa.conflicts > 0 || upa.missing > 0 ||
11716 upa.not_deleted > 0 || upa.unversioned > 0) {
11717 error = got_worktree_rebase_postpone(worktree, fileindex);
11718 if (error)
11719 goto done;
11720 if (upa.conflicts > 0 && upa.missing == 0 &&
11721 upa.not_deleted == 0 && upa.unversioned == 0) {
11722 error = got_error_msg(GOT_ERR_CONFLICTS,
11723 "conflicts must be resolved before rebasing "
11724 "can continue");
11725 } else if (upa.conflicts > 0) {
11726 error = got_error_msg(GOT_ERR_CONFLICTS,
11727 "conflicts must be resolved before rebasing "
11728 "can continue; changes destined for some "
11729 "files were not yet merged and should be "
11730 "merged manually if required before the "
11731 "rebase operation is continued");
11732 } else {
11733 error = got_error_msg(GOT_ERR_CONFLICTS,
11734 "changes destined for some files were not "
11735 "yet merged and should be merged manually "
11736 "if required before the rebase operation "
11737 "is continued");
11739 } else
11740 error = rebase_complete(worktree, fileindex, branch,
11741 tmp_branch, repo, create_backup);
11742 done:
11743 free(cwd);
11744 free(committer);
11745 free(gitconfig_path);
11746 got_object_id_queue_free(&commits);
11747 free(branch_head_commit_id);
11748 free(resume_commit_id);
11749 free(head_commit_id);
11750 free(yca_id);
11751 if (commit)
11752 got_object_commit_close(commit);
11753 if (branch)
11754 got_ref_close(branch);
11755 if (new_base_branch)
11756 got_ref_close(new_base_branch);
11757 if (tmp_branch)
11758 got_ref_close(tmp_branch);
11759 if (head_ref)
11760 got_ref_close(head_ref);
11761 if (worktree)
11762 got_worktree_close(worktree);
11763 if (repo) {
11764 const struct got_error *close_err = got_repo_close(repo);
11765 if (error == NULL)
11766 error = close_err;
11768 if (pack_fds) {
11769 const struct got_error *pack_err =
11770 got_repo_pack_fds_close(pack_fds);
11771 if (error == NULL)
11772 error = pack_err;
11774 return error;
11777 __dead static void
11778 usage_histedit(void)
11780 fprintf(stderr, "usage: %s histedit [-aCcdeflmX] [-F histedit-script] "
11781 "[branch]\n", getprogname());
11782 exit(1);
11785 #define GOT_HISTEDIT_PICK 'p'
11786 #define GOT_HISTEDIT_EDIT 'e'
11787 #define GOT_HISTEDIT_FOLD 'f'
11788 #define GOT_HISTEDIT_DROP 'd'
11789 #define GOT_HISTEDIT_MESG 'm'
11791 static const struct got_histedit_cmd {
11792 unsigned char code;
11793 const char *name;
11794 const char *desc;
11795 } got_histedit_cmds[] = {
11796 { GOT_HISTEDIT_PICK, "pick", "use commit" },
11797 { GOT_HISTEDIT_EDIT, "edit", "use commit but stop for amending" },
11798 { GOT_HISTEDIT_FOLD, "fold", "combine with next commit that will "
11799 "be used" },
11800 { GOT_HISTEDIT_DROP, "drop", "remove commit from history" },
11801 { GOT_HISTEDIT_MESG, "mesg", "open editor to edit the log message" },
11804 struct got_histedit_list_entry {
11805 TAILQ_ENTRY(got_histedit_list_entry) entry;
11806 struct got_object_id *commit_id;
11807 const struct got_histedit_cmd *cmd;
11808 char *logmsg;
11810 TAILQ_HEAD(got_histedit_list, got_histedit_list_entry);
11812 static const struct got_error *
11813 histedit_write_commit(struct got_object_id *commit_id, const char *cmdname,
11814 FILE *f, struct got_repository *repo)
11816 const struct got_error *err = NULL;
11817 char *logmsg = NULL, *id_str = NULL;
11818 struct got_commit_object *commit = NULL;
11819 int n;
11821 err = got_object_open_as_commit(&commit, repo, commit_id);
11822 if (err)
11823 goto done;
11825 err = get_short_logmsg(&logmsg, 34, commit);
11826 if (err)
11827 goto done;
11829 err = got_object_id_str(&id_str, commit_id);
11830 if (err)
11831 goto done;
11833 n = fprintf(f, "%s %s %s\n", cmdname, id_str, logmsg);
11834 if (n < 0)
11835 err = got_ferror(f, GOT_ERR_IO);
11836 done:
11837 if (commit)
11838 got_object_commit_close(commit);
11839 free(id_str);
11840 free(logmsg);
11841 return err;
11844 static const struct got_error *
11845 histedit_write_commit_list(struct got_object_id_queue *commits,
11846 FILE *f, int edit_logmsg_only, int fold_only, int drop_only,
11847 int edit_only, struct got_repository *repo)
11849 const struct got_error *err = NULL;
11850 struct got_object_qid *qid;
11851 const char *histedit_cmd = NULL;
11853 if (STAILQ_EMPTY(commits))
11854 return got_error(GOT_ERR_EMPTY_HISTEDIT);
11856 STAILQ_FOREACH(qid, commits, entry) {
11857 histedit_cmd = got_histedit_cmds[0].name;
11858 if (drop_only)
11859 histedit_cmd = "drop";
11860 else if (edit_only)
11861 histedit_cmd = "edit";
11862 else if (fold_only && STAILQ_NEXT(qid, entry) != NULL)
11863 histedit_cmd = "fold";
11864 else if (edit_logmsg_only)
11865 histedit_cmd = "mesg";
11866 err = histedit_write_commit(&qid->id, histedit_cmd, f, repo);
11867 if (err)
11868 break;
11871 return err;
11874 static const struct got_error *
11875 write_cmd_list(FILE *f, const char *branch_name,
11876 struct got_object_id_queue *commits)
11878 const struct got_error *err = NULL;
11879 size_t i;
11880 int n;
11881 char *id_str;
11882 struct got_object_qid *qid;
11884 qid = STAILQ_FIRST(commits);
11885 err = got_object_id_str(&id_str, &qid->id);
11886 if (err)
11887 return err;
11889 n = fprintf(f,
11890 "# Editing the history of branch '%s' starting at\n"
11891 "# commit %s\n"
11892 "# Commits will be processed in order from top to "
11893 "bottom of this file.\n", branch_name, id_str);
11894 if (n < 0) {
11895 err = got_ferror(f, GOT_ERR_IO);
11896 goto done;
11899 n = fprintf(f, "# Available histedit commands:\n");
11900 if (n < 0) {
11901 err = got_ferror(f, GOT_ERR_IO);
11902 goto done;
11905 for (i = 0; i < nitems(got_histedit_cmds); i++) {
11906 const struct got_histedit_cmd *cmd = &got_histedit_cmds[i];
11907 n = fprintf(f, "# %s (%c): %s\n", cmd->name, cmd->code,
11908 cmd->desc);
11909 if (n < 0) {
11910 err = got_ferror(f, GOT_ERR_IO);
11911 break;
11914 done:
11915 free(id_str);
11916 return err;
11919 static const struct got_error *
11920 histedit_syntax_error(int lineno)
11922 static char msg[42];
11923 int ret;
11925 ret = snprintf(msg, sizeof(msg), "histedit syntax error on line %d",
11926 lineno);
11927 if (ret < 0 || (size_t)ret >= sizeof(msg))
11928 return got_error(GOT_ERR_HISTEDIT_SYNTAX);
11930 return got_error_msg(GOT_ERR_HISTEDIT_SYNTAX, msg);
11933 static const struct got_error *
11934 append_folded_commit_msg(char **new_msg, struct got_histedit_list_entry *hle,
11935 char *logmsg, struct got_repository *repo)
11937 const struct got_error *err;
11938 struct got_commit_object *folded_commit = NULL;
11939 char *id_str, *folded_logmsg = NULL;
11941 err = got_object_id_str(&id_str, hle->commit_id);
11942 if (err)
11943 return err;
11945 err = got_object_open_as_commit(&folded_commit, repo, hle->commit_id);
11946 if (err)
11947 goto done;
11949 err = got_object_commit_get_logmsg(&folded_logmsg, folded_commit);
11950 if (err)
11951 goto done;
11952 if (asprintf(new_msg, "%s%s# log message of folded commit %s: %s",
11953 logmsg ? logmsg : "", logmsg ? "\n" : "", id_str,
11954 folded_logmsg) == -1) {
11955 err = got_error_from_errno("asprintf");
11957 done:
11958 if (folded_commit)
11959 got_object_commit_close(folded_commit);
11960 free(id_str);
11961 free(folded_logmsg);
11962 return err;
11965 static struct got_histedit_list_entry *
11966 get_folded_commits(struct got_histedit_list_entry *hle)
11968 struct got_histedit_list_entry *prev, *folded = NULL;
11970 prev = TAILQ_PREV(hle, got_histedit_list, entry);
11971 while (prev && (prev->cmd->code == GOT_HISTEDIT_FOLD ||
11972 prev->cmd->code == GOT_HISTEDIT_DROP)) {
11973 if (prev->cmd->code == GOT_HISTEDIT_FOLD)
11974 folded = prev;
11975 prev = TAILQ_PREV(prev, got_histedit_list, entry);
11978 return folded;
11981 static const struct got_error *
11982 histedit_edit_logmsg(struct got_histedit_list_entry *hle,
11983 struct got_repository *repo)
11985 char *logmsg_path = NULL, *id_str = NULL, *orig_logmsg = NULL;
11986 char *logmsg = NULL, *new_msg = NULL, *editor = NULL;
11987 const struct got_error *err = NULL;
11988 struct got_commit_object *commit = NULL;
11989 int logmsg_len;
11990 int fd = -1;
11991 struct got_histedit_list_entry *folded = NULL;
11993 err = got_object_open_as_commit(&commit, repo, hle->commit_id);
11994 if (err)
11995 return err;
11997 folded = get_folded_commits(hle);
11998 if (folded) {
11999 while (folded != hle) {
12000 if (folded->cmd->code == GOT_HISTEDIT_DROP) {
12001 folded = TAILQ_NEXT(folded, entry);
12002 continue;
12004 err = append_folded_commit_msg(&new_msg, folded,
12005 logmsg, repo);
12006 if (err)
12007 goto done;
12008 free(logmsg);
12009 logmsg = new_msg;
12010 folded = TAILQ_NEXT(folded, entry);
12014 err = got_object_id_str(&id_str, hle->commit_id);
12015 if (err)
12016 goto done;
12017 err = got_object_commit_get_logmsg(&orig_logmsg, commit);
12018 if (err)
12019 goto done;
12020 logmsg_len = asprintf(&new_msg,
12021 "%s\n# original log message of commit %s: %s",
12022 logmsg ? logmsg : "", id_str, orig_logmsg);
12023 if (logmsg_len == -1) {
12024 err = got_error_from_errno("asprintf");
12025 goto done;
12027 free(logmsg);
12028 logmsg = new_msg;
12030 err = got_object_id_str(&id_str, hle->commit_id);
12031 if (err)
12032 goto done;
12034 err = got_opentemp_named_fd(&logmsg_path, &fd,
12035 GOT_TMPDIR_STR "/got-logmsg", "");
12036 if (err)
12037 goto done;
12039 if (write(fd, logmsg, logmsg_len) == -1) {
12040 err = got_error_from_errno2("write", logmsg_path);
12041 goto done;
12043 if (close(fd) == -1) {
12044 err = got_error_from_errno2("close", logmsg_path);
12045 goto done;
12047 fd = -1;
12049 err = get_editor(&editor);
12050 if (err)
12051 goto done;
12053 err = edit_logmsg(&hle->logmsg, editor, logmsg_path, logmsg,
12054 logmsg_len, 0);
12055 if (err) {
12056 if (err->code != GOT_ERR_COMMIT_MSG_EMPTY)
12057 goto done;
12058 err = NULL;
12059 hle->logmsg = strdup(new_msg);
12060 if (hle->logmsg == NULL)
12061 err = got_error_from_errno("strdup");
12063 done:
12064 if (fd != -1 && close(fd) == -1 && err == NULL)
12065 err = got_error_from_errno2("close", logmsg_path);
12066 if (logmsg_path && unlink(logmsg_path) != 0 && err == NULL)
12067 err = got_error_from_errno2("unlink", logmsg_path);
12068 free(logmsg_path);
12069 free(logmsg);
12070 free(orig_logmsg);
12071 free(editor);
12072 if (commit)
12073 got_object_commit_close(commit);
12074 return err;
12077 static const struct got_error *
12078 histedit_parse_list(struct got_histedit_list *histedit_cmds,
12079 FILE *f, struct got_repository *repo)
12081 const struct got_error *err = NULL;
12082 char *line = NULL, *p, *end;
12083 size_t i, linesize = 0;
12084 ssize_t linelen;
12085 int lineno = 0;
12086 const struct got_histedit_cmd *cmd;
12087 struct got_object_id *commit_id = NULL;
12088 struct got_histedit_list_entry *hle = NULL;
12090 for (;;) {
12091 linelen = getline(&line, &linesize, f);
12092 if (linelen == -1) {
12093 const struct got_error *getline_err;
12094 if (feof(f))
12095 break;
12096 getline_err = got_error_from_errno("getline");
12097 err = got_ferror(f, getline_err->code);
12098 break;
12100 lineno++;
12101 p = line;
12102 while (isspace((unsigned char)p[0]))
12103 p++;
12104 if (p[0] == '#' || p[0] == '\0')
12105 continue;
12106 cmd = NULL;
12107 for (i = 0; i < nitems(got_histedit_cmds); i++) {
12108 cmd = &got_histedit_cmds[i];
12109 if (strncmp(cmd->name, p, strlen(cmd->name)) == 0 &&
12110 isspace((unsigned char)p[strlen(cmd->name)])) {
12111 p += strlen(cmd->name);
12112 break;
12114 if (p[0] == cmd->code && isspace((unsigned char)p[1])) {
12115 p++;
12116 break;
12119 if (i == nitems(got_histedit_cmds)) {
12120 err = histedit_syntax_error(lineno);
12121 break;
12123 while (isspace((unsigned char)p[0]))
12124 p++;
12125 end = p;
12126 while (end[0] && !isspace((unsigned char)end[0]))
12127 end++;
12128 *end = '\0';
12129 err = got_object_resolve_id_str(&commit_id, repo, p);
12130 if (err) {
12131 /* override error code */
12132 err = histedit_syntax_error(lineno);
12133 break;
12135 hle = malloc(sizeof(*hle));
12136 if (hle == NULL) {
12137 err = got_error_from_errno("malloc");
12138 break;
12140 hle->cmd = cmd;
12141 hle->commit_id = commit_id;
12142 hle->logmsg = NULL;
12143 commit_id = NULL;
12144 TAILQ_INSERT_TAIL(histedit_cmds, hle, entry);
12147 free(line);
12148 free(commit_id);
12149 return err;
12152 static const struct got_error *
12153 histedit_check_script(struct got_histedit_list *histedit_cmds,
12154 struct got_object_id_queue *commits, struct got_repository *repo)
12156 const struct got_error *err = NULL;
12157 struct got_object_qid *qid;
12158 struct got_histedit_list_entry *hle;
12159 static char msg[92];
12160 char *id_str;
12162 if (TAILQ_EMPTY(histedit_cmds))
12163 return got_error_msg(GOT_ERR_EMPTY_HISTEDIT,
12164 "histedit script contains no commands");
12165 if (STAILQ_EMPTY(commits))
12166 return got_error(GOT_ERR_EMPTY_HISTEDIT);
12168 TAILQ_FOREACH(hle, histedit_cmds, entry) {
12169 struct got_histedit_list_entry *hle2;
12170 TAILQ_FOREACH(hle2, histedit_cmds, entry) {
12171 if (hle == hle2)
12172 continue;
12173 if (got_object_id_cmp(hle->commit_id,
12174 hle2->commit_id) != 0)
12175 continue;
12176 err = got_object_id_str(&id_str, hle->commit_id);
12177 if (err)
12178 return err;
12179 snprintf(msg, sizeof(msg), "commit %s is listed "
12180 "more than once in histedit script", id_str);
12181 free(id_str);
12182 return got_error_msg(GOT_ERR_HISTEDIT_CMD, msg);
12186 STAILQ_FOREACH(qid, commits, entry) {
12187 TAILQ_FOREACH(hle, histedit_cmds, entry) {
12188 if (got_object_id_cmp(&qid->id, hle->commit_id) == 0)
12189 break;
12191 if (hle == NULL) {
12192 err = got_object_id_str(&id_str, &qid->id);
12193 if (err)
12194 return err;
12195 snprintf(msg, sizeof(msg),
12196 "commit %s missing from histedit script", id_str);
12197 free(id_str);
12198 return got_error_msg(GOT_ERR_HISTEDIT_CMD, msg);
12202 hle = TAILQ_LAST(histedit_cmds, got_histedit_list);
12203 if (hle && hle->cmd->code == GOT_HISTEDIT_FOLD)
12204 return got_error_msg(GOT_ERR_HISTEDIT_CMD,
12205 "last commit in histedit script cannot be folded");
12207 return NULL;
12210 static const struct got_error *
12211 histedit_run_editor(struct got_histedit_list *histedit_cmds,
12212 const char *path, struct got_object_id_queue *commits,
12213 struct got_repository *repo)
12215 const struct got_error *err = NULL;
12216 struct stat st, st2;
12217 struct timespec timeout;
12218 char *editor;
12219 FILE *f = NULL;
12221 err = get_editor(&editor);
12222 if (err)
12223 return err;
12225 if (stat(path, &st) == -1) {
12226 err = got_error_from_errno2("stat", path);
12227 goto done;
12230 if (spawn_editor(editor, path) == -1) {
12231 err = got_error_from_errno("failed spawning editor");
12232 goto done;
12235 timeout.tv_sec = 0;
12236 timeout.tv_nsec = 1;
12237 nanosleep(&timeout, NULL);
12239 if (stat(path, &st2) == -1) {
12240 err = got_error_from_errno2("stat", path);
12241 goto done;
12244 if (st.st_size == st2.st_size &&
12245 timespeccmp(&st.st_mtim, &st2.st_mtim, ==)) {
12246 err = got_error_msg(GOT_ERR_EMPTY_HISTEDIT,
12247 "no changes made to histedit script, aborting");
12248 goto done;
12251 f = fopen(path, "re");
12252 if (f == NULL) {
12253 err = got_error_from_errno("fopen");
12254 goto done;
12256 err = histedit_parse_list(histedit_cmds, f, repo);
12257 if (err)
12258 goto done;
12260 err = histedit_check_script(histedit_cmds, commits, repo);
12261 done:
12262 if (f && fclose(f) == EOF && err == NULL)
12263 err = got_error_from_errno("fclose");
12264 free(editor);
12265 return err;
12268 static const struct got_error *
12269 histedit_edit_list_retry(struct got_histedit_list *, const struct got_error *,
12270 struct got_object_id_queue *, const char *, const char *,
12271 struct got_repository *);
12273 static const struct got_error *
12274 histedit_edit_script(struct got_histedit_list *histedit_cmds,
12275 struct got_object_id_queue *commits, const char *branch_name,
12276 int edit_logmsg_only, int fold_only, int drop_only, int edit_only,
12277 struct got_repository *repo)
12279 const struct got_error *err;
12280 FILE *f = NULL;
12281 char *path = NULL;
12283 err = got_opentemp_named(&path, &f, "got-histedit", "");
12284 if (err)
12285 return err;
12287 err = write_cmd_list(f, branch_name, commits);
12288 if (err)
12289 goto done;
12291 err = histedit_write_commit_list(commits, f, edit_logmsg_only,
12292 fold_only, drop_only, edit_only, repo);
12293 if (err)
12294 goto done;
12296 if (drop_only || edit_logmsg_only || fold_only || edit_only) {
12297 rewind(f);
12298 err = histedit_parse_list(histedit_cmds, f, repo);
12299 } else {
12300 if (fclose(f) == EOF) {
12301 err = got_error_from_errno("fclose");
12302 goto done;
12304 f = NULL;
12305 err = histedit_run_editor(histedit_cmds, path, commits, repo);
12306 if (err) {
12307 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
12308 err->code != GOT_ERR_HISTEDIT_CMD)
12309 goto done;
12310 err = histedit_edit_list_retry(histedit_cmds, err,
12311 commits, path, branch_name, repo);
12314 done:
12315 if (f && fclose(f) == EOF && err == NULL)
12316 err = got_error_from_errno("fclose");
12317 if (path && unlink(path) != 0 && err == NULL)
12318 err = got_error_from_errno2("unlink", path);
12319 free(path);
12320 return err;
12323 static const struct got_error *
12324 histedit_save_list(struct got_histedit_list *histedit_cmds,
12325 struct got_worktree *worktree, struct got_repository *repo)
12327 const struct got_error *err = NULL;
12328 char *path = NULL;
12329 FILE *f = NULL;
12330 struct got_histedit_list_entry *hle;
12332 err = got_worktree_get_histedit_script_path(&path, worktree);
12333 if (err)
12334 return err;
12336 f = fopen(path, "we");
12337 if (f == NULL) {
12338 err = got_error_from_errno2("fopen", path);
12339 goto done;
12341 TAILQ_FOREACH(hle, histedit_cmds, entry) {
12342 err = histedit_write_commit(hle->commit_id, hle->cmd->name, f,
12343 repo);
12344 if (err)
12345 break;
12347 done:
12348 if (f && fclose(f) == EOF && err == NULL)
12349 err = got_error_from_errno("fclose");
12350 free(path);
12351 return err;
12354 static void
12355 histedit_free_list(struct got_histedit_list *histedit_cmds)
12357 struct got_histedit_list_entry *hle;
12359 while ((hle = TAILQ_FIRST(histedit_cmds))) {
12360 TAILQ_REMOVE(histedit_cmds, hle, entry);
12361 free(hle);
12365 static const struct got_error *
12366 histedit_load_list(struct got_histedit_list *histedit_cmds,
12367 const char *path, struct got_repository *repo)
12369 const struct got_error *err = NULL;
12370 FILE *f = NULL;
12372 f = fopen(path, "re");
12373 if (f == NULL) {
12374 err = got_error_from_errno2("fopen", path);
12375 goto done;
12378 err = histedit_parse_list(histedit_cmds, f, repo);
12379 done:
12380 if (f && fclose(f) == EOF && err == NULL)
12381 err = got_error_from_errno("fclose");
12382 return err;
12385 static const struct got_error *
12386 histedit_edit_list_retry(struct got_histedit_list *histedit_cmds,
12387 const struct got_error *edit_err, struct got_object_id_queue *commits,
12388 const char *path, const char *branch_name, struct got_repository *repo)
12390 const struct got_error *err = NULL, *prev_err = edit_err;
12391 int resp = ' ';
12393 while (resp != 'c' && resp != 'r' && resp != 'a') {
12394 printf("%s: %s\n(c)ontinue editing, (r)estart editing, "
12395 "or (a)bort: ", getprogname(), prev_err->msg);
12396 resp = getchar();
12397 if (resp == '\n')
12398 resp = getchar();
12399 if (resp == 'c') {
12400 histedit_free_list(histedit_cmds);
12401 err = histedit_run_editor(histedit_cmds, path, commits,
12402 repo);
12403 if (err) {
12404 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
12405 err->code != GOT_ERR_HISTEDIT_CMD)
12406 break;
12407 prev_err = err;
12408 resp = ' ';
12409 continue;
12411 break;
12412 } else if (resp == 'r') {
12413 histedit_free_list(histedit_cmds);
12414 err = histedit_edit_script(histedit_cmds,
12415 commits, branch_name, 0, 0, 0, 0, repo);
12416 if (err) {
12417 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
12418 err->code != GOT_ERR_HISTEDIT_CMD)
12419 break;
12420 prev_err = err;
12421 resp = ' ';
12422 continue;
12424 break;
12425 } else if (resp == 'a') {
12426 err = got_error(GOT_ERR_HISTEDIT_CANCEL);
12427 break;
12428 } else
12429 printf("invalid response '%c'\n", resp);
12432 return err;
12435 static const struct got_error *
12436 histedit_complete(struct got_worktree *worktree,
12437 struct got_fileindex *fileindex, struct got_reference *tmp_branch,
12438 struct got_reference *branch, struct got_repository *repo)
12440 printf("Switching work tree to %s\n",
12441 got_ref_get_symref_target(branch));
12442 return got_worktree_histedit_complete(worktree, fileindex, tmp_branch,
12443 branch, repo);
12446 static const struct got_error *
12447 show_histedit_progress(struct got_commit_object *commit,
12448 struct got_histedit_list_entry *hle, struct got_object_id *new_id)
12450 const struct got_error *err;
12451 char *old_id_str = NULL, *new_id_str = NULL, *logmsg = NULL;
12453 err = got_object_id_str(&old_id_str, hle->commit_id);
12454 if (err)
12455 goto done;
12457 if (new_id) {
12458 err = got_object_id_str(&new_id_str, new_id);
12459 if (err)
12460 goto done;
12463 old_id_str[12] = '\0';
12464 if (new_id_str)
12465 new_id_str[12] = '\0';
12467 if (hle->logmsg) {
12468 logmsg = strdup(hle->logmsg);
12469 if (logmsg == NULL) {
12470 err = got_error_from_errno("strdup");
12471 goto done;
12473 trim_logmsg(logmsg, 42);
12474 } else {
12475 err = get_short_logmsg(&logmsg, 42, commit);
12476 if (err)
12477 goto done;
12480 switch (hle->cmd->code) {
12481 case GOT_HISTEDIT_PICK:
12482 case GOT_HISTEDIT_EDIT:
12483 case GOT_HISTEDIT_MESG:
12484 printf("%s -> %s: %s\n", old_id_str,
12485 new_id_str ? new_id_str : "no-op change", logmsg);
12486 break;
12487 case GOT_HISTEDIT_DROP:
12488 case GOT_HISTEDIT_FOLD:
12489 printf("%s -> %s commit: %s\n", old_id_str, hle->cmd->name,
12490 logmsg);
12491 break;
12492 default:
12493 break;
12495 done:
12496 free(old_id_str);
12497 free(new_id_str);
12498 return err;
12501 static const struct got_error *
12502 histedit_commit(struct got_pathlist_head *merged_paths,
12503 struct got_worktree *worktree, struct got_fileindex *fileindex,
12504 struct got_reference *tmp_branch, struct got_histedit_list_entry *hle,
12505 const char *committer, int allow_conflict, struct got_repository *repo)
12507 const struct got_error *err;
12508 struct got_commit_object *commit;
12509 struct got_object_id *new_commit_id;
12511 if ((hle->cmd->code == GOT_HISTEDIT_EDIT || get_folded_commits(hle))
12512 && hle->logmsg == NULL) {
12513 err = histedit_edit_logmsg(hle, repo);
12514 if (err)
12515 return err;
12518 err = got_object_open_as_commit(&commit, repo, hle->commit_id);
12519 if (err)
12520 return err;
12522 err = got_worktree_histedit_commit(&new_commit_id, merged_paths,
12523 worktree, fileindex, tmp_branch, committer, commit, hle->commit_id,
12524 hle->logmsg, allow_conflict, repo);
12525 if (err) {
12526 if (err->code != GOT_ERR_COMMIT_NO_CHANGES)
12527 goto done;
12528 err = show_histedit_progress(commit, hle, NULL);
12529 } else {
12530 err = show_histedit_progress(commit, hle, new_commit_id);
12531 free(new_commit_id);
12533 done:
12534 got_object_commit_close(commit);
12535 return err;
12538 static const struct got_error *
12539 histedit_skip_commit(struct got_histedit_list_entry *hle,
12540 struct got_worktree *worktree, struct got_repository *repo)
12542 const struct got_error *error;
12543 struct got_commit_object *commit;
12545 error = got_worktree_histedit_skip_commit(worktree, hle->commit_id,
12546 repo);
12547 if (error)
12548 return error;
12550 error = got_object_open_as_commit(&commit, repo, hle->commit_id);
12551 if (error)
12552 return error;
12554 error = show_histedit_progress(commit, hle, NULL);
12555 got_object_commit_close(commit);
12556 return error;
12559 static const struct got_error *
12560 check_local_changes(void *arg, unsigned char status,
12561 unsigned char staged_status, const char *path,
12562 struct got_object_id *blob_id, struct got_object_id *staged_blob_id,
12563 struct got_object_id *commit_id, int dirfd, const char *de_name)
12565 int *have_local_changes = arg;
12567 switch (status) {
12568 case GOT_STATUS_ADD:
12569 case GOT_STATUS_DELETE:
12570 case GOT_STATUS_MODIFY:
12571 case GOT_STATUS_CONFLICT:
12572 *have_local_changes = 1;
12573 return got_error(GOT_ERR_CANCELLED);
12574 default:
12575 break;
12578 switch (staged_status) {
12579 case GOT_STATUS_ADD:
12580 case GOT_STATUS_DELETE:
12581 case GOT_STATUS_MODIFY:
12582 *have_local_changes = 1;
12583 return got_error(GOT_ERR_CANCELLED);
12584 default:
12585 break;
12588 return NULL;
12591 static const struct got_error *
12592 cmd_histedit(int argc, char *argv[])
12594 const struct got_error *error = NULL;
12595 struct got_worktree *worktree = NULL;
12596 struct got_fileindex *fileindex = NULL;
12597 struct got_repository *repo = NULL;
12598 char *cwd = NULL, *committer = NULL, *gitconfig_path = NULL;
12599 struct got_reference *branch = NULL;
12600 struct got_reference *tmp_branch = NULL;
12601 struct got_object_id *resume_commit_id = NULL;
12602 struct got_object_id *base_commit_id = NULL;
12603 struct got_object_id *head_commit_id = NULL;
12604 struct got_commit_object *commit = NULL;
12605 int ch, rebase_in_progress = 0, merge_in_progress = 0;
12606 struct got_update_progress_arg upa;
12607 int edit_in_progress = 0, abort_edit = 0, continue_edit = 0;
12608 int drop_only = 0, edit_logmsg_only = 0, fold_only = 0, edit_only = 0;
12609 int allow_conflict = 0, list_backups = 0, delete_backups = 0;
12610 const char *edit_script_path = NULL;
12611 struct got_object_id_queue commits;
12612 struct got_pathlist_head merged_paths;
12613 const struct got_object_id_queue *parent_ids;
12614 struct got_object_qid *pid;
12615 struct got_histedit_list histedit_cmds;
12616 struct got_histedit_list_entry *hle;
12617 int *pack_fds = NULL;
12619 STAILQ_INIT(&commits);
12620 TAILQ_INIT(&histedit_cmds);
12621 TAILQ_INIT(&merged_paths);
12622 memset(&upa, 0, sizeof(upa));
12624 #ifndef PROFILE
12625 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
12626 "unveil", NULL) == -1)
12627 err(1, "pledge");
12628 #endif
12630 while ((ch = getopt(argc, argv, "aCcdeF:flmX")) != -1) {
12631 switch (ch) {
12632 case 'a':
12633 abort_edit = 1;
12634 break;
12635 case 'C':
12636 allow_conflict = 1;
12637 break;
12638 case 'c':
12639 continue_edit = 1;
12640 break;
12641 case 'd':
12642 drop_only = 1;
12643 break;
12644 case 'e':
12645 edit_only = 1;
12646 break;
12647 case 'F':
12648 edit_script_path = optarg;
12649 break;
12650 case 'f':
12651 fold_only = 1;
12652 break;
12653 case 'l':
12654 list_backups = 1;
12655 break;
12656 case 'm':
12657 edit_logmsg_only = 1;
12658 break;
12659 case 'X':
12660 delete_backups = 1;
12661 break;
12662 default:
12663 usage_histedit();
12664 /* NOTREACHED */
12668 argc -= optind;
12669 argv += optind;
12671 if (abort_edit && allow_conflict)
12672 option_conflict('a', 'C');
12673 if (abort_edit && continue_edit)
12674 option_conflict('a', 'c');
12675 if (edit_script_path && allow_conflict)
12676 option_conflict('F', 'C');
12677 if (edit_script_path && edit_logmsg_only)
12678 option_conflict('F', 'm');
12679 if (abort_edit && edit_logmsg_only)
12680 option_conflict('a', 'm');
12681 if (edit_logmsg_only && allow_conflict)
12682 option_conflict('m', 'C');
12683 if (continue_edit && edit_logmsg_only)
12684 option_conflict('c', 'm');
12685 if (abort_edit && fold_only)
12686 option_conflict('a', 'f');
12687 if (fold_only && allow_conflict)
12688 option_conflict('f', 'C');
12689 if (continue_edit && fold_only)
12690 option_conflict('c', 'f');
12691 if (fold_only && edit_logmsg_only)
12692 option_conflict('f', 'm');
12693 if (edit_script_path && fold_only)
12694 option_conflict('F', 'f');
12695 if (abort_edit && edit_only)
12696 option_conflict('a', 'e');
12697 if (continue_edit && edit_only)
12698 option_conflict('c', 'e');
12699 if (edit_only && edit_logmsg_only)
12700 option_conflict('e', 'm');
12701 if (edit_script_path && edit_only)
12702 option_conflict('F', 'e');
12703 if (fold_only && edit_only)
12704 option_conflict('f', 'e');
12705 if (drop_only && abort_edit)
12706 option_conflict('d', 'a');
12707 if (drop_only && allow_conflict)
12708 option_conflict('d', 'C');
12709 if (drop_only && continue_edit)
12710 option_conflict('d', 'c');
12711 if (drop_only && edit_logmsg_only)
12712 option_conflict('d', 'm');
12713 if (drop_only && edit_only)
12714 option_conflict('d', 'e');
12715 if (drop_only && edit_script_path)
12716 option_conflict('d', 'F');
12717 if (drop_only && fold_only)
12718 option_conflict('d', 'f');
12719 if (list_backups) {
12720 if (abort_edit)
12721 option_conflict('l', 'a');
12722 if (allow_conflict)
12723 option_conflict('l', 'C');
12724 if (continue_edit)
12725 option_conflict('l', 'c');
12726 if (edit_script_path)
12727 option_conflict('l', 'F');
12728 if (edit_logmsg_only)
12729 option_conflict('l', 'm');
12730 if (drop_only)
12731 option_conflict('l', 'd');
12732 if (fold_only)
12733 option_conflict('l', 'f');
12734 if (edit_only)
12735 option_conflict('l', 'e');
12736 if (delete_backups)
12737 option_conflict('l', 'X');
12738 if (argc != 0 && argc != 1)
12739 usage_histedit();
12740 } else if (delete_backups) {
12741 if (abort_edit)
12742 option_conflict('X', 'a');
12743 if (allow_conflict)
12744 option_conflict('X', 'C');
12745 if (continue_edit)
12746 option_conflict('X', 'c');
12747 if (drop_only)
12748 option_conflict('X', 'd');
12749 if (edit_script_path)
12750 option_conflict('X', 'F');
12751 if (edit_logmsg_only)
12752 option_conflict('X', 'm');
12753 if (fold_only)
12754 option_conflict('X', 'f');
12755 if (edit_only)
12756 option_conflict('X', 'e');
12757 if (list_backups)
12758 option_conflict('X', 'l');
12759 if (argc != 0 && argc != 1)
12760 usage_histedit();
12761 } else if (allow_conflict && !continue_edit)
12762 errx(1, "-C option requires -c");
12763 else if (argc != 0)
12764 usage_histedit();
12767 * This command cannot apply unveil(2) in all cases because the
12768 * user may choose to run an editor to edit the histedit script
12769 * and to edit individual commit log messages.
12770 * unveil(2) traverses exec(2); if an editor is used we have to
12771 * apply unveil after edit script and log messages have been written.
12772 * XXX TODO: Make use of unveil(2) where possible.
12775 cwd = getcwd(NULL, 0);
12776 if (cwd == NULL) {
12777 error = got_error_from_errno("getcwd");
12778 goto done;
12781 error = got_repo_pack_fds_open(&pack_fds);
12782 if (error != NULL)
12783 goto done;
12785 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
12786 if (error) {
12787 if (list_backups || delete_backups) {
12788 if (error->code != GOT_ERR_NOT_WORKTREE)
12789 goto done;
12790 } else {
12791 if (error->code == GOT_ERR_NOT_WORKTREE)
12792 error = wrap_not_worktree_error(error,
12793 "histedit", cwd);
12794 goto done;
12798 if (list_backups || delete_backups) {
12799 error = got_repo_open(&repo,
12800 worktree ? got_worktree_get_repo_path(worktree) : cwd,
12801 NULL, pack_fds);
12802 if (error != NULL)
12803 goto done;
12804 error = apply_unveil(got_repo_get_path(repo), 0,
12805 worktree ? got_worktree_get_root_path(worktree) : NULL);
12806 if (error)
12807 goto done;
12808 error = process_backup_refs(
12809 GOT_WORKTREE_HISTEDIT_BACKUP_REF_PREFIX,
12810 argc == 1 ? argv[0] : NULL, delete_backups, repo);
12811 goto done; /* nothing else to do */
12814 error = get_gitconfig_path(&gitconfig_path);
12815 if (error)
12816 goto done;
12817 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
12818 gitconfig_path, pack_fds);
12819 if (error != NULL)
12820 goto done;
12822 if (worktree != NULL && !list_backups && !delete_backups) {
12823 error = worktree_has_logmsg_ref("histedit", worktree, repo);
12824 if (error)
12825 goto done;
12828 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
12829 if (error)
12830 goto done;
12831 if (rebase_in_progress) {
12832 error = got_error(GOT_ERR_REBASING);
12833 goto done;
12836 error = got_worktree_merge_in_progress(&merge_in_progress, worktree,
12837 repo);
12838 if (error)
12839 goto done;
12840 if (merge_in_progress) {
12841 error = got_error(GOT_ERR_MERGE_BUSY);
12842 goto done;
12845 error = got_worktree_histedit_in_progress(&edit_in_progress, worktree);
12846 if (error)
12847 goto done;
12849 if (edit_in_progress && edit_logmsg_only) {
12850 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
12851 "histedit operation is in progress in this "
12852 "work tree and must be continued or aborted "
12853 "before the -m option can be used");
12854 goto done;
12856 if (edit_in_progress && drop_only) {
12857 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
12858 "histedit operation is in progress in this "
12859 "work tree and must be continued or aborted "
12860 "before the -d option can be used");
12861 goto done;
12863 if (edit_in_progress && fold_only) {
12864 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
12865 "histedit operation is in progress in this "
12866 "work tree and must be continued or aborted "
12867 "before the -f option can be used");
12868 goto done;
12870 if (edit_in_progress && edit_only) {
12871 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
12872 "histedit operation is in progress in this "
12873 "work tree and must be continued or aborted "
12874 "before the -e option can be used");
12875 goto done;
12878 if (edit_in_progress && abort_edit) {
12879 error = got_worktree_histedit_continue(&resume_commit_id,
12880 &tmp_branch, &branch, &base_commit_id, &fileindex,
12881 worktree, repo);
12882 if (error)
12883 goto done;
12884 printf("Switching work tree to %s\n",
12885 got_ref_get_symref_target(branch));
12886 error = got_worktree_histedit_abort(worktree, fileindex, repo,
12887 branch, base_commit_id, abort_progress, &upa);
12888 if (error)
12889 goto done;
12890 printf("Histedit of %s aborted\n",
12891 got_ref_get_symref_target(branch));
12892 print_merge_progress_stats(&upa);
12893 goto done; /* nothing else to do */
12894 } else if (abort_edit) {
12895 error = got_error(GOT_ERR_NOT_HISTEDIT);
12896 goto done;
12899 error = get_author(&committer, repo, worktree);
12900 if (error)
12901 goto done;
12903 if (continue_edit) {
12904 char *path;
12906 if (!edit_in_progress) {
12907 error = got_error(GOT_ERR_NOT_HISTEDIT);
12908 goto done;
12911 error = got_worktree_get_histedit_script_path(&path, worktree);
12912 if (error)
12913 goto done;
12915 error = histedit_load_list(&histedit_cmds, path, repo);
12916 free(path);
12917 if (error)
12918 goto done;
12920 error = got_worktree_histedit_continue(&resume_commit_id,
12921 &tmp_branch, &branch, &base_commit_id, &fileindex,
12922 worktree, repo);
12923 if (error)
12924 goto done;
12926 error = got_ref_resolve(&head_commit_id, repo, branch);
12927 if (error)
12928 goto done;
12930 error = got_object_open_as_commit(&commit, repo,
12931 head_commit_id);
12932 if (error)
12933 goto done;
12934 parent_ids = got_object_commit_get_parent_ids(commit);
12935 pid = STAILQ_FIRST(parent_ids);
12936 if (pid == NULL) {
12937 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
12938 goto done;
12940 error = collect_commits(&commits, head_commit_id, &pid->id,
12941 base_commit_id, got_worktree_get_path_prefix(worktree),
12942 GOT_ERR_HISTEDIT_PATH, repo);
12943 got_object_commit_close(commit);
12944 commit = NULL;
12945 if (error)
12946 goto done;
12947 } else {
12948 if (edit_in_progress) {
12949 error = got_error(GOT_ERR_HISTEDIT_BUSY);
12950 goto done;
12953 error = got_ref_open(&branch, repo,
12954 got_worktree_get_head_ref_name(worktree), 0);
12955 if (error != NULL)
12956 goto done;
12958 if (strncmp(got_ref_get_name(branch), "refs/heads/", 11) != 0) {
12959 error = got_error_msg(GOT_ERR_COMMIT_BRANCH,
12960 "will not edit commit history of a branch outside "
12961 "the \"refs/heads/\" reference namespace");
12962 goto done;
12965 error = got_ref_resolve(&head_commit_id, repo, branch);
12966 got_ref_close(branch);
12967 branch = NULL;
12968 if (error)
12969 goto done;
12971 error = got_object_open_as_commit(&commit, repo,
12972 head_commit_id);
12973 if (error)
12974 goto done;
12975 parent_ids = got_object_commit_get_parent_ids(commit);
12976 pid = STAILQ_FIRST(parent_ids);
12977 if (pid == NULL) {
12978 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
12979 goto done;
12981 error = collect_commits(&commits, head_commit_id, &pid->id,
12982 got_worktree_get_base_commit_id(worktree),
12983 got_worktree_get_path_prefix(worktree),
12984 GOT_ERR_HISTEDIT_PATH, repo);
12985 got_object_commit_close(commit);
12986 commit = NULL;
12987 if (error)
12988 goto done;
12990 if (STAILQ_EMPTY(&commits)) {
12991 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
12992 goto done;
12995 error = got_worktree_histedit_prepare(&tmp_branch, &branch,
12996 &base_commit_id, &fileindex, worktree, repo);
12997 if (error)
12998 goto done;
13000 if (edit_script_path) {
13001 error = histedit_load_list(&histedit_cmds,
13002 edit_script_path, repo);
13003 if (error) {
13004 got_worktree_histedit_abort(worktree, fileindex,
13005 repo, branch, base_commit_id,
13006 abort_progress, &upa);
13007 print_merge_progress_stats(&upa);
13008 goto done;
13010 } else {
13011 const char *branch_name;
13012 branch_name = got_ref_get_symref_target(branch);
13013 if (strncmp(branch_name, "refs/heads/", 11) == 0)
13014 branch_name += 11;
13015 error = histedit_edit_script(&histedit_cmds, &commits,
13016 branch_name, edit_logmsg_only, fold_only,
13017 drop_only, edit_only, repo);
13018 if (error) {
13019 got_worktree_histedit_abort(worktree, fileindex,
13020 repo, branch, base_commit_id,
13021 abort_progress, &upa);
13022 print_merge_progress_stats(&upa);
13023 goto done;
13028 error = histedit_save_list(&histedit_cmds, worktree,
13029 repo);
13030 if (error) {
13031 got_worktree_histedit_abort(worktree, fileindex,
13032 repo, branch, base_commit_id,
13033 abort_progress, &upa);
13034 print_merge_progress_stats(&upa);
13035 goto done;
13040 error = histedit_check_script(&histedit_cmds, &commits, repo);
13041 if (error)
13042 goto done;
13044 TAILQ_FOREACH(hle, &histedit_cmds, entry) {
13045 if (resume_commit_id) {
13046 if (got_object_id_cmp(hle->commit_id,
13047 resume_commit_id) != 0)
13048 continue;
13050 resume_commit_id = NULL;
13051 if (hle->cmd->code == GOT_HISTEDIT_DROP ||
13052 hle->cmd->code == GOT_HISTEDIT_FOLD) {
13053 error = histedit_skip_commit(hle, worktree,
13054 repo);
13055 if (error)
13056 goto done;
13057 } else {
13058 struct got_pathlist_head paths;
13059 int have_changes = 0;
13061 TAILQ_INIT(&paths);
13062 error = got_pathlist_append(&paths, "", NULL);
13063 if (error)
13064 goto done;
13065 error = got_worktree_status(worktree, &paths,
13066 repo, 0, check_local_changes, &have_changes,
13067 check_cancelled, NULL);
13068 got_pathlist_free(&paths,
13069 GOT_PATHLIST_FREE_NONE);
13070 if (error) {
13071 if (error->code != GOT_ERR_CANCELLED)
13072 goto done;
13073 if (sigint_received || sigpipe_received)
13074 goto done;
13076 if (have_changes) {
13077 error = histedit_commit(NULL, worktree,
13078 fileindex, tmp_branch, hle,
13079 committer, allow_conflict, repo);
13080 if (error)
13081 goto done;
13082 } else {
13083 error = got_object_open_as_commit(
13084 &commit, repo, hle->commit_id);
13085 if (error)
13086 goto done;
13087 error = show_histedit_progress(commit,
13088 hle, NULL);
13089 got_object_commit_close(commit);
13090 commit = NULL;
13091 if (error)
13092 goto done;
13095 continue;
13098 if (hle->cmd->code == GOT_HISTEDIT_DROP) {
13099 error = histedit_skip_commit(hle, worktree, repo);
13100 if (error)
13101 goto done;
13102 continue;
13104 error = got_object_open_as_commit(&commit, repo,
13105 hle->commit_id);
13106 if (error)
13107 goto done;
13108 parent_ids = got_object_commit_get_parent_ids(commit);
13109 pid = STAILQ_FIRST(parent_ids);
13111 error = got_worktree_histedit_merge_files(&merged_paths,
13112 worktree, fileindex, &pid->id, hle->commit_id, repo,
13113 update_progress, &upa, check_cancelled, NULL);
13114 if (error)
13115 goto done;
13116 got_object_commit_close(commit);
13117 commit = NULL;
13119 print_merge_progress_stats(&upa);
13120 if (upa.conflicts > 0 || upa.missing > 0 ||
13121 upa.not_deleted > 0 || upa.unversioned > 0) {
13122 if (upa.conflicts > 0) {
13123 error = show_rebase_merge_conflict(
13124 hle->commit_id, repo);
13125 if (error)
13126 goto done;
13128 got_pathlist_free(&merged_paths, GOT_PATHLIST_FREE_PATH);
13129 break;
13132 if (hle->cmd->code == GOT_HISTEDIT_EDIT) {
13133 char *id_str;
13134 error = got_object_id_str(&id_str, hle->commit_id);
13135 if (error)
13136 goto done;
13137 printf("Stopping histedit for amending commit %s\n",
13138 id_str);
13139 free(id_str);
13140 got_pathlist_free(&merged_paths, GOT_PATHLIST_FREE_PATH);
13141 error = got_worktree_histedit_postpone(worktree,
13142 fileindex);
13143 goto done;
13144 } else if (hle->cmd->code == GOT_HISTEDIT_FOLD) {
13145 error = histedit_skip_commit(hle, worktree, repo);
13146 if (error)
13147 goto done;
13148 continue;
13149 } else if (hle->cmd->code == GOT_HISTEDIT_MESG) {
13150 error = histedit_edit_logmsg(hle, repo);
13151 if (error)
13152 goto done;
13155 error = histedit_commit(&merged_paths, worktree, fileindex,
13156 tmp_branch, hle, committer, allow_conflict, repo);
13157 got_pathlist_free(&merged_paths, GOT_PATHLIST_FREE_PATH);
13158 if (error)
13159 goto done;
13162 if (upa.conflicts > 0 || upa.missing > 0 ||
13163 upa.not_deleted > 0 || upa.unversioned > 0) {
13164 error = got_worktree_histedit_postpone(worktree, fileindex);
13165 if (error)
13166 goto done;
13167 if (upa.conflicts > 0 && upa.missing == 0 &&
13168 upa.not_deleted == 0 && upa.unversioned == 0) {
13169 error = got_error_msg(GOT_ERR_CONFLICTS,
13170 "conflicts must be resolved before histedit "
13171 "can continue");
13172 } else if (upa.conflicts > 0) {
13173 error = got_error_msg(GOT_ERR_CONFLICTS,
13174 "conflicts must be resolved before histedit "
13175 "can continue; changes destined for some "
13176 "files were not yet merged and should be "
13177 "merged manually if required before the "
13178 "histedit operation is continued");
13179 } else {
13180 error = got_error_msg(GOT_ERR_CONFLICTS,
13181 "changes destined for some files were not "
13182 "yet merged and should be merged manually "
13183 "if required before the histedit operation "
13184 "is continued");
13186 } else
13187 error = histedit_complete(worktree, fileindex, tmp_branch,
13188 branch, repo);
13189 done:
13190 free(cwd);
13191 free(committer);
13192 free(gitconfig_path);
13193 got_object_id_queue_free(&commits);
13194 histedit_free_list(&histedit_cmds);
13195 free(head_commit_id);
13196 free(base_commit_id);
13197 free(resume_commit_id);
13198 if (commit)
13199 got_object_commit_close(commit);
13200 if (branch)
13201 got_ref_close(branch);
13202 if (tmp_branch)
13203 got_ref_close(tmp_branch);
13204 if (worktree)
13205 got_worktree_close(worktree);
13206 if (repo) {
13207 const struct got_error *close_err = got_repo_close(repo);
13208 if (error == NULL)
13209 error = close_err;
13211 if (pack_fds) {
13212 const struct got_error *pack_err =
13213 got_repo_pack_fds_close(pack_fds);
13214 if (error == NULL)
13215 error = pack_err;
13217 return error;
13220 __dead static void
13221 usage_integrate(void)
13223 fprintf(stderr, "usage: %s integrate branch\n", getprogname());
13224 exit(1);
13227 static const struct got_error *
13228 cmd_integrate(int argc, char *argv[])
13230 const struct got_error *error = NULL;
13231 struct got_repository *repo = NULL;
13232 struct got_worktree *worktree = NULL;
13233 char *cwd = NULL, *refname = NULL, *base_refname = NULL;
13234 const char *branch_arg = NULL;
13235 struct got_reference *branch_ref = NULL, *base_branch_ref = NULL;
13236 struct got_fileindex *fileindex = NULL;
13237 struct got_object_id *commit_id = NULL, *base_commit_id = NULL;
13238 int ch;
13239 struct got_update_progress_arg upa;
13240 int *pack_fds = NULL;
13242 #ifndef PROFILE
13243 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
13244 "unveil", NULL) == -1)
13245 err(1, "pledge");
13246 #endif
13248 while ((ch = getopt(argc, argv, "")) != -1) {
13249 switch (ch) {
13250 default:
13251 usage_integrate();
13252 /* NOTREACHED */
13256 argc -= optind;
13257 argv += optind;
13259 if (argc != 1)
13260 usage_integrate();
13261 branch_arg = argv[0];
13263 cwd = getcwd(NULL, 0);
13264 if (cwd == NULL) {
13265 error = got_error_from_errno("getcwd");
13266 goto done;
13269 error = got_repo_pack_fds_open(&pack_fds);
13270 if (error != NULL)
13271 goto done;
13273 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
13274 if (error) {
13275 if (error->code == GOT_ERR_NOT_WORKTREE)
13276 error = wrap_not_worktree_error(error, "integrate",
13277 cwd);
13278 goto done;
13281 error = check_rebase_or_histedit_in_progress(worktree);
13282 if (error)
13283 goto done;
13285 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
13286 NULL, pack_fds);
13287 if (error != NULL)
13288 goto done;
13290 error = apply_unveil(got_repo_get_path(repo), 0,
13291 got_worktree_get_root_path(worktree));
13292 if (error)
13293 goto done;
13295 error = check_merge_in_progress(worktree, repo);
13296 if (error)
13297 goto done;
13299 if (asprintf(&refname, "refs/heads/%s", branch_arg) == -1) {
13300 error = got_error_from_errno("asprintf");
13301 goto done;
13304 error = got_worktree_integrate_prepare(&fileindex, &branch_ref,
13305 &base_branch_ref, worktree, refname, repo);
13306 if (error)
13307 goto done;
13309 refname = strdup(got_ref_get_name(branch_ref));
13310 if (refname == NULL) {
13311 error = got_error_from_errno("strdup");
13312 got_worktree_integrate_abort(worktree, fileindex, repo,
13313 branch_ref, base_branch_ref);
13314 goto done;
13316 base_refname = strdup(got_ref_get_name(base_branch_ref));
13317 if (base_refname == NULL) {
13318 error = got_error_from_errno("strdup");
13319 got_worktree_integrate_abort(worktree, fileindex, repo,
13320 branch_ref, base_branch_ref);
13321 goto done;
13323 if (strncmp(base_refname, "refs/heads/", 11) != 0) {
13324 error = got_error(GOT_ERR_INTEGRATE_BRANCH);
13325 got_worktree_integrate_abort(worktree, fileindex, repo,
13326 branch_ref, base_branch_ref);
13327 goto done;
13330 error = got_ref_resolve(&commit_id, repo, branch_ref);
13331 if (error)
13332 goto done;
13334 error = got_ref_resolve(&base_commit_id, repo, base_branch_ref);
13335 if (error)
13336 goto done;
13338 if (got_object_id_cmp(commit_id, base_commit_id) == 0) {
13339 error = got_error_msg(GOT_ERR_SAME_BRANCH,
13340 "specified branch has already been integrated");
13341 got_worktree_integrate_abort(worktree, fileindex, repo,
13342 branch_ref, base_branch_ref);
13343 goto done;
13346 error = check_linear_ancestry(commit_id, base_commit_id, 1, repo);
13347 if (error) {
13348 if (error->code == GOT_ERR_ANCESTRY)
13349 error = got_error(GOT_ERR_REBASE_REQUIRED);
13350 got_worktree_integrate_abort(worktree, fileindex, repo,
13351 branch_ref, base_branch_ref);
13352 goto done;
13355 memset(&upa, 0, sizeof(upa));
13356 error = got_worktree_integrate_continue(worktree, fileindex, repo,
13357 branch_ref, base_branch_ref, update_progress, &upa,
13358 check_cancelled, NULL);
13359 if (error)
13360 goto done;
13362 printf("Integrated %s into %s\n", refname, base_refname);
13363 print_update_progress_stats(&upa);
13364 done:
13365 if (repo) {
13366 const struct got_error *close_err = got_repo_close(repo);
13367 if (error == NULL)
13368 error = close_err;
13370 if (worktree)
13371 got_worktree_close(worktree);
13372 if (pack_fds) {
13373 const struct got_error *pack_err =
13374 got_repo_pack_fds_close(pack_fds);
13375 if (error == NULL)
13376 error = pack_err;
13378 free(cwd);
13379 free(base_commit_id);
13380 free(commit_id);
13381 free(refname);
13382 free(base_refname);
13383 return error;
13386 __dead static void
13387 usage_merge(void)
13389 fprintf(stderr, "usage: %s merge [-aCcn] [branch]\n", getprogname());
13390 exit(1);
13393 static const struct got_error *
13394 cmd_merge(int argc, char *argv[])
13396 const struct got_error *error = NULL;
13397 struct got_worktree *worktree = NULL;
13398 struct got_repository *repo = NULL;
13399 struct got_fileindex *fileindex = NULL;
13400 char *cwd = NULL, *id_str = NULL, *author = NULL;
13401 char *gitconfig_path = NULL;
13402 struct got_reference *branch = NULL, *wt_branch = NULL;
13403 struct got_object_id *branch_tip = NULL, *yca_id = NULL;
13404 struct got_object_id *wt_branch_tip = NULL;
13405 int ch, merge_in_progress = 0, abort_merge = 0, continue_merge = 0;
13406 int allow_conflict = 0, prefer_fast_forward = 1, interrupt_merge = 0;
13407 struct got_update_progress_arg upa;
13408 struct got_object_id *merge_commit_id = NULL;
13409 char *branch_name = NULL;
13410 int *pack_fds = NULL;
13412 memset(&upa, 0, sizeof(upa));
13414 #ifndef PROFILE
13415 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
13416 "unveil", NULL) == -1)
13417 err(1, "pledge");
13418 #endif
13420 while ((ch = getopt(argc, argv, "aCcMn")) != -1) {
13421 switch (ch) {
13422 case 'a':
13423 abort_merge = 1;
13424 break;
13425 case 'C':
13426 allow_conflict = 1;
13427 break;
13428 case 'c':
13429 continue_merge = 1;
13430 break;
13431 case 'M':
13432 prefer_fast_forward = 0;
13433 break;
13434 case 'n':
13435 interrupt_merge = 1;
13436 break;
13437 default:
13438 usage_merge();
13439 /* NOTREACHED */
13443 argc -= optind;
13444 argv += optind;
13446 if (abort_merge) {
13447 if (continue_merge)
13448 option_conflict('a', 'c');
13449 if (!prefer_fast_forward)
13450 option_conflict('a', 'M');
13451 if (interrupt_merge)
13452 option_conflict('a', 'n');
13453 } else if (continue_merge) {
13454 if (!prefer_fast_forward)
13455 option_conflict('c', 'M');
13456 if (interrupt_merge)
13457 option_conflict('c', 'n');
13459 if (allow_conflict) {
13460 if (!continue_merge)
13461 errx(1, "-C option requires -c");
13463 if (abort_merge || continue_merge) {
13464 if (argc != 0)
13465 usage_merge();
13466 } else if (argc != 1)
13467 usage_merge();
13469 cwd = getcwd(NULL, 0);
13470 if (cwd == NULL) {
13471 error = got_error_from_errno("getcwd");
13472 goto done;
13475 error = got_repo_pack_fds_open(&pack_fds);
13476 if (error != NULL)
13477 goto done;
13479 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
13480 if (error) {
13481 if (error->code == GOT_ERR_NOT_WORKTREE)
13482 error = wrap_not_worktree_error(error,
13483 "merge", cwd);
13484 goto done;
13487 error = get_gitconfig_path(&gitconfig_path);
13488 if (error)
13489 goto done;
13490 error = got_repo_open(&repo,
13491 worktree ? got_worktree_get_repo_path(worktree) : cwd,
13492 gitconfig_path, pack_fds);
13493 if (error != NULL)
13494 goto done;
13496 if (worktree != NULL) {
13497 error = worktree_has_logmsg_ref("merge", worktree, repo);
13498 if (error)
13499 goto done;
13502 error = apply_unveil(got_repo_get_path(repo), 0,
13503 worktree ? got_worktree_get_root_path(worktree) : NULL);
13504 if (error)
13505 goto done;
13507 error = check_rebase_or_histedit_in_progress(worktree);
13508 if (error)
13509 goto done;
13511 error = got_worktree_merge_in_progress(&merge_in_progress, worktree,
13512 repo);
13513 if (error)
13514 goto done;
13516 if (merge_in_progress && !(abort_merge || continue_merge)) {
13517 error = got_error(GOT_ERR_MERGE_BUSY);
13518 goto done;
13521 if (!merge_in_progress && (abort_merge || continue_merge)) {
13522 error = got_error(GOT_ERR_NOT_MERGING);
13523 goto done;
13526 if (abort_merge) {
13527 error = got_worktree_merge_continue(&branch_name,
13528 &branch_tip, &fileindex, worktree, repo);
13529 if (error)
13530 goto done;
13531 error = got_worktree_merge_abort(worktree, fileindex, repo,
13532 abort_progress, &upa);
13533 if (error)
13534 goto done;
13535 printf("Merge of %s aborted\n", branch_name);
13536 goto done; /* nothing else to do */
13539 if (strncmp(got_worktree_get_head_ref_name(worktree),
13540 "refs/heads/", 11) != 0) {
13541 error = got_error_fmt(GOT_ERR_COMMIT_BRANCH,
13542 "work tree's current branch %s is outside the "
13543 "\"refs/heads/\" reference namespace; "
13544 "update -b required",
13545 got_worktree_get_head_ref_name(worktree));
13546 goto done;
13549 error = get_author(&author, repo, worktree);
13550 if (error)
13551 goto done;
13553 error = got_ref_open(&wt_branch, repo,
13554 got_worktree_get_head_ref_name(worktree), 0);
13555 if (error)
13556 goto done;
13557 error = got_ref_resolve(&wt_branch_tip, repo, wt_branch);
13558 if (error)
13559 goto done;
13561 if (continue_merge) {
13562 struct got_object_id *base_commit_id;
13563 base_commit_id = got_worktree_get_base_commit_id(worktree);
13564 if (got_object_id_cmp(wt_branch_tip, base_commit_id) != 0) {
13565 error = got_error(GOT_ERR_MERGE_COMMIT_OUT_OF_DATE);
13566 goto done;
13568 error = got_worktree_merge_continue(&branch_name,
13569 &branch_tip, &fileindex, worktree, repo);
13570 if (error)
13571 goto done;
13572 } else {
13573 error = got_ref_open(&branch, repo, argv[0], 0);
13574 if (error != NULL)
13575 goto done;
13576 branch_name = strdup(got_ref_get_name(branch));
13577 if (branch_name == NULL) {
13578 error = got_error_from_errno("strdup");
13579 goto done;
13581 error = got_ref_resolve(&branch_tip, repo, branch);
13582 if (error)
13583 goto done;
13586 error = got_commit_graph_find_youngest_common_ancestor(&yca_id,
13587 wt_branch_tip, branch_tip, 0, 0, repo,
13588 check_cancelled, NULL);
13589 if (error && error->code != GOT_ERR_ANCESTRY)
13590 goto done;
13592 if (!continue_merge) {
13593 error = check_path_prefix(wt_branch_tip, branch_tip,
13594 got_worktree_get_path_prefix(worktree),
13595 GOT_ERR_MERGE_PATH, repo);
13596 if (error)
13597 goto done;
13598 error = got_worktree_merge_prepare(&fileindex, worktree, repo);
13599 if (error)
13600 goto done;
13601 if (prefer_fast_forward && yca_id &&
13602 got_object_id_cmp(wt_branch_tip, yca_id) == 0) {
13603 struct got_pathlist_head paths;
13604 if (interrupt_merge) {
13605 error = got_error_fmt(GOT_ERR_BAD_OPTION,
13606 "there are no changes to merge since %s "
13607 "is already based on %s; merge cannot be "
13608 "interrupted for amending; -n",
13609 branch_name, got_ref_get_name(wt_branch));
13610 goto done;
13612 printf("Forwarding %s to %s\n",
13613 got_ref_get_name(wt_branch), branch_name);
13614 error = got_ref_change_ref(wt_branch, branch_tip);
13615 if (error)
13616 goto done;
13617 error = got_ref_write(wt_branch, repo);
13618 if (error)
13619 goto done;
13620 error = got_worktree_set_base_commit_id(worktree, repo,
13621 branch_tip);
13622 if (error)
13623 goto done;
13624 TAILQ_INIT(&paths);
13625 error = got_pathlist_append(&paths, "", NULL);
13626 if (error)
13627 goto done;
13628 error = got_worktree_checkout_files(worktree,
13629 &paths, repo, update_progress, &upa,
13630 check_cancelled, NULL);
13631 got_pathlist_free(&paths, GOT_PATHLIST_FREE_NONE);
13632 if (error)
13633 goto done;
13634 if (upa.did_something) {
13635 char *id_str;
13636 error = got_object_id_str(&id_str, branch_tip);
13637 if (error)
13638 goto done;
13639 printf("Updated to commit %s\n", id_str);
13640 free(id_str);
13641 } else
13642 printf("Already up-to-date\n");
13643 print_update_progress_stats(&upa);
13644 goto done;
13646 error = got_worktree_merge_write_refs(worktree, branch, repo);
13647 if (error)
13648 goto done;
13650 error = got_worktree_merge_branch(worktree, fileindex,
13651 yca_id, branch_tip, repo, update_progress, &upa,
13652 check_cancelled, NULL);
13653 if (error)
13654 goto done;
13655 print_merge_progress_stats(&upa);
13656 if (!upa.did_something) {
13657 error = got_worktree_merge_abort(worktree, fileindex,
13658 repo, abort_progress, &upa);
13659 if (error)
13660 goto done;
13661 printf("Already up-to-date\n");
13662 goto done;
13666 if (interrupt_merge) {
13667 error = got_worktree_merge_postpone(worktree, fileindex);
13668 if (error)
13669 goto done;
13670 printf("Merge of %s interrupted on request\n", branch_name);
13671 } else if (upa.conflicts > 0 || upa.missing > 0 ||
13672 upa.not_deleted > 0 || upa.unversioned > 0) {
13673 error = got_worktree_merge_postpone(worktree, fileindex);
13674 if (error)
13675 goto done;
13676 if (upa.conflicts > 0 && upa.missing == 0 &&
13677 upa.not_deleted == 0 && upa.unversioned == 0) {
13678 error = got_error_msg(GOT_ERR_CONFLICTS,
13679 "conflicts must be resolved before merging "
13680 "can continue");
13681 } else if (upa.conflicts > 0) {
13682 error = got_error_msg(GOT_ERR_CONFLICTS,
13683 "conflicts must be resolved before merging "
13684 "can continue; changes destined for some "
13685 "files were not yet merged and "
13686 "should be merged manually if required before the "
13687 "merge operation is continued");
13688 } else {
13689 error = got_error_msg(GOT_ERR_CONFLICTS,
13690 "changes destined for some "
13691 "files were not yet merged and should be "
13692 "merged manually if required before the "
13693 "merge operation is continued");
13695 goto done;
13696 } else {
13697 error = got_worktree_merge_commit(&merge_commit_id, worktree,
13698 fileindex, author, NULL, 1, branch_tip, branch_name,
13699 allow_conflict, repo, continue_merge ? print_status : NULL,
13700 NULL);
13701 if (error)
13702 goto done;
13703 error = got_worktree_merge_complete(worktree, fileindex, repo);
13704 if (error)
13705 goto done;
13706 error = got_object_id_str(&id_str, merge_commit_id);
13707 if (error)
13708 goto done;
13709 printf("Merged %s into %s: %s\n", branch_name,
13710 got_worktree_get_head_ref_name(worktree),
13711 id_str);
13714 done:
13715 free(gitconfig_path);
13716 free(id_str);
13717 free(merge_commit_id);
13718 free(author);
13719 free(branch_tip);
13720 free(branch_name);
13721 free(yca_id);
13722 if (branch)
13723 got_ref_close(branch);
13724 if (wt_branch)
13725 got_ref_close(wt_branch);
13726 if (worktree)
13727 got_worktree_close(worktree);
13728 if (repo) {
13729 const struct got_error *close_err = got_repo_close(repo);
13730 if (error == NULL)
13731 error = close_err;
13733 if (pack_fds) {
13734 const struct got_error *pack_err =
13735 got_repo_pack_fds_close(pack_fds);
13736 if (error == NULL)
13737 error = pack_err;
13739 return error;
13742 __dead static void
13743 usage_stage(void)
13745 fprintf(stderr, "usage: %s stage [-lpS] [-F response-script] "
13746 "[path ...]\n", getprogname());
13747 exit(1);
13750 static const struct got_error *
13751 print_stage(void *arg, unsigned char status, unsigned char staged_status,
13752 const char *path, struct got_object_id *blob_id,
13753 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
13754 int dirfd, const char *de_name)
13756 const struct got_error *err = NULL;
13757 char *id_str = NULL;
13759 if (staged_status != GOT_STATUS_ADD &&
13760 staged_status != GOT_STATUS_MODIFY &&
13761 staged_status != GOT_STATUS_DELETE)
13762 return NULL;
13764 if (staged_status == GOT_STATUS_ADD ||
13765 staged_status == GOT_STATUS_MODIFY)
13766 err = got_object_id_str(&id_str, staged_blob_id);
13767 else
13768 err = got_object_id_str(&id_str, blob_id);
13769 if (err)
13770 return err;
13772 printf("%s %c %s\n", id_str, staged_status, path);
13773 free(id_str);
13774 return NULL;
13777 static const struct got_error *
13778 cmd_stage(int argc, char *argv[])
13780 const struct got_error *error = NULL;
13781 struct got_repository *repo = NULL;
13782 struct got_worktree *worktree = NULL;
13783 char *cwd = NULL;
13784 struct got_pathlist_head paths;
13785 int ch, list_stage = 0, pflag = 0, allow_bad_symlinks = 0;
13786 FILE *patch_script_file = NULL;
13787 const char *patch_script_path = NULL;
13788 struct choose_patch_arg cpa;
13789 int *pack_fds = NULL;
13791 TAILQ_INIT(&paths);
13793 #ifndef PROFILE
13794 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
13795 "unveil", NULL) == -1)
13796 err(1, "pledge");
13797 #endif
13799 while ((ch = getopt(argc, argv, "F:lpS")) != -1) {
13800 switch (ch) {
13801 case 'F':
13802 patch_script_path = optarg;
13803 break;
13804 case 'l':
13805 list_stage = 1;
13806 break;
13807 case 'p':
13808 pflag = 1;
13809 break;
13810 case 'S':
13811 allow_bad_symlinks = 1;
13812 break;
13813 default:
13814 usage_stage();
13815 /* NOTREACHED */
13819 argc -= optind;
13820 argv += optind;
13822 if (list_stage && (pflag || patch_script_path))
13823 errx(1, "-l option cannot be used with other options");
13824 if (patch_script_path && !pflag)
13825 errx(1, "-F option can only be used together with -p option");
13827 cwd = getcwd(NULL, 0);
13828 if (cwd == NULL) {
13829 error = got_error_from_errno("getcwd");
13830 goto done;
13833 error = got_repo_pack_fds_open(&pack_fds);
13834 if (error != NULL)
13835 goto done;
13837 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
13838 if (error) {
13839 if (error->code == GOT_ERR_NOT_WORKTREE)
13840 error = wrap_not_worktree_error(error, "stage", cwd);
13841 goto done;
13844 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
13845 NULL, pack_fds);
13846 if (error != NULL)
13847 goto done;
13849 if (patch_script_path) {
13850 patch_script_file = fopen(patch_script_path, "re");
13851 if (patch_script_file == NULL) {
13852 error = got_error_from_errno2("fopen",
13853 patch_script_path);
13854 goto done;
13857 error = apply_unveil(got_repo_get_path(repo), 0,
13858 got_worktree_get_root_path(worktree));
13859 if (error)
13860 goto done;
13862 error = check_merge_in_progress(worktree, repo);
13863 if (error)
13864 goto done;
13866 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
13867 if (error)
13868 goto done;
13870 if (list_stage)
13871 error = got_worktree_status(worktree, &paths, repo, 0,
13872 print_stage, NULL, check_cancelled, NULL);
13873 else {
13874 cpa.patch_script_file = patch_script_file;
13875 cpa.action = "stage";
13876 error = got_worktree_stage(worktree, &paths,
13877 pflag ? NULL : print_status, NULL,
13878 pflag ? choose_patch : NULL, &cpa,
13879 allow_bad_symlinks, repo);
13881 done:
13882 if (patch_script_file && fclose(patch_script_file) == EOF &&
13883 error == NULL)
13884 error = got_error_from_errno2("fclose", patch_script_path);
13885 if (repo) {
13886 const struct got_error *close_err = got_repo_close(repo);
13887 if (error == NULL)
13888 error = close_err;
13890 if (worktree)
13891 got_worktree_close(worktree);
13892 if (pack_fds) {
13893 const struct got_error *pack_err =
13894 got_repo_pack_fds_close(pack_fds);
13895 if (error == NULL)
13896 error = pack_err;
13898 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
13899 free(cwd);
13900 return error;
13903 __dead static void
13904 usage_unstage(void)
13906 fprintf(stderr, "usage: %s unstage [-p] [-F response-script] "
13907 "[path ...]\n", getprogname());
13908 exit(1);
13912 static const struct got_error *
13913 cmd_unstage(int argc, char *argv[])
13915 const struct got_error *error = NULL;
13916 struct got_repository *repo = NULL;
13917 struct got_worktree *worktree = NULL;
13918 char *cwd = NULL;
13919 struct got_pathlist_head paths;
13920 int ch, pflag = 0;
13921 struct got_update_progress_arg upa;
13922 FILE *patch_script_file = NULL;
13923 const char *patch_script_path = NULL;
13924 struct choose_patch_arg cpa;
13925 int *pack_fds = NULL;
13927 TAILQ_INIT(&paths);
13929 #ifndef PROFILE
13930 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
13931 "unveil", NULL) == -1)
13932 err(1, "pledge");
13933 #endif
13935 while ((ch = getopt(argc, argv, "F:p")) != -1) {
13936 switch (ch) {
13937 case 'F':
13938 patch_script_path = optarg;
13939 break;
13940 case 'p':
13941 pflag = 1;
13942 break;
13943 default:
13944 usage_unstage();
13945 /* NOTREACHED */
13949 argc -= optind;
13950 argv += optind;
13952 if (patch_script_path && !pflag)
13953 errx(1, "-F option can only be used together with -p option");
13955 cwd = getcwd(NULL, 0);
13956 if (cwd == NULL) {
13957 error = got_error_from_errno("getcwd");
13958 goto done;
13961 error = got_repo_pack_fds_open(&pack_fds);
13962 if (error != NULL)
13963 goto done;
13965 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
13966 if (error) {
13967 if (error->code == GOT_ERR_NOT_WORKTREE)
13968 error = wrap_not_worktree_error(error, "unstage", cwd);
13969 goto done;
13972 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
13973 NULL, pack_fds);
13974 if (error != NULL)
13975 goto done;
13977 if (patch_script_path) {
13978 patch_script_file = fopen(patch_script_path, "re");
13979 if (patch_script_file == NULL) {
13980 error = got_error_from_errno2("fopen",
13981 patch_script_path);
13982 goto done;
13986 error = apply_unveil(got_repo_get_path(repo), 0,
13987 got_worktree_get_root_path(worktree));
13988 if (error)
13989 goto done;
13991 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
13992 if (error)
13993 goto done;
13995 cpa.patch_script_file = patch_script_file;
13996 cpa.action = "unstage";
13997 memset(&upa, 0, sizeof(upa));
13998 error = got_worktree_unstage(worktree, &paths, update_progress,
13999 &upa, pflag ? choose_patch : NULL, &cpa, repo);
14000 if (!error)
14001 print_merge_progress_stats(&upa);
14002 done:
14003 if (patch_script_file && fclose(patch_script_file) == EOF &&
14004 error == NULL)
14005 error = got_error_from_errno2("fclose", patch_script_path);
14006 if (repo) {
14007 const struct got_error *close_err = got_repo_close(repo);
14008 if (error == NULL)
14009 error = close_err;
14011 if (worktree)
14012 got_worktree_close(worktree);
14013 if (pack_fds) {
14014 const struct got_error *pack_err =
14015 got_repo_pack_fds_close(pack_fds);
14016 if (error == NULL)
14017 error = pack_err;
14019 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
14020 free(cwd);
14021 return error;
14024 __dead static void
14025 usage_cat(void)
14027 fprintf(stderr, "usage: %s cat [-P] [-c commit] [-r repository-path] "
14028 "arg ...\n", getprogname());
14029 exit(1);
14032 static const struct got_error *
14033 cat_blob(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
14035 const struct got_error *err;
14036 struct got_blob_object *blob;
14037 int fd = -1;
14039 fd = got_opentempfd();
14040 if (fd == -1)
14041 return got_error_from_errno("got_opentempfd");
14043 err = got_object_open_as_blob(&blob, repo, id, 8192, fd);
14044 if (err)
14045 goto done;
14047 err = got_object_blob_dump_to_file(NULL, NULL, NULL, outfile, blob);
14048 done:
14049 if (fd != -1 && close(fd) == -1 && err == NULL)
14050 err = got_error_from_errno("close");
14051 if (blob)
14052 got_object_blob_close(blob);
14053 return err;
14056 static const struct got_error *
14057 cat_tree(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
14059 const struct got_error *err;
14060 struct got_tree_object *tree;
14061 int nentries, i;
14063 err = got_object_open_as_tree(&tree, repo, id);
14064 if (err)
14065 return err;
14067 nentries = got_object_tree_get_nentries(tree);
14068 for (i = 0; i < nentries; i++) {
14069 struct got_tree_entry *te;
14070 char *id_str;
14071 if (sigint_received || sigpipe_received)
14072 break;
14073 te = got_object_tree_get_entry(tree, i);
14074 err = got_object_id_str(&id_str, got_tree_entry_get_id(te));
14075 if (err)
14076 break;
14077 fprintf(outfile, "%s %.7o %s\n", id_str,
14078 got_tree_entry_get_mode(te),
14079 got_tree_entry_get_name(te));
14080 free(id_str);
14083 got_object_tree_close(tree);
14084 return err;
14087 static const struct got_error *
14088 cat_commit(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
14090 const struct got_error *err;
14091 struct got_commit_object *commit;
14092 const struct got_object_id_queue *parent_ids;
14093 struct got_object_qid *pid;
14094 char *id_str = NULL;
14095 const char *logmsg = NULL;
14096 char gmtoff[6];
14098 err = got_object_open_as_commit(&commit, repo, id);
14099 if (err)
14100 return err;
14102 err = got_object_id_str(&id_str, got_object_commit_get_tree_id(commit));
14103 if (err)
14104 goto done;
14106 fprintf(outfile, "%s%s\n", GOT_COMMIT_LABEL_TREE, id_str);
14107 parent_ids = got_object_commit_get_parent_ids(commit);
14108 fprintf(outfile, "numparents %d\n",
14109 got_object_commit_get_nparents(commit));
14110 STAILQ_FOREACH(pid, parent_ids, entry) {
14111 char *pid_str;
14112 err = got_object_id_str(&pid_str, &pid->id);
14113 if (err)
14114 goto done;
14115 fprintf(outfile, "%s%s\n", GOT_COMMIT_LABEL_PARENT, pid_str);
14116 free(pid_str);
14118 got_date_format_gmtoff(gmtoff, sizeof(gmtoff),
14119 got_object_commit_get_author_gmtoff(commit));
14120 fprintf(outfile, "%s%s %lld %s\n", GOT_COMMIT_LABEL_AUTHOR,
14121 got_object_commit_get_author(commit),
14122 (long long)got_object_commit_get_author_time(commit),
14123 gmtoff);
14125 got_date_format_gmtoff(gmtoff, sizeof(gmtoff),
14126 got_object_commit_get_committer_gmtoff(commit));
14127 fprintf(outfile, "%s%s %lld %s\n", GOT_COMMIT_LABEL_COMMITTER,
14128 got_object_commit_get_committer(commit),
14129 (long long)got_object_commit_get_committer_time(commit),
14130 gmtoff);
14132 logmsg = got_object_commit_get_logmsg_raw(commit);
14133 fprintf(outfile, "messagelen %zd\n", strlen(logmsg));
14134 fprintf(outfile, "%s", logmsg);
14135 done:
14136 free(id_str);
14137 got_object_commit_close(commit);
14138 return err;
14141 static const struct got_error *
14142 cat_tag(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
14144 const struct got_error *err;
14145 struct got_tag_object *tag;
14146 char *id_str = NULL;
14147 const char *tagmsg = NULL;
14148 char gmtoff[6];
14150 err = got_object_open_as_tag(&tag, repo, id);
14151 if (err)
14152 return err;
14154 err = got_object_id_str(&id_str, got_object_tag_get_object_id(tag));
14155 if (err)
14156 goto done;
14158 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_OBJECT, id_str);
14160 switch (got_object_tag_get_object_type(tag)) {
14161 case GOT_OBJ_TYPE_BLOB:
14162 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
14163 GOT_OBJ_LABEL_BLOB);
14164 break;
14165 case GOT_OBJ_TYPE_TREE:
14166 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
14167 GOT_OBJ_LABEL_TREE);
14168 break;
14169 case GOT_OBJ_TYPE_COMMIT:
14170 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
14171 GOT_OBJ_LABEL_COMMIT);
14172 break;
14173 case GOT_OBJ_TYPE_TAG:
14174 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
14175 GOT_OBJ_LABEL_TAG);
14176 break;
14177 default:
14178 break;
14181 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TAG,
14182 got_object_tag_get_name(tag));
14184 got_date_format_gmtoff(gmtoff, sizeof(gmtoff),
14185 got_object_tag_get_tagger_gmtoff(tag));
14186 fprintf(outfile, "%s%s %lld %s\n", GOT_TAG_LABEL_TAGGER,
14187 got_object_tag_get_tagger(tag),
14188 (long long)got_object_tag_get_tagger_time(tag),
14189 gmtoff);
14191 tagmsg = got_object_tag_get_message(tag);
14192 fprintf(outfile, "messagelen %zd\n", strlen(tagmsg));
14193 fprintf(outfile, "%s", tagmsg);
14194 done:
14195 free(id_str);
14196 got_object_tag_close(tag);
14197 return err;
14200 static const struct got_error *
14201 cmd_cat(int argc, char *argv[])
14203 const struct got_error *error;
14204 struct got_repository *repo = NULL;
14205 struct got_worktree *worktree = NULL;
14206 char *cwd = NULL, *repo_path = NULL, *label = NULL;
14207 char *keyword_idstr = NULL;
14208 const char *commit_id_str = NULL;
14209 struct got_object_id *id = NULL, *commit_id = NULL;
14210 struct got_commit_object *commit = NULL;
14211 int ch, obj_type, i, force_path = 0;
14212 struct got_reflist_head refs;
14213 int *pack_fds = NULL;
14215 TAILQ_INIT(&refs);
14217 #ifndef PROFILE
14218 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
14219 NULL) == -1)
14220 err(1, "pledge");
14221 #endif
14223 while ((ch = getopt(argc, argv, "c:Pr:")) != -1) {
14224 switch (ch) {
14225 case 'c':
14226 commit_id_str = optarg;
14227 break;
14228 case 'P':
14229 force_path = 1;
14230 break;
14231 case 'r':
14232 repo_path = realpath(optarg, NULL);
14233 if (repo_path == NULL)
14234 return got_error_from_errno2("realpath",
14235 optarg);
14236 got_path_strip_trailing_slashes(repo_path);
14237 break;
14238 default:
14239 usage_cat();
14240 /* NOTREACHED */
14244 argc -= optind;
14245 argv += optind;
14247 cwd = getcwd(NULL, 0);
14248 if (cwd == NULL) {
14249 error = got_error_from_errno("getcwd");
14250 goto done;
14253 error = got_repo_pack_fds_open(&pack_fds);
14254 if (error != NULL)
14255 goto done;
14257 if (repo_path == NULL) {
14258 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
14259 if (error && error->code != GOT_ERR_NOT_WORKTREE)
14260 goto done;
14261 if (worktree) {
14262 repo_path = strdup(
14263 got_worktree_get_repo_path(worktree));
14264 if (repo_path == NULL) {
14265 error = got_error_from_errno("strdup");
14266 goto done;
14269 if (commit_id_str == NULL) {
14270 /* Release work tree lock. */
14271 got_worktree_close(worktree);
14272 worktree = NULL;
14277 if (repo_path == NULL) {
14278 repo_path = strdup(cwd);
14279 if (repo_path == NULL)
14280 return got_error_from_errno("strdup");
14283 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
14284 free(repo_path);
14285 if (error != NULL)
14286 goto done;
14288 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
14289 if (error)
14290 goto done;
14292 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
14293 if (error)
14294 goto done;
14296 if (commit_id_str != NULL) {
14297 error = got_keyword_to_idstr(&keyword_idstr, commit_id_str,
14298 repo, worktree);
14299 if (error != NULL)
14300 goto done;
14301 if (keyword_idstr != NULL)
14302 commit_id_str = keyword_idstr;
14303 if (worktree != NULL) {
14304 got_worktree_close(worktree);
14305 worktree = NULL;
14307 } else
14308 commit_id_str = GOT_REF_HEAD;
14309 error = got_repo_match_object_id(&commit_id, NULL,
14310 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
14311 if (error)
14312 goto done;
14314 error = got_object_open_as_commit(&commit, repo, commit_id);
14315 if (error)
14316 goto done;
14318 for (i = 0; i < argc; i++) {
14319 if (force_path) {
14320 error = got_object_id_by_path(&id, repo, commit,
14321 argv[i]);
14322 if (error)
14323 break;
14324 } else {
14325 error = got_repo_match_object_id(&id, &label, argv[i],
14326 GOT_OBJ_TYPE_ANY, NULL /* do not resolve tags */,
14327 repo);
14328 if (error) {
14329 if (error->code != GOT_ERR_BAD_OBJ_ID_STR &&
14330 error->code != GOT_ERR_NOT_REF)
14331 break;
14332 error = got_object_id_by_path(&id, repo,
14333 commit, argv[i]);
14334 if (error)
14335 break;
14339 error = got_object_get_type(&obj_type, repo, id);
14340 if (error)
14341 break;
14343 switch (obj_type) {
14344 case GOT_OBJ_TYPE_BLOB:
14345 error = cat_blob(id, repo, stdout);
14346 break;
14347 case GOT_OBJ_TYPE_TREE:
14348 error = cat_tree(id, repo, stdout);
14349 break;
14350 case GOT_OBJ_TYPE_COMMIT:
14351 error = cat_commit(id, repo, stdout);
14352 break;
14353 case GOT_OBJ_TYPE_TAG:
14354 error = cat_tag(id, repo, stdout);
14355 break;
14356 default:
14357 error = got_error(GOT_ERR_OBJ_TYPE);
14358 break;
14360 if (error)
14361 break;
14362 free(label);
14363 label = NULL;
14364 free(id);
14365 id = NULL;
14367 done:
14368 free(label);
14369 free(id);
14370 free(commit_id);
14371 free(keyword_idstr);
14372 if (commit)
14373 got_object_commit_close(commit);
14374 if (worktree)
14375 got_worktree_close(worktree);
14376 if (repo) {
14377 const struct got_error *close_err = got_repo_close(repo);
14378 if (error == NULL)
14379 error = close_err;
14381 if (pack_fds) {
14382 const struct got_error *pack_err =
14383 got_repo_pack_fds_close(pack_fds);
14384 if (error == NULL)
14385 error = pack_err;
14388 got_ref_list_free(&refs);
14389 return error;
14392 __dead static void
14393 usage_info(void)
14395 fprintf(stderr, "usage: %s info [path ...]\n",
14396 getprogname());
14397 exit(1);
14400 static const struct got_error *
14401 print_path_info(void *arg, const char *path, mode_t mode, time_t mtime,
14402 struct got_object_id *blob_id, struct got_object_id *staged_blob_id,
14403 struct got_object_id *commit_id)
14405 const struct got_error *err = NULL;
14406 char *id_str = NULL;
14407 char datebuf[128];
14408 struct tm mytm, *tm;
14409 struct got_pathlist_head *paths = arg;
14410 struct got_pathlist_entry *pe;
14413 * Clear error indication from any of the path arguments which
14414 * would cause this file index entry to be displayed.
14416 TAILQ_FOREACH(pe, paths, entry) {
14417 if (got_path_cmp(path, pe->path, strlen(path),
14418 pe->path_len) == 0 ||
14419 got_path_is_child(path, pe->path, pe->path_len))
14420 pe->data = NULL; /* no error */
14423 printf(GOT_COMMIT_SEP_STR);
14424 if (S_ISLNK(mode))
14425 printf("symlink: %s\n", path);
14426 else if (S_ISREG(mode)) {
14427 printf("file: %s\n", path);
14428 printf("mode: %o\n", mode & (S_IRWXU | S_IRWXG | S_IRWXO));
14429 } else if (S_ISDIR(mode))
14430 printf("directory: %s\n", path);
14431 else
14432 printf("something: %s\n", path);
14434 tm = localtime_r(&mtime, &mytm);
14435 if (tm == NULL)
14436 return NULL;
14437 if (strftime(datebuf, sizeof(datebuf), "%c %Z", tm) == 0)
14438 return got_error(GOT_ERR_NO_SPACE);
14439 printf("timestamp: %s\n", datebuf);
14441 if (blob_id) {
14442 err = got_object_id_str(&id_str, blob_id);
14443 if (err)
14444 return err;
14445 printf("based on blob: %s\n", id_str);
14446 free(id_str);
14449 if (staged_blob_id) {
14450 err = got_object_id_str(&id_str, staged_blob_id);
14451 if (err)
14452 return err;
14453 printf("based on staged blob: %s\n", id_str);
14454 free(id_str);
14457 if (commit_id) {
14458 err = got_object_id_str(&id_str, commit_id);
14459 if (err)
14460 return err;
14461 printf("based on commit: %s\n", id_str);
14462 free(id_str);
14465 return NULL;
14468 static const struct got_error *
14469 cmd_info(int argc, char *argv[])
14471 const struct got_error *error = NULL;
14472 struct got_worktree *worktree = NULL;
14473 char *cwd = NULL, *id_str = NULL;
14474 struct got_pathlist_head paths;
14475 char *uuidstr = NULL;
14476 int ch, show_files = 0;
14478 TAILQ_INIT(&paths);
14480 #ifndef PROFILE
14481 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
14482 NULL) == -1)
14483 err(1, "pledge");
14484 #endif
14486 while ((ch = getopt(argc, argv, "")) != -1) {
14487 switch (ch) {
14488 default:
14489 usage_info();
14490 /* NOTREACHED */
14494 argc -= optind;
14495 argv += optind;
14497 cwd = getcwd(NULL, 0);
14498 if (cwd == NULL) {
14499 error = got_error_from_errno("getcwd");
14500 goto done;
14503 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
14504 if (error) {
14505 if (error->code == GOT_ERR_NOT_WORKTREE)
14506 error = wrap_not_worktree_error(error, "info", cwd);
14507 goto done;
14510 #ifndef PROFILE
14511 /* Remove "wpath cpath proc exec sendfd" promises. */
14512 if (pledge("stdio rpath flock unveil", NULL) == -1)
14513 err(1, "pledge");
14514 #endif
14515 error = apply_unveil(NULL, 0, got_worktree_get_root_path(worktree));
14516 if (error)
14517 goto done;
14519 if (argc >= 1) {
14520 error = get_worktree_paths_from_argv(&paths, argc, argv,
14521 worktree);
14522 if (error)
14523 goto done;
14524 show_files = 1;
14527 error = got_object_id_str(&id_str,
14528 got_worktree_get_base_commit_id(worktree));
14529 if (error)
14530 goto done;
14532 error = got_worktree_get_uuid(&uuidstr, worktree);
14533 if (error)
14534 goto done;
14536 printf("work tree: %s\n", got_worktree_get_root_path(worktree));
14537 printf("work tree base commit: %s\n", id_str);
14538 printf("work tree path prefix: %s\n",
14539 got_worktree_get_path_prefix(worktree));
14540 printf("work tree branch reference: %s\n",
14541 got_worktree_get_head_ref_name(worktree));
14542 printf("work tree UUID: %s\n", uuidstr);
14543 printf("repository: %s\n", got_worktree_get_repo_path(worktree));
14545 if (show_files) {
14546 struct got_pathlist_entry *pe;
14547 TAILQ_FOREACH(pe, &paths, entry) {
14548 if (pe->path_len == 0)
14549 continue;
14551 * Assume this path will fail. This will be corrected
14552 * in print_path_info() in case the path does suceeed.
14554 pe->data = (void *)got_error(GOT_ERR_BAD_PATH);
14556 error = got_worktree_path_info(worktree, &paths,
14557 print_path_info, &paths, check_cancelled, NULL);
14558 if (error)
14559 goto done;
14560 TAILQ_FOREACH(pe, &paths, entry) {
14561 if (pe->data != NULL) {
14562 const struct got_error *perr;
14564 perr = pe->data;
14565 error = got_error_fmt(perr->code, "%s",
14566 pe->path);
14567 break;
14571 done:
14572 if (worktree)
14573 got_worktree_close(worktree);
14574 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
14575 free(cwd);
14576 free(id_str);
14577 free(uuidstr);
14578 return error;