Blob


1 /*
2 * Copyright (c) 2017 Martin Pieuchot <mpi@openbsd.org>
3 * Copyright (c) 2018, 2019, 2020 Stefan Sperling <stsp@openbsd.org>
4 * Copyright (c) 2020 Ori Bernstein <ori@openbsd.org>
5 *
6 * Permission to use, copy, modify, and distribute this software for any
7 * purpose with or without fee is hereby granted, provided that the above
8 * copyright notice and this permission notice appear in all copies.
9 *
10 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
11 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
12 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
13 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
14 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
15 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
16 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
17 */
19 #include <sys/queue.h>
20 #include <sys/time.h>
21 #include <sys/types.h>
22 #include <sys/stat.h>
23 #include <sys/wait.h>
25 #include <err.h>
26 #include <errno.h>
27 #include <fcntl.h>
28 #include <limits.h>
29 #include <locale.h>
30 #include <ctype.h>
31 #include <sha1.h>
32 #include <signal.h>
33 #include <stdio.h>
34 #include <stdlib.h>
35 #include <string.h>
36 #include <unistd.h>
37 #include <libgen.h>
38 #include <time.h>
39 #include <paths.h>
40 #include <regex.h>
41 #include <getopt.h>
42 #include <util.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"
65 #ifndef nitems
66 #define nitems(_a) (sizeof((_a)) / sizeof((_a)[0]))
67 #endif
69 static volatile sig_atomic_t sigint_received;
70 static volatile sig_atomic_t sigpipe_received;
72 static void
73 catch_sigint(int signo)
74 {
75 sigint_received = 1;
76 }
78 static void
79 catch_sigpipe(int signo)
80 {
81 sigpipe_received = 1;
82 }
85 struct got_cmd {
86 const char *cmd_name;
87 const struct got_error *(*cmd_main)(int, char *[]);
88 void (*cmd_usage)(void);
89 const char *cmd_alias;
90 };
92 __dead static void usage(int, int);
93 __dead static void usage_import(void);
94 __dead static void usage_clone(void);
95 __dead static void usage_fetch(void);
96 __dead static void usage_checkout(void);
97 __dead static void usage_update(void);
98 __dead static void usage_log(void);
99 __dead static void usage_diff(void);
100 __dead static void usage_blame(void);
101 __dead static void usage_tree(void);
102 __dead static void usage_status(void);
103 __dead static void usage_ref(void);
104 __dead static void usage_branch(void);
105 __dead static void usage_tag(void);
106 __dead static void usage_add(void);
107 __dead static void usage_remove(void);
108 __dead static void usage_patch(void);
109 __dead static void usage_revert(void);
110 __dead static void usage_commit(void);
111 __dead static void usage_send(void);
112 __dead static void usage_cherrypick(void);
113 __dead static void usage_backout(void);
114 __dead static void usage_rebase(void);
115 __dead static void usage_histedit(void);
116 __dead static void usage_integrate(void);
117 __dead static void usage_merge(void);
118 __dead static void usage_stage(void);
119 __dead static void usage_unstage(void);
120 __dead static void usage_cat(void);
121 __dead static void usage_info(void);
123 static const struct got_error* cmd_import(int, char *[]);
124 static const struct got_error* cmd_clone(int, char *[]);
125 static const struct got_error* cmd_fetch(int, char *[]);
126 static const struct got_error* cmd_checkout(int, char *[]);
127 static const struct got_error* cmd_update(int, char *[]);
128 static const struct got_error* cmd_log(int, char *[]);
129 static const struct got_error* cmd_diff(int, char *[]);
130 static const struct got_error* cmd_blame(int, char *[]);
131 static const struct got_error* cmd_tree(int, char *[]);
132 static const struct got_error* cmd_status(int, char *[]);
133 static const struct got_error* cmd_ref(int, char *[]);
134 static const struct got_error* cmd_branch(int, char *[]);
135 static const struct got_error* cmd_tag(int, char *[]);
136 static const struct got_error* cmd_add(int, char *[]);
137 static const struct got_error* cmd_remove(int, char *[]);
138 static const struct got_error* cmd_patch(int, char *[]);
139 static const struct got_error* cmd_revert(int, char *[]);
140 static const struct got_error* cmd_commit(int, char *[]);
141 static const struct got_error* cmd_send(int, char *[]);
142 static const struct got_error* cmd_cherrypick(int, char *[]);
143 static const struct got_error* cmd_backout(int, char *[]);
144 static const struct got_error* cmd_rebase(int, char *[]);
145 static const struct got_error* cmd_histedit(int, char *[]);
146 static const struct got_error* cmd_integrate(int, char *[]);
147 static const struct got_error* cmd_merge(int, char *[]);
148 static const struct got_error* cmd_stage(int, char *[]);
149 static const struct got_error* cmd_unstage(int, char *[]);
150 static const struct got_error* cmd_cat(int, char *[]);
151 static const struct got_error* cmd_info(int, char *[]);
153 static const struct got_cmd got_commands[] = {
154 { "import", cmd_import, usage_import, "im" },
155 { "clone", cmd_clone, usage_clone, "cl" },
156 { "fetch", cmd_fetch, usage_fetch, "fe" },
157 { "checkout", cmd_checkout, usage_checkout, "co" },
158 { "update", cmd_update, usage_update, "up" },
159 { "log", cmd_log, usage_log, "" },
160 { "diff", cmd_diff, usage_diff, "di" },
161 { "blame", cmd_blame, usage_blame, "bl" },
162 { "tree", cmd_tree, usage_tree, "tr" },
163 { "status", cmd_status, usage_status, "st" },
164 { "ref", cmd_ref, usage_ref, "" },
165 { "branch", cmd_branch, usage_branch, "br" },
166 { "tag", cmd_tag, usage_tag, "" },
167 { "add", cmd_add, usage_add, "" },
168 { "remove", cmd_remove, usage_remove, "rm" },
169 { "patch", cmd_patch, usage_patch, "pa" },
170 { "revert", cmd_revert, usage_revert, "rv" },
171 { "commit", cmd_commit, usage_commit, "ci" },
172 { "send", cmd_send, usage_send, "se" },
173 { "cherrypick", cmd_cherrypick, usage_cherrypick, "cy" },
174 { "backout", cmd_backout, usage_backout, "bo" },
175 { "rebase", cmd_rebase, usage_rebase, "rb" },
176 { "histedit", cmd_histedit, usage_histedit, "he" },
177 { "integrate", cmd_integrate, usage_integrate,"ig" },
178 { "merge", cmd_merge, usage_merge, "mg" },
179 { "stage", cmd_stage, usage_stage, "sg" },
180 { "unstage", cmd_unstage, usage_unstage, "ug" },
181 { "cat", cmd_cat, usage_cat, "" },
182 { "info", cmd_info, usage_info, "" },
183 };
185 static void
186 list_commands(FILE *fp)
188 size_t i;
190 fprintf(fp, "commands:");
191 for (i = 0; i < nitems(got_commands); i++) {
192 const struct got_cmd *cmd = &got_commands[i];
193 fprintf(fp, " %s", cmd->cmd_name);
195 fputc('\n', fp);
198 __dead static void
199 option_conflict(char a, char b)
201 errx(1, "-%c and -%c options are mutually exclusive", a, b);
204 int
205 main(int argc, char *argv[])
207 const struct got_cmd *cmd;
208 size_t i;
209 int ch;
210 int hflag = 0, Vflag = 0;
211 static const struct option longopts[] = {
212 { "version", no_argument, NULL, 'V' },
213 { NULL, 0, NULL, 0 }
214 };
216 setlocale(LC_CTYPE, "");
218 while ((ch = getopt_long(argc, argv, "+hV", longopts, NULL)) != -1) {
219 switch (ch) {
220 case 'h':
221 hflag = 1;
222 break;
223 case 'V':
224 Vflag = 1;
225 break;
226 default:
227 usage(hflag, 1);
228 /* NOTREACHED */
232 argc -= optind;
233 argv += optind;
234 optind = 1;
235 optreset = 1;
237 if (Vflag) {
238 got_version_print_str();
239 return 0;
242 if (argc <= 0)
243 usage(hflag, hflag ? 0 : 1);
245 signal(SIGINT, catch_sigint);
246 signal(SIGPIPE, catch_sigpipe);
248 for (i = 0; i < nitems(got_commands); i++) {
249 const struct got_error *error;
251 cmd = &got_commands[i];
253 if (strcmp(cmd->cmd_name, argv[0]) != 0 &&
254 strcmp(cmd->cmd_alias, argv[0]) != 0)
255 continue;
257 if (hflag)
258 cmd->cmd_usage();
260 error = cmd->cmd_main(argc, argv);
261 if (error && error->code != GOT_ERR_CANCELLED &&
262 error->code != GOT_ERR_PRIVSEP_EXIT &&
263 !(sigpipe_received &&
264 error->code == GOT_ERR_ERRNO && errno == EPIPE) &&
265 !(sigint_received &&
266 error->code == GOT_ERR_ERRNO && errno == EINTR)) {
267 fprintf(stderr, "%s: %s\n", getprogname(), error->msg);
268 return 1;
271 return 0;
274 fprintf(stderr, "%s: unknown command '%s'\n", getprogname(), argv[0]);
275 list_commands(stderr);
276 return 1;
279 __dead static void
280 usage(int hflag, int status)
282 FILE *fp = (status == 0) ? stdout : stderr;
284 fprintf(fp, "usage: %s [-hV] command [arg ...]\n",
285 getprogname());
286 if (hflag)
287 list_commands(fp);
288 exit(status);
291 static const struct got_error *
292 get_editor(char **abspath)
294 const struct got_error *err = NULL;
295 const char *editor;
297 *abspath = NULL;
299 editor = getenv("VISUAL");
300 if (editor == NULL)
301 editor = getenv("EDITOR");
303 if (editor) {
304 err = got_path_find_prog(abspath, editor);
305 if (err)
306 return err;
309 if (*abspath == NULL) {
310 *abspath = strdup("/bin/ed");
311 if (*abspath == NULL)
312 return got_error_from_errno("strdup");
315 return NULL;
318 static const struct got_error *
319 apply_unveil(const char *repo_path, int repo_read_only,
320 const char *worktree_path)
322 const struct got_error *err;
324 #ifdef PROFILE
325 if (unveil("gmon.out", "rwc") != 0)
326 return got_error_from_errno2("unveil", "gmon.out");
327 #endif
328 if (repo_path && unveil(repo_path, repo_read_only ? "r" : "rwc") != 0)
329 return got_error_from_errno2("unveil", repo_path);
331 if (worktree_path && unveil(worktree_path, "rwc") != 0)
332 return got_error_from_errno2("unveil", worktree_path);
334 if (unveil(GOT_TMPDIR_STR, "rwc") != 0)
335 return got_error_from_errno2("unveil", GOT_TMPDIR_STR);
337 err = got_privsep_unveil_exec_helpers();
338 if (err != NULL)
339 return err;
341 if (unveil(NULL, NULL) != 0)
342 return got_error_from_errno("unveil");
344 return NULL;
347 __dead static void
348 usage_import(void)
350 fprintf(stderr, "usage: %s import [-b branch] [-I pattern] [-m message] "
351 "[-r repository-path] directory\n", getprogname());
352 exit(1);
355 static int
356 spawn_editor(const char *editor, const char *file)
358 pid_t pid;
359 sig_t sighup, sigint, sigquit;
360 int st = -1;
362 sighup = signal(SIGHUP, SIG_IGN);
363 sigint = signal(SIGINT, SIG_IGN);
364 sigquit = signal(SIGQUIT, SIG_IGN);
366 switch (pid = fork()) {
367 case -1:
368 goto doneediting;
369 case 0:
370 execl(editor, editor, file, (char *)NULL);
371 _exit(127);
374 while (waitpid(pid, &st, 0) == -1)
375 if (errno != EINTR)
376 break;
378 doneediting:
379 (void)signal(SIGHUP, sighup);
380 (void)signal(SIGINT, sigint);
381 (void)signal(SIGQUIT, sigquit);
383 if (!WIFEXITED(st)) {
384 errno = EINTR;
385 return -1;
388 return WEXITSTATUS(st);
391 static const struct got_error *
392 edit_logmsg(char **logmsg, const char *editor, const char *logmsg_path,
393 const char *initial_content, size_t initial_content_len,
394 int require_modification)
396 const struct got_error *err = NULL;
397 char *line = NULL;
398 size_t linesize = 0;
399 struct stat st, st2;
400 FILE *fp = NULL;
401 size_t len, logmsg_len;
402 char *initial_content_stripped = NULL, *buf = NULL, *s;
404 *logmsg = NULL;
406 if (stat(logmsg_path, &st) == -1)
407 return got_error_from_errno2("stat", logmsg_path);
409 if (spawn_editor(editor, logmsg_path) == -1)
410 return got_error_from_errno("failed spawning editor");
412 if (stat(logmsg_path, &st2) == -1)
413 return got_error_from_errno("stat");
415 if (require_modification &&
416 st.st_mtime == st2.st_mtime && st.st_size == st2.st_size)
417 return got_error_msg(GOT_ERR_COMMIT_MSG_EMPTY,
418 "no changes made to commit message, aborting");
420 /*
421 * Set up a stripped version of the initial content without comments
422 * and blank lines. We need this in order to check if the message
423 * has in fact been edited.
424 */
425 initial_content_stripped = malloc(initial_content_len + 1);
426 if (initial_content_stripped == NULL)
427 return got_error_from_errno("malloc");
428 initial_content_stripped[0] = '\0';
430 buf = strdup(initial_content);
431 if (buf == NULL) {
432 err = got_error_from_errno("strdup");
433 goto done;
435 s = buf;
436 len = 0;
437 while ((line = strsep(&s, "\n")) != NULL) {
438 if ((line[0] == '#' || (len == 0 && line[0] == '\n')))
439 continue; /* remove comments and leading empty lines */
440 len = strlcat(initial_content_stripped, line,
441 initial_content_len + 1);
442 if (len >= initial_content_len + 1) {
443 err = got_error(GOT_ERR_NO_SPACE);
444 goto done;
447 while (len > 0 && initial_content_stripped[len - 1] == '\n') {
448 initial_content_stripped[len - 1] = '\0';
449 len--;
452 logmsg_len = st2.st_size;
453 *logmsg = malloc(logmsg_len + 1);
454 if (*logmsg == NULL)
455 return got_error_from_errno("malloc");
456 (*logmsg)[0] = '\0';
458 fp = fopen(logmsg_path, "re");
459 if (fp == NULL) {
460 err = got_error_from_errno("fopen");
461 goto done;
464 len = 0;
465 while (getline(&line, &linesize, fp) != -1) {
466 if ((line[0] == '#' || (len == 0 && line[0] == '\n')))
467 continue; /* remove comments and leading empty lines */
468 len = strlcat(*logmsg, line, logmsg_len + 1);
469 if (len >= logmsg_len + 1) {
470 err = got_error(GOT_ERR_NO_SPACE);
471 goto done;
474 free(line);
475 if (ferror(fp)) {
476 err = got_ferror(fp, GOT_ERR_IO);
477 goto done;
479 while (len > 0 && (*logmsg)[len - 1] == '\n') {
480 (*logmsg)[len - 1] = '\0';
481 len--;
484 if (len == 0) {
485 err = got_error_msg(GOT_ERR_COMMIT_MSG_EMPTY,
486 "commit message cannot be empty, aborting");
487 goto done;
489 if (require_modification &&
490 strcmp(*logmsg, initial_content_stripped) == 0)
491 err = got_error_msg(GOT_ERR_COMMIT_MSG_EMPTY,
492 "no changes made to commit message, aborting");
493 done:
494 free(initial_content_stripped);
495 free(buf);
496 if (fp && fclose(fp) == EOF && err == NULL)
497 err = got_error_from_errno("fclose");
498 if (err) {
499 free(*logmsg);
500 *logmsg = NULL;
502 return err;
505 static const struct got_error *
506 collect_import_msg(char **logmsg, char **logmsg_path, const char *editor,
507 const char *path_dir, const char *branch_name)
509 char *initial_content = NULL;
510 const struct got_error *err = NULL;
511 int initial_content_len;
512 int fd = -1;
514 initial_content_len = asprintf(&initial_content,
515 "\n# %s to be imported to branch %s\n", path_dir,
516 branch_name);
517 if (initial_content_len == -1)
518 return got_error_from_errno("asprintf");
520 err = got_opentemp_named_fd(logmsg_path, &fd,
521 GOT_TMPDIR_STR "/got-importmsg", "");
522 if (err)
523 goto done;
525 if (write(fd, initial_content, initial_content_len) == -1) {
526 err = got_error_from_errno2("write", *logmsg_path);
527 goto done;
530 err = edit_logmsg(logmsg, editor, *logmsg_path, initial_content,
531 initial_content_len, 1);
532 done:
533 if (fd != -1 && close(fd) == -1 && err == NULL)
534 err = got_error_from_errno2("close", *logmsg_path);
535 free(initial_content);
536 if (err) {
537 free(*logmsg_path);
538 *logmsg_path = NULL;
540 return err;
543 static const struct got_error *
544 import_progress(void *arg, const char *path)
546 printf("A %s\n", path);
547 return NULL;
550 static const struct got_error *
551 valid_author(const char *author)
553 const char *email = author;
555 /*
556 * Git' expects the author (or committer) to be in the form
557 * "name <email>", which are mostly free form (see the
558 * "committer" description in git-fast-import(1)). We're only
559 * doing this to avoid git's object parser breaking on commits
560 * we create.
561 */
563 while (*author && *author != '\n' && *author != '<' && *author != '>')
564 author++;
565 if (author != email && *author == '<' && *(author - 1) != ' ')
566 return got_error_fmt(GOT_ERR_COMMIT_BAD_AUTHOR, "%s: space "
567 "between author name and email required", email);
568 if (*author++ != '<')
569 return got_error_fmt(GOT_ERR_COMMIT_NO_EMAIL, "%s", email);
570 while (*author && *author != '\n' && *author != '<' && *author != '>')
571 author++;
572 if (strcmp(author, ">") != 0)
573 return got_error_fmt(GOT_ERR_COMMIT_NO_EMAIL, "%s", email);
574 return NULL;
577 static const struct got_error *
578 get_author(char **author, struct got_repository *repo,
579 struct got_worktree *worktree)
581 const struct got_error *err = NULL;
582 const char *got_author = NULL, *name, *email;
583 const struct got_gotconfig *worktree_conf = NULL, *repo_conf = NULL;
585 *author = NULL;
587 if (worktree)
588 worktree_conf = got_worktree_get_gotconfig(worktree);
589 repo_conf = got_repo_get_gotconfig(repo);
591 /*
592 * Priority of potential author information sources, from most
593 * significant to least significant:
594 * 1) work tree's .got/got.conf file
595 * 2) repository's got.conf file
596 * 3) repository's git config file
597 * 4) environment variables
598 * 5) global git config files (in user's home directory or /etc)
599 */
601 if (worktree_conf)
602 got_author = got_gotconfig_get_author(worktree_conf);
603 if (got_author == NULL)
604 got_author = got_gotconfig_get_author(repo_conf);
605 if (got_author == NULL) {
606 name = got_repo_get_gitconfig_author_name(repo);
607 email = got_repo_get_gitconfig_author_email(repo);
608 if (name && email) {
609 if (asprintf(author, "%s <%s>", name, email) == -1)
610 return got_error_from_errno("asprintf");
611 return NULL;
614 got_author = getenv("GOT_AUTHOR");
615 if (got_author == NULL) {
616 name = got_repo_get_global_gitconfig_author_name(repo);
617 email = got_repo_get_global_gitconfig_author_email(
618 repo);
619 if (name && email) {
620 if (asprintf(author, "%s <%s>", name, email)
621 == -1)
622 return got_error_from_errno("asprintf");
623 return NULL;
625 /* TODO: Look up user in password database? */
626 return got_error(GOT_ERR_COMMIT_NO_AUTHOR);
630 *author = strdup(got_author);
631 if (*author == NULL)
632 return got_error_from_errno("strdup");
634 err = valid_author(*author);
635 if (err) {
636 free(*author);
637 *author = NULL;
639 return err;
642 static const struct got_error *
643 get_allowed_signers(char **allowed_signers, struct got_repository *repo,
644 struct got_worktree *worktree)
646 const char *got_allowed_signers = NULL;
647 const struct got_gotconfig *worktree_conf = NULL, *repo_conf = NULL;
649 *allowed_signers = NULL;
651 if (worktree)
652 worktree_conf = got_worktree_get_gotconfig(worktree);
653 repo_conf = got_repo_get_gotconfig(repo);
655 /*
656 * Priority of potential author information sources, from most
657 * significant to least significant:
658 * 1) work tree's .got/got.conf file
659 * 2) repository's got.conf file
660 */
662 if (worktree_conf)
663 got_allowed_signers = got_gotconfig_get_allowed_signers_file(
664 worktree_conf);
665 if (got_allowed_signers == NULL)
666 got_allowed_signers = got_gotconfig_get_allowed_signers_file(
667 repo_conf);
669 if (got_allowed_signers) {
670 *allowed_signers = strdup(got_allowed_signers);
671 if (*allowed_signers == NULL)
672 return got_error_from_errno("strdup");
674 return NULL;
677 static const struct got_error *
678 get_revoked_signers(char **revoked_signers, struct got_repository *repo,
679 struct got_worktree *worktree)
681 const char *got_revoked_signers = NULL;
682 const struct got_gotconfig *worktree_conf = NULL, *repo_conf = NULL;
684 *revoked_signers = NULL;
686 if (worktree)
687 worktree_conf = got_worktree_get_gotconfig(worktree);
688 repo_conf = got_repo_get_gotconfig(repo);
690 /*
691 * Priority of potential author information sources, from most
692 * significant to least significant:
693 * 1) work tree's .got/got.conf file
694 * 2) repository's got.conf file
695 */
697 if (worktree_conf)
698 got_revoked_signers = got_gotconfig_get_revoked_signers_file(
699 worktree_conf);
700 if (got_revoked_signers == NULL)
701 got_revoked_signers = got_gotconfig_get_revoked_signers_file(
702 repo_conf);
704 if (got_revoked_signers) {
705 *revoked_signers = strdup(got_revoked_signers);
706 if (*revoked_signers == NULL)
707 return got_error_from_errno("strdup");
709 return NULL;
712 static const char *
713 get_signer_id(struct got_repository *repo, struct got_worktree *worktree)
715 const char *got_signer_id = NULL;
716 const struct got_gotconfig *worktree_conf = NULL, *repo_conf = NULL;
718 if (worktree)
719 worktree_conf = got_worktree_get_gotconfig(worktree);
720 repo_conf = got_repo_get_gotconfig(repo);
722 /*
723 * Priority of potential author information sources, from most
724 * significant to least significant:
725 * 1) work tree's .got/got.conf file
726 * 2) repository's got.conf file
727 */
729 if (worktree_conf)
730 got_signer_id = got_gotconfig_get_signer_id(worktree_conf);
731 if (got_signer_id == NULL)
732 got_signer_id = got_gotconfig_get_signer_id(repo_conf);
734 return got_signer_id;
737 static const struct got_error *
738 get_gitconfig_path(char **gitconfig_path)
740 const char *homedir = getenv("HOME");
742 *gitconfig_path = NULL;
743 if (homedir) {
744 if (asprintf(gitconfig_path, "%s/.gitconfig", homedir) == -1)
745 return got_error_from_errno("asprintf");
748 return NULL;
751 static const struct got_error *
752 cmd_import(int argc, char *argv[])
754 const struct got_error *error = NULL;
755 char *path_dir = NULL, *repo_path = NULL, *logmsg = NULL;
756 char *gitconfig_path = NULL, *editor = NULL, *author = NULL;
757 const char *branch_name = NULL;
758 char *id_str = NULL, *logmsg_path = NULL;
759 char refname[PATH_MAX] = "refs/heads/";
760 struct got_repository *repo = NULL;
761 struct got_reference *branch_ref = NULL, *head_ref = NULL;
762 struct got_object_id *new_commit_id = NULL;
763 int ch, n = 0;
764 struct got_pathlist_head ignores;
765 struct got_pathlist_entry *pe;
766 int preserve_logmsg = 0;
767 int *pack_fds = NULL;
769 TAILQ_INIT(&ignores);
771 while ((ch = getopt(argc, argv, "b:I:m:r:")) != -1) {
772 switch (ch) {
773 case 'b':
774 branch_name = optarg;
775 break;
776 case 'I':
777 if (optarg[0] == '\0')
778 break;
779 error = got_pathlist_insert(&pe, &ignores, optarg,
780 NULL);
781 if (error)
782 goto done;
783 break;
784 case 'm':
785 logmsg = strdup(optarg);
786 if (logmsg == NULL) {
787 error = got_error_from_errno("strdup");
788 goto done;
790 break;
791 case 'r':
792 repo_path = realpath(optarg, NULL);
793 if (repo_path == NULL) {
794 error = got_error_from_errno2("realpath",
795 optarg);
796 goto done;
798 break;
799 default:
800 usage_import();
801 /* NOTREACHED */
805 argc -= optind;
806 argv += optind;
808 #ifndef PROFILE
809 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
810 "unveil",
811 NULL) == -1)
812 err(1, "pledge");
813 #endif
814 if (argc != 1)
815 usage_import();
817 if (repo_path == NULL) {
818 repo_path = getcwd(NULL, 0);
819 if (repo_path == NULL)
820 return got_error_from_errno("getcwd");
822 got_path_strip_trailing_slashes(repo_path);
823 error = get_gitconfig_path(&gitconfig_path);
824 if (error)
825 goto done;
826 error = got_repo_pack_fds_open(&pack_fds);
827 if (error != NULL)
828 goto done;
829 error = got_repo_open(&repo, repo_path, gitconfig_path, pack_fds);
830 if (error)
831 goto done;
833 error = get_author(&author, repo, NULL);
834 if (error)
835 return error;
837 /*
838 * Don't let the user create a branch name with a leading '-'.
839 * While technically a valid reference name, this case is usually
840 * an unintended typo.
841 */
842 if (branch_name && branch_name[0] == '-')
843 return got_error_path(branch_name, GOT_ERR_REF_NAME_MINUS);
845 error = got_ref_open(&head_ref, repo, GOT_REF_HEAD, 0);
846 if (error && error->code != GOT_ERR_NOT_REF)
847 goto done;
849 if (branch_name)
850 n = strlcat(refname, branch_name, sizeof(refname));
851 else if (head_ref && got_ref_is_symbolic(head_ref))
852 n = strlcpy(refname, got_ref_get_symref_target(head_ref),
853 sizeof(refname));
854 else
855 n = strlcat(refname, "main", sizeof(refname));
856 if (n >= sizeof(refname)) {
857 error = got_error(GOT_ERR_NO_SPACE);
858 goto done;
861 error = got_ref_open(&branch_ref, repo, refname, 0);
862 if (error) {
863 if (error->code != GOT_ERR_NOT_REF)
864 goto done;
865 } else {
866 error = got_error_msg(GOT_ERR_BRANCH_EXISTS,
867 "import target branch already exists");
868 goto done;
871 path_dir = realpath(argv[0], NULL);
872 if (path_dir == NULL) {
873 error = got_error_from_errno2("realpath", argv[0]);
874 goto done;
876 got_path_strip_trailing_slashes(path_dir);
878 /*
879 * unveil(2) traverses exec(2); if an editor is used we have
880 * to apply unveil after the log message has been written.
881 */
882 if (logmsg == NULL || strlen(logmsg) == 0) {
883 error = get_editor(&editor);
884 if (error)
885 goto done;
886 free(logmsg);
887 error = collect_import_msg(&logmsg, &logmsg_path, editor,
888 path_dir, refname);
889 if (error) {
890 if (error->code != GOT_ERR_COMMIT_MSG_EMPTY &&
891 logmsg_path != NULL)
892 preserve_logmsg = 1;
893 goto done;
897 if (unveil(path_dir, "r") != 0) {
898 error = got_error_from_errno2("unveil", path_dir);
899 if (logmsg_path)
900 preserve_logmsg = 1;
901 goto done;
904 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
905 if (error) {
906 if (logmsg_path)
907 preserve_logmsg = 1;
908 goto done;
911 error = got_repo_import(&new_commit_id, path_dir, logmsg,
912 author, &ignores, repo, import_progress, NULL);
913 if (error) {
914 if (logmsg_path)
915 preserve_logmsg = 1;
916 goto done;
919 error = got_ref_alloc(&branch_ref, refname, new_commit_id);
920 if (error) {
921 if (logmsg_path)
922 preserve_logmsg = 1;
923 goto done;
926 error = got_ref_write(branch_ref, repo);
927 if (error) {
928 if (logmsg_path)
929 preserve_logmsg = 1;
930 goto done;
933 error = got_object_id_str(&id_str, new_commit_id);
934 if (error) {
935 if (logmsg_path)
936 preserve_logmsg = 1;
937 goto done;
940 error = got_ref_open(&head_ref, repo, GOT_REF_HEAD, 0);
941 if (error) {
942 if (error->code != GOT_ERR_NOT_REF) {
943 if (logmsg_path)
944 preserve_logmsg = 1;
945 goto done;
948 error = got_ref_alloc_symref(&head_ref, GOT_REF_HEAD,
949 branch_ref);
950 if (error) {
951 if (logmsg_path)
952 preserve_logmsg = 1;
953 goto done;
956 error = got_ref_write(head_ref, repo);
957 if (error) {
958 if (logmsg_path)
959 preserve_logmsg = 1;
960 goto done;
964 printf("Created branch %s with commit %s\n",
965 got_ref_get_name(branch_ref), id_str);
966 done:
967 if (pack_fds) {
968 const struct got_error *pack_err =
969 got_repo_pack_fds_close(pack_fds);
970 if (error == NULL)
971 error = pack_err;
973 if (preserve_logmsg) {
974 fprintf(stderr, "%s: log message preserved in %s\n",
975 getprogname(), logmsg_path);
976 } else if (logmsg_path && unlink(logmsg_path) == -1 && error == NULL)
977 error = got_error_from_errno2("unlink", logmsg_path);
978 free(logmsg);
979 free(logmsg_path);
980 free(repo_path);
981 free(editor);
982 free(new_commit_id);
983 free(id_str);
984 free(author);
985 free(gitconfig_path);
986 if (branch_ref)
987 got_ref_close(branch_ref);
988 if (head_ref)
989 got_ref_close(head_ref);
990 return error;
993 __dead static void
994 usage_clone(void)
996 fprintf(stderr, "usage: %s clone [-almqv] [-b branch] [-R reference] "
997 "repository-URL [directory]\n", getprogname());
998 exit(1);
1001 struct got_fetch_progress_arg {
1002 char last_scaled_size[FMT_SCALED_STRSIZE];
1003 int last_p_indexed;
1004 int last_p_resolved;
1005 int verbosity;
1007 struct got_repository *repo;
1009 int create_configs;
1010 int configs_created;
1011 struct {
1012 struct got_pathlist_head *symrefs;
1013 struct got_pathlist_head *wanted_branches;
1014 struct got_pathlist_head *wanted_refs;
1015 const char *proto;
1016 const char *host;
1017 const char *port;
1018 const char *remote_repo_path;
1019 const char *git_url;
1020 int fetch_all_branches;
1021 int mirror_references;
1022 } config_info;
1025 /* XXX forward declaration */
1026 static const struct got_error *
1027 create_config_files(const char *proto, const char *host, const char *port,
1028 const char *remote_repo_path, const char *git_url, int fetch_all_branches,
1029 int mirror_references, struct got_pathlist_head *symrefs,
1030 struct got_pathlist_head *wanted_branches,
1031 struct got_pathlist_head *wanted_refs, struct got_repository *repo);
1033 static const struct got_error *
1034 fetch_progress(void *arg, const char *message, off_t packfile_size,
1035 int nobj_total, int nobj_indexed, int nobj_loose, int nobj_resolved)
1037 const struct got_error *err = NULL;
1038 struct got_fetch_progress_arg *a = arg;
1039 char scaled_size[FMT_SCALED_STRSIZE];
1040 int p_indexed, p_resolved;
1041 int print_size = 0, print_indexed = 0, print_resolved = 0;
1044 * In order to allow a failed clone to be resumed with 'got fetch'
1045 * we try to create configuration files as soon as possible.
1046 * Once the server has sent information about its default branch
1047 * we have all required information.
1049 if (a->create_configs && !a->configs_created &&
1050 !TAILQ_EMPTY(a->config_info.symrefs)) {
1051 err = create_config_files(a->config_info.proto,
1052 a->config_info.host, a->config_info.port,
1053 a->config_info.remote_repo_path,
1054 a->config_info.git_url,
1055 a->config_info.fetch_all_branches,
1056 a->config_info.mirror_references,
1057 a->config_info.symrefs,
1058 a->config_info.wanted_branches,
1059 a->config_info.wanted_refs, a->repo);
1060 if (err)
1061 return err;
1062 a->configs_created = 1;
1065 if (a->verbosity < 0)
1066 return NULL;
1068 if (message && message[0] != '\0') {
1069 printf("\rserver: %s", message);
1070 fflush(stdout);
1071 return NULL;
1074 if (packfile_size > 0 || nobj_indexed > 0) {
1075 if (fmt_scaled(packfile_size, scaled_size) == 0 &&
1076 (a->last_scaled_size[0] == '\0' ||
1077 strcmp(scaled_size, a->last_scaled_size)) != 0) {
1078 print_size = 1;
1079 if (strlcpy(a->last_scaled_size, scaled_size,
1080 FMT_SCALED_STRSIZE) >= FMT_SCALED_STRSIZE)
1081 return got_error(GOT_ERR_NO_SPACE);
1083 if (nobj_indexed > 0) {
1084 p_indexed = (nobj_indexed * 100) / nobj_total;
1085 if (p_indexed != a->last_p_indexed) {
1086 a->last_p_indexed = p_indexed;
1087 print_indexed = 1;
1088 print_size = 1;
1091 if (nobj_resolved > 0) {
1092 p_resolved = (nobj_resolved * 100) /
1093 (nobj_total - nobj_loose);
1094 if (p_resolved != a->last_p_resolved) {
1095 a->last_p_resolved = p_resolved;
1096 print_resolved = 1;
1097 print_indexed = 1;
1098 print_size = 1;
1103 if (print_size || print_indexed || print_resolved)
1104 printf("\r");
1105 if (print_size)
1106 printf("%*s fetched", FMT_SCALED_STRSIZE - 2, scaled_size);
1107 if (print_indexed)
1108 printf("; indexing %d%%", p_indexed);
1109 if (print_resolved)
1110 printf("; resolving deltas %d%%", p_resolved);
1111 if (print_size || print_indexed || print_resolved)
1112 fflush(stdout);
1114 return NULL;
1117 static const struct got_error *
1118 create_symref(const char *refname, struct got_reference *target_ref,
1119 int verbosity, struct got_repository *repo)
1121 const struct got_error *err;
1122 struct got_reference *head_symref;
1124 err = got_ref_alloc_symref(&head_symref, refname, target_ref);
1125 if (err)
1126 return err;
1128 err = got_ref_write(head_symref, repo);
1129 if (err == NULL && verbosity > 0) {
1130 printf("Created reference %s: %s\n", GOT_REF_HEAD,
1131 got_ref_get_name(target_ref));
1133 got_ref_close(head_symref);
1134 return err;
1137 static const struct got_error *
1138 list_remote_refs(struct got_pathlist_head *symrefs,
1139 struct got_pathlist_head *refs)
1141 const struct got_error *err;
1142 struct got_pathlist_entry *pe;
1144 TAILQ_FOREACH(pe, symrefs, entry) {
1145 const char *refname = pe->path;
1146 const char *targetref = pe->data;
1148 printf("%s: %s\n", refname, targetref);
1151 TAILQ_FOREACH(pe, refs, entry) {
1152 const char *refname = pe->path;
1153 struct got_object_id *id = pe->data;
1154 char *id_str;
1156 err = got_object_id_str(&id_str, id);
1157 if (err)
1158 return err;
1159 printf("%s: %s\n", refname, id_str);
1160 free(id_str);
1163 return NULL;
1166 static const struct got_error *
1167 create_ref(const char *refname, struct got_object_id *id,
1168 int verbosity, struct got_repository *repo)
1170 const struct got_error *err = NULL;
1171 struct got_reference *ref;
1172 char *id_str;
1174 err = got_object_id_str(&id_str, id);
1175 if (err)
1176 return err;
1178 err = got_ref_alloc(&ref, refname, id);
1179 if (err)
1180 goto done;
1182 err = got_ref_write(ref, repo);
1183 got_ref_close(ref);
1185 if (err == NULL && verbosity >= 0)
1186 printf("Created reference %s: %s\n", refname, id_str);
1187 done:
1188 free(id_str);
1189 return err;
1192 static int
1193 match_wanted_ref(const char *refname, const char *wanted_ref)
1195 if (strncmp(refname, "refs/", 5) != 0)
1196 return 0;
1197 refname += 5;
1200 * Prevent fetching of references that won't make any
1201 * sense outside of the remote repository's context.
1203 if (strncmp(refname, "got/", 4) == 0)
1204 return 0;
1205 if (strncmp(refname, "remotes/", 8) == 0)
1206 return 0;
1208 if (strncmp(wanted_ref, "refs/", 5) == 0)
1209 wanted_ref += 5;
1211 /* Allow prefix match. */
1212 if (got_path_is_child(refname, wanted_ref, strlen(wanted_ref)))
1213 return 1;
1215 /* Allow exact match. */
1216 return (strcmp(refname, wanted_ref) == 0);
1219 static int
1220 is_wanted_ref(struct got_pathlist_head *wanted_refs, const char *refname)
1222 struct got_pathlist_entry *pe;
1224 TAILQ_FOREACH(pe, wanted_refs, entry) {
1225 if (match_wanted_ref(refname, pe->path))
1226 return 1;
1229 return 0;
1232 static const struct got_error *
1233 create_wanted_ref(const char *refname, struct got_object_id *id,
1234 const char *remote_repo_name, int verbosity, struct got_repository *repo)
1236 const struct got_error *err;
1237 char *remote_refname;
1239 if (strncmp("refs/", refname, 5) == 0)
1240 refname += 5;
1242 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
1243 remote_repo_name, refname) == -1)
1244 return got_error_from_errno("asprintf");
1246 err = create_ref(remote_refname, id, verbosity, repo);
1247 free(remote_refname);
1248 return err;
1251 static const struct got_error *
1252 create_gotconfig(const char *proto, const char *host, const char *port,
1253 const char *remote_repo_path, const char *default_branch,
1254 int fetch_all_branches, struct got_pathlist_head *wanted_branches,
1255 struct got_pathlist_head *wanted_refs, int mirror_references,
1256 struct got_repository *repo)
1258 const struct got_error *err = NULL;
1259 char *gotconfig_path = NULL;
1260 char *gotconfig = NULL;
1261 FILE *gotconfig_file = NULL;
1262 const char *branchname = NULL;
1263 char *branches = NULL, *refs = NULL;
1264 ssize_t n;
1266 if (!fetch_all_branches && !TAILQ_EMPTY(wanted_branches)) {
1267 struct got_pathlist_entry *pe;
1268 TAILQ_FOREACH(pe, wanted_branches, entry) {
1269 char *s;
1270 branchname = pe->path;
1271 if (strncmp(branchname, "refs/heads/", 11) == 0)
1272 branchname += 11;
1273 if (asprintf(&s, "%s\"%s\" ",
1274 branches ? branches : "", branchname) == -1) {
1275 err = got_error_from_errno("asprintf");
1276 goto done;
1278 free(branches);
1279 branches = s;
1281 } else if (!fetch_all_branches && default_branch) {
1282 branchname = default_branch;
1283 if (strncmp(branchname, "refs/heads/", 11) == 0)
1284 branchname += 11;
1285 if (asprintf(&branches, "\"%s\" ", branchname) == -1) {
1286 err = got_error_from_errno("asprintf");
1287 goto done;
1290 if (!TAILQ_EMPTY(wanted_refs)) {
1291 struct got_pathlist_entry *pe;
1292 TAILQ_FOREACH(pe, wanted_refs, entry) {
1293 char *s;
1294 const char *refname = pe->path;
1295 if (strncmp(refname, "refs/", 5) == 0)
1296 branchname += 5;
1297 if (asprintf(&s, "%s\"%s\" ",
1298 refs ? refs : "", refname) == -1) {
1299 err = got_error_from_errno("asprintf");
1300 goto done;
1302 free(refs);
1303 refs = s;
1307 /* Create got.conf(5). */
1308 gotconfig_path = got_repo_get_path_gotconfig(repo);
1309 if (gotconfig_path == NULL) {
1310 err = got_error_from_errno("got_repo_get_path_gotconfig");
1311 goto done;
1313 gotconfig_file = fopen(gotconfig_path, "ae");
1314 if (gotconfig_file == NULL) {
1315 err = got_error_from_errno2("fopen", gotconfig_path);
1316 goto done;
1318 if (asprintf(&gotconfig,
1319 "remote \"%s\" {\n"
1320 "\tserver %s\n"
1321 "\tprotocol %s\n"
1322 "%s%s%s"
1323 "\trepository \"%s\"\n"
1324 "%s%s%s"
1325 "%s%s%s"
1326 "%s"
1327 "%s"
1328 "}\n",
1329 GOT_FETCH_DEFAULT_REMOTE_NAME, host, proto,
1330 port ? "\tport " : "", port ? port : "", port ? "\n" : "",
1331 remote_repo_path, branches ? "\tbranch { " : "",
1332 branches ? branches : "", branches ? "}\n" : "",
1333 refs ? "\treference { " : "", refs ? refs : "", refs ? "}\n" : "",
1334 mirror_references ? "\tmirror_references yes\n" : "",
1335 fetch_all_branches ? "\tfetch_all_branches yes\n" : "") == -1) {
1336 err = got_error_from_errno("asprintf");
1337 goto done;
1339 n = fwrite(gotconfig, 1, strlen(gotconfig), gotconfig_file);
1340 if (n != strlen(gotconfig)) {
1341 err = got_ferror(gotconfig_file, GOT_ERR_IO);
1342 goto done;
1345 done:
1346 if (gotconfig_file && fclose(gotconfig_file) == EOF && err == NULL)
1347 err = got_error_from_errno2("fclose", gotconfig_path);
1348 free(gotconfig_path);
1349 free(branches);
1350 return err;
1353 static const struct got_error *
1354 create_gitconfig(const char *git_url, const char *default_branch,
1355 int fetch_all_branches, struct got_pathlist_head *wanted_branches,
1356 struct got_pathlist_head *wanted_refs, int mirror_references,
1357 struct got_repository *repo)
1359 const struct got_error *err = NULL;
1360 char *gitconfig_path = NULL;
1361 char *gitconfig = NULL;
1362 FILE *gitconfig_file = NULL;
1363 char *branches = NULL, *refs = NULL;
1364 const char *branchname;
1365 ssize_t n;
1367 /* Create a config file Git can understand. */
1368 gitconfig_path = got_repo_get_path_gitconfig(repo);
1369 if (gitconfig_path == NULL) {
1370 err = got_error_from_errno("got_repo_get_path_gitconfig");
1371 goto done;
1373 gitconfig_file = fopen(gitconfig_path, "ae");
1374 if (gitconfig_file == NULL) {
1375 err = got_error_from_errno2("fopen", gitconfig_path);
1376 goto done;
1378 if (fetch_all_branches) {
1379 if (mirror_references) {
1380 if (asprintf(&branches,
1381 "\tfetch = refs/heads/*:refs/heads/*\n") == -1) {
1382 err = got_error_from_errno("asprintf");
1383 goto done;
1385 } else if (asprintf(&branches,
1386 "\tfetch = refs/heads/*:refs/remotes/%s/*\n",
1387 GOT_FETCH_DEFAULT_REMOTE_NAME) == -1) {
1388 err = got_error_from_errno("asprintf");
1389 goto done;
1391 } else if (!TAILQ_EMPTY(wanted_branches)) {
1392 struct got_pathlist_entry *pe;
1393 TAILQ_FOREACH(pe, wanted_branches, entry) {
1394 char *s;
1395 branchname = pe->path;
1396 if (strncmp(branchname, "refs/heads/", 11) == 0)
1397 branchname += 11;
1398 if (mirror_references) {
1399 if (asprintf(&s,
1400 "%s\tfetch = refs/heads/%s:refs/heads/%s\n",
1401 branches ? branches : "",
1402 branchname, branchname) == -1) {
1403 err = got_error_from_errno("asprintf");
1404 goto done;
1406 } else if (asprintf(&s,
1407 "%s\tfetch = refs/heads/%s:refs/remotes/%s/%s\n",
1408 branches ? branches : "",
1409 branchname, GOT_FETCH_DEFAULT_REMOTE_NAME,
1410 branchname) == -1) {
1411 err = got_error_from_errno("asprintf");
1412 goto done;
1414 free(branches);
1415 branches = s;
1417 } else {
1419 * If the server specified a default branch, use just that one.
1420 * Otherwise fall back to fetching all branches on next fetch.
1422 if (default_branch) {
1423 branchname = default_branch;
1424 if (strncmp(branchname, "refs/heads/", 11) == 0)
1425 branchname += 11;
1426 } else
1427 branchname = "*"; /* fall back to all branches */
1428 if (mirror_references) {
1429 if (asprintf(&branches,
1430 "\tfetch = refs/heads/%s:refs/heads/%s\n",
1431 branchname, branchname) == -1) {
1432 err = got_error_from_errno("asprintf");
1433 goto done;
1435 } else if (asprintf(&branches,
1436 "\tfetch = refs/heads/%s:refs/remotes/%s/%s\n",
1437 branchname, GOT_FETCH_DEFAULT_REMOTE_NAME,
1438 branchname) == -1) {
1439 err = got_error_from_errno("asprintf");
1440 goto done;
1443 if (!TAILQ_EMPTY(wanted_refs)) {
1444 struct got_pathlist_entry *pe;
1445 TAILQ_FOREACH(pe, wanted_refs, entry) {
1446 char *s;
1447 const char *refname = pe->path;
1448 if (strncmp(refname, "refs/", 5) == 0)
1449 refname += 5;
1450 if (mirror_references) {
1451 if (asprintf(&s,
1452 "%s\tfetch = refs/%s:refs/%s\n",
1453 refs ? refs : "", refname, refname) == -1) {
1454 err = got_error_from_errno("asprintf");
1455 goto done;
1457 } else if (asprintf(&s,
1458 "%s\tfetch = refs/%s:refs/remotes/%s/%s\n",
1459 refs ? refs : "",
1460 refname, GOT_FETCH_DEFAULT_REMOTE_NAME,
1461 refname) == -1) {
1462 err = got_error_from_errno("asprintf");
1463 goto done;
1465 free(refs);
1466 refs = s;
1470 if (asprintf(&gitconfig,
1471 "[remote \"%s\"]\n"
1472 "\turl = %s\n"
1473 "%s"
1474 "%s"
1475 "\tfetch = refs/tags/*:refs/tags/*\n",
1476 GOT_FETCH_DEFAULT_REMOTE_NAME, git_url, branches ? branches : "",
1477 refs ? refs : "") == -1) {
1478 err = got_error_from_errno("asprintf");
1479 goto done;
1481 n = fwrite(gitconfig, 1, strlen(gitconfig), gitconfig_file);
1482 if (n != strlen(gitconfig)) {
1483 err = got_ferror(gitconfig_file, GOT_ERR_IO);
1484 goto done;
1486 done:
1487 if (gitconfig_file && fclose(gitconfig_file) == EOF && err == NULL)
1488 err = got_error_from_errno2("fclose", gitconfig_path);
1489 free(gitconfig_path);
1490 free(branches);
1491 return err;
1494 static const struct got_error *
1495 create_config_files(const char *proto, const char *host, const char *port,
1496 const char *remote_repo_path, const char *git_url, int fetch_all_branches,
1497 int mirror_references, struct got_pathlist_head *symrefs,
1498 struct got_pathlist_head *wanted_branches,
1499 struct got_pathlist_head *wanted_refs, struct got_repository *repo)
1501 const struct got_error *err = NULL;
1502 const char *default_branch = NULL;
1503 struct got_pathlist_entry *pe;
1506 * If we asked for a set of wanted branches then use the first
1507 * one of those.
1509 if (!TAILQ_EMPTY(wanted_branches)) {
1510 pe = TAILQ_FIRST(wanted_branches);
1511 default_branch = pe->path;
1512 } else {
1513 /* First HEAD ref listed by server is the default branch. */
1514 TAILQ_FOREACH(pe, symrefs, entry) {
1515 const char *refname = pe->path;
1516 const char *target = pe->data;
1518 if (strcmp(refname, GOT_REF_HEAD) != 0)
1519 continue;
1521 default_branch = target;
1522 break;
1526 /* Create got.conf(5). */
1527 err = create_gotconfig(proto, host, port, remote_repo_path,
1528 default_branch, fetch_all_branches, wanted_branches,
1529 wanted_refs, mirror_references, repo);
1530 if (err)
1531 return err;
1533 /* Create a config file Git can understand. */
1534 return create_gitconfig(git_url, default_branch, fetch_all_branches,
1535 wanted_branches, wanted_refs, mirror_references, repo);
1538 static const struct got_error *
1539 cmd_clone(int argc, char *argv[])
1541 const struct got_error *error = NULL;
1542 const char *uri, *dirname;
1543 char *proto, *host, *port, *repo_name, *server_path;
1544 char *default_destdir = NULL, *id_str = NULL;
1545 const char *repo_path;
1546 struct got_repository *repo = NULL;
1547 struct got_pathlist_head refs, symrefs, wanted_branches, wanted_refs;
1548 struct got_pathlist_entry *pe;
1549 struct got_object_id *pack_hash = NULL;
1550 int ch, fetchfd = -1, fetchstatus;
1551 pid_t fetchpid = -1;
1552 struct got_fetch_progress_arg fpa;
1553 char *git_url = NULL;
1554 int verbosity = 0, fetch_all_branches = 0, mirror_references = 0;
1555 int list_refs_only = 0;
1556 int *pack_fds = NULL;
1558 TAILQ_INIT(&refs);
1559 TAILQ_INIT(&symrefs);
1560 TAILQ_INIT(&wanted_branches);
1561 TAILQ_INIT(&wanted_refs);
1563 while ((ch = getopt(argc, argv, "ab:lmqR:v")) != -1) {
1564 switch (ch) {
1565 case 'a':
1566 fetch_all_branches = 1;
1567 break;
1568 case 'b':
1569 error = got_pathlist_append(&wanted_branches,
1570 optarg, NULL);
1571 if (error)
1572 return error;
1573 break;
1574 case 'l':
1575 list_refs_only = 1;
1576 break;
1577 case 'm':
1578 mirror_references = 1;
1579 break;
1580 case 'q':
1581 verbosity = -1;
1582 break;
1583 case 'R':
1584 error = got_pathlist_append(&wanted_refs,
1585 optarg, NULL);
1586 if (error)
1587 return error;
1588 break;
1589 case 'v':
1590 if (verbosity < 0)
1591 verbosity = 0;
1592 else if (verbosity < 3)
1593 verbosity++;
1594 break;
1595 default:
1596 usage_clone();
1597 break;
1600 argc -= optind;
1601 argv += optind;
1603 if (fetch_all_branches && !TAILQ_EMPTY(&wanted_branches))
1604 option_conflict('a', 'b');
1605 if (list_refs_only) {
1606 if (!TAILQ_EMPTY(&wanted_branches))
1607 option_conflict('l', 'b');
1608 if (fetch_all_branches)
1609 option_conflict('l', 'a');
1610 if (mirror_references)
1611 option_conflict('l', 'm');
1612 if (!TAILQ_EMPTY(&wanted_refs))
1613 option_conflict('l', 'R');
1616 uri = argv[0];
1618 if (argc == 1)
1619 dirname = NULL;
1620 else if (argc == 2)
1621 dirname = argv[1];
1622 else
1623 usage_clone();
1625 error = got_dial_parse_uri(&proto, &host, &port, &server_path,
1626 &repo_name, uri);
1627 if (error)
1628 goto done;
1630 if (asprintf(&git_url, "%s://%s%s%s%s%s", proto,
1631 host, port ? ":" : "", port ? port : "",
1632 server_path[0] != '/' ? "/" : "", server_path) == -1) {
1633 error = got_error_from_errno("asprintf");
1634 goto done;
1637 if (strcmp(proto, "git") == 0) {
1638 #ifndef PROFILE
1639 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
1640 "sendfd dns inet unveil", NULL) == -1)
1641 err(1, "pledge");
1642 #endif
1643 } else if (strcmp(proto, "git+ssh") == 0 ||
1644 strcmp(proto, "ssh") == 0) {
1645 #ifndef PROFILE
1646 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
1647 "sendfd unveil", NULL) == -1)
1648 err(1, "pledge");
1649 #endif
1650 } else if (strcmp(proto, "http") == 0 ||
1651 strcmp(proto, "git+http") == 0) {
1652 error = got_error_path(proto, GOT_ERR_NOT_IMPL);
1653 goto done;
1654 } else {
1655 error = got_error_path(proto, GOT_ERR_BAD_PROTO);
1656 goto done;
1658 if (dirname == NULL) {
1659 if (asprintf(&default_destdir, "%s.git", repo_name) == -1) {
1660 error = got_error_from_errno("asprintf");
1661 goto done;
1663 repo_path = default_destdir;
1664 } else
1665 repo_path = dirname;
1667 if (!list_refs_only) {
1668 error = got_path_mkdir(repo_path);
1669 if (error &&
1670 (!(error->code == GOT_ERR_ERRNO && errno == EISDIR) &&
1671 !(error->code == GOT_ERR_ERRNO && errno == EEXIST)))
1672 goto done;
1673 if (!got_path_dir_is_empty(repo_path)) {
1674 error = got_error_path(repo_path,
1675 GOT_ERR_DIR_NOT_EMPTY);
1676 goto done;
1680 error = got_dial_apply_unveil(proto);
1681 if (error)
1682 goto done;
1684 error = apply_unveil(repo_path, 0, NULL);
1685 if (error)
1686 goto done;
1688 if (verbosity >= 0)
1689 printf("Connecting to %s\n", git_url);
1691 error = got_fetch_connect(&fetchpid, &fetchfd, proto, host, port,
1692 server_path, verbosity);
1693 if (error)
1694 goto done;
1696 if (!list_refs_only) {
1697 error = got_repo_init(repo_path, NULL);
1698 if (error)
1699 goto done;
1700 error = got_repo_pack_fds_open(&pack_fds);
1701 if (error != NULL)
1702 goto done;
1703 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
1704 if (error)
1705 goto done;
1708 fpa.last_scaled_size[0] = '\0';
1709 fpa.last_p_indexed = -1;
1710 fpa.last_p_resolved = -1;
1711 fpa.verbosity = verbosity;
1712 fpa.create_configs = 1;
1713 fpa.configs_created = 0;
1714 fpa.repo = repo;
1715 fpa.config_info.symrefs = &symrefs;
1716 fpa.config_info.wanted_branches = &wanted_branches;
1717 fpa.config_info.wanted_refs = &wanted_refs;
1718 fpa.config_info.proto = proto;
1719 fpa.config_info.host = host;
1720 fpa.config_info.port = port;
1721 fpa.config_info.remote_repo_path = server_path;
1722 fpa.config_info.git_url = git_url;
1723 fpa.config_info.fetch_all_branches = fetch_all_branches;
1724 fpa.config_info.mirror_references = mirror_references;
1725 error = got_fetch_pack(&pack_hash, &refs, &symrefs,
1726 GOT_FETCH_DEFAULT_REMOTE_NAME, mirror_references,
1727 fetch_all_branches, &wanted_branches, &wanted_refs,
1728 list_refs_only, verbosity, fetchfd, repo, NULL,
1729 fetch_progress, &fpa);
1730 if (error)
1731 goto done;
1733 if (list_refs_only) {
1734 error = list_remote_refs(&symrefs, &refs);
1735 goto done;
1738 if (pack_hash == NULL) {
1739 error = got_error_fmt(GOT_ERR_FETCH_FAILED, "%s",
1740 "server sent an empty pack file");
1741 goto done;
1743 error = got_object_id_str(&id_str, pack_hash);
1744 if (error)
1745 goto done;
1746 if (verbosity >= 0)
1747 printf("\nFetched %s.pack\n", id_str);
1748 free(id_str);
1750 /* Set up references provided with the pack file. */
1751 TAILQ_FOREACH(pe, &refs, entry) {
1752 const char *refname = pe->path;
1753 struct got_object_id *id = pe->data;
1754 char *remote_refname;
1756 if (is_wanted_ref(&wanted_refs, refname) &&
1757 !mirror_references) {
1758 error = create_wanted_ref(refname, id,
1759 GOT_FETCH_DEFAULT_REMOTE_NAME,
1760 verbosity - 1, repo);
1761 if (error)
1762 goto done;
1763 continue;
1766 error = create_ref(refname, id, verbosity - 1, repo);
1767 if (error)
1768 goto done;
1770 if (mirror_references)
1771 continue;
1773 if (strncmp("refs/heads/", refname, 11) != 0)
1774 continue;
1776 if (asprintf(&remote_refname,
1777 "refs/remotes/%s/%s", GOT_FETCH_DEFAULT_REMOTE_NAME,
1778 refname + 11) == -1) {
1779 error = got_error_from_errno("asprintf");
1780 goto done;
1782 error = create_ref(remote_refname, id, verbosity - 1, repo);
1783 free(remote_refname);
1784 if (error)
1785 goto done;
1788 /* Set the HEAD reference if the server provided one. */
1789 TAILQ_FOREACH(pe, &symrefs, entry) {
1790 struct got_reference *target_ref;
1791 const char *refname = pe->path;
1792 const char *target = pe->data;
1793 char *remote_refname = NULL, *remote_target = NULL;
1795 if (strcmp(refname, GOT_REF_HEAD) != 0)
1796 continue;
1798 error = got_ref_open(&target_ref, repo, target, 0);
1799 if (error) {
1800 if (error->code == GOT_ERR_NOT_REF) {
1801 error = NULL;
1802 continue;
1804 goto done;
1807 error = create_symref(refname, target_ref, verbosity, repo);
1808 got_ref_close(target_ref);
1809 if (error)
1810 goto done;
1812 if (mirror_references)
1813 continue;
1815 if (strncmp("refs/heads/", target, 11) != 0)
1816 continue;
1818 if (asprintf(&remote_refname,
1819 "refs/remotes/%s/%s", GOT_FETCH_DEFAULT_REMOTE_NAME,
1820 refname) == -1) {
1821 error = got_error_from_errno("asprintf");
1822 goto done;
1824 if (asprintf(&remote_target,
1825 "refs/remotes/%s/%s", GOT_FETCH_DEFAULT_REMOTE_NAME,
1826 target + 11) == -1) {
1827 error = got_error_from_errno("asprintf");
1828 free(remote_refname);
1829 goto done;
1831 error = got_ref_open(&target_ref, repo, remote_target, 0);
1832 if (error) {
1833 free(remote_refname);
1834 free(remote_target);
1835 if (error->code == GOT_ERR_NOT_REF) {
1836 error = NULL;
1837 continue;
1839 goto done;
1841 error = create_symref(remote_refname, target_ref,
1842 verbosity - 1, repo);
1843 free(remote_refname);
1844 free(remote_target);
1845 got_ref_close(target_ref);
1846 if (error)
1847 goto done;
1849 if (pe == NULL) {
1851 * We failed to set the HEAD reference. If we asked for
1852 * a set of wanted branches use the first of one of those
1853 * which could be fetched instead.
1855 TAILQ_FOREACH(pe, &wanted_branches, entry) {
1856 const char *target = pe->path;
1857 struct got_reference *target_ref;
1859 error = got_ref_open(&target_ref, repo, target, 0);
1860 if (error) {
1861 if (error->code == GOT_ERR_NOT_REF) {
1862 error = NULL;
1863 continue;
1865 goto done;
1868 error = create_symref(GOT_REF_HEAD, target_ref,
1869 verbosity, repo);
1870 got_ref_close(target_ref);
1871 if (error)
1872 goto done;
1873 break;
1876 if (!fpa.configs_created && pe != NULL) {
1877 error = create_config_files(fpa.config_info.proto,
1878 fpa.config_info.host, fpa.config_info.port,
1879 fpa.config_info.remote_repo_path,
1880 fpa.config_info.git_url,
1881 fpa.config_info.fetch_all_branches,
1882 fpa.config_info.mirror_references,
1883 fpa.config_info.symrefs,
1884 fpa.config_info.wanted_branches,
1885 fpa.config_info.wanted_refs, fpa.repo);
1886 if (error)
1887 goto done;
1891 if (verbosity >= 0)
1892 printf("Created %s repository '%s'\n",
1893 mirror_references ? "mirrored" : "cloned", repo_path);
1894 done:
1895 if (pack_fds) {
1896 const struct got_error *pack_err =
1897 got_repo_pack_fds_close(pack_fds);
1898 if (error == NULL)
1899 error = pack_err;
1901 if (fetchpid > 0) {
1902 if (kill(fetchpid, SIGTERM) == -1)
1903 error = got_error_from_errno("kill");
1904 if (waitpid(fetchpid, &fetchstatus, 0) == -1 && error == NULL)
1905 error = got_error_from_errno("waitpid");
1907 if (fetchfd != -1 && close(fetchfd) == -1 && error == NULL)
1908 error = got_error_from_errno("close");
1909 if (repo) {
1910 const struct got_error *close_err = got_repo_close(repo);
1911 if (error == NULL)
1912 error = close_err;
1914 got_pathlist_free(&refs, GOT_PATHLIST_FREE_ALL);
1915 got_pathlist_free(&symrefs, GOT_PATHLIST_FREE_ALL);
1916 got_pathlist_free(&wanted_branches, GOT_PATHLIST_FREE_NONE);
1917 got_pathlist_free(&wanted_refs, GOT_PATHLIST_FREE_NONE);
1918 free(pack_hash);
1919 free(proto);
1920 free(host);
1921 free(port);
1922 free(server_path);
1923 free(repo_name);
1924 free(default_destdir);
1925 free(git_url);
1926 return error;
1929 static const struct got_error *
1930 update_ref(struct got_reference *ref, struct got_object_id *new_id,
1931 int replace_tags, int verbosity, struct got_repository *repo)
1933 const struct got_error *err = NULL;
1934 char *new_id_str = NULL;
1935 struct got_object_id *old_id = NULL;
1937 err = got_object_id_str(&new_id_str, new_id);
1938 if (err)
1939 goto done;
1941 if (!replace_tags &&
1942 strncmp(got_ref_get_name(ref), "refs/tags/", 10) == 0) {
1943 err = got_ref_resolve(&old_id, repo, ref);
1944 if (err)
1945 goto done;
1946 if (got_object_id_cmp(old_id, new_id) == 0)
1947 goto done;
1948 if (verbosity >= 0) {
1949 printf("Rejecting update of existing tag %s: %s\n",
1950 got_ref_get_name(ref), new_id_str);
1952 goto done;
1955 if (got_ref_is_symbolic(ref)) {
1956 if (verbosity >= 0) {
1957 printf("Replacing reference %s: %s\n",
1958 got_ref_get_name(ref),
1959 got_ref_get_symref_target(ref));
1961 err = got_ref_change_symref_to_ref(ref, new_id);
1962 if (err)
1963 goto done;
1964 err = got_ref_write(ref, repo);
1965 if (err)
1966 goto done;
1967 } else {
1968 err = got_ref_resolve(&old_id, repo, ref);
1969 if (err)
1970 goto done;
1971 if (got_object_id_cmp(old_id, new_id) == 0)
1972 goto done;
1974 err = got_ref_change_ref(ref, new_id);
1975 if (err)
1976 goto done;
1977 err = got_ref_write(ref, repo);
1978 if (err)
1979 goto done;
1982 if (verbosity >= 0)
1983 printf("Updated %s: %s\n", got_ref_get_name(ref),
1984 new_id_str);
1985 done:
1986 free(old_id);
1987 free(new_id_str);
1988 return err;
1991 static const struct got_error *
1992 update_symref(const char *refname, struct got_reference *target_ref,
1993 int verbosity, struct got_repository *repo)
1995 const struct got_error *err = NULL, *unlock_err;
1996 struct got_reference *symref;
1997 int symref_is_locked = 0;
1999 err = got_ref_open(&symref, repo, refname, 1);
2000 if (err) {
2001 if (err->code != GOT_ERR_NOT_REF)
2002 return err;
2003 err = got_ref_alloc_symref(&symref, refname, target_ref);
2004 if (err)
2005 goto done;
2007 err = got_ref_write(symref, repo);
2008 if (err)
2009 goto done;
2011 if (verbosity >= 0)
2012 printf("Created reference %s: %s\n",
2013 got_ref_get_name(symref),
2014 got_ref_get_symref_target(symref));
2015 } else {
2016 symref_is_locked = 1;
2018 if (strcmp(got_ref_get_symref_target(symref),
2019 got_ref_get_name(target_ref)) == 0)
2020 goto done;
2022 err = got_ref_change_symref(symref,
2023 got_ref_get_name(target_ref));
2024 if (err)
2025 goto done;
2027 err = got_ref_write(symref, repo);
2028 if (err)
2029 goto done;
2031 if (verbosity >= 0)
2032 printf("Updated %s: %s\n", got_ref_get_name(symref),
2033 got_ref_get_symref_target(symref));
2036 done:
2037 if (symref_is_locked) {
2038 unlock_err = got_ref_unlock(symref);
2039 if (unlock_err && err == NULL)
2040 err = unlock_err;
2042 got_ref_close(symref);
2043 return err;
2046 __dead static void
2047 usage_fetch(void)
2049 fprintf(stderr, "usage: %s fetch [-adlqtvX] [-b branch] "
2050 "[-R reference] [-r repository-path] [remote-repository]\n",
2051 getprogname());
2052 exit(1);
2055 static const struct got_error *
2056 delete_missing_ref(struct got_reference *ref,
2057 int verbosity, struct got_repository *repo)
2059 const struct got_error *err = NULL;
2060 struct got_object_id *id = NULL;
2061 char *id_str = NULL;
2063 if (got_ref_is_symbolic(ref)) {
2064 err = got_ref_delete(ref, repo);
2065 if (err)
2066 return err;
2067 if (verbosity >= 0) {
2068 printf("Deleted %s: %s\n",
2069 got_ref_get_name(ref),
2070 got_ref_get_symref_target(ref));
2072 } else {
2073 err = got_ref_resolve(&id, repo, ref);
2074 if (err)
2075 return err;
2076 err = got_object_id_str(&id_str, id);
2077 if (err)
2078 goto done;
2080 err = got_ref_delete(ref, repo);
2081 if (err)
2082 goto done;
2083 if (verbosity >= 0) {
2084 printf("Deleted %s: %s\n",
2085 got_ref_get_name(ref), id_str);
2088 done:
2089 free(id);
2090 free(id_str);
2091 return err;
2094 static const struct got_error *
2095 delete_missing_refs(struct got_pathlist_head *their_refs,
2096 struct got_pathlist_head *their_symrefs,
2097 const struct got_remote_repo *remote,
2098 int verbosity, struct got_repository *repo)
2100 const struct got_error *err = NULL, *unlock_err;
2101 struct got_reflist_head my_refs;
2102 struct got_reflist_entry *re;
2103 struct got_pathlist_entry *pe;
2104 char *remote_namespace = NULL;
2105 char *local_refname = NULL;
2107 TAILQ_INIT(&my_refs);
2109 if (asprintf(&remote_namespace, "refs/remotes/%s/", remote->name)
2110 == -1)
2111 return got_error_from_errno("asprintf");
2113 err = got_ref_list(&my_refs, repo, NULL, got_ref_cmp_by_name, NULL);
2114 if (err)
2115 goto done;
2117 TAILQ_FOREACH(re, &my_refs, entry) {
2118 const char *refname = got_ref_get_name(re->ref);
2119 const char *their_refname;
2121 if (remote->mirror_references) {
2122 their_refname = refname;
2123 } else {
2124 if (strncmp(refname, remote_namespace,
2125 strlen(remote_namespace)) == 0) {
2126 if (strcmp(refname + strlen(remote_namespace),
2127 GOT_REF_HEAD) == 0)
2128 continue;
2129 if (asprintf(&local_refname, "refs/heads/%s",
2130 refname + strlen(remote_namespace)) == -1) {
2131 err = got_error_from_errno("asprintf");
2132 goto done;
2134 } else if (strncmp(refname, "refs/tags/", 10) != 0)
2135 continue;
2137 their_refname = local_refname;
2140 TAILQ_FOREACH(pe, their_refs, entry) {
2141 if (strcmp(their_refname, pe->path) == 0)
2142 break;
2144 if (pe != NULL)
2145 continue;
2147 TAILQ_FOREACH(pe, their_symrefs, entry) {
2148 if (strcmp(their_refname, pe->path) == 0)
2149 break;
2151 if (pe != NULL)
2152 continue;
2154 err = delete_missing_ref(re->ref, verbosity, repo);
2155 if (err)
2156 break;
2158 if (local_refname) {
2159 struct got_reference *ref;
2160 err = got_ref_open(&ref, repo, local_refname, 1);
2161 if (err) {
2162 if (err->code != GOT_ERR_NOT_REF)
2163 break;
2164 free(local_refname);
2165 local_refname = NULL;
2166 continue;
2168 err = delete_missing_ref(ref, verbosity, repo);
2169 if (err)
2170 break;
2171 unlock_err = got_ref_unlock(ref);
2172 got_ref_close(ref);
2173 if (unlock_err && err == NULL) {
2174 err = unlock_err;
2175 break;
2178 free(local_refname);
2179 local_refname = NULL;
2182 done:
2183 got_ref_list_free(&my_refs);
2184 free(remote_namespace);
2185 free(local_refname);
2186 return err;
2189 static const struct got_error *
2190 update_wanted_ref(const char *refname, struct got_object_id *id,
2191 const char *remote_repo_name, int verbosity, struct got_repository *repo)
2193 const struct got_error *err, *unlock_err;
2194 char *remote_refname;
2195 struct got_reference *ref;
2197 if (strncmp("refs/", refname, 5) == 0)
2198 refname += 5;
2200 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
2201 remote_repo_name, refname) == -1)
2202 return got_error_from_errno("asprintf");
2204 err = got_ref_open(&ref, repo, remote_refname, 1);
2205 if (err) {
2206 if (err->code != GOT_ERR_NOT_REF)
2207 goto done;
2208 err = create_ref(remote_refname, id, verbosity, repo);
2209 } else {
2210 err = update_ref(ref, id, 0, verbosity, repo);
2211 unlock_err = got_ref_unlock(ref);
2212 if (unlock_err && err == NULL)
2213 err = unlock_err;
2214 got_ref_close(ref);
2216 done:
2217 free(remote_refname);
2218 return err;
2221 static const struct got_error *
2222 delete_ref(struct got_repository *repo, struct got_reference *ref)
2224 const struct got_error *err = NULL;
2225 struct got_object_id *id = NULL;
2226 char *id_str = NULL;
2227 const char *target;
2229 if (got_ref_is_symbolic(ref)) {
2230 target = got_ref_get_symref_target(ref);
2231 } else {
2232 err = got_ref_resolve(&id, repo, ref);
2233 if (err)
2234 goto done;
2235 err = got_object_id_str(&id_str, id);
2236 if (err)
2237 goto done;
2238 target = id_str;
2241 err = got_ref_delete(ref, repo);
2242 if (err)
2243 goto done;
2245 printf("Deleted %s: %s\n", got_ref_get_name(ref), target);
2246 done:
2247 free(id);
2248 free(id_str);
2249 return err;
2252 static const struct got_error *
2253 delete_refs_for_remote(struct got_repository *repo, const char *remote_name)
2255 const struct got_error *err = NULL;
2256 struct got_reflist_head refs;
2257 struct got_reflist_entry *re;
2258 char *prefix;
2260 TAILQ_INIT(&refs);
2262 if (asprintf(&prefix, "refs/remotes/%s", remote_name) == -1) {
2263 err = got_error_from_errno("asprintf");
2264 goto done;
2266 err = got_ref_list(&refs, repo, prefix, got_ref_cmp_by_name, NULL);
2267 if (err)
2268 goto done;
2270 TAILQ_FOREACH(re, &refs, entry)
2271 delete_ref(repo, re->ref);
2272 done:
2273 got_ref_list_free(&refs);
2274 return err;
2277 static const struct got_error *
2278 cmd_fetch(int argc, char *argv[])
2280 const struct got_error *error = NULL, *unlock_err;
2281 char *cwd = NULL, *repo_path = NULL;
2282 const char *remote_name;
2283 char *proto = NULL, *host = NULL, *port = NULL;
2284 char *repo_name = NULL, *server_path = NULL;
2285 const struct got_remote_repo *remotes, *remote = NULL;
2286 int nremotes;
2287 char *id_str = NULL;
2288 struct got_repository *repo = NULL;
2289 struct got_worktree *worktree = NULL;
2290 const struct got_gotconfig *repo_conf = NULL, *worktree_conf = NULL;
2291 struct got_pathlist_head refs, symrefs, wanted_branches, wanted_refs;
2292 struct got_pathlist_entry *pe;
2293 struct got_object_id *pack_hash = NULL;
2294 int i, ch, fetchfd = -1, fetchstatus;
2295 pid_t fetchpid = -1;
2296 struct got_fetch_progress_arg fpa;
2297 int verbosity = 0, fetch_all_branches = 0, list_refs_only = 0;
2298 int delete_refs = 0, replace_tags = 0, delete_remote = 0;
2299 int *pack_fds = NULL, have_bflag = 0;
2301 TAILQ_INIT(&refs);
2302 TAILQ_INIT(&symrefs);
2303 TAILQ_INIT(&wanted_branches);
2304 TAILQ_INIT(&wanted_refs);
2306 while ((ch = getopt(argc, argv, "ab:dlqR:r:tvX")) != -1) {
2307 switch (ch) {
2308 case 'a':
2309 fetch_all_branches = 1;
2310 break;
2311 case 'b':
2312 error = got_pathlist_append(&wanted_branches,
2313 optarg, NULL);
2314 if (error)
2315 return error;
2316 have_bflag = 1;
2317 break;
2318 case 'd':
2319 delete_refs = 1;
2320 break;
2321 case 'l':
2322 list_refs_only = 1;
2323 break;
2324 case 'q':
2325 verbosity = -1;
2326 break;
2327 case 'R':
2328 error = got_pathlist_append(&wanted_refs,
2329 optarg, NULL);
2330 if (error)
2331 return error;
2332 break;
2333 case 'r':
2334 repo_path = realpath(optarg, NULL);
2335 if (repo_path == NULL)
2336 return got_error_from_errno2("realpath",
2337 optarg);
2338 got_path_strip_trailing_slashes(repo_path);
2339 break;
2340 case 't':
2341 replace_tags = 1;
2342 break;
2343 case 'v':
2344 if (verbosity < 0)
2345 verbosity = 0;
2346 else if (verbosity < 3)
2347 verbosity++;
2348 break;
2349 case 'X':
2350 delete_remote = 1;
2351 break;
2352 default:
2353 usage_fetch();
2354 break;
2357 argc -= optind;
2358 argv += optind;
2360 if (fetch_all_branches && !TAILQ_EMPTY(&wanted_branches))
2361 option_conflict('a', 'b');
2362 if (list_refs_only) {
2363 if (!TAILQ_EMPTY(&wanted_branches))
2364 option_conflict('l', 'b');
2365 if (fetch_all_branches)
2366 option_conflict('l', 'a');
2367 if (delete_refs)
2368 option_conflict('l', 'd');
2369 if (delete_remote)
2370 option_conflict('l', 'X');
2372 if (delete_remote) {
2373 if (fetch_all_branches)
2374 option_conflict('X', 'a');
2375 if (!TAILQ_EMPTY(&wanted_branches))
2376 option_conflict('X', 'b');
2377 if (delete_refs)
2378 option_conflict('X', 'd');
2379 if (replace_tags)
2380 option_conflict('X', 't');
2381 if (!TAILQ_EMPTY(&wanted_refs))
2382 option_conflict('X', 'R');
2385 if (argc == 0) {
2386 if (delete_remote)
2387 errx(1, "-X option requires a remote name");
2388 remote_name = GOT_FETCH_DEFAULT_REMOTE_NAME;
2389 } else if (argc == 1)
2390 remote_name = argv[0];
2391 else
2392 usage_fetch();
2394 cwd = getcwd(NULL, 0);
2395 if (cwd == NULL) {
2396 error = got_error_from_errno("getcwd");
2397 goto done;
2400 error = got_repo_pack_fds_open(&pack_fds);
2401 if (error != NULL)
2402 goto done;
2404 if (repo_path == NULL) {
2405 error = got_worktree_open(&worktree, cwd);
2406 if (error && error->code != GOT_ERR_NOT_WORKTREE)
2407 goto done;
2408 else
2409 error = NULL;
2410 if (worktree) {
2411 repo_path =
2412 strdup(got_worktree_get_repo_path(worktree));
2413 if (repo_path == NULL)
2414 error = got_error_from_errno("strdup");
2415 if (error)
2416 goto done;
2417 } else {
2418 repo_path = strdup(cwd);
2419 if (repo_path == NULL) {
2420 error = got_error_from_errno("strdup");
2421 goto done;
2426 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
2427 if (error)
2428 goto done;
2430 if (delete_remote) {
2431 error = delete_refs_for_remote(repo, remote_name);
2432 goto done; /* nothing else to do */
2435 if (worktree) {
2436 worktree_conf = got_worktree_get_gotconfig(worktree);
2437 if (worktree_conf) {
2438 got_gotconfig_get_remotes(&nremotes, &remotes,
2439 worktree_conf);
2440 for (i = 0; i < nremotes; i++) {
2441 if (strcmp(remotes[i].name, remote_name) == 0) {
2442 remote = &remotes[i];
2443 break;
2448 if (remote == NULL) {
2449 repo_conf = got_repo_get_gotconfig(repo);
2450 if (repo_conf) {
2451 got_gotconfig_get_remotes(&nremotes, &remotes,
2452 repo_conf);
2453 for (i = 0; i < nremotes; i++) {
2454 if (strcmp(remotes[i].name, remote_name) == 0) {
2455 remote = &remotes[i];
2456 break;
2461 if (remote == NULL) {
2462 got_repo_get_gitconfig_remotes(&nremotes, &remotes, repo);
2463 for (i = 0; i < nremotes; i++) {
2464 if (strcmp(remotes[i].name, remote_name) == 0) {
2465 remote = &remotes[i];
2466 break;
2470 if (remote == NULL) {
2471 error = got_error_path(remote_name, GOT_ERR_NO_REMOTE);
2472 goto done;
2475 if (TAILQ_EMPTY(&wanted_branches)) {
2476 if (!fetch_all_branches)
2477 fetch_all_branches = remote->fetch_all_branches;
2478 for (i = 0; i < remote->nfetch_branches; i++) {
2479 error = got_pathlist_append(&wanted_branches,
2480 remote->fetch_branches[i], NULL);
2481 if (error)
2482 goto done;
2485 if (TAILQ_EMPTY(&wanted_refs)) {
2486 for (i = 0; i < remote->nfetch_refs; i++) {
2487 error = got_pathlist_append(&wanted_refs,
2488 remote->fetch_refs[i], NULL);
2489 if (error)
2490 goto done;
2494 error = got_dial_parse_uri(&proto, &host, &port, &server_path,
2495 &repo_name, remote->fetch_url);
2496 if (error)
2497 goto done;
2499 if (strcmp(proto, "git") == 0) {
2500 #ifndef PROFILE
2501 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
2502 "sendfd dns inet unveil", NULL) == -1)
2503 err(1, "pledge");
2504 #endif
2505 } else if (strcmp(proto, "git+ssh") == 0 ||
2506 strcmp(proto, "ssh") == 0) {
2507 #ifndef PROFILE
2508 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
2509 "sendfd unveil", NULL) == -1)
2510 err(1, "pledge");
2511 #endif
2512 } else if (strcmp(proto, "http") == 0 ||
2513 strcmp(proto, "git+http") == 0) {
2514 error = got_error_path(proto, GOT_ERR_NOT_IMPL);
2515 goto done;
2516 } else {
2517 error = got_error_path(proto, GOT_ERR_BAD_PROTO);
2518 goto done;
2521 error = got_dial_apply_unveil(proto);
2522 if (error)
2523 goto done;
2525 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
2526 if (error)
2527 goto done;
2529 if (verbosity >= 0) {
2530 printf("Connecting to \"%s\" %s://%s%s%s%s%s\n",
2531 remote->name, proto, host,
2532 port ? ":" : "", port ? port : "",
2533 *server_path == '/' ? "" : "/", server_path);
2536 error = got_fetch_connect(&fetchpid, &fetchfd, proto, host, port,
2537 server_path, verbosity);
2538 if (error)
2539 goto done;
2541 fpa.last_scaled_size[0] = '\0';
2542 fpa.last_p_indexed = -1;
2543 fpa.last_p_resolved = -1;
2544 fpa.verbosity = verbosity;
2545 fpa.repo = repo;
2546 fpa.create_configs = 0;
2547 fpa.configs_created = 0;
2548 memset(&fpa.config_info, 0, sizeof(fpa.config_info));
2549 error = got_fetch_pack(&pack_hash, &refs, &symrefs, remote->name,
2550 remote->mirror_references, fetch_all_branches, &wanted_branches,
2551 &wanted_refs, list_refs_only, verbosity, fetchfd, repo,
2552 (worktree != NULL && !have_bflag) ?
2553 got_worktree_get_head_ref_name(worktree) : NULL,
2554 fetch_progress, &fpa);
2555 if (error)
2556 goto done;
2558 if (list_refs_only) {
2559 error = list_remote_refs(&symrefs, &refs);
2560 goto done;
2563 if (pack_hash == NULL) {
2564 if (verbosity >= 0)
2565 printf("Already up-to-date\n");
2566 } else if (verbosity >= 0) {
2567 error = got_object_id_str(&id_str, pack_hash);
2568 if (error)
2569 goto done;
2570 printf("\nFetched %s.pack\n", id_str);
2571 free(id_str);
2572 id_str = NULL;
2575 /* Update references provided with the pack file. */
2576 TAILQ_FOREACH(pe, &refs, entry) {
2577 const char *refname = pe->path;
2578 struct got_object_id *id = pe->data;
2579 struct got_reference *ref;
2580 char *remote_refname;
2582 if (is_wanted_ref(&wanted_refs, refname) &&
2583 !remote->mirror_references) {
2584 error = update_wanted_ref(refname, id,
2585 remote->name, verbosity, repo);
2586 if (error)
2587 goto done;
2588 continue;
2591 if (remote->mirror_references ||
2592 strncmp("refs/tags/", refname, 10) == 0) {
2593 error = got_ref_open(&ref, repo, refname, 1);
2594 if (error) {
2595 if (error->code != GOT_ERR_NOT_REF)
2596 goto done;
2597 error = create_ref(refname, id, verbosity,
2598 repo);
2599 if (error)
2600 goto done;
2601 } else {
2602 error = update_ref(ref, id, replace_tags,
2603 verbosity, repo);
2604 unlock_err = got_ref_unlock(ref);
2605 if (unlock_err && error == NULL)
2606 error = unlock_err;
2607 got_ref_close(ref);
2608 if (error)
2609 goto done;
2611 } else if (strncmp("refs/heads/", refname, 11) == 0) {
2612 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
2613 remote_name, refname + 11) == -1) {
2614 error = got_error_from_errno("asprintf");
2615 goto done;
2618 error = got_ref_open(&ref, repo, remote_refname, 1);
2619 if (error) {
2620 if (error->code != GOT_ERR_NOT_REF)
2621 goto done;
2622 error = create_ref(remote_refname, id,
2623 verbosity, repo);
2624 if (error)
2625 goto done;
2626 } else {
2627 error = update_ref(ref, id, replace_tags,
2628 verbosity, repo);
2629 unlock_err = got_ref_unlock(ref);
2630 if (unlock_err && error == NULL)
2631 error = unlock_err;
2632 got_ref_close(ref);
2633 if (error)
2634 goto done;
2637 /* Also create a local branch if none exists yet. */
2638 error = got_ref_open(&ref, repo, refname, 1);
2639 if (error) {
2640 if (error->code != GOT_ERR_NOT_REF)
2641 goto done;
2642 error = create_ref(refname, id, verbosity,
2643 repo);
2644 if (error)
2645 goto done;
2646 } else {
2647 unlock_err = got_ref_unlock(ref);
2648 if (unlock_err && error == NULL)
2649 error = unlock_err;
2650 got_ref_close(ref);
2654 if (delete_refs) {
2655 error = delete_missing_refs(&refs, &symrefs, remote,
2656 verbosity, repo);
2657 if (error)
2658 goto done;
2661 if (!remote->mirror_references) {
2662 /* Update remote HEAD reference if the server provided one. */
2663 TAILQ_FOREACH(pe, &symrefs, entry) {
2664 struct got_reference *target_ref;
2665 const char *refname = pe->path;
2666 const char *target = pe->data;
2667 char *remote_refname = NULL, *remote_target = NULL;
2669 if (strcmp(refname, GOT_REF_HEAD) != 0)
2670 continue;
2672 if (strncmp("refs/heads/", target, 11) != 0)
2673 continue;
2675 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
2676 remote->name, refname) == -1) {
2677 error = got_error_from_errno("asprintf");
2678 goto done;
2680 if (asprintf(&remote_target, "refs/remotes/%s/%s",
2681 remote->name, target + 11) == -1) {
2682 error = got_error_from_errno("asprintf");
2683 free(remote_refname);
2684 goto done;
2687 error = got_ref_open(&target_ref, repo, remote_target,
2688 0);
2689 if (error) {
2690 free(remote_refname);
2691 free(remote_target);
2692 if (error->code == GOT_ERR_NOT_REF) {
2693 error = NULL;
2694 continue;
2696 goto done;
2698 error = update_symref(remote_refname, target_ref,
2699 verbosity, repo);
2700 free(remote_refname);
2701 free(remote_target);
2702 got_ref_close(target_ref);
2703 if (error)
2704 goto done;
2707 done:
2708 if (fetchpid > 0) {
2709 if (kill(fetchpid, SIGTERM) == -1)
2710 error = got_error_from_errno("kill");
2711 if (waitpid(fetchpid, &fetchstatus, 0) == -1 && error == NULL)
2712 error = got_error_from_errno("waitpid");
2714 if (fetchfd != -1 && close(fetchfd) == -1 && error == NULL)
2715 error = got_error_from_errno("close");
2716 if (repo) {
2717 const struct got_error *close_err = got_repo_close(repo);
2718 if (error == NULL)
2719 error = close_err;
2721 if (worktree)
2722 got_worktree_close(worktree);
2723 if (pack_fds) {
2724 const struct got_error *pack_err =
2725 got_repo_pack_fds_close(pack_fds);
2726 if (error == NULL)
2727 error = pack_err;
2729 got_pathlist_free(&refs, GOT_PATHLIST_FREE_ALL);
2730 got_pathlist_free(&symrefs, GOT_PATHLIST_FREE_ALL);
2731 got_pathlist_free(&wanted_branches, GOT_PATHLIST_FREE_NONE);
2732 got_pathlist_free(&wanted_refs, GOT_PATHLIST_FREE_NONE);
2733 free(id_str);
2734 free(cwd);
2735 free(repo_path);
2736 free(pack_hash);
2737 free(proto);
2738 free(host);
2739 free(port);
2740 free(server_path);
2741 free(repo_name);
2742 return error;
2746 __dead static void
2747 usage_checkout(void)
2749 fprintf(stderr, "usage: %s checkout [-Eq] [-b branch] [-c commit] "
2750 "[-p path-prefix] repository-path [work-tree-path]\n",
2751 getprogname());
2752 exit(1);
2755 static void
2756 show_worktree_base_ref_warning(void)
2758 fprintf(stderr, "%s: warning: could not create a reference "
2759 "to the work tree's base commit; the commit could be "
2760 "garbage-collected by Git or 'gotadmin cleanup'; making the "
2761 "repository writable and running 'got update' will prevent this\n",
2762 getprogname());
2765 struct got_checkout_progress_arg {
2766 const char *worktree_path;
2767 int had_base_commit_ref_error;
2768 int verbosity;
2771 static const struct got_error *
2772 checkout_progress(void *arg, unsigned char status, const char *path)
2774 struct got_checkout_progress_arg *a = arg;
2776 /* Base commit bump happens silently. */
2777 if (status == GOT_STATUS_BUMP_BASE)
2778 return NULL;
2780 if (status == GOT_STATUS_BASE_REF_ERR) {
2781 a->had_base_commit_ref_error = 1;
2782 return NULL;
2785 while (path[0] == '/')
2786 path++;
2788 if (a->verbosity >= 0)
2789 printf("%c %s/%s\n", status, a->worktree_path, path);
2791 return NULL;
2794 static const struct got_error *
2795 check_cancelled(void *arg)
2797 if (sigint_received || sigpipe_received)
2798 return got_error(GOT_ERR_CANCELLED);
2799 return NULL;
2802 static const struct got_error *
2803 check_linear_ancestry(struct got_object_id *commit_id,
2804 struct got_object_id *base_commit_id, int allow_forwards_in_time_only,
2805 struct got_repository *repo)
2807 const struct got_error *err = NULL;
2808 struct got_object_id *yca_id;
2810 err = got_commit_graph_find_youngest_common_ancestor(&yca_id,
2811 commit_id, base_commit_id, 1, repo, check_cancelled, NULL);
2812 if (err)
2813 return err;
2815 if (yca_id == NULL)
2816 return got_error(GOT_ERR_ANCESTRY);
2819 * Require a straight line of history between the target commit
2820 * and the work tree's base commit.
2822 * Non-linear situations such as this require a rebase:
2824 * (commit) D F (base_commit)
2825 * \ /
2826 * C E
2827 * \ /
2828 * B (yca)
2829 * |
2830 * A
2832 * 'got update' only handles linear cases:
2833 * Update forwards in time: A (base/yca) - B - C - D (commit)
2834 * Update backwards in time: D (base) - C - B - A (commit/yca)
2836 if (allow_forwards_in_time_only) {
2837 if (got_object_id_cmp(base_commit_id, yca_id) != 0)
2838 return got_error(GOT_ERR_ANCESTRY);
2839 } else if (got_object_id_cmp(commit_id, yca_id) != 0 &&
2840 got_object_id_cmp(base_commit_id, yca_id) != 0)
2841 return got_error(GOT_ERR_ANCESTRY);
2843 free(yca_id);
2844 return NULL;
2847 static const struct got_error *
2848 check_same_branch(struct got_object_id *commit_id,
2849 struct got_reference *head_ref, struct got_object_id *yca_id,
2850 struct got_repository *repo)
2852 const struct got_error *err = NULL;
2853 struct got_commit_graph *graph = NULL;
2854 struct got_object_id *head_commit_id = NULL;
2855 int is_same_branch = 0;
2857 err = got_ref_resolve(&head_commit_id, repo, head_ref);
2858 if (err)
2859 goto done;
2861 if (got_object_id_cmp(head_commit_id, commit_id) == 0) {
2862 is_same_branch = 1;
2863 goto done;
2865 if (yca_id && got_object_id_cmp(commit_id, yca_id) == 0) {
2866 is_same_branch = 1;
2867 goto done;
2870 err = got_commit_graph_open(&graph, "/", 1);
2871 if (err)
2872 goto done;
2874 err = got_commit_graph_iter_start(graph, head_commit_id, repo,
2875 check_cancelled, NULL);
2876 if (err)
2877 goto done;
2879 for (;;) {
2880 struct got_object_id id;
2882 err = got_commit_graph_iter_next(&id, graph, repo,
2883 check_cancelled, NULL);
2884 if (err) {
2885 if (err->code == GOT_ERR_ITER_COMPLETED)
2886 err = NULL;
2887 break;
2890 if (yca_id && got_object_id_cmp(&id, yca_id) == 0)
2891 break;
2892 if (got_object_id_cmp(&id, commit_id) == 0) {
2893 is_same_branch = 1;
2894 break;
2897 done:
2898 if (graph)
2899 got_commit_graph_close(graph);
2900 free(head_commit_id);
2901 if (!err && !is_same_branch)
2902 err = got_error(GOT_ERR_ANCESTRY);
2903 return err;
2906 static const struct got_error *
2907 checkout_ancestry_error(struct got_reference *ref, const char *commit_id_str)
2909 static char msg[512];
2910 const char *branch_name;
2912 if (got_ref_is_symbolic(ref))
2913 branch_name = got_ref_get_symref_target(ref);
2914 else
2915 branch_name = got_ref_get_name(ref);
2917 if (strncmp("refs/heads/", branch_name, 11) == 0)
2918 branch_name += 11;
2920 snprintf(msg, sizeof(msg),
2921 "target commit is not contained in branch '%s'; "
2922 "the branch to use must be specified with -b; "
2923 "if necessary a new branch can be created for "
2924 "this commit with 'got branch -c %s BRANCH_NAME'",
2925 branch_name, commit_id_str);
2927 return got_error_msg(GOT_ERR_ANCESTRY, msg);
2930 static const struct got_error *
2931 cmd_checkout(int argc, char *argv[])
2933 const struct got_error *error = NULL;
2934 struct got_repository *repo = NULL;
2935 struct got_reference *head_ref = NULL, *ref = NULL;
2936 struct got_worktree *worktree = NULL;
2937 char *repo_path = NULL;
2938 char *worktree_path = NULL;
2939 const char *path_prefix = "";
2940 const char *branch_name = GOT_REF_HEAD, *refname = NULL;
2941 char *commit_id_str = NULL;
2942 struct got_object_id *commit_id = NULL;
2943 char *cwd = NULL;
2944 int ch, same_path_prefix, allow_nonempty = 0, verbosity = 0;
2945 struct got_pathlist_head paths;
2946 struct got_checkout_progress_arg cpa;
2947 int *pack_fds = NULL;
2949 TAILQ_INIT(&paths);
2951 while ((ch = getopt(argc, argv, "b:c:Ep:q")) != -1) {
2952 switch (ch) {
2953 case 'b':
2954 branch_name = optarg;
2955 break;
2956 case 'c':
2957 commit_id_str = strdup(optarg);
2958 if (commit_id_str == NULL)
2959 return got_error_from_errno("strdup");
2960 break;
2961 case 'E':
2962 allow_nonempty = 1;
2963 break;
2964 case 'p':
2965 path_prefix = optarg;
2966 break;
2967 case 'q':
2968 verbosity = -1;
2969 break;
2970 default:
2971 usage_checkout();
2972 /* NOTREACHED */
2976 argc -= optind;
2977 argv += optind;
2979 #ifndef PROFILE
2980 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
2981 "unveil", NULL) == -1)
2982 err(1, "pledge");
2983 #endif
2984 if (argc == 1) {
2985 char *base, *dotgit;
2986 const char *path;
2987 repo_path = realpath(argv[0], NULL);
2988 if (repo_path == NULL)
2989 return got_error_from_errno2("realpath", argv[0]);
2990 cwd = getcwd(NULL, 0);
2991 if (cwd == NULL) {
2992 error = got_error_from_errno("getcwd");
2993 goto done;
2995 if (path_prefix[0])
2996 path = path_prefix;
2997 else
2998 path = repo_path;
2999 error = got_path_basename(&base, path);
3000 if (error)
3001 goto done;
3002 dotgit = strstr(base, ".git");
3003 if (dotgit)
3004 *dotgit = '\0';
3005 if (asprintf(&worktree_path, "%s/%s", cwd, base) == -1) {
3006 error = got_error_from_errno("asprintf");
3007 free(base);
3008 goto done;
3010 free(base);
3011 } else if (argc == 2) {
3012 repo_path = realpath(argv[0], NULL);
3013 if (repo_path == NULL) {
3014 error = got_error_from_errno2("realpath", argv[0]);
3015 goto done;
3017 worktree_path = realpath(argv[1], NULL);
3018 if (worktree_path == NULL) {
3019 if (errno != ENOENT) {
3020 error = got_error_from_errno2("realpath",
3021 argv[1]);
3022 goto done;
3024 worktree_path = strdup(argv[1]);
3025 if (worktree_path == NULL) {
3026 error = got_error_from_errno("strdup");
3027 goto done;
3030 } else
3031 usage_checkout();
3033 got_path_strip_trailing_slashes(repo_path);
3034 got_path_strip_trailing_slashes(worktree_path);
3036 error = got_repo_pack_fds_open(&pack_fds);
3037 if (error != NULL)
3038 goto done;
3040 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
3041 if (error != NULL)
3042 goto done;
3044 /* Pre-create work tree path for unveil(2) */
3045 error = got_path_mkdir(worktree_path);
3046 if (error) {
3047 if (!(error->code == GOT_ERR_ERRNO && errno == EISDIR) &&
3048 !(error->code == GOT_ERR_ERRNO && errno == EEXIST))
3049 goto done;
3050 if (!allow_nonempty &&
3051 !got_path_dir_is_empty(worktree_path)) {
3052 error = got_error_path(worktree_path,
3053 GOT_ERR_DIR_NOT_EMPTY);
3054 goto done;
3058 error = apply_unveil(got_repo_get_path(repo), 0, worktree_path);
3059 if (error)
3060 goto done;
3062 error = got_ref_open(&head_ref, repo, branch_name, 0);
3063 if (error != NULL)
3064 goto done;
3066 error = got_worktree_init(worktree_path, head_ref, path_prefix, repo);
3067 if (error != NULL && !(error->code == GOT_ERR_ERRNO && errno == EEXIST))
3068 goto done;
3070 error = got_worktree_open(&worktree, worktree_path);
3071 if (error != NULL)
3072 goto done;
3074 error = got_worktree_match_path_prefix(&same_path_prefix, worktree,
3075 path_prefix);
3076 if (error != NULL)
3077 goto done;
3078 if (!same_path_prefix) {
3079 error = got_error(GOT_ERR_PATH_PREFIX);
3080 goto done;
3083 if (commit_id_str) {
3084 struct got_reflist_head refs;
3085 TAILQ_INIT(&refs);
3086 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
3087 NULL);
3088 if (error)
3089 goto done;
3090 error = got_repo_match_object_id(&commit_id, NULL,
3091 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
3092 got_ref_list_free(&refs);
3093 if (error)
3094 goto done;
3095 error = check_linear_ancestry(commit_id,
3096 got_worktree_get_base_commit_id(worktree), 0, repo);
3097 if (error != NULL) {
3098 if (error->code == GOT_ERR_ANCESTRY) {
3099 error = checkout_ancestry_error(
3100 head_ref, commit_id_str);
3102 goto done;
3104 error = check_same_branch(commit_id, head_ref, NULL, repo);
3105 if (error) {
3106 if (error->code == GOT_ERR_ANCESTRY) {
3107 error = checkout_ancestry_error(
3108 head_ref, commit_id_str);
3110 goto done;
3112 error = got_worktree_set_base_commit_id(worktree, repo,
3113 commit_id);
3114 if (error)
3115 goto done;
3116 /* Expand potentially abbreviated commit ID string. */
3117 free(commit_id_str);
3118 error = got_object_id_str(&commit_id_str, commit_id);
3119 if (error)
3120 goto done;
3121 } else {
3122 commit_id = got_object_id_dup(
3123 got_worktree_get_base_commit_id(worktree));
3124 if (commit_id == NULL) {
3125 error = got_error_from_errno("got_object_id_dup");
3126 goto done;
3128 error = got_object_id_str(&commit_id_str, commit_id);
3129 if (error)
3130 goto done;
3133 error = got_pathlist_append(&paths, "", NULL);
3134 if (error)
3135 goto done;
3136 cpa.worktree_path = worktree_path;
3137 cpa.had_base_commit_ref_error = 0;
3138 cpa.verbosity = verbosity;
3139 error = got_worktree_checkout_files(worktree, &paths, repo,
3140 checkout_progress, &cpa, check_cancelled, NULL);
3141 if (error != NULL)
3142 goto done;
3144 if (got_ref_is_symbolic(head_ref)) {
3145 error = got_ref_resolve_symbolic(&ref, repo, head_ref);
3146 if (error)
3147 goto done;
3148 refname = got_ref_get_name(ref);
3149 } else
3150 refname = got_ref_get_name(head_ref);
3151 printf("Checked out %s: %s\n", refname, commit_id_str);
3152 printf("Now shut up and hack\n");
3153 if (cpa.had_base_commit_ref_error)
3154 show_worktree_base_ref_warning();
3155 done:
3156 if (pack_fds) {
3157 const struct got_error *pack_err =
3158 got_repo_pack_fds_close(pack_fds);
3159 if (error == NULL)
3160 error = pack_err;
3162 if (head_ref)
3163 got_ref_close(head_ref);
3164 if (ref)
3165 got_ref_close(ref);
3166 got_pathlist_free(&paths, GOT_PATHLIST_FREE_NONE);
3167 free(commit_id_str);
3168 free(commit_id);
3169 free(repo_path);
3170 free(worktree_path);
3171 free(cwd);
3172 return error;
3175 struct got_update_progress_arg {
3176 int did_something;
3177 int conflicts;
3178 int obstructed;
3179 int not_updated;
3180 int missing;
3181 int not_deleted;
3182 int unversioned;
3183 int verbosity;
3186 static void
3187 print_update_progress_stats(struct got_update_progress_arg *upa)
3189 if (!upa->did_something)
3190 return;
3192 if (upa->conflicts > 0)
3193 printf("Files with new merge conflicts: %d\n", upa->conflicts);
3194 if (upa->obstructed > 0)
3195 printf("File paths obstructed by a non-regular file: %d\n",
3196 upa->obstructed);
3197 if (upa->not_updated > 0)
3198 printf("Files not updated because of existing merge "
3199 "conflicts: %d\n", upa->not_updated);
3203 * The meaning of some status codes differs between merge-style operations and
3204 * update operations. For example, the ! status code means "file was missing"
3205 * if changes were merged into the work tree, and "missing file was restored"
3206 * if the work tree was updated. This function should be used by any operation
3207 * which merges changes into the work tree without updating the work tree.
3209 static void
3210 print_merge_progress_stats(struct got_update_progress_arg *upa)
3212 if (!upa->did_something)
3213 return;
3215 if (upa->conflicts > 0)
3216 printf("Files with new merge conflicts: %d\n", upa->conflicts);
3217 if (upa->obstructed > 0)
3218 printf("File paths obstructed by a non-regular file: %d\n",
3219 upa->obstructed);
3220 if (upa->missing > 0)
3221 printf("Files which had incoming changes but could not be "
3222 "found in the work tree: %d\n", upa->missing);
3223 if (upa->not_deleted > 0)
3224 printf("Files not deleted due to differences in deleted "
3225 "content: %d\n", upa->not_deleted);
3226 if (upa->unversioned > 0)
3227 printf("Files not merged because an unversioned file was "
3228 "found in the work tree: %d\n", upa->unversioned);
3231 __dead static void
3232 usage_update(void)
3234 fprintf(stderr, "usage: %s update [-q] [-b branch] [-c commit] "
3235 "[path ...]\n", getprogname());
3236 exit(1);
3239 static const struct got_error *
3240 update_progress(void *arg, unsigned char status, const char *path)
3242 struct got_update_progress_arg *upa = arg;
3244 if (status == GOT_STATUS_EXISTS ||
3245 status == GOT_STATUS_BASE_REF_ERR)
3246 return NULL;
3248 upa->did_something = 1;
3250 /* Base commit bump happens silently. */
3251 if (status == GOT_STATUS_BUMP_BASE)
3252 return NULL;
3254 if (status == GOT_STATUS_CONFLICT)
3255 upa->conflicts++;
3256 if (status == GOT_STATUS_OBSTRUCTED)
3257 upa->obstructed++;
3258 if (status == GOT_STATUS_CANNOT_UPDATE)
3259 upa->not_updated++;
3260 if (status == GOT_STATUS_MISSING)
3261 upa->missing++;
3262 if (status == GOT_STATUS_CANNOT_DELETE)
3263 upa->not_deleted++;
3264 if (status == GOT_STATUS_UNVERSIONED)
3265 upa->unversioned++;
3267 while (path[0] == '/')
3268 path++;
3269 if (upa->verbosity >= 0)
3270 printf("%c %s\n", status, path);
3272 return NULL;
3275 static const struct got_error *
3276 switch_head_ref(struct got_reference *head_ref,
3277 struct got_object_id *commit_id, struct got_worktree *worktree,
3278 struct got_repository *repo)
3280 const struct got_error *err = NULL;
3281 char *base_id_str;
3282 int ref_has_moved = 0;
3284 /* Trivial case: switching between two different references. */
3285 if (strcmp(got_ref_get_name(head_ref),
3286 got_worktree_get_head_ref_name(worktree)) != 0) {
3287 printf("Switching work tree from %s to %s\n",
3288 got_worktree_get_head_ref_name(worktree),
3289 got_ref_get_name(head_ref));
3290 return got_worktree_set_head_ref(worktree, head_ref);
3293 err = check_linear_ancestry(commit_id,
3294 got_worktree_get_base_commit_id(worktree), 0, repo);
3295 if (err) {
3296 if (err->code != GOT_ERR_ANCESTRY)
3297 return err;
3298 ref_has_moved = 1;
3300 if (!ref_has_moved)
3301 return NULL;
3303 /* Switching to a rebased branch with the same reference name. */
3304 err = got_object_id_str(&base_id_str,
3305 got_worktree_get_base_commit_id(worktree));
3306 if (err)
3307 return err;
3308 printf("Reference %s now points at a different branch\n",
3309 got_worktree_get_head_ref_name(worktree));
3310 printf("Switching work tree from %s to %s\n", base_id_str,
3311 got_worktree_get_head_ref_name(worktree));
3312 return NULL;
3315 static const struct got_error *
3316 check_rebase_or_histedit_in_progress(struct got_worktree *worktree)
3318 const struct got_error *err;
3319 int in_progress;
3321 err = got_worktree_rebase_in_progress(&in_progress, worktree);
3322 if (err)
3323 return err;
3324 if (in_progress)
3325 return got_error(GOT_ERR_REBASING);
3327 err = got_worktree_histedit_in_progress(&in_progress, worktree);
3328 if (err)
3329 return err;
3330 if (in_progress)
3331 return got_error(GOT_ERR_HISTEDIT_BUSY);
3333 return NULL;
3336 static const struct got_error *
3337 check_merge_in_progress(struct got_worktree *worktree,
3338 struct got_repository *repo)
3340 const struct got_error *err;
3341 int in_progress;
3343 err = got_worktree_merge_in_progress(&in_progress, worktree, repo);
3344 if (err)
3345 return err;
3346 if (in_progress)
3347 return got_error(GOT_ERR_MERGE_BUSY);
3349 return NULL;
3352 static const struct got_error *
3353 get_worktree_paths_from_argv(struct got_pathlist_head *paths, int argc,
3354 char *argv[], struct got_worktree *worktree)
3356 const struct got_error *err = NULL;
3357 char *path;
3358 struct got_pathlist_entry *new;
3359 int i;
3361 if (argc == 0) {
3362 path = strdup("");
3363 if (path == NULL)
3364 return got_error_from_errno("strdup");
3365 return got_pathlist_append(paths, path, NULL);
3368 for (i = 0; i < argc; i++) {
3369 err = got_worktree_resolve_path(&path, worktree, argv[i]);
3370 if (err)
3371 break;
3372 err = got_pathlist_insert(&new, paths, path, NULL);
3373 if (err || new == NULL /* duplicate */) {
3374 free(path);
3375 if (err)
3376 break;
3380 return err;
3383 static const struct got_error *
3384 wrap_not_worktree_error(const struct got_error *orig_err,
3385 const char *cmdname, const char *path)
3387 const struct got_error *err;
3388 struct got_repository *repo;
3389 static char msg[512];
3390 int *pack_fds = NULL;
3392 err = got_repo_pack_fds_open(&pack_fds);
3393 if (err)
3394 return err;
3396 err = got_repo_open(&repo, path, NULL, pack_fds);
3397 if (err)
3398 return orig_err;
3400 snprintf(msg, sizeof(msg),
3401 "'got %s' needs a work tree in addition to a git repository\n"
3402 "Work trees can be checked out from this Git repository with "
3403 "'got checkout'.\n"
3404 "The got(1) manual page contains more information.", cmdname);
3405 err = got_error_msg(GOT_ERR_NOT_WORKTREE, msg);
3406 got_repo_close(repo);
3407 if (pack_fds) {
3408 const struct got_error *pack_err =
3409 got_repo_pack_fds_close(pack_fds);
3410 if (err == NULL)
3411 err = pack_err;
3413 return err;
3416 static const struct got_error *
3417 cmd_update(int argc, char *argv[])
3419 const struct got_error *error = NULL;
3420 struct got_repository *repo = NULL;
3421 struct got_worktree *worktree = NULL;
3422 char *worktree_path = NULL;
3423 struct got_object_id *commit_id = NULL;
3424 char *commit_id_str = NULL;
3425 const char *branch_name = NULL;
3426 struct got_reference *head_ref = NULL;
3427 struct got_pathlist_head paths;
3428 struct got_pathlist_entry *pe;
3429 int ch, verbosity = 0;
3430 struct got_update_progress_arg upa;
3431 int *pack_fds = NULL;
3433 TAILQ_INIT(&paths);
3435 while ((ch = getopt(argc, argv, "b:c:q")) != -1) {
3436 switch (ch) {
3437 case 'b':
3438 branch_name = optarg;
3439 break;
3440 case 'c':
3441 commit_id_str = strdup(optarg);
3442 if (commit_id_str == NULL)
3443 return got_error_from_errno("strdup");
3444 break;
3445 case 'q':
3446 verbosity = -1;
3447 break;
3448 default:
3449 usage_update();
3450 /* NOTREACHED */
3454 argc -= optind;
3455 argv += optind;
3457 #ifndef PROFILE
3458 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
3459 "unveil", NULL) == -1)
3460 err(1, "pledge");
3461 #endif
3462 worktree_path = getcwd(NULL, 0);
3463 if (worktree_path == NULL) {
3464 error = got_error_from_errno("getcwd");
3465 goto done;
3468 error = got_repo_pack_fds_open(&pack_fds);
3469 if (error != NULL)
3470 goto done;
3472 error = got_worktree_open(&worktree, worktree_path);
3473 if (error) {
3474 if (error->code == GOT_ERR_NOT_WORKTREE)
3475 error = wrap_not_worktree_error(error, "update",
3476 worktree_path);
3477 goto done;
3480 error = check_rebase_or_histedit_in_progress(worktree);
3481 if (error)
3482 goto done;
3484 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
3485 NULL, pack_fds);
3486 if (error != NULL)
3487 goto done;
3489 error = apply_unveil(got_repo_get_path(repo), 0,
3490 got_worktree_get_root_path(worktree));
3491 if (error)
3492 goto done;
3494 error = check_merge_in_progress(worktree, repo);
3495 if (error)
3496 goto done;
3498 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
3499 if (error)
3500 goto done;
3502 error = got_ref_open(&head_ref, repo, branch_name ? branch_name :
3503 got_worktree_get_head_ref_name(worktree), 0);
3504 if (error != NULL)
3505 goto done;
3506 if (commit_id_str == NULL) {
3507 error = got_ref_resolve(&commit_id, repo, head_ref);
3508 if (error != NULL)
3509 goto done;
3510 error = got_object_id_str(&commit_id_str, commit_id);
3511 if (error != NULL)
3512 goto done;
3513 } else {
3514 struct got_reflist_head refs;
3515 TAILQ_INIT(&refs);
3516 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
3517 NULL);
3518 if (error)
3519 goto done;
3520 error = got_repo_match_object_id(&commit_id, NULL,
3521 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
3522 got_ref_list_free(&refs);
3523 free(commit_id_str);
3524 commit_id_str = NULL;
3525 if (error)
3526 goto done;
3527 error = got_object_id_str(&commit_id_str, commit_id);
3528 if (error)
3529 goto done;
3532 if (branch_name) {
3533 struct got_object_id *head_commit_id;
3534 TAILQ_FOREACH(pe, &paths, entry) {
3535 if (pe->path_len == 0)
3536 continue;
3537 error = got_error_msg(GOT_ERR_BAD_PATH,
3538 "switching between branches requires that "
3539 "the entire work tree gets updated");
3540 goto done;
3542 error = got_ref_resolve(&head_commit_id, repo, head_ref);
3543 if (error)
3544 goto done;
3545 error = check_linear_ancestry(commit_id, head_commit_id, 0,
3546 repo);
3547 free(head_commit_id);
3548 if (error != NULL)
3549 goto done;
3550 error = check_same_branch(commit_id, head_ref, NULL, repo);
3551 if (error)
3552 goto done;
3553 error = switch_head_ref(head_ref, commit_id, worktree, repo);
3554 if (error)
3555 goto done;
3556 } else {
3557 error = check_linear_ancestry(commit_id,
3558 got_worktree_get_base_commit_id(worktree), 0, repo);
3559 if (error != NULL) {
3560 if (error->code == GOT_ERR_ANCESTRY)
3561 error = got_error(GOT_ERR_BRANCH_MOVED);
3562 goto done;
3564 error = check_same_branch(commit_id, head_ref, NULL, repo);
3565 if (error)
3566 goto done;
3569 if (got_object_id_cmp(got_worktree_get_base_commit_id(worktree),
3570 commit_id) != 0) {
3571 error = got_worktree_set_base_commit_id(worktree, repo,
3572 commit_id);
3573 if (error)
3574 goto done;
3577 memset(&upa, 0, sizeof(upa));
3578 upa.verbosity = verbosity;
3579 error = got_worktree_checkout_files(worktree, &paths, repo,
3580 update_progress, &upa, check_cancelled, NULL);
3581 if (error != NULL)
3582 goto done;
3584 if (upa.did_something) {
3585 printf("Updated to %s: %s\n",
3586 got_worktree_get_head_ref_name(worktree), commit_id_str);
3587 } else
3588 printf("Already up-to-date\n");
3590 print_update_progress_stats(&upa);
3591 done:
3592 if (pack_fds) {
3593 const struct got_error *pack_err =
3594 got_repo_pack_fds_close(pack_fds);
3595 if (error == NULL)
3596 error = pack_err;
3598 free(worktree_path);
3599 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
3600 free(commit_id);
3601 free(commit_id_str);
3602 return error;
3605 static const struct got_error *
3606 diff_blobs(struct got_object_id *blob_id1, struct got_object_id *blob_id2,
3607 const char *path, int diff_context, int ignore_whitespace,
3608 int force_text_diff, struct got_diffstat_cb_arg *dsa,
3609 struct got_repository *repo, FILE *outfile)
3611 const struct got_error *err = NULL;
3612 struct got_blob_object *blob1 = NULL, *blob2 = NULL;
3613 FILE *f1 = NULL, *f2 = NULL;
3614 int fd1 = -1, fd2 = -1;
3616 fd1 = got_opentempfd();
3617 if (fd1 == -1)
3618 return got_error_from_errno("got_opentempfd");
3619 fd2 = got_opentempfd();
3620 if (fd2 == -1) {
3621 err = got_error_from_errno("got_opentempfd");
3622 goto done;
3625 if (blob_id1) {
3626 err = got_object_open_as_blob(&blob1, repo, blob_id1, 8192,
3627 fd1);
3628 if (err)
3629 goto done;
3632 err = got_object_open_as_blob(&blob2, repo, blob_id2, 8192, fd2);
3633 if (err)
3634 goto done;
3636 f1 = got_opentemp();
3637 if (f1 == NULL) {
3638 err = got_error_from_errno("got_opentemp");
3639 goto done;
3641 f2 = got_opentemp();
3642 if (f2 == NULL) {
3643 err = got_error_from_errno("got_opentemp");
3644 goto done;
3647 while (path[0] == '/')
3648 path++;
3649 err = got_diff_blob(NULL, NULL, blob1, blob2, f1, f2, path, path,
3650 GOT_DIFF_ALGORITHM_PATIENCE, diff_context, ignore_whitespace,
3651 force_text_diff, dsa, outfile);
3652 done:
3653 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
3654 err = got_error_from_errno("close");
3655 if (blob1)
3656 got_object_blob_close(blob1);
3657 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
3658 err = got_error_from_errno("close");
3659 got_object_blob_close(blob2);
3660 if (f1 && fclose(f1) == EOF && err == NULL)
3661 err = got_error_from_errno("fclose");
3662 if (f2 && fclose(f2) == EOF && err == NULL)
3663 err = got_error_from_errno("fclose");
3664 return err;
3667 static const struct got_error *
3668 diff_trees(struct got_object_id *tree_id1, struct got_object_id *tree_id2,
3669 const char *path, int diff_context, int ignore_whitespace,
3670 int force_text_diff, struct got_diffstat_cb_arg *dsa,
3671 struct got_repository *repo, FILE *outfile)
3673 const struct got_error *err = NULL;
3674 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
3675 struct got_diff_blob_output_unidiff_arg arg;
3676 FILE *f1 = NULL, *f2 = NULL;
3677 int fd1 = -1, fd2 = -1;
3679 if (tree_id1) {
3680 err = got_object_open_as_tree(&tree1, repo, tree_id1);
3681 if (err)
3682 goto done;
3683 fd1 = got_opentempfd();
3684 if (fd1 == -1) {
3685 err = got_error_from_errno("got_opentempfd");
3686 goto done;
3690 err = got_object_open_as_tree(&tree2, repo, tree_id2);
3691 if (err)
3692 goto done;
3694 f1 = got_opentemp();
3695 if (f1 == NULL) {
3696 err = got_error_from_errno("got_opentemp");
3697 goto done;
3700 f2 = got_opentemp();
3701 if (f2 == NULL) {
3702 err = got_error_from_errno("got_opentemp");
3703 goto done;
3705 fd2 = got_opentempfd();
3706 if (fd2 == -1) {
3707 err = got_error_from_errno("got_opentempfd");
3708 goto done;
3710 arg.diff_context = diff_context;
3711 arg.ignore_whitespace = ignore_whitespace;
3712 arg.force_text_diff = force_text_diff;
3713 arg.diffstat = dsa;
3714 arg.diff_algo = GOT_DIFF_ALGORITHM_PATIENCE;
3715 arg.outfile = outfile;
3716 arg.lines = NULL;
3717 arg.nlines = 0;
3718 while (path[0] == '/')
3719 path++;
3720 err = got_diff_tree(tree1, tree2, f1, f2, fd1, fd2, path, path, repo,
3721 got_diff_blob_output_unidiff, &arg, 1);
3722 done:
3723 if (tree1)
3724 got_object_tree_close(tree1);
3725 if (tree2)
3726 got_object_tree_close(tree2);
3727 if (f1 && fclose(f1) == EOF && err == NULL)
3728 err = got_error_from_errno("fclose");
3729 if (f2 && fclose(f2) == EOF && err == NULL)
3730 err = got_error_from_errno("fclose");
3731 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
3732 err = got_error_from_errno("close");
3733 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
3734 err = got_error_from_errno("close");
3735 return err;
3738 static const struct got_error *
3739 get_changed_paths(struct got_pathlist_head *paths,
3740 struct got_commit_object *commit, struct got_repository *repo,
3741 struct got_diffstat_cb_arg *dsa)
3743 const struct got_error *err = NULL;
3744 struct got_object_id *tree_id1 = NULL, *tree_id2 = NULL;
3745 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
3746 struct got_object_qid *qid;
3747 got_diff_blob_cb cb = got_diff_tree_collect_changed_paths;
3748 FILE *f1 = NULL, *f2 = NULL;
3749 int fd1 = -1, fd2 = -1;
3751 if (dsa) {
3752 cb = got_diff_tree_compute_diffstat;
3754 f1 = got_opentemp();
3755 if (f1 == NULL) {
3756 err = got_error_from_errno("got_opentemp");
3757 goto done;
3759 f2 = got_opentemp();
3760 if (f2 == NULL) {
3761 err = got_error_from_errno("got_opentemp");
3762 goto done;
3764 fd1 = got_opentempfd();
3765 if (fd1 == -1) {
3766 err = got_error_from_errno("got_opentempfd");
3767 goto done;
3769 fd2 = got_opentempfd();
3770 if (fd2 == -1) {
3771 err = got_error_from_errno("got_opentempfd");
3772 goto done;
3776 qid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
3777 if (qid != NULL) {
3778 struct got_commit_object *pcommit;
3779 err = got_object_open_as_commit(&pcommit, repo,
3780 &qid->id);
3781 if (err)
3782 return err;
3784 tree_id1 = got_object_id_dup(
3785 got_object_commit_get_tree_id(pcommit));
3786 if (tree_id1 == NULL) {
3787 got_object_commit_close(pcommit);
3788 return got_error_from_errno("got_object_id_dup");
3790 got_object_commit_close(pcommit);
3794 if (tree_id1) {
3795 err = got_object_open_as_tree(&tree1, repo, tree_id1);
3796 if (err)
3797 goto done;
3800 tree_id2 = got_object_commit_get_tree_id(commit);
3801 err = got_object_open_as_tree(&tree2, repo, tree_id2);
3802 if (err)
3803 goto done;
3805 err = got_diff_tree(tree1, tree2, f1, f2, fd1, fd2, "", "", repo,
3806 cb, dsa ? (void *)dsa : paths, dsa ? 1 : 0);
3807 done:
3808 if (tree1)
3809 got_object_tree_close(tree1);
3810 if (tree2)
3811 got_object_tree_close(tree2);
3812 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
3813 err = got_error_from_errno("close");
3814 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
3815 err = got_error_from_errno("close");
3816 if (f1 && fclose(f1) == EOF && err == NULL)
3817 err = got_error_from_errno("fclose");
3818 if (f2 && fclose(f2) == EOF && err == NULL)
3819 err = got_error_from_errno("fclose");
3820 free(tree_id1);
3821 return err;
3824 static const struct got_error *
3825 print_patch(struct got_commit_object *commit, struct got_object_id *id,
3826 const char *path, int diff_context, struct got_diffstat_cb_arg *dsa,
3827 struct got_repository *repo, FILE *outfile)
3829 const struct got_error *err = NULL;
3830 struct got_commit_object *pcommit = NULL;
3831 char *id_str1 = NULL, *id_str2 = NULL;
3832 struct got_object_id *obj_id1 = NULL, *obj_id2 = NULL;
3833 struct got_object_qid *qid;
3835 qid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
3836 if (qid != NULL) {
3837 err = got_object_open_as_commit(&pcommit, repo,
3838 &qid->id);
3839 if (err)
3840 return err;
3841 err = got_object_id_str(&id_str1, &qid->id);
3842 if (err)
3843 goto done;
3846 err = got_object_id_str(&id_str2, id);
3847 if (err)
3848 goto done;
3850 if (path && path[0] != '\0') {
3851 int obj_type;
3852 err = got_object_id_by_path(&obj_id2, repo, commit, path);
3853 if (err)
3854 goto done;
3855 if (pcommit) {
3856 err = got_object_id_by_path(&obj_id1, repo,
3857 pcommit, path);
3858 if (err) {
3859 if (err->code != GOT_ERR_NO_TREE_ENTRY) {
3860 free(obj_id2);
3861 goto done;
3865 err = got_object_get_type(&obj_type, repo, obj_id2);
3866 if (err) {
3867 free(obj_id2);
3868 goto done;
3870 fprintf(outfile,
3871 "diff %s %s\n", id_str1 ? id_str1 : "/dev/null", id_str2);
3872 fprintf(outfile, "commit - %s\n",
3873 id_str1 ? id_str1 : "/dev/null");
3874 fprintf(outfile, "commit + %s\n", id_str2);
3875 switch (obj_type) {
3876 case GOT_OBJ_TYPE_BLOB:
3877 err = diff_blobs(obj_id1, obj_id2, path, diff_context,
3878 0, 0, dsa, repo, outfile);
3879 break;
3880 case GOT_OBJ_TYPE_TREE:
3881 err = diff_trees(obj_id1, obj_id2, path, diff_context,
3882 0, 0, dsa, repo, outfile);
3883 break;
3884 default:
3885 err = got_error(GOT_ERR_OBJ_TYPE);
3886 break;
3888 free(obj_id1);
3889 free(obj_id2);
3890 } else {
3891 obj_id2 = got_object_commit_get_tree_id(commit);
3892 if (pcommit)
3893 obj_id1 = got_object_commit_get_tree_id(pcommit);
3894 fprintf(outfile,
3895 "diff %s %s\n", id_str1 ? id_str1 : "/dev/null", id_str2);
3896 fprintf(outfile, "commit - %s\n",
3897 id_str1 ? id_str1 : "/dev/null");
3898 fprintf(outfile, "commit + %s\n", id_str2);
3899 err = diff_trees(obj_id1, obj_id2, "", diff_context, 0, 0,
3900 dsa, repo, outfile);
3902 done:
3903 free(id_str1);
3904 free(id_str2);
3905 if (pcommit)
3906 got_object_commit_close(pcommit);
3907 return err;
3910 static char *
3911 get_datestr(time_t *time, char *datebuf)
3913 struct tm mytm, *tm;
3914 char *p, *s;
3916 tm = gmtime_r(time, &mytm);
3917 if (tm == NULL)
3918 return NULL;
3919 s = asctime_r(tm, datebuf);
3920 if (s == NULL)
3921 return NULL;
3922 p = strchr(s, '\n');
3923 if (p)
3924 *p = '\0';
3925 return s;
3928 static const struct got_error *
3929 match_commit(int *have_match, struct got_object_id *id,
3930 struct got_commit_object *commit, regex_t *regex)
3932 const struct got_error *err = NULL;
3933 regmatch_t regmatch;
3934 char *id_str = NULL, *logmsg = NULL;
3936 *have_match = 0;
3938 err = got_object_id_str(&id_str, id);
3939 if (err)
3940 return err;
3942 err = got_object_commit_get_logmsg(&logmsg, commit);
3943 if (err)
3944 goto done;
3946 if (regexec(regex, got_object_commit_get_author(commit), 1,
3947 &regmatch, 0) == 0 ||
3948 regexec(regex, got_object_commit_get_committer(commit), 1,
3949 &regmatch, 0) == 0 ||
3950 regexec(regex, id_str, 1, &regmatch, 0) == 0 ||
3951 regexec(regex, logmsg, 1, &regmatch, 0) == 0)
3952 *have_match = 1;
3953 done:
3954 free(id_str);
3955 free(logmsg);
3956 return err;
3959 static void
3960 match_changed_paths(int *have_match, struct got_pathlist_head *changed_paths,
3961 regex_t *regex)
3963 regmatch_t regmatch;
3964 struct got_pathlist_entry *pe;
3966 *have_match = 0;
3968 TAILQ_FOREACH(pe, changed_paths, entry) {
3969 if (regexec(regex, pe->path, 1, &regmatch, 0) == 0) {
3970 *have_match = 1;
3971 break;
3976 static const struct got_error *
3977 match_patch(int *have_match, struct got_commit_object *commit,
3978 struct got_object_id *id, const char *path, int diff_context,
3979 struct got_repository *repo, regex_t *regex, FILE *f)
3981 const struct got_error *err = NULL;
3982 char *line = NULL;
3983 size_t linesize = 0;
3984 regmatch_t regmatch;
3986 *have_match = 0;
3988 err = got_opentemp_truncate(f);
3989 if (err)
3990 return err;
3992 err = print_patch(commit, id, path, diff_context, NULL, repo, f);
3993 if (err)
3994 goto done;
3996 if (fseeko(f, 0L, SEEK_SET) == -1) {
3997 err = got_error_from_errno("fseeko");
3998 goto done;
4001 while (getline(&line, &linesize, f) != -1) {
4002 if (regexec(regex, line, 1, &regmatch, 0) == 0) {
4003 *have_match = 1;
4004 break;
4007 done:
4008 free(line);
4009 return err;
4012 #define GOT_COMMIT_SEP_STR "-----------------------------------------------\n"
4014 static const struct got_error*
4015 build_refs_str(char **refs_str, struct got_reflist_head *refs,
4016 struct got_object_id *id, struct got_repository *repo,
4017 int local_only)
4019 static const struct got_error *err = NULL;
4020 struct got_reflist_entry *re;
4021 char *s;
4022 const char *name;
4024 *refs_str = NULL;
4026 TAILQ_FOREACH(re, refs, entry) {
4027 struct got_tag_object *tag = NULL;
4028 struct got_object_id *ref_id;
4029 int cmp;
4031 name = got_ref_get_name(re->ref);
4032 if (strcmp(name, GOT_REF_HEAD) == 0)
4033 continue;
4034 if (strncmp(name, "refs/", 5) == 0)
4035 name += 5;
4036 if (strncmp(name, "got/", 4) == 0)
4037 continue;
4038 if (strncmp(name, "heads/", 6) == 0)
4039 name += 6;
4040 if (strncmp(name, "remotes/", 8) == 0) {
4041 if (local_only)
4042 continue;
4043 name += 8;
4044 s = strstr(name, "/" GOT_REF_HEAD);
4045 if (s != NULL && s[strlen(s)] == '\0')
4046 continue;
4048 err = got_ref_resolve(&ref_id, repo, re->ref);
4049 if (err)
4050 break;
4051 if (strncmp(name, "tags/", 5) == 0) {
4052 err = got_object_open_as_tag(&tag, repo, ref_id);
4053 if (err) {
4054 if (err->code != GOT_ERR_OBJ_TYPE) {
4055 free(ref_id);
4056 break;
4058 /* Ref points at something other than a tag. */
4059 err = NULL;
4060 tag = NULL;
4063 cmp = got_object_id_cmp(tag ?
4064 got_object_tag_get_object_id(tag) : ref_id, id);
4065 free(ref_id);
4066 if (tag)
4067 got_object_tag_close(tag);
4068 if (cmp != 0)
4069 continue;
4070 s = *refs_str;
4071 if (asprintf(refs_str, "%s%s%s", s ? s : "",
4072 s ? ", " : "", name) == -1) {
4073 err = got_error_from_errno("asprintf");
4074 free(s);
4075 *refs_str = NULL;
4076 break;
4078 free(s);
4081 return err;
4084 static const struct got_error *
4085 print_commit_oneline(struct got_commit_object *commit, struct got_object_id *id,
4086 struct got_repository *repo, struct got_reflist_object_id_map *refs_idmap)
4088 const struct got_error *err = NULL;
4089 char *ref_str = NULL, *id_str = NULL, *logmsg0 = NULL;
4090 char *comma, *s, *nl;
4091 struct got_reflist_head *refs;
4092 char datebuf[12]; /* YYYY-MM-DD + SPACE + NUL */
4093 struct tm tm;
4094 time_t committer_time;
4096 refs = got_reflist_object_id_map_lookup(refs_idmap, id);
4097 if (refs) {
4098 err = build_refs_str(&ref_str, refs, id, repo, 1);
4099 if (err)
4100 return err;
4102 /* Display the first matching ref only. */
4103 if (ref_str && (comma = strchr(ref_str, ',')) != NULL)
4104 *comma = '\0';
4107 if (ref_str == NULL) {
4108 err = got_object_id_str(&id_str, id);
4109 if (err)
4110 return err;
4113 committer_time = got_object_commit_get_committer_time(commit);
4114 if (gmtime_r(&committer_time, &tm) == NULL) {
4115 err = got_error_from_errno("gmtime_r");
4116 goto done;
4118 if (strftime(datebuf, sizeof(datebuf), "%G-%m-%d ", &tm) == 0) {
4119 err = got_error(GOT_ERR_NO_SPACE);
4120 goto done;
4123 err = got_object_commit_get_logmsg(&logmsg0, commit);
4124 if (err)
4125 goto done;
4127 s = logmsg0;
4128 while (isspace((unsigned char)s[0]))
4129 s++;
4131 nl = strchr(s, '\n');
4132 if (nl) {
4133 *nl = '\0';
4136 if (ref_str)
4137 printf("%s%-7s %s\n", datebuf, ref_str, s);
4138 else
4139 printf("%s%.7s %s\n", datebuf, id_str, s);
4141 if (fflush(stdout) != 0 && err == NULL)
4142 err = got_error_from_errno("fflush");
4143 done:
4144 free(id_str);
4145 free(ref_str);
4146 free(logmsg0);
4147 return err;
4150 static const struct got_error *
4151 print_diffstat(struct got_diffstat_cb_arg *dsa, const char *header)
4153 struct got_pathlist_entry *pe;
4155 if (header != NULL)
4156 printf("%s\n", header);
4158 TAILQ_FOREACH(pe, dsa->paths, entry) {
4159 struct got_diff_changed_path *cp = pe->data;
4160 int pad = dsa->max_path_len - pe->path_len + 1;
4162 printf(" %c %s%*c | %*d+ %*d-\n", cp->status, pe->path, pad,
4163 ' ', dsa->add_cols + 1, cp->add, dsa->rm_cols + 1, cp->rm);
4165 printf("\n%d file%s changed, %d insertion%s(+), %d deletion%s(-)\n\n",
4166 dsa->nfiles, dsa->nfiles > 1 ? "s" : "", dsa->ins,
4167 dsa->ins != 1 ? "s" : "", dsa->del, dsa->del != 1 ? "s" : "");
4169 if (fflush(stdout) != 0)
4170 return got_error_from_errno("fflush");
4172 return NULL;
4175 static const struct got_error *
4176 printfile(FILE *f)
4178 char buf[8192];
4179 size_t r;
4181 if (fseeko(f, 0L, SEEK_SET) == -1)
4182 return got_error_from_errno("fseek");
4184 for (;;) {
4185 r = fread(buf, 1, sizeof(buf), f);
4186 if (r == 0) {
4187 if (ferror(f))
4188 return got_error_from_errno("fread");
4189 if (feof(f))
4190 break;
4192 if (fwrite(buf, 1, r, stdout) != r)
4193 return got_ferror(stdout, GOT_ERR_IO);
4196 return NULL;
4199 static const struct got_error *
4200 print_commit(struct got_commit_object *commit, struct got_object_id *id,
4201 struct got_repository *repo, const char *path,
4202 struct got_pathlist_head *changed_paths,
4203 struct got_diffstat_cb_arg *diffstat, int show_patch, int diff_context,
4204 struct got_reflist_object_id_map *refs_idmap, const char *custom_refs_str,
4205 const char *prefix)
4207 const struct got_error *err = NULL;
4208 FILE *f = NULL;
4209 char *id_str, *datestr, *logmsg0, *logmsg, *line;
4210 char datebuf[26];
4211 time_t committer_time;
4212 const char *author, *committer;
4213 char *refs_str = NULL;
4215 err = got_object_id_str(&id_str, id);
4216 if (err)
4217 return err;
4219 if (custom_refs_str == NULL) {
4220 struct got_reflist_head *refs;
4221 refs = got_reflist_object_id_map_lookup(refs_idmap, id);
4222 if (refs) {
4223 err = build_refs_str(&refs_str, refs, id, repo, 0);
4224 if (err)
4225 goto done;
4229 printf(GOT_COMMIT_SEP_STR);
4230 if (custom_refs_str)
4231 printf("%s %s (%s)\n", prefix ? prefix : "commit", id_str,
4232 custom_refs_str);
4233 else
4234 printf("%s %s%s%s%s\n", prefix ? prefix : "commit", id_str,
4235 refs_str ? " (" : "", refs_str ? refs_str : "",
4236 refs_str ? ")" : "");
4237 free(id_str);
4238 id_str = NULL;
4239 free(refs_str);
4240 refs_str = NULL;
4241 printf("from: %s\n", got_object_commit_get_author(commit));
4242 author = got_object_commit_get_author(commit);
4243 committer = got_object_commit_get_committer(commit);
4244 if (strcmp(author, committer) != 0)
4245 printf("via: %s\n", committer);
4246 committer_time = got_object_commit_get_committer_time(commit);
4247 datestr = get_datestr(&committer_time, datebuf);
4248 if (datestr)
4249 printf("date: %s UTC\n", datestr);
4250 if (got_object_commit_get_nparents(commit) > 1) {
4251 const struct got_object_id_queue *parent_ids;
4252 struct got_object_qid *qid;
4253 int n = 1;
4254 parent_ids = got_object_commit_get_parent_ids(commit);
4255 STAILQ_FOREACH(qid, parent_ids, entry) {
4256 err = got_object_id_str(&id_str, &qid->id);
4257 if (err)
4258 goto done;
4259 printf("parent %d: %s\n", n++, id_str);
4260 free(id_str);
4261 id_str = NULL;
4265 err = got_object_commit_get_logmsg(&logmsg0, commit);
4266 if (err)
4267 goto done;
4269 logmsg = logmsg0;
4270 do {
4271 line = strsep(&logmsg, "\n");
4272 if (line)
4273 printf(" %s\n", line);
4274 } while (line);
4275 free(logmsg0);
4277 if (changed_paths && diffstat == NULL) {
4278 struct got_pathlist_entry *pe;
4280 TAILQ_FOREACH(pe, changed_paths, entry) {
4281 struct got_diff_changed_path *cp = pe->data;
4283 printf(" %c %s\n", cp->status, pe->path);
4285 printf("\n");
4287 if (show_patch) {
4288 if (diffstat) {
4289 f = got_opentemp();
4290 if (f == NULL) {
4291 err = got_error_from_errno("got_opentemp");
4292 goto done;
4296 err = print_patch(commit, id, path, diff_context, diffstat,
4297 repo, diffstat == NULL ? stdout : f);
4298 if (err)
4299 goto done;
4301 if (diffstat) {
4302 err = print_diffstat(diffstat, NULL);
4303 if (err)
4304 goto done;
4305 if (show_patch) {
4306 err = printfile(f);
4307 if (err)
4308 goto done;
4311 if (show_patch)
4312 printf("\n");
4314 if (fflush(stdout) != 0 && err == NULL)
4315 err = got_error_from_errno("fflush");
4316 done:
4317 if (f && fclose(f) == EOF && err == NULL)
4318 err = got_error_from_errno("fclose");
4319 free(id_str);
4320 free(refs_str);
4321 return err;
4324 static const struct got_error *
4325 print_commits(struct got_object_id *root_id, struct got_object_id *end_id,
4326 struct got_repository *repo, const char *path, int show_changed_paths,
4327 int show_diffstat, int show_patch, const char *search_pattern,
4328 int diff_context, int limit, int log_branches, int reverse_display_order,
4329 struct got_reflist_object_id_map *refs_idmap, int one_line,
4330 FILE *tmpfile)
4332 const struct got_error *err;
4333 struct got_commit_graph *graph;
4334 regex_t regex;
4335 int have_match;
4336 struct got_object_id_queue reversed_commits;
4337 struct got_object_qid *qid;
4338 struct got_commit_object *commit;
4339 struct got_pathlist_head changed_paths;
4341 STAILQ_INIT(&reversed_commits);
4342 TAILQ_INIT(&changed_paths);
4344 if (search_pattern && regcomp(&regex, search_pattern,
4345 REG_EXTENDED | REG_NOSUB | REG_NEWLINE))
4346 return got_error_msg(GOT_ERR_REGEX, search_pattern);
4348 err = got_commit_graph_open(&graph, path, !log_branches);
4349 if (err)
4350 return err;
4351 err = got_commit_graph_iter_start(graph, root_id, repo,
4352 check_cancelled, NULL);
4353 if (err)
4354 goto done;
4355 for (;;) {
4356 struct got_object_id id;
4357 struct got_diffstat_cb_arg dsa = { 0, 0, 0, 0, 0, 0,
4358 &changed_paths, 0, 0, GOT_DIFF_ALGORITHM_PATIENCE };
4360 if (sigint_received || sigpipe_received)
4361 break;
4363 err = got_commit_graph_iter_next(&id, graph, repo,
4364 check_cancelled, NULL);
4365 if (err) {
4366 if (err->code == GOT_ERR_ITER_COMPLETED)
4367 err = NULL;
4368 break;
4371 err = got_object_open_as_commit(&commit, repo, &id);
4372 if (err)
4373 break;
4375 if ((show_changed_paths || (show_diffstat && !show_patch))
4376 && !reverse_display_order) {
4377 err = get_changed_paths(&changed_paths, commit, repo,
4378 show_diffstat ? &dsa : NULL);
4379 if (err)
4380 break;
4383 if (search_pattern) {
4384 err = match_commit(&have_match, &id, commit, &regex);
4385 if (err) {
4386 got_object_commit_close(commit);
4387 break;
4389 if (have_match == 0 && show_changed_paths)
4390 match_changed_paths(&have_match,
4391 &changed_paths, &regex);
4392 if (have_match == 0 && show_patch) {
4393 err = match_patch(&have_match, commit, &id,
4394 path, diff_context, repo, &regex, tmpfile);
4395 if (err)
4396 break;
4398 if (have_match == 0) {
4399 got_object_commit_close(commit);
4400 got_pathlist_free(&changed_paths,
4401 GOT_PATHLIST_FREE_ALL);
4402 continue;
4406 if (reverse_display_order) {
4407 err = got_object_qid_alloc(&qid, &id);
4408 if (err)
4409 break;
4410 STAILQ_INSERT_HEAD(&reversed_commits, qid, entry);
4411 got_object_commit_close(commit);
4412 } else {
4413 if (one_line)
4414 err = print_commit_oneline(commit, &id,
4415 repo, refs_idmap);
4416 else
4417 err = print_commit(commit, &id, repo, path,
4418 (show_changed_paths || show_diffstat) ?
4419 &changed_paths : NULL,
4420 show_diffstat ? &dsa : NULL, show_patch,
4421 diff_context, refs_idmap, NULL, NULL);
4422 got_object_commit_close(commit);
4423 if (err)
4424 break;
4426 if ((limit && --limit == 0) ||
4427 (end_id && got_object_id_cmp(&id, end_id) == 0))
4428 break;
4430 got_pathlist_free(&changed_paths, GOT_PATHLIST_FREE_ALL);
4432 if (reverse_display_order) {
4433 STAILQ_FOREACH(qid, &reversed_commits, entry) {
4434 struct got_diffstat_cb_arg dsa = { 0, 0, 0, 0, 0, 0,
4435 &changed_paths, 0, 0, GOT_DIFF_ALGORITHM_PATIENCE };
4437 err = got_object_open_as_commit(&commit, repo,
4438 &qid->id);
4439 if (err)
4440 break;
4441 if (show_changed_paths ||
4442 (show_diffstat && !show_patch)) {
4443 err = get_changed_paths(&changed_paths, commit,
4444 repo, show_diffstat ? &dsa : NULL);
4445 if (err)
4446 break;
4448 if (one_line)
4449 err = print_commit_oneline(commit, &qid->id,
4450 repo, refs_idmap);
4451 else
4452 err = print_commit(commit, &qid->id, repo, path,
4453 (show_changed_paths || show_diffstat) ?
4454 &changed_paths : NULL,
4455 show_diffstat ? &dsa : NULL, show_patch,
4456 diff_context, refs_idmap, NULL, NULL);
4457 got_object_commit_close(commit);
4458 if (err)
4459 break;
4460 got_pathlist_free(&changed_paths, GOT_PATHLIST_FREE_ALL);
4463 done:
4464 while (!STAILQ_EMPTY(&reversed_commits)) {
4465 qid = STAILQ_FIRST(&reversed_commits);
4466 STAILQ_REMOVE_HEAD(&reversed_commits, entry);
4467 got_object_qid_free(qid);
4469 got_pathlist_free(&changed_paths, GOT_PATHLIST_FREE_ALL);
4470 if (search_pattern)
4471 regfree(&regex);
4472 got_commit_graph_close(graph);
4473 return err;
4476 __dead static void
4477 usage_log(void)
4479 fprintf(stderr, "usage: %s log [-bdPpRs] [-C number] [-c commit] "
4480 "[-l N] [-r repository-path] [-S search-pattern] [-x commit] "
4481 "[path]\n", getprogname());
4482 exit(1);
4485 static int
4486 get_default_log_limit(void)
4488 const char *got_default_log_limit;
4489 long long n;
4490 const char *errstr;
4492 got_default_log_limit = getenv("GOT_LOG_DEFAULT_LIMIT");
4493 if (got_default_log_limit == NULL)
4494 return 0;
4495 n = strtonum(got_default_log_limit, 0, INT_MAX, &errstr);
4496 if (errstr != NULL)
4497 return 0;
4498 return n;
4501 static const struct got_error *
4502 cmd_log(int argc, char *argv[])
4504 const struct got_error *error;
4505 struct got_repository *repo = NULL;
4506 struct got_worktree *worktree = NULL;
4507 struct got_object_id *start_id = NULL, *end_id = NULL;
4508 char *repo_path = NULL, *path = NULL, *cwd = NULL, *in_repo_path = NULL;
4509 const char *start_commit = NULL, *end_commit = NULL;
4510 const char *search_pattern = NULL;
4511 int diff_context = -1, ch;
4512 int show_changed_paths = 0, show_patch = 0, limit = 0, log_branches = 0;
4513 int show_diffstat = 0, reverse_display_order = 0, one_line = 0;
4514 const char *errstr;
4515 struct got_reflist_head refs;
4516 struct got_reflist_object_id_map *refs_idmap = NULL;
4517 FILE *tmpfile = NULL;
4518 int *pack_fds = NULL;
4520 TAILQ_INIT(&refs);
4522 #ifndef PROFILE
4523 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
4524 NULL)
4525 == -1)
4526 err(1, "pledge");
4527 #endif
4529 limit = get_default_log_limit();
4531 while ((ch = getopt(argc, argv, "bC:c:dl:PpRr:S:sx:")) != -1) {
4532 switch (ch) {
4533 case 'b':
4534 log_branches = 1;
4535 break;
4536 case 'C':
4537 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
4538 &errstr);
4539 if (errstr != NULL)
4540 errx(1, "number of context lines is %s: %s",
4541 errstr, optarg);
4542 break;
4543 case 'c':
4544 start_commit = optarg;
4545 break;
4546 case 'd':
4547 show_diffstat = 1;
4548 break;
4549 case 'l':
4550 limit = strtonum(optarg, 0, INT_MAX, &errstr);
4551 if (errstr != NULL)
4552 errx(1, "number of commits is %s: %s",
4553 errstr, optarg);
4554 break;
4555 case 'P':
4556 show_changed_paths = 1;
4557 break;
4558 case 'p':
4559 show_patch = 1;
4560 break;
4561 case 'R':
4562 reverse_display_order = 1;
4563 break;
4564 case 'r':
4565 repo_path = realpath(optarg, NULL);
4566 if (repo_path == NULL)
4567 return got_error_from_errno2("realpath",
4568 optarg);
4569 got_path_strip_trailing_slashes(repo_path);
4570 break;
4571 case 'S':
4572 search_pattern = optarg;
4573 break;
4574 case 's':
4575 one_line = 1;
4576 break;
4577 case 'x':
4578 end_commit = optarg;
4579 break;
4580 default:
4581 usage_log();
4582 /* NOTREACHED */
4586 argc -= optind;
4587 argv += optind;
4589 if (diff_context == -1)
4590 diff_context = 3;
4591 else if (!show_patch)
4592 errx(1, "-C requires -p");
4594 if (one_line && (show_patch || show_changed_paths || show_diffstat))
4595 errx(1, "cannot use -s with -d, -p or -P");
4597 cwd = getcwd(NULL, 0);
4598 if (cwd == NULL) {
4599 error = got_error_from_errno("getcwd");
4600 goto done;
4603 error = got_repo_pack_fds_open(&pack_fds);
4604 if (error != NULL)
4605 goto done;
4607 if (repo_path == NULL) {
4608 error = got_worktree_open(&worktree, cwd);
4609 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4610 goto done;
4611 error = NULL;
4614 if (argc == 1) {
4615 if (worktree) {
4616 error = got_worktree_resolve_path(&path, worktree,
4617 argv[0]);
4618 if (error)
4619 goto done;
4620 } else {
4621 path = strdup(argv[0]);
4622 if (path == NULL) {
4623 error = got_error_from_errno("strdup");
4624 goto done;
4627 } else if (argc != 0)
4628 usage_log();
4630 if (repo_path == NULL) {
4631 repo_path = worktree ?
4632 strdup(got_worktree_get_repo_path(worktree)) : strdup(cwd);
4634 if (repo_path == NULL) {
4635 error = got_error_from_errno("strdup");
4636 goto done;
4639 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
4640 if (error != NULL)
4641 goto done;
4643 error = apply_unveil(got_repo_get_path(repo), 1,
4644 worktree ? got_worktree_get_root_path(worktree) : NULL);
4645 if (error)
4646 goto done;
4648 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
4649 if (error)
4650 goto done;
4652 error = got_reflist_object_id_map_create(&refs_idmap, &refs, repo);
4653 if (error)
4654 goto done;
4656 if (start_commit == NULL) {
4657 struct got_reference *head_ref;
4658 struct got_commit_object *commit = NULL;
4659 error = got_ref_open(&head_ref, repo,
4660 worktree ? got_worktree_get_head_ref_name(worktree)
4661 : GOT_REF_HEAD, 0);
4662 if (error != NULL)
4663 goto done;
4664 error = got_ref_resolve(&start_id, repo, head_ref);
4665 got_ref_close(head_ref);
4666 if (error != NULL)
4667 goto done;
4668 error = got_object_open_as_commit(&commit, repo,
4669 start_id);
4670 if (error != NULL)
4671 goto done;
4672 got_object_commit_close(commit);
4673 } else {
4674 error = got_repo_match_object_id(&start_id, NULL,
4675 start_commit, GOT_OBJ_TYPE_COMMIT, &refs, repo);
4676 if (error != NULL)
4677 goto done;
4679 if (end_commit != NULL) {
4680 error = got_repo_match_object_id(&end_id, NULL,
4681 end_commit, GOT_OBJ_TYPE_COMMIT, &refs, repo);
4682 if (error != NULL)
4683 goto done;
4686 if (worktree) {
4688 * If a path was specified on the command line it was resolved
4689 * to a path in the work tree above. Prepend the work tree's
4690 * path prefix to obtain the corresponding in-repository path.
4692 if (path) {
4693 const char *prefix;
4694 prefix = got_worktree_get_path_prefix(worktree);
4695 if (asprintf(&in_repo_path, "%s%s%s", prefix,
4696 (path[0] != '\0') ? "/" : "", path) == -1) {
4697 error = got_error_from_errno("asprintf");
4698 goto done;
4701 } else
4702 error = got_repo_map_path(&in_repo_path, repo,
4703 path ? path : "");
4704 if (error != NULL)
4705 goto done;
4706 if (in_repo_path) {
4707 free(path);
4708 path = in_repo_path;
4711 if (worktree) {
4712 /* Release work tree lock. */
4713 got_worktree_close(worktree);
4714 worktree = NULL;
4717 if (search_pattern && show_patch) {
4718 tmpfile = got_opentemp();
4719 if (tmpfile == NULL) {
4720 error = got_error_from_errno("got_opentemp");
4721 goto done;
4725 error = print_commits(start_id, end_id, repo, path ? path : "",
4726 show_changed_paths, show_diffstat, show_patch, search_pattern,
4727 diff_context, limit, log_branches, reverse_display_order,
4728 refs_idmap, one_line, tmpfile);
4729 done:
4730 free(path);
4731 free(repo_path);
4732 free(cwd);
4733 if (worktree)
4734 got_worktree_close(worktree);
4735 if (repo) {
4736 const struct got_error *close_err = got_repo_close(repo);
4737 if (error == NULL)
4738 error = close_err;
4740 if (pack_fds) {
4741 const struct got_error *pack_err =
4742 got_repo_pack_fds_close(pack_fds);
4743 if (error == NULL)
4744 error = pack_err;
4746 if (refs_idmap)
4747 got_reflist_object_id_map_free(refs_idmap);
4748 if (tmpfile && fclose(tmpfile) == EOF && error == NULL)
4749 error = got_error_from_errno("fclose");
4750 got_ref_list_free(&refs);
4751 return error;
4754 __dead static void
4755 usage_diff(void)
4757 fprintf(stderr, "usage: %s diff [-adPsw] [-C number] [-c commit] "
4758 "[-r repository-path] [object1 object2 | path ...]\n",
4759 getprogname());
4760 exit(1);
4763 struct print_diff_arg {
4764 struct got_repository *repo;
4765 struct got_worktree *worktree;
4766 struct got_diffstat_cb_arg *diffstat;
4767 int diff_context;
4768 const char *id_str;
4769 int header_shown;
4770 int diff_staged;
4771 enum got_diff_algorithm diff_algo;
4772 int ignore_whitespace;
4773 int force_text_diff;
4774 FILE *f1;
4775 FILE *f2;
4776 FILE *outfile;
4780 * Create a file which contains the target path of a symlink so we can feed
4781 * it as content to the diff engine.
4783 static const struct got_error *
4784 get_symlink_target_file(int *fd, int dirfd, const char *de_name,
4785 const char *abspath)
4787 const struct got_error *err = NULL;
4788 char target_path[PATH_MAX];
4789 ssize_t target_len, outlen;
4791 *fd = -1;
4793 if (dirfd != -1) {
4794 target_len = readlinkat(dirfd, de_name, target_path, PATH_MAX);
4795 if (target_len == -1)
4796 return got_error_from_errno2("readlinkat", abspath);
4797 } else {
4798 target_len = readlink(abspath, target_path, PATH_MAX);
4799 if (target_len == -1)
4800 return got_error_from_errno2("readlink", abspath);
4803 *fd = got_opentempfd();
4804 if (*fd == -1)
4805 return got_error_from_errno("got_opentempfd");
4807 outlen = write(*fd, target_path, target_len);
4808 if (outlen == -1) {
4809 err = got_error_from_errno("got_opentempfd");
4810 goto done;
4813 if (lseek(*fd, 0, SEEK_SET) == -1) {
4814 err = got_error_from_errno2("lseek", abspath);
4815 goto done;
4817 done:
4818 if (err) {
4819 close(*fd);
4820 *fd = -1;
4822 return err;
4825 static const struct got_error *
4826 print_diff(void *arg, unsigned char status, unsigned char staged_status,
4827 const char *path, struct got_object_id *blob_id,
4828 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
4829 int dirfd, const char *de_name)
4831 struct print_diff_arg *a = arg;
4832 const struct got_error *err = NULL;
4833 struct got_blob_object *blob1 = NULL;
4834 int fd = -1, fd1 = -1, fd2 = -1;
4835 FILE *f2 = NULL;
4836 char *abspath = NULL, *label1 = NULL;
4837 struct stat sb;
4838 off_t size1 = 0;
4839 int f2_exists = 0;
4841 memset(&sb, 0, sizeof(sb));
4843 if (a->diff_staged) {
4844 if (staged_status != GOT_STATUS_MODIFY &&
4845 staged_status != GOT_STATUS_ADD &&
4846 staged_status != GOT_STATUS_DELETE)
4847 return NULL;
4848 } else {
4849 if (staged_status == GOT_STATUS_DELETE)
4850 return NULL;
4851 if (status == GOT_STATUS_NONEXISTENT)
4852 return got_error_set_errno(ENOENT, path);
4853 if (status != GOT_STATUS_MODIFY &&
4854 status != GOT_STATUS_ADD &&
4855 status != GOT_STATUS_DELETE &&
4856 status != GOT_STATUS_CONFLICT)
4857 return NULL;
4860 err = got_opentemp_truncate(a->f1);
4861 if (err)
4862 return got_error_from_errno("got_opentemp_truncate");
4863 err = got_opentemp_truncate(a->f2);
4864 if (err)
4865 return got_error_from_errno("got_opentemp_truncate");
4867 if (!a->header_shown) {
4868 if (fprintf(a->outfile, "diff %s%s\n",
4869 a->diff_staged ? "-s " : "",
4870 got_worktree_get_root_path(a->worktree)) < 0) {
4871 err = got_error_from_errno("fprintf");
4872 goto done;
4874 if (fprintf(a->outfile, "commit - %s\n", a->id_str) < 0) {
4875 err = got_error_from_errno("fprintf");
4876 goto done;
4878 if (fprintf(a->outfile, "path + %s%s\n",
4879 got_worktree_get_root_path(a->worktree),
4880 a->diff_staged ? " (staged changes)" : "") < 0) {
4881 err = got_error_from_errno("fprintf");
4882 goto done;
4884 a->header_shown = 1;
4887 if (a->diff_staged) {
4888 const char *label1 = NULL, *label2 = NULL;
4889 switch (staged_status) {
4890 case GOT_STATUS_MODIFY:
4891 label1 = path;
4892 label2 = path;
4893 break;
4894 case GOT_STATUS_ADD:
4895 label2 = path;
4896 break;
4897 case GOT_STATUS_DELETE:
4898 label1 = path;
4899 break;
4900 default:
4901 return got_error(GOT_ERR_FILE_STATUS);
4903 fd1 = got_opentempfd();
4904 if (fd1 == -1) {
4905 err = got_error_from_errno("got_opentempfd");
4906 goto done;
4908 fd2 = got_opentempfd();
4909 if (fd2 == -1) {
4910 err = got_error_from_errno("got_opentempfd");
4911 goto done;
4913 err = got_diff_objects_as_blobs(NULL, NULL, a->f1, a->f2,
4914 fd1, fd2, blob_id, staged_blob_id, label1, label2,
4915 a->diff_algo, a->diff_context, a->ignore_whitespace,
4916 a->force_text_diff, a->diffstat, a->repo, a->outfile);
4917 goto done;
4920 fd1 = got_opentempfd();
4921 if (fd1 == -1) {
4922 err = got_error_from_errno("got_opentempfd");
4923 goto done;
4926 if (staged_status == GOT_STATUS_ADD ||
4927 staged_status == GOT_STATUS_MODIFY) {
4928 char *id_str;
4929 err = got_object_open_as_blob(&blob1, a->repo, staged_blob_id,
4930 8192, fd1);
4931 if (err)
4932 goto done;
4933 err = got_object_id_str(&id_str, staged_blob_id);
4934 if (err)
4935 goto done;
4936 if (asprintf(&label1, "%s (staged)", id_str) == -1) {
4937 err = got_error_from_errno("asprintf");
4938 free(id_str);
4939 goto done;
4941 free(id_str);
4942 } else if (status != GOT_STATUS_ADD) {
4943 err = got_object_open_as_blob(&blob1, a->repo, blob_id, 8192,
4944 fd1);
4945 if (err)
4946 goto done;
4949 if (status != GOT_STATUS_DELETE) {
4950 if (asprintf(&abspath, "%s/%s",
4951 got_worktree_get_root_path(a->worktree), path) == -1) {
4952 err = got_error_from_errno("asprintf");
4953 goto done;
4956 if (dirfd != -1) {
4957 fd = openat(dirfd, de_name,
4958 O_RDONLY | O_NOFOLLOW | O_CLOEXEC);
4959 if (fd == -1) {
4960 if (!got_err_open_nofollow_on_symlink()) {
4961 err = got_error_from_errno2("openat",
4962 abspath);
4963 goto done;
4965 err = get_symlink_target_file(&fd, dirfd,
4966 de_name, abspath);
4967 if (err)
4968 goto done;
4970 } else {
4971 fd = open(abspath, O_RDONLY | O_NOFOLLOW | O_CLOEXEC);
4972 if (fd == -1) {
4973 if (!got_err_open_nofollow_on_symlink()) {
4974 err = got_error_from_errno2("open",
4975 abspath);
4976 goto done;
4978 err = get_symlink_target_file(&fd, dirfd,
4979 de_name, abspath);
4980 if (err)
4981 goto done;
4984 if (fstatat(fd, abspath, &sb, AT_SYMLINK_NOFOLLOW) == -1) {
4985 err = got_error_from_errno2("fstatat", abspath);
4986 goto done;
4988 f2 = fdopen(fd, "r");
4989 if (f2 == NULL) {
4990 err = got_error_from_errno2("fdopen", abspath);
4991 goto done;
4993 fd = -1;
4994 f2_exists = 1;
4997 if (blob1) {
4998 err = got_object_blob_dump_to_file(&size1, NULL, NULL,
4999 a->f1, blob1);
5000 if (err)
5001 goto done;
5004 err = got_diff_blob_file(blob1, a->f1, size1, label1, f2 ? f2 : a->f2,
5005 f2_exists, &sb, path, GOT_DIFF_ALGORITHM_PATIENCE, a->diff_context,
5006 a->ignore_whitespace, a->force_text_diff, a->diffstat, a->outfile);
5007 done:
5008 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
5009 err = got_error_from_errno("close");
5010 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
5011 err = got_error_from_errno("close");
5012 if (blob1)
5013 got_object_blob_close(blob1);
5014 if (fd != -1 && close(fd) == -1 && err == NULL)
5015 err = got_error_from_errno("close");
5016 if (f2 && fclose(f2) == EOF && err == NULL)
5017 err = got_error_from_errno("fclose");
5018 free(abspath);
5019 return err;
5022 static const struct got_error *
5023 cmd_diff(int argc, char *argv[])
5025 const struct got_error *error;
5026 struct got_repository *repo = NULL;
5027 struct got_worktree *worktree = NULL;
5028 char *cwd = NULL, *repo_path = NULL;
5029 const char *commit_args[2] = { NULL, NULL };
5030 int ncommit_args = 0;
5031 struct got_object_id *ids[2] = { NULL, NULL };
5032 char *labels[2] = { NULL, NULL };
5033 int type1 = GOT_OBJ_TYPE_ANY, type2 = GOT_OBJ_TYPE_ANY;
5034 int diff_context = 3, diff_staged = 0, ignore_whitespace = 0, ch, i;
5035 int force_text_diff = 0, force_path = 0, rflag = 0, show_diffstat = 0;
5036 const char *errstr;
5037 struct got_reflist_head refs;
5038 struct got_pathlist_head diffstat_paths, paths;
5039 FILE *f1 = NULL, *f2 = NULL, *outfile = NULL;
5040 int fd1 = -1, fd2 = -1;
5041 int *pack_fds = NULL;
5042 struct got_diffstat_cb_arg dsa;
5044 memset(&dsa, 0, sizeof(dsa));
5046 TAILQ_INIT(&refs);
5047 TAILQ_INIT(&paths);
5048 TAILQ_INIT(&diffstat_paths);
5050 #ifndef PROFILE
5051 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
5052 NULL) == -1)
5053 err(1, "pledge");
5054 #endif
5056 while ((ch = getopt(argc, argv, "aC:c:dPr:sw")) != -1) {
5057 switch (ch) {
5058 case 'a':
5059 force_text_diff = 1;
5060 break;
5061 case 'C':
5062 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
5063 &errstr);
5064 if (errstr != NULL)
5065 errx(1, "number of context lines is %s: %s",
5066 errstr, optarg);
5067 break;
5068 case 'c':
5069 if (ncommit_args >= 2)
5070 errx(1, "too many -c options used");
5071 commit_args[ncommit_args++] = optarg;
5072 break;
5073 case 'd':
5074 show_diffstat = 1;
5075 break;
5076 case 'P':
5077 force_path = 1;
5078 break;
5079 case 'r':
5080 repo_path = realpath(optarg, NULL);
5081 if (repo_path == NULL)
5082 return got_error_from_errno2("realpath",
5083 optarg);
5084 got_path_strip_trailing_slashes(repo_path);
5085 rflag = 1;
5086 break;
5087 case 's':
5088 diff_staged = 1;
5089 break;
5090 case 'w':
5091 ignore_whitespace = 1;
5092 break;
5093 default:
5094 usage_diff();
5095 /* NOTREACHED */
5099 argc -= optind;
5100 argv += optind;
5102 cwd = getcwd(NULL, 0);
5103 if (cwd == NULL) {
5104 error = got_error_from_errno("getcwd");
5105 goto done;
5108 error = got_repo_pack_fds_open(&pack_fds);
5109 if (error != NULL)
5110 goto done;
5112 if (repo_path == NULL) {
5113 error = got_worktree_open(&worktree, cwd);
5114 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5115 goto done;
5116 else
5117 error = NULL;
5118 if (worktree) {
5119 repo_path =
5120 strdup(got_worktree_get_repo_path(worktree));
5121 if (repo_path == NULL) {
5122 error = got_error_from_errno("strdup");
5123 goto done;
5125 } else {
5126 repo_path = strdup(cwd);
5127 if (repo_path == NULL) {
5128 error = got_error_from_errno("strdup");
5129 goto done;
5134 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
5135 free(repo_path);
5136 if (error != NULL)
5137 goto done;
5139 if (show_diffstat) {
5140 dsa.paths = &diffstat_paths;
5141 dsa.force_text = force_text_diff;
5142 dsa.ignore_ws = ignore_whitespace;
5143 dsa.diff_algo = GOT_DIFF_ALGORITHM_PATIENCE;
5146 if (rflag || worktree == NULL || ncommit_args > 0) {
5147 if (force_path) {
5148 error = got_error_msg(GOT_ERR_NOT_IMPL,
5149 "-P option can only be used when diffing "
5150 "a work tree");
5151 goto done;
5153 if (diff_staged) {
5154 error = got_error_msg(GOT_ERR_NOT_IMPL,
5155 "-s option can only be used when diffing "
5156 "a work tree");
5157 goto done;
5161 error = apply_unveil(got_repo_get_path(repo), 1,
5162 worktree ? got_worktree_get_root_path(worktree) : NULL);
5163 if (error)
5164 goto done;
5166 if ((!force_path && argc == 2) || ncommit_args > 0) {
5167 int obj_type = (ncommit_args > 0 ?
5168 GOT_OBJ_TYPE_COMMIT : GOT_OBJ_TYPE_ANY);
5169 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
5170 NULL);
5171 if (error)
5172 goto done;
5173 for (i = 0; i < (ncommit_args > 0 ? ncommit_args : argc); i++) {
5174 const char *arg;
5175 if (ncommit_args > 0)
5176 arg = commit_args[i];
5177 else
5178 arg = argv[i];
5179 error = got_repo_match_object_id(&ids[i], &labels[i],
5180 arg, obj_type, &refs, repo);
5181 if (error) {
5182 if (error->code != GOT_ERR_NOT_REF &&
5183 error->code != GOT_ERR_NO_OBJ)
5184 goto done;
5185 if (ncommit_args > 0)
5186 goto done;
5187 error = NULL;
5188 break;
5193 f1 = got_opentemp();
5194 if (f1 == NULL) {
5195 error = got_error_from_errno("got_opentemp");
5196 goto done;
5199 f2 = got_opentemp();
5200 if (f2 == NULL) {
5201 error = got_error_from_errno("got_opentemp");
5202 goto done;
5205 outfile = got_opentemp();
5206 if (outfile == NULL) {
5207 error = got_error_from_errno("got_opentemp");
5208 goto done;
5211 if (ncommit_args == 0 && (ids[0] == NULL || ids[1] == NULL)) {
5212 struct print_diff_arg arg;
5213 char *id_str;
5215 if (worktree == NULL) {
5216 if (argc == 2 && ids[0] == NULL) {
5217 error = got_error_path(argv[0], GOT_ERR_NO_OBJ);
5218 goto done;
5219 } else if (argc == 2 && ids[1] == NULL) {
5220 error = got_error_path(argv[1], GOT_ERR_NO_OBJ);
5221 goto done;
5222 } else if (argc > 0) {
5223 error = got_error_fmt(GOT_ERR_NOT_WORKTREE,
5224 "%s", "specified paths cannot be resolved");
5225 goto done;
5226 } else {
5227 error = got_error(GOT_ERR_NOT_WORKTREE);
5228 goto done;
5232 error = get_worktree_paths_from_argv(&paths, argc, argv,
5233 worktree);
5234 if (error)
5235 goto done;
5237 error = got_object_id_str(&id_str,
5238 got_worktree_get_base_commit_id(worktree));
5239 if (error)
5240 goto done;
5241 arg.repo = repo;
5242 arg.worktree = worktree;
5243 arg.diff_algo = GOT_DIFF_ALGORITHM_PATIENCE;
5244 arg.diff_context = diff_context;
5245 arg.id_str = id_str;
5246 arg.header_shown = 0;
5247 arg.diff_staged = diff_staged;
5248 arg.ignore_whitespace = ignore_whitespace;
5249 arg.force_text_diff = force_text_diff;
5250 arg.diffstat = show_diffstat ? &dsa : NULL;
5251 arg.f1 = f1;
5252 arg.f2 = f2;
5253 arg.outfile = outfile;
5255 error = got_worktree_status(worktree, &paths, repo, 0,
5256 print_diff, &arg, check_cancelled, NULL);
5257 free(id_str);
5258 if (error)
5259 goto done;
5261 if (show_diffstat && dsa.nfiles > 0) {
5262 char *header;
5264 if (asprintf(&header, "diffstat %s%s",
5265 diff_staged ? "-s " : "",
5266 got_worktree_get_root_path(worktree)) == -1) {
5267 error = got_error_from_errno("asprintf");
5268 goto done;
5271 error = print_diffstat(&dsa, header);
5272 free(header);
5273 if (error)
5274 goto done;
5277 error = printfile(outfile);
5278 goto done;
5281 if (ncommit_args == 1) {
5282 struct got_commit_object *commit;
5283 error = got_object_open_as_commit(&commit, repo, ids[0]);
5284 if (error)
5285 goto done;
5287 labels[1] = labels[0];
5288 ids[1] = ids[0];
5289 if (got_object_commit_get_nparents(commit) > 0) {
5290 const struct got_object_id_queue *pids;
5291 struct got_object_qid *pid;
5292 pids = got_object_commit_get_parent_ids(commit);
5293 pid = STAILQ_FIRST(pids);
5294 ids[0] = got_object_id_dup(&pid->id);
5295 if (ids[0] == NULL) {
5296 error = got_error_from_errno(
5297 "got_object_id_dup");
5298 got_object_commit_close(commit);
5299 goto done;
5301 error = got_object_id_str(&labels[0], ids[0]);
5302 if (error) {
5303 got_object_commit_close(commit);
5304 goto done;
5306 } else {
5307 ids[0] = NULL;
5308 labels[0] = strdup("/dev/null");
5309 if (labels[0] == NULL) {
5310 error = got_error_from_errno("strdup");
5311 got_object_commit_close(commit);
5312 goto done;
5316 got_object_commit_close(commit);
5319 if (ncommit_args == 0 && argc > 2) {
5320 error = got_error_msg(GOT_ERR_BAD_PATH,
5321 "path arguments cannot be used when diffing two objects");
5322 goto done;
5325 if (ids[0]) {
5326 error = got_object_get_type(&type1, repo, ids[0]);
5327 if (error)
5328 goto done;
5331 error = got_object_get_type(&type2, repo, ids[1]);
5332 if (error)
5333 goto done;
5334 if (type1 != GOT_OBJ_TYPE_ANY && type1 != type2) {
5335 error = got_error(GOT_ERR_OBJ_TYPE);
5336 goto done;
5338 if (type1 == GOT_OBJ_TYPE_BLOB && argc > 2) {
5339 error = got_error_msg(GOT_ERR_OBJ_TYPE,
5340 "path arguments cannot be used when diffing blobs");
5341 goto done;
5344 for (i = 0; ncommit_args > 0 && i < argc; i++) {
5345 char *in_repo_path;
5346 struct got_pathlist_entry *new;
5347 if (worktree) {
5348 const char *prefix;
5349 char *p;
5350 error = got_worktree_resolve_path(&p, worktree,
5351 argv[i]);
5352 if (error)
5353 goto done;
5354 prefix = got_worktree_get_path_prefix(worktree);
5355 while (prefix[0] == '/')
5356 prefix++;
5357 if (asprintf(&in_repo_path, "%s%s%s", prefix,
5358 (p[0] != '\0' && prefix[0] != '\0') ? "/" : "",
5359 p) == -1) {
5360 error = got_error_from_errno("asprintf");
5361 free(p);
5362 goto done;
5364 free(p);
5365 } else {
5366 char *mapped_path, *s;
5367 error = got_repo_map_path(&mapped_path, repo, argv[i]);
5368 if (error)
5369 goto done;
5370 s = mapped_path;
5371 while (s[0] == '/')
5372 s++;
5373 in_repo_path = strdup(s);
5374 if (in_repo_path == NULL) {
5375 error = got_error_from_errno("asprintf");
5376 free(mapped_path);
5377 goto done;
5379 free(mapped_path);
5382 error = got_pathlist_insert(&new, &paths, in_repo_path, NULL);
5383 if (error || new == NULL /* duplicate */)
5384 free(in_repo_path);
5385 if (error)
5386 goto done;
5389 if (worktree) {
5390 /* Release work tree lock. */
5391 got_worktree_close(worktree);
5392 worktree = NULL;
5395 fd1 = got_opentempfd();
5396 if (fd1 == -1) {
5397 error = got_error_from_errno("got_opentempfd");
5398 goto done;
5401 fd2 = got_opentempfd();
5402 if (fd2 == -1) {
5403 error = got_error_from_errno("got_opentempfd");
5404 goto done;
5407 switch (type1 == GOT_OBJ_TYPE_ANY ? type2 : type1) {
5408 case GOT_OBJ_TYPE_BLOB:
5409 error = got_diff_objects_as_blobs(NULL, NULL, f1, f2,
5410 fd1, fd2, ids[0], ids[1], NULL, NULL,
5411 GOT_DIFF_ALGORITHM_PATIENCE, diff_context,
5412 ignore_whitespace, force_text_diff,
5413 show_diffstat ? &dsa : NULL, repo, outfile);
5414 break;
5415 case GOT_OBJ_TYPE_TREE:
5416 error = got_diff_objects_as_trees(NULL, NULL, f1, f2, fd1, fd2,
5417 ids[0], ids[1], &paths, "", "",
5418 GOT_DIFF_ALGORITHM_PATIENCE, diff_context,
5419 ignore_whitespace, force_text_diff,
5420 show_diffstat ? &dsa : NULL, repo, outfile);
5421 break;
5422 case GOT_OBJ_TYPE_COMMIT:
5423 fprintf(outfile, "diff %s %s\n", labels[0], labels[1]);
5424 error = got_diff_objects_as_commits(NULL, NULL, f1, f2,
5425 fd1, fd2, ids[0], ids[1], &paths,
5426 GOT_DIFF_ALGORITHM_PATIENCE, diff_context,
5427 ignore_whitespace, force_text_diff,
5428 show_diffstat ? &dsa : NULL, repo, outfile);
5429 break;
5430 default:
5431 error = got_error(GOT_ERR_OBJ_TYPE);
5433 if (error)
5434 goto done;
5436 if (show_diffstat && dsa.nfiles > 0) {
5437 char *header = NULL;
5439 if (asprintf(&header, "diffstat %s %s",
5440 labels[0], labels[1]) == -1) {
5441 error = got_error_from_errno("asprintf");
5442 goto done;
5445 error = print_diffstat(&dsa, header);
5446 free(header);
5447 if (error)
5448 goto done;
5451 error = printfile(outfile);
5453 done:
5454 free(labels[0]);
5455 free(labels[1]);
5456 free(ids[0]);
5457 free(ids[1]);
5458 if (worktree)
5459 got_worktree_close(worktree);
5460 if (repo) {
5461 const struct got_error *close_err = got_repo_close(repo);
5462 if (error == NULL)
5463 error = close_err;
5465 if (pack_fds) {
5466 const struct got_error *pack_err =
5467 got_repo_pack_fds_close(pack_fds);
5468 if (error == NULL)
5469 error = pack_err;
5471 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
5472 got_pathlist_free(&diffstat_paths, GOT_PATHLIST_FREE_ALL);
5473 got_ref_list_free(&refs);
5474 if (outfile && fclose(outfile) == EOF && error == NULL)
5475 error = got_error_from_errno("fclose");
5476 if (f1 && fclose(f1) == EOF && error == NULL)
5477 error = got_error_from_errno("fclose");
5478 if (f2 && fclose(f2) == EOF && error == NULL)
5479 error = got_error_from_errno("fclose");
5480 if (fd1 != -1 && close(fd1) == -1 && error == NULL)
5481 error = got_error_from_errno("close");
5482 if (fd2 != -1 && close(fd2) == -1 && error == NULL)
5483 error = got_error_from_errno("close");
5484 return error;
5487 __dead static void
5488 usage_blame(void)
5490 fprintf(stderr,
5491 "usage: %s blame [-c commit] [-r repository-path] path\n",
5492 getprogname());
5493 exit(1);
5496 struct blame_line {
5497 int annotated;
5498 char *id_str;
5499 char *committer;
5500 char datebuf[11]; /* YYYY-MM-DD + NUL */
5503 struct blame_cb_args {
5504 struct blame_line *lines;
5505 int nlines;
5506 int nlines_prec;
5507 int lineno_cur;
5508 off_t *line_offsets;
5509 FILE *f;
5510 struct got_repository *repo;
5513 static const struct got_error *
5514 blame_cb(void *arg, int nlines, int lineno,
5515 struct got_commit_object *commit, struct got_object_id *id)
5517 const struct got_error *err = NULL;
5518 struct blame_cb_args *a = arg;
5519 struct blame_line *bline;
5520 char *line = NULL;
5521 size_t linesize = 0;
5522 off_t offset;
5523 struct tm tm;
5524 time_t committer_time;
5526 if (nlines != a->nlines ||
5527 (lineno != -1 && lineno < 1) || lineno > a->nlines)
5528 return got_error(GOT_ERR_RANGE);
5530 if (sigint_received)
5531 return got_error(GOT_ERR_ITER_COMPLETED);
5533 if (lineno == -1)
5534 return NULL; /* no change in this commit */
5536 /* Annotate this line. */
5537 bline = &a->lines[lineno - 1];
5538 if (bline->annotated)
5539 return NULL;
5540 err = got_object_id_str(&bline->id_str, id);
5541 if (err)
5542 return err;
5544 bline->committer = strdup(got_object_commit_get_committer(commit));
5545 if (bline->committer == NULL) {
5546 err = got_error_from_errno("strdup");
5547 goto done;
5550 committer_time = got_object_commit_get_committer_time(commit);
5551 if (gmtime_r(&committer_time, &tm) == NULL)
5552 return got_error_from_errno("gmtime_r");
5553 if (strftime(bline->datebuf, sizeof(bline->datebuf), "%G-%m-%d",
5554 &tm) == 0) {
5555 err = got_error(GOT_ERR_NO_SPACE);
5556 goto done;
5558 bline->annotated = 1;
5560 /* Print lines annotated so far. */
5561 bline = &a->lines[a->lineno_cur - 1];
5562 if (!bline->annotated)
5563 goto done;
5565 offset = a->line_offsets[a->lineno_cur - 1];
5566 if (fseeko(a->f, offset, SEEK_SET) == -1) {
5567 err = got_error_from_errno("fseeko");
5568 goto done;
5571 while (a->lineno_cur <= a->nlines && bline->annotated) {
5572 char *smallerthan, *at, *nl, *committer;
5573 size_t len;
5575 if (getline(&line, &linesize, a->f) == -1) {
5576 if (ferror(a->f))
5577 err = got_error_from_errno("getline");
5578 break;
5581 committer = bline->committer;
5582 smallerthan = strchr(committer, '<');
5583 if (smallerthan && smallerthan[1] != '\0')
5584 committer = smallerthan + 1;
5585 at = strchr(committer, '@');
5586 if (at)
5587 *at = '\0';
5588 len = strlen(committer);
5589 if (len >= 9)
5590 committer[8] = '\0';
5592 nl = strchr(line, '\n');
5593 if (nl)
5594 *nl = '\0';
5595 printf("%.*d) %.8s %s %-8s %s\n", a->nlines_prec, a->lineno_cur,
5596 bline->id_str, bline->datebuf, committer, line);
5598 a->lineno_cur++;
5599 bline = &a->lines[a->lineno_cur - 1];
5601 done:
5602 free(line);
5603 return err;
5606 static const struct got_error *
5607 cmd_blame(int argc, char *argv[])
5609 const struct got_error *error;
5610 struct got_repository *repo = NULL;
5611 struct got_worktree *worktree = NULL;
5612 char *path, *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
5613 char *link_target = NULL;
5614 struct got_object_id *obj_id = NULL;
5615 struct got_object_id *commit_id = NULL;
5616 struct got_commit_object *commit = NULL;
5617 struct got_blob_object *blob = NULL;
5618 char *commit_id_str = NULL;
5619 struct blame_cb_args bca;
5620 int ch, obj_type, i, fd1 = -1, fd2 = -1, fd3 = -1;
5621 off_t filesize;
5622 int *pack_fds = NULL;
5623 FILE *f1 = NULL, *f2 = NULL;
5625 fd1 = got_opentempfd();
5626 if (fd1 == -1)
5627 return got_error_from_errno("got_opentempfd");
5629 memset(&bca, 0, sizeof(bca));
5631 #ifndef PROFILE
5632 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
5633 NULL) == -1)
5634 err(1, "pledge");
5635 #endif
5637 while ((ch = getopt(argc, argv, "c:r:")) != -1) {
5638 switch (ch) {
5639 case 'c':
5640 commit_id_str = optarg;
5641 break;
5642 case 'r':
5643 repo_path = realpath(optarg, NULL);
5644 if (repo_path == NULL)
5645 return got_error_from_errno2("realpath",
5646 optarg);
5647 got_path_strip_trailing_slashes(repo_path);
5648 break;
5649 default:
5650 usage_blame();
5651 /* NOTREACHED */
5655 argc -= optind;
5656 argv += optind;
5658 if (argc == 1)
5659 path = argv[0];
5660 else
5661 usage_blame();
5663 cwd = getcwd(NULL, 0);
5664 if (cwd == NULL) {
5665 error = got_error_from_errno("getcwd");
5666 goto done;
5669 error = got_repo_pack_fds_open(&pack_fds);
5670 if (error != NULL)
5671 goto done;
5673 if (repo_path == NULL) {
5674 error = got_worktree_open(&worktree, cwd);
5675 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5676 goto done;
5677 else
5678 error = NULL;
5679 if (worktree) {
5680 repo_path =
5681 strdup(got_worktree_get_repo_path(worktree));
5682 if (repo_path == NULL) {
5683 error = got_error_from_errno("strdup");
5684 if (error)
5685 goto done;
5687 } else {
5688 repo_path = strdup(cwd);
5689 if (repo_path == NULL) {
5690 error = got_error_from_errno("strdup");
5691 goto done;
5696 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
5697 if (error != NULL)
5698 goto done;
5700 if (worktree) {
5701 const char *prefix = got_worktree_get_path_prefix(worktree);
5702 char *p;
5704 error = got_worktree_resolve_path(&p, worktree, path);
5705 if (error)
5706 goto done;
5707 if (asprintf(&in_repo_path, "%s%s%s", prefix,
5708 (p[0] != '\0' && !got_path_is_root_dir(prefix)) ? "/" : "",
5709 p) == -1) {
5710 error = got_error_from_errno("asprintf");
5711 free(p);
5712 goto done;
5714 free(p);
5715 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5716 } else {
5717 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5718 if (error)
5719 goto done;
5720 error = got_repo_map_path(&in_repo_path, repo, path);
5722 if (error)
5723 goto done;
5725 if (commit_id_str == NULL) {
5726 struct got_reference *head_ref;
5727 error = got_ref_open(&head_ref, repo, worktree ?
5728 got_worktree_get_head_ref_name(worktree) : GOT_REF_HEAD, 0);
5729 if (error != NULL)
5730 goto done;
5731 error = got_ref_resolve(&commit_id, repo, head_ref);
5732 got_ref_close(head_ref);
5733 if (error != NULL)
5734 goto done;
5735 } else {
5736 struct got_reflist_head refs;
5737 TAILQ_INIT(&refs);
5738 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
5739 NULL);
5740 if (error)
5741 goto done;
5742 error = got_repo_match_object_id(&commit_id, NULL,
5743 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
5744 got_ref_list_free(&refs);
5745 if (error)
5746 goto done;
5749 if (worktree) {
5750 /* Release work tree lock. */
5751 got_worktree_close(worktree);
5752 worktree = NULL;
5755 error = got_object_open_as_commit(&commit, repo, commit_id);
5756 if (error)
5757 goto done;
5759 error = got_object_resolve_symlinks(&link_target, in_repo_path,
5760 commit, repo);
5761 if (error)
5762 goto done;
5764 error = got_object_id_by_path(&obj_id, repo, commit,
5765 link_target ? link_target : in_repo_path);
5766 if (error)
5767 goto done;
5769 error = got_object_get_type(&obj_type, repo, obj_id);
5770 if (error)
5771 goto done;
5773 if (obj_type != GOT_OBJ_TYPE_BLOB) {
5774 error = got_error_path(link_target ? link_target : in_repo_path,
5775 GOT_ERR_OBJ_TYPE);
5776 goto done;
5779 error = got_object_open_as_blob(&blob, repo, obj_id, 8192, fd1);
5780 if (error)
5781 goto done;
5782 bca.f = got_opentemp();
5783 if (bca.f == NULL) {
5784 error = got_error_from_errno("got_opentemp");
5785 goto done;
5787 error = got_object_blob_dump_to_file(&filesize, &bca.nlines,
5788 &bca.line_offsets, bca.f, blob);
5789 if (error || bca.nlines == 0)
5790 goto done;
5792 /* Don't include \n at EOF in the blame line count. */
5793 if (bca.line_offsets[bca.nlines - 1] == filesize)
5794 bca.nlines--;
5796 bca.lines = calloc(bca.nlines, sizeof(*bca.lines));
5797 if (bca.lines == NULL) {
5798 error = got_error_from_errno("calloc");
5799 goto done;
5801 bca.lineno_cur = 1;
5802 bca.nlines_prec = 0;
5803 i = bca.nlines;
5804 while (i > 0) {
5805 i /= 10;
5806 bca.nlines_prec++;
5808 bca.repo = repo;
5810 fd2 = got_opentempfd();
5811 if (fd2 == -1) {
5812 error = got_error_from_errno("got_opentempfd");
5813 goto done;
5815 fd3 = got_opentempfd();
5816 if (fd3 == -1) {
5817 error = got_error_from_errno("got_opentempfd");
5818 goto done;
5820 f1 = got_opentemp();
5821 if (f1 == NULL) {
5822 error = got_error_from_errno("got_opentemp");
5823 goto done;
5825 f2 = got_opentemp();
5826 if (f2 == NULL) {
5827 error = got_error_from_errno("got_opentemp");
5828 goto done;
5830 error = got_blame(link_target ? link_target : in_repo_path, commit_id,
5831 repo, GOT_DIFF_ALGORITHM_PATIENCE, blame_cb, &bca,
5832 check_cancelled, NULL, fd2, fd3, f1, f2);
5833 done:
5834 free(in_repo_path);
5835 free(link_target);
5836 free(repo_path);
5837 free(cwd);
5838 free(commit_id);
5839 free(obj_id);
5840 if (commit)
5841 got_object_commit_close(commit);
5843 if (fd1 != -1 && close(fd1) == -1 && error == NULL)
5844 error = got_error_from_errno("close");
5845 if (fd2 != -1 && close(fd2) == -1 && error == NULL)
5846 error = got_error_from_errno("close");
5847 if (fd3 != -1 && close(fd3) == -1 && error == NULL)
5848 error = got_error_from_errno("close");
5849 if (f1 && fclose(f1) == EOF && error == NULL)
5850 error = got_error_from_errno("fclose");
5851 if (f2 && fclose(f2) == EOF && error == NULL)
5852 error = got_error_from_errno("fclose");
5854 if (blob)
5855 got_object_blob_close(blob);
5856 if (worktree)
5857 got_worktree_close(worktree);
5858 if (repo) {
5859 const struct got_error *close_err = got_repo_close(repo);
5860 if (error == NULL)
5861 error = close_err;
5863 if (pack_fds) {
5864 const struct got_error *pack_err =
5865 got_repo_pack_fds_close(pack_fds);
5866 if (error == NULL)
5867 error = pack_err;
5869 if (bca.lines) {
5870 for (i = 0; i < bca.nlines; i++) {
5871 struct blame_line *bline = &bca.lines[i];
5872 free(bline->id_str);
5873 free(bline->committer);
5875 free(bca.lines);
5877 free(bca.line_offsets);
5878 if (bca.f && fclose(bca.f) == EOF && error == NULL)
5879 error = got_error_from_errno("fclose");
5880 return error;
5883 __dead static void
5884 usage_tree(void)
5886 fprintf(stderr, "usage: %s tree [-iR] [-c commit] [-r repository-path] "
5887 "[path]\n", getprogname());
5888 exit(1);
5891 static const struct got_error *
5892 print_entry(struct got_tree_entry *te, const char *id, const char *path,
5893 const char *root_path, struct got_repository *repo)
5895 const struct got_error *err = NULL;
5896 int is_root_path = (strcmp(path, root_path) == 0);
5897 const char *modestr = "";
5898 mode_t mode = got_tree_entry_get_mode(te);
5899 char *link_target = NULL;
5901 path += strlen(root_path);
5902 while (path[0] == '/')
5903 path++;
5905 if (got_object_tree_entry_is_submodule(te))
5906 modestr = "$";
5907 else if (S_ISLNK(mode)) {
5908 int i;
5910 err = got_tree_entry_get_symlink_target(&link_target, te, repo);
5911 if (err)
5912 return err;
5913 for (i = 0; i < strlen(link_target); i++) {
5914 if (!isprint((unsigned char)link_target[i]))
5915 link_target[i] = '?';
5918 modestr = "@";
5920 else if (S_ISDIR(mode))
5921 modestr = "/";
5922 else if (mode & S_IXUSR)
5923 modestr = "*";
5925 printf("%s%s%s%s%s%s%s\n", id ? id : "", path,
5926 is_root_path ? "" : "/", got_tree_entry_get_name(te), modestr,
5927 link_target ? " -> ": "", link_target ? link_target : "");
5929 free(link_target);
5930 return NULL;
5933 static const struct got_error *
5934 print_tree(const char *path, struct got_commit_object *commit,
5935 int show_ids, int recurse, const char *root_path,
5936 struct got_repository *repo)
5938 const struct got_error *err = NULL;
5939 struct got_object_id *tree_id = NULL;
5940 struct got_tree_object *tree = NULL;
5941 int nentries, i;
5943 err = got_object_id_by_path(&tree_id, repo, commit, path);
5944 if (err)
5945 goto done;
5947 err = got_object_open_as_tree(&tree, repo, tree_id);
5948 if (err)
5949 goto done;
5950 nentries = got_object_tree_get_nentries(tree);
5951 for (i = 0; i < nentries; i++) {
5952 struct got_tree_entry *te;
5953 char *id = NULL;
5955 if (sigint_received || sigpipe_received)
5956 break;
5958 te = got_object_tree_get_entry(tree, i);
5959 if (show_ids) {
5960 char *id_str;
5961 err = got_object_id_str(&id_str,
5962 got_tree_entry_get_id(te));
5963 if (err)
5964 goto done;
5965 if (asprintf(&id, "%s ", id_str) == -1) {
5966 err = got_error_from_errno("asprintf");
5967 free(id_str);
5968 goto done;
5970 free(id_str);
5972 err = print_entry(te, id, path, root_path, repo);
5973 free(id);
5974 if (err)
5975 goto done;
5977 if (recurse && S_ISDIR(got_tree_entry_get_mode(te))) {
5978 char *child_path;
5979 if (asprintf(&child_path, "%s%s%s", path,
5980 path[0] == '/' && path[1] == '\0' ? "" : "/",
5981 got_tree_entry_get_name(te)) == -1) {
5982 err = got_error_from_errno("asprintf");
5983 goto done;
5985 err = print_tree(child_path, commit, show_ids, 1,
5986 root_path, repo);
5987 free(child_path);
5988 if (err)
5989 goto done;
5992 done:
5993 if (tree)
5994 got_object_tree_close(tree);
5995 free(tree_id);
5996 return err;
5999 static const struct got_error *
6000 cmd_tree(int argc, char *argv[])
6002 const struct got_error *error;
6003 struct got_repository *repo = NULL;
6004 struct got_worktree *worktree = NULL;
6005 const char *path, *refname = NULL;
6006 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
6007 struct got_object_id *commit_id = NULL;
6008 struct got_commit_object *commit = NULL;
6009 char *commit_id_str = NULL;
6010 int show_ids = 0, recurse = 0;
6011 int ch;
6012 int *pack_fds = NULL;
6014 #ifndef PROFILE
6015 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
6016 NULL) == -1)
6017 err(1, "pledge");
6018 #endif
6020 while ((ch = getopt(argc, argv, "c:iRr:")) != -1) {
6021 switch (ch) {
6022 case 'c':
6023 commit_id_str = optarg;
6024 break;
6025 case 'i':
6026 show_ids = 1;
6027 break;
6028 case 'R':
6029 recurse = 1;
6030 break;
6031 case 'r':
6032 repo_path = realpath(optarg, NULL);
6033 if (repo_path == NULL)
6034 return got_error_from_errno2("realpath",
6035 optarg);
6036 got_path_strip_trailing_slashes(repo_path);
6037 break;
6038 default:
6039 usage_tree();
6040 /* NOTREACHED */
6044 argc -= optind;
6045 argv += optind;
6047 if (argc == 1)
6048 path = argv[0];
6049 else if (argc > 1)
6050 usage_tree();
6051 else
6052 path = NULL;
6054 cwd = getcwd(NULL, 0);
6055 if (cwd == NULL) {
6056 error = got_error_from_errno("getcwd");
6057 goto done;
6060 error = got_repo_pack_fds_open(&pack_fds);
6061 if (error != NULL)
6062 goto done;
6064 if (repo_path == NULL) {
6065 error = got_worktree_open(&worktree, cwd);
6066 if (error && error->code != GOT_ERR_NOT_WORKTREE)
6067 goto done;
6068 else
6069 error = NULL;
6070 if (worktree) {
6071 repo_path =
6072 strdup(got_worktree_get_repo_path(worktree));
6073 if (repo_path == NULL)
6074 error = got_error_from_errno("strdup");
6075 if (error)
6076 goto done;
6077 } else {
6078 repo_path = strdup(cwd);
6079 if (repo_path == NULL) {
6080 error = got_error_from_errno("strdup");
6081 goto done;
6086 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
6087 if (error != NULL)
6088 goto done;
6090 if (worktree) {
6091 const char *prefix = got_worktree_get_path_prefix(worktree);
6092 char *p;
6094 if (path == NULL)
6095 path = "";
6096 error = got_worktree_resolve_path(&p, worktree, path);
6097 if (error)
6098 goto done;
6099 if (asprintf(&in_repo_path, "%s%s%s", prefix,
6100 (p[0] != '\0' && !got_path_is_root_dir(prefix)) ? "/" : "",
6101 p) == -1) {
6102 error = got_error_from_errno("asprintf");
6103 free(p);
6104 goto done;
6106 free(p);
6107 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
6108 if (error)
6109 goto done;
6110 } else {
6111 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
6112 if (error)
6113 goto done;
6114 if (path == NULL)
6115 path = "/";
6116 error = got_repo_map_path(&in_repo_path, repo, path);
6117 if (error != NULL)
6118 goto done;
6121 if (commit_id_str == NULL) {
6122 struct got_reference *head_ref;
6123 if (worktree)
6124 refname = got_worktree_get_head_ref_name(worktree);
6125 else
6126 refname = GOT_REF_HEAD;
6127 error = got_ref_open(&head_ref, repo, refname, 0);
6128 if (error != NULL)
6129 goto done;
6130 error = got_ref_resolve(&commit_id, repo, head_ref);
6131 got_ref_close(head_ref);
6132 if (error != NULL)
6133 goto done;
6134 } else {
6135 struct got_reflist_head refs;
6136 TAILQ_INIT(&refs);
6137 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
6138 NULL);
6139 if (error)
6140 goto done;
6141 error = got_repo_match_object_id(&commit_id, NULL,
6142 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
6143 got_ref_list_free(&refs);
6144 if (error)
6145 goto done;
6148 if (worktree) {
6149 /* Release work tree lock. */
6150 got_worktree_close(worktree);
6151 worktree = NULL;
6154 error = got_object_open_as_commit(&commit, repo, commit_id);
6155 if (error)
6156 goto done;
6158 error = print_tree(in_repo_path, commit, show_ids, recurse,
6159 in_repo_path, repo);
6160 done:
6161 free(in_repo_path);
6162 free(repo_path);
6163 free(cwd);
6164 free(commit_id);
6165 if (commit)
6166 got_object_commit_close(commit);
6167 if (worktree)
6168 got_worktree_close(worktree);
6169 if (repo) {
6170 const struct got_error *close_err = got_repo_close(repo);
6171 if (error == NULL)
6172 error = close_err;
6174 if (pack_fds) {
6175 const struct got_error *pack_err =
6176 got_repo_pack_fds_close(pack_fds);
6177 if (error == NULL)
6178 error = pack_err;
6180 return error;
6183 __dead static void
6184 usage_status(void)
6186 fprintf(stderr, "usage: %s status [-I] [-S status-codes] "
6187 "[-s status-codes] [path ...]\n", getprogname());
6188 exit(1);
6191 struct got_status_arg {
6192 char *status_codes;
6193 int suppress;
6196 static const struct got_error *
6197 print_status(void *arg, unsigned char status, unsigned char staged_status,
6198 const char *path, struct got_object_id *blob_id,
6199 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
6200 int dirfd, const char *de_name)
6202 struct got_status_arg *st = arg;
6204 if (status == staged_status && (status == GOT_STATUS_DELETE))
6205 status = GOT_STATUS_NO_CHANGE;
6206 if (st != NULL && st->status_codes) {
6207 size_t ncodes = strlen(st->status_codes);
6208 int i, j = 0;
6210 for (i = 0; i < ncodes ; i++) {
6211 if (st->suppress) {
6212 if (status == st->status_codes[i] ||
6213 staged_status == st->status_codes[i]) {
6214 j++;
6215 continue;
6217 } else {
6218 if (status == st->status_codes[i] ||
6219 staged_status == st->status_codes[i])
6220 break;
6224 if (st->suppress && j == 0)
6225 goto print;
6227 if (i == ncodes)
6228 return NULL;
6230 print:
6231 printf("%c%c %s\n", status, staged_status, path);
6232 return NULL;
6235 static const struct got_error *
6236 cmd_status(int argc, char *argv[])
6238 const struct got_error *error = NULL;
6239 struct got_repository *repo = NULL;
6240 struct got_worktree *worktree = NULL;
6241 struct got_status_arg st;
6242 char *cwd = NULL;
6243 struct got_pathlist_head paths;
6244 int ch, i, no_ignores = 0;
6245 int *pack_fds = NULL;
6247 TAILQ_INIT(&paths);
6249 memset(&st, 0, sizeof(st));
6250 st.status_codes = NULL;
6251 st.suppress = 0;
6253 while ((ch = getopt(argc, argv, "IS:s:")) != -1) {
6254 switch (ch) {
6255 case 'I':
6256 no_ignores = 1;
6257 break;
6258 case 'S':
6259 if (st.status_codes != NULL && st.suppress == 0)
6260 option_conflict('S', 's');
6261 st.suppress = 1;
6262 /* fallthrough */
6263 case 's':
6264 for (i = 0; i < strlen(optarg); i++) {
6265 switch (optarg[i]) {
6266 case GOT_STATUS_MODIFY:
6267 case GOT_STATUS_ADD:
6268 case GOT_STATUS_DELETE:
6269 case GOT_STATUS_CONFLICT:
6270 case GOT_STATUS_MISSING:
6271 case GOT_STATUS_OBSTRUCTED:
6272 case GOT_STATUS_UNVERSIONED:
6273 case GOT_STATUS_MODE_CHANGE:
6274 case GOT_STATUS_NONEXISTENT:
6275 break;
6276 default:
6277 errx(1, "invalid status code '%c'",
6278 optarg[i]);
6281 if (ch == 's' && st.suppress)
6282 option_conflict('s', 'S');
6283 st.status_codes = optarg;
6284 break;
6285 default:
6286 usage_status();
6287 /* NOTREACHED */
6291 argc -= optind;
6292 argv += optind;
6294 #ifndef PROFILE
6295 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
6296 NULL) == -1)
6297 err(1, "pledge");
6298 #endif
6299 cwd = getcwd(NULL, 0);
6300 if (cwd == NULL) {
6301 error = got_error_from_errno("getcwd");
6302 goto done;
6305 error = got_repo_pack_fds_open(&pack_fds);
6306 if (error != NULL)
6307 goto done;
6309 error = got_worktree_open(&worktree, cwd);
6310 if (error) {
6311 if (error->code == GOT_ERR_NOT_WORKTREE)
6312 error = wrap_not_worktree_error(error, "status", cwd);
6313 goto done;
6316 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
6317 NULL, pack_fds);
6318 if (error != NULL)
6319 goto done;
6321 error = apply_unveil(got_repo_get_path(repo), 1,
6322 got_worktree_get_root_path(worktree));
6323 if (error)
6324 goto done;
6326 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
6327 if (error)
6328 goto done;
6330 error = got_worktree_status(worktree, &paths, repo, no_ignores,
6331 print_status, &st, check_cancelled, NULL);
6332 done:
6333 if (pack_fds) {
6334 const struct got_error *pack_err =
6335 got_repo_pack_fds_close(pack_fds);
6336 if (error == NULL)
6337 error = pack_err;
6340 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
6341 free(cwd);
6342 return error;
6345 __dead static void
6346 usage_ref(void)
6348 fprintf(stderr, "usage: %s ref [-dlt] [-c object] [-r repository-path] "
6349 "[-s reference] [name]\n", getprogname());
6350 exit(1);
6353 static const struct got_error *
6354 list_refs(struct got_repository *repo, const char *refname, int sort_by_time)
6356 static const struct got_error *err = NULL;
6357 struct got_reflist_head refs;
6358 struct got_reflist_entry *re;
6360 TAILQ_INIT(&refs);
6361 err = got_ref_list(&refs, repo, refname, sort_by_time ?
6362 got_ref_cmp_by_commit_timestamp_descending : got_ref_cmp_by_name,
6363 repo);
6364 if (err)
6365 return err;
6367 TAILQ_FOREACH(re, &refs, entry) {
6368 char *refstr;
6369 refstr = got_ref_to_str(re->ref);
6370 if (refstr == NULL) {
6371 err = got_error_from_errno("got_ref_to_str");
6372 break;
6374 printf("%s: %s\n", got_ref_get_name(re->ref), refstr);
6375 free(refstr);
6378 got_ref_list_free(&refs);
6379 return err;
6382 static const struct got_error *
6383 delete_ref_by_name(struct got_repository *repo, const char *refname)
6385 const struct got_error *err;
6386 struct got_reference *ref;
6388 err = got_ref_open(&ref, repo, refname, 0);
6389 if (err)
6390 return err;
6392 err = delete_ref(repo, ref);
6393 got_ref_close(ref);
6394 return err;
6397 static const struct got_error *
6398 add_ref(struct got_repository *repo, const char *refname, const char *target)
6400 const struct got_error *err = NULL;
6401 struct got_object_id *id = NULL;
6402 struct got_reference *ref = NULL;
6403 struct got_reflist_head refs;
6406 * Don't let the user create a reference name with a leading '-'.
6407 * While technically a valid reference name, this case is usually
6408 * an unintended typo.
6410 if (refname[0] == '-')
6411 return got_error_path(refname, GOT_ERR_REF_NAME_MINUS);
6413 TAILQ_INIT(&refs);
6414 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
6415 if (err)
6416 goto done;
6417 err = got_repo_match_object_id(&id, NULL, target, GOT_OBJ_TYPE_ANY,
6418 &refs, repo);
6419 got_ref_list_free(&refs);
6420 if (err)
6421 goto done;
6423 err = got_ref_alloc(&ref, refname, id);
6424 if (err)
6425 goto done;
6427 err = got_ref_write(ref, repo);
6428 done:
6429 if (ref)
6430 got_ref_close(ref);
6431 free(id);
6432 return err;
6435 static const struct got_error *
6436 add_symref(struct got_repository *repo, const char *refname, const char *target)
6438 const struct got_error *err = NULL;
6439 struct got_reference *ref = NULL;
6440 struct got_reference *target_ref = NULL;
6443 * Don't let the user create a reference name with a leading '-'.
6444 * While technically a valid reference name, this case is usually
6445 * an unintended typo.
6447 if (refname[0] == '-')
6448 return got_error_path(refname, GOT_ERR_REF_NAME_MINUS);
6450 err = got_ref_open(&target_ref, repo, target, 0);
6451 if (err)
6452 return err;
6454 err = got_ref_alloc_symref(&ref, refname, target_ref);
6455 if (err)
6456 goto done;
6458 err = got_ref_write(ref, repo);
6459 done:
6460 if (target_ref)
6461 got_ref_close(target_ref);
6462 if (ref)
6463 got_ref_close(ref);
6464 return err;
6467 static const struct got_error *
6468 cmd_ref(int argc, char *argv[])
6470 const struct got_error *error = NULL;
6471 struct got_repository *repo = NULL;
6472 struct got_worktree *worktree = NULL;
6473 char *cwd = NULL, *repo_path = NULL;
6474 int ch, do_list = 0, do_delete = 0, sort_by_time = 0;
6475 const char *obj_arg = NULL, *symref_target= NULL;
6476 char *refname = NULL;
6477 int *pack_fds = NULL;
6479 while ((ch = getopt(argc, argv, "c:dlr:s:t")) != -1) {
6480 switch (ch) {
6481 case 'c':
6482 obj_arg = optarg;
6483 break;
6484 case 'd':
6485 do_delete = 1;
6486 break;
6487 case 'l':
6488 do_list = 1;
6489 break;
6490 case 'r':
6491 repo_path = realpath(optarg, NULL);
6492 if (repo_path == NULL)
6493 return got_error_from_errno2("realpath",
6494 optarg);
6495 got_path_strip_trailing_slashes(repo_path);
6496 break;
6497 case 's':
6498 symref_target = optarg;
6499 break;
6500 case 't':
6501 sort_by_time = 1;
6502 break;
6503 default:
6504 usage_ref();
6505 /* NOTREACHED */
6509 if (obj_arg && do_list)
6510 option_conflict('c', 'l');
6511 if (obj_arg && do_delete)
6512 option_conflict('c', 'd');
6513 if (obj_arg && symref_target)
6514 option_conflict('c', 's');
6515 if (symref_target && do_delete)
6516 option_conflict('s', 'd');
6517 if (symref_target && do_list)
6518 option_conflict('s', 'l');
6519 if (do_delete && do_list)
6520 option_conflict('d', 'l');
6521 if (sort_by_time && !do_list)
6522 errx(1, "-t option requires -l option");
6524 argc -= optind;
6525 argv += optind;
6527 if (do_list) {
6528 if (argc != 0 && argc != 1)
6529 usage_ref();
6530 if (argc == 1) {
6531 refname = strdup(argv[0]);
6532 if (refname == NULL) {
6533 error = got_error_from_errno("strdup");
6534 goto done;
6537 } else {
6538 if (argc != 1)
6539 usage_ref();
6540 refname = strdup(argv[0]);
6541 if (refname == NULL) {
6542 error = got_error_from_errno("strdup");
6543 goto done;
6547 if (refname)
6548 got_path_strip_trailing_slashes(refname);
6550 #ifndef PROFILE
6551 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
6552 "sendfd unveil", NULL) == -1)
6553 err(1, "pledge");
6554 #endif
6555 cwd = getcwd(NULL, 0);
6556 if (cwd == NULL) {
6557 error = got_error_from_errno("getcwd");
6558 goto done;
6561 error = got_repo_pack_fds_open(&pack_fds);
6562 if (error != NULL)
6563 goto done;
6565 if (repo_path == NULL) {
6566 error = got_worktree_open(&worktree, cwd);
6567 if (error && error->code != GOT_ERR_NOT_WORKTREE)
6568 goto done;
6569 else
6570 error = NULL;
6571 if (worktree) {
6572 repo_path =
6573 strdup(got_worktree_get_repo_path(worktree));
6574 if (repo_path == NULL)
6575 error = got_error_from_errno("strdup");
6576 if (error)
6577 goto done;
6578 } else {
6579 repo_path = strdup(cwd);
6580 if (repo_path == NULL) {
6581 error = got_error_from_errno("strdup");
6582 goto done;
6587 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
6588 if (error != NULL)
6589 goto done;
6591 #ifndef PROFILE
6592 if (do_list) {
6593 /* Remove "cpath" promise. */
6594 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
6595 NULL) == -1)
6596 err(1, "pledge");
6598 #endif
6600 error = apply_unveil(got_repo_get_path(repo), do_list,
6601 worktree ? got_worktree_get_root_path(worktree) : NULL);
6602 if (error)
6603 goto done;
6605 if (do_list)
6606 error = list_refs(repo, refname, sort_by_time);
6607 else if (do_delete)
6608 error = delete_ref_by_name(repo, refname);
6609 else if (symref_target)
6610 error = add_symref(repo, refname, symref_target);
6611 else {
6612 if (obj_arg == NULL)
6613 usage_ref();
6614 error = add_ref(repo, refname, obj_arg);
6616 done:
6617 free(refname);
6618 if (repo) {
6619 const struct got_error *close_err = got_repo_close(repo);
6620 if (error == NULL)
6621 error = close_err;
6623 if (worktree)
6624 got_worktree_close(worktree);
6625 if (pack_fds) {
6626 const struct got_error *pack_err =
6627 got_repo_pack_fds_close(pack_fds);
6628 if (error == NULL)
6629 error = pack_err;
6631 free(cwd);
6632 free(repo_path);
6633 return error;
6636 __dead static void
6637 usage_branch(void)
6639 fprintf(stderr, "usage: %s branch [-lnt] [-c commit] [-d name] "
6640 "[-r repository-path] [name]\n", getprogname());
6641 exit(1);
6644 static const struct got_error *
6645 list_branch(struct got_repository *repo, struct got_worktree *worktree,
6646 struct got_reference *ref)
6648 const struct got_error *err = NULL;
6649 const char *refname, *marker = " ";
6650 char *refstr;
6652 refname = got_ref_get_name(ref);
6653 if (worktree && strcmp(refname,
6654 got_worktree_get_head_ref_name(worktree)) == 0) {
6655 struct got_object_id *id = NULL;
6657 err = got_ref_resolve(&id, repo, ref);
6658 if (err)
6659 return err;
6660 if (got_object_id_cmp(id,
6661 got_worktree_get_base_commit_id(worktree)) == 0)
6662 marker = "* ";
6663 else
6664 marker = "~ ";
6665 free(id);
6668 if (strncmp(refname, "refs/heads/", 11) == 0)
6669 refname += 11;
6670 if (strncmp(refname, "refs/got/worktree/", 18) == 0)
6671 refname += 18;
6672 if (strncmp(refname, "refs/remotes/", 13) == 0)
6673 refname += 13;
6675 refstr = got_ref_to_str(ref);
6676 if (refstr == NULL)
6677 return got_error_from_errno("got_ref_to_str");
6679 printf("%s%s: %s\n", marker, refname, refstr);
6680 free(refstr);
6681 return NULL;
6684 static const struct got_error *
6685 show_current_branch(struct got_repository *repo, struct got_worktree *worktree)
6687 const char *refname;
6689 if (worktree == NULL)
6690 return got_error(GOT_ERR_NOT_WORKTREE);
6692 refname = got_worktree_get_head_ref_name(worktree);
6694 if (strncmp(refname, "refs/heads/", 11) == 0)
6695 refname += 11;
6696 if (strncmp(refname, "refs/got/worktree/", 18) == 0)
6697 refname += 18;
6699 printf("%s\n", refname);
6701 return NULL;
6704 static const struct got_error *
6705 list_branches(struct got_repository *repo, struct got_worktree *worktree,
6706 int sort_by_time)
6708 static const struct got_error *err = NULL;
6709 struct got_reflist_head refs;
6710 struct got_reflist_entry *re;
6711 struct got_reference *temp_ref = NULL;
6712 int rebase_in_progress, histedit_in_progress;
6714 TAILQ_INIT(&refs);
6716 if (worktree) {
6717 err = got_worktree_rebase_in_progress(&rebase_in_progress,
6718 worktree);
6719 if (err)
6720 return err;
6722 err = got_worktree_histedit_in_progress(&histedit_in_progress,
6723 worktree);
6724 if (err)
6725 return err;
6727 if (rebase_in_progress || histedit_in_progress) {
6728 err = got_ref_open(&temp_ref, repo,
6729 got_worktree_get_head_ref_name(worktree), 0);
6730 if (err)
6731 return err;
6732 list_branch(repo, worktree, temp_ref);
6733 got_ref_close(temp_ref);
6737 err = got_ref_list(&refs, repo, "refs/heads", sort_by_time ?
6738 got_ref_cmp_by_commit_timestamp_descending : got_ref_cmp_by_name,
6739 repo);
6740 if (err)
6741 return err;
6743 TAILQ_FOREACH(re, &refs, entry)
6744 list_branch(repo, worktree, re->ref);
6746 got_ref_list_free(&refs);
6748 err = got_ref_list(&refs, repo, "refs/remotes", sort_by_time ?
6749 got_ref_cmp_by_commit_timestamp_descending : got_ref_cmp_by_name,
6750 repo);
6751 if (err)
6752 return err;
6754 TAILQ_FOREACH(re, &refs, entry)
6755 list_branch(repo, worktree, re->ref);
6757 got_ref_list_free(&refs);
6759 return NULL;
6762 static const struct got_error *
6763 delete_branch(struct got_repository *repo, struct got_worktree *worktree,
6764 const char *branch_name)
6766 const struct got_error *err = NULL;
6767 struct got_reference *ref = NULL;
6768 char *refname, *remote_refname = NULL;
6770 if (strncmp(branch_name, "refs/", 5) == 0)
6771 branch_name += 5;
6772 if (strncmp(branch_name, "heads/", 6) == 0)
6773 branch_name += 6;
6774 else if (strncmp(branch_name, "remotes/", 8) == 0)
6775 branch_name += 8;
6777 if (asprintf(&refname, "refs/heads/%s", branch_name) == -1)
6778 return got_error_from_errno("asprintf");
6780 if (asprintf(&remote_refname, "refs/remotes/%s",
6781 branch_name) == -1) {
6782 err = got_error_from_errno("asprintf");
6783 goto done;
6786 err = got_ref_open(&ref, repo, refname, 0);
6787 if (err) {
6788 const struct got_error *err2;
6789 if (err->code != GOT_ERR_NOT_REF)
6790 goto done;
6792 * Keep 'err' intact such that if neither branch exists
6793 * we report "refs/heads" rather than "refs/remotes" in
6794 * our error message.
6796 err2 = got_ref_open(&ref, repo, remote_refname, 0);
6797 if (err2)
6798 goto done;
6799 err = NULL;
6802 if (worktree &&
6803 strcmp(got_worktree_get_head_ref_name(worktree),
6804 got_ref_get_name(ref)) == 0) {
6805 err = got_error_msg(GOT_ERR_SAME_BRANCH,
6806 "will not delete this work tree's current branch");
6807 goto done;
6810 err = delete_ref(repo, ref);
6811 done:
6812 if (ref)
6813 got_ref_close(ref);
6814 free(refname);
6815 free(remote_refname);
6816 return err;
6819 static const struct got_error *
6820 add_branch(struct got_repository *repo, const char *branch_name,
6821 struct got_object_id *base_commit_id)
6823 const struct got_error *err = NULL;
6824 struct got_reference *ref = NULL;
6825 char *refname = NULL;
6828 * Don't let the user create a branch name with a leading '-'.
6829 * While technically a valid reference name, this case is usually
6830 * an unintended typo.
6832 if (branch_name[0] == '-')
6833 return got_error_path(branch_name, GOT_ERR_REF_NAME_MINUS);
6835 if (strncmp(branch_name, "refs/heads/", 11) == 0)
6836 branch_name += 11;
6838 if (asprintf(&refname, "refs/heads/%s", branch_name) == -1) {
6839 err = got_error_from_errno("asprintf");
6840 goto done;
6843 err = got_ref_open(&ref, repo, refname, 0);
6844 if (err == NULL) {
6845 err = got_error(GOT_ERR_BRANCH_EXISTS);
6846 goto done;
6847 } else if (err->code != GOT_ERR_NOT_REF)
6848 goto done;
6850 err = got_ref_alloc(&ref, refname, base_commit_id);
6851 if (err)
6852 goto done;
6854 err = got_ref_write(ref, repo);
6855 done:
6856 if (ref)
6857 got_ref_close(ref);
6858 free(refname);
6859 return err;
6862 static const struct got_error *
6863 cmd_branch(int argc, char *argv[])
6865 const struct got_error *error = NULL;
6866 struct got_repository *repo = NULL;
6867 struct got_worktree *worktree = NULL;
6868 char *cwd = NULL, *repo_path = NULL;
6869 int ch, do_list = 0, do_show = 0, do_update = 1, sort_by_time = 0;
6870 const char *delref = NULL, *commit_id_arg = NULL;
6871 struct got_reference *ref = NULL;
6872 struct got_pathlist_head paths;
6873 struct got_object_id *commit_id = NULL;
6874 char *commit_id_str = NULL;
6875 int *pack_fds = NULL;
6877 TAILQ_INIT(&paths);
6879 while ((ch = getopt(argc, argv, "c:d:lnr:t")) != -1) {
6880 switch (ch) {
6881 case 'c':
6882 commit_id_arg = optarg;
6883 break;
6884 case 'd':
6885 delref = optarg;
6886 break;
6887 case 'l':
6888 do_list = 1;
6889 break;
6890 case 'n':
6891 do_update = 0;
6892 break;
6893 case 'r':
6894 repo_path = realpath(optarg, NULL);
6895 if (repo_path == NULL)
6896 return got_error_from_errno2("realpath",
6897 optarg);
6898 got_path_strip_trailing_slashes(repo_path);
6899 break;
6900 case 't':
6901 sort_by_time = 1;
6902 break;
6903 default:
6904 usage_branch();
6905 /* NOTREACHED */
6909 if (do_list && delref)
6910 option_conflict('l', 'd');
6911 if (sort_by_time && !do_list)
6912 errx(1, "-t option requires -l option");
6914 argc -= optind;
6915 argv += optind;
6917 if (!do_list && !delref && argc == 0)
6918 do_show = 1;
6920 if ((do_list || delref || do_show) && commit_id_arg != NULL)
6921 errx(1, "-c option can only be used when creating a branch");
6923 if (do_list || delref) {
6924 if (argc > 0)
6925 usage_branch();
6926 } else if (!do_show && argc != 1)
6927 usage_branch();
6929 #ifndef PROFILE
6930 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
6931 "sendfd unveil", NULL) == -1)
6932 err(1, "pledge");
6933 #endif
6934 cwd = getcwd(NULL, 0);
6935 if (cwd == NULL) {
6936 error = got_error_from_errno("getcwd");
6937 goto done;
6940 error = got_repo_pack_fds_open(&pack_fds);
6941 if (error != NULL)
6942 goto done;
6944 if (repo_path == NULL) {
6945 error = got_worktree_open(&worktree, cwd);
6946 if (error && error->code != GOT_ERR_NOT_WORKTREE)
6947 goto done;
6948 else
6949 error = NULL;
6950 if (worktree) {
6951 repo_path =
6952 strdup(got_worktree_get_repo_path(worktree));
6953 if (repo_path == NULL)
6954 error = got_error_from_errno("strdup");
6955 if (error)
6956 goto done;
6957 } else {
6958 repo_path = strdup(cwd);
6959 if (repo_path == NULL) {
6960 error = got_error_from_errno("strdup");
6961 goto done;
6966 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
6967 if (error != NULL)
6968 goto done;
6970 #ifndef PROFILE
6971 if (do_list || do_show) {
6972 /* Remove "cpath" promise. */
6973 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
6974 NULL) == -1)
6975 err(1, "pledge");
6977 #endif
6979 error = apply_unveil(got_repo_get_path(repo), do_list,
6980 worktree ? got_worktree_get_root_path(worktree) : NULL);
6981 if (error)
6982 goto done;
6984 if (do_show)
6985 error = show_current_branch(repo, worktree);
6986 else if (do_list)
6987 error = list_branches(repo, worktree, sort_by_time);
6988 else if (delref)
6989 error = delete_branch(repo, worktree, delref);
6990 else {
6991 struct got_reflist_head refs;
6992 TAILQ_INIT(&refs);
6993 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
6994 NULL);
6995 if (error)
6996 goto done;
6997 if (commit_id_arg == NULL)
6998 commit_id_arg = worktree ?
6999 got_worktree_get_head_ref_name(worktree) :
7000 GOT_REF_HEAD;
7001 error = got_repo_match_object_id(&commit_id, NULL,
7002 commit_id_arg, GOT_OBJ_TYPE_COMMIT, &refs, repo);
7003 got_ref_list_free(&refs);
7004 if (error)
7005 goto done;
7006 error = add_branch(repo, argv[0], commit_id);
7007 if (error)
7008 goto done;
7009 if (worktree && do_update) {
7010 struct got_update_progress_arg upa;
7011 char *branch_refname = NULL;
7013 error = got_object_id_str(&commit_id_str, commit_id);
7014 if (error)
7015 goto done;
7016 error = get_worktree_paths_from_argv(&paths, 0, NULL,
7017 worktree);
7018 if (error)
7019 goto done;
7020 if (asprintf(&branch_refname, "refs/heads/%s", argv[0])
7021 == -1) {
7022 error = got_error_from_errno("asprintf");
7023 goto done;
7025 error = got_ref_open(&ref, repo, branch_refname, 0);
7026 free(branch_refname);
7027 if (error)
7028 goto done;
7029 error = switch_head_ref(ref, commit_id, worktree,
7030 repo);
7031 if (error)
7032 goto done;
7033 error = got_worktree_set_base_commit_id(worktree, repo,
7034 commit_id);
7035 if (error)
7036 goto done;
7037 memset(&upa, 0, sizeof(upa));
7038 error = got_worktree_checkout_files(worktree, &paths,
7039 repo, update_progress, &upa, check_cancelled,
7040 NULL);
7041 if (error)
7042 goto done;
7043 if (upa.did_something) {
7044 printf("Updated to %s: %s\n",
7045 got_worktree_get_head_ref_name(worktree),
7046 commit_id_str);
7048 print_update_progress_stats(&upa);
7051 done:
7052 if (ref)
7053 got_ref_close(ref);
7054 if (repo) {
7055 const struct got_error *close_err = got_repo_close(repo);
7056 if (error == NULL)
7057 error = close_err;
7059 if (worktree)
7060 got_worktree_close(worktree);
7061 if (pack_fds) {
7062 const struct got_error *pack_err =
7063 got_repo_pack_fds_close(pack_fds);
7064 if (error == NULL)
7065 error = pack_err;
7067 free(cwd);
7068 free(repo_path);
7069 free(commit_id);
7070 free(commit_id_str);
7071 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
7072 return error;
7076 __dead static void
7077 usage_tag(void)
7079 fprintf(stderr, "usage: %s tag [-lVv] [-c commit] [-m message] "
7080 "[-r repository-path] [-s signer-id] name\n", getprogname());
7081 exit(1);
7084 #if 0
7085 static const struct got_error *
7086 sort_tags(struct got_reflist_head *sorted, struct got_reflist_head *tags)
7088 const struct got_error *err = NULL;
7089 struct got_reflist_entry *re, *se, *new;
7090 struct got_object_id *re_id, *se_id;
7091 struct got_tag_object *re_tag, *se_tag;
7092 time_t re_time, se_time;
7094 STAILQ_FOREACH(re, tags, entry) {
7095 se = STAILQ_FIRST(sorted);
7096 if (se == NULL) {
7097 err = got_reflist_entry_dup(&new, re);
7098 if (err)
7099 return err;
7100 STAILQ_INSERT_HEAD(sorted, new, entry);
7101 continue;
7102 } else {
7103 err = got_ref_resolve(&re_id, repo, re->ref);
7104 if (err)
7105 break;
7106 err = got_object_open_as_tag(&re_tag, repo, re_id);
7107 free(re_id);
7108 if (err)
7109 break;
7110 re_time = got_object_tag_get_tagger_time(re_tag);
7111 got_object_tag_close(re_tag);
7114 while (se) {
7115 err = got_ref_resolve(&se_id, repo, re->ref);
7116 if (err)
7117 break;
7118 err = got_object_open_as_tag(&se_tag, repo, se_id);
7119 free(se_id);
7120 if (err)
7121 break;
7122 se_time = got_object_tag_get_tagger_time(se_tag);
7123 got_object_tag_close(se_tag);
7125 if (se_time > re_time) {
7126 err = got_reflist_entry_dup(&new, re);
7127 if (err)
7128 return err;
7129 STAILQ_INSERT_AFTER(sorted, se, new, entry);
7130 break;
7132 se = STAILQ_NEXT(se, entry);
7133 continue;
7136 done:
7137 return err;
7139 #endif
7141 static const struct got_error *
7142 get_tag_refname(char **refname, const char *tag_name)
7144 const struct got_error *err;
7146 if (strncmp("refs/tags/", tag_name, 10) == 0) {
7147 *refname = strdup(tag_name);
7148 if (*refname == NULL)
7149 return got_error_from_errno("strdup");
7150 } else if (asprintf(refname, "refs/tags/%s", tag_name) == -1) {
7151 err = got_error_from_errno("asprintf");
7152 *refname = NULL;
7153 return err;
7156 return NULL;
7159 static const struct got_error *
7160 list_tags(struct got_repository *repo, const char *tag_name, int verify_tags,
7161 const char *allowed_signers, const char *revoked_signers, int verbosity)
7163 static const struct got_error *err = NULL;
7164 struct got_reflist_head refs;
7165 struct got_reflist_entry *re;
7166 char *wanted_refname = NULL;
7167 int bad_sigs = 0;
7169 TAILQ_INIT(&refs);
7171 err = got_ref_list(&refs, repo, "refs/tags", got_ref_cmp_tags, repo);
7172 if (err)
7173 return err;
7175 if (tag_name) {
7176 struct got_reference *ref;
7177 err = get_tag_refname(&wanted_refname, tag_name);
7178 if (err)
7179 goto done;
7180 /* Wanted tag reference should exist. */
7181 err = got_ref_open(&ref, repo, wanted_refname, 0);
7182 if (err)
7183 goto done;
7184 got_ref_close(ref);
7187 TAILQ_FOREACH(re, &refs, entry) {
7188 const char *refname;
7189 char *refstr, *tagmsg0, *tagmsg, *line, *id_str, *datestr;
7190 char datebuf[26];
7191 const char *tagger, *ssh_sig = NULL;
7192 char *sig_msg = NULL;
7193 time_t tagger_time;
7194 struct got_object_id *id;
7195 struct got_tag_object *tag;
7196 struct got_commit_object *commit = NULL;
7198 refname = got_ref_get_name(re->ref);
7199 if (strncmp(refname, "refs/tags/", 10) != 0 ||
7200 (wanted_refname && strcmp(refname, wanted_refname) != 0))
7201 continue;
7202 refname += 10;
7203 refstr = got_ref_to_str(re->ref);
7204 if (refstr == NULL) {
7205 err = got_error_from_errno("got_ref_to_str");
7206 break;
7209 err = got_ref_resolve(&id, repo, re->ref);
7210 if (err)
7211 break;
7212 err = got_object_open_as_tag(&tag, repo, id);
7213 if (err) {
7214 if (err->code != GOT_ERR_OBJ_TYPE) {
7215 free(id);
7216 break;
7218 /* "lightweight" tag */
7219 err = got_object_open_as_commit(&commit, repo, id);
7220 if (err) {
7221 free(id);
7222 break;
7224 tagger = got_object_commit_get_committer(commit);
7225 tagger_time =
7226 got_object_commit_get_committer_time(commit);
7227 err = got_object_id_str(&id_str, id);
7228 free(id);
7229 if (err)
7230 break;
7231 } else {
7232 free(id);
7233 tagger = got_object_tag_get_tagger(tag);
7234 tagger_time = got_object_tag_get_tagger_time(tag);
7235 err = got_object_id_str(&id_str,
7236 got_object_tag_get_object_id(tag));
7237 if (err)
7238 break;
7241 if (tag && verify_tags) {
7242 ssh_sig = got_sigs_get_tagmsg_ssh_signature(
7243 got_object_tag_get_message(tag));
7244 if (ssh_sig && allowed_signers == NULL) {
7245 err = got_error_msg(
7246 GOT_ERR_VERIFY_TAG_SIGNATURE,
7247 "SSH signature verification requires "
7248 "setting allowed_signers in "
7249 "got.conf(5)");
7250 break;
7254 printf("%stag %s %s\n", GOT_COMMIT_SEP_STR, refname, refstr);
7255 free(refstr);
7256 printf("from: %s\n", tagger);
7257 datestr = get_datestr(&tagger_time, datebuf);
7258 if (datestr)
7259 printf("date: %s UTC\n", datestr);
7260 if (commit)
7261 printf("object: %s %s\n", GOT_OBJ_LABEL_COMMIT, id_str);
7262 else {
7263 switch (got_object_tag_get_object_type(tag)) {
7264 case GOT_OBJ_TYPE_BLOB:
7265 printf("object: %s %s\n", GOT_OBJ_LABEL_BLOB,
7266 id_str);
7267 break;
7268 case GOT_OBJ_TYPE_TREE:
7269 printf("object: %s %s\n", GOT_OBJ_LABEL_TREE,
7270 id_str);
7271 break;
7272 case GOT_OBJ_TYPE_COMMIT:
7273 printf("object: %s %s\n", GOT_OBJ_LABEL_COMMIT,
7274 id_str);
7275 break;
7276 case GOT_OBJ_TYPE_TAG:
7277 printf("object: %s %s\n", GOT_OBJ_LABEL_TAG,
7278 id_str);
7279 break;
7280 default:
7281 break;
7284 free(id_str);
7286 if (ssh_sig) {
7287 err = got_sigs_verify_tag_ssh(&sig_msg, tag, ssh_sig,
7288 allowed_signers, revoked_signers, verbosity);
7289 if (err && err->code == GOT_ERR_BAD_TAG_SIGNATURE)
7290 bad_sigs = 1;
7291 else if (err)
7292 break;
7293 printf("signature: %s", sig_msg);
7294 free(sig_msg);
7295 sig_msg = NULL;
7298 if (commit) {
7299 err = got_object_commit_get_logmsg(&tagmsg0, commit);
7300 if (err)
7301 break;
7302 got_object_commit_close(commit);
7303 } else {
7304 tagmsg0 = strdup(got_object_tag_get_message(tag));
7305 got_object_tag_close(tag);
7306 if (tagmsg0 == NULL) {
7307 err = got_error_from_errno("strdup");
7308 break;
7312 tagmsg = tagmsg0;
7313 do {
7314 line = strsep(&tagmsg, "\n");
7315 if (line)
7316 printf(" %s\n", line);
7317 } while (line);
7318 free(tagmsg0);
7320 done:
7321 got_ref_list_free(&refs);
7322 free(wanted_refname);
7324 if (err == NULL && bad_sigs)
7325 err = got_error(GOT_ERR_BAD_TAG_SIGNATURE);
7326 return err;
7329 static const struct got_error *
7330 get_tag_message(char **tagmsg, char **tagmsg_path, const char *commit_id_str,
7331 const char *tag_name, const char *repo_path)
7333 const struct got_error *err = NULL;
7334 char *template = NULL, *initial_content = NULL;
7335 char *editor = NULL;
7336 int initial_content_len;
7337 int fd = -1;
7339 if (asprintf(&template, GOT_TMPDIR_STR "/got-tagmsg") == -1) {
7340 err = got_error_from_errno("asprintf");
7341 goto done;
7344 initial_content_len = asprintf(&initial_content,
7345 "\n# tagging commit %s as %s\n",
7346 commit_id_str, tag_name);
7347 if (initial_content_len == -1) {
7348 err = got_error_from_errno("asprintf");
7349 goto done;
7352 err = got_opentemp_named_fd(tagmsg_path, &fd, template, "");
7353 if (err)
7354 goto done;
7356 if (write(fd, initial_content, initial_content_len) == -1) {
7357 err = got_error_from_errno2("write", *tagmsg_path);
7358 goto done;
7361 err = get_editor(&editor);
7362 if (err)
7363 goto done;
7364 err = edit_logmsg(tagmsg, editor, *tagmsg_path, initial_content,
7365 initial_content_len, 1);
7366 done:
7367 free(initial_content);
7368 free(template);
7369 free(editor);
7371 if (fd != -1 && close(fd) == -1 && err == NULL)
7372 err = got_error_from_errno2("close", *tagmsg_path);
7374 if (err) {
7375 free(*tagmsg);
7376 *tagmsg = NULL;
7378 return err;
7381 static const struct got_error *
7382 add_tag(struct got_repository *repo, const char *tagger,
7383 const char *tag_name, const char *commit_arg, const char *tagmsg_arg,
7384 const char *signer_id, int verbosity)
7386 const struct got_error *err = NULL;
7387 struct got_object_id *commit_id = NULL, *tag_id = NULL;
7388 char *label = NULL, *commit_id_str = NULL;
7389 struct got_reference *ref = NULL;
7390 char *refname = NULL, *tagmsg = NULL;
7391 char *tagmsg_path = NULL, *tag_id_str = NULL;
7392 int preserve_tagmsg = 0;
7393 struct got_reflist_head refs;
7395 TAILQ_INIT(&refs);
7398 * Don't let the user create a tag name with a leading '-'.
7399 * While technically a valid reference name, this case is usually
7400 * an unintended typo.
7402 if (tag_name[0] == '-')
7403 return got_error_path(tag_name, GOT_ERR_REF_NAME_MINUS);
7405 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
7406 if (err)
7407 goto done;
7409 err = got_repo_match_object_id(&commit_id, &label, commit_arg,
7410 GOT_OBJ_TYPE_COMMIT, &refs, repo);
7411 if (err)
7412 goto done;
7414 err = got_object_id_str(&commit_id_str, commit_id);
7415 if (err)
7416 goto done;
7418 err = get_tag_refname(&refname, tag_name);
7419 if (err)
7420 goto done;
7421 if (strncmp("refs/tags/", tag_name, 10) == 0)
7422 tag_name += 10;
7424 err = got_ref_open(&ref, repo, refname, 0);
7425 if (err == NULL) {
7426 err = got_error(GOT_ERR_TAG_EXISTS);
7427 goto done;
7428 } else if (err->code != GOT_ERR_NOT_REF)
7429 goto done;
7431 if (tagmsg_arg == NULL) {
7432 err = get_tag_message(&tagmsg, &tagmsg_path, commit_id_str,
7433 tag_name, got_repo_get_path(repo));
7434 if (err) {
7435 if (err->code != GOT_ERR_COMMIT_MSG_EMPTY &&
7436 tagmsg_path != NULL)
7437 preserve_tagmsg = 1;
7438 goto done;
7440 /* Editor is done; we can now apply unveil(2) */
7441 err = got_sigs_apply_unveil();
7442 if (err)
7443 goto done;
7444 err = apply_unveil(got_repo_get_path(repo), 0, NULL);
7445 if (err)
7446 goto done;
7449 err = got_object_tag_create(&tag_id, tag_name, commit_id,
7450 tagger, time(NULL), tagmsg ? tagmsg : tagmsg_arg, signer_id, repo,
7451 verbosity);
7452 if (err) {
7453 if (tagmsg_path)
7454 preserve_tagmsg = 1;
7455 goto done;
7458 err = got_ref_alloc(&ref, refname, tag_id);
7459 if (err) {
7460 if (tagmsg_path)
7461 preserve_tagmsg = 1;
7462 goto done;
7465 err = got_ref_write(ref, repo);
7466 if (err) {
7467 if (tagmsg_path)
7468 preserve_tagmsg = 1;
7469 goto done;
7472 err = got_object_id_str(&tag_id_str, tag_id);
7473 if (err) {
7474 if (tagmsg_path)
7475 preserve_tagmsg = 1;
7476 goto done;
7478 printf("Created tag %s\n", tag_id_str);
7479 done:
7480 if (preserve_tagmsg) {
7481 fprintf(stderr, "%s: tag message preserved in %s\n",
7482 getprogname(), tagmsg_path);
7483 } else if (tagmsg_path && unlink(tagmsg_path) == -1 && err == NULL)
7484 err = got_error_from_errno2("unlink", tagmsg_path);
7485 free(tag_id_str);
7486 if (ref)
7487 got_ref_close(ref);
7488 free(commit_id);
7489 free(commit_id_str);
7490 free(refname);
7491 free(tagmsg);
7492 free(tagmsg_path);
7493 got_ref_list_free(&refs);
7494 return err;
7497 static const struct got_error *
7498 cmd_tag(int argc, char *argv[])
7500 const struct got_error *error = NULL;
7501 struct got_repository *repo = NULL;
7502 struct got_worktree *worktree = NULL;
7503 char *cwd = NULL, *repo_path = NULL, *commit_id_str = NULL;
7504 char *gitconfig_path = NULL, *tagger = NULL;
7505 char *allowed_signers = NULL, *revoked_signers = NULL;
7506 const char *signer_id = NULL;
7507 const char *tag_name = NULL, *commit_id_arg = NULL, *tagmsg = NULL;
7508 int ch, do_list = 0, verify_tags = 0, verbosity = 0;
7509 int *pack_fds = NULL;
7511 while ((ch = getopt(argc, argv, "c:lm:r:s:Vv")) != -1) {
7512 switch (ch) {
7513 case 'c':
7514 commit_id_arg = optarg;
7515 break;
7516 case 'l':
7517 do_list = 1;
7518 break;
7519 case 'm':
7520 tagmsg = optarg;
7521 break;
7522 case 'r':
7523 repo_path = realpath(optarg, NULL);
7524 if (repo_path == NULL) {
7525 error = got_error_from_errno2("realpath",
7526 optarg);
7527 goto done;
7529 got_path_strip_trailing_slashes(repo_path);
7530 break;
7531 case 's':
7532 signer_id = optarg;
7533 break;
7534 case 'V':
7535 verify_tags = 1;
7536 break;
7537 case 'v':
7538 if (verbosity < 0)
7539 verbosity = 0;
7540 else if (verbosity < 3)
7541 verbosity++;
7542 break;
7543 default:
7544 usage_tag();
7545 /* NOTREACHED */
7549 argc -= optind;
7550 argv += optind;
7552 if (do_list || verify_tags) {
7553 if (commit_id_arg != NULL)
7554 errx(1,
7555 "-c option can only be used when creating a tag");
7556 if (tagmsg) {
7557 if (do_list)
7558 option_conflict('l', 'm');
7559 else
7560 option_conflict('V', 'm');
7562 if (signer_id) {
7563 if (do_list)
7564 option_conflict('l', 's');
7565 else
7566 option_conflict('V', 's');
7568 if (argc > 1)
7569 usage_tag();
7570 } else if (argc != 1)
7571 usage_tag();
7573 if (argc == 1)
7574 tag_name = argv[0];
7576 #ifndef PROFILE
7577 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
7578 "sendfd unveil", NULL) == -1)
7579 err(1, "pledge");
7580 #endif
7581 cwd = getcwd(NULL, 0);
7582 if (cwd == NULL) {
7583 error = got_error_from_errno("getcwd");
7584 goto done;
7587 error = got_repo_pack_fds_open(&pack_fds);
7588 if (error != NULL)
7589 goto done;
7591 if (repo_path == NULL) {
7592 error = got_worktree_open(&worktree, cwd);
7593 if (error && error->code != GOT_ERR_NOT_WORKTREE)
7594 goto done;
7595 else
7596 error = NULL;
7597 if (worktree) {
7598 repo_path =
7599 strdup(got_worktree_get_repo_path(worktree));
7600 if (repo_path == NULL)
7601 error = got_error_from_errno("strdup");
7602 if (error)
7603 goto done;
7604 } else {
7605 repo_path = strdup(cwd);
7606 if (repo_path == NULL) {
7607 error = got_error_from_errno("strdup");
7608 goto done;
7613 if (do_list || verify_tags) {
7614 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
7615 if (error != NULL)
7616 goto done;
7617 error = get_allowed_signers(&allowed_signers, repo, worktree);
7618 if (error)
7619 goto done;
7620 error = get_revoked_signers(&revoked_signers, repo, worktree);
7621 if (error)
7622 goto done;
7623 if (worktree) {
7624 /* Release work tree lock. */
7625 got_worktree_close(worktree);
7626 worktree = NULL;
7630 * Remove "cpath" promise unless needed for signature tmpfile
7631 * creation.
7633 if (verify_tags)
7634 got_sigs_apply_unveil();
7635 else {
7636 #ifndef PROFILE
7637 if (pledge("stdio rpath wpath flock proc exec sendfd "
7638 "unveil", NULL) == -1)
7639 err(1, "pledge");
7640 #endif
7642 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
7643 if (error)
7644 goto done;
7645 error = list_tags(repo, tag_name, verify_tags, allowed_signers,
7646 revoked_signers, verbosity);
7647 } else {
7648 error = get_gitconfig_path(&gitconfig_path);
7649 if (error)
7650 goto done;
7651 error = got_repo_open(&repo, repo_path, gitconfig_path,
7652 pack_fds);
7653 if (error != NULL)
7654 goto done;
7656 error = get_author(&tagger, repo, worktree);
7657 if (error)
7658 goto done;
7659 if (signer_id == NULL)
7660 signer_id = get_signer_id(repo, worktree);
7662 if (tagmsg) {
7663 if (signer_id) {
7664 error = got_sigs_apply_unveil();
7665 if (error)
7666 goto done;
7668 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
7669 if (error)
7670 goto done;
7673 if (commit_id_arg == NULL) {
7674 struct got_reference *head_ref;
7675 struct got_object_id *commit_id;
7676 error = got_ref_open(&head_ref, repo,
7677 worktree ? got_worktree_get_head_ref_name(worktree)
7678 : GOT_REF_HEAD, 0);
7679 if (error)
7680 goto done;
7681 error = got_ref_resolve(&commit_id, repo, head_ref);
7682 got_ref_close(head_ref);
7683 if (error)
7684 goto done;
7685 error = got_object_id_str(&commit_id_str, commit_id);
7686 free(commit_id);
7687 if (error)
7688 goto done;
7691 if (worktree) {
7692 /* Release work tree lock. */
7693 got_worktree_close(worktree);
7694 worktree = NULL;
7697 error = add_tag(repo, tagger, tag_name,
7698 commit_id_str ? commit_id_str : commit_id_arg, tagmsg,
7699 signer_id, verbosity);
7701 done:
7702 if (repo) {
7703 const struct got_error *close_err = got_repo_close(repo);
7704 if (error == NULL)
7705 error = close_err;
7707 if (worktree)
7708 got_worktree_close(worktree);
7709 if (pack_fds) {
7710 const struct got_error *pack_err =
7711 got_repo_pack_fds_close(pack_fds);
7712 if (error == NULL)
7713 error = pack_err;
7715 free(cwd);
7716 free(repo_path);
7717 free(gitconfig_path);
7718 free(commit_id_str);
7719 free(tagger);
7720 free(allowed_signers);
7721 free(revoked_signers);
7722 return error;
7725 __dead static void
7726 usage_add(void)
7728 fprintf(stderr, "usage: %s add [-IR] path ...\n", getprogname());
7729 exit(1);
7732 static const struct got_error *
7733 add_progress(void *arg, unsigned char status, const char *path)
7735 while (path[0] == '/')
7736 path++;
7737 printf("%c %s\n", status, path);
7738 return NULL;
7741 static const struct got_error *
7742 cmd_add(int argc, char *argv[])
7744 const struct got_error *error = NULL;
7745 struct got_repository *repo = NULL;
7746 struct got_worktree *worktree = NULL;
7747 char *cwd = NULL;
7748 struct got_pathlist_head paths;
7749 struct got_pathlist_entry *pe;
7750 int ch, can_recurse = 0, no_ignores = 0;
7751 int *pack_fds = NULL;
7753 TAILQ_INIT(&paths);
7755 while ((ch = getopt(argc, argv, "IR")) != -1) {
7756 switch (ch) {
7757 case 'I':
7758 no_ignores = 1;
7759 break;
7760 case 'R':
7761 can_recurse = 1;
7762 break;
7763 default:
7764 usage_add();
7765 /* NOTREACHED */
7769 argc -= optind;
7770 argv += optind;
7772 #ifndef PROFILE
7773 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
7774 NULL) == -1)
7775 err(1, "pledge");
7776 #endif
7777 if (argc < 1)
7778 usage_add();
7780 cwd = getcwd(NULL, 0);
7781 if (cwd == NULL) {
7782 error = got_error_from_errno("getcwd");
7783 goto done;
7786 error = got_repo_pack_fds_open(&pack_fds);
7787 if (error != NULL)
7788 goto done;
7790 error = got_worktree_open(&worktree, cwd);
7791 if (error) {
7792 if (error->code == GOT_ERR_NOT_WORKTREE)
7793 error = wrap_not_worktree_error(error, "add", cwd);
7794 goto done;
7797 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
7798 NULL, pack_fds);
7799 if (error != NULL)
7800 goto done;
7802 error = apply_unveil(got_repo_get_path(repo), 1,
7803 got_worktree_get_root_path(worktree));
7804 if (error)
7805 goto done;
7807 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
7808 if (error)
7809 goto done;
7811 if (!can_recurse) {
7812 char *ondisk_path;
7813 struct stat sb;
7814 TAILQ_FOREACH(pe, &paths, entry) {
7815 if (asprintf(&ondisk_path, "%s/%s",
7816 got_worktree_get_root_path(worktree),
7817 pe->path) == -1) {
7818 error = got_error_from_errno("asprintf");
7819 goto done;
7821 if (lstat(ondisk_path, &sb) == -1) {
7822 if (errno == ENOENT) {
7823 free(ondisk_path);
7824 continue;
7826 error = got_error_from_errno2("lstat",
7827 ondisk_path);
7828 free(ondisk_path);
7829 goto done;
7831 free(ondisk_path);
7832 if (S_ISDIR(sb.st_mode)) {
7833 error = got_error_msg(GOT_ERR_BAD_PATH,
7834 "adding directories requires -R option");
7835 goto done;
7840 error = got_worktree_schedule_add(worktree, &paths, add_progress,
7841 NULL, repo, no_ignores);
7842 done:
7843 if (repo) {
7844 const struct got_error *close_err = got_repo_close(repo);
7845 if (error == NULL)
7846 error = close_err;
7848 if (worktree)
7849 got_worktree_close(worktree);
7850 if (pack_fds) {
7851 const struct got_error *pack_err =
7852 got_repo_pack_fds_close(pack_fds);
7853 if (error == NULL)
7854 error = pack_err;
7856 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
7857 free(cwd);
7858 return error;
7861 __dead static void
7862 usage_remove(void)
7864 fprintf(stderr, "usage: %s remove [-fkR] [-s status-codes] path ...\n",
7865 getprogname());
7866 exit(1);
7869 static const struct got_error *
7870 print_remove_status(void *arg, unsigned char status,
7871 unsigned char staged_status, const char *path)
7873 while (path[0] == '/')
7874 path++;
7875 if (status == GOT_STATUS_NONEXISTENT)
7876 return NULL;
7877 if (status == staged_status && (status == GOT_STATUS_DELETE))
7878 status = GOT_STATUS_NO_CHANGE;
7879 printf("%c%c %s\n", status, staged_status, path);
7880 return NULL;
7883 static const struct got_error *
7884 cmd_remove(int argc, char *argv[])
7886 const struct got_error *error = NULL;
7887 struct got_worktree *worktree = NULL;
7888 struct got_repository *repo = NULL;
7889 const char *status_codes = NULL;
7890 char *cwd = NULL;
7891 struct got_pathlist_head paths;
7892 struct got_pathlist_entry *pe;
7893 int ch, delete_local_mods = 0, can_recurse = 0, keep_on_disk = 0, i;
7894 int ignore_missing_paths = 0;
7895 int *pack_fds = NULL;
7897 TAILQ_INIT(&paths);
7899 while ((ch = getopt(argc, argv, "fkRs:")) != -1) {
7900 switch (ch) {
7901 case 'f':
7902 delete_local_mods = 1;
7903 ignore_missing_paths = 1;
7904 break;
7905 case 'k':
7906 keep_on_disk = 1;
7907 break;
7908 case 'R':
7909 can_recurse = 1;
7910 break;
7911 case 's':
7912 for (i = 0; i < strlen(optarg); i++) {
7913 switch (optarg[i]) {
7914 case GOT_STATUS_MODIFY:
7915 delete_local_mods = 1;
7916 break;
7917 case GOT_STATUS_MISSING:
7918 ignore_missing_paths = 1;
7919 break;
7920 default:
7921 errx(1, "invalid status code '%c'",
7922 optarg[i]);
7925 status_codes = optarg;
7926 break;
7927 default:
7928 usage_remove();
7929 /* NOTREACHED */
7933 argc -= optind;
7934 argv += optind;
7936 #ifndef PROFILE
7937 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
7938 NULL) == -1)
7939 err(1, "pledge");
7940 #endif
7941 if (argc < 1)
7942 usage_remove();
7944 cwd = getcwd(NULL, 0);
7945 if (cwd == NULL) {
7946 error = got_error_from_errno("getcwd");
7947 goto done;
7950 error = got_repo_pack_fds_open(&pack_fds);
7951 if (error != NULL)
7952 goto done;
7954 error = got_worktree_open(&worktree, cwd);
7955 if (error) {
7956 if (error->code == GOT_ERR_NOT_WORKTREE)
7957 error = wrap_not_worktree_error(error, "remove", cwd);
7958 goto done;
7961 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
7962 NULL, pack_fds);
7963 if (error)
7964 goto done;
7966 error = apply_unveil(got_repo_get_path(repo), 1,
7967 got_worktree_get_root_path(worktree));
7968 if (error)
7969 goto done;
7971 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
7972 if (error)
7973 goto done;
7975 if (!can_recurse) {
7976 char *ondisk_path;
7977 struct stat sb;
7978 TAILQ_FOREACH(pe, &paths, entry) {
7979 if (asprintf(&ondisk_path, "%s/%s",
7980 got_worktree_get_root_path(worktree),
7981 pe->path) == -1) {
7982 error = got_error_from_errno("asprintf");
7983 goto done;
7985 if (lstat(ondisk_path, &sb) == -1) {
7986 if (errno == ENOENT) {
7987 free(ondisk_path);
7988 continue;
7990 error = got_error_from_errno2("lstat",
7991 ondisk_path);
7992 free(ondisk_path);
7993 goto done;
7995 free(ondisk_path);
7996 if (S_ISDIR(sb.st_mode)) {
7997 error = got_error_msg(GOT_ERR_BAD_PATH,
7998 "removing directories requires -R option");
7999 goto done;
8004 error = got_worktree_schedule_delete(worktree, &paths,
8005 delete_local_mods, status_codes, print_remove_status, NULL,
8006 repo, keep_on_disk, ignore_missing_paths);
8007 done:
8008 if (repo) {
8009 const struct got_error *close_err = got_repo_close(repo);
8010 if (error == NULL)
8011 error = close_err;
8013 if (worktree)
8014 got_worktree_close(worktree);
8015 if (pack_fds) {
8016 const struct got_error *pack_err =
8017 got_repo_pack_fds_close(pack_fds);
8018 if (error == NULL)
8019 error = pack_err;
8021 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
8022 free(cwd);
8023 return error;
8026 __dead static void
8027 usage_patch(void)
8029 fprintf(stderr, "usage: %s patch [-nR] [-c commit] [-p strip-count] "
8030 "[patchfile]\n", getprogname());
8031 exit(1);
8034 static const struct got_error *
8035 patch_from_stdin(int *patchfd)
8037 const struct got_error *err = NULL;
8038 ssize_t r;
8039 char buf[BUFSIZ];
8040 sig_t sighup, sigint, sigquit;
8042 *patchfd = got_opentempfd();
8043 if (*patchfd == -1)
8044 return got_error_from_errno("got_opentempfd");
8046 sighup = signal(SIGHUP, SIG_DFL);
8047 sigint = signal(SIGINT, SIG_DFL);
8048 sigquit = signal(SIGQUIT, SIG_DFL);
8050 for (;;) {
8051 r = read(0, buf, sizeof(buf));
8052 if (r == -1) {
8053 err = got_error_from_errno("read");
8054 break;
8056 if (r == 0)
8057 break;
8058 if (write(*patchfd, buf, r) == -1) {
8059 err = got_error_from_errno("write");
8060 break;
8064 signal(SIGHUP, sighup);
8065 signal(SIGINT, sigint);
8066 signal(SIGQUIT, sigquit);
8068 if (err == NULL && lseek(*patchfd, 0, SEEK_SET) == -1)
8069 err = got_error_from_errno("lseek");
8071 if (err != NULL) {
8072 close(*patchfd);
8073 *patchfd = -1;
8076 return err;
8079 static const struct got_error *
8080 patch_progress(void *arg, const char *old, const char *new,
8081 unsigned char status, const struct got_error *error, int old_from,
8082 int old_lines, int new_from, int new_lines, int offset,
8083 int ws_mangled, const struct got_error *hunk_err)
8085 const char *path = new == NULL ? old : new;
8087 while (*path == '/')
8088 path++;
8090 if (status != 0)
8091 printf("%c %s\n", status, path);
8093 if (error != NULL)
8094 fprintf(stderr, "%s: %s\n", getprogname(), error->msg);
8096 if (offset != 0 || hunk_err != NULL || ws_mangled) {
8097 printf("@@ -%d,%d +%d,%d @@ ", old_from,
8098 old_lines, new_from, new_lines);
8099 if (hunk_err != NULL)
8100 printf("%s\n", hunk_err->msg);
8101 else if (offset != 0)
8102 printf("applied with offset %d\n", offset);
8103 else
8104 printf("hunk contains mangled whitespace\n");
8107 return NULL;
8110 static const struct got_error *
8111 cmd_patch(int argc, char *argv[])
8113 const struct got_error *error = NULL, *close_error = NULL;
8114 struct got_worktree *worktree = NULL;
8115 struct got_repository *repo = NULL;
8116 struct got_reflist_head refs;
8117 struct got_object_id *commit_id = NULL;
8118 const char *commit_id_str = NULL;
8119 struct stat sb;
8120 const char *errstr;
8121 char *cwd = NULL;
8122 int ch, nop = 0, strip = -1, reverse = 0;
8123 int patchfd;
8124 int *pack_fds = NULL;
8126 TAILQ_INIT(&refs);
8128 #ifndef PROFILE
8129 if (pledge("stdio rpath wpath cpath fattr proc exec sendfd flock "
8130 "unveil", NULL) == -1)
8131 err(1, "pledge");
8132 #endif
8134 while ((ch = getopt(argc, argv, "c:np:R")) != -1) {
8135 switch (ch) {
8136 case 'c':
8137 commit_id_str = optarg;
8138 break;
8139 case 'n':
8140 nop = 1;
8141 break;
8142 case 'p':
8143 strip = strtonum(optarg, 0, INT_MAX, &errstr);
8144 if (errstr != NULL)
8145 errx(1, "pathname strip count is %s: %s",
8146 errstr, optarg);
8147 break;
8148 case 'R':
8149 reverse = 1;
8150 break;
8151 default:
8152 usage_patch();
8153 /* NOTREACHED */
8157 argc -= optind;
8158 argv += optind;
8160 if (argc == 0) {
8161 error = patch_from_stdin(&patchfd);
8162 if (error)
8163 return error;
8164 } else if (argc == 1) {
8165 patchfd = open(argv[0], O_RDONLY);
8166 if (patchfd == -1) {
8167 error = got_error_from_errno2("open", argv[0]);
8168 return error;
8170 if (fstat(patchfd, &sb) == -1) {
8171 error = got_error_from_errno2("fstat", argv[0]);
8172 goto done;
8174 if (!S_ISREG(sb.st_mode)) {
8175 error = got_error_path(argv[0], GOT_ERR_BAD_FILETYPE);
8176 goto done;
8178 } else
8179 usage_patch();
8181 if ((cwd = getcwd(NULL, 0)) == NULL) {
8182 error = got_error_from_errno("getcwd");
8183 goto done;
8186 error = got_repo_pack_fds_open(&pack_fds);
8187 if (error != NULL)
8188 goto done;
8190 error = got_worktree_open(&worktree, cwd);
8191 if (error != NULL)
8192 goto done;
8194 const char *repo_path = got_worktree_get_repo_path(worktree);
8195 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
8196 if (error != NULL)
8197 goto done;
8199 error = apply_unveil(got_repo_get_path(repo), 0,
8200 got_worktree_get_root_path(worktree));
8201 if (error != NULL)
8202 goto done;
8204 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
8205 if (error)
8206 goto done;
8208 if (commit_id_str != NULL) {
8209 error = got_repo_match_object_id(&commit_id, NULL,
8210 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
8211 if (error)
8212 goto done;
8215 error = got_patch(patchfd, worktree, repo, nop, strip, reverse,
8216 commit_id, &patch_progress, NULL, check_cancelled, NULL);
8218 done:
8219 got_ref_list_free(&refs);
8220 free(commit_id);
8221 if (repo) {
8222 close_error = got_repo_close(repo);
8223 if (error == NULL)
8224 error = close_error;
8226 if (worktree != NULL) {
8227 close_error = got_worktree_close(worktree);
8228 if (error == NULL)
8229 error = close_error;
8231 if (pack_fds) {
8232 const struct got_error *pack_err =
8233 got_repo_pack_fds_close(pack_fds);
8234 if (error == NULL)
8235 error = pack_err;
8237 free(cwd);
8238 return error;
8241 __dead static void
8242 usage_revert(void)
8244 fprintf(stderr, "usage: %s revert [-pR] [-F response-script] path ...\n",
8245 getprogname());
8246 exit(1);
8249 static const struct got_error *
8250 revert_progress(void *arg, unsigned char status, const char *path)
8252 if (status == GOT_STATUS_UNVERSIONED)
8253 return NULL;
8255 while (path[0] == '/')
8256 path++;
8257 printf("%c %s\n", status, path);
8258 return NULL;
8261 struct choose_patch_arg {
8262 FILE *patch_script_file;
8263 const char *action;
8266 static const struct got_error *
8267 show_change(unsigned char status, const char *path, FILE *patch_file, int n,
8268 int nchanges, const char *action)
8270 const struct got_error *err;
8271 char *line = NULL;
8272 size_t linesize = 0;
8273 ssize_t linelen;
8275 switch (status) {
8276 case GOT_STATUS_ADD:
8277 printf("A %s\n%s this addition? [y/n] ", path, action);
8278 break;
8279 case GOT_STATUS_DELETE:
8280 printf("D %s\n%s this deletion? [y/n] ", path, action);
8281 break;
8282 case GOT_STATUS_MODIFY:
8283 if (fseek(patch_file, 0L, SEEK_SET) == -1)
8284 return got_error_from_errno("fseek");
8285 printf(GOT_COMMIT_SEP_STR);
8286 while ((linelen = getline(&line, &linesize, patch_file)) != -1)
8287 printf("%s", line);
8288 if (linelen == -1 && ferror(patch_file)) {
8289 err = got_error_from_errno("getline");
8290 free(line);
8291 return err;
8293 free(line);
8294 printf(GOT_COMMIT_SEP_STR);
8295 printf("M %s (change %d of %d)\n%s this change? [y/n/q] ",
8296 path, n, nchanges, action);
8297 break;
8298 default:
8299 return got_error_path(path, GOT_ERR_FILE_STATUS);
8302 fflush(stdout);
8303 return NULL;
8306 static const struct got_error *
8307 choose_patch(int *choice, void *arg, unsigned char status, const char *path,
8308 FILE *patch_file, int n, int nchanges)
8310 const struct got_error *err = NULL;
8311 char *line = NULL;
8312 size_t linesize = 0;
8313 ssize_t linelen;
8314 int resp = ' ';
8315 struct choose_patch_arg *a = arg;
8317 *choice = GOT_PATCH_CHOICE_NONE;
8319 if (a->patch_script_file) {
8320 char *nl;
8321 err = show_change(status, path, patch_file, n, nchanges,
8322 a->action);
8323 if (err)
8324 return err;
8325 linelen = getline(&line, &linesize, a->patch_script_file);
8326 if (linelen == -1) {
8327 if (ferror(a->patch_script_file))
8328 return got_error_from_errno("getline");
8329 return NULL;
8331 nl = strchr(line, '\n');
8332 if (nl)
8333 *nl = '\0';
8334 if (strcmp(line, "y") == 0) {
8335 *choice = GOT_PATCH_CHOICE_YES;
8336 printf("y\n");
8337 } else if (strcmp(line, "n") == 0) {
8338 *choice = GOT_PATCH_CHOICE_NO;
8339 printf("n\n");
8340 } else if (strcmp(line, "q") == 0 &&
8341 status == GOT_STATUS_MODIFY) {
8342 *choice = GOT_PATCH_CHOICE_QUIT;
8343 printf("q\n");
8344 } else
8345 printf("invalid response '%s'\n", line);
8346 free(line);
8347 return NULL;
8350 while (resp != 'y' && resp != 'n' && resp != 'q') {
8351 err = show_change(status, path, patch_file, n, nchanges,
8352 a->action);
8353 if (err)
8354 return err;
8355 resp = getchar();
8356 if (resp == '\n')
8357 resp = getchar();
8358 if (status == GOT_STATUS_MODIFY) {
8359 if (resp != 'y' && resp != 'n' && resp != 'q') {
8360 printf("invalid response '%c'\n", resp);
8361 resp = ' ';
8363 } else if (resp != 'y' && resp != 'n') {
8364 printf("invalid response '%c'\n", resp);
8365 resp = ' ';
8369 if (resp == 'y')
8370 *choice = GOT_PATCH_CHOICE_YES;
8371 else if (resp == 'n')
8372 *choice = GOT_PATCH_CHOICE_NO;
8373 else if (resp == 'q' && status == GOT_STATUS_MODIFY)
8374 *choice = GOT_PATCH_CHOICE_QUIT;
8376 return NULL;
8379 struct wt_commitable_path_arg {
8380 struct got_pathlist_head *commit_paths;
8381 int *has_changes;
8385 * Shortcut work tree status callback to determine if the set of paths scanned
8386 * has at least one versioned path that is being modified and, if not NULL, is
8387 * in the arg->commit_paths list. Set arg and return GOT_ERR_FILE_MODIFIED as
8388 * soon as a path is passed with a status that satisfies this criteria.
8390 static const struct got_error *
8391 worktree_has_commitable_path(void *arg, unsigned char status,
8392 unsigned char staged_status, const char *path,
8393 struct got_object_id *blob_id, struct got_object_id *staged_blob_id,
8394 struct got_object_id *commit_id, int dirfd, const char *de_name)
8396 struct wt_commitable_path_arg *a = arg;
8398 if (status == staged_status && (status == GOT_STATUS_DELETE))
8399 status = GOT_STATUS_NO_CHANGE;
8401 if (!(status == GOT_STATUS_NO_CHANGE ||
8402 status == GOT_STATUS_UNVERSIONED) ||
8403 staged_status != GOT_STATUS_NO_CHANGE) {
8404 if (a->commit_paths != NULL) {
8405 struct got_pathlist_entry *pe;
8407 TAILQ_FOREACH(pe, a->commit_paths, entry) {
8408 if (strncmp(path, pe->path,
8409 pe->path_len) == 0) {
8410 *a->has_changes = 1;
8411 break;
8414 } else
8415 *a->has_changes = 1;
8417 if (*a->has_changes)
8418 return got_error(GOT_ERR_FILE_MODIFIED);
8421 return NULL;
8425 * Check that the changeset of the commit identified by id is
8426 * comprised of at least one modified path that is being committed.
8428 static const struct got_error *
8429 commit_path_changed_in_worktree(struct wt_commitable_path_arg *wcpa,
8430 struct got_object_id *id, struct got_worktree *worktree,
8431 struct got_repository *repo)
8433 const struct got_error *err;
8434 struct got_pathlist_head paths;
8435 struct got_commit_object *commit = NULL, *pcommit = NULL;
8436 struct got_tree_object *tree = NULL, *ptree = NULL;
8437 struct got_object_qid *pid;
8439 TAILQ_INIT(&paths);
8441 err = got_object_open_as_commit(&commit, repo, id);
8442 if (err)
8443 goto done;
8445 err = got_object_open_as_tree(&tree, repo,
8446 got_object_commit_get_tree_id(commit));
8447 if (err)
8448 goto done;
8450 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
8451 if (pid != NULL) {
8452 err = got_object_open_as_commit(&pcommit, repo, &pid->id);
8453 if (err)
8454 goto done;
8456 err = got_object_open_as_tree(&ptree, repo,
8457 got_object_commit_get_tree_id(pcommit));
8458 if (err)
8459 goto done;
8462 err = got_diff_tree(ptree, tree, NULL, NULL, -1, -1, "", "", repo,
8463 got_diff_tree_collect_changed_paths, &paths, 0);
8464 if (err)
8465 goto done;
8467 err = got_worktree_status(worktree, &paths, repo, 0,
8468 worktree_has_commitable_path, wcpa, check_cancelled, NULL);
8469 if (err && err->code == GOT_ERR_FILE_MODIFIED) {
8471 * At least one changed path in the referenced commit is
8472 * modified in the work tree, that's all we need to know!
8474 err = NULL;
8477 done:
8478 got_pathlist_free(&paths, GOT_PATHLIST_FREE_ALL);
8479 if (commit)
8480 got_object_commit_close(commit);
8481 if (pcommit)
8482 got_object_commit_close(pcommit);
8483 if (tree)
8484 got_object_tree_close(tree);
8485 if (ptree)
8486 got_object_tree_close(ptree);
8487 return err;
8491 * Remove any "logmsg" reference comprised entirely of paths that have
8492 * been reverted in this work tree. If any path in the logmsg ref changeset
8493 * remains in a changed state in the worktree, do not remove the reference.
8495 static const struct got_error *
8496 rm_logmsg_ref(struct got_worktree *worktree, struct got_repository *repo)
8498 const struct got_error *err;
8499 struct got_reflist_head refs;
8500 struct got_reflist_entry *re;
8501 struct got_commit_object *commit = NULL;
8502 struct got_object_id *commit_id = NULL;
8503 struct wt_commitable_path_arg wcpa;
8504 char *uuidstr = NULL;
8506 TAILQ_INIT(&refs);
8508 err = got_worktree_get_uuid(&uuidstr, worktree);
8509 if (err)
8510 goto done;
8512 err = got_ref_list(&refs, repo, "refs/got/worktree",
8513 got_ref_cmp_by_name, repo);
8514 if (err)
8515 goto done;
8517 TAILQ_FOREACH(re, &refs, entry) {
8518 const char *refname;
8519 int has_changes = 0;
8521 refname = got_ref_get_name(re->ref);
8523 if (!strncmp(refname, GOT_WORKTREE_CHERRYPICK_REF_PREFIX,
8524 GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN))
8525 refname += GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN + 1;
8526 else if (!strncmp(refname, GOT_WORKTREE_BACKOUT_REF_PREFIX,
8527 GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN))
8528 refname += GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN + 1;
8529 else
8530 continue;
8532 if (strncmp(refname, uuidstr, GOT_WORKTREE_UUID_STRLEN) == 0)
8533 refname += GOT_WORKTREE_UUID_STRLEN + 1; /* skip '-' */
8534 else
8535 continue;
8537 err = got_repo_match_object_id(&commit_id, NULL, refname,
8538 GOT_OBJ_TYPE_COMMIT, NULL, repo);
8539 if (err)
8540 goto done;
8542 err = got_object_open_as_commit(&commit, repo, commit_id);
8543 if (err)
8544 goto done;
8546 wcpa.commit_paths = NULL;
8547 wcpa.has_changes = &has_changes;
8549 err = commit_path_changed_in_worktree(&wcpa, commit_id,
8550 worktree, repo);
8551 if (err)
8552 goto done;
8554 if (!has_changes) {
8555 err = got_ref_delete(re->ref, repo);
8556 if (err)
8557 goto done;
8560 got_object_commit_close(commit);
8561 commit = NULL;
8562 free(commit_id);
8563 commit_id = NULL;
8566 done:
8567 free(uuidstr);
8568 free(commit_id);
8569 got_ref_list_free(&refs);
8570 if (commit)
8571 got_object_commit_close(commit);
8572 return err;
8575 static const struct got_error *
8576 cmd_revert(int argc, char *argv[])
8578 const struct got_error *error = NULL;
8579 struct got_worktree *worktree = NULL;
8580 struct got_repository *repo = NULL;
8581 char *cwd = NULL, *path = NULL;
8582 struct got_pathlist_head paths;
8583 struct got_pathlist_entry *pe;
8584 int ch, can_recurse = 0, pflag = 0;
8585 FILE *patch_script_file = NULL;
8586 const char *patch_script_path = NULL;
8587 struct choose_patch_arg cpa;
8588 int *pack_fds = NULL;
8590 TAILQ_INIT(&paths);
8592 while ((ch = getopt(argc, argv, "F:pR")) != -1) {
8593 switch (ch) {
8594 case 'F':
8595 patch_script_path = optarg;
8596 break;
8597 case 'p':
8598 pflag = 1;
8599 break;
8600 case 'R':
8601 can_recurse = 1;
8602 break;
8603 default:
8604 usage_revert();
8605 /* NOTREACHED */
8609 argc -= optind;
8610 argv += optind;
8612 #ifndef PROFILE
8613 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
8614 "unveil", NULL) == -1)
8615 err(1, "pledge");
8616 #endif
8617 if (argc < 1)
8618 usage_revert();
8619 if (patch_script_path && !pflag)
8620 errx(1, "-F option can only be used together with -p option");
8622 cwd = getcwd(NULL, 0);
8623 if (cwd == NULL) {
8624 error = got_error_from_errno("getcwd");
8625 goto done;
8628 error = got_repo_pack_fds_open(&pack_fds);
8629 if (error != NULL)
8630 goto done;
8632 error = got_worktree_open(&worktree, cwd);
8633 if (error) {
8634 if (error->code == GOT_ERR_NOT_WORKTREE)
8635 error = wrap_not_worktree_error(error, "revert", cwd);
8636 goto done;
8639 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
8640 NULL, pack_fds);
8641 if (error != NULL)
8642 goto done;
8644 if (patch_script_path) {
8645 patch_script_file = fopen(patch_script_path, "re");
8646 if (patch_script_file == NULL) {
8647 error = got_error_from_errno2("fopen",
8648 patch_script_path);
8649 goto done;
8654 * XXX "c" perm needed on repo dir to delete merge references.
8656 error = apply_unveil(got_repo_get_path(repo), 0,
8657 got_worktree_get_root_path(worktree));
8658 if (error)
8659 goto done;
8661 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
8662 if (error)
8663 goto done;
8665 if (!can_recurse) {
8666 char *ondisk_path;
8667 struct stat sb;
8668 TAILQ_FOREACH(pe, &paths, entry) {
8669 if (asprintf(&ondisk_path, "%s/%s",
8670 got_worktree_get_root_path(worktree),
8671 pe->path) == -1) {
8672 error = got_error_from_errno("asprintf");
8673 goto done;
8675 if (lstat(ondisk_path, &sb) == -1) {
8676 if (errno == ENOENT) {
8677 free(ondisk_path);
8678 continue;
8680 error = got_error_from_errno2("lstat",
8681 ondisk_path);
8682 free(ondisk_path);
8683 goto done;
8685 free(ondisk_path);
8686 if (S_ISDIR(sb.st_mode)) {
8687 error = got_error_msg(GOT_ERR_BAD_PATH,
8688 "reverting directories requires -R option");
8689 goto done;
8694 cpa.patch_script_file = patch_script_file;
8695 cpa.action = "revert";
8696 error = got_worktree_revert(worktree, &paths, revert_progress, NULL,
8697 pflag ? choose_patch : NULL, &cpa, repo);
8699 error = rm_logmsg_ref(worktree, repo);
8700 done:
8701 if (patch_script_file && fclose(patch_script_file) == EOF &&
8702 error == NULL)
8703 error = got_error_from_errno2("fclose", patch_script_path);
8704 if (repo) {
8705 const struct got_error *close_err = got_repo_close(repo);
8706 if (error == NULL)
8707 error = close_err;
8709 if (worktree)
8710 got_worktree_close(worktree);
8711 if (pack_fds) {
8712 const struct got_error *pack_err =
8713 got_repo_pack_fds_close(pack_fds);
8714 if (error == NULL)
8715 error = pack_err;
8717 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
8718 free(path);
8719 free(cwd);
8720 return error;
8723 __dead static void
8724 usage_commit(void)
8726 fprintf(stderr, "usage: %s commit [-NS] [-A author] [-F path] "
8727 "[-m message] [path ...]\n", getprogname());
8728 exit(1);
8731 struct collect_commit_logmsg_arg {
8732 const char *cmdline_log;
8733 const char *prepared_log;
8734 const char *merged_log;
8735 int non_interactive;
8736 const char *editor;
8737 const char *worktree_path;
8738 const char *branch_name;
8739 const char *repo_path;
8740 char *logmsg_path;
8744 static const struct got_error *
8745 read_prepared_logmsg(char **logmsg, const char *path)
8747 const struct got_error *err = NULL;
8748 FILE *f = NULL;
8749 struct stat sb;
8750 size_t r;
8752 *logmsg = NULL;
8753 memset(&sb, 0, sizeof(sb));
8755 f = fopen(path, "re");
8756 if (f == NULL)
8757 return got_error_from_errno2("fopen", path);
8759 if (fstat(fileno(f), &sb) == -1) {
8760 err = got_error_from_errno2("fstat", path);
8761 goto done;
8763 if (sb.st_size == 0) {
8764 err = got_error(GOT_ERR_COMMIT_MSG_EMPTY);
8765 goto done;
8768 *logmsg = malloc(sb.st_size + 1);
8769 if (*logmsg == NULL) {
8770 err = got_error_from_errno("malloc");
8771 goto done;
8774 r = fread(*logmsg, 1, sb.st_size, f);
8775 if (r != sb.st_size) {
8776 if (ferror(f))
8777 err = got_error_from_errno2("fread", path);
8778 else
8779 err = got_error(GOT_ERR_IO);
8780 goto done;
8782 (*logmsg)[sb.st_size] = '\0';
8783 done:
8784 if (fclose(f) == EOF && err == NULL)
8785 err = got_error_from_errno2("fclose", path);
8786 if (err) {
8787 free(*logmsg);
8788 *logmsg = NULL;
8790 return err;
8793 static const struct got_error *
8794 collect_commit_logmsg(struct got_pathlist_head *commitable_paths,
8795 const char *diff_path, char **logmsg, void *arg)
8797 char *initial_content = NULL;
8798 struct got_pathlist_entry *pe;
8799 const struct got_error *err = NULL;
8800 char *template = NULL;
8801 char *prepared_msg = NULL, *merged_msg = NULL;
8802 struct collect_commit_logmsg_arg *a = arg;
8803 int initial_content_len;
8804 int fd = -1;
8805 size_t len;
8807 /* if a message was specified on the command line, just use it */
8808 if (a->cmdline_log != NULL && strlen(a->cmdline_log) != 0) {
8809 len = strlen(a->cmdline_log) + 1;
8810 *logmsg = malloc(len + 1);
8811 if (*logmsg == NULL)
8812 return got_error_from_errno("malloc");
8813 strlcpy(*logmsg, a->cmdline_log, len);
8814 return NULL;
8815 } else if (a->prepared_log != NULL && a->non_interactive)
8816 return read_prepared_logmsg(logmsg, a->prepared_log);
8818 if (asprintf(&template, "%s/logmsg", a->worktree_path) == -1)
8819 return got_error_from_errno("asprintf");
8821 err = got_opentemp_named_fd(&a->logmsg_path, &fd, template, "");
8822 if (err)
8823 goto done;
8825 if (a->prepared_log) {
8826 err = read_prepared_logmsg(&prepared_msg, a->prepared_log);
8827 if (err)
8828 goto done;
8829 } else if (a->merged_log) {
8830 err = read_prepared_logmsg(&merged_msg, a->merged_log);
8831 if (err)
8832 goto done;
8835 initial_content_len = asprintf(&initial_content,
8836 "%s%s\n# changes to be committed on branch %s:\n",
8837 prepared_msg ? prepared_msg : "",
8838 merged_msg ? merged_msg : "", a->branch_name);
8839 if (initial_content_len == -1) {
8840 err = got_error_from_errno("asprintf");
8841 goto done;
8844 if (write(fd, initial_content, initial_content_len) == -1) {
8845 err = got_error_from_errno2("write", a->logmsg_path);
8846 goto done;
8849 TAILQ_FOREACH(pe, commitable_paths, entry) {
8850 struct got_commitable *ct = pe->data;
8851 dprintf(fd, "# %c %s\n",
8852 got_commitable_get_status(ct),
8853 got_commitable_get_path(ct));
8856 if (diff_path) {
8857 dprintf(fd, "# detailed changes can be viewed in %s\n",
8858 diff_path);
8861 err = edit_logmsg(logmsg, a->editor, a->logmsg_path, initial_content,
8862 initial_content_len, a->prepared_log ? 0 : 1);
8863 done:
8864 free(initial_content);
8865 free(template);
8866 free(prepared_msg);
8867 free(merged_msg);
8869 if (fd != -1 && close(fd) == -1 && err == NULL)
8870 err = got_error_from_errno2("close", a->logmsg_path);
8872 /* Editor is done; we can now apply unveil(2) */
8873 if (err == NULL)
8874 err = apply_unveil(a->repo_path, 0, a->worktree_path);
8875 if (err) {
8876 free(*logmsg);
8877 *logmsg = NULL;
8879 return err;
8882 static const struct got_error *
8883 cat_logmsg(FILE *f, struct got_commit_object *commit, const char *idstr,
8884 const char *type, int has_content)
8886 const struct got_error *err = NULL;
8887 char *logmsg = NULL;
8889 err = got_object_commit_get_logmsg(&logmsg, commit);
8890 if (err)
8891 return err;
8893 if (fprintf(f, "%s# log message of %s commit %s:%s",
8894 has_content ? "\n" : "", type, idstr, logmsg) < 0)
8895 err = got_ferror(f, GOT_ERR_IO);
8897 free(logmsg);
8898 return err;
8902 * Lookup "logmsg" references of backed-out and cherrypicked commits
8903 * belonging to the current work tree. If found, and the worktree has
8904 * at least one modified file that was changed in the referenced commit,
8905 * add its log message to a new temporary file at *logmsg_path.
8906 * Add all refs found to matched_refs to be scheduled for removal on
8907 * successful commit.
8909 static const struct got_error *
8910 lookup_logmsg_ref(char **logmsg_path, struct got_pathlist_head *paths,
8911 struct got_reflist_head *matched_refs, struct got_worktree *worktree,
8912 struct got_repository *repo)
8914 const struct got_error *err;
8915 struct got_commit_object *commit = NULL;
8916 struct got_object_id *id = NULL;
8917 struct got_reflist_head refs;
8918 struct got_reflist_entry *re, *re_match;
8919 FILE *f = NULL;
8920 char *uuidstr = NULL;
8921 int added_logmsg = 0;
8923 TAILQ_INIT(&refs);
8925 *logmsg_path = NULL;
8927 err = got_worktree_get_uuid(&uuidstr, worktree);
8928 if (err)
8929 goto done;
8931 err = got_ref_list(&refs, repo, "refs/got/worktree",
8932 got_ref_cmp_by_name, repo);
8933 if (err)
8934 goto done;
8936 TAILQ_FOREACH(re, &refs, entry) {
8937 const char *refname, *type;
8938 struct wt_commitable_path_arg wcpa;
8939 int add_logmsg = 0;
8941 refname = got_ref_get_name(re->ref);
8943 if (strncmp(refname, GOT_WORKTREE_CHERRYPICK_REF_PREFIX,
8944 GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN) == 0) {
8945 refname += GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN + 1;
8946 type = "cherrypicked";
8947 } else if (strncmp(refname, GOT_WORKTREE_BACKOUT_REF_PREFIX,
8948 GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN) == 0) {
8949 refname += GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN + 1;
8950 type = "backed-out";
8951 } else
8952 continue;
8954 if (strncmp(refname, uuidstr, GOT_WORKTREE_UUID_STRLEN) == 0)
8955 refname += GOT_WORKTREE_UUID_STRLEN + 1; /* skip '-' */
8956 else
8957 continue;
8959 err = got_repo_match_object_id(&id, NULL, refname,
8960 GOT_OBJ_TYPE_COMMIT, NULL, repo);
8961 if (err)
8962 goto done;
8964 err = got_object_open_as_commit(&commit, repo, id);
8965 if (err)
8966 goto done;
8968 wcpa.commit_paths = paths;
8969 wcpa.has_changes = &add_logmsg;
8971 err = commit_path_changed_in_worktree(&wcpa, id,
8972 worktree, repo);
8973 if (err)
8974 goto done;
8976 if (add_logmsg) {
8977 if (f == NULL) {
8978 err = got_opentemp_named(logmsg_path, &f,
8979 "got-commit-logmsg", "");
8980 if (err)
8981 goto done;
8983 err = cat_logmsg(f, commit, refname, type,
8984 added_logmsg);
8985 if (err)
8986 goto done;
8987 if (!added_logmsg)
8988 ++added_logmsg;
8990 err = got_reflist_entry_dup(&re_match, re);
8991 if (err)
8992 goto done;
8993 TAILQ_INSERT_HEAD(matched_refs, re_match, entry);
8996 got_object_commit_close(commit);
8997 commit = NULL;
8998 free(id);
8999 id = NULL;
9002 done:
9003 free(id);
9004 free(uuidstr);
9005 got_ref_list_free(&refs);
9006 if (commit)
9007 got_object_commit_close(commit);
9008 if (f && fclose(f) == EOF && err == NULL)
9009 err = got_error_from_errno("fclose");
9010 if (!added_logmsg) {
9011 if (*logmsg_path && unlink(*logmsg_path) != 0 && err == NULL)
9012 err = got_error_from_errno2("unlink", *logmsg_path);
9013 *logmsg_path = NULL;
9015 return err;
9018 static const struct got_error *
9019 cmd_commit(int argc, char *argv[])
9021 const struct got_error *error = NULL;
9022 struct got_worktree *worktree = NULL;
9023 struct got_repository *repo = NULL;
9024 char *cwd = NULL, *id_str = NULL;
9025 struct got_object_id *id = NULL;
9026 const char *logmsg = NULL;
9027 char *prepared_logmsg = NULL, *merged_logmsg = NULL;
9028 struct collect_commit_logmsg_arg cl_arg;
9029 const char *author = NULL;
9030 char *gitconfig_path = NULL, *editor = NULL, *committer = NULL;
9031 int ch, rebase_in_progress, histedit_in_progress, preserve_logmsg = 0;
9032 int allow_bad_symlinks = 0, non_interactive = 0, merge_in_progress = 0;
9033 int show_diff = 1;
9034 struct got_pathlist_head paths;
9035 struct got_reflist_head refs;
9036 struct got_reflist_entry *re;
9037 int *pack_fds = NULL;
9039 TAILQ_INIT(&refs);
9040 TAILQ_INIT(&paths);
9041 cl_arg.logmsg_path = NULL;
9043 while ((ch = getopt(argc, argv, "A:F:m:NnS")) != -1) {
9044 switch (ch) {
9045 case 'A':
9046 author = optarg;
9047 error = valid_author(author);
9048 if (error)
9049 return error;
9050 break;
9051 case 'F':
9052 if (logmsg != NULL)
9053 option_conflict('F', 'm');
9054 prepared_logmsg = realpath(optarg, NULL);
9055 if (prepared_logmsg == NULL)
9056 return got_error_from_errno2("realpath",
9057 optarg);
9058 break;
9059 case 'm':
9060 if (prepared_logmsg)
9061 option_conflict('m', 'F');
9062 logmsg = optarg;
9063 break;
9064 case 'N':
9065 non_interactive = 1;
9066 break;
9067 case 'n':
9068 show_diff = 0;
9069 break;
9070 case 'S':
9071 allow_bad_symlinks = 1;
9072 break;
9073 default:
9074 usage_commit();
9075 /* NOTREACHED */
9079 argc -= optind;
9080 argv += optind;
9082 #ifndef PROFILE
9083 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
9084 "unveil", NULL) == -1)
9085 err(1, "pledge");
9086 #endif
9087 cwd = getcwd(NULL, 0);
9088 if (cwd == NULL) {
9089 error = got_error_from_errno("getcwd");
9090 goto done;
9093 error = got_repo_pack_fds_open(&pack_fds);
9094 if (error != NULL)
9095 goto done;
9097 error = got_worktree_open(&worktree, cwd);
9098 if (error) {
9099 if (error->code == GOT_ERR_NOT_WORKTREE)
9100 error = wrap_not_worktree_error(error, "commit", cwd);
9101 goto done;
9104 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
9105 if (error)
9106 goto done;
9107 if (rebase_in_progress) {
9108 error = got_error(GOT_ERR_REBASING);
9109 goto done;
9112 error = got_worktree_histedit_in_progress(&histedit_in_progress,
9113 worktree);
9114 if (error)
9115 goto done;
9117 error = get_gitconfig_path(&gitconfig_path);
9118 if (error)
9119 goto done;
9120 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
9121 gitconfig_path, pack_fds);
9122 if (error != NULL)
9123 goto done;
9125 error = got_worktree_merge_in_progress(&merge_in_progress, worktree, repo);
9126 if (error)
9127 goto done;
9128 if (merge_in_progress) {
9129 error = got_error(GOT_ERR_MERGE_BUSY);
9130 goto done;
9133 error = get_author(&committer, repo, worktree);
9134 if (error)
9135 goto done;
9137 if (author != NULL && !strcmp(committer, author)) {
9138 error = got_error(GOT_ERR_COMMIT_REDUNDANT_AUTHOR);
9139 goto done;
9142 if (author == NULL)
9143 author = committer;
9146 * unveil(2) traverses exec(2); if an editor is used we have
9147 * to apply unveil after the log message has been written.
9149 if (logmsg == NULL || strlen(logmsg) == 0)
9150 error = get_editor(&editor);
9151 else
9152 error = apply_unveil(got_repo_get_path(repo), 0,
9153 got_worktree_get_root_path(worktree));
9154 if (error)
9155 goto done;
9157 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
9158 if (error)
9159 goto done;
9161 if (prepared_logmsg == NULL) {
9162 error = lookup_logmsg_ref(&merged_logmsg,
9163 argc > 0 ? &paths : NULL, &refs, worktree, repo);
9164 if (error)
9165 goto done;
9168 cl_arg.editor = editor;
9169 cl_arg.cmdline_log = logmsg;
9170 cl_arg.prepared_log = prepared_logmsg;
9171 cl_arg.merged_log = merged_logmsg;
9172 cl_arg.non_interactive = non_interactive;
9173 cl_arg.worktree_path = got_worktree_get_root_path(worktree);
9174 cl_arg.branch_name = got_worktree_get_head_ref_name(worktree);
9175 if (!histedit_in_progress) {
9176 if (strncmp(cl_arg.branch_name, "refs/heads/", 11) != 0) {
9177 error = got_error(GOT_ERR_COMMIT_BRANCH);
9178 goto done;
9180 cl_arg.branch_name += 11;
9182 cl_arg.repo_path = got_repo_get_path(repo);
9183 error = got_worktree_commit(&id, worktree, &paths, author, committer,
9184 allow_bad_symlinks, show_diff, collect_commit_logmsg, &cl_arg,
9185 print_status, NULL, repo);
9186 if (error) {
9187 if (error->code != GOT_ERR_COMMIT_MSG_EMPTY &&
9188 cl_arg.logmsg_path != NULL)
9189 preserve_logmsg = 1;
9190 goto done;
9193 error = got_object_id_str(&id_str, id);
9194 if (error)
9195 goto done;
9196 printf("Created commit %s\n", id_str);
9198 TAILQ_FOREACH(re, &refs, entry) {
9199 error = got_ref_delete(re->ref, repo);
9200 if (error)
9201 goto done;
9204 done:
9205 if (preserve_logmsg) {
9206 fprintf(stderr, "%s: log message preserved in %s\n",
9207 getprogname(), cl_arg.logmsg_path);
9208 } else if (cl_arg.logmsg_path && unlink(cl_arg.logmsg_path) == -1 &&
9209 error == NULL)
9210 error = got_error_from_errno2("unlink", cl_arg.logmsg_path);
9211 free(cl_arg.logmsg_path);
9212 if (merged_logmsg && unlink(merged_logmsg) == -1 && error == NULL)
9213 error = got_error_from_errno2("unlink", merged_logmsg);
9214 free(merged_logmsg);
9215 if (repo) {
9216 const struct got_error *close_err = got_repo_close(repo);
9217 if (error == NULL)
9218 error = close_err;
9220 if (worktree)
9221 got_worktree_close(worktree);
9222 if (pack_fds) {
9223 const struct got_error *pack_err =
9224 got_repo_pack_fds_close(pack_fds);
9225 if (error == NULL)
9226 error = pack_err;
9228 got_ref_list_free(&refs);
9229 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
9230 free(cwd);
9231 free(id_str);
9232 free(gitconfig_path);
9233 free(editor);
9234 free(committer);
9235 free(prepared_logmsg);
9236 return error;
9239 __dead static void
9240 usage_send(void)
9242 fprintf(stderr, "usage: %s send [-afqTv] [-b branch] [-d branch] "
9243 "[-r repository-path] [-t tag] [remote-repository]\n",
9244 getprogname());
9245 exit(1);
9248 static void
9249 print_load_info(int print_colored, int print_found, int print_trees,
9250 int ncolored, int nfound, int ntrees)
9252 if (print_colored) {
9253 printf("%d commit%s colored", ncolored,
9254 ncolored == 1 ? "" : "s");
9256 if (print_found) {
9257 printf("%s%d object%s found",
9258 ncolored > 0 ? "; " : "",
9259 nfound, nfound == 1 ? "" : "s");
9261 if (print_trees) {
9262 printf("; %d tree%s scanned", ntrees,
9263 ntrees == 1 ? "" : "s");
9267 struct got_send_progress_arg {
9268 char last_scaled_packsize[FMT_SCALED_STRSIZE];
9269 int verbosity;
9270 int last_ncolored;
9271 int last_nfound;
9272 int last_ntrees;
9273 int loading_done;
9274 int last_ncommits;
9275 int last_nobj_total;
9276 int last_p_deltify;
9277 int last_p_written;
9278 int last_p_sent;
9279 int printed_something;
9280 int sent_something;
9281 struct got_pathlist_head *delete_branches;
9284 static const struct got_error *
9285 send_progress(void *arg, int ncolored, int nfound, int ntrees,
9286 off_t packfile_size, int ncommits, int nobj_total, int nobj_deltify,
9287 int nobj_written, off_t bytes_sent, const char *refname,
9288 const char *errmsg, int success)
9290 struct got_send_progress_arg *a = arg;
9291 char scaled_packsize[FMT_SCALED_STRSIZE];
9292 char scaled_sent[FMT_SCALED_STRSIZE];
9293 int p_deltify = 0, p_written = 0, p_sent = 0;
9294 int print_colored = 0, print_found = 0, print_trees = 0;
9295 int print_searching = 0, print_total = 0;
9296 int print_deltify = 0, print_written = 0, print_sent = 0;
9298 if (a->verbosity < 0)
9299 return NULL;
9301 if (refname) {
9302 const char *status = success ? "accepted" : "rejected";
9304 if (success) {
9305 struct got_pathlist_entry *pe;
9306 TAILQ_FOREACH(pe, a->delete_branches, entry) {
9307 const char *branchname = pe->path;
9308 if (got_path_cmp(branchname, refname,
9309 strlen(branchname), strlen(refname)) == 0) {
9310 status = "deleted";
9311 a->sent_something = 1;
9312 break;
9317 if (a->printed_something)
9318 putchar('\n');
9319 printf("Server has %s %s", status, refname);
9320 if (errmsg)
9321 printf(": %s", errmsg);
9322 a->printed_something = 1;
9323 return NULL;
9326 if (a->last_ncolored != ncolored) {
9327 print_colored = 1;
9328 a->last_ncolored = ncolored;
9331 if (a->last_nfound != nfound) {
9332 print_colored = 1;
9333 print_found = 1;
9334 a->last_nfound = nfound;
9337 if (a->last_ntrees != ntrees) {
9338 print_colored = 1;
9339 print_found = 1;
9340 print_trees = 1;
9341 a->last_ntrees = ntrees;
9344 if ((print_colored || print_found || print_trees) &&
9345 !a->loading_done) {
9346 printf("\r");
9347 print_load_info(print_colored, print_found, print_trees,
9348 ncolored, nfound, ntrees);
9349 a->printed_something = 1;
9350 fflush(stdout);
9351 return NULL;
9352 } else if (!a->loading_done) {
9353 printf("\r");
9354 print_load_info(1, 1, 1, ncolored, nfound, ntrees);
9355 printf("\n");
9356 a->loading_done = 1;
9359 if (fmt_scaled(packfile_size, scaled_packsize) == -1)
9360 return got_error_from_errno("fmt_scaled");
9361 if (fmt_scaled(bytes_sent, scaled_sent) == -1)
9362 return got_error_from_errno("fmt_scaled");
9364 if (a->last_ncommits != ncommits) {
9365 print_searching = 1;
9366 a->last_ncommits = ncommits;
9369 if (a->last_nobj_total != nobj_total) {
9370 print_searching = 1;
9371 print_total = 1;
9372 a->last_nobj_total = nobj_total;
9375 if (packfile_size > 0 && (a->last_scaled_packsize[0] == '\0' ||
9376 strcmp(scaled_packsize, a->last_scaled_packsize)) != 0) {
9377 if (strlcpy(a->last_scaled_packsize, scaled_packsize,
9378 FMT_SCALED_STRSIZE) >= FMT_SCALED_STRSIZE)
9379 return got_error(GOT_ERR_NO_SPACE);
9382 if (nobj_deltify > 0 || nobj_written > 0) {
9383 if (nobj_deltify > 0) {
9384 p_deltify = (nobj_deltify * 100) / nobj_total;
9385 if (p_deltify != a->last_p_deltify) {
9386 a->last_p_deltify = p_deltify;
9387 print_searching = 1;
9388 print_total = 1;
9389 print_deltify = 1;
9392 if (nobj_written > 0) {
9393 p_written = (nobj_written * 100) / nobj_total;
9394 if (p_written != a->last_p_written) {
9395 a->last_p_written = p_written;
9396 print_searching = 1;
9397 print_total = 1;
9398 print_deltify = 1;
9399 print_written = 1;
9404 if (bytes_sent > 0) {
9405 p_sent = (bytes_sent * 100) / packfile_size;
9406 if (p_sent != a->last_p_sent) {
9407 a->last_p_sent = p_sent;
9408 print_searching = 1;
9409 print_total = 1;
9410 print_deltify = 1;
9411 print_written = 1;
9412 print_sent = 1;
9414 a->sent_something = 1;
9417 if (print_searching || print_total || print_deltify || print_written ||
9418 print_sent)
9419 printf("\r");
9420 if (print_searching)
9421 printf("packing %d reference%s", ncommits,
9422 ncommits == 1 ? "" : "s");
9423 if (print_total)
9424 printf("; %d object%s", nobj_total,
9425 nobj_total == 1 ? "" : "s");
9426 if (print_deltify)
9427 printf("; deltify: %d%%", p_deltify);
9428 if (print_sent)
9429 printf("; uploading pack: %*s %d%%", FMT_SCALED_STRSIZE - 2,
9430 scaled_packsize, p_sent);
9431 else if (print_written)
9432 printf("; writing pack: %*s %d%%", FMT_SCALED_STRSIZE - 2,
9433 scaled_packsize, p_written);
9434 if (print_searching || print_total || print_deltify ||
9435 print_written || print_sent) {
9436 a->printed_something = 1;
9437 fflush(stdout);
9439 return NULL;
9442 static const struct got_error *
9443 cmd_send(int argc, char *argv[])
9445 const struct got_error *error = NULL;
9446 char *cwd = NULL, *repo_path = NULL;
9447 const char *remote_name;
9448 char *proto = NULL, *host = NULL, *port = NULL;
9449 char *repo_name = NULL, *server_path = NULL;
9450 const struct got_remote_repo *remotes, *remote = NULL;
9451 int nremotes, nbranches = 0, ndelete_branches = 0;
9452 struct got_repository *repo = NULL;
9453 struct got_worktree *worktree = NULL;
9454 const struct got_gotconfig *repo_conf = NULL, *worktree_conf = NULL;
9455 struct got_pathlist_head branches;
9456 struct got_pathlist_head tags;
9457 struct got_reflist_head all_branches;
9458 struct got_reflist_head all_tags;
9459 struct got_pathlist_head delete_args;
9460 struct got_pathlist_head delete_branches;
9461 struct got_reflist_entry *re;
9462 struct got_pathlist_entry *pe;
9463 int i, ch, sendfd = -1, sendstatus;
9464 pid_t sendpid = -1;
9465 struct got_send_progress_arg spa;
9466 int verbosity = 0, overwrite_refs = 0;
9467 int send_all_branches = 0, send_all_tags = 0;
9468 struct got_reference *ref = NULL;
9469 int *pack_fds = NULL;
9471 TAILQ_INIT(&branches);
9472 TAILQ_INIT(&tags);
9473 TAILQ_INIT(&all_branches);
9474 TAILQ_INIT(&all_tags);
9475 TAILQ_INIT(&delete_args);
9476 TAILQ_INIT(&delete_branches);
9478 while ((ch = getopt(argc, argv, "ab:d:fqr:Tt:v")) != -1) {
9479 switch (ch) {
9480 case 'a':
9481 send_all_branches = 1;
9482 break;
9483 case 'b':
9484 error = got_pathlist_append(&branches, optarg, NULL);
9485 if (error)
9486 return error;
9487 nbranches++;
9488 break;
9489 case 'd':
9490 error = got_pathlist_append(&delete_args, optarg, NULL);
9491 if (error)
9492 return error;
9493 break;
9494 case 'f':
9495 overwrite_refs = 1;
9496 break;
9497 case 'q':
9498 verbosity = -1;
9499 break;
9500 case 'r':
9501 repo_path = realpath(optarg, NULL);
9502 if (repo_path == NULL)
9503 return got_error_from_errno2("realpath",
9504 optarg);
9505 got_path_strip_trailing_slashes(repo_path);
9506 break;
9507 case 'T':
9508 send_all_tags = 1;
9509 break;
9510 case 't':
9511 error = got_pathlist_append(&tags, optarg, NULL);
9512 if (error)
9513 return error;
9514 break;
9515 case 'v':
9516 if (verbosity < 0)
9517 verbosity = 0;
9518 else if (verbosity < 3)
9519 verbosity++;
9520 break;
9521 default:
9522 usage_send();
9523 /* NOTREACHED */
9526 argc -= optind;
9527 argv += optind;
9529 if (send_all_branches && !TAILQ_EMPTY(&branches))
9530 option_conflict('a', 'b');
9531 if (send_all_tags && !TAILQ_EMPTY(&tags))
9532 option_conflict('T', 't');
9535 if (argc == 0)
9536 remote_name = GOT_SEND_DEFAULT_REMOTE_NAME;
9537 else if (argc == 1)
9538 remote_name = argv[0];
9539 else
9540 usage_send();
9542 cwd = getcwd(NULL, 0);
9543 if (cwd == NULL) {
9544 error = got_error_from_errno("getcwd");
9545 goto done;
9548 error = got_repo_pack_fds_open(&pack_fds);
9549 if (error != NULL)
9550 goto done;
9552 if (repo_path == NULL) {
9553 error = got_worktree_open(&worktree, cwd);
9554 if (error && error->code != GOT_ERR_NOT_WORKTREE)
9555 goto done;
9556 else
9557 error = NULL;
9558 if (worktree) {
9559 repo_path =
9560 strdup(got_worktree_get_repo_path(worktree));
9561 if (repo_path == NULL)
9562 error = got_error_from_errno("strdup");
9563 if (error)
9564 goto done;
9565 } else {
9566 repo_path = strdup(cwd);
9567 if (repo_path == NULL) {
9568 error = got_error_from_errno("strdup");
9569 goto done;
9574 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
9575 if (error)
9576 goto done;
9578 if (worktree) {
9579 worktree_conf = got_worktree_get_gotconfig(worktree);
9580 if (worktree_conf) {
9581 got_gotconfig_get_remotes(&nremotes, &remotes,
9582 worktree_conf);
9583 for (i = 0; i < nremotes; i++) {
9584 if (strcmp(remotes[i].name, remote_name) == 0) {
9585 remote = &remotes[i];
9586 break;
9591 if (remote == NULL) {
9592 repo_conf = got_repo_get_gotconfig(repo);
9593 if (repo_conf) {
9594 got_gotconfig_get_remotes(&nremotes, &remotes,
9595 repo_conf);
9596 for (i = 0; i < nremotes; i++) {
9597 if (strcmp(remotes[i].name, remote_name) == 0) {
9598 remote = &remotes[i];
9599 break;
9604 if (remote == NULL) {
9605 got_repo_get_gitconfig_remotes(&nremotes, &remotes, repo);
9606 for (i = 0; i < nremotes; i++) {
9607 if (strcmp(remotes[i].name, remote_name) == 0) {
9608 remote = &remotes[i];
9609 break;
9613 if (remote == NULL) {
9614 error = got_error_path(remote_name, GOT_ERR_NO_REMOTE);
9615 goto done;
9618 error = got_dial_parse_uri(&proto, &host, &port, &server_path,
9619 &repo_name, remote->send_url);
9620 if (error)
9621 goto done;
9623 if (strcmp(proto, "git") == 0) {
9624 #ifndef PROFILE
9625 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
9626 "sendfd dns inet unveil", NULL) == -1)
9627 err(1, "pledge");
9628 #endif
9629 } else if (strcmp(proto, "git+ssh") == 0 ||
9630 strcmp(proto, "ssh") == 0) {
9631 #ifndef PROFILE
9632 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
9633 "sendfd unveil", NULL) == -1)
9634 err(1, "pledge");
9635 #endif
9636 } else if (strcmp(proto, "http") == 0 ||
9637 strcmp(proto, "git+http") == 0) {
9638 error = got_error_path(proto, GOT_ERR_NOT_IMPL);
9639 goto done;
9640 } else {
9641 error = got_error_path(proto, GOT_ERR_BAD_PROTO);
9642 goto done;
9645 error = got_dial_apply_unveil(proto);
9646 if (error)
9647 goto done;
9649 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
9650 if (error)
9651 goto done;
9653 if (send_all_branches) {
9654 error = got_ref_list(&all_branches, repo, "refs/heads",
9655 got_ref_cmp_by_name, NULL);
9656 if (error)
9657 goto done;
9658 TAILQ_FOREACH(re, &all_branches, entry) {
9659 const char *branchname = got_ref_get_name(re->ref);
9660 error = got_pathlist_append(&branches,
9661 branchname, NULL);
9662 if (error)
9663 goto done;
9664 nbranches++;
9666 } else if (nbranches == 0) {
9667 for (i = 0; i < remote->nsend_branches; i++) {
9668 error = got_pathlist_append(&branches,
9669 remote->send_branches[i], NULL);
9670 if (error)
9671 goto done;
9675 if (send_all_tags) {
9676 error = got_ref_list(&all_tags, repo, "refs/tags",
9677 got_ref_cmp_by_name, NULL);
9678 if (error)
9679 goto done;
9680 TAILQ_FOREACH(re, &all_tags, entry) {
9681 const char *tagname = got_ref_get_name(re->ref);
9682 error = got_pathlist_append(&tags,
9683 tagname, NULL);
9684 if (error)
9685 goto done;
9690 * To prevent accidents only branches in refs/heads/ can be deleted
9691 * with 'got send -d'.
9692 * Deleting anything else requires local repository access or Git.
9694 TAILQ_FOREACH(pe, &delete_args, entry) {
9695 const char *branchname = pe->path;
9696 char *s;
9697 struct got_pathlist_entry *new;
9698 if (strncmp(branchname, "refs/heads/", 11) == 0) {
9699 s = strdup(branchname);
9700 if (s == NULL) {
9701 error = got_error_from_errno("strdup");
9702 goto done;
9704 } else {
9705 if (asprintf(&s, "refs/heads/%s", branchname) == -1) {
9706 error = got_error_from_errno("asprintf");
9707 goto done;
9710 error = got_pathlist_insert(&new, &delete_branches, s, NULL);
9711 if (error || new == NULL /* duplicate */)
9712 free(s);
9713 if (error)
9714 goto done;
9715 ndelete_branches++;
9718 if (nbranches == 0 && ndelete_branches == 0) {
9719 struct got_reference *head_ref;
9720 if (worktree)
9721 error = got_ref_open(&head_ref, repo,
9722 got_worktree_get_head_ref_name(worktree), 0);
9723 else
9724 error = got_ref_open(&head_ref, repo, GOT_REF_HEAD, 0);
9725 if (error)
9726 goto done;
9727 if (got_ref_is_symbolic(head_ref)) {
9728 error = got_ref_resolve_symbolic(&ref, repo, head_ref);
9729 got_ref_close(head_ref);
9730 if (error)
9731 goto done;
9732 } else
9733 ref = head_ref;
9734 error = got_pathlist_append(&branches, got_ref_get_name(ref),
9735 NULL);
9736 if (error)
9737 goto done;
9738 nbranches++;
9741 if (verbosity >= 0) {
9742 printf("Connecting to \"%s\" %s://%s%s%s%s%s\n",
9743 remote->name, proto, host,
9744 port ? ":" : "", port ? port : "",
9745 *server_path == '/' ? "" : "/", server_path);
9748 error = got_send_connect(&sendpid, &sendfd, proto, host, port,
9749 server_path, verbosity);
9750 if (error)
9751 goto done;
9753 memset(&spa, 0, sizeof(spa));
9754 spa.last_scaled_packsize[0] = '\0';
9755 spa.last_p_deltify = -1;
9756 spa.last_p_written = -1;
9757 spa.verbosity = verbosity;
9758 spa.delete_branches = &delete_branches;
9759 error = got_send_pack(remote_name, &branches, &tags, &delete_branches,
9760 verbosity, overwrite_refs, sendfd, repo, send_progress, &spa,
9761 check_cancelled, NULL);
9762 if (spa.printed_something)
9763 putchar('\n');
9764 if (error)
9765 goto done;
9766 if (!spa.sent_something && verbosity >= 0)
9767 printf("Already up-to-date\n");
9768 done:
9769 if (sendpid > 0) {
9770 if (kill(sendpid, SIGTERM) == -1)
9771 error = got_error_from_errno("kill");
9772 if (waitpid(sendpid, &sendstatus, 0) == -1 && error == NULL)
9773 error = got_error_from_errno("waitpid");
9775 if (sendfd != -1 && close(sendfd) == -1 && error == NULL)
9776 error = got_error_from_errno("close");
9777 if (repo) {
9778 const struct got_error *close_err = got_repo_close(repo);
9779 if (error == NULL)
9780 error = close_err;
9782 if (worktree)
9783 got_worktree_close(worktree);
9784 if (pack_fds) {
9785 const struct got_error *pack_err =
9786 got_repo_pack_fds_close(pack_fds);
9787 if (error == NULL)
9788 error = pack_err;
9790 if (ref)
9791 got_ref_close(ref);
9792 got_pathlist_free(&branches, GOT_PATHLIST_FREE_NONE);
9793 got_pathlist_free(&tags, GOT_PATHLIST_FREE_NONE);
9794 got_ref_list_free(&all_branches);
9795 got_ref_list_free(&all_tags);
9796 got_pathlist_free(&delete_args, GOT_PATHLIST_FREE_NONE);
9797 got_pathlist_free(&delete_branches, GOT_PATHLIST_FREE_PATH);
9798 free(cwd);
9799 free(repo_path);
9800 free(proto);
9801 free(host);
9802 free(port);
9803 free(server_path);
9804 free(repo_name);
9805 return error;
9809 * Print and if delete is set delete all ref_prefix references.
9810 * If wanted_ref is not NULL, only print or delete this reference.
9812 static const struct got_error *
9813 process_logmsg_refs(const char *ref_prefix, size_t prefix_len,
9814 const char *wanted_ref, int delete, struct got_worktree *worktree,
9815 struct got_repository *repo)
9817 const struct got_error *err;
9818 struct got_pathlist_head paths;
9819 struct got_reflist_head refs;
9820 struct got_reflist_entry *re;
9821 struct got_reflist_object_id_map *refs_idmap = NULL;
9822 struct got_commit_object *commit = NULL;
9823 struct got_object_id *id = NULL;
9824 const char *header_prefix;
9825 char *uuidstr = NULL;
9826 int found = 0;
9828 TAILQ_INIT(&refs);
9829 TAILQ_INIT(&paths);
9831 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, repo);
9832 if (err)
9833 goto done;
9835 err = got_reflist_object_id_map_create(&refs_idmap, &refs, repo);
9836 if (err)
9837 goto done;
9839 if (worktree != NULL) {
9840 err = got_worktree_get_uuid(&uuidstr, worktree);
9841 if (err)
9842 goto done;
9845 if (wanted_ref) {
9846 if (strncmp(wanted_ref, "refs/heads/", 11) == 0)
9847 wanted_ref += 11;
9850 if (strcmp(ref_prefix, GOT_WORKTREE_BACKOUT_REF_PREFIX) == 0)
9851 header_prefix = "backout";
9852 else
9853 header_prefix = "cherrypick";
9855 TAILQ_FOREACH(re, &refs, entry) {
9856 const char *refname, *wt;
9858 refname = got_ref_get_name(re->ref);
9860 err = check_cancelled(NULL);
9861 if (err)
9862 goto done;
9864 if (strncmp(refname, ref_prefix, prefix_len) == 0)
9865 refname += prefix_len + 1; /* skip '-' delimiter */
9866 else
9867 continue;
9869 wt = refname;
9871 if (worktree == NULL || strncmp(refname, uuidstr,
9872 GOT_WORKTREE_UUID_STRLEN) == 0)
9873 refname += GOT_WORKTREE_UUID_STRLEN + 1; /* skip '-' */
9874 else
9875 continue;
9877 err = got_repo_match_object_id(&id, NULL, refname,
9878 GOT_OBJ_TYPE_COMMIT, NULL, repo);
9879 if (err)
9880 goto done;
9882 err = got_object_open_as_commit(&commit, repo, id);
9883 if (err)
9884 goto done;
9886 if (wanted_ref)
9887 found = strncmp(wanted_ref, refname,
9888 strlen(wanted_ref)) == 0;
9889 if (wanted_ref && !found) {
9890 struct got_reflist_head *ci_refs;
9892 ci_refs = got_reflist_object_id_map_lookup(refs_idmap,
9893 id);
9895 if (ci_refs) {
9896 char *refs_str = NULL;
9897 char const *r = NULL;
9899 err = build_refs_str(&refs_str, ci_refs, id,
9900 repo, 1);
9901 if (err)
9902 goto done;
9904 r = refs_str;
9905 while (r) {
9906 if (strncmp(r, wanted_ref,
9907 strlen(wanted_ref)) == 0) {
9908 found = 1;
9909 break;
9911 r = strchr(r, ' ');
9912 if (r)
9913 ++r;
9915 free(refs_str);
9919 if (wanted_ref == NULL || found) {
9920 if (delete) {
9921 err = got_ref_delete(re->ref, repo);
9922 if (err)
9923 goto done;
9924 printf("Deleted: ");
9925 err = print_commit_oneline(commit, id, repo,
9926 refs_idmap);
9927 } else {
9929 * Print paths modified by commit to help
9930 * associate commits with worktree changes.
9932 err = get_changed_paths(&paths, commit,
9933 repo, NULL);
9934 if (err)
9935 goto done;
9937 err = print_commit(commit, id, repo, NULL,
9938 &paths, NULL, 0, 0, refs_idmap, NULL,
9939 header_prefix);
9940 got_pathlist_free(&paths,
9941 GOT_PATHLIST_FREE_ALL);
9943 if (worktree == NULL)
9944 printf("work tree: %.*s\n\n",
9945 GOT_WORKTREE_UUID_STRLEN, wt);
9947 if (err || found)
9948 goto done;
9951 got_object_commit_close(commit);
9952 commit = NULL;
9953 free(id);
9954 id = NULL;
9957 if (wanted_ref != NULL && !found)
9958 err = got_error_fmt(GOT_ERR_NOT_REF, "%s", wanted_ref);
9960 done:
9961 free(id);
9962 free(uuidstr);
9963 got_ref_list_free(&refs);
9964 got_pathlist_free(&paths, GOT_PATHLIST_FREE_ALL);
9965 if (refs_idmap)
9966 got_reflist_object_id_map_free(refs_idmap);
9967 if (commit)
9968 got_object_commit_close(commit);
9969 return err;
9973 * Create new temp "logmsg" ref of the backed-out or cherrypicked commit
9974 * identified by id for log messages to prepopulate the editor on commit.
9976 static const struct got_error *
9977 logmsg_ref(struct got_object_id *id, const char *prefix,
9978 struct got_worktree *worktree, struct got_repository *repo)
9980 const struct got_error *err = NULL;
9981 char *idstr, *ref = NULL, *refname = NULL;
9982 int histedit_in_progress;
9983 int rebase_in_progress, merge_in_progress;
9986 * Silenty refuse to create merge reference if any histedit, merge,
9987 * or rebase operation is in progress.
9989 err = got_worktree_histedit_in_progress(&histedit_in_progress,
9990 worktree);
9991 if (err)
9992 return err;
9993 if (histedit_in_progress)
9994 return NULL;
9996 err = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
9997 if (err)
9998 return err;
9999 if (rebase_in_progress)
10000 return NULL;
10002 err = got_worktree_merge_in_progress(&merge_in_progress, worktree,
10003 repo);
10004 if (err)
10005 return err;
10006 if (merge_in_progress)
10007 return NULL;
10009 err = got_object_id_str(&idstr, id);
10010 if (err)
10011 return err;
10013 err = got_worktree_get_logmsg_ref_name(&refname, worktree, prefix);
10014 if (err)
10015 goto done;
10017 if (asprintf(&ref, "%s-%s", refname, idstr) == -1) {
10018 err = got_error_from_errno("asprintf");
10019 goto done;
10022 err = create_ref(ref, got_worktree_get_base_commit_id(worktree),
10023 -1, repo);
10024 done:
10025 free(ref);
10026 free(idstr);
10027 free(refname);
10028 return err;
10031 __dead static void
10032 usage_cherrypick(void)
10034 fprintf(stderr, "usage: %s cherrypick [-lX] [commit-id]\n",
10035 getprogname());
10036 exit(1);
10039 static const struct got_error *
10040 cmd_cherrypick(int argc, char *argv[])
10042 const struct got_error *error = NULL;
10043 struct got_worktree *worktree = NULL;
10044 struct got_repository *repo = NULL;
10045 char *cwd = NULL, *commit_id_str = NULL;
10046 struct got_object_id *commit_id = NULL;
10047 struct got_commit_object *commit = NULL;
10048 struct got_object_qid *pid;
10049 int ch, list_refs = 0, remove_refs = 0;
10050 struct got_update_progress_arg upa;
10051 int *pack_fds = NULL;
10053 while ((ch = getopt(argc, argv, "lX")) != -1) {
10054 switch (ch) {
10055 case 'l':
10056 list_refs = 1;
10057 break;
10058 case 'X':
10059 remove_refs = 1;
10060 break;
10061 default:
10062 usage_cherrypick();
10063 /* NOTREACHED */
10067 argc -= optind;
10068 argv += optind;
10070 #ifndef PROFILE
10071 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
10072 "unveil", NULL) == -1)
10073 err(1, "pledge");
10074 #endif
10075 if (list_refs || remove_refs) {
10076 if (argc != 0 && argc != 1)
10077 usage_cherrypick();
10078 } else if (argc != 1)
10079 usage_cherrypick();
10080 if (list_refs && remove_refs)
10081 option_conflict('l', 'X');
10083 cwd = getcwd(NULL, 0);
10084 if (cwd == NULL) {
10085 error = got_error_from_errno("getcwd");
10086 goto done;
10089 error = got_repo_pack_fds_open(&pack_fds);
10090 if (error != NULL)
10091 goto done;
10093 error = got_worktree_open(&worktree, cwd);
10094 if (error) {
10095 if (list_refs || remove_refs) {
10096 if (error->code != GOT_ERR_NOT_WORKTREE)
10097 goto done;
10098 } else {
10099 if (error->code == GOT_ERR_NOT_WORKTREE)
10100 error = wrap_not_worktree_error(error,
10101 "cherrypick", cwd);
10102 goto done;
10106 error = got_repo_open(&repo,
10107 worktree ? got_worktree_get_repo_path(worktree) : cwd,
10108 NULL, pack_fds);
10109 if (error != NULL)
10110 goto done;
10112 error = apply_unveil(got_repo_get_path(repo), 0,
10113 worktree ? got_worktree_get_root_path(worktree) : NULL);
10114 if (error)
10115 goto done;
10117 if (list_refs || remove_refs) {
10118 error = process_logmsg_refs(GOT_WORKTREE_CHERRYPICK_REF_PREFIX,
10119 GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN,
10120 argc == 1 ? argv[0] : NULL, remove_refs, worktree, repo);
10121 goto done;
10124 error = got_repo_match_object_id(&commit_id, NULL, argv[0],
10125 GOT_OBJ_TYPE_COMMIT, NULL, repo);
10126 if (error)
10127 goto done;
10128 error = got_object_id_str(&commit_id_str, commit_id);
10129 if (error)
10130 goto done;
10132 error = got_object_open_as_commit(&commit, repo, commit_id);
10133 if (error)
10134 goto done;
10135 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
10136 memset(&upa, 0, sizeof(upa));
10137 error = got_worktree_merge_files(worktree, pid ? &pid->id : NULL,
10138 commit_id, repo, update_progress, &upa, check_cancelled,
10139 NULL);
10140 if (error != NULL)
10141 goto done;
10143 if (upa.did_something) {
10144 error = logmsg_ref(commit_id,
10145 GOT_WORKTREE_CHERRYPICK_REF_PREFIX, worktree, repo);
10146 if (error)
10147 goto done;
10148 printf("Merged commit %s\n", commit_id_str);
10150 print_merge_progress_stats(&upa);
10151 done:
10152 free(cwd);
10153 if (commit)
10154 got_object_commit_close(commit);
10155 free(commit_id_str);
10156 if (worktree)
10157 got_worktree_close(worktree);
10158 if (repo) {
10159 const struct got_error *close_err = got_repo_close(repo);
10160 if (error == NULL)
10161 error = close_err;
10163 if (pack_fds) {
10164 const struct got_error *pack_err =
10165 got_repo_pack_fds_close(pack_fds);
10166 if (error == NULL)
10167 error = pack_err;
10170 return error;
10173 __dead static void
10174 usage_backout(void)
10176 fprintf(stderr, "usage: %s backout [-lX] [commit-id]\n", getprogname());
10177 exit(1);
10180 static const struct got_error *
10181 cmd_backout(int argc, char *argv[])
10183 const struct got_error *error = NULL;
10184 struct got_worktree *worktree = NULL;
10185 struct got_repository *repo = NULL;
10186 char *cwd = NULL, *commit_id_str = NULL;
10187 struct got_object_id *commit_id = NULL;
10188 struct got_commit_object *commit = NULL;
10189 struct got_object_qid *pid;
10190 int ch, list_refs = 0, remove_refs = 0;
10191 struct got_update_progress_arg upa;
10192 int *pack_fds = NULL;
10194 while ((ch = getopt(argc, argv, "lX")) != -1) {
10195 switch (ch) {
10196 case 'l':
10197 list_refs = 1;
10198 break;
10199 case 'X':
10200 remove_refs = 1;
10201 break;
10202 default:
10203 usage_backout();
10204 /* NOTREACHED */
10208 argc -= optind;
10209 argv += optind;
10211 #ifndef PROFILE
10212 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
10213 "unveil", NULL) == -1)
10214 err(1, "pledge");
10215 #endif
10216 if (list_refs || remove_refs) {
10217 if (argc != 0 && argc != 1)
10218 usage_backout();
10219 } else if (argc != 1)
10220 usage_backout();
10221 if (list_refs && remove_refs)
10222 option_conflict('l', 'X');
10224 cwd = getcwd(NULL, 0);
10225 if (cwd == NULL) {
10226 error = got_error_from_errno("getcwd");
10227 goto done;
10230 error = got_repo_pack_fds_open(&pack_fds);
10231 if (error != NULL)
10232 goto done;
10234 error = got_worktree_open(&worktree, cwd);
10235 if (error) {
10236 if (list_refs || remove_refs) {
10237 if (error->code != GOT_ERR_NOT_WORKTREE)
10238 goto done;
10239 } else {
10240 if (error->code == GOT_ERR_NOT_WORKTREE)
10241 error = wrap_not_worktree_error(error,
10242 "backout", cwd);
10243 goto done;
10247 error = got_repo_open(&repo,
10248 worktree ? got_worktree_get_repo_path(worktree) : cwd,
10249 NULL, pack_fds);
10250 if (error != NULL)
10251 goto done;
10253 error = apply_unveil(got_repo_get_path(repo), 0,
10254 worktree ? got_worktree_get_root_path(worktree) : NULL);
10255 if (error)
10256 goto done;
10258 if (list_refs || remove_refs) {
10259 error = process_logmsg_refs(GOT_WORKTREE_BACKOUT_REF_PREFIX,
10260 GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN,
10261 argc == 1 ? argv[0] : NULL, remove_refs, worktree, repo);
10262 goto done;
10265 error = got_repo_match_object_id(&commit_id, NULL, argv[0],
10266 GOT_OBJ_TYPE_COMMIT, NULL, repo);
10267 if (error)
10268 goto done;
10269 error = got_object_id_str(&commit_id_str, commit_id);
10270 if (error)
10271 goto done;
10273 error = got_object_open_as_commit(&commit, repo, commit_id);
10274 if (error)
10275 goto done;
10276 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
10277 if (pid == NULL) {
10278 error = got_error(GOT_ERR_ROOT_COMMIT);
10279 goto done;
10282 memset(&upa, 0, sizeof(upa));
10283 error = got_worktree_merge_files(worktree, commit_id, &pid->id,
10284 repo, update_progress, &upa, check_cancelled, NULL);
10285 if (error != NULL)
10286 goto done;
10288 if (upa.did_something) {
10289 error = logmsg_ref(commit_id, GOT_WORKTREE_BACKOUT_REF_PREFIX,
10290 worktree, repo);
10291 if (error)
10292 goto done;
10293 printf("Backed out commit %s\n", commit_id_str);
10295 print_merge_progress_stats(&upa);
10296 done:
10297 free(cwd);
10298 if (commit)
10299 got_object_commit_close(commit);
10300 free(commit_id_str);
10301 if (worktree)
10302 got_worktree_close(worktree);
10303 if (repo) {
10304 const struct got_error *close_err = got_repo_close(repo);
10305 if (error == NULL)
10306 error = close_err;
10308 if (pack_fds) {
10309 const struct got_error *pack_err =
10310 got_repo_pack_fds_close(pack_fds);
10311 if (error == NULL)
10312 error = pack_err;
10314 return error;
10317 __dead static void
10318 usage_rebase(void)
10320 fprintf(stderr, "usage: %s rebase [-aclX] [branch]\n", getprogname());
10321 exit(1);
10324 static void
10325 trim_logmsg(char *logmsg, int limit)
10327 char *nl;
10328 size_t len;
10330 len = strlen(logmsg);
10331 if (len > limit)
10332 len = limit;
10333 logmsg[len] = '\0';
10334 nl = strchr(logmsg, '\n');
10335 if (nl)
10336 *nl = '\0';
10339 static const struct got_error *
10340 get_short_logmsg(char **logmsg, int limit, struct got_commit_object *commit)
10342 const struct got_error *err;
10343 char *logmsg0 = NULL;
10344 const char *s;
10346 err = got_object_commit_get_logmsg(&logmsg0, commit);
10347 if (err)
10348 return err;
10350 s = logmsg0;
10351 while (isspace((unsigned char)s[0]))
10352 s++;
10354 *logmsg = strdup(s);
10355 if (*logmsg == NULL) {
10356 err = got_error_from_errno("strdup");
10357 goto done;
10360 trim_logmsg(*logmsg, limit);
10361 done:
10362 free(logmsg0);
10363 return err;
10366 static const struct got_error *
10367 show_rebase_merge_conflict(struct got_object_id *id,
10368 struct got_repository *repo)
10370 const struct got_error *err;
10371 struct got_commit_object *commit = NULL;
10372 char *id_str = NULL, *logmsg = NULL;
10374 err = got_object_open_as_commit(&commit, repo, id);
10375 if (err)
10376 return err;
10378 err = got_object_id_str(&id_str, id);
10379 if (err)
10380 goto done;
10382 id_str[12] = '\0';
10384 err = get_short_logmsg(&logmsg, 42, commit);
10385 if (err)
10386 goto done;
10388 printf("%s -> merge conflict: %s\n", id_str, logmsg);
10389 done:
10390 free(id_str);
10391 got_object_commit_close(commit);
10392 free(logmsg);
10393 return err;
10396 static const struct got_error *
10397 show_rebase_progress(struct got_commit_object *commit,
10398 struct got_object_id *old_id, struct got_object_id *new_id)
10400 const struct got_error *err;
10401 char *old_id_str = NULL, *new_id_str = NULL, *logmsg = NULL;
10403 err = got_object_id_str(&old_id_str, old_id);
10404 if (err)
10405 goto done;
10407 if (new_id) {
10408 err = got_object_id_str(&new_id_str, new_id);
10409 if (err)
10410 goto done;
10413 old_id_str[12] = '\0';
10414 if (new_id_str)
10415 new_id_str[12] = '\0';
10417 err = get_short_logmsg(&logmsg, 42, commit);
10418 if (err)
10419 goto done;
10421 printf("%s -> %s: %s\n", old_id_str,
10422 new_id_str ? new_id_str : "no-op change", logmsg);
10423 done:
10424 free(old_id_str);
10425 free(new_id_str);
10426 free(logmsg);
10427 return err;
10430 static const struct got_error *
10431 rebase_complete(struct got_worktree *worktree, struct got_fileindex *fileindex,
10432 struct got_reference *branch, struct got_reference *tmp_branch,
10433 struct got_repository *repo, int create_backup)
10435 printf("Switching work tree to %s\n", got_ref_get_name(branch));
10436 return got_worktree_rebase_complete(worktree, fileindex,
10437 tmp_branch, branch, repo, create_backup);
10440 static const struct got_error *
10441 rebase_commit(struct got_pathlist_head *merged_paths,
10442 struct got_worktree *worktree, struct got_fileindex *fileindex,
10443 struct got_reference *tmp_branch, const char *committer,
10444 struct got_object_id *commit_id, struct got_repository *repo)
10446 const struct got_error *error;
10447 struct got_commit_object *commit;
10448 struct got_object_id *new_commit_id;
10450 error = got_object_open_as_commit(&commit, repo, commit_id);
10451 if (error)
10452 return error;
10454 error = got_worktree_rebase_commit(&new_commit_id, merged_paths,
10455 worktree, fileindex, tmp_branch, committer, commit, commit_id,
10456 repo);
10457 if (error) {
10458 if (error->code != GOT_ERR_COMMIT_NO_CHANGES)
10459 goto done;
10460 error = show_rebase_progress(commit, commit_id, NULL);
10461 } else {
10462 error = show_rebase_progress(commit, commit_id, new_commit_id);
10463 free(new_commit_id);
10465 done:
10466 got_object_commit_close(commit);
10467 return error;
10470 struct check_path_prefix_arg {
10471 const char *path_prefix;
10472 size_t len;
10473 int errcode;
10476 static const struct got_error *
10477 check_path_prefix_in_diff(void *arg, struct got_blob_object *blob1,
10478 struct got_blob_object *blob2, FILE *f1, FILE *f2,
10479 struct got_object_id *id1, struct got_object_id *id2,
10480 const char *path1, const char *path2,
10481 mode_t mode1, mode_t mode2, struct got_repository *repo)
10483 struct check_path_prefix_arg *a = arg;
10485 if ((path1 && !got_path_is_child(path1, a->path_prefix, a->len)) ||
10486 (path2 && !got_path_is_child(path2, a->path_prefix, a->len)))
10487 return got_error(a->errcode);
10489 return NULL;
10492 static const struct got_error *
10493 check_path_prefix(struct got_object_id *parent_id,
10494 struct got_object_id *commit_id, const char *path_prefix,
10495 int errcode, struct got_repository *repo)
10497 const struct got_error *err;
10498 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
10499 struct got_commit_object *commit = NULL, *parent_commit = NULL;
10500 struct check_path_prefix_arg cpp_arg;
10502 if (got_path_is_root_dir(path_prefix))
10503 return NULL;
10505 err = got_object_open_as_commit(&commit, repo, commit_id);
10506 if (err)
10507 goto done;
10509 err = got_object_open_as_commit(&parent_commit, repo, parent_id);
10510 if (err)
10511 goto done;
10513 err = got_object_open_as_tree(&tree1, repo,
10514 got_object_commit_get_tree_id(parent_commit));
10515 if (err)
10516 goto done;
10518 err = got_object_open_as_tree(&tree2, repo,
10519 got_object_commit_get_tree_id(commit));
10520 if (err)
10521 goto done;
10523 cpp_arg.path_prefix = path_prefix;
10524 while (cpp_arg.path_prefix[0] == '/')
10525 cpp_arg.path_prefix++;
10526 cpp_arg.len = strlen(cpp_arg.path_prefix);
10527 cpp_arg.errcode = errcode;
10528 err = got_diff_tree(tree1, tree2, NULL, NULL, -1, -1, "", "", repo,
10529 check_path_prefix_in_diff, &cpp_arg, 0);
10530 done:
10531 if (tree1)
10532 got_object_tree_close(tree1);
10533 if (tree2)
10534 got_object_tree_close(tree2);
10535 if (commit)
10536 got_object_commit_close(commit);
10537 if (parent_commit)
10538 got_object_commit_close(parent_commit);
10539 return err;
10542 static const struct got_error *
10543 collect_commits(struct got_object_id_queue *commits,
10544 struct got_object_id *initial_commit_id,
10545 struct got_object_id *iter_start_id, struct got_object_id *iter_stop_id,
10546 const char *path_prefix, int path_prefix_errcode,
10547 struct got_repository *repo)
10549 const struct got_error *err = NULL;
10550 struct got_commit_graph *graph = NULL;
10551 struct got_object_id parent_id, commit_id;
10552 struct got_object_qid *qid;
10554 err = got_commit_graph_open(&graph, "/", 1);
10555 if (err)
10556 return err;
10558 err = got_commit_graph_iter_start(graph, iter_start_id, repo,
10559 check_cancelled, NULL);
10560 if (err)
10561 goto done;
10563 memcpy(&commit_id, initial_commit_id, sizeof(commit_id));
10564 while (got_object_id_cmp(&commit_id, iter_stop_id) != 0) {
10565 err = got_commit_graph_iter_next(&parent_id, graph, repo,
10566 check_cancelled, NULL);
10567 if (err) {
10568 if (err->code == GOT_ERR_ITER_COMPLETED) {
10569 err = got_error_msg(GOT_ERR_ANCESTRY,
10570 "ran out of commits to rebase before "
10571 "youngest common ancestor commit has "
10572 "been reached?!?");
10574 goto done;
10575 } else {
10576 err = check_path_prefix(&parent_id, &commit_id,
10577 path_prefix, path_prefix_errcode, repo);
10578 if (err)
10579 goto done;
10581 err = got_object_qid_alloc(&qid, &commit_id);
10582 if (err)
10583 goto done;
10584 STAILQ_INSERT_HEAD(commits, qid, entry);
10586 memcpy(&commit_id, &parent_id, sizeof(commit_id));
10589 done:
10590 got_commit_graph_close(graph);
10591 return err;
10594 static const struct got_error *
10595 get_commit_brief_str(char **brief_str, struct got_commit_object *commit)
10597 const struct got_error *err = NULL;
10598 time_t committer_time;
10599 struct tm tm;
10600 char datebuf[11]; /* YYYY-MM-DD + NUL */
10601 char *author0 = NULL, *author, *smallerthan;
10602 char *logmsg0 = NULL, *logmsg, *newline;
10604 committer_time = got_object_commit_get_committer_time(commit);
10605 if (gmtime_r(&committer_time, &tm) == NULL)
10606 return got_error_from_errno("gmtime_r");
10607 if (strftime(datebuf, sizeof(datebuf), "%G-%m-%d", &tm) == 0)
10608 return got_error(GOT_ERR_NO_SPACE);
10610 author0 = strdup(got_object_commit_get_author(commit));
10611 if (author0 == NULL)
10612 return got_error_from_errno("strdup");
10613 author = author0;
10614 smallerthan = strchr(author, '<');
10615 if (smallerthan && smallerthan[1] != '\0')
10616 author = smallerthan + 1;
10617 author[strcspn(author, "@>")] = '\0';
10619 err = got_object_commit_get_logmsg(&logmsg0, commit);
10620 if (err)
10621 goto done;
10622 logmsg = logmsg0;
10623 while (*logmsg == '\n')
10624 logmsg++;
10625 newline = strchr(logmsg, '\n');
10626 if (newline)
10627 *newline = '\0';
10629 if (asprintf(brief_str, "%s %s %s",
10630 datebuf, author, logmsg) == -1)
10631 err = got_error_from_errno("asprintf");
10632 done:
10633 free(author0);
10634 free(logmsg0);
10635 return err;
10638 static const struct got_error *
10639 delete_backup_ref(struct got_reference *ref, struct got_object_id *id,
10640 struct got_repository *repo)
10642 const struct got_error *err;
10643 char *id_str;
10645 err = got_object_id_str(&id_str, id);
10646 if (err)
10647 return err;
10649 err = got_ref_delete(ref, repo);
10650 if (err)
10651 goto done;
10653 printf("Deleted %s: %s\n", got_ref_get_name(ref), id_str);
10654 done:
10655 free(id_str);
10656 return err;
10659 static const struct got_error *
10660 print_backup_ref(const char *branch_name, const char *new_id_str,
10661 struct got_object_id *old_commit_id, struct got_commit_object *old_commit,
10662 struct got_reflist_object_id_map *refs_idmap,
10663 struct got_repository *repo)
10665 const struct got_error *err = NULL;
10666 struct got_reflist_head *refs;
10667 char *refs_str = NULL;
10668 struct got_object_id *new_commit_id = NULL;
10669 struct got_commit_object *new_commit = NULL;
10670 char *new_commit_brief_str = NULL;
10671 struct got_object_id *yca_id = NULL;
10672 struct got_commit_object *yca_commit = NULL;
10673 char *yca_id_str = NULL, *yca_brief_str = NULL;
10674 char *custom_refs_str;
10676 if (asprintf(&custom_refs_str, "formerly %s", branch_name) == -1)
10677 return got_error_from_errno("asprintf");
10679 err = print_commit(old_commit, old_commit_id, repo, NULL, NULL, NULL,
10680 0, 0, refs_idmap, custom_refs_str, NULL);
10681 if (err)
10682 goto done;
10684 err = got_object_resolve_id_str(&new_commit_id, repo, new_id_str);
10685 if (err)
10686 goto done;
10688 refs = got_reflist_object_id_map_lookup(refs_idmap, new_commit_id);
10689 if (refs) {
10690 err = build_refs_str(&refs_str, refs, new_commit_id, repo, 0);
10691 if (err)
10692 goto done;
10695 err = got_object_open_as_commit(&new_commit, repo, new_commit_id);
10696 if (err)
10697 goto done;
10699 err = get_commit_brief_str(&new_commit_brief_str, new_commit);
10700 if (err)
10701 goto done;
10703 err = got_commit_graph_find_youngest_common_ancestor(&yca_id,
10704 old_commit_id, new_commit_id, 1, repo, check_cancelled, NULL);
10705 if (err)
10706 goto done;
10708 printf("has become commit %s%s%s%s\n %s\n", new_id_str,
10709 refs_str ? " (" : "", refs_str ? refs_str : "",
10710 refs_str ? ")" : "", new_commit_brief_str);
10711 if (yca_id && got_object_id_cmp(yca_id, new_commit_id) != 0 &&
10712 got_object_id_cmp(yca_id, old_commit_id) != 0) {
10713 free(refs_str);
10714 refs_str = NULL;
10716 err = got_object_open_as_commit(&yca_commit, repo, yca_id);
10717 if (err)
10718 goto done;
10720 err = get_commit_brief_str(&yca_brief_str, yca_commit);
10721 if (err)
10722 goto done;
10724 err = got_object_id_str(&yca_id_str, yca_id);
10725 if (err)
10726 goto done;
10728 refs = got_reflist_object_id_map_lookup(refs_idmap, yca_id);
10729 if (refs) {
10730 err = build_refs_str(&refs_str, refs, yca_id, repo, 0);
10731 if (err)
10732 goto done;
10734 printf("history forked at %s%s%s%s\n %s\n",
10735 yca_id_str,
10736 refs_str ? " (" : "", refs_str ? refs_str : "",
10737 refs_str ? ")" : "", yca_brief_str);
10739 done:
10740 free(custom_refs_str);
10741 free(new_commit_id);
10742 free(refs_str);
10743 free(yca_id);
10744 free(yca_id_str);
10745 free(yca_brief_str);
10746 if (new_commit)
10747 got_object_commit_close(new_commit);
10748 if (yca_commit)
10749 got_object_commit_close(yca_commit);
10751 return err;
10754 static const struct got_error *
10755 worktree_has_logmsg_ref(const char *caller, struct got_worktree *worktree,
10756 struct got_repository *repo)
10758 const struct got_error *err;
10759 struct got_reflist_head refs;
10760 struct got_reflist_entry *re;
10761 char *uuidstr = NULL;
10762 static char msg[160];
10764 TAILQ_INIT(&refs);
10766 err = got_worktree_get_uuid(&uuidstr, worktree);
10767 if (err)
10768 goto done;
10770 err = got_ref_list(&refs, repo, "refs/got/worktree",
10771 got_ref_cmp_by_name, repo);
10772 if (err)
10773 goto done;
10775 TAILQ_FOREACH(re, &refs, entry) {
10776 const char *cmd, *refname, *type;
10778 refname = got_ref_get_name(re->ref);
10780 if (strncmp(refname, GOT_WORKTREE_CHERRYPICK_REF_PREFIX,
10781 GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN) == 0) {
10782 refname += GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN + 1;
10783 cmd = "cherrypick";
10784 type = "cherrypicked";
10785 } else if (strncmp(refname, GOT_WORKTREE_BACKOUT_REF_PREFIX,
10786 GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN) == 0) {
10787 refname += GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN + 1;
10788 cmd = "backout";
10789 type = "backed-out";
10790 } else
10791 continue;
10793 if (strncmp(refname, uuidstr, GOT_WORKTREE_UUID_STRLEN) != 0)
10794 continue;
10796 snprintf(msg, sizeof(msg),
10797 "work tree has references created by %s commits which "
10798 "must be removed with 'got %s -X' before running the %s "
10799 "command", type, cmd, caller);
10800 err = got_error_msg(GOT_ERR_WORKTREE_META, msg);
10801 goto done;
10804 done:
10805 free(uuidstr);
10806 got_ref_list_free(&refs);
10807 return err;
10810 static const struct got_error *
10811 process_backup_refs(const char *backup_ref_prefix,
10812 const char *wanted_branch_name,
10813 int delete, struct got_repository *repo)
10815 const struct got_error *err;
10816 struct got_reflist_head refs, backup_refs;
10817 struct got_reflist_entry *re;
10818 const size_t backup_ref_prefix_len = strlen(backup_ref_prefix);
10819 struct got_object_id *old_commit_id = NULL;
10820 char *branch_name = NULL;
10821 struct got_commit_object *old_commit = NULL;
10822 struct got_reflist_object_id_map *refs_idmap = NULL;
10823 int wanted_branch_found = 0;
10825 TAILQ_INIT(&refs);
10826 TAILQ_INIT(&backup_refs);
10828 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
10829 if (err)
10830 return err;
10832 err = got_reflist_object_id_map_create(&refs_idmap, &refs, repo);
10833 if (err)
10834 goto done;
10836 if (wanted_branch_name) {
10837 if (strncmp(wanted_branch_name, "refs/heads/", 11) == 0)
10838 wanted_branch_name += 11;
10841 err = got_ref_list(&backup_refs, repo, backup_ref_prefix,
10842 got_ref_cmp_by_commit_timestamp_descending, repo);
10843 if (err)
10844 goto done;
10846 TAILQ_FOREACH(re, &backup_refs, entry) {
10847 const char *refname = got_ref_get_name(re->ref);
10848 char *slash;
10850 err = check_cancelled(NULL);
10851 if (err)
10852 break;
10854 err = got_ref_resolve(&old_commit_id, repo, re->ref);
10855 if (err)
10856 break;
10858 err = got_object_open_as_commit(&old_commit, repo,
10859 old_commit_id);
10860 if (err)
10861 break;
10863 if (strncmp(backup_ref_prefix, refname,
10864 backup_ref_prefix_len) == 0)
10865 refname += backup_ref_prefix_len;
10867 while (refname[0] == '/')
10868 refname++;
10870 branch_name = strdup(refname);
10871 if (branch_name == NULL) {
10872 err = got_error_from_errno("strdup");
10873 break;
10875 slash = strrchr(branch_name, '/');
10876 if (slash) {
10877 *slash = '\0';
10878 refname += strlen(branch_name) + 1;
10881 if (wanted_branch_name == NULL ||
10882 strcmp(wanted_branch_name, branch_name) == 0) {
10883 wanted_branch_found = 1;
10884 if (delete) {
10885 err = delete_backup_ref(re->ref,
10886 old_commit_id, repo);
10887 } else {
10888 err = print_backup_ref(branch_name, refname,
10889 old_commit_id, old_commit, refs_idmap,
10890 repo);
10892 if (err)
10893 break;
10896 free(old_commit_id);
10897 old_commit_id = NULL;
10898 free(branch_name);
10899 branch_name = NULL;
10900 got_object_commit_close(old_commit);
10901 old_commit = NULL;
10904 if (wanted_branch_name && !wanted_branch_found) {
10905 err = got_error_fmt(GOT_ERR_NOT_REF,
10906 "%s/%s/", backup_ref_prefix, wanted_branch_name);
10908 done:
10909 if (refs_idmap)
10910 got_reflist_object_id_map_free(refs_idmap);
10911 got_ref_list_free(&refs);
10912 got_ref_list_free(&backup_refs);
10913 free(old_commit_id);
10914 free(branch_name);
10915 if (old_commit)
10916 got_object_commit_close(old_commit);
10917 return err;
10920 static const struct got_error *
10921 abort_progress(void *arg, unsigned char status, const char *path)
10924 * Unversioned files should not clutter progress output when
10925 * an operation is aborted.
10927 if (status == GOT_STATUS_UNVERSIONED)
10928 return NULL;
10930 return update_progress(arg, status, path);
10933 static const struct got_error *
10934 cmd_rebase(int argc, char *argv[])
10936 const struct got_error *error = NULL;
10937 struct got_worktree *worktree = NULL;
10938 struct got_repository *repo = NULL;
10939 struct got_fileindex *fileindex = NULL;
10940 char *cwd = NULL, *committer = NULL, *gitconfig_path = NULL;
10941 struct got_reference *branch = NULL;
10942 struct got_reference *new_base_branch = NULL, *tmp_branch = NULL;
10943 struct got_object_id *commit_id = NULL, *parent_id = NULL;
10944 struct got_object_id *resume_commit_id = NULL;
10945 struct got_object_id *branch_head_commit_id = NULL, *yca_id = NULL;
10946 struct got_object_id *head_commit_id = NULL;
10947 struct got_reference *head_ref = NULL;
10948 struct got_commit_object *commit = NULL;
10949 int ch, rebase_in_progress = 0, abort_rebase = 0, continue_rebase = 0;
10950 int histedit_in_progress = 0, merge_in_progress = 0;
10951 int create_backup = 1, list_backups = 0, delete_backups = 0;
10952 struct got_object_id_queue commits;
10953 struct got_pathlist_head merged_paths;
10954 const struct got_object_id_queue *parent_ids;
10955 struct got_object_qid *qid, *pid;
10956 struct got_update_progress_arg upa;
10957 int *pack_fds = NULL;
10959 STAILQ_INIT(&commits);
10960 TAILQ_INIT(&merged_paths);
10961 memset(&upa, 0, sizeof(upa));
10963 while ((ch = getopt(argc, argv, "aclX")) != -1) {
10964 switch (ch) {
10965 case 'a':
10966 abort_rebase = 1;
10967 break;
10968 case 'c':
10969 continue_rebase = 1;
10970 break;
10971 case 'l':
10972 list_backups = 1;
10973 break;
10974 case 'X':
10975 delete_backups = 1;
10976 break;
10977 default:
10978 usage_rebase();
10979 /* NOTREACHED */
10983 argc -= optind;
10984 argv += optind;
10986 #ifndef PROFILE
10987 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
10988 "unveil", NULL) == -1)
10989 err(1, "pledge");
10990 #endif
10991 if (list_backups) {
10992 if (abort_rebase)
10993 option_conflict('l', 'a');
10994 if (continue_rebase)
10995 option_conflict('l', 'c');
10996 if (delete_backups)
10997 option_conflict('l', 'X');
10998 if (argc != 0 && argc != 1)
10999 usage_rebase();
11000 } else if (delete_backups) {
11001 if (abort_rebase)
11002 option_conflict('X', 'a');
11003 if (continue_rebase)
11004 option_conflict('X', 'c');
11005 if (list_backups)
11006 option_conflict('l', 'X');
11007 if (argc != 0 && argc != 1)
11008 usage_rebase();
11009 } else {
11010 if (abort_rebase && continue_rebase)
11011 usage_rebase();
11012 else if (abort_rebase || continue_rebase) {
11013 if (argc != 0)
11014 usage_rebase();
11015 } else if (argc != 1)
11016 usage_rebase();
11019 cwd = getcwd(NULL, 0);
11020 if (cwd == NULL) {
11021 error = got_error_from_errno("getcwd");
11022 goto done;
11025 error = got_repo_pack_fds_open(&pack_fds);
11026 if (error != NULL)
11027 goto done;
11029 error = got_worktree_open(&worktree, cwd);
11030 if (error) {
11031 if (list_backups || delete_backups) {
11032 if (error->code != GOT_ERR_NOT_WORKTREE)
11033 goto done;
11034 } else {
11035 if (error->code == GOT_ERR_NOT_WORKTREE)
11036 error = wrap_not_worktree_error(error,
11037 "rebase", cwd);
11038 goto done;
11042 error = get_gitconfig_path(&gitconfig_path);
11043 if (error)
11044 goto done;
11045 error = got_repo_open(&repo,
11046 worktree ? got_worktree_get_repo_path(worktree) : cwd,
11047 gitconfig_path, pack_fds);
11048 if (error != NULL)
11049 goto done;
11051 if (worktree != NULL && !list_backups && !delete_backups) {
11052 error = worktree_has_logmsg_ref("rebase", worktree, repo);
11053 if (error)
11054 goto done;
11057 error = get_author(&committer, repo, worktree);
11058 if (error && error->code != GOT_ERR_COMMIT_NO_AUTHOR)
11059 goto done;
11061 error = apply_unveil(got_repo_get_path(repo), 0,
11062 worktree ? got_worktree_get_root_path(worktree) : NULL);
11063 if (error)
11064 goto done;
11066 if (list_backups || delete_backups) {
11067 error = process_backup_refs(
11068 GOT_WORKTREE_REBASE_BACKUP_REF_PREFIX,
11069 argc == 1 ? argv[0] : NULL, delete_backups, repo);
11070 goto done; /* nothing else to do */
11073 error = got_worktree_histedit_in_progress(&histedit_in_progress,
11074 worktree);
11075 if (error)
11076 goto done;
11077 if (histedit_in_progress) {
11078 error = got_error(GOT_ERR_HISTEDIT_BUSY);
11079 goto done;
11082 error = got_worktree_merge_in_progress(&merge_in_progress,
11083 worktree, repo);
11084 if (error)
11085 goto done;
11086 if (merge_in_progress) {
11087 error = got_error(GOT_ERR_MERGE_BUSY);
11088 goto done;
11091 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
11092 if (error)
11093 goto done;
11095 if (abort_rebase) {
11096 if (!rebase_in_progress) {
11097 error = got_error(GOT_ERR_NOT_REBASING);
11098 goto done;
11100 error = got_worktree_rebase_continue(&resume_commit_id,
11101 &new_base_branch, &tmp_branch, &branch, &fileindex,
11102 worktree, repo);
11103 if (error)
11104 goto done;
11105 printf("Switching work tree to %s\n",
11106 got_ref_get_symref_target(new_base_branch));
11107 error = got_worktree_rebase_abort(worktree, fileindex, repo,
11108 new_base_branch, abort_progress, &upa);
11109 if (error)
11110 goto done;
11111 printf("Rebase of %s aborted\n", got_ref_get_name(branch));
11112 print_merge_progress_stats(&upa);
11113 goto done; /* nothing else to do */
11116 if (continue_rebase) {
11117 if (!rebase_in_progress) {
11118 error = got_error(GOT_ERR_NOT_REBASING);
11119 goto done;
11121 error = got_worktree_rebase_continue(&resume_commit_id,
11122 &new_base_branch, &tmp_branch, &branch, &fileindex,
11123 worktree, repo);
11124 if (error)
11125 goto done;
11127 error = rebase_commit(NULL, worktree, fileindex, tmp_branch,
11128 committer, resume_commit_id, repo);
11129 if (error)
11130 goto done;
11132 yca_id = got_object_id_dup(resume_commit_id);
11133 if (yca_id == NULL) {
11134 error = got_error_from_errno("got_object_id_dup");
11135 goto done;
11137 } else {
11138 error = got_ref_open(&branch, repo, argv[0], 0);
11139 if (error != NULL)
11140 goto done;
11141 if (strncmp(got_ref_get_name(branch), "refs/heads/", 11) != 0) {
11142 error = got_error_msg(GOT_ERR_COMMIT_BRANCH,
11143 "will not rebase a branch which lives outside "
11144 "the \"refs/heads/\" reference namespace");
11145 goto done;
11149 error = got_ref_resolve(&branch_head_commit_id, repo, branch);
11150 if (error)
11151 goto done;
11153 if (!continue_rebase) {
11154 struct got_object_id *base_commit_id;
11156 error = got_ref_open(&head_ref, repo,
11157 got_worktree_get_head_ref_name(worktree), 0);
11158 if (error)
11159 goto done;
11160 error = got_ref_resolve(&head_commit_id, repo, head_ref);
11161 if (error)
11162 goto done;
11163 base_commit_id = got_worktree_get_base_commit_id(worktree);
11164 if (got_object_id_cmp(base_commit_id, head_commit_id) != 0) {
11165 error = got_error(GOT_ERR_REBASE_OUT_OF_DATE);
11166 goto done;
11169 error = got_commit_graph_find_youngest_common_ancestor(&yca_id,
11170 base_commit_id, branch_head_commit_id, 1, repo,
11171 check_cancelled, NULL);
11172 if (error) {
11173 if (error->code == GOT_ERR_ANCESTRY) {
11174 error = got_error_msg(GOT_ERR_ANCESTRY,
11175 "specified branch shares no common "
11176 "ancestry with work tree's branch");
11178 goto done;
11181 error = check_same_branch(base_commit_id, branch, yca_id, repo);
11182 if (error) {
11183 if (error->code != GOT_ERR_ANCESTRY)
11184 goto done;
11185 error = NULL;
11186 } else {
11187 struct got_pathlist_head paths;
11188 printf("%s is already based on %s\n",
11189 got_ref_get_name(branch),
11190 got_worktree_get_head_ref_name(worktree));
11191 error = switch_head_ref(branch, branch_head_commit_id,
11192 worktree, repo);
11193 if (error)
11194 goto done;
11195 error = got_worktree_set_base_commit_id(worktree, repo,
11196 branch_head_commit_id);
11197 if (error)
11198 goto done;
11199 TAILQ_INIT(&paths);
11200 error = got_pathlist_append(&paths, "", NULL);
11201 if (error)
11202 goto done;
11203 error = got_worktree_checkout_files(worktree,
11204 &paths, repo, update_progress, &upa,
11205 check_cancelled, NULL);
11206 got_pathlist_free(&paths, GOT_PATHLIST_FREE_NONE);
11207 if (error)
11208 goto done;
11209 if (upa.did_something) {
11210 char *id_str;
11211 error = got_object_id_str(&id_str,
11212 branch_head_commit_id);
11213 if (error)
11214 goto done;
11215 printf("Updated to %s: %s\n",
11216 got_worktree_get_head_ref_name(worktree),
11217 id_str);
11218 free(id_str);
11219 } else
11220 printf("Already up-to-date\n");
11221 print_update_progress_stats(&upa);
11222 goto done;
11226 commit_id = branch_head_commit_id;
11227 error = got_object_open_as_commit(&commit, repo, commit_id);
11228 if (error)
11229 goto done;
11231 parent_ids = got_object_commit_get_parent_ids(commit);
11232 pid = STAILQ_FIRST(parent_ids);
11233 if (pid) {
11234 error = collect_commits(&commits, commit_id, &pid->id,
11235 yca_id, got_worktree_get_path_prefix(worktree),
11236 GOT_ERR_REBASE_PATH, repo);
11237 if (error)
11238 goto done;
11241 got_object_commit_close(commit);
11242 commit = NULL;
11244 if (!continue_rebase) {
11245 error = got_worktree_rebase_prepare(&new_base_branch,
11246 &tmp_branch, &fileindex, worktree, branch, repo);
11247 if (error)
11248 goto done;
11251 if (STAILQ_EMPTY(&commits)) {
11252 if (continue_rebase) {
11253 error = rebase_complete(worktree, fileindex,
11254 branch, tmp_branch, repo, create_backup);
11255 goto done;
11256 } else {
11257 /* Fast-forward the reference of the branch. */
11258 struct got_object_id *new_head_commit_id;
11259 char *id_str;
11260 error = got_ref_resolve(&new_head_commit_id, repo,
11261 new_base_branch);
11262 if (error)
11263 goto done;
11264 error = got_object_id_str(&id_str, new_head_commit_id);
11265 if (error)
11266 goto done;
11267 printf("Forwarding %s to commit %s\n",
11268 got_ref_get_name(branch), id_str);
11269 free(id_str);
11270 error = got_ref_change_ref(branch,
11271 new_head_commit_id);
11272 if (error)
11273 goto done;
11274 /* No backup needed since objects did not change. */
11275 create_backup = 0;
11279 pid = NULL;
11280 STAILQ_FOREACH(qid, &commits, entry) {
11282 commit_id = &qid->id;
11283 parent_id = pid ? &pid->id : yca_id;
11284 pid = qid;
11286 memset(&upa, 0, sizeof(upa));
11287 error = got_worktree_rebase_merge_files(&merged_paths,
11288 worktree, fileindex, parent_id, commit_id, repo,
11289 update_progress, &upa, check_cancelled, NULL);
11290 if (error)
11291 goto done;
11293 print_merge_progress_stats(&upa);
11294 if (upa.conflicts > 0 || upa.missing > 0 ||
11295 upa.not_deleted > 0 || upa.unversioned > 0) {
11296 if (upa.conflicts > 0) {
11297 error = show_rebase_merge_conflict(&qid->id,
11298 repo);
11299 if (error)
11300 goto done;
11302 got_pathlist_free(&merged_paths, GOT_PATHLIST_FREE_PATH);
11303 break;
11306 error = rebase_commit(&merged_paths, worktree, fileindex,
11307 tmp_branch, committer, commit_id, repo);
11308 got_pathlist_free(&merged_paths, GOT_PATHLIST_FREE_PATH);
11309 if (error)
11310 goto done;
11313 if (upa.conflicts > 0 || upa.missing > 0 ||
11314 upa.not_deleted > 0 || upa.unversioned > 0) {
11315 error = got_worktree_rebase_postpone(worktree, fileindex);
11316 if (error)
11317 goto done;
11318 if (upa.conflicts > 0 && upa.missing == 0 &&
11319 upa.not_deleted == 0 && upa.unversioned == 0) {
11320 error = got_error_msg(GOT_ERR_CONFLICTS,
11321 "conflicts must be resolved before rebasing "
11322 "can continue");
11323 } else if (upa.conflicts > 0) {
11324 error = got_error_msg(GOT_ERR_CONFLICTS,
11325 "conflicts must be resolved before rebasing "
11326 "can continue; changes destined for some "
11327 "files were not yet merged and should be "
11328 "merged manually if required before the "
11329 "rebase operation is continued");
11330 } else {
11331 error = got_error_msg(GOT_ERR_CONFLICTS,
11332 "changes destined for some files were not "
11333 "yet merged and should be merged manually "
11334 "if required before the rebase operation "
11335 "is continued");
11337 } else
11338 error = rebase_complete(worktree, fileindex, branch,
11339 tmp_branch, repo, create_backup);
11340 done:
11341 free(cwd);
11342 free(committer);
11343 free(gitconfig_path);
11344 got_object_id_queue_free(&commits);
11345 free(branch_head_commit_id);
11346 free(resume_commit_id);
11347 free(head_commit_id);
11348 free(yca_id);
11349 if (commit)
11350 got_object_commit_close(commit);
11351 if (branch)
11352 got_ref_close(branch);
11353 if (new_base_branch)
11354 got_ref_close(new_base_branch);
11355 if (tmp_branch)
11356 got_ref_close(tmp_branch);
11357 if (head_ref)
11358 got_ref_close(head_ref);
11359 if (worktree)
11360 got_worktree_close(worktree);
11361 if (repo) {
11362 const struct got_error *close_err = got_repo_close(repo);
11363 if (error == NULL)
11364 error = close_err;
11366 if (pack_fds) {
11367 const struct got_error *pack_err =
11368 got_repo_pack_fds_close(pack_fds);
11369 if (error == NULL)
11370 error = pack_err;
11372 return error;
11375 __dead static void
11376 usage_histedit(void)
11378 fprintf(stderr, "usage: %s histedit [-acdeflmX] [-F histedit-script] "
11379 "[branch]\n", getprogname());
11380 exit(1);
11383 #define GOT_HISTEDIT_PICK 'p'
11384 #define GOT_HISTEDIT_EDIT 'e'
11385 #define GOT_HISTEDIT_FOLD 'f'
11386 #define GOT_HISTEDIT_DROP 'd'
11387 #define GOT_HISTEDIT_MESG 'm'
11389 static const struct got_histedit_cmd {
11390 unsigned char code;
11391 const char *name;
11392 const char *desc;
11393 } got_histedit_cmds[] = {
11394 { GOT_HISTEDIT_PICK, "pick", "use commit" },
11395 { GOT_HISTEDIT_EDIT, "edit", "use commit but stop for amending" },
11396 { GOT_HISTEDIT_FOLD, "fold", "combine with next commit that will "
11397 "be used" },
11398 { GOT_HISTEDIT_DROP, "drop", "remove commit from history" },
11399 { GOT_HISTEDIT_MESG, "mesg",
11400 "single-line log message for commit above (open editor if empty)" },
11403 struct got_histedit_list_entry {
11404 TAILQ_ENTRY(got_histedit_list_entry) entry;
11405 struct got_object_id *commit_id;
11406 const struct got_histedit_cmd *cmd;
11407 char *logmsg;
11409 TAILQ_HEAD(got_histedit_list, got_histedit_list_entry);
11411 static const struct got_error *
11412 histedit_write_commit(struct got_object_id *commit_id, const char *cmdname,
11413 FILE *f, struct got_repository *repo)
11415 const struct got_error *err = NULL;
11416 char *logmsg = NULL, *id_str = NULL;
11417 struct got_commit_object *commit = NULL;
11418 int n;
11420 err = got_object_open_as_commit(&commit, repo, commit_id);
11421 if (err)
11422 goto done;
11424 err = get_short_logmsg(&logmsg, 34, commit);
11425 if (err)
11426 goto done;
11428 err = got_object_id_str(&id_str, commit_id);
11429 if (err)
11430 goto done;
11432 n = fprintf(f, "%s %s %s\n", cmdname, id_str, logmsg);
11433 if (n < 0)
11434 err = got_ferror(f, GOT_ERR_IO);
11435 done:
11436 if (commit)
11437 got_object_commit_close(commit);
11438 free(id_str);
11439 free(logmsg);
11440 return err;
11443 static const struct got_error *
11444 histedit_write_commit_list(struct got_object_id_queue *commits,
11445 FILE *f, int edit_logmsg_only, int fold_only, int drop_only,
11446 int edit_only, struct got_repository *repo)
11448 const struct got_error *err = NULL;
11449 struct got_object_qid *qid;
11450 const char *histedit_cmd = NULL;
11452 if (STAILQ_EMPTY(commits))
11453 return got_error(GOT_ERR_EMPTY_HISTEDIT);
11455 STAILQ_FOREACH(qid, commits, entry) {
11456 histedit_cmd = got_histedit_cmds[0].name;
11457 if (drop_only)
11458 histedit_cmd = "drop";
11459 else if (edit_only)
11460 histedit_cmd = "edit";
11461 else if (fold_only && STAILQ_NEXT(qid, entry) != NULL)
11462 histedit_cmd = "fold";
11463 err = histedit_write_commit(&qid->id, histedit_cmd, f, repo);
11464 if (err)
11465 break;
11466 if (edit_logmsg_only) {
11467 int n = fprintf(f, "%c\n", GOT_HISTEDIT_MESG);
11468 if (n < 0) {
11469 err = got_ferror(f, GOT_ERR_IO);
11470 break;
11475 return err;
11478 static const struct got_error *
11479 write_cmd_list(FILE *f, const char *branch_name,
11480 struct got_object_id_queue *commits)
11482 const struct got_error *err = NULL;
11483 size_t i;
11484 int n;
11485 char *id_str;
11486 struct got_object_qid *qid;
11488 qid = STAILQ_FIRST(commits);
11489 err = got_object_id_str(&id_str, &qid->id);
11490 if (err)
11491 return err;
11493 n = fprintf(f,
11494 "# Editing the history of branch '%s' starting at\n"
11495 "# commit %s\n"
11496 "# Commits will be processed in order from top to "
11497 "bottom of this file.\n", branch_name, id_str);
11498 if (n < 0) {
11499 err = got_ferror(f, GOT_ERR_IO);
11500 goto done;
11503 n = fprintf(f, "# Available histedit commands:\n");
11504 if (n < 0) {
11505 err = got_ferror(f, GOT_ERR_IO);
11506 goto done;
11509 for (i = 0; i < nitems(got_histedit_cmds); i++) {
11510 const struct got_histedit_cmd *cmd = &got_histedit_cmds[i];
11511 n = fprintf(f, "# %s (%c): %s\n", cmd->name, cmd->code,
11512 cmd->desc);
11513 if (n < 0) {
11514 err = got_ferror(f, GOT_ERR_IO);
11515 break;
11518 done:
11519 free(id_str);
11520 return err;
11523 static const struct got_error *
11524 histedit_syntax_error(int lineno)
11526 static char msg[42];
11527 int ret;
11529 ret = snprintf(msg, sizeof(msg), "histedit syntax error on line %d",
11530 lineno);
11531 if (ret < 0 || (size_t)ret >= sizeof(msg))
11532 return got_error(GOT_ERR_HISTEDIT_SYNTAX);
11534 return got_error_msg(GOT_ERR_HISTEDIT_SYNTAX, msg);
11537 static const struct got_error *
11538 append_folded_commit_msg(char **new_msg, struct got_histedit_list_entry *hle,
11539 char *logmsg, struct got_repository *repo)
11541 const struct got_error *err;
11542 struct got_commit_object *folded_commit = NULL;
11543 char *id_str, *folded_logmsg = NULL;
11545 err = got_object_id_str(&id_str, hle->commit_id);
11546 if (err)
11547 return err;
11549 err = got_object_open_as_commit(&folded_commit, repo, hle->commit_id);
11550 if (err)
11551 goto done;
11553 err = got_object_commit_get_logmsg(&folded_logmsg, folded_commit);
11554 if (err)
11555 goto done;
11556 if (asprintf(new_msg, "%s%s# log message of folded commit %s: %s",
11557 logmsg ? logmsg : "", logmsg ? "\n" : "", id_str,
11558 folded_logmsg) == -1) {
11559 err = got_error_from_errno("asprintf");
11561 done:
11562 if (folded_commit)
11563 got_object_commit_close(folded_commit);
11564 free(id_str);
11565 free(folded_logmsg);
11566 return err;
11569 static struct got_histedit_list_entry *
11570 get_folded_commits(struct got_histedit_list_entry *hle)
11572 struct got_histedit_list_entry *prev, *folded = NULL;
11574 prev = TAILQ_PREV(hle, got_histedit_list, entry);
11575 while (prev && (prev->cmd->code == GOT_HISTEDIT_FOLD ||
11576 prev->cmd->code == GOT_HISTEDIT_DROP)) {
11577 if (prev->cmd->code == GOT_HISTEDIT_FOLD)
11578 folded = prev;
11579 prev = TAILQ_PREV(prev, got_histedit_list, entry);
11582 return folded;
11585 static const struct got_error *
11586 histedit_edit_logmsg(struct got_histedit_list_entry *hle,
11587 struct got_repository *repo)
11589 char *logmsg_path = NULL, *id_str = NULL, *orig_logmsg = NULL;
11590 char *logmsg = NULL, *new_msg = NULL, *editor = NULL;
11591 const struct got_error *err = NULL;
11592 struct got_commit_object *commit = NULL;
11593 int logmsg_len;
11594 int fd;
11595 struct got_histedit_list_entry *folded = NULL;
11597 err = got_object_open_as_commit(&commit, repo, hle->commit_id);
11598 if (err)
11599 return err;
11601 folded = get_folded_commits(hle);
11602 if (folded) {
11603 while (folded != hle) {
11604 if (folded->cmd->code == GOT_HISTEDIT_DROP) {
11605 folded = TAILQ_NEXT(folded, entry);
11606 continue;
11608 err = append_folded_commit_msg(&new_msg, folded,
11609 logmsg, repo);
11610 if (err)
11611 goto done;
11612 free(logmsg);
11613 logmsg = new_msg;
11614 folded = TAILQ_NEXT(folded, entry);
11618 err = got_object_id_str(&id_str, hle->commit_id);
11619 if (err)
11620 goto done;
11621 err = got_object_commit_get_logmsg(&orig_logmsg, commit);
11622 if (err)
11623 goto done;
11624 logmsg_len = asprintf(&new_msg,
11625 "%s\n# original log message of commit %s: %s",
11626 logmsg ? logmsg : "", id_str, orig_logmsg);
11627 if (logmsg_len == -1) {
11628 err = got_error_from_errno("asprintf");
11629 goto done;
11631 free(logmsg);
11632 logmsg = new_msg;
11634 err = got_object_id_str(&id_str, hle->commit_id);
11635 if (err)
11636 goto done;
11638 err = got_opentemp_named_fd(&logmsg_path, &fd,
11639 GOT_TMPDIR_STR "/got-logmsg", "");
11640 if (err)
11641 goto done;
11643 write(fd, logmsg, logmsg_len);
11644 close(fd);
11646 err = get_editor(&editor);
11647 if (err)
11648 goto done;
11650 err = edit_logmsg(&hle->logmsg, editor, logmsg_path, logmsg,
11651 logmsg_len, 0);
11652 if (err) {
11653 if (err->code != GOT_ERR_COMMIT_MSG_EMPTY)
11654 goto done;
11655 err = NULL;
11656 hle->logmsg = strdup(new_msg);
11657 if (hle->logmsg == NULL)
11658 err = got_error_from_errno("strdup");
11660 done:
11661 if (logmsg_path && unlink(logmsg_path) != 0 && err == NULL)
11662 err = got_error_from_errno2("unlink", logmsg_path);
11663 free(logmsg_path);
11664 free(logmsg);
11665 free(orig_logmsg);
11666 free(editor);
11667 if (commit)
11668 got_object_commit_close(commit);
11669 return err;
11672 static const struct got_error *
11673 histedit_parse_list(struct got_histedit_list *histedit_cmds,
11674 FILE *f, struct got_repository *repo)
11676 const struct got_error *err = NULL;
11677 char *line = NULL, *p, *end;
11678 size_t i, size;
11679 ssize_t len;
11680 int lineno = 0, lastcmd = -1;
11681 const struct got_histedit_cmd *cmd;
11682 struct got_object_id *commit_id = NULL;
11683 struct got_histedit_list_entry *hle = NULL;
11685 for (;;) {
11686 len = getline(&line, &size, f);
11687 if (len == -1) {
11688 const struct got_error *getline_err;
11689 if (feof(f))
11690 break;
11691 getline_err = got_error_from_errno("getline");
11692 err = got_ferror(f, getline_err->code);
11693 break;
11695 lineno++;
11696 p = line;
11697 while (isspace((unsigned char)p[0]))
11698 p++;
11699 if (p[0] == '#' || p[0] == '\0') {
11700 free(line);
11701 line = NULL;
11702 continue;
11704 cmd = NULL;
11705 for (i = 0; i < nitems(got_histedit_cmds); i++) {
11706 cmd = &got_histedit_cmds[i];
11707 if (strncmp(cmd->name, p, strlen(cmd->name)) == 0 &&
11708 isspace((unsigned char)p[strlen(cmd->name)])) {
11709 p += strlen(cmd->name);
11710 break;
11712 if (p[0] == cmd->code && isspace((unsigned char)p[1])) {
11713 p++;
11714 break;
11717 if (i == nitems(got_histedit_cmds)) {
11718 err = histedit_syntax_error(lineno);
11719 break;
11721 while (isspace((unsigned char)p[0]))
11722 p++;
11723 if (cmd->code == GOT_HISTEDIT_MESG) {
11724 if (lastcmd != GOT_HISTEDIT_PICK &&
11725 lastcmd != GOT_HISTEDIT_EDIT) {
11726 err = got_error(GOT_ERR_HISTEDIT_CMD);
11727 break;
11729 if (p[0] == '\0') {
11730 err = histedit_edit_logmsg(hle, repo);
11731 if (err)
11732 break;
11733 } else {
11734 hle->logmsg = strdup(p);
11735 if (hle->logmsg == NULL) {
11736 err = got_error_from_errno("strdup");
11737 break;
11740 free(line);
11741 line = NULL;
11742 lastcmd = cmd->code;
11743 continue;
11744 } else {
11745 end = p;
11746 while (end[0] && !isspace((unsigned char)end[0]))
11747 end++;
11748 *end = '\0';
11750 err = got_object_resolve_id_str(&commit_id, repo, p);
11751 if (err) {
11752 /* override error code */
11753 err = histedit_syntax_error(lineno);
11754 break;
11757 hle = malloc(sizeof(*hle));
11758 if (hle == NULL) {
11759 err = got_error_from_errno("malloc");
11760 break;
11762 hle->cmd = cmd;
11763 hle->commit_id = commit_id;
11764 hle->logmsg = NULL;
11765 commit_id = NULL;
11766 free(line);
11767 line = NULL;
11768 TAILQ_INSERT_TAIL(histedit_cmds, hle, entry);
11769 lastcmd = cmd->code;
11772 free(line);
11773 free(commit_id);
11774 return err;
11777 static const struct got_error *
11778 histedit_check_script(struct got_histedit_list *histedit_cmds,
11779 struct got_object_id_queue *commits, struct got_repository *repo)
11781 const struct got_error *err = NULL;
11782 struct got_object_qid *qid;
11783 struct got_histedit_list_entry *hle;
11784 static char msg[92];
11785 char *id_str;
11787 if (TAILQ_EMPTY(histedit_cmds))
11788 return got_error_msg(GOT_ERR_EMPTY_HISTEDIT,
11789 "histedit script contains no commands");
11790 if (STAILQ_EMPTY(commits))
11791 return got_error(GOT_ERR_EMPTY_HISTEDIT);
11793 TAILQ_FOREACH(hle, histedit_cmds, entry) {
11794 struct got_histedit_list_entry *hle2;
11795 TAILQ_FOREACH(hle2, histedit_cmds, entry) {
11796 if (hle == hle2)
11797 continue;
11798 if (got_object_id_cmp(hle->commit_id,
11799 hle2->commit_id) != 0)
11800 continue;
11801 err = got_object_id_str(&id_str, hle->commit_id);
11802 if (err)
11803 return err;
11804 snprintf(msg, sizeof(msg), "commit %s is listed "
11805 "more than once in histedit script", id_str);
11806 free(id_str);
11807 return got_error_msg(GOT_ERR_HISTEDIT_CMD, msg);
11811 STAILQ_FOREACH(qid, commits, entry) {
11812 TAILQ_FOREACH(hle, histedit_cmds, entry) {
11813 if (got_object_id_cmp(&qid->id, hle->commit_id) == 0)
11814 break;
11816 if (hle == NULL) {
11817 err = got_object_id_str(&id_str, &qid->id);
11818 if (err)
11819 return err;
11820 snprintf(msg, sizeof(msg),
11821 "commit %s missing from histedit script", id_str);
11822 free(id_str);
11823 return got_error_msg(GOT_ERR_HISTEDIT_CMD, msg);
11827 hle = TAILQ_LAST(histedit_cmds, got_histedit_list);
11828 if (hle && hle->cmd->code == GOT_HISTEDIT_FOLD)
11829 return got_error_msg(GOT_ERR_HISTEDIT_CMD,
11830 "last commit in histedit script cannot be folded");
11832 return NULL;
11835 static const struct got_error *
11836 histedit_run_editor(struct got_histedit_list *histedit_cmds,
11837 const char *path, struct got_object_id_queue *commits,
11838 struct got_repository *repo)
11840 const struct got_error *err = NULL;
11841 char *editor;
11842 FILE *f = NULL;
11844 err = get_editor(&editor);
11845 if (err)
11846 return err;
11848 if (spawn_editor(editor, path) == -1) {
11849 err = got_error_from_errno("failed spawning editor");
11850 goto done;
11853 f = fopen(path, "re");
11854 if (f == NULL) {
11855 err = got_error_from_errno("fopen");
11856 goto done;
11858 err = histedit_parse_list(histedit_cmds, f, repo);
11859 if (err)
11860 goto done;
11862 err = histedit_check_script(histedit_cmds, commits, repo);
11863 done:
11864 if (f && fclose(f) == EOF && err == NULL)
11865 err = got_error_from_errno("fclose");
11866 free(editor);
11867 return err;
11870 static const struct got_error *
11871 histedit_edit_list_retry(struct got_histedit_list *, const struct got_error *,
11872 struct got_object_id_queue *, const char *, const char *,
11873 struct got_repository *);
11875 static const struct got_error *
11876 histedit_edit_script(struct got_histedit_list *histedit_cmds,
11877 struct got_object_id_queue *commits, const char *branch_name,
11878 int edit_logmsg_only, int fold_only, int drop_only, int edit_only,
11879 struct got_repository *repo)
11881 const struct got_error *err;
11882 FILE *f = NULL;
11883 char *path = NULL;
11885 err = got_opentemp_named(&path, &f, "got-histedit", "");
11886 if (err)
11887 return err;
11889 err = write_cmd_list(f, branch_name, commits);
11890 if (err)
11891 goto done;
11893 err = histedit_write_commit_list(commits, f, edit_logmsg_only,
11894 fold_only, drop_only, edit_only, repo);
11895 if (err)
11896 goto done;
11898 if (drop_only || edit_logmsg_only || fold_only || edit_only) {
11899 rewind(f);
11900 err = histedit_parse_list(histedit_cmds, f, repo);
11901 } else {
11902 if (fclose(f) == EOF) {
11903 err = got_error_from_errno("fclose");
11904 goto done;
11906 f = NULL;
11907 err = histedit_run_editor(histedit_cmds, path, commits, repo);
11908 if (err) {
11909 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
11910 err->code != GOT_ERR_HISTEDIT_CMD)
11911 goto done;
11912 err = histedit_edit_list_retry(histedit_cmds, err,
11913 commits, path, branch_name, repo);
11916 done:
11917 if (f && fclose(f) == EOF && err == NULL)
11918 err = got_error_from_errno("fclose");
11919 if (path && unlink(path) != 0 && err == NULL)
11920 err = got_error_from_errno2("unlink", path);
11921 free(path);
11922 return err;
11925 static const struct got_error *
11926 histedit_save_list(struct got_histedit_list *histedit_cmds,
11927 struct got_worktree *worktree, struct got_repository *repo)
11929 const struct got_error *err = NULL;
11930 char *path = NULL;
11931 FILE *f = NULL;
11932 struct got_histedit_list_entry *hle;
11933 struct got_commit_object *commit = NULL;
11935 err = got_worktree_get_histedit_script_path(&path, worktree);
11936 if (err)
11937 return err;
11939 f = fopen(path, "we");
11940 if (f == NULL) {
11941 err = got_error_from_errno2("fopen", path);
11942 goto done;
11944 TAILQ_FOREACH(hle, histedit_cmds, entry) {
11945 err = histedit_write_commit(hle->commit_id, hle->cmd->name, f,
11946 repo);
11947 if (err)
11948 break;
11950 if (hle->logmsg) {
11951 int n = fprintf(f, "%c %s\n",
11952 GOT_HISTEDIT_MESG, hle->logmsg);
11953 if (n < 0) {
11954 err = got_ferror(f, GOT_ERR_IO);
11955 break;
11959 done:
11960 if (f && fclose(f) == EOF && err == NULL)
11961 err = got_error_from_errno("fclose");
11962 free(path);
11963 if (commit)
11964 got_object_commit_close(commit);
11965 return err;
11968 static void
11969 histedit_free_list(struct got_histedit_list *histedit_cmds)
11971 struct got_histedit_list_entry *hle;
11973 while ((hle = TAILQ_FIRST(histedit_cmds))) {
11974 TAILQ_REMOVE(histedit_cmds, hle, entry);
11975 free(hle);
11979 static const struct got_error *
11980 histedit_load_list(struct got_histedit_list *histedit_cmds,
11981 const char *path, struct got_repository *repo)
11983 const struct got_error *err = NULL;
11984 FILE *f = NULL;
11986 f = fopen(path, "re");
11987 if (f == NULL) {
11988 err = got_error_from_errno2("fopen", path);
11989 goto done;
11992 err = histedit_parse_list(histedit_cmds, f, repo);
11993 done:
11994 if (f && fclose(f) == EOF && err == NULL)
11995 err = got_error_from_errno("fclose");
11996 return err;
11999 static const struct got_error *
12000 histedit_edit_list_retry(struct got_histedit_list *histedit_cmds,
12001 const struct got_error *edit_err, struct got_object_id_queue *commits,
12002 const char *path, const char *branch_name, struct got_repository *repo)
12004 const struct got_error *err = NULL, *prev_err = edit_err;
12005 int resp = ' ';
12007 while (resp != 'c' && resp != 'r' && resp != 'a') {
12008 printf("%s: %s\n(c)ontinue editing, (r)estart editing, "
12009 "or (a)bort: ", getprogname(), prev_err->msg);
12010 resp = getchar();
12011 if (resp == '\n')
12012 resp = getchar();
12013 if (resp == 'c') {
12014 histedit_free_list(histedit_cmds);
12015 err = histedit_run_editor(histedit_cmds, path, commits,
12016 repo);
12017 if (err) {
12018 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
12019 err->code != GOT_ERR_HISTEDIT_CMD)
12020 break;
12021 prev_err = err;
12022 resp = ' ';
12023 continue;
12025 break;
12026 } else if (resp == 'r') {
12027 histedit_free_list(histedit_cmds);
12028 err = histedit_edit_script(histedit_cmds,
12029 commits, branch_name, 0, 0, 0, 0, repo);
12030 if (err) {
12031 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
12032 err->code != GOT_ERR_HISTEDIT_CMD)
12033 break;
12034 prev_err = err;
12035 resp = ' ';
12036 continue;
12038 break;
12039 } else if (resp == 'a') {
12040 err = got_error(GOT_ERR_HISTEDIT_CANCEL);
12041 break;
12042 } else
12043 printf("invalid response '%c'\n", resp);
12046 return err;
12049 static const struct got_error *
12050 histedit_complete(struct got_worktree *worktree,
12051 struct got_fileindex *fileindex, struct got_reference *tmp_branch,
12052 struct got_reference *branch, struct got_repository *repo)
12054 printf("Switching work tree to %s\n",
12055 got_ref_get_symref_target(branch));
12056 return got_worktree_histedit_complete(worktree, fileindex, tmp_branch,
12057 branch, repo);
12060 static const struct got_error *
12061 show_histedit_progress(struct got_commit_object *commit,
12062 struct got_histedit_list_entry *hle, struct got_object_id *new_id)
12064 const struct got_error *err;
12065 char *old_id_str = NULL, *new_id_str = NULL, *logmsg = NULL;
12067 err = got_object_id_str(&old_id_str, hle->commit_id);
12068 if (err)
12069 goto done;
12071 if (new_id) {
12072 err = got_object_id_str(&new_id_str, new_id);
12073 if (err)
12074 goto done;
12077 old_id_str[12] = '\0';
12078 if (new_id_str)
12079 new_id_str[12] = '\0';
12081 if (hle->logmsg) {
12082 logmsg = strdup(hle->logmsg);
12083 if (logmsg == NULL) {
12084 err = got_error_from_errno("strdup");
12085 goto done;
12087 trim_logmsg(logmsg, 42);
12088 } else {
12089 err = get_short_logmsg(&logmsg, 42, commit);
12090 if (err)
12091 goto done;
12094 switch (hle->cmd->code) {
12095 case GOT_HISTEDIT_PICK:
12096 case GOT_HISTEDIT_EDIT:
12097 printf("%s -> %s: %s\n", old_id_str,
12098 new_id_str ? new_id_str : "no-op change", logmsg);
12099 break;
12100 case GOT_HISTEDIT_DROP:
12101 case GOT_HISTEDIT_FOLD:
12102 printf("%s -> %s commit: %s\n", old_id_str, hle->cmd->name,
12103 logmsg);
12104 break;
12105 default:
12106 break;
12108 done:
12109 free(old_id_str);
12110 free(new_id_str);
12111 return err;
12114 static const struct got_error *
12115 histedit_commit(struct got_pathlist_head *merged_paths,
12116 struct got_worktree *worktree, struct got_fileindex *fileindex,
12117 struct got_reference *tmp_branch, struct got_histedit_list_entry *hle,
12118 const char *committer, struct got_repository *repo)
12120 const struct got_error *err;
12121 struct got_commit_object *commit;
12122 struct got_object_id *new_commit_id;
12124 if ((hle->cmd->code == GOT_HISTEDIT_EDIT || get_folded_commits(hle))
12125 && hle->logmsg == NULL) {
12126 err = histedit_edit_logmsg(hle, repo);
12127 if (err)
12128 return err;
12131 err = got_object_open_as_commit(&commit, repo, hle->commit_id);
12132 if (err)
12133 return err;
12135 err = got_worktree_histedit_commit(&new_commit_id, merged_paths,
12136 worktree, fileindex, tmp_branch, committer, commit, hle->commit_id,
12137 hle->logmsg, repo);
12138 if (err) {
12139 if (err->code != GOT_ERR_COMMIT_NO_CHANGES)
12140 goto done;
12141 err = show_histedit_progress(commit, hle, NULL);
12142 } else {
12143 err = show_histedit_progress(commit, hle, new_commit_id);
12144 free(new_commit_id);
12146 done:
12147 got_object_commit_close(commit);
12148 return err;
12151 static const struct got_error *
12152 histedit_skip_commit(struct got_histedit_list_entry *hle,
12153 struct got_worktree *worktree, struct got_repository *repo)
12155 const struct got_error *error;
12156 struct got_commit_object *commit;
12158 error = got_worktree_histedit_skip_commit(worktree, hle->commit_id,
12159 repo);
12160 if (error)
12161 return error;
12163 error = got_object_open_as_commit(&commit, repo, hle->commit_id);
12164 if (error)
12165 return error;
12167 error = show_histedit_progress(commit, hle, NULL);
12168 got_object_commit_close(commit);
12169 return error;
12172 static const struct got_error *
12173 check_local_changes(void *arg, unsigned char status,
12174 unsigned char staged_status, const char *path,
12175 struct got_object_id *blob_id, struct got_object_id *staged_blob_id,
12176 struct got_object_id *commit_id, int dirfd, const char *de_name)
12178 int *have_local_changes = arg;
12180 switch (status) {
12181 case GOT_STATUS_ADD:
12182 case GOT_STATUS_DELETE:
12183 case GOT_STATUS_MODIFY:
12184 case GOT_STATUS_CONFLICT:
12185 *have_local_changes = 1;
12186 return got_error(GOT_ERR_CANCELLED);
12187 default:
12188 break;
12191 switch (staged_status) {
12192 case GOT_STATUS_ADD:
12193 case GOT_STATUS_DELETE:
12194 case GOT_STATUS_MODIFY:
12195 *have_local_changes = 1;
12196 return got_error(GOT_ERR_CANCELLED);
12197 default:
12198 break;
12201 return NULL;
12204 static const struct got_error *
12205 cmd_histedit(int argc, char *argv[])
12207 const struct got_error *error = NULL;
12208 struct got_worktree *worktree = NULL;
12209 struct got_fileindex *fileindex = NULL;
12210 struct got_repository *repo = NULL;
12211 char *cwd = NULL, *committer = NULL, *gitconfig_path = NULL;
12212 struct got_reference *branch = NULL;
12213 struct got_reference *tmp_branch = NULL;
12214 struct got_object_id *resume_commit_id = NULL;
12215 struct got_object_id *base_commit_id = NULL;
12216 struct got_object_id *head_commit_id = NULL;
12217 struct got_commit_object *commit = NULL;
12218 int ch, rebase_in_progress = 0, merge_in_progress = 0;
12219 struct got_update_progress_arg upa;
12220 int edit_in_progress = 0, abort_edit = 0, continue_edit = 0;
12221 int drop_only = 0, edit_logmsg_only = 0, fold_only = 0, edit_only = 0;
12222 int list_backups = 0, delete_backups = 0;
12223 const char *edit_script_path = NULL;
12224 struct got_object_id_queue commits;
12225 struct got_pathlist_head merged_paths;
12226 const struct got_object_id_queue *parent_ids;
12227 struct got_object_qid *pid;
12228 struct got_histedit_list histedit_cmds;
12229 struct got_histedit_list_entry *hle;
12230 int *pack_fds = NULL;
12232 STAILQ_INIT(&commits);
12233 TAILQ_INIT(&histedit_cmds);
12234 TAILQ_INIT(&merged_paths);
12235 memset(&upa, 0, sizeof(upa));
12237 while ((ch = getopt(argc, argv, "acdeF:flmX")) != -1) {
12238 switch (ch) {
12239 case 'a':
12240 abort_edit = 1;
12241 break;
12242 case 'c':
12243 continue_edit = 1;
12244 break;
12245 case 'd':
12246 drop_only = 1;
12247 break;
12248 case 'e':
12249 edit_only = 1;
12250 break;
12251 case 'F':
12252 edit_script_path = optarg;
12253 break;
12254 case 'f':
12255 fold_only = 1;
12256 break;
12257 case 'l':
12258 list_backups = 1;
12259 break;
12260 case 'm':
12261 edit_logmsg_only = 1;
12262 break;
12263 case 'X':
12264 delete_backups = 1;
12265 break;
12266 default:
12267 usage_histedit();
12268 /* NOTREACHED */
12272 argc -= optind;
12273 argv += optind;
12275 #ifndef PROFILE
12276 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
12277 "unveil", NULL) == -1)
12278 err(1, "pledge");
12279 #endif
12280 if (abort_edit && continue_edit)
12281 option_conflict('a', 'c');
12282 if (edit_script_path && edit_logmsg_only)
12283 option_conflict('F', 'm');
12284 if (abort_edit && edit_logmsg_only)
12285 option_conflict('a', 'm');
12286 if (continue_edit && edit_logmsg_only)
12287 option_conflict('c', 'm');
12288 if (abort_edit && fold_only)
12289 option_conflict('a', 'f');
12290 if (continue_edit && fold_only)
12291 option_conflict('c', 'f');
12292 if (fold_only && edit_logmsg_only)
12293 option_conflict('f', 'm');
12294 if (edit_script_path && fold_only)
12295 option_conflict('F', 'f');
12296 if (abort_edit && edit_only)
12297 option_conflict('a', 'e');
12298 if (continue_edit && edit_only)
12299 option_conflict('c', 'e');
12300 if (edit_only && edit_logmsg_only)
12301 option_conflict('e', 'm');
12302 if (edit_script_path && edit_only)
12303 option_conflict('F', 'e');
12304 if (fold_only && edit_only)
12305 option_conflict('f', 'e');
12306 if (drop_only && abort_edit)
12307 option_conflict('d', 'a');
12308 if (drop_only && continue_edit)
12309 option_conflict('d', 'c');
12310 if (drop_only && edit_logmsg_only)
12311 option_conflict('d', 'm');
12312 if (drop_only && edit_only)
12313 option_conflict('d', 'e');
12314 if (drop_only && edit_script_path)
12315 option_conflict('d', 'F');
12316 if (drop_only && fold_only)
12317 option_conflict('d', 'f');
12318 if (list_backups) {
12319 if (abort_edit)
12320 option_conflict('l', 'a');
12321 if (continue_edit)
12322 option_conflict('l', 'c');
12323 if (edit_script_path)
12324 option_conflict('l', 'F');
12325 if (edit_logmsg_only)
12326 option_conflict('l', 'm');
12327 if (drop_only)
12328 option_conflict('l', 'd');
12329 if (fold_only)
12330 option_conflict('l', 'f');
12331 if (edit_only)
12332 option_conflict('l', 'e');
12333 if (delete_backups)
12334 option_conflict('l', 'X');
12335 if (argc != 0 && argc != 1)
12336 usage_histedit();
12337 } else if (delete_backups) {
12338 if (abort_edit)
12339 option_conflict('X', 'a');
12340 if (continue_edit)
12341 option_conflict('X', 'c');
12342 if (drop_only)
12343 option_conflict('X', 'd');
12344 if (edit_script_path)
12345 option_conflict('X', 'F');
12346 if (edit_logmsg_only)
12347 option_conflict('X', 'm');
12348 if (fold_only)
12349 option_conflict('X', 'f');
12350 if (edit_only)
12351 option_conflict('X', 'e');
12352 if (list_backups)
12353 option_conflict('X', 'l');
12354 if (argc != 0 && argc != 1)
12355 usage_histedit();
12356 } else if (argc != 0)
12357 usage_histedit();
12360 * This command cannot apply unveil(2) in all cases because the
12361 * user may choose to run an editor to edit the histedit script
12362 * and to edit individual commit log messages.
12363 * unveil(2) traverses exec(2); if an editor is used we have to
12364 * apply unveil after edit script and log messages have been written.
12365 * XXX TODO: Make use of unveil(2) where possible.
12368 cwd = getcwd(NULL, 0);
12369 if (cwd == NULL) {
12370 error = got_error_from_errno("getcwd");
12371 goto done;
12374 error = got_repo_pack_fds_open(&pack_fds);
12375 if (error != NULL)
12376 goto done;
12378 error = got_worktree_open(&worktree, cwd);
12379 if (error) {
12380 if (list_backups || delete_backups) {
12381 if (error->code != GOT_ERR_NOT_WORKTREE)
12382 goto done;
12383 } else {
12384 if (error->code == GOT_ERR_NOT_WORKTREE)
12385 error = wrap_not_worktree_error(error,
12386 "histedit", cwd);
12387 goto done;
12391 if (list_backups || delete_backups) {
12392 error = got_repo_open(&repo,
12393 worktree ? got_worktree_get_repo_path(worktree) : cwd,
12394 NULL, pack_fds);
12395 if (error != NULL)
12396 goto done;
12397 error = apply_unveil(got_repo_get_path(repo), 0,
12398 worktree ? got_worktree_get_root_path(worktree) : NULL);
12399 if (error)
12400 goto done;
12401 error = process_backup_refs(
12402 GOT_WORKTREE_HISTEDIT_BACKUP_REF_PREFIX,
12403 argc == 1 ? argv[0] : NULL, delete_backups, repo);
12404 goto done; /* nothing else to do */
12407 error = get_gitconfig_path(&gitconfig_path);
12408 if (error)
12409 goto done;
12410 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
12411 gitconfig_path, pack_fds);
12412 if (error != NULL)
12413 goto done;
12415 if (worktree != NULL && !list_backups && !delete_backups) {
12416 error = worktree_has_logmsg_ref("histedit", worktree, repo);
12417 if (error)
12418 goto done;
12421 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
12422 if (error)
12423 goto done;
12424 if (rebase_in_progress) {
12425 error = got_error(GOT_ERR_REBASING);
12426 goto done;
12429 error = got_worktree_merge_in_progress(&merge_in_progress, worktree,
12430 repo);
12431 if (error)
12432 goto done;
12433 if (merge_in_progress) {
12434 error = got_error(GOT_ERR_MERGE_BUSY);
12435 goto done;
12438 error = got_worktree_histedit_in_progress(&edit_in_progress, worktree);
12439 if (error)
12440 goto done;
12442 if (edit_in_progress && edit_logmsg_only) {
12443 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
12444 "histedit operation is in progress in this "
12445 "work tree and must be continued or aborted "
12446 "before the -m option can be used");
12447 goto done;
12449 if (edit_in_progress && drop_only) {
12450 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
12451 "histedit operation is in progress in this "
12452 "work tree and must be continued or aborted "
12453 "before the -d option can be used");
12454 goto done;
12456 if (edit_in_progress && fold_only) {
12457 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
12458 "histedit operation is in progress in this "
12459 "work tree and must be continued or aborted "
12460 "before the -f option can be used");
12461 goto done;
12463 if (edit_in_progress && edit_only) {
12464 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
12465 "histedit operation is in progress in this "
12466 "work tree and must be continued or aborted "
12467 "before the -e option can be used");
12468 goto done;
12471 if (edit_in_progress && abort_edit) {
12472 error = got_worktree_histedit_continue(&resume_commit_id,
12473 &tmp_branch, &branch, &base_commit_id, &fileindex,
12474 worktree, repo);
12475 if (error)
12476 goto done;
12477 printf("Switching work tree to %s\n",
12478 got_ref_get_symref_target(branch));
12479 error = got_worktree_histedit_abort(worktree, fileindex, repo,
12480 branch, base_commit_id, abort_progress, &upa);
12481 if (error)
12482 goto done;
12483 printf("Histedit of %s aborted\n",
12484 got_ref_get_symref_target(branch));
12485 print_merge_progress_stats(&upa);
12486 goto done; /* nothing else to do */
12487 } else if (abort_edit) {
12488 error = got_error(GOT_ERR_NOT_HISTEDIT);
12489 goto done;
12492 error = get_author(&committer, repo, worktree);
12493 if (error)
12494 goto done;
12496 if (continue_edit) {
12497 char *path;
12499 if (!edit_in_progress) {
12500 error = got_error(GOT_ERR_NOT_HISTEDIT);
12501 goto done;
12504 error = got_worktree_get_histedit_script_path(&path, worktree);
12505 if (error)
12506 goto done;
12508 error = histedit_load_list(&histedit_cmds, path, repo);
12509 free(path);
12510 if (error)
12511 goto done;
12513 error = got_worktree_histedit_continue(&resume_commit_id,
12514 &tmp_branch, &branch, &base_commit_id, &fileindex,
12515 worktree, repo);
12516 if (error)
12517 goto done;
12519 error = got_ref_resolve(&head_commit_id, repo, branch);
12520 if (error)
12521 goto done;
12523 error = got_object_open_as_commit(&commit, repo,
12524 head_commit_id);
12525 if (error)
12526 goto done;
12527 parent_ids = got_object_commit_get_parent_ids(commit);
12528 pid = STAILQ_FIRST(parent_ids);
12529 if (pid == NULL) {
12530 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
12531 goto done;
12533 error = collect_commits(&commits, head_commit_id, &pid->id,
12534 base_commit_id, got_worktree_get_path_prefix(worktree),
12535 GOT_ERR_HISTEDIT_PATH, repo);
12536 got_object_commit_close(commit);
12537 commit = NULL;
12538 if (error)
12539 goto done;
12540 } else {
12541 if (edit_in_progress) {
12542 error = got_error(GOT_ERR_HISTEDIT_BUSY);
12543 goto done;
12546 error = got_ref_open(&branch, repo,
12547 got_worktree_get_head_ref_name(worktree), 0);
12548 if (error != NULL)
12549 goto done;
12551 if (strncmp(got_ref_get_name(branch), "refs/heads/", 11) != 0) {
12552 error = got_error_msg(GOT_ERR_COMMIT_BRANCH,
12553 "will not edit commit history of a branch outside "
12554 "the \"refs/heads/\" reference namespace");
12555 goto done;
12558 error = got_ref_resolve(&head_commit_id, repo, branch);
12559 got_ref_close(branch);
12560 branch = NULL;
12561 if (error)
12562 goto done;
12564 error = got_object_open_as_commit(&commit, repo,
12565 head_commit_id);
12566 if (error)
12567 goto done;
12568 parent_ids = got_object_commit_get_parent_ids(commit);
12569 pid = STAILQ_FIRST(parent_ids);
12570 if (pid == NULL) {
12571 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
12572 goto done;
12574 error = collect_commits(&commits, head_commit_id, &pid->id,
12575 got_worktree_get_base_commit_id(worktree),
12576 got_worktree_get_path_prefix(worktree),
12577 GOT_ERR_HISTEDIT_PATH, repo);
12578 got_object_commit_close(commit);
12579 commit = NULL;
12580 if (error)
12581 goto done;
12583 if (STAILQ_EMPTY(&commits)) {
12584 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
12585 goto done;
12588 error = got_worktree_histedit_prepare(&tmp_branch, &branch,
12589 &base_commit_id, &fileindex, worktree, repo);
12590 if (error)
12591 goto done;
12593 if (edit_script_path) {
12594 error = histedit_load_list(&histedit_cmds,
12595 edit_script_path, repo);
12596 if (error) {
12597 got_worktree_histedit_abort(worktree, fileindex,
12598 repo, branch, base_commit_id,
12599 abort_progress, &upa);
12600 print_merge_progress_stats(&upa);
12601 goto done;
12603 } else {
12604 const char *branch_name;
12605 branch_name = got_ref_get_symref_target(branch);
12606 if (strncmp(branch_name, "refs/heads/", 11) == 0)
12607 branch_name += 11;
12608 error = histedit_edit_script(&histedit_cmds, &commits,
12609 branch_name, edit_logmsg_only, fold_only,
12610 drop_only, edit_only, repo);
12611 if (error) {
12612 got_worktree_histedit_abort(worktree, fileindex,
12613 repo, branch, base_commit_id,
12614 abort_progress, &upa);
12615 print_merge_progress_stats(&upa);
12616 goto done;
12621 error = histedit_save_list(&histedit_cmds, worktree,
12622 repo);
12623 if (error) {
12624 got_worktree_histedit_abort(worktree, fileindex,
12625 repo, branch, base_commit_id,
12626 abort_progress, &upa);
12627 print_merge_progress_stats(&upa);
12628 goto done;
12633 error = histedit_check_script(&histedit_cmds, &commits, repo);
12634 if (error)
12635 goto done;
12637 TAILQ_FOREACH(hle, &histedit_cmds, entry) {
12638 if (resume_commit_id) {
12639 if (got_object_id_cmp(hle->commit_id,
12640 resume_commit_id) != 0)
12641 continue;
12643 resume_commit_id = NULL;
12644 if (hle->cmd->code == GOT_HISTEDIT_DROP ||
12645 hle->cmd->code == GOT_HISTEDIT_FOLD) {
12646 error = histedit_skip_commit(hle, worktree,
12647 repo);
12648 if (error)
12649 goto done;
12650 } else {
12651 struct got_pathlist_head paths;
12652 int have_changes = 0;
12654 TAILQ_INIT(&paths);
12655 error = got_pathlist_append(&paths, "", NULL);
12656 if (error)
12657 goto done;
12658 error = got_worktree_status(worktree, &paths,
12659 repo, 0, check_local_changes, &have_changes,
12660 check_cancelled, NULL);
12661 got_pathlist_free(&paths,
12662 GOT_PATHLIST_FREE_NONE);
12663 if (error) {
12664 if (error->code != GOT_ERR_CANCELLED)
12665 goto done;
12666 if (sigint_received || sigpipe_received)
12667 goto done;
12669 if (have_changes) {
12670 error = histedit_commit(NULL, worktree,
12671 fileindex, tmp_branch, hle,
12672 committer, repo);
12673 if (error)
12674 goto done;
12675 } else {
12676 error = got_object_open_as_commit(
12677 &commit, repo, hle->commit_id);
12678 if (error)
12679 goto done;
12680 error = show_histedit_progress(commit,
12681 hle, NULL);
12682 got_object_commit_close(commit);
12683 commit = NULL;
12684 if (error)
12685 goto done;
12688 continue;
12691 if (hle->cmd->code == GOT_HISTEDIT_DROP) {
12692 error = histedit_skip_commit(hle, worktree, repo);
12693 if (error)
12694 goto done;
12695 continue;
12698 error = got_object_open_as_commit(&commit, repo,
12699 hle->commit_id);
12700 if (error)
12701 goto done;
12702 parent_ids = got_object_commit_get_parent_ids(commit);
12703 pid = STAILQ_FIRST(parent_ids);
12705 error = got_worktree_histedit_merge_files(&merged_paths,
12706 worktree, fileindex, &pid->id, hle->commit_id, repo,
12707 update_progress, &upa, check_cancelled, NULL);
12708 if (error)
12709 goto done;
12710 got_object_commit_close(commit);
12711 commit = NULL;
12713 print_merge_progress_stats(&upa);
12714 if (upa.conflicts > 0 || upa.missing > 0 ||
12715 upa.not_deleted > 0 || upa.unversioned > 0) {
12716 if (upa.conflicts > 0) {
12717 error = show_rebase_merge_conflict(
12718 hle->commit_id, repo);
12719 if (error)
12720 goto done;
12722 got_pathlist_free(&merged_paths, GOT_PATHLIST_FREE_PATH);
12723 break;
12726 if (hle->cmd->code == GOT_HISTEDIT_EDIT) {
12727 char *id_str;
12728 error = got_object_id_str(&id_str, hle->commit_id);
12729 if (error)
12730 goto done;
12731 printf("Stopping histedit for amending commit %s\n",
12732 id_str);
12733 free(id_str);
12734 got_pathlist_free(&merged_paths, GOT_PATHLIST_FREE_PATH);
12735 error = got_worktree_histedit_postpone(worktree,
12736 fileindex);
12737 goto done;
12740 if (hle->cmd->code == GOT_HISTEDIT_FOLD) {
12741 error = histedit_skip_commit(hle, worktree, repo);
12742 if (error)
12743 goto done;
12744 continue;
12747 error = histedit_commit(&merged_paths, worktree, fileindex,
12748 tmp_branch, hle, committer, repo);
12749 got_pathlist_free(&merged_paths, GOT_PATHLIST_FREE_PATH);
12750 if (error)
12751 goto done;
12754 if (upa.conflicts > 0 || upa.missing > 0 ||
12755 upa.not_deleted > 0 || upa.unversioned > 0) {
12756 error = got_worktree_histedit_postpone(worktree, fileindex);
12757 if (error)
12758 goto done;
12759 if (upa.conflicts > 0 && upa.missing == 0 &&
12760 upa.not_deleted == 0 && upa.unversioned == 0) {
12761 error = got_error_msg(GOT_ERR_CONFLICTS,
12762 "conflicts must be resolved before histedit "
12763 "can continue");
12764 } else if (upa.conflicts > 0) {
12765 error = got_error_msg(GOT_ERR_CONFLICTS,
12766 "conflicts must be resolved before histedit "
12767 "can continue; changes destined for some "
12768 "files were not yet merged and should be "
12769 "merged manually if required before the "
12770 "histedit operation is continued");
12771 } else {
12772 error = got_error_msg(GOT_ERR_CONFLICTS,
12773 "changes destined for some files were not "
12774 "yet merged and should be merged manually "
12775 "if required before the histedit operation "
12776 "is continued");
12778 } else
12779 error = histedit_complete(worktree, fileindex, tmp_branch,
12780 branch, repo);
12781 done:
12782 free(cwd);
12783 free(committer);
12784 free(gitconfig_path);
12785 got_object_id_queue_free(&commits);
12786 histedit_free_list(&histedit_cmds);
12787 free(head_commit_id);
12788 free(base_commit_id);
12789 free(resume_commit_id);
12790 if (commit)
12791 got_object_commit_close(commit);
12792 if (branch)
12793 got_ref_close(branch);
12794 if (tmp_branch)
12795 got_ref_close(tmp_branch);
12796 if (worktree)
12797 got_worktree_close(worktree);
12798 if (repo) {
12799 const struct got_error *close_err = got_repo_close(repo);
12800 if (error == NULL)
12801 error = close_err;
12803 if (pack_fds) {
12804 const struct got_error *pack_err =
12805 got_repo_pack_fds_close(pack_fds);
12806 if (error == NULL)
12807 error = pack_err;
12809 return error;
12812 __dead static void
12813 usage_integrate(void)
12815 fprintf(stderr, "usage: %s integrate branch\n", getprogname());
12816 exit(1);
12819 static const struct got_error *
12820 cmd_integrate(int argc, char *argv[])
12822 const struct got_error *error = NULL;
12823 struct got_repository *repo = NULL;
12824 struct got_worktree *worktree = NULL;
12825 char *cwd = NULL, *refname = NULL, *base_refname = NULL;
12826 const char *branch_arg = NULL;
12827 struct got_reference *branch_ref = NULL, *base_branch_ref = NULL;
12828 struct got_fileindex *fileindex = NULL;
12829 struct got_object_id *commit_id = NULL, *base_commit_id = NULL;
12830 int ch;
12831 struct got_update_progress_arg upa;
12832 int *pack_fds = NULL;
12834 while ((ch = getopt(argc, argv, "")) != -1) {
12835 switch (ch) {
12836 default:
12837 usage_integrate();
12838 /* NOTREACHED */
12842 argc -= optind;
12843 argv += optind;
12845 if (argc != 1)
12846 usage_integrate();
12847 branch_arg = argv[0];
12848 #ifndef PROFILE
12849 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
12850 "unveil", NULL) == -1)
12851 err(1, "pledge");
12852 #endif
12853 cwd = getcwd(NULL, 0);
12854 if (cwd == NULL) {
12855 error = got_error_from_errno("getcwd");
12856 goto done;
12859 error = got_repo_pack_fds_open(&pack_fds);
12860 if (error != NULL)
12861 goto done;
12863 error = got_worktree_open(&worktree, cwd);
12864 if (error) {
12865 if (error->code == GOT_ERR_NOT_WORKTREE)
12866 error = wrap_not_worktree_error(error, "integrate",
12867 cwd);
12868 goto done;
12871 error = check_rebase_or_histedit_in_progress(worktree);
12872 if (error)
12873 goto done;
12875 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
12876 NULL, pack_fds);
12877 if (error != NULL)
12878 goto done;
12880 error = apply_unveil(got_repo_get_path(repo), 0,
12881 got_worktree_get_root_path(worktree));
12882 if (error)
12883 goto done;
12885 error = check_merge_in_progress(worktree, repo);
12886 if (error)
12887 goto done;
12889 if (asprintf(&refname, "refs/heads/%s", branch_arg) == -1) {
12890 error = got_error_from_errno("asprintf");
12891 goto done;
12894 error = got_worktree_integrate_prepare(&fileindex, &branch_ref,
12895 &base_branch_ref, worktree, refname, repo);
12896 if (error)
12897 goto done;
12899 refname = strdup(got_ref_get_name(branch_ref));
12900 if (refname == NULL) {
12901 error = got_error_from_errno("strdup");
12902 got_worktree_integrate_abort(worktree, fileindex, repo,
12903 branch_ref, base_branch_ref);
12904 goto done;
12906 base_refname = strdup(got_ref_get_name(base_branch_ref));
12907 if (base_refname == NULL) {
12908 error = got_error_from_errno("strdup");
12909 got_worktree_integrate_abort(worktree, fileindex, repo,
12910 branch_ref, base_branch_ref);
12911 goto done;
12913 if (strncmp(base_refname, "refs/heads/", 11) != 0) {
12914 error = got_error(GOT_ERR_INTEGRATE_BRANCH);
12915 got_worktree_integrate_abort(worktree, fileindex, repo,
12916 branch_ref, base_branch_ref);
12917 goto done;
12920 error = got_ref_resolve(&commit_id, repo, branch_ref);
12921 if (error)
12922 goto done;
12924 error = got_ref_resolve(&base_commit_id, repo, base_branch_ref);
12925 if (error)
12926 goto done;
12928 if (got_object_id_cmp(commit_id, base_commit_id) == 0) {
12929 error = got_error_msg(GOT_ERR_SAME_BRANCH,
12930 "specified branch has already been integrated");
12931 got_worktree_integrate_abort(worktree, fileindex, repo,
12932 branch_ref, base_branch_ref);
12933 goto done;
12936 error = check_linear_ancestry(commit_id, base_commit_id, 1, repo);
12937 if (error) {
12938 if (error->code == GOT_ERR_ANCESTRY)
12939 error = got_error(GOT_ERR_REBASE_REQUIRED);
12940 got_worktree_integrate_abort(worktree, fileindex, repo,
12941 branch_ref, base_branch_ref);
12942 goto done;
12945 memset(&upa, 0, sizeof(upa));
12946 error = got_worktree_integrate_continue(worktree, fileindex, repo,
12947 branch_ref, base_branch_ref, update_progress, &upa,
12948 check_cancelled, NULL);
12949 if (error)
12950 goto done;
12952 printf("Integrated %s into %s\n", refname, base_refname);
12953 print_update_progress_stats(&upa);
12954 done:
12955 if (repo) {
12956 const struct got_error *close_err = got_repo_close(repo);
12957 if (error == NULL)
12958 error = close_err;
12960 if (worktree)
12961 got_worktree_close(worktree);
12962 if (pack_fds) {
12963 const struct got_error *pack_err =
12964 got_repo_pack_fds_close(pack_fds);
12965 if (error == NULL)
12966 error = pack_err;
12968 free(cwd);
12969 free(base_commit_id);
12970 free(commit_id);
12971 free(refname);
12972 free(base_refname);
12973 return error;
12976 __dead static void
12977 usage_merge(void)
12979 fprintf(stderr, "usage: %s merge [-acn] [branch]\n", getprogname());
12980 exit(1);
12983 static const struct got_error *
12984 cmd_merge(int argc, char *argv[])
12986 const struct got_error *error = NULL;
12987 struct got_worktree *worktree = NULL;
12988 struct got_repository *repo = NULL;
12989 struct got_fileindex *fileindex = NULL;
12990 char *cwd = NULL, *id_str = NULL, *author = NULL;
12991 struct got_reference *branch = NULL, *wt_branch = NULL;
12992 struct got_object_id *branch_tip = NULL, *yca_id = NULL;
12993 struct got_object_id *wt_branch_tip = NULL;
12994 int ch, merge_in_progress = 0, abort_merge = 0, continue_merge = 0;
12995 int interrupt_merge = 0;
12996 struct got_update_progress_arg upa;
12997 struct got_object_id *merge_commit_id = NULL;
12998 char *branch_name = NULL;
12999 int *pack_fds = NULL;
13001 memset(&upa, 0, sizeof(upa));
13003 while ((ch = getopt(argc, argv, "acn")) != -1) {
13004 switch (ch) {
13005 case 'a':
13006 abort_merge = 1;
13007 break;
13008 case 'c':
13009 continue_merge = 1;
13010 break;
13011 case 'n':
13012 interrupt_merge = 1;
13013 break;
13014 default:
13015 usage_merge();
13016 /* NOTREACHED */
13020 argc -= optind;
13021 argv += optind;
13023 #ifndef PROFILE
13024 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
13025 "unveil", NULL) == -1)
13026 err(1, "pledge");
13027 #endif
13029 if (abort_merge && continue_merge)
13030 option_conflict('a', 'c');
13031 if (abort_merge || continue_merge) {
13032 if (argc != 0)
13033 usage_merge();
13034 } else if (argc != 1)
13035 usage_merge();
13037 cwd = getcwd(NULL, 0);
13038 if (cwd == NULL) {
13039 error = got_error_from_errno("getcwd");
13040 goto done;
13043 error = got_repo_pack_fds_open(&pack_fds);
13044 if (error != NULL)
13045 goto done;
13047 error = got_worktree_open(&worktree, cwd);
13048 if (error) {
13049 if (error->code == GOT_ERR_NOT_WORKTREE)
13050 error = wrap_not_worktree_error(error,
13051 "merge", cwd);
13052 goto done;
13055 error = got_repo_open(&repo,
13056 worktree ? got_worktree_get_repo_path(worktree) : cwd, NULL,
13057 pack_fds);
13058 if (error != NULL)
13059 goto done;
13061 if (worktree != NULL) {
13062 error = worktree_has_logmsg_ref("merge", worktree, repo);
13063 if (error)
13064 goto done;
13067 error = apply_unveil(got_repo_get_path(repo), 0,
13068 worktree ? got_worktree_get_root_path(worktree) : NULL);
13069 if (error)
13070 goto done;
13072 error = check_rebase_or_histedit_in_progress(worktree);
13073 if (error)
13074 goto done;
13076 error = got_worktree_merge_in_progress(&merge_in_progress, worktree,
13077 repo);
13078 if (error)
13079 goto done;
13081 if (abort_merge) {
13082 if (!merge_in_progress) {
13083 error = got_error(GOT_ERR_NOT_MERGING);
13084 goto done;
13086 error = got_worktree_merge_continue(&branch_name,
13087 &branch_tip, &fileindex, worktree, repo);
13088 if (error)
13089 goto done;
13090 error = got_worktree_merge_abort(worktree, fileindex, repo,
13091 abort_progress, &upa);
13092 if (error)
13093 goto done;
13094 printf("Merge of %s aborted\n", branch_name);
13095 goto done; /* nothing else to do */
13098 error = get_author(&author, repo, worktree);
13099 if (error)
13100 goto done;
13102 if (continue_merge) {
13103 if (!merge_in_progress) {
13104 error = got_error(GOT_ERR_NOT_MERGING);
13105 goto done;
13107 error = got_worktree_merge_continue(&branch_name,
13108 &branch_tip, &fileindex, worktree, repo);
13109 if (error)
13110 goto done;
13111 } else {
13112 error = got_ref_open(&branch, repo, argv[0], 0);
13113 if (error != NULL)
13114 goto done;
13115 branch_name = strdup(got_ref_get_name(branch));
13116 if (branch_name == NULL) {
13117 error = got_error_from_errno("strdup");
13118 goto done;
13120 error = got_ref_resolve(&branch_tip, repo, branch);
13121 if (error)
13122 goto done;
13125 error = got_ref_open(&wt_branch, repo,
13126 got_worktree_get_head_ref_name(worktree), 0);
13127 if (error)
13128 goto done;
13129 error = got_ref_resolve(&wt_branch_tip, repo, wt_branch);
13130 if (error)
13131 goto done;
13132 error = got_commit_graph_find_youngest_common_ancestor(&yca_id,
13133 wt_branch_tip, branch_tip, 0, repo,
13134 check_cancelled, NULL);
13135 if (error && error->code != GOT_ERR_ANCESTRY)
13136 goto done;
13138 if (!continue_merge) {
13139 error = check_path_prefix(wt_branch_tip, branch_tip,
13140 got_worktree_get_path_prefix(worktree),
13141 GOT_ERR_MERGE_PATH, repo);
13142 if (error)
13143 goto done;
13144 if (yca_id) {
13145 error = check_same_branch(wt_branch_tip, branch,
13146 yca_id, repo);
13147 if (error) {
13148 if (error->code != GOT_ERR_ANCESTRY)
13149 goto done;
13150 error = NULL;
13151 } else {
13152 static char msg[512];
13153 snprintf(msg, sizeof(msg),
13154 "cannot create a merge commit because "
13155 "%s is based on %s; %s can be integrated "
13156 "with 'got integrate' instead", branch_name,
13157 got_worktree_get_head_ref_name(worktree),
13158 branch_name);
13159 error = got_error_msg(GOT_ERR_SAME_BRANCH, msg);
13160 goto done;
13163 error = got_worktree_merge_prepare(&fileindex, worktree,
13164 branch, repo);
13165 if (error)
13166 goto done;
13168 error = got_worktree_merge_branch(worktree, fileindex,
13169 yca_id, branch_tip, repo, update_progress, &upa,
13170 check_cancelled, NULL);
13171 if (error)
13172 goto done;
13173 print_merge_progress_stats(&upa);
13174 if (!upa.did_something) {
13175 error = got_worktree_merge_abort(worktree, fileindex,
13176 repo, abort_progress, &upa);
13177 if (error)
13178 goto done;
13179 printf("Already up-to-date\n");
13180 goto done;
13184 if (interrupt_merge) {
13185 error = got_worktree_merge_postpone(worktree, fileindex);
13186 if (error)
13187 goto done;
13188 printf("Merge of %s interrupted on request\n", branch_name);
13189 } else if (upa.conflicts > 0 || upa.missing > 0 ||
13190 upa.not_deleted > 0 || upa.unversioned > 0) {
13191 error = got_worktree_merge_postpone(worktree, fileindex);
13192 if (error)
13193 goto done;
13194 if (upa.conflicts > 0 && upa.missing == 0 &&
13195 upa.not_deleted == 0 && upa.unversioned == 0) {
13196 error = got_error_msg(GOT_ERR_CONFLICTS,
13197 "conflicts must be resolved before merging "
13198 "can continue");
13199 } else if (upa.conflicts > 0) {
13200 error = got_error_msg(GOT_ERR_CONFLICTS,
13201 "conflicts must be resolved before merging "
13202 "can continue; changes destined for some "
13203 "files were not yet merged and "
13204 "should be merged manually if required before the "
13205 "merge operation is continued");
13206 } else {
13207 error = got_error_msg(GOT_ERR_CONFLICTS,
13208 "changes destined for some "
13209 "files were not yet merged and should be "
13210 "merged manually if required before the "
13211 "merge operation is continued");
13213 goto done;
13214 } else {
13215 error = got_worktree_merge_commit(&merge_commit_id, worktree,
13216 fileindex, author, NULL, 1, branch_tip, branch_name,
13217 repo, continue_merge ? print_status : NULL, NULL);
13218 if (error)
13219 goto done;
13220 error = got_worktree_merge_complete(worktree, fileindex, repo);
13221 if (error)
13222 goto done;
13223 error = got_object_id_str(&id_str, merge_commit_id);
13224 if (error)
13225 goto done;
13226 printf("Merged %s into %s: %s\n", branch_name,
13227 got_worktree_get_head_ref_name(worktree),
13228 id_str);
13231 done:
13232 free(id_str);
13233 free(merge_commit_id);
13234 free(author);
13235 free(branch_tip);
13236 free(branch_name);
13237 free(yca_id);
13238 if (branch)
13239 got_ref_close(branch);
13240 if (wt_branch)
13241 got_ref_close(wt_branch);
13242 if (worktree)
13243 got_worktree_close(worktree);
13244 if (repo) {
13245 const struct got_error *close_err = got_repo_close(repo);
13246 if (error == NULL)
13247 error = close_err;
13249 if (pack_fds) {
13250 const struct got_error *pack_err =
13251 got_repo_pack_fds_close(pack_fds);
13252 if (error == NULL)
13253 error = pack_err;
13255 return error;
13258 __dead static void
13259 usage_stage(void)
13261 fprintf(stderr, "usage: %s stage [-lpS] [-F response-script] "
13262 "[path ...]\n", getprogname());
13263 exit(1);
13266 static const struct got_error *
13267 print_stage(void *arg, unsigned char status, unsigned char staged_status,
13268 const char *path, struct got_object_id *blob_id,
13269 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
13270 int dirfd, const char *de_name)
13272 const struct got_error *err = NULL;
13273 char *id_str = NULL;
13275 if (staged_status != GOT_STATUS_ADD &&
13276 staged_status != GOT_STATUS_MODIFY &&
13277 staged_status != GOT_STATUS_DELETE)
13278 return NULL;
13280 if (staged_status == GOT_STATUS_ADD ||
13281 staged_status == GOT_STATUS_MODIFY)
13282 err = got_object_id_str(&id_str, staged_blob_id);
13283 else
13284 err = got_object_id_str(&id_str, blob_id);
13285 if (err)
13286 return err;
13288 printf("%s %c %s\n", id_str, staged_status, path);
13289 free(id_str);
13290 return NULL;
13293 static const struct got_error *
13294 cmd_stage(int argc, char *argv[])
13296 const struct got_error *error = NULL;
13297 struct got_repository *repo = NULL;
13298 struct got_worktree *worktree = NULL;
13299 char *cwd = NULL;
13300 struct got_pathlist_head paths;
13301 int ch, list_stage = 0, pflag = 0, allow_bad_symlinks = 0;
13302 FILE *patch_script_file = NULL;
13303 const char *patch_script_path = NULL;
13304 struct choose_patch_arg cpa;
13305 int *pack_fds = NULL;
13307 TAILQ_INIT(&paths);
13309 while ((ch = getopt(argc, argv, "F:lpS")) != -1) {
13310 switch (ch) {
13311 case 'F':
13312 patch_script_path = optarg;
13313 break;
13314 case 'l':
13315 list_stage = 1;
13316 break;
13317 case 'p':
13318 pflag = 1;
13319 break;
13320 case 'S':
13321 allow_bad_symlinks = 1;
13322 break;
13323 default:
13324 usage_stage();
13325 /* NOTREACHED */
13329 argc -= optind;
13330 argv += optind;
13332 #ifndef PROFILE
13333 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
13334 "unveil", NULL) == -1)
13335 err(1, "pledge");
13336 #endif
13337 if (list_stage && (pflag || patch_script_path))
13338 errx(1, "-l option cannot be used with other options");
13339 if (patch_script_path && !pflag)
13340 errx(1, "-F option can only be used together with -p option");
13342 cwd = getcwd(NULL, 0);
13343 if (cwd == NULL) {
13344 error = got_error_from_errno("getcwd");
13345 goto done;
13348 error = got_repo_pack_fds_open(&pack_fds);
13349 if (error != NULL)
13350 goto done;
13352 error = got_worktree_open(&worktree, cwd);
13353 if (error) {
13354 if (error->code == GOT_ERR_NOT_WORKTREE)
13355 error = wrap_not_worktree_error(error, "stage", cwd);
13356 goto done;
13359 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
13360 NULL, pack_fds);
13361 if (error != NULL)
13362 goto done;
13364 if (patch_script_path) {
13365 patch_script_file = fopen(patch_script_path, "re");
13366 if (patch_script_file == NULL) {
13367 error = got_error_from_errno2("fopen",
13368 patch_script_path);
13369 goto done;
13372 error = apply_unveil(got_repo_get_path(repo), 0,
13373 got_worktree_get_root_path(worktree));
13374 if (error)
13375 goto done;
13377 error = check_merge_in_progress(worktree, repo);
13378 if (error)
13379 goto done;
13381 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
13382 if (error)
13383 goto done;
13385 if (list_stage)
13386 error = got_worktree_status(worktree, &paths, repo, 0,
13387 print_stage, NULL, check_cancelled, NULL);
13388 else {
13389 cpa.patch_script_file = patch_script_file;
13390 cpa.action = "stage";
13391 error = got_worktree_stage(worktree, &paths,
13392 pflag ? NULL : print_status, NULL,
13393 pflag ? choose_patch : NULL, &cpa,
13394 allow_bad_symlinks, repo);
13396 done:
13397 if (patch_script_file && fclose(patch_script_file) == EOF &&
13398 error == NULL)
13399 error = got_error_from_errno2("fclose", patch_script_path);
13400 if (repo) {
13401 const struct got_error *close_err = got_repo_close(repo);
13402 if (error == NULL)
13403 error = close_err;
13405 if (worktree)
13406 got_worktree_close(worktree);
13407 if (pack_fds) {
13408 const struct got_error *pack_err =
13409 got_repo_pack_fds_close(pack_fds);
13410 if (error == NULL)
13411 error = pack_err;
13413 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
13414 free(cwd);
13415 return error;
13418 __dead static void
13419 usage_unstage(void)
13421 fprintf(stderr, "usage: %s unstage [-p] [-F response-script] "
13422 "[path ...]\n", getprogname());
13423 exit(1);
13427 static const struct got_error *
13428 cmd_unstage(int argc, char *argv[])
13430 const struct got_error *error = NULL;
13431 struct got_repository *repo = NULL;
13432 struct got_worktree *worktree = NULL;
13433 char *cwd = NULL;
13434 struct got_pathlist_head paths;
13435 int ch, pflag = 0;
13436 struct got_update_progress_arg upa;
13437 FILE *patch_script_file = NULL;
13438 const char *patch_script_path = NULL;
13439 struct choose_patch_arg cpa;
13440 int *pack_fds = NULL;
13442 TAILQ_INIT(&paths);
13444 while ((ch = getopt(argc, argv, "F:p")) != -1) {
13445 switch (ch) {
13446 case 'F':
13447 patch_script_path = optarg;
13448 break;
13449 case 'p':
13450 pflag = 1;
13451 break;
13452 default:
13453 usage_unstage();
13454 /* NOTREACHED */
13458 argc -= optind;
13459 argv += optind;
13461 #ifndef PROFILE
13462 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
13463 "unveil", NULL) == -1)
13464 err(1, "pledge");
13465 #endif
13466 if (patch_script_path && !pflag)
13467 errx(1, "-F option can only be used together with -p option");
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);
13480 if (error) {
13481 if (error->code == GOT_ERR_NOT_WORKTREE)
13482 error = wrap_not_worktree_error(error, "unstage", cwd);
13483 goto done;
13486 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
13487 NULL, pack_fds);
13488 if (error != NULL)
13489 goto done;
13491 if (patch_script_path) {
13492 patch_script_file = fopen(patch_script_path, "re");
13493 if (patch_script_file == NULL) {
13494 error = got_error_from_errno2("fopen",
13495 patch_script_path);
13496 goto done;
13500 error = apply_unveil(got_repo_get_path(repo), 0,
13501 got_worktree_get_root_path(worktree));
13502 if (error)
13503 goto done;
13505 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
13506 if (error)
13507 goto done;
13509 cpa.patch_script_file = patch_script_file;
13510 cpa.action = "unstage";
13511 memset(&upa, 0, sizeof(upa));
13512 error = got_worktree_unstage(worktree, &paths, update_progress,
13513 &upa, pflag ? choose_patch : NULL, &cpa, repo);
13514 if (!error)
13515 print_merge_progress_stats(&upa);
13516 done:
13517 if (patch_script_file && fclose(patch_script_file) == EOF &&
13518 error == NULL)
13519 error = got_error_from_errno2("fclose", patch_script_path);
13520 if (repo) {
13521 const struct got_error *close_err = got_repo_close(repo);
13522 if (error == NULL)
13523 error = close_err;
13525 if (worktree)
13526 got_worktree_close(worktree);
13527 if (pack_fds) {
13528 const struct got_error *pack_err =
13529 got_repo_pack_fds_close(pack_fds);
13530 if (error == NULL)
13531 error = pack_err;
13533 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
13534 free(cwd);
13535 return error;
13538 __dead static void
13539 usage_cat(void)
13541 fprintf(stderr, "usage: %s cat [-P] [-c commit] [-r repository-path] "
13542 "arg ...\n", getprogname());
13543 exit(1);
13546 static const struct got_error *
13547 cat_blob(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
13549 const struct got_error *err;
13550 struct got_blob_object *blob;
13551 int fd = -1;
13553 fd = got_opentempfd();
13554 if (fd == -1)
13555 return got_error_from_errno("got_opentempfd");
13557 err = got_object_open_as_blob(&blob, repo, id, 8192, fd);
13558 if (err)
13559 goto done;
13561 err = got_object_blob_dump_to_file(NULL, NULL, NULL, outfile, blob);
13562 done:
13563 if (fd != -1 && close(fd) == -1 && err == NULL)
13564 err = got_error_from_errno("close");
13565 if (blob)
13566 got_object_blob_close(blob);
13567 return err;
13570 static const struct got_error *
13571 cat_tree(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
13573 const struct got_error *err;
13574 struct got_tree_object *tree;
13575 int nentries, i;
13577 err = got_object_open_as_tree(&tree, repo, id);
13578 if (err)
13579 return err;
13581 nentries = got_object_tree_get_nentries(tree);
13582 for (i = 0; i < nentries; i++) {
13583 struct got_tree_entry *te;
13584 char *id_str;
13585 if (sigint_received || sigpipe_received)
13586 break;
13587 te = got_object_tree_get_entry(tree, i);
13588 err = got_object_id_str(&id_str, got_tree_entry_get_id(te));
13589 if (err)
13590 break;
13591 fprintf(outfile, "%s %.7o %s\n", id_str,
13592 got_tree_entry_get_mode(te),
13593 got_tree_entry_get_name(te));
13594 free(id_str);
13597 got_object_tree_close(tree);
13598 return err;
13601 static const struct got_error *
13602 cat_commit(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
13604 const struct got_error *err;
13605 struct got_commit_object *commit;
13606 const struct got_object_id_queue *parent_ids;
13607 struct got_object_qid *pid;
13608 char *id_str = NULL;
13609 const char *logmsg = NULL;
13610 char gmtoff[6];
13612 err = got_object_open_as_commit(&commit, repo, id);
13613 if (err)
13614 return err;
13616 err = got_object_id_str(&id_str, got_object_commit_get_tree_id(commit));
13617 if (err)
13618 goto done;
13620 fprintf(outfile, "%s%s\n", GOT_COMMIT_LABEL_TREE, id_str);
13621 parent_ids = got_object_commit_get_parent_ids(commit);
13622 fprintf(outfile, "numparents %d\n",
13623 got_object_commit_get_nparents(commit));
13624 STAILQ_FOREACH(pid, parent_ids, entry) {
13625 char *pid_str;
13626 err = got_object_id_str(&pid_str, &pid->id);
13627 if (err)
13628 goto done;
13629 fprintf(outfile, "%s%s\n", GOT_COMMIT_LABEL_PARENT, pid_str);
13630 free(pid_str);
13632 got_date_format_gmtoff(gmtoff, sizeof(gmtoff),
13633 got_object_commit_get_author_gmtoff(commit));
13634 fprintf(outfile, "%s%s %lld %s\n", GOT_COMMIT_LABEL_AUTHOR,
13635 got_object_commit_get_author(commit),
13636 (long long)got_object_commit_get_author_time(commit),
13637 gmtoff);
13639 got_date_format_gmtoff(gmtoff, sizeof(gmtoff),
13640 got_object_commit_get_committer_gmtoff(commit));
13641 fprintf(outfile, "%s%s %lld %s\n", GOT_COMMIT_LABEL_COMMITTER,
13642 got_object_commit_get_committer(commit),
13643 (long long)got_object_commit_get_committer_time(commit),
13644 gmtoff);
13646 logmsg = got_object_commit_get_logmsg_raw(commit);
13647 fprintf(outfile, "messagelen %zd\n", strlen(logmsg));
13648 fprintf(outfile, "%s", logmsg);
13649 done:
13650 free(id_str);
13651 got_object_commit_close(commit);
13652 return err;
13655 static const struct got_error *
13656 cat_tag(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
13658 const struct got_error *err;
13659 struct got_tag_object *tag;
13660 char *id_str = NULL;
13661 const char *tagmsg = NULL;
13662 char gmtoff[6];
13664 err = got_object_open_as_tag(&tag, repo, id);
13665 if (err)
13666 return err;
13668 err = got_object_id_str(&id_str, got_object_tag_get_object_id(tag));
13669 if (err)
13670 goto done;
13672 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_OBJECT, id_str);
13674 switch (got_object_tag_get_object_type(tag)) {
13675 case GOT_OBJ_TYPE_BLOB:
13676 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
13677 GOT_OBJ_LABEL_BLOB);
13678 break;
13679 case GOT_OBJ_TYPE_TREE:
13680 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
13681 GOT_OBJ_LABEL_TREE);
13682 break;
13683 case GOT_OBJ_TYPE_COMMIT:
13684 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
13685 GOT_OBJ_LABEL_COMMIT);
13686 break;
13687 case GOT_OBJ_TYPE_TAG:
13688 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
13689 GOT_OBJ_LABEL_TAG);
13690 break;
13691 default:
13692 break;
13695 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TAG,
13696 got_object_tag_get_name(tag));
13698 got_date_format_gmtoff(gmtoff, sizeof(gmtoff),
13699 got_object_tag_get_tagger_gmtoff(tag));
13700 fprintf(outfile, "%s%s %lld %s\n", GOT_TAG_LABEL_TAGGER,
13701 got_object_tag_get_tagger(tag),
13702 (long long)got_object_tag_get_tagger_time(tag),
13703 gmtoff);
13705 tagmsg = got_object_tag_get_message(tag);
13706 fprintf(outfile, "messagelen %zd\n", strlen(tagmsg));
13707 fprintf(outfile, "%s", tagmsg);
13708 done:
13709 free(id_str);
13710 got_object_tag_close(tag);
13711 return err;
13714 static const struct got_error *
13715 cmd_cat(int argc, char *argv[])
13717 const struct got_error *error;
13718 struct got_repository *repo = NULL;
13719 struct got_worktree *worktree = NULL;
13720 char *cwd = NULL, *repo_path = NULL, *label = NULL;
13721 const char *commit_id_str = NULL;
13722 struct got_object_id *id = NULL, *commit_id = NULL;
13723 struct got_commit_object *commit = NULL;
13724 int ch, obj_type, i, force_path = 0;
13725 struct got_reflist_head refs;
13726 int *pack_fds = NULL;
13728 TAILQ_INIT(&refs);
13730 #ifndef PROFILE
13731 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
13732 NULL) == -1)
13733 err(1, "pledge");
13734 #endif
13736 while ((ch = getopt(argc, argv, "c:Pr:")) != -1) {
13737 switch (ch) {
13738 case 'c':
13739 commit_id_str = optarg;
13740 break;
13741 case 'P':
13742 force_path = 1;
13743 break;
13744 case 'r':
13745 repo_path = realpath(optarg, NULL);
13746 if (repo_path == NULL)
13747 return got_error_from_errno2("realpath",
13748 optarg);
13749 got_path_strip_trailing_slashes(repo_path);
13750 break;
13751 default:
13752 usage_cat();
13753 /* NOTREACHED */
13757 argc -= optind;
13758 argv += optind;
13760 cwd = getcwd(NULL, 0);
13761 if (cwd == NULL) {
13762 error = got_error_from_errno("getcwd");
13763 goto done;
13766 error = got_repo_pack_fds_open(&pack_fds);
13767 if (error != NULL)
13768 goto done;
13770 if (repo_path == NULL) {
13771 error = got_worktree_open(&worktree, cwd);
13772 if (error && error->code != GOT_ERR_NOT_WORKTREE)
13773 goto done;
13774 if (worktree) {
13775 repo_path = strdup(
13776 got_worktree_get_repo_path(worktree));
13777 if (repo_path == NULL) {
13778 error = got_error_from_errno("strdup");
13779 goto done;
13782 /* Release work tree lock. */
13783 got_worktree_close(worktree);
13784 worktree = NULL;
13788 if (repo_path == NULL) {
13789 repo_path = strdup(cwd);
13790 if (repo_path == NULL)
13791 return got_error_from_errno("strdup");
13794 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
13795 free(repo_path);
13796 if (error != NULL)
13797 goto done;
13799 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
13800 if (error)
13801 goto done;
13803 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
13804 if (error)
13805 goto done;
13807 if (commit_id_str == NULL)
13808 commit_id_str = GOT_REF_HEAD;
13809 error = got_repo_match_object_id(&commit_id, NULL,
13810 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
13811 if (error)
13812 goto done;
13814 error = got_object_open_as_commit(&commit, repo, commit_id);
13815 if (error)
13816 goto done;
13818 for (i = 0; i < argc; i++) {
13819 if (force_path) {
13820 error = got_object_id_by_path(&id, repo, commit,
13821 argv[i]);
13822 if (error)
13823 break;
13824 } else {
13825 error = got_repo_match_object_id(&id, &label, argv[i],
13826 GOT_OBJ_TYPE_ANY, NULL /* do not resolve tags */,
13827 repo);
13828 if (error) {
13829 if (error->code != GOT_ERR_BAD_OBJ_ID_STR &&
13830 error->code != GOT_ERR_NOT_REF)
13831 break;
13832 error = got_object_id_by_path(&id, repo,
13833 commit, argv[i]);
13834 if (error)
13835 break;
13839 error = got_object_get_type(&obj_type, repo, id);
13840 if (error)
13841 break;
13843 switch (obj_type) {
13844 case GOT_OBJ_TYPE_BLOB:
13845 error = cat_blob(id, repo, stdout);
13846 break;
13847 case GOT_OBJ_TYPE_TREE:
13848 error = cat_tree(id, repo, stdout);
13849 break;
13850 case GOT_OBJ_TYPE_COMMIT:
13851 error = cat_commit(id, repo, stdout);
13852 break;
13853 case GOT_OBJ_TYPE_TAG:
13854 error = cat_tag(id, repo, stdout);
13855 break;
13856 default:
13857 error = got_error(GOT_ERR_OBJ_TYPE);
13858 break;
13860 if (error)
13861 break;
13862 free(label);
13863 label = NULL;
13864 free(id);
13865 id = NULL;
13867 done:
13868 free(label);
13869 free(id);
13870 free(commit_id);
13871 if (commit)
13872 got_object_commit_close(commit);
13873 if (worktree)
13874 got_worktree_close(worktree);
13875 if (repo) {
13876 const struct got_error *close_err = got_repo_close(repo);
13877 if (error == NULL)
13878 error = close_err;
13880 if (pack_fds) {
13881 const struct got_error *pack_err =
13882 got_repo_pack_fds_close(pack_fds);
13883 if (error == NULL)
13884 error = pack_err;
13887 got_ref_list_free(&refs);
13888 return error;
13891 __dead static void
13892 usage_info(void)
13894 fprintf(stderr, "usage: %s info [path ...]\n",
13895 getprogname());
13896 exit(1);
13899 static const struct got_error *
13900 print_path_info(void *arg, const char *path, mode_t mode, time_t mtime,
13901 struct got_object_id *blob_id, struct got_object_id *staged_blob_id,
13902 struct got_object_id *commit_id)
13904 const struct got_error *err = NULL;
13905 char *id_str = NULL;
13906 char datebuf[128];
13907 struct tm mytm, *tm;
13908 struct got_pathlist_head *paths = arg;
13909 struct got_pathlist_entry *pe;
13912 * Clear error indication from any of the path arguments which
13913 * would cause this file index entry to be displayed.
13915 TAILQ_FOREACH(pe, paths, entry) {
13916 if (got_path_cmp(path, pe->path, strlen(path),
13917 pe->path_len) == 0 ||
13918 got_path_is_child(path, pe->path, pe->path_len))
13919 pe->data = NULL; /* no error */
13922 printf(GOT_COMMIT_SEP_STR);
13923 if (S_ISLNK(mode))
13924 printf("symlink: %s\n", path);
13925 else if (S_ISREG(mode)) {
13926 printf("file: %s\n", path);
13927 printf("mode: %o\n", mode & (S_IRWXU | S_IRWXG | S_IRWXO));
13928 } else if (S_ISDIR(mode))
13929 printf("directory: %s\n", path);
13930 else
13931 printf("something: %s\n", path);
13933 tm = localtime_r(&mtime, &mytm);
13934 if (tm == NULL)
13935 return NULL;
13936 if (strftime(datebuf, sizeof(datebuf), "%c %Z", tm) == 0)
13937 return got_error(GOT_ERR_NO_SPACE);
13938 printf("timestamp: %s\n", datebuf);
13940 if (blob_id) {
13941 err = got_object_id_str(&id_str, blob_id);
13942 if (err)
13943 return err;
13944 printf("based on blob: %s\n", id_str);
13945 free(id_str);
13948 if (staged_blob_id) {
13949 err = got_object_id_str(&id_str, staged_blob_id);
13950 if (err)
13951 return err;
13952 printf("based on staged blob: %s\n", id_str);
13953 free(id_str);
13956 if (commit_id) {
13957 err = got_object_id_str(&id_str, commit_id);
13958 if (err)
13959 return err;
13960 printf("based on commit: %s\n", id_str);
13961 free(id_str);
13964 return NULL;
13967 static const struct got_error *
13968 cmd_info(int argc, char *argv[])
13970 const struct got_error *error = NULL;
13971 struct got_worktree *worktree = NULL;
13972 char *cwd = NULL, *id_str = NULL;
13973 struct got_pathlist_head paths;
13974 char *uuidstr = NULL;
13975 int ch, show_files = 0;
13977 TAILQ_INIT(&paths);
13979 while ((ch = getopt(argc, argv, "")) != -1) {
13980 switch (ch) {
13981 default:
13982 usage_info();
13983 /* NOTREACHED */
13987 argc -= optind;
13988 argv += optind;
13990 #ifndef PROFILE
13991 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
13992 NULL) == -1)
13993 err(1, "pledge");
13994 #endif
13995 cwd = getcwd(NULL, 0);
13996 if (cwd == NULL) {
13997 error = got_error_from_errno("getcwd");
13998 goto done;
14001 error = got_worktree_open(&worktree, cwd);
14002 if (error) {
14003 if (error->code == GOT_ERR_NOT_WORKTREE)
14004 error = wrap_not_worktree_error(error, "info", cwd);
14005 goto done;
14008 #ifndef PROFILE
14009 /* Remove "wpath cpath proc exec sendfd" promises. */
14010 if (pledge("stdio rpath flock unveil", NULL) == -1)
14011 err(1, "pledge");
14012 #endif
14013 error = apply_unveil(NULL, 0, got_worktree_get_root_path(worktree));
14014 if (error)
14015 goto done;
14017 if (argc >= 1) {
14018 error = get_worktree_paths_from_argv(&paths, argc, argv,
14019 worktree);
14020 if (error)
14021 goto done;
14022 show_files = 1;
14025 error = got_object_id_str(&id_str,
14026 got_worktree_get_base_commit_id(worktree));
14027 if (error)
14028 goto done;
14030 error = got_worktree_get_uuid(&uuidstr, worktree);
14031 if (error)
14032 goto done;
14034 printf("work tree: %s\n", got_worktree_get_root_path(worktree));
14035 printf("work tree base commit: %s\n", id_str);
14036 printf("work tree path prefix: %s\n",
14037 got_worktree_get_path_prefix(worktree));
14038 printf("work tree branch reference: %s\n",
14039 got_worktree_get_head_ref_name(worktree));
14040 printf("work tree UUID: %s\n", uuidstr);
14041 printf("repository: %s\n", got_worktree_get_repo_path(worktree));
14043 if (show_files) {
14044 struct got_pathlist_entry *pe;
14045 TAILQ_FOREACH(pe, &paths, entry) {
14046 if (pe->path_len == 0)
14047 continue;
14049 * Assume this path will fail. This will be corrected
14050 * in print_path_info() in case the path does suceeed.
14052 pe->data = (void *)got_error(GOT_ERR_BAD_PATH);
14054 error = got_worktree_path_info(worktree, &paths,
14055 print_path_info, &paths, check_cancelled, NULL);
14056 if (error)
14057 goto done;
14058 TAILQ_FOREACH(pe, &paths, entry) {
14059 if (pe->data != NULL) {
14060 const struct got_error *perr;
14062 perr = pe->data;
14063 error = got_error_fmt(perr->code, "%s",
14064 pe->path);
14065 break;
14069 done:
14070 if (worktree)
14071 got_worktree_close(worktree);
14072 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
14073 free(cwd);
14074 free(id_str);
14075 free(uuidstr);
14076 return error;