Blob


1 /*
2 * Copyright (c) 2017 Martin Pieuchot <mpi@openbsd.org>
3 * Copyright (c) 2018, 2019, 2020 Stefan Sperling <stsp@openbsd.org>
4 * Copyright (c) 2020 Ori Bernstein <ori@openbsd.org>
5 *
6 * Permission to use, copy, modify, and distribute this software for any
7 * purpose with or without fee is hereby granted, provided that the above
8 * copyright notice and this permission notice appear in all copies.
9 *
10 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
11 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
12 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
13 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
14 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
15 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
16 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
17 */
19 #include <sys/queue.h>
20 #include <sys/time.h>
21 #include <sys/types.h>
22 #include <sys/stat.h>
23 #include <sys/wait.h>
25 #include <err.h>
26 #include <errno.h>
27 #include <fcntl.h>
28 #include <limits.h>
29 #include <locale.h>
30 #include <ctype.h>
31 #include <sha1.h>
32 #include <signal.h>
33 #include <stdio.h>
34 #include <stdlib.h>
35 #include <string.h>
36 #include <unistd.h>
37 #include <libgen.h>
38 #include <time.h>
39 #include <paths.h>
40 #include <regex.h>
41 #include <getopt.h>
42 #include <util.h>
44 #include "got_version.h"
45 #include "got_error.h"
46 #include "got_object.h"
47 #include "got_reference.h"
48 #include "got_repository.h"
49 #include "got_path.h"
50 #include "got_cancel.h"
51 #include "got_worktree.h"
52 #include "got_diff.h"
53 #include "got_commit_graph.h"
54 #include "got_fetch.h"
55 #include "got_send.h"
56 #include "got_blame.h"
57 #include "got_privsep.h"
58 #include "got_opentemp.h"
59 #include "got_gotconfig.h"
60 #include "got_dial.h"
61 #include "got_patch.h"
62 #include "got_sigs.h"
63 #include "got_date.h"
65 #ifndef nitems
66 #define nitems(_a) (sizeof((_a)) / sizeof((_a)[0]))
67 #endif
69 static volatile sig_atomic_t sigint_received;
70 static volatile sig_atomic_t sigpipe_received;
72 static void
73 catch_sigint(int signo)
74 {
75 sigint_received = 1;
76 }
78 static void
79 catch_sigpipe(int signo)
80 {
81 sigpipe_received = 1;
82 }
85 struct got_cmd {
86 const char *cmd_name;
87 const struct got_error *(*cmd_main)(int, char *[]);
88 void (*cmd_usage)(void);
89 const char *cmd_alias;
90 };
92 __dead static void usage(int, int);
93 __dead static void usage_import(void);
94 __dead static void usage_clone(void);
95 __dead static void usage_fetch(void);
96 __dead static void usage_checkout(void);
97 __dead static void usage_update(void);
98 __dead static void usage_log(void);
99 __dead static void usage_diff(void);
100 __dead static void usage_blame(void);
101 __dead static void usage_tree(void);
102 __dead static void usage_status(void);
103 __dead static void usage_ref(void);
104 __dead static void usage_branch(void);
105 __dead static void usage_tag(void);
106 __dead static void usage_add(void);
107 __dead static void usage_remove(void);
108 __dead static void usage_patch(void);
109 __dead static void usage_revert(void);
110 __dead static void usage_commit(void);
111 __dead static void usage_send(void);
112 __dead static void usage_cherrypick(void);
113 __dead static void usage_backout(void);
114 __dead static void usage_rebase(void);
115 __dead static void usage_histedit(void);
116 __dead static void usage_integrate(void);
117 __dead static void usage_merge(void);
118 __dead static void usage_stage(void);
119 __dead static void usage_unstage(void);
120 __dead static void usage_cat(void);
121 __dead static void usage_info(void);
123 static const struct got_error* cmd_import(int, char *[]);
124 static const struct got_error* cmd_clone(int, char *[]);
125 static const struct got_error* cmd_fetch(int, char *[]);
126 static const struct got_error* cmd_checkout(int, char *[]);
127 static const struct got_error* cmd_update(int, char *[]);
128 static const struct got_error* cmd_log(int, char *[]);
129 static const struct got_error* cmd_diff(int, char *[]);
130 static const struct got_error* cmd_blame(int, char *[]);
131 static const struct got_error* cmd_tree(int, char *[]);
132 static const struct got_error* cmd_status(int, char *[]);
133 static const struct got_error* cmd_ref(int, char *[]);
134 static const struct got_error* cmd_branch(int, char *[]);
135 static const struct got_error* cmd_tag(int, char *[]);
136 static const struct got_error* cmd_add(int, char *[]);
137 static const struct got_error* cmd_remove(int, char *[]);
138 static const struct got_error* cmd_patch(int, char *[]);
139 static const struct got_error* cmd_revert(int, char *[]);
140 static const struct got_error* cmd_commit(int, char *[]);
141 static const struct got_error* cmd_send(int, char *[]);
142 static const struct got_error* cmd_cherrypick(int, char *[]);
143 static const struct got_error* cmd_backout(int, char *[]);
144 static const struct got_error* cmd_rebase(int, char *[]);
145 static const struct got_error* cmd_histedit(int, char *[]);
146 static const struct got_error* cmd_integrate(int, char *[]);
147 static const struct got_error* cmd_merge(int, char *[]);
148 static const struct got_error* cmd_stage(int, char *[]);
149 static const struct got_error* cmd_unstage(int, char *[]);
150 static const struct got_error* cmd_cat(int, char *[]);
151 static const struct got_error* cmd_info(int, char *[]);
153 static const struct got_cmd got_commands[] = {
154 { "import", cmd_import, usage_import, "im" },
155 { "clone", cmd_clone, usage_clone, "cl" },
156 { "fetch", cmd_fetch, usage_fetch, "fe" },
157 { "checkout", cmd_checkout, usage_checkout, "co" },
158 { "update", cmd_update, usage_update, "up" },
159 { "log", cmd_log, usage_log, "" },
160 { "diff", cmd_diff, usage_diff, "di" },
161 { "blame", cmd_blame, usage_blame, "bl" },
162 { "tree", cmd_tree, usage_tree, "tr" },
163 { "status", cmd_status, usage_status, "st" },
164 { "ref", cmd_ref, usage_ref, "" },
165 { "branch", cmd_branch, usage_branch, "br" },
166 { "tag", cmd_tag, usage_tag, "" },
167 { "add", cmd_add, usage_add, "" },
168 { "remove", cmd_remove, usage_remove, "rm" },
169 { "patch", cmd_patch, usage_patch, "pa" },
170 { "revert", cmd_revert, usage_revert, "rv" },
171 { "commit", cmd_commit, usage_commit, "ci" },
172 { "send", cmd_send, usage_send, "se" },
173 { "cherrypick", cmd_cherrypick, usage_cherrypick, "cy" },
174 { "backout", cmd_backout, usage_backout, "bo" },
175 { "rebase", cmd_rebase, usage_rebase, "rb" },
176 { "histedit", cmd_histedit, usage_histedit, "he" },
177 { "integrate", cmd_integrate, usage_integrate,"ig" },
178 { "merge", cmd_merge, usage_merge, "mg" },
179 { "stage", cmd_stage, usage_stage, "sg" },
180 { "unstage", cmd_unstage, usage_unstage, "ug" },
181 { "cat", cmd_cat, usage_cat, "" },
182 { "info", cmd_info, usage_info, "" },
183 };
185 static void
186 list_commands(FILE *fp)
188 size_t i;
190 fprintf(fp, "commands:");
191 for (i = 0; i < nitems(got_commands); i++) {
192 const struct got_cmd *cmd = &got_commands[i];
193 fprintf(fp, " %s", cmd->cmd_name);
195 fputc('\n', fp);
198 __dead static void
199 option_conflict(char a, char b)
201 errx(1, "-%c and -%c options are mutually exclusive", a, b);
204 int
205 main(int argc, char *argv[])
207 const struct got_cmd *cmd;
208 size_t i;
209 int ch;
210 int hflag = 0, Vflag = 0;
211 static const struct option longopts[] = {
212 { "version", no_argument, NULL, 'V' },
213 { NULL, 0, NULL, 0 }
214 };
216 setlocale(LC_CTYPE, "");
218 while ((ch = getopt_long(argc, argv, "+hV", longopts, NULL)) != -1) {
219 switch (ch) {
220 case 'h':
221 hflag = 1;
222 break;
223 case 'V':
224 Vflag = 1;
225 break;
226 default:
227 usage(hflag, 1);
228 /* NOTREACHED */
232 argc -= optind;
233 argv += optind;
234 optind = 1;
235 optreset = 1;
237 if (Vflag) {
238 got_version_print_str();
239 return 0;
242 if (argc <= 0)
243 usage(hflag, hflag ? 0 : 1);
245 signal(SIGINT, catch_sigint);
246 signal(SIGPIPE, catch_sigpipe);
248 for (i = 0; i < nitems(got_commands); i++) {
249 const struct got_error *error;
251 cmd = &got_commands[i];
253 if (strcmp(cmd->cmd_name, argv[0]) != 0 &&
254 strcmp(cmd->cmd_alias, argv[0]) != 0)
255 continue;
257 if (hflag)
258 cmd->cmd_usage();
260 error = cmd->cmd_main(argc, argv);
261 if (error && error->code != GOT_ERR_CANCELLED &&
262 error->code != GOT_ERR_PRIVSEP_EXIT &&
263 !(sigpipe_received &&
264 error->code == GOT_ERR_ERRNO && errno == EPIPE) &&
265 !(sigint_received &&
266 error->code == GOT_ERR_ERRNO && errno == EINTR)) {
267 fprintf(stderr, "%s: %s\n", getprogname(), error->msg);
268 return 1;
271 return 0;
274 fprintf(stderr, "%s: unknown command '%s'\n", getprogname(), argv[0]);
275 list_commands(stderr);
276 return 1;
279 __dead static void
280 usage(int hflag, int status)
282 FILE *fp = (status == 0) ? stdout : stderr;
284 fprintf(fp, "usage: %s [-hV] command [arg ...]\n",
285 getprogname());
286 if (hflag)
287 list_commands(fp);
288 exit(status);
291 static const struct got_error *
292 get_editor(char **abspath)
294 const struct got_error *err = NULL;
295 const char *editor;
297 *abspath = NULL;
299 editor = getenv("VISUAL");
300 if (editor == NULL)
301 editor = getenv("EDITOR");
303 if (editor) {
304 err = got_path_find_prog(abspath, editor);
305 if (err)
306 return err;
309 if (*abspath == NULL) {
310 *abspath = strdup("/bin/ed");
311 if (*abspath == NULL)
312 return got_error_from_errno("strdup");
315 return NULL;
318 static const struct got_error *
319 apply_unveil(const char *repo_path, int repo_read_only,
320 const char *worktree_path)
322 const struct got_error *err;
324 #ifdef PROFILE
325 if (unveil("gmon.out", "rwc") != 0)
326 return got_error_from_errno2("unveil", "gmon.out");
327 #endif
328 if (repo_path && unveil(repo_path, repo_read_only ? "r" : "rwc") != 0)
329 return got_error_from_errno2("unveil", repo_path);
331 if (worktree_path && unveil(worktree_path, "rwc") != 0)
332 return got_error_from_errno2("unveil", worktree_path);
334 if (unveil(GOT_TMPDIR_STR, "rwc") != 0)
335 return got_error_from_errno2("unveil", GOT_TMPDIR_STR);
337 err = got_privsep_unveil_exec_helpers();
338 if (err != NULL)
339 return err;
341 if (unveil(NULL, NULL) != 0)
342 return got_error_from_errno("unveil");
344 return NULL;
347 __dead static void
348 usage_import(void)
350 fprintf(stderr, "usage: %s import [-b branch] [-I pattern] [-m message] "
351 "[-r repository-path] directory\n", getprogname());
352 exit(1);
355 static int
356 spawn_editor(const char *editor, const char *file)
358 pid_t pid;
359 sig_t sighup, sigint, sigquit;
360 int st = -1;
362 sighup = signal(SIGHUP, SIG_IGN);
363 sigint = signal(SIGINT, SIG_IGN);
364 sigquit = signal(SIGQUIT, SIG_IGN);
366 switch (pid = fork()) {
367 case -1:
368 goto doneediting;
369 case 0:
370 execl(editor, editor, file, (char *)NULL);
371 _exit(127);
374 while (waitpid(pid, &st, 0) == -1)
375 if (errno != EINTR)
376 break;
378 doneediting:
379 (void)signal(SIGHUP, sighup);
380 (void)signal(SIGINT, sigint);
381 (void)signal(SIGQUIT, sigquit);
383 if (!WIFEXITED(st)) {
384 errno = EINTR;
385 return -1;
388 return WEXITSTATUS(st);
391 static const struct got_error *
392 edit_logmsg(char **logmsg, const char *editor, const char *logmsg_path,
393 const char *initial_content, size_t initial_content_len,
394 int require_modification)
396 const struct got_error *err = NULL;
397 char *line = NULL;
398 size_t linesize = 0;
399 struct stat st, st2;
400 FILE *fp = NULL;
401 size_t len, logmsg_len;
402 char *initial_content_stripped = NULL, *buf = NULL, *s;
404 *logmsg = NULL;
406 if (stat(logmsg_path, &st) == -1)
407 return got_error_from_errno2("stat", logmsg_path);
409 if (spawn_editor(editor, logmsg_path) == -1)
410 return got_error_from_errno("failed spawning editor");
412 if (stat(logmsg_path, &st2) == -1)
413 return got_error_from_errno("stat");
415 if (require_modification &&
416 st.st_mtime == st2.st_mtime && st.st_size == st2.st_size)
417 return got_error_msg(GOT_ERR_COMMIT_MSG_EMPTY,
418 "no changes made to commit message, aborting");
420 /*
421 * Set up a stripped version of the initial content without comments
422 * and blank lines. We need this in order to check if the message
423 * has in fact been edited.
424 */
425 initial_content_stripped = malloc(initial_content_len + 1);
426 if (initial_content_stripped == NULL)
427 return got_error_from_errno("malloc");
428 initial_content_stripped[0] = '\0';
430 buf = strdup(initial_content);
431 if (buf == NULL) {
432 err = got_error_from_errno("strdup");
433 goto done;
435 s = buf;
436 len = 0;
437 while ((line = strsep(&s, "\n")) != NULL) {
438 if ((line[0] == '#' || (len == 0 && line[0] == '\n')))
439 continue; /* remove comments and leading empty lines */
440 len = strlcat(initial_content_stripped, line,
441 initial_content_len + 1);
442 if (len >= initial_content_len + 1) {
443 err = got_error(GOT_ERR_NO_SPACE);
444 goto done;
447 while (len > 0 && initial_content_stripped[len - 1] == '\n') {
448 initial_content_stripped[len - 1] = '\0';
449 len--;
452 logmsg_len = st2.st_size;
453 *logmsg = malloc(logmsg_len + 1);
454 if (*logmsg == NULL)
455 return got_error_from_errno("malloc");
456 (*logmsg)[0] = '\0';
458 fp = fopen(logmsg_path, "re");
459 if (fp == NULL) {
460 err = got_error_from_errno("fopen");
461 goto done;
464 len = 0;
465 while (getline(&line, &linesize, fp) != -1) {
466 if ((line[0] == '#' || (len == 0 && line[0] == '\n')))
467 continue; /* remove comments and leading empty lines */
468 len = strlcat(*logmsg, line, logmsg_len + 1);
469 if (len >= logmsg_len + 1) {
470 err = got_error(GOT_ERR_NO_SPACE);
471 goto done;
474 free(line);
475 if (ferror(fp)) {
476 err = got_ferror(fp, GOT_ERR_IO);
477 goto done;
479 while (len > 0 && (*logmsg)[len - 1] == '\n') {
480 (*logmsg)[len - 1] = '\0';
481 len--;
484 if (len == 0) {
485 err = got_error_msg(GOT_ERR_COMMIT_MSG_EMPTY,
486 "commit message cannot be empty, aborting");
487 goto done;
489 if (require_modification &&
490 strcmp(*logmsg, initial_content_stripped) == 0)
491 err = got_error_msg(GOT_ERR_COMMIT_MSG_EMPTY,
492 "no changes made to commit message, aborting");
493 done:
494 free(initial_content_stripped);
495 free(buf);
496 if (fp && fclose(fp) == EOF && err == NULL)
497 err = got_error_from_errno("fclose");
498 if (err) {
499 free(*logmsg);
500 *logmsg = NULL;
502 return err;
505 static const struct got_error *
506 collect_import_msg(char **logmsg, char **logmsg_path, const char *editor,
507 const char *path_dir, const char *branch_name)
509 char *initial_content = NULL;
510 const struct got_error *err = NULL;
511 int initial_content_len;
512 int fd = -1;
514 initial_content_len = asprintf(&initial_content,
515 "\n# %s to be imported to branch %s\n", path_dir,
516 branch_name);
517 if (initial_content_len == -1)
518 return got_error_from_errno("asprintf");
520 err = got_opentemp_named_fd(logmsg_path, &fd,
521 GOT_TMPDIR_STR "/got-importmsg", "");
522 if (err)
523 goto done;
525 if (write(fd, initial_content, initial_content_len) == -1) {
526 err = got_error_from_errno2("write", *logmsg_path);
527 goto done;
530 err = edit_logmsg(logmsg, editor, *logmsg_path, initial_content,
531 initial_content_len, 1);
532 done:
533 if (fd != -1 && close(fd) == -1 && err == NULL)
534 err = got_error_from_errno2("close", *logmsg_path);
535 free(initial_content);
536 if (err) {
537 free(*logmsg_path);
538 *logmsg_path = NULL;
540 return err;
543 static const struct got_error *
544 import_progress(void *arg, const char *path)
546 printf("A %s\n", path);
547 return NULL;
550 static const struct got_error *
551 valid_author(const char *author)
553 const char *email = author;
555 /*
556 * Git' expects the author (or committer) to be in the form
557 * "name <email>", which are mostly free form (see the
558 * "committer" description in git-fast-import(1)). We're only
559 * doing this to avoid git's object parser breaking on commits
560 * we create.
561 */
563 while (*author && *author != '\n' && *author != '<' && *author != '>')
564 author++;
565 if (author != email && *author == '<' && *(author - 1) != ' ')
566 return got_error_fmt(GOT_ERR_COMMIT_BAD_AUTHOR, "%s: space "
567 "between author name and email required", email);
568 if (*author++ != '<')
569 return got_error_fmt(GOT_ERR_COMMIT_NO_EMAIL, "%s", email);
570 while (*author && *author != '\n' && *author != '<' && *author != '>')
571 author++;
572 if (strcmp(author, ">") != 0)
573 return got_error_fmt(GOT_ERR_COMMIT_NO_EMAIL, "%s", email);
574 return NULL;
577 static const struct got_error *
578 get_author(char **author, struct got_repository *repo,
579 struct got_worktree *worktree)
581 const struct got_error *err = NULL;
582 const char *got_author = NULL, *name, *email;
583 const struct got_gotconfig *worktree_conf = NULL, *repo_conf = NULL;
585 *author = NULL;
587 if (worktree)
588 worktree_conf = got_worktree_get_gotconfig(worktree);
589 repo_conf = got_repo_get_gotconfig(repo);
591 /*
592 * Priority of potential author information sources, from most
593 * significant to least significant:
594 * 1) work tree's .got/got.conf file
595 * 2) repository's got.conf file
596 * 3) repository's git config file
597 * 4) environment variables
598 * 5) global git config files (in user's home directory or /etc)
599 */
601 if (worktree_conf)
602 got_author = got_gotconfig_get_author(worktree_conf);
603 if (got_author == NULL)
604 got_author = got_gotconfig_get_author(repo_conf);
605 if (got_author == NULL) {
606 name = got_repo_get_gitconfig_author_name(repo);
607 email = got_repo_get_gitconfig_author_email(repo);
608 if (name && email) {
609 if (asprintf(author, "%s <%s>", name, email) == -1)
610 return got_error_from_errno("asprintf");
611 return NULL;
614 got_author = getenv("GOT_AUTHOR");
615 if (got_author == NULL) {
616 name = got_repo_get_global_gitconfig_author_name(repo);
617 email = got_repo_get_global_gitconfig_author_email(
618 repo);
619 if (name && email) {
620 if (asprintf(author, "%s <%s>", name, email)
621 == -1)
622 return got_error_from_errno("asprintf");
623 return NULL;
625 /* TODO: Look up user in password database? */
626 return got_error(GOT_ERR_COMMIT_NO_AUTHOR);
630 *author = strdup(got_author);
631 if (*author == NULL)
632 return got_error_from_errno("strdup");
634 err = valid_author(*author);
635 if (err) {
636 free(*author);
637 *author = NULL;
639 return err;
642 static const struct got_error *
643 get_allowed_signers(char **allowed_signers, struct got_repository *repo,
644 struct got_worktree *worktree)
646 const char *got_allowed_signers = NULL;
647 const struct got_gotconfig *worktree_conf = NULL, *repo_conf = NULL;
649 *allowed_signers = NULL;
651 if (worktree)
652 worktree_conf = got_worktree_get_gotconfig(worktree);
653 repo_conf = got_repo_get_gotconfig(repo);
655 /*
656 * Priority of potential author information sources, from most
657 * significant to least significant:
658 * 1) work tree's .got/got.conf file
659 * 2) repository's got.conf file
660 */
662 if (worktree_conf)
663 got_allowed_signers = got_gotconfig_get_allowed_signers_file(
664 worktree_conf);
665 if (got_allowed_signers == NULL)
666 got_allowed_signers = got_gotconfig_get_allowed_signers_file(
667 repo_conf);
669 if (got_allowed_signers) {
670 *allowed_signers = strdup(got_allowed_signers);
671 if (*allowed_signers == NULL)
672 return got_error_from_errno("strdup");
674 return NULL;
677 static const struct got_error *
678 get_revoked_signers(char **revoked_signers, struct got_repository *repo,
679 struct got_worktree *worktree)
681 const char *got_revoked_signers = NULL;
682 const struct got_gotconfig *worktree_conf = NULL, *repo_conf = NULL;
684 *revoked_signers = NULL;
686 if (worktree)
687 worktree_conf = got_worktree_get_gotconfig(worktree);
688 repo_conf = got_repo_get_gotconfig(repo);
690 /*
691 * Priority of potential author information sources, from most
692 * significant to least significant:
693 * 1) work tree's .got/got.conf file
694 * 2) repository's got.conf file
695 */
697 if (worktree_conf)
698 got_revoked_signers = got_gotconfig_get_revoked_signers_file(
699 worktree_conf);
700 if (got_revoked_signers == NULL)
701 got_revoked_signers = got_gotconfig_get_revoked_signers_file(
702 repo_conf);
704 if (got_revoked_signers) {
705 *revoked_signers = strdup(got_revoked_signers);
706 if (*revoked_signers == NULL)
707 return got_error_from_errno("strdup");
709 return NULL;
712 static const char *
713 get_signer_id(struct got_repository *repo, struct got_worktree *worktree)
715 const char *got_signer_id = NULL;
716 const struct got_gotconfig *worktree_conf = NULL, *repo_conf = NULL;
718 if (worktree)
719 worktree_conf = got_worktree_get_gotconfig(worktree);
720 repo_conf = got_repo_get_gotconfig(repo);
722 /*
723 * Priority of potential author information sources, from most
724 * significant to least significant:
725 * 1) work tree's .got/got.conf file
726 * 2) repository's got.conf file
727 */
729 if (worktree_conf)
730 got_signer_id = got_gotconfig_get_signer_id(worktree_conf);
731 if (got_signer_id == NULL)
732 got_signer_id = got_gotconfig_get_signer_id(repo_conf);
734 return got_signer_id;
737 static const struct got_error *
738 get_gitconfig_path(char **gitconfig_path)
740 const char *homedir = getenv("HOME");
742 *gitconfig_path = NULL;
743 if (homedir) {
744 if (asprintf(gitconfig_path, "%s/.gitconfig", homedir) == -1)
745 return got_error_from_errno("asprintf");
748 return NULL;
751 static const struct got_error *
752 cmd_import(int argc, char *argv[])
754 const struct got_error *error = NULL;
755 char *path_dir = NULL, *repo_path = NULL, *logmsg = NULL;
756 char *gitconfig_path = NULL, *editor = NULL, *author = NULL;
757 const char *branch_name = NULL;
758 char *id_str = NULL, *logmsg_path = NULL;
759 char refname[PATH_MAX] = "refs/heads/";
760 struct got_repository *repo = NULL;
761 struct got_reference *branch_ref = NULL, *head_ref = NULL;
762 struct got_object_id *new_commit_id = NULL;
763 int ch, n = 0;
764 struct got_pathlist_head ignores;
765 struct got_pathlist_entry *pe;
766 int preserve_logmsg = 0;
767 int *pack_fds = NULL;
769 TAILQ_INIT(&ignores);
771 while ((ch = getopt(argc, argv, "b:I:m:r:")) != -1) {
772 switch (ch) {
773 case 'b':
774 branch_name = optarg;
775 break;
776 case 'I':
777 if (optarg[0] == '\0')
778 break;
779 error = got_pathlist_insert(&pe, &ignores, optarg,
780 NULL);
781 if (error)
782 goto done;
783 break;
784 case 'm':
785 logmsg = strdup(optarg);
786 if (logmsg == NULL) {
787 error = got_error_from_errno("strdup");
788 goto done;
790 break;
791 case 'r':
792 repo_path = realpath(optarg, NULL);
793 if (repo_path == NULL) {
794 error = got_error_from_errno2("realpath",
795 optarg);
796 goto done;
798 break;
799 default:
800 usage_import();
801 /* NOTREACHED */
805 argc -= optind;
806 argv += optind;
808 #ifndef PROFILE
809 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
810 "unveil",
811 NULL) == -1)
812 err(1, "pledge");
813 #endif
814 if (argc != 1)
815 usage_import();
817 if (repo_path == NULL) {
818 repo_path = getcwd(NULL, 0);
819 if (repo_path == NULL)
820 return got_error_from_errno("getcwd");
822 got_path_strip_trailing_slashes(repo_path);
823 error = get_gitconfig_path(&gitconfig_path);
824 if (error)
825 goto done;
826 error = got_repo_pack_fds_open(&pack_fds);
827 if (error != NULL)
828 goto done;
829 error = got_repo_open(&repo, repo_path, gitconfig_path, pack_fds);
830 if (error)
831 goto done;
833 error = get_author(&author, repo, NULL);
834 if (error)
835 return error;
837 /*
838 * Don't let the user create a branch name with a leading '-'.
839 * While technically a valid reference name, this case is usually
840 * an unintended typo.
841 */
842 if (branch_name && branch_name[0] == '-')
843 return got_error_path(branch_name, GOT_ERR_REF_NAME_MINUS);
845 error = got_ref_open(&head_ref, repo, GOT_REF_HEAD, 0);
846 if (error && error->code != GOT_ERR_NOT_REF)
847 goto done;
849 if (branch_name)
850 n = strlcat(refname, branch_name, sizeof(refname));
851 else if (head_ref && got_ref_is_symbolic(head_ref))
852 n = strlcpy(refname, got_ref_get_symref_target(head_ref),
853 sizeof(refname));
854 else
855 n = strlcat(refname, "main", sizeof(refname));
856 if (n >= sizeof(refname)) {
857 error = got_error(GOT_ERR_NO_SPACE);
858 goto done;
861 error = got_ref_open(&branch_ref, repo, refname, 0);
862 if (error) {
863 if (error->code != GOT_ERR_NOT_REF)
864 goto done;
865 } else {
866 error = got_error_msg(GOT_ERR_BRANCH_EXISTS,
867 "import target branch already exists");
868 goto done;
871 path_dir = realpath(argv[0], NULL);
872 if (path_dir == NULL) {
873 error = got_error_from_errno2("realpath", argv[0]);
874 goto done;
876 got_path_strip_trailing_slashes(path_dir);
878 /*
879 * unveil(2) traverses exec(2); if an editor is used we have
880 * to apply unveil after the log message has been written.
881 */
882 if (logmsg == NULL || strlen(logmsg) == 0) {
883 error = get_editor(&editor);
884 if (error)
885 goto done;
886 free(logmsg);
887 error = collect_import_msg(&logmsg, &logmsg_path, editor,
888 path_dir, refname);
889 if (error) {
890 if (error->code != GOT_ERR_COMMIT_MSG_EMPTY &&
891 logmsg_path != NULL)
892 preserve_logmsg = 1;
893 goto done;
897 if (unveil(path_dir, "r") != 0) {
898 error = got_error_from_errno2("unveil", path_dir);
899 if (logmsg_path)
900 preserve_logmsg = 1;
901 goto done;
904 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
905 if (error) {
906 if (logmsg_path)
907 preserve_logmsg = 1;
908 goto done;
911 error = got_repo_import(&new_commit_id, path_dir, logmsg,
912 author, &ignores, repo, import_progress, NULL);
913 if (error) {
914 if (logmsg_path)
915 preserve_logmsg = 1;
916 goto done;
919 error = got_ref_alloc(&branch_ref, refname, new_commit_id);
920 if (error) {
921 if (logmsg_path)
922 preserve_logmsg = 1;
923 goto done;
926 error = got_ref_write(branch_ref, repo);
927 if (error) {
928 if (logmsg_path)
929 preserve_logmsg = 1;
930 goto done;
933 error = got_object_id_str(&id_str, new_commit_id);
934 if (error) {
935 if (logmsg_path)
936 preserve_logmsg = 1;
937 goto done;
940 error = got_ref_open(&head_ref, repo, GOT_REF_HEAD, 0);
941 if (error) {
942 if (error->code != GOT_ERR_NOT_REF) {
943 if (logmsg_path)
944 preserve_logmsg = 1;
945 goto done;
948 error = got_ref_alloc_symref(&head_ref, GOT_REF_HEAD,
949 branch_ref);
950 if (error) {
951 if (logmsg_path)
952 preserve_logmsg = 1;
953 goto done;
956 error = got_ref_write(head_ref, repo);
957 if (error) {
958 if (logmsg_path)
959 preserve_logmsg = 1;
960 goto done;
964 printf("Created branch %s with commit %s\n",
965 got_ref_get_name(branch_ref), id_str);
966 done:
967 if (pack_fds) {
968 const struct got_error *pack_err =
969 got_repo_pack_fds_close(pack_fds);
970 if (error == NULL)
971 error = pack_err;
973 if (preserve_logmsg) {
974 fprintf(stderr, "%s: log message preserved in %s\n",
975 getprogname(), logmsg_path);
976 } else if (logmsg_path && unlink(logmsg_path) == -1 && error == NULL)
977 error = got_error_from_errno2("unlink", logmsg_path);
978 free(logmsg);
979 free(logmsg_path);
980 free(repo_path);
981 free(editor);
982 free(new_commit_id);
983 free(id_str);
984 free(author);
985 free(gitconfig_path);
986 if (branch_ref)
987 got_ref_close(branch_ref);
988 if (head_ref)
989 got_ref_close(head_ref);
990 return error;
993 __dead static void
994 usage_clone(void)
996 fprintf(stderr, "usage: %s clone [-almqv] [-b branch] [-R reference] "
997 "repository-URL [directory]\n", getprogname());
998 exit(1);
1001 struct got_fetch_progress_arg {
1002 char last_scaled_size[FMT_SCALED_STRSIZE];
1003 int last_p_indexed;
1004 int last_p_resolved;
1005 int verbosity;
1007 struct got_repository *repo;
1009 int create_configs;
1010 int configs_created;
1011 struct {
1012 struct got_pathlist_head *symrefs;
1013 struct got_pathlist_head *wanted_branches;
1014 struct got_pathlist_head *wanted_refs;
1015 const char *proto;
1016 const char *host;
1017 const char *port;
1018 const char *remote_repo_path;
1019 const char *git_url;
1020 int fetch_all_branches;
1021 int mirror_references;
1022 } config_info;
1025 /* XXX forward declaration */
1026 static const struct got_error *
1027 create_config_files(const char *proto, const char *host, const char *port,
1028 const char *remote_repo_path, const char *git_url, int fetch_all_branches,
1029 int mirror_references, struct got_pathlist_head *symrefs,
1030 struct got_pathlist_head *wanted_branches,
1031 struct got_pathlist_head *wanted_refs, struct got_repository *repo);
1033 static const struct got_error *
1034 fetch_progress(void *arg, const char *message, off_t packfile_size,
1035 int nobj_total, int nobj_indexed, int nobj_loose, int nobj_resolved)
1037 const struct got_error *err = NULL;
1038 struct got_fetch_progress_arg *a = arg;
1039 char scaled_size[FMT_SCALED_STRSIZE];
1040 int p_indexed, p_resolved;
1041 int print_size = 0, print_indexed = 0, print_resolved = 0;
1044 * In order to allow a failed clone to be resumed with 'got fetch'
1045 * we try to create configuration files as soon as possible.
1046 * Once the server has sent information about its default branch
1047 * we have all required information.
1049 if (a->create_configs && !a->configs_created &&
1050 !TAILQ_EMPTY(a->config_info.symrefs)) {
1051 err = create_config_files(a->config_info.proto,
1052 a->config_info.host, a->config_info.port,
1053 a->config_info.remote_repo_path,
1054 a->config_info.git_url,
1055 a->config_info.fetch_all_branches,
1056 a->config_info.mirror_references,
1057 a->config_info.symrefs,
1058 a->config_info.wanted_branches,
1059 a->config_info.wanted_refs, a->repo);
1060 if (err)
1061 return err;
1062 a->configs_created = 1;
1065 if (a->verbosity < 0)
1066 return NULL;
1068 if (message && message[0] != '\0') {
1069 printf("\rserver: %s", message);
1070 fflush(stdout);
1071 return NULL;
1074 if (packfile_size > 0 || nobj_indexed > 0) {
1075 if (fmt_scaled(packfile_size, scaled_size) == 0 &&
1076 (a->last_scaled_size[0] == '\0' ||
1077 strcmp(scaled_size, a->last_scaled_size)) != 0) {
1078 print_size = 1;
1079 if (strlcpy(a->last_scaled_size, scaled_size,
1080 FMT_SCALED_STRSIZE) >= FMT_SCALED_STRSIZE)
1081 return got_error(GOT_ERR_NO_SPACE);
1083 if (nobj_indexed > 0) {
1084 p_indexed = (nobj_indexed * 100) / nobj_total;
1085 if (p_indexed != a->last_p_indexed) {
1086 a->last_p_indexed = p_indexed;
1087 print_indexed = 1;
1088 print_size = 1;
1091 if (nobj_resolved > 0) {
1092 p_resolved = (nobj_resolved * 100) /
1093 (nobj_total - nobj_loose);
1094 if (p_resolved != a->last_p_resolved) {
1095 a->last_p_resolved = p_resolved;
1096 print_resolved = 1;
1097 print_indexed = 1;
1098 print_size = 1;
1103 if (print_size || print_indexed || print_resolved)
1104 printf("\r");
1105 if (print_size)
1106 printf("%*s fetched", FMT_SCALED_STRSIZE - 2, scaled_size);
1107 if (print_indexed)
1108 printf("; indexing %d%%", p_indexed);
1109 if (print_resolved)
1110 printf("; resolving deltas %d%%", p_resolved);
1111 if (print_size || print_indexed || print_resolved)
1112 fflush(stdout);
1114 return NULL;
1117 static const struct got_error *
1118 create_symref(const char *refname, struct got_reference *target_ref,
1119 int verbosity, struct got_repository *repo)
1121 const struct got_error *err;
1122 struct got_reference *head_symref;
1124 err = got_ref_alloc_symref(&head_symref, refname, target_ref);
1125 if (err)
1126 return err;
1128 err = got_ref_write(head_symref, repo);
1129 if (err == NULL && verbosity > 0) {
1130 printf("Created reference %s: %s\n", GOT_REF_HEAD,
1131 got_ref_get_name(target_ref));
1133 got_ref_close(head_symref);
1134 return err;
1137 static const struct got_error *
1138 list_remote_refs(struct got_pathlist_head *symrefs,
1139 struct got_pathlist_head *refs)
1141 const struct got_error *err;
1142 struct got_pathlist_entry *pe;
1144 TAILQ_FOREACH(pe, symrefs, entry) {
1145 const char *refname = pe->path;
1146 const char *targetref = pe->data;
1148 printf("%s: %s\n", refname, targetref);
1151 TAILQ_FOREACH(pe, refs, entry) {
1152 const char *refname = pe->path;
1153 struct got_object_id *id = pe->data;
1154 char *id_str;
1156 err = got_object_id_str(&id_str, id);
1157 if (err)
1158 return err;
1159 printf("%s: %s\n", refname, id_str);
1160 free(id_str);
1163 return NULL;
1166 static const struct got_error *
1167 create_ref(const char *refname, struct got_object_id *id,
1168 int verbosity, struct got_repository *repo)
1170 const struct got_error *err = NULL;
1171 struct got_reference *ref;
1172 char *id_str;
1174 err = got_object_id_str(&id_str, id);
1175 if (err)
1176 return err;
1178 err = got_ref_alloc(&ref, refname, id);
1179 if (err)
1180 goto done;
1182 err = got_ref_write(ref, repo);
1183 got_ref_close(ref);
1185 if (err == NULL && verbosity >= 0)
1186 printf("Created reference %s: %s\n", refname, id_str);
1187 done:
1188 free(id_str);
1189 return err;
1192 static int
1193 match_wanted_ref(const char *refname, const char *wanted_ref)
1195 if (strncmp(refname, "refs/", 5) != 0)
1196 return 0;
1197 refname += 5;
1200 * Prevent fetching of references that won't make any
1201 * sense outside of the remote repository's context.
1203 if (strncmp(refname, "got/", 4) == 0)
1204 return 0;
1205 if (strncmp(refname, "remotes/", 8) == 0)
1206 return 0;
1208 if (strncmp(wanted_ref, "refs/", 5) == 0)
1209 wanted_ref += 5;
1211 /* Allow prefix match. */
1212 if (got_path_is_child(refname, wanted_ref, strlen(wanted_ref)))
1213 return 1;
1215 /* Allow exact match. */
1216 return (strcmp(refname, wanted_ref) == 0);
1219 static int
1220 is_wanted_ref(struct got_pathlist_head *wanted_refs, const char *refname)
1222 struct got_pathlist_entry *pe;
1224 TAILQ_FOREACH(pe, wanted_refs, entry) {
1225 if (match_wanted_ref(refname, pe->path))
1226 return 1;
1229 return 0;
1232 static const struct got_error *
1233 create_wanted_ref(const char *refname, struct got_object_id *id,
1234 const char *remote_repo_name, int verbosity, struct got_repository *repo)
1236 const struct got_error *err;
1237 char *remote_refname;
1239 if (strncmp("refs/", refname, 5) == 0)
1240 refname += 5;
1242 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
1243 remote_repo_name, refname) == -1)
1244 return got_error_from_errno("asprintf");
1246 err = create_ref(remote_refname, id, verbosity, repo);
1247 free(remote_refname);
1248 return err;
1251 static const struct got_error *
1252 create_gotconfig(const char *proto, const char *host, const char *port,
1253 const char *remote_repo_path, const char *default_branch,
1254 int fetch_all_branches, struct got_pathlist_head *wanted_branches,
1255 struct got_pathlist_head *wanted_refs, int mirror_references,
1256 struct got_repository *repo)
1258 const struct got_error *err = NULL;
1259 char *gotconfig_path = NULL;
1260 char *gotconfig = NULL;
1261 FILE *gotconfig_file = NULL;
1262 const char *branchname = NULL;
1263 char *branches = NULL, *refs = NULL;
1264 ssize_t n;
1266 if (!fetch_all_branches && !TAILQ_EMPTY(wanted_branches)) {
1267 struct got_pathlist_entry *pe;
1268 TAILQ_FOREACH(pe, wanted_branches, entry) {
1269 char *s;
1270 branchname = pe->path;
1271 if (strncmp(branchname, "refs/heads/", 11) == 0)
1272 branchname += 11;
1273 if (asprintf(&s, "%s\"%s\" ",
1274 branches ? branches : "", branchname) == -1) {
1275 err = got_error_from_errno("asprintf");
1276 goto done;
1278 free(branches);
1279 branches = s;
1281 } else if (!fetch_all_branches && default_branch) {
1282 branchname = default_branch;
1283 if (strncmp(branchname, "refs/heads/", 11) == 0)
1284 branchname += 11;
1285 if (asprintf(&branches, "\"%s\" ", branchname) == -1) {
1286 err = got_error_from_errno("asprintf");
1287 goto done;
1290 if (!TAILQ_EMPTY(wanted_refs)) {
1291 struct got_pathlist_entry *pe;
1292 TAILQ_FOREACH(pe, wanted_refs, entry) {
1293 char *s;
1294 const char *refname = pe->path;
1295 if (strncmp(refname, "refs/", 5) == 0)
1296 branchname += 5;
1297 if (asprintf(&s, "%s\"%s\" ",
1298 refs ? refs : "", refname) == -1) {
1299 err = got_error_from_errno("asprintf");
1300 goto done;
1302 free(refs);
1303 refs = s;
1307 /* Create got.conf(5). */
1308 gotconfig_path = got_repo_get_path_gotconfig(repo);
1309 if (gotconfig_path == NULL) {
1310 err = got_error_from_errno("got_repo_get_path_gotconfig");
1311 goto done;
1313 gotconfig_file = fopen(gotconfig_path, "ae");
1314 if (gotconfig_file == NULL) {
1315 err = got_error_from_errno2("fopen", gotconfig_path);
1316 goto done;
1318 if (asprintf(&gotconfig,
1319 "remote \"%s\" {\n"
1320 "\tserver %s\n"
1321 "\tprotocol %s\n"
1322 "%s%s%s"
1323 "\trepository \"%s\"\n"
1324 "%s%s%s"
1325 "%s%s%s"
1326 "%s"
1327 "%s"
1328 "}\n",
1329 GOT_FETCH_DEFAULT_REMOTE_NAME, host, proto,
1330 port ? "\tport " : "", port ? port : "", port ? "\n" : "",
1331 remote_repo_path, branches ? "\tbranch { " : "",
1332 branches ? branches : "", branches ? "}\n" : "",
1333 refs ? "\treference { " : "", refs ? refs : "", refs ? "}\n" : "",
1334 mirror_references ? "\tmirror_references yes\n" : "",
1335 fetch_all_branches ? "\tfetch_all_branches yes\n" : "") == -1) {
1336 err = got_error_from_errno("asprintf");
1337 goto done;
1339 n = fwrite(gotconfig, 1, strlen(gotconfig), gotconfig_file);
1340 if (n != strlen(gotconfig)) {
1341 err = got_ferror(gotconfig_file, GOT_ERR_IO);
1342 goto done;
1345 done:
1346 if (gotconfig_file && fclose(gotconfig_file) == EOF && err == NULL)
1347 err = got_error_from_errno2("fclose", gotconfig_path);
1348 free(gotconfig_path);
1349 free(branches);
1350 return err;
1353 static const struct got_error *
1354 create_gitconfig(const char *git_url, const char *default_branch,
1355 int fetch_all_branches, struct got_pathlist_head *wanted_branches,
1356 struct got_pathlist_head *wanted_refs, int mirror_references,
1357 struct got_repository *repo)
1359 const struct got_error *err = NULL;
1360 char *gitconfig_path = NULL;
1361 char *gitconfig = NULL;
1362 FILE *gitconfig_file = NULL;
1363 char *branches = NULL, *refs = NULL;
1364 const char *branchname;
1365 ssize_t n;
1367 /* Create a config file Git can understand. */
1368 gitconfig_path = got_repo_get_path_gitconfig(repo);
1369 if (gitconfig_path == NULL) {
1370 err = got_error_from_errno("got_repo_get_path_gitconfig");
1371 goto done;
1373 gitconfig_file = fopen(gitconfig_path, "ae");
1374 if (gitconfig_file == NULL) {
1375 err = got_error_from_errno2("fopen", gitconfig_path);
1376 goto done;
1378 if (fetch_all_branches) {
1379 if (mirror_references) {
1380 if (asprintf(&branches,
1381 "\tfetch = refs/heads/*:refs/heads/*\n") == -1) {
1382 err = got_error_from_errno("asprintf");
1383 goto done;
1385 } else if (asprintf(&branches,
1386 "\tfetch = refs/heads/*:refs/remotes/%s/*\n",
1387 GOT_FETCH_DEFAULT_REMOTE_NAME) == -1) {
1388 err = got_error_from_errno("asprintf");
1389 goto done;
1391 } else if (!TAILQ_EMPTY(wanted_branches)) {
1392 struct got_pathlist_entry *pe;
1393 TAILQ_FOREACH(pe, wanted_branches, entry) {
1394 char *s;
1395 branchname = pe->path;
1396 if (strncmp(branchname, "refs/heads/", 11) == 0)
1397 branchname += 11;
1398 if (mirror_references) {
1399 if (asprintf(&s,
1400 "%s\tfetch = refs/heads/%s:refs/heads/%s\n",
1401 branches ? branches : "",
1402 branchname, branchname) == -1) {
1403 err = got_error_from_errno("asprintf");
1404 goto done;
1406 } else if (asprintf(&s,
1407 "%s\tfetch = refs/heads/%s:refs/remotes/%s/%s\n",
1408 branches ? branches : "",
1409 branchname, GOT_FETCH_DEFAULT_REMOTE_NAME,
1410 branchname) == -1) {
1411 err = got_error_from_errno("asprintf");
1412 goto done;
1414 free(branches);
1415 branches = s;
1417 } else {
1419 * If the server specified a default branch, use just that one.
1420 * Otherwise fall back to fetching all branches on next fetch.
1422 if (default_branch) {
1423 branchname = default_branch;
1424 if (strncmp(branchname, "refs/heads/", 11) == 0)
1425 branchname += 11;
1426 } else
1427 branchname = "*"; /* fall back to all branches */
1428 if (mirror_references) {
1429 if (asprintf(&branches,
1430 "\tfetch = refs/heads/%s:refs/heads/%s\n",
1431 branchname, branchname) == -1) {
1432 err = got_error_from_errno("asprintf");
1433 goto done;
1435 } else if (asprintf(&branches,
1436 "\tfetch = refs/heads/%s:refs/remotes/%s/%s\n",
1437 branchname, GOT_FETCH_DEFAULT_REMOTE_NAME,
1438 branchname) == -1) {
1439 err = got_error_from_errno("asprintf");
1440 goto done;
1443 if (!TAILQ_EMPTY(wanted_refs)) {
1444 struct got_pathlist_entry *pe;
1445 TAILQ_FOREACH(pe, wanted_refs, entry) {
1446 char *s;
1447 const char *refname = pe->path;
1448 if (strncmp(refname, "refs/", 5) == 0)
1449 refname += 5;
1450 if (mirror_references) {
1451 if (asprintf(&s,
1452 "%s\tfetch = refs/%s:refs/%s\n",
1453 refs ? refs : "", refname, refname) == -1) {
1454 err = got_error_from_errno("asprintf");
1455 goto done;
1457 } else if (asprintf(&s,
1458 "%s\tfetch = refs/%s:refs/remotes/%s/%s\n",
1459 refs ? refs : "",
1460 refname, GOT_FETCH_DEFAULT_REMOTE_NAME,
1461 refname) == -1) {
1462 err = got_error_from_errno("asprintf");
1463 goto done;
1465 free(refs);
1466 refs = s;
1470 if (asprintf(&gitconfig,
1471 "[remote \"%s\"]\n"
1472 "\turl = %s\n"
1473 "%s"
1474 "%s"
1475 "\tfetch = refs/tags/*:refs/tags/*\n",
1476 GOT_FETCH_DEFAULT_REMOTE_NAME, git_url, branches ? branches : "",
1477 refs ? refs : "") == -1) {
1478 err = got_error_from_errno("asprintf");
1479 goto done;
1481 n = fwrite(gitconfig, 1, strlen(gitconfig), gitconfig_file);
1482 if (n != strlen(gitconfig)) {
1483 err = got_ferror(gitconfig_file, GOT_ERR_IO);
1484 goto done;
1486 done:
1487 if (gitconfig_file && fclose(gitconfig_file) == EOF && err == NULL)
1488 err = got_error_from_errno2("fclose", gitconfig_path);
1489 free(gitconfig_path);
1490 free(branches);
1491 return err;
1494 static const struct got_error *
1495 create_config_files(const char *proto, const char *host, const char *port,
1496 const char *remote_repo_path, const char *git_url, int fetch_all_branches,
1497 int mirror_references, struct got_pathlist_head *symrefs,
1498 struct got_pathlist_head *wanted_branches,
1499 struct got_pathlist_head *wanted_refs, struct got_repository *repo)
1501 const struct got_error *err = NULL;
1502 const char *default_branch = NULL;
1503 struct got_pathlist_entry *pe;
1506 * If we asked for a set of wanted branches then use the first
1507 * one of those.
1509 if (!TAILQ_EMPTY(wanted_branches)) {
1510 pe = TAILQ_FIRST(wanted_branches);
1511 default_branch = pe->path;
1512 } else {
1513 /* First HEAD ref listed by server is the default branch. */
1514 TAILQ_FOREACH(pe, symrefs, entry) {
1515 const char *refname = pe->path;
1516 const char *target = pe->data;
1518 if (strcmp(refname, GOT_REF_HEAD) != 0)
1519 continue;
1521 default_branch = target;
1522 break;
1526 /* Create got.conf(5). */
1527 err = create_gotconfig(proto, host, port, remote_repo_path,
1528 default_branch, fetch_all_branches, wanted_branches,
1529 wanted_refs, mirror_references, repo);
1530 if (err)
1531 return err;
1533 /* Create a config file Git can understand. */
1534 return create_gitconfig(git_url, default_branch, fetch_all_branches,
1535 wanted_branches, wanted_refs, mirror_references, repo);
1538 static const struct got_error *
1539 cmd_clone(int argc, char *argv[])
1541 const struct got_error *error = NULL;
1542 const char *uri, *dirname;
1543 char *proto, *host, *port, *repo_name, *server_path;
1544 char *default_destdir = NULL, *id_str = NULL;
1545 const char *repo_path;
1546 struct got_repository *repo = NULL;
1547 struct got_pathlist_head refs, symrefs, wanted_branches, wanted_refs;
1548 struct got_pathlist_entry *pe;
1549 struct got_object_id *pack_hash = NULL;
1550 int ch, fetchfd = -1, fetchstatus;
1551 pid_t fetchpid = -1;
1552 struct got_fetch_progress_arg fpa;
1553 char *git_url = NULL;
1554 int verbosity = 0, fetch_all_branches = 0, mirror_references = 0;
1555 int list_refs_only = 0;
1556 int *pack_fds = NULL;
1558 TAILQ_INIT(&refs);
1559 TAILQ_INIT(&symrefs);
1560 TAILQ_INIT(&wanted_branches);
1561 TAILQ_INIT(&wanted_refs);
1563 while ((ch = getopt(argc, argv, "ab:lmqR:v")) != -1) {
1564 switch (ch) {
1565 case 'a':
1566 fetch_all_branches = 1;
1567 break;
1568 case 'b':
1569 error = got_pathlist_append(&wanted_branches,
1570 optarg, NULL);
1571 if (error)
1572 return error;
1573 break;
1574 case 'l':
1575 list_refs_only = 1;
1576 break;
1577 case 'm':
1578 mirror_references = 1;
1579 break;
1580 case 'q':
1581 verbosity = -1;
1582 break;
1583 case 'R':
1584 error = got_pathlist_append(&wanted_refs,
1585 optarg, NULL);
1586 if (error)
1587 return error;
1588 break;
1589 case 'v':
1590 if (verbosity < 0)
1591 verbosity = 0;
1592 else if (verbosity < 3)
1593 verbosity++;
1594 break;
1595 default:
1596 usage_clone();
1597 break;
1600 argc -= optind;
1601 argv += optind;
1603 if (fetch_all_branches && !TAILQ_EMPTY(&wanted_branches))
1604 option_conflict('a', 'b');
1605 if (list_refs_only) {
1606 if (!TAILQ_EMPTY(&wanted_branches))
1607 option_conflict('l', 'b');
1608 if (fetch_all_branches)
1609 option_conflict('l', 'a');
1610 if (mirror_references)
1611 option_conflict('l', 'm');
1612 if (!TAILQ_EMPTY(&wanted_refs))
1613 option_conflict('l', 'R');
1616 uri = argv[0];
1618 if (argc == 1)
1619 dirname = NULL;
1620 else if (argc == 2)
1621 dirname = argv[1];
1622 else
1623 usage_clone();
1625 error = got_dial_parse_uri(&proto, &host, &port, &server_path,
1626 &repo_name, uri);
1627 if (error)
1628 goto done;
1630 if (asprintf(&git_url, "%s://%s%s%s%s%s", proto,
1631 host, port ? ":" : "", port ? port : "",
1632 server_path[0] != '/' ? "/" : "", server_path) == -1) {
1633 error = got_error_from_errno("asprintf");
1634 goto done;
1637 if (strcmp(proto, "git") == 0) {
1638 #ifndef PROFILE
1639 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
1640 "sendfd dns inet unveil", NULL) == -1)
1641 err(1, "pledge");
1642 #endif
1643 } else if (strcmp(proto, "git+ssh") == 0 ||
1644 strcmp(proto, "ssh") == 0) {
1645 #ifndef PROFILE
1646 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
1647 "sendfd unveil", NULL) == -1)
1648 err(1, "pledge");
1649 #endif
1650 } else if (strcmp(proto, "http") == 0 ||
1651 strcmp(proto, "git+http") == 0) {
1652 error = got_error_path(proto, GOT_ERR_NOT_IMPL);
1653 goto done;
1654 } else {
1655 error = got_error_path(proto, GOT_ERR_BAD_PROTO);
1656 goto done;
1658 if (dirname == NULL) {
1659 if (asprintf(&default_destdir, "%s.git", repo_name) == -1) {
1660 error = got_error_from_errno("asprintf");
1661 goto done;
1663 repo_path = default_destdir;
1664 } else
1665 repo_path = dirname;
1667 if (!list_refs_only) {
1668 error = got_path_mkdir(repo_path);
1669 if (error &&
1670 (!(error->code == GOT_ERR_ERRNO && errno == EISDIR) &&
1671 !(error->code == GOT_ERR_ERRNO && errno == EEXIST)))
1672 goto done;
1673 if (!got_path_dir_is_empty(repo_path)) {
1674 error = got_error_path(repo_path,
1675 GOT_ERR_DIR_NOT_EMPTY);
1676 goto done;
1680 error = got_dial_apply_unveil(proto);
1681 if (error)
1682 goto done;
1684 error = apply_unveil(repo_path, 0, NULL);
1685 if (error)
1686 goto done;
1688 if (verbosity >= 0)
1689 printf("Connecting to %s\n", git_url);
1691 error = got_fetch_connect(&fetchpid, &fetchfd, proto, host, port,
1692 server_path, verbosity);
1693 if (error)
1694 goto done;
1696 if (!list_refs_only) {
1697 error = got_repo_init(repo_path, NULL);
1698 if (error)
1699 goto done;
1700 error = got_repo_pack_fds_open(&pack_fds);
1701 if (error != NULL)
1702 goto done;
1703 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
1704 if (error)
1705 goto done;
1708 fpa.last_scaled_size[0] = '\0';
1709 fpa.last_p_indexed = -1;
1710 fpa.last_p_resolved = -1;
1711 fpa.verbosity = verbosity;
1712 fpa.create_configs = 1;
1713 fpa.configs_created = 0;
1714 fpa.repo = repo;
1715 fpa.config_info.symrefs = &symrefs;
1716 fpa.config_info.wanted_branches = &wanted_branches;
1717 fpa.config_info.wanted_refs = &wanted_refs;
1718 fpa.config_info.proto = proto;
1719 fpa.config_info.host = host;
1720 fpa.config_info.port = port;
1721 fpa.config_info.remote_repo_path = server_path;
1722 fpa.config_info.git_url = git_url;
1723 fpa.config_info.fetch_all_branches = fetch_all_branches;
1724 fpa.config_info.mirror_references = mirror_references;
1725 error = got_fetch_pack(&pack_hash, &refs, &symrefs,
1726 GOT_FETCH_DEFAULT_REMOTE_NAME, mirror_references,
1727 fetch_all_branches, &wanted_branches, &wanted_refs,
1728 list_refs_only, verbosity, fetchfd, repo,
1729 fetch_progress, &fpa);
1730 if (error)
1731 goto done;
1733 if (list_refs_only) {
1734 error = list_remote_refs(&symrefs, &refs);
1735 goto done;
1738 if (pack_hash == NULL) {
1739 error = got_error_fmt(GOT_ERR_FETCH_FAILED, "%s",
1740 "server sent an empty pack file");
1741 goto done;
1743 error = got_object_id_str(&id_str, pack_hash);
1744 if (error)
1745 goto done;
1746 if (verbosity >= 0)
1747 printf("\nFetched %s.pack\n", id_str);
1748 free(id_str);
1750 /* Set up references provided with the pack file. */
1751 TAILQ_FOREACH(pe, &refs, entry) {
1752 const char *refname = pe->path;
1753 struct got_object_id *id = pe->data;
1754 char *remote_refname;
1756 if (is_wanted_ref(&wanted_refs, refname) &&
1757 !mirror_references) {
1758 error = create_wanted_ref(refname, id,
1759 GOT_FETCH_DEFAULT_REMOTE_NAME,
1760 verbosity - 1, repo);
1761 if (error)
1762 goto done;
1763 continue;
1766 error = create_ref(refname, id, verbosity - 1, repo);
1767 if (error)
1768 goto done;
1770 if (mirror_references)
1771 continue;
1773 if (strncmp("refs/heads/", refname, 11) != 0)
1774 continue;
1776 if (asprintf(&remote_refname,
1777 "refs/remotes/%s/%s", GOT_FETCH_DEFAULT_REMOTE_NAME,
1778 refname + 11) == -1) {
1779 error = got_error_from_errno("asprintf");
1780 goto done;
1782 error = create_ref(remote_refname, id, verbosity - 1, repo);
1783 free(remote_refname);
1784 if (error)
1785 goto done;
1788 /* Set the HEAD reference if the server provided one. */
1789 TAILQ_FOREACH(pe, &symrefs, entry) {
1790 struct got_reference *target_ref;
1791 const char *refname = pe->path;
1792 const char *target = pe->data;
1793 char *remote_refname = NULL, *remote_target = NULL;
1795 if (strcmp(refname, GOT_REF_HEAD) != 0)
1796 continue;
1798 error = got_ref_open(&target_ref, repo, target, 0);
1799 if (error) {
1800 if (error->code == GOT_ERR_NOT_REF) {
1801 error = NULL;
1802 continue;
1804 goto done;
1807 error = create_symref(refname, target_ref, verbosity, repo);
1808 got_ref_close(target_ref);
1809 if (error)
1810 goto done;
1812 if (mirror_references)
1813 continue;
1815 if (strncmp("refs/heads/", target, 11) != 0)
1816 continue;
1818 if (asprintf(&remote_refname,
1819 "refs/remotes/%s/%s", GOT_FETCH_DEFAULT_REMOTE_NAME,
1820 refname) == -1) {
1821 error = got_error_from_errno("asprintf");
1822 goto done;
1824 if (asprintf(&remote_target,
1825 "refs/remotes/%s/%s", GOT_FETCH_DEFAULT_REMOTE_NAME,
1826 target + 11) == -1) {
1827 error = got_error_from_errno("asprintf");
1828 free(remote_refname);
1829 goto done;
1831 error = got_ref_open(&target_ref, repo, remote_target, 0);
1832 if (error) {
1833 free(remote_refname);
1834 free(remote_target);
1835 if (error->code == GOT_ERR_NOT_REF) {
1836 error = NULL;
1837 continue;
1839 goto done;
1841 error = create_symref(remote_refname, target_ref,
1842 verbosity - 1, repo);
1843 free(remote_refname);
1844 free(remote_target);
1845 got_ref_close(target_ref);
1846 if (error)
1847 goto done;
1849 if (pe == NULL) {
1851 * We failed to set the HEAD reference. If we asked for
1852 * a set of wanted branches use the first of one of those
1853 * which could be fetched instead.
1855 TAILQ_FOREACH(pe, &wanted_branches, entry) {
1856 const char *target = pe->path;
1857 struct got_reference *target_ref;
1859 error = got_ref_open(&target_ref, repo, target, 0);
1860 if (error) {
1861 if (error->code == GOT_ERR_NOT_REF) {
1862 error = NULL;
1863 continue;
1865 goto done;
1868 error = create_symref(GOT_REF_HEAD, target_ref,
1869 verbosity, repo);
1870 got_ref_close(target_ref);
1871 if (error)
1872 goto done;
1873 break;
1876 if (!fpa.configs_created && pe != NULL) {
1877 error = create_config_files(fpa.config_info.proto,
1878 fpa.config_info.host, fpa.config_info.port,
1879 fpa.config_info.remote_repo_path,
1880 fpa.config_info.git_url,
1881 fpa.config_info.fetch_all_branches,
1882 fpa.config_info.mirror_references,
1883 fpa.config_info.symrefs,
1884 fpa.config_info.wanted_branches,
1885 fpa.config_info.wanted_refs, fpa.repo);
1886 if (error)
1887 goto done;
1891 if (verbosity >= 0)
1892 printf("Created %s repository '%s'\n",
1893 mirror_references ? "mirrored" : "cloned", repo_path);
1894 done:
1895 if (pack_fds) {
1896 const struct got_error *pack_err =
1897 got_repo_pack_fds_close(pack_fds);
1898 if (error == NULL)
1899 error = pack_err;
1901 if (fetchpid > 0) {
1902 if (kill(fetchpid, SIGTERM) == -1)
1903 error = got_error_from_errno("kill");
1904 if (waitpid(fetchpid, &fetchstatus, 0) == -1 && error == NULL)
1905 error = got_error_from_errno("waitpid");
1907 if (fetchfd != -1 && close(fetchfd) == -1 && error == NULL)
1908 error = got_error_from_errno("close");
1909 if (repo) {
1910 const struct got_error *close_err = got_repo_close(repo);
1911 if (error == NULL)
1912 error = close_err;
1914 got_pathlist_free(&refs, GOT_PATHLIST_FREE_ALL);
1915 got_pathlist_free(&symrefs, GOT_PATHLIST_FREE_ALL);
1916 got_pathlist_free(&wanted_branches, GOT_PATHLIST_FREE_NONE);
1917 got_pathlist_free(&wanted_refs, GOT_PATHLIST_FREE_NONE);
1918 free(pack_hash);
1919 free(proto);
1920 free(host);
1921 free(port);
1922 free(server_path);
1923 free(repo_name);
1924 free(default_destdir);
1925 free(git_url);
1926 return error;
1929 static const struct got_error *
1930 update_ref(struct got_reference *ref, struct got_object_id *new_id,
1931 int replace_tags, int verbosity, struct got_repository *repo)
1933 const struct got_error *err = NULL;
1934 char *new_id_str = NULL;
1935 struct got_object_id *old_id = NULL;
1937 err = got_object_id_str(&new_id_str, new_id);
1938 if (err)
1939 goto done;
1941 if (!replace_tags &&
1942 strncmp(got_ref_get_name(ref), "refs/tags/", 10) == 0) {
1943 err = got_ref_resolve(&old_id, repo, ref);
1944 if (err)
1945 goto done;
1946 if (got_object_id_cmp(old_id, new_id) == 0)
1947 goto done;
1948 if (verbosity >= 0) {
1949 printf("Rejecting update of existing tag %s: %s\n",
1950 got_ref_get_name(ref), new_id_str);
1952 goto done;
1955 if (got_ref_is_symbolic(ref)) {
1956 if (verbosity >= 0) {
1957 printf("Replacing reference %s: %s\n",
1958 got_ref_get_name(ref),
1959 got_ref_get_symref_target(ref));
1961 err = got_ref_change_symref_to_ref(ref, new_id);
1962 if (err)
1963 goto done;
1964 err = got_ref_write(ref, repo);
1965 if (err)
1966 goto done;
1967 } else {
1968 err = got_ref_resolve(&old_id, repo, ref);
1969 if (err)
1970 goto done;
1971 if (got_object_id_cmp(old_id, new_id) == 0)
1972 goto done;
1974 err = got_ref_change_ref(ref, new_id);
1975 if (err)
1976 goto done;
1977 err = got_ref_write(ref, repo);
1978 if (err)
1979 goto done;
1982 if (verbosity >= 0)
1983 printf("Updated %s: %s\n", got_ref_get_name(ref),
1984 new_id_str);
1985 done:
1986 free(old_id);
1987 free(new_id_str);
1988 return err;
1991 static const struct got_error *
1992 update_symref(const char *refname, struct got_reference *target_ref,
1993 int verbosity, struct got_repository *repo)
1995 const struct got_error *err = NULL, *unlock_err;
1996 struct got_reference *symref;
1997 int symref_is_locked = 0;
1999 err = got_ref_open(&symref, repo, refname, 1);
2000 if (err) {
2001 if (err->code != GOT_ERR_NOT_REF)
2002 return err;
2003 err = got_ref_alloc_symref(&symref, refname, target_ref);
2004 if (err)
2005 goto done;
2007 err = got_ref_write(symref, repo);
2008 if (err)
2009 goto done;
2011 if (verbosity >= 0)
2012 printf("Created reference %s: %s\n",
2013 got_ref_get_name(symref),
2014 got_ref_get_symref_target(symref));
2015 } else {
2016 symref_is_locked = 1;
2018 if (strcmp(got_ref_get_symref_target(symref),
2019 got_ref_get_name(target_ref)) == 0)
2020 goto done;
2022 err = got_ref_change_symref(symref,
2023 got_ref_get_name(target_ref));
2024 if (err)
2025 goto done;
2027 err = got_ref_write(symref, repo);
2028 if (err)
2029 goto done;
2031 if (verbosity >= 0)
2032 printf("Updated %s: %s\n", got_ref_get_name(symref),
2033 got_ref_get_symref_target(symref));
2036 done:
2037 if (symref_is_locked) {
2038 unlock_err = got_ref_unlock(symref);
2039 if (unlock_err && err == NULL)
2040 err = unlock_err;
2042 got_ref_close(symref);
2043 return err;
2046 __dead static void
2047 usage_fetch(void)
2049 fprintf(stderr, "usage: %s fetch [-adlqtvX] [-b branch] "
2050 "[-R reference] [-r repository-path] [remote-repository]\n",
2051 getprogname());
2052 exit(1);
2055 static const struct got_error *
2056 delete_missing_ref(struct got_reference *ref,
2057 int verbosity, struct got_repository *repo)
2059 const struct got_error *err = NULL;
2060 struct got_object_id *id = NULL;
2061 char *id_str = NULL;
2063 if (got_ref_is_symbolic(ref)) {
2064 err = got_ref_delete(ref, repo);
2065 if (err)
2066 return err;
2067 if (verbosity >= 0) {
2068 printf("Deleted %s: %s\n",
2069 got_ref_get_name(ref),
2070 got_ref_get_symref_target(ref));
2072 } else {
2073 err = got_ref_resolve(&id, repo, ref);
2074 if (err)
2075 return err;
2076 err = got_object_id_str(&id_str, id);
2077 if (err)
2078 goto done;
2080 err = got_ref_delete(ref, repo);
2081 if (err)
2082 goto done;
2083 if (verbosity >= 0) {
2084 printf("Deleted %s: %s\n",
2085 got_ref_get_name(ref), id_str);
2088 done:
2089 free(id);
2090 free(id_str);
2091 return NULL;
2094 static const struct got_error *
2095 delete_missing_refs(struct got_pathlist_head *their_refs,
2096 struct got_pathlist_head *their_symrefs,
2097 const struct got_remote_repo *remote,
2098 int verbosity, struct got_repository *repo)
2100 const struct got_error *err = NULL, *unlock_err;
2101 struct got_reflist_head my_refs;
2102 struct got_reflist_entry *re;
2103 struct got_pathlist_entry *pe;
2104 char *remote_namespace = NULL;
2105 char *local_refname = NULL;
2107 TAILQ_INIT(&my_refs);
2109 if (asprintf(&remote_namespace, "refs/remotes/%s/", remote->name)
2110 == -1)
2111 return got_error_from_errno("asprintf");
2113 err = got_ref_list(&my_refs, repo, NULL, got_ref_cmp_by_name, NULL);
2114 if (err)
2115 goto done;
2117 TAILQ_FOREACH(re, &my_refs, entry) {
2118 const char *refname = got_ref_get_name(re->ref);
2119 const char *their_refname;
2121 if (remote->mirror_references) {
2122 their_refname = refname;
2123 } else {
2124 if (strncmp(refname, remote_namespace,
2125 strlen(remote_namespace)) == 0) {
2126 if (strcmp(refname + strlen(remote_namespace),
2127 GOT_REF_HEAD) == 0)
2128 continue;
2129 if (asprintf(&local_refname, "refs/heads/%s",
2130 refname + strlen(remote_namespace)) == -1) {
2131 err = got_error_from_errno("asprintf");
2132 goto done;
2134 } else if (strncmp(refname, "refs/tags/", 10) != 0)
2135 continue;
2137 their_refname = local_refname;
2140 TAILQ_FOREACH(pe, their_refs, entry) {
2141 if (strcmp(their_refname, pe->path) == 0)
2142 break;
2144 if (pe != NULL)
2145 continue;
2147 TAILQ_FOREACH(pe, their_symrefs, entry) {
2148 if (strcmp(their_refname, pe->path) == 0)
2149 break;
2151 if (pe != NULL)
2152 continue;
2154 err = delete_missing_ref(re->ref, verbosity, repo);
2155 if (err)
2156 break;
2158 if (local_refname) {
2159 struct got_reference *ref;
2160 err = got_ref_open(&ref, repo, local_refname, 1);
2161 if (err) {
2162 if (err->code != GOT_ERR_NOT_REF)
2163 break;
2164 free(local_refname);
2165 local_refname = NULL;
2166 continue;
2168 err = delete_missing_ref(ref, verbosity, repo);
2169 if (err)
2170 break;
2171 unlock_err = got_ref_unlock(ref);
2172 got_ref_close(ref);
2173 if (unlock_err && err == NULL) {
2174 err = unlock_err;
2175 break;
2178 free(local_refname);
2179 local_refname = NULL;
2182 done:
2183 got_ref_list_free(&my_refs);
2184 free(remote_namespace);
2185 free(local_refname);
2186 return err;
2189 static const struct got_error *
2190 update_wanted_ref(const char *refname, struct got_object_id *id,
2191 const char *remote_repo_name, int verbosity, struct got_repository *repo)
2193 const struct got_error *err, *unlock_err;
2194 char *remote_refname;
2195 struct got_reference *ref;
2197 if (strncmp("refs/", refname, 5) == 0)
2198 refname += 5;
2200 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
2201 remote_repo_name, refname) == -1)
2202 return got_error_from_errno("asprintf");
2204 err = got_ref_open(&ref, repo, remote_refname, 1);
2205 if (err) {
2206 if (err->code != GOT_ERR_NOT_REF)
2207 goto done;
2208 err = create_ref(remote_refname, id, verbosity, repo);
2209 } else {
2210 err = update_ref(ref, id, 0, verbosity, repo);
2211 unlock_err = got_ref_unlock(ref);
2212 if (unlock_err && err == NULL)
2213 err = unlock_err;
2214 got_ref_close(ref);
2216 done:
2217 free(remote_refname);
2218 return err;
2221 static const struct got_error *
2222 delete_ref(struct got_repository *repo, struct got_reference *ref)
2224 const struct got_error *err = NULL;
2225 struct got_object_id *id = NULL;
2226 char *id_str = NULL;
2227 const char *target;
2229 if (got_ref_is_symbolic(ref)) {
2230 target = got_ref_get_symref_target(ref);
2231 } else {
2232 err = got_ref_resolve(&id, repo, ref);
2233 if (err)
2234 goto done;
2235 err = got_object_id_str(&id_str, id);
2236 if (err)
2237 goto done;
2238 target = id_str;
2241 err = got_ref_delete(ref, repo);
2242 if (err)
2243 goto done;
2245 printf("Deleted %s: %s\n", got_ref_get_name(ref), target);
2246 done:
2247 free(id);
2248 free(id_str);
2249 return err;
2252 static const struct got_error *
2253 delete_refs_for_remote(struct got_repository *repo, const char *remote_name)
2255 const struct got_error *err = NULL;
2256 struct got_reflist_head refs;
2257 struct got_reflist_entry *re;
2258 char *prefix;
2260 TAILQ_INIT(&refs);
2262 if (asprintf(&prefix, "refs/remotes/%s", remote_name) == -1) {
2263 err = got_error_from_errno("asprintf");
2264 goto done;
2266 err = got_ref_list(&refs, repo, prefix, got_ref_cmp_by_name, NULL);
2267 if (err)
2268 goto done;
2270 TAILQ_FOREACH(re, &refs, entry)
2271 delete_ref(repo, re->ref);
2272 done:
2273 got_ref_list_free(&refs);
2274 return err;
2277 static const struct got_error *
2278 cmd_fetch(int argc, char *argv[])
2280 const struct got_error *error = NULL, *unlock_err;
2281 char *cwd = NULL, *repo_path = NULL;
2282 const char *remote_name;
2283 char *proto = NULL, *host = NULL, *port = NULL;
2284 char *repo_name = NULL, *server_path = NULL;
2285 const struct got_remote_repo *remotes, *remote = NULL;
2286 int nremotes;
2287 char *id_str = NULL;
2288 struct got_repository *repo = NULL;
2289 struct got_worktree *worktree = NULL;
2290 const struct got_gotconfig *repo_conf = NULL, *worktree_conf = NULL;
2291 struct got_pathlist_head refs, symrefs, wanted_branches, wanted_refs;
2292 struct got_pathlist_entry *pe;
2293 struct got_object_id *pack_hash = NULL;
2294 int i, ch, fetchfd = -1, fetchstatus;
2295 pid_t fetchpid = -1;
2296 struct got_fetch_progress_arg fpa;
2297 int verbosity = 0, fetch_all_branches = 0, list_refs_only = 0;
2298 int delete_refs = 0, replace_tags = 0, delete_remote = 0;
2299 int *pack_fds = NULL;
2301 TAILQ_INIT(&refs);
2302 TAILQ_INIT(&symrefs);
2303 TAILQ_INIT(&wanted_branches);
2304 TAILQ_INIT(&wanted_refs);
2306 while ((ch = getopt(argc, argv, "ab:dlqR:r:tvX")) != -1) {
2307 switch (ch) {
2308 case 'a':
2309 fetch_all_branches = 1;
2310 break;
2311 case 'b':
2312 error = got_pathlist_append(&wanted_branches,
2313 optarg, NULL);
2314 if (error)
2315 return error;
2316 break;
2317 case 'd':
2318 delete_refs = 1;
2319 break;
2320 case 'l':
2321 list_refs_only = 1;
2322 break;
2323 case 'q':
2324 verbosity = -1;
2325 break;
2326 case 'R':
2327 error = got_pathlist_append(&wanted_refs,
2328 optarg, NULL);
2329 if (error)
2330 return error;
2331 break;
2332 case 'r':
2333 repo_path = realpath(optarg, NULL);
2334 if (repo_path == NULL)
2335 return got_error_from_errno2("realpath",
2336 optarg);
2337 got_path_strip_trailing_slashes(repo_path);
2338 break;
2339 case 't':
2340 replace_tags = 1;
2341 break;
2342 case 'v':
2343 if (verbosity < 0)
2344 verbosity = 0;
2345 else if (verbosity < 3)
2346 verbosity++;
2347 break;
2348 case 'X':
2349 delete_remote = 1;
2350 break;
2351 default:
2352 usage_fetch();
2353 break;
2356 argc -= optind;
2357 argv += optind;
2359 if (fetch_all_branches && !TAILQ_EMPTY(&wanted_branches))
2360 option_conflict('a', 'b');
2361 if (list_refs_only) {
2362 if (!TAILQ_EMPTY(&wanted_branches))
2363 option_conflict('l', 'b');
2364 if (fetch_all_branches)
2365 option_conflict('l', 'a');
2366 if (delete_refs)
2367 option_conflict('l', 'd');
2368 if (delete_remote)
2369 option_conflict('l', 'X');
2371 if (delete_remote) {
2372 if (fetch_all_branches)
2373 option_conflict('X', 'a');
2374 if (!TAILQ_EMPTY(&wanted_branches))
2375 option_conflict('X', 'b');
2376 if (delete_refs)
2377 option_conflict('X', 'd');
2378 if (replace_tags)
2379 option_conflict('X', 't');
2380 if (!TAILQ_EMPTY(&wanted_refs))
2381 option_conflict('X', 'R');
2384 if (argc == 0) {
2385 if (delete_remote)
2386 errx(1, "-X option requires a remote name");
2387 remote_name = GOT_FETCH_DEFAULT_REMOTE_NAME;
2388 } else if (argc == 1)
2389 remote_name = argv[0];
2390 else
2391 usage_fetch();
2393 cwd = getcwd(NULL, 0);
2394 if (cwd == NULL) {
2395 error = got_error_from_errno("getcwd");
2396 goto done;
2399 error = got_repo_pack_fds_open(&pack_fds);
2400 if (error != NULL)
2401 goto done;
2403 if (repo_path == NULL) {
2404 error = got_worktree_open(&worktree, cwd);
2405 if (error && error->code != GOT_ERR_NOT_WORKTREE)
2406 goto done;
2407 else
2408 error = NULL;
2409 if (worktree) {
2410 repo_path =
2411 strdup(got_worktree_get_repo_path(worktree));
2412 if (repo_path == NULL)
2413 error = got_error_from_errno("strdup");
2414 if (error)
2415 goto done;
2416 } else {
2417 repo_path = strdup(cwd);
2418 if (repo_path == NULL) {
2419 error = got_error_from_errno("strdup");
2420 goto done;
2425 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
2426 if (error)
2427 goto done;
2429 if (delete_remote) {
2430 error = delete_refs_for_remote(repo, remote_name);
2431 goto done; /* nothing else to do */
2434 if (worktree) {
2435 worktree_conf = got_worktree_get_gotconfig(worktree);
2436 if (worktree_conf) {
2437 got_gotconfig_get_remotes(&nremotes, &remotes,
2438 worktree_conf);
2439 for (i = 0; i < nremotes; i++) {
2440 if (strcmp(remotes[i].name, remote_name) == 0) {
2441 remote = &remotes[i];
2442 break;
2447 if (remote == NULL) {
2448 repo_conf = got_repo_get_gotconfig(repo);
2449 if (repo_conf) {
2450 got_gotconfig_get_remotes(&nremotes, &remotes,
2451 repo_conf);
2452 for (i = 0; i < nremotes; i++) {
2453 if (strcmp(remotes[i].name, remote_name) == 0) {
2454 remote = &remotes[i];
2455 break;
2460 if (remote == NULL) {
2461 got_repo_get_gitconfig_remotes(&nremotes, &remotes, repo);
2462 for (i = 0; i < nremotes; i++) {
2463 if (strcmp(remotes[i].name, remote_name) == 0) {
2464 remote = &remotes[i];
2465 break;
2469 if (remote == NULL) {
2470 error = got_error_path(remote_name, GOT_ERR_NO_REMOTE);
2471 goto done;
2474 if (TAILQ_EMPTY(&wanted_branches)) {
2475 if (!fetch_all_branches)
2476 fetch_all_branches = remote->fetch_all_branches;
2477 for (i = 0; i < remote->nfetch_branches; i++) {
2478 error = got_pathlist_append(&wanted_branches,
2479 remote->fetch_branches[i], NULL);
2480 if (error)
2481 goto done;
2484 if (TAILQ_EMPTY(&wanted_refs)) {
2485 for (i = 0; i < remote->nfetch_refs; i++) {
2486 error = got_pathlist_append(&wanted_refs,
2487 remote->fetch_refs[i], NULL);
2488 if (error)
2489 goto done;
2493 error = got_dial_parse_uri(&proto, &host, &port, &server_path,
2494 &repo_name, remote->fetch_url);
2495 if (error)
2496 goto done;
2498 if (strcmp(proto, "git") == 0) {
2499 #ifndef PROFILE
2500 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
2501 "sendfd dns inet unveil", NULL) == -1)
2502 err(1, "pledge");
2503 #endif
2504 } else if (strcmp(proto, "git+ssh") == 0 ||
2505 strcmp(proto, "ssh") == 0) {
2506 #ifndef PROFILE
2507 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
2508 "sendfd unveil", NULL) == -1)
2509 err(1, "pledge");
2510 #endif
2511 } else if (strcmp(proto, "http") == 0 ||
2512 strcmp(proto, "git+http") == 0) {
2513 error = got_error_path(proto, GOT_ERR_NOT_IMPL);
2514 goto done;
2515 } else {
2516 error = got_error_path(proto, GOT_ERR_BAD_PROTO);
2517 goto done;
2520 error = got_dial_apply_unveil(proto);
2521 if (error)
2522 goto done;
2524 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
2525 if (error)
2526 goto done;
2528 if (verbosity >= 0) {
2529 printf("Connecting to \"%s\" %s://%s%s%s%s%s\n",
2530 remote->name, proto, host,
2531 port ? ":" : "", port ? port : "",
2532 *server_path == '/' ? "" : "/", server_path);
2535 error = got_fetch_connect(&fetchpid, &fetchfd, proto, host, port,
2536 server_path, verbosity);
2537 if (error)
2538 goto done;
2540 fpa.last_scaled_size[0] = '\0';
2541 fpa.last_p_indexed = -1;
2542 fpa.last_p_resolved = -1;
2543 fpa.verbosity = verbosity;
2544 fpa.repo = repo;
2545 fpa.create_configs = 0;
2546 fpa.configs_created = 0;
2547 memset(&fpa.config_info, 0, sizeof(fpa.config_info));
2548 error = got_fetch_pack(&pack_hash, &refs, &symrefs, remote->name,
2549 remote->mirror_references, fetch_all_branches, &wanted_branches,
2550 &wanted_refs, list_refs_only, verbosity, fetchfd, repo,
2551 fetch_progress, &fpa);
2552 if (error)
2553 goto done;
2555 if (list_refs_only) {
2556 error = list_remote_refs(&symrefs, &refs);
2557 goto done;
2560 if (pack_hash == NULL) {
2561 if (verbosity >= 0)
2562 printf("Already up-to-date\n");
2563 } else if (verbosity >= 0) {
2564 error = got_object_id_str(&id_str, pack_hash);
2565 if (error)
2566 goto done;
2567 printf("\nFetched %s.pack\n", id_str);
2568 free(id_str);
2569 id_str = NULL;
2572 /* Update references provided with the pack file. */
2573 TAILQ_FOREACH(pe, &refs, entry) {
2574 const char *refname = pe->path;
2575 struct got_object_id *id = pe->data;
2576 struct got_reference *ref;
2577 char *remote_refname;
2579 if (is_wanted_ref(&wanted_refs, refname) &&
2580 !remote->mirror_references) {
2581 error = update_wanted_ref(refname, id,
2582 remote->name, verbosity, repo);
2583 if (error)
2584 goto done;
2585 continue;
2588 if (remote->mirror_references ||
2589 strncmp("refs/tags/", refname, 10) == 0) {
2590 error = got_ref_open(&ref, repo, refname, 1);
2591 if (error) {
2592 if (error->code != GOT_ERR_NOT_REF)
2593 goto done;
2594 error = create_ref(refname, id, verbosity,
2595 repo);
2596 if (error)
2597 goto done;
2598 } else {
2599 error = update_ref(ref, id, replace_tags,
2600 verbosity, repo);
2601 unlock_err = got_ref_unlock(ref);
2602 if (unlock_err && error == NULL)
2603 error = unlock_err;
2604 got_ref_close(ref);
2605 if (error)
2606 goto done;
2608 } else if (strncmp("refs/heads/", refname, 11) == 0) {
2609 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
2610 remote_name, refname + 11) == -1) {
2611 error = got_error_from_errno("asprintf");
2612 goto done;
2615 error = got_ref_open(&ref, repo, remote_refname, 1);
2616 if (error) {
2617 if (error->code != GOT_ERR_NOT_REF)
2618 goto done;
2619 error = create_ref(remote_refname, id,
2620 verbosity, repo);
2621 if (error)
2622 goto done;
2623 } else {
2624 error = update_ref(ref, id, replace_tags,
2625 verbosity, repo);
2626 unlock_err = got_ref_unlock(ref);
2627 if (unlock_err && error == NULL)
2628 error = unlock_err;
2629 got_ref_close(ref);
2630 if (error)
2631 goto done;
2634 /* Also create a local branch if none exists yet. */
2635 error = got_ref_open(&ref, repo, refname, 1);
2636 if (error) {
2637 if (error->code != GOT_ERR_NOT_REF)
2638 goto done;
2639 error = create_ref(refname, id, verbosity,
2640 repo);
2641 if (error)
2642 goto done;
2643 } else {
2644 unlock_err = got_ref_unlock(ref);
2645 if (unlock_err && error == NULL)
2646 error = unlock_err;
2647 got_ref_close(ref);
2651 if (delete_refs) {
2652 error = delete_missing_refs(&refs, &symrefs, remote,
2653 verbosity, repo);
2654 if (error)
2655 goto done;
2658 if (!remote->mirror_references) {
2659 /* Update remote HEAD reference if the server provided one. */
2660 TAILQ_FOREACH(pe, &symrefs, entry) {
2661 struct got_reference *target_ref;
2662 const char *refname = pe->path;
2663 const char *target = pe->data;
2664 char *remote_refname = NULL, *remote_target = NULL;
2666 if (strcmp(refname, GOT_REF_HEAD) != 0)
2667 continue;
2669 if (strncmp("refs/heads/", target, 11) != 0)
2670 continue;
2672 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
2673 remote->name, refname) == -1) {
2674 error = got_error_from_errno("asprintf");
2675 goto done;
2677 if (asprintf(&remote_target, "refs/remotes/%s/%s",
2678 remote->name, target + 11) == -1) {
2679 error = got_error_from_errno("asprintf");
2680 free(remote_refname);
2681 goto done;
2684 error = got_ref_open(&target_ref, repo, remote_target,
2685 0);
2686 if (error) {
2687 free(remote_refname);
2688 free(remote_target);
2689 if (error->code == GOT_ERR_NOT_REF) {
2690 error = NULL;
2691 continue;
2693 goto done;
2695 error = update_symref(remote_refname, target_ref,
2696 verbosity, repo);
2697 free(remote_refname);
2698 free(remote_target);
2699 got_ref_close(target_ref);
2700 if (error)
2701 goto done;
2704 done:
2705 if (fetchpid > 0) {
2706 if (kill(fetchpid, SIGTERM) == -1)
2707 error = got_error_from_errno("kill");
2708 if (waitpid(fetchpid, &fetchstatus, 0) == -1 && error == NULL)
2709 error = got_error_from_errno("waitpid");
2711 if (fetchfd != -1 && close(fetchfd) == -1 && error == NULL)
2712 error = got_error_from_errno("close");
2713 if (repo) {
2714 const struct got_error *close_err = got_repo_close(repo);
2715 if (error == NULL)
2716 error = close_err;
2718 if (worktree)
2719 got_worktree_close(worktree);
2720 if (pack_fds) {
2721 const struct got_error *pack_err =
2722 got_repo_pack_fds_close(pack_fds);
2723 if (error == NULL)
2724 error = pack_err;
2726 got_pathlist_free(&refs, GOT_PATHLIST_FREE_ALL);
2727 got_pathlist_free(&symrefs, GOT_PATHLIST_FREE_ALL);
2728 got_pathlist_free(&wanted_branches, GOT_PATHLIST_FREE_NONE);
2729 got_pathlist_free(&wanted_refs, GOT_PATHLIST_FREE_NONE);
2730 free(id_str);
2731 free(cwd);
2732 free(repo_path);
2733 free(pack_hash);
2734 free(proto);
2735 free(host);
2736 free(port);
2737 free(server_path);
2738 free(repo_name);
2739 return error;
2743 __dead static void
2744 usage_checkout(void)
2746 fprintf(stderr, "usage: %s checkout [-Eq] [-b branch] [-c commit] "
2747 "[-p path-prefix] repository-path [work-tree-path]\n",
2748 getprogname());
2749 exit(1);
2752 static void
2753 show_worktree_base_ref_warning(void)
2755 fprintf(stderr, "%s: warning: could not create a reference "
2756 "to the work tree's base commit; the commit could be "
2757 "garbage-collected by Git or 'gotadmin cleanup'; making the "
2758 "repository writable and running 'got update' will prevent this\n",
2759 getprogname());
2762 struct got_checkout_progress_arg {
2763 const char *worktree_path;
2764 int had_base_commit_ref_error;
2765 int verbosity;
2768 static const struct got_error *
2769 checkout_progress(void *arg, unsigned char status, const char *path)
2771 struct got_checkout_progress_arg *a = arg;
2773 /* Base commit bump happens silently. */
2774 if (status == GOT_STATUS_BUMP_BASE)
2775 return NULL;
2777 if (status == GOT_STATUS_BASE_REF_ERR) {
2778 a->had_base_commit_ref_error = 1;
2779 return NULL;
2782 while (path[0] == '/')
2783 path++;
2785 if (a->verbosity >= 0)
2786 printf("%c %s/%s\n", status, a->worktree_path, path);
2788 return NULL;
2791 static const struct got_error *
2792 check_cancelled(void *arg)
2794 if (sigint_received || sigpipe_received)
2795 return got_error(GOT_ERR_CANCELLED);
2796 return NULL;
2799 static const struct got_error *
2800 check_linear_ancestry(struct got_object_id *commit_id,
2801 struct got_object_id *base_commit_id, int allow_forwards_in_time_only,
2802 struct got_repository *repo)
2804 const struct got_error *err = NULL;
2805 struct got_object_id *yca_id;
2807 err = got_commit_graph_find_youngest_common_ancestor(&yca_id,
2808 commit_id, base_commit_id, 1, repo, check_cancelled, NULL);
2809 if (err)
2810 return err;
2812 if (yca_id == NULL)
2813 return got_error(GOT_ERR_ANCESTRY);
2816 * Require a straight line of history between the target commit
2817 * and the work tree's base commit.
2819 * Non-linear situations such as this require a rebase:
2821 * (commit) D F (base_commit)
2822 * \ /
2823 * C E
2824 * \ /
2825 * B (yca)
2826 * |
2827 * A
2829 * 'got update' only handles linear cases:
2830 * Update forwards in time: A (base/yca) - B - C - D (commit)
2831 * Update backwards in time: D (base) - C - B - A (commit/yca)
2833 if (allow_forwards_in_time_only) {
2834 if (got_object_id_cmp(base_commit_id, yca_id) != 0)
2835 return got_error(GOT_ERR_ANCESTRY);
2836 } else if (got_object_id_cmp(commit_id, yca_id) != 0 &&
2837 got_object_id_cmp(base_commit_id, yca_id) != 0)
2838 return got_error(GOT_ERR_ANCESTRY);
2840 free(yca_id);
2841 return NULL;
2844 static const struct got_error *
2845 check_same_branch(struct got_object_id *commit_id,
2846 struct got_reference *head_ref, struct got_object_id *yca_id,
2847 struct got_repository *repo)
2849 const struct got_error *err = NULL;
2850 struct got_commit_graph *graph = NULL;
2851 struct got_object_id *head_commit_id = NULL;
2852 int is_same_branch = 0;
2854 err = got_ref_resolve(&head_commit_id, repo, head_ref);
2855 if (err)
2856 goto done;
2858 if (got_object_id_cmp(head_commit_id, commit_id) == 0) {
2859 is_same_branch = 1;
2860 goto done;
2862 if (yca_id && got_object_id_cmp(commit_id, yca_id) == 0) {
2863 is_same_branch = 1;
2864 goto done;
2867 err = got_commit_graph_open(&graph, "/", 1);
2868 if (err)
2869 goto done;
2871 err = got_commit_graph_iter_start(graph, head_commit_id, repo,
2872 check_cancelled, NULL);
2873 if (err)
2874 goto done;
2876 for (;;) {
2877 struct got_object_id id;
2879 err = got_commit_graph_iter_next(&id, graph, repo,
2880 check_cancelled, NULL);
2881 if (err) {
2882 if (err->code == GOT_ERR_ITER_COMPLETED)
2883 err = NULL;
2884 break;
2887 if (yca_id && got_object_id_cmp(&id, yca_id) == 0)
2888 break;
2889 if (got_object_id_cmp(&id, commit_id) == 0) {
2890 is_same_branch = 1;
2891 break;
2894 done:
2895 if (graph)
2896 got_commit_graph_close(graph);
2897 free(head_commit_id);
2898 if (!err && !is_same_branch)
2899 err = got_error(GOT_ERR_ANCESTRY);
2900 return err;
2903 static const struct got_error *
2904 checkout_ancestry_error(struct got_reference *ref, const char *commit_id_str)
2906 static char msg[512];
2907 const char *branch_name;
2909 if (got_ref_is_symbolic(ref))
2910 branch_name = got_ref_get_symref_target(ref);
2911 else
2912 branch_name = got_ref_get_name(ref);
2914 if (strncmp("refs/heads/", branch_name, 11) == 0)
2915 branch_name += 11;
2917 snprintf(msg, sizeof(msg),
2918 "target commit is not contained in branch '%s'; "
2919 "the branch to use must be specified with -b; "
2920 "if necessary a new branch can be created for "
2921 "this commit with 'got branch -c %s BRANCH_NAME'",
2922 branch_name, commit_id_str);
2924 return got_error_msg(GOT_ERR_ANCESTRY, msg);
2927 static const struct got_error *
2928 cmd_checkout(int argc, char *argv[])
2930 const struct got_error *error = NULL;
2931 struct got_repository *repo = NULL;
2932 struct got_reference *head_ref = NULL, *ref = NULL;
2933 struct got_worktree *worktree = NULL;
2934 char *repo_path = NULL;
2935 char *worktree_path = NULL;
2936 const char *path_prefix = "";
2937 const char *branch_name = GOT_REF_HEAD, *refname = NULL;
2938 char *commit_id_str = NULL;
2939 struct got_object_id *commit_id = NULL;
2940 char *cwd = NULL;
2941 int ch, same_path_prefix, allow_nonempty = 0, verbosity = 0;
2942 struct got_pathlist_head paths;
2943 struct got_checkout_progress_arg cpa;
2944 int *pack_fds = NULL;
2946 TAILQ_INIT(&paths);
2948 while ((ch = getopt(argc, argv, "b:c:Ep:q")) != -1) {
2949 switch (ch) {
2950 case 'b':
2951 branch_name = optarg;
2952 break;
2953 case 'c':
2954 commit_id_str = strdup(optarg);
2955 if (commit_id_str == NULL)
2956 return got_error_from_errno("strdup");
2957 break;
2958 case 'E':
2959 allow_nonempty = 1;
2960 break;
2961 case 'p':
2962 path_prefix = optarg;
2963 break;
2964 case 'q':
2965 verbosity = -1;
2966 break;
2967 default:
2968 usage_checkout();
2969 /* NOTREACHED */
2973 argc -= optind;
2974 argv += optind;
2976 #ifndef PROFILE
2977 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
2978 "unveil", NULL) == -1)
2979 err(1, "pledge");
2980 #endif
2981 if (argc == 1) {
2982 char *base, *dotgit;
2983 const char *path;
2984 repo_path = realpath(argv[0], NULL);
2985 if (repo_path == NULL)
2986 return got_error_from_errno2("realpath", argv[0]);
2987 cwd = getcwd(NULL, 0);
2988 if (cwd == NULL) {
2989 error = got_error_from_errno("getcwd");
2990 goto done;
2992 if (path_prefix[0])
2993 path = path_prefix;
2994 else
2995 path = repo_path;
2996 error = got_path_basename(&base, path);
2997 if (error)
2998 goto done;
2999 dotgit = strstr(base, ".git");
3000 if (dotgit)
3001 *dotgit = '\0';
3002 if (asprintf(&worktree_path, "%s/%s", cwd, base) == -1) {
3003 error = got_error_from_errno("asprintf");
3004 free(base);
3005 goto done;
3007 free(base);
3008 } else if (argc == 2) {
3009 repo_path = realpath(argv[0], NULL);
3010 if (repo_path == NULL) {
3011 error = got_error_from_errno2("realpath", argv[0]);
3012 goto done;
3014 worktree_path = realpath(argv[1], NULL);
3015 if (worktree_path == NULL) {
3016 if (errno != ENOENT) {
3017 error = got_error_from_errno2("realpath",
3018 argv[1]);
3019 goto done;
3021 worktree_path = strdup(argv[1]);
3022 if (worktree_path == NULL) {
3023 error = got_error_from_errno("strdup");
3024 goto done;
3027 } else
3028 usage_checkout();
3030 got_path_strip_trailing_slashes(repo_path);
3031 got_path_strip_trailing_slashes(worktree_path);
3033 error = got_repo_pack_fds_open(&pack_fds);
3034 if (error != NULL)
3035 goto done;
3037 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
3038 if (error != NULL)
3039 goto done;
3041 /* Pre-create work tree path for unveil(2) */
3042 error = got_path_mkdir(worktree_path);
3043 if (error) {
3044 if (!(error->code == GOT_ERR_ERRNO && errno == EISDIR) &&
3045 !(error->code == GOT_ERR_ERRNO && errno == EEXIST))
3046 goto done;
3047 if (!allow_nonempty &&
3048 !got_path_dir_is_empty(worktree_path)) {
3049 error = got_error_path(worktree_path,
3050 GOT_ERR_DIR_NOT_EMPTY);
3051 goto done;
3055 error = apply_unveil(got_repo_get_path(repo), 0, worktree_path);
3056 if (error)
3057 goto done;
3059 error = got_ref_open(&head_ref, repo, branch_name, 0);
3060 if (error != NULL)
3061 goto done;
3063 error = got_worktree_init(worktree_path, head_ref, path_prefix, repo);
3064 if (error != NULL && !(error->code == GOT_ERR_ERRNO && errno == EEXIST))
3065 goto done;
3067 error = got_worktree_open(&worktree, worktree_path);
3068 if (error != NULL)
3069 goto done;
3071 error = got_worktree_match_path_prefix(&same_path_prefix, worktree,
3072 path_prefix);
3073 if (error != NULL)
3074 goto done;
3075 if (!same_path_prefix) {
3076 error = got_error(GOT_ERR_PATH_PREFIX);
3077 goto done;
3080 if (commit_id_str) {
3081 struct got_reflist_head refs;
3082 TAILQ_INIT(&refs);
3083 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
3084 NULL);
3085 if (error)
3086 goto done;
3087 error = got_repo_match_object_id(&commit_id, NULL,
3088 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
3089 got_ref_list_free(&refs);
3090 if (error)
3091 goto done;
3092 error = check_linear_ancestry(commit_id,
3093 got_worktree_get_base_commit_id(worktree), 0, repo);
3094 if (error != NULL) {
3095 if (error->code == GOT_ERR_ANCESTRY) {
3096 error = checkout_ancestry_error(
3097 head_ref, commit_id_str);
3099 goto done;
3101 error = check_same_branch(commit_id, head_ref, NULL, repo);
3102 if (error) {
3103 if (error->code == GOT_ERR_ANCESTRY) {
3104 error = checkout_ancestry_error(
3105 head_ref, commit_id_str);
3107 goto done;
3109 error = got_worktree_set_base_commit_id(worktree, repo,
3110 commit_id);
3111 if (error)
3112 goto done;
3113 /* Expand potentially abbreviated commit ID string. */
3114 free(commit_id_str);
3115 error = got_object_id_str(&commit_id_str, commit_id);
3116 if (error)
3117 goto done;
3118 } else {
3119 commit_id = got_object_id_dup(
3120 got_worktree_get_base_commit_id(worktree));
3121 if (commit_id == NULL) {
3122 error = got_error_from_errno("got_object_id_dup");
3123 goto done;
3125 error = got_object_id_str(&commit_id_str, commit_id);
3126 if (error)
3127 goto done;
3130 error = got_pathlist_append(&paths, "", NULL);
3131 if (error)
3132 goto done;
3133 cpa.worktree_path = worktree_path;
3134 cpa.had_base_commit_ref_error = 0;
3135 cpa.verbosity = verbosity;
3136 error = got_worktree_checkout_files(worktree, &paths, repo,
3137 checkout_progress, &cpa, check_cancelled, NULL);
3138 if (error != NULL)
3139 goto done;
3141 if (got_ref_is_symbolic(head_ref)) {
3142 error = got_ref_resolve_symbolic(&ref, repo, head_ref);
3143 if (error)
3144 goto done;
3145 refname = got_ref_get_name(ref);
3146 } else
3147 refname = got_ref_get_name(head_ref);
3148 printf("Checked out %s: %s\n", refname, commit_id_str);
3149 printf("Now shut up and hack\n");
3150 if (cpa.had_base_commit_ref_error)
3151 show_worktree_base_ref_warning();
3152 done:
3153 if (pack_fds) {
3154 const struct got_error *pack_err =
3155 got_repo_pack_fds_close(pack_fds);
3156 if (error == NULL)
3157 error = pack_err;
3159 if (head_ref)
3160 got_ref_close(head_ref);
3161 if (ref)
3162 got_ref_close(ref);
3163 got_pathlist_free(&paths, GOT_PATHLIST_FREE_NONE);
3164 free(commit_id_str);
3165 free(commit_id);
3166 free(repo_path);
3167 free(worktree_path);
3168 free(cwd);
3169 return error;
3172 struct got_update_progress_arg {
3173 int did_something;
3174 int conflicts;
3175 int obstructed;
3176 int not_updated;
3177 int missing;
3178 int not_deleted;
3179 int unversioned;
3180 int verbosity;
3183 static void
3184 print_update_progress_stats(struct got_update_progress_arg *upa)
3186 if (!upa->did_something)
3187 return;
3189 if (upa->conflicts > 0)
3190 printf("Files with new merge conflicts: %d\n", upa->conflicts);
3191 if (upa->obstructed > 0)
3192 printf("File paths obstructed by a non-regular file: %d\n",
3193 upa->obstructed);
3194 if (upa->not_updated > 0)
3195 printf("Files not updated because of existing merge "
3196 "conflicts: %d\n", upa->not_updated);
3200 * The meaning of some status codes differs between merge-style operations and
3201 * update operations. For example, the ! status code means "file was missing"
3202 * if changes were merged into the work tree, and "missing file was restored"
3203 * if the work tree was updated. This function should be used by any operation
3204 * which merges changes into the work tree without updating the work tree.
3206 static void
3207 print_merge_progress_stats(struct got_update_progress_arg *upa)
3209 if (!upa->did_something)
3210 return;
3212 if (upa->conflicts > 0)
3213 printf("Files with new merge conflicts: %d\n", upa->conflicts);
3214 if (upa->obstructed > 0)
3215 printf("File paths obstructed by a non-regular file: %d\n",
3216 upa->obstructed);
3217 if (upa->missing > 0)
3218 printf("Files which had incoming changes but could not be "
3219 "found in the work tree: %d\n", upa->missing);
3220 if (upa->not_deleted > 0)
3221 printf("Files not deleted due to differences in deleted "
3222 "content: %d\n", upa->not_deleted);
3223 if (upa->unversioned > 0)
3224 printf("Files not merged because an unversioned file was "
3225 "found in the work tree: %d\n", upa->unversioned);
3228 __dead static void
3229 usage_update(void)
3231 fprintf(stderr, "usage: %s update [-q] [-b branch] [-c commit] "
3232 "[path ...]\n", getprogname());
3233 exit(1);
3236 static const struct got_error *
3237 update_progress(void *arg, unsigned char status, const char *path)
3239 struct got_update_progress_arg *upa = arg;
3241 if (status == GOT_STATUS_EXISTS ||
3242 status == GOT_STATUS_BASE_REF_ERR)
3243 return NULL;
3245 upa->did_something = 1;
3247 /* Base commit bump happens silently. */
3248 if (status == GOT_STATUS_BUMP_BASE)
3249 return NULL;
3251 if (status == GOT_STATUS_CONFLICT)
3252 upa->conflicts++;
3253 if (status == GOT_STATUS_OBSTRUCTED)
3254 upa->obstructed++;
3255 if (status == GOT_STATUS_CANNOT_UPDATE)
3256 upa->not_updated++;
3257 if (status == GOT_STATUS_MISSING)
3258 upa->missing++;
3259 if (status == GOT_STATUS_CANNOT_DELETE)
3260 upa->not_deleted++;
3261 if (status == GOT_STATUS_UNVERSIONED)
3262 upa->unversioned++;
3264 while (path[0] == '/')
3265 path++;
3266 if (upa->verbosity >= 0)
3267 printf("%c %s\n", status, path);
3269 return NULL;
3272 static const struct got_error *
3273 switch_head_ref(struct got_reference *head_ref,
3274 struct got_object_id *commit_id, struct got_worktree *worktree,
3275 struct got_repository *repo)
3277 const struct got_error *err = NULL;
3278 char *base_id_str;
3279 int ref_has_moved = 0;
3281 /* Trivial case: switching between two different references. */
3282 if (strcmp(got_ref_get_name(head_ref),
3283 got_worktree_get_head_ref_name(worktree)) != 0) {
3284 printf("Switching work tree from %s to %s\n",
3285 got_worktree_get_head_ref_name(worktree),
3286 got_ref_get_name(head_ref));
3287 return got_worktree_set_head_ref(worktree, head_ref);
3290 err = check_linear_ancestry(commit_id,
3291 got_worktree_get_base_commit_id(worktree), 0, repo);
3292 if (err) {
3293 if (err->code != GOT_ERR_ANCESTRY)
3294 return err;
3295 ref_has_moved = 1;
3297 if (!ref_has_moved)
3298 return NULL;
3300 /* Switching to a rebased branch with the same reference name. */
3301 err = got_object_id_str(&base_id_str,
3302 got_worktree_get_base_commit_id(worktree));
3303 if (err)
3304 return err;
3305 printf("Reference %s now points at a different branch\n",
3306 got_worktree_get_head_ref_name(worktree));
3307 printf("Switching work tree from %s to %s\n", base_id_str,
3308 got_worktree_get_head_ref_name(worktree));
3309 return NULL;
3312 static const struct got_error *
3313 check_rebase_or_histedit_in_progress(struct got_worktree *worktree)
3315 const struct got_error *err;
3316 int in_progress;
3318 err = got_worktree_rebase_in_progress(&in_progress, worktree);
3319 if (err)
3320 return err;
3321 if (in_progress)
3322 return got_error(GOT_ERR_REBASING);
3324 err = got_worktree_histedit_in_progress(&in_progress, worktree);
3325 if (err)
3326 return err;
3327 if (in_progress)
3328 return got_error(GOT_ERR_HISTEDIT_BUSY);
3330 return NULL;
3333 static const struct got_error *
3334 check_merge_in_progress(struct got_worktree *worktree,
3335 struct got_repository *repo)
3337 const struct got_error *err;
3338 int in_progress;
3340 err = got_worktree_merge_in_progress(&in_progress, worktree, repo);
3341 if (err)
3342 return err;
3343 if (in_progress)
3344 return got_error(GOT_ERR_MERGE_BUSY);
3346 return NULL;
3349 static const struct got_error *
3350 get_worktree_paths_from_argv(struct got_pathlist_head *paths, int argc,
3351 char *argv[], struct got_worktree *worktree)
3353 const struct got_error *err = NULL;
3354 char *path;
3355 struct got_pathlist_entry *new;
3356 int i;
3358 if (argc == 0) {
3359 path = strdup("");
3360 if (path == NULL)
3361 return got_error_from_errno("strdup");
3362 return got_pathlist_append(paths, path, NULL);
3365 for (i = 0; i < argc; i++) {
3366 err = got_worktree_resolve_path(&path, worktree, argv[i]);
3367 if (err)
3368 break;
3369 err = got_pathlist_insert(&new, paths, path, NULL);
3370 if (err || new == NULL /* duplicate */) {
3371 free(path);
3372 if (err)
3373 break;
3377 return err;
3380 static const struct got_error *
3381 wrap_not_worktree_error(const struct got_error *orig_err,
3382 const char *cmdname, const char *path)
3384 const struct got_error *err;
3385 struct got_repository *repo;
3386 static char msg[512];
3387 int *pack_fds = NULL;
3389 err = got_repo_pack_fds_open(&pack_fds);
3390 if (err)
3391 return err;
3393 err = got_repo_open(&repo, path, NULL, pack_fds);
3394 if (err)
3395 return orig_err;
3397 snprintf(msg, sizeof(msg),
3398 "'got %s' needs a work tree in addition to a git repository\n"
3399 "Work trees can be checked out from this Git repository with "
3400 "'got checkout'.\n"
3401 "The got(1) manual page contains more information.", cmdname);
3402 err = got_error_msg(GOT_ERR_NOT_WORKTREE, msg);
3403 got_repo_close(repo);
3404 if (pack_fds) {
3405 const struct got_error *pack_err =
3406 got_repo_pack_fds_close(pack_fds);
3407 if (err == NULL)
3408 err = pack_err;
3410 return err;
3413 static const struct got_error *
3414 cmd_update(int argc, char *argv[])
3416 const struct got_error *error = NULL;
3417 struct got_repository *repo = NULL;
3418 struct got_worktree *worktree = NULL;
3419 char *worktree_path = NULL;
3420 struct got_object_id *commit_id = NULL;
3421 char *commit_id_str = NULL;
3422 const char *branch_name = NULL;
3423 struct got_reference *head_ref = NULL;
3424 struct got_pathlist_head paths;
3425 struct got_pathlist_entry *pe;
3426 int ch, verbosity = 0;
3427 struct got_update_progress_arg upa;
3428 int *pack_fds = NULL;
3430 TAILQ_INIT(&paths);
3432 while ((ch = getopt(argc, argv, "b:c:q")) != -1) {
3433 switch (ch) {
3434 case 'b':
3435 branch_name = optarg;
3436 break;
3437 case 'c':
3438 commit_id_str = strdup(optarg);
3439 if (commit_id_str == NULL)
3440 return got_error_from_errno("strdup");
3441 break;
3442 case 'q':
3443 verbosity = -1;
3444 break;
3445 default:
3446 usage_update();
3447 /* NOTREACHED */
3451 argc -= optind;
3452 argv += optind;
3454 #ifndef PROFILE
3455 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
3456 "unveil", NULL) == -1)
3457 err(1, "pledge");
3458 #endif
3459 worktree_path = getcwd(NULL, 0);
3460 if (worktree_path == NULL) {
3461 error = got_error_from_errno("getcwd");
3462 goto done;
3465 error = got_repo_pack_fds_open(&pack_fds);
3466 if (error != NULL)
3467 goto done;
3469 error = got_worktree_open(&worktree, worktree_path);
3470 if (error) {
3471 if (error->code == GOT_ERR_NOT_WORKTREE)
3472 error = wrap_not_worktree_error(error, "update",
3473 worktree_path);
3474 goto done;
3477 error = check_rebase_or_histedit_in_progress(worktree);
3478 if (error)
3479 goto done;
3481 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
3482 NULL, pack_fds);
3483 if (error != NULL)
3484 goto done;
3486 error = apply_unveil(got_repo_get_path(repo), 0,
3487 got_worktree_get_root_path(worktree));
3488 if (error)
3489 goto done;
3491 error = check_merge_in_progress(worktree, repo);
3492 if (error)
3493 goto done;
3495 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
3496 if (error)
3497 goto done;
3499 error = got_ref_open(&head_ref, repo, branch_name ? branch_name :
3500 got_worktree_get_head_ref_name(worktree), 0);
3501 if (error != NULL)
3502 goto done;
3503 if (commit_id_str == NULL) {
3504 error = got_ref_resolve(&commit_id, repo, head_ref);
3505 if (error != NULL)
3506 goto done;
3507 error = got_object_id_str(&commit_id_str, commit_id);
3508 if (error != NULL)
3509 goto done;
3510 } else {
3511 struct got_reflist_head refs;
3512 TAILQ_INIT(&refs);
3513 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
3514 NULL);
3515 if (error)
3516 goto done;
3517 error = got_repo_match_object_id(&commit_id, NULL,
3518 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
3519 got_ref_list_free(&refs);
3520 free(commit_id_str);
3521 commit_id_str = NULL;
3522 if (error)
3523 goto done;
3524 error = got_object_id_str(&commit_id_str, commit_id);
3525 if (error)
3526 goto done;
3529 if (branch_name) {
3530 struct got_object_id *head_commit_id;
3531 TAILQ_FOREACH(pe, &paths, entry) {
3532 if (pe->path_len == 0)
3533 continue;
3534 error = got_error_msg(GOT_ERR_BAD_PATH,
3535 "switching between branches requires that "
3536 "the entire work tree gets updated");
3537 goto done;
3539 error = got_ref_resolve(&head_commit_id, repo, head_ref);
3540 if (error)
3541 goto done;
3542 error = check_linear_ancestry(commit_id, head_commit_id, 0,
3543 repo);
3544 free(head_commit_id);
3545 if (error != NULL)
3546 goto done;
3547 error = check_same_branch(commit_id, head_ref, NULL, repo);
3548 if (error)
3549 goto done;
3550 error = switch_head_ref(head_ref, commit_id, worktree, repo);
3551 if (error)
3552 goto done;
3553 } else {
3554 error = check_linear_ancestry(commit_id,
3555 got_worktree_get_base_commit_id(worktree), 0, repo);
3556 if (error != NULL) {
3557 if (error->code == GOT_ERR_ANCESTRY)
3558 error = got_error(GOT_ERR_BRANCH_MOVED);
3559 goto done;
3561 error = check_same_branch(commit_id, head_ref, NULL, repo);
3562 if (error)
3563 goto done;
3566 if (got_object_id_cmp(got_worktree_get_base_commit_id(worktree),
3567 commit_id) != 0) {
3568 error = got_worktree_set_base_commit_id(worktree, repo,
3569 commit_id);
3570 if (error)
3571 goto done;
3574 memset(&upa, 0, sizeof(upa));
3575 upa.verbosity = verbosity;
3576 error = got_worktree_checkout_files(worktree, &paths, repo,
3577 update_progress, &upa, check_cancelled, NULL);
3578 if (error != NULL)
3579 goto done;
3581 if (upa.did_something) {
3582 printf("Updated to %s: %s\n",
3583 got_worktree_get_head_ref_name(worktree), commit_id_str);
3584 } else
3585 printf("Already up-to-date\n");
3587 print_update_progress_stats(&upa);
3588 done:
3589 if (pack_fds) {
3590 const struct got_error *pack_err =
3591 got_repo_pack_fds_close(pack_fds);
3592 if (error == NULL)
3593 error = pack_err;
3595 free(worktree_path);
3596 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
3597 free(commit_id);
3598 free(commit_id_str);
3599 return error;
3602 static const struct got_error *
3603 diff_blobs(struct got_object_id *blob_id1, struct got_object_id *blob_id2,
3604 const char *path, int diff_context, int ignore_whitespace,
3605 int force_text_diff, struct got_diffstat_cb_arg *dsa,
3606 struct got_repository *repo, FILE *outfile)
3608 const struct got_error *err = NULL;
3609 struct got_blob_object *blob1 = NULL, *blob2 = NULL;
3610 FILE *f1 = NULL, *f2 = NULL;
3611 int fd1 = -1, fd2 = -1;
3613 fd1 = got_opentempfd();
3614 if (fd1 == -1)
3615 return got_error_from_errno("got_opentempfd");
3616 fd2 = got_opentempfd();
3617 if (fd2 == -1) {
3618 err = got_error_from_errno("got_opentempfd");
3619 goto done;
3622 if (blob_id1) {
3623 err = got_object_open_as_blob(&blob1, repo, blob_id1, 8192,
3624 fd1);
3625 if (err)
3626 goto done;
3629 err = got_object_open_as_blob(&blob2, repo, blob_id2, 8192, fd2);
3630 if (err)
3631 goto done;
3633 f1 = got_opentemp();
3634 if (f1 == NULL) {
3635 err = got_error_from_errno("got_opentemp");
3636 goto done;
3638 f2 = got_opentemp();
3639 if (f2 == NULL) {
3640 err = got_error_from_errno("got_opentemp");
3641 goto done;
3644 while (path[0] == '/')
3645 path++;
3646 err = got_diff_blob(NULL, NULL, blob1, blob2, f1, f2, path, path,
3647 GOT_DIFF_ALGORITHM_PATIENCE, diff_context, ignore_whitespace,
3648 force_text_diff, dsa, outfile);
3649 done:
3650 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
3651 err = got_error_from_errno("close");
3652 if (blob1)
3653 got_object_blob_close(blob1);
3654 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
3655 err = got_error_from_errno("close");
3656 got_object_blob_close(blob2);
3657 if (f1 && fclose(f1) == EOF && err == NULL)
3658 err = got_error_from_errno("fclose");
3659 if (f2 && fclose(f2) == EOF && err == NULL)
3660 err = got_error_from_errno("fclose");
3661 return err;
3664 static const struct got_error *
3665 diff_trees(struct got_object_id *tree_id1, struct got_object_id *tree_id2,
3666 const char *path, int diff_context, int ignore_whitespace,
3667 int force_text_diff, struct got_diffstat_cb_arg *dsa,
3668 struct got_repository *repo, FILE *outfile)
3670 const struct got_error *err = NULL;
3671 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
3672 struct got_diff_blob_output_unidiff_arg arg;
3673 FILE *f1 = NULL, *f2 = NULL;
3674 int fd1 = -1, fd2 = -1;
3676 if (tree_id1) {
3677 err = got_object_open_as_tree(&tree1, repo, tree_id1);
3678 if (err)
3679 goto done;
3680 fd1 = got_opentempfd();
3681 if (fd1 == -1) {
3682 err = got_error_from_errno("got_opentempfd");
3683 goto done;
3687 err = got_object_open_as_tree(&tree2, repo, tree_id2);
3688 if (err)
3689 goto done;
3691 f1 = got_opentemp();
3692 if (f1 == NULL) {
3693 err = got_error_from_errno("got_opentemp");
3694 goto done;
3697 f2 = got_opentemp();
3698 if (f2 == NULL) {
3699 err = got_error_from_errno("got_opentemp");
3700 goto done;
3702 fd2 = got_opentempfd();
3703 if (fd2 == -1) {
3704 err = got_error_from_errno("got_opentempfd");
3705 goto done;
3707 arg.diff_context = diff_context;
3708 arg.ignore_whitespace = ignore_whitespace;
3709 arg.force_text_diff = force_text_diff;
3710 arg.diffstat = dsa;
3711 arg.diff_algo = GOT_DIFF_ALGORITHM_PATIENCE;
3712 arg.outfile = outfile;
3713 arg.lines = NULL;
3714 arg.nlines = 0;
3715 while (path[0] == '/')
3716 path++;
3717 err = got_diff_tree(tree1, tree2, f1, f2, fd1, fd2, path, path, repo,
3718 got_diff_blob_output_unidiff, &arg, 1);
3719 done:
3720 if (tree1)
3721 got_object_tree_close(tree1);
3722 if (tree2)
3723 got_object_tree_close(tree2);
3724 if (f1 && fclose(f1) == EOF && err == NULL)
3725 err = got_error_from_errno("fclose");
3726 if (f2 && fclose(f2) == EOF && err == NULL)
3727 err = got_error_from_errno("fclose");
3728 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
3729 err = got_error_from_errno("close");
3730 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
3731 err = got_error_from_errno("close");
3732 return err;
3735 static const struct got_error *
3736 get_changed_paths(struct got_pathlist_head *paths,
3737 struct got_commit_object *commit, struct got_repository *repo,
3738 struct got_diffstat_cb_arg *dsa)
3740 const struct got_error *err = NULL;
3741 struct got_object_id *tree_id1 = NULL, *tree_id2 = NULL;
3742 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
3743 struct got_object_qid *qid;
3744 got_diff_blob_cb cb = got_diff_tree_collect_changed_paths;
3745 FILE *f1 = NULL, *f2 = NULL;
3746 int fd1 = -1, fd2 = -1;
3748 if (dsa) {
3749 cb = got_diff_tree_compute_diffstat;
3751 f1 = got_opentemp();
3752 if (f1 == NULL) {
3753 err = got_error_from_errno("got_opentemp");
3754 goto done;
3756 f2 = got_opentemp();
3757 if (f2 == NULL) {
3758 err = got_error_from_errno("got_opentemp");
3759 goto done;
3761 fd1 = got_opentempfd();
3762 if (fd1 == -1) {
3763 err = got_error_from_errno("got_opentempfd");
3764 goto done;
3766 fd2 = got_opentempfd();
3767 if (fd2 == -1) {
3768 err = got_error_from_errno("got_opentempfd");
3769 goto done;
3773 qid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
3774 if (qid != NULL) {
3775 struct got_commit_object *pcommit;
3776 err = got_object_open_as_commit(&pcommit, repo,
3777 &qid->id);
3778 if (err)
3779 return err;
3781 tree_id1 = got_object_id_dup(
3782 got_object_commit_get_tree_id(pcommit));
3783 if (tree_id1 == NULL) {
3784 got_object_commit_close(pcommit);
3785 return got_error_from_errno("got_object_id_dup");
3787 got_object_commit_close(pcommit);
3791 if (tree_id1) {
3792 err = got_object_open_as_tree(&tree1, repo, tree_id1);
3793 if (err)
3794 goto done;
3797 tree_id2 = got_object_commit_get_tree_id(commit);
3798 err = got_object_open_as_tree(&tree2, repo, tree_id2);
3799 if (err)
3800 goto done;
3802 err = got_diff_tree(tree1, tree2, f1, f2, fd1, fd2, "", "", repo,
3803 cb, dsa ? (void *)dsa : paths, dsa ? 1 : 0);
3804 done:
3805 if (tree1)
3806 got_object_tree_close(tree1);
3807 if (tree2)
3808 got_object_tree_close(tree2);
3809 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
3810 err = got_error_from_errno("close");
3811 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
3812 err = got_error_from_errno("close");
3813 if (f1 && fclose(f1) == EOF && err == NULL)
3814 err = got_error_from_errno("fclose");
3815 if (f2 && fclose(f2) == EOF && err == NULL)
3816 err = got_error_from_errno("fclose");
3817 free(tree_id1);
3818 return err;
3821 static const struct got_error *
3822 print_patch(struct got_commit_object *commit, struct got_object_id *id,
3823 const char *path, int diff_context, struct got_diffstat_cb_arg *dsa,
3824 struct got_repository *repo, FILE *outfile)
3826 const struct got_error *err = NULL;
3827 struct got_commit_object *pcommit = NULL;
3828 char *id_str1 = NULL, *id_str2 = NULL;
3829 struct got_object_id *obj_id1 = NULL, *obj_id2 = NULL;
3830 struct got_object_qid *qid;
3832 qid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
3833 if (qid != NULL) {
3834 err = got_object_open_as_commit(&pcommit, repo,
3835 &qid->id);
3836 if (err)
3837 return err;
3838 err = got_object_id_str(&id_str1, &qid->id);
3839 if (err)
3840 goto done;
3843 err = got_object_id_str(&id_str2, id);
3844 if (err)
3845 goto done;
3847 if (path && path[0] != '\0') {
3848 int obj_type;
3849 err = got_object_id_by_path(&obj_id2, repo, commit, path);
3850 if (err)
3851 goto done;
3852 if (pcommit) {
3853 err = got_object_id_by_path(&obj_id1, repo,
3854 pcommit, path);
3855 if (err) {
3856 if (err->code != GOT_ERR_NO_TREE_ENTRY) {
3857 free(obj_id2);
3858 goto done;
3862 err = got_object_get_type(&obj_type, repo, obj_id2);
3863 if (err) {
3864 free(obj_id2);
3865 goto done;
3867 fprintf(outfile,
3868 "diff %s %s\n", id_str1 ? id_str1 : "/dev/null", id_str2);
3869 fprintf(outfile, "commit - %s\n",
3870 id_str1 ? id_str1 : "/dev/null");
3871 fprintf(outfile, "commit + %s\n", id_str2);
3872 switch (obj_type) {
3873 case GOT_OBJ_TYPE_BLOB:
3874 err = diff_blobs(obj_id1, obj_id2, path, diff_context,
3875 0, 0, dsa, repo, outfile);
3876 break;
3877 case GOT_OBJ_TYPE_TREE:
3878 err = diff_trees(obj_id1, obj_id2, path, diff_context,
3879 0, 0, dsa, repo, outfile);
3880 break;
3881 default:
3882 err = got_error(GOT_ERR_OBJ_TYPE);
3883 break;
3885 free(obj_id1);
3886 free(obj_id2);
3887 } else {
3888 obj_id2 = got_object_commit_get_tree_id(commit);
3889 if (pcommit)
3890 obj_id1 = got_object_commit_get_tree_id(pcommit);
3891 fprintf(outfile,
3892 "diff %s %s\n", id_str1 ? id_str1 : "/dev/null", id_str2);
3893 fprintf(outfile, "commit - %s\n",
3894 id_str1 ? id_str1 : "/dev/null");
3895 fprintf(outfile, "commit + %s\n", id_str2);
3896 err = diff_trees(obj_id1, obj_id2, "", diff_context, 0, 0,
3897 dsa, repo, outfile);
3899 done:
3900 free(id_str1);
3901 free(id_str2);
3902 if (pcommit)
3903 got_object_commit_close(pcommit);
3904 return err;
3907 static char *
3908 get_datestr(time_t *time, char *datebuf)
3910 struct tm mytm, *tm;
3911 char *p, *s;
3913 tm = gmtime_r(time, &mytm);
3914 if (tm == NULL)
3915 return NULL;
3916 s = asctime_r(tm, datebuf);
3917 if (s == NULL)
3918 return NULL;
3919 p = strchr(s, '\n');
3920 if (p)
3921 *p = '\0';
3922 return s;
3925 static const struct got_error *
3926 match_commit(int *have_match, struct got_object_id *id,
3927 struct got_commit_object *commit, regex_t *regex)
3929 const struct got_error *err = NULL;
3930 regmatch_t regmatch;
3931 char *id_str = NULL, *logmsg = NULL;
3933 *have_match = 0;
3935 err = got_object_id_str(&id_str, id);
3936 if (err)
3937 return err;
3939 err = got_object_commit_get_logmsg(&logmsg, commit);
3940 if (err)
3941 goto done;
3943 if (regexec(regex, got_object_commit_get_author(commit), 1,
3944 &regmatch, 0) == 0 ||
3945 regexec(regex, got_object_commit_get_committer(commit), 1,
3946 &regmatch, 0) == 0 ||
3947 regexec(regex, id_str, 1, &regmatch, 0) == 0 ||
3948 regexec(regex, logmsg, 1, &regmatch, 0) == 0)
3949 *have_match = 1;
3950 done:
3951 free(id_str);
3952 free(logmsg);
3953 return err;
3956 static void
3957 match_changed_paths(int *have_match, struct got_pathlist_head *changed_paths,
3958 regex_t *regex)
3960 regmatch_t regmatch;
3961 struct got_pathlist_entry *pe;
3963 *have_match = 0;
3965 TAILQ_FOREACH(pe, changed_paths, entry) {
3966 if (regexec(regex, pe->path, 1, &regmatch, 0) == 0) {
3967 *have_match = 1;
3968 break;
3973 static const struct got_error *
3974 match_patch(int *have_match, struct got_commit_object *commit,
3975 struct got_object_id *id, const char *path, int diff_context,
3976 struct got_repository *repo, regex_t *regex, FILE *f)
3978 const struct got_error *err = NULL;
3979 char *line = NULL;
3980 size_t linesize = 0;
3981 regmatch_t regmatch;
3983 *have_match = 0;
3985 err = got_opentemp_truncate(f);
3986 if (err)
3987 return err;
3989 err = print_patch(commit, id, path, diff_context, NULL, repo, f);
3990 if (err)
3991 goto done;
3993 if (fseeko(f, 0L, SEEK_SET) == -1) {
3994 err = got_error_from_errno("fseeko");
3995 goto done;
3998 while (getline(&line, &linesize, f) != -1) {
3999 if (regexec(regex, line, 1, &regmatch, 0) == 0) {
4000 *have_match = 1;
4001 break;
4004 done:
4005 free(line);
4006 return err;
4009 #define GOT_COMMIT_SEP_STR "-----------------------------------------------\n"
4011 static const struct got_error*
4012 build_refs_str(char **refs_str, struct got_reflist_head *refs,
4013 struct got_object_id *id, struct got_repository *repo,
4014 int local_only)
4016 static const struct got_error *err = NULL;
4017 struct got_reflist_entry *re;
4018 char *s;
4019 const char *name;
4021 *refs_str = NULL;
4023 TAILQ_FOREACH(re, refs, entry) {
4024 struct got_tag_object *tag = NULL;
4025 struct got_object_id *ref_id;
4026 int cmp;
4028 name = got_ref_get_name(re->ref);
4029 if (strcmp(name, GOT_REF_HEAD) == 0)
4030 continue;
4031 if (strncmp(name, "refs/", 5) == 0)
4032 name += 5;
4033 if (strncmp(name, "got/", 4) == 0)
4034 continue;
4035 if (strncmp(name, "heads/", 6) == 0)
4036 name += 6;
4037 if (strncmp(name, "remotes/", 8) == 0) {
4038 if (local_only)
4039 continue;
4040 name += 8;
4041 s = strstr(name, "/" GOT_REF_HEAD);
4042 if (s != NULL && s[strlen(s)] == '\0')
4043 continue;
4045 err = got_ref_resolve(&ref_id, repo, re->ref);
4046 if (err)
4047 break;
4048 if (strncmp(name, "tags/", 5) == 0) {
4049 err = got_object_open_as_tag(&tag, repo, ref_id);
4050 if (err) {
4051 if (err->code != GOT_ERR_OBJ_TYPE) {
4052 free(ref_id);
4053 break;
4055 /* Ref points at something other than a tag. */
4056 err = NULL;
4057 tag = NULL;
4060 cmp = got_object_id_cmp(tag ?
4061 got_object_tag_get_object_id(tag) : ref_id, id);
4062 free(ref_id);
4063 if (tag)
4064 got_object_tag_close(tag);
4065 if (cmp != 0)
4066 continue;
4067 s = *refs_str;
4068 if (asprintf(refs_str, "%s%s%s", s ? s : "",
4069 s ? ", " : "", name) == -1) {
4070 err = got_error_from_errno("asprintf");
4071 free(s);
4072 *refs_str = NULL;
4073 break;
4075 free(s);
4078 return err;
4081 static const struct got_error *
4082 print_commit_oneline(struct got_commit_object *commit, struct got_object_id *id,
4083 struct got_repository *repo, struct got_reflist_object_id_map *refs_idmap)
4085 const struct got_error *err = NULL;
4086 char *ref_str = NULL, *id_str = NULL, *logmsg0 = NULL;
4087 char *comma, *s, *nl;
4088 struct got_reflist_head *refs;
4089 char datebuf[12]; /* YYYY-MM-DD + SPACE + NUL */
4090 struct tm tm;
4091 time_t committer_time;
4093 refs = got_reflist_object_id_map_lookup(refs_idmap, id);
4094 if (refs) {
4095 err = build_refs_str(&ref_str, refs, id, repo, 1);
4096 if (err)
4097 return err;
4099 /* Display the first matching ref only. */
4100 if (ref_str && (comma = strchr(ref_str, ',')) != NULL)
4101 *comma = '\0';
4104 if (ref_str == NULL) {
4105 err = got_object_id_str(&id_str, id);
4106 if (err)
4107 return err;
4110 committer_time = got_object_commit_get_committer_time(commit);
4111 if (gmtime_r(&committer_time, &tm) == NULL) {
4112 err = got_error_from_errno("gmtime_r");
4113 goto done;
4115 if (strftime(datebuf, sizeof(datebuf), "%G-%m-%d ", &tm) == 0) {
4116 err = got_error(GOT_ERR_NO_SPACE);
4117 goto done;
4120 err = got_object_commit_get_logmsg(&logmsg0, commit);
4121 if (err)
4122 goto done;
4124 s = logmsg0;
4125 while (isspace((unsigned char)s[0]))
4126 s++;
4128 nl = strchr(s, '\n');
4129 if (nl) {
4130 *nl = '\0';
4133 if (ref_str)
4134 printf("%s%-7s %s\n", datebuf, ref_str, s);
4135 else
4136 printf("%s%.7s %s\n", datebuf, id_str, s);
4138 if (fflush(stdout) != 0 && err == NULL)
4139 err = got_error_from_errno("fflush");
4140 done:
4141 free(id_str);
4142 free(ref_str);
4143 free(logmsg0);
4144 return err;
4147 static const struct got_error *
4148 print_diffstat(struct got_diffstat_cb_arg *dsa, const char *header)
4150 struct got_pathlist_entry *pe;
4152 if (header != NULL)
4153 printf("%s\n", header);
4155 TAILQ_FOREACH(pe, dsa->paths, entry) {
4156 struct got_diff_changed_path *cp = pe->data;
4157 int pad = dsa->max_path_len - pe->path_len + 1;
4159 printf(" %c %s%*c | %*d+ %*d-\n", cp->status, pe->path, pad,
4160 ' ', dsa->add_cols + 1, cp->add, dsa->rm_cols + 1, cp->rm);
4162 printf("\n%d file%s changed, %d insertion%s(+), %d deletion%s(-)\n\n",
4163 dsa->nfiles, dsa->nfiles > 1 ? "s" : "", dsa->ins,
4164 dsa->ins != 1 ? "s" : "", dsa->del, dsa->del != 1 ? "s" : "");
4166 if (fflush(stdout) != 0)
4167 return got_error_from_errno("fflush");
4169 return NULL;
4172 static const struct got_error *
4173 printfile(FILE *f)
4175 char buf[8192];
4176 size_t r;
4178 if (fseeko(f, 0L, SEEK_SET) == -1)
4179 return got_error_from_errno("fseek");
4181 for (;;) {
4182 r = fread(buf, 1, sizeof(buf), f);
4183 if (r == 0) {
4184 if (ferror(f))
4185 return got_error_from_errno("fread");
4186 if (feof(f))
4187 break;
4189 if (fwrite(buf, 1, r, stdout) != r)
4190 return got_ferror(stdout, GOT_ERR_IO);
4193 return NULL;
4196 static const struct got_error *
4197 print_commit(struct got_commit_object *commit, struct got_object_id *id,
4198 struct got_repository *repo, const char *path,
4199 struct got_pathlist_head *changed_paths,
4200 struct got_diffstat_cb_arg *diffstat, int show_patch, int diff_context,
4201 struct got_reflist_object_id_map *refs_idmap, const char *custom_refs_str,
4202 const char *prefix)
4204 const struct got_error *err = NULL;
4205 FILE *f = NULL;
4206 char *id_str, *datestr, *logmsg0, *logmsg, *line;
4207 char datebuf[26];
4208 time_t committer_time;
4209 const char *author, *committer;
4210 char *refs_str = NULL;
4212 err = got_object_id_str(&id_str, id);
4213 if (err)
4214 return err;
4216 if (custom_refs_str == NULL) {
4217 struct got_reflist_head *refs;
4218 refs = got_reflist_object_id_map_lookup(refs_idmap, id);
4219 if (refs) {
4220 err = build_refs_str(&refs_str, refs, id, repo, 0);
4221 if (err)
4222 goto done;
4226 printf(GOT_COMMIT_SEP_STR);
4227 if (custom_refs_str)
4228 printf("%s %s (%s)\n", prefix ? prefix : "commit", id_str,
4229 custom_refs_str);
4230 else
4231 printf("%s %s%s%s%s\n", prefix ? prefix : "commit", id_str,
4232 refs_str ? " (" : "", refs_str ? refs_str : "",
4233 refs_str ? ")" : "");
4234 free(id_str);
4235 id_str = NULL;
4236 free(refs_str);
4237 refs_str = NULL;
4238 printf("from: %s\n", got_object_commit_get_author(commit));
4239 author = got_object_commit_get_author(commit);
4240 committer = got_object_commit_get_committer(commit);
4241 if (strcmp(author, committer) != 0)
4242 printf("via: %s\n", committer);
4243 committer_time = got_object_commit_get_committer_time(commit);
4244 datestr = get_datestr(&committer_time, datebuf);
4245 if (datestr)
4246 printf("date: %s UTC\n", datestr);
4247 if (got_object_commit_get_nparents(commit) > 1) {
4248 const struct got_object_id_queue *parent_ids;
4249 struct got_object_qid *qid;
4250 int n = 1;
4251 parent_ids = got_object_commit_get_parent_ids(commit);
4252 STAILQ_FOREACH(qid, parent_ids, entry) {
4253 err = got_object_id_str(&id_str, &qid->id);
4254 if (err)
4255 goto done;
4256 printf("parent %d: %s\n", n++, id_str);
4257 free(id_str);
4258 id_str = NULL;
4262 err = got_object_commit_get_logmsg(&logmsg0, commit);
4263 if (err)
4264 goto done;
4266 logmsg = logmsg0;
4267 do {
4268 line = strsep(&logmsg, "\n");
4269 if (line)
4270 printf(" %s\n", line);
4271 } while (line);
4272 free(logmsg0);
4274 if (changed_paths && diffstat == NULL) {
4275 struct got_pathlist_entry *pe;
4277 TAILQ_FOREACH(pe, changed_paths, entry) {
4278 struct got_diff_changed_path *cp = pe->data;
4280 printf(" %c %s\n", cp->status, pe->path);
4282 printf("\n");
4284 if (show_patch) {
4285 if (diffstat) {
4286 f = got_opentemp();
4287 if (f == NULL) {
4288 err = got_error_from_errno("got_opentemp");
4289 goto done;
4293 err = print_patch(commit, id, path, diff_context, diffstat,
4294 repo, diffstat == NULL ? stdout : f);
4295 if (err)
4296 goto done;
4298 if (diffstat) {
4299 err = print_diffstat(diffstat, NULL);
4300 if (err)
4301 goto done;
4302 if (show_patch) {
4303 err = printfile(f);
4304 if (err)
4305 goto done;
4308 if (show_patch)
4309 printf("\n");
4311 if (fflush(stdout) != 0 && err == NULL)
4312 err = got_error_from_errno("fflush");
4313 done:
4314 if (f && fclose(f) == EOF && err == NULL)
4315 err = got_error_from_errno("fclose");
4316 free(id_str);
4317 free(refs_str);
4318 return err;
4321 static const struct got_error *
4322 print_commits(struct got_object_id *root_id, struct got_object_id *end_id,
4323 struct got_repository *repo, const char *path, int show_changed_paths,
4324 int show_diffstat, int show_patch, const char *search_pattern,
4325 int diff_context, int limit, int log_branches, int reverse_display_order,
4326 struct got_reflist_object_id_map *refs_idmap, int one_line,
4327 FILE *tmpfile)
4329 const struct got_error *err;
4330 struct got_commit_graph *graph;
4331 regex_t regex;
4332 int have_match;
4333 struct got_object_id_queue reversed_commits;
4334 struct got_object_qid *qid;
4335 struct got_commit_object *commit;
4336 struct got_pathlist_head changed_paths;
4338 STAILQ_INIT(&reversed_commits);
4339 TAILQ_INIT(&changed_paths);
4341 if (search_pattern && regcomp(&regex, search_pattern,
4342 REG_EXTENDED | REG_NOSUB | REG_NEWLINE))
4343 return got_error_msg(GOT_ERR_REGEX, search_pattern);
4345 err = got_commit_graph_open(&graph, path, !log_branches);
4346 if (err)
4347 return err;
4348 err = got_commit_graph_iter_start(graph, root_id, repo,
4349 check_cancelled, NULL);
4350 if (err)
4351 goto done;
4352 for (;;) {
4353 struct got_object_id id;
4354 struct got_diffstat_cb_arg dsa = { 0, 0, 0, 0, 0, 0,
4355 &changed_paths, 0, 0, GOT_DIFF_ALGORITHM_PATIENCE };
4357 if (sigint_received || sigpipe_received)
4358 break;
4360 err = got_commit_graph_iter_next(&id, graph, repo,
4361 check_cancelled, NULL);
4362 if (err) {
4363 if (err->code == GOT_ERR_ITER_COMPLETED)
4364 err = NULL;
4365 break;
4368 err = got_object_open_as_commit(&commit, repo, &id);
4369 if (err)
4370 break;
4372 if ((show_changed_paths || (show_diffstat && !show_patch))
4373 && !reverse_display_order) {
4374 err = get_changed_paths(&changed_paths, commit, repo,
4375 show_diffstat ? &dsa : NULL);
4376 if (err)
4377 break;
4380 if (search_pattern) {
4381 err = match_commit(&have_match, &id, commit, &regex);
4382 if (err) {
4383 got_object_commit_close(commit);
4384 break;
4386 if (have_match == 0 && show_changed_paths)
4387 match_changed_paths(&have_match,
4388 &changed_paths, &regex);
4389 if (have_match == 0 && show_patch) {
4390 err = match_patch(&have_match, commit, &id,
4391 path, diff_context, repo, &regex, tmpfile);
4392 if (err)
4393 break;
4395 if (have_match == 0) {
4396 got_object_commit_close(commit);
4397 got_pathlist_free(&changed_paths,
4398 GOT_PATHLIST_FREE_ALL);
4399 continue;
4403 if (reverse_display_order) {
4404 err = got_object_qid_alloc(&qid, &id);
4405 if (err)
4406 break;
4407 STAILQ_INSERT_HEAD(&reversed_commits, qid, entry);
4408 got_object_commit_close(commit);
4409 } else {
4410 if (one_line)
4411 err = print_commit_oneline(commit, &id,
4412 repo, refs_idmap);
4413 else
4414 err = print_commit(commit, &id, repo, path,
4415 (show_changed_paths || show_diffstat) ?
4416 &changed_paths : NULL,
4417 show_diffstat ? &dsa : NULL, show_patch,
4418 diff_context, refs_idmap, NULL, NULL);
4419 got_object_commit_close(commit);
4420 if (err)
4421 break;
4423 if ((limit && --limit == 0) ||
4424 (end_id && got_object_id_cmp(&id, end_id) == 0))
4425 break;
4427 got_pathlist_free(&changed_paths, GOT_PATHLIST_FREE_ALL);
4429 if (reverse_display_order) {
4430 STAILQ_FOREACH(qid, &reversed_commits, entry) {
4431 struct got_diffstat_cb_arg dsa = { 0, 0, 0, 0, 0, 0,
4432 &changed_paths, 0, 0, GOT_DIFF_ALGORITHM_PATIENCE };
4434 err = got_object_open_as_commit(&commit, repo,
4435 &qid->id);
4436 if (err)
4437 break;
4438 if (show_changed_paths ||
4439 (show_diffstat && !show_patch)) {
4440 err = get_changed_paths(&changed_paths, commit,
4441 repo, show_diffstat ? &dsa : NULL);
4442 if (err)
4443 break;
4445 if (one_line)
4446 err = print_commit_oneline(commit, &qid->id,
4447 repo, refs_idmap);
4448 else
4449 err = print_commit(commit, &qid->id, repo, path,
4450 (show_changed_paths || show_diffstat) ?
4451 &changed_paths : NULL,
4452 show_diffstat ? &dsa : NULL, show_patch,
4453 diff_context, refs_idmap, NULL, NULL);
4454 got_object_commit_close(commit);
4455 if (err)
4456 break;
4457 got_pathlist_free(&changed_paths, GOT_PATHLIST_FREE_ALL);
4460 done:
4461 while (!STAILQ_EMPTY(&reversed_commits)) {
4462 qid = STAILQ_FIRST(&reversed_commits);
4463 STAILQ_REMOVE_HEAD(&reversed_commits, entry);
4464 got_object_qid_free(qid);
4466 got_pathlist_free(&changed_paths, GOT_PATHLIST_FREE_ALL);
4467 if (search_pattern)
4468 regfree(&regex);
4469 got_commit_graph_close(graph);
4470 return err;
4473 __dead static void
4474 usage_log(void)
4476 fprintf(stderr, "usage: %s log [-bdPpRs] [-C number] [-c commit] "
4477 "[-l N] [-r repository-path] [-S search-pattern] [-x commit] "
4478 "[path]\n", getprogname());
4479 exit(1);
4482 static int
4483 get_default_log_limit(void)
4485 const char *got_default_log_limit;
4486 long long n;
4487 const char *errstr;
4489 got_default_log_limit = getenv("GOT_LOG_DEFAULT_LIMIT");
4490 if (got_default_log_limit == NULL)
4491 return 0;
4492 n = strtonum(got_default_log_limit, 0, INT_MAX, &errstr);
4493 if (errstr != NULL)
4494 return 0;
4495 return n;
4498 static const struct got_error *
4499 cmd_log(int argc, char *argv[])
4501 const struct got_error *error;
4502 struct got_repository *repo = NULL;
4503 struct got_worktree *worktree = NULL;
4504 struct got_object_id *start_id = NULL, *end_id = NULL;
4505 char *repo_path = NULL, *path = NULL, *cwd = NULL, *in_repo_path = NULL;
4506 const char *start_commit = NULL, *end_commit = NULL;
4507 const char *search_pattern = NULL;
4508 int diff_context = -1, ch;
4509 int show_changed_paths = 0, show_patch = 0, limit = 0, log_branches = 0;
4510 int show_diffstat = 0, reverse_display_order = 0, one_line = 0;
4511 const char *errstr;
4512 struct got_reflist_head refs;
4513 struct got_reflist_object_id_map *refs_idmap = NULL;
4514 FILE *tmpfile = NULL;
4515 int *pack_fds = NULL;
4517 TAILQ_INIT(&refs);
4519 #ifndef PROFILE
4520 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
4521 NULL)
4522 == -1)
4523 err(1, "pledge");
4524 #endif
4526 limit = get_default_log_limit();
4528 while ((ch = getopt(argc, argv, "bC:c:dl:PpRr:S:sx:")) != -1) {
4529 switch (ch) {
4530 case 'b':
4531 log_branches = 1;
4532 break;
4533 case 'C':
4534 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
4535 &errstr);
4536 if (errstr != NULL)
4537 errx(1, "number of context lines is %s: %s",
4538 errstr, optarg);
4539 break;
4540 case 'c':
4541 start_commit = optarg;
4542 break;
4543 case 'd':
4544 show_diffstat = 1;
4545 break;
4546 case 'l':
4547 limit = strtonum(optarg, 0, INT_MAX, &errstr);
4548 if (errstr != NULL)
4549 errx(1, "number of commits is %s: %s",
4550 errstr, optarg);
4551 break;
4552 case 'P':
4553 show_changed_paths = 1;
4554 break;
4555 case 'p':
4556 show_patch = 1;
4557 break;
4558 case 'R':
4559 reverse_display_order = 1;
4560 break;
4561 case 'r':
4562 repo_path = realpath(optarg, NULL);
4563 if (repo_path == NULL)
4564 return got_error_from_errno2("realpath",
4565 optarg);
4566 got_path_strip_trailing_slashes(repo_path);
4567 break;
4568 case 'S':
4569 search_pattern = optarg;
4570 break;
4571 case 's':
4572 one_line = 1;
4573 break;
4574 case 'x':
4575 end_commit = optarg;
4576 break;
4577 default:
4578 usage_log();
4579 /* NOTREACHED */
4583 argc -= optind;
4584 argv += optind;
4586 if (diff_context == -1)
4587 diff_context = 3;
4588 else if (!show_patch)
4589 errx(1, "-C requires -p");
4591 if (one_line && (show_patch || show_changed_paths || show_diffstat))
4592 errx(1, "cannot use -s with -d, -p or -P");
4594 cwd = getcwd(NULL, 0);
4595 if (cwd == NULL) {
4596 error = got_error_from_errno("getcwd");
4597 goto done;
4600 error = got_repo_pack_fds_open(&pack_fds);
4601 if (error != NULL)
4602 goto done;
4604 if (repo_path == NULL) {
4605 error = got_worktree_open(&worktree, cwd);
4606 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4607 goto done;
4608 error = NULL;
4611 if (argc == 1) {
4612 if (worktree) {
4613 error = got_worktree_resolve_path(&path, worktree,
4614 argv[0]);
4615 if (error)
4616 goto done;
4617 } else {
4618 path = strdup(argv[0]);
4619 if (path == NULL) {
4620 error = got_error_from_errno("strdup");
4621 goto done;
4624 } else if (argc != 0)
4625 usage_log();
4627 if (repo_path == NULL) {
4628 repo_path = worktree ?
4629 strdup(got_worktree_get_repo_path(worktree)) : strdup(cwd);
4631 if (repo_path == NULL) {
4632 error = got_error_from_errno("strdup");
4633 goto done;
4636 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
4637 if (error != NULL)
4638 goto done;
4640 error = apply_unveil(got_repo_get_path(repo), 1,
4641 worktree ? got_worktree_get_root_path(worktree) : NULL);
4642 if (error)
4643 goto done;
4645 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
4646 if (error)
4647 goto done;
4649 error = got_reflist_object_id_map_create(&refs_idmap, &refs, repo);
4650 if (error)
4651 goto done;
4653 if (start_commit == NULL) {
4654 struct got_reference *head_ref;
4655 struct got_commit_object *commit = NULL;
4656 error = got_ref_open(&head_ref, repo,
4657 worktree ? got_worktree_get_head_ref_name(worktree)
4658 : GOT_REF_HEAD, 0);
4659 if (error != NULL)
4660 goto done;
4661 error = got_ref_resolve(&start_id, repo, head_ref);
4662 got_ref_close(head_ref);
4663 if (error != NULL)
4664 goto done;
4665 error = got_object_open_as_commit(&commit, repo,
4666 start_id);
4667 if (error != NULL)
4668 goto done;
4669 got_object_commit_close(commit);
4670 } else {
4671 error = got_repo_match_object_id(&start_id, NULL,
4672 start_commit, GOT_OBJ_TYPE_COMMIT, &refs, repo);
4673 if (error != NULL)
4674 goto done;
4676 if (end_commit != NULL) {
4677 error = got_repo_match_object_id(&end_id, NULL,
4678 end_commit, GOT_OBJ_TYPE_COMMIT, &refs, repo);
4679 if (error != NULL)
4680 goto done;
4683 if (worktree) {
4685 * If a path was specified on the command line it was resolved
4686 * to a path in the work tree above. Prepend the work tree's
4687 * path prefix to obtain the corresponding in-repository path.
4689 if (path) {
4690 const char *prefix;
4691 prefix = got_worktree_get_path_prefix(worktree);
4692 if (asprintf(&in_repo_path, "%s%s%s", prefix,
4693 (path[0] != '\0') ? "/" : "", path) == -1) {
4694 error = got_error_from_errno("asprintf");
4695 goto done;
4698 } else
4699 error = got_repo_map_path(&in_repo_path, repo,
4700 path ? path : "");
4701 if (error != NULL)
4702 goto done;
4703 if (in_repo_path) {
4704 free(path);
4705 path = in_repo_path;
4708 if (worktree) {
4709 /* Release work tree lock. */
4710 got_worktree_close(worktree);
4711 worktree = NULL;
4714 if (search_pattern && show_patch) {
4715 tmpfile = got_opentemp();
4716 if (tmpfile == NULL) {
4717 error = got_error_from_errno("got_opentemp");
4718 goto done;
4722 error = print_commits(start_id, end_id, repo, path ? path : "",
4723 show_changed_paths, show_diffstat, show_patch, search_pattern,
4724 diff_context, limit, log_branches, reverse_display_order,
4725 refs_idmap, one_line, tmpfile);
4726 done:
4727 free(path);
4728 free(repo_path);
4729 free(cwd);
4730 if (worktree)
4731 got_worktree_close(worktree);
4732 if (repo) {
4733 const struct got_error *close_err = got_repo_close(repo);
4734 if (error == NULL)
4735 error = close_err;
4737 if (pack_fds) {
4738 const struct got_error *pack_err =
4739 got_repo_pack_fds_close(pack_fds);
4740 if (error == NULL)
4741 error = pack_err;
4743 if (refs_idmap)
4744 got_reflist_object_id_map_free(refs_idmap);
4745 if (tmpfile && fclose(tmpfile) == EOF && error == NULL)
4746 error = got_error_from_errno("fclose");
4747 got_ref_list_free(&refs);
4748 return error;
4751 __dead static void
4752 usage_diff(void)
4754 fprintf(stderr, "usage: %s diff [-adPsw] [-C number] [-c commit] "
4755 "[-r repository-path] [object1 object2 | path ...]\n",
4756 getprogname());
4757 exit(1);
4760 struct print_diff_arg {
4761 struct got_repository *repo;
4762 struct got_worktree *worktree;
4763 struct got_diffstat_cb_arg *diffstat;
4764 int diff_context;
4765 const char *id_str;
4766 int header_shown;
4767 int diff_staged;
4768 enum got_diff_algorithm diff_algo;
4769 int ignore_whitespace;
4770 int force_text_diff;
4771 FILE *f1;
4772 FILE *f2;
4773 FILE *outfile;
4777 * Create a file which contains the target path of a symlink so we can feed
4778 * it as content to the diff engine.
4780 static const struct got_error *
4781 get_symlink_target_file(int *fd, int dirfd, const char *de_name,
4782 const char *abspath)
4784 const struct got_error *err = NULL;
4785 char target_path[PATH_MAX];
4786 ssize_t target_len, outlen;
4788 *fd = -1;
4790 if (dirfd != -1) {
4791 target_len = readlinkat(dirfd, de_name, target_path, PATH_MAX);
4792 if (target_len == -1)
4793 return got_error_from_errno2("readlinkat", abspath);
4794 } else {
4795 target_len = readlink(abspath, target_path, PATH_MAX);
4796 if (target_len == -1)
4797 return got_error_from_errno2("readlink", abspath);
4800 *fd = got_opentempfd();
4801 if (*fd == -1)
4802 return got_error_from_errno("got_opentempfd");
4804 outlen = write(*fd, target_path, target_len);
4805 if (outlen == -1) {
4806 err = got_error_from_errno("got_opentempfd");
4807 goto done;
4810 if (lseek(*fd, 0, SEEK_SET) == -1) {
4811 err = got_error_from_errno2("lseek", abspath);
4812 goto done;
4814 done:
4815 if (err) {
4816 close(*fd);
4817 *fd = -1;
4819 return err;
4822 static const struct got_error *
4823 print_diff(void *arg, unsigned char status, unsigned char staged_status,
4824 const char *path, struct got_object_id *blob_id,
4825 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
4826 int dirfd, const char *de_name)
4828 struct print_diff_arg *a = arg;
4829 const struct got_error *err = NULL;
4830 struct got_blob_object *blob1 = NULL;
4831 int fd = -1, fd1 = -1, fd2 = -1;
4832 FILE *f2 = NULL;
4833 char *abspath = NULL, *label1 = NULL;
4834 struct stat sb;
4835 off_t size1 = 0;
4836 int f2_exists = 0;
4838 memset(&sb, 0, sizeof(sb));
4840 if (a->diff_staged) {
4841 if (staged_status != GOT_STATUS_MODIFY &&
4842 staged_status != GOT_STATUS_ADD &&
4843 staged_status != GOT_STATUS_DELETE)
4844 return NULL;
4845 } else {
4846 if (staged_status == GOT_STATUS_DELETE)
4847 return NULL;
4848 if (status == GOT_STATUS_NONEXISTENT)
4849 return got_error_set_errno(ENOENT, path);
4850 if (status != GOT_STATUS_MODIFY &&
4851 status != GOT_STATUS_ADD &&
4852 status != GOT_STATUS_DELETE &&
4853 status != GOT_STATUS_CONFLICT)
4854 return NULL;
4857 err = got_opentemp_truncate(a->f1);
4858 if (err)
4859 return got_error_from_errno("got_opentemp_truncate");
4860 err = got_opentemp_truncate(a->f2);
4861 if (err)
4862 return got_error_from_errno("got_opentemp_truncate");
4864 if (!a->header_shown) {
4865 if (fprintf(a->outfile, "diff %s%s\n",
4866 a->diff_staged ? "-s " : "",
4867 got_worktree_get_root_path(a->worktree)) < 0) {
4868 err = got_error_from_errno("fprintf");
4869 goto done;
4871 if (fprintf(a->outfile, "commit - %s\n", a->id_str) < 0) {
4872 err = got_error_from_errno("fprintf");
4873 goto done;
4875 if (fprintf(a->outfile, "path + %s%s\n",
4876 got_worktree_get_root_path(a->worktree),
4877 a->diff_staged ? " (staged changes)" : "") < 0) {
4878 err = got_error_from_errno("fprintf");
4879 goto done;
4881 a->header_shown = 1;
4884 if (a->diff_staged) {
4885 const char *label1 = NULL, *label2 = NULL;
4886 switch (staged_status) {
4887 case GOT_STATUS_MODIFY:
4888 label1 = path;
4889 label2 = path;
4890 break;
4891 case GOT_STATUS_ADD:
4892 label2 = path;
4893 break;
4894 case GOT_STATUS_DELETE:
4895 label1 = path;
4896 break;
4897 default:
4898 return got_error(GOT_ERR_FILE_STATUS);
4900 fd1 = got_opentempfd();
4901 if (fd1 == -1) {
4902 err = got_error_from_errno("got_opentempfd");
4903 goto done;
4905 fd2 = got_opentempfd();
4906 if (fd2 == -1) {
4907 err = got_error_from_errno("got_opentempfd");
4908 goto done;
4910 err = got_diff_objects_as_blobs(NULL, NULL, a->f1, a->f2,
4911 fd1, fd2, blob_id, staged_blob_id, label1, label2,
4912 a->diff_algo, a->diff_context, a->ignore_whitespace,
4913 a->force_text_diff, a->diffstat, a->repo, a->outfile);
4914 goto done;
4917 fd1 = got_opentempfd();
4918 if (fd1 == -1) {
4919 err = got_error_from_errno("got_opentempfd");
4920 goto done;
4923 if (staged_status == GOT_STATUS_ADD ||
4924 staged_status == GOT_STATUS_MODIFY) {
4925 char *id_str;
4926 err = got_object_open_as_blob(&blob1, a->repo, staged_blob_id,
4927 8192, fd1);
4928 if (err)
4929 goto done;
4930 err = got_object_id_str(&id_str, staged_blob_id);
4931 if (err)
4932 goto done;
4933 if (asprintf(&label1, "%s (staged)", id_str) == -1) {
4934 err = got_error_from_errno("asprintf");
4935 free(id_str);
4936 goto done;
4938 free(id_str);
4939 } else if (status != GOT_STATUS_ADD) {
4940 err = got_object_open_as_blob(&blob1, a->repo, blob_id, 8192,
4941 fd1);
4942 if (err)
4943 goto done;
4946 if (status != GOT_STATUS_DELETE) {
4947 if (asprintf(&abspath, "%s/%s",
4948 got_worktree_get_root_path(a->worktree), path) == -1) {
4949 err = got_error_from_errno("asprintf");
4950 goto done;
4953 if (dirfd != -1) {
4954 fd = openat(dirfd, de_name,
4955 O_RDONLY | O_NOFOLLOW | O_CLOEXEC);
4956 if (fd == -1) {
4957 if (!got_err_open_nofollow_on_symlink()) {
4958 err = got_error_from_errno2("openat",
4959 abspath);
4960 goto done;
4962 err = get_symlink_target_file(&fd, dirfd,
4963 de_name, abspath);
4964 if (err)
4965 goto done;
4967 } else {
4968 fd = open(abspath, O_RDONLY | O_NOFOLLOW | O_CLOEXEC);
4969 if (fd == -1) {
4970 if (!got_err_open_nofollow_on_symlink()) {
4971 err = got_error_from_errno2("open",
4972 abspath);
4973 goto done;
4975 err = get_symlink_target_file(&fd, dirfd,
4976 de_name, abspath);
4977 if (err)
4978 goto done;
4981 if (fstatat(fd, abspath, &sb, AT_SYMLINK_NOFOLLOW) == -1) {
4982 err = got_error_from_errno2("fstatat", abspath);
4983 goto done;
4985 f2 = fdopen(fd, "r");
4986 if (f2 == NULL) {
4987 err = got_error_from_errno2("fdopen", abspath);
4988 goto done;
4990 fd = -1;
4991 f2_exists = 1;
4994 if (blob1) {
4995 err = got_object_blob_dump_to_file(&size1, NULL, NULL,
4996 a->f1, blob1);
4997 if (err)
4998 goto done;
5001 err = got_diff_blob_file(blob1, a->f1, size1, label1, f2 ? f2 : a->f2,
5002 f2_exists, &sb, path, GOT_DIFF_ALGORITHM_PATIENCE, a->diff_context,
5003 a->ignore_whitespace, a->force_text_diff, a->diffstat, a->outfile);
5004 done:
5005 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
5006 err = got_error_from_errno("close");
5007 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
5008 err = got_error_from_errno("close");
5009 if (blob1)
5010 got_object_blob_close(blob1);
5011 if (fd != -1 && close(fd) == -1 && err == NULL)
5012 err = got_error_from_errno("close");
5013 if (f2 && fclose(f2) == EOF && err == NULL)
5014 err = got_error_from_errno("fclose");
5015 free(abspath);
5016 return err;
5019 static const struct got_error *
5020 cmd_diff(int argc, char *argv[])
5022 const struct got_error *error;
5023 struct got_repository *repo = NULL;
5024 struct got_worktree *worktree = NULL;
5025 char *cwd = NULL, *repo_path = NULL;
5026 const char *commit_args[2] = { NULL, NULL };
5027 int ncommit_args = 0;
5028 struct got_object_id *ids[2] = { NULL, NULL };
5029 char *labels[2] = { NULL, NULL };
5030 int type1 = GOT_OBJ_TYPE_ANY, type2 = GOT_OBJ_TYPE_ANY;
5031 int diff_context = 3, diff_staged = 0, ignore_whitespace = 0, ch, i;
5032 int force_text_diff = 0, force_path = 0, rflag = 0, show_diffstat = 0;
5033 const char *errstr;
5034 struct got_reflist_head refs;
5035 struct got_pathlist_head diffstat_paths, paths;
5036 FILE *f1 = NULL, *f2 = NULL, *outfile = NULL;
5037 int fd1 = -1, fd2 = -1;
5038 int *pack_fds = NULL;
5039 struct got_diffstat_cb_arg dsa;
5041 memset(&dsa, 0, sizeof(dsa));
5043 TAILQ_INIT(&refs);
5044 TAILQ_INIT(&paths);
5045 TAILQ_INIT(&diffstat_paths);
5047 #ifndef PROFILE
5048 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
5049 NULL) == -1)
5050 err(1, "pledge");
5051 #endif
5053 while ((ch = getopt(argc, argv, "aC:c:dPr:sw")) != -1) {
5054 switch (ch) {
5055 case 'a':
5056 force_text_diff = 1;
5057 break;
5058 case 'C':
5059 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
5060 &errstr);
5061 if (errstr != NULL)
5062 errx(1, "number of context lines is %s: %s",
5063 errstr, optarg);
5064 break;
5065 case 'c':
5066 if (ncommit_args >= 2)
5067 errx(1, "too many -c options used");
5068 commit_args[ncommit_args++] = optarg;
5069 break;
5070 case 'd':
5071 show_diffstat = 1;
5072 break;
5073 case 'P':
5074 force_path = 1;
5075 break;
5076 case 'r':
5077 repo_path = realpath(optarg, NULL);
5078 if (repo_path == NULL)
5079 return got_error_from_errno2("realpath",
5080 optarg);
5081 got_path_strip_trailing_slashes(repo_path);
5082 rflag = 1;
5083 break;
5084 case 's':
5085 diff_staged = 1;
5086 break;
5087 case 'w':
5088 ignore_whitespace = 1;
5089 break;
5090 default:
5091 usage_diff();
5092 /* NOTREACHED */
5096 argc -= optind;
5097 argv += optind;
5099 cwd = getcwd(NULL, 0);
5100 if (cwd == NULL) {
5101 error = got_error_from_errno("getcwd");
5102 goto done;
5105 error = got_repo_pack_fds_open(&pack_fds);
5106 if (error != NULL)
5107 goto done;
5109 if (repo_path == NULL) {
5110 error = got_worktree_open(&worktree, cwd);
5111 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5112 goto done;
5113 else
5114 error = NULL;
5115 if (worktree) {
5116 repo_path =
5117 strdup(got_worktree_get_repo_path(worktree));
5118 if (repo_path == NULL) {
5119 error = got_error_from_errno("strdup");
5120 goto done;
5122 } else {
5123 repo_path = strdup(cwd);
5124 if (repo_path == NULL) {
5125 error = got_error_from_errno("strdup");
5126 goto done;
5131 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
5132 free(repo_path);
5133 if (error != NULL)
5134 goto done;
5136 if (show_diffstat) {
5137 dsa.paths = &diffstat_paths;
5138 dsa.force_text = force_text_diff;
5139 dsa.ignore_ws = ignore_whitespace;
5140 dsa.diff_algo = GOT_DIFF_ALGORITHM_PATIENCE;
5143 if (rflag || worktree == NULL || ncommit_args > 0) {
5144 if (force_path) {
5145 error = got_error_msg(GOT_ERR_NOT_IMPL,
5146 "-P option can only be used when diffing "
5147 "a work tree");
5148 goto done;
5150 if (diff_staged) {
5151 error = got_error_msg(GOT_ERR_NOT_IMPL,
5152 "-s option can only be used when diffing "
5153 "a work tree");
5154 goto done;
5158 error = apply_unveil(got_repo_get_path(repo), 1,
5159 worktree ? got_worktree_get_root_path(worktree) : NULL);
5160 if (error)
5161 goto done;
5163 if ((!force_path && argc == 2) || ncommit_args > 0) {
5164 int obj_type = (ncommit_args > 0 ?
5165 GOT_OBJ_TYPE_COMMIT : GOT_OBJ_TYPE_ANY);
5166 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
5167 NULL);
5168 if (error)
5169 goto done;
5170 for (i = 0; i < (ncommit_args > 0 ? ncommit_args : argc); i++) {
5171 const char *arg;
5172 if (ncommit_args > 0)
5173 arg = commit_args[i];
5174 else
5175 arg = argv[i];
5176 error = got_repo_match_object_id(&ids[i], &labels[i],
5177 arg, obj_type, &refs, repo);
5178 if (error) {
5179 if (error->code != GOT_ERR_NOT_REF &&
5180 error->code != GOT_ERR_NO_OBJ)
5181 goto done;
5182 if (ncommit_args > 0)
5183 goto done;
5184 error = NULL;
5185 break;
5190 f1 = got_opentemp();
5191 if (f1 == NULL) {
5192 error = got_error_from_errno("got_opentemp");
5193 goto done;
5196 f2 = got_opentemp();
5197 if (f2 == NULL) {
5198 error = got_error_from_errno("got_opentemp");
5199 goto done;
5202 outfile = got_opentemp();
5203 if (outfile == NULL) {
5204 error = got_error_from_errno("got_opentemp");
5205 goto done;
5208 if (ncommit_args == 0 && (ids[0] == NULL || ids[1] == NULL)) {
5209 struct print_diff_arg arg;
5210 char *id_str;
5212 if (worktree == NULL) {
5213 if (argc == 2 && ids[0] == NULL) {
5214 error = got_error_path(argv[0], GOT_ERR_NO_OBJ);
5215 goto done;
5216 } else if (argc == 2 && ids[1] == NULL) {
5217 error = got_error_path(argv[1], GOT_ERR_NO_OBJ);
5218 goto done;
5219 } else if (argc > 0) {
5220 error = got_error_fmt(GOT_ERR_NOT_WORKTREE,
5221 "%s", "specified paths cannot be resolved");
5222 goto done;
5223 } else {
5224 error = got_error(GOT_ERR_NOT_WORKTREE);
5225 goto done;
5229 error = get_worktree_paths_from_argv(&paths, argc, argv,
5230 worktree);
5231 if (error)
5232 goto done;
5234 error = got_object_id_str(&id_str,
5235 got_worktree_get_base_commit_id(worktree));
5236 if (error)
5237 goto done;
5238 arg.repo = repo;
5239 arg.worktree = worktree;
5240 arg.diff_algo = GOT_DIFF_ALGORITHM_PATIENCE;
5241 arg.diff_context = diff_context;
5242 arg.id_str = id_str;
5243 arg.header_shown = 0;
5244 arg.diff_staged = diff_staged;
5245 arg.ignore_whitespace = ignore_whitespace;
5246 arg.force_text_diff = force_text_diff;
5247 arg.diffstat = show_diffstat ? &dsa : NULL;
5248 arg.f1 = f1;
5249 arg.f2 = f2;
5250 arg.outfile = outfile;
5252 error = got_worktree_status(worktree, &paths, repo, 0,
5253 print_diff, &arg, check_cancelled, NULL);
5254 free(id_str);
5255 if (error)
5256 goto done;
5258 if (show_diffstat && dsa.nfiles > 0) {
5259 char *header;
5261 if (asprintf(&header, "diffstat %s%s",
5262 diff_staged ? "-s " : "",
5263 got_worktree_get_root_path(worktree)) == -1) {
5264 error = got_error_from_errno("asprintf");
5265 goto done;
5268 error = print_diffstat(&dsa, header);
5269 free(header);
5270 if (error)
5271 goto done;
5274 error = printfile(outfile);
5275 goto done;
5278 if (ncommit_args == 1) {
5279 struct got_commit_object *commit;
5280 error = got_object_open_as_commit(&commit, repo, ids[0]);
5281 if (error)
5282 goto done;
5284 labels[1] = labels[0];
5285 ids[1] = ids[0];
5286 if (got_object_commit_get_nparents(commit) > 0) {
5287 const struct got_object_id_queue *pids;
5288 struct got_object_qid *pid;
5289 pids = got_object_commit_get_parent_ids(commit);
5290 pid = STAILQ_FIRST(pids);
5291 ids[0] = got_object_id_dup(&pid->id);
5292 if (ids[0] == NULL) {
5293 error = got_error_from_errno(
5294 "got_object_id_dup");
5295 got_object_commit_close(commit);
5296 goto done;
5298 error = got_object_id_str(&labels[0], ids[0]);
5299 if (error) {
5300 got_object_commit_close(commit);
5301 goto done;
5303 } else {
5304 ids[0] = NULL;
5305 labels[0] = strdup("/dev/null");
5306 if (labels[0] == NULL) {
5307 error = got_error_from_errno("strdup");
5308 got_object_commit_close(commit);
5309 goto done;
5313 got_object_commit_close(commit);
5316 if (ncommit_args == 0 && argc > 2) {
5317 error = got_error_msg(GOT_ERR_BAD_PATH,
5318 "path arguments cannot be used when diffing two objects");
5319 goto done;
5322 if (ids[0]) {
5323 error = got_object_get_type(&type1, repo, ids[0]);
5324 if (error)
5325 goto done;
5328 error = got_object_get_type(&type2, repo, ids[1]);
5329 if (error)
5330 goto done;
5331 if (type1 != GOT_OBJ_TYPE_ANY && type1 != type2) {
5332 error = got_error(GOT_ERR_OBJ_TYPE);
5333 goto done;
5335 if (type1 == GOT_OBJ_TYPE_BLOB && argc > 2) {
5336 error = got_error_msg(GOT_ERR_OBJ_TYPE,
5337 "path arguments cannot be used when diffing blobs");
5338 goto done;
5341 for (i = 0; ncommit_args > 0 && i < argc; i++) {
5342 char *in_repo_path;
5343 struct got_pathlist_entry *new;
5344 if (worktree) {
5345 const char *prefix;
5346 char *p;
5347 error = got_worktree_resolve_path(&p, worktree,
5348 argv[i]);
5349 if (error)
5350 goto done;
5351 prefix = got_worktree_get_path_prefix(worktree);
5352 while (prefix[0] == '/')
5353 prefix++;
5354 if (asprintf(&in_repo_path, "%s%s%s", prefix,
5355 (p[0] != '\0' && prefix[0] != '\0') ? "/" : "",
5356 p) == -1) {
5357 error = got_error_from_errno("asprintf");
5358 free(p);
5359 goto done;
5361 free(p);
5362 } else {
5363 char *mapped_path, *s;
5364 error = got_repo_map_path(&mapped_path, repo, argv[i]);
5365 if (error)
5366 goto done;
5367 s = mapped_path;
5368 while (s[0] == '/')
5369 s++;
5370 in_repo_path = strdup(s);
5371 if (in_repo_path == NULL) {
5372 error = got_error_from_errno("asprintf");
5373 free(mapped_path);
5374 goto done;
5376 free(mapped_path);
5379 error = got_pathlist_insert(&new, &paths, in_repo_path, NULL);
5380 if (error || new == NULL /* duplicate */)
5381 free(in_repo_path);
5382 if (error)
5383 goto done;
5386 if (worktree) {
5387 /* Release work tree lock. */
5388 got_worktree_close(worktree);
5389 worktree = NULL;
5392 fd1 = got_opentempfd();
5393 if (fd1 == -1) {
5394 error = got_error_from_errno("got_opentempfd");
5395 goto done;
5398 fd2 = got_opentempfd();
5399 if (fd2 == -1) {
5400 error = got_error_from_errno("got_opentempfd");
5401 goto done;
5404 switch (type1 == GOT_OBJ_TYPE_ANY ? type2 : type1) {
5405 case GOT_OBJ_TYPE_BLOB:
5406 error = got_diff_objects_as_blobs(NULL, NULL, f1, f2,
5407 fd1, fd2, ids[0], ids[1], NULL, NULL,
5408 GOT_DIFF_ALGORITHM_PATIENCE, diff_context,
5409 ignore_whitespace, force_text_diff,
5410 show_diffstat ? &dsa : NULL, repo, outfile);
5411 break;
5412 case GOT_OBJ_TYPE_TREE:
5413 error = got_diff_objects_as_trees(NULL, NULL, f1, f2, fd1, fd2,
5414 ids[0], ids[1], &paths, "", "",
5415 GOT_DIFF_ALGORITHM_PATIENCE, diff_context,
5416 ignore_whitespace, force_text_diff,
5417 show_diffstat ? &dsa : NULL, repo, outfile);
5418 break;
5419 case GOT_OBJ_TYPE_COMMIT:
5420 fprintf(outfile, "diff %s %s\n", labels[0], labels[1]);
5421 error = got_diff_objects_as_commits(NULL, NULL, f1, f2,
5422 fd1, fd2, ids[0], ids[1], &paths,
5423 GOT_DIFF_ALGORITHM_PATIENCE, diff_context,
5424 ignore_whitespace, force_text_diff,
5425 show_diffstat ? &dsa : NULL, repo, outfile);
5426 break;
5427 default:
5428 error = got_error(GOT_ERR_OBJ_TYPE);
5430 if (error)
5431 goto done;
5433 if (show_diffstat && dsa.nfiles > 0) {
5434 char *header = NULL;
5436 if (asprintf(&header, "diffstat %s %s",
5437 labels[0], labels[1]) == -1) {
5438 error = got_error_from_errno("asprintf");
5439 goto done;
5442 error = print_diffstat(&dsa, header);
5443 free(header);
5444 if (error)
5445 goto done;
5448 error = printfile(outfile);
5450 done:
5451 free(labels[0]);
5452 free(labels[1]);
5453 free(ids[0]);
5454 free(ids[1]);
5455 if (worktree)
5456 got_worktree_close(worktree);
5457 if (repo) {
5458 const struct got_error *close_err = got_repo_close(repo);
5459 if (error == NULL)
5460 error = close_err;
5462 if (pack_fds) {
5463 const struct got_error *pack_err =
5464 got_repo_pack_fds_close(pack_fds);
5465 if (error == NULL)
5466 error = pack_err;
5468 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
5469 got_pathlist_free(&diffstat_paths, GOT_PATHLIST_FREE_ALL);
5470 got_ref_list_free(&refs);
5471 if (outfile && fclose(outfile) == EOF && error == NULL)
5472 error = got_error_from_errno("fclose");
5473 if (f1 && fclose(f1) == EOF && error == NULL)
5474 error = got_error_from_errno("fclose");
5475 if (f2 && fclose(f2) == EOF && error == NULL)
5476 error = got_error_from_errno("fclose");
5477 if (fd1 != -1 && close(fd1) == -1 && error == NULL)
5478 error = got_error_from_errno("close");
5479 if (fd2 != -1 && close(fd2) == -1 && error == NULL)
5480 error = got_error_from_errno("close");
5481 return error;
5484 __dead static void
5485 usage_blame(void)
5487 fprintf(stderr,
5488 "usage: %s blame [-c commit] [-r repository-path] path\n",
5489 getprogname());
5490 exit(1);
5493 struct blame_line {
5494 int annotated;
5495 char *id_str;
5496 char *committer;
5497 char datebuf[11]; /* YYYY-MM-DD + NUL */
5500 struct blame_cb_args {
5501 struct blame_line *lines;
5502 int nlines;
5503 int nlines_prec;
5504 int lineno_cur;
5505 off_t *line_offsets;
5506 FILE *f;
5507 struct got_repository *repo;
5510 static const struct got_error *
5511 blame_cb(void *arg, int nlines, int lineno,
5512 struct got_commit_object *commit, struct got_object_id *id)
5514 const struct got_error *err = NULL;
5515 struct blame_cb_args *a = arg;
5516 struct blame_line *bline;
5517 char *line = NULL;
5518 size_t linesize = 0;
5519 off_t offset;
5520 struct tm tm;
5521 time_t committer_time;
5523 if (nlines != a->nlines ||
5524 (lineno != -1 && lineno < 1) || lineno > a->nlines)
5525 return got_error(GOT_ERR_RANGE);
5527 if (sigint_received)
5528 return got_error(GOT_ERR_ITER_COMPLETED);
5530 if (lineno == -1)
5531 return NULL; /* no change in this commit */
5533 /* Annotate this line. */
5534 bline = &a->lines[lineno - 1];
5535 if (bline->annotated)
5536 return NULL;
5537 err = got_object_id_str(&bline->id_str, id);
5538 if (err)
5539 return err;
5541 bline->committer = strdup(got_object_commit_get_committer(commit));
5542 if (bline->committer == NULL) {
5543 err = got_error_from_errno("strdup");
5544 goto done;
5547 committer_time = got_object_commit_get_committer_time(commit);
5548 if (gmtime_r(&committer_time, &tm) == NULL)
5549 return got_error_from_errno("gmtime_r");
5550 if (strftime(bline->datebuf, sizeof(bline->datebuf), "%G-%m-%d",
5551 &tm) == 0) {
5552 err = got_error(GOT_ERR_NO_SPACE);
5553 goto done;
5555 bline->annotated = 1;
5557 /* Print lines annotated so far. */
5558 bline = &a->lines[a->lineno_cur - 1];
5559 if (!bline->annotated)
5560 goto done;
5562 offset = a->line_offsets[a->lineno_cur - 1];
5563 if (fseeko(a->f, offset, SEEK_SET) == -1) {
5564 err = got_error_from_errno("fseeko");
5565 goto done;
5568 while (a->lineno_cur <= a->nlines && bline->annotated) {
5569 char *smallerthan, *at, *nl, *committer;
5570 size_t len;
5572 if (getline(&line, &linesize, a->f) == -1) {
5573 if (ferror(a->f))
5574 err = got_error_from_errno("getline");
5575 break;
5578 committer = bline->committer;
5579 smallerthan = strchr(committer, '<');
5580 if (smallerthan && smallerthan[1] != '\0')
5581 committer = smallerthan + 1;
5582 at = strchr(committer, '@');
5583 if (at)
5584 *at = '\0';
5585 len = strlen(committer);
5586 if (len >= 9)
5587 committer[8] = '\0';
5589 nl = strchr(line, '\n');
5590 if (nl)
5591 *nl = '\0';
5592 printf("%.*d) %.8s %s %-8s %s\n", a->nlines_prec, a->lineno_cur,
5593 bline->id_str, bline->datebuf, committer, line);
5595 a->lineno_cur++;
5596 bline = &a->lines[a->lineno_cur - 1];
5598 done:
5599 free(line);
5600 return err;
5603 static const struct got_error *
5604 cmd_blame(int argc, char *argv[])
5606 const struct got_error *error;
5607 struct got_repository *repo = NULL;
5608 struct got_worktree *worktree = NULL;
5609 char *path, *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
5610 char *link_target = NULL;
5611 struct got_object_id *obj_id = NULL;
5612 struct got_object_id *commit_id = NULL;
5613 struct got_commit_object *commit = NULL;
5614 struct got_blob_object *blob = NULL;
5615 char *commit_id_str = NULL;
5616 struct blame_cb_args bca;
5617 int ch, obj_type, i, fd1 = -1, fd2 = -1, fd3 = -1;
5618 off_t filesize;
5619 int *pack_fds = NULL;
5620 FILE *f1 = NULL, *f2 = NULL;
5622 fd1 = got_opentempfd();
5623 if (fd1 == -1)
5624 return got_error_from_errno("got_opentempfd");
5626 memset(&bca, 0, sizeof(bca));
5628 #ifndef PROFILE
5629 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
5630 NULL) == -1)
5631 err(1, "pledge");
5632 #endif
5634 while ((ch = getopt(argc, argv, "c:r:")) != -1) {
5635 switch (ch) {
5636 case 'c':
5637 commit_id_str = optarg;
5638 break;
5639 case 'r':
5640 repo_path = realpath(optarg, NULL);
5641 if (repo_path == NULL)
5642 return got_error_from_errno2("realpath",
5643 optarg);
5644 got_path_strip_trailing_slashes(repo_path);
5645 break;
5646 default:
5647 usage_blame();
5648 /* NOTREACHED */
5652 argc -= optind;
5653 argv += optind;
5655 if (argc == 1)
5656 path = argv[0];
5657 else
5658 usage_blame();
5660 cwd = getcwd(NULL, 0);
5661 if (cwd == NULL) {
5662 error = got_error_from_errno("getcwd");
5663 goto done;
5666 error = got_repo_pack_fds_open(&pack_fds);
5667 if (error != NULL)
5668 goto done;
5670 if (repo_path == NULL) {
5671 error = got_worktree_open(&worktree, cwd);
5672 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5673 goto done;
5674 else
5675 error = NULL;
5676 if (worktree) {
5677 repo_path =
5678 strdup(got_worktree_get_repo_path(worktree));
5679 if (repo_path == NULL) {
5680 error = got_error_from_errno("strdup");
5681 if (error)
5682 goto done;
5684 } else {
5685 repo_path = strdup(cwd);
5686 if (repo_path == NULL) {
5687 error = got_error_from_errno("strdup");
5688 goto done;
5693 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
5694 if (error != NULL)
5695 goto done;
5697 if (worktree) {
5698 const char *prefix = got_worktree_get_path_prefix(worktree);
5699 char *p;
5701 error = got_worktree_resolve_path(&p, worktree, path);
5702 if (error)
5703 goto done;
5704 if (asprintf(&in_repo_path, "%s%s%s", prefix,
5705 (p[0] != '\0' && !got_path_is_root_dir(prefix)) ? "/" : "",
5706 p) == -1) {
5707 error = got_error_from_errno("asprintf");
5708 free(p);
5709 goto done;
5711 free(p);
5712 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5713 } else {
5714 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5715 if (error)
5716 goto done;
5717 error = got_repo_map_path(&in_repo_path, repo, path);
5719 if (error)
5720 goto done;
5722 if (commit_id_str == NULL) {
5723 struct got_reference *head_ref;
5724 error = got_ref_open(&head_ref, repo, worktree ?
5725 got_worktree_get_head_ref_name(worktree) : GOT_REF_HEAD, 0);
5726 if (error != NULL)
5727 goto done;
5728 error = got_ref_resolve(&commit_id, repo, head_ref);
5729 got_ref_close(head_ref);
5730 if (error != NULL)
5731 goto done;
5732 } else {
5733 struct got_reflist_head refs;
5734 TAILQ_INIT(&refs);
5735 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
5736 NULL);
5737 if (error)
5738 goto done;
5739 error = got_repo_match_object_id(&commit_id, NULL,
5740 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
5741 got_ref_list_free(&refs);
5742 if (error)
5743 goto done;
5746 if (worktree) {
5747 /* Release work tree lock. */
5748 got_worktree_close(worktree);
5749 worktree = NULL;
5752 error = got_object_open_as_commit(&commit, repo, commit_id);
5753 if (error)
5754 goto done;
5756 error = got_object_resolve_symlinks(&link_target, in_repo_path,
5757 commit, repo);
5758 if (error)
5759 goto done;
5761 error = got_object_id_by_path(&obj_id, repo, commit,
5762 link_target ? link_target : in_repo_path);
5763 if (error)
5764 goto done;
5766 error = got_object_get_type(&obj_type, repo, obj_id);
5767 if (error)
5768 goto done;
5770 if (obj_type != GOT_OBJ_TYPE_BLOB) {
5771 error = got_error_path(link_target ? link_target : in_repo_path,
5772 GOT_ERR_OBJ_TYPE);
5773 goto done;
5776 error = got_object_open_as_blob(&blob, repo, obj_id, 8192, fd1);
5777 if (error)
5778 goto done;
5779 bca.f = got_opentemp();
5780 if (bca.f == NULL) {
5781 error = got_error_from_errno("got_opentemp");
5782 goto done;
5784 error = got_object_blob_dump_to_file(&filesize, &bca.nlines,
5785 &bca.line_offsets, bca.f, blob);
5786 if (error || bca.nlines == 0)
5787 goto done;
5789 /* Don't include \n at EOF in the blame line count. */
5790 if (bca.line_offsets[bca.nlines - 1] == filesize)
5791 bca.nlines--;
5793 bca.lines = calloc(bca.nlines, sizeof(*bca.lines));
5794 if (bca.lines == NULL) {
5795 error = got_error_from_errno("calloc");
5796 goto done;
5798 bca.lineno_cur = 1;
5799 bca.nlines_prec = 0;
5800 i = bca.nlines;
5801 while (i > 0) {
5802 i /= 10;
5803 bca.nlines_prec++;
5805 bca.repo = repo;
5807 fd2 = got_opentempfd();
5808 if (fd2 == -1) {
5809 error = got_error_from_errno("got_opentempfd");
5810 goto done;
5812 fd3 = got_opentempfd();
5813 if (fd3 == -1) {
5814 error = got_error_from_errno("got_opentempfd");
5815 goto done;
5817 f1 = got_opentemp();
5818 if (f1 == NULL) {
5819 error = got_error_from_errno("got_opentemp");
5820 goto done;
5822 f2 = got_opentemp();
5823 if (f2 == NULL) {
5824 error = got_error_from_errno("got_opentemp");
5825 goto done;
5827 error = got_blame(link_target ? link_target : in_repo_path, commit_id,
5828 repo, GOT_DIFF_ALGORITHM_PATIENCE, blame_cb, &bca,
5829 check_cancelled, NULL, fd2, fd3, f1, f2);
5830 done:
5831 free(in_repo_path);
5832 free(link_target);
5833 free(repo_path);
5834 free(cwd);
5835 free(commit_id);
5836 free(obj_id);
5837 if (commit)
5838 got_object_commit_close(commit);
5840 if (fd1 != -1 && close(fd1) == -1 && error == NULL)
5841 error = got_error_from_errno("close");
5842 if (fd2 != -1 && close(fd2) == -1 && error == NULL)
5843 error = got_error_from_errno("close");
5844 if (fd3 != -1 && close(fd3) == -1 && error == NULL)
5845 error = got_error_from_errno("close");
5846 if (f1 && fclose(f1) == EOF && error == NULL)
5847 error = got_error_from_errno("fclose");
5848 if (f2 && fclose(f2) == EOF && error == NULL)
5849 error = got_error_from_errno("fclose");
5851 if (blob)
5852 got_object_blob_close(blob);
5853 if (worktree)
5854 got_worktree_close(worktree);
5855 if (repo) {
5856 const struct got_error *close_err = got_repo_close(repo);
5857 if (error == NULL)
5858 error = close_err;
5860 if (pack_fds) {
5861 const struct got_error *pack_err =
5862 got_repo_pack_fds_close(pack_fds);
5863 if (error == NULL)
5864 error = pack_err;
5866 if (bca.lines) {
5867 for (i = 0; i < bca.nlines; i++) {
5868 struct blame_line *bline = &bca.lines[i];
5869 free(bline->id_str);
5870 free(bline->committer);
5872 free(bca.lines);
5874 free(bca.line_offsets);
5875 if (bca.f && fclose(bca.f) == EOF && error == NULL)
5876 error = got_error_from_errno("fclose");
5877 return error;
5880 __dead static void
5881 usage_tree(void)
5883 fprintf(stderr, "usage: %s tree [-iR] [-c commit] [-r repository-path] "
5884 "[path]\n", getprogname());
5885 exit(1);
5888 static const struct got_error *
5889 print_entry(struct got_tree_entry *te, const char *id, const char *path,
5890 const char *root_path, struct got_repository *repo)
5892 const struct got_error *err = NULL;
5893 int is_root_path = (strcmp(path, root_path) == 0);
5894 const char *modestr = "";
5895 mode_t mode = got_tree_entry_get_mode(te);
5896 char *link_target = NULL;
5898 path += strlen(root_path);
5899 while (path[0] == '/')
5900 path++;
5902 if (got_object_tree_entry_is_submodule(te))
5903 modestr = "$";
5904 else if (S_ISLNK(mode)) {
5905 int i;
5907 err = got_tree_entry_get_symlink_target(&link_target, te, repo);
5908 if (err)
5909 return err;
5910 for (i = 0; i < strlen(link_target); i++) {
5911 if (!isprint((unsigned char)link_target[i]))
5912 link_target[i] = '?';
5915 modestr = "@";
5917 else if (S_ISDIR(mode))
5918 modestr = "/";
5919 else if (mode & S_IXUSR)
5920 modestr = "*";
5922 printf("%s%s%s%s%s%s%s\n", id ? id : "", path,
5923 is_root_path ? "" : "/", got_tree_entry_get_name(te), modestr,
5924 link_target ? " -> ": "", link_target ? link_target : "");
5926 free(link_target);
5927 return NULL;
5930 static const struct got_error *
5931 print_tree(const char *path, struct got_commit_object *commit,
5932 int show_ids, int recurse, const char *root_path,
5933 struct got_repository *repo)
5935 const struct got_error *err = NULL;
5936 struct got_object_id *tree_id = NULL;
5937 struct got_tree_object *tree = NULL;
5938 int nentries, i;
5940 err = got_object_id_by_path(&tree_id, repo, commit, path);
5941 if (err)
5942 goto done;
5944 err = got_object_open_as_tree(&tree, repo, tree_id);
5945 if (err)
5946 goto done;
5947 nentries = got_object_tree_get_nentries(tree);
5948 for (i = 0; i < nentries; i++) {
5949 struct got_tree_entry *te;
5950 char *id = NULL;
5952 if (sigint_received || sigpipe_received)
5953 break;
5955 te = got_object_tree_get_entry(tree, i);
5956 if (show_ids) {
5957 char *id_str;
5958 err = got_object_id_str(&id_str,
5959 got_tree_entry_get_id(te));
5960 if (err)
5961 goto done;
5962 if (asprintf(&id, "%s ", id_str) == -1) {
5963 err = got_error_from_errno("asprintf");
5964 free(id_str);
5965 goto done;
5967 free(id_str);
5969 err = print_entry(te, id, path, root_path, repo);
5970 free(id);
5971 if (err)
5972 goto done;
5974 if (recurse && S_ISDIR(got_tree_entry_get_mode(te))) {
5975 char *child_path;
5976 if (asprintf(&child_path, "%s%s%s", path,
5977 path[0] == '/' && path[1] == '\0' ? "" : "/",
5978 got_tree_entry_get_name(te)) == -1) {
5979 err = got_error_from_errno("asprintf");
5980 goto done;
5982 err = print_tree(child_path, commit, show_ids, 1,
5983 root_path, repo);
5984 free(child_path);
5985 if (err)
5986 goto done;
5989 done:
5990 if (tree)
5991 got_object_tree_close(tree);
5992 free(tree_id);
5993 return err;
5996 static const struct got_error *
5997 cmd_tree(int argc, char *argv[])
5999 const struct got_error *error;
6000 struct got_repository *repo = NULL;
6001 struct got_worktree *worktree = NULL;
6002 const char *path, *refname = NULL;
6003 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
6004 struct got_object_id *commit_id = NULL;
6005 struct got_commit_object *commit = NULL;
6006 char *commit_id_str = NULL;
6007 int show_ids = 0, recurse = 0;
6008 int ch;
6009 int *pack_fds = NULL;
6011 #ifndef PROFILE
6012 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
6013 NULL) == -1)
6014 err(1, "pledge");
6015 #endif
6017 while ((ch = getopt(argc, argv, "c:iRr:")) != -1) {
6018 switch (ch) {
6019 case 'c':
6020 commit_id_str = optarg;
6021 break;
6022 case 'i':
6023 show_ids = 1;
6024 break;
6025 case 'R':
6026 recurse = 1;
6027 break;
6028 case 'r':
6029 repo_path = realpath(optarg, NULL);
6030 if (repo_path == NULL)
6031 return got_error_from_errno2("realpath",
6032 optarg);
6033 got_path_strip_trailing_slashes(repo_path);
6034 break;
6035 default:
6036 usage_tree();
6037 /* NOTREACHED */
6041 argc -= optind;
6042 argv += optind;
6044 if (argc == 1)
6045 path = argv[0];
6046 else if (argc > 1)
6047 usage_tree();
6048 else
6049 path = NULL;
6051 cwd = getcwd(NULL, 0);
6052 if (cwd == NULL) {
6053 error = got_error_from_errno("getcwd");
6054 goto done;
6057 error = got_repo_pack_fds_open(&pack_fds);
6058 if (error != NULL)
6059 goto done;
6061 if (repo_path == NULL) {
6062 error = got_worktree_open(&worktree, cwd);
6063 if (error && error->code != GOT_ERR_NOT_WORKTREE)
6064 goto done;
6065 else
6066 error = NULL;
6067 if (worktree) {
6068 repo_path =
6069 strdup(got_worktree_get_repo_path(worktree));
6070 if (repo_path == NULL)
6071 error = got_error_from_errno("strdup");
6072 if (error)
6073 goto done;
6074 } else {
6075 repo_path = strdup(cwd);
6076 if (repo_path == NULL) {
6077 error = got_error_from_errno("strdup");
6078 goto done;
6083 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
6084 if (error != NULL)
6085 goto done;
6087 if (worktree) {
6088 const char *prefix = got_worktree_get_path_prefix(worktree);
6089 char *p;
6091 if (path == NULL)
6092 path = "";
6093 error = got_worktree_resolve_path(&p, worktree, path);
6094 if (error)
6095 goto done;
6096 if (asprintf(&in_repo_path, "%s%s%s", prefix,
6097 (p[0] != '\0' && !got_path_is_root_dir(prefix)) ? "/" : "",
6098 p) == -1) {
6099 error = got_error_from_errno("asprintf");
6100 free(p);
6101 goto done;
6103 free(p);
6104 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
6105 if (error)
6106 goto done;
6107 } else {
6108 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
6109 if (error)
6110 goto done;
6111 if (path == NULL)
6112 path = "/";
6113 error = got_repo_map_path(&in_repo_path, repo, path);
6114 if (error != NULL)
6115 goto done;
6118 if (commit_id_str == NULL) {
6119 struct got_reference *head_ref;
6120 if (worktree)
6121 refname = got_worktree_get_head_ref_name(worktree);
6122 else
6123 refname = GOT_REF_HEAD;
6124 error = got_ref_open(&head_ref, repo, refname, 0);
6125 if (error != NULL)
6126 goto done;
6127 error = got_ref_resolve(&commit_id, repo, head_ref);
6128 got_ref_close(head_ref);
6129 if (error != NULL)
6130 goto done;
6131 } else {
6132 struct got_reflist_head refs;
6133 TAILQ_INIT(&refs);
6134 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
6135 NULL);
6136 if (error)
6137 goto done;
6138 error = got_repo_match_object_id(&commit_id, NULL,
6139 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
6140 got_ref_list_free(&refs);
6141 if (error)
6142 goto done;
6145 if (worktree) {
6146 /* Release work tree lock. */
6147 got_worktree_close(worktree);
6148 worktree = NULL;
6151 error = got_object_open_as_commit(&commit, repo, commit_id);
6152 if (error)
6153 goto done;
6155 error = print_tree(in_repo_path, commit, show_ids, recurse,
6156 in_repo_path, repo);
6157 done:
6158 free(in_repo_path);
6159 free(repo_path);
6160 free(cwd);
6161 free(commit_id);
6162 if (commit)
6163 got_object_commit_close(commit);
6164 if (worktree)
6165 got_worktree_close(worktree);
6166 if (repo) {
6167 const struct got_error *close_err = got_repo_close(repo);
6168 if (error == NULL)
6169 error = close_err;
6171 if (pack_fds) {
6172 const struct got_error *pack_err =
6173 got_repo_pack_fds_close(pack_fds);
6174 if (error == NULL)
6175 error = pack_err;
6177 return error;
6180 __dead static void
6181 usage_status(void)
6183 fprintf(stderr, "usage: %s status [-I] [-S status-codes] "
6184 "[-s status-codes] [path ...]\n", getprogname());
6185 exit(1);
6188 struct got_status_arg {
6189 char *status_codes;
6190 int suppress;
6193 static const struct got_error *
6194 print_status(void *arg, unsigned char status, unsigned char staged_status,
6195 const char *path, struct got_object_id *blob_id,
6196 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
6197 int dirfd, const char *de_name)
6199 struct got_status_arg *st = arg;
6201 if (status == staged_status && (status == GOT_STATUS_DELETE))
6202 status = GOT_STATUS_NO_CHANGE;
6203 if (st != NULL && st->status_codes) {
6204 size_t ncodes = strlen(st->status_codes);
6205 int i, j = 0;
6207 for (i = 0; i < ncodes ; i++) {
6208 if (st->suppress) {
6209 if (status == st->status_codes[i] ||
6210 staged_status == st->status_codes[i]) {
6211 j++;
6212 continue;
6214 } else {
6215 if (status == st->status_codes[i] ||
6216 staged_status == st->status_codes[i])
6217 break;
6221 if (st->suppress && j == 0)
6222 goto print;
6224 if (i == ncodes)
6225 return NULL;
6227 print:
6228 printf("%c%c %s\n", status, staged_status, path);
6229 return NULL;
6232 static const struct got_error *
6233 cmd_status(int argc, char *argv[])
6235 const struct got_error *error = NULL;
6236 struct got_repository *repo = NULL;
6237 struct got_worktree *worktree = NULL;
6238 struct got_status_arg st;
6239 char *cwd = NULL;
6240 struct got_pathlist_head paths;
6241 int ch, i, no_ignores = 0;
6242 int *pack_fds = NULL;
6244 TAILQ_INIT(&paths);
6246 memset(&st, 0, sizeof(st));
6247 st.status_codes = NULL;
6248 st.suppress = 0;
6250 while ((ch = getopt(argc, argv, "IS:s:")) != -1) {
6251 switch (ch) {
6252 case 'I':
6253 no_ignores = 1;
6254 break;
6255 case 'S':
6256 if (st.status_codes != NULL && st.suppress == 0)
6257 option_conflict('S', 's');
6258 st.suppress = 1;
6259 /* fallthrough */
6260 case 's':
6261 for (i = 0; i < strlen(optarg); i++) {
6262 switch (optarg[i]) {
6263 case GOT_STATUS_MODIFY:
6264 case GOT_STATUS_ADD:
6265 case GOT_STATUS_DELETE:
6266 case GOT_STATUS_CONFLICT:
6267 case GOT_STATUS_MISSING:
6268 case GOT_STATUS_OBSTRUCTED:
6269 case GOT_STATUS_UNVERSIONED:
6270 case GOT_STATUS_MODE_CHANGE:
6271 case GOT_STATUS_NONEXISTENT:
6272 break;
6273 default:
6274 errx(1, "invalid status code '%c'",
6275 optarg[i]);
6278 if (ch == 's' && st.suppress)
6279 option_conflict('s', 'S');
6280 st.status_codes = optarg;
6281 break;
6282 default:
6283 usage_status();
6284 /* NOTREACHED */
6288 argc -= optind;
6289 argv += optind;
6291 #ifndef PROFILE
6292 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
6293 NULL) == -1)
6294 err(1, "pledge");
6295 #endif
6296 cwd = getcwd(NULL, 0);
6297 if (cwd == NULL) {
6298 error = got_error_from_errno("getcwd");
6299 goto done;
6302 error = got_repo_pack_fds_open(&pack_fds);
6303 if (error != NULL)
6304 goto done;
6306 error = got_worktree_open(&worktree, cwd);
6307 if (error) {
6308 if (error->code == GOT_ERR_NOT_WORKTREE)
6309 error = wrap_not_worktree_error(error, "status", cwd);
6310 goto done;
6313 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
6314 NULL, pack_fds);
6315 if (error != NULL)
6316 goto done;
6318 error = apply_unveil(got_repo_get_path(repo), 1,
6319 got_worktree_get_root_path(worktree));
6320 if (error)
6321 goto done;
6323 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
6324 if (error)
6325 goto done;
6327 error = got_worktree_status(worktree, &paths, repo, no_ignores,
6328 print_status, &st, check_cancelled, NULL);
6329 done:
6330 if (pack_fds) {
6331 const struct got_error *pack_err =
6332 got_repo_pack_fds_close(pack_fds);
6333 if (error == NULL)
6334 error = pack_err;
6337 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
6338 free(cwd);
6339 return error;
6342 __dead static void
6343 usage_ref(void)
6345 fprintf(stderr, "usage: %s ref [-dlt] [-c object] [-r repository-path] "
6346 "[-s reference] [name]\n", getprogname());
6347 exit(1);
6350 static const struct got_error *
6351 list_refs(struct got_repository *repo, const char *refname, int sort_by_time)
6353 static const struct got_error *err = NULL;
6354 struct got_reflist_head refs;
6355 struct got_reflist_entry *re;
6357 TAILQ_INIT(&refs);
6358 err = got_ref_list(&refs, repo, refname, sort_by_time ?
6359 got_ref_cmp_by_commit_timestamp_descending : got_ref_cmp_by_name,
6360 repo);
6361 if (err)
6362 return err;
6364 TAILQ_FOREACH(re, &refs, entry) {
6365 char *refstr;
6366 refstr = got_ref_to_str(re->ref);
6367 if (refstr == NULL) {
6368 err = got_error_from_errno("got_ref_to_str");
6369 break;
6371 printf("%s: %s\n", got_ref_get_name(re->ref), refstr);
6372 free(refstr);
6375 got_ref_list_free(&refs);
6376 return err;
6379 static const struct got_error *
6380 delete_ref_by_name(struct got_repository *repo, const char *refname)
6382 const struct got_error *err;
6383 struct got_reference *ref;
6385 err = got_ref_open(&ref, repo, refname, 0);
6386 if (err)
6387 return err;
6389 err = delete_ref(repo, ref);
6390 got_ref_close(ref);
6391 return err;
6394 static const struct got_error *
6395 add_ref(struct got_repository *repo, const char *refname, const char *target)
6397 const struct got_error *err = NULL;
6398 struct got_object_id *id = NULL;
6399 struct got_reference *ref = NULL;
6400 struct got_reflist_head refs;
6403 * Don't let the user create a reference name with a leading '-'.
6404 * While technically a valid reference name, this case is usually
6405 * an unintended typo.
6407 if (refname[0] == '-')
6408 return got_error_path(refname, GOT_ERR_REF_NAME_MINUS);
6410 TAILQ_INIT(&refs);
6411 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
6412 if (err)
6413 goto done;
6414 err = got_repo_match_object_id(&id, NULL, target, GOT_OBJ_TYPE_ANY,
6415 &refs, repo);
6416 got_ref_list_free(&refs);
6417 if (err)
6418 goto done;
6420 err = got_ref_alloc(&ref, refname, id);
6421 if (err)
6422 goto done;
6424 err = got_ref_write(ref, repo);
6425 done:
6426 if (ref)
6427 got_ref_close(ref);
6428 free(id);
6429 return err;
6432 static const struct got_error *
6433 add_symref(struct got_repository *repo, const char *refname, const char *target)
6435 const struct got_error *err = NULL;
6436 struct got_reference *ref = NULL;
6437 struct got_reference *target_ref = NULL;
6440 * Don't let the user create a reference name with a leading '-'.
6441 * While technically a valid reference name, this case is usually
6442 * an unintended typo.
6444 if (refname[0] == '-')
6445 return got_error_path(refname, GOT_ERR_REF_NAME_MINUS);
6447 err = got_ref_open(&target_ref, repo, target, 0);
6448 if (err)
6449 return err;
6451 err = got_ref_alloc_symref(&ref, refname, target_ref);
6452 if (err)
6453 goto done;
6455 err = got_ref_write(ref, repo);
6456 done:
6457 if (target_ref)
6458 got_ref_close(target_ref);
6459 if (ref)
6460 got_ref_close(ref);
6461 return err;
6464 static const struct got_error *
6465 cmd_ref(int argc, char *argv[])
6467 const struct got_error *error = NULL;
6468 struct got_repository *repo = NULL;
6469 struct got_worktree *worktree = NULL;
6470 char *cwd = NULL, *repo_path = NULL;
6471 int ch, do_list = 0, do_delete = 0, sort_by_time = 0;
6472 const char *obj_arg = NULL, *symref_target= NULL;
6473 char *refname = NULL;
6474 int *pack_fds = NULL;
6476 while ((ch = getopt(argc, argv, "c:dlr:s:t")) != -1) {
6477 switch (ch) {
6478 case 'c':
6479 obj_arg = optarg;
6480 break;
6481 case 'd':
6482 do_delete = 1;
6483 break;
6484 case 'l':
6485 do_list = 1;
6486 break;
6487 case 'r':
6488 repo_path = realpath(optarg, NULL);
6489 if (repo_path == NULL)
6490 return got_error_from_errno2("realpath",
6491 optarg);
6492 got_path_strip_trailing_slashes(repo_path);
6493 break;
6494 case 's':
6495 symref_target = optarg;
6496 break;
6497 case 't':
6498 sort_by_time = 1;
6499 break;
6500 default:
6501 usage_ref();
6502 /* NOTREACHED */
6506 if (obj_arg && do_list)
6507 option_conflict('c', 'l');
6508 if (obj_arg && do_delete)
6509 option_conflict('c', 'd');
6510 if (obj_arg && symref_target)
6511 option_conflict('c', 's');
6512 if (symref_target && do_delete)
6513 option_conflict('s', 'd');
6514 if (symref_target && do_list)
6515 option_conflict('s', 'l');
6516 if (do_delete && do_list)
6517 option_conflict('d', 'l');
6518 if (sort_by_time && !do_list)
6519 errx(1, "-t option requires -l option");
6521 argc -= optind;
6522 argv += optind;
6524 if (do_list) {
6525 if (argc != 0 && argc != 1)
6526 usage_ref();
6527 if (argc == 1) {
6528 refname = strdup(argv[0]);
6529 if (refname == NULL) {
6530 error = got_error_from_errno("strdup");
6531 goto done;
6534 } else {
6535 if (argc != 1)
6536 usage_ref();
6537 refname = strdup(argv[0]);
6538 if (refname == NULL) {
6539 error = got_error_from_errno("strdup");
6540 goto done;
6544 if (refname)
6545 got_path_strip_trailing_slashes(refname);
6547 #ifndef PROFILE
6548 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
6549 "sendfd unveil", NULL) == -1)
6550 err(1, "pledge");
6551 #endif
6552 cwd = getcwd(NULL, 0);
6553 if (cwd == NULL) {
6554 error = got_error_from_errno("getcwd");
6555 goto done;
6558 error = got_repo_pack_fds_open(&pack_fds);
6559 if (error != NULL)
6560 goto done;
6562 if (repo_path == NULL) {
6563 error = got_worktree_open(&worktree, cwd);
6564 if (error && error->code != GOT_ERR_NOT_WORKTREE)
6565 goto done;
6566 else
6567 error = NULL;
6568 if (worktree) {
6569 repo_path =
6570 strdup(got_worktree_get_repo_path(worktree));
6571 if (repo_path == NULL)
6572 error = got_error_from_errno("strdup");
6573 if (error)
6574 goto done;
6575 } else {
6576 repo_path = strdup(cwd);
6577 if (repo_path == NULL) {
6578 error = got_error_from_errno("strdup");
6579 goto done;
6584 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
6585 if (error != NULL)
6586 goto done;
6588 #ifndef PROFILE
6589 if (do_list) {
6590 /* Remove "cpath" promise. */
6591 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
6592 NULL) == -1)
6593 err(1, "pledge");
6595 #endif
6597 error = apply_unveil(got_repo_get_path(repo), do_list,
6598 worktree ? got_worktree_get_root_path(worktree) : NULL);
6599 if (error)
6600 goto done;
6602 if (do_list)
6603 error = list_refs(repo, refname, sort_by_time);
6604 else if (do_delete)
6605 error = delete_ref_by_name(repo, refname);
6606 else if (symref_target)
6607 error = add_symref(repo, refname, symref_target);
6608 else {
6609 if (obj_arg == NULL)
6610 usage_ref();
6611 error = add_ref(repo, refname, obj_arg);
6613 done:
6614 free(refname);
6615 if (repo) {
6616 const struct got_error *close_err = got_repo_close(repo);
6617 if (error == NULL)
6618 error = close_err;
6620 if (worktree)
6621 got_worktree_close(worktree);
6622 if (pack_fds) {
6623 const struct got_error *pack_err =
6624 got_repo_pack_fds_close(pack_fds);
6625 if (error == NULL)
6626 error = pack_err;
6628 free(cwd);
6629 free(repo_path);
6630 return error;
6633 __dead static void
6634 usage_branch(void)
6636 fprintf(stderr, "usage: %s branch [-lnt] [-c commit] [-d name] "
6637 "[-r repository-path] [name]\n", getprogname());
6638 exit(1);
6641 static const struct got_error *
6642 list_branch(struct got_repository *repo, struct got_worktree *worktree,
6643 struct got_reference *ref)
6645 const struct got_error *err = NULL;
6646 const char *refname, *marker = " ";
6647 char *refstr;
6649 refname = got_ref_get_name(ref);
6650 if (worktree && strcmp(refname,
6651 got_worktree_get_head_ref_name(worktree)) == 0) {
6652 struct got_object_id *id = NULL;
6654 err = got_ref_resolve(&id, repo, ref);
6655 if (err)
6656 return err;
6657 if (got_object_id_cmp(id,
6658 got_worktree_get_base_commit_id(worktree)) == 0)
6659 marker = "* ";
6660 else
6661 marker = "~ ";
6662 free(id);
6665 if (strncmp(refname, "refs/heads/", 11) == 0)
6666 refname += 11;
6667 if (strncmp(refname, "refs/got/worktree/", 18) == 0)
6668 refname += 18;
6669 if (strncmp(refname, "refs/remotes/", 13) == 0)
6670 refname += 13;
6672 refstr = got_ref_to_str(ref);
6673 if (refstr == NULL)
6674 return got_error_from_errno("got_ref_to_str");
6676 printf("%s%s: %s\n", marker, refname, refstr);
6677 free(refstr);
6678 return NULL;
6681 static const struct got_error *
6682 show_current_branch(struct got_repository *repo, struct got_worktree *worktree)
6684 const char *refname;
6686 if (worktree == NULL)
6687 return got_error(GOT_ERR_NOT_WORKTREE);
6689 refname = got_worktree_get_head_ref_name(worktree);
6691 if (strncmp(refname, "refs/heads/", 11) == 0)
6692 refname += 11;
6693 if (strncmp(refname, "refs/got/worktree/", 18) == 0)
6694 refname += 18;
6696 printf("%s\n", refname);
6698 return NULL;
6701 static const struct got_error *
6702 list_branches(struct got_repository *repo, struct got_worktree *worktree,
6703 int sort_by_time)
6705 static const struct got_error *err = NULL;
6706 struct got_reflist_head refs;
6707 struct got_reflist_entry *re;
6708 struct got_reference *temp_ref = NULL;
6709 int rebase_in_progress, histedit_in_progress;
6711 TAILQ_INIT(&refs);
6713 if (worktree) {
6714 err = got_worktree_rebase_in_progress(&rebase_in_progress,
6715 worktree);
6716 if (err)
6717 return err;
6719 err = got_worktree_histedit_in_progress(&histedit_in_progress,
6720 worktree);
6721 if (err)
6722 return err;
6724 if (rebase_in_progress || histedit_in_progress) {
6725 err = got_ref_open(&temp_ref, repo,
6726 got_worktree_get_head_ref_name(worktree), 0);
6727 if (err)
6728 return err;
6729 list_branch(repo, worktree, temp_ref);
6730 got_ref_close(temp_ref);
6734 err = got_ref_list(&refs, repo, "refs/heads", sort_by_time ?
6735 got_ref_cmp_by_commit_timestamp_descending : got_ref_cmp_by_name,
6736 repo);
6737 if (err)
6738 return err;
6740 TAILQ_FOREACH(re, &refs, entry)
6741 list_branch(repo, worktree, re->ref);
6743 got_ref_list_free(&refs);
6745 err = got_ref_list(&refs, repo, "refs/remotes", sort_by_time ?
6746 got_ref_cmp_by_commit_timestamp_descending : got_ref_cmp_by_name,
6747 repo);
6748 if (err)
6749 return err;
6751 TAILQ_FOREACH(re, &refs, entry)
6752 list_branch(repo, worktree, re->ref);
6754 got_ref_list_free(&refs);
6756 return NULL;
6759 static const struct got_error *
6760 delete_branch(struct got_repository *repo, struct got_worktree *worktree,
6761 const char *branch_name)
6763 const struct got_error *err = NULL;
6764 struct got_reference *ref = NULL;
6765 char *refname, *remote_refname = NULL;
6767 if (strncmp(branch_name, "refs/", 5) == 0)
6768 branch_name += 5;
6769 if (strncmp(branch_name, "heads/", 6) == 0)
6770 branch_name += 6;
6771 else if (strncmp(branch_name, "remotes/", 8) == 0)
6772 branch_name += 8;
6774 if (asprintf(&refname, "refs/heads/%s", branch_name) == -1)
6775 return got_error_from_errno("asprintf");
6777 if (asprintf(&remote_refname, "refs/remotes/%s",
6778 branch_name) == -1) {
6779 err = got_error_from_errno("asprintf");
6780 goto done;
6783 err = got_ref_open(&ref, repo, refname, 0);
6784 if (err) {
6785 const struct got_error *err2;
6786 if (err->code != GOT_ERR_NOT_REF)
6787 goto done;
6789 * Keep 'err' intact such that if neither branch exists
6790 * we report "refs/heads" rather than "refs/remotes" in
6791 * our error message.
6793 err2 = got_ref_open(&ref, repo, remote_refname, 0);
6794 if (err2)
6795 goto done;
6796 err = NULL;
6799 if (worktree &&
6800 strcmp(got_worktree_get_head_ref_name(worktree),
6801 got_ref_get_name(ref)) == 0) {
6802 err = got_error_msg(GOT_ERR_SAME_BRANCH,
6803 "will not delete this work tree's current branch");
6804 goto done;
6807 err = delete_ref(repo, ref);
6808 done:
6809 if (ref)
6810 got_ref_close(ref);
6811 free(refname);
6812 free(remote_refname);
6813 return err;
6816 static const struct got_error *
6817 add_branch(struct got_repository *repo, const char *branch_name,
6818 struct got_object_id *base_commit_id)
6820 const struct got_error *err = NULL;
6821 struct got_reference *ref = NULL;
6822 char *refname = NULL;
6825 * Don't let the user create a branch name with a leading '-'.
6826 * While technically a valid reference name, this case is usually
6827 * an unintended typo.
6829 if (branch_name[0] == '-')
6830 return got_error_path(branch_name, GOT_ERR_REF_NAME_MINUS);
6832 if (strncmp(branch_name, "refs/heads/", 11) == 0)
6833 branch_name += 11;
6835 if (asprintf(&refname, "refs/heads/%s", branch_name) == -1) {
6836 err = got_error_from_errno("asprintf");
6837 goto done;
6840 err = got_ref_open(&ref, repo, refname, 0);
6841 if (err == NULL) {
6842 err = got_error(GOT_ERR_BRANCH_EXISTS);
6843 goto done;
6844 } else if (err->code != GOT_ERR_NOT_REF)
6845 goto done;
6847 err = got_ref_alloc(&ref, refname, base_commit_id);
6848 if (err)
6849 goto done;
6851 err = got_ref_write(ref, repo);
6852 done:
6853 if (ref)
6854 got_ref_close(ref);
6855 free(refname);
6856 return err;
6859 static const struct got_error *
6860 cmd_branch(int argc, char *argv[])
6862 const struct got_error *error = NULL;
6863 struct got_repository *repo = NULL;
6864 struct got_worktree *worktree = NULL;
6865 char *cwd = NULL, *repo_path = NULL;
6866 int ch, do_list = 0, do_show = 0, do_update = 1, sort_by_time = 0;
6867 const char *delref = NULL, *commit_id_arg = NULL;
6868 struct got_reference *ref = NULL;
6869 struct got_pathlist_head paths;
6870 struct got_object_id *commit_id = NULL;
6871 char *commit_id_str = NULL;
6872 int *pack_fds = NULL;
6874 TAILQ_INIT(&paths);
6876 while ((ch = getopt(argc, argv, "c:d:lnr:t")) != -1) {
6877 switch (ch) {
6878 case 'c':
6879 commit_id_arg = optarg;
6880 break;
6881 case 'd':
6882 delref = optarg;
6883 break;
6884 case 'l':
6885 do_list = 1;
6886 break;
6887 case 'n':
6888 do_update = 0;
6889 break;
6890 case 'r':
6891 repo_path = realpath(optarg, NULL);
6892 if (repo_path == NULL)
6893 return got_error_from_errno2("realpath",
6894 optarg);
6895 got_path_strip_trailing_slashes(repo_path);
6896 break;
6897 case 't':
6898 sort_by_time = 1;
6899 break;
6900 default:
6901 usage_branch();
6902 /* NOTREACHED */
6906 if (do_list && delref)
6907 option_conflict('l', 'd');
6908 if (sort_by_time && !do_list)
6909 errx(1, "-t option requires -l option");
6911 argc -= optind;
6912 argv += optind;
6914 if (!do_list && !delref && argc == 0)
6915 do_show = 1;
6917 if ((do_list || delref || do_show) && commit_id_arg != NULL)
6918 errx(1, "-c option can only be used when creating a branch");
6920 if (do_list || delref) {
6921 if (argc > 0)
6922 usage_branch();
6923 } else if (!do_show && argc != 1)
6924 usage_branch();
6926 #ifndef PROFILE
6927 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
6928 "sendfd unveil", NULL) == -1)
6929 err(1, "pledge");
6930 #endif
6931 cwd = getcwd(NULL, 0);
6932 if (cwd == NULL) {
6933 error = got_error_from_errno("getcwd");
6934 goto done;
6937 error = got_repo_pack_fds_open(&pack_fds);
6938 if (error != NULL)
6939 goto done;
6941 if (repo_path == NULL) {
6942 error = got_worktree_open(&worktree, cwd);
6943 if (error && error->code != GOT_ERR_NOT_WORKTREE)
6944 goto done;
6945 else
6946 error = NULL;
6947 if (worktree) {
6948 repo_path =
6949 strdup(got_worktree_get_repo_path(worktree));
6950 if (repo_path == NULL)
6951 error = got_error_from_errno("strdup");
6952 if (error)
6953 goto done;
6954 } else {
6955 repo_path = strdup(cwd);
6956 if (repo_path == NULL) {
6957 error = got_error_from_errno("strdup");
6958 goto done;
6963 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
6964 if (error != NULL)
6965 goto done;
6967 #ifndef PROFILE
6968 if (do_list || do_show) {
6969 /* Remove "cpath" promise. */
6970 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
6971 NULL) == -1)
6972 err(1, "pledge");
6974 #endif
6976 error = apply_unveil(got_repo_get_path(repo), do_list,
6977 worktree ? got_worktree_get_root_path(worktree) : NULL);
6978 if (error)
6979 goto done;
6981 if (do_show)
6982 error = show_current_branch(repo, worktree);
6983 else if (do_list)
6984 error = list_branches(repo, worktree, sort_by_time);
6985 else if (delref)
6986 error = delete_branch(repo, worktree, delref);
6987 else {
6988 struct got_reflist_head refs;
6989 TAILQ_INIT(&refs);
6990 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
6991 NULL);
6992 if (error)
6993 goto done;
6994 if (commit_id_arg == NULL)
6995 commit_id_arg = worktree ?
6996 got_worktree_get_head_ref_name(worktree) :
6997 GOT_REF_HEAD;
6998 error = got_repo_match_object_id(&commit_id, NULL,
6999 commit_id_arg, GOT_OBJ_TYPE_COMMIT, &refs, repo);
7000 got_ref_list_free(&refs);
7001 if (error)
7002 goto done;
7003 error = add_branch(repo, argv[0], commit_id);
7004 if (error)
7005 goto done;
7006 if (worktree && do_update) {
7007 struct got_update_progress_arg upa;
7008 char *branch_refname = NULL;
7010 error = got_object_id_str(&commit_id_str, commit_id);
7011 if (error)
7012 goto done;
7013 error = get_worktree_paths_from_argv(&paths, 0, NULL,
7014 worktree);
7015 if (error)
7016 goto done;
7017 if (asprintf(&branch_refname, "refs/heads/%s", argv[0])
7018 == -1) {
7019 error = got_error_from_errno("asprintf");
7020 goto done;
7022 error = got_ref_open(&ref, repo, branch_refname, 0);
7023 free(branch_refname);
7024 if (error)
7025 goto done;
7026 error = switch_head_ref(ref, commit_id, worktree,
7027 repo);
7028 if (error)
7029 goto done;
7030 error = got_worktree_set_base_commit_id(worktree, repo,
7031 commit_id);
7032 if (error)
7033 goto done;
7034 memset(&upa, 0, sizeof(upa));
7035 error = got_worktree_checkout_files(worktree, &paths,
7036 repo, update_progress, &upa, check_cancelled,
7037 NULL);
7038 if (error)
7039 goto done;
7040 if (upa.did_something) {
7041 printf("Updated to %s: %s\n",
7042 got_worktree_get_head_ref_name(worktree),
7043 commit_id_str);
7045 print_update_progress_stats(&upa);
7048 done:
7049 if (ref)
7050 got_ref_close(ref);
7051 if (repo) {
7052 const struct got_error *close_err = got_repo_close(repo);
7053 if (error == NULL)
7054 error = close_err;
7056 if (worktree)
7057 got_worktree_close(worktree);
7058 if (pack_fds) {
7059 const struct got_error *pack_err =
7060 got_repo_pack_fds_close(pack_fds);
7061 if (error == NULL)
7062 error = pack_err;
7064 free(cwd);
7065 free(repo_path);
7066 free(commit_id);
7067 free(commit_id_str);
7068 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
7069 return error;
7073 __dead static void
7074 usage_tag(void)
7076 fprintf(stderr, "usage: %s tag [-lVv] [-c commit] [-m message] "
7077 "[-r repository-path] [-s signer-id] name\n", getprogname());
7078 exit(1);
7081 #if 0
7082 static const struct got_error *
7083 sort_tags(struct got_reflist_head *sorted, struct got_reflist_head *tags)
7085 const struct got_error *err = NULL;
7086 struct got_reflist_entry *re, *se, *new;
7087 struct got_object_id *re_id, *se_id;
7088 struct got_tag_object *re_tag, *se_tag;
7089 time_t re_time, se_time;
7091 STAILQ_FOREACH(re, tags, entry) {
7092 se = STAILQ_FIRST(sorted);
7093 if (se == NULL) {
7094 err = got_reflist_entry_dup(&new, re);
7095 if (err)
7096 return err;
7097 STAILQ_INSERT_HEAD(sorted, new, entry);
7098 continue;
7099 } else {
7100 err = got_ref_resolve(&re_id, repo, re->ref);
7101 if (err)
7102 break;
7103 err = got_object_open_as_tag(&re_tag, repo, re_id);
7104 free(re_id);
7105 if (err)
7106 break;
7107 re_time = got_object_tag_get_tagger_time(re_tag);
7108 got_object_tag_close(re_tag);
7111 while (se) {
7112 err = got_ref_resolve(&se_id, repo, re->ref);
7113 if (err)
7114 break;
7115 err = got_object_open_as_tag(&se_tag, repo, se_id);
7116 free(se_id);
7117 if (err)
7118 break;
7119 se_time = got_object_tag_get_tagger_time(se_tag);
7120 got_object_tag_close(se_tag);
7122 if (se_time > re_time) {
7123 err = got_reflist_entry_dup(&new, re);
7124 if (err)
7125 return err;
7126 STAILQ_INSERT_AFTER(sorted, se, new, entry);
7127 break;
7129 se = STAILQ_NEXT(se, entry);
7130 continue;
7133 done:
7134 return err;
7136 #endif
7138 static const struct got_error *
7139 get_tag_refname(char **refname, const char *tag_name)
7141 const struct got_error *err;
7143 if (strncmp("refs/tags/", tag_name, 10) == 0) {
7144 *refname = strdup(tag_name);
7145 if (*refname == NULL)
7146 return got_error_from_errno("strdup");
7147 } else if (asprintf(refname, "refs/tags/%s", tag_name) == -1) {
7148 err = got_error_from_errno("asprintf");
7149 *refname = NULL;
7150 return err;
7153 return NULL;
7156 static const struct got_error *
7157 list_tags(struct got_repository *repo, const char *tag_name, int verify_tags,
7158 const char *allowed_signers, const char *revoked_signers, int verbosity)
7160 static const struct got_error *err = NULL;
7161 struct got_reflist_head refs;
7162 struct got_reflist_entry *re;
7163 char *wanted_refname = NULL;
7164 int bad_sigs = 0;
7166 TAILQ_INIT(&refs);
7168 err = got_ref_list(&refs, repo, "refs/tags", got_ref_cmp_tags, repo);
7169 if (err)
7170 return err;
7172 if (tag_name) {
7173 struct got_reference *ref;
7174 err = get_tag_refname(&wanted_refname, tag_name);
7175 if (err)
7176 goto done;
7177 /* Wanted tag reference should exist. */
7178 err = got_ref_open(&ref, repo, wanted_refname, 0);
7179 if (err)
7180 goto done;
7181 got_ref_close(ref);
7184 TAILQ_FOREACH(re, &refs, entry) {
7185 const char *refname;
7186 char *refstr, *tagmsg0, *tagmsg, *line, *id_str, *datestr;
7187 char datebuf[26];
7188 const char *tagger, *ssh_sig = NULL;
7189 char *sig_msg = NULL;
7190 time_t tagger_time;
7191 struct got_object_id *id;
7192 struct got_tag_object *tag;
7193 struct got_commit_object *commit = NULL;
7195 refname = got_ref_get_name(re->ref);
7196 if (strncmp(refname, "refs/tags/", 10) != 0 ||
7197 (wanted_refname && strcmp(refname, wanted_refname) != 0))
7198 continue;
7199 refname += 10;
7200 refstr = got_ref_to_str(re->ref);
7201 if (refstr == NULL) {
7202 err = got_error_from_errno("got_ref_to_str");
7203 break;
7206 err = got_ref_resolve(&id, repo, re->ref);
7207 if (err)
7208 break;
7209 err = got_object_open_as_tag(&tag, repo, id);
7210 if (err) {
7211 if (err->code != GOT_ERR_OBJ_TYPE) {
7212 free(id);
7213 break;
7215 /* "lightweight" tag */
7216 err = got_object_open_as_commit(&commit, repo, id);
7217 if (err) {
7218 free(id);
7219 break;
7221 tagger = got_object_commit_get_committer(commit);
7222 tagger_time =
7223 got_object_commit_get_committer_time(commit);
7224 err = got_object_id_str(&id_str, id);
7225 free(id);
7226 if (err)
7227 break;
7228 } else {
7229 free(id);
7230 tagger = got_object_tag_get_tagger(tag);
7231 tagger_time = got_object_tag_get_tagger_time(tag);
7232 err = got_object_id_str(&id_str,
7233 got_object_tag_get_object_id(tag));
7234 if (err)
7235 break;
7238 if (tag && verify_tags) {
7239 ssh_sig = got_sigs_get_tagmsg_ssh_signature(
7240 got_object_tag_get_message(tag));
7241 if (ssh_sig && allowed_signers == NULL) {
7242 err = got_error_msg(
7243 GOT_ERR_VERIFY_TAG_SIGNATURE,
7244 "SSH signature verification requires "
7245 "setting allowed_signers in "
7246 "got.conf(5)");
7247 break;
7251 printf("%stag %s %s\n", GOT_COMMIT_SEP_STR, refname, refstr);
7252 free(refstr);
7253 printf("from: %s\n", tagger);
7254 datestr = get_datestr(&tagger_time, datebuf);
7255 if (datestr)
7256 printf("date: %s UTC\n", datestr);
7257 if (commit)
7258 printf("object: %s %s\n", GOT_OBJ_LABEL_COMMIT, id_str);
7259 else {
7260 switch (got_object_tag_get_object_type(tag)) {
7261 case GOT_OBJ_TYPE_BLOB:
7262 printf("object: %s %s\n", GOT_OBJ_LABEL_BLOB,
7263 id_str);
7264 break;
7265 case GOT_OBJ_TYPE_TREE:
7266 printf("object: %s %s\n", GOT_OBJ_LABEL_TREE,
7267 id_str);
7268 break;
7269 case GOT_OBJ_TYPE_COMMIT:
7270 printf("object: %s %s\n", GOT_OBJ_LABEL_COMMIT,
7271 id_str);
7272 break;
7273 case GOT_OBJ_TYPE_TAG:
7274 printf("object: %s %s\n", GOT_OBJ_LABEL_TAG,
7275 id_str);
7276 break;
7277 default:
7278 break;
7281 free(id_str);
7283 if (ssh_sig) {
7284 err = got_sigs_verify_tag_ssh(&sig_msg, tag, ssh_sig,
7285 allowed_signers, revoked_signers, verbosity);
7286 if (err && err->code == GOT_ERR_BAD_TAG_SIGNATURE)
7287 bad_sigs = 1;
7288 else if (err)
7289 break;
7290 printf("signature: %s", sig_msg);
7291 free(sig_msg);
7292 sig_msg = NULL;
7295 if (commit) {
7296 err = got_object_commit_get_logmsg(&tagmsg0, commit);
7297 if (err)
7298 break;
7299 got_object_commit_close(commit);
7300 } else {
7301 tagmsg0 = strdup(got_object_tag_get_message(tag));
7302 got_object_tag_close(tag);
7303 if (tagmsg0 == NULL) {
7304 err = got_error_from_errno("strdup");
7305 break;
7309 tagmsg = tagmsg0;
7310 do {
7311 line = strsep(&tagmsg, "\n");
7312 if (line)
7313 printf(" %s\n", line);
7314 } while (line);
7315 free(tagmsg0);
7317 done:
7318 got_ref_list_free(&refs);
7319 free(wanted_refname);
7321 if (err == NULL && bad_sigs)
7322 err = got_error(GOT_ERR_BAD_TAG_SIGNATURE);
7323 return err;
7326 static const struct got_error *
7327 get_tag_message(char **tagmsg, char **tagmsg_path, const char *commit_id_str,
7328 const char *tag_name, const char *repo_path)
7330 const struct got_error *err = NULL;
7331 char *template = NULL, *initial_content = NULL;
7332 char *editor = NULL;
7333 int initial_content_len;
7334 int fd = -1;
7336 if (asprintf(&template, GOT_TMPDIR_STR "/got-tagmsg") == -1) {
7337 err = got_error_from_errno("asprintf");
7338 goto done;
7341 initial_content_len = asprintf(&initial_content,
7342 "\n# tagging commit %s as %s\n",
7343 commit_id_str, tag_name);
7344 if (initial_content_len == -1) {
7345 err = got_error_from_errno("asprintf");
7346 goto done;
7349 err = got_opentemp_named_fd(tagmsg_path, &fd, template, "");
7350 if (err)
7351 goto done;
7353 if (write(fd, initial_content, initial_content_len) == -1) {
7354 err = got_error_from_errno2("write", *tagmsg_path);
7355 goto done;
7358 err = get_editor(&editor);
7359 if (err)
7360 goto done;
7361 err = edit_logmsg(tagmsg, editor, *tagmsg_path, initial_content,
7362 initial_content_len, 1);
7363 done:
7364 free(initial_content);
7365 free(template);
7366 free(editor);
7368 if (fd != -1 && close(fd) == -1 && err == NULL)
7369 err = got_error_from_errno2("close", *tagmsg_path);
7371 if (err) {
7372 free(*tagmsg);
7373 *tagmsg = NULL;
7375 return err;
7378 static const struct got_error *
7379 add_tag(struct got_repository *repo, const char *tagger,
7380 const char *tag_name, const char *commit_arg, const char *tagmsg_arg,
7381 const char *signer_id, int verbosity)
7383 const struct got_error *err = NULL;
7384 struct got_object_id *commit_id = NULL, *tag_id = NULL;
7385 char *label = NULL, *commit_id_str = NULL;
7386 struct got_reference *ref = NULL;
7387 char *refname = NULL, *tagmsg = NULL;
7388 char *tagmsg_path = NULL, *tag_id_str = NULL;
7389 int preserve_tagmsg = 0;
7390 struct got_reflist_head refs;
7392 TAILQ_INIT(&refs);
7395 * Don't let the user create a tag name with a leading '-'.
7396 * While technically a valid reference name, this case is usually
7397 * an unintended typo.
7399 if (tag_name[0] == '-')
7400 return got_error_path(tag_name, GOT_ERR_REF_NAME_MINUS);
7402 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
7403 if (err)
7404 goto done;
7406 err = got_repo_match_object_id(&commit_id, &label, commit_arg,
7407 GOT_OBJ_TYPE_COMMIT, &refs, repo);
7408 if (err)
7409 goto done;
7411 err = got_object_id_str(&commit_id_str, commit_id);
7412 if (err)
7413 goto done;
7415 err = get_tag_refname(&refname, tag_name);
7416 if (err)
7417 goto done;
7418 if (strncmp("refs/tags/", tag_name, 10) == 0)
7419 tag_name += 10;
7421 err = got_ref_open(&ref, repo, refname, 0);
7422 if (err == NULL) {
7423 err = got_error(GOT_ERR_TAG_EXISTS);
7424 goto done;
7425 } else if (err->code != GOT_ERR_NOT_REF)
7426 goto done;
7428 if (tagmsg_arg == NULL) {
7429 err = get_tag_message(&tagmsg, &tagmsg_path, commit_id_str,
7430 tag_name, got_repo_get_path(repo));
7431 if (err) {
7432 if (err->code != GOT_ERR_COMMIT_MSG_EMPTY &&
7433 tagmsg_path != NULL)
7434 preserve_tagmsg = 1;
7435 goto done;
7437 /* Editor is done; we can now apply unveil(2) */
7438 err = got_sigs_apply_unveil();
7439 if (err)
7440 goto done;
7441 err = apply_unveil(got_repo_get_path(repo), 0, NULL);
7442 if (err)
7443 goto done;
7446 err = got_object_tag_create(&tag_id, tag_name, commit_id,
7447 tagger, time(NULL), tagmsg ? tagmsg : tagmsg_arg, signer_id, repo,
7448 verbosity);
7449 if (err) {
7450 if (tagmsg_path)
7451 preserve_tagmsg = 1;
7452 goto done;
7455 err = got_ref_alloc(&ref, refname, tag_id);
7456 if (err) {
7457 if (tagmsg_path)
7458 preserve_tagmsg = 1;
7459 goto done;
7462 err = got_ref_write(ref, repo);
7463 if (err) {
7464 if (tagmsg_path)
7465 preserve_tagmsg = 1;
7466 goto done;
7469 err = got_object_id_str(&tag_id_str, tag_id);
7470 if (err) {
7471 if (tagmsg_path)
7472 preserve_tagmsg = 1;
7473 goto done;
7475 printf("Created tag %s\n", tag_id_str);
7476 done:
7477 if (preserve_tagmsg) {
7478 fprintf(stderr, "%s: tag message preserved in %s\n",
7479 getprogname(), tagmsg_path);
7480 } else if (tagmsg_path && unlink(tagmsg_path) == -1 && err == NULL)
7481 err = got_error_from_errno2("unlink", tagmsg_path);
7482 free(tag_id_str);
7483 if (ref)
7484 got_ref_close(ref);
7485 free(commit_id);
7486 free(commit_id_str);
7487 free(refname);
7488 free(tagmsg);
7489 free(tagmsg_path);
7490 got_ref_list_free(&refs);
7491 return err;
7494 static const struct got_error *
7495 cmd_tag(int argc, char *argv[])
7497 const struct got_error *error = NULL;
7498 struct got_repository *repo = NULL;
7499 struct got_worktree *worktree = NULL;
7500 char *cwd = NULL, *repo_path = NULL, *commit_id_str = NULL;
7501 char *gitconfig_path = NULL, *tagger = NULL;
7502 char *allowed_signers = NULL, *revoked_signers = NULL;
7503 const char *signer_id = NULL;
7504 const char *tag_name = NULL, *commit_id_arg = NULL, *tagmsg = NULL;
7505 int ch, do_list = 0, verify_tags = 0, verbosity = 0;
7506 int *pack_fds = NULL;
7508 while ((ch = getopt(argc, argv, "c:lm:r:s:Vv")) != -1) {
7509 switch (ch) {
7510 case 'c':
7511 commit_id_arg = optarg;
7512 break;
7513 case 'l':
7514 do_list = 1;
7515 break;
7516 case 'm':
7517 tagmsg = optarg;
7518 break;
7519 case 'r':
7520 repo_path = realpath(optarg, NULL);
7521 if (repo_path == NULL) {
7522 error = got_error_from_errno2("realpath",
7523 optarg);
7524 goto done;
7526 got_path_strip_trailing_slashes(repo_path);
7527 break;
7528 case 's':
7529 signer_id = optarg;
7530 break;
7531 case 'V':
7532 verify_tags = 1;
7533 break;
7534 case 'v':
7535 if (verbosity < 0)
7536 verbosity = 0;
7537 else if (verbosity < 3)
7538 verbosity++;
7539 break;
7540 default:
7541 usage_tag();
7542 /* NOTREACHED */
7546 argc -= optind;
7547 argv += optind;
7549 if (do_list || verify_tags) {
7550 if (commit_id_arg != NULL)
7551 errx(1,
7552 "-c option can only be used when creating a tag");
7553 if (tagmsg) {
7554 if (do_list)
7555 option_conflict('l', 'm');
7556 else
7557 option_conflict('V', 'm');
7559 if (signer_id) {
7560 if (do_list)
7561 option_conflict('l', 's');
7562 else
7563 option_conflict('V', 's');
7565 if (argc > 1)
7566 usage_tag();
7567 } else if (argc != 1)
7568 usage_tag();
7570 if (argc == 1)
7571 tag_name = argv[0];
7573 #ifndef PROFILE
7574 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
7575 "sendfd unveil", NULL) == -1)
7576 err(1, "pledge");
7577 #endif
7578 cwd = getcwd(NULL, 0);
7579 if (cwd == NULL) {
7580 error = got_error_from_errno("getcwd");
7581 goto done;
7584 error = got_repo_pack_fds_open(&pack_fds);
7585 if (error != NULL)
7586 goto done;
7588 if (repo_path == NULL) {
7589 error = got_worktree_open(&worktree, cwd);
7590 if (error && error->code != GOT_ERR_NOT_WORKTREE)
7591 goto done;
7592 else
7593 error = NULL;
7594 if (worktree) {
7595 repo_path =
7596 strdup(got_worktree_get_repo_path(worktree));
7597 if (repo_path == NULL)
7598 error = got_error_from_errno("strdup");
7599 if (error)
7600 goto done;
7601 } else {
7602 repo_path = strdup(cwd);
7603 if (repo_path == NULL) {
7604 error = got_error_from_errno("strdup");
7605 goto done;
7610 if (do_list || verify_tags) {
7611 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
7612 if (error != NULL)
7613 goto done;
7614 error = get_allowed_signers(&allowed_signers, repo, worktree);
7615 if (error)
7616 goto done;
7617 error = get_revoked_signers(&revoked_signers, repo, worktree);
7618 if (error)
7619 goto done;
7620 if (worktree) {
7621 /* Release work tree lock. */
7622 got_worktree_close(worktree);
7623 worktree = NULL;
7627 * Remove "cpath" promise unless needed for signature tmpfile
7628 * creation.
7630 if (verify_tags)
7631 got_sigs_apply_unveil();
7632 else {
7633 #ifndef PROFILE
7634 if (pledge("stdio rpath wpath flock proc exec sendfd "
7635 "unveil", NULL) == -1)
7636 err(1, "pledge");
7637 #endif
7639 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
7640 if (error)
7641 goto done;
7642 error = list_tags(repo, tag_name, verify_tags, allowed_signers,
7643 revoked_signers, verbosity);
7644 } else {
7645 error = get_gitconfig_path(&gitconfig_path);
7646 if (error)
7647 goto done;
7648 error = got_repo_open(&repo, repo_path, gitconfig_path,
7649 pack_fds);
7650 if (error != NULL)
7651 goto done;
7653 error = get_author(&tagger, repo, worktree);
7654 if (error)
7655 goto done;
7656 if (signer_id == NULL)
7657 signer_id = get_signer_id(repo, worktree);
7659 if (tagmsg) {
7660 if (signer_id) {
7661 error = got_sigs_apply_unveil();
7662 if (error)
7663 goto done;
7665 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
7666 if (error)
7667 goto done;
7670 if (commit_id_arg == NULL) {
7671 struct got_reference *head_ref;
7672 struct got_object_id *commit_id;
7673 error = got_ref_open(&head_ref, repo,
7674 worktree ? got_worktree_get_head_ref_name(worktree)
7675 : GOT_REF_HEAD, 0);
7676 if (error)
7677 goto done;
7678 error = got_ref_resolve(&commit_id, repo, head_ref);
7679 got_ref_close(head_ref);
7680 if (error)
7681 goto done;
7682 error = got_object_id_str(&commit_id_str, commit_id);
7683 free(commit_id);
7684 if (error)
7685 goto done;
7688 if (worktree) {
7689 /* Release work tree lock. */
7690 got_worktree_close(worktree);
7691 worktree = NULL;
7694 error = add_tag(repo, tagger, tag_name,
7695 commit_id_str ? commit_id_str : commit_id_arg, tagmsg,
7696 signer_id, verbosity);
7698 done:
7699 if (repo) {
7700 const struct got_error *close_err = got_repo_close(repo);
7701 if (error == NULL)
7702 error = close_err;
7704 if (worktree)
7705 got_worktree_close(worktree);
7706 if (pack_fds) {
7707 const struct got_error *pack_err =
7708 got_repo_pack_fds_close(pack_fds);
7709 if (error == NULL)
7710 error = pack_err;
7712 free(cwd);
7713 free(repo_path);
7714 free(gitconfig_path);
7715 free(commit_id_str);
7716 free(tagger);
7717 free(allowed_signers);
7718 free(revoked_signers);
7719 return error;
7722 __dead static void
7723 usage_add(void)
7725 fprintf(stderr, "usage: %s add [-IR] path ...\n", getprogname());
7726 exit(1);
7729 static const struct got_error *
7730 add_progress(void *arg, unsigned char status, const char *path)
7732 while (path[0] == '/')
7733 path++;
7734 printf("%c %s\n", status, path);
7735 return NULL;
7738 static const struct got_error *
7739 cmd_add(int argc, char *argv[])
7741 const struct got_error *error = NULL;
7742 struct got_repository *repo = NULL;
7743 struct got_worktree *worktree = NULL;
7744 char *cwd = NULL;
7745 struct got_pathlist_head paths;
7746 struct got_pathlist_entry *pe;
7747 int ch, can_recurse = 0, no_ignores = 0;
7748 int *pack_fds = NULL;
7750 TAILQ_INIT(&paths);
7752 while ((ch = getopt(argc, argv, "IR")) != -1) {
7753 switch (ch) {
7754 case 'I':
7755 no_ignores = 1;
7756 break;
7757 case 'R':
7758 can_recurse = 1;
7759 break;
7760 default:
7761 usage_add();
7762 /* NOTREACHED */
7766 argc -= optind;
7767 argv += optind;
7769 #ifndef PROFILE
7770 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
7771 NULL) == -1)
7772 err(1, "pledge");
7773 #endif
7774 if (argc < 1)
7775 usage_add();
7777 cwd = getcwd(NULL, 0);
7778 if (cwd == NULL) {
7779 error = got_error_from_errno("getcwd");
7780 goto done;
7783 error = got_repo_pack_fds_open(&pack_fds);
7784 if (error != NULL)
7785 goto done;
7787 error = got_worktree_open(&worktree, cwd);
7788 if (error) {
7789 if (error->code == GOT_ERR_NOT_WORKTREE)
7790 error = wrap_not_worktree_error(error, "add", cwd);
7791 goto done;
7794 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
7795 NULL, pack_fds);
7796 if (error != NULL)
7797 goto done;
7799 error = apply_unveil(got_repo_get_path(repo), 1,
7800 got_worktree_get_root_path(worktree));
7801 if (error)
7802 goto done;
7804 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
7805 if (error)
7806 goto done;
7808 if (!can_recurse) {
7809 char *ondisk_path;
7810 struct stat sb;
7811 TAILQ_FOREACH(pe, &paths, entry) {
7812 if (asprintf(&ondisk_path, "%s/%s",
7813 got_worktree_get_root_path(worktree),
7814 pe->path) == -1) {
7815 error = got_error_from_errno("asprintf");
7816 goto done;
7818 if (lstat(ondisk_path, &sb) == -1) {
7819 if (errno == ENOENT) {
7820 free(ondisk_path);
7821 continue;
7823 error = got_error_from_errno2("lstat",
7824 ondisk_path);
7825 free(ondisk_path);
7826 goto done;
7828 free(ondisk_path);
7829 if (S_ISDIR(sb.st_mode)) {
7830 error = got_error_msg(GOT_ERR_BAD_PATH,
7831 "adding directories requires -R option");
7832 goto done;
7837 error = got_worktree_schedule_add(worktree, &paths, add_progress,
7838 NULL, repo, no_ignores);
7839 done:
7840 if (repo) {
7841 const struct got_error *close_err = got_repo_close(repo);
7842 if (error == NULL)
7843 error = close_err;
7845 if (worktree)
7846 got_worktree_close(worktree);
7847 if (pack_fds) {
7848 const struct got_error *pack_err =
7849 got_repo_pack_fds_close(pack_fds);
7850 if (error == NULL)
7851 error = pack_err;
7853 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
7854 free(cwd);
7855 return error;
7858 __dead static void
7859 usage_remove(void)
7861 fprintf(stderr, "usage: %s remove [-fkR] [-s status-codes] path ...\n",
7862 getprogname());
7863 exit(1);
7866 static const struct got_error *
7867 print_remove_status(void *arg, unsigned char status,
7868 unsigned char staged_status, const char *path)
7870 while (path[0] == '/')
7871 path++;
7872 if (status == GOT_STATUS_NONEXISTENT)
7873 return NULL;
7874 if (status == staged_status && (status == GOT_STATUS_DELETE))
7875 status = GOT_STATUS_NO_CHANGE;
7876 printf("%c%c %s\n", status, staged_status, path);
7877 return NULL;
7880 static const struct got_error *
7881 cmd_remove(int argc, char *argv[])
7883 const struct got_error *error = NULL;
7884 struct got_worktree *worktree = NULL;
7885 struct got_repository *repo = NULL;
7886 const char *status_codes = NULL;
7887 char *cwd = NULL;
7888 struct got_pathlist_head paths;
7889 struct got_pathlist_entry *pe;
7890 int ch, delete_local_mods = 0, can_recurse = 0, keep_on_disk = 0, i;
7891 int ignore_missing_paths = 0;
7892 int *pack_fds = NULL;
7894 TAILQ_INIT(&paths);
7896 while ((ch = getopt(argc, argv, "fkRs:")) != -1) {
7897 switch (ch) {
7898 case 'f':
7899 delete_local_mods = 1;
7900 ignore_missing_paths = 1;
7901 break;
7902 case 'k':
7903 keep_on_disk = 1;
7904 break;
7905 case 'R':
7906 can_recurse = 1;
7907 break;
7908 case 's':
7909 for (i = 0; i < strlen(optarg); i++) {
7910 switch (optarg[i]) {
7911 case GOT_STATUS_MODIFY:
7912 delete_local_mods = 1;
7913 break;
7914 case GOT_STATUS_MISSING:
7915 ignore_missing_paths = 1;
7916 break;
7917 default:
7918 errx(1, "invalid status code '%c'",
7919 optarg[i]);
7922 status_codes = optarg;
7923 break;
7924 default:
7925 usage_remove();
7926 /* NOTREACHED */
7930 argc -= optind;
7931 argv += optind;
7933 #ifndef PROFILE
7934 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
7935 NULL) == -1)
7936 err(1, "pledge");
7937 #endif
7938 if (argc < 1)
7939 usage_remove();
7941 cwd = getcwd(NULL, 0);
7942 if (cwd == NULL) {
7943 error = got_error_from_errno("getcwd");
7944 goto done;
7947 error = got_repo_pack_fds_open(&pack_fds);
7948 if (error != NULL)
7949 goto done;
7951 error = got_worktree_open(&worktree, cwd);
7952 if (error) {
7953 if (error->code == GOT_ERR_NOT_WORKTREE)
7954 error = wrap_not_worktree_error(error, "remove", cwd);
7955 goto done;
7958 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
7959 NULL, pack_fds);
7960 if (error)
7961 goto done;
7963 error = apply_unveil(got_repo_get_path(repo), 1,
7964 got_worktree_get_root_path(worktree));
7965 if (error)
7966 goto done;
7968 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
7969 if (error)
7970 goto done;
7972 if (!can_recurse) {
7973 char *ondisk_path;
7974 struct stat sb;
7975 TAILQ_FOREACH(pe, &paths, entry) {
7976 if (asprintf(&ondisk_path, "%s/%s",
7977 got_worktree_get_root_path(worktree),
7978 pe->path) == -1) {
7979 error = got_error_from_errno("asprintf");
7980 goto done;
7982 if (lstat(ondisk_path, &sb) == -1) {
7983 if (errno == ENOENT) {
7984 free(ondisk_path);
7985 continue;
7987 error = got_error_from_errno2("lstat",
7988 ondisk_path);
7989 free(ondisk_path);
7990 goto done;
7992 free(ondisk_path);
7993 if (S_ISDIR(sb.st_mode)) {
7994 error = got_error_msg(GOT_ERR_BAD_PATH,
7995 "removing directories requires -R option");
7996 goto done;
8001 error = got_worktree_schedule_delete(worktree, &paths,
8002 delete_local_mods, status_codes, print_remove_status, NULL,
8003 repo, keep_on_disk, ignore_missing_paths);
8004 done:
8005 if (repo) {
8006 const struct got_error *close_err = got_repo_close(repo);
8007 if (error == NULL)
8008 error = close_err;
8010 if (worktree)
8011 got_worktree_close(worktree);
8012 if (pack_fds) {
8013 const struct got_error *pack_err =
8014 got_repo_pack_fds_close(pack_fds);
8015 if (error == NULL)
8016 error = pack_err;
8018 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
8019 free(cwd);
8020 return error;
8023 __dead static void
8024 usage_patch(void)
8026 fprintf(stderr, "usage: %s patch [-nR] [-c commit] [-p strip-count] "
8027 "[patchfile]\n", getprogname());
8028 exit(1);
8031 static const struct got_error *
8032 patch_from_stdin(int *patchfd)
8034 const struct got_error *err = NULL;
8035 ssize_t r;
8036 char buf[BUFSIZ];
8037 sig_t sighup, sigint, sigquit;
8039 *patchfd = got_opentempfd();
8040 if (*patchfd == -1)
8041 return got_error_from_errno("got_opentempfd");
8043 sighup = signal(SIGHUP, SIG_DFL);
8044 sigint = signal(SIGINT, SIG_DFL);
8045 sigquit = signal(SIGQUIT, SIG_DFL);
8047 for (;;) {
8048 r = read(0, buf, sizeof(buf));
8049 if (r == -1) {
8050 err = got_error_from_errno("read");
8051 break;
8053 if (r == 0)
8054 break;
8055 if (write(*patchfd, buf, r) == -1) {
8056 err = got_error_from_errno("write");
8057 break;
8061 signal(SIGHUP, sighup);
8062 signal(SIGINT, sigint);
8063 signal(SIGQUIT, sigquit);
8065 if (err == NULL && lseek(*patchfd, 0, SEEK_SET) == -1)
8066 err = got_error_from_errno("lseek");
8068 if (err != NULL) {
8069 close(*patchfd);
8070 *patchfd = -1;
8073 return err;
8076 static const struct got_error *
8077 patch_progress(void *arg, const char *old, const char *new,
8078 unsigned char status, const struct got_error *error, int old_from,
8079 int old_lines, int new_from, int new_lines, int offset,
8080 int ws_mangled, const struct got_error *hunk_err)
8082 const char *path = new == NULL ? old : new;
8084 while (*path == '/')
8085 path++;
8087 if (status != 0)
8088 printf("%c %s\n", status, path);
8090 if (error != NULL)
8091 fprintf(stderr, "%s: %s\n", getprogname(), error->msg);
8093 if (offset != 0 || hunk_err != NULL || ws_mangled) {
8094 printf("@@ -%d,%d +%d,%d @@ ", old_from,
8095 old_lines, new_from, new_lines);
8096 if (hunk_err != NULL)
8097 printf("%s\n", hunk_err->msg);
8098 else if (offset != 0)
8099 printf("applied with offset %d\n", offset);
8100 else
8101 printf("hunk contains mangled whitespace\n");
8104 return NULL;
8107 static const struct got_error *
8108 cmd_patch(int argc, char *argv[])
8110 const struct got_error *error = NULL, *close_error = NULL;
8111 struct got_worktree *worktree = NULL;
8112 struct got_repository *repo = NULL;
8113 struct got_reflist_head refs;
8114 struct got_object_id *commit_id = NULL;
8115 const char *commit_id_str = NULL;
8116 struct stat sb;
8117 const char *errstr;
8118 char *cwd = NULL;
8119 int ch, nop = 0, strip = -1, reverse = 0;
8120 int patchfd;
8121 int *pack_fds = NULL;
8123 TAILQ_INIT(&refs);
8125 #ifndef PROFILE
8126 if (pledge("stdio rpath wpath cpath fattr proc exec sendfd flock "
8127 "unveil", NULL) == -1)
8128 err(1, "pledge");
8129 #endif
8131 while ((ch = getopt(argc, argv, "c:np:R")) != -1) {
8132 switch (ch) {
8133 case 'c':
8134 commit_id_str = optarg;
8135 break;
8136 case 'n':
8137 nop = 1;
8138 break;
8139 case 'p':
8140 strip = strtonum(optarg, 0, INT_MAX, &errstr);
8141 if (errstr != NULL)
8142 errx(1, "pathname strip count is %s: %s",
8143 errstr, optarg);
8144 break;
8145 case 'R':
8146 reverse = 1;
8147 break;
8148 default:
8149 usage_patch();
8150 /* NOTREACHED */
8154 argc -= optind;
8155 argv += optind;
8157 if (argc == 0) {
8158 error = patch_from_stdin(&patchfd);
8159 if (error)
8160 return error;
8161 } else if (argc == 1) {
8162 patchfd = open(argv[0], O_RDONLY);
8163 if (patchfd == -1) {
8164 error = got_error_from_errno2("open", argv[0]);
8165 return error;
8167 if (fstat(patchfd, &sb) == -1) {
8168 error = got_error_from_errno2("fstat", argv[0]);
8169 goto done;
8171 if (!S_ISREG(sb.st_mode)) {
8172 error = got_error_path(argv[0], GOT_ERR_BAD_FILETYPE);
8173 goto done;
8175 } else
8176 usage_patch();
8178 if ((cwd = getcwd(NULL, 0)) == NULL) {
8179 error = got_error_from_errno("getcwd");
8180 goto done;
8183 error = got_repo_pack_fds_open(&pack_fds);
8184 if (error != NULL)
8185 goto done;
8187 error = got_worktree_open(&worktree, cwd);
8188 if (error != NULL)
8189 goto done;
8191 const char *repo_path = got_worktree_get_repo_path(worktree);
8192 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
8193 if (error != NULL)
8194 goto done;
8196 error = apply_unveil(got_repo_get_path(repo), 0,
8197 got_worktree_get_root_path(worktree));
8198 if (error != NULL)
8199 goto done;
8201 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
8202 if (error)
8203 goto done;
8205 if (commit_id_str != NULL) {
8206 error = got_repo_match_object_id(&commit_id, NULL,
8207 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
8208 if (error)
8209 goto done;
8212 error = got_patch(patchfd, worktree, repo, nop, strip, reverse,
8213 commit_id, &patch_progress, NULL, check_cancelled, NULL);
8215 done:
8216 got_ref_list_free(&refs);
8217 free(commit_id);
8218 if (repo) {
8219 close_error = got_repo_close(repo);
8220 if (error == NULL)
8221 error = close_error;
8223 if (worktree != NULL) {
8224 close_error = got_worktree_close(worktree);
8225 if (error == NULL)
8226 error = close_error;
8228 if (pack_fds) {
8229 const struct got_error *pack_err =
8230 got_repo_pack_fds_close(pack_fds);
8231 if (error == NULL)
8232 error = pack_err;
8234 free(cwd);
8235 return error;
8238 __dead static void
8239 usage_revert(void)
8241 fprintf(stderr, "usage: %s revert [-pR] [-F response-script] path ...\n",
8242 getprogname());
8243 exit(1);
8246 static const struct got_error *
8247 revert_progress(void *arg, unsigned char status, const char *path)
8249 if (status == GOT_STATUS_UNVERSIONED)
8250 return NULL;
8252 while (path[0] == '/')
8253 path++;
8254 printf("%c %s\n", status, path);
8255 return NULL;
8258 struct choose_patch_arg {
8259 FILE *patch_script_file;
8260 const char *action;
8263 static const struct got_error *
8264 show_change(unsigned char status, const char *path, FILE *patch_file, int n,
8265 int nchanges, const char *action)
8267 const struct got_error *err;
8268 char *line = NULL;
8269 size_t linesize = 0;
8270 ssize_t linelen;
8272 switch (status) {
8273 case GOT_STATUS_ADD:
8274 printf("A %s\n%s this addition? [y/n] ", path, action);
8275 break;
8276 case GOT_STATUS_DELETE:
8277 printf("D %s\n%s this deletion? [y/n] ", path, action);
8278 break;
8279 case GOT_STATUS_MODIFY:
8280 if (fseek(patch_file, 0L, SEEK_SET) == -1)
8281 return got_error_from_errno("fseek");
8282 printf(GOT_COMMIT_SEP_STR);
8283 while ((linelen = getline(&line, &linesize, patch_file)) != -1)
8284 printf("%s", line);
8285 if (linelen == -1 && ferror(patch_file)) {
8286 err = got_error_from_errno("getline");
8287 free(line);
8288 return err;
8290 free(line);
8291 printf(GOT_COMMIT_SEP_STR);
8292 printf("M %s (change %d of %d)\n%s this change? [y/n/q] ",
8293 path, n, nchanges, action);
8294 break;
8295 default:
8296 return got_error_path(path, GOT_ERR_FILE_STATUS);
8299 fflush(stdout);
8300 return NULL;
8303 static const struct got_error *
8304 choose_patch(int *choice, void *arg, unsigned char status, const char *path,
8305 FILE *patch_file, int n, int nchanges)
8307 const struct got_error *err = NULL;
8308 char *line = NULL;
8309 size_t linesize = 0;
8310 ssize_t linelen;
8311 int resp = ' ';
8312 struct choose_patch_arg *a = arg;
8314 *choice = GOT_PATCH_CHOICE_NONE;
8316 if (a->patch_script_file) {
8317 char *nl;
8318 err = show_change(status, path, patch_file, n, nchanges,
8319 a->action);
8320 if (err)
8321 return err;
8322 linelen = getline(&line, &linesize, a->patch_script_file);
8323 if (linelen == -1) {
8324 if (ferror(a->patch_script_file))
8325 return got_error_from_errno("getline");
8326 return NULL;
8328 nl = strchr(line, '\n');
8329 if (nl)
8330 *nl = '\0';
8331 if (strcmp(line, "y") == 0) {
8332 *choice = GOT_PATCH_CHOICE_YES;
8333 printf("y\n");
8334 } else if (strcmp(line, "n") == 0) {
8335 *choice = GOT_PATCH_CHOICE_NO;
8336 printf("n\n");
8337 } else if (strcmp(line, "q") == 0 &&
8338 status == GOT_STATUS_MODIFY) {
8339 *choice = GOT_PATCH_CHOICE_QUIT;
8340 printf("q\n");
8341 } else
8342 printf("invalid response '%s'\n", line);
8343 free(line);
8344 return NULL;
8347 while (resp != 'y' && resp != 'n' && resp != 'q') {
8348 err = show_change(status, path, patch_file, n, nchanges,
8349 a->action);
8350 if (err)
8351 return err;
8352 resp = getchar();
8353 if (resp == '\n')
8354 resp = getchar();
8355 if (status == GOT_STATUS_MODIFY) {
8356 if (resp != 'y' && resp != 'n' && resp != 'q') {
8357 printf("invalid response '%c'\n", resp);
8358 resp = ' ';
8360 } else if (resp != 'y' && resp != 'n') {
8361 printf("invalid response '%c'\n", resp);
8362 resp = ' ';
8366 if (resp == 'y')
8367 *choice = GOT_PATCH_CHOICE_YES;
8368 else if (resp == 'n')
8369 *choice = GOT_PATCH_CHOICE_NO;
8370 else if (resp == 'q' && status == GOT_STATUS_MODIFY)
8371 *choice = GOT_PATCH_CHOICE_QUIT;
8373 return NULL;
8376 struct wt_commitable_path_arg {
8377 struct got_pathlist_head *commit_paths;
8378 int *has_changes;
8382 * Shortcut work tree status callback to determine if the set of paths scanned
8383 * has at least one versioned path that is being modified and, if not NULL, is
8384 * in the arg->commit_paths list. Set arg and return GOT_ERR_FILE_MODIFIED as
8385 * soon as a path is passed with a status that satisfies this criteria.
8387 static const struct got_error *
8388 worktree_has_commitable_path(void *arg, unsigned char status,
8389 unsigned char staged_status, const char *path,
8390 struct got_object_id *blob_id, struct got_object_id *staged_blob_id,
8391 struct got_object_id *commit_id, int dirfd, const char *de_name)
8393 struct wt_commitable_path_arg *a = arg;
8395 if (status == staged_status && (status == GOT_STATUS_DELETE))
8396 status = GOT_STATUS_NO_CHANGE;
8398 if (!(status == GOT_STATUS_NO_CHANGE ||
8399 status == GOT_STATUS_UNVERSIONED) ||
8400 staged_status != GOT_STATUS_NO_CHANGE) {
8401 if (a->commit_paths != NULL) {
8402 struct got_pathlist_entry *pe;
8404 TAILQ_FOREACH(pe, a->commit_paths, entry) {
8405 if (strncmp(path, pe->path,
8406 pe->path_len) == 0) {
8407 *a->has_changes = 1;
8408 break;
8411 } else
8412 *a->has_changes = 1;
8414 if (*a->has_changes)
8415 return got_error(GOT_ERR_FILE_MODIFIED);
8418 return NULL;
8422 * Check that the changeset of the commit identified by id is
8423 * comprised of at least one modified path that is being committed.
8425 static const struct got_error *
8426 commit_path_changed_in_worktree(struct wt_commitable_path_arg *wcpa,
8427 struct got_object_id *id, struct got_worktree *worktree,
8428 struct got_repository *repo)
8430 const struct got_error *err;
8431 struct got_pathlist_head paths;
8432 struct got_commit_object *commit = NULL, *pcommit = NULL;
8433 struct got_tree_object *tree = NULL, *ptree = NULL;
8434 struct got_object_qid *pid;
8436 TAILQ_INIT(&paths);
8438 err = got_object_open_as_commit(&commit, repo, id);
8439 if (err)
8440 goto done;
8442 err = got_object_open_as_tree(&tree, repo,
8443 got_object_commit_get_tree_id(commit));
8444 if (err)
8445 goto done;
8447 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
8448 if (pid != NULL) {
8449 err = got_object_open_as_commit(&pcommit, repo, &pid->id);
8450 if (err)
8451 goto done;
8453 err = got_object_open_as_tree(&ptree, repo,
8454 got_object_commit_get_tree_id(pcommit));
8455 if (err)
8456 goto done;
8459 err = got_diff_tree(ptree, tree, NULL, NULL, -1, -1, "", "", repo,
8460 got_diff_tree_collect_changed_paths, &paths, 0);
8461 if (err)
8462 goto done;
8464 err = got_worktree_status(worktree, &paths, repo, 0,
8465 worktree_has_commitable_path, wcpa, check_cancelled, NULL);
8466 if (err && err->code == GOT_ERR_FILE_MODIFIED) {
8468 * At least one changed path in the referenced commit is
8469 * modified in the work tree, that's all we need to know!
8471 err = NULL;
8474 done:
8475 got_pathlist_free(&paths, GOT_PATHLIST_FREE_ALL);
8476 if (commit)
8477 got_object_commit_close(commit);
8478 if (pcommit)
8479 got_object_commit_close(pcommit);
8480 if (tree)
8481 got_object_tree_close(tree);
8482 if (ptree)
8483 got_object_tree_close(ptree);
8484 return err;
8488 * Remove any "logmsg" reference comprised entirely of paths that have
8489 * been reverted in this work tree. If any path in the logmsg ref changeset
8490 * remains in a changed state in the worktree, do not remove the reference.
8492 static const struct got_error *
8493 rm_logmsg_ref(struct got_worktree *worktree, struct got_repository *repo)
8495 const struct got_error *err;
8496 struct got_reflist_head refs;
8497 struct got_reflist_entry *re;
8498 struct got_commit_object *commit = NULL;
8499 struct got_object_id *commit_id = NULL;
8500 struct wt_commitable_path_arg wcpa;
8501 char *uuidstr = NULL;
8503 TAILQ_INIT(&refs);
8505 err = got_worktree_get_uuid(&uuidstr, worktree);
8506 if (err)
8507 goto done;
8509 err = got_ref_list(&refs, repo, "refs/got/worktree",
8510 got_ref_cmp_by_name, repo);
8511 if (err)
8512 goto done;
8514 TAILQ_FOREACH(re, &refs, entry) {
8515 const char *refname;
8516 int has_changes = 0;
8518 refname = got_ref_get_name(re->ref);
8520 if (!strncmp(refname, GOT_WORKTREE_CHERRYPICK_REF_PREFIX,
8521 GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN))
8522 refname += GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN + 1;
8523 else if (!strncmp(refname, GOT_WORKTREE_BACKOUT_REF_PREFIX,
8524 GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN))
8525 refname += GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN + 1;
8526 else
8527 continue;
8529 if (strncmp(refname, uuidstr, GOT_WORKTREE_UUID_STRLEN) == 0)
8530 refname += GOT_WORKTREE_UUID_STRLEN + 1; /* skip '-' */
8531 else
8532 continue;
8534 err = got_repo_match_object_id(&commit_id, NULL, refname,
8535 GOT_OBJ_TYPE_COMMIT, NULL, repo);
8536 if (err)
8537 goto done;
8539 err = got_object_open_as_commit(&commit, repo, commit_id);
8540 if (err)
8541 goto done;
8543 wcpa.commit_paths = NULL;
8544 wcpa.has_changes = &has_changes;
8546 err = commit_path_changed_in_worktree(&wcpa, commit_id,
8547 worktree, repo);
8548 if (err)
8549 goto done;
8551 if (!has_changes) {
8552 err = got_ref_delete(re->ref, repo);
8553 if (err)
8554 goto done;
8557 got_object_commit_close(commit);
8558 commit = NULL;
8559 free(commit_id);
8560 commit_id = NULL;
8563 done:
8564 free(uuidstr);
8565 free(commit_id);
8566 got_ref_list_free(&refs);
8567 if (commit)
8568 got_object_commit_close(commit);
8569 return err;
8572 static const struct got_error *
8573 cmd_revert(int argc, char *argv[])
8575 const struct got_error *error = NULL;
8576 struct got_worktree *worktree = NULL;
8577 struct got_repository *repo = NULL;
8578 char *cwd = NULL, *path = NULL;
8579 struct got_pathlist_head paths;
8580 struct got_pathlist_entry *pe;
8581 int ch, can_recurse = 0, pflag = 0;
8582 FILE *patch_script_file = NULL;
8583 const char *patch_script_path = NULL;
8584 struct choose_patch_arg cpa;
8585 int *pack_fds = NULL;
8587 TAILQ_INIT(&paths);
8589 while ((ch = getopt(argc, argv, "F:pR")) != -1) {
8590 switch (ch) {
8591 case 'F':
8592 patch_script_path = optarg;
8593 break;
8594 case 'p':
8595 pflag = 1;
8596 break;
8597 case 'R':
8598 can_recurse = 1;
8599 break;
8600 default:
8601 usage_revert();
8602 /* NOTREACHED */
8606 argc -= optind;
8607 argv += optind;
8609 #ifndef PROFILE
8610 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
8611 "unveil", NULL) == -1)
8612 err(1, "pledge");
8613 #endif
8614 if (argc < 1)
8615 usage_revert();
8616 if (patch_script_path && !pflag)
8617 errx(1, "-F option can only be used together with -p option");
8619 cwd = getcwd(NULL, 0);
8620 if (cwd == NULL) {
8621 error = got_error_from_errno("getcwd");
8622 goto done;
8625 error = got_repo_pack_fds_open(&pack_fds);
8626 if (error != NULL)
8627 goto done;
8629 error = got_worktree_open(&worktree, cwd);
8630 if (error) {
8631 if (error->code == GOT_ERR_NOT_WORKTREE)
8632 error = wrap_not_worktree_error(error, "revert", cwd);
8633 goto done;
8636 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
8637 NULL, pack_fds);
8638 if (error != NULL)
8639 goto done;
8641 if (patch_script_path) {
8642 patch_script_file = fopen(patch_script_path, "re");
8643 if (patch_script_file == NULL) {
8644 error = got_error_from_errno2("fopen",
8645 patch_script_path);
8646 goto done;
8651 * XXX "c" perm needed on repo dir to delete merge references.
8653 error = apply_unveil(got_repo_get_path(repo), 0,
8654 got_worktree_get_root_path(worktree));
8655 if (error)
8656 goto done;
8658 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
8659 if (error)
8660 goto done;
8662 if (!can_recurse) {
8663 char *ondisk_path;
8664 struct stat sb;
8665 TAILQ_FOREACH(pe, &paths, entry) {
8666 if (asprintf(&ondisk_path, "%s/%s",
8667 got_worktree_get_root_path(worktree),
8668 pe->path) == -1) {
8669 error = got_error_from_errno("asprintf");
8670 goto done;
8672 if (lstat(ondisk_path, &sb) == -1) {
8673 if (errno == ENOENT) {
8674 free(ondisk_path);
8675 continue;
8677 error = got_error_from_errno2("lstat",
8678 ondisk_path);
8679 free(ondisk_path);
8680 goto done;
8682 free(ondisk_path);
8683 if (S_ISDIR(sb.st_mode)) {
8684 error = got_error_msg(GOT_ERR_BAD_PATH,
8685 "reverting directories requires -R option");
8686 goto done;
8691 cpa.patch_script_file = patch_script_file;
8692 cpa.action = "revert";
8693 error = got_worktree_revert(worktree, &paths, revert_progress, NULL,
8694 pflag ? choose_patch : NULL, &cpa, repo);
8696 error = rm_logmsg_ref(worktree, repo);
8697 done:
8698 if (patch_script_file && fclose(patch_script_file) == EOF &&
8699 error == NULL)
8700 error = got_error_from_errno2("fclose", patch_script_path);
8701 if (repo) {
8702 const struct got_error *close_err = got_repo_close(repo);
8703 if (error == NULL)
8704 error = close_err;
8706 if (worktree)
8707 got_worktree_close(worktree);
8708 if (pack_fds) {
8709 const struct got_error *pack_err =
8710 got_repo_pack_fds_close(pack_fds);
8711 if (error == NULL)
8712 error = pack_err;
8714 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
8715 free(path);
8716 free(cwd);
8717 return error;
8720 __dead static void
8721 usage_commit(void)
8723 fprintf(stderr, "usage: %s commit [-NS] [-A author] [-F path] "
8724 "[-m message] [path ...]\n", getprogname());
8725 exit(1);
8728 struct collect_commit_logmsg_arg {
8729 const char *cmdline_log;
8730 const char *prepared_log;
8731 const char *merged_log;
8732 int non_interactive;
8733 const char *editor;
8734 const char *worktree_path;
8735 const char *branch_name;
8736 const char *repo_path;
8737 char *logmsg_path;
8741 static const struct got_error *
8742 read_prepared_logmsg(char **logmsg, const char *path)
8744 const struct got_error *err = NULL;
8745 FILE *f = NULL;
8746 struct stat sb;
8747 size_t r;
8749 *logmsg = NULL;
8750 memset(&sb, 0, sizeof(sb));
8752 f = fopen(path, "re");
8753 if (f == NULL)
8754 return got_error_from_errno2("fopen", path);
8756 if (fstat(fileno(f), &sb) == -1) {
8757 err = got_error_from_errno2("fstat", path);
8758 goto done;
8760 if (sb.st_size == 0) {
8761 err = got_error(GOT_ERR_COMMIT_MSG_EMPTY);
8762 goto done;
8765 *logmsg = malloc(sb.st_size + 1);
8766 if (*logmsg == NULL) {
8767 err = got_error_from_errno("malloc");
8768 goto done;
8771 r = fread(*logmsg, 1, sb.st_size, f);
8772 if (r != sb.st_size) {
8773 if (ferror(f))
8774 err = got_error_from_errno2("fread", path);
8775 else
8776 err = got_error(GOT_ERR_IO);
8777 goto done;
8779 (*logmsg)[sb.st_size] = '\0';
8780 done:
8781 if (fclose(f) == EOF && err == NULL)
8782 err = got_error_from_errno2("fclose", path);
8783 if (err) {
8784 free(*logmsg);
8785 *logmsg = NULL;
8787 return err;
8790 static const struct got_error *
8791 collect_commit_logmsg(struct got_pathlist_head *commitable_paths,
8792 const char *diff_path, char **logmsg, void *arg)
8794 char *initial_content = NULL;
8795 struct got_pathlist_entry *pe;
8796 const struct got_error *err = NULL;
8797 char *template = NULL;
8798 char *prepared_msg = NULL, *merged_msg = NULL;
8799 struct collect_commit_logmsg_arg *a = arg;
8800 int initial_content_len;
8801 int fd = -1;
8802 size_t len;
8804 /* if a message was specified on the command line, just use it */
8805 if (a->cmdline_log != NULL && strlen(a->cmdline_log) != 0) {
8806 len = strlen(a->cmdline_log) + 1;
8807 *logmsg = malloc(len + 1);
8808 if (*logmsg == NULL)
8809 return got_error_from_errno("malloc");
8810 strlcpy(*logmsg, a->cmdline_log, len);
8811 return NULL;
8812 } else if (a->prepared_log != NULL && a->non_interactive)
8813 return read_prepared_logmsg(logmsg, a->prepared_log);
8815 if (asprintf(&template, "%s/logmsg", a->worktree_path) == -1)
8816 return got_error_from_errno("asprintf");
8818 err = got_opentemp_named_fd(&a->logmsg_path, &fd, template, "");
8819 if (err)
8820 goto done;
8822 if (a->prepared_log) {
8823 err = read_prepared_logmsg(&prepared_msg, a->prepared_log);
8824 if (err)
8825 goto done;
8826 } else if (a->merged_log) {
8827 err = read_prepared_logmsg(&merged_msg, a->merged_log);
8828 if (err)
8829 goto done;
8832 initial_content_len = asprintf(&initial_content,
8833 "%s%s\n# changes to be committed on branch %s:\n",
8834 prepared_msg ? prepared_msg : "",
8835 merged_msg ? merged_msg : "", a->branch_name);
8836 if (initial_content_len == -1) {
8837 err = got_error_from_errno("asprintf");
8838 goto done;
8841 if (write(fd, initial_content, initial_content_len) == -1) {
8842 err = got_error_from_errno2("write", a->logmsg_path);
8843 goto done;
8846 TAILQ_FOREACH(pe, commitable_paths, entry) {
8847 struct got_commitable *ct = pe->data;
8848 dprintf(fd, "# %c %s\n",
8849 got_commitable_get_status(ct),
8850 got_commitable_get_path(ct));
8853 if (diff_path) {
8854 dprintf(fd, "# detailed changes can be viewed in %s\n",
8855 diff_path);
8858 err = edit_logmsg(logmsg, a->editor, a->logmsg_path, initial_content,
8859 initial_content_len, a->prepared_log ? 0 : 1);
8860 done:
8861 free(initial_content);
8862 free(template);
8863 free(prepared_msg);
8864 free(merged_msg);
8866 if (fd != -1 && close(fd) == -1 && err == NULL)
8867 err = got_error_from_errno2("close", a->logmsg_path);
8869 /* Editor is done; we can now apply unveil(2) */
8870 if (err == NULL)
8871 err = apply_unveil(a->repo_path, 0, a->worktree_path);
8872 if (err) {
8873 free(*logmsg);
8874 *logmsg = NULL;
8876 return err;
8879 static const struct got_error *
8880 cat_logmsg(FILE *f, struct got_commit_object *commit, const char *idstr,
8881 const char *type, int has_content)
8883 const struct got_error *err = NULL;
8884 char *logmsg = NULL;
8886 err = got_object_commit_get_logmsg(&logmsg, commit);
8887 if (err)
8888 return err;
8890 if (fprintf(f, "%s# log message of %s commit %s:%s",
8891 has_content ? "\n" : "", type, idstr, logmsg) < 0)
8892 err = got_ferror(f, GOT_ERR_IO);
8894 free(logmsg);
8895 return err;
8899 * Lookup "logmsg" references of backed-out and cherrypicked commits
8900 * belonging to the current work tree. If found, and the worktree has
8901 * at least one modified file that was changed in the referenced commit,
8902 * add its log message to a new temporary file at *logmsg_path.
8903 * Add all refs found to matched_refs to be scheduled for removal on
8904 * successful commit.
8906 static const struct got_error *
8907 lookup_logmsg_ref(char **logmsg_path, struct got_pathlist_head *paths,
8908 struct got_reflist_head *matched_refs, struct got_worktree *worktree,
8909 struct got_repository *repo)
8911 const struct got_error *err;
8912 struct got_commit_object *commit = NULL;
8913 struct got_object_id *id = NULL;
8914 struct got_reflist_head refs;
8915 struct got_reflist_entry *re, *re_match;
8916 FILE *f = NULL;
8917 char *uuidstr = NULL;
8918 int added_logmsg = 0;
8920 TAILQ_INIT(&refs);
8922 *logmsg_path = NULL;
8924 err = got_worktree_get_uuid(&uuidstr, worktree);
8925 if (err)
8926 goto done;
8928 err = got_ref_list(&refs, repo, "refs/got/worktree",
8929 got_ref_cmp_by_name, repo);
8930 if (err)
8931 goto done;
8933 TAILQ_FOREACH(re, &refs, entry) {
8934 const char *refname, *type;
8935 struct wt_commitable_path_arg wcpa;
8936 int add_logmsg = 0;
8938 refname = got_ref_get_name(re->ref);
8940 if (strncmp(refname, GOT_WORKTREE_CHERRYPICK_REF_PREFIX,
8941 GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN) == 0) {
8942 refname += GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN + 1;
8943 type = "cherrypicked";
8944 } else if (strncmp(refname, GOT_WORKTREE_BACKOUT_REF_PREFIX,
8945 GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN) == 0) {
8946 refname += GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN + 1;
8947 type = "backed-out";
8948 } else
8949 continue;
8951 if (strncmp(refname, uuidstr, GOT_WORKTREE_UUID_STRLEN) == 0)
8952 refname += GOT_WORKTREE_UUID_STRLEN + 1; /* skip '-' */
8953 else
8954 continue;
8956 err = got_repo_match_object_id(&id, NULL, refname,
8957 GOT_OBJ_TYPE_COMMIT, NULL, repo);
8958 if (err)
8959 goto done;
8961 err = got_object_open_as_commit(&commit, repo, id);
8962 if (err)
8963 goto done;
8965 wcpa.commit_paths = paths;
8966 wcpa.has_changes = &add_logmsg;
8968 err = commit_path_changed_in_worktree(&wcpa, id,
8969 worktree, repo);
8970 if (err)
8971 goto done;
8973 if (add_logmsg) {
8974 if (f == NULL) {
8975 err = got_opentemp_named(logmsg_path, &f,
8976 "got-commit-logmsg", "");
8977 if (err)
8978 goto done;
8980 err = cat_logmsg(f, commit, refname, type,
8981 added_logmsg);
8982 if (err)
8983 goto done;
8984 if (!added_logmsg)
8985 ++added_logmsg;
8987 err = got_reflist_entry_dup(&re_match, re);
8988 if (err)
8989 goto done;
8990 TAILQ_INSERT_HEAD(matched_refs, re_match, entry);
8993 got_object_commit_close(commit);
8994 commit = NULL;
8995 free(id);
8996 id = NULL;
8999 done:
9000 free(id);
9001 free(uuidstr);
9002 got_ref_list_free(&refs);
9003 if (commit)
9004 got_object_commit_close(commit);
9005 if (f && fclose(f) == EOF && err == NULL)
9006 err = got_error_from_errno("fclose");
9007 if (!added_logmsg) {
9008 if (*logmsg_path && unlink(*logmsg_path) != 0 && err == NULL)
9009 err = got_error_from_errno2("unlink", *logmsg_path);
9010 *logmsg_path = NULL;
9012 return err;
9015 static const struct got_error *
9016 cmd_commit(int argc, char *argv[])
9018 const struct got_error *error = NULL;
9019 struct got_worktree *worktree = NULL;
9020 struct got_repository *repo = NULL;
9021 char *cwd = NULL, *id_str = NULL;
9022 struct got_object_id *id = NULL;
9023 const char *logmsg = NULL;
9024 char *prepared_logmsg = NULL, *merged_logmsg = NULL;
9025 struct collect_commit_logmsg_arg cl_arg;
9026 const char *author = NULL;
9027 char *gitconfig_path = NULL, *editor = NULL, *committer = NULL;
9028 int ch, rebase_in_progress, histedit_in_progress, preserve_logmsg = 0;
9029 int allow_bad_symlinks = 0, non_interactive = 0, merge_in_progress = 0;
9030 int show_diff = 1;
9031 struct got_pathlist_head paths;
9032 struct got_reflist_head refs;
9033 struct got_reflist_entry *re;
9034 int *pack_fds = NULL;
9036 TAILQ_INIT(&refs);
9037 TAILQ_INIT(&paths);
9038 cl_arg.logmsg_path = NULL;
9040 while ((ch = getopt(argc, argv, "A:F:m:NnS")) != -1) {
9041 switch (ch) {
9042 case 'A':
9043 author = optarg;
9044 error = valid_author(author);
9045 if (error)
9046 return error;
9047 break;
9048 case 'F':
9049 if (logmsg != NULL)
9050 option_conflict('F', 'm');
9051 prepared_logmsg = realpath(optarg, NULL);
9052 if (prepared_logmsg == NULL)
9053 return got_error_from_errno2("realpath",
9054 optarg);
9055 break;
9056 case 'm':
9057 if (prepared_logmsg)
9058 option_conflict('m', 'F');
9059 logmsg = optarg;
9060 break;
9061 case 'N':
9062 non_interactive = 1;
9063 break;
9064 case 'n':
9065 show_diff = 0;
9066 break;
9067 case 'S':
9068 allow_bad_symlinks = 1;
9069 break;
9070 default:
9071 usage_commit();
9072 /* NOTREACHED */
9076 argc -= optind;
9077 argv += optind;
9079 #ifndef PROFILE
9080 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
9081 "unveil", NULL) == -1)
9082 err(1, "pledge");
9083 #endif
9084 cwd = getcwd(NULL, 0);
9085 if (cwd == NULL) {
9086 error = got_error_from_errno("getcwd");
9087 goto done;
9090 error = got_repo_pack_fds_open(&pack_fds);
9091 if (error != NULL)
9092 goto done;
9094 error = got_worktree_open(&worktree, cwd);
9095 if (error) {
9096 if (error->code == GOT_ERR_NOT_WORKTREE)
9097 error = wrap_not_worktree_error(error, "commit", cwd);
9098 goto done;
9101 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
9102 if (error)
9103 goto done;
9104 if (rebase_in_progress) {
9105 error = got_error(GOT_ERR_REBASING);
9106 goto done;
9109 error = got_worktree_histedit_in_progress(&histedit_in_progress,
9110 worktree);
9111 if (error)
9112 goto done;
9114 error = get_gitconfig_path(&gitconfig_path);
9115 if (error)
9116 goto done;
9117 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
9118 gitconfig_path, pack_fds);
9119 if (error != NULL)
9120 goto done;
9122 error = got_worktree_merge_in_progress(&merge_in_progress, worktree, repo);
9123 if (error)
9124 goto done;
9125 if (merge_in_progress) {
9126 error = got_error(GOT_ERR_MERGE_BUSY);
9127 goto done;
9130 error = get_author(&committer, repo, worktree);
9131 if (error)
9132 goto done;
9134 if (author != NULL && !strcmp(committer, author)) {
9135 error = got_error(GOT_ERR_COMMIT_REDUNDANT_AUTHOR);
9136 goto done;
9139 if (author == NULL)
9140 author = committer;
9143 * unveil(2) traverses exec(2); if an editor is used we have
9144 * to apply unveil after the log message has been written.
9146 if (logmsg == NULL || strlen(logmsg) == 0)
9147 error = get_editor(&editor);
9148 else
9149 error = apply_unveil(got_repo_get_path(repo), 0,
9150 got_worktree_get_root_path(worktree));
9151 if (error)
9152 goto done;
9154 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
9155 if (error)
9156 goto done;
9158 if (prepared_logmsg == NULL) {
9159 error = lookup_logmsg_ref(&merged_logmsg,
9160 argc > 0 ? &paths : NULL, &refs, worktree, repo);
9161 if (error)
9162 goto done;
9165 cl_arg.editor = editor;
9166 cl_arg.cmdline_log = logmsg;
9167 cl_arg.prepared_log = prepared_logmsg;
9168 cl_arg.merged_log = merged_logmsg;
9169 cl_arg.non_interactive = non_interactive;
9170 cl_arg.worktree_path = got_worktree_get_root_path(worktree);
9171 cl_arg.branch_name = got_worktree_get_head_ref_name(worktree);
9172 if (!histedit_in_progress) {
9173 if (strncmp(cl_arg.branch_name, "refs/heads/", 11) != 0) {
9174 error = got_error(GOT_ERR_COMMIT_BRANCH);
9175 goto done;
9177 cl_arg.branch_name += 11;
9179 cl_arg.repo_path = got_repo_get_path(repo);
9180 error = got_worktree_commit(&id, worktree, &paths, author, committer,
9181 allow_bad_symlinks, show_diff, collect_commit_logmsg, &cl_arg,
9182 print_status, NULL, repo);
9183 if (error) {
9184 if (error->code != GOT_ERR_COMMIT_MSG_EMPTY &&
9185 cl_arg.logmsg_path != NULL)
9186 preserve_logmsg = 1;
9187 goto done;
9190 error = got_object_id_str(&id_str, id);
9191 if (error)
9192 goto done;
9193 printf("Created commit %s\n", id_str);
9195 TAILQ_FOREACH(re, &refs, entry) {
9196 error = got_ref_delete(re->ref, repo);
9197 if (error)
9198 goto done;
9201 done:
9202 if (preserve_logmsg) {
9203 fprintf(stderr, "%s: log message preserved in %s\n",
9204 getprogname(), cl_arg.logmsg_path);
9205 } else if (cl_arg.logmsg_path && unlink(cl_arg.logmsg_path) == -1 &&
9206 error == NULL)
9207 error = got_error_from_errno2("unlink", cl_arg.logmsg_path);
9208 free(cl_arg.logmsg_path);
9209 if (merged_logmsg && unlink(merged_logmsg) == -1 && error == NULL)
9210 error = got_error_from_errno2("unlink", merged_logmsg);
9211 free(merged_logmsg);
9212 if (repo) {
9213 const struct got_error *close_err = got_repo_close(repo);
9214 if (error == NULL)
9215 error = close_err;
9217 if (worktree)
9218 got_worktree_close(worktree);
9219 if (pack_fds) {
9220 const struct got_error *pack_err =
9221 got_repo_pack_fds_close(pack_fds);
9222 if (error == NULL)
9223 error = pack_err;
9225 got_ref_list_free(&refs);
9226 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
9227 free(cwd);
9228 free(id_str);
9229 free(gitconfig_path);
9230 free(editor);
9231 free(committer);
9232 free(prepared_logmsg);
9233 return error;
9236 __dead static void
9237 usage_send(void)
9239 fprintf(stderr, "usage: %s send [-afqTv] [-b branch] [-d branch] "
9240 "[-r repository-path] [-t tag] [remote-repository]\n",
9241 getprogname());
9242 exit(1);
9245 static void
9246 print_load_info(int print_colored, int print_found, int print_trees,
9247 int ncolored, int nfound, int ntrees)
9249 if (print_colored) {
9250 printf("%d commit%s colored", ncolored,
9251 ncolored == 1 ? "" : "s");
9253 if (print_found) {
9254 printf("%s%d object%s found",
9255 ncolored > 0 ? "; " : "",
9256 nfound, nfound == 1 ? "" : "s");
9258 if (print_trees) {
9259 printf("; %d tree%s scanned", ntrees,
9260 ntrees == 1 ? "" : "s");
9264 struct got_send_progress_arg {
9265 char last_scaled_packsize[FMT_SCALED_STRSIZE];
9266 int verbosity;
9267 int last_ncolored;
9268 int last_nfound;
9269 int last_ntrees;
9270 int loading_done;
9271 int last_ncommits;
9272 int last_nobj_total;
9273 int last_p_deltify;
9274 int last_p_written;
9275 int last_p_sent;
9276 int printed_something;
9277 int sent_something;
9278 struct got_pathlist_head *delete_branches;
9281 static const struct got_error *
9282 send_progress(void *arg, int ncolored, int nfound, int ntrees,
9283 off_t packfile_size, int ncommits, int nobj_total, int nobj_deltify,
9284 int nobj_written, off_t bytes_sent, const char *refname,
9285 const char *errmsg, int success)
9287 struct got_send_progress_arg *a = arg;
9288 char scaled_packsize[FMT_SCALED_STRSIZE];
9289 char scaled_sent[FMT_SCALED_STRSIZE];
9290 int p_deltify = 0, p_written = 0, p_sent = 0;
9291 int print_colored = 0, print_found = 0, print_trees = 0;
9292 int print_searching = 0, print_total = 0;
9293 int print_deltify = 0, print_written = 0, print_sent = 0;
9295 if (a->verbosity < 0)
9296 return NULL;
9298 if (refname) {
9299 const char *status = success ? "accepted" : "rejected";
9301 if (success) {
9302 struct got_pathlist_entry *pe;
9303 TAILQ_FOREACH(pe, a->delete_branches, entry) {
9304 const char *branchname = pe->path;
9305 if (got_path_cmp(branchname, refname,
9306 strlen(branchname), strlen(refname)) == 0) {
9307 status = "deleted";
9308 a->sent_something = 1;
9309 break;
9314 if (a->printed_something)
9315 putchar('\n');
9316 printf("Server has %s %s", status, refname);
9317 if (errmsg)
9318 printf(": %s", errmsg);
9319 a->printed_something = 1;
9320 return NULL;
9323 if (a->last_ncolored != ncolored) {
9324 print_colored = 1;
9325 a->last_ncolored = ncolored;
9328 if (a->last_nfound != nfound) {
9329 print_colored = 1;
9330 print_found = 1;
9331 a->last_nfound = nfound;
9334 if (a->last_ntrees != ntrees) {
9335 print_colored = 1;
9336 print_found = 1;
9337 print_trees = 1;
9338 a->last_ntrees = ntrees;
9341 if ((print_colored || print_found || print_trees) &&
9342 !a->loading_done) {
9343 printf("\r");
9344 print_load_info(print_colored, print_found, print_trees,
9345 ncolored, nfound, ntrees);
9346 a->printed_something = 1;
9347 fflush(stdout);
9348 return NULL;
9349 } else if (!a->loading_done) {
9350 printf("\r");
9351 print_load_info(1, 1, 1, ncolored, nfound, ntrees);
9352 printf("\n");
9353 a->loading_done = 1;
9356 if (fmt_scaled(packfile_size, scaled_packsize) == -1)
9357 return got_error_from_errno("fmt_scaled");
9358 if (fmt_scaled(bytes_sent, scaled_sent) == -1)
9359 return got_error_from_errno("fmt_scaled");
9361 if (a->last_ncommits != ncommits) {
9362 print_searching = 1;
9363 a->last_ncommits = ncommits;
9366 if (a->last_nobj_total != nobj_total) {
9367 print_searching = 1;
9368 print_total = 1;
9369 a->last_nobj_total = nobj_total;
9372 if (packfile_size > 0 && (a->last_scaled_packsize[0] == '\0' ||
9373 strcmp(scaled_packsize, a->last_scaled_packsize)) != 0) {
9374 if (strlcpy(a->last_scaled_packsize, scaled_packsize,
9375 FMT_SCALED_STRSIZE) >= FMT_SCALED_STRSIZE)
9376 return got_error(GOT_ERR_NO_SPACE);
9379 if (nobj_deltify > 0 || nobj_written > 0) {
9380 if (nobj_deltify > 0) {
9381 p_deltify = (nobj_deltify * 100) / nobj_total;
9382 if (p_deltify != a->last_p_deltify) {
9383 a->last_p_deltify = p_deltify;
9384 print_searching = 1;
9385 print_total = 1;
9386 print_deltify = 1;
9389 if (nobj_written > 0) {
9390 p_written = (nobj_written * 100) / nobj_total;
9391 if (p_written != a->last_p_written) {
9392 a->last_p_written = p_written;
9393 print_searching = 1;
9394 print_total = 1;
9395 print_deltify = 1;
9396 print_written = 1;
9401 if (bytes_sent > 0) {
9402 p_sent = (bytes_sent * 100) / packfile_size;
9403 if (p_sent != a->last_p_sent) {
9404 a->last_p_sent = p_sent;
9405 print_searching = 1;
9406 print_total = 1;
9407 print_deltify = 1;
9408 print_written = 1;
9409 print_sent = 1;
9411 a->sent_something = 1;
9414 if (print_searching || print_total || print_deltify || print_written ||
9415 print_sent)
9416 printf("\r");
9417 if (print_searching)
9418 printf("packing %d reference%s", ncommits,
9419 ncommits == 1 ? "" : "s");
9420 if (print_total)
9421 printf("; %d object%s", nobj_total,
9422 nobj_total == 1 ? "" : "s");
9423 if (print_deltify)
9424 printf("; deltify: %d%%", p_deltify);
9425 if (print_sent)
9426 printf("; uploading pack: %*s %d%%", FMT_SCALED_STRSIZE - 2,
9427 scaled_packsize, p_sent);
9428 else if (print_written)
9429 printf("; writing pack: %*s %d%%", FMT_SCALED_STRSIZE - 2,
9430 scaled_packsize, p_written);
9431 if (print_searching || print_total || print_deltify ||
9432 print_written || print_sent) {
9433 a->printed_something = 1;
9434 fflush(stdout);
9436 return NULL;
9439 static const struct got_error *
9440 cmd_send(int argc, char *argv[])
9442 const struct got_error *error = NULL;
9443 char *cwd = NULL, *repo_path = NULL;
9444 const char *remote_name;
9445 char *proto = NULL, *host = NULL, *port = NULL;
9446 char *repo_name = NULL, *server_path = NULL;
9447 const struct got_remote_repo *remotes, *remote = NULL;
9448 int nremotes, nbranches = 0, ndelete_branches = 0;
9449 struct got_repository *repo = NULL;
9450 struct got_worktree *worktree = NULL;
9451 const struct got_gotconfig *repo_conf = NULL, *worktree_conf = NULL;
9452 struct got_pathlist_head branches;
9453 struct got_pathlist_head tags;
9454 struct got_reflist_head all_branches;
9455 struct got_reflist_head all_tags;
9456 struct got_pathlist_head delete_args;
9457 struct got_pathlist_head delete_branches;
9458 struct got_reflist_entry *re;
9459 struct got_pathlist_entry *pe;
9460 int i, ch, sendfd = -1, sendstatus;
9461 pid_t sendpid = -1;
9462 struct got_send_progress_arg spa;
9463 int verbosity = 0, overwrite_refs = 0;
9464 int send_all_branches = 0, send_all_tags = 0;
9465 struct got_reference *ref = NULL;
9466 int *pack_fds = NULL;
9468 TAILQ_INIT(&branches);
9469 TAILQ_INIT(&tags);
9470 TAILQ_INIT(&all_branches);
9471 TAILQ_INIT(&all_tags);
9472 TAILQ_INIT(&delete_args);
9473 TAILQ_INIT(&delete_branches);
9475 while ((ch = getopt(argc, argv, "ab:d:fqr:Tt:v")) != -1) {
9476 switch (ch) {
9477 case 'a':
9478 send_all_branches = 1;
9479 break;
9480 case 'b':
9481 error = got_pathlist_append(&branches, optarg, NULL);
9482 if (error)
9483 return error;
9484 nbranches++;
9485 break;
9486 case 'd':
9487 error = got_pathlist_append(&delete_args, optarg, NULL);
9488 if (error)
9489 return error;
9490 break;
9491 case 'f':
9492 overwrite_refs = 1;
9493 break;
9494 case 'q':
9495 verbosity = -1;
9496 break;
9497 case 'r':
9498 repo_path = realpath(optarg, NULL);
9499 if (repo_path == NULL)
9500 return got_error_from_errno2("realpath",
9501 optarg);
9502 got_path_strip_trailing_slashes(repo_path);
9503 break;
9504 case 'T':
9505 send_all_tags = 1;
9506 break;
9507 case 't':
9508 error = got_pathlist_append(&tags, optarg, NULL);
9509 if (error)
9510 return error;
9511 break;
9512 case 'v':
9513 if (verbosity < 0)
9514 verbosity = 0;
9515 else if (verbosity < 3)
9516 verbosity++;
9517 break;
9518 default:
9519 usage_send();
9520 /* NOTREACHED */
9523 argc -= optind;
9524 argv += optind;
9526 if (send_all_branches && !TAILQ_EMPTY(&branches))
9527 option_conflict('a', 'b');
9528 if (send_all_tags && !TAILQ_EMPTY(&tags))
9529 option_conflict('T', 't');
9532 if (argc == 0)
9533 remote_name = GOT_SEND_DEFAULT_REMOTE_NAME;
9534 else if (argc == 1)
9535 remote_name = argv[0];
9536 else
9537 usage_send();
9539 cwd = getcwd(NULL, 0);
9540 if (cwd == NULL) {
9541 error = got_error_from_errno("getcwd");
9542 goto done;
9545 error = got_repo_pack_fds_open(&pack_fds);
9546 if (error != NULL)
9547 goto done;
9549 if (repo_path == NULL) {
9550 error = got_worktree_open(&worktree, cwd);
9551 if (error && error->code != GOT_ERR_NOT_WORKTREE)
9552 goto done;
9553 else
9554 error = NULL;
9555 if (worktree) {
9556 repo_path =
9557 strdup(got_worktree_get_repo_path(worktree));
9558 if (repo_path == NULL)
9559 error = got_error_from_errno("strdup");
9560 if (error)
9561 goto done;
9562 } else {
9563 repo_path = strdup(cwd);
9564 if (repo_path == NULL) {
9565 error = got_error_from_errno("strdup");
9566 goto done;
9571 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
9572 if (error)
9573 goto done;
9575 if (worktree) {
9576 worktree_conf = got_worktree_get_gotconfig(worktree);
9577 if (worktree_conf) {
9578 got_gotconfig_get_remotes(&nremotes, &remotes,
9579 worktree_conf);
9580 for (i = 0; i < nremotes; i++) {
9581 if (strcmp(remotes[i].name, remote_name) == 0) {
9582 remote = &remotes[i];
9583 break;
9588 if (remote == NULL) {
9589 repo_conf = got_repo_get_gotconfig(repo);
9590 if (repo_conf) {
9591 got_gotconfig_get_remotes(&nremotes, &remotes,
9592 repo_conf);
9593 for (i = 0; i < nremotes; i++) {
9594 if (strcmp(remotes[i].name, remote_name) == 0) {
9595 remote = &remotes[i];
9596 break;
9601 if (remote == NULL) {
9602 got_repo_get_gitconfig_remotes(&nremotes, &remotes, repo);
9603 for (i = 0; i < nremotes; i++) {
9604 if (strcmp(remotes[i].name, remote_name) == 0) {
9605 remote = &remotes[i];
9606 break;
9610 if (remote == NULL) {
9611 error = got_error_path(remote_name, GOT_ERR_NO_REMOTE);
9612 goto done;
9615 error = got_dial_parse_uri(&proto, &host, &port, &server_path,
9616 &repo_name, remote->send_url);
9617 if (error)
9618 goto done;
9620 if (strcmp(proto, "git") == 0) {
9621 #ifndef PROFILE
9622 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
9623 "sendfd dns inet unveil", NULL) == -1)
9624 err(1, "pledge");
9625 #endif
9626 } else if (strcmp(proto, "git+ssh") == 0 ||
9627 strcmp(proto, "ssh") == 0) {
9628 #ifndef PROFILE
9629 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
9630 "sendfd unveil", NULL) == -1)
9631 err(1, "pledge");
9632 #endif
9633 } else if (strcmp(proto, "http") == 0 ||
9634 strcmp(proto, "git+http") == 0) {
9635 error = got_error_path(proto, GOT_ERR_NOT_IMPL);
9636 goto done;
9637 } else {
9638 error = got_error_path(proto, GOT_ERR_BAD_PROTO);
9639 goto done;
9642 error = got_dial_apply_unveil(proto);
9643 if (error)
9644 goto done;
9646 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
9647 if (error)
9648 goto done;
9650 if (send_all_branches) {
9651 error = got_ref_list(&all_branches, repo, "refs/heads",
9652 got_ref_cmp_by_name, NULL);
9653 if (error)
9654 goto done;
9655 TAILQ_FOREACH(re, &all_branches, entry) {
9656 const char *branchname = got_ref_get_name(re->ref);
9657 error = got_pathlist_append(&branches,
9658 branchname, NULL);
9659 if (error)
9660 goto done;
9661 nbranches++;
9663 } else if (nbranches == 0) {
9664 for (i = 0; i < remote->nsend_branches; i++) {
9665 error = got_pathlist_append(&branches,
9666 remote->send_branches[i], NULL);
9667 if (error)
9668 goto done;
9672 if (send_all_tags) {
9673 error = got_ref_list(&all_tags, repo, "refs/tags",
9674 got_ref_cmp_by_name, NULL);
9675 if (error)
9676 goto done;
9677 TAILQ_FOREACH(re, &all_tags, entry) {
9678 const char *tagname = got_ref_get_name(re->ref);
9679 error = got_pathlist_append(&tags,
9680 tagname, NULL);
9681 if (error)
9682 goto done;
9687 * To prevent accidents only branches in refs/heads/ can be deleted
9688 * with 'got send -d'.
9689 * Deleting anything else requires local repository access or Git.
9691 TAILQ_FOREACH(pe, &delete_args, entry) {
9692 const char *branchname = pe->path;
9693 char *s;
9694 struct got_pathlist_entry *new;
9695 if (strncmp(branchname, "refs/heads/", 11) == 0) {
9696 s = strdup(branchname);
9697 if (s == NULL) {
9698 error = got_error_from_errno("strdup");
9699 goto done;
9701 } else {
9702 if (asprintf(&s, "refs/heads/%s", branchname) == -1) {
9703 error = got_error_from_errno("asprintf");
9704 goto done;
9707 error = got_pathlist_insert(&new, &delete_branches, s, NULL);
9708 if (error || new == NULL /* duplicate */)
9709 free(s);
9710 if (error)
9711 goto done;
9712 ndelete_branches++;
9715 if (nbranches == 0 && ndelete_branches == 0) {
9716 struct got_reference *head_ref;
9717 if (worktree)
9718 error = got_ref_open(&head_ref, repo,
9719 got_worktree_get_head_ref_name(worktree), 0);
9720 else
9721 error = got_ref_open(&head_ref, repo, GOT_REF_HEAD, 0);
9722 if (error)
9723 goto done;
9724 if (got_ref_is_symbolic(head_ref)) {
9725 error = got_ref_resolve_symbolic(&ref, repo, head_ref);
9726 got_ref_close(head_ref);
9727 if (error)
9728 goto done;
9729 } else
9730 ref = head_ref;
9731 error = got_pathlist_append(&branches, got_ref_get_name(ref),
9732 NULL);
9733 if (error)
9734 goto done;
9735 nbranches++;
9738 if (verbosity >= 0) {
9739 printf("Connecting to \"%s\" %s://%s%s%s%s%s\n",
9740 remote->name, proto, host,
9741 port ? ":" : "", port ? port : "",
9742 *server_path == '/' ? "" : "/", server_path);
9745 error = got_send_connect(&sendpid, &sendfd, proto, host, port,
9746 server_path, verbosity);
9747 if (error)
9748 goto done;
9750 memset(&spa, 0, sizeof(spa));
9751 spa.last_scaled_packsize[0] = '\0';
9752 spa.last_p_deltify = -1;
9753 spa.last_p_written = -1;
9754 spa.verbosity = verbosity;
9755 spa.delete_branches = &delete_branches;
9756 error = got_send_pack(remote_name, &branches, &tags, &delete_branches,
9757 verbosity, overwrite_refs, sendfd, repo, send_progress, &spa,
9758 check_cancelled, NULL);
9759 if (spa.printed_something)
9760 putchar('\n');
9761 if (error)
9762 goto done;
9763 if (!spa.sent_something && verbosity >= 0)
9764 printf("Already up-to-date\n");
9765 done:
9766 if (sendpid > 0) {
9767 if (kill(sendpid, SIGTERM) == -1)
9768 error = got_error_from_errno("kill");
9769 if (waitpid(sendpid, &sendstatus, 0) == -1 && error == NULL)
9770 error = got_error_from_errno("waitpid");
9772 if (sendfd != -1 && close(sendfd) == -1 && error == NULL)
9773 error = got_error_from_errno("close");
9774 if (repo) {
9775 const struct got_error *close_err = got_repo_close(repo);
9776 if (error == NULL)
9777 error = close_err;
9779 if (worktree)
9780 got_worktree_close(worktree);
9781 if (pack_fds) {
9782 const struct got_error *pack_err =
9783 got_repo_pack_fds_close(pack_fds);
9784 if (error == NULL)
9785 error = pack_err;
9787 if (ref)
9788 got_ref_close(ref);
9789 got_pathlist_free(&branches, GOT_PATHLIST_FREE_NONE);
9790 got_pathlist_free(&tags, GOT_PATHLIST_FREE_NONE);
9791 got_ref_list_free(&all_branches);
9792 got_ref_list_free(&all_tags);
9793 got_pathlist_free(&delete_args, GOT_PATHLIST_FREE_NONE);
9794 got_pathlist_free(&delete_branches, GOT_PATHLIST_FREE_PATH);
9795 free(cwd);
9796 free(repo_path);
9797 free(proto);
9798 free(host);
9799 free(port);
9800 free(server_path);
9801 free(repo_name);
9802 return error;
9806 * Print and if delete is set delete all ref_prefix references.
9807 * If wanted_ref is not NULL, only print or delete this reference.
9809 static const struct got_error *
9810 process_logmsg_refs(const char *ref_prefix, size_t prefix_len,
9811 const char *wanted_ref, int delete, struct got_worktree *worktree,
9812 struct got_repository *repo)
9814 const struct got_error *err;
9815 struct got_pathlist_head paths;
9816 struct got_reflist_head refs;
9817 struct got_reflist_entry *re;
9818 struct got_reflist_object_id_map *refs_idmap = NULL;
9819 struct got_commit_object *commit = NULL;
9820 struct got_object_id *id = NULL;
9821 const char *header_prefix;
9822 char *uuidstr = NULL;
9823 int found = 0;
9825 TAILQ_INIT(&refs);
9826 TAILQ_INIT(&paths);
9828 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, repo);
9829 if (err)
9830 goto done;
9832 err = got_reflist_object_id_map_create(&refs_idmap, &refs, repo);
9833 if (err)
9834 goto done;
9836 if (worktree != NULL) {
9837 err = got_worktree_get_uuid(&uuidstr, worktree);
9838 if (err)
9839 goto done;
9842 if (wanted_ref) {
9843 if (strncmp(wanted_ref, "refs/heads/", 11) == 0)
9844 wanted_ref += 11;
9847 if (strcmp(ref_prefix, GOT_WORKTREE_BACKOUT_REF_PREFIX) == 0)
9848 header_prefix = "backout";
9849 else
9850 header_prefix = "cherrypick";
9852 TAILQ_FOREACH(re, &refs, entry) {
9853 const char *refname, *wt;
9855 refname = got_ref_get_name(re->ref);
9857 err = check_cancelled(NULL);
9858 if (err)
9859 goto done;
9861 if (strncmp(refname, ref_prefix, prefix_len) == 0)
9862 refname += prefix_len + 1; /* skip '-' delimiter */
9863 else
9864 continue;
9866 wt = refname;
9868 if (worktree == NULL || strncmp(refname, uuidstr,
9869 GOT_WORKTREE_UUID_STRLEN) == 0)
9870 refname += GOT_WORKTREE_UUID_STRLEN + 1; /* skip '-' */
9871 else
9872 continue;
9874 err = got_repo_match_object_id(&id, NULL, refname,
9875 GOT_OBJ_TYPE_COMMIT, NULL, repo);
9876 if (err)
9877 goto done;
9879 err = got_object_open_as_commit(&commit, repo, id);
9880 if (err)
9881 goto done;
9883 if (wanted_ref)
9884 found = strncmp(wanted_ref, refname,
9885 strlen(wanted_ref)) == 0;
9886 if (wanted_ref && !found) {
9887 struct got_reflist_head *ci_refs;
9889 ci_refs = got_reflist_object_id_map_lookup(refs_idmap,
9890 id);
9892 if (ci_refs) {
9893 char *refs_str = NULL;
9894 char const *r = NULL;
9896 err = build_refs_str(&refs_str, ci_refs, id,
9897 repo, 1);
9898 if (err)
9899 goto done;
9901 r = refs_str;
9902 while (r) {
9903 if (strncmp(r, wanted_ref,
9904 strlen(wanted_ref)) == 0) {
9905 found = 1;
9906 break;
9908 r = strchr(r, ' ');
9909 if (r)
9910 ++r;
9912 free(refs_str);
9916 if (wanted_ref == NULL || found) {
9917 if (delete) {
9918 err = got_ref_delete(re->ref, repo);
9919 if (err)
9920 goto done;
9921 printf("Deleted: ");
9922 err = print_commit_oneline(commit, id, repo,
9923 refs_idmap);
9924 } else {
9926 * Print paths modified by commit to help
9927 * associate commits with worktree changes.
9929 err = get_changed_paths(&paths, commit,
9930 repo, NULL);
9931 if (err)
9932 goto done;
9934 err = print_commit(commit, id, repo, NULL,
9935 &paths, NULL, 0, 0, refs_idmap, NULL,
9936 header_prefix);
9937 got_pathlist_free(&paths,
9938 GOT_PATHLIST_FREE_ALL);
9940 if (worktree == NULL)
9941 printf("work tree: %.*s\n\n",
9942 GOT_WORKTREE_UUID_STRLEN, wt);
9944 if (err || found)
9945 goto done;
9948 got_object_commit_close(commit);
9949 commit = NULL;
9950 free(id);
9951 id = NULL;
9954 if (wanted_ref != NULL && !found)
9955 err = got_error_fmt(GOT_ERR_NOT_REF, "%s", wanted_ref);
9957 done:
9958 free(id);
9959 free(uuidstr);
9960 got_ref_list_free(&refs);
9961 got_pathlist_free(&paths, GOT_PATHLIST_FREE_ALL);
9962 if (refs_idmap)
9963 got_reflist_object_id_map_free(refs_idmap);
9964 if (commit)
9965 got_object_commit_close(commit);
9966 return err;
9970 * Create new temp "logmsg" ref of the backed-out or cherrypicked commit
9971 * identified by id for log messages to prepopulate the editor on commit.
9973 static const struct got_error *
9974 logmsg_ref(struct got_object_id *id, const char *prefix,
9975 struct got_worktree *worktree, struct got_repository *repo)
9977 const struct got_error *err = NULL;
9978 char *idstr, *ref = NULL, *refname = NULL;
9979 int histedit_in_progress;
9980 int rebase_in_progress, merge_in_progress;
9983 * Silenty refuse to create merge reference if any histedit, merge,
9984 * or rebase operation is in progress.
9986 err = got_worktree_histedit_in_progress(&histedit_in_progress,
9987 worktree);
9988 if (err)
9989 return err;
9990 if (histedit_in_progress)
9991 return NULL;
9993 err = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
9994 if (err)
9995 return err;
9996 if (rebase_in_progress)
9997 return NULL;
9999 err = got_worktree_merge_in_progress(&merge_in_progress, worktree,
10000 repo);
10001 if (err)
10002 return err;
10003 if (merge_in_progress)
10004 return NULL;
10006 err = got_object_id_str(&idstr, id);
10007 if (err)
10008 return err;
10010 err = got_worktree_get_logmsg_ref_name(&refname, worktree, prefix);
10011 if (err)
10012 goto done;
10014 if (asprintf(&ref, "%s-%s", refname, idstr) == -1) {
10015 err = got_error_from_errno("asprintf");
10016 goto done;
10019 err = create_ref(ref, got_worktree_get_base_commit_id(worktree),
10020 -1, repo);
10021 done:
10022 free(ref);
10023 free(idstr);
10024 free(refname);
10025 return err;
10028 __dead static void
10029 usage_cherrypick(void)
10031 fprintf(stderr, "usage: %s cherrypick [-lX] [commit-id]\n",
10032 getprogname());
10033 exit(1);
10036 static const struct got_error *
10037 cmd_cherrypick(int argc, char *argv[])
10039 const struct got_error *error = NULL;
10040 struct got_worktree *worktree = NULL;
10041 struct got_repository *repo = NULL;
10042 char *cwd = NULL, *commit_id_str = NULL;
10043 struct got_object_id *commit_id = NULL;
10044 struct got_commit_object *commit = NULL;
10045 struct got_object_qid *pid;
10046 int ch, list_refs = 0, remove_refs = 0;
10047 struct got_update_progress_arg upa;
10048 int *pack_fds = NULL;
10050 while ((ch = getopt(argc, argv, "lX")) != -1) {
10051 switch (ch) {
10052 case 'l':
10053 list_refs = 1;
10054 break;
10055 case 'X':
10056 remove_refs = 1;
10057 break;
10058 default:
10059 usage_cherrypick();
10060 /* NOTREACHED */
10064 argc -= optind;
10065 argv += optind;
10067 #ifndef PROFILE
10068 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
10069 "unveil", NULL) == -1)
10070 err(1, "pledge");
10071 #endif
10072 if (list_refs || remove_refs) {
10073 if (argc != 0 && argc != 1)
10074 usage_cherrypick();
10075 } else if (argc != 1)
10076 usage_cherrypick();
10077 if (list_refs && remove_refs)
10078 option_conflict('l', 'X');
10080 cwd = getcwd(NULL, 0);
10081 if (cwd == NULL) {
10082 error = got_error_from_errno("getcwd");
10083 goto done;
10086 error = got_repo_pack_fds_open(&pack_fds);
10087 if (error != NULL)
10088 goto done;
10090 error = got_worktree_open(&worktree, cwd);
10091 if (error) {
10092 if (list_refs || remove_refs) {
10093 if (error->code != GOT_ERR_NOT_WORKTREE)
10094 goto done;
10095 } else {
10096 if (error->code == GOT_ERR_NOT_WORKTREE)
10097 error = wrap_not_worktree_error(error,
10098 "cherrypick", cwd);
10099 goto done;
10103 error = got_repo_open(&repo,
10104 worktree ? got_worktree_get_repo_path(worktree) : cwd,
10105 NULL, pack_fds);
10106 if (error != NULL)
10107 goto done;
10109 error = apply_unveil(got_repo_get_path(repo), 0,
10110 worktree ? got_worktree_get_root_path(worktree) : NULL);
10111 if (error)
10112 goto done;
10114 if (list_refs || remove_refs) {
10115 error = process_logmsg_refs(GOT_WORKTREE_CHERRYPICK_REF_PREFIX,
10116 GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN,
10117 argc == 1 ? argv[0] : NULL, remove_refs, worktree, repo);
10118 goto done;
10121 error = got_repo_match_object_id(&commit_id, NULL, argv[0],
10122 GOT_OBJ_TYPE_COMMIT, NULL, repo);
10123 if (error)
10124 goto done;
10125 error = got_object_id_str(&commit_id_str, commit_id);
10126 if (error)
10127 goto done;
10129 error = got_object_open_as_commit(&commit, repo, commit_id);
10130 if (error)
10131 goto done;
10132 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
10133 memset(&upa, 0, sizeof(upa));
10134 error = got_worktree_merge_files(worktree, pid ? &pid->id : NULL,
10135 commit_id, repo, update_progress, &upa, check_cancelled,
10136 NULL);
10137 if (error != NULL)
10138 goto done;
10140 if (upa.did_something) {
10141 error = logmsg_ref(commit_id,
10142 GOT_WORKTREE_CHERRYPICK_REF_PREFIX, worktree, repo);
10143 if (error)
10144 goto done;
10145 printf("Merged commit %s\n", commit_id_str);
10147 print_merge_progress_stats(&upa);
10148 done:
10149 if (commit)
10150 got_object_commit_close(commit);
10151 free(commit_id_str);
10152 if (worktree)
10153 got_worktree_close(worktree);
10154 if (repo) {
10155 const struct got_error *close_err = got_repo_close(repo);
10156 if (error == NULL)
10157 error = close_err;
10159 if (pack_fds) {
10160 const struct got_error *pack_err =
10161 got_repo_pack_fds_close(pack_fds);
10162 if (error == NULL)
10163 error = pack_err;
10166 return error;
10169 __dead static void
10170 usage_backout(void)
10172 fprintf(stderr, "usage: %s backout [-lX] [commit-id]\n", getprogname());
10173 exit(1);
10176 static const struct got_error *
10177 cmd_backout(int argc, char *argv[])
10179 const struct got_error *error = NULL;
10180 struct got_worktree *worktree = NULL;
10181 struct got_repository *repo = NULL;
10182 char *cwd = NULL, *commit_id_str = NULL;
10183 struct got_object_id *commit_id = NULL;
10184 struct got_commit_object *commit = NULL;
10185 struct got_object_qid *pid;
10186 int ch, list_refs = 0, remove_refs = 0;
10187 struct got_update_progress_arg upa;
10188 int *pack_fds = NULL;
10190 while ((ch = getopt(argc, argv, "lX")) != -1) {
10191 switch (ch) {
10192 case 'l':
10193 list_refs = 1;
10194 break;
10195 case 'X':
10196 remove_refs = 1;
10197 break;
10198 default:
10199 usage_backout();
10200 /* NOTREACHED */
10204 argc -= optind;
10205 argv += optind;
10207 #ifndef PROFILE
10208 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
10209 "unveil", NULL) == -1)
10210 err(1, "pledge");
10211 #endif
10212 if (list_refs || remove_refs) {
10213 if (argc != 0 && argc != 1)
10214 usage_backout();
10215 } else if (argc != 1)
10216 usage_backout();
10217 if (list_refs && remove_refs)
10218 option_conflict('l', 'X');
10220 cwd = getcwd(NULL, 0);
10221 if (cwd == NULL) {
10222 error = got_error_from_errno("getcwd");
10223 goto done;
10226 error = got_repo_pack_fds_open(&pack_fds);
10227 if (error != NULL)
10228 goto done;
10230 error = got_worktree_open(&worktree, cwd);
10231 if (error) {
10232 if (list_refs || remove_refs) {
10233 if (error->code != GOT_ERR_NOT_WORKTREE)
10234 goto done;
10235 } else {
10236 if (error->code == GOT_ERR_NOT_WORKTREE)
10237 error = wrap_not_worktree_error(error,
10238 "backout", cwd);
10239 goto done;
10243 error = got_repo_open(&repo,
10244 worktree ? got_worktree_get_repo_path(worktree) : cwd,
10245 NULL, pack_fds);
10246 if (error != NULL)
10247 goto done;
10249 error = apply_unveil(got_repo_get_path(repo), 0,
10250 worktree ? got_worktree_get_root_path(worktree) : NULL);
10251 if (error)
10252 goto done;
10254 if (list_refs || remove_refs) {
10255 error = process_logmsg_refs(GOT_WORKTREE_BACKOUT_REF_PREFIX,
10256 GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN,
10257 argc == 1 ? argv[0] : NULL, remove_refs, worktree, repo);
10258 goto done;
10261 error = got_repo_match_object_id(&commit_id, NULL, argv[0],
10262 GOT_OBJ_TYPE_COMMIT, NULL, repo);
10263 if (error)
10264 goto done;
10265 error = got_object_id_str(&commit_id_str, commit_id);
10266 if (error)
10267 goto done;
10269 error = got_object_open_as_commit(&commit, repo, commit_id);
10270 if (error)
10271 goto done;
10272 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
10273 if (pid == NULL) {
10274 error = got_error(GOT_ERR_ROOT_COMMIT);
10275 goto done;
10278 memset(&upa, 0, sizeof(upa));
10279 error = got_worktree_merge_files(worktree, commit_id, &pid->id,
10280 repo, update_progress, &upa, check_cancelled, NULL);
10281 if (error != NULL)
10282 goto done;
10284 if (upa.did_something) {
10285 error = logmsg_ref(commit_id, GOT_WORKTREE_BACKOUT_REF_PREFIX,
10286 worktree, repo);
10287 if (error)
10288 goto done;
10289 printf("Backed out commit %s\n", commit_id_str);
10291 print_merge_progress_stats(&upa);
10292 done:
10293 if (commit)
10294 got_object_commit_close(commit);
10295 free(commit_id_str);
10296 if (worktree)
10297 got_worktree_close(worktree);
10298 if (repo) {
10299 const struct got_error *close_err = got_repo_close(repo);
10300 if (error == NULL)
10301 error = close_err;
10303 if (pack_fds) {
10304 const struct got_error *pack_err =
10305 got_repo_pack_fds_close(pack_fds);
10306 if (error == NULL)
10307 error = pack_err;
10309 return error;
10312 __dead static void
10313 usage_rebase(void)
10315 fprintf(stderr, "usage: %s rebase [-aclX] [branch]\n", getprogname());
10316 exit(1);
10319 static void
10320 trim_logmsg(char *logmsg, int limit)
10322 char *nl;
10323 size_t len;
10325 len = strlen(logmsg);
10326 if (len > limit)
10327 len = limit;
10328 logmsg[len] = '\0';
10329 nl = strchr(logmsg, '\n');
10330 if (nl)
10331 *nl = '\0';
10334 static const struct got_error *
10335 get_short_logmsg(char **logmsg, int limit, struct got_commit_object *commit)
10337 const struct got_error *err;
10338 char *logmsg0 = NULL;
10339 const char *s;
10341 err = got_object_commit_get_logmsg(&logmsg0, commit);
10342 if (err)
10343 return err;
10345 s = logmsg0;
10346 while (isspace((unsigned char)s[0]))
10347 s++;
10349 *logmsg = strdup(s);
10350 if (*logmsg == NULL) {
10351 err = got_error_from_errno("strdup");
10352 goto done;
10355 trim_logmsg(*logmsg, limit);
10356 done:
10357 free(logmsg0);
10358 return err;
10361 static const struct got_error *
10362 show_rebase_merge_conflict(struct got_object_id *id,
10363 struct got_repository *repo)
10365 const struct got_error *err;
10366 struct got_commit_object *commit = NULL;
10367 char *id_str = NULL, *logmsg = NULL;
10369 err = got_object_open_as_commit(&commit, repo, id);
10370 if (err)
10371 return err;
10373 err = got_object_id_str(&id_str, id);
10374 if (err)
10375 goto done;
10377 id_str[12] = '\0';
10379 err = get_short_logmsg(&logmsg, 42, commit);
10380 if (err)
10381 goto done;
10383 printf("%s -> merge conflict: %s\n", id_str, logmsg);
10384 done:
10385 free(id_str);
10386 got_object_commit_close(commit);
10387 free(logmsg);
10388 return err;
10391 static const struct got_error *
10392 show_rebase_progress(struct got_commit_object *commit,
10393 struct got_object_id *old_id, struct got_object_id *new_id)
10395 const struct got_error *err;
10396 char *old_id_str = NULL, *new_id_str = NULL, *logmsg = NULL;
10398 err = got_object_id_str(&old_id_str, old_id);
10399 if (err)
10400 goto done;
10402 if (new_id) {
10403 err = got_object_id_str(&new_id_str, new_id);
10404 if (err)
10405 goto done;
10408 old_id_str[12] = '\0';
10409 if (new_id_str)
10410 new_id_str[12] = '\0';
10412 err = get_short_logmsg(&logmsg, 42, commit);
10413 if (err)
10414 goto done;
10416 printf("%s -> %s: %s\n", old_id_str,
10417 new_id_str ? new_id_str : "no-op change", logmsg);
10418 done:
10419 free(old_id_str);
10420 free(new_id_str);
10421 free(logmsg);
10422 return err;
10425 static const struct got_error *
10426 rebase_complete(struct got_worktree *worktree, struct got_fileindex *fileindex,
10427 struct got_reference *branch, struct got_reference *new_base_branch,
10428 struct got_reference *tmp_branch, struct got_repository *repo,
10429 int create_backup)
10431 printf("Switching work tree to %s\n", got_ref_get_name(branch));
10432 return got_worktree_rebase_complete(worktree, fileindex,
10433 new_base_branch, tmp_branch, branch, repo, create_backup);
10436 static const struct got_error *
10437 rebase_commit(struct got_pathlist_head *merged_paths,
10438 struct got_worktree *worktree, struct got_fileindex *fileindex,
10439 struct got_reference *tmp_branch, const char *committer,
10440 struct got_object_id *commit_id, struct got_repository *repo)
10442 const struct got_error *error;
10443 struct got_commit_object *commit;
10444 struct got_object_id *new_commit_id;
10446 error = got_object_open_as_commit(&commit, repo, commit_id);
10447 if (error)
10448 return error;
10450 error = got_worktree_rebase_commit(&new_commit_id, merged_paths,
10451 worktree, fileindex, tmp_branch, committer, commit, commit_id,
10452 repo);
10453 if (error) {
10454 if (error->code != GOT_ERR_COMMIT_NO_CHANGES)
10455 goto done;
10456 error = show_rebase_progress(commit, commit_id, NULL);
10457 } else {
10458 error = show_rebase_progress(commit, commit_id, new_commit_id);
10459 free(new_commit_id);
10461 done:
10462 got_object_commit_close(commit);
10463 return error;
10466 struct check_path_prefix_arg {
10467 const char *path_prefix;
10468 size_t len;
10469 int errcode;
10472 static const struct got_error *
10473 check_path_prefix_in_diff(void *arg, struct got_blob_object *blob1,
10474 struct got_blob_object *blob2, FILE *f1, FILE *f2,
10475 struct got_object_id *id1, struct got_object_id *id2,
10476 const char *path1, const char *path2,
10477 mode_t mode1, mode_t mode2, struct got_repository *repo)
10479 struct check_path_prefix_arg *a = arg;
10481 if ((path1 && !got_path_is_child(path1, a->path_prefix, a->len)) ||
10482 (path2 && !got_path_is_child(path2, a->path_prefix, a->len)))
10483 return got_error(a->errcode);
10485 return NULL;
10488 static const struct got_error *
10489 check_path_prefix(struct got_object_id *parent_id,
10490 struct got_object_id *commit_id, const char *path_prefix,
10491 int errcode, struct got_repository *repo)
10493 const struct got_error *err;
10494 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
10495 struct got_commit_object *commit = NULL, *parent_commit = NULL;
10496 struct check_path_prefix_arg cpp_arg;
10498 if (got_path_is_root_dir(path_prefix))
10499 return NULL;
10501 err = got_object_open_as_commit(&commit, repo, commit_id);
10502 if (err)
10503 goto done;
10505 err = got_object_open_as_commit(&parent_commit, repo, parent_id);
10506 if (err)
10507 goto done;
10509 err = got_object_open_as_tree(&tree1, repo,
10510 got_object_commit_get_tree_id(parent_commit));
10511 if (err)
10512 goto done;
10514 err = got_object_open_as_tree(&tree2, repo,
10515 got_object_commit_get_tree_id(commit));
10516 if (err)
10517 goto done;
10519 cpp_arg.path_prefix = path_prefix;
10520 while (cpp_arg.path_prefix[0] == '/')
10521 cpp_arg.path_prefix++;
10522 cpp_arg.len = strlen(cpp_arg.path_prefix);
10523 cpp_arg.errcode = errcode;
10524 err = got_diff_tree(tree1, tree2, NULL, NULL, -1, -1, "", "", repo,
10525 check_path_prefix_in_diff, &cpp_arg, 0);
10526 done:
10527 if (tree1)
10528 got_object_tree_close(tree1);
10529 if (tree2)
10530 got_object_tree_close(tree2);
10531 if (commit)
10532 got_object_commit_close(commit);
10533 if (parent_commit)
10534 got_object_commit_close(parent_commit);
10535 return err;
10538 static const struct got_error *
10539 collect_commits(struct got_object_id_queue *commits,
10540 struct got_object_id *initial_commit_id,
10541 struct got_object_id *iter_start_id, struct got_object_id *iter_stop_id,
10542 const char *path_prefix, int path_prefix_errcode,
10543 struct got_repository *repo)
10545 const struct got_error *err = NULL;
10546 struct got_commit_graph *graph = NULL;
10547 struct got_object_id parent_id, commit_id;
10548 struct got_object_qid *qid;
10550 err = got_commit_graph_open(&graph, "/", 1);
10551 if (err)
10552 return err;
10554 err = got_commit_graph_iter_start(graph, iter_start_id, repo,
10555 check_cancelled, NULL);
10556 if (err)
10557 goto done;
10559 memcpy(&commit_id, initial_commit_id, sizeof(commit_id));
10560 while (got_object_id_cmp(&commit_id, iter_stop_id) != 0) {
10561 err = got_commit_graph_iter_next(&parent_id, graph, repo,
10562 check_cancelled, NULL);
10563 if (err) {
10564 if (err->code == GOT_ERR_ITER_COMPLETED) {
10565 err = got_error_msg(GOT_ERR_ANCESTRY,
10566 "ran out of commits to rebase before "
10567 "youngest common ancestor commit has "
10568 "been reached?!?");
10570 goto done;
10571 } else {
10572 err = check_path_prefix(&parent_id, &commit_id,
10573 path_prefix, path_prefix_errcode, repo);
10574 if (err)
10575 goto done;
10577 err = got_object_qid_alloc(&qid, &commit_id);
10578 if (err)
10579 goto done;
10580 STAILQ_INSERT_HEAD(commits, qid, entry);
10582 memcpy(&commit_id, &parent_id, sizeof(commit_id));
10585 done:
10586 got_commit_graph_close(graph);
10587 return err;
10590 static const struct got_error *
10591 get_commit_brief_str(char **brief_str, struct got_commit_object *commit)
10593 const struct got_error *err = NULL;
10594 time_t committer_time;
10595 struct tm tm;
10596 char datebuf[11]; /* YYYY-MM-DD + NUL */
10597 char *author0 = NULL, *author, *smallerthan;
10598 char *logmsg0 = NULL, *logmsg, *newline;
10600 committer_time = got_object_commit_get_committer_time(commit);
10601 if (gmtime_r(&committer_time, &tm) == NULL)
10602 return got_error_from_errno("gmtime_r");
10603 if (strftime(datebuf, sizeof(datebuf), "%G-%m-%d", &tm) == 0)
10604 return got_error(GOT_ERR_NO_SPACE);
10606 author0 = strdup(got_object_commit_get_author(commit));
10607 if (author0 == NULL)
10608 return got_error_from_errno("strdup");
10609 author = author0;
10610 smallerthan = strchr(author, '<');
10611 if (smallerthan && smallerthan[1] != '\0')
10612 author = smallerthan + 1;
10613 author[strcspn(author, "@>")] = '\0';
10615 err = got_object_commit_get_logmsg(&logmsg0, commit);
10616 if (err)
10617 goto done;
10618 logmsg = logmsg0;
10619 while (*logmsg == '\n')
10620 logmsg++;
10621 newline = strchr(logmsg, '\n');
10622 if (newline)
10623 *newline = '\0';
10625 if (asprintf(brief_str, "%s %s %s",
10626 datebuf, author, logmsg) == -1)
10627 err = got_error_from_errno("asprintf");
10628 done:
10629 free(author0);
10630 free(logmsg0);
10631 return err;
10634 static const struct got_error *
10635 delete_backup_ref(struct got_reference *ref, struct got_object_id *id,
10636 struct got_repository *repo)
10638 const struct got_error *err;
10639 char *id_str;
10641 err = got_object_id_str(&id_str, id);
10642 if (err)
10643 return err;
10645 err = got_ref_delete(ref, repo);
10646 if (err)
10647 goto done;
10649 printf("Deleted %s: %s\n", got_ref_get_name(ref), id_str);
10650 done:
10651 free(id_str);
10652 return err;
10655 static const struct got_error *
10656 print_backup_ref(const char *branch_name, const char *new_id_str,
10657 struct got_object_id *old_commit_id, struct got_commit_object *old_commit,
10658 struct got_reflist_object_id_map *refs_idmap,
10659 struct got_repository *repo)
10661 const struct got_error *err = NULL;
10662 struct got_reflist_head *refs;
10663 char *refs_str = NULL;
10664 struct got_object_id *new_commit_id = NULL;
10665 struct got_commit_object *new_commit = NULL;
10666 char *new_commit_brief_str = NULL;
10667 struct got_object_id *yca_id = NULL;
10668 struct got_commit_object *yca_commit = NULL;
10669 char *yca_id_str = NULL, *yca_brief_str = NULL;
10670 char *custom_refs_str;
10672 if (asprintf(&custom_refs_str, "formerly %s", branch_name) == -1)
10673 return got_error_from_errno("asprintf");
10675 err = print_commit(old_commit, old_commit_id, repo, NULL, NULL, NULL,
10676 0, 0, refs_idmap, custom_refs_str, NULL);
10677 if (err)
10678 goto done;
10680 err = got_object_resolve_id_str(&new_commit_id, repo, new_id_str);
10681 if (err)
10682 goto done;
10684 refs = got_reflist_object_id_map_lookup(refs_idmap, new_commit_id);
10685 if (refs) {
10686 err = build_refs_str(&refs_str, refs, new_commit_id, repo, 0);
10687 if (err)
10688 goto done;
10691 err = got_object_open_as_commit(&new_commit, repo, new_commit_id);
10692 if (err)
10693 goto done;
10695 err = get_commit_brief_str(&new_commit_brief_str, new_commit);
10696 if (err)
10697 goto done;
10699 err = got_commit_graph_find_youngest_common_ancestor(&yca_id,
10700 old_commit_id, new_commit_id, 1, repo, check_cancelled, NULL);
10701 if (err)
10702 goto done;
10704 printf("has become commit %s%s%s%s\n %s\n", new_id_str,
10705 refs_str ? " (" : "", refs_str ? refs_str : "",
10706 refs_str ? ")" : "", new_commit_brief_str);
10707 if (yca_id && got_object_id_cmp(yca_id, new_commit_id) != 0 &&
10708 got_object_id_cmp(yca_id, old_commit_id) != 0) {
10709 free(refs_str);
10710 refs_str = NULL;
10712 err = got_object_open_as_commit(&yca_commit, repo, yca_id);
10713 if (err)
10714 goto done;
10716 err = get_commit_brief_str(&yca_brief_str, yca_commit);
10717 if (err)
10718 goto done;
10720 err = got_object_id_str(&yca_id_str, yca_id);
10721 if (err)
10722 goto done;
10724 refs = got_reflist_object_id_map_lookup(refs_idmap, yca_id);
10725 if (refs) {
10726 err = build_refs_str(&refs_str, refs, yca_id, repo, 0);
10727 if (err)
10728 goto done;
10730 printf("history forked at %s%s%s%s\n %s\n",
10731 yca_id_str,
10732 refs_str ? " (" : "", refs_str ? refs_str : "",
10733 refs_str ? ")" : "", yca_brief_str);
10735 done:
10736 free(custom_refs_str);
10737 free(new_commit_id);
10738 free(refs_str);
10739 free(yca_id);
10740 free(yca_id_str);
10741 free(yca_brief_str);
10742 if (new_commit)
10743 got_object_commit_close(new_commit);
10744 if (yca_commit)
10745 got_object_commit_close(yca_commit);
10747 return NULL;
10750 static const struct got_error *
10751 worktree_has_logmsg_ref(const char *caller, struct got_worktree *worktree,
10752 struct got_repository *repo)
10754 const struct got_error *err;
10755 struct got_reflist_head refs;
10756 struct got_reflist_entry *re;
10757 char *uuidstr = NULL;
10758 static char msg[160];
10760 TAILQ_INIT(&refs);
10762 err = got_worktree_get_uuid(&uuidstr, worktree);
10763 if (err)
10764 goto done;
10766 err = got_ref_list(&refs, repo, "refs/got/worktree",
10767 got_ref_cmp_by_name, repo);
10768 if (err)
10769 goto done;
10771 TAILQ_FOREACH(re, &refs, entry) {
10772 const char *cmd, *refname, *type;
10774 refname = got_ref_get_name(re->ref);
10776 if (strncmp(refname, GOT_WORKTREE_CHERRYPICK_REF_PREFIX,
10777 GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN) == 0) {
10778 refname += GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN + 1;
10779 cmd = "cherrypick";
10780 type = "cherrypicked";
10781 } else if (strncmp(refname, GOT_WORKTREE_BACKOUT_REF_PREFIX,
10782 GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN) == 0) {
10783 refname += GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN + 1;
10784 cmd = "backout";
10785 type = "backed-out";
10786 } else
10787 continue;
10789 if (strncmp(refname, uuidstr, GOT_WORKTREE_UUID_STRLEN) != 0)
10790 continue;
10792 snprintf(msg, sizeof(msg),
10793 "work tree has references created by %s commits which "
10794 "must be removed with 'got %s -X' before running the %s "
10795 "command", type, cmd, caller);
10796 err = got_error_msg(GOT_ERR_WORKTREE_META, msg);
10797 goto done;
10800 done:
10801 free(uuidstr);
10802 got_ref_list_free(&refs);
10803 return err;
10806 static const struct got_error *
10807 process_backup_refs(const char *backup_ref_prefix,
10808 const char *wanted_branch_name,
10809 int delete, struct got_repository *repo)
10811 const struct got_error *err;
10812 struct got_reflist_head refs, backup_refs;
10813 struct got_reflist_entry *re;
10814 const size_t backup_ref_prefix_len = strlen(backup_ref_prefix);
10815 struct got_object_id *old_commit_id = NULL;
10816 char *branch_name = NULL;
10817 struct got_commit_object *old_commit = NULL;
10818 struct got_reflist_object_id_map *refs_idmap = NULL;
10819 int wanted_branch_found = 0;
10821 TAILQ_INIT(&refs);
10822 TAILQ_INIT(&backup_refs);
10824 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
10825 if (err)
10826 return err;
10828 err = got_reflist_object_id_map_create(&refs_idmap, &refs, repo);
10829 if (err)
10830 goto done;
10832 if (wanted_branch_name) {
10833 if (strncmp(wanted_branch_name, "refs/heads/", 11) == 0)
10834 wanted_branch_name += 11;
10837 err = got_ref_list(&backup_refs, repo, backup_ref_prefix,
10838 got_ref_cmp_by_commit_timestamp_descending, repo);
10839 if (err)
10840 goto done;
10842 TAILQ_FOREACH(re, &backup_refs, entry) {
10843 const char *refname = got_ref_get_name(re->ref);
10844 char *slash;
10846 err = check_cancelled(NULL);
10847 if (err)
10848 break;
10850 err = got_ref_resolve(&old_commit_id, repo, re->ref);
10851 if (err)
10852 break;
10854 err = got_object_open_as_commit(&old_commit, repo,
10855 old_commit_id);
10856 if (err)
10857 break;
10859 if (strncmp(backup_ref_prefix, refname,
10860 backup_ref_prefix_len) == 0)
10861 refname += backup_ref_prefix_len;
10863 while (refname[0] == '/')
10864 refname++;
10866 branch_name = strdup(refname);
10867 if (branch_name == NULL) {
10868 err = got_error_from_errno("strdup");
10869 break;
10871 slash = strrchr(branch_name, '/');
10872 if (slash) {
10873 *slash = '\0';
10874 refname += strlen(branch_name) + 1;
10877 if (wanted_branch_name == NULL ||
10878 strcmp(wanted_branch_name, branch_name) == 0) {
10879 wanted_branch_found = 1;
10880 if (delete) {
10881 err = delete_backup_ref(re->ref,
10882 old_commit_id, repo);
10883 } else {
10884 err = print_backup_ref(branch_name, refname,
10885 old_commit_id, old_commit, refs_idmap,
10886 repo);
10888 if (err)
10889 break;
10892 free(old_commit_id);
10893 old_commit_id = NULL;
10894 free(branch_name);
10895 branch_name = NULL;
10896 got_object_commit_close(old_commit);
10897 old_commit = NULL;
10900 if (wanted_branch_name && !wanted_branch_found) {
10901 err = got_error_fmt(GOT_ERR_NOT_REF,
10902 "%s/%s/", backup_ref_prefix, wanted_branch_name);
10904 done:
10905 if (refs_idmap)
10906 got_reflist_object_id_map_free(refs_idmap);
10907 got_ref_list_free(&refs);
10908 got_ref_list_free(&backup_refs);
10909 free(old_commit_id);
10910 free(branch_name);
10911 if (old_commit)
10912 got_object_commit_close(old_commit);
10913 return err;
10916 static const struct got_error *
10917 abort_progress(void *arg, unsigned char status, const char *path)
10920 * Unversioned files should not clutter progress output when
10921 * an operation is aborted.
10923 if (status == GOT_STATUS_UNVERSIONED)
10924 return NULL;
10926 return update_progress(arg, status, path);
10929 static const struct got_error *
10930 cmd_rebase(int argc, char *argv[])
10932 const struct got_error *error = NULL;
10933 struct got_worktree *worktree = NULL;
10934 struct got_repository *repo = NULL;
10935 struct got_fileindex *fileindex = NULL;
10936 char *cwd = NULL, *committer = NULL, *gitconfig_path = NULL;
10937 struct got_reference *branch = NULL;
10938 struct got_reference *new_base_branch = NULL, *tmp_branch = NULL;
10939 struct got_object_id *commit_id = NULL, *parent_id = NULL;
10940 struct got_object_id *resume_commit_id = NULL;
10941 struct got_object_id *branch_head_commit_id = NULL, *yca_id = NULL;
10942 struct got_object_id *head_commit_id = NULL;
10943 struct got_reference *head_ref = NULL;
10944 struct got_commit_object *commit = NULL;
10945 int ch, rebase_in_progress = 0, abort_rebase = 0, continue_rebase = 0;
10946 int histedit_in_progress = 0, merge_in_progress = 0;
10947 int create_backup = 1, list_backups = 0, delete_backups = 0;
10948 struct got_object_id_queue commits;
10949 struct got_pathlist_head merged_paths;
10950 const struct got_object_id_queue *parent_ids;
10951 struct got_object_qid *qid, *pid;
10952 struct got_update_progress_arg upa;
10953 int *pack_fds = NULL;
10955 STAILQ_INIT(&commits);
10956 TAILQ_INIT(&merged_paths);
10957 memset(&upa, 0, sizeof(upa));
10959 while ((ch = getopt(argc, argv, "aclX")) != -1) {
10960 switch (ch) {
10961 case 'a':
10962 abort_rebase = 1;
10963 break;
10964 case 'c':
10965 continue_rebase = 1;
10966 break;
10967 case 'l':
10968 list_backups = 1;
10969 break;
10970 case 'X':
10971 delete_backups = 1;
10972 break;
10973 default:
10974 usage_rebase();
10975 /* NOTREACHED */
10979 argc -= optind;
10980 argv += optind;
10982 #ifndef PROFILE
10983 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
10984 "unveil", NULL) == -1)
10985 err(1, "pledge");
10986 #endif
10987 if (list_backups) {
10988 if (abort_rebase)
10989 option_conflict('l', 'a');
10990 if (continue_rebase)
10991 option_conflict('l', 'c');
10992 if (delete_backups)
10993 option_conflict('l', 'X');
10994 if (argc != 0 && argc != 1)
10995 usage_rebase();
10996 } else if (delete_backups) {
10997 if (abort_rebase)
10998 option_conflict('X', 'a');
10999 if (continue_rebase)
11000 option_conflict('X', 'c');
11001 if (list_backups)
11002 option_conflict('l', 'X');
11003 if (argc != 0 && argc != 1)
11004 usage_rebase();
11005 } else {
11006 if (abort_rebase && continue_rebase)
11007 usage_rebase();
11008 else if (abort_rebase || continue_rebase) {
11009 if (argc != 0)
11010 usage_rebase();
11011 } else if (argc != 1)
11012 usage_rebase();
11015 cwd = getcwd(NULL, 0);
11016 if (cwd == NULL) {
11017 error = got_error_from_errno("getcwd");
11018 goto done;
11021 error = got_repo_pack_fds_open(&pack_fds);
11022 if (error != NULL)
11023 goto done;
11025 error = got_worktree_open(&worktree, cwd);
11026 if (error) {
11027 if (list_backups || delete_backups) {
11028 if (error->code != GOT_ERR_NOT_WORKTREE)
11029 goto done;
11030 } else {
11031 if (error->code == GOT_ERR_NOT_WORKTREE)
11032 error = wrap_not_worktree_error(error,
11033 "rebase", cwd);
11034 goto done;
11038 error = get_gitconfig_path(&gitconfig_path);
11039 if (error)
11040 goto done;
11041 error = got_repo_open(&repo,
11042 worktree ? got_worktree_get_repo_path(worktree) : cwd,
11043 gitconfig_path, pack_fds);
11044 if (error != NULL)
11045 goto done;
11047 if (worktree != NULL && !list_backups && !delete_backups) {
11048 error = worktree_has_logmsg_ref("rebase", worktree, repo);
11049 if (error)
11050 goto done;
11053 error = get_author(&committer, repo, worktree);
11054 if (error && error->code != GOT_ERR_COMMIT_NO_AUTHOR)
11055 goto done;
11057 error = apply_unveil(got_repo_get_path(repo), 0,
11058 worktree ? got_worktree_get_root_path(worktree) : NULL);
11059 if (error)
11060 goto done;
11062 if (list_backups || delete_backups) {
11063 error = process_backup_refs(
11064 GOT_WORKTREE_REBASE_BACKUP_REF_PREFIX,
11065 argc == 1 ? argv[0] : NULL, delete_backups, repo);
11066 goto done; /* nothing else to do */
11069 error = got_worktree_histedit_in_progress(&histedit_in_progress,
11070 worktree);
11071 if (error)
11072 goto done;
11073 if (histedit_in_progress) {
11074 error = got_error(GOT_ERR_HISTEDIT_BUSY);
11075 goto done;
11078 error = got_worktree_merge_in_progress(&merge_in_progress,
11079 worktree, repo);
11080 if (error)
11081 goto done;
11082 if (merge_in_progress) {
11083 error = got_error(GOT_ERR_MERGE_BUSY);
11084 goto done;
11087 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
11088 if (error)
11089 goto done;
11091 if (abort_rebase) {
11092 if (!rebase_in_progress) {
11093 error = got_error(GOT_ERR_NOT_REBASING);
11094 goto done;
11096 error = got_worktree_rebase_continue(&resume_commit_id,
11097 &new_base_branch, &tmp_branch, &branch, &fileindex,
11098 worktree, repo);
11099 if (error)
11100 goto done;
11101 printf("Switching work tree to %s\n",
11102 got_ref_get_symref_target(new_base_branch));
11103 error = got_worktree_rebase_abort(worktree, fileindex, repo,
11104 new_base_branch, abort_progress, &upa);
11105 if (error)
11106 goto done;
11107 printf("Rebase of %s aborted\n", got_ref_get_name(branch));
11108 print_merge_progress_stats(&upa);
11109 goto done; /* nothing else to do */
11112 if (continue_rebase) {
11113 if (!rebase_in_progress) {
11114 error = got_error(GOT_ERR_NOT_REBASING);
11115 goto done;
11117 error = got_worktree_rebase_continue(&resume_commit_id,
11118 &new_base_branch, &tmp_branch, &branch, &fileindex,
11119 worktree, repo);
11120 if (error)
11121 goto done;
11123 error = rebase_commit(NULL, worktree, fileindex, tmp_branch,
11124 committer, resume_commit_id, repo);
11125 if (error)
11126 goto done;
11128 yca_id = got_object_id_dup(resume_commit_id);
11129 if (yca_id == NULL) {
11130 error = got_error_from_errno("got_object_id_dup");
11131 goto done;
11133 } else {
11134 error = got_ref_open(&branch, repo, argv[0], 0);
11135 if (error != NULL)
11136 goto done;
11137 if (strncmp(got_ref_get_name(branch), "refs/heads/", 11) != 0) {
11138 error = got_error_msg(GOT_ERR_COMMIT_BRANCH,
11139 "will not rebase a branch which lives outside "
11140 "the \"refs/heads/\" reference namespace");
11141 goto done;
11145 error = got_ref_resolve(&branch_head_commit_id, repo, branch);
11146 if (error)
11147 goto done;
11149 if (!continue_rebase) {
11150 struct got_object_id *base_commit_id;
11152 error = got_ref_open(&head_ref, repo,
11153 got_worktree_get_head_ref_name(worktree), 0);
11154 if (error)
11155 goto done;
11156 error = got_ref_resolve(&head_commit_id, repo, head_ref);
11157 if (error)
11158 goto done;
11159 base_commit_id = got_worktree_get_base_commit_id(worktree);
11160 if (got_object_id_cmp(base_commit_id, head_commit_id) != 0) {
11161 error = got_error(GOT_ERR_REBASE_OUT_OF_DATE);
11162 goto done;
11165 error = got_commit_graph_find_youngest_common_ancestor(&yca_id,
11166 base_commit_id, branch_head_commit_id, 1, repo,
11167 check_cancelled, NULL);
11168 if (error) {
11169 if (error->code == GOT_ERR_ANCESTRY) {
11170 error = got_error_msg(GOT_ERR_ANCESTRY,
11171 "specified branch shares no common "
11172 "ancestry with work tree's branch");
11174 goto done;
11177 error = check_same_branch(base_commit_id, branch, yca_id, repo);
11178 if (error) {
11179 if (error->code != GOT_ERR_ANCESTRY)
11180 goto done;
11181 error = NULL;
11182 } else {
11183 struct got_pathlist_head paths;
11184 printf("%s is already based on %s\n",
11185 got_ref_get_name(branch),
11186 got_worktree_get_head_ref_name(worktree));
11187 error = switch_head_ref(branch, branch_head_commit_id,
11188 worktree, repo);
11189 if (error)
11190 goto done;
11191 error = got_worktree_set_base_commit_id(worktree, repo,
11192 branch_head_commit_id);
11193 if (error)
11194 goto done;
11195 TAILQ_INIT(&paths);
11196 error = got_pathlist_append(&paths, "", NULL);
11197 if (error)
11198 goto done;
11199 error = got_worktree_checkout_files(worktree,
11200 &paths, repo, update_progress, &upa,
11201 check_cancelled, NULL);
11202 got_pathlist_free(&paths, GOT_PATHLIST_FREE_NONE);
11203 if (error)
11204 goto done;
11205 if (upa.did_something) {
11206 char *id_str;
11207 error = got_object_id_str(&id_str,
11208 branch_head_commit_id);
11209 if (error)
11210 goto done;
11211 printf("Updated to %s: %s\n",
11212 got_worktree_get_head_ref_name(worktree),
11213 id_str);
11214 free(id_str);
11215 } else
11216 printf("Already up-to-date\n");
11217 print_update_progress_stats(&upa);
11218 goto done;
11222 commit_id = branch_head_commit_id;
11223 error = got_object_open_as_commit(&commit, repo, commit_id);
11224 if (error)
11225 goto done;
11227 parent_ids = got_object_commit_get_parent_ids(commit);
11228 pid = STAILQ_FIRST(parent_ids);
11229 if (pid) {
11230 error = collect_commits(&commits, commit_id, &pid->id,
11231 yca_id, got_worktree_get_path_prefix(worktree),
11232 GOT_ERR_REBASE_PATH, repo);
11233 if (error)
11234 goto done;
11237 got_object_commit_close(commit);
11238 commit = NULL;
11240 if (!continue_rebase) {
11241 error = got_worktree_rebase_prepare(&new_base_branch,
11242 &tmp_branch, &fileindex, worktree, branch, repo);
11243 if (error)
11244 goto done;
11247 if (STAILQ_EMPTY(&commits)) {
11248 if (continue_rebase) {
11249 error = rebase_complete(worktree, fileindex,
11250 branch, new_base_branch, tmp_branch, repo,
11251 create_backup);
11252 goto done;
11253 } else {
11254 /* Fast-forward the reference of the branch. */
11255 struct got_object_id *new_head_commit_id;
11256 char *id_str;
11257 error = got_ref_resolve(&new_head_commit_id, repo,
11258 new_base_branch);
11259 if (error)
11260 goto done;
11261 error = got_object_id_str(&id_str, new_head_commit_id);
11262 if (error)
11263 goto done;
11264 printf("Forwarding %s to commit %s\n",
11265 got_ref_get_name(branch), id_str);
11266 free(id_str);
11267 error = got_ref_change_ref(branch,
11268 new_head_commit_id);
11269 if (error)
11270 goto done;
11271 /* No backup needed since objects did not change. */
11272 create_backup = 0;
11276 pid = NULL;
11277 STAILQ_FOREACH(qid, &commits, entry) {
11279 commit_id = &qid->id;
11280 parent_id = pid ? &pid->id : yca_id;
11281 pid = qid;
11283 memset(&upa, 0, sizeof(upa));
11284 error = got_worktree_rebase_merge_files(&merged_paths,
11285 worktree, fileindex, parent_id, commit_id, repo,
11286 update_progress, &upa, check_cancelled, NULL);
11287 if (error)
11288 goto done;
11290 print_merge_progress_stats(&upa);
11291 if (upa.conflicts > 0 || upa.missing > 0 ||
11292 upa.not_deleted > 0 || upa.unversioned > 0) {
11293 if (upa.conflicts > 0) {
11294 error = show_rebase_merge_conflict(&qid->id,
11295 repo);
11296 if (error)
11297 goto done;
11299 got_pathlist_free(&merged_paths, GOT_PATHLIST_FREE_PATH);
11300 break;
11303 error = rebase_commit(&merged_paths, worktree, fileindex,
11304 tmp_branch, committer, commit_id, repo);
11305 got_pathlist_free(&merged_paths, GOT_PATHLIST_FREE_PATH);
11306 if (error)
11307 goto done;
11310 if (upa.conflicts > 0 || upa.missing > 0 ||
11311 upa.not_deleted > 0 || upa.unversioned > 0) {
11312 error = got_worktree_rebase_postpone(worktree, fileindex);
11313 if (error)
11314 goto done;
11315 if (upa.conflicts > 0 && upa.missing == 0 &&
11316 upa.not_deleted == 0 && upa.unversioned == 0) {
11317 error = got_error_msg(GOT_ERR_CONFLICTS,
11318 "conflicts must be resolved before rebasing "
11319 "can continue");
11320 } else if (upa.conflicts > 0) {
11321 error = got_error_msg(GOT_ERR_CONFLICTS,
11322 "conflicts must be resolved before rebasing "
11323 "can continue; changes destined for some "
11324 "files were not yet merged and should be "
11325 "merged manually if required before the "
11326 "rebase operation is continued");
11327 } else {
11328 error = got_error_msg(GOT_ERR_CONFLICTS,
11329 "changes destined for some files were not "
11330 "yet merged and should be merged manually "
11331 "if required before the rebase operation "
11332 "is continued");
11334 } else
11335 error = rebase_complete(worktree, fileindex, branch,
11336 new_base_branch, tmp_branch, repo, create_backup);
11337 done:
11338 free(cwd);
11339 free(committer);
11340 free(gitconfig_path);
11341 got_object_id_queue_free(&commits);
11342 free(branch_head_commit_id);
11343 free(resume_commit_id);
11344 free(head_commit_id);
11345 free(yca_id);
11346 if (commit)
11347 got_object_commit_close(commit);
11348 if (branch)
11349 got_ref_close(branch);
11350 if (new_base_branch)
11351 got_ref_close(new_base_branch);
11352 if (tmp_branch)
11353 got_ref_close(tmp_branch);
11354 if (head_ref)
11355 got_ref_close(head_ref);
11356 if (worktree)
11357 got_worktree_close(worktree);
11358 if (repo) {
11359 const struct got_error *close_err = got_repo_close(repo);
11360 if (error == NULL)
11361 error = close_err;
11363 if (pack_fds) {
11364 const struct got_error *pack_err =
11365 got_repo_pack_fds_close(pack_fds);
11366 if (error == NULL)
11367 error = pack_err;
11369 return error;
11372 __dead static void
11373 usage_histedit(void)
11375 fprintf(stderr, "usage: %s histedit [-acdeflmX] [-F histedit-script] "
11376 "[branch]\n", getprogname());
11377 exit(1);
11380 #define GOT_HISTEDIT_PICK 'p'
11381 #define GOT_HISTEDIT_EDIT 'e'
11382 #define GOT_HISTEDIT_FOLD 'f'
11383 #define GOT_HISTEDIT_DROP 'd'
11384 #define GOT_HISTEDIT_MESG 'm'
11386 static const struct got_histedit_cmd {
11387 unsigned char code;
11388 const char *name;
11389 const char *desc;
11390 } got_histedit_cmds[] = {
11391 { GOT_HISTEDIT_PICK, "pick", "use commit" },
11392 { GOT_HISTEDIT_EDIT, "edit", "use commit but stop for amending" },
11393 { GOT_HISTEDIT_FOLD, "fold", "combine with next commit that will "
11394 "be used" },
11395 { GOT_HISTEDIT_DROP, "drop", "remove commit from history" },
11396 { GOT_HISTEDIT_MESG, "mesg",
11397 "single-line log message for commit above (open editor if empty)" },
11400 struct got_histedit_list_entry {
11401 TAILQ_ENTRY(got_histedit_list_entry) entry;
11402 struct got_object_id *commit_id;
11403 const struct got_histedit_cmd *cmd;
11404 char *logmsg;
11406 TAILQ_HEAD(got_histedit_list, got_histedit_list_entry);
11408 static const struct got_error *
11409 histedit_write_commit(struct got_object_id *commit_id, const char *cmdname,
11410 FILE *f, struct got_repository *repo)
11412 const struct got_error *err = NULL;
11413 char *logmsg = NULL, *id_str = NULL;
11414 struct got_commit_object *commit = NULL;
11415 int n;
11417 err = got_object_open_as_commit(&commit, repo, commit_id);
11418 if (err)
11419 goto done;
11421 err = get_short_logmsg(&logmsg, 34, commit);
11422 if (err)
11423 goto done;
11425 err = got_object_id_str(&id_str, commit_id);
11426 if (err)
11427 goto done;
11429 n = fprintf(f, "%s %s %s\n", cmdname, id_str, logmsg);
11430 if (n < 0)
11431 err = got_ferror(f, GOT_ERR_IO);
11432 done:
11433 if (commit)
11434 got_object_commit_close(commit);
11435 free(id_str);
11436 free(logmsg);
11437 return err;
11440 static const struct got_error *
11441 histedit_write_commit_list(struct got_object_id_queue *commits,
11442 FILE *f, int edit_logmsg_only, int fold_only, int drop_only,
11443 int edit_only, struct got_repository *repo)
11445 const struct got_error *err = NULL;
11446 struct got_object_qid *qid;
11447 const char *histedit_cmd = NULL;
11449 if (STAILQ_EMPTY(commits))
11450 return got_error(GOT_ERR_EMPTY_HISTEDIT);
11452 STAILQ_FOREACH(qid, commits, entry) {
11453 histedit_cmd = got_histedit_cmds[0].name;
11454 if (drop_only)
11455 histedit_cmd = "drop";
11456 else if (edit_only)
11457 histedit_cmd = "edit";
11458 else if (fold_only && STAILQ_NEXT(qid, entry) != NULL)
11459 histedit_cmd = "fold";
11460 err = histedit_write_commit(&qid->id, histedit_cmd, f, repo);
11461 if (err)
11462 break;
11463 if (edit_logmsg_only) {
11464 int n = fprintf(f, "%c\n", GOT_HISTEDIT_MESG);
11465 if (n < 0) {
11466 err = got_ferror(f, GOT_ERR_IO);
11467 break;
11472 return err;
11475 static const struct got_error *
11476 write_cmd_list(FILE *f, const char *branch_name,
11477 struct got_object_id_queue *commits)
11479 const struct got_error *err = NULL;
11480 size_t i;
11481 int n;
11482 char *id_str;
11483 struct got_object_qid *qid;
11485 qid = STAILQ_FIRST(commits);
11486 err = got_object_id_str(&id_str, &qid->id);
11487 if (err)
11488 return err;
11490 n = fprintf(f,
11491 "# Editing the history of branch '%s' starting at\n"
11492 "# commit %s\n"
11493 "# Commits will be processed in order from top to "
11494 "bottom of this file.\n", branch_name, id_str);
11495 if (n < 0) {
11496 err = got_ferror(f, GOT_ERR_IO);
11497 goto done;
11500 n = fprintf(f, "# Available histedit commands:\n");
11501 if (n < 0) {
11502 err = got_ferror(f, GOT_ERR_IO);
11503 goto done;
11506 for (i = 0; i < nitems(got_histedit_cmds); i++) {
11507 const struct got_histedit_cmd *cmd = &got_histedit_cmds[i];
11508 n = fprintf(f, "# %s (%c): %s\n", cmd->name, cmd->code,
11509 cmd->desc);
11510 if (n < 0) {
11511 err = got_ferror(f, GOT_ERR_IO);
11512 break;
11515 done:
11516 free(id_str);
11517 return err;
11520 static const struct got_error *
11521 histedit_syntax_error(int lineno)
11523 static char msg[42];
11524 int ret;
11526 ret = snprintf(msg, sizeof(msg), "histedit syntax error on line %d",
11527 lineno);
11528 if (ret < 0 || (size_t)ret >= sizeof(msg))
11529 return got_error(GOT_ERR_HISTEDIT_SYNTAX);
11531 return got_error_msg(GOT_ERR_HISTEDIT_SYNTAX, msg);
11534 static const struct got_error *
11535 append_folded_commit_msg(char **new_msg, struct got_histedit_list_entry *hle,
11536 char *logmsg, struct got_repository *repo)
11538 const struct got_error *err;
11539 struct got_commit_object *folded_commit = NULL;
11540 char *id_str, *folded_logmsg = NULL;
11542 err = got_object_id_str(&id_str, hle->commit_id);
11543 if (err)
11544 return err;
11546 err = got_object_open_as_commit(&folded_commit, repo, hle->commit_id);
11547 if (err)
11548 goto done;
11550 err = got_object_commit_get_logmsg(&folded_logmsg, folded_commit);
11551 if (err)
11552 goto done;
11553 if (asprintf(new_msg, "%s%s# log message of folded commit %s: %s",
11554 logmsg ? logmsg : "", logmsg ? "\n" : "", id_str,
11555 folded_logmsg) == -1) {
11556 err = got_error_from_errno("asprintf");
11558 done:
11559 if (folded_commit)
11560 got_object_commit_close(folded_commit);
11561 free(id_str);
11562 free(folded_logmsg);
11563 return err;
11566 static struct got_histedit_list_entry *
11567 get_folded_commits(struct got_histedit_list_entry *hle)
11569 struct got_histedit_list_entry *prev, *folded = NULL;
11571 prev = TAILQ_PREV(hle, got_histedit_list, entry);
11572 while (prev && (prev->cmd->code == GOT_HISTEDIT_FOLD ||
11573 prev->cmd->code == GOT_HISTEDIT_DROP)) {
11574 if (prev->cmd->code == GOT_HISTEDIT_FOLD)
11575 folded = prev;
11576 prev = TAILQ_PREV(prev, got_histedit_list, entry);
11579 return folded;
11582 static const struct got_error *
11583 histedit_edit_logmsg(struct got_histedit_list_entry *hle,
11584 struct got_repository *repo)
11586 char *logmsg_path = NULL, *id_str = NULL, *orig_logmsg = NULL;
11587 char *logmsg = NULL, *new_msg = NULL, *editor = NULL;
11588 const struct got_error *err = NULL;
11589 struct got_commit_object *commit = NULL;
11590 int logmsg_len;
11591 int fd;
11592 struct got_histedit_list_entry *folded = NULL;
11594 err = got_object_open_as_commit(&commit, repo, hle->commit_id);
11595 if (err)
11596 return err;
11598 folded = get_folded_commits(hle);
11599 if (folded) {
11600 while (folded != hle) {
11601 if (folded->cmd->code == GOT_HISTEDIT_DROP) {
11602 folded = TAILQ_NEXT(folded, entry);
11603 continue;
11605 err = append_folded_commit_msg(&new_msg, folded,
11606 logmsg, repo);
11607 if (err)
11608 goto done;
11609 free(logmsg);
11610 logmsg = new_msg;
11611 folded = TAILQ_NEXT(folded, entry);
11615 err = got_object_id_str(&id_str, hle->commit_id);
11616 if (err)
11617 goto done;
11618 err = got_object_commit_get_logmsg(&orig_logmsg, commit);
11619 if (err)
11620 goto done;
11621 logmsg_len = asprintf(&new_msg,
11622 "%s\n# original log message of commit %s: %s",
11623 logmsg ? logmsg : "", id_str, orig_logmsg);
11624 if (logmsg_len == -1) {
11625 err = got_error_from_errno("asprintf");
11626 goto done;
11628 free(logmsg);
11629 logmsg = new_msg;
11631 err = got_object_id_str(&id_str, hle->commit_id);
11632 if (err)
11633 goto done;
11635 err = got_opentemp_named_fd(&logmsg_path, &fd,
11636 GOT_TMPDIR_STR "/got-logmsg", "");
11637 if (err)
11638 goto done;
11640 write(fd, logmsg, logmsg_len);
11641 close(fd);
11643 err = get_editor(&editor);
11644 if (err)
11645 goto done;
11647 err = edit_logmsg(&hle->logmsg, editor, logmsg_path, logmsg,
11648 logmsg_len, 0);
11649 if (err) {
11650 if (err->code != GOT_ERR_COMMIT_MSG_EMPTY)
11651 goto done;
11652 err = NULL;
11653 hle->logmsg = strdup(new_msg);
11654 if (hle->logmsg == NULL)
11655 err = got_error_from_errno("strdup");
11657 done:
11658 if (logmsg_path && unlink(logmsg_path) != 0 && err == NULL)
11659 err = got_error_from_errno2("unlink", logmsg_path);
11660 free(logmsg_path);
11661 free(logmsg);
11662 free(orig_logmsg);
11663 free(editor);
11664 if (commit)
11665 got_object_commit_close(commit);
11666 return err;
11669 static const struct got_error *
11670 histedit_parse_list(struct got_histedit_list *histedit_cmds,
11671 FILE *f, struct got_repository *repo)
11673 const struct got_error *err = NULL;
11674 char *line = NULL, *p, *end;
11675 size_t i, size;
11676 ssize_t len;
11677 int lineno = 0, lastcmd = -1;
11678 const struct got_histedit_cmd *cmd;
11679 struct got_object_id *commit_id = NULL;
11680 struct got_histedit_list_entry *hle = NULL;
11682 for (;;) {
11683 len = getline(&line, &size, f);
11684 if (len == -1) {
11685 const struct got_error *getline_err;
11686 if (feof(f))
11687 break;
11688 getline_err = got_error_from_errno("getline");
11689 err = got_ferror(f, getline_err->code);
11690 break;
11692 lineno++;
11693 p = line;
11694 while (isspace((unsigned char)p[0]))
11695 p++;
11696 if (p[0] == '#' || p[0] == '\0') {
11697 free(line);
11698 line = NULL;
11699 continue;
11701 cmd = NULL;
11702 for (i = 0; i < nitems(got_histedit_cmds); i++) {
11703 cmd = &got_histedit_cmds[i];
11704 if (strncmp(cmd->name, p, strlen(cmd->name)) == 0 &&
11705 isspace((unsigned char)p[strlen(cmd->name)])) {
11706 p += strlen(cmd->name);
11707 break;
11709 if (p[0] == cmd->code && isspace((unsigned char)p[1])) {
11710 p++;
11711 break;
11714 if (i == nitems(got_histedit_cmds)) {
11715 err = histedit_syntax_error(lineno);
11716 break;
11718 while (isspace((unsigned char)p[0]))
11719 p++;
11720 if (cmd->code == GOT_HISTEDIT_MESG) {
11721 if (lastcmd != GOT_HISTEDIT_PICK &&
11722 lastcmd != GOT_HISTEDIT_EDIT) {
11723 err = got_error(GOT_ERR_HISTEDIT_CMD);
11724 break;
11726 if (p[0] == '\0') {
11727 err = histedit_edit_logmsg(hle, repo);
11728 if (err)
11729 break;
11730 } else {
11731 hle->logmsg = strdup(p);
11732 if (hle->logmsg == NULL) {
11733 err = got_error_from_errno("strdup");
11734 break;
11737 free(line);
11738 line = NULL;
11739 lastcmd = cmd->code;
11740 continue;
11741 } else {
11742 end = p;
11743 while (end[0] && !isspace((unsigned char)end[0]))
11744 end++;
11745 *end = '\0';
11747 err = got_object_resolve_id_str(&commit_id, repo, p);
11748 if (err) {
11749 /* override error code */
11750 err = histedit_syntax_error(lineno);
11751 break;
11754 hle = malloc(sizeof(*hle));
11755 if (hle == NULL) {
11756 err = got_error_from_errno("malloc");
11757 break;
11759 hle->cmd = cmd;
11760 hle->commit_id = commit_id;
11761 hle->logmsg = NULL;
11762 commit_id = NULL;
11763 free(line);
11764 line = NULL;
11765 TAILQ_INSERT_TAIL(histedit_cmds, hle, entry);
11766 lastcmd = cmd->code;
11769 free(line);
11770 free(commit_id);
11771 return err;
11774 static const struct got_error *
11775 histedit_check_script(struct got_histedit_list *histedit_cmds,
11776 struct got_object_id_queue *commits, struct got_repository *repo)
11778 const struct got_error *err = NULL;
11779 struct got_object_qid *qid;
11780 struct got_histedit_list_entry *hle;
11781 static char msg[92];
11782 char *id_str;
11784 if (TAILQ_EMPTY(histedit_cmds))
11785 return got_error_msg(GOT_ERR_EMPTY_HISTEDIT,
11786 "histedit script contains no commands");
11787 if (STAILQ_EMPTY(commits))
11788 return got_error(GOT_ERR_EMPTY_HISTEDIT);
11790 TAILQ_FOREACH(hle, histedit_cmds, entry) {
11791 struct got_histedit_list_entry *hle2;
11792 TAILQ_FOREACH(hle2, histedit_cmds, entry) {
11793 if (hle == hle2)
11794 continue;
11795 if (got_object_id_cmp(hle->commit_id,
11796 hle2->commit_id) != 0)
11797 continue;
11798 err = got_object_id_str(&id_str, hle->commit_id);
11799 if (err)
11800 return err;
11801 snprintf(msg, sizeof(msg), "commit %s is listed "
11802 "more than once in histedit script", id_str);
11803 free(id_str);
11804 return got_error_msg(GOT_ERR_HISTEDIT_CMD, msg);
11808 STAILQ_FOREACH(qid, commits, entry) {
11809 TAILQ_FOREACH(hle, histedit_cmds, entry) {
11810 if (got_object_id_cmp(&qid->id, hle->commit_id) == 0)
11811 break;
11813 if (hle == NULL) {
11814 err = got_object_id_str(&id_str, &qid->id);
11815 if (err)
11816 return err;
11817 snprintf(msg, sizeof(msg),
11818 "commit %s missing from histedit script", id_str);
11819 free(id_str);
11820 return got_error_msg(GOT_ERR_HISTEDIT_CMD, msg);
11824 hle = TAILQ_LAST(histedit_cmds, got_histedit_list);
11825 if (hle && hle->cmd->code == GOT_HISTEDIT_FOLD)
11826 return got_error_msg(GOT_ERR_HISTEDIT_CMD,
11827 "last commit in histedit script cannot be folded");
11829 return NULL;
11832 static const struct got_error *
11833 histedit_run_editor(struct got_histedit_list *histedit_cmds,
11834 const char *path, struct got_object_id_queue *commits,
11835 struct got_repository *repo)
11837 const struct got_error *err = NULL;
11838 char *editor;
11839 FILE *f = NULL;
11841 err = get_editor(&editor);
11842 if (err)
11843 return err;
11845 if (spawn_editor(editor, path) == -1) {
11846 err = got_error_from_errno("failed spawning editor");
11847 goto done;
11850 f = fopen(path, "re");
11851 if (f == NULL) {
11852 err = got_error_from_errno("fopen");
11853 goto done;
11855 err = histedit_parse_list(histedit_cmds, f, repo);
11856 if (err)
11857 goto done;
11859 err = histedit_check_script(histedit_cmds, commits, repo);
11860 done:
11861 if (f && fclose(f) == EOF && err == NULL)
11862 err = got_error_from_errno("fclose");
11863 free(editor);
11864 return err;
11867 static const struct got_error *
11868 histedit_edit_list_retry(struct got_histedit_list *, const struct got_error *,
11869 struct got_object_id_queue *, const char *, const char *,
11870 struct got_repository *);
11872 static const struct got_error *
11873 histedit_edit_script(struct got_histedit_list *histedit_cmds,
11874 struct got_object_id_queue *commits, const char *branch_name,
11875 int edit_logmsg_only, int fold_only, int drop_only, int edit_only,
11876 struct got_repository *repo)
11878 const struct got_error *err;
11879 FILE *f = NULL;
11880 char *path = NULL;
11882 err = got_opentemp_named(&path, &f, "got-histedit", "");
11883 if (err)
11884 return err;
11886 err = write_cmd_list(f, branch_name, commits);
11887 if (err)
11888 goto done;
11890 err = histedit_write_commit_list(commits, f, edit_logmsg_only,
11891 fold_only, drop_only, edit_only, repo);
11892 if (err)
11893 goto done;
11895 if (drop_only || edit_logmsg_only || fold_only || edit_only) {
11896 rewind(f);
11897 err = histedit_parse_list(histedit_cmds, f, repo);
11898 } else {
11899 if (fclose(f) == EOF) {
11900 err = got_error_from_errno("fclose");
11901 goto done;
11903 f = NULL;
11904 err = histedit_run_editor(histedit_cmds, path, commits, repo);
11905 if (err) {
11906 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
11907 err->code != GOT_ERR_HISTEDIT_CMD)
11908 goto done;
11909 err = histedit_edit_list_retry(histedit_cmds, err,
11910 commits, path, branch_name, repo);
11913 done:
11914 if (f && fclose(f) == EOF && err == NULL)
11915 err = got_error_from_errno("fclose");
11916 if (path && unlink(path) != 0 && err == NULL)
11917 err = got_error_from_errno2("unlink", path);
11918 free(path);
11919 return err;
11922 static const struct got_error *
11923 histedit_save_list(struct got_histedit_list *histedit_cmds,
11924 struct got_worktree *worktree, struct got_repository *repo)
11926 const struct got_error *err = NULL;
11927 char *path = NULL;
11928 FILE *f = NULL;
11929 struct got_histedit_list_entry *hle;
11930 struct got_commit_object *commit = NULL;
11932 err = got_worktree_get_histedit_script_path(&path, worktree);
11933 if (err)
11934 return err;
11936 f = fopen(path, "we");
11937 if (f == NULL) {
11938 err = got_error_from_errno2("fopen", path);
11939 goto done;
11941 TAILQ_FOREACH(hle, histedit_cmds, entry) {
11942 err = histedit_write_commit(hle->commit_id, hle->cmd->name, f,
11943 repo);
11944 if (err)
11945 break;
11947 if (hle->logmsg) {
11948 int n = fprintf(f, "%c %s\n",
11949 GOT_HISTEDIT_MESG, hle->logmsg);
11950 if (n < 0) {
11951 err = got_ferror(f, GOT_ERR_IO);
11952 break;
11956 done:
11957 if (f && fclose(f) == EOF && err == NULL)
11958 err = got_error_from_errno("fclose");
11959 free(path);
11960 if (commit)
11961 got_object_commit_close(commit);
11962 return err;
11965 static void
11966 histedit_free_list(struct got_histedit_list *histedit_cmds)
11968 struct got_histedit_list_entry *hle;
11970 while ((hle = TAILQ_FIRST(histedit_cmds))) {
11971 TAILQ_REMOVE(histedit_cmds, hle, entry);
11972 free(hle);
11976 static const struct got_error *
11977 histedit_load_list(struct got_histedit_list *histedit_cmds,
11978 const char *path, struct got_repository *repo)
11980 const struct got_error *err = NULL;
11981 FILE *f = NULL;
11983 f = fopen(path, "re");
11984 if (f == NULL) {
11985 err = got_error_from_errno2("fopen", path);
11986 goto done;
11989 err = histedit_parse_list(histedit_cmds, f, repo);
11990 done:
11991 if (f && fclose(f) == EOF && err == NULL)
11992 err = got_error_from_errno("fclose");
11993 return err;
11996 static const struct got_error *
11997 histedit_edit_list_retry(struct got_histedit_list *histedit_cmds,
11998 const struct got_error *edit_err, struct got_object_id_queue *commits,
11999 const char *path, const char *branch_name, struct got_repository *repo)
12001 const struct got_error *err = NULL, *prev_err = edit_err;
12002 int resp = ' ';
12004 while (resp != 'c' && resp != 'r' && resp != 'a') {
12005 printf("%s: %s\n(c)ontinue editing, (r)estart editing, "
12006 "or (a)bort: ", getprogname(), prev_err->msg);
12007 resp = getchar();
12008 if (resp == '\n')
12009 resp = getchar();
12010 if (resp == 'c') {
12011 histedit_free_list(histedit_cmds);
12012 err = histedit_run_editor(histedit_cmds, path, commits,
12013 repo);
12014 if (err) {
12015 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
12016 err->code != GOT_ERR_HISTEDIT_CMD)
12017 break;
12018 prev_err = err;
12019 resp = ' ';
12020 continue;
12022 break;
12023 } else if (resp == 'r') {
12024 histedit_free_list(histedit_cmds);
12025 err = histedit_edit_script(histedit_cmds,
12026 commits, branch_name, 0, 0, 0, 0, repo);
12027 if (err) {
12028 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
12029 err->code != GOT_ERR_HISTEDIT_CMD)
12030 break;
12031 prev_err = err;
12032 resp = ' ';
12033 continue;
12035 break;
12036 } else if (resp == 'a') {
12037 err = got_error(GOT_ERR_HISTEDIT_CANCEL);
12038 break;
12039 } else
12040 printf("invalid response '%c'\n", resp);
12043 return err;
12046 static const struct got_error *
12047 histedit_complete(struct got_worktree *worktree,
12048 struct got_fileindex *fileindex, struct got_reference *tmp_branch,
12049 struct got_reference *branch, struct got_repository *repo)
12051 printf("Switching work tree to %s\n",
12052 got_ref_get_symref_target(branch));
12053 return got_worktree_histedit_complete(worktree, fileindex, tmp_branch,
12054 branch, repo);
12057 static const struct got_error *
12058 show_histedit_progress(struct got_commit_object *commit,
12059 struct got_histedit_list_entry *hle, struct got_object_id *new_id)
12061 const struct got_error *err;
12062 char *old_id_str = NULL, *new_id_str = NULL, *logmsg = NULL;
12064 err = got_object_id_str(&old_id_str, hle->commit_id);
12065 if (err)
12066 goto done;
12068 if (new_id) {
12069 err = got_object_id_str(&new_id_str, new_id);
12070 if (err)
12071 goto done;
12074 old_id_str[12] = '\0';
12075 if (new_id_str)
12076 new_id_str[12] = '\0';
12078 if (hle->logmsg) {
12079 logmsg = strdup(hle->logmsg);
12080 if (logmsg == NULL) {
12081 err = got_error_from_errno("strdup");
12082 goto done;
12084 trim_logmsg(logmsg, 42);
12085 } else {
12086 err = get_short_logmsg(&logmsg, 42, commit);
12087 if (err)
12088 goto done;
12091 switch (hle->cmd->code) {
12092 case GOT_HISTEDIT_PICK:
12093 case GOT_HISTEDIT_EDIT:
12094 printf("%s -> %s: %s\n", old_id_str,
12095 new_id_str ? new_id_str : "no-op change", logmsg);
12096 break;
12097 case GOT_HISTEDIT_DROP:
12098 case GOT_HISTEDIT_FOLD:
12099 printf("%s -> %s commit: %s\n", old_id_str, hle->cmd->name,
12100 logmsg);
12101 break;
12102 default:
12103 break;
12105 done:
12106 free(old_id_str);
12107 free(new_id_str);
12108 return err;
12111 static const struct got_error *
12112 histedit_commit(struct got_pathlist_head *merged_paths,
12113 struct got_worktree *worktree, struct got_fileindex *fileindex,
12114 struct got_reference *tmp_branch, struct got_histedit_list_entry *hle,
12115 const char *committer, struct got_repository *repo)
12117 const struct got_error *err;
12118 struct got_commit_object *commit;
12119 struct got_object_id *new_commit_id;
12121 if ((hle->cmd->code == GOT_HISTEDIT_EDIT || get_folded_commits(hle))
12122 && hle->logmsg == NULL) {
12123 err = histedit_edit_logmsg(hle, repo);
12124 if (err)
12125 return err;
12128 err = got_object_open_as_commit(&commit, repo, hle->commit_id);
12129 if (err)
12130 return err;
12132 err = got_worktree_histedit_commit(&new_commit_id, merged_paths,
12133 worktree, fileindex, tmp_branch, committer, commit, hle->commit_id,
12134 hle->logmsg, repo);
12135 if (err) {
12136 if (err->code != GOT_ERR_COMMIT_NO_CHANGES)
12137 goto done;
12138 err = show_histedit_progress(commit, hle, NULL);
12139 } else {
12140 err = show_histedit_progress(commit, hle, new_commit_id);
12141 free(new_commit_id);
12143 done:
12144 got_object_commit_close(commit);
12145 return err;
12148 static const struct got_error *
12149 histedit_skip_commit(struct got_histedit_list_entry *hle,
12150 struct got_worktree *worktree, struct got_repository *repo)
12152 const struct got_error *error;
12153 struct got_commit_object *commit;
12155 error = got_worktree_histedit_skip_commit(worktree, hle->commit_id,
12156 repo);
12157 if (error)
12158 return error;
12160 error = got_object_open_as_commit(&commit, repo, hle->commit_id);
12161 if (error)
12162 return error;
12164 error = show_histedit_progress(commit, hle, NULL);
12165 got_object_commit_close(commit);
12166 return error;
12169 static const struct got_error *
12170 check_local_changes(void *arg, unsigned char status,
12171 unsigned char staged_status, const char *path,
12172 struct got_object_id *blob_id, struct got_object_id *staged_blob_id,
12173 struct got_object_id *commit_id, int dirfd, const char *de_name)
12175 int *have_local_changes = arg;
12177 switch (status) {
12178 case GOT_STATUS_ADD:
12179 case GOT_STATUS_DELETE:
12180 case GOT_STATUS_MODIFY:
12181 case GOT_STATUS_CONFLICT:
12182 *have_local_changes = 1;
12183 return got_error(GOT_ERR_CANCELLED);
12184 default:
12185 break;
12188 switch (staged_status) {
12189 case GOT_STATUS_ADD:
12190 case GOT_STATUS_DELETE:
12191 case GOT_STATUS_MODIFY:
12192 *have_local_changes = 1;
12193 return got_error(GOT_ERR_CANCELLED);
12194 default:
12195 break;
12198 return NULL;
12201 static const struct got_error *
12202 cmd_histedit(int argc, char *argv[])
12204 const struct got_error *error = NULL;
12205 struct got_worktree *worktree = NULL;
12206 struct got_fileindex *fileindex = NULL;
12207 struct got_repository *repo = NULL;
12208 char *cwd = NULL, *committer = NULL, *gitconfig_path = NULL;
12209 struct got_reference *branch = NULL;
12210 struct got_reference *tmp_branch = NULL;
12211 struct got_object_id *resume_commit_id = NULL;
12212 struct got_object_id *base_commit_id = NULL;
12213 struct got_object_id *head_commit_id = NULL;
12214 struct got_commit_object *commit = NULL;
12215 int ch, rebase_in_progress = 0, merge_in_progress = 0;
12216 struct got_update_progress_arg upa;
12217 int edit_in_progress = 0, abort_edit = 0, continue_edit = 0;
12218 int drop_only = 0, edit_logmsg_only = 0, fold_only = 0, edit_only = 0;
12219 int list_backups = 0, delete_backups = 0;
12220 const char *edit_script_path = NULL;
12221 struct got_object_id_queue commits;
12222 struct got_pathlist_head merged_paths;
12223 const struct got_object_id_queue *parent_ids;
12224 struct got_object_qid *pid;
12225 struct got_histedit_list histedit_cmds;
12226 struct got_histedit_list_entry *hle;
12227 int *pack_fds = NULL;
12229 STAILQ_INIT(&commits);
12230 TAILQ_INIT(&histedit_cmds);
12231 TAILQ_INIT(&merged_paths);
12232 memset(&upa, 0, sizeof(upa));
12234 while ((ch = getopt(argc, argv, "acdeF:flmX")) != -1) {
12235 switch (ch) {
12236 case 'a':
12237 abort_edit = 1;
12238 break;
12239 case 'c':
12240 continue_edit = 1;
12241 break;
12242 case 'd':
12243 drop_only = 1;
12244 break;
12245 case 'e':
12246 edit_only = 1;
12247 break;
12248 case 'F':
12249 edit_script_path = optarg;
12250 break;
12251 case 'f':
12252 fold_only = 1;
12253 break;
12254 case 'l':
12255 list_backups = 1;
12256 break;
12257 case 'm':
12258 edit_logmsg_only = 1;
12259 break;
12260 case 'X':
12261 delete_backups = 1;
12262 break;
12263 default:
12264 usage_histedit();
12265 /* NOTREACHED */
12269 argc -= optind;
12270 argv += optind;
12272 #ifndef PROFILE
12273 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
12274 "unveil", NULL) == -1)
12275 err(1, "pledge");
12276 #endif
12277 if (abort_edit && continue_edit)
12278 option_conflict('a', 'c');
12279 if (edit_script_path && edit_logmsg_only)
12280 option_conflict('F', 'm');
12281 if (abort_edit && edit_logmsg_only)
12282 option_conflict('a', 'm');
12283 if (continue_edit && edit_logmsg_only)
12284 option_conflict('c', 'm');
12285 if (abort_edit && fold_only)
12286 option_conflict('a', 'f');
12287 if (continue_edit && fold_only)
12288 option_conflict('c', 'f');
12289 if (fold_only && edit_logmsg_only)
12290 option_conflict('f', 'm');
12291 if (edit_script_path && fold_only)
12292 option_conflict('F', 'f');
12293 if (abort_edit && edit_only)
12294 option_conflict('a', 'e');
12295 if (continue_edit && edit_only)
12296 option_conflict('c', 'e');
12297 if (edit_only && edit_logmsg_only)
12298 option_conflict('e', 'm');
12299 if (edit_script_path && edit_only)
12300 option_conflict('F', 'e');
12301 if (fold_only && edit_only)
12302 option_conflict('f', 'e');
12303 if (drop_only && abort_edit)
12304 option_conflict('d', 'a');
12305 if (drop_only && continue_edit)
12306 option_conflict('d', 'c');
12307 if (drop_only && edit_logmsg_only)
12308 option_conflict('d', 'm');
12309 if (drop_only && edit_only)
12310 option_conflict('d', 'e');
12311 if (drop_only && edit_script_path)
12312 option_conflict('d', 'F');
12313 if (drop_only && fold_only)
12314 option_conflict('d', 'f');
12315 if (list_backups) {
12316 if (abort_edit)
12317 option_conflict('l', 'a');
12318 if (continue_edit)
12319 option_conflict('l', 'c');
12320 if (edit_script_path)
12321 option_conflict('l', 'F');
12322 if (edit_logmsg_only)
12323 option_conflict('l', 'm');
12324 if (drop_only)
12325 option_conflict('l', 'd');
12326 if (fold_only)
12327 option_conflict('l', 'f');
12328 if (edit_only)
12329 option_conflict('l', 'e');
12330 if (delete_backups)
12331 option_conflict('l', 'X');
12332 if (argc != 0 && argc != 1)
12333 usage_histedit();
12334 } else if (delete_backups) {
12335 if (abort_edit)
12336 option_conflict('X', 'a');
12337 if (continue_edit)
12338 option_conflict('X', 'c');
12339 if (drop_only)
12340 option_conflict('X', 'd');
12341 if (edit_script_path)
12342 option_conflict('X', 'F');
12343 if (edit_logmsg_only)
12344 option_conflict('X', 'm');
12345 if (fold_only)
12346 option_conflict('X', 'f');
12347 if (edit_only)
12348 option_conflict('X', 'e');
12349 if (list_backups)
12350 option_conflict('X', 'l');
12351 if (argc != 0 && argc != 1)
12352 usage_histedit();
12353 } else if (argc != 0)
12354 usage_histedit();
12357 * This command cannot apply unveil(2) in all cases because the
12358 * user may choose to run an editor to edit the histedit script
12359 * and to edit individual commit log messages.
12360 * unveil(2) traverses exec(2); if an editor is used we have to
12361 * apply unveil after edit script and log messages have been written.
12362 * XXX TODO: Make use of unveil(2) where possible.
12365 cwd = getcwd(NULL, 0);
12366 if (cwd == NULL) {
12367 error = got_error_from_errno("getcwd");
12368 goto done;
12371 error = got_repo_pack_fds_open(&pack_fds);
12372 if (error != NULL)
12373 goto done;
12375 error = got_worktree_open(&worktree, cwd);
12376 if (error) {
12377 if (list_backups || delete_backups) {
12378 if (error->code != GOT_ERR_NOT_WORKTREE)
12379 goto done;
12380 } else {
12381 if (error->code == GOT_ERR_NOT_WORKTREE)
12382 error = wrap_not_worktree_error(error,
12383 "histedit", cwd);
12384 goto done;
12388 if (list_backups || delete_backups) {
12389 error = got_repo_open(&repo,
12390 worktree ? got_worktree_get_repo_path(worktree) : cwd,
12391 NULL, pack_fds);
12392 if (error != NULL)
12393 goto done;
12394 error = apply_unveil(got_repo_get_path(repo), 0,
12395 worktree ? got_worktree_get_root_path(worktree) : NULL);
12396 if (error)
12397 goto done;
12398 error = process_backup_refs(
12399 GOT_WORKTREE_HISTEDIT_BACKUP_REF_PREFIX,
12400 argc == 1 ? argv[0] : NULL, delete_backups, repo);
12401 goto done; /* nothing else to do */
12404 error = get_gitconfig_path(&gitconfig_path);
12405 if (error)
12406 goto done;
12407 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
12408 gitconfig_path, pack_fds);
12409 if (error != NULL)
12410 goto done;
12412 if (worktree != NULL && !list_backups && !delete_backups) {
12413 error = worktree_has_logmsg_ref("histedit", worktree, repo);
12414 if (error)
12415 goto done;
12418 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
12419 if (error)
12420 goto done;
12421 if (rebase_in_progress) {
12422 error = got_error(GOT_ERR_REBASING);
12423 goto done;
12426 error = got_worktree_merge_in_progress(&merge_in_progress, worktree,
12427 repo);
12428 if (error)
12429 goto done;
12430 if (merge_in_progress) {
12431 error = got_error(GOT_ERR_MERGE_BUSY);
12432 goto done;
12435 error = got_worktree_histedit_in_progress(&edit_in_progress, worktree);
12436 if (error)
12437 goto done;
12439 if (edit_in_progress && edit_logmsg_only) {
12440 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
12441 "histedit operation is in progress in this "
12442 "work tree and must be continued or aborted "
12443 "before the -m option can be used");
12444 goto done;
12446 if (edit_in_progress && drop_only) {
12447 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
12448 "histedit operation is in progress in this "
12449 "work tree and must be continued or aborted "
12450 "before the -d option can be used");
12451 goto done;
12453 if (edit_in_progress && fold_only) {
12454 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
12455 "histedit operation is in progress in this "
12456 "work tree and must be continued or aborted "
12457 "before the -f option can be used");
12458 goto done;
12460 if (edit_in_progress && edit_only) {
12461 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
12462 "histedit operation is in progress in this "
12463 "work tree and must be continued or aborted "
12464 "before the -e option can be used");
12465 goto done;
12468 if (edit_in_progress && abort_edit) {
12469 error = got_worktree_histedit_continue(&resume_commit_id,
12470 &tmp_branch, &branch, &base_commit_id, &fileindex,
12471 worktree, repo);
12472 if (error)
12473 goto done;
12474 printf("Switching work tree to %s\n",
12475 got_ref_get_symref_target(branch));
12476 error = got_worktree_histedit_abort(worktree, fileindex, repo,
12477 branch, base_commit_id, abort_progress, &upa);
12478 if (error)
12479 goto done;
12480 printf("Histedit of %s aborted\n",
12481 got_ref_get_symref_target(branch));
12482 print_merge_progress_stats(&upa);
12483 goto done; /* nothing else to do */
12484 } else if (abort_edit) {
12485 error = got_error(GOT_ERR_NOT_HISTEDIT);
12486 goto done;
12489 error = get_author(&committer, repo, worktree);
12490 if (error)
12491 goto done;
12493 if (continue_edit) {
12494 char *path;
12496 if (!edit_in_progress) {
12497 error = got_error(GOT_ERR_NOT_HISTEDIT);
12498 goto done;
12501 error = got_worktree_get_histedit_script_path(&path, worktree);
12502 if (error)
12503 goto done;
12505 error = histedit_load_list(&histedit_cmds, path, repo);
12506 free(path);
12507 if (error)
12508 goto done;
12510 error = got_worktree_histedit_continue(&resume_commit_id,
12511 &tmp_branch, &branch, &base_commit_id, &fileindex,
12512 worktree, repo);
12513 if (error)
12514 goto done;
12516 error = got_ref_resolve(&head_commit_id, repo, branch);
12517 if (error)
12518 goto done;
12520 error = got_object_open_as_commit(&commit, repo,
12521 head_commit_id);
12522 if (error)
12523 goto done;
12524 parent_ids = got_object_commit_get_parent_ids(commit);
12525 pid = STAILQ_FIRST(parent_ids);
12526 if (pid == NULL) {
12527 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
12528 goto done;
12530 error = collect_commits(&commits, head_commit_id, &pid->id,
12531 base_commit_id, got_worktree_get_path_prefix(worktree),
12532 GOT_ERR_HISTEDIT_PATH, repo);
12533 got_object_commit_close(commit);
12534 commit = NULL;
12535 if (error)
12536 goto done;
12537 } else {
12538 if (edit_in_progress) {
12539 error = got_error(GOT_ERR_HISTEDIT_BUSY);
12540 goto done;
12543 error = got_ref_open(&branch, repo,
12544 got_worktree_get_head_ref_name(worktree), 0);
12545 if (error != NULL)
12546 goto done;
12548 if (strncmp(got_ref_get_name(branch), "refs/heads/", 11) != 0) {
12549 error = got_error_msg(GOT_ERR_COMMIT_BRANCH,
12550 "will not edit commit history of a branch outside "
12551 "the \"refs/heads/\" reference namespace");
12552 goto done;
12555 error = got_ref_resolve(&head_commit_id, repo, branch);
12556 got_ref_close(branch);
12557 branch = NULL;
12558 if (error)
12559 goto done;
12561 error = got_object_open_as_commit(&commit, repo,
12562 head_commit_id);
12563 if (error)
12564 goto done;
12565 parent_ids = got_object_commit_get_parent_ids(commit);
12566 pid = STAILQ_FIRST(parent_ids);
12567 if (pid == NULL) {
12568 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
12569 goto done;
12571 error = collect_commits(&commits, head_commit_id, &pid->id,
12572 got_worktree_get_base_commit_id(worktree),
12573 got_worktree_get_path_prefix(worktree),
12574 GOT_ERR_HISTEDIT_PATH, repo);
12575 got_object_commit_close(commit);
12576 commit = NULL;
12577 if (error)
12578 goto done;
12580 if (STAILQ_EMPTY(&commits)) {
12581 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
12582 goto done;
12585 error = got_worktree_histedit_prepare(&tmp_branch, &branch,
12586 &base_commit_id, &fileindex, worktree, repo);
12587 if (error)
12588 goto done;
12590 if (edit_script_path) {
12591 error = histedit_load_list(&histedit_cmds,
12592 edit_script_path, repo);
12593 if (error) {
12594 got_worktree_histedit_abort(worktree, fileindex,
12595 repo, branch, base_commit_id,
12596 abort_progress, &upa);
12597 print_merge_progress_stats(&upa);
12598 goto done;
12600 } else {
12601 const char *branch_name;
12602 branch_name = got_ref_get_symref_target(branch);
12603 if (strncmp(branch_name, "refs/heads/", 11) == 0)
12604 branch_name += 11;
12605 error = histedit_edit_script(&histedit_cmds, &commits,
12606 branch_name, edit_logmsg_only, fold_only,
12607 drop_only, edit_only, repo);
12608 if (error) {
12609 got_worktree_histedit_abort(worktree, fileindex,
12610 repo, branch, base_commit_id,
12611 abort_progress, &upa);
12612 print_merge_progress_stats(&upa);
12613 goto done;
12618 error = histedit_save_list(&histedit_cmds, worktree,
12619 repo);
12620 if (error) {
12621 got_worktree_histedit_abort(worktree, fileindex,
12622 repo, branch, base_commit_id,
12623 abort_progress, &upa);
12624 print_merge_progress_stats(&upa);
12625 goto done;
12630 error = histedit_check_script(&histedit_cmds, &commits, repo);
12631 if (error)
12632 goto done;
12634 TAILQ_FOREACH(hle, &histedit_cmds, entry) {
12635 if (resume_commit_id) {
12636 if (got_object_id_cmp(hle->commit_id,
12637 resume_commit_id) != 0)
12638 continue;
12640 resume_commit_id = NULL;
12641 if (hle->cmd->code == GOT_HISTEDIT_DROP ||
12642 hle->cmd->code == GOT_HISTEDIT_FOLD) {
12643 error = histedit_skip_commit(hle, worktree,
12644 repo);
12645 if (error)
12646 goto done;
12647 } else {
12648 struct got_pathlist_head paths;
12649 int have_changes = 0;
12651 TAILQ_INIT(&paths);
12652 error = got_pathlist_append(&paths, "", NULL);
12653 if (error)
12654 goto done;
12655 error = got_worktree_status(worktree, &paths,
12656 repo, 0, check_local_changes, &have_changes,
12657 check_cancelled, NULL);
12658 got_pathlist_free(&paths,
12659 GOT_PATHLIST_FREE_NONE);
12660 if (error) {
12661 if (error->code != GOT_ERR_CANCELLED)
12662 goto done;
12663 if (sigint_received || sigpipe_received)
12664 goto done;
12666 if (have_changes) {
12667 error = histedit_commit(NULL, worktree,
12668 fileindex, tmp_branch, hle,
12669 committer, repo);
12670 if (error)
12671 goto done;
12672 } else {
12673 error = got_object_open_as_commit(
12674 &commit, repo, hle->commit_id);
12675 if (error)
12676 goto done;
12677 error = show_histedit_progress(commit,
12678 hle, NULL);
12679 got_object_commit_close(commit);
12680 commit = NULL;
12681 if (error)
12682 goto done;
12685 continue;
12688 if (hle->cmd->code == GOT_HISTEDIT_DROP) {
12689 error = histedit_skip_commit(hle, worktree, repo);
12690 if (error)
12691 goto done;
12692 continue;
12695 error = got_object_open_as_commit(&commit, repo,
12696 hle->commit_id);
12697 if (error)
12698 goto done;
12699 parent_ids = got_object_commit_get_parent_ids(commit);
12700 pid = STAILQ_FIRST(parent_ids);
12702 error = got_worktree_histedit_merge_files(&merged_paths,
12703 worktree, fileindex, &pid->id, hle->commit_id, repo,
12704 update_progress, &upa, check_cancelled, NULL);
12705 if (error)
12706 goto done;
12707 got_object_commit_close(commit);
12708 commit = NULL;
12710 print_merge_progress_stats(&upa);
12711 if (upa.conflicts > 0 || upa.missing > 0 ||
12712 upa.not_deleted > 0 || upa.unversioned > 0) {
12713 if (upa.conflicts > 0) {
12714 error = show_rebase_merge_conflict(
12715 hle->commit_id, repo);
12716 if (error)
12717 goto done;
12719 got_pathlist_free(&merged_paths, GOT_PATHLIST_FREE_PATH);
12720 break;
12723 if (hle->cmd->code == GOT_HISTEDIT_EDIT) {
12724 char *id_str;
12725 error = got_object_id_str(&id_str, hle->commit_id);
12726 if (error)
12727 goto done;
12728 printf("Stopping histedit for amending commit %s\n",
12729 id_str);
12730 free(id_str);
12731 got_pathlist_free(&merged_paths, GOT_PATHLIST_FREE_PATH);
12732 error = got_worktree_histedit_postpone(worktree,
12733 fileindex);
12734 goto done;
12737 if (hle->cmd->code == GOT_HISTEDIT_FOLD) {
12738 error = histedit_skip_commit(hle, worktree, repo);
12739 if (error)
12740 goto done;
12741 continue;
12744 error = histedit_commit(&merged_paths, worktree, fileindex,
12745 tmp_branch, hle, committer, repo);
12746 got_pathlist_free(&merged_paths, GOT_PATHLIST_FREE_PATH);
12747 if (error)
12748 goto done;
12751 if (upa.conflicts > 0 || upa.missing > 0 ||
12752 upa.not_deleted > 0 || upa.unversioned > 0) {
12753 error = got_worktree_histedit_postpone(worktree, fileindex);
12754 if (error)
12755 goto done;
12756 if (upa.conflicts > 0 && upa.missing == 0 &&
12757 upa.not_deleted == 0 && upa.unversioned == 0) {
12758 error = got_error_msg(GOT_ERR_CONFLICTS,
12759 "conflicts must be resolved before histedit "
12760 "can continue");
12761 } else if (upa.conflicts > 0) {
12762 error = got_error_msg(GOT_ERR_CONFLICTS,
12763 "conflicts must be resolved before histedit "
12764 "can continue; changes destined for some "
12765 "files were not yet merged and should be "
12766 "merged manually if required before the "
12767 "histedit operation is continued");
12768 } else {
12769 error = got_error_msg(GOT_ERR_CONFLICTS,
12770 "changes destined for some files were not "
12771 "yet merged and should be merged manually "
12772 "if required before the histedit operation "
12773 "is continued");
12775 } else
12776 error = histedit_complete(worktree, fileindex, tmp_branch,
12777 branch, repo);
12778 done:
12779 free(cwd);
12780 free(committer);
12781 free(gitconfig_path);
12782 got_object_id_queue_free(&commits);
12783 histedit_free_list(&histedit_cmds);
12784 free(head_commit_id);
12785 free(base_commit_id);
12786 free(resume_commit_id);
12787 if (commit)
12788 got_object_commit_close(commit);
12789 if (branch)
12790 got_ref_close(branch);
12791 if (tmp_branch)
12792 got_ref_close(tmp_branch);
12793 if (worktree)
12794 got_worktree_close(worktree);
12795 if (repo) {
12796 const struct got_error *close_err = got_repo_close(repo);
12797 if (error == NULL)
12798 error = close_err;
12800 if (pack_fds) {
12801 const struct got_error *pack_err =
12802 got_repo_pack_fds_close(pack_fds);
12803 if (error == NULL)
12804 error = pack_err;
12806 return error;
12809 __dead static void
12810 usage_integrate(void)
12812 fprintf(stderr, "usage: %s integrate branch\n", getprogname());
12813 exit(1);
12816 static const struct got_error *
12817 cmd_integrate(int argc, char *argv[])
12819 const struct got_error *error = NULL;
12820 struct got_repository *repo = NULL;
12821 struct got_worktree *worktree = NULL;
12822 char *cwd = NULL, *refname = NULL, *base_refname = NULL;
12823 const char *branch_arg = NULL;
12824 struct got_reference *branch_ref = NULL, *base_branch_ref = NULL;
12825 struct got_fileindex *fileindex = NULL;
12826 struct got_object_id *commit_id = NULL, *base_commit_id = NULL;
12827 int ch;
12828 struct got_update_progress_arg upa;
12829 int *pack_fds = NULL;
12831 while ((ch = getopt(argc, argv, "")) != -1) {
12832 switch (ch) {
12833 default:
12834 usage_integrate();
12835 /* NOTREACHED */
12839 argc -= optind;
12840 argv += optind;
12842 if (argc != 1)
12843 usage_integrate();
12844 branch_arg = argv[0];
12845 #ifndef PROFILE
12846 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
12847 "unveil", NULL) == -1)
12848 err(1, "pledge");
12849 #endif
12850 cwd = getcwd(NULL, 0);
12851 if (cwd == NULL) {
12852 error = got_error_from_errno("getcwd");
12853 goto done;
12856 error = got_repo_pack_fds_open(&pack_fds);
12857 if (error != NULL)
12858 goto done;
12860 error = got_worktree_open(&worktree, cwd);
12861 if (error) {
12862 if (error->code == GOT_ERR_NOT_WORKTREE)
12863 error = wrap_not_worktree_error(error, "integrate",
12864 cwd);
12865 goto done;
12868 error = check_rebase_or_histedit_in_progress(worktree);
12869 if (error)
12870 goto done;
12872 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
12873 NULL, pack_fds);
12874 if (error != NULL)
12875 goto done;
12877 error = apply_unveil(got_repo_get_path(repo), 0,
12878 got_worktree_get_root_path(worktree));
12879 if (error)
12880 goto done;
12882 error = check_merge_in_progress(worktree, repo);
12883 if (error)
12884 goto done;
12886 if (asprintf(&refname, "refs/heads/%s", branch_arg) == -1) {
12887 error = got_error_from_errno("asprintf");
12888 goto done;
12891 error = got_worktree_integrate_prepare(&fileindex, &branch_ref,
12892 &base_branch_ref, worktree, refname, repo);
12893 if (error)
12894 goto done;
12896 refname = strdup(got_ref_get_name(branch_ref));
12897 if (refname == NULL) {
12898 error = got_error_from_errno("strdup");
12899 got_worktree_integrate_abort(worktree, fileindex, repo,
12900 branch_ref, base_branch_ref);
12901 goto done;
12903 base_refname = strdup(got_ref_get_name(base_branch_ref));
12904 if (base_refname == NULL) {
12905 error = got_error_from_errno("strdup");
12906 got_worktree_integrate_abort(worktree, fileindex, repo,
12907 branch_ref, base_branch_ref);
12908 goto done;
12910 if (strncmp(base_refname, "refs/heads/", 11) != 0) {
12911 error = got_error(GOT_ERR_INTEGRATE_BRANCH);
12912 got_worktree_integrate_abort(worktree, fileindex, repo,
12913 branch_ref, base_branch_ref);
12914 goto done;
12917 error = got_ref_resolve(&commit_id, repo, branch_ref);
12918 if (error)
12919 goto done;
12921 error = got_ref_resolve(&base_commit_id, repo, base_branch_ref);
12922 if (error)
12923 goto done;
12925 if (got_object_id_cmp(commit_id, base_commit_id) == 0) {
12926 error = got_error_msg(GOT_ERR_SAME_BRANCH,
12927 "specified branch has already been integrated");
12928 got_worktree_integrate_abort(worktree, fileindex, repo,
12929 branch_ref, base_branch_ref);
12930 goto done;
12933 error = check_linear_ancestry(commit_id, base_commit_id, 1, repo);
12934 if (error) {
12935 if (error->code == GOT_ERR_ANCESTRY)
12936 error = got_error(GOT_ERR_REBASE_REQUIRED);
12937 got_worktree_integrate_abort(worktree, fileindex, repo,
12938 branch_ref, base_branch_ref);
12939 goto done;
12942 memset(&upa, 0, sizeof(upa));
12943 error = got_worktree_integrate_continue(worktree, fileindex, repo,
12944 branch_ref, base_branch_ref, update_progress, &upa,
12945 check_cancelled, NULL);
12946 if (error)
12947 goto done;
12949 printf("Integrated %s into %s\n", refname, base_refname);
12950 print_update_progress_stats(&upa);
12951 done:
12952 if (repo) {
12953 const struct got_error *close_err = got_repo_close(repo);
12954 if (error == NULL)
12955 error = close_err;
12957 if (worktree)
12958 got_worktree_close(worktree);
12959 if (pack_fds) {
12960 const struct got_error *pack_err =
12961 got_repo_pack_fds_close(pack_fds);
12962 if (error == NULL)
12963 error = pack_err;
12965 free(cwd);
12966 free(base_commit_id);
12967 free(commit_id);
12968 free(refname);
12969 free(base_refname);
12970 return error;
12973 __dead static void
12974 usage_merge(void)
12976 fprintf(stderr, "usage: %s merge [-acn] [branch]\n", getprogname());
12977 exit(1);
12980 static const struct got_error *
12981 cmd_merge(int argc, char *argv[])
12983 const struct got_error *error = NULL;
12984 struct got_worktree *worktree = NULL;
12985 struct got_repository *repo = NULL;
12986 struct got_fileindex *fileindex = NULL;
12987 char *cwd = NULL, *id_str = NULL, *author = NULL;
12988 struct got_reference *branch = NULL, *wt_branch = NULL;
12989 struct got_object_id *branch_tip = NULL, *yca_id = NULL;
12990 struct got_object_id *wt_branch_tip = NULL;
12991 int ch, merge_in_progress = 0, abort_merge = 0, continue_merge = 0;
12992 int interrupt_merge = 0;
12993 struct got_update_progress_arg upa;
12994 struct got_object_id *merge_commit_id = NULL;
12995 char *branch_name = NULL;
12996 int *pack_fds = NULL;
12998 memset(&upa, 0, sizeof(upa));
13000 while ((ch = getopt(argc, argv, "acn")) != -1) {
13001 switch (ch) {
13002 case 'a':
13003 abort_merge = 1;
13004 break;
13005 case 'c':
13006 continue_merge = 1;
13007 break;
13008 case 'n':
13009 interrupt_merge = 1;
13010 break;
13011 default:
13012 usage_merge();
13013 /* NOTREACHED */
13017 argc -= optind;
13018 argv += optind;
13020 #ifndef PROFILE
13021 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
13022 "unveil", NULL) == -1)
13023 err(1, "pledge");
13024 #endif
13026 if (abort_merge && continue_merge)
13027 option_conflict('a', 'c');
13028 if (abort_merge || continue_merge) {
13029 if (argc != 0)
13030 usage_merge();
13031 } else if (argc != 1)
13032 usage_merge();
13034 cwd = getcwd(NULL, 0);
13035 if (cwd == NULL) {
13036 error = got_error_from_errno("getcwd");
13037 goto done;
13040 error = got_repo_pack_fds_open(&pack_fds);
13041 if (error != NULL)
13042 goto done;
13044 error = got_worktree_open(&worktree, cwd);
13045 if (error) {
13046 if (error->code == GOT_ERR_NOT_WORKTREE)
13047 error = wrap_not_worktree_error(error,
13048 "merge", cwd);
13049 goto done;
13052 error = got_repo_open(&repo,
13053 worktree ? got_worktree_get_repo_path(worktree) : cwd, NULL,
13054 pack_fds);
13055 if (error != NULL)
13056 goto done;
13058 if (worktree != NULL) {
13059 error = worktree_has_logmsg_ref("merge", worktree, repo);
13060 if (error)
13061 goto done;
13064 error = apply_unveil(got_repo_get_path(repo), 0,
13065 worktree ? got_worktree_get_root_path(worktree) : NULL);
13066 if (error)
13067 goto done;
13069 error = check_rebase_or_histedit_in_progress(worktree);
13070 if (error)
13071 goto done;
13073 error = got_worktree_merge_in_progress(&merge_in_progress, worktree,
13074 repo);
13075 if (error)
13076 goto done;
13078 if (abort_merge) {
13079 if (!merge_in_progress) {
13080 error = got_error(GOT_ERR_NOT_MERGING);
13081 goto done;
13083 error = got_worktree_merge_continue(&branch_name,
13084 &branch_tip, &fileindex, worktree, repo);
13085 if (error)
13086 goto done;
13087 error = got_worktree_merge_abort(worktree, fileindex, repo,
13088 abort_progress, &upa);
13089 if (error)
13090 goto done;
13091 printf("Merge of %s aborted\n", branch_name);
13092 goto done; /* nothing else to do */
13095 error = get_author(&author, repo, worktree);
13096 if (error)
13097 goto done;
13099 if (continue_merge) {
13100 if (!merge_in_progress) {
13101 error = got_error(GOT_ERR_NOT_MERGING);
13102 goto done;
13104 error = got_worktree_merge_continue(&branch_name,
13105 &branch_tip, &fileindex, worktree, repo);
13106 if (error)
13107 goto done;
13108 } else {
13109 error = got_ref_open(&branch, repo, argv[0], 0);
13110 if (error != NULL)
13111 goto done;
13112 branch_name = strdup(got_ref_get_name(branch));
13113 if (branch_name == NULL) {
13114 error = got_error_from_errno("strdup");
13115 goto done;
13117 error = got_ref_resolve(&branch_tip, repo, branch);
13118 if (error)
13119 goto done;
13122 error = got_ref_open(&wt_branch, repo,
13123 got_worktree_get_head_ref_name(worktree), 0);
13124 if (error)
13125 goto done;
13126 error = got_ref_resolve(&wt_branch_tip, repo, wt_branch);
13127 if (error)
13128 goto done;
13129 error = got_commit_graph_find_youngest_common_ancestor(&yca_id,
13130 wt_branch_tip, branch_tip, 0, repo,
13131 check_cancelled, NULL);
13132 if (error && error->code != GOT_ERR_ANCESTRY)
13133 goto done;
13135 if (!continue_merge) {
13136 error = check_path_prefix(wt_branch_tip, branch_tip,
13137 got_worktree_get_path_prefix(worktree),
13138 GOT_ERR_MERGE_PATH, repo);
13139 if (error)
13140 goto done;
13141 if (yca_id) {
13142 error = check_same_branch(wt_branch_tip, branch,
13143 yca_id, repo);
13144 if (error) {
13145 if (error->code != GOT_ERR_ANCESTRY)
13146 goto done;
13147 error = NULL;
13148 } else {
13149 static char msg[512];
13150 snprintf(msg, sizeof(msg),
13151 "cannot create a merge commit because "
13152 "%s is based on %s; %s can be integrated "
13153 "with 'got integrate' instead", branch_name,
13154 got_worktree_get_head_ref_name(worktree),
13155 branch_name);
13156 error = got_error_msg(GOT_ERR_SAME_BRANCH, msg);
13157 goto done;
13160 error = got_worktree_merge_prepare(&fileindex, worktree,
13161 branch, repo);
13162 if (error)
13163 goto done;
13165 error = got_worktree_merge_branch(worktree, fileindex,
13166 yca_id, branch_tip, repo, update_progress, &upa,
13167 check_cancelled, NULL);
13168 if (error)
13169 goto done;
13170 print_merge_progress_stats(&upa);
13171 if (!upa.did_something) {
13172 error = got_worktree_merge_abort(worktree, fileindex,
13173 repo, abort_progress, &upa);
13174 if (error)
13175 goto done;
13176 printf("Already up-to-date\n");
13177 goto done;
13181 if (interrupt_merge) {
13182 error = got_worktree_merge_postpone(worktree, fileindex);
13183 if (error)
13184 goto done;
13185 printf("Merge of %s interrupted on request\n", branch_name);
13186 } else if (upa.conflicts > 0 || upa.missing > 0 ||
13187 upa.not_deleted > 0 || upa.unversioned > 0) {
13188 error = got_worktree_merge_postpone(worktree, fileindex);
13189 if (error)
13190 goto done;
13191 if (upa.conflicts > 0 && upa.missing == 0 &&
13192 upa.not_deleted == 0 && upa.unversioned == 0) {
13193 error = got_error_msg(GOT_ERR_CONFLICTS,
13194 "conflicts must be resolved before merging "
13195 "can continue");
13196 } else if (upa.conflicts > 0) {
13197 error = got_error_msg(GOT_ERR_CONFLICTS,
13198 "conflicts must be resolved before merging "
13199 "can continue; changes destined for some "
13200 "files were not yet merged and "
13201 "should be merged manually if required before the "
13202 "merge operation is continued");
13203 } else {
13204 error = got_error_msg(GOT_ERR_CONFLICTS,
13205 "changes destined for some "
13206 "files were not yet merged and should be "
13207 "merged manually if required before the "
13208 "merge operation is continued");
13210 goto done;
13211 } else {
13212 error = got_worktree_merge_commit(&merge_commit_id, worktree,
13213 fileindex, author, NULL, 1, branch_tip, branch_name,
13214 repo, continue_merge ? print_status : NULL, NULL);
13215 if (error)
13216 goto done;
13217 error = got_worktree_merge_complete(worktree, fileindex, repo);
13218 if (error)
13219 goto done;
13220 error = got_object_id_str(&id_str, merge_commit_id);
13221 if (error)
13222 goto done;
13223 printf("Merged %s into %s: %s\n", branch_name,
13224 got_worktree_get_head_ref_name(worktree),
13225 id_str);
13228 done:
13229 free(id_str);
13230 free(merge_commit_id);
13231 free(author);
13232 free(branch_tip);
13233 free(branch_name);
13234 free(yca_id);
13235 if (branch)
13236 got_ref_close(branch);
13237 if (wt_branch)
13238 got_ref_close(wt_branch);
13239 if (worktree)
13240 got_worktree_close(worktree);
13241 if (repo) {
13242 const struct got_error *close_err = got_repo_close(repo);
13243 if (error == NULL)
13244 error = close_err;
13246 if (pack_fds) {
13247 const struct got_error *pack_err =
13248 got_repo_pack_fds_close(pack_fds);
13249 if (error == NULL)
13250 error = pack_err;
13252 return error;
13255 __dead static void
13256 usage_stage(void)
13258 fprintf(stderr, "usage: %s stage [-lpS] [-F response-script] "
13259 "[path ...]\n", getprogname());
13260 exit(1);
13263 static const struct got_error *
13264 print_stage(void *arg, unsigned char status, unsigned char staged_status,
13265 const char *path, struct got_object_id *blob_id,
13266 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
13267 int dirfd, const char *de_name)
13269 const struct got_error *err = NULL;
13270 char *id_str = NULL;
13272 if (staged_status != GOT_STATUS_ADD &&
13273 staged_status != GOT_STATUS_MODIFY &&
13274 staged_status != GOT_STATUS_DELETE)
13275 return NULL;
13277 if (staged_status == GOT_STATUS_ADD ||
13278 staged_status == GOT_STATUS_MODIFY)
13279 err = got_object_id_str(&id_str, staged_blob_id);
13280 else
13281 err = got_object_id_str(&id_str, blob_id);
13282 if (err)
13283 return err;
13285 printf("%s %c %s\n", id_str, staged_status, path);
13286 free(id_str);
13287 return NULL;
13290 static const struct got_error *
13291 cmd_stage(int argc, char *argv[])
13293 const struct got_error *error = NULL;
13294 struct got_repository *repo = NULL;
13295 struct got_worktree *worktree = NULL;
13296 char *cwd = NULL;
13297 struct got_pathlist_head paths;
13298 int ch, list_stage = 0, pflag = 0, allow_bad_symlinks = 0;
13299 FILE *patch_script_file = NULL;
13300 const char *patch_script_path = NULL;
13301 struct choose_patch_arg cpa;
13302 int *pack_fds = NULL;
13304 TAILQ_INIT(&paths);
13306 while ((ch = getopt(argc, argv, "F:lpS")) != -1) {
13307 switch (ch) {
13308 case 'F':
13309 patch_script_path = optarg;
13310 break;
13311 case 'l':
13312 list_stage = 1;
13313 break;
13314 case 'p':
13315 pflag = 1;
13316 break;
13317 case 'S':
13318 allow_bad_symlinks = 1;
13319 break;
13320 default:
13321 usage_stage();
13322 /* NOTREACHED */
13326 argc -= optind;
13327 argv += optind;
13329 #ifndef PROFILE
13330 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
13331 "unveil", NULL) == -1)
13332 err(1, "pledge");
13333 #endif
13334 if (list_stage && (pflag || patch_script_path))
13335 errx(1, "-l option cannot be used with other options");
13336 if (patch_script_path && !pflag)
13337 errx(1, "-F option can only be used together with -p option");
13339 cwd = getcwd(NULL, 0);
13340 if (cwd == NULL) {
13341 error = got_error_from_errno("getcwd");
13342 goto done;
13345 error = got_repo_pack_fds_open(&pack_fds);
13346 if (error != NULL)
13347 goto done;
13349 error = got_worktree_open(&worktree, cwd);
13350 if (error) {
13351 if (error->code == GOT_ERR_NOT_WORKTREE)
13352 error = wrap_not_worktree_error(error, "stage", cwd);
13353 goto done;
13356 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
13357 NULL, pack_fds);
13358 if (error != NULL)
13359 goto done;
13361 if (patch_script_path) {
13362 patch_script_file = fopen(patch_script_path, "re");
13363 if (patch_script_file == NULL) {
13364 error = got_error_from_errno2("fopen",
13365 patch_script_path);
13366 goto done;
13369 error = apply_unveil(got_repo_get_path(repo), 0,
13370 got_worktree_get_root_path(worktree));
13371 if (error)
13372 goto done;
13374 error = check_merge_in_progress(worktree, repo);
13375 if (error)
13376 goto done;
13378 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
13379 if (error)
13380 goto done;
13382 if (list_stage)
13383 error = got_worktree_status(worktree, &paths, repo, 0,
13384 print_stage, NULL, check_cancelled, NULL);
13385 else {
13386 cpa.patch_script_file = patch_script_file;
13387 cpa.action = "stage";
13388 error = got_worktree_stage(worktree, &paths,
13389 pflag ? NULL : print_status, NULL,
13390 pflag ? choose_patch : NULL, &cpa,
13391 allow_bad_symlinks, repo);
13393 done:
13394 if (patch_script_file && fclose(patch_script_file) == EOF &&
13395 error == NULL)
13396 error = got_error_from_errno2("fclose", patch_script_path);
13397 if (repo) {
13398 const struct got_error *close_err = got_repo_close(repo);
13399 if (error == NULL)
13400 error = close_err;
13402 if (worktree)
13403 got_worktree_close(worktree);
13404 if (pack_fds) {
13405 const struct got_error *pack_err =
13406 got_repo_pack_fds_close(pack_fds);
13407 if (error == NULL)
13408 error = pack_err;
13410 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
13411 free(cwd);
13412 return error;
13415 __dead static void
13416 usage_unstage(void)
13418 fprintf(stderr, "usage: %s unstage [-p] [-F response-script] "
13419 "[path ...]\n", getprogname());
13420 exit(1);
13424 static const struct got_error *
13425 cmd_unstage(int argc, char *argv[])
13427 const struct got_error *error = NULL;
13428 struct got_repository *repo = NULL;
13429 struct got_worktree *worktree = NULL;
13430 char *cwd = NULL;
13431 struct got_pathlist_head paths;
13432 int ch, pflag = 0;
13433 struct got_update_progress_arg upa;
13434 FILE *patch_script_file = NULL;
13435 const char *patch_script_path = NULL;
13436 struct choose_patch_arg cpa;
13437 int *pack_fds = NULL;
13439 TAILQ_INIT(&paths);
13441 while ((ch = getopt(argc, argv, "F:p")) != -1) {
13442 switch (ch) {
13443 case 'F':
13444 patch_script_path = optarg;
13445 break;
13446 case 'p':
13447 pflag = 1;
13448 break;
13449 default:
13450 usage_unstage();
13451 /* NOTREACHED */
13455 argc -= optind;
13456 argv += optind;
13458 #ifndef PROFILE
13459 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
13460 "unveil", NULL) == -1)
13461 err(1, "pledge");
13462 #endif
13463 if (patch_script_path && !pflag)
13464 errx(1, "-F option can only be used together with -p option");
13466 cwd = getcwd(NULL, 0);
13467 if (cwd == NULL) {
13468 error = got_error_from_errno("getcwd");
13469 goto done;
13472 error = got_repo_pack_fds_open(&pack_fds);
13473 if (error != NULL)
13474 goto done;
13476 error = got_worktree_open(&worktree, cwd);
13477 if (error) {
13478 if (error->code == GOT_ERR_NOT_WORKTREE)
13479 error = wrap_not_worktree_error(error, "unstage", cwd);
13480 goto done;
13483 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
13484 NULL, pack_fds);
13485 if (error != NULL)
13486 goto done;
13488 if (patch_script_path) {
13489 patch_script_file = fopen(patch_script_path, "re");
13490 if (patch_script_file == NULL) {
13491 error = got_error_from_errno2("fopen",
13492 patch_script_path);
13493 goto done;
13497 error = apply_unveil(got_repo_get_path(repo), 0,
13498 got_worktree_get_root_path(worktree));
13499 if (error)
13500 goto done;
13502 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
13503 if (error)
13504 goto done;
13506 cpa.patch_script_file = patch_script_file;
13507 cpa.action = "unstage";
13508 memset(&upa, 0, sizeof(upa));
13509 error = got_worktree_unstage(worktree, &paths, update_progress,
13510 &upa, pflag ? choose_patch : NULL, &cpa, repo);
13511 if (!error)
13512 print_merge_progress_stats(&upa);
13513 done:
13514 if (patch_script_file && fclose(patch_script_file) == EOF &&
13515 error == NULL)
13516 error = got_error_from_errno2("fclose", patch_script_path);
13517 if (repo) {
13518 const struct got_error *close_err = got_repo_close(repo);
13519 if (error == NULL)
13520 error = close_err;
13522 if (worktree)
13523 got_worktree_close(worktree);
13524 if (pack_fds) {
13525 const struct got_error *pack_err =
13526 got_repo_pack_fds_close(pack_fds);
13527 if (error == NULL)
13528 error = pack_err;
13530 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
13531 free(cwd);
13532 return error;
13535 __dead static void
13536 usage_cat(void)
13538 fprintf(stderr, "usage: %s cat [-P] [-c commit] [-r repository-path] "
13539 "arg ...\n", getprogname());
13540 exit(1);
13543 static const struct got_error *
13544 cat_blob(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
13546 const struct got_error *err;
13547 struct got_blob_object *blob;
13548 int fd = -1;
13550 fd = got_opentempfd();
13551 if (fd == -1)
13552 return got_error_from_errno("got_opentempfd");
13554 err = got_object_open_as_blob(&blob, repo, id, 8192, fd);
13555 if (err)
13556 goto done;
13558 err = got_object_blob_dump_to_file(NULL, NULL, NULL, outfile, blob);
13559 done:
13560 if (fd != -1 && close(fd) == -1 && err == NULL)
13561 err = got_error_from_errno("close");
13562 if (blob)
13563 got_object_blob_close(blob);
13564 return err;
13567 static const struct got_error *
13568 cat_tree(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
13570 const struct got_error *err;
13571 struct got_tree_object *tree;
13572 int nentries, i;
13574 err = got_object_open_as_tree(&tree, repo, id);
13575 if (err)
13576 return err;
13578 nentries = got_object_tree_get_nentries(tree);
13579 for (i = 0; i < nentries; i++) {
13580 struct got_tree_entry *te;
13581 char *id_str;
13582 if (sigint_received || sigpipe_received)
13583 break;
13584 te = got_object_tree_get_entry(tree, i);
13585 err = got_object_id_str(&id_str, got_tree_entry_get_id(te));
13586 if (err)
13587 break;
13588 fprintf(outfile, "%s %.7o %s\n", id_str,
13589 got_tree_entry_get_mode(te),
13590 got_tree_entry_get_name(te));
13591 free(id_str);
13594 got_object_tree_close(tree);
13595 return err;
13598 static const struct got_error *
13599 cat_commit(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
13601 const struct got_error *err;
13602 struct got_commit_object *commit;
13603 const struct got_object_id_queue *parent_ids;
13604 struct got_object_qid *pid;
13605 char *id_str = NULL;
13606 const char *logmsg = NULL;
13607 char gmtoff[6];
13609 err = got_object_open_as_commit(&commit, repo, id);
13610 if (err)
13611 return err;
13613 err = got_object_id_str(&id_str, got_object_commit_get_tree_id(commit));
13614 if (err)
13615 goto done;
13617 fprintf(outfile, "%s%s\n", GOT_COMMIT_LABEL_TREE, id_str);
13618 parent_ids = got_object_commit_get_parent_ids(commit);
13619 fprintf(outfile, "numparents %d\n",
13620 got_object_commit_get_nparents(commit));
13621 STAILQ_FOREACH(pid, parent_ids, entry) {
13622 char *pid_str;
13623 err = got_object_id_str(&pid_str, &pid->id);
13624 if (err)
13625 goto done;
13626 fprintf(outfile, "%s%s\n", GOT_COMMIT_LABEL_PARENT, pid_str);
13627 free(pid_str);
13629 got_date_format_gmtoff(gmtoff, sizeof(gmtoff),
13630 got_object_commit_get_author_gmtoff(commit));
13631 fprintf(outfile, "%s%s %lld %s\n", GOT_COMMIT_LABEL_AUTHOR,
13632 got_object_commit_get_author(commit),
13633 (long long)got_object_commit_get_author_time(commit),
13634 gmtoff);
13636 got_date_format_gmtoff(gmtoff, sizeof(gmtoff),
13637 got_object_commit_get_committer_gmtoff(commit));
13638 fprintf(outfile, "%s%s %lld %s\n", GOT_COMMIT_LABEL_COMMITTER,
13639 got_object_commit_get_committer(commit),
13640 (long long)got_object_commit_get_committer_time(commit),
13641 gmtoff);
13643 logmsg = got_object_commit_get_logmsg_raw(commit);
13644 fprintf(outfile, "messagelen %zd\n", strlen(logmsg));
13645 fprintf(outfile, "%s", logmsg);
13646 done:
13647 free(id_str);
13648 got_object_commit_close(commit);
13649 return err;
13652 static const struct got_error *
13653 cat_tag(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
13655 const struct got_error *err;
13656 struct got_tag_object *tag;
13657 char *id_str = NULL;
13658 const char *tagmsg = NULL;
13659 char gmtoff[6];
13661 err = got_object_open_as_tag(&tag, repo, id);
13662 if (err)
13663 return err;
13665 err = got_object_id_str(&id_str, got_object_tag_get_object_id(tag));
13666 if (err)
13667 goto done;
13669 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_OBJECT, id_str);
13671 switch (got_object_tag_get_object_type(tag)) {
13672 case GOT_OBJ_TYPE_BLOB:
13673 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
13674 GOT_OBJ_LABEL_BLOB);
13675 break;
13676 case GOT_OBJ_TYPE_TREE:
13677 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
13678 GOT_OBJ_LABEL_TREE);
13679 break;
13680 case GOT_OBJ_TYPE_COMMIT:
13681 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
13682 GOT_OBJ_LABEL_COMMIT);
13683 break;
13684 case GOT_OBJ_TYPE_TAG:
13685 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
13686 GOT_OBJ_LABEL_TAG);
13687 break;
13688 default:
13689 break;
13692 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TAG,
13693 got_object_tag_get_name(tag));
13695 got_date_format_gmtoff(gmtoff, sizeof(gmtoff),
13696 got_object_tag_get_tagger_gmtoff(tag));
13697 fprintf(outfile, "%s%s %lld %s\n", GOT_TAG_LABEL_TAGGER,
13698 got_object_tag_get_tagger(tag),
13699 (long long)got_object_tag_get_tagger_time(tag),
13700 gmtoff);
13702 tagmsg = got_object_tag_get_message(tag);
13703 fprintf(outfile, "messagelen %zd\n", strlen(tagmsg));
13704 fprintf(outfile, "%s", tagmsg);
13705 done:
13706 free(id_str);
13707 got_object_tag_close(tag);
13708 return err;
13711 static const struct got_error *
13712 cmd_cat(int argc, char *argv[])
13714 const struct got_error *error;
13715 struct got_repository *repo = NULL;
13716 struct got_worktree *worktree = NULL;
13717 char *cwd = NULL, *repo_path = NULL, *label = NULL;
13718 const char *commit_id_str = NULL;
13719 struct got_object_id *id = NULL, *commit_id = NULL;
13720 struct got_commit_object *commit = NULL;
13721 int ch, obj_type, i, force_path = 0;
13722 struct got_reflist_head refs;
13723 int *pack_fds = NULL;
13725 TAILQ_INIT(&refs);
13727 #ifndef PROFILE
13728 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
13729 NULL) == -1)
13730 err(1, "pledge");
13731 #endif
13733 while ((ch = getopt(argc, argv, "c:Pr:")) != -1) {
13734 switch (ch) {
13735 case 'c':
13736 commit_id_str = optarg;
13737 break;
13738 case 'P':
13739 force_path = 1;
13740 break;
13741 case 'r':
13742 repo_path = realpath(optarg, NULL);
13743 if (repo_path == NULL)
13744 return got_error_from_errno2("realpath",
13745 optarg);
13746 got_path_strip_trailing_slashes(repo_path);
13747 break;
13748 default:
13749 usage_cat();
13750 /* NOTREACHED */
13754 argc -= optind;
13755 argv += optind;
13757 cwd = getcwd(NULL, 0);
13758 if (cwd == NULL) {
13759 error = got_error_from_errno("getcwd");
13760 goto done;
13763 error = got_repo_pack_fds_open(&pack_fds);
13764 if (error != NULL)
13765 goto done;
13767 if (repo_path == NULL) {
13768 error = got_worktree_open(&worktree, cwd);
13769 if (error && error->code != GOT_ERR_NOT_WORKTREE)
13770 goto done;
13771 if (worktree) {
13772 repo_path = strdup(
13773 got_worktree_get_repo_path(worktree));
13774 if (repo_path == NULL) {
13775 error = got_error_from_errno("strdup");
13776 goto done;
13779 /* Release work tree lock. */
13780 got_worktree_close(worktree);
13781 worktree = NULL;
13785 if (repo_path == NULL) {
13786 repo_path = strdup(cwd);
13787 if (repo_path == NULL)
13788 return got_error_from_errno("strdup");
13791 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
13792 free(repo_path);
13793 if (error != NULL)
13794 goto done;
13796 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
13797 if (error)
13798 goto done;
13800 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
13801 if (error)
13802 goto done;
13804 if (commit_id_str == NULL)
13805 commit_id_str = GOT_REF_HEAD;
13806 error = got_repo_match_object_id(&commit_id, NULL,
13807 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
13808 if (error)
13809 goto done;
13811 error = got_object_open_as_commit(&commit, repo, commit_id);
13812 if (error)
13813 goto done;
13815 for (i = 0; i < argc; i++) {
13816 if (force_path) {
13817 error = got_object_id_by_path(&id, repo, commit,
13818 argv[i]);
13819 if (error)
13820 break;
13821 } else {
13822 error = got_repo_match_object_id(&id, &label, argv[i],
13823 GOT_OBJ_TYPE_ANY, NULL /* do not resolve tags */,
13824 repo);
13825 if (error) {
13826 if (error->code != GOT_ERR_BAD_OBJ_ID_STR &&
13827 error->code != GOT_ERR_NOT_REF)
13828 break;
13829 error = got_object_id_by_path(&id, repo,
13830 commit, argv[i]);
13831 if (error)
13832 break;
13836 error = got_object_get_type(&obj_type, repo, id);
13837 if (error)
13838 break;
13840 switch (obj_type) {
13841 case GOT_OBJ_TYPE_BLOB:
13842 error = cat_blob(id, repo, stdout);
13843 break;
13844 case GOT_OBJ_TYPE_TREE:
13845 error = cat_tree(id, repo, stdout);
13846 break;
13847 case GOT_OBJ_TYPE_COMMIT:
13848 error = cat_commit(id, repo, stdout);
13849 break;
13850 case GOT_OBJ_TYPE_TAG:
13851 error = cat_tag(id, repo, stdout);
13852 break;
13853 default:
13854 error = got_error(GOT_ERR_OBJ_TYPE);
13855 break;
13857 if (error)
13858 break;
13859 free(label);
13860 label = NULL;
13861 free(id);
13862 id = NULL;
13864 done:
13865 free(label);
13866 free(id);
13867 free(commit_id);
13868 if (commit)
13869 got_object_commit_close(commit);
13870 if (worktree)
13871 got_worktree_close(worktree);
13872 if (repo) {
13873 const struct got_error *close_err = got_repo_close(repo);
13874 if (error == NULL)
13875 error = close_err;
13877 if (pack_fds) {
13878 const struct got_error *pack_err =
13879 got_repo_pack_fds_close(pack_fds);
13880 if (error == NULL)
13881 error = pack_err;
13884 got_ref_list_free(&refs);
13885 return error;
13888 __dead static void
13889 usage_info(void)
13891 fprintf(stderr, "usage: %s info [path ...]\n",
13892 getprogname());
13893 exit(1);
13896 static const struct got_error *
13897 print_path_info(void *arg, const char *path, mode_t mode, time_t mtime,
13898 struct got_object_id *blob_id, struct got_object_id *staged_blob_id,
13899 struct got_object_id *commit_id)
13901 const struct got_error *err = NULL;
13902 char *id_str = NULL;
13903 char datebuf[128];
13904 struct tm mytm, *tm;
13905 struct got_pathlist_head *paths = arg;
13906 struct got_pathlist_entry *pe;
13909 * Clear error indication from any of the path arguments which
13910 * would cause this file index entry to be displayed.
13912 TAILQ_FOREACH(pe, paths, entry) {
13913 if (got_path_cmp(path, pe->path, strlen(path),
13914 pe->path_len) == 0 ||
13915 got_path_is_child(path, pe->path, pe->path_len))
13916 pe->data = NULL; /* no error */
13919 printf(GOT_COMMIT_SEP_STR);
13920 if (S_ISLNK(mode))
13921 printf("symlink: %s\n", path);
13922 else if (S_ISREG(mode)) {
13923 printf("file: %s\n", path);
13924 printf("mode: %o\n", mode & (S_IRWXU | S_IRWXG | S_IRWXO));
13925 } else if (S_ISDIR(mode))
13926 printf("directory: %s\n", path);
13927 else
13928 printf("something: %s\n", path);
13930 tm = localtime_r(&mtime, &mytm);
13931 if (tm == NULL)
13932 return NULL;
13933 if (strftime(datebuf, sizeof(datebuf), "%c %Z", tm) == 0)
13934 return got_error(GOT_ERR_NO_SPACE);
13935 printf("timestamp: %s\n", datebuf);
13937 if (blob_id) {
13938 err = got_object_id_str(&id_str, blob_id);
13939 if (err)
13940 return err;
13941 printf("based on blob: %s\n", id_str);
13942 free(id_str);
13945 if (staged_blob_id) {
13946 err = got_object_id_str(&id_str, staged_blob_id);
13947 if (err)
13948 return err;
13949 printf("based on staged blob: %s\n", id_str);
13950 free(id_str);
13953 if (commit_id) {
13954 err = got_object_id_str(&id_str, commit_id);
13955 if (err)
13956 return err;
13957 printf("based on commit: %s\n", id_str);
13958 free(id_str);
13961 return NULL;
13964 static const struct got_error *
13965 cmd_info(int argc, char *argv[])
13967 const struct got_error *error = NULL;
13968 struct got_worktree *worktree = NULL;
13969 char *cwd = NULL, *id_str = NULL;
13970 struct got_pathlist_head paths;
13971 char *uuidstr = NULL;
13972 int ch, show_files = 0;
13974 TAILQ_INIT(&paths);
13976 while ((ch = getopt(argc, argv, "")) != -1) {
13977 switch (ch) {
13978 default:
13979 usage_info();
13980 /* NOTREACHED */
13984 argc -= optind;
13985 argv += optind;
13987 #ifndef PROFILE
13988 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
13989 NULL) == -1)
13990 err(1, "pledge");
13991 #endif
13992 cwd = getcwd(NULL, 0);
13993 if (cwd == NULL) {
13994 error = got_error_from_errno("getcwd");
13995 goto done;
13998 error = got_worktree_open(&worktree, cwd);
13999 if (error) {
14000 if (error->code == GOT_ERR_NOT_WORKTREE)
14001 error = wrap_not_worktree_error(error, "info", cwd);
14002 goto done;
14005 #ifndef PROFILE
14006 /* Remove "wpath cpath proc exec sendfd" promises. */
14007 if (pledge("stdio rpath flock unveil", NULL) == -1)
14008 err(1, "pledge");
14009 #endif
14010 error = apply_unveil(NULL, 0, got_worktree_get_root_path(worktree));
14011 if (error)
14012 goto done;
14014 if (argc >= 1) {
14015 error = get_worktree_paths_from_argv(&paths, argc, argv,
14016 worktree);
14017 if (error)
14018 goto done;
14019 show_files = 1;
14022 error = got_object_id_str(&id_str,
14023 got_worktree_get_base_commit_id(worktree));
14024 if (error)
14025 goto done;
14027 error = got_worktree_get_uuid(&uuidstr, worktree);
14028 if (error)
14029 goto done;
14031 printf("work tree: %s\n", got_worktree_get_root_path(worktree));
14032 printf("work tree base commit: %s\n", id_str);
14033 printf("work tree path prefix: %s\n",
14034 got_worktree_get_path_prefix(worktree));
14035 printf("work tree branch reference: %s\n",
14036 got_worktree_get_head_ref_name(worktree));
14037 printf("work tree UUID: %s\n", uuidstr);
14038 printf("repository: %s\n", got_worktree_get_repo_path(worktree));
14040 if (show_files) {
14041 struct got_pathlist_entry *pe;
14042 TAILQ_FOREACH(pe, &paths, entry) {
14043 if (pe->path_len == 0)
14044 continue;
14046 * Assume this path will fail. This will be corrected
14047 * in print_path_info() in case the path does suceeed.
14049 pe->data = (void *)got_error(GOT_ERR_BAD_PATH);
14051 error = got_worktree_path_info(worktree, &paths,
14052 print_path_info, &paths, check_cancelled, NULL);
14053 if (error)
14054 goto done;
14055 TAILQ_FOREACH(pe, &paths, entry) {
14056 if (pe->data != NULL) {
14057 const struct got_error *perr;
14059 perr = pe->data;
14060 error = got_error_fmt(perr->code, "%s",
14061 pe->path);
14062 break;
14066 done:
14067 if (worktree)
14068 got_worktree_close(worktree);
14069 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
14070 free(cwd);
14071 free(id_str);
14072 free(uuidstr);
14073 return error;