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 read_logmsg(char **logmsg, size_t *len, FILE *fp, size_t filesize,
393 int strip_comments)
395 const struct got_error *err = NULL;
396 char *line = NULL;
397 size_t linesize = 0;
399 *logmsg = NULL;
400 *len = 0;
402 if (fseeko(fp, 0L, SEEK_SET) == -1)
403 return got_error_from_errno("fseeko");
405 *logmsg = malloc(filesize + 1);
406 if (*logmsg == NULL)
407 return got_error_from_errno("malloc");
408 (*logmsg)[0] = '\0';
410 while (getline(&line, &linesize, fp) != -1) {
411 if ((strip_comments && line[0] == '#') ||
412 (*len == 0 && line[0] == '\n'))
413 continue; /* remove comments and leading empty lines */
414 *len = strlcat(*logmsg, line, filesize + 1);
415 if (*len >= filesize + 1) {
416 err = got_error(GOT_ERR_NO_SPACE);
417 goto done;
420 if (ferror(fp)) {
421 err = got_ferror(fp, GOT_ERR_IO);
422 goto done;
425 while (*len > 0 && (*logmsg)[*len - 1] == '\n') {
426 (*logmsg)[*len - 1] = '\0';
427 (*len)--;
429 done:
430 free(line);
431 if (err) {
432 free(*logmsg);
433 *logmsg = NULL;
434 *len = 0;
436 return err;
439 static const struct got_error *
440 edit_logmsg(char **logmsg, const char *editor, const char *logmsg_path,
441 const char *initial_content, size_t initial_content_len,
442 int require_modification)
444 const struct got_error *err = NULL;
445 char *line = NULL;
446 struct stat st, st2;
447 FILE *fp = NULL;
448 size_t len, logmsg_len;
449 char *initial_content_stripped = NULL, *buf = NULL, *s;
451 *logmsg = NULL;
453 if (stat(logmsg_path, &st) == -1)
454 return got_error_from_errno2("stat", logmsg_path);
456 if (spawn_editor(editor, logmsg_path) == -1)
457 return got_error_from_errno("failed spawning editor");
459 if (stat(logmsg_path, &st2) == -1)
460 return got_error_from_errno("stat");
462 if (require_modification &&
463 st.st_mtime == st2.st_mtime && st.st_size == st2.st_size)
464 return got_error_msg(GOT_ERR_COMMIT_MSG_EMPTY,
465 "no changes made to commit message, aborting");
467 /*
468 * Set up a stripped version of the initial content without comments
469 * and blank lines. We need this in order to check if the message
470 * has in fact been edited.
471 */
472 initial_content_stripped = malloc(initial_content_len + 1);
473 if (initial_content_stripped == NULL)
474 return got_error_from_errno("malloc");
475 initial_content_stripped[0] = '\0';
477 buf = strdup(initial_content);
478 if (buf == NULL) {
479 err = got_error_from_errno("strdup");
480 goto done;
482 s = buf;
483 len = 0;
484 while ((line = strsep(&s, "\n")) != NULL) {
485 if (len == 0 && line[0] == '\n')
486 continue; /* remove leading empty lines */
487 len = strlcat(initial_content_stripped, line,
488 initial_content_len + 1);
489 if (len >= initial_content_len + 1) {
490 err = got_error(GOT_ERR_NO_SPACE);
491 goto done;
494 while (len > 0 && initial_content_stripped[len - 1] == '\n') {
495 initial_content_stripped[len - 1] = '\0';
496 len--;
499 fp = fopen(logmsg_path, "re");
500 if (fp == NULL) {
501 err = got_error_from_errno("fopen");
502 goto done;
505 /*
506 * Check whether the log message was modified.
507 * Editing or removal of comments does count as a modifcation to
508 * support reuse of existing log messages during cherrypick/backout.
509 */
510 err = read_logmsg(logmsg, &logmsg_len, fp, st2.st_size, 0);
511 if (err)
512 goto done;
513 if (require_modification &&
514 strcmp(*logmsg, initial_content_stripped) == 0)
515 err = got_error_msg(GOT_ERR_COMMIT_MSG_EMPTY,
516 "no changes made to commit message, aborting");
518 /* Read log message again, stripping comments this time around. */
519 free(*logmsg);
520 err = read_logmsg(logmsg, &logmsg_len, fp, st2.st_size, 1);
521 if (err)
522 goto done;
523 if (logmsg_len == 0) {
524 err = got_error_msg(GOT_ERR_COMMIT_MSG_EMPTY,
525 "commit message cannot be empty, aborting");
526 goto done;
528 done:
529 free(initial_content_stripped);
530 free(buf);
531 if (fp && fclose(fp) == EOF && err == NULL)
532 err = got_error_from_errno("fclose");
533 if (err) {
534 free(*logmsg);
535 *logmsg = NULL;
537 return err;
540 static const struct got_error *
541 collect_import_msg(char **logmsg, char **logmsg_path, const char *editor,
542 const char *path_dir, const char *branch_name)
544 char *initial_content = NULL;
545 const struct got_error *err = NULL;
546 int initial_content_len;
547 int fd = -1;
549 initial_content_len = asprintf(&initial_content,
550 "\n# %s to be imported to branch %s\n", path_dir,
551 branch_name);
552 if (initial_content_len == -1)
553 return got_error_from_errno("asprintf");
555 err = got_opentemp_named_fd(logmsg_path, &fd,
556 GOT_TMPDIR_STR "/got-importmsg", "");
557 if (err)
558 goto done;
560 if (write(fd, initial_content, initial_content_len) == -1) {
561 err = got_error_from_errno2("write", *logmsg_path);
562 goto done;
565 err = edit_logmsg(logmsg, editor, *logmsg_path, initial_content,
566 initial_content_len, 1);
567 done:
568 if (fd != -1 && close(fd) == -1 && err == NULL)
569 err = got_error_from_errno2("close", *logmsg_path);
570 free(initial_content);
571 if (err) {
572 free(*logmsg_path);
573 *logmsg_path = NULL;
575 return err;
578 static const struct got_error *
579 import_progress(void *arg, const char *path)
581 printf("A %s\n", path);
582 return NULL;
585 static const struct got_error *
586 valid_author(const char *author)
588 const char *email = author;
590 /*
591 * Git' expects the author (or committer) to be in the form
592 * "name <email>", which are mostly free form (see the
593 * "committer" description in git-fast-import(1)). We're only
594 * doing this to avoid git's object parser breaking on commits
595 * we create.
596 */
598 while (*author && *author != '\n' && *author != '<' && *author != '>')
599 author++;
600 if (author != email && *author == '<' && *(author - 1) != ' ')
601 return got_error_fmt(GOT_ERR_COMMIT_BAD_AUTHOR, "%s: space "
602 "between author name and email required", email);
603 if (*author++ != '<')
604 return got_error_fmt(GOT_ERR_COMMIT_NO_EMAIL, "%s", email);
605 while (*author && *author != '\n' && *author != '<' && *author != '>')
606 author++;
607 if (strcmp(author, ">") != 0)
608 return got_error_fmt(GOT_ERR_COMMIT_NO_EMAIL, "%s", email);
609 return NULL;
612 static const struct got_error *
613 get_author(char **author, struct got_repository *repo,
614 struct got_worktree *worktree)
616 const struct got_error *err = NULL;
617 const char *got_author = NULL, *name, *email;
618 const struct got_gotconfig *worktree_conf = NULL, *repo_conf = NULL;
620 *author = NULL;
622 if (worktree)
623 worktree_conf = got_worktree_get_gotconfig(worktree);
624 repo_conf = got_repo_get_gotconfig(repo);
626 /*
627 * Priority of potential author information sources, from most
628 * significant to least significant:
629 * 1) work tree's .got/got.conf file
630 * 2) repository's got.conf file
631 * 3) repository's git config file
632 * 4) environment variables
633 * 5) global git config files (in user's home directory or /etc)
634 */
636 if (worktree_conf)
637 got_author = got_gotconfig_get_author(worktree_conf);
638 if (got_author == NULL)
639 got_author = got_gotconfig_get_author(repo_conf);
640 if (got_author == NULL) {
641 name = got_repo_get_gitconfig_author_name(repo);
642 email = got_repo_get_gitconfig_author_email(repo);
643 if (name && email) {
644 if (asprintf(author, "%s <%s>", name, email) == -1)
645 return got_error_from_errno("asprintf");
646 return NULL;
649 got_author = getenv("GOT_AUTHOR");
650 if (got_author == NULL) {
651 name = got_repo_get_global_gitconfig_author_name(repo);
652 email = got_repo_get_global_gitconfig_author_email(
653 repo);
654 if (name && email) {
655 if (asprintf(author, "%s <%s>", name, email)
656 == -1)
657 return got_error_from_errno("asprintf");
658 return NULL;
660 /* TODO: Look up user in password database? */
661 return got_error(GOT_ERR_COMMIT_NO_AUTHOR);
665 *author = strdup(got_author);
666 if (*author == NULL)
667 return got_error_from_errno("strdup");
669 err = valid_author(*author);
670 if (err) {
671 free(*author);
672 *author = NULL;
674 return err;
677 static const struct got_error *
678 get_allowed_signers(char **allowed_signers, struct got_repository *repo,
679 struct got_worktree *worktree)
681 const char *got_allowed_signers = NULL;
682 const struct got_gotconfig *worktree_conf = NULL, *repo_conf = NULL;
684 *allowed_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_allowed_signers = got_gotconfig_get_allowed_signers_file(
699 worktree_conf);
700 if (got_allowed_signers == NULL)
701 got_allowed_signers = got_gotconfig_get_allowed_signers_file(
702 repo_conf);
704 if (got_allowed_signers) {
705 *allowed_signers = strdup(got_allowed_signers);
706 if (*allowed_signers == NULL)
707 return got_error_from_errno("strdup");
709 return NULL;
712 static const struct got_error *
713 get_revoked_signers(char **revoked_signers, struct got_repository *repo,
714 struct got_worktree *worktree)
716 const char *got_revoked_signers = NULL;
717 const struct got_gotconfig *worktree_conf = NULL, *repo_conf = NULL;
719 *revoked_signers = NULL;
721 if (worktree)
722 worktree_conf = got_worktree_get_gotconfig(worktree);
723 repo_conf = got_repo_get_gotconfig(repo);
725 /*
726 * Priority of potential author information sources, from most
727 * significant to least significant:
728 * 1) work tree's .got/got.conf file
729 * 2) repository's got.conf file
730 */
732 if (worktree_conf)
733 got_revoked_signers = got_gotconfig_get_revoked_signers_file(
734 worktree_conf);
735 if (got_revoked_signers == NULL)
736 got_revoked_signers = got_gotconfig_get_revoked_signers_file(
737 repo_conf);
739 if (got_revoked_signers) {
740 *revoked_signers = strdup(got_revoked_signers);
741 if (*revoked_signers == NULL)
742 return got_error_from_errno("strdup");
744 return NULL;
747 static const char *
748 get_signer_id(struct got_repository *repo, struct got_worktree *worktree)
750 const char *got_signer_id = NULL;
751 const struct got_gotconfig *worktree_conf = NULL, *repo_conf = NULL;
753 if (worktree)
754 worktree_conf = got_worktree_get_gotconfig(worktree);
755 repo_conf = got_repo_get_gotconfig(repo);
757 /*
758 * Priority of potential author information sources, from most
759 * significant to least significant:
760 * 1) work tree's .got/got.conf file
761 * 2) repository's got.conf file
762 */
764 if (worktree_conf)
765 got_signer_id = got_gotconfig_get_signer_id(worktree_conf);
766 if (got_signer_id == NULL)
767 got_signer_id = got_gotconfig_get_signer_id(repo_conf);
769 return got_signer_id;
772 static const struct got_error *
773 get_gitconfig_path(char **gitconfig_path)
775 const char *homedir = getenv("HOME");
777 *gitconfig_path = NULL;
778 if (homedir) {
779 if (asprintf(gitconfig_path, "%s/.gitconfig", homedir) == -1)
780 return got_error_from_errno("asprintf");
783 return NULL;
786 static const struct got_error *
787 cmd_import(int argc, char *argv[])
789 const struct got_error *error = NULL;
790 char *path_dir = NULL, *repo_path = NULL, *logmsg = NULL;
791 char *gitconfig_path = NULL, *editor = NULL, *author = NULL;
792 const char *branch_name = NULL;
793 char *id_str = NULL, *logmsg_path = NULL;
794 char refname[PATH_MAX] = "refs/heads/";
795 struct got_repository *repo = NULL;
796 struct got_reference *branch_ref = NULL, *head_ref = NULL;
797 struct got_object_id *new_commit_id = NULL;
798 int ch, n = 0;
799 struct got_pathlist_head ignores;
800 struct got_pathlist_entry *pe;
801 int preserve_logmsg = 0;
802 int *pack_fds = NULL;
804 TAILQ_INIT(&ignores);
806 while ((ch = getopt(argc, argv, "b:I:m:r:")) != -1) {
807 switch (ch) {
808 case 'b':
809 branch_name = optarg;
810 break;
811 case 'I':
812 if (optarg[0] == '\0')
813 break;
814 error = got_pathlist_insert(&pe, &ignores, optarg,
815 NULL);
816 if (error)
817 goto done;
818 break;
819 case 'm':
820 logmsg = strdup(optarg);
821 if (logmsg == NULL) {
822 error = got_error_from_errno("strdup");
823 goto done;
825 break;
826 case 'r':
827 repo_path = realpath(optarg, NULL);
828 if (repo_path == NULL) {
829 error = got_error_from_errno2("realpath",
830 optarg);
831 goto done;
833 break;
834 default:
835 usage_import();
836 /* NOTREACHED */
840 argc -= optind;
841 argv += optind;
843 #ifndef PROFILE
844 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
845 "unveil",
846 NULL) == -1)
847 err(1, "pledge");
848 #endif
849 if (argc != 1)
850 usage_import();
852 if (repo_path == NULL) {
853 repo_path = getcwd(NULL, 0);
854 if (repo_path == NULL)
855 return got_error_from_errno("getcwd");
857 got_path_strip_trailing_slashes(repo_path);
858 error = get_gitconfig_path(&gitconfig_path);
859 if (error)
860 goto done;
861 error = got_repo_pack_fds_open(&pack_fds);
862 if (error != NULL)
863 goto done;
864 error = got_repo_open(&repo, repo_path, gitconfig_path, pack_fds);
865 if (error)
866 goto done;
868 error = get_author(&author, repo, NULL);
869 if (error)
870 return error;
872 /*
873 * Don't let the user create a branch name with a leading '-'.
874 * While technically a valid reference name, this case is usually
875 * an unintended typo.
876 */
877 if (branch_name && branch_name[0] == '-')
878 return got_error_path(branch_name, GOT_ERR_REF_NAME_MINUS);
880 error = got_ref_open(&head_ref, repo, GOT_REF_HEAD, 0);
881 if (error && error->code != GOT_ERR_NOT_REF)
882 goto done;
884 if (branch_name)
885 n = strlcat(refname, branch_name, sizeof(refname));
886 else if (head_ref && got_ref_is_symbolic(head_ref))
887 n = strlcpy(refname, got_ref_get_symref_target(head_ref),
888 sizeof(refname));
889 else
890 n = strlcat(refname, "main", sizeof(refname));
891 if (n >= sizeof(refname)) {
892 error = got_error(GOT_ERR_NO_SPACE);
893 goto done;
896 error = got_ref_open(&branch_ref, repo, refname, 0);
897 if (error) {
898 if (error->code != GOT_ERR_NOT_REF)
899 goto done;
900 } else {
901 error = got_error_msg(GOT_ERR_BRANCH_EXISTS,
902 "import target branch already exists");
903 goto done;
906 path_dir = realpath(argv[0], NULL);
907 if (path_dir == NULL) {
908 error = got_error_from_errno2("realpath", argv[0]);
909 goto done;
911 got_path_strip_trailing_slashes(path_dir);
913 /*
914 * unveil(2) traverses exec(2); if an editor is used we have
915 * to apply unveil after the log message has been written.
916 */
917 if (logmsg == NULL || strlen(logmsg) == 0) {
918 error = get_editor(&editor);
919 if (error)
920 goto done;
921 free(logmsg);
922 error = collect_import_msg(&logmsg, &logmsg_path, editor,
923 path_dir, refname);
924 if (error) {
925 if (error->code != GOT_ERR_COMMIT_MSG_EMPTY &&
926 logmsg_path != NULL)
927 preserve_logmsg = 1;
928 goto done;
932 if (unveil(path_dir, "r") != 0) {
933 error = got_error_from_errno2("unveil", path_dir);
934 if (logmsg_path)
935 preserve_logmsg = 1;
936 goto done;
939 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
940 if (error) {
941 if (logmsg_path)
942 preserve_logmsg = 1;
943 goto done;
946 error = got_repo_import(&new_commit_id, path_dir, logmsg,
947 author, &ignores, repo, import_progress, NULL);
948 if (error) {
949 if (logmsg_path)
950 preserve_logmsg = 1;
951 goto done;
954 error = got_ref_alloc(&branch_ref, refname, new_commit_id);
955 if (error) {
956 if (logmsg_path)
957 preserve_logmsg = 1;
958 goto done;
961 error = got_ref_write(branch_ref, repo);
962 if (error) {
963 if (logmsg_path)
964 preserve_logmsg = 1;
965 goto done;
968 error = got_object_id_str(&id_str, new_commit_id);
969 if (error) {
970 if (logmsg_path)
971 preserve_logmsg = 1;
972 goto done;
975 error = got_ref_open(&head_ref, repo, GOT_REF_HEAD, 0);
976 if (error) {
977 if (error->code != GOT_ERR_NOT_REF) {
978 if (logmsg_path)
979 preserve_logmsg = 1;
980 goto done;
983 error = got_ref_alloc_symref(&head_ref, GOT_REF_HEAD,
984 branch_ref);
985 if (error) {
986 if (logmsg_path)
987 preserve_logmsg = 1;
988 goto done;
991 error = got_ref_write(head_ref, repo);
992 if (error) {
993 if (logmsg_path)
994 preserve_logmsg = 1;
995 goto done;
999 printf("Created branch %s with commit %s\n",
1000 got_ref_get_name(branch_ref), id_str);
1001 done:
1002 if (pack_fds) {
1003 const struct got_error *pack_err =
1004 got_repo_pack_fds_close(pack_fds);
1005 if (error == NULL)
1006 error = pack_err;
1008 if (preserve_logmsg) {
1009 fprintf(stderr, "%s: log message preserved in %s\n",
1010 getprogname(), logmsg_path);
1011 } else if (logmsg_path && unlink(logmsg_path) == -1 && error == NULL)
1012 error = got_error_from_errno2("unlink", logmsg_path);
1013 free(logmsg);
1014 free(logmsg_path);
1015 free(repo_path);
1016 free(editor);
1017 free(new_commit_id);
1018 free(id_str);
1019 free(author);
1020 free(gitconfig_path);
1021 if (branch_ref)
1022 got_ref_close(branch_ref);
1023 if (head_ref)
1024 got_ref_close(head_ref);
1025 return error;
1028 __dead static void
1029 usage_clone(void)
1031 fprintf(stderr, "usage: %s clone [-almqv] [-b branch] [-R reference] "
1032 "repository-URL [directory]\n", getprogname());
1033 exit(1);
1036 struct got_fetch_progress_arg {
1037 char last_scaled_size[FMT_SCALED_STRSIZE];
1038 int last_p_indexed;
1039 int last_p_resolved;
1040 int verbosity;
1042 struct got_repository *repo;
1044 int create_configs;
1045 int configs_created;
1046 struct {
1047 struct got_pathlist_head *symrefs;
1048 struct got_pathlist_head *wanted_branches;
1049 struct got_pathlist_head *wanted_refs;
1050 const char *proto;
1051 const char *host;
1052 const char *port;
1053 const char *remote_repo_path;
1054 const char *git_url;
1055 int fetch_all_branches;
1056 int mirror_references;
1057 } config_info;
1060 /* XXX forward declaration */
1061 static const struct got_error *
1062 create_config_files(const char *proto, const char *host, const char *port,
1063 const char *remote_repo_path, const char *git_url, int fetch_all_branches,
1064 int mirror_references, struct got_pathlist_head *symrefs,
1065 struct got_pathlist_head *wanted_branches,
1066 struct got_pathlist_head *wanted_refs, struct got_repository *repo);
1068 static const struct got_error *
1069 fetch_progress(void *arg, const char *message, off_t packfile_size,
1070 int nobj_total, int nobj_indexed, int nobj_loose, int nobj_resolved)
1072 const struct got_error *err = NULL;
1073 struct got_fetch_progress_arg *a = arg;
1074 char scaled_size[FMT_SCALED_STRSIZE];
1075 int p_indexed, p_resolved;
1076 int print_size = 0, print_indexed = 0, print_resolved = 0;
1079 * In order to allow a failed clone to be resumed with 'got fetch'
1080 * we try to create configuration files as soon as possible.
1081 * Once the server has sent information about its default branch
1082 * we have all required information.
1084 if (a->create_configs && !a->configs_created &&
1085 !TAILQ_EMPTY(a->config_info.symrefs)) {
1086 err = create_config_files(a->config_info.proto,
1087 a->config_info.host, a->config_info.port,
1088 a->config_info.remote_repo_path,
1089 a->config_info.git_url,
1090 a->config_info.fetch_all_branches,
1091 a->config_info.mirror_references,
1092 a->config_info.symrefs,
1093 a->config_info.wanted_branches,
1094 a->config_info.wanted_refs, a->repo);
1095 if (err)
1096 return err;
1097 a->configs_created = 1;
1100 if (a->verbosity < 0)
1101 return NULL;
1103 if (message && message[0] != '\0') {
1104 printf("\rserver: %s", message);
1105 fflush(stdout);
1106 return NULL;
1109 if (packfile_size > 0 || nobj_indexed > 0) {
1110 if (fmt_scaled(packfile_size, scaled_size) == 0 &&
1111 (a->last_scaled_size[0] == '\0' ||
1112 strcmp(scaled_size, a->last_scaled_size)) != 0) {
1113 print_size = 1;
1114 if (strlcpy(a->last_scaled_size, scaled_size,
1115 FMT_SCALED_STRSIZE) >= FMT_SCALED_STRSIZE)
1116 return got_error(GOT_ERR_NO_SPACE);
1118 if (nobj_indexed > 0) {
1119 p_indexed = (nobj_indexed * 100) / nobj_total;
1120 if (p_indexed != a->last_p_indexed) {
1121 a->last_p_indexed = p_indexed;
1122 print_indexed = 1;
1123 print_size = 1;
1126 if (nobj_resolved > 0) {
1127 p_resolved = (nobj_resolved * 100) /
1128 (nobj_total - nobj_loose);
1129 if (p_resolved != a->last_p_resolved) {
1130 a->last_p_resolved = p_resolved;
1131 print_resolved = 1;
1132 print_indexed = 1;
1133 print_size = 1;
1138 if (print_size || print_indexed || print_resolved)
1139 printf("\r");
1140 if (print_size)
1141 printf("%*s fetched", FMT_SCALED_STRSIZE - 2, scaled_size);
1142 if (print_indexed)
1143 printf("; indexing %d%%", p_indexed);
1144 if (print_resolved)
1145 printf("; resolving deltas %d%%", p_resolved);
1146 if (print_size || print_indexed || print_resolved)
1147 fflush(stdout);
1149 return NULL;
1152 static const struct got_error *
1153 create_symref(const char *refname, struct got_reference *target_ref,
1154 int verbosity, struct got_repository *repo)
1156 const struct got_error *err;
1157 struct got_reference *head_symref;
1159 err = got_ref_alloc_symref(&head_symref, refname, target_ref);
1160 if (err)
1161 return err;
1163 err = got_ref_write(head_symref, repo);
1164 if (err == NULL && verbosity > 0) {
1165 printf("Created reference %s: %s\n", GOT_REF_HEAD,
1166 got_ref_get_name(target_ref));
1168 got_ref_close(head_symref);
1169 return err;
1172 static const struct got_error *
1173 list_remote_refs(struct got_pathlist_head *symrefs,
1174 struct got_pathlist_head *refs)
1176 const struct got_error *err;
1177 struct got_pathlist_entry *pe;
1179 TAILQ_FOREACH(pe, symrefs, entry) {
1180 const char *refname = pe->path;
1181 const char *targetref = pe->data;
1183 printf("%s: %s\n", refname, targetref);
1186 TAILQ_FOREACH(pe, refs, entry) {
1187 const char *refname = pe->path;
1188 struct got_object_id *id = pe->data;
1189 char *id_str;
1191 err = got_object_id_str(&id_str, id);
1192 if (err)
1193 return err;
1194 printf("%s: %s\n", refname, id_str);
1195 free(id_str);
1198 return NULL;
1201 static const struct got_error *
1202 create_ref(const char *refname, struct got_object_id *id,
1203 int verbosity, struct got_repository *repo)
1205 const struct got_error *err = NULL;
1206 struct got_reference *ref;
1207 char *id_str;
1209 err = got_object_id_str(&id_str, id);
1210 if (err)
1211 return err;
1213 err = got_ref_alloc(&ref, refname, id);
1214 if (err)
1215 goto done;
1217 err = got_ref_write(ref, repo);
1218 got_ref_close(ref);
1220 if (err == NULL && verbosity >= 0)
1221 printf("Created reference %s: %s\n", refname, id_str);
1222 done:
1223 free(id_str);
1224 return err;
1227 static int
1228 match_wanted_ref(const char *refname, const char *wanted_ref)
1230 if (strncmp(refname, "refs/", 5) != 0)
1231 return 0;
1232 refname += 5;
1235 * Prevent fetching of references that won't make any
1236 * sense outside of the remote repository's context.
1238 if (strncmp(refname, "got/", 4) == 0)
1239 return 0;
1240 if (strncmp(refname, "remotes/", 8) == 0)
1241 return 0;
1243 if (strncmp(wanted_ref, "refs/", 5) == 0)
1244 wanted_ref += 5;
1246 /* Allow prefix match. */
1247 if (got_path_is_child(refname, wanted_ref, strlen(wanted_ref)))
1248 return 1;
1250 /* Allow exact match. */
1251 return (strcmp(refname, wanted_ref) == 0);
1254 static int
1255 is_wanted_ref(struct got_pathlist_head *wanted_refs, const char *refname)
1257 struct got_pathlist_entry *pe;
1259 TAILQ_FOREACH(pe, wanted_refs, entry) {
1260 if (match_wanted_ref(refname, pe->path))
1261 return 1;
1264 return 0;
1267 static const struct got_error *
1268 create_wanted_ref(const char *refname, struct got_object_id *id,
1269 const char *remote_repo_name, int verbosity, struct got_repository *repo)
1271 const struct got_error *err;
1272 char *remote_refname;
1274 if (strncmp("refs/", refname, 5) == 0)
1275 refname += 5;
1277 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
1278 remote_repo_name, refname) == -1)
1279 return got_error_from_errno("asprintf");
1281 err = create_ref(remote_refname, id, verbosity, repo);
1282 free(remote_refname);
1283 return err;
1286 static const struct got_error *
1287 create_gotconfig(const char *proto, const char *host, const char *port,
1288 const char *remote_repo_path, const char *default_branch,
1289 int fetch_all_branches, struct got_pathlist_head *wanted_branches,
1290 struct got_pathlist_head *wanted_refs, int mirror_references,
1291 struct got_repository *repo)
1293 const struct got_error *err = NULL;
1294 char *gotconfig_path = NULL;
1295 char *gotconfig = NULL;
1296 FILE *gotconfig_file = NULL;
1297 const char *branchname = NULL;
1298 char *branches = NULL, *refs = NULL;
1299 ssize_t n;
1301 if (!fetch_all_branches && !TAILQ_EMPTY(wanted_branches)) {
1302 struct got_pathlist_entry *pe;
1303 TAILQ_FOREACH(pe, wanted_branches, entry) {
1304 char *s;
1305 branchname = pe->path;
1306 if (strncmp(branchname, "refs/heads/", 11) == 0)
1307 branchname += 11;
1308 if (asprintf(&s, "%s\"%s\" ",
1309 branches ? branches : "", branchname) == -1) {
1310 err = got_error_from_errno("asprintf");
1311 goto done;
1313 free(branches);
1314 branches = s;
1316 } else if (!fetch_all_branches && default_branch) {
1317 branchname = default_branch;
1318 if (strncmp(branchname, "refs/heads/", 11) == 0)
1319 branchname += 11;
1320 if (asprintf(&branches, "\"%s\" ", branchname) == -1) {
1321 err = got_error_from_errno("asprintf");
1322 goto done;
1325 if (!TAILQ_EMPTY(wanted_refs)) {
1326 struct got_pathlist_entry *pe;
1327 TAILQ_FOREACH(pe, wanted_refs, entry) {
1328 char *s;
1329 const char *refname = pe->path;
1330 if (strncmp(refname, "refs/", 5) == 0)
1331 branchname += 5;
1332 if (asprintf(&s, "%s\"%s\" ",
1333 refs ? refs : "", refname) == -1) {
1334 err = got_error_from_errno("asprintf");
1335 goto done;
1337 free(refs);
1338 refs = s;
1342 /* Create got.conf(5). */
1343 gotconfig_path = got_repo_get_path_gotconfig(repo);
1344 if (gotconfig_path == NULL) {
1345 err = got_error_from_errno("got_repo_get_path_gotconfig");
1346 goto done;
1348 gotconfig_file = fopen(gotconfig_path, "ae");
1349 if (gotconfig_file == NULL) {
1350 err = got_error_from_errno2("fopen", gotconfig_path);
1351 goto done;
1353 if (asprintf(&gotconfig,
1354 "remote \"%s\" {\n"
1355 "\tserver %s\n"
1356 "\tprotocol %s\n"
1357 "%s%s%s"
1358 "\trepository \"%s\"\n"
1359 "%s%s%s"
1360 "%s%s%s"
1361 "%s"
1362 "%s"
1363 "}\n",
1364 GOT_FETCH_DEFAULT_REMOTE_NAME, host, proto,
1365 port ? "\tport " : "", port ? port : "", port ? "\n" : "",
1366 remote_repo_path, branches ? "\tbranch { " : "",
1367 branches ? branches : "", branches ? "}\n" : "",
1368 refs ? "\treference { " : "", refs ? refs : "", refs ? "}\n" : "",
1369 mirror_references ? "\tmirror_references yes\n" : "",
1370 fetch_all_branches ? "\tfetch_all_branches yes\n" : "") == -1) {
1371 err = got_error_from_errno("asprintf");
1372 goto done;
1374 n = fwrite(gotconfig, 1, strlen(gotconfig), gotconfig_file);
1375 if (n != strlen(gotconfig)) {
1376 err = got_ferror(gotconfig_file, GOT_ERR_IO);
1377 goto done;
1380 done:
1381 if (gotconfig_file && fclose(gotconfig_file) == EOF && err == NULL)
1382 err = got_error_from_errno2("fclose", gotconfig_path);
1383 free(gotconfig_path);
1384 free(branches);
1385 return err;
1388 static const struct got_error *
1389 create_gitconfig(const char *git_url, const char *default_branch,
1390 int fetch_all_branches, struct got_pathlist_head *wanted_branches,
1391 struct got_pathlist_head *wanted_refs, int mirror_references,
1392 struct got_repository *repo)
1394 const struct got_error *err = NULL;
1395 char *gitconfig_path = NULL;
1396 char *gitconfig = NULL;
1397 FILE *gitconfig_file = NULL;
1398 char *branches = NULL, *refs = NULL;
1399 const char *branchname;
1400 ssize_t n;
1402 /* Create a config file Git can understand. */
1403 gitconfig_path = got_repo_get_path_gitconfig(repo);
1404 if (gitconfig_path == NULL) {
1405 err = got_error_from_errno("got_repo_get_path_gitconfig");
1406 goto done;
1408 gitconfig_file = fopen(gitconfig_path, "ae");
1409 if (gitconfig_file == NULL) {
1410 err = got_error_from_errno2("fopen", gitconfig_path);
1411 goto done;
1413 if (fetch_all_branches) {
1414 if (mirror_references) {
1415 if (asprintf(&branches,
1416 "\tfetch = refs/heads/*:refs/heads/*\n") == -1) {
1417 err = got_error_from_errno("asprintf");
1418 goto done;
1420 } else if (asprintf(&branches,
1421 "\tfetch = refs/heads/*:refs/remotes/%s/*\n",
1422 GOT_FETCH_DEFAULT_REMOTE_NAME) == -1) {
1423 err = got_error_from_errno("asprintf");
1424 goto done;
1426 } else if (!TAILQ_EMPTY(wanted_branches)) {
1427 struct got_pathlist_entry *pe;
1428 TAILQ_FOREACH(pe, wanted_branches, entry) {
1429 char *s;
1430 branchname = pe->path;
1431 if (strncmp(branchname, "refs/heads/", 11) == 0)
1432 branchname += 11;
1433 if (mirror_references) {
1434 if (asprintf(&s,
1435 "%s\tfetch = refs/heads/%s:refs/heads/%s\n",
1436 branches ? branches : "",
1437 branchname, branchname) == -1) {
1438 err = got_error_from_errno("asprintf");
1439 goto done;
1441 } else if (asprintf(&s,
1442 "%s\tfetch = refs/heads/%s:refs/remotes/%s/%s\n",
1443 branches ? branches : "",
1444 branchname, GOT_FETCH_DEFAULT_REMOTE_NAME,
1445 branchname) == -1) {
1446 err = got_error_from_errno("asprintf");
1447 goto done;
1449 free(branches);
1450 branches = s;
1452 } else {
1454 * If the server specified a default branch, use just that one.
1455 * Otherwise fall back to fetching all branches on next fetch.
1457 if (default_branch) {
1458 branchname = default_branch;
1459 if (strncmp(branchname, "refs/heads/", 11) == 0)
1460 branchname += 11;
1461 } else
1462 branchname = "*"; /* fall back to all branches */
1463 if (mirror_references) {
1464 if (asprintf(&branches,
1465 "\tfetch = refs/heads/%s:refs/heads/%s\n",
1466 branchname, branchname) == -1) {
1467 err = got_error_from_errno("asprintf");
1468 goto done;
1470 } else if (asprintf(&branches,
1471 "\tfetch = refs/heads/%s:refs/remotes/%s/%s\n",
1472 branchname, GOT_FETCH_DEFAULT_REMOTE_NAME,
1473 branchname) == -1) {
1474 err = got_error_from_errno("asprintf");
1475 goto done;
1478 if (!TAILQ_EMPTY(wanted_refs)) {
1479 struct got_pathlist_entry *pe;
1480 TAILQ_FOREACH(pe, wanted_refs, entry) {
1481 char *s;
1482 const char *refname = pe->path;
1483 if (strncmp(refname, "refs/", 5) == 0)
1484 refname += 5;
1485 if (mirror_references) {
1486 if (asprintf(&s,
1487 "%s\tfetch = refs/%s:refs/%s\n",
1488 refs ? refs : "", refname, refname) == -1) {
1489 err = got_error_from_errno("asprintf");
1490 goto done;
1492 } else if (asprintf(&s,
1493 "%s\tfetch = refs/%s:refs/remotes/%s/%s\n",
1494 refs ? refs : "",
1495 refname, GOT_FETCH_DEFAULT_REMOTE_NAME,
1496 refname) == -1) {
1497 err = got_error_from_errno("asprintf");
1498 goto done;
1500 free(refs);
1501 refs = s;
1505 if (asprintf(&gitconfig,
1506 "[remote \"%s\"]\n"
1507 "\turl = %s\n"
1508 "%s"
1509 "%s"
1510 "\tfetch = refs/tags/*:refs/tags/*\n",
1511 GOT_FETCH_DEFAULT_REMOTE_NAME, git_url, branches ? branches : "",
1512 refs ? refs : "") == -1) {
1513 err = got_error_from_errno("asprintf");
1514 goto done;
1516 n = fwrite(gitconfig, 1, strlen(gitconfig), gitconfig_file);
1517 if (n != strlen(gitconfig)) {
1518 err = got_ferror(gitconfig_file, GOT_ERR_IO);
1519 goto done;
1521 done:
1522 if (gitconfig_file && fclose(gitconfig_file) == EOF && err == NULL)
1523 err = got_error_from_errno2("fclose", gitconfig_path);
1524 free(gitconfig_path);
1525 free(branches);
1526 return err;
1529 static const struct got_error *
1530 create_config_files(const char *proto, const char *host, const char *port,
1531 const char *remote_repo_path, const char *git_url, int fetch_all_branches,
1532 int mirror_references, struct got_pathlist_head *symrefs,
1533 struct got_pathlist_head *wanted_branches,
1534 struct got_pathlist_head *wanted_refs, struct got_repository *repo)
1536 const struct got_error *err = NULL;
1537 const char *default_branch = NULL;
1538 struct got_pathlist_entry *pe;
1541 * If we asked for a set of wanted branches then use the first
1542 * one of those.
1544 if (!TAILQ_EMPTY(wanted_branches)) {
1545 pe = TAILQ_FIRST(wanted_branches);
1546 default_branch = pe->path;
1547 } else {
1548 /* First HEAD ref listed by server is the default branch. */
1549 TAILQ_FOREACH(pe, symrefs, entry) {
1550 const char *refname = pe->path;
1551 const char *target = pe->data;
1553 if (strcmp(refname, GOT_REF_HEAD) != 0)
1554 continue;
1556 default_branch = target;
1557 break;
1561 /* Create got.conf(5). */
1562 err = create_gotconfig(proto, host, port, remote_repo_path,
1563 default_branch, fetch_all_branches, wanted_branches,
1564 wanted_refs, mirror_references, repo);
1565 if (err)
1566 return err;
1568 /* Create a config file Git can understand. */
1569 return create_gitconfig(git_url, default_branch, fetch_all_branches,
1570 wanted_branches, wanted_refs, mirror_references, repo);
1573 static const struct got_error *
1574 cmd_clone(int argc, char *argv[])
1576 const struct got_error *error = NULL;
1577 const char *uri, *dirname;
1578 char *proto, *host, *port, *repo_name, *server_path;
1579 char *default_destdir = NULL, *id_str = NULL;
1580 const char *repo_path;
1581 struct got_repository *repo = NULL;
1582 struct got_pathlist_head refs, symrefs, wanted_branches, wanted_refs;
1583 struct got_pathlist_entry *pe;
1584 struct got_object_id *pack_hash = NULL;
1585 int ch, fetchfd = -1, fetchstatus;
1586 pid_t fetchpid = -1;
1587 struct got_fetch_progress_arg fpa;
1588 char *git_url = NULL;
1589 int verbosity = 0, fetch_all_branches = 0, mirror_references = 0;
1590 int list_refs_only = 0;
1591 int *pack_fds = NULL;
1593 TAILQ_INIT(&refs);
1594 TAILQ_INIT(&symrefs);
1595 TAILQ_INIT(&wanted_branches);
1596 TAILQ_INIT(&wanted_refs);
1598 while ((ch = getopt(argc, argv, "ab:lmqR:v")) != -1) {
1599 switch (ch) {
1600 case 'a':
1601 fetch_all_branches = 1;
1602 break;
1603 case 'b':
1604 error = got_pathlist_append(&wanted_branches,
1605 optarg, NULL);
1606 if (error)
1607 return error;
1608 break;
1609 case 'l':
1610 list_refs_only = 1;
1611 break;
1612 case 'm':
1613 mirror_references = 1;
1614 break;
1615 case 'q':
1616 verbosity = -1;
1617 break;
1618 case 'R':
1619 error = got_pathlist_append(&wanted_refs,
1620 optarg, NULL);
1621 if (error)
1622 return error;
1623 break;
1624 case 'v':
1625 if (verbosity < 0)
1626 verbosity = 0;
1627 else if (verbosity < 3)
1628 verbosity++;
1629 break;
1630 default:
1631 usage_clone();
1632 break;
1635 argc -= optind;
1636 argv += optind;
1638 if (fetch_all_branches && !TAILQ_EMPTY(&wanted_branches))
1639 option_conflict('a', 'b');
1640 if (list_refs_only) {
1641 if (!TAILQ_EMPTY(&wanted_branches))
1642 option_conflict('l', 'b');
1643 if (fetch_all_branches)
1644 option_conflict('l', 'a');
1645 if (mirror_references)
1646 option_conflict('l', 'm');
1647 if (!TAILQ_EMPTY(&wanted_refs))
1648 option_conflict('l', 'R');
1651 uri = argv[0];
1653 if (argc == 1)
1654 dirname = NULL;
1655 else if (argc == 2)
1656 dirname = argv[1];
1657 else
1658 usage_clone();
1660 error = got_dial_parse_uri(&proto, &host, &port, &server_path,
1661 &repo_name, uri);
1662 if (error)
1663 goto done;
1665 if (asprintf(&git_url, "%s://%s%s%s%s%s", proto,
1666 host, port ? ":" : "", port ? port : "",
1667 server_path[0] != '/' ? "/" : "", server_path) == -1) {
1668 error = got_error_from_errno("asprintf");
1669 goto done;
1672 if (strcmp(proto, "git") == 0) {
1673 #ifndef PROFILE
1674 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
1675 "sendfd dns inet unveil", NULL) == -1)
1676 err(1, "pledge");
1677 #endif
1678 } else if (strcmp(proto, "git+ssh") == 0 ||
1679 strcmp(proto, "ssh") == 0) {
1680 #ifndef PROFILE
1681 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
1682 "sendfd unveil", NULL) == -1)
1683 err(1, "pledge");
1684 #endif
1685 } else if (strcmp(proto, "http") == 0 ||
1686 strcmp(proto, "git+http") == 0) {
1687 error = got_error_path(proto, GOT_ERR_NOT_IMPL);
1688 goto done;
1689 } else {
1690 error = got_error_path(proto, GOT_ERR_BAD_PROTO);
1691 goto done;
1693 if (dirname == NULL) {
1694 if (asprintf(&default_destdir, "%s.git", repo_name) == -1) {
1695 error = got_error_from_errno("asprintf");
1696 goto done;
1698 repo_path = default_destdir;
1699 } else
1700 repo_path = dirname;
1702 if (!list_refs_only) {
1703 error = got_path_mkdir(repo_path);
1704 if (error &&
1705 (!(error->code == GOT_ERR_ERRNO && errno == EISDIR) &&
1706 !(error->code == GOT_ERR_ERRNO && errno == EEXIST)))
1707 goto done;
1708 if (!got_path_dir_is_empty(repo_path)) {
1709 error = got_error_path(repo_path,
1710 GOT_ERR_DIR_NOT_EMPTY);
1711 goto done;
1715 error = got_dial_apply_unveil(proto);
1716 if (error)
1717 goto done;
1719 error = apply_unveil(repo_path, 0, NULL);
1720 if (error)
1721 goto done;
1723 if (verbosity >= 0)
1724 printf("Connecting to %s\n", git_url);
1726 error = got_fetch_connect(&fetchpid, &fetchfd, proto, host, port,
1727 server_path, verbosity);
1728 if (error)
1729 goto done;
1731 if (!list_refs_only) {
1732 error = got_repo_init(repo_path, NULL);
1733 if (error)
1734 goto done;
1735 error = got_repo_pack_fds_open(&pack_fds);
1736 if (error != NULL)
1737 goto done;
1738 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
1739 if (error)
1740 goto done;
1743 fpa.last_scaled_size[0] = '\0';
1744 fpa.last_p_indexed = -1;
1745 fpa.last_p_resolved = -1;
1746 fpa.verbosity = verbosity;
1747 fpa.create_configs = 1;
1748 fpa.configs_created = 0;
1749 fpa.repo = repo;
1750 fpa.config_info.symrefs = &symrefs;
1751 fpa.config_info.wanted_branches = &wanted_branches;
1752 fpa.config_info.wanted_refs = &wanted_refs;
1753 fpa.config_info.proto = proto;
1754 fpa.config_info.host = host;
1755 fpa.config_info.port = port;
1756 fpa.config_info.remote_repo_path = server_path;
1757 fpa.config_info.git_url = git_url;
1758 fpa.config_info.fetch_all_branches = fetch_all_branches;
1759 fpa.config_info.mirror_references = mirror_references;
1760 error = got_fetch_pack(&pack_hash, &refs, &symrefs,
1761 GOT_FETCH_DEFAULT_REMOTE_NAME, mirror_references,
1762 fetch_all_branches, &wanted_branches, &wanted_refs,
1763 list_refs_only, verbosity, fetchfd, repo, NULL,
1764 fetch_progress, &fpa);
1765 if (error)
1766 goto done;
1768 if (list_refs_only) {
1769 error = list_remote_refs(&symrefs, &refs);
1770 goto done;
1773 if (pack_hash == NULL) {
1774 error = got_error_fmt(GOT_ERR_FETCH_FAILED, "%s",
1775 "server sent an empty pack file");
1776 goto done;
1778 error = got_object_id_str(&id_str, pack_hash);
1779 if (error)
1780 goto done;
1781 if (verbosity >= 0)
1782 printf("\nFetched %s.pack\n", id_str);
1783 free(id_str);
1785 /* Set up references provided with the pack file. */
1786 TAILQ_FOREACH(pe, &refs, entry) {
1787 const char *refname = pe->path;
1788 struct got_object_id *id = pe->data;
1789 char *remote_refname;
1791 if (is_wanted_ref(&wanted_refs, refname) &&
1792 !mirror_references) {
1793 error = create_wanted_ref(refname, id,
1794 GOT_FETCH_DEFAULT_REMOTE_NAME,
1795 verbosity - 1, repo);
1796 if (error)
1797 goto done;
1798 continue;
1801 error = create_ref(refname, id, verbosity - 1, repo);
1802 if (error)
1803 goto done;
1805 if (mirror_references)
1806 continue;
1808 if (strncmp("refs/heads/", refname, 11) != 0)
1809 continue;
1811 if (asprintf(&remote_refname,
1812 "refs/remotes/%s/%s", GOT_FETCH_DEFAULT_REMOTE_NAME,
1813 refname + 11) == -1) {
1814 error = got_error_from_errno("asprintf");
1815 goto done;
1817 error = create_ref(remote_refname, id, verbosity - 1, repo);
1818 free(remote_refname);
1819 if (error)
1820 goto done;
1823 /* Set the HEAD reference if the server provided one. */
1824 TAILQ_FOREACH(pe, &symrefs, entry) {
1825 struct got_reference *target_ref;
1826 const char *refname = pe->path;
1827 const char *target = pe->data;
1828 char *remote_refname = NULL, *remote_target = NULL;
1830 if (strcmp(refname, GOT_REF_HEAD) != 0)
1831 continue;
1833 error = got_ref_open(&target_ref, repo, target, 0);
1834 if (error) {
1835 if (error->code == GOT_ERR_NOT_REF) {
1836 error = NULL;
1837 continue;
1839 goto done;
1842 error = create_symref(refname, target_ref, verbosity, repo);
1843 got_ref_close(target_ref);
1844 if (error)
1845 goto done;
1847 if (mirror_references)
1848 continue;
1850 if (strncmp("refs/heads/", target, 11) != 0)
1851 continue;
1853 if (asprintf(&remote_refname,
1854 "refs/remotes/%s/%s", GOT_FETCH_DEFAULT_REMOTE_NAME,
1855 refname) == -1) {
1856 error = got_error_from_errno("asprintf");
1857 goto done;
1859 if (asprintf(&remote_target,
1860 "refs/remotes/%s/%s", GOT_FETCH_DEFAULT_REMOTE_NAME,
1861 target + 11) == -1) {
1862 error = got_error_from_errno("asprintf");
1863 free(remote_refname);
1864 goto done;
1866 error = got_ref_open(&target_ref, repo, remote_target, 0);
1867 if (error) {
1868 free(remote_refname);
1869 free(remote_target);
1870 if (error->code == GOT_ERR_NOT_REF) {
1871 error = NULL;
1872 continue;
1874 goto done;
1876 error = create_symref(remote_refname, target_ref,
1877 verbosity - 1, repo);
1878 free(remote_refname);
1879 free(remote_target);
1880 got_ref_close(target_ref);
1881 if (error)
1882 goto done;
1884 if (pe == NULL) {
1886 * We failed to set the HEAD reference. If we asked for
1887 * a set of wanted branches use the first of one of those
1888 * which could be fetched instead.
1890 TAILQ_FOREACH(pe, &wanted_branches, entry) {
1891 const char *target = pe->path;
1892 struct got_reference *target_ref;
1894 error = got_ref_open(&target_ref, repo, target, 0);
1895 if (error) {
1896 if (error->code == GOT_ERR_NOT_REF) {
1897 error = NULL;
1898 continue;
1900 goto done;
1903 error = create_symref(GOT_REF_HEAD, target_ref,
1904 verbosity, repo);
1905 got_ref_close(target_ref);
1906 if (error)
1907 goto done;
1908 break;
1911 if (!fpa.configs_created && pe != NULL) {
1912 error = create_config_files(fpa.config_info.proto,
1913 fpa.config_info.host, fpa.config_info.port,
1914 fpa.config_info.remote_repo_path,
1915 fpa.config_info.git_url,
1916 fpa.config_info.fetch_all_branches,
1917 fpa.config_info.mirror_references,
1918 fpa.config_info.symrefs,
1919 fpa.config_info.wanted_branches,
1920 fpa.config_info.wanted_refs, fpa.repo);
1921 if (error)
1922 goto done;
1926 if (verbosity >= 0)
1927 printf("Created %s repository '%s'\n",
1928 mirror_references ? "mirrored" : "cloned", repo_path);
1929 done:
1930 if (pack_fds) {
1931 const struct got_error *pack_err =
1932 got_repo_pack_fds_close(pack_fds);
1933 if (error == NULL)
1934 error = pack_err;
1936 if (fetchpid > 0) {
1937 if (kill(fetchpid, SIGTERM) == -1)
1938 error = got_error_from_errno("kill");
1939 if (waitpid(fetchpid, &fetchstatus, 0) == -1 && error == NULL)
1940 error = got_error_from_errno("waitpid");
1942 if (fetchfd != -1 && close(fetchfd) == -1 && error == NULL)
1943 error = got_error_from_errno("close");
1944 if (repo) {
1945 const struct got_error *close_err = got_repo_close(repo);
1946 if (error == NULL)
1947 error = close_err;
1949 got_pathlist_free(&refs, GOT_PATHLIST_FREE_ALL);
1950 got_pathlist_free(&symrefs, GOT_PATHLIST_FREE_ALL);
1951 got_pathlist_free(&wanted_branches, GOT_PATHLIST_FREE_NONE);
1952 got_pathlist_free(&wanted_refs, GOT_PATHLIST_FREE_NONE);
1953 free(pack_hash);
1954 free(proto);
1955 free(host);
1956 free(port);
1957 free(server_path);
1958 free(repo_name);
1959 free(default_destdir);
1960 free(git_url);
1961 return error;
1964 static const struct got_error *
1965 update_ref(struct got_reference *ref, struct got_object_id *new_id,
1966 int replace_tags, int verbosity, struct got_repository *repo)
1968 const struct got_error *err = NULL;
1969 char *new_id_str = NULL;
1970 struct got_object_id *old_id = NULL;
1972 err = got_object_id_str(&new_id_str, new_id);
1973 if (err)
1974 goto done;
1976 if (!replace_tags &&
1977 strncmp(got_ref_get_name(ref), "refs/tags/", 10) == 0) {
1978 err = got_ref_resolve(&old_id, repo, ref);
1979 if (err)
1980 goto done;
1981 if (got_object_id_cmp(old_id, new_id) == 0)
1982 goto done;
1983 if (verbosity >= 0) {
1984 printf("Rejecting update of existing tag %s: %s\n",
1985 got_ref_get_name(ref), new_id_str);
1987 goto done;
1990 if (got_ref_is_symbolic(ref)) {
1991 if (verbosity >= 0) {
1992 printf("Replacing reference %s: %s\n",
1993 got_ref_get_name(ref),
1994 got_ref_get_symref_target(ref));
1996 err = got_ref_change_symref_to_ref(ref, new_id);
1997 if (err)
1998 goto done;
1999 err = got_ref_write(ref, repo);
2000 if (err)
2001 goto done;
2002 } else {
2003 err = got_ref_resolve(&old_id, repo, ref);
2004 if (err)
2005 goto done;
2006 if (got_object_id_cmp(old_id, new_id) == 0)
2007 goto done;
2009 err = got_ref_change_ref(ref, new_id);
2010 if (err)
2011 goto done;
2012 err = got_ref_write(ref, repo);
2013 if (err)
2014 goto done;
2017 if (verbosity >= 0)
2018 printf("Updated %s: %s\n", got_ref_get_name(ref),
2019 new_id_str);
2020 done:
2021 free(old_id);
2022 free(new_id_str);
2023 return err;
2026 static const struct got_error *
2027 update_symref(const char *refname, struct got_reference *target_ref,
2028 int verbosity, struct got_repository *repo)
2030 const struct got_error *err = NULL, *unlock_err;
2031 struct got_reference *symref;
2032 int symref_is_locked = 0;
2034 err = got_ref_open(&symref, repo, refname, 1);
2035 if (err) {
2036 if (err->code != GOT_ERR_NOT_REF)
2037 return err;
2038 err = got_ref_alloc_symref(&symref, refname, target_ref);
2039 if (err)
2040 goto done;
2042 err = got_ref_write(symref, repo);
2043 if (err)
2044 goto done;
2046 if (verbosity >= 0)
2047 printf("Created reference %s: %s\n",
2048 got_ref_get_name(symref),
2049 got_ref_get_symref_target(symref));
2050 } else {
2051 symref_is_locked = 1;
2053 if (strcmp(got_ref_get_symref_target(symref),
2054 got_ref_get_name(target_ref)) == 0)
2055 goto done;
2057 err = got_ref_change_symref(symref,
2058 got_ref_get_name(target_ref));
2059 if (err)
2060 goto done;
2062 err = got_ref_write(symref, repo);
2063 if (err)
2064 goto done;
2066 if (verbosity >= 0)
2067 printf("Updated %s: %s\n", got_ref_get_name(symref),
2068 got_ref_get_symref_target(symref));
2071 done:
2072 if (symref_is_locked) {
2073 unlock_err = got_ref_unlock(symref);
2074 if (unlock_err && err == NULL)
2075 err = unlock_err;
2077 got_ref_close(symref);
2078 return err;
2081 __dead static void
2082 usage_fetch(void)
2084 fprintf(stderr, "usage: %s fetch [-adlqtvX] [-b branch] "
2085 "[-R reference] [-r repository-path] [remote-repository]\n",
2086 getprogname());
2087 exit(1);
2090 static const struct got_error *
2091 delete_missing_ref(struct got_reference *ref,
2092 int verbosity, struct got_repository *repo)
2094 const struct got_error *err = NULL;
2095 struct got_object_id *id = NULL;
2096 char *id_str = NULL;
2098 if (got_ref_is_symbolic(ref)) {
2099 err = got_ref_delete(ref, repo);
2100 if (err)
2101 return err;
2102 if (verbosity >= 0) {
2103 printf("Deleted %s: %s\n",
2104 got_ref_get_name(ref),
2105 got_ref_get_symref_target(ref));
2107 } else {
2108 err = got_ref_resolve(&id, repo, ref);
2109 if (err)
2110 return err;
2111 err = got_object_id_str(&id_str, id);
2112 if (err)
2113 goto done;
2115 err = got_ref_delete(ref, repo);
2116 if (err)
2117 goto done;
2118 if (verbosity >= 0) {
2119 printf("Deleted %s: %s\n",
2120 got_ref_get_name(ref), id_str);
2123 done:
2124 free(id);
2125 free(id_str);
2126 return err;
2129 static const struct got_error *
2130 delete_missing_refs(struct got_pathlist_head *their_refs,
2131 struct got_pathlist_head *their_symrefs,
2132 const struct got_remote_repo *remote,
2133 int verbosity, struct got_repository *repo)
2135 const struct got_error *err = NULL, *unlock_err;
2136 struct got_reflist_head my_refs;
2137 struct got_reflist_entry *re;
2138 struct got_pathlist_entry *pe;
2139 char *remote_namespace = NULL;
2140 char *local_refname = NULL;
2142 TAILQ_INIT(&my_refs);
2144 if (asprintf(&remote_namespace, "refs/remotes/%s/", remote->name)
2145 == -1)
2146 return got_error_from_errno("asprintf");
2148 err = got_ref_list(&my_refs, repo, NULL, got_ref_cmp_by_name, NULL);
2149 if (err)
2150 goto done;
2152 TAILQ_FOREACH(re, &my_refs, entry) {
2153 const char *refname = got_ref_get_name(re->ref);
2154 const char *their_refname;
2156 if (remote->mirror_references) {
2157 their_refname = refname;
2158 } else {
2159 if (strncmp(refname, remote_namespace,
2160 strlen(remote_namespace)) == 0) {
2161 if (strcmp(refname + strlen(remote_namespace),
2162 GOT_REF_HEAD) == 0)
2163 continue;
2164 if (asprintf(&local_refname, "refs/heads/%s",
2165 refname + strlen(remote_namespace)) == -1) {
2166 err = got_error_from_errno("asprintf");
2167 goto done;
2169 } else if (strncmp(refname, "refs/tags/", 10) != 0)
2170 continue;
2172 their_refname = local_refname;
2175 TAILQ_FOREACH(pe, their_refs, entry) {
2176 if (strcmp(their_refname, pe->path) == 0)
2177 break;
2179 if (pe != NULL)
2180 continue;
2182 TAILQ_FOREACH(pe, their_symrefs, entry) {
2183 if (strcmp(their_refname, pe->path) == 0)
2184 break;
2186 if (pe != NULL)
2187 continue;
2189 err = delete_missing_ref(re->ref, verbosity, repo);
2190 if (err)
2191 break;
2193 if (local_refname) {
2194 struct got_reference *ref;
2195 err = got_ref_open(&ref, repo, local_refname, 1);
2196 if (err) {
2197 if (err->code != GOT_ERR_NOT_REF)
2198 break;
2199 free(local_refname);
2200 local_refname = NULL;
2201 continue;
2203 err = delete_missing_ref(ref, verbosity, repo);
2204 if (err)
2205 break;
2206 unlock_err = got_ref_unlock(ref);
2207 got_ref_close(ref);
2208 if (unlock_err && err == NULL) {
2209 err = unlock_err;
2210 break;
2213 free(local_refname);
2214 local_refname = NULL;
2217 done:
2218 got_ref_list_free(&my_refs);
2219 free(remote_namespace);
2220 free(local_refname);
2221 return err;
2224 static const struct got_error *
2225 update_wanted_ref(const char *refname, struct got_object_id *id,
2226 const char *remote_repo_name, int verbosity, struct got_repository *repo)
2228 const struct got_error *err, *unlock_err;
2229 char *remote_refname;
2230 struct got_reference *ref;
2232 if (strncmp("refs/", refname, 5) == 0)
2233 refname += 5;
2235 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
2236 remote_repo_name, refname) == -1)
2237 return got_error_from_errno("asprintf");
2239 err = got_ref_open(&ref, repo, remote_refname, 1);
2240 if (err) {
2241 if (err->code != GOT_ERR_NOT_REF)
2242 goto done;
2243 err = create_ref(remote_refname, id, verbosity, repo);
2244 } else {
2245 err = update_ref(ref, id, 0, verbosity, repo);
2246 unlock_err = got_ref_unlock(ref);
2247 if (unlock_err && err == NULL)
2248 err = unlock_err;
2249 got_ref_close(ref);
2251 done:
2252 free(remote_refname);
2253 return err;
2256 static const struct got_error *
2257 delete_ref(struct got_repository *repo, struct got_reference *ref)
2259 const struct got_error *err = NULL;
2260 struct got_object_id *id = NULL;
2261 char *id_str = NULL;
2262 const char *target;
2264 if (got_ref_is_symbolic(ref)) {
2265 target = got_ref_get_symref_target(ref);
2266 } else {
2267 err = got_ref_resolve(&id, repo, ref);
2268 if (err)
2269 goto done;
2270 err = got_object_id_str(&id_str, id);
2271 if (err)
2272 goto done;
2273 target = id_str;
2276 err = got_ref_delete(ref, repo);
2277 if (err)
2278 goto done;
2280 printf("Deleted %s: %s\n", got_ref_get_name(ref), target);
2281 done:
2282 free(id);
2283 free(id_str);
2284 return err;
2287 static const struct got_error *
2288 delete_refs_for_remote(struct got_repository *repo, const char *remote_name)
2290 const struct got_error *err = NULL;
2291 struct got_reflist_head refs;
2292 struct got_reflist_entry *re;
2293 char *prefix;
2295 TAILQ_INIT(&refs);
2297 if (asprintf(&prefix, "refs/remotes/%s", remote_name) == -1) {
2298 err = got_error_from_errno("asprintf");
2299 goto done;
2301 err = got_ref_list(&refs, repo, prefix, got_ref_cmp_by_name, NULL);
2302 if (err)
2303 goto done;
2305 TAILQ_FOREACH(re, &refs, entry)
2306 delete_ref(repo, re->ref);
2307 done:
2308 got_ref_list_free(&refs);
2309 return err;
2312 static const struct got_error *
2313 cmd_fetch(int argc, char *argv[])
2315 const struct got_error *error = NULL, *unlock_err;
2316 char *cwd = NULL, *repo_path = NULL;
2317 const char *remote_name;
2318 char *proto = NULL, *host = NULL, *port = NULL;
2319 char *repo_name = NULL, *server_path = NULL;
2320 const struct got_remote_repo *remotes, *remote = NULL;
2321 int nremotes;
2322 char *id_str = NULL;
2323 struct got_repository *repo = NULL;
2324 struct got_worktree *worktree = NULL;
2325 const struct got_gotconfig *repo_conf = NULL, *worktree_conf = NULL;
2326 struct got_pathlist_head refs, symrefs, wanted_branches, wanted_refs;
2327 struct got_pathlist_entry *pe;
2328 struct got_object_id *pack_hash = NULL;
2329 int i, ch, fetchfd = -1, fetchstatus;
2330 pid_t fetchpid = -1;
2331 struct got_fetch_progress_arg fpa;
2332 int verbosity = 0, fetch_all_branches = 0, list_refs_only = 0;
2333 int delete_refs = 0, replace_tags = 0, delete_remote = 0;
2334 int *pack_fds = NULL, have_bflag = 0;
2335 const char *worktree_branch = NULL;
2337 TAILQ_INIT(&refs);
2338 TAILQ_INIT(&symrefs);
2339 TAILQ_INIT(&wanted_branches);
2340 TAILQ_INIT(&wanted_refs);
2342 while ((ch = getopt(argc, argv, "ab:dlqR:r:tvX")) != -1) {
2343 switch (ch) {
2344 case 'a':
2345 fetch_all_branches = 1;
2346 break;
2347 case 'b':
2348 error = got_pathlist_append(&wanted_branches,
2349 optarg, NULL);
2350 if (error)
2351 return error;
2352 have_bflag = 1;
2353 break;
2354 case 'd':
2355 delete_refs = 1;
2356 break;
2357 case 'l':
2358 list_refs_only = 1;
2359 break;
2360 case 'q':
2361 verbosity = -1;
2362 break;
2363 case 'R':
2364 error = got_pathlist_append(&wanted_refs,
2365 optarg, NULL);
2366 if (error)
2367 return error;
2368 break;
2369 case 'r':
2370 repo_path = realpath(optarg, NULL);
2371 if (repo_path == NULL)
2372 return got_error_from_errno2("realpath",
2373 optarg);
2374 got_path_strip_trailing_slashes(repo_path);
2375 break;
2376 case 't':
2377 replace_tags = 1;
2378 break;
2379 case 'v':
2380 if (verbosity < 0)
2381 verbosity = 0;
2382 else if (verbosity < 3)
2383 verbosity++;
2384 break;
2385 case 'X':
2386 delete_remote = 1;
2387 break;
2388 default:
2389 usage_fetch();
2390 break;
2393 argc -= optind;
2394 argv += optind;
2396 if (fetch_all_branches && !TAILQ_EMPTY(&wanted_branches))
2397 option_conflict('a', 'b');
2398 if (list_refs_only) {
2399 if (!TAILQ_EMPTY(&wanted_branches))
2400 option_conflict('l', 'b');
2401 if (fetch_all_branches)
2402 option_conflict('l', 'a');
2403 if (delete_refs)
2404 option_conflict('l', 'd');
2405 if (delete_remote)
2406 option_conflict('l', 'X');
2408 if (delete_remote) {
2409 if (fetch_all_branches)
2410 option_conflict('X', 'a');
2411 if (!TAILQ_EMPTY(&wanted_branches))
2412 option_conflict('X', 'b');
2413 if (delete_refs)
2414 option_conflict('X', 'd');
2415 if (replace_tags)
2416 option_conflict('X', 't');
2417 if (!TAILQ_EMPTY(&wanted_refs))
2418 option_conflict('X', 'R');
2421 if (argc == 0) {
2422 if (delete_remote)
2423 errx(1, "-X option requires a remote name");
2424 remote_name = GOT_FETCH_DEFAULT_REMOTE_NAME;
2425 } else if (argc == 1)
2426 remote_name = argv[0];
2427 else
2428 usage_fetch();
2430 cwd = getcwd(NULL, 0);
2431 if (cwd == NULL) {
2432 error = got_error_from_errno("getcwd");
2433 goto done;
2436 error = got_repo_pack_fds_open(&pack_fds);
2437 if (error != NULL)
2438 goto done;
2440 if (repo_path == NULL) {
2441 error = got_worktree_open(&worktree, cwd);
2442 if (error && error->code != GOT_ERR_NOT_WORKTREE)
2443 goto done;
2444 else
2445 error = NULL;
2446 if (worktree) {
2447 repo_path =
2448 strdup(got_worktree_get_repo_path(worktree));
2449 if (repo_path == NULL)
2450 error = got_error_from_errno("strdup");
2451 if (error)
2452 goto done;
2453 } else {
2454 repo_path = strdup(cwd);
2455 if (repo_path == NULL) {
2456 error = got_error_from_errno("strdup");
2457 goto done;
2462 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
2463 if (error)
2464 goto done;
2466 if (delete_remote) {
2467 error = delete_refs_for_remote(repo, remote_name);
2468 goto done; /* nothing else to do */
2471 if (worktree) {
2472 worktree_conf = got_worktree_get_gotconfig(worktree);
2473 if (worktree_conf) {
2474 got_gotconfig_get_remotes(&nremotes, &remotes,
2475 worktree_conf);
2476 for (i = 0; i < nremotes; i++) {
2477 if (strcmp(remotes[i].name, remote_name) == 0) {
2478 remote = &remotes[i];
2479 break;
2484 if (remote == NULL) {
2485 repo_conf = got_repo_get_gotconfig(repo);
2486 if (repo_conf) {
2487 got_gotconfig_get_remotes(&nremotes, &remotes,
2488 repo_conf);
2489 for (i = 0; i < nremotes; i++) {
2490 if (strcmp(remotes[i].name, remote_name) == 0) {
2491 remote = &remotes[i];
2492 break;
2497 if (remote == NULL) {
2498 got_repo_get_gitconfig_remotes(&nremotes, &remotes, repo);
2499 for (i = 0; i < nremotes; i++) {
2500 if (strcmp(remotes[i].name, remote_name) == 0) {
2501 remote = &remotes[i];
2502 break;
2506 if (remote == NULL) {
2507 error = got_error_path(remote_name, GOT_ERR_NO_REMOTE);
2508 goto done;
2511 if (TAILQ_EMPTY(&wanted_branches)) {
2512 if (!fetch_all_branches)
2513 fetch_all_branches = remote->fetch_all_branches;
2514 for (i = 0; i < remote->nfetch_branches; i++) {
2515 error = got_pathlist_append(&wanted_branches,
2516 remote->fetch_branches[i], NULL);
2517 if (error)
2518 goto done;
2521 if (TAILQ_EMPTY(&wanted_refs)) {
2522 for (i = 0; i < remote->nfetch_refs; i++) {
2523 error = got_pathlist_append(&wanted_refs,
2524 remote->fetch_refs[i], NULL);
2525 if (error)
2526 goto done;
2530 error = got_dial_parse_uri(&proto, &host, &port, &server_path,
2531 &repo_name, remote->fetch_url);
2532 if (error)
2533 goto done;
2535 if (strcmp(proto, "git") == 0) {
2536 #ifndef PROFILE
2537 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
2538 "sendfd dns inet unveil", NULL) == -1)
2539 err(1, "pledge");
2540 #endif
2541 } else if (strcmp(proto, "git+ssh") == 0 ||
2542 strcmp(proto, "ssh") == 0) {
2543 #ifndef PROFILE
2544 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
2545 "sendfd unveil", NULL) == -1)
2546 err(1, "pledge");
2547 #endif
2548 } else if (strcmp(proto, "http") == 0 ||
2549 strcmp(proto, "git+http") == 0) {
2550 error = got_error_path(proto, GOT_ERR_NOT_IMPL);
2551 goto done;
2552 } else {
2553 error = got_error_path(proto, GOT_ERR_BAD_PROTO);
2554 goto done;
2557 error = got_dial_apply_unveil(proto);
2558 if (error)
2559 goto done;
2561 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
2562 if (error)
2563 goto done;
2565 if (verbosity >= 0) {
2566 printf("Connecting to \"%s\" %s://%s%s%s%s%s\n",
2567 remote->name, proto, host,
2568 port ? ":" : "", port ? port : "",
2569 *server_path == '/' ? "" : "/", server_path);
2572 error = got_fetch_connect(&fetchpid, &fetchfd, proto, host, port,
2573 server_path, verbosity);
2574 if (error)
2575 goto done;
2577 if (worktree && !have_bflag) {
2578 const char *refname;
2580 refname = got_worktree_get_head_ref_name(worktree);
2581 if (strncmp(refname, "refs/heads/", 11) == 0)
2582 worktree_branch = refname;
2585 fpa.last_scaled_size[0] = '\0';
2586 fpa.last_p_indexed = -1;
2587 fpa.last_p_resolved = -1;
2588 fpa.verbosity = verbosity;
2589 fpa.repo = repo;
2590 fpa.create_configs = 0;
2591 fpa.configs_created = 0;
2592 memset(&fpa.config_info, 0, sizeof(fpa.config_info));
2593 error = got_fetch_pack(&pack_hash, &refs, &symrefs, remote->name,
2594 remote->mirror_references, fetch_all_branches, &wanted_branches,
2595 &wanted_refs, list_refs_only, verbosity, fetchfd, repo,
2596 worktree_branch, fetch_progress, &fpa);
2597 if (error)
2598 goto done;
2600 if (list_refs_only) {
2601 error = list_remote_refs(&symrefs, &refs);
2602 goto done;
2605 if (pack_hash == NULL) {
2606 if (verbosity >= 0)
2607 printf("Already up-to-date\n");
2608 } else if (verbosity >= 0) {
2609 error = got_object_id_str(&id_str, pack_hash);
2610 if (error)
2611 goto done;
2612 printf("\nFetched %s.pack\n", id_str);
2613 free(id_str);
2614 id_str = NULL;
2617 /* Update references provided with the pack file. */
2618 TAILQ_FOREACH(pe, &refs, entry) {
2619 const char *refname = pe->path;
2620 struct got_object_id *id = pe->data;
2621 struct got_reference *ref;
2622 char *remote_refname;
2624 if (is_wanted_ref(&wanted_refs, refname) &&
2625 !remote->mirror_references) {
2626 error = update_wanted_ref(refname, id,
2627 remote->name, verbosity, repo);
2628 if (error)
2629 goto done;
2630 continue;
2633 if (remote->mirror_references ||
2634 strncmp("refs/tags/", refname, 10) == 0) {
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 error = update_ref(ref, id, replace_tags,
2645 verbosity, repo);
2646 unlock_err = got_ref_unlock(ref);
2647 if (unlock_err && error == NULL)
2648 error = unlock_err;
2649 got_ref_close(ref);
2650 if (error)
2651 goto done;
2653 } else if (strncmp("refs/heads/", refname, 11) == 0) {
2654 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
2655 remote_name, refname + 11) == -1) {
2656 error = got_error_from_errno("asprintf");
2657 goto done;
2660 error = got_ref_open(&ref, repo, remote_refname, 1);
2661 if (error) {
2662 if (error->code != GOT_ERR_NOT_REF)
2663 goto done;
2664 error = create_ref(remote_refname, id,
2665 verbosity, repo);
2666 if (error)
2667 goto done;
2668 } else {
2669 error = update_ref(ref, id, replace_tags,
2670 verbosity, repo);
2671 unlock_err = got_ref_unlock(ref);
2672 if (unlock_err && error == NULL)
2673 error = unlock_err;
2674 got_ref_close(ref);
2675 if (error)
2676 goto done;
2679 /* Also create a local branch if none exists yet. */
2680 error = got_ref_open(&ref, repo, refname, 1);
2681 if (error) {
2682 if (error->code != GOT_ERR_NOT_REF)
2683 goto done;
2684 error = create_ref(refname, id, verbosity,
2685 repo);
2686 if (error)
2687 goto done;
2688 } else {
2689 unlock_err = got_ref_unlock(ref);
2690 if (unlock_err && error == NULL)
2691 error = unlock_err;
2692 got_ref_close(ref);
2696 if (delete_refs) {
2697 error = delete_missing_refs(&refs, &symrefs, remote,
2698 verbosity, repo);
2699 if (error)
2700 goto done;
2703 if (!remote->mirror_references) {
2704 /* Update remote HEAD reference if the server provided one. */
2705 TAILQ_FOREACH(pe, &symrefs, entry) {
2706 struct got_reference *target_ref;
2707 const char *refname = pe->path;
2708 const char *target = pe->data;
2709 char *remote_refname = NULL, *remote_target = NULL;
2711 if (strcmp(refname, GOT_REF_HEAD) != 0)
2712 continue;
2714 if (strncmp("refs/heads/", target, 11) != 0)
2715 continue;
2717 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
2718 remote->name, refname) == -1) {
2719 error = got_error_from_errno("asprintf");
2720 goto done;
2722 if (asprintf(&remote_target, "refs/remotes/%s/%s",
2723 remote->name, target + 11) == -1) {
2724 error = got_error_from_errno("asprintf");
2725 free(remote_refname);
2726 goto done;
2729 error = got_ref_open(&target_ref, repo, remote_target,
2730 0);
2731 if (error) {
2732 free(remote_refname);
2733 free(remote_target);
2734 if (error->code == GOT_ERR_NOT_REF) {
2735 error = NULL;
2736 continue;
2738 goto done;
2740 error = update_symref(remote_refname, target_ref,
2741 verbosity, repo);
2742 free(remote_refname);
2743 free(remote_target);
2744 got_ref_close(target_ref);
2745 if (error)
2746 goto done;
2749 done:
2750 if (fetchpid > 0) {
2751 if (kill(fetchpid, SIGTERM) == -1)
2752 error = got_error_from_errno("kill");
2753 if (waitpid(fetchpid, &fetchstatus, 0) == -1 && error == NULL)
2754 error = got_error_from_errno("waitpid");
2756 if (fetchfd != -1 && close(fetchfd) == -1 && error == NULL)
2757 error = got_error_from_errno("close");
2758 if (repo) {
2759 const struct got_error *close_err = got_repo_close(repo);
2760 if (error == NULL)
2761 error = close_err;
2763 if (worktree)
2764 got_worktree_close(worktree);
2765 if (pack_fds) {
2766 const struct got_error *pack_err =
2767 got_repo_pack_fds_close(pack_fds);
2768 if (error == NULL)
2769 error = pack_err;
2771 got_pathlist_free(&refs, GOT_PATHLIST_FREE_ALL);
2772 got_pathlist_free(&symrefs, GOT_PATHLIST_FREE_ALL);
2773 got_pathlist_free(&wanted_branches, GOT_PATHLIST_FREE_NONE);
2774 got_pathlist_free(&wanted_refs, GOT_PATHLIST_FREE_NONE);
2775 free(id_str);
2776 free(cwd);
2777 free(repo_path);
2778 free(pack_hash);
2779 free(proto);
2780 free(host);
2781 free(port);
2782 free(server_path);
2783 free(repo_name);
2784 return error;
2788 __dead static void
2789 usage_checkout(void)
2791 fprintf(stderr, "usage: %s checkout [-Eq] [-b branch] [-c commit] "
2792 "[-p path-prefix] repository-path [work-tree-path]\n",
2793 getprogname());
2794 exit(1);
2797 static void
2798 show_worktree_base_ref_warning(void)
2800 fprintf(stderr, "%s: warning: could not create a reference "
2801 "to the work tree's base commit; the commit could be "
2802 "garbage-collected by Git or 'gotadmin cleanup'; making the "
2803 "repository writable and running 'got update' will prevent this\n",
2804 getprogname());
2807 struct got_checkout_progress_arg {
2808 const char *worktree_path;
2809 int had_base_commit_ref_error;
2810 int verbosity;
2813 static const struct got_error *
2814 checkout_progress(void *arg, unsigned char status, const char *path)
2816 struct got_checkout_progress_arg *a = arg;
2818 /* Base commit bump happens silently. */
2819 if (status == GOT_STATUS_BUMP_BASE)
2820 return NULL;
2822 if (status == GOT_STATUS_BASE_REF_ERR) {
2823 a->had_base_commit_ref_error = 1;
2824 return NULL;
2827 while (path[0] == '/')
2828 path++;
2830 if (a->verbosity >= 0)
2831 printf("%c %s/%s\n", status, a->worktree_path, path);
2833 return NULL;
2836 static const struct got_error *
2837 check_cancelled(void *arg)
2839 if (sigint_received || sigpipe_received)
2840 return got_error(GOT_ERR_CANCELLED);
2841 return NULL;
2844 static const struct got_error *
2845 check_linear_ancestry(struct got_object_id *commit_id,
2846 struct got_object_id *base_commit_id, int allow_forwards_in_time_only,
2847 struct got_repository *repo)
2849 const struct got_error *err = NULL;
2850 struct got_object_id *yca_id;
2852 err = got_commit_graph_find_youngest_common_ancestor(&yca_id,
2853 commit_id, base_commit_id, 1, repo, check_cancelled, NULL);
2854 if (err)
2855 return err;
2857 if (yca_id == NULL)
2858 return got_error(GOT_ERR_ANCESTRY);
2861 * Require a straight line of history between the target commit
2862 * and the work tree's base commit.
2864 * Non-linear situations such as this require a rebase:
2866 * (commit) D F (base_commit)
2867 * \ /
2868 * C E
2869 * \ /
2870 * B (yca)
2871 * |
2872 * A
2874 * 'got update' only handles linear cases:
2875 * Update forwards in time: A (base/yca) - B - C - D (commit)
2876 * Update backwards in time: D (base) - C - B - A (commit/yca)
2878 if (allow_forwards_in_time_only) {
2879 if (got_object_id_cmp(base_commit_id, yca_id) != 0)
2880 return got_error(GOT_ERR_ANCESTRY);
2881 } else if (got_object_id_cmp(commit_id, yca_id) != 0 &&
2882 got_object_id_cmp(base_commit_id, yca_id) != 0)
2883 return got_error(GOT_ERR_ANCESTRY);
2885 free(yca_id);
2886 return NULL;
2889 static const struct got_error *
2890 check_same_branch(struct got_object_id *commit_id,
2891 struct got_reference *head_ref, struct got_object_id *yca_id,
2892 struct got_repository *repo)
2894 const struct got_error *err = NULL;
2895 struct got_commit_graph *graph = NULL;
2896 struct got_object_id *head_commit_id = NULL;
2897 int is_same_branch = 0;
2899 err = got_ref_resolve(&head_commit_id, repo, head_ref);
2900 if (err)
2901 goto done;
2903 if (got_object_id_cmp(head_commit_id, commit_id) == 0) {
2904 is_same_branch = 1;
2905 goto done;
2907 if (yca_id && got_object_id_cmp(commit_id, yca_id) == 0) {
2908 is_same_branch = 1;
2909 goto done;
2912 err = got_commit_graph_open(&graph, "/", 1);
2913 if (err)
2914 goto done;
2916 err = got_commit_graph_iter_start(graph, head_commit_id, repo,
2917 check_cancelled, NULL);
2918 if (err)
2919 goto done;
2921 for (;;) {
2922 struct got_object_id id;
2924 err = got_commit_graph_iter_next(&id, graph, repo,
2925 check_cancelled, NULL);
2926 if (err) {
2927 if (err->code == GOT_ERR_ITER_COMPLETED)
2928 err = NULL;
2929 break;
2932 if (yca_id && got_object_id_cmp(&id, yca_id) == 0)
2933 break;
2934 if (got_object_id_cmp(&id, commit_id) == 0) {
2935 is_same_branch = 1;
2936 break;
2939 done:
2940 if (graph)
2941 got_commit_graph_close(graph);
2942 free(head_commit_id);
2943 if (!err && !is_same_branch)
2944 err = got_error(GOT_ERR_ANCESTRY);
2945 return err;
2948 static const struct got_error *
2949 checkout_ancestry_error(struct got_reference *ref, const char *commit_id_str)
2951 static char msg[512];
2952 const char *branch_name;
2954 if (got_ref_is_symbolic(ref))
2955 branch_name = got_ref_get_symref_target(ref);
2956 else
2957 branch_name = got_ref_get_name(ref);
2959 if (strncmp("refs/heads/", branch_name, 11) == 0)
2960 branch_name += 11;
2962 snprintf(msg, sizeof(msg),
2963 "target commit is not contained in branch '%s'; "
2964 "the branch to use must be specified with -b; "
2965 "if necessary a new branch can be created for "
2966 "this commit with 'got branch -c %s BRANCH_NAME'",
2967 branch_name, commit_id_str);
2969 return got_error_msg(GOT_ERR_ANCESTRY, msg);
2972 static const struct got_error *
2973 cmd_checkout(int argc, char *argv[])
2975 const struct got_error *error = NULL;
2976 struct got_repository *repo = NULL;
2977 struct got_reference *head_ref = NULL, *ref = NULL;
2978 struct got_worktree *worktree = NULL;
2979 char *repo_path = NULL;
2980 char *worktree_path = NULL;
2981 const char *path_prefix = "";
2982 const char *branch_name = GOT_REF_HEAD, *refname = NULL;
2983 char *commit_id_str = NULL;
2984 struct got_object_id *commit_id = NULL;
2985 char *cwd = NULL;
2986 int ch, same_path_prefix, allow_nonempty = 0, verbosity = 0;
2987 struct got_pathlist_head paths;
2988 struct got_checkout_progress_arg cpa;
2989 int *pack_fds = NULL;
2991 TAILQ_INIT(&paths);
2993 while ((ch = getopt(argc, argv, "b:c:Ep:q")) != -1) {
2994 switch (ch) {
2995 case 'b':
2996 branch_name = optarg;
2997 break;
2998 case 'c':
2999 commit_id_str = strdup(optarg);
3000 if (commit_id_str == NULL)
3001 return got_error_from_errno("strdup");
3002 break;
3003 case 'E':
3004 allow_nonempty = 1;
3005 break;
3006 case 'p':
3007 path_prefix = optarg;
3008 break;
3009 case 'q':
3010 verbosity = -1;
3011 break;
3012 default:
3013 usage_checkout();
3014 /* NOTREACHED */
3018 argc -= optind;
3019 argv += optind;
3021 #ifndef PROFILE
3022 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
3023 "unveil", NULL) == -1)
3024 err(1, "pledge");
3025 #endif
3026 if (argc == 1) {
3027 char *base, *dotgit;
3028 const char *path;
3029 repo_path = realpath(argv[0], NULL);
3030 if (repo_path == NULL)
3031 return got_error_from_errno2("realpath", argv[0]);
3032 cwd = getcwd(NULL, 0);
3033 if (cwd == NULL) {
3034 error = got_error_from_errno("getcwd");
3035 goto done;
3037 if (path_prefix[0])
3038 path = path_prefix;
3039 else
3040 path = repo_path;
3041 error = got_path_basename(&base, path);
3042 if (error)
3043 goto done;
3044 dotgit = strstr(base, ".git");
3045 if (dotgit)
3046 *dotgit = '\0';
3047 if (asprintf(&worktree_path, "%s/%s", cwd, base) == -1) {
3048 error = got_error_from_errno("asprintf");
3049 free(base);
3050 goto done;
3052 free(base);
3053 } else if (argc == 2) {
3054 repo_path = realpath(argv[0], NULL);
3055 if (repo_path == NULL) {
3056 error = got_error_from_errno2("realpath", argv[0]);
3057 goto done;
3059 worktree_path = realpath(argv[1], NULL);
3060 if (worktree_path == NULL) {
3061 if (errno != ENOENT) {
3062 error = got_error_from_errno2("realpath",
3063 argv[1]);
3064 goto done;
3066 worktree_path = strdup(argv[1]);
3067 if (worktree_path == NULL) {
3068 error = got_error_from_errno("strdup");
3069 goto done;
3072 } else
3073 usage_checkout();
3075 got_path_strip_trailing_slashes(repo_path);
3076 got_path_strip_trailing_slashes(worktree_path);
3078 error = got_repo_pack_fds_open(&pack_fds);
3079 if (error != NULL)
3080 goto done;
3082 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
3083 if (error != NULL)
3084 goto done;
3086 /* Pre-create work tree path for unveil(2) */
3087 error = got_path_mkdir(worktree_path);
3088 if (error) {
3089 if (!(error->code == GOT_ERR_ERRNO && errno == EISDIR) &&
3090 !(error->code == GOT_ERR_ERRNO && errno == EEXIST))
3091 goto done;
3092 if (!allow_nonempty &&
3093 !got_path_dir_is_empty(worktree_path)) {
3094 error = got_error_path(worktree_path,
3095 GOT_ERR_DIR_NOT_EMPTY);
3096 goto done;
3100 error = apply_unveil(got_repo_get_path(repo), 0, worktree_path);
3101 if (error)
3102 goto done;
3104 error = got_ref_open(&head_ref, repo, branch_name, 0);
3105 if (error != NULL)
3106 goto done;
3108 error = got_worktree_init(worktree_path, head_ref, path_prefix, repo);
3109 if (error != NULL && !(error->code == GOT_ERR_ERRNO && errno == EEXIST))
3110 goto done;
3112 error = got_worktree_open(&worktree, worktree_path);
3113 if (error != NULL)
3114 goto done;
3116 error = got_worktree_match_path_prefix(&same_path_prefix, worktree,
3117 path_prefix);
3118 if (error != NULL)
3119 goto done;
3120 if (!same_path_prefix) {
3121 error = got_error(GOT_ERR_PATH_PREFIX);
3122 goto done;
3125 if (commit_id_str) {
3126 struct got_reflist_head refs;
3127 TAILQ_INIT(&refs);
3128 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
3129 NULL);
3130 if (error)
3131 goto done;
3132 error = got_repo_match_object_id(&commit_id, NULL,
3133 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
3134 got_ref_list_free(&refs);
3135 if (error)
3136 goto done;
3137 error = check_linear_ancestry(commit_id,
3138 got_worktree_get_base_commit_id(worktree), 0, repo);
3139 if (error != NULL) {
3140 if (error->code == GOT_ERR_ANCESTRY) {
3141 error = checkout_ancestry_error(
3142 head_ref, commit_id_str);
3144 goto done;
3146 error = check_same_branch(commit_id, head_ref, NULL, repo);
3147 if (error) {
3148 if (error->code == GOT_ERR_ANCESTRY) {
3149 error = checkout_ancestry_error(
3150 head_ref, commit_id_str);
3152 goto done;
3154 error = got_worktree_set_base_commit_id(worktree, repo,
3155 commit_id);
3156 if (error)
3157 goto done;
3158 /* Expand potentially abbreviated commit ID string. */
3159 free(commit_id_str);
3160 error = got_object_id_str(&commit_id_str, commit_id);
3161 if (error)
3162 goto done;
3163 } else {
3164 commit_id = got_object_id_dup(
3165 got_worktree_get_base_commit_id(worktree));
3166 if (commit_id == NULL) {
3167 error = got_error_from_errno("got_object_id_dup");
3168 goto done;
3170 error = got_object_id_str(&commit_id_str, commit_id);
3171 if (error)
3172 goto done;
3175 error = got_pathlist_append(&paths, "", NULL);
3176 if (error)
3177 goto done;
3178 cpa.worktree_path = worktree_path;
3179 cpa.had_base_commit_ref_error = 0;
3180 cpa.verbosity = verbosity;
3181 error = got_worktree_checkout_files(worktree, &paths, repo,
3182 checkout_progress, &cpa, check_cancelled, NULL);
3183 if (error != NULL)
3184 goto done;
3186 if (got_ref_is_symbolic(head_ref)) {
3187 error = got_ref_resolve_symbolic(&ref, repo, head_ref);
3188 if (error)
3189 goto done;
3190 refname = got_ref_get_name(ref);
3191 } else
3192 refname = got_ref_get_name(head_ref);
3193 printf("Checked out %s: %s\n", refname, commit_id_str);
3194 printf("Now shut up and hack\n");
3195 if (cpa.had_base_commit_ref_error)
3196 show_worktree_base_ref_warning();
3197 done:
3198 if (pack_fds) {
3199 const struct got_error *pack_err =
3200 got_repo_pack_fds_close(pack_fds);
3201 if (error == NULL)
3202 error = pack_err;
3204 if (head_ref)
3205 got_ref_close(head_ref);
3206 if (ref)
3207 got_ref_close(ref);
3208 got_pathlist_free(&paths, GOT_PATHLIST_FREE_NONE);
3209 free(commit_id_str);
3210 free(commit_id);
3211 free(repo_path);
3212 free(worktree_path);
3213 free(cwd);
3214 return error;
3217 struct got_update_progress_arg {
3218 int did_something;
3219 int conflicts;
3220 int obstructed;
3221 int not_updated;
3222 int missing;
3223 int not_deleted;
3224 int unversioned;
3225 int verbosity;
3228 static void
3229 print_update_progress_stats(struct got_update_progress_arg *upa)
3231 if (!upa->did_something)
3232 return;
3234 if (upa->conflicts > 0)
3235 printf("Files with new merge conflicts: %d\n", upa->conflicts);
3236 if (upa->obstructed > 0)
3237 printf("File paths obstructed by a non-regular file: %d\n",
3238 upa->obstructed);
3239 if (upa->not_updated > 0)
3240 printf("Files not updated because of existing merge "
3241 "conflicts: %d\n", upa->not_updated);
3245 * The meaning of some status codes differs between merge-style operations and
3246 * update operations. For example, the ! status code means "file was missing"
3247 * if changes were merged into the work tree, and "missing file was restored"
3248 * if the work tree was updated. This function should be used by any operation
3249 * which merges changes into the work tree without updating the work tree.
3251 static void
3252 print_merge_progress_stats(struct got_update_progress_arg *upa)
3254 if (!upa->did_something)
3255 return;
3257 if (upa->conflicts > 0)
3258 printf("Files with new merge conflicts: %d\n", upa->conflicts);
3259 if (upa->obstructed > 0)
3260 printf("File paths obstructed by a non-regular file: %d\n",
3261 upa->obstructed);
3262 if (upa->missing > 0)
3263 printf("Files which had incoming changes but could not be "
3264 "found in the work tree: %d\n", upa->missing);
3265 if (upa->not_deleted > 0)
3266 printf("Files not deleted due to differences in deleted "
3267 "content: %d\n", upa->not_deleted);
3268 if (upa->unversioned > 0)
3269 printf("Files not merged because an unversioned file was "
3270 "found in the work tree: %d\n", upa->unversioned);
3273 __dead static void
3274 usage_update(void)
3276 fprintf(stderr, "usage: %s update [-q] [-b branch] [-c commit] "
3277 "[path ...]\n", getprogname());
3278 exit(1);
3281 static const struct got_error *
3282 update_progress(void *arg, unsigned char status, const char *path)
3284 struct got_update_progress_arg *upa = arg;
3286 if (status == GOT_STATUS_EXISTS ||
3287 status == GOT_STATUS_BASE_REF_ERR)
3288 return NULL;
3290 upa->did_something = 1;
3292 /* Base commit bump happens silently. */
3293 if (status == GOT_STATUS_BUMP_BASE)
3294 return NULL;
3296 if (status == GOT_STATUS_CONFLICT)
3297 upa->conflicts++;
3298 if (status == GOT_STATUS_OBSTRUCTED)
3299 upa->obstructed++;
3300 if (status == GOT_STATUS_CANNOT_UPDATE)
3301 upa->not_updated++;
3302 if (status == GOT_STATUS_MISSING)
3303 upa->missing++;
3304 if (status == GOT_STATUS_CANNOT_DELETE)
3305 upa->not_deleted++;
3306 if (status == GOT_STATUS_UNVERSIONED)
3307 upa->unversioned++;
3309 while (path[0] == '/')
3310 path++;
3311 if (upa->verbosity >= 0)
3312 printf("%c %s\n", status, path);
3314 return NULL;
3317 static const struct got_error *
3318 switch_head_ref(struct got_reference *head_ref,
3319 struct got_object_id *commit_id, struct got_worktree *worktree,
3320 struct got_repository *repo)
3322 const struct got_error *err = NULL;
3323 char *base_id_str;
3324 int ref_has_moved = 0;
3326 /* Trivial case: switching between two different references. */
3327 if (strcmp(got_ref_get_name(head_ref),
3328 got_worktree_get_head_ref_name(worktree)) != 0) {
3329 printf("Switching work tree from %s to %s\n",
3330 got_worktree_get_head_ref_name(worktree),
3331 got_ref_get_name(head_ref));
3332 return got_worktree_set_head_ref(worktree, head_ref);
3335 err = check_linear_ancestry(commit_id,
3336 got_worktree_get_base_commit_id(worktree), 0, repo);
3337 if (err) {
3338 if (err->code != GOT_ERR_ANCESTRY)
3339 return err;
3340 ref_has_moved = 1;
3342 if (!ref_has_moved)
3343 return NULL;
3345 /* Switching to a rebased branch with the same reference name. */
3346 err = got_object_id_str(&base_id_str,
3347 got_worktree_get_base_commit_id(worktree));
3348 if (err)
3349 return err;
3350 printf("Reference %s now points at a different branch\n",
3351 got_worktree_get_head_ref_name(worktree));
3352 printf("Switching work tree from %s to %s\n", base_id_str,
3353 got_worktree_get_head_ref_name(worktree));
3354 return NULL;
3357 static const struct got_error *
3358 check_rebase_or_histedit_in_progress(struct got_worktree *worktree)
3360 const struct got_error *err;
3361 int in_progress;
3363 err = got_worktree_rebase_in_progress(&in_progress, worktree);
3364 if (err)
3365 return err;
3366 if (in_progress)
3367 return got_error(GOT_ERR_REBASING);
3369 err = got_worktree_histedit_in_progress(&in_progress, worktree);
3370 if (err)
3371 return err;
3372 if (in_progress)
3373 return got_error(GOT_ERR_HISTEDIT_BUSY);
3375 return NULL;
3378 static const struct got_error *
3379 check_merge_in_progress(struct got_worktree *worktree,
3380 struct got_repository *repo)
3382 const struct got_error *err;
3383 int in_progress;
3385 err = got_worktree_merge_in_progress(&in_progress, worktree, repo);
3386 if (err)
3387 return err;
3388 if (in_progress)
3389 return got_error(GOT_ERR_MERGE_BUSY);
3391 return NULL;
3394 static const struct got_error *
3395 get_worktree_paths_from_argv(struct got_pathlist_head *paths, int argc,
3396 char *argv[], struct got_worktree *worktree)
3398 const struct got_error *err = NULL;
3399 char *path;
3400 struct got_pathlist_entry *new;
3401 int i;
3403 if (argc == 0) {
3404 path = strdup("");
3405 if (path == NULL)
3406 return got_error_from_errno("strdup");
3407 return got_pathlist_append(paths, path, NULL);
3410 for (i = 0; i < argc; i++) {
3411 err = got_worktree_resolve_path(&path, worktree, argv[i]);
3412 if (err)
3413 break;
3414 err = got_pathlist_insert(&new, paths, path, NULL);
3415 if (err || new == NULL /* duplicate */) {
3416 free(path);
3417 if (err)
3418 break;
3422 return err;
3425 static const struct got_error *
3426 wrap_not_worktree_error(const struct got_error *orig_err,
3427 const char *cmdname, const char *path)
3429 const struct got_error *err;
3430 struct got_repository *repo;
3431 static char msg[512];
3432 int *pack_fds = NULL;
3434 err = got_repo_pack_fds_open(&pack_fds);
3435 if (err)
3436 return err;
3438 err = got_repo_open(&repo, path, NULL, pack_fds);
3439 if (err)
3440 return orig_err;
3442 snprintf(msg, sizeof(msg),
3443 "'got %s' needs a work tree in addition to a git repository\n"
3444 "Work trees can be checked out from this Git repository with "
3445 "'got checkout'.\n"
3446 "The got(1) manual page contains more information.", cmdname);
3447 err = got_error_msg(GOT_ERR_NOT_WORKTREE, msg);
3448 got_repo_close(repo);
3449 if (pack_fds) {
3450 const struct got_error *pack_err =
3451 got_repo_pack_fds_close(pack_fds);
3452 if (err == NULL)
3453 err = pack_err;
3455 return err;
3458 static const struct got_error *
3459 cmd_update(int argc, char *argv[])
3461 const struct got_error *error = NULL;
3462 struct got_repository *repo = NULL;
3463 struct got_worktree *worktree = NULL;
3464 char *worktree_path = NULL;
3465 struct got_object_id *commit_id = NULL;
3466 char *commit_id_str = NULL;
3467 const char *branch_name = NULL;
3468 struct got_reference *head_ref = NULL;
3469 struct got_pathlist_head paths;
3470 struct got_pathlist_entry *pe;
3471 int ch, verbosity = 0;
3472 struct got_update_progress_arg upa;
3473 int *pack_fds = NULL;
3475 TAILQ_INIT(&paths);
3477 while ((ch = getopt(argc, argv, "b:c:q")) != -1) {
3478 switch (ch) {
3479 case 'b':
3480 branch_name = optarg;
3481 break;
3482 case 'c':
3483 commit_id_str = strdup(optarg);
3484 if (commit_id_str == NULL)
3485 return got_error_from_errno("strdup");
3486 break;
3487 case 'q':
3488 verbosity = -1;
3489 break;
3490 default:
3491 usage_update();
3492 /* NOTREACHED */
3496 argc -= optind;
3497 argv += optind;
3499 #ifndef PROFILE
3500 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
3501 "unveil", NULL) == -1)
3502 err(1, "pledge");
3503 #endif
3504 worktree_path = getcwd(NULL, 0);
3505 if (worktree_path == NULL) {
3506 error = got_error_from_errno("getcwd");
3507 goto done;
3510 error = got_repo_pack_fds_open(&pack_fds);
3511 if (error != NULL)
3512 goto done;
3514 error = got_worktree_open(&worktree, worktree_path);
3515 if (error) {
3516 if (error->code == GOT_ERR_NOT_WORKTREE)
3517 error = wrap_not_worktree_error(error, "update",
3518 worktree_path);
3519 goto done;
3522 error = check_rebase_or_histedit_in_progress(worktree);
3523 if (error)
3524 goto done;
3526 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
3527 NULL, pack_fds);
3528 if (error != NULL)
3529 goto done;
3531 error = apply_unveil(got_repo_get_path(repo), 0,
3532 got_worktree_get_root_path(worktree));
3533 if (error)
3534 goto done;
3536 error = check_merge_in_progress(worktree, repo);
3537 if (error)
3538 goto done;
3540 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
3541 if (error)
3542 goto done;
3544 error = got_ref_open(&head_ref, repo, branch_name ? branch_name :
3545 got_worktree_get_head_ref_name(worktree), 0);
3546 if (error != NULL)
3547 goto done;
3548 if (commit_id_str == NULL) {
3549 error = got_ref_resolve(&commit_id, repo, head_ref);
3550 if (error != NULL)
3551 goto done;
3552 error = got_object_id_str(&commit_id_str, commit_id);
3553 if (error != NULL)
3554 goto done;
3555 } else {
3556 struct got_reflist_head refs;
3557 TAILQ_INIT(&refs);
3558 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
3559 NULL);
3560 if (error)
3561 goto done;
3562 error = got_repo_match_object_id(&commit_id, NULL,
3563 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
3564 got_ref_list_free(&refs);
3565 free(commit_id_str);
3566 commit_id_str = NULL;
3567 if (error)
3568 goto done;
3569 error = got_object_id_str(&commit_id_str, commit_id);
3570 if (error)
3571 goto done;
3574 if (branch_name) {
3575 struct got_object_id *head_commit_id;
3576 TAILQ_FOREACH(pe, &paths, entry) {
3577 if (pe->path_len == 0)
3578 continue;
3579 error = got_error_msg(GOT_ERR_BAD_PATH,
3580 "switching between branches requires that "
3581 "the entire work tree gets updated");
3582 goto done;
3584 error = got_ref_resolve(&head_commit_id, repo, head_ref);
3585 if (error)
3586 goto done;
3587 error = check_linear_ancestry(commit_id, head_commit_id, 0,
3588 repo);
3589 free(head_commit_id);
3590 if (error != NULL)
3591 goto done;
3592 error = check_same_branch(commit_id, head_ref, NULL, repo);
3593 if (error)
3594 goto done;
3595 error = switch_head_ref(head_ref, commit_id, worktree, repo);
3596 if (error)
3597 goto done;
3598 } else {
3599 error = check_linear_ancestry(commit_id,
3600 got_worktree_get_base_commit_id(worktree), 0, repo);
3601 if (error != NULL) {
3602 if (error->code == GOT_ERR_ANCESTRY)
3603 error = got_error(GOT_ERR_BRANCH_MOVED);
3604 goto done;
3606 error = check_same_branch(commit_id, head_ref, NULL, repo);
3607 if (error)
3608 goto done;
3611 if (got_object_id_cmp(got_worktree_get_base_commit_id(worktree),
3612 commit_id) != 0) {
3613 error = got_worktree_set_base_commit_id(worktree, repo,
3614 commit_id);
3615 if (error)
3616 goto done;
3619 memset(&upa, 0, sizeof(upa));
3620 upa.verbosity = verbosity;
3621 error = got_worktree_checkout_files(worktree, &paths, repo,
3622 update_progress, &upa, check_cancelled, NULL);
3623 if (error != NULL)
3624 goto done;
3626 if (upa.did_something) {
3627 printf("Updated to %s: %s\n",
3628 got_worktree_get_head_ref_name(worktree), commit_id_str);
3629 } else
3630 printf("Already up-to-date\n");
3632 print_update_progress_stats(&upa);
3633 done:
3634 if (pack_fds) {
3635 const struct got_error *pack_err =
3636 got_repo_pack_fds_close(pack_fds);
3637 if (error == NULL)
3638 error = pack_err;
3640 free(worktree_path);
3641 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
3642 free(commit_id);
3643 free(commit_id_str);
3644 return error;
3647 static const struct got_error *
3648 diff_blobs(struct got_object_id *blob_id1, struct got_object_id *blob_id2,
3649 const char *path, int diff_context, int ignore_whitespace,
3650 int force_text_diff, struct got_diffstat_cb_arg *dsa,
3651 struct got_repository *repo, FILE *outfile)
3653 const struct got_error *err = NULL;
3654 struct got_blob_object *blob1 = NULL, *blob2 = NULL;
3655 FILE *f1 = NULL, *f2 = NULL;
3656 int fd1 = -1, fd2 = -1;
3658 fd1 = got_opentempfd();
3659 if (fd1 == -1)
3660 return got_error_from_errno("got_opentempfd");
3661 fd2 = got_opentempfd();
3662 if (fd2 == -1) {
3663 err = got_error_from_errno("got_opentempfd");
3664 goto done;
3667 if (blob_id1) {
3668 err = got_object_open_as_blob(&blob1, repo, blob_id1, 8192,
3669 fd1);
3670 if (err)
3671 goto done;
3674 err = got_object_open_as_blob(&blob2, repo, blob_id2, 8192, fd2);
3675 if (err)
3676 goto done;
3678 f1 = got_opentemp();
3679 if (f1 == NULL) {
3680 err = got_error_from_errno("got_opentemp");
3681 goto done;
3683 f2 = got_opentemp();
3684 if (f2 == NULL) {
3685 err = got_error_from_errno("got_opentemp");
3686 goto done;
3689 while (path[0] == '/')
3690 path++;
3691 err = got_diff_blob(NULL, NULL, blob1, blob2, f1, f2, path, path,
3692 GOT_DIFF_ALGORITHM_PATIENCE, diff_context, ignore_whitespace,
3693 force_text_diff, dsa, outfile);
3694 done:
3695 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
3696 err = got_error_from_errno("close");
3697 if (blob1)
3698 got_object_blob_close(blob1);
3699 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
3700 err = got_error_from_errno("close");
3701 got_object_blob_close(blob2);
3702 if (f1 && fclose(f1) == EOF && err == NULL)
3703 err = got_error_from_errno("fclose");
3704 if (f2 && fclose(f2) == EOF && err == NULL)
3705 err = got_error_from_errno("fclose");
3706 return err;
3709 static const struct got_error *
3710 diff_trees(struct got_object_id *tree_id1, struct got_object_id *tree_id2,
3711 const char *path, int diff_context, int ignore_whitespace,
3712 int force_text_diff, struct got_diffstat_cb_arg *dsa,
3713 struct got_repository *repo, FILE *outfile)
3715 const struct got_error *err = NULL;
3716 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
3717 struct got_diff_blob_output_unidiff_arg arg;
3718 FILE *f1 = NULL, *f2 = NULL;
3719 int fd1 = -1, fd2 = -1;
3721 if (tree_id1) {
3722 err = got_object_open_as_tree(&tree1, repo, tree_id1);
3723 if (err)
3724 goto done;
3725 fd1 = got_opentempfd();
3726 if (fd1 == -1) {
3727 err = got_error_from_errno("got_opentempfd");
3728 goto done;
3732 err = got_object_open_as_tree(&tree2, repo, tree_id2);
3733 if (err)
3734 goto done;
3736 f1 = got_opentemp();
3737 if (f1 == NULL) {
3738 err = got_error_from_errno("got_opentemp");
3739 goto done;
3742 f2 = got_opentemp();
3743 if (f2 == NULL) {
3744 err = got_error_from_errno("got_opentemp");
3745 goto done;
3747 fd2 = got_opentempfd();
3748 if (fd2 == -1) {
3749 err = got_error_from_errno("got_opentempfd");
3750 goto done;
3752 arg.diff_context = diff_context;
3753 arg.ignore_whitespace = ignore_whitespace;
3754 arg.force_text_diff = force_text_diff;
3755 arg.diffstat = dsa;
3756 arg.diff_algo = GOT_DIFF_ALGORITHM_PATIENCE;
3757 arg.outfile = outfile;
3758 arg.lines = NULL;
3759 arg.nlines = 0;
3760 while (path[0] == '/')
3761 path++;
3762 err = got_diff_tree(tree1, tree2, f1, f2, fd1, fd2, path, path, repo,
3763 got_diff_blob_output_unidiff, &arg, 1);
3764 done:
3765 if (tree1)
3766 got_object_tree_close(tree1);
3767 if (tree2)
3768 got_object_tree_close(tree2);
3769 if (f1 && fclose(f1) == EOF && err == NULL)
3770 err = got_error_from_errno("fclose");
3771 if (f2 && fclose(f2) == EOF && err == NULL)
3772 err = got_error_from_errno("fclose");
3773 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
3774 err = got_error_from_errno("close");
3775 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
3776 err = got_error_from_errno("close");
3777 return err;
3780 static const struct got_error *
3781 get_changed_paths(struct got_pathlist_head *paths,
3782 struct got_commit_object *commit, struct got_repository *repo,
3783 struct got_diffstat_cb_arg *dsa)
3785 const struct got_error *err = NULL;
3786 struct got_object_id *tree_id1 = NULL, *tree_id2 = NULL;
3787 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
3788 struct got_object_qid *qid;
3789 got_diff_blob_cb cb = got_diff_tree_collect_changed_paths;
3790 FILE *f1 = NULL, *f2 = NULL;
3791 int fd1 = -1, fd2 = -1;
3793 if (dsa) {
3794 cb = got_diff_tree_compute_diffstat;
3796 f1 = got_opentemp();
3797 if (f1 == NULL) {
3798 err = got_error_from_errno("got_opentemp");
3799 goto done;
3801 f2 = got_opentemp();
3802 if (f2 == NULL) {
3803 err = got_error_from_errno("got_opentemp");
3804 goto done;
3806 fd1 = got_opentempfd();
3807 if (fd1 == -1) {
3808 err = got_error_from_errno("got_opentempfd");
3809 goto done;
3811 fd2 = got_opentempfd();
3812 if (fd2 == -1) {
3813 err = got_error_from_errno("got_opentempfd");
3814 goto done;
3818 qid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
3819 if (qid != NULL) {
3820 struct got_commit_object *pcommit;
3821 err = got_object_open_as_commit(&pcommit, repo,
3822 &qid->id);
3823 if (err)
3824 return err;
3826 tree_id1 = got_object_id_dup(
3827 got_object_commit_get_tree_id(pcommit));
3828 if (tree_id1 == NULL) {
3829 got_object_commit_close(pcommit);
3830 return got_error_from_errno("got_object_id_dup");
3832 got_object_commit_close(pcommit);
3836 if (tree_id1) {
3837 err = got_object_open_as_tree(&tree1, repo, tree_id1);
3838 if (err)
3839 goto done;
3842 tree_id2 = got_object_commit_get_tree_id(commit);
3843 err = got_object_open_as_tree(&tree2, repo, tree_id2);
3844 if (err)
3845 goto done;
3847 err = got_diff_tree(tree1, tree2, f1, f2, fd1, fd2, "", "", repo,
3848 cb, dsa ? (void *)dsa : paths, dsa ? 1 : 0);
3849 done:
3850 if (tree1)
3851 got_object_tree_close(tree1);
3852 if (tree2)
3853 got_object_tree_close(tree2);
3854 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
3855 err = got_error_from_errno("close");
3856 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
3857 err = got_error_from_errno("close");
3858 if (f1 && fclose(f1) == EOF && err == NULL)
3859 err = got_error_from_errno("fclose");
3860 if (f2 && fclose(f2) == EOF && err == NULL)
3861 err = got_error_from_errno("fclose");
3862 free(tree_id1);
3863 return err;
3866 static const struct got_error *
3867 print_patch(struct got_commit_object *commit, struct got_object_id *id,
3868 const char *path, int diff_context, struct got_diffstat_cb_arg *dsa,
3869 struct got_repository *repo, FILE *outfile)
3871 const struct got_error *err = NULL;
3872 struct got_commit_object *pcommit = NULL;
3873 char *id_str1 = NULL, *id_str2 = NULL;
3874 struct got_object_id *obj_id1 = NULL, *obj_id2 = NULL;
3875 struct got_object_qid *qid;
3877 qid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
3878 if (qid != NULL) {
3879 err = got_object_open_as_commit(&pcommit, repo,
3880 &qid->id);
3881 if (err)
3882 return err;
3883 err = got_object_id_str(&id_str1, &qid->id);
3884 if (err)
3885 goto done;
3888 err = got_object_id_str(&id_str2, id);
3889 if (err)
3890 goto done;
3892 if (path && path[0] != '\0') {
3893 int obj_type;
3894 err = got_object_id_by_path(&obj_id2, repo, commit, path);
3895 if (err)
3896 goto done;
3897 if (pcommit) {
3898 err = got_object_id_by_path(&obj_id1, repo,
3899 pcommit, path);
3900 if (err) {
3901 if (err->code != GOT_ERR_NO_TREE_ENTRY) {
3902 free(obj_id2);
3903 goto done;
3907 err = got_object_get_type(&obj_type, repo, obj_id2);
3908 if (err) {
3909 free(obj_id2);
3910 goto done;
3912 fprintf(outfile,
3913 "diff %s %s\n", id_str1 ? id_str1 : "/dev/null", id_str2);
3914 fprintf(outfile, "commit - %s\n",
3915 id_str1 ? id_str1 : "/dev/null");
3916 fprintf(outfile, "commit + %s\n", id_str2);
3917 switch (obj_type) {
3918 case GOT_OBJ_TYPE_BLOB:
3919 err = diff_blobs(obj_id1, obj_id2, path, diff_context,
3920 0, 0, dsa, repo, outfile);
3921 break;
3922 case GOT_OBJ_TYPE_TREE:
3923 err = diff_trees(obj_id1, obj_id2, path, diff_context,
3924 0, 0, dsa, repo, outfile);
3925 break;
3926 default:
3927 err = got_error(GOT_ERR_OBJ_TYPE);
3928 break;
3930 free(obj_id1);
3931 free(obj_id2);
3932 } else {
3933 obj_id2 = got_object_commit_get_tree_id(commit);
3934 if (pcommit)
3935 obj_id1 = got_object_commit_get_tree_id(pcommit);
3936 fprintf(outfile,
3937 "diff %s %s\n", id_str1 ? id_str1 : "/dev/null", id_str2);
3938 fprintf(outfile, "commit - %s\n",
3939 id_str1 ? id_str1 : "/dev/null");
3940 fprintf(outfile, "commit + %s\n", id_str2);
3941 err = diff_trees(obj_id1, obj_id2, "", diff_context, 0, 0,
3942 dsa, repo, outfile);
3944 done:
3945 free(id_str1);
3946 free(id_str2);
3947 if (pcommit)
3948 got_object_commit_close(pcommit);
3949 return err;
3952 static char *
3953 get_datestr(time_t *time, char *datebuf)
3955 struct tm mytm, *tm;
3956 char *p, *s;
3958 tm = gmtime_r(time, &mytm);
3959 if (tm == NULL)
3960 return NULL;
3961 s = asctime_r(tm, datebuf);
3962 if (s == NULL)
3963 return NULL;
3964 p = strchr(s, '\n');
3965 if (p)
3966 *p = '\0';
3967 return s;
3970 static const struct got_error *
3971 match_commit(int *have_match, struct got_object_id *id,
3972 struct got_commit_object *commit, regex_t *regex)
3974 const struct got_error *err = NULL;
3975 regmatch_t regmatch;
3976 char *id_str = NULL, *logmsg = NULL;
3978 *have_match = 0;
3980 err = got_object_id_str(&id_str, id);
3981 if (err)
3982 return err;
3984 err = got_object_commit_get_logmsg(&logmsg, commit);
3985 if (err)
3986 goto done;
3988 if (regexec(regex, got_object_commit_get_author(commit), 1,
3989 &regmatch, 0) == 0 ||
3990 regexec(regex, got_object_commit_get_committer(commit), 1,
3991 &regmatch, 0) == 0 ||
3992 regexec(regex, id_str, 1, &regmatch, 0) == 0 ||
3993 regexec(regex, logmsg, 1, &regmatch, 0) == 0)
3994 *have_match = 1;
3995 done:
3996 free(id_str);
3997 free(logmsg);
3998 return err;
4001 static void
4002 match_changed_paths(int *have_match, struct got_pathlist_head *changed_paths,
4003 regex_t *regex)
4005 regmatch_t regmatch;
4006 struct got_pathlist_entry *pe;
4008 *have_match = 0;
4010 TAILQ_FOREACH(pe, changed_paths, entry) {
4011 if (regexec(regex, pe->path, 1, &regmatch, 0) == 0) {
4012 *have_match = 1;
4013 break;
4018 static const struct got_error *
4019 match_patch(int *have_match, struct got_commit_object *commit,
4020 struct got_object_id *id, const char *path, int diff_context,
4021 struct got_repository *repo, regex_t *regex, FILE *f)
4023 const struct got_error *err = NULL;
4024 char *line = NULL;
4025 size_t linesize = 0;
4026 regmatch_t regmatch;
4028 *have_match = 0;
4030 err = got_opentemp_truncate(f);
4031 if (err)
4032 return err;
4034 err = print_patch(commit, id, path, diff_context, NULL, repo, f);
4035 if (err)
4036 goto done;
4038 if (fseeko(f, 0L, SEEK_SET) == -1) {
4039 err = got_error_from_errno("fseeko");
4040 goto done;
4043 while (getline(&line, &linesize, f) != -1) {
4044 if (regexec(regex, line, 1, &regmatch, 0) == 0) {
4045 *have_match = 1;
4046 break;
4049 done:
4050 free(line);
4051 return err;
4054 #define GOT_COMMIT_SEP_STR "-----------------------------------------------\n"
4056 static const struct got_error*
4057 build_refs_str(char **refs_str, struct got_reflist_head *refs,
4058 struct got_object_id *id, struct got_repository *repo,
4059 int local_only)
4061 static const struct got_error *err = NULL;
4062 struct got_reflist_entry *re;
4063 char *s;
4064 const char *name;
4066 *refs_str = NULL;
4068 TAILQ_FOREACH(re, refs, entry) {
4069 struct got_tag_object *tag = NULL;
4070 struct got_object_id *ref_id;
4071 int cmp;
4073 name = got_ref_get_name(re->ref);
4074 if (strcmp(name, GOT_REF_HEAD) == 0)
4075 continue;
4076 if (strncmp(name, "refs/", 5) == 0)
4077 name += 5;
4078 if (strncmp(name, "got/", 4) == 0)
4079 continue;
4080 if (strncmp(name, "heads/", 6) == 0)
4081 name += 6;
4082 if (strncmp(name, "remotes/", 8) == 0) {
4083 if (local_only)
4084 continue;
4085 name += 8;
4086 s = strstr(name, "/" GOT_REF_HEAD);
4087 if (s != NULL && s[strlen(s)] == '\0')
4088 continue;
4090 err = got_ref_resolve(&ref_id, repo, re->ref);
4091 if (err)
4092 break;
4093 if (strncmp(name, "tags/", 5) == 0) {
4094 err = got_object_open_as_tag(&tag, repo, ref_id);
4095 if (err) {
4096 if (err->code != GOT_ERR_OBJ_TYPE) {
4097 free(ref_id);
4098 break;
4100 /* Ref points at something other than a tag. */
4101 err = NULL;
4102 tag = NULL;
4105 cmp = got_object_id_cmp(tag ?
4106 got_object_tag_get_object_id(tag) : ref_id, id);
4107 free(ref_id);
4108 if (tag)
4109 got_object_tag_close(tag);
4110 if (cmp != 0)
4111 continue;
4112 s = *refs_str;
4113 if (asprintf(refs_str, "%s%s%s", s ? s : "",
4114 s ? ", " : "", name) == -1) {
4115 err = got_error_from_errno("asprintf");
4116 free(s);
4117 *refs_str = NULL;
4118 break;
4120 free(s);
4123 return err;
4126 static const struct got_error *
4127 print_commit_oneline(struct got_commit_object *commit, struct got_object_id *id,
4128 struct got_repository *repo, struct got_reflist_object_id_map *refs_idmap)
4130 const struct got_error *err = NULL;
4131 char *ref_str = NULL, *id_str = NULL, *logmsg0 = NULL;
4132 char *comma, *s, *nl;
4133 struct got_reflist_head *refs;
4134 char datebuf[12]; /* YYYY-MM-DD + SPACE + NUL */
4135 struct tm tm;
4136 time_t committer_time;
4138 refs = got_reflist_object_id_map_lookup(refs_idmap, id);
4139 if (refs) {
4140 err = build_refs_str(&ref_str, refs, id, repo, 1);
4141 if (err)
4142 return err;
4144 /* Display the first matching ref only. */
4145 if (ref_str && (comma = strchr(ref_str, ',')) != NULL)
4146 *comma = '\0';
4149 if (ref_str == NULL) {
4150 err = got_object_id_str(&id_str, id);
4151 if (err)
4152 return err;
4155 committer_time = got_object_commit_get_committer_time(commit);
4156 if (gmtime_r(&committer_time, &tm) == NULL) {
4157 err = got_error_from_errno("gmtime_r");
4158 goto done;
4160 if (strftime(datebuf, sizeof(datebuf), "%G-%m-%d ", &tm) == 0) {
4161 err = got_error(GOT_ERR_NO_SPACE);
4162 goto done;
4165 err = got_object_commit_get_logmsg(&logmsg0, commit);
4166 if (err)
4167 goto done;
4169 s = logmsg0;
4170 while (isspace((unsigned char)s[0]))
4171 s++;
4173 nl = strchr(s, '\n');
4174 if (nl) {
4175 *nl = '\0';
4178 if (ref_str)
4179 printf("%s%-7s %s\n", datebuf, ref_str, s);
4180 else
4181 printf("%s%.7s %s\n", datebuf, id_str, s);
4183 if (fflush(stdout) != 0 && err == NULL)
4184 err = got_error_from_errno("fflush");
4185 done:
4186 free(id_str);
4187 free(ref_str);
4188 free(logmsg0);
4189 return err;
4192 static const struct got_error *
4193 print_diffstat(struct got_diffstat_cb_arg *dsa, const char *header)
4195 struct got_pathlist_entry *pe;
4197 if (header != NULL)
4198 printf("%s\n", header);
4200 TAILQ_FOREACH(pe, dsa->paths, entry) {
4201 struct got_diff_changed_path *cp = pe->data;
4202 int pad = dsa->max_path_len - pe->path_len + 1;
4204 printf(" %c %s%*c | %*d+ %*d-\n", cp->status, pe->path, pad,
4205 ' ', dsa->add_cols + 1, cp->add, dsa->rm_cols + 1, cp->rm);
4207 printf("\n%d file%s changed, %d insertion%s(+), %d deletion%s(-)\n\n",
4208 dsa->nfiles, dsa->nfiles > 1 ? "s" : "", dsa->ins,
4209 dsa->ins != 1 ? "s" : "", dsa->del, dsa->del != 1 ? "s" : "");
4211 if (fflush(stdout) != 0)
4212 return got_error_from_errno("fflush");
4214 return NULL;
4217 static const struct got_error *
4218 printfile(FILE *f)
4220 char buf[8192];
4221 size_t r;
4223 if (fseeko(f, 0L, SEEK_SET) == -1)
4224 return got_error_from_errno("fseek");
4226 for (;;) {
4227 r = fread(buf, 1, sizeof(buf), f);
4228 if (r == 0) {
4229 if (ferror(f))
4230 return got_error_from_errno("fread");
4231 if (feof(f))
4232 break;
4234 if (fwrite(buf, 1, r, stdout) != r)
4235 return got_ferror(stdout, GOT_ERR_IO);
4238 return NULL;
4241 static const struct got_error *
4242 print_commit(struct got_commit_object *commit, struct got_object_id *id,
4243 struct got_repository *repo, const char *path,
4244 struct got_pathlist_head *changed_paths,
4245 struct got_diffstat_cb_arg *diffstat, int show_patch, int diff_context,
4246 struct got_reflist_object_id_map *refs_idmap, const char *custom_refs_str,
4247 const char *prefix)
4249 const struct got_error *err = NULL;
4250 FILE *f = NULL;
4251 char *id_str, *datestr, *logmsg0, *logmsg, *line;
4252 char datebuf[26];
4253 time_t committer_time;
4254 const char *author, *committer;
4255 char *refs_str = NULL;
4257 err = got_object_id_str(&id_str, id);
4258 if (err)
4259 return err;
4261 if (custom_refs_str == NULL) {
4262 struct got_reflist_head *refs;
4263 refs = got_reflist_object_id_map_lookup(refs_idmap, id);
4264 if (refs) {
4265 err = build_refs_str(&refs_str, refs, id, repo, 0);
4266 if (err)
4267 goto done;
4271 printf(GOT_COMMIT_SEP_STR);
4272 if (custom_refs_str)
4273 printf("%s %s (%s)\n", prefix ? prefix : "commit", id_str,
4274 custom_refs_str);
4275 else
4276 printf("%s %s%s%s%s\n", prefix ? prefix : "commit", id_str,
4277 refs_str ? " (" : "", refs_str ? refs_str : "",
4278 refs_str ? ")" : "");
4279 free(id_str);
4280 id_str = NULL;
4281 free(refs_str);
4282 refs_str = NULL;
4283 printf("from: %s\n", got_object_commit_get_author(commit));
4284 author = got_object_commit_get_author(commit);
4285 committer = got_object_commit_get_committer(commit);
4286 if (strcmp(author, committer) != 0)
4287 printf("via: %s\n", committer);
4288 committer_time = got_object_commit_get_committer_time(commit);
4289 datestr = get_datestr(&committer_time, datebuf);
4290 if (datestr)
4291 printf("date: %s UTC\n", datestr);
4292 if (got_object_commit_get_nparents(commit) > 1) {
4293 const struct got_object_id_queue *parent_ids;
4294 struct got_object_qid *qid;
4295 int n = 1;
4296 parent_ids = got_object_commit_get_parent_ids(commit);
4297 STAILQ_FOREACH(qid, parent_ids, entry) {
4298 err = got_object_id_str(&id_str, &qid->id);
4299 if (err)
4300 goto done;
4301 printf("parent %d: %s\n", n++, id_str);
4302 free(id_str);
4303 id_str = NULL;
4307 err = got_object_commit_get_logmsg(&logmsg0, commit);
4308 if (err)
4309 goto done;
4311 logmsg = logmsg0;
4312 do {
4313 line = strsep(&logmsg, "\n");
4314 if (line)
4315 printf(" %s\n", line);
4316 } while (line);
4317 free(logmsg0);
4319 if (changed_paths && diffstat == NULL) {
4320 struct got_pathlist_entry *pe;
4322 TAILQ_FOREACH(pe, changed_paths, entry) {
4323 struct got_diff_changed_path *cp = pe->data;
4325 printf(" %c %s\n", cp->status, pe->path);
4327 printf("\n");
4329 if (show_patch) {
4330 if (diffstat) {
4331 f = got_opentemp();
4332 if (f == NULL) {
4333 err = got_error_from_errno("got_opentemp");
4334 goto done;
4338 err = print_patch(commit, id, path, diff_context, diffstat,
4339 repo, diffstat == NULL ? stdout : f);
4340 if (err)
4341 goto done;
4343 if (diffstat) {
4344 err = print_diffstat(diffstat, NULL);
4345 if (err)
4346 goto done;
4347 if (show_patch) {
4348 err = printfile(f);
4349 if (err)
4350 goto done;
4353 if (show_patch)
4354 printf("\n");
4356 if (fflush(stdout) != 0 && err == NULL)
4357 err = got_error_from_errno("fflush");
4358 done:
4359 if (f && fclose(f) == EOF && err == NULL)
4360 err = got_error_from_errno("fclose");
4361 free(id_str);
4362 free(refs_str);
4363 return err;
4366 static const struct got_error *
4367 print_commits(struct got_object_id *root_id, struct got_object_id *end_id,
4368 struct got_repository *repo, const char *path, int show_changed_paths,
4369 int show_diffstat, int show_patch, const char *search_pattern,
4370 int diff_context, int limit, int log_branches, int reverse_display_order,
4371 struct got_reflist_object_id_map *refs_idmap, int one_line,
4372 FILE *tmpfile)
4374 const struct got_error *err;
4375 struct got_commit_graph *graph;
4376 regex_t regex;
4377 int have_match;
4378 struct got_object_id_queue reversed_commits;
4379 struct got_object_qid *qid;
4380 struct got_commit_object *commit;
4381 struct got_pathlist_head changed_paths;
4383 STAILQ_INIT(&reversed_commits);
4384 TAILQ_INIT(&changed_paths);
4386 if (search_pattern && regcomp(&regex, search_pattern,
4387 REG_EXTENDED | REG_NOSUB | REG_NEWLINE))
4388 return got_error_msg(GOT_ERR_REGEX, search_pattern);
4390 err = got_commit_graph_open(&graph, path, !log_branches);
4391 if (err)
4392 return err;
4393 err = got_commit_graph_iter_start(graph, root_id, repo,
4394 check_cancelled, NULL);
4395 if (err)
4396 goto done;
4397 for (;;) {
4398 struct got_object_id id;
4399 struct got_diffstat_cb_arg dsa = { 0, 0, 0, 0, 0, 0,
4400 &changed_paths, 0, 0, GOT_DIFF_ALGORITHM_PATIENCE };
4402 if (sigint_received || sigpipe_received)
4403 break;
4405 err = got_commit_graph_iter_next(&id, graph, repo,
4406 check_cancelled, NULL);
4407 if (err) {
4408 if (err->code == GOT_ERR_ITER_COMPLETED)
4409 err = NULL;
4410 break;
4413 err = got_object_open_as_commit(&commit, repo, &id);
4414 if (err)
4415 break;
4417 if ((show_changed_paths || (show_diffstat && !show_patch))
4418 && !reverse_display_order) {
4419 err = get_changed_paths(&changed_paths, commit, repo,
4420 show_diffstat ? &dsa : NULL);
4421 if (err)
4422 break;
4425 if (search_pattern) {
4426 err = match_commit(&have_match, &id, commit, &regex);
4427 if (err) {
4428 got_object_commit_close(commit);
4429 break;
4431 if (have_match == 0 && show_changed_paths)
4432 match_changed_paths(&have_match,
4433 &changed_paths, &regex);
4434 if (have_match == 0 && show_patch) {
4435 err = match_patch(&have_match, commit, &id,
4436 path, diff_context, repo, &regex, tmpfile);
4437 if (err)
4438 break;
4440 if (have_match == 0) {
4441 got_object_commit_close(commit);
4442 got_pathlist_free(&changed_paths,
4443 GOT_PATHLIST_FREE_ALL);
4444 continue;
4448 if (reverse_display_order) {
4449 err = got_object_qid_alloc(&qid, &id);
4450 if (err)
4451 break;
4452 STAILQ_INSERT_HEAD(&reversed_commits, qid, entry);
4453 got_object_commit_close(commit);
4454 } else {
4455 if (one_line)
4456 err = print_commit_oneline(commit, &id,
4457 repo, refs_idmap);
4458 else
4459 err = print_commit(commit, &id, repo, path,
4460 (show_changed_paths || show_diffstat) ?
4461 &changed_paths : NULL,
4462 show_diffstat ? &dsa : NULL, show_patch,
4463 diff_context, refs_idmap, NULL, NULL);
4464 got_object_commit_close(commit);
4465 if (err)
4466 break;
4468 if ((limit && --limit == 0) ||
4469 (end_id && got_object_id_cmp(&id, end_id) == 0))
4470 break;
4472 got_pathlist_free(&changed_paths, GOT_PATHLIST_FREE_ALL);
4474 if (reverse_display_order) {
4475 STAILQ_FOREACH(qid, &reversed_commits, entry) {
4476 struct got_diffstat_cb_arg dsa = { 0, 0, 0, 0, 0, 0,
4477 &changed_paths, 0, 0, GOT_DIFF_ALGORITHM_PATIENCE };
4479 err = got_object_open_as_commit(&commit, repo,
4480 &qid->id);
4481 if (err)
4482 break;
4483 if (show_changed_paths ||
4484 (show_diffstat && !show_patch)) {
4485 err = get_changed_paths(&changed_paths, commit,
4486 repo, show_diffstat ? &dsa : NULL);
4487 if (err)
4488 break;
4490 if (one_line)
4491 err = print_commit_oneline(commit, &qid->id,
4492 repo, refs_idmap);
4493 else
4494 err = print_commit(commit, &qid->id, repo, path,
4495 (show_changed_paths || show_diffstat) ?
4496 &changed_paths : NULL,
4497 show_diffstat ? &dsa : NULL, show_patch,
4498 diff_context, refs_idmap, NULL, NULL);
4499 got_object_commit_close(commit);
4500 if (err)
4501 break;
4502 got_pathlist_free(&changed_paths, GOT_PATHLIST_FREE_ALL);
4505 done:
4506 while (!STAILQ_EMPTY(&reversed_commits)) {
4507 qid = STAILQ_FIRST(&reversed_commits);
4508 STAILQ_REMOVE_HEAD(&reversed_commits, entry);
4509 got_object_qid_free(qid);
4511 got_pathlist_free(&changed_paths, GOT_PATHLIST_FREE_ALL);
4512 if (search_pattern)
4513 regfree(&regex);
4514 got_commit_graph_close(graph);
4515 return err;
4518 __dead static void
4519 usage_log(void)
4521 fprintf(stderr, "usage: %s log [-bdPpRs] [-C number] [-c commit] "
4522 "[-l N] [-r repository-path] [-S search-pattern] [-x commit] "
4523 "[path]\n", getprogname());
4524 exit(1);
4527 static int
4528 get_default_log_limit(void)
4530 const char *got_default_log_limit;
4531 long long n;
4532 const char *errstr;
4534 got_default_log_limit = getenv("GOT_LOG_DEFAULT_LIMIT");
4535 if (got_default_log_limit == NULL)
4536 return 0;
4537 n = strtonum(got_default_log_limit, 0, INT_MAX, &errstr);
4538 if (errstr != NULL)
4539 return 0;
4540 return n;
4543 static const struct got_error *
4544 cmd_log(int argc, char *argv[])
4546 const struct got_error *error;
4547 struct got_repository *repo = NULL;
4548 struct got_worktree *worktree = NULL;
4549 struct got_object_id *start_id = NULL, *end_id = NULL;
4550 char *repo_path = NULL, *path = NULL, *cwd = NULL, *in_repo_path = NULL;
4551 const char *start_commit = NULL, *end_commit = NULL;
4552 const char *search_pattern = NULL;
4553 int diff_context = -1, ch;
4554 int show_changed_paths = 0, show_patch = 0, limit = 0, log_branches = 0;
4555 int show_diffstat = 0, reverse_display_order = 0, one_line = 0;
4556 const char *errstr;
4557 struct got_reflist_head refs;
4558 struct got_reflist_object_id_map *refs_idmap = NULL;
4559 FILE *tmpfile = NULL;
4560 int *pack_fds = NULL;
4562 TAILQ_INIT(&refs);
4564 #ifndef PROFILE
4565 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
4566 NULL)
4567 == -1)
4568 err(1, "pledge");
4569 #endif
4571 limit = get_default_log_limit();
4573 while ((ch = getopt(argc, argv, "bC:c:dl:PpRr:S:sx:")) != -1) {
4574 switch (ch) {
4575 case 'b':
4576 log_branches = 1;
4577 break;
4578 case 'C':
4579 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
4580 &errstr);
4581 if (errstr != NULL)
4582 errx(1, "number of context lines is %s: %s",
4583 errstr, optarg);
4584 break;
4585 case 'c':
4586 start_commit = optarg;
4587 break;
4588 case 'd':
4589 show_diffstat = 1;
4590 break;
4591 case 'l':
4592 limit = strtonum(optarg, 0, INT_MAX, &errstr);
4593 if (errstr != NULL)
4594 errx(1, "number of commits is %s: %s",
4595 errstr, optarg);
4596 break;
4597 case 'P':
4598 show_changed_paths = 1;
4599 break;
4600 case 'p':
4601 show_patch = 1;
4602 break;
4603 case 'R':
4604 reverse_display_order = 1;
4605 break;
4606 case 'r':
4607 repo_path = realpath(optarg, NULL);
4608 if (repo_path == NULL)
4609 return got_error_from_errno2("realpath",
4610 optarg);
4611 got_path_strip_trailing_slashes(repo_path);
4612 break;
4613 case 'S':
4614 search_pattern = optarg;
4615 break;
4616 case 's':
4617 one_line = 1;
4618 break;
4619 case 'x':
4620 end_commit = optarg;
4621 break;
4622 default:
4623 usage_log();
4624 /* NOTREACHED */
4628 argc -= optind;
4629 argv += optind;
4631 if (diff_context == -1)
4632 diff_context = 3;
4633 else if (!show_patch)
4634 errx(1, "-C requires -p");
4636 if (one_line && (show_patch || show_changed_paths || show_diffstat))
4637 errx(1, "cannot use -s with -d, -p or -P");
4639 cwd = getcwd(NULL, 0);
4640 if (cwd == NULL) {
4641 error = got_error_from_errno("getcwd");
4642 goto done;
4645 error = got_repo_pack_fds_open(&pack_fds);
4646 if (error != NULL)
4647 goto done;
4649 if (repo_path == NULL) {
4650 error = got_worktree_open(&worktree, cwd);
4651 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4652 goto done;
4653 error = NULL;
4656 if (argc == 1) {
4657 if (worktree) {
4658 error = got_worktree_resolve_path(&path, worktree,
4659 argv[0]);
4660 if (error)
4661 goto done;
4662 } else {
4663 path = strdup(argv[0]);
4664 if (path == NULL) {
4665 error = got_error_from_errno("strdup");
4666 goto done;
4669 } else if (argc != 0)
4670 usage_log();
4672 if (repo_path == NULL) {
4673 repo_path = worktree ?
4674 strdup(got_worktree_get_repo_path(worktree)) : strdup(cwd);
4676 if (repo_path == NULL) {
4677 error = got_error_from_errno("strdup");
4678 goto done;
4681 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
4682 if (error != NULL)
4683 goto done;
4685 error = apply_unveil(got_repo_get_path(repo), 1,
4686 worktree ? got_worktree_get_root_path(worktree) : NULL);
4687 if (error)
4688 goto done;
4690 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
4691 if (error)
4692 goto done;
4694 error = got_reflist_object_id_map_create(&refs_idmap, &refs, repo);
4695 if (error)
4696 goto done;
4698 if (start_commit == NULL) {
4699 struct got_reference *head_ref;
4700 struct got_commit_object *commit = NULL;
4701 error = got_ref_open(&head_ref, repo,
4702 worktree ? got_worktree_get_head_ref_name(worktree)
4703 : GOT_REF_HEAD, 0);
4704 if (error != NULL)
4705 goto done;
4706 error = got_ref_resolve(&start_id, repo, head_ref);
4707 got_ref_close(head_ref);
4708 if (error != NULL)
4709 goto done;
4710 error = got_object_open_as_commit(&commit, repo,
4711 start_id);
4712 if (error != NULL)
4713 goto done;
4714 got_object_commit_close(commit);
4715 } else {
4716 error = got_repo_match_object_id(&start_id, NULL,
4717 start_commit, GOT_OBJ_TYPE_COMMIT, &refs, repo);
4718 if (error != NULL)
4719 goto done;
4721 if (end_commit != NULL) {
4722 error = got_repo_match_object_id(&end_id, NULL,
4723 end_commit, GOT_OBJ_TYPE_COMMIT, &refs, repo);
4724 if (error != NULL)
4725 goto done;
4728 if (worktree) {
4730 * If a path was specified on the command line it was resolved
4731 * to a path in the work tree above. Prepend the work tree's
4732 * path prefix to obtain the corresponding in-repository path.
4734 if (path) {
4735 const char *prefix;
4736 prefix = got_worktree_get_path_prefix(worktree);
4737 if (asprintf(&in_repo_path, "%s%s%s", prefix,
4738 (path[0] != '\0') ? "/" : "", path) == -1) {
4739 error = got_error_from_errno("asprintf");
4740 goto done;
4743 } else
4744 error = got_repo_map_path(&in_repo_path, repo,
4745 path ? path : "");
4746 if (error != NULL)
4747 goto done;
4748 if (in_repo_path) {
4749 free(path);
4750 path = in_repo_path;
4753 if (worktree) {
4754 /* Release work tree lock. */
4755 got_worktree_close(worktree);
4756 worktree = NULL;
4759 if (search_pattern && show_patch) {
4760 tmpfile = got_opentemp();
4761 if (tmpfile == NULL) {
4762 error = got_error_from_errno("got_opentemp");
4763 goto done;
4767 error = print_commits(start_id, end_id, repo, path ? path : "",
4768 show_changed_paths, show_diffstat, show_patch, search_pattern,
4769 diff_context, limit, log_branches, reverse_display_order,
4770 refs_idmap, one_line, tmpfile);
4771 done:
4772 free(path);
4773 free(repo_path);
4774 free(cwd);
4775 if (worktree)
4776 got_worktree_close(worktree);
4777 if (repo) {
4778 const struct got_error *close_err = got_repo_close(repo);
4779 if (error == NULL)
4780 error = close_err;
4782 if (pack_fds) {
4783 const struct got_error *pack_err =
4784 got_repo_pack_fds_close(pack_fds);
4785 if (error == NULL)
4786 error = pack_err;
4788 if (refs_idmap)
4789 got_reflist_object_id_map_free(refs_idmap);
4790 if (tmpfile && fclose(tmpfile) == EOF && error == NULL)
4791 error = got_error_from_errno("fclose");
4792 got_ref_list_free(&refs);
4793 return error;
4796 __dead static void
4797 usage_diff(void)
4799 fprintf(stderr, "usage: %s diff [-adPsw] [-C number] [-c commit] "
4800 "[-r repository-path] [object1 object2 | path ...]\n",
4801 getprogname());
4802 exit(1);
4805 struct print_diff_arg {
4806 struct got_repository *repo;
4807 struct got_worktree *worktree;
4808 struct got_diffstat_cb_arg *diffstat;
4809 int diff_context;
4810 const char *id_str;
4811 int header_shown;
4812 int diff_staged;
4813 enum got_diff_algorithm diff_algo;
4814 int ignore_whitespace;
4815 int force_text_diff;
4816 FILE *f1;
4817 FILE *f2;
4818 FILE *outfile;
4822 * Create a file which contains the target path of a symlink so we can feed
4823 * it as content to the diff engine.
4825 static const struct got_error *
4826 get_symlink_target_file(int *fd, int dirfd, const char *de_name,
4827 const char *abspath)
4829 const struct got_error *err = NULL;
4830 char target_path[PATH_MAX];
4831 ssize_t target_len, outlen;
4833 *fd = -1;
4835 if (dirfd != -1) {
4836 target_len = readlinkat(dirfd, de_name, target_path, PATH_MAX);
4837 if (target_len == -1)
4838 return got_error_from_errno2("readlinkat", abspath);
4839 } else {
4840 target_len = readlink(abspath, target_path, PATH_MAX);
4841 if (target_len == -1)
4842 return got_error_from_errno2("readlink", abspath);
4845 *fd = got_opentempfd();
4846 if (*fd == -1)
4847 return got_error_from_errno("got_opentempfd");
4849 outlen = write(*fd, target_path, target_len);
4850 if (outlen == -1) {
4851 err = got_error_from_errno("got_opentempfd");
4852 goto done;
4855 if (lseek(*fd, 0, SEEK_SET) == -1) {
4856 err = got_error_from_errno2("lseek", abspath);
4857 goto done;
4859 done:
4860 if (err) {
4861 close(*fd);
4862 *fd = -1;
4864 return err;
4867 static const struct got_error *
4868 print_diff(void *arg, unsigned char status, unsigned char staged_status,
4869 const char *path, struct got_object_id *blob_id,
4870 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
4871 int dirfd, const char *de_name)
4873 struct print_diff_arg *a = arg;
4874 const struct got_error *err = NULL;
4875 struct got_blob_object *blob1 = NULL;
4876 int fd = -1, fd1 = -1, fd2 = -1;
4877 FILE *f2 = NULL;
4878 char *abspath = NULL, *label1 = NULL;
4879 struct stat sb;
4880 off_t size1 = 0;
4881 int f2_exists = 0;
4883 memset(&sb, 0, sizeof(sb));
4885 if (a->diff_staged) {
4886 if (staged_status != GOT_STATUS_MODIFY &&
4887 staged_status != GOT_STATUS_ADD &&
4888 staged_status != GOT_STATUS_DELETE)
4889 return NULL;
4890 } else {
4891 if (staged_status == GOT_STATUS_DELETE)
4892 return NULL;
4893 if (status == GOT_STATUS_NONEXISTENT)
4894 return got_error_set_errno(ENOENT, path);
4895 if (status != GOT_STATUS_MODIFY &&
4896 status != GOT_STATUS_ADD &&
4897 status != GOT_STATUS_DELETE &&
4898 status != GOT_STATUS_CONFLICT)
4899 return NULL;
4902 err = got_opentemp_truncate(a->f1);
4903 if (err)
4904 return got_error_from_errno("got_opentemp_truncate");
4905 err = got_opentemp_truncate(a->f2);
4906 if (err)
4907 return got_error_from_errno("got_opentemp_truncate");
4909 if (!a->header_shown) {
4910 if (fprintf(a->outfile, "diff %s%s\n",
4911 a->diff_staged ? "-s " : "",
4912 got_worktree_get_root_path(a->worktree)) < 0) {
4913 err = got_error_from_errno("fprintf");
4914 goto done;
4916 if (fprintf(a->outfile, "commit - %s\n", a->id_str) < 0) {
4917 err = got_error_from_errno("fprintf");
4918 goto done;
4920 if (fprintf(a->outfile, "path + %s%s\n",
4921 got_worktree_get_root_path(a->worktree),
4922 a->diff_staged ? " (staged changes)" : "") < 0) {
4923 err = got_error_from_errno("fprintf");
4924 goto done;
4926 a->header_shown = 1;
4929 if (a->diff_staged) {
4930 const char *label1 = NULL, *label2 = NULL;
4931 switch (staged_status) {
4932 case GOT_STATUS_MODIFY:
4933 label1 = path;
4934 label2 = path;
4935 break;
4936 case GOT_STATUS_ADD:
4937 label2 = path;
4938 break;
4939 case GOT_STATUS_DELETE:
4940 label1 = path;
4941 break;
4942 default:
4943 return got_error(GOT_ERR_FILE_STATUS);
4945 fd1 = got_opentempfd();
4946 if (fd1 == -1) {
4947 err = got_error_from_errno("got_opentempfd");
4948 goto done;
4950 fd2 = got_opentempfd();
4951 if (fd2 == -1) {
4952 err = got_error_from_errno("got_opentempfd");
4953 goto done;
4955 err = got_diff_objects_as_blobs(NULL, NULL, a->f1, a->f2,
4956 fd1, fd2, blob_id, staged_blob_id, label1, label2,
4957 a->diff_algo, a->diff_context, a->ignore_whitespace,
4958 a->force_text_diff, a->diffstat, a->repo, a->outfile);
4959 goto done;
4962 fd1 = got_opentempfd();
4963 if (fd1 == -1) {
4964 err = got_error_from_errno("got_opentempfd");
4965 goto done;
4968 if (staged_status == GOT_STATUS_ADD ||
4969 staged_status == GOT_STATUS_MODIFY) {
4970 char *id_str;
4971 err = got_object_open_as_blob(&blob1, a->repo, staged_blob_id,
4972 8192, fd1);
4973 if (err)
4974 goto done;
4975 err = got_object_id_str(&id_str, staged_blob_id);
4976 if (err)
4977 goto done;
4978 if (asprintf(&label1, "%s (staged)", id_str) == -1) {
4979 err = got_error_from_errno("asprintf");
4980 free(id_str);
4981 goto done;
4983 free(id_str);
4984 } else if (status != GOT_STATUS_ADD) {
4985 err = got_object_open_as_blob(&blob1, a->repo, blob_id, 8192,
4986 fd1);
4987 if (err)
4988 goto done;
4991 if (status != GOT_STATUS_DELETE) {
4992 if (asprintf(&abspath, "%s/%s",
4993 got_worktree_get_root_path(a->worktree), path) == -1) {
4994 err = got_error_from_errno("asprintf");
4995 goto done;
4998 if (dirfd != -1) {
4999 fd = openat(dirfd, de_name,
5000 O_RDONLY | O_NOFOLLOW | O_CLOEXEC);
5001 if (fd == -1) {
5002 if (!got_err_open_nofollow_on_symlink()) {
5003 err = got_error_from_errno2("openat",
5004 abspath);
5005 goto done;
5007 err = get_symlink_target_file(&fd, dirfd,
5008 de_name, abspath);
5009 if (err)
5010 goto done;
5012 } else {
5013 fd = open(abspath, O_RDONLY | O_NOFOLLOW | O_CLOEXEC);
5014 if (fd == -1) {
5015 if (!got_err_open_nofollow_on_symlink()) {
5016 err = got_error_from_errno2("open",
5017 abspath);
5018 goto done;
5020 err = get_symlink_target_file(&fd, dirfd,
5021 de_name, abspath);
5022 if (err)
5023 goto done;
5026 if (fstatat(fd, abspath, &sb, AT_SYMLINK_NOFOLLOW) == -1) {
5027 err = got_error_from_errno2("fstatat", abspath);
5028 goto done;
5030 f2 = fdopen(fd, "r");
5031 if (f2 == NULL) {
5032 err = got_error_from_errno2("fdopen", abspath);
5033 goto done;
5035 fd = -1;
5036 f2_exists = 1;
5039 if (blob1) {
5040 err = got_object_blob_dump_to_file(&size1, NULL, NULL,
5041 a->f1, blob1);
5042 if (err)
5043 goto done;
5046 err = got_diff_blob_file(blob1, a->f1, size1, label1, f2 ? f2 : a->f2,
5047 f2_exists, &sb, path, GOT_DIFF_ALGORITHM_PATIENCE, a->diff_context,
5048 a->ignore_whitespace, a->force_text_diff, a->diffstat, a->outfile);
5049 done:
5050 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
5051 err = got_error_from_errno("close");
5052 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
5053 err = got_error_from_errno("close");
5054 if (blob1)
5055 got_object_blob_close(blob1);
5056 if (fd != -1 && close(fd) == -1 && err == NULL)
5057 err = got_error_from_errno("close");
5058 if (f2 && fclose(f2) == EOF && err == NULL)
5059 err = got_error_from_errno("fclose");
5060 free(abspath);
5061 return err;
5064 static const struct got_error *
5065 cmd_diff(int argc, char *argv[])
5067 const struct got_error *error;
5068 struct got_repository *repo = NULL;
5069 struct got_worktree *worktree = NULL;
5070 char *cwd = NULL, *repo_path = NULL;
5071 const char *commit_args[2] = { NULL, NULL };
5072 int ncommit_args = 0;
5073 struct got_object_id *ids[2] = { NULL, NULL };
5074 char *labels[2] = { NULL, NULL };
5075 int type1 = GOT_OBJ_TYPE_ANY, type2 = GOT_OBJ_TYPE_ANY;
5076 int diff_context = 3, diff_staged = 0, ignore_whitespace = 0, ch, i;
5077 int force_text_diff = 0, force_path = 0, rflag = 0, show_diffstat = 0;
5078 const char *errstr;
5079 struct got_reflist_head refs;
5080 struct got_pathlist_head diffstat_paths, paths;
5081 FILE *f1 = NULL, *f2 = NULL, *outfile = NULL;
5082 int fd1 = -1, fd2 = -1;
5083 int *pack_fds = NULL;
5084 struct got_diffstat_cb_arg dsa;
5086 memset(&dsa, 0, sizeof(dsa));
5088 TAILQ_INIT(&refs);
5089 TAILQ_INIT(&paths);
5090 TAILQ_INIT(&diffstat_paths);
5092 #ifndef PROFILE
5093 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
5094 NULL) == -1)
5095 err(1, "pledge");
5096 #endif
5098 while ((ch = getopt(argc, argv, "aC:c:dPr:sw")) != -1) {
5099 switch (ch) {
5100 case 'a':
5101 force_text_diff = 1;
5102 break;
5103 case 'C':
5104 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
5105 &errstr);
5106 if (errstr != NULL)
5107 errx(1, "number of context lines is %s: %s",
5108 errstr, optarg);
5109 break;
5110 case 'c':
5111 if (ncommit_args >= 2)
5112 errx(1, "too many -c options used");
5113 commit_args[ncommit_args++] = optarg;
5114 break;
5115 case 'd':
5116 show_diffstat = 1;
5117 break;
5118 case 'P':
5119 force_path = 1;
5120 break;
5121 case 'r':
5122 repo_path = realpath(optarg, NULL);
5123 if (repo_path == NULL)
5124 return got_error_from_errno2("realpath",
5125 optarg);
5126 got_path_strip_trailing_slashes(repo_path);
5127 rflag = 1;
5128 break;
5129 case 's':
5130 diff_staged = 1;
5131 break;
5132 case 'w':
5133 ignore_whitespace = 1;
5134 break;
5135 default:
5136 usage_diff();
5137 /* NOTREACHED */
5141 argc -= optind;
5142 argv += optind;
5144 cwd = getcwd(NULL, 0);
5145 if (cwd == NULL) {
5146 error = got_error_from_errno("getcwd");
5147 goto done;
5150 error = got_repo_pack_fds_open(&pack_fds);
5151 if (error != NULL)
5152 goto done;
5154 if (repo_path == NULL) {
5155 error = got_worktree_open(&worktree, cwd);
5156 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5157 goto done;
5158 else
5159 error = NULL;
5160 if (worktree) {
5161 repo_path =
5162 strdup(got_worktree_get_repo_path(worktree));
5163 if (repo_path == NULL) {
5164 error = got_error_from_errno("strdup");
5165 goto done;
5167 } else {
5168 repo_path = strdup(cwd);
5169 if (repo_path == NULL) {
5170 error = got_error_from_errno("strdup");
5171 goto done;
5176 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
5177 free(repo_path);
5178 if (error != NULL)
5179 goto done;
5181 if (show_diffstat) {
5182 dsa.paths = &diffstat_paths;
5183 dsa.force_text = force_text_diff;
5184 dsa.ignore_ws = ignore_whitespace;
5185 dsa.diff_algo = GOT_DIFF_ALGORITHM_PATIENCE;
5188 if (rflag || worktree == NULL || ncommit_args > 0) {
5189 if (force_path) {
5190 error = got_error_msg(GOT_ERR_NOT_IMPL,
5191 "-P option can only be used when diffing "
5192 "a work tree");
5193 goto done;
5195 if (diff_staged) {
5196 error = got_error_msg(GOT_ERR_NOT_IMPL,
5197 "-s option can only be used when diffing "
5198 "a work tree");
5199 goto done;
5203 error = apply_unveil(got_repo_get_path(repo), 1,
5204 worktree ? got_worktree_get_root_path(worktree) : NULL);
5205 if (error)
5206 goto done;
5208 if ((!force_path && argc == 2) || ncommit_args > 0) {
5209 int obj_type = (ncommit_args > 0 ?
5210 GOT_OBJ_TYPE_COMMIT : GOT_OBJ_TYPE_ANY);
5211 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
5212 NULL);
5213 if (error)
5214 goto done;
5215 for (i = 0; i < (ncommit_args > 0 ? ncommit_args : argc); i++) {
5216 const char *arg;
5217 if (ncommit_args > 0)
5218 arg = commit_args[i];
5219 else
5220 arg = argv[i];
5221 error = got_repo_match_object_id(&ids[i], &labels[i],
5222 arg, obj_type, &refs, repo);
5223 if (error) {
5224 if (error->code != GOT_ERR_NOT_REF &&
5225 error->code != GOT_ERR_NO_OBJ)
5226 goto done;
5227 if (ncommit_args > 0)
5228 goto done;
5229 error = NULL;
5230 break;
5235 f1 = got_opentemp();
5236 if (f1 == NULL) {
5237 error = got_error_from_errno("got_opentemp");
5238 goto done;
5241 f2 = got_opentemp();
5242 if (f2 == NULL) {
5243 error = got_error_from_errno("got_opentemp");
5244 goto done;
5247 outfile = got_opentemp();
5248 if (outfile == NULL) {
5249 error = got_error_from_errno("got_opentemp");
5250 goto done;
5253 if (ncommit_args == 0 && (ids[0] == NULL || ids[1] == NULL)) {
5254 struct print_diff_arg arg;
5255 char *id_str;
5257 if (worktree == NULL) {
5258 if (argc == 2 && ids[0] == NULL) {
5259 error = got_error_path(argv[0], GOT_ERR_NO_OBJ);
5260 goto done;
5261 } else if (argc == 2 && ids[1] == NULL) {
5262 error = got_error_path(argv[1], GOT_ERR_NO_OBJ);
5263 goto done;
5264 } else if (argc > 0) {
5265 error = got_error_fmt(GOT_ERR_NOT_WORKTREE,
5266 "%s", "specified paths cannot be resolved");
5267 goto done;
5268 } else {
5269 error = got_error(GOT_ERR_NOT_WORKTREE);
5270 goto done;
5274 error = get_worktree_paths_from_argv(&paths, argc, argv,
5275 worktree);
5276 if (error)
5277 goto done;
5279 error = got_object_id_str(&id_str,
5280 got_worktree_get_base_commit_id(worktree));
5281 if (error)
5282 goto done;
5283 arg.repo = repo;
5284 arg.worktree = worktree;
5285 arg.diff_algo = GOT_DIFF_ALGORITHM_PATIENCE;
5286 arg.diff_context = diff_context;
5287 arg.id_str = id_str;
5288 arg.header_shown = 0;
5289 arg.diff_staged = diff_staged;
5290 arg.ignore_whitespace = ignore_whitespace;
5291 arg.force_text_diff = force_text_diff;
5292 arg.diffstat = show_diffstat ? &dsa : NULL;
5293 arg.f1 = f1;
5294 arg.f2 = f2;
5295 arg.outfile = outfile;
5297 error = got_worktree_status(worktree, &paths, repo, 0,
5298 print_diff, &arg, check_cancelled, NULL);
5299 free(id_str);
5300 if (error)
5301 goto done;
5303 if (show_diffstat && dsa.nfiles > 0) {
5304 char *header;
5306 if (asprintf(&header, "diffstat %s%s",
5307 diff_staged ? "-s " : "",
5308 got_worktree_get_root_path(worktree)) == -1) {
5309 error = got_error_from_errno("asprintf");
5310 goto done;
5313 error = print_diffstat(&dsa, header);
5314 free(header);
5315 if (error)
5316 goto done;
5319 error = printfile(outfile);
5320 goto done;
5323 if (ncommit_args == 1) {
5324 struct got_commit_object *commit;
5325 error = got_object_open_as_commit(&commit, repo, ids[0]);
5326 if (error)
5327 goto done;
5329 labels[1] = labels[0];
5330 ids[1] = ids[0];
5331 if (got_object_commit_get_nparents(commit) > 0) {
5332 const struct got_object_id_queue *pids;
5333 struct got_object_qid *pid;
5334 pids = got_object_commit_get_parent_ids(commit);
5335 pid = STAILQ_FIRST(pids);
5336 ids[0] = got_object_id_dup(&pid->id);
5337 if (ids[0] == NULL) {
5338 error = got_error_from_errno(
5339 "got_object_id_dup");
5340 got_object_commit_close(commit);
5341 goto done;
5343 error = got_object_id_str(&labels[0], ids[0]);
5344 if (error) {
5345 got_object_commit_close(commit);
5346 goto done;
5348 } else {
5349 ids[0] = NULL;
5350 labels[0] = strdup("/dev/null");
5351 if (labels[0] == NULL) {
5352 error = got_error_from_errno("strdup");
5353 got_object_commit_close(commit);
5354 goto done;
5358 got_object_commit_close(commit);
5361 if (ncommit_args == 0 && argc > 2) {
5362 error = got_error_msg(GOT_ERR_BAD_PATH,
5363 "path arguments cannot be used when diffing two objects");
5364 goto done;
5367 if (ids[0]) {
5368 error = got_object_get_type(&type1, repo, ids[0]);
5369 if (error)
5370 goto done;
5373 error = got_object_get_type(&type2, repo, ids[1]);
5374 if (error)
5375 goto done;
5376 if (type1 != GOT_OBJ_TYPE_ANY && type1 != type2) {
5377 error = got_error(GOT_ERR_OBJ_TYPE);
5378 goto done;
5380 if (type1 == GOT_OBJ_TYPE_BLOB && argc > 2) {
5381 error = got_error_msg(GOT_ERR_OBJ_TYPE,
5382 "path arguments cannot be used when diffing blobs");
5383 goto done;
5386 for (i = 0; ncommit_args > 0 && i < argc; i++) {
5387 char *in_repo_path;
5388 struct got_pathlist_entry *new;
5389 if (worktree) {
5390 const char *prefix;
5391 char *p;
5392 error = got_worktree_resolve_path(&p, worktree,
5393 argv[i]);
5394 if (error)
5395 goto done;
5396 prefix = got_worktree_get_path_prefix(worktree);
5397 while (prefix[0] == '/')
5398 prefix++;
5399 if (asprintf(&in_repo_path, "%s%s%s", prefix,
5400 (p[0] != '\0' && prefix[0] != '\0') ? "/" : "",
5401 p) == -1) {
5402 error = got_error_from_errno("asprintf");
5403 free(p);
5404 goto done;
5406 free(p);
5407 } else {
5408 char *mapped_path, *s;
5409 error = got_repo_map_path(&mapped_path, repo, argv[i]);
5410 if (error)
5411 goto done;
5412 s = mapped_path;
5413 while (s[0] == '/')
5414 s++;
5415 in_repo_path = strdup(s);
5416 if (in_repo_path == NULL) {
5417 error = got_error_from_errno("asprintf");
5418 free(mapped_path);
5419 goto done;
5421 free(mapped_path);
5424 error = got_pathlist_insert(&new, &paths, in_repo_path, NULL);
5425 if (error || new == NULL /* duplicate */)
5426 free(in_repo_path);
5427 if (error)
5428 goto done;
5431 if (worktree) {
5432 /* Release work tree lock. */
5433 got_worktree_close(worktree);
5434 worktree = NULL;
5437 fd1 = got_opentempfd();
5438 if (fd1 == -1) {
5439 error = got_error_from_errno("got_opentempfd");
5440 goto done;
5443 fd2 = got_opentempfd();
5444 if (fd2 == -1) {
5445 error = got_error_from_errno("got_opentempfd");
5446 goto done;
5449 switch (type1 == GOT_OBJ_TYPE_ANY ? type2 : type1) {
5450 case GOT_OBJ_TYPE_BLOB:
5451 error = got_diff_objects_as_blobs(NULL, NULL, f1, f2,
5452 fd1, fd2, ids[0], ids[1], NULL, NULL,
5453 GOT_DIFF_ALGORITHM_PATIENCE, diff_context,
5454 ignore_whitespace, force_text_diff,
5455 show_diffstat ? &dsa : NULL, repo, outfile);
5456 break;
5457 case GOT_OBJ_TYPE_TREE:
5458 error = got_diff_objects_as_trees(NULL, NULL, f1, f2, fd1, fd2,
5459 ids[0], ids[1], &paths, "", "",
5460 GOT_DIFF_ALGORITHM_PATIENCE, diff_context,
5461 ignore_whitespace, force_text_diff,
5462 show_diffstat ? &dsa : NULL, repo, outfile);
5463 break;
5464 case GOT_OBJ_TYPE_COMMIT:
5465 fprintf(outfile, "diff %s %s\n", labels[0], labels[1]);
5466 error = got_diff_objects_as_commits(NULL, NULL, f1, f2,
5467 fd1, fd2, ids[0], ids[1], &paths,
5468 GOT_DIFF_ALGORITHM_PATIENCE, diff_context,
5469 ignore_whitespace, force_text_diff,
5470 show_diffstat ? &dsa : NULL, repo, outfile);
5471 break;
5472 default:
5473 error = got_error(GOT_ERR_OBJ_TYPE);
5475 if (error)
5476 goto done;
5478 if (show_diffstat && dsa.nfiles > 0) {
5479 char *header = NULL;
5481 if (asprintf(&header, "diffstat %s %s",
5482 labels[0], labels[1]) == -1) {
5483 error = got_error_from_errno("asprintf");
5484 goto done;
5487 error = print_diffstat(&dsa, header);
5488 free(header);
5489 if (error)
5490 goto done;
5493 error = printfile(outfile);
5495 done:
5496 free(labels[0]);
5497 free(labels[1]);
5498 free(ids[0]);
5499 free(ids[1]);
5500 if (worktree)
5501 got_worktree_close(worktree);
5502 if (repo) {
5503 const struct got_error *close_err = got_repo_close(repo);
5504 if (error == NULL)
5505 error = close_err;
5507 if (pack_fds) {
5508 const struct got_error *pack_err =
5509 got_repo_pack_fds_close(pack_fds);
5510 if (error == NULL)
5511 error = pack_err;
5513 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
5514 got_pathlist_free(&diffstat_paths, GOT_PATHLIST_FREE_ALL);
5515 got_ref_list_free(&refs);
5516 if (outfile && fclose(outfile) == EOF && error == NULL)
5517 error = got_error_from_errno("fclose");
5518 if (f1 && fclose(f1) == EOF && error == NULL)
5519 error = got_error_from_errno("fclose");
5520 if (f2 && fclose(f2) == EOF && error == NULL)
5521 error = got_error_from_errno("fclose");
5522 if (fd1 != -1 && close(fd1) == -1 && error == NULL)
5523 error = got_error_from_errno("close");
5524 if (fd2 != -1 && close(fd2) == -1 && error == NULL)
5525 error = got_error_from_errno("close");
5526 return error;
5529 __dead static void
5530 usage_blame(void)
5532 fprintf(stderr,
5533 "usage: %s blame [-c commit] [-r repository-path] path\n",
5534 getprogname());
5535 exit(1);
5538 struct blame_line {
5539 int annotated;
5540 char *id_str;
5541 char *committer;
5542 char datebuf[11]; /* YYYY-MM-DD + NUL */
5545 struct blame_cb_args {
5546 struct blame_line *lines;
5547 int nlines;
5548 int nlines_prec;
5549 int lineno_cur;
5550 off_t *line_offsets;
5551 FILE *f;
5552 struct got_repository *repo;
5555 static const struct got_error *
5556 blame_cb(void *arg, int nlines, int lineno,
5557 struct got_commit_object *commit, struct got_object_id *id)
5559 const struct got_error *err = NULL;
5560 struct blame_cb_args *a = arg;
5561 struct blame_line *bline;
5562 char *line = NULL;
5563 size_t linesize = 0;
5564 off_t offset;
5565 struct tm tm;
5566 time_t committer_time;
5568 if (nlines != a->nlines ||
5569 (lineno != -1 && lineno < 1) || lineno > a->nlines)
5570 return got_error(GOT_ERR_RANGE);
5572 if (sigint_received)
5573 return got_error(GOT_ERR_ITER_COMPLETED);
5575 if (lineno == -1)
5576 return NULL; /* no change in this commit */
5578 /* Annotate this line. */
5579 bline = &a->lines[lineno - 1];
5580 if (bline->annotated)
5581 return NULL;
5582 err = got_object_id_str(&bline->id_str, id);
5583 if (err)
5584 return err;
5586 bline->committer = strdup(got_object_commit_get_committer(commit));
5587 if (bline->committer == NULL) {
5588 err = got_error_from_errno("strdup");
5589 goto done;
5592 committer_time = got_object_commit_get_committer_time(commit);
5593 if (gmtime_r(&committer_time, &tm) == NULL)
5594 return got_error_from_errno("gmtime_r");
5595 if (strftime(bline->datebuf, sizeof(bline->datebuf), "%G-%m-%d",
5596 &tm) == 0) {
5597 err = got_error(GOT_ERR_NO_SPACE);
5598 goto done;
5600 bline->annotated = 1;
5602 /* Print lines annotated so far. */
5603 bline = &a->lines[a->lineno_cur - 1];
5604 if (!bline->annotated)
5605 goto done;
5607 offset = a->line_offsets[a->lineno_cur - 1];
5608 if (fseeko(a->f, offset, SEEK_SET) == -1) {
5609 err = got_error_from_errno("fseeko");
5610 goto done;
5613 while (a->lineno_cur <= a->nlines && bline->annotated) {
5614 char *smallerthan, *at, *nl, *committer;
5615 size_t len;
5617 if (getline(&line, &linesize, a->f) == -1) {
5618 if (ferror(a->f))
5619 err = got_error_from_errno("getline");
5620 break;
5623 committer = bline->committer;
5624 smallerthan = strchr(committer, '<');
5625 if (smallerthan && smallerthan[1] != '\0')
5626 committer = smallerthan + 1;
5627 at = strchr(committer, '@');
5628 if (at)
5629 *at = '\0';
5630 len = strlen(committer);
5631 if (len >= 9)
5632 committer[8] = '\0';
5634 nl = strchr(line, '\n');
5635 if (nl)
5636 *nl = '\0';
5637 printf("%.*d) %.8s %s %-8s %s\n", a->nlines_prec, a->lineno_cur,
5638 bline->id_str, bline->datebuf, committer, line);
5640 a->lineno_cur++;
5641 bline = &a->lines[a->lineno_cur - 1];
5643 done:
5644 free(line);
5645 return err;
5648 static const struct got_error *
5649 cmd_blame(int argc, char *argv[])
5651 const struct got_error *error;
5652 struct got_repository *repo = NULL;
5653 struct got_worktree *worktree = NULL;
5654 char *path, *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
5655 char *link_target = NULL;
5656 struct got_object_id *obj_id = NULL;
5657 struct got_object_id *commit_id = NULL;
5658 struct got_commit_object *commit = NULL;
5659 struct got_blob_object *blob = NULL;
5660 char *commit_id_str = NULL;
5661 struct blame_cb_args bca;
5662 int ch, obj_type, i, fd1 = -1, fd2 = -1, fd3 = -1;
5663 off_t filesize;
5664 int *pack_fds = NULL;
5665 FILE *f1 = NULL, *f2 = NULL;
5667 fd1 = got_opentempfd();
5668 if (fd1 == -1)
5669 return got_error_from_errno("got_opentempfd");
5671 memset(&bca, 0, sizeof(bca));
5673 #ifndef PROFILE
5674 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
5675 NULL) == -1)
5676 err(1, "pledge");
5677 #endif
5679 while ((ch = getopt(argc, argv, "c:r:")) != -1) {
5680 switch (ch) {
5681 case 'c':
5682 commit_id_str = optarg;
5683 break;
5684 case 'r':
5685 repo_path = realpath(optarg, NULL);
5686 if (repo_path == NULL)
5687 return got_error_from_errno2("realpath",
5688 optarg);
5689 got_path_strip_trailing_slashes(repo_path);
5690 break;
5691 default:
5692 usage_blame();
5693 /* NOTREACHED */
5697 argc -= optind;
5698 argv += optind;
5700 if (argc == 1)
5701 path = argv[0];
5702 else
5703 usage_blame();
5705 cwd = getcwd(NULL, 0);
5706 if (cwd == NULL) {
5707 error = got_error_from_errno("getcwd");
5708 goto done;
5711 error = got_repo_pack_fds_open(&pack_fds);
5712 if (error != NULL)
5713 goto done;
5715 if (repo_path == NULL) {
5716 error = got_worktree_open(&worktree, cwd);
5717 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5718 goto done;
5719 else
5720 error = NULL;
5721 if (worktree) {
5722 repo_path =
5723 strdup(got_worktree_get_repo_path(worktree));
5724 if (repo_path == NULL) {
5725 error = got_error_from_errno("strdup");
5726 if (error)
5727 goto done;
5729 } else {
5730 repo_path = strdup(cwd);
5731 if (repo_path == NULL) {
5732 error = got_error_from_errno("strdup");
5733 goto done;
5738 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
5739 if (error != NULL)
5740 goto done;
5742 if (worktree) {
5743 const char *prefix = got_worktree_get_path_prefix(worktree);
5744 char *p;
5746 error = got_worktree_resolve_path(&p, worktree, path);
5747 if (error)
5748 goto done;
5749 if (asprintf(&in_repo_path, "%s%s%s", prefix,
5750 (p[0] != '\0' && !got_path_is_root_dir(prefix)) ? "/" : "",
5751 p) == -1) {
5752 error = got_error_from_errno("asprintf");
5753 free(p);
5754 goto done;
5756 free(p);
5757 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5758 } else {
5759 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5760 if (error)
5761 goto done;
5762 error = got_repo_map_path(&in_repo_path, repo, path);
5764 if (error)
5765 goto done;
5767 if (commit_id_str == NULL) {
5768 struct got_reference *head_ref;
5769 error = got_ref_open(&head_ref, repo, worktree ?
5770 got_worktree_get_head_ref_name(worktree) : GOT_REF_HEAD, 0);
5771 if (error != NULL)
5772 goto done;
5773 error = got_ref_resolve(&commit_id, repo, head_ref);
5774 got_ref_close(head_ref);
5775 if (error != NULL)
5776 goto done;
5777 } else {
5778 struct got_reflist_head refs;
5779 TAILQ_INIT(&refs);
5780 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
5781 NULL);
5782 if (error)
5783 goto done;
5784 error = got_repo_match_object_id(&commit_id, NULL,
5785 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
5786 got_ref_list_free(&refs);
5787 if (error)
5788 goto done;
5791 if (worktree) {
5792 /* Release work tree lock. */
5793 got_worktree_close(worktree);
5794 worktree = NULL;
5797 error = got_object_open_as_commit(&commit, repo, commit_id);
5798 if (error)
5799 goto done;
5801 error = got_object_resolve_symlinks(&link_target, in_repo_path,
5802 commit, repo);
5803 if (error)
5804 goto done;
5806 error = got_object_id_by_path(&obj_id, repo, commit,
5807 link_target ? link_target : in_repo_path);
5808 if (error)
5809 goto done;
5811 error = got_object_get_type(&obj_type, repo, obj_id);
5812 if (error)
5813 goto done;
5815 if (obj_type != GOT_OBJ_TYPE_BLOB) {
5816 error = got_error_path(link_target ? link_target : in_repo_path,
5817 GOT_ERR_OBJ_TYPE);
5818 goto done;
5821 error = got_object_open_as_blob(&blob, repo, obj_id, 8192, fd1);
5822 if (error)
5823 goto done;
5824 bca.f = got_opentemp();
5825 if (bca.f == NULL) {
5826 error = got_error_from_errno("got_opentemp");
5827 goto done;
5829 error = got_object_blob_dump_to_file(&filesize, &bca.nlines,
5830 &bca.line_offsets, bca.f, blob);
5831 if (error || bca.nlines == 0)
5832 goto done;
5834 /* Don't include \n at EOF in the blame line count. */
5835 if (bca.line_offsets[bca.nlines - 1] == filesize)
5836 bca.nlines--;
5838 bca.lines = calloc(bca.nlines, sizeof(*bca.lines));
5839 if (bca.lines == NULL) {
5840 error = got_error_from_errno("calloc");
5841 goto done;
5843 bca.lineno_cur = 1;
5844 bca.nlines_prec = 0;
5845 i = bca.nlines;
5846 while (i > 0) {
5847 i /= 10;
5848 bca.nlines_prec++;
5850 bca.repo = repo;
5852 fd2 = got_opentempfd();
5853 if (fd2 == -1) {
5854 error = got_error_from_errno("got_opentempfd");
5855 goto done;
5857 fd3 = got_opentempfd();
5858 if (fd3 == -1) {
5859 error = got_error_from_errno("got_opentempfd");
5860 goto done;
5862 f1 = got_opentemp();
5863 if (f1 == NULL) {
5864 error = got_error_from_errno("got_opentemp");
5865 goto done;
5867 f2 = got_opentemp();
5868 if (f2 == NULL) {
5869 error = got_error_from_errno("got_opentemp");
5870 goto done;
5872 error = got_blame(link_target ? link_target : in_repo_path, commit_id,
5873 repo, GOT_DIFF_ALGORITHM_PATIENCE, blame_cb, &bca,
5874 check_cancelled, NULL, fd2, fd3, f1, f2);
5875 done:
5876 free(in_repo_path);
5877 free(link_target);
5878 free(repo_path);
5879 free(cwd);
5880 free(commit_id);
5881 free(obj_id);
5882 if (commit)
5883 got_object_commit_close(commit);
5885 if (fd1 != -1 && close(fd1) == -1 && error == NULL)
5886 error = got_error_from_errno("close");
5887 if (fd2 != -1 && close(fd2) == -1 && error == NULL)
5888 error = got_error_from_errno("close");
5889 if (fd3 != -1 && close(fd3) == -1 && error == NULL)
5890 error = got_error_from_errno("close");
5891 if (f1 && fclose(f1) == EOF && error == NULL)
5892 error = got_error_from_errno("fclose");
5893 if (f2 && fclose(f2) == EOF && error == NULL)
5894 error = got_error_from_errno("fclose");
5896 if (blob)
5897 got_object_blob_close(blob);
5898 if (worktree)
5899 got_worktree_close(worktree);
5900 if (repo) {
5901 const struct got_error *close_err = got_repo_close(repo);
5902 if (error == NULL)
5903 error = close_err;
5905 if (pack_fds) {
5906 const struct got_error *pack_err =
5907 got_repo_pack_fds_close(pack_fds);
5908 if (error == NULL)
5909 error = pack_err;
5911 if (bca.lines) {
5912 for (i = 0; i < bca.nlines; i++) {
5913 struct blame_line *bline = &bca.lines[i];
5914 free(bline->id_str);
5915 free(bline->committer);
5917 free(bca.lines);
5919 free(bca.line_offsets);
5920 if (bca.f && fclose(bca.f) == EOF && error == NULL)
5921 error = got_error_from_errno("fclose");
5922 return error;
5925 __dead static void
5926 usage_tree(void)
5928 fprintf(stderr, "usage: %s tree [-iR] [-c commit] [-r repository-path] "
5929 "[path]\n", getprogname());
5930 exit(1);
5933 static const struct got_error *
5934 print_entry(struct got_tree_entry *te, const char *id, const char *path,
5935 const char *root_path, struct got_repository *repo)
5937 const struct got_error *err = NULL;
5938 int is_root_path = (strcmp(path, root_path) == 0);
5939 const char *modestr = "";
5940 mode_t mode = got_tree_entry_get_mode(te);
5941 char *link_target = NULL;
5943 path += strlen(root_path);
5944 while (path[0] == '/')
5945 path++;
5947 if (got_object_tree_entry_is_submodule(te))
5948 modestr = "$";
5949 else if (S_ISLNK(mode)) {
5950 int i;
5952 err = got_tree_entry_get_symlink_target(&link_target, te, repo);
5953 if (err)
5954 return err;
5955 for (i = 0; i < strlen(link_target); i++) {
5956 if (!isprint((unsigned char)link_target[i]))
5957 link_target[i] = '?';
5960 modestr = "@";
5962 else if (S_ISDIR(mode))
5963 modestr = "/";
5964 else if (mode & S_IXUSR)
5965 modestr = "*";
5967 printf("%s%s%s%s%s%s%s\n", id ? id : "", path,
5968 is_root_path ? "" : "/", got_tree_entry_get_name(te), modestr,
5969 link_target ? " -> ": "", link_target ? link_target : "");
5971 free(link_target);
5972 return NULL;
5975 static const struct got_error *
5976 print_tree(const char *path, struct got_commit_object *commit,
5977 int show_ids, int recurse, const char *root_path,
5978 struct got_repository *repo)
5980 const struct got_error *err = NULL;
5981 struct got_object_id *tree_id = NULL;
5982 struct got_tree_object *tree = NULL;
5983 int nentries, i;
5985 err = got_object_id_by_path(&tree_id, repo, commit, path);
5986 if (err)
5987 goto done;
5989 err = got_object_open_as_tree(&tree, repo, tree_id);
5990 if (err)
5991 goto done;
5992 nentries = got_object_tree_get_nentries(tree);
5993 for (i = 0; i < nentries; i++) {
5994 struct got_tree_entry *te;
5995 char *id = NULL;
5997 if (sigint_received || sigpipe_received)
5998 break;
6000 te = got_object_tree_get_entry(tree, i);
6001 if (show_ids) {
6002 char *id_str;
6003 err = got_object_id_str(&id_str,
6004 got_tree_entry_get_id(te));
6005 if (err)
6006 goto done;
6007 if (asprintf(&id, "%s ", id_str) == -1) {
6008 err = got_error_from_errno("asprintf");
6009 free(id_str);
6010 goto done;
6012 free(id_str);
6014 err = print_entry(te, id, path, root_path, repo);
6015 free(id);
6016 if (err)
6017 goto done;
6019 if (recurse && S_ISDIR(got_tree_entry_get_mode(te))) {
6020 char *child_path;
6021 if (asprintf(&child_path, "%s%s%s", path,
6022 path[0] == '/' && path[1] == '\0' ? "" : "/",
6023 got_tree_entry_get_name(te)) == -1) {
6024 err = got_error_from_errno("asprintf");
6025 goto done;
6027 err = print_tree(child_path, commit, show_ids, 1,
6028 root_path, repo);
6029 free(child_path);
6030 if (err)
6031 goto done;
6034 done:
6035 if (tree)
6036 got_object_tree_close(tree);
6037 free(tree_id);
6038 return err;
6041 static const struct got_error *
6042 cmd_tree(int argc, char *argv[])
6044 const struct got_error *error;
6045 struct got_repository *repo = NULL;
6046 struct got_worktree *worktree = NULL;
6047 const char *path, *refname = NULL;
6048 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
6049 struct got_object_id *commit_id = NULL;
6050 struct got_commit_object *commit = NULL;
6051 char *commit_id_str = NULL;
6052 int show_ids = 0, recurse = 0;
6053 int ch;
6054 int *pack_fds = NULL;
6056 #ifndef PROFILE
6057 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
6058 NULL) == -1)
6059 err(1, "pledge");
6060 #endif
6062 while ((ch = getopt(argc, argv, "c:iRr:")) != -1) {
6063 switch (ch) {
6064 case 'c':
6065 commit_id_str = optarg;
6066 break;
6067 case 'i':
6068 show_ids = 1;
6069 break;
6070 case 'R':
6071 recurse = 1;
6072 break;
6073 case 'r':
6074 repo_path = realpath(optarg, NULL);
6075 if (repo_path == NULL)
6076 return got_error_from_errno2("realpath",
6077 optarg);
6078 got_path_strip_trailing_slashes(repo_path);
6079 break;
6080 default:
6081 usage_tree();
6082 /* NOTREACHED */
6086 argc -= optind;
6087 argv += optind;
6089 if (argc == 1)
6090 path = argv[0];
6091 else if (argc > 1)
6092 usage_tree();
6093 else
6094 path = NULL;
6096 cwd = getcwd(NULL, 0);
6097 if (cwd == NULL) {
6098 error = got_error_from_errno("getcwd");
6099 goto done;
6102 error = got_repo_pack_fds_open(&pack_fds);
6103 if (error != NULL)
6104 goto done;
6106 if (repo_path == NULL) {
6107 error = got_worktree_open(&worktree, cwd);
6108 if (error && error->code != GOT_ERR_NOT_WORKTREE)
6109 goto done;
6110 else
6111 error = NULL;
6112 if (worktree) {
6113 repo_path =
6114 strdup(got_worktree_get_repo_path(worktree));
6115 if (repo_path == NULL)
6116 error = got_error_from_errno("strdup");
6117 if (error)
6118 goto done;
6119 } else {
6120 repo_path = strdup(cwd);
6121 if (repo_path == NULL) {
6122 error = got_error_from_errno("strdup");
6123 goto done;
6128 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
6129 if (error != NULL)
6130 goto done;
6132 if (worktree) {
6133 const char *prefix = got_worktree_get_path_prefix(worktree);
6134 char *p;
6136 if (path == NULL)
6137 path = "";
6138 error = got_worktree_resolve_path(&p, worktree, path);
6139 if (error)
6140 goto done;
6141 if (asprintf(&in_repo_path, "%s%s%s", prefix,
6142 (p[0] != '\0' && !got_path_is_root_dir(prefix)) ? "/" : "",
6143 p) == -1) {
6144 error = got_error_from_errno("asprintf");
6145 free(p);
6146 goto done;
6148 free(p);
6149 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
6150 if (error)
6151 goto done;
6152 } else {
6153 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
6154 if (error)
6155 goto done;
6156 if (path == NULL)
6157 path = "/";
6158 error = got_repo_map_path(&in_repo_path, repo, path);
6159 if (error != NULL)
6160 goto done;
6163 if (commit_id_str == NULL) {
6164 struct got_reference *head_ref;
6165 if (worktree)
6166 refname = got_worktree_get_head_ref_name(worktree);
6167 else
6168 refname = GOT_REF_HEAD;
6169 error = got_ref_open(&head_ref, repo, refname, 0);
6170 if (error != NULL)
6171 goto done;
6172 error = got_ref_resolve(&commit_id, repo, head_ref);
6173 got_ref_close(head_ref);
6174 if (error != NULL)
6175 goto done;
6176 } else {
6177 struct got_reflist_head refs;
6178 TAILQ_INIT(&refs);
6179 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
6180 NULL);
6181 if (error)
6182 goto done;
6183 error = got_repo_match_object_id(&commit_id, NULL,
6184 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
6185 got_ref_list_free(&refs);
6186 if (error)
6187 goto done;
6190 if (worktree) {
6191 /* Release work tree lock. */
6192 got_worktree_close(worktree);
6193 worktree = NULL;
6196 error = got_object_open_as_commit(&commit, repo, commit_id);
6197 if (error)
6198 goto done;
6200 error = print_tree(in_repo_path, commit, show_ids, recurse,
6201 in_repo_path, repo);
6202 done:
6203 free(in_repo_path);
6204 free(repo_path);
6205 free(cwd);
6206 free(commit_id);
6207 if (commit)
6208 got_object_commit_close(commit);
6209 if (worktree)
6210 got_worktree_close(worktree);
6211 if (repo) {
6212 const struct got_error *close_err = got_repo_close(repo);
6213 if (error == NULL)
6214 error = close_err;
6216 if (pack_fds) {
6217 const struct got_error *pack_err =
6218 got_repo_pack_fds_close(pack_fds);
6219 if (error == NULL)
6220 error = pack_err;
6222 return error;
6225 __dead static void
6226 usage_status(void)
6228 fprintf(stderr, "usage: %s status [-I] [-S status-codes] "
6229 "[-s status-codes] [path ...]\n", getprogname());
6230 exit(1);
6233 struct got_status_arg {
6234 char *status_codes;
6235 int suppress;
6238 static const struct got_error *
6239 print_status(void *arg, unsigned char status, unsigned char staged_status,
6240 const char *path, struct got_object_id *blob_id,
6241 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
6242 int dirfd, const char *de_name)
6244 struct got_status_arg *st = arg;
6246 if (status == staged_status && (status == GOT_STATUS_DELETE))
6247 status = GOT_STATUS_NO_CHANGE;
6248 if (st != NULL && st->status_codes) {
6249 size_t ncodes = strlen(st->status_codes);
6250 int i, j = 0;
6252 for (i = 0; i < ncodes ; i++) {
6253 if (st->suppress) {
6254 if (status == st->status_codes[i] ||
6255 staged_status == st->status_codes[i]) {
6256 j++;
6257 continue;
6259 } else {
6260 if (status == st->status_codes[i] ||
6261 staged_status == st->status_codes[i])
6262 break;
6266 if (st->suppress && j == 0)
6267 goto print;
6269 if (i == ncodes)
6270 return NULL;
6272 print:
6273 printf("%c%c %s\n", status, staged_status, path);
6274 return NULL;
6277 static const struct got_error *
6278 cmd_status(int argc, char *argv[])
6280 const struct got_error *error = NULL;
6281 struct got_repository *repo = NULL;
6282 struct got_worktree *worktree = NULL;
6283 struct got_status_arg st;
6284 char *cwd = NULL;
6285 struct got_pathlist_head paths;
6286 int ch, i, no_ignores = 0;
6287 int *pack_fds = NULL;
6289 TAILQ_INIT(&paths);
6291 memset(&st, 0, sizeof(st));
6292 st.status_codes = NULL;
6293 st.suppress = 0;
6295 while ((ch = getopt(argc, argv, "IS:s:")) != -1) {
6296 switch (ch) {
6297 case 'I':
6298 no_ignores = 1;
6299 break;
6300 case 'S':
6301 if (st.status_codes != NULL && st.suppress == 0)
6302 option_conflict('S', 's');
6303 st.suppress = 1;
6304 /* fallthrough */
6305 case 's':
6306 for (i = 0; i < strlen(optarg); i++) {
6307 switch (optarg[i]) {
6308 case GOT_STATUS_MODIFY:
6309 case GOT_STATUS_ADD:
6310 case GOT_STATUS_DELETE:
6311 case GOT_STATUS_CONFLICT:
6312 case GOT_STATUS_MISSING:
6313 case GOT_STATUS_OBSTRUCTED:
6314 case GOT_STATUS_UNVERSIONED:
6315 case GOT_STATUS_MODE_CHANGE:
6316 case GOT_STATUS_NONEXISTENT:
6317 break;
6318 default:
6319 errx(1, "invalid status code '%c'",
6320 optarg[i]);
6323 if (ch == 's' && st.suppress)
6324 option_conflict('s', 'S');
6325 st.status_codes = optarg;
6326 break;
6327 default:
6328 usage_status();
6329 /* NOTREACHED */
6333 argc -= optind;
6334 argv += optind;
6336 #ifndef PROFILE
6337 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
6338 NULL) == -1)
6339 err(1, "pledge");
6340 #endif
6341 cwd = getcwd(NULL, 0);
6342 if (cwd == NULL) {
6343 error = got_error_from_errno("getcwd");
6344 goto done;
6347 error = got_repo_pack_fds_open(&pack_fds);
6348 if (error != NULL)
6349 goto done;
6351 error = got_worktree_open(&worktree, cwd);
6352 if (error) {
6353 if (error->code == GOT_ERR_NOT_WORKTREE)
6354 error = wrap_not_worktree_error(error, "status", cwd);
6355 goto done;
6358 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
6359 NULL, pack_fds);
6360 if (error != NULL)
6361 goto done;
6363 error = apply_unveil(got_repo_get_path(repo), 1,
6364 got_worktree_get_root_path(worktree));
6365 if (error)
6366 goto done;
6368 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
6369 if (error)
6370 goto done;
6372 error = got_worktree_status(worktree, &paths, repo, no_ignores,
6373 print_status, &st, check_cancelled, NULL);
6374 done:
6375 if (pack_fds) {
6376 const struct got_error *pack_err =
6377 got_repo_pack_fds_close(pack_fds);
6378 if (error == NULL)
6379 error = pack_err;
6382 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
6383 free(cwd);
6384 return error;
6387 __dead static void
6388 usage_ref(void)
6390 fprintf(stderr, "usage: %s ref [-dlt] [-c object] [-r repository-path] "
6391 "[-s reference] [name]\n", getprogname());
6392 exit(1);
6395 static const struct got_error *
6396 list_refs(struct got_repository *repo, const char *refname, int sort_by_time)
6398 static const struct got_error *err = NULL;
6399 struct got_reflist_head refs;
6400 struct got_reflist_entry *re;
6402 TAILQ_INIT(&refs);
6403 err = got_ref_list(&refs, repo, refname, sort_by_time ?
6404 got_ref_cmp_by_commit_timestamp_descending : got_ref_cmp_by_name,
6405 repo);
6406 if (err)
6407 return err;
6409 TAILQ_FOREACH(re, &refs, entry) {
6410 char *refstr;
6411 refstr = got_ref_to_str(re->ref);
6412 if (refstr == NULL) {
6413 err = got_error_from_errno("got_ref_to_str");
6414 break;
6416 printf("%s: %s\n", got_ref_get_name(re->ref), refstr);
6417 free(refstr);
6420 got_ref_list_free(&refs);
6421 return err;
6424 static const struct got_error *
6425 delete_ref_by_name(struct got_repository *repo, const char *refname)
6427 const struct got_error *err;
6428 struct got_reference *ref;
6430 err = got_ref_open(&ref, repo, refname, 0);
6431 if (err)
6432 return err;
6434 err = delete_ref(repo, ref);
6435 got_ref_close(ref);
6436 return err;
6439 static const struct got_error *
6440 add_ref(struct got_repository *repo, const char *refname, const char *target)
6442 const struct got_error *err = NULL;
6443 struct got_object_id *id = NULL;
6444 struct got_reference *ref = NULL;
6445 struct got_reflist_head refs;
6448 * Don't let the user create a reference name with a leading '-'.
6449 * While technically a valid reference name, this case is usually
6450 * an unintended typo.
6452 if (refname[0] == '-')
6453 return got_error_path(refname, GOT_ERR_REF_NAME_MINUS);
6455 TAILQ_INIT(&refs);
6456 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
6457 if (err)
6458 goto done;
6459 err = got_repo_match_object_id(&id, NULL, target, GOT_OBJ_TYPE_ANY,
6460 &refs, repo);
6461 got_ref_list_free(&refs);
6462 if (err)
6463 goto done;
6465 err = got_ref_alloc(&ref, refname, id);
6466 if (err)
6467 goto done;
6469 err = got_ref_write(ref, repo);
6470 done:
6471 if (ref)
6472 got_ref_close(ref);
6473 free(id);
6474 return err;
6477 static const struct got_error *
6478 add_symref(struct got_repository *repo, const char *refname, const char *target)
6480 const struct got_error *err = NULL;
6481 struct got_reference *ref = NULL;
6482 struct got_reference *target_ref = NULL;
6485 * Don't let the user create a reference name with a leading '-'.
6486 * While technically a valid reference name, this case is usually
6487 * an unintended typo.
6489 if (refname[0] == '-')
6490 return got_error_path(refname, GOT_ERR_REF_NAME_MINUS);
6492 err = got_ref_open(&target_ref, repo, target, 0);
6493 if (err)
6494 return err;
6496 err = got_ref_alloc_symref(&ref, refname, target_ref);
6497 if (err)
6498 goto done;
6500 err = got_ref_write(ref, repo);
6501 done:
6502 if (target_ref)
6503 got_ref_close(target_ref);
6504 if (ref)
6505 got_ref_close(ref);
6506 return err;
6509 static const struct got_error *
6510 cmd_ref(int argc, char *argv[])
6512 const struct got_error *error = NULL;
6513 struct got_repository *repo = NULL;
6514 struct got_worktree *worktree = NULL;
6515 char *cwd = NULL, *repo_path = NULL;
6516 int ch, do_list = 0, do_delete = 0, sort_by_time = 0;
6517 const char *obj_arg = NULL, *symref_target= NULL;
6518 char *refname = NULL;
6519 int *pack_fds = NULL;
6521 while ((ch = getopt(argc, argv, "c:dlr:s:t")) != -1) {
6522 switch (ch) {
6523 case 'c':
6524 obj_arg = optarg;
6525 break;
6526 case 'd':
6527 do_delete = 1;
6528 break;
6529 case 'l':
6530 do_list = 1;
6531 break;
6532 case 'r':
6533 repo_path = realpath(optarg, NULL);
6534 if (repo_path == NULL)
6535 return got_error_from_errno2("realpath",
6536 optarg);
6537 got_path_strip_trailing_slashes(repo_path);
6538 break;
6539 case 's':
6540 symref_target = optarg;
6541 break;
6542 case 't':
6543 sort_by_time = 1;
6544 break;
6545 default:
6546 usage_ref();
6547 /* NOTREACHED */
6551 if (obj_arg && do_list)
6552 option_conflict('c', 'l');
6553 if (obj_arg && do_delete)
6554 option_conflict('c', 'd');
6555 if (obj_arg && symref_target)
6556 option_conflict('c', 's');
6557 if (symref_target && do_delete)
6558 option_conflict('s', 'd');
6559 if (symref_target && do_list)
6560 option_conflict('s', 'l');
6561 if (do_delete && do_list)
6562 option_conflict('d', 'l');
6563 if (sort_by_time && !do_list)
6564 errx(1, "-t option requires -l option");
6566 argc -= optind;
6567 argv += optind;
6569 if (do_list) {
6570 if (argc != 0 && argc != 1)
6571 usage_ref();
6572 if (argc == 1) {
6573 refname = strdup(argv[0]);
6574 if (refname == NULL) {
6575 error = got_error_from_errno("strdup");
6576 goto done;
6579 } else {
6580 if (argc != 1)
6581 usage_ref();
6582 refname = strdup(argv[0]);
6583 if (refname == NULL) {
6584 error = got_error_from_errno("strdup");
6585 goto done;
6589 if (refname)
6590 got_path_strip_trailing_slashes(refname);
6592 #ifndef PROFILE
6593 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
6594 "sendfd unveil", NULL) == -1)
6595 err(1, "pledge");
6596 #endif
6597 cwd = getcwd(NULL, 0);
6598 if (cwd == NULL) {
6599 error = got_error_from_errno("getcwd");
6600 goto done;
6603 error = got_repo_pack_fds_open(&pack_fds);
6604 if (error != NULL)
6605 goto done;
6607 if (repo_path == NULL) {
6608 error = got_worktree_open(&worktree, cwd);
6609 if (error && error->code != GOT_ERR_NOT_WORKTREE)
6610 goto done;
6611 else
6612 error = NULL;
6613 if (worktree) {
6614 repo_path =
6615 strdup(got_worktree_get_repo_path(worktree));
6616 if (repo_path == NULL)
6617 error = got_error_from_errno("strdup");
6618 if (error)
6619 goto done;
6620 } else {
6621 repo_path = strdup(cwd);
6622 if (repo_path == NULL) {
6623 error = got_error_from_errno("strdup");
6624 goto done;
6629 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
6630 if (error != NULL)
6631 goto done;
6633 #ifndef PROFILE
6634 if (do_list) {
6635 /* Remove "cpath" promise. */
6636 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
6637 NULL) == -1)
6638 err(1, "pledge");
6640 #endif
6642 error = apply_unveil(got_repo_get_path(repo), do_list,
6643 worktree ? got_worktree_get_root_path(worktree) : NULL);
6644 if (error)
6645 goto done;
6647 if (do_list)
6648 error = list_refs(repo, refname, sort_by_time);
6649 else if (do_delete)
6650 error = delete_ref_by_name(repo, refname);
6651 else if (symref_target)
6652 error = add_symref(repo, refname, symref_target);
6653 else {
6654 if (obj_arg == NULL)
6655 usage_ref();
6656 error = add_ref(repo, refname, obj_arg);
6658 done:
6659 free(refname);
6660 if (repo) {
6661 const struct got_error *close_err = got_repo_close(repo);
6662 if (error == NULL)
6663 error = close_err;
6665 if (worktree)
6666 got_worktree_close(worktree);
6667 if (pack_fds) {
6668 const struct got_error *pack_err =
6669 got_repo_pack_fds_close(pack_fds);
6670 if (error == NULL)
6671 error = pack_err;
6673 free(cwd);
6674 free(repo_path);
6675 return error;
6678 __dead static void
6679 usage_branch(void)
6681 fprintf(stderr, "usage: %s branch [-lnt] [-c commit] [-d name] "
6682 "[-r repository-path] [name]\n", getprogname());
6683 exit(1);
6686 static const struct got_error *
6687 list_branch(struct got_repository *repo, struct got_worktree *worktree,
6688 struct got_reference *ref)
6690 const struct got_error *err = NULL;
6691 const char *refname, *marker = " ";
6692 char *refstr;
6694 refname = got_ref_get_name(ref);
6695 if (worktree && strcmp(refname,
6696 got_worktree_get_head_ref_name(worktree)) == 0) {
6697 struct got_object_id *id = NULL;
6699 err = got_ref_resolve(&id, repo, ref);
6700 if (err)
6701 return err;
6702 if (got_object_id_cmp(id,
6703 got_worktree_get_base_commit_id(worktree)) == 0)
6704 marker = "* ";
6705 else
6706 marker = "~ ";
6707 free(id);
6710 if (strncmp(refname, "refs/heads/", 11) == 0)
6711 refname += 11;
6712 if (strncmp(refname, "refs/got/worktree/", 18) == 0)
6713 refname += 18;
6714 if (strncmp(refname, "refs/remotes/", 13) == 0)
6715 refname += 13;
6717 refstr = got_ref_to_str(ref);
6718 if (refstr == NULL)
6719 return got_error_from_errno("got_ref_to_str");
6721 printf("%s%s: %s\n", marker, refname, refstr);
6722 free(refstr);
6723 return NULL;
6726 static const struct got_error *
6727 show_current_branch(struct got_repository *repo, struct got_worktree *worktree)
6729 const char *refname;
6731 if (worktree == NULL)
6732 return got_error(GOT_ERR_NOT_WORKTREE);
6734 refname = got_worktree_get_head_ref_name(worktree);
6736 if (strncmp(refname, "refs/heads/", 11) == 0)
6737 refname += 11;
6738 if (strncmp(refname, "refs/got/worktree/", 18) == 0)
6739 refname += 18;
6741 printf("%s\n", refname);
6743 return NULL;
6746 static const struct got_error *
6747 list_branches(struct got_repository *repo, struct got_worktree *worktree,
6748 int sort_by_time)
6750 static const struct got_error *err = NULL;
6751 struct got_reflist_head refs;
6752 struct got_reflist_entry *re;
6753 struct got_reference *temp_ref = NULL;
6754 int rebase_in_progress, histedit_in_progress;
6756 TAILQ_INIT(&refs);
6758 if (worktree) {
6759 err = got_worktree_rebase_in_progress(&rebase_in_progress,
6760 worktree);
6761 if (err)
6762 return err;
6764 err = got_worktree_histedit_in_progress(&histedit_in_progress,
6765 worktree);
6766 if (err)
6767 return err;
6769 if (rebase_in_progress || histedit_in_progress) {
6770 err = got_ref_open(&temp_ref, repo,
6771 got_worktree_get_head_ref_name(worktree), 0);
6772 if (err)
6773 return err;
6774 list_branch(repo, worktree, temp_ref);
6775 got_ref_close(temp_ref);
6779 err = got_ref_list(&refs, repo, "refs/heads", sort_by_time ?
6780 got_ref_cmp_by_commit_timestamp_descending : got_ref_cmp_by_name,
6781 repo);
6782 if (err)
6783 return err;
6785 TAILQ_FOREACH(re, &refs, entry)
6786 list_branch(repo, worktree, re->ref);
6788 got_ref_list_free(&refs);
6790 err = got_ref_list(&refs, repo, "refs/remotes", sort_by_time ?
6791 got_ref_cmp_by_commit_timestamp_descending : got_ref_cmp_by_name,
6792 repo);
6793 if (err)
6794 return err;
6796 TAILQ_FOREACH(re, &refs, entry)
6797 list_branch(repo, worktree, re->ref);
6799 got_ref_list_free(&refs);
6801 return NULL;
6804 static const struct got_error *
6805 delete_branch(struct got_repository *repo, struct got_worktree *worktree,
6806 const char *branch_name)
6808 const struct got_error *err = NULL;
6809 struct got_reference *ref = NULL;
6810 char *refname, *remote_refname = NULL;
6812 if (strncmp(branch_name, "refs/", 5) == 0)
6813 branch_name += 5;
6814 if (strncmp(branch_name, "heads/", 6) == 0)
6815 branch_name += 6;
6816 else if (strncmp(branch_name, "remotes/", 8) == 0)
6817 branch_name += 8;
6819 if (asprintf(&refname, "refs/heads/%s", branch_name) == -1)
6820 return got_error_from_errno("asprintf");
6822 if (asprintf(&remote_refname, "refs/remotes/%s",
6823 branch_name) == -1) {
6824 err = got_error_from_errno("asprintf");
6825 goto done;
6828 err = got_ref_open(&ref, repo, refname, 0);
6829 if (err) {
6830 const struct got_error *err2;
6831 if (err->code != GOT_ERR_NOT_REF)
6832 goto done;
6834 * Keep 'err' intact such that if neither branch exists
6835 * we report "refs/heads" rather than "refs/remotes" in
6836 * our error message.
6838 err2 = got_ref_open(&ref, repo, remote_refname, 0);
6839 if (err2)
6840 goto done;
6841 err = NULL;
6844 if (worktree &&
6845 strcmp(got_worktree_get_head_ref_name(worktree),
6846 got_ref_get_name(ref)) == 0) {
6847 err = got_error_msg(GOT_ERR_SAME_BRANCH,
6848 "will not delete this work tree's current branch");
6849 goto done;
6852 err = delete_ref(repo, ref);
6853 done:
6854 if (ref)
6855 got_ref_close(ref);
6856 free(refname);
6857 free(remote_refname);
6858 return err;
6861 static const struct got_error *
6862 add_branch(struct got_repository *repo, const char *branch_name,
6863 struct got_object_id *base_commit_id)
6865 const struct got_error *err = NULL;
6866 struct got_reference *ref = NULL;
6867 char *refname = NULL;
6870 * Don't let the user create a branch name with a leading '-'.
6871 * While technically a valid reference name, this case is usually
6872 * an unintended typo.
6874 if (branch_name[0] == '-')
6875 return got_error_path(branch_name, GOT_ERR_REF_NAME_MINUS);
6877 if (strncmp(branch_name, "refs/heads/", 11) == 0)
6878 branch_name += 11;
6880 if (asprintf(&refname, "refs/heads/%s", branch_name) == -1) {
6881 err = got_error_from_errno("asprintf");
6882 goto done;
6885 err = got_ref_open(&ref, repo, refname, 0);
6886 if (err == NULL) {
6887 err = got_error(GOT_ERR_BRANCH_EXISTS);
6888 goto done;
6889 } else if (err->code != GOT_ERR_NOT_REF)
6890 goto done;
6892 err = got_ref_alloc(&ref, refname, base_commit_id);
6893 if (err)
6894 goto done;
6896 err = got_ref_write(ref, repo);
6897 done:
6898 if (ref)
6899 got_ref_close(ref);
6900 free(refname);
6901 return err;
6904 static const struct got_error *
6905 cmd_branch(int argc, char *argv[])
6907 const struct got_error *error = NULL;
6908 struct got_repository *repo = NULL;
6909 struct got_worktree *worktree = NULL;
6910 char *cwd = NULL, *repo_path = NULL;
6911 int ch, do_list = 0, do_show = 0, do_update = 1, sort_by_time = 0;
6912 const char *delref = NULL, *commit_id_arg = NULL;
6913 struct got_reference *ref = NULL;
6914 struct got_pathlist_head paths;
6915 struct got_object_id *commit_id = NULL;
6916 char *commit_id_str = NULL;
6917 int *pack_fds = NULL;
6919 TAILQ_INIT(&paths);
6921 while ((ch = getopt(argc, argv, "c:d:lnr:t")) != -1) {
6922 switch (ch) {
6923 case 'c':
6924 commit_id_arg = optarg;
6925 break;
6926 case 'd':
6927 delref = optarg;
6928 break;
6929 case 'l':
6930 do_list = 1;
6931 break;
6932 case 'n':
6933 do_update = 0;
6934 break;
6935 case 'r':
6936 repo_path = realpath(optarg, NULL);
6937 if (repo_path == NULL)
6938 return got_error_from_errno2("realpath",
6939 optarg);
6940 got_path_strip_trailing_slashes(repo_path);
6941 break;
6942 case 't':
6943 sort_by_time = 1;
6944 break;
6945 default:
6946 usage_branch();
6947 /* NOTREACHED */
6951 if (do_list && delref)
6952 option_conflict('l', 'd');
6953 if (sort_by_time && !do_list)
6954 errx(1, "-t option requires -l option");
6956 argc -= optind;
6957 argv += optind;
6959 if (!do_list && !delref && argc == 0)
6960 do_show = 1;
6962 if ((do_list || delref || do_show) && commit_id_arg != NULL)
6963 errx(1, "-c option can only be used when creating a branch");
6965 if (do_list || delref) {
6966 if (argc > 0)
6967 usage_branch();
6968 } else if (!do_show && argc != 1)
6969 usage_branch();
6971 #ifndef PROFILE
6972 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
6973 "sendfd unveil", NULL) == -1)
6974 err(1, "pledge");
6975 #endif
6976 cwd = getcwd(NULL, 0);
6977 if (cwd == NULL) {
6978 error = got_error_from_errno("getcwd");
6979 goto done;
6982 error = got_repo_pack_fds_open(&pack_fds);
6983 if (error != NULL)
6984 goto done;
6986 if (repo_path == NULL) {
6987 error = got_worktree_open(&worktree, cwd);
6988 if (error && error->code != GOT_ERR_NOT_WORKTREE)
6989 goto done;
6990 else
6991 error = NULL;
6992 if (worktree) {
6993 repo_path =
6994 strdup(got_worktree_get_repo_path(worktree));
6995 if (repo_path == NULL)
6996 error = got_error_from_errno("strdup");
6997 if (error)
6998 goto done;
6999 } else {
7000 repo_path = strdup(cwd);
7001 if (repo_path == NULL) {
7002 error = got_error_from_errno("strdup");
7003 goto done;
7008 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
7009 if (error != NULL)
7010 goto done;
7012 #ifndef PROFILE
7013 if (do_list || do_show) {
7014 /* Remove "cpath" promise. */
7015 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
7016 NULL) == -1)
7017 err(1, "pledge");
7019 #endif
7021 error = apply_unveil(got_repo_get_path(repo), do_list,
7022 worktree ? got_worktree_get_root_path(worktree) : NULL);
7023 if (error)
7024 goto done;
7026 if (do_show)
7027 error = show_current_branch(repo, worktree);
7028 else if (do_list)
7029 error = list_branches(repo, worktree, sort_by_time);
7030 else if (delref)
7031 error = delete_branch(repo, worktree, delref);
7032 else {
7033 struct got_reflist_head refs;
7034 TAILQ_INIT(&refs);
7035 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
7036 NULL);
7037 if (error)
7038 goto done;
7039 if (commit_id_arg == NULL)
7040 commit_id_arg = worktree ?
7041 got_worktree_get_head_ref_name(worktree) :
7042 GOT_REF_HEAD;
7043 error = got_repo_match_object_id(&commit_id, NULL,
7044 commit_id_arg, GOT_OBJ_TYPE_COMMIT, &refs, repo);
7045 got_ref_list_free(&refs);
7046 if (error)
7047 goto done;
7048 error = add_branch(repo, argv[0], commit_id);
7049 if (error)
7050 goto done;
7051 if (worktree && do_update) {
7052 struct got_update_progress_arg upa;
7053 char *branch_refname = NULL;
7055 error = got_object_id_str(&commit_id_str, commit_id);
7056 if (error)
7057 goto done;
7058 error = get_worktree_paths_from_argv(&paths, 0, NULL,
7059 worktree);
7060 if (error)
7061 goto done;
7062 if (asprintf(&branch_refname, "refs/heads/%s", argv[0])
7063 == -1) {
7064 error = got_error_from_errno("asprintf");
7065 goto done;
7067 error = got_ref_open(&ref, repo, branch_refname, 0);
7068 free(branch_refname);
7069 if (error)
7070 goto done;
7071 error = switch_head_ref(ref, commit_id, worktree,
7072 repo);
7073 if (error)
7074 goto done;
7075 error = got_worktree_set_base_commit_id(worktree, repo,
7076 commit_id);
7077 if (error)
7078 goto done;
7079 memset(&upa, 0, sizeof(upa));
7080 error = got_worktree_checkout_files(worktree, &paths,
7081 repo, update_progress, &upa, check_cancelled,
7082 NULL);
7083 if (error)
7084 goto done;
7085 if (upa.did_something) {
7086 printf("Updated to %s: %s\n",
7087 got_worktree_get_head_ref_name(worktree),
7088 commit_id_str);
7090 print_update_progress_stats(&upa);
7093 done:
7094 if (ref)
7095 got_ref_close(ref);
7096 if (repo) {
7097 const struct got_error *close_err = got_repo_close(repo);
7098 if (error == NULL)
7099 error = close_err;
7101 if (worktree)
7102 got_worktree_close(worktree);
7103 if (pack_fds) {
7104 const struct got_error *pack_err =
7105 got_repo_pack_fds_close(pack_fds);
7106 if (error == NULL)
7107 error = pack_err;
7109 free(cwd);
7110 free(repo_path);
7111 free(commit_id);
7112 free(commit_id_str);
7113 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
7114 return error;
7118 __dead static void
7119 usage_tag(void)
7121 fprintf(stderr, "usage: %s tag [-lVv] [-c commit] [-m message] "
7122 "[-r repository-path] [-s signer-id] name\n", getprogname());
7123 exit(1);
7126 #if 0
7127 static const struct got_error *
7128 sort_tags(struct got_reflist_head *sorted, struct got_reflist_head *tags)
7130 const struct got_error *err = NULL;
7131 struct got_reflist_entry *re, *se, *new;
7132 struct got_object_id *re_id, *se_id;
7133 struct got_tag_object *re_tag, *se_tag;
7134 time_t re_time, se_time;
7136 STAILQ_FOREACH(re, tags, entry) {
7137 se = STAILQ_FIRST(sorted);
7138 if (se == NULL) {
7139 err = got_reflist_entry_dup(&new, re);
7140 if (err)
7141 return err;
7142 STAILQ_INSERT_HEAD(sorted, new, entry);
7143 continue;
7144 } else {
7145 err = got_ref_resolve(&re_id, repo, re->ref);
7146 if (err)
7147 break;
7148 err = got_object_open_as_tag(&re_tag, repo, re_id);
7149 free(re_id);
7150 if (err)
7151 break;
7152 re_time = got_object_tag_get_tagger_time(re_tag);
7153 got_object_tag_close(re_tag);
7156 while (se) {
7157 err = got_ref_resolve(&se_id, repo, re->ref);
7158 if (err)
7159 break;
7160 err = got_object_open_as_tag(&se_tag, repo, se_id);
7161 free(se_id);
7162 if (err)
7163 break;
7164 se_time = got_object_tag_get_tagger_time(se_tag);
7165 got_object_tag_close(se_tag);
7167 if (se_time > re_time) {
7168 err = got_reflist_entry_dup(&new, re);
7169 if (err)
7170 return err;
7171 STAILQ_INSERT_AFTER(sorted, se, new, entry);
7172 break;
7174 se = STAILQ_NEXT(se, entry);
7175 continue;
7178 done:
7179 return err;
7181 #endif
7183 static const struct got_error *
7184 get_tag_refname(char **refname, const char *tag_name)
7186 const struct got_error *err;
7188 if (strncmp("refs/tags/", tag_name, 10) == 0) {
7189 *refname = strdup(tag_name);
7190 if (*refname == NULL)
7191 return got_error_from_errno("strdup");
7192 } else if (asprintf(refname, "refs/tags/%s", tag_name) == -1) {
7193 err = got_error_from_errno("asprintf");
7194 *refname = NULL;
7195 return err;
7198 return NULL;
7201 static const struct got_error *
7202 list_tags(struct got_repository *repo, const char *tag_name, int verify_tags,
7203 const char *allowed_signers, const char *revoked_signers, int verbosity)
7205 static const struct got_error *err = NULL;
7206 struct got_reflist_head refs;
7207 struct got_reflist_entry *re;
7208 char *wanted_refname = NULL;
7209 int bad_sigs = 0;
7211 TAILQ_INIT(&refs);
7213 err = got_ref_list(&refs, repo, "refs/tags", got_ref_cmp_tags, repo);
7214 if (err)
7215 return err;
7217 if (tag_name) {
7218 struct got_reference *ref;
7219 err = get_tag_refname(&wanted_refname, tag_name);
7220 if (err)
7221 goto done;
7222 /* Wanted tag reference should exist. */
7223 err = got_ref_open(&ref, repo, wanted_refname, 0);
7224 if (err)
7225 goto done;
7226 got_ref_close(ref);
7229 TAILQ_FOREACH(re, &refs, entry) {
7230 const char *refname;
7231 char *refstr, *tagmsg0, *tagmsg, *line, *id_str, *datestr;
7232 char datebuf[26];
7233 const char *tagger, *ssh_sig = NULL;
7234 char *sig_msg = NULL;
7235 time_t tagger_time;
7236 struct got_object_id *id;
7237 struct got_tag_object *tag;
7238 struct got_commit_object *commit = NULL;
7240 refname = got_ref_get_name(re->ref);
7241 if (strncmp(refname, "refs/tags/", 10) != 0 ||
7242 (wanted_refname && strcmp(refname, wanted_refname) != 0))
7243 continue;
7244 refname += 10;
7245 refstr = got_ref_to_str(re->ref);
7246 if (refstr == NULL) {
7247 err = got_error_from_errno("got_ref_to_str");
7248 break;
7251 err = got_ref_resolve(&id, repo, re->ref);
7252 if (err)
7253 break;
7254 err = got_object_open_as_tag(&tag, repo, id);
7255 if (err) {
7256 if (err->code != GOT_ERR_OBJ_TYPE) {
7257 free(id);
7258 break;
7260 /* "lightweight" tag */
7261 err = got_object_open_as_commit(&commit, repo, id);
7262 if (err) {
7263 free(id);
7264 break;
7266 tagger = got_object_commit_get_committer(commit);
7267 tagger_time =
7268 got_object_commit_get_committer_time(commit);
7269 err = got_object_id_str(&id_str, id);
7270 free(id);
7271 if (err)
7272 break;
7273 } else {
7274 free(id);
7275 tagger = got_object_tag_get_tagger(tag);
7276 tagger_time = got_object_tag_get_tagger_time(tag);
7277 err = got_object_id_str(&id_str,
7278 got_object_tag_get_object_id(tag));
7279 if (err)
7280 break;
7283 if (tag && verify_tags) {
7284 ssh_sig = got_sigs_get_tagmsg_ssh_signature(
7285 got_object_tag_get_message(tag));
7286 if (ssh_sig && allowed_signers == NULL) {
7287 err = got_error_msg(
7288 GOT_ERR_VERIFY_TAG_SIGNATURE,
7289 "SSH signature verification requires "
7290 "setting allowed_signers in "
7291 "got.conf(5)");
7292 break;
7296 printf("%stag %s %s\n", GOT_COMMIT_SEP_STR, refname, refstr);
7297 free(refstr);
7298 printf("from: %s\n", tagger);
7299 datestr = get_datestr(&tagger_time, datebuf);
7300 if (datestr)
7301 printf("date: %s UTC\n", datestr);
7302 if (commit)
7303 printf("object: %s %s\n", GOT_OBJ_LABEL_COMMIT, id_str);
7304 else {
7305 switch (got_object_tag_get_object_type(tag)) {
7306 case GOT_OBJ_TYPE_BLOB:
7307 printf("object: %s %s\n", GOT_OBJ_LABEL_BLOB,
7308 id_str);
7309 break;
7310 case GOT_OBJ_TYPE_TREE:
7311 printf("object: %s %s\n", GOT_OBJ_LABEL_TREE,
7312 id_str);
7313 break;
7314 case GOT_OBJ_TYPE_COMMIT:
7315 printf("object: %s %s\n", GOT_OBJ_LABEL_COMMIT,
7316 id_str);
7317 break;
7318 case GOT_OBJ_TYPE_TAG:
7319 printf("object: %s %s\n", GOT_OBJ_LABEL_TAG,
7320 id_str);
7321 break;
7322 default:
7323 break;
7326 free(id_str);
7328 if (ssh_sig) {
7329 err = got_sigs_verify_tag_ssh(&sig_msg, tag, ssh_sig,
7330 allowed_signers, revoked_signers, verbosity);
7331 if (err && err->code == GOT_ERR_BAD_TAG_SIGNATURE)
7332 bad_sigs = 1;
7333 else if (err)
7334 break;
7335 printf("signature: %s", sig_msg);
7336 free(sig_msg);
7337 sig_msg = NULL;
7340 if (commit) {
7341 err = got_object_commit_get_logmsg(&tagmsg0, commit);
7342 if (err)
7343 break;
7344 got_object_commit_close(commit);
7345 } else {
7346 tagmsg0 = strdup(got_object_tag_get_message(tag));
7347 got_object_tag_close(tag);
7348 if (tagmsg0 == NULL) {
7349 err = got_error_from_errno("strdup");
7350 break;
7354 tagmsg = tagmsg0;
7355 do {
7356 line = strsep(&tagmsg, "\n");
7357 if (line)
7358 printf(" %s\n", line);
7359 } while (line);
7360 free(tagmsg0);
7362 done:
7363 got_ref_list_free(&refs);
7364 free(wanted_refname);
7366 if (err == NULL && bad_sigs)
7367 err = got_error(GOT_ERR_BAD_TAG_SIGNATURE);
7368 return err;
7371 static const struct got_error *
7372 get_tag_message(char **tagmsg, char **tagmsg_path, const char *commit_id_str,
7373 const char *tag_name, const char *repo_path)
7375 const struct got_error *err = NULL;
7376 char *template = NULL, *initial_content = NULL;
7377 char *editor = NULL;
7378 int initial_content_len;
7379 int fd = -1;
7381 if (asprintf(&template, GOT_TMPDIR_STR "/got-tagmsg") == -1) {
7382 err = got_error_from_errno("asprintf");
7383 goto done;
7386 initial_content_len = asprintf(&initial_content,
7387 "\n# tagging commit %s as %s\n",
7388 commit_id_str, tag_name);
7389 if (initial_content_len == -1) {
7390 err = got_error_from_errno("asprintf");
7391 goto done;
7394 err = got_opentemp_named_fd(tagmsg_path, &fd, template, "");
7395 if (err)
7396 goto done;
7398 if (write(fd, initial_content, initial_content_len) == -1) {
7399 err = got_error_from_errno2("write", *tagmsg_path);
7400 goto done;
7403 err = get_editor(&editor);
7404 if (err)
7405 goto done;
7406 err = edit_logmsg(tagmsg, editor, *tagmsg_path, initial_content,
7407 initial_content_len, 1);
7408 done:
7409 free(initial_content);
7410 free(template);
7411 free(editor);
7413 if (fd != -1 && close(fd) == -1 && err == NULL)
7414 err = got_error_from_errno2("close", *tagmsg_path);
7416 if (err) {
7417 free(*tagmsg);
7418 *tagmsg = NULL;
7420 return err;
7423 static const struct got_error *
7424 add_tag(struct got_repository *repo, const char *tagger,
7425 const char *tag_name, const char *commit_arg, const char *tagmsg_arg,
7426 const char *signer_id, int verbosity)
7428 const struct got_error *err = NULL;
7429 struct got_object_id *commit_id = NULL, *tag_id = NULL;
7430 char *label = NULL, *commit_id_str = NULL;
7431 struct got_reference *ref = NULL;
7432 char *refname = NULL, *tagmsg = NULL;
7433 char *tagmsg_path = NULL, *tag_id_str = NULL;
7434 int preserve_tagmsg = 0;
7435 struct got_reflist_head refs;
7437 TAILQ_INIT(&refs);
7440 * Don't let the user create a tag name with a leading '-'.
7441 * While technically a valid reference name, this case is usually
7442 * an unintended typo.
7444 if (tag_name[0] == '-')
7445 return got_error_path(tag_name, GOT_ERR_REF_NAME_MINUS);
7447 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
7448 if (err)
7449 goto done;
7451 err = got_repo_match_object_id(&commit_id, &label, commit_arg,
7452 GOT_OBJ_TYPE_COMMIT, &refs, repo);
7453 if (err)
7454 goto done;
7456 err = got_object_id_str(&commit_id_str, commit_id);
7457 if (err)
7458 goto done;
7460 err = get_tag_refname(&refname, tag_name);
7461 if (err)
7462 goto done;
7463 if (strncmp("refs/tags/", tag_name, 10) == 0)
7464 tag_name += 10;
7466 err = got_ref_open(&ref, repo, refname, 0);
7467 if (err == NULL) {
7468 err = got_error(GOT_ERR_TAG_EXISTS);
7469 goto done;
7470 } else if (err->code != GOT_ERR_NOT_REF)
7471 goto done;
7473 if (tagmsg_arg == NULL) {
7474 err = get_tag_message(&tagmsg, &tagmsg_path, commit_id_str,
7475 tag_name, got_repo_get_path(repo));
7476 if (err) {
7477 if (err->code != GOT_ERR_COMMIT_MSG_EMPTY &&
7478 tagmsg_path != NULL)
7479 preserve_tagmsg = 1;
7480 goto done;
7482 /* Editor is done; we can now apply unveil(2) */
7483 err = got_sigs_apply_unveil();
7484 if (err)
7485 goto done;
7486 err = apply_unveil(got_repo_get_path(repo), 0, NULL);
7487 if (err)
7488 goto done;
7491 err = got_object_tag_create(&tag_id, tag_name, commit_id,
7492 tagger, time(NULL), tagmsg ? tagmsg : tagmsg_arg, signer_id, repo,
7493 verbosity);
7494 if (err) {
7495 if (tagmsg_path)
7496 preserve_tagmsg = 1;
7497 goto done;
7500 err = got_ref_alloc(&ref, refname, tag_id);
7501 if (err) {
7502 if (tagmsg_path)
7503 preserve_tagmsg = 1;
7504 goto done;
7507 err = got_ref_write(ref, repo);
7508 if (err) {
7509 if (tagmsg_path)
7510 preserve_tagmsg = 1;
7511 goto done;
7514 err = got_object_id_str(&tag_id_str, tag_id);
7515 if (err) {
7516 if (tagmsg_path)
7517 preserve_tagmsg = 1;
7518 goto done;
7520 printf("Created tag %s\n", tag_id_str);
7521 done:
7522 if (preserve_tagmsg) {
7523 fprintf(stderr, "%s: tag message preserved in %s\n",
7524 getprogname(), tagmsg_path);
7525 } else if (tagmsg_path && unlink(tagmsg_path) == -1 && err == NULL)
7526 err = got_error_from_errno2("unlink", tagmsg_path);
7527 free(tag_id_str);
7528 if (ref)
7529 got_ref_close(ref);
7530 free(commit_id);
7531 free(commit_id_str);
7532 free(refname);
7533 free(tagmsg);
7534 free(tagmsg_path);
7535 got_ref_list_free(&refs);
7536 return err;
7539 static const struct got_error *
7540 cmd_tag(int argc, char *argv[])
7542 const struct got_error *error = NULL;
7543 struct got_repository *repo = NULL;
7544 struct got_worktree *worktree = NULL;
7545 char *cwd = NULL, *repo_path = NULL, *commit_id_str = NULL;
7546 char *gitconfig_path = NULL, *tagger = NULL;
7547 char *allowed_signers = NULL, *revoked_signers = NULL;
7548 const char *signer_id = NULL;
7549 const char *tag_name = NULL, *commit_id_arg = NULL, *tagmsg = NULL;
7550 int ch, do_list = 0, verify_tags = 0, verbosity = 0;
7551 int *pack_fds = NULL;
7553 while ((ch = getopt(argc, argv, "c:lm:r:s:Vv")) != -1) {
7554 switch (ch) {
7555 case 'c':
7556 commit_id_arg = optarg;
7557 break;
7558 case 'l':
7559 do_list = 1;
7560 break;
7561 case 'm':
7562 tagmsg = optarg;
7563 break;
7564 case 'r':
7565 repo_path = realpath(optarg, NULL);
7566 if (repo_path == NULL) {
7567 error = got_error_from_errno2("realpath",
7568 optarg);
7569 goto done;
7571 got_path_strip_trailing_slashes(repo_path);
7572 break;
7573 case 's':
7574 signer_id = optarg;
7575 break;
7576 case 'V':
7577 verify_tags = 1;
7578 break;
7579 case 'v':
7580 if (verbosity < 0)
7581 verbosity = 0;
7582 else if (verbosity < 3)
7583 verbosity++;
7584 break;
7585 default:
7586 usage_tag();
7587 /* NOTREACHED */
7591 argc -= optind;
7592 argv += optind;
7594 if (do_list || verify_tags) {
7595 if (commit_id_arg != NULL)
7596 errx(1,
7597 "-c option can only be used when creating a tag");
7598 if (tagmsg) {
7599 if (do_list)
7600 option_conflict('l', 'm');
7601 else
7602 option_conflict('V', 'm');
7604 if (signer_id) {
7605 if (do_list)
7606 option_conflict('l', 's');
7607 else
7608 option_conflict('V', 's');
7610 if (argc > 1)
7611 usage_tag();
7612 } else if (argc != 1)
7613 usage_tag();
7615 if (argc == 1)
7616 tag_name = argv[0];
7618 #ifndef PROFILE
7619 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
7620 "sendfd unveil", NULL) == -1)
7621 err(1, "pledge");
7622 #endif
7623 cwd = getcwd(NULL, 0);
7624 if (cwd == NULL) {
7625 error = got_error_from_errno("getcwd");
7626 goto done;
7629 error = got_repo_pack_fds_open(&pack_fds);
7630 if (error != NULL)
7631 goto done;
7633 if (repo_path == NULL) {
7634 error = got_worktree_open(&worktree, cwd);
7635 if (error && error->code != GOT_ERR_NOT_WORKTREE)
7636 goto done;
7637 else
7638 error = NULL;
7639 if (worktree) {
7640 repo_path =
7641 strdup(got_worktree_get_repo_path(worktree));
7642 if (repo_path == NULL)
7643 error = got_error_from_errno("strdup");
7644 if (error)
7645 goto done;
7646 } else {
7647 repo_path = strdup(cwd);
7648 if (repo_path == NULL) {
7649 error = got_error_from_errno("strdup");
7650 goto done;
7655 if (do_list || verify_tags) {
7656 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
7657 if (error != NULL)
7658 goto done;
7659 error = get_allowed_signers(&allowed_signers, repo, worktree);
7660 if (error)
7661 goto done;
7662 error = get_revoked_signers(&revoked_signers, repo, worktree);
7663 if (error)
7664 goto done;
7665 if (worktree) {
7666 /* Release work tree lock. */
7667 got_worktree_close(worktree);
7668 worktree = NULL;
7672 * Remove "cpath" promise unless needed for signature tmpfile
7673 * creation.
7675 if (verify_tags)
7676 got_sigs_apply_unveil();
7677 else {
7678 #ifndef PROFILE
7679 if (pledge("stdio rpath wpath flock proc exec sendfd "
7680 "unveil", NULL) == -1)
7681 err(1, "pledge");
7682 #endif
7684 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
7685 if (error)
7686 goto done;
7687 error = list_tags(repo, tag_name, verify_tags, allowed_signers,
7688 revoked_signers, verbosity);
7689 } else {
7690 error = get_gitconfig_path(&gitconfig_path);
7691 if (error)
7692 goto done;
7693 error = got_repo_open(&repo, repo_path, gitconfig_path,
7694 pack_fds);
7695 if (error != NULL)
7696 goto done;
7698 error = get_author(&tagger, repo, worktree);
7699 if (error)
7700 goto done;
7701 if (signer_id == NULL)
7702 signer_id = get_signer_id(repo, worktree);
7704 if (tagmsg) {
7705 if (signer_id) {
7706 error = got_sigs_apply_unveil();
7707 if (error)
7708 goto done;
7710 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
7711 if (error)
7712 goto done;
7715 if (commit_id_arg == NULL) {
7716 struct got_reference *head_ref;
7717 struct got_object_id *commit_id;
7718 error = got_ref_open(&head_ref, repo,
7719 worktree ? got_worktree_get_head_ref_name(worktree)
7720 : GOT_REF_HEAD, 0);
7721 if (error)
7722 goto done;
7723 error = got_ref_resolve(&commit_id, repo, head_ref);
7724 got_ref_close(head_ref);
7725 if (error)
7726 goto done;
7727 error = got_object_id_str(&commit_id_str, commit_id);
7728 free(commit_id);
7729 if (error)
7730 goto done;
7733 if (worktree) {
7734 /* Release work tree lock. */
7735 got_worktree_close(worktree);
7736 worktree = NULL;
7739 error = add_tag(repo, tagger, tag_name,
7740 commit_id_str ? commit_id_str : commit_id_arg, tagmsg,
7741 signer_id, verbosity);
7743 done:
7744 if (repo) {
7745 const struct got_error *close_err = got_repo_close(repo);
7746 if (error == NULL)
7747 error = close_err;
7749 if (worktree)
7750 got_worktree_close(worktree);
7751 if (pack_fds) {
7752 const struct got_error *pack_err =
7753 got_repo_pack_fds_close(pack_fds);
7754 if (error == NULL)
7755 error = pack_err;
7757 free(cwd);
7758 free(repo_path);
7759 free(gitconfig_path);
7760 free(commit_id_str);
7761 free(tagger);
7762 free(allowed_signers);
7763 free(revoked_signers);
7764 return error;
7767 __dead static void
7768 usage_add(void)
7770 fprintf(stderr, "usage: %s add [-IR] path ...\n", getprogname());
7771 exit(1);
7774 static const struct got_error *
7775 add_progress(void *arg, unsigned char status, const char *path)
7777 while (path[0] == '/')
7778 path++;
7779 printf("%c %s\n", status, path);
7780 return NULL;
7783 static const struct got_error *
7784 cmd_add(int argc, char *argv[])
7786 const struct got_error *error = NULL;
7787 struct got_repository *repo = NULL;
7788 struct got_worktree *worktree = NULL;
7789 char *cwd = NULL;
7790 struct got_pathlist_head paths;
7791 struct got_pathlist_entry *pe;
7792 int ch, can_recurse = 0, no_ignores = 0;
7793 int *pack_fds = NULL;
7795 TAILQ_INIT(&paths);
7797 while ((ch = getopt(argc, argv, "IR")) != -1) {
7798 switch (ch) {
7799 case 'I':
7800 no_ignores = 1;
7801 break;
7802 case 'R':
7803 can_recurse = 1;
7804 break;
7805 default:
7806 usage_add();
7807 /* NOTREACHED */
7811 argc -= optind;
7812 argv += optind;
7814 #ifndef PROFILE
7815 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
7816 NULL) == -1)
7817 err(1, "pledge");
7818 #endif
7819 if (argc < 1)
7820 usage_add();
7822 cwd = getcwd(NULL, 0);
7823 if (cwd == NULL) {
7824 error = got_error_from_errno("getcwd");
7825 goto done;
7828 error = got_repo_pack_fds_open(&pack_fds);
7829 if (error != NULL)
7830 goto done;
7832 error = got_worktree_open(&worktree, cwd);
7833 if (error) {
7834 if (error->code == GOT_ERR_NOT_WORKTREE)
7835 error = wrap_not_worktree_error(error, "add", cwd);
7836 goto done;
7839 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
7840 NULL, pack_fds);
7841 if (error != NULL)
7842 goto done;
7844 error = apply_unveil(got_repo_get_path(repo), 1,
7845 got_worktree_get_root_path(worktree));
7846 if (error)
7847 goto done;
7849 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
7850 if (error)
7851 goto done;
7853 if (!can_recurse) {
7854 char *ondisk_path;
7855 struct stat sb;
7856 TAILQ_FOREACH(pe, &paths, entry) {
7857 if (asprintf(&ondisk_path, "%s/%s",
7858 got_worktree_get_root_path(worktree),
7859 pe->path) == -1) {
7860 error = got_error_from_errno("asprintf");
7861 goto done;
7863 if (lstat(ondisk_path, &sb) == -1) {
7864 if (errno == ENOENT) {
7865 free(ondisk_path);
7866 continue;
7868 error = got_error_from_errno2("lstat",
7869 ondisk_path);
7870 free(ondisk_path);
7871 goto done;
7873 free(ondisk_path);
7874 if (S_ISDIR(sb.st_mode)) {
7875 error = got_error_msg(GOT_ERR_BAD_PATH,
7876 "adding directories requires -R option");
7877 goto done;
7882 error = got_worktree_schedule_add(worktree, &paths, add_progress,
7883 NULL, repo, no_ignores);
7884 done:
7885 if (repo) {
7886 const struct got_error *close_err = got_repo_close(repo);
7887 if (error == NULL)
7888 error = close_err;
7890 if (worktree)
7891 got_worktree_close(worktree);
7892 if (pack_fds) {
7893 const struct got_error *pack_err =
7894 got_repo_pack_fds_close(pack_fds);
7895 if (error == NULL)
7896 error = pack_err;
7898 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
7899 free(cwd);
7900 return error;
7903 __dead static void
7904 usage_remove(void)
7906 fprintf(stderr, "usage: %s remove [-fkR] [-s status-codes] path ...\n",
7907 getprogname());
7908 exit(1);
7911 static const struct got_error *
7912 print_remove_status(void *arg, unsigned char status,
7913 unsigned char staged_status, const char *path)
7915 while (path[0] == '/')
7916 path++;
7917 if (status == GOT_STATUS_NONEXISTENT)
7918 return NULL;
7919 if (status == staged_status && (status == GOT_STATUS_DELETE))
7920 status = GOT_STATUS_NO_CHANGE;
7921 printf("%c%c %s\n", status, staged_status, path);
7922 return NULL;
7925 static const struct got_error *
7926 cmd_remove(int argc, char *argv[])
7928 const struct got_error *error = NULL;
7929 struct got_worktree *worktree = NULL;
7930 struct got_repository *repo = NULL;
7931 const char *status_codes = NULL;
7932 char *cwd = NULL;
7933 struct got_pathlist_head paths;
7934 struct got_pathlist_entry *pe;
7935 int ch, delete_local_mods = 0, can_recurse = 0, keep_on_disk = 0, i;
7936 int ignore_missing_paths = 0;
7937 int *pack_fds = NULL;
7939 TAILQ_INIT(&paths);
7941 while ((ch = getopt(argc, argv, "fkRs:")) != -1) {
7942 switch (ch) {
7943 case 'f':
7944 delete_local_mods = 1;
7945 ignore_missing_paths = 1;
7946 break;
7947 case 'k':
7948 keep_on_disk = 1;
7949 break;
7950 case 'R':
7951 can_recurse = 1;
7952 break;
7953 case 's':
7954 for (i = 0; i < strlen(optarg); i++) {
7955 switch (optarg[i]) {
7956 case GOT_STATUS_MODIFY:
7957 delete_local_mods = 1;
7958 break;
7959 case GOT_STATUS_MISSING:
7960 ignore_missing_paths = 1;
7961 break;
7962 default:
7963 errx(1, "invalid status code '%c'",
7964 optarg[i]);
7967 status_codes = optarg;
7968 break;
7969 default:
7970 usage_remove();
7971 /* NOTREACHED */
7975 argc -= optind;
7976 argv += optind;
7978 #ifndef PROFILE
7979 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
7980 NULL) == -1)
7981 err(1, "pledge");
7982 #endif
7983 if (argc < 1)
7984 usage_remove();
7986 cwd = getcwd(NULL, 0);
7987 if (cwd == NULL) {
7988 error = got_error_from_errno("getcwd");
7989 goto done;
7992 error = got_repo_pack_fds_open(&pack_fds);
7993 if (error != NULL)
7994 goto done;
7996 error = got_worktree_open(&worktree, cwd);
7997 if (error) {
7998 if (error->code == GOT_ERR_NOT_WORKTREE)
7999 error = wrap_not_worktree_error(error, "remove", cwd);
8000 goto done;
8003 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
8004 NULL, pack_fds);
8005 if (error)
8006 goto done;
8008 error = apply_unveil(got_repo_get_path(repo), 1,
8009 got_worktree_get_root_path(worktree));
8010 if (error)
8011 goto done;
8013 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
8014 if (error)
8015 goto done;
8017 if (!can_recurse) {
8018 char *ondisk_path;
8019 struct stat sb;
8020 TAILQ_FOREACH(pe, &paths, entry) {
8021 if (asprintf(&ondisk_path, "%s/%s",
8022 got_worktree_get_root_path(worktree),
8023 pe->path) == -1) {
8024 error = got_error_from_errno("asprintf");
8025 goto done;
8027 if (lstat(ondisk_path, &sb) == -1) {
8028 if (errno == ENOENT) {
8029 free(ondisk_path);
8030 continue;
8032 error = got_error_from_errno2("lstat",
8033 ondisk_path);
8034 free(ondisk_path);
8035 goto done;
8037 free(ondisk_path);
8038 if (S_ISDIR(sb.st_mode)) {
8039 error = got_error_msg(GOT_ERR_BAD_PATH,
8040 "removing directories requires -R option");
8041 goto done;
8046 error = got_worktree_schedule_delete(worktree, &paths,
8047 delete_local_mods, status_codes, print_remove_status, NULL,
8048 repo, keep_on_disk, ignore_missing_paths);
8049 done:
8050 if (repo) {
8051 const struct got_error *close_err = got_repo_close(repo);
8052 if (error == NULL)
8053 error = close_err;
8055 if (worktree)
8056 got_worktree_close(worktree);
8057 if (pack_fds) {
8058 const struct got_error *pack_err =
8059 got_repo_pack_fds_close(pack_fds);
8060 if (error == NULL)
8061 error = pack_err;
8063 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
8064 free(cwd);
8065 return error;
8068 __dead static void
8069 usage_patch(void)
8071 fprintf(stderr, "usage: %s patch [-nR] [-c commit] [-p strip-count] "
8072 "[patchfile]\n", getprogname());
8073 exit(1);
8076 static const struct got_error *
8077 patch_from_stdin(int *patchfd)
8079 const struct got_error *err = NULL;
8080 ssize_t r;
8081 char buf[BUFSIZ];
8082 sig_t sighup, sigint, sigquit;
8084 *patchfd = got_opentempfd();
8085 if (*patchfd == -1)
8086 return got_error_from_errno("got_opentempfd");
8088 sighup = signal(SIGHUP, SIG_DFL);
8089 sigint = signal(SIGINT, SIG_DFL);
8090 sigquit = signal(SIGQUIT, SIG_DFL);
8092 for (;;) {
8093 r = read(0, buf, sizeof(buf));
8094 if (r == -1) {
8095 err = got_error_from_errno("read");
8096 break;
8098 if (r == 0)
8099 break;
8100 if (write(*patchfd, buf, r) == -1) {
8101 err = got_error_from_errno("write");
8102 break;
8106 signal(SIGHUP, sighup);
8107 signal(SIGINT, sigint);
8108 signal(SIGQUIT, sigquit);
8110 if (err == NULL && lseek(*patchfd, 0, SEEK_SET) == -1)
8111 err = got_error_from_errno("lseek");
8113 if (err != NULL) {
8114 close(*patchfd);
8115 *patchfd = -1;
8118 return err;
8121 static const struct got_error *
8122 patch_progress(void *arg, const char *old, const char *new,
8123 unsigned char status, const struct got_error *error, int old_from,
8124 int old_lines, int new_from, int new_lines, int offset,
8125 int ws_mangled, const struct got_error *hunk_err)
8127 const char *path = new == NULL ? old : new;
8129 while (*path == '/')
8130 path++;
8132 if (status != 0)
8133 printf("%c %s\n", status, path);
8135 if (error != NULL)
8136 fprintf(stderr, "%s: %s\n", getprogname(), error->msg);
8138 if (offset != 0 || hunk_err != NULL || ws_mangled) {
8139 printf("@@ -%d,%d +%d,%d @@ ", old_from,
8140 old_lines, new_from, new_lines);
8141 if (hunk_err != NULL)
8142 printf("%s\n", hunk_err->msg);
8143 else if (offset != 0)
8144 printf("applied with offset %d\n", offset);
8145 else
8146 printf("hunk contains mangled whitespace\n");
8149 return NULL;
8152 static const struct got_error *
8153 cmd_patch(int argc, char *argv[])
8155 const struct got_error *error = NULL, *close_error = NULL;
8156 struct got_worktree *worktree = NULL;
8157 struct got_repository *repo = NULL;
8158 struct got_reflist_head refs;
8159 struct got_object_id *commit_id = NULL;
8160 const char *commit_id_str = NULL;
8161 struct stat sb;
8162 const char *errstr;
8163 char *cwd = NULL;
8164 int ch, nop = 0, strip = -1, reverse = 0;
8165 int patchfd;
8166 int *pack_fds = NULL;
8168 TAILQ_INIT(&refs);
8170 #ifndef PROFILE
8171 if (pledge("stdio rpath wpath cpath fattr proc exec sendfd flock "
8172 "unveil", NULL) == -1)
8173 err(1, "pledge");
8174 #endif
8176 while ((ch = getopt(argc, argv, "c:np:R")) != -1) {
8177 switch (ch) {
8178 case 'c':
8179 commit_id_str = optarg;
8180 break;
8181 case 'n':
8182 nop = 1;
8183 break;
8184 case 'p':
8185 strip = strtonum(optarg, 0, INT_MAX, &errstr);
8186 if (errstr != NULL)
8187 errx(1, "pathname strip count is %s: %s",
8188 errstr, optarg);
8189 break;
8190 case 'R':
8191 reverse = 1;
8192 break;
8193 default:
8194 usage_patch();
8195 /* NOTREACHED */
8199 argc -= optind;
8200 argv += optind;
8202 if (argc == 0) {
8203 error = patch_from_stdin(&patchfd);
8204 if (error)
8205 return error;
8206 } else if (argc == 1) {
8207 patchfd = open(argv[0], O_RDONLY);
8208 if (patchfd == -1) {
8209 error = got_error_from_errno2("open", argv[0]);
8210 return error;
8212 if (fstat(patchfd, &sb) == -1) {
8213 error = got_error_from_errno2("fstat", argv[0]);
8214 goto done;
8216 if (!S_ISREG(sb.st_mode)) {
8217 error = got_error_path(argv[0], GOT_ERR_BAD_FILETYPE);
8218 goto done;
8220 } else
8221 usage_patch();
8223 if ((cwd = getcwd(NULL, 0)) == NULL) {
8224 error = got_error_from_errno("getcwd");
8225 goto done;
8228 error = got_repo_pack_fds_open(&pack_fds);
8229 if (error != NULL)
8230 goto done;
8232 error = got_worktree_open(&worktree, cwd);
8233 if (error != NULL)
8234 goto done;
8236 const char *repo_path = got_worktree_get_repo_path(worktree);
8237 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
8238 if (error != NULL)
8239 goto done;
8241 error = apply_unveil(got_repo_get_path(repo), 0,
8242 got_worktree_get_root_path(worktree));
8243 if (error != NULL)
8244 goto done;
8246 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
8247 if (error)
8248 goto done;
8250 if (commit_id_str != NULL) {
8251 error = got_repo_match_object_id(&commit_id, NULL,
8252 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
8253 if (error)
8254 goto done;
8257 error = got_patch(patchfd, worktree, repo, nop, strip, reverse,
8258 commit_id, &patch_progress, NULL, check_cancelled, NULL);
8260 done:
8261 got_ref_list_free(&refs);
8262 free(commit_id);
8263 if (repo) {
8264 close_error = got_repo_close(repo);
8265 if (error == NULL)
8266 error = close_error;
8268 if (worktree != NULL) {
8269 close_error = got_worktree_close(worktree);
8270 if (error == NULL)
8271 error = close_error;
8273 if (pack_fds) {
8274 const struct got_error *pack_err =
8275 got_repo_pack_fds_close(pack_fds);
8276 if (error == NULL)
8277 error = pack_err;
8279 free(cwd);
8280 return error;
8283 __dead static void
8284 usage_revert(void)
8286 fprintf(stderr, "usage: %s revert [-pR] [-F response-script] path ...\n",
8287 getprogname());
8288 exit(1);
8291 static const struct got_error *
8292 revert_progress(void *arg, unsigned char status, const char *path)
8294 if (status == GOT_STATUS_UNVERSIONED)
8295 return NULL;
8297 while (path[0] == '/')
8298 path++;
8299 printf("%c %s\n", status, path);
8300 return NULL;
8303 struct choose_patch_arg {
8304 FILE *patch_script_file;
8305 const char *action;
8308 static const struct got_error *
8309 show_change(unsigned char status, const char *path, FILE *patch_file, int n,
8310 int nchanges, const char *action)
8312 const struct got_error *err;
8313 char *line = NULL;
8314 size_t linesize = 0;
8315 ssize_t linelen;
8317 switch (status) {
8318 case GOT_STATUS_ADD:
8319 printf("A %s\n%s this addition? [y/n] ", path, action);
8320 break;
8321 case GOT_STATUS_DELETE:
8322 printf("D %s\n%s this deletion? [y/n] ", path, action);
8323 break;
8324 case GOT_STATUS_MODIFY:
8325 if (fseek(patch_file, 0L, SEEK_SET) == -1)
8326 return got_error_from_errno("fseek");
8327 printf(GOT_COMMIT_SEP_STR);
8328 while ((linelen = getline(&line, &linesize, patch_file)) != -1)
8329 printf("%s", line);
8330 if (linelen == -1 && ferror(patch_file)) {
8331 err = got_error_from_errno("getline");
8332 free(line);
8333 return err;
8335 free(line);
8336 printf(GOT_COMMIT_SEP_STR);
8337 printf("M %s (change %d of %d)\n%s this change? [y/n/q] ",
8338 path, n, nchanges, action);
8339 break;
8340 default:
8341 return got_error_path(path, GOT_ERR_FILE_STATUS);
8344 fflush(stdout);
8345 return NULL;
8348 static const struct got_error *
8349 choose_patch(int *choice, void *arg, unsigned char status, const char *path,
8350 FILE *patch_file, int n, int nchanges)
8352 const struct got_error *err = NULL;
8353 char *line = NULL;
8354 size_t linesize = 0;
8355 ssize_t linelen;
8356 int resp = ' ';
8357 struct choose_patch_arg *a = arg;
8359 *choice = GOT_PATCH_CHOICE_NONE;
8361 if (a->patch_script_file) {
8362 char *nl;
8363 err = show_change(status, path, patch_file, n, nchanges,
8364 a->action);
8365 if (err)
8366 return err;
8367 linelen = getline(&line, &linesize, a->patch_script_file);
8368 if (linelen == -1) {
8369 if (ferror(a->patch_script_file))
8370 return got_error_from_errno("getline");
8371 return NULL;
8373 nl = strchr(line, '\n');
8374 if (nl)
8375 *nl = '\0';
8376 if (strcmp(line, "y") == 0) {
8377 *choice = GOT_PATCH_CHOICE_YES;
8378 printf("y\n");
8379 } else if (strcmp(line, "n") == 0) {
8380 *choice = GOT_PATCH_CHOICE_NO;
8381 printf("n\n");
8382 } else if (strcmp(line, "q") == 0 &&
8383 status == GOT_STATUS_MODIFY) {
8384 *choice = GOT_PATCH_CHOICE_QUIT;
8385 printf("q\n");
8386 } else
8387 printf("invalid response '%s'\n", line);
8388 free(line);
8389 return NULL;
8392 while (resp != 'y' && resp != 'n' && resp != 'q') {
8393 err = show_change(status, path, patch_file, n, nchanges,
8394 a->action);
8395 if (err)
8396 return err;
8397 resp = getchar();
8398 if (resp == '\n')
8399 resp = getchar();
8400 if (status == GOT_STATUS_MODIFY) {
8401 if (resp != 'y' && resp != 'n' && resp != 'q') {
8402 printf("invalid response '%c'\n", resp);
8403 resp = ' ';
8405 } else if (resp != 'y' && resp != 'n') {
8406 printf("invalid response '%c'\n", resp);
8407 resp = ' ';
8411 if (resp == 'y')
8412 *choice = GOT_PATCH_CHOICE_YES;
8413 else if (resp == 'n')
8414 *choice = GOT_PATCH_CHOICE_NO;
8415 else if (resp == 'q' && status == GOT_STATUS_MODIFY)
8416 *choice = GOT_PATCH_CHOICE_QUIT;
8418 return NULL;
8421 struct wt_commitable_path_arg {
8422 struct got_pathlist_head *commit_paths;
8423 int *has_changes;
8427 * Shortcut work tree status callback to determine if the set of paths scanned
8428 * has at least one versioned path that is being modified and, if not NULL, is
8429 * in the arg->commit_paths list. Set arg and return GOT_ERR_FILE_MODIFIED as
8430 * soon as a path is passed with a status that satisfies this criteria.
8432 static const struct got_error *
8433 worktree_has_commitable_path(void *arg, unsigned char status,
8434 unsigned char staged_status, const char *path,
8435 struct got_object_id *blob_id, struct got_object_id *staged_blob_id,
8436 struct got_object_id *commit_id, int dirfd, const char *de_name)
8438 struct wt_commitable_path_arg *a = arg;
8440 if (status == staged_status && (status == GOT_STATUS_DELETE))
8441 status = GOT_STATUS_NO_CHANGE;
8443 if (!(status == GOT_STATUS_NO_CHANGE ||
8444 status == GOT_STATUS_UNVERSIONED) ||
8445 staged_status != GOT_STATUS_NO_CHANGE) {
8446 if (a->commit_paths != NULL) {
8447 struct got_pathlist_entry *pe;
8449 TAILQ_FOREACH(pe, a->commit_paths, entry) {
8450 if (strncmp(path, pe->path,
8451 pe->path_len) == 0) {
8452 *a->has_changes = 1;
8453 break;
8456 } else
8457 *a->has_changes = 1;
8459 if (*a->has_changes)
8460 return got_error(GOT_ERR_FILE_MODIFIED);
8463 return NULL;
8467 * Check that the changeset of the commit identified by id is
8468 * comprised of at least one modified path that is being committed.
8470 static const struct got_error *
8471 commit_path_changed_in_worktree(struct wt_commitable_path_arg *wcpa,
8472 struct got_object_id *id, struct got_worktree *worktree,
8473 struct got_repository *repo)
8475 const struct got_error *err;
8476 struct got_pathlist_head paths;
8477 struct got_commit_object *commit = NULL, *pcommit = NULL;
8478 struct got_tree_object *tree = NULL, *ptree = NULL;
8479 struct got_object_qid *pid;
8481 TAILQ_INIT(&paths);
8483 err = got_object_open_as_commit(&commit, repo, id);
8484 if (err)
8485 goto done;
8487 err = got_object_open_as_tree(&tree, repo,
8488 got_object_commit_get_tree_id(commit));
8489 if (err)
8490 goto done;
8492 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
8493 if (pid != NULL) {
8494 err = got_object_open_as_commit(&pcommit, repo, &pid->id);
8495 if (err)
8496 goto done;
8498 err = got_object_open_as_tree(&ptree, repo,
8499 got_object_commit_get_tree_id(pcommit));
8500 if (err)
8501 goto done;
8504 err = got_diff_tree(ptree, tree, NULL, NULL, -1, -1, "", "", repo,
8505 got_diff_tree_collect_changed_paths, &paths, 0);
8506 if (err)
8507 goto done;
8509 err = got_worktree_status(worktree, &paths, repo, 0,
8510 worktree_has_commitable_path, wcpa, check_cancelled, NULL);
8511 if (err && err->code == GOT_ERR_FILE_MODIFIED) {
8513 * At least one changed path in the referenced commit is
8514 * modified in the work tree, that's all we need to know!
8516 err = NULL;
8519 done:
8520 got_pathlist_free(&paths, GOT_PATHLIST_FREE_ALL);
8521 if (commit)
8522 got_object_commit_close(commit);
8523 if (pcommit)
8524 got_object_commit_close(pcommit);
8525 if (tree)
8526 got_object_tree_close(tree);
8527 if (ptree)
8528 got_object_tree_close(ptree);
8529 return err;
8533 * Remove any "logmsg" reference comprised entirely of paths that have
8534 * been reverted in this work tree. If any path in the logmsg ref changeset
8535 * remains in a changed state in the worktree, do not remove the reference.
8537 static const struct got_error *
8538 rm_logmsg_ref(struct got_worktree *worktree, struct got_repository *repo)
8540 const struct got_error *err;
8541 struct got_reflist_head refs;
8542 struct got_reflist_entry *re;
8543 struct got_commit_object *commit = NULL;
8544 struct got_object_id *commit_id = NULL;
8545 struct wt_commitable_path_arg wcpa;
8546 char *uuidstr = NULL;
8548 TAILQ_INIT(&refs);
8550 err = got_worktree_get_uuid(&uuidstr, worktree);
8551 if (err)
8552 goto done;
8554 err = got_ref_list(&refs, repo, "refs/got/worktree",
8555 got_ref_cmp_by_name, repo);
8556 if (err)
8557 goto done;
8559 TAILQ_FOREACH(re, &refs, entry) {
8560 const char *refname;
8561 int has_changes = 0;
8563 refname = got_ref_get_name(re->ref);
8565 if (!strncmp(refname, GOT_WORKTREE_CHERRYPICK_REF_PREFIX,
8566 GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN))
8567 refname += GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN + 1;
8568 else if (!strncmp(refname, GOT_WORKTREE_BACKOUT_REF_PREFIX,
8569 GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN))
8570 refname += GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN + 1;
8571 else
8572 continue;
8574 if (strncmp(refname, uuidstr, GOT_WORKTREE_UUID_STRLEN) == 0)
8575 refname += GOT_WORKTREE_UUID_STRLEN + 1; /* skip '-' */
8576 else
8577 continue;
8579 err = got_repo_match_object_id(&commit_id, NULL, refname,
8580 GOT_OBJ_TYPE_COMMIT, NULL, repo);
8581 if (err)
8582 goto done;
8584 err = got_object_open_as_commit(&commit, repo, commit_id);
8585 if (err)
8586 goto done;
8588 wcpa.commit_paths = NULL;
8589 wcpa.has_changes = &has_changes;
8591 err = commit_path_changed_in_worktree(&wcpa, commit_id,
8592 worktree, repo);
8593 if (err)
8594 goto done;
8596 if (!has_changes) {
8597 err = got_ref_delete(re->ref, repo);
8598 if (err)
8599 goto done;
8602 got_object_commit_close(commit);
8603 commit = NULL;
8604 free(commit_id);
8605 commit_id = NULL;
8608 done:
8609 free(uuidstr);
8610 free(commit_id);
8611 got_ref_list_free(&refs);
8612 if (commit)
8613 got_object_commit_close(commit);
8614 return err;
8617 static const struct got_error *
8618 cmd_revert(int argc, char *argv[])
8620 const struct got_error *error = NULL;
8621 struct got_worktree *worktree = NULL;
8622 struct got_repository *repo = NULL;
8623 char *cwd = NULL, *path = NULL;
8624 struct got_pathlist_head paths;
8625 struct got_pathlist_entry *pe;
8626 int ch, can_recurse = 0, pflag = 0;
8627 FILE *patch_script_file = NULL;
8628 const char *patch_script_path = NULL;
8629 struct choose_patch_arg cpa;
8630 int *pack_fds = NULL;
8632 TAILQ_INIT(&paths);
8634 while ((ch = getopt(argc, argv, "F:pR")) != -1) {
8635 switch (ch) {
8636 case 'F':
8637 patch_script_path = optarg;
8638 break;
8639 case 'p':
8640 pflag = 1;
8641 break;
8642 case 'R':
8643 can_recurse = 1;
8644 break;
8645 default:
8646 usage_revert();
8647 /* NOTREACHED */
8651 argc -= optind;
8652 argv += optind;
8654 #ifndef PROFILE
8655 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
8656 "unveil", NULL) == -1)
8657 err(1, "pledge");
8658 #endif
8659 if (argc < 1)
8660 usage_revert();
8661 if (patch_script_path && !pflag)
8662 errx(1, "-F option can only be used together with -p option");
8664 cwd = getcwd(NULL, 0);
8665 if (cwd == NULL) {
8666 error = got_error_from_errno("getcwd");
8667 goto done;
8670 error = got_repo_pack_fds_open(&pack_fds);
8671 if (error != NULL)
8672 goto done;
8674 error = got_worktree_open(&worktree, cwd);
8675 if (error) {
8676 if (error->code == GOT_ERR_NOT_WORKTREE)
8677 error = wrap_not_worktree_error(error, "revert", cwd);
8678 goto done;
8681 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
8682 NULL, pack_fds);
8683 if (error != NULL)
8684 goto done;
8686 if (patch_script_path) {
8687 patch_script_file = fopen(patch_script_path, "re");
8688 if (patch_script_file == NULL) {
8689 error = got_error_from_errno2("fopen",
8690 patch_script_path);
8691 goto done;
8696 * XXX "c" perm needed on repo dir to delete merge references.
8698 error = apply_unveil(got_repo_get_path(repo), 0,
8699 got_worktree_get_root_path(worktree));
8700 if (error)
8701 goto done;
8703 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
8704 if (error)
8705 goto done;
8707 if (!can_recurse) {
8708 char *ondisk_path;
8709 struct stat sb;
8710 TAILQ_FOREACH(pe, &paths, entry) {
8711 if (asprintf(&ondisk_path, "%s/%s",
8712 got_worktree_get_root_path(worktree),
8713 pe->path) == -1) {
8714 error = got_error_from_errno("asprintf");
8715 goto done;
8717 if (lstat(ondisk_path, &sb) == -1) {
8718 if (errno == ENOENT) {
8719 free(ondisk_path);
8720 continue;
8722 error = got_error_from_errno2("lstat",
8723 ondisk_path);
8724 free(ondisk_path);
8725 goto done;
8727 free(ondisk_path);
8728 if (S_ISDIR(sb.st_mode)) {
8729 error = got_error_msg(GOT_ERR_BAD_PATH,
8730 "reverting directories requires -R option");
8731 goto done;
8736 cpa.patch_script_file = patch_script_file;
8737 cpa.action = "revert";
8738 error = got_worktree_revert(worktree, &paths, revert_progress, NULL,
8739 pflag ? choose_patch : NULL, &cpa, repo);
8741 error = rm_logmsg_ref(worktree, repo);
8742 done:
8743 if (patch_script_file && fclose(patch_script_file) == EOF &&
8744 error == NULL)
8745 error = got_error_from_errno2("fclose", patch_script_path);
8746 if (repo) {
8747 const struct got_error *close_err = got_repo_close(repo);
8748 if (error == NULL)
8749 error = close_err;
8751 if (worktree)
8752 got_worktree_close(worktree);
8753 if (pack_fds) {
8754 const struct got_error *pack_err =
8755 got_repo_pack_fds_close(pack_fds);
8756 if (error == NULL)
8757 error = pack_err;
8759 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
8760 free(path);
8761 free(cwd);
8762 return error;
8765 __dead static void
8766 usage_commit(void)
8768 fprintf(stderr, "usage: %s commit [-NS] [-A author] [-F path] "
8769 "[-m message] [path ...]\n", getprogname());
8770 exit(1);
8773 struct collect_commit_logmsg_arg {
8774 const char *cmdline_log;
8775 const char *prepared_log;
8776 const char *merged_log;
8777 int non_interactive;
8778 const char *editor;
8779 const char *worktree_path;
8780 const char *branch_name;
8781 const char *repo_path;
8782 char *logmsg_path;
8786 static const struct got_error *
8787 read_prepared_logmsg(char **logmsg, const char *path)
8789 const struct got_error *err = NULL;
8790 FILE *f = NULL;
8791 struct stat sb;
8792 size_t r;
8794 *logmsg = NULL;
8795 memset(&sb, 0, sizeof(sb));
8797 f = fopen(path, "re");
8798 if (f == NULL)
8799 return got_error_from_errno2("fopen", path);
8801 if (fstat(fileno(f), &sb) == -1) {
8802 err = got_error_from_errno2("fstat", path);
8803 goto done;
8805 if (sb.st_size == 0) {
8806 err = got_error(GOT_ERR_COMMIT_MSG_EMPTY);
8807 goto done;
8810 *logmsg = malloc(sb.st_size + 1);
8811 if (*logmsg == NULL) {
8812 err = got_error_from_errno("malloc");
8813 goto done;
8816 r = fread(*logmsg, 1, sb.st_size, f);
8817 if (r != sb.st_size) {
8818 if (ferror(f))
8819 err = got_error_from_errno2("fread", path);
8820 else
8821 err = got_error(GOT_ERR_IO);
8822 goto done;
8824 (*logmsg)[sb.st_size] = '\0';
8825 done:
8826 if (fclose(f) == EOF && err == NULL)
8827 err = got_error_from_errno2("fclose", path);
8828 if (err) {
8829 free(*logmsg);
8830 *logmsg = NULL;
8832 return err;
8835 static const struct got_error *
8836 collect_commit_logmsg(struct got_pathlist_head *commitable_paths,
8837 const char *diff_path, char **logmsg, void *arg)
8839 char *initial_content = NULL;
8840 struct got_pathlist_entry *pe;
8841 const struct got_error *err = NULL;
8842 char *template = NULL;
8843 char *prepared_msg = NULL, *merged_msg = NULL;
8844 struct collect_commit_logmsg_arg *a = arg;
8845 int initial_content_len;
8846 int fd = -1;
8847 size_t len;
8849 /* if a message was specified on the command line, just use it */
8850 if (a->cmdline_log != NULL && strlen(a->cmdline_log) != 0) {
8851 len = strlen(a->cmdline_log) + 1;
8852 *logmsg = malloc(len + 1);
8853 if (*logmsg == NULL)
8854 return got_error_from_errno("malloc");
8855 strlcpy(*logmsg, a->cmdline_log, len);
8856 return NULL;
8857 } else if (a->prepared_log != NULL && a->non_interactive)
8858 return read_prepared_logmsg(logmsg, a->prepared_log);
8860 if (asprintf(&template, "%s/logmsg", a->worktree_path) == -1)
8861 return got_error_from_errno("asprintf");
8863 err = got_opentemp_named_fd(&a->logmsg_path, &fd, template, "");
8864 if (err)
8865 goto done;
8867 if (a->prepared_log) {
8868 err = read_prepared_logmsg(&prepared_msg, a->prepared_log);
8869 if (err)
8870 goto done;
8871 } else if (a->merged_log) {
8872 err = read_prepared_logmsg(&merged_msg, a->merged_log);
8873 if (err)
8874 goto done;
8877 initial_content_len = asprintf(&initial_content,
8878 "%s%s\n# changes to be committed on branch %s:\n",
8879 prepared_msg ? prepared_msg : "",
8880 merged_msg ? merged_msg : "", a->branch_name);
8881 if (initial_content_len == -1) {
8882 err = got_error_from_errno("asprintf");
8883 goto done;
8886 if (write(fd, initial_content, initial_content_len) == -1) {
8887 err = got_error_from_errno2("write", a->logmsg_path);
8888 goto done;
8891 TAILQ_FOREACH(pe, commitable_paths, entry) {
8892 struct got_commitable *ct = pe->data;
8893 dprintf(fd, "# %c %s\n",
8894 got_commitable_get_status(ct),
8895 got_commitable_get_path(ct));
8898 if (diff_path) {
8899 dprintf(fd, "# detailed changes can be viewed in %s\n",
8900 diff_path);
8903 err = edit_logmsg(logmsg, a->editor, a->logmsg_path, initial_content,
8904 initial_content_len, a->prepared_log ? 0 : 1);
8905 done:
8906 free(initial_content);
8907 free(template);
8908 free(prepared_msg);
8909 free(merged_msg);
8911 if (fd != -1 && close(fd) == -1 && err == NULL)
8912 err = got_error_from_errno2("close", a->logmsg_path);
8914 /* Editor is done; we can now apply unveil(2) */
8915 if (err == NULL)
8916 err = apply_unveil(a->repo_path, 0, a->worktree_path);
8917 if (err) {
8918 free(*logmsg);
8919 *logmsg = NULL;
8921 return err;
8924 static const struct got_error *
8925 cat_logmsg(FILE *f, struct got_commit_object *commit, const char *idstr,
8926 const char *type, int has_content)
8928 const struct got_error *err = NULL;
8929 char *logmsg = NULL;
8931 err = got_object_commit_get_logmsg(&logmsg, commit);
8932 if (err)
8933 return err;
8935 if (fprintf(f, "%s# log message of %s commit %s:%s",
8936 has_content ? "\n" : "", type, idstr, logmsg) < 0)
8937 err = got_ferror(f, GOT_ERR_IO);
8939 free(logmsg);
8940 return err;
8944 * Lookup "logmsg" references of backed-out and cherrypicked commits
8945 * belonging to the current work tree. If found, and the worktree has
8946 * at least one modified file that was changed in the referenced commit,
8947 * add its log message to a new temporary file at *logmsg_path.
8948 * Add all refs found to matched_refs to be scheduled for removal on
8949 * successful commit.
8951 static const struct got_error *
8952 lookup_logmsg_ref(char **logmsg_path, struct got_pathlist_head *paths,
8953 struct got_reflist_head *matched_refs, struct got_worktree *worktree,
8954 struct got_repository *repo)
8956 const struct got_error *err;
8957 struct got_commit_object *commit = NULL;
8958 struct got_object_id *id = NULL;
8959 struct got_reflist_head refs;
8960 struct got_reflist_entry *re, *re_match;
8961 FILE *f = NULL;
8962 char *uuidstr = NULL;
8963 int added_logmsg = 0;
8965 TAILQ_INIT(&refs);
8967 *logmsg_path = NULL;
8969 err = got_worktree_get_uuid(&uuidstr, worktree);
8970 if (err)
8971 goto done;
8973 err = got_ref_list(&refs, repo, "refs/got/worktree",
8974 got_ref_cmp_by_name, repo);
8975 if (err)
8976 goto done;
8978 TAILQ_FOREACH(re, &refs, entry) {
8979 const char *refname, *type;
8980 struct wt_commitable_path_arg wcpa;
8981 int add_logmsg = 0;
8983 refname = got_ref_get_name(re->ref);
8985 if (strncmp(refname, GOT_WORKTREE_CHERRYPICK_REF_PREFIX,
8986 GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN) == 0) {
8987 refname += GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN + 1;
8988 type = "cherrypicked";
8989 } else if (strncmp(refname, GOT_WORKTREE_BACKOUT_REF_PREFIX,
8990 GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN) == 0) {
8991 refname += GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN + 1;
8992 type = "backed-out";
8993 } else
8994 continue;
8996 if (strncmp(refname, uuidstr, GOT_WORKTREE_UUID_STRLEN) == 0)
8997 refname += GOT_WORKTREE_UUID_STRLEN + 1; /* skip '-' */
8998 else
8999 continue;
9001 err = got_repo_match_object_id(&id, NULL, refname,
9002 GOT_OBJ_TYPE_COMMIT, NULL, repo);
9003 if (err)
9004 goto done;
9006 err = got_object_open_as_commit(&commit, repo, id);
9007 if (err)
9008 goto done;
9010 wcpa.commit_paths = paths;
9011 wcpa.has_changes = &add_logmsg;
9013 err = commit_path_changed_in_worktree(&wcpa, id,
9014 worktree, repo);
9015 if (err)
9016 goto done;
9018 if (add_logmsg) {
9019 if (f == NULL) {
9020 err = got_opentemp_named(logmsg_path, &f,
9021 "got-commit-logmsg", "");
9022 if (err)
9023 goto done;
9025 err = cat_logmsg(f, commit, refname, type,
9026 added_logmsg);
9027 if (err)
9028 goto done;
9029 if (!added_logmsg)
9030 ++added_logmsg;
9032 err = got_reflist_entry_dup(&re_match, re);
9033 if (err)
9034 goto done;
9035 TAILQ_INSERT_HEAD(matched_refs, re_match, entry);
9038 got_object_commit_close(commit);
9039 commit = NULL;
9040 free(id);
9041 id = NULL;
9044 done:
9045 free(id);
9046 free(uuidstr);
9047 got_ref_list_free(&refs);
9048 if (commit)
9049 got_object_commit_close(commit);
9050 if (f && fclose(f) == EOF && err == NULL)
9051 err = got_error_from_errno("fclose");
9052 if (!added_logmsg) {
9053 if (*logmsg_path && unlink(*logmsg_path) != 0 && err == NULL)
9054 err = got_error_from_errno2("unlink", *logmsg_path);
9055 *logmsg_path = NULL;
9057 return err;
9060 static const struct got_error *
9061 cmd_commit(int argc, char *argv[])
9063 const struct got_error *error = NULL;
9064 struct got_worktree *worktree = NULL;
9065 struct got_repository *repo = NULL;
9066 char *cwd = NULL, *id_str = NULL;
9067 struct got_object_id *id = NULL;
9068 const char *logmsg = NULL;
9069 char *prepared_logmsg = NULL, *merged_logmsg = NULL;
9070 struct collect_commit_logmsg_arg cl_arg;
9071 const char *author = NULL;
9072 char *gitconfig_path = NULL, *editor = NULL, *committer = NULL;
9073 int ch, rebase_in_progress, histedit_in_progress, preserve_logmsg = 0;
9074 int allow_bad_symlinks = 0, non_interactive = 0, merge_in_progress = 0;
9075 int show_diff = 1;
9076 struct got_pathlist_head paths;
9077 struct got_reflist_head refs;
9078 struct got_reflist_entry *re;
9079 int *pack_fds = NULL;
9081 TAILQ_INIT(&refs);
9082 TAILQ_INIT(&paths);
9083 cl_arg.logmsg_path = NULL;
9085 while ((ch = getopt(argc, argv, "A:F:m:NnS")) != -1) {
9086 switch (ch) {
9087 case 'A':
9088 author = optarg;
9089 error = valid_author(author);
9090 if (error)
9091 return error;
9092 break;
9093 case 'F':
9094 if (logmsg != NULL)
9095 option_conflict('F', 'm');
9096 prepared_logmsg = realpath(optarg, NULL);
9097 if (prepared_logmsg == NULL)
9098 return got_error_from_errno2("realpath",
9099 optarg);
9100 break;
9101 case 'm':
9102 if (prepared_logmsg)
9103 option_conflict('m', 'F');
9104 logmsg = optarg;
9105 break;
9106 case 'N':
9107 non_interactive = 1;
9108 break;
9109 case 'n':
9110 show_diff = 0;
9111 break;
9112 case 'S':
9113 allow_bad_symlinks = 1;
9114 break;
9115 default:
9116 usage_commit();
9117 /* NOTREACHED */
9121 argc -= optind;
9122 argv += optind;
9124 #ifndef PROFILE
9125 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
9126 "unveil", NULL) == -1)
9127 err(1, "pledge");
9128 #endif
9129 cwd = getcwd(NULL, 0);
9130 if (cwd == NULL) {
9131 error = got_error_from_errno("getcwd");
9132 goto done;
9135 error = got_repo_pack_fds_open(&pack_fds);
9136 if (error != NULL)
9137 goto done;
9139 error = got_worktree_open(&worktree, cwd);
9140 if (error) {
9141 if (error->code == GOT_ERR_NOT_WORKTREE)
9142 error = wrap_not_worktree_error(error, "commit", cwd);
9143 goto done;
9146 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
9147 if (error)
9148 goto done;
9149 if (rebase_in_progress) {
9150 error = got_error(GOT_ERR_REBASING);
9151 goto done;
9154 error = got_worktree_histedit_in_progress(&histedit_in_progress,
9155 worktree);
9156 if (error)
9157 goto done;
9159 error = get_gitconfig_path(&gitconfig_path);
9160 if (error)
9161 goto done;
9162 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
9163 gitconfig_path, pack_fds);
9164 if (error != NULL)
9165 goto done;
9167 error = got_worktree_merge_in_progress(&merge_in_progress, worktree, repo);
9168 if (error)
9169 goto done;
9170 if (merge_in_progress) {
9171 error = got_error(GOT_ERR_MERGE_BUSY);
9172 goto done;
9175 error = get_author(&committer, repo, worktree);
9176 if (error)
9177 goto done;
9179 if (author != NULL && !strcmp(committer, author)) {
9180 error = got_error(GOT_ERR_COMMIT_REDUNDANT_AUTHOR);
9181 goto done;
9184 if (author == NULL)
9185 author = committer;
9188 * unveil(2) traverses exec(2); if an editor is used we have
9189 * to apply unveil after the log message has been written.
9191 if (logmsg == NULL || strlen(logmsg) == 0)
9192 error = get_editor(&editor);
9193 else
9194 error = apply_unveil(got_repo_get_path(repo), 0,
9195 got_worktree_get_root_path(worktree));
9196 if (error)
9197 goto done;
9199 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
9200 if (error)
9201 goto done;
9203 if (prepared_logmsg == NULL) {
9204 error = lookup_logmsg_ref(&merged_logmsg,
9205 argc > 0 ? &paths : NULL, &refs, worktree, repo);
9206 if (error)
9207 goto done;
9210 cl_arg.editor = editor;
9211 cl_arg.cmdline_log = logmsg;
9212 cl_arg.prepared_log = prepared_logmsg;
9213 cl_arg.merged_log = merged_logmsg;
9214 cl_arg.non_interactive = non_interactive;
9215 cl_arg.worktree_path = got_worktree_get_root_path(worktree);
9216 cl_arg.branch_name = got_worktree_get_head_ref_name(worktree);
9217 if (!histedit_in_progress) {
9218 if (strncmp(cl_arg.branch_name, "refs/heads/", 11) != 0) {
9219 error = got_error(GOT_ERR_COMMIT_BRANCH);
9220 goto done;
9222 cl_arg.branch_name += 11;
9224 cl_arg.repo_path = got_repo_get_path(repo);
9225 error = got_worktree_commit(&id, worktree, &paths, author, committer,
9226 allow_bad_symlinks, show_diff, collect_commit_logmsg, &cl_arg,
9227 print_status, NULL, repo);
9228 if (error) {
9229 if (error->code != GOT_ERR_COMMIT_MSG_EMPTY &&
9230 cl_arg.logmsg_path != NULL)
9231 preserve_logmsg = 1;
9232 goto done;
9235 error = got_object_id_str(&id_str, id);
9236 if (error)
9237 goto done;
9238 printf("Created commit %s\n", id_str);
9240 TAILQ_FOREACH(re, &refs, entry) {
9241 error = got_ref_delete(re->ref, repo);
9242 if (error)
9243 goto done;
9246 done:
9247 if (preserve_logmsg) {
9248 fprintf(stderr, "%s: log message preserved in %s\n",
9249 getprogname(), cl_arg.logmsg_path);
9250 } else if (cl_arg.logmsg_path && unlink(cl_arg.logmsg_path) == -1 &&
9251 error == NULL)
9252 error = got_error_from_errno2("unlink", cl_arg.logmsg_path);
9253 free(cl_arg.logmsg_path);
9254 if (merged_logmsg && unlink(merged_logmsg) == -1 && error == NULL)
9255 error = got_error_from_errno2("unlink", merged_logmsg);
9256 free(merged_logmsg);
9257 if (repo) {
9258 const struct got_error *close_err = got_repo_close(repo);
9259 if (error == NULL)
9260 error = close_err;
9262 if (worktree)
9263 got_worktree_close(worktree);
9264 if (pack_fds) {
9265 const struct got_error *pack_err =
9266 got_repo_pack_fds_close(pack_fds);
9267 if (error == NULL)
9268 error = pack_err;
9270 got_ref_list_free(&refs);
9271 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
9272 free(cwd);
9273 free(id_str);
9274 free(gitconfig_path);
9275 free(editor);
9276 free(committer);
9277 free(prepared_logmsg);
9278 return error;
9281 __dead static void
9282 usage_send(void)
9284 fprintf(stderr, "usage: %s send [-afqTv] [-b branch] [-d branch] "
9285 "[-r repository-path] [-t tag] [remote-repository]\n",
9286 getprogname());
9287 exit(1);
9290 static void
9291 print_load_info(int print_colored, int print_found, int print_trees,
9292 int ncolored, int nfound, int ntrees)
9294 if (print_colored) {
9295 printf("%d commit%s colored", ncolored,
9296 ncolored == 1 ? "" : "s");
9298 if (print_found) {
9299 printf("%s%d object%s found",
9300 ncolored > 0 ? "; " : "",
9301 nfound, nfound == 1 ? "" : "s");
9303 if (print_trees) {
9304 printf("; %d tree%s scanned", ntrees,
9305 ntrees == 1 ? "" : "s");
9309 struct got_send_progress_arg {
9310 char last_scaled_packsize[FMT_SCALED_STRSIZE];
9311 int verbosity;
9312 int last_ncolored;
9313 int last_nfound;
9314 int last_ntrees;
9315 int loading_done;
9316 int last_ncommits;
9317 int last_nobj_total;
9318 int last_p_deltify;
9319 int last_p_written;
9320 int last_p_sent;
9321 int printed_something;
9322 int sent_something;
9323 struct got_pathlist_head *delete_branches;
9326 static const struct got_error *
9327 send_progress(void *arg, int ncolored, int nfound, int ntrees,
9328 off_t packfile_size, int ncommits, int nobj_total, int nobj_deltify,
9329 int nobj_written, off_t bytes_sent, const char *refname,
9330 const char *errmsg, int success)
9332 struct got_send_progress_arg *a = arg;
9333 char scaled_packsize[FMT_SCALED_STRSIZE];
9334 char scaled_sent[FMT_SCALED_STRSIZE];
9335 int p_deltify = 0, p_written = 0, p_sent = 0;
9336 int print_colored = 0, print_found = 0, print_trees = 0;
9337 int print_searching = 0, print_total = 0;
9338 int print_deltify = 0, print_written = 0, print_sent = 0;
9340 if (a->verbosity < 0)
9341 return NULL;
9343 if (refname) {
9344 const char *status = success ? "accepted" : "rejected";
9346 if (success) {
9347 struct got_pathlist_entry *pe;
9348 TAILQ_FOREACH(pe, a->delete_branches, entry) {
9349 const char *branchname = pe->path;
9350 if (got_path_cmp(branchname, refname,
9351 strlen(branchname), strlen(refname)) == 0) {
9352 status = "deleted";
9353 a->sent_something = 1;
9354 break;
9359 if (a->printed_something)
9360 putchar('\n');
9361 printf("Server has %s %s", status, refname);
9362 if (errmsg)
9363 printf(": %s", errmsg);
9364 a->printed_something = 1;
9365 return NULL;
9368 if (a->last_ncolored != ncolored) {
9369 print_colored = 1;
9370 a->last_ncolored = ncolored;
9373 if (a->last_nfound != nfound) {
9374 print_colored = 1;
9375 print_found = 1;
9376 a->last_nfound = nfound;
9379 if (a->last_ntrees != ntrees) {
9380 print_colored = 1;
9381 print_found = 1;
9382 print_trees = 1;
9383 a->last_ntrees = ntrees;
9386 if ((print_colored || print_found || print_trees) &&
9387 !a->loading_done) {
9388 printf("\r");
9389 print_load_info(print_colored, print_found, print_trees,
9390 ncolored, nfound, ntrees);
9391 a->printed_something = 1;
9392 fflush(stdout);
9393 return NULL;
9394 } else if (!a->loading_done) {
9395 printf("\r");
9396 print_load_info(1, 1, 1, ncolored, nfound, ntrees);
9397 printf("\n");
9398 a->loading_done = 1;
9401 if (fmt_scaled(packfile_size, scaled_packsize) == -1)
9402 return got_error_from_errno("fmt_scaled");
9403 if (fmt_scaled(bytes_sent, scaled_sent) == -1)
9404 return got_error_from_errno("fmt_scaled");
9406 if (a->last_ncommits != ncommits) {
9407 print_searching = 1;
9408 a->last_ncommits = ncommits;
9411 if (a->last_nobj_total != nobj_total) {
9412 print_searching = 1;
9413 print_total = 1;
9414 a->last_nobj_total = nobj_total;
9417 if (packfile_size > 0 && (a->last_scaled_packsize[0] == '\0' ||
9418 strcmp(scaled_packsize, a->last_scaled_packsize)) != 0) {
9419 if (strlcpy(a->last_scaled_packsize, scaled_packsize,
9420 FMT_SCALED_STRSIZE) >= FMT_SCALED_STRSIZE)
9421 return got_error(GOT_ERR_NO_SPACE);
9424 if (nobj_deltify > 0 || nobj_written > 0) {
9425 if (nobj_deltify > 0) {
9426 p_deltify = (nobj_deltify * 100) / nobj_total;
9427 if (p_deltify != a->last_p_deltify) {
9428 a->last_p_deltify = p_deltify;
9429 print_searching = 1;
9430 print_total = 1;
9431 print_deltify = 1;
9434 if (nobj_written > 0) {
9435 p_written = (nobj_written * 100) / nobj_total;
9436 if (p_written != a->last_p_written) {
9437 a->last_p_written = p_written;
9438 print_searching = 1;
9439 print_total = 1;
9440 print_deltify = 1;
9441 print_written = 1;
9446 if (bytes_sent > 0) {
9447 p_sent = (bytes_sent * 100) / packfile_size;
9448 if (p_sent != a->last_p_sent) {
9449 a->last_p_sent = p_sent;
9450 print_searching = 1;
9451 print_total = 1;
9452 print_deltify = 1;
9453 print_written = 1;
9454 print_sent = 1;
9456 a->sent_something = 1;
9459 if (print_searching || print_total || print_deltify || print_written ||
9460 print_sent)
9461 printf("\r");
9462 if (print_searching)
9463 printf("packing %d reference%s", ncommits,
9464 ncommits == 1 ? "" : "s");
9465 if (print_total)
9466 printf("; %d object%s", nobj_total,
9467 nobj_total == 1 ? "" : "s");
9468 if (print_deltify)
9469 printf("; deltify: %d%%", p_deltify);
9470 if (print_sent)
9471 printf("; uploading pack: %*s %d%%", FMT_SCALED_STRSIZE - 2,
9472 scaled_packsize, p_sent);
9473 else if (print_written)
9474 printf("; writing pack: %*s %d%%", FMT_SCALED_STRSIZE - 2,
9475 scaled_packsize, p_written);
9476 if (print_searching || print_total || print_deltify ||
9477 print_written || print_sent) {
9478 a->printed_something = 1;
9479 fflush(stdout);
9481 return NULL;
9484 static const struct got_error *
9485 cmd_send(int argc, char *argv[])
9487 const struct got_error *error = NULL;
9488 char *cwd = NULL, *repo_path = NULL;
9489 const char *remote_name;
9490 char *proto = NULL, *host = NULL, *port = NULL;
9491 char *repo_name = NULL, *server_path = NULL;
9492 const struct got_remote_repo *remotes, *remote = NULL;
9493 int nremotes, nbranches = 0, ndelete_branches = 0;
9494 struct got_repository *repo = NULL;
9495 struct got_worktree *worktree = NULL;
9496 const struct got_gotconfig *repo_conf = NULL, *worktree_conf = NULL;
9497 struct got_pathlist_head branches;
9498 struct got_pathlist_head tags;
9499 struct got_reflist_head all_branches;
9500 struct got_reflist_head all_tags;
9501 struct got_pathlist_head delete_args;
9502 struct got_pathlist_head delete_branches;
9503 struct got_reflist_entry *re;
9504 struct got_pathlist_entry *pe;
9505 int i, ch, sendfd = -1, sendstatus;
9506 pid_t sendpid = -1;
9507 struct got_send_progress_arg spa;
9508 int verbosity = 0, overwrite_refs = 0;
9509 int send_all_branches = 0, send_all_tags = 0;
9510 struct got_reference *ref = NULL;
9511 int *pack_fds = NULL;
9513 TAILQ_INIT(&branches);
9514 TAILQ_INIT(&tags);
9515 TAILQ_INIT(&all_branches);
9516 TAILQ_INIT(&all_tags);
9517 TAILQ_INIT(&delete_args);
9518 TAILQ_INIT(&delete_branches);
9520 while ((ch = getopt(argc, argv, "ab:d:fqr:Tt:v")) != -1) {
9521 switch (ch) {
9522 case 'a':
9523 send_all_branches = 1;
9524 break;
9525 case 'b':
9526 error = got_pathlist_append(&branches, optarg, NULL);
9527 if (error)
9528 return error;
9529 nbranches++;
9530 break;
9531 case 'd':
9532 error = got_pathlist_append(&delete_args, optarg, NULL);
9533 if (error)
9534 return error;
9535 break;
9536 case 'f':
9537 overwrite_refs = 1;
9538 break;
9539 case 'q':
9540 verbosity = -1;
9541 break;
9542 case 'r':
9543 repo_path = realpath(optarg, NULL);
9544 if (repo_path == NULL)
9545 return got_error_from_errno2("realpath",
9546 optarg);
9547 got_path_strip_trailing_slashes(repo_path);
9548 break;
9549 case 'T':
9550 send_all_tags = 1;
9551 break;
9552 case 't':
9553 error = got_pathlist_append(&tags, optarg, NULL);
9554 if (error)
9555 return error;
9556 break;
9557 case 'v':
9558 if (verbosity < 0)
9559 verbosity = 0;
9560 else if (verbosity < 3)
9561 verbosity++;
9562 break;
9563 default:
9564 usage_send();
9565 /* NOTREACHED */
9568 argc -= optind;
9569 argv += optind;
9571 if (send_all_branches && !TAILQ_EMPTY(&branches))
9572 option_conflict('a', 'b');
9573 if (send_all_tags && !TAILQ_EMPTY(&tags))
9574 option_conflict('T', 't');
9577 if (argc == 0)
9578 remote_name = GOT_SEND_DEFAULT_REMOTE_NAME;
9579 else if (argc == 1)
9580 remote_name = argv[0];
9581 else
9582 usage_send();
9584 cwd = getcwd(NULL, 0);
9585 if (cwd == NULL) {
9586 error = got_error_from_errno("getcwd");
9587 goto done;
9590 error = got_repo_pack_fds_open(&pack_fds);
9591 if (error != NULL)
9592 goto done;
9594 if (repo_path == NULL) {
9595 error = got_worktree_open(&worktree, cwd);
9596 if (error && error->code != GOT_ERR_NOT_WORKTREE)
9597 goto done;
9598 else
9599 error = NULL;
9600 if (worktree) {
9601 repo_path =
9602 strdup(got_worktree_get_repo_path(worktree));
9603 if (repo_path == NULL)
9604 error = got_error_from_errno("strdup");
9605 if (error)
9606 goto done;
9607 } else {
9608 repo_path = strdup(cwd);
9609 if (repo_path == NULL) {
9610 error = got_error_from_errno("strdup");
9611 goto done;
9616 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
9617 if (error)
9618 goto done;
9620 if (worktree) {
9621 worktree_conf = got_worktree_get_gotconfig(worktree);
9622 if (worktree_conf) {
9623 got_gotconfig_get_remotes(&nremotes, &remotes,
9624 worktree_conf);
9625 for (i = 0; i < nremotes; i++) {
9626 if (strcmp(remotes[i].name, remote_name) == 0) {
9627 remote = &remotes[i];
9628 break;
9633 if (remote == NULL) {
9634 repo_conf = got_repo_get_gotconfig(repo);
9635 if (repo_conf) {
9636 got_gotconfig_get_remotes(&nremotes, &remotes,
9637 repo_conf);
9638 for (i = 0; i < nremotes; i++) {
9639 if (strcmp(remotes[i].name, remote_name) == 0) {
9640 remote = &remotes[i];
9641 break;
9646 if (remote == NULL) {
9647 got_repo_get_gitconfig_remotes(&nremotes, &remotes, repo);
9648 for (i = 0; i < nremotes; i++) {
9649 if (strcmp(remotes[i].name, remote_name) == 0) {
9650 remote = &remotes[i];
9651 break;
9655 if (remote == NULL) {
9656 error = got_error_path(remote_name, GOT_ERR_NO_REMOTE);
9657 goto done;
9660 error = got_dial_parse_uri(&proto, &host, &port, &server_path,
9661 &repo_name, remote->send_url);
9662 if (error)
9663 goto done;
9665 if (strcmp(proto, "git") == 0) {
9666 #ifndef PROFILE
9667 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
9668 "sendfd dns inet unveil", NULL) == -1)
9669 err(1, "pledge");
9670 #endif
9671 } else if (strcmp(proto, "git+ssh") == 0 ||
9672 strcmp(proto, "ssh") == 0) {
9673 #ifndef PROFILE
9674 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
9675 "sendfd unveil", NULL) == -1)
9676 err(1, "pledge");
9677 #endif
9678 } else if (strcmp(proto, "http") == 0 ||
9679 strcmp(proto, "git+http") == 0) {
9680 error = got_error_path(proto, GOT_ERR_NOT_IMPL);
9681 goto done;
9682 } else {
9683 error = got_error_path(proto, GOT_ERR_BAD_PROTO);
9684 goto done;
9687 error = got_dial_apply_unveil(proto);
9688 if (error)
9689 goto done;
9691 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
9692 if (error)
9693 goto done;
9695 if (send_all_branches) {
9696 error = got_ref_list(&all_branches, repo, "refs/heads",
9697 got_ref_cmp_by_name, NULL);
9698 if (error)
9699 goto done;
9700 TAILQ_FOREACH(re, &all_branches, entry) {
9701 const char *branchname = got_ref_get_name(re->ref);
9702 error = got_pathlist_append(&branches,
9703 branchname, NULL);
9704 if (error)
9705 goto done;
9706 nbranches++;
9708 } else if (nbranches == 0) {
9709 for (i = 0; i < remote->nsend_branches; i++) {
9710 error = got_pathlist_append(&branches,
9711 remote->send_branches[i], NULL);
9712 if (error)
9713 goto done;
9717 if (send_all_tags) {
9718 error = got_ref_list(&all_tags, repo, "refs/tags",
9719 got_ref_cmp_by_name, NULL);
9720 if (error)
9721 goto done;
9722 TAILQ_FOREACH(re, &all_tags, entry) {
9723 const char *tagname = got_ref_get_name(re->ref);
9724 error = got_pathlist_append(&tags,
9725 tagname, NULL);
9726 if (error)
9727 goto done;
9732 * To prevent accidents only branches in refs/heads/ can be deleted
9733 * with 'got send -d'.
9734 * Deleting anything else requires local repository access or Git.
9736 TAILQ_FOREACH(pe, &delete_args, entry) {
9737 const char *branchname = pe->path;
9738 char *s;
9739 struct got_pathlist_entry *new;
9740 if (strncmp(branchname, "refs/heads/", 11) == 0) {
9741 s = strdup(branchname);
9742 if (s == NULL) {
9743 error = got_error_from_errno("strdup");
9744 goto done;
9746 } else {
9747 if (asprintf(&s, "refs/heads/%s", branchname) == -1) {
9748 error = got_error_from_errno("asprintf");
9749 goto done;
9752 error = got_pathlist_insert(&new, &delete_branches, s, NULL);
9753 if (error || new == NULL /* duplicate */)
9754 free(s);
9755 if (error)
9756 goto done;
9757 ndelete_branches++;
9760 if (nbranches == 0 && ndelete_branches == 0) {
9761 struct got_reference *head_ref;
9762 if (worktree)
9763 error = got_ref_open(&head_ref, repo,
9764 got_worktree_get_head_ref_name(worktree), 0);
9765 else
9766 error = got_ref_open(&head_ref, repo, GOT_REF_HEAD, 0);
9767 if (error)
9768 goto done;
9769 if (got_ref_is_symbolic(head_ref)) {
9770 error = got_ref_resolve_symbolic(&ref, repo, head_ref);
9771 got_ref_close(head_ref);
9772 if (error)
9773 goto done;
9774 } else
9775 ref = head_ref;
9776 error = got_pathlist_append(&branches, got_ref_get_name(ref),
9777 NULL);
9778 if (error)
9779 goto done;
9780 nbranches++;
9783 if (verbosity >= 0) {
9784 printf("Connecting to \"%s\" %s://%s%s%s%s%s\n",
9785 remote->name, proto, host,
9786 port ? ":" : "", port ? port : "",
9787 *server_path == '/' ? "" : "/", server_path);
9790 error = got_send_connect(&sendpid, &sendfd, proto, host, port,
9791 server_path, verbosity);
9792 if (error)
9793 goto done;
9795 memset(&spa, 0, sizeof(spa));
9796 spa.last_scaled_packsize[0] = '\0';
9797 spa.last_p_deltify = -1;
9798 spa.last_p_written = -1;
9799 spa.verbosity = verbosity;
9800 spa.delete_branches = &delete_branches;
9801 error = got_send_pack(remote_name, &branches, &tags, &delete_branches,
9802 verbosity, overwrite_refs, sendfd, repo, send_progress, &spa,
9803 check_cancelled, NULL);
9804 if (spa.printed_something)
9805 putchar('\n');
9806 if (error)
9807 goto done;
9808 if (!spa.sent_something && verbosity >= 0)
9809 printf("Already up-to-date\n");
9810 done:
9811 if (sendpid > 0) {
9812 if (kill(sendpid, SIGTERM) == -1)
9813 error = got_error_from_errno("kill");
9814 if (waitpid(sendpid, &sendstatus, 0) == -1 && error == NULL)
9815 error = got_error_from_errno("waitpid");
9817 if (sendfd != -1 && close(sendfd) == -1 && error == NULL)
9818 error = got_error_from_errno("close");
9819 if (repo) {
9820 const struct got_error *close_err = got_repo_close(repo);
9821 if (error == NULL)
9822 error = close_err;
9824 if (worktree)
9825 got_worktree_close(worktree);
9826 if (pack_fds) {
9827 const struct got_error *pack_err =
9828 got_repo_pack_fds_close(pack_fds);
9829 if (error == NULL)
9830 error = pack_err;
9832 if (ref)
9833 got_ref_close(ref);
9834 got_pathlist_free(&branches, GOT_PATHLIST_FREE_NONE);
9835 got_pathlist_free(&tags, GOT_PATHLIST_FREE_NONE);
9836 got_ref_list_free(&all_branches);
9837 got_ref_list_free(&all_tags);
9838 got_pathlist_free(&delete_args, GOT_PATHLIST_FREE_NONE);
9839 got_pathlist_free(&delete_branches, GOT_PATHLIST_FREE_PATH);
9840 free(cwd);
9841 free(repo_path);
9842 free(proto);
9843 free(host);
9844 free(port);
9845 free(server_path);
9846 free(repo_name);
9847 return error;
9851 * Print and if delete is set delete all ref_prefix references.
9852 * If wanted_ref is not NULL, only print or delete this reference.
9854 static const struct got_error *
9855 process_logmsg_refs(const char *ref_prefix, size_t prefix_len,
9856 const char *wanted_ref, int delete, struct got_worktree *worktree,
9857 struct got_repository *repo)
9859 const struct got_error *err;
9860 struct got_pathlist_head paths;
9861 struct got_reflist_head refs;
9862 struct got_reflist_entry *re;
9863 struct got_reflist_object_id_map *refs_idmap = NULL;
9864 struct got_commit_object *commit = NULL;
9865 struct got_object_id *id = NULL;
9866 const char *header_prefix;
9867 char *uuidstr = NULL;
9868 int found = 0;
9870 TAILQ_INIT(&refs);
9871 TAILQ_INIT(&paths);
9873 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, repo);
9874 if (err)
9875 goto done;
9877 err = got_reflist_object_id_map_create(&refs_idmap, &refs, repo);
9878 if (err)
9879 goto done;
9881 if (worktree != NULL) {
9882 err = got_worktree_get_uuid(&uuidstr, worktree);
9883 if (err)
9884 goto done;
9887 if (wanted_ref) {
9888 if (strncmp(wanted_ref, "refs/heads/", 11) == 0)
9889 wanted_ref += 11;
9892 if (strcmp(ref_prefix, GOT_WORKTREE_BACKOUT_REF_PREFIX) == 0)
9893 header_prefix = "backout";
9894 else
9895 header_prefix = "cherrypick";
9897 TAILQ_FOREACH(re, &refs, entry) {
9898 const char *refname, *wt;
9900 refname = got_ref_get_name(re->ref);
9902 err = check_cancelled(NULL);
9903 if (err)
9904 goto done;
9906 if (strncmp(refname, ref_prefix, prefix_len) == 0)
9907 refname += prefix_len + 1; /* skip '-' delimiter */
9908 else
9909 continue;
9911 wt = refname;
9913 if (worktree == NULL || strncmp(refname, uuidstr,
9914 GOT_WORKTREE_UUID_STRLEN) == 0)
9915 refname += GOT_WORKTREE_UUID_STRLEN + 1; /* skip '-' */
9916 else
9917 continue;
9919 err = got_repo_match_object_id(&id, NULL, refname,
9920 GOT_OBJ_TYPE_COMMIT, NULL, repo);
9921 if (err)
9922 goto done;
9924 err = got_object_open_as_commit(&commit, repo, id);
9925 if (err)
9926 goto done;
9928 if (wanted_ref)
9929 found = strncmp(wanted_ref, refname,
9930 strlen(wanted_ref)) == 0;
9931 if (wanted_ref && !found) {
9932 struct got_reflist_head *ci_refs;
9934 ci_refs = got_reflist_object_id_map_lookup(refs_idmap,
9935 id);
9937 if (ci_refs) {
9938 char *refs_str = NULL;
9939 char const *r = NULL;
9941 err = build_refs_str(&refs_str, ci_refs, id,
9942 repo, 1);
9943 if (err)
9944 goto done;
9946 r = refs_str;
9947 while (r) {
9948 if (strncmp(r, wanted_ref,
9949 strlen(wanted_ref)) == 0) {
9950 found = 1;
9951 break;
9953 r = strchr(r, ' ');
9954 if (r)
9955 ++r;
9957 free(refs_str);
9961 if (wanted_ref == NULL || found) {
9962 if (delete) {
9963 err = got_ref_delete(re->ref, repo);
9964 if (err)
9965 goto done;
9966 printf("Deleted: ");
9967 err = print_commit_oneline(commit, id, repo,
9968 refs_idmap);
9969 } else {
9971 * Print paths modified by commit to help
9972 * associate commits with worktree changes.
9974 err = get_changed_paths(&paths, commit,
9975 repo, NULL);
9976 if (err)
9977 goto done;
9979 err = print_commit(commit, id, repo, NULL,
9980 &paths, NULL, 0, 0, refs_idmap, NULL,
9981 header_prefix);
9982 got_pathlist_free(&paths,
9983 GOT_PATHLIST_FREE_ALL);
9985 if (worktree == NULL)
9986 printf("work tree: %.*s\n\n",
9987 GOT_WORKTREE_UUID_STRLEN, wt);
9989 if (err || found)
9990 goto done;
9993 got_object_commit_close(commit);
9994 commit = NULL;
9995 free(id);
9996 id = NULL;
9999 if (wanted_ref != NULL && !found)
10000 err = got_error_fmt(GOT_ERR_NOT_REF, "%s", wanted_ref);
10002 done:
10003 free(id);
10004 free(uuidstr);
10005 got_ref_list_free(&refs);
10006 got_pathlist_free(&paths, GOT_PATHLIST_FREE_ALL);
10007 if (refs_idmap)
10008 got_reflist_object_id_map_free(refs_idmap);
10009 if (commit)
10010 got_object_commit_close(commit);
10011 return err;
10015 * Create new temp "logmsg" ref of the backed-out or cherrypicked commit
10016 * identified by id for log messages to prepopulate the editor on commit.
10018 static const struct got_error *
10019 logmsg_ref(struct got_object_id *id, const char *prefix,
10020 struct got_worktree *worktree, struct got_repository *repo)
10022 const struct got_error *err = NULL;
10023 char *idstr, *ref = NULL, *refname = NULL;
10024 int histedit_in_progress;
10025 int rebase_in_progress, merge_in_progress;
10028 * Silenty refuse to create merge reference if any histedit, merge,
10029 * or rebase operation is in progress.
10031 err = got_worktree_histedit_in_progress(&histedit_in_progress,
10032 worktree);
10033 if (err)
10034 return err;
10035 if (histedit_in_progress)
10036 return NULL;
10038 err = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
10039 if (err)
10040 return err;
10041 if (rebase_in_progress)
10042 return NULL;
10044 err = got_worktree_merge_in_progress(&merge_in_progress, worktree,
10045 repo);
10046 if (err)
10047 return err;
10048 if (merge_in_progress)
10049 return NULL;
10051 err = got_object_id_str(&idstr, id);
10052 if (err)
10053 return err;
10055 err = got_worktree_get_logmsg_ref_name(&refname, worktree, prefix);
10056 if (err)
10057 goto done;
10059 if (asprintf(&ref, "%s-%s", refname, idstr) == -1) {
10060 err = got_error_from_errno("asprintf");
10061 goto done;
10064 err = create_ref(ref, got_worktree_get_base_commit_id(worktree),
10065 -1, repo);
10066 done:
10067 free(ref);
10068 free(idstr);
10069 free(refname);
10070 return err;
10073 __dead static void
10074 usage_cherrypick(void)
10076 fprintf(stderr, "usage: %s cherrypick [-lX] [commit-id]\n",
10077 getprogname());
10078 exit(1);
10081 static const struct got_error *
10082 cmd_cherrypick(int argc, char *argv[])
10084 const struct got_error *error = NULL;
10085 struct got_worktree *worktree = NULL;
10086 struct got_repository *repo = NULL;
10087 char *cwd = NULL, *commit_id_str = NULL;
10088 struct got_object_id *commit_id = NULL;
10089 struct got_commit_object *commit = NULL;
10090 struct got_object_qid *pid;
10091 int ch, list_refs = 0, remove_refs = 0;
10092 struct got_update_progress_arg upa;
10093 int *pack_fds = NULL;
10095 while ((ch = getopt(argc, argv, "lX")) != -1) {
10096 switch (ch) {
10097 case 'l':
10098 list_refs = 1;
10099 break;
10100 case 'X':
10101 remove_refs = 1;
10102 break;
10103 default:
10104 usage_cherrypick();
10105 /* NOTREACHED */
10109 argc -= optind;
10110 argv += optind;
10112 #ifndef PROFILE
10113 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
10114 "unveil", NULL) == -1)
10115 err(1, "pledge");
10116 #endif
10117 if (list_refs || remove_refs) {
10118 if (argc != 0 && argc != 1)
10119 usage_cherrypick();
10120 } else if (argc != 1)
10121 usage_cherrypick();
10122 if (list_refs && remove_refs)
10123 option_conflict('l', 'X');
10125 cwd = getcwd(NULL, 0);
10126 if (cwd == NULL) {
10127 error = got_error_from_errno("getcwd");
10128 goto done;
10131 error = got_repo_pack_fds_open(&pack_fds);
10132 if (error != NULL)
10133 goto done;
10135 error = got_worktree_open(&worktree, cwd);
10136 if (error) {
10137 if (list_refs || remove_refs) {
10138 if (error->code != GOT_ERR_NOT_WORKTREE)
10139 goto done;
10140 } else {
10141 if (error->code == GOT_ERR_NOT_WORKTREE)
10142 error = wrap_not_worktree_error(error,
10143 "cherrypick", cwd);
10144 goto done;
10148 error = got_repo_open(&repo,
10149 worktree ? got_worktree_get_repo_path(worktree) : cwd,
10150 NULL, pack_fds);
10151 if (error != NULL)
10152 goto done;
10154 error = apply_unveil(got_repo_get_path(repo), 0,
10155 worktree ? got_worktree_get_root_path(worktree) : NULL);
10156 if (error)
10157 goto done;
10159 if (list_refs || remove_refs) {
10160 error = process_logmsg_refs(GOT_WORKTREE_CHERRYPICK_REF_PREFIX,
10161 GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN,
10162 argc == 1 ? argv[0] : NULL, remove_refs, worktree, repo);
10163 goto done;
10166 error = got_repo_match_object_id(&commit_id, NULL, argv[0],
10167 GOT_OBJ_TYPE_COMMIT, NULL, repo);
10168 if (error)
10169 goto done;
10170 error = got_object_id_str(&commit_id_str, commit_id);
10171 if (error)
10172 goto done;
10174 error = got_object_open_as_commit(&commit, repo, commit_id);
10175 if (error)
10176 goto done;
10177 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
10178 memset(&upa, 0, sizeof(upa));
10179 error = got_worktree_merge_files(worktree, pid ? &pid->id : NULL,
10180 commit_id, repo, update_progress, &upa, check_cancelled,
10181 NULL);
10182 if (error != NULL)
10183 goto done;
10185 if (upa.did_something) {
10186 error = logmsg_ref(commit_id,
10187 GOT_WORKTREE_CHERRYPICK_REF_PREFIX, worktree, repo);
10188 if (error)
10189 goto done;
10190 printf("Merged commit %s\n", commit_id_str);
10192 print_merge_progress_stats(&upa);
10193 done:
10194 free(cwd);
10195 if (commit)
10196 got_object_commit_close(commit);
10197 free(commit_id_str);
10198 if (worktree)
10199 got_worktree_close(worktree);
10200 if (repo) {
10201 const struct got_error *close_err = got_repo_close(repo);
10202 if (error == NULL)
10203 error = close_err;
10205 if (pack_fds) {
10206 const struct got_error *pack_err =
10207 got_repo_pack_fds_close(pack_fds);
10208 if (error == NULL)
10209 error = pack_err;
10212 return error;
10215 __dead static void
10216 usage_backout(void)
10218 fprintf(stderr, "usage: %s backout [-lX] [commit-id]\n", getprogname());
10219 exit(1);
10222 static const struct got_error *
10223 cmd_backout(int argc, char *argv[])
10225 const struct got_error *error = NULL;
10226 struct got_worktree *worktree = NULL;
10227 struct got_repository *repo = NULL;
10228 char *cwd = NULL, *commit_id_str = NULL;
10229 struct got_object_id *commit_id = NULL;
10230 struct got_commit_object *commit = NULL;
10231 struct got_object_qid *pid;
10232 int ch, list_refs = 0, remove_refs = 0;
10233 struct got_update_progress_arg upa;
10234 int *pack_fds = NULL;
10236 while ((ch = getopt(argc, argv, "lX")) != -1) {
10237 switch (ch) {
10238 case 'l':
10239 list_refs = 1;
10240 break;
10241 case 'X':
10242 remove_refs = 1;
10243 break;
10244 default:
10245 usage_backout();
10246 /* NOTREACHED */
10250 argc -= optind;
10251 argv += optind;
10253 #ifndef PROFILE
10254 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
10255 "unveil", NULL) == -1)
10256 err(1, "pledge");
10257 #endif
10258 if (list_refs || remove_refs) {
10259 if (argc != 0 && argc != 1)
10260 usage_backout();
10261 } else if (argc != 1)
10262 usage_backout();
10263 if (list_refs && remove_refs)
10264 option_conflict('l', 'X');
10266 cwd = getcwd(NULL, 0);
10267 if (cwd == NULL) {
10268 error = got_error_from_errno("getcwd");
10269 goto done;
10272 error = got_repo_pack_fds_open(&pack_fds);
10273 if (error != NULL)
10274 goto done;
10276 error = got_worktree_open(&worktree, cwd);
10277 if (error) {
10278 if (list_refs || remove_refs) {
10279 if (error->code != GOT_ERR_NOT_WORKTREE)
10280 goto done;
10281 } else {
10282 if (error->code == GOT_ERR_NOT_WORKTREE)
10283 error = wrap_not_worktree_error(error,
10284 "backout", cwd);
10285 goto done;
10289 error = got_repo_open(&repo,
10290 worktree ? got_worktree_get_repo_path(worktree) : cwd,
10291 NULL, pack_fds);
10292 if (error != NULL)
10293 goto done;
10295 error = apply_unveil(got_repo_get_path(repo), 0,
10296 worktree ? got_worktree_get_root_path(worktree) : NULL);
10297 if (error)
10298 goto done;
10300 if (list_refs || remove_refs) {
10301 error = process_logmsg_refs(GOT_WORKTREE_BACKOUT_REF_PREFIX,
10302 GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN,
10303 argc == 1 ? argv[0] : NULL, remove_refs, worktree, repo);
10304 goto done;
10307 error = got_repo_match_object_id(&commit_id, NULL, argv[0],
10308 GOT_OBJ_TYPE_COMMIT, NULL, repo);
10309 if (error)
10310 goto done;
10311 error = got_object_id_str(&commit_id_str, commit_id);
10312 if (error)
10313 goto done;
10315 error = got_object_open_as_commit(&commit, repo, commit_id);
10316 if (error)
10317 goto done;
10318 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
10319 if (pid == NULL) {
10320 error = got_error(GOT_ERR_ROOT_COMMIT);
10321 goto done;
10324 memset(&upa, 0, sizeof(upa));
10325 error = got_worktree_merge_files(worktree, commit_id, &pid->id,
10326 repo, update_progress, &upa, check_cancelled, NULL);
10327 if (error != NULL)
10328 goto done;
10330 if (upa.did_something) {
10331 error = logmsg_ref(commit_id, GOT_WORKTREE_BACKOUT_REF_PREFIX,
10332 worktree, repo);
10333 if (error)
10334 goto done;
10335 printf("Backed out commit %s\n", commit_id_str);
10337 print_merge_progress_stats(&upa);
10338 done:
10339 free(cwd);
10340 if (commit)
10341 got_object_commit_close(commit);
10342 free(commit_id_str);
10343 if (worktree)
10344 got_worktree_close(worktree);
10345 if (repo) {
10346 const struct got_error *close_err = got_repo_close(repo);
10347 if (error == NULL)
10348 error = close_err;
10350 if (pack_fds) {
10351 const struct got_error *pack_err =
10352 got_repo_pack_fds_close(pack_fds);
10353 if (error == NULL)
10354 error = pack_err;
10356 return error;
10359 __dead static void
10360 usage_rebase(void)
10362 fprintf(stderr, "usage: %s rebase [-aclX] [branch]\n", getprogname());
10363 exit(1);
10366 static void
10367 trim_logmsg(char *logmsg, int limit)
10369 char *nl;
10370 size_t len;
10372 len = strlen(logmsg);
10373 if (len > limit)
10374 len = limit;
10375 logmsg[len] = '\0';
10376 nl = strchr(logmsg, '\n');
10377 if (nl)
10378 *nl = '\0';
10381 static const struct got_error *
10382 get_short_logmsg(char **logmsg, int limit, struct got_commit_object *commit)
10384 const struct got_error *err;
10385 char *logmsg0 = NULL;
10386 const char *s;
10388 err = got_object_commit_get_logmsg(&logmsg0, commit);
10389 if (err)
10390 return err;
10392 s = logmsg0;
10393 while (isspace((unsigned char)s[0]))
10394 s++;
10396 *logmsg = strdup(s);
10397 if (*logmsg == NULL) {
10398 err = got_error_from_errno("strdup");
10399 goto done;
10402 trim_logmsg(*logmsg, limit);
10403 done:
10404 free(logmsg0);
10405 return err;
10408 static const struct got_error *
10409 show_rebase_merge_conflict(struct got_object_id *id,
10410 struct got_repository *repo)
10412 const struct got_error *err;
10413 struct got_commit_object *commit = NULL;
10414 char *id_str = NULL, *logmsg = NULL;
10416 err = got_object_open_as_commit(&commit, repo, id);
10417 if (err)
10418 return err;
10420 err = got_object_id_str(&id_str, id);
10421 if (err)
10422 goto done;
10424 id_str[12] = '\0';
10426 err = get_short_logmsg(&logmsg, 42, commit);
10427 if (err)
10428 goto done;
10430 printf("%s -> merge conflict: %s\n", id_str, logmsg);
10431 done:
10432 free(id_str);
10433 got_object_commit_close(commit);
10434 free(logmsg);
10435 return err;
10438 static const struct got_error *
10439 show_rebase_progress(struct got_commit_object *commit,
10440 struct got_object_id *old_id, struct got_object_id *new_id)
10442 const struct got_error *err;
10443 char *old_id_str = NULL, *new_id_str = NULL, *logmsg = NULL;
10445 err = got_object_id_str(&old_id_str, old_id);
10446 if (err)
10447 goto done;
10449 if (new_id) {
10450 err = got_object_id_str(&new_id_str, new_id);
10451 if (err)
10452 goto done;
10455 old_id_str[12] = '\0';
10456 if (new_id_str)
10457 new_id_str[12] = '\0';
10459 err = get_short_logmsg(&logmsg, 42, commit);
10460 if (err)
10461 goto done;
10463 printf("%s -> %s: %s\n", old_id_str,
10464 new_id_str ? new_id_str : "no-op change", logmsg);
10465 done:
10466 free(old_id_str);
10467 free(new_id_str);
10468 free(logmsg);
10469 return err;
10472 static const struct got_error *
10473 rebase_complete(struct got_worktree *worktree, struct got_fileindex *fileindex,
10474 struct got_reference *branch, struct got_reference *tmp_branch,
10475 struct got_repository *repo, int create_backup)
10477 printf("Switching work tree to %s\n", got_ref_get_name(branch));
10478 return got_worktree_rebase_complete(worktree, fileindex,
10479 tmp_branch, branch, repo, create_backup);
10482 static const struct got_error *
10483 rebase_commit(struct got_pathlist_head *merged_paths,
10484 struct got_worktree *worktree, struct got_fileindex *fileindex,
10485 struct got_reference *tmp_branch, const char *committer,
10486 struct got_object_id *commit_id, struct got_repository *repo)
10488 const struct got_error *error;
10489 struct got_commit_object *commit;
10490 struct got_object_id *new_commit_id;
10492 error = got_object_open_as_commit(&commit, repo, commit_id);
10493 if (error)
10494 return error;
10496 error = got_worktree_rebase_commit(&new_commit_id, merged_paths,
10497 worktree, fileindex, tmp_branch, committer, commit, commit_id,
10498 repo);
10499 if (error) {
10500 if (error->code != GOT_ERR_COMMIT_NO_CHANGES)
10501 goto done;
10502 error = show_rebase_progress(commit, commit_id, NULL);
10503 } else {
10504 error = show_rebase_progress(commit, commit_id, new_commit_id);
10505 free(new_commit_id);
10507 done:
10508 got_object_commit_close(commit);
10509 return error;
10512 struct check_path_prefix_arg {
10513 const char *path_prefix;
10514 size_t len;
10515 int errcode;
10518 static const struct got_error *
10519 check_path_prefix_in_diff(void *arg, struct got_blob_object *blob1,
10520 struct got_blob_object *blob2, FILE *f1, FILE *f2,
10521 struct got_object_id *id1, struct got_object_id *id2,
10522 const char *path1, const char *path2,
10523 mode_t mode1, mode_t mode2, struct got_repository *repo)
10525 struct check_path_prefix_arg *a = arg;
10527 if ((path1 && !got_path_is_child(path1, a->path_prefix, a->len)) ||
10528 (path2 && !got_path_is_child(path2, a->path_prefix, a->len)))
10529 return got_error(a->errcode);
10531 return NULL;
10534 static const struct got_error *
10535 check_path_prefix(struct got_object_id *parent_id,
10536 struct got_object_id *commit_id, const char *path_prefix,
10537 int errcode, struct got_repository *repo)
10539 const struct got_error *err;
10540 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
10541 struct got_commit_object *commit = NULL, *parent_commit = NULL;
10542 struct check_path_prefix_arg cpp_arg;
10544 if (got_path_is_root_dir(path_prefix))
10545 return NULL;
10547 err = got_object_open_as_commit(&commit, repo, commit_id);
10548 if (err)
10549 goto done;
10551 err = got_object_open_as_commit(&parent_commit, repo, parent_id);
10552 if (err)
10553 goto done;
10555 err = got_object_open_as_tree(&tree1, repo,
10556 got_object_commit_get_tree_id(parent_commit));
10557 if (err)
10558 goto done;
10560 err = got_object_open_as_tree(&tree2, repo,
10561 got_object_commit_get_tree_id(commit));
10562 if (err)
10563 goto done;
10565 cpp_arg.path_prefix = path_prefix;
10566 while (cpp_arg.path_prefix[0] == '/')
10567 cpp_arg.path_prefix++;
10568 cpp_arg.len = strlen(cpp_arg.path_prefix);
10569 cpp_arg.errcode = errcode;
10570 err = got_diff_tree(tree1, tree2, NULL, NULL, -1, -1, "", "", repo,
10571 check_path_prefix_in_diff, &cpp_arg, 0);
10572 done:
10573 if (tree1)
10574 got_object_tree_close(tree1);
10575 if (tree2)
10576 got_object_tree_close(tree2);
10577 if (commit)
10578 got_object_commit_close(commit);
10579 if (parent_commit)
10580 got_object_commit_close(parent_commit);
10581 return err;
10584 static const struct got_error *
10585 collect_commits(struct got_object_id_queue *commits,
10586 struct got_object_id *initial_commit_id,
10587 struct got_object_id *iter_start_id, struct got_object_id *iter_stop_id,
10588 const char *path_prefix, int path_prefix_errcode,
10589 struct got_repository *repo)
10591 const struct got_error *err = NULL;
10592 struct got_commit_graph *graph = NULL;
10593 struct got_object_id parent_id, commit_id;
10594 struct got_object_qid *qid;
10596 err = got_commit_graph_open(&graph, "/", 1);
10597 if (err)
10598 return err;
10600 err = got_commit_graph_iter_start(graph, iter_start_id, repo,
10601 check_cancelled, NULL);
10602 if (err)
10603 goto done;
10605 memcpy(&commit_id, initial_commit_id, sizeof(commit_id));
10606 while (got_object_id_cmp(&commit_id, iter_stop_id) != 0) {
10607 err = got_commit_graph_iter_next(&parent_id, graph, repo,
10608 check_cancelled, NULL);
10609 if (err) {
10610 if (err->code == GOT_ERR_ITER_COMPLETED) {
10611 err = got_error_msg(GOT_ERR_ANCESTRY,
10612 "ran out of commits to rebase before "
10613 "youngest common ancestor commit has "
10614 "been reached?!?");
10616 goto done;
10617 } else {
10618 err = check_path_prefix(&parent_id, &commit_id,
10619 path_prefix, path_prefix_errcode, repo);
10620 if (err)
10621 goto done;
10623 err = got_object_qid_alloc(&qid, &commit_id);
10624 if (err)
10625 goto done;
10626 STAILQ_INSERT_HEAD(commits, qid, entry);
10628 memcpy(&commit_id, &parent_id, sizeof(commit_id));
10631 done:
10632 got_commit_graph_close(graph);
10633 return err;
10636 static const struct got_error *
10637 get_commit_brief_str(char **brief_str, struct got_commit_object *commit)
10639 const struct got_error *err = NULL;
10640 time_t committer_time;
10641 struct tm tm;
10642 char datebuf[11]; /* YYYY-MM-DD + NUL */
10643 char *author0 = NULL, *author, *smallerthan;
10644 char *logmsg0 = NULL, *logmsg, *newline;
10646 committer_time = got_object_commit_get_committer_time(commit);
10647 if (gmtime_r(&committer_time, &tm) == NULL)
10648 return got_error_from_errno("gmtime_r");
10649 if (strftime(datebuf, sizeof(datebuf), "%G-%m-%d", &tm) == 0)
10650 return got_error(GOT_ERR_NO_SPACE);
10652 author0 = strdup(got_object_commit_get_author(commit));
10653 if (author0 == NULL)
10654 return got_error_from_errno("strdup");
10655 author = author0;
10656 smallerthan = strchr(author, '<');
10657 if (smallerthan && smallerthan[1] != '\0')
10658 author = smallerthan + 1;
10659 author[strcspn(author, "@>")] = '\0';
10661 err = got_object_commit_get_logmsg(&logmsg0, commit);
10662 if (err)
10663 goto done;
10664 logmsg = logmsg0;
10665 while (*logmsg == '\n')
10666 logmsg++;
10667 newline = strchr(logmsg, '\n');
10668 if (newline)
10669 *newline = '\0';
10671 if (asprintf(brief_str, "%s %s %s",
10672 datebuf, author, logmsg) == -1)
10673 err = got_error_from_errno("asprintf");
10674 done:
10675 free(author0);
10676 free(logmsg0);
10677 return err;
10680 static const struct got_error *
10681 delete_backup_ref(struct got_reference *ref, struct got_object_id *id,
10682 struct got_repository *repo)
10684 const struct got_error *err;
10685 char *id_str;
10687 err = got_object_id_str(&id_str, id);
10688 if (err)
10689 return err;
10691 err = got_ref_delete(ref, repo);
10692 if (err)
10693 goto done;
10695 printf("Deleted %s: %s\n", got_ref_get_name(ref), id_str);
10696 done:
10697 free(id_str);
10698 return err;
10701 static const struct got_error *
10702 print_backup_ref(const char *branch_name, const char *new_id_str,
10703 struct got_object_id *old_commit_id, struct got_commit_object *old_commit,
10704 struct got_reflist_object_id_map *refs_idmap,
10705 struct got_repository *repo)
10707 const struct got_error *err = NULL;
10708 struct got_reflist_head *refs;
10709 char *refs_str = NULL;
10710 struct got_object_id *new_commit_id = NULL;
10711 struct got_commit_object *new_commit = NULL;
10712 char *new_commit_brief_str = NULL;
10713 struct got_object_id *yca_id = NULL;
10714 struct got_commit_object *yca_commit = NULL;
10715 char *yca_id_str = NULL, *yca_brief_str = NULL;
10716 char *custom_refs_str;
10718 if (asprintf(&custom_refs_str, "formerly %s", branch_name) == -1)
10719 return got_error_from_errno("asprintf");
10721 err = print_commit(old_commit, old_commit_id, repo, NULL, NULL, NULL,
10722 0, 0, refs_idmap, custom_refs_str, NULL);
10723 if (err)
10724 goto done;
10726 err = got_object_resolve_id_str(&new_commit_id, repo, new_id_str);
10727 if (err)
10728 goto done;
10730 refs = got_reflist_object_id_map_lookup(refs_idmap, new_commit_id);
10731 if (refs) {
10732 err = build_refs_str(&refs_str, refs, new_commit_id, repo, 0);
10733 if (err)
10734 goto done;
10737 err = got_object_open_as_commit(&new_commit, repo, new_commit_id);
10738 if (err)
10739 goto done;
10741 err = get_commit_brief_str(&new_commit_brief_str, new_commit);
10742 if (err)
10743 goto done;
10745 err = got_commit_graph_find_youngest_common_ancestor(&yca_id,
10746 old_commit_id, new_commit_id, 1, repo, check_cancelled, NULL);
10747 if (err)
10748 goto done;
10750 printf("has become commit %s%s%s%s\n %s\n", new_id_str,
10751 refs_str ? " (" : "", refs_str ? refs_str : "",
10752 refs_str ? ")" : "", new_commit_brief_str);
10753 if (yca_id && got_object_id_cmp(yca_id, new_commit_id) != 0 &&
10754 got_object_id_cmp(yca_id, old_commit_id) != 0) {
10755 free(refs_str);
10756 refs_str = NULL;
10758 err = got_object_open_as_commit(&yca_commit, repo, yca_id);
10759 if (err)
10760 goto done;
10762 err = get_commit_brief_str(&yca_brief_str, yca_commit);
10763 if (err)
10764 goto done;
10766 err = got_object_id_str(&yca_id_str, yca_id);
10767 if (err)
10768 goto done;
10770 refs = got_reflist_object_id_map_lookup(refs_idmap, yca_id);
10771 if (refs) {
10772 err = build_refs_str(&refs_str, refs, yca_id, repo, 0);
10773 if (err)
10774 goto done;
10776 printf("history forked at %s%s%s%s\n %s\n",
10777 yca_id_str,
10778 refs_str ? " (" : "", refs_str ? refs_str : "",
10779 refs_str ? ")" : "", yca_brief_str);
10781 done:
10782 free(custom_refs_str);
10783 free(new_commit_id);
10784 free(refs_str);
10785 free(yca_id);
10786 free(yca_id_str);
10787 free(yca_brief_str);
10788 if (new_commit)
10789 got_object_commit_close(new_commit);
10790 if (yca_commit)
10791 got_object_commit_close(yca_commit);
10793 return err;
10796 static const struct got_error *
10797 worktree_has_logmsg_ref(const char *caller, struct got_worktree *worktree,
10798 struct got_repository *repo)
10800 const struct got_error *err;
10801 struct got_reflist_head refs;
10802 struct got_reflist_entry *re;
10803 char *uuidstr = NULL;
10804 static char msg[160];
10806 TAILQ_INIT(&refs);
10808 err = got_worktree_get_uuid(&uuidstr, worktree);
10809 if (err)
10810 goto done;
10812 err = got_ref_list(&refs, repo, "refs/got/worktree",
10813 got_ref_cmp_by_name, repo);
10814 if (err)
10815 goto done;
10817 TAILQ_FOREACH(re, &refs, entry) {
10818 const char *cmd, *refname, *type;
10820 refname = got_ref_get_name(re->ref);
10822 if (strncmp(refname, GOT_WORKTREE_CHERRYPICK_REF_PREFIX,
10823 GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN) == 0) {
10824 refname += GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN + 1;
10825 cmd = "cherrypick";
10826 type = "cherrypicked";
10827 } else if (strncmp(refname, GOT_WORKTREE_BACKOUT_REF_PREFIX,
10828 GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN) == 0) {
10829 refname += GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN + 1;
10830 cmd = "backout";
10831 type = "backed-out";
10832 } else
10833 continue;
10835 if (strncmp(refname, uuidstr, GOT_WORKTREE_UUID_STRLEN) != 0)
10836 continue;
10838 snprintf(msg, sizeof(msg),
10839 "work tree has references created by %s commits which "
10840 "must be removed with 'got %s -X' before running the %s "
10841 "command", type, cmd, caller);
10842 err = got_error_msg(GOT_ERR_WORKTREE_META, msg);
10843 goto done;
10846 done:
10847 free(uuidstr);
10848 got_ref_list_free(&refs);
10849 return err;
10852 static const struct got_error *
10853 process_backup_refs(const char *backup_ref_prefix,
10854 const char *wanted_branch_name,
10855 int delete, struct got_repository *repo)
10857 const struct got_error *err;
10858 struct got_reflist_head refs, backup_refs;
10859 struct got_reflist_entry *re;
10860 const size_t backup_ref_prefix_len = strlen(backup_ref_prefix);
10861 struct got_object_id *old_commit_id = NULL;
10862 char *branch_name = NULL;
10863 struct got_commit_object *old_commit = NULL;
10864 struct got_reflist_object_id_map *refs_idmap = NULL;
10865 int wanted_branch_found = 0;
10867 TAILQ_INIT(&refs);
10868 TAILQ_INIT(&backup_refs);
10870 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
10871 if (err)
10872 return err;
10874 err = got_reflist_object_id_map_create(&refs_idmap, &refs, repo);
10875 if (err)
10876 goto done;
10878 if (wanted_branch_name) {
10879 if (strncmp(wanted_branch_name, "refs/heads/", 11) == 0)
10880 wanted_branch_name += 11;
10883 err = got_ref_list(&backup_refs, repo, backup_ref_prefix,
10884 got_ref_cmp_by_commit_timestamp_descending, repo);
10885 if (err)
10886 goto done;
10888 TAILQ_FOREACH(re, &backup_refs, entry) {
10889 const char *refname = got_ref_get_name(re->ref);
10890 char *slash;
10892 err = check_cancelled(NULL);
10893 if (err)
10894 break;
10896 err = got_ref_resolve(&old_commit_id, repo, re->ref);
10897 if (err)
10898 break;
10900 err = got_object_open_as_commit(&old_commit, repo,
10901 old_commit_id);
10902 if (err)
10903 break;
10905 if (strncmp(backup_ref_prefix, refname,
10906 backup_ref_prefix_len) == 0)
10907 refname += backup_ref_prefix_len;
10909 while (refname[0] == '/')
10910 refname++;
10912 branch_name = strdup(refname);
10913 if (branch_name == NULL) {
10914 err = got_error_from_errno("strdup");
10915 break;
10917 slash = strrchr(branch_name, '/');
10918 if (slash) {
10919 *slash = '\0';
10920 refname += strlen(branch_name) + 1;
10923 if (wanted_branch_name == NULL ||
10924 strcmp(wanted_branch_name, branch_name) == 0) {
10925 wanted_branch_found = 1;
10926 if (delete) {
10927 err = delete_backup_ref(re->ref,
10928 old_commit_id, repo);
10929 } else {
10930 err = print_backup_ref(branch_name, refname,
10931 old_commit_id, old_commit, refs_idmap,
10932 repo);
10934 if (err)
10935 break;
10938 free(old_commit_id);
10939 old_commit_id = NULL;
10940 free(branch_name);
10941 branch_name = NULL;
10942 got_object_commit_close(old_commit);
10943 old_commit = NULL;
10946 if (wanted_branch_name && !wanted_branch_found) {
10947 err = got_error_fmt(GOT_ERR_NOT_REF,
10948 "%s/%s/", backup_ref_prefix, wanted_branch_name);
10950 done:
10951 if (refs_idmap)
10952 got_reflist_object_id_map_free(refs_idmap);
10953 got_ref_list_free(&refs);
10954 got_ref_list_free(&backup_refs);
10955 free(old_commit_id);
10956 free(branch_name);
10957 if (old_commit)
10958 got_object_commit_close(old_commit);
10959 return err;
10962 static const struct got_error *
10963 abort_progress(void *arg, unsigned char status, const char *path)
10966 * Unversioned files should not clutter progress output when
10967 * an operation is aborted.
10969 if (status == GOT_STATUS_UNVERSIONED)
10970 return NULL;
10972 return update_progress(arg, status, path);
10975 static const struct got_error *
10976 cmd_rebase(int argc, char *argv[])
10978 const struct got_error *error = NULL;
10979 struct got_worktree *worktree = NULL;
10980 struct got_repository *repo = NULL;
10981 struct got_fileindex *fileindex = NULL;
10982 char *cwd = NULL, *committer = NULL, *gitconfig_path = NULL;
10983 struct got_reference *branch = NULL;
10984 struct got_reference *new_base_branch = NULL, *tmp_branch = NULL;
10985 struct got_object_id *commit_id = NULL, *parent_id = NULL;
10986 struct got_object_id *resume_commit_id = NULL;
10987 struct got_object_id *branch_head_commit_id = NULL, *yca_id = NULL;
10988 struct got_object_id *head_commit_id = NULL;
10989 struct got_reference *head_ref = NULL;
10990 struct got_commit_object *commit = NULL;
10991 int ch, rebase_in_progress = 0, abort_rebase = 0, continue_rebase = 0;
10992 int histedit_in_progress = 0, merge_in_progress = 0;
10993 int create_backup = 1, list_backups = 0, delete_backups = 0;
10994 struct got_object_id_queue commits;
10995 struct got_pathlist_head merged_paths;
10996 const struct got_object_id_queue *parent_ids;
10997 struct got_object_qid *qid, *pid;
10998 struct got_update_progress_arg upa;
10999 int *pack_fds = NULL;
11001 STAILQ_INIT(&commits);
11002 TAILQ_INIT(&merged_paths);
11003 memset(&upa, 0, sizeof(upa));
11005 while ((ch = getopt(argc, argv, "aclX")) != -1) {
11006 switch (ch) {
11007 case 'a':
11008 abort_rebase = 1;
11009 break;
11010 case 'c':
11011 continue_rebase = 1;
11012 break;
11013 case 'l':
11014 list_backups = 1;
11015 break;
11016 case 'X':
11017 delete_backups = 1;
11018 break;
11019 default:
11020 usage_rebase();
11021 /* NOTREACHED */
11025 argc -= optind;
11026 argv += optind;
11028 #ifndef PROFILE
11029 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
11030 "unveil", NULL) == -1)
11031 err(1, "pledge");
11032 #endif
11033 if (list_backups) {
11034 if (abort_rebase)
11035 option_conflict('l', 'a');
11036 if (continue_rebase)
11037 option_conflict('l', 'c');
11038 if (delete_backups)
11039 option_conflict('l', 'X');
11040 if (argc != 0 && argc != 1)
11041 usage_rebase();
11042 } else if (delete_backups) {
11043 if (abort_rebase)
11044 option_conflict('X', 'a');
11045 if (continue_rebase)
11046 option_conflict('X', 'c');
11047 if (list_backups)
11048 option_conflict('l', 'X');
11049 if (argc != 0 && argc != 1)
11050 usage_rebase();
11051 } else {
11052 if (abort_rebase && continue_rebase)
11053 usage_rebase();
11054 else if (abort_rebase || continue_rebase) {
11055 if (argc != 0)
11056 usage_rebase();
11057 } else if (argc != 1)
11058 usage_rebase();
11061 cwd = getcwd(NULL, 0);
11062 if (cwd == NULL) {
11063 error = got_error_from_errno("getcwd");
11064 goto done;
11067 error = got_repo_pack_fds_open(&pack_fds);
11068 if (error != NULL)
11069 goto done;
11071 error = got_worktree_open(&worktree, cwd);
11072 if (error) {
11073 if (list_backups || delete_backups) {
11074 if (error->code != GOT_ERR_NOT_WORKTREE)
11075 goto done;
11076 } else {
11077 if (error->code == GOT_ERR_NOT_WORKTREE)
11078 error = wrap_not_worktree_error(error,
11079 "rebase", cwd);
11080 goto done;
11084 error = get_gitconfig_path(&gitconfig_path);
11085 if (error)
11086 goto done;
11087 error = got_repo_open(&repo,
11088 worktree ? got_worktree_get_repo_path(worktree) : cwd,
11089 gitconfig_path, pack_fds);
11090 if (error != NULL)
11091 goto done;
11093 if (worktree != NULL && !list_backups && !delete_backups) {
11094 error = worktree_has_logmsg_ref("rebase", worktree, repo);
11095 if (error)
11096 goto done;
11099 error = get_author(&committer, repo, worktree);
11100 if (error && error->code != GOT_ERR_COMMIT_NO_AUTHOR)
11101 goto done;
11103 error = apply_unveil(got_repo_get_path(repo), 0,
11104 worktree ? got_worktree_get_root_path(worktree) : NULL);
11105 if (error)
11106 goto done;
11108 if (list_backups || delete_backups) {
11109 error = process_backup_refs(
11110 GOT_WORKTREE_REBASE_BACKUP_REF_PREFIX,
11111 argc == 1 ? argv[0] : NULL, delete_backups, repo);
11112 goto done; /* nothing else to do */
11115 error = got_worktree_histedit_in_progress(&histedit_in_progress,
11116 worktree);
11117 if (error)
11118 goto done;
11119 if (histedit_in_progress) {
11120 error = got_error(GOT_ERR_HISTEDIT_BUSY);
11121 goto done;
11124 error = got_worktree_merge_in_progress(&merge_in_progress,
11125 worktree, repo);
11126 if (error)
11127 goto done;
11128 if (merge_in_progress) {
11129 error = got_error(GOT_ERR_MERGE_BUSY);
11130 goto done;
11133 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
11134 if (error)
11135 goto done;
11137 if (abort_rebase) {
11138 if (!rebase_in_progress) {
11139 error = got_error(GOT_ERR_NOT_REBASING);
11140 goto done;
11142 error = got_worktree_rebase_continue(&resume_commit_id,
11143 &new_base_branch, &tmp_branch, &branch, &fileindex,
11144 worktree, repo);
11145 if (error)
11146 goto done;
11147 printf("Switching work tree to %s\n",
11148 got_ref_get_symref_target(new_base_branch));
11149 error = got_worktree_rebase_abort(worktree, fileindex, repo,
11150 new_base_branch, abort_progress, &upa);
11151 if (error)
11152 goto done;
11153 printf("Rebase of %s aborted\n", got_ref_get_name(branch));
11154 print_merge_progress_stats(&upa);
11155 goto done; /* nothing else to do */
11158 if (continue_rebase) {
11159 if (!rebase_in_progress) {
11160 error = got_error(GOT_ERR_NOT_REBASING);
11161 goto done;
11163 error = got_worktree_rebase_continue(&resume_commit_id,
11164 &new_base_branch, &tmp_branch, &branch, &fileindex,
11165 worktree, repo);
11166 if (error)
11167 goto done;
11169 error = rebase_commit(NULL, worktree, fileindex, tmp_branch,
11170 committer, resume_commit_id, repo);
11171 if (error)
11172 goto done;
11174 yca_id = got_object_id_dup(resume_commit_id);
11175 if (yca_id == NULL) {
11176 error = got_error_from_errno("got_object_id_dup");
11177 goto done;
11179 } else {
11180 error = got_ref_open(&branch, repo, argv[0], 0);
11181 if (error != NULL)
11182 goto done;
11183 if (strncmp(got_ref_get_name(branch), "refs/heads/", 11) != 0) {
11184 error = got_error_msg(GOT_ERR_COMMIT_BRANCH,
11185 "will not rebase a branch which lives outside "
11186 "the \"refs/heads/\" reference namespace");
11187 goto done;
11191 error = got_ref_resolve(&branch_head_commit_id, repo, branch);
11192 if (error)
11193 goto done;
11195 if (!continue_rebase) {
11196 struct got_object_id *base_commit_id;
11198 error = got_ref_open(&head_ref, repo,
11199 got_worktree_get_head_ref_name(worktree), 0);
11200 if (error)
11201 goto done;
11202 error = got_ref_resolve(&head_commit_id, repo, head_ref);
11203 if (error)
11204 goto done;
11205 base_commit_id = got_worktree_get_base_commit_id(worktree);
11206 if (got_object_id_cmp(base_commit_id, head_commit_id) != 0) {
11207 error = got_error(GOT_ERR_REBASE_OUT_OF_DATE);
11208 goto done;
11211 error = got_commit_graph_find_youngest_common_ancestor(&yca_id,
11212 base_commit_id, branch_head_commit_id, 1, repo,
11213 check_cancelled, NULL);
11214 if (error) {
11215 if (error->code == GOT_ERR_ANCESTRY) {
11216 error = got_error_msg(GOT_ERR_ANCESTRY,
11217 "specified branch shares no common "
11218 "ancestry with work tree's branch");
11220 goto done;
11223 error = check_same_branch(base_commit_id, branch, yca_id, repo);
11224 if (error) {
11225 if (error->code != GOT_ERR_ANCESTRY)
11226 goto done;
11227 error = NULL;
11228 } else {
11229 struct got_pathlist_head paths;
11230 printf("%s is already based on %s\n",
11231 got_ref_get_name(branch),
11232 got_worktree_get_head_ref_name(worktree));
11233 error = switch_head_ref(branch, branch_head_commit_id,
11234 worktree, repo);
11235 if (error)
11236 goto done;
11237 error = got_worktree_set_base_commit_id(worktree, repo,
11238 branch_head_commit_id);
11239 if (error)
11240 goto done;
11241 TAILQ_INIT(&paths);
11242 error = got_pathlist_append(&paths, "", NULL);
11243 if (error)
11244 goto done;
11245 error = got_worktree_checkout_files(worktree,
11246 &paths, repo, update_progress, &upa,
11247 check_cancelled, NULL);
11248 got_pathlist_free(&paths, GOT_PATHLIST_FREE_NONE);
11249 if (error)
11250 goto done;
11251 if (upa.did_something) {
11252 char *id_str;
11253 error = got_object_id_str(&id_str,
11254 branch_head_commit_id);
11255 if (error)
11256 goto done;
11257 printf("Updated to %s: %s\n",
11258 got_worktree_get_head_ref_name(worktree),
11259 id_str);
11260 free(id_str);
11261 } else
11262 printf("Already up-to-date\n");
11263 print_update_progress_stats(&upa);
11264 goto done;
11268 commit_id = branch_head_commit_id;
11269 error = got_object_open_as_commit(&commit, repo, commit_id);
11270 if (error)
11271 goto done;
11273 parent_ids = got_object_commit_get_parent_ids(commit);
11274 pid = STAILQ_FIRST(parent_ids);
11275 if (pid) {
11276 error = collect_commits(&commits, commit_id, &pid->id,
11277 yca_id, got_worktree_get_path_prefix(worktree),
11278 GOT_ERR_REBASE_PATH, repo);
11279 if (error)
11280 goto done;
11283 got_object_commit_close(commit);
11284 commit = NULL;
11286 if (!continue_rebase) {
11287 error = got_worktree_rebase_prepare(&new_base_branch,
11288 &tmp_branch, &fileindex, worktree, branch, repo);
11289 if (error)
11290 goto done;
11293 if (STAILQ_EMPTY(&commits)) {
11294 if (continue_rebase) {
11295 error = rebase_complete(worktree, fileindex,
11296 branch, tmp_branch, repo, create_backup);
11297 goto done;
11298 } else {
11299 /* Fast-forward the reference of the branch. */
11300 struct got_object_id *new_head_commit_id;
11301 char *id_str;
11302 error = got_ref_resolve(&new_head_commit_id, repo,
11303 new_base_branch);
11304 if (error)
11305 goto done;
11306 error = got_object_id_str(&id_str, new_head_commit_id);
11307 if (error)
11308 goto done;
11309 printf("Forwarding %s to commit %s\n",
11310 got_ref_get_name(branch), id_str);
11311 free(id_str);
11312 error = got_ref_change_ref(branch,
11313 new_head_commit_id);
11314 if (error)
11315 goto done;
11316 /* No backup needed since objects did not change. */
11317 create_backup = 0;
11321 pid = NULL;
11322 STAILQ_FOREACH(qid, &commits, entry) {
11324 commit_id = &qid->id;
11325 parent_id = pid ? &pid->id : yca_id;
11326 pid = qid;
11328 memset(&upa, 0, sizeof(upa));
11329 error = got_worktree_rebase_merge_files(&merged_paths,
11330 worktree, fileindex, parent_id, commit_id, repo,
11331 update_progress, &upa, check_cancelled, NULL);
11332 if (error)
11333 goto done;
11335 print_merge_progress_stats(&upa);
11336 if (upa.conflicts > 0 || upa.missing > 0 ||
11337 upa.not_deleted > 0 || upa.unversioned > 0) {
11338 if (upa.conflicts > 0) {
11339 error = show_rebase_merge_conflict(&qid->id,
11340 repo);
11341 if (error)
11342 goto done;
11344 got_pathlist_free(&merged_paths, GOT_PATHLIST_FREE_PATH);
11345 break;
11348 error = rebase_commit(&merged_paths, worktree, fileindex,
11349 tmp_branch, committer, commit_id, repo);
11350 got_pathlist_free(&merged_paths, GOT_PATHLIST_FREE_PATH);
11351 if (error)
11352 goto done;
11355 if (upa.conflicts > 0 || upa.missing > 0 ||
11356 upa.not_deleted > 0 || upa.unversioned > 0) {
11357 error = got_worktree_rebase_postpone(worktree, fileindex);
11358 if (error)
11359 goto done;
11360 if (upa.conflicts > 0 && upa.missing == 0 &&
11361 upa.not_deleted == 0 && upa.unversioned == 0) {
11362 error = got_error_msg(GOT_ERR_CONFLICTS,
11363 "conflicts must be resolved before rebasing "
11364 "can continue");
11365 } else if (upa.conflicts > 0) {
11366 error = got_error_msg(GOT_ERR_CONFLICTS,
11367 "conflicts must be resolved before rebasing "
11368 "can continue; changes destined for some "
11369 "files were not yet merged and should be "
11370 "merged manually if required before the "
11371 "rebase operation is continued");
11372 } else {
11373 error = got_error_msg(GOT_ERR_CONFLICTS,
11374 "changes destined for some files were not "
11375 "yet merged and should be merged manually "
11376 "if required before the rebase operation "
11377 "is continued");
11379 } else
11380 error = rebase_complete(worktree, fileindex, branch,
11381 tmp_branch, repo, create_backup);
11382 done:
11383 free(cwd);
11384 free(committer);
11385 free(gitconfig_path);
11386 got_object_id_queue_free(&commits);
11387 free(branch_head_commit_id);
11388 free(resume_commit_id);
11389 free(head_commit_id);
11390 free(yca_id);
11391 if (commit)
11392 got_object_commit_close(commit);
11393 if (branch)
11394 got_ref_close(branch);
11395 if (new_base_branch)
11396 got_ref_close(new_base_branch);
11397 if (tmp_branch)
11398 got_ref_close(tmp_branch);
11399 if (head_ref)
11400 got_ref_close(head_ref);
11401 if (worktree)
11402 got_worktree_close(worktree);
11403 if (repo) {
11404 const struct got_error *close_err = got_repo_close(repo);
11405 if (error == NULL)
11406 error = close_err;
11408 if (pack_fds) {
11409 const struct got_error *pack_err =
11410 got_repo_pack_fds_close(pack_fds);
11411 if (error == NULL)
11412 error = pack_err;
11414 return error;
11417 __dead static void
11418 usage_histedit(void)
11420 fprintf(stderr, "usage: %s histedit [-acdeflmX] [-F histedit-script] "
11421 "[branch]\n", getprogname());
11422 exit(1);
11425 #define GOT_HISTEDIT_PICK 'p'
11426 #define GOT_HISTEDIT_EDIT 'e'
11427 #define GOT_HISTEDIT_FOLD 'f'
11428 #define GOT_HISTEDIT_DROP 'd'
11429 #define GOT_HISTEDIT_MESG 'm'
11431 static const struct got_histedit_cmd {
11432 unsigned char code;
11433 const char *name;
11434 const char *desc;
11435 } got_histedit_cmds[] = {
11436 { GOT_HISTEDIT_PICK, "pick", "use commit" },
11437 { GOT_HISTEDIT_EDIT, "edit", "use commit but stop for amending" },
11438 { GOT_HISTEDIT_FOLD, "fold", "combine with next commit that will "
11439 "be used" },
11440 { GOT_HISTEDIT_DROP, "drop", "remove commit from history" },
11441 { GOT_HISTEDIT_MESG, "mesg",
11442 "single-line log message for commit above (open editor if empty)" },
11445 struct got_histedit_list_entry {
11446 TAILQ_ENTRY(got_histedit_list_entry) entry;
11447 struct got_object_id *commit_id;
11448 const struct got_histedit_cmd *cmd;
11449 char *logmsg;
11451 TAILQ_HEAD(got_histedit_list, got_histedit_list_entry);
11453 static const struct got_error *
11454 histedit_write_commit(struct got_object_id *commit_id, const char *cmdname,
11455 FILE *f, struct got_repository *repo)
11457 const struct got_error *err = NULL;
11458 char *logmsg = NULL, *id_str = NULL;
11459 struct got_commit_object *commit = NULL;
11460 int n;
11462 err = got_object_open_as_commit(&commit, repo, commit_id);
11463 if (err)
11464 goto done;
11466 err = get_short_logmsg(&logmsg, 34, commit);
11467 if (err)
11468 goto done;
11470 err = got_object_id_str(&id_str, commit_id);
11471 if (err)
11472 goto done;
11474 n = fprintf(f, "%s %s %s\n", cmdname, id_str, logmsg);
11475 if (n < 0)
11476 err = got_ferror(f, GOT_ERR_IO);
11477 done:
11478 if (commit)
11479 got_object_commit_close(commit);
11480 free(id_str);
11481 free(logmsg);
11482 return err;
11485 static const struct got_error *
11486 histedit_write_commit_list(struct got_object_id_queue *commits,
11487 FILE *f, int edit_logmsg_only, int fold_only, int drop_only,
11488 int edit_only, struct got_repository *repo)
11490 const struct got_error *err = NULL;
11491 struct got_object_qid *qid;
11492 const char *histedit_cmd = NULL;
11494 if (STAILQ_EMPTY(commits))
11495 return got_error(GOT_ERR_EMPTY_HISTEDIT);
11497 STAILQ_FOREACH(qid, commits, entry) {
11498 histedit_cmd = got_histedit_cmds[0].name;
11499 if (drop_only)
11500 histedit_cmd = "drop";
11501 else if (edit_only)
11502 histedit_cmd = "edit";
11503 else if (fold_only && STAILQ_NEXT(qid, entry) != NULL)
11504 histedit_cmd = "fold";
11505 err = histedit_write_commit(&qid->id, histedit_cmd, f, repo);
11506 if (err)
11507 break;
11508 if (edit_logmsg_only) {
11509 int n = fprintf(f, "%c\n", GOT_HISTEDIT_MESG);
11510 if (n < 0) {
11511 err = got_ferror(f, GOT_ERR_IO);
11512 break;
11517 return err;
11520 static const struct got_error *
11521 write_cmd_list(FILE *f, const char *branch_name,
11522 struct got_object_id_queue *commits)
11524 const struct got_error *err = NULL;
11525 size_t i;
11526 int n;
11527 char *id_str;
11528 struct got_object_qid *qid;
11530 qid = STAILQ_FIRST(commits);
11531 err = got_object_id_str(&id_str, &qid->id);
11532 if (err)
11533 return err;
11535 n = fprintf(f,
11536 "# Editing the history of branch '%s' starting at\n"
11537 "# commit %s\n"
11538 "# Commits will be processed in order from top to "
11539 "bottom of this file.\n", branch_name, id_str);
11540 if (n < 0) {
11541 err = got_ferror(f, GOT_ERR_IO);
11542 goto done;
11545 n = fprintf(f, "# Available histedit commands:\n");
11546 if (n < 0) {
11547 err = got_ferror(f, GOT_ERR_IO);
11548 goto done;
11551 for (i = 0; i < nitems(got_histedit_cmds); i++) {
11552 const struct got_histedit_cmd *cmd = &got_histedit_cmds[i];
11553 n = fprintf(f, "# %s (%c): %s\n", cmd->name, cmd->code,
11554 cmd->desc);
11555 if (n < 0) {
11556 err = got_ferror(f, GOT_ERR_IO);
11557 break;
11560 done:
11561 free(id_str);
11562 return err;
11565 static const struct got_error *
11566 histedit_syntax_error(int lineno)
11568 static char msg[42];
11569 int ret;
11571 ret = snprintf(msg, sizeof(msg), "histedit syntax error on line %d",
11572 lineno);
11573 if (ret < 0 || (size_t)ret >= sizeof(msg))
11574 return got_error(GOT_ERR_HISTEDIT_SYNTAX);
11576 return got_error_msg(GOT_ERR_HISTEDIT_SYNTAX, msg);
11579 static const struct got_error *
11580 append_folded_commit_msg(char **new_msg, struct got_histedit_list_entry *hle,
11581 char *logmsg, struct got_repository *repo)
11583 const struct got_error *err;
11584 struct got_commit_object *folded_commit = NULL;
11585 char *id_str, *folded_logmsg = NULL;
11587 err = got_object_id_str(&id_str, hle->commit_id);
11588 if (err)
11589 return err;
11591 err = got_object_open_as_commit(&folded_commit, repo, hle->commit_id);
11592 if (err)
11593 goto done;
11595 err = got_object_commit_get_logmsg(&folded_logmsg, folded_commit);
11596 if (err)
11597 goto done;
11598 if (asprintf(new_msg, "%s%s# log message of folded commit %s: %s",
11599 logmsg ? logmsg : "", logmsg ? "\n" : "", id_str,
11600 folded_logmsg) == -1) {
11601 err = got_error_from_errno("asprintf");
11603 done:
11604 if (folded_commit)
11605 got_object_commit_close(folded_commit);
11606 free(id_str);
11607 free(folded_logmsg);
11608 return err;
11611 static struct got_histedit_list_entry *
11612 get_folded_commits(struct got_histedit_list_entry *hle)
11614 struct got_histedit_list_entry *prev, *folded = NULL;
11616 prev = TAILQ_PREV(hle, got_histedit_list, entry);
11617 while (prev && (prev->cmd->code == GOT_HISTEDIT_FOLD ||
11618 prev->cmd->code == GOT_HISTEDIT_DROP)) {
11619 if (prev->cmd->code == GOT_HISTEDIT_FOLD)
11620 folded = prev;
11621 prev = TAILQ_PREV(prev, got_histedit_list, entry);
11624 return folded;
11627 static const struct got_error *
11628 histedit_edit_logmsg(struct got_histedit_list_entry *hle,
11629 struct got_repository *repo)
11631 char *logmsg_path = NULL, *id_str = NULL, *orig_logmsg = NULL;
11632 char *logmsg = NULL, *new_msg = NULL, *editor = NULL;
11633 const struct got_error *err = NULL;
11634 struct got_commit_object *commit = NULL;
11635 int logmsg_len;
11636 int fd;
11637 struct got_histedit_list_entry *folded = NULL;
11639 err = got_object_open_as_commit(&commit, repo, hle->commit_id);
11640 if (err)
11641 return err;
11643 folded = get_folded_commits(hle);
11644 if (folded) {
11645 while (folded != hle) {
11646 if (folded->cmd->code == GOT_HISTEDIT_DROP) {
11647 folded = TAILQ_NEXT(folded, entry);
11648 continue;
11650 err = append_folded_commit_msg(&new_msg, folded,
11651 logmsg, repo);
11652 if (err)
11653 goto done;
11654 free(logmsg);
11655 logmsg = new_msg;
11656 folded = TAILQ_NEXT(folded, entry);
11660 err = got_object_id_str(&id_str, hle->commit_id);
11661 if (err)
11662 goto done;
11663 err = got_object_commit_get_logmsg(&orig_logmsg, commit);
11664 if (err)
11665 goto done;
11666 logmsg_len = asprintf(&new_msg,
11667 "%s\n# original log message of commit %s: %s",
11668 logmsg ? logmsg : "", id_str, orig_logmsg);
11669 if (logmsg_len == -1) {
11670 err = got_error_from_errno("asprintf");
11671 goto done;
11673 free(logmsg);
11674 logmsg = new_msg;
11676 err = got_object_id_str(&id_str, hle->commit_id);
11677 if (err)
11678 goto done;
11680 err = got_opentemp_named_fd(&logmsg_path, &fd,
11681 GOT_TMPDIR_STR "/got-logmsg", "");
11682 if (err)
11683 goto done;
11685 write(fd, logmsg, logmsg_len);
11686 close(fd);
11688 err = get_editor(&editor);
11689 if (err)
11690 goto done;
11692 err = edit_logmsg(&hle->logmsg, editor, logmsg_path, logmsg,
11693 logmsg_len, 0);
11694 if (err) {
11695 if (err->code != GOT_ERR_COMMIT_MSG_EMPTY)
11696 goto done;
11697 err = NULL;
11698 hle->logmsg = strdup(new_msg);
11699 if (hle->logmsg == NULL)
11700 err = got_error_from_errno("strdup");
11702 done:
11703 if (logmsg_path && unlink(logmsg_path) != 0 && err == NULL)
11704 err = got_error_from_errno2("unlink", logmsg_path);
11705 free(logmsg_path);
11706 free(logmsg);
11707 free(orig_logmsg);
11708 free(editor);
11709 if (commit)
11710 got_object_commit_close(commit);
11711 return err;
11714 static const struct got_error *
11715 histedit_parse_list(struct got_histedit_list *histedit_cmds,
11716 FILE *f, struct got_repository *repo)
11718 const struct got_error *err = NULL;
11719 char *line = NULL, *p, *end;
11720 size_t i, size;
11721 ssize_t len;
11722 int lineno = 0, lastcmd = -1;
11723 const struct got_histedit_cmd *cmd;
11724 struct got_object_id *commit_id = NULL;
11725 struct got_histedit_list_entry *hle = NULL;
11727 for (;;) {
11728 len = getline(&line, &size, f);
11729 if (len == -1) {
11730 const struct got_error *getline_err;
11731 if (feof(f))
11732 break;
11733 getline_err = got_error_from_errno("getline");
11734 err = got_ferror(f, getline_err->code);
11735 break;
11737 lineno++;
11738 p = line;
11739 while (isspace((unsigned char)p[0]))
11740 p++;
11741 if (p[0] == '#' || p[0] == '\0') {
11742 free(line);
11743 line = NULL;
11744 continue;
11746 cmd = NULL;
11747 for (i = 0; i < nitems(got_histedit_cmds); i++) {
11748 cmd = &got_histedit_cmds[i];
11749 if (strncmp(cmd->name, p, strlen(cmd->name)) == 0 &&
11750 isspace((unsigned char)p[strlen(cmd->name)])) {
11751 p += strlen(cmd->name);
11752 break;
11754 if (p[0] == cmd->code && isspace((unsigned char)p[1])) {
11755 p++;
11756 break;
11759 if (i == nitems(got_histedit_cmds)) {
11760 err = histedit_syntax_error(lineno);
11761 break;
11763 while (isspace((unsigned char)p[0]))
11764 p++;
11765 if (cmd->code == GOT_HISTEDIT_MESG) {
11766 if (lastcmd != GOT_HISTEDIT_PICK &&
11767 lastcmd != GOT_HISTEDIT_EDIT) {
11768 err = got_error(GOT_ERR_HISTEDIT_CMD);
11769 break;
11771 if (p[0] == '\0') {
11772 err = histedit_edit_logmsg(hle, repo);
11773 if (err)
11774 break;
11775 } else {
11776 hle->logmsg = strdup(p);
11777 if (hle->logmsg == NULL) {
11778 err = got_error_from_errno("strdup");
11779 break;
11782 free(line);
11783 line = NULL;
11784 lastcmd = cmd->code;
11785 continue;
11786 } else {
11787 end = p;
11788 while (end[0] && !isspace((unsigned char)end[0]))
11789 end++;
11790 *end = '\0';
11792 err = got_object_resolve_id_str(&commit_id, repo, p);
11793 if (err) {
11794 /* override error code */
11795 err = histedit_syntax_error(lineno);
11796 break;
11799 hle = malloc(sizeof(*hle));
11800 if (hle == NULL) {
11801 err = got_error_from_errno("malloc");
11802 break;
11804 hle->cmd = cmd;
11805 hle->commit_id = commit_id;
11806 hle->logmsg = NULL;
11807 commit_id = NULL;
11808 free(line);
11809 line = NULL;
11810 TAILQ_INSERT_TAIL(histedit_cmds, hle, entry);
11811 lastcmd = cmd->code;
11814 free(line);
11815 free(commit_id);
11816 return err;
11819 static const struct got_error *
11820 histedit_check_script(struct got_histedit_list *histedit_cmds,
11821 struct got_object_id_queue *commits, struct got_repository *repo)
11823 const struct got_error *err = NULL;
11824 struct got_object_qid *qid;
11825 struct got_histedit_list_entry *hle;
11826 static char msg[92];
11827 char *id_str;
11829 if (TAILQ_EMPTY(histedit_cmds))
11830 return got_error_msg(GOT_ERR_EMPTY_HISTEDIT,
11831 "histedit script contains no commands");
11832 if (STAILQ_EMPTY(commits))
11833 return got_error(GOT_ERR_EMPTY_HISTEDIT);
11835 TAILQ_FOREACH(hle, histedit_cmds, entry) {
11836 struct got_histedit_list_entry *hle2;
11837 TAILQ_FOREACH(hle2, histedit_cmds, entry) {
11838 if (hle == hle2)
11839 continue;
11840 if (got_object_id_cmp(hle->commit_id,
11841 hle2->commit_id) != 0)
11842 continue;
11843 err = got_object_id_str(&id_str, hle->commit_id);
11844 if (err)
11845 return err;
11846 snprintf(msg, sizeof(msg), "commit %s is listed "
11847 "more than once in histedit script", id_str);
11848 free(id_str);
11849 return got_error_msg(GOT_ERR_HISTEDIT_CMD, msg);
11853 STAILQ_FOREACH(qid, commits, entry) {
11854 TAILQ_FOREACH(hle, histedit_cmds, entry) {
11855 if (got_object_id_cmp(&qid->id, hle->commit_id) == 0)
11856 break;
11858 if (hle == NULL) {
11859 err = got_object_id_str(&id_str, &qid->id);
11860 if (err)
11861 return err;
11862 snprintf(msg, sizeof(msg),
11863 "commit %s missing from histedit script", id_str);
11864 free(id_str);
11865 return got_error_msg(GOT_ERR_HISTEDIT_CMD, msg);
11869 hle = TAILQ_LAST(histedit_cmds, got_histedit_list);
11870 if (hle && hle->cmd->code == GOT_HISTEDIT_FOLD)
11871 return got_error_msg(GOT_ERR_HISTEDIT_CMD,
11872 "last commit in histedit script cannot be folded");
11874 return NULL;
11877 static const struct got_error *
11878 histedit_run_editor(struct got_histedit_list *histedit_cmds,
11879 const char *path, struct got_object_id_queue *commits,
11880 struct got_repository *repo)
11882 const struct got_error *err = NULL;
11883 char *editor;
11884 FILE *f = NULL;
11886 err = get_editor(&editor);
11887 if (err)
11888 return err;
11890 if (spawn_editor(editor, path) == -1) {
11891 err = got_error_from_errno("failed spawning editor");
11892 goto done;
11895 f = fopen(path, "re");
11896 if (f == NULL) {
11897 err = got_error_from_errno("fopen");
11898 goto done;
11900 err = histedit_parse_list(histedit_cmds, f, repo);
11901 if (err)
11902 goto done;
11904 err = histedit_check_script(histedit_cmds, commits, repo);
11905 done:
11906 if (f && fclose(f) == EOF && err == NULL)
11907 err = got_error_from_errno("fclose");
11908 free(editor);
11909 return err;
11912 static const struct got_error *
11913 histedit_edit_list_retry(struct got_histedit_list *, const struct got_error *,
11914 struct got_object_id_queue *, const char *, const char *,
11915 struct got_repository *);
11917 static const struct got_error *
11918 histedit_edit_script(struct got_histedit_list *histedit_cmds,
11919 struct got_object_id_queue *commits, const char *branch_name,
11920 int edit_logmsg_only, int fold_only, int drop_only, int edit_only,
11921 struct got_repository *repo)
11923 const struct got_error *err;
11924 FILE *f = NULL;
11925 char *path = NULL;
11927 err = got_opentemp_named(&path, &f, "got-histedit", "");
11928 if (err)
11929 return err;
11931 err = write_cmd_list(f, branch_name, commits);
11932 if (err)
11933 goto done;
11935 err = histedit_write_commit_list(commits, f, edit_logmsg_only,
11936 fold_only, drop_only, edit_only, repo);
11937 if (err)
11938 goto done;
11940 if (drop_only || edit_logmsg_only || fold_only || edit_only) {
11941 rewind(f);
11942 err = histedit_parse_list(histedit_cmds, f, repo);
11943 } else {
11944 if (fclose(f) == EOF) {
11945 err = got_error_from_errno("fclose");
11946 goto done;
11948 f = NULL;
11949 err = histedit_run_editor(histedit_cmds, path, commits, repo);
11950 if (err) {
11951 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
11952 err->code != GOT_ERR_HISTEDIT_CMD)
11953 goto done;
11954 err = histedit_edit_list_retry(histedit_cmds, err,
11955 commits, path, branch_name, repo);
11958 done:
11959 if (f && fclose(f) == EOF && err == NULL)
11960 err = got_error_from_errno("fclose");
11961 if (path && unlink(path) != 0 && err == NULL)
11962 err = got_error_from_errno2("unlink", path);
11963 free(path);
11964 return err;
11967 static const struct got_error *
11968 histedit_save_list(struct got_histedit_list *histedit_cmds,
11969 struct got_worktree *worktree, struct got_repository *repo)
11971 const struct got_error *err = NULL;
11972 char *path = NULL;
11973 FILE *f = NULL;
11974 struct got_histedit_list_entry *hle;
11975 struct got_commit_object *commit = NULL;
11977 err = got_worktree_get_histedit_script_path(&path, worktree);
11978 if (err)
11979 return err;
11981 f = fopen(path, "we");
11982 if (f == NULL) {
11983 err = got_error_from_errno2("fopen", path);
11984 goto done;
11986 TAILQ_FOREACH(hle, histedit_cmds, entry) {
11987 err = histedit_write_commit(hle->commit_id, hle->cmd->name, f,
11988 repo);
11989 if (err)
11990 break;
11992 if (hle->logmsg) {
11993 int n = fprintf(f, "%c %s\n",
11994 GOT_HISTEDIT_MESG, hle->logmsg);
11995 if (n < 0) {
11996 err = got_ferror(f, GOT_ERR_IO);
11997 break;
12001 done:
12002 if (f && fclose(f) == EOF && err == NULL)
12003 err = got_error_from_errno("fclose");
12004 free(path);
12005 if (commit)
12006 got_object_commit_close(commit);
12007 return err;
12010 static void
12011 histedit_free_list(struct got_histedit_list *histedit_cmds)
12013 struct got_histedit_list_entry *hle;
12015 while ((hle = TAILQ_FIRST(histedit_cmds))) {
12016 TAILQ_REMOVE(histedit_cmds, hle, entry);
12017 free(hle);
12021 static const struct got_error *
12022 histedit_load_list(struct got_histedit_list *histedit_cmds,
12023 const char *path, struct got_repository *repo)
12025 const struct got_error *err = NULL;
12026 FILE *f = NULL;
12028 f = fopen(path, "re");
12029 if (f == NULL) {
12030 err = got_error_from_errno2("fopen", path);
12031 goto done;
12034 err = histedit_parse_list(histedit_cmds, f, repo);
12035 done:
12036 if (f && fclose(f) == EOF && err == NULL)
12037 err = got_error_from_errno("fclose");
12038 return err;
12041 static const struct got_error *
12042 histedit_edit_list_retry(struct got_histedit_list *histedit_cmds,
12043 const struct got_error *edit_err, struct got_object_id_queue *commits,
12044 const char *path, const char *branch_name, struct got_repository *repo)
12046 const struct got_error *err = NULL, *prev_err = edit_err;
12047 int resp = ' ';
12049 while (resp != 'c' && resp != 'r' && resp != 'a') {
12050 printf("%s: %s\n(c)ontinue editing, (r)estart editing, "
12051 "or (a)bort: ", getprogname(), prev_err->msg);
12052 resp = getchar();
12053 if (resp == '\n')
12054 resp = getchar();
12055 if (resp == 'c') {
12056 histedit_free_list(histedit_cmds);
12057 err = histedit_run_editor(histedit_cmds, path, commits,
12058 repo);
12059 if (err) {
12060 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
12061 err->code != GOT_ERR_HISTEDIT_CMD)
12062 break;
12063 prev_err = err;
12064 resp = ' ';
12065 continue;
12067 break;
12068 } else if (resp == 'r') {
12069 histedit_free_list(histedit_cmds);
12070 err = histedit_edit_script(histedit_cmds,
12071 commits, branch_name, 0, 0, 0, 0, repo);
12072 if (err) {
12073 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
12074 err->code != GOT_ERR_HISTEDIT_CMD)
12075 break;
12076 prev_err = err;
12077 resp = ' ';
12078 continue;
12080 break;
12081 } else if (resp == 'a') {
12082 err = got_error(GOT_ERR_HISTEDIT_CANCEL);
12083 break;
12084 } else
12085 printf("invalid response '%c'\n", resp);
12088 return err;
12091 static const struct got_error *
12092 histedit_complete(struct got_worktree *worktree,
12093 struct got_fileindex *fileindex, struct got_reference *tmp_branch,
12094 struct got_reference *branch, struct got_repository *repo)
12096 printf("Switching work tree to %s\n",
12097 got_ref_get_symref_target(branch));
12098 return got_worktree_histedit_complete(worktree, fileindex, tmp_branch,
12099 branch, repo);
12102 static const struct got_error *
12103 show_histedit_progress(struct got_commit_object *commit,
12104 struct got_histedit_list_entry *hle, struct got_object_id *new_id)
12106 const struct got_error *err;
12107 char *old_id_str = NULL, *new_id_str = NULL, *logmsg = NULL;
12109 err = got_object_id_str(&old_id_str, hle->commit_id);
12110 if (err)
12111 goto done;
12113 if (new_id) {
12114 err = got_object_id_str(&new_id_str, new_id);
12115 if (err)
12116 goto done;
12119 old_id_str[12] = '\0';
12120 if (new_id_str)
12121 new_id_str[12] = '\0';
12123 if (hle->logmsg) {
12124 logmsg = strdup(hle->logmsg);
12125 if (logmsg == NULL) {
12126 err = got_error_from_errno("strdup");
12127 goto done;
12129 trim_logmsg(logmsg, 42);
12130 } else {
12131 err = get_short_logmsg(&logmsg, 42, commit);
12132 if (err)
12133 goto done;
12136 switch (hle->cmd->code) {
12137 case GOT_HISTEDIT_PICK:
12138 case GOT_HISTEDIT_EDIT:
12139 printf("%s -> %s: %s\n", old_id_str,
12140 new_id_str ? new_id_str : "no-op change", logmsg);
12141 break;
12142 case GOT_HISTEDIT_DROP:
12143 case GOT_HISTEDIT_FOLD:
12144 printf("%s -> %s commit: %s\n", old_id_str, hle->cmd->name,
12145 logmsg);
12146 break;
12147 default:
12148 break;
12150 done:
12151 free(old_id_str);
12152 free(new_id_str);
12153 return err;
12156 static const struct got_error *
12157 histedit_commit(struct got_pathlist_head *merged_paths,
12158 struct got_worktree *worktree, struct got_fileindex *fileindex,
12159 struct got_reference *tmp_branch, struct got_histedit_list_entry *hle,
12160 const char *committer, struct got_repository *repo)
12162 const struct got_error *err;
12163 struct got_commit_object *commit;
12164 struct got_object_id *new_commit_id;
12166 if ((hle->cmd->code == GOT_HISTEDIT_EDIT || get_folded_commits(hle))
12167 && hle->logmsg == NULL) {
12168 err = histedit_edit_logmsg(hle, repo);
12169 if (err)
12170 return err;
12173 err = got_object_open_as_commit(&commit, repo, hle->commit_id);
12174 if (err)
12175 return err;
12177 err = got_worktree_histedit_commit(&new_commit_id, merged_paths,
12178 worktree, fileindex, tmp_branch, committer, commit, hle->commit_id,
12179 hle->logmsg, repo);
12180 if (err) {
12181 if (err->code != GOT_ERR_COMMIT_NO_CHANGES)
12182 goto done;
12183 err = show_histedit_progress(commit, hle, NULL);
12184 } else {
12185 err = show_histedit_progress(commit, hle, new_commit_id);
12186 free(new_commit_id);
12188 done:
12189 got_object_commit_close(commit);
12190 return err;
12193 static const struct got_error *
12194 histedit_skip_commit(struct got_histedit_list_entry *hle,
12195 struct got_worktree *worktree, struct got_repository *repo)
12197 const struct got_error *error;
12198 struct got_commit_object *commit;
12200 error = got_worktree_histedit_skip_commit(worktree, hle->commit_id,
12201 repo);
12202 if (error)
12203 return error;
12205 error = got_object_open_as_commit(&commit, repo, hle->commit_id);
12206 if (error)
12207 return error;
12209 error = show_histedit_progress(commit, hle, NULL);
12210 got_object_commit_close(commit);
12211 return error;
12214 static const struct got_error *
12215 check_local_changes(void *arg, unsigned char status,
12216 unsigned char staged_status, const char *path,
12217 struct got_object_id *blob_id, struct got_object_id *staged_blob_id,
12218 struct got_object_id *commit_id, int dirfd, const char *de_name)
12220 int *have_local_changes = arg;
12222 switch (status) {
12223 case GOT_STATUS_ADD:
12224 case GOT_STATUS_DELETE:
12225 case GOT_STATUS_MODIFY:
12226 case GOT_STATUS_CONFLICT:
12227 *have_local_changes = 1;
12228 return got_error(GOT_ERR_CANCELLED);
12229 default:
12230 break;
12233 switch (staged_status) {
12234 case GOT_STATUS_ADD:
12235 case GOT_STATUS_DELETE:
12236 case GOT_STATUS_MODIFY:
12237 *have_local_changes = 1;
12238 return got_error(GOT_ERR_CANCELLED);
12239 default:
12240 break;
12243 return NULL;
12246 static const struct got_error *
12247 cmd_histedit(int argc, char *argv[])
12249 const struct got_error *error = NULL;
12250 struct got_worktree *worktree = NULL;
12251 struct got_fileindex *fileindex = NULL;
12252 struct got_repository *repo = NULL;
12253 char *cwd = NULL, *committer = NULL, *gitconfig_path = NULL;
12254 struct got_reference *branch = NULL;
12255 struct got_reference *tmp_branch = NULL;
12256 struct got_object_id *resume_commit_id = NULL;
12257 struct got_object_id *base_commit_id = NULL;
12258 struct got_object_id *head_commit_id = NULL;
12259 struct got_commit_object *commit = NULL;
12260 int ch, rebase_in_progress = 0, merge_in_progress = 0;
12261 struct got_update_progress_arg upa;
12262 int edit_in_progress = 0, abort_edit = 0, continue_edit = 0;
12263 int drop_only = 0, edit_logmsg_only = 0, fold_only = 0, edit_only = 0;
12264 int list_backups = 0, delete_backups = 0;
12265 const char *edit_script_path = NULL;
12266 struct got_object_id_queue commits;
12267 struct got_pathlist_head merged_paths;
12268 const struct got_object_id_queue *parent_ids;
12269 struct got_object_qid *pid;
12270 struct got_histedit_list histedit_cmds;
12271 struct got_histedit_list_entry *hle;
12272 int *pack_fds = NULL;
12274 STAILQ_INIT(&commits);
12275 TAILQ_INIT(&histedit_cmds);
12276 TAILQ_INIT(&merged_paths);
12277 memset(&upa, 0, sizeof(upa));
12279 while ((ch = getopt(argc, argv, "acdeF:flmX")) != -1) {
12280 switch (ch) {
12281 case 'a':
12282 abort_edit = 1;
12283 break;
12284 case 'c':
12285 continue_edit = 1;
12286 break;
12287 case 'd':
12288 drop_only = 1;
12289 break;
12290 case 'e':
12291 edit_only = 1;
12292 break;
12293 case 'F':
12294 edit_script_path = optarg;
12295 break;
12296 case 'f':
12297 fold_only = 1;
12298 break;
12299 case 'l':
12300 list_backups = 1;
12301 break;
12302 case 'm':
12303 edit_logmsg_only = 1;
12304 break;
12305 case 'X':
12306 delete_backups = 1;
12307 break;
12308 default:
12309 usage_histedit();
12310 /* NOTREACHED */
12314 argc -= optind;
12315 argv += optind;
12317 #ifndef PROFILE
12318 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
12319 "unveil", NULL) == -1)
12320 err(1, "pledge");
12321 #endif
12322 if (abort_edit && continue_edit)
12323 option_conflict('a', 'c');
12324 if (edit_script_path && edit_logmsg_only)
12325 option_conflict('F', 'm');
12326 if (abort_edit && edit_logmsg_only)
12327 option_conflict('a', 'm');
12328 if (continue_edit && edit_logmsg_only)
12329 option_conflict('c', 'm');
12330 if (abort_edit && fold_only)
12331 option_conflict('a', 'f');
12332 if (continue_edit && fold_only)
12333 option_conflict('c', 'f');
12334 if (fold_only && edit_logmsg_only)
12335 option_conflict('f', 'm');
12336 if (edit_script_path && fold_only)
12337 option_conflict('F', 'f');
12338 if (abort_edit && edit_only)
12339 option_conflict('a', 'e');
12340 if (continue_edit && edit_only)
12341 option_conflict('c', 'e');
12342 if (edit_only && edit_logmsg_only)
12343 option_conflict('e', 'm');
12344 if (edit_script_path && edit_only)
12345 option_conflict('F', 'e');
12346 if (fold_only && edit_only)
12347 option_conflict('f', 'e');
12348 if (drop_only && abort_edit)
12349 option_conflict('d', 'a');
12350 if (drop_only && continue_edit)
12351 option_conflict('d', 'c');
12352 if (drop_only && edit_logmsg_only)
12353 option_conflict('d', 'm');
12354 if (drop_only && edit_only)
12355 option_conflict('d', 'e');
12356 if (drop_only && edit_script_path)
12357 option_conflict('d', 'F');
12358 if (drop_only && fold_only)
12359 option_conflict('d', 'f');
12360 if (list_backups) {
12361 if (abort_edit)
12362 option_conflict('l', 'a');
12363 if (continue_edit)
12364 option_conflict('l', 'c');
12365 if (edit_script_path)
12366 option_conflict('l', 'F');
12367 if (edit_logmsg_only)
12368 option_conflict('l', 'm');
12369 if (drop_only)
12370 option_conflict('l', 'd');
12371 if (fold_only)
12372 option_conflict('l', 'f');
12373 if (edit_only)
12374 option_conflict('l', 'e');
12375 if (delete_backups)
12376 option_conflict('l', 'X');
12377 if (argc != 0 && argc != 1)
12378 usage_histedit();
12379 } else if (delete_backups) {
12380 if (abort_edit)
12381 option_conflict('X', 'a');
12382 if (continue_edit)
12383 option_conflict('X', 'c');
12384 if (drop_only)
12385 option_conflict('X', 'd');
12386 if (edit_script_path)
12387 option_conflict('X', 'F');
12388 if (edit_logmsg_only)
12389 option_conflict('X', 'm');
12390 if (fold_only)
12391 option_conflict('X', 'f');
12392 if (edit_only)
12393 option_conflict('X', 'e');
12394 if (list_backups)
12395 option_conflict('X', 'l');
12396 if (argc != 0 && argc != 1)
12397 usage_histedit();
12398 } else if (argc != 0)
12399 usage_histedit();
12402 * This command cannot apply unveil(2) in all cases because the
12403 * user may choose to run an editor to edit the histedit script
12404 * and to edit individual commit log messages.
12405 * unveil(2) traverses exec(2); if an editor is used we have to
12406 * apply unveil after edit script and log messages have been written.
12407 * XXX TODO: Make use of unveil(2) where possible.
12410 cwd = getcwd(NULL, 0);
12411 if (cwd == NULL) {
12412 error = got_error_from_errno("getcwd");
12413 goto done;
12416 error = got_repo_pack_fds_open(&pack_fds);
12417 if (error != NULL)
12418 goto done;
12420 error = got_worktree_open(&worktree, cwd);
12421 if (error) {
12422 if (list_backups || delete_backups) {
12423 if (error->code != GOT_ERR_NOT_WORKTREE)
12424 goto done;
12425 } else {
12426 if (error->code == GOT_ERR_NOT_WORKTREE)
12427 error = wrap_not_worktree_error(error,
12428 "histedit", cwd);
12429 goto done;
12433 if (list_backups || delete_backups) {
12434 error = got_repo_open(&repo,
12435 worktree ? got_worktree_get_repo_path(worktree) : cwd,
12436 NULL, pack_fds);
12437 if (error != NULL)
12438 goto done;
12439 error = apply_unveil(got_repo_get_path(repo), 0,
12440 worktree ? got_worktree_get_root_path(worktree) : NULL);
12441 if (error)
12442 goto done;
12443 error = process_backup_refs(
12444 GOT_WORKTREE_HISTEDIT_BACKUP_REF_PREFIX,
12445 argc == 1 ? argv[0] : NULL, delete_backups, repo);
12446 goto done; /* nothing else to do */
12449 error = get_gitconfig_path(&gitconfig_path);
12450 if (error)
12451 goto done;
12452 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
12453 gitconfig_path, pack_fds);
12454 if (error != NULL)
12455 goto done;
12457 if (worktree != NULL && !list_backups && !delete_backups) {
12458 error = worktree_has_logmsg_ref("histedit", worktree, repo);
12459 if (error)
12460 goto done;
12463 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
12464 if (error)
12465 goto done;
12466 if (rebase_in_progress) {
12467 error = got_error(GOT_ERR_REBASING);
12468 goto done;
12471 error = got_worktree_merge_in_progress(&merge_in_progress, worktree,
12472 repo);
12473 if (error)
12474 goto done;
12475 if (merge_in_progress) {
12476 error = got_error(GOT_ERR_MERGE_BUSY);
12477 goto done;
12480 error = got_worktree_histedit_in_progress(&edit_in_progress, worktree);
12481 if (error)
12482 goto done;
12484 if (edit_in_progress && edit_logmsg_only) {
12485 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
12486 "histedit operation is in progress in this "
12487 "work tree and must be continued or aborted "
12488 "before the -m option can be used");
12489 goto done;
12491 if (edit_in_progress && drop_only) {
12492 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
12493 "histedit operation is in progress in this "
12494 "work tree and must be continued or aborted "
12495 "before the -d option can be used");
12496 goto done;
12498 if (edit_in_progress && fold_only) {
12499 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
12500 "histedit operation is in progress in this "
12501 "work tree and must be continued or aborted "
12502 "before the -f option can be used");
12503 goto done;
12505 if (edit_in_progress && edit_only) {
12506 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
12507 "histedit operation is in progress in this "
12508 "work tree and must be continued or aborted "
12509 "before the -e option can be used");
12510 goto done;
12513 if (edit_in_progress && abort_edit) {
12514 error = got_worktree_histedit_continue(&resume_commit_id,
12515 &tmp_branch, &branch, &base_commit_id, &fileindex,
12516 worktree, repo);
12517 if (error)
12518 goto done;
12519 printf("Switching work tree to %s\n",
12520 got_ref_get_symref_target(branch));
12521 error = got_worktree_histedit_abort(worktree, fileindex, repo,
12522 branch, base_commit_id, abort_progress, &upa);
12523 if (error)
12524 goto done;
12525 printf("Histedit of %s aborted\n",
12526 got_ref_get_symref_target(branch));
12527 print_merge_progress_stats(&upa);
12528 goto done; /* nothing else to do */
12529 } else if (abort_edit) {
12530 error = got_error(GOT_ERR_NOT_HISTEDIT);
12531 goto done;
12534 error = get_author(&committer, repo, worktree);
12535 if (error)
12536 goto done;
12538 if (continue_edit) {
12539 char *path;
12541 if (!edit_in_progress) {
12542 error = got_error(GOT_ERR_NOT_HISTEDIT);
12543 goto done;
12546 error = got_worktree_get_histedit_script_path(&path, worktree);
12547 if (error)
12548 goto done;
12550 error = histedit_load_list(&histedit_cmds, path, repo);
12551 free(path);
12552 if (error)
12553 goto done;
12555 error = got_worktree_histedit_continue(&resume_commit_id,
12556 &tmp_branch, &branch, &base_commit_id, &fileindex,
12557 worktree, repo);
12558 if (error)
12559 goto done;
12561 error = got_ref_resolve(&head_commit_id, repo, branch);
12562 if (error)
12563 goto done;
12565 error = got_object_open_as_commit(&commit, repo,
12566 head_commit_id);
12567 if (error)
12568 goto done;
12569 parent_ids = got_object_commit_get_parent_ids(commit);
12570 pid = STAILQ_FIRST(parent_ids);
12571 if (pid == NULL) {
12572 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
12573 goto done;
12575 error = collect_commits(&commits, head_commit_id, &pid->id,
12576 base_commit_id, got_worktree_get_path_prefix(worktree),
12577 GOT_ERR_HISTEDIT_PATH, repo);
12578 got_object_commit_close(commit);
12579 commit = NULL;
12580 if (error)
12581 goto done;
12582 } else {
12583 if (edit_in_progress) {
12584 error = got_error(GOT_ERR_HISTEDIT_BUSY);
12585 goto done;
12588 error = got_ref_open(&branch, repo,
12589 got_worktree_get_head_ref_name(worktree), 0);
12590 if (error != NULL)
12591 goto done;
12593 if (strncmp(got_ref_get_name(branch), "refs/heads/", 11) != 0) {
12594 error = got_error_msg(GOT_ERR_COMMIT_BRANCH,
12595 "will not edit commit history of a branch outside "
12596 "the \"refs/heads/\" reference namespace");
12597 goto done;
12600 error = got_ref_resolve(&head_commit_id, repo, branch);
12601 got_ref_close(branch);
12602 branch = NULL;
12603 if (error)
12604 goto done;
12606 error = got_object_open_as_commit(&commit, repo,
12607 head_commit_id);
12608 if (error)
12609 goto done;
12610 parent_ids = got_object_commit_get_parent_ids(commit);
12611 pid = STAILQ_FIRST(parent_ids);
12612 if (pid == NULL) {
12613 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
12614 goto done;
12616 error = collect_commits(&commits, head_commit_id, &pid->id,
12617 got_worktree_get_base_commit_id(worktree),
12618 got_worktree_get_path_prefix(worktree),
12619 GOT_ERR_HISTEDIT_PATH, repo);
12620 got_object_commit_close(commit);
12621 commit = NULL;
12622 if (error)
12623 goto done;
12625 if (STAILQ_EMPTY(&commits)) {
12626 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
12627 goto done;
12630 error = got_worktree_histedit_prepare(&tmp_branch, &branch,
12631 &base_commit_id, &fileindex, worktree, repo);
12632 if (error)
12633 goto done;
12635 if (edit_script_path) {
12636 error = histedit_load_list(&histedit_cmds,
12637 edit_script_path, repo);
12638 if (error) {
12639 got_worktree_histedit_abort(worktree, fileindex,
12640 repo, branch, base_commit_id,
12641 abort_progress, &upa);
12642 print_merge_progress_stats(&upa);
12643 goto done;
12645 } else {
12646 const char *branch_name;
12647 branch_name = got_ref_get_symref_target(branch);
12648 if (strncmp(branch_name, "refs/heads/", 11) == 0)
12649 branch_name += 11;
12650 error = histedit_edit_script(&histedit_cmds, &commits,
12651 branch_name, edit_logmsg_only, fold_only,
12652 drop_only, edit_only, repo);
12653 if (error) {
12654 got_worktree_histedit_abort(worktree, fileindex,
12655 repo, branch, base_commit_id,
12656 abort_progress, &upa);
12657 print_merge_progress_stats(&upa);
12658 goto done;
12663 error = histedit_save_list(&histedit_cmds, worktree,
12664 repo);
12665 if (error) {
12666 got_worktree_histedit_abort(worktree, fileindex,
12667 repo, branch, base_commit_id,
12668 abort_progress, &upa);
12669 print_merge_progress_stats(&upa);
12670 goto done;
12675 error = histedit_check_script(&histedit_cmds, &commits, repo);
12676 if (error)
12677 goto done;
12679 TAILQ_FOREACH(hle, &histedit_cmds, entry) {
12680 if (resume_commit_id) {
12681 if (got_object_id_cmp(hle->commit_id,
12682 resume_commit_id) != 0)
12683 continue;
12685 resume_commit_id = NULL;
12686 if (hle->cmd->code == GOT_HISTEDIT_DROP ||
12687 hle->cmd->code == GOT_HISTEDIT_FOLD) {
12688 error = histedit_skip_commit(hle, worktree,
12689 repo);
12690 if (error)
12691 goto done;
12692 } else {
12693 struct got_pathlist_head paths;
12694 int have_changes = 0;
12696 TAILQ_INIT(&paths);
12697 error = got_pathlist_append(&paths, "", NULL);
12698 if (error)
12699 goto done;
12700 error = got_worktree_status(worktree, &paths,
12701 repo, 0, check_local_changes, &have_changes,
12702 check_cancelled, NULL);
12703 got_pathlist_free(&paths,
12704 GOT_PATHLIST_FREE_NONE);
12705 if (error) {
12706 if (error->code != GOT_ERR_CANCELLED)
12707 goto done;
12708 if (sigint_received || sigpipe_received)
12709 goto done;
12711 if (have_changes) {
12712 error = histedit_commit(NULL, worktree,
12713 fileindex, tmp_branch, hle,
12714 committer, repo);
12715 if (error)
12716 goto done;
12717 } else {
12718 error = got_object_open_as_commit(
12719 &commit, repo, hle->commit_id);
12720 if (error)
12721 goto done;
12722 error = show_histedit_progress(commit,
12723 hle, NULL);
12724 got_object_commit_close(commit);
12725 commit = NULL;
12726 if (error)
12727 goto done;
12730 continue;
12733 if (hle->cmd->code == GOT_HISTEDIT_DROP) {
12734 error = histedit_skip_commit(hle, worktree, repo);
12735 if (error)
12736 goto done;
12737 continue;
12740 error = got_object_open_as_commit(&commit, repo,
12741 hle->commit_id);
12742 if (error)
12743 goto done;
12744 parent_ids = got_object_commit_get_parent_ids(commit);
12745 pid = STAILQ_FIRST(parent_ids);
12747 error = got_worktree_histedit_merge_files(&merged_paths,
12748 worktree, fileindex, &pid->id, hle->commit_id, repo,
12749 update_progress, &upa, check_cancelled, NULL);
12750 if (error)
12751 goto done;
12752 got_object_commit_close(commit);
12753 commit = NULL;
12755 print_merge_progress_stats(&upa);
12756 if (upa.conflicts > 0 || upa.missing > 0 ||
12757 upa.not_deleted > 0 || upa.unversioned > 0) {
12758 if (upa.conflicts > 0) {
12759 error = show_rebase_merge_conflict(
12760 hle->commit_id, repo);
12761 if (error)
12762 goto done;
12764 got_pathlist_free(&merged_paths, GOT_PATHLIST_FREE_PATH);
12765 break;
12768 if (hle->cmd->code == GOT_HISTEDIT_EDIT) {
12769 char *id_str;
12770 error = got_object_id_str(&id_str, hle->commit_id);
12771 if (error)
12772 goto done;
12773 printf("Stopping histedit for amending commit %s\n",
12774 id_str);
12775 free(id_str);
12776 got_pathlist_free(&merged_paths, GOT_PATHLIST_FREE_PATH);
12777 error = got_worktree_histedit_postpone(worktree,
12778 fileindex);
12779 goto done;
12782 if (hle->cmd->code == GOT_HISTEDIT_FOLD) {
12783 error = histedit_skip_commit(hle, worktree, repo);
12784 if (error)
12785 goto done;
12786 continue;
12789 error = histedit_commit(&merged_paths, worktree, fileindex,
12790 tmp_branch, hle, committer, repo);
12791 got_pathlist_free(&merged_paths, GOT_PATHLIST_FREE_PATH);
12792 if (error)
12793 goto done;
12796 if (upa.conflicts > 0 || upa.missing > 0 ||
12797 upa.not_deleted > 0 || upa.unversioned > 0) {
12798 error = got_worktree_histedit_postpone(worktree, fileindex);
12799 if (error)
12800 goto done;
12801 if (upa.conflicts > 0 && upa.missing == 0 &&
12802 upa.not_deleted == 0 && upa.unversioned == 0) {
12803 error = got_error_msg(GOT_ERR_CONFLICTS,
12804 "conflicts must be resolved before histedit "
12805 "can continue");
12806 } else if (upa.conflicts > 0) {
12807 error = got_error_msg(GOT_ERR_CONFLICTS,
12808 "conflicts must be resolved before histedit "
12809 "can continue; changes destined for some "
12810 "files were not yet merged and should be "
12811 "merged manually if required before the "
12812 "histedit operation is continued");
12813 } else {
12814 error = got_error_msg(GOT_ERR_CONFLICTS,
12815 "changes destined for some files were not "
12816 "yet merged and should be merged manually "
12817 "if required before the histedit operation "
12818 "is continued");
12820 } else
12821 error = histedit_complete(worktree, fileindex, tmp_branch,
12822 branch, repo);
12823 done:
12824 free(cwd);
12825 free(committer);
12826 free(gitconfig_path);
12827 got_object_id_queue_free(&commits);
12828 histedit_free_list(&histedit_cmds);
12829 free(head_commit_id);
12830 free(base_commit_id);
12831 free(resume_commit_id);
12832 if (commit)
12833 got_object_commit_close(commit);
12834 if (branch)
12835 got_ref_close(branch);
12836 if (tmp_branch)
12837 got_ref_close(tmp_branch);
12838 if (worktree)
12839 got_worktree_close(worktree);
12840 if (repo) {
12841 const struct got_error *close_err = got_repo_close(repo);
12842 if (error == NULL)
12843 error = close_err;
12845 if (pack_fds) {
12846 const struct got_error *pack_err =
12847 got_repo_pack_fds_close(pack_fds);
12848 if (error == NULL)
12849 error = pack_err;
12851 return error;
12854 __dead static void
12855 usage_integrate(void)
12857 fprintf(stderr, "usage: %s integrate branch\n", getprogname());
12858 exit(1);
12861 static const struct got_error *
12862 cmd_integrate(int argc, char *argv[])
12864 const struct got_error *error = NULL;
12865 struct got_repository *repo = NULL;
12866 struct got_worktree *worktree = NULL;
12867 char *cwd = NULL, *refname = NULL, *base_refname = NULL;
12868 const char *branch_arg = NULL;
12869 struct got_reference *branch_ref = NULL, *base_branch_ref = NULL;
12870 struct got_fileindex *fileindex = NULL;
12871 struct got_object_id *commit_id = NULL, *base_commit_id = NULL;
12872 int ch;
12873 struct got_update_progress_arg upa;
12874 int *pack_fds = NULL;
12876 while ((ch = getopt(argc, argv, "")) != -1) {
12877 switch (ch) {
12878 default:
12879 usage_integrate();
12880 /* NOTREACHED */
12884 argc -= optind;
12885 argv += optind;
12887 if (argc != 1)
12888 usage_integrate();
12889 branch_arg = argv[0];
12890 #ifndef PROFILE
12891 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
12892 "unveil", NULL) == -1)
12893 err(1, "pledge");
12894 #endif
12895 cwd = getcwd(NULL, 0);
12896 if (cwd == NULL) {
12897 error = got_error_from_errno("getcwd");
12898 goto done;
12901 error = got_repo_pack_fds_open(&pack_fds);
12902 if (error != NULL)
12903 goto done;
12905 error = got_worktree_open(&worktree, cwd);
12906 if (error) {
12907 if (error->code == GOT_ERR_NOT_WORKTREE)
12908 error = wrap_not_worktree_error(error, "integrate",
12909 cwd);
12910 goto done;
12913 error = check_rebase_or_histedit_in_progress(worktree);
12914 if (error)
12915 goto done;
12917 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
12918 NULL, pack_fds);
12919 if (error != NULL)
12920 goto done;
12922 error = apply_unveil(got_repo_get_path(repo), 0,
12923 got_worktree_get_root_path(worktree));
12924 if (error)
12925 goto done;
12927 error = check_merge_in_progress(worktree, repo);
12928 if (error)
12929 goto done;
12931 if (asprintf(&refname, "refs/heads/%s", branch_arg) == -1) {
12932 error = got_error_from_errno("asprintf");
12933 goto done;
12936 error = got_worktree_integrate_prepare(&fileindex, &branch_ref,
12937 &base_branch_ref, worktree, refname, repo);
12938 if (error)
12939 goto done;
12941 refname = strdup(got_ref_get_name(branch_ref));
12942 if (refname == NULL) {
12943 error = got_error_from_errno("strdup");
12944 got_worktree_integrate_abort(worktree, fileindex, repo,
12945 branch_ref, base_branch_ref);
12946 goto done;
12948 base_refname = strdup(got_ref_get_name(base_branch_ref));
12949 if (base_refname == NULL) {
12950 error = got_error_from_errno("strdup");
12951 got_worktree_integrate_abort(worktree, fileindex, repo,
12952 branch_ref, base_branch_ref);
12953 goto done;
12955 if (strncmp(base_refname, "refs/heads/", 11) != 0) {
12956 error = got_error(GOT_ERR_INTEGRATE_BRANCH);
12957 got_worktree_integrate_abort(worktree, fileindex, repo,
12958 branch_ref, base_branch_ref);
12959 goto done;
12962 error = got_ref_resolve(&commit_id, repo, branch_ref);
12963 if (error)
12964 goto done;
12966 error = got_ref_resolve(&base_commit_id, repo, base_branch_ref);
12967 if (error)
12968 goto done;
12970 if (got_object_id_cmp(commit_id, base_commit_id) == 0) {
12971 error = got_error_msg(GOT_ERR_SAME_BRANCH,
12972 "specified branch has already been integrated");
12973 got_worktree_integrate_abort(worktree, fileindex, repo,
12974 branch_ref, base_branch_ref);
12975 goto done;
12978 error = check_linear_ancestry(commit_id, base_commit_id, 1, repo);
12979 if (error) {
12980 if (error->code == GOT_ERR_ANCESTRY)
12981 error = got_error(GOT_ERR_REBASE_REQUIRED);
12982 got_worktree_integrate_abort(worktree, fileindex, repo,
12983 branch_ref, base_branch_ref);
12984 goto done;
12987 memset(&upa, 0, sizeof(upa));
12988 error = got_worktree_integrate_continue(worktree, fileindex, repo,
12989 branch_ref, base_branch_ref, update_progress, &upa,
12990 check_cancelled, NULL);
12991 if (error)
12992 goto done;
12994 printf("Integrated %s into %s\n", refname, base_refname);
12995 print_update_progress_stats(&upa);
12996 done:
12997 if (repo) {
12998 const struct got_error *close_err = got_repo_close(repo);
12999 if (error == NULL)
13000 error = close_err;
13002 if (worktree)
13003 got_worktree_close(worktree);
13004 if (pack_fds) {
13005 const struct got_error *pack_err =
13006 got_repo_pack_fds_close(pack_fds);
13007 if (error == NULL)
13008 error = pack_err;
13010 free(cwd);
13011 free(base_commit_id);
13012 free(commit_id);
13013 free(refname);
13014 free(base_refname);
13015 return error;
13018 __dead static void
13019 usage_merge(void)
13021 fprintf(stderr, "usage: %s merge [-acn] [branch]\n", getprogname());
13022 exit(1);
13025 static const struct got_error *
13026 cmd_merge(int argc, char *argv[])
13028 const struct got_error *error = NULL;
13029 struct got_worktree *worktree = NULL;
13030 struct got_repository *repo = NULL;
13031 struct got_fileindex *fileindex = NULL;
13032 char *cwd = NULL, *id_str = NULL, *author = NULL;
13033 struct got_reference *branch = NULL, *wt_branch = NULL;
13034 struct got_object_id *branch_tip = NULL, *yca_id = NULL;
13035 struct got_object_id *wt_branch_tip = NULL;
13036 int ch, merge_in_progress = 0, abort_merge = 0, continue_merge = 0;
13037 int interrupt_merge = 0;
13038 struct got_update_progress_arg upa;
13039 struct got_object_id *merge_commit_id = NULL;
13040 char *branch_name = NULL;
13041 int *pack_fds = NULL;
13043 memset(&upa, 0, sizeof(upa));
13045 while ((ch = getopt(argc, argv, "acn")) != -1) {
13046 switch (ch) {
13047 case 'a':
13048 abort_merge = 1;
13049 break;
13050 case 'c':
13051 continue_merge = 1;
13052 break;
13053 case 'n':
13054 interrupt_merge = 1;
13055 break;
13056 default:
13057 usage_merge();
13058 /* NOTREACHED */
13062 argc -= optind;
13063 argv += optind;
13065 #ifndef PROFILE
13066 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
13067 "unveil", NULL) == -1)
13068 err(1, "pledge");
13069 #endif
13071 if (abort_merge && continue_merge)
13072 option_conflict('a', 'c');
13073 if (abort_merge || continue_merge) {
13074 if (argc != 0)
13075 usage_merge();
13076 } else if (argc != 1)
13077 usage_merge();
13079 cwd = getcwd(NULL, 0);
13080 if (cwd == NULL) {
13081 error = got_error_from_errno("getcwd");
13082 goto done;
13085 error = got_repo_pack_fds_open(&pack_fds);
13086 if (error != NULL)
13087 goto done;
13089 error = got_worktree_open(&worktree, cwd);
13090 if (error) {
13091 if (error->code == GOT_ERR_NOT_WORKTREE)
13092 error = wrap_not_worktree_error(error,
13093 "merge", cwd);
13094 goto done;
13097 error = got_repo_open(&repo,
13098 worktree ? got_worktree_get_repo_path(worktree) : cwd, NULL,
13099 pack_fds);
13100 if (error != NULL)
13101 goto done;
13103 if (worktree != NULL) {
13104 error = worktree_has_logmsg_ref("merge", worktree, repo);
13105 if (error)
13106 goto done;
13109 error = apply_unveil(got_repo_get_path(repo), 0,
13110 worktree ? got_worktree_get_root_path(worktree) : NULL);
13111 if (error)
13112 goto done;
13114 error = check_rebase_or_histedit_in_progress(worktree);
13115 if (error)
13116 goto done;
13118 error = got_worktree_merge_in_progress(&merge_in_progress, worktree,
13119 repo);
13120 if (error)
13121 goto done;
13123 if (abort_merge) {
13124 if (!merge_in_progress) {
13125 error = got_error(GOT_ERR_NOT_MERGING);
13126 goto done;
13128 error = got_worktree_merge_continue(&branch_name,
13129 &branch_tip, &fileindex, worktree, repo);
13130 if (error)
13131 goto done;
13132 error = got_worktree_merge_abort(worktree, fileindex, repo,
13133 abort_progress, &upa);
13134 if (error)
13135 goto done;
13136 printf("Merge of %s aborted\n", branch_name);
13137 goto done; /* nothing else to do */
13140 error = get_author(&author, repo, worktree);
13141 if (error)
13142 goto done;
13144 if (continue_merge) {
13145 if (!merge_in_progress) {
13146 error = got_error(GOT_ERR_NOT_MERGING);
13147 goto done;
13149 error = got_worktree_merge_continue(&branch_name,
13150 &branch_tip, &fileindex, worktree, repo);
13151 if (error)
13152 goto done;
13153 } else {
13154 error = got_ref_open(&branch, repo, argv[0], 0);
13155 if (error != NULL)
13156 goto done;
13157 branch_name = strdup(got_ref_get_name(branch));
13158 if (branch_name == NULL) {
13159 error = got_error_from_errno("strdup");
13160 goto done;
13162 error = got_ref_resolve(&branch_tip, repo, branch);
13163 if (error)
13164 goto done;
13167 error = got_ref_open(&wt_branch, repo,
13168 got_worktree_get_head_ref_name(worktree), 0);
13169 if (error)
13170 goto done;
13171 error = got_ref_resolve(&wt_branch_tip, repo, wt_branch);
13172 if (error)
13173 goto done;
13174 error = got_commit_graph_find_youngest_common_ancestor(&yca_id,
13175 wt_branch_tip, branch_tip, 0, repo,
13176 check_cancelled, NULL);
13177 if (error && error->code != GOT_ERR_ANCESTRY)
13178 goto done;
13180 if (!continue_merge) {
13181 error = check_path_prefix(wt_branch_tip, branch_tip,
13182 got_worktree_get_path_prefix(worktree),
13183 GOT_ERR_MERGE_PATH, repo);
13184 if (error)
13185 goto done;
13186 if (yca_id) {
13187 error = check_same_branch(wt_branch_tip, branch,
13188 yca_id, repo);
13189 if (error) {
13190 if (error->code != GOT_ERR_ANCESTRY)
13191 goto done;
13192 error = NULL;
13193 } else {
13194 static char msg[512];
13195 snprintf(msg, sizeof(msg),
13196 "cannot create a merge commit because "
13197 "%s is based on %s; %s can be integrated "
13198 "with 'got integrate' instead", branch_name,
13199 got_worktree_get_head_ref_name(worktree),
13200 branch_name);
13201 error = got_error_msg(GOT_ERR_SAME_BRANCH, msg);
13202 goto done;
13205 error = got_worktree_merge_prepare(&fileindex, worktree,
13206 branch, repo);
13207 if (error)
13208 goto done;
13210 error = got_worktree_merge_branch(worktree, fileindex,
13211 yca_id, branch_tip, repo, update_progress, &upa,
13212 check_cancelled, NULL);
13213 if (error)
13214 goto done;
13215 print_merge_progress_stats(&upa);
13216 if (!upa.did_something) {
13217 error = got_worktree_merge_abort(worktree, fileindex,
13218 repo, abort_progress, &upa);
13219 if (error)
13220 goto done;
13221 printf("Already up-to-date\n");
13222 goto done;
13226 if (interrupt_merge) {
13227 error = got_worktree_merge_postpone(worktree, fileindex);
13228 if (error)
13229 goto done;
13230 printf("Merge of %s interrupted on request\n", branch_name);
13231 } else if (upa.conflicts > 0 || upa.missing > 0 ||
13232 upa.not_deleted > 0 || upa.unversioned > 0) {
13233 error = got_worktree_merge_postpone(worktree, fileindex);
13234 if (error)
13235 goto done;
13236 if (upa.conflicts > 0 && upa.missing == 0 &&
13237 upa.not_deleted == 0 && upa.unversioned == 0) {
13238 error = got_error_msg(GOT_ERR_CONFLICTS,
13239 "conflicts must be resolved before merging "
13240 "can continue");
13241 } else if (upa.conflicts > 0) {
13242 error = got_error_msg(GOT_ERR_CONFLICTS,
13243 "conflicts must be resolved before merging "
13244 "can continue; changes destined for some "
13245 "files were not yet merged and "
13246 "should be merged manually if required before the "
13247 "merge operation is continued");
13248 } else {
13249 error = got_error_msg(GOT_ERR_CONFLICTS,
13250 "changes destined for some "
13251 "files were not yet merged and should be "
13252 "merged manually if required before the "
13253 "merge operation is continued");
13255 goto done;
13256 } else {
13257 error = got_worktree_merge_commit(&merge_commit_id, worktree,
13258 fileindex, author, NULL, 1, branch_tip, branch_name,
13259 repo, continue_merge ? print_status : NULL, NULL);
13260 if (error)
13261 goto done;
13262 error = got_worktree_merge_complete(worktree, fileindex, repo);
13263 if (error)
13264 goto done;
13265 error = got_object_id_str(&id_str, merge_commit_id);
13266 if (error)
13267 goto done;
13268 printf("Merged %s into %s: %s\n", branch_name,
13269 got_worktree_get_head_ref_name(worktree),
13270 id_str);
13273 done:
13274 free(id_str);
13275 free(merge_commit_id);
13276 free(author);
13277 free(branch_tip);
13278 free(branch_name);
13279 free(yca_id);
13280 if (branch)
13281 got_ref_close(branch);
13282 if (wt_branch)
13283 got_ref_close(wt_branch);
13284 if (worktree)
13285 got_worktree_close(worktree);
13286 if (repo) {
13287 const struct got_error *close_err = got_repo_close(repo);
13288 if (error == NULL)
13289 error = close_err;
13291 if (pack_fds) {
13292 const struct got_error *pack_err =
13293 got_repo_pack_fds_close(pack_fds);
13294 if (error == NULL)
13295 error = pack_err;
13297 return error;
13300 __dead static void
13301 usage_stage(void)
13303 fprintf(stderr, "usage: %s stage [-lpS] [-F response-script] "
13304 "[path ...]\n", getprogname());
13305 exit(1);
13308 static const struct got_error *
13309 print_stage(void *arg, unsigned char status, unsigned char staged_status,
13310 const char *path, struct got_object_id *blob_id,
13311 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
13312 int dirfd, const char *de_name)
13314 const struct got_error *err = NULL;
13315 char *id_str = NULL;
13317 if (staged_status != GOT_STATUS_ADD &&
13318 staged_status != GOT_STATUS_MODIFY &&
13319 staged_status != GOT_STATUS_DELETE)
13320 return NULL;
13322 if (staged_status == GOT_STATUS_ADD ||
13323 staged_status == GOT_STATUS_MODIFY)
13324 err = got_object_id_str(&id_str, staged_blob_id);
13325 else
13326 err = got_object_id_str(&id_str, blob_id);
13327 if (err)
13328 return err;
13330 printf("%s %c %s\n", id_str, staged_status, path);
13331 free(id_str);
13332 return NULL;
13335 static const struct got_error *
13336 cmd_stage(int argc, char *argv[])
13338 const struct got_error *error = NULL;
13339 struct got_repository *repo = NULL;
13340 struct got_worktree *worktree = NULL;
13341 char *cwd = NULL;
13342 struct got_pathlist_head paths;
13343 int ch, list_stage = 0, pflag = 0, allow_bad_symlinks = 0;
13344 FILE *patch_script_file = NULL;
13345 const char *patch_script_path = NULL;
13346 struct choose_patch_arg cpa;
13347 int *pack_fds = NULL;
13349 TAILQ_INIT(&paths);
13351 while ((ch = getopt(argc, argv, "F:lpS")) != -1) {
13352 switch (ch) {
13353 case 'F':
13354 patch_script_path = optarg;
13355 break;
13356 case 'l':
13357 list_stage = 1;
13358 break;
13359 case 'p':
13360 pflag = 1;
13361 break;
13362 case 'S':
13363 allow_bad_symlinks = 1;
13364 break;
13365 default:
13366 usage_stage();
13367 /* NOTREACHED */
13371 argc -= optind;
13372 argv += optind;
13374 #ifndef PROFILE
13375 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
13376 "unveil", NULL) == -1)
13377 err(1, "pledge");
13378 #endif
13379 if (list_stage && (pflag || patch_script_path))
13380 errx(1, "-l option cannot be used with other options");
13381 if (patch_script_path && !pflag)
13382 errx(1, "-F option can only be used together with -p option");
13384 cwd = getcwd(NULL, 0);
13385 if (cwd == NULL) {
13386 error = got_error_from_errno("getcwd");
13387 goto done;
13390 error = got_repo_pack_fds_open(&pack_fds);
13391 if (error != NULL)
13392 goto done;
13394 error = got_worktree_open(&worktree, cwd);
13395 if (error) {
13396 if (error->code == GOT_ERR_NOT_WORKTREE)
13397 error = wrap_not_worktree_error(error, "stage", cwd);
13398 goto done;
13401 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
13402 NULL, pack_fds);
13403 if (error != NULL)
13404 goto done;
13406 if (patch_script_path) {
13407 patch_script_file = fopen(patch_script_path, "re");
13408 if (patch_script_file == NULL) {
13409 error = got_error_from_errno2("fopen",
13410 patch_script_path);
13411 goto done;
13414 error = apply_unveil(got_repo_get_path(repo), 0,
13415 got_worktree_get_root_path(worktree));
13416 if (error)
13417 goto done;
13419 error = check_merge_in_progress(worktree, repo);
13420 if (error)
13421 goto done;
13423 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
13424 if (error)
13425 goto done;
13427 if (list_stage)
13428 error = got_worktree_status(worktree, &paths, repo, 0,
13429 print_stage, NULL, check_cancelled, NULL);
13430 else {
13431 cpa.patch_script_file = patch_script_file;
13432 cpa.action = "stage";
13433 error = got_worktree_stage(worktree, &paths,
13434 pflag ? NULL : print_status, NULL,
13435 pflag ? choose_patch : NULL, &cpa,
13436 allow_bad_symlinks, repo);
13438 done:
13439 if (patch_script_file && fclose(patch_script_file) == EOF &&
13440 error == NULL)
13441 error = got_error_from_errno2("fclose", patch_script_path);
13442 if (repo) {
13443 const struct got_error *close_err = got_repo_close(repo);
13444 if (error == NULL)
13445 error = close_err;
13447 if (worktree)
13448 got_worktree_close(worktree);
13449 if (pack_fds) {
13450 const struct got_error *pack_err =
13451 got_repo_pack_fds_close(pack_fds);
13452 if (error == NULL)
13453 error = pack_err;
13455 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
13456 free(cwd);
13457 return error;
13460 __dead static void
13461 usage_unstage(void)
13463 fprintf(stderr, "usage: %s unstage [-p] [-F response-script] "
13464 "[path ...]\n", getprogname());
13465 exit(1);
13469 static const struct got_error *
13470 cmd_unstage(int argc, char *argv[])
13472 const struct got_error *error = NULL;
13473 struct got_repository *repo = NULL;
13474 struct got_worktree *worktree = NULL;
13475 char *cwd = NULL;
13476 struct got_pathlist_head paths;
13477 int ch, pflag = 0;
13478 struct got_update_progress_arg upa;
13479 FILE *patch_script_file = NULL;
13480 const char *patch_script_path = NULL;
13481 struct choose_patch_arg cpa;
13482 int *pack_fds = NULL;
13484 TAILQ_INIT(&paths);
13486 while ((ch = getopt(argc, argv, "F:p")) != -1) {
13487 switch (ch) {
13488 case 'F':
13489 patch_script_path = optarg;
13490 break;
13491 case 'p':
13492 pflag = 1;
13493 break;
13494 default:
13495 usage_unstage();
13496 /* NOTREACHED */
13500 argc -= optind;
13501 argv += optind;
13503 #ifndef PROFILE
13504 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
13505 "unveil", NULL) == -1)
13506 err(1, "pledge");
13507 #endif
13508 if (patch_script_path && !pflag)
13509 errx(1, "-F option can only be used together with -p option");
13511 cwd = getcwd(NULL, 0);
13512 if (cwd == NULL) {
13513 error = got_error_from_errno("getcwd");
13514 goto done;
13517 error = got_repo_pack_fds_open(&pack_fds);
13518 if (error != NULL)
13519 goto done;
13521 error = got_worktree_open(&worktree, cwd);
13522 if (error) {
13523 if (error->code == GOT_ERR_NOT_WORKTREE)
13524 error = wrap_not_worktree_error(error, "unstage", cwd);
13525 goto done;
13528 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
13529 NULL, pack_fds);
13530 if (error != NULL)
13531 goto done;
13533 if (patch_script_path) {
13534 patch_script_file = fopen(patch_script_path, "re");
13535 if (patch_script_file == NULL) {
13536 error = got_error_from_errno2("fopen",
13537 patch_script_path);
13538 goto done;
13542 error = apply_unveil(got_repo_get_path(repo), 0,
13543 got_worktree_get_root_path(worktree));
13544 if (error)
13545 goto done;
13547 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
13548 if (error)
13549 goto done;
13551 cpa.patch_script_file = patch_script_file;
13552 cpa.action = "unstage";
13553 memset(&upa, 0, sizeof(upa));
13554 error = got_worktree_unstage(worktree, &paths, update_progress,
13555 &upa, pflag ? choose_patch : NULL, &cpa, repo);
13556 if (!error)
13557 print_merge_progress_stats(&upa);
13558 done:
13559 if (patch_script_file && fclose(patch_script_file) == EOF &&
13560 error == NULL)
13561 error = got_error_from_errno2("fclose", patch_script_path);
13562 if (repo) {
13563 const struct got_error *close_err = got_repo_close(repo);
13564 if (error == NULL)
13565 error = close_err;
13567 if (worktree)
13568 got_worktree_close(worktree);
13569 if (pack_fds) {
13570 const struct got_error *pack_err =
13571 got_repo_pack_fds_close(pack_fds);
13572 if (error == NULL)
13573 error = pack_err;
13575 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
13576 free(cwd);
13577 return error;
13580 __dead static void
13581 usage_cat(void)
13583 fprintf(stderr, "usage: %s cat [-P] [-c commit] [-r repository-path] "
13584 "arg ...\n", getprogname());
13585 exit(1);
13588 static const struct got_error *
13589 cat_blob(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
13591 const struct got_error *err;
13592 struct got_blob_object *blob;
13593 int fd = -1;
13595 fd = got_opentempfd();
13596 if (fd == -1)
13597 return got_error_from_errno("got_opentempfd");
13599 err = got_object_open_as_blob(&blob, repo, id, 8192, fd);
13600 if (err)
13601 goto done;
13603 err = got_object_blob_dump_to_file(NULL, NULL, NULL, outfile, blob);
13604 done:
13605 if (fd != -1 && close(fd) == -1 && err == NULL)
13606 err = got_error_from_errno("close");
13607 if (blob)
13608 got_object_blob_close(blob);
13609 return err;
13612 static const struct got_error *
13613 cat_tree(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
13615 const struct got_error *err;
13616 struct got_tree_object *tree;
13617 int nentries, i;
13619 err = got_object_open_as_tree(&tree, repo, id);
13620 if (err)
13621 return err;
13623 nentries = got_object_tree_get_nentries(tree);
13624 for (i = 0; i < nentries; i++) {
13625 struct got_tree_entry *te;
13626 char *id_str;
13627 if (sigint_received || sigpipe_received)
13628 break;
13629 te = got_object_tree_get_entry(tree, i);
13630 err = got_object_id_str(&id_str, got_tree_entry_get_id(te));
13631 if (err)
13632 break;
13633 fprintf(outfile, "%s %.7o %s\n", id_str,
13634 got_tree_entry_get_mode(te),
13635 got_tree_entry_get_name(te));
13636 free(id_str);
13639 got_object_tree_close(tree);
13640 return err;
13643 static const struct got_error *
13644 cat_commit(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
13646 const struct got_error *err;
13647 struct got_commit_object *commit;
13648 const struct got_object_id_queue *parent_ids;
13649 struct got_object_qid *pid;
13650 char *id_str = NULL;
13651 const char *logmsg = NULL;
13652 char gmtoff[6];
13654 err = got_object_open_as_commit(&commit, repo, id);
13655 if (err)
13656 return err;
13658 err = got_object_id_str(&id_str, got_object_commit_get_tree_id(commit));
13659 if (err)
13660 goto done;
13662 fprintf(outfile, "%s%s\n", GOT_COMMIT_LABEL_TREE, id_str);
13663 parent_ids = got_object_commit_get_parent_ids(commit);
13664 fprintf(outfile, "numparents %d\n",
13665 got_object_commit_get_nparents(commit));
13666 STAILQ_FOREACH(pid, parent_ids, entry) {
13667 char *pid_str;
13668 err = got_object_id_str(&pid_str, &pid->id);
13669 if (err)
13670 goto done;
13671 fprintf(outfile, "%s%s\n", GOT_COMMIT_LABEL_PARENT, pid_str);
13672 free(pid_str);
13674 got_date_format_gmtoff(gmtoff, sizeof(gmtoff),
13675 got_object_commit_get_author_gmtoff(commit));
13676 fprintf(outfile, "%s%s %lld %s\n", GOT_COMMIT_LABEL_AUTHOR,
13677 got_object_commit_get_author(commit),
13678 (long long)got_object_commit_get_author_time(commit),
13679 gmtoff);
13681 got_date_format_gmtoff(gmtoff, sizeof(gmtoff),
13682 got_object_commit_get_committer_gmtoff(commit));
13683 fprintf(outfile, "%s%s %lld %s\n", GOT_COMMIT_LABEL_COMMITTER,
13684 got_object_commit_get_committer(commit),
13685 (long long)got_object_commit_get_committer_time(commit),
13686 gmtoff);
13688 logmsg = got_object_commit_get_logmsg_raw(commit);
13689 fprintf(outfile, "messagelen %zd\n", strlen(logmsg));
13690 fprintf(outfile, "%s", logmsg);
13691 done:
13692 free(id_str);
13693 got_object_commit_close(commit);
13694 return err;
13697 static const struct got_error *
13698 cat_tag(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
13700 const struct got_error *err;
13701 struct got_tag_object *tag;
13702 char *id_str = NULL;
13703 const char *tagmsg = NULL;
13704 char gmtoff[6];
13706 err = got_object_open_as_tag(&tag, repo, id);
13707 if (err)
13708 return err;
13710 err = got_object_id_str(&id_str, got_object_tag_get_object_id(tag));
13711 if (err)
13712 goto done;
13714 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_OBJECT, id_str);
13716 switch (got_object_tag_get_object_type(tag)) {
13717 case GOT_OBJ_TYPE_BLOB:
13718 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
13719 GOT_OBJ_LABEL_BLOB);
13720 break;
13721 case GOT_OBJ_TYPE_TREE:
13722 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
13723 GOT_OBJ_LABEL_TREE);
13724 break;
13725 case GOT_OBJ_TYPE_COMMIT:
13726 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
13727 GOT_OBJ_LABEL_COMMIT);
13728 break;
13729 case GOT_OBJ_TYPE_TAG:
13730 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
13731 GOT_OBJ_LABEL_TAG);
13732 break;
13733 default:
13734 break;
13737 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TAG,
13738 got_object_tag_get_name(tag));
13740 got_date_format_gmtoff(gmtoff, sizeof(gmtoff),
13741 got_object_tag_get_tagger_gmtoff(tag));
13742 fprintf(outfile, "%s%s %lld %s\n", GOT_TAG_LABEL_TAGGER,
13743 got_object_tag_get_tagger(tag),
13744 (long long)got_object_tag_get_tagger_time(tag),
13745 gmtoff);
13747 tagmsg = got_object_tag_get_message(tag);
13748 fprintf(outfile, "messagelen %zd\n", strlen(tagmsg));
13749 fprintf(outfile, "%s", tagmsg);
13750 done:
13751 free(id_str);
13752 got_object_tag_close(tag);
13753 return err;
13756 static const struct got_error *
13757 cmd_cat(int argc, char *argv[])
13759 const struct got_error *error;
13760 struct got_repository *repo = NULL;
13761 struct got_worktree *worktree = NULL;
13762 char *cwd = NULL, *repo_path = NULL, *label = NULL;
13763 const char *commit_id_str = NULL;
13764 struct got_object_id *id = NULL, *commit_id = NULL;
13765 struct got_commit_object *commit = NULL;
13766 int ch, obj_type, i, force_path = 0;
13767 struct got_reflist_head refs;
13768 int *pack_fds = NULL;
13770 TAILQ_INIT(&refs);
13772 #ifndef PROFILE
13773 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
13774 NULL) == -1)
13775 err(1, "pledge");
13776 #endif
13778 while ((ch = getopt(argc, argv, "c:Pr:")) != -1) {
13779 switch (ch) {
13780 case 'c':
13781 commit_id_str = optarg;
13782 break;
13783 case 'P':
13784 force_path = 1;
13785 break;
13786 case 'r':
13787 repo_path = realpath(optarg, NULL);
13788 if (repo_path == NULL)
13789 return got_error_from_errno2("realpath",
13790 optarg);
13791 got_path_strip_trailing_slashes(repo_path);
13792 break;
13793 default:
13794 usage_cat();
13795 /* NOTREACHED */
13799 argc -= optind;
13800 argv += optind;
13802 cwd = getcwd(NULL, 0);
13803 if (cwd == NULL) {
13804 error = got_error_from_errno("getcwd");
13805 goto done;
13808 error = got_repo_pack_fds_open(&pack_fds);
13809 if (error != NULL)
13810 goto done;
13812 if (repo_path == NULL) {
13813 error = got_worktree_open(&worktree, cwd);
13814 if (error && error->code != GOT_ERR_NOT_WORKTREE)
13815 goto done;
13816 if (worktree) {
13817 repo_path = strdup(
13818 got_worktree_get_repo_path(worktree));
13819 if (repo_path == NULL) {
13820 error = got_error_from_errno("strdup");
13821 goto done;
13824 /* Release work tree lock. */
13825 got_worktree_close(worktree);
13826 worktree = NULL;
13830 if (repo_path == NULL) {
13831 repo_path = strdup(cwd);
13832 if (repo_path == NULL)
13833 return got_error_from_errno("strdup");
13836 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
13837 free(repo_path);
13838 if (error != NULL)
13839 goto done;
13841 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
13842 if (error)
13843 goto done;
13845 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
13846 if (error)
13847 goto done;
13849 if (commit_id_str == NULL)
13850 commit_id_str = GOT_REF_HEAD;
13851 error = got_repo_match_object_id(&commit_id, NULL,
13852 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
13853 if (error)
13854 goto done;
13856 error = got_object_open_as_commit(&commit, repo, commit_id);
13857 if (error)
13858 goto done;
13860 for (i = 0; i < argc; i++) {
13861 if (force_path) {
13862 error = got_object_id_by_path(&id, repo, commit,
13863 argv[i]);
13864 if (error)
13865 break;
13866 } else {
13867 error = got_repo_match_object_id(&id, &label, argv[i],
13868 GOT_OBJ_TYPE_ANY, NULL /* do not resolve tags */,
13869 repo);
13870 if (error) {
13871 if (error->code != GOT_ERR_BAD_OBJ_ID_STR &&
13872 error->code != GOT_ERR_NOT_REF)
13873 break;
13874 error = got_object_id_by_path(&id, repo,
13875 commit, argv[i]);
13876 if (error)
13877 break;
13881 error = got_object_get_type(&obj_type, repo, id);
13882 if (error)
13883 break;
13885 switch (obj_type) {
13886 case GOT_OBJ_TYPE_BLOB:
13887 error = cat_blob(id, repo, stdout);
13888 break;
13889 case GOT_OBJ_TYPE_TREE:
13890 error = cat_tree(id, repo, stdout);
13891 break;
13892 case GOT_OBJ_TYPE_COMMIT:
13893 error = cat_commit(id, repo, stdout);
13894 break;
13895 case GOT_OBJ_TYPE_TAG:
13896 error = cat_tag(id, repo, stdout);
13897 break;
13898 default:
13899 error = got_error(GOT_ERR_OBJ_TYPE);
13900 break;
13902 if (error)
13903 break;
13904 free(label);
13905 label = NULL;
13906 free(id);
13907 id = NULL;
13909 done:
13910 free(label);
13911 free(id);
13912 free(commit_id);
13913 if (commit)
13914 got_object_commit_close(commit);
13915 if (worktree)
13916 got_worktree_close(worktree);
13917 if (repo) {
13918 const struct got_error *close_err = got_repo_close(repo);
13919 if (error == NULL)
13920 error = close_err;
13922 if (pack_fds) {
13923 const struct got_error *pack_err =
13924 got_repo_pack_fds_close(pack_fds);
13925 if (error == NULL)
13926 error = pack_err;
13929 got_ref_list_free(&refs);
13930 return error;
13933 __dead static void
13934 usage_info(void)
13936 fprintf(stderr, "usage: %s info [path ...]\n",
13937 getprogname());
13938 exit(1);
13941 static const struct got_error *
13942 print_path_info(void *arg, const char *path, mode_t mode, time_t mtime,
13943 struct got_object_id *blob_id, struct got_object_id *staged_blob_id,
13944 struct got_object_id *commit_id)
13946 const struct got_error *err = NULL;
13947 char *id_str = NULL;
13948 char datebuf[128];
13949 struct tm mytm, *tm;
13950 struct got_pathlist_head *paths = arg;
13951 struct got_pathlist_entry *pe;
13954 * Clear error indication from any of the path arguments which
13955 * would cause this file index entry to be displayed.
13957 TAILQ_FOREACH(pe, paths, entry) {
13958 if (got_path_cmp(path, pe->path, strlen(path),
13959 pe->path_len) == 0 ||
13960 got_path_is_child(path, pe->path, pe->path_len))
13961 pe->data = NULL; /* no error */
13964 printf(GOT_COMMIT_SEP_STR);
13965 if (S_ISLNK(mode))
13966 printf("symlink: %s\n", path);
13967 else if (S_ISREG(mode)) {
13968 printf("file: %s\n", path);
13969 printf("mode: %o\n", mode & (S_IRWXU | S_IRWXG | S_IRWXO));
13970 } else if (S_ISDIR(mode))
13971 printf("directory: %s\n", path);
13972 else
13973 printf("something: %s\n", path);
13975 tm = localtime_r(&mtime, &mytm);
13976 if (tm == NULL)
13977 return NULL;
13978 if (strftime(datebuf, sizeof(datebuf), "%c %Z", tm) == 0)
13979 return got_error(GOT_ERR_NO_SPACE);
13980 printf("timestamp: %s\n", datebuf);
13982 if (blob_id) {
13983 err = got_object_id_str(&id_str, blob_id);
13984 if (err)
13985 return err;
13986 printf("based on blob: %s\n", id_str);
13987 free(id_str);
13990 if (staged_blob_id) {
13991 err = got_object_id_str(&id_str, staged_blob_id);
13992 if (err)
13993 return err;
13994 printf("based on staged blob: %s\n", id_str);
13995 free(id_str);
13998 if (commit_id) {
13999 err = got_object_id_str(&id_str, commit_id);
14000 if (err)
14001 return err;
14002 printf("based on commit: %s\n", id_str);
14003 free(id_str);
14006 return NULL;
14009 static const struct got_error *
14010 cmd_info(int argc, char *argv[])
14012 const struct got_error *error = NULL;
14013 struct got_worktree *worktree = NULL;
14014 char *cwd = NULL, *id_str = NULL;
14015 struct got_pathlist_head paths;
14016 char *uuidstr = NULL;
14017 int ch, show_files = 0;
14019 TAILQ_INIT(&paths);
14021 while ((ch = getopt(argc, argv, "")) != -1) {
14022 switch (ch) {
14023 default:
14024 usage_info();
14025 /* NOTREACHED */
14029 argc -= optind;
14030 argv += optind;
14032 #ifndef PROFILE
14033 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
14034 NULL) == -1)
14035 err(1, "pledge");
14036 #endif
14037 cwd = getcwd(NULL, 0);
14038 if (cwd == NULL) {
14039 error = got_error_from_errno("getcwd");
14040 goto done;
14043 error = got_worktree_open(&worktree, cwd);
14044 if (error) {
14045 if (error->code == GOT_ERR_NOT_WORKTREE)
14046 error = wrap_not_worktree_error(error, "info", cwd);
14047 goto done;
14050 #ifndef PROFILE
14051 /* Remove "wpath cpath proc exec sendfd" promises. */
14052 if (pledge("stdio rpath flock unveil", NULL) == -1)
14053 err(1, "pledge");
14054 #endif
14055 error = apply_unveil(NULL, 0, got_worktree_get_root_path(worktree));
14056 if (error)
14057 goto done;
14059 if (argc >= 1) {
14060 error = get_worktree_paths_from_argv(&paths, argc, argv,
14061 worktree);
14062 if (error)
14063 goto done;
14064 show_files = 1;
14067 error = got_object_id_str(&id_str,
14068 got_worktree_get_base_commit_id(worktree));
14069 if (error)
14070 goto done;
14072 error = got_worktree_get_uuid(&uuidstr, worktree);
14073 if (error)
14074 goto done;
14076 printf("work tree: %s\n", got_worktree_get_root_path(worktree));
14077 printf("work tree base commit: %s\n", id_str);
14078 printf("work tree path prefix: %s\n",
14079 got_worktree_get_path_prefix(worktree));
14080 printf("work tree branch reference: %s\n",
14081 got_worktree_get_head_ref_name(worktree));
14082 printf("work tree UUID: %s\n", uuidstr);
14083 printf("repository: %s\n", got_worktree_get_repo_path(worktree));
14085 if (show_files) {
14086 struct got_pathlist_entry *pe;
14087 TAILQ_FOREACH(pe, &paths, entry) {
14088 if (pe->path_len == 0)
14089 continue;
14091 * Assume this path will fail. This will be corrected
14092 * in print_path_info() in case the path does suceeed.
14094 pe->data = (void *)got_error(GOT_ERR_BAD_PATH);
14096 error = got_worktree_path_info(worktree, &paths,
14097 print_path_info, &paths, check_cancelled, NULL);
14098 if (error)
14099 goto done;
14100 TAILQ_FOREACH(pe, &paths, entry) {
14101 if (pe->data != NULL) {
14102 const struct got_error *perr;
14104 perr = pe->data;
14105 error = got_error_fmt(perr->code, "%s",
14106 pe->path);
14107 break;
14111 done:
14112 if (worktree)
14113 got_worktree_close(worktree);
14114 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
14115 free(cwd);
14116 free(id_str);
14117 free(uuidstr);
14118 return error;