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,
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;
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 break;
2317 case 'd':
2318 delete_refs = 1;
2319 break;
2320 case 'l':
2321 list_refs_only = 1;
2322 break;
2323 case 'q':
2324 verbosity = -1;
2325 break;
2326 case 'R':
2327 error = got_pathlist_append(&wanted_refs,
2328 optarg, NULL);
2329 if (error)
2330 return error;
2331 break;
2332 case 'r':
2333 repo_path = realpath(optarg, NULL);
2334 if (repo_path == NULL)
2335 return got_error_from_errno2("realpath",
2336 optarg);
2337 got_path_strip_trailing_slashes(repo_path);
2338 break;
2339 case 't':
2340 replace_tags = 1;
2341 break;
2342 case 'v':
2343 if (verbosity < 0)
2344 verbosity = 0;
2345 else if (verbosity < 3)
2346 verbosity++;
2347 break;
2348 case 'X':
2349 delete_remote = 1;
2350 break;
2351 default:
2352 usage_fetch();
2353 break;
2356 argc -= optind;
2357 argv += optind;
2359 if (fetch_all_branches && !TAILQ_EMPTY(&wanted_branches))
2360 option_conflict('a', 'b');
2361 if (list_refs_only) {
2362 if (!TAILQ_EMPTY(&wanted_branches))
2363 option_conflict('l', 'b');
2364 if (fetch_all_branches)
2365 option_conflict('l', 'a');
2366 if (delete_refs)
2367 option_conflict('l', 'd');
2368 if (delete_remote)
2369 option_conflict('l', 'X');
2371 if (delete_remote) {
2372 if (fetch_all_branches)
2373 option_conflict('X', 'a');
2374 if (!TAILQ_EMPTY(&wanted_branches))
2375 option_conflict('X', 'b');
2376 if (delete_refs)
2377 option_conflict('X', 'd');
2378 if (replace_tags)
2379 option_conflict('X', 't');
2380 if (!TAILQ_EMPTY(&wanted_refs))
2381 option_conflict('X', 'R');
2384 if (argc == 0) {
2385 if (delete_remote)
2386 errx(1, "-X option requires a remote name");
2387 remote_name = GOT_FETCH_DEFAULT_REMOTE_NAME;
2388 } else if (argc == 1)
2389 remote_name = argv[0];
2390 else
2391 usage_fetch();
2393 cwd = getcwd(NULL, 0);
2394 if (cwd == NULL) {
2395 error = got_error_from_errno("getcwd");
2396 goto done;
2399 error = got_repo_pack_fds_open(&pack_fds);
2400 if (error != NULL)
2401 goto done;
2403 if (repo_path == NULL) {
2404 error = got_worktree_open(&worktree, cwd);
2405 if (error && error->code != GOT_ERR_NOT_WORKTREE)
2406 goto done;
2407 else
2408 error = NULL;
2409 if (worktree) {
2410 repo_path =
2411 strdup(got_worktree_get_repo_path(worktree));
2412 if (repo_path == NULL)
2413 error = got_error_from_errno("strdup");
2414 if (error)
2415 goto done;
2416 } else {
2417 repo_path = strdup(cwd);
2418 if (repo_path == NULL) {
2419 error = got_error_from_errno("strdup");
2420 goto done;
2425 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
2426 if (error)
2427 goto done;
2429 if (delete_remote) {
2430 error = delete_refs_for_remote(repo, remote_name);
2431 goto done; /* nothing else to do */
2434 if (worktree) {
2435 worktree_conf = got_worktree_get_gotconfig(worktree);
2436 if (worktree_conf) {
2437 got_gotconfig_get_remotes(&nremotes, &remotes,
2438 worktree_conf);
2439 for (i = 0; i < nremotes; i++) {
2440 if (strcmp(remotes[i].name, remote_name) == 0) {
2441 remote = &remotes[i];
2442 break;
2446 if (TAILQ_EMPTY(&wanted_branches)) {
2447 error = got_pathlist_append(&wanted_branches,
2448 got_worktree_get_head_ref_name(worktree), NULL);
2449 if (error)
2450 goto done;
2453 if (remote == NULL) {
2454 repo_conf = got_repo_get_gotconfig(repo);
2455 if (repo_conf) {
2456 got_gotconfig_get_remotes(&nremotes, &remotes,
2457 repo_conf);
2458 for (i = 0; i < nremotes; i++) {
2459 if (strcmp(remotes[i].name, remote_name) == 0) {
2460 remote = &remotes[i];
2461 break;
2466 if (remote == NULL) {
2467 got_repo_get_gitconfig_remotes(&nremotes, &remotes, repo);
2468 for (i = 0; i < nremotes; i++) {
2469 if (strcmp(remotes[i].name, remote_name) == 0) {
2470 remote = &remotes[i];
2471 break;
2475 if (remote == NULL) {
2476 error = got_error_path(remote_name, GOT_ERR_NO_REMOTE);
2477 goto done;
2480 if (TAILQ_EMPTY(&wanted_branches)) {
2481 if (!fetch_all_branches)
2482 fetch_all_branches = remote->fetch_all_branches;
2483 for (i = 0; i < remote->nfetch_branches; i++) {
2484 error = got_pathlist_append(&wanted_branches,
2485 remote->fetch_branches[i], NULL);
2486 if (error)
2487 goto done;
2490 if (TAILQ_EMPTY(&wanted_refs)) {
2491 for (i = 0; i < remote->nfetch_refs; i++) {
2492 error = got_pathlist_append(&wanted_refs,
2493 remote->fetch_refs[i], NULL);
2494 if (error)
2495 goto done;
2499 error = got_dial_parse_uri(&proto, &host, &port, &server_path,
2500 &repo_name, remote->fetch_url);
2501 if (error)
2502 goto done;
2504 if (strcmp(proto, "git") == 0) {
2505 #ifndef PROFILE
2506 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
2507 "sendfd dns inet unveil", NULL) == -1)
2508 err(1, "pledge");
2509 #endif
2510 } else if (strcmp(proto, "git+ssh") == 0 ||
2511 strcmp(proto, "ssh") == 0) {
2512 #ifndef PROFILE
2513 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
2514 "sendfd unveil", NULL) == -1)
2515 err(1, "pledge");
2516 #endif
2517 } else if (strcmp(proto, "http") == 0 ||
2518 strcmp(proto, "git+http") == 0) {
2519 error = got_error_path(proto, GOT_ERR_NOT_IMPL);
2520 goto done;
2521 } else {
2522 error = got_error_path(proto, GOT_ERR_BAD_PROTO);
2523 goto done;
2526 error = got_dial_apply_unveil(proto);
2527 if (error)
2528 goto done;
2530 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
2531 if (error)
2532 goto done;
2534 if (verbosity >= 0) {
2535 printf("Connecting to \"%s\" %s://%s%s%s%s%s\n",
2536 remote->name, proto, host,
2537 port ? ":" : "", port ? port : "",
2538 *server_path == '/' ? "" : "/", server_path);
2541 error = got_fetch_connect(&fetchpid, &fetchfd, proto, host, port,
2542 server_path, verbosity);
2543 if (error)
2544 goto done;
2546 fpa.last_scaled_size[0] = '\0';
2547 fpa.last_p_indexed = -1;
2548 fpa.last_p_resolved = -1;
2549 fpa.verbosity = verbosity;
2550 fpa.repo = repo;
2551 fpa.create_configs = 0;
2552 fpa.configs_created = 0;
2553 memset(&fpa.config_info, 0, sizeof(fpa.config_info));
2554 error = got_fetch_pack(&pack_hash, &refs, &symrefs, remote->name,
2555 remote->mirror_references, fetch_all_branches, &wanted_branches,
2556 &wanted_refs, list_refs_only, verbosity, fetchfd, repo,
2557 fetch_progress, &fpa);
2558 if (error)
2559 goto done;
2561 if (list_refs_only) {
2562 error = list_remote_refs(&symrefs, &refs);
2563 goto done;
2566 if (pack_hash == NULL) {
2567 if (verbosity >= 0)
2568 printf("Already up-to-date\n");
2569 } else if (verbosity >= 0) {
2570 error = got_object_id_str(&id_str, pack_hash);
2571 if (error)
2572 goto done;
2573 printf("\nFetched %s.pack\n", id_str);
2574 free(id_str);
2575 id_str = NULL;
2578 /* Update references provided with the pack file. */
2579 TAILQ_FOREACH(pe, &refs, entry) {
2580 const char *refname = pe->path;
2581 struct got_object_id *id = pe->data;
2582 struct got_reference *ref;
2583 char *remote_refname;
2585 if (is_wanted_ref(&wanted_refs, refname) &&
2586 !remote->mirror_references) {
2587 error = update_wanted_ref(refname, id,
2588 remote->name, verbosity, repo);
2589 if (error)
2590 goto done;
2591 continue;
2594 if (remote->mirror_references ||
2595 strncmp("refs/tags/", refname, 10) == 0) {
2596 error = got_ref_open(&ref, repo, refname, 1);
2597 if (error) {
2598 if (error->code != GOT_ERR_NOT_REF)
2599 goto done;
2600 error = create_ref(refname, id, verbosity,
2601 repo);
2602 if (error)
2603 goto done;
2604 } else {
2605 error = update_ref(ref, id, replace_tags,
2606 verbosity, repo);
2607 unlock_err = got_ref_unlock(ref);
2608 if (unlock_err && error == NULL)
2609 error = unlock_err;
2610 got_ref_close(ref);
2611 if (error)
2612 goto done;
2614 } else if (strncmp("refs/heads/", refname, 11) == 0) {
2615 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
2616 remote_name, refname + 11) == -1) {
2617 error = got_error_from_errno("asprintf");
2618 goto done;
2621 error = got_ref_open(&ref, repo, remote_refname, 1);
2622 if (error) {
2623 if (error->code != GOT_ERR_NOT_REF)
2624 goto done;
2625 error = create_ref(remote_refname, id,
2626 verbosity, repo);
2627 if (error)
2628 goto done;
2629 } else {
2630 error = update_ref(ref, id, replace_tags,
2631 verbosity, repo);
2632 unlock_err = got_ref_unlock(ref);
2633 if (unlock_err && error == NULL)
2634 error = unlock_err;
2635 got_ref_close(ref);
2636 if (error)
2637 goto done;
2640 /* Also create a local branch if none exists yet. */
2641 error = got_ref_open(&ref, repo, refname, 1);
2642 if (error) {
2643 if (error->code != GOT_ERR_NOT_REF)
2644 goto done;
2645 error = create_ref(refname, id, verbosity,
2646 repo);
2647 if (error)
2648 goto done;
2649 } else {
2650 unlock_err = got_ref_unlock(ref);
2651 if (unlock_err && error == NULL)
2652 error = unlock_err;
2653 got_ref_close(ref);
2657 if (delete_refs) {
2658 error = delete_missing_refs(&refs, &symrefs, remote,
2659 verbosity, repo);
2660 if (error)
2661 goto done;
2664 if (!remote->mirror_references) {
2665 /* Update remote HEAD reference if the server provided one. */
2666 TAILQ_FOREACH(pe, &symrefs, entry) {
2667 struct got_reference *target_ref;
2668 const char *refname = pe->path;
2669 const char *target = pe->data;
2670 char *remote_refname = NULL, *remote_target = NULL;
2672 if (strcmp(refname, GOT_REF_HEAD) != 0)
2673 continue;
2675 if (strncmp("refs/heads/", target, 11) != 0)
2676 continue;
2678 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
2679 remote->name, refname) == -1) {
2680 error = got_error_from_errno("asprintf");
2681 goto done;
2683 if (asprintf(&remote_target, "refs/remotes/%s/%s",
2684 remote->name, target + 11) == -1) {
2685 error = got_error_from_errno("asprintf");
2686 free(remote_refname);
2687 goto done;
2690 error = got_ref_open(&target_ref, repo, remote_target,
2691 0);
2692 if (error) {
2693 free(remote_refname);
2694 free(remote_target);
2695 if (error->code == GOT_ERR_NOT_REF) {
2696 error = NULL;
2697 continue;
2699 goto done;
2701 error = update_symref(remote_refname, target_ref,
2702 verbosity, repo);
2703 free(remote_refname);
2704 free(remote_target);
2705 got_ref_close(target_ref);
2706 if (error)
2707 goto done;
2710 done:
2711 if (fetchpid > 0) {
2712 if (kill(fetchpid, SIGTERM) == -1)
2713 error = got_error_from_errno("kill");
2714 if (waitpid(fetchpid, &fetchstatus, 0) == -1 && error == NULL)
2715 error = got_error_from_errno("waitpid");
2717 if (fetchfd != -1 && close(fetchfd) == -1 && error == NULL)
2718 error = got_error_from_errno("close");
2719 if (repo) {
2720 const struct got_error *close_err = got_repo_close(repo);
2721 if (error == NULL)
2722 error = close_err;
2724 if (worktree)
2725 got_worktree_close(worktree);
2726 if (pack_fds) {
2727 const struct got_error *pack_err =
2728 got_repo_pack_fds_close(pack_fds);
2729 if (error == NULL)
2730 error = pack_err;
2732 got_pathlist_free(&refs, GOT_PATHLIST_FREE_ALL);
2733 got_pathlist_free(&symrefs, GOT_PATHLIST_FREE_ALL);
2734 got_pathlist_free(&wanted_branches, GOT_PATHLIST_FREE_NONE);
2735 got_pathlist_free(&wanted_refs, GOT_PATHLIST_FREE_NONE);
2736 free(id_str);
2737 free(cwd);
2738 free(repo_path);
2739 free(pack_hash);
2740 free(proto);
2741 free(host);
2742 free(port);
2743 free(server_path);
2744 free(repo_name);
2745 return error;
2749 __dead static void
2750 usage_checkout(void)
2752 fprintf(stderr, "usage: %s checkout [-Eq] [-b branch] [-c commit] "
2753 "[-p path-prefix] repository-path [work-tree-path]\n",
2754 getprogname());
2755 exit(1);
2758 static void
2759 show_worktree_base_ref_warning(void)
2761 fprintf(stderr, "%s: warning: could not create a reference "
2762 "to the work tree's base commit; the commit could be "
2763 "garbage-collected by Git or 'gotadmin cleanup'; making the "
2764 "repository writable and running 'got update' will prevent this\n",
2765 getprogname());
2768 struct got_checkout_progress_arg {
2769 const char *worktree_path;
2770 int had_base_commit_ref_error;
2771 int verbosity;
2774 static const struct got_error *
2775 checkout_progress(void *arg, unsigned char status, const char *path)
2777 struct got_checkout_progress_arg *a = arg;
2779 /* Base commit bump happens silently. */
2780 if (status == GOT_STATUS_BUMP_BASE)
2781 return NULL;
2783 if (status == GOT_STATUS_BASE_REF_ERR) {
2784 a->had_base_commit_ref_error = 1;
2785 return NULL;
2788 while (path[0] == '/')
2789 path++;
2791 if (a->verbosity >= 0)
2792 printf("%c %s/%s\n", status, a->worktree_path, path);
2794 return NULL;
2797 static const struct got_error *
2798 check_cancelled(void *arg)
2800 if (sigint_received || sigpipe_received)
2801 return got_error(GOT_ERR_CANCELLED);
2802 return NULL;
2805 static const struct got_error *
2806 check_linear_ancestry(struct got_object_id *commit_id,
2807 struct got_object_id *base_commit_id, int allow_forwards_in_time_only,
2808 struct got_repository *repo)
2810 const struct got_error *err = NULL;
2811 struct got_object_id *yca_id;
2813 err = got_commit_graph_find_youngest_common_ancestor(&yca_id,
2814 commit_id, base_commit_id, 1, repo, check_cancelled, NULL);
2815 if (err)
2816 return err;
2818 if (yca_id == NULL)
2819 return got_error(GOT_ERR_ANCESTRY);
2822 * Require a straight line of history between the target commit
2823 * and the work tree's base commit.
2825 * Non-linear situations such as this require a rebase:
2827 * (commit) D F (base_commit)
2828 * \ /
2829 * C E
2830 * \ /
2831 * B (yca)
2832 * |
2833 * A
2835 * 'got update' only handles linear cases:
2836 * Update forwards in time: A (base/yca) - B - C - D (commit)
2837 * Update backwards in time: D (base) - C - B - A (commit/yca)
2839 if (allow_forwards_in_time_only) {
2840 if (got_object_id_cmp(base_commit_id, yca_id) != 0)
2841 return got_error(GOT_ERR_ANCESTRY);
2842 } else if (got_object_id_cmp(commit_id, yca_id) != 0 &&
2843 got_object_id_cmp(base_commit_id, yca_id) != 0)
2844 return got_error(GOT_ERR_ANCESTRY);
2846 free(yca_id);
2847 return NULL;
2850 static const struct got_error *
2851 check_same_branch(struct got_object_id *commit_id,
2852 struct got_reference *head_ref, struct got_object_id *yca_id,
2853 struct got_repository *repo)
2855 const struct got_error *err = NULL;
2856 struct got_commit_graph *graph = NULL;
2857 struct got_object_id *head_commit_id = NULL;
2858 int is_same_branch = 0;
2860 err = got_ref_resolve(&head_commit_id, repo, head_ref);
2861 if (err)
2862 goto done;
2864 if (got_object_id_cmp(head_commit_id, commit_id) == 0) {
2865 is_same_branch = 1;
2866 goto done;
2868 if (yca_id && got_object_id_cmp(commit_id, yca_id) == 0) {
2869 is_same_branch = 1;
2870 goto done;
2873 err = got_commit_graph_open(&graph, "/", 1);
2874 if (err)
2875 goto done;
2877 err = got_commit_graph_iter_start(graph, head_commit_id, repo,
2878 check_cancelled, NULL);
2879 if (err)
2880 goto done;
2882 for (;;) {
2883 struct got_object_id id;
2885 err = got_commit_graph_iter_next(&id, graph, repo,
2886 check_cancelled, NULL);
2887 if (err) {
2888 if (err->code == GOT_ERR_ITER_COMPLETED)
2889 err = NULL;
2890 break;
2893 if (yca_id && got_object_id_cmp(&id, yca_id) == 0)
2894 break;
2895 if (got_object_id_cmp(&id, commit_id) == 0) {
2896 is_same_branch = 1;
2897 break;
2900 done:
2901 if (graph)
2902 got_commit_graph_close(graph);
2903 free(head_commit_id);
2904 if (!err && !is_same_branch)
2905 err = got_error(GOT_ERR_ANCESTRY);
2906 return err;
2909 static const struct got_error *
2910 checkout_ancestry_error(struct got_reference *ref, const char *commit_id_str)
2912 static char msg[512];
2913 const char *branch_name;
2915 if (got_ref_is_symbolic(ref))
2916 branch_name = got_ref_get_symref_target(ref);
2917 else
2918 branch_name = got_ref_get_name(ref);
2920 if (strncmp("refs/heads/", branch_name, 11) == 0)
2921 branch_name += 11;
2923 snprintf(msg, sizeof(msg),
2924 "target commit is not contained in branch '%s'; "
2925 "the branch to use must be specified with -b; "
2926 "if necessary a new branch can be created for "
2927 "this commit with 'got branch -c %s BRANCH_NAME'",
2928 branch_name, commit_id_str);
2930 return got_error_msg(GOT_ERR_ANCESTRY, msg);
2933 static const struct got_error *
2934 cmd_checkout(int argc, char *argv[])
2936 const struct got_error *error = NULL;
2937 struct got_repository *repo = NULL;
2938 struct got_reference *head_ref = NULL, *ref = NULL;
2939 struct got_worktree *worktree = NULL;
2940 char *repo_path = NULL;
2941 char *worktree_path = NULL;
2942 const char *path_prefix = "";
2943 const char *branch_name = GOT_REF_HEAD, *refname = NULL;
2944 char *commit_id_str = NULL;
2945 struct got_object_id *commit_id = NULL;
2946 char *cwd = NULL;
2947 int ch, same_path_prefix, allow_nonempty = 0, verbosity = 0;
2948 struct got_pathlist_head paths;
2949 struct got_checkout_progress_arg cpa;
2950 int *pack_fds = NULL;
2952 TAILQ_INIT(&paths);
2954 while ((ch = getopt(argc, argv, "b:c:Ep:q")) != -1) {
2955 switch (ch) {
2956 case 'b':
2957 branch_name = optarg;
2958 break;
2959 case 'c':
2960 commit_id_str = strdup(optarg);
2961 if (commit_id_str == NULL)
2962 return got_error_from_errno("strdup");
2963 break;
2964 case 'E':
2965 allow_nonempty = 1;
2966 break;
2967 case 'p':
2968 path_prefix = optarg;
2969 break;
2970 case 'q':
2971 verbosity = -1;
2972 break;
2973 default:
2974 usage_checkout();
2975 /* NOTREACHED */
2979 argc -= optind;
2980 argv += optind;
2982 #ifndef PROFILE
2983 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
2984 "unveil", NULL) == -1)
2985 err(1, "pledge");
2986 #endif
2987 if (argc == 1) {
2988 char *base, *dotgit;
2989 const char *path;
2990 repo_path = realpath(argv[0], NULL);
2991 if (repo_path == NULL)
2992 return got_error_from_errno2("realpath", argv[0]);
2993 cwd = getcwd(NULL, 0);
2994 if (cwd == NULL) {
2995 error = got_error_from_errno("getcwd");
2996 goto done;
2998 if (path_prefix[0])
2999 path = path_prefix;
3000 else
3001 path = repo_path;
3002 error = got_path_basename(&base, path);
3003 if (error)
3004 goto done;
3005 dotgit = strstr(base, ".git");
3006 if (dotgit)
3007 *dotgit = '\0';
3008 if (asprintf(&worktree_path, "%s/%s", cwd, base) == -1) {
3009 error = got_error_from_errno("asprintf");
3010 free(base);
3011 goto done;
3013 free(base);
3014 } else if (argc == 2) {
3015 repo_path = realpath(argv[0], NULL);
3016 if (repo_path == NULL) {
3017 error = got_error_from_errno2("realpath", argv[0]);
3018 goto done;
3020 worktree_path = realpath(argv[1], NULL);
3021 if (worktree_path == NULL) {
3022 if (errno != ENOENT) {
3023 error = got_error_from_errno2("realpath",
3024 argv[1]);
3025 goto done;
3027 worktree_path = strdup(argv[1]);
3028 if (worktree_path == NULL) {
3029 error = got_error_from_errno("strdup");
3030 goto done;
3033 } else
3034 usage_checkout();
3036 got_path_strip_trailing_slashes(repo_path);
3037 got_path_strip_trailing_slashes(worktree_path);
3039 error = got_repo_pack_fds_open(&pack_fds);
3040 if (error != NULL)
3041 goto done;
3043 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
3044 if (error != NULL)
3045 goto done;
3047 /* Pre-create work tree path for unveil(2) */
3048 error = got_path_mkdir(worktree_path);
3049 if (error) {
3050 if (!(error->code == GOT_ERR_ERRNO && errno == EISDIR) &&
3051 !(error->code == GOT_ERR_ERRNO && errno == EEXIST))
3052 goto done;
3053 if (!allow_nonempty &&
3054 !got_path_dir_is_empty(worktree_path)) {
3055 error = got_error_path(worktree_path,
3056 GOT_ERR_DIR_NOT_EMPTY);
3057 goto done;
3061 error = apply_unveil(got_repo_get_path(repo), 0, worktree_path);
3062 if (error)
3063 goto done;
3065 error = got_ref_open(&head_ref, repo, branch_name, 0);
3066 if (error != NULL)
3067 goto done;
3069 error = got_worktree_init(worktree_path, head_ref, path_prefix, repo);
3070 if (error != NULL && !(error->code == GOT_ERR_ERRNO && errno == EEXIST))
3071 goto done;
3073 error = got_worktree_open(&worktree, worktree_path);
3074 if (error != NULL)
3075 goto done;
3077 error = got_worktree_match_path_prefix(&same_path_prefix, worktree,
3078 path_prefix);
3079 if (error != NULL)
3080 goto done;
3081 if (!same_path_prefix) {
3082 error = got_error(GOT_ERR_PATH_PREFIX);
3083 goto done;
3086 if (commit_id_str) {
3087 struct got_reflist_head refs;
3088 TAILQ_INIT(&refs);
3089 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
3090 NULL);
3091 if (error)
3092 goto done;
3093 error = got_repo_match_object_id(&commit_id, NULL,
3094 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
3095 got_ref_list_free(&refs);
3096 if (error)
3097 goto done;
3098 error = check_linear_ancestry(commit_id,
3099 got_worktree_get_base_commit_id(worktree), 0, repo);
3100 if (error != NULL) {
3101 if (error->code == GOT_ERR_ANCESTRY) {
3102 error = checkout_ancestry_error(
3103 head_ref, commit_id_str);
3105 goto done;
3107 error = check_same_branch(commit_id, head_ref, NULL, repo);
3108 if (error) {
3109 if (error->code == GOT_ERR_ANCESTRY) {
3110 error = checkout_ancestry_error(
3111 head_ref, commit_id_str);
3113 goto done;
3115 error = got_worktree_set_base_commit_id(worktree, repo,
3116 commit_id);
3117 if (error)
3118 goto done;
3119 /* Expand potentially abbreviated commit ID string. */
3120 free(commit_id_str);
3121 error = got_object_id_str(&commit_id_str, commit_id);
3122 if (error)
3123 goto done;
3124 } else {
3125 commit_id = got_object_id_dup(
3126 got_worktree_get_base_commit_id(worktree));
3127 if (commit_id == NULL) {
3128 error = got_error_from_errno("got_object_id_dup");
3129 goto done;
3131 error = got_object_id_str(&commit_id_str, commit_id);
3132 if (error)
3133 goto done;
3136 error = got_pathlist_append(&paths, "", NULL);
3137 if (error)
3138 goto done;
3139 cpa.worktree_path = worktree_path;
3140 cpa.had_base_commit_ref_error = 0;
3141 cpa.verbosity = verbosity;
3142 error = got_worktree_checkout_files(worktree, &paths, repo,
3143 checkout_progress, &cpa, check_cancelled, NULL);
3144 if (error != NULL)
3145 goto done;
3147 if (got_ref_is_symbolic(head_ref)) {
3148 error = got_ref_resolve_symbolic(&ref, repo, head_ref);
3149 if (error)
3150 goto done;
3151 refname = got_ref_get_name(ref);
3152 } else
3153 refname = got_ref_get_name(head_ref);
3154 printf("Checked out %s: %s\n", refname, commit_id_str);
3155 printf("Now shut up and hack\n");
3156 if (cpa.had_base_commit_ref_error)
3157 show_worktree_base_ref_warning();
3158 done:
3159 if (pack_fds) {
3160 const struct got_error *pack_err =
3161 got_repo_pack_fds_close(pack_fds);
3162 if (error == NULL)
3163 error = pack_err;
3165 if (head_ref)
3166 got_ref_close(head_ref);
3167 if (ref)
3168 got_ref_close(ref);
3169 got_pathlist_free(&paths, GOT_PATHLIST_FREE_NONE);
3170 free(commit_id_str);
3171 free(commit_id);
3172 free(repo_path);
3173 free(worktree_path);
3174 free(cwd);
3175 return error;
3178 struct got_update_progress_arg {
3179 int did_something;
3180 int conflicts;
3181 int obstructed;
3182 int not_updated;
3183 int missing;
3184 int not_deleted;
3185 int unversioned;
3186 int verbosity;
3189 static void
3190 print_update_progress_stats(struct got_update_progress_arg *upa)
3192 if (!upa->did_something)
3193 return;
3195 if (upa->conflicts > 0)
3196 printf("Files with new merge conflicts: %d\n", upa->conflicts);
3197 if (upa->obstructed > 0)
3198 printf("File paths obstructed by a non-regular file: %d\n",
3199 upa->obstructed);
3200 if (upa->not_updated > 0)
3201 printf("Files not updated because of existing merge "
3202 "conflicts: %d\n", upa->not_updated);
3206 * The meaning of some status codes differs between merge-style operations and
3207 * update operations. For example, the ! status code means "file was missing"
3208 * if changes were merged into the work tree, and "missing file was restored"
3209 * if the work tree was updated. This function should be used by any operation
3210 * which merges changes into the work tree without updating the work tree.
3212 static void
3213 print_merge_progress_stats(struct got_update_progress_arg *upa)
3215 if (!upa->did_something)
3216 return;
3218 if (upa->conflicts > 0)
3219 printf("Files with new merge conflicts: %d\n", upa->conflicts);
3220 if (upa->obstructed > 0)
3221 printf("File paths obstructed by a non-regular file: %d\n",
3222 upa->obstructed);
3223 if (upa->missing > 0)
3224 printf("Files which had incoming changes but could not be "
3225 "found in the work tree: %d\n", upa->missing);
3226 if (upa->not_deleted > 0)
3227 printf("Files not deleted due to differences in deleted "
3228 "content: %d\n", upa->not_deleted);
3229 if (upa->unversioned > 0)
3230 printf("Files not merged because an unversioned file was "
3231 "found in the work tree: %d\n", upa->unversioned);
3234 __dead static void
3235 usage_update(void)
3237 fprintf(stderr, "usage: %s update [-q] [-b branch] [-c commit] "
3238 "[path ...]\n", getprogname());
3239 exit(1);
3242 static const struct got_error *
3243 update_progress(void *arg, unsigned char status, const char *path)
3245 struct got_update_progress_arg *upa = arg;
3247 if (status == GOT_STATUS_EXISTS ||
3248 status == GOT_STATUS_BASE_REF_ERR)
3249 return NULL;
3251 upa->did_something = 1;
3253 /* Base commit bump happens silently. */
3254 if (status == GOT_STATUS_BUMP_BASE)
3255 return NULL;
3257 if (status == GOT_STATUS_CONFLICT)
3258 upa->conflicts++;
3259 if (status == GOT_STATUS_OBSTRUCTED)
3260 upa->obstructed++;
3261 if (status == GOT_STATUS_CANNOT_UPDATE)
3262 upa->not_updated++;
3263 if (status == GOT_STATUS_MISSING)
3264 upa->missing++;
3265 if (status == GOT_STATUS_CANNOT_DELETE)
3266 upa->not_deleted++;
3267 if (status == GOT_STATUS_UNVERSIONED)
3268 upa->unversioned++;
3270 while (path[0] == '/')
3271 path++;
3272 if (upa->verbosity >= 0)
3273 printf("%c %s\n", status, path);
3275 return NULL;
3278 static const struct got_error *
3279 switch_head_ref(struct got_reference *head_ref,
3280 struct got_object_id *commit_id, struct got_worktree *worktree,
3281 struct got_repository *repo)
3283 const struct got_error *err = NULL;
3284 char *base_id_str;
3285 int ref_has_moved = 0;
3287 /* Trivial case: switching between two different references. */
3288 if (strcmp(got_ref_get_name(head_ref),
3289 got_worktree_get_head_ref_name(worktree)) != 0) {
3290 printf("Switching work tree from %s to %s\n",
3291 got_worktree_get_head_ref_name(worktree),
3292 got_ref_get_name(head_ref));
3293 return got_worktree_set_head_ref(worktree, head_ref);
3296 err = check_linear_ancestry(commit_id,
3297 got_worktree_get_base_commit_id(worktree), 0, repo);
3298 if (err) {
3299 if (err->code != GOT_ERR_ANCESTRY)
3300 return err;
3301 ref_has_moved = 1;
3303 if (!ref_has_moved)
3304 return NULL;
3306 /* Switching to a rebased branch with the same reference name. */
3307 err = got_object_id_str(&base_id_str,
3308 got_worktree_get_base_commit_id(worktree));
3309 if (err)
3310 return err;
3311 printf("Reference %s now points at a different branch\n",
3312 got_worktree_get_head_ref_name(worktree));
3313 printf("Switching work tree from %s to %s\n", base_id_str,
3314 got_worktree_get_head_ref_name(worktree));
3315 return NULL;
3318 static const struct got_error *
3319 check_rebase_or_histedit_in_progress(struct got_worktree *worktree)
3321 const struct got_error *err;
3322 int in_progress;
3324 err = got_worktree_rebase_in_progress(&in_progress, worktree);
3325 if (err)
3326 return err;
3327 if (in_progress)
3328 return got_error(GOT_ERR_REBASING);
3330 err = got_worktree_histedit_in_progress(&in_progress, worktree);
3331 if (err)
3332 return err;
3333 if (in_progress)
3334 return got_error(GOT_ERR_HISTEDIT_BUSY);
3336 return NULL;
3339 static const struct got_error *
3340 check_merge_in_progress(struct got_worktree *worktree,
3341 struct got_repository *repo)
3343 const struct got_error *err;
3344 int in_progress;
3346 err = got_worktree_merge_in_progress(&in_progress, worktree, repo);
3347 if (err)
3348 return err;
3349 if (in_progress)
3350 return got_error(GOT_ERR_MERGE_BUSY);
3352 return NULL;
3355 static const struct got_error *
3356 get_worktree_paths_from_argv(struct got_pathlist_head *paths, int argc,
3357 char *argv[], struct got_worktree *worktree)
3359 const struct got_error *err = NULL;
3360 char *path;
3361 struct got_pathlist_entry *new;
3362 int i;
3364 if (argc == 0) {
3365 path = strdup("");
3366 if (path == NULL)
3367 return got_error_from_errno("strdup");
3368 return got_pathlist_append(paths, path, NULL);
3371 for (i = 0; i < argc; i++) {
3372 err = got_worktree_resolve_path(&path, worktree, argv[i]);
3373 if (err)
3374 break;
3375 err = got_pathlist_insert(&new, paths, path, NULL);
3376 if (err || new == NULL /* duplicate */) {
3377 free(path);
3378 if (err)
3379 break;
3383 return err;
3386 static const struct got_error *
3387 wrap_not_worktree_error(const struct got_error *orig_err,
3388 const char *cmdname, const char *path)
3390 const struct got_error *err;
3391 struct got_repository *repo;
3392 static char msg[512];
3393 int *pack_fds = NULL;
3395 err = got_repo_pack_fds_open(&pack_fds);
3396 if (err)
3397 return err;
3399 err = got_repo_open(&repo, path, NULL, pack_fds);
3400 if (err)
3401 return orig_err;
3403 snprintf(msg, sizeof(msg),
3404 "'got %s' needs a work tree in addition to a git repository\n"
3405 "Work trees can be checked out from this Git repository with "
3406 "'got checkout'.\n"
3407 "The got(1) manual page contains more information.", cmdname);
3408 err = got_error_msg(GOT_ERR_NOT_WORKTREE, msg);
3409 got_repo_close(repo);
3410 if (pack_fds) {
3411 const struct got_error *pack_err =
3412 got_repo_pack_fds_close(pack_fds);
3413 if (err == NULL)
3414 err = pack_err;
3416 return err;
3419 static const struct got_error *
3420 cmd_update(int argc, char *argv[])
3422 const struct got_error *error = NULL;
3423 struct got_repository *repo = NULL;
3424 struct got_worktree *worktree = NULL;
3425 char *worktree_path = NULL;
3426 struct got_object_id *commit_id = NULL;
3427 char *commit_id_str = NULL;
3428 const char *branch_name = NULL;
3429 struct got_reference *head_ref = NULL;
3430 struct got_pathlist_head paths;
3431 struct got_pathlist_entry *pe;
3432 int ch, verbosity = 0;
3433 struct got_update_progress_arg upa;
3434 int *pack_fds = NULL;
3436 TAILQ_INIT(&paths);
3438 while ((ch = getopt(argc, argv, "b:c:q")) != -1) {
3439 switch (ch) {
3440 case 'b':
3441 branch_name = optarg;
3442 break;
3443 case 'c':
3444 commit_id_str = strdup(optarg);
3445 if (commit_id_str == NULL)
3446 return got_error_from_errno("strdup");
3447 break;
3448 case 'q':
3449 verbosity = -1;
3450 break;
3451 default:
3452 usage_update();
3453 /* NOTREACHED */
3457 argc -= optind;
3458 argv += optind;
3460 #ifndef PROFILE
3461 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
3462 "unveil", NULL) == -1)
3463 err(1, "pledge");
3464 #endif
3465 worktree_path = getcwd(NULL, 0);
3466 if (worktree_path == NULL) {
3467 error = got_error_from_errno("getcwd");
3468 goto done;
3471 error = got_repo_pack_fds_open(&pack_fds);
3472 if (error != NULL)
3473 goto done;
3475 error = got_worktree_open(&worktree, worktree_path);
3476 if (error) {
3477 if (error->code == GOT_ERR_NOT_WORKTREE)
3478 error = wrap_not_worktree_error(error, "update",
3479 worktree_path);
3480 goto done;
3483 error = check_rebase_or_histedit_in_progress(worktree);
3484 if (error)
3485 goto done;
3487 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
3488 NULL, pack_fds);
3489 if (error != NULL)
3490 goto done;
3492 error = apply_unveil(got_repo_get_path(repo), 0,
3493 got_worktree_get_root_path(worktree));
3494 if (error)
3495 goto done;
3497 error = check_merge_in_progress(worktree, repo);
3498 if (error)
3499 goto done;
3501 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
3502 if (error)
3503 goto done;
3505 error = got_ref_open(&head_ref, repo, branch_name ? branch_name :
3506 got_worktree_get_head_ref_name(worktree), 0);
3507 if (error != NULL)
3508 goto done;
3509 if (commit_id_str == NULL) {
3510 error = got_ref_resolve(&commit_id, repo, head_ref);
3511 if (error != NULL)
3512 goto done;
3513 error = got_object_id_str(&commit_id_str, commit_id);
3514 if (error != NULL)
3515 goto done;
3516 } else {
3517 struct got_reflist_head refs;
3518 TAILQ_INIT(&refs);
3519 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
3520 NULL);
3521 if (error)
3522 goto done;
3523 error = got_repo_match_object_id(&commit_id, NULL,
3524 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
3525 got_ref_list_free(&refs);
3526 free(commit_id_str);
3527 commit_id_str = NULL;
3528 if (error)
3529 goto done;
3530 error = got_object_id_str(&commit_id_str, commit_id);
3531 if (error)
3532 goto done;
3535 if (branch_name) {
3536 struct got_object_id *head_commit_id;
3537 TAILQ_FOREACH(pe, &paths, entry) {
3538 if (pe->path_len == 0)
3539 continue;
3540 error = got_error_msg(GOT_ERR_BAD_PATH,
3541 "switching between branches requires that "
3542 "the entire work tree gets updated");
3543 goto done;
3545 error = got_ref_resolve(&head_commit_id, repo, head_ref);
3546 if (error)
3547 goto done;
3548 error = check_linear_ancestry(commit_id, head_commit_id, 0,
3549 repo);
3550 free(head_commit_id);
3551 if (error != NULL)
3552 goto done;
3553 error = check_same_branch(commit_id, head_ref, NULL, repo);
3554 if (error)
3555 goto done;
3556 error = switch_head_ref(head_ref, commit_id, worktree, repo);
3557 if (error)
3558 goto done;
3559 } else {
3560 error = check_linear_ancestry(commit_id,
3561 got_worktree_get_base_commit_id(worktree), 0, repo);
3562 if (error != NULL) {
3563 if (error->code == GOT_ERR_ANCESTRY)
3564 error = got_error(GOT_ERR_BRANCH_MOVED);
3565 goto done;
3567 error = check_same_branch(commit_id, head_ref, NULL, repo);
3568 if (error)
3569 goto done;
3572 if (got_object_id_cmp(got_worktree_get_base_commit_id(worktree),
3573 commit_id) != 0) {
3574 error = got_worktree_set_base_commit_id(worktree, repo,
3575 commit_id);
3576 if (error)
3577 goto done;
3580 memset(&upa, 0, sizeof(upa));
3581 upa.verbosity = verbosity;
3582 error = got_worktree_checkout_files(worktree, &paths, repo,
3583 update_progress, &upa, check_cancelled, NULL);
3584 if (error != NULL)
3585 goto done;
3587 if (upa.did_something) {
3588 printf("Updated to %s: %s\n",
3589 got_worktree_get_head_ref_name(worktree), commit_id_str);
3590 } else
3591 printf("Already up-to-date\n");
3593 print_update_progress_stats(&upa);
3594 done:
3595 if (pack_fds) {
3596 const struct got_error *pack_err =
3597 got_repo_pack_fds_close(pack_fds);
3598 if (error == NULL)
3599 error = pack_err;
3601 free(worktree_path);
3602 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
3603 free(commit_id);
3604 free(commit_id_str);
3605 return error;
3608 static const struct got_error *
3609 diff_blobs(struct got_object_id *blob_id1, struct got_object_id *blob_id2,
3610 const char *path, int diff_context, int ignore_whitespace,
3611 int force_text_diff, struct got_diffstat_cb_arg *dsa,
3612 struct got_repository *repo, FILE *outfile)
3614 const struct got_error *err = NULL;
3615 struct got_blob_object *blob1 = NULL, *blob2 = NULL;
3616 FILE *f1 = NULL, *f2 = NULL;
3617 int fd1 = -1, fd2 = -1;
3619 fd1 = got_opentempfd();
3620 if (fd1 == -1)
3621 return got_error_from_errno("got_opentempfd");
3622 fd2 = got_opentempfd();
3623 if (fd2 == -1) {
3624 err = got_error_from_errno("got_opentempfd");
3625 goto done;
3628 if (blob_id1) {
3629 err = got_object_open_as_blob(&blob1, repo, blob_id1, 8192,
3630 fd1);
3631 if (err)
3632 goto done;
3635 err = got_object_open_as_blob(&blob2, repo, blob_id2, 8192, fd2);
3636 if (err)
3637 goto done;
3639 f1 = got_opentemp();
3640 if (f1 == NULL) {
3641 err = got_error_from_errno("got_opentemp");
3642 goto done;
3644 f2 = got_opentemp();
3645 if (f2 == NULL) {
3646 err = got_error_from_errno("got_opentemp");
3647 goto done;
3650 while (path[0] == '/')
3651 path++;
3652 err = got_diff_blob(NULL, NULL, blob1, blob2, f1, f2, path, path,
3653 GOT_DIFF_ALGORITHM_PATIENCE, diff_context, ignore_whitespace,
3654 force_text_diff, dsa, outfile);
3655 done:
3656 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
3657 err = got_error_from_errno("close");
3658 if (blob1)
3659 got_object_blob_close(blob1);
3660 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
3661 err = got_error_from_errno("close");
3662 got_object_blob_close(blob2);
3663 if (f1 && fclose(f1) == EOF && err == NULL)
3664 err = got_error_from_errno("fclose");
3665 if (f2 && fclose(f2) == EOF && err == NULL)
3666 err = got_error_from_errno("fclose");
3667 return err;
3670 static const struct got_error *
3671 diff_trees(struct got_object_id *tree_id1, struct got_object_id *tree_id2,
3672 const char *path, int diff_context, int ignore_whitespace,
3673 int force_text_diff, struct got_diffstat_cb_arg *dsa,
3674 struct got_repository *repo, FILE *outfile)
3676 const struct got_error *err = NULL;
3677 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
3678 struct got_diff_blob_output_unidiff_arg arg;
3679 FILE *f1 = NULL, *f2 = NULL;
3680 int fd1 = -1, fd2 = -1;
3682 if (tree_id1) {
3683 err = got_object_open_as_tree(&tree1, repo, tree_id1);
3684 if (err)
3685 goto done;
3686 fd1 = got_opentempfd();
3687 if (fd1 == -1) {
3688 err = got_error_from_errno("got_opentempfd");
3689 goto done;
3693 err = got_object_open_as_tree(&tree2, repo, tree_id2);
3694 if (err)
3695 goto done;
3697 f1 = got_opentemp();
3698 if (f1 == NULL) {
3699 err = got_error_from_errno("got_opentemp");
3700 goto done;
3703 f2 = got_opentemp();
3704 if (f2 == NULL) {
3705 err = got_error_from_errno("got_opentemp");
3706 goto done;
3708 fd2 = got_opentempfd();
3709 if (fd2 == -1) {
3710 err = got_error_from_errno("got_opentempfd");
3711 goto done;
3713 arg.diff_context = diff_context;
3714 arg.ignore_whitespace = ignore_whitespace;
3715 arg.force_text_diff = force_text_diff;
3716 arg.diffstat = dsa;
3717 arg.diff_algo = GOT_DIFF_ALGORITHM_PATIENCE;
3718 arg.outfile = outfile;
3719 arg.lines = NULL;
3720 arg.nlines = 0;
3721 while (path[0] == '/')
3722 path++;
3723 err = got_diff_tree(tree1, tree2, f1, f2, fd1, fd2, path, path, repo,
3724 got_diff_blob_output_unidiff, &arg, 1);
3725 done:
3726 if (tree1)
3727 got_object_tree_close(tree1);
3728 if (tree2)
3729 got_object_tree_close(tree2);
3730 if (f1 && fclose(f1) == EOF && err == NULL)
3731 err = got_error_from_errno("fclose");
3732 if (f2 && fclose(f2) == EOF && err == NULL)
3733 err = got_error_from_errno("fclose");
3734 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
3735 err = got_error_from_errno("close");
3736 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
3737 err = got_error_from_errno("close");
3738 return err;
3741 static const struct got_error *
3742 get_changed_paths(struct got_pathlist_head *paths,
3743 struct got_commit_object *commit, struct got_repository *repo,
3744 struct got_diffstat_cb_arg *dsa)
3746 const struct got_error *err = NULL;
3747 struct got_object_id *tree_id1 = NULL, *tree_id2 = NULL;
3748 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
3749 struct got_object_qid *qid;
3750 got_diff_blob_cb cb = got_diff_tree_collect_changed_paths;
3751 FILE *f1 = NULL, *f2 = NULL;
3752 int fd1 = -1, fd2 = -1;
3754 if (dsa) {
3755 cb = got_diff_tree_compute_diffstat;
3757 f1 = got_opentemp();
3758 if (f1 == NULL) {
3759 err = got_error_from_errno("got_opentemp");
3760 goto done;
3762 f2 = got_opentemp();
3763 if (f2 == NULL) {
3764 err = got_error_from_errno("got_opentemp");
3765 goto done;
3767 fd1 = got_opentempfd();
3768 if (fd1 == -1) {
3769 err = got_error_from_errno("got_opentempfd");
3770 goto done;
3772 fd2 = got_opentempfd();
3773 if (fd2 == -1) {
3774 err = got_error_from_errno("got_opentempfd");
3775 goto done;
3779 qid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
3780 if (qid != NULL) {
3781 struct got_commit_object *pcommit;
3782 err = got_object_open_as_commit(&pcommit, repo,
3783 &qid->id);
3784 if (err)
3785 return err;
3787 tree_id1 = got_object_id_dup(
3788 got_object_commit_get_tree_id(pcommit));
3789 if (tree_id1 == NULL) {
3790 got_object_commit_close(pcommit);
3791 return got_error_from_errno("got_object_id_dup");
3793 got_object_commit_close(pcommit);
3797 if (tree_id1) {
3798 err = got_object_open_as_tree(&tree1, repo, tree_id1);
3799 if (err)
3800 goto done;
3803 tree_id2 = got_object_commit_get_tree_id(commit);
3804 err = got_object_open_as_tree(&tree2, repo, tree_id2);
3805 if (err)
3806 goto done;
3808 err = got_diff_tree(tree1, tree2, f1, f2, fd1, fd2, "", "", repo,
3809 cb, dsa ? (void *)dsa : paths, dsa ? 1 : 0);
3810 done:
3811 if (tree1)
3812 got_object_tree_close(tree1);
3813 if (tree2)
3814 got_object_tree_close(tree2);
3815 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
3816 err = got_error_from_errno("close");
3817 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
3818 err = got_error_from_errno("close");
3819 if (f1 && fclose(f1) == EOF && err == NULL)
3820 err = got_error_from_errno("fclose");
3821 if (f2 && fclose(f2) == EOF && err == NULL)
3822 err = got_error_from_errno("fclose");
3823 free(tree_id1);
3824 return err;
3827 static const struct got_error *
3828 print_patch(struct got_commit_object *commit, struct got_object_id *id,
3829 const char *path, int diff_context, struct got_diffstat_cb_arg *dsa,
3830 struct got_repository *repo, FILE *outfile)
3832 const struct got_error *err = NULL;
3833 struct got_commit_object *pcommit = NULL;
3834 char *id_str1 = NULL, *id_str2 = NULL;
3835 struct got_object_id *obj_id1 = NULL, *obj_id2 = NULL;
3836 struct got_object_qid *qid;
3838 qid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
3839 if (qid != NULL) {
3840 err = got_object_open_as_commit(&pcommit, repo,
3841 &qid->id);
3842 if (err)
3843 return err;
3844 err = got_object_id_str(&id_str1, &qid->id);
3845 if (err)
3846 goto done;
3849 err = got_object_id_str(&id_str2, id);
3850 if (err)
3851 goto done;
3853 if (path && path[0] != '\0') {
3854 int obj_type;
3855 err = got_object_id_by_path(&obj_id2, repo, commit, path);
3856 if (err)
3857 goto done;
3858 if (pcommit) {
3859 err = got_object_id_by_path(&obj_id1, repo,
3860 pcommit, path);
3861 if (err) {
3862 if (err->code != GOT_ERR_NO_TREE_ENTRY) {
3863 free(obj_id2);
3864 goto done;
3868 err = got_object_get_type(&obj_type, repo, obj_id2);
3869 if (err) {
3870 free(obj_id2);
3871 goto done;
3873 fprintf(outfile,
3874 "diff %s %s\n", id_str1 ? id_str1 : "/dev/null", id_str2);
3875 fprintf(outfile, "commit - %s\n",
3876 id_str1 ? id_str1 : "/dev/null");
3877 fprintf(outfile, "commit + %s\n", id_str2);
3878 switch (obj_type) {
3879 case GOT_OBJ_TYPE_BLOB:
3880 err = diff_blobs(obj_id1, obj_id2, path, diff_context,
3881 0, 0, dsa, repo, outfile);
3882 break;
3883 case GOT_OBJ_TYPE_TREE:
3884 err = diff_trees(obj_id1, obj_id2, path, diff_context,
3885 0, 0, dsa, repo, outfile);
3886 break;
3887 default:
3888 err = got_error(GOT_ERR_OBJ_TYPE);
3889 break;
3891 free(obj_id1);
3892 free(obj_id2);
3893 } else {
3894 obj_id2 = got_object_commit_get_tree_id(commit);
3895 if (pcommit)
3896 obj_id1 = got_object_commit_get_tree_id(pcommit);
3897 fprintf(outfile,
3898 "diff %s %s\n", id_str1 ? id_str1 : "/dev/null", id_str2);
3899 fprintf(outfile, "commit - %s\n",
3900 id_str1 ? id_str1 : "/dev/null");
3901 fprintf(outfile, "commit + %s\n", id_str2);
3902 err = diff_trees(obj_id1, obj_id2, "", diff_context, 0, 0,
3903 dsa, repo, outfile);
3905 done:
3906 free(id_str1);
3907 free(id_str2);
3908 if (pcommit)
3909 got_object_commit_close(pcommit);
3910 return err;
3913 static char *
3914 get_datestr(time_t *time, char *datebuf)
3916 struct tm mytm, *tm;
3917 char *p, *s;
3919 tm = gmtime_r(time, &mytm);
3920 if (tm == NULL)
3921 return NULL;
3922 s = asctime_r(tm, datebuf);
3923 if (s == NULL)
3924 return NULL;
3925 p = strchr(s, '\n');
3926 if (p)
3927 *p = '\0';
3928 return s;
3931 static const struct got_error *
3932 match_commit(int *have_match, struct got_object_id *id,
3933 struct got_commit_object *commit, regex_t *regex)
3935 const struct got_error *err = NULL;
3936 regmatch_t regmatch;
3937 char *id_str = NULL, *logmsg = NULL;
3939 *have_match = 0;
3941 err = got_object_id_str(&id_str, id);
3942 if (err)
3943 return err;
3945 err = got_object_commit_get_logmsg(&logmsg, commit);
3946 if (err)
3947 goto done;
3949 if (regexec(regex, got_object_commit_get_author(commit), 1,
3950 &regmatch, 0) == 0 ||
3951 regexec(regex, got_object_commit_get_committer(commit), 1,
3952 &regmatch, 0) == 0 ||
3953 regexec(regex, id_str, 1, &regmatch, 0) == 0 ||
3954 regexec(regex, logmsg, 1, &regmatch, 0) == 0)
3955 *have_match = 1;
3956 done:
3957 free(id_str);
3958 free(logmsg);
3959 return err;
3962 static void
3963 match_changed_paths(int *have_match, struct got_pathlist_head *changed_paths,
3964 regex_t *regex)
3966 regmatch_t regmatch;
3967 struct got_pathlist_entry *pe;
3969 *have_match = 0;
3971 TAILQ_FOREACH(pe, changed_paths, entry) {
3972 if (regexec(regex, pe->path, 1, &regmatch, 0) == 0) {
3973 *have_match = 1;
3974 break;
3979 static const struct got_error *
3980 match_patch(int *have_match, struct got_commit_object *commit,
3981 struct got_object_id *id, const char *path, int diff_context,
3982 struct got_repository *repo, regex_t *regex, FILE *f)
3984 const struct got_error *err = NULL;
3985 char *line = NULL;
3986 size_t linesize = 0;
3987 regmatch_t regmatch;
3989 *have_match = 0;
3991 err = got_opentemp_truncate(f);
3992 if (err)
3993 return err;
3995 err = print_patch(commit, id, path, diff_context, NULL, repo, f);
3996 if (err)
3997 goto done;
3999 if (fseeko(f, 0L, SEEK_SET) == -1) {
4000 err = got_error_from_errno("fseeko");
4001 goto done;
4004 while (getline(&line, &linesize, f) != -1) {
4005 if (regexec(regex, line, 1, &regmatch, 0) == 0) {
4006 *have_match = 1;
4007 break;
4010 done:
4011 free(line);
4012 return err;
4015 #define GOT_COMMIT_SEP_STR "-----------------------------------------------\n"
4017 static const struct got_error*
4018 build_refs_str(char **refs_str, struct got_reflist_head *refs,
4019 struct got_object_id *id, struct got_repository *repo,
4020 int local_only)
4022 static const struct got_error *err = NULL;
4023 struct got_reflist_entry *re;
4024 char *s;
4025 const char *name;
4027 *refs_str = NULL;
4029 TAILQ_FOREACH(re, refs, entry) {
4030 struct got_tag_object *tag = NULL;
4031 struct got_object_id *ref_id;
4032 int cmp;
4034 name = got_ref_get_name(re->ref);
4035 if (strcmp(name, GOT_REF_HEAD) == 0)
4036 continue;
4037 if (strncmp(name, "refs/", 5) == 0)
4038 name += 5;
4039 if (strncmp(name, "got/", 4) == 0)
4040 continue;
4041 if (strncmp(name, "heads/", 6) == 0)
4042 name += 6;
4043 if (strncmp(name, "remotes/", 8) == 0) {
4044 if (local_only)
4045 continue;
4046 name += 8;
4047 s = strstr(name, "/" GOT_REF_HEAD);
4048 if (s != NULL && s[strlen(s)] == '\0')
4049 continue;
4051 err = got_ref_resolve(&ref_id, repo, re->ref);
4052 if (err)
4053 break;
4054 if (strncmp(name, "tags/", 5) == 0) {
4055 err = got_object_open_as_tag(&tag, repo, ref_id);
4056 if (err) {
4057 if (err->code != GOT_ERR_OBJ_TYPE) {
4058 free(ref_id);
4059 break;
4061 /* Ref points at something other than a tag. */
4062 err = NULL;
4063 tag = NULL;
4066 cmp = got_object_id_cmp(tag ?
4067 got_object_tag_get_object_id(tag) : ref_id, id);
4068 free(ref_id);
4069 if (tag)
4070 got_object_tag_close(tag);
4071 if (cmp != 0)
4072 continue;
4073 s = *refs_str;
4074 if (asprintf(refs_str, "%s%s%s", s ? s : "",
4075 s ? ", " : "", name) == -1) {
4076 err = got_error_from_errno("asprintf");
4077 free(s);
4078 *refs_str = NULL;
4079 break;
4081 free(s);
4084 return err;
4087 static const struct got_error *
4088 print_commit_oneline(struct got_commit_object *commit, struct got_object_id *id,
4089 struct got_repository *repo, struct got_reflist_object_id_map *refs_idmap)
4091 const struct got_error *err = NULL;
4092 char *ref_str = NULL, *id_str = NULL, *logmsg0 = NULL;
4093 char *comma, *s, *nl;
4094 struct got_reflist_head *refs;
4095 char datebuf[12]; /* YYYY-MM-DD + SPACE + NUL */
4096 struct tm tm;
4097 time_t committer_time;
4099 refs = got_reflist_object_id_map_lookup(refs_idmap, id);
4100 if (refs) {
4101 err = build_refs_str(&ref_str, refs, id, repo, 1);
4102 if (err)
4103 return err;
4105 /* Display the first matching ref only. */
4106 if (ref_str && (comma = strchr(ref_str, ',')) != NULL)
4107 *comma = '\0';
4110 if (ref_str == NULL) {
4111 err = got_object_id_str(&id_str, id);
4112 if (err)
4113 return err;
4116 committer_time = got_object_commit_get_committer_time(commit);
4117 if (gmtime_r(&committer_time, &tm) == NULL) {
4118 err = got_error_from_errno("gmtime_r");
4119 goto done;
4121 if (strftime(datebuf, sizeof(datebuf), "%G-%m-%d ", &tm) == 0) {
4122 err = got_error(GOT_ERR_NO_SPACE);
4123 goto done;
4126 err = got_object_commit_get_logmsg(&logmsg0, commit);
4127 if (err)
4128 goto done;
4130 s = logmsg0;
4131 while (isspace((unsigned char)s[0]))
4132 s++;
4134 nl = strchr(s, '\n');
4135 if (nl) {
4136 *nl = '\0';
4139 if (ref_str)
4140 printf("%s%-7s %s\n", datebuf, ref_str, s);
4141 else
4142 printf("%s%.7s %s\n", datebuf, id_str, s);
4144 if (fflush(stdout) != 0 && err == NULL)
4145 err = got_error_from_errno("fflush");
4146 done:
4147 free(id_str);
4148 free(ref_str);
4149 free(logmsg0);
4150 return err;
4153 static const struct got_error *
4154 print_diffstat(struct got_diffstat_cb_arg *dsa, const char *header)
4156 struct got_pathlist_entry *pe;
4158 if (header != NULL)
4159 printf("%s\n", header);
4161 TAILQ_FOREACH(pe, dsa->paths, entry) {
4162 struct got_diff_changed_path *cp = pe->data;
4163 int pad = dsa->max_path_len - pe->path_len + 1;
4165 printf(" %c %s%*c | %*d+ %*d-\n", cp->status, pe->path, pad,
4166 ' ', dsa->add_cols + 1, cp->add, dsa->rm_cols + 1, cp->rm);
4168 printf("\n%d file%s changed, %d insertion%s(+), %d deletion%s(-)\n\n",
4169 dsa->nfiles, dsa->nfiles > 1 ? "s" : "", dsa->ins,
4170 dsa->ins != 1 ? "s" : "", dsa->del, dsa->del != 1 ? "s" : "");
4172 if (fflush(stdout) != 0)
4173 return got_error_from_errno("fflush");
4175 return NULL;
4178 static const struct got_error *
4179 printfile(FILE *f)
4181 char buf[8192];
4182 size_t r;
4184 if (fseeko(f, 0L, SEEK_SET) == -1)
4185 return got_error_from_errno("fseek");
4187 for (;;) {
4188 r = fread(buf, 1, sizeof(buf), f);
4189 if (r == 0) {
4190 if (ferror(f))
4191 return got_error_from_errno("fread");
4192 if (feof(f))
4193 break;
4195 if (fwrite(buf, 1, r, stdout) != r)
4196 return got_ferror(stdout, GOT_ERR_IO);
4199 return NULL;
4202 static const struct got_error *
4203 print_commit(struct got_commit_object *commit, struct got_object_id *id,
4204 struct got_repository *repo, const char *path,
4205 struct got_pathlist_head *changed_paths,
4206 struct got_diffstat_cb_arg *diffstat, int show_patch, int diff_context,
4207 struct got_reflist_object_id_map *refs_idmap, const char *custom_refs_str,
4208 const char *prefix)
4210 const struct got_error *err = NULL;
4211 FILE *f = NULL;
4212 char *id_str, *datestr, *logmsg0, *logmsg, *line;
4213 char datebuf[26];
4214 time_t committer_time;
4215 const char *author, *committer;
4216 char *refs_str = NULL;
4218 err = got_object_id_str(&id_str, id);
4219 if (err)
4220 return err;
4222 if (custom_refs_str == NULL) {
4223 struct got_reflist_head *refs;
4224 refs = got_reflist_object_id_map_lookup(refs_idmap, id);
4225 if (refs) {
4226 err = build_refs_str(&refs_str, refs, id, repo, 0);
4227 if (err)
4228 goto done;
4232 printf(GOT_COMMIT_SEP_STR);
4233 if (custom_refs_str)
4234 printf("%s %s (%s)\n", prefix ? prefix : "commit", id_str,
4235 custom_refs_str);
4236 else
4237 printf("%s %s%s%s%s\n", prefix ? prefix : "commit", id_str,
4238 refs_str ? " (" : "", refs_str ? refs_str : "",
4239 refs_str ? ")" : "");
4240 free(id_str);
4241 id_str = NULL;
4242 free(refs_str);
4243 refs_str = NULL;
4244 printf("from: %s\n", got_object_commit_get_author(commit));
4245 author = got_object_commit_get_author(commit);
4246 committer = got_object_commit_get_committer(commit);
4247 if (strcmp(author, committer) != 0)
4248 printf("via: %s\n", committer);
4249 committer_time = got_object_commit_get_committer_time(commit);
4250 datestr = get_datestr(&committer_time, datebuf);
4251 if (datestr)
4252 printf("date: %s UTC\n", datestr);
4253 if (got_object_commit_get_nparents(commit) > 1) {
4254 const struct got_object_id_queue *parent_ids;
4255 struct got_object_qid *qid;
4256 int n = 1;
4257 parent_ids = got_object_commit_get_parent_ids(commit);
4258 STAILQ_FOREACH(qid, parent_ids, entry) {
4259 err = got_object_id_str(&id_str, &qid->id);
4260 if (err)
4261 goto done;
4262 printf("parent %d: %s\n", n++, id_str);
4263 free(id_str);
4264 id_str = NULL;
4268 err = got_object_commit_get_logmsg(&logmsg0, commit);
4269 if (err)
4270 goto done;
4272 logmsg = logmsg0;
4273 do {
4274 line = strsep(&logmsg, "\n");
4275 if (line)
4276 printf(" %s\n", line);
4277 } while (line);
4278 free(logmsg0);
4280 if (changed_paths && diffstat == NULL) {
4281 struct got_pathlist_entry *pe;
4283 TAILQ_FOREACH(pe, changed_paths, entry) {
4284 struct got_diff_changed_path *cp = pe->data;
4286 printf(" %c %s\n", cp->status, pe->path);
4288 printf("\n");
4290 if (show_patch) {
4291 if (diffstat) {
4292 f = got_opentemp();
4293 if (f == NULL) {
4294 err = got_error_from_errno("got_opentemp");
4295 goto done;
4299 err = print_patch(commit, id, path, diff_context, diffstat,
4300 repo, diffstat == NULL ? stdout : f);
4301 if (err)
4302 goto done;
4304 if (diffstat) {
4305 err = print_diffstat(diffstat, NULL);
4306 if (err)
4307 goto done;
4308 if (show_patch) {
4309 err = printfile(f);
4310 if (err)
4311 goto done;
4314 if (show_patch)
4315 printf("\n");
4317 if (fflush(stdout) != 0 && err == NULL)
4318 err = got_error_from_errno("fflush");
4319 done:
4320 if (f && fclose(f) == EOF && err == NULL)
4321 err = got_error_from_errno("fclose");
4322 free(id_str);
4323 free(refs_str);
4324 return err;
4327 static const struct got_error *
4328 print_commits(struct got_object_id *root_id, struct got_object_id *end_id,
4329 struct got_repository *repo, const char *path, int show_changed_paths,
4330 int show_diffstat, int show_patch, const char *search_pattern,
4331 int diff_context, int limit, int log_branches, int reverse_display_order,
4332 struct got_reflist_object_id_map *refs_idmap, int one_line,
4333 FILE *tmpfile)
4335 const struct got_error *err;
4336 struct got_commit_graph *graph;
4337 regex_t regex;
4338 int have_match;
4339 struct got_object_id_queue reversed_commits;
4340 struct got_object_qid *qid;
4341 struct got_commit_object *commit;
4342 struct got_pathlist_head changed_paths;
4344 STAILQ_INIT(&reversed_commits);
4345 TAILQ_INIT(&changed_paths);
4347 if (search_pattern && regcomp(&regex, search_pattern,
4348 REG_EXTENDED | REG_NOSUB | REG_NEWLINE))
4349 return got_error_msg(GOT_ERR_REGEX, search_pattern);
4351 err = got_commit_graph_open(&graph, path, !log_branches);
4352 if (err)
4353 return err;
4354 err = got_commit_graph_iter_start(graph, root_id, repo,
4355 check_cancelled, NULL);
4356 if (err)
4357 goto done;
4358 for (;;) {
4359 struct got_object_id id;
4360 struct got_diffstat_cb_arg dsa = { 0, 0, 0, 0, 0, 0,
4361 &changed_paths, 0, 0, GOT_DIFF_ALGORITHM_PATIENCE };
4363 if (sigint_received || sigpipe_received)
4364 break;
4366 err = got_commit_graph_iter_next(&id, graph, repo,
4367 check_cancelled, NULL);
4368 if (err) {
4369 if (err->code == GOT_ERR_ITER_COMPLETED)
4370 err = NULL;
4371 break;
4374 err = got_object_open_as_commit(&commit, repo, &id);
4375 if (err)
4376 break;
4378 if ((show_changed_paths || (show_diffstat && !show_patch))
4379 && !reverse_display_order) {
4380 err = get_changed_paths(&changed_paths, commit, repo,
4381 show_diffstat ? &dsa : NULL);
4382 if (err)
4383 break;
4386 if (search_pattern) {
4387 err = match_commit(&have_match, &id, commit, &regex);
4388 if (err) {
4389 got_object_commit_close(commit);
4390 break;
4392 if (have_match == 0 && show_changed_paths)
4393 match_changed_paths(&have_match,
4394 &changed_paths, &regex);
4395 if (have_match == 0 && show_patch) {
4396 err = match_patch(&have_match, commit, &id,
4397 path, diff_context, repo, &regex, tmpfile);
4398 if (err)
4399 break;
4401 if (have_match == 0) {
4402 got_object_commit_close(commit);
4403 got_pathlist_free(&changed_paths,
4404 GOT_PATHLIST_FREE_ALL);
4405 continue;
4409 if (reverse_display_order) {
4410 err = got_object_qid_alloc(&qid, &id);
4411 if (err)
4412 break;
4413 STAILQ_INSERT_HEAD(&reversed_commits, qid, entry);
4414 got_object_commit_close(commit);
4415 } else {
4416 if (one_line)
4417 err = print_commit_oneline(commit, &id,
4418 repo, refs_idmap);
4419 else
4420 err = print_commit(commit, &id, repo, path,
4421 (show_changed_paths || show_diffstat) ?
4422 &changed_paths : NULL,
4423 show_diffstat ? &dsa : NULL, show_patch,
4424 diff_context, refs_idmap, NULL, NULL);
4425 got_object_commit_close(commit);
4426 if (err)
4427 break;
4429 if ((limit && --limit == 0) ||
4430 (end_id && got_object_id_cmp(&id, end_id) == 0))
4431 break;
4433 got_pathlist_free(&changed_paths, GOT_PATHLIST_FREE_ALL);
4435 if (reverse_display_order) {
4436 STAILQ_FOREACH(qid, &reversed_commits, entry) {
4437 struct got_diffstat_cb_arg dsa = { 0, 0, 0, 0, 0, 0,
4438 &changed_paths, 0, 0, GOT_DIFF_ALGORITHM_PATIENCE };
4440 err = got_object_open_as_commit(&commit, repo,
4441 &qid->id);
4442 if (err)
4443 break;
4444 if (show_changed_paths ||
4445 (show_diffstat && !show_patch)) {
4446 err = get_changed_paths(&changed_paths, commit,
4447 repo, show_diffstat ? &dsa : NULL);
4448 if (err)
4449 break;
4451 if (one_line)
4452 err = print_commit_oneline(commit, &qid->id,
4453 repo, refs_idmap);
4454 else
4455 err = print_commit(commit, &qid->id, repo, path,
4456 (show_changed_paths || show_diffstat) ?
4457 &changed_paths : NULL,
4458 show_diffstat ? &dsa : NULL, show_patch,
4459 diff_context, refs_idmap, NULL, NULL);
4460 got_object_commit_close(commit);
4461 if (err)
4462 break;
4463 got_pathlist_free(&changed_paths, GOT_PATHLIST_FREE_ALL);
4466 done:
4467 while (!STAILQ_EMPTY(&reversed_commits)) {
4468 qid = STAILQ_FIRST(&reversed_commits);
4469 STAILQ_REMOVE_HEAD(&reversed_commits, entry);
4470 got_object_qid_free(qid);
4472 got_pathlist_free(&changed_paths, GOT_PATHLIST_FREE_ALL);
4473 if (search_pattern)
4474 regfree(&regex);
4475 got_commit_graph_close(graph);
4476 return err;
4479 __dead static void
4480 usage_log(void)
4482 fprintf(stderr, "usage: %s log [-bdPpRs] [-C number] [-c commit] "
4483 "[-l N] [-r repository-path] [-S search-pattern] [-x commit] "
4484 "[path]\n", getprogname());
4485 exit(1);
4488 static int
4489 get_default_log_limit(void)
4491 const char *got_default_log_limit;
4492 long long n;
4493 const char *errstr;
4495 got_default_log_limit = getenv("GOT_LOG_DEFAULT_LIMIT");
4496 if (got_default_log_limit == NULL)
4497 return 0;
4498 n = strtonum(got_default_log_limit, 0, INT_MAX, &errstr);
4499 if (errstr != NULL)
4500 return 0;
4501 return n;
4504 static const struct got_error *
4505 cmd_log(int argc, char *argv[])
4507 const struct got_error *error;
4508 struct got_repository *repo = NULL;
4509 struct got_worktree *worktree = NULL;
4510 struct got_object_id *start_id = NULL, *end_id = NULL;
4511 char *repo_path = NULL, *path = NULL, *cwd = NULL, *in_repo_path = NULL;
4512 const char *start_commit = NULL, *end_commit = NULL;
4513 const char *search_pattern = NULL;
4514 int diff_context = -1, ch;
4515 int show_changed_paths = 0, show_patch = 0, limit = 0, log_branches = 0;
4516 int show_diffstat = 0, reverse_display_order = 0, one_line = 0;
4517 const char *errstr;
4518 struct got_reflist_head refs;
4519 struct got_reflist_object_id_map *refs_idmap = NULL;
4520 FILE *tmpfile = NULL;
4521 int *pack_fds = NULL;
4523 TAILQ_INIT(&refs);
4525 #ifndef PROFILE
4526 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
4527 NULL)
4528 == -1)
4529 err(1, "pledge");
4530 #endif
4532 limit = get_default_log_limit();
4534 while ((ch = getopt(argc, argv, "bC:c:dl:PpRr:S:sx:")) != -1) {
4535 switch (ch) {
4536 case 'b':
4537 log_branches = 1;
4538 break;
4539 case 'C':
4540 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
4541 &errstr);
4542 if (errstr != NULL)
4543 errx(1, "number of context lines is %s: %s",
4544 errstr, optarg);
4545 break;
4546 case 'c':
4547 start_commit = optarg;
4548 break;
4549 case 'd':
4550 show_diffstat = 1;
4551 break;
4552 case 'l':
4553 limit = strtonum(optarg, 0, INT_MAX, &errstr);
4554 if (errstr != NULL)
4555 errx(1, "number of commits is %s: %s",
4556 errstr, optarg);
4557 break;
4558 case 'P':
4559 show_changed_paths = 1;
4560 break;
4561 case 'p':
4562 show_patch = 1;
4563 break;
4564 case 'R':
4565 reverse_display_order = 1;
4566 break;
4567 case 'r':
4568 repo_path = realpath(optarg, NULL);
4569 if (repo_path == NULL)
4570 return got_error_from_errno2("realpath",
4571 optarg);
4572 got_path_strip_trailing_slashes(repo_path);
4573 break;
4574 case 'S':
4575 search_pattern = optarg;
4576 break;
4577 case 's':
4578 one_line = 1;
4579 break;
4580 case 'x':
4581 end_commit = optarg;
4582 break;
4583 default:
4584 usage_log();
4585 /* NOTREACHED */
4589 argc -= optind;
4590 argv += optind;
4592 if (diff_context == -1)
4593 diff_context = 3;
4594 else if (!show_patch)
4595 errx(1, "-C requires -p");
4597 if (one_line && (show_patch || show_changed_paths || show_diffstat))
4598 errx(1, "cannot use -s with -d, -p or -P");
4600 cwd = getcwd(NULL, 0);
4601 if (cwd == NULL) {
4602 error = got_error_from_errno("getcwd");
4603 goto done;
4606 error = got_repo_pack_fds_open(&pack_fds);
4607 if (error != NULL)
4608 goto done;
4610 if (repo_path == NULL) {
4611 error = got_worktree_open(&worktree, cwd);
4612 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4613 goto done;
4614 error = NULL;
4617 if (argc == 1) {
4618 if (worktree) {
4619 error = got_worktree_resolve_path(&path, worktree,
4620 argv[0]);
4621 if (error)
4622 goto done;
4623 } else {
4624 path = strdup(argv[0]);
4625 if (path == NULL) {
4626 error = got_error_from_errno("strdup");
4627 goto done;
4630 } else if (argc != 0)
4631 usage_log();
4633 if (repo_path == NULL) {
4634 repo_path = worktree ?
4635 strdup(got_worktree_get_repo_path(worktree)) : strdup(cwd);
4637 if (repo_path == NULL) {
4638 error = got_error_from_errno("strdup");
4639 goto done;
4642 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
4643 if (error != NULL)
4644 goto done;
4646 error = apply_unveil(got_repo_get_path(repo), 1,
4647 worktree ? got_worktree_get_root_path(worktree) : NULL);
4648 if (error)
4649 goto done;
4651 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
4652 if (error)
4653 goto done;
4655 error = got_reflist_object_id_map_create(&refs_idmap, &refs, repo);
4656 if (error)
4657 goto done;
4659 if (start_commit == NULL) {
4660 struct got_reference *head_ref;
4661 struct got_commit_object *commit = NULL;
4662 error = got_ref_open(&head_ref, repo,
4663 worktree ? got_worktree_get_head_ref_name(worktree)
4664 : GOT_REF_HEAD, 0);
4665 if (error != NULL)
4666 goto done;
4667 error = got_ref_resolve(&start_id, repo, head_ref);
4668 got_ref_close(head_ref);
4669 if (error != NULL)
4670 goto done;
4671 error = got_object_open_as_commit(&commit, repo,
4672 start_id);
4673 if (error != NULL)
4674 goto done;
4675 got_object_commit_close(commit);
4676 } else {
4677 error = got_repo_match_object_id(&start_id, NULL,
4678 start_commit, GOT_OBJ_TYPE_COMMIT, &refs, repo);
4679 if (error != NULL)
4680 goto done;
4682 if (end_commit != NULL) {
4683 error = got_repo_match_object_id(&end_id, NULL,
4684 end_commit, GOT_OBJ_TYPE_COMMIT, &refs, repo);
4685 if (error != NULL)
4686 goto done;
4689 if (worktree) {
4691 * If a path was specified on the command line it was resolved
4692 * to a path in the work tree above. Prepend the work tree's
4693 * path prefix to obtain the corresponding in-repository path.
4695 if (path) {
4696 const char *prefix;
4697 prefix = got_worktree_get_path_prefix(worktree);
4698 if (asprintf(&in_repo_path, "%s%s%s", prefix,
4699 (path[0] != '\0') ? "/" : "", path) == -1) {
4700 error = got_error_from_errno("asprintf");
4701 goto done;
4704 } else
4705 error = got_repo_map_path(&in_repo_path, repo,
4706 path ? path : "");
4707 if (error != NULL)
4708 goto done;
4709 if (in_repo_path) {
4710 free(path);
4711 path = in_repo_path;
4714 if (worktree) {
4715 /* Release work tree lock. */
4716 got_worktree_close(worktree);
4717 worktree = NULL;
4720 if (search_pattern && show_patch) {
4721 tmpfile = got_opentemp();
4722 if (tmpfile == NULL) {
4723 error = got_error_from_errno("got_opentemp");
4724 goto done;
4728 error = print_commits(start_id, end_id, repo, path ? path : "",
4729 show_changed_paths, show_diffstat, show_patch, search_pattern,
4730 diff_context, limit, log_branches, reverse_display_order,
4731 refs_idmap, one_line, tmpfile);
4732 done:
4733 free(path);
4734 free(repo_path);
4735 free(cwd);
4736 if (worktree)
4737 got_worktree_close(worktree);
4738 if (repo) {
4739 const struct got_error *close_err = got_repo_close(repo);
4740 if (error == NULL)
4741 error = close_err;
4743 if (pack_fds) {
4744 const struct got_error *pack_err =
4745 got_repo_pack_fds_close(pack_fds);
4746 if (error == NULL)
4747 error = pack_err;
4749 if (refs_idmap)
4750 got_reflist_object_id_map_free(refs_idmap);
4751 if (tmpfile && fclose(tmpfile) == EOF && error == NULL)
4752 error = got_error_from_errno("fclose");
4753 got_ref_list_free(&refs);
4754 return error;
4757 __dead static void
4758 usage_diff(void)
4760 fprintf(stderr, "usage: %s diff [-adPsw] [-C number] [-c commit] "
4761 "[-r repository-path] [object1 object2 | path ...]\n",
4762 getprogname());
4763 exit(1);
4766 struct print_diff_arg {
4767 struct got_repository *repo;
4768 struct got_worktree *worktree;
4769 struct got_diffstat_cb_arg *diffstat;
4770 int diff_context;
4771 const char *id_str;
4772 int header_shown;
4773 int diff_staged;
4774 enum got_diff_algorithm diff_algo;
4775 int ignore_whitespace;
4776 int force_text_diff;
4777 FILE *f1;
4778 FILE *f2;
4779 FILE *outfile;
4783 * Create a file which contains the target path of a symlink so we can feed
4784 * it as content to the diff engine.
4786 static const struct got_error *
4787 get_symlink_target_file(int *fd, int dirfd, const char *de_name,
4788 const char *abspath)
4790 const struct got_error *err = NULL;
4791 char target_path[PATH_MAX];
4792 ssize_t target_len, outlen;
4794 *fd = -1;
4796 if (dirfd != -1) {
4797 target_len = readlinkat(dirfd, de_name, target_path, PATH_MAX);
4798 if (target_len == -1)
4799 return got_error_from_errno2("readlinkat", abspath);
4800 } else {
4801 target_len = readlink(abspath, target_path, PATH_MAX);
4802 if (target_len == -1)
4803 return got_error_from_errno2("readlink", abspath);
4806 *fd = got_opentempfd();
4807 if (*fd == -1)
4808 return got_error_from_errno("got_opentempfd");
4810 outlen = write(*fd, target_path, target_len);
4811 if (outlen == -1) {
4812 err = got_error_from_errno("got_opentempfd");
4813 goto done;
4816 if (lseek(*fd, 0, SEEK_SET) == -1) {
4817 err = got_error_from_errno2("lseek", abspath);
4818 goto done;
4820 done:
4821 if (err) {
4822 close(*fd);
4823 *fd = -1;
4825 return err;
4828 static const struct got_error *
4829 print_diff(void *arg, unsigned char status, unsigned char staged_status,
4830 const char *path, struct got_object_id *blob_id,
4831 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
4832 int dirfd, const char *de_name)
4834 struct print_diff_arg *a = arg;
4835 const struct got_error *err = NULL;
4836 struct got_blob_object *blob1 = NULL;
4837 int fd = -1, fd1 = -1, fd2 = -1;
4838 FILE *f2 = NULL;
4839 char *abspath = NULL, *label1 = NULL;
4840 struct stat sb;
4841 off_t size1 = 0;
4842 int f2_exists = 0;
4844 memset(&sb, 0, sizeof(sb));
4846 if (a->diff_staged) {
4847 if (staged_status != GOT_STATUS_MODIFY &&
4848 staged_status != GOT_STATUS_ADD &&
4849 staged_status != GOT_STATUS_DELETE)
4850 return NULL;
4851 } else {
4852 if (staged_status == GOT_STATUS_DELETE)
4853 return NULL;
4854 if (status == GOT_STATUS_NONEXISTENT)
4855 return got_error_set_errno(ENOENT, path);
4856 if (status != GOT_STATUS_MODIFY &&
4857 status != GOT_STATUS_ADD &&
4858 status != GOT_STATUS_DELETE &&
4859 status != GOT_STATUS_CONFLICT)
4860 return NULL;
4863 err = got_opentemp_truncate(a->f1);
4864 if (err)
4865 return got_error_from_errno("got_opentemp_truncate");
4866 err = got_opentemp_truncate(a->f2);
4867 if (err)
4868 return got_error_from_errno("got_opentemp_truncate");
4870 if (!a->header_shown) {
4871 if (fprintf(a->outfile, "diff %s%s\n",
4872 a->diff_staged ? "-s " : "",
4873 got_worktree_get_root_path(a->worktree)) < 0) {
4874 err = got_error_from_errno("fprintf");
4875 goto done;
4877 if (fprintf(a->outfile, "commit - %s\n", a->id_str) < 0) {
4878 err = got_error_from_errno("fprintf");
4879 goto done;
4881 if (fprintf(a->outfile, "path + %s%s\n",
4882 got_worktree_get_root_path(a->worktree),
4883 a->diff_staged ? " (staged changes)" : "") < 0) {
4884 err = got_error_from_errno("fprintf");
4885 goto done;
4887 a->header_shown = 1;
4890 if (a->diff_staged) {
4891 const char *label1 = NULL, *label2 = NULL;
4892 switch (staged_status) {
4893 case GOT_STATUS_MODIFY:
4894 label1 = path;
4895 label2 = path;
4896 break;
4897 case GOT_STATUS_ADD:
4898 label2 = path;
4899 break;
4900 case GOT_STATUS_DELETE:
4901 label1 = path;
4902 break;
4903 default:
4904 return got_error(GOT_ERR_FILE_STATUS);
4906 fd1 = got_opentempfd();
4907 if (fd1 == -1) {
4908 err = got_error_from_errno("got_opentempfd");
4909 goto done;
4911 fd2 = got_opentempfd();
4912 if (fd2 == -1) {
4913 err = got_error_from_errno("got_opentempfd");
4914 goto done;
4916 err = got_diff_objects_as_blobs(NULL, NULL, a->f1, a->f2,
4917 fd1, fd2, blob_id, staged_blob_id, label1, label2,
4918 a->diff_algo, a->diff_context, a->ignore_whitespace,
4919 a->force_text_diff, a->diffstat, a->repo, a->outfile);
4920 goto done;
4923 fd1 = got_opentempfd();
4924 if (fd1 == -1) {
4925 err = got_error_from_errno("got_opentempfd");
4926 goto done;
4929 if (staged_status == GOT_STATUS_ADD ||
4930 staged_status == GOT_STATUS_MODIFY) {
4931 char *id_str;
4932 err = got_object_open_as_blob(&blob1, a->repo, staged_blob_id,
4933 8192, fd1);
4934 if (err)
4935 goto done;
4936 err = got_object_id_str(&id_str, staged_blob_id);
4937 if (err)
4938 goto done;
4939 if (asprintf(&label1, "%s (staged)", id_str) == -1) {
4940 err = got_error_from_errno("asprintf");
4941 free(id_str);
4942 goto done;
4944 free(id_str);
4945 } else if (status != GOT_STATUS_ADD) {
4946 err = got_object_open_as_blob(&blob1, a->repo, blob_id, 8192,
4947 fd1);
4948 if (err)
4949 goto done;
4952 if (status != GOT_STATUS_DELETE) {
4953 if (asprintf(&abspath, "%s/%s",
4954 got_worktree_get_root_path(a->worktree), path) == -1) {
4955 err = got_error_from_errno("asprintf");
4956 goto done;
4959 if (dirfd != -1) {
4960 fd = openat(dirfd, de_name,
4961 O_RDONLY | O_NOFOLLOW | O_CLOEXEC);
4962 if (fd == -1) {
4963 if (!got_err_open_nofollow_on_symlink()) {
4964 err = got_error_from_errno2("openat",
4965 abspath);
4966 goto done;
4968 err = get_symlink_target_file(&fd, dirfd,
4969 de_name, abspath);
4970 if (err)
4971 goto done;
4973 } else {
4974 fd = open(abspath, O_RDONLY | O_NOFOLLOW | O_CLOEXEC);
4975 if (fd == -1) {
4976 if (!got_err_open_nofollow_on_symlink()) {
4977 err = got_error_from_errno2("open",
4978 abspath);
4979 goto done;
4981 err = get_symlink_target_file(&fd, dirfd,
4982 de_name, abspath);
4983 if (err)
4984 goto done;
4987 if (fstatat(fd, abspath, &sb, AT_SYMLINK_NOFOLLOW) == -1) {
4988 err = got_error_from_errno2("fstatat", abspath);
4989 goto done;
4991 f2 = fdopen(fd, "r");
4992 if (f2 == NULL) {
4993 err = got_error_from_errno2("fdopen", abspath);
4994 goto done;
4996 fd = -1;
4997 f2_exists = 1;
5000 if (blob1) {
5001 err = got_object_blob_dump_to_file(&size1, NULL, NULL,
5002 a->f1, blob1);
5003 if (err)
5004 goto done;
5007 err = got_diff_blob_file(blob1, a->f1, size1, label1, f2 ? f2 : a->f2,
5008 f2_exists, &sb, path, GOT_DIFF_ALGORITHM_PATIENCE, a->diff_context,
5009 a->ignore_whitespace, a->force_text_diff, a->diffstat, a->outfile);
5010 done:
5011 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
5012 err = got_error_from_errno("close");
5013 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
5014 err = got_error_from_errno("close");
5015 if (blob1)
5016 got_object_blob_close(blob1);
5017 if (fd != -1 && close(fd) == -1 && err == NULL)
5018 err = got_error_from_errno("close");
5019 if (f2 && fclose(f2) == EOF && err == NULL)
5020 err = got_error_from_errno("fclose");
5021 free(abspath);
5022 return err;
5025 static const struct got_error *
5026 cmd_diff(int argc, char *argv[])
5028 const struct got_error *error;
5029 struct got_repository *repo = NULL;
5030 struct got_worktree *worktree = NULL;
5031 char *cwd = NULL, *repo_path = NULL;
5032 const char *commit_args[2] = { NULL, NULL };
5033 int ncommit_args = 0;
5034 struct got_object_id *ids[2] = { NULL, NULL };
5035 char *labels[2] = { NULL, NULL };
5036 int type1 = GOT_OBJ_TYPE_ANY, type2 = GOT_OBJ_TYPE_ANY;
5037 int diff_context = 3, diff_staged = 0, ignore_whitespace = 0, ch, i;
5038 int force_text_diff = 0, force_path = 0, rflag = 0, show_diffstat = 0;
5039 const char *errstr;
5040 struct got_reflist_head refs;
5041 struct got_pathlist_head diffstat_paths, paths;
5042 FILE *f1 = NULL, *f2 = NULL, *outfile = NULL;
5043 int fd1 = -1, fd2 = -1;
5044 int *pack_fds = NULL;
5045 struct got_diffstat_cb_arg dsa;
5047 memset(&dsa, 0, sizeof(dsa));
5049 TAILQ_INIT(&refs);
5050 TAILQ_INIT(&paths);
5051 TAILQ_INIT(&diffstat_paths);
5053 #ifndef PROFILE
5054 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
5055 NULL) == -1)
5056 err(1, "pledge");
5057 #endif
5059 while ((ch = getopt(argc, argv, "aC:c:dPr:sw")) != -1) {
5060 switch (ch) {
5061 case 'a':
5062 force_text_diff = 1;
5063 break;
5064 case 'C':
5065 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
5066 &errstr);
5067 if (errstr != NULL)
5068 errx(1, "number of context lines is %s: %s",
5069 errstr, optarg);
5070 break;
5071 case 'c':
5072 if (ncommit_args >= 2)
5073 errx(1, "too many -c options used");
5074 commit_args[ncommit_args++] = optarg;
5075 break;
5076 case 'd':
5077 show_diffstat = 1;
5078 break;
5079 case 'P':
5080 force_path = 1;
5081 break;
5082 case 'r':
5083 repo_path = realpath(optarg, NULL);
5084 if (repo_path == NULL)
5085 return got_error_from_errno2("realpath",
5086 optarg);
5087 got_path_strip_trailing_slashes(repo_path);
5088 rflag = 1;
5089 break;
5090 case 's':
5091 diff_staged = 1;
5092 break;
5093 case 'w':
5094 ignore_whitespace = 1;
5095 break;
5096 default:
5097 usage_diff();
5098 /* NOTREACHED */
5102 argc -= optind;
5103 argv += optind;
5105 cwd = getcwd(NULL, 0);
5106 if (cwd == NULL) {
5107 error = got_error_from_errno("getcwd");
5108 goto done;
5111 error = got_repo_pack_fds_open(&pack_fds);
5112 if (error != NULL)
5113 goto done;
5115 if (repo_path == NULL) {
5116 error = got_worktree_open(&worktree, cwd);
5117 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5118 goto done;
5119 else
5120 error = NULL;
5121 if (worktree) {
5122 repo_path =
5123 strdup(got_worktree_get_repo_path(worktree));
5124 if (repo_path == NULL) {
5125 error = got_error_from_errno("strdup");
5126 goto done;
5128 } else {
5129 repo_path = strdup(cwd);
5130 if (repo_path == NULL) {
5131 error = got_error_from_errno("strdup");
5132 goto done;
5137 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
5138 free(repo_path);
5139 if (error != NULL)
5140 goto done;
5142 if (show_diffstat) {
5143 dsa.paths = &diffstat_paths;
5144 dsa.force_text = force_text_diff;
5145 dsa.ignore_ws = ignore_whitespace;
5146 dsa.diff_algo = GOT_DIFF_ALGORITHM_PATIENCE;
5149 if (rflag || worktree == NULL || ncommit_args > 0) {
5150 if (force_path) {
5151 error = got_error_msg(GOT_ERR_NOT_IMPL,
5152 "-P option can only be used when diffing "
5153 "a work tree");
5154 goto done;
5156 if (diff_staged) {
5157 error = got_error_msg(GOT_ERR_NOT_IMPL,
5158 "-s option can only be used when diffing "
5159 "a work tree");
5160 goto done;
5164 error = apply_unveil(got_repo_get_path(repo), 1,
5165 worktree ? got_worktree_get_root_path(worktree) : NULL);
5166 if (error)
5167 goto done;
5169 if ((!force_path && argc == 2) || ncommit_args > 0) {
5170 int obj_type = (ncommit_args > 0 ?
5171 GOT_OBJ_TYPE_COMMIT : GOT_OBJ_TYPE_ANY);
5172 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
5173 NULL);
5174 if (error)
5175 goto done;
5176 for (i = 0; i < (ncommit_args > 0 ? ncommit_args : argc); i++) {
5177 const char *arg;
5178 if (ncommit_args > 0)
5179 arg = commit_args[i];
5180 else
5181 arg = argv[i];
5182 error = got_repo_match_object_id(&ids[i], &labels[i],
5183 arg, obj_type, &refs, repo);
5184 if (error) {
5185 if (error->code != GOT_ERR_NOT_REF &&
5186 error->code != GOT_ERR_NO_OBJ)
5187 goto done;
5188 if (ncommit_args > 0)
5189 goto done;
5190 error = NULL;
5191 break;
5196 f1 = got_opentemp();
5197 if (f1 == NULL) {
5198 error = got_error_from_errno("got_opentemp");
5199 goto done;
5202 f2 = got_opentemp();
5203 if (f2 == NULL) {
5204 error = got_error_from_errno("got_opentemp");
5205 goto done;
5208 outfile = got_opentemp();
5209 if (outfile == NULL) {
5210 error = got_error_from_errno("got_opentemp");
5211 goto done;
5214 if (ncommit_args == 0 && (ids[0] == NULL || ids[1] == NULL)) {
5215 struct print_diff_arg arg;
5216 char *id_str;
5218 if (worktree == NULL) {
5219 if (argc == 2 && ids[0] == NULL) {
5220 error = got_error_path(argv[0], GOT_ERR_NO_OBJ);
5221 goto done;
5222 } else if (argc == 2 && ids[1] == NULL) {
5223 error = got_error_path(argv[1], GOT_ERR_NO_OBJ);
5224 goto done;
5225 } else if (argc > 0) {
5226 error = got_error_fmt(GOT_ERR_NOT_WORKTREE,
5227 "%s", "specified paths cannot be resolved");
5228 goto done;
5229 } else {
5230 error = got_error(GOT_ERR_NOT_WORKTREE);
5231 goto done;
5235 error = get_worktree_paths_from_argv(&paths, argc, argv,
5236 worktree);
5237 if (error)
5238 goto done;
5240 error = got_object_id_str(&id_str,
5241 got_worktree_get_base_commit_id(worktree));
5242 if (error)
5243 goto done;
5244 arg.repo = repo;
5245 arg.worktree = worktree;
5246 arg.diff_algo = GOT_DIFF_ALGORITHM_PATIENCE;
5247 arg.diff_context = diff_context;
5248 arg.id_str = id_str;
5249 arg.header_shown = 0;
5250 arg.diff_staged = diff_staged;
5251 arg.ignore_whitespace = ignore_whitespace;
5252 arg.force_text_diff = force_text_diff;
5253 arg.diffstat = show_diffstat ? &dsa : NULL;
5254 arg.f1 = f1;
5255 arg.f2 = f2;
5256 arg.outfile = outfile;
5258 error = got_worktree_status(worktree, &paths, repo, 0,
5259 print_diff, &arg, check_cancelled, NULL);
5260 free(id_str);
5261 if (error)
5262 goto done;
5264 if (show_diffstat && dsa.nfiles > 0) {
5265 char *header;
5267 if (asprintf(&header, "diffstat %s%s",
5268 diff_staged ? "-s " : "",
5269 got_worktree_get_root_path(worktree)) == -1) {
5270 error = got_error_from_errno("asprintf");
5271 goto done;
5274 error = print_diffstat(&dsa, header);
5275 free(header);
5276 if (error)
5277 goto done;
5280 error = printfile(outfile);
5281 goto done;
5284 if (ncommit_args == 1) {
5285 struct got_commit_object *commit;
5286 error = got_object_open_as_commit(&commit, repo, ids[0]);
5287 if (error)
5288 goto done;
5290 labels[1] = labels[0];
5291 ids[1] = ids[0];
5292 if (got_object_commit_get_nparents(commit) > 0) {
5293 const struct got_object_id_queue *pids;
5294 struct got_object_qid *pid;
5295 pids = got_object_commit_get_parent_ids(commit);
5296 pid = STAILQ_FIRST(pids);
5297 ids[0] = got_object_id_dup(&pid->id);
5298 if (ids[0] == NULL) {
5299 error = got_error_from_errno(
5300 "got_object_id_dup");
5301 got_object_commit_close(commit);
5302 goto done;
5304 error = got_object_id_str(&labels[0], ids[0]);
5305 if (error) {
5306 got_object_commit_close(commit);
5307 goto done;
5309 } else {
5310 ids[0] = NULL;
5311 labels[0] = strdup("/dev/null");
5312 if (labels[0] == NULL) {
5313 error = got_error_from_errno("strdup");
5314 got_object_commit_close(commit);
5315 goto done;
5319 got_object_commit_close(commit);
5322 if (ncommit_args == 0 && argc > 2) {
5323 error = got_error_msg(GOT_ERR_BAD_PATH,
5324 "path arguments cannot be used when diffing two objects");
5325 goto done;
5328 if (ids[0]) {
5329 error = got_object_get_type(&type1, repo, ids[0]);
5330 if (error)
5331 goto done;
5334 error = got_object_get_type(&type2, repo, ids[1]);
5335 if (error)
5336 goto done;
5337 if (type1 != GOT_OBJ_TYPE_ANY && type1 != type2) {
5338 error = got_error(GOT_ERR_OBJ_TYPE);
5339 goto done;
5341 if (type1 == GOT_OBJ_TYPE_BLOB && argc > 2) {
5342 error = got_error_msg(GOT_ERR_OBJ_TYPE,
5343 "path arguments cannot be used when diffing blobs");
5344 goto done;
5347 for (i = 0; ncommit_args > 0 && i < argc; i++) {
5348 char *in_repo_path;
5349 struct got_pathlist_entry *new;
5350 if (worktree) {
5351 const char *prefix;
5352 char *p;
5353 error = got_worktree_resolve_path(&p, worktree,
5354 argv[i]);
5355 if (error)
5356 goto done;
5357 prefix = got_worktree_get_path_prefix(worktree);
5358 while (prefix[0] == '/')
5359 prefix++;
5360 if (asprintf(&in_repo_path, "%s%s%s", prefix,
5361 (p[0] != '\0' && prefix[0] != '\0') ? "/" : "",
5362 p) == -1) {
5363 error = got_error_from_errno("asprintf");
5364 free(p);
5365 goto done;
5367 free(p);
5368 } else {
5369 char *mapped_path, *s;
5370 error = got_repo_map_path(&mapped_path, repo, argv[i]);
5371 if (error)
5372 goto done;
5373 s = mapped_path;
5374 while (s[0] == '/')
5375 s++;
5376 in_repo_path = strdup(s);
5377 if (in_repo_path == NULL) {
5378 error = got_error_from_errno("asprintf");
5379 free(mapped_path);
5380 goto done;
5382 free(mapped_path);
5385 error = got_pathlist_insert(&new, &paths, in_repo_path, NULL);
5386 if (error || new == NULL /* duplicate */)
5387 free(in_repo_path);
5388 if (error)
5389 goto done;
5392 if (worktree) {
5393 /* Release work tree lock. */
5394 got_worktree_close(worktree);
5395 worktree = NULL;
5398 fd1 = got_opentempfd();
5399 if (fd1 == -1) {
5400 error = got_error_from_errno("got_opentempfd");
5401 goto done;
5404 fd2 = got_opentempfd();
5405 if (fd2 == -1) {
5406 error = got_error_from_errno("got_opentempfd");
5407 goto done;
5410 switch (type1 == GOT_OBJ_TYPE_ANY ? type2 : type1) {
5411 case GOT_OBJ_TYPE_BLOB:
5412 error = got_diff_objects_as_blobs(NULL, NULL, f1, f2,
5413 fd1, fd2, ids[0], ids[1], NULL, NULL,
5414 GOT_DIFF_ALGORITHM_PATIENCE, diff_context,
5415 ignore_whitespace, force_text_diff,
5416 show_diffstat ? &dsa : NULL, repo, outfile);
5417 break;
5418 case GOT_OBJ_TYPE_TREE:
5419 error = got_diff_objects_as_trees(NULL, NULL, f1, f2, fd1, fd2,
5420 ids[0], ids[1], &paths, "", "",
5421 GOT_DIFF_ALGORITHM_PATIENCE, diff_context,
5422 ignore_whitespace, force_text_diff,
5423 show_diffstat ? &dsa : NULL, repo, outfile);
5424 break;
5425 case GOT_OBJ_TYPE_COMMIT:
5426 fprintf(outfile, "diff %s %s\n", labels[0], labels[1]);
5427 error = got_diff_objects_as_commits(NULL, NULL, f1, f2,
5428 fd1, fd2, ids[0], ids[1], &paths,
5429 GOT_DIFF_ALGORITHM_PATIENCE, diff_context,
5430 ignore_whitespace, force_text_diff,
5431 show_diffstat ? &dsa : NULL, repo, outfile);
5432 break;
5433 default:
5434 error = got_error(GOT_ERR_OBJ_TYPE);
5436 if (error)
5437 goto done;
5439 if (show_diffstat && dsa.nfiles > 0) {
5440 char *header = NULL;
5442 if (asprintf(&header, "diffstat %s %s",
5443 labels[0], labels[1]) == -1) {
5444 error = got_error_from_errno("asprintf");
5445 goto done;
5448 error = print_diffstat(&dsa, header);
5449 free(header);
5450 if (error)
5451 goto done;
5454 error = printfile(outfile);
5456 done:
5457 free(labels[0]);
5458 free(labels[1]);
5459 free(ids[0]);
5460 free(ids[1]);
5461 if (worktree)
5462 got_worktree_close(worktree);
5463 if (repo) {
5464 const struct got_error *close_err = got_repo_close(repo);
5465 if (error == NULL)
5466 error = close_err;
5468 if (pack_fds) {
5469 const struct got_error *pack_err =
5470 got_repo_pack_fds_close(pack_fds);
5471 if (error == NULL)
5472 error = pack_err;
5474 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
5475 got_pathlist_free(&diffstat_paths, GOT_PATHLIST_FREE_ALL);
5476 got_ref_list_free(&refs);
5477 if (outfile && fclose(outfile) == EOF && error == NULL)
5478 error = got_error_from_errno("fclose");
5479 if (f1 && fclose(f1) == EOF && error == NULL)
5480 error = got_error_from_errno("fclose");
5481 if (f2 && fclose(f2) == EOF && error == NULL)
5482 error = got_error_from_errno("fclose");
5483 if (fd1 != -1 && close(fd1) == -1 && error == NULL)
5484 error = got_error_from_errno("close");
5485 if (fd2 != -1 && close(fd2) == -1 && error == NULL)
5486 error = got_error_from_errno("close");
5487 return error;
5490 __dead static void
5491 usage_blame(void)
5493 fprintf(stderr,
5494 "usage: %s blame [-c commit] [-r repository-path] path\n",
5495 getprogname());
5496 exit(1);
5499 struct blame_line {
5500 int annotated;
5501 char *id_str;
5502 char *committer;
5503 char datebuf[11]; /* YYYY-MM-DD + NUL */
5506 struct blame_cb_args {
5507 struct blame_line *lines;
5508 int nlines;
5509 int nlines_prec;
5510 int lineno_cur;
5511 off_t *line_offsets;
5512 FILE *f;
5513 struct got_repository *repo;
5516 static const struct got_error *
5517 blame_cb(void *arg, int nlines, int lineno,
5518 struct got_commit_object *commit, struct got_object_id *id)
5520 const struct got_error *err = NULL;
5521 struct blame_cb_args *a = arg;
5522 struct blame_line *bline;
5523 char *line = NULL;
5524 size_t linesize = 0;
5525 off_t offset;
5526 struct tm tm;
5527 time_t committer_time;
5529 if (nlines != a->nlines ||
5530 (lineno != -1 && lineno < 1) || lineno > a->nlines)
5531 return got_error(GOT_ERR_RANGE);
5533 if (sigint_received)
5534 return got_error(GOT_ERR_ITER_COMPLETED);
5536 if (lineno == -1)
5537 return NULL; /* no change in this commit */
5539 /* Annotate this line. */
5540 bline = &a->lines[lineno - 1];
5541 if (bline->annotated)
5542 return NULL;
5543 err = got_object_id_str(&bline->id_str, id);
5544 if (err)
5545 return err;
5547 bline->committer = strdup(got_object_commit_get_committer(commit));
5548 if (bline->committer == NULL) {
5549 err = got_error_from_errno("strdup");
5550 goto done;
5553 committer_time = got_object_commit_get_committer_time(commit);
5554 if (gmtime_r(&committer_time, &tm) == NULL)
5555 return got_error_from_errno("gmtime_r");
5556 if (strftime(bline->datebuf, sizeof(bline->datebuf), "%G-%m-%d",
5557 &tm) == 0) {
5558 err = got_error(GOT_ERR_NO_SPACE);
5559 goto done;
5561 bline->annotated = 1;
5563 /* Print lines annotated so far. */
5564 bline = &a->lines[a->lineno_cur - 1];
5565 if (!bline->annotated)
5566 goto done;
5568 offset = a->line_offsets[a->lineno_cur - 1];
5569 if (fseeko(a->f, offset, SEEK_SET) == -1) {
5570 err = got_error_from_errno("fseeko");
5571 goto done;
5574 while (a->lineno_cur <= a->nlines && bline->annotated) {
5575 char *smallerthan, *at, *nl, *committer;
5576 size_t len;
5578 if (getline(&line, &linesize, a->f) == -1) {
5579 if (ferror(a->f))
5580 err = got_error_from_errno("getline");
5581 break;
5584 committer = bline->committer;
5585 smallerthan = strchr(committer, '<');
5586 if (smallerthan && smallerthan[1] != '\0')
5587 committer = smallerthan + 1;
5588 at = strchr(committer, '@');
5589 if (at)
5590 *at = '\0';
5591 len = strlen(committer);
5592 if (len >= 9)
5593 committer[8] = '\0';
5595 nl = strchr(line, '\n');
5596 if (nl)
5597 *nl = '\0';
5598 printf("%.*d) %.8s %s %-8s %s\n", a->nlines_prec, a->lineno_cur,
5599 bline->id_str, bline->datebuf, committer, line);
5601 a->lineno_cur++;
5602 bline = &a->lines[a->lineno_cur - 1];
5604 done:
5605 free(line);
5606 return err;
5609 static const struct got_error *
5610 cmd_blame(int argc, char *argv[])
5612 const struct got_error *error;
5613 struct got_repository *repo = NULL;
5614 struct got_worktree *worktree = NULL;
5615 char *path, *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
5616 char *link_target = NULL;
5617 struct got_object_id *obj_id = NULL;
5618 struct got_object_id *commit_id = NULL;
5619 struct got_commit_object *commit = NULL;
5620 struct got_blob_object *blob = NULL;
5621 char *commit_id_str = NULL;
5622 struct blame_cb_args bca;
5623 int ch, obj_type, i, fd1 = -1, fd2 = -1, fd3 = -1;
5624 off_t filesize;
5625 int *pack_fds = NULL;
5626 FILE *f1 = NULL, *f2 = NULL;
5628 fd1 = got_opentempfd();
5629 if (fd1 == -1)
5630 return got_error_from_errno("got_opentempfd");
5632 memset(&bca, 0, sizeof(bca));
5634 #ifndef PROFILE
5635 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
5636 NULL) == -1)
5637 err(1, "pledge");
5638 #endif
5640 while ((ch = getopt(argc, argv, "c:r:")) != -1) {
5641 switch (ch) {
5642 case 'c':
5643 commit_id_str = optarg;
5644 break;
5645 case 'r':
5646 repo_path = realpath(optarg, NULL);
5647 if (repo_path == NULL)
5648 return got_error_from_errno2("realpath",
5649 optarg);
5650 got_path_strip_trailing_slashes(repo_path);
5651 break;
5652 default:
5653 usage_blame();
5654 /* NOTREACHED */
5658 argc -= optind;
5659 argv += optind;
5661 if (argc == 1)
5662 path = argv[0];
5663 else
5664 usage_blame();
5666 cwd = getcwd(NULL, 0);
5667 if (cwd == NULL) {
5668 error = got_error_from_errno("getcwd");
5669 goto done;
5672 error = got_repo_pack_fds_open(&pack_fds);
5673 if (error != NULL)
5674 goto done;
5676 if (repo_path == NULL) {
5677 error = got_worktree_open(&worktree, cwd);
5678 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5679 goto done;
5680 else
5681 error = NULL;
5682 if (worktree) {
5683 repo_path =
5684 strdup(got_worktree_get_repo_path(worktree));
5685 if (repo_path == NULL) {
5686 error = got_error_from_errno("strdup");
5687 if (error)
5688 goto done;
5690 } else {
5691 repo_path = strdup(cwd);
5692 if (repo_path == NULL) {
5693 error = got_error_from_errno("strdup");
5694 goto done;
5699 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
5700 if (error != NULL)
5701 goto done;
5703 if (worktree) {
5704 const char *prefix = got_worktree_get_path_prefix(worktree);
5705 char *p;
5707 error = got_worktree_resolve_path(&p, worktree, path);
5708 if (error)
5709 goto done;
5710 if (asprintf(&in_repo_path, "%s%s%s", prefix,
5711 (p[0] != '\0' && !got_path_is_root_dir(prefix)) ? "/" : "",
5712 p) == -1) {
5713 error = got_error_from_errno("asprintf");
5714 free(p);
5715 goto done;
5717 free(p);
5718 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5719 } else {
5720 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5721 if (error)
5722 goto done;
5723 error = got_repo_map_path(&in_repo_path, repo, path);
5725 if (error)
5726 goto done;
5728 if (commit_id_str == NULL) {
5729 struct got_reference *head_ref;
5730 error = got_ref_open(&head_ref, repo, worktree ?
5731 got_worktree_get_head_ref_name(worktree) : GOT_REF_HEAD, 0);
5732 if (error != NULL)
5733 goto done;
5734 error = got_ref_resolve(&commit_id, repo, head_ref);
5735 got_ref_close(head_ref);
5736 if (error != NULL)
5737 goto done;
5738 } else {
5739 struct got_reflist_head refs;
5740 TAILQ_INIT(&refs);
5741 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
5742 NULL);
5743 if (error)
5744 goto done;
5745 error = got_repo_match_object_id(&commit_id, NULL,
5746 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
5747 got_ref_list_free(&refs);
5748 if (error)
5749 goto done;
5752 if (worktree) {
5753 /* Release work tree lock. */
5754 got_worktree_close(worktree);
5755 worktree = NULL;
5758 error = got_object_open_as_commit(&commit, repo, commit_id);
5759 if (error)
5760 goto done;
5762 error = got_object_resolve_symlinks(&link_target, in_repo_path,
5763 commit, repo);
5764 if (error)
5765 goto done;
5767 error = got_object_id_by_path(&obj_id, repo, commit,
5768 link_target ? link_target : in_repo_path);
5769 if (error)
5770 goto done;
5772 error = got_object_get_type(&obj_type, repo, obj_id);
5773 if (error)
5774 goto done;
5776 if (obj_type != GOT_OBJ_TYPE_BLOB) {
5777 error = got_error_path(link_target ? link_target : in_repo_path,
5778 GOT_ERR_OBJ_TYPE);
5779 goto done;
5782 error = got_object_open_as_blob(&blob, repo, obj_id, 8192, fd1);
5783 if (error)
5784 goto done;
5785 bca.f = got_opentemp();
5786 if (bca.f == NULL) {
5787 error = got_error_from_errno("got_opentemp");
5788 goto done;
5790 error = got_object_blob_dump_to_file(&filesize, &bca.nlines,
5791 &bca.line_offsets, bca.f, blob);
5792 if (error || bca.nlines == 0)
5793 goto done;
5795 /* Don't include \n at EOF in the blame line count. */
5796 if (bca.line_offsets[bca.nlines - 1] == filesize)
5797 bca.nlines--;
5799 bca.lines = calloc(bca.nlines, sizeof(*bca.lines));
5800 if (bca.lines == NULL) {
5801 error = got_error_from_errno("calloc");
5802 goto done;
5804 bca.lineno_cur = 1;
5805 bca.nlines_prec = 0;
5806 i = bca.nlines;
5807 while (i > 0) {
5808 i /= 10;
5809 bca.nlines_prec++;
5811 bca.repo = repo;
5813 fd2 = got_opentempfd();
5814 if (fd2 == -1) {
5815 error = got_error_from_errno("got_opentempfd");
5816 goto done;
5818 fd3 = got_opentempfd();
5819 if (fd3 == -1) {
5820 error = got_error_from_errno("got_opentempfd");
5821 goto done;
5823 f1 = got_opentemp();
5824 if (f1 == NULL) {
5825 error = got_error_from_errno("got_opentemp");
5826 goto done;
5828 f2 = got_opentemp();
5829 if (f2 == NULL) {
5830 error = got_error_from_errno("got_opentemp");
5831 goto done;
5833 error = got_blame(link_target ? link_target : in_repo_path, commit_id,
5834 repo, GOT_DIFF_ALGORITHM_PATIENCE, blame_cb, &bca,
5835 check_cancelled, NULL, fd2, fd3, f1, f2);
5836 done:
5837 free(in_repo_path);
5838 free(link_target);
5839 free(repo_path);
5840 free(cwd);
5841 free(commit_id);
5842 free(obj_id);
5843 if (commit)
5844 got_object_commit_close(commit);
5846 if (fd1 != -1 && close(fd1) == -1 && error == NULL)
5847 error = got_error_from_errno("close");
5848 if (fd2 != -1 && close(fd2) == -1 && error == NULL)
5849 error = got_error_from_errno("close");
5850 if (fd3 != -1 && close(fd3) == -1 && error == NULL)
5851 error = got_error_from_errno("close");
5852 if (f1 && fclose(f1) == EOF && error == NULL)
5853 error = got_error_from_errno("fclose");
5854 if (f2 && fclose(f2) == EOF && error == NULL)
5855 error = got_error_from_errno("fclose");
5857 if (blob)
5858 got_object_blob_close(blob);
5859 if (worktree)
5860 got_worktree_close(worktree);
5861 if (repo) {
5862 const struct got_error *close_err = got_repo_close(repo);
5863 if (error == NULL)
5864 error = close_err;
5866 if (pack_fds) {
5867 const struct got_error *pack_err =
5868 got_repo_pack_fds_close(pack_fds);
5869 if (error == NULL)
5870 error = pack_err;
5872 if (bca.lines) {
5873 for (i = 0; i < bca.nlines; i++) {
5874 struct blame_line *bline = &bca.lines[i];
5875 free(bline->id_str);
5876 free(bline->committer);
5878 free(bca.lines);
5880 free(bca.line_offsets);
5881 if (bca.f && fclose(bca.f) == EOF && error == NULL)
5882 error = got_error_from_errno("fclose");
5883 return error;
5886 __dead static void
5887 usage_tree(void)
5889 fprintf(stderr, "usage: %s tree [-iR] [-c commit] [-r repository-path] "
5890 "[path]\n", getprogname());
5891 exit(1);
5894 static const struct got_error *
5895 print_entry(struct got_tree_entry *te, const char *id, const char *path,
5896 const char *root_path, struct got_repository *repo)
5898 const struct got_error *err = NULL;
5899 int is_root_path = (strcmp(path, root_path) == 0);
5900 const char *modestr = "";
5901 mode_t mode = got_tree_entry_get_mode(te);
5902 char *link_target = NULL;
5904 path += strlen(root_path);
5905 while (path[0] == '/')
5906 path++;
5908 if (got_object_tree_entry_is_submodule(te))
5909 modestr = "$";
5910 else if (S_ISLNK(mode)) {
5911 int i;
5913 err = got_tree_entry_get_symlink_target(&link_target, te, repo);
5914 if (err)
5915 return err;
5916 for (i = 0; i < strlen(link_target); i++) {
5917 if (!isprint((unsigned char)link_target[i]))
5918 link_target[i] = '?';
5921 modestr = "@";
5923 else if (S_ISDIR(mode))
5924 modestr = "/";
5925 else if (mode & S_IXUSR)
5926 modestr = "*";
5928 printf("%s%s%s%s%s%s%s\n", id ? id : "", path,
5929 is_root_path ? "" : "/", got_tree_entry_get_name(te), modestr,
5930 link_target ? " -> ": "", link_target ? link_target : "");
5932 free(link_target);
5933 return NULL;
5936 static const struct got_error *
5937 print_tree(const char *path, struct got_commit_object *commit,
5938 int show_ids, int recurse, const char *root_path,
5939 struct got_repository *repo)
5941 const struct got_error *err = NULL;
5942 struct got_object_id *tree_id = NULL;
5943 struct got_tree_object *tree = NULL;
5944 int nentries, i;
5946 err = got_object_id_by_path(&tree_id, repo, commit, path);
5947 if (err)
5948 goto done;
5950 err = got_object_open_as_tree(&tree, repo, tree_id);
5951 if (err)
5952 goto done;
5953 nentries = got_object_tree_get_nentries(tree);
5954 for (i = 0; i < nentries; i++) {
5955 struct got_tree_entry *te;
5956 char *id = NULL;
5958 if (sigint_received || sigpipe_received)
5959 break;
5961 te = got_object_tree_get_entry(tree, i);
5962 if (show_ids) {
5963 char *id_str;
5964 err = got_object_id_str(&id_str,
5965 got_tree_entry_get_id(te));
5966 if (err)
5967 goto done;
5968 if (asprintf(&id, "%s ", id_str) == -1) {
5969 err = got_error_from_errno("asprintf");
5970 free(id_str);
5971 goto done;
5973 free(id_str);
5975 err = print_entry(te, id, path, root_path, repo);
5976 free(id);
5977 if (err)
5978 goto done;
5980 if (recurse && S_ISDIR(got_tree_entry_get_mode(te))) {
5981 char *child_path;
5982 if (asprintf(&child_path, "%s%s%s", path,
5983 path[0] == '/' && path[1] == '\0' ? "" : "/",
5984 got_tree_entry_get_name(te)) == -1) {
5985 err = got_error_from_errno("asprintf");
5986 goto done;
5988 err = print_tree(child_path, commit, show_ids, 1,
5989 root_path, repo);
5990 free(child_path);
5991 if (err)
5992 goto done;
5995 done:
5996 if (tree)
5997 got_object_tree_close(tree);
5998 free(tree_id);
5999 return err;
6002 static const struct got_error *
6003 cmd_tree(int argc, char *argv[])
6005 const struct got_error *error;
6006 struct got_repository *repo = NULL;
6007 struct got_worktree *worktree = NULL;
6008 const char *path, *refname = NULL;
6009 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
6010 struct got_object_id *commit_id = NULL;
6011 struct got_commit_object *commit = NULL;
6012 char *commit_id_str = NULL;
6013 int show_ids = 0, recurse = 0;
6014 int ch;
6015 int *pack_fds = NULL;
6017 #ifndef PROFILE
6018 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
6019 NULL) == -1)
6020 err(1, "pledge");
6021 #endif
6023 while ((ch = getopt(argc, argv, "c:iRr:")) != -1) {
6024 switch (ch) {
6025 case 'c':
6026 commit_id_str = optarg;
6027 break;
6028 case 'i':
6029 show_ids = 1;
6030 break;
6031 case 'R':
6032 recurse = 1;
6033 break;
6034 case 'r':
6035 repo_path = realpath(optarg, NULL);
6036 if (repo_path == NULL)
6037 return got_error_from_errno2("realpath",
6038 optarg);
6039 got_path_strip_trailing_slashes(repo_path);
6040 break;
6041 default:
6042 usage_tree();
6043 /* NOTREACHED */
6047 argc -= optind;
6048 argv += optind;
6050 if (argc == 1)
6051 path = argv[0];
6052 else if (argc > 1)
6053 usage_tree();
6054 else
6055 path = NULL;
6057 cwd = getcwd(NULL, 0);
6058 if (cwd == NULL) {
6059 error = got_error_from_errno("getcwd");
6060 goto done;
6063 error = got_repo_pack_fds_open(&pack_fds);
6064 if (error != NULL)
6065 goto done;
6067 if (repo_path == NULL) {
6068 error = got_worktree_open(&worktree, cwd);
6069 if (error && error->code != GOT_ERR_NOT_WORKTREE)
6070 goto done;
6071 else
6072 error = NULL;
6073 if (worktree) {
6074 repo_path =
6075 strdup(got_worktree_get_repo_path(worktree));
6076 if (repo_path == NULL)
6077 error = got_error_from_errno("strdup");
6078 if (error)
6079 goto done;
6080 } else {
6081 repo_path = strdup(cwd);
6082 if (repo_path == NULL) {
6083 error = got_error_from_errno("strdup");
6084 goto done;
6089 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
6090 if (error != NULL)
6091 goto done;
6093 if (worktree) {
6094 const char *prefix = got_worktree_get_path_prefix(worktree);
6095 char *p;
6097 if (path == NULL)
6098 path = "";
6099 error = got_worktree_resolve_path(&p, worktree, path);
6100 if (error)
6101 goto done;
6102 if (asprintf(&in_repo_path, "%s%s%s", prefix,
6103 (p[0] != '\0' && !got_path_is_root_dir(prefix)) ? "/" : "",
6104 p) == -1) {
6105 error = got_error_from_errno("asprintf");
6106 free(p);
6107 goto done;
6109 free(p);
6110 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
6111 if (error)
6112 goto done;
6113 } else {
6114 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
6115 if (error)
6116 goto done;
6117 if (path == NULL)
6118 path = "/";
6119 error = got_repo_map_path(&in_repo_path, repo, path);
6120 if (error != NULL)
6121 goto done;
6124 if (commit_id_str == NULL) {
6125 struct got_reference *head_ref;
6126 if (worktree)
6127 refname = got_worktree_get_head_ref_name(worktree);
6128 else
6129 refname = GOT_REF_HEAD;
6130 error = got_ref_open(&head_ref, repo, refname, 0);
6131 if (error != NULL)
6132 goto done;
6133 error = got_ref_resolve(&commit_id, repo, head_ref);
6134 got_ref_close(head_ref);
6135 if (error != NULL)
6136 goto done;
6137 } else {
6138 struct got_reflist_head refs;
6139 TAILQ_INIT(&refs);
6140 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
6141 NULL);
6142 if (error)
6143 goto done;
6144 error = got_repo_match_object_id(&commit_id, NULL,
6145 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
6146 got_ref_list_free(&refs);
6147 if (error)
6148 goto done;
6151 if (worktree) {
6152 /* Release work tree lock. */
6153 got_worktree_close(worktree);
6154 worktree = NULL;
6157 error = got_object_open_as_commit(&commit, repo, commit_id);
6158 if (error)
6159 goto done;
6161 error = print_tree(in_repo_path, commit, show_ids, recurse,
6162 in_repo_path, repo);
6163 done:
6164 free(in_repo_path);
6165 free(repo_path);
6166 free(cwd);
6167 free(commit_id);
6168 if (commit)
6169 got_object_commit_close(commit);
6170 if (worktree)
6171 got_worktree_close(worktree);
6172 if (repo) {
6173 const struct got_error *close_err = got_repo_close(repo);
6174 if (error == NULL)
6175 error = close_err;
6177 if (pack_fds) {
6178 const struct got_error *pack_err =
6179 got_repo_pack_fds_close(pack_fds);
6180 if (error == NULL)
6181 error = pack_err;
6183 return error;
6186 __dead static void
6187 usage_status(void)
6189 fprintf(stderr, "usage: %s status [-I] [-S status-codes] "
6190 "[-s status-codes] [path ...]\n", getprogname());
6191 exit(1);
6194 struct got_status_arg {
6195 char *status_codes;
6196 int suppress;
6199 static const struct got_error *
6200 print_status(void *arg, unsigned char status, unsigned char staged_status,
6201 const char *path, struct got_object_id *blob_id,
6202 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
6203 int dirfd, const char *de_name)
6205 struct got_status_arg *st = arg;
6207 if (status == staged_status && (status == GOT_STATUS_DELETE))
6208 status = GOT_STATUS_NO_CHANGE;
6209 if (st != NULL && st->status_codes) {
6210 size_t ncodes = strlen(st->status_codes);
6211 int i, j = 0;
6213 for (i = 0; i < ncodes ; i++) {
6214 if (st->suppress) {
6215 if (status == st->status_codes[i] ||
6216 staged_status == st->status_codes[i]) {
6217 j++;
6218 continue;
6220 } else {
6221 if (status == st->status_codes[i] ||
6222 staged_status == st->status_codes[i])
6223 break;
6227 if (st->suppress && j == 0)
6228 goto print;
6230 if (i == ncodes)
6231 return NULL;
6233 print:
6234 printf("%c%c %s\n", status, staged_status, path);
6235 return NULL;
6238 static const struct got_error *
6239 cmd_status(int argc, char *argv[])
6241 const struct got_error *error = NULL;
6242 struct got_repository *repo = NULL;
6243 struct got_worktree *worktree = NULL;
6244 struct got_status_arg st;
6245 char *cwd = NULL;
6246 struct got_pathlist_head paths;
6247 int ch, i, no_ignores = 0;
6248 int *pack_fds = NULL;
6250 TAILQ_INIT(&paths);
6252 memset(&st, 0, sizeof(st));
6253 st.status_codes = NULL;
6254 st.suppress = 0;
6256 while ((ch = getopt(argc, argv, "IS:s:")) != -1) {
6257 switch (ch) {
6258 case 'I':
6259 no_ignores = 1;
6260 break;
6261 case 'S':
6262 if (st.status_codes != NULL && st.suppress == 0)
6263 option_conflict('S', 's');
6264 st.suppress = 1;
6265 /* fallthrough */
6266 case 's':
6267 for (i = 0; i < strlen(optarg); i++) {
6268 switch (optarg[i]) {
6269 case GOT_STATUS_MODIFY:
6270 case GOT_STATUS_ADD:
6271 case GOT_STATUS_DELETE:
6272 case GOT_STATUS_CONFLICT:
6273 case GOT_STATUS_MISSING:
6274 case GOT_STATUS_OBSTRUCTED:
6275 case GOT_STATUS_UNVERSIONED:
6276 case GOT_STATUS_MODE_CHANGE:
6277 case GOT_STATUS_NONEXISTENT:
6278 break;
6279 default:
6280 errx(1, "invalid status code '%c'",
6281 optarg[i]);
6284 if (ch == 's' && st.suppress)
6285 option_conflict('s', 'S');
6286 st.status_codes = optarg;
6287 break;
6288 default:
6289 usage_status();
6290 /* NOTREACHED */
6294 argc -= optind;
6295 argv += optind;
6297 #ifndef PROFILE
6298 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
6299 NULL) == -1)
6300 err(1, "pledge");
6301 #endif
6302 cwd = getcwd(NULL, 0);
6303 if (cwd == NULL) {
6304 error = got_error_from_errno("getcwd");
6305 goto done;
6308 error = got_repo_pack_fds_open(&pack_fds);
6309 if (error != NULL)
6310 goto done;
6312 error = got_worktree_open(&worktree, cwd);
6313 if (error) {
6314 if (error->code == GOT_ERR_NOT_WORKTREE)
6315 error = wrap_not_worktree_error(error, "status", cwd);
6316 goto done;
6319 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
6320 NULL, pack_fds);
6321 if (error != NULL)
6322 goto done;
6324 error = apply_unveil(got_repo_get_path(repo), 1,
6325 got_worktree_get_root_path(worktree));
6326 if (error)
6327 goto done;
6329 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
6330 if (error)
6331 goto done;
6333 error = got_worktree_status(worktree, &paths, repo, no_ignores,
6334 print_status, &st, check_cancelled, NULL);
6335 done:
6336 if (pack_fds) {
6337 const struct got_error *pack_err =
6338 got_repo_pack_fds_close(pack_fds);
6339 if (error == NULL)
6340 error = pack_err;
6343 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
6344 free(cwd);
6345 return error;
6348 __dead static void
6349 usage_ref(void)
6351 fprintf(stderr, "usage: %s ref [-dlt] [-c object] [-r repository-path] "
6352 "[-s reference] [name]\n", getprogname());
6353 exit(1);
6356 static const struct got_error *
6357 list_refs(struct got_repository *repo, const char *refname, int sort_by_time)
6359 static const struct got_error *err = NULL;
6360 struct got_reflist_head refs;
6361 struct got_reflist_entry *re;
6363 TAILQ_INIT(&refs);
6364 err = got_ref_list(&refs, repo, refname, sort_by_time ?
6365 got_ref_cmp_by_commit_timestamp_descending : got_ref_cmp_by_name,
6366 repo);
6367 if (err)
6368 return err;
6370 TAILQ_FOREACH(re, &refs, entry) {
6371 char *refstr;
6372 refstr = got_ref_to_str(re->ref);
6373 if (refstr == NULL) {
6374 err = got_error_from_errno("got_ref_to_str");
6375 break;
6377 printf("%s: %s\n", got_ref_get_name(re->ref), refstr);
6378 free(refstr);
6381 got_ref_list_free(&refs);
6382 return err;
6385 static const struct got_error *
6386 delete_ref_by_name(struct got_repository *repo, const char *refname)
6388 const struct got_error *err;
6389 struct got_reference *ref;
6391 err = got_ref_open(&ref, repo, refname, 0);
6392 if (err)
6393 return err;
6395 err = delete_ref(repo, ref);
6396 got_ref_close(ref);
6397 return err;
6400 static const struct got_error *
6401 add_ref(struct got_repository *repo, const char *refname, const char *target)
6403 const struct got_error *err = NULL;
6404 struct got_object_id *id = NULL;
6405 struct got_reference *ref = NULL;
6406 struct got_reflist_head refs;
6409 * Don't let the user create a reference name with a leading '-'.
6410 * While technically a valid reference name, this case is usually
6411 * an unintended typo.
6413 if (refname[0] == '-')
6414 return got_error_path(refname, GOT_ERR_REF_NAME_MINUS);
6416 TAILQ_INIT(&refs);
6417 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
6418 if (err)
6419 goto done;
6420 err = got_repo_match_object_id(&id, NULL, target, GOT_OBJ_TYPE_ANY,
6421 &refs, repo);
6422 got_ref_list_free(&refs);
6423 if (err)
6424 goto done;
6426 err = got_ref_alloc(&ref, refname, id);
6427 if (err)
6428 goto done;
6430 err = got_ref_write(ref, repo);
6431 done:
6432 if (ref)
6433 got_ref_close(ref);
6434 free(id);
6435 return err;
6438 static const struct got_error *
6439 add_symref(struct got_repository *repo, const char *refname, const char *target)
6441 const struct got_error *err = NULL;
6442 struct got_reference *ref = NULL;
6443 struct got_reference *target_ref = NULL;
6446 * Don't let the user create a reference name with a leading '-'.
6447 * While technically a valid reference name, this case is usually
6448 * an unintended typo.
6450 if (refname[0] == '-')
6451 return got_error_path(refname, GOT_ERR_REF_NAME_MINUS);
6453 err = got_ref_open(&target_ref, repo, target, 0);
6454 if (err)
6455 return err;
6457 err = got_ref_alloc_symref(&ref, refname, target_ref);
6458 if (err)
6459 goto done;
6461 err = got_ref_write(ref, repo);
6462 done:
6463 if (target_ref)
6464 got_ref_close(target_ref);
6465 if (ref)
6466 got_ref_close(ref);
6467 return err;
6470 static const struct got_error *
6471 cmd_ref(int argc, char *argv[])
6473 const struct got_error *error = NULL;
6474 struct got_repository *repo = NULL;
6475 struct got_worktree *worktree = NULL;
6476 char *cwd = NULL, *repo_path = NULL;
6477 int ch, do_list = 0, do_delete = 0, sort_by_time = 0;
6478 const char *obj_arg = NULL, *symref_target= NULL;
6479 char *refname = NULL;
6480 int *pack_fds = NULL;
6482 while ((ch = getopt(argc, argv, "c:dlr:s:t")) != -1) {
6483 switch (ch) {
6484 case 'c':
6485 obj_arg = optarg;
6486 break;
6487 case 'd':
6488 do_delete = 1;
6489 break;
6490 case 'l':
6491 do_list = 1;
6492 break;
6493 case 'r':
6494 repo_path = realpath(optarg, NULL);
6495 if (repo_path == NULL)
6496 return got_error_from_errno2("realpath",
6497 optarg);
6498 got_path_strip_trailing_slashes(repo_path);
6499 break;
6500 case 's':
6501 symref_target = optarg;
6502 break;
6503 case 't':
6504 sort_by_time = 1;
6505 break;
6506 default:
6507 usage_ref();
6508 /* NOTREACHED */
6512 if (obj_arg && do_list)
6513 option_conflict('c', 'l');
6514 if (obj_arg && do_delete)
6515 option_conflict('c', 'd');
6516 if (obj_arg && symref_target)
6517 option_conflict('c', 's');
6518 if (symref_target && do_delete)
6519 option_conflict('s', 'd');
6520 if (symref_target && do_list)
6521 option_conflict('s', 'l');
6522 if (do_delete && do_list)
6523 option_conflict('d', 'l');
6524 if (sort_by_time && !do_list)
6525 errx(1, "-t option requires -l option");
6527 argc -= optind;
6528 argv += optind;
6530 if (do_list) {
6531 if (argc != 0 && argc != 1)
6532 usage_ref();
6533 if (argc == 1) {
6534 refname = strdup(argv[0]);
6535 if (refname == NULL) {
6536 error = got_error_from_errno("strdup");
6537 goto done;
6540 } else {
6541 if (argc != 1)
6542 usage_ref();
6543 refname = strdup(argv[0]);
6544 if (refname == NULL) {
6545 error = got_error_from_errno("strdup");
6546 goto done;
6550 if (refname)
6551 got_path_strip_trailing_slashes(refname);
6553 #ifndef PROFILE
6554 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
6555 "sendfd unveil", NULL) == -1)
6556 err(1, "pledge");
6557 #endif
6558 cwd = getcwd(NULL, 0);
6559 if (cwd == NULL) {
6560 error = got_error_from_errno("getcwd");
6561 goto done;
6564 error = got_repo_pack_fds_open(&pack_fds);
6565 if (error != NULL)
6566 goto done;
6568 if (repo_path == NULL) {
6569 error = got_worktree_open(&worktree, cwd);
6570 if (error && error->code != GOT_ERR_NOT_WORKTREE)
6571 goto done;
6572 else
6573 error = NULL;
6574 if (worktree) {
6575 repo_path =
6576 strdup(got_worktree_get_repo_path(worktree));
6577 if (repo_path == NULL)
6578 error = got_error_from_errno("strdup");
6579 if (error)
6580 goto done;
6581 } else {
6582 repo_path = strdup(cwd);
6583 if (repo_path == NULL) {
6584 error = got_error_from_errno("strdup");
6585 goto done;
6590 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
6591 if (error != NULL)
6592 goto done;
6594 #ifndef PROFILE
6595 if (do_list) {
6596 /* Remove "cpath" promise. */
6597 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
6598 NULL) == -1)
6599 err(1, "pledge");
6601 #endif
6603 error = apply_unveil(got_repo_get_path(repo), do_list,
6604 worktree ? got_worktree_get_root_path(worktree) : NULL);
6605 if (error)
6606 goto done;
6608 if (do_list)
6609 error = list_refs(repo, refname, sort_by_time);
6610 else if (do_delete)
6611 error = delete_ref_by_name(repo, refname);
6612 else if (symref_target)
6613 error = add_symref(repo, refname, symref_target);
6614 else {
6615 if (obj_arg == NULL)
6616 usage_ref();
6617 error = add_ref(repo, refname, obj_arg);
6619 done:
6620 free(refname);
6621 if (repo) {
6622 const struct got_error *close_err = got_repo_close(repo);
6623 if (error == NULL)
6624 error = close_err;
6626 if (worktree)
6627 got_worktree_close(worktree);
6628 if (pack_fds) {
6629 const struct got_error *pack_err =
6630 got_repo_pack_fds_close(pack_fds);
6631 if (error == NULL)
6632 error = pack_err;
6634 free(cwd);
6635 free(repo_path);
6636 return error;
6639 __dead static void
6640 usage_branch(void)
6642 fprintf(stderr, "usage: %s branch [-lnt] [-c commit] [-d name] "
6643 "[-r repository-path] [name]\n", getprogname());
6644 exit(1);
6647 static const struct got_error *
6648 list_branch(struct got_repository *repo, struct got_worktree *worktree,
6649 struct got_reference *ref)
6651 const struct got_error *err = NULL;
6652 const char *refname, *marker = " ";
6653 char *refstr;
6655 refname = got_ref_get_name(ref);
6656 if (worktree && strcmp(refname,
6657 got_worktree_get_head_ref_name(worktree)) == 0) {
6658 struct got_object_id *id = NULL;
6660 err = got_ref_resolve(&id, repo, ref);
6661 if (err)
6662 return err;
6663 if (got_object_id_cmp(id,
6664 got_worktree_get_base_commit_id(worktree)) == 0)
6665 marker = "* ";
6666 else
6667 marker = "~ ";
6668 free(id);
6671 if (strncmp(refname, "refs/heads/", 11) == 0)
6672 refname += 11;
6673 if (strncmp(refname, "refs/got/worktree/", 18) == 0)
6674 refname += 18;
6675 if (strncmp(refname, "refs/remotes/", 13) == 0)
6676 refname += 13;
6678 refstr = got_ref_to_str(ref);
6679 if (refstr == NULL)
6680 return got_error_from_errno("got_ref_to_str");
6682 printf("%s%s: %s\n", marker, refname, refstr);
6683 free(refstr);
6684 return NULL;
6687 static const struct got_error *
6688 show_current_branch(struct got_repository *repo, struct got_worktree *worktree)
6690 const char *refname;
6692 if (worktree == NULL)
6693 return got_error(GOT_ERR_NOT_WORKTREE);
6695 refname = got_worktree_get_head_ref_name(worktree);
6697 if (strncmp(refname, "refs/heads/", 11) == 0)
6698 refname += 11;
6699 if (strncmp(refname, "refs/got/worktree/", 18) == 0)
6700 refname += 18;
6702 printf("%s\n", refname);
6704 return NULL;
6707 static const struct got_error *
6708 list_branches(struct got_repository *repo, struct got_worktree *worktree,
6709 int sort_by_time)
6711 static const struct got_error *err = NULL;
6712 struct got_reflist_head refs;
6713 struct got_reflist_entry *re;
6714 struct got_reference *temp_ref = NULL;
6715 int rebase_in_progress, histedit_in_progress;
6717 TAILQ_INIT(&refs);
6719 if (worktree) {
6720 err = got_worktree_rebase_in_progress(&rebase_in_progress,
6721 worktree);
6722 if (err)
6723 return err;
6725 err = got_worktree_histedit_in_progress(&histedit_in_progress,
6726 worktree);
6727 if (err)
6728 return err;
6730 if (rebase_in_progress || histedit_in_progress) {
6731 err = got_ref_open(&temp_ref, repo,
6732 got_worktree_get_head_ref_name(worktree), 0);
6733 if (err)
6734 return err;
6735 list_branch(repo, worktree, temp_ref);
6736 got_ref_close(temp_ref);
6740 err = got_ref_list(&refs, repo, "refs/heads", sort_by_time ?
6741 got_ref_cmp_by_commit_timestamp_descending : got_ref_cmp_by_name,
6742 repo);
6743 if (err)
6744 return err;
6746 TAILQ_FOREACH(re, &refs, entry)
6747 list_branch(repo, worktree, re->ref);
6749 got_ref_list_free(&refs);
6751 err = got_ref_list(&refs, repo, "refs/remotes", sort_by_time ?
6752 got_ref_cmp_by_commit_timestamp_descending : got_ref_cmp_by_name,
6753 repo);
6754 if (err)
6755 return err;
6757 TAILQ_FOREACH(re, &refs, entry)
6758 list_branch(repo, worktree, re->ref);
6760 got_ref_list_free(&refs);
6762 return NULL;
6765 static const struct got_error *
6766 delete_branch(struct got_repository *repo, struct got_worktree *worktree,
6767 const char *branch_name)
6769 const struct got_error *err = NULL;
6770 struct got_reference *ref = NULL;
6771 char *refname, *remote_refname = NULL;
6773 if (strncmp(branch_name, "refs/", 5) == 0)
6774 branch_name += 5;
6775 if (strncmp(branch_name, "heads/", 6) == 0)
6776 branch_name += 6;
6777 else if (strncmp(branch_name, "remotes/", 8) == 0)
6778 branch_name += 8;
6780 if (asprintf(&refname, "refs/heads/%s", branch_name) == -1)
6781 return got_error_from_errno("asprintf");
6783 if (asprintf(&remote_refname, "refs/remotes/%s",
6784 branch_name) == -1) {
6785 err = got_error_from_errno("asprintf");
6786 goto done;
6789 err = got_ref_open(&ref, repo, refname, 0);
6790 if (err) {
6791 const struct got_error *err2;
6792 if (err->code != GOT_ERR_NOT_REF)
6793 goto done;
6795 * Keep 'err' intact such that if neither branch exists
6796 * we report "refs/heads" rather than "refs/remotes" in
6797 * our error message.
6799 err2 = got_ref_open(&ref, repo, remote_refname, 0);
6800 if (err2)
6801 goto done;
6802 err = NULL;
6805 if (worktree &&
6806 strcmp(got_worktree_get_head_ref_name(worktree),
6807 got_ref_get_name(ref)) == 0) {
6808 err = got_error_msg(GOT_ERR_SAME_BRANCH,
6809 "will not delete this work tree's current branch");
6810 goto done;
6813 err = delete_ref(repo, ref);
6814 done:
6815 if (ref)
6816 got_ref_close(ref);
6817 free(refname);
6818 free(remote_refname);
6819 return err;
6822 static const struct got_error *
6823 add_branch(struct got_repository *repo, const char *branch_name,
6824 struct got_object_id *base_commit_id)
6826 const struct got_error *err = NULL;
6827 struct got_reference *ref = NULL;
6828 char *refname = NULL;
6831 * Don't let the user create a branch name with a leading '-'.
6832 * While technically a valid reference name, this case is usually
6833 * an unintended typo.
6835 if (branch_name[0] == '-')
6836 return got_error_path(branch_name, GOT_ERR_REF_NAME_MINUS);
6838 if (strncmp(branch_name, "refs/heads/", 11) == 0)
6839 branch_name += 11;
6841 if (asprintf(&refname, "refs/heads/%s", branch_name) == -1) {
6842 err = got_error_from_errno("asprintf");
6843 goto done;
6846 err = got_ref_open(&ref, repo, refname, 0);
6847 if (err == NULL) {
6848 err = got_error(GOT_ERR_BRANCH_EXISTS);
6849 goto done;
6850 } else if (err->code != GOT_ERR_NOT_REF)
6851 goto done;
6853 err = got_ref_alloc(&ref, refname, base_commit_id);
6854 if (err)
6855 goto done;
6857 err = got_ref_write(ref, repo);
6858 done:
6859 if (ref)
6860 got_ref_close(ref);
6861 free(refname);
6862 return err;
6865 static const struct got_error *
6866 cmd_branch(int argc, char *argv[])
6868 const struct got_error *error = NULL;
6869 struct got_repository *repo = NULL;
6870 struct got_worktree *worktree = NULL;
6871 char *cwd = NULL, *repo_path = NULL;
6872 int ch, do_list = 0, do_show = 0, do_update = 1, sort_by_time = 0;
6873 const char *delref = NULL, *commit_id_arg = NULL;
6874 struct got_reference *ref = NULL;
6875 struct got_pathlist_head paths;
6876 struct got_object_id *commit_id = NULL;
6877 char *commit_id_str = NULL;
6878 int *pack_fds = NULL;
6880 TAILQ_INIT(&paths);
6882 while ((ch = getopt(argc, argv, "c:d:lnr:t")) != -1) {
6883 switch (ch) {
6884 case 'c':
6885 commit_id_arg = optarg;
6886 break;
6887 case 'd':
6888 delref = optarg;
6889 break;
6890 case 'l':
6891 do_list = 1;
6892 break;
6893 case 'n':
6894 do_update = 0;
6895 break;
6896 case 'r':
6897 repo_path = realpath(optarg, NULL);
6898 if (repo_path == NULL)
6899 return got_error_from_errno2("realpath",
6900 optarg);
6901 got_path_strip_trailing_slashes(repo_path);
6902 break;
6903 case 't':
6904 sort_by_time = 1;
6905 break;
6906 default:
6907 usage_branch();
6908 /* NOTREACHED */
6912 if (do_list && delref)
6913 option_conflict('l', 'd');
6914 if (sort_by_time && !do_list)
6915 errx(1, "-t option requires -l option");
6917 argc -= optind;
6918 argv += optind;
6920 if (!do_list && !delref && argc == 0)
6921 do_show = 1;
6923 if ((do_list || delref || do_show) && commit_id_arg != NULL)
6924 errx(1, "-c option can only be used when creating a branch");
6926 if (do_list || delref) {
6927 if (argc > 0)
6928 usage_branch();
6929 } else if (!do_show && argc != 1)
6930 usage_branch();
6932 #ifndef PROFILE
6933 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
6934 "sendfd unveil", NULL) == -1)
6935 err(1, "pledge");
6936 #endif
6937 cwd = getcwd(NULL, 0);
6938 if (cwd == NULL) {
6939 error = got_error_from_errno("getcwd");
6940 goto done;
6943 error = got_repo_pack_fds_open(&pack_fds);
6944 if (error != NULL)
6945 goto done;
6947 if (repo_path == NULL) {
6948 error = got_worktree_open(&worktree, cwd);
6949 if (error && error->code != GOT_ERR_NOT_WORKTREE)
6950 goto done;
6951 else
6952 error = NULL;
6953 if (worktree) {
6954 repo_path =
6955 strdup(got_worktree_get_repo_path(worktree));
6956 if (repo_path == NULL)
6957 error = got_error_from_errno("strdup");
6958 if (error)
6959 goto done;
6960 } else {
6961 repo_path = strdup(cwd);
6962 if (repo_path == NULL) {
6963 error = got_error_from_errno("strdup");
6964 goto done;
6969 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
6970 if (error != NULL)
6971 goto done;
6973 #ifndef PROFILE
6974 if (do_list || do_show) {
6975 /* Remove "cpath" promise. */
6976 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
6977 NULL) == -1)
6978 err(1, "pledge");
6980 #endif
6982 error = apply_unveil(got_repo_get_path(repo), do_list,
6983 worktree ? got_worktree_get_root_path(worktree) : NULL);
6984 if (error)
6985 goto done;
6987 if (do_show)
6988 error = show_current_branch(repo, worktree);
6989 else if (do_list)
6990 error = list_branches(repo, worktree, sort_by_time);
6991 else if (delref)
6992 error = delete_branch(repo, worktree, delref);
6993 else {
6994 struct got_reflist_head refs;
6995 TAILQ_INIT(&refs);
6996 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
6997 NULL);
6998 if (error)
6999 goto done;
7000 if (commit_id_arg == NULL)
7001 commit_id_arg = worktree ?
7002 got_worktree_get_head_ref_name(worktree) :
7003 GOT_REF_HEAD;
7004 error = got_repo_match_object_id(&commit_id, NULL,
7005 commit_id_arg, GOT_OBJ_TYPE_COMMIT, &refs, repo);
7006 got_ref_list_free(&refs);
7007 if (error)
7008 goto done;
7009 error = add_branch(repo, argv[0], commit_id);
7010 if (error)
7011 goto done;
7012 if (worktree && do_update) {
7013 struct got_update_progress_arg upa;
7014 char *branch_refname = NULL;
7016 error = got_object_id_str(&commit_id_str, commit_id);
7017 if (error)
7018 goto done;
7019 error = get_worktree_paths_from_argv(&paths, 0, NULL,
7020 worktree);
7021 if (error)
7022 goto done;
7023 if (asprintf(&branch_refname, "refs/heads/%s", argv[0])
7024 == -1) {
7025 error = got_error_from_errno("asprintf");
7026 goto done;
7028 error = got_ref_open(&ref, repo, branch_refname, 0);
7029 free(branch_refname);
7030 if (error)
7031 goto done;
7032 error = switch_head_ref(ref, commit_id, worktree,
7033 repo);
7034 if (error)
7035 goto done;
7036 error = got_worktree_set_base_commit_id(worktree, repo,
7037 commit_id);
7038 if (error)
7039 goto done;
7040 memset(&upa, 0, sizeof(upa));
7041 error = got_worktree_checkout_files(worktree, &paths,
7042 repo, update_progress, &upa, check_cancelled,
7043 NULL);
7044 if (error)
7045 goto done;
7046 if (upa.did_something) {
7047 printf("Updated to %s: %s\n",
7048 got_worktree_get_head_ref_name(worktree),
7049 commit_id_str);
7051 print_update_progress_stats(&upa);
7054 done:
7055 if (ref)
7056 got_ref_close(ref);
7057 if (repo) {
7058 const struct got_error *close_err = got_repo_close(repo);
7059 if (error == NULL)
7060 error = close_err;
7062 if (worktree)
7063 got_worktree_close(worktree);
7064 if (pack_fds) {
7065 const struct got_error *pack_err =
7066 got_repo_pack_fds_close(pack_fds);
7067 if (error == NULL)
7068 error = pack_err;
7070 free(cwd);
7071 free(repo_path);
7072 free(commit_id);
7073 free(commit_id_str);
7074 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
7075 return error;
7079 __dead static void
7080 usage_tag(void)
7082 fprintf(stderr, "usage: %s tag [-lVv] [-c commit] [-m message] "
7083 "[-r repository-path] [-s signer-id] name\n", getprogname());
7084 exit(1);
7087 #if 0
7088 static const struct got_error *
7089 sort_tags(struct got_reflist_head *sorted, struct got_reflist_head *tags)
7091 const struct got_error *err = NULL;
7092 struct got_reflist_entry *re, *se, *new;
7093 struct got_object_id *re_id, *se_id;
7094 struct got_tag_object *re_tag, *se_tag;
7095 time_t re_time, se_time;
7097 STAILQ_FOREACH(re, tags, entry) {
7098 se = STAILQ_FIRST(sorted);
7099 if (se == NULL) {
7100 err = got_reflist_entry_dup(&new, re);
7101 if (err)
7102 return err;
7103 STAILQ_INSERT_HEAD(sorted, new, entry);
7104 continue;
7105 } else {
7106 err = got_ref_resolve(&re_id, repo, re->ref);
7107 if (err)
7108 break;
7109 err = got_object_open_as_tag(&re_tag, repo, re_id);
7110 free(re_id);
7111 if (err)
7112 break;
7113 re_time = got_object_tag_get_tagger_time(re_tag);
7114 got_object_tag_close(re_tag);
7117 while (se) {
7118 err = got_ref_resolve(&se_id, repo, re->ref);
7119 if (err)
7120 break;
7121 err = got_object_open_as_tag(&se_tag, repo, se_id);
7122 free(se_id);
7123 if (err)
7124 break;
7125 se_time = got_object_tag_get_tagger_time(se_tag);
7126 got_object_tag_close(se_tag);
7128 if (se_time > re_time) {
7129 err = got_reflist_entry_dup(&new, re);
7130 if (err)
7131 return err;
7132 STAILQ_INSERT_AFTER(sorted, se, new, entry);
7133 break;
7135 se = STAILQ_NEXT(se, entry);
7136 continue;
7139 done:
7140 return err;
7142 #endif
7144 static const struct got_error *
7145 get_tag_refname(char **refname, const char *tag_name)
7147 const struct got_error *err;
7149 if (strncmp("refs/tags/", tag_name, 10) == 0) {
7150 *refname = strdup(tag_name);
7151 if (*refname == NULL)
7152 return got_error_from_errno("strdup");
7153 } else if (asprintf(refname, "refs/tags/%s", tag_name) == -1) {
7154 err = got_error_from_errno("asprintf");
7155 *refname = NULL;
7156 return err;
7159 return NULL;
7162 static const struct got_error *
7163 list_tags(struct got_repository *repo, const char *tag_name, int verify_tags,
7164 const char *allowed_signers, const char *revoked_signers, int verbosity)
7166 static const struct got_error *err = NULL;
7167 struct got_reflist_head refs;
7168 struct got_reflist_entry *re;
7169 char *wanted_refname = NULL;
7170 int bad_sigs = 0;
7172 TAILQ_INIT(&refs);
7174 err = got_ref_list(&refs, repo, "refs/tags", got_ref_cmp_tags, repo);
7175 if (err)
7176 return err;
7178 if (tag_name) {
7179 struct got_reference *ref;
7180 err = get_tag_refname(&wanted_refname, tag_name);
7181 if (err)
7182 goto done;
7183 /* Wanted tag reference should exist. */
7184 err = got_ref_open(&ref, repo, wanted_refname, 0);
7185 if (err)
7186 goto done;
7187 got_ref_close(ref);
7190 TAILQ_FOREACH(re, &refs, entry) {
7191 const char *refname;
7192 char *refstr, *tagmsg0, *tagmsg, *line, *id_str, *datestr;
7193 char datebuf[26];
7194 const char *tagger, *ssh_sig = NULL;
7195 char *sig_msg = NULL;
7196 time_t tagger_time;
7197 struct got_object_id *id;
7198 struct got_tag_object *tag;
7199 struct got_commit_object *commit = NULL;
7201 refname = got_ref_get_name(re->ref);
7202 if (strncmp(refname, "refs/tags/", 10) != 0 ||
7203 (wanted_refname && strcmp(refname, wanted_refname) != 0))
7204 continue;
7205 refname += 10;
7206 refstr = got_ref_to_str(re->ref);
7207 if (refstr == NULL) {
7208 err = got_error_from_errno("got_ref_to_str");
7209 break;
7212 err = got_ref_resolve(&id, repo, re->ref);
7213 if (err)
7214 break;
7215 err = got_object_open_as_tag(&tag, repo, id);
7216 if (err) {
7217 if (err->code != GOT_ERR_OBJ_TYPE) {
7218 free(id);
7219 break;
7221 /* "lightweight" tag */
7222 err = got_object_open_as_commit(&commit, repo, id);
7223 if (err) {
7224 free(id);
7225 break;
7227 tagger = got_object_commit_get_committer(commit);
7228 tagger_time =
7229 got_object_commit_get_committer_time(commit);
7230 err = got_object_id_str(&id_str, id);
7231 free(id);
7232 if (err)
7233 break;
7234 } else {
7235 free(id);
7236 tagger = got_object_tag_get_tagger(tag);
7237 tagger_time = got_object_tag_get_tagger_time(tag);
7238 err = got_object_id_str(&id_str,
7239 got_object_tag_get_object_id(tag));
7240 if (err)
7241 break;
7244 if (tag && verify_tags) {
7245 ssh_sig = got_sigs_get_tagmsg_ssh_signature(
7246 got_object_tag_get_message(tag));
7247 if (ssh_sig && allowed_signers == NULL) {
7248 err = got_error_msg(
7249 GOT_ERR_VERIFY_TAG_SIGNATURE,
7250 "SSH signature verification requires "
7251 "setting allowed_signers in "
7252 "got.conf(5)");
7253 break;
7257 printf("%stag %s %s\n", GOT_COMMIT_SEP_STR, refname, refstr);
7258 free(refstr);
7259 printf("from: %s\n", tagger);
7260 datestr = get_datestr(&tagger_time, datebuf);
7261 if (datestr)
7262 printf("date: %s UTC\n", datestr);
7263 if (commit)
7264 printf("object: %s %s\n", GOT_OBJ_LABEL_COMMIT, id_str);
7265 else {
7266 switch (got_object_tag_get_object_type(tag)) {
7267 case GOT_OBJ_TYPE_BLOB:
7268 printf("object: %s %s\n", GOT_OBJ_LABEL_BLOB,
7269 id_str);
7270 break;
7271 case GOT_OBJ_TYPE_TREE:
7272 printf("object: %s %s\n", GOT_OBJ_LABEL_TREE,
7273 id_str);
7274 break;
7275 case GOT_OBJ_TYPE_COMMIT:
7276 printf("object: %s %s\n", GOT_OBJ_LABEL_COMMIT,
7277 id_str);
7278 break;
7279 case GOT_OBJ_TYPE_TAG:
7280 printf("object: %s %s\n", GOT_OBJ_LABEL_TAG,
7281 id_str);
7282 break;
7283 default:
7284 break;
7287 free(id_str);
7289 if (ssh_sig) {
7290 err = got_sigs_verify_tag_ssh(&sig_msg, tag, ssh_sig,
7291 allowed_signers, revoked_signers, verbosity);
7292 if (err && err->code == GOT_ERR_BAD_TAG_SIGNATURE)
7293 bad_sigs = 1;
7294 else if (err)
7295 break;
7296 printf("signature: %s", sig_msg);
7297 free(sig_msg);
7298 sig_msg = NULL;
7301 if (commit) {
7302 err = got_object_commit_get_logmsg(&tagmsg0, commit);
7303 if (err)
7304 break;
7305 got_object_commit_close(commit);
7306 } else {
7307 tagmsg0 = strdup(got_object_tag_get_message(tag));
7308 got_object_tag_close(tag);
7309 if (tagmsg0 == NULL) {
7310 err = got_error_from_errno("strdup");
7311 break;
7315 tagmsg = tagmsg0;
7316 do {
7317 line = strsep(&tagmsg, "\n");
7318 if (line)
7319 printf(" %s\n", line);
7320 } while (line);
7321 free(tagmsg0);
7323 done:
7324 got_ref_list_free(&refs);
7325 free(wanted_refname);
7327 if (err == NULL && bad_sigs)
7328 err = got_error(GOT_ERR_BAD_TAG_SIGNATURE);
7329 return err;
7332 static const struct got_error *
7333 get_tag_message(char **tagmsg, char **tagmsg_path, const char *commit_id_str,
7334 const char *tag_name, const char *repo_path)
7336 const struct got_error *err = NULL;
7337 char *template = NULL, *initial_content = NULL;
7338 char *editor = NULL;
7339 int initial_content_len;
7340 int fd = -1;
7342 if (asprintf(&template, GOT_TMPDIR_STR "/got-tagmsg") == -1) {
7343 err = got_error_from_errno("asprintf");
7344 goto done;
7347 initial_content_len = asprintf(&initial_content,
7348 "\n# tagging commit %s as %s\n",
7349 commit_id_str, tag_name);
7350 if (initial_content_len == -1) {
7351 err = got_error_from_errno("asprintf");
7352 goto done;
7355 err = got_opentemp_named_fd(tagmsg_path, &fd, template, "");
7356 if (err)
7357 goto done;
7359 if (write(fd, initial_content, initial_content_len) == -1) {
7360 err = got_error_from_errno2("write", *tagmsg_path);
7361 goto done;
7364 err = get_editor(&editor);
7365 if (err)
7366 goto done;
7367 err = edit_logmsg(tagmsg, editor, *tagmsg_path, initial_content,
7368 initial_content_len, 1);
7369 done:
7370 free(initial_content);
7371 free(template);
7372 free(editor);
7374 if (fd != -1 && close(fd) == -1 && err == NULL)
7375 err = got_error_from_errno2("close", *tagmsg_path);
7377 if (err) {
7378 free(*tagmsg);
7379 *tagmsg = NULL;
7381 return err;
7384 static const struct got_error *
7385 add_tag(struct got_repository *repo, const char *tagger,
7386 const char *tag_name, const char *commit_arg, const char *tagmsg_arg,
7387 const char *signer_id, int verbosity)
7389 const struct got_error *err = NULL;
7390 struct got_object_id *commit_id = NULL, *tag_id = NULL;
7391 char *label = NULL, *commit_id_str = NULL;
7392 struct got_reference *ref = NULL;
7393 char *refname = NULL, *tagmsg = NULL;
7394 char *tagmsg_path = NULL, *tag_id_str = NULL;
7395 int preserve_tagmsg = 0;
7396 struct got_reflist_head refs;
7398 TAILQ_INIT(&refs);
7401 * Don't let the user create a tag name with a leading '-'.
7402 * While technically a valid reference name, this case is usually
7403 * an unintended typo.
7405 if (tag_name[0] == '-')
7406 return got_error_path(tag_name, GOT_ERR_REF_NAME_MINUS);
7408 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
7409 if (err)
7410 goto done;
7412 err = got_repo_match_object_id(&commit_id, &label, commit_arg,
7413 GOT_OBJ_TYPE_COMMIT, &refs, repo);
7414 if (err)
7415 goto done;
7417 err = got_object_id_str(&commit_id_str, commit_id);
7418 if (err)
7419 goto done;
7421 err = get_tag_refname(&refname, tag_name);
7422 if (err)
7423 goto done;
7424 if (strncmp("refs/tags/", tag_name, 10) == 0)
7425 tag_name += 10;
7427 err = got_ref_open(&ref, repo, refname, 0);
7428 if (err == NULL) {
7429 err = got_error(GOT_ERR_TAG_EXISTS);
7430 goto done;
7431 } else if (err->code != GOT_ERR_NOT_REF)
7432 goto done;
7434 if (tagmsg_arg == NULL) {
7435 err = get_tag_message(&tagmsg, &tagmsg_path, commit_id_str,
7436 tag_name, got_repo_get_path(repo));
7437 if (err) {
7438 if (err->code != GOT_ERR_COMMIT_MSG_EMPTY &&
7439 tagmsg_path != NULL)
7440 preserve_tagmsg = 1;
7441 goto done;
7443 /* Editor is done; we can now apply unveil(2) */
7444 err = got_sigs_apply_unveil();
7445 if (err)
7446 goto done;
7447 err = apply_unveil(got_repo_get_path(repo), 0, NULL);
7448 if (err)
7449 goto done;
7452 err = got_object_tag_create(&tag_id, tag_name, commit_id,
7453 tagger, time(NULL), tagmsg ? tagmsg : tagmsg_arg, signer_id, repo,
7454 verbosity);
7455 if (err) {
7456 if (tagmsg_path)
7457 preserve_tagmsg = 1;
7458 goto done;
7461 err = got_ref_alloc(&ref, refname, tag_id);
7462 if (err) {
7463 if (tagmsg_path)
7464 preserve_tagmsg = 1;
7465 goto done;
7468 err = got_ref_write(ref, repo);
7469 if (err) {
7470 if (tagmsg_path)
7471 preserve_tagmsg = 1;
7472 goto done;
7475 err = got_object_id_str(&tag_id_str, tag_id);
7476 if (err) {
7477 if (tagmsg_path)
7478 preserve_tagmsg = 1;
7479 goto done;
7481 printf("Created tag %s\n", tag_id_str);
7482 done:
7483 if (preserve_tagmsg) {
7484 fprintf(stderr, "%s: tag message preserved in %s\n",
7485 getprogname(), tagmsg_path);
7486 } else if (tagmsg_path && unlink(tagmsg_path) == -1 && err == NULL)
7487 err = got_error_from_errno2("unlink", tagmsg_path);
7488 free(tag_id_str);
7489 if (ref)
7490 got_ref_close(ref);
7491 free(commit_id);
7492 free(commit_id_str);
7493 free(refname);
7494 free(tagmsg);
7495 free(tagmsg_path);
7496 got_ref_list_free(&refs);
7497 return err;
7500 static const struct got_error *
7501 cmd_tag(int argc, char *argv[])
7503 const struct got_error *error = NULL;
7504 struct got_repository *repo = NULL;
7505 struct got_worktree *worktree = NULL;
7506 char *cwd = NULL, *repo_path = NULL, *commit_id_str = NULL;
7507 char *gitconfig_path = NULL, *tagger = NULL;
7508 char *allowed_signers = NULL, *revoked_signers = NULL;
7509 const char *signer_id = NULL;
7510 const char *tag_name = NULL, *commit_id_arg = NULL, *tagmsg = NULL;
7511 int ch, do_list = 0, verify_tags = 0, verbosity = 0;
7512 int *pack_fds = NULL;
7514 while ((ch = getopt(argc, argv, "c:lm:r:s:Vv")) != -1) {
7515 switch (ch) {
7516 case 'c':
7517 commit_id_arg = optarg;
7518 break;
7519 case 'l':
7520 do_list = 1;
7521 break;
7522 case 'm':
7523 tagmsg = optarg;
7524 break;
7525 case 'r':
7526 repo_path = realpath(optarg, NULL);
7527 if (repo_path == NULL) {
7528 error = got_error_from_errno2("realpath",
7529 optarg);
7530 goto done;
7532 got_path_strip_trailing_slashes(repo_path);
7533 break;
7534 case 's':
7535 signer_id = optarg;
7536 break;
7537 case 'V':
7538 verify_tags = 1;
7539 break;
7540 case 'v':
7541 if (verbosity < 0)
7542 verbosity = 0;
7543 else if (verbosity < 3)
7544 verbosity++;
7545 break;
7546 default:
7547 usage_tag();
7548 /* NOTREACHED */
7552 argc -= optind;
7553 argv += optind;
7555 if (do_list || verify_tags) {
7556 if (commit_id_arg != NULL)
7557 errx(1,
7558 "-c option can only be used when creating a tag");
7559 if (tagmsg) {
7560 if (do_list)
7561 option_conflict('l', 'm');
7562 else
7563 option_conflict('V', 'm');
7565 if (signer_id) {
7566 if (do_list)
7567 option_conflict('l', 's');
7568 else
7569 option_conflict('V', 's');
7571 if (argc > 1)
7572 usage_tag();
7573 } else if (argc != 1)
7574 usage_tag();
7576 if (argc == 1)
7577 tag_name = argv[0];
7579 #ifndef PROFILE
7580 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
7581 "sendfd unveil", NULL) == -1)
7582 err(1, "pledge");
7583 #endif
7584 cwd = getcwd(NULL, 0);
7585 if (cwd == NULL) {
7586 error = got_error_from_errno("getcwd");
7587 goto done;
7590 error = got_repo_pack_fds_open(&pack_fds);
7591 if (error != NULL)
7592 goto done;
7594 if (repo_path == NULL) {
7595 error = got_worktree_open(&worktree, cwd);
7596 if (error && error->code != GOT_ERR_NOT_WORKTREE)
7597 goto done;
7598 else
7599 error = NULL;
7600 if (worktree) {
7601 repo_path =
7602 strdup(got_worktree_get_repo_path(worktree));
7603 if (repo_path == NULL)
7604 error = got_error_from_errno("strdup");
7605 if (error)
7606 goto done;
7607 } else {
7608 repo_path = strdup(cwd);
7609 if (repo_path == NULL) {
7610 error = got_error_from_errno("strdup");
7611 goto done;
7616 if (do_list || verify_tags) {
7617 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
7618 if (error != NULL)
7619 goto done;
7620 error = get_allowed_signers(&allowed_signers, repo, worktree);
7621 if (error)
7622 goto done;
7623 error = get_revoked_signers(&revoked_signers, repo, worktree);
7624 if (error)
7625 goto done;
7626 if (worktree) {
7627 /* Release work tree lock. */
7628 got_worktree_close(worktree);
7629 worktree = NULL;
7633 * Remove "cpath" promise unless needed for signature tmpfile
7634 * creation.
7636 if (verify_tags)
7637 got_sigs_apply_unveil();
7638 else {
7639 #ifndef PROFILE
7640 if (pledge("stdio rpath wpath flock proc exec sendfd "
7641 "unveil", NULL) == -1)
7642 err(1, "pledge");
7643 #endif
7645 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
7646 if (error)
7647 goto done;
7648 error = list_tags(repo, tag_name, verify_tags, allowed_signers,
7649 revoked_signers, verbosity);
7650 } else {
7651 error = get_gitconfig_path(&gitconfig_path);
7652 if (error)
7653 goto done;
7654 error = got_repo_open(&repo, repo_path, gitconfig_path,
7655 pack_fds);
7656 if (error != NULL)
7657 goto done;
7659 error = get_author(&tagger, repo, worktree);
7660 if (error)
7661 goto done;
7662 if (signer_id == NULL)
7663 signer_id = get_signer_id(repo, worktree);
7665 if (tagmsg) {
7666 if (signer_id) {
7667 error = got_sigs_apply_unveil();
7668 if (error)
7669 goto done;
7671 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
7672 if (error)
7673 goto done;
7676 if (commit_id_arg == NULL) {
7677 struct got_reference *head_ref;
7678 struct got_object_id *commit_id;
7679 error = got_ref_open(&head_ref, repo,
7680 worktree ? got_worktree_get_head_ref_name(worktree)
7681 : GOT_REF_HEAD, 0);
7682 if (error)
7683 goto done;
7684 error = got_ref_resolve(&commit_id, repo, head_ref);
7685 got_ref_close(head_ref);
7686 if (error)
7687 goto done;
7688 error = got_object_id_str(&commit_id_str, commit_id);
7689 free(commit_id);
7690 if (error)
7691 goto done;
7694 if (worktree) {
7695 /* Release work tree lock. */
7696 got_worktree_close(worktree);
7697 worktree = NULL;
7700 error = add_tag(repo, tagger, tag_name,
7701 commit_id_str ? commit_id_str : commit_id_arg, tagmsg,
7702 signer_id, verbosity);
7704 done:
7705 if (repo) {
7706 const struct got_error *close_err = got_repo_close(repo);
7707 if (error == NULL)
7708 error = close_err;
7710 if (worktree)
7711 got_worktree_close(worktree);
7712 if (pack_fds) {
7713 const struct got_error *pack_err =
7714 got_repo_pack_fds_close(pack_fds);
7715 if (error == NULL)
7716 error = pack_err;
7718 free(cwd);
7719 free(repo_path);
7720 free(gitconfig_path);
7721 free(commit_id_str);
7722 free(tagger);
7723 free(allowed_signers);
7724 free(revoked_signers);
7725 return error;
7728 __dead static void
7729 usage_add(void)
7731 fprintf(stderr, "usage: %s add [-IR] path ...\n", getprogname());
7732 exit(1);
7735 static const struct got_error *
7736 add_progress(void *arg, unsigned char status, const char *path)
7738 while (path[0] == '/')
7739 path++;
7740 printf("%c %s\n", status, path);
7741 return NULL;
7744 static const struct got_error *
7745 cmd_add(int argc, char *argv[])
7747 const struct got_error *error = NULL;
7748 struct got_repository *repo = NULL;
7749 struct got_worktree *worktree = NULL;
7750 char *cwd = NULL;
7751 struct got_pathlist_head paths;
7752 struct got_pathlist_entry *pe;
7753 int ch, can_recurse = 0, no_ignores = 0;
7754 int *pack_fds = NULL;
7756 TAILQ_INIT(&paths);
7758 while ((ch = getopt(argc, argv, "IR")) != -1) {
7759 switch (ch) {
7760 case 'I':
7761 no_ignores = 1;
7762 break;
7763 case 'R':
7764 can_recurse = 1;
7765 break;
7766 default:
7767 usage_add();
7768 /* NOTREACHED */
7772 argc -= optind;
7773 argv += optind;
7775 #ifndef PROFILE
7776 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
7777 NULL) == -1)
7778 err(1, "pledge");
7779 #endif
7780 if (argc < 1)
7781 usage_add();
7783 cwd = getcwd(NULL, 0);
7784 if (cwd == NULL) {
7785 error = got_error_from_errno("getcwd");
7786 goto done;
7789 error = got_repo_pack_fds_open(&pack_fds);
7790 if (error != NULL)
7791 goto done;
7793 error = got_worktree_open(&worktree, cwd);
7794 if (error) {
7795 if (error->code == GOT_ERR_NOT_WORKTREE)
7796 error = wrap_not_worktree_error(error, "add", cwd);
7797 goto done;
7800 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
7801 NULL, pack_fds);
7802 if (error != NULL)
7803 goto done;
7805 error = apply_unveil(got_repo_get_path(repo), 1,
7806 got_worktree_get_root_path(worktree));
7807 if (error)
7808 goto done;
7810 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
7811 if (error)
7812 goto done;
7814 if (!can_recurse) {
7815 char *ondisk_path;
7816 struct stat sb;
7817 TAILQ_FOREACH(pe, &paths, entry) {
7818 if (asprintf(&ondisk_path, "%s/%s",
7819 got_worktree_get_root_path(worktree),
7820 pe->path) == -1) {
7821 error = got_error_from_errno("asprintf");
7822 goto done;
7824 if (lstat(ondisk_path, &sb) == -1) {
7825 if (errno == ENOENT) {
7826 free(ondisk_path);
7827 continue;
7829 error = got_error_from_errno2("lstat",
7830 ondisk_path);
7831 free(ondisk_path);
7832 goto done;
7834 free(ondisk_path);
7835 if (S_ISDIR(sb.st_mode)) {
7836 error = got_error_msg(GOT_ERR_BAD_PATH,
7837 "adding directories requires -R option");
7838 goto done;
7843 error = got_worktree_schedule_add(worktree, &paths, add_progress,
7844 NULL, repo, no_ignores);
7845 done:
7846 if (repo) {
7847 const struct got_error *close_err = got_repo_close(repo);
7848 if (error == NULL)
7849 error = close_err;
7851 if (worktree)
7852 got_worktree_close(worktree);
7853 if (pack_fds) {
7854 const struct got_error *pack_err =
7855 got_repo_pack_fds_close(pack_fds);
7856 if (error == NULL)
7857 error = pack_err;
7859 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
7860 free(cwd);
7861 return error;
7864 __dead static void
7865 usage_remove(void)
7867 fprintf(stderr, "usage: %s remove [-fkR] [-s status-codes] path ...\n",
7868 getprogname());
7869 exit(1);
7872 static const struct got_error *
7873 print_remove_status(void *arg, unsigned char status,
7874 unsigned char staged_status, const char *path)
7876 while (path[0] == '/')
7877 path++;
7878 if (status == GOT_STATUS_NONEXISTENT)
7879 return NULL;
7880 if (status == staged_status && (status == GOT_STATUS_DELETE))
7881 status = GOT_STATUS_NO_CHANGE;
7882 printf("%c%c %s\n", status, staged_status, path);
7883 return NULL;
7886 static const struct got_error *
7887 cmd_remove(int argc, char *argv[])
7889 const struct got_error *error = NULL;
7890 struct got_worktree *worktree = NULL;
7891 struct got_repository *repo = NULL;
7892 const char *status_codes = NULL;
7893 char *cwd = NULL;
7894 struct got_pathlist_head paths;
7895 struct got_pathlist_entry *pe;
7896 int ch, delete_local_mods = 0, can_recurse = 0, keep_on_disk = 0, i;
7897 int ignore_missing_paths = 0;
7898 int *pack_fds = NULL;
7900 TAILQ_INIT(&paths);
7902 while ((ch = getopt(argc, argv, "fkRs:")) != -1) {
7903 switch (ch) {
7904 case 'f':
7905 delete_local_mods = 1;
7906 ignore_missing_paths = 1;
7907 break;
7908 case 'k':
7909 keep_on_disk = 1;
7910 break;
7911 case 'R':
7912 can_recurse = 1;
7913 break;
7914 case 's':
7915 for (i = 0; i < strlen(optarg); i++) {
7916 switch (optarg[i]) {
7917 case GOT_STATUS_MODIFY:
7918 delete_local_mods = 1;
7919 break;
7920 case GOT_STATUS_MISSING:
7921 ignore_missing_paths = 1;
7922 break;
7923 default:
7924 errx(1, "invalid status code '%c'",
7925 optarg[i]);
7928 status_codes = optarg;
7929 break;
7930 default:
7931 usage_remove();
7932 /* NOTREACHED */
7936 argc -= optind;
7937 argv += optind;
7939 #ifndef PROFILE
7940 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
7941 NULL) == -1)
7942 err(1, "pledge");
7943 #endif
7944 if (argc < 1)
7945 usage_remove();
7947 cwd = getcwd(NULL, 0);
7948 if (cwd == NULL) {
7949 error = got_error_from_errno("getcwd");
7950 goto done;
7953 error = got_repo_pack_fds_open(&pack_fds);
7954 if (error != NULL)
7955 goto done;
7957 error = got_worktree_open(&worktree, cwd);
7958 if (error) {
7959 if (error->code == GOT_ERR_NOT_WORKTREE)
7960 error = wrap_not_worktree_error(error, "remove", cwd);
7961 goto done;
7964 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
7965 NULL, pack_fds);
7966 if (error)
7967 goto done;
7969 error = apply_unveil(got_repo_get_path(repo), 1,
7970 got_worktree_get_root_path(worktree));
7971 if (error)
7972 goto done;
7974 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
7975 if (error)
7976 goto done;
7978 if (!can_recurse) {
7979 char *ondisk_path;
7980 struct stat sb;
7981 TAILQ_FOREACH(pe, &paths, entry) {
7982 if (asprintf(&ondisk_path, "%s/%s",
7983 got_worktree_get_root_path(worktree),
7984 pe->path) == -1) {
7985 error = got_error_from_errno("asprintf");
7986 goto done;
7988 if (lstat(ondisk_path, &sb) == -1) {
7989 if (errno == ENOENT) {
7990 free(ondisk_path);
7991 continue;
7993 error = got_error_from_errno2("lstat",
7994 ondisk_path);
7995 free(ondisk_path);
7996 goto done;
7998 free(ondisk_path);
7999 if (S_ISDIR(sb.st_mode)) {
8000 error = got_error_msg(GOT_ERR_BAD_PATH,
8001 "removing directories requires -R option");
8002 goto done;
8007 error = got_worktree_schedule_delete(worktree, &paths,
8008 delete_local_mods, status_codes, print_remove_status, NULL,
8009 repo, keep_on_disk, ignore_missing_paths);
8010 done:
8011 if (repo) {
8012 const struct got_error *close_err = got_repo_close(repo);
8013 if (error == NULL)
8014 error = close_err;
8016 if (worktree)
8017 got_worktree_close(worktree);
8018 if (pack_fds) {
8019 const struct got_error *pack_err =
8020 got_repo_pack_fds_close(pack_fds);
8021 if (error == NULL)
8022 error = pack_err;
8024 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
8025 free(cwd);
8026 return error;
8029 __dead static void
8030 usage_patch(void)
8032 fprintf(stderr, "usage: %s patch [-nR] [-c commit] [-p strip-count] "
8033 "[patchfile]\n", getprogname());
8034 exit(1);
8037 static const struct got_error *
8038 patch_from_stdin(int *patchfd)
8040 const struct got_error *err = NULL;
8041 ssize_t r;
8042 char buf[BUFSIZ];
8043 sig_t sighup, sigint, sigquit;
8045 *patchfd = got_opentempfd();
8046 if (*patchfd == -1)
8047 return got_error_from_errno("got_opentempfd");
8049 sighup = signal(SIGHUP, SIG_DFL);
8050 sigint = signal(SIGINT, SIG_DFL);
8051 sigquit = signal(SIGQUIT, SIG_DFL);
8053 for (;;) {
8054 r = read(0, buf, sizeof(buf));
8055 if (r == -1) {
8056 err = got_error_from_errno("read");
8057 break;
8059 if (r == 0)
8060 break;
8061 if (write(*patchfd, buf, r) == -1) {
8062 err = got_error_from_errno("write");
8063 break;
8067 signal(SIGHUP, sighup);
8068 signal(SIGINT, sigint);
8069 signal(SIGQUIT, sigquit);
8071 if (err == NULL && lseek(*patchfd, 0, SEEK_SET) == -1)
8072 err = got_error_from_errno("lseek");
8074 if (err != NULL) {
8075 close(*patchfd);
8076 *patchfd = -1;
8079 return err;
8082 static const struct got_error *
8083 patch_progress(void *arg, const char *old, const char *new,
8084 unsigned char status, const struct got_error *error, int old_from,
8085 int old_lines, int new_from, int new_lines, int offset,
8086 int ws_mangled, const struct got_error *hunk_err)
8088 const char *path = new == NULL ? old : new;
8090 while (*path == '/')
8091 path++;
8093 if (status != 0)
8094 printf("%c %s\n", status, path);
8096 if (error != NULL)
8097 fprintf(stderr, "%s: %s\n", getprogname(), error->msg);
8099 if (offset != 0 || hunk_err != NULL || ws_mangled) {
8100 printf("@@ -%d,%d +%d,%d @@ ", old_from,
8101 old_lines, new_from, new_lines);
8102 if (hunk_err != NULL)
8103 printf("%s\n", hunk_err->msg);
8104 else if (offset != 0)
8105 printf("applied with offset %d\n", offset);
8106 else
8107 printf("hunk contains mangled whitespace\n");
8110 return NULL;
8113 static const struct got_error *
8114 cmd_patch(int argc, char *argv[])
8116 const struct got_error *error = NULL, *close_error = NULL;
8117 struct got_worktree *worktree = NULL;
8118 struct got_repository *repo = NULL;
8119 struct got_reflist_head refs;
8120 struct got_object_id *commit_id = NULL;
8121 const char *commit_id_str = NULL;
8122 struct stat sb;
8123 const char *errstr;
8124 char *cwd = NULL;
8125 int ch, nop = 0, strip = -1, reverse = 0;
8126 int patchfd;
8127 int *pack_fds = NULL;
8129 TAILQ_INIT(&refs);
8131 #ifndef PROFILE
8132 if (pledge("stdio rpath wpath cpath fattr proc exec sendfd flock "
8133 "unveil", NULL) == -1)
8134 err(1, "pledge");
8135 #endif
8137 while ((ch = getopt(argc, argv, "c:np:R")) != -1) {
8138 switch (ch) {
8139 case 'c':
8140 commit_id_str = optarg;
8141 break;
8142 case 'n':
8143 nop = 1;
8144 break;
8145 case 'p':
8146 strip = strtonum(optarg, 0, INT_MAX, &errstr);
8147 if (errstr != NULL)
8148 errx(1, "pathname strip count is %s: %s",
8149 errstr, optarg);
8150 break;
8151 case 'R':
8152 reverse = 1;
8153 break;
8154 default:
8155 usage_patch();
8156 /* NOTREACHED */
8160 argc -= optind;
8161 argv += optind;
8163 if (argc == 0) {
8164 error = patch_from_stdin(&patchfd);
8165 if (error)
8166 return error;
8167 } else if (argc == 1) {
8168 patchfd = open(argv[0], O_RDONLY);
8169 if (patchfd == -1) {
8170 error = got_error_from_errno2("open", argv[0]);
8171 return error;
8173 if (fstat(patchfd, &sb) == -1) {
8174 error = got_error_from_errno2("fstat", argv[0]);
8175 goto done;
8177 if (!S_ISREG(sb.st_mode)) {
8178 error = got_error_path(argv[0], GOT_ERR_BAD_FILETYPE);
8179 goto done;
8181 } else
8182 usage_patch();
8184 if ((cwd = getcwd(NULL, 0)) == NULL) {
8185 error = got_error_from_errno("getcwd");
8186 goto done;
8189 error = got_repo_pack_fds_open(&pack_fds);
8190 if (error != NULL)
8191 goto done;
8193 error = got_worktree_open(&worktree, cwd);
8194 if (error != NULL)
8195 goto done;
8197 const char *repo_path = got_worktree_get_repo_path(worktree);
8198 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
8199 if (error != NULL)
8200 goto done;
8202 error = apply_unveil(got_repo_get_path(repo), 0,
8203 got_worktree_get_root_path(worktree));
8204 if (error != NULL)
8205 goto done;
8207 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
8208 if (error)
8209 goto done;
8211 if (commit_id_str != NULL) {
8212 error = got_repo_match_object_id(&commit_id, NULL,
8213 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
8214 if (error)
8215 goto done;
8218 error = got_patch(patchfd, worktree, repo, nop, strip, reverse,
8219 commit_id, &patch_progress, NULL, check_cancelled, NULL);
8221 done:
8222 got_ref_list_free(&refs);
8223 free(commit_id);
8224 if (repo) {
8225 close_error = got_repo_close(repo);
8226 if (error == NULL)
8227 error = close_error;
8229 if (worktree != NULL) {
8230 close_error = got_worktree_close(worktree);
8231 if (error == NULL)
8232 error = close_error;
8234 if (pack_fds) {
8235 const struct got_error *pack_err =
8236 got_repo_pack_fds_close(pack_fds);
8237 if (error == NULL)
8238 error = pack_err;
8240 free(cwd);
8241 return error;
8244 __dead static void
8245 usage_revert(void)
8247 fprintf(stderr, "usage: %s revert [-pR] [-F response-script] path ...\n",
8248 getprogname());
8249 exit(1);
8252 static const struct got_error *
8253 revert_progress(void *arg, unsigned char status, const char *path)
8255 if (status == GOT_STATUS_UNVERSIONED)
8256 return NULL;
8258 while (path[0] == '/')
8259 path++;
8260 printf("%c %s\n", status, path);
8261 return NULL;
8264 struct choose_patch_arg {
8265 FILE *patch_script_file;
8266 const char *action;
8269 static const struct got_error *
8270 show_change(unsigned char status, const char *path, FILE *patch_file, int n,
8271 int nchanges, const char *action)
8273 const struct got_error *err;
8274 char *line = NULL;
8275 size_t linesize = 0;
8276 ssize_t linelen;
8278 switch (status) {
8279 case GOT_STATUS_ADD:
8280 printf("A %s\n%s this addition? [y/n] ", path, action);
8281 break;
8282 case GOT_STATUS_DELETE:
8283 printf("D %s\n%s this deletion? [y/n] ", path, action);
8284 break;
8285 case GOT_STATUS_MODIFY:
8286 if (fseek(patch_file, 0L, SEEK_SET) == -1)
8287 return got_error_from_errno("fseek");
8288 printf(GOT_COMMIT_SEP_STR);
8289 while ((linelen = getline(&line, &linesize, patch_file)) != -1)
8290 printf("%s", line);
8291 if (linelen == -1 && ferror(patch_file)) {
8292 err = got_error_from_errno("getline");
8293 free(line);
8294 return err;
8296 free(line);
8297 printf(GOT_COMMIT_SEP_STR);
8298 printf("M %s (change %d of %d)\n%s this change? [y/n/q] ",
8299 path, n, nchanges, action);
8300 break;
8301 default:
8302 return got_error_path(path, GOT_ERR_FILE_STATUS);
8305 fflush(stdout);
8306 return NULL;
8309 static const struct got_error *
8310 choose_patch(int *choice, void *arg, unsigned char status, const char *path,
8311 FILE *patch_file, int n, int nchanges)
8313 const struct got_error *err = NULL;
8314 char *line = NULL;
8315 size_t linesize = 0;
8316 ssize_t linelen;
8317 int resp = ' ';
8318 struct choose_patch_arg *a = arg;
8320 *choice = GOT_PATCH_CHOICE_NONE;
8322 if (a->patch_script_file) {
8323 char *nl;
8324 err = show_change(status, path, patch_file, n, nchanges,
8325 a->action);
8326 if (err)
8327 return err;
8328 linelen = getline(&line, &linesize, a->patch_script_file);
8329 if (linelen == -1) {
8330 if (ferror(a->patch_script_file))
8331 return got_error_from_errno("getline");
8332 return NULL;
8334 nl = strchr(line, '\n');
8335 if (nl)
8336 *nl = '\0';
8337 if (strcmp(line, "y") == 0) {
8338 *choice = GOT_PATCH_CHOICE_YES;
8339 printf("y\n");
8340 } else if (strcmp(line, "n") == 0) {
8341 *choice = GOT_PATCH_CHOICE_NO;
8342 printf("n\n");
8343 } else if (strcmp(line, "q") == 0 &&
8344 status == GOT_STATUS_MODIFY) {
8345 *choice = GOT_PATCH_CHOICE_QUIT;
8346 printf("q\n");
8347 } else
8348 printf("invalid response '%s'\n", line);
8349 free(line);
8350 return NULL;
8353 while (resp != 'y' && resp != 'n' && resp != 'q') {
8354 err = show_change(status, path, patch_file, n, nchanges,
8355 a->action);
8356 if (err)
8357 return err;
8358 resp = getchar();
8359 if (resp == '\n')
8360 resp = getchar();
8361 if (status == GOT_STATUS_MODIFY) {
8362 if (resp != 'y' && resp != 'n' && resp != 'q') {
8363 printf("invalid response '%c'\n", resp);
8364 resp = ' ';
8366 } else if (resp != 'y' && resp != 'n') {
8367 printf("invalid response '%c'\n", resp);
8368 resp = ' ';
8372 if (resp == 'y')
8373 *choice = GOT_PATCH_CHOICE_YES;
8374 else if (resp == 'n')
8375 *choice = GOT_PATCH_CHOICE_NO;
8376 else if (resp == 'q' && status == GOT_STATUS_MODIFY)
8377 *choice = GOT_PATCH_CHOICE_QUIT;
8379 return NULL;
8382 struct wt_commitable_path_arg {
8383 struct got_pathlist_head *commit_paths;
8384 int *has_changes;
8388 * Shortcut work tree status callback to determine if the set of paths scanned
8389 * has at least one versioned path that is being modified and, if not NULL, is
8390 * in the arg->commit_paths list. Set arg and return GOT_ERR_FILE_MODIFIED as
8391 * soon as a path is passed with a status that satisfies this criteria.
8393 static const struct got_error *
8394 worktree_has_commitable_path(void *arg, unsigned char status,
8395 unsigned char staged_status, const char *path,
8396 struct got_object_id *blob_id, struct got_object_id *staged_blob_id,
8397 struct got_object_id *commit_id, int dirfd, const char *de_name)
8399 struct wt_commitable_path_arg *a = arg;
8401 if (status == staged_status && (status == GOT_STATUS_DELETE))
8402 status = GOT_STATUS_NO_CHANGE;
8404 if (!(status == GOT_STATUS_NO_CHANGE ||
8405 status == GOT_STATUS_UNVERSIONED) ||
8406 staged_status != GOT_STATUS_NO_CHANGE) {
8407 if (a->commit_paths != NULL) {
8408 struct got_pathlist_entry *pe;
8410 TAILQ_FOREACH(pe, a->commit_paths, entry) {
8411 if (strncmp(path, pe->path,
8412 pe->path_len) == 0) {
8413 *a->has_changes = 1;
8414 break;
8417 } else
8418 *a->has_changes = 1;
8420 if (*a->has_changes)
8421 return got_error(GOT_ERR_FILE_MODIFIED);
8424 return NULL;
8428 * Check that the changeset of the commit identified by id is
8429 * comprised of at least one modified path that is being committed.
8431 static const struct got_error *
8432 commit_path_changed_in_worktree(struct wt_commitable_path_arg *wcpa,
8433 struct got_object_id *id, struct got_worktree *worktree,
8434 struct got_repository *repo)
8436 const struct got_error *err;
8437 struct got_pathlist_head paths;
8438 struct got_commit_object *commit = NULL, *pcommit = NULL;
8439 struct got_tree_object *tree = NULL, *ptree = NULL;
8440 struct got_object_qid *pid;
8442 TAILQ_INIT(&paths);
8444 err = got_object_open_as_commit(&commit, repo, id);
8445 if (err)
8446 goto done;
8448 err = got_object_open_as_tree(&tree, repo,
8449 got_object_commit_get_tree_id(commit));
8450 if (err)
8451 goto done;
8453 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
8454 if (pid != NULL) {
8455 err = got_object_open_as_commit(&pcommit, repo, &pid->id);
8456 if (err)
8457 goto done;
8459 err = got_object_open_as_tree(&ptree, repo,
8460 got_object_commit_get_tree_id(pcommit));
8461 if (err)
8462 goto done;
8465 err = got_diff_tree(ptree, tree, NULL, NULL, -1, -1, "", "", repo,
8466 got_diff_tree_collect_changed_paths, &paths, 0);
8467 if (err)
8468 goto done;
8470 err = got_worktree_status(worktree, &paths, repo, 0,
8471 worktree_has_commitable_path, wcpa, check_cancelled, NULL);
8472 if (err && err->code == GOT_ERR_FILE_MODIFIED) {
8474 * At least one changed path in the referenced commit is
8475 * modified in the work tree, that's all we need to know!
8477 err = NULL;
8480 done:
8481 got_pathlist_free(&paths, GOT_PATHLIST_FREE_ALL);
8482 if (commit)
8483 got_object_commit_close(commit);
8484 if (pcommit)
8485 got_object_commit_close(pcommit);
8486 if (tree)
8487 got_object_tree_close(tree);
8488 if (ptree)
8489 got_object_tree_close(ptree);
8490 return err;
8494 * Remove any "logmsg" reference comprised entirely of paths that have
8495 * been reverted in this work tree. If any path in the logmsg ref changeset
8496 * remains in a changed state in the worktree, do not remove the reference.
8498 static const struct got_error *
8499 rm_logmsg_ref(struct got_worktree *worktree, struct got_repository *repo)
8501 const struct got_error *err;
8502 struct got_reflist_head refs;
8503 struct got_reflist_entry *re;
8504 struct got_commit_object *commit = NULL;
8505 struct got_object_id *commit_id = NULL;
8506 struct wt_commitable_path_arg wcpa;
8507 char *uuidstr = NULL;
8509 TAILQ_INIT(&refs);
8511 err = got_worktree_get_uuid(&uuidstr, worktree);
8512 if (err)
8513 goto done;
8515 err = got_ref_list(&refs, repo, "refs/got/worktree",
8516 got_ref_cmp_by_name, repo);
8517 if (err)
8518 goto done;
8520 TAILQ_FOREACH(re, &refs, entry) {
8521 const char *refname;
8522 int has_changes = 0;
8524 refname = got_ref_get_name(re->ref);
8526 if (!strncmp(refname, GOT_WORKTREE_CHERRYPICK_REF_PREFIX,
8527 GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN))
8528 refname += GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN + 1;
8529 else if (!strncmp(refname, GOT_WORKTREE_BACKOUT_REF_PREFIX,
8530 GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN))
8531 refname += GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN + 1;
8532 else
8533 continue;
8535 if (strncmp(refname, uuidstr, GOT_WORKTREE_UUID_STRLEN) == 0)
8536 refname += GOT_WORKTREE_UUID_STRLEN + 1; /* skip '-' */
8537 else
8538 continue;
8540 err = got_repo_match_object_id(&commit_id, NULL, refname,
8541 GOT_OBJ_TYPE_COMMIT, NULL, repo);
8542 if (err)
8543 goto done;
8545 err = got_object_open_as_commit(&commit, repo, commit_id);
8546 if (err)
8547 goto done;
8549 wcpa.commit_paths = NULL;
8550 wcpa.has_changes = &has_changes;
8552 err = commit_path_changed_in_worktree(&wcpa, commit_id,
8553 worktree, repo);
8554 if (err)
8555 goto done;
8557 if (!has_changes) {
8558 err = got_ref_delete(re->ref, repo);
8559 if (err)
8560 goto done;
8563 got_object_commit_close(commit);
8564 commit = NULL;
8565 free(commit_id);
8566 commit_id = NULL;
8569 done:
8570 free(uuidstr);
8571 free(commit_id);
8572 got_ref_list_free(&refs);
8573 if (commit)
8574 got_object_commit_close(commit);
8575 return err;
8578 static const struct got_error *
8579 cmd_revert(int argc, char *argv[])
8581 const struct got_error *error = NULL;
8582 struct got_worktree *worktree = NULL;
8583 struct got_repository *repo = NULL;
8584 char *cwd = NULL, *path = NULL;
8585 struct got_pathlist_head paths;
8586 struct got_pathlist_entry *pe;
8587 int ch, can_recurse = 0, pflag = 0;
8588 FILE *patch_script_file = NULL;
8589 const char *patch_script_path = NULL;
8590 struct choose_patch_arg cpa;
8591 int *pack_fds = NULL;
8593 TAILQ_INIT(&paths);
8595 while ((ch = getopt(argc, argv, "F:pR")) != -1) {
8596 switch (ch) {
8597 case 'F':
8598 patch_script_path = optarg;
8599 break;
8600 case 'p':
8601 pflag = 1;
8602 break;
8603 case 'R':
8604 can_recurse = 1;
8605 break;
8606 default:
8607 usage_revert();
8608 /* NOTREACHED */
8612 argc -= optind;
8613 argv += optind;
8615 #ifndef PROFILE
8616 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
8617 "unveil", NULL) == -1)
8618 err(1, "pledge");
8619 #endif
8620 if (argc < 1)
8621 usage_revert();
8622 if (patch_script_path && !pflag)
8623 errx(1, "-F option can only be used together with -p option");
8625 cwd = getcwd(NULL, 0);
8626 if (cwd == NULL) {
8627 error = got_error_from_errno("getcwd");
8628 goto done;
8631 error = got_repo_pack_fds_open(&pack_fds);
8632 if (error != NULL)
8633 goto done;
8635 error = got_worktree_open(&worktree, cwd);
8636 if (error) {
8637 if (error->code == GOT_ERR_NOT_WORKTREE)
8638 error = wrap_not_worktree_error(error, "revert", cwd);
8639 goto done;
8642 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
8643 NULL, pack_fds);
8644 if (error != NULL)
8645 goto done;
8647 if (patch_script_path) {
8648 patch_script_file = fopen(patch_script_path, "re");
8649 if (patch_script_file == NULL) {
8650 error = got_error_from_errno2("fopen",
8651 patch_script_path);
8652 goto done;
8657 * XXX "c" perm needed on repo dir to delete merge references.
8659 error = apply_unveil(got_repo_get_path(repo), 0,
8660 got_worktree_get_root_path(worktree));
8661 if (error)
8662 goto done;
8664 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
8665 if (error)
8666 goto done;
8668 if (!can_recurse) {
8669 char *ondisk_path;
8670 struct stat sb;
8671 TAILQ_FOREACH(pe, &paths, entry) {
8672 if (asprintf(&ondisk_path, "%s/%s",
8673 got_worktree_get_root_path(worktree),
8674 pe->path) == -1) {
8675 error = got_error_from_errno("asprintf");
8676 goto done;
8678 if (lstat(ondisk_path, &sb) == -1) {
8679 if (errno == ENOENT) {
8680 free(ondisk_path);
8681 continue;
8683 error = got_error_from_errno2("lstat",
8684 ondisk_path);
8685 free(ondisk_path);
8686 goto done;
8688 free(ondisk_path);
8689 if (S_ISDIR(sb.st_mode)) {
8690 error = got_error_msg(GOT_ERR_BAD_PATH,
8691 "reverting directories requires -R option");
8692 goto done;
8697 cpa.patch_script_file = patch_script_file;
8698 cpa.action = "revert";
8699 error = got_worktree_revert(worktree, &paths, revert_progress, NULL,
8700 pflag ? choose_patch : NULL, &cpa, repo);
8702 error = rm_logmsg_ref(worktree, repo);
8703 done:
8704 if (patch_script_file && fclose(patch_script_file) == EOF &&
8705 error == NULL)
8706 error = got_error_from_errno2("fclose", patch_script_path);
8707 if (repo) {
8708 const struct got_error *close_err = got_repo_close(repo);
8709 if (error == NULL)
8710 error = close_err;
8712 if (worktree)
8713 got_worktree_close(worktree);
8714 if (pack_fds) {
8715 const struct got_error *pack_err =
8716 got_repo_pack_fds_close(pack_fds);
8717 if (error == NULL)
8718 error = pack_err;
8720 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
8721 free(path);
8722 free(cwd);
8723 return error;
8726 __dead static void
8727 usage_commit(void)
8729 fprintf(stderr, "usage: %s commit [-NS] [-A author] [-F path] "
8730 "[-m message] [path ...]\n", getprogname());
8731 exit(1);
8734 struct collect_commit_logmsg_arg {
8735 const char *cmdline_log;
8736 const char *prepared_log;
8737 const char *merged_log;
8738 int non_interactive;
8739 const char *editor;
8740 const char *worktree_path;
8741 const char *branch_name;
8742 const char *repo_path;
8743 char *logmsg_path;
8747 static const struct got_error *
8748 read_prepared_logmsg(char **logmsg, const char *path)
8750 const struct got_error *err = NULL;
8751 FILE *f = NULL;
8752 struct stat sb;
8753 size_t r;
8755 *logmsg = NULL;
8756 memset(&sb, 0, sizeof(sb));
8758 f = fopen(path, "re");
8759 if (f == NULL)
8760 return got_error_from_errno2("fopen", path);
8762 if (fstat(fileno(f), &sb) == -1) {
8763 err = got_error_from_errno2("fstat", path);
8764 goto done;
8766 if (sb.st_size == 0) {
8767 err = got_error(GOT_ERR_COMMIT_MSG_EMPTY);
8768 goto done;
8771 *logmsg = malloc(sb.st_size + 1);
8772 if (*logmsg == NULL) {
8773 err = got_error_from_errno("malloc");
8774 goto done;
8777 r = fread(*logmsg, 1, sb.st_size, f);
8778 if (r != sb.st_size) {
8779 if (ferror(f))
8780 err = got_error_from_errno2("fread", path);
8781 else
8782 err = got_error(GOT_ERR_IO);
8783 goto done;
8785 (*logmsg)[sb.st_size] = '\0';
8786 done:
8787 if (fclose(f) == EOF && err == NULL)
8788 err = got_error_from_errno2("fclose", path);
8789 if (err) {
8790 free(*logmsg);
8791 *logmsg = NULL;
8793 return err;
8796 static const struct got_error *
8797 collect_commit_logmsg(struct got_pathlist_head *commitable_paths,
8798 const char *diff_path, char **logmsg, void *arg)
8800 char *initial_content = NULL;
8801 struct got_pathlist_entry *pe;
8802 const struct got_error *err = NULL;
8803 char *template = NULL;
8804 char *prepared_msg = NULL, *merged_msg = NULL;
8805 struct collect_commit_logmsg_arg *a = arg;
8806 int initial_content_len;
8807 int fd = -1;
8808 size_t len;
8810 /* if a message was specified on the command line, just use it */
8811 if (a->cmdline_log != NULL && strlen(a->cmdline_log) != 0) {
8812 len = strlen(a->cmdline_log) + 1;
8813 *logmsg = malloc(len + 1);
8814 if (*logmsg == NULL)
8815 return got_error_from_errno("malloc");
8816 strlcpy(*logmsg, a->cmdline_log, len);
8817 return NULL;
8818 } else if (a->prepared_log != NULL && a->non_interactive)
8819 return read_prepared_logmsg(logmsg, a->prepared_log);
8821 if (asprintf(&template, "%s/logmsg", a->worktree_path) == -1)
8822 return got_error_from_errno("asprintf");
8824 err = got_opentemp_named_fd(&a->logmsg_path, &fd, template, "");
8825 if (err)
8826 goto done;
8828 if (a->prepared_log) {
8829 err = read_prepared_logmsg(&prepared_msg, a->prepared_log);
8830 if (err)
8831 goto done;
8832 } else if (a->merged_log) {
8833 err = read_prepared_logmsg(&merged_msg, a->merged_log);
8834 if (err)
8835 goto done;
8838 initial_content_len = asprintf(&initial_content,
8839 "%s%s\n# changes to be committed on branch %s:\n",
8840 prepared_msg ? prepared_msg : "",
8841 merged_msg ? merged_msg : "", a->branch_name);
8842 if (initial_content_len == -1) {
8843 err = got_error_from_errno("asprintf");
8844 goto done;
8847 if (write(fd, initial_content, initial_content_len) == -1) {
8848 err = got_error_from_errno2("write", a->logmsg_path);
8849 goto done;
8852 TAILQ_FOREACH(pe, commitable_paths, entry) {
8853 struct got_commitable *ct = pe->data;
8854 dprintf(fd, "# %c %s\n",
8855 got_commitable_get_status(ct),
8856 got_commitable_get_path(ct));
8859 if (diff_path) {
8860 dprintf(fd, "# detailed changes can be viewed in %s\n",
8861 diff_path);
8864 err = edit_logmsg(logmsg, a->editor, a->logmsg_path, initial_content,
8865 initial_content_len, a->prepared_log ? 0 : 1);
8866 done:
8867 free(initial_content);
8868 free(template);
8869 free(prepared_msg);
8870 free(merged_msg);
8872 if (fd != -1 && close(fd) == -1 && err == NULL)
8873 err = got_error_from_errno2("close", a->logmsg_path);
8875 /* Editor is done; we can now apply unveil(2) */
8876 if (err == NULL)
8877 err = apply_unveil(a->repo_path, 0, a->worktree_path);
8878 if (err) {
8879 free(*logmsg);
8880 *logmsg = NULL;
8882 return err;
8885 static const struct got_error *
8886 cat_logmsg(FILE *f, struct got_commit_object *commit, const char *idstr,
8887 const char *type, int has_content)
8889 const struct got_error *err = NULL;
8890 char *logmsg = NULL;
8892 err = got_object_commit_get_logmsg(&logmsg, commit);
8893 if (err)
8894 return err;
8896 if (fprintf(f, "%s# log message of %s commit %s:%s",
8897 has_content ? "\n" : "", type, idstr, logmsg) < 0)
8898 err = got_ferror(f, GOT_ERR_IO);
8900 free(logmsg);
8901 return err;
8905 * Lookup "logmsg" references of backed-out and cherrypicked commits
8906 * belonging to the current work tree. If found, and the worktree has
8907 * at least one modified file that was changed in the referenced commit,
8908 * add its log message to a new temporary file at *logmsg_path.
8909 * Add all refs found to matched_refs to be scheduled for removal on
8910 * successful commit.
8912 static const struct got_error *
8913 lookup_logmsg_ref(char **logmsg_path, struct got_pathlist_head *paths,
8914 struct got_reflist_head *matched_refs, struct got_worktree *worktree,
8915 struct got_repository *repo)
8917 const struct got_error *err;
8918 struct got_commit_object *commit = NULL;
8919 struct got_object_id *id = NULL;
8920 struct got_reflist_head refs;
8921 struct got_reflist_entry *re, *re_match;
8922 FILE *f = NULL;
8923 char *uuidstr = NULL;
8924 int added_logmsg = 0;
8926 TAILQ_INIT(&refs);
8928 *logmsg_path = NULL;
8930 err = got_worktree_get_uuid(&uuidstr, worktree);
8931 if (err)
8932 goto done;
8934 err = got_ref_list(&refs, repo, "refs/got/worktree",
8935 got_ref_cmp_by_name, repo);
8936 if (err)
8937 goto done;
8939 TAILQ_FOREACH(re, &refs, entry) {
8940 const char *refname, *type;
8941 struct wt_commitable_path_arg wcpa;
8942 int add_logmsg = 0;
8944 refname = got_ref_get_name(re->ref);
8946 if (strncmp(refname, GOT_WORKTREE_CHERRYPICK_REF_PREFIX,
8947 GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN) == 0) {
8948 refname += GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN + 1;
8949 type = "cherrypicked";
8950 } else if (strncmp(refname, GOT_WORKTREE_BACKOUT_REF_PREFIX,
8951 GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN) == 0) {
8952 refname += GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN + 1;
8953 type = "backed-out";
8954 } else
8955 continue;
8957 if (strncmp(refname, uuidstr, GOT_WORKTREE_UUID_STRLEN) == 0)
8958 refname += GOT_WORKTREE_UUID_STRLEN + 1; /* skip '-' */
8959 else
8960 continue;
8962 err = got_repo_match_object_id(&id, NULL, refname,
8963 GOT_OBJ_TYPE_COMMIT, NULL, repo);
8964 if (err)
8965 goto done;
8967 err = got_object_open_as_commit(&commit, repo, id);
8968 if (err)
8969 goto done;
8971 wcpa.commit_paths = paths;
8972 wcpa.has_changes = &add_logmsg;
8974 err = commit_path_changed_in_worktree(&wcpa, id,
8975 worktree, repo);
8976 if (err)
8977 goto done;
8979 if (add_logmsg) {
8980 if (f == NULL) {
8981 err = got_opentemp_named(logmsg_path, &f,
8982 "got-commit-logmsg", "");
8983 if (err)
8984 goto done;
8986 err = cat_logmsg(f, commit, refname, type,
8987 added_logmsg);
8988 if (err)
8989 goto done;
8990 if (!added_logmsg)
8991 ++added_logmsg;
8993 err = got_reflist_entry_dup(&re_match, re);
8994 if (err)
8995 goto done;
8996 TAILQ_INSERT_HEAD(matched_refs, re_match, entry);
8999 got_object_commit_close(commit);
9000 commit = NULL;
9001 free(id);
9002 id = NULL;
9005 done:
9006 free(id);
9007 free(uuidstr);
9008 got_ref_list_free(&refs);
9009 if (commit)
9010 got_object_commit_close(commit);
9011 if (f && fclose(f) == EOF && err == NULL)
9012 err = got_error_from_errno("fclose");
9013 if (!added_logmsg) {
9014 if (*logmsg_path && unlink(*logmsg_path) != 0 && err == NULL)
9015 err = got_error_from_errno2("unlink", *logmsg_path);
9016 *logmsg_path = NULL;
9018 return err;
9021 static const struct got_error *
9022 cmd_commit(int argc, char *argv[])
9024 const struct got_error *error = NULL;
9025 struct got_worktree *worktree = NULL;
9026 struct got_repository *repo = NULL;
9027 char *cwd = NULL, *id_str = NULL;
9028 struct got_object_id *id = NULL;
9029 const char *logmsg = NULL;
9030 char *prepared_logmsg = NULL, *merged_logmsg = NULL;
9031 struct collect_commit_logmsg_arg cl_arg;
9032 const char *author = NULL;
9033 char *gitconfig_path = NULL, *editor = NULL, *committer = NULL;
9034 int ch, rebase_in_progress, histedit_in_progress, preserve_logmsg = 0;
9035 int allow_bad_symlinks = 0, non_interactive = 0, merge_in_progress = 0;
9036 int show_diff = 1;
9037 struct got_pathlist_head paths;
9038 struct got_reflist_head refs;
9039 struct got_reflist_entry *re;
9040 int *pack_fds = NULL;
9042 TAILQ_INIT(&refs);
9043 TAILQ_INIT(&paths);
9044 cl_arg.logmsg_path = NULL;
9046 while ((ch = getopt(argc, argv, "A:F:m:NnS")) != -1) {
9047 switch (ch) {
9048 case 'A':
9049 author = optarg;
9050 error = valid_author(author);
9051 if (error)
9052 return error;
9053 break;
9054 case 'F':
9055 if (logmsg != NULL)
9056 option_conflict('F', 'm');
9057 prepared_logmsg = realpath(optarg, NULL);
9058 if (prepared_logmsg == NULL)
9059 return got_error_from_errno2("realpath",
9060 optarg);
9061 break;
9062 case 'm':
9063 if (prepared_logmsg)
9064 option_conflict('m', 'F');
9065 logmsg = optarg;
9066 break;
9067 case 'N':
9068 non_interactive = 1;
9069 break;
9070 case 'n':
9071 show_diff = 0;
9072 break;
9073 case 'S':
9074 allow_bad_symlinks = 1;
9075 break;
9076 default:
9077 usage_commit();
9078 /* NOTREACHED */
9082 argc -= optind;
9083 argv += optind;
9085 #ifndef PROFILE
9086 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
9087 "unveil", NULL) == -1)
9088 err(1, "pledge");
9089 #endif
9090 cwd = getcwd(NULL, 0);
9091 if (cwd == NULL) {
9092 error = got_error_from_errno("getcwd");
9093 goto done;
9096 error = got_repo_pack_fds_open(&pack_fds);
9097 if (error != NULL)
9098 goto done;
9100 error = got_worktree_open(&worktree, cwd);
9101 if (error) {
9102 if (error->code == GOT_ERR_NOT_WORKTREE)
9103 error = wrap_not_worktree_error(error, "commit", cwd);
9104 goto done;
9107 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
9108 if (error)
9109 goto done;
9110 if (rebase_in_progress) {
9111 error = got_error(GOT_ERR_REBASING);
9112 goto done;
9115 error = got_worktree_histedit_in_progress(&histedit_in_progress,
9116 worktree);
9117 if (error)
9118 goto done;
9120 error = get_gitconfig_path(&gitconfig_path);
9121 if (error)
9122 goto done;
9123 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
9124 gitconfig_path, pack_fds);
9125 if (error != NULL)
9126 goto done;
9128 error = got_worktree_merge_in_progress(&merge_in_progress, worktree, repo);
9129 if (error)
9130 goto done;
9131 if (merge_in_progress) {
9132 error = got_error(GOT_ERR_MERGE_BUSY);
9133 goto done;
9136 error = get_author(&committer, repo, worktree);
9137 if (error)
9138 goto done;
9140 if (author != NULL && !strcmp(committer, author)) {
9141 error = got_error(GOT_ERR_COMMIT_REDUNDANT_AUTHOR);
9142 goto done;
9145 if (author == NULL)
9146 author = committer;
9149 * unveil(2) traverses exec(2); if an editor is used we have
9150 * to apply unveil after the log message has been written.
9152 if (logmsg == NULL || strlen(logmsg) == 0)
9153 error = get_editor(&editor);
9154 else
9155 error = apply_unveil(got_repo_get_path(repo), 0,
9156 got_worktree_get_root_path(worktree));
9157 if (error)
9158 goto done;
9160 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
9161 if (error)
9162 goto done;
9164 if (prepared_logmsg == NULL) {
9165 error = lookup_logmsg_ref(&merged_logmsg,
9166 argc > 0 ? &paths : NULL, &refs, worktree, repo);
9167 if (error)
9168 goto done;
9171 cl_arg.editor = editor;
9172 cl_arg.cmdline_log = logmsg;
9173 cl_arg.prepared_log = prepared_logmsg;
9174 cl_arg.merged_log = merged_logmsg;
9175 cl_arg.non_interactive = non_interactive;
9176 cl_arg.worktree_path = got_worktree_get_root_path(worktree);
9177 cl_arg.branch_name = got_worktree_get_head_ref_name(worktree);
9178 if (!histedit_in_progress) {
9179 if (strncmp(cl_arg.branch_name, "refs/heads/", 11) != 0) {
9180 error = got_error(GOT_ERR_COMMIT_BRANCH);
9181 goto done;
9183 cl_arg.branch_name += 11;
9185 cl_arg.repo_path = got_repo_get_path(repo);
9186 error = got_worktree_commit(&id, worktree, &paths, author, committer,
9187 allow_bad_symlinks, show_diff, collect_commit_logmsg, &cl_arg,
9188 print_status, NULL, repo);
9189 if (error) {
9190 if (error->code != GOT_ERR_COMMIT_MSG_EMPTY &&
9191 cl_arg.logmsg_path != NULL)
9192 preserve_logmsg = 1;
9193 goto done;
9196 error = got_object_id_str(&id_str, id);
9197 if (error)
9198 goto done;
9199 printf("Created commit %s\n", id_str);
9201 TAILQ_FOREACH(re, &refs, entry) {
9202 error = got_ref_delete(re->ref, repo);
9203 if (error)
9204 goto done;
9207 done:
9208 if (preserve_logmsg) {
9209 fprintf(stderr, "%s: log message preserved in %s\n",
9210 getprogname(), cl_arg.logmsg_path);
9211 } else if (cl_arg.logmsg_path && unlink(cl_arg.logmsg_path) == -1 &&
9212 error == NULL)
9213 error = got_error_from_errno2("unlink", cl_arg.logmsg_path);
9214 free(cl_arg.logmsg_path);
9215 if (merged_logmsg && unlink(merged_logmsg) == -1 && error == NULL)
9216 error = got_error_from_errno2("unlink", merged_logmsg);
9217 free(merged_logmsg);
9218 if (repo) {
9219 const struct got_error *close_err = got_repo_close(repo);
9220 if (error == NULL)
9221 error = close_err;
9223 if (worktree)
9224 got_worktree_close(worktree);
9225 if (pack_fds) {
9226 const struct got_error *pack_err =
9227 got_repo_pack_fds_close(pack_fds);
9228 if (error == NULL)
9229 error = pack_err;
9231 got_ref_list_free(&refs);
9232 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
9233 free(cwd);
9234 free(id_str);
9235 free(gitconfig_path);
9236 free(editor);
9237 free(committer);
9238 free(prepared_logmsg);
9239 return error;
9242 __dead static void
9243 usage_send(void)
9245 fprintf(stderr, "usage: %s send [-afqTv] [-b branch] [-d branch] "
9246 "[-r repository-path] [-t tag] [remote-repository]\n",
9247 getprogname());
9248 exit(1);
9251 static void
9252 print_load_info(int print_colored, int print_found, int print_trees,
9253 int ncolored, int nfound, int ntrees)
9255 if (print_colored) {
9256 printf("%d commit%s colored", ncolored,
9257 ncolored == 1 ? "" : "s");
9259 if (print_found) {
9260 printf("%s%d object%s found",
9261 ncolored > 0 ? "; " : "",
9262 nfound, nfound == 1 ? "" : "s");
9264 if (print_trees) {
9265 printf("; %d tree%s scanned", ntrees,
9266 ntrees == 1 ? "" : "s");
9270 struct got_send_progress_arg {
9271 char last_scaled_packsize[FMT_SCALED_STRSIZE];
9272 int verbosity;
9273 int last_ncolored;
9274 int last_nfound;
9275 int last_ntrees;
9276 int loading_done;
9277 int last_ncommits;
9278 int last_nobj_total;
9279 int last_p_deltify;
9280 int last_p_written;
9281 int last_p_sent;
9282 int printed_something;
9283 int sent_something;
9284 struct got_pathlist_head *delete_branches;
9287 static const struct got_error *
9288 send_progress(void *arg, int ncolored, int nfound, int ntrees,
9289 off_t packfile_size, int ncommits, int nobj_total, int nobj_deltify,
9290 int nobj_written, off_t bytes_sent, const char *refname,
9291 const char *errmsg, int success)
9293 struct got_send_progress_arg *a = arg;
9294 char scaled_packsize[FMT_SCALED_STRSIZE];
9295 char scaled_sent[FMT_SCALED_STRSIZE];
9296 int p_deltify = 0, p_written = 0, p_sent = 0;
9297 int print_colored = 0, print_found = 0, print_trees = 0;
9298 int print_searching = 0, print_total = 0;
9299 int print_deltify = 0, print_written = 0, print_sent = 0;
9301 if (a->verbosity < 0)
9302 return NULL;
9304 if (refname) {
9305 const char *status = success ? "accepted" : "rejected";
9307 if (success) {
9308 struct got_pathlist_entry *pe;
9309 TAILQ_FOREACH(pe, a->delete_branches, entry) {
9310 const char *branchname = pe->path;
9311 if (got_path_cmp(branchname, refname,
9312 strlen(branchname), strlen(refname)) == 0) {
9313 status = "deleted";
9314 a->sent_something = 1;
9315 break;
9320 if (a->printed_something)
9321 putchar('\n');
9322 printf("Server has %s %s", status, refname);
9323 if (errmsg)
9324 printf(": %s", errmsg);
9325 a->printed_something = 1;
9326 return NULL;
9329 if (a->last_ncolored != ncolored) {
9330 print_colored = 1;
9331 a->last_ncolored = ncolored;
9334 if (a->last_nfound != nfound) {
9335 print_colored = 1;
9336 print_found = 1;
9337 a->last_nfound = nfound;
9340 if (a->last_ntrees != ntrees) {
9341 print_colored = 1;
9342 print_found = 1;
9343 print_trees = 1;
9344 a->last_ntrees = ntrees;
9347 if ((print_colored || print_found || print_trees) &&
9348 !a->loading_done) {
9349 printf("\r");
9350 print_load_info(print_colored, print_found, print_trees,
9351 ncolored, nfound, ntrees);
9352 a->printed_something = 1;
9353 fflush(stdout);
9354 return NULL;
9355 } else if (!a->loading_done) {
9356 printf("\r");
9357 print_load_info(1, 1, 1, ncolored, nfound, ntrees);
9358 printf("\n");
9359 a->loading_done = 1;
9362 if (fmt_scaled(packfile_size, scaled_packsize) == -1)
9363 return got_error_from_errno("fmt_scaled");
9364 if (fmt_scaled(bytes_sent, scaled_sent) == -1)
9365 return got_error_from_errno("fmt_scaled");
9367 if (a->last_ncommits != ncommits) {
9368 print_searching = 1;
9369 a->last_ncommits = ncommits;
9372 if (a->last_nobj_total != nobj_total) {
9373 print_searching = 1;
9374 print_total = 1;
9375 a->last_nobj_total = nobj_total;
9378 if (packfile_size > 0 && (a->last_scaled_packsize[0] == '\0' ||
9379 strcmp(scaled_packsize, a->last_scaled_packsize)) != 0) {
9380 if (strlcpy(a->last_scaled_packsize, scaled_packsize,
9381 FMT_SCALED_STRSIZE) >= FMT_SCALED_STRSIZE)
9382 return got_error(GOT_ERR_NO_SPACE);
9385 if (nobj_deltify > 0 || nobj_written > 0) {
9386 if (nobj_deltify > 0) {
9387 p_deltify = (nobj_deltify * 100) / nobj_total;
9388 if (p_deltify != a->last_p_deltify) {
9389 a->last_p_deltify = p_deltify;
9390 print_searching = 1;
9391 print_total = 1;
9392 print_deltify = 1;
9395 if (nobj_written > 0) {
9396 p_written = (nobj_written * 100) / nobj_total;
9397 if (p_written != a->last_p_written) {
9398 a->last_p_written = p_written;
9399 print_searching = 1;
9400 print_total = 1;
9401 print_deltify = 1;
9402 print_written = 1;
9407 if (bytes_sent > 0) {
9408 p_sent = (bytes_sent * 100) / packfile_size;
9409 if (p_sent != a->last_p_sent) {
9410 a->last_p_sent = p_sent;
9411 print_searching = 1;
9412 print_total = 1;
9413 print_deltify = 1;
9414 print_written = 1;
9415 print_sent = 1;
9417 a->sent_something = 1;
9420 if (print_searching || print_total || print_deltify || print_written ||
9421 print_sent)
9422 printf("\r");
9423 if (print_searching)
9424 printf("packing %d reference%s", ncommits,
9425 ncommits == 1 ? "" : "s");
9426 if (print_total)
9427 printf("; %d object%s", nobj_total,
9428 nobj_total == 1 ? "" : "s");
9429 if (print_deltify)
9430 printf("; deltify: %d%%", p_deltify);
9431 if (print_sent)
9432 printf("; uploading pack: %*s %d%%", FMT_SCALED_STRSIZE - 2,
9433 scaled_packsize, p_sent);
9434 else if (print_written)
9435 printf("; writing pack: %*s %d%%", FMT_SCALED_STRSIZE - 2,
9436 scaled_packsize, p_written);
9437 if (print_searching || print_total || print_deltify ||
9438 print_written || print_sent) {
9439 a->printed_something = 1;
9440 fflush(stdout);
9442 return NULL;
9445 static const struct got_error *
9446 cmd_send(int argc, char *argv[])
9448 const struct got_error *error = NULL;
9449 char *cwd = NULL, *repo_path = NULL;
9450 const char *remote_name;
9451 char *proto = NULL, *host = NULL, *port = NULL;
9452 char *repo_name = NULL, *server_path = NULL;
9453 const struct got_remote_repo *remotes, *remote = NULL;
9454 int nremotes, nbranches = 0, ndelete_branches = 0;
9455 struct got_repository *repo = NULL;
9456 struct got_worktree *worktree = NULL;
9457 const struct got_gotconfig *repo_conf = NULL, *worktree_conf = NULL;
9458 struct got_pathlist_head branches;
9459 struct got_pathlist_head tags;
9460 struct got_reflist_head all_branches;
9461 struct got_reflist_head all_tags;
9462 struct got_pathlist_head delete_args;
9463 struct got_pathlist_head delete_branches;
9464 struct got_reflist_entry *re;
9465 struct got_pathlist_entry *pe;
9466 int i, ch, sendfd = -1, sendstatus;
9467 pid_t sendpid = -1;
9468 struct got_send_progress_arg spa;
9469 int verbosity = 0, overwrite_refs = 0;
9470 int send_all_branches = 0, send_all_tags = 0;
9471 struct got_reference *ref = NULL;
9472 int *pack_fds = NULL;
9474 TAILQ_INIT(&branches);
9475 TAILQ_INIT(&tags);
9476 TAILQ_INIT(&all_branches);
9477 TAILQ_INIT(&all_tags);
9478 TAILQ_INIT(&delete_args);
9479 TAILQ_INIT(&delete_branches);
9481 while ((ch = getopt(argc, argv, "ab:d:fqr:Tt:v")) != -1) {
9482 switch (ch) {
9483 case 'a':
9484 send_all_branches = 1;
9485 break;
9486 case 'b':
9487 error = got_pathlist_append(&branches, optarg, NULL);
9488 if (error)
9489 return error;
9490 nbranches++;
9491 break;
9492 case 'd':
9493 error = got_pathlist_append(&delete_args, optarg, NULL);
9494 if (error)
9495 return error;
9496 break;
9497 case 'f':
9498 overwrite_refs = 1;
9499 break;
9500 case 'q':
9501 verbosity = -1;
9502 break;
9503 case 'r':
9504 repo_path = realpath(optarg, NULL);
9505 if (repo_path == NULL)
9506 return got_error_from_errno2("realpath",
9507 optarg);
9508 got_path_strip_trailing_slashes(repo_path);
9509 break;
9510 case 'T':
9511 send_all_tags = 1;
9512 break;
9513 case 't':
9514 error = got_pathlist_append(&tags, optarg, NULL);
9515 if (error)
9516 return error;
9517 break;
9518 case 'v':
9519 if (verbosity < 0)
9520 verbosity = 0;
9521 else if (verbosity < 3)
9522 verbosity++;
9523 break;
9524 default:
9525 usage_send();
9526 /* NOTREACHED */
9529 argc -= optind;
9530 argv += optind;
9532 if (send_all_branches && !TAILQ_EMPTY(&branches))
9533 option_conflict('a', 'b');
9534 if (send_all_tags && !TAILQ_EMPTY(&tags))
9535 option_conflict('T', 't');
9538 if (argc == 0)
9539 remote_name = GOT_SEND_DEFAULT_REMOTE_NAME;
9540 else if (argc == 1)
9541 remote_name = argv[0];
9542 else
9543 usage_send();
9545 cwd = getcwd(NULL, 0);
9546 if (cwd == NULL) {
9547 error = got_error_from_errno("getcwd");
9548 goto done;
9551 error = got_repo_pack_fds_open(&pack_fds);
9552 if (error != NULL)
9553 goto done;
9555 if (repo_path == NULL) {
9556 error = got_worktree_open(&worktree, cwd);
9557 if (error && error->code != GOT_ERR_NOT_WORKTREE)
9558 goto done;
9559 else
9560 error = NULL;
9561 if (worktree) {
9562 repo_path =
9563 strdup(got_worktree_get_repo_path(worktree));
9564 if (repo_path == NULL)
9565 error = got_error_from_errno("strdup");
9566 if (error)
9567 goto done;
9568 } else {
9569 repo_path = strdup(cwd);
9570 if (repo_path == NULL) {
9571 error = got_error_from_errno("strdup");
9572 goto done;
9577 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
9578 if (error)
9579 goto done;
9581 if (worktree) {
9582 worktree_conf = got_worktree_get_gotconfig(worktree);
9583 if (worktree_conf) {
9584 got_gotconfig_get_remotes(&nremotes, &remotes,
9585 worktree_conf);
9586 for (i = 0; i < nremotes; i++) {
9587 if (strcmp(remotes[i].name, remote_name) == 0) {
9588 remote = &remotes[i];
9589 break;
9594 if (remote == NULL) {
9595 repo_conf = got_repo_get_gotconfig(repo);
9596 if (repo_conf) {
9597 got_gotconfig_get_remotes(&nremotes, &remotes,
9598 repo_conf);
9599 for (i = 0; i < nremotes; i++) {
9600 if (strcmp(remotes[i].name, remote_name) == 0) {
9601 remote = &remotes[i];
9602 break;
9607 if (remote == NULL) {
9608 got_repo_get_gitconfig_remotes(&nremotes, &remotes, repo);
9609 for (i = 0; i < nremotes; i++) {
9610 if (strcmp(remotes[i].name, remote_name) == 0) {
9611 remote = &remotes[i];
9612 break;
9616 if (remote == NULL) {
9617 error = got_error_path(remote_name, GOT_ERR_NO_REMOTE);
9618 goto done;
9621 error = got_dial_parse_uri(&proto, &host, &port, &server_path,
9622 &repo_name, remote->send_url);
9623 if (error)
9624 goto done;
9626 if (strcmp(proto, "git") == 0) {
9627 #ifndef PROFILE
9628 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
9629 "sendfd dns inet unveil", NULL) == -1)
9630 err(1, "pledge");
9631 #endif
9632 } else if (strcmp(proto, "git+ssh") == 0 ||
9633 strcmp(proto, "ssh") == 0) {
9634 #ifndef PROFILE
9635 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
9636 "sendfd unveil", NULL) == -1)
9637 err(1, "pledge");
9638 #endif
9639 } else if (strcmp(proto, "http") == 0 ||
9640 strcmp(proto, "git+http") == 0) {
9641 error = got_error_path(proto, GOT_ERR_NOT_IMPL);
9642 goto done;
9643 } else {
9644 error = got_error_path(proto, GOT_ERR_BAD_PROTO);
9645 goto done;
9648 error = got_dial_apply_unveil(proto);
9649 if (error)
9650 goto done;
9652 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
9653 if (error)
9654 goto done;
9656 if (send_all_branches) {
9657 error = got_ref_list(&all_branches, repo, "refs/heads",
9658 got_ref_cmp_by_name, NULL);
9659 if (error)
9660 goto done;
9661 TAILQ_FOREACH(re, &all_branches, entry) {
9662 const char *branchname = got_ref_get_name(re->ref);
9663 error = got_pathlist_append(&branches,
9664 branchname, NULL);
9665 if (error)
9666 goto done;
9667 nbranches++;
9669 } else if (nbranches == 0) {
9670 for (i = 0; i < remote->nsend_branches; i++) {
9671 error = got_pathlist_append(&branches,
9672 remote->send_branches[i], NULL);
9673 if (error)
9674 goto done;
9678 if (send_all_tags) {
9679 error = got_ref_list(&all_tags, repo, "refs/tags",
9680 got_ref_cmp_by_name, NULL);
9681 if (error)
9682 goto done;
9683 TAILQ_FOREACH(re, &all_tags, entry) {
9684 const char *tagname = got_ref_get_name(re->ref);
9685 error = got_pathlist_append(&tags,
9686 tagname, NULL);
9687 if (error)
9688 goto done;
9693 * To prevent accidents only branches in refs/heads/ can be deleted
9694 * with 'got send -d'.
9695 * Deleting anything else requires local repository access or Git.
9697 TAILQ_FOREACH(pe, &delete_args, entry) {
9698 const char *branchname = pe->path;
9699 char *s;
9700 struct got_pathlist_entry *new;
9701 if (strncmp(branchname, "refs/heads/", 11) == 0) {
9702 s = strdup(branchname);
9703 if (s == NULL) {
9704 error = got_error_from_errno("strdup");
9705 goto done;
9707 } else {
9708 if (asprintf(&s, "refs/heads/%s", branchname) == -1) {
9709 error = got_error_from_errno("asprintf");
9710 goto done;
9713 error = got_pathlist_insert(&new, &delete_branches, s, NULL);
9714 if (error || new == NULL /* duplicate */)
9715 free(s);
9716 if (error)
9717 goto done;
9718 ndelete_branches++;
9721 if (nbranches == 0 && ndelete_branches == 0) {
9722 struct got_reference *head_ref;
9723 if (worktree)
9724 error = got_ref_open(&head_ref, repo,
9725 got_worktree_get_head_ref_name(worktree), 0);
9726 else
9727 error = got_ref_open(&head_ref, repo, GOT_REF_HEAD, 0);
9728 if (error)
9729 goto done;
9730 if (got_ref_is_symbolic(head_ref)) {
9731 error = got_ref_resolve_symbolic(&ref, repo, head_ref);
9732 got_ref_close(head_ref);
9733 if (error)
9734 goto done;
9735 } else
9736 ref = head_ref;
9737 error = got_pathlist_append(&branches, got_ref_get_name(ref),
9738 NULL);
9739 if (error)
9740 goto done;
9741 nbranches++;
9744 if (verbosity >= 0) {
9745 printf("Connecting to \"%s\" %s://%s%s%s%s%s\n",
9746 remote->name, proto, host,
9747 port ? ":" : "", port ? port : "",
9748 *server_path == '/' ? "" : "/", server_path);
9751 error = got_send_connect(&sendpid, &sendfd, proto, host, port,
9752 server_path, verbosity);
9753 if (error)
9754 goto done;
9756 memset(&spa, 0, sizeof(spa));
9757 spa.last_scaled_packsize[0] = '\0';
9758 spa.last_p_deltify = -1;
9759 spa.last_p_written = -1;
9760 spa.verbosity = verbosity;
9761 spa.delete_branches = &delete_branches;
9762 error = got_send_pack(remote_name, &branches, &tags, &delete_branches,
9763 verbosity, overwrite_refs, sendfd, repo, send_progress, &spa,
9764 check_cancelled, NULL);
9765 if (spa.printed_something)
9766 putchar('\n');
9767 if (error)
9768 goto done;
9769 if (!spa.sent_something && verbosity >= 0)
9770 printf("Already up-to-date\n");
9771 done:
9772 if (sendpid > 0) {
9773 if (kill(sendpid, SIGTERM) == -1)
9774 error = got_error_from_errno("kill");
9775 if (waitpid(sendpid, &sendstatus, 0) == -1 && error == NULL)
9776 error = got_error_from_errno("waitpid");
9778 if (sendfd != -1 && close(sendfd) == -1 && error == NULL)
9779 error = got_error_from_errno("close");
9780 if (repo) {
9781 const struct got_error *close_err = got_repo_close(repo);
9782 if (error == NULL)
9783 error = close_err;
9785 if (worktree)
9786 got_worktree_close(worktree);
9787 if (pack_fds) {
9788 const struct got_error *pack_err =
9789 got_repo_pack_fds_close(pack_fds);
9790 if (error == NULL)
9791 error = pack_err;
9793 if (ref)
9794 got_ref_close(ref);
9795 got_pathlist_free(&branches, GOT_PATHLIST_FREE_NONE);
9796 got_pathlist_free(&tags, GOT_PATHLIST_FREE_NONE);
9797 got_ref_list_free(&all_branches);
9798 got_ref_list_free(&all_tags);
9799 got_pathlist_free(&delete_args, GOT_PATHLIST_FREE_NONE);
9800 got_pathlist_free(&delete_branches, GOT_PATHLIST_FREE_PATH);
9801 free(cwd);
9802 free(repo_path);
9803 free(proto);
9804 free(host);
9805 free(port);
9806 free(server_path);
9807 free(repo_name);
9808 return error;
9812 * Print and if delete is set delete all ref_prefix references.
9813 * If wanted_ref is not NULL, only print or delete this reference.
9815 static const struct got_error *
9816 process_logmsg_refs(const char *ref_prefix, size_t prefix_len,
9817 const char *wanted_ref, int delete, struct got_worktree *worktree,
9818 struct got_repository *repo)
9820 const struct got_error *err;
9821 struct got_pathlist_head paths;
9822 struct got_reflist_head refs;
9823 struct got_reflist_entry *re;
9824 struct got_reflist_object_id_map *refs_idmap = NULL;
9825 struct got_commit_object *commit = NULL;
9826 struct got_object_id *id = NULL;
9827 const char *header_prefix;
9828 char *uuidstr = NULL;
9829 int found = 0;
9831 TAILQ_INIT(&refs);
9832 TAILQ_INIT(&paths);
9834 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, repo);
9835 if (err)
9836 goto done;
9838 err = got_reflist_object_id_map_create(&refs_idmap, &refs, repo);
9839 if (err)
9840 goto done;
9842 if (worktree != NULL) {
9843 err = got_worktree_get_uuid(&uuidstr, worktree);
9844 if (err)
9845 goto done;
9848 if (wanted_ref) {
9849 if (strncmp(wanted_ref, "refs/heads/", 11) == 0)
9850 wanted_ref += 11;
9853 if (strcmp(ref_prefix, GOT_WORKTREE_BACKOUT_REF_PREFIX) == 0)
9854 header_prefix = "backout";
9855 else
9856 header_prefix = "cherrypick";
9858 TAILQ_FOREACH(re, &refs, entry) {
9859 const char *refname, *wt;
9861 refname = got_ref_get_name(re->ref);
9863 err = check_cancelled(NULL);
9864 if (err)
9865 goto done;
9867 if (strncmp(refname, ref_prefix, prefix_len) == 0)
9868 refname += prefix_len + 1; /* skip '-' delimiter */
9869 else
9870 continue;
9872 wt = refname;
9874 if (worktree == NULL || strncmp(refname, uuidstr,
9875 GOT_WORKTREE_UUID_STRLEN) == 0)
9876 refname += GOT_WORKTREE_UUID_STRLEN + 1; /* skip '-' */
9877 else
9878 continue;
9880 err = got_repo_match_object_id(&id, NULL, refname,
9881 GOT_OBJ_TYPE_COMMIT, NULL, repo);
9882 if (err)
9883 goto done;
9885 err = got_object_open_as_commit(&commit, repo, id);
9886 if (err)
9887 goto done;
9889 if (wanted_ref)
9890 found = strncmp(wanted_ref, refname,
9891 strlen(wanted_ref)) == 0;
9892 if (wanted_ref && !found) {
9893 struct got_reflist_head *ci_refs;
9895 ci_refs = got_reflist_object_id_map_lookup(refs_idmap,
9896 id);
9898 if (ci_refs) {
9899 char *refs_str = NULL;
9900 char const *r = NULL;
9902 err = build_refs_str(&refs_str, ci_refs, id,
9903 repo, 1);
9904 if (err)
9905 goto done;
9907 r = refs_str;
9908 while (r) {
9909 if (strncmp(r, wanted_ref,
9910 strlen(wanted_ref)) == 0) {
9911 found = 1;
9912 break;
9914 r = strchr(r, ' ');
9915 if (r)
9916 ++r;
9918 free(refs_str);
9922 if (wanted_ref == NULL || found) {
9923 if (delete) {
9924 err = got_ref_delete(re->ref, repo);
9925 if (err)
9926 goto done;
9927 printf("Deleted: ");
9928 err = print_commit_oneline(commit, id, repo,
9929 refs_idmap);
9930 } else {
9932 * Print paths modified by commit to help
9933 * associate commits with worktree changes.
9935 err = get_changed_paths(&paths, commit,
9936 repo, NULL);
9937 if (err)
9938 goto done;
9940 err = print_commit(commit, id, repo, NULL,
9941 &paths, NULL, 0, 0, refs_idmap, NULL,
9942 header_prefix);
9943 got_pathlist_free(&paths,
9944 GOT_PATHLIST_FREE_ALL);
9946 if (worktree == NULL)
9947 printf("work tree: %.*s\n\n",
9948 GOT_WORKTREE_UUID_STRLEN, wt);
9950 if (err || found)
9951 goto done;
9954 got_object_commit_close(commit);
9955 commit = NULL;
9956 free(id);
9957 id = NULL;
9960 if (wanted_ref != NULL && !found)
9961 err = got_error_fmt(GOT_ERR_NOT_REF, "%s", wanted_ref);
9963 done:
9964 free(id);
9965 free(uuidstr);
9966 got_ref_list_free(&refs);
9967 got_pathlist_free(&paths, GOT_PATHLIST_FREE_ALL);
9968 if (refs_idmap)
9969 got_reflist_object_id_map_free(refs_idmap);
9970 if (commit)
9971 got_object_commit_close(commit);
9972 return err;
9976 * Create new temp "logmsg" ref of the backed-out or cherrypicked commit
9977 * identified by id for log messages to prepopulate the editor on commit.
9979 static const struct got_error *
9980 logmsg_ref(struct got_object_id *id, const char *prefix,
9981 struct got_worktree *worktree, struct got_repository *repo)
9983 const struct got_error *err = NULL;
9984 char *idstr, *ref = NULL, *refname = NULL;
9985 int histedit_in_progress;
9986 int rebase_in_progress, merge_in_progress;
9989 * Silenty refuse to create merge reference if any histedit, merge,
9990 * or rebase operation is in progress.
9992 err = got_worktree_histedit_in_progress(&histedit_in_progress,
9993 worktree);
9994 if (err)
9995 return err;
9996 if (histedit_in_progress)
9997 return NULL;
9999 err = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
10000 if (err)
10001 return err;
10002 if (rebase_in_progress)
10003 return NULL;
10005 err = got_worktree_merge_in_progress(&merge_in_progress, worktree,
10006 repo);
10007 if (err)
10008 return err;
10009 if (merge_in_progress)
10010 return NULL;
10012 err = got_object_id_str(&idstr, id);
10013 if (err)
10014 return err;
10016 err = got_worktree_get_logmsg_ref_name(&refname, worktree, prefix);
10017 if (err)
10018 goto done;
10020 if (asprintf(&ref, "%s-%s", refname, idstr) == -1) {
10021 err = got_error_from_errno("asprintf");
10022 goto done;
10025 err = create_ref(ref, got_worktree_get_base_commit_id(worktree),
10026 -1, repo);
10027 done:
10028 free(ref);
10029 free(idstr);
10030 free(refname);
10031 return err;
10034 __dead static void
10035 usage_cherrypick(void)
10037 fprintf(stderr, "usage: %s cherrypick [-lX] [commit-id]\n",
10038 getprogname());
10039 exit(1);
10042 static const struct got_error *
10043 cmd_cherrypick(int argc, char *argv[])
10045 const struct got_error *error = NULL;
10046 struct got_worktree *worktree = NULL;
10047 struct got_repository *repo = NULL;
10048 char *cwd = NULL, *commit_id_str = NULL;
10049 struct got_object_id *commit_id = NULL;
10050 struct got_commit_object *commit = NULL;
10051 struct got_object_qid *pid;
10052 int ch, list_refs = 0, remove_refs = 0;
10053 struct got_update_progress_arg upa;
10054 int *pack_fds = NULL;
10056 while ((ch = getopt(argc, argv, "lX")) != -1) {
10057 switch (ch) {
10058 case 'l':
10059 list_refs = 1;
10060 break;
10061 case 'X':
10062 remove_refs = 1;
10063 break;
10064 default:
10065 usage_cherrypick();
10066 /* NOTREACHED */
10070 argc -= optind;
10071 argv += optind;
10073 #ifndef PROFILE
10074 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
10075 "unveil", NULL) == -1)
10076 err(1, "pledge");
10077 #endif
10078 if (list_refs || remove_refs) {
10079 if (argc != 0 && argc != 1)
10080 usage_cherrypick();
10081 } else if (argc != 1)
10082 usage_cherrypick();
10083 if (list_refs && remove_refs)
10084 option_conflict('l', 'X');
10086 cwd = getcwd(NULL, 0);
10087 if (cwd == NULL) {
10088 error = got_error_from_errno("getcwd");
10089 goto done;
10092 error = got_repo_pack_fds_open(&pack_fds);
10093 if (error != NULL)
10094 goto done;
10096 error = got_worktree_open(&worktree, cwd);
10097 if (error) {
10098 if (list_refs || remove_refs) {
10099 if (error->code != GOT_ERR_NOT_WORKTREE)
10100 goto done;
10101 } else {
10102 if (error->code == GOT_ERR_NOT_WORKTREE)
10103 error = wrap_not_worktree_error(error,
10104 "cherrypick", cwd);
10105 goto done;
10109 error = got_repo_open(&repo,
10110 worktree ? got_worktree_get_repo_path(worktree) : cwd,
10111 NULL, pack_fds);
10112 if (error != NULL)
10113 goto done;
10115 error = apply_unveil(got_repo_get_path(repo), 0,
10116 worktree ? got_worktree_get_root_path(worktree) : NULL);
10117 if (error)
10118 goto done;
10120 if (list_refs || remove_refs) {
10121 error = process_logmsg_refs(GOT_WORKTREE_CHERRYPICK_REF_PREFIX,
10122 GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN,
10123 argc == 1 ? argv[0] : NULL, remove_refs, worktree, repo);
10124 goto done;
10127 error = got_repo_match_object_id(&commit_id, NULL, argv[0],
10128 GOT_OBJ_TYPE_COMMIT, NULL, repo);
10129 if (error)
10130 goto done;
10131 error = got_object_id_str(&commit_id_str, commit_id);
10132 if (error)
10133 goto done;
10135 error = got_object_open_as_commit(&commit, repo, commit_id);
10136 if (error)
10137 goto done;
10138 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
10139 memset(&upa, 0, sizeof(upa));
10140 error = got_worktree_merge_files(worktree, pid ? &pid->id : NULL,
10141 commit_id, repo, update_progress, &upa, check_cancelled,
10142 NULL);
10143 if (error != NULL)
10144 goto done;
10146 if (upa.did_something) {
10147 error = logmsg_ref(commit_id,
10148 GOT_WORKTREE_CHERRYPICK_REF_PREFIX, worktree, repo);
10149 if (error)
10150 goto done;
10151 printf("Merged commit %s\n", commit_id_str);
10153 print_merge_progress_stats(&upa);
10154 done:
10155 free(cwd);
10156 if (commit)
10157 got_object_commit_close(commit);
10158 free(commit_id_str);
10159 if (worktree)
10160 got_worktree_close(worktree);
10161 if (repo) {
10162 const struct got_error *close_err = got_repo_close(repo);
10163 if (error == NULL)
10164 error = close_err;
10166 if (pack_fds) {
10167 const struct got_error *pack_err =
10168 got_repo_pack_fds_close(pack_fds);
10169 if (error == NULL)
10170 error = pack_err;
10173 return error;
10176 __dead static void
10177 usage_backout(void)
10179 fprintf(stderr, "usage: %s backout [-lX] [commit-id]\n", getprogname());
10180 exit(1);
10183 static const struct got_error *
10184 cmd_backout(int argc, char *argv[])
10186 const struct got_error *error = NULL;
10187 struct got_worktree *worktree = NULL;
10188 struct got_repository *repo = NULL;
10189 char *cwd = NULL, *commit_id_str = NULL;
10190 struct got_object_id *commit_id = NULL;
10191 struct got_commit_object *commit = NULL;
10192 struct got_object_qid *pid;
10193 int ch, list_refs = 0, remove_refs = 0;
10194 struct got_update_progress_arg upa;
10195 int *pack_fds = NULL;
10197 while ((ch = getopt(argc, argv, "lX")) != -1) {
10198 switch (ch) {
10199 case 'l':
10200 list_refs = 1;
10201 break;
10202 case 'X':
10203 remove_refs = 1;
10204 break;
10205 default:
10206 usage_backout();
10207 /* NOTREACHED */
10211 argc -= optind;
10212 argv += optind;
10214 #ifndef PROFILE
10215 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
10216 "unveil", NULL) == -1)
10217 err(1, "pledge");
10218 #endif
10219 if (list_refs || remove_refs) {
10220 if (argc != 0 && argc != 1)
10221 usage_backout();
10222 } else if (argc != 1)
10223 usage_backout();
10224 if (list_refs && remove_refs)
10225 option_conflict('l', 'X');
10227 cwd = getcwd(NULL, 0);
10228 if (cwd == NULL) {
10229 error = got_error_from_errno("getcwd");
10230 goto done;
10233 error = got_repo_pack_fds_open(&pack_fds);
10234 if (error != NULL)
10235 goto done;
10237 error = got_worktree_open(&worktree, cwd);
10238 if (error) {
10239 if (list_refs || remove_refs) {
10240 if (error->code != GOT_ERR_NOT_WORKTREE)
10241 goto done;
10242 } else {
10243 if (error->code == GOT_ERR_NOT_WORKTREE)
10244 error = wrap_not_worktree_error(error,
10245 "backout", cwd);
10246 goto done;
10250 error = got_repo_open(&repo,
10251 worktree ? got_worktree_get_repo_path(worktree) : cwd,
10252 NULL, pack_fds);
10253 if (error != NULL)
10254 goto done;
10256 error = apply_unveil(got_repo_get_path(repo), 0,
10257 worktree ? got_worktree_get_root_path(worktree) : NULL);
10258 if (error)
10259 goto done;
10261 if (list_refs || remove_refs) {
10262 error = process_logmsg_refs(GOT_WORKTREE_BACKOUT_REF_PREFIX,
10263 GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN,
10264 argc == 1 ? argv[0] : NULL, remove_refs, worktree, repo);
10265 goto done;
10268 error = got_repo_match_object_id(&commit_id, NULL, argv[0],
10269 GOT_OBJ_TYPE_COMMIT, NULL, repo);
10270 if (error)
10271 goto done;
10272 error = got_object_id_str(&commit_id_str, commit_id);
10273 if (error)
10274 goto done;
10276 error = got_object_open_as_commit(&commit, repo, commit_id);
10277 if (error)
10278 goto done;
10279 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
10280 if (pid == NULL) {
10281 error = got_error(GOT_ERR_ROOT_COMMIT);
10282 goto done;
10285 memset(&upa, 0, sizeof(upa));
10286 error = got_worktree_merge_files(worktree, commit_id, &pid->id,
10287 repo, update_progress, &upa, check_cancelled, NULL);
10288 if (error != NULL)
10289 goto done;
10291 if (upa.did_something) {
10292 error = logmsg_ref(commit_id, GOT_WORKTREE_BACKOUT_REF_PREFIX,
10293 worktree, repo);
10294 if (error)
10295 goto done;
10296 printf("Backed out commit %s\n", commit_id_str);
10298 print_merge_progress_stats(&upa);
10299 done:
10300 free(cwd);
10301 if (commit)
10302 got_object_commit_close(commit);
10303 free(commit_id_str);
10304 if (worktree)
10305 got_worktree_close(worktree);
10306 if (repo) {
10307 const struct got_error *close_err = got_repo_close(repo);
10308 if (error == NULL)
10309 error = close_err;
10311 if (pack_fds) {
10312 const struct got_error *pack_err =
10313 got_repo_pack_fds_close(pack_fds);
10314 if (error == NULL)
10315 error = pack_err;
10317 return error;
10320 __dead static void
10321 usage_rebase(void)
10323 fprintf(stderr, "usage: %s rebase [-aclX] [branch]\n", getprogname());
10324 exit(1);
10327 static void
10328 trim_logmsg(char *logmsg, int limit)
10330 char *nl;
10331 size_t len;
10333 len = strlen(logmsg);
10334 if (len > limit)
10335 len = limit;
10336 logmsg[len] = '\0';
10337 nl = strchr(logmsg, '\n');
10338 if (nl)
10339 *nl = '\0';
10342 static const struct got_error *
10343 get_short_logmsg(char **logmsg, int limit, struct got_commit_object *commit)
10345 const struct got_error *err;
10346 char *logmsg0 = NULL;
10347 const char *s;
10349 err = got_object_commit_get_logmsg(&logmsg0, commit);
10350 if (err)
10351 return err;
10353 s = logmsg0;
10354 while (isspace((unsigned char)s[0]))
10355 s++;
10357 *logmsg = strdup(s);
10358 if (*logmsg == NULL) {
10359 err = got_error_from_errno("strdup");
10360 goto done;
10363 trim_logmsg(*logmsg, limit);
10364 done:
10365 free(logmsg0);
10366 return err;
10369 static const struct got_error *
10370 show_rebase_merge_conflict(struct got_object_id *id,
10371 struct got_repository *repo)
10373 const struct got_error *err;
10374 struct got_commit_object *commit = NULL;
10375 char *id_str = NULL, *logmsg = NULL;
10377 err = got_object_open_as_commit(&commit, repo, id);
10378 if (err)
10379 return err;
10381 err = got_object_id_str(&id_str, id);
10382 if (err)
10383 goto done;
10385 id_str[12] = '\0';
10387 err = get_short_logmsg(&logmsg, 42, commit);
10388 if (err)
10389 goto done;
10391 printf("%s -> merge conflict: %s\n", id_str, logmsg);
10392 done:
10393 free(id_str);
10394 got_object_commit_close(commit);
10395 free(logmsg);
10396 return err;
10399 static const struct got_error *
10400 show_rebase_progress(struct got_commit_object *commit,
10401 struct got_object_id *old_id, struct got_object_id *new_id)
10403 const struct got_error *err;
10404 char *old_id_str = NULL, *new_id_str = NULL, *logmsg = NULL;
10406 err = got_object_id_str(&old_id_str, old_id);
10407 if (err)
10408 goto done;
10410 if (new_id) {
10411 err = got_object_id_str(&new_id_str, new_id);
10412 if (err)
10413 goto done;
10416 old_id_str[12] = '\0';
10417 if (new_id_str)
10418 new_id_str[12] = '\0';
10420 err = get_short_logmsg(&logmsg, 42, commit);
10421 if (err)
10422 goto done;
10424 printf("%s -> %s: %s\n", old_id_str,
10425 new_id_str ? new_id_str : "no-op change", logmsg);
10426 done:
10427 free(old_id_str);
10428 free(new_id_str);
10429 free(logmsg);
10430 return err;
10433 static const struct got_error *
10434 rebase_complete(struct got_worktree *worktree, struct got_fileindex *fileindex,
10435 struct got_reference *branch, struct got_reference *tmp_branch,
10436 struct got_repository *repo, int create_backup)
10438 printf("Switching work tree to %s\n", got_ref_get_name(branch));
10439 return got_worktree_rebase_complete(worktree, fileindex,
10440 tmp_branch, branch, repo, create_backup);
10443 static const struct got_error *
10444 rebase_commit(struct got_pathlist_head *merged_paths,
10445 struct got_worktree *worktree, struct got_fileindex *fileindex,
10446 struct got_reference *tmp_branch, const char *committer,
10447 struct got_object_id *commit_id, struct got_repository *repo)
10449 const struct got_error *error;
10450 struct got_commit_object *commit;
10451 struct got_object_id *new_commit_id;
10453 error = got_object_open_as_commit(&commit, repo, commit_id);
10454 if (error)
10455 return error;
10457 error = got_worktree_rebase_commit(&new_commit_id, merged_paths,
10458 worktree, fileindex, tmp_branch, committer, commit, commit_id,
10459 repo);
10460 if (error) {
10461 if (error->code != GOT_ERR_COMMIT_NO_CHANGES)
10462 goto done;
10463 error = show_rebase_progress(commit, commit_id, NULL);
10464 } else {
10465 error = show_rebase_progress(commit, commit_id, new_commit_id);
10466 free(new_commit_id);
10468 done:
10469 got_object_commit_close(commit);
10470 return error;
10473 struct check_path_prefix_arg {
10474 const char *path_prefix;
10475 size_t len;
10476 int errcode;
10479 static const struct got_error *
10480 check_path_prefix_in_diff(void *arg, struct got_blob_object *blob1,
10481 struct got_blob_object *blob2, FILE *f1, FILE *f2,
10482 struct got_object_id *id1, struct got_object_id *id2,
10483 const char *path1, const char *path2,
10484 mode_t mode1, mode_t mode2, struct got_repository *repo)
10486 struct check_path_prefix_arg *a = arg;
10488 if ((path1 && !got_path_is_child(path1, a->path_prefix, a->len)) ||
10489 (path2 && !got_path_is_child(path2, a->path_prefix, a->len)))
10490 return got_error(a->errcode);
10492 return NULL;
10495 static const struct got_error *
10496 check_path_prefix(struct got_object_id *parent_id,
10497 struct got_object_id *commit_id, const char *path_prefix,
10498 int errcode, struct got_repository *repo)
10500 const struct got_error *err;
10501 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
10502 struct got_commit_object *commit = NULL, *parent_commit = NULL;
10503 struct check_path_prefix_arg cpp_arg;
10505 if (got_path_is_root_dir(path_prefix))
10506 return NULL;
10508 err = got_object_open_as_commit(&commit, repo, commit_id);
10509 if (err)
10510 goto done;
10512 err = got_object_open_as_commit(&parent_commit, repo, parent_id);
10513 if (err)
10514 goto done;
10516 err = got_object_open_as_tree(&tree1, repo,
10517 got_object_commit_get_tree_id(parent_commit));
10518 if (err)
10519 goto done;
10521 err = got_object_open_as_tree(&tree2, repo,
10522 got_object_commit_get_tree_id(commit));
10523 if (err)
10524 goto done;
10526 cpp_arg.path_prefix = path_prefix;
10527 while (cpp_arg.path_prefix[0] == '/')
10528 cpp_arg.path_prefix++;
10529 cpp_arg.len = strlen(cpp_arg.path_prefix);
10530 cpp_arg.errcode = errcode;
10531 err = got_diff_tree(tree1, tree2, NULL, NULL, -1, -1, "", "", repo,
10532 check_path_prefix_in_diff, &cpp_arg, 0);
10533 done:
10534 if (tree1)
10535 got_object_tree_close(tree1);
10536 if (tree2)
10537 got_object_tree_close(tree2);
10538 if (commit)
10539 got_object_commit_close(commit);
10540 if (parent_commit)
10541 got_object_commit_close(parent_commit);
10542 return err;
10545 static const struct got_error *
10546 collect_commits(struct got_object_id_queue *commits,
10547 struct got_object_id *initial_commit_id,
10548 struct got_object_id *iter_start_id, struct got_object_id *iter_stop_id,
10549 const char *path_prefix, int path_prefix_errcode,
10550 struct got_repository *repo)
10552 const struct got_error *err = NULL;
10553 struct got_commit_graph *graph = NULL;
10554 struct got_object_id parent_id, commit_id;
10555 struct got_object_qid *qid;
10557 err = got_commit_graph_open(&graph, "/", 1);
10558 if (err)
10559 return err;
10561 err = got_commit_graph_iter_start(graph, iter_start_id, repo,
10562 check_cancelled, NULL);
10563 if (err)
10564 goto done;
10566 memcpy(&commit_id, initial_commit_id, sizeof(commit_id));
10567 while (got_object_id_cmp(&commit_id, iter_stop_id) != 0) {
10568 err = got_commit_graph_iter_next(&parent_id, graph, repo,
10569 check_cancelled, NULL);
10570 if (err) {
10571 if (err->code == GOT_ERR_ITER_COMPLETED) {
10572 err = got_error_msg(GOT_ERR_ANCESTRY,
10573 "ran out of commits to rebase before "
10574 "youngest common ancestor commit has "
10575 "been reached?!?");
10577 goto done;
10578 } else {
10579 err = check_path_prefix(&parent_id, &commit_id,
10580 path_prefix, path_prefix_errcode, repo);
10581 if (err)
10582 goto done;
10584 err = got_object_qid_alloc(&qid, &commit_id);
10585 if (err)
10586 goto done;
10587 STAILQ_INSERT_HEAD(commits, qid, entry);
10589 memcpy(&commit_id, &parent_id, sizeof(commit_id));
10592 done:
10593 got_commit_graph_close(graph);
10594 return err;
10597 static const struct got_error *
10598 get_commit_brief_str(char **brief_str, struct got_commit_object *commit)
10600 const struct got_error *err = NULL;
10601 time_t committer_time;
10602 struct tm tm;
10603 char datebuf[11]; /* YYYY-MM-DD + NUL */
10604 char *author0 = NULL, *author, *smallerthan;
10605 char *logmsg0 = NULL, *logmsg, *newline;
10607 committer_time = got_object_commit_get_committer_time(commit);
10608 if (gmtime_r(&committer_time, &tm) == NULL)
10609 return got_error_from_errno("gmtime_r");
10610 if (strftime(datebuf, sizeof(datebuf), "%G-%m-%d", &tm) == 0)
10611 return got_error(GOT_ERR_NO_SPACE);
10613 author0 = strdup(got_object_commit_get_author(commit));
10614 if (author0 == NULL)
10615 return got_error_from_errno("strdup");
10616 author = author0;
10617 smallerthan = strchr(author, '<');
10618 if (smallerthan && smallerthan[1] != '\0')
10619 author = smallerthan + 1;
10620 author[strcspn(author, "@>")] = '\0';
10622 err = got_object_commit_get_logmsg(&logmsg0, commit);
10623 if (err)
10624 goto done;
10625 logmsg = logmsg0;
10626 while (*logmsg == '\n')
10627 logmsg++;
10628 newline = strchr(logmsg, '\n');
10629 if (newline)
10630 *newline = '\0';
10632 if (asprintf(brief_str, "%s %s %s",
10633 datebuf, author, logmsg) == -1)
10634 err = got_error_from_errno("asprintf");
10635 done:
10636 free(author0);
10637 free(logmsg0);
10638 return err;
10641 static const struct got_error *
10642 delete_backup_ref(struct got_reference *ref, struct got_object_id *id,
10643 struct got_repository *repo)
10645 const struct got_error *err;
10646 char *id_str;
10648 err = got_object_id_str(&id_str, id);
10649 if (err)
10650 return err;
10652 err = got_ref_delete(ref, repo);
10653 if (err)
10654 goto done;
10656 printf("Deleted %s: %s\n", got_ref_get_name(ref), id_str);
10657 done:
10658 free(id_str);
10659 return err;
10662 static const struct got_error *
10663 print_backup_ref(const char *branch_name, const char *new_id_str,
10664 struct got_object_id *old_commit_id, struct got_commit_object *old_commit,
10665 struct got_reflist_object_id_map *refs_idmap,
10666 struct got_repository *repo)
10668 const struct got_error *err = NULL;
10669 struct got_reflist_head *refs;
10670 char *refs_str = NULL;
10671 struct got_object_id *new_commit_id = NULL;
10672 struct got_commit_object *new_commit = NULL;
10673 char *new_commit_brief_str = NULL;
10674 struct got_object_id *yca_id = NULL;
10675 struct got_commit_object *yca_commit = NULL;
10676 char *yca_id_str = NULL, *yca_brief_str = NULL;
10677 char *custom_refs_str;
10679 if (asprintf(&custom_refs_str, "formerly %s", branch_name) == -1)
10680 return got_error_from_errno("asprintf");
10682 err = print_commit(old_commit, old_commit_id, repo, NULL, NULL, NULL,
10683 0, 0, refs_idmap, custom_refs_str, NULL);
10684 if (err)
10685 goto done;
10687 err = got_object_resolve_id_str(&new_commit_id, repo, new_id_str);
10688 if (err)
10689 goto done;
10691 refs = got_reflist_object_id_map_lookup(refs_idmap, new_commit_id);
10692 if (refs) {
10693 err = build_refs_str(&refs_str, refs, new_commit_id, repo, 0);
10694 if (err)
10695 goto done;
10698 err = got_object_open_as_commit(&new_commit, repo, new_commit_id);
10699 if (err)
10700 goto done;
10702 err = get_commit_brief_str(&new_commit_brief_str, new_commit);
10703 if (err)
10704 goto done;
10706 err = got_commit_graph_find_youngest_common_ancestor(&yca_id,
10707 old_commit_id, new_commit_id, 1, repo, check_cancelled, NULL);
10708 if (err)
10709 goto done;
10711 printf("has become commit %s%s%s%s\n %s\n", new_id_str,
10712 refs_str ? " (" : "", refs_str ? refs_str : "",
10713 refs_str ? ")" : "", new_commit_brief_str);
10714 if (yca_id && got_object_id_cmp(yca_id, new_commit_id) != 0 &&
10715 got_object_id_cmp(yca_id, old_commit_id) != 0) {
10716 free(refs_str);
10717 refs_str = NULL;
10719 err = got_object_open_as_commit(&yca_commit, repo, yca_id);
10720 if (err)
10721 goto done;
10723 err = get_commit_brief_str(&yca_brief_str, yca_commit);
10724 if (err)
10725 goto done;
10727 err = got_object_id_str(&yca_id_str, yca_id);
10728 if (err)
10729 goto done;
10731 refs = got_reflist_object_id_map_lookup(refs_idmap, yca_id);
10732 if (refs) {
10733 err = build_refs_str(&refs_str, refs, yca_id, repo, 0);
10734 if (err)
10735 goto done;
10737 printf("history forked at %s%s%s%s\n %s\n",
10738 yca_id_str,
10739 refs_str ? " (" : "", refs_str ? refs_str : "",
10740 refs_str ? ")" : "", yca_brief_str);
10742 done:
10743 free(custom_refs_str);
10744 free(new_commit_id);
10745 free(refs_str);
10746 free(yca_id);
10747 free(yca_id_str);
10748 free(yca_brief_str);
10749 if (new_commit)
10750 got_object_commit_close(new_commit);
10751 if (yca_commit)
10752 got_object_commit_close(yca_commit);
10754 return err;
10757 static const struct got_error *
10758 worktree_has_logmsg_ref(const char *caller, struct got_worktree *worktree,
10759 struct got_repository *repo)
10761 const struct got_error *err;
10762 struct got_reflist_head refs;
10763 struct got_reflist_entry *re;
10764 char *uuidstr = NULL;
10765 static char msg[160];
10767 TAILQ_INIT(&refs);
10769 err = got_worktree_get_uuid(&uuidstr, worktree);
10770 if (err)
10771 goto done;
10773 err = got_ref_list(&refs, repo, "refs/got/worktree",
10774 got_ref_cmp_by_name, repo);
10775 if (err)
10776 goto done;
10778 TAILQ_FOREACH(re, &refs, entry) {
10779 const char *cmd, *refname, *type;
10781 refname = got_ref_get_name(re->ref);
10783 if (strncmp(refname, GOT_WORKTREE_CHERRYPICK_REF_PREFIX,
10784 GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN) == 0) {
10785 refname += GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN + 1;
10786 cmd = "cherrypick";
10787 type = "cherrypicked";
10788 } else if (strncmp(refname, GOT_WORKTREE_BACKOUT_REF_PREFIX,
10789 GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN) == 0) {
10790 refname += GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN + 1;
10791 cmd = "backout";
10792 type = "backed-out";
10793 } else
10794 continue;
10796 if (strncmp(refname, uuidstr, GOT_WORKTREE_UUID_STRLEN) != 0)
10797 continue;
10799 snprintf(msg, sizeof(msg),
10800 "work tree has references created by %s commits which "
10801 "must be removed with 'got %s -X' before running the %s "
10802 "command", type, cmd, caller);
10803 err = got_error_msg(GOT_ERR_WORKTREE_META, msg);
10804 goto done;
10807 done:
10808 free(uuidstr);
10809 got_ref_list_free(&refs);
10810 return err;
10813 static const struct got_error *
10814 process_backup_refs(const char *backup_ref_prefix,
10815 const char *wanted_branch_name,
10816 int delete, struct got_repository *repo)
10818 const struct got_error *err;
10819 struct got_reflist_head refs, backup_refs;
10820 struct got_reflist_entry *re;
10821 const size_t backup_ref_prefix_len = strlen(backup_ref_prefix);
10822 struct got_object_id *old_commit_id = NULL;
10823 char *branch_name = NULL;
10824 struct got_commit_object *old_commit = NULL;
10825 struct got_reflist_object_id_map *refs_idmap = NULL;
10826 int wanted_branch_found = 0;
10828 TAILQ_INIT(&refs);
10829 TAILQ_INIT(&backup_refs);
10831 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
10832 if (err)
10833 return err;
10835 err = got_reflist_object_id_map_create(&refs_idmap, &refs, repo);
10836 if (err)
10837 goto done;
10839 if (wanted_branch_name) {
10840 if (strncmp(wanted_branch_name, "refs/heads/", 11) == 0)
10841 wanted_branch_name += 11;
10844 err = got_ref_list(&backup_refs, repo, backup_ref_prefix,
10845 got_ref_cmp_by_commit_timestamp_descending, repo);
10846 if (err)
10847 goto done;
10849 TAILQ_FOREACH(re, &backup_refs, entry) {
10850 const char *refname = got_ref_get_name(re->ref);
10851 char *slash;
10853 err = check_cancelled(NULL);
10854 if (err)
10855 break;
10857 err = got_ref_resolve(&old_commit_id, repo, re->ref);
10858 if (err)
10859 break;
10861 err = got_object_open_as_commit(&old_commit, repo,
10862 old_commit_id);
10863 if (err)
10864 break;
10866 if (strncmp(backup_ref_prefix, refname,
10867 backup_ref_prefix_len) == 0)
10868 refname += backup_ref_prefix_len;
10870 while (refname[0] == '/')
10871 refname++;
10873 branch_name = strdup(refname);
10874 if (branch_name == NULL) {
10875 err = got_error_from_errno("strdup");
10876 break;
10878 slash = strrchr(branch_name, '/');
10879 if (slash) {
10880 *slash = '\0';
10881 refname += strlen(branch_name) + 1;
10884 if (wanted_branch_name == NULL ||
10885 strcmp(wanted_branch_name, branch_name) == 0) {
10886 wanted_branch_found = 1;
10887 if (delete) {
10888 err = delete_backup_ref(re->ref,
10889 old_commit_id, repo);
10890 } else {
10891 err = print_backup_ref(branch_name, refname,
10892 old_commit_id, old_commit, refs_idmap,
10893 repo);
10895 if (err)
10896 break;
10899 free(old_commit_id);
10900 old_commit_id = NULL;
10901 free(branch_name);
10902 branch_name = NULL;
10903 got_object_commit_close(old_commit);
10904 old_commit = NULL;
10907 if (wanted_branch_name && !wanted_branch_found) {
10908 err = got_error_fmt(GOT_ERR_NOT_REF,
10909 "%s/%s/", backup_ref_prefix, wanted_branch_name);
10911 done:
10912 if (refs_idmap)
10913 got_reflist_object_id_map_free(refs_idmap);
10914 got_ref_list_free(&refs);
10915 got_ref_list_free(&backup_refs);
10916 free(old_commit_id);
10917 free(branch_name);
10918 if (old_commit)
10919 got_object_commit_close(old_commit);
10920 return err;
10923 static const struct got_error *
10924 abort_progress(void *arg, unsigned char status, const char *path)
10927 * Unversioned files should not clutter progress output when
10928 * an operation is aborted.
10930 if (status == GOT_STATUS_UNVERSIONED)
10931 return NULL;
10933 return update_progress(arg, status, path);
10936 static const struct got_error *
10937 cmd_rebase(int argc, char *argv[])
10939 const struct got_error *error = NULL;
10940 struct got_worktree *worktree = NULL;
10941 struct got_repository *repo = NULL;
10942 struct got_fileindex *fileindex = NULL;
10943 char *cwd = NULL, *committer = NULL, *gitconfig_path = NULL;
10944 struct got_reference *branch = NULL;
10945 struct got_reference *new_base_branch = NULL, *tmp_branch = NULL;
10946 struct got_object_id *commit_id = NULL, *parent_id = NULL;
10947 struct got_object_id *resume_commit_id = NULL;
10948 struct got_object_id *branch_head_commit_id = NULL, *yca_id = NULL;
10949 struct got_object_id *head_commit_id = NULL;
10950 struct got_reference *head_ref = NULL;
10951 struct got_commit_object *commit = NULL;
10952 int ch, rebase_in_progress = 0, abort_rebase = 0, continue_rebase = 0;
10953 int histedit_in_progress = 0, merge_in_progress = 0;
10954 int create_backup = 1, list_backups = 0, delete_backups = 0;
10955 struct got_object_id_queue commits;
10956 struct got_pathlist_head merged_paths;
10957 const struct got_object_id_queue *parent_ids;
10958 struct got_object_qid *qid, *pid;
10959 struct got_update_progress_arg upa;
10960 int *pack_fds = NULL;
10962 STAILQ_INIT(&commits);
10963 TAILQ_INIT(&merged_paths);
10964 memset(&upa, 0, sizeof(upa));
10966 while ((ch = getopt(argc, argv, "aclX")) != -1) {
10967 switch (ch) {
10968 case 'a':
10969 abort_rebase = 1;
10970 break;
10971 case 'c':
10972 continue_rebase = 1;
10973 break;
10974 case 'l':
10975 list_backups = 1;
10976 break;
10977 case 'X':
10978 delete_backups = 1;
10979 break;
10980 default:
10981 usage_rebase();
10982 /* NOTREACHED */
10986 argc -= optind;
10987 argv += optind;
10989 #ifndef PROFILE
10990 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
10991 "unveil", NULL) == -1)
10992 err(1, "pledge");
10993 #endif
10994 if (list_backups) {
10995 if (abort_rebase)
10996 option_conflict('l', 'a');
10997 if (continue_rebase)
10998 option_conflict('l', 'c');
10999 if (delete_backups)
11000 option_conflict('l', 'X');
11001 if (argc != 0 && argc != 1)
11002 usage_rebase();
11003 } else if (delete_backups) {
11004 if (abort_rebase)
11005 option_conflict('X', 'a');
11006 if (continue_rebase)
11007 option_conflict('X', 'c');
11008 if (list_backups)
11009 option_conflict('l', 'X');
11010 if (argc != 0 && argc != 1)
11011 usage_rebase();
11012 } else {
11013 if (abort_rebase && continue_rebase)
11014 usage_rebase();
11015 else if (abort_rebase || continue_rebase) {
11016 if (argc != 0)
11017 usage_rebase();
11018 } else if (argc != 1)
11019 usage_rebase();
11022 cwd = getcwd(NULL, 0);
11023 if (cwd == NULL) {
11024 error = got_error_from_errno("getcwd");
11025 goto done;
11028 error = got_repo_pack_fds_open(&pack_fds);
11029 if (error != NULL)
11030 goto done;
11032 error = got_worktree_open(&worktree, cwd);
11033 if (error) {
11034 if (list_backups || delete_backups) {
11035 if (error->code != GOT_ERR_NOT_WORKTREE)
11036 goto done;
11037 } else {
11038 if (error->code == GOT_ERR_NOT_WORKTREE)
11039 error = wrap_not_worktree_error(error,
11040 "rebase", cwd);
11041 goto done;
11045 error = get_gitconfig_path(&gitconfig_path);
11046 if (error)
11047 goto done;
11048 error = got_repo_open(&repo,
11049 worktree ? got_worktree_get_repo_path(worktree) : cwd,
11050 gitconfig_path, pack_fds);
11051 if (error != NULL)
11052 goto done;
11054 if (worktree != NULL && !list_backups && !delete_backups) {
11055 error = worktree_has_logmsg_ref("rebase", worktree, repo);
11056 if (error)
11057 goto done;
11060 error = get_author(&committer, repo, worktree);
11061 if (error && error->code != GOT_ERR_COMMIT_NO_AUTHOR)
11062 goto done;
11064 error = apply_unveil(got_repo_get_path(repo), 0,
11065 worktree ? got_worktree_get_root_path(worktree) : NULL);
11066 if (error)
11067 goto done;
11069 if (list_backups || delete_backups) {
11070 error = process_backup_refs(
11071 GOT_WORKTREE_REBASE_BACKUP_REF_PREFIX,
11072 argc == 1 ? argv[0] : NULL, delete_backups, repo);
11073 goto done; /* nothing else to do */
11076 error = got_worktree_histedit_in_progress(&histedit_in_progress,
11077 worktree);
11078 if (error)
11079 goto done;
11080 if (histedit_in_progress) {
11081 error = got_error(GOT_ERR_HISTEDIT_BUSY);
11082 goto done;
11085 error = got_worktree_merge_in_progress(&merge_in_progress,
11086 worktree, repo);
11087 if (error)
11088 goto done;
11089 if (merge_in_progress) {
11090 error = got_error(GOT_ERR_MERGE_BUSY);
11091 goto done;
11094 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
11095 if (error)
11096 goto done;
11098 if (abort_rebase) {
11099 if (!rebase_in_progress) {
11100 error = got_error(GOT_ERR_NOT_REBASING);
11101 goto done;
11103 error = got_worktree_rebase_continue(&resume_commit_id,
11104 &new_base_branch, &tmp_branch, &branch, &fileindex,
11105 worktree, repo);
11106 if (error)
11107 goto done;
11108 printf("Switching work tree to %s\n",
11109 got_ref_get_symref_target(new_base_branch));
11110 error = got_worktree_rebase_abort(worktree, fileindex, repo,
11111 new_base_branch, abort_progress, &upa);
11112 if (error)
11113 goto done;
11114 printf("Rebase of %s aborted\n", got_ref_get_name(branch));
11115 print_merge_progress_stats(&upa);
11116 goto done; /* nothing else to do */
11119 if (continue_rebase) {
11120 if (!rebase_in_progress) {
11121 error = got_error(GOT_ERR_NOT_REBASING);
11122 goto done;
11124 error = got_worktree_rebase_continue(&resume_commit_id,
11125 &new_base_branch, &tmp_branch, &branch, &fileindex,
11126 worktree, repo);
11127 if (error)
11128 goto done;
11130 error = rebase_commit(NULL, worktree, fileindex, tmp_branch,
11131 committer, resume_commit_id, repo);
11132 if (error)
11133 goto done;
11135 yca_id = got_object_id_dup(resume_commit_id);
11136 if (yca_id == NULL) {
11137 error = got_error_from_errno("got_object_id_dup");
11138 goto done;
11140 } else {
11141 error = got_ref_open(&branch, repo, argv[0], 0);
11142 if (error != NULL)
11143 goto done;
11144 if (strncmp(got_ref_get_name(branch), "refs/heads/", 11) != 0) {
11145 error = got_error_msg(GOT_ERR_COMMIT_BRANCH,
11146 "will not rebase a branch which lives outside "
11147 "the \"refs/heads/\" reference namespace");
11148 goto done;
11152 error = got_ref_resolve(&branch_head_commit_id, repo, branch);
11153 if (error)
11154 goto done;
11156 if (!continue_rebase) {
11157 struct got_object_id *base_commit_id;
11159 error = got_ref_open(&head_ref, repo,
11160 got_worktree_get_head_ref_name(worktree), 0);
11161 if (error)
11162 goto done;
11163 error = got_ref_resolve(&head_commit_id, repo, head_ref);
11164 if (error)
11165 goto done;
11166 base_commit_id = got_worktree_get_base_commit_id(worktree);
11167 if (got_object_id_cmp(base_commit_id, head_commit_id) != 0) {
11168 error = got_error(GOT_ERR_REBASE_OUT_OF_DATE);
11169 goto done;
11172 error = got_commit_graph_find_youngest_common_ancestor(&yca_id,
11173 base_commit_id, branch_head_commit_id, 1, repo,
11174 check_cancelled, NULL);
11175 if (error) {
11176 if (error->code == GOT_ERR_ANCESTRY) {
11177 error = got_error_msg(GOT_ERR_ANCESTRY,
11178 "specified branch shares no common "
11179 "ancestry with work tree's branch");
11181 goto done;
11184 error = check_same_branch(base_commit_id, branch, yca_id, repo);
11185 if (error) {
11186 if (error->code != GOT_ERR_ANCESTRY)
11187 goto done;
11188 error = NULL;
11189 } else {
11190 struct got_pathlist_head paths;
11191 printf("%s is already based on %s\n",
11192 got_ref_get_name(branch),
11193 got_worktree_get_head_ref_name(worktree));
11194 error = switch_head_ref(branch, branch_head_commit_id,
11195 worktree, repo);
11196 if (error)
11197 goto done;
11198 error = got_worktree_set_base_commit_id(worktree, repo,
11199 branch_head_commit_id);
11200 if (error)
11201 goto done;
11202 TAILQ_INIT(&paths);
11203 error = got_pathlist_append(&paths, "", NULL);
11204 if (error)
11205 goto done;
11206 error = got_worktree_checkout_files(worktree,
11207 &paths, repo, update_progress, &upa,
11208 check_cancelled, NULL);
11209 got_pathlist_free(&paths, GOT_PATHLIST_FREE_NONE);
11210 if (error)
11211 goto done;
11212 if (upa.did_something) {
11213 char *id_str;
11214 error = got_object_id_str(&id_str,
11215 branch_head_commit_id);
11216 if (error)
11217 goto done;
11218 printf("Updated to %s: %s\n",
11219 got_worktree_get_head_ref_name(worktree),
11220 id_str);
11221 free(id_str);
11222 } else
11223 printf("Already up-to-date\n");
11224 print_update_progress_stats(&upa);
11225 goto done;
11229 commit_id = branch_head_commit_id;
11230 error = got_object_open_as_commit(&commit, repo, commit_id);
11231 if (error)
11232 goto done;
11234 parent_ids = got_object_commit_get_parent_ids(commit);
11235 pid = STAILQ_FIRST(parent_ids);
11236 if (pid) {
11237 error = collect_commits(&commits, commit_id, &pid->id,
11238 yca_id, got_worktree_get_path_prefix(worktree),
11239 GOT_ERR_REBASE_PATH, repo);
11240 if (error)
11241 goto done;
11244 got_object_commit_close(commit);
11245 commit = NULL;
11247 if (!continue_rebase) {
11248 error = got_worktree_rebase_prepare(&new_base_branch,
11249 &tmp_branch, &fileindex, worktree, branch, repo);
11250 if (error)
11251 goto done;
11254 if (STAILQ_EMPTY(&commits)) {
11255 if (continue_rebase) {
11256 error = rebase_complete(worktree, fileindex,
11257 branch, tmp_branch, repo, create_backup);
11258 goto done;
11259 } else {
11260 /* Fast-forward the reference of the branch. */
11261 struct got_object_id *new_head_commit_id;
11262 char *id_str;
11263 error = got_ref_resolve(&new_head_commit_id, repo,
11264 new_base_branch);
11265 if (error)
11266 goto done;
11267 error = got_object_id_str(&id_str, new_head_commit_id);
11268 if (error)
11269 goto done;
11270 printf("Forwarding %s to commit %s\n",
11271 got_ref_get_name(branch), id_str);
11272 free(id_str);
11273 error = got_ref_change_ref(branch,
11274 new_head_commit_id);
11275 if (error)
11276 goto done;
11277 /* No backup needed since objects did not change. */
11278 create_backup = 0;
11282 pid = NULL;
11283 STAILQ_FOREACH(qid, &commits, entry) {
11285 commit_id = &qid->id;
11286 parent_id = pid ? &pid->id : yca_id;
11287 pid = qid;
11289 memset(&upa, 0, sizeof(upa));
11290 error = got_worktree_rebase_merge_files(&merged_paths,
11291 worktree, fileindex, parent_id, commit_id, repo,
11292 update_progress, &upa, check_cancelled, NULL);
11293 if (error)
11294 goto done;
11296 print_merge_progress_stats(&upa);
11297 if (upa.conflicts > 0 || upa.missing > 0 ||
11298 upa.not_deleted > 0 || upa.unversioned > 0) {
11299 if (upa.conflicts > 0) {
11300 error = show_rebase_merge_conflict(&qid->id,
11301 repo);
11302 if (error)
11303 goto done;
11305 got_pathlist_free(&merged_paths, GOT_PATHLIST_FREE_PATH);
11306 break;
11309 error = rebase_commit(&merged_paths, worktree, fileindex,
11310 tmp_branch, committer, commit_id, repo);
11311 got_pathlist_free(&merged_paths, GOT_PATHLIST_FREE_PATH);
11312 if (error)
11313 goto done;
11316 if (upa.conflicts > 0 || upa.missing > 0 ||
11317 upa.not_deleted > 0 || upa.unversioned > 0) {
11318 error = got_worktree_rebase_postpone(worktree, fileindex);
11319 if (error)
11320 goto done;
11321 if (upa.conflicts > 0 && upa.missing == 0 &&
11322 upa.not_deleted == 0 && upa.unversioned == 0) {
11323 error = got_error_msg(GOT_ERR_CONFLICTS,
11324 "conflicts must be resolved before rebasing "
11325 "can continue");
11326 } else if (upa.conflicts > 0) {
11327 error = got_error_msg(GOT_ERR_CONFLICTS,
11328 "conflicts must be resolved before rebasing "
11329 "can continue; changes destined for some "
11330 "files were not yet merged and should be "
11331 "merged manually if required before the "
11332 "rebase operation is continued");
11333 } else {
11334 error = got_error_msg(GOT_ERR_CONFLICTS,
11335 "changes destined for some files were not "
11336 "yet merged and should be merged manually "
11337 "if required before the rebase operation "
11338 "is continued");
11340 } else
11341 error = rebase_complete(worktree, fileindex, branch,
11342 tmp_branch, repo, create_backup);
11343 done:
11344 free(cwd);
11345 free(committer);
11346 free(gitconfig_path);
11347 got_object_id_queue_free(&commits);
11348 free(branch_head_commit_id);
11349 free(resume_commit_id);
11350 free(head_commit_id);
11351 free(yca_id);
11352 if (commit)
11353 got_object_commit_close(commit);
11354 if (branch)
11355 got_ref_close(branch);
11356 if (new_base_branch)
11357 got_ref_close(new_base_branch);
11358 if (tmp_branch)
11359 got_ref_close(tmp_branch);
11360 if (head_ref)
11361 got_ref_close(head_ref);
11362 if (worktree)
11363 got_worktree_close(worktree);
11364 if (repo) {
11365 const struct got_error *close_err = got_repo_close(repo);
11366 if (error == NULL)
11367 error = close_err;
11369 if (pack_fds) {
11370 const struct got_error *pack_err =
11371 got_repo_pack_fds_close(pack_fds);
11372 if (error == NULL)
11373 error = pack_err;
11375 return error;
11378 __dead static void
11379 usage_histedit(void)
11381 fprintf(stderr, "usage: %s histedit [-acdeflmX] [-F histedit-script] "
11382 "[branch]\n", getprogname());
11383 exit(1);
11386 #define GOT_HISTEDIT_PICK 'p'
11387 #define GOT_HISTEDIT_EDIT 'e'
11388 #define GOT_HISTEDIT_FOLD 'f'
11389 #define GOT_HISTEDIT_DROP 'd'
11390 #define GOT_HISTEDIT_MESG 'm'
11392 static const struct got_histedit_cmd {
11393 unsigned char code;
11394 const char *name;
11395 const char *desc;
11396 } got_histedit_cmds[] = {
11397 { GOT_HISTEDIT_PICK, "pick", "use commit" },
11398 { GOT_HISTEDIT_EDIT, "edit", "use commit but stop for amending" },
11399 { GOT_HISTEDIT_FOLD, "fold", "combine with next commit that will "
11400 "be used" },
11401 { GOT_HISTEDIT_DROP, "drop", "remove commit from history" },
11402 { GOT_HISTEDIT_MESG, "mesg",
11403 "single-line log message for commit above (open editor if empty)" },
11406 struct got_histedit_list_entry {
11407 TAILQ_ENTRY(got_histedit_list_entry) entry;
11408 struct got_object_id *commit_id;
11409 const struct got_histedit_cmd *cmd;
11410 char *logmsg;
11412 TAILQ_HEAD(got_histedit_list, got_histedit_list_entry);
11414 static const struct got_error *
11415 histedit_write_commit(struct got_object_id *commit_id, const char *cmdname,
11416 FILE *f, struct got_repository *repo)
11418 const struct got_error *err = NULL;
11419 char *logmsg = NULL, *id_str = NULL;
11420 struct got_commit_object *commit = NULL;
11421 int n;
11423 err = got_object_open_as_commit(&commit, repo, commit_id);
11424 if (err)
11425 goto done;
11427 err = get_short_logmsg(&logmsg, 34, commit);
11428 if (err)
11429 goto done;
11431 err = got_object_id_str(&id_str, commit_id);
11432 if (err)
11433 goto done;
11435 n = fprintf(f, "%s %s %s\n", cmdname, id_str, logmsg);
11436 if (n < 0)
11437 err = got_ferror(f, GOT_ERR_IO);
11438 done:
11439 if (commit)
11440 got_object_commit_close(commit);
11441 free(id_str);
11442 free(logmsg);
11443 return err;
11446 static const struct got_error *
11447 histedit_write_commit_list(struct got_object_id_queue *commits,
11448 FILE *f, int edit_logmsg_only, int fold_only, int drop_only,
11449 int edit_only, struct got_repository *repo)
11451 const struct got_error *err = NULL;
11452 struct got_object_qid *qid;
11453 const char *histedit_cmd = NULL;
11455 if (STAILQ_EMPTY(commits))
11456 return got_error(GOT_ERR_EMPTY_HISTEDIT);
11458 STAILQ_FOREACH(qid, commits, entry) {
11459 histedit_cmd = got_histedit_cmds[0].name;
11460 if (drop_only)
11461 histedit_cmd = "drop";
11462 else if (edit_only)
11463 histedit_cmd = "edit";
11464 else if (fold_only && STAILQ_NEXT(qid, entry) != NULL)
11465 histedit_cmd = "fold";
11466 err = histedit_write_commit(&qid->id, histedit_cmd, f, repo);
11467 if (err)
11468 break;
11469 if (edit_logmsg_only) {
11470 int n = fprintf(f, "%c\n", GOT_HISTEDIT_MESG);
11471 if (n < 0) {
11472 err = got_ferror(f, GOT_ERR_IO);
11473 break;
11478 return err;
11481 static const struct got_error *
11482 write_cmd_list(FILE *f, const char *branch_name,
11483 struct got_object_id_queue *commits)
11485 const struct got_error *err = NULL;
11486 size_t i;
11487 int n;
11488 char *id_str;
11489 struct got_object_qid *qid;
11491 qid = STAILQ_FIRST(commits);
11492 err = got_object_id_str(&id_str, &qid->id);
11493 if (err)
11494 return err;
11496 n = fprintf(f,
11497 "# Editing the history of branch '%s' starting at\n"
11498 "# commit %s\n"
11499 "# Commits will be processed in order from top to "
11500 "bottom of this file.\n", branch_name, id_str);
11501 if (n < 0) {
11502 err = got_ferror(f, GOT_ERR_IO);
11503 goto done;
11506 n = fprintf(f, "# Available histedit commands:\n");
11507 if (n < 0) {
11508 err = got_ferror(f, GOT_ERR_IO);
11509 goto done;
11512 for (i = 0; i < nitems(got_histedit_cmds); i++) {
11513 const struct got_histedit_cmd *cmd = &got_histedit_cmds[i];
11514 n = fprintf(f, "# %s (%c): %s\n", cmd->name, cmd->code,
11515 cmd->desc);
11516 if (n < 0) {
11517 err = got_ferror(f, GOT_ERR_IO);
11518 break;
11521 done:
11522 free(id_str);
11523 return err;
11526 static const struct got_error *
11527 histedit_syntax_error(int lineno)
11529 static char msg[42];
11530 int ret;
11532 ret = snprintf(msg, sizeof(msg), "histedit syntax error on line %d",
11533 lineno);
11534 if (ret < 0 || (size_t)ret >= sizeof(msg))
11535 return got_error(GOT_ERR_HISTEDIT_SYNTAX);
11537 return got_error_msg(GOT_ERR_HISTEDIT_SYNTAX, msg);
11540 static const struct got_error *
11541 append_folded_commit_msg(char **new_msg, struct got_histedit_list_entry *hle,
11542 char *logmsg, struct got_repository *repo)
11544 const struct got_error *err;
11545 struct got_commit_object *folded_commit = NULL;
11546 char *id_str, *folded_logmsg = NULL;
11548 err = got_object_id_str(&id_str, hle->commit_id);
11549 if (err)
11550 return err;
11552 err = got_object_open_as_commit(&folded_commit, repo, hle->commit_id);
11553 if (err)
11554 goto done;
11556 err = got_object_commit_get_logmsg(&folded_logmsg, folded_commit);
11557 if (err)
11558 goto done;
11559 if (asprintf(new_msg, "%s%s# log message of folded commit %s: %s",
11560 logmsg ? logmsg : "", logmsg ? "\n" : "", id_str,
11561 folded_logmsg) == -1) {
11562 err = got_error_from_errno("asprintf");
11564 done:
11565 if (folded_commit)
11566 got_object_commit_close(folded_commit);
11567 free(id_str);
11568 free(folded_logmsg);
11569 return err;
11572 static struct got_histedit_list_entry *
11573 get_folded_commits(struct got_histedit_list_entry *hle)
11575 struct got_histedit_list_entry *prev, *folded = NULL;
11577 prev = TAILQ_PREV(hle, got_histedit_list, entry);
11578 while (prev && (prev->cmd->code == GOT_HISTEDIT_FOLD ||
11579 prev->cmd->code == GOT_HISTEDIT_DROP)) {
11580 if (prev->cmd->code == GOT_HISTEDIT_FOLD)
11581 folded = prev;
11582 prev = TAILQ_PREV(prev, got_histedit_list, entry);
11585 return folded;
11588 static const struct got_error *
11589 histedit_edit_logmsg(struct got_histedit_list_entry *hle,
11590 struct got_repository *repo)
11592 char *logmsg_path = NULL, *id_str = NULL, *orig_logmsg = NULL;
11593 char *logmsg = NULL, *new_msg = NULL, *editor = NULL;
11594 const struct got_error *err = NULL;
11595 struct got_commit_object *commit = NULL;
11596 int logmsg_len;
11597 int fd;
11598 struct got_histedit_list_entry *folded = NULL;
11600 err = got_object_open_as_commit(&commit, repo, hle->commit_id);
11601 if (err)
11602 return err;
11604 folded = get_folded_commits(hle);
11605 if (folded) {
11606 while (folded != hle) {
11607 if (folded->cmd->code == GOT_HISTEDIT_DROP) {
11608 folded = TAILQ_NEXT(folded, entry);
11609 continue;
11611 err = append_folded_commit_msg(&new_msg, folded,
11612 logmsg, repo);
11613 if (err)
11614 goto done;
11615 free(logmsg);
11616 logmsg = new_msg;
11617 folded = TAILQ_NEXT(folded, entry);
11621 err = got_object_id_str(&id_str, hle->commit_id);
11622 if (err)
11623 goto done;
11624 err = got_object_commit_get_logmsg(&orig_logmsg, commit);
11625 if (err)
11626 goto done;
11627 logmsg_len = asprintf(&new_msg,
11628 "%s\n# original log message of commit %s: %s",
11629 logmsg ? logmsg : "", id_str, orig_logmsg);
11630 if (logmsg_len == -1) {
11631 err = got_error_from_errno("asprintf");
11632 goto done;
11634 free(logmsg);
11635 logmsg = new_msg;
11637 err = got_object_id_str(&id_str, hle->commit_id);
11638 if (err)
11639 goto done;
11641 err = got_opentemp_named_fd(&logmsg_path, &fd,
11642 GOT_TMPDIR_STR "/got-logmsg", "");
11643 if (err)
11644 goto done;
11646 write(fd, logmsg, logmsg_len);
11647 close(fd);
11649 err = get_editor(&editor);
11650 if (err)
11651 goto done;
11653 err = edit_logmsg(&hle->logmsg, editor, logmsg_path, logmsg,
11654 logmsg_len, 0);
11655 if (err) {
11656 if (err->code != GOT_ERR_COMMIT_MSG_EMPTY)
11657 goto done;
11658 err = NULL;
11659 hle->logmsg = strdup(new_msg);
11660 if (hle->logmsg == NULL)
11661 err = got_error_from_errno("strdup");
11663 done:
11664 if (logmsg_path && unlink(logmsg_path) != 0 && err == NULL)
11665 err = got_error_from_errno2("unlink", logmsg_path);
11666 free(logmsg_path);
11667 free(logmsg);
11668 free(orig_logmsg);
11669 free(editor);
11670 if (commit)
11671 got_object_commit_close(commit);
11672 return err;
11675 static const struct got_error *
11676 histedit_parse_list(struct got_histedit_list *histedit_cmds,
11677 FILE *f, struct got_repository *repo)
11679 const struct got_error *err = NULL;
11680 char *line = NULL, *p, *end;
11681 size_t i, size;
11682 ssize_t len;
11683 int lineno = 0, lastcmd = -1;
11684 const struct got_histedit_cmd *cmd;
11685 struct got_object_id *commit_id = NULL;
11686 struct got_histedit_list_entry *hle = NULL;
11688 for (;;) {
11689 len = getline(&line, &size, f);
11690 if (len == -1) {
11691 const struct got_error *getline_err;
11692 if (feof(f))
11693 break;
11694 getline_err = got_error_from_errno("getline");
11695 err = got_ferror(f, getline_err->code);
11696 break;
11698 lineno++;
11699 p = line;
11700 while (isspace((unsigned char)p[0]))
11701 p++;
11702 if (p[0] == '#' || p[0] == '\0') {
11703 free(line);
11704 line = NULL;
11705 continue;
11707 cmd = NULL;
11708 for (i = 0; i < nitems(got_histedit_cmds); i++) {
11709 cmd = &got_histedit_cmds[i];
11710 if (strncmp(cmd->name, p, strlen(cmd->name)) == 0 &&
11711 isspace((unsigned char)p[strlen(cmd->name)])) {
11712 p += strlen(cmd->name);
11713 break;
11715 if (p[0] == cmd->code && isspace((unsigned char)p[1])) {
11716 p++;
11717 break;
11720 if (i == nitems(got_histedit_cmds)) {
11721 err = histedit_syntax_error(lineno);
11722 break;
11724 while (isspace((unsigned char)p[0]))
11725 p++;
11726 if (cmd->code == GOT_HISTEDIT_MESG) {
11727 if (lastcmd != GOT_HISTEDIT_PICK &&
11728 lastcmd != GOT_HISTEDIT_EDIT) {
11729 err = got_error(GOT_ERR_HISTEDIT_CMD);
11730 break;
11732 if (p[0] == '\0') {
11733 err = histedit_edit_logmsg(hle, repo);
11734 if (err)
11735 break;
11736 } else {
11737 hle->logmsg = strdup(p);
11738 if (hle->logmsg == NULL) {
11739 err = got_error_from_errno("strdup");
11740 break;
11743 free(line);
11744 line = NULL;
11745 lastcmd = cmd->code;
11746 continue;
11747 } else {
11748 end = p;
11749 while (end[0] && !isspace((unsigned char)end[0]))
11750 end++;
11751 *end = '\0';
11753 err = got_object_resolve_id_str(&commit_id, repo, p);
11754 if (err) {
11755 /* override error code */
11756 err = histedit_syntax_error(lineno);
11757 break;
11760 hle = malloc(sizeof(*hle));
11761 if (hle == NULL) {
11762 err = got_error_from_errno("malloc");
11763 break;
11765 hle->cmd = cmd;
11766 hle->commit_id = commit_id;
11767 hle->logmsg = NULL;
11768 commit_id = NULL;
11769 free(line);
11770 line = NULL;
11771 TAILQ_INSERT_TAIL(histedit_cmds, hle, entry);
11772 lastcmd = cmd->code;
11775 free(line);
11776 free(commit_id);
11777 return err;
11780 static const struct got_error *
11781 histedit_check_script(struct got_histedit_list *histedit_cmds,
11782 struct got_object_id_queue *commits, struct got_repository *repo)
11784 const struct got_error *err = NULL;
11785 struct got_object_qid *qid;
11786 struct got_histedit_list_entry *hle;
11787 static char msg[92];
11788 char *id_str;
11790 if (TAILQ_EMPTY(histedit_cmds))
11791 return got_error_msg(GOT_ERR_EMPTY_HISTEDIT,
11792 "histedit script contains no commands");
11793 if (STAILQ_EMPTY(commits))
11794 return got_error(GOT_ERR_EMPTY_HISTEDIT);
11796 TAILQ_FOREACH(hle, histedit_cmds, entry) {
11797 struct got_histedit_list_entry *hle2;
11798 TAILQ_FOREACH(hle2, histedit_cmds, entry) {
11799 if (hle == hle2)
11800 continue;
11801 if (got_object_id_cmp(hle->commit_id,
11802 hle2->commit_id) != 0)
11803 continue;
11804 err = got_object_id_str(&id_str, hle->commit_id);
11805 if (err)
11806 return err;
11807 snprintf(msg, sizeof(msg), "commit %s is listed "
11808 "more than once in histedit script", id_str);
11809 free(id_str);
11810 return got_error_msg(GOT_ERR_HISTEDIT_CMD, msg);
11814 STAILQ_FOREACH(qid, commits, entry) {
11815 TAILQ_FOREACH(hle, histedit_cmds, entry) {
11816 if (got_object_id_cmp(&qid->id, hle->commit_id) == 0)
11817 break;
11819 if (hle == NULL) {
11820 err = got_object_id_str(&id_str, &qid->id);
11821 if (err)
11822 return err;
11823 snprintf(msg, sizeof(msg),
11824 "commit %s missing from histedit script", id_str);
11825 free(id_str);
11826 return got_error_msg(GOT_ERR_HISTEDIT_CMD, msg);
11830 hle = TAILQ_LAST(histedit_cmds, got_histedit_list);
11831 if (hle && hle->cmd->code == GOT_HISTEDIT_FOLD)
11832 return got_error_msg(GOT_ERR_HISTEDIT_CMD,
11833 "last commit in histedit script cannot be folded");
11835 return NULL;
11838 static const struct got_error *
11839 histedit_run_editor(struct got_histedit_list *histedit_cmds,
11840 const char *path, struct got_object_id_queue *commits,
11841 struct got_repository *repo)
11843 const struct got_error *err = NULL;
11844 char *editor;
11845 FILE *f = NULL;
11847 err = get_editor(&editor);
11848 if (err)
11849 return err;
11851 if (spawn_editor(editor, path) == -1) {
11852 err = got_error_from_errno("failed spawning editor");
11853 goto done;
11856 f = fopen(path, "re");
11857 if (f == NULL) {
11858 err = got_error_from_errno("fopen");
11859 goto done;
11861 err = histedit_parse_list(histedit_cmds, f, repo);
11862 if (err)
11863 goto done;
11865 err = histedit_check_script(histedit_cmds, commits, repo);
11866 done:
11867 if (f && fclose(f) == EOF && err == NULL)
11868 err = got_error_from_errno("fclose");
11869 free(editor);
11870 return err;
11873 static const struct got_error *
11874 histedit_edit_list_retry(struct got_histedit_list *, const struct got_error *,
11875 struct got_object_id_queue *, const char *, const char *,
11876 struct got_repository *);
11878 static const struct got_error *
11879 histedit_edit_script(struct got_histedit_list *histedit_cmds,
11880 struct got_object_id_queue *commits, const char *branch_name,
11881 int edit_logmsg_only, int fold_only, int drop_only, int edit_only,
11882 struct got_repository *repo)
11884 const struct got_error *err;
11885 FILE *f = NULL;
11886 char *path = NULL;
11888 err = got_opentemp_named(&path, &f, "got-histedit", "");
11889 if (err)
11890 return err;
11892 err = write_cmd_list(f, branch_name, commits);
11893 if (err)
11894 goto done;
11896 err = histedit_write_commit_list(commits, f, edit_logmsg_only,
11897 fold_only, drop_only, edit_only, repo);
11898 if (err)
11899 goto done;
11901 if (drop_only || edit_logmsg_only || fold_only || edit_only) {
11902 rewind(f);
11903 err = histedit_parse_list(histedit_cmds, f, repo);
11904 } else {
11905 if (fclose(f) == EOF) {
11906 err = got_error_from_errno("fclose");
11907 goto done;
11909 f = NULL;
11910 err = histedit_run_editor(histedit_cmds, path, commits, repo);
11911 if (err) {
11912 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
11913 err->code != GOT_ERR_HISTEDIT_CMD)
11914 goto done;
11915 err = histedit_edit_list_retry(histedit_cmds, err,
11916 commits, path, branch_name, repo);
11919 done:
11920 if (f && fclose(f) == EOF && err == NULL)
11921 err = got_error_from_errno("fclose");
11922 if (path && unlink(path) != 0 && err == NULL)
11923 err = got_error_from_errno2("unlink", path);
11924 free(path);
11925 return err;
11928 static const struct got_error *
11929 histedit_save_list(struct got_histedit_list *histedit_cmds,
11930 struct got_worktree *worktree, struct got_repository *repo)
11932 const struct got_error *err = NULL;
11933 char *path = NULL;
11934 FILE *f = NULL;
11935 struct got_histedit_list_entry *hle;
11936 struct got_commit_object *commit = NULL;
11938 err = got_worktree_get_histedit_script_path(&path, worktree);
11939 if (err)
11940 return err;
11942 f = fopen(path, "we");
11943 if (f == NULL) {
11944 err = got_error_from_errno2("fopen", path);
11945 goto done;
11947 TAILQ_FOREACH(hle, histedit_cmds, entry) {
11948 err = histedit_write_commit(hle->commit_id, hle->cmd->name, f,
11949 repo);
11950 if (err)
11951 break;
11953 if (hle->logmsg) {
11954 int n = fprintf(f, "%c %s\n",
11955 GOT_HISTEDIT_MESG, hle->logmsg);
11956 if (n < 0) {
11957 err = got_ferror(f, GOT_ERR_IO);
11958 break;
11962 done:
11963 if (f && fclose(f) == EOF && err == NULL)
11964 err = got_error_from_errno("fclose");
11965 free(path);
11966 if (commit)
11967 got_object_commit_close(commit);
11968 return err;
11971 static void
11972 histedit_free_list(struct got_histedit_list *histedit_cmds)
11974 struct got_histedit_list_entry *hle;
11976 while ((hle = TAILQ_FIRST(histedit_cmds))) {
11977 TAILQ_REMOVE(histedit_cmds, hle, entry);
11978 free(hle);
11982 static const struct got_error *
11983 histedit_load_list(struct got_histedit_list *histedit_cmds,
11984 const char *path, struct got_repository *repo)
11986 const struct got_error *err = NULL;
11987 FILE *f = NULL;
11989 f = fopen(path, "re");
11990 if (f == NULL) {
11991 err = got_error_from_errno2("fopen", path);
11992 goto done;
11995 err = histedit_parse_list(histedit_cmds, f, repo);
11996 done:
11997 if (f && fclose(f) == EOF && err == NULL)
11998 err = got_error_from_errno("fclose");
11999 return err;
12002 static const struct got_error *
12003 histedit_edit_list_retry(struct got_histedit_list *histedit_cmds,
12004 const struct got_error *edit_err, struct got_object_id_queue *commits,
12005 const char *path, const char *branch_name, struct got_repository *repo)
12007 const struct got_error *err = NULL, *prev_err = edit_err;
12008 int resp = ' ';
12010 while (resp != 'c' && resp != 'r' && resp != 'a') {
12011 printf("%s: %s\n(c)ontinue editing, (r)estart editing, "
12012 "or (a)bort: ", getprogname(), prev_err->msg);
12013 resp = getchar();
12014 if (resp == '\n')
12015 resp = getchar();
12016 if (resp == 'c') {
12017 histedit_free_list(histedit_cmds);
12018 err = histedit_run_editor(histedit_cmds, path, commits,
12019 repo);
12020 if (err) {
12021 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
12022 err->code != GOT_ERR_HISTEDIT_CMD)
12023 break;
12024 prev_err = err;
12025 resp = ' ';
12026 continue;
12028 break;
12029 } else if (resp == 'r') {
12030 histedit_free_list(histedit_cmds);
12031 err = histedit_edit_script(histedit_cmds,
12032 commits, branch_name, 0, 0, 0, 0, repo);
12033 if (err) {
12034 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
12035 err->code != GOT_ERR_HISTEDIT_CMD)
12036 break;
12037 prev_err = err;
12038 resp = ' ';
12039 continue;
12041 break;
12042 } else if (resp == 'a') {
12043 err = got_error(GOT_ERR_HISTEDIT_CANCEL);
12044 break;
12045 } else
12046 printf("invalid response '%c'\n", resp);
12049 return err;
12052 static const struct got_error *
12053 histedit_complete(struct got_worktree *worktree,
12054 struct got_fileindex *fileindex, struct got_reference *tmp_branch,
12055 struct got_reference *branch, struct got_repository *repo)
12057 printf("Switching work tree to %s\n",
12058 got_ref_get_symref_target(branch));
12059 return got_worktree_histedit_complete(worktree, fileindex, tmp_branch,
12060 branch, repo);
12063 static const struct got_error *
12064 show_histedit_progress(struct got_commit_object *commit,
12065 struct got_histedit_list_entry *hle, struct got_object_id *new_id)
12067 const struct got_error *err;
12068 char *old_id_str = NULL, *new_id_str = NULL, *logmsg = NULL;
12070 err = got_object_id_str(&old_id_str, hle->commit_id);
12071 if (err)
12072 goto done;
12074 if (new_id) {
12075 err = got_object_id_str(&new_id_str, new_id);
12076 if (err)
12077 goto done;
12080 old_id_str[12] = '\0';
12081 if (new_id_str)
12082 new_id_str[12] = '\0';
12084 if (hle->logmsg) {
12085 logmsg = strdup(hle->logmsg);
12086 if (logmsg == NULL) {
12087 err = got_error_from_errno("strdup");
12088 goto done;
12090 trim_logmsg(logmsg, 42);
12091 } else {
12092 err = get_short_logmsg(&logmsg, 42, commit);
12093 if (err)
12094 goto done;
12097 switch (hle->cmd->code) {
12098 case GOT_HISTEDIT_PICK:
12099 case GOT_HISTEDIT_EDIT:
12100 printf("%s -> %s: %s\n", old_id_str,
12101 new_id_str ? new_id_str : "no-op change", logmsg);
12102 break;
12103 case GOT_HISTEDIT_DROP:
12104 case GOT_HISTEDIT_FOLD:
12105 printf("%s -> %s commit: %s\n", old_id_str, hle->cmd->name,
12106 logmsg);
12107 break;
12108 default:
12109 break;
12111 done:
12112 free(old_id_str);
12113 free(new_id_str);
12114 return err;
12117 static const struct got_error *
12118 histedit_commit(struct got_pathlist_head *merged_paths,
12119 struct got_worktree *worktree, struct got_fileindex *fileindex,
12120 struct got_reference *tmp_branch, struct got_histedit_list_entry *hle,
12121 const char *committer, struct got_repository *repo)
12123 const struct got_error *err;
12124 struct got_commit_object *commit;
12125 struct got_object_id *new_commit_id;
12127 if ((hle->cmd->code == GOT_HISTEDIT_EDIT || get_folded_commits(hle))
12128 && hle->logmsg == NULL) {
12129 err = histedit_edit_logmsg(hle, repo);
12130 if (err)
12131 return err;
12134 err = got_object_open_as_commit(&commit, repo, hle->commit_id);
12135 if (err)
12136 return err;
12138 err = got_worktree_histedit_commit(&new_commit_id, merged_paths,
12139 worktree, fileindex, tmp_branch, committer, commit, hle->commit_id,
12140 hle->logmsg, repo);
12141 if (err) {
12142 if (err->code != GOT_ERR_COMMIT_NO_CHANGES)
12143 goto done;
12144 err = show_histedit_progress(commit, hle, NULL);
12145 } else {
12146 err = show_histedit_progress(commit, hle, new_commit_id);
12147 free(new_commit_id);
12149 done:
12150 got_object_commit_close(commit);
12151 return err;
12154 static const struct got_error *
12155 histedit_skip_commit(struct got_histedit_list_entry *hle,
12156 struct got_worktree *worktree, struct got_repository *repo)
12158 const struct got_error *error;
12159 struct got_commit_object *commit;
12161 error = got_worktree_histedit_skip_commit(worktree, hle->commit_id,
12162 repo);
12163 if (error)
12164 return error;
12166 error = got_object_open_as_commit(&commit, repo, hle->commit_id);
12167 if (error)
12168 return error;
12170 error = show_histedit_progress(commit, hle, NULL);
12171 got_object_commit_close(commit);
12172 return error;
12175 static const struct got_error *
12176 check_local_changes(void *arg, unsigned char status,
12177 unsigned char staged_status, const char *path,
12178 struct got_object_id *blob_id, struct got_object_id *staged_blob_id,
12179 struct got_object_id *commit_id, int dirfd, const char *de_name)
12181 int *have_local_changes = arg;
12183 switch (status) {
12184 case GOT_STATUS_ADD:
12185 case GOT_STATUS_DELETE:
12186 case GOT_STATUS_MODIFY:
12187 case GOT_STATUS_CONFLICT:
12188 *have_local_changes = 1;
12189 return got_error(GOT_ERR_CANCELLED);
12190 default:
12191 break;
12194 switch (staged_status) {
12195 case GOT_STATUS_ADD:
12196 case GOT_STATUS_DELETE:
12197 case GOT_STATUS_MODIFY:
12198 *have_local_changes = 1;
12199 return got_error(GOT_ERR_CANCELLED);
12200 default:
12201 break;
12204 return NULL;
12207 static const struct got_error *
12208 cmd_histedit(int argc, char *argv[])
12210 const struct got_error *error = NULL;
12211 struct got_worktree *worktree = NULL;
12212 struct got_fileindex *fileindex = NULL;
12213 struct got_repository *repo = NULL;
12214 char *cwd = NULL, *committer = NULL, *gitconfig_path = NULL;
12215 struct got_reference *branch = NULL;
12216 struct got_reference *tmp_branch = NULL;
12217 struct got_object_id *resume_commit_id = NULL;
12218 struct got_object_id *base_commit_id = NULL;
12219 struct got_object_id *head_commit_id = NULL;
12220 struct got_commit_object *commit = NULL;
12221 int ch, rebase_in_progress = 0, merge_in_progress = 0;
12222 struct got_update_progress_arg upa;
12223 int edit_in_progress = 0, abort_edit = 0, continue_edit = 0;
12224 int drop_only = 0, edit_logmsg_only = 0, fold_only = 0, edit_only = 0;
12225 int list_backups = 0, delete_backups = 0;
12226 const char *edit_script_path = NULL;
12227 struct got_object_id_queue commits;
12228 struct got_pathlist_head merged_paths;
12229 const struct got_object_id_queue *parent_ids;
12230 struct got_object_qid *pid;
12231 struct got_histedit_list histedit_cmds;
12232 struct got_histedit_list_entry *hle;
12233 int *pack_fds = NULL;
12235 STAILQ_INIT(&commits);
12236 TAILQ_INIT(&histedit_cmds);
12237 TAILQ_INIT(&merged_paths);
12238 memset(&upa, 0, sizeof(upa));
12240 while ((ch = getopt(argc, argv, "acdeF:flmX")) != -1) {
12241 switch (ch) {
12242 case 'a':
12243 abort_edit = 1;
12244 break;
12245 case 'c':
12246 continue_edit = 1;
12247 break;
12248 case 'd':
12249 drop_only = 1;
12250 break;
12251 case 'e':
12252 edit_only = 1;
12253 break;
12254 case 'F':
12255 edit_script_path = optarg;
12256 break;
12257 case 'f':
12258 fold_only = 1;
12259 break;
12260 case 'l':
12261 list_backups = 1;
12262 break;
12263 case 'm':
12264 edit_logmsg_only = 1;
12265 break;
12266 case 'X':
12267 delete_backups = 1;
12268 break;
12269 default:
12270 usage_histedit();
12271 /* NOTREACHED */
12275 argc -= optind;
12276 argv += optind;
12278 #ifndef PROFILE
12279 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
12280 "unveil", NULL) == -1)
12281 err(1, "pledge");
12282 #endif
12283 if (abort_edit && continue_edit)
12284 option_conflict('a', 'c');
12285 if (edit_script_path && edit_logmsg_only)
12286 option_conflict('F', 'm');
12287 if (abort_edit && edit_logmsg_only)
12288 option_conflict('a', 'm');
12289 if (continue_edit && edit_logmsg_only)
12290 option_conflict('c', 'm');
12291 if (abort_edit && fold_only)
12292 option_conflict('a', 'f');
12293 if (continue_edit && fold_only)
12294 option_conflict('c', 'f');
12295 if (fold_only && edit_logmsg_only)
12296 option_conflict('f', 'm');
12297 if (edit_script_path && fold_only)
12298 option_conflict('F', 'f');
12299 if (abort_edit && edit_only)
12300 option_conflict('a', 'e');
12301 if (continue_edit && edit_only)
12302 option_conflict('c', 'e');
12303 if (edit_only && edit_logmsg_only)
12304 option_conflict('e', 'm');
12305 if (edit_script_path && edit_only)
12306 option_conflict('F', 'e');
12307 if (fold_only && edit_only)
12308 option_conflict('f', 'e');
12309 if (drop_only && abort_edit)
12310 option_conflict('d', 'a');
12311 if (drop_only && continue_edit)
12312 option_conflict('d', 'c');
12313 if (drop_only && edit_logmsg_only)
12314 option_conflict('d', 'm');
12315 if (drop_only && edit_only)
12316 option_conflict('d', 'e');
12317 if (drop_only && edit_script_path)
12318 option_conflict('d', 'F');
12319 if (drop_only && fold_only)
12320 option_conflict('d', 'f');
12321 if (list_backups) {
12322 if (abort_edit)
12323 option_conflict('l', 'a');
12324 if (continue_edit)
12325 option_conflict('l', 'c');
12326 if (edit_script_path)
12327 option_conflict('l', 'F');
12328 if (edit_logmsg_only)
12329 option_conflict('l', 'm');
12330 if (drop_only)
12331 option_conflict('l', 'd');
12332 if (fold_only)
12333 option_conflict('l', 'f');
12334 if (edit_only)
12335 option_conflict('l', 'e');
12336 if (delete_backups)
12337 option_conflict('l', 'X');
12338 if (argc != 0 && argc != 1)
12339 usage_histedit();
12340 } else if (delete_backups) {
12341 if (abort_edit)
12342 option_conflict('X', 'a');
12343 if (continue_edit)
12344 option_conflict('X', 'c');
12345 if (drop_only)
12346 option_conflict('X', 'd');
12347 if (edit_script_path)
12348 option_conflict('X', 'F');
12349 if (edit_logmsg_only)
12350 option_conflict('X', 'm');
12351 if (fold_only)
12352 option_conflict('X', 'f');
12353 if (edit_only)
12354 option_conflict('X', 'e');
12355 if (list_backups)
12356 option_conflict('X', 'l');
12357 if (argc != 0 && argc != 1)
12358 usage_histedit();
12359 } else if (argc != 0)
12360 usage_histedit();
12363 * This command cannot apply unveil(2) in all cases because the
12364 * user may choose to run an editor to edit the histedit script
12365 * and to edit individual commit log messages.
12366 * unveil(2) traverses exec(2); if an editor is used we have to
12367 * apply unveil after edit script and log messages have been written.
12368 * XXX TODO: Make use of unveil(2) where possible.
12371 cwd = getcwd(NULL, 0);
12372 if (cwd == NULL) {
12373 error = got_error_from_errno("getcwd");
12374 goto done;
12377 error = got_repo_pack_fds_open(&pack_fds);
12378 if (error != NULL)
12379 goto done;
12381 error = got_worktree_open(&worktree, cwd);
12382 if (error) {
12383 if (list_backups || delete_backups) {
12384 if (error->code != GOT_ERR_NOT_WORKTREE)
12385 goto done;
12386 } else {
12387 if (error->code == GOT_ERR_NOT_WORKTREE)
12388 error = wrap_not_worktree_error(error,
12389 "histedit", cwd);
12390 goto done;
12394 if (list_backups || delete_backups) {
12395 error = got_repo_open(&repo,
12396 worktree ? got_worktree_get_repo_path(worktree) : cwd,
12397 NULL, pack_fds);
12398 if (error != NULL)
12399 goto done;
12400 error = apply_unveil(got_repo_get_path(repo), 0,
12401 worktree ? got_worktree_get_root_path(worktree) : NULL);
12402 if (error)
12403 goto done;
12404 error = process_backup_refs(
12405 GOT_WORKTREE_HISTEDIT_BACKUP_REF_PREFIX,
12406 argc == 1 ? argv[0] : NULL, delete_backups, repo);
12407 goto done; /* nothing else to do */
12410 error = get_gitconfig_path(&gitconfig_path);
12411 if (error)
12412 goto done;
12413 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
12414 gitconfig_path, pack_fds);
12415 if (error != NULL)
12416 goto done;
12418 if (worktree != NULL && !list_backups && !delete_backups) {
12419 error = worktree_has_logmsg_ref("histedit", worktree, repo);
12420 if (error)
12421 goto done;
12424 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
12425 if (error)
12426 goto done;
12427 if (rebase_in_progress) {
12428 error = got_error(GOT_ERR_REBASING);
12429 goto done;
12432 error = got_worktree_merge_in_progress(&merge_in_progress, worktree,
12433 repo);
12434 if (error)
12435 goto done;
12436 if (merge_in_progress) {
12437 error = got_error(GOT_ERR_MERGE_BUSY);
12438 goto done;
12441 error = got_worktree_histedit_in_progress(&edit_in_progress, worktree);
12442 if (error)
12443 goto done;
12445 if (edit_in_progress && edit_logmsg_only) {
12446 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
12447 "histedit operation is in progress in this "
12448 "work tree and must be continued or aborted "
12449 "before the -m option can be used");
12450 goto done;
12452 if (edit_in_progress && drop_only) {
12453 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
12454 "histedit operation is in progress in this "
12455 "work tree and must be continued or aborted "
12456 "before the -d option can be used");
12457 goto done;
12459 if (edit_in_progress && fold_only) {
12460 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
12461 "histedit operation is in progress in this "
12462 "work tree and must be continued or aborted "
12463 "before the -f option can be used");
12464 goto done;
12466 if (edit_in_progress && edit_only) {
12467 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
12468 "histedit operation is in progress in this "
12469 "work tree and must be continued or aborted "
12470 "before the -e option can be used");
12471 goto done;
12474 if (edit_in_progress && abort_edit) {
12475 error = got_worktree_histedit_continue(&resume_commit_id,
12476 &tmp_branch, &branch, &base_commit_id, &fileindex,
12477 worktree, repo);
12478 if (error)
12479 goto done;
12480 printf("Switching work tree to %s\n",
12481 got_ref_get_symref_target(branch));
12482 error = got_worktree_histedit_abort(worktree, fileindex, repo,
12483 branch, base_commit_id, abort_progress, &upa);
12484 if (error)
12485 goto done;
12486 printf("Histedit of %s aborted\n",
12487 got_ref_get_symref_target(branch));
12488 print_merge_progress_stats(&upa);
12489 goto done; /* nothing else to do */
12490 } else if (abort_edit) {
12491 error = got_error(GOT_ERR_NOT_HISTEDIT);
12492 goto done;
12495 error = get_author(&committer, repo, worktree);
12496 if (error)
12497 goto done;
12499 if (continue_edit) {
12500 char *path;
12502 if (!edit_in_progress) {
12503 error = got_error(GOT_ERR_NOT_HISTEDIT);
12504 goto done;
12507 error = got_worktree_get_histedit_script_path(&path, worktree);
12508 if (error)
12509 goto done;
12511 error = histedit_load_list(&histedit_cmds, path, repo);
12512 free(path);
12513 if (error)
12514 goto done;
12516 error = got_worktree_histedit_continue(&resume_commit_id,
12517 &tmp_branch, &branch, &base_commit_id, &fileindex,
12518 worktree, repo);
12519 if (error)
12520 goto done;
12522 error = got_ref_resolve(&head_commit_id, repo, branch);
12523 if (error)
12524 goto done;
12526 error = got_object_open_as_commit(&commit, repo,
12527 head_commit_id);
12528 if (error)
12529 goto done;
12530 parent_ids = got_object_commit_get_parent_ids(commit);
12531 pid = STAILQ_FIRST(parent_ids);
12532 if (pid == NULL) {
12533 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
12534 goto done;
12536 error = collect_commits(&commits, head_commit_id, &pid->id,
12537 base_commit_id, got_worktree_get_path_prefix(worktree),
12538 GOT_ERR_HISTEDIT_PATH, repo);
12539 got_object_commit_close(commit);
12540 commit = NULL;
12541 if (error)
12542 goto done;
12543 } else {
12544 if (edit_in_progress) {
12545 error = got_error(GOT_ERR_HISTEDIT_BUSY);
12546 goto done;
12549 error = got_ref_open(&branch, repo,
12550 got_worktree_get_head_ref_name(worktree), 0);
12551 if (error != NULL)
12552 goto done;
12554 if (strncmp(got_ref_get_name(branch), "refs/heads/", 11) != 0) {
12555 error = got_error_msg(GOT_ERR_COMMIT_BRANCH,
12556 "will not edit commit history of a branch outside "
12557 "the \"refs/heads/\" reference namespace");
12558 goto done;
12561 error = got_ref_resolve(&head_commit_id, repo, branch);
12562 got_ref_close(branch);
12563 branch = NULL;
12564 if (error)
12565 goto done;
12567 error = got_object_open_as_commit(&commit, repo,
12568 head_commit_id);
12569 if (error)
12570 goto done;
12571 parent_ids = got_object_commit_get_parent_ids(commit);
12572 pid = STAILQ_FIRST(parent_ids);
12573 if (pid == NULL) {
12574 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
12575 goto done;
12577 error = collect_commits(&commits, head_commit_id, &pid->id,
12578 got_worktree_get_base_commit_id(worktree),
12579 got_worktree_get_path_prefix(worktree),
12580 GOT_ERR_HISTEDIT_PATH, repo);
12581 got_object_commit_close(commit);
12582 commit = NULL;
12583 if (error)
12584 goto done;
12586 if (STAILQ_EMPTY(&commits)) {
12587 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
12588 goto done;
12591 error = got_worktree_histedit_prepare(&tmp_branch, &branch,
12592 &base_commit_id, &fileindex, worktree, repo);
12593 if (error)
12594 goto done;
12596 if (edit_script_path) {
12597 error = histedit_load_list(&histedit_cmds,
12598 edit_script_path, repo);
12599 if (error) {
12600 got_worktree_histedit_abort(worktree, fileindex,
12601 repo, branch, base_commit_id,
12602 abort_progress, &upa);
12603 print_merge_progress_stats(&upa);
12604 goto done;
12606 } else {
12607 const char *branch_name;
12608 branch_name = got_ref_get_symref_target(branch);
12609 if (strncmp(branch_name, "refs/heads/", 11) == 0)
12610 branch_name += 11;
12611 error = histedit_edit_script(&histedit_cmds, &commits,
12612 branch_name, edit_logmsg_only, fold_only,
12613 drop_only, edit_only, repo);
12614 if (error) {
12615 got_worktree_histedit_abort(worktree, fileindex,
12616 repo, branch, base_commit_id,
12617 abort_progress, &upa);
12618 print_merge_progress_stats(&upa);
12619 goto done;
12624 error = histedit_save_list(&histedit_cmds, worktree,
12625 repo);
12626 if (error) {
12627 got_worktree_histedit_abort(worktree, fileindex,
12628 repo, branch, base_commit_id,
12629 abort_progress, &upa);
12630 print_merge_progress_stats(&upa);
12631 goto done;
12636 error = histedit_check_script(&histedit_cmds, &commits, repo);
12637 if (error)
12638 goto done;
12640 TAILQ_FOREACH(hle, &histedit_cmds, entry) {
12641 if (resume_commit_id) {
12642 if (got_object_id_cmp(hle->commit_id,
12643 resume_commit_id) != 0)
12644 continue;
12646 resume_commit_id = NULL;
12647 if (hle->cmd->code == GOT_HISTEDIT_DROP ||
12648 hle->cmd->code == GOT_HISTEDIT_FOLD) {
12649 error = histedit_skip_commit(hle, worktree,
12650 repo);
12651 if (error)
12652 goto done;
12653 } else {
12654 struct got_pathlist_head paths;
12655 int have_changes = 0;
12657 TAILQ_INIT(&paths);
12658 error = got_pathlist_append(&paths, "", NULL);
12659 if (error)
12660 goto done;
12661 error = got_worktree_status(worktree, &paths,
12662 repo, 0, check_local_changes, &have_changes,
12663 check_cancelled, NULL);
12664 got_pathlist_free(&paths,
12665 GOT_PATHLIST_FREE_NONE);
12666 if (error) {
12667 if (error->code != GOT_ERR_CANCELLED)
12668 goto done;
12669 if (sigint_received || sigpipe_received)
12670 goto done;
12672 if (have_changes) {
12673 error = histedit_commit(NULL, worktree,
12674 fileindex, tmp_branch, hle,
12675 committer, repo);
12676 if (error)
12677 goto done;
12678 } else {
12679 error = got_object_open_as_commit(
12680 &commit, repo, hle->commit_id);
12681 if (error)
12682 goto done;
12683 error = show_histedit_progress(commit,
12684 hle, NULL);
12685 got_object_commit_close(commit);
12686 commit = NULL;
12687 if (error)
12688 goto done;
12691 continue;
12694 if (hle->cmd->code == GOT_HISTEDIT_DROP) {
12695 error = histedit_skip_commit(hle, worktree, repo);
12696 if (error)
12697 goto done;
12698 continue;
12701 error = got_object_open_as_commit(&commit, repo,
12702 hle->commit_id);
12703 if (error)
12704 goto done;
12705 parent_ids = got_object_commit_get_parent_ids(commit);
12706 pid = STAILQ_FIRST(parent_ids);
12708 error = got_worktree_histedit_merge_files(&merged_paths,
12709 worktree, fileindex, &pid->id, hle->commit_id, repo,
12710 update_progress, &upa, check_cancelled, NULL);
12711 if (error)
12712 goto done;
12713 got_object_commit_close(commit);
12714 commit = NULL;
12716 print_merge_progress_stats(&upa);
12717 if (upa.conflicts > 0 || upa.missing > 0 ||
12718 upa.not_deleted > 0 || upa.unversioned > 0) {
12719 if (upa.conflicts > 0) {
12720 error = show_rebase_merge_conflict(
12721 hle->commit_id, repo);
12722 if (error)
12723 goto done;
12725 got_pathlist_free(&merged_paths, GOT_PATHLIST_FREE_PATH);
12726 break;
12729 if (hle->cmd->code == GOT_HISTEDIT_EDIT) {
12730 char *id_str;
12731 error = got_object_id_str(&id_str, hle->commit_id);
12732 if (error)
12733 goto done;
12734 printf("Stopping histedit for amending commit %s\n",
12735 id_str);
12736 free(id_str);
12737 got_pathlist_free(&merged_paths, GOT_PATHLIST_FREE_PATH);
12738 error = got_worktree_histedit_postpone(worktree,
12739 fileindex);
12740 goto done;
12743 if (hle->cmd->code == GOT_HISTEDIT_FOLD) {
12744 error = histedit_skip_commit(hle, worktree, repo);
12745 if (error)
12746 goto done;
12747 continue;
12750 error = histedit_commit(&merged_paths, worktree, fileindex,
12751 tmp_branch, hle, committer, repo);
12752 got_pathlist_free(&merged_paths, GOT_PATHLIST_FREE_PATH);
12753 if (error)
12754 goto done;
12757 if (upa.conflicts > 0 || upa.missing > 0 ||
12758 upa.not_deleted > 0 || upa.unversioned > 0) {
12759 error = got_worktree_histedit_postpone(worktree, fileindex);
12760 if (error)
12761 goto done;
12762 if (upa.conflicts > 0 && upa.missing == 0 &&
12763 upa.not_deleted == 0 && upa.unversioned == 0) {
12764 error = got_error_msg(GOT_ERR_CONFLICTS,
12765 "conflicts must be resolved before histedit "
12766 "can continue");
12767 } else if (upa.conflicts > 0) {
12768 error = got_error_msg(GOT_ERR_CONFLICTS,
12769 "conflicts must be resolved before histedit "
12770 "can continue; changes destined for some "
12771 "files were not yet merged and should be "
12772 "merged manually if required before the "
12773 "histedit operation is continued");
12774 } else {
12775 error = got_error_msg(GOT_ERR_CONFLICTS,
12776 "changes destined for some files were not "
12777 "yet merged and should be merged manually "
12778 "if required before the histedit operation "
12779 "is continued");
12781 } else
12782 error = histedit_complete(worktree, fileindex, tmp_branch,
12783 branch, repo);
12784 done:
12785 free(cwd);
12786 free(committer);
12787 free(gitconfig_path);
12788 got_object_id_queue_free(&commits);
12789 histedit_free_list(&histedit_cmds);
12790 free(head_commit_id);
12791 free(base_commit_id);
12792 free(resume_commit_id);
12793 if (commit)
12794 got_object_commit_close(commit);
12795 if (branch)
12796 got_ref_close(branch);
12797 if (tmp_branch)
12798 got_ref_close(tmp_branch);
12799 if (worktree)
12800 got_worktree_close(worktree);
12801 if (repo) {
12802 const struct got_error *close_err = got_repo_close(repo);
12803 if (error == NULL)
12804 error = close_err;
12806 if (pack_fds) {
12807 const struct got_error *pack_err =
12808 got_repo_pack_fds_close(pack_fds);
12809 if (error == NULL)
12810 error = pack_err;
12812 return error;
12815 __dead static void
12816 usage_integrate(void)
12818 fprintf(stderr, "usage: %s integrate branch\n", getprogname());
12819 exit(1);
12822 static const struct got_error *
12823 cmd_integrate(int argc, char *argv[])
12825 const struct got_error *error = NULL;
12826 struct got_repository *repo = NULL;
12827 struct got_worktree *worktree = NULL;
12828 char *cwd = NULL, *refname = NULL, *base_refname = NULL;
12829 const char *branch_arg = NULL;
12830 struct got_reference *branch_ref = NULL, *base_branch_ref = NULL;
12831 struct got_fileindex *fileindex = NULL;
12832 struct got_object_id *commit_id = NULL, *base_commit_id = NULL;
12833 int ch;
12834 struct got_update_progress_arg upa;
12835 int *pack_fds = NULL;
12837 while ((ch = getopt(argc, argv, "")) != -1) {
12838 switch (ch) {
12839 default:
12840 usage_integrate();
12841 /* NOTREACHED */
12845 argc -= optind;
12846 argv += optind;
12848 if (argc != 1)
12849 usage_integrate();
12850 branch_arg = argv[0];
12851 #ifndef PROFILE
12852 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
12853 "unveil", NULL) == -1)
12854 err(1, "pledge");
12855 #endif
12856 cwd = getcwd(NULL, 0);
12857 if (cwd == NULL) {
12858 error = got_error_from_errno("getcwd");
12859 goto done;
12862 error = got_repo_pack_fds_open(&pack_fds);
12863 if (error != NULL)
12864 goto done;
12866 error = got_worktree_open(&worktree, cwd);
12867 if (error) {
12868 if (error->code == GOT_ERR_NOT_WORKTREE)
12869 error = wrap_not_worktree_error(error, "integrate",
12870 cwd);
12871 goto done;
12874 error = check_rebase_or_histedit_in_progress(worktree);
12875 if (error)
12876 goto done;
12878 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
12879 NULL, pack_fds);
12880 if (error != NULL)
12881 goto done;
12883 error = apply_unveil(got_repo_get_path(repo), 0,
12884 got_worktree_get_root_path(worktree));
12885 if (error)
12886 goto done;
12888 error = check_merge_in_progress(worktree, repo);
12889 if (error)
12890 goto done;
12892 if (asprintf(&refname, "refs/heads/%s", branch_arg) == -1) {
12893 error = got_error_from_errno("asprintf");
12894 goto done;
12897 error = got_worktree_integrate_prepare(&fileindex, &branch_ref,
12898 &base_branch_ref, worktree, refname, repo);
12899 if (error)
12900 goto done;
12902 refname = strdup(got_ref_get_name(branch_ref));
12903 if (refname == NULL) {
12904 error = got_error_from_errno("strdup");
12905 got_worktree_integrate_abort(worktree, fileindex, repo,
12906 branch_ref, base_branch_ref);
12907 goto done;
12909 base_refname = strdup(got_ref_get_name(base_branch_ref));
12910 if (base_refname == NULL) {
12911 error = got_error_from_errno("strdup");
12912 got_worktree_integrate_abort(worktree, fileindex, repo,
12913 branch_ref, base_branch_ref);
12914 goto done;
12916 if (strncmp(base_refname, "refs/heads/", 11) != 0) {
12917 error = got_error(GOT_ERR_INTEGRATE_BRANCH);
12918 got_worktree_integrate_abort(worktree, fileindex, repo,
12919 branch_ref, base_branch_ref);
12920 goto done;
12923 error = got_ref_resolve(&commit_id, repo, branch_ref);
12924 if (error)
12925 goto done;
12927 error = got_ref_resolve(&base_commit_id, repo, base_branch_ref);
12928 if (error)
12929 goto done;
12931 if (got_object_id_cmp(commit_id, base_commit_id) == 0) {
12932 error = got_error_msg(GOT_ERR_SAME_BRANCH,
12933 "specified branch has already been integrated");
12934 got_worktree_integrate_abort(worktree, fileindex, repo,
12935 branch_ref, base_branch_ref);
12936 goto done;
12939 error = check_linear_ancestry(commit_id, base_commit_id, 1, repo);
12940 if (error) {
12941 if (error->code == GOT_ERR_ANCESTRY)
12942 error = got_error(GOT_ERR_REBASE_REQUIRED);
12943 got_worktree_integrate_abort(worktree, fileindex, repo,
12944 branch_ref, base_branch_ref);
12945 goto done;
12948 memset(&upa, 0, sizeof(upa));
12949 error = got_worktree_integrate_continue(worktree, fileindex, repo,
12950 branch_ref, base_branch_ref, update_progress, &upa,
12951 check_cancelled, NULL);
12952 if (error)
12953 goto done;
12955 printf("Integrated %s into %s\n", refname, base_refname);
12956 print_update_progress_stats(&upa);
12957 done:
12958 if (repo) {
12959 const struct got_error *close_err = got_repo_close(repo);
12960 if (error == NULL)
12961 error = close_err;
12963 if (worktree)
12964 got_worktree_close(worktree);
12965 if (pack_fds) {
12966 const struct got_error *pack_err =
12967 got_repo_pack_fds_close(pack_fds);
12968 if (error == NULL)
12969 error = pack_err;
12971 free(cwd);
12972 free(base_commit_id);
12973 free(commit_id);
12974 free(refname);
12975 free(base_refname);
12976 return error;
12979 __dead static void
12980 usage_merge(void)
12982 fprintf(stderr, "usage: %s merge [-acn] [branch]\n", getprogname());
12983 exit(1);
12986 static const struct got_error *
12987 cmd_merge(int argc, char *argv[])
12989 const struct got_error *error = NULL;
12990 struct got_worktree *worktree = NULL;
12991 struct got_repository *repo = NULL;
12992 struct got_fileindex *fileindex = NULL;
12993 char *cwd = NULL, *id_str = NULL, *author = NULL;
12994 struct got_reference *branch = NULL, *wt_branch = NULL;
12995 struct got_object_id *branch_tip = NULL, *yca_id = NULL;
12996 struct got_object_id *wt_branch_tip = NULL;
12997 int ch, merge_in_progress = 0, abort_merge = 0, continue_merge = 0;
12998 int interrupt_merge = 0;
12999 struct got_update_progress_arg upa;
13000 struct got_object_id *merge_commit_id = NULL;
13001 char *branch_name = NULL;
13002 int *pack_fds = NULL;
13004 memset(&upa, 0, sizeof(upa));
13006 while ((ch = getopt(argc, argv, "acn")) != -1) {
13007 switch (ch) {
13008 case 'a':
13009 abort_merge = 1;
13010 break;
13011 case 'c':
13012 continue_merge = 1;
13013 break;
13014 case 'n':
13015 interrupt_merge = 1;
13016 break;
13017 default:
13018 usage_merge();
13019 /* NOTREACHED */
13023 argc -= optind;
13024 argv += optind;
13026 #ifndef PROFILE
13027 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
13028 "unveil", NULL) == -1)
13029 err(1, "pledge");
13030 #endif
13032 if (abort_merge && continue_merge)
13033 option_conflict('a', 'c');
13034 if (abort_merge || continue_merge) {
13035 if (argc != 0)
13036 usage_merge();
13037 } else if (argc != 1)
13038 usage_merge();
13040 cwd = getcwd(NULL, 0);
13041 if (cwd == NULL) {
13042 error = got_error_from_errno("getcwd");
13043 goto done;
13046 error = got_repo_pack_fds_open(&pack_fds);
13047 if (error != NULL)
13048 goto done;
13050 error = got_worktree_open(&worktree, cwd);
13051 if (error) {
13052 if (error->code == GOT_ERR_NOT_WORKTREE)
13053 error = wrap_not_worktree_error(error,
13054 "merge", cwd);
13055 goto done;
13058 error = got_repo_open(&repo,
13059 worktree ? got_worktree_get_repo_path(worktree) : cwd, NULL,
13060 pack_fds);
13061 if (error != NULL)
13062 goto done;
13064 if (worktree != NULL) {
13065 error = worktree_has_logmsg_ref("merge", worktree, repo);
13066 if (error)
13067 goto done;
13070 error = apply_unveil(got_repo_get_path(repo), 0,
13071 worktree ? got_worktree_get_root_path(worktree) : NULL);
13072 if (error)
13073 goto done;
13075 error = check_rebase_or_histedit_in_progress(worktree);
13076 if (error)
13077 goto done;
13079 error = got_worktree_merge_in_progress(&merge_in_progress, worktree,
13080 repo);
13081 if (error)
13082 goto done;
13084 if (abort_merge) {
13085 if (!merge_in_progress) {
13086 error = got_error(GOT_ERR_NOT_MERGING);
13087 goto done;
13089 error = got_worktree_merge_continue(&branch_name,
13090 &branch_tip, &fileindex, worktree, repo);
13091 if (error)
13092 goto done;
13093 error = got_worktree_merge_abort(worktree, fileindex, repo,
13094 abort_progress, &upa);
13095 if (error)
13096 goto done;
13097 printf("Merge of %s aborted\n", branch_name);
13098 goto done; /* nothing else to do */
13101 error = get_author(&author, repo, worktree);
13102 if (error)
13103 goto done;
13105 if (continue_merge) {
13106 if (!merge_in_progress) {
13107 error = got_error(GOT_ERR_NOT_MERGING);
13108 goto done;
13110 error = got_worktree_merge_continue(&branch_name,
13111 &branch_tip, &fileindex, worktree, repo);
13112 if (error)
13113 goto done;
13114 } else {
13115 error = got_ref_open(&branch, repo, argv[0], 0);
13116 if (error != NULL)
13117 goto done;
13118 branch_name = strdup(got_ref_get_name(branch));
13119 if (branch_name == NULL) {
13120 error = got_error_from_errno("strdup");
13121 goto done;
13123 error = got_ref_resolve(&branch_tip, repo, branch);
13124 if (error)
13125 goto done;
13128 error = got_ref_open(&wt_branch, repo,
13129 got_worktree_get_head_ref_name(worktree), 0);
13130 if (error)
13131 goto done;
13132 error = got_ref_resolve(&wt_branch_tip, repo, wt_branch);
13133 if (error)
13134 goto done;
13135 error = got_commit_graph_find_youngest_common_ancestor(&yca_id,
13136 wt_branch_tip, branch_tip, 0, repo,
13137 check_cancelled, NULL);
13138 if (error && error->code != GOT_ERR_ANCESTRY)
13139 goto done;
13141 if (!continue_merge) {
13142 error = check_path_prefix(wt_branch_tip, branch_tip,
13143 got_worktree_get_path_prefix(worktree),
13144 GOT_ERR_MERGE_PATH, repo);
13145 if (error)
13146 goto done;
13147 if (yca_id) {
13148 error = check_same_branch(wt_branch_tip, branch,
13149 yca_id, repo);
13150 if (error) {
13151 if (error->code != GOT_ERR_ANCESTRY)
13152 goto done;
13153 error = NULL;
13154 } else {
13155 static char msg[512];
13156 snprintf(msg, sizeof(msg),
13157 "cannot create a merge commit because "
13158 "%s is based on %s; %s can be integrated "
13159 "with 'got integrate' instead", branch_name,
13160 got_worktree_get_head_ref_name(worktree),
13161 branch_name);
13162 error = got_error_msg(GOT_ERR_SAME_BRANCH, msg);
13163 goto done;
13166 error = got_worktree_merge_prepare(&fileindex, worktree,
13167 branch, repo);
13168 if (error)
13169 goto done;
13171 error = got_worktree_merge_branch(worktree, fileindex,
13172 yca_id, branch_tip, repo, update_progress, &upa,
13173 check_cancelled, NULL);
13174 if (error)
13175 goto done;
13176 print_merge_progress_stats(&upa);
13177 if (!upa.did_something) {
13178 error = got_worktree_merge_abort(worktree, fileindex,
13179 repo, abort_progress, &upa);
13180 if (error)
13181 goto done;
13182 printf("Already up-to-date\n");
13183 goto done;
13187 if (interrupt_merge) {
13188 error = got_worktree_merge_postpone(worktree, fileindex);
13189 if (error)
13190 goto done;
13191 printf("Merge of %s interrupted on request\n", branch_name);
13192 } else if (upa.conflicts > 0 || upa.missing > 0 ||
13193 upa.not_deleted > 0 || upa.unversioned > 0) {
13194 error = got_worktree_merge_postpone(worktree, fileindex);
13195 if (error)
13196 goto done;
13197 if (upa.conflicts > 0 && upa.missing == 0 &&
13198 upa.not_deleted == 0 && upa.unversioned == 0) {
13199 error = got_error_msg(GOT_ERR_CONFLICTS,
13200 "conflicts must be resolved before merging "
13201 "can continue");
13202 } else if (upa.conflicts > 0) {
13203 error = got_error_msg(GOT_ERR_CONFLICTS,
13204 "conflicts must be resolved before merging "
13205 "can continue; changes destined for some "
13206 "files were not yet merged and "
13207 "should be merged manually if required before the "
13208 "merge operation is continued");
13209 } else {
13210 error = got_error_msg(GOT_ERR_CONFLICTS,
13211 "changes destined for some "
13212 "files were not yet merged and should be "
13213 "merged manually if required before the "
13214 "merge operation is continued");
13216 goto done;
13217 } else {
13218 error = got_worktree_merge_commit(&merge_commit_id, worktree,
13219 fileindex, author, NULL, 1, branch_tip, branch_name,
13220 repo, continue_merge ? print_status : NULL, NULL);
13221 if (error)
13222 goto done;
13223 error = got_worktree_merge_complete(worktree, fileindex, repo);
13224 if (error)
13225 goto done;
13226 error = got_object_id_str(&id_str, merge_commit_id);
13227 if (error)
13228 goto done;
13229 printf("Merged %s into %s: %s\n", branch_name,
13230 got_worktree_get_head_ref_name(worktree),
13231 id_str);
13234 done:
13235 free(id_str);
13236 free(merge_commit_id);
13237 free(author);
13238 free(branch_tip);
13239 free(branch_name);
13240 free(yca_id);
13241 if (branch)
13242 got_ref_close(branch);
13243 if (wt_branch)
13244 got_ref_close(wt_branch);
13245 if (worktree)
13246 got_worktree_close(worktree);
13247 if (repo) {
13248 const struct got_error *close_err = got_repo_close(repo);
13249 if (error == NULL)
13250 error = close_err;
13252 if (pack_fds) {
13253 const struct got_error *pack_err =
13254 got_repo_pack_fds_close(pack_fds);
13255 if (error == NULL)
13256 error = pack_err;
13258 return error;
13261 __dead static void
13262 usage_stage(void)
13264 fprintf(stderr, "usage: %s stage [-lpS] [-F response-script] "
13265 "[path ...]\n", getprogname());
13266 exit(1);
13269 static const struct got_error *
13270 print_stage(void *arg, unsigned char status, unsigned char staged_status,
13271 const char *path, struct got_object_id *blob_id,
13272 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
13273 int dirfd, const char *de_name)
13275 const struct got_error *err = NULL;
13276 char *id_str = NULL;
13278 if (staged_status != GOT_STATUS_ADD &&
13279 staged_status != GOT_STATUS_MODIFY &&
13280 staged_status != GOT_STATUS_DELETE)
13281 return NULL;
13283 if (staged_status == GOT_STATUS_ADD ||
13284 staged_status == GOT_STATUS_MODIFY)
13285 err = got_object_id_str(&id_str, staged_blob_id);
13286 else
13287 err = got_object_id_str(&id_str, blob_id);
13288 if (err)
13289 return err;
13291 printf("%s %c %s\n", id_str, staged_status, path);
13292 free(id_str);
13293 return NULL;
13296 static const struct got_error *
13297 cmd_stage(int argc, char *argv[])
13299 const struct got_error *error = NULL;
13300 struct got_repository *repo = NULL;
13301 struct got_worktree *worktree = NULL;
13302 char *cwd = NULL;
13303 struct got_pathlist_head paths;
13304 int ch, list_stage = 0, pflag = 0, allow_bad_symlinks = 0;
13305 FILE *patch_script_file = NULL;
13306 const char *patch_script_path = NULL;
13307 struct choose_patch_arg cpa;
13308 int *pack_fds = NULL;
13310 TAILQ_INIT(&paths);
13312 while ((ch = getopt(argc, argv, "F:lpS")) != -1) {
13313 switch (ch) {
13314 case 'F':
13315 patch_script_path = optarg;
13316 break;
13317 case 'l':
13318 list_stage = 1;
13319 break;
13320 case 'p':
13321 pflag = 1;
13322 break;
13323 case 'S':
13324 allow_bad_symlinks = 1;
13325 break;
13326 default:
13327 usage_stage();
13328 /* NOTREACHED */
13332 argc -= optind;
13333 argv += optind;
13335 #ifndef PROFILE
13336 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
13337 "unveil", NULL) == -1)
13338 err(1, "pledge");
13339 #endif
13340 if (list_stage && (pflag || patch_script_path))
13341 errx(1, "-l option cannot be used with other options");
13342 if (patch_script_path && !pflag)
13343 errx(1, "-F option can only be used together with -p option");
13345 cwd = getcwd(NULL, 0);
13346 if (cwd == NULL) {
13347 error = got_error_from_errno("getcwd");
13348 goto done;
13351 error = got_repo_pack_fds_open(&pack_fds);
13352 if (error != NULL)
13353 goto done;
13355 error = got_worktree_open(&worktree, cwd);
13356 if (error) {
13357 if (error->code == GOT_ERR_NOT_WORKTREE)
13358 error = wrap_not_worktree_error(error, "stage", cwd);
13359 goto done;
13362 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
13363 NULL, pack_fds);
13364 if (error != NULL)
13365 goto done;
13367 if (patch_script_path) {
13368 patch_script_file = fopen(patch_script_path, "re");
13369 if (patch_script_file == NULL) {
13370 error = got_error_from_errno2("fopen",
13371 patch_script_path);
13372 goto done;
13375 error = apply_unveil(got_repo_get_path(repo), 0,
13376 got_worktree_get_root_path(worktree));
13377 if (error)
13378 goto done;
13380 error = check_merge_in_progress(worktree, repo);
13381 if (error)
13382 goto done;
13384 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
13385 if (error)
13386 goto done;
13388 if (list_stage)
13389 error = got_worktree_status(worktree, &paths, repo, 0,
13390 print_stage, NULL, check_cancelled, NULL);
13391 else {
13392 cpa.patch_script_file = patch_script_file;
13393 cpa.action = "stage";
13394 error = got_worktree_stage(worktree, &paths,
13395 pflag ? NULL : print_status, NULL,
13396 pflag ? choose_patch : NULL, &cpa,
13397 allow_bad_symlinks, repo);
13399 done:
13400 if (patch_script_file && fclose(patch_script_file) == EOF &&
13401 error == NULL)
13402 error = got_error_from_errno2("fclose", patch_script_path);
13403 if (repo) {
13404 const struct got_error *close_err = got_repo_close(repo);
13405 if (error == NULL)
13406 error = close_err;
13408 if (worktree)
13409 got_worktree_close(worktree);
13410 if (pack_fds) {
13411 const struct got_error *pack_err =
13412 got_repo_pack_fds_close(pack_fds);
13413 if (error == NULL)
13414 error = pack_err;
13416 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
13417 free(cwd);
13418 return error;
13421 __dead static void
13422 usage_unstage(void)
13424 fprintf(stderr, "usage: %s unstage [-p] [-F response-script] "
13425 "[path ...]\n", getprogname());
13426 exit(1);
13430 static const struct got_error *
13431 cmd_unstage(int argc, char *argv[])
13433 const struct got_error *error = NULL;
13434 struct got_repository *repo = NULL;
13435 struct got_worktree *worktree = NULL;
13436 char *cwd = NULL;
13437 struct got_pathlist_head paths;
13438 int ch, pflag = 0;
13439 struct got_update_progress_arg upa;
13440 FILE *patch_script_file = NULL;
13441 const char *patch_script_path = NULL;
13442 struct choose_patch_arg cpa;
13443 int *pack_fds = NULL;
13445 TAILQ_INIT(&paths);
13447 while ((ch = getopt(argc, argv, "F:p")) != -1) {
13448 switch (ch) {
13449 case 'F':
13450 patch_script_path = optarg;
13451 break;
13452 case 'p':
13453 pflag = 1;
13454 break;
13455 default:
13456 usage_unstage();
13457 /* NOTREACHED */
13461 argc -= optind;
13462 argv += optind;
13464 #ifndef PROFILE
13465 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
13466 "unveil", NULL) == -1)
13467 err(1, "pledge");
13468 #endif
13469 if (patch_script_path && !pflag)
13470 errx(1, "-F option can only be used together with -p option");
13472 cwd = getcwd(NULL, 0);
13473 if (cwd == NULL) {
13474 error = got_error_from_errno("getcwd");
13475 goto done;
13478 error = got_repo_pack_fds_open(&pack_fds);
13479 if (error != NULL)
13480 goto done;
13482 error = got_worktree_open(&worktree, cwd);
13483 if (error) {
13484 if (error->code == GOT_ERR_NOT_WORKTREE)
13485 error = wrap_not_worktree_error(error, "unstage", cwd);
13486 goto done;
13489 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
13490 NULL, pack_fds);
13491 if (error != NULL)
13492 goto done;
13494 if (patch_script_path) {
13495 patch_script_file = fopen(patch_script_path, "re");
13496 if (patch_script_file == NULL) {
13497 error = got_error_from_errno2("fopen",
13498 patch_script_path);
13499 goto done;
13503 error = apply_unveil(got_repo_get_path(repo), 0,
13504 got_worktree_get_root_path(worktree));
13505 if (error)
13506 goto done;
13508 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
13509 if (error)
13510 goto done;
13512 cpa.patch_script_file = patch_script_file;
13513 cpa.action = "unstage";
13514 memset(&upa, 0, sizeof(upa));
13515 error = got_worktree_unstage(worktree, &paths, update_progress,
13516 &upa, pflag ? choose_patch : NULL, &cpa, repo);
13517 if (!error)
13518 print_merge_progress_stats(&upa);
13519 done:
13520 if (patch_script_file && fclose(patch_script_file) == EOF &&
13521 error == NULL)
13522 error = got_error_from_errno2("fclose", patch_script_path);
13523 if (repo) {
13524 const struct got_error *close_err = got_repo_close(repo);
13525 if (error == NULL)
13526 error = close_err;
13528 if (worktree)
13529 got_worktree_close(worktree);
13530 if (pack_fds) {
13531 const struct got_error *pack_err =
13532 got_repo_pack_fds_close(pack_fds);
13533 if (error == NULL)
13534 error = pack_err;
13536 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
13537 free(cwd);
13538 return error;
13541 __dead static void
13542 usage_cat(void)
13544 fprintf(stderr, "usage: %s cat [-P] [-c commit] [-r repository-path] "
13545 "arg ...\n", getprogname());
13546 exit(1);
13549 static const struct got_error *
13550 cat_blob(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
13552 const struct got_error *err;
13553 struct got_blob_object *blob;
13554 int fd = -1;
13556 fd = got_opentempfd();
13557 if (fd == -1)
13558 return got_error_from_errno("got_opentempfd");
13560 err = got_object_open_as_blob(&blob, repo, id, 8192, fd);
13561 if (err)
13562 goto done;
13564 err = got_object_blob_dump_to_file(NULL, NULL, NULL, outfile, blob);
13565 done:
13566 if (fd != -1 && close(fd) == -1 && err == NULL)
13567 err = got_error_from_errno("close");
13568 if (blob)
13569 got_object_blob_close(blob);
13570 return err;
13573 static const struct got_error *
13574 cat_tree(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
13576 const struct got_error *err;
13577 struct got_tree_object *tree;
13578 int nentries, i;
13580 err = got_object_open_as_tree(&tree, repo, id);
13581 if (err)
13582 return err;
13584 nentries = got_object_tree_get_nentries(tree);
13585 for (i = 0; i < nentries; i++) {
13586 struct got_tree_entry *te;
13587 char *id_str;
13588 if (sigint_received || sigpipe_received)
13589 break;
13590 te = got_object_tree_get_entry(tree, i);
13591 err = got_object_id_str(&id_str, got_tree_entry_get_id(te));
13592 if (err)
13593 break;
13594 fprintf(outfile, "%s %.7o %s\n", id_str,
13595 got_tree_entry_get_mode(te),
13596 got_tree_entry_get_name(te));
13597 free(id_str);
13600 got_object_tree_close(tree);
13601 return err;
13604 static const struct got_error *
13605 cat_commit(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
13607 const struct got_error *err;
13608 struct got_commit_object *commit;
13609 const struct got_object_id_queue *parent_ids;
13610 struct got_object_qid *pid;
13611 char *id_str = NULL;
13612 const char *logmsg = NULL;
13613 char gmtoff[6];
13615 err = got_object_open_as_commit(&commit, repo, id);
13616 if (err)
13617 return err;
13619 err = got_object_id_str(&id_str, got_object_commit_get_tree_id(commit));
13620 if (err)
13621 goto done;
13623 fprintf(outfile, "%s%s\n", GOT_COMMIT_LABEL_TREE, id_str);
13624 parent_ids = got_object_commit_get_parent_ids(commit);
13625 fprintf(outfile, "numparents %d\n",
13626 got_object_commit_get_nparents(commit));
13627 STAILQ_FOREACH(pid, parent_ids, entry) {
13628 char *pid_str;
13629 err = got_object_id_str(&pid_str, &pid->id);
13630 if (err)
13631 goto done;
13632 fprintf(outfile, "%s%s\n", GOT_COMMIT_LABEL_PARENT, pid_str);
13633 free(pid_str);
13635 got_date_format_gmtoff(gmtoff, sizeof(gmtoff),
13636 got_object_commit_get_author_gmtoff(commit));
13637 fprintf(outfile, "%s%s %lld %s\n", GOT_COMMIT_LABEL_AUTHOR,
13638 got_object_commit_get_author(commit),
13639 (long long)got_object_commit_get_author_time(commit),
13640 gmtoff);
13642 got_date_format_gmtoff(gmtoff, sizeof(gmtoff),
13643 got_object_commit_get_committer_gmtoff(commit));
13644 fprintf(outfile, "%s%s %lld %s\n", GOT_COMMIT_LABEL_COMMITTER,
13645 got_object_commit_get_committer(commit),
13646 (long long)got_object_commit_get_committer_time(commit),
13647 gmtoff);
13649 logmsg = got_object_commit_get_logmsg_raw(commit);
13650 fprintf(outfile, "messagelen %zd\n", strlen(logmsg));
13651 fprintf(outfile, "%s", logmsg);
13652 done:
13653 free(id_str);
13654 got_object_commit_close(commit);
13655 return err;
13658 static const struct got_error *
13659 cat_tag(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
13661 const struct got_error *err;
13662 struct got_tag_object *tag;
13663 char *id_str = NULL;
13664 const char *tagmsg = NULL;
13665 char gmtoff[6];
13667 err = got_object_open_as_tag(&tag, repo, id);
13668 if (err)
13669 return err;
13671 err = got_object_id_str(&id_str, got_object_tag_get_object_id(tag));
13672 if (err)
13673 goto done;
13675 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_OBJECT, id_str);
13677 switch (got_object_tag_get_object_type(tag)) {
13678 case GOT_OBJ_TYPE_BLOB:
13679 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
13680 GOT_OBJ_LABEL_BLOB);
13681 break;
13682 case GOT_OBJ_TYPE_TREE:
13683 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
13684 GOT_OBJ_LABEL_TREE);
13685 break;
13686 case GOT_OBJ_TYPE_COMMIT:
13687 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
13688 GOT_OBJ_LABEL_COMMIT);
13689 break;
13690 case GOT_OBJ_TYPE_TAG:
13691 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
13692 GOT_OBJ_LABEL_TAG);
13693 break;
13694 default:
13695 break;
13698 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TAG,
13699 got_object_tag_get_name(tag));
13701 got_date_format_gmtoff(gmtoff, sizeof(gmtoff),
13702 got_object_tag_get_tagger_gmtoff(tag));
13703 fprintf(outfile, "%s%s %lld %s\n", GOT_TAG_LABEL_TAGGER,
13704 got_object_tag_get_tagger(tag),
13705 (long long)got_object_tag_get_tagger_time(tag),
13706 gmtoff);
13708 tagmsg = got_object_tag_get_message(tag);
13709 fprintf(outfile, "messagelen %zd\n", strlen(tagmsg));
13710 fprintf(outfile, "%s", tagmsg);
13711 done:
13712 free(id_str);
13713 got_object_tag_close(tag);
13714 return err;
13717 static const struct got_error *
13718 cmd_cat(int argc, char *argv[])
13720 const struct got_error *error;
13721 struct got_repository *repo = NULL;
13722 struct got_worktree *worktree = NULL;
13723 char *cwd = NULL, *repo_path = NULL, *label = NULL;
13724 const char *commit_id_str = NULL;
13725 struct got_object_id *id = NULL, *commit_id = NULL;
13726 struct got_commit_object *commit = NULL;
13727 int ch, obj_type, i, force_path = 0;
13728 struct got_reflist_head refs;
13729 int *pack_fds = NULL;
13731 TAILQ_INIT(&refs);
13733 #ifndef PROFILE
13734 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
13735 NULL) == -1)
13736 err(1, "pledge");
13737 #endif
13739 while ((ch = getopt(argc, argv, "c:Pr:")) != -1) {
13740 switch (ch) {
13741 case 'c':
13742 commit_id_str = optarg;
13743 break;
13744 case 'P':
13745 force_path = 1;
13746 break;
13747 case 'r':
13748 repo_path = realpath(optarg, NULL);
13749 if (repo_path == NULL)
13750 return got_error_from_errno2("realpath",
13751 optarg);
13752 got_path_strip_trailing_slashes(repo_path);
13753 break;
13754 default:
13755 usage_cat();
13756 /* NOTREACHED */
13760 argc -= optind;
13761 argv += optind;
13763 cwd = getcwd(NULL, 0);
13764 if (cwd == NULL) {
13765 error = got_error_from_errno("getcwd");
13766 goto done;
13769 error = got_repo_pack_fds_open(&pack_fds);
13770 if (error != NULL)
13771 goto done;
13773 if (repo_path == NULL) {
13774 error = got_worktree_open(&worktree, cwd);
13775 if (error && error->code != GOT_ERR_NOT_WORKTREE)
13776 goto done;
13777 if (worktree) {
13778 repo_path = strdup(
13779 got_worktree_get_repo_path(worktree));
13780 if (repo_path == NULL) {
13781 error = got_error_from_errno("strdup");
13782 goto done;
13785 /* Release work tree lock. */
13786 got_worktree_close(worktree);
13787 worktree = NULL;
13791 if (repo_path == NULL) {
13792 repo_path = strdup(cwd);
13793 if (repo_path == NULL)
13794 return got_error_from_errno("strdup");
13797 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
13798 free(repo_path);
13799 if (error != NULL)
13800 goto done;
13802 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
13803 if (error)
13804 goto done;
13806 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
13807 if (error)
13808 goto done;
13810 if (commit_id_str == NULL)
13811 commit_id_str = GOT_REF_HEAD;
13812 error = got_repo_match_object_id(&commit_id, NULL,
13813 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
13814 if (error)
13815 goto done;
13817 error = got_object_open_as_commit(&commit, repo, commit_id);
13818 if (error)
13819 goto done;
13821 for (i = 0; i < argc; i++) {
13822 if (force_path) {
13823 error = got_object_id_by_path(&id, repo, commit,
13824 argv[i]);
13825 if (error)
13826 break;
13827 } else {
13828 error = got_repo_match_object_id(&id, &label, argv[i],
13829 GOT_OBJ_TYPE_ANY, NULL /* do not resolve tags */,
13830 repo);
13831 if (error) {
13832 if (error->code != GOT_ERR_BAD_OBJ_ID_STR &&
13833 error->code != GOT_ERR_NOT_REF)
13834 break;
13835 error = got_object_id_by_path(&id, repo,
13836 commit, argv[i]);
13837 if (error)
13838 break;
13842 error = got_object_get_type(&obj_type, repo, id);
13843 if (error)
13844 break;
13846 switch (obj_type) {
13847 case GOT_OBJ_TYPE_BLOB:
13848 error = cat_blob(id, repo, stdout);
13849 break;
13850 case GOT_OBJ_TYPE_TREE:
13851 error = cat_tree(id, repo, stdout);
13852 break;
13853 case GOT_OBJ_TYPE_COMMIT:
13854 error = cat_commit(id, repo, stdout);
13855 break;
13856 case GOT_OBJ_TYPE_TAG:
13857 error = cat_tag(id, repo, stdout);
13858 break;
13859 default:
13860 error = got_error(GOT_ERR_OBJ_TYPE);
13861 break;
13863 if (error)
13864 break;
13865 free(label);
13866 label = NULL;
13867 free(id);
13868 id = NULL;
13870 done:
13871 free(label);
13872 free(id);
13873 free(commit_id);
13874 if (commit)
13875 got_object_commit_close(commit);
13876 if (worktree)
13877 got_worktree_close(worktree);
13878 if (repo) {
13879 const struct got_error *close_err = got_repo_close(repo);
13880 if (error == NULL)
13881 error = close_err;
13883 if (pack_fds) {
13884 const struct got_error *pack_err =
13885 got_repo_pack_fds_close(pack_fds);
13886 if (error == NULL)
13887 error = pack_err;
13890 got_ref_list_free(&refs);
13891 return error;
13894 __dead static void
13895 usage_info(void)
13897 fprintf(stderr, "usage: %s info [path ...]\n",
13898 getprogname());
13899 exit(1);
13902 static const struct got_error *
13903 print_path_info(void *arg, const char *path, mode_t mode, time_t mtime,
13904 struct got_object_id *blob_id, struct got_object_id *staged_blob_id,
13905 struct got_object_id *commit_id)
13907 const struct got_error *err = NULL;
13908 char *id_str = NULL;
13909 char datebuf[128];
13910 struct tm mytm, *tm;
13911 struct got_pathlist_head *paths = arg;
13912 struct got_pathlist_entry *pe;
13915 * Clear error indication from any of the path arguments which
13916 * would cause this file index entry to be displayed.
13918 TAILQ_FOREACH(pe, paths, entry) {
13919 if (got_path_cmp(path, pe->path, strlen(path),
13920 pe->path_len) == 0 ||
13921 got_path_is_child(path, pe->path, pe->path_len))
13922 pe->data = NULL; /* no error */
13925 printf(GOT_COMMIT_SEP_STR);
13926 if (S_ISLNK(mode))
13927 printf("symlink: %s\n", path);
13928 else if (S_ISREG(mode)) {
13929 printf("file: %s\n", path);
13930 printf("mode: %o\n", mode & (S_IRWXU | S_IRWXG | S_IRWXO));
13931 } else if (S_ISDIR(mode))
13932 printf("directory: %s\n", path);
13933 else
13934 printf("something: %s\n", path);
13936 tm = localtime_r(&mtime, &mytm);
13937 if (tm == NULL)
13938 return NULL;
13939 if (strftime(datebuf, sizeof(datebuf), "%c %Z", tm) == 0)
13940 return got_error(GOT_ERR_NO_SPACE);
13941 printf("timestamp: %s\n", datebuf);
13943 if (blob_id) {
13944 err = got_object_id_str(&id_str, blob_id);
13945 if (err)
13946 return err;
13947 printf("based on blob: %s\n", id_str);
13948 free(id_str);
13951 if (staged_blob_id) {
13952 err = got_object_id_str(&id_str, staged_blob_id);
13953 if (err)
13954 return err;
13955 printf("based on staged blob: %s\n", id_str);
13956 free(id_str);
13959 if (commit_id) {
13960 err = got_object_id_str(&id_str, commit_id);
13961 if (err)
13962 return err;
13963 printf("based on commit: %s\n", id_str);
13964 free(id_str);
13967 return NULL;
13970 static const struct got_error *
13971 cmd_info(int argc, char *argv[])
13973 const struct got_error *error = NULL;
13974 struct got_worktree *worktree = NULL;
13975 char *cwd = NULL, *id_str = NULL;
13976 struct got_pathlist_head paths;
13977 char *uuidstr = NULL;
13978 int ch, show_files = 0;
13980 TAILQ_INIT(&paths);
13982 while ((ch = getopt(argc, argv, "")) != -1) {
13983 switch (ch) {
13984 default:
13985 usage_info();
13986 /* NOTREACHED */
13990 argc -= optind;
13991 argv += optind;
13993 #ifndef PROFILE
13994 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
13995 NULL) == -1)
13996 err(1, "pledge");
13997 #endif
13998 cwd = getcwd(NULL, 0);
13999 if (cwd == NULL) {
14000 error = got_error_from_errno("getcwd");
14001 goto done;
14004 error = got_worktree_open(&worktree, cwd);
14005 if (error) {
14006 if (error->code == GOT_ERR_NOT_WORKTREE)
14007 error = wrap_not_worktree_error(error, "info", cwd);
14008 goto done;
14011 #ifndef PROFILE
14012 /* Remove "wpath cpath proc exec sendfd" promises. */
14013 if (pledge("stdio rpath flock unveil", NULL) == -1)
14014 err(1, "pledge");
14015 #endif
14016 error = apply_unveil(NULL, 0, got_worktree_get_root_path(worktree));
14017 if (error)
14018 goto done;
14020 if (argc >= 1) {
14021 error = get_worktree_paths_from_argv(&paths, argc, argv,
14022 worktree);
14023 if (error)
14024 goto done;
14025 show_files = 1;
14028 error = got_object_id_str(&id_str,
14029 got_worktree_get_base_commit_id(worktree));
14030 if (error)
14031 goto done;
14033 error = got_worktree_get_uuid(&uuidstr, worktree);
14034 if (error)
14035 goto done;
14037 printf("work tree: %s\n", got_worktree_get_root_path(worktree));
14038 printf("work tree base commit: %s\n", id_str);
14039 printf("work tree path prefix: %s\n",
14040 got_worktree_get_path_prefix(worktree));
14041 printf("work tree branch reference: %s\n",
14042 got_worktree_get_head_ref_name(worktree));
14043 printf("work tree UUID: %s\n", uuidstr);
14044 printf("repository: %s\n", got_worktree_get_repo_path(worktree));
14046 if (show_files) {
14047 struct got_pathlist_entry *pe;
14048 TAILQ_FOREACH(pe, &paths, entry) {
14049 if (pe->path_len == 0)
14050 continue;
14052 * Assume this path will fail. This will be corrected
14053 * in print_path_info() in case the path does suceeed.
14055 pe->data = (void *)got_error(GOT_ERR_BAD_PATH);
14057 error = got_worktree_path_info(worktree, &paths,
14058 print_path_info, &paths, check_cancelled, NULL);
14059 if (error)
14060 goto done;
14061 TAILQ_FOREACH(pe, &paths, entry) {
14062 if (pe->data != NULL) {
14063 const struct got_error *perr;
14065 perr = pe->data;
14066 error = got_error_fmt(perr->code, "%s",
14067 pe->path);
14068 break;
14072 done:
14073 if (worktree)
14074 got_worktree_close(worktree);
14075 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
14076 free(cwd);
14077 free(id_str);
14078 free(uuidstr);
14079 return error;