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 <sha2.h>
33 #include <signal.h>
34 #include <stdio.h>
35 #include <stdlib.h>
36 #include <string.h>
37 #include <unistd.h>
38 #include <libgen.h>
39 #include <time.h>
40 #include <paths.h>
41 #include <regex.h>
42 #include <getopt.h>
43 #include <util.h>
45 #include "got_version.h"
46 #include "got_error.h"
47 #include "got_object.h"
48 #include "got_reference.h"
49 #include "got_repository.h"
50 #include "got_path.h"
51 #include "got_cancel.h"
52 #include "got_worktree.h"
53 #include "got_diff.h"
54 #include "got_commit_graph.h"
55 #include "got_fetch.h"
56 #include "got_send.h"
57 #include "got_blame.h"
58 #include "got_privsep.h"
59 #include "got_opentemp.h"
60 #include "got_gotconfig.h"
61 #include "got_dial.h"
62 #include "got_patch.h"
63 #include "got_sigs.h"
64 #include "got_date.h"
65 #include "got_keyword.h"
67 #ifndef nitems
68 #define nitems(_a) (sizeof((_a)) / sizeof((_a)[0]))
69 #endif
71 #ifndef GOT_DEFAULT_EDITOR
72 #define GOT_DEFAULT_EDITOR "/usr/bin/vi"
73 #endif
75 static volatile sig_atomic_t sigint_received;
76 static volatile sig_atomic_t sigpipe_received;
78 static void
79 catch_sigint(int signo)
80 {
81 sigint_received = 1;
82 }
84 static void
85 catch_sigpipe(int signo)
86 {
87 sigpipe_received = 1;
88 }
91 struct got_cmd {
92 const char *cmd_name;
93 const struct got_error *(*cmd_main)(int, char *[]);
94 void (*cmd_usage)(void);
95 const char *cmd_alias;
96 };
98 __dead static void usage(int, int);
99 __dead static void usage_init(void);
100 __dead static void usage_import(void);
101 __dead static void usage_clone(void);
102 __dead static void usage_fetch(void);
103 __dead static void usage_checkout(void);
104 __dead static void usage_update(void);
105 __dead static void usage_log(void);
106 __dead static void usage_diff(void);
107 __dead static void usage_blame(void);
108 __dead static void usage_tree(void);
109 __dead static void usage_status(void);
110 __dead static void usage_ref(void);
111 __dead static void usage_branch(void);
112 __dead static void usage_tag(void);
113 __dead static void usage_add(void);
114 __dead static void usage_remove(void);
115 __dead static void usage_patch(void);
116 __dead static void usage_revert(void);
117 __dead static void usage_commit(void);
118 __dead static void usage_send(void);
119 __dead static void usage_cherrypick(void);
120 __dead static void usage_backout(void);
121 __dead static void usage_rebase(void);
122 __dead static void usage_histedit(void);
123 __dead static void usage_integrate(void);
124 __dead static void usage_merge(void);
125 __dead static void usage_stage(void);
126 __dead static void usage_unstage(void);
127 __dead static void usage_cat(void);
128 __dead static void usage_info(void);
130 static const struct got_error* cmd_init(int, char *[]);
131 static const struct got_error* cmd_import(int, char *[]);
132 static const struct got_error* cmd_clone(int, char *[]);
133 static const struct got_error* cmd_fetch(int, char *[]);
134 static const struct got_error* cmd_checkout(int, char *[]);
135 static const struct got_error* cmd_update(int, char *[]);
136 static const struct got_error* cmd_log(int, char *[]);
137 static const struct got_error* cmd_diff(int, char *[]);
138 static const struct got_error* cmd_blame(int, char *[]);
139 static const struct got_error* cmd_tree(int, char *[]);
140 static const struct got_error* cmd_status(int, char *[]);
141 static const struct got_error* cmd_ref(int, char *[]);
142 static const struct got_error* cmd_branch(int, char *[]);
143 static const struct got_error* cmd_tag(int, char *[]);
144 static const struct got_error* cmd_add(int, char *[]);
145 static const struct got_error* cmd_remove(int, char *[]);
146 static const struct got_error* cmd_patch(int, char *[]);
147 static const struct got_error* cmd_revert(int, char *[]);
148 static const struct got_error* cmd_commit(int, char *[]);
149 static const struct got_error* cmd_send(int, char *[]);
150 static const struct got_error* cmd_cherrypick(int, char *[]);
151 static const struct got_error* cmd_backout(int, char *[]);
152 static const struct got_error* cmd_rebase(int, char *[]);
153 static const struct got_error* cmd_histedit(int, char *[]);
154 static const struct got_error* cmd_integrate(int, char *[]);
155 static const struct got_error* cmd_merge(int, char *[]);
156 static const struct got_error* cmd_stage(int, char *[]);
157 static const struct got_error* cmd_unstage(int, char *[]);
158 static const struct got_error* cmd_cat(int, char *[]);
159 static const struct got_error* cmd_info(int, char *[]);
161 static const struct got_cmd got_commands[] = {
162 { "init", cmd_init, usage_init, "" },
163 { "import", cmd_import, usage_import, "im" },
164 { "clone", cmd_clone, usage_clone, "cl" },
165 { "fetch", cmd_fetch, usage_fetch, "fe" },
166 { "checkout", cmd_checkout, usage_checkout, "co" },
167 { "update", cmd_update, usage_update, "up" },
168 { "log", cmd_log, usage_log, "" },
169 { "diff", cmd_diff, usage_diff, "di" },
170 { "blame", cmd_blame, usage_blame, "bl" },
171 { "tree", cmd_tree, usage_tree, "tr" },
172 { "status", cmd_status, usage_status, "st" },
173 { "ref", cmd_ref, usage_ref, "" },
174 { "branch", cmd_branch, usage_branch, "br" },
175 { "tag", cmd_tag, usage_tag, "" },
176 { "add", cmd_add, usage_add, "" },
177 { "remove", cmd_remove, usage_remove, "rm" },
178 { "patch", cmd_patch, usage_patch, "pa" },
179 { "revert", cmd_revert, usage_revert, "rv" },
180 { "commit", cmd_commit, usage_commit, "ci" },
181 { "send", cmd_send, usage_send, "se" },
182 { "cherrypick", cmd_cherrypick, usage_cherrypick, "cy" },
183 { "backout", cmd_backout, usage_backout, "bo" },
184 { "rebase", cmd_rebase, usage_rebase, "rb" },
185 { "histedit", cmd_histedit, usage_histedit, "he" },
186 { "integrate", cmd_integrate, usage_integrate,"ig" },
187 { "merge", cmd_merge, usage_merge, "mg" },
188 { "stage", cmd_stage, usage_stage, "sg" },
189 { "unstage", cmd_unstage, usage_unstage, "ug" },
190 { "cat", cmd_cat, usage_cat, "" },
191 { "info", cmd_info, usage_info, "" },
192 };
194 static void
195 list_commands(FILE *fp)
197 size_t i;
199 fprintf(fp, "commands:");
200 for (i = 0; i < nitems(got_commands); i++) {
201 const struct got_cmd *cmd = &got_commands[i];
202 fprintf(fp, " %s", cmd->cmd_name);
204 fputc('\n', fp);
207 __dead static void
208 option_conflict(char a, char b)
210 errx(1, "-%c and -%c options are mutually exclusive", a, b);
213 int
214 main(int argc, char *argv[])
216 const struct got_cmd *cmd;
217 size_t i;
218 int ch;
219 int hflag = 0, Vflag = 0;
220 static const struct option longopts[] = {
221 { "version", no_argument, NULL, 'V' },
222 { NULL, 0, NULL, 0 }
223 };
225 setlocale(LC_CTYPE, "");
227 while ((ch = getopt_long(argc, argv, "+hV", longopts, NULL)) != -1) {
228 switch (ch) {
229 case 'h':
230 hflag = 1;
231 break;
232 case 'V':
233 Vflag = 1;
234 break;
235 default:
236 usage(hflag, 1);
237 /* NOTREACHED */
241 argc -= optind;
242 argv += optind;
243 optind = 1;
244 optreset = 1;
246 if (Vflag) {
247 got_version_print_str();
248 return 0;
251 if (argc <= 0)
252 usage(hflag, hflag ? 0 : 1);
254 signal(SIGINT, catch_sigint);
255 signal(SIGPIPE, catch_sigpipe);
257 for (i = 0; i < nitems(got_commands); i++) {
258 const struct got_error *error;
260 cmd = &got_commands[i];
262 if (strcmp(cmd->cmd_name, argv[0]) != 0 &&
263 strcmp(cmd->cmd_alias, argv[0]) != 0)
264 continue;
266 if (hflag)
267 cmd->cmd_usage();
269 error = cmd->cmd_main(argc, argv);
270 if (error && error->code != GOT_ERR_CANCELLED &&
271 error->code != GOT_ERR_PRIVSEP_EXIT &&
272 !(sigpipe_received &&
273 error->code == GOT_ERR_ERRNO && errno == EPIPE) &&
274 !(sigint_received &&
275 error->code == GOT_ERR_ERRNO && errno == EINTR)) {
276 fflush(stdout);
277 fprintf(stderr, "%s: %s\n", getprogname(), error->msg);
278 return 1;
281 return 0;
284 fprintf(stderr, "%s: unknown command '%s'\n", getprogname(), argv[0]);
285 list_commands(stderr);
286 return 1;
289 __dead static void
290 usage(int hflag, int status)
292 FILE *fp = (status == 0) ? stdout : stderr;
294 fprintf(fp, "usage: %s [-hV] command [arg ...]\n",
295 getprogname());
296 if (hflag)
297 list_commands(fp);
298 exit(status);
301 static const struct got_error *
302 get_editor(char **abspath)
304 const struct got_error *err = NULL;
305 const char *editor;
307 *abspath = NULL;
309 editor = getenv("VISUAL");
310 if (editor == NULL)
311 editor = getenv("EDITOR");
313 if (editor) {
314 err = got_path_find_prog(abspath, editor);
315 if (err)
316 return err;
319 if (*abspath == NULL) {
320 *abspath = strdup(GOT_DEFAULT_EDITOR);
321 if (*abspath == NULL)
322 return got_error_from_errno("strdup");
325 return NULL;
328 static const struct got_error *
329 apply_unveil(const char *repo_path, int repo_read_only,
330 const char *worktree_path)
332 const struct got_error *err;
334 #ifdef PROFILE
335 if (unveil("gmon.out", "rwc") != 0)
336 return got_error_from_errno2("unveil", "gmon.out");
337 #endif
338 if (repo_path && unveil(repo_path, repo_read_only ? "r" : "rwc") != 0)
339 return got_error_from_errno2("unveil", repo_path);
341 if (worktree_path && unveil(worktree_path, "rwc") != 0)
342 return got_error_from_errno2("unveil", worktree_path);
344 if (unveil(GOT_TMPDIR_STR, "rwc") != 0)
345 return got_error_from_errno2("unveil", GOT_TMPDIR_STR);
347 err = got_privsep_unveil_exec_helpers();
348 if (err != NULL)
349 return err;
351 if (unveil(NULL, NULL) != 0)
352 return got_error_from_errno("unveil");
354 return NULL;
357 __dead static void
358 usage_init(void)
360 fprintf(stderr, "usage: %s init [-b branch] repository-path\n",
361 getprogname());
362 exit(1);
365 static const struct got_error *
366 cmd_init(int argc, char *argv[])
368 const struct got_error *error = NULL;
369 const char *head_name = NULL;
370 char *repo_path = NULL;
371 int ch;
373 while ((ch = getopt(argc, argv, "b:")) != -1) {
374 switch (ch) {
375 case 'b':
376 head_name = optarg;
377 break;
378 default:
379 usage_init();
380 /* NOTREACHED */
384 argc -= optind;
385 argv += optind;
387 #ifndef PROFILE
388 if (pledge("stdio rpath wpath cpath unveil", NULL) == -1)
389 err(1, "pledge");
390 #endif
391 if (argc != 1)
392 usage_init();
394 repo_path = strdup(argv[0]);
395 if (repo_path == NULL)
396 return got_error_from_errno("strdup");
398 got_path_strip_trailing_slashes(repo_path);
400 error = got_path_mkdir(repo_path);
401 if (error &&
402 !(error->code == GOT_ERR_ERRNO && errno == EEXIST))
403 goto done;
405 error = apply_unveil(repo_path, 0, NULL);
406 if (error)
407 goto done;
409 error = got_repo_init(repo_path, head_name);
410 done:
411 free(repo_path);
412 return error;
415 __dead static void
416 usage_import(void)
418 fprintf(stderr, "usage: %s import [-b branch] [-I pattern] [-m message] "
419 "[-r repository-path] directory\n", getprogname());
420 exit(1);
423 static int
424 spawn_editor(const char *editor, const char *file)
426 pid_t pid;
427 sig_t sighup, sigint, sigquit;
428 int st = -1;
430 sighup = signal(SIGHUP, SIG_IGN);
431 sigint = signal(SIGINT, SIG_IGN);
432 sigquit = signal(SIGQUIT, SIG_IGN);
434 switch (pid = fork()) {
435 case -1:
436 goto doneediting;
437 case 0:
438 execl(editor, editor, file, (char *)NULL);
439 _exit(127);
442 while (waitpid(pid, &st, 0) == -1)
443 if (errno != EINTR)
444 break;
446 doneediting:
447 (void)signal(SIGHUP, sighup);
448 (void)signal(SIGINT, sigint);
449 (void)signal(SIGQUIT, sigquit);
451 if (!WIFEXITED(st)) {
452 errno = EINTR;
453 return -1;
456 return WEXITSTATUS(st);
459 static const struct got_error *
460 read_logmsg(char **logmsg, size_t *len, FILE *fp, size_t filesize)
462 const struct got_error *err = NULL;
463 char *line = NULL;
464 size_t linesize = 0;
466 *logmsg = NULL;
467 *len = 0;
469 if (fseeko(fp, 0L, SEEK_SET) == -1)
470 return got_error_from_errno("fseeko");
472 *logmsg = malloc(filesize + 1);
473 if (*logmsg == NULL)
474 return got_error_from_errno("malloc");
475 (*logmsg)[0] = '\0';
477 while (getline(&line, &linesize, fp) != -1) {
478 if (line[0] == '#' || (*len == 0 && line[0] == '\n'))
479 continue; /* remove comments and leading empty lines */
480 *len = strlcat(*logmsg, line, filesize + 1);
481 if (*len >= filesize + 1) {
482 err = got_error(GOT_ERR_NO_SPACE);
483 goto done;
486 if (ferror(fp)) {
487 err = got_ferror(fp, GOT_ERR_IO);
488 goto done;
491 while (*len > 0 && (*logmsg)[*len - 1] == '\n') {
492 (*logmsg)[*len - 1] = '\0';
493 (*len)--;
495 done:
496 free(line);
497 if (err) {
498 free(*logmsg);
499 *logmsg = NULL;
500 *len = 0;
502 return err;
505 static const struct got_error *
506 edit_logmsg(char **logmsg, const char *editor, const char *logmsg_path,
507 const char *initial_content, size_t initial_content_len,
508 int require_modification)
510 const struct got_error *err = NULL;
511 struct stat st, st2;
512 FILE *fp = NULL;
513 size_t logmsg_len;
515 *logmsg = NULL;
517 if (stat(logmsg_path, &st) == -1)
518 return got_error_from_errno2("stat", logmsg_path);
520 if (spawn_editor(editor, logmsg_path) == -1)
521 return got_error_from_errno("failed spawning editor");
523 if (require_modification) {
524 struct timespec timeout;
526 timeout.tv_sec = 0;
527 timeout.tv_nsec = 1;
528 nanosleep(&timeout, NULL);
531 if (stat(logmsg_path, &st2) == -1)
532 return got_error_from_errno2("stat", logmsg_path);
534 if (require_modification && st.st_size == st2.st_size &&
535 timespeccmp(&st.st_mtim, &st2.st_mtim, ==))
536 return got_error_msg(GOT_ERR_COMMIT_MSG_EMPTY,
537 "no changes made to commit message, aborting");
539 fp = fopen(logmsg_path, "re");
540 if (fp == NULL) {
541 err = got_error_from_errno("fopen");
542 goto done;
545 /* strip comments and leading/trailing newlines */
546 err = read_logmsg(logmsg, &logmsg_len, fp, st2.st_size);
547 if (err)
548 goto done;
549 if (logmsg_len == 0) {
550 err = got_error_msg(GOT_ERR_COMMIT_MSG_EMPTY,
551 "commit message cannot be empty, aborting");
552 goto done;
554 done:
555 if (fp && fclose(fp) == EOF && err == NULL)
556 err = got_error_from_errno("fclose");
557 if (err) {
558 free(*logmsg);
559 *logmsg = NULL;
561 return err;
564 static const struct got_error *
565 collect_import_msg(char **logmsg, char **logmsg_path, const char *editor,
566 const char *path_dir, const char *branch_name)
568 char *initial_content = NULL;
569 const struct got_error *err = NULL;
570 int initial_content_len;
571 int fd = -1;
573 initial_content_len = asprintf(&initial_content,
574 "\n# %s to be imported to branch %s\n", path_dir,
575 branch_name);
576 if (initial_content_len == -1)
577 return got_error_from_errno("asprintf");
579 err = got_opentemp_named_fd(logmsg_path, &fd,
580 GOT_TMPDIR_STR "/got-importmsg", "");
581 if (err)
582 goto done;
584 if (write(fd, initial_content, initial_content_len) == -1) {
585 err = got_error_from_errno2("write", *logmsg_path);
586 goto done;
588 if (close(fd) == -1) {
589 err = got_error_from_errno2("close", *logmsg_path);
590 goto done;
592 fd = -1;
594 err = edit_logmsg(logmsg, editor, *logmsg_path, initial_content,
595 initial_content_len, 1);
596 done:
597 if (fd != -1 && close(fd) == -1 && err == NULL)
598 err = got_error_from_errno2("close", *logmsg_path);
599 free(initial_content);
600 if (err) {
601 free(*logmsg_path);
602 *logmsg_path = NULL;
604 return err;
607 static const struct got_error *
608 import_progress(void *arg, const char *path)
610 printf("A %s\n", path);
611 return NULL;
614 static const struct got_error *
615 valid_author(const char *author)
617 const char *email = author;
619 /*
620 * Git' expects the author (or committer) to be in the form
621 * "name <email>", which are mostly free form (see the
622 * "committer" description in git-fast-import(1)). We're only
623 * doing this to avoid git's object parser breaking on commits
624 * we create.
625 */
627 while (*author && *author != '\n' && *author != '<' && *author != '>')
628 author++;
629 if (author != email && *author == '<' && *(author - 1) != ' ')
630 return got_error_fmt(GOT_ERR_COMMIT_BAD_AUTHOR, "%s: space "
631 "between author name and email required", email);
632 if (*author++ != '<')
633 return got_error_fmt(GOT_ERR_COMMIT_NO_EMAIL, "%s", email);
634 while (*author && *author != '\n' && *author != '<' && *author != '>')
635 author++;
636 if (strcmp(author, ">") != 0)
637 return got_error_fmt(GOT_ERR_COMMIT_NO_EMAIL, "%s", email);
638 return NULL;
641 static const struct got_error *
642 get_author(char **author, struct got_repository *repo,
643 struct got_worktree *worktree)
645 const struct got_error *err = NULL;
646 const char *got_author = NULL, *name, *email;
647 const struct got_gotconfig *worktree_conf = NULL, *repo_conf = NULL;
649 *author = NULL;
651 if (worktree)
652 worktree_conf = got_worktree_get_gotconfig(worktree);
653 repo_conf = got_repo_get_gotconfig(repo);
655 /*
656 * Priority of potential author information sources, from most
657 * significant to least significant:
658 * 1) work tree's .got/got.conf file
659 * 2) repository's got.conf file
660 * 3) repository's git config file
661 * 4) environment variables
662 * 5) global git config files (in user's home directory or /etc)
663 */
665 if (worktree_conf)
666 got_author = got_gotconfig_get_author(worktree_conf);
667 if (got_author == NULL)
668 got_author = got_gotconfig_get_author(repo_conf);
669 if (got_author == NULL) {
670 name = got_repo_get_gitconfig_author_name(repo);
671 email = got_repo_get_gitconfig_author_email(repo);
672 if (name && email) {
673 if (asprintf(author, "%s <%s>", name, email) == -1)
674 return got_error_from_errno("asprintf");
675 return NULL;
678 got_author = getenv("GOT_AUTHOR");
679 if (got_author == NULL) {
680 name = got_repo_get_global_gitconfig_author_name(repo);
681 email = got_repo_get_global_gitconfig_author_email(
682 repo);
683 if (name && email) {
684 if (asprintf(author, "%s <%s>", name, email)
685 == -1)
686 return got_error_from_errno("asprintf");
687 return NULL;
689 /* TODO: Look up user in password database? */
690 return got_error(GOT_ERR_COMMIT_NO_AUTHOR);
694 *author = strdup(got_author);
695 if (*author == NULL)
696 return got_error_from_errno("strdup");
698 err = valid_author(*author);
699 if (err) {
700 free(*author);
701 *author = NULL;
703 return err;
706 static const struct got_error *
707 get_allowed_signers(char **allowed_signers, struct got_repository *repo,
708 struct got_worktree *worktree)
710 const char *got_allowed_signers = NULL;
711 const struct got_gotconfig *worktree_conf = NULL, *repo_conf = NULL;
713 *allowed_signers = NULL;
715 if (worktree)
716 worktree_conf = got_worktree_get_gotconfig(worktree);
717 repo_conf = got_repo_get_gotconfig(repo);
719 /*
720 * Priority of potential author information sources, from most
721 * significant to least significant:
722 * 1) work tree's .got/got.conf file
723 * 2) repository's got.conf file
724 */
726 if (worktree_conf)
727 got_allowed_signers = got_gotconfig_get_allowed_signers_file(
728 worktree_conf);
729 if (got_allowed_signers == NULL)
730 got_allowed_signers = got_gotconfig_get_allowed_signers_file(
731 repo_conf);
733 if (got_allowed_signers) {
734 *allowed_signers = strdup(got_allowed_signers);
735 if (*allowed_signers == NULL)
736 return got_error_from_errno("strdup");
738 return NULL;
741 static const struct got_error *
742 get_revoked_signers(char **revoked_signers, struct got_repository *repo,
743 struct got_worktree *worktree)
745 const char *got_revoked_signers = NULL;
746 const struct got_gotconfig *worktree_conf = NULL, *repo_conf = NULL;
748 *revoked_signers = NULL;
750 if (worktree)
751 worktree_conf = got_worktree_get_gotconfig(worktree);
752 repo_conf = got_repo_get_gotconfig(repo);
754 /*
755 * Priority of potential author information sources, from most
756 * significant to least significant:
757 * 1) work tree's .got/got.conf file
758 * 2) repository's got.conf file
759 */
761 if (worktree_conf)
762 got_revoked_signers = got_gotconfig_get_revoked_signers_file(
763 worktree_conf);
764 if (got_revoked_signers == NULL)
765 got_revoked_signers = got_gotconfig_get_revoked_signers_file(
766 repo_conf);
768 if (got_revoked_signers) {
769 *revoked_signers = strdup(got_revoked_signers);
770 if (*revoked_signers == NULL)
771 return got_error_from_errno("strdup");
773 return NULL;
776 static const char *
777 get_signer_id(struct got_repository *repo, struct got_worktree *worktree)
779 const char *got_signer_id = NULL;
780 const struct got_gotconfig *worktree_conf = NULL, *repo_conf = NULL;
782 if (worktree)
783 worktree_conf = got_worktree_get_gotconfig(worktree);
784 repo_conf = got_repo_get_gotconfig(repo);
786 /*
787 * Priority of potential author information sources, from most
788 * significant to least significant:
789 * 1) work tree's .got/got.conf file
790 * 2) repository's got.conf file
791 */
793 if (worktree_conf)
794 got_signer_id = got_gotconfig_get_signer_id(worktree_conf);
795 if (got_signer_id == NULL)
796 got_signer_id = got_gotconfig_get_signer_id(repo_conf);
798 return got_signer_id;
801 static const struct got_error *
802 get_gitconfig_path(char **gitconfig_path)
804 const char *homedir = getenv("HOME");
806 *gitconfig_path = NULL;
807 if (homedir) {
808 if (asprintf(gitconfig_path, "%s/.gitconfig", homedir) == -1)
809 return got_error_from_errno("asprintf");
812 return NULL;
815 static const struct got_error *
816 cmd_import(int argc, char *argv[])
818 const struct got_error *error = NULL;
819 char *path_dir = NULL, *repo_path = NULL, *logmsg = NULL;
820 char *gitconfig_path = NULL, *editor = NULL, *author = NULL;
821 const char *branch_name = NULL;
822 char *id_str = NULL, *logmsg_path = NULL;
823 char refname[PATH_MAX] = "refs/heads/";
824 struct got_repository *repo = NULL;
825 struct got_reference *branch_ref = NULL, *head_ref = NULL;
826 struct got_object_id *new_commit_id = NULL;
827 int ch, n = 0;
828 struct got_pathlist_head ignores;
829 struct got_pathlist_entry *pe;
830 int preserve_logmsg = 0;
831 int *pack_fds = NULL;
833 TAILQ_INIT(&ignores);
835 #ifndef PROFILE
836 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
837 "unveil",
838 NULL) == -1)
839 err(1, "pledge");
840 #endif
842 while ((ch = getopt(argc, argv, "b:I:m:r:")) != -1) {
843 switch (ch) {
844 case 'b':
845 branch_name = optarg;
846 break;
847 case 'I':
848 if (optarg[0] == '\0')
849 break;
850 error = got_pathlist_insert(&pe, &ignores, optarg,
851 NULL);
852 if (error)
853 goto done;
854 break;
855 case 'm':
856 logmsg = strdup(optarg);
857 if (logmsg == NULL) {
858 error = got_error_from_errno("strdup");
859 goto done;
861 break;
862 case 'r':
863 repo_path = realpath(optarg, NULL);
864 if (repo_path == NULL) {
865 error = got_error_from_errno2("realpath",
866 optarg);
867 goto done;
869 break;
870 default:
871 usage_import();
872 /* NOTREACHED */
876 argc -= optind;
877 argv += optind;
879 if (argc != 1)
880 usage_import();
882 if (repo_path == NULL) {
883 repo_path = getcwd(NULL, 0);
884 if (repo_path == NULL)
885 return got_error_from_errno("getcwd");
887 got_path_strip_trailing_slashes(repo_path);
888 error = get_gitconfig_path(&gitconfig_path);
889 if (error)
890 goto done;
891 error = got_repo_pack_fds_open(&pack_fds);
892 if (error != NULL)
893 goto done;
894 error = got_repo_open(&repo, repo_path, gitconfig_path, pack_fds);
895 if (error)
896 goto done;
898 path_dir = realpath(argv[0], NULL);
899 if (path_dir == NULL) {
900 error = got_error_from_errno2("realpath", argv[0]);
901 goto done;
903 got_path_strip_trailing_slashes(path_dir);
905 error = get_editor(&editor);
906 if (error)
907 goto done;
909 if (unveil(path_dir, "r") != 0) {
910 error = got_error_from_errno2("unveil", path_dir);
911 goto done;
913 if (unveil(editor, "x") != 0) {
914 error = got_error_from_errno2("unveil", editor);
915 goto done;
917 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
918 if (error)
919 goto done;
921 error = get_author(&author, repo, NULL);
922 if (error)
923 return error;
925 /*
926 * Don't let the user create a branch name with a leading '-'.
927 * While technically a valid reference name, this case is usually
928 * an unintended typo.
929 */
930 if (branch_name && branch_name[0] == '-')
931 return got_error_path(branch_name, GOT_ERR_REF_NAME_MINUS);
933 error = got_ref_open(&head_ref, repo, GOT_REF_HEAD, 0);
934 if (error && error->code != GOT_ERR_NOT_REF)
935 goto done;
937 if (branch_name)
938 n = strlcat(refname, branch_name, sizeof(refname));
939 else if (head_ref && got_ref_is_symbolic(head_ref))
940 n = strlcpy(refname, got_ref_get_symref_target(head_ref),
941 sizeof(refname));
942 else
943 n = strlcat(refname, "main", sizeof(refname));
944 if (n >= sizeof(refname)) {
945 error = got_error(GOT_ERR_NO_SPACE);
946 goto done;
949 error = got_ref_open(&branch_ref, repo, refname, 0);
950 if (error) {
951 if (error->code != GOT_ERR_NOT_REF)
952 goto done;
953 } else {
954 error = got_error_msg(GOT_ERR_BRANCH_EXISTS,
955 "import target branch already exists");
956 goto done;
959 if (logmsg == NULL || *logmsg == '\0') {
960 free(logmsg);
961 error = collect_import_msg(&logmsg, &logmsg_path, editor,
962 path_dir, refname);
963 if (error) {
964 if (error->code != GOT_ERR_COMMIT_MSG_EMPTY &&
965 logmsg_path != NULL)
966 preserve_logmsg = 1;
967 goto done;
971 error = got_repo_import(&new_commit_id, path_dir, logmsg,
972 author, &ignores, repo, import_progress, NULL);
973 if (error) {
974 if (logmsg_path)
975 preserve_logmsg = 1;
976 goto done;
979 error = got_ref_alloc(&branch_ref, refname, new_commit_id);
980 if (error) {
981 if (logmsg_path)
982 preserve_logmsg = 1;
983 goto done;
986 error = got_ref_write(branch_ref, repo);
987 if (error) {
988 if (logmsg_path)
989 preserve_logmsg = 1;
990 goto done;
993 error = got_object_id_str(&id_str, new_commit_id);
994 if (error) {
995 if (logmsg_path)
996 preserve_logmsg = 1;
997 goto done;
1000 error = got_ref_open(&head_ref, repo, GOT_REF_HEAD, 0);
1001 if (error) {
1002 if (error->code != GOT_ERR_NOT_REF) {
1003 if (logmsg_path)
1004 preserve_logmsg = 1;
1005 goto done;
1008 error = got_ref_alloc_symref(&head_ref, GOT_REF_HEAD,
1009 branch_ref);
1010 if (error) {
1011 if (logmsg_path)
1012 preserve_logmsg = 1;
1013 goto done;
1016 error = got_ref_write(head_ref, repo);
1017 if (error) {
1018 if (logmsg_path)
1019 preserve_logmsg = 1;
1020 goto done;
1024 printf("Created branch %s with commit %s\n",
1025 got_ref_get_name(branch_ref), id_str);
1026 done:
1027 if (pack_fds) {
1028 const struct got_error *pack_err =
1029 got_repo_pack_fds_close(pack_fds);
1030 if (error == NULL)
1031 error = pack_err;
1033 if (repo) {
1034 const struct got_error *close_err = got_repo_close(repo);
1035 if (error == NULL)
1036 error = close_err;
1038 if (preserve_logmsg) {
1039 fprintf(stderr, "%s: log message preserved in %s\n",
1040 getprogname(), logmsg_path);
1041 } else if (logmsg_path && unlink(logmsg_path) == -1 && error == NULL)
1042 error = got_error_from_errno2("unlink", logmsg_path);
1043 free(logmsg);
1044 free(logmsg_path);
1045 free(repo_path);
1046 free(editor);
1047 free(new_commit_id);
1048 free(id_str);
1049 free(author);
1050 free(gitconfig_path);
1051 if (branch_ref)
1052 got_ref_close(branch_ref);
1053 if (head_ref)
1054 got_ref_close(head_ref);
1055 return error;
1058 __dead static void
1059 usage_clone(void)
1061 fprintf(stderr, "usage: %s clone [-almqv] [-b branch] [-R reference] "
1062 "repository-URL [directory]\n", getprogname());
1063 exit(1);
1066 struct got_fetch_progress_arg {
1067 char last_scaled_size[FMT_SCALED_STRSIZE];
1068 int last_p_indexed;
1069 int last_p_resolved;
1070 int verbosity;
1072 struct got_repository *repo;
1074 int create_configs;
1075 int configs_created;
1076 struct {
1077 struct got_pathlist_head *symrefs;
1078 struct got_pathlist_head *wanted_branches;
1079 struct got_pathlist_head *wanted_refs;
1080 const char *proto;
1081 const char *host;
1082 const char *port;
1083 const char *remote_repo_path;
1084 const char *git_url;
1085 int fetch_all_branches;
1086 int mirror_references;
1087 } config_info;
1090 /* XXX forward declaration */
1091 static const struct got_error *
1092 create_config_files(const char *proto, const char *host, const char *port,
1093 const char *remote_repo_path, const char *git_url, int fetch_all_branches,
1094 int mirror_references, struct got_pathlist_head *symrefs,
1095 struct got_pathlist_head *wanted_branches,
1096 struct got_pathlist_head *wanted_refs, struct got_repository *repo);
1098 static const struct got_error *
1099 fetch_progress(void *arg, const char *message, off_t packfile_size,
1100 int nobj_total, int nobj_indexed, int nobj_loose, int nobj_resolved)
1102 const struct got_error *err = NULL;
1103 struct got_fetch_progress_arg *a = arg;
1104 char scaled_size[FMT_SCALED_STRSIZE];
1105 int p_indexed, p_resolved;
1106 int print_size = 0, print_indexed = 0, print_resolved = 0;
1109 * In order to allow a failed clone to be resumed with 'got fetch'
1110 * we try to create configuration files as soon as possible.
1111 * Once the server has sent information about its default branch
1112 * we have all required information.
1114 if (a->create_configs && !a->configs_created &&
1115 !TAILQ_EMPTY(a->config_info.symrefs)) {
1116 err = create_config_files(a->config_info.proto,
1117 a->config_info.host, a->config_info.port,
1118 a->config_info.remote_repo_path,
1119 a->config_info.git_url,
1120 a->config_info.fetch_all_branches,
1121 a->config_info.mirror_references,
1122 a->config_info.symrefs,
1123 a->config_info.wanted_branches,
1124 a->config_info.wanted_refs, a->repo);
1125 if (err)
1126 return err;
1127 a->configs_created = 1;
1130 if (a->verbosity < 0)
1131 return NULL;
1133 if (message && message[0] != '\0') {
1134 printf("\rserver: %s", message);
1135 fflush(stdout);
1136 return NULL;
1139 if (packfile_size > 0 || nobj_indexed > 0) {
1140 if (fmt_scaled(packfile_size, scaled_size) == 0 &&
1141 (a->last_scaled_size[0] == '\0' ||
1142 strcmp(scaled_size, a->last_scaled_size)) != 0) {
1143 print_size = 1;
1144 if (strlcpy(a->last_scaled_size, scaled_size,
1145 FMT_SCALED_STRSIZE) >= FMT_SCALED_STRSIZE)
1146 return got_error(GOT_ERR_NO_SPACE);
1148 if (nobj_indexed > 0) {
1149 p_indexed = (nobj_indexed * 100) / nobj_total;
1150 if (p_indexed != a->last_p_indexed) {
1151 a->last_p_indexed = p_indexed;
1152 print_indexed = 1;
1153 print_size = 1;
1156 if (nobj_resolved > 0) {
1157 p_resolved = (nobj_resolved * 100) /
1158 (nobj_total - nobj_loose);
1159 if (p_resolved != a->last_p_resolved) {
1160 a->last_p_resolved = p_resolved;
1161 print_resolved = 1;
1162 print_indexed = 1;
1163 print_size = 1;
1168 if (print_size || print_indexed || print_resolved)
1169 printf("\r");
1170 if (print_size)
1171 printf("%*s fetched", FMT_SCALED_STRSIZE - 2, scaled_size);
1172 if (print_indexed)
1173 printf("; indexing %d%%", p_indexed);
1174 if (print_resolved)
1175 printf("; resolving deltas %d%%", p_resolved);
1176 if (print_size || print_indexed || print_resolved)
1177 fflush(stdout);
1179 return NULL;
1182 static const struct got_error *
1183 create_symref(const char *refname, struct got_reference *target_ref,
1184 int verbosity, struct got_repository *repo)
1186 const struct got_error *err;
1187 struct got_reference *head_symref;
1189 err = got_ref_alloc_symref(&head_symref, refname, target_ref);
1190 if (err)
1191 return err;
1193 err = got_ref_write(head_symref, repo);
1194 if (err == NULL && verbosity > 0) {
1195 printf("Created reference %s: %s\n", GOT_REF_HEAD,
1196 got_ref_get_name(target_ref));
1198 got_ref_close(head_symref);
1199 return err;
1202 static const struct got_error *
1203 list_remote_refs(struct got_pathlist_head *symrefs,
1204 struct got_pathlist_head *refs)
1206 const struct got_error *err;
1207 struct got_pathlist_entry *pe;
1209 TAILQ_FOREACH(pe, symrefs, entry) {
1210 const char *refname = pe->path;
1211 const char *targetref = pe->data;
1213 printf("%s: %s\n", refname, targetref);
1216 TAILQ_FOREACH(pe, refs, entry) {
1217 const char *refname = pe->path;
1218 struct got_object_id *id = pe->data;
1219 char *id_str;
1221 err = got_object_id_str(&id_str, id);
1222 if (err)
1223 return err;
1224 printf("%s: %s\n", refname, id_str);
1225 free(id_str);
1228 return NULL;
1231 static const struct got_error *
1232 create_ref(const char *refname, struct got_object_id *id,
1233 int verbosity, struct got_repository *repo)
1235 const struct got_error *err = NULL;
1236 struct got_reference *ref;
1237 char *id_str;
1239 err = got_object_id_str(&id_str, id);
1240 if (err)
1241 return err;
1243 err = got_ref_alloc(&ref, refname, id);
1244 if (err)
1245 goto done;
1247 err = got_ref_write(ref, repo);
1248 got_ref_close(ref);
1250 if (err == NULL && verbosity >= 0)
1251 printf("Created reference %s: %s\n", refname, id_str);
1252 done:
1253 free(id_str);
1254 return err;
1257 static int
1258 match_wanted_ref(const char *refname, const char *wanted_ref)
1260 if (strncmp(refname, "refs/", 5) != 0)
1261 return 0;
1262 refname += 5;
1265 * Prevent fetching of references that won't make any
1266 * sense outside of the remote repository's context.
1268 if (strncmp(refname, "got/", 4) == 0)
1269 return 0;
1270 if (strncmp(refname, "remotes/", 8) == 0)
1271 return 0;
1273 if (strncmp(wanted_ref, "refs/", 5) == 0)
1274 wanted_ref += 5;
1276 /* Allow prefix match. */
1277 if (got_path_is_child(refname, wanted_ref, strlen(wanted_ref)))
1278 return 1;
1280 /* Allow exact match. */
1281 return (strcmp(refname, wanted_ref) == 0);
1284 static int
1285 is_wanted_ref(struct got_pathlist_head *wanted_refs, const char *refname)
1287 struct got_pathlist_entry *pe;
1289 TAILQ_FOREACH(pe, wanted_refs, entry) {
1290 if (match_wanted_ref(refname, pe->path))
1291 return 1;
1294 return 0;
1297 static const struct got_error *
1298 create_wanted_ref(const char *refname, struct got_object_id *id,
1299 const char *remote_repo_name, int verbosity, struct got_repository *repo)
1301 const struct got_error *err;
1302 char *remote_refname;
1304 if (strncmp("refs/", refname, 5) == 0)
1305 refname += 5;
1307 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
1308 remote_repo_name, refname) == -1)
1309 return got_error_from_errno("asprintf");
1311 err = create_ref(remote_refname, id, verbosity, repo);
1312 free(remote_refname);
1313 return err;
1316 static const struct got_error *
1317 create_gotconfig(const char *proto, const char *host, const char *port,
1318 const char *remote_repo_path, const char *default_branch,
1319 int fetch_all_branches, struct got_pathlist_head *wanted_branches,
1320 struct got_pathlist_head *wanted_refs, int mirror_references,
1321 struct got_repository *repo)
1323 const struct got_error *err = NULL;
1324 char *gotconfig_path = NULL;
1325 char *gotconfig = NULL;
1326 FILE *gotconfig_file = NULL;
1327 const char *branchname = NULL;
1328 char *branches = NULL, *refs = NULL;
1329 ssize_t n;
1331 if (!fetch_all_branches && !TAILQ_EMPTY(wanted_branches)) {
1332 struct got_pathlist_entry *pe;
1333 TAILQ_FOREACH(pe, wanted_branches, entry) {
1334 char *s;
1335 branchname = pe->path;
1336 if (strncmp(branchname, "refs/heads/", 11) == 0)
1337 branchname += 11;
1338 if (asprintf(&s, "%s\"%s\" ",
1339 branches ? branches : "", branchname) == -1) {
1340 err = got_error_from_errno("asprintf");
1341 goto done;
1343 free(branches);
1344 branches = s;
1346 } else if (!fetch_all_branches && default_branch) {
1347 branchname = default_branch;
1348 if (strncmp(branchname, "refs/heads/", 11) == 0)
1349 branchname += 11;
1350 if (asprintf(&branches, "\"%s\" ", branchname) == -1) {
1351 err = got_error_from_errno("asprintf");
1352 goto done;
1355 if (!TAILQ_EMPTY(wanted_refs)) {
1356 struct got_pathlist_entry *pe;
1357 TAILQ_FOREACH(pe, wanted_refs, entry) {
1358 char *s;
1359 const char *refname = pe->path;
1360 if (strncmp(refname, "refs/", 5) == 0)
1361 branchname += 5;
1362 if (asprintf(&s, "%s\"%s\" ",
1363 refs ? refs : "", refname) == -1) {
1364 err = got_error_from_errno("asprintf");
1365 goto done;
1367 free(refs);
1368 refs = s;
1372 /* Create got.conf(5). */
1373 gotconfig_path = got_repo_get_path_gotconfig(repo);
1374 if (gotconfig_path == NULL) {
1375 err = got_error_from_errno("got_repo_get_path_gotconfig");
1376 goto done;
1378 gotconfig_file = fopen(gotconfig_path, "ae");
1379 if (gotconfig_file == NULL) {
1380 err = got_error_from_errno2("fopen", gotconfig_path);
1381 goto done;
1383 if (asprintf(&gotconfig,
1384 "remote \"%s\" {\n"
1385 "\tserver %s\n"
1386 "\tprotocol %s\n"
1387 "%s%s%s"
1388 "\trepository \"%s\"\n"
1389 "%s%s%s"
1390 "%s%s%s"
1391 "%s"
1392 "%s"
1393 "}\n",
1394 GOT_FETCH_DEFAULT_REMOTE_NAME, host, proto,
1395 port ? "\tport " : "", port ? port : "", port ? "\n" : "",
1396 remote_repo_path, branches ? "\tbranch { " : "",
1397 branches ? branches : "", branches ? "}\n" : "",
1398 refs ? "\treference { " : "", refs ? refs : "", refs ? "}\n" : "",
1399 mirror_references ? "\tmirror_references yes\n" : "",
1400 fetch_all_branches ? "\tfetch_all_branches yes\n" : "") == -1) {
1401 err = got_error_from_errno("asprintf");
1402 goto done;
1404 n = fwrite(gotconfig, 1, strlen(gotconfig), gotconfig_file);
1405 if (n != strlen(gotconfig)) {
1406 err = got_ferror(gotconfig_file, GOT_ERR_IO);
1407 goto done;
1410 done:
1411 if (gotconfig_file && fclose(gotconfig_file) == EOF && err == NULL)
1412 err = got_error_from_errno2("fclose", gotconfig_path);
1413 free(gotconfig_path);
1414 free(branches);
1415 return err;
1418 static const struct got_error *
1419 create_gitconfig(const char *git_url, const char *default_branch,
1420 int fetch_all_branches, struct got_pathlist_head *wanted_branches,
1421 struct got_pathlist_head *wanted_refs, int mirror_references,
1422 struct got_repository *repo)
1424 const struct got_error *err = NULL;
1425 char *gitconfig_path = NULL;
1426 char *gitconfig = NULL;
1427 FILE *gitconfig_file = NULL;
1428 char *branches = NULL, *refs = NULL;
1429 const char *branchname;
1430 ssize_t n;
1432 /* Create a config file Git can understand. */
1433 gitconfig_path = got_repo_get_path_gitconfig(repo);
1434 if (gitconfig_path == NULL) {
1435 err = got_error_from_errno("got_repo_get_path_gitconfig");
1436 goto done;
1438 gitconfig_file = fopen(gitconfig_path, "ae");
1439 if (gitconfig_file == NULL) {
1440 err = got_error_from_errno2("fopen", gitconfig_path);
1441 goto done;
1443 if (fetch_all_branches) {
1444 if (mirror_references) {
1445 if (asprintf(&branches,
1446 "\tfetch = refs/heads/*:refs/heads/*\n") == -1) {
1447 err = got_error_from_errno("asprintf");
1448 goto done;
1450 } else if (asprintf(&branches,
1451 "\tfetch = refs/heads/*:refs/remotes/%s/*\n",
1452 GOT_FETCH_DEFAULT_REMOTE_NAME) == -1) {
1453 err = got_error_from_errno("asprintf");
1454 goto done;
1456 } else if (!TAILQ_EMPTY(wanted_branches)) {
1457 struct got_pathlist_entry *pe;
1458 TAILQ_FOREACH(pe, wanted_branches, entry) {
1459 char *s;
1460 branchname = pe->path;
1461 if (strncmp(branchname, "refs/heads/", 11) == 0)
1462 branchname += 11;
1463 if (mirror_references) {
1464 if (asprintf(&s,
1465 "%s\tfetch = refs/heads/%s:refs/heads/%s\n",
1466 branches ? branches : "",
1467 branchname, branchname) == -1) {
1468 err = got_error_from_errno("asprintf");
1469 goto done;
1471 } else if (asprintf(&s,
1472 "%s\tfetch = refs/heads/%s:refs/remotes/%s/%s\n",
1473 branches ? branches : "",
1474 branchname, GOT_FETCH_DEFAULT_REMOTE_NAME,
1475 branchname) == -1) {
1476 err = got_error_from_errno("asprintf");
1477 goto done;
1479 free(branches);
1480 branches = s;
1482 } else {
1484 * If the server specified a default branch, use just that one.
1485 * Otherwise fall back to fetching all branches on next fetch.
1487 if (default_branch) {
1488 branchname = default_branch;
1489 if (strncmp(branchname, "refs/heads/", 11) == 0)
1490 branchname += 11;
1491 } else
1492 branchname = "*"; /* fall back to all branches */
1493 if (mirror_references) {
1494 if (asprintf(&branches,
1495 "\tfetch = refs/heads/%s:refs/heads/%s\n",
1496 branchname, branchname) == -1) {
1497 err = got_error_from_errno("asprintf");
1498 goto done;
1500 } else if (asprintf(&branches,
1501 "\tfetch = refs/heads/%s:refs/remotes/%s/%s\n",
1502 branchname, GOT_FETCH_DEFAULT_REMOTE_NAME,
1503 branchname) == -1) {
1504 err = got_error_from_errno("asprintf");
1505 goto done;
1508 if (!TAILQ_EMPTY(wanted_refs)) {
1509 struct got_pathlist_entry *pe;
1510 TAILQ_FOREACH(pe, wanted_refs, entry) {
1511 char *s;
1512 const char *refname = pe->path;
1513 if (strncmp(refname, "refs/", 5) == 0)
1514 refname += 5;
1515 if (mirror_references) {
1516 if (asprintf(&s,
1517 "%s\tfetch = refs/%s:refs/%s\n",
1518 refs ? refs : "", refname, refname) == -1) {
1519 err = got_error_from_errno("asprintf");
1520 goto done;
1522 } else if (asprintf(&s,
1523 "%s\tfetch = refs/%s:refs/remotes/%s/%s\n",
1524 refs ? refs : "",
1525 refname, GOT_FETCH_DEFAULT_REMOTE_NAME,
1526 refname) == -1) {
1527 err = got_error_from_errno("asprintf");
1528 goto done;
1530 free(refs);
1531 refs = s;
1535 if (asprintf(&gitconfig,
1536 "[remote \"%s\"]\n"
1537 "\turl = %s\n"
1538 "%s"
1539 "%s"
1540 "\tfetch = refs/tags/*:refs/tags/*\n",
1541 GOT_FETCH_DEFAULT_REMOTE_NAME, git_url, branches ? branches : "",
1542 refs ? refs : "") == -1) {
1543 err = got_error_from_errno("asprintf");
1544 goto done;
1546 n = fwrite(gitconfig, 1, strlen(gitconfig), gitconfig_file);
1547 if (n != strlen(gitconfig)) {
1548 err = got_ferror(gitconfig_file, GOT_ERR_IO);
1549 goto done;
1551 done:
1552 if (gitconfig_file && fclose(gitconfig_file) == EOF && err == NULL)
1553 err = got_error_from_errno2("fclose", gitconfig_path);
1554 free(gitconfig_path);
1555 free(branches);
1556 return err;
1559 static const struct got_error *
1560 create_config_files(const char *proto, const char *host, const char *port,
1561 const char *remote_repo_path, const char *git_url, int fetch_all_branches,
1562 int mirror_references, struct got_pathlist_head *symrefs,
1563 struct got_pathlist_head *wanted_branches,
1564 struct got_pathlist_head *wanted_refs, struct got_repository *repo)
1566 const struct got_error *err = NULL;
1567 const char *default_branch = NULL;
1568 struct got_pathlist_entry *pe;
1571 * If we asked for a set of wanted branches then use the first
1572 * one of those.
1574 if (!TAILQ_EMPTY(wanted_branches)) {
1575 pe = TAILQ_FIRST(wanted_branches);
1576 default_branch = pe->path;
1577 } else {
1578 /* First HEAD ref listed by server is the default branch. */
1579 TAILQ_FOREACH(pe, symrefs, entry) {
1580 const char *refname = pe->path;
1581 const char *target = pe->data;
1583 if (strcmp(refname, GOT_REF_HEAD) != 0)
1584 continue;
1586 default_branch = target;
1587 break;
1591 /* Create got.conf(5). */
1592 err = create_gotconfig(proto, host, port, remote_repo_path,
1593 default_branch, fetch_all_branches, wanted_branches,
1594 wanted_refs, mirror_references, repo);
1595 if (err)
1596 return err;
1598 /* Create a config file Git can understand. */
1599 return create_gitconfig(git_url, default_branch, fetch_all_branches,
1600 wanted_branches, wanted_refs, mirror_references, repo);
1603 static const struct got_error *
1604 cmd_clone(int argc, char *argv[])
1606 const struct got_error *error = NULL;
1607 const char *uri, *dirname;
1608 char *proto, *host, *port, *repo_name, *server_path;
1609 char *default_destdir = NULL, *id_str = NULL;
1610 const char *repo_path;
1611 struct got_repository *repo = NULL;
1612 struct got_pathlist_head refs, symrefs, wanted_branches, wanted_refs;
1613 struct got_pathlist_entry *pe;
1614 struct got_object_id *pack_hash = NULL;
1615 int ch, fetchfd = -1, fetchstatus;
1616 pid_t fetchpid = -1;
1617 struct got_fetch_progress_arg fpa;
1618 char *git_url = NULL;
1619 int verbosity = 0, fetch_all_branches = 0, mirror_references = 0;
1620 int bflag = 0, list_refs_only = 0;
1621 int *pack_fds = NULL;
1623 TAILQ_INIT(&refs);
1624 TAILQ_INIT(&symrefs);
1625 TAILQ_INIT(&wanted_branches);
1626 TAILQ_INIT(&wanted_refs);
1628 while ((ch = getopt(argc, argv, "ab:lmqR:v")) != -1) {
1629 switch (ch) {
1630 case 'a':
1631 fetch_all_branches = 1;
1632 break;
1633 case 'b':
1634 error = got_pathlist_append(&wanted_branches,
1635 optarg, NULL);
1636 if (error)
1637 return error;
1638 bflag = 1;
1639 break;
1640 case 'l':
1641 list_refs_only = 1;
1642 break;
1643 case 'm':
1644 mirror_references = 1;
1645 break;
1646 case 'q':
1647 verbosity = -1;
1648 break;
1649 case 'R':
1650 error = got_pathlist_append(&wanted_refs,
1651 optarg, NULL);
1652 if (error)
1653 return error;
1654 break;
1655 case 'v':
1656 if (verbosity < 0)
1657 verbosity = 0;
1658 else if (verbosity < 3)
1659 verbosity++;
1660 break;
1661 default:
1662 usage_clone();
1663 break;
1666 argc -= optind;
1667 argv += optind;
1669 if (fetch_all_branches && !TAILQ_EMPTY(&wanted_branches))
1670 option_conflict('a', 'b');
1671 if (list_refs_only) {
1672 if (!TAILQ_EMPTY(&wanted_branches))
1673 option_conflict('l', 'b');
1674 if (fetch_all_branches)
1675 option_conflict('l', 'a');
1676 if (mirror_references)
1677 option_conflict('l', 'm');
1678 if (!TAILQ_EMPTY(&wanted_refs))
1679 option_conflict('l', 'R');
1682 uri = argv[0];
1684 if (argc == 1)
1685 dirname = NULL;
1686 else if (argc == 2)
1687 dirname = argv[1];
1688 else
1689 usage_clone();
1691 error = got_dial_parse_uri(&proto, &host, &port, &server_path,
1692 &repo_name, uri);
1693 if (error)
1694 goto done;
1696 if (asprintf(&git_url, "%s://%s%s%s%s%s", proto,
1697 host, port ? ":" : "", port ? port : "",
1698 server_path[0] != '/' ? "/" : "", server_path) == -1) {
1699 error = got_error_from_errno("asprintf");
1700 goto done;
1703 if (strcmp(proto, "git") == 0) {
1704 #ifndef PROFILE
1705 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
1706 "sendfd dns inet unveil", NULL) == -1)
1707 err(1, "pledge");
1708 #endif
1709 } else if (strcmp(proto, "git+ssh") == 0 ||
1710 strcmp(proto, "ssh") == 0 ||
1711 strcmp(proto, "git+http") == 0 ||
1712 strcmp(proto, "http") == 0 ||
1713 strcmp(proto, "git+https") == 0 ||
1714 strcmp(proto, "https") == 0) {
1715 #ifndef PROFILE
1716 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
1717 "sendfd unveil", NULL) == -1)
1718 err(1, "pledge");
1719 #endif
1720 } else {
1721 error = got_error_path(proto, GOT_ERR_BAD_PROTO);
1722 goto done;
1724 if (dirname == NULL) {
1725 if (asprintf(&default_destdir, "%s.git", repo_name) == -1) {
1726 error = got_error_from_errno("asprintf");
1727 goto done;
1729 repo_path = default_destdir;
1730 } else
1731 repo_path = dirname;
1733 if (!list_refs_only) {
1734 error = got_path_mkdir(repo_path);
1735 if (error &&
1736 (!(error->code == GOT_ERR_ERRNO && errno == EISDIR) &&
1737 !(error->code == GOT_ERR_ERRNO && errno == EEXIST)))
1738 goto done;
1739 if (!got_path_dir_is_empty(repo_path)) {
1740 error = got_error_path(repo_path,
1741 GOT_ERR_DIR_NOT_EMPTY);
1742 goto done;
1746 error = got_dial_apply_unveil(proto);
1747 if (error)
1748 goto done;
1750 error = apply_unveil(repo_path, 0, NULL);
1751 if (error)
1752 goto done;
1754 if (verbosity >= 0)
1755 printf("Connecting to %s\n", git_url);
1757 error = got_fetch_connect(&fetchpid, &fetchfd, proto, host, port,
1758 server_path, verbosity);
1759 if (error)
1760 goto done;
1762 #ifndef PROFILE
1763 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd",
1764 NULL) == -1)
1765 err(1, "pledge");
1766 #endif
1767 if (!list_refs_only) {
1768 error = got_repo_init(repo_path, NULL);
1769 if (error)
1770 goto done;
1771 error = got_repo_pack_fds_open(&pack_fds);
1772 if (error != NULL)
1773 goto done;
1774 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
1775 if (error)
1776 goto done;
1779 fpa.last_scaled_size[0] = '\0';
1780 fpa.last_p_indexed = -1;
1781 fpa.last_p_resolved = -1;
1782 fpa.verbosity = verbosity;
1783 fpa.create_configs = 1;
1784 fpa.configs_created = 0;
1785 fpa.repo = repo;
1786 fpa.config_info.symrefs = &symrefs;
1787 fpa.config_info.wanted_branches = &wanted_branches;
1788 fpa.config_info.wanted_refs = &wanted_refs;
1789 fpa.config_info.proto = proto;
1790 fpa.config_info.host = host;
1791 fpa.config_info.port = port;
1792 fpa.config_info.remote_repo_path = server_path;
1793 fpa.config_info.git_url = git_url;
1794 fpa.config_info.fetch_all_branches = fetch_all_branches;
1795 fpa.config_info.mirror_references = mirror_references;
1796 error = got_fetch_pack(&pack_hash, &refs, &symrefs,
1797 GOT_FETCH_DEFAULT_REMOTE_NAME, mirror_references,
1798 fetch_all_branches, &wanted_branches, &wanted_refs,
1799 list_refs_only, verbosity, fetchfd, repo, NULL, NULL, bflag,
1800 fetch_progress, &fpa);
1801 if (error)
1802 goto done;
1804 if (list_refs_only) {
1805 error = list_remote_refs(&symrefs, &refs);
1806 goto done;
1809 if (pack_hash == NULL) {
1810 error = got_error_fmt(GOT_ERR_FETCH_FAILED, "%s",
1811 "server sent an empty pack file");
1812 goto done;
1814 error = got_object_id_str(&id_str, pack_hash);
1815 if (error)
1816 goto done;
1817 if (verbosity >= 0)
1818 printf("\nFetched %s.pack\n", id_str);
1819 free(id_str);
1821 /* Set up references provided with the pack file. */
1822 TAILQ_FOREACH(pe, &refs, entry) {
1823 const char *refname = pe->path;
1824 struct got_object_id *id = pe->data;
1825 char *remote_refname;
1827 if (is_wanted_ref(&wanted_refs, refname) &&
1828 !mirror_references) {
1829 error = create_wanted_ref(refname, id,
1830 GOT_FETCH_DEFAULT_REMOTE_NAME,
1831 verbosity - 1, repo);
1832 if (error)
1833 goto done;
1834 continue;
1837 error = create_ref(refname, id, verbosity - 1, repo);
1838 if (error)
1839 goto done;
1841 if (mirror_references)
1842 continue;
1844 if (strncmp("refs/heads/", refname, 11) != 0)
1845 continue;
1847 if (asprintf(&remote_refname,
1848 "refs/remotes/%s/%s", GOT_FETCH_DEFAULT_REMOTE_NAME,
1849 refname + 11) == -1) {
1850 error = got_error_from_errno("asprintf");
1851 goto done;
1853 error = create_ref(remote_refname, id, verbosity - 1, repo);
1854 free(remote_refname);
1855 if (error)
1856 goto done;
1859 /* Set the HEAD reference if the server provided one. */
1860 TAILQ_FOREACH(pe, &symrefs, entry) {
1861 struct got_reference *target_ref;
1862 const char *refname = pe->path;
1863 const char *target = pe->data;
1864 char *remote_refname = NULL, *remote_target = NULL;
1866 if (strcmp(refname, GOT_REF_HEAD) != 0)
1867 continue;
1869 error = got_ref_open(&target_ref, repo, target, 0);
1870 if (error) {
1871 if (error->code == GOT_ERR_NOT_REF) {
1872 error = NULL;
1873 continue;
1875 goto done;
1878 error = create_symref(refname, target_ref, verbosity, repo);
1879 got_ref_close(target_ref);
1880 if (error)
1881 goto done;
1883 if (mirror_references)
1884 continue;
1886 if (strncmp("refs/heads/", target, 11) != 0)
1887 continue;
1889 if (asprintf(&remote_refname,
1890 "refs/remotes/%s/%s", GOT_FETCH_DEFAULT_REMOTE_NAME,
1891 refname) == -1) {
1892 error = got_error_from_errno("asprintf");
1893 goto done;
1895 if (asprintf(&remote_target,
1896 "refs/remotes/%s/%s", GOT_FETCH_DEFAULT_REMOTE_NAME,
1897 target + 11) == -1) {
1898 error = got_error_from_errno("asprintf");
1899 free(remote_refname);
1900 goto done;
1902 error = got_ref_open(&target_ref, repo, remote_target, 0);
1903 if (error) {
1904 free(remote_refname);
1905 free(remote_target);
1906 if (error->code == GOT_ERR_NOT_REF) {
1907 error = NULL;
1908 continue;
1910 goto done;
1912 error = create_symref(remote_refname, target_ref,
1913 verbosity - 1, repo);
1914 free(remote_refname);
1915 free(remote_target);
1916 got_ref_close(target_ref);
1917 if (error)
1918 goto done;
1920 if (pe == NULL) {
1922 * We failed to set the HEAD reference. If we asked for
1923 * a set of wanted branches use the first of one of those
1924 * which could be fetched instead.
1926 TAILQ_FOREACH(pe, &wanted_branches, entry) {
1927 const char *target = pe->path;
1928 struct got_reference *target_ref;
1930 error = got_ref_open(&target_ref, repo, target, 0);
1931 if (error) {
1932 if (error->code == GOT_ERR_NOT_REF) {
1933 error = NULL;
1934 continue;
1936 goto done;
1939 error = create_symref(GOT_REF_HEAD, target_ref,
1940 verbosity, repo);
1941 got_ref_close(target_ref);
1942 if (error)
1943 goto done;
1944 break;
1947 if (!fpa.configs_created && pe != NULL) {
1948 error = create_config_files(fpa.config_info.proto,
1949 fpa.config_info.host, fpa.config_info.port,
1950 fpa.config_info.remote_repo_path,
1951 fpa.config_info.git_url,
1952 fpa.config_info.fetch_all_branches,
1953 fpa.config_info.mirror_references,
1954 fpa.config_info.symrefs,
1955 fpa.config_info.wanted_branches,
1956 fpa.config_info.wanted_refs, fpa.repo);
1957 if (error)
1958 goto done;
1962 if (verbosity >= 0)
1963 printf("Created %s repository '%s'\n",
1964 mirror_references ? "mirrored" : "cloned", repo_path);
1965 done:
1966 if (pack_fds) {
1967 const struct got_error *pack_err =
1968 got_repo_pack_fds_close(pack_fds);
1969 if (error == NULL)
1970 error = pack_err;
1972 if (fetchpid > 0) {
1973 if (kill(fetchpid, SIGTERM) == -1)
1974 error = got_error_from_errno("kill");
1975 if (waitpid(fetchpid, &fetchstatus, 0) == -1 && error == NULL)
1976 error = got_error_from_errno("waitpid");
1978 if (fetchfd != -1 && close(fetchfd) == -1 && error == NULL)
1979 error = got_error_from_errno("close");
1980 if (repo) {
1981 const struct got_error *close_err = got_repo_close(repo);
1982 if (error == NULL)
1983 error = close_err;
1985 got_pathlist_free(&refs, GOT_PATHLIST_FREE_ALL);
1986 got_pathlist_free(&symrefs, GOT_PATHLIST_FREE_ALL);
1987 got_pathlist_free(&wanted_branches, GOT_PATHLIST_FREE_NONE);
1988 got_pathlist_free(&wanted_refs, GOT_PATHLIST_FREE_NONE);
1989 free(pack_hash);
1990 free(proto);
1991 free(host);
1992 free(port);
1993 free(server_path);
1994 free(repo_name);
1995 free(default_destdir);
1996 free(git_url);
1997 return error;
2000 static const struct got_error *
2001 update_ref(struct got_reference *ref, struct got_object_id *new_id,
2002 int replace_tags, int verbosity, struct got_repository *repo)
2004 const struct got_error *err = NULL;
2005 char *new_id_str = NULL;
2006 struct got_object_id *old_id = NULL;
2008 err = got_object_id_str(&new_id_str, new_id);
2009 if (err)
2010 goto done;
2012 if (!replace_tags &&
2013 strncmp(got_ref_get_name(ref), "refs/tags/", 10) == 0) {
2014 err = got_ref_resolve(&old_id, repo, ref);
2015 if (err)
2016 goto done;
2017 if (got_object_id_cmp(old_id, new_id) == 0)
2018 goto done;
2019 if (verbosity >= 0) {
2020 printf("Rejecting update of existing tag %s: %s\n",
2021 got_ref_get_name(ref), new_id_str);
2023 goto done;
2026 if (got_ref_is_symbolic(ref)) {
2027 if (verbosity >= 0) {
2028 printf("Replacing reference %s: %s\n",
2029 got_ref_get_name(ref),
2030 got_ref_get_symref_target(ref));
2032 err = got_ref_change_symref_to_ref(ref, new_id);
2033 if (err)
2034 goto done;
2035 err = got_ref_write(ref, repo);
2036 if (err)
2037 goto done;
2038 } else {
2039 err = got_ref_resolve(&old_id, repo, ref);
2040 if (err)
2041 goto done;
2042 if (got_object_id_cmp(old_id, new_id) == 0)
2043 goto done;
2045 err = got_ref_change_ref(ref, new_id);
2046 if (err)
2047 goto done;
2048 err = got_ref_write(ref, repo);
2049 if (err)
2050 goto done;
2053 if (verbosity >= 0)
2054 printf("Updated %s: %s\n", got_ref_get_name(ref),
2055 new_id_str);
2056 done:
2057 free(old_id);
2058 free(new_id_str);
2059 return err;
2062 static const struct got_error *
2063 update_symref(const char *refname, struct got_reference *target_ref,
2064 int verbosity, struct got_repository *repo)
2066 const struct got_error *err = NULL, *unlock_err;
2067 struct got_reference *symref;
2068 int symref_is_locked = 0;
2070 err = got_ref_open(&symref, repo, refname, 1);
2071 if (err) {
2072 if (err->code != GOT_ERR_NOT_REF)
2073 return err;
2074 err = got_ref_alloc_symref(&symref, refname, target_ref);
2075 if (err)
2076 goto done;
2078 err = got_ref_write(symref, repo);
2079 if (err)
2080 goto done;
2082 if (verbosity >= 0)
2083 printf("Created reference %s: %s\n",
2084 got_ref_get_name(symref),
2085 got_ref_get_symref_target(symref));
2086 } else {
2087 symref_is_locked = 1;
2089 if (strcmp(got_ref_get_symref_target(symref),
2090 got_ref_get_name(target_ref)) == 0)
2091 goto done;
2093 err = got_ref_change_symref(symref,
2094 got_ref_get_name(target_ref));
2095 if (err)
2096 goto done;
2098 err = got_ref_write(symref, repo);
2099 if (err)
2100 goto done;
2102 if (verbosity >= 0)
2103 printf("Updated %s: %s\n", got_ref_get_name(symref),
2104 got_ref_get_symref_target(symref));
2107 done:
2108 if (symref_is_locked) {
2109 unlock_err = got_ref_unlock(symref);
2110 if (unlock_err && err == NULL)
2111 err = unlock_err;
2113 got_ref_close(symref);
2114 return err;
2117 __dead static void
2118 usage_fetch(void)
2120 fprintf(stderr, "usage: %s fetch [-adlqtvX] [-b branch] "
2121 "[-R reference] [-r repository-path] [remote-repository]\n",
2122 getprogname());
2123 exit(1);
2126 static const struct got_error *
2127 delete_missing_ref(struct got_reference *ref,
2128 int verbosity, struct got_repository *repo)
2130 const struct got_error *err = NULL;
2131 struct got_object_id *id = NULL;
2132 char *id_str = NULL;
2134 if (got_ref_is_symbolic(ref)) {
2135 err = got_ref_delete(ref, repo);
2136 if (err)
2137 return err;
2138 if (verbosity >= 0) {
2139 printf("Deleted %s: %s\n",
2140 got_ref_get_name(ref),
2141 got_ref_get_symref_target(ref));
2143 } else {
2144 err = got_ref_resolve(&id, repo, ref);
2145 if (err)
2146 return err;
2147 err = got_object_id_str(&id_str, id);
2148 if (err)
2149 goto done;
2151 err = got_ref_delete(ref, repo);
2152 if (err)
2153 goto done;
2154 if (verbosity >= 0) {
2155 printf("Deleted %s: %s\n",
2156 got_ref_get_name(ref), id_str);
2159 done:
2160 free(id);
2161 free(id_str);
2162 return err;
2165 static const struct got_error *
2166 delete_missing_refs(struct got_pathlist_head *their_refs,
2167 struct got_pathlist_head *their_symrefs,
2168 const struct got_remote_repo *remote,
2169 int verbosity, struct got_repository *repo)
2171 const struct got_error *err = NULL, *unlock_err;
2172 struct got_reflist_head my_refs;
2173 struct got_reflist_entry *re;
2174 struct got_pathlist_entry *pe;
2175 char *remote_namespace = NULL;
2176 char *local_refname = NULL;
2178 TAILQ_INIT(&my_refs);
2180 if (asprintf(&remote_namespace, "refs/remotes/%s/", remote->name)
2181 == -1)
2182 return got_error_from_errno("asprintf");
2184 err = got_ref_list(&my_refs, repo, NULL, got_ref_cmp_by_name, NULL);
2185 if (err)
2186 goto done;
2188 TAILQ_FOREACH(re, &my_refs, entry) {
2189 const char *refname = got_ref_get_name(re->ref);
2190 const char *their_refname;
2192 if (remote->mirror_references) {
2193 their_refname = refname;
2194 } else {
2195 if (strncmp(refname, remote_namespace,
2196 strlen(remote_namespace)) == 0) {
2197 if (strcmp(refname + strlen(remote_namespace),
2198 GOT_REF_HEAD) == 0)
2199 continue;
2200 if (asprintf(&local_refname, "refs/heads/%s",
2201 refname + strlen(remote_namespace)) == -1) {
2202 err = got_error_from_errno("asprintf");
2203 goto done;
2205 } else if (strncmp(refname, "refs/tags/", 10) != 0)
2206 continue;
2208 their_refname = local_refname;
2211 TAILQ_FOREACH(pe, their_refs, entry) {
2212 if (strcmp(their_refname, pe->path) == 0)
2213 break;
2215 if (pe != NULL)
2216 continue;
2218 TAILQ_FOREACH(pe, their_symrefs, entry) {
2219 if (strcmp(their_refname, pe->path) == 0)
2220 break;
2222 if (pe != NULL)
2223 continue;
2225 err = delete_missing_ref(re->ref, verbosity, repo);
2226 if (err)
2227 break;
2229 if (local_refname) {
2230 struct got_reference *ref;
2231 err = got_ref_open(&ref, repo, local_refname, 1);
2232 if (err) {
2233 if (err->code != GOT_ERR_NOT_REF)
2234 break;
2235 free(local_refname);
2236 local_refname = NULL;
2237 continue;
2239 err = delete_missing_ref(ref, verbosity, repo);
2240 if (err)
2241 break;
2242 unlock_err = got_ref_unlock(ref);
2243 got_ref_close(ref);
2244 if (unlock_err && err == NULL) {
2245 err = unlock_err;
2246 break;
2249 free(local_refname);
2250 local_refname = NULL;
2253 done:
2254 got_ref_list_free(&my_refs);
2255 free(remote_namespace);
2256 free(local_refname);
2257 return err;
2260 static const struct got_error *
2261 update_wanted_ref(const char *refname, struct got_object_id *id,
2262 const char *remote_repo_name, int verbosity, struct got_repository *repo)
2264 const struct got_error *err, *unlock_err;
2265 char *remote_refname;
2266 struct got_reference *ref;
2268 if (strncmp("refs/", refname, 5) == 0)
2269 refname += 5;
2271 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
2272 remote_repo_name, refname) == -1)
2273 return got_error_from_errno("asprintf");
2275 err = got_ref_open(&ref, repo, remote_refname, 1);
2276 if (err) {
2277 if (err->code != GOT_ERR_NOT_REF)
2278 goto done;
2279 err = create_ref(remote_refname, id, verbosity, repo);
2280 } else {
2281 err = update_ref(ref, id, 0, verbosity, repo);
2282 unlock_err = got_ref_unlock(ref);
2283 if (unlock_err && err == NULL)
2284 err = unlock_err;
2285 got_ref_close(ref);
2287 done:
2288 free(remote_refname);
2289 return err;
2292 static const struct got_error *
2293 delete_ref(struct got_repository *repo, struct got_reference *ref)
2295 const struct got_error *err = NULL;
2296 struct got_object_id *id = NULL;
2297 char *id_str = NULL;
2298 const char *target;
2300 if (got_ref_is_symbolic(ref)) {
2301 target = got_ref_get_symref_target(ref);
2302 } else {
2303 err = got_ref_resolve(&id, repo, ref);
2304 if (err)
2305 goto done;
2306 err = got_object_id_str(&id_str, id);
2307 if (err)
2308 goto done;
2309 target = id_str;
2312 err = got_ref_delete(ref, repo);
2313 if (err)
2314 goto done;
2316 printf("Deleted %s: %s\n", got_ref_get_name(ref), target);
2317 done:
2318 free(id);
2319 free(id_str);
2320 return err;
2323 static const struct got_error *
2324 delete_refs_for_remote(struct got_repository *repo, const char *remote_name)
2326 const struct got_error *err = NULL;
2327 struct got_reflist_head refs;
2328 struct got_reflist_entry *re;
2329 char *prefix;
2331 TAILQ_INIT(&refs);
2333 if (asprintf(&prefix, "refs/remotes/%s", remote_name) == -1) {
2334 err = got_error_from_errno("asprintf");
2335 goto done;
2337 err = got_ref_list(&refs, repo, prefix, got_ref_cmp_by_name, NULL);
2338 if (err)
2339 goto done;
2341 TAILQ_FOREACH(re, &refs, entry)
2342 delete_ref(repo, re->ref);
2343 done:
2344 got_ref_list_free(&refs);
2345 return err;
2348 static const struct got_error *
2349 cmd_fetch(int argc, char *argv[])
2351 const struct got_error *error = NULL, *unlock_err;
2352 char *cwd = NULL, *repo_path = NULL;
2353 const char *remote_name;
2354 char *proto = NULL, *host = NULL, *port = NULL;
2355 char *repo_name = NULL, *server_path = NULL;
2356 const struct got_remote_repo *remotes;
2357 struct got_remote_repo *remote = NULL;
2358 int nremotes;
2359 char *id_str = NULL;
2360 struct got_repository *repo = NULL;
2361 struct got_worktree *worktree = NULL;
2362 const struct got_gotconfig *repo_conf = NULL, *worktree_conf = NULL;
2363 struct got_pathlist_head refs, symrefs, wanted_branches, wanted_refs;
2364 char *head_refname = NULL;
2365 struct got_pathlist_entry *pe;
2366 struct got_reflist_head remote_refs;
2367 struct got_reflist_entry *re;
2368 struct got_object_id *pack_hash = NULL;
2369 int i, ch, fetchfd = -1, fetchstatus;
2370 pid_t fetchpid = -1;
2371 struct got_fetch_progress_arg fpa;
2372 int verbosity = 0, fetch_all_branches = 0, list_refs_only = 0;
2373 int delete_refs = 0, replace_tags = 0, delete_remote = 0;
2374 int *pack_fds = NULL, have_bflag = 0;
2375 const char *remote_head = NULL, *worktree_branch = NULL;
2377 TAILQ_INIT(&refs);
2378 TAILQ_INIT(&symrefs);
2379 TAILQ_INIT(&remote_refs);
2380 TAILQ_INIT(&wanted_branches);
2381 TAILQ_INIT(&wanted_refs);
2383 while ((ch = getopt(argc, argv, "ab:dlqR:r:tvX")) != -1) {
2384 switch (ch) {
2385 case 'a':
2386 fetch_all_branches = 1;
2387 break;
2388 case 'b':
2389 error = got_pathlist_append(&wanted_branches,
2390 optarg, NULL);
2391 if (error)
2392 return error;
2393 have_bflag = 1;
2394 break;
2395 case 'd':
2396 delete_refs = 1;
2397 break;
2398 case 'l':
2399 list_refs_only = 1;
2400 break;
2401 case 'q':
2402 verbosity = -1;
2403 break;
2404 case 'R':
2405 error = got_pathlist_append(&wanted_refs,
2406 optarg, NULL);
2407 if (error)
2408 return error;
2409 break;
2410 case 'r':
2411 repo_path = realpath(optarg, NULL);
2412 if (repo_path == NULL)
2413 return got_error_from_errno2("realpath",
2414 optarg);
2415 got_path_strip_trailing_slashes(repo_path);
2416 break;
2417 case 't':
2418 replace_tags = 1;
2419 break;
2420 case 'v':
2421 if (verbosity < 0)
2422 verbosity = 0;
2423 else if (verbosity < 3)
2424 verbosity++;
2425 break;
2426 case 'X':
2427 delete_remote = 1;
2428 break;
2429 default:
2430 usage_fetch();
2431 break;
2434 argc -= optind;
2435 argv += optind;
2437 if (fetch_all_branches && !TAILQ_EMPTY(&wanted_branches))
2438 option_conflict('a', 'b');
2439 if (list_refs_only) {
2440 if (!TAILQ_EMPTY(&wanted_branches))
2441 option_conflict('l', 'b');
2442 if (fetch_all_branches)
2443 option_conflict('l', 'a');
2444 if (delete_refs)
2445 option_conflict('l', 'd');
2446 if (delete_remote)
2447 option_conflict('l', 'X');
2449 if (delete_remote) {
2450 if (fetch_all_branches)
2451 option_conflict('X', 'a');
2452 if (!TAILQ_EMPTY(&wanted_branches))
2453 option_conflict('X', 'b');
2454 if (delete_refs)
2455 option_conflict('X', 'd');
2456 if (replace_tags)
2457 option_conflict('X', 't');
2458 if (!TAILQ_EMPTY(&wanted_refs))
2459 option_conflict('X', 'R');
2462 if (argc == 0) {
2463 if (delete_remote)
2464 errx(1, "-X option requires a remote name");
2465 remote_name = GOT_FETCH_DEFAULT_REMOTE_NAME;
2466 } else if (argc == 1)
2467 remote_name = argv[0];
2468 else
2469 usage_fetch();
2471 cwd = getcwd(NULL, 0);
2472 if (cwd == NULL) {
2473 error = got_error_from_errno("getcwd");
2474 goto done;
2477 error = got_repo_pack_fds_open(&pack_fds);
2478 if (error != NULL)
2479 goto done;
2481 if (repo_path == NULL) {
2482 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
2483 if (error && error->code != GOT_ERR_NOT_WORKTREE)
2484 goto done;
2485 else
2486 error = NULL;
2487 if (worktree) {
2488 repo_path =
2489 strdup(got_worktree_get_repo_path(worktree));
2490 if (repo_path == NULL)
2491 error = got_error_from_errno("strdup");
2492 if (error)
2493 goto done;
2494 } else {
2495 repo_path = strdup(cwd);
2496 if (repo_path == NULL) {
2497 error = got_error_from_errno("strdup");
2498 goto done;
2503 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
2504 if (error)
2505 goto done;
2507 if (delete_remote) {
2508 error = delete_refs_for_remote(repo, remote_name);
2509 goto done; /* nothing else to do */
2512 if (worktree) {
2513 worktree_conf = got_worktree_get_gotconfig(worktree);
2514 if (worktree_conf) {
2515 got_gotconfig_get_remotes(&nremotes, &remotes,
2516 worktree_conf);
2517 for (i = 0; i < nremotes; i++) {
2518 if (strcmp(remotes[i].name, remote_name) == 0) {
2519 error = got_repo_remote_repo_dup(&remote,
2520 &remotes[i]);
2521 if (error)
2522 goto done;
2523 break;
2528 if (remote == NULL) {
2529 repo_conf = got_repo_get_gotconfig(repo);
2530 if (repo_conf) {
2531 got_gotconfig_get_remotes(&nremotes, &remotes,
2532 repo_conf);
2533 for (i = 0; i < nremotes; i++) {
2534 if (strcmp(remotes[i].name, remote_name) == 0) {
2535 error = got_repo_remote_repo_dup(&remote,
2536 &remotes[i]);
2537 if (error)
2538 goto done;
2539 break;
2544 if (remote == NULL) {
2545 got_repo_get_gitconfig_remotes(&nremotes, &remotes, repo);
2546 for (i = 0; i < nremotes; i++) {
2547 if (strcmp(remotes[i].name, remote_name) == 0) {
2548 error = got_repo_remote_repo_dup(&remote,
2549 &remotes[i]);
2550 if (error)
2551 goto done;
2552 break;
2556 if (remote == NULL) {
2557 error = got_error_path(remote_name, GOT_ERR_NO_REMOTE);
2558 goto done;
2561 if (TAILQ_EMPTY(&wanted_branches)) {
2562 if (!fetch_all_branches)
2563 fetch_all_branches = remote->fetch_all_branches;
2564 for (i = 0; i < remote->nfetch_branches; i++) {
2565 error = got_pathlist_append(&wanted_branches,
2566 remote->fetch_branches[i], NULL);
2567 if (error)
2568 goto done;
2571 if (TAILQ_EMPTY(&wanted_refs)) {
2572 for (i = 0; i < remote->nfetch_refs; i++) {
2573 error = got_pathlist_append(&wanted_refs,
2574 remote->fetch_refs[i], NULL);
2575 if (error)
2576 goto done;
2580 error = got_dial_parse_uri(&proto, &host, &port, &server_path,
2581 &repo_name, remote->fetch_url);
2582 if (error)
2583 goto done;
2585 if (strcmp(proto, "git") == 0) {
2586 #ifndef PROFILE
2587 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
2588 "sendfd dns inet unveil", NULL) == -1)
2589 err(1, "pledge");
2590 #endif
2591 } else if (strcmp(proto, "git+ssh") == 0 ||
2592 strcmp(proto, "ssh") == 0 ||
2593 strcmp(proto, "git+http") == 0 ||
2594 strcmp(proto, "http") == 0 ||
2595 strcmp(proto, "git+https") == 0 ||
2596 strcmp(proto, "https") == 0) {
2597 #ifndef PROFILE
2598 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
2599 "sendfd unveil", NULL) == -1)
2600 err(1, "pledge");
2601 #endif
2602 } else {
2603 error = got_error_path(proto, GOT_ERR_BAD_PROTO);
2604 goto done;
2607 error = got_dial_apply_unveil(proto);
2608 if (error)
2609 goto done;
2611 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
2612 if (error)
2613 goto done;
2615 if (worktree) {
2616 head_refname = strdup(got_worktree_get_head_ref_name(worktree));
2617 if (head_refname == NULL) {
2618 error = got_error_from_errno("strdup");
2619 goto done;
2622 /* Release work tree lock. */
2623 got_worktree_close(worktree);
2624 worktree = NULL;
2627 if (verbosity >= 0) {
2628 printf("Connecting to \"%s\" %s://%s%s%s%s%s\n",
2629 remote->name, proto, host,
2630 port ? ":" : "", port ? port : "",
2631 *server_path == '/' ? "" : "/", server_path);
2634 error = got_fetch_connect(&fetchpid, &fetchfd, proto, host, port,
2635 server_path, verbosity);
2636 if (error)
2637 goto done;
2638 #ifndef PROFILE
2639 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd",
2640 NULL) == -1)
2641 err(1, "pledge");
2642 #endif
2643 if (!have_bflag) {
2645 * If set, get this remote's HEAD ref target so
2646 * if it has changed on the server we can fetch it.
2648 error = got_ref_list(&remote_refs, repo, "refs/remotes",
2649 got_ref_cmp_by_name, repo);
2650 if (error)
2651 goto done;
2653 TAILQ_FOREACH(re, &remote_refs, entry) {
2654 const char *remote_refname, *remote_target;
2655 size_t remote_name_len;
2657 if (!got_ref_is_symbolic(re->ref))
2658 continue;
2660 remote_name_len = strlen(remote->name);
2661 remote_refname = got_ref_get_name(re->ref);
2663 /* we only want refs/remotes/$remote->name/HEAD */
2664 if (strncmp(remote_refname + 13, remote->name,
2665 remote_name_len) != 0)
2666 continue;
2668 if (strcmp(remote_refname + remote_name_len + 14,
2669 GOT_REF_HEAD) != 0)
2670 continue;
2673 * Take the name itself because we already
2674 * only match with refs/heads/ in fetch_pack().
2676 remote_target = got_ref_get_symref_target(re->ref);
2677 remote_head = remote_target + remote_name_len + 14;
2678 break;
2681 if (head_refname &&
2682 strncmp(head_refname, "refs/heads/", 11) == 0)
2683 worktree_branch = head_refname;
2686 fpa.last_scaled_size[0] = '\0';
2687 fpa.last_p_indexed = -1;
2688 fpa.last_p_resolved = -1;
2689 fpa.verbosity = verbosity;
2690 fpa.repo = repo;
2691 fpa.create_configs = 0;
2692 fpa.configs_created = 0;
2693 memset(&fpa.config_info, 0, sizeof(fpa.config_info));
2695 error = got_fetch_pack(&pack_hash, &refs, &symrefs, remote->name,
2696 remote->mirror_references, fetch_all_branches, &wanted_branches,
2697 &wanted_refs, list_refs_only, verbosity, fetchfd, repo,
2698 worktree_branch, remote_head, have_bflag, fetch_progress, &fpa);
2699 if (error)
2700 goto done;
2702 if (list_refs_only) {
2703 error = list_remote_refs(&symrefs, &refs);
2704 goto done;
2707 if (pack_hash == NULL) {
2708 if (verbosity >= 0)
2709 printf("Already up-to-date\n");
2710 } else if (verbosity >= 0) {
2711 error = got_object_id_str(&id_str, pack_hash);
2712 if (error)
2713 goto done;
2714 printf("\nFetched %s.pack\n", id_str);
2715 free(id_str);
2716 id_str = NULL;
2719 /* Update references provided with the pack file. */
2720 TAILQ_FOREACH(pe, &refs, entry) {
2721 const char *refname = pe->path;
2722 struct got_object_id *id = pe->data;
2723 struct got_reference *ref;
2724 char *remote_refname;
2726 if (is_wanted_ref(&wanted_refs, refname) &&
2727 !remote->mirror_references) {
2728 error = update_wanted_ref(refname, id,
2729 remote->name, verbosity, repo);
2730 if (error)
2731 goto done;
2732 continue;
2735 if (remote->mirror_references ||
2736 strncmp("refs/tags/", refname, 10) == 0) {
2737 error = got_ref_open(&ref, repo, refname, 1);
2738 if (error) {
2739 if (error->code != GOT_ERR_NOT_REF)
2740 goto done;
2741 error = create_ref(refname, id, verbosity,
2742 repo);
2743 if (error)
2744 goto done;
2745 } else {
2746 error = update_ref(ref, id, replace_tags,
2747 verbosity, repo);
2748 unlock_err = got_ref_unlock(ref);
2749 if (unlock_err && error == NULL)
2750 error = unlock_err;
2751 got_ref_close(ref);
2752 if (error)
2753 goto done;
2755 } else if (strncmp("refs/heads/", refname, 11) == 0) {
2756 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
2757 remote_name, refname + 11) == -1) {
2758 error = got_error_from_errno("asprintf");
2759 goto done;
2762 error = got_ref_open(&ref, repo, remote_refname, 1);
2763 if (error) {
2764 if (error->code != GOT_ERR_NOT_REF)
2765 goto done;
2766 error = create_ref(remote_refname, id,
2767 verbosity, repo);
2768 if (error)
2769 goto done;
2770 } else {
2771 error = update_ref(ref, id, replace_tags,
2772 verbosity, repo);
2773 unlock_err = got_ref_unlock(ref);
2774 if (unlock_err && error == NULL)
2775 error = unlock_err;
2776 got_ref_close(ref);
2777 if (error)
2778 goto done;
2781 /* Also create a local branch if none exists yet. */
2782 error = got_ref_open(&ref, repo, refname, 1);
2783 if (error) {
2784 if (error->code != GOT_ERR_NOT_REF)
2785 goto done;
2786 error = create_ref(refname, id, verbosity,
2787 repo);
2788 if (error)
2789 goto done;
2790 } else {
2791 unlock_err = got_ref_unlock(ref);
2792 if (unlock_err && error == NULL)
2793 error = unlock_err;
2794 got_ref_close(ref);
2798 if (delete_refs) {
2799 error = delete_missing_refs(&refs, &symrefs, remote,
2800 verbosity, repo);
2801 if (error)
2802 goto done;
2805 if (!remote->mirror_references) {
2806 /* Update remote HEAD reference if the server provided one. */
2807 TAILQ_FOREACH(pe, &symrefs, entry) {
2808 struct got_reference *target_ref;
2809 const char *refname = pe->path;
2810 const char *target = pe->data;
2811 char *remote_refname = NULL, *remote_target = NULL;
2813 if (strcmp(refname, GOT_REF_HEAD) != 0)
2814 continue;
2816 if (strncmp("refs/heads/", target, 11) != 0)
2817 continue;
2819 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
2820 remote->name, refname) == -1) {
2821 error = got_error_from_errno("asprintf");
2822 goto done;
2824 if (asprintf(&remote_target, "refs/remotes/%s/%s",
2825 remote->name, target + 11) == -1) {
2826 error = got_error_from_errno("asprintf");
2827 free(remote_refname);
2828 goto done;
2831 error = got_ref_open(&target_ref, repo, remote_target,
2832 0);
2833 if (error) {
2834 free(remote_refname);
2835 free(remote_target);
2836 if (error->code == GOT_ERR_NOT_REF) {
2837 error = NULL;
2838 continue;
2840 goto done;
2842 error = update_symref(remote_refname, target_ref,
2843 verbosity, repo);
2844 free(remote_refname);
2845 free(remote_target);
2846 got_ref_close(target_ref);
2847 if (error)
2848 goto done;
2851 done:
2852 if (fetchpid > 0) {
2853 if (kill(fetchpid, SIGTERM) == -1)
2854 error = got_error_from_errno("kill");
2855 if (waitpid(fetchpid, &fetchstatus, 0) == -1 && error == NULL)
2856 error = got_error_from_errno("waitpid");
2858 if (fetchfd != -1 && close(fetchfd) == -1 && error == NULL)
2859 error = got_error_from_errno("close");
2860 if (repo) {
2861 const struct got_error *close_err = got_repo_close(repo);
2862 if (error == NULL)
2863 error = close_err;
2865 if (worktree)
2866 got_worktree_close(worktree);
2867 if (pack_fds) {
2868 const struct got_error *pack_err =
2869 got_repo_pack_fds_close(pack_fds);
2870 if (error == NULL)
2871 error = pack_err;
2873 got_pathlist_free(&refs, GOT_PATHLIST_FREE_ALL);
2874 got_pathlist_free(&symrefs, GOT_PATHLIST_FREE_ALL);
2875 got_pathlist_free(&wanted_branches, GOT_PATHLIST_FREE_NONE);
2876 got_pathlist_free(&wanted_refs, GOT_PATHLIST_FREE_NONE);
2877 got_ref_list_free(&remote_refs);
2878 got_repo_free_remote_repo_data(remote);
2879 free(remote);
2880 free(head_refname);
2881 free(id_str);
2882 free(cwd);
2883 free(repo_path);
2884 free(pack_hash);
2885 free(proto);
2886 free(host);
2887 free(port);
2888 free(server_path);
2889 free(repo_name);
2890 return error;
2894 __dead static void
2895 usage_checkout(void)
2897 fprintf(stderr, "usage: %s checkout [-Eq] [-b branch] [-c commit] "
2898 "[-p path-prefix] repository-path [work-tree-path]\n",
2899 getprogname());
2900 exit(1);
2903 static void
2904 show_worktree_base_ref_warning(void)
2906 fprintf(stderr, "%s: warning: could not create a reference "
2907 "to the work tree's base commit; the commit could be "
2908 "garbage-collected by Git or 'gotadmin cleanup'; making the "
2909 "repository writable and running 'got update' will prevent this\n",
2910 getprogname());
2913 struct got_checkout_progress_arg {
2914 const char *worktree_path;
2915 int had_base_commit_ref_error;
2916 int verbosity;
2919 static const struct got_error *
2920 checkout_progress(void *arg, unsigned char status, const char *path)
2922 struct got_checkout_progress_arg *a = arg;
2924 /* Base commit bump happens silently. */
2925 if (status == GOT_STATUS_BUMP_BASE)
2926 return NULL;
2928 if (status == GOT_STATUS_BASE_REF_ERR) {
2929 a->had_base_commit_ref_error = 1;
2930 return NULL;
2933 while (path[0] == '/')
2934 path++;
2936 if (a->verbosity >= 0)
2937 printf("%c %s/%s\n", status, a->worktree_path, path);
2939 return NULL;
2942 static const struct got_error *
2943 check_cancelled(void *arg)
2945 if (sigint_received || sigpipe_received)
2946 return got_error(GOT_ERR_CANCELLED);
2947 return NULL;
2950 static const struct got_error *
2951 check_linear_ancestry(struct got_object_id *commit_id,
2952 struct got_object_id *base_commit_id, int allow_forwards_in_time_only,
2953 struct got_repository *repo)
2955 const struct got_error *err = NULL;
2956 struct got_object_id *yca_id;
2958 err = got_commit_graph_find_youngest_common_ancestor(&yca_id,
2959 commit_id, base_commit_id, 1, 0, repo, check_cancelled, NULL);
2960 if (err)
2961 return err;
2963 if (yca_id == NULL)
2964 return got_error(GOT_ERR_ANCESTRY);
2967 * Require a straight line of history between the target commit
2968 * and the work tree's base commit.
2970 * Non-linear situations such as this require a rebase:
2972 * (commit) D F (base_commit)
2973 * \ /
2974 * C E
2975 * \ /
2976 * B (yca)
2977 * |
2978 * A
2980 * 'got update' only handles linear cases:
2981 * Update forwards in time: A (base/yca) - B - C - D (commit)
2982 * Update backwards in time: D (base) - C - B - A (commit/yca)
2984 if (allow_forwards_in_time_only) {
2985 if (got_object_id_cmp(base_commit_id, yca_id) != 0)
2986 return got_error(GOT_ERR_ANCESTRY);
2987 } else if (got_object_id_cmp(commit_id, yca_id) != 0 &&
2988 got_object_id_cmp(base_commit_id, yca_id) != 0)
2989 return got_error(GOT_ERR_ANCESTRY);
2991 free(yca_id);
2992 return NULL;
2995 static const struct got_error *
2996 check_same_branch(struct got_object_id *commit_id,
2997 struct got_reference *head_ref, struct got_repository *repo)
2999 const struct got_error *err = NULL;
3000 struct got_commit_graph *graph = NULL;
3001 struct got_object_id *head_commit_id = NULL;
3003 err = got_ref_resolve(&head_commit_id, repo, head_ref);
3004 if (err)
3005 goto done;
3007 if (got_object_id_cmp(head_commit_id, commit_id) == 0)
3008 goto done;
3010 err = got_commit_graph_open(&graph, "/", 1);
3011 if (err)
3012 goto done;
3014 err = got_commit_graph_bfsort(graph, head_commit_id, repo,
3015 check_cancelled, NULL);
3016 if (err)
3017 goto done;
3019 for (;;) {
3020 struct got_object_id id;
3022 err = got_commit_graph_iter_next(&id, graph, repo,
3023 check_cancelled, NULL);
3024 if (err) {
3025 if (err->code == GOT_ERR_ITER_COMPLETED)
3026 err = got_error(GOT_ERR_ANCESTRY);
3027 break;
3030 if (got_object_id_cmp(&id, commit_id) == 0)
3031 break;
3033 done:
3034 if (graph)
3035 got_commit_graph_close(graph);
3036 free(head_commit_id);
3037 return err;
3040 static const struct got_error *
3041 checkout_ancestry_error(struct got_reference *ref, const char *commit_id_str)
3043 static char msg[512];
3044 const char *branch_name;
3046 if (got_ref_is_symbolic(ref))
3047 branch_name = got_ref_get_symref_target(ref);
3048 else
3049 branch_name = got_ref_get_name(ref);
3051 if (strncmp("refs/heads/", branch_name, 11) == 0)
3052 branch_name += 11;
3054 snprintf(msg, sizeof(msg),
3055 "target commit is not contained in branch '%s'; "
3056 "the branch to use must be specified with -b; "
3057 "if necessary a new branch can be created for "
3058 "this commit with 'got branch -c %s BRANCH_NAME'",
3059 branch_name, commit_id_str);
3061 return got_error_msg(GOT_ERR_ANCESTRY, msg);
3064 static const struct got_error *
3065 cmd_checkout(int argc, char *argv[])
3067 const struct got_error *close_err, *error = NULL;
3068 struct got_repository *repo = NULL;
3069 struct got_reference *head_ref = NULL, *ref = NULL;
3070 struct got_worktree *worktree = NULL;
3071 char *repo_path = NULL;
3072 char *worktree_path = NULL;
3073 const char *path_prefix = "";
3074 const char *branch_name = GOT_REF_HEAD, *refname = NULL;
3075 char *commit_id_str = NULL, *keyword_idstr = NULL;
3076 struct got_object_id *commit_id = NULL;
3077 char *cwd = NULL;
3078 int ch, same_path_prefix, allow_nonempty = 0, verbosity = 0;
3079 struct got_pathlist_head paths;
3080 struct got_checkout_progress_arg cpa;
3081 int *pack_fds = NULL;
3083 TAILQ_INIT(&paths);
3085 #ifndef PROFILE
3086 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
3087 "unveil", NULL) == -1)
3088 err(1, "pledge");
3089 #endif
3091 while ((ch = getopt(argc, argv, "b:c:Ep:q")) != -1) {
3092 switch (ch) {
3093 case 'b':
3094 branch_name = optarg;
3095 break;
3096 case 'c':
3097 commit_id_str = strdup(optarg);
3098 if (commit_id_str == NULL)
3099 return got_error_from_errno("strdup");
3100 break;
3101 case 'E':
3102 allow_nonempty = 1;
3103 break;
3104 case 'p':
3105 path_prefix = optarg;
3106 break;
3107 case 'q':
3108 verbosity = -1;
3109 break;
3110 default:
3111 usage_checkout();
3112 /* NOTREACHED */
3116 argc -= optind;
3117 argv += optind;
3119 if (argc == 1) {
3120 char *base, *dotgit;
3121 const char *path;
3122 repo_path = realpath(argv[0], NULL);
3123 if (repo_path == NULL)
3124 return got_error_from_errno2("realpath", argv[0]);
3125 cwd = getcwd(NULL, 0);
3126 if (cwd == NULL) {
3127 error = got_error_from_errno("getcwd");
3128 goto done;
3130 if (path_prefix[0])
3131 path = path_prefix;
3132 else
3133 path = repo_path;
3134 error = got_path_basename(&base, path);
3135 if (error)
3136 goto done;
3137 dotgit = strstr(base, ".git");
3138 if (dotgit)
3139 *dotgit = '\0';
3140 if (asprintf(&worktree_path, "%s/%s", cwd, base) == -1) {
3141 error = got_error_from_errno("asprintf");
3142 free(base);
3143 goto done;
3145 free(base);
3146 } else if (argc == 2) {
3147 repo_path = realpath(argv[0], NULL);
3148 if (repo_path == NULL) {
3149 error = got_error_from_errno2("realpath", argv[0]);
3150 goto done;
3152 worktree_path = realpath(argv[1], NULL);
3153 if (worktree_path == NULL) {
3154 if (errno != ENOENT) {
3155 error = got_error_from_errno2("realpath",
3156 argv[1]);
3157 goto done;
3159 worktree_path = strdup(argv[1]);
3160 if (worktree_path == NULL) {
3161 error = got_error_from_errno("strdup");
3162 goto done;
3165 } else
3166 usage_checkout();
3168 got_path_strip_trailing_slashes(repo_path);
3169 got_path_strip_trailing_slashes(worktree_path);
3171 if (got_path_is_child(worktree_path, repo_path, strlen(repo_path)) ||
3172 got_path_is_child(repo_path, worktree_path,
3173 strlen(worktree_path))) {
3174 error = got_error_fmt(GOT_ERR_BAD_PATH,
3175 "work tree and repository paths may not overlap: %s",
3176 worktree_path);
3177 goto done;
3180 error = got_repo_pack_fds_open(&pack_fds);
3181 if (error != NULL)
3182 goto done;
3184 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
3185 if (error != NULL)
3186 goto done;
3188 /* Pre-create work tree path for unveil(2) */
3189 error = got_path_mkdir(worktree_path);
3190 if (error) {
3191 if (!(error->code == GOT_ERR_ERRNO && errno == EISDIR) &&
3192 !(error->code == GOT_ERR_ERRNO && errno == EEXIST))
3193 goto done;
3194 if (!allow_nonempty &&
3195 !got_path_dir_is_empty(worktree_path)) {
3196 error = got_error_path(worktree_path,
3197 GOT_ERR_DIR_NOT_EMPTY);
3198 goto done;
3202 error = apply_unveil(got_repo_get_path(repo), 0, worktree_path);
3203 if (error)
3204 goto done;
3206 error = got_ref_open(&head_ref, repo, branch_name, 0);
3207 if (error != NULL)
3208 goto done;
3210 error = got_worktree_init(worktree_path, head_ref, path_prefix,
3211 GOT_WORKTREE_GOT_DIR, repo);
3212 if (error != NULL && !(error->code == GOT_ERR_ERRNO && errno == EEXIST))
3213 goto done;
3215 error = got_worktree_open(&worktree, worktree_path,
3216 GOT_WORKTREE_GOT_DIR);
3217 if (error != NULL)
3218 goto done;
3220 error = got_worktree_match_path_prefix(&same_path_prefix, worktree,
3221 path_prefix);
3222 if (error != NULL)
3223 goto done;
3224 if (!same_path_prefix) {
3225 error = got_error(GOT_ERR_PATH_PREFIX);
3226 goto done;
3229 if (commit_id_str) {
3230 struct got_reflist_head refs;
3231 TAILQ_INIT(&refs);
3232 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
3233 NULL);
3234 if (error)
3235 goto done;
3237 error = got_keyword_to_idstr(&keyword_idstr, commit_id_str,
3238 repo, worktree);
3239 if (error != NULL)
3240 goto done;
3241 if (keyword_idstr != NULL) {
3242 free(commit_id_str);
3243 commit_id_str = keyword_idstr;
3246 error = got_repo_match_object_id(&commit_id, NULL,
3247 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
3248 got_ref_list_free(&refs);
3249 if (error)
3250 goto done;
3251 error = check_linear_ancestry(commit_id,
3252 got_worktree_get_base_commit_id(worktree), 0, repo);
3253 if (error != NULL) {
3254 if (error->code == GOT_ERR_ANCESTRY) {
3255 error = checkout_ancestry_error(
3256 head_ref, commit_id_str);
3258 goto done;
3260 error = check_same_branch(commit_id, head_ref, repo);
3261 if (error) {
3262 if (error->code == GOT_ERR_ANCESTRY) {
3263 error = checkout_ancestry_error(
3264 head_ref, commit_id_str);
3266 goto done;
3268 error = got_worktree_set_base_commit_id(worktree, repo,
3269 commit_id);
3270 if (error)
3271 goto done;
3272 /* Expand potentially abbreviated commit ID string. */
3273 free(commit_id_str);
3274 error = got_object_id_str(&commit_id_str, commit_id);
3275 if (error)
3276 goto done;
3277 } else {
3278 commit_id = got_object_id_dup(
3279 got_worktree_get_base_commit_id(worktree));
3280 if (commit_id == NULL) {
3281 error = got_error_from_errno("got_object_id_dup");
3282 goto done;
3284 error = got_object_id_str(&commit_id_str, commit_id);
3285 if (error)
3286 goto done;
3289 error = got_pathlist_append(&paths, "", NULL);
3290 if (error)
3291 goto done;
3292 cpa.worktree_path = worktree_path;
3293 cpa.had_base_commit_ref_error = 0;
3294 cpa.verbosity = verbosity;
3295 error = got_worktree_checkout_files(worktree, &paths, repo,
3296 checkout_progress, &cpa, check_cancelled, NULL);
3297 if (error != NULL)
3298 goto done;
3300 if (got_ref_is_symbolic(head_ref)) {
3301 error = got_ref_resolve_symbolic(&ref, repo, head_ref);
3302 if (error)
3303 goto done;
3304 refname = got_ref_get_name(ref);
3305 } else
3306 refname = got_ref_get_name(head_ref);
3307 printf("Checked out %s: %s\n", refname, commit_id_str);
3308 printf("Now shut up and hack\n");
3309 if (cpa.had_base_commit_ref_error)
3310 show_worktree_base_ref_warning();
3311 done:
3312 if (pack_fds) {
3313 const struct got_error *pack_err =
3314 got_repo_pack_fds_close(pack_fds);
3315 if (error == NULL)
3316 error = pack_err;
3318 if (head_ref)
3319 got_ref_close(head_ref);
3320 if (ref)
3321 got_ref_close(ref);
3322 if (repo) {
3323 close_err = got_repo_close(repo);
3324 if (error == NULL)
3325 error = close_err;
3327 if (worktree != NULL) {
3328 close_err = got_worktree_close(worktree);
3329 if (error == NULL)
3330 error = close_err;
3332 got_pathlist_free(&paths, GOT_PATHLIST_FREE_NONE);
3333 free(commit_id_str);
3334 free(commit_id);
3335 free(repo_path);
3336 free(worktree_path);
3337 free(cwd);
3338 return error;
3341 struct got_update_progress_arg {
3342 int did_something;
3343 int conflicts;
3344 int obstructed;
3345 int not_updated;
3346 int missing;
3347 int not_deleted;
3348 int unversioned;
3349 int verbosity;
3352 static void
3353 print_update_progress_stats(struct got_update_progress_arg *upa)
3355 if (!upa->did_something)
3356 return;
3358 if (upa->conflicts > 0)
3359 printf("Files with new merge conflicts: %d\n", upa->conflicts);
3360 if (upa->obstructed > 0)
3361 printf("File paths obstructed by a non-regular file: %d\n",
3362 upa->obstructed);
3363 if (upa->not_updated > 0)
3364 printf("Files not updated because of existing merge "
3365 "conflicts: %d\n", upa->not_updated);
3369 * The meaning of some status codes differs between merge-style operations and
3370 * update operations. For example, the ! status code means "file was missing"
3371 * if changes were merged into the work tree, and "missing file was restored"
3372 * if the work tree was updated. This function should be used by any operation
3373 * which merges changes into the work tree without updating the work tree.
3375 static void
3376 print_merge_progress_stats(struct got_update_progress_arg *upa)
3378 if (!upa->did_something)
3379 return;
3381 if (upa->conflicts > 0)
3382 printf("Files with new merge conflicts: %d\n", upa->conflicts);
3383 if (upa->obstructed > 0)
3384 printf("File paths obstructed by a non-regular file: %d\n",
3385 upa->obstructed);
3386 if (upa->missing > 0)
3387 printf("Files which had incoming changes but could not be "
3388 "found in the work tree: %d\n", upa->missing);
3389 if (upa->not_deleted > 0)
3390 printf("Files not deleted due to differences in deleted "
3391 "content: %d\n", upa->not_deleted);
3392 if (upa->unversioned > 0)
3393 printf("Files not merged because an unversioned file was "
3394 "found in the work tree: %d\n", upa->unversioned);
3397 __dead static void
3398 usage_update(void)
3400 fprintf(stderr, "usage: %s update [-q] [-b branch] [-c commit] "
3401 "[path ...]\n", getprogname());
3402 exit(1);
3405 static const struct got_error *
3406 update_progress(void *arg, unsigned char status, const char *path)
3408 struct got_update_progress_arg *upa = arg;
3410 if (status == GOT_STATUS_EXISTS ||
3411 status == GOT_STATUS_BASE_REF_ERR)
3412 return NULL;
3414 upa->did_something = 1;
3416 /* Base commit bump happens silently. */
3417 if (status == GOT_STATUS_BUMP_BASE)
3418 return NULL;
3420 if (status == GOT_STATUS_CONFLICT)
3421 upa->conflicts++;
3422 if (status == GOT_STATUS_OBSTRUCTED)
3423 upa->obstructed++;
3424 if (status == GOT_STATUS_CANNOT_UPDATE)
3425 upa->not_updated++;
3426 if (status == GOT_STATUS_MISSING)
3427 upa->missing++;
3428 if (status == GOT_STATUS_CANNOT_DELETE)
3429 upa->not_deleted++;
3430 if (status == GOT_STATUS_UNVERSIONED)
3431 upa->unversioned++;
3433 while (path[0] == '/')
3434 path++;
3435 if (upa->verbosity >= 0)
3436 printf("%c %s\n", status, path);
3438 return NULL;
3441 static const struct got_error *
3442 switch_head_ref(struct got_reference *head_ref,
3443 struct got_object_id *commit_id, struct got_worktree *worktree,
3444 struct got_repository *repo)
3446 const struct got_error *err = NULL;
3447 char *base_id_str;
3448 int ref_has_moved = 0;
3450 /* Trivial case: switching between two different references. */
3451 if (strcmp(got_ref_get_name(head_ref),
3452 got_worktree_get_head_ref_name(worktree)) != 0) {
3453 printf("Switching work tree from %s to %s\n",
3454 got_worktree_get_head_ref_name(worktree),
3455 got_ref_get_name(head_ref));
3456 return got_worktree_set_head_ref(worktree, head_ref);
3459 err = check_linear_ancestry(commit_id,
3460 got_worktree_get_base_commit_id(worktree), 0, repo);
3461 if (err) {
3462 if (err->code != GOT_ERR_ANCESTRY)
3463 return err;
3464 ref_has_moved = 1;
3466 if (!ref_has_moved)
3467 return NULL;
3469 /* Switching to a rebased branch with the same reference name. */
3470 err = got_object_id_str(&base_id_str,
3471 got_worktree_get_base_commit_id(worktree));
3472 if (err)
3473 return err;
3474 printf("Reference %s now points at a different branch\n",
3475 got_worktree_get_head_ref_name(worktree));
3476 printf("Switching work tree from %s to %s\n", base_id_str,
3477 got_worktree_get_head_ref_name(worktree));
3478 return NULL;
3481 static const struct got_error *
3482 check_rebase_or_histedit_in_progress(struct got_worktree *worktree)
3484 const struct got_error *err;
3485 int in_progress;
3487 err = got_worktree_rebase_in_progress(&in_progress, worktree);
3488 if (err)
3489 return err;
3490 if (in_progress)
3491 return got_error(GOT_ERR_REBASING);
3493 err = got_worktree_histedit_in_progress(&in_progress, worktree);
3494 if (err)
3495 return err;
3496 if (in_progress)
3497 return got_error(GOT_ERR_HISTEDIT_BUSY);
3499 return NULL;
3502 static const struct got_error *
3503 check_merge_in_progress(struct got_worktree *worktree,
3504 struct got_repository *repo)
3506 const struct got_error *err;
3507 int in_progress;
3509 err = got_worktree_merge_in_progress(&in_progress, worktree, repo);
3510 if (err)
3511 return err;
3512 if (in_progress)
3513 return got_error(GOT_ERR_MERGE_BUSY);
3515 return NULL;
3518 static const struct got_error *
3519 get_worktree_paths_from_argv(struct got_pathlist_head *paths, int argc,
3520 char *argv[], struct got_worktree *worktree)
3522 const struct got_error *err = NULL;
3523 char *path;
3524 struct got_pathlist_entry *new;
3525 int i;
3527 if (argc == 0) {
3528 path = strdup("");
3529 if (path == NULL)
3530 return got_error_from_errno("strdup");
3531 return got_pathlist_append(paths, path, NULL);
3534 for (i = 0; i < argc; i++) {
3535 err = got_worktree_resolve_path(&path, worktree, argv[i]);
3536 if (err)
3537 break;
3538 err = got_pathlist_insert(&new, paths, path, NULL);
3539 if (err || new == NULL /* duplicate */) {
3540 free(path);
3541 if (err)
3542 break;
3546 return err;
3549 static const struct got_error *
3550 wrap_not_worktree_error(const struct got_error *orig_err,
3551 const char *cmdname, const char *path)
3553 const struct got_error *err;
3554 struct got_repository *repo;
3555 static char msg[512];
3556 int *pack_fds = NULL;
3558 err = got_repo_pack_fds_open(&pack_fds);
3559 if (err)
3560 return err;
3562 err = got_repo_open(&repo, path, NULL, pack_fds);
3563 if (err)
3564 return orig_err;
3566 snprintf(msg, sizeof(msg),
3567 "'got %s' needs a work tree in addition to a git repository\n"
3568 "Work trees can be checked out from this Git repository with "
3569 "'got checkout'.\n"
3570 "The got(1) manual page contains more information.", cmdname);
3571 err = got_error_msg(GOT_ERR_NOT_WORKTREE, msg);
3572 if (repo) {
3573 const struct got_error *close_err = got_repo_close(repo);
3574 if (err == NULL)
3575 err = close_err;
3577 if (pack_fds) {
3578 const struct got_error *pack_err =
3579 got_repo_pack_fds_close(pack_fds);
3580 if (err == NULL)
3581 err = pack_err;
3583 return err;
3586 static const struct got_error *
3587 cmd_update(int argc, char *argv[])
3589 const struct got_error *close_err, *error = NULL;
3590 struct got_repository *repo = NULL;
3591 struct got_worktree *worktree = NULL;
3592 char *worktree_path = NULL;
3593 struct got_object_id *commit_id = NULL;
3594 char *commit_id_str = NULL;
3595 const char *branch_name = NULL;
3596 struct got_reference *head_ref = NULL;
3597 struct got_pathlist_head paths;
3598 struct got_pathlist_entry *pe;
3599 int ch, verbosity = 0;
3600 struct got_update_progress_arg upa;
3601 int *pack_fds = NULL;
3603 TAILQ_INIT(&paths);
3605 #ifndef PROFILE
3606 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
3607 "unveil", NULL) == -1)
3608 err(1, "pledge");
3609 #endif
3611 while ((ch = getopt(argc, argv, "b:c:q")) != -1) {
3612 switch (ch) {
3613 case 'b':
3614 branch_name = optarg;
3615 break;
3616 case 'c':
3617 commit_id_str = strdup(optarg);
3618 if (commit_id_str == NULL)
3619 return got_error_from_errno("strdup");
3620 break;
3621 case 'q':
3622 verbosity = -1;
3623 break;
3624 default:
3625 usage_update();
3626 /* NOTREACHED */
3630 argc -= optind;
3631 argv += optind;
3633 worktree_path = getcwd(NULL, 0);
3634 if (worktree_path == NULL) {
3635 error = got_error_from_errno("getcwd");
3636 goto done;
3639 error = got_repo_pack_fds_open(&pack_fds);
3640 if (error != NULL)
3641 goto done;
3643 error = got_worktree_open(&worktree, worktree_path,
3644 GOT_WORKTREE_GOT_DIR);
3645 if (error) {
3646 if (error->code == GOT_ERR_NOT_WORKTREE)
3647 error = wrap_not_worktree_error(error, "update",
3648 worktree_path);
3649 goto done;
3652 error = check_rebase_or_histedit_in_progress(worktree);
3653 if (error)
3654 goto done;
3656 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
3657 NULL, pack_fds);
3658 if (error != NULL)
3659 goto done;
3661 error = apply_unveil(got_repo_get_path(repo), 0,
3662 got_worktree_get_root_path(worktree));
3663 if (error)
3664 goto done;
3666 error = check_merge_in_progress(worktree, repo);
3667 if (error)
3668 goto done;
3670 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
3671 if (error)
3672 goto done;
3674 error = got_ref_open(&head_ref, repo, branch_name ? branch_name :
3675 got_worktree_get_head_ref_name(worktree), 0);
3676 if (error != NULL)
3677 goto done;
3678 if (commit_id_str == NULL) {
3679 error = got_ref_resolve(&commit_id, repo, head_ref);
3680 if (error != NULL)
3681 goto done;
3682 error = got_object_id_str(&commit_id_str, commit_id);
3683 if (error != NULL)
3684 goto done;
3685 } else {
3686 struct got_reflist_head refs;
3687 char *keyword_idstr = NULL;
3689 TAILQ_INIT(&refs);
3691 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
3692 NULL);
3693 if (error)
3694 goto done;
3696 error = got_keyword_to_idstr(&keyword_idstr, commit_id_str,
3697 repo, worktree);
3698 if (error != NULL)
3699 goto done;
3700 if (keyword_idstr != NULL) {
3701 free(commit_id_str);
3702 commit_id_str = keyword_idstr;
3705 error = got_repo_match_object_id(&commit_id, NULL,
3706 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
3707 got_ref_list_free(&refs);
3708 free(commit_id_str);
3709 commit_id_str = NULL;
3710 if (error)
3711 goto done;
3712 error = got_object_id_str(&commit_id_str, commit_id);
3713 if (error)
3714 goto done;
3717 if (branch_name) {
3718 struct got_object_id *head_commit_id;
3719 TAILQ_FOREACH(pe, &paths, entry) {
3720 if (pe->path_len == 0)
3721 continue;
3722 error = got_error_msg(GOT_ERR_BAD_PATH,
3723 "switching between branches requires that "
3724 "the entire work tree gets updated");
3725 goto done;
3727 error = got_ref_resolve(&head_commit_id, repo, head_ref);
3728 if (error)
3729 goto done;
3730 error = check_linear_ancestry(commit_id, head_commit_id, 0,
3731 repo);
3732 free(head_commit_id);
3733 if (error != NULL)
3734 goto done;
3735 error = check_same_branch(commit_id, head_ref, repo);
3736 if (error)
3737 goto done;
3738 error = switch_head_ref(head_ref, commit_id, worktree, repo);
3739 if (error)
3740 goto done;
3741 } else {
3742 error = check_linear_ancestry(commit_id,
3743 got_worktree_get_base_commit_id(worktree), 0, repo);
3744 if (error != NULL) {
3745 if (error->code == GOT_ERR_ANCESTRY)
3746 error = got_error(GOT_ERR_BRANCH_MOVED);
3747 goto done;
3749 error = check_same_branch(commit_id, head_ref, repo);
3750 if (error)
3751 goto done;
3754 if (got_object_id_cmp(got_worktree_get_base_commit_id(worktree),
3755 commit_id) != 0) {
3756 error = got_worktree_set_base_commit_id(worktree, repo,
3757 commit_id);
3758 if (error)
3759 goto done;
3762 memset(&upa, 0, sizeof(upa));
3763 upa.verbosity = verbosity;
3764 error = got_worktree_checkout_files(worktree, &paths, repo,
3765 update_progress, &upa, check_cancelled, NULL);
3766 if (error != NULL)
3767 goto done;
3769 if (upa.did_something) {
3770 printf("Updated to %s: %s\n",
3771 got_worktree_get_head_ref_name(worktree), commit_id_str);
3772 } else
3773 printf("Already up-to-date\n");
3775 print_update_progress_stats(&upa);
3776 done:
3777 if (pack_fds) {
3778 const struct got_error *pack_err =
3779 got_repo_pack_fds_close(pack_fds);
3780 if (error == NULL)
3781 error = pack_err;
3783 if (repo) {
3784 close_err = got_repo_close(repo);
3785 if (error == NULL)
3786 error = close_err;
3788 if (worktree != NULL) {
3789 close_err = got_worktree_close(worktree);
3790 if (error == NULL)
3791 error = close_err;
3793 if (head_ref != NULL)
3794 got_ref_close(head_ref);
3795 free(worktree_path);
3796 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
3797 free(commit_id);
3798 free(commit_id_str);
3799 return error;
3802 static const struct got_error *
3803 diff_blobs(struct got_object_id *blob_id1, struct got_object_id *blob_id2,
3804 const char *path, int diff_context, int ignore_whitespace,
3805 int force_text_diff, struct got_diffstat_cb_arg *dsa,
3806 struct got_repository *repo, FILE *outfile)
3808 const struct got_error *err = NULL;
3809 struct got_blob_object *blob1 = NULL, *blob2 = NULL;
3810 FILE *f1 = NULL, *f2 = NULL;
3811 int fd1 = -1, fd2 = -1;
3813 fd1 = got_opentempfd();
3814 if (fd1 == -1)
3815 return got_error_from_errno("got_opentempfd");
3816 fd2 = got_opentempfd();
3817 if (fd2 == -1) {
3818 err = got_error_from_errno("got_opentempfd");
3819 goto done;
3822 if (blob_id1) {
3823 err = got_object_open_as_blob(&blob1, repo, blob_id1, 8192,
3824 fd1);
3825 if (err)
3826 goto done;
3829 err = got_object_open_as_blob(&blob2, repo, blob_id2, 8192, fd2);
3830 if (err)
3831 goto done;
3833 f1 = got_opentemp();
3834 if (f1 == NULL) {
3835 err = got_error_from_errno("got_opentemp");
3836 goto done;
3838 f2 = got_opentemp();
3839 if (f2 == NULL) {
3840 err = got_error_from_errno("got_opentemp");
3841 goto done;
3844 while (path[0] == '/')
3845 path++;
3846 err = got_diff_blob(NULL, NULL, blob1, blob2, f1, f2, path, path,
3847 GOT_DIFF_ALGORITHM_PATIENCE, diff_context, ignore_whitespace,
3848 force_text_diff, dsa, outfile);
3849 done:
3850 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
3851 err = got_error_from_errno("close");
3852 if (blob1)
3853 got_object_blob_close(blob1);
3854 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
3855 err = got_error_from_errno("close");
3856 if (blob2)
3857 got_object_blob_close(blob2);
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 return err;
3865 static const struct got_error *
3866 diff_trees(struct got_object_id *tree_id1, struct got_object_id *tree_id2,
3867 const char *path, int diff_context, int ignore_whitespace,
3868 int force_text_diff, struct got_diffstat_cb_arg *dsa,
3869 struct got_repository *repo, FILE *outfile)
3871 const struct got_error *err = NULL;
3872 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
3873 struct got_diff_blob_output_unidiff_arg arg;
3874 FILE *f1 = NULL, *f2 = NULL;
3875 int fd1 = -1, fd2 = -1;
3877 if (tree_id1) {
3878 err = got_object_open_as_tree(&tree1, repo, tree_id1);
3879 if (err)
3880 goto done;
3881 fd1 = got_opentempfd();
3882 if (fd1 == -1) {
3883 err = got_error_from_errno("got_opentempfd");
3884 goto done;
3888 err = got_object_open_as_tree(&tree2, repo, tree_id2);
3889 if (err)
3890 goto done;
3892 f1 = got_opentemp();
3893 if (f1 == NULL) {
3894 err = got_error_from_errno("got_opentemp");
3895 goto done;
3898 f2 = got_opentemp();
3899 if (f2 == NULL) {
3900 err = got_error_from_errno("got_opentemp");
3901 goto done;
3903 fd2 = got_opentempfd();
3904 if (fd2 == -1) {
3905 err = got_error_from_errno("got_opentempfd");
3906 goto done;
3908 arg.diff_context = diff_context;
3909 arg.ignore_whitespace = ignore_whitespace;
3910 arg.force_text_diff = force_text_diff;
3911 arg.diffstat = dsa;
3912 arg.diff_algo = GOT_DIFF_ALGORITHM_PATIENCE;
3913 arg.outfile = outfile;
3914 arg.lines = NULL;
3915 arg.nlines = 0;
3916 while (path[0] == '/')
3917 path++;
3918 err = got_diff_tree(tree1, tree2, f1, f2, fd1, fd2, path, path, repo,
3919 got_diff_blob_output_unidiff, &arg, 1);
3920 done:
3921 if (tree1)
3922 got_object_tree_close(tree1);
3923 if (tree2)
3924 got_object_tree_close(tree2);
3925 if (f1 && fclose(f1) == EOF && err == NULL)
3926 err = got_error_from_errno("fclose");
3927 if (f2 && fclose(f2) == EOF && err == NULL)
3928 err = got_error_from_errno("fclose");
3929 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
3930 err = got_error_from_errno("close");
3931 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
3932 err = got_error_from_errno("close");
3933 return err;
3936 static const struct got_error *
3937 get_changed_paths(struct got_pathlist_head *paths,
3938 struct got_commit_object *commit, struct got_repository *repo,
3939 struct got_diffstat_cb_arg *dsa)
3941 const struct got_error *err = NULL;
3942 struct got_object_id *tree_id1 = NULL, *tree_id2 = NULL;
3943 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
3944 struct got_object_qid *qid;
3945 got_diff_blob_cb cb = got_diff_tree_collect_changed_paths;
3946 FILE *f1 = NULL, *f2 = NULL;
3947 int fd1 = -1, fd2 = -1;
3949 if (dsa) {
3950 cb = got_diff_tree_compute_diffstat;
3952 f1 = got_opentemp();
3953 if (f1 == NULL) {
3954 err = got_error_from_errno("got_opentemp");
3955 goto done;
3957 f2 = got_opentemp();
3958 if (f2 == NULL) {
3959 err = got_error_from_errno("got_opentemp");
3960 goto done;
3962 fd1 = got_opentempfd();
3963 if (fd1 == -1) {
3964 err = got_error_from_errno("got_opentempfd");
3965 goto done;
3967 fd2 = got_opentempfd();
3968 if (fd2 == -1) {
3969 err = got_error_from_errno("got_opentempfd");
3970 goto done;
3974 qid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
3975 if (qid != NULL) {
3976 struct got_commit_object *pcommit;
3977 err = got_object_open_as_commit(&pcommit, repo,
3978 &qid->id);
3979 if (err)
3980 return err;
3982 tree_id1 = got_object_id_dup(
3983 got_object_commit_get_tree_id(pcommit));
3984 if (tree_id1 == NULL) {
3985 got_object_commit_close(pcommit);
3986 return got_error_from_errno("got_object_id_dup");
3988 got_object_commit_close(pcommit);
3992 if (tree_id1) {
3993 err = got_object_open_as_tree(&tree1, repo, tree_id1);
3994 if (err)
3995 goto done;
3998 tree_id2 = got_object_commit_get_tree_id(commit);
3999 err = got_object_open_as_tree(&tree2, repo, tree_id2);
4000 if (err)
4001 goto done;
4003 err = got_diff_tree(tree1, tree2, f1, f2, fd1, fd2, "", "", repo,
4004 cb, dsa ? (void *)dsa : paths, dsa ? 1 : 0);
4005 done:
4006 if (tree1)
4007 got_object_tree_close(tree1);
4008 if (tree2)
4009 got_object_tree_close(tree2);
4010 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
4011 err = got_error_from_errno("close");
4012 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
4013 err = got_error_from_errno("close");
4014 if (f1 && fclose(f1) == EOF && err == NULL)
4015 err = got_error_from_errno("fclose");
4016 if (f2 && fclose(f2) == EOF && err == NULL)
4017 err = got_error_from_errno("fclose");
4018 free(tree_id1);
4019 return err;
4022 static const struct got_error *
4023 print_patch(struct got_commit_object *commit, struct got_object_id *id,
4024 const char *path, int diff_context, struct got_diffstat_cb_arg *dsa,
4025 struct got_repository *repo, FILE *outfile)
4027 const struct got_error *err = NULL;
4028 struct got_commit_object *pcommit = NULL;
4029 char *id_str1 = NULL, *id_str2 = NULL;
4030 struct got_object_id *obj_id1 = NULL, *obj_id2 = NULL;
4031 struct got_object_qid *qid;
4033 qid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
4034 if (qid != NULL) {
4035 err = got_object_open_as_commit(&pcommit, repo,
4036 &qid->id);
4037 if (err)
4038 return err;
4039 err = got_object_id_str(&id_str1, &qid->id);
4040 if (err)
4041 goto done;
4044 err = got_object_id_str(&id_str2, id);
4045 if (err)
4046 goto done;
4048 if (path && path[0] != '\0') {
4049 int obj_type;
4050 err = got_object_id_by_path(&obj_id2, repo, commit, path);
4051 if (err)
4052 goto done;
4053 if (pcommit) {
4054 err = got_object_id_by_path(&obj_id1, repo,
4055 pcommit, path);
4056 if (err) {
4057 if (err->code != GOT_ERR_NO_TREE_ENTRY) {
4058 free(obj_id2);
4059 goto done;
4063 err = got_object_get_type(&obj_type, repo, obj_id2);
4064 if (err) {
4065 free(obj_id2);
4066 goto done;
4068 fprintf(outfile,
4069 "diff %s %s\n", id_str1 ? id_str1 : "/dev/null", id_str2);
4070 fprintf(outfile, "commit - %s\n",
4071 id_str1 ? id_str1 : "/dev/null");
4072 fprintf(outfile, "commit + %s\n", id_str2);
4073 switch (obj_type) {
4074 case GOT_OBJ_TYPE_BLOB:
4075 err = diff_blobs(obj_id1, obj_id2, path, diff_context,
4076 0, 0, dsa, repo, outfile);
4077 break;
4078 case GOT_OBJ_TYPE_TREE:
4079 err = diff_trees(obj_id1, obj_id2, path, diff_context,
4080 0, 0, dsa, repo, outfile);
4081 break;
4082 default:
4083 err = got_error(GOT_ERR_OBJ_TYPE);
4084 break;
4086 free(obj_id1);
4087 free(obj_id2);
4088 } else {
4089 obj_id2 = got_object_commit_get_tree_id(commit);
4090 if (pcommit)
4091 obj_id1 = got_object_commit_get_tree_id(pcommit);
4092 fprintf(outfile,
4093 "diff %s %s\n", id_str1 ? id_str1 : "/dev/null", id_str2);
4094 fprintf(outfile, "commit - %s\n",
4095 id_str1 ? id_str1 : "/dev/null");
4096 fprintf(outfile, "commit + %s\n", id_str2);
4097 err = diff_trees(obj_id1, obj_id2, "", diff_context, 0, 0,
4098 dsa, repo, outfile);
4100 done:
4101 free(id_str1);
4102 free(id_str2);
4103 if (pcommit)
4104 got_object_commit_close(pcommit);
4105 return err;
4108 static char *
4109 get_datestr(time_t *time, char *datebuf)
4111 struct tm mytm, *tm;
4112 char *p, *s;
4114 tm = gmtime_r(time, &mytm);
4115 if (tm == NULL)
4116 return NULL;
4117 s = asctime_r(tm, datebuf);
4118 if (s == NULL)
4119 return NULL;
4120 p = strchr(s, '\n');
4121 if (p)
4122 *p = '\0';
4123 return s;
4126 static const struct got_error *
4127 match_commit(int *have_match, struct got_object_id *id,
4128 struct got_commit_object *commit, regex_t *regex)
4130 const struct got_error *err = NULL;
4131 regmatch_t regmatch;
4132 char *id_str = NULL, *logmsg = NULL;
4134 *have_match = 0;
4136 err = got_object_id_str(&id_str, id);
4137 if (err)
4138 return err;
4140 err = got_object_commit_get_logmsg(&logmsg, commit);
4141 if (err)
4142 goto done;
4144 if (regexec(regex, got_object_commit_get_author(commit), 1,
4145 &regmatch, 0) == 0 ||
4146 regexec(regex, got_object_commit_get_committer(commit), 1,
4147 &regmatch, 0) == 0 ||
4148 regexec(regex, id_str, 1, &regmatch, 0) == 0 ||
4149 regexec(regex, logmsg, 1, &regmatch, 0) == 0)
4150 *have_match = 1;
4151 done:
4152 free(id_str);
4153 free(logmsg);
4154 return err;
4157 static void
4158 match_changed_paths(int *have_match, struct got_pathlist_head *changed_paths,
4159 regex_t *regex)
4161 regmatch_t regmatch;
4162 struct got_pathlist_entry *pe;
4164 *have_match = 0;
4166 TAILQ_FOREACH(pe, changed_paths, entry) {
4167 if (regexec(regex, pe->path, 1, &regmatch, 0) == 0) {
4168 *have_match = 1;
4169 break;
4174 static const struct got_error *
4175 match_patch(int *have_match, struct got_commit_object *commit,
4176 struct got_object_id *id, const char *path, int diff_context,
4177 struct got_repository *repo, regex_t *regex, FILE *f)
4179 const struct got_error *err = NULL;
4180 char *line = NULL;
4181 size_t linesize = 0;
4182 regmatch_t regmatch;
4184 *have_match = 0;
4186 err = got_opentemp_truncate(f);
4187 if (err)
4188 return err;
4190 err = print_patch(commit, id, path, diff_context, NULL, repo, f);
4191 if (err)
4192 goto done;
4194 if (fseeko(f, 0L, SEEK_SET) == -1) {
4195 err = got_error_from_errno("fseeko");
4196 goto done;
4199 while (getline(&line, &linesize, f) != -1) {
4200 if (regexec(regex, line, 1, &regmatch, 0) == 0) {
4201 *have_match = 1;
4202 break;
4205 done:
4206 free(line);
4207 return err;
4210 #define GOT_COMMIT_SEP_STR "-----------------------------------------------\n"
4212 static const struct got_error*
4213 build_refs_str(char **refs_str, struct got_reflist_head *refs,
4214 struct got_object_id *id, struct got_repository *repo,
4215 int local_only)
4217 static const struct got_error *err = NULL;
4218 struct got_reflist_entry *re;
4219 char *s;
4220 const char *name;
4222 *refs_str = NULL;
4224 TAILQ_FOREACH(re, refs, entry) {
4225 struct got_tag_object *tag = NULL;
4226 struct got_object_id *ref_id;
4227 int cmp;
4229 name = got_ref_get_name(re->ref);
4230 if (strcmp(name, GOT_REF_HEAD) == 0)
4231 continue;
4232 if (strncmp(name, "refs/", 5) == 0)
4233 name += 5;
4234 if (strncmp(name, "got/", 4) == 0)
4235 continue;
4236 if (strncmp(name, "heads/", 6) == 0)
4237 name += 6;
4238 if (strncmp(name, "remotes/", 8) == 0) {
4239 if (local_only)
4240 continue;
4241 name += 8;
4242 s = strstr(name, "/" GOT_REF_HEAD);
4243 if (s != NULL && strcmp(s, "/" GOT_REF_HEAD) == 0)
4244 continue;
4246 err = got_ref_resolve(&ref_id, repo, re->ref);
4247 if (err)
4248 break;
4249 if (strncmp(name, "tags/", 5) == 0) {
4250 err = got_object_open_as_tag(&tag, repo, ref_id);
4251 if (err) {
4252 if (err->code != GOT_ERR_OBJ_TYPE) {
4253 free(ref_id);
4254 break;
4256 /* Ref points at something other than a tag. */
4257 err = NULL;
4258 tag = NULL;
4261 cmp = got_object_id_cmp(tag ?
4262 got_object_tag_get_object_id(tag) : ref_id, id);
4263 free(ref_id);
4264 if (tag)
4265 got_object_tag_close(tag);
4266 if (cmp != 0)
4267 continue;
4268 s = *refs_str;
4269 if (asprintf(refs_str, "%s%s%s", s ? s : "",
4270 s ? ", " : "", name) == -1) {
4271 err = got_error_from_errno("asprintf");
4272 free(s);
4273 *refs_str = NULL;
4274 break;
4276 free(s);
4279 return err;
4282 static const struct got_error *
4283 print_commit_oneline(struct got_commit_object *commit, struct got_object_id *id,
4284 struct got_repository *repo, struct got_reflist_object_id_map *refs_idmap)
4286 const struct got_error *err = NULL;
4287 char *ref_str = NULL, *id_str = NULL, *logmsg0 = NULL;
4288 char *comma, *s, *nl;
4289 struct got_reflist_head *refs;
4290 char datebuf[12]; /* YYYY-MM-DD + SPACE + NUL */
4291 struct tm tm;
4292 time_t committer_time;
4294 refs = got_reflist_object_id_map_lookup(refs_idmap, id);
4295 if (refs) {
4296 err = build_refs_str(&ref_str, refs, id, repo, 1);
4297 if (err)
4298 return err;
4300 /* Display the first matching ref only. */
4301 if (ref_str && (comma = strchr(ref_str, ',')) != NULL)
4302 *comma = '\0';
4305 if (ref_str == NULL) {
4306 err = got_object_id_str(&id_str, id);
4307 if (err)
4308 return err;
4311 committer_time = got_object_commit_get_committer_time(commit);
4312 if (gmtime_r(&committer_time, &tm) == NULL) {
4313 err = got_error_from_errno("gmtime_r");
4314 goto done;
4316 if (strftime(datebuf, sizeof(datebuf), "%F ", &tm) == 0) {
4317 err = got_error(GOT_ERR_NO_SPACE);
4318 goto done;
4321 err = got_object_commit_get_logmsg(&logmsg0, commit);
4322 if (err)
4323 goto done;
4325 s = logmsg0;
4326 while (isspace((unsigned char)s[0]))
4327 s++;
4329 nl = strchr(s, '\n');
4330 if (nl) {
4331 *nl = '\0';
4334 if (ref_str)
4335 printf("%s%-7s %s\n", datebuf, ref_str, s);
4336 else
4337 printf("%s%.7s %s\n", datebuf, id_str, s);
4339 if (fflush(stdout) != 0 && err == NULL)
4340 err = got_error_from_errno("fflush");
4341 done:
4342 free(id_str);
4343 free(ref_str);
4344 free(logmsg0);
4345 return err;
4348 static const struct got_error *
4349 print_diffstat(struct got_diffstat_cb_arg *dsa, const char *header)
4351 struct got_pathlist_entry *pe;
4353 if (header != NULL)
4354 printf("%s\n", header);
4356 TAILQ_FOREACH(pe, dsa->paths, entry) {
4357 struct got_diff_changed_path *cp = pe->data;
4358 int pad = dsa->max_path_len - pe->path_len + 1;
4360 printf(" %c %s%*c | %*d+ %*d-\n", cp->status, pe->path, pad,
4361 ' ', dsa->add_cols + 1, cp->add, dsa->rm_cols + 1, cp->rm);
4363 printf("\n%d file%s changed, %d insertion%s(+), %d deletion%s(-)\n\n",
4364 dsa->nfiles, dsa->nfiles > 1 ? "s" : "", dsa->ins,
4365 dsa->ins != 1 ? "s" : "", dsa->del, dsa->del != 1 ? "s" : "");
4367 if (fflush(stdout) != 0)
4368 return got_error_from_errno("fflush");
4370 return NULL;
4373 static const struct got_error *
4374 printfile(FILE *f)
4376 char buf[8192];
4377 size_t r;
4379 if (fseeko(f, 0L, SEEK_SET) == -1)
4380 return got_error_from_errno("fseek");
4382 for (;;) {
4383 r = fread(buf, 1, sizeof(buf), f);
4384 if (r == 0) {
4385 if (ferror(f))
4386 return got_error_from_errno("fread");
4387 if (feof(f))
4388 break;
4390 if (fwrite(buf, 1, r, stdout) != r)
4391 return got_ferror(stdout, GOT_ERR_IO);
4394 return NULL;
4397 static const struct got_error *
4398 print_commit(struct got_commit_object *commit, struct got_object_id *id,
4399 struct got_repository *repo, const char *path,
4400 struct got_pathlist_head *changed_paths,
4401 struct got_diffstat_cb_arg *diffstat, int show_patch, int diff_context,
4402 struct got_reflist_object_id_map *refs_idmap, const char *custom_refs_str,
4403 const char *prefix)
4405 const struct got_error *err = NULL;
4406 FILE *f = NULL;
4407 char *id_str, *datestr, *logmsg0, *logmsg, *line;
4408 char datebuf[26];
4409 time_t committer_time;
4410 const char *author, *committer;
4411 char *refs_str = NULL;
4413 err = got_object_id_str(&id_str, id);
4414 if (err)
4415 return err;
4417 if (custom_refs_str == NULL) {
4418 struct got_reflist_head *refs;
4419 refs = got_reflist_object_id_map_lookup(refs_idmap, id);
4420 if (refs) {
4421 err = build_refs_str(&refs_str, refs, id, repo, 0);
4422 if (err)
4423 goto done;
4427 printf(GOT_COMMIT_SEP_STR);
4428 if (custom_refs_str)
4429 printf("%s %s (%s)\n", prefix ? prefix : "commit", id_str,
4430 custom_refs_str);
4431 else
4432 printf("%s %s%s%s%s\n", prefix ? prefix : "commit", id_str,
4433 refs_str ? " (" : "", refs_str ? refs_str : "",
4434 refs_str ? ")" : "");
4435 free(id_str);
4436 id_str = NULL;
4437 free(refs_str);
4438 refs_str = NULL;
4439 printf("from: %s\n", got_object_commit_get_author(commit));
4440 author = got_object_commit_get_author(commit);
4441 committer = got_object_commit_get_committer(commit);
4442 if (strcmp(author, committer) != 0)
4443 printf("via: %s\n", committer);
4444 committer_time = got_object_commit_get_committer_time(commit);
4445 datestr = get_datestr(&committer_time, datebuf);
4446 if (datestr)
4447 printf("date: %s UTC\n", datestr);
4448 if (got_object_commit_get_nparents(commit) > 1) {
4449 const struct got_object_id_queue *parent_ids;
4450 struct got_object_qid *qid;
4451 int n = 1;
4452 parent_ids = got_object_commit_get_parent_ids(commit);
4453 STAILQ_FOREACH(qid, parent_ids, entry) {
4454 err = got_object_id_str(&id_str, &qid->id);
4455 if (err)
4456 goto done;
4457 printf("parent %d: %s\n", n++, id_str);
4458 free(id_str);
4459 id_str = NULL;
4463 err = got_object_commit_get_logmsg(&logmsg0, commit);
4464 if (err)
4465 goto done;
4467 logmsg = logmsg0;
4468 do {
4469 line = strsep(&logmsg, "\n");
4470 if (line)
4471 printf(" %s\n", line);
4472 } while (line);
4473 free(logmsg0);
4475 if (changed_paths && diffstat == NULL) {
4476 struct got_pathlist_entry *pe;
4478 TAILQ_FOREACH(pe, changed_paths, entry) {
4479 struct got_diff_changed_path *cp = pe->data;
4481 printf(" %c %s\n", cp->status, pe->path);
4483 printf("\n");
4485 if (show_patch) {
4486 if (diffstat) {
4487 f = got_opentemp();
4488 if (f == NULL) {
4489 err = got_error_from_errno("got_opentemp");
4490 goto done;
4494 err = print_patch(commit, id, path, diff_context, diffstat,
4495 repo, diffstat == NULL ? stdout : f);
4496 if (err)
4497 goto done;
4499 if (diffstat) {
4500 err = print_diffstat(diffstat, NULL);
4501 if (err)
4502 goto done;
4503 if (show_patch) {
4504 err = printfile(f);
4505 if (err)
4506 goto done;
4509 if (show_patch)
4510 printf("\n");
4512 if (fflush(stdout) != 0 && err == NULL)
4513 err = got_error_from_errno("fflush");
4514 done:
4515 if (f && fclose(f) == EOF && err == NULL)
4516 err = got_error_from_errno("fclose");
4517 free(id_str);
4518 free(refs_str);
4519 return err;
4522 static const struct got_error *
4523 print_commits(struct got_object_id *root_id, struct got_object_id *end_id,
4524 struct got_repository *repo, const char *path, int show_changed_paths,
4525 int show_diffstat, int show_patch, const char *search_pattern,
4526 int diff_context, int limit, int log_branches, int reverse_display_order,
4527 struct got_reflist_object_id_map *refs_idmap, int one_line, int toposort,
4528 FILE *tmpfile)
4530 const struct got_error *err;
4531 struct got_commit_graph *graph;
4532 regex_t regex;
4533 int have_match;
4534 struct got_object_id_queue reversed_commits;
4535 struct got_object_qid *qid;
4536 struct got_commit_object *commit;
4537 struct got_pathlist_head changed_paths;
4539 STAILQ_INIT(&reversed_commits);
4540 TAILQ_INIT(&changed_paths);
4542 if (search_pattern && regcomp(&regex, search_pattern,
4543 REG_EXTENDED | REG_NOSUB | REG_NEWLINE))
4544 return got_error_msg(GOT_ERR_REGEX, search_pattern);
4546 err = got_commit_graph_open(&graph, path, !log_branches);
4547 if (err)
4548 return err;
4549 if (log_branches && toposort) {
4550 err = got_commit_graph_toposort(graph, root_id, repo,
4551 check_cancelled, NULL);
4552 } else {
4553 err = got_commit_graph_bfsort(graph, root_id, repo,
4554 check_cancelled, NULL);
4556 if (err)
4557 goto done;
4558 for (;;) {
4559 struct got_object_id id;
4560 struct got_diffstat_cb_arg dsa = { 0, 0, 0, 0, 0, 0,
4561 &changed_paths, 0, 0, GOT_DIFF_ALGORITHM_PATIENCE };
4563 if (sigint_received || sigpipe_received)
4564 break;
4566 err = got_commit_graph_iter_next(&id, graph, repo,
4567 check_cancelled, NULL);
4568 if (err) {
4569 if (err->code == GOT_ERR_ITER_COMPLETED)
4570 err = NULL;
4571 break;
4574 err = got_object_open_as_commit(&commit, repo, &id);
4575 if (err)
4576 break;
4578 if (((show_changed_paths && !show_diffstat) ||
4579 (show_diffstat && !show_patch))
4580 && !reverse_display_order) {
4581 err = get_changed_paths(&changed_paths, commit, repo,
4582 show_diffstat ? &dsa : NULL);
4583 if (err)
4584 break;
4587 if (search_pattern) {
4588 err = match_commit(&have_match, &id, commit, &regex);
4589 if (err) {
4590 got_object_commit_close(commit);
4591 break;
4593 if (have_match == 0 && show_changed_paths)
4594 match_changed_paths(&have_match,
4595 &changed_paths, &regex);
4596 if (have_match == 0 && show_patch) {
4597 err = match_patch(&have_match, commit, &id,
4598 path, diff_context, repo, &regex, tmpfile);
4599 if (err)
4600 break;
4602 if (have_match == 0) {
4603 got_object_commit_close(commit);
4604 got_pathlist_free(&changed_paths,
4605 GOT_PATHLIST_FREE_ALL);
4606 continue;
4610 if (reverse_display_order) {
4611 err = got_object_qid_alloc(&qid, &id);
4612 if (err)
4613 break;
4614 STAILQ_INSERT_HEAD(&reversed_commits, qid, entry);
4615 got_object_commit_close(commit);
4616 } else {
4617 if (one_line)
4618 err = print_commit_oneline(commit, &id,
4619 repo, refs_idmap);
4620 else
4621 err = print_commit(commit, &id, repo, path,
4622 (show_changed_paths || show_diffstat) ?
4623 &changed_paths : NULL,
4624 show_diffstat ? &dsa : NULL, show_patch,
4625 diff_context, refs_idmap, NULL, NULL);
4626 got_object_commit_close(commit);
4627 if (err)
4628 break;
4630 if ((limit && --limit == 0) ||
4631 (end_id && got_object_id_cmp(&id, end_id) == 0))
4632 break;
4634 got_pathlist_free(&changed_paths, GOT_PATHLIST_FREE_ALL);
4636 if (reverse_display_order) {
4637 STAILQ_FOREACH(qid, &reversed_commits, entry) {
4638 struct got_diffstat_cb_arg dsa = { 0, 0, 0, 0, 0, 0,
4639 &changed_paths, 0, 0, GOT_DIFF_ALGORITHM_PATIENCE };
4641 err = got_object_open_as_commit(&commit, repo,
4642 &qid->id);
4643 if (err)
4644 break;
4645 if ((show_changed_paths && !show_diffstat) ||
4646 (show_diffstat && !show_patch)) {
4647 err = get_changed_paths(&changed_paths, commit,
4648 repo, show_diffstat ? &dsa : NULL);
4649 if (err)
4650 break;
4652 if (one_line)
4653 err = print_commit_oneline(commit, &qid->id,
4654 repo, refs_idmap);
4655 else
4656 err = print_commit(commit, &qid->id, repo, path,
4657 (show_changed_paths || show_diffstat) ?
4658 &changed_paths : NULL,
4659 show_diffstat ? &dsa : NULL, show_patch,
4660 diff_context, refs_idmap, NULL, NULL);
4661 got_object_commit_close(commit);
4662 if (err)
4663 break;
4664 got_pathlist_free(&changed_paths, GOT_PATHLIST_FREE_ALL);
4667 done:
4668 while (!STAILQ_EMPTY(&reversed_commits)) {
4669 qid = STAILQ_FIRST(&reversed_commits);
4670 STAILQ_REMOVE_HEAD(&reversed_commits, entry);
4671 got_object_qid_free(qid);
4673 got_pathlist_free(&changed_paths, GOT_PATHLIST_FREE_ALL);
4674 if (search_pattern)
4675 regfree(&regex);
4676 got_commit_graph_close(graph);
4677 return err;
4680 __dead static void
4681 usage_log(void)
4683 fprintf(stderr, "usage: %s log [-bdPpRst] [-C number] [-c commit] "
4684 "[-l N] [-r repository-path] [-S search-pattern] [-x commit] "
4685 "[path]\n", getprogname());
4686 exit(1);
4689 static int
4690 get_default_log_limit(void)
4692 const char *got_default_log_limit;
4693 long long n;
4694 const char *errstr;
4696 got_default_log_limit = getenv("GOT_LOG_DEFAULT_LIMIT");
4697 if (got_default_log_limit == NULL)
4698 return 0;
4699 n = strtonum(got_default_log_limit, 0, INT_MAX, &errstr);
4700 if (errstr != NULL)
4701 return 0;
4702 return n;
4705 static const struct got_error *
4706 cmd_log(int argc, char *argv[])
4708 const struct got_error *error;
4709 struct got_repository *repo = NULL;
4710 struct got_worktree *worktree = NULL;
4711 struct got_object_id *start_id = NULL, *end_id = NULL;
4712 char *repo_path = NULL, *path = NULL, *cwd = NULL, *in_repo_path = NULL;
4713 char *keyword_idstr = NULL;
4714 const char *start_commit = NULL, *end_commit = NULL;
4715 const char *search_pattern = NULL;
4716 int diff_context = -1, ch;
4717 int show_changed_paths = 0, show_patch = 0, limit = 0, log_branches = 0;
4718 int show_diffstat = 0, reverse_display_order = 0, one_line = 0;
4719 int toposort = 0;
4720 const char *errstr;
4721 struct got_reflist_head refs;
4722 struct got_reflist_object_id_map *refs_idmap = NULL;
4723 FILE *tmpfile = NULL;
4724 int *pack_fds = NULL;
4726 TAILQ_INIT(&refs);
4728 #ifndef PROFILE
4729 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
4730 NULL)
4731 == -1)
4732 err(1, "pledge");
4733 #endif
4735 limit = get_default_log_limit();
4737 while ((ch = getopt(argc, argv, "bC:c:dl:PpRr:S:stx:")) != -1) {
4738 switch (ch) {
4739 case 'b':
4740 log_branches = 1;
4741 break;
4742 case 'C':
4743 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
4744 &errstr);
4745 if (errstr != NULL)
4746 errx(1, "number of context lines is %s: %s",
4747 errstr, optarg);
4748 break;
4749 case 'c':
4750 start_commit = optarg;
4751 break;
4752 case 'd':
4753 show_diffstat = 1;
4754 break;
4755 case 'l':
4756 limit = strtonum(optarg, 0, INT_MAX, &errstr);
4757 if (errstr != NULL)
4758 errx(1, "number of commits is %s: %s",
4759 errstr, optarg);
4760 break;
4761 case 'P':
4762 show_changed_paths = 1;
4763 break;
4764 case 'p':
4765 show_patch = 1;
4766 break;
4767 case 'R':
4768 reverse_display_order = 1;
4769 break;
4770 case 'r':
4771 repo_path = realpath(optarg, NULL);
4772 if (repo_path == NULL)
4773 return got_error_from_errno2("realpath",
4774 optarg);
4775 got_path_strip_trailing_slashes(repo_path);
4776 break;
4777 case 'S':
4778 search_pattern = optarg;
4779 break;
4780 case 's':
4781 one_line = 1;
4782 break;
4783 case 't':
4784 toposort = 1;
4785 break;
4786 case 'x':
4787 end_commit = optarg;
4788 break;
4789 default:
4790 usage_log();
4791 /* NOTREACHED */
4795 argc -= optind;
4796 argv += optind;
4798 if (diff_context == -1)
4799 diff_context = 3;
4800 else if (!show_patch)
4801 errx(1, "-C requires -p");
4803 if (one_line && (show_patch || show_changed_paths || show_diffstat))
4804 errx(1, "cannot use -s with -d, -p or -P");
4806 cwd = getcwd(NULL, 0);
4807 if (cwd == NULL) {
4808 error = got_error_from_errno("getcwd");
4809 goto done;
4812 error = got_repo_pack_fds_open(&pack_fds);
4813 if (error != NULL)
4814 goto done;
4816 if (repo_path == NULL) {
4817 error = got_worktree_open(&worktree, cwd,
4818 GOT_WORKTREE_GOT_DIR);
4819 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4820 goto done;
4821 error = NULL;
4824 if (argc == 1) {
4825 if (worktree) {
4826 error = got_worktree_resolve_path(&path, worktree,
4827 argv[0]);
4828 if (error)
4829 goto done;
4830 } else {
4831 path = strdup(argv[0]);
4832 if (path == NULL) {
4833 error = got_error_from_errno("strdup");
4834 goto done;
4837 } else if (argc != 0)
4838 usage_log();
4840 if (repo_path == NULL) {
4841 repo_path = worktree ?
4842 strdup(got_worktree_get_repo_path(worktree)) : strdup(cwd);
4844 if (repo_path == NULL) {
4845 error = got_error_from_errno("strdup");
4846 goto done;
4849 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
4850 if (error != NULL)
4851 goto done;
4853 error = apply_unveil(got_repo_get_path(repo), 1,
4854 worktree ? got_worktree_get_root_path(worktree) : NULL);
4855 if (error)
4856 goto done;
4858 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
4859 if (error)
4860 goto done;
4862 error = got_reflist_object_id_map_create(&refs_idmap, &refs, repo);
4863 if (error)
4864 goto done;
4866 if (start_commit == NULL) {
4867 struct got_reference *head_ref;
4868 struct got_commit_object *commit = NULL;
4869 error = got_ref_open(&head_ref, repo,
4870 worktree ? got_worktree_get_head_ref_name(worktree)
4871 : GOT_REF_HEAD, 0);
4872 if (error != NULL)
4873 goto done;
4874 error = got_ref_resolve(&start_id, repo, head_ref);
4875 got_ref_close(head_ref);
4876 if (error != NULL)
4877 goto done;
4878 error = got_object_open_as_commit(&commit, repo,
4879 start_id);
4880 if (error != NULL)
4881 goto done;
4882 got_object_commit_close(commit);
4883 } else {
4884 error = got_keyword_to_idstr(&keyword_idstr, start_commit,
4885 repo, worktree);
4886 if (error != NULL)
4887 goto done;
4888 if (keyword_idstr != NULL)
4889 start_commit = keyword_idstr;
4891 error = got_repo_match_object_id(&start_id, NULL,
4892 start_commit, GOT_OBJ_TYPE_COMMIT, &refs, repo);
4893 if (error != NULL)
4894 goto done;
4896 if (end_commit != NULL) {
4897 error = got_keyword_to_idstr(&keyword_idstr, end_commit,
4898 repo, worktree);
4899 if (error != NULL)
4900 goto done;
4901 if (keyword_idstr != NULL)
4902 end_commit = keyword_idstr;
4904 error = got_repo_match_object_id(&end_id, NULL,
4905 end_commit, GOT_OBJ_TYPE_COMMIT, &refs, repo);
4906 if (error != NULL)
4907 goto done;
4910 if (worktree) {
4912 * If a path was specified on the command line it was resolved
4913 * to a path in the work tree above. Prepend the work tree's
4914 * path prefix to obtain the corresponding in-repository path.
4916 if (path) {
4917 const char *prefix;
4918 prefix = got_worktree_get_path_prefix(worktree);
4919 if (asprintf(&in_repo_path, "%s%s%s", prefix,
4920 (path[0] != '\0') ? "/" : "", path) == -1) {
4921 error = got_error_from_errno("asprintf");
4922 goto done;
4925 } else
4926 error = got_repo_map_path(&in_repo_path, repo,
4927 path ? path : "");
4928 if (error != NULL)
4929 goto done;
4930 if (in_repo_path) {
4931 free(path);
4932 path = in_repo_path;
4935 if (worktree) {
4936 /* Release work tree lock. */
4937 got_worktree_close(worktree);
4938 worktree = NULL;
4941 if (search_pattern && show_patch) {
4942 tmpfile = got_opentemp();
4943 if (tmpfile == NULL) {
4944 error = got_error_from_errno("got_opentemp");
4945 goto done;
4949 error = print_commits(start_id, end_id, repo, path ? path : "",
4950 show_changed_paths, show_diffstat, show_patch, search_pattern,
4951 diff_context, limit, log_branches, reverse_display_order,
4952 refs_idmap, one_line, toposort, tmpfile);
4953 done:
4954 free(path);
4955 free(repo_path);
4956 free(cwd);
4957 free(start_id);
4958 free(end_id);
4959 free(keyword_idstr);
4960 if (worktree)
4961 got_worktree_close(worktree);
4962 if (repo) {
4963 const struct got_error *close_err = got_repo_close(repo);
4964 if (error == NULL)
4965 error = close_err;
4967 if (pack_fds) {
4968 const struct got_error *pack_err =
4969 got_repo_pack_fds_close(pack_fds);
4970 if (error == NULL)
4971 error = pack_err;
4973 if (refs_idmap)
4974 got_reflist_object_id_map_free(refs_idmap);
4975 if (tmpfile && fclose(tmpfile) == EOF && error == NULL)
4976 error = got_error_from_errno("fclose");
4977 got_ref_list_free(&refs);
4978 return error;
4981 __dead static void
4982 usage_diff(void)
4984 fprintf(stderr, "usage: %s diff [-adPsw] [-C number] [-c commit] "
4985 "[-r repository-path] [object1 object2 | path ...]\n",
4986 getprogname());
4987 exit(1);
4990 struct print_diff_arg {
4991 struct got_repository *repo;
4992 struct got_worktree *worktree;
4993 struct got_diffstat_cb_arg *diffstat;
4994 int diff_context;
4995 const char *id_str;
4996 int header_shown;
4997 int diff_staged;
4998 enum got_diff_algorithm diff_algo;
4999 int ignore_whitespace;
5000 int force_text_diff;
5001 FILE *f1;
5002 FILE *f2;
5003 FILE *outfile;
5007 * Create a file which contains the target path of a symlink so we can feed
5008 * it as content to the diff engine.
5010 static const struct got_error *
5011 get_symlink_target_file(int *fd, int dirfd, const char *de_name,
5012 const char *abspath)
5014 const struct got_error *err = NULL;
5015 char target_path[PATH_MAX];
5016 ssize_t target_len, outlen;
5018 *fd = -1;
5020 if (dirfd != -1) {
5021 target_len = readlinkat(dirfd, de_name, target_path, PATH_MAX);
5022 if (target_len == -1)
5023 return got_error_from_errno2("readlinkat", abspath);
5024 } else {
5025 target_len = readlink(abspath, target_path, PATH_MAX);
5026 if (target_len == -1)
5027 return got_error_from_errno2("readlink", abspath);
5030 *fd = got_opentempfd();
5031 if (*fd == -1)
5032 return got_error_from_errno("got_opentempfd");
5034 outlen = write(*fd, target_path, target_len);
5035 if (outlen == -1) {
5036 err = got_error_from_errno("got_opentempfd");
5037 goto done;
5040 if (lseek(*fd, 0, SEEK_SET) == -1) {
5041 err = got_error_from_errno2("lseek", abspath);
5042 goto done;
5044 done:
5045 if (err) {
5046 close(*fd);
5047 *fd = -1;
5049 return err;
5052 static const struct got_error *
5053 print_diff(void *arg, unsigned char status, unsigned char staged_status,
5054 const char *path, struct got_object_id *blob_id,
5055 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
5056 int dirfd, const char *de_name)
5058 struct print_diff_arg *a = arg;
5059 const struct got_error *err = NULL;
5060 struct got_blob_object *blob1 = NULL;
5061 int fd = -1, fd1 = -1, fd2 = -1;
5062 FILE *f2 = NULL;
5063 char *abspath = NULL, *label1 = NULL;
5064 struct stat sb;
5065 off_t size1 = 0;
5066 int f2_exists = 0;
5068 memset(&sb, 0, sizeof(sb));
5070 if (a->diff_staged) {
5071 if (staged_status != GOT_STATUS_MODIFY &&
5072 staged_status != GOT_STATUS_ADD &&
5073 staged_status != GOT_STATUS_DELETE)
5074 return NULL;
5075 } else {
5076 if (staged_status == GOT_STATUS_DELETE)
5077 return NULL;
5078 if (status == GOT_STATUS_NONEXISTENT)
5079 return got_error_set_errno(ENOENT, path);
5080 if (status != GOT_STATUS_MODIFY &&
5081 status != GOT_STATUS_ADD &&
5082 status != GOT_STATUS_DELETE &&
5083 status != GOT_STATUS_CONFLICT)
5084 return NULL;
5087 err = got_opentemp_truncate(a->f1);
5088 if (err)
5089 return got_error_from_errno("got_opentemp_truncate");
5090 err = got_opentemp_truncate(a->f2);
5091 if (err)
5092 return got_error_from_errno("got_opentemp_truncate");
5094 if (!a->header_shown) {
5095 if (fprintf(a->outfile, "diff %s%s\n",
5096 a->diff_staged ? "-s " : "",
5097 got_worktree_get_root_path(a->worktree)) < 0) {
5098 err = got_error_from_errno("fprintf");
5099 goto done;
5101 if (fprintf(a->outfile, "commit - %s\n", a->id_str) < 0) {
5102 err = got_error_from_errno("fprintf");
5103 goto done;
5105 if (fprintf(a->outfile, "path + %s%s\n",
5106 got_worktree_get_root_path(a->worktree),
5107 a->diff_staged ? " (staged changes)" : "") < 0) {
5108 err = got_error_from_errno("fprintf");
5109 goto done;
5111 a->header_shown = 1;
5114 if (a->diff_staged) {
5115 const char *label1 = NULL, *label2 = NULL;
5116 switch (staged_status) {
5117 case GOT_STATUS_MODIFY:
5118 label1 = path;
5119 label2 = path;
5120 break;
5121 case GOT_STATUS_ADD:
5122 label2 = path;
5123 break;
5124 case GOT_STATUS_DELETE:
5125 label1 = path;
5126 break;
5127 default:
5128 return got_error(GOT_ERR_FILE_STATUS);
5130 fd1 = got_opentempfd();
5131 if (fd1 == -1) {
5132 err = got_error_from_errno("got_opentempfd");
5133 goto done;
5135 fd2 = got_opentempfd();
5136 if (fd2 == -1) {
5137 err = got_error_from_errno("got_opentempfd");
5138 goto done;
5140 err = got_diff_objects_as_blobs(NULL, NULL, a->f1, a->f2,
5141 fd1, fd2, blob_id, staged_blob_id, label1, label2,
5142 a->diff_algo, a->diff_context, a->ignore_whitespace,
5143 a->force_text_diff, a->diffstat, a->repo, a->outfile);
5144 goto done;
5147 fd1 = got_opentempfd();
5148 if (fd1 == -1) {
5149 err = got_error_from_errno("got_opentempfd");
5150 goto done;
5153 if (staged_status == GOT_STATUS_ADD ||
5154 staged_status == GOT_STATUS_MODIFY) {
5155 char *id_str;
5156 err = got_object_open_as_blob(&blob1, a->repo, staged_blob_id,
5157 8192, fd1);
5158 if (err)
5159 goto done;
5160 err = got_object_id_str(&id_str, staged_blob_id);
5161 if (err)
5162 goto done;
5163 if (asprintf(&label1, "%s (staged)", id_str) == -1) {
5164 err = got_error_from_errno("asprintf");
5165 free(id_str);
5166 goto done;
5168 free(id_str);
5169 } else if (status != GOT_STATUS_ADD) {
5170 err = got_object_open_as_blob(&blob1, a->repo, blob_id, 8192,
5171 fd1);
5172 if (err)
5173 goto done;
5176 if (status != GOT_STATUS_DELETE) {
5177 if (asprintf(&abspath, "%s/%s",
5178 got_worktree_get_root_path(a->worktree), path) == -1) {
5179 err = got_error_from_errno("asprintf");
5180 goto done;
5183 if (dirfd != -1) {
5184 fd = openat(dirfd, de_name,
5185 O_RDONLY | O_NOFOLLOW | O_CLOEXEC);
5186 if (fd == -1) {
5187 if (!got_err_open_nofollow_on_symlink()) {
5188 err = got_error_from_errno2("openat",
5189 abspath);
5190 goto done;
5192 err = get_symlink_target_file(&fd, dirfd,
5193 de_name, abspath);
5194 if (err)
5195 goto done;
5197 } else {
5198 fd = open(abspath, O_RDONLY | O_NOFOLLOW | O_CLOEXEC);
5199 if (fd == -1) {
5200 if (!got_err_open_nofollow_on_symlink()) {
5201 err = got_error_from_errno2("open",
5202 abspath);
5203 goto done;
5205 err = get_symlink_target_file(&fd, dirfd,
5206 de_name, abspath);
5207 if (err)
5208 goto done;
5211 if (fstatat(fd, abspath, &sb, AT_SYMLINK_NOFOLLOW) == -1) {
5212 err = got_error_from_errno2("fstatat", abspath);
5213 goto done;
5215 f2 = fdopen(fd, "r");
5216 if (f2 == NULL) {
5217 err = got_error_from_errno2("fdopen", abspath);
5218 goto done;
5220 fd = -1;
5221 f2_exists = 1;
5224 if (blob1) {
5225 err = got_object_blob_dump_to_file(&size1, NULL, NULL,
5226 a->f1, blob1);
5227 if (err)
5228 goto done;
5231 err = got_diff_blob_file(blob1, a->f1, size1, label1, f2 ? f2 : a->f2,
5232 f2_exists, &sb, path, GOT_DIFF_ALGORITHM_PATIENCE, a->diff_context,
5233 a->ignore_whitespace, a->force_text_diff, a->diffstat, a->outfile);
5234 done:
5235 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
5236 err = got_error_from_errno("close");
5237 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
5238 err = got_error_from_errno("close");
5239 if (blob1)
5240 got_object_blob_close(blob1);
5241 if (fd != -1 && close(fd) == -1 && err == NULL)
5242 err = got_error_from_errno("close");
5243 if (f2 && fclose(f2) == EOF && err == NULL)
5244 err = got_error_from_errno("fclose");
5245 free(abspath);
5246 return err;
5249 static const struct got_error *
5250 cmd_diff(int argc, char *argv[])
5252 const struct got_error *error;
5253 struct got_repository *repo = NULL;
5254 struct got_worktree *worktree = NULL;
5255 char *cwd = NULL, *repo_path = NULL;
5256 const char *commit_args[2] = { NULL, NULL };
5257 int ncommit_args = 0;
5258 struct got_object_id *ids[2] = { NULL, NULL };
5259 char *labels[2] = { NULL, NULL };
5260 int type1 = GOT_OBJ_TYPE_ANY, type2 = GOT_OBJ_TYPE_ANY;
5261 int diff_context = 3, diff_staged = 0, ignore_whitespace = 0, ch, i;
5262 int force_text_diff = 0, force_path = 0, rflag = 0, show_diffstat = 0;
5263 const char *errstr;
5264 struct got_reflist_head refs;
5265 struct got_pathlist_head diffstat_paths, paths;
5266 FILE *f1 = NULL, *f2 = NULL, *outfile = NULL;
5267 int fd1 = -1, fd2 = -1;
5268 int *pack_fds = NULL;
5269 struct got_diffstat_cb_arg dsa;
5271 memset(&dsa, 0, sizeof(dsa));
5273 TAILQ_INIT(&refs);
5274 TAILQ_INIT(&paths);
5275 TAILQ_INIT(&diffstat_paths);
5277 #ifndef PROFILE
5278 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
5279 NULL) == -1)
5280 err(1, "pledge");
5281 #endif
5283 while ((ch = getopt(argc, argv, "aC:c:dPr:sw")) != -1) {
5284 switch (ch) {
5285 case 'a':
5286 force_text_diff = 1;
5287 break;
5288 case 'C':
5289 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
5290 &errstr);
5291 if (errstr != NULL)
5292 errx(1, "number of context lines is %s: %s",
5293 errstr, optarg);
5294 break;
5295 case 'c':
5296 if (ncommit_args >= 2)
5297 errx(1, "too many -c options used");
5298 commit_args[ncommit_args++] = optarg;
5299 break;
5300 case 'd':
5301 show_diffstat = 1;
5302 break;
5303 case 'P':
5304 force_path = 1;
5305 break;
5306 case 'r':
5307 repo_path = realpath(optarg, NULL);
5308 if (repo_path == NULL)
5309 return got_error_from_errno2("realpath",
5310 optarg);
5311 got_path_strip_trailing_slashes(repo_path);
5312 rflag = 1;
5313 break;
5314 case 's':
5315 diff_staged = 1;
5316 break;
5317 case 'w':
5318 ignore_whitespace = 1;
5319 break;
5320 default:
5321 usage_diff();
5322 /* NOTREACHED */
5326 argc -= optind;
5327 argv += optind;
5329 cwd = getcwd(NULL, 0);
5330 if (cwd == NULL) {
5331 error = got_error_from_errno("getcwd");
5332 goto done;
5335 error = got_repo_pack_fds_open(&pack_fds);
5336 if (error != NULL)
5337 goto done;
5339 if (repo_path == NULL) {
5340 error = got_worktree_open(&worktree, cwd,
5341 GOT_WORKTREE_GOT_DIR);
5342 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5343 goto done;
5344 else
5345 error = NULL;
5346 if (worktree) {
5347 repo_path =
5348 strdup(got_worktree_get_repo_path(worktree));
5349 if (repo_path == NULL) {
5350 error = got_error_from_errno("strdup");
5351 goto done;
5353 } else {
5354 repo_path = strdup(cwd);
5355 if (repo_path == NULL) {
5356 error = got_error_from_errno("strdup");
5357 goto done;
5362 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
5363 free(repo_path);
5364 if (error != NULL)
5365 goto done;
5367 if (show_diffstat) {
5368 dsa.paths = &diffstat_paths;
5369 dsa.force_text = force_text_diff;
5370 dsa.ignore_ws = ignore_whitespace;
5371 dsa.diff_algo = GOT_DIFF_ALGORITHM_PATIENCE;
5374 if (rflag || worktree == NULL || ncommit_args > 0) {
5375 if (force_path) {
5376 error = got_error_msg(GOT_ERR_NOT_IMPL,
5377 "-P option can only be used when diffing "
5378 "a work tree");
5379 goto done;
5381 if (diff_staged) {
5382 error = got_error_msg(GOT_ERR_NOT_IMPL,
5383 "-s option can only be used when diffing "
5384 "a work tree");
5385 goto done;
5389 error = apply_unveil(got_repo_get_path(repo), 1,
5390 worktree ? got_worktree_get_root_path(worktree) : NULL);
5391 if (error)
5392 goto done;
5394 if ((!force_path && argc == 2) || ncommit_args > 0) {
5395 int obj_type = (ncommit_args > 0 ?
5396 GOT_OBJ_TYPE_COMMIT : GOT_OBJ_TYPE_ANY);
5397 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
5398 NULL);
5399 if (error)
5400 goto done;
5401 for (i = 0; i < (ncommit_args > 0 ? ncommit_args : argc); i++) {
5402 const char *arg;
5403 char *keyword_idstr = NULL;
5405 if (ncommit_args > 0)
5406 arg = commit_args[i];
5407 else
5408 arg = argv[i];
5410 error = got_keyword_to_idstr(&keyword_idstr, arg,
5411 repo, worktree);
5412 if (error != NULL)
5413 goto done;
5414 if (keyword_idstr != NULL)
5415 arg = keyword_idstr;
5417 error = got_repo_match_object_id(&ids[i], &labels[i],
5418 arg, obj_type, &refs, repo);
5419 free(keyword_idstr);
5420 if (error) {
5421 if (error->code != GOT_ERR_NOT_REF &&
5422 error->code != GOT_ERR_NO_OBJ)
5423 goto done;
5424 if (ncommit_args > 0)
5425 goto done;
5426 error = NULL;
5427 break;
5432 f1 = got_opentemp();
5433 if (f1 == NULL) {
5434 error = got_error_from_errno("got_opentemp");
5435 goto done;
5438 f2 = got_opentemp();
5439 if (f2 == NULL) {
5440 error = got_error_from_errno("got_opentemp");
5441 goto done;
5444 outfile = got_opentemp();
5445 if (outfile == NULL) {
5446 error = got_error_from_errno("got_opentemp");
5447 goto done;
5450 if (ncommit_args == 0 && (ids[0] == NULL || ids[1] == NULL)) {
5451 struct print_diff_arg arg;
5452 char *id_str;
5454 if (worktree == NULL) {
5455 if (argc == 2 && ids[0] == NULL) {
5456 error = got_error_path(argv[0], GOT_ERR_NO_OBJ);
5457 goto done;
5458 } else if (argc == 2 && ids[1] == NULL) {
5459 error = got_error_path(argv[1], GOT_ERR_NO_OBJ);
5460 goto done;
5461 } else if (argc > 0) {
5462 error = got_error_fmt(GOT_ERR_NOT_WORKTREE,
5463 "%s", "specified paths cannot be resolved");
5464 goto done;
5465 } else {
5466 error = got_error(GOT_ERR_NOT_WORKTREE);
5467 goto done;
5471 error = get_worktree_paths_from_argv(&paths, argc, argv,
5472 worktree);
5473 if (error)
5474 goto done;
5476 error = got_object_id_str(&id_str,
5477 got_worktree_get_base_commit_id(worktree));
5478 if (error)
5479 goto done;
5480 arg.repo = repo;
5481 arg.worktree = worktree;
5482 arg.diff_algo = GOT_DIFF_ALGORITHM_PATIENCE;
5483 arg.diff_context = diff_context;
5484 arg.id_str = id_str;
5485 arg.header_shown = 0;
5486 arg.diff_staged = diff_staged;
5487 arg.ignore_whitespace = ignore_whitespace;
5488 arg.force_text_diff = force_text_diff;
5489 arg.diffstat = show_diffstat ? &dsa : NULL;
5490 arg.f1 = f1;
5491 arg.f2 = f2;
5492 arg.outfile = outfile;
5494 error = got_worktree_status(worktree, &paths, repo, 0,
5495 print_diff, &arg, check_cancelled, NULL);
5496 free(id_str);
5497 if (error)
5498 goto done;
5500 if (show_diffstat && dsa.nfiles > 0) {
5501 char *header;
5503 if (asprintf(&header, "diffstat %s%s",
5504 diff_staged ? "-s " : "",
5505 got_worktree_get_root_path(worktree)) == -1) {
5506 error = got_error_from_errno("asprintf");
5507 goto done;
5510 error = print_diffstat(&dsa, header);
5511 free(header);
5512 if (error)
5513 goto done;
5516 error = printfile(outfile);
5517 goto done;
5520 if (ncommit_args == 1) {
5521 struct got_commit_object *commit;
5522 error = got_object_open_as_commit(&commit, repo, ids[0]);
5523 if (error)
5524 goto done;
5526 labels[1] = labels[0];
5527 ids[1] = ids[0];
5528 if (got_object_commit_get_nparents(commit) > 0) {
5529 const struct got_object_id_queue *pids;
5530 struct got_object_qid *pid;
5531 pids = got_object_commit_get_parent_ids(commit);
5532 pid = STAILQ_FIRST(pids);
5533 ids[0] = got_object_id_dup(&pid->id);
5534 if (ids[0] == NULL) {
5535 error = got_error_from_errno(
5536 "got_object_id_dup");
5537 got_object_commit_close(commit);
5538 goto done;
5540 error = got_object_id_str(&labels[0], ids[0]);
5541 if (error) {
5542 got_object_commit_close(commit);
5543 goto done;
5545 } else {
5546 ids[0] = NULL;
5547 labels[0] = strdup("/dev/null");
5548 if (labels[0] == NULL) {
5549 error = got_error_from_errno("strdup");
5550 got_object_commit_close(commit);
5551 goto done;
5555 got_object_commit_close(commit);
5558 if (ncommit_args == 0 && argc > 2) {
5559 error = got_error_msg(GOT_ERR_BAD_PATH,
5560 "path arguments cannot be used when diffing two objects");
5561 goto done;
5564 if (ids[0]) {
5565 error = got_object_get_type(&type1, repo, ids[0]);
5566 if (error)
5567 goto done;
5570 error = got_object_get_type(&type2, repo, ids[1]);
5571 if (error)
5572 goto done;
5573 if (type1 != GOT_OBJ_TYPE_ANY && type1 != type2) {
5574 error = got_error(GOT_ERR_OBJ_TYPE);
5575 goto done;
5577 if (type1 == GOT_OBJ_TYPE_BLOB && argc > 2) {
5578 error = got_error_msg(GOT_ERR_OBJ_TYPE,
5579 "path arguments cannot be used when diffing blobs");
5580 goto done;
5583 for (i = 0; ncommit_args > 0 && i < argc; i++) {
5584 char *in_repo_path;
5585 struct got_pathlist_entry *new;
5586 if (worktree) {
5587 const char *prefix;
5588 char *p;
5589 error = got_worktree_resolve_path(&p, worktree,
5590 argv[i]);
5591 if (error)
5592 goto done;
5593 prefix = got_worktree_get_path_prefix(worktree);
5594 while (prefix[0] == '/')
5595 prefix++;
5596 if (asprintf(&in_repo_path, "%s%s%s", prefix,
5597 (p[0] != '\0' && prefix[0] != '\0') ? "/" : "",
5598 p) == -1) {
5599 error = got_error_from_errno("asprintf");
5600 free(p);
5601 goto done;
5603 free(p);
5604 } else {
5605 char *mapped_path, *s;
5606 error = got_repo_map_path(&mapped_path, repo, argv[i]);
5607 if (error)
5608 goto done;
5609 s = mapped_path;
5610 while (s[0] == '/')
5611 s++;
5612 in_repo_path = strdup(s);
5613 if (in_repo_path == NULL) {
5614 error = got_error_from_errno("asprintf");
5615 free(mapped_path);
5616 goto done;
5618 free(mapped_path);
5621 error = got_pathlist_insert(&new, &paths, in_repo_path, NULL);
5622 if (error || new == NULL /* duplicate */)
5623 free(in_repo_path);
5624 if (error)
5625 goto done;
5628 if (worktree) {
5629 /* Release work tree lock. */
5630 got_worktree_close(worktree);
5631 worktree = NULL;
5634 fd1 = got_opentempfd();
5635 if (fd1 == -1) {
5636 error = got_error_from_errno("got_opentempfd");
5637 goto done;
5640 fd2 = got_opentempfd();
5641 if (fd2 == -1) {
5642 error = got_error_from_errno("got_opentempfd");
5643 goto done;
5646 switch (type1 == GOT_OBJ_TYPE_ANY ? type2 : type1) {
5647 case GOT_OBJ_TYPE_BLOB:
5648 error = got_diff_objects_as_blobs(NULL, NULL, f1, f2,
5649 fd1, fd2, ids[0], ids[1], NULL, NULL,
5650 GOT_DIFF_ALGORITHM_PATIENCE, diff_context,
5651 ignore_whitespace, force_text_diff,
5652 show_diffstat ? &dsa : NULL, repo, outfile);
5653 break;
5654 case GOT_OBJ_TYPE_TREE:
5655 error = got_diff_objects_as_trees(NULL, NULL, f1, f2, fd1, fd2,
5656 ids[0], ids[1], &paths, "", "",
5657 GOT_DIFF_ALGORITHM_PATIENCE, diff_context,
5658 ignore_whitespace, force_text_diff,
5659 show_diffstat ? &dsa : NULL, repo, outfile);
5660 break;
5661 case GOT_OBJ_TYPE_COMMIT:
5662 fprintf(outfile, "diff %s %s\n", labels[0], labels[1]);
5663 error = got_diff_objects_as_commits(NULL, NULL, f1, f2,
5664 fd1, fd2, ids[0], ids[1], &paths,
5665 GOT_DIFF_ALGORITHM_PATIENCE, diff_context,
5666 ignore_whitespace, force_text_diff,
5667 show_diffstat ? &dsa : NULL, repo, outfile);
5668 break;
5669 default:
5670 error = got_error(GOT_ERR_OBJ_TYPE);
5672 if (error)
5673 goto done;
5675 if (show_diffstat && dsa.nfiles > 0) {
5676 char *header = NULL;
5678 if (asprintf(&header, "diffstat %s %s",
5679 labels[0], labels[1]) == -1) {
5680 error = got_error_from_errno("asprintf");
5681 goto done;
5684 error = print_diffstat(&dsa, header);
5685 free(header);
5686 if (error)
5687 goto done;
5690 error = printfile(outfile);
5692 done:
5693 free(cwd);
5694 free(labels[0]);
5695 free(labels[1]);
5696 free(ids[0]);
5697 free(ids[1]);
5698 if (worktree)
5699 got_worktree_close(worktree);
5700 if (repo) {
5701 const struct got_error *close_err = got_repo_close(repo);
5702 if (error == NULL)
5703 error = close_err;
5705 if (pack_fds) {
5706 const struct got_error *pack_err =
5707 got_repo_pack_fds_close(pack_fds);
5708 if (error == NULL)
5709 error = pack_err;
5711 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
5712 got_pathlist_free(&diffstat_paths, GOT_PATHLIST_FREE_ALL);
5713 got_ref_list_free(&refs);
5714 if (outfile && fclose(outfile) == EOF && error == NULL)
5715 error = got_error_from_errno("fclose");
5716 if (f1 && fclose(f1) == EOF && error == NULL)
5717 error = got_error_from_errno("fclose");
5718 if (f2 && fclose(f2) == EOF && error == NULL)
5719 error = got_error_from_errno("fclose");
5720 if (fd1 != -1 && close(fd1) == -1 && error == NULL)
5721 error = got_error_from_errno("close");
5722 if (fd2 != -1 && close(fd2) == -1 && error == NULL)
5723 error = got_error_from_errno("close");
5724 return error;
5727 __dead static void
5728 usage_blame(void)
5730 fprintf(stderr,
5731 "usage: %s blame [-c commit] [-r repository-path] path\n",
5732 getprogname());
5733 exit(1);
5736 struct blame_line {
5737 int annotated;
5738 char *id_str;
5739 char *committer;
5740 char datebuf[11]; /* YYYY-MM-DD + NUL */
5743 struct blame_cb_args {
5744 struct blame_line *lines;
5745 int nlines;
5746 int nlines_prec;
5747 int lineno_cur;
5748 off_t *line_offsets;
5749 FILE *f;
5750 struct got_repository *repo;
5753 static const struct got_error *
5754 blame_cb(void *arg, int nlines, int lineno,
5755 struct got_commit_object *commit, struct got_object_id *id)
5757 const struct got_error *err = NULL;
5758 struct blame_cb_args *a = arg;
5759 struct blame_line *bline;
5760 char *line = NULL;
5761 size_t linesize = 0;
5762 off_t offset;
5763 struct tm tm;
5764 time_t committer_time;
5766 if (nlines != a->nlines ||
5767 (lineno != -1 && lineno < 1) || lineno > a->nlines)
5768 return got_error(GOT_ERR_RANGE);
5770 if (sigint_received)
5771 return got_error(GOT_ERR_ITER_COMPLETED);
5773 if (lineno == -1)
5774 return NULL; /* no change in this commit */
5776 /* Annotate this line. */
5777 bline = &a->lines[lineno - 1];
5778 if (bline->annotated)
5779 return NULL;
5780 err = got_object_id_str(&bline->id_str, id);
5781 if (err)
5782 return err;
5784 bline->committer = strdup(got_object_commit_get_committer(commit));
5785 if (bline->committer == NULL) {
5786 err = got_error_from_errno("strdup");
5787 goto done;
5790 committer_time = got_object_commit_get_committer_time(commit);
5791 if (gmtime_r(&committer_time, &tm) == NULL)
5792 return got_error_from_errno("gmtime_r");
5793 if (strftime(bline->datebuf, sizeof(bline->datebuf), "%F", &tm) == 0) {
5794 err = got_error(GOT_ERR_NO_SPACE);
5795 goto done;
5797 bline->annotated = 1;
5799 /* Print lines annotated so far. */
5800 bline = &a->lines[a->lineno_cur - 1];
5801 if (!bline->annotated)
5802 goto done;
5804 offset = a->line_offsets[a->lineno_cur - 1];
5805 if (fseeko(a->f, offset, SEEK_SET) == -1) {
5806 err = got_error_from_errno("fseeko");
5807 goto done;
5810 while (a->lineno_cur <= a->nlines && bline->annotated) {
5811 char *smallerthan, *at, *nl, *committer;
5812 size_t len;
5814 if (getline(&line, &linesize, a->f) == -1) {
5815 if (ferror(a->f))
5816 err = got_error_from_errno("getline");
5817 break;
5820 committer = bline->committer;
5821 smallerthan = strchr(committer, '<');
5822 if (smallerthan && smallerthan[1] != '\0')
5823 committer = smallerthan + 1;
5824 at = strchr(committer, '@');
5825 if (at)
5826 *at = '\0';
5827 len = strlen(committer);
5828 if (len >= 9)
5829 committer[8] = '\0';
5831 nl = strchr(line, '\n');
5832 if (nl)
5833 *nl = '\0';
5834 printf("%.*d) %.8s %s %-8s %s\n", a->nlines_prec, a->lineno_cur,
5835 bline->id_str, bline->datebuf, committer, line);
5837 a->lineno_cur++;
5838 bline = &a->lines[a->lineno_cur - 1];
5840 done:
5841 free(line);
5842 return err;
5845 static const struct got_error *
5846 cmd_blame(int argc, char *argv[])
5848 const struct got_error *error;
5849 struct got_repository *repo = NULL;
5850 struct got_worktree *worktree = NULL;
5851 char *path, *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
5852 char *link_target = NULL;
5853 struct got_object_id *obj_id = NULL;
5854 struct got_object_id *commit_id = NULL;
5855 struct got_commit_object *commit = NULL;
5856 struct got_blob_object *blob = NULL;
5857 char *commit_id_str = NULL, *keyword_idstr = NULL;
5858 struct blame_cb_args bca;
5859 int ch, obj_type, i, fd1 = -1, fd2 = -1, fd3 = -1;
5860 off_t filesize;
5861 int *pack_fds = NULL;
5862 FILE *f1 = NULL, *f2 = NULL;
5864 fd1 = got_opentempfd();
5865 if (fd1 == -1)
5866 return got_error_from_errno("got_opentempfd");
5868 memset(&bca, 0, sizeof(bca));
5870 #ifndef PROFILE
5871 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
5872 NULL) == -1)
5873 err(1, "pledge");
5874 #endif
5876 while ((ch = getopt(argc, argv, "c:r:")) != -1) {
5877 switch (ch) {
5878 case 'c':
5879 commit_id_str = optarg;
5880 break;
5881 case 'r':
5882 repo_path = realpath(optarg, NULL);
5883 if (repo_path == NULL)
5884 return got_error_from_errno2("realpath",
5885 optarg);
5886 got_path_strip_trailing_slashes(repo_path);
5887 break;
5888 default:
5889 usage_blame();
5890 /* NOTREACHED */
5894 argc -= optind;
5895 argv += optind;
5897 if (argc == 1)
5898 path = argv[0];
5899 else
5900 usage_blame();
5902 cwd = getcwd(NULL, 0);
5903 if (cwd == NULL) {
5904 error = got_error_from_errno("getcwd");
5905 goto done;
5908 error = got_repo_pack_fds_open(&pack_fds);
5909 if (error != NULL)
5910 goto done;
5912 if (repo_path == NULL) {
5913 error = got_worktree_open(&worktree, cwd,
5914 GOT_WORKTREE_GOT_DIR);
5915 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5916 goto done;
5917 else
5918 error = NULL;
5919 if (worktree) {
5920 repo_path =
5921 strdup(got_worktree_get_repo_path(worktree));
5922 if (repo_path == NULL) {
5923 error = got_error_from_errno("strdup");
5924 if (error)
5925 goto done;
5927 } else {
5928 repo_path = strdup(cwd);
5929 if (repo_path == NULL) {
5930 error = got_error_from_errno("strdup");
5931 goto done;
5936 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
5937 if (error != NULL)
5938 goto done;
5940 if (worktree) {
5941 const char *prefix = got_worktree_get_path_prefix(worktree);
5942 char *p;
5944 error = got_worktree_resolve_path(&p, worktree, path);
5945 if (error)
5946 goto done;
5947 if (asprintf(&in_repo_path, "%s%s%s", prefix,
5948 (p[0] != '\0' && !got_path_is_root_dir(prefix)) ? "/" : "",
5949 p) == -1) {
5950 error = got_error_from_errno("asprintf");
5951 free(p);
5952 goto done;
5954 free(p);
5955 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5956 } else {
5957 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5958 if (error)
5959 goto done;
5960 error = got_repo_map_path(&in_repo_path, repo, path);
5962 if (error)
5963 goto done;
5965 if (commit_id_str == NULL) {
5966 struct got_reference *head_ref;
5967 error = got_ref_open(&head_ref, repo, worktree ?
5968 got_worktree_get_head_ref_name(worktree) : GOT_REF_HEAD, 0);
5969 if (error != NULL)
5970 goto done;
5971 error = got_ref_resolve(&commit_id, repo, head_ref);
5972 got_ref_close(head_ref);
5973 if (error != NULL)
5974 goto done;
5975 } else {
5976 struct got_reflist_head refs;
5978 TAILQ_INIT(&refs);
5979 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
5980 NULL);
5981 if (error)
5982 goto done;
5984 error = got_keyword_to_idstr(&keyword_idstr, commit_id_str,
5985 repo, worktree);
5986 if (error != NULL)
5987 goto done;
5988 if (keyword_idstr != NULL)
5989 commit_id_str = keyword_idstr;
5991 error = got_repo_match_object_id(&commit_id, NULL,
5992 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
5993 got_ref_list_free(&refs);
5994 if (error)
5995 goto done;
5998 if (worktree) {
5999 /* Release work tree lock. */
6000 got_worktree_close(worktree);
6001 worktree = NULL;
6004 error = got_object_open_as_commit(&commit, repo, commit_id);
6005 if (error)
6006 goto done;
6008 error = got_object_resolve_symlinks(&link_target, in_repo_path,
6009 commit, repo);
6010 if (error)
6011 goto done;
6013 error = got_object_id_by_path(&obj_id, repo, commit,
6014 link_target ? link_target : in_repo_path);
6015 if (error)
6016 goto done;
6018 error = got_object_get_type(&obj_type, repo, obj_id);
6019 if (error)
6020 goto done;
6022 if (obj_type != GOT_OBJ_TYPE_BLOB) {
6023 error = got_error_path(link_target ? link_target : in_repo_path,
6024 GOT_ERR_OBJ_TYPE);
6025 goto done;
6028 error = got_object_open_as_blob(&blob, repo, obj_id, 8192, fd1);
6029 if (error)
6030 goto done;
6031 bca.f = got_opentemp();
6032 if (bca.f == NULL) {
6033 error = got_error_from_errno("got_opentemp");
6034 goto done;
6036 error = got_object_blob_dump_to_file(&filesize, &bca.nlines,
6037 &bca.line_offsets, bca.f, blob);
6038 if (error || bca.nlines == 0)
6039 goto done;
6041 /* Don't include \n at EOF in the blame line count. */
6042 if (bca.line_offsets[bca.nlines - 1] == filesize)
6043 bca.nlines--;
6045 bca.lines = calloc(bca.nlines, sizeof(*bca.lines));
6046 if (bca.lines == NULL) {
6047 error = got_error_from_errno("calloc");
6048 goto done;
6050 bca.lineno_cur = 1;
6051 bca.nlines_prec = 0;
6052 i = bca.nlines;
6053 while (i > 0) {
6054 i /= 10;
6055 bca.nlines_prec++;
6057 bca.repo = repo;
6059 fd2 = got_opentempfd();
6060 if (fd2 == -1) {
6061 error = got_error_from_errno("got_opentempfd");
6062 goto done;
6064 fd3 = got_opentempfd();
6065 if (fd3 == -1) {
6066 error = got_error_from_errno("got_opentempfd");
6067 goto done;
6069 f1 = got_opentemp();
6070 if (f1 == NULL) {
6071 error = got_error_from_errno("got_opentemp");
6072 goto done;
6074 f2 = got_opentemp();
6075 if (f2 == NULL) {
6076 error = got_error_from_errno("got_opentemp");
6077 goto done;
6079 error = got_blame(link_target ? link_target : in_repo_path, commit_id,
6080 repo, GOT_DIFF_ALGORITHM_PATIENCE, blame_cb, &bca,
6081 check_cancelled, NULL, fd2, fd3, f1, f2);
6082 done:
6083 free(keyword_idstr);
6084 free(in_repo_path);
6085 free(link_target);
6086 free(repo_path);
6087 free(cwd);
6088 free(commit_id);
6089 free(obj_id);
6090 if (commit)
6091 got_object_commit_close(commit);
6093 if (fd1 != -1 && close(fd1) == -1 && error == NULL)
6094 error = got_error_from_errno("close");
6095 if (fd2 != -1 && close(fd2) == -1 && error == NULL)
6096 error = got_error_from_errno("close");
6097 if (fd3 != -1 && close(fd3) == -1 && error == NULL)
6098 error = got_error_from_errno("close");
6099 if (f1 && fclose(f1) == EOF && error == NULL)
6100 error = got_error_from_errno("fclose");
6101 if (f2 && fclose(f2) == EOF && error == NULL)
6102 error = got_error_from_errno("fclose");
6104 if (blob)
6105 got_object_blob_close(blob);
6106 if (worktree)
6107 got_worktree_close(worktree);
6108 if (repo) {
6109 const struct got_error *close_err = got_repo_close(repo);
6110 if (error == NULL)
6111 error = close_err;
6113 if (pack_fds) {
6114 const struct got_error *pack_err =
6115 got_repo_pack_fds_close(pack_fds);
6116 if (error == NULL)
6117 error = pack_err;
6119 if (bca.lines) {
6120 for (i = 0; i < bca.nlines; i++) {
6121 struct blame_line *bline = &bca.lines[i];
6122 free(bline->id_str);
6123 free(bline->committer);
6125 free(bca.lines);
6127 free(bca.line_offsets);
6128 if (bca.f && fclose(bca.f) == EOF && error == NULL)
6129 error = got_error_from_errno("fclose");
6130 return error;
6133 __dead static void
6134 usage_tree(void)
6136 fprintf(stderr, "usage: %s tree [-iR] [-c commit] [-r repository-path] "
6137 "[path]\n", getprogname());
6138 exit(1);
6141 static const struct got_error *
6142 print_entry(struct got_tree_entry *te, const char *id, const char *path,
6143 const char *root_path, struct got_repository *repo)
6145 const struct got_error *err = NULL;
6146 int is_root_path = (strcmp(path, root_path) == 0);
6147 const char *modestr = "";
6148 mode_t mode = got_tree_entry_get_mode(te);
6149 char *link_target = NULL;
6151 path += strlen(root_path);
6152 while (path[0] == '/')
6153 path++;
6155 if (got_object_tree_entry_is_submodule(te))
6156 modestr = "$";
6157 else if (S_ISLNK(mode)) {
6158 int i;
6160 err = got_tree_entry_get_symlink_target(&link_target, te, repo);
6161 if (err)
6162 return err;
6163 for (i = 0; link_target[i] != '\0'; i++) {
6164 if (!isprint((unsigned char)link_target[i]))
6165 link_target[i] = '?';
6168 modestr = "@";
6170 else if (S_ISDIR(mode))
6171 modestr = "/";
6172 else if (mode & S_IXUSR)
6173 modestr = "*";
6175 printf("%s%s%s%s%s%s%s\n", id ? id : "", path,
6176 is_root_path ? "" : "/", got_tree_entry_get_name(te), modestr,
6177 link_target ? " -> ": "", link_target ? link_target : "");
6179 free(link_target);
6180 return NULL;
6183 static const struct got_error *
6184 print_tree(const char *path, struct got_commit_object *commit,
6185 int show_ids, int recurse, const char *root_path,
6186 struct got_repository *repo)
6188 const struct got_error *err = NULL;
6189 struct got_object_id *tree_id = NULL;
6190 struct got_tree_object *tree = NULL;
6191 int nentries, i;
6193 err = got_object_id_by_path(&tree_id, repo, commit, path);
6194 if (err)
6195 goto done;
6197 err = got_object_open_as_tree(&tree, repo, tree_id);
6198 if (err)
6199 goto done;
6200 nentries = got_object_tree_get_nentries(tree);
6201 for (i = 0; i < nentries; i++) {
6202 struct got_tree_entry *te;
6203 char *id = NULL;
6205 if (sigint_received || sigpipe_received)
6206 break;
6208 te = got_object_tree_get_entry(tree, i);
6209 if (show_ids) {
6210 char *id_str;
6211 err = got_object_id_str(&id_str,
6212 got_tree_entry_get_id(te));
6213 if (err)
6214 goto done;
6215 if (asprintf(&id, "%s ", id_str) == -1) {
6216 err = got_error_from_errno("asprintf");
6217 free(id_str);
6218 goto done;
6220 free(id_str);
6222 err = print_entry(te, id, path, root_path, repo);
6223 free(id);
6224 if (err)
6225 goto done;
6227 if (recurse && S_ISDIR(got_tree_entry_get_mode(te))) {
6228 char *child_path;
6229 if (asprintf(&child_path, "%s%s%s", path,
6230 path[0] == '/' && path[1] == '\0' ? "" : "/",
6231 got_tree_entry_get_name(te)) == -1) {
6232 err = got_error_from_errno("asprintf");
6233 goto done;
6235 err = print_tree(child_path, commit, show_ids, 1,
6236 root_path, repo);
6237 free(child_path);
6238 if (err)
6239 goto done;
6242 done:
6243 if (tree)
6244 got_object_tree_close(tree);
6245 free(tree_id);
6246 return err;
6249 static const struct got_error *
6250 cmd_tree(int argc, char *argv[])
6252 const struct got_error *error;
6253 struct got_repository *repo = NULL;
6254 struct got_worktree *worktree = NULL;
6255 const char *path, *refname = NULL;
6256 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
6257 struct got_object_id *commit_id = NULL;
6258 struct got_commit_object *commit = NULL;
6259 char *commit_id_str = NULL, *keyword_idstr = NULL;
6260 int show_ids = 0, recurse = 0;
6261 int ch;
6262 int *pack_fds = NULL;
6264 #ifndef PROFILE
6265 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
6266 NULL) == -1)
6267 err(1, "pledge");
6268 #endif
6270 while ((ch = getopt(argc, argv, "c:iRr:")) != -1) {
6271 switch (ch) {
6272 case 'c':
6273 commit_id_str = optarg;
6274 break;
6275 case 'i':
6276 show_ids = 1;
6277 break;
6278 case 'R':
6279 recurse = 1;
6280 break;
6281 case 'r':
6282 repo_path = realpath(optarg, NULL);
6283 if (repo_path == NULL)
6284 return got_error_from_errno2("realpath",
6285 optarg);
6286 got_path_strip_trailing_slashes(repo_path);
6287 break;
6288 default:
6289 usage_tree();
6290 /* NOTREACHED */
6294 argc -= optind;
6295 argv += optind;
6297 if (argc == 1)
6298 path = argv[0];
6299 else if (argc > 1)
6300 usage_tree();
6301 else
6302 path = NULL;
6304 cwd = getcwd(NULL, 0);
6305 if (cwd == NULL) {
6306 error = got_error_from_errno("getcwd");
6307 goto done;
6310 error = got_repo_pack_fds_open(&pack_fds);
6311 if (error != NULL)
6312 goto done;
6314 if (repo_path == NULL) {
6315 error = got_worktree_open(&worktree, cwd,
6316 GOT_WORKTREE_GOT_DIR);
6317 if (error && error->code != GOT_ERR_NOT_WORKTREE)
6318 goto done;
6319 else
6320 error = NULL;
6321 if (worktree) {
6322 repo_path =
6323 strdup(got_worktree_get_repo_path(worktree));
6324 if (repo_path == NULL)
6325 error = got_error_from_errno("strdup");
6326 if (error)
6327 goto done;
6328 } else {
6329 repo_path = strdup(cwd);
6330 if (repo_path == NULL) {
6331 error = got_error_from_errno("strdup");
6332 goto done;
6337 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
6338 if (error != NULL)
6339 goto done;
6341 if (worktree) {
6342 const char *prefix = got_worktree_get_path_prefix(worktree);
6343 char *p;
6345 if (path == NULL || got_path_is_root_dir(path))
6346 path = "";
6347 error = got_worktree_resolve_path(&p, worktree, path);
6348 if (error)
6349 goto done;
6350 if (asprintf(&in_repo_path, "%s%s%s", prefix,
6351 (p[0] != '\0' && !got_path_is_root_dir(prefix)) ? "/" : "",
6352 p) == -1) {
6353 error = got_error_from_errno("asprintf");
6354 free(p);
6355 goto done;
6357 free(p);
6358 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
6359 if (error)
6360 goto done;
6361 } else {
6362 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
6363 if (error)
6364 goto done;
6365 if (path == NULL)
6366 path = "/";
6367 error = got_repo_map_path(&in_repo_path, repo, path);
6368 if (error != NULL)
6369 goto done;
6372 if (commit_id_str == NULL) {
6373 struct got_reference *head_ref;
6374 if (worktree)
6375 refname = got_worktree_get_head_ref_name(worktree);
6376 else
6377 refname = GOT_REF_HEAD;
6378 error = got_ref_open(&head_ref, repo, refname, 0);
6379 if (error != NULL)
6380 goto done;
6381 error = got_ref_resolve(&commit_id, repo, head_ref);
6382 got_ref_close(head_ref);
6383 if (error != NULL)
6384 goto done;
6385 } else {
6386 struct got_reflist_head refs;
6388 TAILQ_INIT(&refs);
6389 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
6390 NULL);
6391 if (error)
6392 goto done;
6394 error = got_keyword_to_idstr(&keyword_idstr, commit_id_str,
6395 repo, worktree);
6396 if (error != NULL)
6397 goto done;
6398 if (keyword_idstr != NULL)
6399 commit_id_str = keyword_idstr;
6401 error = got_repo_match_object_id(&commit_id, NULL,
6402 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
6403 got_ref_list_free(&refs);
6404 if (error)
6405 goto done;
6408 if (worktree) {
6409 /* Release work tree lock. */
6410 got_worktree_close(worktree);
6411 worktree = NULL;
6414 error = got_object_open_as_commit(&commit, repo, commit_id);
6415 if (error)
6416 goto done;
6418 error = print_tree(in_repo_path, commit, show_ids, recurse,
6419 in_repo_path, repo);
6420 done:
6421 free(keyword_idstr);
6422 free(in_repo_path);
6423 free(repo_path);
6424 free(cwd);
6425 free(commit_id);
6426 if (commit)
6427 got_object_commit_close(commit);
6428 if (worktree)
6429 got_worktree_close(worktree);
6430 if (repo) {
6431 const struct got_error *close_err = got_repo_close(repo);
6432 if (error == NULL)
6433 error = close_err;
6435 if (pack_fds) {
6436 const struct got_error *pack_err =
6437 got_repo_pack_fds_close(pack_fds);
6438 if (error == NULL)
6439 error = pack_err;
6441 return error;
6444 __dead static void
6445 usage_status(void)
6447 fprintf(stderr, "usage: %s status [-I] [-S status-codes] "
6448 "[-s status-codes] [path ...]\n", getprogname());
6449 exit(1);
6452 struct got_status_arg {
6453 char *status_codes;
6454 int suppress;
6457 static const struct got_error *
6458 print_status(void *arg, unsigned char status, unsigned char staged_status,
6459 const char *path, struct got_object_id *blob_id,
6460 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
6461 int dirfd, const char *de_name)
6463 struct got_status_arg *st = arg;
6465 if (status == staged_status && (status == GOT_STATUS_DELETE))
6466 status = GOT_STATUS_NO_CHANGE;
6467 if (st != NULL && st->status_codes) {
6468 size_t ncodes = strlen(st->status_codes);
6469 int i, j = 0;
6471 for (i = 0; i < ncodes ; i++) {
6472 if (st->suppress) {
6473 if (status == st->status_codes[i] ||
6474 staged_status == st->status_codes[i]) {
6475 j++;
6476 continue;
6478 } else {
6479 if (status == st->status_codes[i] ||
6480 staged_status == st->status_codes[i])
6481 break;
6485 if (st->suppress && j == 0)
6486 goto print;
6488 if (i == ncodes)
6489 return NULL;
6491 print:
6492 printf("%c%c %s\n", status, staged_status, path);
6493 return NULL;
6496 static const struct got_error *
6497 show_operation_in_progress(struct got_worktree *worktree,
6498 struct got_repository *repo)
6500 const struct got_error *err;
6501 char *new_base_branch_name = NULL;
6502 char *branch_name = NULL;
6503 int rebase_in_progress, histedit_in_progress, merge_in_progress;
6505 err = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
6506 if (err)
6507 return err;
6508 if (rebase_in_progress) {
6509 err = got_worktree_rebase_info(&new_base_branch_name,
6510 &branch_name, worktree, repo);
6511 if (err)
6512 return err;
6513 printf("Work tree is rebasing %s onto %s\n",
6514 branch_name, new_base_branch_name);
6517 err = got_worktree_histedit_in_progress(&histedit_in_progress,
6518 worktree);
6519 if (err)
6520 return err;
6521 if (histedit_in_progress) {
6522 err = got_worktree_histedit_info(&branch_name, worktree, repo);
6523 if (err)
6524 return err;
6525 printf("Work tree is editing the history of %s\n", branch_name);
6528 err = got_worktree_merge_in_progress(&merge_in_progress,
6529 worktree, repo);
6530 if (err)
6531 return err;
6532 if (merge_in_progress) {
6533 err = got_worktree_merge_info(&branch_name, worktree,
6534 repo);
6535 if (err)
6536 return err;
6537 printf("Work tree is merging %s into %s\n", branch_name,
6538 got_worktree_get_head_ref_name(worktree));
6541 free(new_base_branch_name);
6542 free(branch_name);
6543 return NULL;
6546 static const struct got_error *
6547 cmd_status(int argc, char *argv[])
6549 const struct got_error *close_err, *error = NULL;
6550 struct got_repository *repo = NULL;
6551 struct got_worktree *worktree = NULL;
6552 struct got_status_arg st;
6553 char *cwd = NULL;
6554 struct got_pathlist_head paths;
6555 int ch, i, no_ignores = 0;
6556 int *pack_fds = NULL;
6558 TAILQ_INIT(&paths);
6560 memset(&st, 0, sizeof(st));
6561 st.status_codes = NULL;
6562 st.suppress = 0;
6564 #ifndef PROFILE
6565 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
6566 NULL) == -1)
6567 err(1, "pledge");
6568 #endif
6570 while ((ch = getopt(argc, argv, "IS:s:")) != -1) {
6571 switch (ch) {
6572 case 'I':
6573 no_ignores = 1;
6574 break;
6575 case 'S':
6576 if (st.status_codes != NULL && st.suppress == 0)
6577 option_conflict('S', 's');
6578 st.suppress = 1;
6579 /* fallthrough */
6580 case 's':
6581 for (i = 0; optarg[i] != '\0'; i++) {
6582 switch (optarg[i]) {
6583 case GOT_STATUS_MODIFY:
6584 case GOT_STATUS_ADD:
6585 case GOT_STATUS_DELETE:
6586 case GOT_STATUS_CONFLICT:
6587 case GOT_STATUS_MISSING:
6588 case GOT_STATUS_OBSTRUCTED:
6589 case GOT_STATUS_UNVERSIONED:
6590 case GOT_STATUS_MODE_CHANGE:
6591 case GOT_STATUS_NONEXISTENT:
6592 break;
6593 default:
6594 errx(1, "invalid status code '%c'",
6595 optarg[i]);
6598 if (ch == 's' && st.suppress)
6599 option_conflict('s', 'S');
6600 st.status_codes = optarg;
6601 break;
6602 default:
6603 usage_status();
6604 /* NOTREACHED */
6608 argc -= optind;
6609 argv += optind;
6611 cwd = getcwd(NULL, 0);
6612 if (cwd == NULL) {
6613 error = got_error_from_errno("getcwd");
6614 goto done;
6617 error = got_repo_pack_fds_open(&pack_fds);
6618 if (error != NULL)
6619 goto done;
6621 error = got_worktree_open(&worktree, cwd,
6622 GOT_WORKTREE_GOT_DIR);
6623 if (error) {
6624 if (error->code == GOT_ERR_NOT_WORKTREE)
6625 error = wrap_not_worktree_error(error, "status", cwd);
6626 goto done;
6629 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
6630 NULL, pack_fds);
6631 if (error != NULL)
6632 goto done;
6634 error = apply_unveil(got_repo_get_path(repo), 1,
6635 got_worktree_get_root_path(worktree));
6636 if (error)
6637 goto done;
6639 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
6640 if (error)
6641 goto done;
6643 error = got_worktree_status(worktree, &paths, repo, no_ignores,
6644 print_status, &st, check_cancelled, NULL);
6645 if (error)
6646 goto done;
6648 error = show_operation_in_progress(worktree, repo);
6649 done:
6650 if (pack_fds) {
6651 const struct got_error *pack_err =
6652 got_repo_pack_fds_close(pack_fds);
6653 if (error == NULL)
6654 error = pack_err;
6656 if (repo) {
6657 close_err = got_repo_close(repo);
6658 if (error == NULL)
6659 error = close_err;
6661 if (worktree != NULL) {
6662 close_err = got_worktree_close(worktree);
6663 if (error == NULL)
6664 error = close_err;
6667 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
6668 free(cwd);
6669 return error;
6672 __dead static void
6673 usage_ref(void)
6675 fprintf(stderr, "usage: %s ref [-dlt] [-c object] [-r repository-path] "
6676 "[-s reference] [name]\n", getprogname());
6677 exit(1);
6680 static const struct got_error *
6681 list_refs(struct got_repository *repo, const char *refname, int sort_by_time)
6683 static const struct got_error *err = NULL;
6684 struct got_reflist_head refs;
6685 struct got_reflist_entry *re;
6687 TAILQ_INIT(&refs);
6688 err = got_ref_list(&refs, repo, refname, sort_by_time ?
6689 got_ref_cmp_by_commit_timestamp_descending : got_ref_cmp_by_name,
6690 repo);
6691 if (err)
6692 return err;
6694 TAILQ_FOREACH(re, &refs, entry) {
6695 char *refstr;
6696 refstr = got_ref_to_str(re->ref);
6697 if (refstr == NULL) {
6698 err = got_error_from_errno("got_ref_to_str");
6699 break;
6701 printf("%s: %s\n", got_ref_get_name(re->ref), refstr);
6702 free(refstr);
6705 got_ref_list_free(&refs);
6706 return err;
6709 static const struct got_error *
6710 delete_ref_by_name(struct got_repository *repo, const char *refname)
6712 const struct got_error *err;
6713 struct got_reference *ref;
6715 err = got_ref_open(&ref, repo, refname, 0);
6716 if (err)
6717 return err;
6719 err = delete_ref(repo, ref);
6720 got_ref_close(ref);
6721 return err;
6724 static const struct got_error *
6725 add_ref(struct got_repository *repo, const char *refname, const char *target)
6727 const struct got_error *err = NULL;
6728 struct got_object_id *id = NULL;
6729 struct got_reference *ref = NULL;
6730 struct got_reflist_head refs;
6733 * Don't let the user create a reference name with a leading '-'.
6734 * While technically a valid reference name, this case is usually
6735 * an unintended typo.
6737 if (refname[0] == '-')
6738 return got_error_path(refname, GOT_ERR_REF_NAME_MINUS);
6740 TAILQ_INIT(&refs);
6741 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
6742 if (err)
6743 goto done;
6744 err = got_repo_match_object_id(&id, NULL, target, GOT_OBJ_TYPE_ANY,
6745 &refs, repo);
6746 got_ref_list_free(&refs);
6747 if (err)
6748 goto done;
6750 err = got_ref_alloc(&ref, refname, id);
6751 if (err)
6752 goto done;
6754 err = got_ref_write(ref, repo);
6755 done:
6756 if (ref)
6757 got_ref_close(ref);
6758 free(id);
6759 return err;
6762 static const struct got_error *
6763 add_symref(struct got_repository *repo, const char *refname, const char *target)
6765 const struct got_error *err = NULL;
6766 struct got_reference *ref = NULL;
6767 struct got_reference *target_ref = NULL;
6770 * Don't let the user create a reference name with a leading '-'.
6771 * While technically a valid reference name, this case is usually
6772 * an unintended typo.
6774 if (refname[0] == '-')
6775 return got_error_path(refname, GOT_ERR_REF_NAME_MINUS);
6777 err = got_ref_open(&target_ref, repo, target, 0);
6778 if (err)
6779 return err;
6781 err = got_ref_alloc_symref(&ref, refname, target_ref);
6782 if (err)
6783 goto done;
6785 err = got_ref_write(ref, repo);
6786 done:
6787 if (target_ref)
6788 got_ref_close(target_ref);
6789 if (ref)
6790 got_ref_close(ref);
6791 return err;
6794 static const struct got_error *
6795 cmd_ref(int argc, char *argv[])
6797 const struct got_error *error = NULL;
6798 struct got_repository *repo = NULL;
6799 struct got_worktree *worktree = NULL;
6800 char *cwd = NULL, *repo_path = NULL;
6801 int ch, do_list = 0, do_delete = 0, sort_by_time = 0;
6802 const char *obj_arg = NULL, *symref_target= NULL;
6803 char *refname = NULL, *keyword_idstr = NULL;
6804 int *pack_fds = NULL;
6806 #ifndef PROFILE
6807 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
6808 "sendfd unveil", NULL) == -1)
6809 err(1, "pledge");
6810 #endif
6812 while ((ch = getopt(argc, argv, "c:dlr:s:t")) != -1) {
6813 switch (ch) {
6814 case 'c':
6815 obj_arg = optarg;
6816 break;
6817 case 'd':
6818 do_delete = 1;
6819 break;
6820 case 'l':
6821 do_list = 1;
6822 break;
6823 case 'r':
6824 repo_path = realpath(optarg, NULL);
6825 if (repo_path == NULL)
6826 return got_error_from_errno2("realpath",
6827 optarg);
6828 got_path_strip_trailing_slashes(repo_path);
6829 break;
6830 case 's':
6831 symref_target = optarg;
6832 break;
6833 case 't':
6834 sort_by_time = 1;
6835 break;
6836 default:
6837 usage_ref();
6838 /* NOTREACHED */
6842 if (obj_arg && do_list)
6843 option_conflict('c', 'l');
6844 if (obj_arg && do_delete)
6845 option_conflict('c', 'd');
6846 if (obj_arg && symref_target)
6847 option_conflict('c', 's');
6848 if (symref_target && do_delete)
6849 option_conflict('s', 'd');
6850 if (symref_target && do_list)
6851 option_conflict('s', 'l');
6852 if (do_delete && do_list)
6853 option_conflict('d', 'l');
6854 if (sort_by_time && !do_list)
6855 errx(1, "-t option requires -l option");
6857 argc -= optind;
6858 argv += optind;
6860 if (do_list) {
6861 if (argc != 0 && argc != 1)
6862 usage_ref();
6863 if (argc == 1) {
6864 refname = strdup(argv[0]);
6865 if (refname == NULL) {
6866 error = got_error_from_errno("strdup");
6867 goto done;
6870 } else {
6871 if (argc != 1)
6872 usage_ref();
6873 refname = strdup(argv[0]);
6874 if (refname == NULL) {
6875 error = got_error_from_errno("strdup");
6876 goto done;
6880 if (refname)
6881 got_path_strip_trailing_slashes(refname);
6883 cwd = getcwd(NULL, 0);
6884 if (cwd == NULL) {
6885 error = got_error_from_errno("getcwd");
6886 goto done;
6889 error = got_repo_pack_fds_open(&pack_fds);
6890 if (error != NULL)
6891 goto done;
6893 if (repo_path == NULL) {
6894 error = got_worktree_open(&worktree, cwd,
6895 GOT_WORKTREE_GOT_DIR);
6896 if (error && error->code != GOT_ERR_NOT_WORKTREE)
6897 goto done;
6898 else
6899 error = NULL;
6900 if (worktree) {
6901 repo_path =
6902 strdup(got_worktree_get_repo_path(worktree));
6903 if (repo_path == NULL)
6904 error = got_error_from_errno("strdup");
6905 if (error)
6906 goto done;
6907 } else {
6908 repo_path = strdup(cwd);
6909 if (repo_path == NULL) {
6910 error = got_error_from_errno("strdup");
6911 goto done;
6916 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
6917 if (error != NULL)
6918 goto done;
6920 #ifndef PROFILE
6921 if (do_list) {
6922 /* Remove "cpath" promise. */
6923 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
6924 NULL) == -1)
6925 err(1, "pledge");
6927 #endif
6929 error = apply_unveil(got_repo_get_path(repo), do_list,
6930 worktree ? got_worktree_get_root_path(worktree) : NULL);
6931 if (error)
6932 goto done;
6934 if (do_list)
6935 error = list_refs(repo, refname, sort_by_time);
6936 else if (do_delete)
6937 error = delete_ref_by_name(repo, refname);
6938 else if (symref_target)
6939 error = add_symref(repo, refname, symref_target);
6940 else {
6941 if (obj_arg == NULL)
6942 usage_ref();
6944 error = got_keyword_to_idstr(&keyword_idstr, obj_arg,
6945 repo, worktree);
6946 if (error != NULL)
6947 goto done;
6948 if (keyword_idstr != NULL)
6949 obj_arg = keyword_idstr;
6951 error = add_ref(repo, refname, obj_arg);
6953 done:
6954 free(refname);
6955 if (repo) {
6956 const struct got_error *close_err = got_repo_close(repo);
6957 if (error == NULL)
6958 error = close_err;
6960 if (worktree)
6961 got_worktree_close(worktree);
6962 if (pack_fds) {
6963 const struct got_error *pack_err =
6964 got_repo_pack_fds_close(pack_fds);
6965 if (error == NULL)
6966 error = pack_err;
6968 free(cwd);
6969 free(repo_path);
6970 free(keyword_idstr);
6971 return error;
6974 __dead static void
6975 usage_branch(void)
6977 fprintf(stderr, "usage: %s branch [-lnt] [-c commit] [-d name] "
6978 "[-r repository-path] [name]\n", getprogname());
6979 exit(1);
6982 static const struct got_error *
6983 list_branch(struct got_repository *repo, struct got_worktree *worktree,
6984 struct got_reference *ref)
6986 const struct got_error *err = NULL;
6987 const char *refname;
6988 char *refstr;
6989 char marker = ' ';
6991 refname = got_ref_get_name(ref);
6992 if (worktree && strcmp(refname,
6993 got_worktree_get_head_ref_name(worktree)) == 0) {
6994 err = got_worktree_get_state(&marker, repo, worktree,
6995 check_cancelled, NULL);
6996 if (err != NULL)
6997 return err;
7000 if (strncmp(refname, "refs/heads/", 11) == 0)
7001 refname += 11;
7002 if (strncmp(refname, "refs/got/worktree/", 18) == 0)
7003 refname += 18;
7004 if (strncmp(refname, "refs/remotes/", 13) == 0)
7005 refname += 13;
7007 refstr = got_ref_to_str(ref);
7008 if (refstr == NULL)
7009 return got_error_from_errno("got_ref_to_str");
7011 printf("%c %s: %s\n", marker, refname, refstr);
7012 free(refstr);
7013 return NULL;
7016 static const struct got_error *
7017 show_current_branch(struct got_repository *repo, struct got_worktree *worktree)
7019 const char *refname;
7021 if (worktree == NULL)
7022 return got_error(GOT_ERR_NOT_WORKTREE);
7024 refname = got_worktree_get_head_ref_name(worktree);
7026 if (strncmp(refname, "refs/heads/", 11) == 0)
7027 refname += 11;
7028 if (strncmp(refname, "refs/got/worktree/", 18) == 0)
7029 refname += 18;
7031 printf("%s\n", refname);
7033 return NULL;
7036 static const struct got_error *
7037 list_branches(struct got_repository *repo, struct got_worktree *worktree,
7038 int sort_by_time)
7040 static const struct got_error *err = NULL;
7041 struct got_reflist_head refs;
7042 struct got_reflist_entry *re;
7043 struct got_reference *temp_ref = NULL;
7044 int rebase_in_progress, histedit_in_progress;
7046 TAILQ_INIT(&refs);
7048 if (worktree) {
7049 err = got_worktree_rebase_in_progress(&rebase_in_progress,
7050 worktree);
7051 if (err)
7052 return err;
7054 err = got_worktree_histedit_in_progress(&histedit_in_progress,
7055 worktree);
7056 if (err)
7057 return err;
7059 if (rebase_in_progress || histedit_in_progress) {
7060 err = got_ref_open(&temp_ref, repo,
7061 got_worktree_get_head_ref_name(worktree), 0);
7062 if (err)
7063 return err;
7064 list_branch(repo, worktree, temp_ref);
7065 got_ref_close(temp_ref);
7069 err = got_ref_list(&refs, repo, "refs/heads", sort_by_time ?
7070 got_ref_cmp_by_commit_timestamp_descending : got_ref_cmp_by_name,
7071 repo);
7072 if (err)
7073 return err;
7075 TAILQ_FOREACH(re, &refs, entry)
7076 list_branch(repo, worktree, re->ref);
7078 got_ref_list_free(&refs);
7080 err = got_ref_list(&refs, repo, "refs/remotes", sort_by_time ?
7081 got_ref_cmp_by_commit_timestamp_descending : got_ref_cmp_by_name,
7082 repo);
7083 if (err)
7084 return err;
7086 TAILQ_FOREACH(re, &refs, entry)
7087 list_branch(repo, worktree, re->ref);
7089 got_ref_list_free(&refs);
7091 return NULL;
7094 static const struct got_error *
7095 delete_branch(struct got_repository *repo, struct got_worktree *worktree,
7096 const char *branch_name)
7098 const struct got_error *err = NULL;
7099 struct got_reference *ref = NULL;
7100 char *refname, *remote_refname = NULL;
7102 if (strncmp(branch_name, "refs/", 5) == 0)
7103 branch_name += 5;
7104 if (strncmp(branch_name, "heads/", 6) == 0)
7105 branch_name += 6;
7106 else if (strncmp(branch_name, "remotes/", 8) == 0)
7107 branch_name += 8;
7109 if (asprintf(&refname, "refs/heads/%s", branch_name) == -1)
7110 return got_error_from_errno("asprintf");
7112 if (asprintf(&remote_refname, "refs/remotes/%s",
7113 branch_name) == -1) {
7114 err = got_error_from_errno("asprintf");
7115 goto done;
7118 err = got_ref_open(&ref, repo, refname, 0);
7119 if (err) {
7120 const struct got_error *err2;
7121 if (err->code != GOT_ERR_NOT_REF)
7122 goto done;
7124 * Keep 'err' intact such that if neither branch exists
7125 * we report "refs/heads" rather than "refs/remotes" in
7126 * our error message.
7128 err2 = got_ref_open(&ref, repo, remote_refname, 0);
7129 if (err2)
7130 goto done;
7131 err = NULL;
7134 if (worktree &&
7135 strcmp(got_worktree_get_head_ref_name(worktree),
7136 got_ref_get_name(ref)) == 0) {
7137 err = got_error_msg(GOT_ERR_SAME_BRANCH,
7138 "will not delete this work tree's current branch");
7139 goto done;
7142 err = delete_ref(repo, ref);
7143 done:
7144 if (ref)
7145 got_ref_close(ref);
7146 free(refname);
7147 free(remote_refname);
7148 return err;
7151 static const struct got_error *
7152 add_branch(struct got_repository *repo, const char *branch_name,
7153 struct got_object_id *base_commit_id)
7155 const struct got_error *err = NULL;
7156 struct got_reference *ref = NULL;
7157 char *refname = NULL;
7160 * Don't let the user create a branch name with a leading '-'.
7161 * While technically a valid reference name, this case is usually
7162 * an unintended typo.
7164 if (branch_name[0] == '-')
7165 return got_error_path(branch_name, GOT_ERR_REF_NAME_MINUS);
7167 if (strncmp(branch_name, "refs/heads/", 11) == 0)
7168 branch_name += 11;
7170 if (asprintf(&refname, "refs/heads/%s", branch_name) == -1) {
7171 err = got_error_from_errno("asprintf");
7172 goto done;
7175 err = got_ref_open(&ref, repo, refname, 0);
7176 if (err == NULL) {
7177 err = got_error(GOT_ERR_BRANCH_EXISTS);
7178 goto done;
7179 } else if (err->code != GOT_ERR_NOT_REF)
7180 goto done;
7182 err = got_ref_alloc(&ref, refname, base_commit_id);
7183 if (err)
7184 goto done;
7186 err = got_ref_write(ref, repo);
7187 done:
7188 if (ref)
7189 got_ref_close(ref);
7190 free(refname);
7191 return err;
7194 static const struct got_error *
7195 cmd_branch(int argc, char *argv[])
7197 const struct got_error *error = NULL;
7198 struct got_repository *repo = NULL;
7199 struct got_worktree *worktree = NULL;
7200 char *cwd = NULL, *repo_path = NULL;
7201 int ch, do_list = 0, do_show = 0, do_update = 1, sort_by_time = 0;
7202 const char *delref = NULL, *commit_id_arg = NULL;
7203 struct got_reference *ref = NULL;
7204 struct got_pathlist_head paths;
7205 struct got_object_id *commit_id = NULL;
7206 char *commit_id_str = NULL, *keyword_idstr = NULL;;
7207 int *pack_fds = NULL;
7209 TAILQ_INIT(&paths);
7211 #ifndef PROFILE
7212 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
7213 "sendfd unveil", NULL) == -1)
7214 err(1, "pledge");
7215 #endif
7217 while ((ch = getopt(argc, argv, "c:d:lnr:t")) != -1) {
7218 switch (ch) {
7219 case 'c':
7220 commit_id_arg = optarg;
7221 break;
7222 case 'd':
7223 delref = optarg;
7224 break;
7225 case 'l':
7226 do_list = 1;
7227 break;
7228 case 'n':
7229 do_update = 0;
7230 break;
7231 case 'r':
7232 repo_path = realpath(optarg, NULL);
7233 if (repo_path == NULL)
7234 return got_error_from_errno2("realpath",
7235 optarg);
7236 got_path_strip_trailing_slashes(repo_path);
7237 break;
7238 case 't':
7239 sort_by_time = 1;
7240 break;
7241 default:
7242 usage_branch();
7243 /* NOTREACHED */
7247 if (do_list && delref)
7248 option_conflict('l', 'd');
7249 if (sort_by_time && !do_list)
7250 errx(1, "-t option requires -l option");
7252 argc -= optind;
7253 argv += optind;
7255 if (!do_list && !delref && argc == 0)
7256 do_show = 1;
7258 if ((do_list || delref || do_show) && commit_id_arg != NULL)
7259 errx(1, "-c option can only be used when creating a branch");
7261 if (do_list || delref) {
7262 if (argc > 0)
7263 usage_branch();
7264 } else if (!do_show && argc != 1)
7265 usage_branch();
7267 cwd = getcwd(NULL, 0);
7268 if (cwd == NULL) {
7269 error = got_error_from_errno("getcwd");
7270 goto done;
7273 error = got_repo_pack_fds_open(&pack_fds);
7274 if (error != NULL)
7275 goto done;
7277 if (repo_path == NULL) {
7278 error = got_worktree_open(&worktree, cwd,
7279 GOT_WORKTREE_GOT_DIR);
7280 if (error && error->code != GOT_ERR_NOT_WORKTREE)
7281 goto done;
7282 else
7283 error = NULL;
7284 if (worktree) {
7285 repo_path =
7286 strdup(got_worktree_get_repo_path(worktree));
7287 if (repo_path == NULL)
7288 error = got_error_from_errno("strdup");
7289 if (error)
7290 goto done;
7291 } else {
7292 repo_path = strdup(cwd);
7293 if (repo_path == NULL) {
7294 error = got_error_from_errno("strdup");
7295 goto done;
7300 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
7301 if (error != NULL)
7302 goto done;
7304 #ifndef PROFILE
7305 if (do_list || do_show) {
7306 /* Remove "cpath" promise. */
7307 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
7308 NULL) == -1)
7309 err(1, "pledge");
7311 #endif
7313 error = apply_unveil(got_repo_get_path(repo), do_list,
7314 worktree ? got_worktree_get_root_path(worktree) : NULL);
7315 if (error)
7316 goto done;
7318 if (do_show)
7319 error = show_current_branch(repo, worktree);
7320 else if (do_list)
7321 error = list_branches(repo, worktree, sort_by_time);
7322 else if (delref)
7323 error = delete_branch(repo, worktree, delref);
7324 else {
7325 struct got_reflist_head refs;
7326 TAILQ_INIT(&refs);
7327 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
7328 NULL);
7329 if (error)
7330 goto done;
7331 if (commit_id_arg == NULL)
7332 commit_id_arg = worktree ?
7333 got_worktree_get_head_ref_name(worktree) :
7334 GOT_REF_HEAD;
7335 else {
7336 error = got_keyword_to_idstr(&keyword_idstr,
7337 commit_id_arg, repo, worktree);
7338 if (error != NULL)
7339 goto done;
7340 if (keyword_idstr != NULL)
7341 commit_id_arg = keyword_idstr;
7343 error = got_repo_match_object_id(&commit_id, NULL,
7344 commit_id_arg, GOT_OBJ_TYPE_COMMIT, &refs, repo);
7345 got_ref_list_free(&refs);
7346 if (error)
7347 goto done;
7348 error = add_branch(repo, argv[0], commit_id);
7349 if (error)
7350 goto done;
7351 if (worktree && do_update) {
7352 struct got_update_progress_arg upa;
7353 char *branch_refname = NULL;
7355 error = got_object_id_str(&commit_id_str, commit_id);
7356 if (error)
7357 goto done;
7358 error = get_worktree_paths_from_argv(&paths, 0, NULL,
7359 worktree);
7360 if (error)
7361 goto done;
7362 if (asprintf(&branch_refname, "refs/heads/%s", argv[0])
7363 == -1) {
7364 error = got_error_from_errno("asprintf");
7365 goto done;
7367 error = got_ref_open(&ref, repo, branch_refname, 0);
7368 free(branch_refname);
7369 if (error)
7370 goto done;
7371 error = switch_head_ref(ref, commit_id, worktree,
7372 repo);
7373 if (error)
7374 goto done;
7375 error = got_worktree_set_base_commit_id(worktree, repo,
7376 commit_id);
7377 if (error)
7378 goto done;
7379 memset(&upa, 0, sizeof(upa));
7380 error = got_worktree_checkout_files(worktree, &paths,
7381 repo, update_progress, &upa, check_cancelled,
7382 NULL);
7383 if (error)
7384 goto done;
7385 if (upa.did_something) {
7386 printf("Updated to %s: %s\n",
7387 got_worktree_get_head_ref_name(worktree),
7388 commit_id_str);
7390 print_update_progress_stats(&upa);
7393 done:
7394 free(keyword_idstr);
7395 if (ref)
7396 got_ref_close(ref);
7397 if (repo) {
7398 const struct got_error *close_err = got_repo_close(repo);
7399 if (error == NULL)
7400 error = close_err;
7402 if (worktree)
7403 got_worktree_close(worktree);
7404 if (pack_fds) {
7405 const struct got_error *pack_err =
7406 got_repo_pack_fds_close(pack_fds);
7407 if (error == NULL)
7408 error = pack_err;
7410 free(cwd);
7411 free(repo_path);
7412 free(commit_id);
7413 free(commit_id_str);
7414 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
7415 return error;
7419 __dead static void
7420 usage_tag(void)
7422 fprintf(stderr, "usage: %s tag [-lVv] [-c commit] [-m message] "
7423 "[-r repository-path] [-s signer-id] name\n", getprogname());
7424 exit(1);
7427 #if 0
7428 static const struct got_error *
7429 sort_tags(struct got_reflist_head *sorted, struct got_reflist_head *tags)
7431 const struct got_error *err = NULL;
7432 struct got_reflist_entry *re, *se, *new;
7433 struct got_object_id *re_id, *se_id;
7434 struct got_tag_object *re_tag, *se_tag;
7435 time_t re_time, se_time;
7437 STAILQ_FOREACH(re, tags, entry) {
7438 se = STAILQ_FIRST(sorted);
7439 if (se == NULL) {
7440 err = got_reflist_entry_dup(&new, re);
7441 if (err)
7442 return err;
7443 STAILQ_INSERT_HEAD(sorted, new, entry);
7444 continue;
7445 } else {
7446 err = got_ref_resolve(&re_id, repo, re->ref);
7447 if (err)
7448 break;
7449 err = got_object_open_as_tag(&re_tag, repo, re_id);
7450 free(re_id);
7451 if (err)
7452 break;
7453 re_time = got_object_tag_get_tagger_time(re_tag);
7454 got_object_tag_close(re_tag);
7457 while (se) {
7458 err = got_ref_resolve(&se_id, repo, re->ref);
7459 if (err)
7460 break;
7461 err = got_object_open_as_tag(&se_tag, repo, se_id);
7462 free(se_id);
7463 if (err)
7464 break;
7465 se_time = got_object_tag_get_tagger_time(se_tag);
7466 got_object_tag_close(se_tag);
7468 if (se_time > re_time) {
7469 err = got_reflist_entry_dup(&new, re);
7470 if (err)
7471 return err;
7472 STAILQ_INSERT_AFTER(sorted, se, new, entry);
7473 break;
7475 se = STAILQ_NEXT(se, entry);
7476 continue;
7479 done:
7480 return err;
7482 #endif
7484 static const struct got_error *
7485 get_tag_refname(char **refname, const char *tag_name)
7487 const struct got_error *err;
7489 if (strncmp("refs/tags/", tag_name, 10) == 0) {
7490 *refname = strdup(tag_name);
7491 if (*refname == NULL)
7492 return got_error_from_errno("strdup");
7493 } else if (asprintf(refname, "refs/tags/%s", tag_name) == -1) {
7494 err = got_error_from_errno("asprintf");
7495 *refname = NULL;
7496 return err;
7499 return NULL;
7502 static const struct got_error *
7503 list_tags(struct got_repository *repo, const char *tag_name, int verify_tags,
7504 const char *allowed_signers, const char *revoked_signers, int verbosity)
7506 static const struct got_error *err = NULL;
7507 struct got_reflist_head refs;
7508 struct got_reflist_entry *re;
7509 char *wanted_refname = NULL;
7510 int bad_sigs = 0;
7512 TAILQ_INIT(&refs);
7514 err = got_ref_list(&refs, repo, "refs/tags", got_ref_cmp_tags, repo);
7515 if (err)
7516 return err;
7518 if (tag_name) {
7519 struct got_reference *ref;
7520 err = get_tag_refname(&wanted_refname, tag_name);
7521 if (err)
7522 goto done;
7523 /* Wanted tag reference should exist. */
7524 err = got_ref_open(&ref, repo, wanted_refname, 0);
7525 if (err)
7526 goto done;
7527 got_ref_close(ref);
7530 TAILQ_FOREACH(re, &refs, entry) {
7531 const char *refname;
7532 char *refstr, *tagmsg0, *tagmsg, *line, *id_str, *datestr;
7533 char datebuf[26];
7534 const char *tagger, *ssh_sig = NULL;
7535 char *sig_msg = NULL;
7536 time_t tagger_time;
7537 struct got_object_id *id;
7538 struct got_tag_object *tag;
7539 struct got_commit_object *commit = NULL;
7541 refname = got_ref_get_name(re->ref);
7542 if (strncmp(refname, "refs/tags/", 10) != 0 ||
7543 (wanted_refname && strcmp(refname, wanted_refname) != 0))
7544 continue;
7545 refname += 10;
7546 refstr = got_ref_to_str(re->ref);
7547 if (refstr == NULL) {
7548 err = got_error_from_errno("got_ref_to_str");
7549 break;
7552 err = got_ref_resolve(&id, repo, re->ref);
7553 if (err)
7554 break;
7555 err = got_object_open_as_tag(&tag, repo, id);
7556 if (err) {
7557 if (err->code != GOT_ERR_OBJ_TYPE) {
7558 free(id);
7559 break;
7561 /* "lightweight" tag */
7562 err = got_object_open_as_commit(&commit, repo, id);
7563 if (err) {
7564 free(id);
7565 break;
7567 tagger = got_object_commit_get_committer(commit);
7568 tagger_time =
7569 got_object_commit_get_committer_time(commit);
7570 err = got_object_id_str(&id_str, id);
7571 free(id);
7572 if (err)
7573 break;
7574 } else {
7575 free(id);
7576 tagger = got_object_tag_get_tagger(tag);
7577 tagger_time = got_object_tag_get_tagger_time(tag);
7578 err = got_object_id_str(&id_str,
7579 got_object_tag_get_object_id(tag));
7580 if (err)
7581 break;
7584 if (tag && verify_tags) {
7585 ssh_sig = got_sigs_get_tagmsg_ssh_signature(
7586 got_object_tag_get_message(tag));
7587 if (ssh_sig && allowed_signers == NULL) {
7588 err = got_error_msg(
7589 GOT_ERR_VERIFY_TAG_SIGNATURE,
7590 "SSH signature verification requires "
7591 "setting allowed_signers in "
7592 "got.conf(5)");
7593 break;
7597 printf("%stag %s %s\n", GOT_COMMIT_SEP_STR, refname, refstr);
7598 free(refstr);
7599 printf("from: %s\n", tagger);
7600 datestr = get_datestr(&tagger_time, datebuf);
7601 if (datestr)
7602 printf("date: %s UTC\n", datestr);
7603 if (commit)
7604 printf("object: %s %s\n", GOT_OBJ_LABEL_COMMIT, id_str);
7605 else {
7606 switch (got_object_tag_get_object_type(tag)) {
7607 case GOT_OBJ_TYPE_BLOB:
7608 printf("object: %s %s\n", GOT_OBJ_LABEL_BLOB,
7609 id_str);
7610 break;
7611 case GOT_OBJ_TYPE_TREE:
7612 printf("object: %s %s\n", GOT_OBJ_LABEL_TREE,
7613 id_str);
7614 break;
7615 case GOT_OBJ_TYPE_COMMIT:
7616 printf("object: %s %s\n", GOT_OBJ_LABEL_COMMIT,
7617 id_str);
7618 break;
7619 case GOT_OBJ_TYPE_TAG:
7620 printf("object: %s %s\n", GOT_OBJ_LABEL_TAG,
7621 id_str);
7622 break;
7623 default:
7624 break;
7627 free(id_str);
7629 if (ssh_sig) {
7630 err = got_sigs_verify_tag_ssh(&sig_msg, tag, ssh_sig,
7631 allowed_signers, revoked_signers, verbosity);
7632 if (err && err->code == GOT_ERR_BAD_TAG_SIGNATURE)
7633 bad_sigs = 1;
7634 else if (err)
7635 break;
7636 printf("signature: %s", sig_msg);
7637 free(sig_msg);
7638 sig_msg = NULL;
7641 if (commit) {
7642 err = got_object_commit_get_logmsg(&tagmsg0, commit);
7643 if (err)
7644 break;
7645 got_object_commit_close(commit);
7646 } else {
7647 tagmsg0 = strdup(got_object_tag_get_message(tag));
7648 got_object_tag_close(tag);
7649 if (tagmsg0 == NULL) {
7650 err = got_error_from_errno("strdup");
7651 break;
7655 tagmsg = tagmsg0;
7656 do {
7657 line = strsep(&tagmsg, "\n");
7658 if (line)
7659 printf(" %s\n", line);
7660 } while (line);
7661 free(tagmsg0);
7663 done:
7664 got_ref_list_free(&refs);
7665 free(wanted_refname);
7667 if (err == NULL && bad_sigs)
7668 err = got_error(GOT_ERR_BAD_TAG_SIGNATURE);
7669 return err;
7672 static const struct got_error *
7673 get_tag_message(char **tagmsg, char **tagmsg_path, const char *commit_id_str,
7674 const char *tag_name, const char *editor, const char *repo_path)
7676 const struct got_error *err = NULL;
7677 char *template = NULL, *initial_content = NULL;
7678 int initial_content_len;
7679 int fd = -1;
7681 if (asprintf(&template, GOT_TMPDIR_STR "/got-tagmsg") == -1) {
7682 err = got_error_from_errno("asprintf");
7683 goto done;
7686 initial_content_len = asprintf(&initial_content,
7687 "\n# tagging commit %s as %s\n",
7688 commit_id_str, tag_name);
7689 if (initial_content_len == -1) {
7690 err = got_error_from_errno("asprintf");
7691 goto done;
7694 err = got_opentemp_named_fd(tagmsg_path, &fd, template, "");
7695 if (err)
7696 goto done;
7698 if (write(fd, initial_content, initial_content_len) == -1) {
7699 err = got_error_from_errno2("write", *tagmsg_path);
7700 goto done;
7702 if (close(fd) == -1) {
7703 err = got_error_from_errno2("close", *tagmsg_path);
7704 goto done;
7706 fd = -1;
7708 err = edit_logmsg(tagmsg, editor, *tagmsg_path, initial_content,
7709 initial_content_len, 1);
7710 done:
7711 free(initial_content);
7712 free(template);
7714 if (fd != -1 && close(fd) == -1 && err == NULL)
7715 err = got_error_from_errno2("close", *tagmsg_path);
7717 if (err) {
7718 free(*tagmsg);
7719 *tagmsg = NULL;
7721 return err;
7724 static const struct got_error *
7725 add_tag(struct got_repository *repo, const char *tagger,
7726 const char *tag_name, const char *commit_arg, const char *tagmsg_arg,
7727 const char *signer_id, const char *editor, int verbosity)
7729 const struct got_error *err = NULL;
7730 struct got_object_id *commit_id = NULL, *tag_id = NULL;
7731 char *label = NULL, *commit_id_str = NULL;
7732 struct got_reference *ref = NULL;
7733 char *refname = NULL, *tagmsg = NULL;
7734 char *tagmsg_path = NULL, *tag_id_str = NULL;
7735 int preserve_tagmsg = 0;
7736 struct got_reflist_head refs;
7738 TAILQ_INIT(&refs);
7741 * Don't let the user create a tag name with a leading '-'.
7742 * While technically a valid reference name, this case is usually
7743 * an unintended typo.
7745 if (tag_name[0] == '-')
7746 return got_error_path(tag_name, GOT_ERR_REF_NAME_MINUS);
7748 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
7749 if (err)
7750 goto done;
7752 err = got_repo_match_object_id(&commit_id, &label, commit_arg,
7753 GOT_OBJ_TYPE_COMMIT, &refs, repo);
7754 if (err)
7755 goto done;
7757 err = got_object_id_str(&commit_id_str, commit_id);
7758 if (err)
7759 goto done;
7761 err = get_tag_refname(&refname, tag_name);
7762 if (err)
7763 goto done;
7764 if (strncmp("refs/tags/", tag_name, 10) == 0)
7765 tag_name += 10;
7767 err = got_ref_open(&ref, repo, refname, 0);
7768 if (err == NULL) {
7769 err = got_error(GOT_ERR_TAG_EXISTS);
7770 goto done;
7771 } else if (err->code != GOT_ERR_NOT_REF)
7772 goto done;
7774 if (tagmsg_arg == NULL) {
7775 err = get_tag_message(&tagmsg, &tagmsg_path, commit_id_str,
7776 tag_name, editor, got_repo_get_path(repo));
7777 if (err) {
7778 if (err->code != GOT_ERR_COMMIT_MSG_EMPTY &&
7779 tagmsg_path != NULL)
7780 preserve_tagmsg = 1;
7781 goto done;
7785 err = got_object_tag_create(&tag_id, tag_name, commit_id,
7786 tagger, time(NULL), tagmsg ? tagmsg : tagmsg_arg, signer_id, repo,
7787 verbosity);
7788 if (err) {
7789 if (tagmsg_path)
7790 preserve_tagmsg = 1;
7791 goto done;
7794 err = got_ref_alloc(&ref, refname, tag_id);
7795 if (err) {
7796 if (tagmsg_path)
7797 preserve_tagmsg = 1;
7798 goto done;
7801 err = got_ref_write(ref, repo);
7802 if (err) {
7803 if (tagmsg_path)
7804 preserve_tagmsg = 1;
7805 goto done;
7808 err = got_object_id_str(&tag_id_str, tag_id);
7809 if (err) {
7810 if (tagmsg_path)
7811 preserve_tagmsg = 1;
7812 goto done;
7814 printf("Created tag %s\n", tag_id_str);
7815 done:
7816 if (preserve_tagmsg) {
7817 fprintf(stderr, "%s: tag message preserved in %s\n",
7818 getprogname(), tagmsg_path);
7819 } else if (tagmsg_path && unlink(tagmsg_path) == -1 && err == NULL)
7820 err = got_error_from_errno2("unlink", tagmsg_path);
7821 free(tag_id_str);
7822 if (ref)
7823 got_ref_close(ref);
7824 free(commit_id);
7825 free(commit_id_str);
7826 free(refname);
7827 free(tagmsg);
7828 free(tagmsg_path);
7829 got_ref_list_free(&refs);
7830 return err;
7833 static const struct got_error *
7834 cmd_tag(int argc, char *argv[])
7836 const struct got_error *error = NULL;
7837 struct got_repository *repo = NULL;
7838 struct got_worktree *worktree = NULL;
7839 char *cwd = NULL, *repo_path = NULL, *commit_id_str = NULL;
7840 char *gitconfig_path = NULL, *tagger = NULL, *keyword_idstr = NULL;
7841 char *allowed_signers = NULL, *revoked_signers = NULL, *editor = NULL;
7842 const char *signer_id = NULL;
7843 const char *tag_name = NULL, *commit_id_arg = NULL, *tagmsg = NULL;
7844 int ch, do_list = 0, verify_tags = 0, verbosity = 0;
7845 int *pack_fds = NULL;
7847 #ifndef PROFILE
7848 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
7849 "sendfd unveil", NULL) == -1)
7850 err(1, "pledge");
7851 #endif
7853 while ((ch = getopt(argc, argv, "c:lm:r:s:Vv")) != -1) {
7854 switch (ch) {
7855 case 'c':
7856 commit_id_arg = optarg;
7857 break;
7858 case 'l':
7859 do_list = 1;
7860 break;
7861 case 'm':
7862 tagmsg = optarg;
7863 break;
7864 case 'r':
7865 repo_path = realpath(optarg, NULL);
7866 if (repo_path == NULL) {
7867 error = got_error_from_errno2("realpath",
7868 optarg);
7869 goto done;
7871 got_path_strip_trailing_slashes(repo_path);
7872 break;
7873 case 's':
7874 signer_id = optarg;
7875 break;
7876 case 'V':
7877 verify_tags = 1;
7878 break;
7879 case 'v':
7880 if (verbosity < 0)
7881 verbosity = 0;
7882 else if (verbosity < 3)
7883 verbosity++;
7884 break;
7885 default:
7886 usage_tag();
7887 /* NOTREACHED */
7891 argc -= optind;
7892 argv += optind;
7894 if (do_list || verify_tags) {
7895 if (commit_id_arg != NULL)
7896 errx(1,
7897 "-c option can only be used when creating a tag");
7898 if (tagmsg) {
7899 if (do_list)
7900 option_conflict('l', 'm');
7901 else
7902 option_conflict('V', 'm');
7904 if (signer_id) {
7905 if (do_list)
7906 option_conflict('l', 's');
7907 else
7908 option_conflict('V', 's');
7910 if (argc > 1)
7911 usage_tag();
7912 } else if (argc != 1)
7913 usage_tag();
7915 if (argc == 1)
7916 tag_name = argv[0];
7918 cwd = getcwd(NULL, 0);
7919 if (cwd == NULL) {
7920 error = got_error_from_errno("getcwd");
7921 goto done;
7924 error = got_repo_pack_fds_open(&pack_fds);
7925 if (error != NULL)
7926 goto done;
7928 if (repo_path == NULL) {
7929 error = got_worktree_open(&worktree, cwd,
7930 GOT_WORKTREE_GOT_DIR);
7931 if (error && error->code != GOT_ERR_NOT_WORKTREE)
7932 goto done;
7933 else
7934 error = NULL;
7935 if (worktree) {
7936 repo_path =
7937 strdup(got_worktree_get_repo_path(worktree));
7938 if (repo_path == NULL)
7939 error = got_error_from_errno("strdup");
7940 if (error)
7941 goto done;
7942 } else {
7943 repo_path = strdup(cwd);
7944 if (repo_path == NULL) {
7945 error = got_error_from_errno("strdup");
7946 goto done;
7951 if (do_list || verify_tags) {
7952 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
7953 if (error != NULL)
7954 goto done;
7955 error = get_allowed_signers(&allowed_signers, repo, worktree);
7956 if (error)
7957 goto done;
7958 error = get_revoked_signers(&revoked_signers, repo, worktree);
7959 if (error)
7960 goto done;
7961 if (worktree) {
7962 /* Release work tree lock. */
7963 got_worktree_close(worktree);
7964 worktree = NULL;
7968 * Remove "cpath" promise unless needed for signature tmpfile
7969 * creation.
7971 if (verify_tags)
7972 got_sigs_apply_unveil();
7973 else {
7974 #ifndef PROFILE
7975 if (pledge("stdio rpath wpath flock proc exec sendfd "
7976 "unveil", NULL) == -1)
7977 err(1, "pledge");
7978 #endif
7980 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
7981 if (error)
7982 goto done;
7983 error = list_tags(repo, tag_name, verify_tags, allowed_signers,
7984 revoked_signers, verbosity);
7985 } else {
7986 error = get_gitconfig_path(&gitconfig_path);
7987 if (error)
7988 goto done;
7989 error = got_repo_open(&repo, repo_path, gitconfig_path,
7990 pack_fds);
7991 if (error != NULL)
7992 goto done;
7994 error = get_author(&tagger, repo, worktree);
7995 if (error)
7996 goto done;
7997 if (signer_id == NULL)
7998 signer_id = get_signer_id(repo, worktree);
8000 if (tagmsg == NULL) {
8001 error = get_editor(&editor);
8002 if (error)
8003 goto done;
8004 if (unveil(editor, "x") != 0) {
8005 error = got_error_from_errno2("unveil", editor);
8006 goto done;
8009 if (signer_id) {
8010 error = got_sigs_apply_unveil();
8011 if (error)
8012 goto done;
8014 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
8015 if (error)
8016 goto done;
8018 if (commit_id_arg == NULL) {
8019 struct got_reference *head_ref;
8020 struct got_object_id *commit_id;
8021 error = got_ref_open(&head_ref, repo,
8022 worktree ? got_worktree_get_head_ref_name(worktree)
8023 : GOT_REF_HEAD, 0);
8024 if (error)
8025 goto done;
8026 error = got_ref_resolve(&commit_id, repo, head_ref);
8027 got_ref_close(head_ref);
8028 if (error)
8029 goto done;
8030 error = got_object_id_str(&commit_id_str, commit_id);
8031 free(commit_id);
8032 if (error)
8033 goto done;
8034 } else {
8035 error = got_keyword_to_idstr(&keyword_idstr,
8036 commit_id_arg, repo, worktree);
8037 if (error != NULL)
8038 goto done;
8039 commit_id_str = keyword_idstr;
8042 if (worktree) {
8043 /* Release work tree lock. */
8044 got_worktree_close(worktree);
8045 worktree = NULL;
8048 error = add_tag(repo, tagger, tag_name,
8049 commit_id_str ? commit_id_str : commit_id_arg, tagmsg,
8050 signer_id, editor, verbosity);
8052 done:
8053 if (repo) {
8054 const struct got_error *close_err = got_repo_close(repo);
8055 if (error == NULL)
8056 error = close_err;
8058 if (worktree)
8059 got_worktree_close(worktree);
8060 if (pack_fds) {
8061 const struct got_error *pack_err =
8062 got_repo_pack_fds_close(pack_fds);
8063 if (error == NULL)
8064 error = pack_err;
8066 free(cwd);
8067 free(editor);
8068 free(repo_path);
8069 free(gitconfig_path);
8070 free(commit_id_str);
8071 free(tagger);
8072 free(allowed_signers);
8073 free(revoked_signers);
8074 return error;
8077 __dead static void
8078 usage_add(void)
8080 fprintf(stderr, "usage: %s add [-IR] path ...\n", getprogname());
8081 exit(1);
8084 static const struct got_error *
8085 add_progress(void *arg, unsigned char status, const char *path)
8087 while (path[0] == '/')
8088 path++;
8089 printf("%c %s\n", status, path);
8090 return NULL;
8093 static const struct got_error *
8094 cmd_add(int argc, char *argv[])
8096 const struct got_error *error = NULL;
8097 struct got_repository *repo = NULL;
8098 struct got_worktree *worktree = NULL;
8099 char *cwd = NULL;
8100 struct got_pathlist_head paths;
8101 struct got_pathlist_entry *pe;
8102 int ch, can_recurse = 0, no_ignores = 0;
8103 int *pack_fds = NULL;
8105 TAILQ_INIT(&paths);
8107 #ifndef PROFILE
8108 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
8109 NULL) == -1)
8110 err(1, "pledge");
8111 #endif
8113 while ((ch = getopt(argc, argv, "IR")) != -1) {
8114 switch (ch) {
8115 case 'I':
8116 no_ignores = 1;
8117 break;
8118 case 'R':
8119 can_recurse = 1;
8120 break;
8121 default:
8122 usage_add();
8123 /* NOTREACHED */
8127 argc -= optind;
8128 argv += optind;
8130 if (argc < 1)
8131 usage_add();
8133 cwd = getcwd(NULL, 0);
8134 if (cwd == NULL) {
8135 error = got_error_from_errno("getcwd");
8136 goto done;
8139 error = got_repo_pack_fds_open(&pack_fds);
8140 if (error != NULL)
8141 goto done;
8143 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
8144 if (error) {
8145 if (error->code == GOT_ERR_NOT_WORKTREE)
8146 error = wrap_not_worktree_error(error, "add", cwd);
8147 goto done;
8150 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
8151 NULL, pack_fds);
8152 if (error != NULL)
8153 goto done;
8155 error = apply_unveil(got_repo_get_path(repo), 1,
8156 got_worktree_get_root_path(worktree));
8157 if (error)
8158 goto done;
8160 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
8161 if (error)
8162 goto done;
8164 if (!can_recurse) {
8165 char *ondisk_path;
8166 struct stat sb;
8167 TAILQ_FOREACH(pe, &paths, entry) {
8168 if (asprintf(&ondisk_path, "%s/%s",
8169 got_worktree_get_root_path(worktree),
8170 pe->path) == -1) {
8171 error = got_error_from_errno("asprintf");
8172 goto done;
8174 if (lstat(ondisk_path, &sb) == -1) {
8175 if (errno == ENOENT) {
8176 free(ondisk_path);
8177 continue;
8179 error = got_error_from_errno2("lstat",
8180 ondisk_path);
8181 free(ondisk_path);
8182 goto done;
8184 free(ondisk_path);
8185 if (S_ISDIR(sb.st_mode)) {
8186 error = got_error_msg(GOT_ERR_BAD_PATH,
8187 "adding directories requires -R option");
8188 goto done;
8193 error = got_worktree_schedule_add(worktree, &paths, add_progress,
8194 NULL, repo, no_ignores);
8195 done:
8196 if (repo) {
8197 const struct got_error *close_err = got_repo_close(repo);
8198 if (error == NULL)
8199 error = close_err;
8201 if (worktree)
8202 got_worktree_close(worktree);
8203 if (pack_fds) {
8204 const struct got_error *pack_err =
8205 got_repo_pack_fds_close(pack_fds);
8206 if (error == NULL)
8207 error = pack_err;
8209 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
8210 free(cwd);
8211 return error;
8214 __dead static void
8215 usage_remove(void)
8217 fprintf(stderr, "usage: %s remove [-fkR] [-s status-codes] path ...\n",
8218 getprogname());
8219 exit(1);
8222 static const struct got_error *
8223 print_remove_status(void *arg, unsigned char status,
8224 unsigned char staged_status, const char *path)
8226 while (path[0] == '/')
8227 path++;
8228 if (status == GOT_STATUS_NONEXISTENT)
8229 return NULL;
8230 if (status == staged_status && (status == GOT_STATUS_DELETE))
8231 status = GOT_STATUS_NO_CHANGE;
8232 printf("%c%c %s\n", status, staged_status, path);
8233 return NULL;
8236 static const struct got_error *
8237 cmd_remove(int argc, char *argv[])
8239 const struct got_error *error = NULL;
8240 struct got_worktree *worktree = NULL;
8241 struct got_repository *repo = NULL;
8242 const char *status_codes = NULL;
8243 char *cwd = NULL;
8244 struct got_pathlist_head paths;
8245 struct got_pathlist_entry *pe;
8246 int ch, delete_local_mods = 0, can_recurse = 0, keep_on_disk = 0, i;
8247 int ignore_missing_paths = 0;
8248 int *pack_fds = NULL;
8250 TAILQ_INIT(&paths);
8252 #ifndef PROFILE
8253 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
8254 NULL) == -1)
8255 err(1, "pledge");
8256 #endif
8258 while ((ch = getopt(argc, argv, "fkRs:")) != -1) {
8259 switch (ch) {
8260 case 'f':
8261 delete_local_mods = 1;
8262 ignore_missing_paths = 1;
8263 break;
8264 case 'k':
8265 keep_on_disk = 1;
8266 break;
8267 case 'R':
8268 can_recurse = 1;
8269 break;
8270 case 's':
8271 for (i = 0; optarg[i] != '\0'; i++) {
8272 switch (optarg[i]) {
8273 case GOT_STATUS_MODIFY:
8274 delete_local_mods = 1;
8275 break;
8276 case GOT_STATUS_MISSING:
8277 ignore_missing_paths = 1;
8278 break;
8279 default:
8280 errx(1, "invalid status code '%c'",
8281 optarg[i]);
8284 status_codes = optarg;
8285 break;
8286 default:
8287 usage_remove();
8288 /* NOTREACHED */
8292 argc -= optind;
8293 argv += optind;
8295 if (argc < 1)
8296 usage_remove();
8298 cwd = getcwd(NULL, 0);
8299 if (cwd == NULL) {
8300 error = got_error_from_errno("getcwd");
8301 goto done;
8304 error = got_repo_pack_fds_open(&pack_fds);
8305 if (error != NULL)
8306 goto done;
8308 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
8309 if (error) {
8310 if (error->code == GOT_ERR_NOT_WORKTREE)
8311 error = wrap_not_worktree_error(error, "remove", cwd);
8312 goto done;
8315 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
8316 NULL, pack_fds);
8317 if (error)
8318 goto done;
8320 error = apply_unveil(got_repo_get_path(repo), 1,
8321 got_worktree_get_root_path(worktree));
8322 if (error)
8323 goto done;
8325 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
8326 if (error)
8327 goto done;
8329 if (!can_recurse) {
8330 char *ondisk_path;
8331 struct stat sb;
8332 TAILQ_FOREACH(pe, &paths, entry) {
8333 if (asprintf(&ondisk_path, "%s/%s",
8334 got_worktree_get_root_path(worktree),
8335 pe->path) == -1) {
8336 error = got_error_from_errno("asprintf");
8337 goto done;
8339 if (lstat(ondisk_path, &sb) == -1) {
8340 if (errno == ENOENT) {
8341 free(ondisk_path);
8342 continue;
8344 error = got_error_from_errno2("lstat",
8345 ondisk_path);
8346 free(ondisk_path);
8347 goto done;
8349 free(ondisk_path);
8350 if (S_ISDIR(sb.st_mode)) {
8351 error = got_error_msg(GOT_ERR_BAD_PATH,
8352 "removing directories requires -R option");
8353 goto done;
8358 error = got_worktree_schedule_delete(worktree, &paths,
8359 delete_local_mods, status_codes, print_remove_status, NULL,
8360 repo, keep_on_disk, ignore_missing_paths);
8361 done:
8362 if (repo) {
8363 const struct got_error *close_err = got_repo_close(repo);
8364 if (error == NULL)
8365 error = close_err;
8367 if (worktree)
8368 got_worktree_close(worktree);
8369 if (pack_fds) {
8370 const struct got_error *pack_err =
8371 got_repo_pack_fds_close(pack_fds);
8372 if (error == NULL)
8373 error = pack_err;
8375 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
8376 free(cwd);
8377 return error;
8380 __dead static void
8381 usage_patch(void)
8383 fprintf(stderr, "usage: %s patch [-nR] [-c commit] [-p strip-count] "
8384 "[patchfile]\n", getprogname());
8385 exit(1);
8388 static const struct got_error *
8389 patch_from_stdin(int *patchfd)
8391 const struct got_error *err = NULL;
8392 ssize_t r;
8393 char buf[BUFSIZ];
8394 sig_t sighup, sigint, sigquit;
8396 *patchfd = got_opentempfd();
8397 if (*patchfd == -1)
8398 return got_error_from_errno("got_opentempfd");
8400 sighup = signal(SIGHUP, SIG_DFL);
8401 sigint = signal(SIGINT, SIG_DFL);
8402 sigquit = signal(SIGQUIT, SIG_DFL);
8404 for (;;) {
8405 r = read(0, buf, sizeof(buf));
8406 if (r == -1) {
8407 err = got_error_from_errno("read");
8408 break;
8410 if (r == 0)
8411 break;
8412 if (write(*patchfd, buf, r) == -1) {
8413 err = got_error_from_errno("write");
8414 break;
8418 signal(SIGHUP, sighup);
8419 signal(SIGINT, sigint);
8420 signal(SIGQUIT, sigquit);
8422 if (err == NULL && lseek(*patchfd, 0, SEEK_SET) == -1)
8423 err = got_error_from_errno("lseek");
8425 if (err != NULL) {
8426 close(*patchfd);
8427 *patchfd = -1;
8430 return err;
8433 struct got_patch_progress_arg {
8434 int did_something;
8435 int conflicts;
8436 int rejects;
8439 static const struct got_error *
8440 patch_progress(void *arg, const char *old, const char *new,
8441 unsigned char status, const struct got_error *error, int old_from,
8442 int old_lines, int new_from, int new_lines, int offset,
8443 int ws_mangled, const struct got_error *hunk_err)
8445 const char *path = new == NULL ? old : new;
8446 struct got_patch_progress_arg *a = arg;
8448 while (*path == '/')
8449 path++;
8451 if (status != GOT_STATUS_NO_CHANGE &&
8452 status != 0 /* per-hunk progress */) {
8453 printf("%c %s\n", status, path);
8454 a->did_something = 1;
8457 if (hunk_err == NULL) {
8458 if (status == GOT_STATUS_CANNOT_UPDATE)
8459 a->rejects++;
8460 else if (status == GOT_STATUS_CONFLICT)
8461 a->conflicts++;
8464 if (error != NULL)
8465 fprintf(stderr, "%s: %s\n", getprogname(), error->msg);
8467 if (offset != 0 || hunk_err != NULL || ws_mangled) {
8468 printf("@@ -%d,%d +%d,%d @@ ", old_from,
8469 old_lines, new_from, new_lines);
8470 if (hunk_err != NULL)
8471 printf("%s\n", hunk_err->msg);
8472 else if (offset != 0)
8473 printf("applied with offset %d\n", offset);
8474 else
8475 printf("hunk contains mangled whitespace\n");
8478 return NULL;
8481 static void
8482 print_patch_progress_stats(struct got_patch_progress_arg *ppa)
8484 if (!ppa->did_something)
8485 return;
8487 if (ppa->conflicts > 0)
8488 printf("Files with merge conflicts: %d\n", ppa->conflicts);
8490 if (ppa->rejects > 0) {
8491 printf("Files where patch failed to apply: %d\n",
8492 ppa->rejects);
8496 static const struct got_error *
8497 cmd_patch(int argc, char *argv[])
8499 const struct got_error *error = NULL, *close_error = NULL;
8500 struct got_worktree *worktree = NULL;
8501 struct got_repository *repo = NULL;
8502 struct got_reflist_head refs;
8503 struct got_object_id *commit_id = NULL;
8504 const char *commit_id_str = NULL;
8505 struct stat sb;
8506 const char *errstr;
8507 char *cwd = NULL, *keyword_idstr = NULL;
8508 int ch, nop = 0, strip = -1, reverse = 0;
8509 int patchfd;
8510 int *pack_fds = NULL;
8511 struct got_patch_progress_arg ppa;
8513 TAILQ_INIT(&refs);
8515 #ifndef PROFILE
8516 if (pledge("stdio rpath wpath cpath fattr proc exec sendfd flock "
8517 "unveil", NULL) == -1)
8518 err(1, "pledge");
8519 #endif
8521 while ((ch = getopt(argc, argv, "c:np:R")) != -1) {
8522 switch (ch) {
8523 case 'c':
8524 commit_id_str = optarg;
8525 break;
8526 case 'n':
8527 nop = 1;
8528 break;
8529 case 'p':
8530 strip = strtonum(optarg, 0, INT_MAX, &errstr);
8531 if (errstr != NULL)
8532 errx(1, "pathname strip count is %s: %s",
8533 errstr, optarg);
8534 break;
8535 case 'R':
8536 reverse = 1;
8537 break;
8538 default:
8539 usage_patch();
8540 /* NOTREACHED */
8544 argc -= optind;
8545 argv += optind;
8547 if (argc == 0) {
8548 error = patch_from_stdin(&patchfd);
8549 if (error)
8550 return error;
8551 } else if (argc == 1) {
8552 patchfd = open(argv[0], O_RDONLY);
8553 if (patchfd == -1) {
8554 error = got_error_from_errno2("open", argv[0]);
8555 return error;
8557 if (fstat(patchfd, &sb) == -1) {
8558 error = got_error_from_errno2("fstat", argv[0]);
8559 goto done;
8561 if (!S_ISREG(sb.st_mode)) {
8562 error = got_error_path(argv[0], GOT_ERR_BAD_FILETYPE);
8563 goto done;
8565 } else
8566 usage_patch();
8568 if ((cwd = getcwd(NULL, 0)) == NULL) {
8569 error = got_error_from_errno("getcwd");
8570 goto done;
8573 error = got_repo_pack_fds_open(&pack_fds);
8574 if (error != NULL)
8575 goto done;
8577 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
8578 if (error != NULL)
8579 goto done;
8581 const char *repo_path = got_worktree_get_repo_path(worktree);
8582 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
8583 if (error != NULL)
8584 goto done;
8586 error = apply_unveil(got_repo_get_path(repo), 0,
8587 got_worktree_get_root_path(worktree));
8588 if (error != NULL)
8589 goto done;
8591 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
8592 if (error)
8593 goto done;
8595 if (commit_id_str != NULL) {
8596 error = got_keyword_to_idstr(&keyword_idstr, commit_id_str,
8597 repo, worktree);
8598 if (error != NULL)
8599 goto done;
8601 error = got_repo_match_object_id(&commit_id, NULL,
8602 keyword_idstr != NULL ? keyword_idstr : commit_id_str,
8603 GOT_OBJ_TYPE_COMMIT, &refs, repo);
8604 if (error)
8605 goto done;
8608 memset(&ppa, 0, sizeof(ppa));
8609 error = got_patch(patchfd, worktree, repo, nop, strip, reverse,
8610 commit_id, patch_progress, &ppa, check_cancelled, NULL);
8611 print_patch_progress_stats(&ppa);
8612 done:
8613 got_ref_list_free(&refs);
8614 free(keyword_idstr);
8615 free(commit_id);
8616 if (repo) {
8617 close_error = got_repo_close(repo);
8618 if (error == NULL)
8619 error = close_error;
8621 if (worktree != NULL) {
8622 close_error = got_worktree_close(worktree);
8623 if (error == NULL)
8624 error = close_error;
8626 if (pack_fds) {
8627 const struct got_error *pack_err =
8628 got_repo_pack_fds_close(pack_fds);
8629 if (error == NULL)
8630 error = pack_err;
8632 free(cwd);
8633 return error;
8636 __dead static void
8637 usage_revert(void)
8639 fprintf(stderr, "usage: %s revert [-pR] [-F response-script] path ...\n",
8640 getprogname());
8641 exit(1);
8644 static const struct got_error *
8645 revert_progress(void *arg, unsigned char status, const char *path)
8647 if (status == GOT_STATUS_UNVERSIONED)
8648 return NULL;
8650 while (path[0] == '/')
8651 path++;
8652 printf("%c %s\n", status, path);
8653 return NULL;
8656 struct choose_patch_arg {
8657 FILE *patch_script_file;
8658 const char *action;
8661 static const struct got_error *
8662 show_change(unsigned char status, const char *path, FILE *patch_file, int n,
8663 int nchanges, const char *action)
8665 const struct got_error *err;
8666 char *line = NULL;
8667 size_t linesize = 0;
8668 ssize_t linelen;
8670 switch (status) {
8671 case GOT_STATUS_ADD:
8672 printf("A %s\n%s this addition? [y/n] ", path, action);
8673 break;
8674 case GOT_STATUS_DELETE:
8675 printf("D %s\n%s this deletion? [y/n] ", path, action);
8676 break;
8677 case GOT_STATUS_MODIFY:
8678 if (fseek(patch_file, 0L, SEEK_SET) == -1)
8679 return got_error_from_errno("fseek");
8680 printf(GOT_COMMIT_SEP_STR);
8681 while ((linelen = getline(&line, &linesize, patch_file)) != -1)
8682 printf("%s", line);
8683 if (linelen == -1 && ferror(patch_file)) {
8684 err = got_error_from_errno("getline");
8685 free(line);
8686 return err;
8688 free(line);
8689 printf(GOT_COMMIT_SEP_STR);
8690 printf("M %s (change %d of %d)\n%s this change? [y/n/q] ",
8691 path, n, nchanges, action);
8692 break;
8693 default:
8694 return got_error_path(path, GOT_ERR_FILE_STATUS);
8697 fflush(stdout);
8698 return NULL;
8701 #define CHOOSE_PATCH_VALID_RESPONSES "ynq"
8703 static const struct got_error *
8704 choose_patch(int *choice, void *arg, unsigned char status, const char *path,
8705 FILE *patch_file, int n, int nchanges)
8707 const struct got_error *err = NULL;
8708 char *nl, *line = NULL;
8709 FILE *fp = stdin;
8710 size_t linesize = 0;
8711 ssize_t linelen;
8712 int interactive = 1;
8713 struct choose_patch_arg *a = arg;
8715 *choice = GOT_PATCH_CHOICE_NONE;
8717 if (a->patch_script_file) {
8718 interactive = 0;
8719 fp = a->patch_script_file;
8722 for (;;) {
8723 err = show_change(status, path, patch_file, n, nchanges,
8724 a->action);
8725 if (err)
8726 return err;
8728 linelen = getline(&line, &linesize, fp);
8729 if (linelen == -1) {
8730 free(line);
8731 if (ferror(fp))
8732 return got_error_from_errno("getline");
8733 if (feof(fp))
8734 return got_error(GOT_ERR_EOF);
8735 return NULL;
8738 nl = strchr(line, '\n');
8739 if (nl)
8740 *nl = '\0';
8741 if (strlen(line) != 1 ||
8742 !strchr(CHOOSE_PATCH_VALID_RESPONSES, line[0])) {
8743 printf("invalid response '%s'\n", line);
8744 if (interactive)
8745 continue;
8748 /* ADD and DELETE do not accept 'q' response currently. */
8749 if (status != GOT_STATUS_MODIFY && line[0] == 'q') {
8750 printf("invalid response '%s'\n", line);
8751 continue;
8754 break;
8757 switch (line[0]) {
8758 case 'y':
8759 *choice = GOT_PATCH_CHOICE_YES;
8760 break;
8761 case 'n':
8762 *choice = GOT_PATCH_CHOICE_NO;
8763 break;
8764 case 'q':
8765 if (status == GOT_STATUS_MODIFY)
8766 *choice = GOT_PATCH_CHOICE_QUIT;
8767 break;
8768 default:
8769 printf("invalid response '%s'\n", line);
8770 free(line);
8771 return NULL;
8774 if (!interactive)
8775 printf("%c\n", line[0]);
8777 free(line);
8778 return NULL;
8781 struct wt_commitable_path_arg {
8782 struct got_pathlist_head *commit_paths;
8783 int *has_changes;
8787 * Shortcut work tree status callback to determine if the set of paths scanned
8788 * has at least one versioned path that is being modified and, if not NULL, is
8789 * in the arg->commit_paths list. Set arg and return GOT_ERR_FILE_MODIFIED as
8790 * soon as a path is passed with a status that satisfies this criteria.
8792 static const struct got_error *
8793 worktree_has_commitable_path(void *arg, unsigned char status,
8794 unsigned char staged_status, const char *path,
8795 struct got_object_id *blob_id, struct got_object_id *staged_blob_id,
8796 struct got_object_id *commit_id, int dirfd, const char *de_name)
8798 struct wt_commitable_path_arg *a = arg;
8800 if (status == staged_status && (status == GOT_STATUS_DELETE))
8801 status = GOT_STATUS_NO_CHANGE;
8803 if (!(status == GOT_STATUS_NO_CHANGE ||
8804 status == GOT_STATUS_UNVERSIONED) ||
8805 staged_status != GOT_STATUS_NO_CHANGE) {
8806 if (a->commit_paths != NULL) {
8807 struct got_pathlist_entry *pe;
8809 TAILQ_FOREACH(pe, a->commit_paths, entry) {
8810 if (strncmp(path, pe->path,
8811 pe->path_len) == 0) {
8812 *a->has_changes = 1;
8813 break;
8816 } else
8817 *a->has_changes = 1;
8819 if (*a->has_changes)
8820 return got_error(GOT_ERR_FILE_MODIFIED);
8823 return NULL;
8827 * Check that the changeset of the commit identified by id is
8828 * comprised of at least one modified path that is being committed.
8830 static const struct got_error *
8831 commit_path_changed_in_worktree(struct wt_commitable_path_arg *wcpa,
8832 struct got_object_id *id, struct got_worktree *worktree,
8833 struct got_repository *repo)
8835 const struct got_error *err;
8836 struct got_pathlist_head paths;
8837 struct got_commit_object *commit = NULL, *pcommit = NULL;
8838 struct got_tree_object *tree = NULL, *ptree = NULL;
8839 struct got_object_qid *pid;
8841 TAILQ_INIT(&paths);
8843 err = got_object_open_as_commit(&commit, repo, id);
8844 if (err)
8845 goto done;
8847 err = got_object_open_as_tree(&tree, repo,
8848 got_object_commit_get_tree_id(commit));
8849 if (err)
8850 goto done;
8852 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
8853 if (pid != NULL) {
8854 err = got_object_open_as_commit(&pcommit, repo, &pid->id);
8855 if (err)
8856 goto done;
8858 err = got_object_open_as_tree(&ptree, repo,
8859 got_object_commit_get_tree_id(pcommit));
8860 if (err)
8861 goto done;
8864 err = got_diff_tree(ptree, tree, NULL, NULL, -1, -1, "", "", repo,
8865 got_diff_tree_collect_changed_paths, &paths, 0);
8866 if (err)
8867 goto done;
8869 err = got_worktree_status(worktree, &paths, repo, 0,
8870 worktree_has_commitable_path, wcpa, check_cancelled, NULL);
8871 if (err && err->code == GOT_ERR_FILE_MODIFIED) {
8873 * At least one changed path in the referenced commit is
8874 * modified in the work tree, that's all we need to know!
8876 err = NULL;
8879 done:
8880 got_pathlist_free(&paths, GOT_PATHLIST_FREE_ALL);
8881 if (commit)
8882 got_object_commit_close(commit);
8883 if (pcommit)
8884 got_object_commit_close(pcommit);
8885 if (tree)
8886 got_object_tree_close(tree);
8887 if (ptree)
8888 got_object_tree_close(ptree);
8889 return err;
8893 * Remove any "logmsg" reference comprised entirely of paths that have
8894 * been reverted in this work tree. If any path in the logmsg ref changeset
8895 * remains in a changed state in the worktree, do not remove the reference.
8897 static const struct got_error *
8898 rm_logmsg_ref(struct got_worktree *worktree, struct got_repository *repo)
8900 const struct got_error *err;
8901 struct got_reflist_head refs;
8902 struct got_reflist_entry *re;
8903 struct got_commit_object *commit = NULL;
8904 struct got_object_id *commit_id = NULL;
8905 struct wt_commitable_path_arg wcpa;
8906 char *uuidstr = NULL;
8908 TAILQ_INIT(&refs);
8910 err = got_worktree_get_uuid(&uuidstr, worktree);
8911 if (err)
8912 goto done;
8914 err = got_ref_list(&refs, repo, "refs/got/worktree",
8915 got_ref_cmp_by_name, repo);
8916 if (err)
8917 goto done;
8919 TAILQ_FOREACH(re, &refs, entry) {
8920 const char *refname;
8921 int has_changes = 0;
8923 refname = got_ref_get_name(re->ref);
8925 if (!strncmp(refname, GOT_WORKTREE_CHERRYPICK_REF_PREFIX,
8926 GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN))
8927 refname += GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN + 1;
8928 else if (!strncmp(refname, GOT_WORKTREE_BACKOUT_REF_PREFIX,
8929 GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN))
8930 refname += GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN + 1;
8931 else
8932 continue;
8934 if (strncmp(refname, uuidstr, GOT_WORKTREE_UUID_STRLEN) == 0)
8935 refname += GOT_WORKTREE_UUID_STRLEN + 1; /* skip '-' */
8936 else
8937 continue;
8939 err = got_repo_match_object_id(&commit_id, NULL, refname,
8940 GOT_OBJ_TYPE_COMMIT, NULL, repo);
8941 if (err)
8942 goto done;
8944 err = got_object_open_as_commit(&commit, repo, commit_id);
8945 if (err)
8946 goto done;
8948 wcpa.commit_paths = NULL;
8949 wcpa.has_changes = &has_changes;
8951 err = commit_path_changed_in_worktree(&wcpa, commit_id,
8952 worktree, repo);
8953 if (err)
8954 goto done;
8956 if (!has_changes) {
8957 err = got_ref_delete(re->ref, repo);
8958 if (err)
8959 goto done;
8962 got_object_commit_close(commit);
8963 commit = NULL;
8964 free(commit_id);
8965 commit_id = NULL;
8968 done:
8969 free(uuidstr);
8970 free(commit_id);
8971 got_ref_list_free(&refs);
8972 if (commit)
8973 got_object_commit_close(commit);
8974 return err;
8977 static const struct got_error *
8978 cmd_revert(int argc, char *argv[])
8980 const struct got_error *error = NULL;
8981 struct got_worktree *worktree = NULL;
8982 struct got_repository *repo = NULL;
8983 char *cwd = NULL, *path = NULL;
8984 struct got_pathlist_head paths;
8985 struct got_pathlist_entry *pe;
8986 int ch, can_recurse = 0, pflag = 0;
8987 FILE *patch_script_file = NULL;
8988 const char *patch_script_path = NULL;
8989 struct choose_patch_arg cpa;
8990 int *pack_fds = NULL;
8992 TAILQ_INIT(&paths);
8994 #ifndef PROFILE
8995 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
8996 "unveil", NULL) == -1)
8997 err(1, "pledge");
8998 #endif
9000 while ((ch = getopt(argc, argv, "F:pR")) != -1) {
9001 switch (ch) {
9002 case 'F':
9003 patch_script_path = optarg;
9004 break;
9005 case 'p':
9006 pflag = 1;
9007 break;
9008 case 'R':
9009 can_recurse = 1;
9010 break;
9011 default:
9012 usage_revert();
9013 /* NOTREACHED */
9017 argc -= optind;
9018 argv += optind;
9020 if (argc < 1)
9021 usage_revert();
9022 if (patch_script_path && !pflag)
9023 errx(1, "-F option can only be used together with -p option");
9025 cwd = getcwd(NULL, 0);
9026 if (cwd == NULL) {
9027 error = got_error_from_errno("getcwd");
9028 goto done;
9031 error = got_repo_pack_fds_open(&pack_fds);
9032 if (error != NULL)
9033 goto done;
9035 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
9036 if (error) {
9037 if (error->code == GOT_ERR_NOT_WORKTREE)
9038 error = wrap_not_worktree_error(error, "revert", cwd);
9039 goto done;
9042 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
9043 NULL, pack_fds);
9044 if (error != NULL)
9045 goto done;
9047 if (patch_script_path) {
9048 patch_script_file = fopen(patch_script_path, "re");
9049 if (patch_script_file == NULL) {
9050 error = got_error_from_errno2("fopen",
9051 patch_script_path);
9052 goto done;
9057 * XXX "c" perm needed on repo dir to delete merge references.
9059 error = apply_unveil(got_repo_get_path(repo), 0,
9060 got_worktree_get_root_path(worktree));
9061 if (error)
9062 goto done;
9064 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
9065 if (error)
9066 goto done;
9068 if (!can_recurse) {
9069 char *ondisk_path;
9070 struct stat sb;
9071 TAILQ_FOREACH(pe, &paths, entry) {
9072 if (asprintf(&ondisk_path, "%s/%s",
9073 got_worktree_get_root_path(worktree),
9074 pe->path) == -1) {
9075 error = got_error_from_errno("asprintf");
9076 goto done;
9078 if (lstat(ondisk_path, &sb) == -1) {
9079 if (errno == ENOENT) {
9080 free(ondisk_path);
9081 continue;
9083 error = got_error_from_errno2("lstat",
9084 ondisk_path);
9085 free(ondisk_path);
9086 goto done;
9088 free(ondisk_path);
9089 if (S_ISDIR(sb.st_mode)) {
9090 error = got_error_msg(GOT_ERR_BAD_PATH,
9091 "reverting directories requires -R option");
9092 goto done;
9097 cpa.patch_script_file = patch_script_file;
9098 cpa.action = "revert";
9099 error = got_worktree_revert(worktree, &paths, revert_progress, NULL,
9100 pflag ? choose_patch : NULL, &cpa, repo);
9102 error = rm_logmsg_ref(worktree, repo);
9103 done:
9104 if (patch_script_file && fclose(patch_script_file) == EOF &&
9105 error == NULL)
9106 error = got_error_from_errno2("fclose", patch_script_path);
9107 if (repo) {
9108 const struct got_error *close_err = got_repo_close(repo);
9109 if (error == NULL)
9110 error = close_err;
9112 if (worktree)
9113 got_worktree_close(worktree);
9114 if (pack_fds) {
9115 const struct got_error *pack_err =
9116 got_repo_pack_fds_close(pack_fds);
9117 if (error == NULL)
9118 error = pack_err;
9120 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
9121 free(path);
9122 free(cwd);
9123 return error;
9126 __dead static void
9127 usage_commit(void)
9129 fprintf(stderr, "usage: %s commit [-CNnS] [-A author] [-F path] "
9130 "[-m message] [path ...]\n", getprogname());
9131 exit(1);
9134 struct collect_commit_logmsg_arg {
9135 const char *cmdline_log;
9136 const char *prepared_log;
9137 const char *merged_log;
9138 int non_interactive;
9139 const char *editor;
9140 const char *worktree_path;
9141 const char *branch_name;
9142 const char *repo_path;
9143 char *logmsg_path;
9147 static const struct got_error *
9148 read_prepared_logmsg(char **logmsg, const char *path)
9150 const struct got_error *err = NULL;
9151 FILE *f = NULL;
9152 struct stat sb;
9153 size_t r;
9155 *logmsg = NULL;
9156 memset(&sb, 0, sizeof(sb));
9158 f = fopen(path, "re");
9159 if (f == NULL)
9160 return got_error_from_errno2("fopen", path);
9162 if (fstat(fileno(f), &sb) == -1) {
9163 err = got_error_from_errno2("fstat", path);
9164 goto done;
9166 if (sb.st_size == 0) {
9167 err = got_error(GOT_ERR_COMMIT_MSG_EMPTY);
9168 goto done;
9171 *logmsg = malloc(sb.st_size + 1);
9172 if (*logmsg == NULL) {
9173 err = got_error_from_errno("malloc");
9174 goto done;
9177 r = fread(*logmsg, 1, sb.st_size, f);
9178 if (r != sb.st_size) {
9179 if (ferror(f))
9180 err = got_error_from_errno2("fread", path);
9181 else
9182 err = got_error(GOT_ERR_IO);
9183 goto done;
9185 (*logmsg)[sb.st_size] = '\0';
9186 done:
9187 if (fclose(f) == EOF && err == NULL)
9188 err = got_error_from_errno2("fclose", path);
9189 if (err) {
9190 free(*logmsg);
9191 *logmsg = NULL;
9193 return err;
9196 static const struct got_error *
9197 collect_commit_logmsg(struct got_pathlist_head *commitable_paths,
9198 const char *diff_path, char **logmsg, void *arg)
9200 char *initial_content = NULL;
9201 struct got_pathlist_entry *pe;
9202 const struct got_error *err = NULL;
9203 char *template = NULL;
9204 char *prepared_msg = NULL, *merged_msg = NULL;
9205 struct collect_commit_logmsg_arg *a = arg;
9206 int initial_content_len;
9207 int fd = -1;
9208 size_t len;
9210 /* if a message was specified on the command line, just use it */
9211 if (a->cmdline_log != NULL && *a->cmdline_log != '\0') {
9212 len = strlen(a->cmdline_log) + 1;
9213 *logmsg = malloc(len + 1);
9214 if (*logmsg == NULL)
9215 return got_error_from_errno("malloc");
9216 strlcpy(*logmsg, a->cmdline_log, len);
9217 return NULL;
9218 } else if (a->prepared_log != NULL && a->non_interactive)
9219 return read_prepared_logmsg(logmsg, a->prepared_log);
9221 if (asprintf(&template, "%s/logmsg", a->worktree_path) == -1)
9222 return got_error_from_errno("asprintf");
9224 err = got_opentemp_named_fd(&a->logmsg_path, &fd, template, "");
9225 if (err)
9226 goto done;
9228 if (a->prepared_log) {
9229 err = read_prepared_logmsg(&prepared_msg, a->prepared_log);
9230 if (err)
9231 goto done;
9232 } else if (a->merged_log) {
9233 err = read_prepared_logmsg(&merged_msg, a->merged_log);
9234 if (err)
9235 goto done;
9238 initial_content_len = asprintf(&initial_content,
9239 "%s%s\n# changes to be committed on branch %s:\n",
9240 prepared_msg ? prepared_msg : "",
9241 merged_msg ? merged_msg : "", a->branch_name);
9242 if (initial_content_len == -1) {
9243 err = got_error_from_errno("asprintf");
9244 goto done;
9247 if (write(fd, initial_content, initial_content_len) == -1) {
9248 err = got_error_from_errno2("write", a->logmsg_path);
9249 goto done;
9252 TAILQ_FOREACH(pe, commitable_paths, entry) {
9253 struct got_commitable *ct = pe->data;
9254 dprintf(fd, "# %c %s\n",
9255 got_commitable_get_status(ct),
9256 got_commitable_get_path(ct));
9259 if (diff_path) {
9260 dprintf(fd, "# detailed changes can be viewed in %s\n",
9261 diff_path);
9264 if (close(fd) == -1) {
9265 err = got_error_from_errno2("close", a->logmsg_path);
9266 goto done;
9268 fd = -1;
9270 err = edit_logmsg(logmsg, a->editor, a->logmsg_path, initial_content,
9271 initial_content_len, a->prepared_log ? 0 : 1);
9272 done:
9273 free(initial_content);
9274 free(template);
9275 free(prepared_msg);
9276 free(merged_msg);
9278 if (fd != -1 && close(fd) == -1 && err == NULL)
9279 err = got_error_from_errno2("close", a->logmsg_path);
9280 if (err) {
9281 free(*logmsg);
9282 *logmsg = NULL;
9284 return err;
9287 static const struct got_error *
9288 cat_logmsg(FILE *f, struct got_commit_object *commit, const char *idstr,
9289 const char *type, int has_content)
9291 const struct got_error *err = NULL;
9292 char *logmsg = NULL;
9294 err = got_object_commit_get_logmsg(&logmsg, commit);
9295 if (err)
9296 return err;
9298 if (fprintf(f, "%s# log message of %s commit %s:%s",
9299 has_content ? "\n" : "", type, idstr, logmsg) < 0)
9300 err = got_ferror(f, GOT_ERR_IO);
9302 free(logmsg);
9303 return err;
9307 * Lookup "logmsg" references of backed-out and cherrypicked commits
9308 * belonging to the current work tree. If found, and the worktree has
9309 * at least one modified file that was changed in the referenced commit,
9310 * add its log message to a new temporary file at *logmsg_path.
9311 * Add all refs found to matched_refs to be scheduled for removal on
9312 * successful commit.
9314 static const struct got_error *
9315 lookup_logmsg_ref(char **logmsg_path, struct got_pathlist_head *paths,
9316 struct got_reflist_head *matched_refs, struct got_worktree *worktree,
9317 struct got_repository *repo)
9319 const struct got_error *err;
9320 struct got_commit_object *commit = NULL;
9321 struct got_object_id *id = NULL;
9322 struct got_reflist_head refs;
9323 struct got_reflist_entry *re, *re_match;
9324 FILE *f = NULL;
9325 char *uuidstr = NULL;
9326 int added_logmsg = 0;
9328 TAILQ_INIT(&refs);
9330 *logmsg_path = NULL;
9332 err = got_worktree_get_uuid(&uuidstr, worktree);
9333 if (err)
9334 goto done;
9336 err = got_ref_list(&refs, repo, "refs/got/worktree",
9337 got_ref_cmp_by_name, repo);
9338 if (err)
9339 goto done;
9341 TAILQ_FOREACH(re, &refs, entry) {
9342 const char *refname, *type;
9343 struct wt_commitable_path_arg wcpa;
9344 int add_logmsg = 0;
9346 refname = got_ref_get_name(re->ref);
9348 if (strncmp(refname, GOT_WORKTREE_CHERRYPICK_REF_PREFIX,
9349 GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN) == 0) {
9350 refname += GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN + 1;
9351 type = "cherrypicked";
9352 } else if (strncmp(refname, GOT_WORKTREE_BACKOUT_REF_PREFIX,
9353 GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN) == 0) {
9354 refname += GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN + 1;
9355 type = "backed-out";
9356 } else
9357 continue;
9359 if (strncmp(refname, uuidstr, GOT_WORKTREE_UUID_STRLEN) == 0)
9360 refname += GOT_WORKTREE_UUID_STRLEN + 1; /* skip '-' */
9361 else
9362 continue;
9364 err = got_repo_match_object_id(&id, NULL, refname,
9365 GOT_OBJ_TYPE_COMMIT, NULL, repo);
9366 if (err)
9367 goto done;
9369 err = got_object_open_as_commit(&commit, repo, id);
9370 if (err)
9371 goto done;
9373 wcpa.commit_paths = paths;
9374 wcpa.has_changes = &add_logmsg;
9376 err = commit_path_changed_in_worktree(&wcpa, id,
9377 worktree, repo);
9378 if (err)
9379 goto done;
9381 if (add_logmsg) {
9382 if (f == NULL) {
9383 err = got_opentemp_named(logmsg_path, &f,
9384 "got-commit-logmsg", "");
9385 if (err)
9386 goto done;
9388 err = cat_logmsg(f, commit, refname, type,
9389 added_logmsg);
9390 if (err)
9391 goto done;
9392 if (!added_logmsg)
9393 ++added_logmsg;
9395 err = got_reflist_entry_dup(&re_match, re);
9396 if (err)
9397 goto done;
9398 TAILQ_INSERT_HEAD(matched_refs, re_match, entry);
9401 got_object_commit_close(commit);
9402 commit = NULL;
9403 free(id);
9404 id = NULL;
9407 done:
9408 free(id);
9409 free(uuidstr);
9410 got_ref_list_free(&refs);
9411 if (commit)
9412 got_object_commit_close(commit);
9413 if (f && fclose(f) == EOF && err == NULL)
9414 err = got_error_from_errno("fclose");
9415 if (!added_logmsg) {
9416 if (*logmsg_path && unlink(*logmsg_path) != 0 && err == NULL)
9417 err = got_error_from_errno2("unlink", *logmsg_path);
9418 *logmsg_path = NULL;
9420 return err;
9423 static const struct got_error *
9424 cmd_commit(int argc, char *argv[])
9426 const struct got_error *error = NULL;
9427 struct got_worktree *worktree = NULL;
9428 struct got_repository *repo = NULL;
9429 char *cwd = NULL, *id_str = NULL;
9430 struct got_object_id *id = NULL;
9431 const char *logmsg = NULL;
9432 char *prepared_logmsg = NULL, *merged_logmsg = NULL;
9433 struct collect_commit_logmsg_arg cl_arg;
9434 const char *author = NULL;
9435 char *gitconfig_path = NULL, *editor = NULL, *committer = NULL;
9436 int ch, rebase_in_progress, histedit_in_progress, preserve_logmsg = 0;
9437 int allow_bad_symlinks = 0, non_interactive = 0, merge_in_progress = 0;
9438 int show_diff = 1, commit_conflicts = 0;
9439 struct got_pathlist_head paths;
9440 struct got_reflist_head refs;
9441 struct got_reflist_entry *re;
9442 int *pack_fds = NULL;
9444 TAILQ_INIT(&refs);
9445 TAILQ_INIT(&paths);
9446 cl_arg.logmsg_path = NULL;
9448 #ifndef PROFILE
9449 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
9450 "unveil", NULL) == -1)
9451 err(1, "pledge");
9452 #endif
9454 while ((ch = getopt(argc, argv, "A:CF:m:NnS")) != -1) {
9455 switch (ch) {
9456 case 'A':
9457 author = optarg;
9458 error = valid_author(author);
9459 if (error)
9460 return error;
9461 break;
9462 case 'C':
9463 commit_conflicts = 1;
9464 break;
9465 case 'F':
9466 if (logmsg != NULL)
9467 option_conflict('F', 'm');
9468 prepared_logmsg = realpath(optarg, NULL);
9469 if (prepared_logmsg == NULL)
9470 return got_error_from_errno2("realpath",
9471 optarg);
9472 break;
9473 case 'm':
9474 if (prepared_logmsg)
9475 option_conflict('m', 'F');
9476 logmsg = optarg;
9477 break;
9478 case 'N':
9479 non_interactive = 1;
9480 break;
9481 case 'n':
9482 show_diff = 0;
9483 break;
9484 case 'S':
9485 allow_bad_symlinks = 1;
9486 break;
9487 default:
9488 usage_commit();
9489 /* NOTREACHED */
9493 argc -= optind;
9494 argv += optind;
9496 cwd = getcwd(NULL, 0);
9497 if (cwd == NULL) {
9498 error = got_error_from_errno("getcwd");
9499 goto done;
9502 error = got_repo_pack_fds_open(&pack_fds);
9503 if (error != NULL)
9504 goto done;
9506 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
9507 if (error) {
9508 if (error->code == GOT_ERR_NOT_WORKTREE)
9509 error = wrap_not_worktree_error(error, "commit", cwd);
9510 goto done;
9513 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
9514 if (error)
9515 goto done;
9516 if (rebase_in_progress) {
9517 error = got_error(GOT_ERR_REBASING);
9518 goto done;
9521 error = got_worktree_histedit_in_progress(&histedit_in_progress,
9522 worktree);
9523 if (error)
9524 goto done;
9526 error = get_gitconfig_path(&gitconfig_path);
9527 if (error)
9528 goto done;
9529 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
9530 gitconfig_path, pack_fds);
9531 if (error != NULL)
9532 goto done;
9534 error = got_worktree_merge_in_progress(&merge_in_progress, worktree, repo);
9535 if (error)
9536 goto done;
9537 if (merge_in_progress) {
9538 error = got_error(GOT_ERR_MERGE_BUSY);
9539 goto done;
9542 error = get_author(&committer, repo, worktree);
9543 if (error)
9544 goto done;
9546 if (author == NULL)
9547 author = committer;
9549 if (logmsg == NULL || strlen(logmsg) == 0) {
9550 error = get_editor(&editor);
9551 if (error)
9552 goto done;
9553 if (unveil(editor, "x") != 0) {
9554 error = got_error_from_errno2("unveil", editor);
9555 goto done;
9558 if (prepared_logmsg) {
9559 if (unveil(prepared_logmsg, "r") != 0) {
9560 error = got_error_from_errno2("unveil",
9561 prepared_logmsg);
9562 goto done;
9566 error = apply_unveil(got_repo_get_path(repo), 0,
9567 got_worktree_get_root_path(worktree));
9568 if (error)
9569 goto done;
9571 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
9572 if (error)
9573 goto done;
9575 if (prepared_logmsg == NULL) {
9576 error = lookup_logmsg_ref(&merged_logmsg,
9577 argc > 0 ? &paths : NULL, &refs, worktree, repo);
9578 if (error)
9579 goto done;
9582 cl_arg.editor = editor;
9583 cl_arg.cmdline_log = logmsg;
9584 cl_arg.prepared_log = prepared_logmsg;
9585 cl_arg.merged_log = merged_logmsg;
9586 cl_arg.non_interactive = non_interactive;
9587 cl_arg.worktree_path = got_worktree_get_root_path(worktree);
9588 cl_arg.branch_name = got_worktree_get_head_ref_name(worktree);
9589 if (!histedit_in_progress) {
9590 if (strncmp(cl_arg.branch_name, "refs/heads/", 11) != 0) {
9591 error = got_error(GOT_ERR_COMMIT_BRANCH);
9592 goto done;
9594 cl_arg.branch_name += 11;
9596 cl_arg.repo_path = got_repo_get_path(repo);
9597 error = got_worktree_commit(&id, worktree, &paths, author, committer,
9598 allow_bad_symlinks, show_diff, commit_conflicts,
9599 collect_commit_logmsg, &cl_arg, print_status, NULL, repo);
9600 if (error) {
9601 if (error->code != GOT_ERR_COMMIT_MSG_EMPTY &&
9602 cl_arg.logmsg_path != NULL)
9603 preserve_logmsg = 1;
9604 goto done;
9607 error = got_object_id_str(&id_str, id);
9608 if (error)
9609 goto done;
9610 printf("Created commit %s\n", id_str);
9612 TAILQ_FOREACH(re, &refs, entry) {
9613 error = got_ref_delete(re->ref, repo);
9614 if (error)
9615 goto done;
9618 done:
9619 if (preserve_logmsg) {
9620 fprintf(stderr, "%s: log message preserved in %s\n",
9621 getprogname(), cl_arg.logmsg_path);
9622 } else if (cl_arg.logmsg_path && unlink(cl_arg.logmsg_path) == -1 &&
9623 error == NULL)
9624 error = got_error_from_errno2("unlink", cl_arg.logmsg_path);
9625 free(cl_arg.logmsg_path);
9626 if (merged_logmsg && unlink(merged_logmsg) == -1 && error == NULL)
9627 error = got_error_from_errno2("unlink", merged_logmsg);
9628 free(merged_logmsg);
9629 if (repo) {
9630 const struct got_error *close_err = got_repo_close(repo);
9631 if (error == NULL)
9632 error = close_err;
9634 if (worktree)
9635 got_worktree_close(worktree);
9636 if (pack_fds) {
9637 const struct got_error *pack_err =
9638 got_repo_pack_fds_close(pack_fds);
9639 if (error == NULL)
9640 error = pack_err;
9642 got_ref_list_free(&refs);
9643 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
9644 free(cwd);
9645 free(id_str);
9646 free(gitconfig_path);
9647 free(editor);
9648 free(committer);
9649 free(prepared_logmsg);
9650 return error;
9653 __dead static void
9654 usage_send(void)
9656 fprintf(stderr, "usage: %s send [-afqTv] [-b branch] [-d branch] "
9657 "[-r repository-path] [-t tag] [remote-repository]\n",
9658 getprogname());
9659 exit(1);
9662 static void
9663 print_load_info(int print_colored, int print_found, int print_trees,
9664 int ncolored, int nfound, int ntrees)
9666 if (print_colored) {
9667 printf("%d commit%s colored", ncolored,
9668 ncolored == 1 ? "" : "s");
9670 if (print_found) {
9671 printf("%s%d object%s found",
9672 ncolored > 0 ? "; " : "",
9673 nfound, nfound == 1 ? "" : "s");
9675 if (print_trees) {
9676 printf("; %d tree%s scanned", ntrees,
9677 ntrees == 1 ? "" : "s");
9681 struct got_send_progress_arg {
9682 char last_scaled_packsize[FMT_SCALED_STRSIZE];
9683 int verbosity;
9684 int last_ncolored;
9685 int last_nfound;
9686 int last_ntrees;
9687 int loading_done;
9688 int last_ncommits;
9689 int last_nobj_total;
9690 int last_p_deltify;
9691 int last_p_written;
9692 int last_p_sent;
9693 int printed_something;
9694 int sent_something;
9695 struct got_pathlist_head *delete_branches;
9698 static const struct got_error *
9699 send_progress(void *arg, int ncolored, int nfound, int ntrees,
9700 off_t packfile_size, int ncommits, int nobj_total, int nobj_deltify,
9701 int nobj_written, off_t bytes_sent, const char *refname,
9702 const char *errmsg, int success)
9704 struct got_send_progress_arg *a = arg;
9705 char scaled_packsize[FMT_SCALED_STRSIZE];
9706 char scaled_sent[FMT_SCALED_STRSIZE];
9707 int p_deltify = 0, p_written = 0, p_sent = 0;
9708 int print_colored = 0, print_found = 0, print_trees = 0;
9709 int print_searching = 0, print_total = 0;
9710 int print_deltify = 0, print_written = 0, print_sent = 0;
9712 if (a->verbosity < 0)
9713 return NULL;
9715 if (refname) {
9716 const char *status = success ? "accepted" : "rejected";
9718 if (success) {
9719 struct got_pathlist_entry *pe;
9720 TAILQ_FOREACH(pe, a->delete_branches, entry) {
9721 const char *branchname = pe->path;
9722 if (got_path_cmp(branchname, refname,
9723 strlen(branchname), strlen(refname)) == 0) {
9724 status = "deleted";
9725 a->sent_something = 1;
9726 break;
9731 if (a->printed_something)
9732 putchar('\n');
9733 printf("Server has %s %s", status, refname);
9734 if (errmsg)
9735 printf(": %s", errmsg);
9736 a->printed_something = 1;
9737 return NULL;
9740 if (a->last_ncolored != ncolored) {
9741 print_colored = 1;
9742 a->last_ncolored = ncolored;
9745 if (a->last_nfound != nfound) {
9746 print_colored = 1;
9747 print_found = 1;
9748 a->last_nfound = nfound;
9751 if (a->last_ntrees != ntrees) {
9752 print_colored = 1;
9753 print_found = 1;
9754 print_trees = 1;
9755 a->last_ntrees = ntrees;
9758 if ((print_colored || print_found || print_trees) &&
9759 !a->loading_done) {
9760 printf("\r");
9761 print_load_info(print_colored, print_found, print_trees,
9762 ncolored, nfound, ntrees);
9763 a->printed_something = 1;
9764 fflush(stdout);
9765 return NULL;
9766 } else if (!a->loading_done) {
9767 printf("\r");
9768 print_load_info(1, 1, 1, ncolored, nfound, ntrees);
9769 printf("\n");
9770 a->loading_done = 1;
9773 if (fmt_scaled(packfile_size, scaled_packsize) == -1)
9774 return got_error_from_errno("fmt_scaled");
9775 if (fmt_scaled(bytes_sent, scaled_sent) == -1)
9776 return got_error_from_errno("fmt_scaled");
9778 if (a->last_ncommits != ncommits) {
9779 print_searching = 1;
9780 a->last_ncommits = ncommits;
9783 if (a->last_nobj_total != nobj_total) {
9784 print_searching = 1;
9785 print_total = 1;
9786 a->last_nobj_total = nobj_total;
9789 if (packfile_size > 0 && (a->last_scaled_packsize[0] == '\0' ||
9790 strcmp(scaled_packsize, a->last_scaled_packsize)) != 0) {
9791 if (strlcpy(a->last_scaled_packsize, scaled_packsize,
9792 FMT_SCALED_STRSIZE) >= FMT_SCALED_STRSIZE)
9793 return got_error(GOT_ERR_NO_SPACE);
9796 if (nobj_deltify > 0 || nobj_written > 0) {
9797 if (nobj_deltify > 0) {
9798 p_deltify = (nobj_deltify * 100) / nobj_total;
9799 if (p_deltify != a->last_p_deltify) {
9800 a->last_p_deltify = p_deltify;
9801 print_searching = 1;
9802 print_total = 1;
9803 print_deltify = 1;
9806 if (nobj_written > 0) {
9807 p_written = (nobj_written * 100) / nobj_total;
9808 if (p_written != a->last_p_written) {
9809 a->last_p_written = p_written;
9810 print_searching = 1;
9811 print_total = 1;
9812 print_deltify = 1;
9813 print_written = 1;
9818 if (bytes_sent > 0) {
9819 p_sent = (bytes_sent * 100) / packfile_size;
9820 if (p_sent != a->last_p_sent) {
9821 a->last_p_sent = p_sent;
9822 print_searching = 1;
9823 print_total = 1;
9824 print_deltify = 1;
9825 print_written = 1;
9826 print_sent = 1;
9828 a->sent_something = 1;
9831 if (print_searching || print_total || print_deltify || print_written ||
9832 print_sent)
9833 printf("\r");
9834 if (print_searching)
9835 printf("packing %d reference%s", ncommits,
9836 ncommits == 1 ? "" : "s");
9837 if (print_total)
9838 printf("; %d object%s", nobj_total,
9839 nobj_total == 1 ? "" : "s");
9840 if (print_deltify)
9841 printf("; deltify: %d%%", p_deltify);
9842 if (print_sent)
9843 printf("; uploading pack: %*s %d%%", FMT_SCALED_STRSIZE - 2,
9844 scaled_packsize, p_sent);
9845 else if (print_written)
9846 printf("; writing pack: %*s %d%%", FMT_SCALED_STRSIZE - 2,
9847 scaled_packsize, p_written);
9848 if (print_searching || print_total || print_deltify ||
9849 print_written || print_sent) {
9850 a->printed_something = 1;
9851 fflush(stdout);
9853 return NULL;
9856 static const struct got_error *
9857 cmd_send(int argc, char *argv[])
9859 const struct got_error *error = NULL;
9860 char *cwd = NULL, *repo_path = NULL;
9861 const char *remote_name;
9862 char *proto = NULL, *host = NULL, *port = NULL;
9863 char *repo_name = NULL, *server_path = NULL;
9864 const struct got_remote_repo *remotes;
9865 struct got_remote_repo *remote = NULL;
9866 int nremotes, nbranches = 0, ndelete_branches = 0;
9867 struct got_repository *repo = NULL;
9868 struct got_worktree *worktree = NULL;
9869 const struct got_gotconfig *repo_conf = NULL, *worktree_conf = NULL;
9870 struct got_pathlist_head branches;
9871 struct got_pathlist_head tags;
9872 struct got_reflist_head all_branches;
9873 struct got_reflist_head all_tags;
9874 struct got_pathlist_head delete_args;
9875 struct got_pathlist_head delete_branches;
9876 struct got_reflist_entry *re;
9877 struct got_pathlist_entry *pe;
9878 int i, ch, sendfd = -1, sendstatus;
9879 pid_t sendpid = -1;
9880 struct got_send_progress_arg spa;
9881 int verbosity = 0, overwrite_refs = 0;
9882 int send_all_branches = 0, send_all_tags = 0;
9883 struct got_reference *ref = NULL;
9884 int *pack_fds = NULL;
9886 TAILQ_INIT(&branches);
9887 TAILQ_INIT(&tags);
9888 TAILQ_INIT(&all_branches);
9889 TAILQ_INIT(&all_tags);
9890 TAILQ_INIT(&delete_args);
9891 TAILQ_INIT(&delete_branches);
9893 while ((ch = getopt(argc, argv, "ab:d:fqr:Tt:v")) != -1) {
9894 switch (ch) {
9895 case 'a':
9896 send_all_branches = 1;
9897 break;
9898 case 'b':
9899 error = got_pathlist_append(&branches, optarg, NULL);
9900 if (error)
9901 return error;
9902 nbranches++;
9903 break;
9904 case 'd':
9905 error = got_pathlist_append(&delete_args, optarg, NULL);
9906 if (error)
9907 return error;
9908 break;
9909 case 'f':
9910 overwrite_refs = 1;
9911 break;
9912 case 'q':
9913 verbosity = -1;
9914 break;
9915 case 'r':
9916 repo_path = realpath(optarg, NULL);
9917 if (repo_path == NULL)
9918 return got_error_from_errno2("realpath",
9919 optarg);
9920 got_path_strip_trailing_slashes(repo_path);
9921 break;
9922 case 'T':
9923 send_all_tags = 1;
9924 break;
9925 case 't':
9926 error = got_pathlist_append(&tags, optarg, NULL);
9927 if (error)
9928 return error;
9929 break;
9930 case 'v':
9931 if (verbosity < 0)
9932 verbosity = 0;
9933 else if (verbosity < 3)
9934 verbosity++;
9935 break;
9936 default:
9937 usage_send();
9938 /* NOTREACHED */
9941 argc -= optind;
9942 argv += optind;
9944 if (send_all_branches && !TAILQ_EMPTY(&branches))
9945 option_conflict('a', 'b');
9946 if (send_all_tags && !TAILQ_EMPTY(&tags))
9947 option_conflict('T', 't');
9950 if (argc == 0)
9951 remote_name = GOT_SEND_DEFAULT_REMOTE_NAME;
9952 else if (argc == 1)
9953 remote_name = argv[0];
9954 else
9955 usage_send();
9957 cwd = getcwd(NULL, 0);
9958 if (cwd == NULL) {
9959 error = got_error_from_errno("getcwd");
9960 goto done;
9963 error = got_repo_pack_fds_open(&pack_fds);
9964 if (error != NULL)
9965 goto done;
9967 if (repo_path == NULL) {
9968 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
9969 if (error && error->code != GOT_ERR_NOT_WORKTREE)
9970 goto done;
9971 else
9972 error = NULL;
9973 if (worktree) {
9974 repo_path =
9975 strdup(got_worktree_get_repo_path(worktree));
9976 if (repo_path == NULL)
9977 error = got_error_from_errno("strdup");
9978 if (error)
9979 goto done;
9980 } else {
9981 repo_path = strdup(cwd);
9982 if (repo_path == NULL) {
9983 error = got_error_from_errno("strdup");
9984 goto done;
9989 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
9990 if (error)
9991 goto done;
9993 if (worktree) {
9994 worktree_conf = got_worktree_get_gotconfig(worktree);
9995 if (worktree_conf) {
9996 got_gotconfig_get_remotes(&nremotes, &remotes,
9997 worktree_conf);
9998 for (i = 0; i < nremotes; i++) {
9999 if (strcmp(remotes[i].name, remote_name) == 0) {
10000 error = got_repo_remote_repo_dup(&remote,
10001 &remotes[i]);
10002 if (error)
10003 goto done;
10004 break;
10009 if (remote == NULL) {
10010 repo_conf = got_repo_get_gotconfig(repo);
10011 if (repo_conf) {
10012 got_gotconfig_get_remotes(&nremotes, &remotes,
10013 repo_conf);
10014 for (i = 0; i < nremotes; i++) {
10015 if (strcmp(remotes[i].name, remote_name) == 0) {
10016 error = got_repo_remote_repo_dup(&remote,
10017 &remotes[i]);
10018 if (error)
10019 goto done;
10020 break;
10025 if (remote == NULL) {
10026 got_repo_get_gitconfig_remotes(&nremotes, &remotes, repo);
10027 for (i = 0; i < nremotes; i++) {
10028 if (strcmp(remotes[i].name, remote_name) == 0) {
10029 error = got_repo_remote_repo_dup(&remote,
10030 &remotes[i]);
10031 if (error)
10032 goto done;
10033 break;
10037 if (remote == NULL) {
10038 error = got_error_path(remote_name, GOT_ERR_NO_REMOTE);
10039 goto done;
10042 error = got_dial_parse_uri(&proto, &host, &port, &server_path,
10043 &repo_name, remote->send_url);
10044 if (error)
10045 goto done;
10047 if (strcmp(proto, "git") == 0) {
10048 #ifndef PROFILE
10049 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
10050 "sendfd dns inet unveil", NULL) == -1)
10051 err(1, "pledge");
10052 #endif
10053 } else if (strcmp(proto, "git+ssh") == 0 ||
10054 strcmp(proto, "ssh") == 0) {
10055 #ifndef PROFILE
10056 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
10057 "sendfd unveil", NULL) == -1)
10058 err(1, "pledge");
10059 #endif
10060 } else if (strcmp(proto, "http") == 0 ||
10061 strcmp(proto, "git+http") == 0) {
10062 error = got_error_path(proto, GOT_ERR_NOT_IMPL);
10063 goto done;
10064 } else {
10065 error = got_error_path(proto, GOT_ERR_BAD_PROTO);
10066 goto done;
10069 error = got_dial_apply_unveil(proto);
10070 if (error)
10071 goto done;
10073 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
10074 if (error)
10075 goto done;
10077 if (send_all_branches) {
10078 error = got_ref_list(&all_branches, repo, "refs/heads",
10079 got_ref_cmp_by_name, NULL);
10080 if (error)
10081 goto done;
10082 TAILQ_FOREACH(re, &all_branches, entry) {
10083 const char *branchname = got_ref_get_name(re->ref);
10084 error = got_pathlist_append(&branches,
10085 branchname, NULL);
10086 if (error)
10087 goto done;
10088 nbranches++;
10090 } else if (nbranches == 0) {
10091 for (i = 0; i < remote->nsend_branches; i++) {
10092 error = got_pathlist_append(&branches,
10093 remote->send_branches[i], NULL);
10094 if (error)
10095 goto done;
10099 if (send_all_tags) {
10100 error = got_ref_list(&all_tags, repo, "refs/tags",
10101 got_ref_cmp_by_name, NULL);
10102 if (error)
10103 goto done;
10104 TAILQ_FOREACH(re, &all_tags, entry) {
10105 const char *tagname = got_ref_get_name(re->ref);
10106 error = got_pathlist_append(&tags,
10107 tagname, NULL);
10108 if (error)
10109 goto done;
10114 * To prevent accidents only branches in refs/heads/ can be deleted
10115 * with 'got send -d'.
10116 * Deleting anything else requires local repository access or Git.
10118 TAILQ_FOREACH(pe, &delete_args, entry) {
10119 const char *branchname = pe->path;
10120 char *s;
10121 struct got_pathlist_entry *new;
10122 if (strncmp(branchname, "refs/heads/", 11) == 0) {
10123 s = strdup(branchname);
10124 if (s == NULL) {
10125 error = got_error_from_errno("strdup");
10126 goto done;
10128 } else {
10129 if (asprintf(&s, "refs/heads/%s", branchname) == -1) {
10130 error = got_error_from_errno("asprintf");
10131 goto done;
10134 error = got_pathlist_insert(&new, &delete_branches, s, NULL);
10135 if (error || new == NULL /* duplicate */)
10136 free(s);
10137 if (error)
10138 goto done;
10139 ndelete_branches++;
10142 if (nbranches == 0 && ndelete_branches == 0) {
10143 struct got_reference *head_ref;
10144 if (worktree)
10145 error = got_ref_open(&head_ref, repo,
10146 got_worktree_get_head_ref_name(worktree), 0);
10147 else
10148 error = got_ref_open(&head_ref, repo, GOT_REF_HEAD, 0);
10149 if (error)
10150 goto done;
10151 if (got_ref_is_symbolic(head_ref)) {
10152 error = got_ref_resolve_symbolic(&ref, repo, head_ref);
10153 got_ref_close(head_ref);
10154 if (error)
10155 goto done;
10156 } else
10157 ref = head_ref;
10158 error = got_pathlist_append(&branches, got_ref_get_name(ref),
10159 NULL);
10160 if (error)
10161 goto done;
10162 nbranches++;
10165 if (worktree) {
10166 /* Release work tree lock. */
10167 got_worktree_close(worktree);
10168 worktree = NULL;
10171 if (verbosity >= 0) {
10172 printf("Connecting to \"%s\" %s://%s%s%s%s%s\n",
10173 remote->name, proto, host,
10174 port ? ":" : "", port ? port : "",
10175 *server_path == '/' ? "" : "/", server_path);
10178 error = got_send_connect(&sendpid, &sendfd, proto, host, port,
10179 server_path, verbosity);
10180 if (error)
10181 goto done;
10183 memset(&spa, 0, sizeof(spa));
10184 spa.last_scaled_packsize[0] = '\0';
10185 spa.last_p_deltify = -1;
10186 spa.last_p_written = -1;
10187 spa.verbosity = verbosity;
10188 spa.delete_branches = &delete_branches;
10189 error = got_send_pack(remote_name, &branches, &tags, &delete_branches,
10190 verbosity, overwrite_refs, sendfd, repo, send_progress, &spa,
10191 check_cancelled, NULL);
10192 if (spa.printed_something)
10193 putchar('\n');
10194 if (error)
10195 goto done;
10196 if (!spa.sent_something && verbosity >= 0)
10197 printf("Already up-to-date\n");
10198 done:
10199 if (sendpid > 0) {
10200 if (kill(sendpid, SIGTERM) == -1)
10201 error = got_error_from_errno("kill");
10202 if (waitpid(sendpid, &sendstatus, 0) == -1 && error == NULL)
10203 error = got_error_from_errno("waitpid");
10205 if (sendfd != -1 && close(sendfd) == -1 && error == NULL)
10206 error = got_error_from_errno("close");
10207 if (repo) {
10208 const struct got_error *close_err = got_repo_close(repo);
10209 if (error == NULL)
10210 error = close_err;
10212 if (worktree)
10213 got_worktree_close(worktree);
10214 if (pack_fds) {
10215 const struct got_error *pack_err =
10216 got_repo_pack_fds_close(pack_fds);
10217 if (error == NULL)
10218 error = pack_err;
10220 if (ref)
10221 got_ref_close(ref);
10222 got_repo_free_remote_repo_data(remote);
10223 free(remote);
10224 got_pathlist_free(&branches, GOT_PATHLIST_FREE_NONE);
10225 got_pathlist_free(&tags, GOT_PATHLIST_FREE_NONE);
10226 got_ref_list_free(&all_branches);
10227 got_ref_list_free(&all_tags);
10228 got_pathlist_free(&delete_args, GOT_PATHLIST_FREE_NONE);
10229 got_pathlist_free(&delete_branches, GOT_PATHLIST_FREE_PATH);
10230 free(cwd);
10231 free(repo_path);
10232 free(proto);
10233 free(host);
10234 free(port);
10235 free(server_path);
10236 free(repo_name);
10237 return error;
10241 * Print and if delete is set delete all ref_prefix references.
10242 * If wanted_ref is not NULL, only print or delete this reference.
10244 static const struct got_error *
10245 process_logmsg_refs(const char *ref_prefix, size_t prefix_len,
10246 const char *wanted_ref, int delete, struct got_worktree *worktree,
10247 struct got_repository *repo)
10249 const struct got_error *err;
10250 struct got_pathlist_head paths;
10251 struct got_reflist_head refs;
10252 struct got_reflist_entry *re;
10253 struct got_reflist_object_id_map *refs_idmap = NULL;
10254 struct got_commit_object *commit = NULL;
10255 struct got_object_id *id = NULL;
10256 const char *header_prefix;
10257 char *uuidstr = NULL;
10258 int found = 0;
10260 TAILQ_INIT(&refs);
10261 TAILQ_INIT(&paths);
10263 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, repo);
10264 if (err)
10265 goto done;
10267 err = got_reflist_object_id_map_create(&refs_idmap, &refs, repo);
10268 if (err)
10269 goto done;
10271 if (worktree != NULL) {
10272 err = got_worktree_get_uuid(&uuidstr, worktree);
10273 if (err)
10274 goto done;
10277 if (wanted_ref) {
10278 if (strncmp(wanted_ref, "refs/heads/", 11) == 0)
10279 wanted_ref += 11;
10282 if (strcmp(ref_prefix, GOT_WORKTREE_BACKOUT_REF_PREFIX) == 0)
10283 header_prefix = "backout";
10284 else
10285 header_prefix = "cherrypick";
10287 TAILQ_FOREACH(re, &refs, entry) {
10288 const char *refname, *wt;
10290 refname = got_ref_get_name(re->ref);
10292 err = check_cancelled(NULL);
10293 if (err)
10294 goto done;
10296 if (strncmp(refname, ref_prefix, prefix_len) == 0)
10297 refname += prefix_len + 1; /* skip '-' delimiter */
10298 else
10299 continue;
10301 wt = refname;
10303 if (worktree == NULL || strncmp(refname, uuidstr,
10304 GOT_WORKTREE_UUID_STRLEN) == 0)
10305 refname += GOT_WORKTREE_UUID_STRLEN + 1; /* skip '-' */
10306 else
10307 continue;
10309 err = got_repo_match_object_id(&id, NULL, refname,
10310 GOT_OBJ_TYPE_COMMIT, NULL, repo);
10311 if (err)
10312 goto done;
10314 err = got_object_open_as_commit(&commit, repo, id);
10315 if (err)
10316 goto done;
10318 if (wanted_ref)
10319 found = strncmp(wanted_ref, refname,
10320 strlen(wanted_ref)) == 0;
10321 if (wanted_ref && !found) {
10322 struct got_reflist_head *ci_refs;
10324 ci_refs = got_reflist_object_id_map_lookup(refs_idmap,
10325 id);
10327 if (ci_refs) {
10328 char *refs_str = NULL;
10329 char const *r = NULL;
10331 err = build_refs_str(&refs_str, ci_refs, id,
10332 repo, 1);
10333 if (err)
10334 goto done;
10336 r = refs_str;
10337 while (r) {
10338 if (strncmp(r, wanted_ref,
10339 strlen(wanted_ref)) == 0) {
10340 found = 1;
10341 break;
10343 r = strchr(r, ' ');
10344 if (r)
10345 ++r;
10347 free(refs_str);
10351 if (wanted_ref == NULL || found) {
10352 if (delete) {
10353 err = got_ref_delete(re->ref, repo);
10354 if (err)
10355 goto done;
10356 printf("Deleted: ");
10357 err = print_commit_oneline(commit, id, repo,
10358 refs_idmap);
10359 } else {
10361 * Print paths modified by commit to help
10362 * associate commits with worktree changes.
10364 err = get_changed_paths(&paths, commit,
10365 repo, NULL);
10366 if (err)
10367 goto done;
10369 err = print_commit(commit, id, repo, NULL,
10370 &paths, NULL, 0, 0, refs_idmap, NULL,
10371 header_prefix);
10372 got_pathlist_free(&paths,
10373 GOT_PATHLIST_FREE_ALL);
10375 if (worktree == NULL)
10376 printf("work tree: %.*s\n\n",
10377 GOT_WORKTREE_UUID_STRLEN, wt);
10379 if (err || found)
10380 goto done;
10383 got_object_commit_close(commit);
10384 commit = NULL;
10385 free(id);
10386 id = NULL;
10389 if (wanted_ref != NULL && !found)
10390 err = got_error_fmt(GOT_ERR_NOT_REF, "%s", wanted_ref);
10392 done:
10393 free(id);
10394 free(uuidstr);
10395 got_ref_list_free(&refs);
10396 got_pathlist_free(&paths, GOT_PATHLIST_FREE_ALL);
10397 if (refs_idmap)
10398 got_reflist_object_id_map_free(refs_idmap);
10399 if (commit)
10400 got_object_commit_close(commit);
10401 return err;
10405 * Create new temp "logmsg" ref of the backed-out or cherrypicked commit
10406 * identified by id for log messages to prepopulate the editor on commit.
10408 static const struct got_error *
10409 logmsg_ref(struct got_object_id *id, const char *prefix,
10410 struct got_worktree *worktree, struct got_repository *repo)
10412 const struct got_error *err = NULL;
10413 char *idstr, *ref = NULL, *refname = NULL;
10414 int histedit_in_progress;
10415 int rebase_in_progress, merge_in_progress;
10418 * Silenty refuse to create merge reference if any histedit, merge,
10419 * or rebase operation is in progress.
10421 err = got_worktree_histedit_in_progress(&histedit_in_progress,
10422 worktree);
10423 if (err)
10424 return err;
10425 if (histedit_in_progress)
10426 return NULL;
10428 err = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
10429 if (err)
10430 return err;
10431 if (rebase_in_progress)
10432 return NULL;
10434 err = got_worktree_merge_in_progress(&merge_in_progress, worktree,
10435 repo);
10436 if (err)
10437 return err;
10438 if (merge_in_progress)
10439 return NULL;
10441 err = got_object_id_str(&idstr, id);
10442 if (err)
10443 return err;
10445 err = got_worktree_get_logmsg_ref_name(&refname, worktree, prefix);
10446 if (err)
10447 goto done;
10449 if (asprintf(&ref, "%s-%s", refname, idstr) == -1) {
10450 err = got_error_from_errno("asprintf");
10451 goto done;
10454 err = create_ref(ref, got_worktree_get_base_commit_id(worktree),
10455 -1, repo);
10456 done:
10457 free(ref);
10458 free(idstr);
10459 free(refname);
10460 return err;
10463 __dead static void
10464 usage_cherrypick(void)
10466 fprintf(stderr, "usage: %s cherrypick [-lX] [commit-id]\n",
10467 getprogname());
10468 exit(1);
10471 static const struct got_error *
10472 cmd_cherrypick(int argc, char *argv[])
10474 const struct got_error *error = NULL;
10475 struct got_worktree *worktree = NULL;
10476 struct got_repository *repo = NULL;
10477 char *cwd = NULL, *commit_id_str = NULL, *keyword_idstr = NULL;
10478 struct got_object_id *commit_id = NULL;
10479 struct got_commit_object *commit = NULL;
10480 struct got_object_qid *pid;
10481 int ch, list_refs = 0, remove_refs = 0;
10482 struct got_update_progress_arg upa;
10483 int *pack_fds = NULL;
10485 #ifndef PROFILE
10486 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
10487 "unveil", NULL) == -1)
10488 err(1, "pledge");
10489 #endif
10491 while ((ch = getopt(argc, argv, "lX")) != -1) {
10492 switch (ch) {
10493 case 'l':
10494 list_refs = 1;
10495 break;
10496 case 'X':
10497 remove_refs = 1;
10498 break;
10499 default:
10500 usage_cherrypick();
10501 /* NOTREACHED */
10505 argc -= optind;
10506 argv += optind;
10508 if (list_refs || remove_refs) {
10509 if (argc != 0 && argc != 1)
10510 usage_cherrypick();
10511 } else if (argc != 1)
10512 usage_cherrypick();
10513 if (list_refs && remove_refs)
10514 option_conflict('l', 'X');
10516 cwd = getcwd(NULL, 0);
10517 if (cwd == NULL) {
10518 error = got_error_from_errno("getcwd");
10519 goto done;
10522 error = got_repo_pack_fds_open(&pack_fds);
10523 if (error != NULL)
10524 goto done;
10526 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
10527 if (error) {
10528 if (list_refs || remove_refs) {
10529 if (error->code != GOT_ERR_NOT_WORKTREE)
10530 goto done;
10531 } else {
10532 if (error->code == GOT_ERR_NOT_WORKTREE)
10533 error = wrap_not_worktree_error(error,
10534 "cherrypick", cwd);
10535 goto done;
10539 error = got_repo_open(&repo,
10540 worktree ? got_worktree_get_repo_path(worktree) : cwd,
10541 NULL, pack_fds);
10542 if (error != NULL)
10543 goto done;
10545 error = apply_unveil(got_repo_get_path(repo), 0,
10546 worktree ? got_worktree_get_root_path(worktree) : NULL);
10547 if (error)
10548 goto done;
10550 if (list_refs || remove_refs) {
10551 error = process_logmsg_refs(GOT_WORKTREE_CHERRYPICK_REF_PREFIX,
10552 GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN,
10553 argc == 1 ? argv[0] : NULL, remove_refs, worktree, repo);
10554 goto done;
10557 error = got_keyword_to_idstr(&keyword_idstr, argv[0], repo, worktree);
10558 if (error != NULL)
10559 goto done;
10561 error = got_repo_match_object_id(&commit_id, NULL,
10562 keyword_idstr != NULL ? keyword_idstr : argv[0],
10563 GOT_OBJ_TYPE_COMMIT, NULL, repo);
10564 if (error)
10565 goto done;
10566 error = got_object_id_str(&commit_id_str, commit_id);
10567 if (error)
10568 goto done;
10570 error = got_object_open_as_commit(&commit, repo, commit_id);
10571 if (error)
10572 goto done;
10573 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
10574 memset(&upa, 0, sizeof(upa));
10575 error = got_worktree_merge_files(worktree, pid ? &pid->id : NULL,
10576 commit_id, repo, update_progress, &upa, check_cancelled,
10577 NULL);
10578 if (error != NULL)
10579 goto done;
10581 if (upa.did_something) {
10582 error = logmsg_ref(commit_id,
10583 GOT_WORKTREE_CHERRYPICK_REF_PREFIX, worktree, repo);
10584 if (error)
10585 goto done;
10586 printf("Merged commit %s\n", commit_id_str);
10588 print_merge_progress_stats(&upa);
10589 done:
10590 free(cwd);
10591 free(keyword_idstr);
10592 if (commit)
10593 got_object_commit_close(commit);
10594 free(commit_id_str);
10595 if (worktree)
10596 got_worktree_close(worktree);
10597 if (repo) {
10598 const struct got_error *close_err = got_repo_close(repo);
10599 if (error == NULL)
10600 error = close_err;
10602 if (pack_fds) {
10603 const struct got_error *pack_err =
10604 got_repo_pack_fds_close(pack_fds);
10605 if (error == NULL)
10606 error = pack_err;
10609 return error;
10612 __dead static void
10613 usage_backout(void)
10615 fprintf(stderr, "usage: %s backout [-lX] [commit-id]\n", getprogname());
10616 exit(1);
10619 static const struct got_error *
10620 cmd_backout(int argc, char *argv[])
10622 const struct got_error *error = NULL;
10623 struct got_worktree *worktree = NULL;
10624 struct got_repository *repo = NULL;
10625 char *cwd = NULL, *commit_id_str = NULL, *keyword_idstr = NULL;
10626 struct got_object_id *commit_id = NULL;
10627 struct got_commit_object *commit = NULL;
10628 struct got_object_qid *pid;
10629 int ch, list_refs = 0, remove_refs = 0;
10630 struct got_update_progress_arg upa;
10631 int *pack_fds = NULL;
10633 #ifndef PROFILE
10634 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
10635 "unveil", NULL) == -1)
10636 err(1, "pledge");
10637 #endif
10639 while ((ch = getopt(argc, argv, "lX")) != -1) {
10640 switch (ch) {
10641 case 'l':
10642 list_refs = 1;
10643 break;
10644 case 'X':
10645 remove_refs = 1;
10646 break;
10647 default:
10648 usage_backout();
10649 /* NOTREACHED */
10653 argc -= optind;
10654 argv += optind;
10656 if (list_refs || remove_refs) {
10657 if (argc != 0 && argc != 1)
10658 usage_backout();
10659 } else if (argc != 1)
10660 usage_backout();
10661 if (list_refs && remove_refs)
10662 option_conflict('l', 'X');
10664 cwd = getcwd(NULL, 0);
10665 if (cwd == NULL) {
10666 error = got_error_from_errno("getcwd");
10667 goto done;
10670 error = got_repo_pack_fds_open(&pack_fds);
10671 if (error != NULL)
10672 goto done;
10674 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
10675 if (error) {
10676 if (list_refs || remove_refs) {
10677 if (error->code != GOT_ERR_NOT_WORKTREE)
10678 goto done;
10679 } else {
10680 if (error->code == GOT_ERR_NOT_WORKTREE)
10681 error = wrap_not_worktree_error(error,
10682 "backout", cwd);
10683 goto done;
10687 error = got_repo_open(&repo,
10688 worktree ? got_worktree_get_repo_path(worktree) : cwd,
10689 NULL, pack_fds);
10690 if (error != NULL)
10691 goto done;
10693 error = apply_unveil(got_repo_get_path(repo), 0,
10694 worktree ? got_worktree_get_root_path(worktree) : NULL);
10695 if (error)
10696 goto done;
10698 if (list_refs || remove_refs) {
10699 error = process_logmsg_refs(GOT_WORKTREE_BACKOUT_REF_PREFIX,
10700 GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN,
10701 argc == 1 ? argv[0] : NULL, remove_refs, worktree, repo);
10702 goto done;
10705 error = got_keyword_to_idstr(&keyword_idstr, argv[0], repo, worktree);
10706 if (error != NULL)
10707 goto done;
10709 error = got_repo_match_object_id(&commit_id, NULL,
10710 keyword_idstr != NULL ? keyword_idstr : argv[0],
10711 GOT_OBJ_TYPE_COMMIT, NULL, repo);
10712 if (error)
10713 goto done;
10714 error = got_object_id_str(&commit_id_str, commit_id);
10715 if (error)
10716 goto done;
10718 error = got_object_open_as_commit(&commit, repo, commit_id);
10719 if (error)
10720 goto done;
10721 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
10722 if (pid == NULL) {
10723 error = got_error(GOT_ERR_ROOT_COMMIT);
10724 goto done;
10727 memset(&upa, 0, sizeof(upa));
10728 error = got_worktree_merge_files(worktree, commit_id, &pid->id,
10729 repo, update_progress, &upa, check_cancelled, NULL);
10730 if (error != NULL)
10731 goto done;
10733 if (upa.did_something) {
10734 error = logmsg_ref(commit_id, GOT_WORKTREE_BACKOUT_REF_PREFIX,
10735 worktree, repo);
10736 if (error)
10737 goto done;
10738 printf("Backed out commit %s\n", commit_id_str);
10740 print_merge_progress_stats(&upa);
10741 done:
10742 free(cwd);
10743 free(keyword_idstr);
10744 if (commit)
10745 got_object_commit_close(commit);
10746 free(commit_id_str);
10747 if (worktree)
10748 got_worktree_close(worktree);
10749 if (repo) {
10750 const struct got_error *close_err = got_repo_close(repo);
10751 if (error == NULL)
10752 error = close_err;
10754 if (pack_fds) {
10755 const struct got_error *pack_err =
10756 got_repo_pack_fds_close(pack_fds);
10757 if (error == NULL)
10758 error = pack_err;
10760 return error;
10763 __dead static void
10764 usage_rebase(void)
10766 fprintf(stderr, "usage: %s rebase [-aCclX] [branch]\n", getprogname());
10767 exit(1);
10770 static void
10771 trim_logmsg(char *logmsg, int limit)
10773 char *nl;
10774 size_t len;
10776 len = strlen(logmsg);
10777 if (len > limit)
10778 len = limit;
10779 logmsg[len] = '\0';
10780 nl = strchr(logmsg, '\n');
10781 if (nl)
10782 *nl = '\0';
10785 static const struct got_error *
10786 get_short_logmsg(char **logmsg, int limit, struct got_commit_object *commit)
10788 const struct got_error *err;
10789 char *logmsg0 = NULL;
10790 const char *s;
10792 err = got_object_commit_get_logmsg(&logmsg0, commit);
10793 if (err)
10794 return err;
10796 s = logmsg0;
10797 while (isspace((unsigned char)s[0]))
10798 s++;
10800 *logmsg = strdup(s);
10801 if (*logmsg == NULL) {
10802 err = got_error_from_errno("strdup");
10803 goto done;
10806 trim_logmsg(*logmsg, limit);
10807 done:
10808 free(logmsg0);
10809 return err;
10812 static const struct got_error *
10813 show_rebase_merge_conflict(struct got_object_id *id,
10814 struct got_repository *repo)
10816 const struct got_error *err;
10817 struct got_commit_object *commit = NULL;
10818 char *id_str = NULL, *logmsg = NULL;
10820 err = got_object_open_as_commit(&commit, repo, id);
10821 if (err)
10822 return err;
10824 err = got_object_id_str(&id_str, id);
10825 if (err)
10826 goto done;
10828 id_str[12] = '\0';
10830 err = get_short_logmsg(&logmsg, 42, commit);
10831 if (err)
10832 goto done;
10834 printf("%s -> merge conflict: %s\n", id_str, logmsg);
10835 done:
10836 free(id_str);
10837 got_object_commit_close(commit);
10838 free(logmsg);
10839 return err;
10842 static const struct got_error *
10843 show_rebase_progress(struct got_commit_object *commit,
10844 struct got_object_id *old_id, struct got_object_id *new_id)
10846 const struct got_error *err;
10847 char *old_id_str = NULL, *new_id_str = NULL, *logmsg = NULL;
10849 err = got_object_id_str(&old_id_str, old_id);
10850 if (err)
10851 goto done;
10853 if (new_id) {
10854 err = got_object_id_str(&new_id_str, new_id);
10855 if (err)
10856 goto done;
10859 old_id_str[12] = '\0';
10860 if (new_id_str)
10861 new_id_str[12] = '\0';
10863 err = get_short_logmsg(&logmsg, 42, commit);
10864 if (err)
10865 goto done;
10867 printf("%s -> %s: %s\n", old_id_str,
10868 new_id_str ? new_id_str : "no-op change", logmsg);
10869 done:
10870 free(old_id_str);
10871 free(new_id_str);
10872 free(logmsg);
10873 return err;
10876 static const struct got_error *
10877 rebase_complete(struct got_worktree *worktree, struct got_fileindex *fileindex,
10878 struct got_reference *branch, struct got_reference *tmp_branch,
10879 struct got_repository *repo, int create_backup)
10881 printf("Switching work tree to %s\n", got_ref_get_name(branch));
10882 return got_worktree_rebase_complete(worktree, fileindex,
10883 tmp_branch, branch, repo, create_backup);
10886 static const struct got_error *
10887 rebase_commit(struct got_pathlist_head *merged_paths,
10888 struct got_worktree *worktree, struct got_fileindex *fileindex,
10889 struct got_reference *tmp_branch, const char *committer,
10890 struct got_object_id *commit_id, int allow_conflict,
10891 struct got_repository *repo)
10893 const struct got_error *error;
10894 struct got_commit_object *commit;
10895 struct got_object_id *new_commit_id;
10897 error = got_object_open_as_commit(&commit, repo, commit_id);
10898 if (error)
10899 return error;
10901 error = got_worktree_rebase_commit(&new_commit_id, merged_paths,
10902 worktree, fileindex, tmp_branch, committer, commit, commit_id,
10903 allow_conflict, repo);
10904 if (error) {
10905 if (error->code != GOT_ERR_COMMIT_NO_CHANGES)
10906 goto done;
10907 error = show_rebase_progress(commit, commit_id, NULL);
10908 } else {
10909 error = show_rebase_progress(commit, commit_id, new_commit_id);
10910 free(new_commit_id);
10912 done:
10913 got_object_commit_close(commit);
10914 return error;
10917 struct check_path_prefix_arg {
10918 const char *path_prefix;
10919 size_t len;
10920 int errcode;
10923 static const struct got_error *
10924 check_path_prefix_in_diff(void *arg, struct got_blob_object *blob1,
10925 struct got_blob_object *blob2, FILE *f1, FILE *f2,
10926 struct got_object_id *id1, struct got_object_id *id2,
10927 const char *path1, const char *path2,
10928 mode_t mode1, mode_t mode2, struct got_repository *repo)
10930 struct check_path_prefix_arg *a = arg;
10932 if ((path1 && !got_path_is_child(path1, a->path_prefix, a->len)) ||
10933 (path2 && !got_path_is_child(path2, a->path_prefix, a->len)))
10934 return got_error(a->errcode);
10936 return NULL;
10939 static const struct got_error *
10940 check_path_prefix(struct got_object_id *parent_id,
10941 struct got_object_id *commit_id, const char *path_prefix,
10942 int errcode, struct got_repository *repo)
10944 const struct got_error *err;
10945 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
10946 struct got_commit_object *commit = NULL, *parent_commit = NULL;
10947 struct check_path_prefix_arg cpp_arg;
10949 if (got_path_is_root_dir(path_prefix))
10950 return NULL;
10952 err = got_object_open_as_commit(&commit, repo, commit_id);
10953 if (err)
10954 goto done;
10956 err = got_object_open_as_commit(&parent_commit, repo, parent_id);
10957 if (err)
10958 goto done;
10960 err = got_object_open_as_tree(&tree1, repo,
10961 got_object_commit_get_tree_id(parent_commit));
10962 if (err)
10963 goto done;
10965 err = got_object_open_as_tree(&tree2, repo,
10966 got_object_commit_get_tree_id(commit));
10967 if (err)
10968 goto done;
10970 cpp_arg.path_prefix = path_prefix;
10971 while (cpp_arg.path_prefix[0] == '/')
10972 cpp_arg.path_prefix++;
10973 cpp_arg.len = strlen(cpp_arg.path_prefix);
10974 cpp_arg.errcode = errcode;
10975 err = got_diff_tree(tree1, tree2, NULL, NULL, -1, -1, "", "", repo,
10976 check_path_prefix_in_diff, &cpp_arg, 0);
10977 done:
10978 if (tree1)
10979 got_object_tree_close(tree1);
10980 if (tree2)
10981 got_object_tree_close(tree2);
10982 if (commit)
10983 got_object_commit_close(commit);
10984 if (parent_commit)
10985 got_object_commit_close(parent_commit);
10986 return err;
10989 static const struct got_error *
10990 collect_commits(struct got_object_id_queue *commits,
10991 struct got_object_id *initial_commit_id,
10992 struct got_object_id *iter_start_id, struct got_object_id *iter_stop_id,
10993 const char *path_prefix, int path_prefix_errcode,
10994 struct got_repository *repo)
10996 const struct got_error *err = NULL;
10997 struct got_commit_graph *graph = NULL;
10998 struct got_object_id parent_id, commit_id;
10999 struct got_object_qid *qid;
11001 err = got_commit_graph_open(&graph, "/", 1);
11002 if (err)
11003 return err;
11005 err = got_commit_graph_bfsort(graph, iter_start_id, repo,
11006 check_cancelled, NULL);
11007 if (err)
11008 goto done;
11010 memcpy(&commit_id, initial_commit_id, sizeof(commit_id));
11011 while (got_object_id_cmp(&commit_id, iter_stop_id) != 0) {
11012 err = got_commit_graph_iter_next(&parent_id, graph, repo,
11013 check_cancelled, NULL);
11014 if (err) {
11015 if (err->code == GOT_ERR_ITER_COMPLETED) {
11016 err = got_error_msg(GOT_ERR_ANCESTRY,
11017 "ran out of commits to rebase before "
11018 "youngest common ancestor commit has "
11019 "been reached?!?");
11021 goto done;
11022 } else {
11023 err = check_path_prefix(&parent_id, &commit_id,
11024 path_prefix, path_prefix_errcode, repo);
11025 if (err)
11026 goto done;
11028 err = got_object_qid_alloc(&qid, &commit_id);
11029 if (err)
11030 goto done;
11031 STAILQ_INSERT_HEAD(commits, qid, entry);
11033 memcpy(&commit_id, &parent_id, sizeof(commit_id));
11036 done:
11037 got_commit_graph_close(graph);
11038 return err;
11041 static const struct got_error *
11042 get_commit_brief_str(char **brief_str, struct got_commit_object *commit)
11044 const struct got_error *err = NULL;
11045 time_t committer_time;
11046 struct tm tm;
11047 char datebuf[11]; /* YYYY-MM-DD + NUL */
11048 char *author0 = NULL, *author, *smallerthan;
11049 char *logmsg0 = NULL, *logmsg, *newline;
11051 committer_time = got_object_commit_get_committer_time(commit);
11052 if (gmtime_r(&committer_time, &tm) == NULL)
11053 return got_error_from_errno("gmtime_r");
11054 if (strftime(datebuf, sizeof(datebuf), "%F", &tm) == 0)
11055 return got_error(GOT_ERR_NO_SPACE);
11057 author0 = strdup(got_object_commit_get_author(commit));
11058 if (author0 == NULL)
11059 return got_error_from_errno("strdup");
11060 author = author0;
11061 smallerthan = strchr(author, '<');
11062 if (smallerthan && smallerthan[1] != '\0')
11063 author = smallerthan + 1;
11064 author[strcspn(author, "@>")] = '\0';
11066 err = got_object_commit_get_logmsg(&logmsg0, commit);
11067 if (err)
11068 goto done;
11069 logmsg = logmsg0;
11070 while (*logmsg == '\n')
11071 logmsg++;
11072 newline = strchr(logmsg, '\n');
11073 if (newline)
11074 *newline = '\0';
11076 if (asprintf(brief_str, "%s %s %s",
11077 datebuf, author, logmsg) == -1)
11078 err = got_error_from_errno("asprintf");
11079 done:
11080 free(author0);
11081 free(logmsg0);
11082 return err;
11085 static const struct got_error *
11086 delete_backup_ref(struct got_reference *ref, struct got_object_id *id,
11087 struct got_repository *repo)
11089 const struct got_error *err;
11090 char *id_str;
11092 err = got_object_id_str(&id_str, id);
11093 if (err)
11094 return err;
11096 err = got_ref_delete(ref, repo);
11097 if (err)
11098 goto done;
11100 printf("Deleted %s: %s\n", got_ref_get_name(ref), id_str);
11101 done:
11102 free(id_str);
11103 return err;
11106 static const struct got_error *
11107 print_backup_ref(const char *branch_name, const char *new_id_str,
11108 struct got_object_id *old_commit_id, struct got_commit_object *old_commit,
11109 struct got_reflist_object_id_map *refs_idmap,
11110 struct got_repository *repo)
11112 const struct got_error *err = NULL;
11113 struct got_reflist_head *refs;
11114 char *refs_str = NULL;
11115 struct got_object_id *new_commit_id = NULL;
11116 struct got_commit_object *new_commit = NULL;
11117 char *new_commit_brief_str = NULL;
11118 struct got_object_id *yca_id = NULL;
11119 struct got_commit_object *yca_commit = NULL;
11120 char *yca_id_str = NULL, *yca_brief_str = NULL;
11121 char *custom_refs_str;
11123 if (asprintf(&custom_refs_str, "formerly %s", branch_name) == -1)
11124 return got_error_from_errno("asprintf");
11126 err = print_commit(old_commit, old_commit_id, repo, NULL, NULL, NULL,
11127 0, 0, refs_idmap, custom_refs_str, NULL);
11128 if (err)
11129 goto done;
11131 err = got_object_resolve_id_str(&new_commit_id, repo, new_id_str);
11132 if (err)
11133 goto done;
11135 refs = got_reflist_object_id_map_lookup(refs_idmap, new_commit_id);
11136 if (refs) {
11137 err = build_refs_str(&refs_str, refs, new_commit_id, repo, 0);
11138 if (err)
11139 goto done;
11142 err = got_object_open_as_commit(&new_commit, repo, new_commit_id);
11143 if (err)
11144 goto done;
11146 err = get_commit_brief_str(&new_commit_brief_str, new_commit);
11147 if (err)
11148 goto done;
11150 err = got_commit_graph_find_youngest_common_ancestor(&yca_id,
11151 old_commit_id, new_commit_id, 1, 0, repo, check_cancelled, NULL);
11152 if (err)
11153 goto done;
11155 printf("has become commit %s%s%s%s\n %s\n", new_id_str,
11156 refs_str ? " (" : "", refs_str ? refs_str : "",
11157 refs_str ? ")" : "", new_commit_brief_str);
11158 if (yca_id && got_object_id_cmp(yca_id, new_commit_id) != 0 &&
11159 got_object_id_cmp(yca_id, old_commit_id) != 0) {
11160 free(refs_str);
11161 refs_str = NULL;
11163 err = got_object_open_as_commit(&yca_commit, repo, yca_id);
11164 if (err)
11165 goto done;
11167 err = get_commit_brief_str(&yca_brief_str, yca_commit);
11168 if (err)
11169 goto done;
11171 err = got_object_id_str(&yca_id_str, yca_id);
11172 if (err)
11173 goto done;
11175 refs = got_reflist_object_id_map_lookup(refs_idmap, yca_id);
11176 if (refs) {
11177 err = build_refs_str(&refs_str, refs, yca_id, repo, 0);
11178 if (err)
11179 goto done;
11181 printf("history forked at %s%s%s%s\n %s\n",
11182 yca_id_str,
11183 refs_str ? " (" : "", refs_str ? refs_str : "",
11184 refs_str ? ")" : "", yca_brief_str);
11186 done:
11187 free(custom_refs_str);
11188 free(new_commit_id);
11189 free(refs_str);
11190 free(yca_id);
11191 free(yca_id_str);
11192 free(yca_brief_str);
11193 if (new_commit)
11194 got_object_commit_close(new_commit);
11195 if (yca_commit)
11196 got_object_commit_close(yca_commit);
11198 return err;
11201 static const struct got_error *
11202 worktree_has_logmsg_ref(const char *caller, struct got_worktree *worktree,
11203 struct got_repository *repo)
11205 const struct got_error *err;
11206 struct got_reflist_head refs;
11207 struct got_reflist_entry *re;
11208 char *uuidstr = NULL;
11209 static char msg[160];
11211 TAILQ_INIT(&refs);
11213 err = got_worktree_get_uuid(&uuidstr, worktree);
11214 if (err)
11215 goto done;
11217 err = got_ref_list(&refs, repo, "refs/got/worktree",
11218 got_ref_cmp_by_name, repo);
11219 if (err)
11220 goto done;
11222 TAILQ_FOREACH(re, &refs, entry) {
11223 const char *cmd, *refname, *type;
11225 refname = got_ref_get_name(re->ref);
11227 if (strncmp(refname, GOT_WORKTREE_CHERRYPICK_REF_PREFIX,
11228 GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN) == 0) {
11229 refname += GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN + 1;
11230 cmd = "cherrypick";
11231 type = "cherrypicked";
11232 } else if (strncmp(refname, GOT_WORKTREE_BACKOUT_REF_PREFIX,
11233 GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN) == 0) {
11234 refname += GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN + 1;
11235 cmd = "backout";
11236 type = "backed-out";
11237 } else
11238 continue;
11240 if (strncmp(refname, uuidstr, GOT_WORKTREE_UUID_STRLEN) != 0)
11241 continue;
11243 snprintf(msg, sizeof(msg),
11244 "work tree has references created by %s commits which "
11245 "must be removed with 'got %s -X' before running the %s "
11246 "command", type, cmd, caller);
11247 err = got_error_msg(GOT_ERR_WORKTREE_META, msg);
11248 goto done;
11251 done:
11252 free(uuidstr);
11253 got_ref_list_free(&refs);
11254 return err;
11257 static const struct got_error *
11258 process_backup_refs(const char *backup_ref_prefix,
11259 const char *wanted_branch_name,
11260 int delete, struct got_repository *repo)
11262 const struct got_error *err;
11263 struct got_reflist_head refs, backup_refs;
11264 struct got_reflist_entry *re;
11265 const size_t backup_ref_prefix_len = strlen(backup_ref_prefix);
11266 struct got_object_id *old_commit_id = NULL;
11267 char *branch_name = NULL;
11268 struct got_commit_object *old_commit = NULL;
11269 struct got_reflist_object_id_map *refs_idmap = NULL;
11270 int wanted_branch_found = 0;
11272 TAILQ_INIT(&refs);
11273 TAILQ_INIT(&backup_refs);
11275 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
11276 if (err)
11277 return err;
11279 err = got_reflist_object_id_map_create(&refs_idmap, &refs, repo);
11280 if (err)
11281 goto done;
11283 if (wanted_branch_name) {
11284 if (strncmp(wanted_branch_name, "refs/heads/", 11) == 0)
11285 wanted_branch_name += 11;
11288 err = got_ref_list(&backup_refs, repo, backup_ref_prefix,
11289 got_ref_cmp_by_commit_timestamp_descending, repo);
11290 if (err)
11291 goto done;
11293 TAILQ_FOREACH(re, &backup_refs, entry) {
11294 const char *refname = got_ref_get_name(re->ref);
11295 char *slash;
11297 err = check_cancelled(NULL);
11298 if (err)
11299 break;
11301 err = got_ref_resolve(&old_commit_id, repo, re->ref);
11302 if (err)
11303 break;
11305 err = got_object_open_as_commit(&old_commit, repo,
11306 old_commit_id);
11307 if (err)
11308 break;
11310 if (strncmp(backup_ref_prefix, refname,
11311 backup_ref_prefix_len) == 0)
11312 refname += backup_ref_prefix_len;
11314 while (refname[0] == '/')
11315 refname++;
11317 branch_name = strdup(refname);
11318 if (branch_name == NULL) {
11319 err = got_error_from_errno("strdup");
11320 break;
11322 slash = strrchr(branch_name, '/');
11323 if (slash) {
11324 *slash = '\0';
11325 refname += strlen(branch_name) + 1;
11328 if (wanted_branch_name == NULL ||
11329 strcmp(wanted_branch_name, branch_name) == 0) {
11330 wanted_branch_found = 1;
11331 if (delete) {
11332 err = delete_backup_ref(re->ref,
11333 old_commit_id, repo);
11334 } else {
11335 err = print_backup_ref(branch_name, refname,
11336 old_commit_id, old_commit, refs_idmap,
11337 repo);
11339 if (err)
11340 break;
11343 free(old_commit_id);
11344 old_commit_id = NULL;
11345 free(branch_name);
11346 branch_name = NULL;
11347 got_object_commit_close(old_commit);
11348 old_commit = NULL;
11351 if (wanted_branch_name && !wanted_branch_found) {
11352 err = got_error_fmt(GOT_ERR_NOT_REF,
11353 "%s/%s/", backup_ref_prefix, wanted_branch_name);
11355 done:
11356 if (refs_idmap)
11357 got_reflist_object_id_map_free(refs_idmap);
11358 got_ref_list_free(&refs);
11359 got_ref_list_free(&backup_refs);
11360 free(old_commit_id);
11361 free(branch_name);
11362 if (old_commit)
11363 got_object_commit_close(old_commit);
11364 return err;
11367 static const struct got_error *
11368 abort_progress(void *arg, unsigned char status, const char *path)
11371 * Unversioned files should not clutter progress output when
11372 * an operation is aborted.
11374 if (status == GOT_STATUS_UNVERSIONED)
11375 return NULL;
11377 return update_progress(arg, status, path);
11380 static const struct got_error *
11381 find_merge_commit_yca(struct got_object_id **new_yca_id,
11382 struct got_object_id *branch_head_commit_id,
11383 struct got_object_id *yca_id,
11384 struct got_object_id *base_commit_id,
11385 struct got_repository *repo)
11387 const struct got_error *err = NULL;
11388 struct got_commit_graph *graph = NULL;
11389 struct got_commit_object *commit = NULL;
11391 *new_yca_id = NULL;
11393 err = got_commit_graph_open(&graph, "/", 1);
11394 if (err)
11395 return err;
11397 err = got_commit_graph_bfsort(graph, base_commit_id,
11398 repo, check_cancelled, NULL);
11399 if (err)
11400 goto done;
11402 for (;;) {
11403 struct got_object_id id;
11405 err = got_commit_graph_iter_next(&id, graph, repo,
11406 check_cancelled, NULL);
11407 if (err) {
11408 if (err->code == GOT_ERR_ITER_COMPLETED)
11409 err = NULL;
11410 break;
11413 err = got_object_open_as_commit(&commit, repo, &id);
11414 if (err)
11415 break;
11417 if (got_object_commit_get_nparents(commit) > 1) {
11418 /* Search for a better YCA using toposort. */
11419 err = got_commit_graph_find_youngest_common_ancestor(
11420 new_yca_id, base_commit_id, branch_head_commit_id,
11421 0, 1, repo, check_cancelled, NULL);
11422 break;
11425 if (got_object_id_cmp(&id, yca_id) == 0)
11426 break;
11427 got_object_commit_close(commit);
11428 commit = NULL;
11430 done:
11431 got_commit_graph_close(graph);
11432 if (commit)
11433 got_object_commit_close(commit);
11434 return err;
11437 static const struct got_error *
11438 cmd_rebase(int argc, char *argv[])
11440 const struct got_error *error = NULL;
11441 struct got_worktree *worktree = NULL;
11442 struct got_repository *repo = NULL;
11443 struct got_fileindex *fileindex = NULL;
11444 char *cwd = NULL, *committer = NULL, *gitconfig_path = NULL;
11445 struct got_reference *branch = NULL;
11446 struct got_reference *new_base_branch = NULL, *tmp_branch = NULL;
11447 struct got_object_id *commit_id = NULL, *parent_id = NULL;
11448 struct got_object_id *resume_commit_id = NULL;
11449 struct got_object_id *branch_head_commit_id = NULL, *yca_id = NULL;
11450 struct got_object_id *head_commit_id = NULL;
11451 struct got_reference *head_ref = NULL;
11452 struct got_commit_object *commit = NULL;
11453 int ch, rebase_in_progress = 0, abort_rebase = 0, continue_rebase = 0;
11454 int histedit_in_progress = 0, merge_in_progress = 0;
11455 int create_backup = 1, list_backups = 0, delete_backups = 0;
11456 int allow_conflict = 0;
11457 struct got_object_id_queue commits;
11458 struct got_pathlist_head merged_paths;
11459 const struct got_object_id_queue *parent_ids;
11460 struct got_object_qid *qid, *pid;
11461 struct got_update_progress_arg upa;
11462 int *pack_fds = NULL;
11464 STAILQ_INIT(&commits);
11465 TAILQ_INIT(&merged_paths);
11466 memset(&upa, 0, sizeof(upa));
11468 #ifndef PROFILE
11469 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
11470 "unveil", NULL) == -1)
11471 err(1, "pledge");
11472 #endif
11474 while ((ch = getopt(argc, argv, "aCclX")) != -1) {
11475 switch (ch) {
11476 case 'a':
11477 abort_rebase = 1;
11478 break;
11479 case 'C':
11480 allow_conflict = 1;
11481 break;
11482 case 'c':
11483 continue_rebase = 1;
11484 break;
11485 case 'l':
11486 list_backups = 1;
11487 break;
11488 case 'X':
11489 delete_backups = 1;
11490 break;
11491 default:
11492 usage_rebase();
11493 /* NOTREACHED */
11497 argc -= optind;
11498 argv += optind;
11500 if (list_backups) {
11501 if (abort_rebase)
11502 option_conflict('l', 'a');
11503 if (allow_conflict)
11504 option_conflict('l', 'C');
11505 if (continue_rebase)
11506 option_conflict('l', 'c');
11507 if (delete_backups)
11508 option_conflict('l', 'X');
11509 if (argc != 0 && argc != 1)
11510 usage_rebase();
11511 } else if (delete_backups) {
11512 if (abort_rebase)
11513 option_conflict('X', 'a');
11514 if (allow_conflict)
11515 option_conflict('X', 'C');
11516 if (continue_rebase)
11517 option_conflict('X', 'c');
11518 if (list_backups)
11519 option_conflict('l', 'X');
11520 if (argc != 0 && argc != 1)
11521 usage_rebase();
11522 } else if (allow_conflict) {
11523 if (abort_rebase)
11524 option_conflict('C', 'a');
11525 if (!continue_rebase)
11526 errx(1, "-C option requires -c");
11527 } else {
11528 if (abort_rebase && continue_rebase)
11529 usage_rebase();
11530 else if (abort_rebase || continue_rebase) {
11531 if (argc != 0)
11532 usage_rebase();
11533 } else if (argc != 1)
11534 usage_rebase();
11537 cwd = getcwd(NULL, 0);
11538 if (cwd == NULL) {
11539 error = got_error_from_errno("getcwd");
11540 goto done;
11543 error = got_repo_pack_fds_open(&pack_fds);
11544 if (error != NULL)
11545 goto done;
11547 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
11548 if (error) {
11549 if (list_backups || delete_backups) {
11550 if (error->code != GOT_ERR_NOT_WORKTREE)
11551 goto done;
11552 } else {
11553 if (error->code == GOT_ERR_NOT_WORKTREE)
11554 error = wrap_not_worktree_error(error,
11555 "rebase", cwd);
11556 goto done;
11560 error = get_gitconfig_path(&gitconfig_path);
11561 if (error)
11562 goto done;
11563 error = got_repo_open(&repo,
11564 worktree ? got_worktree_get_repo_path(worktree) : cwd,
11565 gitconfig_path, pack_fds);
11566 if (error != NULL)
11567 goto done;
11569 if (worktree != NULL && !list_backups && !delete_backups) {
11570 error = worktree_has_logmsg_ref("rebase", worktree, repo);
11571 if (error)
11572 goto done;
11575 error = get_author(&committer, repo, worktree);
11576 if (error && error->code != GOT_ERR_COMMIT_NO_AUTHOR)
11577 goto done;
11579 error = apply_unveil(got_repo_get_path(repo), 0,
11580 worktree ? got_worktree_get_root_path(worktree) : NULL);
11581 if (error)
11582 goto done;
11584 if (list_backups || delete_backups) {
11585 error = process_backup_refs(
11586 GOT_WORKTREE_REBASE_BACKUP_REF_PREFIX,
11587 argc == 1 ? argv[0] : NULL, delete_backups, repo);
11588 goto done; /* nothing else to do */
11591 error = got_worktree_histedit_in_progress(&histedit_in_progress,
11592 worktree);
11593 if (error)
11594 goto done;
11595 if (histedit_in_progress) {
11596 error = got_error(GOT_ERR_HISTEDIT_BUSY);
11597 goto done;
11600 error = got_worktree_merge_in_progress(&merge_in_progress,
11601 worktree, repo);
11602 if (error)
11603 goto done;
11604 if (merge_in_progress) {
11605 error = got_error(GOT_ERR_MERGE_BUSY);
11606 goto done;
11609 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
11610 if (error)
11611 goto done;
11613 if (abort_rebase) {
11614 if (!rebase_in_progress) {
11615 error = got_error(GOT_ERR_NOT_REBASING);
11616 goto done;
11618 error = got_worktree_rebase_continue(&resume_commit_id,
11619 &new_base_branch, &tmp_branch, &branch, &fileindex,
11620 worktree, repo);
11621 if (error)
11622 goto done;
11623 printf("Switching work tree to %s\n",
11624 got_ref_get_symref_target(new_base_branch));
11625 error = got_worktree_rebase_abort(worktree, fileindex, repo,
11626 new_base_branch, abort_progress, &upa);
11627 if (error)
11628 goto done;
11629 printf("Rebase of %s aborted\n", got_ref_get_name(branch));
11630 print_merge_progress_stats(&upa);
11631 goto done; /* nothing else to do */
11634 if (continue_rebase) {
11635 if (!rebase_in_progress) {
11636 error = got_error(GOT_ERR_NOT_REBASING);
11637 goto done;
11639 error = got_worktree_rebase_continue(&resume_commit_id,
11640 &new_base_branch, &tmp_branch, &branch, &fileindex,
11641 worktree, repo);
11642 if (error)
11643 goto done;
11645 error = rebase_commit(NULL, worktree, fileindex, tmp_branch,
11646 committer, resume_commit_id, allow_conflict, repo);
11647 if (error)
11648 goto done;
11650 yca_id = got_object_id_dup(resume_commit_id);
11651 if (yca_id == NULL) {
11652 error = got_error_from_errno("got_object_id_dup");
11653 goto done;
11655 } else {
11656 error = got_ref_open(&branch, repo, argv[0], 0);
11657 if (error != NULL)
11658 goto done;
11659 if (strncmp(got_ref_get_name(branch), "refs/heads/", 11) != 0) {
11660 error = got_error_msg(GOT_ERR_COMMIT_BRANCH,
11661 "will not rebase a branch which lives outside "
11662 "the \"refs/heads/\" reference namespace");
11663 goto done;
11667 error = got_ref_resolve(&branch_head_commit_id, repo, branch);
11668 if (error)
11669 goto done;
11671 if (!continue_rebase) {
11672 struct got_object_id *base_commit_id;
11674 error = got_ref_open(&head_ref, repo,
11675 got_worktree_get_head_ref_name(worktree), 0);
11676 if (error)
11677 goto done;
11678 error = got_ref_resolve(&head_commit_id, repo, head_ref);
11679 if (error)
11680 goto done;
11681 base_commit_id = got_worktree_get_base_commit_id(worktree);
11682 if (got_object_id_cmp(base_commit_id, head_commit_id) != 0) {
11683 error = got_error(GOT_ERR_REBASE_OUT_OF_DATE);
11684 goto done;
11687 error = got_commit_graph_find_youngest_common_ancestor(&yca_id,
11688 base_commit_id, branch_head_commit_id, 1, 0,
11689 repo, check_cancelled, NULL);
11690 if (error) {
11691 if (error->code == GOT_ERR_ANCESTRY) {
11692 error = got_error_msg(GOT_ERR_ANCESTRY,
11693 "specified branch shares no common "
11694 "ancestry with work tree's branch");
11696 goto done;
11700 * If a merge commit appears between the new base branch tip
11701 * and a YCA found via first-parent traversal then we might
11702 * find a better YCA using topologically sorted commits.
11704 if (got_object_id_cmp(base_commit_id, yca_id) != 0) {
11705 struct got_object_id *better_yca_id;
11706 error = find_merge_commit_yca(&better_yca_id,
11707 branch_head_commit_id, yca_id,
11708 base_commit_id, repo);
11709 if (error)
11710 goto done;
11711 if (better_yca_id) {
11712 free(yca_id);
11713 yca_id = better_yca_id;
11717 if (got_object_id_cmp(base_commit_id, yca_id) == 0) {
11718 struct got_pathlist_head paths;
11719 const char *branch_name = got_ref_get_name(branch);
11720 const char *base =
11721 got_worktree_get_head_ref_name(worktree);
11723 if (strcmp(branch_name, base) == 0) {
11724 error = got_error_fmt(GOT_ERR_WRONG_BRANCH,
11725 "cannot rebase %s onto itself",
11726 branch_name);
11727 goto done;
11728 } else {
11729 printf("%s is already based on %s\n",
11730 branch_name, base);
11732 error = switch_head_ref(branch, branch_head_commit_id,
11733 worktree, repo);
11734 if (error)
11735 goto done;
11736 error = got_worktree_set_base_commit_id(worktree, repo,
11737 branch_head_commit_id);
11738 if (error)
11739 goto done;
11740 TAILQ_INIT(&paths);
11741 error = got_pathlist_append(&paths, "", NULL);
11742 if (error)
11743 goto done;
11744 error = got_worktree_checkout_files(worktree,
11745 &paths, repo, update_progress, &upa,
11746 check_cancelled, NULL);
11747 got_pathlist_free(&paths, GOT_PATHLIST_FREE_NONE);
11748 if (error)
11749 goto done;
11750 if (upa.did_something) {
11751 char *id_str;
11752 error = got_object_id_str(&id_str,
11753 branch_head_commit_id);
11754 if (error)
11755 goto done;
11756 printf("Updated to %s: %s\n",
11757 got_worktree_get_head_ref_name(worktree),
11758 id_str);
11759 free(id_str);
11760 } else
11761 printf("Already up-to-date\n");
11762 print_update_progress_stats(&upa);
11763 goto done;
11767 commit_id = branch_head_commit_id;
11768 error = got_object_open_as_commit(&commit, repo, commit_id);
11769 if (error)
11770 goto done;
11772 parent_ids = got_object_commit_get_parent_ids(commit);
11773 pid = STAILQ_FIRST(parent_ids);
11774 if (pid) {
11775 error = collect_commits(&commits, commit_id, &pid->id,
11776 yca_id, got_worktree_get_path_prefix(worktree),
11777 GOT_ERR_REBASE_PATH, repo);
11778 if (error)
11779 goto done;
11782 got_object_commit_close(commit);
11783 commit = NULL;
11785 if (!continue_rebase) {
11786 error = got_worktree_rebase_prepare(&new_base_branch,
11787 &tmp_branch, &fileindex, worktree, branch, repo);
11788 if (error)
11789 goto done;
11792 if (STAILQ_EMPTY(&commits)) {
11793 if (continue_rebase) {
11794 error = rebase_complete(worktree, fileindex,
11795 branch, tmp_branch, repo, create_backup);
11796 goto done;
11797 } else {
11798 /* Fast-forward the reference of the branch. */
11799 struct got_object_id *new_head_commit_id;
11800 char *id_str;
11801 error = got_ref_resolve(&new_head_commit_id, repo,
11802 new_base_branch);
11803 if (error)
11804 goto done;
11805 error = got_object_id_str(&id_str, new_head_commit_id);
11806 if (error)
11807 goto done;
11808 printf("Forwarding %s to commit %s\n",
11809 got_ref_get_name(branch), id_str);
11810 free(id_str);
11811 error = got_ref_change_ref(branch,
11812 new_head_commit_id);
11813 if (error)
11814 goto done;
11815 /* No backup needed since objects did not change. */
11816 create_backup = 0;
11820 pid = NULL;
11821 STAILQ_FOREACH(qid, &commits, entry) {
11823 commit_id = &qid->id;
11824 parent_id = pid ? &pid->id : yca_id;
11825 pid = qid;
11827 memset(&upa, 0, sizeof(upa));
11828 error = got_worktree_rebase_merge_files(&merged_paths,
11829 worktree, fileindex, parent_id, commit_id, repo,
11830 update_progress, &upa, check_cancelled, NULL);
11831 if (error)
11832 goto done;
11834 print_merge_progress_stats(&upa);
11835 if (upa.conflicts > 0 || upa.missing > 0 ||
11836 upa.not_deleted > 0 || upa.unversioned > 0) {
11837 if (upa.conflicts > 0) {
11838 error = show_rebase_merge_conflict(&qid->id,
11839 repo);
11840 if (error)
11841 goto done;
11843 got_pathlist_free(&merged_paths, GOT_PATHLIST_FREE_PATH);
11844 break;
11847 error = rebase_commit(&merged_paths, worktree, fileindex,
11848 tmp_branch, committer, commit_id, 0, repo);
11849 got_pathlist_free(&merged_paths, GOT_PATHLIST_FREE_PATH);
11850 if (error)
11851 goto done;
11854 if (upa.conflicts > 0 || upa.missing > 0 ||
11855 upa.not_deleted > 0 || upa.unversioned > 0) {
11856 error = got_worktree_rebase_postpone(worktree, fileindex);
11857 if (error)
11858 goto done;
11859 if (upa.conflicts > 0 && upa.missing == 0 &&
11860 upa.not_deleted == 0 && upa.unversioned == 0) {
11861 error = got_error_msg(GOT_ERR_CONFLICTS,
11862 "conflicts must be resolved before rebasing "
11863 "can continue");
11864 } else if (upa.conflicts > 0) {
11865 error = got_error_msg(GOT_ERR_CONFLICTS,
11866 "conflicts must be resolved before rebasing "
11867 "can continue; changes destined for some "
11868 "files were not yet merged and should be "
11869 "merged manually if required before the "
11870 "rebase operation is continued");
11871 } else {
11872 error = got_error_msg(GOT_ERR_CONFLICTS,
11873 "changes destined for some files were not "
11874 "yet merged and should be merged manually "
11875 "if required before the rebase operation "
11876 "is continued");
11878 } else
11879 error = rebase_complete(worktree, fileindex, branch,
11880 tmp_branch, repo, create_backup);
11881 done:
11882 free(cwd);
11883 free(committer);
11884 free(gitconfig_path);
11885 got_object_id_queue_free(&commits);
11886 free(branch_head_commit_id);
11887 free(resume_commit_id);
11888 free(head_commit_id);
11889 free(yca_id);
11890 if (commit)
11891 got_object_commit_close(commit);
11892 if (branch)
11893 got_ref_close(branch);
11894 if (new_base_branch)
11895 got_ref_close(new_base_branch);
11896 if (tmp_branch)
11897 got_ref_close(tmp_branch);
11898 if (head_ref)
11899 got_ref_close(head_ref);
11900 if (worktree)
11901 got_worktree_close(worktree);
11902 if (repo) {
11903 const struct got_error *close_err = got_repo_close(repo);
11904 if (error == NULL)
11905 error = close_err;
11907 if (pack_fds) {
11908 const struct got_error *pack_err =
11909 got_repo_pack_fds_close(pack_fds);
11910 if (error == NULL)
11911 error = pack_err;
11913 return error;
11916 __dead static void
11917 usage_histedit(void)
11919 fprintf(stderr, "usage: %s histedit [-aCcdeflmX] [-F histedit-script] "
11920 "[branch]\n", getprogname());
11921 exit(1);
11924 #define GOT_HISTEDIT_PICK 'p'
11925 #define GOT_HISTEDIT_EDIT 'e'
11926 #define GOT_HISTEDIT_FOLD 'f'
11927 #define GOT_HISTEDIT_DROP 'd'
11928 #define GOT_HISTEDIT_MESG 'm'
11930 static const struct got_histedit_cmd {
11931 unsigned char code;
11932 const char *name;
11933 const char *desc;
11934 } got_histedit_cmds[] = {
11935 { GOT_HISTEDIT_PICK, "pick", "use commit" },
11936 { GOT_HISTEDIT_EDIT, "edit", "use commit but stop for amending" },
11937 { GOT_HISTEDIT_FOLD, "fold", "combine with next commit that will "
11938 "be used" },
11939 { GOT_HISTEDIT_DROP, "drop", "remove commit from history" },
11940 { GOT_HISTEDIT_MESG, "mesg", "open editor to edit the log message" },
11943 struct got_histedit_list_entry {
11944 TAILQ_ENTRY(got_histedit_list_entry) entry;
11945 struct got_object_id *commit_id;
11946 const struct got_histedit_cmd *cmd;
11947 char *logmsg;
11949 TAILQ_HEAD(got_histedit_list, got_histedit_list_entry);
11951 static const struct got_error *
11952 histedit_write_commit(struct got_object_id *commit_id, const char *cmdname,
11953 FILE *f, struct got_repository *repo)
11955 const struct got_error *err = NULL;
11956 char *logmsg = NULL, *id_str = NULL;
11957 struct got_commit_object *commit = NULL;
11958 int n;
11960 err = got_object_open_as_commit(&commit, repo, commit_id);
11961 if (err)
11962 goto done;
11964 err = get_short_logmsg(&logmsg, 34, commit);
11965 if (err)
11966 goto done;
11968 err = got_object_id_str(&id_str, commit_id);
11969 if (err)
11970 goto done;
11972 n = fprintf(f, "%s %s %s\n", cmdname, id_str, logmsg);
11973 if (n < 0)
11974 err = got_ferror(f, GOT_ERR_IO);
11975 done:
11976 if (commit)
11977 got_object_commit_close(commit);
11978 free(id_str);
11979 free(logmsg);
11980 return err;
11983 static const struct got_error *
11984 histedit_write_commit_list(struct got_object_id_queue *commits,
11985 FILE *f, int edit_logmsg_only, int fold_only, int drop_only,
11986 int edit_only, struct got_repository *repo)
11988 const struct got_error *err = NULL;
11989 struct got_object_qid *qid;
11990 const char *histedit_cmd = NULL;
11992 if (STAILQ_EMPTY(commits))
11993 return got_error(GOT_ERR_EMPTY_HISTEDIT);
11995 STAILQ_FOREACH(qid, commits, entry) {
11996 histedit_cmd = got_histedit_cmds[0].name;
11997 if (drop_only)
11998 histedit_cmd = "drop";
11999 else if (edit_only)
12000 histedit_cmd = "edit";
12001 else if (fold_only && STAILQ_NEXT(qid, entry) != NULL)
12002 histedit_cmd = "fold";
12003 else if (edit_logmsg_only)
12004 histedit_cmd = "mesg";
12005 err = histedit_write_commit(&qid->id, histedit_cmd, f, repo);
12006 if (err)
12007 break;
12010 return err;
12013 static const struct got_error *
12014 write_cmd_list(FILE *f, const char *branch_name,
12015 struct got_object_id_queue *commits)
12017 const struct got_error *err = NULL;
12018 size_t i;
12019 int n;
12020 char *id_str;
12021 struct got_object_qid *qid;
12023 qid = STAILQ_FIRST(commits);
12024 err = got_object_id_str(&id_str, &qid->id);
12025 if (err)
12026 return err;
12028 n = fprintf(f,
12029 "# Editing the history of branch '%s' starting at\n"
12030 "# commit %s\n"
12031 "# Commits will be processed in order from top to "
12032 "bottom of this file.\n", branch_name, id_str);
12033 if (n < 0) {
12034 err = got_ferror(f, GOT_ERR_IO);
12035 goto done;
12038 n = fprintf(f, "# Available histedit commands:\n");
12039 if (n < 0) {
12040 err = got_ferror(f, GOT_ERR_IO);
12041 goto done;
12044 for (i = 0; i < nitems(got_histedit_cmds); i++) {
12045 const struct got_histedit_cmd *cmd = &got_histedit_cmds[i];
12046 n = fprintf(f, "# %s (%c): %s\n", cmd->name, cmd->code,
12047 cmd->desc);
12048 if (n < 0) {
12049 err = got_ferror(f, GOT_ERR_IO);
12050 break;
12053 done:
12054 free(id_str);
12055 return err;
12058 static const struct got_error *
12059 histedit_syntax_error(int lineno)
12061 static char msg[42];
12062 int ret;
12064 ret = snprintf(msg, sizeof(msg), "histedit syntax error on line %d",
12065 lineno);
12066 if (ret < 0 || (size_t)ret >= sizeof(msg))
12067 return got_error(GOT_ERR_HISTEDIT_SYNTAX);
12069 return got_error_msg(GOT_ERR_HISTEDIT_SYNTAX, msg);
12072 static const struct got_error *
12073 append_folded_commit_msg(char **new_msg, struct got_histedit_list_entry *hle,
12074 char *logmsg, struct got_repository *repo)
12076 const struct got_error *err;
12077 struct got_commit_object *folded_commit = NULL;
12078 char *id_str, *folded_logmsg = NULL;
12080 err = got_object_id_str(&id_str, hle->commit_id);
12081 if (err)
12082 return err;
12084 err = got_object_open_as_commit(&folded_commit, repo, hle->commit_id);
12085 if (err)
12086 goto done;
12088 err = got_object_commit_get_logmsg(&folded_logmsg, folded_commit);
12089 if (err)
12090 goto done;
12091 if (asprintf(new_msg, "%s%s# log message of folded commit %s: %s",
12092 logmsg ? logmsg : "", logmsg ? "\n" : "", id_str,
12093 folded_logmsg) == -1) {
12094 err = got_error_from_errno("asprintf");
12096 done:
12097 if (folded_commit)
12098 got_object_commit_close(folded_commit);
12099 free(id_str);
12100 free(folded_logmsg);
12101 return err;
12104 static struct got_histedit_list_entry *
12105 get_folded_commits(struct got_histedit_list_entry *hle)
12107 struct got_histedit_list_entry *prev, *folded = NULL;
12109 prev = TAILQ_PREV(hle, got_histedit_list, entry);
12110 while (prev && (prev->cmd->code == GOT_HISTEDIT_FOLD ||
12111 prev->cmd->code == GOT_HISTEDIT_DROP)) {
12112 if (prev->cmd->code == GOT_HISTEDIT_FOLD)
12113 folded = prev;
12114 prev = TAILQ_PREV(prev, got_histedit_list, entry);
12117 return folded;
12120 static const struct got_error *
12121 histedit_edit_logmsg(struct got_histedit_list_entry *hle,
12122 const char *editor, struct got_repository *repo)
12124 char *logmsg_path = NULL, *id_str = NULL, *orig_logmsg = NULL;
12125 char *logmsg = NULL, *new_msg = NULL;
12126 const struct got_error *err = NULL;
12127 struct got_commit_object *commit = NULL;
12128 int logmsg_len;
12129 int fd = -1;
12130 struct got_histedit_list_entry *folded = NULL;
12132 err = got_object_open_as_commit(&commit, repo, hle->commit_id);
12133 if (err)
12134 return err;
12136 folded = get_folded_commits(hle);
12137 if (folded) {
12138 while (folded != hle) {
12139 if (folded->cmd->code == GOT_HISTEDIT_DROP) {
12140 folded = TAILQ_NEXT(folded, entry);
12141 continue;
12143 err = append_folded_commit_msg(&new_msg, folded,
12144 logmsg, repo);
12145 if (err)
12146 goto done;
12147 free(logmsg);
12148 logmsg = new_msg;
12149 folded = TAILQ_NEXT(folded, entry);
12153 err = got_object_id_str(&id_str, hle->commit_id);
12154 if (err)
12155 goto done;
12156 err = got_object_commit_get_logmsg(&orig_logmsg, commit);
12157 if (err)
12158 goto done;
12159 logmsg_len = asprintf(&new_msg,
12160 "%s\n# original log message of commit %s: %s",
12161 logmsg ? logmsg : "", id_str, orig_logmsg);
12162 if (logmsg_len == -1) {
12163 err = got_error_from_errno("asprintf");
12164 goto done;
12166 free(logmsg);
12167 logmsg = new_msg;
12169 err = got_object_id_str(&id_str, hle->commit_id);
12170 if (err)
12171 goto done;
12173 err = got_opentemp_named_fd(&logmsg_path, &fd,
12174 GOT_TMPDIR_STR "/got-logmsg", "");
12175 if (err)
12176 goto done;
12178 if (write(fd, logmsg, logmsg_len) == -1) {
12179 err = got_error_from_errno2("write", logmsg_path);
12180 goto done;
12182 if (close(fd) == -1) {
12183 err = got_error_from_errno2("close", logmsg_path);
12184 goto done;
12186 fd = -1;
12188 err = edit_logmsg(&hle->logmsg, editor, logmsg_path, logmsg,
12189 logmsg_len, 0);
12190 if (err) {
12191 if (err->code != GOT_ERR_COMMIT_MSG_EMPTY)
12192 goto done;
12193 err = NULL;
12194 hle->logmsg = strdup(new_msg);
12195 if (hle->logmsg == NULL)
12196 err = got_error_from_errno("strdup");
12198 done:
12199 if (fd != -1 && close(fd) == -1 && err == NULL)
12200 err = got_error_from_errno2("close", logmsg_path);
12201 if (logmsg_path && unlink(logmsg_path) != 0 && err == NULL)
12202 err = got_error_from_errno2("unlink", logmsg_path);
12203 free(logmsg_path);
12204 free(logmsg);
12205 free(orig_logmsg);
12206 if (commit)
12207 got_object_commit_close(commit);
12208 return err;
12211 static const struct got_error *
12212 histedit_parse_list(struct got_histedit_list *histedit_cmds,
12213 FILE *f, struct got_repository *repo)
12215 const struct got_error *err = NULL;
12216 char *line = NULL, *p, *end;
12217 size_t i, linesize = 0;
12218 ssize_t linelen;
12219 int lineno = 0;
12220 const struct got_histedit_cmd *cmd;
12221 struct got_object_id *commit_id = NULL;
12222 struct got_histedit_list_entry *hle = NULL;
12224 for (;;) {
12225 linelen = getline(&line, &linesize, f);
12226 if (linelen == -1) {
12227 const struct got_error *getline_err;
12228 if (feof(f))
12229 break;
12230 getline_err = got_error_from_errno("getline");
12231 err = got_ferror(f, getline_err->code);
12232 break;
12234 lineno++;
12235 p = line;
12236 while (isspace((unsigned char)p[0]))
12237 p++;
12238 if (p[0] == '#' || p[0] == '\0')
12239 continue;
12240 cmd = NULL;
12241 for (i = 0; i < nitems(got_histedit_cmds); i++) {
12242 cmd = &got_histedit_cmds[i];
12243 if (strncmp(cmd->name, p, strlen(cmd->name)) == 0 &&
12244 isspace((unsigned char)p[strlen(cmd->name)])) {
12245 p += strlen(cmd->name);
12246 break;
12248 if (p[0] == cmd->code && isspace((unsigned char)p[1])) {
12249 p++;
12250 break;
12253 if (i == nitems(got_histedit_cmds)) {
12254 err = histedit_syntax_error(lineno);
12255 break;
12257 while (isspace((unsigned char)p[0]))
12258 p++;
12259 end = p;
12260 while (end[0] && !isspace((unsigned char)end[0]))
12261 end++;
12262 *end = '\0';
12263 err = got_object_resolve_id_str(&commit_id, repo, p);
12264 if (err) {
12265 /* override error code */
12266 err = histedit_syntax_error(lineno);
12267 break;
12269 hle = malloc(sizeof(*hle));
12270 if (hle == NULL) {
12271 err = got_error_from_errno("malloc");
12272 break;
12274 hle->cmd = cmd;
12275 hle->commit_id = commit_id;
12276 hle->logmsg = NULL;
12277 commit_id = NULL;
12278 TAILQ_INSERT_TAIL(histedit_cmds, hle, entry);
12281 free(line);
12282 free(commit_id);
12283 return err;
12286 static const struct got_error *
12287 histedit_check_script(struct got_histedit_list *histedit_cmds,
12288 struct got_object_id_queue *commits, struct got_repository *repo)
12290 const struct got_error *err = NULL;
12291 struct got_object_qid *qid;
12292 struct got_histedit_list_entry *hle;
12293 static char msg[92];
12294 char *id_str;
12296 if (TAILQ_EMPTY(histedit_cmds))
12297 return got_error_msg(GOT_ERR_EMPTY_HISTEDIT,
12298 "histedit script contains no commands");
12299 if (STAILQ_EMPTY(commits))
12300 return got_error(GOT_ERR_EMPTY_HISTEDIT);
12302 TAILQ_FOREACH(hle, histedit_cmds, entry) {
12303 struct got_histedit_list_entry *hle2;
12304 TAILQ_FOREACH(hle2, histedit_cmds, entry) {
12305 if (hle == hle2)
12306 continue;
12307 if (got_object_id_cmp(hle->commit_id,
12308 hle2->commit_id) != 0)
12309 continue;
12310 err = got_object_id_str(&id_str, hle->commit_id);
12311 if (err)
12312 return err;
12313 snprintf(msg, sizeof(msg), "commit %s is listed "
12314 "more than once in histedit script", id_str);
12315 free(id_str);
12316 return got_error_msg(GOT_ERR_HISTEDIT_CMD, msg);
12320 STAILQ_FOREACH(qid, commits, entry) {
12321 TAILQ_FOREACH(hle, histedit_cmds, entry) {
12322 if (got_object_id_cmp(&qid->id, hle->commit_id) == 0)
12323 break;
12325 if (hle == NULL) {
12326 err = got_object_id_str(&id_str, &qid->id);
12327 if (err)
12328 return err;
12329 snprintf(msg, sizeof(msg),
12330 "commit %s missing from histedit script", id_str);
12331 free(id_str);
12332 return got_error_msg(GOT_ERR_HISTEDIT_CMD, msg);
12336 hle = TAILQ_LAST(histedit_cmds, got_histedit_list);
12337 if (hle && hle->cmd->code == GOT_HISTEDIT_FOLD)
12338 return got_error_msg(GOT_ERR_HISTEDIT_CMD,
12339 "last commit in histedit script cannot be folded");
12341 return NULL;
12344 static const struct got_error *
12345 histedit_run_editor(struct got_histedit_list *histedit_cmds,
12346 const char *editor, const char *path,
12347 struct got_object_id_queue *commits, struct got_repository *repo)
12349 const struct got_error *err = NULL;
12350 struct stat st, st2;
12351 struct timespec timeout;
12352 FILE *f = NULL;
12354 if (stat(path, &st) == -1) {
12355 err = got_error_from_errno2("stat", path);
12356 goto done;
12359 if (spawn_editor(editor, path) == -1) {
12360 err = got_error_from_errno("failed spawning editor");
12361 goto done;
12364 timeout.tv_sec = 0;
12365 timeout.tv_nsec = 1;
12366 nanosleep(&timeout, NULL);
12368 if (stat(path, &st2) == -1) {
12369 err = got_error_from_errno2("stat", path);
12370 goto done;
12373 if (st.st_size == st2.st_size &&
12374 timespeccmp(&st.st_mtim, &st2.st_mtim, ==)) {
12375 err = got_error_msg(GOT_ERR_EMPTY_HISTEDIT,
12376 "no changes made to histedit script, aborting");
12377 goto done;
12380 f = fopen(path, "re");
12381 if (f == NULL) {
12382 err = got_error_from_errno("fopen");
12383 goto done;
12385 err = histedit_parse_list(histedit_cmds, f, repo);
12386 if (err)
12387 goto done;
12389 err = histedit_check_script(histedit_cmds, commits, repo);
12390 done:
12391 if (f && fclose(f) == EOF && err == NULL)
12392 err = got_error_from_errno("fclose");
12393 return err;
12396 static const struct got_error *
12397 histedit_edit_list_retry(struct got_histedit_list *, const struct got_error *,
12398 struct got_object_id_queue *, const char *, const char *, const char *,
12399 struct got_repository *);
12401 static const struct got_error *
12402 histedit_edit_script(struct got_histedit_list *histedit_cmds,
12403 struct got_object_id_queue *commits, const char *branch_name,
12404 int edit_logmsg_only, int fold_only, int drop_only, int edit_only,
12405 const char *editor, struct got_repository *repo)
12407 const struct got_error *err;
12408 FILE *f = NULL;
12409 char *path = NULL;
12411 err = got_opentemp_named(&path, &f, "got-histedit", "");
12412 if (err)
12413 return err;
12415 err = write_cmd_list(f, branch_name, commits);
12416 if (err)
12417 goto done;
12419 err = histedit_write_commit_list(commits, f, edit_logmsg_only,
12420 fold_only, drop_only, edit_only, repo);
12421 if (err)
12422 goto done;
12424 if (drop_only || edit_logmsg_only || fold_only || edit_only) {
12425 rewind(f);
12426 err = histedit_parse_list(histedit_cmds, f, repo);
12427 } else {
12428 if (fclose(f) == EOF) {
12429 err = got_error_from_errno("fclose");
12430 goto done;
12432 f = NULL;
12433 err = histedit_run_editor(histedit_cmds, editor, path,
12434 commits, repo);
12435 if (err) {
12436 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
12437 err->code != GOT_ERR_HISTEDIT_CMD)
12438 goto done;
12439 err = histedit_edit_list_retry(histedit_cmds, err,
12440 commits, editor, path, branch_name, repo);
12443 done:
12444 if (f && fclose(f) == EOF && err == NULL)
12445 err = got_error_from_errno("fclose");
12446 if (path && unlink(path) != 0 && err == NULL)
12447 err = got_error_from_errno2("unlink", path);
12448 free(path);
12449 return err;
12452 static const struct got_error *
12453 histedit_save_list(struct got_histedit_list *histedit_cmds,
12454 struct got_worktree *worktree, struct got_repository *repo)
12456 const struct got_error *err = NULL;
12457 char *path = NULL;
12458 FILE *f = NULL;
12459 struct got_histedit_list_entry *hle;
12461 err = got_worktree_get_histedit_script_path(&path, worktree);
12462 if (err)
12463 return err;
12465 f = fopen(path, "we");
12466 if (f == NULL) {
12467 err = got_error_from_errno2("fopen", path);
12468 goto done;
12470 TAILQ_FOREACH(hle, histedit_cmds, entry) {
12471 err = histedit_write_commit(hle->commit_id, hle->cmd->name, f,
12472 repo);
12473 if (err)
12474 break;
12476 done:
12477 if (f && fclose(f) == EOF && err == NULL)
12478 err = got_error_from_errno("fclose");
12479 free(path);
12480 return err;
12483 static void
12484 histedit_free_list(struct got_histedit_list *histedit_cmds)
12486 struct got_histedit_list_entry *hle;
12488 while ((hle = TAILQ_FIRST(histedit_cmds))) {
12489 TAILQ_REMOVE(histedit_cmds, hle, entry);
12490 free(hle);
12494 static const struct got_error *
12495 histedit_load_list(struct got_histedit_list *histedit_cmds,
12496 const char *path, struct got_repository *repo)
12498 const struct got_error *err = NULL;
12499 FILE *f = NULL;
12501 f = fopen(path, "re");
12502 if (f == NULL) {
12503 err = got_error_from_errno2("fopen", path);
12504 goto done;
12507 err = histedit_parse_list(histedit_cmds, f, repo);
12508 done:
12509 if (f && fclose(f) == EOF && err == NULL)
12510 err = got_error_from_errno("fclose");
12511 return err;
12514 static const struct got_error *
12515 histedit_edit_list_retry(struct got_histedit_list *histedit_cmds,
12516 const struct got_error *edit_err, struct got_object_id_queue *commits,
12517 const char *editor, const char *path, const char *branch_name,
12518 struct got_repository *repo)
12520 const struct got_error *err = NULL, *prev_err = edit_err;
12521 int resp = ' ';
12523 while (resp != 'c' && resp != 'r' && resp != 'a') {
12524 printf("%s: %s\n(c)ontinue editing, (r)estart editing, "
12525 "or (a)bort: ", getprogname(), prev_err->msg);
12526 resp = getchar();
12527 if (resp == '\n')
12528 resp = getchar();
12529 if (resp == 'c') {
12530 histedit_free_list(histedit_cmds);
12531 err = histedit_run_editor(histedit_cmds, editor, path,
12532 commits, repo);
12533 if (err) {
12534 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
12535 err->code != GOT_ERR_HISTEDIT_CMD)
12536 break;
12537 prev_err = err;
12538 resp = ' ';
12539 continue;
12541 break;
12542 } else if (resp == 'r') {
12543 histedit_free_list(histedit_cmds);
12544 err = histedit_edit_script(histedit_cmds,
12545 commits, branch_name, 0, 0, 0, 0, editor, repo);
12546 if (err) {
12547 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
12548 err->code != GOT_ERR_HISTEDIT_CMD)
12549 break;
12550 prev_err = err;
12551 resp = ' ';
12552 continue;
12554 break;
12555 } else if (resp == 'a') {
12556 err = got_error(GOT_ERR_HISTEDIT_CANCEL);
12557 break;
12558 } else
12559 printf("invalid response '%c'\n", resp);
12562 return err;
12565 static const struct got_error *
12566 histedit_complete(struct got_worktree *worktree,
12567 struct got_fileindex *fileindex, struct got_reference *tmp_branch,
12568 struct got_reference *branch, struct got_repository *repo)
12570 printf("Switching work tree to %s\n",
12571 got_ref_get_symref_target(branch));
12572 return got_worktree_histedit_complete(worktree, fileindex, tmp_branch,
12573 branch, repo);
12576 static const struct got_error *
12577 show_histedit_progress(struct got_commit_object *commit,
12578 struct got_histedit_list_entry *hle, struct got_object_id *new_id)
12580 const struct got_error *err;
12581 char *old_id_str = NULL, *new_id_str = NULL, *logmsg = NULL;
12583 err = got_object_id_str(&old_id_str, hle->commit_id);
12584 if (err)
12585 goto done;
12587 if (new_id) {
12588 err = got_object_id_str(&new_id_str, new_id);
12589 if (err)
12590 goto done;
12593 old_id_str[12] = '\0';
12594 if (new_id_str)
12595 new_id_str[12] = '\0';
12597 if (hle->logmsg) {
12598 logmsg = strdup(hle->logmsg);
12599 if (logmsg == NULL) {
12600 err = got_error_from_errno("strdup");
12601 goto done;
12603 trim_logmsg(logmsg, 42);
12604 } else {
12605 err = get_short_logmsg(&logmsg, 42, commit);
12606 if (err)
12607 goto done;
12610 switch (hle->cmd->code) {
12611 case GOT_HISTEDIT_PICK:
12612 case GOT_HISTEDIT_EDIT:
12613 case GOT_HISTEDIT_MESG:
12614 printf("%s -> %s: %s\n", old_id_str,
12615 new_id_str ? new_id_str : "no-op change", logmsg);
12616 break;
12617 case GOT_HISTEDIT_DROP:
12618 case GOT_HISTEDIT_FOLD:
12619 printf("%s -> %s commit: %s\n", old_id_str, hle->cmd->name,
12620 logmsg);
12621 break;
12622 default:
12623 break;
12625 done:
12626 free(old_id_str);
12627 free(new_id_str);
12628 return err;
12631 static const struct got_error *
12632 histedit_commit(struct got_pathlist_head *merged_paths,
12633 struct got_worktree *worktree, struct got_fileindex *fileindex,
12634 struct got_reference *tmp_branch, struct got_histedit_list_entry *hle,
12635 const char *committer, int allow_conflict, const char *editor,
12636 struct got_repository *repo)
12638 const struct got_error *err;
12639 struct got_commit_object *commit;
12640 struct got_object_id *new_commit_id;
12642 if ((hle->cmd->code == GOT_HISTEDIT_EDIT || get_folded_commits(hle))
12643 && hle->logmsg == NULL) {
12644 err = histedit_edit_logmsg(hle, editor, repo);
12645 if (err)
12646 return err;
12649 err = got_object_open_as_commit(&commit, repo, hle->commit_id);
12650 if (err)
12651 return err;
12653 err = got_worktree_histedit_commit(&new_commit_id, merged_paths,
12654 worktree, fileindex, tmp_branch, committer, commit, hle->commit_id,
12655 hle->logmsg, allow_conflict, repo);
12656 if (err) {
12657 if (err->code != GOT_ERR_COMMIT_NO_CHANGES)
12658 goto done;
12659 err = show_histedit_progress(commit, hle, NULL);
12660 } else {
12661 err = show_histedit_progress(commit, hle, new_commit_id);
12662 free(new_commit_id);
12664 done:
12665 got_object_commit_close(commit);
12666 return err;
12669 static const struct got_error *
12670 histedit_skip_commit(struct got_histedit_list_entry *hle,
12671 struct got_worktree *worktree, struct got_repository *repo)
12673 const struct got_error *error;
12674 struct got_commit_object *commit;
12676 error = got_worktree_histedit_skip_commit(worktree, hle->commit_id,
12677 repo);
12678 if (error)
12679 return error;
12681 error = got_object_open_as_commit(&commit, repo, hle->commit_id);
12682 if (error)
12683 return error;
12685 error = show_histedit_progress(commit, hle, NULL);
12686 got_object_commit_close(commit);
12687 return error;
12690 static const struct got_error *
12691 check_local_changes(void *arg, unsigned char status,
12692 unsigned char staged_status, const char *path,
12693 struct got_object_id *blob_id, struct got_object_id *staged_blob_id,
12694 struct got_object_id *commit_id, int dirfd, const char *de_name)
12696 int *have_local_changes = arg;
12698 switch (status) {
12699 case GOT_STATUS_ADD:
12700 case GOT_STATUS_DELETE:
12701 case GOT_STATUS_MODIFY:
12702 case GOT_STATUS_CONFLICT:
12703 *have_local_changes = 1;
12704 return got_error(GOT_ERR_CANCELLED);
12705 default:
12706 break;
12709 switch (staged_status) {
12710 case GOT_STATUS_ADD:
12711 case GOT_STATUS_DELETE:
12712 case GOT_STATUS_MODIFY:
12713 *have_local_changes = 1;
12714 return got_error(GOT_ERR_CANCELLED);
12715 default:
12716 break;
12719 return NULL;
12722 static const struct got_error *
12723 cmd_histedit(int argc, char *argv[])
12725 const struct got_error *error = NULL;
12726 struct got_worktree *worktree = NULL;
12727 struct got_fileindex *fileindex = NULL;
12728 struct got_repository *repo = NULL;
12729 char *cwd = NULL, *committer = NULL, *gitconfig_path = NULL;
12730 struct got_reference *branch = NULL;
12731 struct got_reference *tmp_branch = NULL;
12732 struct got_object_id *resume_commit_id = NULL;
12733 struct got_object_id *base_commit_id = NULL;
12734 struct got_object_id *head_commit_id = NULL;
12735 struct got_commit_object *commit = NULL;
12736 int ch, rebase_in_progress = 0, merge_in_progress = 0;
12737 struct got_update_progress_arg upa;
12738 int edit_in_progress = 0, abort_edit = 0, continue_edit = 0;
12739 int drop_only = 0, edit_logmsg_only = 0, fold_only = 0, edit_only = 0;
12740 int allow_conflict = 0, list_backups = 0, delete_backups = 0;
12741 const char *edit_script_path = NULL;
12742 char *editor = NULL;
12743 struct got_object_id_queue commits;
12744 struct got_pathlist_head merged_paths;
12745 const struct got_object_id_queue *parent_ids;
12746 struct got_object_qid *pid;
12747 struct got_histedit_list histedit_cmds;
12748 struct got_histedit_list_entry *hle;
12749 int *pack_fds = NULL;
12751 STAILQ_INIT(&commits);
12752 TAILQ_INIT(&histedit_cmds);
12753 TAILQ_INIT(&merged_paths);
12754 memset(&upa, 0, sizeof(upa));
12756 #ifndef PROFILE
12757 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
12758 "unveil", NULL) == -1)
12759 err(1, "pledge");
12760 #endif
12762 while ((ch = getopt(argc, argv, "aCcdeF:flmX")) != -1) {
12763 switch (ch) {
12764 case 'a':
12765 abort_edit = 1;
12766 break;
12767 case 'C':
12768 allow_conflict = 1;
12769 break;
12770 case 'c':
12771 continue_edit = 1;
12772 break;
12773 case 'd':
12774 drop_only = 1;
12775 break;
12776 case 'e':
12777 edit_only = 1;
12778 break;
12779 case 'F':
12780 edit_script_path = optarg;
12781 break;
12782 case 'f':
12783 fold_only = 1;
12784 break;
12785 case 'l':
12786 list_backups = 1;
12787 break;
12788 case 'm':
12789 edit_logmsg_only = 1;
12790 break;
12791 case 'X':
12792 delete_backups = 1;
12793 break;
12794 default:
12795 usage_histedit();
12796 /* NOTREACHED */
12800 argc -= optind;
12801 argv += optind;
12803 if (abort_edit && allow_conflict)
12804 option_conflict('a', 'C');
12805 if (abort_edit && continue_edit)
12806 option_conflict('a', 'c');
12807 if (edit_script_path && allow_conflict)
12808 option_conflict('F', 'C');
12809 if (edit_script_path && edit_logmsg_only)
12810 option_conflict('F', 'm');
12811 if (abort_edit && edit_logmsg_only)
12812 option_conflict('a', 'm');
12813 if (edit_logmsg_only && allow_conflict)
12814 option_conflict('m', 'C');
12815 if (continue_edit && edit_logmsg_only)
12816 option_conflict('c', 'm');
12817 if (abort_edit && fold_only)
12818 option_conflict('a', 'f');
12819 if (fold_only && allow_conflict)
12820 option_conflict('f', 'C');
12821 if (continue_edit && fold_only)
12822 option_conflict('c', 'f');
12823 if (fold_only && edit_logmsg_only)
12824 option_conflict('f', 'm');
12825 if (edit_script_path && fold_only)
12826 option_conflict('F', 'f');
12827 if (abort_edit && edit_only)
12828 option_conflict('a', 'e');
12829 if (continue_edit && edit_only)
12830 option_conflict('c', 'e');
12831 if (edit_only && edit_logmsg_only)
12832 option_conflict('e', 'm');
12833 if (edit_script_path && edit_only)
12834 option_conflict('F', 'e');
12835 if (fold_only && edit_only)
12836 option_conflict('f', 'e');
12837 if (drop_only && abort_edit)
12838 option_conflict('d', 'a');
12839 if (drop_only && allow_conflict)
12840 option_conflict('d', 'C');
12841 if (drop_only && continue_edit)
12842 option_conflict('d', 'c');
12843 if (drop_only && edit_logmsg_only)
12844 option_conflict('d', 'm');
12845 if (drop_only && edit_only)
12846 option_conflict('d', 'e');
12847 if (drop_only && edit_script_path)
12848 option_conflict('d', 'F');
12849 if (drop_only && fold_only)
12850 option_conflict('d', 'f');
12851 if (list_backups) {
12852 if (abort_edit)
12853 option_conflict('l', 'a');
12854 if (allow_conflict)
12855 option_conflict('l', 'C');
12856 if (continue_edit)
12857 option_conflict('l', 'c');
12858 if (edit_script_path)
12859 option_conflict('l', 'F');
12860 if (edit_logmsg_only)
12861 option_conflict('l', 'm');
12862 if (drop_only)
12863 option_conflict('l', 'd');
12864 if (fold_only)
12865 option_conflict('l', 'f');
12866 if (edit_only)
12867 option_conflict('l', 'e');
12868 if (delete_backups)
12869 option_conflict('l', 'X');
12870 if (argc != 0 && argc != 1)
12871 usage_histedit();
12872 } else if (delete_backups) {
12873 if (abort_edit)
12874 option_conflict('X', 'a');
12875 if (allow_conflict)
12876 option_conflict('X', 'C');
12877 if (continue_edit)
12878 option_conflict('X', 'c');
12879 if (drop_only)
12880 option_conflict('X', 'd');
12881 if (edit_script_path)
12882 option_conflict('X', 'F');
12883 if (edit_logmsg_only)
12884 option_conflict('X', 'm');
12885 if (fold_only)
12886 option_conflict('X', 'f');
12887 if (edit_only)
12888 option_conflict('X', 'e');
12889 if (list_backups)
12890 option_conflict('X', 'l');
12891 if (argc != 0 && argc != 1)
12892 usage_histedit();
12893 } else if (allow_conflict && !continue_edit)
12894 errx(1, "-C option requires -c");
12895 else if (argc != 0)
12896 usage_histedit();
12898 cwd = getcwd(NULL, 0);
12899 if (cwd == NULL) {
12900 error = got_error_from_errno("getcwd");
12901 goto done;
12904 error = got_repo_pack_fds_open(&pack_fds);
12905 if (error != NULL)
12906 goto done;
12908 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
12909 if (error) {
12910 if (list_backups || delete_backups) {
12911 if (error->code != GOT_ERR_NOT_WORKTREE)
12912 goto done;
12913 } else {
12914 if (error->code == GOT_ERR_NOT_WORKTREE)
12915 error = wrap_not_worktree_error(error,
12916 "histedit", cwd);
12917 goto done;
12921 if (list_backups || delete_backups) {
12922 error = got_repo_open(&repo,
12923 worktree ? got_worktree_get_repo_path(worktree) : cwd,
12924 NULL, pack_fds);
12925 if (error != NULL)
12926 goto done;
12927 error = apply_unveil(got_repo_get_path(repo), 0,
12928 worktree ? got_worktree_get_root_path(worktree) : NULL);
12929 if (error)
12930 goto done;
12931 error = process_backup_refs(
12932 GOT_WORKTREE_HISTEDIT_BACKUP_REF_PREFIX,
12933 argc == 1 ? argv[0] : NULL, delete_backups, repo);
12934 goto done; /* nothing else to do */
12935 } else {
12936 error = get_gitconfig_path(&gitconfig_path);
12937 if (error)
12938 goto done;
12939 error = got_repo_open(&repo,
12940 got_worktree_get_repo_path(worktree), gitconfig_path,
12941 pack_fds);
12942 if (error != NULL)
12943 goto done;
12944 error = get_editor(&editor);
12945 if (error)
12946 goto done;
12947 if (unveil(editor, "x") != 0) {
12948 error = got_error_from_errno2("unveil", editor);
12949 goto done;
12951 if (edit_script_path) {
12952 if (unveil(edit_script_path, "r") != 0) {
12953 error = got_error_from_errno2("unveil",
12954 edit_script_path);
12955 goto done;
12958 error = apply_unveil(got_repo_get_path(repo), 0,
12959 got_worktree_get_root_path(worktree));
12960 if (error)
12961 goto done;
12964 if (worktree != NULL && !list_backups && !delete_backups) {
12965 error = worktree_has_logmsg_ref("histedit", worktree, repo);
12966 if (error)
12967 goto done;
12970 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
12971 if (error)
12972 goto done;
12973 if (rebase_in_progress) {
12974 error = got_error(GOT_ERR_REBASING);
12975 goto done;
12978 error = got_worktree_merge_in_progress(&merge_in_progress, worktree,
12979 repo);
12980 if (error)
12981 goto done;
12982 if (merge_in_progress) {
12983 error = got_error(GOT_ERR_MERGE_BUSY);
12984 goto done;
12987 error = got_worktree_histedit_in_progress(&edit_in_progress, worktree);
12988 if (error)
12989 goto done;
12991 if (edit_in_progress && edit_logmsg_only) {
12992 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
12993 "histedit operation is in progress in this "
12994 "work tree and must be continued or aborted "
12995 "before the -m option can be used");
12996 goto done;
12998 if (edit_in_progress && drop_only) {
12999 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
13000 "histedit operation is in progress in this "
13001 "work tree and must be continued or aborted "
13002 "before the -d option can be used");
13003 goto done;
13005 if (edit_in_progress && fold_only) {
13006 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
13007 "histedit operation is in progress in this "
13008 "work tree and must be continued or aborted "
13009 "before the -f option can be used");
13010 goto done;
13012 if (edit_in_progress && edit_only) {
13013 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
13014 "histedit operation is in progress in this "
13015 "work tree and must be continued or aborted "
13016 "before the -e option can be used");
13017 goto done;
13020 if (edit_in_progress && abort_edit) {
13021 error = got_worktree_histedit_continue(&resume_commit_id,
13022 &tmp_branch, &branch, &base_commit_id, &fileindex,
13023 worktree, repo);
13024 if (error)
13025 goto done;
13026 printf("Switching work tree to %s\n",
13027 got_ref_get_symref_target(branch));
13028 error = got_worktree_histedit_abort(worktree, fileindex, repo,
13029 branch, base_commit_id, abort_progress, &upa);
13030 if (error)
13031 goto done;
13032 printf("Histedit of %s aborted\n",
13033 got_ref_get_symref_target(branch));
13034 print_merge_progress_stats(&upa);
13035 goto done; /* nothing else to do */
13036 } else if (abort_edit) {
13037 error = got_error(GOT_ERR_NOT_HISTEDIT);
13038 goto done;
13041 error = get_author(&committer, repo, worktree);
13042 if (error)
13043 goto done;
13045 if (continue_edit) {
13046 char *path;
13048 if (!edit_in_progress) {
13049 error = got_error(GOT_ERR_NOT_HISTEDIT);
13050 goto done;
13053 error = got_worktree_get_histedit_script_path(&path, worktree);
13054 if (error)
13055 goto done;
13057 error = histedit_load_list(&histedit_cmds, path, repo);
13058 free(path);
13059 if (error)
13060 goto done;
13062 error = got_worktree_histedit_continue(&resume_commit_id,
13063 &tmp_branch, &branch, &base_commit_id, &fileindex,
13064 worktree, repo);
13065 if (error)
13066 goto done;
13068 error = got_ref_resolve(&head_commit_id, repo, branch);
13069 if (error)
13070 goto done;
13072 error = got_object_open_as_commit(&commit, repo,
13073 head_commit_id);
13074 if (error)
13075 goto done;
13076 parent_ids = got_object_commit_get_parent_ids(commit);
13077 pid = STAILQ_FIRST(parent_ids);
13078 if (pid == NULL) {
13079 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
13080 goto done;
13082 error = collect_commits(&commits, head_commit_id, &pid->id,
13083 base_commit_id, got_worktree_get_path_prefix(worktree),
13084 GOT_ERR_HISTEDIT_PATH, repo);
13085 got_object_commit_close(commit);
13086 commit = NULL;
13087 if (error)
13088 goto done;
13089 } else {
13090 if (edit_in_progress) {
13091 error = got_error(GOT_ERR_HISTEDIT_BUSY);
13092 goto done;
13095 error = got_ref_open(&branch, repo,
13096 got_worktree_get_head_ref_name(worktree), 0);
13097 if (error != NULL)
13098 goto done;
13100 if (strncmp(got_ref_get_name(branch), "refs/heads/", 11) != 0) {
13101 error = got_error_msg(GOT_ERR_COMMIT_BRANCH,
13102 "will not edit commit history of a branch outside "
13103 "the \"refs/heads/\" reference namespace");
13104 goto done;
13107 error = got_ref_resolve(&head_commit_id, repo, branch);
13108 got_ref_close(branch);
13109 branch = NULL;
13110 if (error)
13111 goto done;
13113 error = got_object_open_as_commit(&commit, repo,
13114 head_commit_id);
13115 if (error)
13116 goto done;
13117 parent_ids = got_object_commit_get_parent_ids(commit);
13118 pid = STAILQ_FIRST(parent_ids);
13119 if (pid == NULL) {
13120 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
13121 goto done;
13123 error = collect_commits(&commits, head_commit_id, &pid->id,
13124 got_worktree_get_base_commit_id(worktree),
13125 got_worktree_get_path_prefix(worktree),
13126 GOT_ERR_HISTEDIT_PATH, repo);
13127 got_object_commit_close(commit);
13128 commit = NULL;
13129 if (error)
13130 goto done;
13132 if (STAILQ_EMPTY(&commits)) {
13133 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
13134 goto done;
13137 error = got_worktree_histedit_prepare(&tmp_branch, &branch,
13138 &base_commit_id, &fileindex, worktree, repo);
13139 if (error)
13140 goto done;
13142 if (edit_script_path) {
13143 error = histedit_load_list(&histedit_cmds,
13144 edit_script_path, repo);
13145 if (error) {
13146 got_worktree_histedit_abort(worktree, fileindex,
13147 repo, branch, base_commit_id,
13148 abort_progress, &upa);
13149 print_merge_progress_stats(&upa);
13150 goto done;
13152 } else {
13153 const char *branch_name;
13154 branch_name = got_ref_get_symref_target(branch);
13155 if (strncmp(branch_name, "refs/heads/", 11) == 0)
13156 branch_name += 11;
13157 error = histedit_edit_script(&histedit_cmds, &commits,
13158 branch_name, edit_logmsg_only, fold_only,
13159 drop_only, edit_only, editor, repo);
13160 if (error) {
13161 got_worktree_histedit_abort(worktree, fileindex,
13162 repo, branch, base_commit_id,
13163 abort_progress, &upa);
13164 print_merge_progress_stats(&upa);
13165 goto done;
13170 error = histedit_save_list(&histedit_cmds, worktree,
13171 repo);
13172 if (error) {
13173 got_worktree_histedit_abort(worktree, fileindex,
13174 repo, branch, base_commit_id,
13175 abort_progress, &upa);
13176 print_merge_progress_stats(&upa);
13177 goto done;
13182 error = histedit_check_script(&histedit_cmds, &commits, repo);
13183 if (error)
13184 goto done;
13186 TAILQ_FOREACH(hle, &histedit_cmds, entry) {
13187 if (resume_commit_id) {
13188 if (got_object_id_cmp(hle->commit_id,
13189 resume_commit_id) != 0)
13190 continue;
13192 resume_commit_id = NULL;
13193 if (hle->cmd->code == GOT_HISTEDIT_DROP ||
13194 hle->cmd->code == GOT_HISTEDIT_FOLD) {
13195 error = histedit_skip_commit(hle, worktree,
13196 repo);
13197 if (error)
13198 goto done;
13199 } else {
13200 struct got_pathlist_head paths;
13201 int have_changes = 0;
13203 TAILQ_INIT(&paths);
13204 error = got_pathlist_append(&paths, "", NULL);
13205 if (error)
13206 goto done;
13207 error = got_worktree_status(worktree, &paths,
13208 repo, 0, check_local_changes, &have_changes,
13209 check_cancelled, NULL);
13210 got_pathlist_free(&paths,
13211 GOT_PATHLIST_FREE_NONE);
13212 if (error) {
13213 if (error->code != GOT_ERR_CANCELLED)
13214 goto done;
13215 if (sigint_received || sigpipe_received)
13216 goto done;
13218 if (have_changes) {
13219 error = histedit_commit(NULL, worktree,
13220 fileindex, tmp_branch, hle,
13221 committer, allow_conflict, editor,
13222 repo);
13223 if (error)
13224 goto done;
13225 } else {
13226 error = got_object_open_as_commit(
13227 &commit, repo, hle->commit_id);
13228 if (error)
13229 goto done;
13230 error = show_histedit_progress(commit,
13231 hle, NULL);
13232 got_object_commit_close(commit);
13233 commit = NULL;
13234 if (error)
13235 goto done;
13238 continue;
13241 if (hle->cmd->code == GOT_HISTEDIT_DROP) {
13242 error = histedit_skip_commit(hle, worktree, repo);
13243 if (error)
13244 goto done;
13245 continue;
13247 error = got_object_open_as_commit(&commit, repo,
13248 hle->commit_id);
13249 if (error)
13250 goto done;
13251 parent_ids = got_object_commit_get_parent_ids(commit);
13252 pid = STAILQ_FIRST(parent_ids);
13254 error = got_worktree_histedit_merge_files(&merged_paths,
13255 worktree, fileindex, &pid->id, hle->commit_id, repo,
13256 update_progress, &upa, check_cancelled, NULL);
13257 if (error)
13258 goto done;
13259 got_object_commit_close(commit);
13260 commit = NULL;
13262 print_merge_progress_stats(&upa);
13263 if (upa.conflicts > 0 || upa.missing > 0 ||
13264 upa.not_deleted > 0 || upa.unversioned > 0) {
13265 if (upa.conflicts > 0) {
13266 error = show_rebase_merge_conflict(
13267 hle->commit_id, repo);
13268 if (error)
13269 goto done;
13271 got_pathlist_free(&merged_paths, GOT_PATHLIST_FREE_PATH);
13272 break;
13275 if (hle->cmd->code == GOT_HISTEDIT_EDIT) {
13276 char *id_str;
13277 error = got_object_id_str(&id_str, hle->commit_id);
13278 if (error)
13279 goto done;
13280 printf("Stopping histedit for amending commit %s\n",
13281 id_str);
13282 free(id_str);
13283 got_pathlist_free(&merged_paths, GOT_PATHLIST_FREE_PATH);
13284 error = got_worktree_histedit_postpone(worktree,
13285 fileindex);
13286 goto done;
13287 } else if (hle->cmd->code == GOT_HISTEDIT_FOLD) {
13288 error = histedit_skip_commit(hle, worktree, repo);
13289 if (error)
13290 goto done;
13291 continue;
13292 } else if (hle->cmd->code == GOT_HISTEDIT_MESG) {
13293 error = histedit_edit_logmsg(hle, editor, repo);
13294 if (error)
13295 goto done;
13298 error = histedit_commit(&merged_paths, worktree, fileindex,
13299 tmp_branch, hle, committer, allow_conflict, editor, repo);
13300 got_pathlist_free(&merged_paths, GOT_PATHLIST_FREE_PATH);
13301 if (error)
13302 goto done;
13305 if (upa.conflicts > 0 || upa.missing > 0 ||
13306 upa.not_deleted > 0 || upa.unversioned > 0) {
13307 error = got_worktree_histedit_postpone(worktree, fileindex);
13308 if (error)
13309 goto done;
13310 if (upa.conflicts > 0 && upa.missing == 0 &&
13311 upa.not_deleted == 0 && upa.unversioned == 0) {
13312 error = got_error_msg(GOT_ERR_CONFLICTS,
13313 "conflicts must be resolved before histedit "
13314 "can continue");
13315 } else if (upa.conflicts > 0) {
13316 error = got_error_msg(GOT_ERR_CONFLICTS,
13317 "conflicts must be resolved before histedit "
13318 "can continue; changes destined for some "
13319 "files were not yet merged and should be "
13320 "merged manually if required before the "
13321 "histedit operation is continued");
13322 } else {
13323 error = got_error_msg(GOT_ERR_CONFLICTS,
13324 "changes destined for some files were not "
13325 "yet merged and should be merged manually "
13326 "if required before the histedit operation "
13327 "is continued");
13329 } else
13330 error = histedit_complete(worktree, fileindex, tmp_branch,
13331 branch, repo);
13332 done:
13333 free(cwd);
13334 free(editor);
13335 free(committer);
13336 free(gitconfig_path);
13337 got_object_id_queue_free(&commits);
13338 histedit_free_list(&histedit_cmds);
13339 free(head_commit_id);
13340 free(base_commit_id);
13341 free(resume_commit_id);
13342 if (commit)
13343 got_object_commit_close(commit);
13344 if (branch)
13345 got_ref_close(branch);
13346 if (tmp_branch)
13347 got_ref_close(tmp_branch);
13348 if (worktree)
13349 got_worktree_close(worktree);
13350 if (repo) {
13351 const struct got_error *close_err = got_repo_close(repo);
13352 if (error == NULL)
13353 error = close_err;
13355 if (pack_fds) {
13356 const struct got_error *pack_err =
13357 got_repo_pack_fds_close(pack_fds);
13358 if (error == NULL)
13359 error = pack_err;
13361 return error;
13364 __dead static void
13365 usage_integrate(void)
13367 fprintf(stderr, "usage: %s integrate branch\n", getprogname());
13368 exit(1);
13371 static const struct got_error *
13372 cmd_integrate(int argc, char *argv[])
13374 const struct got_error *error = NULL;
13375 struct got_repository *repo = NULL;
13376 struct got_worktree *worktree = NULL;
13377 char *cwd = NULL, *refname = NULL, *base_refname = NULL;
13378 const char *branch_arg = NULL;
13379 struct got_reference *branch_ref = NULL, *base_branch_ref = NULL;
13380 struct got_fileindex *fileindex = NULL;
13381 struct got_object_id *commit_id = NULL, *base_commit_id = NULL;
13382 int ch;
13383 struct got_update_progress_arg upa;
13384 int *pack_fds = NULL;
13386 #ifndef PROFILE
13387 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
13388 "unveil", NULL) == -1)
13389 err(1, "pledge");
13390 #endif
13392 while ((ch = getopt(argc, argv, "")) != -1) {
13393 switch (ch) {
13394 default:
13395 usage_integrate();
13396 /* NOTREACHED */
13400 argc -= optind;
13401 argv += optind;
13403 if (argc != 1)
13404 usage_integrate();
13405 branch_arg = argv[0];
13407 cwd = getcwd(NULL, 0);
13408 if (cwd == NULL) {
13409 error = got_error_from_errno("getcwd");
13410 goto done;
13413 error = got_repo_pack_fds_open(&pack_fds);
13414 if (error != NULL)
13415 goto done;
13417 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
13418 if (error) {
13419 if (error->code == GOT_ERR_NOT_WORKTREE)
13420 error = wrap_not_worktree_error(error, "integrate",
13421 cwd);
13422 goto done;
13425 error = check_rebase_or_histedit_in_progress(worktree);
13426 if (error)
13427 goto done;
13429 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
13430 NULL, pack_fds);
13431 if (error != NULL)
13432 goto done;
13434 error = apply_unveil(got_repo_get_path(repo), 0,
13435 got_worktree_get_root_path(worktree));
13436 if (error)
13437 goto done;
13439 error = check_merge_in_progress(worktree, repo);
13440 if (error)
13441 goto done;
13443 if (asprintf(&refname, "refs/heads/%s", branch_arg) == -1) {
13444 error = got_error_from_errno("asprintf");
13445 goto done;
13448 error = got_worktree_integrate_prepare(&fileindex, &branch_ref,
13449 &base_branch_ref, worktree, refname, repo);
13450 if (error)
13451 goto done;
13453 refname = strdup(got_ref_get_name(branch_ref));
13454 if (refname == NULL) {
13455 error = got_error_from_errno("strdup");
13456 got_worktree_integrate_abort(worktree, fileindex, repo,
13457 branch_ref, base_branch_ref);
13458 goto done;
13460 base_refname = strdup(got_ref_get_name(base_branch_ref));
13461 if (base_refname == NULL) {
13462 error = got_error_from_errno("strdup");
13463 got_worktree_integrate_abort(worktree, fileindex, repo,
13464 branch_ref, base_branch_ref);
13465 goto done;
13467 if (strncmp(base_refname, "refs/heads/", 11) != 0) {
13468 error = got_error(GOT_ERR_INTEGRATE_BRANCH);
13469 got_worktree_integrate_abort(worktree, fileindex, repo,
13470 branch_ref, base_branch_ref);
13471 goto done;
13474 error = got_ref_resolve(&commit_id, repo, branch_ref);
13475 if (error)
13476 goto done;
13478 error = got_ref_resolve(&base_commit_id, repo, base_branch_ref);
13479 if (error)
13480 goto done;
13482 if (got_object_id_cmp(commit_id, base_commit_id) == 0) {
13483 error = got_error_msg(GOT_ERR_SAME_BRANCH,
13484 "specified branch has already been integrated");
13485 got_worktree_integrate_abort(worktree, fileindex, repo,
13486 branch_ref, base_branch_ref);
13487 goto done;
13490 error = check_linear_ancestry(commit_id, base_commit_id, 1, repo);
13491 if (error) {
13492 if (error->code == GOT_ERR_ANCESTRY)
13493 error = got_error(GOT_ERR_REBASE_REQUIRED);
13494 got_worktree_integrate_abort(worktree, fileindex, repo,
13495 branch_ref, base_branch_ref);
13496 goto done;
13499 memset(&upa, 0, sizeof(upa));
13500 error = got_worktree_integrate_continue(worktree, fileindex, repo,
13501 branch_ref, base_branch_ref, update_progress, &upa,
13502 check_cancelled, NULL);
13503 if (error)
13504 goto done;
13506 printf("Integrated %s into %s\n", refname, base_refname);
13507 print_update_progress_stats(&upa);
13508 done:
13509 if (repo) {
13510 const struct got_error *close_err = got_repo_close(repo);
13511 if (error == NULL)
13512 error = close_err;
13514 if (worktree)
13515 got_worktree_close(worktree);
13516 if (pack_fds) {
13517 const struct got_error *pack_err =
13518 got_repo_pack_fds_close(pack_fds);
13519 if (error == NULL)
13520 error = pack_err;
13522 free(cwd);
13523 free(base_commit_id);
13524 free(commit_id);
13525 free(refname);
13526 free(base_refname);
13527 return error;
13530 __dead static void
13531 usage_merge(void)
13533 fprintf(stderr, "usage: %s merge [-aCcn] [branch]\n", getprogname());
13534 exit(1);
13537 static const struct got_error *
13538 cmd_merge(int argc, char *argv[])
13540 const struct got_error *error = NULL;
13541 struct got_worktree *worktree = NULL;
13542 struct got_repository *repo = NULL;
13543 struct got_fileindex *fileindex = NULL;
13544 char *cwd = NULL, *id_str = NULL, *author = NULL;
13545 char *gitconfig_path = NULL;
13546 struct got_reference *branch = NULL, *wt_branch = NULL;
13547 struct got_object_id *branch_tip = NULL, *yca_id = NULL;
13548 struct got_object_id *wt_branch_tip = NULL;
13549 int ch, merge_in_progress = 0, abort_merge = 0, continue_merge = 0;
13550 int allow_conflict = 0, prefer_fast_forward = 1, interrupt_merge = 0;
13551 struct got_update_progress_arg upa;
13552 struct got_object_id *merge_commit_id = NULL;
13553 char *branch_name = NULL;
13554 int *pack_fds = NULL;
13556 memset(&upa, 0, sizeof(upa));
13558 #ifndef PROFILE
13559 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
13560 "unveil", NULL) == -1)
13561 err(1, "pledge");
13562 #endif
13564 while ((ch = getopt(argc, argv, "aCcMn")) != -1) {
13565 switch (ch) {
13566 case 'a':
13567 abort_merge = 1;
13568 break;
13569 case 'C':
13570 allow_conflict = 1;
13571 break;
13572 case 'c':
13573 continue_merge = 1;
13574 break;
13575 case 'M':
13576 prefer_fast_forward = 0;
13577 break;
13578 case 'n':
13579 interrupt_merge = 1;
13580 break;
13581 default:
13582 usage_merge();
13583 /* NOTREACHED */
13587 argc -= optind;
13588 argv += optind;
13590 if (abort_merge) {
13591 if (continue_merge)
13592 option_conflict('a', 'c');
13593 if (!prefer_fast_forward)
13594 option_conflict('a', 'M');
13595 if (interrupt_merge)
13596 option_conflict('a', 'n');
13597 } else if (continue_merge) {
13598 if (!prefer_fast_forward)
13599 option_conflict('c', 'M');
13600 if (interrupt_merge)
13601 option_conflict('c', 'n');
13603 if (allow_conflict) {
13604 if (!continue_merge)
13605 errx(1, "-C option requires -c");
13607 if (abort_merge || continue_merge) {
13608 if (argc != 0)
13609 usage_merge();
13610 } else if (argc != 1)
13611 usage_merge();
13613 cwd = getcwd(NULL, 0);
13614 if (cwd == NULL) {
13615 error = got_error_from_errno("getcwd");
13616 goto done;
13619 error = got_repo_pack_fds_open(&pack_fds);
13620 if (error != NULL)
13621 goto done;
13623 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
13624 if (error) {
13625 if (error->code == GOT_ERR_NOT_WORKTREE)
13626 error = wrap_not_worktree_error(error,
13627 "merge", cwd);
13628 goto done;
13631 error = get_gitconfig_path(&gitconfig_path);
13632 if (error)
13633 goto done;
13634 error = got_repo_open(&repo,
13635 worktree ? got_worktree_get_repo_path(worktree) : cwd,
13636 gitconfig_path, pack_fds);
13637 if (error != NULL)
13638 goto done;
13640 if (worktree != NULL) {
13641 error = worktree_has_logmsg_ref("merge", worktree, repo);
13642 if (error)
13643 goto done;
13646 error = apply_unveil(got_repo_get_path(repo), 0,
13647 worktree ? got_worktree_get_root_path(worktree) : NULL);
13648 if (error)
13649 goto done;
13651 error = check_rebase_or_histedit_in_progress(worktree);
13652 if (error)
13653 goto done;
13655 error = got_worktree_merge_in_progress(&merge_in_progress, worktree,
13656 repo);
13657 if (error)
13658 goto done;
13660 if (merge_in_progress && !(abort_merge || continue_merge)) {
13661 error = got_error(GOT_ERR_MERGE_BUSY);
13662 goto done;
13665 if (!merge_in_progress && (abort_merge || continue_merge)) {
13666 error = got_error(GOT_ERR_NOT_MERGING);
13667 goto done;
13670 if (abort_merge) {
13671 error = got_worktree_merge_continue(&branch_name,
13672 &branch_tip, &fileindex, worktree, repo);
13673 if (error)
13674 goto done;
13675 error = got_worktree_merge_abort(worktree, fileindex, repo,
13676 abort_progress, &upa);
13677 if (error)
13678 goto done;
13679 printf("Merge of %s aborted\n", branch_name);
13680 goto done; /* nothing else to do */
13683 if (strncmp(got_worktree_get_head_ref_name(worktree),
13684 "refs/heads/", 11) != 0) {
13685 error = got_error_fmt(GOT_ERR_COMMIT_BRANCH,
13686 "work tree's current branch %s is outside the "
13687 "\"refs/heads/\" reference namespace; "
13688 "update -b required",
13689 got_worktree_get_head_ref_name(worktree));
13690 goto done;
13693 error = get_author(&author, repo, worktree);
13694 if (error)
13695 goto done;
13697 error = got_ref_open(&wt_branch, repo,
13698 got_worktree_get_head_ref_name(worktree), 0);
13699 if (error)
13700 goto done;
13701 error = got_ref_resolve(&wt_branch_tip, repo, wt_branch);
13702 if (error)
13703 goto done;
13705 if (continue_merge) {
13706 struct got_object_id *base_commit_id;
13707 base_commit_id = got_worktree_get_base_commit_id(worktree);
13708 if (got_object_id_cmp(wt_branch_tip, base_commit_id) != 0) {
13709 error = got_error(GOT_ERR_MERGE_COMMIT_OUT_OF_DATE);
13710 goto done;
13712 error = got_worktree_merge_continue(&branch_name,
13713 &branch_tip, &fileindex, worktree, repo);
13714 if (error)
13715 goto done;
13716 } else {
13717 error = got_ref_open(&branch, repo, argv[0], 0);
13718 if (error != NULL)
13719 goto done;
13720 branch_name = strdup(got_ref_get_name(branch));
13721 if (branch_name == NULL) {
13722 error = got_error_from_errno("strdup");
13723 goto done;
13725 error = got_ref_resolve(&branch_tip, repo, branch);
13726 if (error)
13727 goto done;
13730 error = got_commit_graph_find_youngest_common_ancestor(&yca_id,
13731 wt_branch_tip, branch_tip, 0, 0, repo,
13732 check_cancelled, NULL);
13733 if (error && error->code != GOT_ERR_ANCESTRY)
13734 goto done;
13736 if (!continue_merge) {
13737 error = check_path_prefix(wt_branch_tip, branch_tip,
13738 got_worktree_get_path_prefix(worktree),
13739 GOT_ERR_MERGE_PATH, repo);
13740 if (error)
13741 goto done;
13742 error = got_worktree_merge_prepare(&fileindex, worktree, repo);
13743 if (error)
13744 goto done;
13745 if (prefer_fast_forward && yca_id &&
13746 got_object_id_cmp(wt_branch_tip, yca_id) == 0) {
13747 struct got_pathlist_head paths;
13748 if (interrupt_merge) {
13749 error = got_error_fmt(GOT_ERR_BAD_OPTION,
13750 "there are no changes to merge since %s "
13751 "is already based on %s; merge cannot be "
13752 "interrupted for amending; -n",
13753 branch_name, got_ref_get_name(wt_branch));
13754 goto done;
13756 printf("Forwarding %s to %s\n",
13757 got_ref_get_name(wt_branch), branch_name);
13758 error = got_ref_change_ref(wt_branch, branch_tip);
13759 if (error)
13760 goto done;
13761 error = got_ref_write(wt_branch, repo);
13762 if (error)
13763 goto done;
13764 error = got_worktree_set_base_commit_id(worktree, repo,
13765 branch_tip);
13766 if (error)
13767 goto done;
13768 TAILQ_INIT(&paths);
13769 error = got_pathlist_append(&paths, "", NULL);
13770 if (error)
13771 goto done;
13772 error = got_worktree_checkout_files(worktree,
13773 &paths, repo, update_progress, &upa,
13774 check_cancelled, NULL);
13775 got_pathlist_free(&paths, GOT_PATHLIST_FREE_NONE);
13776 if (error)
13777 goto done;
13778 if (upa.did_something) {
13779 char *id_str;
13780 error = got_object_id_str(&id_str, branch_tip);
13781 if (error)
13782 goto done;
13783 printf("Updated to commit %s\n", id_str);
13784 free(id_str);
13785 } else
13786 printf("Already up-to-date\n");
13787 print_update_progress_stats(&upa);
13788 goto done;
13790 error = got_worktree_merge_write_refs(worktree, branch, repo);
13791 if (error)
13792 goto done;
13794 error = got_worktree_merge_branch(worktree, fileindex,
13795 yca_id, branch_tip, repo, update_progress, &upa,
13796 check_cancelled, NULL);
13797 if (error)
13798 goto done;
13799 print_merge_progress_stats(&upa);
13800 if (!upa.did_something) {
13801 error = got_worktree_merge_abort(worktree, fileindex,
13802 repo, abort_progress, &upa);
13803 if (error)
13804 goto done;
13805 printf("Already up-to-date\n");
13806 goto done;
13810 if (interrupt_merge) {
13811 error = got_worktree_merge_postpone(worktree, fileindex);
13812 if (error)
13813 goto done;
13814 printf("Merge of %s interrupted on request\n", branch_name);
13815 } else if (upa.conflicts > 0 || upa.missing > 0 ||
13816 upa.not_deleted > 0 || upa.unversioned > 0) {
13817 error = got_worktree_merge_postpone(worktree, fileindex);
13818 if (error)
13819 goto done;
13820 if (upa.conflicts > 0 && upa.missing == 0 &&
13821 upa.not_deleted == 0 && upa.unversioned == 0) {
13822 error = got_error_msg(GOT_ERR_CONFLICTS,
13823 "conflicts must be resolved before merging "
13824 "can continue");
13825 } else if (upa.conflicts > 0) {
13826 error = got_error_msg(GOT_ERR_CONFLICTS,
13827 "conflicts must be resolved before merging "
13828 "can continue; changes destined for some "
13829 "files were not yet merged and "
13830 "should be merged manually if required before the "
13831 "merge operation is continued");
13832 } else {
13833 error = got_error_msg(GOT_ERR_CONFLICTS,
13834 "changes destined for some "
13835 "files were not yet merged and should be "
13836 "merged manually if required before the "
13837 "merge operation is continued");
13839 goto done;
13840 } else {
13841 error = got_worktree_merge_commit(&merge_commit_id, worktree,
13842 fileindex, author, NULL, 1, branch_tip, branch_name,
13843 allow_conflict, repo, continue_merge ? print_status : NULL,
13844 NULL);
13845 if (error)
13846 goto done;
13847 error = got_worktree_merge_complete(worktree, fileindex, repo);
13848 if (error)
13849 goto done;
13850 error = got_object_id_str(&id_str, merge_commit_id);
13851 if (error)
13852 goto done;
13853 printf("Merged %s into %s: %s\n", branch_name,
13854 got_worktree_get_head_ref_name(worktree),
13855 id_str);
13858 done:
13859 free(cwd);
13860 free(gitconfig_path);
13861 free(id_str);
13862 free(merge_commit_id);
13863 free(author);
13864 free(branch_tip);
13865 free(branch_name);
13866 free(yca_id);
13867 if (branch)
13868 got_ref_close(branch);
13869 if (wt_branch)
13870 got_ref_close(wt_branch);
13871 if (worktree)
13872 got_worktree_close(worktree);
13873 if (repo) {
13874 const struct got_error *close_err = got_repo_close(repo);
13875 if (error == NULL)
13876 error = close_err;
13878 if (pack_fds) {
13879 const struct got_error *pack_err =
13880 got_repo_pack_fds_close(pack_fds);
13881 if (error == NULL)
13882 error = pack_err;
13884 return error;
13887 __dead static void
13888 usage_stage(void)
13890 fprintf(stderr, "usage: %s stage [-lpS] [-F response-script] "
13891 "[path ...]\n", getprogname());
13892 exit(1);
13895 static const struct got_error *
13896 print_stage(void *arg, unsigned char status, unsigned char staged_status,
13897 const char *path, struct got_object_id *blob_id,
13898 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
13899 int dirfd, const char *de_name)
13901 const struct got_error *err = NULL;
13902 char *id_str = NULL;
13904 if (staged_status != GOT_STATUS_ADD &&
13905 staged_status != GOT_STATUS_MODIFY &&
13906 staged_status != GOT_STATUS_DELETE)
13907 return NULL;
13909 if (staged_status == GOT_STATUS_ADD ||
13910 staged_status == GOT_STATUS_MODIFY)
13911 err = got_object_id_str(&id_str, staged_blob_id);
13912 else
13913 err = got_object_id_str(&id_str, blob_id);
13914 if (err)
13915 return err;
13917 printf("%s %c %s\n", id_str, staged_status, path);
13918 free(id_str);
13919 return NULL;
13922 static const struct got_error *
13923 cmd_stage(int argc, char *argv[])
13925 const struct got_error *error = NULL;
13926 struct got_repository *repo = NULL;
13927 struct got_worktree *worktree = NULL;
13928 char *cwd = NULL;
13929 struct got_pathlist_head paths;
13930 int ch, list_stage = 0, pflag = 0, allow_bad_symlinks = 0;
13931 FILE *patch_script_file = NULL;
13932 const char *patch_script_path = NULL;
13933 struct choose_patch_arg cpa;
13934 int *pack_fds = NULL;
13936 TAILQ_INIT(&paths);
13938 #ifndef PROFILE
13939 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
13940 "unveil", NULL) == -1)
13941 err(1, "pledge");
13942 #endif
13944 while ((ch = getopt(argc, argv, "F:lpS")) != -1) {
13945 switch (ch) {
13946 case 'F':
13947 patch_script_path = optarg;
13948 break;
13949 case 'l':
13950 list_stage = 1;
13951 break;
13952 case 'p':
13953 pflag = 1;
13954 break;
13955 case 'S':
13956 allow_bad_symlinks = 1;
13957 break;
13958 default:
13959 usage_stage();
13960 /* NOTREACHED */
13964 argc -= optind;
13965 argv += optind;
13967 if (list_stage && (pflag || patch_script_path))
13968 errx(1, "-l option cannot be used with other options");
13969 if (patch_script_path && !pflag)
13970 errx(1, "-F option can only be used together with -p option");
13972 cwd = getcwd(NULL, 0);
13973 if (cwd == NULL) {
13974 error = got_error_from_errno("getcwd");
13975 goto done;
13978 error = got_repo_pack_fds_open(&pack_fds);
13979 if (error != NULL)
13980 goto done;
13982 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
13983 if (error) {
13984 if (error->code == GOT_ERR_NOT_WORKTREE)
13985 error = wrap_not_worktree_error(error, "stage", cwd);
13986 goto done;
13989 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
13990 NULL, pack_fds);
13991 if (error != NULL)
13992 goto done;
13994 if (patch_script_path) {
13995 patch_script_file = fopen(patch_script_path, "re");
13996 if (patch_script_file == NULL) {
13997 error = got_error_from_errno2("fopen",
13998 patch_script_path);
13999 goto done;
14002 error = apply_unveil(got_repo_get_path(repo), 0,
14003 got_worktree_get_root_path(worktree));
14004 if (error)
14005 goto done;
14007 error = check_merge_in_progress(worktree, repo);
14008 if (error)
14009 goto done;
14011 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
14012 if (error)
14013 goto done;
14015 if (list_stage)
14016 error = got_worktree_status(worktree, &paths, repo, 0,
14017 print_stage, NULL, check_cancelled, NULL);
14018 else {
14019 cpa.patch_script_file = patch_script_file;
14020 cpa.action = "stage";
14021 error = got_worktree_stage(worktree, &paths,
14022 pflag ? NULL : print_status, NULL,
14023 pflag ? choose_patch : NULL, &cpa,
14024 allow_bad_symlinks, repo);
14026 done:
14027 if (patch_script_file && fclose(patch_script_file) == EOF &&
14028 error == NULL)
14029 error = got_error_from_errno2("fclose", patch_script_path);
14030 if (repo) {
14031 const struct got_error *close_err = got_repo_close(repo);
14032 if (error == NULL)
14033 error = close_err;
14035 if (worktree)
14036 got_worktree_close(worktree);
14037 if (pack_fds) {
14038 const struct got_error *pack_err =
14039 got_repo_pack_fds_close(pack_fds);
14040 if (error == NULL)
14041 error = pack_err;
14043 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
14044 free(cwd);
14045 return error;
14048 __dead static void
14049 usage_unstage(void)
14051 fprintf(stderr, "usage: %s unstage [-p] [-F response-script] "
14052 "[path ...]\n", getprogname());
14053 exit(1);
14057 static const struct got_error *
14058 cmd_unstage(int argc, char *argv[])
14060 const struct got_error *error = NULL;
14061 struct got_repository *repo = NULL;
14062 struct got_worktree *worktree = NULL;
14063 char *cwd = NULL;
14064 struct got_pathlist_head paths;
14065 int ch, pflag = 0;
14066 struct got_update_progress_arg upa;
14067 FILE *patch_script_file = NULL;
14068 const char *patch_script_path = NULL;
14069 struct choose_patch_arg cpa;
14070 int *pack_fds = NULL;
14072 TAILQ_INIT(&paths);
14074 #ifndef PROFILE
14075 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
14076 "unveil", NULL) == -1)
14077 err(1, "pledge");
14078 #endif
14080 while ((ch = getopt(argc, argv, "F:p")) != -1) {
14081 switch (ch) {
14082 case 'F':
14083 patch_script_path = optarg;
14084 break;
14085 case 'p':
14086 pflag = 1;
14087 break;
14088 default:
14089 usage_unstage();
14090 /* NOTREACHED */
14094 argc -= optind;
14095 argv += optind;
14097 if (patch_script_path && !pflag)
14098 errx(1, "-F option can only be used together with -p option");
14100 cwd = getcwd(NULL, 0);
14101 if (cwd == NULL) {
14102 error = got_error_from_errno("getcwd");
14103 goto done;
14106 error = got_repo_pack_fds_open(&pack_fds);
14107 if (error != NULL)
14108 goto done;
14110 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
14111 if (error) {
14112 if (error->code == GOT_ERR_NOT_WORKTREE)
14113 error = wrap_not_worktree_error(error, "unstage", cwd);
14114 goto done;
14117 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
14118 NULL, pack_fds);
14119 if (error != NULL)
14120 goto done;
14122 if (patch_script_path) {
14123 patch_script_file = fopen(patch_script_path, "re");
14124 if (patch_script_file == NULL) {
14125 error = got_error_from_errno2("fopen",
14126 patch_script_path);
14127 goto done;
14131 error = apply_unveil(got_repo_get_path(repo), 0,
14132 got_worktree_get_root_path(worktree));
14133 if (error)
14134 goto done;
14136 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
14137 if (error)
14138 goto done;
14140 cpa.patch_script_file = patch_script_file;
14141 cpa.action = "unstage";
14142 memset(&upa, 0, sizeof(upa));
14143 error = got_worktree_unstage(worktree, &paths, update_progress,
14144 &upa, pflag ? choose_patch : NULL, &cpa, repo);
14145 if (!error)
14146 print_merge_progress_stats(&upa);
14147 done:
14148 if (patch_script_file && fclose(patch_script_file) == EOF &&
14149 error == NULL)
14150 error = got_error_from_errno2("fclose", patch_script_path);
14151 if (repo) {
14152 const struct got_error *close_err = got_repo_close(repo);
14153 if (error == NULL)
14154 error = close_err;
14156 if (worktree)
14157 got_worktree_close(worktree);
14158 if (pack_fds) {
14159 const struct got_error *pack_err =
14160 got_repo_pack_fds_close(pack_fds);
14161 if (error == NULL)
14162 error = pack_err;
14164 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
14165 free(cwd);
14166 return error;
14169 __dead static void
14170 usage_cat(void)
14172 fprintf(stderr, "usage: %s cat [-P] [-c commit] [-r repository-path] "
14173 "arg ...\n", getprogname());
14174 exit(1);
14177 static const struct got_error *
14178 cat_blob(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
14180 const struct got_error *err;
14181 struct got_blob_object *blob;
14182 int fd = -1;
14184 fd = got_opentempfd();
14185 if (fd == -1)
14186 return got_error_from_errno("got_opentempfd");
14188 err = got_object_open_as_blob(&blob, repo, id, 8192, fd);
14189 if (err)
14190 goto done;
14192 err = got_object_blob_dump_to_file(NULL, NULL, NULL, outfile, blob);
14193 done:
14194 if (fd != -1 && close(fd) == -1 && err == NULL)
14195 err = got_error_from_errno("close");
14196 if (blob)
14197 got_object_blob_close(blob);
14198 return err;
14201 static const struct got_error *
14202 cat_tree(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
14204 const struct got_error *err;
14205 struct got_tree_object *tree;
14206 int nentries, i;
14208 err = got_object_open_as_tree(&tree, repo, id);
14209 if (err)
14210 return err;
14212 nentries = got_object_tree_get_nentries(tree);
14213 for (i = 0; i < nentries; i++) {
14214 struct got_tree_entry *te;
14215 char *id_str;
14216 if (sigint_received || sigpipe_received)
14217 break;
14218 te = got_object_tree_get_entry(tree, i);
14219 err = got_object_id_str(&id_str, got_tree_entry_get_id(te));
14220 if (err)
14221 break;
14222 fprintf(outfile, "%s %.7o %s\n", id_str,
14223 got_tree_entry_get_mode(te),
14224 got_tree_entry_get_name(te));
14225 free(id_str);
14228 got_object_tree_close(tree);
14229 return err;
14232 static const struct got_error *
14233 cat_commit(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
14235 const struct got_error *err;
14236 struct got_commit_object *commit;
14237 const struct got_object_id_queue *parent_ids;
14238 struct got_object_qid *pid;
14239 char *id_str = NULL;
14240 const char *logmsg = NULL;
14241 char gmtoff[6];
14243 err = got_object_open_as_commit(&commit, repo, id);
14244 if (err)
14245 return err;
14247 err = got_object_id_str(&id_str, got_object_commit_get_tree_id(commit));
14248 if (err)
14249 goto done;
14251 fprintf(outfile, "%s%s\n", GOT_COMMIT_LABEL_TREE, id_str);
14252 parent_ids = got_object_commit_get_parent_ids(commit);
14253 fprintf(outfile, "numparents %d\n",
14254 got_object_commit_get_nparents(commit));
14255 STAILQ_FOREACH(pid, parent_ids, entry) {
14256 char *pid_str;
14257 err = got_object_id_str(&pid_str, &pid->id);
14258 if (err)
14259 goto done;
14260 fprintf(outfile, "%s%s\n", GOT_COMMIT_LABEL_PARENT, pid_str);
14261 free(pid_str);
14263 got_date_format_gmtoff(gmtoff, sizeof(gmtoff),
14264 got_object_commit_get_author_gmtoff(commit));
14265 fprintf(outfile, "%s%s %lld %s\n", GOT_COMMIT_LABEL_AUTHOR,
14266 got_object_commit_get_author(commit),
14267 (long long)got_object_commit_get_author_time(commit),
14268 gmtoff);
14270 got_date_format_gmtoff(gmtoff, sizeof(gmtoff),
14271 got_object_commit_get_committer_gmtoff(commit));
14272 fprintf(outfile, "%s%s %lld %s\n", GOT_COMMIT_LABEL_COMMITTER,
14273 got_object_commit_get_committer(commit),
14274 (long long)got_object_commit_get_committer_time(commit),
14275 gmtoff);
14277 logmsg = got_object_commit_get_logmsg_raw(commit);
14278 fprintf(outfile, "messagelen %zd\n", strlen(logmsg));
14279 fprintf(outfile, "%s", logmsg);
14280 done:
14281 free(id_str);
14282 got_object_commit_close(commit);
14283 return err;
14286 static const struct got_error *
14287 cat_tag(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
14289 const struct got_error *err;
14290 struct got_tag_object *tag;
14291 char *id_str = NULL;
14292 const char *tagmsg = NULL;
14293 char gmtoff[6];
14295 err = got_object_open_as_tag(&tag, repo, id);
14296 if (err)
14297 return err;
14299 err = got_object_id_str(&id_str, got_object_tag_get_object_id(tag));
14300 if (err)
14301 goto done;
14303 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_OBJECT, id_str);
14305 switch (got_object_tag_get_object_type(tag)) {
14306 case GOT_OBJ_TYPE_BLOB:
14307 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
14308 GOT_OBJ_LABEL_BLOB);
14309 break;
14310 case GOT_OBJ_TYPE_TREE:
14311 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
14312 GOT_OBJ_LABEL_TREE);
14313 break;
14314 case GOT_OBJ_TYPE_COMMIT:
14315 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
14316 GOT_OBJ_LABEL_COMMIT);
14317 break;
14318 case GOT_OBJ_TYPE_TAG:
14319 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
14320 GOT_OBJ_LABEL_TAG);
14321 break;
14322 default:
14323 break;
14326 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TAG,
14327 got_object_tag_get_name(tag));
14329 got_date_format_gmtoff(gmtoff, sizeof(gmtoff),
14330 got_object_tag_get_tagger_gmtoff(tag));
14331 fprintf(outfile, "%s%s %lld %s\n", GOT_TAG_LABEL_TAGGER,
14332 got_object_tag_get_tagger(tag),
14333 (long long)got_object_tag_get_tagger_time(tag),
14334 gmtoff);
14336 tagmsg = got_object_tag_get_message(tag);
14337 fprintf(outfile, "messagelen %zd\n", strlen(tagmsg));
14338 fprintf(outfile, "%s", tagmsg);
14339 done:
14340 free(id_str);
14341 got_object_tag_close(tag);
14342 return err;
14345 static const struct got_error *
14346 cmd_cat(int argc, char *argv[])
14348 const struct got_error *error;
14349 struct got_repository *repo = NULL;
14350 struct got_worktree *worktree = NULL;
14351 char *cwd = NULL, *repo_path = NULL, *label = NULL;
14352 char *keyword_idstr = NULL;
14353 const char *commit_id_str = NULL;
14354 struct got_object_id *id = NULL, *commit_id = NULL;
14355 struct got_commit_object *commit = NULL;
14356 int ch, obj_type, i, force_path = 0;
14357 struct got_reflist_head refs;
14358 int *pack_fds = NULL;
14360 TAILQ_INIT(&refs);
14362 #ifndef PROFILE
14363 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
14364 NULL) == -1)
14365 err(1, "pledge");
14366 #endif
14368 while ((ch = getopt(argc, argv, "c:Pr:")) != -1) {
14369 switch (ch) {
14370 case 'c':
14371 commit_id_str = optarg;
14372 break;
14373 case 'P':
14374 force_path = 1;
14375 break;
14376 case 'r':
14377 repo_path = realpath(optarg, NULL);
14378 if (repo_path == NULL)
14379 return got_error_from_errno2("realpath",
14380 optarg);
14381 got_path_strip_trailing_slashes(repo_path);
14382 break;
14383 default:
14384 usage_cat();
14385 /* NOTREACHED */
14389 argc -= optind;
14390 argv += optind;
14392 cwd = getcwd(NULL, 0);
14393 if (cwd == NULL) {
14394 error = got_error_from_errno("getcwd");
14395 goto done;
14398 error = got_repo_pack_fds_open(&pack_fds);
14399 if (error != NULL)
14400 goto done;
14402 if (repo_path == NULL) {
14403 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
14404 if (error && error->code != GOT_ERR_NOT_WORKTREE)
14405 goto done;
14406 if (worktree) {
14407 repo_path = strdup(
14408 got_worktree_get_repo_path(worktree));
14409 if (repo_path == NULL) {
14410 error = got_error_from_errno("strdup");
14411 goto done;
14414 if (commit_id_str == NULL) {
14415 /* Release work tree lock. */
14416 got_worktree_close(worktree);
14417 worktree = NULL;
14422 if (repo_path == NULL) {
14423 repo_path = strdup(cwd);
14424 if (repo_path == NULL)
14425 return got_error_from_errno("strdup");
14428 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
14429 free(repo_path);
14430 if (error != NULL)
14431 goto done;
14433 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
14434 if (error)
14435 goto done;
14437 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
14438 if (error)
14439 goto done;
14441 if (commit_id_str != NULL) {
14442 error = got_keyword_to_idstr(&keyword_idstr, commit_id_str,
14443 repo, worktree);
14444 if (error != NULL)
14445 goto done;
14446 if (keyword_idstr != NULL)
14447 commit_id_str = keyword_idstr;
14448 if (worktree != NULL) {
14449 got_worktree_close(worktree);
14450 worktree = NULL;
14452 } else
14453 commit_id_str = GOT_REF_HEAD;
14454 error = got_repo_match_object_id(&commit_id, NULL,
14455 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
14456 if (error)
14457 goto done;
14459 error = got_object_open_as_commit(&commit, repo, commit_id);
14460 if (error)
14461 goto done;
14463 for (i = 0; i < argc; i++) {
14464 if (force_path) {
14465 error = got_object_id_by_path(&id, repo, commit,
14466 argv[i]);
14467 if (error)
14468 break;
14469 } else {
14470 error = got_repo_match_object_id(&id, &label, argv[i],
14471 GOT_OBJ_TYPE_ANY, NULL /* do not resolve tags */,
14472 repo);
14473 if (error) {
14474 if (error->code != GOT_ERR_BAD_OBJ_ID_STR &&
14475 error->code != GOT_ERR_NOT_REF)
14476 break;
14477 error = got_object_id_by_path(&id, repo,
14478 commit, argv[i]);
14479 if (error)
14480 break;
14484 error = got_object_get_type(&obj_type, repo, id);
14485 if (error)
14486 break;
14488 switch (obj_type) {
14489 case GOT_OBJ_TYPE_BLOB:
14490 error = cat_blob(id, repo, stdout);
14491 break;
14492 case GOT_OBJ_TYPE_TREE:
14493 error = cat_tree(id, repo, stdout);
14494 break;
14495 case GOT_OBJ_TYPE_COMMIT:
14496 error = cat_commit(id, repo, stdout);
14497 break;
14498 case GOT_OBJ_TYPE_TAG:
14499 error = cat_tag(id, repo, stdout);
14500 break;
14501 default:
14502 error = got_error(GOT_ERR_OBJ_TYPE);
14503 break;
14505 if (error)
14506 break;
14507 free(label);
14508 label = NULL;
14509 free(id);
14510 id = NULL;
14512 done:
14513 free(cwd);
14514 free(label);
14515 free(id);
14516 free(commit_id);
14517 free(keyword_idstr);
14518 if (commit)
14519 got_object_commit_close(commit);
14520 if (worktree)
14521 got_worktree_close(worktree);
14522 if (repo) {
14523 const struct got_error *close_err = got_repo_close(repo);
14524 if (error == NULL)
14525 error = close_err;
14527 if (pack_fds) {
14528 const struct got_error *pack_err =
14529 got_repo_pack_fds_close(pack_fds);
14530 if (error == NULL)
14531 error = pack_err;
14534 got_ref_list_free(&refs);
14535 return error;
14538 __dead static void
14539 usage_info(void)
14541 fprintf(stderr, "usage: %s info [path ...]\n",
14542 getprogname());
14543 exit(1);
14546 static const struct got_error *
14547 print_path_info(void *arg, const char *path, mode_t mode, time_t mtime,
14548 struct got_object_id *blob_id, struct got_object_id *staged_blob_id,
14549 struct got_object_id *commit_id)
14551 const struct got_error *err = NULL;
14552 char *id_str = NULL;
14553 char datebuf[128];
14554 struct tm mytm, *tm;
14555 struct got_pathlist_head *paths = arg;
14556 struct got_pathlist_entry *pe;
14559 * Clear error indication from any of the path arguments which
14560 * would cause this file index entry to be displayed.
14562 TAILQ_FOREACH(pe, paths, entry) {
14563 if (got_path_cmp(path, pe->path, strlen(path),
14564 pe->path_len) == 0 ||
14565 got_path_is_child(path, pe->path, pe->path_len))
14566 pe->data = NULL; /* no error */
14569 printf(GOT_COMMIT_SEP_STR);
14570 if (S_ISLNK(mode))
14571 printf("symlink: %s\n", path);
14572 else if (S_ISREG(mode)) {
14573 printf("file: %s\n", path);
14574 printf("mode: %o\n", mode & (S_IRWXU | S_IRWXG | S_IRWXO));
14575 } else if (S_ISDIR(mode))
14576 printf("directory: %s\n", path);
14577 else
14578 printf("something: %s\n", path);
14580 tm = localtime_r(&mtime, &mytm);
14581 if (tm == NULL)
14582 return NULL;
14583 if (strftime(datebuf, sizeof(datebuf), "%c %Z", tm) == 0)
14584 return got_error(GOT_ERR_NO_SPACE);
14585 printf("timestamp: %s\n", datebuf);
14587 if (blob_id) {
14588 err = got_object_id_str(&id_str, blob_id);
14589 if (err)
14590 return err;
14591 printf("based on blob: %s\n", id_str);
14592 free(id_str);
14595 if (staged_blob_id) {
14596 err = got_object_id_str(&id_str, staged_blob_id);
14597 if (err)
14598 return err;
14599 printf("based on staged blob: %s\n", id_str);
14600 free(id_str);
14603 if (commit_id) {
14604 err = got_object_id_str(&id_str, commit_id);
14605 if (err)
14606 return err;
14607 printf("based on commit: %s\n", id_str);
14608 free(id_str);
14611 return NULL;
14614 static const struct got_error *
14615 cmd_info(int argc, char *argv[])
14617 const struct got_error *error = NULL;
14618 struct got_worktree *worktree = NULL;
14619 char *cwd = NULL, *id_str = NULL;
14620 struct got_pathlist_head paths;
14621 char *uuidstr = NULL;
14622 int ch, show_files = 0;
14624 TAILQ_INIT(&paths);
14626 #ifndef PROFILE
14627 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
14628 NULL) == -1)
14629 err(1, "pledge");
14630 #endif
14632 while ((ch = getopt(argc, argv, "")) != -1) {
14633 switch (ch) {
14634 default:
14635 usage_info();
14636 /* NOTREACHED */
14640 argc -= optind;
14641 argv += optind;
14643 cwd = getcwd(NULL, 0);
14644 if (cwd == NULL) {
14645 error = got_error_from_errno("getcwd");
14646 goto done;
14649 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
14650 if (error) {
14651 if (error->code == GOT_ERR_NOT_WORKTREE)
14652 error = wrap_not_worktree_error(error, "info", cwd);
14653 goto done;
14656 #ifndef PROFILE
14657 /* Remove "wpath cpath proc exec sendfd" promises. */
14658 if (pledge("stdio rpath flock unveil", NULL) == -1)
14659 err(1, "pledge");
14660 #endif
14661 error = apply_unveil(NULL, 0, got_worktree_get_root_path(worktree));
14662 if (error)
14663 goto done;
14665 if (argc >= 1) {
14666 error = get_worktree_paths_from_argv(&paths, argc, argv,
14667 worktree);
14668 if (error)
14669 goto done;
14670 show_files = 1;
14673 error = got_object_id_str(&id_str,
14674 got_worktree_get_base_commit_id(worktree));
14675 if (error)
14676 goto done;
14678 error = got_worktree_get_uuid(&uuidstr, worktree);
14679 if (error)
14680 goto done;
14682 printf("work tree: %s\n", got_worktree_get_root_path(worktree));
14683 printf("work tree base commit: %s\n", id_str);
14684 printf("work tree path prefix: %s\n",
14685 got_worktree_get_path_prefix(worktree));
14686 printf("work tree branch reference: %s\n",
14687 got_worktree_get_head_ref_name(worktree));
14688 printf("work tree UUID: %s\n", uuidstr);
14689 printf("repository: %s\n", got_worktree_get_repo_path(worktree));
14691 if (show_files) {
14692 struct got_pathlist_entry *pe;
14693 TAILQ_FOREACH(pe, &paths, entry) {
14694 if (pe->path_len == 0)
14695 continue;
14697 * Assume this path will fail. This will be corrected
14698 * in print_path_info() in case the path does suceeed.
14700 pe->data = (void *)got_error(GOT_ERR_BAD_PATH);
14702 error = got_worktree_path_info(worktree, &paths,
14703 print_path_info, &paths, check_cancelled, NULL);
14704 if (error)
14705 goto done;
14706 TAILQ_FOREACH(pe, &paths, entry) {
14707 if (pe->data != NULL) {
14708 const struct got_error *perr;
14710 perr = pe->data;
14711 error = got_error_fmt(perr->code, "%s",
14712 pe->path);
14713 break;
14717 done:
14718 if (worktree)
14719 got_worktree_close(worktree);
14720 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
14721 free(cwd);
14722 free(id_str);
14723 free(uuidstr);
14724 return error;