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)
4203 const struct got_error *err = NULL;
4204 FILE *f = NULL;
4205 char *id_str, *datestr, *logmsg0, *logmsg, *line;
4206 char datebuf[26];
4207 time_t committer_time;
4208 const char *author, *committer;
4209 char *refs_str = NULL;
4211 err = got_object_id_str(&id_str, id);
4212 if (err)
4213 return err;
4215 if (custom_refs_str == NULL) {
4216 struct got_reflist_head *refs;
4217 refs = got_reflist_object_id_map_lookup(refs_idmap, id);
4218 if (refs) {
4219 err = build_refs_str(&refs_str, refs, id, repo, 0);
4220 if (err)
4221 goto done;
4225 printf(GOT_COMMIT_SEP_STR);
4226 if (custom_refs_str)
4227 printf("commit %s (%s)\n", id_str, custom_refs_str);
4228 else
4229 printf("commit %s%s%s%s\n", id_str, refs_str ? " (" : "",
4230 refs_str ? refs_str : "", refs_str ? ")" : "");
4231 free(id_str);
4232 id_str = NULL;
4233 free(refs_str);
4234 refs_str = NULL;
4235 printf("from: %s\n", got_object_commit_get_author(commit));
4236 author = got_object_commit_get_author(commit);
4237 committer = got_object_commit_get_committer(commit);
4238 if (strcmp(author, committer) != 0)
4239 printf("via: %s\n", committer);
4240 committer_time = got_object_commit_get_committer_time(commit);
4241 datestr = get_datestr(&committer_time, datebuf);
4242 if (datestr)
4243 printf("date: %s UTC\n", datestr);
4244 if (got_object_commit_get_nparents(commit) > 1) {
4245 const struct got_object_id_queue *parent_ids;
4246 struct got_object_qid *qid;
4247 int n = 1;
4248 parent_ids = got_object_commit_get_parent_ids(commit);
4249 STAILQ_FOREACH(qid, parent_ids, entry) {
4250 err = got_object_id_str(&id_str, &qid->id);
4251 if (err)
4252 goto done;
4253 printf("parent %d: %s\n", n++, id_str);
4254 free(id_str);
4255 id_str = NULL;
4259 err = got_object_commit_get_logmsg(&logmsg0, commit);
4260 if (err)
4261 goto done;
4263 logmsg = logmsg0;
4264 do {
4265 line = strsep(&logmsg, "\n");
4266 if (line)
4267 printf(" %s\n", line);
4268 } while (line);
4269 free(logmsg0);
4271 if (changed_paths && diffstat == NULL) {
4272 struct got_pathlist_entry *pe;
4274 TAILQ_FOREACH(pe, changed_paths, entry) {
4275 struct got_diff_changed_path *cp = pe->data;
4277 printf(" %c %s\n", cp->status, pe->path);
4279 printf("\n");
4281 if (show_patch) {
4282 if (diffstat) {
4283 f = got_opentemp();
4284 if (f == NULL) {
4285 err = got_error_from_errno("got_opentemp");
4286 goto done;
4290 err = print_patch(commit, id, path, diff_context, diffstat,
4291 repo, diffstat == NULL ? stdout : f);
4292 if (err)
4293 goto done;
4295 if (diffstat) {
4296 err = print_diffstat(diffstat, NULL);
4297 if (err)
4298 goto done;
4299 if (show_patch) {
4300 err = printfile(f);
4301 if (err)
4302 goto done;
4305 if (show_patch)
4306 printf("\n");
4308 if (fflush(stdout) != 0 && err == NULL)
4309 err = got_error_from_errno("fflush");
4310 done:
4311 if (f && fclose(f) == EOF && err == NULL)
4312 err = got_error_from_errno("fclose");
4313 free(id_str);
4314 free(refs_str);
4315 return err;
4318 static const struct got_error *
4319 print_commits(struct got_object_id *root_id, struct got_object_id *end_id,
4320 struct got_repository *repo, const char *path, int show_changed_paths,
4321 int show_diffstat, int show_patch, const char *search_pattern,
4322 int diff_context, int limit, int log_branches, int reverse_display_order,
4323 struct got_reflist_object_id_map *refs_idmap, int one_line,
4324 FILE *tmpfile)
4326 const struct got_error *err;
4327 struct got_commit_graph *graph;
4328 regex_t regex;
4329 int have_match;
4330 struct got_object_id_queue reversed_commits;
4331 struct got_object_qid *qid;
4332 struct got_commit_object *commit;
4333 struct got_pathlist_head changed_paths;
4335 STAILQ_INIT(&reversed_commits);
4336 TAILQ_INIT(&changed_paths);
4338 if (search_pattern && regcomp(&regex, search_pattern,
4339 REG_EXTENDED | REG_NOSUB | REG_NEWLINE))
4340 return got_error_msg(GOT_ERR_REGEX, search_pattern);
4342 err = got_commit_graph_open(&graph, path, !log_branches);
4343 if (err)
4344 return err;
4345 err = got_commit_graph_iter_start(graph, root_id, repo,
4346 check_cancelled, NULL);
4347 if (err)
4348 goto done;
4349 for (;;) {
4350 struct got_object_id id;
4351 struct got_diffstat_cb_arg dsa = { 0, 0, 0, 0, 0, 0,
4352 &changed_paths, 0, 0, GOT_DIFF_ALGORITHM_PATIENCE };
4354 if (sigint_received || sigpipe_received)
4355 break;
4357 err = got_commit_graph_iter_next(&id, graph, repo,
4358 check_cancelled, NULL);
4359 if (err) {
4360 if (err->code == GOT_ERR_ITER_COMPLETED)
4361 err = NULL;
4362 break;
4365 err = got_object_open_as_commit(&commit, repo, &id);
4366 if (err)
4367 break;
4369 if ((show_changed_paths || (show_diffstat && !show_patch))
4370 && !reverse_display_order) {
4371 err = get_changed_paths(&changed_paths, commit, repo,
4372 show_diffstat ? &dsa : NULL);
4373 if (err)
4374 break;
4377 if (search_pattern) {
4378 err = match_commit(&have_match, &id, commit, &regex);
4379 if (err) {
4380 got_object_commit_close(commit);
4381 break;
4383 if (have_match == 0 && show_changed_paths)
4384 match_changed_paths(&have_match,
4385 &changed_paths, &regex);
4386 if (have_match == 0 && show_patch) {
4387 err = match_patch(&have_match, commit, &id,
4388 path, diff_context, repo, &regex, tmpfile);
4389 if (err)
4390 break;
4392 if (have_match == 0) {
4393 got_object_commit_close(commit);
4394 got_pathlist_free(&changed_paths,
4395 GOT_PATHLIST_FREE_ALL);
4396 continue;
4400 if (reverse_display_order) {
4401 err = got_object_qid_alloc(&qid, &id);
4402 if (err)
4403 break;
4404 STAILQ_INSERT_HEAD(&reversed_commits, qid, entry);
4405 got_object_commit_close(commit);
4406 } else {
4407 if (one_line)
4408 err = print_commit_oneline(commit, &id,
4409 repo, refs_idmap);
4410 else
4411 err = print_commit(commit, &id, repo, path,
4412 (show_changed_paths || show_diffstat) ?
4413 &changed_paths : NULL,
4414 show_diffstat ? &dsa : NULL, show_patch,
4415 diff_context, refs_idmap, NULL);
4416 got_object_commit_close(commit);
4417 if (err)
4418 break;
4420 if ((limit && --limit == 0) ||
4421 (end_id && got_object_id_cmp(&id, end_id) == 0))
4422 break;
4424 got_pathlist_free(&changed_paths, GOT_PATHLIST_FREE_ALL);
4426 if (reverse_display_order) {
4427 STAILQ_FOREACH(qid, &reversed_commits, entry) {
4428 struct got_diffstat_cb_arg dsa = { 0, 0, 0, 0, 0, 0,
4429 &changed_paths, 0, 0, GOT_DIFF_ALGORITHM_PATIENCE };
4431 err = got_object_open_as_commit(&commit, repo,
4432 &qid->id);
4433 if (err)
4434 break;
4435 if (show_changed_paths ||
4436 (show_diffstat && !show_patch)) {
4437 err = get_changed_paths(&changed_paths, commit,
4438 repo, show_diffstat ? &dsa : NULL);
4439 if (err)
4440 break;
4442 if (one_line)
4443 err = print_commit_oneline(commit, &qid->id,
4444 repo, refs_idmap);
4445 else
4446 err = print_commit(commit, &qid->id, repo, path,
4447 (show_changed_paths || show_diffstat) ?
4448 &changed_paths : NULL,
4449 show_diffstat ? &dsa : NULL, show_patch,
4450 diff_context, refs_idmap, NULL);
4451 got_object_commit_close(commit);
4452 if (err)
4453 break;
4454 got_pathlist_free(&changed_paths, GOT_PATHLIST_FREE_ALL);
4457 done:
4458 while (!STAILQ_EMPTY(&reversed_commits)) {
4459 qid = STAILQ_FIRST(&reversed_commits);
4460 STAILQ_REMOVE_HEAD(&reversed_commits, entry);
4461 got_object_qid_free(qid);
4463 got_pathlist_free(&changed_paths, GOT_PATHLIST_FREE_ALL);
4464 if (search_pattern)
4465 regfree(&regex);
4466 got_commit_graph_close(graph);
4467 return err;
4470 __dead static void
4471 usage_log(void)
4473 fprintf(stderr, "usage: %s log [-bdPpRs] [-C number] [-c commit] "
4474 "[-l N] [-r repository-path] [-S search-pattern] [-x commit] "
4475 "[path]\n", getprogname());
4476 exit(1);
4479 static int
4480 get_default_log_limit(void)
4482 const char *got_default_log_limit;
4483 long long n;
4484 const char *errstr;
4486 got_default_log_limit = getenv("GOT_LOG_DEFAULT_LIMIT");
4487 if (got_default_log_limit == NULL)
4488 return 0;
4489 n = strtonum(got_default_log_limit, 0, INT_MAX, &errstr);
4490 if (errstr != NULL)
4491 return 0;
4492 return n;
4495 static const struct got_error *
4496 cmd_log(int argc, char *argv[])
4498 const struct got_error *error;
4499 struct got_repository *repo = NULL;
4500 struct got_worktree *worktree = NULL;
4501 struct got_object_id *start_id = NULL, *end_id = NULL;
4502 char *repo_path = NULL, *path = NULL, *cwd = NULL, *in_repo_path = NULL;
4503 const char *start_commit = NULL, *end_commit = NULL;
4504 const char *search_pattern = NULL;
4505 int diff_context = -1, ch;
4506 int show_changed_paths = 0, show_patch = 0, limit = 0, log_branches = 0;
4507 int show_diffstat = 0, reverse_display_order = 0, one_line = 0;
4508 const char *errstr;
4509 struct got_reflist_head refs;
4510 struct got_reflist_object_id_map *refs_idmap = NULL;
4511 FILE *tmpfile = NULL;
4512 int *pack_fds = NULL;
4514 TAILQ_INIT(&refs);
4516 #ifndef PROFILE
4517 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
4518 NULL)
4519 == -1)
4520 err(1, "pledge");
4521 #endif
4523 limit = get_default_log_limit();
4525 while ((ch = getopt(argc, argv, "bC:c:dl:PpRr:S:sx:")) != -1) {
4526 switch (ch) {
4527 case 'b':
4528 log_branches = 1;
4529 break;
4530 case 'C':
4531 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
4532 &errstr);
4533 if (errstr != NULL)
4534 errx(1, "number of context lines is %s: %s",
4535 errstr, optarg);
4536 break;
4537 case 'c':
4538 start_commit = optarg;
4539 break;
4540 case 'd':
4541 show_diffstat = 1;
4542 break;
4543 case 'l':
4544 limit = strtonum(optarg, 0, INT_MAX, &errstr);
4545 if (errstr != NULL)
4546 errx(1, "number of commits is %s: %s",
4547 errstr, optarg);
4548 break;
4549 case 'P':
4550 show_changed_paths = 1;
4551 break;
4552 case 'p':
4553 show_patch = 1;
4554 break;
4555 case 'R':
4556 reverse_display_order = 1;
4557 break;
4558 case 'r':
4559 repo_path = realpath(optarg, NULL);
4560 if (repo_path == NULL)
4561 return got_error_from_errno2("realpath",
4562 optarg);
4563 got_path_strip_trailing_slashes(repo_path);
4564 break;
4565 case 'S':
4566 search_pattern = optarg;
4567 break;
4568 case 's':
4569 one_line = 1;
4570 break;
4571 case 'x':
4572 end_commit = optarg;
4573 break;
4574 default:
4575 usage_log();
4576 /* NOTREACHED */
4580 argc -= optind;
4581 argv += optind;
4583 if (diff_context == -1)
4584 diff_context = 3;
4585 else if (!show_patch)
4586 errx(1, "-C requires -p");
4588 if (one_line && (show_patch || show_changed_paths || show_diffstat))
4589 errx(1, "cannot use -s with -d, -p or -P");
4591 cwd = getcwd(NULL, 0);
4592 if (cwd == NULL) {
4593 error = got_error_from_errno("getcwd");
4594 goto done;
4597 error = got_repo_pack_fds_open(&pack_fds);
4598 if (error != NULL)
4599 goto done;
4601 if (repo_path == NULL) {
4602 error = got_worktree_open(&worktree, cwd);
4603 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4604 goto done;
4605 error = NULL;
4608 if (argc == 1) {
4609 if (worktree) {
4610 error = got_worktree_resolve_path(&path, worktree,
4611 argv[0]);
4612 if (error)
4613 goto done;
4614 } else {
4615 path = strdup(argv[0]);
4616 if (path == NULL) {
4617 error = got_error_from_errno("strdup");
4618 goto done;
4621 } else if (argc != 0)
4622 usage_log();
4624 if (repo_path == NULL) {
4625 repo_path = worktree ?
4626 strdup(got_worktree_get_repo_path(worktree)) : strdup(cwd);
4628 if (repo_path == NULL) {
4629 error = got_error_from_errno("strdup");
4630 goto done;
4633 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
4634 if (error != NULL)
4635 goto done;
4637 error = apply_unveil(got_repo_get_path(repo), 1,
4638 worktree ? got_worktree_get_root_path(worktree) : NULL);
4639 if (error)
4640 goto done;
4642 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
4643 if (error)
4644 goto done;
4646 error = got_reflist_object_id_map_create(&refs_idmap, &refs, repo);
4647 if (error)
4648 goto done;
4650 if (start_commit == NULL) {
4651 struct got_reference *head_ref;
4652 struct got_commit_object *commit = NULL;
4653 error = got_ref_open(&head_ref, repo,
4654 worktree ? got_worktree_get_head_ref_name(worktree)
4655 : GOT_REF_HEAD, 0);
4656 if (error != NULL)
4657 goto done;
4658 error = got_ref_resolve(&start_id, repo, head_ref);
4659 got_ref_close(head_ref);
4660 if (error != NULL)
4661 goto done;
4662 error = got_object_open_as_commit(&commit, repo,
4663 start_id);
4664 if (error != NULL)
4665 goto done;
4666 got_object_commit_close(commit);
4667 } else {
4668 error = got_repo_match_object_id(&start_id, NULL,
4669 start_commit, GOT_OBJ_TYPE_COMMIT, &refs, repo);
4670 if (error != NULL)
4671 goto done;
4673 if (end_commit != NULL) {
4674 error = got_repo_match_object_id(&end_id, NULL,
4675 end_commit, GOT_OBJ_TYPE_COMMIT, &refs, repo);
4676 if (error != NULL)
4677 goto done;
4680 if (worktree) {
4682 * If a path was specified on the command line it was resolved
4683 * to a path in the work tree above. Prepend the work tree's
4684 * path prefix to obtain the corresponding in-repository path.
4686 if (path) {
4687 const char *prefix;
4688 prefix = got_worktree_get_path_prefix(worktree);
4689 if (asprintf(&in_repo_path, "%s%s%s", prefix,
4690 (path[0] != '\0') ? "/" : "", path) == -1) {
4691 error = got_error_from_errno("asprintf");
4692 goto done;
4695 } else
4696 error = got_repo_map_path(&in_repo_path, repo,
4697 path ? path : "");
4698 if (error != NULL)
4699 goto done;
4700 if (in_repo_path) {
4701 free(path);
4702 path = in_repo_path;
4705 if (worktree) {
4706 /* Release work tree lock. */
4707 got_worktree_close(worktree);
4708 worktree = NULL;
4711 if (search_pattern && show_patch) {
4712 tmpfile = got_opentemp();
4713 if (tmpfile == NULL) {
4714 error = got_error_from_errno("got_opentemp");
4715 goto done;
4719 error = print_commits(start_id, end_id, repo, path ? path : "",
4720 show_changed_paths, show_diffstat, show_patch, search_pattern,
4721 diff_context, limit, log_branches, reverse_display_order,
4722 refs_idmap, one_line, tmpfile);
4723 done:
4724 free(path);
4725 free(repo_path);
4726 free(cwd);
4727 if (worktree)
4728 got_worktree_close(worktree);
4729 if (repo) {
4730 const struct got_error *close_err = got_repo_close(repo);
4731 if (error == NULL)
4732 error = close_err;
4734 if (pack_fds) {
4735 const struct got_error *pack_err =
4736 got_repo_pack_fds_close(pack_fds);
4737 if (error == NULL)
4738 error = pack_err;
4740 if (refs_idmap)
4741 got_reflist_object_id_map_free(refs_idmap);
4742 if (tmpfile && fclose(tmpfile) == EOF && error == NULL)
4743 error = got_error_from_errno("fclose");
4744 got_ref_list_free(&refs);
4745 return error;
4748 __dead static void
4749 usage_diff(void)
4751 fprintf(stderr, "usage: %s diff [-adPsw] [-C number] [-c commit] "
4752 "[-r repository-path] [object1 object2 | path ...]\n",
4753 getprogname());
4754 exit(1);
4757 struct print_diff_arg {
4758 struct got_repository *repo;
4759 struct got_worktree *worktree;
4760 struct got_diffstat_cb_arg *diffstat;
4761 int diff_context;
4762 const char *id_str;
4763 int header_shown;
4764 int diff_staged;
4765 enum got_diff_algorithm diff_algo;
4766 int ignore_whitespace;
4767 int force_text_diff;
4768 FILE *f1;
4769 FILE *f2;
4770 FILE *outfile;
4774 * Create a file which contains the target path of a symlink so we can feed
4775 * it as content to the diff engine.
4777 static const struct got_error *
4778 get_symlink_target_file(int *fd, int dirfd, const char *de_name,
4779 const char *abspath)
4781 const struct got_error *err = NULL;
4782 char target_path[PATH_MAX];
4783 ssize_t target_len, outlen;
4785 *fd = -1;
4787 if (dirfd != -1) {
4788 target_len = readlinkat(dirfd, de_name, target_path, PATH_MAX);
4789 if (target_len == -1)
4790 return got_error_from_errno2("readlinkat", abspath);
4791 } else {
4792 target_len = readlink(abspath, target_path, PATH_MAX);
4793 if (target_len == -1)
4794 return got_error_from_errno2("readlink", abspath);
4797 *fd = got_opentempfd();
4798 if (*fd == -1)
4799 return got_error_from_errno("got_opentempfd");
4801 outlen = write(*fd, target_path, target_len);
4802 if (outlen == -1) {
4803 err = got_error_from_errno("got_opentempfd");
4804 goto done;
4807 if (lseek(*fd, 0, SEEK_SET) == -1) {
4808 err = got_error_from_errno2("lseek", abspath);
4809 goto done;
4811 done:
4812 if (err) {
4813 close(*fd);
4814 *fd = -1;
4816 return err;
4819 static const struct got_error *
4820 print_diff(void *arg, unsigned char status, unsigned char staged_status,
4821 const char *path, struct got_object_id *blob_id,
4822 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
4823 int dirfd, const char *de_name)
4825 struct print_diff_arg *a = arg;
4826 const struct got_error *err = NULL;
4827 struct got_blob_object *blob1 = NULL;
4828 int fd = -1, fd1 = -1, fd2 = -1;
4829 FILE *f2 = NULL;
4830 char *abspath = NULL, *label1 = NULL;
4831 struct stat sb;
4832 off_t size1 = 0;
4833 int f2_exists = 0;
4835 memset(&sb, 0, sizeof(sb));
4837 if (a->diff_staged) {
4838 if (staged_status != GOT_STATUS_MODIFY &&
4839 staged_status != GOT_STATUS_ADD &&
4840 staged_status != GOT_STATUS_DELETE)
4841 return NULL;
4842 } else {
4843 if (staged_status == GOT_STATUS_DELETE)
4844 return NULL;
4845 if (status == GOT_STATUS_NONEXISTENT)
4846 return got_error_set_errno(ENOENT, path);
4847 if (status != GOT_STATUS_MODIFY &&
4848 status != GOT_STATUS_ADD &&
4849 status != GOT_STATUS_DELETE &&
4850 status != GOT_STATUS_CONFLICT)
4851 return NULL;
4854 err = got_opentemp_truncate(a->f1);
4855 if (err)
4856 return got_error_from_errno("got_opentemp_truncate");
4857 err = got_opentemp_truncate(a->f2);
4858 if (err)
4859 return got_error_from_errno("got_opentemp_truncate");
4861 if (!a->header_shown) {
4862 if (fprintf(a->outfile, "diff %s%s\n",
4863 a->diff_staged ? "-s " : "",
4864 got_worktree_get_root_path(a->worktree)) < 0) {
4865 err = got_error_from_errno("fprintf");
4866 goto done;
4868 if (fprintf(a->outfile, "commit - %s\n", a->id_str) < 0) {
4869 err = got_error_from_errno("fprintf");
4870 goto done;
4872 if (fprintf(a->outfile, "path + %s%s\n",
4873 got_worktree_get_root_path(a->worktree),
4874 a->diff_staged ? " (staged changes)" : "") < 0) {
4875 err = got_error_from_errno("fprintf");
4876 goto done;
4878 a->header_shown = 1;
4881 if (a->diff_staged) {
4882 const char *label1 = NULL, *label2 = NULL;
4883 switch (staged_status) {
4884 case GOT_STATUS_MODIFY:
4885 label1 = path;
4886 label2 = path;
4887 break;
4888 case GOT_STATUS_ADD:
4889 label2 = path;
4890 break;
4891 case GOT_STATUS_DELETE:
4892 label1 = path;
4893 break;
4894 default:
4895 return got_error(GOT_ERR_FILE_STATUS);
4897 fd1 = got_opentempfd();
4898 if (fd1 == -1) {
4899 err = got_error_from_errno("got_opentempfd");
4900 goto done;
4902 fd2 = got_opentempfd();
4903 if (fd2 == -1) {
4904 err = got_error_from_errno("got_opentempfd");
4905 goto done;
4907 err = got_diff_objects_as_blobs(NULL, NULL, a->f1, a->f2,
4908 fd1, fd2, blob_id, staged_blob_id, label1, label2,
4909 a->diff_algo, a->diff_context, a->ignore_whitespace,
4910 a->force_text_diff, a->diffstat, a->repo, a->outfile);
4911 goto done;
4914 fd1 = got_opentempfd();
4915 if (fd1 == -1) {
4916 err = got_error_from_errno("got_opentempfd");
4917 goto done;
4920 if (staged_status == GOT_STATUS_ADD ||
4921 staged_status == GOT_STATUS_MODIFY) {
4922 char *id_str;
4923 err = got_object_open_as_blob(&blob1, a->repo, staged_blob_id,
4924 8192, fd1);
4925 if (err)
4926 goto done;
4927 err = got_object_id_str(&id_str, staged_blob_id);
4928 if (err)
4929 goto done;
4930 if (asprintf(&label1, "%s (staged)", id_str) == -1) {
4931 err = got_error_from_errno("asprintf");
4932 free(id_str);
4933 goto done;
4935 free(id_str);
4936 } else if (status != GOT_STATUS_ADD) {
4937 err = got_object_open_as_blob(&blob1, a->repo, blob_id, 8192,
4938 fd1);
4939 if (err)
4940 goto done;
4943 if (status != GOT_STATUS_DELETE) {
4944 if (asprintf(&abspath, "%s/%s",
4945 got_worktree_get_root_path(a->worktree), path) == -1) {
4946 err = got_error_from_errno("asprintf");
4947 goto done;
4950 if (dirfd != -1) {
4951 fd = openat(dirfd, de_name,
4952 O_RDONLY | O_NOFOLLOW | O_CLOEXEC);
4953 if (fd == -1) {
4954 if (!got_err_open_nofollow_on_symlink()) {
4955 err = got_error_from_errno2("openat",
4956 abspath);
4957 goto done;
4959 err = get_symlink_target_file(&fd, dirfd,
4960 de_name, abspath);
4961 if (err)
4962 goto done;
4964 } else {
4965 fd = open(abspath, O_RDONLY | O_NOFOLLOW | O_CLOEXEC);
4966 if (fd == -1) {
4967 if (!got_err_open_nofollow_on_symlink()) {
4968 err = got_error_from_errno2("open",
4969 abspath);
4970 goto done;
4972 err = get_symlink_target_file(&fd, dirfd,
4973 de_name, abspath);
4974 if (err)
4975 goto done;
4978 if (fstatat(fd, abspath, &sb, AT_SYMLINK_NOFOLLOW) == -1) {
4979 err = got_error_from_errno2("fstatat", abspath);
4980 goto done;
4982 f2 = fdopen(fd, "r");
4983 if (f2 == NULL) {
4984 err = got_error_from_errno2("fdopen", abspath);
4985 goto done;
4987 fd = -1;
4988 f2_exists = 1;
4991 if (blob1) {
4992 err = got_object_blob_dump_to_file(&size1, NULL, NULL,
4993 a->f1, blob1);
4994 if (err)
4995 goto done;
4998 err = got_diff_blob_file(blob1, a->f1, size1, label1, f2 ? f2 : a->f2,
4999 f2_exists, &sb, path, GOT_DIFF_ALGORITHM_PATIENCE, a->diff_context,
5000 a->ignore_whitespace, a->force_text_diff, a->diffstat, a->outfile);
5001 done:
5002 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
5003 err = got_error_from_errno("close");
5004 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
5005 err = got_error_from_errno("close");
5006 if (blob1)
5007 got_object_blob_close(blob1);
5008 if (fd != -1 && close(fd) == -1 && err == NULL)
5009 err = got_error_from_errno("close");
5010 if (f2 && fclose(f2) == EOF && err == NULL)
5011 err = got_error_from_errno("fclose");
5012 free(abspath);
5013 return err;
5016 static const struct got_error *
5017 cmd_diff(int argc, char *argv[])
5019 const struct got_error *error;
5020 struct got_repository *repo = NULL;
5021 struct got_worktree *worktree = NULL;
5022 char *cwd = NULL, *repo_path = NULL;
5023 const char *commit_args[2] = { NULL, NULL };
5024 int ncommit_args = 0;
5025 struct got_object_id *ids[2] = { NULL, NULL };
5026 char *labels[2] = { NULL, NULL };
5027 int type1 = GOT_OBJ_TYPE_ANY, type2 = GOT_OBJ_TYPE_ANY;
5028 int diff_context = 3, diff_staged = 0, ignore_whitespace = 0, ch, i;
5029 int force_text_diff = 0, force_path = 0, rflag = 0, show_diffstat = 0;
5030 const char *errstr;
5031 struct got_reflist_head refs;
5032 struct got_pathlist_head diffstat_paths, paths;
5033 FILE *f1 = NULL, *f2 = NULL, *outfile = NULL;
5034 int fd1 = -1, fd2 = -1;
5035 int *pack_fds = NULL;
5036 struct got_diffstat_cb_arg dsa;
5038 memset(&dsa, 0, sizeof(dsa));
5040 TAILQ_INIT(&refs);
5041 TAILQ_INIT(&paths);
5042 TAILQ_INIT(&diffstat_paths);
5044 #ifndef PROFILE
5045 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
5046 NULL) == -1)
5047 err(1, "pledge");
5048 #endif
5050 while ((ch = getopt(argc, argv, "aC:c:dPr:sw")) != -1) {
5051 switch (ch) {
5052 case 'a':
5053 force_text_diff = 1;
5054 break;
5055 case 'C':
5056 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
5057 &errstr);
5058 if (errstr != NULL)
5059 errx(1, "number of context lines is %s: %s",
5060 errstr, optarg);
5061 break;
5062 case 'c':
5063 if (ncommit_args >= 2)
5064 errx(1, "too many -c options used");
5065 commit_args[ncommit_args++] = optarg;
5066 break;
5067 case 'd':
5068 show_diffstat = 1;
5069 break;
5070 case 'P':
5071 force_path = 1;
5072 break;
5073 case 'r':
5074 repo_path = realpath(optarg, NULL);
5075 if (repo_path == NULL)
5076 return got_error_from_errno2("realpath",
5077 optarg);
5078 got_path_strip_trailing_slashes(repo_path);
5079 rflag = 1;
5080 break;
5081 case 's':
5082 diff_staged = 1;
5083 break;
5084 case 'w':
5085 ignore_whitespace = 1;
5086 break;
5087 default:
5088 usage_diff();
5089 /* NOTREACHED */
5093 argc -= optind;
5094 argv += optind;
5096 cwd = getcwd(NULL, 0);
5097 if (cwd == NULL) {
5098 error = got_error_from_errno("getcwd");
5099 goto done;
5102 error = got_repo_pack_fds_open(&pack_fds);
5103 if (error != NULL)
5104 goto done;
5106 if (repo_path == NULL) {
5107 error = got_worktree_open(&worktree, cwd);
5108 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5109 goto done;
5110 else
5111 error = NULL;
5112 if (worktree) {
5113 repo_path =
5114 strdup(got_worktree_get_repo_path(worktree));
5115 if (repo_path == NULL) {
5116 error = got_error_from_errno("strdup");
5117 goto done;
5119 } else {
5120 repo_path = strdup(cwd);
5121 if (repo_path == NULL) {
5122 error = got_error_from_errno("strdup");
5123 goto done;
5128 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
5129 free(repo_path);
5130 if (error != NULL)
5131 goto done;
5133 if (show_diffstat) {
5134 dsa.paths = &diffstat_paths;
5135 dsa.force_text = force_text_diff;
5136 dsa.ignore_ws = ignore_whitespace;
5137 dsa.diff_algo = GOT_DIFF_ALGORITHM_PATIENCE;
5140 if (rflag || worktree == NULL || ncommit_args > 0) {
5141 if (force_path) {
5142 error = got_error_msg(GOT_ERR_NOT_IMPL,
5143 "-P option can only be used when diffing "
5144 "a work tree");
5145 goto done;
5147 if (diff_staged) {
5148 error = got_error_msg(GOT_ERR_NOT_IMPL,
5149 "-s option can only be used when diffing "
5150 "a work tree");
5151 goto done;
5155 error = apply_unveil(got_repo_get_path(repo), 1,
5156 worktree ? got_worktree_get_root_path(worktree) : NULL);
5157 if (error)
5158 goto done;
5160 if ((!force_path && argc == 2) || ncommit_args > 0) {
5161 int obj_type = (ncommit_args > 0 ?
5162 GOT_OBJ_TYPE_COMMIT : GOT_OBJ_TYPE_ANY);
5163 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
5164 NULL);
5165 if (error)
5166 goto done;
5167 for (i = 0; i < (ncommit_args > 0 ? ncommit_args : argc); i++) {
5168 const char *arg;
5169 if (ncommit_args > 0)
5170 arg = commit_args[i];
5171 else
5172 arg = argv[i];
5173 error = got_repo_match_object_id(&ids[i], &labels[i],
5174 arg, obj_type, &refs, repo);
5175 if (error) {
5176 if (error->code != GOT_ERR_NOT_REF &&
5177 error->code != GOT_ERR_NO_OBJ)
5178 goto done;
5179 if (ncommit_args > 0)
5180 goto done;
5181 error = NULL;
5182 break;
5187 f1 = got_opentemp();
5188 if (f1 == NULL) {
5189 error = got_error_from_errno("got_opentemp");
5190 goto done;
5193 f2 = got_opentemp();
5194 if (f2 == NULL) {
5195 error = got_error_from_errno("got_opentemp");
5196 goto done;
5199 outfile = got_opentemp();
5200 if (outfile == NULL) {
5201 error = got_error_from_errno("got_opentemp");
5202 goto done;
5205 if (ncommit_args == 0 && (ids[0] == NULL || ids[1] == NULL)) {
5206 struct print_diff_arg arg;
5207 char *id_str;
5209 if (worktree == NULL) {
5210 if (argc == 2 && ids[0] == NULL) {
5211 error = got_error_path(argv[0], GOT_ERR_NO_OBJ);
5212 goto done;
5213 } else if (argc == 2 && ids[1] == NULL) {
5214 error = got_error_path(argv[1], GOT_ERR_NO_OBJ);
5215 goto done;
5216 } else if (argc > 0) {
5217 error = got_error_fmt(GOT_ERR_NOT_WORKTREE,
5218 "%s", "specified paths cannot be resolved");
5219 goto done;
5220 } else {
5221 error = got_error(GOT_ERR_NOT_WORKTREE);
5222 goto done;
5226 error = get_worktree_paths_from_argv(&paths, argc, argv,
5227 worktree);
5228 if (error)
5229 goto done;
5231 error = got_object_id_str(&id_str,
5232 got_worktree_get_base_commit_id(worktree));
5233 if (error)
5234 goto done;
5235 arg.repo = repo;
5236 arg.worktree = worktree;
5237 arg.diff_algo = GOT_DIFF_ALGORITHM_PATIENCE;
5238 arg.diff_context = diff_context;
5239 arg.id_str = id_str;
5240 arg.header_shown = 0;
5241 arg.diff_staged = diff_staged;
5242 arg.ignore_whitespace = ignore_whitespace;
5243 arg.force_text_diff = force_text_diff;
5244 arg.diffstat = show_diffstat ? &dsa : NULL;
5245 arg.f1 = f1;
5246 arg.f2 = f2;
5247 arg.outfile = outfile;
5249 error = got_worktree_status(worktree, &paths, repo, 0,
5250 print_diff, &arg, check_cancelled, NULL);
5251 free(id_str);
5252 if (error)
5253 goto done;
5255 if (show_diffstat && dsa.nfiles > 0) {
5256 char *header;
5258 if (asprintf(&header, "diffstat %s%s",
5259 diff_staged ? "-s " : "",
5260 got_worktree_get_root_path(worktree)) == -1) {
5261 error = got_error_from_errno("asprintf");
5262 goto done;
5265 error = print_diffstat(&dsa, header);
5266 free(header);
5267 if (error)
5268 goto done;
5271 error = printfile(outfile);
5272 goto done;
5275 if (ncommit_args == 1) {
5276 struct got_commit_object *commit;
5277 error = got_object_open_as_commit(&commit, repo, ids[0]);
5278 if (error)
5279 goto done;
5281 labels[1] = labels[0];
5282 ids[1] = ids[0];
5283 if (got_object_commit_get_nparents(commit) > 0) {
5284 const struct got_object_id_queue *pids;
5285 struct got_object_qid *pid;
5286 pids = got_object_commit_get_parent_ids(commit);
5287 pid = STAILQ_FIRST(pids);
5288 ids[0] = got_object_id_dup(&pid->id);
5289 if (ids[0] == NULL) {
5290 error = got_error_from_errno(
5291 "got_object_id_dup");
5292 got_object_commit_close(commit);
5293 goto done;
5295 error = got_object_id_str(&labels[0], ids[0]);
5296 if (error) {
5297 got_object_commit_close(commit);
5298 goto done;
5300 } else {
5301 ids[0] = NULL;
5302 labels[0] = strdup("/dev/null");
5303 if (labels[0] == NULL) {
5304 error = got_error_from_errno("strdup");
5305 got_object_commit_close(commit);
5306 goto done;
5310 got_object_commit_close(commit);
5313 if (ncommit_args == 0 && argc > 2) {
5314 error = got_error_msg(GOT_ERR_BAD_PATH,
5315 "path arguments cannot be used when diffing two objects");
5316 goto done;
5319 if (ids[0]) {
5320 error = got_object_get_type(&type1, repo, ids[0]);
5321 if (error)
5322 goto done;
5325 error = got_object_get_type(&type2, repo, ids[1]);
5326 if (error)
5327 goto done;
5328 if (type1 != GOT_OBJ_TYPE_ANY && type1 != type2) {
5329 error = got_error(GOT_ERR_OBJ_TYPE);
5330 goto done;
5332 if (type1 == GOT_OBJ_TYPE_BLOB && argc > 2) {
5333 error = got_error_msg(GOT_ERR_OBJ_TYPE,
5334 "path arguments cannot be used when diffing blobs");
5335 goto done;
5338 for (i = 0; ncommit_args > 0 && i < argc; i++) {
5339 char *in_repo_path;
5340 struct got_pathlist_entry *new;
5341 if (worktree) {
5342 const char *prefix;
5343 char *p;
5344 error = got_worktree_resolve_path(&p, worktree,
5345 argv[i]);
5346 if (error)
5347 goto done;
5348 prefix = got_worktree_get_path_prefix(worktree);
5349 while (prefix[0] == '/')
5350 prefix++;
5351 if (asprintf(&in_repo_path, "%s%s%s", prefix,
5352 (p[0] != '\0' && prefix[0] != '\0') ? "/" : "",
5353 p) == -1) {
5354 error = got_error_from_errno("asprintf");
5355 free(p);
5356 goto done;
5358 free(p);
5359 } else {
5360 char *mapped_path, *s;
5361 error = got_repo_map_path(&mapped_path, repo, argv[i]);
5362 if (error)
5363 goto done;
5364 s = mapped_path;
5365 while (s[0] == '/')
5366 s++;
5367 in_repo_path = strdup(s);
5368 if (in_repo_path == NULL) {
5369 error = got_error_from_errno("asprintf");
5370 free(mapped_path);
5371 goto done;
5373 free(mapped_path);
5376 error = got_pathlist_insert(&new, &paths, in_repo_path, NULL);
5377 if (error || new == NULL /* duplicate */)
5378 free(in_repo_path);
5379 if (error)
5380 goto done;
5383 if (worktree) {
5384 /* Release work tree lock. */
5385 got_worktree_close(worktree);
5386 worktree = NULL;
5389 fd1 = got_opentempfd();
5390 if (fd1 == -1) {
5391 error = got_error_from_errno("got_opentempfd");
5392 goto done;
5395 fd2 = got_opentempfd();
5396 if (fd2 == -1) {
5397 error = got_error_from_errno("got_opentempfd");
5398 goto done;
5401 switch (type1 == GOT_OBJ_TYPE_ANY ? type2 : type1) {
5402 case GOT_OBJ_TYPE_BLOB:
5403 error = got_diff_objects_as_blobs(NULL, NULL, f1, f2,
5404 fd1, fd2, ids[0], ids[1], NULL, NULL,
5405 GOT_DIFF_ALGORITHM_PATIENCE, diff_context,
5406 ignore_whitespace, force_text_diff,
5407 show_diffstat ? &dsa : NULL, repo, outfile);
5408 break;
5409 case GOT_OBJ_TYPE_TREE:
5410 error = got_diff_objects_as_trees(NULL, NULL, f1, f2, fd1, fd2,
5411 ids[0], ids[1], &paths, "", "",
5412 GOT_DIFF_ALGORITHM_PATIENCE, diff_context,
5413 ignore_whitespace, force_text_diff,
5414 show_diffstat ? &dsa : NULL, repo, outfile);
5415 break;
5416 case GOT_OBJ_TYPE_COMMIT:
5417 fprintf(outfile, "diff %s %s\n", labels[0], labels[1]);
5418 error = got_diff_objects_as_commits(NULL, NULL, f1, f2,
5419 fd1, fd2, ids[0], ids[1], &paths,
5420 GOT_DIFF_ALGORITHM_PATIENCE, diff_context,
5421 ignore_whitespace, force_text_diff,
5422 show_diffstat ? &dsa : NULL, repo, outfile);
5423 break;
5424 default:
5425 error = got_error(GOT_ERR_OBJ_TYPE);
5427 if (error)
5428 goto done;
5430 if (show_diffstat && dsa.nfiles > 0) {
5431 char *header = NULL;
5433 if (asprintf(&header, "diffstat %s %s",
5434 labels[0], labels[1]) == -1) {
5435 error = got_error_from_errno("asprintf");
5436 goto done;
5439 error = print_diffstat(&dsa, header);
5440 free(header);
5441 if (error)
5442 goto done;
5445 error = printfile(outfile);
5447 done:
5448 free(labels[0]);
5449 free(labels[1]);
5450 free(ids[0]);
5451 free(ids[1]);
5452 if (worktree)
5453 got_worktree_close(worktree);
5454 if (repo) {
5455 const struct got_error *close_err = got_repo_close(repo);
5456 if (error == NULL)
5457 error = close_err;
5459 if (pack_fds) {
5460 const struct got_error *pack_err =
5461 got_repo_pack_fds_close(pack_fds);
5462 if (error == NULL)
5463 error = pack_err;
5465 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
5466 got_pathlist_free(&diffstat_paths, GOT_PATHLIST_FREE_ALL);
5467 got_ref_list_free(&refs);
5468 if (outfile && fclose(outfile) == EOF && error == NULL)
5469 error = got_error_from_errno("fclose");
5470 if (f1 && fclose(f1) == EOF && error == NULL)
5471 error = got_error_from_errno("fclose");
5472 if (f2 && fclose(f2) == EOF && error == NULL)
5473 error = got_error_from_errno("fclose");
5474 if (fd1 != -1 && close(fd1) == -1 && error == NULL)
5475 error = got_error_from_errno("close");
5476 if (fd2 != -1 && close(fd2) == -1 && error == NULL)
5477 error = got_error_from_errno("close");
5478 return error;
5481 __dead static void
5482 usage_blame(void)
5484 fprintf(stderr,
5485 "usage: %s blame [-c commit] [-r repository-path] path\n",
5486 getprogname());
5487 exit(1);
5490 struct blame_line {
5491 int annotated;
5492 char *id_str;
5493 char *committer;
5494 char datebuf[11]; /* YYYY-MM-DD + NUL */
5497 struct blame_cb_args {
5498 struct blame_line *lines;
5499 int nlines;
5500 int nlines_prec;
5501 int lineno_cur;
5502 off_t *line_offsets;
5503 FILE *f;
5504 struct got_repository *repo;
5507 static const struct got_error *
5508 blame_cb(void *arg, int nlines, int lineno,
5509 struct got_commit_object *commit, struct got_object_id *id)
5511 const struct got_error *err = NULL;
5512 struct blame_cb_args *a = arg;
5513 struct blame_line *bline;
5514 char *line = NULL;
5515 size_t linesize = 0;
5516 off_t offset;
5517 struct tm tm;
5518 time_t committer_time;
5520 if (nlines != a->nlines ||
5521 (lineno != -1 && lineno < 1) || lineno > a->nlines)
5522 return got_error(GOT_ERR_RANGE);
5524 if (sigint_received)
5525 return got_error(GOT_ERR_ITER_COMPLETED);
5527 if (lineno == -1)
5528 return NULL; /* no change in this commit */
5530 /* Annotate this line. */
5531 bline = &a->lines[lineno - 1];
5532 if (bline->annotated)
5533 return NULL;
5534 err = got_object_id_str(&bline->id_str, id);
5535 if (err)
5536 return err;
5538 bline->committer = strdup(got_object_commit_get_committer(commit));
5539 if (bline->committer == NULL) {
5540 err = got_error_from_errno("strdup");
5541 goto done;
5544 committer_time = got_object_commit_get_committer_time(commit);
5545 if (gmtime_r(&committer_time, &tm) == NULL)
5546 return got_error_from_errno("gmtime_r");
5547 if (strftime(bline->datebuf, sizeof(bline->datebuf), "%G-%m-%d",
5548 &tm) == 0) {
5549 err = got_error(GOT_ERR_NO_SPACE);
5550 goto done;
5552 bline->annotated = 1;
5554 /* Print lines annotated so far. */
5555 bline = &a->lines[a->lineno_cur - 1];
5556 if (!bline->annotated)
5557 goto done;
5559 offset = a->line_offsets[a->lineno_cur - 1];
5560 if (fseeko(a->f, offset, SEEK_SET) == -1) {
5561 err = got_error_from_errno("fseeko");
5562 goto done;
5565 while (a->lineno_cur <= a->nlines && bline->annotated) {
5566 char *smallerthan, *at, *nl, *committer;
5567 size_t len;
5569 if (getline(&line, &linesize, a->f) == -1) {
5570 if (ferror(a->f))
5571 err = got_error_from_errno("getline");
5572 break;
5575 committer = bline->committer;
5576 smallerthan = strchr(committer, '<');
5577 if (smallerthan && smallerthan[1] != '\0')
5578 committer = smallerthan + 1;
5579 at = strchr(committer, '@');
5580 if (at)
5581 *at = '\0';
5582 len = strlen(committer);
5583 if (len >= 9)
5584 committer[8] = '\0';
5586 nl = strchr(line, '\n');
5587 if (nl)
5588 *nl = '\0';
5589 printf("%.*d) %.8s %s %-8s %s\n", a->nlines_prec, a->lineno_cur,
5590 bline->id_str, bline->datebuf, committer, line);
5592 a->lineno_cur++;
5593 bline = &a->lines[a->lineno_cur - 1];
5595 done:
5596 free(line);
5597 return err;
5600 static const struct got_error *
5601 cmd_blame(int argc, char *argv[])
5603 const struct got_error *error;
5604 struct got_repository *repo = NULL;
5605 struct got_worktree *worktree = NULL;
5606 char *path, *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
5607 char *link_target = NULL;
5608 struct got_object_id *obj_id = NULL;
5609 struct got_object_id *commit_id = NULL;
5610 struct got_commit_object *commit = NULL;
5611 struct got_blob_object *blob = NULL;
5612 char *commit_id_str = NULL;
5613 struct blame_cb_args bca;
5614 int ch, obj_type, i, fd1 = -1, fd2 = -1, fd3 = -1;
5615 off_t filesize;
5616 int *pack_fds = NULL;
5617 FILE *f1 = NULL, *f2 = NULL;
5619 fd1 = got_opentempfd();
5620 if (fd1 == -1)
5621 return got_error_from_errno("got_opentempfd");
5623 memset(&bca, 0, sizeof(bca));
5625 #ifndef PROFILE
5626 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
5627 NULL) == -1)
5628 err(1, "pledge");
5629 #endif
5631 while ((ch = getopt(argc, argv, "c:r:")) != -1) {
5632 switch (ch) {
5633 case 'c':
5634 commit_id_str = optarg;
5635 break;
5636 case 'r':
5637 repo_path = realpath(optarg, NULL);
5638 if (repo_path == NULL)
5639 return got_error_from_errno2("realpath",
5640 optarg);
5641 got_path_strip_trailing_slashes(repo_path);
5642 break;
5643 default:
5644 usage_blame();
5645 /* NOTREACHED */
5649 argc -= optind;
5650 argv += optind;
5652 if (argc == 1)
5653 path = argv[0];
5654 else
5655 usage_blame();
5657 cwd = getcwd(NULL, 0);
5658 if (cwd == NULL) {
5659 error = got_error_from_errno("getcwd");
5660 goto done;
5663 error = got_repo_pack_fds_open(&pack_fds);
5664 if (error != NULL)
5665 goto done;
5667 if (repo_path == NULL) {
5668 error = got_worktree_open(&worktree, cwd);
5669 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5670 goto done;
5671 else
5672 error = NULL;
5673 if (worktree) {
5674 repo_path =
5675 strdup(got_worktree_get_repo_path(worktree));
5676 if (repo_path == NULL) {
5677 error = got_error_from_errno("strdup");
5678 if (error)
5679 goto done;
5681 } else {
5682 repo_path = strdup(cwd);
5683 if (repo_path == NULL) {
5684 error = got_error_from_errno("strdup");
5685 goto done;
5690 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
5691 if (error != NULL)
5692 goto done;
5694 if (worktree) {
5695 const char *prefix = got_worktree_get_path_prefix(worktree);
5696 char *p;
5698 error = got_worktree_resolve_path(&p, worktree, path);
5699 if (error)
5700 goto done;
5701 if (asprintf(&in_repo_path, "%s%s%s", prefix,
5702 (p[0] != '\0' && !got_path_is_root_dir(prefix)) ? "/" : "",
5703 p) == -1) {
5704 error = got_error_from_errno("asprintf");
5705 free(p);
5706 goto done;
5708 free(p);
5709 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5710 } else {
5711 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5712 if (error)
5713 goto done;
5714 error = got_repo_map_path(&in_repo_path, repo, path);
5716 if (error)
5717 goto done;
5719 if (commit_id_str == NULL) {
5720 struct got_reference *head_ref;
5721 error = got_ref_open(&head_ref, repo, worktree ?
5722 got_worktree_get_head_ref_name(worktree) : GOT_REF_HEAD, 0);
5723 if (error != NULL)
5724 goto done;
5725 error = got_ref_resolve(&commit_id, repo, head_ref);
5726 got_ref_close(head_ref);
5727 if (error != NULL)
5728 goto done;
5729 } else {
5730 struct got_reflist_head refs;
5731 TAILQ_INIT(&refs);
5732 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
5733 NULL);
5734 if (error)
5735 goto done;
5736 error = got_repo_match_object_id(&commit_id, NULL,
5737 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
5738 got_ref_list_free(&refs);
5739 if (error)
5740 goto done;
5743 if (worktree) {
5744 /* Release work tree lock. */
5745 got_worktree_close(worktree);
5746 worktree = NULL;
5749 error = got_object_open_as_commit(&commit, repo, commit_id);
5750 if (error)
5751 goto done;
5753 error = got_object_resolve_symlinks(&link_target, in_repo_path,
5754 commit, repo);
5755 if (error)
5756 goto done;
5758 error = got_object_id_by_path(&obj_id, repo, commit,
5759 link_target ? link_target : in_repo_path);
5760 if (error)
5761 goto done;
5763 error = got_object_get_type(&obj_type, repo, obj_id);
5764 if (error)
5765 goto done;
5767 if (obj_type != GOT_OBJ_TYPE_BLOB) {
5768 error = got_error_path(link_target ? link_target : in_repo_path,
5769 GOT_ERR_OBJ_TYPE);
5770 goto done;
5773 error = got_object_open_as_blob(&blob, repo, obj_id, 8192, fd1);
5774 if (error)
5775 goto done;
5776 bca.f = got_opentemp();
5777 if (bca.f == NULL) {
5778 error = got_error_from_errno("got_opentemp");
5779 goto done;
5781 error = got_object_blob_dump_to_file(&filesize, &bca.nlines,
5782 &bca.line_offsets, bca.f, blob);
5783 if (error || bca.nlines == 0)
5784 goto done;
5786 /* Don't include \n at EOF in the blame line count. */
5787 if (bca.line_offsets[bca.nlines - 1] == filesize)
5788 bca.nlines--;
5790 bca.lines = calloc(bca.nlines, sizeof(*bca.lines));
5791 if (bca.lines == NULL) {
5792 error = got_error_from_errno("calloc");
5793 goto done;
5795 bca.lineno_cur = 1;
5796 bca.nlines_prec = 0;
5797 i = bca.nlines;
5798 while (i > 0) {
5799 i /= 10;
5800 bca.nlines_prec++;
5802 bca.repo = repo;
5804 fd2 = got_opentempfd();
5805 if (fd2 == -1) {
5806 error = got_error_from_errno("got_opentempfd");
5807 goto done;
5809 fd3 = got_opentempfd();
5810 if (fd3 == -1) {
5811 error = got_error_from_errno("got_opentempfd");
5812 goto done;
5814 f1 = got_opentemp();
5815 if (f1 == NULL) {
5816 error = got_error_from_errno("got_opentemp");
5817 goto done;
5819 f2 = got_opentemp();
5820 if (f2 == NULL) {
5821 error = got_error_from_errno("got_opentemp");
5822 goto done;
5824 error = got_blame(link_target ? link_target : in_repo_path, commit_id,
5825 repo, GOT_DIFF_ALGORITHM_PATIENCE, blame_cb, &bca,
5826 check_cancelled, NULL, fd2, fd3, f1, f2);
5827 done:
5828 free(in_repo_path);
5829 free(link_target);
5830 free(repo_path);
5831 free(cwd);
5832 free(commit_id);
5833 free(obj_id);
5834 if (commit)
5835 got_object_commit_close(commit);
5837 if (fd1 != -1 && close(fd1) == -1 && error == NULL)
5838 error = got_error_from_errno("close");
5839 if (fd2 != -1 && close(fd2) == -1 && error == NULL)
5840 error = got_error_from_errno("close");
5841 if (fd3 != -1 && close(fd3) == -1 && error == NULL)
5842 error = got_error_from_errno("close");
5843 if (f1 && fclose(f1) == EOF && error == NULL)
5844 error = got_error_from_errno("fclose");
5845 if (f2 && fclose(f2) == EOF && error == NULL)
5846 error = got_error_from_errno("fclose");
5848 if (blob)
5849 got_object_blob_close(blob);
5850 if (worktree)
5851 got_worktree_close(worktree);
5852 if (repo) {
5853 const struct got_error *close_err = got_repo_close(repo);
5854 if (error == NULL)
5855 error = close_err;
5857 if (pack_fds) {
5858 const struct got_error *pack_err =
5859 got_repo_pack_fds_close(pack_fds);
5860 if (error == NULL)
5861 error = pack_err;
5863 if (bca.lines) {
5864 for (i = 0; i < bca.nlines; i++) {
5865 struct blame_line *bline = &bca.lines[i];
5866 free(bline->id_str);
5867 free(bline->committer);
5869 free(bca.lines);
5871 free(bca.line_offsets);
5872 if (bca.f && fclose(bca.f) == EOF && error == NULL)
5873 error = got_error_from_errno("fclose");
5874 return error;
5877 __dead static void
5878 usage_tree(void)
5880 fprintf(stderr, "usage: %s tree [-iR] [-c commit] [-r repository-path] "
5881 "[path]\n", getprogname());
5882 exit(1);
5885 static const struct got_error *
5886 print_entry(struct got_tree_entry *te, const char *id, const char *path,
5887 const char *root_path, struct got_repository *repo)
5889 const struct got_error *err = NULL;
5890 int is_root_path = (strcmp(path, root_path) == 0);
5891 const char *modestr = "";
5892 mode_t mode = got_tree_entry_get_mode(te);
5893 char *link_target = NULL;
5895 path += strlen(root_path);
5896 while (path[0] == '/')
5897 path++;
5899 if (got_object_tree_entry_is_submodule(te))
5900 modestr = "$";
5901 else if (S_ISLNK(mode)) {
5902 int i;
5904 err = got_tree_entry_get_symlink_target(&link_target, te, repo);
5905 if (err)
5906 return err;
5907 for (i = 0; i < strlen(link_target); i++) {
5908 if (!isprint((unsigned char)link_target[i]))
5909 link_target[i] = '?';
5912 modestr = "@";
5914 else if (S_ISDIR(mode))
5915 modestr = "/";
5916 else if (mode & S_IXUSR)
5917 modestr = "*";
5919 printf("%s%s%s%s%s%s%s\n", id ? id : "", path,
5920 is_root_path ? "" : "/", got_tree_entry_get_name(te), modestr,
5921 link_target ? " -> ": "", link_target ? link_target : "");
5923 free(link_target);
5924 return NULL;
5927 static const struct got_error *
5928 print_tree(const char *path, struct got_commit_object *commit,
5929 int show_ids, int recurse, const char *root_path,
5930 struct got_repository *repo)
5932 const struct got_error *err = NULL;
5933 struct got_object_id *tree_id = NULL;
5934 struct got_tree_object *tree = NULL;
5935 int nentries, i;
5937 err = got_object_id_by_path(&tree_id, repo, commit, path);
5938 if (err)
5939 goto done;
5941 err = got_object_open_as_tree(&tree, repo, tree_id);
5942 if (err)
5943 goto done;
5944 nentries = got_object_tree_get_nentries(tree);
5945 for (i = 0; i < nentries; i++) {
5946 struct got_tree_entry *te;
5947 char *id = NULL;
5949 if (sigint_received || sigpipe_received)
5950 break;
5952 te = got_object_tree_get_entry(tree, i);
5953 if (show_ids) {
5954 char *id_str;
5955 err = got_object_id_str(&id_str,
5956 got_tree_entry_get_id(te));
5957 if (err)
5958 goto done;
5959 if (asprintf(&id, "%s ", id_str) == -1) {
5960 err = got_error_from_errno("asprintf");
5961 free(id_str);
5962 goto done;
5964 free(id_str);
5966 err = print_entry(te, id, path, root_path, repo);
5967 free(id);
5968 if (err)
5969 goto done;
5971 if (recurse && S_ISDIR(got_tree_entry_get_mode(te))) {
5972 char *child_path;
5973 if (asprintf(&child_path, "%s%s%s", path,
5974 path[0] == '/' && path[1] == '\0' ? "" : "/",
5975 got_tree_entry_get_name(te)) == -1) {
5976 err = got_error_from_errno("asprintf");
5977 goto done;
5979 err = print_tree(child_path, commit, show_ids, 1,
5980 root_path, repo);
5981 free(child_path);
5982 if (err)
5983 goto done;
5986 done:
5987 if (tree)
5988 got_object_tree_close(tree);
5989 free(tree_id);
5990 return err;
5993 static const struct got_error *
5994 cmd_tree(int argc, char *argv[])
5996 const struct got_error *error;
5997 struct got_repository *repo = NULL;
5998 struct got_worktree *worktree = NULL;
5999 const char *path, *refname = NULL;
6000 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
6001 struct got_object_id *commit_id = NULL;
6002 struct got_commit_object *commit = NULL;
6003 char *commit_id_str = NULL;
6004 int show_ids = 0, recurse = 0;
6005 int ch;
6006 int *pack_fds = NULL;
6008 #ifndef PROFILE
6009 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
6010 NULL) == -1)
6011 err(1, "pledge");
6012 #endif
6014 while ((ch = getopt(argc, argv, "c:iRr:")) != -1) {
6015 switch (ch) {
6016 case 'c':
6017 commit_id_str = optarg;
6018 break;
6019 case 'i':
6020 show_ids = 1;
6021 break;
6022 case 'R':
6023 recurse = 1;
6024 break;
6025 case 'r':
6026 repo_path = realpath(optarg, NULL);
6027 if (repo_path == NULL)
6028 return got_error_from_errno2("realpath",
6029 optarg);
6030 got_path_strip_trailing_slashes(repo_path);
6031 break;
6032 default:
6033 usage_tree();
6034 /* NOTREACHED */
6038 argc -= optind;
6039 argv += optind;
6041 if (argc == 1)
6042 path = argv[0];
6043 else if (argc > 1)
6044 usage_tree();
6045 else
6046 path = NULL;
6048 cwd = getcwd(NULL, 0);
6049 if (cwd == NULL) {
6050 error = got_error_from_errno("getcwd");
6051 goto done;
6054 error = got_repo_pack_fds_open(&pack_fds);
6055 if (error != NULL)
6056 goto done;
6058 if (repo_path == NULL) {
6059 error = got_worktree_open(&worktree, cwd);
6060 if (error && error->code != GOT_ERR_NOT_WORKTREE)
6061 goto done;
6062 else
6063 error = NULL;
6064 if (worktree) {
6065 repo_path =
6066 strdup(got_worktree_get_repo_path(worktree));
6067 if (repo_path == NULL)
6068 error = got_error_from_errno("strdup");
6069 if (error)
6070 goto done;
6071 } else {
6072 repo_path = strdup(cwd);
6073 if (repo_path == NULL) {
6074 error = got_error_from_errno("strdup");
6075 goto done;
6080 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
6081 if (error != NULL)
6082 goto done;
6084 if (worktree) {
6085 const char *prefix = got_worktree_get_path_prefix(worktree);
6086 char *p;
6088 if (path == NULL)
6089 path = "";
6090 error = got_worktree_resolve_path(&p, worktree, path);
6091 if (error)
6092 goto done;
6093 if (asprintf(&in_repo_path, "%s%s%s", prefix,
6094 (p[0] != '\0' && !got_path_is_root_dir(prefix)) ? "/" : "",
6095 p) == -1) {
6096 error = got_error_from_errno("asprintf");
6097 free(p);
6098 goto done;
6100 free(p);
6101 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
6102 if (error)
6103 goto done;
6104 } else {
6105 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
6106 if (error)
6107 goto done;
6108 if (path == NULL)
6109 path = "/";
6110 error = got_repo_map_path(&in_repo_path, repo, path);
6111 if (error != NULL)
6112 goto done;
6115 if (commit_id_str == NULL) {
6116 struct got_reference *head_ref;
6117 if (worktree)
6118 refname = got_worktree_get_head_ref_name(worktree);
6119 else
6120 refname = GOT_REF_HEAD;
6121 error = got_ref_open(&head_ref, repo, refname, 0);
6122 if (error != NULL)
6123 goto done;
6124 error = got_ref_resolve(&commit_id, repo, head_ref);
6125 got_ref_close(head_ref);
6126 if (error != NULL)
6127 goto done;
6128 } else {
6129 struct got_reflist_head refs;
6130 TAILQ_INIT(&refs);
6131 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
6132 NULL);
6133 if (error)
6134 goto done;
6135 error = got_repo_match_object_id(&commit_id, NULL,
6136 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
6137 got_ref_list_free(&refs);
6138 if (error)
6139 goto done;
6142 if (worktree) {
6143 /* Release work tree lock. */
6144 got_worktree_close(worktree);
6145 worktree = NULL;
6148 error = got_object_open_as_commit(&commit, repo, commit_id);
6149 if (error)
6150 goto done;
6152 error = print_tree(in_repo_path, commit, show_ids, recurse,
6153 in_repo_path, repo);
6154 done:
6155 free(in_repo_path);
6156 free(repo_path);
6157 free(cwd);
6158 free(commit_id);
6159 if (commit)
6160 got_object_commit_close(commit);
6161 if (worktree)
6162 got_worktree_close(worktree);
6163 if (repo) {
6164 const struct got_error *close_err = got_repo_close(repo);
6165 if (error == NULL)
6166 error = close_err;
6168 if (pack_fds) {
6169 const struct got_error *pack_err =
6170 got_repo_pack_fds_close(pack_fds);
6171 if (error == NULL)
6172 error = pack_err;
6174 return error;
6177 __dead static void
6178 usage_status(void)
6180 fprintf(stderr, "usage: %s status [-I] [-S status-codes] "
6181 "[-s status-codes] [path ...]\n", getprogname());
6182 exit(1);
6185 struct got_status_arg {
6186 char *status_codes;
6187 int suppress;
6190 static const struct got_error *
6191 print_status(void *arg, unsigned char status, unsigned char staged_status,
6192 const char *path, struct got_object_id *blob_id,
6193 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
6194 int dirfd, const char *de_name)
6196 struct got_status_arg *st = arg;
6198 if (status == staged_status && (status == GOT_STATUS_DELETE))
6199 status = GOT_STATUS_NO_CHANGE;
6200 if (st != NULL && st->status_codes) {
6201 size_t ncodes = strlen(st->status_codes);
6202 int i, j = 0;
6204 for (i = 0; i < ncodes ; i++) {
6205 if (st->suppress) {
6206 if (status == st->status_codes[i] ||
6207 staged_status == st->status_codes[i]) {
6208 j++;
6209 continue;
6211 } else {
6212 if (status == st->status_codes[i] ||
6213 staged_status == st->status_codes[i])
6214 break;
6218 if (st->suppress && j == 0)
6219 goto print;
6221 if (i == ncodes)
6222 return NULL;
6224 print:
6225 printf("%c%c %s\n", status, staged_status, path);
6226 return NULL;
6229 static const struct got_error *
6230 cmd_status(int argc, char *argv[])
6232 const struct got_error *error = NULL;
6233 struct got_repository *repo = NULL;
6234 struct got_worktree *worktree = NULL;
6235 struct got_status_arg st;
6236 char *cwd = NULL;
6237 struct got_pathlist_head paths;
6238 int ch, i, no_ignores = 0;
6239 int *pack_fds = NULL;
6241 TAILQ_INIT(&paths);
6243 memset(&st, 0, sizeof(st));
6244 st.status_codes = NULL;
6245 st.suppress = 0;
6247 while ((ch = getopt(argc, argv, "IS:s:")) != -1) {
6248 switch (ch) {
6249 case 'I':
6250 no_ignores = 1;
6251 break;
6252 case 'S':
6253 if (st.status_codes != NULL && st.suppress == 0)
6254 option_conflict('S', 's');
6255 st.suppress = 1;
6256 /* fallthrough */
6257 case 's':
6258 for (i = 0; i < strlen(optarg); i++) {
6259 switch (optarg[i]) {
6260 case GOT_STATUS_MODIFY:
6261 case GOT_STATUS_ADD:
6262 case GOT_STATUS_DELETE:
6263 case GOT_STATUS_CONFLICT:
6264 case GOT_STATUS_MISSING:
6265 case GOT_STATUS_OBSTRUCTED:
6266 case GOT_STATUS_UNVERSIONED:
6267 case GOT_STATUS_MODE_CHANGE:
6268 case GOT_STATUS_NONEXISTENT:
6269 break;
6270 default:
6271 errx(1, "invalid status code '%c'",
6272 optarg[i]);
6275 if (ch == 's' && st.suppress)
6276 option_conflict('s', 'S');
6277 st.status_codes = optarg;
6278 break;
6279 default:
6280 usage_status();
6281 /* NOTREACHED */
6285 argc -= optind;
6286 argv += optind;
6288 #ifndef PROFILE
6289 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
6290 NULL) == -1)
6291 err(1, "pledge");
6292 #endif
6293 cwd = getcwd(NULL, 0);
6294 if (cwd == NULL) {
6295 error = got_error_from_errno("getcwd");
6296 goto done;
6299 error = got_repo_pack_fds_open(&pack_fds);
6300 if (error != NULL)
6301 goto done;
6303 error = got_worktree_open(&worktree, cwd);
6304 if (error) {
6305 if (error->code == GOT_ERR_NOT_WORKTREE)
6306 error = wrap_not_worktree_error(error, "status", cwd);
6307 goto done;
6310 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
6311 NULL, pack_fds);
6312 if (error != NULL)
6313 goto done;
6315 error = apply_unveil(got_repo_get_path(repo), 1,
6316 got_worktree_get_root_path(worktree));
6317 if (error)
6318 goto done;
6320 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
6321 if (error)
6322 goto done;
6324 error = got_worktree_status(worktree, &paths, repo, no_ignores,
6325 print_status, &st, check_cancelled, NULL);
6326 done:
6327 if (pack_fds) {
6328 const struct got_error *pack_err =
6329 got_repo_pack_fds_close(pack_fds);
6330 if (error == NULL)
6331 error = pack_err;
6334 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
6335 free(cwd);
6336 return error;
6339 __dead static void
6340 usage_ref(void)
6342 fprintf(stderr, "usage: %s ref [-dlt] [-c object] [-r repository-path] "
6343 "[-s reference] [name]\n", getprogname());
6344 exit(1);
6347 static const struct got_error *
6348 list_refs(struct got_repository *repo, const char *refname, int sort_by_time)
6350 static const struct got_error *err = NULL;
6351 struct got_reflist_head refs;
6352 struct got_reflist_entry *re;
6354 TAILQ_INIT(&refs);
6355 err = got_ref_list(&refs, repo, refname, sort_by_time ?
6356 got_ref_cmp_by_commit_timestamp_descending : got_ref_cmp_by_name,
6357 repo);
6358 if (err)
6359 return err;
6361 TAILQ_FOREACH(re, &refs, entry) {
6362 char *refstr;
6363 refstr = got_ref_to_str(re->ref);
6364 if (refstr == NULL) {
6365 err = got_error_from_errno("got_ref_to_str");
6366 break;
6368 printf("%s: %s\n", got_ref_get_name(re->ref), refstr);
6369 free(refstr);
6372 got_ref_list_free(&refs);
6373 return err;
6376 static const struct got_error *
6377 delete_ref_by_name(struct got_repository *repo, const char *refname)
6379 const struct got_error *err;
6380 struct got_reference *ref;
6382 err = got_ref_open(&ref, repo, refname, 0);
6383 if (err)
6384 return err;
6386 err = delete_ref(repo, ref);
6387 got_ref_close(ref);
6388 return err;
6391 static const struct got_error *
6392 add_ref(struct got_repository *repo, const char *refname, const char *target)
6394 const struct got_error *err = NULL;
6395 struct got_object_id *id = NULL;
6396 struct got_reference *ref = NULL;
6397 struct got_reflist_head refs;
6400 * Don't let the user create a reference name with a leading '-'.
6401 * While technically a valid reference name, this case is usually
6402 * an unintended typo.
6404 if (refname[0] == '-')
6405 return got_error_path(refname, GOT_ERR_REF_NAME_MINUS);
6407 TAILQ_INIT(&refs);
6408 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
6409 if (err)
6410 goto done;
6411 err = got_repo_match_object_id(&id, NULL, target, GOT_OBJ_TYPE_ANY,
6412 &refs, repo);
6413 got_ref_list_free(&refs);
6414 if (err)
6415 goto done;
6417 err = got_ref_alloc(&ref, refname, id);
6418 if (err)
6419 goto done;
6421 err = got_ref_write(ref, repo);
6422 done:
6423 if (ref)
6424 got_ref_close(ref);
6425 free(id);
6426 return err;
6429 static const struct got_error *
6430 add_symref(struct got_repository *repo, const char *refname, const char *target)
6432 const struct got_error *err = NULL;
6433 struct got_reference *ref = NULL;
6434 struct got_reference *target_ref = NULL;
6437 * Don't let the user create a reference name with a leading '-'.
6438 * While technically a valid reference name, this case is usually
6439 * an unintended typo.
6441 if (refname[0] == '-')
6442 return got_error_path(refname, GOT_ERR_REF_NAME_MINUS);
6444 err = got_ref_open(&target_ref, repo, target, 0);
6445 if (err)
6446 return err;
6448 err = got_ref_alloc_symref(&ref, refname, target_ref);
6449 if (err)
6450 goto done;
6452 err = got_ref_write(ref, repo);
6453 done:
6454 if (target_ref)
6455 got_ref_close(target_ref);
6456 if (ref)
6457 got_ref_close(ref);
6458 return err;
6461 static const struct got_error *
6462 cmd_ref(int argc, char *argv[])
6464 const struct got_error *error = NULL;
6465 struct got_repository *repo = NULL;
6466 struct got_worktree *worktree = NULL;
6467 char *cwd = NULL, *repo_path = NULL;
6468 int ch, do_list = 0, do_delete = 0, sort_by_time = 0;
6469 const char *obj_arg = NULL, *symref_target= NULL;
6470 char *refname = NULL;
6471 int *pack_fds = NULL;
6473 while ((ch = getopt(argc, argv, "c:dlr:s:t")) != -1) {
6474 switch (ch) {
6475 case 'c':
6476 obj_arg = optarg;
6477 break;
6478 case 'd':
6479 do_delete = 1;
6480 break;
6481 case 'l':
6482 do_list = 1;
6483 break;
6484 case 'r':
6485 repo_path = realpath(optarg, NULL);
6486 if (repo_path == NULL)
6487 return got_error_from_errno2("realpath",
6488 optarg);
6489 got_path_strip_trailing_slashes(repo_path);
6490 break;
6491 case 's':
6492 symref_target = optarg;
6493 break;
6494 case 't':
6495 sort_by_time = 1;
6496 break;
6497 default:
6498 usage_ref();
6499 /* NOTREACHED */
6503 if (obj_arg && do_list)
6504 option_conflict('c', 'l');
6505 if (obj_arg && do_delete)
6506 option_conflict('c', 'd');
6507 if (obj_arg && symref_target)
6508 option_conflict('c', 's');
6509 if (symref_target && do_delete)
6510 option_conflict('s', 'd');
6511 if (symref_target && do_list)
6512 option_conflict('s', 'l');
6513 if (do_delete && do_list)
6514 option_conflict('d', 'l');
6515 if (sort_by_time && !do_list)
6516 errx(1, "-t option requires -l option");
6518 argc -= optind;
6519 argv += optind;
6521 if (do_list) {
6522 if (argc != 0 && argc != 1)
6523 usage_ref();
6524 if (argc == 1) {
6525 refname = strdup(argv[0]);
6526 if (refname == NULL) {
6527 error = got_error_from_errno("strdup");
6528 goto done;
6531 } else {
6532 if (argc != 1)
6533 usage_ref();
6534 refname = strdup(argv[0]);
6535 if (refname == NULL) {
6536 error = got_error_from_errno("strdup");
6537 goto done;
6541 if (refname)
6542 got_path_strip_trailing_slashes(refname);
6544 #ifndef PROFILE
6545 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
6546 "sendfd unveil", NULL) == -1)
6547 err(1, "pledge");
6548 #endif
6549 cwd = getcwd(NULL, 0);
6550 if (cwd == NULL) {
6551 error = got_error_from_errno("getcwd");
6552 goto done;
6555 error = got_repo_pack_fds_open(&pack_fds);
6556 if (error != NULL)
6557 goto done;
6559 if (repo_path == NULL) {
6560 error = got_worktree_open(&worktree, cwd);
6561 if (error && error->code != GOT_ERR_NOT_WORKTREE)
6562 goto done;
6563 else
6564 error = NULL;
6565 if (worktree) {
6566 repo_path =
6567 strdup(got_worktree_get_repo_path(worktree));
6568 if (repo_path == NULL)
6569 error = got_error_from_errno("strdup");
6570 if (error)
6571 goto done;
6572 } else {
6573 repo_path = strdup(cwd);
6574 if (repo_path == NULL) {
6575 error = got_error_from_errno("strdup");
6576 goto done;
6581 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
6582 if (error != NULL)
6583 goto done;
6585 #ifndef PROFILE
6586 if (do_list) {
6587 /* Remove "cpath" promise. */
6588 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
6589 NULL) == -1)
6590 err(1, "pledge");
6592 #endif
6594 error = apply_unveil(got_repo_get_path(repo), do_list,
6595 worktree ? got_worktree_get_root_path(worktree) : NULL);
6596 if (error)
6597 goto done;
6599 if (do_list)
6600 error = list_refs(repo, refname, sort_by_time);
6601 else if (do_delete)
6602 error = delete_ref_by_name(repo, refname);
6603 else if (symref_target)
6604 error = add_symref(repo, refname, symref_target);
6605 else {
6606 if (obj_arg == NULL)
6607 usage_ref();
6608 error = add_ref(repo, refname, obj_arg);
6610 done:
6611 free(refname);
6612 if (repo) {
6613 const struct got_error *close_err = got_repo_close(repo);
6614 if (error == NULL)
6615 error = close_err;
6617 if (worktree)
6618 got_worktree_close(worktree);
6619 if (pack_fds) {
6620 const struct got_error *pack_err =
6621 got_repo_pack_fds_close(pack_fds);
6622 if (error == NULL)
6623 error = pack_err;
6625 free(cwd);
6626 free(repo_path);
6627 return error;
6630 __dead static void
6631 usage_branch(void)
6633 fprintf(stderr, "usage: %s branch [-lnt] [-c commit] [-d name] "
6634 "[-r repository-path] [name]\n", getprogname());
6635 exit(1);
6638 static const struct got_error *
6639 list_branch(struct got_repository *repo, struct got_worktree *worktree,
6640 struct got_reference *ref)
6642 const struct got_error *err = NULL;
6643 const char *refname, *marker = " ";
6644 char *refstr;
6646 refname = got_ref_get_name(ref);
6647 if (worktree && strcmp(refname,
6648 got_worktree_get_head_ref_name(worktree)) == 0) {
6649 struct got_object_id *id = NULL;
6651 err = got_ref_resolve(&id, repo, ref);
6652 if (err)
6653 return err;
6654 if (got_object_id_cmp(id,
6655 got_worktree_get_base_commit_id(worktree)) == 0)
6656 marker = "* ";
6657 else
6658 marker = "~ ";
6659 free(id);
6662 if (strncmp(refname, "refs/heads/", 11) == 0)
6663 refname += 11;
6664 if (strncmp(refname, "refs/got/worktree/", 18) == 0)
6665 refname += 18;
6666 if (strncmp(refname, "refs/remotes/", 13) == 0)
6667 refname += 13;
6669 refstr = got_ref_to_str(ref);
6670 if (refstr == NULL)
6671 return got_error_from_errno("got_ref_to_str");
6673 printf("%s%s: %s\n", marker, refname, refstr);
6674 free(refstr);
6675 return NULL;
6678 static const struct got_error *
6679 show_current_branch(struct got_repository *repo, struct got_worktree *worktree)
6681 const char *refname;
6683 if (worktree == NULL)
6684 return got_error(GOT_ERR_NOT_WORKTREE);
6686 refname = got_worktree_get_head_ref_name(worktree);
6688 if (strncmp(refname, "refs/heads/", 11) == 0)
6689 refname += 11;
6690 if (strncmp(refname, "refs/got/worktree/", 18) == 0)
6691 refname += 18;
6693 printf("%s\n", refname);
6695 return NULL;
6698 static const struct got_error *
6699 list_branches(struct got_repository *repo, struct got_worktree *worktree,
6700 int sort_by_time)
6702 static const struct got_error *err = NULL;
6703 struct got_reflist_head refs;
6704 struct got_reflist_entry *re;
6705 struct got_reference *temp_ref = NULL;
6706 int rebase_in_progress, histedit_in_progress;
6708 TAILQ_INIT(&refs);
6710 if (worktree) {
6711 err = got_worktree_rebase_in_progress(&rebase_in_progress,
6712 worktree);
6713 if (err)
6714 return err;
6716 err = got_worktree_histedit_in_progress(&histedit_in_progress,
6717 worktree);
6718 if (err)
6719 return err;
6721 if (rebase_in_progress || histedit_in_progress) {
6722 err = got_ref_open(&temp_ref, repo,
6723 got_worktree_get_head_ref_name(worktree), 0);
6724 if (err)
6725 return err;
6726 list_branch(repo, worktree, temp_ref);
6727 got_ref_close(temp_ref);
6731 err = got_ref_list(&refs, repo, "refs/heads", sort_by_time ?
6732 got_ref_cmp_by_commit_timestamp_descending : got_ref_cmp_by_name,
6733 repo);
6734 if (err)
6735 return err;
6737 TAILQ_FOREACH(re, &refs, entry)
6738 list_branch(repo, worktree, re->ref);
6740 got_ref_list_free(&refs);
6742 err = got_ref_list(&refs, repo, "refs/remotes", sort_by_time ?
6743 got_ref_cmp_by_commit_timestamp_descending : got_ref_cmp_by_name,
6744 repo);
6745 if (err)
6746 return err;
6748 TAILQ_FOREACH(re, &refs, entry)
6749 list_branch(repo, worktree, re->ref);
6751 got_ref_list_free(&refs);
6753 return NULL;
6756 static const struct got_error *
6757 delete_branch(struct got_repository *repo, struct got_worktree *worktree,
6758 const char *branch_name)
6760 const struct got_error *err = NULL;
6761 struct got_reference *ref = NULL;
6762 char *refname, *remote_refname = NULL;
6764 if (strncmp(branch_name, "refs/", 5) == 0)
6765 branch_name += 5;
6766 if (strncmp(branch_name, "heads/", 6) == 0)
6767 branch_name += 6;
6768 else if (strncmp(branch_name, "remotes/", 8) == 0)
6769 branch_name += 8;
6771 if (asprintf(&refname, "refs/heads/%s", branch_name) == -1)
6772 return got_error_from_errno("asprintf");
6774 if (asprintf(&remote_refname, "refs/remotes/%s",
6775 branch_name) == -1) {
6776 err = got_error_from_errno("asprintf");
6777 goto done;
6780 err = got_ref_open(&ref, repo, refname, 0);
6781 if (err) {
6782 const struct got_error *err2;
6783 if (err->code != GOT_ERR_NOT_REF)
6784 goto done;
6786 * Keep 'err' intact such that if neither branch exists
6787 * we report "refs/heads" rather than "refs/remotes" in
6788 * our error message.
6790 err2 = got_ref_open(&ref, repo, remote_refname, 0);
6791 if (err2)
6792 goto done;
6793 err = NULL;
6796 if (worktree &&
6797 strcmp(got_worktree_get_head_ref_name(worktree),
6798 got_ref_get_name(ref)) == 0) {
6799 err = got_error_msg(GOT_ERR_SAME_BRANCH,
6800 "will not delete this work tree's current branch");
6801 goto done;
6804 err = delete_ref(repo, ref);
6805 done:
6806 if (ref)
6807 got_ref_close(ref);
6808 free(refname);
6809 free(remote_refname);
6810 return err;
6813 static const struct got_error *
6814 add_branch(struct got_repository *repo, const char *branch_name,
6815 struct got_object_id *base_commit_id)
6817 const struct got_error *err = NULL;
6818 struct got_reference *ref = NULL;
6819 char *refname = NULL;
6822 * Don't let the user create a branch name with a leading '-'.
6823 * While technically a valid reference name, this case is usually
6824 * an unintended typo.
6826 if (branch_name[0] == '-')
6827 return got_error_path(branch_name, GOT_ERR_REF_NAME_MINUS);
6829 if (strncmp(branch_name, "refs/heads/", 11) == 0)
6830 branch_name += 11;
6832 if (asprintf(&refname, "refs/heads/%s", branch_name) == -1) {
6833 err = got_error_from_errno("asprintf");
6834 goto done;
6837 err = got_ref_open(&ref, repo, refname, 0);
6838 if (err == NULL) {
6839 err = got_error(GOT_ERR_BRANCH_EXISTS);
6840 goto done;
6841 } else if (err->code != GOT_ERR_NOT_REF)
6842 goto done;
6844 err = got_ref_alloc(&ref, refname, base_commit_id);
6845 if (err)
6846 goto done;
6848 err = got_ref_write(ref, repo);
6849 done:
6850 if (ref)
6851 got_ref_close(ref);
6852 free(refname);
6853 return err;
6856 static const struct got_error *
6857 cmd_branch(int argc, char *argv[])
6859 const struct got_error *error = NULL;
6860 struct got_repository *repo = NULL;
6861 struct got_worktree *worktree = NULL;
6862 char *cwd = NULL, *repo_path = NULL;
6863 int ch, do_list = 0, do_show = 0, do_update = 1, sort_by_time = 0;
6864 const char *delref = NULL, *commit_id_arg = NULL;
6865 struct got_reference *ref = NULL;
6866 struct got_pathlist_head paths;
6867 struct got_object_id *commit_id = NULL;
6868 char *commit_id_str = NULL;
6869 int *pack_fds = NULL;
6871 TAILQ_INIT(&paths);
6873 while ((ch = getopt(argc, argv, "c:d:lnr:t")) != -1) {
6874 switch (ch) {
6875 case 'c':
6876 commit_id_arg = optarg;
6877 break;
6878 case 'd':
6879 delref = optarg;
6880 break;
6881 case 'l':
6882 do_list = 1;
6883 break;
6884 case 'n':
6885 do_update = 0;
6886 break;
6887 case 'r':
6888 repo_path = realpath(optarg, NULL);
6889 if (repo_path == NULL)
6890 return got_error_from_errno2("realpath",
6891 optarg);
6892 got_path_strip_trailing_slashes(repo_path);
6893 break;
6894 case 't':
6895 sort_by_time = 1;
6896 break;
6897 default:
6898 usage_branch();
6899 /* NOTREACHED */
6903 if (do_list && delref)
6904 option_conflict('l', 'd');
6905 if (sort_by_time && !do_list)
6906 errx(1, "-t option requires -l option");
6908 argc -= optind;
6909 argv += optind;
6911 if (!do_list && !delref && argc == 0)
6912 do_show = 1;
6914 if ((do_list || delref || do_show) && commit_id_arg != NULL)
6915 errx(1, "-c option can only be used when creating a branch");
6917 if (do_list || delref) {
6918 if (argc > 0)
6919 usage_branch();
6920 } else if (!do_show && argc != 1)
6921 usage_branch();
6923 #ifndef PROFILE
6924 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
6925 "sendfd unveil", NULL) == -1)
6926 err(1, "pledge");
6927 #endif
6928 cwd = getcwd(NULL, 0);
6929 if (cwd == NULL) {
6930 error = got_error_from_errno("getcwd");
6931 goto done;
6934 error = got_repo_pack_fds_open(&pack_fds);
6935 if (error != NULL)
6936 goto done;
6938 if (repo_path == NULL) {
6939 error = got_worktree_open(&worktree, cwd);
6940 if (error && error->code != GOT_ERR_NOT_WORKTREE)
6941 goto done;
6942 else
6943 error = NULL;
6944 if (worktree) {
6945 repo_path =
6946 strdup(got_worktree_get_repo_path(worktree));
6947 if (repo_path == NULL)
6948 error = got_error_from_errno("strdup");
6949 if (error)
6950 goto done;
6951 } else {
6952 repo_path = strdup(cwd);
6953 if (repo_path == NULL) {
6954 error = got_error_from_errno("strdup");
6955 goto done;
6960 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
6961 if (error != NULL)
6962 goto done;
6964 #ifndef PROFILE
6965 if (do_list || do_show) {
6966 /* Remove "cpath" promise. */
6967 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
6968 NULL) == -1)
6969 err(1, "pledge");
6971 #endif
6973 error = apply_unveil(got_repo_get_path(repo), do_list,
6974 worktree ? got_worktree_get_root_path(worktree) : NULL);
6975 if (error)
6976 goto done;
6978 if (do_show)
6979 error = show_current_branch(repo, worktree);
6980 else if (do_list)
6981 error = list_branches(repo, worktree, sort_by_time);
6982 else if (delref)
6983 error = delete_branch(repo, worktree, delref);
6984 else {
6985 struct got_reflist_head refs;
6986 TAILQ_INIT(&refs);
6987 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
6988 NULL);
6989 if (error)
6990 goto done;
6991 if (commit_id_arg == NULL)
6992 commit_id_arg = worktree ?
6993 got_worktree_get_head_ref_name(worktree) :
6994 GOT_REF_HEAD;
6995 error = got_repo_match_object_id(&commit_id, NULL,
6996 commit_id_arg, GOT_OBJ_TYPE_COMMIT, &refs, repo);
6997 got_ref_list_free(&refs);
6998 if (error)
6999 goto done;
7000 error = add_branch(repo, argv[0], commit_id);
7001 if (error)
7002 goto done;
7003 if (worktree && do_update) {
7004 struct got_update_progress_arg upa;
7005 char *branch_refname = NULL;
7007 error = got_object_id_str(&commit_id_str, commit_id);
7008 if (error)
7009 goto done;
7010 error = get_worktree_paths_from_argv(&paths, 0, NULL,
7011 worktree);
7012 if (error)
7013 goto done;
7014 if (asprintf(&branch_refname, "refs/heads/%s", argv[0])
7015 == -1) {
7016 error = got_error_from_errno("asprintf");
7017 goto done;
7019 error = got_ref_open(&ref, repo, branch_refname, 0);
7020 free(branch_refname);
7021 if (error)
7022 goto done;
7023 error = switch_head_ref(ref, commit_id, worktree,
7024 repo);
7025 if (error)
7026 goto done;
7027 error = got_worktree_set_base_commit_id(worktree, repo,
7028 commit_id);
7029 if (error)
7030 goto done;
7031 memset(&upa, 0, sizeof(upa));
7032 error = got_worktree_checkout_files(worktree, &paths,
7033 repo, update_progress, &upa, check_cancelled,
7034 NULL);
7035 if (error)
7036 goto done;
7037 if (upa.did_something) {
7038 printf("Updated to %s: %s\n",
7039 got_worktree_get_head_ref_name(worktree),
7040 commit_id_str);
7042 print_update_progress_stats(&upa);
7045 done:
7046 if (ref)
7047 got_ref_close(ref);
7048 if (repo) {
7049 const struct got_error *close_err = got_repo_close(repo);
7050 if (error == NULL)
7051 error = close_err;
7053 if (worktree)
7054 got_worktree_close(worktree);
7055 if (pack_fds) {
7056 const struct got_error *pack_err =
7057 got_repo_pack_fds_close(pack_fds);
7058 if (error == NULL)
7059 error = pack_err;
7061 free(cwd);
7062 free(repo_path);
7063 free(commit_id);
7064 free(commit_id_str);
7065 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
7066 return error;
7070 __dead static void
7071 usage_tag(void)
7073 fprintf(stderr, "usage: %s tag [-lVv] [-c commit] [-m message] "
7074 "[-r repository-path] [-s signer-id] name\n", getprogname());
7075 exit(1);
7078 #if 0
7079 static const struct got_error *
7080 sort_tags(struct got_reflist_head *sorted, struct got_reflist_head *tags)
7082 const struct got_error *err = NULL;
7083 struct got_reflist_entry *re, *se, *new;
7084 struct got_object_id *re_id, *se_id;
7085 struct got_tag_object *re_tag, *se_tag;
7086 time_t re_time, se_time;
7088 STAILQ_FOREACH(re, tags, entry) {
7089 se = STAILQ_FIRST(sorted);
7090 if (se == NULL) {
7091 err = got_reflist_entry_dup(&new, re);
7092 if (err)
7093 return err;
7094 STAILQ_INSERT_HEAD(sorted, new, entry);
7095 continue;
7096 } else {
7097 err = got_ref_resolve(&re_id, repo, re->ref);
7098 if (err)
7099 break;
7100 err = got_object_open_as_tag(&re_tag, repo, re_id);
7101 free(re_id);
7102 if (err)
7103 break;
7104 re_time = got_object_tag_get_tagger_time(re_tag);
7105 got_object_tag_close(re_tag);
7108 while (se) {
7109 err = got_ref_resolve(&se_id, repo, re->ref);
7110 if (err)
7111 break;
7112 err = got_object_open_as_tag(&se_tag, repo, se_id);
7113 free(se_id);
7114 if (err)
7115 break;
7116 se_time = got_object_tag_get_tagger_time(se_tag);
7117 got_object_tag_close(se_tag);
7119 if (se_time > re_time) {
7120 err = got_reflist_entry_dup(&new, re);
7121 if (err)
7122 return err;
7123 STAILQ_INSERT_AFTER(sorted, se, new, entry);
7124 break;
7126 se = STAILQ_NEXT(se, entry);
7127 continue;
7130 done:
7131 return err;
7133 #endif
7135 static const struct got_error *
7136 get_tag_refname(char **refname, const char *tag_name)
7138 const struct got_error *err;
7140 if (strncmp("refs/tags/", tag_name, 10) == 0) {
7141 *refname = strdup(tag_name);
7142 if (*refname == NULL)
7143 return got_error_from_errno("strdup");
7144 } else if (asprintf(refname, "refs/tags/%s", tag_name) == -1) {
7145 err = got_error_from_errno("asprintf");
7146 *refname = NULL;
7147 return err;
7150 return NULL;
7153 static const struct got_error *
7154 list_tags(struct got_repository *repo, const char *tag_name, int verify_tags,
7155 const char *allowed_signers, const char *revoked_signers, int verbosity)
7157 static const struct got_error *err = NULL;
7158 struct got_reflist_head refs;
7159 struct got_reflist_entry *re;
7160 char *wanted_refname = NULL;
7161 int bad_sigs = 0;
7163 TAILQ_INIT(&refs);
7165 err = got_ref_list(&refs, repo, "refs/tags", got_ref_cmp_tags, repo);
7166 if (err)
7167 return err;
7169 if (tag_name) {
7170 struct got_reference *ref;
7171 err = get_tag_refname(&wanted_refname, tag_name);
7172 if (err)
7173 goto done;
7174 /* Wanted tag reference should exist. */
7175 err = got_ref_open(&ref, repo, wanted_refname, 0);
7176 if (err)
7177 goto done;
7178 got_ref_close(ref);
7181 TAILQ_FOREACH(re, &refs, entry) {
7182 const char *refname;
7183 char *refstr, *tagmsg0, *tagmsg, *line, *id_str, *datestr;
7184 char datebuf[26];
7185 const char *tagger, *ssh_sig = NULL;
7186 char *sig_msg = NULL;
7187 time_t tagger_time;
7188 struct got_object_id *id;
7189 struct got_tag_object *tag;
7190 struct got_commit_object *commit = NULL;
7192 refname = got_ref_get_name(re->ref);
7193 if (strncmp(refname, "refs/tags/", 10) != 0 ||
7194 (wanted_refname && strcmp(refname, wanted_refname) != 0))
7195 continue;
7196 refname += 10;
7197 refstr = got_ref_to_str(re->ref);
7198 if (refstr == NULL) {
7199 err = got_error_from_errno("got_ref_to_str");
7200 break;
7203 err = got_ref_resolve(&id, repo, re->ref);
7204 if (err)
7205 break;
7206 err = got_object_open_as_tag(&tag, repo, id);
7207 if (err) {
7208 if (err->code != GOT_ERR_OBJ_TYPE) {
7209 free(id);
7210 break;
7212 /* "lightweight" tag */
7213 err = got_object_open_as_commit(&commit, repo, id);
7214 if (err) {
7215 free(id);
7216 break;
7218 tagger = got_object_commit_get_committer(commit);
7219 tagger_time =
7220 got_object_commit_get_committer_time(commit);
7221 err = got_object_id_str(&id_str, id);
7222 free(id);
7223 if (err)
7224 break;
7225 } else {
7226 free(id);
7227 tagger = got_object_tag_get_tagger(tag);
7228 tagger_time = got_object_tag_get_tagger_time(tag);
7229 err = got_object_id_str(&id_str,
7230 got_object_tag_get_object_id(tag));
7231 if (err)
7232 break;
7235 if (tag && verify_tags) {
7236 ssh_sig = got_sigs_get_tagmsg_ssh_signature(
7237 got_object_tag_get_message(tag));
7238 if (ssh_sig && allowed_signers == NULL) {
7239 err = got_error_msg(
7240 GOT_ERR_VERIFY_TAG_SIGNATURE,
7241 "SSH signature verification requires "
7242 "setting allowed_signers in "
7243 "got.conf(5)");
7244 break;
7248 printf("%stag %s %s\n", GOT_COMMIT_SEP_STR, refname, refstr);
7249 free(refstr);
7250 printf("from: %s\n", tagger);
7251 datestr = get_datestr(&tagger_time, datebuf);
7252 if (datestr)
7253 printf("date: %s UTC\n", datestr);
7254 if (commit)
7255 printf("object: %s %s\n", GOT_OBJ_LABEL_COMMIT, id_str);
7256 else {
7257 switch (got_object_tag_get_object_type(tag)) {
7258 case GOT_OBJ_TYPE_BLOB:
7259 printf("object: %s %s\n", GOT_OBJ_LABEL_BLOB,
7260 id_str);
7261 break;
7262 case GOT_OBJ_TYPE_TREE:
7263 printf("object: %s %s\n", GOT_OBJ_LABEL_TREE,
7264 id_str);
7265 break;
7266 case GOT_OBJ_TYPE_COMMIT:
7267 printf("object: %s %s\n", GOT_OBJ_LABEL_COMMIT,
7268 id_str);
7269 break;
7270 case GOT_OBJ_TYPE_TAG:
7271 printf("object: %s %s\n", GOT_OBJ_LABEL_TAG,
7272 id_str);
7273 break;
7274 default:
7275 break;
7278 free(id_str);
7280 if (ssh_sig) {
7281 err = got_sigs_verify_tag_ssh(&sig_msg, tag, ssh_sig,
7282 allowed_signers, revoked_signers, verbosity);
7283 if (err && err->code == GOT_ERR_BAD_TAG_SIGNATURE)
7284 bad_sigs = 1;
7285 else if (err)
7286 break;
7287 printf("signature: %s", sig_msg);
7288 free(sig_msg);
7289 sig_msg = NULL;
7292 if (commit) {
7293 err = got_object_commit_get_logmsg(&tagmsg0, commit);
7294 if (err)
7295 break;
7296 got_object_commit_close(commit);
7297 } else {
7298 tagmsg0 = strdup(got_object_tag_get_message(tag));
7299 got_object_tag_close(tag);
7300 if (tagmsg0 == NULL) {
7301 err = got_error_from_errno("strdup");
7302 break;
7306 tagmsg = tagmsg0;
7307 do {
7308 line = strsep(&tagmsg, "\n");
7309 if (line)
7310 printf(" %s\n", line);
7311 } while (line);
7312 free(tagmsg0);
7314 done:
7315 got_ref_list_free(&refs);
7316 free(wanted_refname);
7318 if (err == NULL && bad_sigs)
7319 err = got_error(GOT_ERR_BAD_TAG_SIGNATURE);
7320 return err;
7323 static const struct got_error *
7324 get_tag_message(char **tagmsg, char **tagmsg_path, const char *commit_id_str,
7325 const char *tag_name, const char *repo_path)
7327 const struct got_error *err = NULL;
7328 char *template = NULL, *initial_content = NULL;
7329 char *editor = NULL;
7330 int initial_content_len;
7331 int fd = -1;
7333 if (asprintf(&template, GOT_TMPDIR_STR "/got-tagmsg") == -1) {
7334 err = got_error_from_errno("asprintf");
7335 goto done;
7338 initial_content_len = asprintf(&initial_content,
7339 "\n# tagging commit %s as %s\n",
7340 commit_id_str, tag_name);
7341 if (initial_content_len == -1) {
7342 err = got_error_from_errno("asprintf");
7343 goto done;
7346 err = got_opentemp_named_fd(tagmsg_path, &fd, template, "");
7347 if (err)
7348 goto done;
7350 if (write(fd, initial_content, initial_content_len) == -1) {
7351 err = got_error_from_errno2("write", *tagmsg_path);
7352 goto done;
7355 err = get_editor(&editor);
7356 if (err)
7357 goto done;
7358 err = edit_logmsg(tagmsg, editor, *tagmsg_path, initial_content,
7359 initial_content_len, 1);
7360 done:
7361 free(initial_content);
7362 free(template);
7363 free(editor);
7365 if (fd != -1 && close(fd) == -1 && err == NULL)
7366 err = got_error_from_errno2("close", *tagmsg_path);
7368 if (err) {
7369 free(*tagmsg);
7370 *tagmsg = NULL;
7372 return err;
7375 static const struct got_error *
7376 add_tag(struct got_repository *repo, const char *tagger,
7377 const char *tag_name, const char *commit_arg, const char *tagmsg_arg,
7378 const char *signer_id, int verbosity)
7380 const struct got_error *err = NULL;
7381 struct got_object_id *commit_id = NULL, *tag_id = NULL;
7382 char *label = NULL, *commit_id_str = NULL;
7383 struct got_reference *ref = NULL;
7384 char *refname = NULL, *tagmsg = NULL;
7385 char *tagmsg_path = NULL, *tag_id_str = NULL;
7386 int preserve_tagmsg = 0;
7387 struct got_reflist_head refs;
7389 TAILQ_INIT(&refs);
7392 * Don't let the user create a tag name with a leading '-'.
7393 * While technically a valid reference name, this case is usually
7394 * an unintended typo.
7396 if (tag_name[0] == '-')
7397 return got_error_path(tag_name, GOT_ERR_REF_NAME_MINUS);
7399 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
7400 if (err)
7401 goto done;
7403 err = got_repo_match_object_id(&commit_id, &label, commit_arg,
7404 GOT_OBJ_TYPE_COMMIT, &refs, repo);
7405 if (err)
7406 goto done;
7408 err = got_object_id_str(&commit_id_str, commit_id);
7409 if (err)
7410 goto done;
7412 err = get_tag_refname(&refname, tag_name);
7413 if (err)
7414 goto done;
7415 if (strncmp("refs/tags/", tag_name, 10) == 0)
7416 tag_name += 10;
7418 err = got_ref_open(&ref, repo, refname, 0);
7419 if (err == NULL) {
7420 err = got_error(GOT_ERR_TAG_EXISTS);
7421 goto done;
7422 } else if (err->code != GOT_ERR_NOT_REF)
7423 goto done;
7425 if (tagmsg_arg == NULL) {
7426 err = get_tag_message(&tagmsg, &tagmsg_path, commit_id_str,
7427 tag_name, got_repo_get_path(repo));
7428 if (err) {
7429 if (err->code != GOT_ERR_COMMIT_MSG_EMPTY &&
7430 tagmsg_path != NULL)
7431 preserve_tagmsg = 1;
7432 goto done;
7434 /* Editor is done; we can now apply unveil(2) */
7435 err = got_sigs_apply_unveil();
7436 if (err)
7437 goto done;
7438 err = apply_unveil(got_repo_get_path(repo), 0, NULL);
7439 if (err)
7440 goto done;
7443 err = got_object_tag_create(&tag_id, tag_name, commit_id,
7444 tagger, time(NULL), tagmsg ? tagmsg : tagmsg_arg, signer_id, repo,
7445 verbosity);
7446 if (err) {
7447 if (tagmsg_path)
7448 preserve_tagmsg = 1;
7449 goto done;
7452 err = got_ref_alloc(&ref, refname, tag_id);
7453 if (err) {
7454 if (tagmsg_path)
7455 preserve_tagmsg = 1;
7456 goto done;
7459 err = got_ref_write(ref, repo);
7460 if (err) {
7461 if (tagmsg_path)
7462 preserve_tagmsg = 1;
7463 goto done;
7466 err = got_object_id_str(&tag_id_str, tag_id);
7467 if (err) {
7468 if (tagmsg_path)
7469 preserve_tagmsg = 1;
7470 goto done;
7472 printf("Created tag %s\n", tag_id_str);
7473 done:
7474 if (preserve_tagmsg) {
7475 fprintf(stderr, "%s: tag message preserved in %s\n",
7476 getprogname(), tagmsg_path);
7477 } else if (tagmsg_path && unlink(tagmsg_path) == -1 && err == NULL)
7478 err = got_error_from_errno2("unlink", tagmsg_path);
7479 free(tag_id_str);
7480 if (ref)
7481 got_ref_close(ref);
7482 free(commit_id);
7483 free(commit_id_str);
7484 free(refname);
7485 free(tagmsg);
7486 free(tagmsg_path);
7487 got_ref_list_free(&refs);
7488 return err;
7491 static const struct got_error *
7492 cmd_tag(int argc, char *argv[])
7494 const struct got_error *error = NULL;
7495 struct got_repository *repo = NULL;
7496 struct got_worktree *worktree = NULL;
7497 char *cwd = NULL, *repo_path = NULL, *commit_id_str = NULL;
7498 char *gitconfig_path = NULL, *tagger = NULL;
7499 char *allowed_signers = NULL, *revoked_signers = NULL;
7500 const char *signer_id = NULL;
7501 const char *tag_name = NULL, *commit_id_arg = NULL, *tagmsg = NULL;
7502 int ch, do_list = 0, verify_tags = 0, verbosity = 0;
7503 int *pack_fds = NULL;
7505 while ((ch = getopt(argc, argv, "c:lm:r:s:Vv")) != -1) {
7506 switch (ch) {
7507 case 'c':
7508 commit_id_arg = optarg;
7509 break;
7510 case 'l':
7511 do_list = 1;
7512 break;
7513 case 'm':
7514 tagmsg = optarg;
7515 break;
7516 case 'r':
7517 repo_path = realpath(optarg, NULL);
7518 if (repo_path == NULL) {
7519 error = got_error_from_errno2("realpath",
7520 optarg);
7521 goto done;
7523 got_path_strip_trailing_slashes(repo_path);
7524 break;
7525 case 's':
7526 signer_id = optarg;
7527 break;
7528 case 'V':
7529 verify_tags = 1;
7530 break;
7531 case 'v':
7532 if (verbosity < 0)
7533 verbosity = 0;
7534 else if (verbosity < 3)
7535 verbosity++;
7536 break;
7537 default:
7538 usage_tag();
7539 /* NOTREACHED */
7543 argc -= optind;
7544 argv += optind;
7546 if (do_list || verify_tags) {
7547 if (commit_id_arg != NULL)
7548 errx(1,
7549 "-c option can only be used when creating a tag");
7550 if (tagmsg) {
7551 if (do_list)
7552 option_conflict('l', 'm');
7553 else
7554 option_conflict('V', 'm');
7556 if (signer_id) {
7557 if (do_list)
7558 option_conflict('l', 's');
7559 else
7560 option_conflict('V', 's');
7562 if (argc > 1)
7563 usage_tag();
7564 } else if (argc != 1)
7565 usage_tag();
7567 if (argc == 1)
7568 tag_name = argv[0];
7570 #ifndef PROFILE
7571 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
7572 "sendfd unveil", NULL) == -1)
7573 err(1, "pledge");
7574 #endif
7575 cwd = getcwd(NULL, 0);
7576 if (cwd == NULL) {
7577 error = got_error_from_errno("getcwd");
7578 goto done;
7581 error = got_repo_pack_fds_open(&pack_fds);
7582 if (error != NULL)
7583 goto done;
7585 if (repo_path == NULL) {
7586 error = got_worktree_open(&worktree, cwd);
7587 if (error && error->code != GOT_ERR_NOT_WORKTREE)
7588 goto done;
7589 else
7590 error = NULL;
7591 if (worktree) {
7592 repo_path =
7593 strdup(got_worktree_get_repo_path(worktree));
7594 if (repo_path == NULL)
7595 error = got_error_from_errno("strdup");
7596 if (error)
7597 goto done;
7598 } else {
7599 repo_path = strdup(cwd);
7600 if (repo_path == NULL) {
7601 error = got_error_from_errno("strdup");
7602 goto done;
7607 if (do_list || verify_tags) {
7608 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
7609 if (error != NULL)
7610 goto done;
7611 error = get_allowed_signers(&allowed_signers, repo, worktree);
7612 if (error)
7613 goto done;
7614 error = get_revoked_signers(&revoked_signers, repo, worktree);
7615 if (error)
7616 goto done;
7617 if (worktree) {
7618 /* Release work tree lock. */
7619 got_worktree_close(worktree);
7620 worktree = NULL;
7624 * Remove "cpath" promise unless needed for signature tmpfile
7625 * creation.
7627 if (verify_tags)
7628 got_sigs_apply_unveil();
7629 else {
7630 #ifndef PROFILE
7631 if (pledge("stdio rpath wpath flock proc exec sendfd "
7632 "unveil", NULL) == -1)
7633 err(1, "pledge");
7634 #endif
7636 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
7637 if (error)
7638 goto done;
7639 error = list_tags(repo, tag_name, verify_tags, allowed_signers,
7640 revoked_signers, verbosity);
7641 } else {
7642 error = get_gitconfig_path(&gitconfig_path);
7643 if (error)
7644 goto done;
7645 error = got_repo_open(&repo, repo_path, gitconfig_path,
7646 pack_fds);
7647 if (error != NULL)
7648 goto done;
7650 error = get_author(&tagger, repo, worktree);
7651 if (error)
7652 goto done;
7653 if (signer_id == NULL)
7654 signer_id = get_signer_id(repo, worktree);
7656 if (tagmsg) {
7657 if (signer_id) {
7658 error = got_sigs_apply_unveil();
7659 if (error)
7660 goto done;
7662 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
7663 if (error)
7664 goto done;
7667 if (commit_id_arg == NULL) {
7668 struct got_reference *head_ref;
7669 struct got_object_id *commit_id;
7670 error = got_ref_open(&head_ref, repo,
7671 worktree ? got_worktree_get_head_ref_name(worktree)
7672 : GOT_REF_HEAD, 0);
7673 if (error)
7674 goto done;
7675 error = got_ref_resolve(&commit_id, repo, head_ref);
7676 got_ref_close(head_ref);
7677 if (error)
7678 goto done;
7679 error = got_object_id_str(&commit_id_str, commit_id);
7680 free(commit_id);
7681 if (error)
7682 goto done;
7685 if (worktree) {
7686 /* Release work tree lock. */
7687 got_worktree_close(worktree);
7688 worktree = NULL;
7691 error = add_tag(repo, tagger, tag_name,
7692 commit_id_str ? commit_id_str : commit_id_arg, tagmsg,
7693 signer_id, verbosity);
7695 done:
7696 if (repo) {
7697 const struct got_error *close_err = got_repo_close(repo);
7698 if (error == NULL)
7699 error = close_err;
7701 if (worktree)
7702 got_worktree_close(worktree);
7703 if (pack_fds) {
7704 const struct got_error *pack_err =
7705 got_repo_pack_fds_close(pack_fds);
7706 if (error == NULL)
7707 error = pack_err;
7709 free(cwd);
7710 free(repo_path);
7711 free(gitconfig_path);
7712 free(commit_id_str);
7713 free(tagger);
7714 free(allowed_signers);
7715 free(revoked_signers);
7716 return error;
7719 __dead static void
7720 usage_add(void)
7722 fprintf(stderr, "usage: %s add [-IR] path ...\n", getprogname());
7723 exit(1);
7726 static const struct got_error *
7727 add_progress(void *arg, unsigned char status, const char *path)
7729 while (path[0] == '/')
7730 path++;
7731 printf("%c %s\n", status, path);
7732 return NULL;
7735 static const struct got_error *
7736 cmd_add(int argc, char *argv[])
7738 const struct got_error *error = NULL;
7739 struct got_repository *repo = NULL;
7740 struct got_worktree *worktree = NULL;
7741 char *cwd = NULL;
7742 struct got_pathlist_head paths;
7743 struct got_pathlist_entry *pe;
7744 int ch, can_recurse = 0, no_ignores = 0;
7745 int *pack_fds = NULL;
7747 TAILQ_INIT(&paths);
7749 while ((ch = getopt(argc, argv, "IR")) != -1) {
7750 switch (ch) {
7751 case 'I':
7752 no_ignores = 1;
7753 break;
7754 case 'R':
7755 can_recurse = 1;
7756 break;
7757 default:
7758 usage_add();
7759 /* NOTREACHED */
7763 argc -= optind;
7764 argv += optind;
7766 #ifndef PROFILE
7767 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
7768 NULL) == -1)
7769 err(1, "pledge");
7770 #endif
7771 if (argc < 1)
7772 usage_add();
7774 cwd = getcwd(NULL, 0);
7775 if (cwd == NULL) {
7776 error = got_error_from_errno("getcwd");
7777 goto done;
7780 error = got_repo_pack_fds_open(&pack_fds);
7781 if (error != NULL)
7782 goto done;
7784 error = got_worktree_open(&worktree, cwd);
7785 if (error) {
7786 if (error->code == GOT_ERR_NOT_WORKTREE)
7787 error = wrap_not_worktree_error(error, "add", cwd);
7788 goto done;
7791 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
7792 NULL, pack_fds);
7793 if (error != NULL)
7794 goto done;
7796 error = apply_unveil(got_repo_get_path(repo), 1,
7797 got_worktree_get_root_path(worktree));
7798 if (error)
7799 goto done;
7801 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
7802 if (error)
7803 goto done;
7805 if (!can_recurse) {
7806 char *ondisk_path;
7807 struct stat sb;
7808 TAILQ_FOREACH(pe, &paths, entry) {
7809 if (asprintf(&ondisk_path, "%s/%s",
7810 got_worktree_get_root_path(worktree),
7811 pe->path) == -1) {
7812 error = got_error_from_errno("asprintf");
7813 goto done;
7815 if (lstat(ondisk_path, &sb) == -1) {
7816 if (errno == ENOENT) {
7817 free(ondisk_path);
7818 continue;
7820 error = got_error_from_errno2("lstat",
7821 ondisk_path);
7822 free(ondisk_path);
7823 goto done;
7825 free(ondisk_path);
7826 if (S_ISDIR(sb.st_mode)) {
7827 error = got_error_msg(GOT_ERR_BAD_PATH,
7828 "adding directories requires -R option");
7829 goto done;
7834 error = got_worktree_schedule_add(worktree, &paths, add_progress,
7835 NULL, repo, no_ignores);
7836 done:
7837 if (repo) {
7838 const struct got_error *close_err = got_repo_close(repo);
7839 if (error == NULL)
7840 error = close_err;
7842 if (worktree)
7843 got_worktree_close(worktree);
7844 if (pack_fds) {
7845 const struct got_error *pack_err =
7846 got_repo_pack_fds_close(pack_fds);
7847 if (error == NULL)
7848 error = pack_err;
7850 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
7851 free(cwd);
7852 return error;
7855 __dead static void
7856 usage_remove(void)
7858 fprintf(stderr, "usage: %s remove [-fkR] [-s status-codes] path ...\n",
7859 getprogname());
7860 exit(1);
7863 static const struct got_error *
7864 print_remove_status(void *arg, unsigned char status,
7865 unsigned char staged_status, const char *path)
7867 while (path[0] == '/')
7868 path++;
7869 if (status == GOT_STATUS_NONEXISTENT)
7870 return NULL;
7871 if (status == staged_status && (status == GOT_STATUS_DELETE))
7872 status = GOT_STATUS_NO_CHANGE;
7873 printf("%c%c %s\n", status, staged_status, path);
7874 return NULL;
7877 static const struct got_error *
7878 cmd_remove(int argc, char *argv[])
7880 const struct got_error *error = NULL;
7881 struct got_worktree *worktree = NULL;
7882 struct got_repository *repo = NULL;
7883 const char *status_codes = NULL;
7884 char *cwd = NULL;
7885 struct got_pathlist_head paths;
7886 struct got_pathlist_entry *pe;
7887 int ch, delete_local_mods = 0, can_recurse = 0, keep_on_disk = 0, i;
7888 int ignore_missing_paths = 0;
7889 int *pack_fds = NULL;
7891 TAILQ_INIT(&paths);
7893 while ((ch = getopt(argc, argv, "fkRs:")) != -1) {
7894 switch (ch) {
7895 case 'f':
7896 delete_local_mods = 1;
7897 ignore_missing_paths = 1;
7898 break;
7899 case 'k':
7900 keep_on_disk = 1;
7901 break;
7902 case 'R':
7903 can_recurse = 1;
7904 break;
7905 case 's':
7906 for (i = 0; i < strlen(optarg); i++) {
7907 switch (optarg[i]) {
7908 case GOT_STATUS_MODIFY:
7909 delete_local_mods = 1;
7910 break;
7911 case GOT_STATUS_MISSING:
7912 ignore_missing_paths = 1;
7913 break;
7914 default:
7915 errx(1, "invalid status code '%c'",
7916 optarg[i]);
7919 status_codes = optarg;
7920 break;
7921 default:
7922 usage_remove();
7923 /* NOTREACHED */
7927 argc -= optind;
7928 argv += optind;
7930 #ifndef PROFILE
7931 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
7932 NULL) == -1)
7933 err(1, "pledge");
7934 #endif
7935 if (argc < 1)
7936 usage_remove();
7938 cwd = getcwd(NULL, 0);
7939 if (cwd == NULL) {
7940 error = got_error_from_errno("getcwd");
7941 goto done;
7944 error = got_repo_pack_fds_open(&pack_fds);
7945 if (error != NULL)
7946 goto done;
7948 error = got_worktree_open(&worktree, cwd);
7949 if (error) {
7950 if (error->code == GOT_ERR_NOT_WORKTREE)
7951 error = wrap_not_worktree_error(error, "remove", cwd);
7952 goto done;
7955 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
7956 NULL, pack_fds);
7957 if (error)
7958 goto done;
7960 error = apply_unveil(got_repo_get_path(repo), 1,
7961 got_worktree_get_root_path(worktree));
7962 if (error)
7963 goto done;
7965 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
7966 if (error)
7967 goto done;
7969 if (!can_recurse) {
7970 char *ondisk_path;
7971 struct stat sb;
7972 TAILQ_FOREACH(pe, &paths, entry) {
7973 if (asprintf(&ondisk_path, "%s/%s",
7974 got_worktree_get_root_path(worktree),
7975 pe->path) == -1) {
7976 error = got_error_from_errno("asprintf");
7977 goto done;
7979 if (lstat(ondisk_path, &sb) == -1) {
7980 if (errno == ENOENT) {
7981 free(ondisk_path);
7982 continue;
7984 error = got_error_from_errno2("lstat",
7985 ondisk_path);
7986 free(ondisk_path);
7987 goto done;
7989 free(ondisk_path);
7990 if (S_ISDIR(sb.st_mode)) {
7991 error = got_error_msg(GOT_ERR_BAD_PATH,
7992 "removing directories requires -R option");
7993 goto done;
7998 error = got_worktree_schedule_delete(worktree, &paths,
7999 delete_local_mods, status_codes, print_remove_status, NULL,
8000 repo, keep_on_disk, ignore_missing_paths);
8001 done:
8002 if (repo) {
8003 const struct got_error *close_err = got_repo_close(repo);
8004 if (error == NULL)
8005 error = close_err;
8007 if (worktree)
8008 got_worktree_close(worktree);
8009 if (pack_fds) {
8010 const struct got_error *pack_err =
8011 got_repo_pack_fds_close(pack_fds);
8012 if (error == NULL)
8013 error = pack_err;
8015 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
8016 free(cwd);
8017 return error;
8020 __dead static void
8021 usage_patch(void)
8023 fprintf(stderr, "usage: %s patch [-nR] [-c commit] [-p strip-count] "
8024 "[patchfile]\n", getprogname());
8025 exit(1);
8028 static const struct got_error *
8029 patch_from_stdin(int *patchfd)
8031 const struct got_error *err = NULL;
8032 ssize_t r;
8033 char buf[BUFSIZ];
8034 sig_t sighup, sigint, sigquit;
8036 *patchfd = got_opentempfd();
8037 if (*patchfd == -1)
8038 return got_error_from_errno("got_opentempfd");
8040 sighup = signal(SIGHUP, SIG_DFL);
8041 sigint = signal(SIGINT, SIG_DFL);
8042 sigquit = signal(SIGQUIT, SIG_DFL);
8044 for (;;) {
8045 r = read(0, buf, sizeof(buf));
8046 if (r == -1) {
8047 err = got_error_from_errno("read");
8048 break;
8050 if (r == 0)
8051 break;
8052 if (write(*patchfd, buf, r) == -1) {
8053 err = got_error_from_errno("write");
8054 break;
8058 signal(SIGHUP, sighup);
8059 signal(SIGINT, sigint);
8060 signal(SIGQUIT, sigquit);
8062 if (err == NULL && lseek(*patchfd, 0, SEEK_SET) == -1)
8063 err = got_error_from_errno("lseek");
8065 if (err != NULL) {
8066 close(*patchfd);
8067 *patchfd = -1;
8070 return err;
8073 static const struct got_error *
8074 patch_progress(void *arg, const char *old, const char *new,
8075 unsigned char status, const struct got_error *error, int old_from,
8076 int old_lines, int new_from, int new_lines, int offset,
8077 int ws_mangled, const struct got_error *hunk_err)
8079 const char *path = new == NULL ? old : new;
8081 while (*path == '/')
8082 path++;
8084 if (status != 0)
8085 printf("%c %s\n", status, path);
8087 if (error != NULL)
8088 fprintf(stderr, "%s: %s\n", getprogname(), error->msg);
8090 if (offset != 0 || hunk_err != NULL || ws_mangled) {
8091 printf("@@ -%d,%d +%d,%d @@ ", old_from,
8092 old_lines, new_from, new_lines);
8093 if (hunk_err != NULL)
8094 printf("%s\n", hunk_err->msg);
8095 else if (offset != 0)
8096 printf("applied with offset %d\n", offset);
8097 else
8098 printf("hunk contains mangled whitespace\n");
8101 return NULL;
8104 static const struct got_error *
8105 cmd_patch(int argc, char *argv[])
8107 const struct got_error *error = NULL, *close_error = NULL;
8108 struct got_worktree *worktree = NULL;
8109 struct got_repository *repo = NULL;
8110 struct got_reflist_head refs;
8111 struct got_object_id *commit_id = NULL;
8112 const char *commit_id_str = NULL;
8113 struct stat sb;
8114 const char *errstr;
8115 char *cwd = NULL;
8116 int ch, nop = 0, strip = -1, reverse = 0;
8117 int patchfd;
8118 int *pack_fds = NULL;
8120 TAILQ_INIT(&refs);
8122 #ifndef PROFILE
8123 if (pledge("stdio rpath wpath cpath fattr proc exec sendfd flock "
8124 "unveil", NULL) == -1)
8125 err(1, "pledge");
8126 #endif
8128 while ((ch = getopt(argc, argv, "c:np:R")) != -1) {
8129 switch (ch) {
8130 case 'c':
8131 commit_id_str = optarg;
8132 break;
8133 case 'n':
8134 nop = 1;
8135 break;
8136 case 'p':
8137 strip = strtonum(optarg, 0, INT_MAX, &errstr);
8138 if (errstr != NULL)
8139 errx(1, "pathname strip count is %s: %s",
8140 errstr, optarg);
8141 break;
8142 case 'R':
8143 reverse = 1;
8144 break;
8145 default:
8146 usage_patch();
8147 /* NOTREACHED */
8151 argc -= optind;
8152 argv += optind;
8154 if (argc == 0) {
8155 error = patch_from_stdin(&patchfd);
8156 if (error)
8157 return error;
8158 } else if (argc == 1) {
8159 patchfd = open(argv[0], O_RDONLY);
8160 if (patchfd == -1) {
8161 error = got_error_from_errno2("open", argv[0]);
8162 return error;
8164 if (fstat(patchfd, &sb) == -1) {
8165 error = got_error_from_errno2("fstat", argv[0]);
8166 goto done;
8168 if (!S_ISREG(sb.st_mode)) {
8169 error = got_error_path(argv[0], GOT_ERR_BAD_FILETYPE);
8170 goto done;
8172 } else
8173 usage_patch();
8175 if ((cwd = getcwd(NULL, 0)) == NULL) {
8176 error = got_error_from_errno("getcwd");
8177 goto done;
8180 error = got_repo_pack_fds_open(&pack_fds);
8181 if (error != NULL)
8182 goto done;
8184 error = got_worktree_open(&worktree, cwd);
8185 if (error != NULL)
8186 goto done;
8188 const char *repo_path = got_worktree_get_repo_path(worktree);
8189 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
8190 if (error != NULL)
8191 goto done;
8193 error = apply_unveil(got_repo_get_path(repo), 0,
8194 got_worktree_get_root_path(worktree));
8195 if (error != NULL)
8196 goto done;
8198 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
8199 if (error)
8200 goto done;
8202 if (commit_id_str != NULL) {
8203 error = got_repo_match_object_id(&commit_id, NULL,
8204 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
8205 if (error)
8206 goto done;
8209 error = got_patch(patchfd, worktree, repo, nop, strip, reverse,
8210 commit_id, &patch_progress, NULL, check_cancelled, NULL);
8212 done:
8213 got_ref_list_free(&refs);
8214 free(commit_id);
8215 if (repo) {
8216 close_error = got_repo_close(repo);
8217 if (error == NULL)
8218 error = close_error;
8220 if (worktree != NULL) {
8221 close_error = got_worktree_close(worktree);
8222 if (error == NULL)
8223 error = close_error;
8225 if (pack_fds) {
8226 const struct got_error *pack_err =
8227 got_repo_pack_fds_close(pack_fds);
8228 if (error == NULL)
8229 error = pack_err;
8231 free(cwd);
8232 return error;
8235 __dead static void
8236 usage_revert(void)
8238 fprintf(stderr, "usage: %s revert [-pR] [-F response-script] path ...\n",
8239 getprogname());
8240 exit(1);
8243 static const struct got_error *
8244 revert_progress(void *arg, unsigned char status, const char *path)
8246 if (status == GOT_STATUS_UNVERSIONED)
8247 return NULL;
8249 while (path[0] == '/')
8250 path++;
8251 printf("%c %s\n", status, path);
8252 return NULL;
8255 struct choose_patch_arg {
8256 FILE *patch_script_file;
8257 const char *action;
8260 static const struct got_error *
8261 show_change(unsigned char status, const char *path, FILE *patch_file, int n,
8262 int nchanges, const char *action)
8264 const struct got_error *err;
8265 char *line = NULL;
8266 size_t linesize = 0;
8267 ssize_t linelen;
8269 switch (status) {
8270 case GOT_STATUS_ADD:
8271 printf("A %s\n%s this addition? [y/n] ", path, action);
8272 break;
8273 case GOT_STATUS_DELETE:
8274 printf("D %s\n%s this deletion? [y/n] ", path, action);
8275 break;
8276 case GOT_STATUS_MODIFY:
8277 if (fseek(patch_file, 0L, SEEK_SET) == -1)
8278 return got_error_from_errno("fseek");
8279 printf(GOT_COMMIT_SEP_STR);
8280 while ((linelen = getline(&line, &linesize, patch_file)) != -1)
8281 printf("%s", line);
8282 if (linelen == -1 && ferror(patch_file)) {
8283 err = got_error_from_errno("getline");
8284 free(line);
8285 return err;
8287 free(line);
8288 printf(GOT_COMMIT_SEP_STR);
8289 printf("M %s (change %d of %d)\n%s this change? [y/n/q] ",
8290 path, n, nchanges, action);
8291 break;
8292 default:
8293 return got_error_path(path, GOT_ERR_FILE_STATUS);
8296 fflush(stdout);
8297 return NULL;
8300 static const struct got_error *
8301 choose_patch(int *choice, void *arg, unsigned char status, const char *path,
8302 FILE *patch_file, int n, int nchanges)
8304 const struct got_error *err = NULL;
8305 char *line = NULL;
8306 size_t linesize = 0;
8307 ssize_t linelen;
8308 int resp = ' ';
8309 struct choose_patch_arg *a = arg;
8311 *choice = GOT_PATCH_CHOICE_NONE;
8313 if (a->patch_script_file) {
8314 char *nl;
8315 err = show_change(status, path, patch_file, n, nchanges,
8316 a->action);
8317 if (err)
8318 return err;
8319 linelen = getline(&line, &linesize, a->patch_script_file);
8320 if (linelen == -1) {
8321 if (ferror(a->patch_script_file))
8322 return got_error_from_errno("getline");
8323 return NULL;
8325 nl = strchr(line, '\n');
8326 if (nl)
8327 *nl = '\0';
8328 if (strcmp(line, "y") == 0) {
8329 *choice = GOT_PATCH_CHOICE_YES;
8330 printf("y\n");
8331 } else if (strcmp(line, "n") == 0) {
8332 *choice = GOT_PATCH_CHOICE_NO;
8333 printf("n\n");
8334 } else if (strcmp(line, "q") == 0 &&
8335 status == GOT_STATUS_MODIFY) {
8336 *choice = GOT_PATCH_CHOICE_QUIT;
8337 printf("q\n");
8338 } else
8339 printf("invalid response '%s'\n", line);
8340 free(line);
8341 return NULL;
8344 while (resp != 'y' && resp != 'n' && resp != 'q') {
8345 err = show_change(status, path, patch_file, n, nchanges,
8346 a->action);
8347 if (err)
8348 return err;
8349 resp = getchar();
8350 if (resp == '\n')
8351 resp = getchar();
8352 if (status == GOT_STATUS_MODIFY) {
8353 if (resp != 'y' && resp != 'n' && resp != 'q') {
8354 printf("invalid response '%c'\n", resp);
8355 resp = ' ';
8357 } else if (resp != 'y' && resp != 'n') {
8358 printf("invalid response '%c'\n", resp);
8359 resp = ' ';
8363 if (resp == 'y')
8364 *choice = GOT_PATCH_CHOICE_YES;
8365 else if (resp == 'n')
8366 *choice = GOT_PATCH_CHOICE_NO;
8367 else if (resp == 'q' && status == GOT_STATUS_MODIFY)
8368 *choice = GOT_PATCH_CHOICE_QUIT;
8370 return NULL;
8373 struct wt_commitable_path_arg {
8374 struct got_pathlist_head *commit_paths;
8375 int *has_changes;
8379 * Shortcut work tree status callback to determine if the set of paths scanned
8380 * has at least one versioned path that is being modified and, if not NULL, is
8381 * in the arg->commit_paths list. Set arg and return GOT_ERR_FILE_MODIFIED as
8382 * soon as a path is passed with a status that satisfies this criteria.
8384 static const struct got_error *
8385 worktree_has_commitable_path(void *arg, unsigned char status,
8386 unsigned char staged_status, const char *path,
8387 struct got_object_id *blob_id, struct got_object_id *staged_blob_id,
8388 struct got_object_id *commit_id, int dirfd, const char *de_name)
8390 struct wt_commitable_path_arg *a = arg;
8392 if (status == staged_status && (status == GOT_STATUS_DELETE))
8393 status = GOT_STATUS_NO_CHANGE;
8395 if (!(status == GOT_STATUS_NO_CHANGE ||
8396 status == GOT_STATUS_UNVERSIONED) ||
8397 staged_status != GOT_STATUS_NO_CHANGE) {
8398 if (a->commit_paths != NULL) {
8399 struct got_pathlist_entry *pe;
8401 TAILQ_FOREACH(pe, a->commit_paths, entry) {
8402 if (strncmp(path, pe->path,
8403 pe->path_len) == 0) {
8404 *a->has_changes = 1;
8405 break;
8408 } else
8409 *a->has_changes = 1;
8411 if (*a->has_changes)
8412 return got_error(GOT_ERR_FILE_MODIFIED);
8415 return NULL;
8419 * Check that the changeset of the commit identified by id is
8420 * comprised of at least one modified path that is being committed.
8422 static const struct got_error *
8423 commit_path_changed_in_worktree(struct wt_commitable_path_arg *wcpa,
8424 struct got_object_id *id, struct got_worktree *worktree,
8425 struct got_repository *repo)
8427 const struct got_error *err;
8428 struct got_pathlist_head paths;
8429 struct got_commit_object *commit = NULL, *pcommit = NULL;
8430 struct got_tree_object *tree = NULL, *ptree = NULL;
8431 struct got_object_qid *pid;
8433 TAILQ_INIT(&paths);
8435 err = got_object_open_as_commit(&commit, repo, id);
8436 if (err)
8437 goto done;
8439 err = got_object_open_as_tree(&tree, repo,
8440 got_object_commit_get_tree_id(commit));
8441 if (err)
8442 goto done;
8444 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
8445 if (pid != NULL) {
8446 err = got_object_open_as_commit(&pcommit, repo, &pid->id);
8447 if (err)
8448 goto done;
8450 err = got_object_open_as_tree(&ptree, repo,
8451 got_object_commit_get_tree_id(pcommit));
8452 if (err)
8453 goto done;
8456 err = got_diff_tree(ptree, tree, NULL, NULL, -1, -1, "", "", repo,
8457 got_diff_tree_collect_changed_paths, &paths, 0);
8458 if (err)
8459 goto done;
8461 err = got_worktree_status(worktree, &paths, repo, 0,
8462 worktree_has_commitable_path, wcpa, check_cancelled, NULL);
8463 if (err && err->code == GOT_ERR_FILE_MODIFIED) {
8465 * At least one changed path in the referenced commit is
8466 * modified in the work tree, that's all we need to know!
8468 err = NULL;
8471 done:
8472 got_pathlist_free(&paths, GOT_PATHLIST_FREE_ALL);
8473 if (commit)
8474 got_object_commit_close(commit);
8475 if (pcommit)
8476 got_object_commit_close(pcommit);
8477 if (tree)
8478 got_object_tree_close(tree);
8479 if (ptree)
8480 got_object_tree_close(ptree);
8481 return err;
8485 * Remove any "logmsg" reference comprised entirely of paths that have
8486 * been reverted in this work tree. If any path in the logmsg ref changeset
8487 * remains in a changed state in the worktree, do not remove the reference.
8489 static const struct got_error *
8490 rm_logmsg_ref(struct got_worktree *worktree, struct got_repository *repo)
8492 const struct got_error *err;
8493 struct got_reflist_head refs;
8494 struct got_reflist_entry *re;
8495 struct got_commit_object *commit = NULL;
8496 struct got_object_id *commit_id = NULL;
8497 struct wt_commitable_path_arg wcpa;
8498 char *uuidstr = NULL;
8500 TAILQ_INIT(&refs);
8502 err = got_worktree_get_uuid(&uuidstr, worktree);
8503 if (err)
8504 goto done;
8506 err = got_ref_list(&refs, repo, "refs/got/worktree",
8507 got_ref_cmp_by_name, repo);
8508 if (err)
8509 goto done;
8511 TAILQ_FOREACH(re, &refs, entry) {
8512 const char *refname;
8513 int has_changes = 0;
8515 refname = got_ref_get_name(re->ref);
8517 if (!strncmp(refname, GOT_WORKTREE_CHERRYPICK_REF_PREFIX,
8518 GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN))
8519 refname += GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN + 1;
8520 else if (!strncmp(refname, GOT_WORKTREE_BACKOUT_REF_PREFIX,
8521 GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN))
8522 refname += GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN + 1;
8523 else
8524 continue;
8526 if (strncmp(refname, uuidstr, GOT_WORKTREE_UUID_STRLEN) == 0)
8527 refname += GOT_WORKTREE_UUID_STRLEN + 1; /* skip '-' */
8528 else
8529 continue;
8531 err = got_repo_match_object_id(&commit_id, NULL, refname,
8532 GOT_OBJ_TYPE_COMMIT, NULL, repo);
8533 if (err)
8534 goto done;
8536 err = got_object_open_as_commit(&commit, repo, commit_id);
8537 if (err)
8538 goto done;
8540 wcpa.commit_paths = NULL;
8541 wcpa.has_changes = &has_changes;
8543 err = commit_path_changed_in_worktree(&wcpa, commit_id,
8544 worktree, repo);
8545 if (err)
8546 goto done;
8548 if (!has_changes) {
8549 err = got_ref_delete(re->ref, repo);
8550 if (err)
8551 goto done;
8554 got_object_commit_close(commit);
8555 commit = NULL;
8556 free(commit_id);
8557 commit_id = NULL;
8560 done:
8561 free(uuidstr);
8562 free(commit_id);
8563 got_ref_list_free(&refs);
8564 if (commit)
8565 got_object_commit_close(commit);
8566 return err;
8569 static const struct got_error *
8570 cmd_revert(int argc, char *argv[])
8572 const struct got_error *error = NULL;
8573 struct got_worktree *worktree = NULL;
8574 struct got_repository *repo = NULL;
8575 char *cwd = NULL, *path = NULL;
8576 struct got_pathlist_head paths;
8577 struct got_pathlist_entry *pe;
8578 int ch, can_recurse = 0, pflag = 0;
8579 FILE *patch_script_file = NULL;
8580 const char *patch_script_path = NULL;
8581 struct choose_patch_arg cpa;
8582 int *pack_fds = NULL;
8584 TAILQ_INIT(&paths);
8586 while ((ch = getopt(argc, argv, "F:pR")) != -1) {
8587 switch (ch) {
8588 case 'F':
8589 patch_script_path = optarg;
8590 break;
8591 case 'p':
8592 pflag = 1;
8593 break;
8594 case 'R':
8595 can_recurse = 1;
8596 break;
8597 default:
8598 usage_revert();
8599 /* NOTREACHED */
8603 argc -= optind;
8604 argv += optind;
8606 #ifndef PROFILE
8607 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
8608 "unveil", NULL) == -1)
8609 err(1, "pledge");
8610 #endif
8611 if (argc < 1)
8612 usage_revert();
8613 if (patch_script_path && !pflag)
8614 errx(1, "-F option can only be used together with -p option");
8616 cwd = getcwd(NULL, 0);
8617 if (cwd == NULL) {
8618 error = got_error_from_errno("getcwd");
8619 goto done;
8622 error = got_repo_pack_fds_open(&pack_fds);
8623 if (error != NULL)
8624 goto done;
8626 error = got_worktree_open(&worktree, cwd);
8627 if (error) {
8628 if (error->code == GOT_ERR_NOT_WORKTREE)
8629 error = wrap_not_worktree_error(error, "revert", cwd);
8630 goto done;
8633 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
8634 NULL, pack_fds);
8635 if (error != NULL)
8636 goto done;
8638 if (patch_script_path) {
8639 patch_script_file = fopen(patch_script_path, "re");
8640 if (patch_script_file == NULL) {
8641 error = got_error_from_errno2("fopen",
8642 patch_script_path);
8643 goto done;
8648 * XXX "c" perm needed on repo dir to delete merge references.
8650 error = apply_unveil(got_repo_get_path(repo), 0,
8651 got_worktree_get_root_path(worktree));
8652 if (error)
8653 goto done;
8655 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
8656 if (error)
8657 goto done;
8659 if (!can_recurse) {
8660 char *ondisk_path;
8661 struct stat sb;
8662 TAILQ_FOREACH(pe, &paths, entry) {
8663 if (asprintf(&ondisk_path, "%s/%s",
8664 got_worktree_get_root_path(worktree),
8665 pe->path) == -1) {
8666 error = got_error_from_errno("asprintf");
8667 goto done;
8669 if (lstat(ondisk_path, &sb) == -1) {
8670 if (errno == ENOENT) {
8671 free(ondisk_path);
8672 continue;
8674 error = got_error_from_errno2("lstat",
8675 ondisk_path);
8676 free(ondisk_path);
8677 goto done;
8679 free(ondisk_path);
8680 if (S_ISDIR(sb.st_mode)) {
8681 error = got_error_msg(GOT_ERR_BAD_PATH,
8682 "reverting directories requires -R option");
8683 goto done;
8688 cpa.patch_script_file = patch_script_file;
8689 cpa.action = "revert";
8690 error = got_worktree_revert(worktree, &paths, revert_progress, NULL,
8691 pflag ? choose_patch : NULL, &cpa, repo);
8693 error = rm_logmsg_ref(worktree, repo);
8694 done:
8695 if (patch_script_file && fclose(patch_script_file) == EOF &&
8696 error == NULL)
8697 error = got_error_from_errno2("fclose", patch_script_path);
8698 if (repo) {
8699 const struct got_error *close_err = got_repo_close(repo);
8700 if (error == NULL)
8701 error = close_err;
8703 if (worktree)
8704 got_worktree_close(worktree);
8705 if (pack_fds) {
8706 const struct got_error *pack_err =
8707 got_repo_pack_fds_close(pack_fds);
8708 if (error == NULL)
8709 error = pack_err;
8711 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
8712 free(path);
8713 free(cwd);
8714 return error;
8717 __dead static void
8718 usage_commit(void)
8720 fprintf(stderr, "usage: %s commit [-NS] [-A author] [-F path] "
8721 "[-m message] [path ...]\n", getprogname());
8722 exit(1);
8725 struct collect_commit_logmsg_arg {
8726 const char *cmdline_log;
8727 const char *prepared_log;
8728 const char *merged_log;
8729 int non_interactive;
8730 const char *editor;
8731 const char *worktree_path;
8732 const char *branch_name;
8733 const char *repo_path;
8734 char *logmsg_path;
8738 static const struct got_error *
8739 read_prepared_logmsg(char **logmsg, const char *path)
8741 const struct got_error *err = NULL;
8742 FILE *f = NULL;
8743 struct stat sb;
8744 size_t r;
8746 *logmsg = NULL;
8747 memset(&sb, 0, sizeof(sb));
8749 f = fopen(path, "re");
8750 if (f == NULL)
8751 return got_error_from_errno2("fopen", path);
8753 if (fstat(fileno(f), &sb) == -1) {
8754 err = got_error_from_errno2("fstat", path);
8755 goto done;
8757 if (sb.st_size == 0) {
8758 err = got_error(GOT_ERR_COMMIT_MSG_EMPTY);
8759 goto done;
8762 *logmsg = malloc(sb.st_size + 1);
8763 if (*logmsg == NULL) {
8764 err = got_error_from_errno("malloc");
8765 goto done;
8768 r = fread(*logmsg, 1, sb.st_size, f);
8769 if (r != sb.st_size) {
8770 if (ferror(f))
8771 err = got_error_from_errno2("fread", path);
8772 else
8773 err = got_error(GOT_ERR_IO);
8774 goto done;
8776 (*logmsg)[sb.st_size] = '\0';
8777 done:
8778 if (fclose(f) == EOF && err == NULL)
8779 err = got_error_from_errno2("fclose", path);
8780 if (err) {
8781 free(*logmsg);
8782 *logmsg = NULL;
8784 return err;
8787 static const struct got_error *
8788 collect_commit_logmsg(struct got_pathlist_head *commitable_paths,
8789 const char *diff_path, char **logmsg, void *arg)
8791 char *initial_content = NULL;
8792 struct got_pathlist_entry *pe;
8793 const struct got_error *err = NULL;
8794 char *template = NULL;
8795 char *prepared_msg = NULL, *merged_msg = NULL;
8796 struct collect_commit_logmsg_arg *a = arg;
8797 int initial_content_len;
8798 int fd = -1;
8799 size_t len;
8801 /* if a message was specified on the command line, just use it */
8802 if (a->cmdline_log != NULL && strlen(a->cmdline_log) != 0) {
8803 len = strlen(a->cmdline_log) + 1;
8804 *logmsg = malloc(len + 1);
8805 if (*logmsg == NULL)
8806 return got_error_from_errno("malloc");
8807 strlcpy(*logmsg, a->cmdline_log, len);
8808 return NULL;
8809 } else if (a->prepared_log != NULL && a->non_interactive)
8810 return read_prepared_logmsg(logmsg, a->prepared_log);
8812 if (asprintf(&template, "%s/logmsg", a->worktree_path) == -1)
8813 return got_error_from_errno("asprintf");
8815 err = got_opentemp_named_fd(&a->logmsg_path, &fd, template, "");
8816 if (err)
8817 goto done;
8819 if (a->prepared_log) {
8820 err = read_prepared_logmsg(&prepared_msg, a->prepared_log);
8821 if (err)
8822 goto done;
8823 } else if (a->merged_log) {
8824 err = read_prepared_logmsg(&merged_msg, a->merged_log);
8825 if (err)
8826 goto done;
8829 initial_content_len = asprintf(&initial_content,
8830 "%s%s\n# changes to be committed on branch %s:\n",
8831 prepared_msg ? prepared_msg : "",
8832 merged_msg ? merged_msg : "", a->branch_name);
8833 if (initial_content_len == -1) {
8834 err = got_error_from_errno("asprintf");
8835 goto done;
8838 if (write(fd, initial_content, initial_content_len) == -1) {
8839 err = got_error_from_errno2("write", a->logmsg_path);
8840 goto done;
8843 TAILQ_FOREACH(pe, commitable_paths, entry) {
8844 struct got_commitable *ct = pe->data;
8845 dprintf(fd, "# %c %s\n",
8846 got_commitable_get_status(ct),
8847 got_commitable_get_path(ct));
8850 if (diff_path) {
8851 dprintf(fd, "# detailed changes can be viewed in %s\n",
8852 diff_path);
8855 err = edit_logmsg(logmsg, a->editor, a->logmsg_path, initial_content,
8856 initial_content_len, a->prepared_log ? 0 : 1);
8857 done:
8858 free(initial_content);
8859 free(template);
8860 free(prepared_msg);
8861 free(merged_msg);
8863 if (fd != -1 && close(fd) == -1 && err == NULL)
8864 err = got_error_from_errno2("close", a->logmsg_path);
8866 /* Editor is done; we can now apply unveil(2) */
8867 if (err == NULL)
8868 err = apply_unveil(a->repo_path, 0, a->worktree_path);
8869 if (err) {
8870 free(*logmsg);
8871 *logmsg = NULL;
8873 return err;
8876 static const struct got_error *
8877 cat_logmsg(FILE *f, struct got_commit_object *commit, const char *idstr,
8878 const char *type, int has_content)
8880 const struct got_error *err = NULL;
8881 char *logmsg = NULL;
8883 err = got_object_commit_get_logmsg(&logmsg, commit);
8884 if (err)
8885 return err;
8887 if (fprintf(f, "%s# log message of %s commit %s:%s",
8888 has_content ? "\n" : "", type, idstr, logmsg) < 0)
8889 err = got_ferror(f, GOT_ERR_IO);
8891 free(logmsg);
8892 return err;
8896 * Lookup "logmsg" references of backed-out and cherrypicked commits
8897 * belonging to the current work tree. If found, and the worktree has
8898 * at least one modified file that was changed in the referenced commit,
8899 * add its log message to a new temporary file at *logmsg_path.
8900 * Add all refs found to matched_refs to be scheduled for removal on
8901 * successful commit.
8903 static const struct got_error *
8904 lookup_logmsg_ref(char **logmsg_path, struct got_pathlist_head *paths,
8905 struct got_reflist_head *matched_refs, struct got_worktree *worktree,
8906 struct got_repository *repo)
8908 const struct got_error *err;
8909 struct got_commit_object *commit = NULL;
8910 struct got_object_id *id = NULL;
8911 struct got_reflist_head refs;
8912 struct got_reflist_entry *re, *re_match;
8913 FILE *f = NULL;
8914 char *uuidstr = NULL;
8915 int added_logmsg = 0;
8917 TAILQ_INIT(&refs);
8919 *logmsg_path = NULL;
8921 err = got_worktree_get_uuid(&uuidstr, worktree);
8922 if (err)
8923 goto done;
8925 err = got_ref_list(&refs, repo, "refs/got/worktree",
8926 got_ref_cmp_by_name, repo);
8927 if (err)
8928 goto done;
8930 TAILQ_FOREACH(re, &refs, entry) {
8931 const char *refname, *type;
8932 struct wt_commitable_path_arg wcpa;
8933 int add_logmsg = 0;
8935 refname = got_ref_get_name(re->ref);
8937 if (strncmp(refname, GOT_WORKTREE_CHERRYPICK_REF_PREFIX,
8938 GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN) == 0) {
8939 refname += GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN + 1;
8940 type = "cherrypicked";
8941 } else if (strncmp(refname, GOT_WORKTREE_BACKOUT_REF_PREFIX,
8942 GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN) == 0) {
8943 refname += GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN + 1;
8944 type = "backed-out";
8945 } else
8946 continue;
8948 if (strncmp(refname, uuidstr, GOT_WORKTREE_UUID_STRLEN) == 0)
8949 refname += GOT_WORKTREE_UUID_STRLEN + 1; /* skip '-' */
8950 else
8951 continue;
8953 err = got_repo_match_object_id(&id, NULL, refname,
8954 GOT_OBJ_TYPE_COMMIT, NULL, repo);
8955 if (err)
8956 goto done;
8958 err = got_object_open_as_commit(&commit, repo, id);
8959 if (err)
8960 goto done;
8962 wcpa.commit_paths = paths;
8963 wcpa.has_changes = &add_logmsg;
8965 err = commit_path_changed_in_worktree(&wcpa, id,
8966 worktree, repo);
8967 if (err)
8968 goto done;
8970 if (add_logmsg) {
8971 if (f == NULL) {
8972 err = got_opentemp_named(logmsg_path, &f,
8973 "got-commit-logmsg", "");
8974 if (err)
8975 goto done;
8977 err = cat_logmsg(f, commit, refname, type,
8978 added_logmsg);
8979 if (err)
8980 goto done;
8981 if (!added_logmsg)
8982 ++added_logmsg;
8984 err = got_reflist_entry_dup(&re_match, re);
8985 if (err)
8986 goto done;
8987 TAILQ_INSERT_HEAD(matched_refs, re_match, entry);
8990 got_object_commit_close(commit);
8991 commit = NULL;
8992 free(id);
8993 id = NULL;
8996 done:
8997 free(id);
8998 free(uuidstr);
8999 got_ref_list_free(&refs);
9000 if (commit)
9001 got_object_commit_close(commit);
9002 if (f && fclose(f) == EOF && err == NULL)
9003 err = got_error_from_errno("fclose");
9004 if (!added_logmsg) {
9005 if (*logmsg_path && unlink(*logmsg_path) != 0 && err == NULL)
9006 err = got_error_from_errno2("unlink", *logmsg_path);
9007 *logmsg_path = NULL;
9009 return err;
9012 static const struct got_error *
9013 cmd_commit(int argc, char *argv[])
9015 const struct got_error *error = NULL;
9016 struct got_worktree *worktree = NULL;
9017 struct got_repository *repo = NULL;
9018 char *cwd = NULL, *id_str = NULL;
9019 struct got_object_id *id = NULL;
9020 const char *logmsg = NULL;
9021 char *prepared_logmsg = NULL, *merged_logmsg = NULL;
9022 struct collect_commit_logmsg_arg cl_arg;
9023 const char *author = NULL;
9024 char *gitconfig_path = NULL, *editor = NULL, *committer = NULL;
9025 int ch, rebase_in_progress, histedit_in_progress, preserve_logmsg = 0;
9026 int allow_bad_symlinks = 0, non_interactive = 0, merge_in_progress = 0;
9027 int show_diff = 1;
9028 struct got_pathlist_head paths;
9029 struct got_reflist_head refs;
9030 struct got_reflist_entry *re;
9031 int *pack_fds = NULL;
9033 TAILQ_INIT(&refs);
9034 TAILQ_INIT(&paths);
9035 cl_arg.logmsg_path = NULL;
9037 while ((ch = getopt(argc, argv, "A:F:m:NnS")) != -1) {
9038 switch (ch) {
9039 case 'A':
9040 author = optarg;
9041 error = valid_author(author);
9042 if (error)
9043 return error;
9044 break;
9045 case 'F':
9046 if (logmsg != NULL)
9047 option_conflict('F', 'm');
9048 prepared_logmsg = realpath(optarg, NULL);
9049 if (prepared_logmsg == NULL)
9050 return got_error_from_errno2("realpath",
9051 optarg);
9052 break;
9053 case 'm':
9054 if (prepared_logmsg)
9055 option_conflict('m', 'F');
9056 logmsg = optarg;
9057 break;
9058 case 'N':
9059 non_interactive = 1;
9060 break;
9061 case 'n':
9062 show_diff = 0;
9063 break;
9064 case 'S':
9065 allow_bad_symlinks = 1;
9066 break;
9067 default:
9068 usage_commit();
9069 /* NOTREACHED */
9073 argc -= optind;
9074 argv += optind;
9076 #ifndef PROFILE
9077 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
9078 "unveil", NULL) == -1)
9079 err(1, "pledge");
9080 #endif
9081 cwd = getcwd(NULL, 0);
9082 if (cwd == NULL) {
9083 error = got_error_from_errno("getcwd");
9084 goto done;
9087 error = got_repo_pack_fds_open(&pack_fds);
9088 if (error != NULL)
9089 goto done;
9091 error = got_worktree_open(&worktree, cwd);
9092 if (error) {
9093 if (error->code == GOT_ERR_NOT_WORKTREE)
9094 error = wrap_not_worktree_error(error, "commit", cwd);
9095 goto done;
9098 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
9099 if (error)
9100 goto done;
9101 if (rebase_in_progress) {
9102 error = got_error(GOT_ERR_REBASING);
9103 goto done;
9106 error = got_worktree_histedit_in_progress(&histedit_in_progress,
9107 worktree);
9108 if (error)
9109 goto done;
9111 error = get_gitconfig_path(&gitconfig_path);
9112 if (error)
9113 goto done;
9114 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
9115 gitconfig_path, pack_fds);
9116 if (error != NULL)
9117 goto done;
9119 error = got_worktree_merge_in_progress(&merge_in_progress, worktree, repo);
9120 if (error)
9121 goto done;
9122 if (merge_in_progress) {
9123 error = got_error(GOT_ERR_MERGE_BUSY);
9124 goto done;
9127 error = get_author(&committer, repo, worktree);
9128 if (error)
9129 goto done;
9131 if (author != NULL && !strcmp(committer, author)) {
9132 error = got_error(GOT_ERR_COMMIT_REDUNDANT_AUTHOR);
9133 goto done;
9136 if (author == NULL)
9137 author = committer;
9140 * unveil(2) traverses exec(2); if an editor is used we have
9141 * to apply unveil after the log message has been written.
9143 if (logmsg == NULL || strlen(logmsg) == 0)
9144 error = get_editor(&editor);
9145 else
9146 error = apply_unveil(got_repo_get_path(repo), 0,
9147 got_worktree_get_root_path(worktree));
9148 if (error)
9149 goto done;
9151 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
9152 if (error)
9153 goto done;
9155 if (prepared_logmsg == NULL) {
9156 error = lookup_logmsg_ref(&merged_logmsg,
9157 argc > 0 ? &paths : NULL, &refs, worktree, repo);
9158 if (error)
9159 goto done;
9162 cl_arg.editor = editor;
9163 cl_arg.cmdline_log = logmsg;
9164 cl_arg.prepared_log = prepared_logmsg;
9165 cl_arg.merged_log = merged_logmsg;
9166 cl_arg.non_interactive = non_interactive;
9167 cl_arg.worktree_path = got_worktree_get_root_path(worktree);
9168 cl_arg.branch_name = got_worktree_get_head_ref_name(worktree);
9169 if (!histedit_in_progress) {
9170 if (strncmp(cl_arg.branch_name, "refs/heads/", 11) != 0) {
9171 error = got_error(GOT_ERR_COMMIT_BRANCH);
9172 goto done;
9174 cl_arg.branch_name += 11;
9176 cl_arg.repo_path = got_repo_get_path(repo);
9177 error = got_worktree_commit(&id, worktree, &paths, author, committer,
9178 allow_bad_symlinks, show_diff, collect_commit_logmsg, &cl_arg,
9179 print_status, NULL, repo);
9180 if (error) {
9181 if (error->code != GOT_ERR_COMMIT_MSG_EMPTY &&
9182 cl_arg.logmsg_path != NULL)
9183 preserve_logmsg = 1;
9184 goto done;
9187 error = got_object_id_str(&id_str, id);
9188 if (error)
9189 goto done;
9190 printf("Created commit %s\n", id_str);
9192 TAILQ_FOREACH(re, &refs, entry) {
9193 error = got_ref_delete(re->ref, repo);
9194 if (error)
9195 goto done;
9198 done:
9199 if (preserve_logmsg) {
9200 fprintf(stderr, "%s: log message preserved in %s\n",
9201 getprogname(), cl_arg.logmsg_path);
9202 } else if (cl_arg.logmsg_path && unlink(cl_arg.logmsg_path) == -1 &&
9203 error == NULL)
9204 error = got_error_from_errno2("unlink", cl_arg.logmsg_path);
9205 free(cl_arg.logmsg_path);
9206 if (repo) {
9207 const struct got_error *close_err = got_repo_close(repo);
9208 if (error == NULL)
9209 error = close_err;
9211 if (worktree)
9212 got_worktree_close(worktree);
9213 if (pack_fds) {
9214 const struct got_error *pack_err =
9215 got_repo_pack_fds_close(pack_fds);
9216 if (error == NULL)
9217 error = pack_err;
9219 got_ref_list_free(&refs);
9220 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
9221 free(cwd);
9222 free(id_str);
9223 free(gitconfig_path);
9224 free(editor);
9225 free(committer);
9226 free(prepared_logmsg);
9227 return error;
9230 __dead static void
9231 usage_send(void)
9233 fprintf(stderr, "usage: %s send [-afqTv] [-b branch] [-d branch] "
9234 "[-r repository-path] [-t tag] [remote-repository]\n",
9235 getprogname());
9236 exit(1);
9239 static void
9240 print_load_info(int print_colored, int print_found, int print_trees,
9241 int ncolored, int nfound, int ntrees)
9243 if (print_colored) {
9244 printf("%d commit%s colored", ncolored,
9245 ncolored == 1 ? "" : "s");
9247 if (print_found) {
9248 printf("%s%d object%s found",
9249 ncolored > 0 ? "; " : "",
9250 nfound, nfound == 1 ? "" : "s");
9252 if (print_trees) {
9253 printf("; %d tree%s scanned", ntrees,
9254 ntrees == 1 ? "" : "s");
9258 struct got_send_progress_arg {
9259 char last_scaled_packsize[FMT_SCALED_STRSIZE];
9260 int verbosity;
9261 int last_ncolored;
9262 int last_nfound;
9263 int last_ntrees;
9264 int loading_done;
9265 int last_ncommits;
9266 int last_nobj_total;
9267 int last_p_deltify;
9268 int last_p_written;
9269 int last_p_sent;
9270 int printed_something;
9271 int sent_something;
9272 struct got_pathlist_head *delete_branches;
9275 static const struct got_error *
9276 send_progress(void *arg, int ncolored, int nfound, int ntrees,
9277 off_t packfile_size, int ncommits, int nobj_total, int nobj_deltify,
9278 int nobj_written, off_t bytes_sent, const char *refname,
9279 const char *errmsg, int success)
9281 struct got_send_progress_arg *a = arg;
9282 char scaled_packsize[FMT_SCALED_STRSIZE];
9283 char scaled_sent[FMT_SCALED_STRSIZE];
9284 int p_deltify = 0, p_written = 0, p_sent = 0;
9285 int print_colored = 0, print_found = 0, print_trees = 0;
9286 int print_searching = 0, print_total = 0;
9287 int print_deltify = 0, print_written = 0, print_sent = 0;
9289 if (a->verbosity < 0)
9290 return NULL;
9292 if (refname) {
9293 const char *status = success ? "accepted" : "rejected";
9295 if (success) {
9296 struct got_pathlist_entry *pe;
9297 TAILQ_FOREACH(pe, a->delete_branches, entry) {
9298 const char *branchname = pe->path;
9299 if (got_path_cmp(branchname, refname,
9300 strlen(branchname), strlen(refname)) == 0) {
9301 status = "deleted";
9302 a->sent_something = 1;
9303 break;
9308 if (a->printed_something)
9309 putchar('\n');
9310 printf("Server has %s %s", status, refname);
9311 if (errmsg)
9312 printf(": %s", errmsg);
9313 a->printed_something = 1;
9314 return NULL;
9317 if (a->last_ncolored != ncolored) {
9318 print_colored = 1;
9319 a->last_ncolored = ncolored;
9322 if (a->last_nfound != nfound) {
9323 print_colored = 1;
9324 print_found = 1;
9325 a->last_nfound = nfound;
9328 if (a->last_ntrees != ntrees) {
9329 print_colored = 1;
9330 print_found = 1;
9331 print_trees = 1;
9332 a->last_ntrees = ntrees;
9335 if ((print_colored || print_found || print_trees) &&
9336 !a->loading_done) {
9337 printf("\r");
9338 print_load_info(print_colored, print_found, print_trees,
9339 ncolored, nfound, ntrees);
9340 a->printed_something = 1;
9341 fflush(stdout);
9342 return NULL;
9343 } else if (!a->loading_done) {
9344 printf("\r");
9345 print_load_info(1, 1, 1, ncolored, nfound, ntrees);
9346 printf("\n");
9347 a->loading_done = 1;
9350 if (fmt_scaled(packfile_size, scaled_packsize) == -1)
9351 return got_error_from_errno("fmt_scaled");
9352 if (fmt_scaled(bytes_sent, scaled_sent) == -1)
9353 return got_error_from_errno("fmt_scaled");
9355 if (a->last_ncommits != ncommits) {
9356 print_searching = 1;
9357 a->last_ncommits = ncommits;
9360 if (a->last_nobj_total != nobj_total) {
9361 print_searching = 1;
9362 print_total = 1;
9363 a->last_nobj_total = nobj_total;
9366 if (packfile_size > 0 && (a->last_scaled_packsize[0] == '\0' ||
9367 strcmp(scaled_packsize, a->last_scaled_packsize)) != 0) {
9368 if (strlcpy(a->last_scaled_packsize, scaled_packsize,
9369 FMT_SCALED_STRSIZE) >= FMT_SCALED_STRSIZE)
9370 return got_error(GOT_ERR_NO_SPACE);
9373 if (nobj_deltify > 0 || nobj_written > 0) {
9374 if (nobj_deltify > 0) {
9375 p_deltify = (nobj_deltify * 100) / nobj_total;
9376 if (p_deltify != a->last_p_deltify) {
9377 a->last_p_deltify = p_deltify;
9378 print_searching = 1;
9379 print_total = 1;
9380 print_deltify = 1;
9383 if (nobj_written > 0) {
9384 p_written = (nobj_written * 100) / nobj_total;
9385 if (p_written != a->last_p_written) {
9386 a->last_p_written = p_written;
9387 print_searching = 1;
9388 print_total = 1;
9389 print_deltify = 1;
9390 print_written = 1;
9395 if (bytes_sent > 0) {
9396 p_sent = (bytes_sent * 100) / packfile_size;
9397 if (p_sent != a->last_p_sent) {
9398 a->last_p_sent = p_sent;
9399 print_searching = 1;
9400 print_total = 1;
9401 print_deltify = 1;
9402 print_written = 1;
9403 print_sent = 1;
9405 a->sent_something = 1;
9408 if (print_searching || print_total || print_deltify || print_written ||
9409 print_sent)
9410 printf("\r");
9411 if (print_searching)
9412 printf("packing %d reference%s", ncommits,
9413 ncommits == 1 ? "" : "s");
9414 if (print_total)
9415 printf("; %d object%s", nobj_total,
9416 nobj_total == 1 ? "" : "s");
9417 if (print_deltify)
9418 printf("; deltify: %d%%", p_deltify);
9419 if (print_sent)
9420 printf("; uploading pack: %*s %d%%", FMT_SCALED_STRSIZE - 2,
9421 scaled_packsize, p_sent);
9422 else if (print_written)
9423 printf("; writing pack: %*s %d%%", FMT_SCALED_STRSIZE - 2,
9424 scaled_packsize, p_written);
9425 if (print_searching || print_total || print_deltify ||
9426 print_written || print_sent) {
9427 a->printed_something = 1;
9428 fflush(stdout);
9430 return NULL;
9433 static const struct got_error *
9434 cmd_send(int argc, char *argv[])
9436 const struct got_error *error = NULL;
9437 char *cwd = NULL, *repo_path = NULL;
9438 const char *remote_name;
9439 char *proto = NULL, *host = NULL, *port = NULL;
9440 char *repo_name = NULL, *server_path = NULL;
9441 const struct got_remote_repo *remotes, *remote = NULL;
9442 int nremotes, nbranches = 0, ndelete_branches = 0;
9443 struct got_repository *repo = NULL;
9444 struct got_worktree *worktree = NULL;
9445 const struct got_gotconfig *repo_conf = NULL, *worktree_conf = NULL;
9446 struct got_pathlist_head branches;
9447 struct got_pathlist_head tags;
9448 struct got_reflist_head all_branches;
9449 struct got_reflist_head all_tags;
9450 struct got_pathlist_head delete_args;
9451 struct got_pathlist_head delete_branches;
9452 struct got_reflist_entry *re;
9453 struct got_pathlist_entry *pe;
9454 int i, ch, sendfd = -1, sendstatus;
9455 pid_t sendpid = -1;
9456 struct got_send_progress_arg spa;
9457 int verbosity = 0, overwrite_refs = 0;
9458 int send_all_branches = 0, send_all_tags = 0;
9459 struct got_reference *ref = NULL;
9460 int *pack_fds = NULL;
9462 TAILQ_INIT(&branches);
9463 TAILQ_INIT(&tags);
9464 TAILQ_INIT(&all_branches);
9465 TAILQ_INIT(&all_tags);
9466 TAILQ_INIT(&delete_args);
9467 TAILQ_INIT(&delete_branches);
9469 while ((ch = getopt(argc, argv, "ab:d:fqr:Tt:v")) != -1) {
9470 switch (ch) {
9471 case 'a':
9472 send_all_branches = 1;
9473 break;
9474 case 'b':
9475 error = got_pathlist_append(&branches, optarg, NULL);
9476 if (error)
9477 return error;
9478 nbranches++;
9479 break;
9480 case 'd':
9481 error = got_pathlist_append(&delete_args, optarg, NULL);
9482 if (error)
9483 return error;
9484 break;
9485 case 'f':
9486 overwrite_refs = 1;
9487 break;
9488 case 'q':
9489 verbosity = -1;
9490 break;
9491 case 'r':
9492 repo_path = realpath(optarg, NULL);
9493 if (repo_path == NULL)
9494 return got_error_from_errno2("realpath",
9495 optarg);
9496 got_path_strip_trailing_slashes(repo_path);
9497 break;
9498 case 'T':
9499 send_all_tags = 1;
9500 break;
9501 case 't':
9502 error = got_pathlist_append(&tags, optarg, NULL);
9503 if (error)
9504 return error;
9505 break;
9506 case 'v':
9507 if (verbosity < 0)
9508 verbosity = 0;
9509 else if (verbosity < 3)
9510 verbosity++;
9511 break;
9512 default:
9513 usage_send();
9514 /* NOTREACHED */
9517 argc -= optind;
9518 argv += optind;
9520 if (send_all_branches && !TAILQ_EMPTY(&branches))
9521 option_conflict('a', 'b');
9522 if (send_all_tags && !TAILQ_EMPTY(&tags))
9523 option_conflict('T', 't');
9526 if (argc == 0)
9527 remote_name = GOT_SEND_DEFAULT_REMOTE_NAME;
9528 else if (argc == 1)
9529 remote_name = argv[0];
9530 else
9531 usage_send();
9533 cwd = getcwd(NULL, 0);
9534 if (cwd == NULL) {
9535 error = got_error_from_errno("getcwd");
9536 goto done;
9539 error = got_repo_pack_fds_open(&pack_fds);
9540 if (error != NULL)
9541 goto done;
9543 if (repo_path == NULL) {
9544 error = got_worktree_open(&worktree, cwd);
9545 if (error && error->code != GOT_ERR_NOT_WORKTREE)
9546 goto done;
9547 else
9548 error = NULL;
9549 if (worktree) {
9550 repo_path =
9551 strdup(got_worktree_get_repo_path(worktree));
9552 if (repo_path == NULL)
9553 error = got_error_from_errno("strdup");
9554 if (error)
9555 goto done;
9556 } else {
9557 repo_path = strdup(cwd);
9558 if (repo_path == NULL) {
9559 error = got_error_from_errno("strdup");
9560 goto done;
9565 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
9566 if (error)
9567 goto done;
9569 if (worktree) {
9570 worktree_conf = got_worktree_get_gotconfig(worktree);
9571 if (worktree_conf) {
9572 got_gotconfig_get_remotes(&nremotes, &remotes,
9573 worktree_conf);
9574 for (i = 0; i < nremotes; i++) {
9575 if (strcmp(remotes[i].name, remote_name) == 0) {
9576 remote = &remotes[i];
9577 break;
9582 if (remote == NULL) {
9583 repo_conf = got_repo_get_gotconfig(repo);
9584 if (repo_conf) {
9585 got_gotconfig_get_remotes(&nremotes, &remotes,
9586 repo_conf);
9587 for (i = 0; i < nremotes; i++) {
9588 if (strcmp(remotes[i].name, remote_name) == 0) {
9589 remote = &remotes[i];
9590 break;
9595 if (remote == NULL) {
9596 got_repo_get_gitconfig_remotes(&nremotes, &remotes, repo);
9597 for (i = 0; i < nremotes; i++) {
9598 if (strcmp(remotes[i].name, remote_name) == 0) {
9599 remote = &remotes[i];
9600 break;
9604 if (remote == NULL) {
9605 error = got_error_path(remote_name, GOT_ERR_NO_REMOTE);
9606 goto done;
9609 error = got_dial_parse_uri(&proto, &host, &port, &server_path,
9610 &repo_name, remote->send_url);
9611 if (error)
9612 goto done;
9614 if (strcmp(proto, "git") == 0) {
9615 #ifndef PROFILE
9616 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
9617 "sendfd dns inet unveil", NULL) == -1)
9618 err(1, "pledge");
9619 #endif
9620 } else if (strcmp(proto, "git+ssh") == 0 ||
9621 strcmp(proto, "ssh") == 0) {
9622 #ifndef PROFILE
9623 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
9624 "sendfd unveil", NULL) == -1)
9625 err(1, "pledge");
9626 #endif
9627 } else if (strcmp(proto, "http") == 0 ||
9628 strcmp(proto, "git+http") == 0) {
9629 error = got_error_path(proto, GOT_ERR_NOT_IMPL);
9630 goto done;
9631 } else {
9632 error = got_error_path(proto, GOT_ERR_BAD_PROTO);
9633 goto done;
9636 error = got_dial_apply_unveil(proto);
9637 if (error)
9638 goto done;
9640 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
9641 if (error)
9642 goto done;
9644 if (send_all_branches) {
9645 error = got_ref_list(&all_branches, repo, "refs/heads",
9646 got_ref_cmp_by_name, NULL);
9647 if (error)
9648 goto done;
9649 TAILQ_FOREACH(re, &all_branches, entry) {
9650 const char *branchname = got_ref_get_name(re->ref);
9651 error = got_pathlist_append(&branches,
9652 branchname, NULL);
9653 if (error)
9654 goto done;
9655 nbranches++;
9657 } else if (nbranches == 0) {
9658 for (i = 0; i < remote->nsend_branches; i++) {
9659 error = got_pathlist_append(&branches,
9660 remote->send_branches[i], NULL);
9661 if (error)
9662 goto done;
9666 if (send_all_tags) {
9667 error = got_ref_list(&all_tags, repo, "refs/tags",
9668 got_ref_cmp_by_name, NULL);
9669 if (error)
9670 goto done;
9671 TAILQ_FOREACH(re, &all_tags, entry) {
9672 const char *tagname = got_ref_get_name(re->ref);
9673 error = got_pathlist_append(&tags,
9674 tagname, NULL);
9675 if (error)
9676 goto done;
9681 * To prevent accidents only branches in refs/heads/ can be deleted
9682 * with 'got send -d'.
9683 * Deleting anything else requires local repository access or Git.
9685 TAILQ_FOREACH(pe, &delete_args, entry) {
9686 const char *branchname = pe->path;
9687 char *s;
9688 struct got_pathlist_entry *new;
9689 if (strncmp(branchname, "refs/heads/", 11) == 0) {
9690 s = strdup(branchname);
9691 if (s == NULL) {
9692 error = got_error_from_errno("strdup");
9693 goto done;
9695 } else {
9696 if (asprintf(&s, "refs/heads/%s", branchname) == -1) {
9697 error = got_error_from_errno("asprintf");
9698 goto done;
9701 error = got_pathlist_insert(&new, &delete_branches, s, NULL);
9702 if (error || new == NULL /* duplicate */)
9703 free(s);
9704 if (error)
9705 goto done;
9706 ndelete_branches++;
9709 if (nbranches == 0 && ndelete_branches == 0) {
9710 struct got_reference *head_ref;
9711 if (worktree)
9712 error = got_ref_open(&head_ref, repo,
9713 got_worktree_get_head_ref_name(worktree), 0);
9714 else
9715 error = got_ref_open(&head_ref, repo, GOT_REF_HEAD, 0);
9716 if (error)
9717 goto done;
9718 if (got_ref_is_symbolic(head_ref)) {
9719 error = got_ref_resolve_symbolic(&ref, repo, head_ref);
9720 got_ref_close(head_ref);
9721 if (error)
9722 goto done;
9723 } else
9724 ref = head_ref;
9725 error = got_pathlist_append(&branches, got_ref_get_name(ref),
9726 NULL);
9727 if (error)
9728 goto done;
9729 nbranches++;
9732 if (verbosity >= 0) {
9733 printf("Connecting to \"%s\" %s://%s%s%s%s%s\n",
9734 remote->name, proto, host,
9735 port ? ":" : "", port ? port : "",
9736 *server_path == '/' ? "" : "/", server_path);
9739 error = got_send_connect(&sendpid, &sendfd, proto, host, port,
9740 server_path, verbosity);
9741 if (error)
9742 goto done;
9744 memset(&spa, 0, sizeof(spa));
9745 spa.last_scaled_packsize[0] = '\0';
9746 spa.last_p_deltify = -1;
9747 spa.last_p_written = -1;
9748 spa.verbosity = verbosity;
9749 spa.delete_branches = &delete_branches;
9750 error = got_send_pack(remote_name, &branches, &tags, &delete_branches,
9751 verbosity, overwrite_refs, sendfd, repo, send_progress, &spa,
9752 check_cancelled, NULL);
9753 if (spa.printed_something)
9754 putchar('\n');
9755 if (error)
9756 goto done;
9757 if (!spa.sent_something && verbosity >= 0)
9758 printf("Already up-to-date\n");
9759 done:
9760 if (sendpid > 0) {
9761 if (kill(sendpid, SIGTERM) == -1)
9762 error = got_error_from_errno("kill");
9763 if (waitpid(sendpid, &sendstatus, 0) == -1 && error == NULL)
9764 error = got_error_from_errno("waitpid");
9766 if (sendfd != -1 && close(sendfd) == -1 && error == NULL)
9767 error = got_error_from_errno("close");
9768 if (repo) {
9769 const struct got_error *close_err = got_repo_close(repo);
9770 if (error == NULL)
9771 error = close_err;
9773 if (worktree)
9774 got_worktree_close(worktree);
9775 if (pack_fds) {
9776 const struct got_error *pack_err =
9777 got_repo_pack_fds_close(pack_fds);
9778 if (error == NULL)
9779 error = pack_err;
9781 if (ref)
9782 got_ref_close(ref);
9783 got_pathlist_free(&branches, GOT_PATHLIST_FREE_NONE);
9784 got_pathlist_free(&tags, GOT_PATHLIST_FREE_NONE);
9785 got_ref_list_free(&all_branches);
9786 got_ref_list_free(&all_tags);
9787 got_pathlist_free(&delete_args, GOT_PATHLIST_FREE_NONE);
9788 got_pathlist_free(&delete_branches, GOT_PATHLIST_FREE_PATH);
9789 free(cwd);
9790 free(repo_path);
9791 free(proto);
9792 free(host);
9793 free(port);
9794 free(server_path);
9795 free(repo_name);
9796 return error;
9800 * Print and if delete is set delete all ref_prefix references.
9801 * If wanted_ref is not NULL, only print or delete this reference.
9803 static const struct got_error *
9804 process_logmsg_refs(const char *ref_prefix, size_t prefix_len,
9805 const char *wanted_ref, int delete, struct got_worktree *worktree,
9806 struct got_repository *repo)
9808 const struct got_error *err;
9809 struct got_pathlist_head paths;
9810 struct got_reflist_head refs;
9811 struct got_reflist_entry *re;
9812 struct got_reflist_object_id_map *refs_idmap = NULL;
9813 struct got_commit_object *commit = NULL;
9814 struct got_object_id *id = NULL;
9815 char *uuidstr = NULL;
9816 int found = 0;
9818 TAILQ_INIT(&refs);
9819 TAILQ_INIT(&paths);
9821 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, repo);
9822 if (err)
9823 goto done;
9825 err = got_reflist_object_id_map_create(&refs_idmap, &refs, repo);
9826 if (err)
9827 goto done;
9829 if (worktree != NULL) {
9830 err = got_worktree_get_uuid(&uuidstr, worktree);
9831 if (err)
9832 goto done;
9835 if (wanted_ref) {
9836 if (strncmp(wanted_ref, "refs/heads/", 11) == 0)
9837 wanted_ref += 11;
9840 TAILQ_FOREACH(re, &refs, entry) {
9841 const char *refname;
9843 refname = got_ref_get_name(re->ref);
9845 err = check_cancelled(NULL);
9846 if (err)
9847 goto done;
9849 if (strncmp(refname, ref_prefix, prefix_len) == 0)
9850 refname += prefix_len + 1; /* skip '-' delimiter */
9851 else
9852 continue;
9854 if (worktree == NULL || strncmp(refname, uuidstr,
9855 GOT_WORKTREE_UUID_STRLEN) == 0)
9856 refname += GOT_WORKTREE_UUID_STRLEN + 1; /* skip '-' */
9857 else
9858 continue;
9860 err = got_repo_match_object_id(&id, NULL, refname,
9861 GOT_OBJ_TYPE_COMMIT, NULL, repo);
9862 if (err)
9863 goto done;
9865 err = got_object_open_as_commit(&commit, repo, id);
9866 if (err)
9867 goto done;
9869 if (wanted_ref)
9870 found = strncmp(wanted_ref, refname,
9871 strlen(wanted_ref)) == 0;
9872 if (wanted_ref && !found) {
9873 struct got_reflist_head *ci_refs;
9875 ci_refs = got_reflist_object_id_map_lookup(refs_idmap,
9876 id);
9878 if (ci_refs) {
9879 char *refs_str = NULL;
9880 char const *r = NULL;
9882 err = build_refs_str(&refs_str, ci_refs, id,
9883 repo, 1);
9884 if (err)
9885 goto done;
9887 r = refs_str;
9888 while (r) {
9889 if (strncmp(r, wanted_ref,
9890 strlen(wanted_ref)) == 0) {
9891 found = 1;
9892 break;
9894 r = strchr(r, ' ');
9895 if (r)
9896 ++r;
9898 free(refs_str);
9902 if (wanted_ref == NULL || found) {
9903 if (delete) {
9904 err = got_ref_delete(re->ref, repo);
9905 if (err)
9906 goto done;
9907 printf("Deleted: ");
9908 err = print_commit_oneline(commit, id, repo,
9909 refs_idmap);
9910 } else {
9912 * Print paths modified by commit to help
9913 * associate commits with worktree changes.
9915 err = get_changed_paths(&paths, commit,
9916 repo, NULL);
9917 if (err)
9918 goto done;
9920 err = print_commit(commit, id, repo, NULL,
9921 &paths, NULL, 0, 0, refs_idmap, NULL);
9922 got_pathlist_free(&paths,
9923 GOT_PATHLIST_FREE_ALL);
9925 if (err || found)
9926 goto done;
9929 got_object_commit_close(commit);
9930 commit = NULL;
9931 free(id);
9932 id = NULL;
9935 if (wanted_ref != NULL && !found)
9936 err = got_error_fmt(GOT_ERR_NOT_REF, "%s", wanted_ref);
9938 done:
9939 free(id);
9940 free(uuidstr);
9941 got_ref_list_free(&refs);
9942 got_pathlist_free(&paths, GOT_PATHLIST_FREE_ALL);
9943 if (refs_idmap)
9944 got_reflist_object_id_map_free(refs_idmap);
9945 if (commit)
9946 got_object_commit_close(commit);
9947 return err;
9951 * Create new temp "logmsg" ref of the backed-out or cherrypicked commit
9952 * identified by id for log messages to prepopulate the editor on commit.
9954 static const struct got_error *
9955 logmsg_ref(struct got_object_id *id, const char *prefix,
9956 struct got_worktree *worktree, struct got_repository *repo)
9958 const struct got_error *err = NULL;
9959 char *idstr, *ref = NULL, *refname = NULL;
9960 int histedit_in_progress;
9961 int rebase_in_progress, merge_in_progress;
9964 * Silenty refuse to create merge reference if any histedit, merge,
9965 * or rebase operation is in progress.
9967 err = got_worktree_histedit_in_progress(&histedit_in_progress,
9968 worktree);
9969 if (err)
9970 return err;
9971 if (histedit_in_progress)
9972 return NULL;
9974 err = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
9975 if (err)
9976 return err;
9977 if (rebase_in_progress)
9978 return NULL;
9980 err = got_worktree_merge_in_progress(&merge_in_progress, worktree,
9981 repo);
9982 if (err)
9983 return err;
9984 if (merge_in_progress)
9985 return NULL;
9987 err = got_object_id_str(&idstr, id);
9988 if (err)
9989 return err;
9991 err = got_worktree_get_logmsg_ref_name(&refname, worktree, prefix);
9992 if (err)
9993 goto done;
9995 if (asprintf(&ref, "%s-%s", refname, idstr) == -1) {
9996 err = got_error_from_errno("asprintf");
9997 goto done;
10000 err = create_ref(ref, got_worktree_get_base_commit_id(worktree),
10001 -1, repo);
10002 done:
10003 free(ref);
10004 free(idstr);
10005 free(refname);
10006 return err;
10009 __dead static void
10010 usage_cherrypick(void)
10012 fprintf(stderr, "usage: %s cherrypick [-lX] [commit-id]\n",
10013 getprogname());
10014 exit(1);
10017 static const struct got_error *
10018 cmd_cherrypick(int argc, char *argv[])
10020 const struct got_error *error = NULL;
10021 struct got_worktree *worktree = NULL;
10022 struct got_repository *repo = NULL;
10023 char *cwd = NULL, *commit_id_str = NULL;
10024 struct got_object_id *commit_id = NULL;
10025 struct got_commit_object *commit = NULL;
10026 struct got_object_qid *pid;
10027 int ch, list_refs = 0, remove_refs = 0;
10028 struct got_update_progress_arg upa;
10029 int *pack_fds = NULL;
10031 while ((ch = getopt(argc, argv, "lX")) != -1) {
10032 switch (ch) {
10033 case 'l':
10034 list_refs = 1;
10035 break;
10036 case 'X':
10037 remove_refs = 1;
10038 break;
10039 default:
10040 usage_cherrypick();
10041 /* NOTREACHED */
10045 argc -= optind;
10046 argv += optind;
10048 #ifndef PROFILE
10049 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
10050 "unveil", NULL) == -1)
10051 err(1, "pledge");
10052 #endif
10053 if (list_refs || remove_refs) {
10054 if (argc != 0 && argc != 1)
10055 usage_cherrypick();
10056 } else if (argc != 1)
10057 usage_cherrypick();
10058 if (list_refs && remove_refs)
10059 option_conflict('l', 'X');
10061 cwd = getcwd(NULL, 0);
10062 if (cwd == NULL) {
10063 error = got_error_from_errno("getcwd");
10064 goto done;
10067 error = got_repo_pack_fds_open(&pack_fds);
10068 if (error != NULL)
10069 goto done;
10071 error = got_worktree_open(&worktree, cwd);
10072 if (error) {
10073 if (list_refs || remove_refs) {
10074 if (error->code != GOT_ERR_NOT_WORKTREE)
10075 goto done;
10076 } else {
10077 if (error->code == GOT_ERR_NOT_WORKTREE)
10078 error = wrap_not_worktree_error(error,
10079 "cherrypick", cwd);
10080 goto done;
10084 error = got_repo_open(&repo,
10085 worktree ? got_worktree_get_repo_path(worktree) : cwd,
10086 NULL, pack_fds);
10087 if (error != NULL)
10088 goto done;
10090 error = apply_unveil(got_repo_get_path(repo), 0,
10091 worktree ? got_worktree_get_root_path(worktree) : NULL);
10092 if (error)
10093 goto done;
10095 if (list_refs || remove_refs) {
10096 error = process_logmsg_refs(GOT_WORKTREE_CHERRYPICK_REF_PREFIX,
10097 GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN,
10098 argc == 1 ? argv[0] : NULL, remove_refs, worktree, repo);
10099 goto done;
10102 error = got_repo_match_object_id(&commit_id, NULL, argv[0],
10103 GOT_OBJ_TYPE_COMMIT, NULL, repo);
10104 if (error)
10105 goto done;
10106 error = got_object_id_str(&commit_id_str, commit_id);
10107 if (error)
10108 goto done;
10110 error = got_object_open_as_commit(&commit, repo, commit_id);
10111 if (error)
10112 goto done;
10113 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
10114 memset(&upa, 0, sizeof(upa));
10115 error = got_worktree_merge_files(worktree, pid ? &pid->id : NULL,
10116 commit_id, repo, update_progress, &upa, check_cancelled,
10117 NULL);
10118 if (error != NULL)
10119 goto done;
10121 if (upa.did_something) {
10122 error = logmsg_ref(commit_id,
10123 GOT_WORKTREE_CHERRYPICK_REF_PREFIX, worktree, repo);
10124 if (error)
10125 goto done;
10126 printf("Merged commit %s\n", commit_id_str);
10128 print_merge_progress_stats(&upa);
10129 done:
10130 if (commit)
10131 got_object_commit_close(commit);
10132 free(commit_id_str);
10133 if (worktree)
10134 got_worktree_close(worktree);
10135 if (repo) {
10136 const struct got_error *close_err = got_repo_close(repo);
10137 if (error == NULL)
10138 error = close_err;
10140 if (pack_fds) {
10141 const struct got_error *pack_err =
10142 got_repo_pack_fds_close(pack_fds);
10143 if (error == NULL)
10144 error = pack_err;
10147 return error;
10150 __dead static void
10151 usage_backout(void)
10153 fprintf(stderr, "usage: %s backout [-lX] [commit-id]\n", getprogname());
10154 exit(1);
10157 static const struct got_error *
10158 cmd_backout(int argc, char *argv[])
10160 const struct got_error *error = NULL;
10161 struct got_worktree *worktree = NULL;
10162 struct got_repository *repo = NULL;
10163 char *cwd = NULL, *commit_id_str = NULL;
10164 struct got_object_id *commit_id = NULL;
10165 struct got_commit_object *commit = NULL;
10166 struct got_object_qid *pid;
10167 int ch, list_refs = 0, remove_refs = 0;
10168 struct got_update_progress_arg upa;
10169 int *pack_fds = NULL;
10171 while ((ch = getopt(argc, argv, "lX")) != -1) {
10172 switch (ch) {
10173 case 'l':
10174 list_refs = 1;
10175 break;
10176 case 'X':
10177 remove_refs = 1;
10178 break;
10179 default:
10180 usage_backout();
10181 /* NOTREACHED */
10185 argc -= optind;
10186 argv += optind;
10188 #ifndef PROFILE
10189 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
10190 "unveil", NULL) == -1)
10191 err(1, "pledge");
10192 #endif
10193 if (list_refs || remove_refs) {
10194 if (argc != 0 && argc != 1)
10195 usage_backout();
10196 } else if (argc != 1)
10197 usage_backout();
10198 if (list_refs && remove_refs)
10199 option_conflict('l', 'X');
10201 cwd = getcwd(NULL, 0);
10202 if (cwd == NULL) {
10203 error = got_error_from_errno("getcwd");
10204 goto done;
10207 error = got_repo_pack_fds_open(&pack_fds);
10208 if (error != NULL)
10209 goto done;
10211 error = got_worktree_open(&worktree, cwd);
10212 if (error) {
10213 if (list_refs || remove_refs) {
10214 if (error->code != GOT_ERR_NOT_WORKTREE)
10215 goto done;
10216 } else {
10217 if (error->code == GOT_ERR_NOT_WORKTREE)
10218 error = wrap_not_worktree_error(error,
10219 "backout", cwd);
10220 goto done;
10224 error = got_repo_open(&repo,
10225 worktree ? got_worktree_get_repo_path(worktree) : cwd,
10226 NULL, pack_fds);
10227 if (error != NULL)
10228 goto done;
10230 error = apply_unveil(got_repo_get_path(repo), 0,
10231 worktree ? got_worktree_get_root_path(worktree) : NULL);
10232 if (error)
10233 goto done;
10235 if (list_refs || remove_refs) {
10236 error = process_logmsg_refs(GOT_WORKTREE_BACKOUT_REF_PREFIX,
10237 GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN,
10238 argc == 1 ? argv[0] : NULL, remove_refs, worktree, repo);
10239 goto done;
10242 error = got_repo_match_object_id(&commit_id, NULL, argv[0],
10243 GOT_OBJ_TYPE_COMMIT, NULL, repo);
10244 if (error)
10245 goto done;
10246 error = got_object_id_str(&commit_id_str, commit_id);
10247 if (error)
10248 goto done;
10250 error = got_object_open_as_commit(&commit, repo, commit_id);
10251 if (error)
10252 goto done;
10253 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
10254 if (pid == NULL) {
10255 error = got_error(GOT_ERR_ROOT_COMMIT);
10256 goto done;
10259 memset(&upa, 0, sizeof(upa));
10260 error = got_worktree_merge_files(worktree, commit_id, &pid->id,
10261 repo, update_progress, &upa, check_cancelled, NULL);
10262 if (error != NULL)
10263 goto done;
10265 if (upa.did_something) {
10266 error = logmsg_ref(commit_id, GOT_WORKTREE_BACKOUT_REF_PREFIX,
10267 worktree, repo);
10268 if (error)
10269 goto done;
10270 printf("Backed out commit %s\n", commit_id_str);
10272 print_merge_progress_stats(&upa);
10273 done:
10274 if (commit)
10275 got_object_commit_close(commit);
10276 free(commit_id_str);
10277 if (worktree)
10278 got_worktree_close(worktree);
10279 if (repo) {
10280 const struct got_error *close_err = got_repo_close(repo);
10281 if (error == NULL)
10282 error = close_err;
10284 if (pack_fds) {
10285 const struct got_error *pack_err =
10286 got_repo_pack_fds_close(pack_fds);
10287 if (error == NULL)
10288 error = pack_err;
10290 return error;
10293 __dead static void
10294 usage_rebase(void)
10296 fprintf(stderr, "usage: %s rebase [-aclX] [branch]\n", getprogname());
10297 exit(1);
10300 static void
10301 trim_logmsg(char *logmsg, int limit)
10303 char *nl;
10304 size_t len;
10306 len = strlen(logmsg);
10307 if (len > limit)
10308 len = limit;
10309 logmsg[len] = '\0';
10310 nl = strchr(logmsg, '\n');
10311 if (nl)
10312 *nl = '\0';
10315 static const struct got_error *
10316 get_short_logmsg(char **logmsg, int limit, struct got_commit_object *commit)
10318 const struct got_error *err;
10319 char *logmsg0 = NULL;
10320 const char *s;
10322 err = got_object_commit_get_logmsg(&logmsg0, commit);
10323 if (err)
10324 return err;
10326 s = logmsg0;
10327 while (isspace((unsigned char)s[0]))
10328 s++;
10330 *logmsg = strdup(s);
10331 if (*logmsg == NULL) {
10332 err = got_error_from_errno("strdup");
10333 goto done;
10336 trim_logmsg(*logmsg, limit);
10337 done:
10338 free(logmsg0);
10339 return err;
10342 static const struct got_error *
10343 show_rebase_merge_conflict(struct got_object_id *id,
10344 struct got_repository *repo)
10346 const struct got_error *err;
10347 struct got_commit_object *commit = NULL;
10348 char *id_str = NULL, *logmsg = NULL;
10350 err = got_object_open_as_commit(&commit, repo, id);
10351 if (err)
10352 return err;
10354 err = got_object_id_str(&id_str, id);
10355 if (err)
10356 goto done;
10358 id_str[12] = '\0';
10360 err = get_short_logmsg(&logmsg, 42, commit);
10361 if (err)
10362 goto done;
10364 printf("%s -> merge conflict: %s\n", id_str, logmsg);
10365 done:
10366 free(id_str);
10367 got_object_commit_close(commit);
10368 free(logmsg);
10369 return err;
10372 static const struct got_error *
10373 show_rebase_progress(struct got_commit_object *commit,
10374 struct got_object_id *old_id, struct got_object_id *new_id)
10376 const struct got_error *err;
10377 char *old_id_str = NULL, *new_id_str = NULL, *logmsg = NULL;
10379 err = got_object_id_str(&old_id_str, old_id);
10380 if (err)
10381 goto done;
10383 if (new_id) {
10384 err = got_object_id_str(&new_id_str, new_id);
10385 if (err)
10386 goto done;
10389 old_id_str[12] = '\0';
10390 if (new_id_str)
10391 new_id_str[12] = '\0';
10393 err = get_short_logmsg(&logmsg, 42, commit);
10394 if (err)
10395 goto done;
10397 printf("%s -> %s: %s\n", old_id_str,
10398 new_id_str ? new_id_str : "no-op change", logmsg);
10399 done:
10400 free(old_id_str);
10401 free(new_id_str);
10402 free(logmsg);
10403 return err;
10406 static const struct got_error *
10407 rebase_complete(struct got_worktree *worktree, struct got_fileindex *fileindex,
10408 struct got_reference *branch, struct got_reference *new_base_branch,
10409 struct got_reference *tmp_branch, struct got_repository *repo,
10410 int create_backup)
10412 printf("Switching work tree to %s\n", got_ref_get_name(branch));
10413 return got_worktree_rebase_complete(worktree, fileindex,
10414 new_base_branch, tmp_branch, branch, repo, create_backup);
10417 static const struct got_error *
10418 rebase_commit(struct got_pathlist_head *merged_paths,
10419 struct got_worktree *worktree, struct got_fileindex *fileindex,
10420 struct got_reference *tmp_branch, const char *committer,
10421 struct got_object_id *commit_id, struct got_repository *repo)
10423 const struct got_error *error;
10424 struct got_commit_object *commit;
10425 struct got_object_id *new_commit_id;
10427 error = got_object_open_as_commit(&commit, repo, commit_id);
10428 if (error)
10429 return error;
10431 error = got_worktree_rebase_commit(&new_commit_id, merged_paths,
10432 worktree, fileindex, tmp_branch, committer, commit, commit_id,
10433 repo);
10434 if (error) {
10435 if (error->code != GOT_ERR_COMMIT_NO_CHANGES)
10436 goto done;
10437 error = show_rebase_progress(commit, commit_id, NULL);
10438 } else {
10439 error = show_rebase_progress(commit, commit_id, new_commit_id);
10440 free(new_commit_id);
10442 done:
10443 got_object_commit_close(commit);
10444 return error;
10447 struct check_path_prefix_arg {
10448 const char *path_prefix;
10449 size_t len;
10450 int errcode;
10453 static const struct got_error *
10454 check_path_prefix_in_diff(void *arg, struct got_blob_object *blob1,
10455 struct got_blob_object *blob2, FILE *f1, FILE *f2,
10456 struct got_object_id *id1, struct got_object_id *id2,
10457 const char *path1, const char *path2,
10458 mode_t mode1, mode_t mode2, struct got_repository *repo)
10460 struct check_path_prefix_arg *a = arg;
10462 if ((path1 && !got_path_is_child(path1, a->path_prefix, a->len)) ||
10463 (path2 && !got_path_is_child(path2, a->path_prefix, a->len)))
10464 return got_error(a->errcode);
10466 return NULL;
10469 static const struct got_error *
10470 check_path_prefix(struct got_object_id *parent_id,
10471 struct got_object_id *commit_id, const char *path_prefix,
10472 int errcode, struct got_repository *repo)
10474 const struct got_error *err;
10475 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
10476 struct got_commit_object *commit = NULL, *parent_commit = NULL;
10477 struct check_path_prefix_arg cpp_arg;
10479 if (got_path_is_root_dir(path_prefix))
10480 return NULL;
10482 err = got_object_open_as_commit(&commit, repo, commit_id);
10483 if (err)
10484 goto done;
10486 err = got_object_open_as_commit(&parent_commit, repo, parent_id);
10487 if (err)
10488 goto done;
10490 err = got_object_open_as_tree(&tree1, repo,
10491 got_object_commit_get_tree_id(parent_commit));
10492 if (err)
10493 goto done;
10495 err = got_object_open_as_tree(&tree2, repo,
10496 got_object_commit_get_tree_id(commit));
10497 if (err)
10498 goto done;
10500 cpp_arg.path_prefix = path_prefix;
10501 while (cpp_arg.path_prefix[0] == '/')
10502 cpp_arg.path_prefix++;
10503 cpp_arg.len = strlen(cpp_arg.path_prefix);
10504 cpp_arg.errcode = errcode;
10505 err = got_diff_tree(tree1, tree2, NULL, NULL, -1, -1, "", "", repo,
10506 check_path_prefix_in_diff, &cpp_arg, 0);
10507 done:
10508 if (tree1)
10509 got_object_tree_close(tree1);
10510 if (tree2)
10511 got_object_tree_close(tree2);
10512 if (commit)
10513 got_object_commit_close(commit);
10514 if (parent_commit)
10515 got_object_commit_close(parent_commit);
10516 return err;
10519 static const struct got_error *
10520 collect_commits(struct got_object_id_queue *commits,
10521 struct got_object_id *initial_commit_id,
10522 struct got_object_id *iter_start_id, struct got_object_id *iter_stop_id,
10523 const char *path_prefix, int path_prefix_errcode,
10524 struct got_repository *repo)
10526 const struct got_error *err = NULL;
10527 struct got_commit_graph *graph = NULL;
10528 struct got_object_id parent_id, commit_id;
10529 struct got_object_qid *qid;
10531 err = got_commit_graph_open(&graph, "/", 1);
10532 if (err)
10533 return err;
10535 err = got_commit_graph_iter_start(graph, iter_start_id, repo,
10536 check_cancelled, NULL);
10537 if (err)
10538 goto done;
10540 memcpy(&commit_id, initial_commit_id, sizeof(commit_id));
10541 while (got_object_id_cmp(&commit_id, iter_stop_id) != 0) {
10542 err = got_commit_graph_iter_next(&parent_id, graph, repo,
10543 check_cancelled, NULL);
10544 if (err) {
10545 if (err->code == GOT_ERR_ITER_COMPLETED) {
10546 err = got_error_msg(GOT_ERR_ANCESTRY,
10547 "ran out of commits to rebase before "
10548 "youngest common ancestor commit has "
10549 "been reached?!?");
10551 goto done;
10552 } else {
10553 err = check_path_prefix(&parent_id, &commit_id,
10554 path_prefix, path_prefix_errcode, repo);
10555 if (err)
10556 goto done;
10558 err = got_object_qid_alloc(&qid, &commit_id);
10559 if (err)
10560 goto done;
10561 STAILQ_INSERT_HEAD(commits, qid, entry);
10563 memcpy(&commit_id, &parent_id, sizeof(commit_id));
10566 done:
10567 got_commit_graph_close(graph);
10568 return err;
10571 static const struct got_error *
10572 get_commit_brief_str(char **brief_str, struct got_commit_object *commit)
10574 const struct got_error *err = NULL;
10575 time_t committer_time;
10576 struct tm tm;
10577 char datebuf[11]; /* YYYY-MM-DD + NUL */
10578 char *author0 = NULL, *author, *smallerthan;
10579 char *logmsg0 = NULL, *logmsg, *newline;
10581 committer_time = got_object_commit_get_committer_time(commit);
10582 if (gmtime_r(&committer_time, &tm) == NULL)
10583 return got_error_from_errno("gmtime_r");
10584 if (strftime(datebuf, sizeof(datebuf), "%G-%m-%d", &tm) == 0)
10585 return got_error(GOT_ERR_NO_SPACE);
10587 author0 = strdup(got_object_commit_get_author(commit));
10588 if (author0 == NULL)
10589 return got_error_from_errno("strdup");
10590 author = author0;
10591 smallerthan = strchr(author, '<');
10592 if (smallerthan && smallerthan[1] != '\0')
10593 author = smallerthan + 1;
10594 author[strcspn(author, "@>")] = '\0';
10596 err = got_object_commit_get_logmsg(&logmsg0, commit);
10597 if (err)
10598 goto done;
10599 logmsg = logmsg0;
10600 while (*logmsg == '\n')
10601 logmsg++;
10602 newline = strchr(logmsg, '\n');
10603 if (newline)
10604 *newline = '\0';
10606 if (asprintf(brief_str, "%s %s %s",
10607 datebuf, author, logmsg) == -1)
10608 err = got_error_from_errno("asprintf");
10609 done:
10610 free(author0);
10611 free(logmsg0);
10612 return err;
10615 static const struct got_error *
10616 delete_backup_ref(struct got_reference *ref, struct got_object_id *id,
10617 struct got_repository *repo)
10619 const struct got_error *err;
10620 char *id_str;
10622 err = got_object_id_str(&id_str, id);
10623 if (err)
10624 return err;
10626 err = got_ref_delete(ref, repo);
10627 if (err)
10628 goto done;
10630 printf("Deleted %s: %s\n", got_ref_get_name(ref), id_str);
10631 done:
10632 free(id_str);
10633 return err;
10636 static const struct got_error *
10637 print_backup_ref(const char *branch_name, const char *new_id_str,
10638 struct got_object_id *old_commit_id, struct got_commit_object *old_commit,
10639 struct got_reflist_object_id_map *refs_idmap,
10640 struct got_repository *repo)
10642 const struct got_error *err = NULL;
10643 struct got_reflist_head *refs;
10644 char *refs_str = NULL;
10645 struct got_object_id *new_commit_id = NULL;
10646 struct got_commit_object *new_commit = NULL;
10647 char *new_commit_brief_str = NULL;
10648 struct got_object_id *yca_id = NULL;
10649 struct got_commit_object *yca_commit = NULL;
10650 char *yca_id_str = NULL, *yca_brief_str = NULL;
10651 char *custom_refs_str;
10653 if (asprintf(&custom_refs_str, "formerly %s", branch_name) == -1)
10654 return got_error_from_errno("asprintf");
10656 err = print_commit(old_commit, old_commit_id, repo, NULL, NULL, NULL,
10657 0, 0, refs_idmap, custom_refs_str);
10658 if (err)
10659 goto done;
10661 err = got_object_resolve_id_str(&new_commit_id, repo, new_id_str);
10662 if (err)
10663 goto done;
10665 refs = got_reflist_object_id_map_lookup(refs_idmap, new_commit_id);
10666 if (refs) {
10667 err = build_refs_str(&refs_str, refs, new_commit_id, repo, 0);
10668 if (err)
10669 goto done;
10672 err = got_object_open_as_commit(&new_commit, repo, new_commit_id);
10673 if (err)
10674 goto done;
10676 err = get_commit_brief_str(&new_commit_brief_str, new_commit);
10677 if (err)
10678 goto done;
10680 err = got_commit_graph_find_youngest_common_ancestor(&yca_id,
10681 old_commit_id, new_commit_id, 1, repo, check_cancelled, NULL);
10682 if (err)
10683 goto done;
10685 printf("has become commit %s%s%s%s\n %s\n", new_id_str,
10686 refs_str ? " (" : "", refs_str ? refs_str : "",
10687 refs_str ? ")" : "", new_commit_brief_str);
10688 if (yca_id && got_object_id_cmp(yca_id, new_commit_id) != 0 &&
10689 got_object_id_cmp(yca_id, old_commit_id) != 0) {
10690 free(refs_str);
10691 refs_str = NULL;
10693 err = got_object_open_as_commit(&yca_commit, repo, yca_id);
10694 if (err)
10695 goto done;
10697 err = get_commit_brief_str(&yca_brief_str, yca_commit);
10698 if (err)
10699 goto done;
10701 err = got_object_id_str(&yca_id_str, yca_id);
10702 if (err)
10703 goto done;
10705 refs = got_reflist_object_id_map_lookup(refs_idmap, yca_id);
10706 if (refs) {
10707 err = build_refs_str(&refs_str, refs, yca_id, repo, 0);
10708 if (err)
10709 goto done;
10711 printf("history forked at %s%s%s%s\n %s\n",
10712 yca_id_str,
10713 refs_str ? " (" : "", refs_str ? refs_str : "",
10714 refs_str ? ")" : "", yca_brief_str);
10716 done:
10717 free(custom_refs_str);
10718 free(new_commit_id);
10719 free(refs_str);
10720 free(yca_id);
10721 free(yca_id_str);
10722 free(yca_brief_str);
10723 if (new_commit)
10724 got_object_commit_close(new_commit);
10725 if (yca_commit)
10726 got_object_commit_close(yca_commit);
10728 return NULL;
10731 static const struct got_error *
10732 worktree_has_logmsg_ref(const char *caller, struct got_worktree *worktree,
10733 struct got_repository *repo)
10735 const struct got_error *err;
10736 struct got_reflist_head refs;
10737 struct got_reflist_entry *re;
10738 char *uuidstr = NULL;
10739 static char msg[160];
10741 TAILQ_INIT(&refs);
10743 err = got_worktree_get_uuid(&uuidstr, worktree);
10744 if (err)
10745 goto done;
10747 err = got_ref_list(&refs, repo, "refs/got/worktree",
10748 got_ref_cmp_by_name, repo);
10749 if (err)
10750 goto done;
10752 TAILQ_FOREACH(re, &refs, entry) {
10753 const char *cmd, *refname, *type;
10755 refname = got_ref_get_name(re->ref);
10757 if (strncmp(refname, GOT_WORKTREE_CHERRYPICK_REF_PREFIX,
10758 GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN) == 0) {
10759 refname += GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN + 1;
10760 cmd = "cherrypick";
10761 type = "cherrypicked";
10762 } else if (strncmp(refname, GOT_WORKTREE_BACKOUT_REF_PREFIX,
10763 GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN) == 0) {
10764 refname += GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN + 1;
10765 cmd = "backout";
10766 type = "backed-out";
10767 } else
10768 continue;
10770 if (strncmp(refname, uuidstr, GOT_WORKTREE_UUID_STRLEN) != 0)
10771 continue;
10773 snprintf(msg, sizeof(msg),
10774 "work tree has references created by %s commits which "
10775 "must be removed with 'got %s -X' before running the %s "
10776 "command", type, cmd, caller);
10777 err = got_error_msg(GOT_ERR_WORKTREE_META, msg);
10778 goto done;
10781 done:
10782 free(uuidstr);
10783 got_ref_list_free(&refs);
10784 return err;
10787 static const struct got_error *
10788 process_backup_refs(const char *backup_ref_prefix,
10789 const char *wanted_branch_name,
10790 int delete, struct got_repository *repo)
10792 const struct got_error *err;
10793 struct got_reflist_head refs, backup_refs;
10794 struct got_reflist_entry *re;
10795 const size_t backup_ref_prefix_len = strlen(backup_ref_prefix);
10796 struct got_object_id *old_commit_id = NULL;
10797 char *branch_name = NULL;
10798 struct got_commit_object *old_commit = NULL;
10799 struct got_reflist_object_id_map *refs_idmap = NULL;
10800 int wanted_branch_found = 0;
10802 TAILQ_INIT(&refs);
10803 TAILQ_INIT(&backup_refs);
10805 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
10806 if (err)
10807 return err;
10809 err = got_reflist_object_id_map_create(&refs_idmap, &refs, repo);
10810 if (err)
10811 goto done;
10813 if (wanted_branch_name) {
10814 if (strncmp(wanted_branch_name, "refs/heads/", 11) == 0)
10815 wanted_branch_name += 11;
10818 err = got_ref_list(&backup_refs, repo, backup_ref_prefix,
10819 got_ref_cmp_by_commit_timestamp_descending, repo);
10820 if (err)
10821 goto done;
10823 TAILQ_FOREACH(re, &backup_refs, entry) {
10824 const char *refname = got_ref_get_name(re->ref);
10825 char *slash;
10827 err = check_cancelled(NULL);
10828 if (err)
10829 break;
10831 err = got_ref_resolve(&old_commit_id, repo, re->ref);
10832 if (err)
10833 break;
10835 err = got_object_open_as_commit(&old_commit, repo,
10836 old_commit_id);
10837 if (err)
10838 break;
10840 if (strncmp(backup_ref_prefix, refname,
10841 backup_ref_prefix_len) == 0)
10842 refname += backup_ref_prefix_len;
10844 while (refname[0] == '/')
10845 refname++;
10847 branch_name = strdup(refname);
10848 if (branch_name == NULL) {
10849 err = got_error_from_errno("strdup");
10850 break;
10852 slash = strrchr(branch_name, '/');
10853 if (slash) {
10854 *slash = '\0';
10855 refname += strlen(branch_name) + 1;
10858 if (wanted_branch_name == NULL ||
10859 strcmp(wanted_branch_name, branch_name) == 0) {
10860 wanted_branch_found = 1;
10861 if (delete) {
10862 err = delete_backup_ref(re->ref,
10863 old_commit_id, repo);
10864 } else {
10865 err = print_backup_ref(branch_name, refname,
10866 old_commit_id, old_commit, refs_idmap,
10867 repo);
10869 if (err)
10870 break;
10873 free(old_commit_id);
10874 old_commit_id = NULL;
10875 free(branch_name);
10876 branch_name = NULL;
10877 got_object_commit_close(old_commit);
10878 old_commit = NULL;
10881 if (wanted_branch_name && !wanted_branch_found) {
10882 err = got_error_fmt(GOT_ERR_NOT_REF,
10883 "%s/%s/", backup_ref_prefix, wanted_branch_name);
10885 done:
10886 if (refs_idmap)
10887 got_reflist_object_id_map_free(refs_idmap);
10888 got_ref_list_free(&refs);
10889 got_ref_list_free(&backup_refs);
10890 free(old_commit_id);
10891 free(branch_name);
10892 if (old_commit)
10893 got_object_commit_close(old_commit);
10894 return err;
10897 static const struct got_error *
10898 abort_progress(void *arg, unsigned char status, const char *path)
10901 * Unversioned files should not clutter progress output when
10902 * an operation is aborted.
10904 if (status == GOT_STATUS_UNVERSIONED)
10905 return NULL;
10907 return update_progress(arg, status, path);
10910 static const struct got_error *
10911 cmd_rebase(int argc, char *argv[])
10913 const struct got_error *error = NULL;
10914 struct got_worktree *worktree = NULL;
10915 struct got_repository *repo = NULL;
10916 struct got_fileindex *fileindex = NULL;
10917 char *cwd = NULL, *committer = NULL, *gitconfig_path = NULL;
10918 struct got_reference *branch = NULL;
10919 struct got_reference *new_base_branch = NULL, *tmp_branch = NULL;
10920 struct got_object_id *commit_id = NULL, *parent_id = NULL;
10921 struct got_object_id *resume_commit_id = NULL;
10922 struct got_object_id *branch_head_commit_id = NULL, *yca_id = NULL;
10923 struct got_object_id *head_commit_id = NULL;
10924 struct got_reference *head_ref = NULL;
10925 struct got_commit_object *commit = NULL;
10926 int ch, rebase_in_progress = 0, abort_rebase = 0, continue_rebase = 0;
10927 int histedit_in_progress = 0, merge_in_progress = 0;
10928 int create_backup = 1, list_backups = 0, delete_backups = 0;
10929 struct got_object_id_queue commits;
10930 struct got_pathlist_head merged_paths;
10931 const struct got_object_id_queue *parent_ids;
10932 struct got_object_qid *qid, *pid;
10933 struct got_update_progress_arg upa;
10934 int *pack_fds = NULL;
10936 STAILQ_INIT(&commits);
10937 TAILQ_INIT(&merged_paths);
10938 memset(&upa, 0, sizeof(upa));
10940 while ((ch = getopt(argc, argv, "aclX")) != -1) {
10941 switch (ch) {
10942 case 'a':
10943 abort_rebase = 1;
10944 break;
10945 case 'c':
10946 continue_rebase = 1;
10947 break;
10948 case 'l':
10949 list_backups = 1;
10950 break;
10951 case 'X':
10952 delete_backups = 1;
10953 break;
10954 default:
10955 usage_rebase();
10956 /* NOTREACHED */
10960 argc -= optind;
10961 argv += optind;
10963 #ifndef PROFILE
10964 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
10965 "unveil", NULL) == -1)
10966 err(1, "pledge");
10967 #endif
10968 if (list_backups) {
10969 if (abort_rebase)
10970 option_conflict('l', 'a');
10971 if (continue_rebase)
10972 option_conflict('l', 'c');
10973 if (delete_backups)
10974 option_conflict('l', 'X');
10975 if (argc != 0 && argc != 1)
10976 usage_rebase();
10977 } else if (delete_backups) {
10978 if (abort_rebase)
10979 option_conflict('X', 'a');
10980 if (continue_rebase)
10981 option_conflict('X', 'c');
10982 if (list_backups)
10983 option_conflict('l', 'X');
10984 if (argc != 0 && argc != 1)
10985 usage_rebase();
10986 } else {
10987 if (abort_rebase && continue_rebase)
10988 usage_rebase();
10989 else if (abort_rebase || continue_rebase) {
10990 if (argc != 0)
10991 usage_rebase();
10992 } else if (argc != 1)
10993 usage_rebase();
10996 cwd = getcwd(NULL, 0);
10997 if (cwd == NULL) {
10998 error = got_error_from_errno("getcwd");
10999 goto done;
11002 error = got_repo_pack_fds_open(&pack_fds);
11003 if (error != NULL)
11004 goto done;
11006 error = got_worktree_open(&worktree, cwd);
11007 if (error) {
11008 if (list_backups || delete_backups) {
11009 if (error->code != GOT_ERR_NOT_WORKTREE)
11010 goto done;
11011 } else {
11012 if (error->code == GOT_ERR_NOT_WORKTREE)
11013 error = wrap_not_worktree_error(error,
11014 "rebase", cwd);
11015 goto done;
11019 error = get_gitconfig_path(&gitconfig_path);
11020 if (error)
11021 goto done;
11022 error = got_repo_open(&repo,
11023 worktree ? got_worktree_get_repo_path(worktree) : cwd,
11024 gitconfig_path, pack_fds);
11025 if (error != NULL)
11026 goto done;
11028 if (worktree != NULL && !list_backups && !delete_backups) {
11029 error = worktree_has_logmsg_ref("rebase", worktree, repo);
11030 if (error)
11031 goto done;
11034 error = get_author(&committer, repo, worktree);
11035 if (error && error->code != GOT_ERR_COMMIT_NO_AUTHOR)
11036 goto done;
11038 error = apply_unveil(got_repo_get_path(repo), 0,
11039 worktree ? got_worktree_get_root_path(worktree) : NULL);
11040 if (error)
11041 goto done;
11043 if (list_backups || delete_backups) {
11044 error = process_backup_refs(
11045 GOT_WORKTREE_REBASE_BACKUP_REF_PREFIX,
11046 argc == 1 ? argv[0] : NULL, delete_backups, repo);
11047 goto done; /* nothing else to do */
11050 error = got_worktree_histedit_in_progress(&histedit_in_progress,
11051 worktree);
11052 if (error)
11053 goto done;
11054 if (histedit_in_progress) {
11055 error = got_error(GOT_ERR_HISTEDIT_BUSY);
11056 goto done;
11059 error = got_worktree_merge_in_progress(&merge_in_progress,
11060 worktree, repo);
11061 if (error)
11062 goto done;
11063 if (merge_in_progress) {
11064 error = got_error(GOT_ERR_MERGE_BUSY);
11065 goto done;
11068 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
11069 if (error)
11070 goto done;
11072 if (abort_rebase) {
11073 if (!rebase_in_progress) {
11074 error = got_error(GOT_ERR_NOT_REBASING);
11075 goto done;
11077 error = got_worktree_rebase_continue(&resume_commit_id,
11078 &new_base_branch, &tmp_branch, &branch, &fileindex,
11079 worktree, repo);
11080 if (error)
11081 goto done;
11082 printf("Switching work tree to %s\n",
11083 got_ref_get_symref_target(new_base_branch));
11084 error = got_worktree_rebase_abort(worktree, fileindex, repo,
11085 new_base_branch, abort_progress, &upa);
11086 if (error)
11087 goto done;
11088 printf("Rebase of %s aborted\n", got_ref_get_name(branch));
11089 print_merge_progress_stats(&upa);
11090 goto done; /* nothing else to do */
11093 if (continue_rebase) {
11094 if (!rebase_in_progress) {
11095 error = got_error(GOT_ERR_NOT_REBASING);
11096 goto done;
11098 error = got_worktree_rebase_continue(&resume_commit_id,
11099 &new_base_branch, &tmp_branch, &branch, &fileindex,
11100 worktree, repo);
11101 if (error)
11102 goto done;
11104 error = rebase_commit(NULL, worktree, fileindex, tmp_branch,
11105 committer, resume_commit_id, repo);
11106 if (error)
11107 goto done;
11109 yca_id = got_object_id_dup(resume_commit_id);
11110 if (yca_id == NULL) {
11111 error = got_error_from_errno("got_object_id_dup");
11112 goto done;
11114 } else {
11115 error = got_ref_open(&branch, repo, argv[0], 0);
11116 if (error != NULL)
11117 goto done;
11118 if (strncmp(got_ref_get_name(branch), "refs/heads/", 11) != 0) {
11119 error = got_error_msg(GOT_ERR_COMMIT_BRANCH,
11120 "will not rebase a branch which lives outside "
11121 "the \"refs/heads/\" reference namespace");
11122 goto done;
11126 error = got_ref_resolve(&branch_head_commit_id, repo, branch);
11127 if (error)
11128 goto done;
11130 if (!continue_rebase) {
11131 struct got_object_id *base_commit_id;
11133 error = got_ref_open(&head_ref, repo,
11134 got_worktree_get_head_ref_name(worktree), 0);
11135 if (error)
11136 goto done;
11137 error = got_ref_resolve(&head_commit_id, repo, head_ref);
11138 if (error)
11139 goto done;
11140 base_commit_id = got_worktree_get_base_commit_id(worktree);
11141 if (got_object_id_cmp(base_commit_id, head_commit_id) != 0) {
11142 error = got_error(GOT_ERR_REBASE_OUT_OF_DATE);
11143 goto done;
11146 error = got_commit_graph_find_youngest_common_ancestor(&yca_id,
11147 base_commit_id, branch_head_commit_id, 1, repo,
11148 check_cancelled, NULL);
11149 if (error)
11150 goto done;
11151 if (yca_id == NULL) {
11152 error = got_error_msg(GOT_ERR_ANCESTRY,
11153 "specified branch shares no common ancestry "
11154 "with work tree's branch");
11155 goto done;
11158 error = check_same_branch(base_commit_id, branch, yca_id, repo);
11159 if (error) {
11160 if (error->code != GOT_ERR_ANCESTRY)
11161 goto done;
11162 error = NULL;
11163 } else {
11164 struct got_pathlist_head paths;
11165 printf("%s is already based on %s\n",
11166 got_ref_get_name(branch),
11167 got_worktree_get_head_ref_name(worktree));
11168 error = switch_head_ref(branch, branch_head_commit_id,
11169 worktree, repo);
11170 if (error)
11171 goto done;
11172 error = got_worktree_set_base_commit_id(worktree, repo,
11173 branch_head_commit_id);
11174 if (error)
11175 goto done;
11176 TAILQ_INIT(&paths);
11177 error = got_pathlist_append(&paths, "", NULL);
11178 if (error)
11179 goto done;
11180 error = got_worktree_checkout_files(worktree,
11181 &paths, repo, update_progress, &upa,
11182 check_cancelled, NULL);
11183 got_pathlist_free(&paths, GOT_PATHLIST_FREE_NONE);
11184 if (error)
11185 goto done;
11186 if (upa.did_something) {
11187 char *id_str;
11188 error = got_object_id_str(&id_str,
11189 branch_head_commit_id);
11190 if (error)
11191 goto done;
11192 printf("Updated to %s: %s\n",
11193 got_worktree_get_head_ref_name(worktree),
11194 id_str);
11195 free(id_str);
11196 } else
11197 printf("Already up-to-date\n");
11198 print_update_progress_stats(&upa);
11199 goto done;
11203 commit_id = branch_head_commit_id;
11204 error = got_object_open_as_commit(&commit, repo, commit_id);
11205 if (error)
11206 goto done;
11208 parent_ids = got_object_commit_get_parent_ids(commit);
11209 pid = STAILQ_FIRST(parent_ids);
11210 if (pid == NULL) {
11211 error = got_error(GOT_ERR_EMPTY_REBASE);
11212 goto done;
11214 error = collect_commits(&commits, commit_id, &pid->id,
11215 yca_id, got_worktree_get_path_prefix(worktree),
11216 GOT_ERR_REBASE_PATH, repo);
11217 got_object_commit_close(commit);
11218 commit = NULL;
11219 if (error)
11220 goto done;
11222 if (!continue_rebase) {
11223 error = got_worktree_rebase_prepare(&new_base_branch,
11224 &tmp_branch, &fileindex, worktree, branch, repo);
11225 if (error)
11226 goto done;
11229 if (STAILQ_EMPTY(&commits)) {
11230 if (continue_rebase) {
11231 error = rebase_complete(worktree, fileindex,
11232 branch, new_base_branch, tmp_branch, repo,
11233 create_backup);
11234 goto done;
11235 } else {
11236 /* Fast-forward the reference of the branch. */
11237 struct got_object_id *new_head_commit_id;
11238 char *id_str;
11239 error = got_ref_resolve(&new_head_commit_id, repo,
11240 new_base_branch);
11241 if (error)
11242 goto done;
11243 error = got_object_id_str(&id_str, new_head_commit_id);
11244 if (error)
11245 goto done;
11246 printf("Forwarding %s to commit %s\n",
11247 got_ref_get_name(branch), id_str);
11248 free(id_str);
11249 error = got_ref_change_ref(branch,
11250 new_head_commit_id);
11251 if (error)
11252 goto done;
11253 /* No backup needed since objects did not change. */
11254 create_backup = 0;
11258 pid = NULL;
11259 STAILQ_FOREACH(qid, &commits, entry) {
11261 commit_id = &qid->id;
11262 parent_id = pid ? &pid->id : yca_id;
11263 pid = qid;
11265 memset(&upa, 0, sizeof(upa));
11266 error = got_worktree_rebase_merge_files(&merged_paths,
11267 worktree, fileindex, parent_id, commit_id, repo,
11268 update_progress, &upa, check_cancelled, NULL);
11269 if (error)
11270 goto done;
11272 print_merge_progress_stats(&upa);
11273 if (upa.conflicts > 0 || upa.missing > 0 ||
11274 upa.not_deleted > 0 || upa.unversioned > 0) {
11275 if (upa.conflicts > 0) {
11276 error = show_rebase_merge_conflict(&qid->id,
11277 repo);
11278 if (error)
11279 goto done;
11281 got_pathlist_free(&merged_paths, GOT_PATHLIST_FREE_PATH);
11282 break;
11285 error = rebase_commit(&merged_paths, worktree, fileindex,
11286 tmp_branch, committer, commit_id, repo);
11287 got_pathlist_free(&merged_paths, GOT_PATHLIST_FREE_PATH);
11288 if (error)
11289 goto done;
11292 if (upa.conflicts > 0 || upa.missing > 0 ||
11293 upa.not_deleted > 0 || upa.unversioned > 0) {
11294 error = got_worktree_rebase_postpone(worktree, fileindex);
11295 if (error)
11296 goto done;
11297 if (upa.conflicts > 0 && upa.missing == 0 &&
11298 upa.not_deleted == 0 && upa.unversioned == 0) {
11299 error = got_error_msg(GOT_ERR_CONFLICTS,
11300 "conflicts must be resolved before rebasing "
11301 "can continue");
11302 } else if (upa.conflicts > 0) {
11303 error = got_error_msg(GOT_ERR_CONFLICTS,
11304 "conflicts must be resolved before rebasing "
11305 "can continue; changes destined for some "
11306 "files were not yet merged and should be "
11307 "merged manually if required before the "
11308 "rebase operation is continued");
11309 } else {
11310 error = got_error_msg(GOT_ERR_CONFLICTS,
11311 "changes destined for some files were not "
11312 "yet merged and should be merged manually "
11313 "if required before the rebase operation "
11314 "is continued");
11316 } else
11317 error = rebase_complete(worktree, fileindex, branch,
11318 new_base_branch, tmp_branch, repo, create_backup);
11319 done:
11320 free(cwd);
11321 free(committer);
11322 free(gitconfig_path);
11323 got_object_id_queue_free(&commits);
11324 free(branch_head_commit_id);
11325 free(resume_commit_id);
11326 free(head_commit_id);
11327 free(yca_id);
11328 if (commit)
11329 got_object_commit_close(commit);
11330 if (branch)
11331 got_ref_close(branch);
11332 if (new_base_branch)
11333 got_ref_close(new_base_branch);
11334 if (tmp_branch)
11335 got_ref_close(tmp_branch);
11336 if (head_ref)
11337 got_ref_close(head_ref);
11338 if (worktree)
11339 got_worktree_close(worktree);
11340 if (repo) {
11341 const struct got_error *close_err = got_repo_close(repo);
11342 if (error == NULL)
11343 error = close_err;
11345 if (pack_fds) {
11346 const struct got_error *pack_err =
11347 got_repo_pack_fds_close(pack_fds);
11348 if (error == NULL)
11349 error = pack_err;
11351 return error;
11354 __dead static void
11355 usage_histedit(void)
11357 fprintf(stderr, "usage: %s histedit [-aceflmX] [-F histedit-script] "
11358 "[branch]\n", getprogname());
11359 exit(1);
11362 #define GOT_HISTEDIT_PICK 'p'
11363 #define GOT_HISTEDIT_EDIT 'e'
11364 #define GOT_HISTEDIT_FOLD 'f'
11365 #define GOT_HISTEDIT_DROP 'd'
11366 #define GOT_HISTEDIT_MESG 'm'
11368 static const struct got_histedit_cmd {
11369 unsigned char code;
11370 const char *name;
11371 const char *desc;
11372 } got_histedit_cmds[] = {
11373 { GOT_HISTEDIT_PICK, "pick", "use commit" },
11374 { GOT_HISTEDIT_EDIT, "edit", "use commit but stop for amending" },
11375 { GOT_HISTEDIT_FOLD, "fold", "combine with next commit that will "
11376 "be used" },
11377 { GOT_HISTEDIT_DROP, "drop", "remove commit from history" },
11378 { GOT_HISTEDIT_MESG, "mesg",
11379 "single-line log message for commit above (open editor if empty)" },
11382 struct got_histedit_list_entry {
11383 TAILQ_ENTRY(got_histedit_list_entry) entry;
11384 struct got_object_id *commit_id;
11385 const struct got_histedit_cmd *cmd;
11386 char *logmsg;
11388 TAILQ_HEAD(got_histedit_list, got_histedit_list_entry);
11390 static const struct got_error *
11391 histedit_write_commit(struct got_object_id *commit_id, const char *cmdname,
11392 FILE *f, struct got_repository *repo)
11394 const struct got_error *err = NULL;
11395 char *logmsg = NULL, *id_str = NULL;
11396 struct got_commit_object *commit = NULL;
11397 int n;
11399 err = got_object_open_as_commit(&commit, repo, commit_id);
11400 if (err)
11401 goto done;
11403 err = get_short_logmsg(&logmsg, 34, commit);
11404 if (err)
11405 goto done;
11407 err = got_object_id_str(&id_str, commit_id);
11408 if (err)
11409 goto done;
11411 n = fprintf(f, "%s %s %s\n", cmdname, id_str, logmsg);
11412 if (n < 0)
11413 err = got_ferror(f, GOT_ERR_IO);
11414 done:
11415 if (commit)
11416 got_object_commit_close(commit);
11417 free(id_str);
11418 free(logmsg);
11419 return err;
11422 static const struct got_error *
11423 histedit_write_commit_list(struct got_object_id_queue *commits,
11424 FILE *f, int edit_logmsg_only, int fold_only, int edit_only,
11425 struct got_repository *repo)
11427 const struct got_error *err = NULL;
11428 struct got_object_qid *qid;
11429 const char *histedit_cmd = NULL;
11431 if (STAILQ_EMPTY(commits))
11432 return got_error(GOT_ERR_EMPTY_HISTEDIT);
11434 STAILQ_FOREACH(qid, commits, entry) {
11435 histedit_cmd = got_histedit_cmds[0].name;
11436 if (edit_only)
11437 histedit_cmd = "edit";
11438 else if (fold_only && STAILQ_NEXT(qid, entry) != NULL)
11439 histedit_cmd = "fold";
11440 err = histedit_write_commit(&qid->id, histedit_cmd, f, repo);
11441 if (err)
11442 break;
11443 if (edit_logmsg_only) {
11444 int n = fprintf(f, "%c\n", GOT_HISTEDIT_MESG);
11445 if (n < 0) {
11446 err = got_ferror(f, GOT_ERR_IO);
11447 break;
11452 return err;
11455 static const struct got_error *
11456 write_cmd_list(FILE *f, const char *branch_name,
11457 struct got_object_id_queue *commits)
11459 const struct got_error *err = NULL;
11460 size_t i;
11461 int n;
11462 char *id_str;
11463 struct got_object_qid *qid;
11465 qid = STAILQ_FIRST(commits);
11466 err = got_object_id_str(&id_str, &qid->id);
11467 if (err)
11468 return err;
11470 n = fprintf(f,
11471 "# Editing the history of branch '%s' starting at\n"
11472 "# commit %s\n"
11473 "# Commits will be processed in order from top to "
11474 "bottom of this file.\n", branch_name, id_str);
11475 if (n < 0) {
11476 err = got_ferror(f, GOT_ERR_IO);
11477 goto done;
11480 n = fprintf(f, "# Available histedit commands:\n");
11481 if (n < 0) {
11482 err = got_ferror(f, GOT_ERR_IO);
11483 goto done;
11486 for (i = 0; i < nitems(got_histedit_cmds); i++) {
11487 const struct got_histedit_cmd *cmd = &got_histedit_cmds[i];
11488 n = fprintf(f, "# %s (%c): %s\n", cmd->name, cmd->code,
11489 cmd->desc);
11490 if (n < 0) {
11491 err = got_ferror(f, GOT_ERR_IO);
11492 break;
11495 done:
11496 free(id_str);
11497 return err;
11500 static const struct got_error *
11501 histedit_syntax_error(int lineno)
11503 static char msg[42];
11504 int ret;
11506 ret = snprintf(msg, sizeof(msg), "histedit syntax error on line %d",
11507 lineno);
11508 if (ret < 0 || (size_t)ret >= sizeof(msg))
11509 return got_error(GOT_ERR_HISTEDIT_SYNTAX);
11511 return got_error_msg(GOT_ERR_HISTEDIT_SYNTAX, msg);
11514 static const struct got_error *
11515 append_folded_commit_msg(char **new_msg, struct got_histedit_list_entry *hle,
11516 char *logmsg, struct got_repository *repo)
11518 const struct got_error *err;
11519 struct got_commit_object *folded_commit = NULL;
11520 char *id_str, *folded_logmsg = NULL;
11522 err = got_object_id_str(&id_str, hle->commit_id);
11523 if (err)
11524 return err;
11526 err = got_object_open_as_commit(&folded_commit, repo, hle->commit_id);
11527 if (err)
11528 goto done;
11530 err = got_object_commit_get_logmsg(&folded_logmsg, folded_commit);
11531 if (err)
11532 goto done;
11533 if (asprintf(new_msg, "%s%s# log message of folded commit %s: %s",
11534 logmsg ? logmsg : "", logmsg ? "\n" : "", id_str,
11535 folded_logmsg) == -1) {
11536 err = got_error_from_errno("asprintf");
11538 done:
11539 if (folded_commit)
11540 got_object_commit_close(folded_commit);
11541 free(id_str);
11542 free(folded_logmsg);
11543 return err;
11546 static struct got_histedit_list_entry *
11547 get_folded_commits(struct got_histedit_list_entry *hle)
11549 struct got_histedit_list_entry *prev, *folded = NULL;
11551 prev = TAILQ_PREV(hle, got_histedit_list, entry);
11552 while (prev && (prev->cmd->code == GOT_HISTEDIT_FOLD ||
11553 prev->cmd->code == GOT_HISTEDIT_DROP)) {
11554 if (prev->cmd->code == GOT_HISTEDIT_FOLD)
11555 folded = prev;
11556 prev = TAILQ_PREV(prev, got_histedit_list, entry);
11559 return folded;
11562 static const struct got_error *
11563 histedit_edit_logmsg(struct got_histedit_list_entry *hle,
11564 struct got_repository *repo)
11566 char *logmsg_path = NULL, *id_str = NULL, *orig_logmsg = NULL;
11567 char *logmsg = NULL, *new_msg = NULL, *editor = NULL;
11568 const struct got_error *err = NULL;
11569 struct got_commit_object *commit = NULL;
11570 int logmsg_len;
11571 int fd;
11572 struct got_histedit_list_entry *folded = NULL;
11574 err = got_object_open_as_commit(&commit, repo, hle->commit_id);
11575 if (err)
11576 return err;
11578 folded = get_folded_commits(hle);
11579 if (folded) {
11580 while (folded != hle) {
11581 if (folded->cmd->code == GOT_HISTEDIT_DROP) {
11582 folded = TAILQ_NEXT(folded, entry);
11583 continue;
11585 err = append_folded_commit_msg(&new_msg, folded,
11586 logmsg, repo);
11587 if (err)
11588 goto done;
11589 free(logmsg);
11590 logmsg = new_msg;
11591 folded = TAILQ_NEXT(folded, entry);
11595 err = got_object_id_str(&id_str, hle->commit_id);
11596 if (err)
11597 goto done;
11598 err = got_object_commit_get_logmsg(&orig_logmsg, commit);
11599 if (err)
11600 goto done;
11601 logmsg_len = asprintf(&new_msg,
11602 "%s\n# original log message of commit %s: %s",
11603 logmsg ? logmsg : "", id_str, orig_logmsg);
11604 if (logmsg_len == -1) {
11605 err = got_error_from_errno("asprintf");
11606 goto done;
11608 free(logmsg);
11609 logmsg = new_msg;
11611 err = got_object_id_str(&id_str, hle->commit_id);
11612 if (err)
11613 goto done;
11615 err = got_opentemp_named_fd(&logmsg_path, &fd,
11616 GOT_TMPDIR_STR "/got-logmsg", "");
11617 if (err)
11618 goto done;
11620 write(fd, logmsg, logmsg_len);
11621 close(fd);
11623 err = get_editor(&editor);
11624 if (err)
11625 goto done;
11627 err = edit_logmsg(&hle->logmsg, editor, logmsg_path, logmsg,
11628 logmsg_len, 0);
11629 if (err) {
11630 if (err->code != GOT_ERR_COMMIT_MSG_EMPTY)
11631 goto done;
11632 err = NULL;
11633 hle->logmsg = strdup(new_msg);
11634 if (hle->logmsg == NULL)
11635 err = got_error_from_errno("strdup");
11637 done:
11638 if (logmsg_path && unlink(logmsg_path) != 0 && err == NULL)
11639 err = got_error_from_errno2("unlink", logmsg_path);
11640 free(logmsg_path);
11641 free(logmsg);
11642 free(orig_logmsg);
11643 free(editor);
11644 if (commit)
11645 got_object_commit_close(commit);
11646 return err;
11649 static const struct got_error *
11650 histedit_parse_list(struct got_histedit_list *histedit_cmds,
11651 FILE *f, struct got_repository *repo)
11653 const struct got_error *err = NULL;
11654 char *line = NULL, *p, *end;
11655 size_t i, size;
11656 ssize_t len;
11657 int lineno = 0, lastcmd = -1;
11658 const struct got_histedit_cmd *cmd;
11659 struct got_object_id *commit_id = NULL;
11660 struct got_histedit_list_entry *hle = NULL;
11662 for (;;) {
11663 len = getline(&line, &size, f);
11664 if (len == -1) {
11665 const struct got_error *getline_err;
11666 if (feof(f))
11667 break;
11668 getline_err = got_error_from_errno("getline");
11669 err = got_ferror(f, getline_err->code);
11670 break;
11672 lineno++;
11673 p = line;
11674 while (isspace((unsigned char)p[0]))
11675 p++;
11676 if (p[0] == '#' || p[0] == '\0') {
11677 free(line);
11678 line = NULL;
11679 continue;
11681 cmd = NULL;
11682 for (i = 0; i < nitems(got_histedit_cmds); i++) {
11683 cmd = &got_histedit_cmds[i];
11684 if (strncmp(cmd->name, p, strlen(cmd->name)) == 0 &&
11685 isspace((unsigned char)p[strlen(cmd->name)])) {
11686 p += strlen(cmd->name);
11687 break;
11689 if (p[0] == cmd->code && isspace((unsigned char)p[1])) {
11690 p++;
11691 break;
11694 if (i == nitems(got_histedit_cmds)) {
11695 err = histedit_syntax_error(lineno);
11696 break;
11698 while (isspace((unsigned char)p[0]))
11699 p++;
11700 if (cmd->code == GOT_HISTEDIT_MESG) {
11701 if (lastcmd != GOT_HISTEDIT_PICK &&
11702 lastcmd != GOT_HISTEDIT_EDIT) {
11703 err = got_error(GOT_ERR_HISTEDIT_CMD);
11704 break;
11706 if (p[0] == '\0') {
11707 err = histedit_edit_logmsg(hle, repo);
11708 if (err)
11709 break;
11710 } else {
11711 hle->logmsg = strdup(p);
11712 if (hle->logmsg == NULL) {
11713 err = got_error_from_errno("strdup");
11714 break;
11717 free(line);
11718 line = NULL;
11719 lastcmd = cmd->code;
11720 continue;
11721 } else {
11722 end = p;
11723 while (end[0] && !isspace((unsigned char)end[0]))
11724 end++;
11725 *end = '\0';
11727 err = got_object_resolve_id_str(&commit_id, repo, p);
11728 if (err) {
11729 /* override error code */
11730 err = histedit_syntax_error(lineno);
11731 break;
11734 hle = malloc(sizeof(*hle));
11735 if (hle == NULL) {
11736 err = got_error_from_errno("malloc");
11737 break;
11739 hle->cmd = cmd;
11740 hle->commit_id = commit_id;
11741 hle->logmsg = NULL;
11742 commit_id = NULL;
11743 free(line);
11744 line = NULL;
11745 TAILQ_INSERT_TAIL(histedit_cmds, hle, entry);
11746 lastcmd = cmd->code;
11749 free(line);
11750 free(commit_id);
11751 return err;
11754 static const struct got_error *
11755 histedit_check_script(struct got_histedit_list *histedit_cmds,
11756 struct got_object_id_queue *commits, struct got_repository *repo)
11758 const struct got_error *err = NULL;
11759 struct got_object_qid *qid;
11760 struct got_histedit_list_entry *hle;
11761 static char msg[92];
11762 char *id_str;
11764 if (TAILQ_EMPTY(histedit_cmds))
11765 return got_error_msg(GOT_ERR_EMPTY_HISTEDIT,
11766 "histedit script contains no commands");
11767 if (STAILQ_EMPTY(commits))
11768 return got_error(GOT_ERR_EMPTY_HISTEDIT);
11770 TAILQ_FOREACH(hle, histedit_cmds, entry) {
11771 struct got_histedit_list_entry *hle2;
11772 TAILQ_FOREACH(hle2, histedit_cmds, entry) {
11773 if (hle == hle2)
11774 continue;
11775 if (got_object_id_cmp(hle->commit_id,
11776 hle2->commit_id) != 0)
11777 continue;
11778 err = got_object_id_str(&id_str, hle->commit_id);
11779 if (err)
11780 return err;
11781 snprintf(msg, sizeof(msg), "commit %s is listed "
11782 "more than once in histedit script", id_str);
11783 free(id_str);
11784 return got_error_msg(GOT_ERR_HISTEDIT_CMD, msg);
11788 STAILQ_FOREACH(qid, commits, entry) {
11789 TAILQ_FOREACH(hle, histedit_cmds, entry) {
11790 if (got_object_id_cmp(&qid->id, hle->commit_id) == 0)
11791 break;
11793 if (hle == NULL) {
11794 err = got_object_id_str(&id_str, &qid->id);
11795 if (err)
11796 return err;
11797 snprintf(msg, sizeof(msg),
11798 "commit %s missing from histedit script", id_str);
11799 free(id_str);
11800 return got_error_msg(GOT_ERR_HISTEDIT_CMD, msg);
11804 hle = TAILQ_LAST(histedit_cmds, got_histedit_list);
11805 if (hle && hle->cmd->code == GOT_HISTEDIT_FOLD)
11806 return got_error_msg(GOT_ERR_HISTEDIT_CMD,
11807 "last commit in histedit script cannot be folded");
11809 return NULL;
11812 static const struct got_error *
11813 histedit_run_editor(struct got_histedit_list *histedit_cmds,
11814 const char *path, struct got_object_id_queue *commits,
11815 struct got_repository *repo)
11817 const struct got_error *err = NULL;
11818 char *editor;
11819 FILE *f = NULL;
11821 err = get_editor(&editor);
11822 if (err)
11823 return err;
11825 if (spawn_editor(editor, path) == -1) {
11826 err = got_error_from_errno("failed spawning editor");
11827 goto done;
11830 f = fopen(path, "re");
11831 if (f == NULL) {
11832 err = got_error_from_errno("fopen");
11833 goto done;
11835 err = histedit_parse_list(histedit_cmds, f, repo);
11836 if (err)
11837 goto done;
11839 err = histedit_check_script(histedit_cmds, commits, repo);
11840 done:
11841 if (f && fclose(f) == EOF && err == NULL)
11842 err = got_error_from_errno("fclose");
11843 free(editor);
11844 return err;
11847 static const struct got_error *
11848 histedit_edit_list_retry(struct got_histedit_list *, const struct got_error *,
11849 struct got_object_id_queue *, const char *, const char *,
11850 struct got_repository *);
11852 static const struct got_error *
11853 histedit_edit_script(struct got_histedit_list *histedit_cmds,
11854 struct got_object_id_queue *commits, const char *branch_name,
11855 int edit_logmsg_only, int fold_only, int edit_only,
11856 struct got_repository *repo)
11858 const struct got_error *err;
11859 FILE *f = NULL;
11860 char *path = NULL;
11862 err = got_opentemp_named(&path, &f, "got-histedit", "");
11863 if (err)
11864 return err;
11866 err = write_cmd_list(f, branch_name, commits);
11867 if (err)
11868 goto done;
11870 err = histedit_write_commit_list(commits, f, edit_logmsg_only,
11871 fold_only, edit_only, repo);
11872 if (err)
11873 goto done;
11875 if (edit_logmsg_only || fold_only || edit_only) {
11876 rewind(f);
11877 err = histedit_parse_list(histedit_cmds, f, repo);
11878 } else {
11879 if (fclose(f) == EOF) {
11880 err = got_error_from_errno("fclose");
11881 goto done;
11883 f = NULL;
11884 err = histedit_run_editor(histedit_cmds, path, commits, repo);
11885 if (err) {
11886 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
11887 err->code != GOT_ERR_HISTEDIT_CMD)
11888 goto done;
11889 err = histedit_edit_list_retry(histedit_cmds, err,
11890 commits, path, branch_name, repo);
11893 done:
11894 if (f && fclose(f) == EOF && err == NULL)
11895 err = got_error_from_errno("fclose");
11896 if (path && unlink(path) != 0 && err == NULL)
11897 err = got_error_from_errno2("unlink", path);
11898 free(path);
11899 return err;
11902 static const struct got_error *
11903 histedit_save_list(struct got_histedit_list *histedit_cmds,
11904 struct got_worktree *worktree, struct got_repository *repo)
11906 const struct got_error *err = NULL;
11907 char *path = NULL;
11908 FILE *f = NULL;
11909 struct got_histedit_list_entry *hle;
11910 struct got_commit_object *commit = NULL;
11912 err = got_worktree_get_histedit_script_path(&path, worktree);
11913 if (err)
11914 return err;
11916 f = fopen(path, "we");
11917 if (f == NULL) {
11918 err = got_error_from_errno2("fopen", path);
11919 goto done;
11921 TAILQ_FOREACH(hle, histedit_cmds, entry) {
11922 err = histedit_write_commit(hle->commit_id, hle->cmd->name, f,
11923 repo);
11924 if (err)
11925 break;
11927 if (hle->logmsg) {
11928 int n = fprintf(f, "%c %s\n",
11929 GOT_HISTEDIT_MESG, hle->logmsg);
11930 if (n < 0) {
11931 err = got_ferror(f, GOT_ERR_IO);
11932 break;
11936 done:
11937 if (f && fclose(f) == EOF && err == NULL)
11938 err = got_error_from_errno("fclose");
11939 free(path);
11940 if (commit)
11941 got_object_commit_close(commit);
11942 return err;
11945 static void
11946 histedit_free_list(struct got_histedit_list *histedit_cmds)
11948 struct got_histedit_list_entry *hle;
11950 while ((hle = TAILQ_FIRST(histedit_cmds))) {
11951 TAILQ_REMOVE(histedit_cmds, hle, entry);
11952 free(hle);
11956 static const struct got_error *
11957 histedit_load_list(struct got_histedit_list *histedit_cmds,
11958 const char *path, struct got_repository *repo)
11960 const struct got_error *err = NULL;
11961 FILE *f = NULL;
11963 f = fopen(path, "re");
11964 if (f == NULL) {
11965 err = got_error_from_errno2("fopen", path);
11966 goto done;
11969 err = histedit_parse_list(histedit_cmds, f, repo);
11970 done:
11971 if (f && fclose(f) == EOF && err == NULL)
11972 err = got_error_from_errno("fclose");
11973 return err;
11976 static const struct got_error *
11977 histedit_edit_list_retry(struct got_histedit_list *histedit_cmds,
11978 const struct got_error *edit_err, struct got_object_id_queue *commits,
11979 const char *path, const char *branch_name, struct got_repository *repo)
11981 const struct got_error *err = NULL, *prev_err = edit_err;
11982 int resp = ' ';
11984 while (resp != 'c' && resp != 'r' && resp != 'a') {
11985 printf("%s: %s\n(c)ontinue editing, (r)estart editing, "
11986 "or (a)bort: ", getprogname(), prev_err->msg);
11987 resp = getchar();
11988 if (resp == '\n')
11989 resp = getchar();
11990 if (resp == 'c') {
11991 histedit_free_list(histedit_cmds);
11992 err = histedit_run_editor(histedit_cmds, path, commits,
11993 repo);
11994 if (err) {
11995 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
11996 err->code != GOT_ERR_HISTEDIT_CMD)
11997 break;
11998 prev_err = err;
11999 resp = ' ';
12000 continue;
12002 break;
12003 } else if (resp == 'r') {
12004 histedit_free_list(histedit_cmds);
12005 err = histedit_edit_script(histedit_cmds,
12006 commits, branch_name, 0, 0, 0, repo);
12007 if (err) {
12008 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
12009 err->code != GOT_ERR_HISTEDIT_CMD)
12010 break;
12011 prev_err = err;
12012 resp = ' ';
12013 continue;
12015 break;
12016 } else if (resp == 'a') {
12017 err = got_error(GOT_ERR_HISTEDIT_CANCEL);
12018 break;
12019 } else
12020 printf("invalid response '%c'\n", resp);
12023 return err;
12026 static const struct got_error *
12027 histedit_complete(struct got_worktree *worktree,
12028 struct got_fileindex *fileindex, struct got_reference *tmp_branch,
12029 struct got_reference *branch, struct got_repository *repo)
12031 printf("Switching work tree to %s\n",
12032 got_ref_get_symref_target(branch));
12033 return got_worktree_histedit_complete(worktree, fileindex, tmp_branch,
12034 branch, repo);
12037 static const struct got_error *
12038 show_histedit_progress(struct got_commit_object *commit,
12039 struct got_histedit_list_entry *hle, struct got_object_id *new_id)
12041 const struct got_error *err;
12042 char *old_id_str = NULL, *new_id_str = NULL, *logmsg = NULL;
12044 err = got_object_id_str(&old_id_str, hle->commit_id);
12045 if (err)
12046 goto done;
12048 if (new_id) {
12049 err = got_object_id_str(&new_id_str, new_id);
12050 if (err)
12051 goto done;
12054 old_id_str[12] = '\0';
12055 if (new_id_str)
12056 new_id_str[12] = '\0';
12058 if (hle->logmsg) {
12059 logmsg = strdup(hle->logmsg);
12060 if (logmsg == NULL) {
12061 err = got_error_from_errno("strdup");
12062 goto done;
12064 trim_logmsg(logmsg, 42);
12065 } else {
12066 err = get_short_logmsg(&logmsg, 42, commit);
12067 if (err)
12068 goto done;
12071 switch (hle->cmd->code) {
12072 case GOT_HISTEDIT_PICK:
12073 case GOT_HISTEDIT_EDIT:
12074 printf("%s -> %s: %s\n", old_id_str,
12075 new_id_str ? new_id_str : "no-op change", logmsg);
12076 break;
12077 case GOT_HISTEDIT_DROP:
12078 case GOT_HISTEDIT_FOLD:
12079 printf("%s -> %s commit: %s\n", old_id_str, hle->cmd->name,
12080 logmsg);
12081 break;
12082 default:
12083 break;
12085 done:
12086 free(old_id_str);
12087 free(new_id_str);
12088 return err;
12091 static const struct got_error *
12092 histedit_commit(struct got_pathlist_head *merged_paths,
12093 struct got_worktree *worktree, struct got_fileindex *fileindex,
12094 struct got_reference *tmp_branch, struct got_histedit_list_entry *hle,
12095 const char *committer, struct got_repository *repo)
12097 const struct got_error *err;
12098 struct got_commit_object *commit;
12099 struct got_object_id *new_commit_id;
12101 if ((hle->cmd->code == GOT_HISTEDIT_EDIT || get_folded_commits(hle))
12102 && hle->logmsg == NULL) {
12103 err = histedit_edit_logmsg(hle, repo);
12104 if (err)
12105 return err;
12108 err = got_object_open_as_commit(&commit, repo, hle->commit_id);
12109 if (err)
12110 return err;
12112 err = got_worktree_histedit_commit(&new_commit_id, merged_paths,
12113 worktree, fileindex, tmp_branch, committer, commit, hle->commit_id,
12114 hle->logmsg, repo);
12115 if (err) {
12116 if (err->code != GOT_ERR_COMMIT_NO_CHANGES)
12117 goto done;
12118 err = show_histedit_progress(commit, hle, NULL);
12119 } else {
12120 err = show_histedit_progress(commit, hle, new_commit_id);
12121 free(new_commit_id);
12123 done:
12124 got_object_commit_close(commit);
12125 return err;
12128 static const struct got_error *
12129 histedit_skip_commit(struct got_histedit_list_entry *hle,
12130 struct got_worktree *worktree, struct got_repository *repo)
12132 const struct got_error *error;
12133 struct got_commit_object *commit;
12135 error = got_worktree_histedit_skip_commit(worktree, hle->commit_id,
12136 repo);
12137 if (error)
12138 return error;
12140 error = got_object_open_as_commit(&commit, repo, hle->commit_id);
12141 if (error)
12142 return error;
12144 error = show_histedit_progress(commit, hle, NULL);
12145 got_object_commit_close(commit);
12146 return error;
12149 static const struct got_error *
12150 check_local_changes(void *arg, unsigned char status,
12151 unsigned char staged_status, const char *path,
12152 struct got_object_id *blob_id, struct got_object_id *staged_blob_id,
12153 struct got_object_id *commit_id, int dirfd, const char *de_name)
12155 int *have_local_changes = arg;
12157 switch (status) {
12158 case GOT_STATUS_ADD:
12159 case GOT_STATUS_DELETE:
12160 case GOT_STATUS_MODIFY:
12161 case GOT_STATUS_CONFLICT:
12162 *have_local_changes = 1;
12163 return got_error(GOT_ERR_CANCELLED);
12164 default:
12165 break;
12168 switch (staged_status) {
12169 case GOT_STATUS_ADD:
12170 case GOT_STATUS_DELETE:
12171 case GOT_STATUS_MODIFY:
12172 *have_local_changes = 1;
12173 return got_error(GOT_ERR_CANCELLED);
12174 default:
12175 break;
12178 return NULL;
12181 static const struct got_error *
12182 cmd_histedit(int argc, char *argv[])
12184 const struct got_error *error = NULL;
12185 struct got_worktree *worktree = NULL;
12186 struct got_fileindex *fileindex = NULL;
12187 struct got_repository *repo = NULL;
12188 char *cwd = NULL, *committer = NULL, *gitconfig_path = NULL;
12189 struct got_reference *branch = NULL;
12190 struct got_reference *tmp_branch = NULL;
12191 struct got_object_id *resume_commit_id = NULL;
12192 struct got_object_id *base_commit_id = NULL;
12193 struct got_object_id *head_commit_id = NULL;
12194 struct got_commit_object *commit = NULL;
12195 int ch, rebase_in_progress = 0, merge_in_progress = 0;
12196 struct got_update_progress_arg upa;
12197 int edit_in_progress = 0, abort_edit = 0, continue_edit = 0;
12198 int edit_logmsg_only = 0, fold_only = 0, edit_only = 0;
12199 int list_backups = 0, delete_backups = 0;
12200 const char *edit_script_path = NULL;
12201 struct got_object_id_queue commits;
12202 struct got_pathlist_head merged_paths;
12203 const struct got_object_id_queue *parent_ids;
12204 struct got_object_qid *pid;
12205 struct got_histedit_list histedit_cmds;
12206 struct got_histedit_list_entry *hle;
12207 int *pack_fds = NULL;
12209 STAILQ_INIT(&commits);
12210 TAILQ_INIT(&histedit_cmds);
12211 TAILQ_INIT(&merged_paths);
12212 memset(&upa, 0, sizeof(upa));
12214 while ((ch = getopt(argc, argv, "aceF:flmX")) != -1) {
12215 switch (ch) {
12216 case 'a':
12217 abort_edit = 1;
12218 break;
12219 case 'c':
12220 continue_edit = 1;
12221 break;
12222 case 'e':
12223 edit_only = 1;
12224 break;
12225 case 'F':
12226 edit_script_path = optarg;
12227 break;
12228 case 'f':
12229 fold_only = 1;
12230 break;
12231 case 'l':
12232 list_backups = 1;
12233 break;
12234 case 'm':
12235 edit_logmsg_only = 1;
12236 break;
12237 case 'X':
12238 delete_backups = 1;
12239 break;
12240 default:
12241 usage_histedit();
12242 /* NOTREACHED */
12246 argc -= optind;
12247 argv += optind;
12249 #ifndef PROFILE
12250 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
12251 "unveil", NULL) == -1)
12252 err(1, "pledge");
12253 #endif
12254 if (abort_edit && continue_edit)
12255 option_conflict('a', 'c');
12256 if (edit_script_path && edit_logmsg_only)
12257 option_conflict('F', 'm');
12258 if (abort_edit && edit_logmsg_only)
12259 option_conflict('a', 'm');
12260 if (continue_edit && edit_logmsg_only)
12261 option_conflict('c', 'm');
12262 if (abort_edit && fold_only)
12263 option_conflict('a', 'f');
12264 if (continue_edit && fold_only)
12265 option_conflict('c', 'f');
12266 if (fold_only && edit_logmsg_only)
12267 option_conflict('f', 'm');
12268 if (edit_script_path && fold_only)
12269 option_conflict('F', 'f');
12270 if (abort_edit && edit_only)
12271 option_conflict('a', 'e');
12272 if (continue_edit && edit_only)
12273 option_conflict('c', 'e');
12274 if (edit_only && edit_logmsg_only)
12275 option_conflict('e', 'm');
12276 if (edit_script_path && edit_only)
12277 option_conflict('F', 'e');
12278 if (list_backups) {
12279 if (abort_edit)
12280 option_conflict('l', 'a');
12281 if (continue_edit)
12282 option_conflict('l', 'c');
12283 if (edit_script_path)
12284 option_conflict('l', 'F');
12285 if (edit_logmsg_only)
12286 option_conflict('l', 'm');
12287 if (fold_only)
12288 option_conflict('l', 'f');
12289 if (edit_only)
12290 option_conflict('l', 'e');
12291 if (delete_backups)
12292 option_conflict('l', 'X');
12293 if (argc != 0 && argc != 1)
12294 usage_histedit();
12295 } else if (delete_backups) {
12296 if (abort_edit)
12297 option_conflict('X', 'a');
12298 if (continue_edit)
12299 option_conflict('X', 'c');
12300 if (edit_script_path)
12301 option_conflict('X', 'F');
12302 if (edit_logmsg_only)
12303 option_conflict('X', 'm');
12304 if (fold_only)
12305 option_conflict('X', 'f');
12306 if (edit_only)
12307 option_conflict('X', 'e');
12308 if (list_backups)
12309 option_conflict('X', 'l');
12310 if (argc != 0 && argc != 1)
12311 usage_histedit();
12312 } else if (argc != 0)
12313 usage_histedit();
12316 * This command cannot apply unveil(2) in all cases because the
12317 * user may choose to run an editor to edit the histedit script
12318 * and to edit individual commit log messages.
12319 * unveil(2) traverses exec(2); if an editor is used we have to
12320 * apply unveil after edit script and log messages have been written.
12321 * XXX TODO: Make use of unveil(2) where possible.
12324 cwd = getcwd(NULL, 0);
12325 if (cwd == NULL) {
12326 error = got_error_from_errno("getcwd");
12327 goto done;
12330 error = got_repo_pack_fds_open(&pack_fds);
12331 if (error != NULL)
12332 goto done;
12334 error = got_worktree_open(&worktree, cwd);
12335 if (error) {
12336 if (list_backups || delete_backups) {
12337 if (error->code != GOT_ERR_NOT_WORKTREE)
12338 goto done;
12339 } else {
12340 if (error->code == GOT_ERR_NOT_WORKTREE)
12341 error = wrap_not_worktree_error(error,
12342 "histedit", cwd);
12343 goto done;
12347 if (list_backups || delete_backups) {
12348 error = got_repo_open(&repo,
12349 worktree ? got_worktree_get_repo_path(worktree) : cwd,
12350 NULL, pack_fds);
12351 if (error != NULL)
12352 goto done;
12353 error = apply_unveil(got_repo_get_path(repo), 0,
12354 worktree ? got_worktree_get_root_path(worktree) : NULL);
12355 if (error)
12356 goto done;
12357 error = process_backup_refs(
12358 GOT_WORKTREE_HISTEDIT_BACKUP_REF_PREFIX,
12359 argc == 1 ? argv[0] : NULL, delete_backups, repo);
12360 goto done; /* nothing else to do */
12363 error = get_gitconfig_path(&gitconfig_path);
12364 if (error)
12365 goto done;
12366 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
12367 gitconfig_path, pack_fds);
12368 if (error != NULL)
12369 goto done;
12371 if (worktree != NULL && !list_backups && !delete_backups) {
12372 error = worktree_has_logmsg_ref("histedit", worktree, repo);
12373 if (error)
12374 goto done;
12377 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
12378 if (error)
12379 goto done;
12380 if (rebase_in_progress) {
12381 error = got_error(GOT_ERR_REBASING);
12382 goto done;
12385 error = got_worktree_merge_in_progress(&merge_in_progress, worktree,
12386 repo);
12387 if (error)
12388 goto done;
12389 if (merge_in_progress) {
12390 error = got_error(GOT_ERR_MERGE_BUSY);
12391 goto done;
12394 error = got_worktree_histedit_in_progress(&edit_in_progress, worktree);
12395 if (error)
12396 goto done;
12398 if (edit_in_progress && edit_logmsg_only) {
12399 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
12400 "histedit operation is in progress in this "
12401 "work tree and must be continued or aborted "
12402 "before the -m option can be used");
12403 goto done;
12405 if (edit_in_progress && fold_only) {
12406 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
12407 "histedit operation is in progress in this "
12408 "work tree and must be continued or aborted "
12409 "before the -f option can be used");
12410 goto done;
12412 if (edit_in_progress && edit_only) {
12413 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
12414 "histedit operation is in progress in this "
12415 "work tree and must be continued or aborted "
12416 "before the -e option can be used");
12417 goto done;
12420 if (edit_in_progress && abort_edit) {
12421 error = got_worktree_histedit_continue(&resume_commit_id,
12422 &tmp_branch, &branch, &base_commit_id, &fileindex,
12423 worktree, repo);
12424 if (error)
12425 goto done;
12426 printf("Switching work tree to %s\n",
12427 got_ref_get_symref_target(branch));
12428 error = got_worktree_histedit_abort(worktree, fileindex, repo,
12429 branch, base_commit_id, abort_progress, &upa);
12430 if (error)
12431 goto done;
12432 printf("Histedit of %s aborted\n",
12433 got_ref_get_symref_target(branch));
12434 print_merge_progress_stats(&upa);
12435 goto done; /* nothing else to do */
12436 } else if (abort_edit) {
12437 error = got_error(GOT_ERR_NOT_HISTEDIT);
12438 goto done;
12441 error = get_author(&committer, repo, worktree);
12442 if (error)
12443 goto done;
12445 if (continue_edit) {
12446 char *path;
12448 if (!edit_in_progress) {
12449 error = got_error(GOT_ERR_NOT_HISTEDIT);
12450 goto done;
12453 error = got_worktree_get_histedit_script_path(&path, worktree);
12454 if (error)
12455 goto done;
12457 error = histedit_load_list(&histedit_cmds, path, repo);
12458 free(path);
12459 if (error)
12460 goto done;
12462 error = got_worktree_histedit_continue(&resume_commit_id,
12463 &tmp_branch, &branch, &base_commit_id, &fileindex,
12464 worktree, repo);
12465 if (error)
12466 goto done;
12468 error = got_ref_resolve(&head_commit_id, repo, branch);
12469 if (error)
12470 goto done;
12472 error = got_object_open_as_commit(&commit, repo,
12473 head_commit_id);
12474 if (error)
12475 goto done;
12476 parent_ids = got_object_commit_get_parent_ids(commit);
12477 pid = STAILQ_FIRST(parent_ids);
12478 if (pid == NULL) {
12479 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
12480 goto done;
12482 error = collect_commits(&commits, head_commit_id, &pid->id,
12483 base_commit_id, got_worktree_get_path_prefix(worktree),
12484 GOT_ERR_HISTEDIT_PATH, repo);
12485 got_object_commit_close(commit);
12486 commit = NULL;
12487 if (error)
12488 goto done;
12489 } else {
12490 if (edit_in_progress) {
12491 error = got_error(GOT_ERR_HISTEDIT_BUSY);
12492 goto done;
12495 error = got_ref_open(&branch, repo,
12496 got_worktree_get_head_ref_name(worktree), 0);
12497 if (error != NULL)
12498 goto done;
12500 if (strncmp(got_ref_get_name(branch), "refs/heads/", 11) != 0) {
12501 error = got_error_msg(GOT_ERR_COMMIT_BRANCH,
12502 "will not edit commit history of a branch outside "
12503 "the \"refs/heads/\" reference namespace");
12504 goto done;
12507 error = got_ref_resolve(&head_commit_id, repo, branch);
12508 got_ref_close(branch);
12509 branch = NULL;
12510 if (error)
12511 goto done;
12513 error = got_object_open_as_commit(&commit, repo,
12514 head_commit_id);
12515 if (error)
12516 goto done;
12517 parent_ids = got_object_commit_get_parent_ids(commit);
12518 pid = STAILQ_FIRST(parent_ids);
12519 if (pid == NULL) {
12520 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
12521 goto done;
12523 error = collect_commits(&commits, head_commit_id, &pid->id,
12524 got_worktree_get_base_commit_id(worktree),
12525 got_worktree_get_path_prefix(worktree),
12526 GOT_ERR_HISTEDIT_PATH, repo);
12527 got_object_commit_close(commit);
12528 commit = NULL;
12529 if (error)
12530 goto done;
12532 if (STAILQ_EMPTY(&commits)) {
12533 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
12534 goto done;
12537 error = got_worktree_histedit_prepare(&tmp_branch, &branch,
12538 &base_commit_id, &fileindex, worktree, repo);
12539 if (error)
12540 goto done;
12542 if (edit_script_path) {
12543 error = histedit_load_list(&histedit_cmds,
12544 edit_script_path, repo);
12545 if (error) {
12546 got_worktree_histedit_abort(worktree, fileindex,
12547 repo, branch, base_commit_id,
12548 abort_progress, &upa);
12549 print_merge_progress_stats(&upa);
12550 goto done;
12552 } else {
12553 const char *branch_name;
12554 branch_name = got_ref_get_symref_target(branch);
12555 if (strncmp(branch_name, "refs/heads/", 11) == 0)
12556 branch_name += 11;
12557 error = histedit_edit_script(&histedit_cmds, &commits,
12558 branch_name, edit_logmsg_only, fold_only,
12559 edit_only, repo);
12560 if (error) {
12561 got_worktree_histedit_abort(worktree, fileindex,
12562 repo, branch, base_commit_id,
12563 abort_progress, &upa);
12564 print_merge_progress_stats(&upa);
12565 goto done;
12570 error = histedit_save_list(&histedit_cmds, worktree,
12571 repo);
12572 if (error) {
12573 got_worktree_histedit_abort(worktree, fileindex,
12574 repo, branch, base_commit_id,
12575 abort_progress, &upa);
12576 print_merge_progress_stats(&upa);
12577 goto done;
12582 error = histedit_check_script(&histedit_cmds, &commits, repo);
12583 if (error)
12584 goto done;
12586 TAILQ_FOREACH(hle, &histedit_cmds, entry) {
12587 if (resume_commit_id) {
12588 if (got_object_id_cmp(hle->commit_id,
12589 resume_commit_id) != 0)
12590 continue;
12592 resume_commit_id = NULL;
12593 if (hle->cmd->code == GOT_HISTEDIT_DROP ||
12594 hle->cmd->code == GOT_HISTEDIT_FOLD) {
12595 error = histedit_skip_commit(hle, worktree,
12596 repo);
12597 if (error)
12598 goto done;
12599 } else {
12600 struct got_pathlist_head paths;
12601 int have_changes = 0;
12603 TAILQ_INIT(&paths);
12604 error = got_pathlist_append(&paths, "", NULL);
12605 if (error)
12606 goto done;
12607 error = got_worktree_status(worktree, &paths,
12608 repo, 0, check_local_changes, &have_changes,
12609 check_cancelled, NULL);
12610 got_pathlist_free(&paths,
12611 GOT_PATHLIST_FREE_NONE);
12612 if (error) {
12613 if (error->code != GOT_ERR_CANCELLED)
12614 goto done;
12615 if (sigint_received || sigpipe_received)
12616 goto done;
12618 if (have_changes) {
12619 error = histedit_commit(NULL, worktree,
12620 fileindex, tmp_branch, hle,
12621 committer, repo);
12622 if (error)
12623 goto done;
12624 } else {
12625 error = got_object_open_as_commit(
12626 &commit, repo, hle->commit_id);
12627 if (error)
12628 goto done;
12629 error = show_histedit_progress(commit,
12630 hle, NULL);
12631 got_object_commit_close(commit);
12632 commit = NULL;
12633 if (error)
12634 goto done;
12637 continue;
12640 if (hle->cmd->code == GOT_HISTEDIT_DROP) {
12641 error = histedit_skip_commit(hle, worktree, repo);
12642 if (error)
12643 goto done;
12644 continue;
12647 error = got_object_open_as_commit(&commit, repo,
12648 hle->commit_id);
12649 if (error)
12650 goto done;
12651 parent_ids = got_object_commit_get_parent_ids(commit);
12652 pid = STAILQ_FIRST(parent_ids);
12654 error = got_worktree_histedit_merge_files(&merged_paths,
12655 worktree, fileindex, &pid->id, hle->commit_id, repo,
12656 update_progress, &upa, check_cancelled, NULL);
12657 if (error)
12658 goto done;
12659 got_object_commit_close(commit);
12660 commit = NULL;
12662 print_merge_progress_stats(&upa);
12663 if (upa.conflicts > 0 || upa.missing > 0 ||
12664 upa.not_deleted > 0 || upa.unversioned > 0) {
12665 if (upa.conflicts > 0) {
12666 error = show_rebase_merge_conflict(
12667 hle->commit_id, repo);
12668 if (error)
12669 goto done;
12671 got_pathlist_free(&merged_paths, GOT_PATHLIST_FREE_PATH);
12672 break;
12675 if (hle->cmd->code == GOT_HISTEDIT_EDIT) {
12676 char *id_str;
12677 error = got_object_id_str(&id_str, hle->commit_id);
12678 if (error)
12679 goto done;
12680 printf("Stopping histedit for amending commit %s\n",
12681 id_str);
12682 free(id_str);
12683 got_pathlist_free(&merged_paths, GOT_PATHLIST_FREE_PATH);
12684 error = got_worktree_histedit_postpone(worktree,
12685 fileindex);
12686 goto done;
12689 if (hle->cmd->code == GOT_HISTEDIT_FOLD) {
12690 error = histedit_skip_commit(hle, worktree, repo);
12691 if (error)
12692 goto done;
12693 continue;
12696 error = histedit_commit(&merged_paths, worktree, fileindex,
12697 tmp_branch, hle, committer, repo);
12698 got_pathlist_free(&merged_paths, GOT_PATHLIST_FREE_PATH);
12699 if (error)
12700 goto done;
12703 if (upa.conflicts > 0 || upa.missing > 0 ||
12704 upa.not_deleted > 0 || upa.unversioned > 0) {
12705 error = got_worktree_histedit_postpone(worktree, fileindex);
12706 if (error)
12707 goto done;
12708 if (upa.conflicts > 0 && upa.missing == 0 &&
12709 upa.not_deleted == 0 && upa.unversioned == 0) {
12710 error = got_error_msg(GOT_ERR_CONFLICTS,
12711 "conflicts must be resolved before histedit "
12712 "can continue");
12713 } else if (upa.conflicts > 0) {
12714 error = got_error_msg(GOT_ERR_CONFLICTS,
12715 "conflicts must be resolved before histedit "
12716 "can continue; changes destined for some "
12717 "files were not yet merged and should be "
12718 "merged manually if required before the "
12719 "histedit operation is continued");
12720 } else {
12721 error = got_error_msg(GOT_ERR_CONFLICTS,
12722 "changes destined for some files were not "
12723 "yet merged and should be merged manually "
12724 "if required before the histedit operation "
12725 "is continued");
12727 } else
12728 error = histedit_complete(worktree, fileindex, tmp_branch,
12729 branch, repo);
12730 done:
12731 free(cwd);
12732 free(committer);
12733 free(gitconfig_path);
12734 got_object_id_queue_free(&commits);
12735 histedit_free_list(&histedit_cmds);
12736 free(head_commit_id);
12737 free(base_commit_id);
12738 free(resume_commit_id);
12739 if (commit)
12740 got_object_commit_close(commit);
12741 if (branch)
12742 got_ref_close(branch);
12743 if (tmp_branch)
12744 got_ref_close(tmp_branch);
12745 if (worktree)
12746 got_worktree_close(worktree);
12747 if (repo) {
12748 const struct got_error *close_err = got_repo_close(repo);
12749 if (error == NULL)
12750 error = close_err;
12752 if (pack_fds) {
12753 const struct got_error *pack_err =
12754 got_repo_pack_fds_close(pack_fds);
12755 if (error == NULL)
12756 error = pack_err;
12758 return error;
12761 __dead static void
12762 usage_integrate(void)
12764 fprintf(stderr, "usage: %s integrate branch\n", getprogname());
12765 exit(1);
12768 static const struct got_error *
12769 cmd_integrate(int argc, char *argv[])
12771 const struct got_error *error = NULL;
12772 struct got_repository *repo = NULL;
12773 struct got_worktree *worktree = NULL;
12774 char *cwd = NULL, *refname = NULL, *base_refname = NULL;
12775 const char *branch_arg = NULL;
12776 struct got_reference *branch_ref = NULL, *base_branch_ref = NULL;
12777 struct got_fileindex *fileindex = NULL;
12778 struct got_object_id *commit_id = NULL, *base_commit_id = NULL;
12779 int ch;
12780 struct got_update_progress_arg upa;
12781 int *pack_fds = NULL;
12783 while ((ch = getopt(argc, argv, "")) != -1) {
12784 switch (ch) {
12785 default:
12786 usage_integrate();
12787 /* NOTREACHED */
12791 argc -= optind;
12792 argv += optind;
12794 if (argc != 1)
12795 usage_integrate();
12796 branch_arg = argv[0];
12797 #ifndef PROFILE
12798 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
12799 "unveil", NULL) == -1)
12800 err(1, "pledge");
12801 #endif
12802 cwd = getcwd(NULL, 0);
12803 if (cwd == NULL) {
12804 error = got_error_from_errno("getcwd");
12805 goto done;
12808 error = got_repo_pack_fds_open(&pack_fds);
12809 if (error != NULL)
12810 goto done;
12812 error = got_worktree_open(&worktree, cwd);
12813 if (error) {
12814 if (error->code == GOT_ERR_NOT_WORKTREE)
12815 error = wrap_not_worktree_error(error, "integrate",
12816 cwd);
12817 goto done;
12820 error = check_rebase_or_histedit_in_progress(worktree);
12821 if (error)
12822 goto done;
12824 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
12825 NULL, pack_fds);
12826 if (error != NULL)
12827 goto done;
12829 error = apply_unveil(got_repo_get_path(repo), 0,
12830 got_worktree_get_root_path(worktree));
12831 if (error)
12832 goto done;
12834 error = check_merge_in_progress(worktree, repo);
12835 if (error)
12836 goto done;
12838 if (asprintf(&refname, "refs/heads/%s", branch_arg) == -1) {
12839 error = got_error_from_errno("asprintf");
12840 goto done;
12843 error = got_worktree_integrate_prepare(&fileindex, &branch_ref,
12844 &base_branch_ref, worktree, refname, repo);
12845 if (error)
12846 goto done;
12848 refname = strdup(got_ref_get_name(branch_ref));
12849 if (refname == NULL) {
12850 error = got_error_from_errno("strdup");
12851 got_worktree_integrate_abort(worktree, fileindex, repo,
12852 branch_ref, base_branch_ref);
12853 goto done;
12855 base_refname = strdup(got_ref_get_name(base_branch_ref));
12856 if (base_refname == NULL) {
12857 error = got_error_from_errno("strdup");
12858 got_worktree_integrate_abort(worktree, fileindex, repo,
12859 branch_ref, base_branch_ref);
12860 goto done;
12862 if (strncmp(base_refname, "refs/heads/", 11) != 0) {
12863 error = got_error(GOT_ERR_INTEGRATE_BRANCH);
12864 got_worktree_integrate_abort(worktree, fileindex, repo,
12865 branch_ref, base_branch_ref);
12866 goto done;
12869 error = got_ref_resolve(&commit_id, repo, branch_ref);
12870 if (error)
12871 goto done;
12873 error = got_ref_resolve(&base_commit_id, repo, base_branch_ref);
12874 if (error)
12875 goto done;
12877 if (got_object_id_cmp(commit_id, base_commit_id) == 0) {
12878 error = got_error_msg(GOT_ERR_SAME_BRANCH,
12879 "specified branch has already been integrated");
12880 got_worktree_integrate_abort(worktree, fileindex, repo,
12881 branch_ref, base_branch_ref);
12882 goto done;
12885 error = check_linear_ancestry(commit_id, base_commit_id, 1, repo);
12886 if (error) {
12887 if (error->code == GOT_ERR_ANCESTRY)
12888 error = got_error(GOT_ERR_REBASE_REQUIRED);
12889 got_worktree_integrate_abort(worktree, fileindex, repo,
12890 branch_ref, base_branch_ref);
12891 goto done;
12894 memset(&upa, 0, sizeof(upa));
12895 error = got_worktree_integrate_continue(worktree, fileindex, repo,
12896 branch_ref, base_branch_ref, update_progress, &upa,
12897 check_cancelled, NULL);
12898 if (error)
12899 goto done;
12901 printf("Integrated %s into %s\n", refname, base_refname);
12902 print_update_progress_stats(&upa);
12903 done:
12904 if (repo) {
12905 const struct got_error *close_err = got_repo_close(repo);
12906 if (error == NULL)
12907 error = close_err;
12909 if (worktree)
12910 got_worktree_close(worktree);
12911 if (pack_fds) {
12912 const struct got_error *pack_err =
12913 got_repo_pack_fds_close(pack_fds);
12914 if (error == NULL)
12915 error = pack_err;
12917 free(cwd);
12918 free(base_commit_id);
12919 free(commit_id);
12920 free(refname);
12921 free(base_refname);
12922 return error;
12925 __dead static void
12926 usage_merge(void)
12928 fprintf(stderr, "usage: %s merge [-acn] [branch]\n", getprogname());
12929 exit(1);
12932 static const struct got_error *
12933 cmd_merge(int argc, char *argv[])
12935 const struct got_error *error = NULL;
12936 struct got_worktree *worktree = NULL;
12937 struct got_repository *repo = NULL;
12938 struct got_fileindex *fileindex = NULL;
12939 char *cwd = NULL, *id_str = NULL, *author = NULL;
12940 struct got_reference *branch = NULL, *wt_branch = NULL;
12941 struct got_object_id *branch_tip = NULL, *yca_id = NULL;
12942 struct got_object_id *wt_branch_tip = NULL;
12943 int ch, merge_in_progress = 0, abort_merge = 0, continue_merge = 0;
12944 int interrupt_merge = 0;
12945 struct got_update_progress_arg upa;
12946 struct got_object_id *merge_commit_id = NULL;
12947 char *branch_name = NULL;
12948 int *pack_fds = NULL;
12950 memset(&upa, 0, sizeof(upa));
12952 while ((ch = getopt(argc, argv, "acn")) != -1) {
12953 switch (ch) {
12954 case 'a':
12955 abort_merge = 1;
12956 break;
12957 case 'c':
12958 continue_merge = 1;
12959 break;
12960 case 'n':
12961 interrupt_merge = 1;
12962 break;
12963 default:
12964 usage_merge();
12965 /* NOTREACHED */
12969 argc -= optind;
12970 argv += optind;
12972 #ifndef PROFILE
12973 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
12974 "unveil", NULL) == -1)
12975 err(1, "pledge");
12976 #endif
12978 if (abort_merge && continue_merge)
12979 option_conflict('a', 'c');
12980 if (abort_merge || continue_merge) {
12981 if (argc != 0)
12982 usage_merge();
12983 } else if (argc != 1)
12984 usage_merge();
12986 cwd = getcwd(NULL, 0);
12987 if (cwd == NULL) {
12988 error = got_error_from_errno("getcwd");
12989 goto done;
12992 error = got_repo_pack_fds_open(&pack_fds);
12993 if (error != NULL)
12994 goto done;
12996 error = got_worktree_open(&worktree, cwd);
12997 if (error) {
12998 if (error->code == GOT_ERR_NOT_WORKTREE)
12999 error = wrap_not_worktree_error(error,
13000 "merge", cwd);
13001 goto done;
13004 error = got_repo_open(&repo,
13005 worktree ? got_worktree_get_repo_path(worktree) : cwd, NULL,
13006 pack_fds);
13007 if (error != NULL)
13008 goto done;
13010 if (worktree != NULL) {
13011 error = worktree_has_logmsg_ref("merge", worktree, repo);
13012 if (error)
13013 goto done;
13016 error = apply_unveil(got_repo_get_path(repo), 0,
13017 worktree ? got_worktree_get_root_path(worktree) : NULL);
13018 if (error)
13019 goto done;
13021 error = check_rebase_or_histedit_in_progress(worktree);
13022 if (error)
13023 goto done;
13025 error = got_worktree_merge_in_progress(&merge_in_progress, worktree,
13026 repo);
13027 if (error)
13028 goto done;
13030 if (abort_merge) {
13031 if (!merge_in_progress) {
13032 error = got_error(GOT_ERR_NOT_MERGING);
13033 goto done;
13035 error = got_worktree_merge_continue(&branch_name,
13036 &branch_tip, &fileindex, worktree, repo);
13037 if (error)
13038 goto done;
13039 error = got_worktree_merge_abort(worktree, fileindex, repo,
13040 abort_progress, &upa);
13041 if (error)
13042 goto done;
13043 printf("Merge of %s aborted\n", branch_name);
13044 goto done; /* nothing else to do */
13047 error = get_author(&author, repo, worktree);
13048 if (error)
13049 goto done;
13051 if (continue_merge) {
13052 if (!merge_in_progress) {
13053 error = got_error(GOT_ERR_NOT_MERGING);
13054 goto done;
13056 error = got_worktree_merge_continue(&branch_name,
13057 &branch_tip, &fileindex, worktree, repo);
13058 if (error)
13059 goto done;
13060 } else {
13061 error = got_ref_open(&branch, repo, argv[0], 0);
13062 if (error != NULL)
13063 goto done;
13064 branch_name = strdup(got_ref_get_name(branch));
13065 if (branch_name == NULL) {
13066 error = got_error_from_errno("strdup");
13067 goto done;
13069 error = got_ref_resolve(&branch_tip, repo, branch);
13070 if (error)
13071 goto done;
13074 error = got_ref_open(&wt_branch, repo,
13075 got_worktree_get_head_ref_name(worktree), 0);
13076 if (error)
13077 goto done;
13078 error = got_ref_resolve(&wt_branch_tip, repo, wt_branch);
13079 if (error)
13080 goto done;
13081 error = got_commit_graph_find_youngest_common_ancestor(&yca_id,
13082 wt_branch_tip, branch_tip, 0, repo,
13083 check_cancelled, NULL);
13084 if (error && error->code != GOT_ERR_ANCESTRY)
13085 goto done;
13087 if (!continue_merge) {
13088 error = check_path_prefix(wt_branch_tip, branch_tip,
13089 got_worktree_get_path_prefix(worktree),
13090 GOT_ERR_MERGE_PATH, repo);
13091 if (error)
13092 goto done;
13093 if (yca_id) {
13094 error = check_same_branch(wt_branch_tip, branch,
13095 yca_id, repo);
13096 if (error) {
13097 if (error->code != GOT_ERR_ANCESTRY)
13098 goto done;
13099 error = NULL;
13100 } else {
13101 static char msg[512];
13102 snprintf(msg, sizeof(msg),
13103 "cannot create a merge commit because "
13104 "%s is based on %s; %s can be integrated "
13105 "with 'got integrate' instead", branch_name,
13106 got_worktree_get_head_ref_name(worktree),
13107 branch_name);
13108 error = got_error_msg(GOT_ERR_SAME_BRANCH, msg);
13109 goto done;
13112 error = got_worktree_merge_prepare(&fileindex, worktree,
13113 branch, repo);
13114 if (error)
13115 goto done;
13117 error = got_worktree_merge_branch(worktree, fileindex,
13118 yca_id, branch_tip, repo, update_progress, &upa,
13119 check_cancelled, NULL);
13120 if (error)
13121 goto done;
13122 print_merge_progress_stats(&upa);
13123 if (!upa.did_something) {
13124 error = got_worktree_merge_abort(worktree, fileindex,
13125 repo, abort_progress, &upa);
13126 if (error)
13127 goto done;
13128 printf("Already up-to-date\n");
13129 goto done;
13133 if (interrupt_merge) {
13134 error = got_worktree_merge_postpone(worktree, fileindex);
13135 if (error)
13136 goto done;
13137 printf("Merge of %s interrupted on request\n", branch_name);
13138 } else if (upa.conflicts > 0 || upa.missing > 0 ||
13139 upa.not_deleted > 0 || upa.unversioned > 0) {
13140 error = got_worktree_merge_postpone(worktree, fileindex);
13141 if (error)
13142 goto done;
13143 if (upa.conflicts > 0 && upa.missing == 0 &&
13144 upa.not_deleted == 0 && upa.unversioned == 0) {
13145 error = got_error_msg(GOT_ERR_CONFLICTS,
13146 "conflicts must be resolved before merging "
13147 "can continue");
13148 } else if (upa.conflicts > 0) {
13149 error = got_error_msg(GOT_ERR_CONFLICTS,
13150 "conflicts must be resolved before merging "
13151 "can continue; changes destined for some "
13152 "files were not yet merged and "
13153 "should be merged manually if required before the "
13154 "merge operation is continued");
13155 } else {
13156 error = got_error_msg(GOT_ERR_CONFLICTS,
13157 "changes destined for some "
13158 "files were not yet merged and should be "
13159 "merged manually if required before the "
13160 "merge operation is continued");
13162 goto done;
13163 } else {
13164 error = got_worktree_merge_commit(&merge_commit_id, worktree,
13165 fileindex, author, NULL, 1, branch_tip, branch_name,
13166 repo, continue_merge ? print_status : NULL, NULL);
13167 if (error)
13168 goto done;
13169 error = got_worktree_merge_complete(worktree, fileindex, repo);
13170 if (error)
13171 goto done;
13172 error = got_object_id_str(&id_str, merge_commit_id);
13173 if (error)
13174 goto done;
13175 printf("Merged %s into %s: %s\n", branch_name,
13176 got_worktree_get_head_ref_name(worktree),
13177 id_str);
13180 done:
13181 free(id_str);
13182 free(merge_commit_id);
13183 free(author);
13184 free(branch_tip);
13185 free(branch_name);
13186 free(yca_id);
13187 if (branch)
13188 got_ref_close(branch);
13189 if (wt_branch)
13190 got_ref_close(wt_branch);
13191 if (worktree)
13192 got_worktree_close(worktree);
13193 if (repo) {
13194 const struct got_error *close_err = got_repo_close(repo);
13195 if (error == NULL)
13196 error = close_err;
13198 if (pack_fds) {
13199 const struct got_error *pack_err =
13200 got_repo_pack_fds_close(pack_fds);
13201 if (error == NULL)
13202 error = pack_err;
13204 return error;
13207 __dead static void
13208 usage_stage(void)
13210 fprintf(stderr, "usage: %s stage [-lpS] [-F response-script] "
13211 "[path ...]\n", getprogname());
13212 exit(1);
13215 static const struct got_error *
13216 print_stage(void *arg, unsigned char status, unsigned char staged_status,
13217 const char *path, struct got_object_id *blob_id,
13218 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
13219 int dirfd, const char *de_name)
13221 const struct got_error *err = NULL;
13222 char *id_str = NULL;
13224 if (staged_status != GOT_STATUS_ADD &&
13225 staged_status != GOT_STATUS_MODIFY &&
13226 staged_status != GOT_STATUS_DELETE)
13227 return NULL;
13229 if (staged_status == GOT_STATUS_ADD ||
13230 staged_status == GOT_STATUS_MODIFY)
13231 err = got_object_id_str(&id_str, staged_blob_id);
13232 else
13233 err = got_object_id_str(&id_str, blob_id);
13234 if (err)
13235 return err;
13237 printf("%s %c %s\n", id_str, staged_status, path);
13238 free(id_str);
13239 return NULL;
13242 static const struct got_error *
13243 cmd_stage(int argc, char *argv[])
13245 const struct got_error *error = NULL;
13246 struct got_repository *repo = NULL;
13247 struct got_worktree *worktree = NULL;
13248 char *cwd = NULL;
13249 struct got_pathlist_head paths;
13250 int ch, list_stage = 0, pflag = 0, allow_bad_symlinks = 0;
13251 FILE *patch_script_file = NULL;
13252 const char *patch_script_path = NULL;
13253 struct choose_patch_arg cpa;
13254 int *pack_fds = NULL;
13256 TAILQ_INIT(&paths);
13258 while ((ch = getopt(argc, argv, "F:lpS")) != -1) {
13259 switch (ch) {
13260 case 'F':
13261 patch_script_path = optarg;
13262 break;
13263 case 'l':
13264 list_stage = 1;
13265 break;
13266 case 'p':
13267 pflag = 1;
13268 break;
13269 case 'S':
13270 allow_bad_symlinks = 1;
13271 break;
13272 default:
13273 usage_stage();
13274 /* NOTREACHED */
13278 argc -= optind;
13279 argv += optind;
13281 #ifndef PROFILE
13282 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
13283 "unveil", NULL) == -1)
13284 err(1, "pledge");
13285 #endif
13286 if (list_stage && (pflag || patch_script_path))
13287 errx(1, "-l option cannot be used with other options");
13288 if (patch_script_path && !pflag)
13289 errx(1, "-F option can only be used together with -p option");
13291 cwd = getcwd(NULL, 0);
13292 if (cwd == NULL) {
13293 error = got_error_from_errno("getcwd");
13294 goto done;
13297 error = got_repo_pack_fds_open(&pack_fds);
13298 if (error != NULL)
13299 goto done;
13301 error = got_worktree_open(&worktree, cwd);
13302 if (error) {
13303 if (error->code == GOT_ERR_NOT_WORKTREE)
13304 error = wrap_not_worktree_error(error, "stage", cwd);
13305 goto done;
13308 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
13309 NULL, pack_fds);
13310 if (error != NULL)
13311 goto done;
13313 if (patch_script_path) {
13314 patch_script_file = fopen(patch_script_path, "re");
13315 if (patch_script_file == NULL) {
13316 error = got_error_from_errno2("fopen",
13317 patch_script_path);
13318 goto done;
13321 error = apply_unveil(got_repo_get_path(repo), 0,
13322 got_worktree_get_root_path(worktree));
13323 if (error)
13324 goto done;
13326 error = check_merge_in_progress(worktree, repo);
13327 if (error)
13328 goto done;
13330 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
13331 if (error)
13332 goto done;
13334 if (list_stage)
13335 error = got_worktree_status(worktree, &paths, repo, 0,
13336 print_stage, NULL, check_cancelled, NULL);
13337 else {
13338 cpa.patch_script_file = patch_script_file;
13339 cpa.action = "stage";
13340 error = got_worktree_stage(worktree, &paths,
13341 pflag ? NULL : print_status, NULL,
13342 pflag ? choose_patch : NULL, &cpa,
13343 allow_bad_symlinks, repo);
13345 done:
13346 if (patch_script_file && fclose(patch_script_file) == EOF &&
13347 error == NULL)
13348 error = got_error_from_errno2("fclose", patch_script_path);
13349 if (repo) {
13350 const struct got_error *close_err = got_repo_close(repo);
13351 if (error == NULL)
13352 error = close_err;
13354 if (worktree)
13355 got_worktree_close(worktree);
13356 if (pack_fds) {
13357 const struct got_error *pack_err =
13358 got_repo_pack_fds_close(pack_fds);
13359 if (error == NULL)
13360 error = pack_err;
13362 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
13363 free(cwd);
13364 return error;
13367 __dead static void
13368 usage_unstage(void)
13370 fprintf(stderr, "usage: %s unstage [-p] [-F response-script] "
13371 "[path ...]\n", getprogname());
13372 exit(1);
13376 static const struct got_error *
13377 cmd_unstage(int argc, char *argv[])
13379 const struct got_error *error = NULL;
13380 struct got_repository *repo = NULL;
13381 struct got_worktree *worktree = NULL;
13382 char *cwd = NULL;
13383 struct got_pathlist_head paths;
13384 int ch, pflag = 0;
13385 struct got_update_progress_arg upa;
13386 FILE *patch_script_file = NULL;
13387 const char *patch_script_path = NULL;
13388 struct choose_patch_arg cpa;
13389 int *pack_fds = NULL;
13391 TAILQ_INIT(&paths);
13393 while ((ch = getopt(argc, argv, "F:p")) != -1) {
13394 switch (ch) {
13395 case 'F':
13396 patch_script_path = optarg;
13397 break;
13398 case 'p':
13399 pflag = 1;
13400 break;
13401 default:
13402 usage_unstage();
13403 /* NOTREACHED */
13407 argc -= optind;
13408 argv += optind;
13410 #ifndef PROFILE
13411 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
13412 "unveil", NULL) == -1)
13413 err(1, "pledge");
13414 #endif
13415 if (patch_script_path && !pflag)
13416 errx(1, "-F option can only be used together with -p option");
13418 cwd = getcwd(NULL, 0);
13419 if (cwd == NULL) {
13420 error = got_error_from_errno("getcwd");
13421 goto done;
13424 error = got_repo_pack_fds_open(&pack_fds);
13425 if (error != NULL)
13426 goto done;
13428 error = got_worktree_open(&worktree, cwd);
13429 if (error) {
13430 if (error->code == GOT_ERR_NOT_WORKTREE)
13431 error = wrap_not_worktree_error(error, "unstage", cwd);
13432 goto done;
13435 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
13436 NULL, pack_fds);
13437 if (error != NULL)
13438 goto done;
13440 if (patch_script_path) {
13441 patch_script_file = fopen(patch_script_path, "re");
13442 if (patch_script_file == NULL) {
13443 error = got_error_from_errno2("fopen",
13444 patch_script_path);
13445 goto done;
13449 error = apply_unveil(got_repo_get_path(repo), 0,
13450 got_worktree_get_root_path(worktree));
13451 if (error)
13452 goto done;
13454 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
13455 if (error)
13456 goto done;
13458 cpa.patch_script_file = patch_script_file;
13459 cpa.action = "unstage";
13460 memset(&upa, 0, sizeof(upa));
13461 error = got_worktree_unstage(worktree, &paths, update_progress,
13462 &upa, pflag ? choose_patch : NULL, &cpa, repo);
13463 if (!error)
13464 print_merge_progress_stats(&upa);
13465 done:
13466 if (patch_script_file && fclose(patch_script_file) == EOF &&
13467 error == NULL)
13468 error = got_error_from_errno2("fclose", patch_script_path);
13469 if (repo) {
13470 const struct got_error *close_err = got_repo_close(repo);
13471 if (error == NULL)
13472 error = close_err;
13474 if (worktree)
13475 got_worktree_close(worktree);
13476 if (pack_fds) {
13477 const struct got_error *pack_err =
13478 got_repo_pack_fds_close(pack_fds);
13479 if (error == NULL)
13480 error = pack_err;
13482 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
13483 free(cwd);
13484 return error;
13487 __dead static void
13488 usage_cat(void)
13490 fprintf(stderr, "usage: %s cat [-P] [-c commit] [-r repository-path] "
13491 "arg ...\n", getprogname());
13492 exit(1);
13495 static const struct got_error *
13496 cat_blob(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
13498 const struct got_error *err;
13499 struct got_blob_object *blob;
13500 int fd = -1;
13502 fd = got_opentempfd();
13503 if (fd == -1)
13504 return got_error_from_errno("got_opentempfd");
13506 err = got_object_open_as_blob(&blob, repo, id, 8192, fd);
13507 if (err)
13508 goto done;
13510 err = got_object_blob_dump_to_file(NULL, NULL, NULL, outfile, blob);
13511 done:
13512 if (fd != -1 && close(fd) == -1 && err == NULL)
13513 err = got_error_from_errno("close");
13514 if (blob)
13515 got_object_blob_close(blob);
13516 return err;
13519 static const struct got_error *
13520 cat_tree(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
13522 const struct got_error *err;
13523 struct got_tree_object *tree;
13524 int nentries, i;
13526 err = got_object_open_as_tree(&tree, repo, id);
13527 if (err)
13528 return err;
13530 nentries = got_object_tree_get_nentries(tree);
13531 for (i = 0; i < nentries; i++) {
13532 struct got_tree_entry *te;
13533 char *id_str;
13534 if (sigint_received || sigpipe_received)
13535 break;
13536 te = got_object_tree_get_entry(tree, i);
13537 err = got_object_id_str(&id_str, got_tree_entry_get_id(te));
13538 if (err)
13539 break;
13540 fprintf(outfile, "%s %.7o %s\n", id_str,
13541 got_tree_entry_get_mode(te),
13542 got_tree_entry_get_name(te));
13543 free(id_str);
13546 got_object_tree_close(tree);
13547 return err;
13550 static const struct got_error *
13551 cat_commit(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
13553 const struct got_error *err;
13554 struct got_commit_object *commit;
13555 const struct got_object_id_queue *parent_ids;
13556 struct got_object_qid *pid;
13557 char *id_str = NULL;
13558 const char *logmsg = NULL;
13559 char gmtoff[6];
13561 err = got_object_open_as_commit(&commit, repo, id);
13562 if (err)
13563 return err;
13565 err = got_object_id_str(&id_str, got_object_commit_get_tree_id(commit));
13566 if (err)
13567 goto done;
13569 fprintf(outfile, "%s%s\n", GOT_COMMIT_LABEL_TREE, id_str);
13570 parent_ids = got_object_commit_get_parent_ids(commit);
13571 fprintf(outfile, "numparents %d\n",
13572 got_object_commit_get_nparents(commit));
13573 STAILQ_FOREACH(pid, parent_ids, entry) {
13574 char *pid_str;
13575 err = got_object_id_str(&pid_str, &pid->id);
13576 if (err)
13577 goto done;
13578 fprintf(outfile, "%s%s\n", GOT_COMMIT_LABEL_PARENT, pid_str);
13579 free(pid_str);
13581 got_date_format_gmtoff(gmtoff, sizeof(gmtoff),
13582 got_object_commit_get_author_gmtoff(commit));
13583 fprintf(outfile, "%s%s %lld %s\n", GOT_COMMIT_LABEL_AUTHOR,
13584 got_object_commit_get_author(commit),
13585 (long long)got_object_commit_get_author_time(commit),
13586 gmtoff);
13588 got_date_format_gmtoff(gmtoff, sizeof(gmtoff),
13589 got_object_commit_get_committer_gmtoff(commit));
13590 fprintf(outfile, "%s%s %lld %s\n", GOT_COMMIT_LABEL_COMMITTER,
13591 got_object_commit_get_committer(commit),
13592 (long long)got_object_commit_get_committer_time(commit),
13593 gmtoff);
13595 logmsg = got_object_commit_get_logmsg_raw(commit);
13596 fprintf(outfile, "messagelen %zd\n", strlen(logmsg));
13597 fprintf(outfile, "%s", logmsg);
13598 done:
13599 free(id_str);
13600 got_object_commit_close(commit);
13601 return err;
13604 static const struct got_error *
13605 cat_tag(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
13607 const struct got_error *err;
13608 struct got_tag_object *tag;
13609 char *id_str = NULL;
13610 const char *tagmsg = NULL;
13611 char gmtoff[6];
13613 err = got_object_open_as_tag(&tag, repo, id);
13614 if (err)
13615 return err;
13617 err = got_object_id_str(&id_str, got_object_tag_get_object_id(tag));
13618 if (err)
13619 goto done;
13621 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_OBJECT, id_str);
13623 switch (got_object_tag_get_object_type(tag)) {
13624 case GOT_OBJ_TYPE_BLOB:
13625 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
13626 GOT_OBJ_LABEL_BLOB);
13627 break;
13628 case GOT_OBJ_TYPE_TREE:
13629 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
13630 GOT_OBJ_LABEL_TREE);
13631 break;
13632 case GOT_OBJ_TYPE_COMMIT:
13633 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
13634 GOT_OBJ_LABEL_COMMIT);
13635 break;
13636 case GOT_OBJ_TYPE_TAG:
13637 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
13638 GOT_OBJ_LABEL_TAG);
13639 break;
13640 default:
13641 break;
13644 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TAG,
13645 got_object_tag_get_name(tag));
13647 got_date_format_gmtoff(gmtoff, sizeof(gmtoff),
13648 got_object_tag_get_tagger_gmtoff(tag));
13649 fprintf(outfile, "%s%s %lld %s\n", GOT_TAG_LABEL_TAGGER,
13650 got_object_tag_get_tagger(tag),
13651 (long long)got_object_tag_get_tagger_time(tag),
13652 gmtoff);
13654 tagmsg = got_object_tag_get_message(tag);
13655 fprintf(outfile, "messagelen %zd\n", strlen(tagmsg));
13656 fprintf(outfile, "%s", tagmsg);
13657 done:
13658 free(id_str);
13659 got_object_tag_close(tag);
13660 return err;
13663 static const struct got_error *
13664 cmd_cat(int argc, char *argv[])
13666 const struct got_error *error;
13667 struct got_repository *repo = NULL;
13668 struct got_worktree *worktree = NULL;
13669 char *cwd = NULL, *repo_path = NULL, *label = NULL;
13670 const char *commit_id_str = NULL;
13671 struct got_object_id *id = NULL, *commit_id = NULL;
13672 struct got_commit_object *commit = NULL;
13673 int ch, obj_type, i, force_path = 0;
13674 struct got_reflist_head refs;
13675 int *pack_fds = NULL;
13677 TAILQ_INIT(&refs);
13679 #ifndef PROFILE
13680 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
13681 NULL) == -1)
13682 err(1, "pledge");
13683 #endif
13685 while ((ch = getopt(argc, argv, "c:Pr:")) != -1) {
13686 switch (ch) {
13687 case 'c':
13688 commit_id_str = optarg;
13689 break;
13690 case 'P':
13691 force_path = 1;
13692 break;
13693 case 'r':
13694 repo_path = realpath(optarg, NULL);
13695 if (repo_path == NULL)
13696 return got_error_from_errno2("realpath",
13697 optarg);
13698 got_path_strip_trailing_slashes(repo_path);
13699 break;
13700 default:
13701 usage_cat();
13702 /* NOTREACHED */
13706 argc -= optind;
13707 argv += optind;
13709 cwd = getcwd(NULL, 0);
13710 if (cwd == NULL) {
13711 error = got_error_from_errno("getcwd");
13712 goto done;
13715 error = got_repo_pack_fds_open(&pack_fds);
13716 if (error != NULL)
13717 goto done;
13719 if (repo_path == NULL) {
13720 error = got_worktree_open(&worktree, cwd);
13721 if (error && error->code != GOT_ERR_NOT_WORKTREE)
13722 goto done;
13723 if (worktree) {
13724 repo_path = strdup(
13725 got_worktree_get_repo_path(worktree));
13726 if (repo_path == NULL) {
13727 error = got_error_from_errno("strdup");
13728 goto done;
13731 /* Release work tree lock. */
13732 got_worktree_close(worktree);
13733 worktree = NULL;
13737 if (repo_path == NULL) {
13738 repo_path = strdup(cwd);
13739 if (repo_path == NULL)
13740 return got_error_from_errno("strdup");
13743 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
13744 free(repo_path);
13745 if (error != NULL)
13746 goto done;
13748 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
13749 if (error)
13750 goto done;
13752 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
13753 if (error)
13754 goto done;
13756 if (commit_id_str == NULL)
13757 commit_id_str = GOT_REF_HEAD;
13758 error = got_repo_match_object_id(&commit_id, NULL,
13759 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
13760 if (error)
13761 goto done;
13763 error = got_object_open_as_commit(&commit, repo, commit_id);
13764 if (error)
13765 goto done;
13767 for (i = 0; i < argc; i++) {
13768 if (force_path) {
13769 error = got_object_id_by_path(&id, repo, commit,
13770 argv[i]);
13771 if (error)
13772 break;
13773 } else {
13774 error = got_repo_match_object_id(&id, &label, argv[i],
13775 GOT_OBJ_TYPE_ANY, NULL /* do not resolve tags */,
13776 repo);
13777 if (error) {
13778 if (error->code != GOT_ERR_BAD_OBJ_ID_STR &&
13779 error->code != GOT_ERR_NOT_REF)
13780 break;
13781 error = got_object_id_by_path(&id, repo,
13782 commit, argv[i]);
13783 if (error)
13784 break;
13788 error = got_object_get_type(&obj_type, repo, id);
13789 if (error)
13790 break;
13792 switch (obj_type) {
13793 case GOT_OBJ_TYPE_BLOB:
13794 error = cat_blob(id, repo, stdout);
13795 break;
13796 case GOT_OBJ_TYPE_TREE:
13797 error = cat_tree(id, repo, stdout);
13798 break;
13799 case GOT_OBJ_TYPE_COMMIT:
13800 error = cat_commit(id, repo, stdout);
13801 break;
13802 case GOT_OBJ_TYPE_TAG:
13803 error = cat_tag(id, repo, stdout);
13804 break;
13805 default:
13806 error = got_error(GOT_ERR_OBJ_TYPE);
13807 break;
13809 if (error)
13810 break;
13811 free(label);
13812 label = NULL;
13813 free(id);
13814 id = NULL;
13816 done:
13817 free(label);
13818 free(id);
13819 free(commit_id);
13820 if (commit)
13821 got_object_commit_close(commit);
13822 if (worktree)
13823 got_worktree_close(worktree);
13824 if (repo) {
13825 const struct got_error *close_err = got_repo_close(repo);
13826 if (error == NULL)
13827 error = close_err;
13829 if (pack_fds) {
13830 const struct got_error *pack_err =
13831 got_repo_pack_fds_close(pack_fds);
13832 if (error == NULL)
13833 error = pack_err;
13836 got_ref_list_free(&refs);
13837 return error;
13840 __dead static void
13841 usage_info(void)
13843 fprintf(stderr, "usage: %s info [path ...]\n",
13844 getprogname());
13845 exit(1);
13848 static const struct got_error *
13849 print_path_info(void *arg, const char *path, mode_t mode, time_t mtime,
13850 struct got_object_id *blob_id, struct got_object_id *staged_blob_id,
13851 struct got_object_id *commit_id)
13853 const struct got_error *err = NULL;
13854 char *id_str = NULL;
13855 char datebuf[128];
13856 struct tm mytm, *tm;
13857 struct got_pathlist_head *paths = arg;
13858 struct got_pathlist_entry *pe;
13861 * Clear error indication from any of the path arguments which
13862 * would cause this file index entry to be displayed.
13864 TAILQ_FOREACH(pe, paths, entry) {
13865 if (got_path_cmp(path, pe->path, strlen(path),
13866 pe->path_len) == 0 ||
13867 got_path_is_child(path, pe->path, pe->path_len))
13868 pe->data = NULL; /* no error */
13871 printf(GOT_COMMIT_SEP_STR);
13872 if (S_ISLNK(mode))
13873 printf("symlink: %s\n", path);
13874 else if (S_ISREG(mode)) {
13875 printf("file: %s\n", path);
13876 printf("mode: %o\n", mode & (S_IRWXU | S_IRWXG | S_IRWXO));
13877 } else if (S_ISDIR(mode))
13878 printf("directory: %s\n", path);
13879 else
13880 printf("something: %s\n", path);
13882 tm = localtime_r(&mtime, &mytm);
13883 if (tm == NULL)
13884 return NULL;
13885 if (strftime(datebuf, sizeof(datebuf), "%c %Z", tm) == 0)
13886 return got_error(GOT_ERR_NO_SPACE);
13887 printf("timestamp: %s\n", datebuf);
13889 if (blob_id) {
13890 err = got_object_id_str(&id_str, blob_id);
13891 if (err)
13892 return err;
13893 printf("based on blob: %s\n", id_str);
13894 free(id_str);
13897 if (staged_blob_id) {
13898 err = got_object_id_str(&id_str, staged_blob_id);
13899 if (err)
13900 return err;
13901 printf("based on staged blob: %s\n", id_str);
13902 free(id_str);
13905 if (commit_id) {
13906 err = got_object_id_str(&id_str, commit_id);
13907 if (err)
13908 return err;
13909 printf("based on commit: %s\n", id_str);
13910 free(id_str);
13913 return NULL;
13916 static const struct got_error *
13917 cmd_info(int argc, char *argv[])
13919 const struct got_error *error = NULL;
13920 struct got_worktree *worktree = NULL;
13921 char *cwd = NULL, *id_str = NULL;
13922 struct got_pathlist_head paths;
13923 char *uuidstr = NULL;
13924 int ch, show_files = 0;
13926 TAILQ_INIT(&paths);
13928 while ((ch = getopt(argc, argv, "")) != -1) {
13929 switch (ch) {
13930 default:
13931 usage_info();
13932 /* NOTREACHED */
13936 argc -= optind;
13937 argv += optind;
13939 #ifndef PROFILE
13940 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
13941 NULL) == -1)
13942 err(1, "pledge");
13943 #endif
13944 cwd = getcwd(NULL, 0);
13945 if (cwd == NULL) {
13946 error = got_error_from_errno("getcwd");
13947 goto done;
13950 error = got_worktree_open(&worktree, cwd);
13951 if (error) {
13952 if (error->code == GOT_ERR_NOT_WORKTREE)
13953 error = wrap_not_worktree_error(error, "info", cwd);
13954 goto done;
13957 #ifndef PROFILE
13958 /* Remove "wpath cpath proc exec sendfd" promises. */
13959 if (pledge("stdio rpath flock unveil", NULL) == -1)
13960 err(1, "pledge");
13961 #endif
13962 error = apply_unveil(NULL, 0, got_worktree_get_root_path(worktree));
13963 if (error)
13964 goto done;
13966 if (argc >= 1) {
13967 error = get_worktree_paths_from_argv(&paths, argc, argv,
13968 worktree);
13969 if (error)
13970 goto done;
13971 show_files = 1;
13974 error = got_object_id_str(&id_str,
13975 got_worktree_get_base_commit_id(worktree));
13976 if (error)
13977 goto done;
13979 error = got_worktree_get_uuid(&uuidstr, worktree);
13980 if (error)
13981 goto done;
13983 printf("work tree: %s\n", got_worktree_get_root_path(worktree));
13984 printf("work tree base commit: %s\n", id_str);
13985 printf("work tree path prefix: %s\n",
13986 got_worktree_get_path_prefix(worktree));
13987 printf("work tree branch reference: %s\n",
13988 got_worktree_get_head_ref_name(worktree));
13989 printf("work tree UUID: %s\n", uuidstr);
13990 printf("repository: %s\n", got_worktree_get_repo_path(worktree));
13992 if (show_files) {
13993 struct got_pathlist_entry *pe;
13994 TAILQ_FOREACH(pe, &paths, entry) {
13995 if (pe->path_len == 0)
13996 continue;
13998 * Assume this path will fail. This will be corrected
13999 * in print_path_info() in case the path does suceeed.
14001 pe->data = (void *)got_error(GOT_ERR_BAD_PATH);
14003 error = got_worktree_path_info(worktree, &paths,
14004 print_path_info, &paths, check_cancelled, NULL);
14005 if (error)
14006 goto done;
14007 TAILQ_FOREACH(pe, &paths, entry) {
14008 if (pe->data != NULL) {
14009 const struct got_error *perr;
14011 perr = pe->data;
14012 error = got_error_fmt(perr->code, "%s",
14013 pe->path);
14014 break;
14018 done:
14019 if (worktree)
14020 got_worktree_close(worktree);
14021 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
14022 free(cwd);
14023 free(id_str);
14024 free(uuidstr);
14025 return error;