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 <signal.h>
32 #include <stdio.h>
33 #include <stdlib.h>
34 #include <string.h>
35 #include <unistd.h>
36 #include <libgen.h>
37 #include <time.h>
38 #include <paths.h>
39 #include <regex.h>
40 #include <getopt.h>
42 #include "got_compat.h"
44 #include "got_version.h"
45 #include "got_error.h"
46 #include "got_object.h"
47 #include "got_reference.h"
48 #include "got_repository.h"
49 #include "got_path.h"
50 #include "got_cancel.h"
51 #include "got_worktree.h"
52 #include "got_diff.h"
53 #include "got_commit_graph.h"
54 #include "got_fetch.h"
55 #include "got_send.h"
56 #include "got_blame.h"
57 #include "got_privsep.h"
58 #include "got_opentemp.h"
59 #include "got_gotconfig.h"
60 #include "got_dial.h"
61 #include "got_patch.h"
62 #include "got_sigs.h"
63 #include "got_date.h"
65 #ifndef nitems
66 #define nitems(_a) (sizeof((_a)) / sizeof((_a)[0]))
67 #endif
69 static volatile sig_atomic_t sigint_received;
70 static volatile sig_atomic_t sigpipe_received;
72 static void
73 catch_sigint(int signo)
74 {
75 sigint_received = 1;
76 }
78 static void
79 catch_sigpipe(int signo)
80 {
81 sigpipe_received = 1;
82 }
85 struct got_cmd {
86 const char *cmd_name;
87 const struct got_error *(*cmd_main)(int, char *[]);
88 void (*cmd_usage)(void);
89 const char *cmd_alias;
90 };
92 __dead static void usage(int, int);
93 __dead static void usage_import(void);
94 __dead static void usage_clone(void);
95 __dead static void usage_fetch(void);
96 __dead static void usage_checkout(void);
97 __dead static void usage_update(void);
98 __dead static void usage_log(void);
99 __dead static void usage_diff(void);
100 __dead static void usage_blame(void);
101 __dead static void usage_tree(void);
102 __dead static void usage_status(void);
103 __dead static void usage_ref(void);
104 __dead static void usage_branch(void);
105 __dead static void usage_tag(void);
106 __dead static void usage_add(void);
107 __dead static void usage_remove(void);
108 __dead static void usage_patch(void);
109 __dead static void usage_revert(void);
110 __dead static void usage_commit(void);
111 __dead static void usage_send(void);
112 __dead static void usage_cherrypick(void);
113 __dead static void usage_backout(void);
114 __dead static void usage_rebase(void);
115 __dead static void usage_histedit(void);
116 __dead static void usage_integrate(void);
117 __dead static void usage_merge(void);
118 __dead static void usage_stage(void);
119 __dead static void usage_unstage(void);
120 __dead static void usage_cat(void);
121 __dead static void usage_info(void);
123 static const struct got_error* cmd_import(int, char *[]);
124 static const struct got_error* cmd_clone(int, char *[]);
125 static const struct got_error* cmd_fetch(int, char *[]);
126 static const struct got_error* cmd_checkout(int, char *[]);
127 static const struct got_error* cmd_update(int, char *[]);
128 static const struct got_error* cmd_log(int, char *[]);
129 static const struct got_error* cmd_diff(int, char *[]);
130 static const struct got_error* cmd_blame(int, char *[]);
131 static const struct got_error* cmd_tree(int, char *[]);
132 static const struct got_error* cmd_status(int, char *[]);
133 static const struct got_error* cmd_ref(int, char *[]);
134 static const struct got_error* cmd_branch(int, char *[]);
135 static const struct got_error* cmd_tag(int, char *[]);
136 static const struct got_error* cmd_add(int, char *[]);
137 static const struct got_error* cmd_remove(int, char *[]);
138 static const struct got_error* cmd_patch(int, char *[]);
139 static const struct got_error* cmd_revert(int, char *[]);
140 static const struct got_error* cmd_commit(int, char *[]);
141 static const struct got_error* cmd_send(int, char *[]);
142 static const struct got_error* cmd_cherrypick(int, char *[]);
143 static const struct got_error* cmd_backout(int, char *[]);
144 static const struct got_error* cmd_rebase(int, char *[]);
145 static const struct got_error* cmd_histedit(int, char *[]);
146 static const struct got_error* cmd_integrate(int, char *[]);
147 static const struct got_error* cmd_merge(int, char *[]);
148 static const struct got_error* cmd_stage(int, char *[]);
149 static const struct got_error* cmd_unstage(int, char *[]);
150 static const struct got_error* cmd_cat(int, char *[]);
151 static const struct got_error* cmd_info(int, char *[]);
153 static const struct got_cmd got_commands[] = {
154 { "import", cmd_import, usage_import, "im" },
155 { "clone", cmd_clone, usage_clone, "cl" },
156 { "fetch", cmd_fetch, usage_fetch, "fe" },
157 { "checkout", cmd_checkout, usage_checkout, "co" },
158 { "update", cmd_update, usage_update, "up" },
159 { "log", cmd_log, usage_log, "" },
160 { "diff", cmd_diff, usage_diff, "di" },
161 { "blame", cmd_blame, usage_blame, "bl" },
162 { "tree", cmd_tree, usage_tree, "tr" },
163 { "status", cmd_status, usage_status, "st" },
164 { "ref", cmd_ref, usage_ref, "" },
165 { "branch", cmd_branch, usage_branch, "br" },
166 { "tag", cmd_tag, usage_tag, "" },
167 { "add", cmd_add, usage_add, "" },
168 { "remove", cmd_remove, usage_remove, "rm" },
169 { "patch", cmd_patch, usage_patch, "pa" },
170 { "revert", cmd_revert, usage_revert, "rv" },
171 { "commit", cmd_commit, usage_commit, "ci" },
172 { "send", cmd_send, usage_send, "se" },
173 { "cherrypick", cmd_cherrypick, usage_cherrypick, "cy" },
174 { "backout", cmd_backout, usage_backout, "bo" },
175 { "rebase", cmd_rebase, usage_rebase, "rb" },
176 { "histedit", cmd_histedit, usage_histedit, "he" },
177 { "integrate", cmd_integrate, usage_integrate,"ig" },
178 { "merge", cmd_merge, usage_merge, "mg" },
179 { "stage", cmd_stage, usage_stage, "sg" },
180 { "unstage", cmd_unstage, usage_unstage, "ug" },
181 { "cat", cmd_cat, usage_cat, "" },
182 { "info", cmd_info, usage_info, "" },
183 };
185 static void
186 list_commands(FILE *fp)
188 size_t i;
190 fprintf(fp, "commands:");
191 for (i = 0; i < nitems(got_commands); i++) {
192 const struct got_cmd *cmd = &got_commands[i];
193 fprintf(fp, " %s", cmd->cmd_name);
195 fputc('\n', fp);
198 __dead static void
199 option_conflict(char a, char b)
201 errx(1, "-%c and -%c options are mutually exclusive", a, b);
204 int
205 main(int argc, char *argv[])
207 const struct got_cmd *cmd;
208 size_t i;
209 int ch;
210 int hflag = 0, Vflag = 0;
211 static const struct option longopts[] = {
212 { "version", no_argument, NULL, 'V' },
213 { NULL, 0, NULL, 0 }
214 };
216 setlocale(LC_CTYPE, "");
218 while ((ch = getopt_long(argc, argv, "+hV", longopts, NULL)) != -1) {
219 switch (ch) {
220 case 'h':
221 hflag = 1;
222 break;
223 case 'V':
224 Vflag = 1;
225 break;
226 default:
227 usage(hflag, 1);
228 /* NOTREACHED */
232 argc -= optind;
233 argv += optind;
234 optind = 1;
235 optreset = 1;
237 if (Vflag) {
238 got_version_print_str();
239 return 0;
242 if (argc <= 0)
243 usage(hflag, hflag ? 0 : 1);
245 signal(SIGINT, catch_sigint);
246 signal(SIGPIPE, catch_sigpipe);
248 for (i = 0; i < nitems(got_commands); i++) {
249 const struct got_error *error;
251 cmd = &got_commands[i];
253 if (strcmp(cmd->cmd_name, argv[0]) != 0 &&
254 strcmp(cmd->cmd_alias, argv[0]) != 0)
255 continue;
257 if (hflag)
258 cmd->cmd_usage();
260 error = cmd->cmd_main(argc, argv);
261 if (error && error->code != GOT_ERR_CANCELLED &&
262 error->code != GOT_ERR_PRIVSEP_EXIT &&
263 !(sigpipe_received &&
264 error->code == GOT_ERR_ERRNO && errno == EPIPE) &&
265 !(sigint_received &&
266 error->code == GOT_ERR_ERRNO && errno == EINTR)) {
267 fprintf(stderr, "%s: %s\n", getprogname(), error->msg);
268 return 1;
271 return 0;
274 fprintf(stderr, "%s: unknown command '%s'\n", getprogname(), argv[0]);
275 list_commands(stderr);
276 return 1;
279 __dead static void
280 usage(int hflag, int status)
282 FILE *fp = (status == 0) ? stdout : stderr;
284 fprintf(fp, "usage: %s [-hV] command [arg ...]\n",
285 getprogname());
286 if (hflag)
287 list_commands(fp);
288 exit(status);
291 static const struct got_error *
292 get_editor(char **abspath)
294 const struct got_error *err = NULL;
295 const char *editor;
297 *abspath = NULL;
299 editor = getenv("VISUAL");
300 if (editor == NULL)
301 editor = getenv("EDITOR");
303 if (editor) {
304 err = got_path_find_prog(abspath, editor);
305 if (err)
306 return err;
309 if (*abspath == NULL) {
310 *abspath = strdup("/bin/ed");
311 if (*abspath == NULL)
312 return got_error_from_errno("strdup");
315 return NULL;
318 static const struct got_error *
319 apply_unveil(const char *repo_path, int repo_read_only,
320 const char *worktree_path)
322 const struct got_error *err;
324 #ifdef PROFILE
325 if (unveil("gmon.out", "rwc") != 0)
326 return got_error_from_errno2("unveil", "gmon.out");
327 #endif
328 if (repo_path && unveil(repo_path, repo_read_only ? "r" : "rwc") != 0)
329 return got_error_from_errno2("unveil", repo_path);
331 if (worktree_path && unveil(worktree_path, "rwc") != 0)
332 return got_error_from_errno2("unveil", worktree_path);
334 if (unveil(GOT_TMPDIR_STR, "rwc") != 0)
335 return got_error_from_errno2("unveil", GOT_TMPDIR_STR);
337 err = got_privsep_unveil_exec_helpers();
338 if (err != NULL)
339 return err;
341 if (unveil(NULL, NULL) != 0)
342 return got_error_from_errno("unveil");
344 return NULL;
347 __dead static void
348 usage_import(void)
350 fprintf(stderr, "usage: %s import [-b branch] [-I pattern] [-m message] "
351 "[-r repository-path] directory\n", getprogname());
352 exit(1);
355 static int
356 spawn_editor(const char *editor, const char *file)
358 pid_t pid;
359 sig_t sighup, sigint, sigquit;
360 int st = -1;
362 sighup = signal(SIGHUP, SIG_IGN);
363 sigint = signal(SIGINT, SIG_IGN);
364 sigquit = signal(SIGQUIT, SIG_IGN);
366 switch (pid = fork()) {
367 case -1:
368 goto doneediting;
369 case 0:
370 execl(editor, editor, file, (char *)NULL);
371 _exit(127);
374 while (waitpid(pid, &st, 0) == -1)
375 if (errno != EINTR)
376 break;
378 doneediting:
379 (void)signal(SIGHUP, sighup);
380 (void)signal(SIGINT, sigint);
381 (void)signal(SIGQUIT, sigquit);
383 if (!WIFEXITED(st)) {
384 errno = EINTR;
385 return -1;
388 return WEXITSTATUS(st);
391 static const struct got_error *
392 edit_logmsg(char **logmsg, const char *editor, const char *logmsg_path,
393 const char *initial_content, size_t initial_content_len,
394 int require_modification)
396 const struct got_error *err = NULL;
397 char *line = NULL;
398 size_t linesize = 0;
399 struct stat st, st2;
400 FILE *fp = NULL;
401 size_t len, logmsg_len;
402 char *initial_content_stripped = NULL, *buf = NULL, *s;
404 *logmsg = NULL;
406 if (stat(logmsg_path, &st) == -1)
407 return got_error_from_errno2("stat", logmsg_path);
409 if (spawn_editor(editor, logmsg_path) == -1)
410 return got_error_from_errno("failed spawning editor");
412 if (stat(logmsg_path, &st2) == -1)
413 return got_error_from_errno("stat");
415 if (require_modification &&
416 st.st_mtime == st2.st_mtime && st.st_size == st2.st_size)
417 return got_error_msg(GOT_ERR_COMMIT_MSG_EMPTY,
418 "no changes made to commit message, aborting");
420 /*
421 * Set up a stripped version of the initial content without comments
422 * and blank lines. We need this in order to check if the message
423 * has in fact been edited.
424 */
425 initial_content_stripped = malloc(initial_content_len + 1);
426 if (initial_content_stripped == NULL)
427 return got_error_from_errno("malloc");
428 initial_content_stripped[0] = '\0';
430 buf = strdup(initial_content);
431 if (buf == NULL) {
432 err = got_error_from_errno("strdup");
433 goto done;
435 s = buf;
436 len = 0;
437 while ((line = strsep(&s, "\n")) != NULL) {
438 if ((line[0] == '#' || (len == 0 && line[0] == '\n')))
439 continue; /* remove comments and leading empty lines */
440 len = strlcat(initial_content_stripped, line,
441 initial_content_len + 1);
442 if (len >= initial_content_len + 1) {
443 err = got_error(GOT_ERR_NO_SPACE);
444 goto done;
447 while (len > 0 && initial_content_stripped[len - 1] == '\n') {
448 initial_content_stripped[len - 1] = '\0';
449 len--;
452 logmsg_len = st2.st_size;
453 *logmsg = malloc(logmsg_len + 1);
454 if (*logmsg == NULL)
455 return got_error_from_errno("malloc");
456 (*logmsg)[0] = '\0';
458 fp = fopen(logmsg_path, "re");
459 if (fp == NULL) {
460 err = got_error_from_errno("fopen");
461 goto done;
464 len = 0;
465 while (getline(&line, &linesize, fp) != -1) {
466 if ((line[0] == '#' || (len == 0 && line[0] == '\n')))
467 continue; /* remove comments and leading empty lines */
468 len = strlcat(*logmsg, line, logmsg_len + 1);
469 if (len >= logmsg_len + 1) {
470 err = got_error(GOT_ERR_NO_SPACE);
471 goto done;
474 free(line);
475 if (ferror(fp)) {
476 err = got_ferror(fp, GOT_ERR_IO);
477 goto done;
479 while (len > 0 && (*logmsg)[len - 1] == '\n') {
480 (*logmsg)[len - 1] = '\0';
481 len--;
484 if (len == 0) {
485 err = got_error_msg(GOT_ERR_COMMIT_MSG_EMPTY,
486 "commit message cannot be empty, aborting");
487 goto done;
489 if (require_modification &&
490 strcmp(*logmsg, initial_content_stripped) == 0)
491 err = got_error_msg(GOT_ERR_COMMIT_MSG_EMPTY,
492 "no changes made to commit message, aborting");
493 done:
494 free(initial_content_stripped);
495 free(buf);
496 if (fp && fclose(fp) == EOF && err == NULL)
497 err = got_error_from_errno("fclose");
498 if (err) {
499 free(*logmsg);
500 *logmsg = NULL;
502 return err;
505 static const struct got_error *
506 collect_import_msg(char **logmsg, char **logmsg_path, const char *editor,
507 const char *path_dir, const char *branch_name)
509 char *initial_content = NULL;
510 const struct got_error *err = NULL;
511 int initial_content_len;
512 int fd = -1;
514 initial_content_len = asprintf(&initial_content,
515 "\n# %s to be imported to branch %s\n", path_dir,
516 branch_name);
517 if (initial_content_len == -1)
518 return got_error_from_errno("asprintf");
520 err = got_opentemp_named_fd(logmsg_path, &fd,
521 GOT_TMPDIR_STR "/got-importmsg", "");
522 if (err)
523 goto done;
525 if (write(fd, initial_content, initial_content_len) == -1) {
526 err = got_error_from_errno2("write", *logmsg_path);
527 goto done;
530 err = edit_logmsg(logmsg, editor, *logmsg_path, initial_content,
531 initial_content_len, 1);
532 done:
533 if (fd != -1 && close(fd) == -1 && err == NULL)
534 err = got_error_from_errno2("close", *logmsg_path);
535 free(initial_content);
536 if (err) {
537 free(*logmsg_path);
538 *logmsg_path = NULL;
540 return err;
543 static const struct got_error *
544 import_progress(void *arg, const char *path)
546 printf("A %s\n", path);
547 return NULL;
550 static const struct got_error *
551 valid_author(const char *author)
553 const char *email = author;
555 /*
556 * Git' expects the author (or committer) to be in the form
557 * "name <email>", which are mostly free form (see the
558 * "committer" description in git-fast-import(1)). We're only
559 * doing this to avoid git's object parser breaking on commits
560 * we create.
561 */
563 while (*author && *author != '\n' && *author != '<' && *author != '>')
564 author++;
565 if (author != email && *author == '<' && *(author - 1) != ' ')
566 return got_error_fmt(GOT_ERR_COMMIT_BAD_AUTHOR, "%s: space "
567 "between author name and email required", email);
568 if (*author++ != '<')
569 return got_error_fmt(GOT_ERR_COMMIT_NO_EMAIL, "%s", email);
570 while (*author && *author != '\n' && *author != '<' && *author != '>')
571 author++;
572 if (strcmp(author, ">") != 0)
573 return got_error_fmt(GOT_ERR_COMMIT_NO_EMAIL, "%s", email);
574 return NULL;
577 static const struct got_error *
578 get_author(char **author, struct got_repository *repo,
579 struct got_worktree *worktree)
581 const struct got_error *err = NULL;
582 const char *got_author = NULL, *name, *email;
583 const struct got_gotconfig *worktree_conf = NULL, *repo_conf = NULL;
585 *author = NULL;
587 if (worktree)
588 worktree_conf = got_worktree_get_gotconfig(worktree);
589 repo_conf = got_repo_get_gotconfig(repo);
591 /*
592 * Priority of potential author information sources, from most
593 * significant to least significant:
594 * 1) work tree's .got/got.conf file
595 * 2) repository's got.conf file
596 * 3) repository's git config file
597 * 4) environment variables
598 * 5) global git config files (in user's home directory or /etc)
599 */
601 if (worktree_conf)
602 got_author = got_gotconfig_get_author(worktree_conf);
603 if (got_author == NULL)
604 got_author = got_gotconfig_get_author(repo_conf);
605 if (got_author == NULL) {
606 name = got_repo_get_gitconfig_author_name(repo);
607 email = got_repo_get_gitconfig_author_email(repo);
608 if (name && email) {
609 if (asprintf(author, "%s <%s>", name, email) == -1)
610 return got_error_from_errno("asprintf");
611 return NULL;
614 got_author = getenv("GOT_AUTHOR");
615 if (got_author == NULL) {
616 name = got_repo_get_global_gitconfig_author_name(repo);
617 email = got_repo_get_global_gitconfig_author_email(
618 repo);
619 if (name && email) {
620 if (asprintf(author, "%s <%s>", name, email)
621 == -1)
622 return got_error_from_errno("asprintf");
623 return NULL;
625 /* TODO: Look up user in password database? */
626 return got_error(GOT_ERR_COMMIT_NO_AUTHOR);
630 *author = strdup(got_author);
631 if (*author == NULL)
632 return got_error_from_errno("strdup");
634 err = valid_author(*author);
635 if (err) {
636 free(*author);
637 *author = NULL;
639 return err;
642 static const struct got_error *
643 get_allowed_signers(char **allowed_signers, struct got_repository *repo,
644 struct got_worktree *worktree)
646 const char *got_allowed_signers = NULL;
647 const struct got_gotconfig *worktree_conf = NULL, *repo_conf = NULL;
649 *allowed_signers = NULL;
651 if (worktree)
652 worktree_conf = got_worktree_get_gotconfig(worktree);
653 repo_conf = got_repo_get_gotconfig(repo);
655 /*
656 * Priority of potential author information sources, from most
657 * significant to least significant:
658 * 1) work tree's .got/got.conf file
659 * 2) repository's got.conf file
660 */
662 if (worktree_conf)
663 got_allowed_signers = got_gotconfig_get_allowed_signers_file(
664 worktree_conf);
665 if (got_allowed_signers == NULL)
666 got_allowed_signers = got_gotconfig_get_allowed_signers_file(
667 repo_conf);
669 if (got_allowed_signers) {
670 *allowed_signers = strdup(got_allowed_signers);
671 if (*allowed_signers == NULL)
672 return got_error_from_errno("strdup");
674 return NULL;
677 static const struct got_error *
678 get_revoked_signers(char **revoked_signers, struct got_repository *repo,
679 struct got_worktree *worktree)
681 const char *got_revoked_signers = NULL;
682 const struct got_gotconfig *worktree_conf = NULL, *repo_conf = NULL;
684 *revoked_signers = NULL;
686 if (worktree)
687 worktree_conf = got_worktree_get_gotconfig(worktree);
688 repo_conf = got_repo_get_gotconfig(repo);
690 /*
691 * Priority of potential author information sources, from most
692 * significant to least significant:
693 * 1) work tree's .got/got.conf file
694 * 2) repository's got.conf file
695 */
697 if (worktree_conf)
698 got_revoked_signers = got_gotconfig_get_revoked_signers_file(
699 worktree_conf);
700 if (got_revoked_signers == NULL)
701 got_revoked_signers = got_gotconfig_get_revoked_signers_file(
702 repo_conf);
704 if (got_revoked_signers) {
705 *revoked_signers = strdup(got_revoked_signers);
706 if (*revoked_signers == NULL)
707 return got_error_from_errno("strdup");
709 return NULL;
712 static const char *
713 get_signer_id(struct got_repository *repo, struct got_worktree *worktree)
715 const char *got_signer_id = NULL;
716 const struct got_gotconfig *worktree_conf = NULL, *repo_conf = NULL;
718 if (worktree)
719 worktree_conf = got_worktree_get_gotconfig(worktree);
720 repo_conf = got_repo_get_gotconfig(repo);
722 /*
723 * Priority of potential author information sources, from most
724 * significant to least significant:
725 * 1) work tree's .got/got.conf file
726 * 2) repository's got.conf file
727 */
729 if (worktree_conf)
730 got_signer_id = got_gotconfig_get_signer_id(worktree_conf);
731 if (got_signer_id == NULL)
732 got_signer_id = got_gotconfig_get_signer_id(repo_conf);
734 return got_signer_id;
737 static const struct got_error *
738 get_gitconfig_path(char **gitconfig_path)
740 const char *homedir = getenv("HOME");
742 *gitconfig_path = NULL;
743 if (homedir) {
744 if (asprintf(gitconfig_path, "%s/.gitconfig", homedir) == -1)
745 return got_error_from_errno("asprintf");
748 return NULL;
751 static const struct got_error *
752 cmd_import(int argc, char *argv[])
754 const struct got_error *error = NULL;
755 char *path_dir = NULL, *repo_path = NULL, *logmsg = NULL;
756 char *gitconfig_path = NULL, *editor = NULL, *author = NULL;
757 const char *branch_name = NULL;
758 char *id_str = NULL, *logmsg_path = NULL;
759 char refname[PATH_MAX] = "refs/heads/";
760 struct got_repository *repo = NULL;
761 struct got_reference *branch_ref = NULL, *head_ref = NULL;
762 struct got_object_id *new_commit_id = NULL;
763 int ch, n = 0;
764 struct got_pathlist_head ignores;
765 struct got_pathlist_entry *pe;
766 int preserve_logmsg = 0;
767 int *pack_fds = NULL;
769 TAILQ_INIT(&ignores);
771 while ((ch = getopt(argc, argv, "b:I:m:r:")) != -1) {
772 switch (ch) {
773 case 'b':
774 branch_name = optarg;
775 break;
776 case 'I':
777 if (optarg[0] == '\0')
778 break;
779 error = got_pathlist_insert(&pe, &ignores, optarg,
780 NULL);
781 if (error)
782 goto done;
783 break;
784 case 'm':
785 logmsg = strdup(optarg);
786 if (logmsg == NULL) {
787 error = got_error_from_errno("strdup");
788 goto done;
790 break;
791 case 'r':
792 repo_path = realpath(optarg, NULL);
793 if (repo_path == NULL) {
794 error = got_error_from_errno2("realpath",
795 optarg);
796 goto done;
798 break;
799 default:
800 usage_import();
801 /* NOTREACHED */
805 argc -= optind;
806 argv += optind;
808 #ifndef PROFILE
809 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
810 "unveil",
811 NULL) == -1)
812 err(1, "pledge");
813 #endif
814 if (argc != 1)
815 usage_import();
817 if (repo_path == NULL) {
818 repo_path = getcwd(NULL, 0);
819 if (repo_path == NULL)
820 return got_error_from_errno("getcwd");
822 got_path_strip_trailing_slashes(repo_path);
823 error = get_gitconfig_path(&gitconfig_path);
824 if (error)
825 goto done;
826 error = got_repo_pack_fds_open(&pack_fds);
827 if (error != NULL)
828 goto done;
829 error = got_repo_open(&repo, repo_path, gitconfig_path, pack_fds);
830 if (error)
831 goto done;
833 error = get_author(&author, repo, NULL);
834 if (error)
835 return error;
837 /*
838 * Don't let the user create a branch name with a leading '-'.
839 * While technically a valid reference name, this case is usually
840 * an unintended typo.
841 */
842 if (branch_name && branch_name[0] == '-')
843 return got_error_path(branch_name, GOT_ERR_REF_NAME_MINUS);
845 error = got_ref_open(&head_ref, repo, GOT_REF_HEAD, 0);
846 if (error && error->code != GOT_ERR_NOT_REF)
847 goto done;
849 if (branch_name)
850 n = strlcat(refname, branch_name, sizeof(refname));
851 else if (head_ref && got_ref_is_symbolic(head_ref))
852 n = strlcpy(refname, got_ref_get_symref_target(head_ref),
853 sizeof(refname));
854 else
855 n = strlcat(refname, "main", sizeof(refname));
856 if (n >= sizeof(refname)) {
857 error = got_error(GOT_ERR_NO_SPACE);
858 goto done;
861 error = got_ref_open(&branch_ref, repo, refname, 0);
862 if (error) {
863 if (error->code != GOT_ERR_NOT_REF)
864 goto done;
865 } else {
866 error = got_error_msg(GOT_ERR_BRANCH_EXISTS,
867 "import target branch already exists");
868 goto done;
871 path_dir = realpath(argv[0], NULL);
872 if (path_dir == NULL) {
873 error = got_error_from_errno2("realpath", argv[0]);
874 goto done;
876 got_path_strip_trailing_slashes(path_dir);
878 /*
879 * unveil(2) traverses exec(2); if an editor is used we have
880 * to apply unveil after the log message has been written.
881 */
882 if (logmsg == NULL || strlen(logmsg) == 0) {
883 error = get_editor(&editor);
884 if (error)
885 goto done;
886 free(logmsg);
887 error = collect_import_msg(&logmsg, &logmsg_path, editor,
888 path_dir, refname);
889 if (error) {
890 if (error->code != GOT_ERR_COMMIT_MSG_EMPTY &&
891 logmsg_path != NULL)
892 preserve_logmsg = 1;
893 goto done;
897 if (unveil(path_dir, "r") != 0) {
898 error = got_error_from_errno2("unveil", path_dir);
899 if (logmsg_path)
900 preserve_logmsg = 1;
901 goto done;
904 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
905 if (error) {
906 if (logmsg_path)
907 preserve_logmsg = 1;
908 goto done;
911 error = got_repo_import(&new_commit_id, path_dir, logmsg,
912 author, &ignores, repo, import_progress, NULL);
913 if (error) {
914 if (logmsg_path)
915 preserve_logmsg = 1;
916 goto done;
919 error = got_ref_alloc(&branch_ref, refname, new_commit_id);
920 if (error) {
921 if (logmsg_path)
922 preserve_logmsg = 1;
923 goto done;
926 error = got_ref_write(branch_ref, repo);
927 if (error) {
928 if (logmsg_path)
929 preserve_logmsg = 1;
930 goto done;
933 error = got_object_id_str(&id_str, new_commit_id);
934 if (error) {
935 if (logmsg_path)
936 preserve_logmsg = 1;
937 goto done;
940 error = got_ref_open(&head_ref, repo, GOT_REF_HEAD, 0);
941 if (error) {
942 if (error->code != GOT_ERR_NOT_REF) {
943 if (logmsg_path)
944 preserve_logmsg = 1;
945 goto done;
948 error = got_ref_alloc_symref(&head_ref, GOT_REF_HEAD,
949 branch_ref);
950 if (error) {
951 if (logmsg_path)
952 preserve_logmsg = 1;
953 goto done;
956 error = got_ref_write(head_ref, repo);
957 if (error) {
958 if (logmsg_path)
959 preserve_logmsg = 1;
960 goto done;
964 printf("Created branch %s with commit %s\n",
965 got_ref_get_name(branch_ref), id_str);
966 done:
967 if (pack_fds) {
968 const struct got_error *pack_err =
969 got_repo_pack_fds_close(pack_fds);
970 if (error == NULL)
971 error = pack_err;
973 if (preserve_logmsg) {
974 fprintf(stderr, "%s: log message preserved in %s\n",
975 getprogname(), logmsg_path);
976 } else if (logmsg_path && unlink(logmsg_path) == -1 && error == NULL)
977 error = got_error_from_errno2("unlink", logmsg_path);
978 free(logmsg);
979 free(logmsg_path);
980 free(repo_path);
981 free(editor);
982 free(new_commit_id);
983 free(id_str);
984 free(author);
985 free(gitconfig_path);
986 if (branch_ref)
987 got_ref_close(branch_ref);
988 if (head_ref)
989 got_ref_close(head_ref);
990 return error;
993 __dead static void
994 usage_clone(void)
996 fprintf(stderr, "usage: %s clone [-almqv] [-b branch] [-R reference] "
997 "repository-URL [directory]\n", getprogname());
998 exit(1);
1001 struct got_fetch_progress_arg {
1002 char last_scaled_size[FMT_SCALED_STRSIZE];
1003 int last_p_indexed;
1004 int last_p_resolved;
1005 int verbosity;
1007 struct got_repository *repo;
1009 int create_configs;
1010 int configs_created;
1011 struct {
1012 struct got_pathlist_head *symrefs;
1013 struct got_pathlist_head *wanted_branches;
1014 struct got_pathlist_head *wanted_refs;
1015 const char *proto;
1016 const char *host;
1017 const char *port;
1018 const char *remote_repo_path;
1019 const char *git_url;
1020 int fetch_all_branches;
1021 int mirror_references;
1022 } config_info;
1025 /* XXX forward declaration */
1026 static const struct got_error *
1027 create_config_files(const char *proto, const char *host, const char *port,
1028 const char *remote_repo_path, const char *git_url, int fetch_all_branches,
1029 int mirror_references, struct got_pathlist_head *symrefs,
1030 struct got_pathlist_head *wanted_branches,
1031 struct got_pathlist_head *wanted_refs, struct got_repository *repo);
1033 static const struct got_error *
1034 fetch_progress(void *arg, const char *message, off_t packfile_size,
1035 int nobj_total, int nobj_indexed, int nobj_loose, int nobj_resolved)
1037 const struct got_error *err = NULL;
1038 struct got_fetch_progress_arg *a = arg;
1039 char scaled_size[FMT_SCALED_STRSIZE];
1040 int p_indexed, p_resolved;
1041 int print_size = 0, print_indexed = 0, print_resolved = 0;
1044 * In order to allow a failed clone to be resumed with 'got fetch'
1045 * we try to create configuration files as soon as possible.
1046 * Once the server has sent information about its default branch
1047 * we have all required information.
1049 if (a->create_configs && !a->configs_created &&
1050 !TAILQ_EMPTY(a->config_info.symrefs)) {
1051 err = create_config_files(a->config_info.proto,
1052 a->config_info.host, a->config_info.port,
1053 a->config_info.remote_repo_path,
1054 a->config_info.git_url,
1055 a->config_info.fetch_all_branches,
1056 a->config_info.mirror_references,
1057 a->config_info.symrefs,
1058 a->config_info.wanted_branches,
1059 a->config_info.wanted_refs, a->repo);
1060 if (err)
1061 return err;
1062 a->configs_created = 1;
1065 if (a->verbosity < 0)
1066 return NULL;
1068 if (message && message[0] != '\0') {
1069 printf("\rserver: %s", message);
1070 fflush(stdout);
1071 return NULL;
1074 if (packfile_size > 0 || nobj_indexed > 0) {
1075 if (fmt_scaled(packfile_size, scaled_size) == 0 &&
1076 (a->last_scaled_size[0] == '\0' ||
1077 strcmp(scaled_size, a->last_scaled_size)) != 0) {
1078 print_size = 1;
1079 if (strlcpy(a->last_scaled_size, scaled_size,
1080 FMT_SCALED_STRSIZE) >= FMT_SCALED_STRSIZE)
1081 return got_error(GOT_ERR_NO_SPACE);
1083 if (nobj_indexed > 0) {
1084 p_indexed = (nobj_indexed * 100) / nobj_total;
1085 if (p_indexed != a->last_p_indexed) {
1086 a->last_p_indexed = p_indexed;
1087 print_indexed = 1;
1088 print_size = 1;
1091 if (nobj_resolved > 0) {
1092 p_resolved = (nobj_resolved * 100) /
1093 (nobj_total - nobj_loose);
1094 if (p_resolved != a->last_p_resolved) {
1095 a->last_p_resolved = p_resolved;
1096 print_resolved = 1;
1097 print_indexed = 1;
1098 print_size = 1;
1103 if (print_size || print_indexed || print_resolved)
1104 printf("\r");
1105 if (print_size)
1106 printf("%*s fetched", FMT_SCALED_STRSIZE - 2, scaled_size);
1107 if (print_indexed)
1108 printf("; indexing %d%%", p_indexed);
1109 if (print_resolved)
1110 printf("; resolving deltas %d%%", p_resolved);
1111 if (print_size || print_indexed || print_resolved)
1112 fflush(stdout);
1114 return NULL;
1117 static const struct got_error *
1118 create_symref(const char *refname, struct got_reference *target_ref,
1119 int verbosity, struct got_repository *repo)
1121 const struct got_error *err;
1122 struct got_reference *head_symref;
1124 err = got_ref_alloc_symref(&head_symref, refname, target_ref);
1125 if (err)
1126 return err;
1128 err = got_ref_write(head_symref, repo);
1129 if (err == NULL && verbosity > 0) {
1130 printf("Created reference %s: %s\n", GOT_REF_HEAD,
1131 got_ref_get_name(target_ref));
1133 got_ref_close(head_symref);
1134 return err;
1137 static const struct got_error *
1138 list_remote_refs(struct got_pathlist_head *symrefs,
1139 struct got_pathlist_head *refs)
1141 const struct got_error *err;
1142 struct got_pathlist_entry *pe;
1144 TAILQ_FOREACH(pe, symrefs, entry) {
1145 const char *refname = pe->path;
1146 const char *targetref = pe->data;
1148 printf("%s: %s\n", refname, targetref);
1151 TAILQ_FOREACH(pe, refs, entry) {
1152 const char *refname = pe->path;
1153 struct got_object_id *id = pe->data;
1154 char *id_str;
1156 err = got_object_id_str(&id_str, id);
1157 if (err)
1158 return err;
1159 printf("%s: %s\n", refname, id_str);
1160 free(id_str);
1163 return NULL;
1166 static const struct got_error *
1167 create_ref(const char *refname, struct got_object_id *id,
1168 int verbosity, struct got_repository *repo)
1170 const struct got_error *err = NULL;
1171 struct got_reference *ref;
1172 char *id_str;
1174 err = got_object_id_str(&id_str, id);
1175 if (err)
1176 return err;
1178 err = got_ref_alloc(&ref, refname, id);
1179 if (err)
1180 goto done;
1182 err = got_ref_write(ref, repo);
1183 got_ref_close(ref);
1185 if (err == NULL && verbosity >= 0)
1186 printf("Created reference %s: %s\n", refname, id_str);
1187 done:
1188 free(id_str);
1189 return err;
1192 static int
1193 match_wanted_ref(const char *refname, const char *wanted_ref)
1195 if (strncmp(refname, "refs/", 5) != 0)
1196 return 0;
1197 refname += 5;
1200 * Prevent fetching of references that won't make any
1201 * sense outside of the remote repository's context.
1203 if (strncmp(refname, "got/", 4) == 0)
1204 return 0;
1205 if (strncmp(refname, "remotes/", 8) == 0)
1206 return 0;
1208 if (strncmp(wanted_ref, "refs/", 5) == 0)
1209 wanted_ref += 5;
1211 /* Allow prefix match. */
1212 if (got_path_is_child(refname, wanted_ref, strlen(wanted_ref)))
1213 return 1;
1215 /* Allow exact match. */
1216 return (strcmp(refname, wanted_ref) == 0);
1219 static int
1220 is_wanted_ref(struct got_pathlist_head *wanted_refs, const char *refname)
1222 struct got_pathlist_entry *pe;
1224 TAILQ_FOREACH(pe, wanted_refs, entry) {
1225 if (match_wanted_ref(refname, pe->path))
1226 return 1;
1229 return 0;
1232 static const struct got_error *
1233 create_wanted_ref(const char *refname, struct got_object_id *id,
1234 const char *remote_repo_name, int verbosity, struct got_repository *repo)
1236 const struct got_error *err;
1237 char *remote_refname;
1239 if (strncmp("refs/", refname, 5) == 0)
1240 refname += 5;
1242 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
1243 remote_repo_name, refname) == -1)
1244 return got_error_from_errno("asprintf");
1246 err = create_ref(remote_refname, id, verbosity, repo);
1247 free(remote_refname);
1248 return err;
1251 static const struct got_error *
1252 create_gotconfig(const char *proto, const char *host, const char *port,
1253 const char *remote_repo_path, const char *default_branch,
1254 int fetch_all_branches, struct got_pathlist_head *wanted_branches,
1255 struct got_pathlist_head *wanted_refs, int mirror_references,
1256 struct got_repository *repo)
1258 const struct got_error *err = NULL;
1259 char *gotconfig_path = NULL;
1260 char *gotconfig = NULL;
1261 FILE *gotconfig_file = NULL;
1262 const char *branchname = NULL;
1263 char *branches = NULL, *refs = NULL;
1264 ssize_t n;
1266 if (!fetch_all_branches && !TAILQ_EMPTY(wanted_branches)) {
1267 struct got_pathlist_entry *pe;
1268 TAILQ_FOREACH(pe, wanted_branches, entry) {
1269 char *s;
1270 branchname = pe->path;
1271 if (strncmp(branchname, "refs/heads/", 11) == 0)
1272 branchname += 11;
1273 if (asprintf(&s, "%s\"%s\" ",
1274 branches ? branches : "", branchname) == -1) {
1275 err = got_error_from_errno("asprintf");
1276 goto done;
1278 free(branches);
1279 branches = s;
1281 } else if (!fetch_all_branches && default_branch) {
1282 branchname = default_branch;
1283 if (strncmp(branchname, "refs/heads/", 11) == 0)
1284 branchname += 11;
1285 if (asprintf(&branches, "\"%s\" ", branchname) == -1) {
1286 err = got_error_from_errno("asprintf");
1287 goto done;
1290 if (!TAILQ_EMPTY(wanted_refs)) {
1291 struct got_pathlist_entry *pe;
1292 TAILQ_FOREACH(pe, wanted_refs, entry) {
1293 char *s;
1294 const char *refname = pe->path;
1295 if (strncmp(refname, "refs/", 5) == 0)
1296 branchname += 5;
1297 if (asprintf(&s, "%s\"%s\" ",
1298 refs ? refs : "", refname) == -1) {
1299 err = got_error_from_errno("asprintf");
1300 goto done;
1302 free(refs);
1303 refs = s;
1307 /* Create got.conf(5). */
1308 gotconfig_path = got_repo_get_path_gotconfig(repo);
1309 if (gotconfig_path == NULL) {
1310 err = got_error_from_errno("got_repo_get_path_gotconfig");
1311 goto done;
1313 gotconfig_file = fopen(gotconfig_path, "ae");
1314 if (gotconfig_file == NULL) {
1315 err = got_error_from_errno2("fopen", gotconfig_path);
1316 goto done;
1318 if (asprintf(&gotconfig,
1319 "remote \"%s\" {\n"
1320 "\tserver %s\n"
1321 "\tprotocol %s\n"
1322 "%s%s%s"
1323 "\trepository \"%s\"\n"
1324 "%s%s%s"
1325 "%s%s%s"
1326 "%s"
1327 "%s"
1328 "}\n",
1329 GOT_FETCH_DEFAULT_REMOTE_NAME, host, proto,
1330 port ? "\tport " : "", port ? port : "", port ? "\n" : "",
1331 remote_repo_path, branches ? "\tbranch { " : "",
1332 branches ? branches : "", branches ? "}\n" : "",
1333 refs ? "\treference { " : "", refs ? refs : "", refs ? "}\n" : "",
1334 mirror_references ? "\tmirror_references yes\n" : "",
1335 fetch_all_branches ? "\tfetch_all_branches yes\n" : "") == -1) {
1336 err = got_error_from_errno("asprintf");
1337 goto done;
1339 n = fwrite(gotconfig, 1, strlen(gotconfig), gotconfig_file);
1340 if (n != strlen(gotconfig)) {
1341 err = got_ferror(gotconfig_file, GOT_ERR_IO);
1342 goto done;
1345 done:
1346 if (gotconfig_file && fclose(gotconfig_file) == EOF && err == NULL)
1347 err = got_error_from_errno2("fclose", gotconfig_path);
1348 free(gotconfig_path);
1349 free(branches);
1350 return err;
1353 static const struct got_error *
1354 create_gitconfig(const char *git_url, const char *default_branch,
1355 int fetch_all_branches, struct got_pathlist_head *wanted_branches,
1356 struct got_pathlist_head *wanted_refs, int mirror_references,
1357 struct got_repository *repo)
1359 const struct got_error *err = NULL;
1360 char *gitconfig_path = NULL;
1361 char *gitconfig = NULL;
1362 FILE *gitconfig_file = NULL;
1363 char *branches = NULL, *refs = NULL;
1364 const char *branchname;
1365 ssize_t n;
1367 /* Create a config file Git can understand. */
1368 gitconfig_path = got_repo_get_path_gitconfig(repo);
1369 if (gitconfig_path == NULL) {
1370 err = got_error_from_errno("got_repo_get_path_gitconfig");
1371 goto done;
1373 gitconfig_file = fopen(gitconfig_path, "ae");
1374 if (gitconfig_file == NULL) {
1375 err = got_error_from_errno2("fopen", gitconfig_path);
1376 goto done;
1378 if (fetch_all_branches) {
1379 if (mirror_references) {
1380 if (asprintf(&branches,
1381 "\tfetch = refs/heads/*:refs/heads/*\n") == -1) {
1382 err = got_error_from_errno("asprintf");
1383 goto done;
1385 } else if (asprintf(&branches,
1386 "\tfetch = refs/heads/*:refs/remotes/%s/*\n",
1387 GOT_FETCH_DEFAULT_REMOTE_NAME) == -1) {
1388 err = got_error_from_errno("asprintf");
1389 goto done;
1391 } else if (!TAILQ_EMPTY(wanted_branches)) {
1392 struct got_pathlist_entry *pe;
1393 TAILQ_FOREACH(pe, wanted_branches, entry) {
1394 char *s;
1395 branchname = pe->path;
1396 if (strncmp(branchname, "refs/heads/", 11) == 0)
1397 branchname += 11;
1398 if (mirror_references) {
1399 if (asprintf(&s,
1400 "%s\tfetch = refs/heads/%s:refs/heads/%s\n",
1401 branches ? branches : "",
1402 branchname, branchname) == -1) {
1403 err = got_error_from_errno("asprintf");
1404 goto done;
1406 } else if (asprintf(&s,
1407 "%s\tfetch = refs/heads/%s:refs/remotes/%s/%s\n",
1408 branches ? branches : "",
1409 branchname, GOT_FETCH_DEFAULT_REMOTE_NAME,
1410 branchname) == -1) {
1411 err = got_error_from_errno("asprintf");
1412 goto done;
1414 free(branches);
1415 branches = s;
1417 } else {
1419 * If the server specified a default branch, use just that one.
1420 * Otherwise fall back to fetching all branches on next fetch.
1422 if (default_branch) {
1423 branchname = default_branch;
1424 if (strncmp(branchname, "refs/heads/", 11) == 0)
1425 branchname += 11;
1426 } else
1427 branchname = "*"; /* fall back to all branches */
1428 if (mirror_references) {
1429 if (asprintf(&branches,
1430 "\tfetch = refs/heads/%s:refs/heads/%s\n",
1431 branchname, branchname) == -1) {
1432 err = got_error_from_errno("asprintf");
1433 goto done;
1435 } else if (asprintf(&branches,
1436 "\tfetch = refs/heads/%s:refs/remotes/%s/%s\n",
1437 branchname, GOT_FETCH_DEFAULT_REMOTE_NAME,
1438 branchname) == -1) {
1439 err = got_error_from_errno("asprintf");
1440 goto done;
1443 if (!TAILQ_EMPTY(wanted_refs)) {
1444 struct got_pathlist_entry *pe;
1445 TAILQ_FOREACH(pe, wanted_refs, entry) {
1446 char *s;
1447 const char *refname = pe->path;
1448 if (strncmp(refname, "refs/", 5) == 0)
1449 refname += 5;
1450 if (mirror_references) {
1451 if (asprintf(&s,
1452 "%s\tfetch = refs/%s:refs/%s\n",
1453 refs ? refs : "", refname, refname) == -1) {
1454 err = got_error_from_errno("asprintf");
1455 goto done;
1457 } else if (asprintf(&s,
1458 "%s\tfetch = refs/%s:refs/remotes/%s/%s\n",
1459 refs ? refs : "",
1460 refname, GOT_FETCH_DEFAULT_REMOTE_NAME,
1461 refname) == -1) {
1462 err = got_error_from_errno("asprintf");
1463 goto done;
1465 free(refs);
1466 refs = s;
1470 if (asprintf(&gitconfig,
1471 "[remote \"%s\"]\n"
1472 "\turl = %s\n"
1473 "%s"
1474 "%s"
1475 "\tfetch = refs/tags/*:refs/tags/*\n",
1476 GOT_FETCH_DEFAULT_REMOTE_NAME, git_url, branches ? branches : "",
1477 refs ? refs : "") == -1) {
1478 err = got_error_from_errno("asprintf");
1479 goto done;
1481 n = fwrite(gitconfig, 1, strlen(gitconfig), gitconfig_file);
1482 if (n != strlen(gitconfig)) {
1483 err = got_ferror(gitconfig_file, GOT_ERR_IO);
1484 goto done;
1486 done:
1487 if (gitconfig_file && fclose(gitconfig_file) == EOF && err == NULL)
1488 err = got_error_from_errno2("fclose", gitconfig_path);
1489 free(gitconfig_path);
1490 free(branches);
1491 return err;
1494 static const struct got_error *
1495 create_config_files(const char *proto, const char *host, const char *port,
1496 const char *remote_repo_path, const char *git_url, int fetch_all_branches,
1497 int mirror_references, struct got_pathlist_head *symrefs,
1498 struct got_pathlist_head *wanted_branches,
1499 struct got_pathlist_head *wanted_refs, struct got_repository *repo)
1501 const struct got_error *err = NULL;
1502 const char *default_branch = NULL;
1503 struct got_pathlist_entry *pe;
1506 * If we asked for a set of wanted branches then use the first
1507 * one of those.
1509 if (!TAILQ_EMPTY(wanted_branches)) {
1510 pe = TAILQ_FIRST(wanted_branches);
1511 default_branch = pe->path;
1512 } else {
1513 /* First HEAD ref listed by server is the default branch. */
1514 TAILQ_FOREACH(pe, symrefs, entry) {
1515 const char *refname = pe->path;
1516 const char *target = pe->data;
1518 if (strcmp(refname, GOT_REF_HEAD) != 0)
1519 continue;
1521 default_branch = target;
1522 break;
1526 /* Create got.conf(5). */
1527 err = create_gotconfig(proto, host, port, remote_repo_path,
1528 default_branch, fetch_all_branches, wanted_branches,
1529 wanted_refs, mirror_references, repo);
1530 if (err)
1531 return err;
1533 /* Create a config file Git can understand. */
1534 return create_gitconfig(git_url, default_branch, fetch_all_branches,
1535 wanted_branches, wanted_refs, mirror_references, repo);
1538 static const struct got_error *
1539 cmd_clone(int argc, char *argv[])
1541 const struct got_error *error = NULL;
1542 const char *uri, *dirname;
1543 char *proto, *host, *port, *repo_name, *server_path;
1544 char *default_destdir = NULL, *id_str = NULL;
1545 const char *repo_path;
1546 struct got_repository *repo = NULL;
1547 struct got_pathlist_head refs, symrefs, wanted_branches, wanted_refs;
1548 struct got_pathlist_entry *pe;
1549 struct got_object_id *pack_hash = NULL;
1550 int ch, fetchfd = -1, fetchstatus;
1551 pid_t fetchpid = -1;
1552 struct got_fetch_progress_arg fpa;
1553 char *git_url = NULL;
1554 int verbosity = 0, fetch_all_branches = 0, mirror_references = 0;
1555 int list_refs_only = 0;
1556 int *pack_fds = NULL;
1558 TAILQ_INIT(&refs);
1559 TAILQ_INIT(&symrefs);
1560 TAILQ_INIT(&wanted_branches);
1561 TAILQ_INIT(&wanted_refs);
1563 while ((ch = getopt(argc, argv, "ab:lmqR:v")) != -1) {
1564 switch (ch) {
1565 case 'a':
1566 fetch_all_branches = 1;
1567 break;
1568 case 'b':
1569 error = got_pathlist_append(&wanted_branches,
1570 optarg, NULL);
1571 if (error)
1572 return error;
1573 break;
1574 case 'l':
1575 list_refs_only = 1;
1576 break;
1577 case 'm':
1578 mirror_references = 1;
1579 break;
1580 case 'q':
1581 verbosity = -1;
1582 break;
1583 case 'R':
1584 error = got_pathlist_append(&wanted_refs,
1585 optarg, NULL);
1586 if (error)
1587 return error;
1588 break;
1589 case 'v':
1590 if (verbosity < 0)
1591 verbosity = 0;
1592 else if (verbosity < 3)
1593 verbosity++;
1594 break;
1595 default:
1596 usage_clone();
1597 break;
1600 argc -= optind;
1601 argv += optind;
1603 if (fetch_all_branches && !TAILQ_EMPTY(&wanted_branches))
1604 option_conflict('a', 'b');
1605 if (list_refs_only) {
1606 if (!TAILQ_EMPTY(&wanted_branches))
1607 option_conflict('l', 'b');
1608 if (fetch_all_branches)
1609 option_conflict('l', 'a');
1610 if (mirror_references)
1611 option_conflict('l', 'm');
1612 if (!TAILQ_EMPTY(&wanted_refs))
1613 option_conflict('l', 'R');
1616 uri = argv[0];
1618 if (argc == 1)
1619 dirname = NULL;
1620 else if (argc == 2)
1621 dirname = argv[1];
1622 else
1623 usage_clone();
1625 error = got_dial_parse_uri(&proto, &host, &port, &server_path,
1626 &repo_name, uri);
1627 if (error)
1628 goto done;
1630 if (asprintf(&git_url, "%s://%s%s%s%s%s", proto,
1631 host, port ? ":" : "", port ? port : "",
1632 server_path[0] != '/' ? "/" : "", server_path) == -1) {
1633 error = got_error_from_errno("asprintf");
1634 goto done;
1637 if (strcmp(proto, "git") == 0) {
1638 #ifndef PROFILE
1639 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
1640 "sendfd dns inet unveil", NULL) == -1)
1641 err(1, "pledge");
1642 #endif
1643 } else if (strcmp(proto, "git+ssh") == 0 ||
1644 strcmp(proto, "ssh") == 0) {
1645 #ifndef PROFILE
1646 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
1647 "sendfd unveil", NULL) == -1)
1648 err(1, "pledge");
1649 #endif
1650 } else if (strcmp(proto, "http") == 0 ||
1651 strcmp(proto, "git+http") == 0) {
1652 error = got_error_path(proto, GOT_ERR_NOT_IMPL);
1653 goto done;
1654 } else {
1655 error = got_error_path(proto, GOT_ERR_BAD_PROTO);
1656 goto done;
1658 if (dirname == NULL) {
1659 if (asprintf(&default_destdir, "%s.git", repo_name) == -1) {
1660 error = got_error_from_errno("asprintf");
1661 goto done;
1663 repo_path = default_destdir;
1664 } else
1665 repo_path = dirname;
1667 if (!list_refs_only) {
1668 error = got_path_mkdir(repo_path);
1669 if (error &&
1670 (!(error->code == GOT_ERR_ERRNO && errno == EISDIR) &&
1671 !(error->code == GOT_ERR_ERRNO && errno == EEXIST)))
1672 goto done;
1673 if (!got_path_dir_is_empty(repo_path)) {
1674 error = got_error_path(repo_path,
1675 GOT_ERR_DIR_NOT_EMPTY);
1676 goto done;
1680 error = got_dial_apply_unveil(proto);
1681 if (error)
1682 goto done;
1684 error = apply_unveil(repo_path, 0, NULL);
1685 if (error)
1686 goto done;
1688 if (verbosity >= 0)
1689 printf("Connecting to %s\n", git_url);
1691 error = got_fetch_connect(&fetchpid, &fetchfd, proto, host, port,
1692 server_path, verbosity);
1693 if (error)
1694 goto done;
1696 if (!list_refs_only) {
1697 error = got_repo_init(repo_path, NULL);
1698 if (error)
1699 goto done;
1700 error = got_repo_pack_fds_open(&pack_fds);
1701 if (error != NULL)
1702 goto done;
1703 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
1704 if (error)
1705 goto done;
1708 fpa.last_scaled_size[0] = '\0';
1709 fpa.last_p_indexed = -1;
1710 fpa.last_p_resolved = -1;
1711 fpa.verbosity = verbosity;
1712 fpa.create_configs = 1;
1713 fpa.configs_created = 0;
1714 fpa.repo = repo;
1715 fpa.config_info.symrefs = &symrefs;
1716 fpa.config_info.wanted_branches = &wanted_branches;
1717 fpa.config_info.wanted_refs = &wanted_refs;
1718 fpa.config_info.proto = proto;
1719 fpa.config_info.host = host;
1720 fpa.config_info.port = port;
1721 fpa.config_info.remote_repo_path = server_path;
1722 fpa.config_info.git_url = git_url;
1723 fpa.config_info.fetch_all_branches = fetch_all_branches;
1724 fpa.config_info.mirror_references = mirror_references;
1725 error = got_fetch_pack(&pack_hash, &refs, &symrefs,
1726 GOT_FETCH_DEFAULT_REMOTE_NAME, mirror_references,
1727 fetch_all_branches, &wanted_branches, &wanted_refs,
1728 list_refs_only, verbosity, fetchfd, repo, NULL,
1729 fetch_progress, &fpa);
1730 if (error)
1731 goto done;
1733 if (list_refs_only) {
1734 error = list_remote_refs(&symrefs, &refs);
1735 goto done;
1738 if (pack_hash == NULL) {
1739 error = got_error_fmt(GOT_ERR_FETCH_FAILED, "%s",
1740 "server sent an empty pack file");
1741 goto done;
1743 error = got_object_id_str(&id_str, pack_hash);
1744 if (error)
1745 goto done;
1746 if (verbosity >= 0)
1747 printf("\nFetched %s.pack\n", id_str);
1748 free(id_str);
1750 /* Set up references provided with the pack file. */
1751 TAILQ_FOREACH(pe, &refs, entry) {
1752 const char *refname = pe->path;
1753 struct got_object_id *id = pe->data;
1754 char *remote_refname;
1756 if (is_wanted_ref(&wanted_refs, refname) &&
1757 !mirror_references) {
1758 error = create_wanted_ref(refname, id,
1759 GOT_FETCH_DEFAULT_REMOTE_NAME,
1760 verbosity - 1, repo);
1761 if (error)
1762 goto done;
1763 continue;
1766 error = create_ref(refname, id, verbosity - 1, repo);
1767 if (error)
1768 goto done;
1770 if (mirror_references)
1771 continue;
1773 if (strncmp("refs/heads/", refname, 11) != 0)
1774 continue;
1776 if (asprintf(&remote_refname,
1777 "refs/remotes/%s/%s", GOT_FETCH_DEFAULT_REMOTE_NAME,
1778 refname + 11) == -1) {
1779 error = got_error_from_errno("asprintf");
1780 goto done;
1782 error = create_ref(remote_refname, id, verbosity - 1, repo);
1783 free(remote_refname);
1784 if (error)
1785 goto done;
1788 /* Set the HEAD reference if the server provided one. */
1789 TAILQ_FOREACH(pe, &symrefs, entry) {
1790 struct got_reference *target_ref;
1791 const char *refname = pe->path;
1792 const char *target = pe->data;
1793 char *remote_refname = NULL, *remote_target = NULL;
1795 if (strcmp(refname, GOT_REF_HEAD) != 0)
1796 continue;
1798 error = got_ref_open(&target_ref, repo, target, 0);
1799 if (error) {
1800 if (error->code == GOT_ERR_NOT_REF) {
1801 error = NULL;
1802 continue;
1804 goto done;
1807 error = create_symref(refname, target_ref, verbosity, repo);
1808 got_ref_close(target_ref);
1809 if (error)
1810 goto done;
1812 if (mirror_references)
1813 continue;
1815 if (strncmp("refs/heads/", target, 11) != 0)
1816 continue;
1818 if (asprintf(&remote_refname,
1819 "refs/remotes/%s/%s", GOT_FETCH_DEFAULT_REMOTE_NAME,
1820 refname) == -1) {
1821 error = got_error_from_errno("asprintf");
1822 goto done;
1824 if (asprintf(&remote_target,
1825 "refs/remotes/%s/%s", GOT_FETCH_DEFAULT_REMOTE_NAME,
1826 target + 11) == -1) {
1827 error = got_error_from_errno("asprintf");
1828 free(remote_refname);
1829 goto done;
1831 error = got_ref_open(&target_ref, repo, remote_target, 0);
1832 if (error) {
1833 free(remote_refname);
1834 free(remote_target);
1835 if (error->code == GOT_ERR_NOT_REF) {
1836 error = NULL;
1837 continue;
1839 goto done;
1841 error = create_symref(remote_refname, target_ref,
1842 verbosity - 1, repo);
1843 free(remote_refname);
1844 free(remote_target);
1845 got_ref_close(target_ref);
1846 if (error)
1847 goto done;
1849 if (pe == NULL) {
1851 * We failed to set the HEAD reference. If we asked for
1852 * a set of wanted branches use the first of one of those
1853 * which could be fetched instead.
1855 TAILQ_FOREACH(pe, &wanted_branches, entry) {
1856 const char *target = pe->path;
1857 struct got_reference *target_ref;
1859 error = got_ref_open(&target_ref, repo, target, 0);
1860 if (error) {
1861 if (error->code == GOT_ERR_NOT_REF) {
1862 error = NULL;
1863 continue;
1865 goto done;
1868 error = create_symref(GOT_REF_HEAD, target_ref,
1869 verbosity, repo);
1870 got_ref_close(target_ref);
1871 if (error)
1872 goto done;
1873 break;
1876 if (!fpa.configs_created && pe != NULL) {
1877 error = create_config_files(fpa.config_info.proto,
1878 fpa.config_info.host, fpa.config_info.port,
1879 fpa.config_info.remote_repo_path,
1880 fpa.config_info.git_url,
1881 fpa.config_info.fetch_all_branches,
1882 fpa.config_info.mirror_references,
1883 fpa.config_info.symrefs,
1884 fpa.config_info.wanted_branches,
1885 fpa.config_info.wanted_refs, fpa.repo);
1886 if (error)
1887 goto done;
1891 if (verbosity >= 0)
1892 printf("Created %s repository '%s'\n",
1893 mirror_references ? "mirrored" : "cloned", repo_path);
1894 done:
1895 if (pack_fds) {
1896 const struct got_error *pack_err =
1897 got_repo_pack_fds_close(pack_fds);
1898 if (error == NULL)
1899 error = pack_err;
1901 if (fetchpid > 0) {
1902 if (kill(fetchpid, SIGTERM) == -1)
1903 error = got_error_from_errno("kill");
1904 if (waitpid(fetchpid, &fetchstatus, 0) == -1 && error == NULL)
1905 error = got_error_from_errno("waitpid");
1907 if (fetchfd != -1 && close(fetchfd) == -1 && error == NULL)
1908 error = got_error_from_errno("close");
1909 if (repo) {
1910 const struct got_error *close_err = got_repo_close(repo);
1911 if (error == NULL)
1912 error = close_err;
1914 got_pathlist_free(&refs, GOT_PATHLIST_FREE_ALL);
1915 got_pathlist_free(&symrefs, GOT_PATHLIST_FREE_ALL);
1916 got_pathlist_free(&wanted_branches, GOT_PATHLIST_FREE_NONE);
1917 got_pathlist_free(&wanted_refs, GOT_PATHLIST_FREE_NONE);
1918 free(pack_hash);
1919 free(proto);
1920 free(host);
1921 free(port);
1922 free(server_path);
1923 free(repo_name);
1924 free(default_destdir);
1925 free(git_url);
1926 return error;
1929 static const struct got_error *
1930 update_ref(struct got_reference *ref, struct got_object_id *new_id,
1931 int replace_tags, int verbosity, struct got_repository *repo)
1933 const struct got_error *err = NULL;
1934 char *new_id_str = NULL;
1935 struct got_object_id *old_id = NULL;
1937 err = got_object_id_str(&new_id_str, new_id);
1938 if (err)
1939 goto done;
1941 if (!replace_tags &&
1942 strncmp(got_ref_get_name(ref), "refs/tags/", 10) == 0) {
1943 err = got_ref_resolve(&old_id, repo, ref);
1944 if (err)
1945 goto done;
1946 if (got_object_id_cmp(old_id, new_id) == 0)
1947 goto done;
1948 if (verbosity >= 0) {
1949 printf("Rejecting update of existing tag %s: %s\n",
1950 got_ref_get_name(ref), new_id_str);
1952 goto done;
1955 if (got_ref_is_symbolic(ref)) {
1956 if (verbosity >= 0) {
1957 printf("Replacing reference %s: %s\n",
1958 got_ref_get_name(ref),
1959 got_ref_get_symref_target(ref));
1961 err = got_ref_change_symref_to_ref(ref, new_id);
1962 if (err)
1963 goto done;
1964 err = got_ref_write(ref, repo);
1965 if (err)
1966 goto done;
1967 } else {
1968 err = got_ref_resolve(&old_id, repo, ref);
1969 if (err)
1970 goto done;
1971 if (got_object_id_cmp(old_id, new_id) == 0)
1972 goto done;
1974 err = got_ref_change_ref(ref, new_id);
1975 if (err)
1976 goto done;
1977 err = got_ref_write(ref, repo);
1978 if (err)
1979 goto done;
1982 if (verbosity >= 0)
1983 printf("Updated %s: %s\n", got_ref_get_name(ref),
1984 new_id_str);
1985 done:
1986 free(old_id);
1987 free(new_id_str);
1988 return err;
1991 static const struct got_error *
1992 update_symref(const char *refname, struct got_reference *target_ref,
1993 int verbosity, struct got_repository *repo)
1995 const struct got_error *err = NULL, *unlock_err;
1996 struct got_reference *symref;
1997 int symref_is_locked = 0;
1999 err = got_ref_open(&symref, repo, refname, 1);
2000 if (err) {
2001 if (err->code != GOT_ERR_NOT_REF)
2002 return err;
2003 err = got_ref_alloc_symref(&symref, refname, target_ref);
2004 if (err)
2005 goto done;
2007 err = got_ref_write(symref, repo);
2008 if (err)
2009 goto done;
2011 if (verbosity >= 0)
2012 printf("Created reference %s: %s\n",
2013 got_ref_get_name(symref),
2014 got_ref_get_symref_target(symref));
2015 } else {
2016 symref_is_locked = 1;
2018 if (strcmp(got_ref_get_symref_target(symref),
2019 got_ref_get_name(target_ref)) == 0)
2020 goto done;
2022 err = got_ref_change_symref(symref,
2023 got_ref_get_name(target_ref));
2024 if (err)
2025 goto done;
2027 err = got_ref_write(symref, repo);
2028 if (err)
2029 goto done;
2031 if (verbosity >= 0)
2032 printf("Updated %s: %s\n", got_ref_get_name(symref),
2033 got_ref_get_symref_target(symref));
2036 done:
2037 if (symref_is_locked) {
2038 unlock_err = got_ref_unlock(symref);
2039 if (unlock_err && err == NULL)
2040 err = unlock_err;
2042 got_ref_close(symref);
2043 return err;
2046 __dead static void
2047 usage_fetch(void)
2049 fprintf(stderr, "usage: %s fetch [-adlqtvX] [-b branch] "
2050 "[-R reference] [-r repository-path] [remote-repository]\n",
2051 getprogname());
2052 exit(1);
2055 static const struct got_error *
2056 delete_missing_ref(struct got_reference *ref,
2057 int verbosity, struct got_repository *repo)
2059 const struct got_error *err = NULL;
2060 struct got_object_id *id = NULL;
2061 char *id_str = NULL;
2063 if (got_ref_is_symbolic(ref)) {
2064 err = got_ref_delete(ref, repo);
2065 if (err)
2066 return err;
2067 if (verbosity >= 0) {
2068 printf("Deleted %s: %s\n",
2069 got_ref_get_name(ref),
2070 got_ref_get_symref_target(ref));
2072 } else {
2073 err = got_ref_resolve(&id, repo, ref);
2074 if (err)
2075 return err;
2076 err = got_object_id_str(&id_str, id);
2077 if (err)
2078 goto done;
2080 err = got_ref_delete(ref, repo);
2081 if (err)
2082 goto done;
2083 if (verbosity >= 0) {
2084 printf("Deleted %s: %s\n",
2085 got_ref_get_name(ref), id_str);
2088 done:
2089 free(id);
2090 free(id_str);
2091 return err;
2094 static const struct got_error *
2095 delete_missing_refs(struct got_pathlist_head *their_refs,
2096 struct got_pathlist_head *their_symrefs,
2097 const struct got_remote_repo *remote,
2098 int verbosity, struct got_repository *repo)
2100 const struct got_error *err = NULL, *unlock_err;
2101 struct got_reflist_head my_refs;
2102 struct got_reflist_entry *re;
2103 struct got_pathlist_entry *pe;
2104 char *remote_namespace = NULL;
2105 char *local_refname = NULL;
2107 TAILQ_INIT(&my_refs);
2109 if (asprintf(&remote_namespace, "refs/remotes/%s/", remote->name)
2110 == -1)
2111 return got_error_from_errno("asprintf");
2113 err = got_ref_list(&my_refs, repo, NULL, got_ref_cmp_by_name, NULL);
2114 if (err)
2115 goto done;
2117 TAILQ_FOREACH(re, &my_refs, entry) {
2118 const char *refname = got_ref_get_name(re->ref);
2119 const char *their_refname;
2121 if (remote->mirror_references) {
2122 their_refname = refname;
2123 } else {
2124 if (strncmp(refname, remote_namespace,
2125 strlen(remote_namespace)) == 0) {
2126 if (strcmp(refname + strlen(remote_namespace),
2127 GOT_REF_HEAD) == 0)
2128 continue;
2129 if (asprintf(&local_refname, "refs/heads/%s",
2130 refname + strlen(remote_namespace)) == -1) {
2131 err = got_error_from_errno("asprintf");
2132 goto done;
2134 } else if (strncmp(refname, "refs/tags/", 10) != 0)
2135 continue;
2137 their_refname = local_refname;
2140 TAILQ_FOREACH(pe, their_refs, entry) {
2141 if (strcmp(their_refname, pe->path) == 0)
2142 break;
2144 if (pe != NULL)
2145 continue;
2147 TAILQ_FOREACH(pe, their_symrefs, entry) {
2148 if (strcmp(their_refname, pe->path) == 0)
2149 break;
2151 if (pe != NULL)
2152 continue;
2154 err = delete_missing_ref(re->ref, verbosity, repo);
2155 if (err)
2156 break;
2158 if (local_refname) {
2159 struct got_reference *ref;
2160 err = got_ref_open(&ref, repo, local_refname, 1);
2161 if (err) {
2162 if (err->code != GOT_ERR_NOT_REF)
2163 break;
2164 free(local_refname);
2165 local_refname = NULL;
2166 continue;
2168 err = delete_missing_ref(ref, verbosity, repo);
2169 if (err)
2170 break;
2171 unlock_err = got_ref_unlock(ref);
2172 got_ref_close(ref);
2173 if (unlock_err && err == NULL) {
2174 err = unlock_err;
2175 break;
2178 free(local_refname);
2179 local_refname = NULL;
2182 done:
2183 got_ref_list_free(&my_refs);
2184 free(remote_namespace);
2185 free(local_refname);
2186 return err;
2189 static const struct got_error *
2190 update_wanted_ref(const char *refname, struct got_object_id *id,
2191 const char *remote_repo_name, int verbosity, struct got_repository *repo)
2193 const struct got_error *err, *unlock_err;
2194 char *remote_refname;
2195 struct got_reference *ref;
2197 if (strncmp("refs/", refname, 5) == 0)
2198 refname += 5;
2200 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
2201 remote_repo_name, refname) == -1)
2202 return got_error_from_errno("asprintf");
2204 err = got_ref_open(&ref, repo, remote_refname, 1);
2205 if (err) {
2206 if (err->code != GOT_ERR_NOT_REF)
2207 goto done;
2208 err = create_ref(remote_refname, id, verbosity, repo);
2209 } else {
2210 err = update_ref(ref, id, 0, verbosity, repo);
2211 unlock_err = got_ref_unlock(ref);
2212 if (unlock_err && err == NULL)
2213 err = unlock_err;
2214 got_ref_close(ref);
2216 done:
2217 free(remote_refname);
2218 return err;
2221 static const struct got_error *
2222 delete_ref(struct got_repository *repo, struct got_reference *ref)
2224 const struct got_error *err = NULL;
2225 struct got_object_id *id = NULL;
2226 char *id_str = NULL;
2227 const char *target;
2229 if (got_ref_is_symbolic(ref)) {
2230 target = got_ref_get_symref_target(ref);
2231 } else {
2232 err = got_ref_resolve(&id, repo, ref);
2233 if (err)
2234 goto done;
2235 err = got_object_id_str(&id_str, id);
2236 if (err)
2237 goto done;
2238 target = id_str;
2241 err = got_ref_delete(ref, repo);
2242 if (err)
2243 goto done;
2245 printf("Deleted %s: %s\n", got_ref_get_name(ref), target);
2246 done:
2247 free(id);
2248 free(id_str);
2249 return err;
2252 static const struct got_error *
2253 delete_refs_for_remote(struct got_repository *repo, const char *remote_name)
2255 const struct got_error *err = NULL;
2256 struct got_reflist_head refs;
2257 struct got_reflist_entry *re;
2258 char *prefix;
2260 TAILQ_INIT(&refs);
2262 if (asprintf(&prefix, "refs/remotes/%s", remote_name) == -1) {
2263 err = got_error_from_errno("asprintf");
2264 goto done;
2266 err = got_ref_list(&refs, repo, prefix, got_ref_cmp_by_name, NULL);
2267 if (err)
2268 goto done;
2270 TAILQ_FOREACH(re, &refs, entry)
2271 delete_ref(repo, re->ref);
2272 done:
2273 got_ref_list_free(&refs);
2274 return err;
2277 static const struct got_error *
2278 cmd_fetch(int argc, char *argv[])
2280 const struct got_error *error = NULL, *unlock_err;
2281 char *cwd = NULL, *repo_path = NULL;
2282 const char *remote_name;
2283 char *proto = NULL, *host = NULL, *port = NULL;
2284 char *repo_name = NULL, *server_path = NULL;
2285 const struct got_remote_repo *remotes, *remote = NULL;
2286 int nremotes;
2287 char *id_str = NULL;
2288 struct got_repository *repo = NULL;
2289 struct got_worktree *worktree = NULL;
2290 const struct got_gotconfig *repo_conf = NULL, *worktree_conf = NULL;
2291 struct got_pathlist_head refs, symrefs, wanted_branches, wanted_refs;
2292 struct got_pathlist_entry *pe;
2293 struct got_object_id *pack_hash = NULL;
2294 int i, ch, fetchfd = -1, fetchstatus;
2295 pid_t fetchpid = -1;
2296 struct got_fetch_progress_arg fpa;
2297 int verbosity = 0, fetch_all_branches = 0, list_refs_only = 0;
2298 int delete_refs = 0, replace_tags = 0, delete_remote = 0;
2299 int *pack_fds = NULL, have_bflag = 0;
2300 const char *worktree_branch = NULL;
2302 TAILQ_INIT(&refs);
2303 TAILQ_INIT(&symrefs);
2304 TAILQ_INIT(&wanted_branches);
2305 TAILQ_INIT(&wanted_refs);
2307 while ((ch = getopt(argc, argv, "ab:dlqR:r:tvX")) != -1) {
2308 switch (ch) {
2309 case 'a':
2310 fetch_all_branches = 1;
2311 break;
2312 case 'b':
2313 error = got_pathlist_append(&wanted_branches,
2314 optarg, NULL);
2315 if (error)
2316 return error;
2317 have_bflag = 1;
2318 break;
2319 case 'd':
2320 delete_refs = 1;
2321 break;
2322 case 'l':
2323 list_refs_only = 1;
2324 break;
2325 case 'q':
2326 verbosity = -1;
2327 break;
2328 case 'R':
2329 error = got_pathlist_append(&wanted_refs,
2330 optarg, NULL);
2331 if (error)
2332 return error;
2333 break;
2334 case 'r':
2335 repo_path = realpath(optarg, NULL);
2336 if (repo_path == NULL)
2337 return got_error_from_errno2("realpath",
2338 optarg);
2339 got_path_strip_trailing_slashes(repo_path);
2340 break;
2341 case 't':
2342 replace_tags = 1;
2343 break;
2344 case 'v':
2345 if (verbosity < 0)
2346 verbosity = 0;
2347 else if (verbosity < 3)
2348 verbosity++;
2349 break;
2350 case 'X':
2351 delete_remote = 1;
2352 break;
2353 default:
2354 usage_fetch();
2355 break;
2358 argc -= optind;
2359 argv += optind;
2361 if (fetch_all_branches && !TAILQ_EMPTY(&wanted_branches))
2362 option_conflict('a', 'b');
2363 if (list_refs_only) {
2364 if (!TAILQ_EMPTY(&wanted_branches))
2365 option_conflict('l', 'b');
2366 if (fetch_all_branches)
2367 option_conflict('l', 'a');
2368 if (delete_refs)
2369 option_conflict('l', 'd');
2370 if (delete_remote)
2371 option_conflict('l', 'X');
2373 if (delete_remote) {
2374 if (fetch_all_branches)
2375 option_conflict('X', 'a');
2376 if (!TAILQ_EMPTY(&wanted_branches))
2377 option_conflict('X', 'b');
2378 if (delete_refs)
2379 option_conflict('X', 'd');
2380 if (replace_tags)
2381 option_conflict('X', 't');
2382 if (!TAILQ_EMPTY(&wanted_refs))
2383 option_conflict('X', 'R');
2386 if (argc == 0) {
2387 if (delete_remote)
2388 errx(1, "-X option requires a remote name");
2389 remote_name = GOT_FETCH_DEFAULT_REMOTE_NAME;
2390 } else if (argc == 1)
2391 remote_name = argv[0];
2392 else
2393 usage_fetch();
2395 cwd = getcwd(NULL, 0);
2396 if (cwd == NULL) {
2397 error = got_error_from_errno("getcwd");
2398 goto done;
2401 error = got_repo_pack_fds_open(&pack_fds);
2402 if (error != NULL)
2403 goto done;
2405 if (repo_path == NULL) {
2406 error = got_worktree_open(&worktree, cwd);
2407 if (error && error->code != GOT_ERR_NOT_WORKTREE)
2408 goto done;
2409 else
2410 error = NULL;
2411 if (worktree) {
2412 repo_path =
2413 strdup(got_worktree_get_repo_path(worktree));
2414 if (repo_path == NULL)
2415 error = got_error_from_errno("strdup");
2416 if (error)
2417 goto done;
2418 } else {
2419 repo_path = strdup(cwd);
2420 if (repo_path == NULL) {
2421 error = got_error_from_errno("strdup");
2422 goto done;
2427 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
2428 if (error)
2429 goto done;
2431 if (delete_remote) {
2432 error = delete_refs_for_remote(repo, remote_name);
2433 goto done; /* nothing else to do */
2436 if (worktree) {
2437 worktree_conf = got_worktree_get_gotconfig(worktree);
2438 if (worktree_conf) {
2439 got_gotconfig_get_remotes(&nremotes, &remotes,
2440 worktree_conf);
2441 for (i = 0; i < nremotes; i++) {
2442 if (strcmp(remotes[i].name, remote_name) == 0) {
2443 remote = &remotes[i];
2444 break;
2449 if (remote == NULL) {
2450 repo_conf = got_repo_get_gotconfig(repo);
2451 if (repo_conf) {
2452 got_gotconfig_get_remotes(&nremotes, &remotes,
2453 repo_conf);
2454 for (i = 0; i < nremotes; i++) {
2455 if (strcmp(remotes[i].name, remote_name) == 0) {
2456 remote = &remotes[i];
2457 break;
2462 if (remote == NULL) {
2463 got_repo_get_gitconfig_remotes(&nremotes, &remotes, repo);
2464 for (i = 0; i < nremotes; i++) {
2465 if (strcmp(remotes[i].name, remote_name) == 0) {
2466 remote = &remotes[i];
2467 break;
2471 if (remote == NULL) {
2472 error = got_error_path(remote_name, GOT_ERR_NO_REMOTE);
2473 goto done;
2476 if (TAILQ_EMPTY(&wanted_branches)) {
2477 if (!fetch_all_branches)
2478 fetch_all_branches = remote->fetch_all_branches;
2479 for (i = 0; i < remote->nfetch_branches; i++) {
2480 error = got_pathlist_append(&wanted_branches,
2481 remote->fetch_branches[i], NULL);
2482 if (error)
2483 goto done;
2486 if (TAILQ_EMPTY(&wanted_refs)) {
2487 for (i = 0; i < remote->nfetch_refs; i++) {
2488 error = got_pathlist_append(&wanted_refs,
2489 remote->fetch_refs[i], NULL);
2490 if (error)
2491 goto done;
2495 error = got_dial_parse_uri(&proto, &host, &port, &server_path,
2496 &repo_name, remote->fetch_url);
2497 if (error)
2498 goto done;
2500 if (strcmp(proto, "git") == 0) {
2501 #ifndef PROFILE
2502 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
2503 "sendfd dns inet unveil", NULL) == -1)
2504 err(1, "pledge");
2505 #endif
2506 } else if (strcmp(proto, "git+ssh") == 0 ||
2507 strcmp(proto, "ssh") == 0) {
2508 #ifndef PROFILE
2509 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
2510 "sendfd unveil", NULL) == -1)
2511 err(1, "pledge");
2512 #endif
2513 } else if (strcmp(proto, "http") == 0 ||
2514 strcmp(proto, "git+http") == 0) {
2515 error = got_error_path(proto, GOT_ERR_NOT_IMPL);
2516 goto done;
2517 } else {
2518 error = got_error_path(proto, GOT_ERR_BAD_PROTO);
2519 goto done;
2522 error = got_dial_apply_unveil(proto);
2523 if (error)
2524 goto done;
2526 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
2527 if (error)
2528 goto done;
2530 if (verbosity >= 0) {
2531 printf("Connecting to \"%s\" %s://%s%s%s%s%s\n",
2532 remote->name, proto, host,
2533 port ? ":" : "", port ? port : "",
2534 *server_path == '/' ? "" : "/", server_path);
2537 error = got_fetch_connect(&fetchpid, &fetchfd, proto, host, port,
2538 server_path, verbosity);
2539 if (error)
2540 goto done;
2542 if (worktree && !have_bflag) {
2543 const char *refname;
2545 refname = got_worktree_get_head_ref_name(worktree);
2546 if (strncmp(refname, "refs/heads/", 11) == 0)
2547 worktree_branch = refname;
2550 fpa.last_scaled_size[0] = '\0';
2551 fpa.last_p_indexed = -1;
2552 fpa.last_p_resolved = -1;
2553 fpa.verbosity = verbosity;
2554 fpa.repo = repo;
2555 fpa.create_configs = 0;
2556 fpa.configs_created = 0;
2557 memset(&fpa.config_info, 0, sizeof(fpa.config_info));
2558 error = got_fetch_pack(&pack_hash, &refs, &symrefs, remote->name,
2559 remote->mirror_references, fetch_all_branches, &wanted_branches,
2560 &wanted_refs, list_refs_only, verbosity, fetchfd, repo,
2561 worktree_branch, fetch_progress, &fpa);
2562 if (error)
2563 goto done;
2565 if (list_refs_only) {
2566 error = list_remote_refs(&symrefs, &refs);
2567 goto done;
2570 if (pack_hash == NULL) {
2571 if (verbosity >= 0)
2572 printf("Already up-to-date\n");
2573 } else if (verbosity >= 0) {
2574 error = got_object_id_str(&id_str, pack_hash);
2575 if (error)
2576 goto done;
2577 printf("\nFetched %s.pack\n", id_str);
2578 free(id_str);
2579 id_str = NULL;
2582 /* Update references provided with the pack file. */
2583 TAILQ_FOREACH(pe, &refs, entry) {
2584 const char *refname = pe->path;
2585 struct got_object_id *id = pe->data;
2586 struct got_reference *ref;
2587 char *remote_refname;
2589 if (is_wanted_ref(&wanted_refs, refname) &&
2590 !remote->mirror_references) {
2591 error = update_wanted_ref(refname, id,
2592 remote->name, verbosity, repo);
2593 if (error)
2594 goto done;
2595 continue;
2598 if (remote->mirror_references ||
2599 strncmp("refs/tags/", refname, 10) == 0) {
2600 error = got_ref_open(&ref, repo, refname, 1);
2601 if (error) {
2602 if (error->code != GOT_ERR_NOT_REF)
2603 goto done;
2604 error = create_ref(refname, id, verbosity,
2605 repo);
2606 if (error)
2607 goto done;
2608 } else {
2609 error = update_ref(ref, id, replace_tags,
2610 verbosity, repo);
2611 unlock_err = got_ref_unlock(ref);
2612 if (unlock_err && error == NULL)
2613 error = unlock_err;
2614 got_ref_close(ref);
2615 if (error)
2616 goto done;
2618 } else if (strncmp("refs/heads/", refname, 11) == 0) {
2619 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
2620 remote_name, refname + 11) == -1) {
2621 error = got_error_from_errno("asprintf");
2622 goto done;
2625 error = got_ref_open(&ref, repo, remote_refname, 1);
2626 if (error) {
2627 if (error->code != GOT_ERR_NOT_REF)
2628 goto done;
2629 error = create_ref(remote_refname, id,
2630 verbosity, repo);
2631 if (error)
2632 goto done;
2633 } else {
2634 error = update_ref(ref, id, replace_tags,
2635 verbosity, repo);
2636 unlock_err = got_ref_unlock(ref);
2637 if (unlock_err && error == NULL)
2638 error = unlock_err;
2639 got_ref_close(ref);
2640 if (error)
2641 goto done;
2644 /* Also create a local branch if none exists yet. */
2645 error = got_ref_open(&ref, repo, refname, 1);
2646 if (error) {
2647 if (error->code != GOT_ERR_NOT_REF)
2648 goto done;
2649 error = create_ref(refname, id, verbosity,
2650 repo);
2651 if (error)
2652 goto done;
2653 } else {
2654 unlock_err = got_ref_unlock(ref);
2655 if (unlock_err && error == NULL)
2656 error = unlock_err;
2657 got_ref_close(ref);
2661 if (delete_refs) {
2662 error = delete_missing_refs(&refs, &symrefs, remote,
2663 verbosity, repo);
2664 if (error)
2665 goto done;
2668 if (!remote->mirror_references) {
2669 /* Update remote HEAD reference if the server provided one. */
2670 TAILQ_FOREACH(pe, &symrefs, entry) {
2671 struct got_reference *target_ref;
2672 const char *refname = pe->path;
2673 const char *target = pe->data;
2674 char *remote_refname = NULL, *remote_target = NULL;
2676 if (strcmp(refname, GOT_REF_HEAD) != 0)
2677 continue;
2679 if (strncmp("refs/heads/", target, 11) != 0)
2680 continue;
2682 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
2683 remote->name, refname) == -1) {
2684 error = got_error_from_errno("asprintf");
2685 goto done;
2687 if (asprintf(&remote_target, "refs/remotes/%s/%s",
2688 remote->name, target + 11) == -1) {
2689 error = got_error_from_errno("asprintf");
2690 free(remote_refname);
2691 goto done;
2694 error = got_ref_open(&target_ref, repo, remote_target,
2695 0);
2696 if (error) {
2697 free(remote_refname);
2698 free(remote_target);
2699 if (error->code == GOT_ERR_NOT_REF) {
2700 error = NULL;
2701 continue;
2703 goto done;
2705 error = update_symref(remote_refname, target_ref,
2706 verbosity, repo);
2707 free(remote_refname);
2708 free(remote_target);
2709 got_ref_close(target_ref);
2710 if (error)
2711 goto done;
2714 done:
2715 if (fetchpid > 0) {
2716 if (kill(fetchpid, SIGTERM) == -1)
2717 error = got_error_from_errno("kill");
2718 if (waitpid(fetchpid, &fetchstatus, 0) == -1 && error == NULL)
2719 error = got_error_from_errno("waitpid");
2721 if (fetchfd != -1 && close(fetchfd) == -1 && error == NULL)
2722 error = got_error_from_errno("close");
2723 if (repo) {
2724 const struct got_error *close_err = got_repo_close(repo);
2725 if (error == NULL)
2726 error = close_err;
2728 if (worktree)
2729 got_worktree_close(worktree);
2730 if (pack_fds) {
2731 const struct got_error *pack_err =
2732 got_repo_pack_fds_close(pack_fds);
2733 if (error == NULL)
2734 error = pack_err;
2736 got_pathlist_free(&refs, GOT_PATHLIST_FREE_ALL);
2737 got_pathlist_free(&symrefs, GOT_PATHLIST_FREE_ALL);
2738 got_pathlist_free(&wanted_branches, GOT_PATHLIST_FREE_NONE);
2739 got_pathlist_free(&wanted_refs, GOT_PATHLIST_FREE_NONE);
2740 free(id_str);
2741 free(cwd);
2742 free(repo_path);
2743 free(pack_hash);
2744 free(proto);
2745 free(host);
2746 free(port);
2747 free(server_path);
2748 free(repo_name);
2749 return error;
2753 __dead static void
2754 usage_checkout(void)
2756 fprintf(stderr, "usage: %s checkout [-Eq] [-b branch] [-c commit] "
2757 "[-p path-prefix] repository-path [work-tree-path]\n",
2758 getprogname());
2759 exit(1);
2762 static void
2763 show_worktree_base_ref_warning(void)
2765 fprintf(stderr, "%s: warning: could not create a reference "
2766 "to the work tree's base commit; the commit could be "
2767 "garbage-collected by Git or 'gotadmin cleanup'; making the "
2768 "repository writable and running 'got update' will prevent this\n",
2769 getprogname());
2772 struct got_checkout_progress_arg {
2773 const char *worktree_path;
2774 int had_base_commit_ref_error;
2775 int verbosity;
2778 static const struct got_error *
2779 checkout_progress(void *arg, unsigned char status, const char *path)
2781 struct got_checkout_progress_arg *a = arg;
2783 /* Base commit bump happens silently. */
2784 if (status == GOT_STATUS_BUMP_BASE)
2785 return NULL;
2787 if (status == GOT_STATUS_BASE_REF_ERR) {
2788 a->had_base_commit_ref_error = 1;
2789 return NULL;
2792 while (path[0] == '/')
2793 path++;
2795 if (a->verbosity >= 0)
2796 printf("%c %s/%s\n", status, a->worktree_path, path);
2798 return NULL;
2801 static const struct got_error *
2802 check_cancelled(void *arg)
2804 if (sigint_received || sigpipe_received)
2805 return got_error(GOT_ERR_CANCELLED);
2806 return NULL;
2809 static const struct got_error *
2810 check_linear_ancestry(struct got_object_id *commit_id,
2811 struct got_object_id *base_commit_id, int allow_forwards_in_time_only,
2812 struct got_repository *repo)
2814 const struct got_error *err = NULL;
2815 struct got_object_id *yca_id;
2817 err = got_commit_graph_find_youngest_common_ancestor(&yca_id,
2818 commit_id, base_commit_id, 1, repo, check_cancelled, NULL);
2819 if (err)
2820 return err;
2822 if (yca_id == NULL)
2823 return got_error(GOT_ERR_ANCESTRY);
2826 * Require a straight line of history between the target commit
2827 * and the work tree's base commit.
2829 * Non-linear situations such as this require a rebase:
2831 * (commit) D F (base_commit)
2832 * \ /
2833 * C E
2834 * \ /
2835 * B (yca)
2836 * |
2837 * A
2839 * 'got update' only handles linear cases:
2840 * Update forwards in time: A (base/yca) - B - C - D (commit)
2841 * Update backwards in time: D (base) - C - B - A (commit/yca)
2843 if (allow_forwards_in_time_only) {
2844 if (got_object_id_cmp(base_commit_id, yca_id) != 0)
2845 return got_error(GOT_ERR_ANCESTRY);
2846 } else if (got_object_id_cmp(commit_id, yca_id) != 0 &&
2847 got_object_id_cmp(base_commit_id, yca_id) != 0)
2848 return got_error(GOT_ERR_ANCESTRY);
2850 free(yca_id);
2851 return NULL;
2854 static const struct got_error *
2855 check_same_branch(struct got_object_id *commit_id,
2856 struct got_reference *head_ref, struct got_object_id *yca_id,
2857 struct got_repository *repo)
2859 const struct got_error *err = NULL;
2860 struct got_commit_graph *graph = NULL;
2861 struct got_object_id *head_commit_id = NULL;
2862 int is_same_branch = 0;
2864 err = got_ref_resolve(&head_commit_id, repo, head_ref);
2865 if (err)
2866 goto done;
2868 if (got_object_id_cmp(head_commit_id, commit_id) == 0) {
2869 is_same_branch = 1;
2870 goto done;
2872 if (yca_id && got_object_id_cmp(commit_id, yca_id) == 0) {
2873 is_same_branch = 1;
2874 goto done;
2877 err = got_commit_graph_open(&graph, "/", 1);
2878 if (err)
2879 goto done;
2881 err = got_commit_graph_iter_start(graph, head_commit_id, repo,
2882 check_cancelled, NULL);
2883 if (err)
2884 goto done;
2886 for (;;) {
2887 struct got_object_id id;
2889 err = got_commit_graph_iter_next(&id, graph, repo,
2890 check_cancelled, NULL);
2891 if (err) {
2892 if (err->code == GOT_ERR_ITER_COMPLETED)
2893 err = NULL;
2894 break;
2897 if (yca_id && got_object_id_cmp(&id, yca_id) == 0)
2898 break;
2899 if (got_object_id_cmp(&id, commit_id) == 0) {
2900 is_same_branch = 1;
2901 break;
2904 done:
2905 if (graph)
2906 got_commit_graph_close(graph);
2907 free(head_commit_id);
2908 if (!err && !is_same_branch)
2909 err = got_error(GOT_ERR_ANCESTRY);
2910 return err;
2913 static const struct got_error *
2914 checkout_ancestry_error(struct got_reference *ref, const char *commit_id_str)
2916 static char msg[512];
2917 const char *branch_name;
2919 if (got_ref_is_symbolic(ref))
2920 branch_name = got_ref_get_symref_target(ref);
2921 else
2922 branch_name = got_ref_get_name(ref);
2924 if (strncmp("refs/heads/", branch_name, 11) == 0)
2925 branch_name += 11;
2927 snprintf(msg, sizeof(msg),
2928 "target commit is not contained in branch '%s'; "
2929 "the branch to use must be specified with -b; "
2930 "if necessary a new branch can be created for "
2931 "this commit with 'got branch -c %s BRANCH_NAME'",
2932 branch_name, commit_id_str);
2934 return got_error_msg(GOT_ERR_ANCESTRY, msg);
2937 static const struct got_error *
2938 cmd_checkout(int argc, char *argv[])
2940 const struct got_error *error = NULL;
2941 struct got_repository *repo = NULL;
2942 struct got_reference *head_ref = NULL, *ref = NULL;
2943 struct got_worktree *worktree = NULL;
2944 char *repo_path = NULL;
2945 char *worktree_path = NULL;
2946 const char *path_prefix = "";
2947 const char *branch_name = GOT_REF_HEAD, *refname = NULL;
2948 char *commit_id_str = NULL;
2949 struct got_object_id *commit_id = NULL;
2950 char *cwd = NULL;
2951 int ch, same_path_prefix, allow_nonempty = 0, verbosity = 0;
2952 struct got_pathlist_head paths;
2953 struct got_checkout_progress_arg cpa;
2954 int *pack_fds = NULL;
2956 TAILQ_INIT(&paths);
2958 while ((ch = getopt(argc, argv, "b:c:Ep:q")) != -1) {
2959 switch (ch) {
2960 case 'b':
2961 branch_name = optarg;
2962 break;
2963 case 'c':
2964 commit_id_str = strdup(optarg);
2965 if (commit_id_str == NULL)
2966 return got_error_from_errno("strdup");
2967 break;
2968 case 'E':
2969 allow_nonempty = 1;
2970 break;
2971 case 'p':
2972 path_prefix = optarg;
2973 break;
2974 case 'q':
2975 verbosity = -1;
2976 break;
2977 default:
2978 usage_checkout();
2979 /* NOTREACHED */
2983 argc -= optind;
2984 argv += optind;
2986 #ifndef PROFILE
2987 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
2988 "unveil", NULL) == -1)
2989 err(1, "pledge");
2990 #endif
2991 if (argc == 1) {
2992 char *base, *dotgit;
2993 const char *path;
2994 repo_path = realpath(argv[0], NULL);
2995 if (repo_path == NULL)
2996 return got_error_from_errno2("realpath", argv[0]);
2997 cwd = getcwd(NULL, 0);
2998 if (cwd == NULL) {
2999 error = got_error_from_errno("getcwd");
3000 goto done;
3002 if (path_prefix[0])
3003 path = path_prefix;
3004 else
3005 path = repo_path;
3006 error = got_path_basename(&base, path);
3007 if (error)
3008 goto done;
3009 dotgit = strstr(base, ".git");
3010 if (dotgit)
3011 *dotgit = '\0';
3012 if (asprintf(&worktree_path, "%s/%s", cwd, base) == -1) {
3013 error = got_error_from_errno("asprintf");
3014 free(base);
3015 goto done;
3017 free(base);
3018 } else if (argc == 2) {
3019 repo_path = realpath(argv[0], NULL);
3020 if (repo_path == NULL) {
3021 error = got_error_from_errno2("realpath", argv[0]);
3022 goto done;
3024 worktree_path = realpath(argv[1], NULL);
3025 if (worktree_path == NULL) {
3026 if (errno != ENOENT) {
3027 error = got_error_from_errno2("realpath",
3028 argv[1]);
3029 goto done;
3031 worktree_path = strdup(argv[1]);
3032 if (worktree_path == NULL) {
3033 error = got_error_from_errno("strdup");
3034 goto done;
3037 } else
3038 usage_checkout();
3040 got_path_strip_trailing_slashes(repo_path);
3041 got_path_strip_trailing_slashes(worktree_path);
3043 error = got_repo_pack_fds_open(&pack_fds);
3044 if (error != NULL)
3045 goto done;
3047 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
3048 if (error != NULL)
3049 goto done;
3051 /* Pre-create work tree path for unveil(2) */
3052 error = got_path_mkdir(worktree_path);
3053 if (error) {
3054 if (!(error->code == GOT_ERR_ERRNO && errno == EISDIR) &&
3055 !(error->code == GOT_ERR_ERRNO && errno == EEXIST))
3056 goto done;
3057 if (!allow_nonempty &&
3058 !got_path_dir_is_empty(worktree_path)) {
3059 error = got_error_path(worktree_path,
3060 GOT_ERR_DIR_NOT_EMPTY);
3061 goto done;
3065 error = apply_unveil(got_repo_get_path(repo), 0, worktree_path);
3066 if (error)
3067 goto done;
3069 error = got_ref_open(&head_ref, repo, branch_name, 0);
3070 if (error != NULL)
3071 goto done;
3073 error = got_worktree_init(worktree_path, head_ref, path_prefix, repo);
3074 if (error != NULL && !(error->code == GOT_ERR_ERRNO && errno == EEXIST))
3075 goto done;
3077 error = got_worktree_open(&worktree, worktree_path);
3078 if (error != NULL)
3079 goto done;
3081 error = got_worktree_match_path_prefix(&same_path_prefix, worktree,
3082 path_prefix);
3083 if (error != NULL)
3084 goto done;
3085 if (!same_path_prefix) {
3086 error = got_error(GOT_ERR_PATH_PREFIX);
3087 goto done;
3090 if (commit_id_str) {
3091 struct got_reflist_head refs;
3092 TAILQ_INIT(&refs);
3093 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
3094 NULL);
3095 if (error)
3096 goto done;
3097 error = got_repo_match_object_id(&commit_id, NULL,
3098 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
3099 got_ref_list_free(&refs);
3100 if (error)
3101 goto done;
3102 error = check_linear_ancestry(commit_id,
3103 got_worktree_get_base_commit_id(worktree), 0, repo);
3104 if (error != NULL) {
3105 if (error->code == GOT_ERR_ANCESTRY) {
3106 error = checkout_ancestry_error(
3107 head_ref, commit_id_str);
3109 goto done;
3111 error = check_same_branch(commit_id, head_ref, NULL, repo);
3112 if (error) {
3113 if (error->code == GOT_ERR_ANCESTRY) {
3114 error = checkout_ancestry_error(
3115 head_ref, commit_id_str);
3117 goto done;
3119 error = got_worktree_set_base_commit_id(worktree, repo,
3120 commit_id);
3121 if (error)
3122 goto done;
3123 /* Expand potentially abbreviated commit ID string. */
3124 free(commit_id_str);
3125 error = got_object_id_str(&commit_id_str, commit_id);
3126 if (error)
3127 goto done;
3128 } else {
3129 commit_id = got_object_id_dup(
3130 got_worktree_get_base_commit_id(worktree));
3131 if (commit_id == NULL) {
3132 error = got_error_from_errno("got_object_id_dup");
3133 goto done;
3135 error = got_object_id_str(&commit_id_str, commit_id);
3136 if (error)
3137 goto done;
3140 error = got_pathlist_append(&paths, "", NULL);
3141 if (error)
3142 goto done;
3143 cpa.worktree_path = worktree_path;
3144 cpa.had_base_commit_ref_error = 0;
3145 cpa.verbosity = verbosity;
3146 error = got_worktree_checkout_files(worktree, &paths, repo,
3147 checkout_progress, &cpa, check_cancelled, NULL);
3148 if (error != NULL)
3149 goto done;
3151 if (got_ref_is_symbolic(head_ref)) {
3152 error = got_ref_resolve_symbolic(&ref, repo, head_ref);
3153 if (error)
3154 goto done;
3155 refname = got_ref_get_name(ref);
3156 } else
3157 refname = got_ref_get_name(head_ref);
3158 printf("Checked out %s: %s\n", refname, commit_id_str);
3159 printf("Now shut up and hack\n");
3160 if (cpa.had_base_commit_ref_error)
3161 show_worktree_base_ref_warning();
3162 done:
3163 if (pack_fds) {
3164 const struct got_error *pack_err =
3165 got_repo_pack_fds_close(pack_fds);
3166 if (error == NULL)
3167 error = pack_err;
3169 if (head_ref)
3170 got_ref_close(head_ref);
3171 if (ref)
3172 got_ref_close(ref);
3173 got_pathlist_free(&paths, GOT_PATHLIST_FREE_NONE);
3174 free(commit_id_str);
3175 free(commit_id);
3176 free(repo_path);
3177 free(worktree_path);
3178 free(cwd);
3179 return error;
3182 struct got_update_progress_arg {
3183 int did_something;
3184 int conflicts;
3185 int obstructed;
3186 int not_updated;
3187 int missing;
3188 int not_deleted;
3189 int unversioned;
3190 int verbosity;
3193 static void
3194 print_update_progress_stats(struct got_update_progress_arg *upa)
3196 if (!upa->did_something)
3197 return;
3199 if (upa->conflicts > 0)
3200 printf("Files with new merge conflicts: %d\n", upa->conflicts);
3201 if (upa->obstructed > 0)
3202 printf("File paths obstructed by a non-regular file: %d\n",
3203 upa->obstructed);
3204 if (upa->not_updated > 0)
3205 printf("Files not updated because of existing merge "
3206 "conflicts: %d\n", upa->not_updated);
3210 * The meaning of some status codes differs between merge-style operations and
3211 * update operations. For example, the ! status code means "file was missing"
3212 * if changes were merged into the work tree, and "missing file was restored"
3213 * if the work tree was updated. This function should be used by any operation
3214 * which merges changes into the work tree without updating the work tree.
3216 static void
3217 print_merge_progress_stats(struct got_update_progress_arg *upa)
3219 if (!upa->did_something)
3220 return;
3222 if (upa->conflicts > 0)
3223 printf("Files with new merge conflicts: %d\n", upa->conflicts);
3224 if (upa->obstructed > 0)
3225 printf("File paths obstructed by a non-regular file: %d\n",
3226 upa->obstructed);
3227 if (upa->missing > 0)
3228 printf("Files which had incoming changes but could not be "
3229 "found in the work tree: %d\n", upa->missing);
3230 if (upa->not_deleted > 0)
3231 printf("Files not deleted due to differences in deleted "
3232 "content: %d\n", upa->not_deleted);
3233 if (upa->unversioned > 0)
3234 printf("Files not merged because an unversioned file was "
3235 "found in the work tree: %d\n", upa->unversioned);
3238 __dead static void
3239 usage_update(void)
3241 fprintf(stderr, "usage: %s update [-q] [-b branch] [-c commit] "
3242 "[path ...]\n", getprogname());
3243 exit(1);
3246 static const struct got_error *
3247 update_progress(void *arg, unsigned char status, const char *path)
3249 struct got_update_progress_arg *upa = arg;
3251 if (status == GOT_STATUS_EXISTS ||
3252 status == GOT_STATUS_BASE_REF_ERR)
3253 return NULL;
3255 upa->did_something = 1;
3257 /* Base commit bump happens silently. */
3258 if (status == GOT_STATUS_BUMP_BASE)
3259 return NULL;
3261 if (status == GOT_STATUS_CONFLICT)
3262 upa->conflicts++;
3263 if (status == GOT_STATUS_OBSTRUCTED)
3264 upa->obstructed++;
3265 if (status == GOT_STATUS_CANNOT_UPDATE)
3266 upa->not_updated++;
3267 if (status == GOT_STATUS_MISSING)
3268 upa->missing++;
3269 if (status == GOT_STATUS_CANNOT_DELETE)
3270 upa->not_deleted++;
3271 if (status == GOT_STATUS_UNVERSIONED)
3272 upa->unversioned++;
3274 while (path[0] == '/')
3275 path++;
3276 if (upa->verbosity >= 0)
3277 printf("%c %s\n", status, path);
3279 return NULL;
3282 static const struct got_error *
3283 switch_head_ref(struct got_reference *head_ref,
3284 struct got_object_id *commit_id, struct got_worktree *worktree,
3285 struct got_repository *repo)
3287 const struct got_error *err = NULL;
3288 char *base_id_str;
3289 int ref_has_moved = 0;
3291 /* Trivial case: switching between two different references. */
3292 if (strcmp(got_ref_get_name(head_ref),
3293 got_worktree_get_head_ref_name(worktree)) != 0) {
3294 printf("Switching work tree from %s to %s\n",
3295 got_worktree_get_head_ref_name(worktree),
3296 got_ref_get_name(head_ref));
3297 return got_worktree_set_head_ref(worktree, head_ref);
3300 err = check_linear_ancestry(commit_id,
3301 got_worktree_get_base_commit_id(worktree), 0, repo);
3302 if (err) {
3303 if (err->code != GOT_ERR_ANCESTRY)
3304 return err;
3305 ref_has_moved = 1;
3307 if (!ref_has_moved)
3308 return NULL;
3310 /* Switching to a rebased branch with the same reference name. */
3311 err = got_object_id_str(&base_id_str,
3312 got_worktree_get_base_commit_id(worktree));
3313 if (err)
3314 return err;
3315 printf("Reference %s now points at a different branch\n",
3316 got_worktree_get_head_ref_name(worktree));
3317 printf("Switching work tree from %s to %s\n", base_id_str,
3318 got_worktree_get_head_ref_name(worktree));
3319 return NULL;
3322 static const struct got_error *
3323 check_rebase_or_histedit_in_progress(struct got_worktree *worktree)
3325 const struct got_error *err;
3326 int in_progress;
3328 err = got_worktree_rebase_in_progress(&in_progress, worktree);
3329 if (err)
3330 return err;
3331 if (in_progress)
3332 return got_error(GOT_ERR_REBASING);
3334 err = got_worktree_histedit_in_progress(&in_progress, worktree);
3335 if (err)
3336 return err;
3337 if (in_progress)
3338 return got_error(GOT_ERR_HISTEDIT_BUSY);
3340 return NULL;
3343 static const struct got_error *
3344 check_merge_in_progress(struct got_worktree *worktree,
3345 struct got_repository *repo)
3347 const struct got_error *err;
3348 int in_progress;
3350 err = got_worktree_merge_in_progress(&in_progress, worktree, repo);
3351 if (err)
3352 return err;
3353 if (in_progress)
3354 return got_error(GOT_ERR_MERGE_BUSY);
3356 return NULL;
3359 static const struct got_error *
3360 get_worktree_paths_from_argv(struct got_pathlist_head *paths, int argc,
3361 char *argv[], struct got_worktree *worktree)
3363 const struct got_error *err = NULL;
3364 char *path;
3365 struct got_pathlist_entry *new;
3366 int i;
3368 if (argc == 0) {
3369 path = strdup("");
3370 if (path == NULL)
3371 return got_error_from_errno("strdup");
3372 return got_pathlist_append(paths, path, NULL);
3375 for (i = 0; i < argc; i++) {
3376 err = got_worktree_resolve_path(&path, worktree, argv[i]);
3377 if (err)
3378 break;
3379 err = got_pathlist_insert(&new, paths, path, NULL);
3380 if (err || new == NULL /* duplicate */) {
3381 free(path);
3382 if (err)
3383 break;
3387 return err;
3390 static const struct got_error *
3391 wrap_not_worktree_error(const struct got_error *orig_err,
3392 const char *cmdname, const char *path)
3394 const struct got_error *err;
3395 struct got_repository *repo;
3396 static char msg[512];
3397 int *pack_fds = NULL;
3399 err = got_repo_pack_fds_open(&pack_fds);
3400 if (err)
3401 return err;
3403 err = got_repo_open(&repo, path, NULL, pack_fds);
3404 if (err)
3405 return orig_err;
3407 snprintf(msg, sizeof(msg),
3408 "'got %s' needs a work tree in addition to a git repository\n"
3409 "Work trees can be checked out from this Git repository with "
3410 "'got checkout'.\n"
3411 "The got(1) manual page contains more information.", cmdname);
3412 err = got_error_msg(GOT_ERR_NOT_WORKTREE, msg);
3413 got_repo_close(repo);
3414 if (pack_fds) {
3415 const struct got_error *pack_err =
3416 got_repo_pack_fds_close(pack_fds);
3417 if (err == NULL)
3418 err = pack_err;
3420 return err;
3423 static const struct got_error *
3424 cmd_update(int argc, char *argv[])
3426 const struct got_error *error = NULL;
3427 struct got_repository *repo = NULL;
3428 struct got_worktree *worktree = NULL;
3429 char *worktree_path = NULL;
3430 struct got_object_id *commit_id = NULL;
3431 char *commit_id_str = NULL;
3432 const char *branch_name = NULL;
3433 struct got_reference *head_ref = NULL;
3434 struct got_pathlist_head paths;
3435 struct got_pathlist_entry *pe;
3436 int ch, verbosity = 0;
3437 struct got_update_progress_arg upa;
3438 int *pack_fds = NULL;
3440 TAILQ_INIT(&paths);
3442 while ((ch = getopt(argc, argv, "b:c:q")) != -1) {
3443 switch (ch) {
3444 case 'b':
3445 branch_name = optarg;
3446 break;
3447 case 'c':
3448 commit_id_str = strdup(optarg);
3449 if (commit_id_str == NULL)
3450 return got_error_from_errno("strdup");
3451 break;
3452 case 'q':
3453 verbosity = -1;
3454 break;
3455 default:
3456 usage_update();
3457 /* NOTREACHED */
3461 argc -= optind;
3462 argv += optind;
3464 #ifndef PROFILE
3465 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
3466 "unveil", NULL) == -1)
3467 err(1, "pledge");
3468 #endif
3469 worktree_path = getcwd(NULL, 0);
3470 if (worktree_path == NULL) {
3471 error = got_error_from_errno("getcwd");
3472 goto done;
3475 error = got_repo_pack_fds_open(&pack_fds);
3476 if (error != NULL)
3477 goto done;
3479 error = got_worktree_open(&worktree, worktree_path);
3480 if (error) {
3481 if (error->code == GOT_ERR_NOT_WORKTREE)
3482 error = wrap_not_worktree_error(error, "update",
3483 worktree_path);
3484 goto done;
3487 error = check_rebase_or_histedit_in_progress(worktree);
3488 if (error)
3489 goto done;
3491 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
3492 NULL, pack_fds);
3493 if (error != NULL)
3494 goto done;
3496 error = apply_unveil(got_repo_get_path(repo), 0,
3497 got_worktree_get_root_path(worktree));
3498 if (error)
3499 goto done;
3501 error = check_merge_in_progress(worktree, repo);
3502 if (error)
3503 goto done;
3505 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
3506 if (error)
3507 goto done;
3509 error = got_ref_open(&head_ref, repo, branch_name ? branch_name :
3510 got_worktree_get_head_ref_name(worktree), 0);
3511 if (error != NULL)
3512 goto done;
3513 if (commit_id_str == NULL) {
3514 error = got_ref_resolve(&commit_id, repo, head_ref);
3515 if (error != NULL)
3516 goto done;
3517 error = got_object_id_str(&commit_id_str, commit_id);
3518 if (error != NULL)
3519 goto done;
3520 } else {
3521 struct got_reflist_head refs;
3522 TAILQ_INIT(&refs);
3523 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
3524 NULL);
3525 if (error)
3526 goto done;
3527 error = got_repo_match_object_id(&commit_id, NULL,
3528 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
3529 got_ref_list_free(&refs);
3530 free(commit_id_str);
3531 commit_id_str = NULL;
3532 if (error)
3533 goto done;
3534 error = got_object_id_str(&commit_id_str, commit_id);
3535 if (error)
3536 goto done;
3539 if (branch_name) {
3540 struct got_object_id *head_commit_id;
3541 TAILQ_FOREACH(pe, &paths, entry) {
3542 if (pe->path_len == 0)
3543 continue;
3544 error = got_error_msg(GOT_ERR_BAD_PATH,
3545 "switching between branches requires that "
3546 "the entire work tree gets updated");
3547 goto done;
3549 error = got_ref_resolve(&head_commit_id, repo, head_ref);
3550 if (error)
3551 goto done;
3552 error = check_linear_ancestry(commit_id, head_commit_id, 0,
3553 repo);
3554 free(head_commit_id);
3555 if (error != NULL)
3556 goto done;
3557 error = check_same_branch(commit_id, head_ref, NULL, repo);
3558 if (error)
3559 goto done;
3560 error = switch_head_ref(head_ref, commit_id, worktree, repo);
3561 if (error)
3562 goto done;
3563 } else {
3564 error = check_linear_ancestry(commit_id,
3565 got_worktree_get_base_commit_id(worktree), 0, repo);
3566 if (error != NULL) {
3567 if (error->code == GOT_ERR_ANCESTRY)
3568 error = got_error(GOT_ERR_BRANCH_MOVED);
3569 goto done;
3571 error = check_same_branch(commit_id, head_ref, NULL, repo);
3572 if (error)
3573 goto done;
3576 if (got_object_id_cmp(got_worktree_get_base_commit_id(worktree),
3577 commit_id) != 0) {
3578 error = got_worktree_set_base_commit_id(worktree, repo,
3579 commit_id);
3580 if (error)
3581 goto done;
3584 memset(&upa, 0, sizeof(upa));
3585 upa.verbosity = verbosity;
3586 error = got_worktree_checkout_files(worktree, &paths, repo,
3587 update_progress, &upa, check_cancelled, NULL);
3588 if (error != NULL)
3589 goto done;
3591 if (upa.did_something) {
3592 printf("Updated to %s: %s\n",
3593 got_worktree_get_head_ref_name(worktree), commit_id_str);
3594 } else
3595 printf("Already up-to-date\n");
3597 print_update_progress_stats(&upa);
3598 done:
3599 if (pack_fds) {
3600 const struct got_error *pack_err =
3601 got_repo_pack_fds_close(pack_fds);
3602 if (error == NULL)
3603 error = pack_err;
3605 free(worktree_path);
3606 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
3607 free(commit_id);
3608 free(commit_id_str);
3609 return error;
3612 static const struct got_error *
3613 diff_blobs(struct got_object_id *blob_id1, struct got_object_id *blob_id2,
3614 const char *path, int diff_context, int ignore_whitespace,
3615 int force_text_diff, struct got_diffstat_cb_arg *dsa,
3616 struct got_repository *repo, FILE *outfile)
3618 const struct got_error *err = NULL;
3619 struct got_blob_object *blob1 = NULL, *blob2 = NULL;
3620 FILE *f1 = NULL, *f2 = NULL;
3621 int fd1 = -1, fd2 = -1;
3623 fd1 = got_opentempfd();
3624 if (fd1 == -1)
3625 return got_error_from_errno("got_opentempfd");
3626 fd2 = got_opentempfd();
3627 if (fd2 == -1) {
3628 err = got_error_from_errno("got_opentempfd");
3629 goto done;
3632 if (blob_id1) {
3633 err = got_object_open_as_blob(&blob1, repo, blob_id1, 8192,
3634 fd1);
3635 if (err)
3636 goto done;
3639 err = got_object_open_as_blob(&blob2, repo, blob_id2, 8192, fd2);
3640 if (err)
3641 goto done;
3643 f1 = got_opentemp();
3644 if (f1 == NULL) {
3645 err = got_error_from_errno("got_opentemp");
3646 goto done;
3648 f2 = got_opentemp();
3649 if (f2 == NULL) {
3650 err = got_error_from_errno("got_opentemp");
3651 goto done;
3654 while (path[0] == '/')
3655 path++;
3656 err = got_diff_blob(NULL, NULL, blob1, blob2, f1, f2, path, path,
3657 GOT_DIFF_ALGORITHM_PATIENCE, diff_context, ignore_whitespace,
3658 force_text_diff, dsa, outfile);
3659 done:
3660 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
3661 err = got_error_from_errno("close");
3662 if (blob1)
3663 got_object_blob_close(blob1);
3664 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
3665 err = got_error_from_errno("close");
3666 got_object_blob_close(blob2);
3667 if (f1 && fclose(f1) == EOF && err == NULL)
3668 err = got_error_from_errno("fclose");
3669 if (f2 && fclose(f2) == EOF && err == NULL)
3670 err = got_error_from_errno("fclose");
3671 return err;
3674 static const struct got_error *
3675 diff_trees(struct got_object_id *tree_id1, struct got_object_id *tree_id2,
3676 const char *path, int diff_context, int ignore_whitespace,
3677 int force_text_diff, struct got_diffstat_cb_arg *dsa,
3678 struct got_repository *repo, FILE *outfile)
3680 const struct got_error *err = NULL;
3681 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
3682 struct got_diff_blob_output_unidiff_arg arg;
3683 FILE *f1 = NULL, *f2 = NULL;
3684 int fd1 = -1, fd2 = -1;
3686 if (tree_id1) {
3687 err = got_object_open_as_tree(&tree1, repo, tree_id1);
3688 if (err)
3689 goto done;
3690 fd1 = got_opentempfd();
3691 if (fd1 == -1) {
3692 err = got_error_from_errno("got_opentempfd");
3693 goto done;
3697 err = got_object_open_as_tree(&tree2, repo, tree_id2);
3698 if (err)
3699 goto done;
3701 f1 = got_opentemp();
3702 if (f1 == NULL) {
3703 err = got_error_from_errno("got_opentemp");
3704 goto done;
3707 f2 = got_opentemp();
3708 if (f2 == NULL) {
3709 err = got_error_from_errno("got_opentemp");
3710 goto done;
3712 fd2 = got_opentempfd();
3713 if (fd2 == -1) {
3714 err = got_error_from_errno("got_opentempfd");
3715 goto done;
3717 arg.diff_context = diff_context;
3718 arg.ignore_whitespace = ignore_whitespace;
3719 arg.force_text_diff = force_text_diff;
3720 arg.diffstat = dsa;
3721 arg.diff_algo = GOT_DIFF_ALGORITHM_PATIENCE;
3722 arg.outfile = outfile;
3723 arg.lines = NULL;
3724 arg.nlines = 0;
3725 while (path[0] == '/')
3726 path++;
3727 err = got_diff_tree(tree1, tree2, f1, f2, fd1, fd2, path, path, repo,
3728 got_diff_blob_output_unidiff, &arg, 1);
3729 done:
3730 if (tree1)
3731 got_object_tree_close(tree1);
3732 if (tree2)
3733 got_object_tree_close(tree2);
3734 if (f1 && fclose(f1) == EOF && err == NULL)
3735 err = got_error_from_errno("fclose");
3736 if (f2 && fclose(f2) == EOF && err == NULL)
3737 err = got_error_from_errno("fclose");
3738 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
3739 err = got_error_from_errno("close");
3740 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
3741 err = got_error_from_errno("close");
3742 return err;
3745 static const struct got_error *
3746 get_changed_paths(struct got_pathlist_head *paths,
3747 struct got_commit_object *commit, struct got_repository *repo,
3748 struct got_diffstat_cb_arg *dsa)
3750 const struct got_error *err = NULL;
3751 struct got_object_id *tree_id1 = NULL, *tree_id2 = NULL;
3752 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
3753 struct got_object_qid *qid;
3754 got_diff_blob_cb cb = got_diff_tree_collect_changed_paths;
3755 FILE *f1 = NULL, *f2 = NULL;
3756 int fd1 = -1, fd2 = -1;
3758 if (dsa) {
3759 cb = got_diff_tree_compute_diffstat;
3761 f1 = got_opentemp();
3762 if (f1 == NULL) {
3763 err = got_error_from_errno("got_opentemp");
3764 goto done;
3766 f2 = got_opentemp();
3767 if (f2 == NULL) {
3768 err = got_error_from_errno("got_opentemp");
3769 goto done;
3771 fd1 = got_opentempfd();
3772 if (fd1 == -1) {
3773 err = got_error_from_errno("got_opentempfd");
3774 goto done;
3776 fd2 = got_opentempfd();
3777 if (fd2 == -1) {
3778 err = got_error_from_errno("got_opentempfd");
3779 goto done;
3783 qid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
3784 if (qid != NULL) {
3785 struct got_commit_object *pcommit;
3786 err = got_object_open_as_commit(&pcommit, repo,
3787 &qid->id);
3788 if (err)
3789 return err;
3791 tree_id1 = got_object_id_dup(
3792 got_object_commit_get_tree_id(pcommit));
3793 if (tree_id1 == NULL) {
3794 got_object_commit_close(pcommit);
3795 return got_error_from_errno("got_object_id_dup");
3797 got_object_commit_close(pcommit);
3801 if (tree_id1) {
3802 err = got_object_open_as_tree(&tree1, repo, tree_id1);
3803 if (err)
3804 goto done;
3807 tree_id2 = got_object_commit_get_tree_id(commit);
3808 err = got_object_open_as_tree(&tree2, repo, tree_id2);
3809 if (err)
3810 goto done;
3812 err = got_diff_tree(tree1, tree2, f1, f2, fd1, fd2, "", "", repo,
3813 cb, dsa ? (void *)dsa : paths, dsa ? 1 : 0);
3814 done:
3815 if (tree1)
3816 got_object_tree_close(tree1);
3817 if (tree2)
3818 got_object_tree_close(tree2);
3819 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
3820 err = got_error_from_errno("close");
3821 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
3822 err = got_error_from_errno("close");
3823 if (f1 && fclose(f1) == EOF && err == NULL)
3824 err = got_error_from_errno("fclose");
3825 if (f2 && fclose(f2) == EOF && err == NULL)
3826 err = got_error_from_errno("fclose");
3827 free(tree_id1);
3828 return err;
3831 static const struct got_error *
3832 print_patch(struct got_commit_object *commit, struct got_object_id *id,
3833 const char *path, int diff_context, struct got_diffstat_cb_arg *dsa,
3834 struct got_repository *repo, FILE *outfile)
3836 const struct got_error *err = NULL;
3837 struct got_commit_object *pcommit = NULL;
3838 char *id_str1 = NULL, *id_str2 = NULL;
3839 struct got_object_id *obj_id1 = NULL, *obj_id2 = NULL;
3840 struct got_object_qid *qid;
3842 qid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
3843 if (qid != NULL) {
3844 err = got_object_open_as_commit(&pcommit, repo,
3845 &qid->id);
3846 if (err)
3847 return err;
3848 err = got_object_id_str(&id_str1, &qid->id);
3849 if (err)
3850 goto done;
3853 err = got_object_id_str(&id_str2, id);
3854 if (err)
3855 goto done;
3857 if (path && path[0] != '\0') {
3858 int obj_type;
3859 err = got_object_id_by_path(&obj_id2, repo, commit, path);
3860 if (err)
3861 goto done;
3862 if (pcommit) {
3863 err = got_object_id_by_path(&obj_id1, repo,
3864 pcommit, path);
3865 if (err) {
3866 if (err->code != GOT_ERR_NO_TREE_ENTRY) {
3867 free(obj_id2);
3868 goto done;
3872 err = got_object_get_type(&obj_type, repo, obj_id2);
3873 if (err) {
3874 free(obj_id2);
3875 goto done;
3877 fprintf(outfile,
3878 "diff %s %s\n", id_str1 ? id_str1 : "/dev/null", id_str2);
3879 fprintf(outfile, "commit - %s\n",
3880 id_str1 ? id_str1 : "/dev/null");
3881 fprintf(outfile, "commit + %s\n", id_str2);
3882 switch (obj_type) {
3883 case GOT_OBJ_TYPE_BLOB:
3884 err = diff_blobs(obj_id1, obj_id2, path, diff_context,
3885 0, 0, dsa, repo, outfile);
3886 break;
3887 case GOT_OBJ_TYPE_TREE:
3888 err = diff_trees(obj_id1, obj_id2, path, diff_context,
3889 0, 0, dsa, repo, outfile);
3890 break;
3891 default:
3892 err = got_error(GOT_ERR_OBJ_TYPE);
3893 break;
3895 free(obj_id1);
3896 free(obj_id2);
3897 } else {
3898 obj_id2 = got_object_commit_get_tree_id(commit);
3899 if (pcommit)
3900 obj_id1 = got_object_commit_get_tree_id(pcommit);
3901 fprintf(outfile,
3902 "diff %s %s\n", id_str1 ? id_str1 : "/dev/null", id_str2);
3903 fprintf(outfile, "commit - %s\n",
3904 id_str1 ? id_str1 : "/dev/null");
3905 fprintf(outfile, "commit + %s\n", id_str2);
3906 err = diff_trees(obj_id1, obj_id2, "", diff_context, 0, 0,
3907 dsa, repo, outfile);
3909 done:
3910 free(id_str1);
3911 free(id_str2);
3912 if (pcommit)
3913 got_object_commit_close(pcommit);
3914 return err;
3917 static char *
3918 get_datestr(time_t *time, char *datebuf)
3920 struct tm mytm, *tm;
3921 char *p, *s;
3923 tm = gmtime_r(time, &mytm);
3924 if (tm == NULL)
3925 return NULL;
3926 s = asctime_r(tm, datebuf);
3927 if (s == NULL)
3928 return NULL;
3929 p = strchr(s, '\n');
3930 if (p)
3931 *p = '\0';
3932 return s;
3935 static const struct got_error *
3936 match_commit(int *have_match, struct got_object_id *id,
3937 struct got_commit_object *commit, regex_t *regex)
3939 const struct got_error *err = NULL;
3940 regmatch_t regmatch;
3941 char *id_str = NULL, *logmsg = NULL;
3943 *have_match = 0;
3945 err = got_object_id_str(&id_str, id);
3946 if (err)
3947 return err;
3949 err = got_object_commit_get_logmsg(&logmsg, commit);
3950 if (err)
3951 goto done;
3953 if (regexec(regex, got_object_commit_get_author(commit), 1,
3954 &regmatch, 0) == 0 ||
3955 regexec(regex, got_object_commit_get_committer(commit), 1,
3956 &regmatch, 0) == 0 ||
3957 regexec(regex, id_str, 1, &regmatch, 0) == 0 ||
3958 regexec(regex, logmsg, 1, &regmatch, 0) == 0)
3959 *have_match = 1;
3960 done:
3961 free(id_str);
3962 free(logmsg);
3963 return err;
3966 static void
3967 match_changed_paths(int *have_match, struct got_pathlist_head *changed_paths,
3968 regex_t *regex)
3970 regmatch_t regmatch;
3971 struct got_pathlist_entry *pe;
3973 *have_match = 0;
3975 TAILQ_FOREACH(pe, changed_paths, entry) {
3976 if (regexec(regex, pe->path, 1, &regmatch, 0) == 0) {
3977 *have_match = 1;
3978 break;
3983 static const struct got_error *
3984 match_patch(int *have_match, struct got_commit_object *commit,
3985 struct got_object_id *id, const char *path, int diff_context,
3986 struct got_repository *repo, regex_t *regex, FILE *f)
3988 const struct got_error *err = NULL;
3989 char *line = NULL;
3990 size_t linesize = 0;
3991 regmatch_t regmatch;
3993 *have_match = 0;
3995 err = got_opentemp_truncate(f);
3996 if (err)
3997 return err;
3999 err = print_patch(commit, id, path, diff_context, NULL, repo, f);
4000 if (err)
4001 goto done;
4003 if (fseeko(f, 0L, SEEK_SET) == -1) {
4004 err = got_error_from_errno("fseeko");
4005 goto done;
4008 while (getline(&line, &linesize, f) != -1) {
4009 if (regexec(regex, line, 1, &regmatch, 0) == 0) {
4010 *have_match = 1;
4011 break;
4014 done:
4015 free(line);
4016 return err;
4019 #define GOT_COMMIT_SEP_STR "-----------------------------------------------\n"
4021 static const struct got_error*
4022 build_refs_str(char **refs_str, struct got_reflist_head *refs,
4023 struct got_object_id *id, struct got_repository *repo,
4024 int local_only)
4026 static const struct got_error *err = NULL;
4027 struct got_reflist_entry *re;
4028 char *s;
4029 const char *name;
4031 *refs_str = NULL;
4033 TAILQ_FOREACH(re, refs, entry) {
4034 struct got_tag_object *tag = NULL;
4035 struct got_object_id *ref_id;
4036 int cmp;
4038 name = got_ref_get_name(re->ref);
4039 if (strcmp(name, GOT_REF_HEAD) == 0)
4040 continue;
4041 if (strncmp(name, "refs/", 5) == 0)
4042 name += 5;
4043 if (strncmp(name, "got/", 4) == 0)
4044 continue;
4045 if (strncmp(name, "heads/", 6) == 0)
4046 name += 6;
4047 if (strncmp(name, "remotes/", 8) == 0) {
4048 if (local_only)
4049 continue;
4050 name += 8;
4051 s = strstr(name, "/" GOT_REF_HEAD);
4052 if (s != NULL && s[strlen(s)] == '\0')
4053 continue;
4055 err = got_ref_resolve(&ref_id, repo, re->ref);
4056 if (err)
4057 break;
4058 if (strncmp(name, "tags/", 5) == 0) {
4059 err = got_object_open_as_tag(&tag, repo, ref_id);
4060 if (err) {
4061 if (err->code != GOT_ERR_OBJ_TYPE) {
4062 free(ref_id);
4063 break;
4065 /* Ref points at something other than a tag. */
4066 err = NULL;
4067 tag = NULL;
4070 cmp = got_object_id_cmp(tag ?
4071 got_object_tag_get_object_id(tag) : ref_id, id);
4072 free(ref_id);
4073 if (tag)
4074 got_object_tag_close(tag);
4075 if (cmp != 0)
4076 continue;
4077 s = *refs_str;
4078 if (asprintf(refs_str, "%s%s%s", s ? s : "",
4079 s ? ", " : "", name) == -1) {
4080 err = got_error_from_errno("asprintf");
4081 free(s);
4082 *refs_str = NULL;
4083 break;
4085 free(s);
4088 return err;
4091 static const struct got_error *
4092 print_commit_oneline(struct got_commit_object *commit, struct got_object_id *id,
4093 struct got_repository *repo, struct got_reflist_object_id_map *refs_idmap)
4095 const struct got_error *err = NULL;
4096 char *ref_str = NULL, *id_str = NULL, *logmsg0 = NULL;
4097 char *comma, *s, *nl;
4098 struct got_reflist_head *refs;
4099 char datebuf[12]; /* YYYY-MM-DD + SPACE + NUL */
4100 struct tm tm;
4101 time_t committer_time;
4103 refs = got_reflist_object_id_map_lookup(refs_idmap, id);
4104 if (refs) {
4105 err = build_refs_str(&ref_str, refs, id, repo, 1);
4106 if (err)
4107 return err;
4109 /* Display the first matching ref only. */
4110 if (ref_str && (comma = strchr(ref_str, ',')) != NULL)
4111 *comma = '\0';
4114 if (ref_str == NULL) {
4115 err = got_object_id_str(&id_str, id);
4116 if (err)
4117 return err;
4120 committer_time = got_object_commit_get_committer_time(commit);
4121 if (gmtime_r(&committer_time, &tm) == NULL) {
4122 err = got_error_from_errno("gmtime_r");
4123 goto done;
4125 if (strftime(datebuf, sizeof(datebuf), "%G-%m-%d ", &tm) == 0) {
4126 err = got_error(GOT_ERR_NO_SPACE);
4127 goto done;
4130 err = got_object_commit_get_logmsg(&logmsg0, commit);
4131 if (err)
4132 goto done;
4134 s = logmsg0;
4135 while (isspace((unsigned char)s[0]))
4136 s++;
4138 nl = strchr(s, '\n');
4139 if (nl) {
4140 *nl = '\0';
4143 if (ref_str)
4144 printf("%s%-7s %s\n", datebuf, ref_str, s);
4145 else
4146 printf("%s%.7s %s\n", datebuf, id_str, s);
4148 if (fflush(stdout) != 0 && err == NULL)
4149 err = got_error_from_errno("fflush");
4150 done:
4151 free(id_str);
4152 free(ref_str);
4153 free(logmsg0);
4154 return err;
4157 static const struct got_error *
4158 print_diffstat(struct got_diffstat_cb_arg *dsa, const char *header)
4160 struct got_pathlist_entry *pe;
4162 if (header != NULL)
4163 printf("%s\n", header);
4165 TAILQ_FOREACH(pe, dsa->paths, entry) {
4166 struct got_diff_changed_path *cp = pe->data;
4167 int pad = dsa->max_path_len - pe->path_len + 1;
4169 printf(" %c %s%*c | %*d+ %*d-\n", cp->status, pe->path, pad,
4170 ' ', dsa->add_cols + 1, cp->add, dsa->rm_cols + 1, cp->rm);
4172 printf("\n%d file%s changed, %d insertion%s(+), %d deletion%s(-)\n\n",
4173 dsa->nfiles, dsa->nfiles > 1 ? "s" : "", dsa->ins,
4174 dsa->ins != 1 ? "s" : "", dsa->del, dsa->del != 1 ? "s" : "");
4176 if (fflush(stdout) != 0)
4177 return got_error_from_errno("fflush");
4179 return NULL;
4182 static const struct got_error *
4183 printfile(FILE *f)
4185 char buf[8192];
4186 size_t r;
4188 if (fseeko(f, 0L, SEEK_SET) == -1)
4189 return got_error_from_errno("fseek");
4191 for (;;) {
4192 r = fread(buf, 1, sizeof(buf), f);
4193 if (r == 0) {
4194 if (ferror(f))
4195 return got_error_from_errno("fread");
4196 if (feof(f))
4197 break;
4199 if (fwrite(buf, 1, r, stdout) != r)
4200 return got_ferror(stdout, GOT_ERR_IO);
4203 return NULL;
4206 static const struct got_error *
4207 print_commit(struct got_commit_object *commit, struct got_object_id *id,
4208 struct got_repository *repo, const char *path,
4209 struct got_pathlist_head *changed_paths,
4210 struct got_diffstat_cb_arg *diffstat, int show_patch, int diff_context,
4211 struct got_reflist_object_id_map *refs_idmap, const char *custom_refs_str,
4212 const char *prefix)
4214 const struct got_error *err = NULL;
4215 FILE *f = NULL;
4216 char *id_str, *datestr, *logmsg0, *logmsg, *line;
4217 char datebuf[26];
4218 time_t committer_time;
4219 const char *author, *committer;
4220 char *refs_str = NULL;
4222 err = got_object_id_str(&id_str, id);
4223 if (err)
4224 return err;
4226 if (custom_refs_str == NULL) {
4227 struct got_reflist_head *refs;
4228 refs = got_reflist_object_id_map_lookup(refs_idmap, id);
4229 if (refs) {
4230 err = build_refs_str(&refs_str, refs, id, repo, 0);
4231 if (err)
4232 goto done;
4236 printf(GOT_COMMIT_SEP_STR);
4237 if (custom_refs_str)
4238 printf("%s %s (%s)\n", prefix ? prefix : "commit", id_str,
4239 custom_refs_str);
4240 else
4241 printf("%s %s%s%s%s\n", prefix ? prefix : "commit", id_str,
4242 refs_str ? " (" : "", refs_str ? refs_str : "",
4243 refs_str ? ")" : "");
4244 free(id_str);
4245 id_str = NULL;
4246 free(refs_str);
4247 refs_str = NULL;
4248 printf("from: %s\n", got_object_commit_get_author(commit));
4249 author = got_object_commit_get_author(commit);
4250 committer = got_object_commit_get_committer(commit);
4251 if (strcmp(author, committer) != 0)
4252 printf("via: %s\n", committer);
4253 committer_time = got_object_commit_get_committer_time(commit);
4254 datestr = get_datestr(&committer_time, datebuf);
4255 if (datestr)
4256 printf("date: %s UTC\n", datestr);
4257 if (got_object_commit_get_nparents(commit) > 1) {
4258 const struct got_object_id_queue *parent_ids;
4259 struct got_object_qid *qid;
4260 int n = 1;
4261 parent_ids = got_object_commit_get_parent_ids(commit);
4262 STAILQ_FOREACH(qid, parent_ids, entry) {
4263 err = got_object_id_str(&id_str, &qid->id);
4264 if (err)
4265 goto done;
4266 printf("parent %d: %s\n", n++, id_str);
4267 free(id_str);
4268 id_str = NULL;
4272 err = got_object_commit_get_logmsg(&logmsg0, commit);
4273 if (err)
4274 goto done;
4276 logmsg = logmsg0;
4277 do {
4278 line = strsep(&logmsg, "\n");
4279 if (line)
4280 printf(" %s\n", line);
4281 } while (line);
4282 free(logmsg0);
4284 if (changed_paths && diffstat == NULL) {
4285 struct got_pathlist_entry *pe;
4287 TAILQ_FOREACH(pe, changed_paths, entry) {
4288 struct got_diff_changed_path *cp = pe->data;
4290 printf(" %c %s\n", cp->status, pe->path);
4292 printf("\n");
4294 if (show_patch) {
4295 if (diffstat) {
4296 f = got_opentemp();
4297 if (f == NULL) {
4298 err = got_error_from_errno("got_opentemp");
4299 goto done;
4303 err = print_patch(commit, id, path, diff_context, diffstat,
4304 repo, diffstat == NULL ? stdout : f);
4305 if (err)
4306 goto done;
4308 if (diffstat) {
4309 err = print_diffstat(diffstat, NULL);
4310 if (err)
4311 goto done;
4312 if (show_patch) {
4313 err = printfile(f);
4314 if (err)
4315 goto done;
4318 if (show_patch)
4319 printf("\n");
4321 if (fflush(stdout) != 0 && err == NULL)
4322 err = got_error_from_errno("fflush");
4323 done:
4324 if (f && fclose(f) == EOF && err == NULL)
4325 err = got_error_from_errno("fclose");
4326 free(id_str);
4327 free(refs_str);
4328 return err;
4331 static const struct got_error *
4332 print_commits(struct got_object_id *root_id, struct got_object_id *end_id,
4333 struct got_repository *repo, const char *path, int show_changed_paths,
4334 int show_diffstat, int show_patch, const char *search_pattern,
4335 int diff_context, int limit, int log_branches, int reverse_display_order,
4336 struct got_reflist_object_id_map *refs_idmap, int one_line,
4337 FILE *tmpfile)
4339 const struct got_error *err;
4340 struct got_commit_graph *graph;
4341 regex_t regex;
4342 int have_match;
4343 struct got_object_id_queue reversed_commits;
4344 struct got_object_qid *qid;
4345 struct got_commit_object *commit;
4346 struct got_pathlist_head changed_paths;
4348 STAILQ_INIT(&reversed_commits);
4349 TAILQ_INIT(&changed_paths);
4351 if (search_pattern && regcomp(&regex, search_pattern,
4352 REG_EXTENDED | REG_NOSUB | REG_NEWLINE))
4353 return got_error_msg(GOT_ERR_REGEX, search_pattern);
4355 err = got_commit_graph_open(&graph, path, !log_branches);
4356 if (err)
4357 return err;
4358 err = got_commit_graph_iter_start(graph, root_id, repo,
4359 check_cancelled, NULL);
4360 if (err)
4361 goto done;
4362 for (;;) {
4363 struct got_object_id id;
4364 struct got_diffstat_cb_arg dsa = { 0, 0, 0, 0, 0, 0,
4365 &changed_paths, 0, 0, GOT_DIFF_ALGORITHM_PATIENCE };
4367 if (sigint_received || sigpipe_received)
4368 break;
4370 err = got_commit_graph_iter_next(&id, graph, repo,
4371 check_cancelled, NULL);
4372 if (err) {
4373 if (err->code == GOT_ERR_ITER_COMPLETED)
4374 err = NULL;
4375 break;
4378 err = got_object_open_as_commit(&commit, repo, &id);
4379 if (err)
4380 break;
4382 if ((show_changed_paths || (show_diffstat && !show_patch))
4383 && !reverse_display_order) {
4384 err = get_changed_paths(&changed_paths, commit, repo,
4385 show_diffstat ? &dsa : NULL);
4386 if (err)
4387 break;
4390 if (search_pattern) {
4391 err = match_commit(&have_match, &id, commit, &regex);
4392 if (err) {
4393 got_object_commit_close(commit);
4394 break;
4396 if (have_match == 0 && show_changed_paths)
4397 match_changed_paths(&have_match,
4398 &changed_paths, &regex);
4399 if (have_match == 0 && show_patch) {
4400 err = match_patch(&have_match, commit, &id,
4401 path, diff_context, repo, &regex, tmpfile);
4402 if (err)
4403 break;
4405 if (have_match == 0) {
4406 got_object_commit_close(commit);
4407 got_pathlist_free(&changed_paths,
4408 GOT_PATHLIST_FREE_ALL);
4409 continue;
4413 if (reverse_display_order) {
4414 err = got_object_qid_alloc(&qid, &id);
4415 if (err)
4416 break;
4417 STAILQ_INSERT_HEAD(&reversed_commits, qid, entry);
4418 got_object_commit_close(commit);
4419 } else {
4420 if (one_line)
4421 err = print_commit_oneline(commit, &id,
4422 repo, refs_idmap);
4423 else
4424 err = print_commit(commit, &id, repo, path,
4425 (show_changed_paths || show_diffstat) ?
4426 &changed_paths : NULL,
4427 show_diffstat ? &dsa : NULL, show_patch,
4428 diff_context, refs_idmap, NULL, NULL);
4429 got_object_commit_close(commit);
4430 if (err)
4431 break;
4433 if ((limit && --limit == 0) ||
4434 (end_id && got_object_id_cmp(&id, end_id) == 0))
4435 break;
4437 got_pathlist_free(&changed_paths, GOT_PATHLIST_FREE_ALL);
4439 if (reverse_display_order) {
4440 STAILQ_FOREACH(qid, &reversed_commits, entry) {
4441 struct got_diffstat_cb_arg dsa = { 0, 0, 0, 0, 0, 0,
4442 &changed_paths, 0, 0, GOT_DIFF_ALGORITHM_PATIENCE };
4444 err = got_object_open_as_commit(&commit, repo,
4445 &qid->id);
4446 if (err)
4447 break;
4448 if (show_changed_paths ||
4449 (show_diffstat && !show_patch)) {
4450 err = get_changed_paths(&changed_paths, commit,
4451 repo, show_diffstat ? &dsa : NULL);
4452 if (err)
4453 break;
4455 if (one_line)
4456 err = print_commit_oneline(commit, &qid->id,
4457 repo, refs_idmap);
4458 else
4459 err = print_commit(commit, &qid->id, repo, path,
4460 (show_changed_paths || show_diffstat) ?
4461 &changed_paths : NULL,
4462 show_diffstat ? &dsa : NULL, show_patch,
4463 diff_context, refs_idmap, NULL, NULL);
4464 got_object_commit_close(commit);
4465 if (err)
4466 break;
4467 got_pathlist_free(&changed_paths, GOT_PATHLIST_FREE_ALL);
4470 done:
4471 while (!STAILQ_EMPTY(&reversed_commits)) {
4472 qid = STAILQ_FIRST(&reversed_commits);
4473 STAILQ_REMOVE_HEAD(&reversed_commits, entry);
4474 got_object_qid_free(qid);
4476 got_pathlist_free(&changed_paths, GOT_PATHLIST_FREE_ALL);
4477 if (search_pattern)
4478 regfree(&regex);
4479 got_commit_graph_close(graph);
4480 return err;
4483 __dead static void
4484 usage_log(void)
4486 fprintf(stderr, "usage: %s log [-bdPpRs] [-C number] [-c commit] "
4487 "[-l N] [-r repository-path] [-S search-pattern] [-x commit] "
4488 "[path]\n", getprogname());
4489 exit(1);
4492 static int
4493 get_default_log_limit(void)
4495 const char *got_default_log_limit;
4496 long long n;
4497 const char *errstr;
4499 got_default_log_limit = getenv("GOT_LOG_DEFAULT_LIMIT");
4500 if (got_default_log_limit == NULL)
4501 return 0;
4502 n = strtonum(got_default_log_limit, 0, INT_MAX, &errstr);
4503 if (errstr != NULL)
4504 return 0;
4505 return n;
4508 static const struct got_error *
4509 cmd_log(int argc, char *argv[])
4511 const struct got_error *error;
4512 struct got_repository *repo = NULL;
4513 struct got_worktree *worktree = NULL;
4514 struct got_object_id *start_id = NULL, *end_id = NULL;
4515 char *repo_path = NULL, *path = NULL, *cwd = NULL, *in_repo_path = NULL;
4516 const char *start_commit = NULL, *end_commit = NULL;
4517 const char *search_pattern = NULL;
4518 int diff_context = -1, ch;
4519 int show_changed_paths = 0, show_patch = 0, limit = 0, log_branches = 0;
4520 int show_diffstat = 0, reverse_display_order = 0, one_line = 0;
4521 const char *errstr;
4522 struct got_reflist_head refs;
4523 struct got_reflist_object_id_map *refs_idmap = NULL;
4524 FILE *tmpfile = NULL;
4525 int *pack_fds = NULL;
4527 TAILQ_INIT(&refs);
4529 #ifndef PROFILE
4530 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
4531 NULL)
4532 == -1)
4533 err(1, "pledge");
4534 #endif
4536 limit = get_default_log_limit();
4538 while ((ch = getopt(argc, argv, "bC:c:dl:PpRr:S:sx:")) != -1) {
4539 switch (ch) {
4540 case 'b':
4541 log_branches = 1;
4542 break;
4543 case 'C':
4544 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
4545 &errstr);
4546 if (errstr != NULL)
4547 errx(1, "number of context lines is %s: %s",
4548 errstr, optarg);
4549 break;
4550 case 'c':
4551 start_commit = optarg;
4552 break;
4553 case 'd':
4554 show_diffstat = 1;
4555 break;
4556 case 'l':
4557 limit = strtonum(optarg, 0, INT_MAX, &errstr);
4558 if (errstr != NULL)
4559 errx(1, "number of commits is %s: %s",
4560 errstr, optarg);
4561 break;
4562 case 'P':
4563 show_changed_paths = 1;
4564 break;
4565 case 'p':
4566 show_patch = 1;
4567 break;
4568 case 'R':
4569 reverse_display_order = 1;
4570 break;
4571 case 'r':
4572 repo_path = realpath(optarg, NULL);
4573 if (repo_path == NULL)
4574 return got_error_from_errno2("realpath",
4575 optarg);
4576 got_path_strip_trailing_slashes(repo_path);
4577 break;
4578 case 'S':
4579 search_pattern = optarg;
4580 break;
4581 case 's':
4582 one_line = 1;
4583 break;
4584 case 'x':
4585 end_commit = optarg;
4586 break;
4587 default:
4588 usage_log();
4589 /* NOTREACHED */
4593 argc -= optind;
4594 argv += optind;
4596 if (diff_context == -1)
4597 diff_context = 3;
4598 else if (!show_patch)
4599 errx(1, "-C requires -p");
4601 if (one_line && (show_patch || show_changed_paths || show_diffstat))
4602 errx(1, "cannot use -s with -d, -p or -P");
4604 cwd = getcwd(NULL, 0);
4605 if (cwd == NULL) {
4606 error = got_error_from_errno("getcwd");
4607 goto done;
4610 error = got_repo_pack_fds_open(&pack_fds);
4611 if (error != NULL)
4612 goto done;
4614 if (repo_path == NULL) {
4615 error = got_worktree_open(&worktree, cwd);
4616 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4617 goto done;
4618 error = NULL;
4621 if (argc == 1) {
4622 if (worktree) {
4623 error = got_worktree_resolve_path(&path, worktree,
4624 argv[0]);
4625 if (error)
4626 goto done;
4627 } else {
4628 path = strdup(argv[0]);
4629 if (path == NULL) {
4630 error = got_error_from_errno("strdup");
4631 goto done;
4634 } else if (argc != 0)
4635 usage_log();
4637 if (repo_path == NULL) {
4638 repo_path = worktree ?
4639 strdup(got_worktree_get_repo_path(worktree)) : strdup(cwd);
4641 if (repo_path == NULL) {
4642 error = got_error_from_errno("strdup");
4643 goto done;
4646 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
4647 if (error != NULL)
4648 goto done;
4650 error = apply_unveil(got_repo_get_path(repo), 1,
4651 worktree ? got_worktree_get_root_path(worktree) : NULL);
4652 if (error)
4653 goto done;
4655 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
4656 if (error)
4657 goto done;
4659 error = got_reflist_object_id_map_create(&refs_idmap, &refs, repo);
4660 if (error)
4661 goto done;
4663 if (start_commit == NULL) {
4664 struct got_reference *head_ref;
4665 struct got_commit_object *commit = NULL;
4666 error = got_ref_open(&head_ref, repo,
4667 worktree ? got_worktree_get_head_ref_name(worktree)
4668 : GOT_REF_HEAD, 0);
4669 if (error != NULL)
4670 goto done;
4671 error = got_ref_resolve(&start_id, repo, head_ref);
4672 got_ref_close(head_ref);
4673 if (error != NULL)
4674 goto done;
4675 error = got_object_open_as_commit(&commit, repo,
4676 start_id);
4677 if (error != NULL)
4678 goto done;
4679 got_object_commit_close(commit);
4680 } else {
4681 error = got_repo_match_object_id(&start_id, NULL,
4682 start_commit, GOT_OBJ_TYPE_COMMIT, &refs, repo);
4683 if (error != NULL)
4684 goto done;
4686 if (end_commit != NULL) {
4687 error = got_repo_match_object_id(&end_id, NULL,
4688 end_commit, GOT_OBJ_TYPE_COMMIT, &refs, repo);
4689 if (error != NULL)
4690 goto done;
4693 if (worktree) {
4695 * If a path was specified on the command line it was resolved
4696 * to a path in the work tree above. Prepend the work tree's
4697 * path prefix to obtain the corresponding in-repository path.
4699 if (path) {
4700 const char *prefix;
4701 prefix = got_worktree_get_path_prefix(worktree);
4702 if (asprintf(&in_repo_path, "%s%s%s", prefix,
4703 (path[0] != '\0') ? "/" : "", path) == -1) {
4704 error = got_error_from_errno("asprintf");
4705 goto done;
4708 } else
4709 error = got_repo_map_path(&in_repo_path, repo,
4710 path ? path : "");
4711 if (error != NULL)
4712 goto done;
4713 if (in_repo_path) {
4714 free(path);
4715 path = in_repo_path;
4718 if (worktree) {
4719 /* Release work tree lock. */
4720 got_worktree_close(worktree);
4721 worktree = NULL;
4724 if (search_pattern && show_patch) {
4725 tmpfile = got_opentemp();
4726 if (tmpfile == NULL) {
4727 error = got_error_from_errno("got_opentemp");
4728 goto done;
4732 error = print_commits(start_id, end_id, repo, path ? path : "",
4733 show_changed_paths, show_diffstat, show_patch, search_pattern,
4734 diff_context, limit, log_branches, reverse_display_order,
4735 refs_idmap, one_line, tmpfile);
4736 done:
4737 free(path);
4738 free(repo_path);
4739 free(cwd);
4740 if (worktree)
4741 got_worktree_close(worktree);
4742 if (repo) {
4743 const struct got_error *close_err = got_repo_close(repo);
4744 if (error == NULL)
4745 error = close_err;
4747 if (pack_fds) {
4748 const struct got_error *pack_err =
4749 got_repo_pack_fds_close(pack_fds);
4750 if (error == NULL)
4751 error = pack_err;
4753 if (refs_idmap)
4754 got_reflist_object_id_map_free(refs_idmap);
4755 if (tmpfile && fclose(tmpfile) == EOF && error == NULL)
4756 error = got_error_from_errno("fclose");
4757 got_ref_list_free(&refs);
4758 return error;
4761 __dead static void
4762 usage_diff(void)
4764 fprintf(stderr, "usage: %s diff [-adPsw] [-C number] [-c commit] "
4765 "[-r repository-path] [object1 object2 | path ...]\n",
4766 getprogname());
4767 exit(1);
4770 struct print_diff_arg {
4771 struct got_repository *repo;
4772 struct got_worktree *worktree;
4773 struct got_diffstat_cb_arg *diffstat;
4774 int diff_context;
4775 const char *id_str;
4776 int header_shown;
4777 int diff_staged;
4778 enum got_diff_algorithm diff_algo;
4779 int ignore_whitespace;
4780 int force_text_diff;
4781 FILE *f1;
4782 FILE *f2;
4783 FILE *outfile;
4787 * Create a file which contains the target path of a symlink so we can feed
4788 * it as content to the diff engine.
4790 static const struct got_error *
4791 get_symlink_target_file(int *fd, int dirfd, const char *de_name,
4792 const char *abspath)
4794 const struct got_error *err = NULL;
4795 char target_path[PATH_MAX];
4796 ssize_t target_len, outlen;
4798 *fd = -1;
4800 if (dirfd != -1) {
4801 target_len = readlinkat(dirfd, de_name, target_path, PATH_MAX);
4802 if (target_len == -1)
4803 return got_error_from_errno2("readlinkat", abspath);
4804 } else {
4805 target_len = readlink(abspath, target_path, PATH_MAX);
4806 if (target_len == -1)
4807 return got_error_from_errno2("readlink", abspath);
4810 *fd = got_opentempfd();
4811 if (*fd == -1)
4812 return got_error_from_errno("got_opentempfd");
4814 outlen = write(*fd, target_path, target_len);
4815 if (outlen == -1) {
4816 err = got_error_from_errno("got_opentempfd");
4817 goto done;
4820 if (lseek(*fd, 0, SEEK_SET) == -1) {
4821 err = got_error_from_errno2("lseek", abspath);
4822 goto done;
4824 done:
4825 if (err) {
4826 close(*fd);
4827 *fd = -1;
4829 return err;
4832 static const struct got_error *
4833 print_diff(void *arg, unsigned char status, unsigned char staged_status,
4834 const char *path, struct got_object_id *blob_id,
4835 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
4836 int dirfd, const char *de_name)
4838 struct print_diff_arg *a = arg;
4839 const struct got_error *err = NULL;
4840 struct got_blob_object *blob1 = NULL;
4841 int fd = -1, fd1 = -1, fd2 = -1;
4842 FILE *f2 = NULL;
4843 char *abspath = NULL, *label1 = NULL;
4844 struct stat sb;
4845 off_t size1 = 0;
4846 int f2_exists = 0;
4848 memset(&sb, 0, sizeof(sb));
4850 if (a->diff_staged) {
4851 if (staged_status != GOT_STATUS_MODIFY &&
4852 staged_status != GOT_STATUS_ADD &&
4853 staged_status != GOT_STATUS_DELETE)
4854 return NULL;
4855 } else {
4856 if (staged_status == GOT_STATUS_DELETE)
4857 return NULL;
4858 if (status == GOT_STATUS_NONEXISTENT)
4859 return got_error_set_errno(ENOENT, path);
4860 if (status != GOT_STATUS_MODIFY &&
4861 status != GOT_STATUS_ADD &&
4862 status != GOT_STATUS_DELETE &&
4863 status != GOT_STATUS_CONFLICT)
4864 return NULL;
4867 err = got_opentemp_truncate(a->f1);
4868 if (err)
4869 return got_error_from_errno("got_opentemp_truncate");
4870 err = got_opentemp_truncate(a->f2);
4871 if (err)
4872 return got_error_from_errno("got_opentemp_truncate");
4874 if (!a->header_shown) {
4875 if (fprintf(a->outfile, "diff %s%s\n",
4876 a->diff_staged ? "-s " : "",
4877 got_worktree_get_root_path(a->worktree)) < 0) {
4878 err = got_error_from_errno("fprintf");
4879 goto done;
4881 if (fprintf(a->outfile, "commit - %s\n", a->id_str) < 0) {
4882 err = got_error_from_errno("fprintf");
4883 goto done;
4885 if (fprintf(a->outfile, "path + %s%s\n",
4886 got_worktree_get_root_path(a->worktree),
4887 a->diff_staged ? " (staged changes)" : "") < 0) {
4888 err = got_error_from_errno("fprintf");
4889 goto done;
4891 a->header_shown = 1;
4894 if (a->diff_staged) {
4895 const char *label1 = NULL, *label2 = NULL;
4896 switch (staged_status) {
4897 case GOT_STATUS_MODIFY:
4898 label1 = path;
4899 label2 = path;
4900 break;
4901 case GOT_STATUS_ADD:
4902 label2 = path;
4903 break;
4904 case GOT_STATUS_DELETE:
4905 label1 = path;
4906 break;
4907 default:
4908 return got_error(GOT_ERR_FILE_STATUS);
4910 fd1 = got_opentempfd();
4911 if (fd1 == -1) {
4912 err = got_error_from_errno("got_opentempfd");
4913 goto done;
4915 fd2 = got_opentempfd();
4916 if (fd2 == -1) {
4917 err = got_error_from_errno("got_opentempfd");
4918 goto done;
4920 err = got_diff_objects_as_blobs(NULL, NULL, a->f1, a->f2,
4921 fd1, fd2, blob_id, staged_blob_id, label1, label2,
4922 a->diff_algo, a->diff_context, a->ignore_whitespace,
4923 a->force_text_diff, a->diffstat, a->repo, a->outfile);
4924 goto done;
4927 fd1 = got_opentempfd();
4928 if (fd1 == -1) {
4929 err = got_error_from_errno("got_opentempfd");
4930 goto done;
4933 if (staged_status == GOT_STATUS_ADD ||
4934 staged_status == GOT_STATUS_MODIFY) {
4935 char *id_str;
4936 err = got_object_open_as_blob(&blob1, a->repo, staged_blob_id,
4937 8192, fd1);
4938 if (err)
4939 goto done;
4940 err = got_object_id_str(&id_str, staged_blob_id);
4941 if (err)
4942 goto done;
4943 if (asprintf(&label1, "%s (staged)", id_str) == -1) {
4944 err = got_error_from_errno("asprintf");
4945 free(id_str);
4946 goto done;
4948 free(id_str);
4949 } else if (status != GOT_STATUS_ADD) {
4950 err = got_object_open_as_blob(&blob1, a->repo, blob_id, 8192,
4951 fd1);
4952 if (err)
4953 goto done;
4956 if (status != GOT_STATUS_DELETE) {
4957 if (asprintf(&abspath, "%s/%s",
4958 got_worktree_get_root_path(a->worktree), path) == -1) {
4959 err = got_error_from_errno("asprintf");
4960 goto done;
4963 if (dirfd != -1) {
4964 fd = openat(dirfd, de_name,
4965 O_RDONLY | O_NOFOLLOW | O_CLOEXEC);
4966 if (fd == -1) {
4967 if (!got_err_open_nofollow_on_symlink()) {
4968 err = got_error_from_errno2("openat",
4969 abspath);
4970 goto done;
4972 err = get_symlink_target_file(&fd, dirfd,
4973 de_name, abspath);
4974 if (err)
4975 goto done;
4977 } else {
4978 fd = open(abspath, O_RDONLY | O_NOFOLLOW | O_CLOEXEC);
4979 if (fd == -1) {
4980 if (!got_err_open_nofollow_on_symlink()) {
4981 err = got_error_from_errno2("open",
4982 abspath);
4983 goto done;
4985 err = get_symlink_target_file(&fd, dirfd,
4986 de_name, abspath);
4987 if (err)
4988 goto done;
4991 if (fstatat(fd, abspath, &sb, AT_SYMLINK_NOFOLLOW) == -1) {
4992 err = got_error_from_errno2("fstatat", abspath);
4993 goto done;
4995 f2 = fdopen(fd, "r");
4996 if (f2 == NULL) {
4997 err = got_error_from_errno2("fdopen", abspath);
4998 goto done;
5000 fd = -1;
5001 f2_exists = 1;
5004 if (blob1) {
5005 err = got_object_blob_dump_to_file(&size1, NULL, NULL,
5006 a->f1, blob1);
5007 if (err)
5008 goto done;
5011 err = got_diff_blob_file(blob1, a->f1, size1, label1, f2 ? f2 : a->f2,
5012 f2_exists, &sb, path, GOT_DIFF_ALGORITHM_PATIENCE, a->diff_context,
5013 a->ignore_whitespace, a->force_text_diff, a->diffstat, a->outfile);
5014 done:
5015 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
5016 err = got_error_from_errno("close");
5017 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
5018 err = got_error_from_errno("close");
5019 if (blob1)
5020 got_object_blob_close(blob1);
5021 if (fd != -1 && close(fd) == -1 && err == NULL)
5022 err = got_error_from_errno("close");
5023 if (f2 && fclose(f2) == EOF && err == NULL)
5024 err = got_error_from_errno("fclose");
5025 free(abspath);
5026 return err;
5029 static const struct got_error *
5030 cmd_diff(int argc, char *argv[])
5032 const struct got_error *error;
5033 struct got_repository *repo = NULL;
5034 struct got_worktree *worktree = NULL;
5035 char *cwd = NULL, *repo_path = NULL;
5036 const char *commit_args[2] = { NULL, NULL };
5037 int ncommit_args = 0;
5038 struct got_object_id *ids[2] = { NULL, NULL };
5039 char *labels[2] = { NULL, NULL };
5040 int type1 = GOT_OBJ_TYPE_ANY, type2 = GOT_OBJ_TYPE_ANY;
5041 int diff_context = 3, diff_staged = 0, ignore_whitespace = 0, ch, i;
5042 int force_text_diff = 0, force_path = 0, rflag = 0, show_diffstat = 0;
5043 const char *errstr;
5044 struct got_reflist_head refs;
5045 struct got_pathlist_head diffstat_paths, paths;
5046 FILE *f1 = NULL, *f2 = NULL, *outfile = NULL;
5047 int fd1 = -1, fd2 = -1;
5048 int *pack_fds = NULL;
5049 struct got_diffstat_cb_arg dsa;
5051 memset(&dsa, 0, sizeof(dsa));
5053 TAILQ_INIT(&refs);
5054 TAILQ_INIT(&paths);
5055 TAILQ_INIT(&diffstat_paths);
5057 #ifndef PROFILE
5058 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
5059 NULL) == -1)
5060 err(1, "pledge");
5061 #endif
5063 while ((ch = getopt(argc, argv, "aC:c:dPr:sw")) != -1) {
5064 switch (ch) {
5065 case 'a':
5066 force_text_diff = 1;
5067 break;
5068 case 'C':
5069 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
5070 &errstr);
5071 if (errstr != NULL)
5072 errx(1, "number of context lines is %s: %s",
5073 errstr, optarg);
5074 break;
5075 case 'c':
5076 if (ncommit_args >= 2)
5077 errx(1, "too many -c options used");
5078 commit_args[ncommit_args++] = optarg;
5079 break;
5080 case 'd':
5081 show_diffstat = 1;
5082 break;
5083 case 'P':
5084 force_path = 1;
5085 break;
5086 case 'r':
5087 repo_path = realpath(optarg, NULL);
5088 if (repo_path == NULL)
5089 return got_error_from_errno2("realpath",
5090 optarg);
5091 got_path_strip_trailing_slashes(repo_path);
5092 rflag = 1;
5093 break;
5094 case 's':
5095 diff_staged = 1;
5096 break;
5097 case 'w':
5098 ignore_whitespace = 1;
5099 break;
5100 default:
5101 usage_diff();
5102 /* NOTREACHED */
5106 argc -= optind;
5107 argv += optind;
5109 cwd = getcwd(NULL, 0);
5110 if (cwd == NULL) {
5111 error = got_error_from_errno("getcwd");
5112 goto done;
5115 error = got_repo_pack_fds_open(&pack_fds);
5116 if (error != NULL)
5117 goto done;
5119 if (repo_path == NULL) {
5120 error = got_worktree_open(&worktree, cwd);
5121 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5122 goto done;
5123 else
5124 error = NULL;
5125 if (worktree) {
5126 repo_path =
5127 strdup(got_worktree_get_repo_path(worktree));
5128 if (repo_path == NULL) {
5129 error = got_error_from_errno("strdup");
5130 goto done;
5132 } else {
5133 repo_path = strdup(cwd);
5134 if (repo_path == NULL) {
5135 error = got_error_from_errno("strdup");
5136 goto done;
5141 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
5142 free(repo_path);
5143 if (error != NULL)
5144 goto done;
5146 if (show_diffstat) {
5147 dsa.paths = &diffstat_paths;
5148 dsa.force_text = force_text_diff;
5149 dsa.ignore_ws = ignore_whitespace;
5150 dsa.diff_algo = GOT_DIFF_ALGORITHM_PATIENCE;
5153 if (rflag || worktree == NULL || ncommit_args > 0) {
5154 if (force_path) {
5155 error = got_error_msg(GOT_ERR_NOT_IMPL,
5156 "-P option can only be used when diffing "
5157 "a work tree");
5158 goto done;
5160 if (diff_staged) {
5161 error = got_error_msg(GOT_ERR_NOT_IMPL,
5162 "-s option can only be used when diffing "
5163 "a work tree");
5164 goto done;
5168 error = apply_unveil(got_repo_get_path(repo), 1,
5169 worktree ? got_worktree_get_root_path(worktree) : NULL);
5170 if (error)
5171 goto done;
5173 if ((!force_path && argc == 2) || ncommit_args > 0) {
5174 int obj_type = (ncommit_args > 0 ?
5175 GOT_OBJ_TYPE_COMMIT : GOT_OBJ_TYPE_ANY);
5176 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
5177 NULL);
5178 if (error)
5179 goto done;
5180 for (i = 0; i < (ncommit_args > 0 ? ncommit_args : argc); i++) {
5181 const char *arg;
5182 if (ncommit_args > 0)
5183 arg = commit_args[i];
5184 else
5185 arg = argv[i];
5186 error = got_repo_match_object_id(&ids[i], &labels[i],
5187 arg, obj_type, &refs, repo);
5188 if (error) {
5189 if (error->code != GOT_ERR_NOT_REF &&
5190 error->code != GOT_ERR_NO_OBJ)
5191 goto done;
5192 if (ncommit_args > 0)
5193 goto done;
5194 error = NULL;
5195 break;
5200 f1 = got_opentemp();
5201 if (f1 == NULL) {
5202 error = got_error_from_errno("got_opentemp");
5203 goto done;
5206 f2 = got_opentemp();
5207 if (f2 == NULL) {
5208 error = got_error_from_errno("got_opentemp");
5209 goto done;
5212 outfile = got_opentemp();
5213 if (outfile == NULL) {
5214 error = got_error_from_errno("got_opentemp");
5215 goto done;
5218 if (ncommit_args == 0 && (ids[0] == NULL || ids[1] == NULL)) {
5219 struct print_diff_arg arg;
5220 char *id_str;
5222 if (worktree == NULL) {
5223 if (argc == 2 && ids[0] == NULL) {
5224 error = got_error_path(argv[0], GOT_ERR_NO_OBJ);
5225 goto done;
5226 } else if (argc == 2 && ids[1] == NULL) {
5227 error = got_error_path(argv[1], GOT_ERR_NO_OBJ);
5228 goto done;
5229 } else if (argc > 0) {
5230 error = got_error_fmt(GOT_ERR_NOT_WORKTREE,
5231 "%s", "specified paths cannot be resolved");
5232 goto done;
5233 } else {
5234 error = got_error(GOT_ERR_NOT_WORKTREE);
5235 goto done;
5239 error = get_worktree_paths_from_argv(&paths, argc, argv,
5240 worktree);
5241 if (error)
5242 goto done;
5244 error = got_object_id_str(&id_str,
5245 got_worktree_get_base_commit_id(worktree));
5246 if (error)
5247 goto done;
5248 arg.repo = repo;
5249 arg.worktree = worktree;
5250 arg.diff_algo = GOT_DIFF_ALGORITHM_PATIENCE;
5251 arg.diff_context = diff_context;
5252 arg.id_str = id_str;
5253 arg.header_shown = 0;
5254 arg.diff_staged = diff_staged;
5255 arg.ignore_whitespace = ignore_whitespace;
5256 arg.force_text_diff = force_text_diff;
5257 arg.diffstat = show_diffstat ? &dsa : NULL;
5258 arg.f1 = f1;
5259 arg.f2 = f2;
5260 arg.outfile = outfile;
5262 error = got_worktree_status(worktree, &paths, repo, 0,
5263 print_diff, &arg, check_cancelled, NULL);
5264 free(id_str);
5265 if (error)
5266 goto done;
5268 if (show_diffstat && dsa.nfiles > 0) {
5269 char *header;
5271 if (asprintf(&header, "diffstat %s%s",
5272 diff_staged ? "-s " : "",
5273 got_worktree_get_root_path(worktree)) == -1) {
5274 error = got_error_from_errno("asprintf");
5275 goto done;
5278 error = print_diffstat(&dsa, header);
5279 free(header);
5280 if (error)
5281 goto done;
5284 error = printfile(outfile);
5285 goto done;
5288 if (ncommit_args == 1) {
5289 struct got_commit_object *commit;
5290 error = got_object_open_as_commit(&commit, repo, ids[0]);
5291 if (error)
5292 goto done;
5294 labels[1] = labels[0];
5295 ids[1] = ids[0];
5296 if (got_object_commit_get_nparents(commit) > 0) {
5297 const struct got_object_id_queue *pids;
5298 struct got_object_qid *pid;
5299 pids = got_object_commit_get_parent_ids(commit);
5300 pid = STAILQ_FIRST(pids);
5301 ids[0] = got_object_id_dup(&pid->id);
5302 if (ids[0] == NULL) {
5303 error = got_error_from_errno(
5304 "got_object_id_dup");
5305 got_object_commit_close(commit);
5306 goto done;
5308 error = got_object_id_str(&labels[0], ids[0]);
5309 if (error) {
5310 got_object_commit_close(commit);
5311 goto done;
5313 } else {
5314 ids[0] = NULL;
5315 labels[0] = strdup("/dev/null");
5316 if (labels[0] == NULL) {
5317 error = got_error_from_errno("strdup");
5318 got_object_commit_close(commit);
5319 goto done;
5323 got_object_commit_close(commit);
5326 if (ncommit_args == 0 && argc > 2) {
5327 error = got_error_msg(GOT_ERR_BAD_PATH,
5328 "path arguments cannot be used when diffing two objects");
5329 goto done;
5332 if (ids[0]) {
5333 error = got_object_get_type(&type1, repo, ids[0]);
5334 if (error)
5335 goto done;
5338 error = got_object_get_type(&type2, repo, ids[1]);
5339 if (error)
5340 goto done;
5341 if (type1 != GOT_OBJ_TYPE_ANY && type1 != type2) {
5342 error = got_error(GOT_ERR_OBJ_TYPE);
5343 goto done;
5345 if (type1 == GOT_OBJ_TYPE_BLOB && argc > 2) {
5346 error = got_error_msg(GOT_ERR_OBJ_TYPE,
5347 "path arguments cannot be used when diffing blobs");
5348 goto done;
5351 for (i = 0; ncommit_args > 0 && i < argc; i++) {
5352 char *in_repo_path;
5353 struct got_pathlist_entry *new;
5354 if (worktree) {
5355 const char *prefix;
5356 char *p;
5357 error = got_worktree_resolve_path(&p, worktree,
5358 argv[i]);
5359 if (error)
5360 goto done;
5361 prefix = got_worktree_get_path_prefix(worktree);
5362 while (prefix[0] == '/')
5363 prefix++;
5364 if (asprintf(&in_repo_path, "%s%s%s", prefix,
5365 (p[0] != '\0' && prefix[0] != '\0') ? "/" : "",
5366 p) == -1) {
5367 error = got_error_from_errno("asprintf");
5368 free(p);
5369 goto done;
5371 free(p);
5372 } else {
5373 char *mapped_path, *s;
5374 error = got_repo_map_path(&mapped_path, repo, argv[i]);
5375 if (error)
5376 goto done;
5377 s = mapped_path;
5378 while (s[0] == '/')
5379 s++;
5380 in_repo_path = strdup(s);
5381 if (in_repo_path == NULL) {
5382 error = got_error_from_errno("asprintf");
5383 free(mapped_path);
5384 goto done;
5386 free(mapped_path);
5389 error = got_pathlist_insert(&new, &paths, in_repo_path, NULL);
5390 if (error || new == NULL /* duplicate */)
5391 free(in_repo_path);
5392 if (error)
5393 goto done;
5396 if (worktree) {
5397 /* Release work tree lock. */
5398 got_worktree_close(worktree);
5399 worktree = NULL;
5402 fd1 = got_opentempfd();
5403 if (fd1 == -1) {
5404 error = got_error_from_errno("got_opentempfd");
5405 goto done;
5408 fd2 = got_opentempfd();
5409 if (fd2 == -1) {
5410 error = got_error_from_errno("got_opentempfd");
5411 goto done;
5414 switch (type1 == GOT_OBJ_TYPE_ANY ? type2 : type1) {
5415 case GOT_OBJ_TYPE_BLOB:
5416 error = got_diff_objects_as_blobs(NULL, NULL, f1, f2,
5417 fd1, fd2, ids[0], ids[1], NULL, NULL,
5418 GOT_DIFF_ALGORITHM_PATIENCE, diff_context,
5419 ignore_whitespace, force_text_diff,
5420 show_diffstat ? &dsa : NULL, repo, outfile);
5421 break;
5422 case GOT_OBJ_TYPE_TREE:
5423 error = got_diff_objects_as_trees(NULL, NULL, f1, f2, fd1, fd2,
5424 ids[0], ids[1], &paths, "", "",
5425 GOT_DIFF_ALGORITHM_PATIENCE, diff_context,
5426 ignore_whitespace, force_text_diff,
5427 show_diffstat ? &dsa : NULL, repo, outfile);
5428 break;
5429 case GOT_OBJ_TYPE_COMMIT:
5430 fprintf(outfile, "diff %s %s\n", labels[0], labels[1]);
5431 error = got_diff_objects_as_commits(NULL, NULL, f1, f2,
5432 fd1, fd2, ids[0], ids[1], &paths,
5433 GOT_DIFF_ALGORITHM_PATIENCE, diff_context,
5434 ignore_whitespace, force_text_diff,
5435 show_diffstat ? &dsa : NULL, repo, outfile);
5436 break;
5437 default:
5438 error = got_error(GOT_ERR_OBJ_TYPE);
5440 if (error)
5441 goto done;
5443 if (show_diffstat && dsa.nfiles > 0) {
5444 char *header = NULL;
5446 if (asprintf(&header, "diffstat %s %s",
5447 labels[0], labels[1]) == -1) {
5448 error = got_error_from_errno("asprintf");
5449 goto done;
5452 error = print_diffstat(&dsa, header);
5453 free(header);
5454 if (error)
5455 goto done;
5458 error = printfile(outfile);
5460 done:
5461 free(labels[0]);
5462 free(labels[1]);
5463 free(ids[0]);
5464 free(ids[1]);
5465 if (worktree)
5466 got_worktree_close(worktree);
5467 if (repo) {
5468 const struct got_error *close_err = got_repo_close(repo);
5469 if (error == NULL)
5470 error = close_err;
5472 if (pack_fds) {
5473 const struct got_error *pack_err =
5474 got_repo_pack_fds_close(pack_fds);
5475 if (error == NULL)
5476 error = pack_err;
5478 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
5479 got_pathlist_free(&diffstat_paths, GOT_PATHLIST_FREE_ALL);
5480 got_ref_list_free(&refs);
5481 if (outfile && fclose(outfile) == EOF && error == NULL)
5482 error = got_error_from_errno("fclose");
5483 if (f1 && fclose(f1) == EOF && error == NULL)
5484 error = got_error_from_errno("fclose");
5485 if (f2 && fclose(f2) == EOF && error == NULL)
5486 error = got_error_from_errno("fclose");
5487 if (fd1 != -1 && close(fd1) == -1 && error == NULL)
5488 error = got_error_from_errno("close");
5489 if (fd2 != -1 && close(fd2) == -1 && error == NULL)
5490 error = got_error_from_errno("close");
5491 return error;
5494 __dead static void
5495 usage_blame(void)
5497 fprintf(stderr,
5498 "usage: %s blame [-c commit] [-r repository-path] path\n",
5499 getprogname());
5500 exit(1);
5503 struct blame_line {
5504 int annotated;
5505 char *id_str;
5506 char *committer;
5507 char datebuf[11]; /* YYYY-MM-DD + NUL */
5510 struct blame_cb_args {
5511 struct blame_line *lines;
5512 int nlines;
5513 int nlines_prec;
5514 int lineno_cur;
5515 off_t *line_offsets;
5516 FILE *f;
5517 struct got_repository *repo;
5520 static const struct got_error *
5521 blame_cb(void *arg, int nlines, int lineno,
5522 struct got_commit_object *commit, struct got_object_id *id)
5524 const struct got_error *err = NULL;
5525 struct blame_cb_args *a = arg;
5526 struct blame_line *bline;
5527 char *line = NULL;
5528 size_t linesize = 0;
5529 off_t offset;
5530 struct tm tm;
5531 time_t committer_time;
5533 if (nlines != a->nlines ||
5534 (lineno != -1 && lineno < 1) || lineno > a->nlines)
5535 return got_error(GOT_ERR_RANGE);
5537 if (sigint_received)
5538 return got_error(GOT_ERR_ITER_COMPLETED);
5540 if (lineno == -1)
5541 return NULL; /* no change in this commit */
5543 /* Annotate this line. */
5544 bline = &a->lines[lineno - 1];
5545 if (bline->annotated)
5546 return NULL;
5547 err = got_object_id_str(&bline->id_str, id);
5548 if (err)
5549 return err;
5551 bline->committer = strdup(got_object_commit_get_committer(commit));
5552 if (bline->committer == NULL) {
5553 err = got_error_from_errno("strdup");
5554 goto done;
5557 committer_time = got_object_commit_get_committer_time(commit);
5558 if (gmtime_r(&committer_time, &tm) == NULL)
5559 return got_error_from_errno("gmtime_r");
5560 if (strftime(bline->datebuf, sizeof(bline->datebuf), "%G-%m-%d",
5561 &tm) == 0) {
5562 err = got_error(GOT_ERR_NO_SPACE);
5563 goto done;
5565 bline->annotated = 1;
5567 /* Print lines annotated so far. */
5568 bline = &a->lines[a->lineno_cur - 1];
5569 if (!bline->annotated)
5570 goto done;
5572 offset = a->line_offsets[a->lineno_cur - 1];
5573 if (fseeko(a->f, offset, SEEK_SET) == -1) {
5574 err = got_error_from_errno("fseeko");
5575 goto done;
5578 while (a->lineno_cur <= a->nlines && bline->annotated) {
5579 char *smallerthan, *at, *nl, *committer;
5580 size_t len;
5582 if (getline(&line, &linesize, a->f) == -1) {
5583 if (ferror(a->f))
5584 err = got_error_from_errno("getline");
5585 break;
5588 committer = bline->committer;
5589 smallerthan = strchr(committer, '<');
5590 if (smallerthan && smallerthan[1] != '\0')
5591 committer = smallerthan + 1;
5592 at = strchr(committer, '@');
5593 if (at)
5594 *at = '\0';
5595 len = strlen(committer);
5596 if (len >= 9)
5597 committer[8] = '\0';
5599 nl = strchr(line, '\n');
5600 if (nl)
5601 *nl = '\0';
5602 printf("%.*d) %.8s %s %-8s %s\n", a->nlines_prec, a->lineno_cur,
5603 bline->id_str, bline->datebuf, committer, line);
5605 a->lineno_cur++;
5606 bline = &a->lines[a->lineno_cur - 1];
5608 done:
5609 free(line);
5610 return err;
5613 static const struct got_error *
5614 cmd_blame(int argc, char *argv[])
5616 const struct got_error *error;
5617 struct got_repository *repo = NULL;
5618 struct got_worktree *worktree = NULL;
5619 char *path, *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
5620 char *link_target = NULL;
5621 struct got_object_id *obj_id = NULL;
5622 struct got_object_id *commit_id = NULL;
5623 struct got_commit_object *commit = NULL;
5624 struct got_blob_object *blob = NULL;
5625 char *commit_id_str = NULL;
5626 struct blame_cb_args bca;
5627 int ch, obj_type, i, fd1 = -1, fd2 = -1, fd3 = -1;
5628 off_t filesize;
5629 int *pack_fds = NULL;
5630 FILE *f1 = NULL, *f2 = NULL;
5632 fd1 = got_opentempfd();
5633 if (fd1 == -1)
5634 return got_error_from_errno("got_opentempfd");
5636 memset(&bca, 0, sizeof(bca));
5638 #ifndef PROFILE
5639 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
5640 NULL) == -1)
5641 err(1, "pledge");
5642 #endif
5644 while ((ch = getopt(argc, argv, "c:r:")) != -1) {
5645 switch (ch) {
5646 case 'c':
5647 commit_id_str = optarg;
5648 break;
5649 case 'r':
5650 repo_path = realpath(optarg, NULL);
5651 if (repo_path == NULL)
5652 return got_error_from_errno2("realpath",
5653 optarg);
5654 got_path_strip_trailing_slashes(repo_path);
5655 break;
5656 default:
5657 usage_blame();
5658 /* NOTREACHED */
5662 argc -= optind;
5663 argv += optind;
5665 if (argc == 1)
5666 path = argv[0];
5667 else
5668 usage_blame();
5670 cwd = getcwd(NULL, 0);
5671 if (cwd == NULL) {
5672 error = got_error_from_errno("getcwd");
5673 goto done;
5676 error = got_repo_pack_fds_open(&pack_fds);
5677 if (error != NULL)
5678 goto done;
5680 if (repo_path == NULL) {
5681 error = got_worktree_open(&worktree, cwd);
5682 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5683 goto done;
5684 else
5685 error = NULL;
5686 if (worktree) {
5687 repo_path =
5688 strdup(got_worktree_get_repo_path(worktree));
5689 if (repo_path == NULL) {
5690 error = got_error_from_errno("strdup");
5691 if (error)
5692 goto done;
5694 } else {
5695 repo_path = strdup(cwd);
5696 if (repo_path == NULL) {
5697 error = got_error_from_errno("strdup");
5698 goto done;
5703 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
5704 if (error != NULL)
5705 goto done;
5707 if (worktree) {
5708 const char *prefix = got_worktree_get_path_prefix(worktree);
5709 char *p;
5711 error = got_worktree_resolve_path(&p, worktree, path);
5712 if (error)
5713 goto done;
5714 if (asprintf(&in_repo_path, "%s%s%s", prefix,
5715 (p[0] != '\0' && !got_path_is_root_dir(prefix)) ? "/" : "",
5716 p) == -1) {
5717 error = got_error_from_errno("asprintf");
5718 free(p);
5719 goto done;
5721 free(p);
5722 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5723 } else {
5724 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5725 if (error)
5726 goto done;
5727 error = got_repo_map_path(&in_repo_path, repo, path);
5729 if (error)
5730 goto done;
5732 if (commit_id_str == NULL) {
5733 struct got_reference *head_ref;
5734 error = got_ref_open(&head_ref, repo, worktree ?
5735 got_worktree_get_head_ref_name(worktree) : GOT_REF_HEAD, 0);
5736 if (error != NULL)
5737 goto done;
5738 error = got_ref_resolve(&commit_id, repo, head_ref);
5739 got_ref_close(head_ref);
5740 if (error != NULL)
5741 goto done;
5742 } else {
5743 struct got_reflist_head refs;
5744 TAILQ_INIT(&refs);
5745 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
5746 NULL);
5747 if (error)
5748 goto done;
5749 error = got_repo_match_object_id(&commit_id, NULL,
5750 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
5751 got_ref_list_free(&refs);
5752 if (error)
5753 goto done;
5756 if (worktree) {
5757 /* Release work tree lock. */
5758 got_worktree_close(worktree);
5759 worktree = NULL;
5762 error = got_object_open_as_commit(&commit, repo, commit_id);
5763 if (error)
5764 goto done;
5766 error = got_object_resolve_symlinks(&link_target, in_repo_path,
5767 commit, repo);
5768 if (error)
5769 goto done;
5771 error = got_object_id_by_path(&obj_id, repo, commit,
5772 link_target ? link_target : in_repo_path);
5773 if (error)
5774 goto done;
5776 error = got_object_get_type(&obj_type, repo, obj_id);
5777 if (error)
5778 goto done;
5780 if (obj_type != GOT_OBJ_TYPE_BLOB) {
5781 error = got_error_path(link_target ? link_target : in_repo_path,
5782 GOT_ERR_OBJ_TYPE);
5783 goto done;
5786 error = got_object_open_as_blob(&blob, repo, obj_id, 8192, fd1);
5787 if (error)
5788 goto done;
5789 bca.f = got_opentemp();
5790 if (bca.f == NULL) {
5791 error = got_error_from_errno("got_opentemp");
5792 goto done;
5794 error = got_object_blob_dump_to_file(&filesize, &bca.nlines,
5795 &bca.line_offsets, bca.f, blob);
5796 if (error || bca.nlines == 0)
5797 goto done;
5799 /* Don't include \n at EOF in the blame line count. */
5800 if (bca.line_offsets[bca.nlines - 1] == filesize)
5801 bca.nlines--;
5803 bca.lines = calloc(bca.nlines, sizeof(*bca.lines));
5804 if (bca.lines == NULL) {
5805 error = got_error_from_errno("calloc");
5806 goto done;
5808 bca.lineno_cur = 1;
5809 bca.nlines_prec = 0;
5810 i = bca.nlines;
5811 while (i > 0) {
5812 i /= 10;
5813 bca.nlines_prec++;
5815 bca.repo = repo;
5817 fd2 = got_opentempfd();
5818 if (fd2 == -1) {
5819 error = got_error_from_errno("got_opentempfd");
5820 goto done;
5822 fd3 = got_opentempfd();
5823 if (fd3 == -1) {
5824 error = got_error_from_errno("got_opentempfd");
5825 goto done;
5827 f1 = got_opentemp();
5828 if (f1 == NULL) {
5829 error = got_error_from_errno("got_opentemp");
5830 goto done;
5832 f2 = got_opentemp();
5833 if (f2 == NULL) {
5834 error = got_error_from_errno("got_opentemp");
5835 goto done;
5837 error = got_blame(link_target ? link_target : in_repo_path, commit_id,
5838 repo, GOT_DIFF_ALGORITHM_PATIENCE, blame_cb, &bca,
5839 check_cancelled, NULL, fd2, fd3, f1, f2);
5840 done:
5841 free(in_repo_path);
5842 free(link_target);
5843 free(repo_path);
5844 free(cwd);
5845 free(commit_id);
5846 free(obj_id);
5847 if (commit)
5848 got_object_commit_close(commit);
5850 if (fd1 != -1 && close(fd1) == -1 && error == NULL)
5851 error = got_error_from_errno("close");
5852 if (fd2 != -1 && close(fd2) == -1 && error == NULL)
5853 error = got_error_from_errno("close");
5854 if (fd3 != -1 && close(fd3) == -1 && error == NULL)
5855 error = got_error_from_errno("close");
5856 if (f1 && fclose(f1) == EOF && error == NULL)
5857 error = got_error_from_errno("fclose");
5858 if (f2 && fclose(f2) == EOF && error == NULL)
5859 error = got_error_from_errno("fclose");
5861 if (blob)
5862 got_object_blob_close(blob);
5863 if (worktree)
5864 got_worktree_close(worktree);
5865 if (repo) {
5866 const struct got_error *close_err = got_repo_close(repo);
5867 if (error == NULL)
5868 error = close_err;
5870 if (pack_fds) {
5871 const struct got_error *pack_err =
5872 got_repo_pack_fds_close(pack_fds);
5873 if (error == NULL)
5874 error = pack_err;
5876 if (bca.lines) {
5877 for (i = 0; i < bca.nlines; i++) {
5878 struct blame_line *bline = &bca.lines[i];
5879 free(bline->id_str);
5880 free(bline->committer);
5882 free(bca.lines);
5884 free(bca.line_offsets);
5885 if (bca.f && fclose(bca.f) == EOF && error == NULL)
5886 error = got_error_from_errno("fclose");
5887 return error;
5890 __dead static void
5891 usage_tree(void)
5893 fprintf(stderr, "usage: %s tree [-iR] [-c commit] [-r repository-path] "
5894 "[path]\n", getprogname());
5895 exit(1);
5898 static const struct got_error *
5899 print_entry(struct got_tree_entry *te, const char *id, const char *path,
5900 const char *root_path, struct got_repository *repo)
5902 const struct got_error *err = NULL;
5903 int is_root_path = (strcmp(path, root_path) == 0);
5904 const char *modestr = "";
5905 mode_t mode = got_tree_entry_get_mode(te);
5906 char *link_target = NULL;
5908 path += strlen(root_path);
5909 while (path[0] == '/')
5910 path++;
5912 if (got_object_tree_entry_is_submodule(te))
5913 modestr = "$";
5914 else if (S_ISLNK(mode)) {
5915 int i;
5917 err = got_tree_entry_get_symlink_target(&link_target, te, repo);
5918 if (err)
5919 return err;
5920 for (i = 0; i < strlen(link_target); i++) {
5921 if (!isprint((unsigned char)link_target[i]))
5922 link_target[i] = '?';
5925 modestr = "@";
5927 else if (S_ISDIR(mode))
5928 modestr = "/";
5929 else if (mode & S_IXUSR)
5930 modestr = "*";
5932 printf("%s%s%s%s%s%s%s\n", id ? id : "", path,
5933 is_root_path ? "" : "/", got_tree_entry_get_name(te), modestr,
5934 link_target ? " -> ": "", link_target ? link_target : "");
5936 free(link_target);
5937 return NULL;
5940 static const struct got_error *
5941 print_tree(const char *path, struct got_commit_object *commit,
5942 int show_ids, int recurse, const char *root_path,
5943 struct got_repository *repo)
5945 const struct got_error *err = NULL;
5946 struct got_object_id *tree_id = NULL;
5947 struct got_tree_object *tree = NULL;
5948 int nentries, i;
5950 err = got_object_id_by_path(&tree_id, repo, commit, path);
5951 if (err)
5952 goto done;
5954 err = got_object_open_as_tree(&tree, repo, tree_id);
5955 if (err)
5956 goto done;
5957 nentries = got_object_tree_get_nentries(tree);
5958 for (i = 0; i < nentries; i++) {
5959 struct got_tree_entry *te;
5960 char *id = NULL;
5962 if (sigint_received || sigpipe_received)
5963 break;
5965 te = got_object_tree_get_entry(tree, i);
5966 if (show_ids) {
5967 char *id_str;
5968 err = got_object_id_str(&id_str,
5969 got_tree_entry_get_id(te));
5970 if (err)
5971 goto done;
5972 if (asprintf(&id, "%s ", id_str) == -1) {
5973 err = got_error_from_errno("asprintf");
5974 free(id_str);
5975 goto done;
5977 free(id_str);
5979 err = print_entry(te, id, path, root_path, repo);
5980 free(id);
5981 if (err)
5982 goto done;
5984 if (recurse && S_ISDIR(got_tree_entry_get_mode(te))) {
5985 char *child_path;
5986 if (asprintf(&child_path, "%s%s%s", path,
5987 path[0] == '/' && path[1] == '\0' ? "" : "/",
5988 got_tree_entry_get_name(te)) == -1) {
5989 err = got_error_from_errno("asprintf");
5990 goto done;
5992 err = print_tree(child_path, commit, show_ids, 1,
5993 root_path, repo);
5994 free(child_path);
5995 if (err)
5996 goto done;
5999 done:
6000 if (tree)
6001 got_object_tree_close(tree);
6002 free(tree_id);
6003 return err;
6006 static const struct got_error *
6007 cmd_tree(int argc, char *argv[])
6009 const struct got_error *error;
6010 struct got_repository *repo = NULL;
6011 struct got_worktree *worktree = NULL;
6012 const char *path, *refname = NULL;
6013 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
6014 struct got_object_id *commit_id = NULL;
6015 struct got_commit_object *commit = NULL;
6016 char *commit_id_str = NULL;
6017 int show_ids = 0, recurse = 0;
6018 int ch;
6019 int *pack_fds = NULL;
6021 #ifndef PROFILE
6022 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
6023 NULL) == -1)
6024 err(1, "pledge");
6025 #endif
6027 while ((ch = getopt(argc, argv, "c:iRr:")) != -1) {
6028 switch (ch) {
6029 case 'c':
6030 commit_id_str = optarg;
6031 break;
6032 case 'i':
6033 show_ids = 1;
6034 break;
6035 case 'R':
6036 recurse = 1;
6037 break;
6038 case 'r':
6039 repo_path = realpath(optarg, NULL);
6040 if (repo_path == NULL)
6041 return got_error_from_errno2("realpath",
6042 optarg);
6043 got_path_strip_trailing_slashes(repo_path);
6044 break;
6045 default:
6046 usage_tree();
6047 /* NOTREACHED */
6051 argc -= optind;
6052 argv += optind;
6054 if (argc == 1)
6055 path = argv[0];
6056 else if (argc > 1)
6057 usage_tree();
6058 else
6059 path = NULL;
6061 cwd = getcwd(NULL, 0);
6062 if (cwd == NULL) {
6063 error = got_error_from_errno("getcwd");
6064 goto done;
6067 error = got_repo_pack_fds_open(&pack_fds);
6068 if (error != NULL)
6069 goto done;
6071 if (repo_path == NULL) {
6072 error = got_worktree_open(&worktree, cwd);
6073 if (error && error->code != GOT_ERR_NOT_WORKTREE)
6074 goto done;
6075 else
6076 error = NULL;
6077 if (worktree) {
6078 repo_path =
6079 strdup(got_worktree_get_repo_path(worktree));
6080 if (repo_path == NULL)
6081 error = got_error_from_errno("strdup");
6082 if (error)
6083 goto done;
6084 } else {
6085 repo_path = strdup(cwd);
6086 if (repo_path == NULL) {
6087 error = got_error_from_errno("strdup");
6088 goto done;
6093 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
6094 if (error != NULL)
6095 goto done;
6097 if (worktree) {
6098 const char *prefix = got_worktree_get_path_prefix(worktree);
6099 char *p;
6101 if (path == NULL)
6102 path = "";
6103 error = got_worktree_resolve_path(&p, worktree, path);
6104 if (error)
6105 goto done;
6106 if (asprintf(&in_repo_path, "%s%s%s", prefix,
6107 (p[0] != '\0' && !got_path_is_root_dir(prefix)) ? "/" : "",
6108 p) == -1) {
6109 error = got_error_from_errno("asprintf");
6110 free(p);
6111 goto done;
6113 free(p);
6114 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
6115 if (error)
6116 goto done;
6117 } else {
6118 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
6119 if (error)
6120 goto done;
6121 if (path == NULL)
6122 path = "/";
6123 error = got_repo_map_path(&in_repo_path, repo, path);
6124 if (error != NULL)
6125 goto done;
6128 if (commit_id_str == NULL) {
6129 struct got_reference *head_ref;
6130 if (worktree)
6131 refname = got_worktree_get_head_ref_name(worktree);
6132 else
6133 refname = GOT_REF_HEAD;
6134 error = got_ref_open(&head_ref, repo, refname, 0);
6135 if (error != NULL)
6136 goto done;
6137 error = got_ref_resolve(&commit_id, repo, head_ref);
6138 got_ref_close(head_ref);
6139 if (error != NULL)
6140 goto done;
6141 } else {
6142 struct got_reflist_head refs;
6143 TAILQ_INIT(&refs);
6144 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
6145 NULL);
6146 if (error)
6147 goto done;
6148 error = got_repo_match_object_id(&commit_id, NULL,
6149 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
6150 got_ref_list_free(&refs);
6151 if (error)
6152 goto done;
6155 if (worktree) {
6156 /* Release work tree lock. */
6157 got_worktree_close(worktree);
6158 worktree = NULL;
6161 error = got_object_open_as_commit(&commit, repo, commit_id);
6162 if (error)
6163 goto done;
6165 error = print_tree(in_repo_path, commit, show_ids, recurse,
6166 in_repo_path, repo);
6167 done:
6168 free(in_repo_path);
6169 free(repo_path);
6170 free(cwd);
6171 free(commit_id);
6172 if (commit)
6173 got_object_commit_close(commit);
6174 if (worktree)
6175 got_worktree_close(worktree);
6176 if (repo) {
6177 const struct got_error *close_err = got_repo_close(repo);
6178 if (error == NULL)
6179 error = close_err;
6181 if (pack_fds) {
6182 const struct got_error *pack_err =
6183 got_repo_pack_fds_close(pack_fds);
6184 if (error == NULL)
6185 error = pack_err;
6187 return error;
6190 __dead static void
6191 usage_status(void)
6193 fprintf(stderr, "usage: %s status [-I] [-S status-codes] "
6194 "[-s status-codes] [path ...]\n", getprogname());
6195 exit(1);
6198 struct got_status_arg {
6199 char *status_codes;
6200 int suppress;
6203 static const struct got_error *
6204 print_status(void *arg, unsigned char status, unsigned char staged_status,
6205 const char *path, struct got_object_id *blob_id,
6206 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
6207 int dirfd, const char *de_name)
6209 struct got_status_arg *st = arg;
6211 if (status == staged_status && (status == GOT_STATUS_DELETE))
6212 status = GOT_STATUS_NO_CHANGE;
6213 if (st != NULL && st->status_codes) {
6214 size_t ncodes = strlen(st->status_codes);
6215 int i, j = 0;
6217 for (i = 0; i < ncodes ; i++) {
6218 if (st->suppress) {
6219 if (status == st->status_codes[i] ||
6220 staged_status == st->status_codes[i]) {
6221 j++;
6222 continue;
6224 } else {
6225 if (status == st->status_codes[i] ||
6226 staged_status == st->status_codes[i])
6227 break;
6231 if (st->suppress && j == 0)
6232 goto print;
6234 if (i == ncodes)
6235 return NULL;
6237 print:
6238 printf("%c%c %s\n", status, staged_status, path);
6239 return NULL;
6242 static const struct got_error *
6243 cmd_status(int argc, char *argv[])
6245 const struct got_error *error = NULL;
6246 struct got_repository *repo = NULL;
6247 struct got_worktree *worktree = NULL;
6248 struct got_status_arg st;
6249 char *cwd = NULL;
6250 struct got_pathlist_head paths;
6251 int ch, i, no_ignores = 0;
6252 int *pack_fds = NULL;
6254 TAILQ_INIT(&paths);
6256 memset(&st, 0, sizeof(st));
6257 st.status_codes = NULL;
6258 st.suppress = 0;
6260 while ((ch = getopt(argc, argv, "IS:s:")) != -1) {
6261 switch (ch) {
6262 case 'I':
6263 no_ignores = 1;
6264 break;
6265 case 'S':
6266 if (st.status_codes != NULL && st.suppress == 0)
6267 option_conflict('S', 's');
6268 st.suppress = 1;
6269 /* fallthrough */
6270 case 's':
6271 for (i = 0; i < strlen(optarg); i++) {
6272 switch (optarg[i]) {
6273 case GOT_STATUS_MODIFY:
6274 case GOT_STATUS_ADD:
6275 case GOT_STATUS_DELETE:
6276 case GOT_STATUS_CONFLICT:
6277 case GOT_STATUS_MISSING:
6278 case GOT_STATUS_OBSTRUCTED:
6279 case GOT_STATUS_UNVERSIONED:
6280 case GOT_STATUS_MODE_CHANGE:
6281 case GOT_STATUS_NONEXISTENT:
6282 break;
6283 default:
6284 errx(1, "invalid status code '%c'",
6285 optarg[i]);
6288 if (ch == 's' && st.suppress)
6289 option_conflict('s', 'S');
6290 st.status_codes = optarg;
6291 break;
6292 default:
6293 usage_status();
6294 /* NOTREACHED */
6298 argc -= optind;
6299 argv += optind;
6301 #ifndef PROFILE
6302 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
6303 NULL) == -1)
6304 err(1, "pledge");
6305 #endif
6306 cwd = getcwd(NULL, 0);
6307 if (cwd == NULL) {
6308 error = got_error_from_errno("getcwd");
6309 goto done;
6312 error = got_repo_pack_fds_open(&pack_fds);
6313 if (error != NULL)
6314 goto done;
6316 error = got_worktree_open(&worktree, cwd);
6317 if (error) {
6318 if (error->code == GOT_ERR_NOT_WORKTREE)
6319 error = wrap_not_worktree_error(error, "status", cwd);
6320 goto done;
6323 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
6324 NULL, pack_fds);
6325 if (error != NULL)
6326 goto done;
6328 error = apply_unveil(got_repo_get_path(repo), 1,
6329 got_worktree_get_root_path(worktree));
6330 if (error)
6331 goto done;
6333 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
6334 if (error)
6335 goto done;
6337 error = got_worktree_status(worktree, &paths, repo, no_ignores,
6338 print_status, &st, check_cancelled, NULL);
6339 done:
6340 if (pack_fds) {
6341 const struct got_error *pack_err =
6342 got_repo_pack_fds_close(pack_fds);
6343 if (error == NULL)
6344 error = pack_err;
6347 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
6348 free(cwd);
6349 return error;
6352 __dead static void
6353 usage_ref(void)
6355 fprintf(stderr, "usage: %s ref [-dlt] [-c object] [-r repository-path] "
6356 "[-s reference] [name]\n", getprogname());
6357 exit(1);
6360 static const struct got_error *
6361 list_refs(struct got_repository *repo, const char *refname, int sort_by_time)
6363 static const struct got_error *err = NULL;
6364 struct got_reflist_head refs;
6365 struct got_reflist_entry *re;
6367 TAILQ_INIT(&refs);
6368 err = got_ref_list(&refs, repo, refname, sort_by_time ?
6369 got_ref_cmp_by_commit_timestamp_descending : got_ref_cmp_by_name,
6370 repo);
6371 if (err)
6372 return err;
6374 TAILQ_FOREACH(re, &refs, entry) {
6375 char *refstr;
6376 refstr = got_ref_to_str(re->ref);
6377 if (refstr == NULL) {
6378 err = got_error_from_errno("got_ref_to_str");
6379 break;
6381 printf("%s: %s\n", got_ref_get_name(re->ref), refstr);
6382 free(refstr);
6385 got_ref_list_free(&refs);
6386 return err;
6389 static const struct got_error *
6390 delete_ref_by_name(struct got_repository *repo, const char *refname)
6392 const struct got_error *err;
6393 struct got_reference *ref;
6395 err = got_ref_open(&ref, repo, refname, 0);
6396 if (err)
6397 return err;
6399 err = delete_ref(repo, ref);
6400 got_ref_close(ref);
6401 return err;
6404 static const struct got_error *
6405 add_ref(struct got_repository *repo, const char *refname, const char *target)
6407 const struct got_error *err = NULL;
6408 struct got_object_id *id = NULL;
6409 struct got_reference *ref = NULL;
6410 struct got_reflist_head refs;
6413 * Don't let the user create a reference name with a leading '-'.
6414 * While technically a valid reference name, this case is usually
6415 * an unintended typo.
6417 if (refname[0] == '-')
6418 return got_error_path(refname, GOT_ERR_REF_NAME_MINUS);
6420 TAILQ_INIT(&refs);
6421 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
6422 if (err)
6423 goto done;
6424 err = got_repo_match_object_id(&id, NULL, target, GOT_OBJ_TYPE_ANY,
6425 &refs, repo);
6426 got_ref_list_free(&refs);
6427 if (err)
6428 goto done;
6430 err = got_ref_alloc(&ref, refname, id);
6431 if (err)
6432 goto done;
6434 err = got_ref_write(ref, repo);
6435 done:
6436 if (ref)
6437 got_ref_close(ref);
6438 free(id);
6439 return err;
6442 static const struct got_error *
6443 add_symref(struct got_repository *repo, const char *refname, const char *target)
6445 const struct got_error *err = NULL;
6446 struct got_reference *ref = NULL;
6447 struct got_reference *target_ref = NULL;
6450 * Don't let the user create a reference name with a leading '-'.
6451 * While technically a valid reference name, this case is usually
6452 * an unintended typo.
6454 if (refname[0] == '-')
6455 return got_error_path(refname, GOT_ERR_REF_NAME_MINUS);
6457 err = got_ref_open(&target_ref, repo, target, 0);
6458 if (err)
6459 return err;
6461 err = got_ref_alloc_symref(&ref, refname, target_ref);
6462 if (err)
6463 goto done;
6465 err = got_ref_write(ref, repo);
6466 done:
6467 if (target_ref)
6468 got_ref_close(target_ref);
6469 if (ref)
6470 got_ref_close(ref);
6471 return err;
6474 static const struct got_error *
6475 cmd_ref(int argc, char *argv[])
6477 const struct got_error *error = NULL;
6478 struct got_repository *repo = NULL;
6479 struct got_worktree *worktree = NULL;
6480 char *cwd = NULL, *repo_path = NULL;
6481 int ch, do_list = 0, do_delete = 0, sort_by_time = 0;
6482 const char *obj_arg = NULL, *symref_target= NULL;
6483 char *refname = NULL;
6484 int *pack_fds = NULL;
6486 while ((ch = getopt(argc, argv, "c:dlr:s:t")) != -1) {
6487 switch (ch) {
6488 case 'c':
6489 obj_arg = optarg;
6490 break;
6491 case 'd':
6492 do_delete = 1;
6493 break;
6494 case 'l':
6495 do_list = 1;
6496 break;
6497 case 'r':
6498 repo_path = realpath(optarg, NULL);
6499 if (repo_path == NULL)
6500 return got_error_from_errno2("realpath",
6501 optarg);
6502 got_path_strip_trailing_slashes(repo_path);
6503 break;
6504 case 's':
6505 symref_target = optarg;
6506 break;
6507 case 't':
6508 sort_by_time = 1;
6509 break;
6510 default:
6511 usage_ref();
6512 /* NOTREACHED */
6516 if (obj_arg && do_list)
6517 option_conflict('c', 'l');
6518 if (obj_arg && do_delete)
6519 option_conflict('c', 'd');
6520 if (obj_arg && symref_target)
6521 option_conflict('c', 's');
6522 if (symref_target && do_delete)
6523 option_conflict('s', 'd');
6524 if (symref_target && do_list)
6525 option_conflict('s', 'l');
6526 if (do_delete && do_list)
6527 option_conflict('d', 'l');
6528 if (sort_by_time && !do_list)
6529 errx(1, "-t option requires -l option");
6531 argc -= optind;
6532 argv += optind;
6534 if (do_list) {
6535 if (argc != 0 && argc != 1)
6536 usage_ref();
6537 if (argc == 1) {
6538 refname = strdup(argv[0]);
6539 if (refname == NULL) {
6540 error = got_error_from_errno("strdup");
6541 goto done;
6544 } else {
6545 if (argc != 1)
6546 usage_ref();
6547 refname = strdup(argv[0]);
6548 if (refname == NULL) {
6549 error = got_error_from_errno("strdup");
6550 goto done;
6554 if (refname)
6555 got_path_strip_trailing_slashes(refname);
6557 #ifndef PROFILE
6558 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
6559 "sendfd unveil", NULL) == -1)
6560 err(1, "pledge");
6561 #endif
6562 cwd = getcwd(NULL, 0);
6563 if (cwd == NULL) {
6564 error = got_error_from_errno("getcwd");
6565 goto done;
6568 error = got_repo_pack_fds_open(&pack_fds);
6569 if (error != NULL)
6570 goto done;
6572 if (repo_path == NULL) {
6573 error = got_worktree_open(&worktree, cwd);
6574 if (error && error->code != GOT_ERR_NOT_WORKTREE)
6575 goto done;
6576 else
6577 error = NULL;
6578 if (worktree) {
6579 repo_path =
6580 strdup(got_worktree_get_repo_path(worktree));
6581 if (repo_path == NULL)
6582 error = got_error_from_errno("strdup");
6583 if (error)
6584 goto done;
6585 } else {
6586 repo_path = strdup(cwd);
6587 if (repo_path == NULL) {
6588 error = got_error_from_errno("strdup");
6589 goto done;
6594 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
6595 if (error != NULL)
6596 goto done;
6598 #ifndef PROFILE
6599 if (do_list) {
6600 /* Remove "cpath" promise. */
6601 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
6602 NULL) == -1)
6603 err(1, "pledge");
6605 #endif
6607 error = apply_unveil(got_repo_get_path(repo), do_list,
6608 worktree ? got_worktree_get_root_path(worktree) : NULL);
6609 if (error)
6610 goto done;
6612 if (do_list)
6613 error = list_refs(repo, refname, sort_by_time);
6614 else if (do_delete)
6615 error = delete_ref_by_name(repo, refname);
6616 else if (symref_target)
6617 error = add_symref(repo, refname, symref_target);
6618 else {
6619 if (obj_arg == NULL)
6620 usage_ref();
6621 error = add_ref(repo, refname, obj_arg);
6623 done:
6624 free(refname);
6625 if (repo) {
6626 const struct got_error *close_err = got_repo_close(repo);
6627 if (error == NULL)
6628 error = close_err;
6630 if (worktree)
6631 got_worktree_close(worktree);
6632 if (pack_fds) {
6633 const struct got_error *pack_err =
6634 got_repo_pack_fds_close(pack_fds);
6635 if (error == NULL)
6636 error = pack_err;
6638 free(cwd);
6639 free(repo_path);
6640 return error;
6643 __dead static void
6644 usage_branch(void)
6646 fprintf(stderr, "usage: %s branch [-lnt] [-c commit] [-d name] "
6647 "[-r repository-path] [name]\n", getprogname());
6648 exit(1);
6651 static const struct got_error *
6652 list_branch(struct got_repository *repo, struct got_worktree *worktree,
6653 struct got_reference *ref)
6655 const struct got_error *err = NULL;
6656 const char *refname, *marker = " ";
6657 char *refstr;
6659 refname = got_ref_get_name(ref);
6660 if (worktree && strcmp(refname,
6661 got_worktree_get_head_ref_name(worktree)) == 0) {
6662 struct got_object_id *id = NULL;
6664 err = got_ref_resolve(&id, repo, ref);
6665 if (err)
6666 return err;
6667 if (got_object_id_cmp(id,
6668 got_worktree_get_base_commit_id(worktree)) == 0)
6669 marker = "* ";
6670 else
6671 marker = "~ ";
6672 free(id);
6675 if (strncmp(refname, "refs/heads/", 11) == 0)
6676 refname += 11;
6677 if (strncmp(refname, "refs/got/worktree/", 18) == 0)
6678 refname += 18;
6679 if (strncmp(refname, "refs/remotes/", 13) == 0)
6680 refname += 13;
6682 refstr = got_ref_to_str(ref);
6683 if (refstr == NULL)
6684 return got_error_from_errno("got_ref_to_str");
6686 printf("%s%s: %s\n", marker, refname, refstr);
6687 free(refstr);
6688 return NULL;
6691 static const struct got_error *
6692 show_current_branch(struct got_repository *repo, struct got_worktree *worktree)
6694 const char *refname;
6696 if (worktree == NULL)
6697 return got_error(GOT_ERR_NOT_WORKTREE);
6699 refname = got_worktree_get_head_ref_name(worktree);
6701 if (strncmp(refname, "refs/heads/", 11) == 0)
6702 refname += 11;
6703 if (strncmp(refname, "refs/got/worktree/", 18) == 0)
6704 refname += 18;
6706 printf("%s\n", refname);
6708 return NULL;
6711 static const struct got_error *
6712 list_branches(struct got_repository *repo, struct got_worktree *worktree,
6713 int sort_by_time)
6715 static const struct got_error *err = NULL;
6716 struct got_reflist_head refs;
6717 struct got_reflist_entry *re;
6718 struct got_reference *temp_ref = NULL;
6719 int rebase_in_progress, histedit_in_progress;
6721 TAILQ_INIT(&refs);
6723 if (worktree) {
6724 err = got_worktree_rebase_in_progress(&rebase_in_progress,
6725 worktree);
6726 if (err)
6727 return err;
6729 err = got_worktree_histedit_in_progress(&histedit_in_progress,
6730 worktree);
6731 if (err)
6732 return err;
6734 if (rebase_in_progress || histedit_in_progress) {
6735 err = got_ref_open(&temp_ref, repo,
6736 got_worktree_get_head_ref_name(worktree), 0);
6737 if (err)
6738 return err;
6739 list_branch(repo, worktree, temp_ref);
6740 got_ref_close(temp_ref);
6744 err = got_ref_list(&refs, repo, "refs/heads", sort_by_time ?
6745 got_ref_cmp_by_commit_timestamp_descending : got_ref_cmp_by_name,
6746 repo);
6747 if (err)
6748 return err;
6750 TAILQ_FOREACH(re, &refs, entry)
6751 list_branch(repo, worktree, re->ref);
6753 got_ref_list_free(&refs);
6755 err = got_ref_list(&refs, repo, "refs/remotes", sort_by_time ?
6756 got_ref_cmp_by_commit_timestamp_descending : got_ref_cmp_by_name,
6757 repo);
6758 if (err)
6759 return err;
6761 TAILQ_FOREACH(re, &refs, entry)
6762 list_branch(repo, worktree, re->ref);
6764 got_ref_list_free(&refs);
6766 return NULL;
6769 static const struct got_error *
6770 delete_branch(struct got_repository *repo, struct got_worktree *worktree,
6771 const char *branch_name)
6773 const struct got_error *err = NULL;
6774 struct got_reference *ref = NULL;
6775 char *refname, *remote_refname = NULL;
6777 if (strncmp(branch_name, "refs/", 5) == 0)
6778 branch_name += 5;
6779 if (strncmp(branch_name, "heads/", 6) == 0)
6780 branch_name += 6;
6781 else if (strncmp(branch_name, "remotes/", 8) == 0)
6782 branch_name += 8;
6784 if (asprintf(&refname, "refs/heads/%s", branch_name) == -1)
6785 return got_error_from_errno("asprintf");
6787 if (asprintf(&remote_refname, "refs/remotes/%s",
6788 branch_name) == -1) {
6789 err = got_error_from_errno("asprintf");
6790 goto done;
6793 err = got_ref_open(&ref, repo, refname, 0);
6794 if (err) {
6795 const struct got_error *err2;
6796 if (err->code != GOT_ERR_NOT_REF)
6797 goto done;
6799 * Keep 'err' intact such that if neither branch exists
6800 * we report "refs/heads" rather than "refs/remotes" in
6801 * our error message.
6803 err2 = got_ref_open(&ref, repo, remote_refname, 0);
6804 if (err2)
6805 goto done;
6806 err = NULL;
6809 if (worktree &&
6810 strcmp(got_worktree_get_head_ref_name(worktree),
6811 got_ref_get_name(ref)) == 0) {
6812 err = got_error_msg(GOT_ERR_SAME_BRANCH,
6813 "will not delete this work tree's current branch");
6814 goto done;
6817 err = delete_ref(repo, ref);
6818 done:
6819 if (ref)
6820 got_ref_close(ref);
6821 free(refname);
6822 free(remote_refname);
6823 return err;
6826 static const struct got_error *
6827 add_branch(struct got_repository *repo, const char *branch_name,
6828 struct got_object_id *base_commit_id)
6830 const struct got_error *err = NULL;
6831 struct got_reference *ref = NULL;
6832 char *refname = NULL;
6835 * Don't let the user create a branch name with a leading '-'.
6836 * While technically a valid reference name, this case is usually
6837 * an unintended typo.
6839 if (branch_name[0] == '-')
6840 return got_error_path(branch_name, GOT_ERR_REF_NAME_MINUS);
6842 if (strncmp(branch_name, "refs/heads/", 11) == 0)
6843 branch_name += 11;
6845 if (asprintf(&refname, "refs/heads/%s", branch_name) == -1) {
6846 err = got_error_from_errno("asprintf");
6847 goto done;
6850 err = got_ref_open(&ref, repo, refname, 0);
6851 if (err == NULL) {
6852 err = got_error(GOT_ERR_BRANCH_EXISTS);
6853 goto done;
6854 } else if (err->code != GOT_ERR_NOT_REF)
6855 goto done;
6857 err = got_ref_alloc(&ref, refname, base_commit_id);
6858 if (err)
6859 goto done;
6861 err = got_ref_write(ref, repo);
6862 done:
6863 if (ref)
6864 got_ref_close(ref);
6865 free(refname);
6866 return err;
6869 static const struct got_error *
6870 cmd_branch(int argc, char *argv[])
6872 const struct got_error *error = NULL;
6873 struct got_repository *repo = NULL;
6874 struct got_worktree *worktree = NULL;
6875 char *cwd = NULL, *repo_path = NULL;
6876 int ch, do_list = 0, do_show = 0, do_update = 1, sort_by_time = 0;
6877 const char *delref = NULL, *commit_id_arg = NULL;
6878 struct got_reference *ref = NULL;
6879 struct got_pathlist_head paths;
6880 struct got_object_id *commit_id = NULL;
6881 char *commit_id_str = NULL;
6882 int *pack_fds = NULL;
6884 TAILQ_INIT(&paths);
6886 while ((ch = getopt(argc, argv, "c:d:lnr:t")) != -1) {
6887 switch (ch) {
6888 case 'c':
6889 commit_id_arg = optarg;
6890 break;
6891 case 'd':
6892 delref = optarg;
6893 break;
6894 case 'l':
6895 do_list = 1;
6896 break;
6897 case 'n':
6898 do_update = 0;
6899 break;
6900 case 'r':
6901 repo_path = realpath(optarg, NULL);
6902 if (repo_path == NULL)
6903 return got_error_from_errno2("realpath",
6904 optarg);
6905 got_path_strip_trailing_slashes(repo_path);
6906 break;
6907 case 't':
6908 sort_by_time = 1;
6909 break;
6910 default:
6911 usage_branch();
6912 /* NOTREACHED */
6916 if (do_list && delref)
6917 option_conflict('l', 'd');
6918 if (sort_by_time && !do_list)
6919 errx(1, "-t option requires -l option");
6921 argc -= optind;
6922 argv += optind;
6924 if (!do_list && !delref && argc == 0)
6925 do_show = 1;
6927 if ((do_list || delref || do_show) && commit_id_arg != NULL)
6928 errx(1, "-c option can only be used when creating a branch");
6930 if (do_list || delref) {
6931 if (argc > 0)
6932 usage_branch();
6933 } else if (!do_show && argc != 1)
6934 usage_branch();
6936 #ifndef PROFILE
6937 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
6938 "sendfd unveil", NULL) == -1)
6939 err(1, "pledge");
6940 #endif
6941 cwd = getcwd(NULL, 0);
6942 if (cwd == NULL) {
6943 error = got_error_from_errno("getcwd");
6944 goto done;
6947 error = got_repo_pack_fds_open(&pack_fds);
6948 if (error != NULL)
6949 goto done;
6951 if (repo_path == NULL) {
6952 error = got_worktree_open(&worktree, cwd);
6953 if (error && error->code != GOT_ERR_NOT_WORKTREE)
6954 goto done;
6955 else
6956 error = NULL;
6957 if (worktree) {
6958 repo_path =
6959 strdup(got_worktree_get_repo_path(worktree));
6960 if (repo_path == NULL)
6961 error = got_error_from_errno("strdup");
6962 if (error)
6963 goto done;
6964 } else {
6965 repo_path = strdup(cwd);
6966 if (repo_path == NULL) {
6967 error = got_error_from_errno("strdup");
6968 goto done;
6973 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
6974 if (error != NULL)
6975 goto done;
6977 #ifndef PROFILE
6978 if (do_list || do_show) {
6979 /* Remove "cpath" promise. */
6980 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
6981 NULL) == -1)
6982 err(1, "pledge");
6984 #endif
6986 error = apply_unveil(got_repo_get_path(repo), do_list,
6987 worktree ? got_worktree_get_root_path(worktree) : NULL);
6988 if (error)
6989 goto done;
6991 if (do_show)
6992 error = show_current_branch(repo, worktree);
6993 else if (do_list)
6994 error = list_branches(repo, worktree, sort_by_time);
6995 else if (delref)
6996 error = delete_branch(repo, worktree, delref);
6997 else {
6998 struct got_reflist_head refs;
6999 TAILQ_INIT(&refs);
7000 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
7001 NULL);
7002 if (error)
7003 goto done;
7004 if (commit_id_arg == NULL)
7005 commit_id_arg = worktree ?
7006 got_worktree_get_head_ref_name(worktree) :
7007 GOT_REF_HEAD;
7008 error = got_repo_match_object_id(&commit_id, NULL,
7009 commit_id_arg, GOT_OBJ_TYPE_COMMIT, &refs, repo);
7010 got_ref_list_free(&refs);
7011 if (error)
7012 goto done;
7013 error = add_branch(repo, argv[0], commit_id);
7014 if (error)
7015 goto done;
7016 if (worktree && do_update) {
7017 struct got_update_progress_arg upa;
7018 char *branch_refname = NULL;
7020 error = got_object_id_str(&commit_id_str, commit_id);
7021 if (error)
7022 goto done;
7023 error = get_worktree_paths_from_argv(&paths, 0, NULL,
7024 worktree);
7025 if (error)
7026 goto done;
7027 if (asprintf(&branch_refname, "refs/heads/%s", argv[0])
7028 == -1) {
7029 error = got_error_from_errno("asprintf");
7030 goto done;
7032 error = got_ref_open(&ref, repo, branch_refname, 0);
7033 free(branch_refname);
7034 if (error)
7035 goto done;
7036 error = switch_head_ref(ref, commit_id, worktree,
7037 repo);
7038 if (error)
7039 goto done;
7040 error = got_worktree_set_base_commit_id(worktree, repo,
7041 commit_id);
7042 if (error)
7043 goto done;
7044 memset(&upa, 0, sizeof(upa));
7045 error = got_worktree_checkout_files(worktree, &paths,
7046 repo, update_progress, &upa, check_cancelled,
7047 NULL);
7048 if (error)
7049 goto done;
7050 if (upa.did_something) {
7051 printf("Updated to %s: %s\n",
7052 got_worktree_get_head_ref_name(worktree),
7053 commit_id_str);
7055 print_update_progress_stats(&upa);
7058 done:
7059 if (ref)
7060 got_ref_close(ref);
7061 if (repo) {
7062 const struct got_error *close_err = got_repo_close(repo);
7063 if (error == NULL)
7064 error = close_err;
7066 if (worktree)
7067 got_worktree_close(worktree);
7068 if (pack_fds) {
7069 const struct got_error *pack_err =
7070 got_repo_pack_fds_close(pack_fds);
7071 if (error == NULL)
7072 error = pack_err;
7074 free(cwd);
7075 free(repo_path);
7076 free(commit_id);
7077 free(commit_id_str);
7078 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
7079 return error;
7083 __dead static void
7084 usage_tag(void)
7086 fprintf(stderr, "usage: %s tag [-lVv] [-c commit] [-m message] "
7087 "[-r repository-path] [-s signer-id] name\n", getprogname());
7088 exit(1);
7091 #if 0
7092 static const struct got_error *
7093 sort_tags(struct got_reflist_head *sorted, struct got_reflist_head *tags)
7095 const struct got_error *err = NULL;
7096 struct got_reflist_entry *re, *se, *new;
7097 struct got_object_id *re_id, *se_id;
7098 struct got_tag_object *re_tag, *se_tag;
7099 time_t re_time, se_time;
7101 STAILQ_FOREACH(re, tags, entry) {
7102 se = STAILQ_FIRST(sorted);
7103 if (se == NULL) {
7104 err = got_reflist_entry_dup(&new, re);
7105 if (err)
7106 return err;
7107 STAILQ_INSERT_HEAD(sorted, new, entry);
7108 continue;
7109 } else {
7110 err = got_ref_resolve(&re_id, repo, re->ref);
7111 if (err)
7112 break;
7113 err = got_object_open_as_tag(&re_tag, repo, re_id);
7114 free(re_id);
7115 if (err)
7116 break;
7117 re_time = got_object_tag_get_tagger_time(re_tag);
7118 got_object_tag_close(re_tag);
7121 while (se) {
7122 err = got_ref_resolve(&se_id, repo, re->ref);
7123 if (err)
7124 break;
7125 err = got_object_open_as_tag(&se_tag, repo, se_id);
7126 free(se_id);
7127 if (err)
7128 break;
7129 se_time = got_object_tag_get_tagger_time(se_tag);
7130 got_object_tag_close(se_tag);
7132 if (se_time > re_time) {
7133 err = got_reflist_entry_dup(&new, re);
7134 if (err)
7135 return err;
7136 STAILQ_INSERT_AFTER(sorted, se, new, entry);
7137 break;
7139 se = STAILQ_NEXT(se, entry);
7140 continue;
7143 done:
7144 return err;
7146 #endif
7148 static const struct got_error *
7149 get_tag_refname(char **refname, const char *tag_name)
7151 const struct got_error *err;
7153 if (strncmp("refs/tags/", tag_name, 10) == 0) {
7154 *refname = strdup(tag_name);
7155 if (*refname == NULL)
7156 return got_error_from_errno("strdup");
7157 } else if (asprintf(refname, "refs/tags/%s", tag_name) == -1) {
7158 err = got_error_from_errno("asprintf");
7159 *refname = NULL;
7160 return err;
7163 return NULL;
7166 static const struct got_error *
7167 list_tags(struct got_repository *repo, const char *tag_name, int verify_tags,
7168 const char *allowed_signers, const char *revoked_signers, int verbosity)
7170 static const struct got_error *err = NULL;
7171 struct got_reflist_head refs;
7172 struct got_reflist_entry *re;
7173 char *wanted_refname = NULL;
7174 int bad_sigs = 0;
7176 TAILQ_INIT(&refs);
7178 err = got_ref_list(&refs, repo, "refs/tags", got_ref_cmp_tags, repo);
7179 if (err)
7180 return err;
7182 if (tag_name) {
7183 struct got_reference *ref;
7184 err = get_tag_refname(&wanted_refname, tag_name);
7185 if (err)
7186 goto done;
7187 /* Wanted tag reference should exist. */
7188 err = got_ref_open(&ref, repo, wanted_refname, 0);
7189 if (err)
7190 goto done;
7191 got_ref_close(ref);
7194 TAILQ_FOREACH(re, &refs, entry) {
7195 const char *refname;
7196 char *refstr, *tagmsg0, *tagmsg, *line, *id_str, *datestr;
7197 char datebuf[26];
7198 const char *tagger, *ssh_sig = NULL;
7199 char *sig_msg = NULL;
7200 time_t tagger_time;
7201 struct got_object_id *id;
7202 struct got_tag_object *tag;
7203 struct got_commit_object *commit = NULL;
7205 refname = got_ref_get_name(re->ref);
7206 if (strncmp(refname, "refs/tags/", 10) != 0 ||
7207 (wanted_refname && strcmp(refname, wanted_refname) != 0))
7208 continue;
7209 refname += 10;
7210 refstr = got_ref_to_str(re->ref);
7211 if (refstr == NULL) {
7212 err = got_error_from_errno("got_ref_to_str");
7213 break;
7216 err = got_ref_resolve(&id, repo, re->ref);
7217 if (err)
7218 break;
7219 err = got_object_open_as_tag(&tag, repo, id);
7220 if (err) {
7221 if (err->code != GOT_ERR_OBJ_TYPE) {
7222 free(id);
7223 break;
7225 /* "lightweight" tag */
7226 err = got_object_open_as_commit(&commit, repo, id);
7227 if (err) {
7228 free(id);
7229 break;
7231 tagger = got_object_commit_get_committer(commit);
7232 tagger_time =
7233 got_object_commit_get_committer_time(commit);
7234 err = got_object_id_str(&id_str, id);
7235 free(id);
7236 if (err)
7237 break;
7238 } else {
7239 free(id);
7240 tagger = got_object_tag_get_tagger(tag);
7241 tagger_time = got_object_tag_get_tagger_time(tag);
7242 err = got_object_id_str(&id_str,
7243 got_object_tag_get_object_id(tag));
7244 if (err)
7245 break;
7248 if (tag && verify_tags) {
7249 ssh_sig = got_sigs_get_tagmsg_ssh_signature(
7250 got_object_tag_get_message(tag));
7251 if (ssh_sig && allowed_signers == NULL) {
7252 err = got_error_msg(
7253 GOT_ERR_VERIFY_TAG_SIGNATURE,
7254 "SSH signature verification requires "
7255 "setting allowed_signers in "
7256 "got.conf(5)");
7257 break;
7261 printf("%stag %s %s\n", GOT_COMMIT_SEP_STR, refname, refstr);
7262 free(refstr);
7263 printf("from: %s\n", tagger);
7264 datestr = get_datestr(&tagger_time, datebuf);
7265 if (datestr)
7266 printf("date: %s UTC\n", datestr);
7267 if (commit)
7268 printf("object: %s %s\n", GOT_OBJ_LABEL_COMMIT, id_str);
7269 else {
7270 switch (got_object_tag_get_object_type(tag)) {
7271 case GOT_OBJ_TYPE_BLOB:
7272 printf("object: %s %s\n", GOT_OBJ_LABEL_BLOB,
7273 id_str);
7274 break;
7275 case GOT_OBJ_TYPE_TREE:
7276 printf("object: %s %s\n", GOT_OBJ_LABEL_TREE,
7277 id_str);
7278 break;
7279 case GOT_OBJ_TYPE_COMMIT:
7280 printf("object: %s %s\n", GOT_OBJ_LABEL_COMMIT,
7281 id_str);
7282 break;
7283 case GOT_OBJ_TYPE_TAG:
7284 printf("object: %s %s\n", GOT_OBJ_LABEL_TAG,
7285 id_str);
7286 break;
7287 default:
7288 break;
7291 free(id_str);
7293 if (ssh_sig) {
7294 err = got_sigs_verify_tag_ssh(&sig_msg, tag, ssh_sig,
7295 allowed_signers, revoked_signers, verbosity);
7296 if (err && err->code == GOT_ERR_BAD_TAG_SIGNATURE)
7297 bad_sigs = 1;
7298 else if (err)
7299 break;
7300 printf("signature: %s", sig_msg);
7301 free(sig_msg);
7302 sig_msg = NULL;
7305 if (commit) {
7306 err = got_object_commit_get_logmsg(&tagmsg0, commit);
7307 if (err)
7308 break;
7309 got_object_commit_close(commit);
7310 } else {
7311 tagmsg0 = strdup(got_object_tag_get_message(tag));
7312 got_object_tag_close(tag);
7313 if (tagmsg0 == NULL) {
7314 err = got_error_from_errno("strdup");
7315 break;
7319 tagmsg = tagmsg0;
7320 do {
7321 line = strsep(&tagmsg, "\n");
7322 if (line)
7323 printf(" %s\n", line);
7324 } while (line);
7325 free(tagmsg0);
7327 done:
7328 got_ref_list_free(&refs);
7329 free(wanted_refname);
7331 if (err == NULL && bad_sigs)
7332 err = got_error(GOT_ERR_BAD_TAG_SIGNATURE);
7333 return err;
7336 static const struct got_error *
7337 get_tag_message(char **tagmsg, char **tagmsg_path, const char *commit_id_str,
7338 const char *tag_name, const char *repo_path)
7340 const struct got_error *err = NULL;
7341 char *template = NULL, *initial_content = NULL;
7342 char *editor = NULL;
7343 int initial_content_len;
7344 int fd = -1;
7346 if (asprintf(&template, GOT_TMPDIR_STR "/got-tagmsg") == -1) {
7347 err = got_error_from_errno("asprintf");
7348 goto done;
7351 initial_content_len = asprintf(&initial_content,
7352 "\n# tagging commit %s as %s\n",
7353 commit_id_str, tag_name);
7354 if (initial_content_len == -1) {
7355 err = got_error_from_errno("asprintf");
7356 goto done;
7359 err = got_opentemp_named_fd(tagmsg_path, &fd, template, "");
7360 if (err)
7361 goto done;
7363 if (write(fd, initial_content, initial_content_len) == -1) {
7364 err = got_error_from_errno2("write", *tagmsg_path);
7365 goto done;
7368 err = get_editor(&editor);
7369 if (err)
7370 goto done;
7371 err = edit_logmsg(tagmsg, editor, *tagmsg_path, initial_content,
7372 initial_content_len, 1);
7373 done:
7374 free(initial_content);
7375 free(template);
7376 free(editor);
7378 if (fd != -1 && close(fd) == -1 && err == NULL)
7379 err = got_error_from_errno2("close", *tagmsg_path);
7381 if (err) {
7382 free(*tagmsg);
7383 *tagmsg = NULL;
7385 return err;
7388 static const struct got_error *
7389 add_tag(struct got_repository *repo, const char *tagger,
7390 const char *tag_name, const char *commit_arg, const char *tagmsg_arg,
7391 const char *signer_id, int verbosity)
7393 const struct got_error *err = NULL;
7394 struct got_object_id *commit_id = NULL, *tag_id = NULL;
7395 char *label = NULL, *commit_id_str = NULL;
7396 struct got_reference *ref = NULL;
7397 char *refname = NULL, *tagmsg = NULL;
7398 char *tagmsg_path = NULL, *tag_id_str = NULL;
7399 int preserve_tagmsg = 0;
7400 struct got_reflist_head refs;
7402 TAILQ_INIT(&refs);
7405 * Don't let the user create a tag name with a leading '-'.
7406 * While technically a valid reference name, this case is usually
7407 * an unintended typo.
7409 if (tag_name[0] == '-')
7410 return got_error_path(tag_name, GOT_ERR_REF_NAME_MINUS);
7412 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
7413 if (err)
7414 goto done;
7416 err = got_repo_match_object_id(&commit_id, &label, commit_arg,
7417 GOT_OBJ_TYPE_COMMIT, &refs, repo);
7418 if (err)
7419 goto done;
7421 err = got_object_id_str(&commit_id_str, commit_id);
7422 if (err)
7423 goto done;
7425 err = get_tag_refname(&refname, tag_name);
7426 if (err)
7427 goto done;
7428 if (strncmp("refs/tags/", tag_name, 10) == 0)
7429 tag_name += 10;
7431 err = got_ref_open(&ref, repo, refname, 0);
7432 if (err == NULL) {
7433 err = got_error(GOT_ERR_TAG_EXISTS);
7434 goto done;
7435 } else if (err->code != GOT_ERR_NOT_REF)
7436 goto done;
7438 if (tagmsg_arg == NULL) {
7439 err = get_tag_message(&tagmsg, &tagmsg_path, commit_id_str,
7440 tag_name, got_repo_get_path(repo));
7441 if (err) {
7442 if (err->code != GOT_ERR_COMMIT_MSG_EMPTY &&
7443 tagmsg_path != NULL)
7444 preserve_tagmsg = 1;
7445 goto done;
7447 /* Editor is done; we can now apply unveil(2) */
7448 err = got_sigs_apply_unveil();
7449 if (err)
7450 goto done;
7451 err = apply_unveil(got_repo_get_path(repo), 0, NULL);
7452 if (err)
7453 goto done;
7456 err = got_object_tag_create(&tag_id, tag_name, commit_id,
7457 tagger, time(NULL), tagmsg ? tagmsg : tagmsg_arg, signer_id, repo,
7458 verbosity);
7459 if (err) {
7460 if (tagmsg_path)
7461 preserve_tagmsg = 1;
7462 goto done;
7465 err = got_ref_alloc(&ref, refname, tag_id);
7466 if (err) {
7467 if (tagmsg_path)
7468 preserve_tagmsg = 1;
7469 goto done;
7472 err = got_ref_write(ref, repo);
7473 if (err) {
7474 if (tagmsg_path)
7475 preserve_tagmsg = 1;
7476 goto done;
7479 err = got_object_id_str(&tag_id_str, tag_id);
7480 if (err) {
7481 if (tagmsg_path)
7482 preserve_tagmsg = 1;
7483 goto done;
7485 printf("Created tag %s\n", tag_id_str);
7486 done:
7487 if (preserve_tagmsg) {
7488 fprintf(stderr, "%s: tag message preserved in %s\n",
7489 getprogname(), tagmsg_path);
7490 } else if (tagmsg_path && unlink(tagmsg_path) == -1 && err == NULL)
7491 err = got_error_from_errno2("unlink", tagmsg_path);
7492 free(tag_id_str);
7493 if (ref)
7494 got_ref_close(ref);
7495 free(commit_id);
7496 free(commit_id_str);
7497 free(refname);
7498 free(tagmsg);
7499 free(tagmsg_path);
7500 got_ref_list_free(&refs);
7501 return err;
7504 static const struct got_error *
7505 cmd_tag(int argc, char *argv[])
7507 const struct got_error *error = NULL;
7508 struct got_repository *repo = NULL;
7509 struct got_worktree *worktree = NULL;
7510 char *cwd = NULL, *repo_path = NULL, *commit_id_str = NULL;
7511 char *gitconfig_path = NULL, *tagger = NULL;
7512 char *allowed_signers = NULL, *revoked_signers = NULL;
7513 const char *signer_id = NULL;
7514 const char *tag_name = NULL, *commit_id_arg = NULL, *tagmsg = NULL;
7515 int ch, do_list = 0, verify_tags = 0, verbosity = 0;
7516 int *pack_fds = NULL;
7518 while ((ch = getopt(argc, argv, "c:lm:r:s:Vv")) != -1) {
7519 switch (ch) {
7520 case 'c':
7521 commit_id_arg = optarg;
7522 break;
7523 case 'l':
7524 do_list = 1;
7525 break;
7526 case 'm':
7527 tagmsg = optarg;
7528 break;
7529 case 'r':
7530 repo_path = realpath(optarg, NULL);
7531 if (repo_path == NULL) {
7532 error = got_error_from_errno2("realpath",
7533 optarg);
7534 goto done;
7536 got_path_strip_trailing_slashes(repo_path);
7537 break;
7538 case 's':
7539 signer_id = optarg;
7540 break;
7541 case 'V':
7542 verify_tags = 1;
7543 break;
7544 case 'v':
7545 if (verbosity < 0)
7546 verbosity = 0;
7547 else if (verbosity < 3)
7548 verbosity++;
7549 break;
7550 default:
7551 usage_tag();
7552 /* NOTREACHED */
7556 argc -= optind;
7557 argv += optind;
7559 if (do_list || verify_tags) {
7560 if (commit_id_arg != NULL)
7561 errx(1,
7562 "-c option can only be used when creating a tag");
7563 if (tagmsg) {
7564 if (do_list)
7565 option_conflict('l', 'm');
7566 else
7567 option_conflict('V', 'm');
7569 if (signer_id) {
7570 if (do_list)
7571 option_conflict('l', 's');
7572 else
7573 option_conflict('V', 's');
7575 if (argc > 1)
7576 usage_tag();
7577 } else if (argc != 1)
7578 usage_tag();
7580 if (argc == 1)
7581 tag_name = argv[0];
7583 #ifndef PROFILE
7584 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
7585 "sendfd unveil", NULL) == -1)
7586 err(1, "pledge");
7587 #endif
7588 cwd = getcwd(NULL, 0);
7589 if (cwd == NULL) {
7590 error = got_error_from_errno("getcwd");
7591 goto done;
7594 error = got_repo_pack_fds_open(&pack_fds);
7595 if (error != NULL)
7596 goto done;
7598 if (repo_path == NULL) {
7599 error = got_worktree_open(&worktree, cwd);
7600 if (error && error->code != GOT_ERR_NOT_WORKTREE)
7601 goto done;
7602 else
7603 error = NULL;
7604 if (worktree) {
7605 repo_path =
7606 strdup(got_worktree_get_repo_path(worktree));
7607 if (repo_path == NULL)
7608 error = got_error_from_errno("strdup");
7609 if (error)
7610 goto done;
7611 } else {
7612 repo_path = strdup(cwd);
7613 if (repo_path == NULL) {
7614 error = got_error_from_errno("strdup");
7615 goto done;
7620 if (do_list || verify_tags) {
7621 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
7622 if (error != NULL)
7623 goto done;
7624 error = get_allowed_signers(&allowed_signers, repo, worktree);
7625 if (error)
7626 goto done;
7627 error = get_revoked_signers(&revoked_signers, repo, worktree);
7628 if (error)
7629 goto done;
7630 if (worktree) {
7631 /* Release work tree lock. */
7632 got_worktree_close(worktree);
7633 worktree = NULL;
7637 * Remove "cpath" promise unless needed for signature tmpfile
7638 * creation.
7640 if (verify_tags)
7641 got_sigs_apply_unveil();
7642 else {
7643 #ifndef PROFILE
7644 if (pledge("stdio rpath wpath flock proc exec sendfd "
7645 "unveil", NULL) == -1)
7646 err(1, "pledge");
7647 #endif
7649 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
7650 if (error)
7651 goto done;
7652 error = list_tags(repo, tag_name, verify_tags, allowed_signers,
7653 revoked_signers, verbosity);
7654 } else {
7655 error = get_gitconfig_path(&gitconfig_path);
7656 if (error)
7657 goto done;
7658 error = got_repo_open(&repo, repo_path, gitconfig_path,
7659 pack_fds);
7660 if (error != NULL)
7661 goto done;
7663 error = get_author(&tagger, repo, worktree);
7664 if (error)
7665 goto done;
7666 if (signer_id == NULL)
7667 signer_id = get_signer_id(repo, worktree);
7669 if (tagmsg) {
7670 if (signer_id) {
7671 error = got_sigs_apply_unveil();
7672 if (error)
7673 goto done;
7675 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
7676 if (error)
7677 goto done;
7680 if (commit_id_arg == NULL) {
7681 struct got_reference *head_ref;
7682 struct got_object_id *commit_id;
7683 error = got_ref_open(&head_ref, repo,
7684 worktree ? got_worktree_get_head_ref_name(worktree)
7685 : GOT_REF_HEAD, 0);
7686 if (error)
7687 goto done;
7688 error = got_ref_resolve(&commit_id, repo, head_ref);
7689 got_ref_close(head_ref);
7690 if (error)
7691 goto done;
7692 error = got_object_id_str(&commit_id_str, commit_id);
7693 free(commit_id);
7694 if (error)
7695 goto done;
7698 if (worktree) {
7699 /* Release work tree lock. */
7700 got_worktree_close(worktree);
7701 worktree = NULL;
7704 error = add_tag(repo, tagger, tag_name,
7705 commit_id_str ? commit_id_str : commit_id_arg, tagmsg,
7706 signer_id, verbosity);
7708 done:
7709 if (repo) {
7710 const struct got_error *close_err = got_repo_close(repo);
7711 if (error == NULL)
7712 error = close_err;
7714 if (worktree)
7715 got_worktree_close(worktree);
7716 if (pack_fds) {
7717 const struct got_error *pack_err =
7718 got_repo_pack_fds_close(pack_fds);
7719 if (error == NULL)
7720 error = pack_err;
7722 free(cwd);
7723 free(repo_path);
7724 free(gitconfig_path);
7725 free(commit_id_str);
7726 free(tagger);
7727 free(allowed_signers);
7728 free(revoked_signers);
7729 return error;
7732 __dead static void
7733 usage_add(void)
7735 fprintf(stderr, "usage: %s add [-IR] path ...\n", getprogname());
7736 exit(1);
7739 static const struct got_error *
7740 add_progress(void *arg, unsigned char status, const char *path)
7742 while (path[0] == '/')
7743 path++;
7744 printf("%c %s\n", status, path);
7745 return NULL;
7748 static const struct got_error *
7749 cmd_add(int argc, char *argv[])
7751 const struct got_error *error = NULL;
7752 struct got_repository *repo = NULL;
7753 struct got_worktree *worktree = NULL;
7754 char *cwd = NULL;
7755 struct got_pathlist_head paths;
7756 struct got_pathlist_entry *pe;
7757 int ch, can_recurse = 0, no_ignores = 0;
7758 int *pack_fds = NULL;
7760 TAILQ_INIT(&paths);
7762 while ((ch = getopt(argc, argv, "IR")) != -1) {
7763 switch (ch) {
7764 case 'I':
7765 no_ignores = 1;
7766 break;
7767 case 'R':
7768 can_recurse = 1;
7769 break;
7770 default:
7771 usage_add();
7772 /* NOTREACHED */
7776 argc -= optind;
7777 argv += optind;
7779 #ifndef PROFILE
7780 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
7781 NULL) == -1)
7782 err(1, "pledge");
7783 #endif
7784 if (argc < 1)
7785 usage_add();
7787 cwd = getcwd(NULL, 0);
7788 if (cwd == NULL) {
7789 error = got_error_from_errno("getcwd");
7790 goto done;
7793 error = got_repo_pack_fds_open(&pack_fds);
7794 if (error != NULL)
7795 goto done;
7797 error = got_worktree_open(&worktree, cwd);
7798 if (error) {
7799 if (error->code == GOT_ERR_NOT_WORKTREE)
7800 error = wrap_not_worktree_error(error, "add", cwd);
7801 goto done;
7804 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
7805 NULL, pack_fds);
7806 if (error != NULL)
7807 goto done;
7809 error = apply_unveil(got_repo_get_path(repo), 1,
7810 got_worktree_get_root_path(worktree));
7811 if (error)
7812 goto done;
7814 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
7815 if (error)
7816 goto done;
7818 if (!can_recurse) {
7819 char *ondisk_path;
7820 struct stat sb;
7821 TAILQ_FOREACH(pe, &paths, entry) {
7822 if (asprintf(&ondisk_path, "%s/%s",
7823 got_worktree_get_root_path(worktree),
7824 pe->path) == -1) {
7825 error = got_error_from_errno("asprintf");
7826 goto done;
7828 if (lstat(ondisk_path, &sb) == -1) {
7829 if (errno == ENOENT) {
7830 free(ondisk_path);
7831 continue;
7833 error = got_error_from_errno2("lstat",
7834 ondisk_path);
7835 free(ondisk_path);
7836 goto done;
7838 free(ondisk_path);
7839 if (S_ISDIR(sb.st_mode)) {
7840 error = got_error_msg(GOT_ERR_BAD_PATH,
7841 "adding directories requires -R option");
7842 goto done;
7847 error = got_worktree_schedule_add(worktree, &paths, add_progress,
7848 NULL, repo, no_ignores);
7849 done:
7850 if (repo) {
7851 const struct got_error *close_err = got_repo_close(repo);
7852 if (error == NULL)
7853 error = close_err;
7855 if (worktree)
7856 got_worktree_close(worktree);
7857 if (pack_fds) {
7858 const struct got_error *pack_err =
7859 got_repo_pack_fds_close(pack_fds);
7860 if (error == NULL)
7861 error = pack_err;
7863 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
7864 free(cwd);
7865 return error;
7868 __dead static void
7869 usage_remove(void)
7871 fprintf(stderr, "usage: %s remove [-fkR] [-s status-codes] path ...\n",
7872 getprogname());
7873 exit(1);
7876 static const struct got_error *
7877 print_remove_status(void *arg, unsigned char status,
7878 unsigned char staged_status, const char *path)
7880 while (path[0] == '/')
7881 path++;
7882 if (status == GOT_STATUS_NONEXISTENT)
7883 return NULL;
7884 if (status == staged_status && (status == GOT_STATUS_DELETE))
7885 status = GOT_STATUS_NO_CHANGE;
7886 printf("%c%c %s\n", status, staged_status, path);
7887 return NULL;
7890 static const struct got_error *
7891 cmd_remove(int argc, char *argv[])
7893 const struct got_error *error = NULL;
7894 struct got_worktree *worktree = NULL;
7895 struct got_repository *repo = NULL;
7896 const char *status_codes = NULL;
7897 char *cwd = NULL;
7898 struct got_pathlist_head paths;
7899 struct got_pathlist_entry *pe;
7900 int ch, delete_local_mods = 0, can_recurse = 0, keep_on_disk = 0, i;
7901 int ignore_missing_paths = 0;
7902 int *pack_fds = NULL;
7904 TAILQ_INIT(&paths);
7906 while ((ch = getopt(argc, argv, "fkRs:")) != -1) {
7907 switch (ch) {
7908 case 'f':
7909 delete_local_mods = 1;
7910 ignore_missing_paths = 1;
7911 break;
7912 case 'k':
7913 keep_on_disk = 1;
7914 break;
7915 case 'R':
7916 can_recurse = 1;
7917 break;
7918 case 's':
7919 for (i = 0; i < strlen(optarg); i++) {
7920 switch (optarg[i]) {
7921 case GOT_STATUS_MODIFY:
7922 delete_local_mods = 1;
7923 break;
7924 case GOT_STATUS_MISSING:
7925 ignore_missing_paths = 1;
7926 break;
7927 default:
7928 errx(1, "invalid status code '%c'",
7929 optarg[i]);
7932 status_codes = optarg;
7933 break;
7934 default:
7935 usage_remove();
7936 /* NOTREACHED */
7940 argc -= optind;
7941 argv += optind;
7943 #ifndef PROFILE
7944 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
7945 NULL) == -1)
7946 err(1, "pledge");
7947 #endif
7948 if (argc < 1)
7949 usage_remove();
7951 cwd = getcwd(NULL, 0);
7952 if (cwd == NULL) {
7953 error = got_error_from_errno("getcwd");
7954 goto done;
7957 error = got_repo_pack_fds_open(&pack_fds);
7958 if (error != NULL)
7959 goto done;
7961 error = got_worktree_open(&worktree, cwd);
7962 if (error) {
7963 if (error->code == GOT_ERR_NOT_WORKTREE)
7964 error = wrap_not_worktree_error(error, "remove", cwd);
7965 goto done;
7968 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
7969 NULL, pack_fds);
7970 if (error)
7971 goto done;
7973 error = apply_unveil(got_repo_get_path(repo), 1,
7974 got_worktree_get_root_path(worktree));
7975 if (error)
7976 goto done;
7978 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
7979 if (error)
7980 goto done;
7982 if (!can_recurse) {
7983 char *ondisk_path;
7984 struct stat sb;
7985 TAILQ_FOREACH(pe, &paths, entry) {
7986 if (asprintf(&ondisk_path, "%s/%s",
7987 got_worktree_get_root_path(worktree),
7988 pe->path) == -1) {
7989 error = got_error_from_errno("asprintf");
7990 goto done;
7992 if (lstat(ondisk_path, &sb) == -1) {
7993 if (errno == ENOENT) {
7994 free(ondisk_path);
7995 continue;
7997 error = got_error_from_errno2("lstat",
7998 ondisk_path);
7999 free(ondisk_path);
8000 goto done;
8002 free(ondisk_path);
8003 if (S_ISDIR(sb.st_mode)) {
8004 error = got_error_msg(GOT_ERR_BAD_PATH,
8005 "removing directories requires -R option");
8006 goto done;
8011 error = got_worktree_schedule_delete(worktree, &paths,
8012 delete_local_mods, status_codes, print_remove_status, NULL,
8013 repo, keep_on_disk, ignore_missing_paths);
8014 done:
8015 if (repo) {
8016 const struct got_error *close_err = got_repo_close(repo);
8017 if (error == NULL)
8018 error = close_err;
8020 if (worktree)
8021 got_worktree_close(worktree);
8022 if (pack_fds) {
8023 const struct got_error *pack_err =
8024 got_repo_pack_fds_close(pack_fds);
8025 if (error == NULL)
8026 error = pack_err;
8028 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
8029 free(cwd);
8030 return error;
8033 __dead static void
8034 usage_patch(void)
8036 fprintf(stderr, "usage: %s patch [-nR] [-c commit] [-p strip-count] "
8037 "[patchfile]\n", getprogname());
8038 exit(1);
8041 static const struct got_error *
8042 patch_from_stdin(int *patchfd)
8044 const struct got_error *err = NULL;
8045 ssize_t r;
8046 char buf[BUFSIZ];
8047 sig_t sighup, sigint, sigquit;
8049 *patchfd = got_opentempfd();
8050 if (*patchfd == -1)
8051 return got_error_from_errno("got_opentempfd");
8053 sighup = signal(SIGHUP, SIG_DFL);
8054 sigint = signal(SIGINT, SIG_DFL);
8055 sigquit = signal(SIGQUIT, SIG_DFL);
8057 for (;;) {
8058 r = read(0, buf, sizeof(buf));
8059 if (r == -1) {
8060 err = got_error_from_errno("read");
8061 break;
8063 if (r == 0)
8064 break;
8065 if (write(*patchfd, buf, r) == -1) {
8066 err = got_error_from_errno("write");
8067 break;
8071 signal(SIGHUP, sighup);
8072 signal(SIGINT, sigint);
8073 signal(SIGQUIT, sigquit);
8075 if (err == NULL && lseek(*patchfd, 0, SEEK_SET) == -1)
8076 err = got_error_from_errno("lseek");
8078 if (err != NULL) {
8079 close(*patchfd);
8080 *patchfd = -1;
8083 return err;
8086 static const struct got_error *
8087 patch_progress(void *arg, const char *old, const char *new,
8088 unsigned char status, const struct got_error *error, int old_from,
8089 int old_lines, int new_from, int new_lines, int offset,
8090 int ws_mangled, const struct got_error *hunk_err)
8092 const char *path = new == NULL ? old : new;
8094 while (*path == '/')
8095 path++;
8097 if (status != 0)
8098 printf("%c %s\n", status, path);
8100 if (error != NULL)
8101 fprintf(stderr, "%s: %s\n", getprogname(), error->msg);
8103 if (offset != 0 || hunk_err != NULL || ws_mangled) {
8104 printf("@@ -%d,%d +%d,%d @@ ", old_from,
8105 old_lines, new_from, new_lines);
8106 if (hunk_err != NULL)
8107 printf("%s\n", hunk_err->msg);
8108 else if (offset != 0)
8109 printf("applied with offset %d\n", offset);
8110 else
8111 printf("hunk contains mangled whitespace\n");
8114 return NULL;
8117 static const struct got_error *
8118 cmd_patch(int argc, char *argv[])
8120 const struct got_error *error = NULL, *close_error = NULL;
8121 struct got_worktree *worktree = NULL;
8122 struct got_repository *repo = NULL;
8123 struct got_reflist_head refs;
8124 struct got_object_id *commit_id = NULL;
8125 const char *commit_id_str = NULL;
8126 struct stat sb;
8127 const char *errstr;
8128 char *cwd = NULL;
8129 int ch, nop = 0, strip = -1, reverse = 0;
8130 int patchfd;
8131 int *pack_fds = NULL;
8133 TAILQ_INIT(&refs);
8135 #ifndef PROFILE
8136 if (pledge("stdio rpath wpath cpath fattr proc exec sendfd flock "
8137 "unveil", NULL) == -1)
8138 err(1, "pledge");
8139 #endif
8141 while ((ch = getopt(argc, argv, "c:np:R")) != -1) {
8142 switch (ch) {
8143 case 'c':
8144 commit_id_str = optarg;
8145 break;
8146 case 'n':
8147 nop = 1;
8148 break;
8149 case 'p':
8150 strip = strtonum(optarg, 0, INT_MAX, &errstr);
8151 if (errstr != NULL)
8152 errx(1, "pathname strip count is %s: %s",
8153 errstr, optarg);
8154 break;
8155 case 'R':
8156 reverse = 1;
8157 break;
8158 default:
8159 usage_patch();
8160 /* NOTREACHED */
8164 argc -= optind;
8165 argv += optind;
8167 if (argc == 0) {
8168 error = patch_from_stdin(&patchfd);
8169 if (error)
8170 return error;
8171 } else if (argc == 1) {
8172 patchfd = open(argv[0], O_RDONLY);
8173 if (patchfd == -1) {
8174 error = got_error_from_errno2("open", argv[0]);
8175 return error;
8177 if (fstat(patchfd, &sb) == -1) {
8178 error = got_error_from_errno2("fstat", argv[0]);
8179 goto done;
8181 if (!S_ISREG(sb.st_mode)) {
8182 error = got_error_path(argv[0], GOT_ERR_BAD_FILETYPE);
8183 goto done;
8185 } else
8186 usage_patch();
8188 if ((cwd = getcwd(NULL, 0)) == NULL) {
8189 error = got_error_from_errno("getcwd");
8190 goto done;
8193 error = got_repo_pack_fds_open(&pack_fds);
8194 if (error != NULL)
8195 goto done;
8197 error = got_worktree_open(&worktree, cwd);
8198 if (error != NULL)
8199 goto done;
8201 const char *repo_path = got_worktree_get_repo_path(worktree);
8202 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
8203 if (error != NULL)
8204 goto done;
8206 error = apply_unveil(got_repo_get_path(repo), 0,
8207 got_worktree_get_root_path(worktree));
8208 if (error != NULL)
8209 goto done;
8211 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
8212 if (error)
8213 goto done;
8215 if (commit_id_str != NULL) {
8216 error = got_repo_match_object_id(&commit_id, NULL,
8217 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
8218 if (error)
8219 goto done;
8222 error = got_patch(patchfd, worktree, repo, nop, strip, reverse,
8223 commit_id, &patch_progress, NULL, check_cancelled, NULL);
8225 done:
8226 got_ref_list_free(&refs);
8227 free(commit_id);
8228 if (repo) {
8229 close_error = got_repo_close(repo);
8230 if (error == NULL)
8231 error = close_error;
8233 if (worktree != NULL) {
8234 close_error = got_worktree_close(worktree);
8235 if (error == NULL)
8236 error = close_error;
8238 if (pack_fds) {
8239 const struct got_error *pack_err =
8240 got_repo_pack_fds_close(pack_fds);
8241 if (error == NULL)
8242 error = pack_err;
8244 free(cwd);
8245 return error;
8248 __dead static void
8249 usage_revert(void)
8251 fprintf(stderr, "usage: %s revert [-pR] [-F response-script] path ...\n",
8252 getprogname());
8253 exit(1);
8256 static const struct got_error *
8257 revert_progress(void *arg, unsigned char status, const char *path)
8259 if (status == GOT_STATUS_UNVERSIONED)
8260 return NULL;
8262 while (path[0] == '/')
8263 path++;
8264 printf("%c %s\n", status, path);
8265 return NULL;
8268 struct choose_patch_arg {
8269 FILE *patch_script_file;
8270 const char *action;
8273 static const struct got_error *
8274 show_change(unsigned char status, const char *path, FILE *patch_file, int n,
8275 int nchanges, const char *action)
8277 const struct got_error *err;
8278 char *line = NULL;
8279 size_t linesize = 0;
8280 ssize_t linelen;
8282 switch (status) {
8283 case GOT_STATUS_ADD:
8284 printf("A %s\n%s this addition? [y/n] ", path, action);
8285 break;
8286 case GOT_STATUS_DELETE:
8287 printf("D %s\n%s this deletion? [y/n] ", path, action);
8288 break;
8289 case GOT_STATUS_MODIFY:
8290 if (fseek(patch_file, 0L, SEEK_SET) == -1)
8291 return got_error_from_errno("fseek");
8292 printf(GOT_COMMIT_SEP_STR);
8293 while ((linelen = getline(&line, &linesize, patch_file)) != -1)
8294 printf("%s", line);
8295 if (linelen == -1 && ferror(patch_file)) {
8296 err = got_error_from_errno("getline");
8297 free(line);
8298 return err;
8300 free(line);
8301 printf(GOT_COMMIT_SEP_STR);
8302 printf("M %s (change %d of %d)\n%s this change? [y/n/q] ",
8303 path, n, nchanges, action);
8304 break;
8305 default:
8306 return got_error_path(path, GOT_ERR_FILE_STATUS);
8309 fflush(stdout);
8310 return NULL;
8313 static const struct got_error *
8314 choose_patch(int *choice, void *arg, unsigned char status, const char *path,
8315 FILE *patch_file, int n, int nchanges)
8317 const struct got_error *err = NULL;
8318 char *line = NULL;
8319 size_t linesize = 0;
8320 ssize_t linelen;
8321 int resp = ' ';
8322 struct choose_patch_arg *a = arg;
8324 *choice = GOT_PATCH_CHOICE_NONE;
8326 if (a->patch_script_file) {
8327 char *nl;
8328 err = show_change(status, path, patch_file, n, nchanges,
8329 a->action);
8330 if (err)
8331 return err;
8332 linelen = getline(&line, &linesize, a->patch_script_file);
8333 if (linelen == -1) {
8334 if (ferror(a->patch_script_file))
8335 return got_error_from_errno("getline");
8336 return NULL;
8338 nl = strchr(line, '\n');
8339 if (nl)
8340 *nl = '\0';
8341 if (strcmp(line, "y") == 0) {
8342 *choice = GOT_PATCH_CHOICE_YES;
8343 printf("y\n");
8344 } else if (strcmp(line, "n") == 0) {
8345 *choice = GOT_PATCH_CHOICE_NO;
8346 printf("n\n");
8347 } else if (strcmp(line, "q") == 0 &&
8348 status == GOT_STATUS_MODIFY) {
8349 *choice = GOT_PATCH_CHOICE_QUIT;
8350 printf("q\n");
8351 } else
8352 printf("invalid response '%s'\n", line);
8353 free(line);
8354 return NULL;
8357 while (resp != 'y' && resp != 'n' && resp != 'q') {
8358 err = show_change(status, path, patch_file, n, nchanges,
8359 a->action);
8360 if (err)
8361 return err;
8362 resp = getchar();
8363 if (resp == '\n')
8364 resp = getchar();
8365 if (status == GOT_STATUS_MODIFY) {
8366 if (resp != 'y' && resp != 'n' && resp != 'q') {
8367 printf("invalid response '%c'\n", resp);
8368 resp = ' ';
8370 } else if (resp != 'y' && resp != 'n') {
8371 printf("invalid response '%c'\n", resp);
8372 resp = ' ';
8376 if (resp == 'y')
8377 *choice = GOT_PATCH_CHOICE_YES;
8378 else if (resp == 'n')
8379 *choice = GOT_PATCH_CHOICE_NO;
8380 else if (resp == 'q' && status == GOT_STATUS_MODIFY)
8381 *choice = GOT_PATCH_CHOICE_QUIT;
8383 return NULL;
8386 struct wt_commitable_path_arg {
8387 struct got_pathlist_head *commit_paths;
8388 int *has_changes;
8392 * Shortcut work tree status callback to determine if the set of paths scanned
8393 * has at least one versioned path that is being modified and, if not NULL, is
8394 * in the arg->commit_paths list. Set arg and return GOT_ERR_FILE_MODIFIED as
8395 * soon as a path is passed with a status that satisfies this criteria.
8397 static const struct got_error *
8398 worktree_has_commitable_path(void *arg, unsigned char status,
8399 unsigned char staged_status, const char *path,
8400 struct got_object_id *blob_id, struct got_object_id *staged_blob_id,
8401 struct got_object_id *commit_id, int dirfd, const char *de_name)
8403 struct wt_commitable_path_arg *a = arg;
8405 if (status == staged_status && (status == GOT_STATUS_DELETE))
8406 status = GOT_STATUS_NO_CHANGE;
8408 if (!(status == GOT_STATUS_NO_CHANGE ||
8409 status == GOT_STATUS_UNVERSIONED) ||
8410 staged_status != GOT_STATUS_NO_CHANGE) {
8411 if (a->commit_paths != NULL) {
8412 struct got_pathlist_entry *pe;
8414 TAILQ_FOREACH(pe, a->commit_paths, entry) {
8415 if (strncmp(path, pe->path,
8416 pe->path_len) == 0) {
8417 *a->has_changes = 1;
8418 break;
8421 } else
8422 *a->has_changes = 1;
8424 if (*a->has_changes)
8425 return got_error(GOT_ERR_FILE_MODIFIED);
8428 return NULL;
8432 * Check that the changeset of the commit identified by id is
8433 * comprised of at least one modified path that is being committed.
8435 static const struct got_error *
8436 commit_path_changed_in_worktree(struct wt_commitable_path_arg *wcpa,
8437 struct got_object_id *id, struct got_worktree *worktree,
8438 struct got_repository *repo)
8440 const struct got_error *err;
8441 struct got_pathlist_head paths;
8442 struct got_commit_object *commit = NULL, *pcommit = NULL;
8443 struct got_tree_object *tree = NULL, *ptree = NULL;
8444 struct got_object_qid *pid;
8446 TAILQ_INIT(&paths);
8448 err = got_object_open_as_commit(&commit, repo, id);
8449 if (err)
8450 goto done;
8452 err = got_object_open_as_tree(&tree, repo,
8453 got_object_commit_get_tree_id(commit));
8454 if (err)
8455 goto done;
8457 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
8458 if (pid != NULL) {
8459 err = got_object_open_as_commit(&pcommit, repo, &pid->id);
8460 if (err)
8461 goto done;
8463 err = got_object_open_as_tree(&ptree, repo,
8464 got_object_commit_get_tree_id(pcommit));
8465 if (err)
8466 goto done;
8469 err = got_diff_tree(ptree, tree, NULL, NULL, -1, -1, "", "", repo,
8470 got_diff_tree_collect_changed_paths, &paths, 0);
8471 if (err)
8472 goto done;
8474 err = got_worktree_status(worktree, &paths, repo, 0,
8475 worktree_has_commitable_path, wcpa, check_cancelled, NULL);
8476 if (err && err->code == GOT_ERR_FILE_MODIFIED) {
8478 * At least one changed path in the referenced commit is
8479 * modified in the work tree, that's all we need to know!
8481 err = NULL;
8484 done:
8485 got_pathlist_free(&paths, GOT_PATHLIST_FREE_ALL);
8486 if (commit)
8487 got_object_commit_close(commit);
8488 if (pcommit)
8489 got_object_commit_close(pcommit);
8490 if (tree)
8491 got_object_tree_close(tree);
8492 if (ptree)
8493 got_object_tree_close(ptree);
8494 return err;
8498 * Remove any "logmsg" reference comprised entirely of paths that have
8499 * been reverted in this work tree. If any path in the logmsg ref changeset
8500 * remains in a changed state in the worktree, do not remove the reference.
8502 static const struct got_error *
8503 rm_logmsg_ref(struct got_worktree *worktree, struct got_repository *repo)
8505 const struct got_error *err;
8506 struct got_reflist_head refs;
8507 struct got_reflist_entry *re;
8508 struct got_commit_object *commit = NULL;
8509 struct got_object_id *commit_id = NULL;
8510 struct wt_commitable_path_arg wcpa;
8511 char *uuidstr = NULL;
8513 TAILQ_INIT(&refs);
8515 err = got_worktree_get_uuid(&uuidstr, worktree);
8516 if (err)
8517 goto done;
8519 err = got_ref_list(&refs, repo, "refs/got/worktree",
8520 got_ref_cmp_by_name, repo);
8521 if (err)
8522 goto done;
8524 TAILQ_FOREACH(re, &refs, entry) {
8525 const char *refname;
8526 int has_changes = 0;
8528 refname = got_ref_get_name(re->ref);
8530 if (!strncmp(refname, GOT_WORKTREE_CHERRYPICK_REF_PREFIX,
8531 GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN))
8532 refname += GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN + 1;
8533 else if (!strncmp(refname, GOT_WORKTREE_BACKOUT_REF_PREFIX,
8534 GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN))
8535 refname += GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN + 1;
8536 else
8537 continue;
8539 if (strncmp(refname, uuidstr, GOT_WORKTREE_UUID_STRLEN) == 0)
8540 refname += GOT_WORKTREE_UUID_STRLEN + 1; /* skip '-' */
8541 else
8542 continue;
8544 err = got_repo_match_object_id(&commit_id, NULL, refname,
8545 GOT_OBJ_TYPE_COMMIT, NULL, repo);
8546 if (err)
8547 goto done;
8549 err = got_object_open_as_commit(&commit, repo, commit_id);
8550 if (err)
8551 goto done;
8553 wcpa.commit_paths = NULL;
8554 wcpa.has_changes = &has_changes;
8556 err = commit_path_changed_in_worktree(&wcpa, commit_id,
8557 worktree, repo);
8558 if (err)
8559 goto done;
8561 if (!has_changes) {
8562 err = got_ref_delete(re->ref, repo);
8563 if (err)
8564 goto done;
8567 got_object_commit_close(commit);
8568 commit = NULL;
8569 free(commit_id);
8570 commit_id = NULL;
8573 done:
8574 free(uuidstr);
8575 free(commit_id);
8576 got_ref_list_free(&refs);
8577 if (commit)
8578 got_object_commit_close(commit);
8579 return err;
8582 static const struct got_error *
8583 cmd_revert(int argc, char *argv[])
8585 const struct got_error *error = NULL;
8586 struct got_worktree *worktree = NULL;
8587 struct got_repository *repo = NULL;
8588 char *cwd = NULL, *path = NULL;
8589 struct got_pathlist_head paths;
8590 struct got_pathlist_entry *pe;
8591 int ch, can_recurse = 0, pflag = 0;
8592 FILE *patch_script_file = NULL;
8593 const char *patch_script_path = NULL;
8594 struct choose_patch_arg cpa;
8595 int *pack_fds = NULL;
8597 TAILQ_INIT(&paths);
8599 while ((ch = getopt(argc, argv, "F:pR")) != -1) {
8600 switch (ch) {
8601 case 'F':
8602 patch_script_path = optarg;
8603 break;
8604 case 'p':
8605 pflag = 1;
8606 break;
8607 case 'R':
8608 can_recurse = 1;
8609 break;
8610 default:
8611 usage_revert();
8612 /* NOTREACHED */
8616 argc -= optind;
8617 argv += optind;
8619 #ifndef PROFILE
8620 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
8621 "unveil", NULL) == -1)
8622 err(1, "pledge");
8623 #endif
8624 if (argc < 1)
8625 usage_revert();
8626 if (patch_script_path && !pflag)
8627 errx(1, "-F option can only be used together with -p option");
8629 cwd = getcwd(NULL, 0);
8630 if (cwd == NULL) {
8631 error = got_error_from_errno("getcwd");
8632 goto done;
8635 error = got_repo_pack_fds_open(&pack_fds);
8636 if (error != NULL)
8637 goto done;
8639 error = got_worktree_open(&worktree, cwd);
8640 if (error) {
8641 if (error->code == GOT_ERR_NOT_WORKTREE)
8642 error = wrap_not_worktree_error(error, "revert", cwd);
8643 goto done;
8646 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
8647 NULL, pack_fds);
8648 if (error != NULL)
8649 goto done;
8651 if (patch_script_path) {
8652 patch_script_file = fopen(patch_script_path, "re");
8653 if (patch_script_file == NULL) {
8654 error = got_error_from_errno2("fopen",
8655 patch_script_path);
8656 goto done;
8661 * XXX "c" perm needed on repo dir to delete merge references.
8663 error = apply_unveil(got_repo_get_path(repo), 0,
8664 got_worktree_get_root_path(worktree));
8665 if (error)
8666 goto done;
8668 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
8669 if (error)
8670 goto done;
8672 if (!can_recurse) {
8673 char *ondisk_path;
8674 struct stat sb;
8675 TAILQ_FOREACH(pe, &paths, entry) {
8676 if (asprintf(&ondisk_path, "%s/%s",
8677 got_worktree_get_root_path(worktree),
8678 pe->path) == -1) {
8679 error = got_error_from_errno("asprintf");
8680 goto done;
8682 if (lstat(ondisk_path, &sb) == -1) {
8683 if (errno == ENOENT) {
8684 free(ondisk_path);
8685 continue;
8687 error = got_error_from_errno2("lstat",
8688 ondisk_path);
8689 free(ondisk_path);
8690 goto done;
8692 free(ondisk_path);
8693 if (S_ISDIR(sb.st_mode)) {
8694 error = got_error_msg(GOT_ERR_BAD_PATH,
8695 "reverting directories requires -R option");
8696 goto done;
8701 cpa.patch_script_file = patch_script_file;
8702 cpa.action = "revert";
8703 error = got_worktree_revert(worktree, &paths, revert_progress, NULL,
8704 pflag ? choose_patch : NULL, &cpa, repo);
8706 error = rm_logmsg_ref(worktree, repo);
8707 done:
8708 if (patch_script_file && fclose(patch_script_file) == EOF &&
8709 error == NULL)
8710 error = got_error_from_errno2("fclose", patch_script_path);
8711 if (repo) {
8712 const struct got_error *close_err = got_repo_close(repo);
8713 if (error == NULL)
8714 error = close_err;
8716 if (worktree)
8717 got_worktree_close(worktree);
8718 if (pack_fds) {
8719 const struct got_error *pack_err =
8720 got_repo_pack_fds_close(pack_fds);
8721 if (error == NULL)
8722 error = pack_err;
8724 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
8725 free(path);
8726 free(cwd);
8727 return error;
8730 __dead static void
8731 usage_commit(void)
8733 fprintf(stderr, "usage: %s commit [-NS] [-A author] [-F path] "
8734 "[-m message] [path ...]\n", getprogname());
8735 exit(1);
8738 struct collect_commit_logmsg_arg {
8739 const char *cmdline_log;
8740 const char *prepared_log;
8741 const char *merged_log;
8742 int non_interactive;
8743 const char *editor;
8744 const char *worktree_path;
8745 const char *branch_name;
8746 const char *repo_path;
8747 char *logmsg_path;
8751 static const struct got_error *
8752 read_prepared_logmsg(char **logmsg, const char *path)
8754 const struct got_error *err = NULL;
8755 FILE *f = NULL;
8756 struct stat sb;
8757 size_t r;
8759 *logmsg = NULL;
8760 memset(&sb, 0, sizeof(sb));
8762 f = fopen(path, "re");
8763 if (f == NULL)
8764 return got_error_from_errno2("fopen", path);
8766 if (fstat(fileno(f), &sb) == -1) {
8767 err = got_error_from_errno2("fstat", path);
8768 goto done;
8770 if (sb.st_size == 0) {
8771 err = got_error(GOT_ERR_COMMIT_MSG_EMPTY);
8772 goto done;
8775 *logmsg = malloc(sb.st_size + 1);
8776 if (*logmsg == NULL) {
8777 err = got_error_from_errno("malloc");
8778 goto done;
8781 r = fread(*logmsg, 1, sb.st_size, f);
8782 if (r != sb.st_size) {
8783 if (ferror(f))
8784 err = got_error_from_errno2("fread", path);
8785 else
8786 err = got_error(GOT_ERR_IO);
8787 goto done;
8789 (*logmsg)[sb.st_size] = '\0';
8790 done:
8791 if (fclose(f) == EOF && err == NULL)
8792 err = got_error_from_errno2("fclose", path);
8793 if (err) {
8794 free(*logmsg);
8795 *logmsg = NULL;
8797 return err;
8800 static const struct got_error *
8801 collect_commit_logmsg(struct got_pathlist_head *commitable_paths,
8802 const char *diff_path, char **logmsg, void *arg)
8804 char *initial_content = NULL;
8805 struct got_pathlist_entry *pe;
8806 const struct got_error *err = NULL;
8807 char *template = NULL;
8808 char *prepared_msg = NULL, *merged_msg = NULL;
8809 struct collect_commit_logmsg_arg *a = arg;
8810 int initial_content_len;
8811 int fd = -1;
8812 size_t len;
8814 /* if a message was specified on the command line, just use it */
8815 if (a->cmdline_log != NULL && strlen(a->cmdline_log) != 0) {
8816 len = strlen(a->cmdline_log) + 1;
8817 *logmsg = malloc(len + 1);
8818 if (*logmsg == NULL)
8819 return got_error_from_errno("malloc");
8820 strlcpy(*logmsg, a->cmdline_log, len);
8821 return NULL;
8822 } else if (a->prepared_log != NULL && a->non_interactive)
8823 return read_prepared_logmsg(logmsg, a->prepared_log);
8825 if (asprintf(&template, "%s/logmsg", a->worktree_path) == -1)
8826 return got_error_from_errno("asprintf");
8828 err = got_opentemp_named_fd(&a->logmsg_path, &fd, template, "");
8829 if (err)
8830 goto done;
8832 if (a->prepared_log) {
8833 err = read_prepared_logmsg(&prepared_msg, a->prepared_log);
8834 if (err)
8835 goto done;
8836 } else if (a->merged_log) {
8837 err = read_prepared_logmsg(&merged_msg, a->merged_log);
8838 if (err)
8839 goto done;
8842 initial_content_len = asprintf(&initial_content,
8843 "%s%s\n# changes to be committed on branch %s:\n",
8844 prepared_msg ? prepared_msg : "",
8845 merged_msg ? merged_msg : "", a->branch_name);
8846 if (initial_content_len == -1) {
8847 err = got_error_from_errno("asprintf");
8848 goto done;
8851 if (write(fd, initial_content, initial_content_len) == -1) {
8852 err = got_error_from_errno2("write", a->logmsg_path);
8853 goto done;
8856 TAILQ_FOREACH(pe, commitable_paths, entry) {
8857 struct got_commitable *ct = pe->data;
8858 dprintf(fd, "# %c %s\n",
8859 got_commitable_get_status(ct),
8860 got_commitable_get_path(ct));
8863 if (diff_path) {
8864 dprintf(fd, "# detailed changes can be viewed in %s\n",
8865 diff_path);
8868 err = edit_logmsg(logmsg, a->editor, a->logmsg_path, initial_content,
8869 initial_content_len, a->prepared_log ? 0 : 1);
8870 done:
8871 free(initial_content);
8872 free(template);
8873 free(prepared_msg);
8874 free(merged_msg);
8876 if (fd != -1 && close(fd) == -1 && err == NULL)
8877 err = got_error_from_errno2("close", a->logmsg_path);
8879 /* Editor is done; we can now apply unveil(2) */
8880 if (err == NULL)
8881 err = apply_unveil(a->repo_path, 0, a->worktree_path);
8882 if (err) {
8883 free(*logmsg);
8884 *logmsg = NULL;
8886 return err;
8889 static const struct got_error *
8890 cat_logmsg(FILE *f, struct got_commit_object *commit, const char *idstr,
8891 const char *type, int has_content)
8893 const struct got_error *err = NULL;
8894 char *logmsg = NULL;
8896 err = got_object_commit_get_logmsg(&logmsg, commit);
8897 if (err)
8898 return err;
8900 if (fprintf(f, "%s# log message of %s commit %s:%s",
8901 has_content ? "\n" : "", type, idstr, logmsg) < 0)
8902 err = got_ferror(f, GOT_ERR_IO);
8904 free(logmsg);
8905 return err;
8909 * Lookup "logmsg" references of backed-out and cherrypicked commits
8910 * belonging to the current work tree. If found, and the worktree has
8911 * at least one modified file that was changed in the referenced commit,
8912 * add its log message to a new temporary file at *logmsg_path.
8913 * Add all refs found to matched_refs to be scheduled for removal on
8914 * successful commit.
8916 static const struct got_error *
8917 lookup_logmsg_ref(char **logmsg_path, struct got_pathlist_head *paths,
8918 struct got_reflist_head *matched_refs, struct got_worktree *worktree,
8919 struct got_repository *repo)
8921 const struct got_error *err;
8922 struct got_commit_object *commit = NULL;
8923 struct got_object_id *id = NULL;
8924 struct got_reflist_head refs;
8925 struct got_reflist_entry *re, *re_match;
8926 FILE *f = NULL;
8927 char *uuidstr = NULL;
8928 int added_logmsg = 0;
8930 TAILQ_INIT(&refs);
8932 *logmsg_path = NULL;
8934 err = got_worktree_get_uuid(&uuidstr, worktree);
8935 if (err)
8936 goto done;
8938 err = got_ref_list(&refs, repo, "refs/got/worktree",
8939 got_ref_cmp_by_name, repo);
8940 if (err)
8941 goto done;
8943 TAILQ_FOREACH(re, &refs, entry) {
8944 const char *refname, *type;
8945 struct wt_commitable_path_arg wcpa;
8946 int add_logmsg = 0;
8948 refname = got_ref_get_name(re->ref);
8950 if (strncmp(refname, GOT_WORKTREE_CHERRYPICK_REF_PREFIX,
8951 GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN) == 0) {
8952 refname += GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN + 1;
8953 type = "cherrypicked";
8954 } else if (strncmp(refname, GOT_WORKTREE_BACKOUT_REF_PREFIX,
8955 GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN) == 0) {
8956 refname += GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN + 1;
8957 type = "backed-out";
8958 } else
8959 continue;
8961 if (strncmp(refname, uuidstr, GOT_WORKTREE_UUID_STRLEN) == 0)
8962 refname += GOT_WORKTREE_UUID_STRLEN + 1; /* skip '-' */
8963 else
8964 continue;
8966 err = got_repo_match_object_id(&id, NULL, refname,
8967 GOT_OBJ_TYPE_COMMIT, NULL, repo);
8968 if (err)
8969 goto done;
8971 err = got_object_open_as_commit(&commit, repo, id);
8972 if (err)
8973 goto done;
8975 wcpa.commit_paths = paths;
8976 wcpa.has_changes = &add_logmsg;
8978 err = commit_path_changed_in_worktree(&wcpa, id,
8979 worktree, repo);
8980 if (err)
8981 goto done;
8983 if (add_logmsg) {
8984 if (f == NULL) {
8985 err = got_opentemp_named(logmsg_path, &f,
8986 "got-commit-logmsg", "");
8987 if (err)
8988 goto done;
8990 err = cat_logmsg(f, commit, refname, type,
8991 added_logmsg);
8992 if (err)
8993 goto done;
8994 if (!added_logmsg)
8995 ++added_logmsg;
8997 err = got_reflist_entry_dup(&re_match, re);
8998 if (err)
8999 goto done;
9000 TAILQ_INSERT_HEAD(matched_refs, re_match, entry);
9003 got_object_commit_close(commit);
9004 commit = NULL;
9005 free(id);
9006 id = NULL;
9009 done:
9010 free(id);
9011 free(uuidstr);
9012 got_ref_list_free(&refs);
9013 if (commit)
9014 got_object_commit_close(commit);
9015 if (f && fclose(f) == EOF && err == NULL)
9016 err = got_error_from_errno("fclose");
9017 if (!added_logmsg) {
9018 if (*logmsg_path && unlink(*logmsg_path) != 0 && err == NULL)
9019 err = got_error_from_errno2("unlink", *logmsg_path);
9020 *logmsg_path = NULL;
9022 return err;
9025 static const struct got_error *
9026 cmd_commit(int argc, char *argv[])
9028 const struct got_error *error = NULL;
9029 struct got_worktree *worktree = NULL;
9030 struct got_repository *repo = NULL;
9031 char *cwd = NULL, *id_str = NULL;
9032 struct got_object_id *id = NULL;
9033 const char *logmsg = NULL;
9034 char *prepared_logmsg = NULL, *merged_logmsg = NULL;
9035 struct collect_commit_logmsg_arg cl_arg;
9036 const char *author = NULL;
9037 char *gitconfig_path = NULL, *editor = NULL, *committer = NULL;
9038 int ch, rebase_in_progress, histedit_in_progress, preserve_logmsg = 0;
9039 int allow_bad_symlinks = 0, non_interactive = 0, merge_in_progress = 0;
9040 int show_diff = 1;
9041 struct got_pathlist_head paths;
9042 struct got_reflist_head refs;
9043 struct got_reflist_entry *re;
9044 int *pack_fds = NULL;
9046 TAILQ_INIT(&refs);
9047 TAILQ_INIT(&paths);
9048 cl_arg.logmsg_path = NULL;
9050 while ((ch = getopt(argc, argv, "A:F:m:NnS")) != -1) {
9051 switch (ch) {
9052 case 'A':
9053 author = optarg;
9054 error = valid_author(author);
9055 if (error)
9056 return error;
9057 break;
9058 case 'F':
9059 if (logmsg != NULL)
9060 option_conflict('F', 'm');
9061 prepared_logmsg = realpath(optarg, NULL);
9062 if (prepared_logmsg == NULL)
9063 return got_error_from_errno2("realpath",
9064 optarg);
9065 break;
9066 case 'm':
9067 if (prepared_logmsg)
9068 option_conflict('m', 'F');
9069 logmsg = optarg;
9070 break;
9071 case 'N':
9072 non_interactive = 1;
9073 break;
9074 case 'n':
9075 show_diff = 0;
9076 break;
9077 case 'S':
9078 allow_bad_symlinks = 1;
9079 break;
9080 default:
9081 usage_commit();
9082 /* NOTREACHED */
9086 argc -= optind;
9087 argv += optind;
9089 #ifndef PROFILE
9090 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
9091 "unveil", NULL) == -1)
9092 err(1, "pledge");
9093 #endif
9094 cwd = getcwd(NULL, 0);
9095 if (cwd == NULL) {
9096 error = got_error_from_errno("getcwd");
9097 goto done;
9100 error = got_repo_pack_fds_open(&pack_fds);
9101 if (error != NULL)
9102 goto done;
9104 error = got_worktree_open(&worktree, cwd);
9105 if (error) {
9106 if (error->code == GOT_ERR_NOT_WORKTREE)
9107 error = wrap_not_worktree_error(error, "commit", cwd);
9108 goto done;
9111 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
9112 if (error)
9113 goto done;
9114 if (rebase_in_progress) {
9115 error = got_error(GOT_ERR_REBASING);
9116 goto done;
9119 error = got_worktree_histedit_in_progress(&histedit_in_progress,
9120 worktree);
9121 if (error)
9122 goto done;
9124 error = get_gitconfig_path(&gitconfig_path);
9125 if (error)
9126 goto done;
9127 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
9128 gitconfig_path, pack_fds);
9129 if (error != NULL)
9130 goto done;
9132 error = got_worktree_merge_in_progress(&merge_in_progress, worktree, repo);
9133 if (error)
9134 goto done;
9135 if (merge_in_progress) {
9136 error = got_error(GOT_ERR_MERGE_BUSY);
9137 goto done;
9140 error = get_author(&committer, repo, worktree);
9141 if (error)
9142 goto done;
9144 if (author != NULL && !strcmp(committer, author)) {
9145 error = got_error(GOT_ERR_COMMIT_REDUNDANT_AUTHOR);
9146 goto done;
9149 if (author == NULL)
9150 author = committer;
9153 * unveil(2) traverses exec(2); if an editor is used we have
9154 * to apply unveil after the log message has been written.
9156 if (logmsg == NULL || strlen(logmsg) == 0)
9157 error = get_editor(&editor);
9158 else
9159 error = apply_unveil(got_repo_get_path(repo), 0,
9160 got_worktree_get_root_path(worktree));
9161 if (error)
9162 goto done;
9164 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
9165 if (error)
9166 goto done;
9168 if (prepared_logmsg == NULL) {
9169 error = lookup_logmsg_ref(&merged_logmsg,
9170 argc > 0 ? &paths : NULL, &refs, worktree, repo);
9171 if (error)
9172 goto done;
9175 cl_arg.editor = editor;
9176 cl_arg.cmdline_log = logmsg;
9177 cl_arg.prepared_log = prepared_logmsg;
9178 cl_arg.merged_log = merged_logmsg;
9179 cl_arg.non_interactive = non_interactive;
9180 cl_arg.worktree_path = got_worktree_get_root_path(worktree);
9181 cl_arg.branch_name = got_worktree_get_head_ref_name(worktree);
9182 if (!histedit_in_progress) {
9183 if (strncmp(cl_arg.branch_name, "refs/heads/", 11) != 0) {
9184 error = got_error(GOT_ERR_COMMIT_BRANCH);
9185 goto done;
9187 cl_arg.branch_name += 11;
9189 cl_arg.repo_path = got_repo_get_path(repo);
9190 error = got_worktree_commit(&id, worktree, &paths, author, committer,
9191 allow_bad_symlinks, show_diff, collect_commit_logmsg, &cl_arg,
9192 print_status, NULL, repo);
9193 if (error) {
9194 if (error->code != GOT_ERR_COMMIT_MSG_EMPTY &&
9195 cl_arg.logmsg_path != NULL)
9196 preserve_logmsg = 1;
9197 goto done;
9200 error = got_object_id_str(&id_str, id);
9201 if (error)
9202 goto done;
9203 printf("Created commit %s\n", id_str);
9205 TAILQ_FOREACH(re, &refs, entry) {
9206 error = got_ref_delete(re->ref, repo);
9207 if (error)
9208 goto done;
9211 done:
9212 if (preserve_logmsg) {
9213 fprintf(stderr, "%s: log message preserved in %s\n",
9214 getprogname(), cl_arg.logmsg_path);
9215 } else if (cl_arg.logmsg_path && unlink(cl_arg.logmsg_path) == -1 &&
9216 error == NULL)
9217 error = got_error_from_errno2("unlink", cl_arg.logmsg_path);
9218 free(cl_arg.logmsg_path);
9219 if (merged_logmsg && unlink(merged_logmsg) == -1 && error == NULL)
9220 error = got_error_from_errno2("unlink", merged_logmsg);
9221 free(merged_logmsg);
9222 if (repo) {
9223 const struct got_error *close_err = got_repo_close(repo);
9224 if (error == NULL)
9225 error = close_err;
9227 if (worktree)
9228 got_worktree_close(worktree);
9229 if (pack_fds) {
9230 const struct got_error *pack_err =
9231 got_repo_pack_fds_close(pack_fds);
9232 if (error == NULL)
9233 error = pack_err;
9235 got_ref_list_free(&refs);
9236 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
9237 free(cwd);
9238 free(id_str);
9239 free(gitconfig_path);
9240 free(editor);
9241 free(committer);
9242 free(prepared_logmsg);
9243 return error;
9246 __dead static void
9247 usage_send(void)
9249 fprintf(stderr, "usage: %s send [-afqTv] [-b branch] [-d branch] "
9250 "[-r repository-path] [-t tag] [remote-repository]\n",
9251 getprogname());
9252 exit(1);
9255 static void
9256 print_load_info(int print_colored, int print_found, int print_trees,
9257 int ncolored, int nfound, int ntrees)
9259 if (print_colored) {
9260 printf("%d commit%s colored", ncolored,
9261 ncolored == 1 ? "" : "s");
9263 if (print_found) {
9264 printf("%s%d object%s found",
9265 ncolored > 0 ? "; " : "",
9266 nfound, nfound == 1 ? "" : "s");
9268 if (print_trees) {
9269 printf("; %d tree%s scanned", ntrees,
9270 ntrees == 1 ? "" : "s");
9274 struct got_send_progress_arg {
9275 char last_scaled_packsize[FMT_SCALED_STRSIZE];
9276 int verbosity;
9277 int last_ncolored;
9278 int last_nfound;
9279 int last_ntrees;
9280 int loading_done;
9281 int last_ncommits;
9282 int last_nobj_total;
9283 int last_p_deltify;
9284 int last_p_written;
9285 int last_p_sent;
9286 int printed_something;
9287 int sent_something;
9288 struct got_pathlist_head *delete_branches;
9291 static const struct got_error *
9292 send_progress(void *arg, int ncolored, int nfound, int ntrees,
9293 off_t packfile_size, int ncommits, int nobj_total, int nobj_deltify,
9294 int nobj_written, off_t bytes_sent, const char *refname,
9295 const char *errmsg, int success)
9297 struct got_send_progress_arg *a = arg;
9298 char scaled_packsize[FMT_SCALED_STRSIZE];
9299 char scaled_sent[FMT_SCALED_STRSIZE];
9300 int p_deltify = 0, p_written = 0, p_sent = 0;
9301 int print_colored = 0, print_found = 0, print_trees = 0;
9302 int print_searching = 0, print_total = 0;
9303 int print_deltify = 0, print_written = 0, print_sent = 0;
9305 if (a->verbosity < 0)
9306 return NULL;
9308 if (refname) {
9309 const char *status = success ? "accepted" : "rejected";
9311 if (success) {
9312 struct got_pathlist_entry *pe;
9313 TAILQ_FOREACH(pe, a->delete_branches, entry) {
9314 const char *branchname = pe->path;
9315 if (got_path_cmp(branchname, refname,
9316 strlen(branchname), strlen(refname)) == 0) {
9317 status = "deleted";
9318 a->sent_something = 1;
9319 break;
9324 if (a->printed_something)
9325 putchar('\n');
9326 printf("Server has %s %s", status, refname);
9327 if (errmsg)
9328 printf(": %s", errmsg);
9329 a->printed_something = 1;
9330 return NULL;
9333 if (a->last_ncolored != ncolored) {
9334 print_colored = 1;
9335 a->last_ncolored = ncolored;
9338 if (a->last_nfound != nfound) {
9339 print_colored = 1;
9340 print_found = 1;
9341 a->last_nfound = nfound;
9344 if (a->last_ntrees != ntrees) {
9345 print_colored = 1;
9346 print_found = 1;
9347 print_trees = 1;
9348 a->last_ntrees = ntrees;
9351 if ((print_colored || print_found || print_trees) &&
9352 !a->loading_done) {
9353 printf("\r");
9354 print_load_info(print_colored, print_found, print_trees,
9355 ncolored, nfound, ntrees);
9356 a->printed_something = 1;
9357 fflush(stdout);
9358 return NULL;
9359 } else if (!a->loading_done) {
9360 printf("\r");
9361 print_load_info(1, 1, 1, ncolored, nfound, ntrees);
9362 printf("\n");
9363 a->loading_done = 1;
9366 if (fmt_scaled(packfile_size, scaled_packsize) == -1)
9367 return got_error_from_errno("fmt_scaled");
9368 if (fmt_scaled(bytes_sent, scaled_sent) == -1)
9369 return got_error_from_errno("fmt_scaled");
9371 if (a->last_ncommits != ncommits) {
9372 print_searching = 1;
9373 a->last_ncommits = ncommits;
9376 if (a->last_nobj_total != nobj_total) {
9377 print_searching = 1;
9378 print_total = 1;
9379 a->last_nobj_total = nobj_total;
9382 if (packfile_size > 0 && (a->last_scaled_packsize[0] == '\0' ||
9383 strcmp(scaled_packsize, a->last_scaled_packsize)) != 0) {
9384 if (strlcpy(a->last_scaled_packsize, scaled_packsize,
9385 FMT_SCALED_STRSIZE) >= FMT_SCALED_STRSIZE)
9386 return got_error(GOT_ERR_NO_SPACE);
9389 if (nobj_deltify > 0 || nobj_written > 0) {
9390 if (nobj_deltify > 0) {
9391 p_deltify = (nobj_deltify * 100) / nobj_total;
9392 if (p_deltify != a->last_p_deltify) {
9393 a->last_p_deltify = p_deltify;
9394 print_searching = 1;
9395 print_total = 1;
9396 print_deltify = 1;
9399 if (nobj_written > 0) {
9400 p_written = (nobj_written * 100) / nobj_total;
9401 if (p_written != a->last_p_written) {
9402 a->last_p_written = p_written;
9403 print_searching = 1;
9404 print_total = 1;
9405 print_deltify = 1;
9406 print_written = 1;
9411 if (bytes_sent > 0) {
9412 p_sent = (bytes_sent * 100) / packfile_size;
9413 if (p_sent != a->last_p_sent) {
9414 a->last_p_sent = p_sent;
9415 print_searching = 1;
9416 print_total = 1;
9417 print_deltify = 1;
9418 print_written = 1;
9419 print_sent = 1;
9421 a->sent_something = 1;
9424 if (print_searching || print_total || print_deltify || print_written ||
9425 print_sent)
9426 printf("\r");
9427 if (print_searching)
9428 printf("packing %d reference%s", ncommits,
9429 ncommits == 1 ? "" : "s");
9430 if (print_total)
9431 printf("; %d object%s", nobj_total,
9432 nobj_total == 1 ? "" : "s");
9433 if (print_deltify)
9434 printf("; deltify: %d%%", p_deltify);
9435 if (print_sent)
9436 printf("; uploading pack: %*s %d%%", FMT_SCALED_STRSIZE - 2,
9437 scaled_packsize, p_sent);
9438 else if (print_written)
9439 printf("; writing pack: %*s %d%%", FMT_SCALED_STRSIZE - 2,
9440 scaled_packsize, p_written);
9441 if (print_searching || print_total || print_deltify ||
9442 print_written || print_sent) {
9443 a->printed_something = 1;
9444 fflush(stdout);
9446 return NULL;
9449 static const struct got_error *
9450 cmd_send(int argc, char *argv[])
9452 const struct got_error *error = NULL;
9453 char *cwd = NULL, *repo_path = NULL;
9454 const char *remote_name;
9455 char *proto = NULL, *host = NULL, *port = NULL;
9456 char *repo_name = NULL, *server_path = NULL;
9457 const struct got_remote_repo *remotes, *remote = NULL;
9458 int nremotes, nbranches = 0, ndelete_branches = 0;
9459 struct got_repository *repo = NULL;
9460 struct got_worktree *worktree = NULL;
9461 const struct got_gotconfig *repo_conf = NULL, *worktree_conf = NULL;
9462 struct got_pathlist_head branches;
9463 struct got_pathlist_head tags;
9464 struct got_reflist_head all_branches;
9465 struct got_reflist_head all_tags;
9466 struct got_pathlist_head delete_args;
9467 struct got_pathlist_head delete_branches;
9468 struct got_reflist_entry *re;
9469 struct got_pathlist_entry *pe;
9470 int i, ch, sendfd = -1, sendstatus;
9471 pid_t sendpid = -1;
9472 struct got_send_progress_arg spa;
9473 int verbosity = 0, overwrite_refs = 0;
9474 int send_all_branches = 0, send_all_tags = 0;
9475 struct got_reference *ref = NULL;
9476 int *pack_fds = NULL;
9478 TAILQ_INIT(&branches);
9479 TAILQ_INIT(&tags);
9480 TAILQ_INIT(&all_branches);
9481 TAILQ_INIT(&all_tags);
9482 TAILQ_INIT(&delete_args);
9483 TAILQ_INIT(&delete_branches);
9485 while ((ch = getopt(argc, argv, "ab:d:fqr:Tt:v")) != -1) {
9486 switch (ch) {
9487 case 'a':
9488 send_all_branches = 1;
9489 break;
9490 case 'b':
9491 error = got_pathlist_append(&branches, optarg, NULL);
9492 if (error)
9493 return error;
9494 nbranches++;
9495 break;
9496 case 'd':
9497 error = got_pathlist_append(&delete_args, optarg, NULL);
9498 if (error)
9499 return error;
9500 break;
9501 case 'f':
9502 overwrite_refs = 1;
9503 break;
9504 case 'q':
9505 verbosity = -1;
9506 break;
9507 case 'r':
9508 repo_path = realpath(optarg, NULL);
9509 if (repo_path == NULL)
9510 return got_error_from_errno2("realpath",
9511 optarg);
9512 got_path_strip_trailing_slashes(repo_path);
9513 break;
9514 case 'T':
9515 send_all_tags = 1;
9516 break;
9517 case 't':
9518 error = got_pathlist_append(&tags, optarg, NULL);
9519 if (error)
9520 return error;
9521 break;
9522 case 'v':
9523 if (verbosity < 0)
9524 verbosity = 0;
9525 else if (verbosity < 3)
9526 verbosity++;
9527 break;
9528 default:
9529 usage_send();
9530 /* NOTREACHED */
9533 argc -= optind;
9534 argv += optind;
9536 if (send_all_branches && !TAILQ_EMPTY(&branches))
9537 option_conflict('a', 'b');
9538 if (send_all_tags && !TAILQ_EMPTY(&tags))
9539 option_conflict('T', 't');
9542 if (argc == 0)
9543 remote_name = GOT_SEND_DEFAULT_REMOTE_NAME;
9544 else if (argc == 1)
9545 remote_name = argv[0];
9546 else
9547 usage_send();
9549 cwd = getcwd(NULL, 0);
9550 if (cwd == NULL) {
9551 error = got_error_from_errno("getcwd");
9552 goto done;
9555 error = got_repo_pack_fds_open(&pack_fds);
9556 if (error != NULL)
9557 goto done;
9559 if (repo_path == NULL) {
9560 error = got_worktree_open(&worktree, cwd);
9561 if (error && error->code != GOT_ERR_NOT_WORKTREE)
9562 goto done;
9563 else
9564 error = NULL;
9565 if (worktree) {
9566 repo_path =
9567 strdup(got_worktree_get_repo_path(worktree));
9568 if (repo_path == NULL)
9569 error = got_error_from_errno("strdup");
9570 if (error)
9571 goto done;
9572 } else {
9573 repo_path = strdup(cwd);
9574 if (repo_path == NULL) {
9575 error = got_error_from_errno("strdup");
9576 goto done;
9581 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
9582 if (error)
9583 goto done;
9585 if (worktree) {
9586 worktree_conf = got_worktree_get_gotconfig(worktree);
9587 if (worktree_conf) {
9588 got_gotconfig_get_remotes(&nremotes, &remotes,
9589 worktree_conf);
9590 for (i = 0; i < nremotes; i++) {
9591 if (strcmp(remotes[i].name, remote_name) == 0) {
9592 remote = &remotes[i];
9593 break;
9598 if (remote == NULL) {
9599 repo_conf = got_repo_get_gotconfig(repo);
9600 if (repo_conf) {
9601 got_gotconfig_get_remotes(&nremotes, &remotes,
9602 repo_conf);
9603 for (i = 0; i < nremotes; i++) {
9604 if (strcmp(remotes[i].name, remote_name) == 0) {
9605 remote = &remotes[i];
9606 break;
9611 if (remote == NULL) {
9612 got_repo_get_gitconfig_remotes(&nremotes, &remotes, repo);
9613 for (i = 0; i < nremotes; i++) {
9614 if (strcmp(remotes[i].name, remote_name) == 0) {
9615 remote = &remotes[i];
9616 break;
9620 if (remote == NULL) {
9621 error = got_error_path(remote_name, GOT_ERR_NO_REMOTE);
9622 goto done;
9625 error = got_dial_parse_uri(&proto, &host, &port, &server_path,
9626 &repo_name, remote->send_url);
9627 if (error)
9628 goto done;
9630 if (strcmp(proto, "git") == 0) {
9631 #ifndef PROFILE
9632 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
9633 "sendfd dns inet unveil", NULL) == -1)
9634 err(1, "pledge");
9635 #endif
9636 } else if (strcmp(proto, "git+ssh") == 0 ||
9637 strcmp(proto, "ssh") == 0) {
9638 #ifndef PROFILE
9639 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
9640 "sendfd unveil", NULL) == -1)
9641 err(1, "pledge");
9642 #endif
9643 } else if (strcmp(proto, "http") == 0 ||
9644 strcmp(proto, "git+http") == 0) {
9645 error = got_error_path(proto, GOT_ERR_NOT_IMPL);
9646 goto done;
9647 } else {
9648 error = got_error_path(proto, GOT_ERR_BAD_PROTO);
9649 goto done;
9652 error = got_dial_apply_unveil(proto);
9653 if (error)
9654 goto done;
9656 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
9657 if (error)
9658 goto done;
9660 if (send_all_branches) {
9661 error = got_ref_list(&all_branches, repo, "refs/heads",
9662 got_ref_cmp_by_name, NULL);
9663 if (error)
9664 goto done;
9665 TAILQ_FOREACH(re, &all_branches, entry) {
9666 const char *branchname = got_ref_get_name(re->ref);
9667 error = got_pathlist_append(&branches,
9668 branchname, NULL);
9669 if (error)
9670 goto done;
9671 nbranches++;
9673 } else if (nbranches == 0) {
9674 for (i = 0; i < remote->nsend_branches; i++) {
9675 error = got_pathlist_append(&branches,
9676 remote->send_branches[i], NULL);
9677 if (error)
9678 goto done;
9682 if (send_all_tags) {
9683 error = got_ref_list(&all_tags, repo, "refs/tags",
9684 got_ref_cmp_by_name, NULL);
9685 if (error)
9686 goto done;
9687 TAILQ_FOREACH(re, &all_tags, entry) {
9688 const char *tagname = got_ref_get_name(re->ref);
9689 error = got_pathlist_append(&tags,
9690 tagname, NULL);
9691 if (error)
9692 goto done;
9697 * To prevent accidents only branches in refs/heads/ can be deleted
9698 * with 'got send -d'.
9699 * Deleting anything else requires local repository access or Git.
9701 TAILQ_FOREACH(pe, &delete_args, entry) {
9702 const char *branchname = pe->path;
9703 char *s;
9704 struct got_pathlist_entry *new;
9705 if (strncmp(branchname, "refs/heads/", 11) == 0) {
9706 s = strdup(branchname);
9707 if (s == NULL) {
9708 error = got_error_from_errno("strdup");
9709 goto done;
9711 } else {
9712 if (asprintf(&s, "refs/heads/%s", branchname) == -1) {
9713 error = got_error_from_errno("asprintf");
9714 goto done;
9717 error = got_pathlist_insert(&new, &delete_branches, s, NULL);
9718 if (error || new == NULL /* duplicate */)
9719 free(s);
9720 if (error)
9721 goto done;
9722 ndelete_branches++;
9725 if (nbranches == 0 && ndelete_branches == 0) {
9726 struct got_reference *head_ref;
9727 if (worktree)
9728 error = got_ref_open(&head_ref, repo,
9729 got_worktree_get_head_ref_name(worktree), 0);
9730 else
9731 error = got_ref_open(&head_ref, repo, GOT_REF_HEAD, 0);
9732 if (error)
9733 goto done;
9734 if (got_ref_is_symbolic(head_ref)) {
9735 error = got_ref_resolve_symbolic(&ref, repo, head_ref);
9736 got_ref_close(head_ref);
9737 if (error)
9738 goto done;
9739 } else
9740 ref = head_ref;
9741 error = got_pathlist_append(&branches, got_ref_get_name(ref),
9742 NULL);
9743 if (error)
9744 goto done;
9745 nbranches++;
9748 if (verbosity >= 0) {
9749 printf("Connecting to \"%s\" %s://%s%s%s%s%s\n",
9750 remote->name, proto, host,
9751 port ? ":" : "", port ? port : "",
9752 *server_path == '/' ? "" : "/", server_path);
9755 error = got_send_connect(&sendpid, &sendfd, proto, host, port,
9756 server_path, verbosity);
9757 if (error)
9758 goto done;
9760 memset(&spa, 0, sizeof(spa));
9761 spa.last_scaled_packsize[0] = '\0';
9762 spa.last_p_deltify = -1;
9763 spa.last_p_written = -1;
9764 spa.verbosity = verbosity;
9765 spa.delete_branches = &delete_branches;
9766 error = got_send_pack(remote_name, &branches, &tags, &delete_branches,
9767 verbosity, overwrite_refs, sendfd, repo, send_progress, &spa,
9768 check_cancelled, NULL);
9769 if (spa.printed_something)
9770 putchar('\n');
9771 if (error)
9772 goto done;
9773 if (!spa.sent_something && verbosity >= 0)
9774 printf("Already up-to-date\n");
9775 done:
9776 if (sendpid > 0) {
9777 if (kill(sendpid, SIGTERM) == -1)
9778 error = got_error_from_errno("kill");
9779 if (waitpid(sendpid, &sendstatus, 0) == -1 && error == NULL)
9780 error = got_error_from_errno("waitpid");
9782 if (sendfd != -1 && close(sendfd) == -1 && error == NULL)
9783 error = got_error_from_errno("close");
9784 if (repo) {
9785 const struct got_error *close_err = got_repo_close(repo);
9786 if (error == NULL)
9787 error = close_err;
9789 if (worktree)
9790 got_worktree_close(worktree);
9791 if (pack_fds) {
9792 const struct got_error *pack_err =
9793 got_repo_pack_fds_close(pack_fds);
9794 if (error == NULL)
9795 error = pack_err;
9797 if (ref)
9798 got_ref_close(ref);
9799 got_pathlist_free(&branches, GOT_PATHLIST_FREE_NONE);
9800 got_pathlist_free(&tags, GOT_PATHLIST_FREE_NONE);
9801 got_ref_list_free(&all_branches);
9802 got_ref_list_free(&all_tags);
9803 got_pathlist_free(&delete_args, GOT_PATHLIST_FREE_NONE);
9804 got_pathlist_free(&delete_branches, GOT_PATHLIST_FREE_PATH);
9805 free(cwd);
9806 free(repo_path);
9807 free(proto);
9808 free(host);
9809 free(port);
9810 free(server_path);
9811 free(repo_name);
9812 return error;
9816 * Print and if delete is set delete all ref_prefix references.
9817 * If wanted_ref is not NULL, only print or delete this reference.
9819 static const struct got_error *
9820 process_logmsg_refs(const char *ref_prefix, size_t prefix_len,
9821 const char *wanted_ref, int delete, struct got_worktree *worktree,
9822 struct got_repository *repo)
9824 const struct got_error *err;
9825 struct got_pathlist_head paths;
9826 struct got_reflist_head refs;
9827 struct got_reflist_entry *re;
9828 struct got_reflist_object_id_map *refs_idmap = NULL;
9829 struct got_commit_object *commit = NULL;
9830 struct got_object_id *id = NULL;
9831 const char *header_prefix;
9832 char *uuidstr = NULL;
9833 int found = 0;
9835 TAILQ_INIT(&refs);
9836 TAILQ_INIT(&paths);
9838 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, repo);
9839 if (err)
9840 goto done;
9842 err = got_reflist_object_id_map_create(&refs_idmap, &refs, repo);
9843 if (err)
9844 goto done;
9846 if (worktree != NULL) {
9847 err = got_worktree_get_uuid(&uuidstr, worktree);
9848 if (err)
9849 goto done;
9852 if (wanted_ref) {
9853 if (strncmp(wanted_ref, "refs/heads/", 11) == 0)
9854 wanted_ref += 11;
9857 if (strcmp(ref_prefix, GOT_WORKTREE_BACKOUT_REF_PREFIX) == 0)
9858 header_prefix = "backout";
9859 else
9860 header_prefix = "cherrypick";
9862 TAILQ_FOREACH(re, &refs, entry) {
9863 const char *refname, *wt;
9865 refname = got_ref_get_name(re->ref);
9867 err = check_cancelled(NULL);
9868 if (err)
9869 goto done;
9871 if (strncmp(refname, ref_prefix, prefix_len) == 0)
9872 refname += prefix_len + 1; /* skip '-' delimiter */
9873 else
9874 continue;
9876 wt = refname;
9878 if (worktree == NULL || strncmp(refname, uuidstr,
9879 GOT_WORKTREE_UUID_STRLEN) == 0)
9880 refname += GOT_WORKTREE_UUID_STRLEN + 1; /* skip '-' */
9881 else
9882 continue;
9884 err = got_repo_match_object_id(&id, NULL, refname,
9885 GOT_OBJ_TYPE_COMMIT, NULL, repo);
9886 if (err)
9887 goto done;
9889 err = got_object_open_as_commit(&commit, repo, id);
9890 if (err)
9891 goto done;
9893 if (wanted_ref)
9894 found = strncmp(wanted_ref, refname,
9895 strlen(wanted_ref)) == 0;
9896 if (wanted_ref && !found) {
9897 struct got_reflist_head *ci_refs;
9899 ci_refs = got_reflist_object_id_map_lookup(refs_idmap,
9900 id);
9902 if (ci_refs) {
9903 char *refs_str = NULL;
9904 char const *r = NULL;
9906 err = build_refs_str(&refs_str, ci_refs, id,
9907 repo, 1);
9908 if (err)
9909 goto done;
9911 r = refs_str;
9912 while (r) {
9913 if (strncmp(r, wanted_ref,
9914 strlen(wanted_ref)) == 0) {
9915 found = 1;
9916 break;
9918 r = strchr(r, ' ');
9919 if (r)
9920 ++r;
9922 free(refs_str);
9926 if (wanted_ref == NULL || found) {
9927 if (delete) {
9928 err = got_ref_delete(re->ref, repo);
9929 if (err)
9930 goto done;
9931 printf("Deleted: ");
9932 err = print_commit_oneline(commit, id, repo,
9933 refs_idmap);
9934 } else {
9936 * Print paths modified by commit to help
9937 * associate commits with worktree changes.
9939 err = get_changed_paths(&paths, commit,
9940 repo, NULL);
9941 if (err)
9942 goto done;
9944 err = print_commit(commit, id, repo, NULL,
9945 &paths, NULL, 0, 0, refs_idmap, NULL,
9946 header_prefix);
9947 got_pathlist_free(&paths,
9948 GOT_PATHLIST_FREE_ALL);
9950 if (worktree == NULL)
9951 printf("work tree: %.*s\n\n",
9952 GOT_WORKTREE_UUID_STRLEN, wt);
9954 if (err || found)
9955 goto done;
9958 got_object_commit_close(commit);
9959 commit = NULL;
9960 free(id);
9961 id = NULL;
9964 if (wanted_ref != NULL && !found)
9965 err = got_error_fmt(GOT_ERR_NOT_REF, "%s", wanted_ref);
9967 done:
9968 free(id);
9969 free(uuidstr);
9970 got_ref_list_free(&refs);
9971 got_pathlist_free(&paths, GOT_PATHLIST_FREE_ALL);
9972 if (refs_idmap)
9973 got_reflist_object_id_map_free(refs_idmap);
9974 if (commit)
9975 got_object_commit_close(commit);
9976 return err;
9980 * Create new temp "logmsg" ref of the backed-out or cherrypicked commit
9981 * identified by id for log messages to prepopulate the editor on commit.
9983 static const struct got_error *
9984 logmsg_ref(struct got_object_id *id, const char *prefix,
9985 struct got_worktree *worktree, struct got_repository *repo)
9987 const struct got_error *err = NULL;
9988 char *idstr, *ref = NULL, *refname = NULL;
9989 int histedit_in_progress;
9990 int rebase_in_progress, merge_in_progress;
9993 * Silenty refuse to create merge reference if any histedit, merge,
9994 * or rebase operation is in progress.
9996 err = got_worktree_histedit_in_progress(&histedit_in_progress,
9997 worktree);
9998 if (err)
9999 return err;
10000 if (histedit_in_progress)
10001 return NULL;
10003 err = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
10004 if (err)
10005 return err;
10006 if (rebase_in_progress)
10007 return NULL;
10009 err = got_worktree_merge_in_progress(&merge_in_progress, worktree,
10010 repo);
10011 if (err)
10012 return err;
10013 if (merge_in_progress)
10014 return NULL;
10016 err = got_object_id_str(&idstr, id);
10017 if (err)
10018 return err;
10020 err = got_worktree_get_logmsg_ref_name(&refname, worktree, prefix);
10021 if (err)
10022 goto done;
10024 if (asprintf(&ref, "%s-%s", refname, idstr) == -1) {
10025 err = got_error_from_errno("asprintf");
10026 goto done;
10029 err = create_ref(ref, got_worktree_get_base_commit_id(worktree),
10030 -1, repo);
10031 done:
10032 free(ref);
10033 free(idstr);
10034 free(refname);
10035 return err;
10038 __dead static void
10039 usage_cherrypick(void)
10041 fprintf(stderr, "usage: %s cherrypick [-lX] [commit-id]\n",
10042 getprogname());
10043 exit(1);
10046 static const struct got_error *
10047 cmd_cherrypick(int argc, char *argv[])
10049 const struct got_error *error = NULL;
10050 struct got_worktree *worktree = NULL;
10051 struct got_repository *repo = NULL;
10052 char *cwd = NULL, *commit_id_str = NULL;
10053 struct got_object_id *commit_id = NULL;
10054 struct got_commit_object *commit = NULL;
10055 struct got_object_qid *pid;
10056 int ch, list_refs = 0, remove_refs = 0;
10057 struct got_update_progress_arg upa;
10058 int *pack_fds = NULL;
10060 while ((ch = getopt(argc, argv, "lX")) != -1) {
10061 switch (ch) {
10062 case 'l':
10063 list_refs = 1;
10064 break;
10065 case 'X':
10066 remove_refs = 1;
10067 break;
10068 default:
10069 usage_cherrypick();
10070 /* NOTREACHED */
10074 argc -= optind;
10075 argv += optind;
10077 #ifndef PROFILE
10078 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
10079 "unveil", NULL) == -1)
10080 err(1, "pledge");
10081 #endif
10082 if (list_refs || remove_refs) {
10083 if (argc != 0 && argc != 1)
10084 usage_cherrypick();
10085 } else if (argc != 1)
10086 usage_cherrypick();
10087 if (list_refs && remove_refs)
10088 option_conflict('l', 'X');
10090 cwd = getcwd(NULL, 0);
10091 if (cwd == NULL) {
10092 error = got_error_from_errno("getcwd");
10093 goto done;
10096 error = got_repo_pack_fds_open(&pack_fds);
10097 if (error != NULL)
10098 goto done;
10100 error = got_worktree_open(&worktree, cwd);
10101 if (error) {
10102 if (list_refs || remove_refs) {
10103 if (error->code != GOT_ERR_NOT_WORKTREE)
10104 goto done;
10105 } else {
10106 if (error->code == GOT_ERR_NOT_WORKTREE)
10107 error = wrap_not_worktree_error(error,
10108 "cherrypick", cwd);
10109 goto done;
10113 error = got_repo_open(&repo,
10114 worktree ? got_worktree_get_repo_path(worktree) : cwd,
10115 NULL, pack_fds);
10116 if (error != NULL)
10117 goto done;
10119 error = apply_unveil(got_repo_get_path(repo), 0,
10120 worktree ? got_worktree_get_root_path(worktree) : NULL);
10121 if (error)
10122 goto done;
10124 if (list_refs || remove_refs) {
10125 error = process_logmsg_refs(GOT_WORKTREE_CHERRYPICK_REF_PREFIX,
10126 GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN,
10127 argc == 1 ? argv[0] : NULL, remove_refs, worktree, repo);
10128 goto done;
10131 error = got_repo_match_object_id(&commit_id, NULL, argv[0],
10132 GOT_OBJ_TYPE_COMMIT, NULL, repo);
10133 if (error)
10134 goto done;
10135 error = got_object_id_str(&commit_id_str, commit_id);
10136 if (error)
10137 goto done;
10139 error = got_object_open_as_commit(&commit, repo, commit_id);
10140 if (error)
10141 goto done;
10142 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
10143 memset(&upa, 0, sizeof(upa));
10144 error = got_worktree_merge_files(worktree, pid ? &pid->id : NULL,
10145 commit_id, repo, update_progress, &upa, check_cancelled,
10146 NULL);
10147 if (error != NULL)
10148 goto done;
10150 if (upa.did_something) {
10151 error = logmsg_ref(commit_id,
10152 GOT_WORKTREE_CHERRYPICK_REF_PREFIX, worktree, repo);
10153 if (error)
10154 goto done;
10155 printf("Merged commit %s\n", commit_id_str);
10157 print_merge_progress_stats(&upa);
10158 done:
10159 free(cwd);
10160 if (commit)
10161 got_object_commit_close(commit);
10162 free(commit_id_str);
10163 if (worktree)
10164 got_worktree_close(worktree);
10165 if (repo) {
10166 const struct got_error *close_err = got_repo_close(repo);
10167 if (error == NULL)
10168 error = close_err;
10170 if (pack_fds) {
10171 const struct got_error *pack_err =
10172 got_repo_pack_fds_close(pack_fds);
10173 if (error == NULL)
10174 error = pack_err;
10177 return error;
10180 __dead static void
10181 usage_backout(void)
10183 fprintf(stderr, "usage: %s backout [-lX] [commit-id]\n", getprogname());
10184 exit(1);
10187 static const struct got_error *
10188 cmd_backout(int argc, char *argv[])
10190 const struct got_error *error = NULL;
10191 struct got_worktree *worktree = NULL;
10192 struct got_repository *repo = NULL;
10193 char *cwd = NULL, *commit_id_str = NULL;
10194 struct got_object_id *commit_id = NULL;
10195 struct got_commit_object *commit = NULL;
10196 struct got_object_qid *pid;
10197 int ch, list_refs = 0, remove_refs = 0;
10198 struct got_update_progress_arg upa;
10199 int *pack_fds = NULL;
10201 while ((ch = getopt(argc, argv, "lX")) != -1) {
10202 switch (ch) {
10203 case 'l':
10204 list_refs = 1;
10205 break;
10206 case 'X':
10207 remove_refs = 1;
10208 break;
10209 default:
10210 usage_backout();
10211 /* NOTREACHED */
10215 argc -= optind;
10216 argv += optind;
10218 #ifndef PROFILE
10219 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
10220 "unveil", NULL) == -1)
10221 err(1, "pledge");
10222 #endif
10223 if (list_refs || remove_refs) {
10224 if (argc != 0 && argc != 1)
10225 usage_backout();
10226 } else if (argc != 1)
10227 usage_backout();
10228 if (list_refs && remove_refs)
10229 option_conflict('l', 'X');
10231 cwd = getcwd(NULL, 0);
10232 if (cwd == NULL) {
10233 error = got_error_from_errno("getcwd");
10234 goto done;
10237 error = got_repo_pack_fds_open(&pack_fds);
10238 if (error != NULL)
10239 goto done;
10241 error = got_worktree_open(&worktree, cwd);
10242 if (error) {
10243 if (list_refs || remove_refs) {
10244 if (error->code != GOT_ERR_NOT_WORKTREE)
10245 goto done;
10246 } else {
10247 if (error->code == GOT_ERR_NOT_WORKTREE)
10248 error = wrap_not_worktree_error(error,
10249 "backout", cwd);
10250 goto done;
10254 error = got_repo_open(&repo,
10255 worktree ? got_worktree_get_repo_path(worktree) : cwd,
10256 NULL, pack_fds);
10257 if (error != NULL)
10258 goto done;
10260 error = apply_unveil(got_repo_get_path(repo), 0,
10261 worktree ? got_worktree_get_root_path(worktree) : NULL);
10262 if (error)
10263 goto done;
10265 if (list_refs || remove_refs) {
10266 error = process_logmsg_refs(GOT_WORKTREE_BACKOUT_REF_PREFIX,
10267 GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN,
10268 argc == 1 ? argv[0] : NULL, remove_refs, worktree, repo);
10269 goto done;
10272 error = got_repo_match_object_id(&commit_id, NULL, argv[0],
10273 GOT_OBJ_TYPE_COMMIT, NULL, repo);
10274 if (error)
10275 goto done;
10276 error = got_object_id_str(&commit_id_str, commit_id);
10277 if (error)
10278 goto done;
10280 error = got_object_open_as_commit(&commit, repo, commit_id);
10281 if (error)
10282 goto done;
10283 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
10284 if (pid == NULL) {
10285 error = got_error(GOT_ERR_ROOT_COMMIT);
10286 goto done;
10289 memset(&upa, 0, sizeof(upa));
10290 error = got_worktree_merge_files(worktree, commit_id, &pid->id,
10291 repo, update_progress, &upa, check_cancelled, NULL);
10292 if (error != NULL)
10293 goto done;
10295 if (upa.did_something) {
10296 error = logmsg_ref(commit_id, GOT_WORKTREE_BACKOUT_REF_PREFIX,
10297 worktree, repo);
10298 if (error)
10299 goto done;
10300 printf("Backed out commit %s\n", commit_id_str);
10302 print_merge_progress_stats(&upa);
10303 done:
10304 free(cwd);
10305 if (commit)
10306 got_object_commit_close(commit);
10307 free(commit_id_str);
10308 if (worktree)
10309 got_worktree_close(worktree);
10310 if (repo) {
10311 const struct got_error *close_err = got_repo_close(repo);
10312 if (error == NULL)
10313 error = close_err;
10315 if (pack_fds) {
10316 const struct got_error *pack_err =
10317 got_repo_pack_fds_close(pack_fds);
10318 if (error == NULL)
10319 error = pack_err;
10321 return error;
10324 __dead static void
10325 usage_rebase(void)
10327 fprintf(stderr, "usage: %s rebase [-aclX] [branch]\n", getprogname());
10328 exit(1);
10331 static void
10332 trim_logmsg(char *logmsg, int limit)
10334 char *nl;
10335 size_t len;
10337 len = strlen(logmsg);
10338 if (len > limit)
10339 len = limit;
10340 logmsg[len] = '\0';
10341 nl = strchr(logmsg, '\n');
10342 if (nl)
10343 *nl = '\0';
10346 static const struct got_error *
10347 get_short_logmsg(char **logmsg, int limit, struct got_commit_object *commit)
10349 const struct got_error *err;
10350 char *logmsg0 = NULL;
10351 const char *s;
10353 err = got_object_commit_get_logmsg(&logmsg0, commit);
10354 if (err)
10355 return err;
10357 s = logmsg0;
10358 while (isspace((unsigned char)s[0]))
10359 s++;
10361 *logmsg = strdup(s);
10362 if (*logmsg == NULL) {
10363 err = got_error_from_errno("strdup");
10364 goto done;
10367 trim_logmsg(*logmsg, limit);
10368 done:
10369 free(logmsg0);
10370 return err;
10373 static const struct got_error *
10374 show_rebase_merge_conflict(struct got_object_id *id,
10375 struct got_repository *repo)
10377 const struct got_error *err;
10378 struct got_commit_object *commit = NULL;
10379 char *id_str = NULL, *logmsg = NULL;
10381 err = got_object_open_as_commit(&commit, repo, id);
10382 if (err)
10383 return err;
10385 err = got_object_id_str(&id_str, id);
10386 if (err)
10387 goto done;
10389 id_str[12] = '\0';
10391 err = get_short_logmsg(&logmsg, 42, commit);
10392 if (err)
10393 goto done;
10395 printf("%s -> merge conflict: %s\n", id_str, logmsg);
10396 done:
10397 free(id_str);
10398 got_object_commit_close(commit);
10399 free(logmsg);
10400 return err;
10403 static const struct got_error *
10404 show_rebase_progress(struct got_commit_object *commit,
10405 struct got_object_id *old_id, struct got_object_id *new_id)
10407 const struct got_error *err;
10408 char *old_id_str = NULL, *new_id_str = NULL, *logmsg = NULL;
10410 err = got_object_id_str(&old_id_str, old_id);
10411 if (err)
10412 goto done;
10414 if (new_id) {
10415 err = got_object_id_str(&new_id_str, new_id);
10416 if (err)
10417 goto done;
10420 old_id_str[12] = '\0';
10421 if (new_id_str)
10422 new_id_str[12] = '\0';
10424 err = get_short_logmsg(&logmsg, 42, commit);
10425 if (err)
10426 goto done;
10428 printf("%s -> %s: %s\n", old_id_str,
10429 new_id_str ? new_id_str : "no-op change", logmsg);
10430 done:
10431 free(old_id_str);
10432 free(new_id_str);
10433 free(logmsg);
10434 return err;
10437 static const struct got_error *
10438 rebase_complete(struct got_worktree *worktree, struct got_fileindex *fileindex,
10439 struct got_reference *branch, struct got_reference *tmp_branch,
10440 struct got_repository *repo, int create_backup)
10442 printf("Switching work tree to %s\n", got_ref_get_name(branch));
10443 return got_worktree_rebase_complete(worktree, fileindex,
10444 tmp_branch, branch, repo, create_backup);
10447 static const struct got_error *
10448 rebase_commit(struct got_pathlist_head *merged_paths,
10449 struct got_worktree *worktree, struct got_fileindex *fileindex,
10450 struct got_reference *tmp_branch, const char *committer,
10451 struct got_object_id *commit_id, struct got_repository *repo)
10453 const struct got_error *error;
10454 struct got_commit_object *commit;
10455 struct got_object_id *new_commit_id;
10457 error = got_object_open_as_commit(&commit, repo, commit_id);
10458 if (error)
10459 return error;
10461 error = got_worktree_rebase_commit(&new_commit_id, merged_paths,
10462 worktree, fileindex, tmp_branch, committer, commit, commit_id,
10463 repo);
10464 if (error) {
10465 if (error->code != GOT_ERR_COMMIT_NO_CHANGES)
10466 goto done;
10467 error = show_rebase_progress(commit, commit_id, NULL);
10468 } else {
10469 error = show_rebase_progress(commit, commit_id, new_commit_id);
10470 free(new_commit_id);
10472 done:
10473 got_object_commit_close(commit);
10474 return error;
10477 struct check_path_prefix_arg {
10478 const char *path_prefix;
10479 size_t len;
10480 int errcode;
10483 static const struct got_error *
10484 check_path_prefix_in_diff(void *arg, struct got_blob_object *blob1,
10485 struct got_blob_object *blob2, FILE *f1, FILE *f2,
10486 struct got_object_id *id1, struct got_object_id *id2,
10487 const char *path1, const char *path2,
10488 mode_t mode1, mode_t mode2, struct got_repository *repo)
10490 struct check_path_prefix_arg *a = arg;
10492 if ((path1 && !got_path_is_child(path1, a->path_prefix, a->len)) ||
10493 (path2 && !got_path_is_child(path2, a->path_prefix, a->len)))
10494 return got_error(a->errcode);
10496 return NULL;
10499 static const struct got_error *
10500 check_path_prefix(struct got_object_id *parent_id,
10501 struct got_object_id *commit_id, const char *path_prefix,
10502 int errcode, struct got_repository *repo)
10504 const struct got_error *err;
10505 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
10506 struct got_commit_object *commit = NULL, *parent_commit = NULL;
10507 struct check_path_prefix_arg cpp_arg;
10509 if (got_path_is_root_dir(path_prefix))
10510 return NULL;
10512 err = got_object_open_as_commit(&commit, repo, commit_id);
10513 if (err)
10514 goto done;
10516 err = got_object_open_as_commit(&parent_commit, repo, parent_id);
10517 if (err)
10518 goto done;
10520 err = got_object_open_as_tree(&tree1, repo,
10521 got_object_commit_get_tree_id(parent_commit));
10522 if (err)
10523 goto done;
10525 err = got_object_open_as_tree(&tree2, repo,
10526 got_object_commit_get_tree_id(commit));
10527 if (err)
10528 goto done;
10530 cpp_arg.path_prefix = path_prefix;
10531 while (cpp_arg.path_prefix[0] == '/')
10532 cpp_arg.path_prefix++;
10533 cpp_arg.len = strlen(cpp_arg.path_prefix);
10534 cpp_arg.errcode = errcode;
10535 err = got_diff_tree(tree1, tree2, NULL, NULL, -1, -1, "", "", repo,
10536 check_path_prefix_in_diff, &cpp_arg, 0);
10537 done:
10538 if (tree1)
10539 got_object_tree_close(tree1);
10540 if (tree2)
10541 got_object_tree_close(tree2);
10542 if (commit)
10543 got_object_commit_close(commit);
10544 if (parent_commit)
10545 got_object_commit_close(parent_commit);
10546 return err;
10549 static const struct got_error *
10550 collect_commits(struct got_object_id_queue *commits,
10551 struct got_object_id *initial_commit_id,
10552 struct got_object_id *iter_start_id, struct got_object_id *iter_stop_id,
10553 const char *path_prefix, int path_prefix_errcode,
10554 struct got_repository *repo)
10556 const struct got_error *err = NULL;
10557 struct got_commit_graph *graph = NULL;
10558 struct got_object_id parent_id, commit_id;
10559 struct got_object_qid *qid;
10561 err = got_commit_graph_open(&graph, "/", 1);
10562 if (err)
10563 return err;
10565 err = got_commit_graph_iter_start(graph, iter_start_id, repo,
10566 check_cancelled, NULL);
10567 if (err)
10568 goto done;
10570 memcpy(&commit_id, initial_commit_id, sizeof(commit_id));
10571 while (got_object_id_cmp(&commit_id, iter_stop_id) != 0) {
10572 err = got_commit_graph_iter_next(&parent_id, graph, repo,
10573 check_cancelled, NULL);
10574 if (err) {
10575 if (err->code == GOT_ERR_ITER_COMPLETED) {
10576 err = got_error_msg(GOT_ERR_ANCESTRY,
10577 "ran out of commits to rebase before "
10578 "youngest common ancestor commit has "
10579 "been reached?!?");
10581 goto done;
10582 } else {
10583 err = check_path_prefix(&parent_id, &commit_id,
10584 path_prefix, path_prefix_errcode, repo);
10585 if (err)
10586 goto done;
10588 err = got_object_qid_alloc(&qid, &commit_id);
10589 if (err)
10590 goto done;
10591 STAILQ_INSERT_HEAD(commits, qid, entry);
10593 memcpy(&commit_id, &parent_id, sizeof(commit_id));
10596 done:
10597 got_commit_graph_close(graph);
10598 return err;
10601 static const struct got_error *
10602 get_commit_brief_str(char **brief_str, struct got_commit_object *commit)
10604 const struct got_error *err = NULL;
10605 time_t committer_time;
10606 struct tm tm;
10607 char datebuf[11]; /* YYYY-MM-DD + NUL */
10608 char *author0 = NULL, *author, *smallerthan;
10609 char *logmsg0 = NULL, *logmsg, *newline;
10611 committer_time = got_object_commit_get_committer_time(commit);
10612 if (gmtime_r(&committer_time, &tm) == NULL)
10613 return got_error_from_errno("gmtime_r");
10614 if (strftime(datebuf, sizeof(datebuf), "%G-%m-%d", &tm) == 0)
10615 return got_error(GOT_ERR_NO_SPACE);
10617 author0 = strdup(got_object_commit_get_author(commit));
10618 if (author0 == NULL)
10619 return got_error_from_errno("strdup");
10620 author = author0;
10621 smallerthan = strchr(author, '<');
10622 if (smallerthan && smallerthan[1] != '\0')
10623 author = smallerthan + 1;
10624 author[strcspn(author, "@>")] = '\0';
10626 err = got_object_commit_get_logmsg(&logmsg0, commit);
10627 if (err)
10628 goto done;
10629 logmsg = logmsg0;
10630 while (*logmsg == '\n')
10631 logmsg++;
10632 newline = strchr(logmsg, '\n');
10633 if (newline)
10634 *newline = '\0';
10636 if (asprintf(brief_str, "%s %s %s",
10637 datebuf, author, logmsg) == -1)
10638 err = got_error_from_errno("asprintf");
10639 done:
10640 free(author0);
10641 free(logmsg0);
10642 return err;
10645 static const struct got_error *
10646 delete_backup_ref(struct got_reference *ref, struct got_object_id *id,
10647 struct got_repository *repo)
10649 const struct got_error *err;
10650 char *id_str;
10652 err = got_object_id_str(&id_str, id);
10653 if (err)
10654 return err;
10656 err = got_ref_delete(ref, repo);
10657 if (err)
10658 goto done;
10660 printf("Deleted %s: %s\n", got_ref_get_name(ref), id_str);
10661 done:
10662 free(id_str);
10663 return err;
10666 static const struct got_error *
10667 print_backup_ref(const char *branch_name, const char *new_id_str,
10668 struct got_object_id *old_commit_id, struct got_commit_object *old_commit,
10669 struct got_reflist_object_id_map *refs_idmap,
10670 struct got_repository *repo)
10672 const struct got_error *err = NULL;
10673 struct got_reflist_head *refs;
10674 char *refs_str = NULL;
10675 struct got_object_id *new_commit_id = NULL;
10676 struct got_commit_object *new_commit = NULL;
10677 char *new_commit_brief_str = NULL;
10678 struct got_object_id *yca_id = NULL;
10679 struct got_commit_object *yca_commit = NULL;
10680 char *yca_id_str = NULL, *yca_brief_str = NULL;
10681 char *custom_refs_str;
10683 if (asprintf(&custom_refs_str, "formerly %s", branch_name) == -1)
10684 return got_error_from_errno("asprintf");
10686 err = print_commit(old_commit, old_commit_id, repo, NULL, NULL, NULL,
10687 0, 0, refs_idmap, custom_refs_str, NULL);
10688 if (err)
10689 goto done;
10691 err = got_object_resolve_id_str(&new_commit_id, repo, new_id_str);
10692 if (err)
10693 goto done;
10695 refs = got_reflist_object_id_map_lookup(refs_idmap, new_commit_id);
10696 if (refs) {
10697 err = build_refs_str(&refs_str, refs, new_commit_id, repo, 0);
10698 if (err)
10699 goto done;
10702 err = got_object_open_as_commit(&new_commit, repo, new_commit_id);
10703 if (err)
10704 goto done;
10706 err = get_commit_brief_str(&new_commit_brief_str, new_commit);
10707 if (err)
10708 goto done;
10710 err = got_commit_graph_find_youngest_common_ancestor(&yca_id,
10711 old_commit_id, new_commit_id, 1, repo, check_cancelled, NULL);
10712 if (err)
10713 goto done;
10715 printf("has become commit %s%s%s%s\n %s\n", new_id_str,
10716 refs_str ? " (" : "", refs_str ? refs_str : "",
10717 refs_str ? ")" : "", new_commit_brief_str);
10718 if (yca_id && got_object_id_cmp(yca_id, new_commit_id) != 0 &&
10719 got_object_id_cmp(yca_id, old_commit_id) != 0) {
10720 free(refs_str);
10721 refs_str = NULL;
10723 err = got_object_open_as_commit(&yca_commit, repo, yca_id);
10724 if (err)
10725 goto done;
10727 err = get_commit_brief_str(&yca_brief_str, yca_commit);
10728 if (err)
10729 goto done;
10731 err = got_object_id_str(&yca_id_str, yca_id);
10732 if (err)
10733 goto done;
10735 refs = got_reflist_object_id_map_lookup(refs_idmap, yca_id);
10736 if (refs) {
10737 err = build_refs_str(&refs_str, refs, yca_id, repo, 0);
10738 if (err)
10739 goto done;
10741 printf("history forked at %s%s%s%s\n %s\n",
10742 yca_id_str,
10743 refs_str ? " (" : "", refs_str ? refs_str : "",
10744 refs_str ? ")" : "", yca_brief_str);
10746 done:
10747 free(custom_refs_str);
10748 free(new_commit_id);
10749 free(refs_str);
10750 free(yca_id);
10751 free(yca_id_str);
10752 free(yca_brief_str);
10753 if (new_commit)
10754 got_object_commit_close(new_commit);
10755 if (yca_commit)
10756 got_object_commit_close(yca_commit);
10758 return err;
10761 static const struct got_error *
10762 worktree_has_logmsg_ref(const char *caller, struct got_worktree *worktree,
10763 struct got_repository *repo)
10765 const struct got_error *err;
10766 struct got_reflist_head refs;
10767 struct got_reflist_entry *re;
10768 char *uuidstr = NULL;
10769 static char msg[160];
10771 TAILQ_INIT(&refs);
10773 err = got_worktree_get_uuid(&uuidstr, worktree);
10774 if (err)
10775 goto done;
10777 err = got_ref_list(&refs, repo, "refs/got/worktree",
10778 got_ref_cmp_by_name, repo);
10779 if (err)
10780 goto done;
10782 TAILQ_FOREACH(re, &refs, entry) {
10783 const char *cmd, *refname, *type;
10785 refname = got_ref_get_name(re->ref);
10787 if (strncmp(refname, GOT_WORKTREE_CHERRYPICK_REF_PREFIX,
10788 GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN) == 0) {
10789 refname += GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN + 1;
10790 cmd = "cherrypick";
10791 type = "cherrypicked";
10792 } else if (strncmp(refname, GOT_WORKTREE_BACKOUT_REF_PREFIX,
10793 GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN) == 0) {
10794 refname += GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN + 1;
10795 cmd = "backout";
10796 type = "backed-out";
10797 } else
10798 continue;
10800 if (strncmp(refname, uuidstr, GOT_WORKTREE_UUID_STRLEN) != 0)
10801 continue;
10803 snprintf(msg, sizeof(msg),
10804 "work tree has references created by %s commits which "
10805 "must be removed with 'got %s -X' before running the %s "
10806 "command", type, cmd, caller);
10807 err = got_error_msg(GOT_ERR_WORKTREE_META, msg);
10808 goto done;
10811 done:
10812 free(uuidstr);
10813 got_ref_list_free(&refs);
10814 return err;
10817 static const struct got_error *
10818 process_backup_refs(const char *backup_ref_prefix,
10819 const char *wanted_branch_name,
10820 int delete, struct got_repository *repo)
10822 const struct got_error *err;
10823 struct got_reflist_head refs, backup_refs;
10824 struct got_reflist_entry *re;
10825 const size_t backup_ref_prefix_len = strlen(backup_ref_prefix);
10826 struct got_object_id *old_commit_id = NULL;
10827 char *branch_name = NULL;
10828 struct got_commit_object *old_commit = NULL;
10829 struct got_reflist_object_id_map *refs_idmap = NULL;
10830 int wanted_branch_found = 0;
10832 TAILQ_INIT(&refs);
10833 TAILQ_INIT(&backup_refs);
10835 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
10836 if (err)
10837 return err;
10839 err = got_reflist_object_id_map_create(&refs_idmap, &refs, repo);
10840 if (err)
10841 goto done;
10843 if (wanted_branch_name) {
10844 if (strncmp(wanted_branch_name, "refs/heads/", 11) == 0)
10845 wanted_branch_name += 11;
10848 err = got_ref_list(&backup_refs, repo, backup_ref_prefix,
10849 got_ref_cmp_by_commit_timestamp_descending, repo);
10850 if (err)
10851 goto done;
10853 TAILQ_FOREACH(re, &backup_refs, entry) {
10854 const char *refname = got_ref_get_name(re->ref);
10855 char *slash;
10857 err = check_cancelled(NULL);
10858 if (err)
10859 break;
10861 err = got_ref_resolve(&old_commit_id, repo, re->ref);
10862 if (err)
10863 break;
10865 err = got_object_open_as_commit(&old_commit, repo,
10866 old_commit_id);
10867 if (err)
10868 break;
10870 if (strncmp(backup_ref_prefix, refname,
10871 backup_ref_prefix_len) == 0)
10872 refname += backup_ref_prefix_len;
10874 while (refname[0] == '/')
10875 refname++;
10877 branch_name = strdup(refname);
10878 if (branch_name == NULL) {
10879 err = got_error_from_errno("strdup");
10880 break;
10882 slash = strrchr(branch_name, '/');
10883 if (slash) {
10884 *slash = '\0';
10885 refname += strlen(branch_name) + 1;
10888 if (wanted_branch_name == NULL ||
10889 strcmp(wanted_branch_name, branch_name) == 0) {
10890 wanted_branch_found = 1;
10891 if (delete) {
10892 err = delete_backup_ref(re->ref,
10893 old_commit_id, repo);
10894 } else {
10895 err = print_backup_ref(branch_name, refname,
10896 old_commit_id, old_commit, refs_idmap,
10897 repo);
10899 if (err)
10900 break;
10903 free(old_commit_id);
10904 old_commit_id = NULL;
10905 free(branch_name);
10906 branch_name = NULL;
10907 got_object_commit_close(old_commit);
10908 old_commit = NULL;
10911 if (wanted_branch_name && !wanted_branch_found) {
10912 err = got_error_fmt(GOT_ERR_NOT_REF,
10913 "%s/%s/", backup_ref_prefix, wanted_branch_name);
10915 done:
10916 if (refs_idmap)
10917 got_reflist_object_id_map_free(refs_idmap);
10918 got_ref_list_free(&refs);
10919 got_ref_list_free(&backup_refs);
10920 free(old_commit_id);
10921 free(branch_name);
10922 if (old_commit)
10923 got_object_commit_close(old_commit);
10924 return err;
10927 static const struct got_error *
10928 abort_progress(void *arg, unsigned char status, const char *path)
10931 * Unversioned files should not clutter progress output when
10932 * an operation is aborted.
10934 if (status == GOT_STATUS_UNVERSIONED)
10935 return NULL;
10937 return update_progress(arg, status, path);
10940 static const struct got_error *
10941 cmd_rebase(int argc, char *argv[])
10943 const struct got_error *error = NULL;
10944 struct got_worktree *worktree = NULL;
10945 struct got_repository *repo = NULL;
10946 struct got_fileindex *fileindex = NULL;
10947 char *cwd = NULL, *committer = NULL, *gitconfig_path = NULL;
10948 struct got_reference *branch = NULL;
10949 struct got_reference *new_base_branch = NULL, *tmp_branch = NULL;
10950 struct got_object_id *commit_id = NULL, *parent_id = NULL;
10951 struct got_object_id *resume_commit_id = NULL;
10952 struct got_object_id *branch_head_commit_id = NULL, *yca_id = NULL;
10953 struct got_object_id *head_commit_id = NULL;
10954 struct got_reference *head_ref = NULL;
10955 struct got_commit_object *commit = NULL;
10956 int ch, rebase_in_progress = 0, abort_rebase = 0, continue_rebase = 0;
10957 int histedit_in_progress = 0, merge_in_progress = 0;
10958 int create_backup = 1, list_backups = 0, delete_backups = 0;
10959 struct got_object_id_queue commits;
10960 struct got_pathlist_head merged_paths;
10961 const struct got_object_id_queue *parent_ids;
10962 struct got_object_qid *qid, *pid;
10963 struct got_update_progress_arg upa;
10964 int *pack_fds = NULL;
10966 STAILQ_INIT(&commits);
10967 TAILQ_INIT(&merged_paths);
10968 memset(&upa, 0, sizeof(upa));
10970 while ((ch = getopt(argc, argv, "aclX")) != -1) {
10971 switch (ch) {
10972 case 'a':
10973 abort_rebase = 1;
10974 break;
10975 case 'c':
10976 continue_rebase = 1;
10977 break;
10978 case 'l':
10979 list_backups = 1;
10980 break;
10981 case 'X':
10982 delete_backups = 1;
10983 break;
10984 default:
10985 usage_rebase();
10986 /* NOTREACHED */
10990 argc -= optind;
10991 argv += optind;
10993 #ifndef PROFILE
10994 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
10995 "unveil", NULL) == -1)
10996 err(1, "pledge");
10997 #endif
10998 if (list_backups) {
10999 if (abort_rebase)
11000 option_conflict('l', 'a');
11001 if (continue_rebase)
11002 option_conflict('l', 'c');
11003 if (delete_backups)
11004 option_conflict('l', 'X');
11005 if (argc != 0 && argc != 1)
11006 usage_rebase();
11007 } else if (delete_backups) {
11008 if (abort_rebase)
11009 option_conflict('X', 'a');
11010 if (continue_rebase)
11011 option_conflict('X', 'c');
11012 if (list_backups)
11013 option_conflict('l', 'X');
11014 if (argc != 0 && argc != 1)
11015 usage_rebase();
11016 } else {
11017 if (abort_rebase && continue_rebase)
11018 usage_rebase();
11019 else if (abort_rebase || continue_rebase) {
11020 if (argc != 0)
11021 usage_rebase();
11022 } else if (argc != 1)
11023 usage_rebase();
11026 cwd = getcwd(NULL, 0);
11027 if (cwd == NULL) {
11028 error = got_error_from_errno("getcwd");
11029 goto done;
11032 error = got_repo_pack_fds_open(&pack_fds);
11033 if (error != NULL)
11034 goto done;
11036 error = got_worktree_open(&worktree, cwd);
11037 if (error) {
11038 if (list_backups || delete_backups) {
11039 if (error->code != GOT_ERR_NOT_WORKTREE)
11040 goto done;
11041 } else {
11042 if (error->code == GOT_ERR_NOT_WORKTREE)
11043 error = wrap_not_worktree_error(error,
11044 "rebase", cwd);
11045 goto done;
11049 error = get_gitconfig_path(&gitconfig_path);
11050 if (error)
11051 goto done;
11052 error = got_repo_open(&repo,
11053 worktree ? got_worktree_get_repo_path(worktree) : cwd,
11054 gitconfig_path, pack_fds);
11055 if (error != NULL)
11056 goto done;
11058 if (worktree != NULL && !list_backups && !delete_backups) {
11059 error = worktree_has_logmsg_ref("rebase", worktree, repo);
11060 if (error)
11061 goto done;
11064 error = get_author(&committer, repo, worktree);
11065 if (error && error->code != GOT_ERR_COMMIT_NO_AUTHOR)
11066 goto done;
11068 error = apply_unveil(got_repo_get_path(repo), 0,
11069 worktree ? got_worktree_get_root_path(worktree) : NULL);
11070 if (error)
11071 goto done;
11073 if (list_backups || delete_backups) {
11074 error = process_backup_refs(
11075 GOT_WORKTREE_REBASE_BACKUP_REF_PREFIX,
11076 argc == 1 ? argv[0] : NULL, delete_backups, repo);
11077 goto done; /* nothing else to do */
11080 error = got_worktree_histedit_in_progress(&histedit_in_progress,
11081 worktree);
11082 if (error)
11083 goto done;
11084 if (histedit_in_progress) {
11085 error = got_error(GOT_ERR_HISTEDIT_BUSY);
11086 goto done;
11089 error = got_worktree_merge_in_progress(&merge_in_progress,
11090 worktree, repo);
11091 if (error)
11092 goto done;
11093 if (merge_in_progress) {
11094 error = got_error(GOT_ERR_MERGE_BUSY);
11095 goto done;
11098 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
11099 if (error)
11100 goto done;
11102 if (abort_rebase) {
11103 if (!rebase_in_progress) {
11104 error = got_error(GOT_ERR_NOT_REBASING);
11105 goto done;
11107 error = got_worktree_rebase_continue(&resume_commit_id,
11108 &new_base_branch, &tmp_branch, &branch, &fileindex,
11109 worktree, repo);
11110 if (error)
11111 goto done;
11112 printf("Switching work tree to %s\n",
11113 got_ref_get_symref_target(new_base_branch));
11114 error = got_worktree_rebase_abort(worktree, fileindex, repo,
11115 new_base_branch, abort_progress, &upa);
11116 if (error)
11117 goto done;
11118 printf("Rebase of %s aborted\n", got_ref_get_name(branch));
11119 print_merge_progress_stats(&upa);
11120 goto done; /* nothing else to do */
11123 if (continue_rebase) {
11124 if (!rebase_in_progress) {
11125 error = got_error(GOT_ERR_NOT_REBASING);
11126 goto done;
11128 error = got_worktree_rebase_continue(&resume_commit_id,
11129 &new_base_branch, &tmp_branch, &branch, &fileindex,
11130 worktree, repo);
11131 if (error)
11132 goto done;
11134 error = rebase_commit(NULL, worktree, fileindex, tmp_branch,
11135 committer, resume_commit_id, repo);
11136 if (error)
11137 goto done;
11139 yca_id = got_object_id_dup(resume_commit_id);
11140 if (yca_id == NULL) {
11141 error = got_error_from_errno("got_object_id_dup");
11142 goto done;
11144 } else {
11145 error = got_ref_open(&branch, repo, argv[0], 0);
11146 if (error != NULL)
11147 goto done;
11148 if (strncmp(got_ref_get_name(branch), "refs/heads/", 11) != 0) {
11149 error = got_error_msg(GOT_ERR_COMMIT_BRANCH,
11150 "will not rebase a branch which lives outside "
11151 "the \"refs/heads/\" reference namespace");
11152 goto done;
11156 error = got_ref_resolve(&branch_head_commit_id, repo, branch);
11157 if (error)
11158 goto done;
11160 if (!continue_rebase) {
11161 struct got_object_id *base_commit_id;
11163 error = got_ref_open(&head_ref, repo,
11164 got_worktree_get_head_ref_name(worktree), 0);
11165 if (error)
11166 goto done;
11167 error = got_ref_resolve(&head_commit_id, repo, head_ref);
11168 if (error)
11169 goto done;
11170 base_commit_id = got_worktree_get_base_commit_id(worktree);
11171 if (got_object_id_cmp(base_commit_id, head_commit_id) != 0) {
11172 error = got_error(GOT_ERR_REBASE_OUT_OF_DATE);
11173 goto done;
11176 error = got_commit_graph_find_youngest_common_ancestor(&yca_id,
11177 base_commit_id, branch_head_commit_id, 1, repo,
11178 check_cancelled, NULL);
11179 if (error) {
11180 if (error->code == GOT_ERR_ANCESTRY) {
11181 error = got_error_msg(GOT_ERR_ANCESTRY,
11182 "specified branch shares no common "
11183 "ancestry with work tree's branch");
11185 goto done;
11188 error = check_same_branch(base_commit_id, branch, yca_id, repo);
11189 if (error) {
11190 if (error->code != GOT_ERR_ANCESTRY)
11191 goto done;
11192 error = NULL;
11193 } else {
11194 struct got_pathlist_head paths;
11195 printf("%s is already based on %s\n",
11196 got_ref_get_name(branch),
11197 got_worktree_get_head_ref_name(worktree));
11198 error = switch_head_ref(branch, branch_head_commit_id,
11199 worktree, repo);
11200 if (error)
11201 goto done;
11202 error = got_worktree_set_base_commit_id(worktree, repo,
11203 branch_head_commit_id);
11204 if (error)
11205 goto done;
11206 TAILQ_INIT(&paths);
11207 error = got_pathlist_append(&paths, "", NULL);
11208 if (error)
11209 goto done;
11210 error = got_worktree_checkout_files(worktree,
11211 &paths, repo, update_progress, &upa,
11212 check_cancelled, NULL);
11213 got_pathlist_free(&paths, GOT_PATHLIST_FREE_NONE);
11214 if (error)
11215 goto done;
11216 if (upa.did_something) {
11217 char *id_str;
11218 error = got_object_id_str(&id_str,
11219 branch_head_commit_id);
11220 if (error)
11221 goto done;
11222 printf("Updated to %s: %s\n",
11223 got_worktree_get_head_ref_name(worktree),
11224 id_str);
11225 free(id_str);
11226 } else
11227 printf("Already up-to-date\n");
11228 print_update_progress_stats(&upa);
11229 goto done;
11233 commit_id = branch_head_commit_id;
11234 error = got_object_open_as_commit(&commit, repo, commit_id);
11235 if (error)
11236 goto done;
11238 parent_ids = got_object_commit_get_parent_ids(commit);
11239 pid = STAILQ_FIRST(parent_ids);
11240 if (pid) {
11241 error = collect_commits(&commits, commit_id, &pid->id,
11242 yca_id, got_worktree_get_path_prefix(worktree),
11243 GOT_ERR_REBASE_PATH, repo);
11244 if (error)
11245 goto done;
11248 got_object_commit_close(commit);
11249 commit = NULL;
11251 if (!continue_rebase) {
11252 error = got_worktree_rebase_prepare(&new_base_branch,
11253 &tmp_branch, &fileindex, worktree, branch, repo);
11254 if (error)
11255 goto done;
11258 if (STAILQ_EMPTY(&commits)) {
11259 if (continue_rebase) {
11260 error = rebase_complete(worktree, fileindex,
11261 branch, tmp_branch, repo, create_backup);
11262 goto done;
11263 } else {
11264 /* Fast-forward the reference of the branch. */
11265 struct got_object_id *new_head_commit_id;
11266 char *id_str;
11267 error = got_ref_resolve(&new_head_commit_id, repo,
11268 new_base_branch);
11269 if (error)
11270 goto done;
11271 error = got_object_id_str(&id_str, new_head_commit_id);
11272 if (error)
11273 goto done;
11274 printf("Forwarding %s to commit %s\n",
11275 got_ref_get_name(branch), id_str);
11276 free(id_str);
11277 error = got_ref_change_ref(branch,
11278 new_head_commit_id);
11279 if (error)
11280 goto done;
11281 /* No backup needed since objects did not change. */
11282 create_backup = 0;
11286 pid = NULL;
11287 STAILQ_FOREACH(qid, &commits, entry) {
11289 commit_id = &qid->id;
11290 parent_id = pid ? &pid->id : yca_id;
11291 pid = qid;
11293 memset(&upa, 0, sizeof(upa));
11294 error = got_worktree_rebase_merge_files(&merged_paths,
11295 worktree, fileindex, parent_id, commit_id, repo,
11296 update_progress, &upa, check_cancelled, NULL);
11297 if (error)
11298 goto done;
11300 print_merge_progress_stats(&upa);
11301 if (upa.conflicts > 0 || upa.missing > 0 ||
11302 upa.not_deleted > 0 || upa.unversioned > 0) {
11303 if (upa.conflicts > 0) {
11304 error = show_rebase_merge_conflict(&qid->id,
11305 repo);
11306 if (error)
11307 goto done;
11309 got_pathlist_free(&merged_paths, GOT_PATHLIST_FREE_PATH);
11310 break;
11313 error = rebase_commit(&merged_paths, worktree, fileindex,
11314 tmp_branch, committer, commit_id, repo);
11315 got_pathlist_free(&merged_paths, GOT_PATHLIST_FREE_PATH);
11316 if (error)
11317 goto done;
11320 if (upa.conflicts > 0 || upa.missing > 0 ||
11321 upa.not_deleted > 0 || upa.unversioned > 0) {
11322 error = got_worktree_rebase_postpone(worktree, fileindex);
11323 if (error)
11324 goto done;
11325 if (upa.conflicts > 0 && upa.missing == 0 &&
11326 upa.not_deleted == 0 && upa.unversioned == 0) {
11327 error = got_error_msg(GOT_ERR_CONFLICTS,
11328 "conflicts must be resolved before rebasing "
11329 "can continue");
11330 } else if (upa.conflicts > 0) {
11331 error = got_error_msg(GOT_ERR_CONFLICTS,
11332 "conflicts must be resolved before rebasing "
11333 "can continue; changes destined for some "
11334 "files were not yet merged and should be "
11335 "merged manually if required before the "
11336 "rebase operation is continued");
11337 } else {
11338 error = got_error_msg(GOT_ERR_CONFLICTS,
11339 "changes destined for some files were not "
11340 "yet merged and should be merged manually "
11341 "if required before the rebase operation "
11342 "is continued");
11344 } else
11345 error = rebase_complete(worktree, fileindex, branch,
11346 tmp_branch, repo, create_backup);
11347 done:
11348 free(cwd);
11349 free(committer);
11350 free(gitconfig_path);
11351 got_object_id_queue_free(&commits);
11352 free(branch_head_commit_id);
11353 free(resume_commit_id);
11354 free(head_commit_id);
11355 free(yca_id);
11356 if (commit)
11357 got_object_commit_close(commit);
11358 if (branch)
11359 got_ref_close(branch);
11360 if (new_base_branch)
11361 got_ref_close(new_base_branch);
11362 if (tmp_branch)
11363 got_ref_close(tmp_branch);
11364 if (head_ref)
11365 got_ref_close(head_ref);
11366 if (worktree)
11367 got_worktree_close(worktree);
11368 if (repo) {
11369 const struct got_error *close_err = got_repo_close(repo);
11370 if (error == NULL)
11371 error = close_err;
11373 if (pack_fds) {
11374 const struct got_error *pack_err =
11375 got_repo_pack_fds_close(pack_fds);
11376 if (error == NULL)
11377 error = pack_err;
11379 return error;
11382 __dead static void
11383 usage_histedit(void)
11385 fprintf(stderr, "usage: %s histedit [-acdeflmX] [-F histedit-script] "
11386 "[branch]\n", getprogname());
11387 exit(1);
11390 #define GOT_HISTEDIT_PICK 'p'
11391 #define GOT_HISTEDIT_EDIT 'e'
11392 #define GOT_HISTEDIT_FOLD 'f'
11393 #define GOT_HISTEDIT_DROP 'd'
11394 #define GOT_HISTEDIT_MESG 'm'
11396 static const struct got_histedit_cmd {
11397 unsigned char code;
11398 const char *name;
11399 const char *desc;
11400 } got_histedit_cmds[] = {
11401 { GOT_HISTEDIT_PICK, "pick", "use commit" },
11402 { GOT_HISTEDIT_EDIT, "edit", "use commit but stop for amending" },
11403 { GOT_HISTEDIT_FOLD, "fold", "combine with next commit that will "
11404 "be used" },
11405 { GOT_HISTEDIT_DROP, "drop", "remove commit from history" },
11406 { GOT_HISTEDIT_MESG, "mesg",
11407 "single-line log message for commit above (open editor if empty)" },
11410 struct got_histedit_list_entry {
11411 TAILQ_ENTRY(got_histedit_list_entry) entry;
11412 struct got_object_id *commit_id;
11413 const struct got_histedit_cmd *cmd;
11414 char *logmsg;
11416 TAILQ_HEAD(got_histedit_list, got_histedit_list_entry);
11418 static const struct got_error *
11419 histedit_write_commit(struct got_object_id *commit_id, const char *cmdname,
11420 FILE *f, struct got_repository *repo)
11422 const struct got_error *err = NULL;
11423 char *logmsg = NULL, *id_str = NULL;
11424 struct got_commit_object *commit = NULL;
11425 int n;
11427 err = got_object_open_as_commit(&commit, repo, commit_id);
11428 if (err)
11429 goto done;
11431 err = get_short_logmsg(&logmsg, 34, commit);
11432 if (err)
11433 goto done;
11435 err = got_object_id_str(&id_str, commit_id);
11436 if (err)
11437 goto done;
11439 n = fprintf(f, "%s %s %s\n", cmdname, id_str, logmsg);
11440 if (n < 0)
11441 err = got_ferror(f, GOT_ERR_IO);
11442 done:
11443 if (commit)
11444 got_object_commit_close(commit);
11445 free(id_str);
11446 free(logmsg);
11447 return err;
11450 static const struct got_error *
11451 histedit_write_commit_list(struct got_object_id_queue *commits,
11452 FILE *f, int edit_logmsg_only, int fold_only, int drop_only,
11453 int edit_only, struct got_repository *repo)
11455 const struct got_error *err = NULL;
11456 struct got_object_qid *qid;
11457 const char *histedit_cmd = NULL;
11459 if (STAILQ_EMPTY(commits))
11460 return got_error(GOT_ERR_EMPTY_HISTEDIT);
11462 STAILQ_FOREACH(qid, commits, entry) {
11463 histedit_cmd = got_histedit_cmds[0].name;
11464 if (drop_only)
11465 histedit_cmd = "drop";
11466 else if (edit_only)
11467 histedit_cmd = "edit";
11468 else if (fold_only && STAILQ_NEXT(qid, entry) != NULL)
11469 histedit_cmd = "fold";
11470 err = histedit_write_commit(&qid->id, histedit_cmd, f, repo);
11471 if (err)
11472 break;
11473 if (edit_logmsg_only) {
11474 int n = fprintf(f, "%c\n", GOT_HISTEDIT_MESG);
11475 if (n < 0) {
11476 err = got_ferror(f, GOT_ERR_IO);
11477 break;
11482 return err;
11485 static const struct got_error *
11486 write_cmd_list(FILE *f, const char *branch_name,
11487 struct got_object_id_queue *commits)
11489 const struct got_error *err = NULL;
11490 size_t i;
11491 int n;
11492 char *id_str;
11493 struct got_object_qid *qid;
11495 qid = STAILQ_FIRST(commits);
11496 err = got_object_id_str(&id_str, &qid->id);
11497 if (err)
11498 return err;
11500 n = fprintf(f,
11501 "# Editing the history of branch '%s' starting at\n"
11502 "# commit %s\n"
11503 "# Commits will be processed in order from top to "
11504 "bottom of this file.\n", branch_name, id_str);
11505 if (n < 0) {
11506 err = got_ferror(f, GOT_ERR_IO);
11507 goto done;
11510 n = fprintf(f, "# Available histedit commands:\n");
11511 if (n < 0) {
11512 err = got_ferror(f, GOT_ERR_IO);
11513 goto done;
11516 for (i = 0; i < nitems(got_histedit_cmds); i++) {
11517 const struct got_histedit_cmd *cmd = &got_histedit_cmds[i];
11518 n = fprintf(f, "# %s (%c): %s\n", cmd->name, cmd->code,
11519 cmd->desc);
11520 if (n < 0) {
11521 err = got_ferror(f, GOT_ERR_IO);
11522 break;
11525 done:
11526 free(id_str);
11527 return err;
11530 static const struct got_error *
11531 histedit_syntax_error(int lineno)
11533 static char msg[42];
11534 int ret;
11536 ret = snprintf(msg, sizeof(msg), "histedit syntax error on line %d",
11537 lineno);
11538 if (ret < 0 || (size_t)ret >= sizeof(msg))
11539 return got_error(GOT_ERR_HISTEDIT_SYNTAX);
11541 return got_error_msg(GOT_ERR_HISTEDIT_SYNTAX, msg);
11544 static const struct got_error *
11545 append_folded_commit_msg(char **new_msg, struct got_histedit_list_entry *hle,
11546 char *logmsg, struct got_repository *repo)
11548 const struct got_error *err;
11549 struct got_commit_object *folded_commit = NULL;
11550 char *id_str, *folded_logmsg = NULL;
11552 err = got_object_id_str(&id_str, hle->commit_id);
11553 if (err)
11554 return err;
11556 err = got_object_open_as_commit(&folded_commit, repo, hle->commit_id);
11557 if (err)
11558 goto done;
11560 err = got_object_commit_get_logmsg(&folded_logmsg, folded_commit);
11561 if (err)
11562 goto done;
11563 if (asprintf(new_msg, "%s%s# log message of folded commit %s: %s",
11564 logmsg ? logmsg : "", logmsg ? "\n" : "", id_str,
11565 folded_logmsg) == -1) {
11566 err = got_error_from_errno("asprintf");
11568 done:
11569 if (folded_commit)
11570 got_object_commit_close(folded_commit);
11571 free(id_str);
11572 free(folded_logmsg);
11573 return err;
11576 static struct got_histedit_list_entry *
11577 get_folded_commits(struct got_histedit_list_entry *hle)
11579 struct got_histedit_list_entry *prev, *folded = NULL;
11581 prev = TAILQ_PREV(hle, got_histedit_list, entry);
11582 while (prev && (prev->cmd->code == GOT_HISTEDIT_FOLD ||
11583 prev->cmd->code == GOT_HISTEDIT_DROP)) {
11584 if (prev->cmd->code == GOT_HISTEDIT_FOLD)
11585 folded = prev;
11586 prev = TAILQ_PREV(prev, got_histedit_list, entry);
11589 return folded;
11592 static const struct got_error *
11593 histedit_edit_logmsg(struct got_histedit_list_entry *hle,
11594 struct got_repository *repo)
11596 char *logmsg_path = NULL, *id_str = NULL, *orig_logmsg = NULL;
11597 char *logmsg = NULL, *new_msg = NULL, *editor = NULL;
11598 const struct got_error *err = NULL;
11599 struct got_commit_object *commit = NULL;
11600 int logmsg_len;
11601 int fd;
11602 struct got_histedit_list_entry *folded = NULL;
11604 err = got_object_open_as_commit(&commit, repo, hle->commit_id);
11605 if (err)
11606 return err;
11608 folded = get_folded_commits(hle);
11609 if (folded) {
11610 while (folded != hle) {
11611 if (folded->cmd->code == GOT_HISTEDIT_DROP) {
11612 folded = TAILQ_NEXT(folded, entry);
11613 continue;
11615 err = append_folded_commit_msg(&new_msg, folded,
11616 logmsg, repo);
11617 if (err)
11618 goto done;
11619 free(logmsg);
11620 logmsg = new_msg;
11621 folded = TAILQ_NEXT(folded, entry);
11625 err = got_object_id_str(&id_str, hle->commit_id);
11626 if (err)
11627 goto done;
11628 err = got_object_commit_get_logmsg(&orig_logmsg, commit);
11629 if (err)
11630 goto done;
11631 logmsg_len = asprintf(&new_msg,
11632 "%s\n# original log message of commit %s: %s",
11633 logmsg ? logmsg : "", id_str, orig_logmsg);
11634 if (logmsg_len == -1) {
11635 err = got_error_from_errno("asprintf");
11636 goto done;
11638 free(logmsg);
11639 logmsg = new_msg;
11641 err = got_object_id_str(&id_str, hle->commit_id);
11642 if (err)
11643 goto done;
11645 err = got_opentemp_named_fd(&logmsg_path, &fd,
11646 GOT_TMPDIR_STR "/got-logmsg", "");
11647 if (err)
11648 goto done;
11650 write(fd, logmsg, logmsg_len);
11651 close(fd);
11653 err = get_editor(&editor);
11654 if (err)
11655 goto done;
11657 err = edit_logmsg(&hle->logmsg, editor, logmsg_path, logmsg,
11658 logmsg_len, 0);
11659 if (err) {
11660 if (err->code != GOT_ERR_COMMIT_MSG_EMPTY)
11661 goto done;
11662 err = NULL;
11663 hle->logmsg = strdup(new_msg);
11664 if (hle->logmsg == NULL)
11665 err = got_error_from_errno("strdup");
11667 done:
11668 if (logmsg_path && unlink(logmsg_path) != 0 && err == NULL)
11669 err = got_error_from_errno2("unlink", logmsg_path);
11670 free(logmsg_path);
11671 free(logmsg);
11672 free(orig_logmsg);
11673 free(editor);
11674 if (commit)
11675 got_object_commit_close(commit);
11676 return err;
11679 static const struct got_error *
11680 histedit_parse_list(struct got_histedit_list *histedit_cmds,
11681 FILE *f, struct got_repository *repo)
11683 const struct got_error *err = NULL;
11684 char *line = NULL, *p, *end;
11685 size_t i, size;
11686 ssize_t len;
11687 int lineno = 0, lastcmd = -1;
11688 const struct got_histedit_cmd *cmd;
11689 struct got_object_id *commit_id = NULL;
11690 struct got_histedit_list_entry *hle = NULL;
11692 for (;;) {
11693 len = getline(&line, &size, f);
11694 if (len == -1) {
11695 const struct got_error *getline_err;
11696 if (feof(f))
11697 break;
11698 getline_err = got_error_from_errno("getline");
11699 err = got_ferror(f, getline_err->code);
11700 break;
11702 lineno++;
11703 p = line;
11704 while (isspace((unsigned char)p[0]))
11705 p++;
11706 if (p[0] == '#' || p[0] == '\0') {
11707 free(line);
11708 line = NULL;
11709 continue;
11711 cmd = NULL;
11712 for (i = 0; i < nitems(got_histedit_cmds); i++) {
11713 cmd = &got_histedit_cmds[i];
11714 if (strncmp(cmd->name, p, strlen(cmd->name)) == 0 &&
11715 isspace((unsigned char)p[strlen(cmd->name)])) {
11716 p += strlen(cmd->name);
11717 break;
11719 if (p[0] == cmd->code && isspace((unsigned char)p[1])) {
11720 p++;
11721 break;
11724 if (i == nitems(got_histedit_cmds)) {
11725 err = histedit_syntax_error(lineno);
11726 break;
11728 while (isspace((unsigned char)p[0]))
11729 p++;
11730 if (cmd->code == GOT_HISTEDIT_MESG) {
11731 if (lastcmd != GOT_HISTEDIT_PICK &&
11732 lastcmd != GOT_HISTEDIT_EDIT) {
11733 err = got_error(GOT_ERR_HISTEDIT_CMD);
11734 break;
11736 if (p[0] == '\0') {
11737 err = histedit_edit_logmsg(hle, repo);
11738 if (err)
11739 break;
11740 } else {
11741 hle->logmsg = strdup(p);
11742 if (hle->logmsg == NULL) {
11743 err = got_error_from_errno("strdup");
11744 break;
11747 free(line);
11748 line = NULL;
11749 lastcmd = cmd->code;
11750 continue;
11751 } else {
11752 end = p;
11753 while (end[0] && !isspace((unsigned char)end[0]))
11754 end++;
11755 *end = '\0';
11757 err = got_object_resolve_id_str(&commit_id, repo, p);
11758 if (err) {
11759 /* override error code */
11760 err = histedit_syntax_error(lineno);
11761 break;
11764 hle = malloc(sizeof(*hle));
11765 if (hle == NULL) {
11766 err = got_error_from_errno("malloc");
11767 break;
11769 hle->cmd = cmd;
11770 hle->commit_id = commit_id;
11771 hle->logmsg = NULL;
11772 commit_id = NULL;
11773 free(line);
11774 line = NULL;
11775 TAILQ_INSERT_TAIL(histedit_cmds, hle, entry);
11776 lastcmd = cmd->code;
11779 free(line);
11780 free(commit_id);
11781 return err;
11784 static const struct got_error *
11785 histedit_check_script(struct got_histedit_list *histedit_cmds,
11786 struct got_object_id_queue *commits, struct got_repository *repo)
11788 const struct got_error *err = NULL;
11789 struct got_object_qid *qid;
11790 struct got_histedit_list_entry *hle;
11791 static char msg[92];
11792 char *id_str;
11794 if (TAILQ_EMPTY(histedit_cmds))
11795 return got_error_msg(GOT_ERR_EMPTY_HISTEDIT,
11796 "histedit script contains no commands");
11797 if (STAILQ_EMPTY(commits))
11798 return got_error(GOT_ERR_EMPTY_HISTEDIT);
11800 TAILQ_FOREACH(hle, histedit_cmds, entry) {
11801 struct got_histedit_list_entry *hle2;
11802 TAILQ_FOREACH(hle2, histedit_cmds, entry) {
11803 if (hle == hle2)
11804 continue;
11805 if (got_object_id_cmp(hle->commit_id,
11806 hle2->commit_id) != 0)
11807 continue;
11808 err = got_object_id_str(&id_str, hle->commit_id);
11809 if (err)
11810 return err;
11811 snprintf(msg, sizeof(msg), "commit %s is listed "
11812 "more than once in histedit script", id_str);
11813 free(id_str);
11814 return got_error_msg(GOT_ERR_HISTEDIT_CMD, msg);
11818 STAILQ_FOREACH(qid, commits, entry) {
11819 TAILQ_FOREACH(hle, histedit_cmds, entry) {
11820 if (got_object_id_cmp(&qid->id, hle->commit_id) == 0)
11821 break;
11823 if (hle == NULL) {
11824 err = got_object_id_str(&id_str, &qid->id);
11825 if (err)
11826 return err;
11827 snprintf(msg, sizeof(msg),
11828 "commit %s missing from histedit script", id_str);
11829 free(id_str);
11830 return got_error_msg(GOT_ERR_HISTEDIT_CMD, msg);
11834 hle = TAILQ_LAST(histedit_cmds, got_histedit_list);
11835 if (hle && hle->cmd->code == GOT_HISTEDIT_FOLD)
11836 return got_error_msg(GOT_ERR_HISTEDIT_CMD,
11837 "last commit in histedit script cannot be folded");
11839 return NULL;
11842 static const struct got_error *
11843 histedit_run_editor(struct got_histedit_list *histedit_cmds,
11844 const char *path, struct got_object_id_queue *commits,
11845 struct got_repository *repo)
11847 const struct got_error *err = NULL;
11848 char *editor;
11849 FILE *f = NULL;
11851 err = get_editor(&editor);
11852 if (err)
11853 return err;
11855 if (spawn_editor(editor, path) == -1) {
11856 err = got_error_from_errno("failed spawning editor");
11857 goto done;
11860 f = fopen(path, "re");
11861 if (f == NULL) {
11862 err = got_error_from_errno("fopen");
11863 goto done;
11865 err = histedit_parse_list(histedit_cmds, f, repo);
11866 if (err)
11867 goto done;
11869 err = histedit_check_script(histedit_cmds, commits, repo);
11870 done:
11871 if (f && fclose(f) == EOF && err == NULL)
11872 err = got_error_from_errno("fclose");
11873 free(editor);
11874 return err;
11877 static const struct got_error *
11878 histedit_edit_list_retry(struct got_histedit_list *, const struct got_error *,
11879 struct got_object_id_queue *, const char *, const char *,
11880 struct got_repository *);
11882 static const struct got_error *
11883 histedit_edit_script(struct got_histedit_list *histedit_cmds,
11884 struct got_object_id_queue *commits, const char *branch_name,
11885 int edit_logmsg_only, int fold_only, int drop_only, int edit_only,
11886 struct got_repository *repo)
11888 const struct got_error *err;
11889 FILE *f = NULL;
11890 char *path = NULL;
11892 err = got_opentemp_named(&path, &f, "got-histedit", "");
11893 if (err)
11894 return err;
11896 err = write_cmd_list(f, branch_name, commits);
11897 if (err)
11898 goto done;
11900 err = histedit_write_commit_list(commits, f, edit_logmsg_only,
11901 fold_only, drop_only, edit_only, repo);
11902 if (err)
11903 goto done;
11905 if (drop_only || edit_logmsg_only || fold_only || edit_only) {
11906 rewind(f);
11907 err = histedit_parse_list(histedit_cmds, f, repo);
11908 } else {
11909 if (fclose(f) == EOF) {
11910 err = got_error_from_errno("fclose");
11911 goto done;
11913 f = NULL;
11914 err = histedit_run_editor(histedit_cmds, path, commits, repo);
11915 if (err) {
11916 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
11917 err->code != GOT_ERR_HISTEDIT_CMD)
11918 goto done;
11919 err = histedit_edit_list_retry(histedit_cmds, err,
11920 commits, path, branch_name, repo);
11923 done:
11924 if (f && fclose(f) == EOF && err == NULL)
11925 err = got_error_from_errno("fclose");
11926 if (path && unlink(path) != 0 && err == NULL)
11927 err = got_error_from_errno2("unlink", path);
11928 free(path);
11929 return err;
11932 static const struct got_error *
11933 histedit_save_list(struct got_histedit_list *histedit_cmds,
11934 struct got_worktree *worktree, struct got_repository *repo)
11936 const struct got_error *err = NULL;
11937 char *path = NULL;
11938 FILE *f = NULL;
11939 struct got_histedit_list_entry *hle;
11940 struct got_commit_object *commit = NULL;
11942 err = got_worktree_get_histedit_script_path(&path, worktree);
11943 if (err)
11944 return err;
11946 f = fopen(path, "we");
11947 if (f == NULL) {
11948 err = got_error_from_errno2("fopen", path);
11949 goto done;
11951 TAILQ_FOREACH(hle, histedit_cmds, entry) {
11952 err = histedit_write_commit(hle->commit_id, hle->cmd->name, f,
11953 repo);
11954 if (err)
11955 break;
11957 if (hle->logmsg) {
11958 int n = fprintf(f, "%c %s\n",
11959 GOT_HISTEDIT_MESG, hle->logmsg);
11960 if (n < 0) {
11961 err = got_ferror(f, GOT_ERR_IO);
11962 break;
11966 done:
11967 if (f && fclose(f) == EOF && err == NULL)
11968 err = got_error_from_errno("fclose");
11969 free(path);
11970 if (commit)
11971 got_object_commit_close(commit);
11972 return err;
11975 static void
11976 histedit_free_list(struct got_histedit_list *histedit_cmds)
11978 struct got_histedit_list_entry *hle;
11980 while ((hle = TAILQ_FIRST(histedit_cmds))) {
11981 TAILQ_REMOVE(histedit_cmds, hle, entry);
11982 free(hle);
11986 static const struct got_error *
11987 histedit_load_list(struct got_histedit_list *histedit_cmds,
11988 const char *path, struct got_repository *repo)
11990 const struct got_error *err = NULL;
11991 FILE *f = NULL;
11993 f = fopen(path, "re");
11994 if (f == NULL) {
11995 err = got_error_from_errno2("fopen", path);
11996 goto done;
11999 err = histedit_parse_list(histedit_cmds, f, repo);
12000 done:
12001 if (f && fclose(f) == EOF && err == NULL)
12002 err = got_error_from_errno("fclose");
12003 return err;
12006 static const struct got_error *
12007 histedit_edit_list_retry(struct got_histedit_list *histedit_cmds,
12008 const struct got_error *edit_err, struct got_object_id_queue *commits,
12009 const char *path, const char *branch_name, struct got_repository *repo)
12011 const struct got_error *err = NULL, *prev_err = edit_err;
12012 int resp = ' ';
12014 while (resp != 'c' && resp != 'r' && resp != 'a') {
12015 printf("%s: %s\n(c)ontinue editing, (r)estart editing, "
12016 "or (a)bort: ", getprogname(), prev_err->msg);
12017 resp = getchar();
12018 if (resp == '\n')
12019 resp = getchar();
12020 if (resp == 'c') {
12021 histedit_free_list(histedit_cmds);
12022 err = histedit_run_editor(histedit_cmds, path, commits,
12023 repo);
12024 if (err) {
12025 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
12026 err->code != GOT_ERR_HISTEDIT_CMD)
12027 break;
12028 prev_err = err;
12029 resp = ' ';
12030 continue;
12032 break;
12033 } else if (resp == 'r') {
12034 histedit_free_list(histedit_cmds);
12035 err = histedit_edit_script(histedit_cmds,
12036 commits, branch_name, 0, 0, 0, 0, repo);
12037 if (err) {
12038 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
12039 err->code != GOT_ERR_HISTEDIT_CMD)
12040 break;
12041 prev_err = err;
12042 resp = ' ';
12043 continue;
12045 break;
12046 } else if (resp == 'a') {
12047 err = got_error(GOT_ERR_HISTEDIT_CANCEL);
12048 break;
12049 } else
12050 printf("invalid response '%c'\n", resp);
12053 return err;
12056 static const struct got_error *
12057 histedit_complete(struct got_worktree *worktree,
12058 struct got_fileindex *fileindex, struct got_reference *tmp_branch,
12059 struct got_reference *branch, struct got_repository *repo)
12061 printf("Switching work tree to %s\n",
12062 got_ref_get_symref_target(branch));
12063 return got_worktree_histedit_complete(worktree, fileindex, tmp_branch,
12064 branch, repo);
12067 static const struct got_error *
12068 show_histedit_progress(struct got_commit_object *commit,
12069 struct got_histedit_list_entry *hle, struct got_object_id *new_id)
12071 const struct got_error *err;
12072 char *old_id_str = NULL, *new_id_str = NULL, *logmsg = NULL;
12074 err = got_object_id_str(&old_id_str, hle->commit_id);
12075 if (err)
12076 goto done;
12078 if (new_id) {
12079 err = got_object_id_str(&new_id_str, new_id);
12080 if (err)
12081 goto done;
12084 old_id_str[12] = '\0';
12085 if (new_id_str)
12086 new_id_str[12] = '\0';
12088 if (hle->logmsg) {
12089 logmsg = strdup(hle->logmsg);
12090 if (logmsg == NULL) {
12091 err = got_error_from_errno("strdup");
12092 goto done;
12094 trim_logmsg(logmsg, 42);
12095 } else {
12096 err = get_short_logmsg(&logmsg, 42, commit);
12097 if (err)
12098 goto done;
12101 switch (hle->cmd->code) {
12102 case GOT_HISTEDIT_PICK:
12103 case GOT_HISTEDIT_EDIT:
12104 printf("%s -> %s: %s\n", old_id_str,
12105 new_id_str ? new_id_str : "no-op change", logmsg);
12106 break;
12107 case GOT_HISTEDIT_DROP:
12108 case GOT_HISTEDIT_FOLD:
12109 printf("%s -> %s commit: %s\n", old_id_str, hle->cmd->name,
12110 logmsg);
12111 break;
12112 default:
12113 break;
12115 done:
12116 free(old_id_str);
12117 free(new_id_str);
12118 return err;
12121 static const struct got_error *
12122 histedit_commit(struct got_pathlist_head *merged_paths,
12123 struct got_worktree *worktree, struct got_fileindex *fileindex,
12124 struct got_reference *tmp_branch, struct got_histedit_list_entry *hle,
12125 const char *committer, struct got_repository *repo)
12127 const struct got_error *err;
12128 struct got_commit_object *commit;
12129 struct got_object_id *new_commit_id;
12131 if ((hle->cmd->code == GOT_HISTEDIT_EDIT || get_folded_commits(hle))
12132 && hle->logmsg == NULL) {
12133 err = histedit_edit_logmsg(hle, repo);
12134 if (err)
12135 return err;
12138 err = got_object_open_as_commit(&commit, repo, hle->commit_id);
12139 if (err)
12140 return err;
12142 err = got_worktree_histedit_commit(&new_commit_id, merged_paths,
12143 worktree, fileindex, tmp_branch, committer, commit, hle->commit_id,
12144 hle->logmsg, repo);
12145 if (err) {
12146 if (err->code != GOT_ERR_COMMIT_NO_CHANGES)
12147 goto done;
12148 err = show_histedit_progress(commit, hle, NULL);
12149 } else {
12150 err = show_histedit_progress(commit, hle, new_commit_id);
12151 free(new_commit_id);
12153 done:
12154 got_object_commit_close(commit);
12155 return err;
12158 static const struct got_error *
12159 histedit_skip_commit(struct got_histedit_list_entry *hle,
12160 struct got_worktree *worktree, struct got_repository *repo)
12162 const struct got_error *error;
12163 struct got_commit_object *commit;
12165 error = got_worktree_histedit_skip_commit(worktree, hle->commit_id,
12166 repo);
12167 if (error)
12168 return error;
12170 error = got_object_open_as_commit(&commit, repo, hle->commit_id);
12171 if (error)
12172 return error;
12174 error = show_histedit_progress(commit, hle, NULL);
12175 got_object_commit_close(commit);
12176 return error;
12179 static const struct got_error *
12180 check_local_changes(void *arg, unsigned char status,
12181 unsigned char staged_status, const char *path,
12182 struct got_object_id *blob_id, struct got_object_id *staged_blob_id,
12183 struct got_object_id *commit_id, int dirfd, const char *de_name)
12185 int *have_local_changes = arg;
12187 switch (status) {
12188 case GOT_STATUS_ADD:
12189 case GOT_STATUS_DELETE:
12190 case GOT_STATUS_MODIFY:
12191 case GOT_STATUS_CONFLICT:
12192 *have_local_changes = 1;
12193 return got_error(GOT_ERR_CANCELLED);
12194 default:
12195 break;
12198 switch (staged_status) {
12199 case GOT_STATUS_ADD:
12200 case GOT_STATUS_DELETE:
12201 case GOT_STATUS_MODIFY:
12202 *have_local_changes = 1;
12203 return got_error(GOT_ERR_CANCELLED);
12204 default:
12205 break;
12208 return NULL;
12211 static const struct got_error *
12212 cmd_histedit(int argc, char *argv[])
12214 const struct got_error *error = NULL;
12215 struct got_worktree *worktree = NULL;
12216 struct got_fileindex *fileindex = NULL;
12217 struct got_repository *repo = NULL;
12218 char *cwd = NULL, *committer = NULL, *gitconfig_path = NULL;
12219 struct got_reference *branch = NULL;
12220 struct got_reference *tmp_branch = NULL;
12221 struct got_object_id *resume_commit_id = NULL;
12222 struct got_object_id *base_commit_id = NULL;
12223 struct got_object_id *head_commit_id = NULL;
12224 struct got_commit_object *commit = NULL;
12225 int ch, rebase_in_progress = 0, merge_in_progress = 0;
12226 struct got_update_progress_arg upa;
12227 int edit_in_progress = 0, abort_edit = 0, continue_edit = 0;
12228 int drop_only = 0, edit_logmsg_only = 0, fold_only = 0, edit_only = 0;
12229 int list_backups = 0, delete_backups = 0;
12230 const char *edit_script_path = NULL;
12231 struct got_object_id_queue commits;
12232 struct got_pathlist_head merged_paths;
12233 const struct got_object_id_queue *parent_ids;
12234 struct got_object_qid *pid;
12235 struct got_histedit_list histedit_cmds;
12236 struct got_histedit_list_entry *hle;
12237 int *pack_fds = NULL;
12239 STAILQ_INIT(&commits);
12240 TAILQ_INIT(&histedit_cmds);
12241 TAILQ_INIT(&merged_paths);
12242 memset(&upa, 0, sizeof(upa));
12244 while ((ch = getopt(argc, argv, "acdeF:flmX")) != -1) {
12245 switch (ch) {
12246 case 'a':
12247 abort_edit = 1;
12248 break;
12249 case 'c':
12250 continue_edit = 1;
12251 break;
12252 case 'd':
12253 drop_only = 1;
12254 break;
12255 case 'e':
12256 edit_only = 1;
12257 break;
12258 case 'F':
12259 edit_script_path = optarg;
12260 break;
12261 case 'f':
12262 fold_only = 1;
12263 break;
12264 case 'l':
12265 list_backups = 1;
12266 break;
12267 case 'm':
12268 edit_logmsg_only = 1;
12269 break;
12270 case 'X':
12271 delete_backups = 1;
12272 break;
12273 default:
12274 usage_histedit();
12275 /* NOTREACHED */
12279 argc -= optind;
12280 argv += optind;
12282 #ifndef PROFILE
12283 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
12284 "unveil", NULL) == -1)
12285 err(1, "pledge");
12286 #endif
12287 if (abort_edit && continue_edit)
12288 option_conflict('a', 'c');
12289 if (edit_script_path && edit_logmsg_only)
12290 option_conflict('F', 'm');
12291 if (abort_edit && edit_logmsg_only)
12292 option_conflict('a', 'm');
12293 if (continue_edit && edit_logmsg_only)
12294 option_conflict('c', 'm');
12295 if (abort_edit && fold_only)
12296 option_conflict('a', 'f');
12297 if (continue_edit && fold_only)
12298 option_conflict('c', 'f');
12299 if (fold_only && edit_logmsg_only)
12300 option_conflict('f', 'm');
12301 if (edit_script_path && fold_only)
12302 option_conflict('F', 'f');
12303 if (abort_edit && edit_only)
12304 option_conflict('a', 'e');
12305 if (continue_edit && edit_only)
12306 option_conflict('c', 'e');
12307 if (edit_only && edit_logmsg_only)
12308 option_conflict('e', 'm');
12309 if (edit_script_path && edit_only)
12310 option_conflict('F', 'e');
12311 if (fold_only && edit_only)
12312 option_conflict('f', 'e');
12313 if (drop_only && abort_edit)
12314 option_conflict('d', 'a');
12315 if (drop_only && continue_edit)
12316 option_conflict('d', 'c');
12317 if (drop_only && edit_logmsg_only)
12318 option_conflict('d', 'm');
12319 if (drop_only && edit_only)
12320 option_conflict('d', 'e');
12321 if (drop_only && edit_script_path)
12322 option_conflict('d', 'F');
12323 if (drop_only && fold_only)
12324 option_conflict('d', 'f');
12325 if (list_backups) {
12326 if (abort_edit)
12327 option_conflict('l', 'a');
12328 if (continue_edit)
12329 option_conflict('l', 'c');
12330 if (edit_script_path)
12331 option_conflict('l', 'F');
12332 if (edit_logmsg_only)
12333 option_conflict('l', 'm');
12334 if (drop_only)
12335 option_conflict('l', 'd');
12336 if (fold_only)
12337 option_conflict('l', 'f');
12338 if (edit_only)
12339 option_conflict('l', 'e');
12340 if (delete_backups)
12341 option_conflict('l', 'X');
12342 if (argc != 0 && argc != 1)
12343 usage_histedit();
12344 } else if (delete_backups) {
12345 if (abort_edit)
12346 option_conflict('X', 'a');
12347 if (continue_edit)
12348 option_conflict('X', 'c');
12349 if (drop_only)
12350 option_conflict('X', 'd');
12351 if (edit_script_path)
12352 option_conflict('X', 'F');
12353 if (edit_logmsg_only)
12354 option_conflict('X', 'm');
12355 if (fold_only)
12356 option_conflict('X', 'f');
12357 if (edit_only)
12358 option_conflict('X', 'e');
12359 if (list_backups)
12360 option_conflict('X', 'l');
12361 if (argc != 0 && argc != 1)
12362 usage_histedit();
12363 } else if (argc != 0)
12364 usage_histedit();
12367 * This command cannot apply unveil(2) in all cases because the
12368 * user may choose to run an editor to edit the histedit script
12369 * and to edit individual commit log messages.
12370 * unveil(2) traverses exec(2); if an editor is used we have to
12371 * apply unveil after edit script and log messages have been written.
12372 * XXX TODO: Make use of unveil(2) where possible.
12375 cwd = getcwd(NULL, 0);
12376 if (cwd == NULL) {
12377 error = got_error_from_errno("getcwd");
12378 goto done;
12381 error = got_repo_pack_fds_open(&pack_fds);
12382 if (error != NULL)
12383 goto done;
12385 error = got_worktree_open(&worktree, cwd);
12386 if (error) {
12387 if (list_backups || delete_backups) {
12388 if (error->code != GOT_ERR_NOT_WORKTREE)
12389 goto done;
12390 } else {
12391 if (error->code == GOT_ERR_NOT_WORKTREE)
12392 error = wrap_not_worktree_error(error,
12393 "histedit", cwd);
12394 goto done;
12398 if (list_backups || delete_backups) {
12399 error = got_repo_open(&repo,
12400 worktree ? got_worktree_get_repo_path(worktree) : cwd,
12401 NULL, pack_fds);
12402 if (error != NULL)
12403 goto done;
12404 error = apply_unveil(got_repo_get_path(repo), 0,
12405 worktree ? got_worktree_get_root_path(worktree) : NULL);
12406 if (error)
12407 goto done;
12408 error = process_backup_refs(
12409 GOT_WORKTREE_HISTEDIT_BACKUP_REF_PREFIX,
12410 argc == 1 ? argv[0] : NULL, delete_backups, repo);
12411 goto done; /* nothing else to do */
12414 error = get_gitconfig_path(&gitconfig_path);
12415 if (error)
12416 goto done;
12417 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
12418 gitconfig_path, pack_fds);
12419 if (error != NULL)
12420 goto done;
12422 if (worktree != NULL && !list_backups && !delete_backups) {
12423 error = worktree_has_logmsg_ref("histedit", worktree, repo);
12424 if (error)
12425 goto done;
12428 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
12429 if (error)
12430 goto done;
12431 if (rebase_in_progress) {
12432 error = got_error(GOT_ERR_REBASING);
12433 goto done;
12436 error = got_worktree_merge_in_progress(&merge_in_progress, worktree,
12437 repo);
12438 if (error)
12439 goto done;
12440 if (merge_in_progress) {
12441 error = got_error(GOT_ERR_MERGE_BUSY);
12442 goto done;
12445 error = got_worktree_histedit_in_progress(&edit_in_progress, worktree);
12446 if (error)
12447 goto done;
12449 if (edit_in_progress && edit_logmsg_only) {
12450 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
12451 "histedit operation is in progress in this "
12452 "work tree and must be continued or aborted "
12453 "before the -m option can be used");
12454 goto done;
12456 if (edit_in_progress && drop_only) {
12457 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
12458 "histedit operation is in progress in this "
12459 "work tree and must be continued or aborted "
12460 "before the -d option can be used");
12461 goto done;
12463 if (edit_in_progress && fold_only) {
12464 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
12465 "histedit operation is in progress in this "
12466 "work tree and must be continued or aborted "
12467 "before the -f option can be used");
12468 goto done;
12470 if (edit_in_progress && edit_only) {
12471 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
12472 "histedit operation is in progress in this "
12473 "work tree and must be continued or aborted "
12474 "before the -e option can be used");
12475 goto done;
12478 if (edit_in_progress && abort_edit) {
12479 error = got_worktree_histedit_continue(&resume_commit_id,
12480 &tmp_branch, &branch, &base_commit_id, &fileindex,
12481 worktree, repo);
12482 if (error)
12483 goto done;
12484 printf("Switching work tree to %s\n",
12485 got_ref_get_symref_target(branch));
12486 error = got_worktree_histedit_abort(worktree, fileindex, repo,
12487 branch, base_commit_id, abort_progress, &upa);
12488 if (error)
12489 goto done;
12490 printf("Histedit of %s aborted\n",
12491 got_ref_get_symref_target(branch));
12492 print_merge_progress_stats(&upa);
12493 goto done; /* nothing else to do */
12494 } else if (abort_edit) {
12495 error = got_error(GOT_ERR_NOT_HISTEDIT);
12496 goto done;
12499 error = get_author(&committer, repo, worktree);
12500 if (error)
12501 goto done;
12503 if (continue_edit) {
12504 char *path;
12506 if (!edit_in_progress) {
12507 error = got_error(GOT_ERR_NOT_HISTEDIT);
12508 goto done;
12511 error = got_worktree_get_histedit_script_path(&path, worktree);
12512 if (error)
12513 goto done;
12515 error = histedit_load_list(&histedit_cmds, path, repo);
12516 free(path);
12517 if (error)
12518 goto done;
12520 error = got_worktree_histedit_continue(&resume_commit_id,
12521 &tmp_branch, &branch, &base_commit_id, &fileindex,
12522 worktree, repo);
12523 if (error)
12524 goto done;
12526 error = got_ref_resolve(&head_commit_id, repo, branch);
12527 if (error)
12528 goto done;
12530 error = got_object_open_as_commit(&commit, repo,
12531 head_commit_id);
12532 if (error)
12533 goto done;
12534 parent_ids = got_object_commit_get_parent_ids(commit);
12535 pid = STAILQ_FIRST(parent_ids);
12536 if (pid == NULL) {
12537 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
12538 goto done;
12540 error = collect_commits(&commits, head_commit_id, &pid->id,
12541 base_commit_id, got_worktree_get_path_prefix(worktree),
12542 GOT_ERR_HISTEDIT_PATH, repo);
12543 got_object_commit_close(commit);
12544 commit = NULL;
12545 if (error)
12546 goto done;
12547 } else {
12548 if (edit_in_progress) {
12549 error = got_error(GOT_ERR_HISTEDIT_BUSY);
12550 goto done;
12553 error = got_ref_open(&branch, repo,
12554 got_worktree_get_head_ref_name(worktree), 0);
12555 if (error != NULL)
12556 goto done;
12558 if (strncmp(got_ref_get_name(branch), "refs/heads/", 11) != 0) {
12559 error = got_error_msg(GOT_ERR_COMMIT_BRANCH,
12560 "will not edit commit history of a branch outside "
12561 "the \"refs/heads/\" reference namespace");
12562 goto done;
12565 error = got_ref_resolve(&head_commit_id, repo, branch);
12566 got_ref_close(branch);
12567 branch = NULL;
12568 if (error)
12569 goto done;
12571 error = got_object_open_as_commit(&commit, repo,
12572 head_commit_id);
12573 if (error)
12574 goto done;
12575 parent_ids = got_object_commit_get_parent_ids(commit);
12576 pid = STAILQ_FIRST(parent_ids);
12577 if (pid == NULL) {
12578 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
12579 goto done;
12581 error = collect_commits(&commits, head_commit_id, &pid->id,
12582 got_worktree_get_base_commit_id(worktree),
12583 got_worktree_get_path_prefix(worktree),
12584 GOT_ERR_HISTEDIT_PATH, repo);
12585 got_object_commit_close(commit);
12586 commit = NULL;
12587 if (error)
12588 goto done;
12590 if (STAILQ_EMPTY(&commits)) {
12591 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
12592 goto done;
12595 error = got_worktree_histedit_prepare(&tmp_branch, &branch,
12596 &base_commit_id, &fileindex, worktree, repo);
12597 if (error)
12598 goto done;
12600 if (edit_script_path) {
12601 error = histedit_load_list(&histedit_cmds,
12602 edit_script_path, repo);
12603 if (error) {
12604 got_worktree_histedit_abort(worktree, fileindex,
12605 repo, branch, base_commit_id,
12606 abort_progress, &upa);
12607 print_merge_progress_stats(&upa);
12608 goto done;
12610 } else {
12611 const char *branch_name;
12612 branch_name = got_ref_get_symref_target(branch);
12613 if (strncmp(branch_name, "refs/heads/", 11) == 0)
12614 branch_name += 11;
12615 error = histedit_edit_script(&histedit_cmds, &commits,
12616 branch_name, edit_logmsg_only, fold_only,
12617 drop_only, edit_only, repo);
12618 if (error) {
12619 got_worktree_histedit_abort(worktree, fileindex,
12620 repo, branch, base_commit_id,
12621 abort_progress, &upa);
12622 print_merge_progress_stats(&upa);
12623 goto done;
12628 error = histedit_save_list(&histedit_cmds, worktree,
12629 repo);
12630 if (error) {
12631 got_worktree_histedit_abort(worktree, fileindex,
12632 repo, branch, base_commit_id,
12633 abort_progress, &upa);
12634 print_merge_progress_stats(&upa);
12635 goto done;
12640 error = histedit_check_script(&histedit_cmds, &commits, repo);
12641 if (error)
12642 goto done;
12644 TAILQ_FOREACH(hle, &histedit_cmds, entry) {
12645 if (resume_commit_id) {
12646 if (got_object_id_cmp(hle->commit_id,
12647 resume_commit_id) != 0)
12648 continue;
12650 resume_commit_id = NULL;
12651 if (hle->cmd->code == GOT_HISTEDIT_DROP ||
12652 hle->cmd->code == GOT_HISTEDIT_FOLD) {
12653 error = histedit_skip_commit(hle, worktree,
12654 repo);
12655 if (error)
12656 goto done;
12657 } else {
12658 struct got_pathlist_head paths;
12659 int have_changes = 0;
12661 TAILQ_INIT(&paths);
12662 error = got_pathlist_append(&paths, "", NULL);
12663 if (error)
12664 goto done;
12665 error = got_worktree_status(worktree, &paths,
12666 repo, 0, check_local_changes, &have_changes,
12667 check_cancelled, NULL);
12668 got_pathlist_free(&paths,
12669 GOT_PATHLIST_FREE_NONE);
12670 if (error) {
12671 if (error->code != GOT_ERR_CANCELLED)
12672 goto done;
12673 if (sigint_received || sigpipe_received)
12674 goto done;
12676 if (have_changes) {
12677 error = histedit_commit(NULL, worktree,
12678 fileindex, tmp_branch, hle,
12679 committer, repo);
12680 if (error)
12681 goto done;
12682 } else {
12683 error = got_object_open_as_commit(
12684 &commit, repo, hle->commit_id);
12685 if (error)
12686 goto done;
12687 error = show_histedit_progress(commit,
12688 hle, NULL);
12689 got_object_commit_close(commit);
12690 commit = NULL;
12691 if (error)
12692 goto done;
12695 continue;
12698 if (hle->cmd->code == GOT_HISTEDIT_DROP) {
12699 error = histedit_skip_commit(hle, worktree, repo);
12700 if (error)
12701 goto done;
12702 continue;
12705 error = got_object_open_as_commit(&commit, repo,
12706 hle->commit_id);
12707 if (error)
12708 goto done;
12709 parent_ids = got_object_commit_get_parent_ids(commit);
12710 pid = STAILQ_FIRST(parent_ids);
12712 error = got_worktree_histedit_merge_files(&merged_paths,
12713 worktree, fileindex, &pid->id, hle->commit_id, repo,
12714 update_progress, &upa, check_cancelled, NULL);
12715 if (error)
12716 goto done;
12717 got_object_commit_close(commit);
12718 commit = NULL;
12720 print_merge_progress_stats(&upa);
12721 if (upa.conflicts > 0 || upa.missing > 0 ||
12722 upa.not_deleted > 0 || upa.unversioned > 0) {
12723 if (upa.conflicts > 0) {
12724 error = show_rebase_merge_conflict(
12725 hle->commit_id, repo);
12726 if (error)
12727 goto done;
12729 got_pathlist_free(&merged_paths, GOT_PATHLIST_FREE_PATH);
12730 break;
12733 if (hle->cmd->code == GOT_HISTEDIT_EDIT) {
12734 char *id_str;
12735 error = got_object_id_str(&id_str, hle->commit_id);
12736 if (error)
12737 goto done;
12738 printf("Stopping histedit for amending commit %s\n",
12739 id_str);
12740 free(id_str);
12741 got_pathlist_free(&merged_paths, GOT_PATHLIST_FREE_PATH);
12742 error = got_worktree_histedit_postpone(worktree,
12743 fileindex);
12744 goto done;
12747 if (hle->cmd->code == GOT_HISTEDIT_FOLD) {
12748 error = histedit_skip_commit(hle, worktree, repo);
12749 if (error)
12750 goto done;
12751 continue;
12754 error = histedit_commit(&merged_paths, worktree, fileindex,
12755 tmp_branch, hle, committer, repo);
12756 got_pathlist_free(&merged_paths, GOT_PATHLIST_FREE_PATH);
12757 if (error)
12758 goto done;
12761 if (upa.conflicts > 0 || upa.missing > 0 ||
12762 upa.not_deleted > 0 || upa.unversioned > 0) {
12763 error = got_worktree_histedit_postpone(worktree, fileindex);
12764 if (error)
12765 goto done;
12766 if (upa.conflicts > 0 && upa.missing == 0 &&
12767 upa.not_deleted == 0 && upa.unversioned == 0) {
12768 error = got_error_msg(GOT_ERR_CONFLICTS,
12769 "conflicts must be resolved before histedit "
12770 "can continue");
12771 } else if (upa.conflicts > 0) {
12772 error = got_error_msg(GOT_ERR_CONFLICTS,
12773 "conflicts must be resolved before histedit "
12774 "can continue; changes destined for some "
12775 "files were not yet merged and should be "
12776 "merged manually if required before the "
12777 "histedit operation is continued");
12778 } else {
12779 error = got_error_msg(GOT_ERR_CONFLICTS,
12780 "changes destined for some files were not "
12781 "yet merged and should be merged manually "
12782 "if required before the histedit operation "
12783 "is continued");
12785 } else
12786 error = histedit_complete(worktree, fileindex, tmp_branch,
12787 branch, repo);
12788 done:
12789 free(cwd);
12790 free(committer);
12791 free(gitconfig_path);
12792 got_object_id_queue_free(&commits);
12793 histedit_free_list(&histedit_cmds);
12794 free(head_commit_id);
12795 free(base_commit_id);
12796 free(resume_commit_id);
12797 if (commit)
12798 got_object_commit_close(commit);
12799 if (branch)
12800 got_ref_close(branch);
12801 if (tmp_branch)
12802 got_ref_close(tmp_branch);
12803 if (worktree)
12804 got_worktree_close(worktree);
12805 if (repo) {
12806 const struct got_error *close_err = got_repo_close(repo);
12807 if (error == NULL)
12808 error = close_err;
12810 if (pack_fds) {
12811 const struct got_error *pack_err =
12812 got_repo_pack_fds_close(pack_fds);
12813 if (error == NULL)
12814 error = pack_err;
12816 return error;
12819 __dead static void
12820 usage_integrate(void)
12822 fprintf(stderr, "usage: %s integrate branch\n", getprogname());
12823 exit(1);
12826 static const struct got_error *
12827 cmd_integrate(int argc, char *argv[])
12829 const struct got_error *error = NULL;
12830 struct got_repository *repo = NULL;
12831 struct got_worktree *worktree = NULL;
12832 char *cwd = NULL, *refname = NULL, *base_refname = NULL;
12833 const char *branch_arg = NULL;
12834 struct got_reference *branch_ref = NULL, *base_branch_ref = NULL;
12835 struct got_fileindex *fileindex = NULL;
12836 struct got_object_id *commit_id = NULL, *base_commit_id = NULL;
12837 int ch;
12838 struct got_update_progress_arg upa;
12839 int *pack_fds = NULL;
12841 while ((ch = getopt(argc, argv, "")) != -1) {
12842 switch (ch) {
12843 default:
12844 usage_integrate();
12845 /* NOTREACHED */
12849 argc -= optind;
12850 argv += optind;
12852 if (argc != 1)
12853 usage_integrate();
12854 branch_arg = argv[0];
12855 #ifndef PROFILE
12856 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
12857 "unveil", NULL) == -1)
12858 err(1, "pledge");
12859 #endif
12860 cwd = getcwd(NULL, 0);
12861 if (cwd == NULL) {
12862 error = got_error_from_errno("getcwd");
12863 goto done;
12866 error = got_repo_pack_fds_open(&pack_fds);
12867 if (error != NULL)
12868 goto done;
12870 error = got_worktree_open(&worktree, cwd);
12871 if (error) {
12872 if (error->code == GOT_ERR_NOT_WORKTREE)
12873 error = wrap_not_worktree_error(error, "integrate",
12874 cwd);
12875 goto done;
12878 error = check_rebase_or_histedit_in_progress(worktree);
12879 if (error)
12880 goto done;
12882 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
12883 NULL, pack_fds);
12884 if (error != NULL)
12885 goto done;
12887 error = apply_unveil(got_repo_get_path(repo), 0,
12888 got_worktree_get_root_path(worktree));
12889 if (error)
12890 goto done;
12892 error = check_merge_in_progress(worktree, repo);
12893 if (error)
12894 goto done;
12896 if (asprintf(&refname, "refs/heads/%s", branch_arg) == -1) {
12897 error = got_error_from_errno("asprintf");
12898 goto done;
12901 error = got_worktree_integrate_prepare(&fileindex, &branch_ref,
12902 &base_branch_ref, worktree, refname, repo);
12903 if (error)
12904 goto done;
12906 refname = strdup(got_ref_get_name(branch_ref));
12907 if (refname == NULL) {
12908 error = got_error_from_errno("strdup");
12909 got_worktree_integrate_abort(worktree, fileindex, repo,
12910 branch_ref, base_branch_ref);
12911 goto done;
12913 base_refname = strdup(got_ref_get_name(base_branch_ref));
12914 if (base_refname == NULL) {
12915 error = got_error_from_errno("strdup");
12916 got_worktree_integrate_abort(worktree, fileindex, repo,
12917 branch_ref, base_branch_ref);
12918 goto done;
12920 if (strncmp(base_refname, "refs/heads/", 11) != 0) {
12921 error = got_error(GOT_ERR_INTEGRATE_BRANCH);
12922 got_worktree_integrate_abort(worktree, fileindex, repo,
12923 branch_ref, base_branch_ref);
12924 goto done;
12927 error = got_ref_resolve(&commit_id, repo, branch_ref);
12928 if (error)
12929 goto done;
12931 error = got_ref_resolve(&base_commit_id, repo, base_branch_ref);
12932 if (error)
12933 goto done;
12935 if (got_object_id_cmp(commit_id, base_commit_id) == 0) {
12936 error = got_error_msg(GOT_ERR_SAME_BRANCH,
12937 "specified branch has already been integrated");
12938 got_worktree_integrate_abort(worktree, fileindex, repo,
12939 branch_ref, base_branch_ref);
12940 goto done;
12943 error = check_linear_ancestry(commit_id, base_commit_id, 1, repo);
12944 if (error) {
12945 if (error->code == GOT_ERR_ANCESTRY)
12946 error = got_error(GOT_ERR_REBASE_REQUIRED);
12947 got_worktree_integrate_abort(worktree, fileindex, repo,
12948 branch_ref, base_branch_ref);
12949 goto done;
12952 memset(&upa, 0, sizeof(upa));
12953 error = got_worktree_integrate_continue(worktree, fileindex, repo,
12954 branch_ref, base_branch_ref, update_progress, &upa,
12955 check_cancelled, NULL);
12956 if (error)
12957 goto done;
12959 printf("Integrated %s into %s\n", refname, base_refname);
12960 print_update_progress_stats(&upa);
12961 done:
12962 if (repo) {
12963 const struct got_error *close_err = got_repo_close(repo);
12964 if (error == NULL)
12965 error = close_err;
12967 if (worktree)
12968 got_worktree_close(worktree);
12969 if (pack_fds) {
12970 const struct got_error *pack_err =
12971 got_repo_pack_fds_close(pack_fds);
12972 if (error == NULL)
12973 error = pack_err;
12975 free(cwd);
12976 free(base_commit_id);
12977 free(commit_id);
12978 free(refname);
12979 free(base_refname);
12980 return error;
12983 __dead static void
12984 usage_merge(void)
12986 fprintf(stderr, "usage: %s merge [-acn] [branch]\n", getprogname());
12987 exit(1);
12990 static const struct got_error *
12991 cmd_merge(int argc, char *argv[])
12993 const struct got_error *error = NULL;
12994 struct got_worktree *worktree = NULL;
12995 struct got_repository *repo = NULL;
12996 struct got_fileindex *fileindex = NULL;
12997 char *cwd = NULL, *id_str = NULL, *author = NULL;
12998 struct got_reference *branch = NULL, *wt_branch = NULL;
12999 struct got_object_id *branch_tip = NULL, *yca_id = NULL;
13000 struct got_object_id *wt_branch_tip = NULL;
13001 int ch, merge_in_progress = 0, abort_merge = 0, continue_merge = 0;
13002 int interrupt_merge = 0;
13003 struct got_update_progress_arg upa;
13004 struct got_object_id *merge_commit_id = NULL;
13005 char *branch_name = NULL;
13006 int *pack_fds = NULL;
13008 memset(&upa, 0, sizeof(upa));
13010 while ((ch = getopt(argc, argv, "acn")) != -1) {
13011 switch (ch) {
13012 case 'a':
13013 abort_merge = 1;
13014 break;
13015 case 'c':
13016 continue_merge = 1;
13017 break;
13018 case 'n':
13019 interrupt_merge = 1;
13020 break;
13021 default:
13022 usage_merge();
13023 /* NOTREACHED */
13027 argc -= optind;
13028 argv += optind;
13030 #ifndef PROFILE
13031 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
13032 "unveil", NULL) == -1)
13033 err(1, "pledge");
13034 #endif
13036 if (abort_merge && continue_merge)
13037 option_conflict('a', 'c');
13038 if (abort_merge || continue_merge) {
13039 if (argc != 0)
13040 usage_merge();
13041 } else if (argc != 1)
13042 usage_merge();
13044 cwd = getcwd(NULL, 0);
13045 if (cwd == NULL) {
13046 error = got_error_from_errno("getcwd");
13047 goto done;
13050 error = got_repo_pack_fds_open(&pack_fds);
13051 if (error != NULL)
13052 goto done;
13054 error = got_worktree_open(&worktree, cwd);
13055 if (error) {
13056 if (error->code == GOT_ERR_NOT_WORKTREE)
13057 error = wrap_not_worktree_error(error,
13058 "merge", cwd);
13059 goto done;
13062 error = got_repo_open(&repo,
13063 worktree ? got_worktree_get_repo_path(worktree) : cwd, NULL,
13064 pack_fds);
13065 if (error != NULL)
13066 goto done;
13068 if (worktree != NULL) {
13069 error = worktree_has_logmsg_ref("merge", worktree, repo);
13070 if (error)
13071 goto done;
13074 error = apply_unveil(got_repo_get_path(repo), 0,
13075 worktree ? got_worktree_get_root_path(worktree) : NULL);
13076 if (error)
13077 goto done;
13079 error = check_rebase_or_histedit_in_progress(worktree);
13080 if (error)
13081 goto done;
13083 error = got_worktree_merge_in_progress(&merge_in_progress, worktree,
13084 repo);
13085 if (error)
13086 goto done;
13088 if (abort_merge) {
13089 if (!merge_in_progress) {
13090 error = got_error(GOT_ERR_NOT_MERGING);
13091 goto done;
13093 error = got_worktree_merge_continue(&branch_name,
13094 &branch_tip, &fileindex, worktree, repo);
13095 if (error)
13096 goto done;
13097 error = got_worktree_merge_abort(worktree, fileindex, repo,
13098 abort_progress, &upa);
13099 if (error)
13100 goto done;
13101 printf("Merge of %s aborted\n", branch_name);
13102 goto done; /* nothing else to do */
13105 error = get_author(&author, repo, worktree);
13106 if (error)
13107 goto done;
13109 if (continue_merge) {
13110 if (!merge_in_progress) {
13111 error = got_error(GOT_ERR_NOT_MERGING);
13112 goto done;
13114 error = got_worktree_merge_continue(&branch_name,
13115 &branch_tip, &fileindex, worktree, repo);
13116 if (error)
13117 goto done;
13118 } else {
13119 error = got_ref_open(&branch, repo, argv[0], 0);
13120 if (error != NULL)
13121 goto done;
13122 branch_name = strdup(got_ref_get_name(branch));
13123 if (branch_name == NULL) {
13124 error = got_error_from_errno("strdup");
13125 goto done;
13127 error = got_ref_resolve(&branch_tip, repo, branch);
13128 if (error)
13129 goto done;
13132 error = got_ref_open(&wt_branch, repo,
13133 got_worktree_get_head_ref_name(worktree), 0);
13134 if (error)
13135 goto done;
13136 error = got_ref_resolve(&wt_branch_tip, repo, wt_branch);
13137 if (error)
13138 goto done;
13139 error = got_commit_graph_find_youngest_common_ancestor(&yca_id,
13140 wt_branch_tip, branch_tip, 0, repo,
13141 check_cancelled, NULL);
13142 if (error && error->code != GOT_ERR_ANCESTRY)
13143 goto done;
13145 if (!continue_merge) {
13146 error = check_path_prefix(wt_branch_tip, branch_tip,
13147 got_worktree_get_path_prefix(worktree),
13148 GOT_ERR_MERGE_PATH, repo);
13149 if (error)
13150 goto done;
13151 if (yca_id) {
13152 error = check_same_branch(wt_branch_tip, branch,
13153 yca_id, repo);
13154 if (error) {
13155 if (error->code != GOT_ERR_ANCESTRY)
13156 goto done;
13157 error = NULL;
13158 } else {
13159 static char msg[512];
13160 snprintf(msg, sizeof(msg),
13161 "cannot create a merge commit because "
13162 "%s is based on %s; %s can be integrated "
13163 "with 'got integrate' instead", branch_name,
13164 got_worktree_get_head_ref_name(worktree),
13165 branch_name);
13166 error = got_error_msg(GOT_ERR_SAME_BRANCH, msg);
13167 goto done;
13170 error = got_worktree_merge_prepare(&fileindex, worktree,
13171 branch, repo);
13172 if (error)
13173 goto done;
13175 error = got_worktree_merge_branch(worktree, fileindex,
13176 yca_id, branch_tip, repo, update_progress, &upa,
13177 check_cancelled, NULL);
13178 if (error)
13179 goto done;
13180 print_merge_progress_stats(&upa);
13181 if (!upa.did_something) {
13182 error = got_worktree_merge_abort(worktree, fileindex,
13183 repo, abort_progress, &upa);
13184 if (error)
13185 goto done;
13186 printf("Already up-to-date\n");
13187 goto done;
13191 if (interrupt_merge) {
13192 error = got_worktree_merge_postpone(worktree, fileindex);
13193 if (error)
13194 goto done;
13195 printf("Merge of %s interrupted on request\n", branch_name);
13196 } else if (upa.conflicts > 0 || upa.missing > 0 ||
13197 upa.not_deleted > 0 || upa.unversioned > 0) {
13198 error = got_worktree_merge_postpone(worktree, fileindex);
13199 if (error)
13200 goto done;
13201 if (upa.conflicts > 0 && upa.missing == 0 &&
13202 upa.not_deleted == 0 && upa.unversioned == 0) {
13203 error = got_error_msg(GOT_ERR_CONFLICTS,
13204 "conflicts must be resolved before merging "
13205 "can continue");
13206 } else if (upa.conflicts > 0) {
13207 error = got_error_msg(GOT_ERR_CONFLICTS,
13208 "conflicts must be resolved before merging "
13209 "can continue; changes destined for some "
13210 "files were not yet merged and "
13211 "should be merged manually if required before the "
13212 "merge operation is continued");
13213 } else {
13214 error = got_error_msg(GOT_ERR_CONFLICTS,
13215 "changes destined for some "
13216 "files were not yet merged and should be "
13217 "merged manually if required before the "
13218 "merge operation is continued");
13220 goto done;
13221 } else {
13222 error = got_worktree_merge_commit(&merge_commit_id, worktree,
13223 fileindex, author, NULL, 1, branch_tip, branch_name,
13224 repo, continue_merge ? print_status : NULL, NULL);
13225 if (error)
13226 goto done;
13227 error = got_worktree_merge_complete(worktree, fileindex, repo);
13228 if (error)
13229 goto done;
13230 error = got_object_id_str(&id_str, merge_commit_id);
13231 if (error)
13232 goto done;
13233 printf("Merged %s into %s: %s\n", branch_name,
13234 got_worktree_get_head_ref_name(worktree),
13235 id_str);
13238 done:
13239 free(id_str);
13240 free(merge_commit_id);
13241 free(author);
13242 free(branch_tip);
13243 free(branch_name);
13244 free(yca_id);
13245 if (branch)
13246 got_ref_close(branch);
13247 if (wt_branch)
13248 got_ref_close(wt_branch);
13249 if (worktree)
13250 got_worktree_close(worktree);
13251 if (repo) {
13252 const struct got_error *close_err = got_repo_close(repo);
13253 if (error == NULL)
13254 error = close_err;
13256 if (pack_fds) {
13257 const struct got_error *pack_err =
13258 got_repo_pack_fds_close(pack_fds);
13259 if (error == NULL)
13260 error = pack_err;
13262 return error;
13265 __dead static void
13266 usage_stage(void)
13268 fprintf(stderr, "usage: %s stage [-lpS] [-F response-script] "
13269 "[path ...]\n", getprogname());
13270 exit(1);
13273 static const struct got_error *
13274 print_stage(void *arg, unsigned char status, unsigned char staged_status,
13275 const char *path, struct got_object_id *blob_id,
13276 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
13277 int dirfd, const char *de_name)
13279 const struct got_error *err = NULL;
13280 char *id_str = NULL;
13282 if (staged_status != GOT_STATUS_ADD &&
13283 staged_status != GOT_STATUS_MODIFY &&
13284 staged_status != GOT_STATUS_DELETE)
13285 return NULL;
13287 if (staged_status == GOT_STATUS_ADD ||
13288 staged_status == GOT_STATUS_MODIFY)
13289 err = got_object_id_str(&id_str, staged_blob_id);
13290 else
13291 err = got_object_id_str(&id_str, blob_id);
13292 if (err)
13293 return err;
13295 printf("%s %c %s\n", id_str, staged_status, path);
13296 free(id_str);
13297 return NULL;
13300 static const struct got_error *
13301 cmd_stage(int argc, char *argv[])
13303 const struct got_error *error = NULL;
13304 struct got_repository *repo = NULL;
13305 struct got_worktree *worktree = NULL;
13306 char *cwd = NULL;
13307 struct got_pathlist_head paths;
13308 int ch, list_stage = 0, pflag = 0, allow_bad_symlinks = 0;
13309 FILE *patch_script_file = NULL;
13310 const char *patch_script_path = NULL;
13311 struct choose_patch_arg cpa;
13312 int *pack_fds = NULL;
13314 TAILQ_INIT(&paths);
13316 while ((ch = getopt(argc, argv, "F:lpS")) != -1) {
13317 switch (ch) {
13318 case 'F':
13319 patch_script_path = optarg;
13320 break;
13321 case 'l':
13322 list_stage = 1;
13323 break;
13324 case 'p':
13325 pflag = 1;
13326 break;
13327 case 'S':
13328 allow_bad_symlinks = 1;
13329 break;
13330 default:
13331 usage_stage();
13332 /* NOTREACHED */
13336 argc -= optind;
13337 argv += optind;
13339 #ifndef PROFILE
13340 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
13341 "unveil", NULL) == -1)
13342 err(1, "pledge");
13343 #endif
13344 if (list_stage && (pflag || patch_script_path))
13345 errx(1, "-l option cannot be used with other options");
13346 if (patch_script_path && !pflag)
13347 errx(1, "-F option can only be used together with -p option");
13349 cwd = getcwd(NULL, 0);
13350 if (cwd == NULL) {
13351 error = got_error_from_errno("getcwd");
13352 goto done;
13355 error = got_repo_pack_fds_open(&pack_fds);
13356 if (error != NULL)
13357 goto done;
13359 error = got_worktree_open(&worktree, cwd);
13360 if (error) {
13361 if (error->code == GOT_ERR_NOT_WORKTREE)
13362 error = wrap_not_worktree_error(error, "stage", cwd);
13363 goto done;
13366 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
13367 NULL, pack_fds);
13368 if (error != NULL)
13369 goto done;
13371 if (patch_script_path) {
13372 patch_script_file = fopen(patch_script_path, "re");
13373 if (patch_script_file == NULL) {
13374 error = got_error_from_errno2("fopen",
13375 patch_script_path);
13376 goto done;
13379 error = apply_unveil(got_repo_get_path(repo), 0,
13380 got_worktree_get_root_path(worktree));
13381 if (error)
13382 goto done;
13384 error = check_merge_in_progress(worktree, repo);
13385 if (error)
13386 goto done;
13388 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
13389 if (error)
13390 goto done;
13392 if (list_stage)
13393 error = got_worktree_status(worktree, &paths, repo, 0,
13394 print_stage, NULL, check_cancelled, NULL);
13395 else {
13396 cpa.patch_script_file = patch_script_file;
13397 cpa.action = "stage";
13398 error = got_worktree_stage(worktree, &paths,
13399 pflag ? NULL : print_status, NULL,
13400 pflag ? choose_patch : NULL, &cpa,
13401 allow_bad_symlinks, repo);
13403 done:
13404 if (patch_script_file && fclose(patch_script_file) == EOF &&
13405 error == NULL)
13406 error = got_error_from_errno2("fclose", patch_script_path);
13407 if (repo) {
13408 const struct got_error *close_err = got_repo_close(repo);
13409 if (error == NULL)
13410 error = close_err;
13412 if (worktree)
13413 got_worktree_close(worktree);
13414 if (pack_fds) {
13415 const struct got_error *pack_err =
13416 got_repo_pack_fds_close(pack_fds);
13417 if (error == NULL)
13418 error = pack_err;
13420 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
13421 free(cwd);
13422 return error;
13425 __dead static void
13426 usage_unstage(void)
13428 fprintf(stderr, "usage: %s unstage [-p] [-F response-script] "
13429 "[path ...]\n", getprogname());
13430 exit(1);
13434 static const struct got_error *
13435 cmd_unstage(int argc, char *argv[])
13437 const struct got_error *error = NULL;
13438 struct got_repository *repo = NULL;
13439 struct got_worktree *worktree = NULL;
13440 char *cwd = NULL;
13441 struct got_pathlist_head paths;
13442 int ch, pflag = 0;
13443 struct got_update_progress_arg upa;
13444 FILE *patch_script_file = NULL;
13445 const char *patch_script_path = NULL;
13446 struct choose_patch_arg cpa;
13447 int *pack_fds = NULL;
13449 TAILQ_INIT(&paths);
13451 while ((ch = getopt(argc, argv, "F:p")) != -1) {
13452 switch (ch) {
13453 case 'F':
13454 patch_script_path = optarg;
13455 break;
13456 case 'p':
13457 pflag = 1;
13458 break;
13459 default:
13460 usage_unstage();
13461 /* NOTREACHED */
13465 argc -= optind;
13466 argv += optind;
13468 #ifndef PROFILE
13469 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
13470 "unveil", NULL) == -1)
13471 err(1, "pledge");
13472 #endif
13473 if (patch_script_path && !pflag)
13474 errx(1, "-F option can only be used together with -p option");
13476 cwd = getcwd(NULL, 0);
13477 if (cwd == NULL) {
13478 error = got_error_from_errno("getcwd");
13479 goto done;
13482 error = got_repo_pack_fds_open(&pack_fds);
13483 if (error != NULL)
13484 goto done;
13486 error = got_worktree_open(&worktree, cwd);
13487 if (error) {
13488 if (error->code == GOT_ERR_NOT_WORKTREE)
13489 error = wrap_not_worktree_error(error, "unstage", cwd);
13490 goto done;
13493 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
13494 NULL, pack_fds);
13495 if (error != NULL)
13496 goto done;
13498 if (patch_script_path) {
13499 patch_script_file = fopen(patch_script_path, "re");
13500 if (patch_script_file == NULL) {
13501 error = got_error_from_errno2("fopen",
13502 patch_script_path);
13503 goto done;
13507 error = apply_unveil(got_repo_get_path(repo), 0,
13508 got_worktree_get_root_path(worktree));
13509 if (error)
13510 goto done;
13512 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
13513 if (error)
13514 goto done;
13516 cpa.patch_script_file = patch_script_file;
13517 cpa.action = "unstage";
13518 memset(&upa, 0, sizeof(upa));
13519 error = got_worktree_unstage(worktree, &paths, update_progress,
13520 &upa, pflag ? choose_patch : NULL, &cpa, repo);
13521 if (!error)
13522 print_merge_progress_stats(&upa);
13523 done:
13524 if (patch_script_file && fclose(patch_script_file) == EOF &&
13525 error == NULL)
13526 error = got_error_from_errno2("fclose", patch_script_path);
13527 if (repo) {
13528 const struct got_error *close_err = got_repo_close(repo);
13529 if (error == NULL)
13530 error = close_err;
13532 if (worktree)
13533 got_worktree_close(worktree);
13534 if (pack_fds) {
13535 const struct got_error *pack_err =
13536 got_repo_pack_fds_close(pack_fds);
13537 if (error == NULL)
13538 error = pack_err;
13540 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
13541 free(cwd);
13542 return error;
13545 __dead static void
13546 usage_cat(void)
13548 fprintf(stderr, "usage: %s cat [-P] [-c commit] [-r repository-path] "
13549 "arg ...\n", getprogname());
13550 exit(1);
13553 static const struct got_error *
13554 cat_blob(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
13556 const struct got_error *err;
13557 struct got_blob_object *blob;
13558 int fd = -1;
13560 fd = got_opentempfd();
13561 if (fd == -1)
13562 return got_error_from_errno("got_opentempfd");
13564 err = got_object_open_as_blob(&blob, repo, id, 8192, fd);
13565 if (err)
13566 goto done;
13568 err = got_object_blob_dump_to_file(NULL, NULL, NULL, outfile, blob);
13569 done:
13570 if (fd != -1 && close(fd) == -1 && err == NULL)
13571 err = got_error_from_errno("close");
13572 if (blob)
13573 got_object_blob_close(blob);
13574 return err;
13577 static const struct got_error *
13578 cat_tree(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
13580 const struct got_error *err;
13581 struct got_tree_object *tree;
13582 int nentries, i;
13584 err = got_object_open_as_tree(&tree, repo, id);
13585 if (err)
13586 return err;
13588 nentries = got_object_tree_get_nentries(tree);
13589 for (i = 0; i < nentries; i++) {
13590 struct got_tree_entry *te;
13591 char *id_str;
13592 if (sigint_received || sigpipe_received)
13593 break;
13594 te = got_object_tree_get_entry(tree, i);
13595 err = got_object_id_str(&id_str, got_tree_entry_get_id(te));
13596 if (err)
13597 break;
13598 fprintf(outfile, "%s %.7o %s\n", id_str,
13599 got_tree_entry_get_mode(te),
13600 got_tree_entry_get_name(te));
13601 free(id_str);
13604 got_object_tree_close(tree);
13605 return err;
13608 static const struct got_error *
13609 cat_commit(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
13611 const struct got_error *err;
13612 struct got_commit_object *commit;
13613 const struct got_object_id_queue *parent_ids;
13614 struct got_object_qid *pid;
13615 char *id_str = NULL;
13616 const char *logmsg = NULL;
13617 char gmtoff[6];
13619 err = got_object_open_as_commit(&commit, repo, id);
13620 if (err)
13621 return err;
13623 err = got_object_id_str(&id_str, got_object_commit_get_tree_id(commit));
13624 if (err)
13625 goto done;
13627 fprintf(outfile, "%s%s\n", GOT_COMMIT_LABEL_TREE, id_str);
13628 parent_ids = got_object_commit_get_parent_ids(commit);
13629 fprintf(outfile, "numparents %d\n",
13630 got_object_commit_get_nparents(commit));
13631 STAILQ_FOREACH(pid, parent_ids, entry) {
13632 char *pid_str;
13633 err = got_object_id_str(&pid_str, &pid->id);
13634 if (err)
13635 goto done;
13636 fprintf(outfile, "%s%s\n", GOT_COMMIT_LABEL_PARENT, pid_str);
13637 free(pid_str);
13639 got_date_format_gmtoff(gmtoff, sizeof(gmtoff),
13640 got_object_commit_get_author_gmtoff(commit));
13641 fprintf(outfile, "%s%s %lld %s\n", GOT_COMMIT_LABEL_AUTHOR,
13642 got_object_commit_get_author(commit),
13643 (long long)got_object_commit_get_author_time(commit),
13644 gmtoff);
13646 got_date_format_gmtoff(gmtoff, sizeof(gmtoff),
13647 got_object_commit_get_committer_gmtoff(commit));
13648 fprintf(outfile, "%s%s %lld %s\n", GOT_COMMIT_LABEL_COMMITTER,
13649 got_object_commit_get_committer(commit),
13650 (long long)got_object_commit_get_committer_time(commit),
13651 gmtoff);
13653 logmsg = got_object_commit_get_logmsg_raw(commit);
13654 fprintf(outfile, "messagelen %zd\n", strlen(logmsg));
13655 fprintf(outfile, "%s", logmsg);
13656 done:
13657 free(id_str);
13658 got_object_commit_close(commit);
13659 return err;
13662 static const struct got_error *
13663 cat_tag(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
13665 const struct got_error *err;
13666 struct got_tag_object *tag;
13667 char *id_str = NULL;
13668 const char *tagmsg = NULL;
13669 char gmtoff[6];
13671 err = got_object_open_as_tag(&tag, repo, id);
13672 if (err)
13673 return err;
13675 err = got_object_id_str(&id_str, got_object_tag_get_object_id(tag));
13676 if (err)
13677 goto done;
13679 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_OBJECT, id_str);
13681 switch (got_object_tag_get_object_type(tag)) {
13682 case GOT_OBJ_TYPE_BLOB:
13683 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
13684 GOT_OBJ_LABEL_BLOB);
13685 break;
13686 case GOT_OBJ_TYPE_TREE:
13687 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
13688 GOT_OBJ_LABEL_TREE);
13689 break;
13690 case GOT_OBJ_TYPE_COMMIT:
13691 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
13692 GOT_OBJ_LABEL_COMMIT);
13693 break;
13694 case GOT_OBJ_TYPE_TAG:
13695 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
13696 GOT_OBJ_LABEL_TAG);
13697 break;
13698 default:
13699 break;
13702 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TAG,
13703 got_object_tag_get_name(tag));
13705 got_date_format_gmtoff(gmtoff, sizeof(gmtoff),
13706 got_object_tag_get_tagger_gmtoff(tag));
13707 fprintf(outfile, "%s%s %lld %s\n", GOT_TAG_LABEL_TAGGER,
13708 got_object_tag_get_tagger(tag),
13709 (long long)got_object_tag_get_tagger_time(tag),
13710 gmtoff);
13712 tagmsg = got_object_tag_get_message(tag);
13713 fprintf(outfile, "messagelen %zd\n", strlen(tagmsg));
13714 fprintf(outfile, "%s", tagmsg);
13715 done:
13716 free(id_str);
13717 got_object_tag_close(tag);
13718 return err;
13721 static const struct got_error *
13722 cmd_cat(int argc, char *argv[])
13724 const struct got_error *error;
13725 struct got_repository *repo = NULL;
13726 struct got_worktree *worktree = NULL;
13727 char *cwd = NULL, *repo_path = NULL, *label = NULL;
13728 const char *commit_id_str = NULL;
13729 struct got_object_id *id = NULL, *commit_id = NULL;
13730 struct got_commit_object *commit = NULL;
13731 int ch, obj_type, i, force_path = 0;
13732 struct got_reflist_head refs;
13733 int *pack_fds = NULL;
13735 TAILQ_INIT(&refs);
13737 #ifndef PROFILE
13738 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
13739 NULL) == -1)
13740 err(1, "pledge");
13741 #endif
13743 while ((ch = getopt(argc, argv, "c:Pr:")) != -1) {
13744 switch (ch) {
13745 case 'c':
13746 commit_id_str = optarg;
13747 break;
13748 case 'P':
13749 force_path = 1;
13750 break;
13751 case 'r':
13752 repo_path = realpath(optarg, NULL);
13753 if (repo_path == NULL)
13754 return got_error_from_errno2("realpath",
13755 optarg);
13756 got_path_strip_trailing_slashes(repo_path);
13757 break;
13758 default:
13759 usage_cat();
13760 /* NOTREACHED */
13764 argc -= optind;
13765 argv += optind;
13767 cwd = getcwd(NULL, 0);
13768 if (cwd == NULL) {
13769 error = got_error_from_errno("getcwd");
13770 goto done;
13773 error = got_repo_pack_fds_open(&pack_fds);
13774 if (error != NULL)
13775 goto done;
13777 if (repo_path == NULL) {
13778 error = got_worktree_open(&worktree, cwd);
13779 if (error && error->code != GOT_ERR_NOT_WORKTREE)
13780 goto done;
13781 if (worktree) {
13782 repo_path = strdup(
13783 got_worktree_get_repo_path(worktree));
13784 if (repo_path == NULL) {
13785 error = got_error_from_errno("strdup");
13786 goto done;
13789 /* Release work tree lock. */
13790 got_worktree_close(worktree);
13791 worktree = NULL;
13795 if (repo_path == NULL) {
13796 repo_path = strdup(cwd);
13797 if (repo_path == NULL)
13798 return got_error_from_errno("strdup");
13801 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
13802 free(repo_path);
13803 if (error != NULL)
13804 goto done;
13806 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
13807 if (error)
13808 goto done;
13810 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
13811 if (error)
13812 goto done;
13814 if (commit_id_str == NULL)
13815 commit_id_str = GOT_REF_HEAD;
13816 error = got_repo_match_object_id(&commit_id, NULL,
13817 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
13818 if (error)
13819 goto done;
13821 error = got_object_open_as_commit(&commit, repo, commit_id);
13822 if (error)
13823 goto done;
13825 for (i = 0; i < argc; i++) {
13826 if (force_path) {
13827 error = got_object_id_by_path(&id, repo, commit,
13828 argv[i]);
13829 if (error)
13830 break;
13831 } else {
13832 error = got_repo_match_object_id(&id, &label, argv[i],
13833 GOT_OBJ_TYPE_ANY, NULL /* do not resolve tags */,
13834 repo);
13835 if (error) {
13836 if (error->code != GOT_ERR_BAD_OBJ_ID_STR &&
13837 error->code != GOT_ERR_NOT_REF)
13838 break;
13839 error = got_object_id_by_path(&id, repo,
13840 commit, argv[i]);
13841 if (error)
13842 break;
13846 error = got_object_get_type(&obj_type, repo, id);
13847 if (error)
13848 break;
13850 switch (obj_type) {
13851 case GOT_OBJ_TYPE_BLOB:
13852 error = cat_blob(id, repo, stdout);
13853 break;
13854 case GOT_OBJ_TYPE_TREE:
13855 error = cat_tree(id, repo, stdout);
13856 break;
13857 case GOT_OBJ_TYPE_COMMIT:
13858 error = cat_commit(id, repo, stdout);
13859 break;
13860 case GOT_OBJ_TYPE_TAG:
13861 error = cat_tag(id, repo, stdout);
13862 break;
13863 default:
13864 error = got_error(GOT_ERR_OBJ_TYPE);
13865 break;
13867 if (error)
13868 break;
13869 free(label);
13870 label = NULL;
13871 free(id);
13872 id = NULL;
13874 done:
13875 free(label);
13876 free(id);
13877 free(commit_id);
13878 if (commit)
13879 got_object_commit_close(commit);
13880 if (worktree)
13881 got_worktree_close(worktree);
13882 if (repo) {
13883 const struct got_error *close_err = got_repo_close(repo);
13884 if (error == NULL)
13885 error = close_err;
13887 if (pack_fds) {
13888 const struct got_error *pack_err =
13889 got_repo_pack_fds_close(pack_fds);
13890 if (error == NULL)
13891 error = pack_err;
13894 got_ref_list_free(&refs);
13895 return error;
13898 __dead static void
13899 usage_info(void)
13901 fprintf(stderr, "usage: %s info [path ...]\n",
13902 getprogname());
13903 exit(1);
13906 static const struct got_error *
13907 print_path_info(void *arg, const char *path, mode_t mode, time_t mtime,
13908 struct got_object_id *blob_id, struct got_object_id *staged_blob_id,
13909 struct got_object_id *commit_id)
13911 const struct got_error *err = NULL;
13912 char *id_str = NULL;
13913 char datebuf[128];
13914 struct tm mytm, *tm;
13915 struct got_pathlist_head *paths = arg;
13916 struct got_pathlist_entry *pe;
13919 * Clear error indication from any of the path arguments which
13920 * would cause this file index entry to be displayed.
13922 TAILQ_FOREACH(pe, paths, entry) {
13923 if (got_path_cmp(path, pe->path, strlen(path),
13924 pe->path_len) == 0 ||
13925 got_path_is_child(path, pe->path, pe->path_len))
13926 pe->data = NULL; /* no error */
13929 printf(GOT_COMMIT_SEP_STR);
13930 if (S_ISLNK(mode))
13931 printf("symlink: %s\n", path);
13932 else if (S_ISREG(mode)) {
13933 printf("file: %s\n", path);
13934 printf("mode: %o\n", mode & (S_IRWXU | S_IRWXG | S_IRWXO));
13935 } else if (S_ISDIR(mode))
13936 printf("directory: %s\n", path);
13937 else
13938 printf("something: %s\n", path);
13940 tm = localtime_r(&mtime, &mytm);
13941 if (tm == NULL)
13942 return NULL;
13943 if (strftime(datebuf, sizeof(datebuf), "%c %Z", tm) == 0)
13944 return got_error(GOT_ERR_NO_SPACE);
13945 printf("timestamp: %s\n", datebuf);
13947 if (blob_id) {
13948 err = got_object_id_str(&id_str, blob_id);
13949 if (err)
13950 return err;
13951 printf("based on blob: %s\n", id_str);
13952 free(id_str);
13955 if (staged_blob_id) {
13956 err = got_object_id_str(&id_str, staged_blob_id);
13957 if (err)
13958 return err;
13959 printf("based on staged blob: %s\n", id_str);
13960 free(id_str);
13963 if (commit_id) {
13964 err = got_object_id_str(&id_str, commit_id);
13965 if (err)
13966 return err;
13967 printf("based on commit: %s\n", id_str);
13968 free(id_str);
13971 return NULL;
13974 static const struct got_error *
13975 cmd_info(int argc, char *argv[])
13977 const struct got_error *error = NULL;
13978 struct got_worktree *worktree = NULL;
13979 char *cwd = NULL, *id_str = NULL;
13980 struct got_pathlist_head paths;
13981 char *uuidstr = NULL;
13982 int ch, show_files = 0;
13984 TAILQ_INIT(&paths);
13986 while ((ch = getopt(argc, argv, "")) != -1) {
13987 switch (ch) {
13988 default:
13989 usage_info();
13990 /* NOTREACHED */
13994 argc -= optind;
13995 argv += optind;
13997 #ifndef PROFILE
13998 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
13999 NULL) == -1)
14000 err(1, "pledge");
14001 #endif
14002 cwd = getcwd(NULL, 0);
14003 if (cwd == NULL) {
14004 error = got_error_from_errno("getcwd");
14005 goto done;
14008 error = got_worktree_open(&worktree, cwd);
14009 if (error) {
14010 if (error->code == GOT_ERR_NOT_WORKTREE)
14011 error = wrap_not_worktree_error(error, "info", cwd);
14012 goto done;
14015 #ifndef PROFILE
14016 /* Remove "wpath cpath proc exec sendfd" promises. */
14017 if (pledge("stdio rpath flock unveil", NULL) == -1)
14018 err(1, "pledge");
14019 #endif
14020 error = apply_unveil(NULL, 0, got_worktree_get_root_path(worktree));
14021 if (error)
14022 goto done;
14024 if (argc >= 1) {
14025 error = get_worktree_paths_from_argv(&paths, argc, argv,
14026 worktree);
14027 if (error)
14028 goto done;
14029 show_files = 1;
14032 error = got_object_id_str(&id_str,
14033 got_worktree_get_base_commit_id(worktree));
14034 if (error)
14035 goto done;
14037 error = got_worktree_get_uuid(&uuidstr, worktree);
14038 if (error)
14039 goto done;
14041 printf("work tree: %s\n", got_worktree_get_root_path(worktree));
14042 printf("work tree base commit: %s\n", id_str);
14043 printf("work tree path prefix: %s\n",
14044 got_worktree_get_path_prefix(worktree));
14045 printf("work tree branch reference: %s\n",
14046 got_worktree_get_head_ref_name(worktree));
14047 printf("work tree UUID: %s\n", uuidstr);
14048 printf("repository: %s\n", got_worktree_get_repo_path(worktree));
14050 if (show_files) {
14051 struct got_pathlist_entry *pe;
14052 TAILQ_FOREACH(pe, &paths, entry) {
14053 if (pe->path_len == 0)
14054 continue;
14056 * Assume this path will fail. This will be corrected
14057 * in print_path_info() in case the path does suceeed.
14059 pe->data = (void *)got_error(GOT_ERR_BAD_PATH);
14061 error = got_worktree_path_info(worktree, &paths,
14062 print_path_info, &paths, check_cancelled, NULL);
14063 if (error)
14064 goto done;
14065 TAILQ_FOREACH(pe, &paths, entry) {
14066 if (pe->data != NULL) {
14067 const struct got_error *perr;
14069 perr = pe->data;
14070 error = got_error_fmt(perr->code, "%s",
14071 pe->path);
14072 break;
14076 done:
14077 if (worktree)
14078 got_worktree_close(worktree);
14079 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
14080 free(cwd);
14081 free(id_str);
14082 free(uuidstr);
14083 return error;