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 "got_compat.h"
21 #include <sys/queue.h>
22 #include <sys/time.h>
23 #include <sys/types.h>
24 #include <sys/stat.h>
25 #include <sys/wait.h>
27 #include <err.h>
28 #include <errno.h>
29 #include <fcntl.h>
30 #include <limits.h>
31 #include <locale.h>
32 #include <ctype.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>
44 #include "got_version.h"
45 #include "got_error.h"
46 #include "got_object.h"
47 #include "got_reference.h"
48 #include "got_repository.h"
49 #include "got_path.h"
50 #include "got_cancel.h"
51 #include "got_worktree.h"
52 #include "got_diff.h"
53 #include "got_commit_graph.h"
54 #include "got_fetch.h"
55 #include "got_send.h"
56 #include "got_blame.h"
57 #include "got_privsep.h"
58 #include "got_opentemp.h"
59 #include "got_gotconfig.h"
60 #include "got_dial.h"
61 #include "got_patch.h"
62 #include "got_sigs.h"
63 #include "got_date.h"
65 #ifndef nitems
66 #define nitems(_a) (sizeof((_a)) / sizeof((_a)[0]))
67 #endif
69 static volatile sig_atomic_t sigint_received;
70 static volatile sig_atomic_t sigpipe_received;
72 static void
73 catch_sigint(int signo)
74 {
75 sigint_received = 1;
76 }
78 static void
79 catch_sigpipe(int signo)
80 {
81 sigpipe_received = 1;
82 }
85 struct got_cmd {
86 const char *cmd_name;
87 const struct got_error *(*cmd_main)(int, char *[]);
88 void (*cmd_usage)(void);
89 const char *cmd_alias;
90 };
92 __dead static void usage(int, int);
93 __dead static void usage_import(void);
94 __dead static void usage_clone(void);
95 __dead static void usage_fetch(void);
96 __dead static void usage_checkout(void);
97 __dead static void usage_update(void);
98 __dead static void usage_log(void);
99 __dead static void usage_diff(void);
100 __dead static void usage_blame(void);
101 __dead static void usage_tree(void);
102 __dead static void usage_status(void);
103 __dead static void usage_ref(void);
104 __dead static void usage_branch(void);
105 __dead static void usage_tag(void);
106 __dead static void usage_add(void);
107 __dead static void usage_remove(void);
108 __dead static void usage_patch(void);
109 __dead static void usage_revert(void);
110 __dead static void usage_commit(void);
111 __dead static void usage_send(void);
112 __dead static void usage_cherrypick(void);
113 __dead static void usage_backout(void);
114 __dead static void usage_rebase(void);
115 __dead static void usage_histedit(void);
116 __dead static void usage_integrate(void);
117 __dead static void usage_merge(void);
118 __dead static void usage_stage(void);
119 __dead static void usage_unstage(void);
120 __dead static void usage_cat(void);
121 __dead static void usage_info(void);
123 static const struct got_error* cmd_import(int, char *[]);
124 static const struct got_error* cmd_clone(int, char *[]);
125 static const struct got_error* cmd_fetch(int, char *[]);
126 static const struct got_error* cmd_checkout(int, char *[]);
127 static const struct got_error* cmd_update(int, char *[]);
128 static const struct got_error* cmd_log(int, char *[]);
129 static const struct got_error* cmd_diff(int, char *[]);
130 static const struct got_error* cmd_blame(int, char *[]);
131 static const struct got_error* cmd_tree(int, char *[]);
132 static const struct got_error* cmd_status(int, char *[]);
133 static const struct got_error* cmd_ref(int, char *[]);
134 static const struct got_error* cmd_branch(int, char *[]);
135 static const struct got_error* cmd_tag(int, char *[]);
136 static const struct got_error* cmd_add(int, char *[]);
137 static const struct got_error* cmd_remove(int, char *[]);
138 static const struct got_error* cmd_patch(int, char *[]);
139 static const struct got_error* cmd_revert(int, char *[]);
140 static const struct got_error* cmd_commit(int, char *[]);
141 static const struct got_error* cmd_send(int, char *[]);
142 static const struct got_error* cmd_cherrypick(int, char *[]);
143 static const struct got_error* cmd_backout(int, char *[]);
144 static const struct got_error* cmd_rebase(int, char *[]);
145 static const struct got_error* cmd_histedit(int, char *[]);
146 static const struct got_error* cmd_integrate(int, char *[]);
147 static const struct got_error* cmd_merge(int, char *[]);
148 static const struct got_error* cmd_stage(int, char *[]);
149 static const struct got_error* cmd_unstage(int, char *[]);
150 static const struct got_error* cmd_cat(int, char *[]);
151 static const struct got_error* cmd_info(int, char *[]);
153 static const struct got_cmd got_commands[] = {
154 { "import", cmd_import, usage_import, "im" },
155 { "clone", cmd_clone, usage_clone, "cl" },
156 { "fetch", cmd_fetch, usage_fetch, "fe" },
157 { "checkout", cmd_checkout, usage_checkout, "co" },
158 { "update", cmd_update, usage_update, "up" },
159 { "log", cmd_log, usage_log, "" },
160 { "diff", cmd_diff, usage_diff, "di" },
161 { "blame", cmd_blame, usage_blame, "bl" },
162 { "tree", cmd_tree, usage_tree, "tr" },
163 { "status", cmd_status, usage_status, "st" },
164 { "ref", cmd_ref, usage_ref, "" },
165 { "branch", cmd_branch, usage_branch, "br" },
166 { "tag", cmd_tag, usage_tag, "" },
167 { "add", cmd_add, usage_add, "" },
168 { "remove", cmd_remove, usage_remove, "rm" },
169 { "patch", cmd_patch, usage_patch, "pa" },
170 { "revert", cmd_revert, usage_revert, "rv" },
171 { "commit", cmd_commit, usage_commit, "ci" },
172 { "send", cmd_send, usage_send, "se" },
173 { "cherrypick", cmd_cherrypick, usage_cherrypick, "cy" },
174 { "backout", cmd_backout, usage_backout, "bo" },
175 { "rebase", cmd_rebase, usage_rebase, "rb" },
176 { "histedit", cmd_histedit, usage_histedit, "he" },
177 { "integrate", cmd_integrate, usage_integrate,"ig" },
178 { "merge", cmd_merge, usage_merge, "mg" },
179 { "stage", cmd_stage, usage_stage, "sg" },
180 { "unstage", cmd_unstage, usage_unstage, "ug" },
181 { "cat", cmd_cat, usage_cat, "" },
182 { "info", cmd_info, usage_info, "" },
183 };
185 static void
186 list_commands(FILE *fp)
188 size_t i;
190 fprintf(fp, "commands:");
191 for (i = 0; i < nitems(got_commands); i++) {
192 const struct got_cmd *cmd = &got_commands[i];
193 fprintf(fp, " %s", cmd->cmd_name);
195 fputc('\n', fp);
198 __dead static void
199 option_conflict(char a, char b)
201 errx(1, "-%c and -%c options are mutually exclusive", a, b);
204 int
205 main(int argc, char *argv[])
207 const struct got_cmd *cmd;
208 size_t i;
209 int ch;
210 int hflag = 0, Vflag = 0;
211 static const struct option longopts[] = {
212 { "version", no_argument, NULL, 'V' },
213 { NULL, 0, NULL, 0 }
214 };
216 setlocale(LC_CTYPE, "");
218 while ((ch = getopt_long(argc, argv, "+hV", longopts, NULL)) != -1) {
219 switch (ch) {
220 case 'h':
221 hflag = 1;
222 break;
223 case 'V':
224 Vflag = 1;
225 break;
226 default:
227 usage(hflag, 1);
228 /* NOTREACHED */
232 argc -= optind;
233 argv += optind;
234 optind = 1;
235 optreset = 1;
237 if (Vflag) {
238 got_version_print_str();
239 return 0;
242 if (argc <= 0)
243 usage(hflag, hflag ? 0 : 1);
245 signal(SIGINT, catch_sigint);
246 signal(SIGPIPE, catch_sigpipe);
248 for (i = 0; i < nitems(got_commands); i++) {
249 const struct got_error *error;
251 cmd = &got_commands[i];
253 if (strcmp(cmd->cmd_name, argv[0]) != 0 &&
254 strcmp(cmd->cmd_alias, argv[0]) != 0)
255 continue;
257 if (hflag)
258 cmd->cmd_usage();
260 error = cmd->cmd_main(argc, argv);
261 if (error && error->code != GOT_ERR_CANCELLED &&
262 error->code != GOT_ERR_PRIVSEP_EXIT &&
263 !(sigpipe_received &&
264 error->code == GOT_ERR_ERRNO && errno == EPIPE) &&
265 !(sigint_received &&
266 error->code == GOT_ERR_ERRNO && errno == EINTR)) {
267 fflush(stdout);
268 fprintf(stderr, "%s: %s\n", getprogname(), error->msg);
269 return 1;
272 return 0;
275 fprintf(stderr, "%s: unknown command '%s'\n", getprogname(), argv[0]);
276 list_commands(stderr);
277 return 1;
280 __dead static void
281 usage(int hflag, int status)
283 FILE *fp = (status == 0) ? stdout : stderr;
285 fprintf(fp, "usage: %s [-hV] command [arg ...]\n",
286 getprogname());
287 if (hflag)
288 list_commands(fp);
289 exit(status);
292 static const struct got_error *
293 get_editor(char **abspath)
295 const struct got_error *err = NULL;
296 const char *editor;
298 *abspath = NULL;
300 editor = getenv("VISUAL");
301 if (editor == NULL)
302 editor = getenv("EDITOR");
304 if (editor) {
305 err = got_path_find_prog(abspath, editor);
306 if (err)
307 return err;
310 if (*abspath == NULL) {
311 *abspath = strdup("/usr/bin/vi");
312 if (*abspath == NULL)
313 return got_error_from_errno("strdup");
316 return NULL;
319 static const struct got_error *
320 apply_unveil(const char *repo_path, int repo_read_only,
321 const char *worktree_path)
323 const struct got_error *err;
325 #ifdef PROFILE
326 if (unveil("gmon.out", "rwc") != 0)
327 return got_error_from_errno2("unveil", "gmon.out");
328 #endif
329 if (repo_path && unveil(repo_path, repo_read_only ? "r" : "rwc") != 0)
330 return got_error_from_errno2("unveil", repo_path);
332 if (worktree_path && unveil(worktree_path, "rwc") != 0)
333 return got_error_from_errno2("unveil", worktree_path);
335 if (unveil(GOT_TMPDIR_STR, "rwc") != 0)
336 return got_error_from_errno2("unveil", GOT_TMPDIR_STR);
338 err = got_privsep_unveil_exec_helpers();
339 if (err != NULL)
340 return err;
342 if (unveil(NULL, NULL) != 0)
343 return got_error_from_errno("unveil");
345 return NULL;
348 __dead static void
349 usage_import(void)
351 fprintf(stderr, "usage: %s import [-b branch] [-I pattern] [-m message] "
352 "[-r repository-path] directory\n", getprogname());
353 exit(1);
356 static int
357 spawn_editor(const char *editor, const char *file)
359 pid_t pid;
360 sig_t sighup, sigint, sigquit;
361 int st = -1;
363 sighup = signal(SIGHUP, SIG_IGN);
364 sigint = signal(SIGINT, SIG_IGN);
365 sigquit = signal(SIGQUIT, SIG_IGN);
367 switch (pid = fork()) {
368 case -1:
369 goto doneediting;
370 case 0:
371 execl(editor, editor, file, (char *)NULL);
372 _exit(127);
375 while (waitpid(pid, &st, 0) == -1)
376 if (errno != EINTR)
377 break;
379 doneediting:
380 (void)signal(SIGHUP, sighup);
381 (void)signal(SIGINT, sigint);
382 (void)signal(SIGQUIT, sigquit);
384 if (!WIFEXITED(st)) {
385 errno = EINTR;
386 return -1;
389 return WEXITSTATUS(st);
392 static const struct got_error *
393 read_logmsg(char **logmsg, size_t *len, FILE *fp, size_t filesize)
395 const struct got_error *err = NULL;
396 char *line = NULL;
397 size_t linesize = 0;
399 *logmsg = NULL;
400 *len = 0;
402 if (fseeko(fp, 0L, SEEK_SET) == -1)
403 return got_error_from_errno("fseeko");
405 *logmsg = malloc(filesize + 1);
406 if (*logmsg == NULL)
407 return got_error_from_errno("malloc");
408 (*logmsg)[0] = '\0';
410 while (getline(&line, &linesize, fp) != -1) {
411 if (line[0] == '#' || (*len == 0 && line[0] == '\n'))
412 continue; /* remove comments and leading empty lines */
413 *len = strlcat(*logmsg, line, filesize + 1);
414 if (*len >= filesize + 1) {
415 err = got_error(GOT_ERR_NO_SPACE);
416 goto done;
419 if (ferror(fp)) {
420 err = got_ferror(fp, GOT_ERR_IO);
421 goto done;
424 while (*len > 0 && (*logmsg)[*len - 1] == '\n') {
425 (*logmsg)[*len - 1] = '\0';
426 (*len)--;
428 done:
429 free(line);
430 if (err) {
431 free(*logmsg);
432 *logmsg = NULL;
433 *len = 0;
435 return err;
438 static const struct got_error *
439 edit_logmsg(char **logmsg, const char *editor, const char *logmsg_path,
440 const char *initial_content, size_t initial_content_len,
441 int require_modification)
443 const struct got_error *err = NULL;
444 struct stat st, st2;
445 FILE *fp = NULL;
446 size_t logmsg_len;
448 *logmsg = NULL;
450 if (stat(logmsg_path, &st) == -1)
451 return got_error_from_errno2("stat", logmsg_path);
453 if (spawn_editor(editor, logmsg_path) == -1)
454 return got_error_from_errno("failed spawning editor");
456 if (require_modification) {
457 struct timespec timeout;
459 timeout.tv_sec = 0;
460 timeout.tv_nsec = 1;
461 nanosleep(&timeout, NULL);
464 if (stat(logmsg_path, &st2) == -1)
465 return got_error_from_errno2("stat", logmsg_path);
467 if (require_modification && st.st_size == st2.st_size &&
468 timespeccmp(&st.st_mtim, &st2.st_mtim, ==))
469 return got_error_msg(GOT_ERR_COMMIT_MSG_EMPTY,
470 "no changes made to commit message, aborting");
472 fp = fopen(logmsg_path, "re");
473 if (fp == NULL) {
474 err = got_error_from_errno("fopen");
475 goto done;
478 /* strip comments and leading/trailing newlines */
479 err = read_logmsg(logmsg, &logmsg_len, fp, st2.st_size);
480 if (err)
481 goto done;
482 if (logmsg_len == 0) {
483 err = got_error_msg(GOT_ERR_COMMIT_MSG_EMPTY,
484 "commit message cannot be empty, aborting");
485 goto done;
487 done:
488 if (fp && fclose(fp) == EOF && err == NULL)
489 err = got_error_from_errno("fclose");
490 if (err) {
491 free(*logmsg);
492 *logmsg = NULL;
494 return err;
497 static const struct got_error *
498 collect_import_msg(char **logmsg, char **logmsg_path, const char *editor,
499 const char *path_dir, const char *branch_name)
501 char *initial_content = NULL;
502 const struct got_error *err = NULL;
503 int initial_content_len;
504 int fd = -1;
506 initial_content_len = asprintf(&initial_content,
507 "\n# %s to be imported to branch %s\n", path_dir,
508 branch_name);
509 if (initial_content_len == -1)
510 return got_error_from_errno("asprintf");
512 err = got_opentemp_named_fd(logmsg_path, &fd,
513 GOT_TMPDIR_STR "/got-importmsg", "");
514 if (err)
515 goto done;
517 if (write(fd, initial_content, initial_content_len) == -1) {
518 err = got_error_from_errno2("write", *logmsg_path);
519 goto done;
521 if (close(fd) == -1) {
522 err = got_error_from_errno2("close", *logmsg_path);
523 goto done;
525 fd = -1;
527 err = edit_logmsg(logmsg, editor, *logmsg_path, initial_content,
528 initial_content_len, 1);
529 done:
530 if (fd != -1 && close(fd) == -1 && err == NULL)
531 err = got_error_from_errno2("close", *logmsg_path);
532 free(initial_content);
533 if (err) {
534 free(*logmsg_path);
535 *logmsg_path = NULL;
537 return err;
540 static const struct got_error *
541 import_progress(void *arg, const char *path)
543 printf("A %s\n", path);
544 return NULL;
547 static const struct got_error *
548 valid_author(const char *author)
550 const char *email = author;
552 /*
553 * Git' expects the author (or committer) to be in the form
554 * "name <email>", which are mostly free form (see the
555 * "committer" description in git-fast-import(1)). We're only
556 * doing this to avoid git's object parser breaking on commits
557 * we create.
558 */
560 while (*author && *author != '\n' && *author != '<' && *author != '>')
561 author++;
562 if (author != email && *author == '<' && *(author - 1) != ' ')
563 return got_error_fmt(GOT_ERR_COMMIT_BAD_AUTHOR, "%s: space "
564 "between author name and email required", email);
565 if (*author++ != '<')
566 return got_error_fmt(GOT_ERR_COMMIT_NO_EMAIL, "%s", email);
567 while (*author && *author != '\n' && *author != '<' && *author != '>')
568 author++;
569 if (strcmp(author, ">") != 0)
570 return got_error_fmt(GOT_ERR_COMMIT_NO_EMAIL, "%s", email);
571 return NULL;
574 static const struct got_error *
575 get_author(char **author, struct got_repository *repo,
576 struct got_worktree *worktree)
578 const struct got_error *err = NULL;
579 const char *got_author = NULL, *name, *email;
580 const struct got_gotconfig *worktree_conf = NULL, *repo_conf = NULL;
582 *author = NULL;
584 if (worktree)
585 worktree_conf = got_worktree_get_gotconfig(worktree);
586 repo_conf = got_repo_get_gotconfig(repo);
588 /*
589 * Priority of potential author information sources, from most
590 * significant to least significant:
591 * 1) work tree's .got/got.conf file
592 * 2) repository's got.conf file
593 * 3) repository's git config file
594 * 4) environment variables
595 * 5) global git config files (in user's home directory or /etc)
596 */
598 if (worktree_conf)
599 got_author = got_gotconfig_get_author(worktree_conf);
600 if (got_author == NULL)
601 got_author = got_gotconfig_get_author(repo_conf);
602 if (got_author == NULL) {
603 name = got_repo_get_gitconfig_author_name(repo);
604 email = got_repo_get_gitconfig_author_email(repo);
605 if (name && email) {
606 if (asprintf(author, "%s <%s>", name, email) == -1)
607 return got_error_from_errno("asprintf");
608 return NULL;
611 got_author = getenv("GOT_AUTHOR");
612 if (got_author == NULL) {
613 name = got_repo_get_global_gitconfig_author_name(repo);
614 email = got_repo_get_global_gitconfig_author_email(
615 repo);
616 if (name && email) {
617 if (asprintf(author, "%s <%s>", name, email)
618 == -1)
619 return got_error_from_errno("asprintf");
620 return NULL;
622 /* TODO: Look up user in password database? */
623 return got_error(GOT_ERR_COMMIT_NO_AUTHOR);
627 *author = strdup(got_author);
628 if (*author == NULL)
629 return got_error_from_errno("strdup");
631 err = valid_author(*author);
632 if (err) {
633 free(*author);
634 *author = NULL;
636 return err;
639 static const struct got_error *
640 get_allowed_signers(char **allowed_signers, struct got_repository *repo,
641 struct got_worktree *worktree)
643 const char *got_allowed_signers = NULL;
644 const struct got_gotconfig *worktree_conf = NULL, *repo_conf = NULL;
646 *allowed_signers = NULL;
648 if (worktree)
649 worktree_conf = got_worktree_get_gotconfig(worktree);
650 repo_conf = got_repo_get_gotconfig(repo);
652 /*
653 * Priority of potential author information sources, from most
654 * significant to least significant:
655 * 1) work tree's .got/got.conf file
656 * 2) repository's got.conf file
657 */
659 if (worktree_conf)
660 got_allowed_signers = got_gotconfig_get_allowed_signers_file(
661 worktree_conf);
662 if (got_allowed_signers == NULL)
663 got_allowed_signers = got_gotconfig_get_allowed_signers_file(
664 repo_conf);
666 if (got_allowed_signers) {
667 *allowed_signers = strdup(got_allowed_signers);
668 if (*allowed_signers == NULL)
669 return got_error_from_errno("strdup");
671 return NULL;
674 static const struct got_error *
675 get_revoked_signers(char **revoked_signers, struct got_repository *repo,
676 struct got_worktree *worktree)
678 const char *got_revoked_signers = NULL;
679 const struct got_gotconfig *worktree_conf = NULL, *repo_conf = NULL;
681 *revoked_signers = NULL;
683 if (worktree)
684 worktree_conf = got_worktree_get_gotconfig(worktree);
685 repo_conf = got_repo_get_gotconfig(repo);
687 /*
688 * Priority of potential author information sources, from most
689 * significant to least significant:
690 * 1) work tree's .got/got.conf file
691 * 2) repository's got.conf file
692 */
694 if (worktree_conf)
695 got_revoked_signers = got_gotconfig_get_revoked_signers_file(
696 worktree_conf);
697 if (got_revoked_signers == NULL)
698 got_revoked_signers = got_gotconfig_get_revoked_signers_file(
699 repo_conf);
701 if (got_revoked_signers) {
702 *revoked_signers = strdup(got_revoked_signers);
703 if (*revoked_signers == NULL)
704 return got_error_from_errno("strdup");
706 return NULL;
709 static const char *
710 get_signer_id(struct got_repository *repo, struct got_worktree *worktree)
712 const char *got_signer_id = NULL;
713 const struct got_gotconfig *worktree_conf = NULL, *repo_conf = 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_signer_id = got_gotconfig_get_signer_id(worktree_conf);
728 if (got_signer_id == NULL)
729 got_signer_id = got_gotconfig_get_signer_id(repo_conf);
731 return got_signer_id;
734 static const struct got_error *
735 get_gitconfig_path(char **gitconfig_path)
737 const char *homedir = getenv("HOME");
739 *gitconfig_path = NULL;
740 if (homedir) {
741 if (asprintf(gitconfig_path, "%s/.gitconfig", homedir) == -1)
742 return got_error_from_errno("asprintf");
745 return NULL;
748 static const struct got_error *
749 cmd_import(int argc, char *argv[])
751 const struct got_error *error = NULL;
752 char *path_dir = NULL, *repo_path = NULL, *logmsg = NULL;
753 char *gitconfig_path = NULL, *editor = NULL, *author = NULL;
754 const char *branch_name = NULL;
755 char *id_str = NULL, *logmsg_path = NULL;
756 char refname[PATH_MAX] = "refs/heads/";
757 struct got_repository *repo = NULL;
758 struct got_reference *branch_ref = NULL, *head_ref = NULL;
759 struct got_object_id *new_commit_id = NULL;
760 int ch, n = 0;
761 struct got_pathlist_head ignores;
762 struct got_pathlist_entry *pe;
763 int preserve_logmsg = 0;
764 int *pack_fds = NULL;
766 TAILQ_INIT(&ignores);
768 #ifndef PROFILE
769 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
770 "unveil",
771 NULL) == -1)
772 err(1, "pledge");
773 #endif
775 while ((ch = getopt(argc, argv, "b:I:m:r:")) != -1) {
776 switch (ch) {
777 case 'b':
778 branch_name = optarg;
779 break;
780 case 'I':
781 if (optarg[0] == '\0')
782 break;
783 error = got_pathlist_insert(&pe, &ignores, optarg,
784 NULL);
785 if (error)
786 goto done;
787 break;
788 case 'm':
789 logmsg = strdup(optarg);
790 if (logmsg == NULL) {
791 error = got_error_from_errno("strdup");
792 goto done;
794 break;
795 case 'r':
796 repo_path = realpath(optarg, NULL);
797 if (repo_path == NULL) {
798 error = got_error_from_errno2("realpath",
799 optarg);
800 goto done;
802 break;
803 default:
804 usage_import();
805 /* NOTREACHED */
809 argc -= optind;
810 argv += optind;
812 if (argc != 1)
813 usage_import();
815 if (repo_path == NULL) {
816 repo_path = getcwd(NULL, 0);
817 if (repo_path == NULL)
818 return got_error_from_errno("getcwd");
820 got_path_strip_trailing_slashes(repo_path);
821 error = get_gitconfig_path(&gitconfig_path);
822 if (error)
823 goto done;
824 error = got_repo_pack_fds_open(&pack_fds);
825 if (error != NULL)
826 goto done;
827 error = got_repo_open(&repo, repo_path, gitconfig_path, pack_fds);
828 if (error)
829 goto done;
831 error = get_author(&author, repo, NULL);
832 if (error)
833 return error;
835 /*
836 * Don't let the user create a branch name with a leading '-'.
837 * While technically a valid reference name, this case is usually
838 * an unintended typo.
839 */
840 if (branch_name && branch_name[0] == '-')
841 return got_error_path(branch_name, GOT_ERR_REF_NAME_MINUS);
843 error = got_ref_open(&head_ref, repo, GOT_REF_HEAD, 0);
844 if (error && error->code != GOT_ERR_NOT_REF)
845 goto done;
847 if (branch_name)
848 n = strlcat(refname, branch_name, sizeof(refname));
849 else if (head_ref && got_ref_is_symbolic(head_ref))
850 n = strlcpy(refname, got_ref_get_symref_target(head_ref),
851 sizeof(refname));
852 else
853 n = strlcat(refname, "main", sizeof(refname));
854 if (n >= sizeof(refname)) {
855 error = got_error(GOT_ERR_NO_SPACE);
856 goto done;
859 error = got_ref_open(&branch_ref, repo, refname, 0);
860 if (error) {
861 if (error->code != GOT_ERR_NOT_REF)
862 goto done;
863 } else {
864 error = got_error_msg(GOT_ERR_BRANCH_EXISTS,
865 "import target branch already exists");
866 goto done;
869 path_dir = realpath(argv[0], NULL);
870 if (path_dir == NULL) {
871 error = got_error_from_errno2("realpath", argv[0]);
872 goto done;
874 got_path_strip_trailing_slashes(path_dir);
876 /*
877 * unveil(2) traverses exec(2); if an editor is used we have
878 * to apply unveil after the log message has been written.
879 */
880 if (logmsg == NULL || *logmsg == '\0') {
881 error = get_editor(&editor);
882 if (error)
883 goto done;
884 free(logmsg);
885 error = collect_import_msg(&logmsg, &logmsg_path, editor,
886 path_dir, refname);
887 if (error) {
888 if (error->code != GOT_ERR_COMMIT_MSG_EMPTY &&
889 logmsg_path != NULL)
890 preserve_logmsg = 1;
891 goto done;
895 if (unveil(path_dir, "r") != 0) {
896 error = got_error_from_errno2("unveil", path_dir);
897 if (logmsg_path)
898 preserve_logmsg = 1;
899 goto done;
902 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
903 if (error) {
904 if (logmsg_path)
905 preserve_logmsg = 1;
906 goto done;
909 error = got_repo_import(&new_commit_id, path_dir, logmsg,
910 author, &ignores, repo, import_progress, NULL);
911 if (error) {
912 if (logmsg_path)
913 preserve_logmsg = 1;
914 goto done;
917 error = got_ref_alloc(&branch_ref, refname, new_commit_id);
918 if (error) {
919 if (logmsg_path)
920 preserve_logmsg = 1;
921 goto done;
924 error = got_ref_write(branch_ref, repo);
925 if (error) {
926 if (logmsg_path)
927 preserve_logmsg = 1;
928 goto done;
931 error = got_object_id_str(&id_str, new_commit_id);
932 if (error) {
933 if (logmsg_path)
934 preserve_logmsg = 1;
935 goto done;
938 error = got_ref_open(&head_ref, repo, GOT_REF_HEAD, 0);
939 if (error) {
940 if (error->code != GOT_ERR_NOT_REF) {
941 if (logmsg_path)
942 preserve_logmsg = 1;
943 goto done;
946 error = got_ref_alloc_symref(&head_ref, GOT_REF_HEAD,
947 branch_ref);
948 if (error) {
949 if (logmsg_path)
950 preserve_logmsg = 1;
951 goto done;
954 error = got_ref_write(head_ref, repo);
955 if (error) {
956 if (logmsg_path)
957 preserve_logmsg = 1;
958 goto done;
962 printf("Created branch %s with commit %s\n",
963 got_ref_get_name(branch_ref), id_str);
964 done:
965 if (pack_fds) {
966 const struct got_error *pack_err =
967 got_repo_pack_fds_close(pack_fds);
968 if (error == NULL)
969 error = pack_err;
971 if (repo) {
972 const struct got_error *close_err = got_repo_close(repo);
973 if (error == NULL)
974 error = close_err;
976 if (preserve_logmsg) {
977 fprintf(stderr, "%s: log message preserved in %s\n",
978 getprogname(), logmsg_path);
979 } else if (logmsg_path && unlink(logmsg_path) == -1 && error == NULL)
980 error = got_error_from_errno2("unlink", logmsg_path);
981 free(logmsg);
982 free(logmsg_path);
983 free(repo_path);
984 free(editor);
985 free(new_commit_id);
986 free(id_str);
987 free(author);
988 free(gitconfig_path);
989 if (branch_ref)
990 got_ref_close(branch_ref);
991 if (head_ref)
992 got_ref_close(head_ref);
993 return error;
996 __dead static void
997 usage_clone(void)
999 fprintf(stderr, "usage: %s clone [-almqv] [-b branch] [-R reference] "
1000 "repository-URL [directory]\n", getprogname());
1001 exit(1);
1004 struct got_fetch_progress_arg {
1005 char last_scaled_size[FMT_SCALED_STRSIZE];
1006 int last_p_indexed;
1007 int last_p_resolved;
1008 int verbosity;
1010 struct got_repository *repo;
1012 int create_configs;
1013 int configs_created;
1014 struct {
1015 struct got_pathlist_head *symrefs;
1016 struct got_pathlist_head *wanted_branches;
1017 struct got_pathlist_head *wanted_refs;
1018 const char *proto;
1019 const char *host;
1020 const char *port;
1021 const char *remote_repo_path;
1022 const char *git_url;
1023 int fetch_all_branches;
1024 int mirror_references;
1025 } config_info;
1028 /* XXX forward declaration */
1029 static const struct got_error *
1030 create_config_files(const char *proto, const char *host, const char *port,
1031 const char *remote_repo_path, const char *git_url, int fetch_all_branches,
1032 int mirror_references, struct got_pathlist_head *symrefs,
1033 struct got_pathlist_head *wanted_branches,
1034 struct got_pathlist_head *wanted_refs, struct got_repository *repo);
1036 static const struct got_error *
1037 fetch_progress(void *arg, const char *message, off_t packfile_size,
1038 int nobj_total, int nobj_indexed, int nobj_loose, int nobj_resolved)
1040 const struct got_error *err = NULL;
1041 struct got_fetch_progress_arg *a = arg;
1042 char scaled_size[FMT_SCALED_STRSIZE];
1043 int p_indexed, p_resolved;
1044 int print_size = 0, print_indexed = 0, print_resolved = 0;
1047 * In order to allow a failed clone to be resumed with 'got fetch'
1048 * we try to create configuration files as soon as possible.
1049 * Once the server has sent information about its default branch
1050 * we have all required information.
1052 if (a->create_configs && !a->configs_created &&
1053 !TAILQ_EMPTY(a->config_info.symrefs)) {
1054 err = create_config_files(a->config_info.proto,
1055 a->config_info.host, a->config_info.port,
1056 a->config_info.remote_repo_path,
1057 a->config_info.git_url,
1058 a->config_info.fetch_all_branches,
1059 a->config_info.mirror_references,
1060 a->config_info.symrefs,
1061 a->config_info.wanted_branches,
1062 a->config_info.wanted_refs, a->repo);
1063 if (err)
1064 return err;
1065 a->configs_created = 1;
1068 if (a->verbosity < 0)
1069 return NULL;
1071 if (message && message[0] != '\0') {
1072 printf("\rserver: %s", message);
1073 fflush(stdout);
1074 return NULL;
1077 if (packfile_size > 0 || nobj_indexed > 0) {
1078 if (fmt_scaled(packfile_size, scaled_size) == 0 &&
1079 (a->last_scaled_size[0] == '\0' ||
1080 strcmp(scaled_size, a->last_scaled_size)) != 0) {
1081 print_size = 1;
1082 if (strlcpy(a->last_scaled_size, scaled_size,
1083 FMT_SCALED_STRSIZE) >= FMT_SCALED_STRSIZE)
1084 return got_error(GOT_ERR_NO_SPACE);
1086 if (nobj_indexed > 0) {
1087 p_indexed = (nobj_indexed * 100) / nobj_total;
1088 if (p_indexed != a->last_p_indexed) {
1089 a->last_p_indexed = p_indexed;
1090 print_indexed = 1;
1091 print_size = 1;
1094 if (nobj_resolved > 0) {
1095 p_resolved = (nobj_resolved * 100) /
1096 (nobj_total - nobj_loose);
1097 if (p_resolved != a->last_p_resolved) {
1098 a->last_p_resolved = p_resolved;
1099 print_resolved = 1;
1100 print_indexed = 1;
1101 print_size = 1;
1106 if (print_size || print_indexed || print_resolved)
1107 printf("\r");
1108 if (print_size)
1109 printf("%*s fetched", FMT_SCALED_STRSIZE - 2, scaled_size);
1110 if (print_indexed)
1111 printf("; indexing %d%%", p_indexed);
1112 if (print_resolved)
1113 printf("; resolving deltas %d%%", p_resolved);
1114 if (print_size || print_indexed || print_resolved)
1115 fflush(stdout);
1117 return NULL;
1120 static const struct got_error *
1121 create_symref(const char *refname, struct got_reference *target_ref,
1122 int verbosity, struct got_repository *repo)
1124 const struct got_error *err;
1125 struct got_reference *head_symref;
1127 err = got_ref_alloc_symref(&head_symref, refname, target_ref);
1128 if (err)
1129 return err;
1131 err = got_ref_write(head_symref, repo);
1132 if (err == NULL && verbosity > 0) {
1133 printf("Created reference %s: %s\n", GOT_REF_HEAD,
1134 got_ref_get_name(target_ref));
1136 got_ref_close(head_symref);
1137 return err;
1140 static const struct got_error *
1141 list_remote_refs(struct got_pathlist_head *symrefs,
1142 struct got_pathlist_head *refs)
1144 const struct got_error *err;
1145 struct got_pathlist_entry *pe;
1147 TAILQ_FOREACH(pe, symrefs, entry) {
1148 const char *refname = pe->path;
1149 const char *targetref = pe->data;
1151 printf("%s: %s\n", refname, targetref);
1154 TAILQ_FOREACH(pe, refs, entry) {
1155 const char *refname = pe->path;
1156 struct got_object_id *id = pe->data;
1157 char *id_str;
1159 err = got_object_id_str(&id_str, id);
1160 if (err)
1161 return err;
1162 printf("%s: %s\n", refname, id_str);
1163 free(id_str);
1166 return NULL;
1169 static const struct got_error *
1170 create_ref(const char *refname, struct got_object_id *id,
1171 int verbosity, struct got_repository *repo)
1173 const struct got_error *err = NULL;
1174 struct got_reference *ref;
1175 char *id_str;
1177 err = got_object_id_str(&id_str, id);
1178 if (err)
1179 return err;
1181 err = got_ref_alloc(&ref, refname, id);
1182 if (err)
1183 goto done;
1185 err = got_ref_write(ref, repo);
1186 got_ref_close(ref);
1188 if (err == NULL && verbosity >= 0)
1189 printf("Created reference %s: %s\n", refname, id_str);
1190 done:
1191 free(id_str);
1192 return err;
1195 static int
1196 match_wanted_ref(const char *refname, const char *wanted_ref)
1198 if (strncmp(refname, "refs/", 5) != 0)
1199 return 0;
1200 refname += 5;
1203 * Prevent fetching of references that won't make any
1204 * sense outside of the remote repository's context.
1206 if (strncmp(refname, "got/", 4) == 0)
1207 return 0;
1208 if (strncmp(refname, "remotes/", 8) == 0)
1209 return 0;
1211 if (strncmp(wanted_ref, "refs/", 5) == 0)
1212 wanted_ref += 5;
1214 /* Allow prefix match. */
1215 if (got_path_is_child(refname, wanted_ref, strlen(wanted_ref)))
1216 return 1;
1218 /* Allow exact match. */
1219 return (strcmp(refname, wanted_ref) == 0);
1222 static int
1223 is_wanted_ref(struct got_pathlist_head *wanted_refs, const char *refname)
1225 struct got_pathlist_entry *pe;
1227 TAILQ_FOREACH(pe, wanted_refs, entry) {
1228 if (match_wanted_ref(refname, pe->path))
1229 return 1;
1232 return 0;
1235 static const struct got_error *
1236 create_wanted_ref(const char *refname, struct got_object_id *id,
1237 const char *remote_repo_name, int verbosity, struct got_repository *repo)
1239 const struct got_error *err;
1240 char *remote_refname;
1242 if (strncmp("refs/", refname, 5) == 0)
1243 refname += 5;
1245 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
1246 remote_repo_name, refname) == -1)
1247 return got_error_from_errno("asprintf");
1249 err = create_ref(remote_refname, id, verbosity, repo);
1250 free(remote_refname);
1251 return err;
1254 static const struct got_error *
1255 create_gotconfig(const char *proto, const char *host, const char *port,
1256 const char *remote_repo_path, const char *default_branch,
1257 int fetch_all_branches, struct got_pathlist_head *wanted_branches,
1258 struct got_pathlist_head *wanted_refs, int mirror_references,
1259 struct got_repository *repo)
1261 const struct got_error *err = NULL;
1262 char *gotconfig_path = NULL;
1263 char *gotconfig = NULL;
1264 FILE *gotconfig_file = NULL;
1265 const char *branchname = NULL;
1266 char *branches = NULL, *refs = NULL;
1267 ssize_t n;
1269 if (!fetch_all_branches && !TAILQ_EMPTY(wanted_branches)) {
1270 struct got_pathlist_entry *pe;
1271 TAILQ_FOREACH(pe, wanted_branches, entry) {
1272 char *s;
1273 branchname = pe->path;
1274 if (strncmp(branchname, "refs/heads/", 11) == 0)
1275 branchname += 11;
1276 if (asprintf(&s, "%s\"%s\" ",
1277 branches ? branches : "", branchname) == -1) {
1278 err = got_error_from_errno("asprintf");
1279 goto done;
1281 free(branches);
1282 branches = s;
1284 } else if (!fetch_all_branches && default_branch) {
1285 branchname = default_branch;
1286 if (strncmp(branchname, "refs/heads/", 11) == 0)
1287 branchname += 11;
1288 if (asprintf(&branches, "\"%s\" ", branchname) == -1) {
1289 err = got_error_from_errno("asprintf");
1290 goto done;
1293 if (!TAILQ_EMPTY(wanted_refs)) {
1294 struct got_pathlist_entry *pe;
1295 TAILQ_FOREACH(pe, wanted_refs, entry) {
1296 char *s;
1297 const char *refname = pe->path;
1298 if (strncmp(refname, "refs/", 5) == 0)
1299 branchname += 5;
1300 if (asprintf(&s, "%s\"%s\" ",
1301 refs ? refs : "", refname) == -1) {
1302 err = got_error_from_errno("asprintf");
1303 goto done;
1305 free(refs);
1306 refs = s;
1310 /* Create got.conf(5). */
1311 gotconfig_path = got_repo_get_path_gotconfig(repo);
1312 if (gotconfig_path == NULL) {
1313 err = got_error_from_errno("got_repo_get_path_gotconfig");
1314 goto done;
1316 gotconfig_file = fopen(gotconfig_path, "ae");
1317 if (gotconfig_file == NULL) {
1318 err = got_error_from_errno2("fopen", gotconfig_path);
1319 goto done;
1321 if (asprintf(&gotconfig,
1322 "remote \"%s\" {\n"
1323 "\tserver %s\n"
1324 "\tprotocol %s\n"
1325 "%s%s%s"
1326 "\trepository \"%s\"\n"
1327 "%s%s%s"
1328 "%s%s%s"
1329 "%s"
1330 "%s"
1331 "}\n",
1332 GOT_FETCH_DEFAULT_REMOTE_NAME, host, proto,
1333 port ? "\tport " : "", port ? port : "", port ? "\n" : "",
1334 remote_repo_path, branches ? "\tbranch { " : "",
1335 branches ? branches : "", branches ? "}\n" : "",
1336 refs ? "\treference { " : "", refs ? refs : "", refs ? "}\n" : "",
1337 mirror_references ? "\tmirror_references yes\n" : "",
1338 fetch_all_branches ? "\tfetch_all_branches yes\n" : "") == -1) {
1339 err = got_error_from_errno("asprintf");
1340 goto done;
1342 n = fwrite(gotconfig, 1, strlen(gotconfig), gotconfig_file);
1343 if (n != strlen(gotconfig)) {
1344 err = got_ferror(gotconfig_file, GOT_ERR_IO);
1345 goto done;
1348 done:
1349 if (gotconfig_file && fclose(gotconfig_file) == EOF && err == NULL)
1350 err = got_error_from_errno2("fclose", gotconfig_path);
1351 free(gotconfig_path);
1352 free(branches);
1353 return err;
1356 static const struct got_error *
1357 create_gitconfig(const char *git_url, const char *default_branch,
1358 int fetch_all_branches, struct got_pathlist_head *wanted_branches,
1359 struct got_pathlist_head *wanted_refs, int mirror_references,
1360 struct got_repository *repo)
1362 const struct got_error *err = NULL;
1363 char *gitconfig_path = NULL;
1364 char *gitconfig = NULL;
1365 FILE *gitconfig_file = NULL;
1366 char *branches = NULL, *refs = NULL;
1367 const char *branchname;
1368 ssize_t n;
1370 /* Create a config file Git can understand. */
1371 gitconfig_path = got_repo_get_path_gitconfig(repo);
1372 if (gitconfig_path == NULL) {
1373 err = got_error_from_errno("got_repo_get_path_gitconfig");
1374 goto done;
1376 gitconfig_file = fopen(gitconfig_path, "ae");
1377 if (gitconfig_file == NULL) {
1378 err = got_error_from_errno2("fopen", gitconfig_path);
1379 goto done;
1381 if (fetch_all_branches) {
1382 if (mirror_references) {
1383 if (asprintf(&branches,
1384 "\tfetch = refs/heads/*:refs/heads/*\n") == -1) {
1385 err = got_error_from_errno("asprintf");
1386 goto done;
1388 } else if (asprintf(&branches,
1389 "\tfetch = refs/heads/*:refs/remotes/%s/*\n",
1390 GOT_FETCH_DEFAULT_REMOTE_NAME) == -1) {
1391 err = got_error_from_errno("asprintf");
1392 goto done;
1394 } else if (!TAILQ_EMPTY(wanted_branches)) {
1395 struct got_pathlist_entry *pe;
1396 TAILQ_FOREACH(pe, wanted_branches, entry) {
1397 char *s;
1398 branchname = pe->path;
1399 if (strncmp(branchname, "refs/heads/", 11) == 0)
1400 branchname += 11;
1401 if (mirror_references) {
1402 if (asprintf(&s,
1403 "%s\tfetch = refs/heads/%s:refs/heads/%s\n",
1404 branches ? branches : "",
1405 branchname, branchname) == -1) {
1406 err = got_error_from_errno("asprintf");
1407 goto done;
1409 } else if (asprintf(&s,
1410 "%s\tfetch = refs/heads/%s:refs/remotes/%s/%s\n",
1411 branches ? branches : "",
1412 branchname, GOT_FETCH_DEFAULT_REMOTE_NAME,
1413 branchname) == -1) {
1414 err = got_error_from_errno("asprintf");
1415 goto done;
1417 free(branches);
1418 branches = s;
1420 } else {
1422 * If the server specified a default branch, use just that one.
1423 * Otherwise fall back to fetching all branches on next fetch.
1425 if (default_branch) {
1426 branchname = default_branch;
1427 if (strncmp(branchname, "refs/heads/", 11) == 0)
1428 branchname += 11;
1429 } else
1430 branchname = "*"; /* fall back to all branches */
1431 if (mirror_references) {
1432 if (asprintf(&branches,
1433 "\tfetch = refs/heads/%s:refs/heads/%s\n",
1434 branchname, branchname) == -1) {
1435 err = got_error_from_errno("asprintf");
1436 goto done;
1438 } else if (asprintf(&branches,
1439 "\tfetch = refs/heads/%s:refs/remotes/%s/%s\n",
1440 branchname, GOT_FETCH_DEFAULT_REMOTE_NAME,
1441 branchname) == -1) {
1442 err = got_error_from_errno("asprintf");
1443 goto done;
1446 if (!TAILQ_EMPTY(wanted_refs)) {
1447 struct got_pathlist_entry *pe;
1448 TAILQ_FOREACH(pe, wanted_refs, entry) {
1449 char *s;
1450 const char *refname = pe->path;
1451 if (strncmp(refname, "refs/", 5) == 0)
1452 refname += 5;
1453 if (mirror_references) {
1454 if (asprintf(&s,
1455 "%s\tfetch = refs/%s:refs/%s\n",
1456 refs ? refs : "", refname, refname) == -1) {
1457 err = got_error_from_errno("asprintf");
1458 goto done;
1460 } else if (asprintf(&s,
1461 "%s\tfetch = refs/%s:refs/remotes/%s/%s\n",
1462 refs ? refs : "",
1463 refname, GOT_FETCH_DEFAULT_REMOTE_NAME,
1464 refname) == -1) {
1465 err = got_error_from_errno("asprintf");
1466 goto done;
1468 free(refs);
1469 refs = s;
1473 if (asprintf(&gitconfig,
1474 "[remote \"%s\"]\n"
1475 "\turl = %s\n"
1476 "%s"
1477 "%s"
1478 "\tfetch = refs/tags/*:refs/tags/*\n",
1479 GOT_FETCH_DEFAULT_REMOTE_NAME, git_url, branches ? branches : "",
1480 refs ? refs : "") == -1) {
1481 err = got_error_from_errno("asprintf");
1482 goto done;
1484 n = fwrite(gitconfig, 1, strlen(gitconfig), gitconfig_file);
1485 if (n != strlen(gitconfig)) {
1486 err = got_ferror(gitconfig_file, GOT_ERR_IO);
1487 goto done;
1489 done:
1490 if (gitconfig_file && fclose(gitconfig_file) == EOF && err == NULL)
1491 err = got_error_from_errno2("fclose", gitconfig_path);
1492 free(gitconfig_path);
1493 free(branches);
1494 return err;
1497 static const struct got_error *
1498 create_config_files(const char *proto, const char *host, const char *port,
1499 const char *remote_repo_path, const char *git_url, int fetch_all_branches,
1500 int mirror_references, struct got_pathlist_head *symrefs,
1501 struct got_pathlist_head *wanted_branches,
1502 struct got_pathlist_head *wanted_refs, struct got_repository *repo)
1504 const struct got_error *err = NULL;
1505 const char *default_branch = NULL;
1506 struct got_pathlist_entry *pe;
1509 * If we asked for a set of wanted branches then use the first
1510 * one of those.
1512 if (!TAILQ_EMPTY(wanted_branches)) {
1513 pe = TAILQ_FIRST(wanted_branches);
1514 default_branch = pe->path;
1515 } else {
1516 /* First HEAD ref listed by server is the default branch. */
1517 TAILQ_FOREACH(pe, symrefs, entry) {
1518 const char *refname = pe->path;
1519 const char *target = pe->data;
1521 if (strcmp(refname, GOT_REF_HEAD) != 0)
1522 continue;
1524 default_branch = target;
1525 break;
1529 /* Create got.conf(5). */
1530 err = create_gotconfig(proto, host, port, remote_repo_path,
1531 default_branch, fetch_all_branches, wanted_branches,
1532 wanted_refs, mirror_references, repo);
1533 if (err)
1534 return err;
1536 /* Create a config file Git can understand. */
1537 return create_gitconfig(git_url, default_branch, fetch_all_branches,
1538 wanted_branches, wanted_refs, mirror_references, repo);
1541 static const struct got_error *
1542 cmd_clone(int argc, char *argv[])
1544 const struct got_error *error = NULL;
1545 const char *uri, *dirname;
1546 char *proto, *host, *port, *repo_name, *server_path;
1547 char *default_destdir = NULL, *id_str = NULL;
1548 const char *repo_path;
1549 struct got_repository *repo = NULL;
1550 struct got_pathlist_head refs, symrefs, wanted_branches, wanted_refs;
1551 struct got_pathlist_entry *pe;
1552 struct got_object_id *pack_hash = NULL;
1553 int ch, fetchfd = -1, fetchstatus;
1554 pid_t fetchpid = -1;
1555 struct got_fetch_progress_arg fpa;
1556 char *git_url = NULL;
1557 int verbosity = 0, fetch_all_branches = 0, mirror_references = 0;
1558 int bflag = 0, list_refs_only = 0;
1559 int *pack_fds = NULL;
1561 TAILQ_INIT(&refs);
1562 TAILQ_INIT(&symrefs);
1563 TAILQ_INIT(&wanted_branches);
1564 TAILQ_INIT(&wanted_refs);
1566 while ((ch = getopt(argc, argv, "ab:lmqR:v")) != -1) {
1567 switch (ch) {
1568 case 'a':
1569 fetch_all_branches = 1;
1570 break;
1571 case 'b':
1572 error = got_pathlist_append(&wanted_branches,
1573 optarg, NULL);
1574 if (error)
1575 return error;
1576 bflag = 1;
1577 break;
1578 case 'l':
1579 list_refs_only = 1;
1580 break;
1581 case 'm':
1582 mirror_references = 1;
1583 break;
1584 case 'q':
1585 verbosity = -1;
1586 break;
1587 case 'R':
1588 error = got_pathlist_append(&wanted_refs,
1589 optarg, NULL);
1590 if (error)
1591 return error;
1592 break;
1593 case 'v':
1594 if (verbosity < 0)
1595 verbosity = 0;
1596 else if (verbosity < 3)
1597 verbosity++;
1598 break;
1599 default:
1600 usage_clone();
1601 break;
1604 argc -= optind;
1605 argv += optind;
1607 if (fetch_all_branches && !TAILQ_EMPTY(&wanted_branches))
1608 option_conflict('a', 'b');
1609 if (list_refs_only) {
1610 if (!TAILQ_EMPTY(&wanted_branches))
1611 option_conflict('l', 'b');
1612 if (fetch_all_branches)
1613 option_conflict('l', 'a');
1614 if (mirror_references)
1615 option_conflict('l', 'm');
1616 if (!TAILQ_EMPTY(&wanted_refs))
1617 option_conflict('l', 'R');
1620 uri = argv[0];
1622 if (argc == 1)
1623 dirname = NULL;
1624 else if (argc == 2)
1625 dirname = argv[1];
1626 else
1627 usage_clone();
1629 error = got_dial_parse_uri(&proto, &host, &port, &server_path,
1630 &repo_name, uri);
1631 if (error)
1632 goto done;
1634 if (asprintf(&git_url, "%s://%s%s%s%s%s", proto,
1635 host, port ? ":" : "", port ? port : "",
1636 server_path[0] != '/' ? "/" : "", server_path) == -1) {
1637 error = got_error_from_errno("asprintf");
1638 goto done;
1641 if (strcmp(proto, "git") == 0) {
1642 #ifndef PROFILE
1643 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
1644 "sendfd dns inet unveil", NULL) == -1)
1645 err(1, "pledge");
1646 #endif
1647 } else if (strcmp(proto, "git+ssh") == 0 ||
1648 strcmp(proto, "ssh") == 0) {
1649 #ifndef PROFILE
1650 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
1651 "sendfd unveil", NULL) == -1)
1652 err(1, "pledge");
1653 #endif
1654 } else if (strcmp(proto, "http") == 0 ||
1655 strcmp(proto, "git+http") == 0) {
1656 error = got_error_path(proto, GOT_ERR_NOT_IMPL);
1657 goto done;
1658 } else {
1659 error = got_error_path(proto, GOT_ERR_BAD_PROTO);
1660 goto done;
1662 if (dirname == NULL) {
1663 if (asprintf(&default_destdir, "%s.git", repo_name) == -1) {
1664 error = got_error_from_errno("asprintf");
1665 goto done;
1667 repo_path = default_destdir;
1668 } else
1669 repo_path = dirname;
1671 if (!list_refs_only) {
1672 error = got_path_mkdir(repo_path);
1673 if (error &&
1674 (!(error->code == GOT_ERR_ERRNO && errno == EISDIR) &&
1675 !(error->code == GOT_ERR_ERRNO && errno == EEXIST)))
1676 goto done;
1677 if (!got_path_dir_is_empty(repo_path)) {
1678 error = got_error_path(repo_path,
1679 GOT_ERR_DIR_NOT_EMPTY);
1680 goto done;
1684 error = got_dial_apply_unveil(proto);
1685 if (error)
1686 goto done;
1688 error = apply_unveil(repo_path, 0, NULL);
1689 if (error)
1690 goto done;
1692 if (verbosity >= 0)
1693 printf("Connecting to %s\n", git_url);
1695 error = got_fetch_connect(&fetchpid, &fetchfd, proto, host, port,
1696 server_path, verbosity);
1697 if (error)
1698 goto done;
1700 if (!list_refs_only) {
1701 error = got_repo_init(repo_path, NULL);
1702 if (error)
1703 goto done;
1704 error = got_repo_pack_fds_open(&pack_fds);
1705 if (error != NULL)
1706 goto done;
1707 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
1708 if (error)
1709 goto done;
1712 fpa.last_scaled_size[0] = '\0';
1713 fpa.last_p_indexed = -1;
1714 fpa.last_p_resolved = -1;
1715 fpa.verbosity = verbosity;
1716 fpa.create_configs = 1;
1717 fpa.configs_created = 0;
1718 fpa.repo = repo;
1719 fpa.config_info.symrefs = &symrefs;
1720 fpa.config_info.wanted_branches = &wanted_branches;
1721 fpa.config_info.wanted_refs = &wanted_refs;
1722 fpa.config_info.proto = proto;
1723 fpa.config_info.host = host;
1724 fpa.config_info.port = port;
1725 fpa.config_info.remote_repo_path = server_path;
1726 fpa.config_info.git_url = git_url;
1727 fpa.config_info.fetch_all_branches = fetch_all_branches;
1728 fpa.config_info.mirror_references = mirror_references;
1729 error = got_fetch_pack(&pack_hash, &refs, &symrefs,
1730 GOT_FETCH_DEFAULT_REMOTE_NAME, mirror_references,
1731 fetch_all_branches, &wanted_branches, &wanted_refs,
1732 list_refs_only, verbosity, fetchfd, repo, NULL, NULL, bflag,
1733 fetch_progress, &fpa);
1734 if (error)
1735 goto done;
1737 if (list_refs_only) {
1738 error = list_remote_refs(&symrefs, &refs);
1739 goto done;
1742 if (pack_hash == NULL) {
1743 error = got_error_fmt(GOT_ERR_FETCH_FAILED, "%s",
1744 "server sent an empty pack file");
1745 goto done;
1747 error = got_object_id_str(&id_str, pack_hash);
1748 if (error)
1749 goto done;
1750 if (verbosity >= 0)
1751 printf("\nFetched %s.pack\n", id_str);
1752 free(id_str);
1754 /* Set up references provided with the pack file. */
1755 TAILQ_FOREACH(pe, &refs, entry) {
1756 const char *refname = pe->path;
1757 struct got_object_id *id = pe->data;
1758 char *remote_refname;
1760 if (is_wanted_ref(&wanted_refs, refname) &&
1761 !mirror_references) {
1762 error = create_wanted_ref(refname, id,
1763 GOT_FETCH_DEFAULT_REMOTE_NAME,
1764 verbosity - 1, repo);
1765 if (error)
1766 goto done;
1767 continue;
1770 error = create_ref(refname, id, verbosity - 1, repo);
1771 if (error)
1772 goto done;
1774 if (mirror_references)
1775 continue;
1777 if (strncmp("refs/heads/", refname, 11) != 0)
1778 continue;
1780 if (asprintf(&remote_refname,
1781 "refs/remotes/%s/%s", GOT_FETCH_DEFAULT_REMOTE_NAME,
1782 refname + 11) == -1) {
1783 error = got_error_from_errno("asprintf");
1784 goto done;
1786 error = create_ref(remote_refname, id, verbosity - 1, repo);
1787 free(remote_refname);
1788 if (error)
1789 goto done;
1792 /* Set the HEAD reference if the server provided one. */
1793 TAILQ_FOREACH(pe, &symrefs, entry) {
1794 struct got_reference *target_ref;
1795 const char *refname = pe->path;
1796 const char *target = pe->data;
1797 char *remote_refname = NULL, *remote_target = NULL;
1799 if (strcmp(refname, GOT_REF_HEAD) != 0)
1800 continue;
1802 error = got_ref_open(&target_ref, repo, target, 0);
1803 if (error) {
1804 if (error->code == GOT_ERR_NOT_REF) {
1805 error = NULL;
1806 continue;
1808 goto done;
1811 error = create_symref(refname, target_ref, verbosity, repo);
1812 got_ref_close(target_ref);
1813 if (error)
1814 goto done;
1816 if (mirror_references)
1817 continue;
1819 if (strncmp("refs/heads/", target, 11) != 0)
1820 continue;
1822 if (asprintf(&remote_refname,
1823 "refs/remotes/%s/%s", GOT_FETCH_DEFAULT_REMOTE_NAME,
1824 refname) == -1) {
1825 error = got_error_from_errno("asprintf");
1826 goto done;
1828 if (asprintf(&remote_target,
1829 "refs/remotes/%s/%s", GOT_FETCH_DEFAULT_REMOTE_NAME,
1830 target + 11) == -1) {
1831 error = got_error_from_errno("asprintf");
1832 free(remote_refname);
1833 goto done;
1835 error = got_ref_open(&target_ref, repo, remote_target, 0);
1836 if (error) {
1837 free(remote_refname);
1838 free(remote_target);
1839 if (error->code == GOT_ERR_NOT_REF) {
1840 error = NULL;
1841 continue;
1843 goto done;
1845 error = create_symref(remote_refname, target_ref,
1846 verbosity - 1, repo);
1847 free(remote_refname);
1848 free(remote_target);
1849 got_ref_close(target_ref);
1850 if (error)
1851 goto done;
1853 if (pe == NULL) {
1855 * We failed to set the HEAD reference. If we asked for
1856 * a set of wanted branches use the first of one of those
1857 * which could be fetched instead.
1859 TAILQ_FOREACH(pe, &wanted_branches, entry) {
1860 const char *target = pe->path;
1861 struct got_reference *target_ref;
1863 error = got_ref_open(&target_ref, repo, target, 0);
1864 if (error) {
1865 if (error->code == GOT_ERR_NOT_REF) {
1866 error = NULL;
1867 continue;
1869 goto done;
1872 error = create_symref(GOT_REF_HEAD, target_ref,
1873 verbosity, repo);
1874 got_ref_close(target_ref);
1875 if (error)
1876 goto done;
1877 break;
1880 if (!fpa.configs_created && pe != NULL) {
1881 error = create_config_files(fpa.config_info.proto,
1882 fpa.config_info.host, fpa.config_info.port,
1883 fpa.config_info.remote_repo_path,
1884 fpa.config_info.git_url,
1885 fpa.config_info.fetch_all_branches,
1886 fpa.config_info.mirror_references,
1887 fpa.config_info.symrefs,
1888 fpa.config_info.wanted_branches,
1889 fpa.config_info.wanted_refs, fpa.repo);
1890 if (error)
1891 goto done;
1895 if (verbosity >= 0)
1896 printf("Created %s repository '%s'\n",
1897 mirror_references ? "mirrored" : "cloned", repo_path);
1898 done:
1899 if (pack_fds) {
1900 const struct got_error *pack_err =
1901 got_repo_pack_fds_close(pack_fds);
1902 if (error == NULL)
1903 error = pack_err;
1905 if (fetchpid > 0) {
1906 if (kill(fetchpid, SIGTERM) == -1)
1907 error = got_error_from_errno("kill");
1908 if (waitpid(fetchpid, &fetchstatus, 0) == -1 && error == NULL)
1909 error = got_error_from_errno("waitpid");
1911 if (fetchfd != -1 && close(fetchfd) == -1 && error == NULL)
1912 error = got_error_from_errno("close");
1913 if (repo) {
1914 const struct got_error *close_err = got_repo_close(repo);
1915 if (error == NULL)
1916 error = close_err;
1918 got_pathlist_free(&refs, GOT_PATHLIST_FREE_ALL);
1919 got_pathlist_free(&symrefs, GOT_PATHLIST_FREE_ALL);
1920 got_pathlist_free(&wanted_branches, GOT_PATHLIST_FREE_NONE);
1921 got_pathlist_free(&wanted_refs, GOT_PATHLIST_FREE_NONE);
1922 free(pack_hash);
1923 free(proto);
1924 free(host);
1925 free(port);
1926 free(server_path);
1927 free(repo_name);
1928 free(default_destdir);
1929 free(git_url);
1930 return error;
1933 static const struct got_error *
1934 update_ref(struct got_reference *ref, struct got_object_id *new_id,
1935 int replace_tags, int verbosity, struct got_repository *repo)
1937 const struct got_error *err = NULL;
1938 char *new_id_str = NULL;
1939 struct got_object_id *old_id = NULL;
1941 err = got_object_id_str(&new_id_str, new_id);
1942 if (err)
1943 goto done;
1945 if (!replace_tags &&
1946 strncmp(got_ref_get_name(ref), "refs/tags/", 10) == 0) {
1947 err = got_ref_resolve(&old_id, repo, ref);
1948 if (err)
1949 goto done;
1950 if (got_object_id_cmp(old_id, new_id) == 0)
1951 goto done;
1952 if (verbosity >= 0) {
1953 printf("Rejecting update of existing tag %s: %s\n",
1954 got_ref_get_name(ref), new_id_str);
1956 goto done;
1959 if (got_ref_is_symbolic(ref)) {
1960 if (verbosity >= 0) {
1961 printf("Replacing reference %s: %s\n",
1962 got_ref_get_name(ref),
1963 got_ref_get_symref_target(ref));
1965 err = got_ref_change_symref_to_ref(ref, new_id);
1966 if (err)
1967 goto done;
1968 err = got_ref_write(ref, repo);
1969 if (err)
1970 goto done;
1971 } else {
1972 err = got_ref_resolve(&old_id, repo, ref);
1973 if (err)
1974 goto done;
1975 if (got_object_id_cmp(old_id, new_id) == 0)
1976 goto done;
1978 err = got_ref_change_ref(ref, new_id);
1979 if (err)
1980 goto done;
1981 err = got_ref_write(ref, repo);
1982 if (err)
1983 goto done;
1986 if (verbosity >= 0)
1987 printf("Updated %s: %s\n", got_ref_get_name(ref),
1988 new_id_str);
1989 done:
1990 free(old_id);
1991 free(new_id_str);
1992 return err;
1995 static const struct got_error *
1996 update_symref(const char *refname, struct got_reference *target_ref,
1997 int verbosity, struct got_repository *repo)
1999 const struct got_error *err = NULL, *unlock_err;
2000 struct got_reference *symref;
2001 int symref_is_locked = 0;
2003 err = got_ref_open(&symref, repo, refname, 1);
2004 if (err) {
2005 if (err->code != GOT_ERR_NOT_REF)
2006 return err;
2007 err = got_ref_alloc_symref(&symref, refname, target_ref);
2008 if (err)
2009 goto done;
2011 err = got_ref_write(symref, repo);
2012 if (err)
2013 goto done;
2015 if (verbosity >= 0)
2016 printf("Created reference %s: %s\n",
2017 got_ref_get_name(symref),
2018 got_ref_get_symref_target(symref));
2019 } else {
2020 symref_is_locked = 1;
2022 if (strcmp(got_ref_get_symref_target(symref),
2023 got_ref_get_name(target_ref)) == 0)
2024 goto done;
2026 err = got_ref_change_symref(symref,
2027 got_ref_get_name(target_ref));
2028 if (err)
2029 goto done;
2031 err = got_ref_write(symref, repo);
2032 if (err)
2033 goto done;
2035 if (verbosity >= 0)
2036 printf("Updated %s: %s\n", got_ref_get_name(symref),
2037 got_ref_get_symref_target(symref));
2040 done:
2041 if (symref_is_locked) {
2042 unlock_err = got_ref_unlock(symref);
2043 if (unlock_err && err == NULL)
2044 err = unlock_err;
2046 got_ref_close(symref);
2047 return err;
2050 __dead static void
2051 usage_fetch(void)
2053 fprintf(stderr, "usage: %s fetch [-adlqtvX] [-b branch] "
2054 "[-R reference] [-r repository-path] [remote-repository]\n",
2055 getprogname());
2056 exit(1);
2059 static const struct got_error *
2060 delete_missing_ref(struct got_reference *ref,
2061 int verbosity, struct got_repository *repo)
2063 const struct got_error *err = NULL;
2064 struct got_object_id *id = NULL;
2065 char *id_str = NULL;
2067 if (got_ref_is_symbolic(ref)) {
2068 err = got_ref_delete(ref, repo);
2069 if (err)
2070 return err;
2071 if (verbosity >= 0) {
2072 printf("Deleted %s: %s\n",
2073 got_ref_get_name(ref),
2074 got_ref_get_symref_target(ref));
2076 } else {
2077 err = got_ref_resolve(&id, repo, ref);
2078 if (err)
2079 return err;
2080 err = got_object_id_str(&id_str, id);
2081 if (err)
2082 goto done;
2084 err = got_ref_delete(ref, repo);
2085 if (err)
2086 goto done;
2087 if (verbosity >= 0) {
2088 printf("Deleted %s: %s\n",
2089 got_ref_get_name(ref), id_str);
2092 done:
2093 free(id);
2094 free(id_str);
2095 return err;
2098 static const struct got_error *
2099 delete_missing_refs(struct got_pathlist_head *their_refs,
2100 struct got_pathlist_head *their_symrefs,
2101 const struct got_remote_repo *remote,
2102 int verbosity, struct got_repository *repo)
2104 const struct got_error *err = NULL, *unlock_err;
2105 struct got_reflist_head my_refs;
2106 struct got_reflist_entry *re;
2107 struct got_pathlist_entry *pe;
2108 char *remote_namespace = NULL;
2109 char *local_refname = NULL;
2111 TAILQ_INIT(&my_refs);
2113 if (asprintf(&remote_namespace, "refs/remotes/%s/", remote->name)
2114 == -1)
2115 return got_error_from_errno("asprintf");
2117 err = got_ref_list(&my_refs, repo, NULL, got_ref_cmp_by_name, NULL);
2118 if (err)
2119 goto done;
2121 TAILQ_FOREACH(re, &my_refs, entry) {
2122 const char *refname = got_ref_get_name(re->ref);
2123 const char *their_refname;
2125 if (remote->mirror_references) {
2126 their_refname = refname;
2127 } else {
2128 if (strncmp(refname, remote_namespace,
2129 strlen(remote_namespace)) == 0) {
2130 if (strcmp(refname + strlen(remote_namespace),
2131 GOT_REF_HEAD) == 0)
2132 continue;
2133 if (asprintf(&local_refname, "refs/heads/%s",
2134 refname + strlen(remote_namespace)) == -1) {
2135 err = got_error_from_errno("asprintf");
2136 goto done;
2138 } else if (strncmp(refname, "refs/tags/", 10) != 0)
2139 continue;
2141 their_refname = local_refname;
2144 TAILQ_FOREACH(pe, their_refs, entry) {
2145 if (strcmp(their_refname, pe->path) == 0)
2146 break;
2148 if (pe != NULL)
2149 continue;
2151 TAILQ_FOREACH(pe, their_symrefs, entry) {
2152 if (strcmp(their_refname, pe->path) == 0)
2153 break;
2155 if (pe != NULL)
2156 continue;
2158 err = delete_missing_ref(re->ref, verbosity, repo);
2159 if (err)
2160 break;
2162 if (local_refname) {
2163 struct got_reference *ref;
2164 err = got_ref_open(&ref, repo, local_refname, 1);
2165 if (err) {
2166 if (err->code != GOT_ERR_NOT_REF)
2167 break;
2168 free(local_refname);
2169 local_refname = NULL;
2170 continue;
2172 err = delete_missing_ref(ref, verbosity, repo);
2173 if (err)
2174 break;
2175 unlock_err = got_ref_unlock(ref);
2176 got_ref_close(ref);
2177 if (unlock_err && err == NULL) {
2178 err = unlock_err;
2179 break;
2182 free(local_refname);
2183 local_refname = NULL;
2186 done:
2187 got_ref_list_free(&my_refs);
2188 free(remote_namespace);
2189 free(local_refname);
2190 return err;
2193 static const struct got_error *
2194 update_wanted_ref(const char *refname, struct got_object_id *id,
2195 const char *remote_repo_name, int verbosity, struct got_repository *repo)
2197 const struct got_error *err, *unlock_err;
2198 char *remote_refname;
2199 struct got_reference *ref;
2201 if (strncmp("refs/", refname, 5) == 0)
2202 refname += 5;
2204 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
2205 remote_repo_name, refname) == -1)
2206 return got_error_from_errno("asprintf");
2208 err = got_ref_open(&ref, repo, remote_refname, 1);
2209 if (err) {
2210 if (err->code != GOT_ERR_NOT_REF)
2211 goto done;
2212 err = create_ref(remote_refname, id, verbosity, repo);
2213 } else {
2214 err = update_ref(ref, id, 0, verbosity, repo);
2215 unlock_err = got_ref_unlock(ref);
2216 if (unlock_err && err == NULL)
2217 err = unlock_err;
2218 got_ref_close(ref);
2220 done:
2221 free(remote_refname);
2222 return err;
2225 static const struct got_error *
2226 delete_ref(struct got_repository *repo, struct got_reference *ref)
2228 const struct got_error *err = NULL;
2229 struct got_object_id *id = NULL;
2230 char *id_str = NULL;
2231 const char *target;
2233 if (got_ref_is_symbolic(ref)) {
2234 target = got_ref_get_symref_target(ref);
2235 } else {
2236 err = got_ref_resolve(&id, repo, ref);
2237 if (err)
2238 goto done;
2239 err = got_object_id_str(&id_str, id);
2240 if (err)
2241 goto done;
2242 target = id_str;
2245 err = got_ref_delete(ref, repo);
2246 if (err)
2247 goto done;
2249 printf("Deleted %s: %s\n", got_ref_get_name(ref), target);
2250 done:
2251 free(id);
2252 free(id_str);
2253 return err;
2256 static const struct got_error *
2257 delete_refs_for_remote(struct got_repository *repo, const char *remote_name)
2259 const struct got_error *err = NULL;
2260 struct got_reflist_head refs;
2261 struct got_reflist_entry *re;
2262 char *prefix;
2264 TAILQ_INIT(&refs);
2266 if (asprintf(&prefix, "refs/remotes/%s", remote_name) == -1) {
2267 err = got_error_from_errno("asprintf");
2268 goto done;
2270 err = got_ref_list(&refs, repo, prefix, got_ref_cmp_by_name, NULL);
2271 if (err)
2272 goto done;
2274 TAILQ_FOREACH(re, &refs, entry)
2275 delete_ref(repo, re->ref);
2276 done:
2277 got_ref_list_free(&refs);
2278 return err;
2281 static const struct got_error *
2282 cmd_fetch(int argc, char *argv[])
2284 const struct got_error *error = NULL, *unlock_err;
2285 char *cwd = NULL, *repo_path = NULL;
2286 const char *remote_name;
2287 char *proto = NULL, *host = NULL, *port = NULL;
2288 char *repo_name = NULL, *server_path = NULL;
2289 const struct got_remote_repo *remotes, *remote = NULL;
2290 int nremotes;
2291 char *id_str = NULL;
2292 struct got_repository *repo = NULL;
2293 struct got_worktree *worktree = NULL;
2294 const struct got_gotconfig *repo_conf = NULL, *worktree_conf = NULL;
2295 struct got_pathlist_head refs, symrefs, wanted_branches, wanted_refs;
2296 struct got_pathlist_entry *pe;
2297 struct got_reflist_head remote_refs;
2298 struct got_reflist_entry *re;
2299 struct got_object_id *pack_hash = NULL;
2300 int i, ch, fetchfd = -1, fetchstatus;
2301 pid_t fetchpid = -1;
2302 struct got_fetch_progress_arg fpa;
2303 int verbosity = 0, fetch_all_branches = 0, list_refs_only = 0;
2304 int delete_refs = 0, replace_tags = 0, delete_remote = 0;
2305 int *pack_fds = NULL, have_bflag = 0;
2306 const char *remote_head = NULL, *worktree_branch = NULL;
2308 TAILQ_INIT(&refs);
2309 TAILQ_INIT(&symrefs);
2310 TAILQ_INIT(&remote_refs);
2311 TAILQ_INIT(&wanted_branches);
2312 TAILQ_INIT(&wanted_refs);
2314 while ((ch = getopt(argc, argv, "ab:dlqR:r:tvX")) != -1) {
2315 switch (ch) {
2316 case 'a':
2317 fetch_all_branches = 1;
2318 break;
2319 case 'b':
2320 error = got_pathlist_append(&wanted_branches,
2321 optarg, NULL);
2322 if (error)
2323 return error;
2324 have_bflag = 1;
2325 break;
2326 case 'd':
2327 delete_refs = 1;
2328 break;
2329 case 'l':
2330 list_refs_only = 1;
2331 break;
2332 case 'q':
2333 verbosity = -1;
2334 break;
2335 case 'R':
2336 error = got_pathlist_append(&wanted_refs,
2337 optarg, NULL);
2338 if (error)
2339 return error;
2340 break;
2341 case 'r':
2342 repo_path = realpath(optarg, NULL);
2343 if (repo_path == NULL)
2344 return got_error_from_errno2("realpath",
2345 optarg);
2346 got_path_strip_trailing_slashes(repo_path);
2347 break;
2348 case 't':
2349 replace_tags = 1;
2350 break;
2351 case 'v':
2352 if (verbosity < 0)
2353 verbosity = 0;
2354 else if (verbosity < 3)
2355 verbosity++;
2356 break;
2357 case 'X':
2358 delete_remote = 1;
2359 break;
2360 default:
2361 usage_fetch();
2362 break;
2365 argc -= optind;
2366 argv += optind;
2368 if (fetch_all_branches && !TAILQ_EMPTY(&wanted_branches))
2369 option_conflict('a', 'b');
2370 if (list_refs_only) {
2371 if (!TAILQ_EMPTY(&wanted_branches))
2372 option_conflict('l', 'b');
2373 if (fetch_all_branches)
2374 option_conflict('l', 'a');
2375 if (delete_refs)
2376 option_conflict('l', 'd');
2377 if (delete_remote)
2378 option_conflict('l', 'X');
2380 if (delete_remote) {
2381 if (fetch_all_branches)
2382 option_conflict('X', 'a');
2383 if (!TAILQ_EMPTY(&wanted_branches))
2384 option_conflict('X', 'b');
2385 if (delete_refs)
2386 option_conflict('X', 'd');
2387 if (replace_tags)
2388 option_conflict('X', 't');
2389 if (!TAILQ_EMPTY(&wanted_refs))
2390 option_conflict('X', 'R');
2393 if (argc == 0) {
2394 if (delete_remote)
2395 errx(1, "-X option requires a remote name");
2396 remote_name = GOT_FETCH_DEFAULT_REMOTE_NAME;
2397 } else if (argc == 1)
2398 remote_name = argv[0];
2399 else
2400 usage_fetch();
2402 cwd = getcwd(NULL, 0);
2403 if (cwd == NULL) {
2404 error = got_error_from_errno("getcwd");
2405 goto done;
2408 error = got_repo_pack_fds_open(&pack_fds);
2409 if (error != NULL)
2410 goto done;
2412 if (repo_path == NULL) {
2413 error = got_worktree_open(&worktree, cwd);
2414 if (error && error->code != GOT_ERR_NOT_WORKTREE)
2415 goto done;
2416 else
2417 error = NULL;
2418 if (worktree) {
2419 repo_path =
2420 strdup(got_worktree_get_repo_path(worktree));
2421 if (repo_path == NULL)
2422 error = got_error_from_errno("strdup");
2423 if (error)
2424 goto done;
2425 } else {
2426 repo_path = strdup(cwd);
2427 if (repo_path == NULL) {
2428 error = got_error_from_errno("strdup");
2429 goto done;
2434 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
2435 if (error)
2436 goto done;
2438 if (delete_remote) {
2439 error = delete_refs_for_remote(repo, remote_name);
2440 goto done; /* nothing else to do */
2443 if (worktree) {
2444 worktree_conf = got_worktree_get_gotconfig(worktree);
2445 if (worktree_conf) {
2446 got_gotconfig_get_remotes(&nremotes, &remotes,
2447 worktree_conf);
2448 for (i = 0; i < nremotes; i++) {
2449 if (strcmp(remotes[i].name, remote_name) == 0) {
2450 remote = &remotes[i];
2451 break;
2456 if (remote == NULL) {
2457 repo_conf = got_repo_get_gotconfig(repo);
2458 if (repo_conf) {
2459 got_gotconfig_get_remotes(&nremotes, &remotes,
2460 repo_conf);
2461 for (i = 0; i < nremotes; i++) {
2462 if (strcmp(remotes[i].name, remote_name) == 0) {
2463 remote = &remotes[i];
2464 break;
2469 if (remote == NULL) {
2470 got_repo_get_gitconfig_remotes(&nremotes, &remotes, repo);
2471 for (i = 0; i < nremotes; i++) {
2472 if (strcmp(remotes[i].name, remote_name) == 0) {
2473 remote = &remotes[i];
2474 break;
2478 if (remote == NULL) {
2479 error = got_error_path(remote_name, GOT_ERR_NO_REMOTE);
2480 goto done;
2483 if (TAILQ_EMPTY(&wanted_branches)) {
2484 if (!fetch_all_branches)
2485 fetch_all_branches = remote->fetch_all_branches;
2486 for (i = 0; i < remote->nfetch_branches; i++) {
2487 error = got_pathlist_append(&wanted_branches,
2488 remote->fetch_branches[i], NULL);
2489 if (error)
2490 goto done;
2493 if (TAILQ_EMPTY(&wanted_refs)) {
2494 for (i = 0; i < remote->nfetch_refs; i++) {
2495 error = got_pathlist_append(&wanted_refs,
2496 remote->fetch_refs[i], NULL);
2497 if (error)
2498 goto done;
2502 error = got_dial_parse_uri(&proto, &host, &port, &server_path,
2503 &repo_name, remote->fetch_url);
2504 if (error)
2505 goto done;
2507 if (strcmp(proto, "git") == 0) {
2508 #ifndef PROFILE
2509 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
2510 "sendfd dns inet unveil", NULL) == -1)
2511 err(1, "pledge");
2512 #endif
2513 } else if (strcmp(proto, "git+ssh") == 0 ||
2514 strcmp(proto, "ssh") == 0) {
2515 #ifndef PROFILE
2516 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
2517 "sendfd unveil", NULL) == -1)
2518 err(1, "pledge");
2519 #endif
2520 } else if (strcmp(proto, "http") == 0 ||
2521 strcmp(proto, "git+http") == 0) {
2522 error = got_error_path(proto, GOT_ERR_NOT_IMPL);
2523 goto done;
2524 } else {
2525 error = got_error_path(proto, GOT_ERR_BAD_PROTO);
2526 goto done;
2529 error = got_dial_apply_unveil(proto);
2530 if (error)
2531 goto done;
2533 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
2534 if (error)
2535 goto done;
2537 if (verbosity >= 0) {
2538 printf("Connecting to \"%s\" %s://%s%s%s%s%s\n",
2539 remote->name, proto, host,
2540 port ? ":" : "", port ? port : "",
2541 *server_path == '/' ? "" : "/", server_path);
2544 error = got_fetch_connect(&fetchpid, &fetchfd, proto, host, port,
2545 server_path, verbosity);
2546 if (error)
2547 goto done;
2549 if (!have_bflag) {
2551 * If set, get this remote's HEAD ref target so
2552 * if it has changed on the server we can fetch it.
2554 error = got_ref_list(&remote_refs, repo, "refs/remotes",
2555 got_ref_cmp_by_name, repo);
2556 if (error)
2557 goto done;
2559 TAILQ_FOREACH(re, &remote_refs, entry) {
2560 const char *remote_refname, *remote_target;
2561 size_t remote_name_len;
2563 if (!got_ref_is_symbolic(re->ref))
2564 continue;
2566 remote_name_len = strlen(remote->name);
2567 remote_refname = got_ref_get_name(re->ref);
2569 /* we only want refs/remotes/$remote->name/HEAD */
2570 if (strncmp(remote_refname + 13, remote->name,
2571 remote_name_len) != 0)
2572 continue;
2574 if (strcmp(remote_refname + remote_name_len + 14,
2575 GOT_REF_HEAD) != 0)
2576 continue;
2579 * Take the name itself because we already
2580 * only match with refs/heads/ in fetch_pack().
2582 remote_target = got_ref_get_symref_target(re->ref);
2583 remote_head = remote_target + remote_name_len + 14;
2584 break;
2587 if (worktree) {
2588 const char *refname;
2590 refname = got_worktree_get_head_ref_name(worktree);
2591 if (strncmp(refname, "refs/heads/", 11) == 0)
2592 worktree_branch = refname;
2596 fpa.last_scaled_size[0] = '\0';
2597 fpa.last_p_indexed = -1;
2598 fpa.last_p_resolved = -1;
2599 fpa.verbosity = verbosity;
2600 fpa.repo = repo;
2601 fpa.create_configs = 0;
2602 fpa.configs_created = 0;
2603 memset(&fpa.config_info, 0, sizeof(fpa.config_info));
2605 error = got_fetch_pack(&pack_hash, &refs, &symrefs, remote->name,
2606 remote->mirror_references, fetch_all_branches, &wanted_branches,
2607 &wanted_refs, list_refs_only, verbosity, fetchfd, repo,
2608 worktree_branch, remote_head, have_bflag, fetch_progress, &fpa);
2609 if (error)
2610 goto done;
2612 if (list_refs_only) {
2613 error = list_remote_refs(&symrefs, &refs);
2614 goto done;
2617 if (pack_hash == NULL) {
2618 if (verbosity >= 0)
2619 printf("Already up-to-date\n");
2620 } else if (verbosity >= 0) {
2621 error = got_object_id_str(&id_str, pack_hash);
2622 if (error)
2623 goto done;
2624 printf("\nFetched %s.pack\n", id_str);
2625 free(id_str);
2626 id_str = NULL;
2629 /* Update references provided with the pack file. */
2630 TAILQ_FOREACH(pe, &refs, entry) {
2631 const char *refname = pe->path;
2632 struct got_object_id *id = pe->data;
2633 struct got_reference *ref;
2634 char *remote_refname;
2636 if (is_wanted_ref(&wanted_refs, refname) &&
2637 !remote->mirror_references) {
2638 error = update_wanted_ref(refname, id,
2639 remote->name, verbosity, repo);
2640 if (error)
2641 goto done;
2642 continue;
2645 if (remote->mirror_references ||
2646 strncmp("refs/tags/", refname, 10) == 0) {
2647 error = got_ref_open(&ref, repo, refname, 1);
2648 if (error) {
2649 if (error->code != GOT_ERR_NOT_REF)
2650 goto done;
2651 error = create_ref(refname, id, verbosity,
2652 repo);
2653 if (error)
2654 goto done;
2655 } else {
2656 error = update_ref(ref, id, replace_tags,
2657 verbosity, repo);
2658 unlock_err = got_ref_unlock(ref);
2659 if (unlock_err && error == NULL)
2660 error = unlock_err;
2661 got_ref_close(ref);
2662 if (error)
2663 goto done;
2665 } else if (strncmp("refs/heads/", refname, 11) == 0) {
2666 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
2667 remote_name, refname + 11) == -1) {
2668 error = got_error_from_errno("asprintf");
2669 goto done;
2672 error = got_ref_open(&ref, repo, remote_refname, 1);
2673 if (error) {
2674 if (error->code != GOT_ERR_NOT_REF)
2675 goto done;
2676 error = create_ref(remote_refname, id,
2677 verbosity, repo);
2678 if (error)
2679 goto done;
2680 } else {
2681 error = update_ref(ref, id, replace_tags,
2682 verbosity, repo);
2683 unlock_err = got_ref_unlock(ref);
2684 if (unlock_err && error == NULL)
2685 error = unlock_err;
2686 got_ref_close(ref);
2687 if (error)
2688 goto done;
2691 /* Also create a local branch if none exists yet. */
2692 error = got_ref_open(&ref, repo, refname, 1);
2693 if (error) {
2694 if (error->code != GOT_ERR_NOT_REF)
2695 goto done;
2696 error = create_ref(refname, id, verbosity,
2697 repo);
2698 if (error)
2699 goto done;
2700 } else {
2701 unlock_err = got_ref_unlock(ref);
2702 if (unlock_err && error == NULL)
2703 error = unlock_err;
2704 got_ref_close(ref);
2708 if (delete_refs) {
2709 error = delete_missing_refs(&refs, &symrefs, remote,
2710 verbosity, repo);
2711 if (error)
2712 goto done;
2715 if (!remote->mirror_references) {
2716 /* Update remote HEAD reference if the server provided one. */
2717 TAILQ_FOREACH(pe, &symrefs, entry) {
2718 struct got_reference *target_ref;
2719 const char *refname = pe->path;
2720 const char *target = pe->data;
2721 char *remote_refname = NULL, *remote_target = NULL;
2723 if (strcmp(refname, GOT_REF_HEAD) != 0)
2724 continue;
2726 if (strncmp("refs/heads/", target, 11) != 0)
2727 continue;
2729 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
2730 remote->name, refname) == -1) {
2731 error = got_error_from_errno("asprintf");
2732 goto done;
2734 if (asprintf(&remote_target, "refs/remotes/%s/%s",
2735 remote->name, target + 11) == -1) {
2736 error = got_error_from_errno("asprintf");
2737 free(remote_refname);
2738 goto done;
2741 error = got_ref_open(&target_ref, repo, remote_target,
2742 0);
2743 if (error) {
2744 free(remote_refname);
2745 free(remote_target);
2746 if (error->code == GOT_ERR_NOT_REF) {
2747 error = NULL;
2748 continue;
2750 goto done;
2752 error = update_symref(remote_refname, target_ref,
2753 verbosity, repo);
2754 free(remote_refname);
2755 free(remote_target);
2756 got_ref_close(target_ref);
2757 if (error)
2758 goto done;
2761 done:
2762 if (fetchpid > 0) {
2763 if (kill(fetchpid, SIGTERM) == -1)
2764 error = got_error_from_errno("kill");
2765 if (waitpid(fetchpid, &fetchstatus, 0) == -1 && error == NULL)
2766 error = got_error_from_errno("waitpid");
2768 if (fetchfd != -1 && close(fetchfd) == -1 && error == NULL)
2769 error = got_error_from_errno("close");
2770 if (repo) {
2771 const struct got_error *close_err = got_repo_close(repo);
2772 if (error == NULL)
2773 error = close_err;
2775 if (worktree)
2776 got_worktree_close(worktree);
2777 if (pack_fds) {
2778 const struct got_error *pack_err =
2779 got_repo_pack_fds_close(pack_fds);
2780 if (error == NULL)
2781 error = pack_err;
2783 got_pathlist_free(&refs, GOT_PATHLIST_FREE_ALL);
2784 got_pathlist_free(&symrefs, GOT_PATHLIST_FREE_ALL);
2785 got_pathlist_free(&wanted_branches, GOT_PATHLIST_FREE_NONE);
2786 got_pathlist_free(&wanted_refs, GOT_PATHLIST_FREE_NONE);
2787 got_ref_list_free(&remote_refs);
2788 free(id_str);
2789 free(cwd);
2790 free(repo_path);
2791 free(pack_hash);
2792 free(proto);
2793 free(host);
2794 free(port);
2795 free(server_path);
2796 free(repo_name);
2797 return error;
2801 __dead static void
2802 usage_checkout(void)
2804 fprintf(stderr, "usage: %s checkout [-Eq] [-b branch] [-c commit] "
2805 "[-p path-prefix] repository-path [work-tree-path]\n",
2806 getprogname());
2807 exit(1);
2810 static void
2811 show_worktree_base_ref_warning(void)
2813 fprintf(stderr, "%s: warning: could not create a reference "
2814 "to the work tree's base commit; the commit could be "
2815 "garbage-collected by Git or 'gotadmin cleanup'; making the "
2816 "repository writable and running 'got update' will prevent this\n",
2817 getprogname());
2820 struct got_checkout_progress_arg {
2821 const char *worktree_path;
2822 int had_base_commit_ref_error;
2823 int verbosity;
2826 static const struct got_error *
2827 checkout_progress(void *arg, unsigned char status, const char *path)
2829 struct got_checkout_progress_arg *a = arg;
2831 /* Base commit bump happens silently. */
2832 if (status == GOT_STATUS_BUMP_BASE)
2833 return NULL;
2835 if (status == GOT_STATUS_BASE_REF_ERR) {
2836 a->had_base_commit_ref_error = 1;
2837 return NULL;
2840 while (path[0] == '/')
2841 path++;
2843 if (a->verbosity >= 0)
2844 printf("%c %s/%s\n", status, a->worktree_path, path);
2846 return NULL;
2849 static const struct got_error *
2850 check_cancelled(void *arg)
2852 if (sigint_received || sigpipe_received)
2853 return got_error(GOT_ERR_CANCELLED);
2854 return NULL;
2857 static const struct got_error *
2858 check_linear_ancestry(struct got_object_id *commit_id,
2859 struct got_object_id *base_commit_id, int allow_forwards_in_time_only,
2860 struct got_repository *repo)
2862 const struct got_error *err = NULL;
2863 struct got_object_id *yca_id;
2865 err = got_commit_graph_find_youngest_common_ancestor(&yca_id,
2866 commit_id, base_commit_id, 1, repo, check_cancelled, NULL);
2867 if (err)
2868 return err;
2870 if (yca_id == NULL)
2871 return got_error(GOT_ERR_ANCESTRY);
2874 * Require a straight line of history between the target commit
2875 * and the work tree's base commit.
2877 * Non-linear situations such as this require a rebase:
2879 * (commit) D F (base_commit)
2880 * \ /
2881 * C E
2882 * \ /
2883 * B (yca)
2884 * |
2885 * A
2887 * 'got update' only handles linear cases:
2888 * Update forwards in time: A (base/yca) - B - C - D (commit)
2889 * Update backwards in time: D (base) - C - B - A (commit/yca)
2891 if (allow_forwards_in_time_only) {
2892 if (got_object_id_cmp(base_commit_id, yca_id) != 0)
2893 return got_error(GOT_ERR_ANCESTRY);
2894 } else if (got_object_id_cmp(commit_id, yca_id) != 0 &&
2895 got_object_id_cmp(base_commit_id, yca_id) != 0)
2896 return got_error(GOT_ERR_ANCESTRY);
2898 free(yca_id);
2899 return NULL;
2902 static const struct got_error *
2903 check_same_branch(struct got_object_id *commit_id,
2904 struct got_reference *head_ref, struct got_repository *repo)
2906 const struct got_error *err = NULL;
2907 struct got_commit_graph *graph = NULL;
2908 struct got_object_id *head_commit_id = NULL;
2910 err = got_ref_resolve(&head_commit_id, repo, head_ref);
2911 if (err)
2912 goto done;
2914 if (got_object_id_cmp(head_commit_id, commit_id) == 0)
2915 goto done;
2917 err = got_commit_graph_open(&graph, "/", 1);
2918 if (err)
2919 goto done;
2921 err = got_commit_graph_iter_start(graph, head_commit_id, repo,
2922 check_cancelled, NULL);
2923 if (err)
2924 goto done;
2926 for (;;) {
2927 struct got_object_id id;
2929 err = got_commit_graph_iter_next(&id, graph, repo,
2930 check_cancelled, NULL);
2931 if (err) {
2932 if (err->code == GOT_ERR_ITER_COMPLETED)
2933 err = got_error(GOT_ERR_ANCESTRY);
2934 break;
2937 if (got_object_id_cmp(&id, commit_id) == 0)
2938 break;
2940 done:
2941 if (graph)
2942 got_commit_graph_close(graph);
2943 free(head_commit_id);
2944 return err;
2947 static const struct got_error *
2948 checkout_ancestry_error(struct got_reference *ref, const char *commit_id_str)
2950 static char msg[512];
2951 const char *branch_name;
2953 if (got_ref_is_symbolic(ref))
2954 branch_name = got_ref_get_symref_target(ref);
2955 else
2956 branch_name = got_ref_get_name(ref);
2958 if (strncmp("refs/heads/", branch_name, 11) == 0)
2959 branch_name += 11;
2961 snprintf(msg, sizeof(msg),
2962 "target commit is not contained in branch '%s'; "
2963 "the branch to use must be specified with -b; "
2964 "if necessary a new branch can be created for "
2965 "this commit with 'got branch -c %s BRANCH_NAME'",
2966 branch_name, commit_id_str);
2968 return got_error_msg(GOT_ERR_ANCESTRY, msg);
2971 static const struct got_error *
2972 cmd_checkout(int argc, char *argv[])
2974 const struct got_error *error = NULL;
2975 struct got_repository *repo = NULL;
2976 struct got_reference *head_ref = NULL, *ref = NULL;
2977 struct got_worktree *worktree = NULL;
2978 char *repo_path = NULL;
2979 char *worktree_path = NULL;
2980 const char *path_prefix = "";
2981 const char *branch_name = GOT_REF_HEAD, *refname = NULL;
2982 char *commit_id_str = NULL;
2983 struct got_object_id *commit_id = NULL;
2984 char *cwd = NULL;
2985 int ch, same_path_prefix, allow_nonempty = 0, verbosity = 0;
2986 struct got_pathlist_head paths;
2987 struct got_checkout_progress_arg cpa;
2988 int *pack_fds = NULL;
2990 TAILQ_INIT(&paths);
2992 #ifndef PROFILE
2993 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
2994 "unveil", NULL) == -1)
2995 err(1, "pledge");
2996 #endif
2998 while ((ch = getopt(argc, argv, "b:c:Ep:q")) != -1) {
2999 switch (ch) {
3000 case 'b':
3001 branch_name = optarg;
3002 break;
3003 case 'c':
3004 commit_id_str = strdup(optarg);
3005 if (commit_id_str == NULL)
3006 return got_error_from_errno("strdup");
3007 break;
3008 case 'E':
3009 allow_nonempty = 1;
3010 break;
3011 case 'p':
3012 path_prefix = optarg;
3013 break;
3014 case 'q':
3015 verbosity = -1;
3016 break;
3017 default:
3018 usage_checkout();
3019 /* NOTREACHED */
3023 argc -= optind;
3024 argv += optind;
3026 if (argc == 1) {
3027 char *base, *dotgit;
3028 const char *path;
3029 repo_path = realpath(argv[0], NULL);
3030 if (repo_path == NULL)
3031 return got_error_from_errno2("realpath", argv[0]);
3032 cwd = getcwd(NULL, 0);
3033 if (cwd == NULL) {
3034 error = got_error_from_errno("getcwd");
3035 goto done;
3037 if (path_prefix[0])
3038 path = path_prefix;
3039 else
3040 path = repo_path;
3041 error = got_path_basename(&base, path);
3042 if (error)
3043 goto done;
3044 dotgit = strstr(base, ".git");
3045 if (dotgit)
3046 *dotgit = '\0';
3047 if (asprintf(&worktree_path, "%s/%s", cwd, base) == -1) {
3048 error = got_error_from_errno("asprintf");
3049 free(base);
3050 goto done;
3052 free(base);
3053 } else if (argc == 2) {
3054 repo_path = realpath(argv[0], NULL);
3055 if (repo_path == NULL) {
3056 error = got_error_from_errno2("realpath", argv[0]);
3057 goto done;
3059 worktree_path = realpath(argv[1], NULL);
3060 if (worktree_path == NULL) {
3061 if (errno != ENOENT) {
3062 error = got_error_from_errno2("realpath",
3063 argv[1]);
3064 goto done;
3066 worktree_path = strdup(argv[1]);
3067 if (worktree_path == NULL) {
3068 error = got_error_from_errno("strdup");
3069 goto done;
3072 } else
3073 usage_checkout();
3075 got_path_strip_trailing_slashes(repo_path);
3076 got_path_strip_trailing_slashes(worktree_path);
3078 error = got_repo_pack_fds_open(&pack_fds);
3079 if (error != NULL)
3080 goto done;
3082 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
3083 if (error != NULL)
3084 goto done;
3086 /* Pre-create work tree path for unveil(2) */
3087 error = got_path_mkdir(worktree_path);
3088 if (error) {
3089 if (!(error->code == GOT_ERR_ERRNO && errno == EISDIR) &&
3090 !(error->code == GOT_ERR_ERRNO && errno == EEXIST))
3091 goto done;
3092 if (!allow_nonempty &&
3093 !got_path_dir_is_empty(worktree_path)) {
3094 error = got_error_path(worktree_path,
3095 GOT_ERR_DIR_NOT_EMPTY);
3096 goto done;
3100 error = apply_unveil(got_repo_get_path(repo), 0, worktree_path);
3101 if (error)
3102 goto done;
3104 error = got_ref_open(&head_ref, repo, branch_name, 0);
3105 if (error != NULL)
3106 goto done;
3108 error = got_worktree_init(worktree_path, head_ref, path_prefix, repo);
3109 if (error != NULL && !(error->code == GOT_ERR_ERRNO && errno == EEXIST))
3110 goto done;
3112 error = got_worktree_open(&worktree, worktree_path);
3113 if (error != NULL)
3114 goto done;
3116 error = got_worktree_match_path_prefix(&same_path_prefix, worktree,
3117 path_prefix);
3118 if (error != NULL)
3119 goto done;
3120 if (!same_path_prefix) {
3121 error = got_error(GOT_ERR_PATH_PREFIX);
3122 goto done;
3125 if (commit_id_str) {
3126 struct got_reflist_head refs;
3127 TAILQ_INIT(&refs);
3128 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
3129 NULL);
3130 if (error)
3131 goto done;
3132 error = got_repo_match_object_id(&commit_id, NULL,
3133 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
3134 got_ref_list_free(&refs);
3135 if (error)
3136 goto done;
3137 error = check_linear_ancestry(commit_id,
3138 got_worktree_get_base_commit_id(worktree), 0, repo);
3139 if (error != NULL) {
3140 if (error->code == GOT_ERR_ANCESTRY) {
3141 error = checkout_ancestry_error(
3142 head_ref, commit_id_str);
3144 goto done;
3146 error = check_same_branch(commit_id, head_ref, repo);
3147 if (error) {
3148 if (error->code == GOT_ERR_ANCESTRY) {
3149 error = checkout_ancestry_error(
3150 head_ref, commit_id_str);
3152 goto done;
3154 error = got_worktree_set_base_commit_id(worktree, repo,
3155 commit_id);
3156 if (error)
3157 goto done;
3158 /* Expand potentially abbreviated commit ID string. */
3159 free(commit_id_str);
3160 error = got_object_id_str(&commit_id_str, commit_id);
3161 if (error)
3162 goto done;
3163 } else {
3164 commit_id = got_object_id_dup(
3165 got_worktree_get_base_commit_id(worktree));
3166 if (commit_id == NULL) {
3167 error = got_error_from_errno("got_object_id_dup");
3168 goto done;
3170 error = got_object_id_str(&commit_id_str, commit_id);
3171 if (error)
3172 goto done;
3175 error = got_pathlist_append(&paths, "", NULL);
3176 if (error)
3177 goto done;
3178 cpa.worktree_path = worktree_path;
3179 cpa.had_base_commit_ref_error = 0;
3180 cpa.verbosity = verbosity;
3181 error = got_worktree_checkout_files(worktree, &paths, repo,
3182 checkout_progress, &cpa, check_cancelled, NULL);
3183 if (error != NULL)
3184 goto done;
3186 if (got_ref_is_symbolic(head_ref)) {
3187 error = got_ref_resolve_symbolic(&ref, repo, head_ref);
3188 if (error)
3189 goto done;
3190 refname = got_ref_get_name(ref);
3191 } else
3192 refname = got_ref_get_name(head_ref);
3193 printf("Checked out %s: %s\n", refname, commit_id_str);
3194 printf("Now shut up and hack\n");
3195 if (cpa.had_base_commit_ref_error)
3196 show_worktree_base_ref_warning();
3197 done:
3198 if (pack_fds) {
3199 const struct got_error *pack_err =
3200 got_repo_pack_fds_close(pack_fds);
3201 if (error == NULL)
3202 error = pack_err;
3204 if (head_ref)
3205 got_ref_close(head_ref);
3206 if (ref)
3207 got_ref_close(ref);
3208 if (repo) {
3209 const struct got_error *close_err = got_repo_close(repo);
3210 if (error == NULL)
3211 error = close_err;
3213 got_pathlist_free(&paths, GOT_PATHLIST_FREE_NONE);
3214 free(commit_id_str);
3215 free(commit_id);
3216 free(repo_path);
3217 free(worktree_path);
3218 free(cwd);
3219 return error;
3222 struct got_update_progress_arg {
3223 int did_something;
3224 int conflicts;
3225 int obstructed;
3226 int not_updated;
3227 int missing;
3228 int not_deleted;
3229 int unversioned;
3230 int verbosity;
3233 static void
3234 print_update_progress_stats(struct got_update_progress_arg *upa)
3236 if (!upa->did_something)
3237 return;
3239 if (upa->conflicts > 0)
3240 printf("Files with new merge conflicts: %d\n", upa->conflicts);
3241 if (upa->obstructed > 0)
3242 printf("File paths obstructed by a non-regular file: %d\n",
3243 upa->obstructed);
3244 if (upa->not_updated > 0)
3245 printf("Files not updated because of existing merge "
3246 "conflicts: %d\n", upa->not_updated);
3250 * The meaning of some status codes differs between merge-style operations and
3251 * update operations. For example, the ! status code means "file was missing"
3252 * if changes were merged into the work tree, and "missing file was restored"
3253 * if the work tree was updated. This function should be used by any operation
3254 * which merges changes into the work tree without updating the work tree.
3256 static void
3257 print_merge_progress_stats(struct got_update_progress_arg *upa)
3259 if (!upa->did_something)
3260 return;
3262 if (upa->conflicts > 0)
3263 printf("Files with new merge conflicts: %d\n", upa->conflicts);
3264 if (upa->obstructed > 0)
3265 printf("File paths obstructed by a non-regular file: %d\n",
3266 upa->obstructed);
3267 if (upa->missing > 0)
3268 printf("Files which had incoming changes but could not be "
3269 "found in the work tree: %d\n", upa->missing);
3270 if (upa->not_deleted > 0)
3271 printf("Files not deleted due to differences in deleted "
3272 "content: %d\n", upa->not_deleted);
3273 if (upa->unversioned > 0)
3274 printf("Files not merged because an unversioned file was "
3275 "found in the work tree: %d\n", upa->unversioned);
3278 __dead static void
3279 usage_update(void)
3281 fprintf(stderr, "usage: %s update [-q] [-b branch] [-c commit] "
3282 "[path ...]\n", getprogname());
3283 exit(1);
3286 static const struct got_error *
3287 update_progress(void *arg, unsigned char status, const char *path)
3289 struct got_update_progress_arg *upa = arg;
3291 if (status == GOT_STATUS_EXISTS ||
3292 status == GOT_STATUS_BASE_REF_ERR)
3293 return NULL;
3295 upa->did_something = 1;
3297 /* Base commit bump happens silently. */
3298 if (status == GOT_STATUS_BUMP_BASE)
3299 return NULL;
3301 if (status == GOT_STATUS_CONFLICT)
3302 upa->conflicts++;
3303 if (status == GOT_STATUS_OBSTRUCTED)
3304 upa->obstructed++;
3305 if (status == GOT_STATUS_CANNOT_UPDATE)
3306 upa->not_updated++;
3307 if (status == GOT_STATUS_MISSING)
3308 upa->missing++;
3309 if (status == GOT_STATUS_CANNOT_DELETE)
3310 upa->not_deleted++;
3311 if (status == GOT_STATUS_UNVERSIONED)
3312 upa->unversioned++;
3314 while (path[0] == '/')
3315 path++;
3316 if (upa->verbosity >= 0)
3317 printf("%c %s\n", status, path);
3319 return NULL;
3322 static const struct got_error *
3323 switch_head_ref(struct got_reference *head_ref,
3324 struct got_object_id *commit_id, struct got_worktree *worktree,
3325 struct got_repository *repo)
3327 const struct got_error *err = NULL;
3328 char *base_id_str;
3329 int ref_has_moved = 0;
3331 /* Trivial case: switching between two different references. */
3332 if (strcmp(got_ref_get_name(head_ref),
3333 got_worktree_get_head_ref_name(worktree)) != 0) {
3334 printf("Switching work tree from %s to %s\n",
3335 got_worktree_get_head_ref_name(worktree),
3336 got_ref_get_name(head_ref));
3337 return got_worktree_set_head_ref(worktree, head_ref);
3340 err = check_linear_ancestry(commit_id,
3341 got_worktree_get_base_commit_id(worktree), 0, repo);
3342 if (err) {
3343 if (err->code != GOT_ERR_ANCESTRY)
3344 return err;
3345 ref_has_moved = 1;
3347 if (!ref_has_moved)
3348 return NULL;
3350 /* Switching to a rebased branch with the same reference name. */
3351 err = got_object_id_str(&base_id_str,
3352 got_worktree_get_base_commit_id(worktree));
3353 if (err)
3354 return err;
3355 printf("Reference %s now points at a different branch\n",
3356 got_worktree_get_head_ref_name(worktree));
3357 printf("Switching work tree from %s to %s\n", base_id_str,
3358 got_worktree_get_head_ref_name(worktree));
3359 return NULL;
3362 static const struct got_error *
3363 check_rebase_or_histedit_in_progress(struct got_worktree *worktree)
3365 const struct got_error *err;
3366 int in_progress;
3368 err = got_worktree_rebase_in_progress(&in_progress, worktree);
3369 if (err)
3370 return err;
3371 if (in_progress)
3372 return got_error(GOT_ERR_REBASING);
3374 err = got_worktree_histedit_in_progress(&in_progress, worktree);
3375 if (err)
3376 return err;
3377 if (in_progress)
3378 return got_error(GOT_ERR_HISTEDIT_BUSY);
3380 return NULL;
3383 static const struct got_error *
3384 check_merge_in_progress(struct got_worktree *worktree,
3385 struct got_repository *repo)
3387 const struct got_error *err;
3388 int in_progress;
3390 err = got_worktree_merge_in_progress(&in_progress, worktree, repo);
3391 if (err)
3392 return err;
3393 if (in_progress)
3394 return got_error(GOT_ERR_MERGE_BUSY);
3396 return NULL;
3399 static const struct got_error *
3400 get_worktree_paths_from_argv(struct got_pathlist_head *paths, int argc,
3401 char *argv[], struct got_worktree *worktree)
3403 const struct got_error *err = NULL;
3404 char *path;
3405 struct got_pathlist_entry *new;
3406 int i;
3408 if (argc == 0) {
3409 path = strdup("");
3410 if (path == NULL)
3411 return got_error_from_errno("strdup");
3412 return got_pathlist_append(paths, path, NULL);
3415 for (i = 0; i < argc; i++) {
3416 err = got_worktree_resolve_path(&path, worktree, argv[i]);
3417 if (err)
3418 break;
3419 err = got_pathlist_insert(&new, paths, path, NULL);
3420 if (err || new == NULL /* duplicate */) {
3421 free(path);
3422 if (err)
3423 break;
3427 return err;
3430 static const struct got_error *
3431 wrap_not_worktree_error(const struct got_error *orig_err,
3432 const char *cmdname, const char *path)
3434 const struct got_error *err;
3435 struct got_repository *repo;
3436 static char msg[512];
3437 int *pack_fds = NULL;
3439 err = got_repo_pack_fds_open(&pack_fds);
3440 if (err)
3441 return err;
3443 err = got_repo_open(&repo, path, NULL, pack_fds);
3444 if (err)
3445 return orig_err;
3447 snprintf(msg, sizeof(msg),
3448 "'got %s' needs a work tree in addition to a git repository\n"
3449 "Work trees can be checked out from this Git repository with "
3450 "'got checkout'.\n"
3451 "The got(1) manual page contains more information.", cmdname);
3452 err = got_error_msg(GOT_ERR_NOT_WORKTREE, msg);
3453 if (repo) {
3454 const struct got_error *close_err = got_repo_close(repo);
3455 if (err == NULL)
3456 err = close_err;
3458 if (pack_fds) {
3459 const struct got_error *pack_err =
3460 got_repo_pack_fds_close(pack_fds);
3461 if (err == NULL)
3462 err = pack_err;
3464 return err;
3467 static const struct got_error *
3468 cmd_update(int argc, char *argv[])
3470 const struct got_error *error = NULL;
3471 struct got_repository *repo = NULL;
3472 struct got_worktree *worktree = NULL;
3473 char *worktree_path = NULL;
3474 struct got_object_id *commit_id = NULL;
3475 char *commit_id_str = NULL;
3476 const char *branch_name = NULL;
3477 struct got_reference *head_ref = NULL;
3478 struct got_pathlist_head paths;
3479 struct got_pathlist_entry *pe;
3480 int ch, verbosity = 0;
3481 struct got_update_progress_arg upa;
3482 int *pack_fds = NULL;
3484 TAILQ_INIT(&paths);
3486 #ifndef PROFILE
3487 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
3488 "unveil", NULL) == -1)
3489 err(1, "pledge");
3490 #endif
3492 while ((ch = getopt(argc, argv, "b:c:q")) != -1) {
3493 switch (ch) {
3494 case 'b':
3495 branch_name = optarg;
3496 break;
3497 case 'c':
3498 commit_id_str = strdup(optarg);
3499 if (commit_id_str == NULL)
3500 return got_error_from_errno("strdup");
3501 break;
3502 case 'q':
3503 verbosity = -1;
3504 break;
3505 default:
3506 usage_update();
3507 /* NOTREACHED */
3511 argc -= optind;
3512 argv += optind;
3514 worktree_path = getcwd(NULL, 0);
3515 if (worktree_path == NULL) {
3516 error = got_error_from_errno("getcwd");
3517 goto done;
3520 error = got_repo_pack_fds_open(&pack_fds);
3521 if (error != NULL)
3522 goto done;
3524 error = got_worktree_open(&worktree, worktree_path);
3525 if (error) {
3526 if (error->code == GOT_ERR_NOT_WORKTREE)
3527 error = wrap_not_worktree_error(error, "update",
3528 worktree_path);
3529 goto done;
3532 error = check_rebase_or_histedit_in_progress(worktree);
3533 if (error)
3534 goto done;
3536 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
3537 NULL, pack_fds);
3538 if (error != NULL)
3539 goto done;
3541 error = apply_unveil(got_repo_get_path(repo), 0,
3542 got_worktree_get_root_path(worktree));
3543 if (error)
3544 goto done;
3546 error = check_merge_in_progress(worktree, repo);
3547 if (error)
3548 goto done;
3550 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
3551 if (error)
3552 goto done;
3554 error = got_ref_open(&head_ref, repo, branch_name ? branch_name :
3555 got_worktree_get_head_ref_name(worktree), 0);
3556 if (error != NULL)
3557 goto done;
3558 if (commit_id_str == NULL) {
3559 error = got_ref_resolve(&commit_id, repo, head_ref);
3560 if (error != NULL)
3561 goto done;
3562 error = got_object_id_str(&commit_id_str, commit_id);
3563 if (error != NULL)
3564 goto done;
3565 } else {
3566 struct got_reflist_head refs;
3567 TAILQ_INIT(&refs);
3568 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
3569 NULL);
3570 if (error)
3571 goto done;
3572 error = got_repo_match_object_id(&commit_id, NULL,
3573 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
3574 got_ref_list_free(&refs);
3575 free(commit_id_str);
3576 commit_id_str = NULL;
3577 if (error)
3578 goto done;
3579 error = got_object_id_str(&commit_id_str, commit_id);
3580 if (error)
3581 goto done;
3584 if (branch_name) {
3585 struct got_object_id *head_commit_id;
3586 TAILQ_FOREACH(pe, &paths, entry) {
3587 if (pe->path_len == 0)
3588 continue;
3589 error = got_error_msg(GOT_ERR_BAD_PATH,
3590 "switching between branches requires that "
3591 "the entire work tree gets updated");
3592 goto done;
3594 error = got_ref_resolve(&head_commit_id, repo, head_ref);
3595 if (error)
3596 goto done;
3597 error = check_linear_ancestry(commit_id, head_commit_id, 0,
3598 repo);
3599 free(head_commit_id);
3600 if (error != NULL)
3601 goto done;
3602 error = check_same_branch(commit_id, head_ref, repo);
3603 if (error)
3604 goto done;
3605 error = switch_head_ref(head_ref, commit_id, worktree, repo);
3606 if (error)
3607 goto done;
3608 } else {
3609 error = check_linear_ancestry(commit_id,
3610 got_worktree_get_base_commit_id(worktree), 0, repo);
3611 if (error != NULL) {
3612 if (error->code == GOT_ERR_ANCESTRY)
3613 error = got_error(GOT_ERR_BRANCH_MOVED);
3614 goto done;
3616 error = check_same_branch(commit_id, head_ref, repo);
3617 if (error)
3618 goto done;
3621 if (got_object_id_cmp(got_worktree_get_base_commit_id(worktree),
3622 commit_id) != 0) {
3623 error = got_worktree_set_base_commit_id(worktree, repo,
3624 commit_id);
3625 if (error)
3626 goto done;
3629 memset(&upa, 0, sizeof(upa));
3630 upa.verbosity = verbosity;
3631 error = got_worktree_checkout_files(worktree, &paths, repo,
3632 update_progress, &upa, check_cancelled, NULL);
3633 if (error != NULL)
3634 goto done;
3636 if (upa.did_something) {
3637 printf("Updated to %s: %s\n",
3638 got_worktree_get_head_ref_name(worktree), commit_id_str);
3639 } else
3640 printf("Already up-to-date\n");
3642 print_update_progress_stats(&upa);
3643 done:
3644 if (pack_fds) {
3645 const struct got_error *pack_err =
3646 got_repo_pack_fds_close(pack_fds);
3647 if (error == NULL)
3648 error = pack_err;
3650 if (repo) {
3651 const struct got_error *close_err = got_repo_close(repo);
3652 if (error == NULL)
3653 error = close_err;
3655 free(worktree_path);
3656 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
3657 free(commit_id);
3658 free(commit_id_str);
3659 return error;
3662 static const struct got_error *
3663 diff_blobs(struct got_object_id *blob_id1, struct got_object_id *blob_id2,
3664 const char *path, int diff_context, int ignore_whitespace,
3665 int force_text_diff, struct got_diffstat_cb_arg *dsa,
3666 struct got_repository *repo, FILE *outfile)
3668 const struct got_error *err = NULL;
3669 struct got_blob_object *blob1 = NULL, *blob2 = NULL;
3670 FILE *f1 = NULL, *f2 = NULL;
3671 int fd1 = -1, fd2 = -1;
3673 fd1 = got_opentempfd();
3674 if (fd1 == -1)
3675 return got_error_from_errno("got_opentempfd");
3676 fd2 = got_opentempfd();
3677 if (fd2 == -1) {
3678 err = got_error_from_errno("got_opentempfd");
3679 goto done;
3682 if (blob_id1) {
3683 err = got_object_open_as_blob(&blob1, repo, blob_id1, 8192,
3684 fd1);
3685 if (err)
3686 goto done;
3689 err = got_object_open_as_blob(&blob2, repo, blob_id2, 8192, fd2);
3690 if (err)
3691 goto done;
3693 f1 = got_opentemp();
3694 if (f1 == NULL) {
3695 err = got_error_from_errno("got_opentemp");
3696 goto done;
3698 f2 = got_opentemp();
3699 if (f2 == NULL) {
3700 err = got_error_from_errno("got_opentemp");
3701 goto done;
3704 while (path[0] == '/')
3705 path++;
3706 err = got_diff_blob(NULL, NULL, blob1, blob2, f1, f2, path, path,
3707 GOT_DIFF_ALGORITHM_PATIENCE, diff_context, ignore_whitespace,
3708 force_text_diff, dsa, outfile);
3709 done:
3710 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
3711 err = got_error_from_errno("close");
3712 if (blob1)
3713 got_object_blob_close(blob1);
3714 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
3715 err = got_error_from_errno("close");
3716 if (blob2)
3717 got_object_blob_close(blob2);
3718 if (f1 && fclose(f1) == EOF && err == NULL)
3719 err = got_error_from_errno("fclose");
3720 if (f2 && fclose(f2) == EOF && err == NULL)
3721 err = got_error_from_errno("fclose");
3722 return err;
3725 static const struct got_error *
3726 diff_trees(struct got_object_id *tree_id1, struct got_object_id *tree_id2,
3727 const char *path, int diff_context, int ignore_whitespace,
3728 int force_text_diff, struct got_diffstat_cb_arg *dsa,
3729 struct got_repository *repo, FILE *outfile)
3731 const struct got_error *err = NULL;
3732 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
3733 struct got_diff_blob_output_unidiff_arg arg;
3734 FILE *f1 = NULL, *f2 = NULL;
3735 int fd1 = -1, fd2 = -1;
3737 if (tree_id1) {
3738 err = got_object_open_as_tree(&tree1, repo, tree_id1);
3739 if (err)
3740 goto done;
3741 fd1 = got_opentempfd();
3742 if (fd1 == -1) {
3743 err = got_error_from_errno("got_opentempfd");
3744 goto done;
3748 err = got_object_open_as_tree(&tree2, repo, tree_id2);
3749 if (err)
3750 goto done;
3752 f1 = got_opentemp();
3753 if (f1 == NULL) {
3754 err = got_error_from_errno("got_opentemp");
3755 goto done;
3758 f2 = got_opentemp();
3759 if (f2 == NULL) {
3760 err = got_error_from_errno("got_opentemp");
3761 goto done;
3763 fd2 = got_opentempfd();
3764 if (fd2 == -1) {
3765 err = got_error_from_errno("got_opentempfd");
3766 goto done;
3768 arg.diff_context = diff_context;
3769 arg.ignore_whitespace = ignore_whitespace;
3770 arg.force_text_diff = force_text_diff;
3771 arg.diffstat = dsa;
3772 arg.diff_algo = GOT_DIFF_ALGORITHM_PATIENCE;
3773 arg.outfile = outfile;
3774 arg.lines = NULL;
3775 arg.nlines = 0;
3776 while (path[0] == '/')
3777 path++;
3778 err = got_diff_tree(tree1, tree2, f1, f2, fd1, fd2, path, path, repo,
3779 got_diff_blob_output_unidiff, &arg, 1);
3780 done:
3781 if (tree1)
3782 got_object_tree_close(tree1);
3783 if (tree2)
3784 got_object_tree_close(tree2);
3785 if (f1 && fclose(f1) == EOF && err == NULL)
3786 err = got_error_from_errno("fclose");
3787 if (f2 && fclose(f2) == EOF && err == NULL)
3788 err = got_error_from_errno("fclose");
3789 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
3790 err = got_error_from_errno("close");
3791 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
3792 err = got_error_from_errno("close");
3793 return err;
3796 static const struct got_error *
3797 get_changed_paths(struct got_pathlist_head *paths,
3798 struct got_commit_object *commit, struct got_repository *repo,
3799 struct got_diffstat_cb_arg *dsa)
3801 const struct got_error *err = NULL;
3802 struct got_object_id *tree_id1 = NULL, *tree_id2 = NULL;
3803 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
3804 struct got_object_qid *qid;
3805 got_diff_blob_cb cb = got_diff_tree_collect_changed_paths;
3806 FILE *f1 = NULL, *f2 = NULL;
3807 int fd1 = -1, fd2 = -1;
3809 if (dsa) {
3810 cb = got_diff_tree_compute_diffstat;
3812 f1 = got_opentemp();
3813 if (f1 == NULL) {
3814 err = got_error_from_errno("got_opentemp");
3815 goto done;
3817 f2 = got_opentemp();
3818 if (f2 == NULL) {
3819 err = got_error_from_errno("got_opentemp");
3820 goto done;
3822 fd1 = got_opentempfd();
3823 if (fd1 == -1) {
3824 err = got_error_from_errno("got_opentempfd");
3825 goto done;
3827 fd2 = got_opentempfd();
3828 if (fd2 == -1) {
3829 err = got_error_from_errno("got_opentempfd");
3830 goto done;
3834 qid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
3835 if (qid != NULL) {
3836 struct got_commit_object *pcommit;
3837 err = got_object_open_as_commit(&pcommit, repo,
3838 &qid->id);
3839 if (err)
3840 return err;
3842 tree_id1 = got_object_id_dup(
3843 got_object_commit_get_tree_id(pcommit));
3844 if (tree_id1 == NULL) {
3845 got_object_commit_close(pcommit);
3846 return got_error_from_errno("got_object_id_dup");
3848 got_object_commit_close(pcommit);
3852 if (tree_id1) {
3853 err = got_object_open_as_tree(&tree1, repo, tree_id1);
3854 if (err)
3855 goto done;
3858 tree_id2 = got_object_commit_get_tree_id(commit);
3859 err = got_object_open_as_tree(&tree2, repo, tree_id2);
3860 if (err)
3861 goto done;
3863 err = got_diff_tree(tree1, tree2, f1, f2, fd1, fd2, "", "", repo,
3864 cb, dsa ? (void *)dsa : paths, dsa ? 1 : 0);
3865 done:
3866 if (tree1)
3867 got_object_tree_close(tree1);
3868 if (tree2)
3869 got_object_tree_close(tree2);
3870 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
3871 err = got_error_from_errno("close");
3872 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
3873 err = got_error_from_errno("close");
3874 if (f1 && fclose(f1) == EOF && err == NULL)
3875 err = got_error_from_errno("fclose");
3876 if (f2 && fclose(f2) == EOF && err == NULL)
3877 err = got_error_from_errno("fclose");
3878 free(tree_id1);
3879 return err;
3882 static const struct got_error *
3883 print_patch(struct got_commit_object *commit, struct got_object_id *id,
3884 const char *path, int diff_context, struct got_diffstat_cb_arg *dsa,
3885 struct got_repository *repo, FILE *outfile)
3887 const struct got_error *err = NULL;
3888 struct got_commit_object *pcommit = NULL;
3889 char *id_str1 = NULL, *id_str2 = NULL;
3890 struct got_object_id *obj_id1 = NULL, *obj_id2 = NULL;
3891 struct got_object_qid *qid;
3893 qid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
3894 if (qid != NULL) {
3895 err = got_object_open_as_commit(&pcommit, repo,
3896 &qid->id);
3897 if (err)
3898 return err;
3899 err = got_object_id_str(&id_str1, &qid->id);
3900 if (err)
3901 goto done;
3904 err = got_object_id_str(&id_str2, id);
3905 if (err)
3906 goto done;
3908 if (path && path[0] != '\0') {
3909 int obj_type;
3910 err = got_object_id_by_path(&obj_id2, repo, commit, path);
3911 if (err)
3912 goto done;
3913 if (pcommit) {
3914 err = got_object_id_by_path(&obj_id1, repo,
3915 pcommit, path);
3916 if (err) {
3917 if (err->code != GOT_ERR_NO_TREE_ENTRY) {
3918 free(obj_id2);
3919 goto done;
3923 err = got_object_get_type(&obj_type, repo, obj_id2);
3924 if (err) {
3925 free(obj_id2);
3926 goto done;
3928 fprintf(outfile,
3929 "diff %s %s\n", id_str1 ? id_str1 : "/dev/null", id_str2);
3930 fprintf(outfile, "commit - %s\n",
3931 id_str1 ? id_str1 : "/dev/null");
3932 fprintf(outfile, "commit + %s\n", id_str2);
3933 switch (obj_type) {
3934 case GOT_OBJ_TYPE_BLOB:
3935 err = diff_blobs(obj_id1, obj_id2, path, diff_context,
3936 0, 0, dsa, repo, outfile);
3937 break;
3938 case GOT_OBJ_TYPE_TREE:
3939 err = diff_trees(obj_id1, obj_id2, path, diff_context,
3940 0, 0, dsa, repo, outfile);
3941 break;
3942 default:
3943 err = got_error(GOT_ERR_OBJ_TYPE);
3944 break;
3946 free(obj_id1);
3947 free(obj_id2);
3948 } else {
3949 obj_id2 = got_object_commit_get_tree_id(commit);
3950 if (pcommit)
3951 obj_id1 = got_object_commit_get_tree_id(pcommit);
3952 fprintf(outfile,
3953 "diff %s %s\n", id_str1 ? id_str1 : "/dev/null", id_str2);
3954 fprintf(outfile, "commit - %s\n",
3955 id_str1 ? id_str1 : "/dev/null");
3956 fprintf(outfile, "commit + %s\n", id_str2);
3957 err = diff_trees(obj_id1, obj_id2, "", diff_context, 0, 0,
3958 dsa, repo, outfile);
3960 done:
3961 free(id_str1);
3962 free(id_str2);
3963 if (pcommit)
3964 got_object_commit_close(pcommit);
3965 return err;
3968 static char *
3969 get_datestr(time_t *time, char *datebuf)
3971 struct tm mytm, *tm;
3972 char *p, *s;
3974 tm = gmtime_r(time, &mytm);
3975 if (tm == NULL)
3976 return NULL;
3977 s = asctime_r(tm, datebuf);
3978 if (s == NULL)
3979 return NULL;
3980 p = strchr(s, '\n');
3981 if (p)
3982 *p = '\0';
3983 return s;
3986 static const struct got_error *
3987 match_commit(int *have_match, struct got_object_id *id,
3988 struct got_commit_object *commit, regex_t *regex)
3990 const struct got_error *err = NULL;
3991 regmatch_t regmatch;
3992 char *id_str = NULL, *logmsg = NULL;
3994 *have_match = 0;
3996 err = got_object_id_str(&id_str, id);
3997 if (err)
3998 return err;
4000 err = got_object_commit_get_logmsg(&logmsg, commit);
4001 if (err)
4002 goto done;
4004 if (regexec(regex, got_object_commit_get_author(commit), 1,
4005 &regmatch, 0) == 0 ||
4006 regexec(regex, got_object_commit_get_committer(commit), 1,
4007 &regmatch, 0) == 0 ||
4008 regexec(regex, id_str, 1, &regmatch, 0) == 0 ||
4009 regexec(regex, logmsg, 1, &regmatch, 0) == 0)
4010 *have_match = 1;
4011 done:
4012 free(id_str);
4013 free(logmsg);
4014 return err;
4017 static void
4018 match_changed_paths(int *have_match, struct got_pathlist_head *changed_paths,
4019 regex_t *regex)
4021 regmatch_t regmatch;
4022 struct got_pathlist_entry *pe;
4024 *have_match = 0;
4026 TAILQ_FOREACH(pe, changed_paths, entry) {
4027 if (regexec(regex, pe->path, 1, &regmatch, 0) == 0) {
4028 *have_match = 1;
4029 break;
4034 static const struct got_error *
4035 match_patch(int *have_match, struct got_commit_object *commit,
4036 struct got_object_id *id, const char *path, int diff_context,
4037 struct got_repository *repo, regex_t *regex, FILE *f)
4039 const struct got_error *err = NULL;
4040 char *line = NULL;
4041 size_t linesize = 0;
4042 regmatch_t regmatch;
4044 *have_match = 0;
4046 err = got_opentemp_truncate(f);
4047 if (err)
4048 return err;
4050 err = print_patch(commit, id, path, diff_context, NULL, repo, f);
4051 if (err)
4052 goto done;
4054 if (fseeko(f, 0L, SEEK_SET) == -1) {
4055 err = got_error_from_errno("fseeko");
4056 goto done;
4059 while (getline(&line, &linesize, f) != -1) {
4060 if (regexec(regex, line, 1, &regmatch, 0) == 0) {
4061 *have_match = 1;
4062 break;
4065 done:
4066 free(line);
4067 return err;
4070 #define GOT_COMMIT_SEP_STR "-----------------------------------------------\n"
4072 static const struct got_error*
4073 build_refs_str(char **refs_str, struct got_reflist_head *refs,
4074 struct got_object_id *id, struct got_repository *repo,
4075 int local_only)
4077 static const struct got_error *err = NULL;
4078 struct got_reflist_entry *re;
4079 char *s;
4080 const char *name;
4082 *refs_str = NULL;
4084 TAILQ_FOREACH(re, refs, entry) {
4085 struct got_tag_object *tag = NULL;
4086 struct got_object_id *ref_id;
4087 int cmp;
4089 name = got_ref_get_name(re->ref);
4090 if (strcmp(name, GOT_REF_HEAD) == 0)
4091 continue;
4092 if (strncmp(name, "refs/", 5) == 0)
4093 name += 5;
4094 if (strncmp(name, "got/", 4) == 0)
4095 continue;
4096 if (strncmp(name, "heads/", 6) == 0)
4097 name += 6;
4098 if (strncmp(name, "remotes/", 8) == 0) {
4099 if (local_only)
4100 continue;
4101 name += 8;
4102 s = strstr(name, "/" GOT_REF_HEAD);
4103 if (s != NULL && strcmp(s, "/" GOT_REF_HEAD) == 0)
4104 continue;
4106 err = got_ref_resolve(&ref_id, repo, re->ref);
4107 if (err)
4108 break;
4109 if (strncmp(name, "tags/", 5) == 0) {
4110 err = got_object_open_as_tag(&tag, repo, ref_id);
4111 if (err) {
4112 if (err->code != GOT_ERR_OBJ_TYPE) {
4113 free(ref_id);
4114 break;
4116 /* Ref points at something other than a tag. */
4117 err = NULL;
4118 tag = NULL;
4121 cmp = got_object_id_cmp(tag ?
4122 got_object_tag_get_object_id(tag) : ref_id, id);
4123 free(ref_id);
4124 if (tag)
4125 got_object_tag_close(tag);
4126 if (cmp != 0)
4127 continue;
4128 s = *refs_str;
4129 if (asprintf(refs_str, "%s%s%s", s ? s : "",
4130 s ? ", " : "", name) == -1) {
4131 err = got_error_from_errno("asprintf");
4132 free(s);
4133 *refs_str = NULL;
4134 break;
4136 free(s);
4139 return err;
4142 static const struct got_error *
4143 print_commit_oneline(struct got_commit_object *commit, struct got_object_id *id,
4144 struct got_repository *repo, struct got_reflist_object_id_map *refs_idmap)
4146 const struct got_error *err = NULL;
4147 char *ref_str = NULL, *id_str = NULL, *logmsg0 = NULL;
4148 char *comma, *s, *nl;
4149 struct got_reflist_head *refs;
4150 char datebuf[12]; /* YYYY-MM-DD + SPACE + NUL */
4151 struct tm tm;
4152 time_t committer_time;
4154 refs = got_reflist_object_id_map_lookup(refs_idmap, id);
4155 if (refs) {
4156 err = build_refs_str(&ref_str, refs, id, repo, 1);
4157 if (err)
4158 return err;
4160 /* Display the first matching ref only. */
4161 if (ref_str && (comma = strchr(ref_str, ',')) != NULL)
4162 *comma = '\0';
4165 if (ref_str == NULL) {
4166 err = got_object_id_str(&id_str, id);
4167 if (err)
4168 return err;
4171 committer_time = got_object_commit_get_committer_time(commit);
4172 if (gmtime_r(&committer_time, &tm) == NULL) {
4173 err = got_error_from_errno("gmtime_r");
4174 goto done;
4176 if (strftime(datebuf, sizeof(datebuf), "%G-%m-%d ", &tm) == 0) {
4177 err = got_error(GOT_ERR_NO_SPACE);
4178 goto done;
4181 err = got_object_commit_get_logmsg(&logmsg0, commit);
4182 if (err)
4183 goto done;
4185 s = logmsg0;
4186 while (isspace((unsigned char)s[0]))
4187 s++;
4189 nl = strchr(s, '\n');
4190 if (nl) {
4191 *nl = '\0';
4194 if (ref_str)
4195 printf("%s%-7s %s\n", datebuf, ref_str, s);
4196 else
4197 printf("%s%.7s %s\n", datebuf, id_str, s);
4199 if (fflush(stdout) != 0 && err == NULL)
4200 err = got_error_from_errno("fflush");
4201 done:
4202 free(id_str);
4203 free(ref_str);
4204 free(logmsg0);
4205 return err;
4208 static const struct got_error *
4209 print_diffstat(struct got_diffstat_cb_arg *dsa, const char *header)
4211 struct got_pathlist_entry *pe;
4213 if (header != NULL)
4214 printf("%s\n", header);
4216 TAILQ_FOREACH(pe, dsa->paths, entry) {
4217 struct got_diff_changed_path *cp = pe->data;
4218 int pad = dsa->max_path_len - pe->path_len + 1;
4220 printf(" %c %s%*c | %*d+ %*d-\n", cp->status, pe->path, pad,
4221 ' ', dsa->add_cols + 1, cp->add, dsa->rm_cols + 1, cp->rm);
4223 printf("\n%d file%s changed, %d insertion%s(+), %d deletion%s(-)\n\n",
4224 dsa->nfiles, dsa->nfiles > 1 ? "s" : "", dsa->ins,
4225 dsa->ins != 1 ? "s" : "", dsa->del, dsa->del != 1 ? "s" : "");
4227 if (fflush(stdout) != 0)
4228 return got_error_from_errno("fflush");
4230 return NULL;
4233 static const struct got_error *
4234 printfile(FILE *f)
4236 char buf[8192];
4237 size_t r;
4239 if (fseeko(f, 0L, SEEK_SET) == -1)
4240 return got_error_from_errno("fseek");
4242 for (;;) {
4243 r = fread(buf, 1, sizeof(buf), f);
4244 if (r == 0) {
4245 if (ferror(f))
4246 return got_error_from_errno("fread");
4247 if (feof(f))
4248 break;
4250 if (fwrite(buf, 1, r, stdout) != r)
4251 return got_ferror(stdout, GOT_ERR_IO);
4254 return NULL;
4257 static const struct got_error *
4258 print_commit(struct got_commit_object *commit, struct got_object_id *id,
4259 struct got_repository *repo, const char *path,
4260 struct got_pathlist_head *changed_paths,
4261 struct got_diffstat_cb_arg *diffstat, int show_patch, int diff_context,
4262 struct got_reflist_object_id_map *refs_idmap, const char *custom_refs_str,
4263 const char *prefix)
4265 const struct got_error *err = NULL;
4266 FILE *f = NULL;
4267 char *id_str, *datestr, *logmsg0, *logmsg, *line;
4268 char datebuf[26];
4269 time_t committer_time;
4270 const char *author, *committer;
4271 char *refs_str = NULL;
4273 err = got_object_id_str(&id_str, id);
4274 if (err)
4275 return err;
4277 if (custom_refs_str == NULL) {
4278 struct got_reflist_head *refs;
4279 refs = got_reflist_object_id_map_lookup(refs_idmap, id);
4280 if (refs) {
4281 err = build_refs_str(&refs_str, refs, id, repo, 0);
4282 if (err)
4283 goto done;
4287 printf(GOT_COMMIT_SEP_STR);
4288 if (custom_refs_str)
4289 printf("%s %s (%s)\n", prefix ? prefix : "commit", id_str,
4290 custom_refs_str);
4291 else
4292 printf("%s %s%s%s%s\n", prefix ? prefix : "commit", id_str,
4293 refs_str ? " (" : "", refs_str ? refs_str : "",
4294 refs_str ? ")" : "");
4295 free(id_str);
4296 id_str = NULL;
4297 free(refs_str);
4298 refs_str = NULL;
4299 printf("from: %s\n", got_object_commit_get_author(commit));
4300 author = got_object_commit_get_author(commit);
4301 committer = got_object_commit_get_committer(commit);
4302 if (strcmp(author, committer) != 0)
4303 printf("via: %s\n", committer);
4304 committer_time = got_object_commit_get_committer_time(commit);
4305 datestr = get_datestr(&committer_time, datebuf);
4306 if (datestr)
4307 printf("date: %s UTC\n", datestr);
4308 if (got_object_commit_get_nparents(commit) > 1) {
4309 const struct got_object_id_queue *parent_ids;
4310 struct got_object_qid *qid;
4311 int n = 1;
4312 parent_ids = got_object_commit_get_parent_ids(commit);
4313 STAILQ_FOREACH(qid, parent_ids, entry) {
4314 err = got_object_id_str(&id_str, &qid->id);
4315 if (err)
4316 goto done;
4317 printf("parent %d: %s\n", n++, id_str);
4318 free(id_str);
4319 id_str = NULL;
4323 err = got_object_commit_get_logmsg(&logmsg0, commit);
4324 if (err)
4325 goto done;
4327 logmsg = logmsg0;
4328 do {
4329 line = strsep(&logmsg, "\n");
4330 if (line)
4331 printf(" %s\n", line);
4332 } while (line);
4333 free(logmsg0);
4335 if (changed_paths && diffstat == NULL) {
4336 struct got_pathlist_entry *pe;
4338 TAILQ_FOREACH(pe, changed_paths, entry) {
4339 struct got_diff_changed_path *cp = pe->data;
4341 printf(" %c %s\n", cp->status, pe->path);
4343 printf("\n");
4345 if (show_patch) {
4346 if (diffstat) {
4347 f = got_opentemp();
4348 if (f == NULL) {
4349 err = got_error_from_errno("got_opentemp");
4350 goto done;
4354 err = print_patch(commit, id, path, diff_context, diffstat,
4355 repo, diffstat == NULL ? stdout : f);
4356 if (err)
4357 goto done;
4359 if (diffstat) {
4360 err = print_diffstat(diffstat, NULL);
4361 if (err)
4362 goto done;
4363 if (show_patch) {
4364 err = printfile(f);
4365 if (err)
4366 goto done;
4369 if (show_patch)
4370 printf("\n");
4372 if (fflush(stdout) != 0 && err == NULL)
4373 err = got_error_from_errno("fflush");
4374 done:
4375 if (f && fclose(f) == EOF && err == NULL)
4376 err = got_error_from_errno("fclose");
4377 free(id_str);
4378 free(refs_str);
4379 return err;
4382 static const struct got_error *
4383 print_commits(struct got_object_id *root_id, struct got_object_id *end_id,
4384 struct got_repository *repo, const char *path, int show_changed_paths,
4385 int show_diffstat, int show_patch, const char *search_pattern,
4386 int diff_context, int limit, int log_branches, int reverse_display_order,
4387 struct got_reflist_object_id_map *refs_idmap, int one_line,
4388 FILE *tmpfile)
4390 const struct got_error *err;
4391 struct got_commit_graph *graph;
4392 regex_t regex;
4393 int have_match;
4394 struct got_object_id_queue reversed_commits;
4395 struct got_object_qid *qid;
4396 struct got_commit_object *commit;
4397 struct got_pathlist_head changed_paths;
4399 STAILQ_INIT(&reversed_commits);
4400 TAILQ_INIT(&changed_paths);
4402 if (search_pattern && regcomp(&regex, search_pattern,
4403 REG_EXTENDED | REG_NOSUB | REG_NEWLINE))
4404 return got_error_msg(GOT_ERR_REGEX, search_pattern);
4406 err = got_commit_graph_open(&graph, path, !log_branches);
4407 if (err)
4408 return err;
4409 err = got_commit_graph_iter_start(graph, root_id, repo,
4410 check_cancelled, NULL);
4411 if (err)
4412 goto done;
4413 for (;;) {
4414 struct got_object_id id;
4415 struct got_diffstat_cb_arg dsa = { 0, 0, 0, 0, 0, 0,
4416 &changed_paths, 0, 0, GOT_DIFF_ALGORITHM_PATIENCE };
4418 if (sigint_received || sigpipe_received)
4419 break;
4421 err = got_commit_graph_iter_next(&id, graph, repo,
4422 check_cancelled, NULL);
4423 if (err) {
4424 if (err->code == GOT_ERR_ITER_COMPLETED)
4425 err = NULL;
4426 break;
4429 err = got_object_open_as_commit(&commit, repo, &id);
4430 if (err)
4431 break;
4433 if ((show_changed_paths || (show_diffstat && !show_patch))
4434 && !reverse_display_order) {
4435 err = get_changed_paths(&changed_paths, commit, repo,
4436 show_diffstat ? &dsa : NULL);
4437 if (err)
4438 break;
4441 if (search_pattern) {
4442 err = match_commit(&have_match, &id, commit, &regex);
4443 if (err) {
4444 got_object_commit_close(commit);
4445 break;
4447 if (have_match == 0 && show_changed_paths)
4448 match_changed_paths(&have_match,
4449 &changed_paths, &regex);
4450 if (have_match == 0 && show_patch) {
4451 err = match_patch(&have_match, commit, &id,
4452 path, diff_context, repo, &regex, tmpfile);
4453 if (err)
4454 break;
4456 if (have_match == 0) {
4457 got_object_commit_close(commit);
4458 got_pathlist_free(&changed_paths,
4459 GOT_PATHLIST_FREE_ALL);
4460 continue;
4464 if (reverse_display_order) {
4465 err = got_object_qid_alloc(&qid, &id);
4466 if (err)
4467 break;
4468 STAILQ_INSERT_HEAD(&reversed_commits, qid, entry);
4469 got_object_commit_close(commit);
4470 } else {
4471 if (one_line)
4472 err = print_commit_oneline(commit, &id,
4473 repo, refs_idmap);
4474 else
4475 err = print_commit(commit, &id, repo, path,
4476 (show_changed_paths || show_diffstat) ?
4477 &changed_paths : NULL,
4478 show_diffstat ? &dsa : NULL, show_patch,
4479 diff_context, refs_idmap, NULL, NULL);
4480 got_object_commit_close(commit);
4481 if (err)
4482 break;
4484 if ((limit && --limit == 0) ||
4485 (end_id && got_object_id_cmp(&id, end_id) == 0))
4486 break;
4488 got_pathlist_free(&changed_paths, GOT_PATHLIST_FREE_ALL);
4490 if (reverse_display_order) {
4491 STAILQ_FOREACH(qid, &reversed_commits, entry) {
4492 struct got_diffstat_cb_arg dsa = { 0, 0, 0, 0, 0, 0,
4493 &changed_paths, 0, 0, GOT_DIFF_ALGORITHM_PATIENCE };
4495 err = got_object_open_as_commit(&commit, repo,
4496 &qid->id);
4497 if (err)
4498 break;
4499 if (show_changed_paths ||
4500 (show_diffstat && !show_patch)) {
4501 err = get_changed_paths(&changed_paths, commit,
4502 repo, show_diffstat ? &dsa : NULL);
4503 if (err)
4504 break;
4506 if (one_line)
4507 err = print_commit_oneline(commit, &qid->id,
4508 repo, refs_idmap);
4509 else
4510 err = print_commit(commit, &qid->id, repo, path,
4511 (show_changed_paths || show_diffstat) ?
4512 &changed_paths : NULL,
4513 show_diffstat ? &dsa : NULL, show_patch,
4514 diff_context, refs_idmap, NULL, NULL);
4515 got_object_commit_close(commit);
4516 if (err)
4517 break;
4518 got_pathlist_free(&changed_paths, GOT_PATHLIST_FREE_ALL);
4521 done:
4522 while (!STAILQ_EMPTY(&reversed_commits)) {
4523 qid = STAILQ_FIRST(&reversed_commits);
4524 STAILQ_REMOVE_HEAD(&reversed_commits, entry);
4525 got_object_qid_free(qid);
4527 got_pathlist_free(&changed_paths, GOT_PATHLIST_FREE_ALL);
4528 if (search_pattern)
4529 regfree(&regex);
4530 got_commit_graph_close(graph);
4531 return err;
4534 __dead static void
4535 usage_log(void)
4537 fprintf(stderr, "usage: %s log [-bdPpRs] [-C number] [-c commit] "
4538 "[-l N] [-r repository-path] [-S search-pattern] [-x commit] "
4539 "[path]\n", getprogname());
4540 exit(1);
4543 static int
4544 get_default_log_limit(void)
4546 const char *got_default_log_limit;
4547 long long n;
4548 const char *errstr;
4550 got_default_log_limit = getenv("GOT_LOG_DEFAULT_LIMIT");
4551 if (got_default_log_limit == NULL)
4552 return 0;
4553 n = strtonum(got_default_log_limit, 0, INT_MAX, &errstr);
4554 if (errstr != NULL)
4555 return 0;
4556 return n;
4559 static const struct got_error *
4560 cmd_log(int argc, char *argv[])
4562 const struct got_error *error;
4563 struct got_repository *repo = NULL;
4564 struct got_worktree *worktree = NULL;
4565 struct got_object_id *start_id = NULL, *end_id = NULL;
4566 char *repo_path = NULL, *path = NULL, *cwd = NULL, *in_repo_path = NULL;
4567 const char *start_commit = NULL, *end_commit = NULL;
4568 const char *search_pattern = NULL;
4569 int diff_context = -1, ch;
4570 int show_changed_paths = 0, show_patch = 0, limit = 0, log_branches = 0;
4571 int show_diffstat = 0, reverse_display_order = 0, one_line = 0;
4572 const char *errstr;
4573 struct got_reflist_head refs;
4574 struct got_reflist_object_id_map *refs_idmap = NULL;
4575 FILE *tmpfile = NULL;
4576 int *pack_fds = NULL;
4578 TAILQ_INIT(&refs);
4580 #ifndef PROFILE
4581 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
4582 NULL)
4583 == -1)
4584 err(1, "pledge");
4585 #endif
4587 limit = get_default_log_limit();
4589 while ((ch = getopt(argc, argv, "bC:c:dl:PpRr:S:sx:")) != -1) {
4590 switch (ch) {
4591 case 'b':
4592 log_branches = 1;
4593 break;
4594 case 'C':
4595 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
4596 &errstr);
4597 if (errstr != NULL)
4598 errx(1, "number of context lines is %s: %s",
4599 errstr, optarg);
4600 break;
4601 case 'c':
4602 start_commit = optarg;
4603 break;
4604 case 'd':
4605 show_diffstat = 1;
4606 break;
4607 case 'l':
4608 limit = strtonum(optarg, 0, INT_MAX, &errstr);
4609 if (errstr != NULL)
4610 errx(1, "number of commits is %s: %s",
4611 errstr, optarg);
4612 break;
4613 case 'P':
4614 show_changed_paths = 1;
4615 break;
4616 case 'p':
4617 show_patch = 1;
4618 break;
4619 case 'R':
4620 reverse_display_order = 1;
4621 break;
4622 case 'r':
4623 repo_path = realpath(optarg, NULL);
4624 if (repo_path == NULL)
4625 return got_error_from_errno2("realpath",
4626 optarg);
4627 got_path_strip_trailing_slashes(repo_path);
4628 break;
4629 case 'S':
4630 search_pattern = optarg;
4631 break;
4632 case 's':
4633 one_line = 1;
4634 break;
4635 case 'x':
4636 end_commit = optarg;
4637 break;
4638 default:
4639 usage_log();
4640 /* NOTREACHED */
4644 argc -= optind;
4645 argv += optind;
4647 if (diff_context == -1)
4648 diff_context = 3;
4649 else if (!show_patch)
4650 errx(1, "-C requires -p");
4652 if (one_line && (show_patch || show_changed_paths || show_diffstat))
4653 errx(1, "cannot use -s with -d, -p or -P");
4655 cwd = getcwd(NULL, 0);
4656 if (cwd == NULL) {
4657 error = got_error_from_errno("getcwd");
4658 goto done;
4661 error = got_repo_pack_fds_open(&pack_fds);
4662 if (error != NULL)
4663 goto done;
4665 if (repo_path == NULL) {
4666 error = got_worktree_open(&worktree, cwd);
4667 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4668 goto done;
4669 error = NULL;
4672 if (argc == 1) {
4673 if (worktree) {
4674 error = got_worktree_resolve_path(&path, worktree,
4675 argv[0]);
4676 if (error)
4677 goto done;
4678 } else {
4679 path = strdup(argv[0]);
4680 if (path == NULL) {
4681 error = got_error_from_errno("strdup");
4682 goto done;
4685 } else if (argc != 0)
4686 usage_log();
4688 if (repo_path == NULL) {
4689 repo_path = worktree ?
4690 strdup(got_worktree_get_repo_path(worktree)) : strdup(cwd);
4692 if (repo_path == NULL) {
4693 error = got_error_from_errno("strdup");
4694 goto done;
4697 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
4698 if (error != NULL)
4699 goto done;
4701 error = apply_unveil(got_repo_get_path(repo), 1,
4702 worktree ? got_worktree_get_root_path(worktree) : NULL);
4703 if (error)
4704 goto done;
4706 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
4707 if (error)
4708 goto done;
4710 error = got_reflist_object_id_map_create(&refs_idmap, &refs, repo);
4711 if (error)
4712 goto done;
4714 if (start_commit == NULL) {
4715 struct got_reference *head_ref;
4716 struct got_commit_object *commit = NULL;
4717 error = got_ref_open(&head_ref, repo,
4718 worktree ? got_worktree_get_head_ref_name(worktree)
4719 : GOT_REF_HEAD, 0);
4720 if (error != NULL)
4721 goto done;
4722 error = got_ref_resolve(&start_id, repo, head_ref);
4723 got_ref_close(head_ref);
4724 if (error != NULL)
4725 goto done;
4726 error = got_object_open_as_commit(&commit, repo,
4727 start_id);
4728 if (error != NULL)
4729 goto done;
4730 got_object_commit_close(commit);
4731 } else {
4732 error = got_repo_match_object_id(&start_id, NULL,
4733 start_commit, GOT_OBJ_TYPE_COMMIT, &refs, repo);
4734 if (error != NULL)
4735 goto done;
4737 if (end_commit != NULL) {
4738 error = got_repo_match_object_id(&end_id, NULL,
4739 end_commit, GOT_OBJ_TYPE_COMMIT, &refs, repo);
4740 if (error != NULL)
4741 goto done;
4744 if (worktree) {
4746 * If a path was specified on the command line it was resolved
4747 * to a path in the work tree above. Prepend the work tree's
4748 * path prefix to obtain the corresponding in-repository path.
4750 if (path) {
4751 const char *prefix;
4752 prefix = got_worktree_get_path_prefix(worktree);
4753 if (asprintf(&in_repo_path, "%s%s%s", prefix,
4754 (path[0] != '\0') ? "/" : "", path) == -1) {
4755 error = got_error_from_errno("asprintf");
4756 goto done;
4759 } else
4760 error = got_repo_map_path(&in_repo_path, repo,
4761 path ? path : "");
4762 if (error != NULL)
4763 goto done;
4764 if (in_repo_path) {
4765 free(path);
4766 path = in_repo_path;
4769 if (worktree) {
4770 /* Release work tree lock. */
4771 got_worktree_close(worktree);
4772 worktree = NULL;
4775 if (search_pattern && show_patch) {
4776 tmpfile = got_opentemp();
4777 if (tmpfile == NULL) {
4778 error = got_error_from_errno("got_opentemp");
4779 goto done;
4783 error = print_commits(start_id, end_id, repo, path ? path : "",
4784 show_changed_paths, show_diffstat, show_patch, search_pattern,
4785 diff_context, limit, log_branches, reverse_display_order,
4786 refs_idmap, one_line, tmpfile);
4787 done:
4788 free(path);
4789 free(repo_path);
4790 free(cwd);
4791 free(start_id);
4792 free(end_id);
4793 if (worktree)
4794 got_worktree_close(worktree);
4795 if (repo) {
4796 const struct got_error *close_err = got_repo_close(repo);
4797 if (error == NULL)
4798 error = close_err;
4800 if (pack_fds) {
4801 const struct got_error *pack_err =
4802 got_repo_pack_fds_close(pack_fds);
4803 if (error == NULL)
4804 error = pack_err;
4806 if (refs_idmap)
4807 got_reflist_object_id_map_free(refs_idmap);
4808 if (tmpfile && fclose(tmpfile) == EOF && error == NULL)
4809 error = got_error_from_errno("fclose");
4810 got_ref_list_free(&refs);
4811 return error;
4814 __dead static void
4815 usage_diff(void)
4817 fprintf(stderr, "usage: %s diff [-adPsw] [-C number] [-c commit] "
4818 "[-r repository-path] [object1 object2 | path ...]\n",
4819 getprogname());
4820 exit(1);
4823 struct print_diff_arg {
4824 struct got_repository *repo;
4825 struct got_worktree *worktree;
4826 struct got_diffstat_cb_arg *diffstat;
4827 int diff_context;
4828 const char *id_str;
4829 int header_shown;
4830 int diff_staged;
4831 enum got_diff_algorithm diff_algo;
4832 int ignore_whitespace;
4833 int force_text_diff;
4834 FILE *f1;
4835 FILE *f2;
4836 FILE *outfile;
4840 * Create a file which contains the target path of a symlink so we can feed
4841 * it as content to the diff engine.
4843 static const struct got_error *
4844 get_symlink_target_file(int *fd, int dirfd, const char *de_name,
4845 const char *abspath)
4847 const struct got_error *err = NULL;
4848 char target_path[PATH_MAX];
4849 ssize_t target_len, outlen;
4851 *fd = -1;
4853 if (dirfd != -1) {
4854 target_len = readlinkat(dirfd, de_name, target_path, PATH_MAX);
4855 if (target_len == -1)
4856 return got_error_from_errno2("readlinkat", abspath);
4857 } else {
4858 target_len = readlink(abspath, target_path, PATH_MAX);
4859 if (target_len == -1)
4860 return got_error_from_errno2("readlink", abspath);
4863 *fd = got_opentempfd();
4864 if (*fd == -1)
4865 return got_error_from_errno("got_opentempfd");
4867 outlen = write(*fd, target_path, target_len);
4868 if (outlen == -1) {
4869 err = got_error_from_errno("got_opentempfd");
4870 goto done;
4873 if (lseek(*fd, 0, SEEK_SET) == -1) {
4874 err = got_error_from_errno2("lseek", abspath);
4875 goto done;
4877 done:
4878 if (err) {
4879 close(*fd);
4880 *fd = -1;
4882 return err;
4885 static const struct got_error *
4886 print_diff(void *arg, unsigned char status, unsigned char staged_status,
4887 const char *path, struct got_object_id *blob_id,
4888 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
4889 int dirfd, const char *de_name)
4891 struct print_diff_arg *a = arg;
4892 const struct got_error *err = NULL;
4893 struct got_blob_object *blob1 = NULL;
4894 int fd = -1, fd1 = -1, fd2 = -1;
4895 FILE *f2 = NULL;
4896 char *abspath = NULL, *label1 = NULL;
4897 struct stat sb;
4898 off_t size1 = 0;
4899 int f2_exists = 0;
4901 memset(&sb, 0, sizeof(sb));
4903 if (a->diff_staged) {
4904 if (staged_status != GOT_STATUS_MODIFY &&
4905 staged_status != GOT_STATUS_ADD &&
4906 staged_status != GOT_STATUS_DELETE)
4907 return NULL;
4908 } else {
4909 if (staged_status == GOT_STATUS_DELETE)
4910 return NULL;
4911 if (status == GOT_STATUS_NONEXISTENT)
4912 return got_error_set_errno(ENOENT, path);
4913 if (status != GOT_STATUS_MODIFY &&
4914 status != GOT_STATUS_ADD &&
4915 status != GOT_STATUS_DELETE &&
4916 status != GOT_STATUS_CONFLICT)
4917 return NULL;
4920 err = got_opentemp_truncate(a->f1);
4921 if (err)
4922 return got_error_from_errno("got_opentemp_truncate");
4923 err = got_opentemp_truncate(a->f2);
4924 if (err)
4925 return got_error_from_errno("got_opentemp_truncate");
4927 if (!a->header_shown) {
4928 if (fprintf(a->outfile, "diff %s%s\n",
4929 a->diff_staged ? "-s " : "",
4930 got_worktree_get_root_path(a->worktree)) < 0) {
4931 err = got_error_from_errno("fprintf");
4932 goto done;
4934 if (fprintf(a->outfile, "commit - %s\n", a->id_str) < 0) {
4935 err = got_error_from_errno("fprintf");
4936 goto done;
4938 if (fprintf(a->outfile, "path + %s%s\n",
4939 got_worktree_get_root_path(a->worktree),
4940 a->diff_staged ? " (staged changes)" : "") < 0) {
4941 err = got_error_from_errno("fprintf");
4942 goto done;
4944 a->header_shown = 1;
4947 if (a->diff_staged) {
4948 const char *label1 = NULL, *label2 = NULL;
4949 switch (staged_status) {
4950 case GOT_STATUS_MODIFY:
4951 label1 = path;
4952 label2 = path;
4953 break;
4954 case GOT_STATUS_ADD:
4955 label2 = path;
4956 break;
4957 case GOT_STATUS_DELETE:
4958 label1 = path;
4959 break;
4960 default:
4961 return got_error(GOT_ERR_FILE_STATUS);
4963 fd1 = got_opentempfd();
4964 if (fd1 == -1) {
4965 err = got_error_from_errno("got_opentempfd");
4966 goto done;
4968 fd2 = got_opentempfd();
4969 if (fd2 == -1) {
4970 err = got_error_from_errno("got_opentempfd");
4971 goto done;
4973 err = got_diff_objects_as_blobs(NULL, NULL, a->f1, a->f2,
4974 fd1, fd2, blob_id, staged_blob_id, label1, label2,
4975 a->diff_algo, a->diff_context, a->ignore_whitespace,
4976 a->force_text_diff, a->diffstat, a->repo, a->outfile);
4977 goto done;
4980 fd1 = got_opentempfd();
4981 if (fd1 == -1) {
4982 err = got_error_from_errno("got_opentempfd");
4983 goto done;
4986 if (staged_status == GOT_STATUS_ADD ||
4987 staged_status == GOT_STATUS_MODIFY) {
4988 char *id_str;
4989 err = got_object_open_as_blob(&blob1, a->repo, staged_blob_id,
4990 8192, fd1);
4991 if (err)
4992 goto done;
4993 err = got_object_id_str(&id_str, staged_blob_id);
4994 if (err)
4995 goto done;
4996 if (asprintf(&label1, "%s (staged)", id_str) == -1) {
4997 err = got_error_from_errno("asprintf");
4998 free(id_str);
4999 goto done;
5001 free(id_str);
5002 } else if (status != GOT_STATUS_ADD) {
5003 err = got_object_open_as_blob(&blob1, a->repo, blob_id, 8192,
5004 fd1);
5005 if (err)
5006 goto done;
5009 if (status != GOT_STATUS_DELETE) {
5010 if (asprintf(&abspath, "%s/%s",
5011 got_worktree_get_root_path(a->worktree), path) == -1) {
5012 err = got_error_from_errno("asprintf");
5013 goto done;
5016 if (dirfd != -1) {
5017 fd = openat(dirfd, de_name,
5018 O_RDONLY | O_NOFOLLOW | O_CLOEXEC);
5019 if (fd == -1) {
5020 if (!got_err_open_nofollow_on_symlink()) {
5021 err = got_error_from_errno2("openat",
5022 abspath);
5023 goto done;
5025 err = get_symlink_target_file(&fd, dirfd,
5026 de_name, abspath);
5027 if (err)
5028 goto done;
5030 } else {
5031 fd = open(abspath, O_RDONLY | O_NOFOLLOW | O_CLOEXEC);
5032 if (fd == -1) {
5033 if (!got_err_open_nofollow_on_symlink()) {
5034 err = got_error_from_errno2("open",
5035 abspath);
5036 goto done;
5038 err = get_symlink_target_file(&fd, dirfd,
5039 de_name, abspath);
5040 if (err)
5041 goto done;
5044 if (fstatat(fd, abspath, &sb, AT_SYMLINK_NOFOLLOW) == -1) {
5045 err = got_error_from_errno2("fstatat", abspath);
5046 goto done;
5048 f2 = fdopen(fd, "r");
5049 if (f2 == NULL) {
5050 err = got_error_from_errno2("fdopen", abspath);
5051 goto done;
5053 fd = -1;
5054 f2_exists = 1;
5057 if (blob1) {
5058 err = got_object_blob_dump_to_file(&size1, NULL, NULL,
5059 a->f1, blob1);
5060 if (err)
5061 goto done;
5064 err = got_diff_blob_file(blob1, a->f1, size1, label1, f2 ? f2 : a->f2,
5065 f2_exists, &sb, path, GOT_DIFF_ALGORITHM_PATIENCE, a->diff_context,
5066 a->ignore_whitespace, a->force_text_diff, a->diffstat, a->outfile);
5067 done:
5068 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
5069 err = got_error_from_errno("close");
5070 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
5071 err = got_error_from_errno("close");
5072 if (blob1)
5073 got_object_blob_close(blob1);
5074 if (fd != -1 && close(fd) == -1 && err == NULL)
5075 err = got_error_from_errno("close");
5076 if (f2 && fclose(f2) == EOF && err == NULL)
5077 err = got_error_from_errno("fclose");
5078 free(abspath);
5079 return err;
5082 static const struct got_error *
5083 cmd_diff(int argc, char *argv[])
5085 const struct got_error *error;
5086 struct got_repository *repo = NULL;
5087 struct got_worktree *worktree = NULL;
5088 char *cwd = NULL, *repo_path = NULL;
5089 const char *commit_args[2] = { NULL, NULL };
5090 int ncommit_args = 0;
5091 struct got_object_id *ids[2] = { NULL, NULL };
5092 char *labels[2] = { NULL, NULL };
5093 int type1 = GOT_OBJ_TYPE_ANY, type2 = GOT_OBJ_TYPE_ANY;
5094 int diff_context = 3, diff_staged = 0, ignore_whitespace = 0, ch, i;
5095 int force_text_diff = 0, force_path = 0, rflag = 0, show_diffstat = 0;
5096 const char *errstr;
5097 struct got_reflist_head refs;
5098 struct got_pathlist_head diffstat_paths, paths;
5099 FILE *f1 = NULL, *f2 = NULL, *outfile = NULL;
5100 int fd1 = -1, fd2 = -1;
5101 int *pack_fds = NULL;
5102 struct got_diffstat_cb_arg dsa;
5104 memset(&dsa, 0, sizeof(dsa));
5106 TAILQ_INIT(&refs);
5107 TAILQ_INIT(&paths);
5108 TAILQ_INIT(&diffstat_paths);
5110 #ifndef PROFILE
5111 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
5112 NULL) == -1)
5113 err(1, "pledge");
5114 #endif
5116 while ((ch = getopt(argc, argv, "aC:c:dPr:sw")) != -1) {
5117 switch (ch) {
5118 case 'a':
5119 force_text_diff = 1;
5120 break;
5121 case 'C':
5122 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
5123 &errstr);
5124 if (errstr != NULL)
5125 errx(1, "number of context lines is %s: %s",
5126 errstr, optarg);
5127 break;
5128 case 'c':
5129 if (ncommit_args >= 2)
5130 errx(1, "too many -c options used");
5131 commit_args[ncommit_args++] = optarg;
5132 break;
5133 case 'd':
5134 show_diffstat = 1;
5135 break;
5136 case 'P':
5137 force_path = 1;
5138 break;
5139 case 'r':
5140 repo_path = realpath(optarg, NULL);
5141 if (repo_path == NULL)
5142 return got_error_from_errno2("realpath",
5143 optarg);
5144 got_path_strip_trailing_slashes(repo_path);
5145 rflag = 1;
5146 break;
5147 case 's':
5148 diff_staged = 1;
5149 break;
5150 case 'w':
5151 ignore_whitespace = 1;
5152 break;
5153 default:
5154 usage_diff();
5155 /* NOTREACHED */
5159 argc -= optind;
5160 argv += optind;
5162 cwd = getcwd(NULL, 0);
5163 if (cwd == NULL) {
5164 error = got_error_from_errno("getcwd");
5165 goto done;
5168 error = got_repo_pack_fds_open(&pack_fds);
5169 if (error != NULL)
5170 goto done;
5172 if (repo_path == NULL) {
5173 error = got_worktree_open(&worktree, cwd);
5174 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5175 goto done;
5176 else
5177 error = NULL;
5178 if (worktree) {
5179 repo_path =
5180 strdup(got_worktree_get_repo_path(worktree));
5181 if (repo_path == NULL) {
5182 error = got_error_from_errno("strdup");
5183 goto done;
5185 } else {
5186 repo_path = strdup(cwd);
5187 if (repo_path == NULL) {
5188 error = got_error_from_errno("strdup");
5189 goto done;
5194 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
5195 free(repo_path);
5196 if (error != NULL)
5197 goto done;
5199 if (show_diffstat) {
5200 dsa.paths = &diffstat_paths;
5201 dsa.force_text = force_text_diff;
5202 dsa.ignore_ws = ignore_whitespace;
5203 dsa.diff_algo = GOT_DIFF_ALGORITHM_PATIENCE;
5206 if (rflag || worktree == NULL || ncommit_args > 0) {
5207 if (force_path) {
5208 error = got_error_msg(GOT_ERR_NOT_IMPL,
5209 "-P option can only be used when diffing "
5210 "a work tree");
5211 goto done;
5213 if (diff_staged) {
5214 error = got_error_msg(GOT_ERR_NOT_IMPL,
5215 "-s option can only be used when diffing "
5216 "a work tree");
5217 goto done;
5221 error = apply_unveil(got_repo_get_path(repo), 1,
5222 worktree ? got_worktree_get_root_path(worktree) : NULL);
5223 if (error)
5224 goto done;
5226 if ((!force_path && argc == 2) || ncommit_args > 0) {
5227 int obj_type = (ncommit_args > 0 ?
5228 GOT_OBJ_TYPE_COMMIT : GOT_OBJ_TYPE_ANY);
5229 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
5230 NULL);
5231 if (error)
5232 goto done;
5233 for (i = 0; i < (ncommit_args > 0 ? ncommit_args : argc); i++) {
5234 const char *arg;
5235 if (ncommit_args > 0)
5236 arg = commit_args[i];
5237 else
5238 arg = argv[i];
5239 error = got_repo_match_object_id(&ids[i], &labels[i],
5240 arg, obj_type, &refs, repo);
5241 if (error) {
5242 if (error->code != GOT_ERR_NOT_REF &&
5243 error->code != GOT_ERR_NO_OBJ)
5244 goto done;
5245 if (ncommit_args > 0)
5246 goto done;
5247 error = NULL;
5248 break;
5253 f1 = got_opentemp();
5254 if (f1 == NULL) {
5255 error = got_error_from_errno("got_opentemp");
5256 goto done;
5259 f2 = got_opentemp();
5260 if (f2 == NULL) {
5261 error = got_error_from_errno("got_opentemp");
5262 goto done;
5265 outfile = got_opentemp();
5266 if (outfile == NULL) {
5267 error = got_error_from_errno("got_opentemp");
5268 goto done;
5271 if (ncommit_args == 0 && (ids[0] == NULL || ids[1] == NULL)) {
5272 struct print_diff_arg arg;
5273 char *id_str;
5275 if (worktree == NULL) {
5276 if (argc == 2 && ids[0] == NULL) {
5277 error = got_error_path(argv[0], GOT_ERR_NO_OBJ);
5278 goto done;
5279 } else if (argc == 2 && ids[1] == NULL) {
5280 error = got_error_path(argv[1], GOT_ERR_NO_OBJ);
5281 goto done;
5282 } else if (argc > 0) {
5283 error = got_error_fmt(GOT_ERR_NOT_WORKTREE,
5284 "%s", "specified paths cannot be resolved");
5285 goto done;
5286 } else {
5287 error = got_error(GOT_ERR_NOT_WORKTREE);
5288 goto done;
5292 error = get_worktree_paths_from_argv(&paths, argc, argv,
5293 worktree);
5294 if (error)
5295 goto done;
5297 error = got_object_id_str(&id_str,
5298 got_worktree_get_base_commit_id(worktree));
5299 if (error)
5300 goto done;
5301 arg.repo = repo;
5302 arg.worktree = worktree;
5303 arg.diff_algo = GOT_DIFF_ALGORITHM_PATIENCE;
5304 arg.diff_context = diff_context;
5305 arg.id_str = id_str;
5306 arg.header_shown = 0;
5307 arg.diff_staged = diff_staged;
5308 arg.ignore_whitespace = ignore_whitespace;
5309 arg.force_text_diff = force_text_diff;
5310 arg.diffstat = show_diffstat ? &dsa : NULL;
5311 arg.f1 = f1;
5312 arg.f2 = f2;
5313 arg.outfile = outfile;
5315 error = got_worktree_status(worktree, &paths, repo, 0,
5316 print_diff, &arg, check_cancelled, NULL);
5317 free(id_str);
5318 if (error)
5319 goto done;
5321 if (show_diffstat && dsa.nfiles > 0) {
5322 char *header;
5324 if (asprintf(&header, "diffstat %s%s",
5325 diff_staged ? "-s " : "",
5326 got_worktree_get_root_path(worktree)) == -1) {
5327 error = got_error_from_errno("asprintf");
5328 goto done;
5331 error = print_diffstat(&dsa, header);
5332 free(header);
5333 if (error)
5334 goto done;
5337 error = printfile(outfile);
5338 goto done;
5341 if (ncommit_args == 1) {
5342 struct got_commit_object *commit;
5343 error = got_object_open_as_commit(&commit, repo, ids[0]);
5344 if (error)
5345 goto done;
5347 labels[1] = labels[0];
5348 ids[1] = ids[0];
5349 if (got_object_commit_get_nparents(commit) > 0) {
5350 const struct got_object_id_queue *pids;
5351 struct got_object_qid *pid;
5352 pids = got_object_commit_get_parent_ids(commit);
5353 pid = STAILQ_FIRST(pids);
5354 ids[0] = got_object_id_dup(&pid->id);
5355 if (ids[0] == NULL) {
5356 error = got_error_from_errno(
5357 "got_object_id_dup");
5358 got_object_commit_close(commit);
5359 goto done;
5361 error = got_object_id_str(&labels[0], ids[0]);
5362 if (error) {
5363 got_object_commit_close(commit);
5364 goto done;
5366 } else {
5367 ids[0] = NULL;
5368 labels[0] = strdup("/dev/null");
5369 if (labels[0] == NULL) {
5370 error = got_error_from_errno("strdup");
5371 got_object_commit_close(commit);
5372 goto done;
5376 got_object_commit_close(commit);
5379 if (ncommit_args == 0 && argc > 2) {
5380 error = got_error_msg(GOT_ERR_BAD_PATH,
5381 "path arguments cannot be used when diffing two objects");
5382 goto done;
5385 if (ids[0]) {
5386 error = got_object_get_type(&type1, repo, ids[0]);
5387 if (error)
5388 goto done;
5391 error = got_object_get_type(&type2, repo, ids[1]);
5392 if (error)
5393 goto done;
5394 if (type1 != GOT_OBJ_TYPE_ANY && type1 != type2) {
5395 error = got_error(GOT_ERR_OBJ_TYPE);
5396 goto done;
5398 if (type1 == GOT_OBJ_TYPE_BLOB && argc > 2) {
5399 error = got_error_msg(GOT_ERR_OBJ_TYPE,
5400 "path arguments cannot be used when diffing blobs");
5401 goto done;
5404 for (i = 0; ncommit_args > 0 && i < argc; i++) {
5405 char *in_repo_path;
5406 struct got_pathlist_entry *new;
5407 if (worktree) {
5408 const char *prefix;
5409 char *p;
5410 error = got_worktree_resolve_path(&p, worktree,
5411 argv[i]);
5412 if (error)
5413 goto done;
5414 prefix = got_worktree_get_path_prefix(worktree);
5415 while (prefix[0] == '/')
5416 prefix++;
5417 if (asprintf(&in_repo_path, "%s%s%s", prefix,
5418 (p[0] != '\0' && prefix[0] != '\0') ? "/" : "",
5419 p) == -1) {
5420 error = got_error_from_errno("asprintf");
5421 free(p);
5422 goto done;
5424 free(p);
5425 } else {
5426 char *mapped_path, *s;
5427 error = got_repo_map_path(&mapped_path, repo, argv[i]);
5428 if (error)
5429 goto done;
5430 s = mapped_path;
5431 while (s[0] == '/')
5432 s++;
5433 in_repo_path = strdup(s);
5434 if (in_repo_path == NULL) {
5435 error = got_error_from_errno("asprintf");
5436 free(mapped_path);
5437 goto done;
5439 free(mapped_path);
5442 error = got_pathlist_insert(&new, &paths, in_repo_path, NULL);
5443 if (error || new == NULL /* duplicate */)
5444 free(in_repo_path);
5445 if (error)
5446 goto done;
5449 if (worktree) {
5450 /* Release work tree lock. */
5451 got_worktree_close(worktree);
5452 worktree = NULL;
5455 fd1 = got_opentempfd();
5456 if (fd1 == -1) {
5457 error = got_error_from_errno("got_opentempfd");
5458 goto done;
5461 fd2 = got_opentempfd();
5462 if (fd2 == -1) {
5463 error = got_error_from_errno("got_opentempfd");
5464 goto done;
5467 switch (type1 == GOT_OBJ_TYPE_ANY ? type2 : type1) {
5468 case GOT_OBJ_TYPE_BLOB:
5469 error = got_diff_objects_as_blobs(NULL, NULL, f1, f2,
5470 fd1, fd2, ids[0], ids[1], NULL, NULL,
5471 GOT_DIFF_ALGORITHM_PATIENCE, diff_context,
5472 ignore_whitespace, force_text_diff,
5473 show_diffstat ? &dsa : NULL, repo, outfile);
5474 break;
5475 case GOT_OBJ_TYPE_TREE:
5476 error = got_diff_objects_as_trees(NULL, NULL, f1, f2, fd1, fd2,
5477 ids[0], ids[1], &paths, "", "",
5478 GOT_DIFF_ALGORITHM_PATIENCE, diff_context,
5479 ignore_whitespace, force_text_diff,
5480 show_diffstat ? &dsa : NULL, repo, outfile);
5481 break;
5482 case GOT_OBJ_TYPE_COMMIT:
5483 fprintf(outfile, "diff %s %s\n", labels[0], labels[1]);
5484 error = got_diff_objects_as_commits(NULL, NULL, f1, f2,
5485 fd1, fd2, ids[0], ids[1], &paths,
5486 GOT_DIFF_ALGORITHM_PATIENCE, diff_context,
5487 ignore_whitespace, force_text_diff,
5488 show_diffstat ? &dsa : NULL, repo, outfile);
5489 break;
5490 default:
5491 error = got_error(GOT_ERR_OBJ_TYPE);
5493 if (error)
5494 goto done;
5496 if (show_diffstat && dsa.nfiles > 0) {
5497 char *header = NULL;
5499 if (asprintf(&header, "diffstat %s %s",
5500 labels[0], labels[1]) == -1) {
5501 error = got_error_from_errno("asprintf");
5502 goto done;
5505 error = print_diffstat(&dsa, header);
5506 free(header);
5507 if (error)
5508 goto done;
5511 error = printfile(outfile);
5513 done:
5514 free(labels[0]);
5515 free(labels[1]);
5516 free(ids[0]);
5517 free(ids[1]);
5518 if (worktree)
5519 got_worktree_close(worktree);
5520 if (repo) {
5521 const struct got_error *close_err = got_repo_close(repo);
5522 if (error == NULL)
5523 error = close_err;
5525 if (pack_fds) {
5526 const struct got_error *pack_err =
5527 got_repo_pack_fds_close(pack_fds);
5528 if (error == NULL)
5529 error = pack_err;
5531 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
5532 got_pathlist_free(&diffstat_paths, GOT_PATHLIST_FREE_ALL);
5533 got_ref_list_free(&refs);
5534 if (outfile && fclose(outfile) == EOF && error == NULL)
5535 error = got_error_from_errno("fclose");
5536 if (f1 && fclose(f1) == EOF && error == NULL)
5537 error = got_error_from_errno("fclose");
5538 if (f2 && fclose(f2) == EOF && error == NULL)
5539 error = got_error_from_errno("fclose");
5540 if (fd1 != -1 && close(fd1) == -1 && error == NULL)
5541 error = got_error_from_errno("close");
5542 if (fd2 != -1 && close(fd2) == -1 && error == NULL)
5543 error = got_error_from_errno("close");
5544 return error;
5547 __dead static void
5548 usage_blame(void)
5550 fprintf(stderr,
5551 "usage: %s blame [-c commit] [-r repository-path] path\n",
5552 getprogname());
5553 exit(1);
5556 struct blame_line {
5557 int annotated;
5558 char *id_str;
5559 char *committer;
5560 char datebuf[11]; /* YYYY-MM-DD + NUL */
5563 struct blame_cb_args {
5564 struct blame_line *lines;
5565 int nlines;
5566 int nlines_prec;
5567 int lineno_cur;
5568 off_t *line_offsets;
5569 FILE *f;
5570 struct got_repository *repo;
5573 static const struct got_error *
5574 blame_cb(void *arg, int nlines, int lineno,
5575 struct got_commit_object *commit, struct got_object_id *id)
5577 const struct got_error *err = NULL;
5578 struct blame_cb_args *a = arg;
5579 struct blame_line *bline;
5580 char *line = NULL;
5581 size_t linesize = 0;
5582 off_t offset;
5583 struct tm tm;
5584 time_t committer_time;
5586 if (nlines != a->nlines ||
5587 (lineno != -1 && lineno < 1) || lineno > a->nlines)
5588 return got_error(GOT_ERR_RANGE);
5590 if (sigint_received)
5591 return got_error(GOT_ERR_ITER_COMPLETED);
5593 if (lineno == -1)
5594 return NULL; /* no change in this commit */
5596 /* Annotate this line. */
5597 bline = &a->lines[lineno - 1];
5598 if (bline->annotated)
5599 return NULL;
5600 err = got_object_id_str(&bline->id_str, id);
5601 if (err)
5602 return err;
5604 bline->committer = strdup(got_object_commit_get_committer(commit));
5605 if (bline->committer == NULL) {
5606 err = got_error_from_errno("strdup");
5607 goto done;
5610 committer_time = got_object_commit_get_committer_time(commit);
5611 if (gmtime_r(&committer_time, &tm) == NULL)
5612 return got_error_from_errno("gmtime_r");
5613 if (strftime(bline->datebuf, sizeof(bline->datebuf), "%G-%m-%d",
5614 &tm) == 0) {
5615 err = got_error(GOT_ERR_NO_SPACE);
5616 goto done;
5618 bline->annotated = 1;
5620 /* Print lines annotated so far. */
5621 bline = &a->lines[a->lineno_cur - 1];
5622 if (!bline->annotated)
5623 goto done;
5625 offset = a->line_offsets[a->lineno_cur - 1];
5626 if (fseeko(a->f, offset, SEEK_SET) == -1) {
5627 err = got_error_from_errno("fseeko");
5628 goto done;
5631 while (a->lineno_cur <= a->nlines && bline->annotated) {
5632 char *smallerthan, *at, *nl, *committer;
5633 size_t len;
5635 if (getline(&line, &linesize, a->f) == -1) {
5636 if (ferror(a->f))
5637 err = got_error_from_errno("getline");
5638 break;
5641 committer = bline->committer;
5642 smallerthan = strchr(committer, '<');
5643 if (smallerthan && smallerthan[1] != '\0')
5644 committer = smallerthan + 1;
5645 at = strchr(committer, '@');
5646 if (at)
5647 *at = '\0';
5648 len = strlen(committer);
5649 if (len >= 9)
5650 committer[8] = '\0';
5652 nl = strchr(line, '\n');
5653 if (nl)
5654 *nl = '\0';
5655 printf("%.*d) %.8s %s %-8s %s\n", a->nlines_prec, a->lineno_cur,
5656 bline->id_str, bline->datebuf, committer, line);
5658 a->lineno_cur++;
5659 bline = &a->lines[a->lineno_cur - 1];
5661 done:
5662 free(line);
5663 return err;
5666 static const struct got_error *
5667 cmd_blame(int argc, char *argv[])
5669 const struct got_error *error;
5670 struct got_repository *repo = NULL;
5671 struct got_worktree *worktree = NULL;
5672 char *path, *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
5673 char *link_target = NULL;
5674 struct got_object_id *obj_id = NULL;
5675 struct got_object_id *commit_id = NULL;
5676 struct got_commit_object *commit = NULL;
5677 struct got_blob_object *blob = NULL;
5678 char *commit_id_str = NULL;
5679 struct blame_cb_args bca;
5680 int ch, obj_type, i, fd1 = -1, fd2 = -1, fd3 = -1;
5681 off_t filesize;
5682 int *pack_fds = NULL;
5683 FILE *f1 = NULL, *f2 = NULL;
5685 fd1 = got_opentempfd();
5686 if (fd1 == -1)
5687 return got_error_from_errno("got_opentempfd");
5689 memset(&bca, 0, sizeof(bca));
5691 #ifndef PROFILE
5692 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
5693 NULL) == -1)
5694 err(1, "pledge");
5695 #endif
5697 while ((ch = getopt(argc, argv, "c:r:")) != -1) {
5698 switch (ch) {
5699 case 'c':
5700 commit_id_str = optarg;
5701 break;
5702 case 'r':
5703 repo_path = realpath(optarg, NULL);
5704 if (repo_path == NULL)
5705 return got_error_from_errno2("realpath",
5706 optarg);
5707 got_path_strip_trailing_slashes(repo_path);
5708 break;
5709 default:
5710 usage_blame();
5711 /* NOTREACHED */
5715 argc -= optind;
5716 argv += optind;
5718 if (argc == 1)
5719 path = argv[0];
5720 else
5721 usage_blame();
5723 cwd = getcwd(NULL, 0);
5724 if (cwd == NULL) {
5725 error = got_error_from_errno("getcwd");
5726 goto done;
5729 error = got_repo_pack_fds_open(&pack_fds);
5730 if (error != NULL)
5731 goto done;
5733 if (repo_path == NULL) {
5734 error = got_worktree_open(&worktree, cwd);
5735 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5736 goto done;
5737 else
5738 error = NULL;
5739 if (worktree) {
5740 repo_path =
5741 strdup(got_worktree_get_repo_path(worktree));
5742 if (repo_path == NULL) {
5743 error = got_error_from_errno("strdup");
5744 if (error)
5745 goto done;
5747 } else {
5748 repo_path = strdup(cwd);
5749 if (repo_path == NULL) {
5750 error = got_error_from_errno("strdup");
5751 goto done;
5756 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
5757 if (error != NULL)
5758 goto done;
5760 if (worktree) {
5761 const char *prefix = got_worktree_get_path_prefix(worktree);
5762 char *p;
5764 error = got_worktree_resolve_path(&p, worktree, path);
5765 if (error)
5766 goto done;
5767 if (asprintf(&in_repo_path, "%s%s%s", prefix,
5768 (p[0] != '\0' && !got_path_is_root_dir(prefix)) ? "/" : "",
5769 p) == -1) {
5770 error = got_error_from_errno("asprintf");
5771 free(p);
5772 goto done;
5774 free(p);
5775 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5776 } else {
5777 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5778 if (error)
5779 goto done;
5780 error = got_repo_map_path(&in_repo_path, repo, path);
5782 if (error)
5783 goto done;
5785 if (commit_id_str == NULL) {
5786 struct got_reference *head_ref;
5787 error = got_ref_open(&head_ref, repo, worktree ?
5788 got_worktree_get_head_ref_name(worktree) : GOT_REF_HEAD, 0);
5789 if (error != NULL)
5790 goto done;
5791 error = got_ref_resolve(&commit_id, repo, head_ref);
5792 got_ref_close(head_ref);
5793 if (error != NULL)
5794 goto done;
5795 } else {
5796 struct got_reflist_head refs;
5797 TAILQ_INIT(&refs);
5798 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
5799 NULL);
5800 if (error)
5801 goto done;
5802 error = got_repo_match_object_id(&commit_id, NULL,
5803 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
5804 got_ref_list_free(&refs);
5805 if (error)
5806 goto done;
5809 if (worktree) {
5810 /* Release work tree lock. */
5811 got_worktree_close(worktree);
5812 worktree = NULL;
5815 error = got_object_open_as_commit(&commit, repo, commit_id);
5816 if (error)
5817 goto done;
5819 error = got_object_resolve_symlinks(&link_target, in_repo_path,
5820 commit, repo);
5821 if (error)
5822 goto done;
5824 error = got_object_id_by_path(&obj_id, repo, commit,
5825 link_target ? link_target : in_repo_path);
5826 if (error)
5827 goto done;
5829 error = got_object_get_type(&obj_type, repo, obj_id);
5830 if (error)
5831 goto done;
5833 if (obj_type != GOT_OBJ_TYPE_BLOB) {
5834 error = got_error_path(link_target ? link_target : in_repo_path,
5835 GOT_ERR_OBJ_TYPE);
5836 goto done;
5839 error = got_object_open_as_blob(&blob, repo, obj_id, 8192, fd1);
5840 if (error)
5841 goto done;
5842 bca.f = got_opentemp();
5843 if (bca.f == NULL) {
5844 error = got_error_from_errno("got_opentemp");
5845 goto done;
5847 error = got_object_blob_dump_to_file(&filesize, &bca.nlines,
5848 &bca.line_offsets, bca.f, blob);
5849 if (error || bca.nlines == 0)
5850 goto done;
5852 /* Don't include \n at EOF in the blame line count. */
5853 if (bca.line_offsets[bca.nlines - 1] == filesize)
5854 bca.nlines--;
5856 bca.lines = calloc(bca.nlines, sizeof(*bca.lines));
5857 if (bca.lines == NULL) {
5858 error = got_error_from_errno("calloc");
5859 goto done;
5861 bca.lineno_cur = 1;
5862 bca.nlines_prec = 0;
5863 i = bca.nlines;
5864 while (i > 0) {
5865 i /= 10;
5866 bca.nlines_prec++;
5868 bca.repo = repo;
5870 fd2 = got_opentempfd();
5871 if (fd2 == -1) {
5872 error = got_error_from_errno("got_opentempfd");
5873 goto done;
5875 fd3 = got_opentempfd();
5876 if (fd3 == -1) {
5877 error = got_error_from_errno("got_opentempfd");
5878 goto done;
5880 f1 = got_opentemp();
5881 if (f1 == NULL) {
5882 error = got_error_from_errno("got_opentemp");
5883 goto done;
5885 f2 = got_opentemp();
5886 if (f2 == NULL) {
5887 error = got_error_from_errno("got_opentemp");
5888 goto done;
5890 error = got_blame(link_target ? link_target : in_repo_path, commit_id,
5891 repo, GOT_DIFF_ALGORITHM_PATIENCE, blame_cb, &bca,
5892 check_cancelled, NULL, fd2, fd3, f1, f2);
5893 done:
5894 free(in_repo_path);
5895 free(link_target);
5896 free(repo_path);
5897 free(cwd);
5898 free(commit_id);
5899 free(obj_id);
5900 if (commit)
5901 got_object_commit_close(commit);
5903 if (fd1 != -1 && close(fd1) == -1 && error == NULL)
5904 error = got_error_from_errno("close");
5905 if (fd2 != -1 && close(fd2) == -1 && error == NULL)
5906 error = got_error_from_errno("close");
5907 if (fd3 != -1 && close(fd3) == -1 && error == NULL)
5908 error = got_error_from_errno("close");
5909 if (f1 && fclose(f1) == EOF && error == NULL)
5910 error = got_error_from_errno("fclose");
5911 if (f2 && fclose(f2) == EOF && error == NULL)
5912 error = got_error_from_errno("fclose");
5914 if (blob)
5915 got_object_blob_close(blob);
5916 if (worktree)
5917 got_worktree_close(worktree);
5918 if (repo) {
5919 const struct got_error *close_err = got_repo_close(repo);
5920 if (error == NULL)
5921 error = close_err;
5923 if (pack_fds) {
5924 const struct got_error *pack_err =
5925 got_repo_pack_fds_close(pack_fds);
5926 if (error == NULL)
5927 error = pack_err;
5929 if (bca.lines) {
5930 for (i = 0; i < bca.nlines; i++) {
5931 struct blame_line *bline = &bca.lines[i];
5932 free(bline->id_str);
5933 free(bline->committer);
5935 free(bca.lines);
5937 free(bca.line_offsets);
5938 if (bca.f && fclose(bca.f) == EOF && error == NULL)
5939 error = got_error_from_errno("fclose");
5940 return error;
5943 __dead static void
5944 usage_tree(void)
5946 fprintf(stderr, "usage: %s tree [-iR] [-c commit] [-r repository-path] "
5947 "[path]\n", getprogname());
5948 exit(1);
5951 static const struct got_error *
5952 print_entry(struct got_tree_entry *te, const char *id, const char *path,
5953 const char *root_path, struct got_repository *repo)
5955 const struct got_error *err = NULL;
5956 int is_root_path = (strcmp(path, root_path) == 0);
5957 const char *modestr = "";
5958 mode_t mode = got_tree_entry_get_mode(te);
5959 char *link_target = NULL;
5961 path += strlen(root_path);
5962 while (path[0] == '/')
5963 path++;
5965 if (got_object_tree_entry_is_submodule(te))
5966 modestr = "$";
5967 else if (S_ISLNK(mode)) {
5968 int i;
5970 err = got_tree_entry_get_symlink_target(&link_target, te, repo);
5971 if (err)
5972 return err;
5973 for (i = 0; link_target[i] != '\0'; i++) {
5974 if (!isprint((unsigned char)link_target[i]))
5975 link_target[i] = '?';
5978 modestr = "@";
5980 else if (S_ISDIR(mode))
5981 modestr = "/";
5982 else if (mode & S_IXUSR)
5983 modestr = "*";
5985 printf("%s%s%s%s%s%s%s\n", id ? id : "", path,
5986 is_root_path ? "" : "/", got_tree_entry_get_name(te), modestr,
5987 link_target ? " -> ": "", link_target ? link_target : "");
5989 free(link_target);
5990 return NULL;
5993 static const struct got_error *
5994 print_tree(const char *path, struct got_commit_object *commit,
5995 int show_ids, int recurse, const char *root_path,
5996 struct got_repository *repo)
5998 const struct got_error *err = NULL;
5999 struct got_object_id *tree_id = NULL;
6000 struct got_tree_object *tree = NULL;
6001 int nentries, i;
6003 err = got_object_id_by_path(&tree_id, repo, commit, path);
6004 if (err)
6005 goto done;
6007 err = got_object_open_as_tree(&tree, repo, tree_id);
6008 if (err)
6009 goto done;
6010 nentries = got_object_tree_get_nentries(tree);
6011 for (i = 0; i < nentries; i++) {
6012 struct got_tree_entry *te;
6013 char *id = NULL;
6015 if (sigint_received || sigpipe_received)
6016 break;
6018 te = got_object_tree_get_entry(tree, i);
6019 if (show_ids) {
6020 char *id_str;
6021 err = got_object_id_str(&id_str,
6022 got_tree_entry_get_id(te));
6023 if (err)
6024 goto done;
6025 if (asprintf(&id, "%s ", id_str) == -1) {
6026 err = got_error_from_errno("asprintf");
6027 free(id_str);
6028 goto done;
6030 free(id_str);
6032 err = print_entry(te, id, path, root_path, repo);
6033 free(id);
6034 if (err)
6035 goto done;
6037 if (recurse && S_ISDIR(got_tree_entry_get_mode(te))) {
6038 char *child_path;
6039 if (asprintf(&child_path, "%s%s%s", path,
6040 path[0] == '/' && path[1] == '\0' ? "" : "/",
6041 got_tree_entry_get_name(te)) == -1) {
6042 err = got_error_from_errno("asprintf");
6043 goto done;
6045 err = print_tree(child_path, commit, show_ids, 1,
6046 root_path, repo);
6047 free(child_path);
6048 if (err)
6049 goto done;
6052 done:
6053 if (tree)
6054 got_object_tree_close(tree);
6055 free(tree_id);
6056 return err;
6059 static const struct got_error *
6060 cmd_tree(int argc, char *argv[])
6062 const struct got_error *error;
6063 struct got_repository *repo = NULL;
6064 struct got_worktree *worktree = NULL;
6065 const char *path, *refname = NULL;
6066 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
6067 struct got_object_id *commit_id = NULL;
6068 struct got_commit_object *commit = NULL;
6069 char *commit_id_str = NULL;
6070 int show_ids = 0, recurse = 0;
6071 int ch;
6072 int *pack_fds = NULL;
6074 #ifndef PROFILE
6075 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
6076 NULL) == -1)
6077 err(1, "pledge");
6078 #endif
6080 while ((ch = getopt(argc, argv, "c:iRr:")) != -1) {
6081 switch (ch) {
6082 case 'c':
6083 commit_id_str = optarg;
6084 break;
6085 case 'i':
6086 show_ids = 1;
6087 break;
6088 case 'R':
6089 recurse = 1;
6090 break;
6091 case 'r':
6092 repo_path = realpath(optarg, NULL);
6093 if (repo_path == NULL)
6094 return got_error_from_errno2("realpath",
6095 optarg);
6096 got_path_strip_trailing_slashes(repo_path);
6097 break;
6098 default:
6099 usage_tree();
6100 /* NOTREACHED */
6104 argc -= optind;
6105 argv += optind;
6107 if (argc == 1)
6108 path = argv[0];
6109 else if (argc > 1)
6110 usage_tree();
6111 else
6112 path = NULL;
6114 cwd = getcwd(NULL, 0);
6115 if (cwd == NULL) {
6116 error = got_error_from_errno("getcwd");
6117 goto done;
6120 error = got_repo_pack_fds_open(&pack_fds);
6121 if (error != NULL)
6122 goto done;
6124 if (repo_path == NULL) {
6125 error = got_worktree_open(&worktree, cwd);
6126 if (error && error->code != GOT_ERR_NOT_WORKTREE)
6127 goto done;
6128 else
6129 error = NULL;
6130 if (worktree) {
6131 repo_path =
6132 strdup(got_worktree_get_repo_path(worktree));
6133 if (repo_path == NULL)
6134 error = got_error_from_errno("strdup");
6135 if (error)
6136 goto done;
6137 } else {
6138 repo_path = strdup(cwd);
6139 if (repo_path == NULL) {
6140 error = got_error_from_errno("strdup");
6141 goto done;
6146 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
6147 if (error != NULL)
6148 goto done;
6150 if (worktree) {
6151 const char *prefix = got_worktree_get_path_prefix(worktree);
6152 char *p;
6154 if (path == NULL || got_path_is_root_dir(path))
6155 path = "";
6156 error = got_worktree_resolve_path(&p, worktree, path);
6157 if (error)
6158 goto done;
6159 if (asprintf(&in_repo_path, "%s%s%s", prefix,
6160 (p[0] != '\0' && !got_path_is_root_dir(prefix)) ? "/" : "",
6161 p) == -1) {
6162 error = got_error_from_errno("asprintf");
6163 free(p);
6164 goto done;
6166 free(p);
6167 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
6168 if (error)
6169 goto done;
6170 } else {
6171 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
6172 if (error)
6173 goto done;
6174 if (path == NULL)
6175 path = "/";
6176 error = got_repo_map_path(&in_repo_path, repo, path);
6177 if (error != NULL)
6178 goto done;
6181 if (commit_id_str == NULL) {
6182 struct got_reference *head_ref;
6183 if (worktree)
6184 refname = got_worktree_get_head_ref_name(worktree);
6185 else
6186 refname = GOT_REF_HEAD;
6187 error = got_ref_open(&head_ref, repo, refname, 0);
6188 if (error != NULL)
6189 goto done;
6190 error = got_ref_resolve(&commit_id, repo, head_ref);
6191 got_ref_close(head_ref);
6192 if (error != NULL)
6193 goto done;
6194 } else {
6195 struct got_reflist_head refs;
6196 TAILQ_INIT(&refs);
6197 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
6198 NULL);
6199 if (error)
6200 goto done;
6201 error = got_repo_match_object_id(&commit_id, NULL,
6202 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
6203 got_ref_list_free(&refs);
6204 if (error)
6205 goto done;
6208 if (worktree) {
6209 /* Release work tree lock. */
6210 got_worktree_close(worktree);
6211 worktree = NULL;
6214 error = got_object_open_as_commit(&commit, repo, commit_id);
6215 if (error)
6216 goto done;
6218 error = print_tree(in_repo_path, commit, show_ids, recurse,
6219 in_repo_path, repo);
6220 done:
6221 free(in_repo_path);
6222 free(repo_path);
6223 free(cwd);
6224 free(commit_id);
6225 if (commit)
6226 got_object_commit_close(commit);
6227 if (worktree)
6228 got_worktree_close(worktree);
6229 if (repo) {
6230 const struct got_error *close_err = got_repo_close(repo);
6231 if (error == NULL)
6232 error = close_err;
6234 if (pack_fds) {
6235 const struct got_error *pack_err =
6236 got_repo_pack_fds_close(pack_fds);
6237 if (error == NULL)
6238 error = pack_err;
6240 return error;
6243 __dead static void
6244 usage_status(void)
6246 fprintf(stderr, "usage: %s status [-I] [-S status-codes] "
6247 "[-s status-codes] [path ...]\n", getprogname());
6248 exit(1);
6251 struct got_status_arg {
6252 char *status_codes;
6253 int suppress;
6256 static const struct got_error *
6257 print_status(void *arg, unsigned char status, unsigned char staged_status,
6258 const char *path, struct got_object_id *blob_id,
6259 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
6260 int dirfd, const char *de_name)
6262 struct got_status_arg *st = arg;
6264 if (status == staged_status && (status == GOT_STATUS_DELETE))
6265 status = GOT_STATUS_NO_CHANGE;
6266 if (st != NULL && st->status_codes) {
6267 size_t ncodes = strlen(st->status_codes);
6268 int i, j = 0;
6270 for (i = 0; i < ncodes ; i++) {
6271 if (st->suppress) {
6272 if (status == st->status_codes[i] ||
6273 staged_status == st->status_codes[i]) {
6274 j++;
6275 continue;
6277 } else {
6278 if (status == st->status_codes[i] ||
6279 staged_status == st->status_codes[i])
6280 break;
6284 if (st->suppress && j == 0)
6285 goto print;
6287 if (i == ncodes)
6288 return NULL;
6290 print:
6291 printf("%c%c %s\n", status, staged_status, path);
6292 return NULL;
6295 static const struct got_error *
6296 cmd_status(int argc, char *argv[])
6298 const struct got_error *error = NULL;
6299 struct got_repository *repo = NULL;
6300 struct got_worktree *worktree = NULL;
6301 struct got_status_arg st;
6302 char *cwd = NULL;
6303 struct got_pathlist_head paths;
6304 int ch, i, no_ignores = 0;
6305 int *pack_fds = NULL;
6307 TAILQ_INIT(&paths);
6309 memset(&st, 0, sizeof(st));
6310 st.status_codes = NULL;
6311 st.suppress = 0;
6313 #ifndef PROFILE
6314 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
6315 NULL) == -1)
6316 err(1, "pledge");
6317 #endif
6319 while ((ch = getopt(argc, argv, "IS:s:")) != -1) {
6320 switch (ch) {
6321 case 'I':
6322 no_ignores = 1;
6323 break;
6324 case 'S':
6325 if (st.status_codes != NULL && st.suppress == 0)
6326 option_conflict('S', 's');
6327 st.suppress = 1;
6328 /* fallthrough */
6329 case 's':
6330 for (i = 0; optarg[i] != '\0'; i++) {
6331 switch (optarg[i]) {
6332 case GOT_STATUS_MODIFY:
6333 case GOT_STATUS_ADD:
6334 case GOT_STATUS_DELETE:
6335 case GOT_STATUS_CONFLICT:
6336 case GOT_STATUS_MISSING:
6337 case GOT_STATUS_OBSTRUCTED:
6338 case GOT_STATUS_UNVERSIONED:
6339 case GOT_STATUS_MODE_CHANGE:
6340 case GOT_STATUS_NONEXISTENT:
6341 break;
6342 default:
6343 errx(1, "invalid status code '%c'",
6344 optarg[i]);
6347 if (ch == 's' && st.suppress)
6348 option_conflict('s', 'S');
6349 st.status_codes = optarg;
6350 break;
6351 default:
6352 usage_status();
6353 /* NOTREACHED */
6357 argc -= optind;
6358 argv += optind;
6360 cwd = getcwd(NULL, 0);
6361 if (cwd == NULL) {
6362 error = got_error_from_errno("getcwd");
6363 goto done;
6366 error = got_repo_pack_fds_open(&pack_fds);
6367 if (error != NULL)
6368 goto done;
6370 error = got_worktree_open(&worktree, cwd);
6371 if (error) {
6372 if (error->code == GOT_ERR_NOT_WORKTREE)
6373 error = wrap_not_worktree_error(error, "status", cwd);
6374 goto done;
6377 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
6378 NULL, pack_fds);
6379 if (error != NULL)
6380 goto done;
6382 error = apply_unveil(got_repo_get_path(repo), 1,
6383 got_worktree_get_root_path(worktree));
6384 if (error)
6385 goto done;
6387 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
6388 if (error)
6389 goto done;
6391 error = got_worktree_status(worktree, &paths, repo, no_ignores,
6392 print_status, &st, check_cancelled, NULL);
6393 done:
6394 if (pack_fds) {
6395 const struct got_error *pack_err =
6396 got_repo_pack_fds_close(pack_fds);
6397 if (error == NULL)
6398 error = pack_err;
6400 if (repo) {
6401 const struct got_error *close_err = got_repo_close(repo);
6402 if (error == NULL)
6403 error = close_err;
6406 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
6407 free(cwd);
6408 return error;
6411 __dead static void
6412 usage_ref(void)
6414 fprintf(stderr, "usage: %s ref [-dlt] [-c object] [-r repository-path] "
6415 "[-s reference] [name]\n", getprogname());
6416 exit(1);
6419 static const struct got_error *
6420 list_refs(struct got_repository *repo, const char *refname, int sort_by_time)
6422 static const struct got_error *err = NULL;
6423 struct got_reflist_head refs;
6424 struct got_reflist_entry *re;
6426 TAILQ_INIT(&refs);
6427 err = got_ref_list(&refs, repo, refname, sort_by_time ?
6428 got_ref_cmp_by_commit_timestamp_descending : got_ref_cmp_by_name,
6429 repo);
6430 if (err)
6431 return err;
6433 TAILQ_FOREACH(re, &refs, entry) {
6434 char *refstr;
6435 refstr = got_ref_to_str(re->ref);
6436 if (refstr == NULL) {
6437 err = got_error_from_errno("got_ref_to_str");
6438 break;
6440 printf("%s: %s\n", got_ref_get_name(re->ref), refstr);
6441 free(refstr);
6444 got_ref_list_free(&refs);
6445 return err;
6448 static const struct got_error *
6449 delete_ref_by_name(struct got_repository *repo, const char *refname)
6451 const struct got_error *err;
6452 struct got_reference *ref;
6454 err = got_ref_open(&ref, repo, refname, 0);
6455 if (err)
6456 return err;
6458 err = delete_ref(repo, ref);
6459 got_ref_close(ref);
6460 return err;
6463 static const struct got_error *
6464 add_ref(struct got_repository *repo, const char *refname, const char *target)
6466 const struct got_error *err = NULL;
6467 struct got_object_id *id = NULL;
6468 struct got_reference *ref = NULL;
6469 struct got_reflist_head refs;
6472 * Don't let the user create a reference name with a leading '-'.
6473 * While technically a valid reference name, this case is usually
6474 * an unintended typo.
6476 if (refname[0] == '-')
6477 return got_error_path(refname, GOT_ERR_REF_NAME_MINUS);
6479 TAILQ_INIT(&refs);
6480 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
6481 if (err)
6482 goto done;
6483 err = got_repo_match_object_id(&id, NULL, target, GOT_OBJ_TYPE_ANY,
6484 &refs, repo);
6485 got_ref_list_free(&refs);
6486 if (err)
6487 goto done;
6489 err = got_ref_alloc(&ref, refname, id);
6490 if (err)
6491 goto done;
6493 err = got_ref_write(ref, repo);
6494 done:
6495 if (ref)
6496 got_ref_close(ref);
6497 free(id);
6498 return err;
6501 static const struct got_error *
6502 add_symref(struct got_repository *repo, const char *refname, const char *target)
6504 const struct got_error *err = NULL;
6505 struct got_reference *ref = NULL;
6506 struct got_reference *target_ref = NULL;
6509 * Don't let the user create a reference name with a leading '-'.
6510 * While technically a valid reference name, this case is usually
6511 * an unintended typo.
6513 if (refname[0] == '-')
6514 return got_error_path(refname, GOT_ERR_REF_NAME_MINUS);
6516 err = got_ref_open(&target_ref, repo, target, 0);
6517 if (err)
6518 return err;
6520 err = got_ref_alloc_symref(&ref, refname, target_ref);
6521 if (err)
6522 goto done;
6524 err = got_ref_write(ref, repo);
6525 done:
6526 if (target_ref)
6527 got_ref_close(target_ref);
6528 if (ref)
6529 got_ref_close(ref);
6530 return err;
6533 static const struct got_error *
6534 cmd_ref(int argc, char *argv[])
6536 const struct got_error *error = NULL;
6537 struct got_repository *repo = NULL;
6538 struct got_worktree *worktree = NULL;
6539 char *cwd = NULL, *repo_path = NULL;
6540 int ch, do_list = 0, do_delete = 0, sort_by_time = 0;
6541 const char *obj_arg = NULL, *symref_target= NULL;
6542 char *refname = NULL;
6543 int *pack_fds = NULL;
6545 #ifndef PROFILE
6546 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
6547 "sendfd unveil", NULL) == -1)
6548 err(1, "pledge");
6549 #endif
6551 while ((ch = getopt(argc, argv, "c:dlr:s:t")) != -1) {
6552 switch (ch) {
6553 case 'c':
6554 obj_arg = optarg;
6555 break;
6556 case 'd':
6557 do_delete = 1;
6558 break;
6559 case 'l':
6560 do_list = 1;
6561 break;
6562 case 'r':
6563 repo_path = realpath(optarg, NULL);
6564 if (repo_path == NULL)
6565 return got_error_from_errno2("realpath",
6566 optarg);
6567 got_path_strip_trailing_slashes(repo_path);
6568 break;
6569 case 's':
6570 symref_target = optarg;
6571 break;
6572 case 't':
6573 sort_by_time = 1;
6574 break;
6575 default:
6576 usage_ref();
6577 /* NOTREACHED */
6581 if (obj_arg && do_list)
6582 option_conflict('c', 'l');
6583 if (obj_arg && do_delete)
6584 option_conflict('c', 'd');
6585 if (obj_arg && symref_target)
6586 option_conflict('c', 's');
6587 if (symref_target && do_delete)
6588 option_conflict('s', 'd');
6589 if (symref_target && do_list)
6590 option_conflict('s', 'l');
6591 if (do_delete && do_list)
6592 option_conflict('d', 'l');
6593 if (sort_by_time && !do_list)
6594 errx(1, "-t option requires -l option");
6596 argc -= optind;
6597 argv += optind;
6599 if (do_list) {
6600 if (argc != 0 && argc != 1)
6601 usage_ref();
6602 if (argc == 1) {
6603 refname = strdup(argv[0]);
6604 if (refname == NULL) {
6605 error = got_error_from_errno("strdup");
6606 goto done;
6609 } else {
6610 if (argc != 1)
6611 usage_ref();
6612 refname = strdup(argv[0]);
6613 if (refname == NULL) {
6614 error = got_error_from_errno("strdup");
6615 goto done;
6619 if (refname)
6620 got_path_strip_trailing_slashes(refname);
6622 cwd = getcwd(NULL, 0);
6623 if (cwd == NULL) {
6624 error = got_error_from_errno("getcwd");
6625 goto done;
6628 error = got_repo_pack_fds_open(&pack_fds);
6629 if (error != NULL)
6630 goto done;
6632 if (repo_path == NULL) {
6633 error = got_worktree_open(&worktree, cwd);
6634 if (error && error->code != GOT_ERR_NOT_WORKTREE)
6635 goto done;
6636 else
6637 error = NULL;
6638 if (worktree) {
6639 repo_path =
6640 strdup(got_worktree_get_repo_path(worktree));
6641 if (repo_path == NULL)
6642 error = got_error_from_errno("strdup");
6643 if (error)
6644 goto done;
6645 } else {
6646 repo_path = strdup(cwd);
6647 if (repo_path == NULL) {
6648 error = got_error_from_errno("strdup");
6649 goto done;
6654 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
6655 if (error != NULL)
6656 goto done;
6658 #ifndef PROFILE
6659 if (do_list) {
6660 /* Remove "cpath" promise. */
6661 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
6662 NULL) == -1)
6663 err(1, "pledge");
6665 #endif
6667 error = apply_unveil(got_repo_get_path(repo), do_list,
6668 worktree ? got_worktree_get_root_path(worktree) : NULL);
6669 if (error)
6670 goto done;
6672 if (do_list)
6673 error = list_refs(repo, refname, sort_by_time);
6674 else if (do_delete)
6675 error = delete_ref_by_name(repo, refname);
6676 else if (symref_target)
6677 error = add_symref(repo, refname, symref_target);
6678 else {
6679 if (obj_arg == NULL)
6680 usage_ref();
6681 error = add_ref(repo, refname, obj_arg);
6683 done:
6684 free(refname);
6685 if (repo) {
6686 const struct got_error *close_err = got_repo_close(repo);
6687 if (error == NULL)
6688 error = close_err;
6690 if (worktree)
6691 got_worktree_close(worktree);
6692 if (pack_fds) {
6693 const struct got_error *pack_err =
6694 got_repo_pack_fds_close(pack_fds);
6695 if (error == NULL)
6696 error = pack_err;
6698 free(cwd);
6699 free(repo_path);
6700 return error;
6703 __dead static void
6704 usage_branch(void)
6706 fprintf(stderr, "usage: %s branch [-lnt] [-c commit] [-d name] "
6707 "[-r repository-path] [name]\n", getprogname());
6708 exit(1);
6711 static const struct got_error *
6712 list_branch(struct got_repository *repo, struct got_worktree *worktree,
6713 struct got_reference *ref)
6715 const struct got_error *err = NULL;
6716 const char *refname, *marker = " ";
6717 char *refstr;
6719 refname = got_ref_get_name(ref);
6720 if (worktree && strcmp(refname,
6721 got_worktree_get_head_ref_name(worktree)) == 0) {
6722 struct got_object_id *id = NULL;
6724 err = got_ref_resolve(&id, repo, ref);
6725 if (err)
6726 return err;
6727 if (got_object_id_cmp(id,
6728 got_worktree_get_base_commit_id(worktree)) == 0)
6729 marker = "* ";
6730 else
6731 marker = "~ ";
6732 free(id);
6735 if (strncmp(refname, "refs/heads/", 11) == 0)
6736 refname += 11;
6737 if (strncmp(refname, "refs/got/worktree/", 18) == 0)
6738 refname += 18;
6739 if (strncmp(refname, "refs/remotes/", 13) == 0)
6740 refname += 13;
6742 refstr = got_ref_to_str(ref);
6743 if (refstr == NULL)
6744 return got_error_from_errno("got_ref_to_str");
6746 printf("%s%s: %s\n", marker, refname, refstr);
6747 free(refstr);
6748 return NULL;
6751 static const struct got_error *
6752 show_current_branch(struct got_repository *repo, struct got_worktree *worktree)
6754 const char *refname;
6756 if (worktree == NULL)
6757 return got_error(GOT_ERR_NOT_WORKTREE);
6759 refname = got_worktree_get_head_ref_name(worktree);
6761 if (strncmp(refname, "refs/heads/", 11) == 0)
6762 refname += 11;
6763 if (strncmp(refname, "refs/got/worktree/", 18) == 0)
6764 refname += 18;
6766 printf("%s\n", refname);
6768 return NULL;
6771 static const struct got_error *
6772 list_branches(struct got_repository *repo, struct got_worktree *worktree,
6773 int sort_by_time)
6775 static const struct got_error *err = NULL;
6776 struct got_reflist_head refs;
6777 struct got_reflist_entry *re;
6778 struct got_reference *temp_ref = NULL;
6779 int rebase_in_progress, histedit_in_progress;
6781 TAILQ_INIT(&refs);
6783 if (worktree) {
6784 err = got_worktree_rebase_in_progress(&rebase_in_progress,
6785 worktree);
6786 if (err)
6787 return err;
6789 err = got_worktree_histedit_in_progress(&histedit_in_progress,
6790 worktree);
6791 if (err)
6792 return err;
6794 if (rebase_in_progress || histedit_in_progress) {
6795 err = got_ref_open(&temp_ref, repo,
6796 got_worktree_get_head_ref_name(worktree), 0);
6797 if (err)
6798 return err;
6799 list_branch(repo, worktree, temp_ref);
6800 got_ref_close(temp_ref);
6804 err = got_ref_list(&refs, repo, "refs/heads", sort_by_time ?
6805 got_ref_cmp_by_commit_timestamp_descending : got_ref_cmp_by_name,
6806 repo);
6807 if (err)
6808 return err;
6810 TAILQ_FOREACH(re, &refs, entry)
6811 list_branch(repo, worktree, re->ref);
6813 got_ref_list_free(&refs);
6815 err = got_ref_list(&refs, repo, "refs/remotes", sort_by_time ?
6816 got_ref_cmp_by_commit_timestamp_descending : got_ref_cmp_by_name,
6817 repo);
6818 if (err)
6819 return err;
6821 TAILQ_FOREACH(re, &refs, entry)
6822 list_branch(repo, worktree, re->ref);
6824 got_ref_list_free(&refs);
6826 return NULL;
6829 static const struct got_error *
6830 delete_branch(struct got_repository *repo, struct got_worktree *worktree,
6831 const char *branch_name)
6833 const struct got_error *err = NULL;
6834 struct got_reference *ref = NULL;
6835 char *refname, *remote_refname = NULL;
6837 if (strncmp(branch_name, "refs/", 5) == 0)
6838 branch_name += 5;
6839 if (strncmp(branch_name, "heads/", 6) == 0)
6840 branch_name += 6;
6841 else if (strncmp(branch_name, "remotes/", 8) == 0)
6842 branch_name += 8;
6844 if (asprintf(&refname, "refs/heads/%s", branch_name) == -1)
6845 return got_error_from_errno("asprintf");
6847 if (asprintf(&remote_refname, "refs/remotes/%s",
6848 branch_name) == -1) {
6849 err = got_error_from_errno("asprintf");
6850 goto done;
6853 err = got_ref_open(&ref, repo, refname, 0);
6854 if (err) {
6855 const struct got_error *err2;
6856 if (err->code != GOT_ERR_NOT_REF)
6857 goto done;
6859 * Keep 'err' intact such that if neither branch exists
6860 * we report "refs/heads" rather than "refs/remotes" in
6861 * our error message.
6863 err2 = got_ref_open(&ref, repo, remote_refname, 0);
6864 if (err2)
6865 goto done;
6866 err = NULL;
6869 if (worktree &&
6870 strcmp(got_worktree_get_head_ref_name(worktree),
6871 got_ref_get_name(ref)) == 0) {
6872 err = got_error_msg(GOT_ERR_SAME_BRANCH,
6873 "will not delete this work tree's current branch");
6874 goto done;
6877 err = delete_ref(repo, ref);
6878 done:
6879 if (ref)
6880 got_ref_close(ref);
6881 free(refname);
6882 free(remote_refname);
6883 return err;
6886 static const struct got_error *
6887 add_branch(struct got_repository *repo, const char *branch_name,
6888 struct got_object_id *base_commit_id)
6890 const struct got_error *err = NULL;
6891 struct got_reference *ref = NULL;
6892 char *refname = NULL;
6895 * Don't let the user create a branch name with a leading '-'.
6896 * While technically a valid reference name, this case is usually
6897 * an unintended typo.
6899 if (branch_name[0] == '-')
6900 return got_error_path(branch_name, GOT_ERR_REF_NAME_MINUS);
6902 if (strncmp(branch_name, "refs/heads/", 11) == 0)
6903 branch_name += 11;
6905 if (asprintf(&refname, "refs/heads/%s", branch_name) == -1) {
6906 err = got_error_from_errno("asprintf");
6907 goto done;
6910 err = got_ref_open(&ref, repo, refname, 0);
6911 if (err == NULL) {
6912 err = got_error(GOT_ERR_BRANCH_EXISTS);
6913 goto done;
6914 } else if (err->code != GOT_ERR_NOT_REF)
6915 goto done;
6917 err = got_ref_alloc(&ref, refname, base_commit_id);
6918 if (err)
6919 goto done;
6921 err = got_ref_write(ref, repo);
6922 done:
6923 if (ref)
6924 got_ref_close(ref);
6925 free(refname);
6926 return err;
6929 static const struct got_error *
6930 cmd_branch(int argc, char *argv[])
6932 const struct got_error *error = NULL;
6933 struct got_repository *repo = NULL;
6934 struct got_worktree *worktree = NULL;
6935 char *cwd = NULL, *repo_path = NULL;
6936 int ch, do_list = 0, do_show = 0, do_update = 1, sort_by_time = 0;
6937 const char *delref = NULL, *commit_id_arg = NULL;
6938 struct got_reference *ref = NULL;
6939 struct got_pathlist_head paths;
6940 struct got_object_id *commit_id = NULL;
6941 char *commit_id_str = NULL;
6942 int *pack_fds = NULL;
6944 TAILQ_INIT(&paths);
6946 #ifndef PROFILE
6947 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
6948 "sendfd unveil", NULL) == -1)
6949 err(1, "pledge");
6950 #endif
6952 while ((ch = getopt(argc, argv, "c:d:lnr:t")) != -1) {
6953 switch (ch) {
6954 case 'c':
6955 commit_id_arg = optarg;
6956 break;
6957 case 'd':
6958 delref = optarg;
6959 break;
6960 case 'l':
6961 do_list = 1;
6962 break;
6963 case 'n':
6964 do_update = 0;
6965 break;
6966 case 'r':
6967 repo_path = realpath(optarg, NULL);
6968 if (repo_path == NULL)
6969 return got_error_from_errno2("realpath",
6970 optarg);
6971 got_path_strip_trailing_slashes(repo_path);
6972 break;
6973 case 't':
6974 sort_by_time = 1;
6975 break;
6976 default:
6977 usage_branch();
6978 /* NOTREACHED */
6982 if (do_list && delref)
6983 option_conflict('l', 'd');
6984 if (sort_by_time && !do_list)
6985 errx(1, "-t option requires -l option");
6987 argc -= optind;
6988 argv += optind;
6990 if (!do_list && !delref && argc == 0)
6991 do_show = 1;
6993 if ((do_list || delref || do_show) && commit_id_arg != NULL)
6994 errx(1, "-c option can only be used when creating a branch");
6996 if (do_list || delref) {
6997 if (argc > 0)
6998 usage_branch();
6999 } else if (!do_show && argc != 1)
7000 usage_branch();
7002 cwd = getcwd(NULL, 0);
7003 if (cwd == NULL) {
7004 error = got_error_from_errno("getcwd");
7005 goto done;
7008 error = got_repo_pack_fds_open(&pack_fds);
7009 if (error != NULL)
7010 goto done;
7012 if (repo_path == NULL) {
7013 error = got_worktree_open(&worktree, cwd);
7014 if (error && error->code != GOT_ERR_NOT_WORKTREE)
7015 goto done;
7016 else
7017 error = NULL;
7018 if (worktree) {
7019 repo_path =
7020 strdup(got_worktree_get_repo_path(worktree));
7021 if (repo_path == NULL)
7022 error = got_error_from_errno("strdup");
7023 if (error)
7024 goto done;
7025 } else {
7026 repo_path = strdup(cwd);
7027 if (repo_path == NULL) {
7028 error = got_error_from_errno("strdup");
7029 goto done;
7034 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
7035 if (error != NULL)
7036 goto done;
7038 #ifndef PROFILE
7039 if (do_list || do_show) {
7040 /* Remove "cpath" promise. */
7041 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
7042 NULL) == -1)
7043 err(1, "pledge");
7045 #endif
7047 error = apply_unveil(got_repo_get_path(repo), do_list,
7048 worktree ? got_worktree_get_root_path(worktree) : NULL);
7049 if (error)
7050 goto done;
7052 if (do_show)
7053 error = show_current_branch(repo, worktree);
7054 else if (do_list)
7055 error = list_branches(repo, worktree, sort_by_time);
7056 else if (delref)
7057 error = delete_branch(repo, worktree, delref);
7058 else {
7059 struct got_reflist_head refs;
7060 TAILQ_INIT(&refs);
7061 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
7062 NULL);
7063 if (error)
7064 goto done;
7065 if (commit_id_arg == NULL)
7066 commit_id_arg = worktree ?
7067 got_worktree_get_head_ref_name(worktree) :
7068 GOT_REF_HEAD;
7069 error = got_repo_match_object_id(&commit_id, NULL,
7070 commit_id_arg, GOT_OBJ_TYPE_COMMIT, &refs, repo);
7071 got_ref_list_free(&refs);
7072 if (error)
7073 goto done;
7074 error = add_branch(repo, argv[0], commit_id);
7075 if (error)
7076 goto done;
7077 if (worktree && do_update) {
7078 struct got_update_progress_arg upa;
7079 char *branch_refname = NULL;
7081 error = got_object_id_str(&commit_id_str, commit_id);
7082 if (error)
7083 goto done;
7084 error = get_worktree_paths_from_argv(&paths, 0, NULL,
7085 worktree);
7086 if (error)
7087 goto done;
7088 if (asprintf(&branch_refname, "refs/heads/%s", argv[0])
7089 == -1) {
7090 error = got_error_from_errno("asprintf");
7091 goto done;
7093 error = got_ref_open(&ref, repo, branch_refname, 0);
7094 free(branch_refname);
7095 if (error)
7096 goto done;
7097 error = switch_head_ref(ref, commit_id, worktree,
7098 repo);
7099 if (error)
7100 goto done;
7101 error = got_worktree_set_base_commit_id(worktree, repo,
7102 commit_id);
7103 if (error)
7104 goto done;
7105 memset(&upa, 0, sizeof(upa));
7106 error = got_worktree_checkout_files(worktree, &paths,
7107 repo, update_progress, &upa, check_cancelled,
7108 NULL);
7109 if (error)
7110 goto done;
7111 if (upa.did_something) {
7112 printf("Updated to %s: %s\n",
7113 got_worktree_get_head_ref_name(worktree),
7114 commit_id_str);
7116 print_update_progress_stats(&upa);
7119 done:
7120 if (ref)
7121 got_ref_close(ref);
7122 if (repo) {
7123 const struct got_error *close_err = got_repo_close(repo);
7124 if (error == NULL)
7125 error = close_err;
7127 if (worktree)
7128 got_worktree_close(worktree);
7129 if (pack_fds) {
7130 const struct got_error *pack_err =
7131 got_repo_pack_fds_close(pack_fds);
7132 if (error == NULL)
7133 error = pack_err;
7135 free(cwd);
7136 free(repo_path);
7137 free(commit_id);
7138 free(commit_id_str);
7139 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
7140 return error;
7144 __dead static void
7145 usage_tag(void)
7147 fprintf(stderr, "usage: %s tag [-lVv] [-c commit] [-m message] "
7148 "[-r repository-path] [-s signer-id] name\n", getprogname());
7149 exit(1);
7152 #if 0
7153 static const struct got_error *
7154 sort_tags(struct got_reflist_head *sorted, struct got_reflist_head *tags)
7156 const struct got_error *err = NULL;
7157 struct got_reflist_entry *re, *se, *new;
7158 struct got_object_id *re_id, *se_id;
7159 struct got_tag_object *re_tag, *se_tag;
7160 time_t re_time, se_time;
7162 STAILQ_FOREACH(re, tags, entry) {
7163 se = STAILQ_FIRST(sorted);
7164 if (se == NULL) {
7165 err = got_reflist_entry_dup(&new, re);
7166 if (err)
7167 return err;
7168 STAILQ_INSERT_HEAD(sorted, new, entry);
7169 continue;
7170 } else {
7171 err = got_ref_resolve(&re_id, repo, re->ref);
7172 if (err)
7173 break;
7174 err = got_object_open_as_tag(&re_tag, repo, re_id);
7175 free(re_id);
7176 if (err)
7177 break;
7178 re_time = got_object_tag_get_tagger_time(re_tag);
7179 got_object_tag_close(re_tag);
7182 while (se) {
7183 err = got_ref_resolve(&se_id, repo, re->ref);
7184 if (err)
7185 break;
7186 err = got_object_open_as_tag(&se_tag, repo, se_id);
7187 free(se_id);
7188 if (err)
7189 break;
7190 se_time = got_object_tag_get_tagger_time(se_tag);
7191 got_object_tag_close(se_tag);
7193 if (se_time > re_time) {
7194 err = got_reflist_entry_dup(&new, re);
7195 if (err)
7196 return err;
7197 STAILQ_INSERT_AFTER(sorted, se, new, entry);
7198 break;
7200 se = STAILQ_NEXT(se, entry);
7201 continue;
7204 done:
7205 return err;
7207 #endif
7209 static const struct got_error *
7210 get_tag_refname(char **refname, const char *tag_name)
7212 const struct got_error *err;
7214 if (strncmp("refs/tags/", tag_name, 10) == 0) {
7215 *refname = strdup(tag_name);
7216 if (*refname == NULL)
7217 return got_error_from_errno("strdup");
7218 } else if (asprintf(refname, "refs/tags/%s", tag_name) == -1) {
7219 err = got_error_from_errno("asprintf");
7220 *refname = NULL;
7221 return err;
7224 return NULL;
7227 static const struct got_error *
7228 list_tags(struct got_repository *repo, const char *tag_name, int verify_tags,
7229 const char *allowed_signers, const char *revoked_signers, int verbosity)
7231 static const struct got_error *err = NULL;
7232 struct got_reflist_head refs;
7233 struct got_reflist_entry *re;
7234 char *wanted_refname = NULL;
7235 int bad_sigs = 0;
7237 TAILQ_INIT(&refs);
7239 err = got_ref_list(&refs, repo, "refs/tags", got_ref_cmp_tags, repo);
7240 if (err)
7241 return err;
7243 if (tag_name) {
7244 struct got_reference *ref;
7245 err = get_tag_refname(&wanted_refname, tag_name);
7246 if (err)
7247 goto done;
7248 /* Wanted tag reference should exist. */
7249 err = got_ref_open(&ref, repo, wanted_refname, 0);
7250 if (err)
7251 goto done;
7252 got_ref_close(ref);
7255 TAILQ_FOREACH(re, &refs, entry) {
7256 const char *refname;
7257 char *refstr, *tagmsg0, *tagmsg, *line, *id_str, *datestr;
7258 char datebuf[26];
7259 const char *tagger, *ssh_sig = NULL;
7260 char *sig_msg = NULL;
7261 time_t tagger_time;
7262 struct got_object_id *id;
7263 struct got_tag_object *tag;
7264 struct got_commit_object *commit = NULL;
7266 refname = got_ref_get_name(re->ref);
7267 if (strncmp(refname, "refs/tags/", 10) != 0 ||
7268 (wanted_refname && strcmp(refname, wanted_refname) != 0))
7269 continue;
7270 refname += 10;
7271 refstr = got_ref_to_str(re->ref);
7272 if (refstr == NULL) {
7273 err = got_error_from_errno("got_ref_to_str");
7274 break;
7277 err = got_ref_resolve(&id, repo, re->ref);
7278 if (err)
7279 break;
7280 err = got_object_open_as_tag(&tag, repo, id);
7281 if (err) {
7282 if (err->code != GOT_ERR_OBJ_TYPE) {
7283 free(id);
7284 break;
7286 /* "lightweight" tag */
7287 err = got_object_open_as_commit(&commit, repo, id);
7288 if (err) {
7289 free(id);
7290 break;
7292 tagger = got_object_commit_get_committer(commit);
7293 tagger_time =
7294 got_object_commit_get_committer_time(commit);
7295 err = got_object_id_str(&id_str, id);
7296 free(id);
7297 if (err)
7298 break;
7299 } else {
7300 free(id);
7301 tagger = got_object_tag_get_tagger(tag);
7302 tagger_time = got_object_tag_get_tagger_time(tag);
7303 err = got_object_id_str(&id_str,
7304 got_object_tag_get_object_id(tag));
7305 if (err)
7306 break;
7309 if (tag && verify_tags) {
7310 ssh_sig = got_sigs_get_tagmsg_ssh_signature(
7311 got_object_tag_get_message(tag));
7312 if (ssh_sig && allowed_signers == NULL) {
7313 err = got_error_msg(
7314 GOT_ERR_VERIFY_TAG_SIGNATURE,
7315 "SSH signature verification requires "
7316 "setting allowed_signers in "
7317 "got.conf(5)");
7318 break;
7322 printf("%stag %s %s\n", GOT_COMMIT_SEP_STR, refname, refstr);
7323 free(refstr);
7324 printf("from: %s\n", tagger);
7325 datestr = get_datestr(&tagger_time, datebuf);
7326 if (datestr)
7327 printf("date: %s UTC\n", datestr);
7328 if (commit)
7329 printf("object: %s %s\n", GOT_OBJ_LABEL_COMMIT, id_str);
7330 else {
7331 switch (got_object_tag_get_object_type(tag)) {
7332 case GOT_OBJ_TYPE_BLOB:
7333 printf("object: %s %s\n", GOT_OBJ_LABEL_BLOB,
7334 id_str);
7335 break;
7336 case GOT_OBJ_TYPE_TREE:
7337 printf("object: %s %s\n", GOT_OBJ_LABEL_TREE,
7338 id_str);
7339 break;
7340 case GOT_OBJ_TYPE_COMMIT:
7341 printf("object: %s %s\n", GOT_OBJ_LABEL_COMMIT,
7342 id_str);
7343 break;
7344 case GOT_OBJ_TYPE_TAG:
7345 printf("object: %s %s\n", GOT_OBJ_LABEL_TAG,
7346 id_str);
7347 break;
7348 default:
7349 break;
7352 free(id_str);
7354 if (ssh_sig) {
7355 err = got_sigs_verify_tag_ssh(&sig_msg, tag, ssh_sig,
7356 allowed_signers, revoked_signers, verbosity);
7357 if (err && err->code == GOT_ERR_BAD_TAG_SIGNATURE)
7358 bad_sigs = 1;
7359 else if (err)
7360 break;
7361 printf("signature: %s", sig_msg);
7362 free(sig_msg);
7363 sig_msg = NULL;
7366 if (commit) {
7367 err = got_object_commit_get_logmsg(&tagmsg0, commit);
7368 if (err)
7369 break;
7370 got_object_commit_close(commit);
7371 } else {
7372 tagmsg0 = strdup(got_object_tag_get_message(tag));
7373 got_object_tag_close(tag);
7374 if (tagmsg0 == NULL) {
7375 err = got_error_from_errno("strdup");
7376 break;
7380 tagmsg = tagmsg0;
7381 do {
7382 line = strsep(&tagmsg, "\n");
7383 if (line)
7384 printf(" %s\n", line);
7385 } while (line);
7386 free(tagmsg0);
7388 done:
7389 got_ref_list_free(&refs);
7390 free(wanted_refname);
7392 if (err == NULL && bad_sigs)
7393 err = got_error(GOT_ERR_BAD_TAG_SIGNATURE);
7394 return err;
7397 static const struct got_error *
7398 get_tag_message(char **tagmsg, char **tagmsg_path, const char *commit_id_str,
7399 const char *tag_name, const char *repo_path)
7401 const struct got_error *err = NULL;
7402 char *template = NULL, *initial_content = NULL;
7403 char *editor = NULL;
7404 int initial_content_len;
7405 int fd = -1;
7407 if (asprintf(&template, GOT_TMPDIR_STR "/got-tagmsg") == -1) {
7408 err = got_error_from_errno("asprintf");
7409 goto done;
7412 initial_content_len = asprintf(&initial_content,
7413 "\n# tagging commit %s as %s\n",
7414 commit_id_str, tag_name);
7415 if (initial_content_len == -1) {
7416 err = got_error_from_errno("asprintf");
7417 goto done;
7420 err = got_opentemp_named_fd(tagmsg_path, &fd, template, "");
7421 if (err)
7422 goto done;
7424 if (write(fd, initial_content, initial_content_len) == -1) {
7425 err = got_error_from_errno2("write", *tagmsg_path);
7426 goto done;
7428 if (close(fd) == -1) {
7429 err = got_error_from_errno2("close", *tagmsg_path);
7430 goto done;
7432 fd = -1;
7434 err = get_editor(&editor);
7435 if (err)
7436 goto done;
7437 err = edit_logmsg(tagmsg, editor, *tagmsg_path, initial_content,
7438 initial_content_len, 1);
7439 done:
7440 free(initial_content);
7441 free(template);
7442 free(editor);
7444 if (fd != -1 && close(fd) == -1 && err == NULL)
7445 err = got_error_from_errno2("close", *tagmsg_path);
7447 if (err) {
7448 free(*tagmsg);
7449 *tagmsg = NULL;
7451 return err;
7454 static const struct got_error *
7455 add_tag(struct got_repository *repo, const char *tagger,
7456 const char *tag_name, const char *commit_arg, const char *tagmsg_arg,
7457 const char *signer_id, int verbosity)
7459 const struct got_error *err = NULL;
7460 struct got_object_id *commit_id = NULL, *tag_id = NULL;
7461 char *label = NULL, *commit_id_str = NULL;
7462 struct got_reference *ref = NULL;
7463 char *refname = NULL, *tagmsg = NULL;
7464 char *tagmsg_path = NULL, *tag_id_str = NULL;
7465 int preserve_tagmsg = 0;
7466 struct got_reflist_head refs;
7468 TAILQ_INIT(&refs);
7471 * Don't let the user create a tag name with a leading '-'.
7472 * While technically a valid reference name, this case is usually
7473 * an unintended typo.
7475 if (tag_name[0] == '-')
7476 return got_error_path(tag_name, GOT_ERR_REF_NAME_MINUS);
7478 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
7479 if (err)
7480 goto done;
7482 err = got_repo_match_object_id(&commit_id, &label, commit_arg,
7483 GOT_OBJ_TYPE_COMMIT, &refs, repo);
7484 if (err)
7485 goto done;
7487 err = got_object_id_str(&commit_id_str, commit_id);
7488 if (err)
7489 goto done;
7491 err = get_tag_refname(&refname, tag_name);
7492 if (err)
7493 goto done;
7494 if (strncmp("refs/tags/", tag_name, 10) == 0)
7495 tag_name += 10;
7497 err = got_ref_open(&ref, repo, refname, 0);
7498 if (err == NULL) {
7499 err = got_error(GOT_ERR_TAG_EXISTS);
7500 goto done;
7501 } else if (err->code != GOT_ERR_NOT_REF)
7502 goto done;
7504 if (tagmsg_arg == NULL) {
7505 err = get_tag_message(&tagmsg, &tagmsg_path, commit_id_str,
7506 tag_name, got_repo_get_path(repo));
7507 if (err) {
7508 if (err->code != GOT_ERR_COMMIT_MSG_EMPTY &&
7509 tagmsg_path != NULL)
7510 preserve_tagmsg = 1;
7511 goto done;
7513 /* Editor is done; we can now apply unveil(2) */
7514 err = got_sigs_apply_unveil();
7515 if (err)
7516 goto done;
7517 err = apply_unveil(got_repo_get_path(repo), 0, NULL);
7518 if (err)
7519 goto done;
7522 err = got_object_tag_create(&tag_id, tag_name, commit_id,
7523 tagger, time(NULL), tagmsg ? tagmsg : tagmsg_arg, signer_id, repo,
7524 verbosity);
7525 if (err) {
7526 if (tagmsg_path)
7527 preserve_tagmsg = 1;
7528 goto done;
7531 err = got_ref_alloc(&ref, refname, tag_id);
7532 if (err) {
7533 if (tagmsg_path)
7534 preserve_tagmsg = 1;
7535 goto done;
7538 err = got_ref_write(ref, repo);
7539 if (err) {
7540 if (tagmsg_path)
7541 preserve_tagmsg = 1;
7542 goto done;
7545 err = got_object_id_str(&tag_id_str, tag_id);
7546 if (err) {
7547 if (tagmsg_path)
7548 preserve_tagmsg = 1;
7549 goto done;
7551 printf("Created tag %s\n", tag_id_str);
7552 done:
7553 if (preserve_tagmsg) {
7554 fprintf(stderr, "%s: tag message preserved in %s\n",
7555 getprogname(), tagmsg_path);
7556 } else if (tagmsg_path && unlink(tagmsg_path) == -1 && err == NULL)
7557 err = got_error_from_errno2("unlink", tagmsg_path);
7558 free(tag_id_str);
7559 if (ref)
7560 got_ref_close(ref);
7561 free(commit_id);
7562 free(commit_id_str);
7563 free(refname);
7564 free(tagmsg);
7565 free(tagmsg_path);
7566 got_ref_list_free(&refs);
7567 return err;
7570 static const struct got_error *
7571 cmd_tag(int argc, char *argv[])
7573 const struct got_error *error = NULL;
7574 struct got_repository *repo = NULL;
7575 struct got_worktree *worktree = NULL;
7576 char *cwd = NULL, *repo_path = NULL, *commit_id_str = NULL;
7577 char *gitconfig_path = NULL, *tagger = NULL;
7578 char *allowed_signers = NULL, *revoked_signers = NULL;
7579 const char *signer_id = NULL;
7580 const char *tag_name = NULL, *commit_id_arg = NULL, *tagmsg = NULL;
7581 int ch, do_list = 0, verify_tags = 0, verbosity = 0;
7582 int *pack_fds = NULL;
7584 #ifndef PROFILE
7585 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
7586 "sendfd unveil", NULL) == -1)
7587 err(1, "pledge");
7588 #endif
7590 while ((ch = getopt(argc, argv, "c:lm:r:s:Vv")) != -1) {
7591 switch (ch) {
7592 case 'c':
7593 commit_id_arg = optarg;
7594 break;
7595 case 'l':
7596 do_list = 1;
7597 break;
7598 case 'm':
7599 tagmsg = optarg;
7600 break;
7601 case 'r':
7602 repo_path = realpath(optarg, NULL);
7603 if (repo_path == NULL) {
7604 error = got_error_from_errno2("realpath",
7605 optarg);
7606 goto done;
7608 got_path_strip_trailing_slashes(repo_path);
7609 break;
7610 case 's':
7611 signer_id = optarg;
7612 break;
7613 case 'V':
7614 verify_tags = 1;
7615 break;
7616 case 'v':
7617 if (verbosity < 0)
7618 verbosity = 0;
7619 else if (verbosity < 3)
7620 verbosity++;
7621 break;
7622 default:
7623 usage_tag();
7624 /* NOTREACHED */
7628 argc -= optind;
7629 argv += optind;
7631 if (do_list || verify_tags) {
7632 if (commit_id_arg != NULL)
7633 errx(1,
7634 "-c option can only be used when creating a tag");
7635 if (tagmsg) {
7636 if (do_list)
7637 option_conflict('l', 'm');
7638 else
7639 option_conflict('V', 'm');
7641 if (signer_id) {
7642 if (do_list)
7643 option_conflict('l', 's');
7644 else
7645 option_conflict('V', 's');
7647 if (argc > 1)
7648 usage_tag();
7649 } else if (argc != 1)
7650 usage_tag();
7652 if (argc == 1)
7653 tag_name = argv[0];
7655 cwd = getcwd(NULL, 0);
7656 if (cwd == NULL) {
7657 error = got_error_from_errno("getcwd");
7658 goto done;
7661 error = got_repo_pack_fds_open(&pack_fds);
7662 if (error != NULL)
7663 goto done;
7665 if (repo_path == NULL) {
7666 error = got_worktree_open(&worktree, cwd);
7667 if (error && error->code != GOT_ERR_NOT_WORKTREE)
7668 goto done;
7669 else
7670 error = NULL;
7671 if (worktree) {
7672 repo_path =
7673 strdup(got_worktree_get_repo_path(worktree));
7674 if (repo_path == NULL)
7675 error = got_error_from_errno("strdup");
7676 if (error)
7677 goto done;
7678 } else {
7679 repo_path = strdup(cwd);
7680 if (repo_path == NULL) {
7681 error = got_error_from_errno("strdup");
7682 goto done;
7687 if (do_list || verify_tags) {
7688 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
7689 if (error != NULL)
7690 goto done;
7691 error = get_allowed_signers(&allowed_signers, repo, worktree);
7692 if (error)
7693 goto done;
7694 error = get_revoked_signers(&revoked_signers, repo, worktree);
7695 if (error)
7696 goto done;
7697 if (worktree) {
7698 /* Release work tree lock. */
7699 got_worktree_close(worktree);
7700 worktree = NULL;
7704 * Remove "cpath" promise unless needed for signature tmpfile
7705 * creation.
7707 if (verify_tags)
7708 got_sigs_apply_unveil();
7709 else {
7710 #ifndef PROFILE
7711 if (pledge("stdio rpath wpath flock proc exec sendfd "
7712 "unveil", NULL) == -1)
7713 err(1, "pledge");
7714 #endif
7716 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
7717 if (error)
7718 goto done;
7719 error = list_tags(repo, tag_name, verify_tags, allowed_signers,
7720 revoked_signers, verbosity);
7721 } else {
7722 error = get_gitconfig_path(&gitconfig_path);
7723 if (error)
7724 goto done;
7725 error = got_repo_open(&repo, repo_path, gitconfig_path,
7726 pack_fds);
7727 if (error != NULL)
7728 goto done;
7730 error = get_author(&tagger, repo, worktree);
7731 if (error)
7732 goto done;
7733 if (signer_id == NULL)
7734 signer_id = get_signer_id(repo, worktree);
7736 if (tagmsg) {
7737 if (signer_id) {
7738 error = got_sigs_apply_unveil();
7739 if (error)
7740 goto done;
7742 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
7743 if (error)
7744 goto done;
7747 if (commit_id_arg == NULL) {
7748 struct got_reference *head_ref;
7749 struct got_object_id *commit_id;
7750 error = got_ref_open(&head_ref, repo,
7751 worktree ? got_worktree_get_head_ref_name(worktree)
7752 : GOT_REF_HEAD, 0);
7753 if (error)
7754 goto done;
7755 error = got_ref_resolve(&commit_id, repo, head_ref);
7756 got_ref_close(head_ref);
7757 if (error)
7758 goto done;
7759 error = got_object_id_str(&commit_id_str, commit_id);
7760 free(commit_id);
7761 if (error)
7762 goto done;
7765 if (worktree) {
7766 /* Release work tree lock. */
7767 got_worktree_close(worktree);
7768 worktree = NULL;
7771 error = add_tag(repo, tagger, tag_name,
7772 commit_id_str ? commit_id_str : commit_id_arg, tagmsg,
7773 signer_id, verbosity);
7775 done:
7776 if (repo) {
7777 const struct got_error *close_err = got_repo_close(repo);
7778 if (error == NULL)
7779 error = close_err;
7781 if (worktree)
7782 got_worktree_close(worktree);
7783 if (pack_fds) {
7784 const struct got_error *pack_err =
7785 got_repo_pack_fds_close(pack_fds);
7786 if (error == NULL)
7787 error = pack_err;
7789 free(cwd);
7790 free(repo_path);
7791 free(gitconfig_path);
7792 free(commit_id_str);
7793 free(tagger);
7794 free(allowed_signers);
7795 free(revoked_signers);
7796 return error;
7799 __dead static void
7800 usage_add(void)
7802 fprintf(stderr, "usage: %s add [-IR] path ...\n", getprogname());
7803 exit(1);
7806 static const struct got_error *
7807 add_progress(void *arg, unsigned char status, const char *path)
7809 while (path[0] == '/')
7810 path++;
7811 printf("%c %s\n", status, path);
7812 return NULL;
7815 static const struct got_error *
7816 cmd_add(int argc, char *argv[])
7818 const struct got_error *error = NULL;
7819 struct got_repository *repo = NULL;
7820 struct got_worktree *worktree = NULL;
7821 char *cwd = NULL;
7822 struct got_pathlist_head paths;
7823 struct got_pathlist_entry *pe;
7824 int ch, can_recurse = 0, no_ignores = 0;
7825 int *pack_fds = NULL;
7827 TAILQ_INIT(&paths);
7829 #ifndef PROFILE
7830 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
7831 NULL) == -1)
7832 err(1, "pledge");
7833 #endif
7835 while ((ch = getopt(argc, argv, "IR")) != -1) {
7836 switch (ch) {
7837 case 'I':
7838 no_ignores = 1;
7839 break;
7840 case 'R':
7841 can_recurse = 1;
7842 break;
7843 default:
7844 usage_add();
7845 /* NOTREACHED */
7849 argc -= optind;
7850 argv += optind;
7852 if (argc < 1)
7853 usage_add();
7855 cwd = getcwd(NULL, 0);
7856 if (cwd == NULL) {
7857 error = got_error_from_errno("getcwd");
7858 goto done;
7861 error = got_repo_pack_fds_open(&pack_fds);
7862 if (error != NULL)
7863 goto done;
7865 error = got_worktree_open(&worktree, cwd);
7866 if (error) {
7867 if (error->code == GOT_ERR_NOT_WORKTREE)
7868 error = wrap_not_worktree_error(error, "add", cwd);
7869 goto done;
7872 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
7873 NULL, pack_fds);
7874 if (error != NULL)
7875 goto done;
7877 error = apply_unveil(got_repo_get_path(repo), 1,
7878 got_worktree_get_root_path(worktree));
7879 if (error)
7880 goto done;
7882 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
7883 if (error)
7884 goto done;
7886 if (!can_recurse) {
7887 char *ondisk_path;
7888 struct stat sb;
7889 TAILQ_FOREACH(pe, &paths, entry) {
7890 if (asprintf(&ondisk_path, "%s/%s",
7891 got_worktree_get_root_path(worktree),
7892 pe->path) == -1) {
7893 error = got_error_from_errno("asprintf");
7894 goto done;
7896 if (lstat(ondisk_path, &sb) == -1) {
7897 if (errno == ENOENT) {
7898 free(ondisk_path);
7899 continue;
7901 error = got_error_from_errno2("lstat",
7902 ondisk_path);
7903 free(ondisk_path);
7904 goto done;
7906 free(ondisk_path);
7907 if (S_ISDIR(sb.st_mode)) {
7908 error = got_error_msg(GOT_ERR_BAD_PATH,
7909 "adding directories requires -R option");
7910 goto done;
7915 error = got_worktree_schedule_add(worktree, &paths, add_progress,
7916 NULL, repo, no_ignores);
7917 done:
7918 if (repo) {
7919 const struct got_error *close_err = got_repo_close(repo);
7920 if (error == NULL)
7921 error = close_err;
7923 if (worktree)
7924 got_worktree_close(worktree);
7925 if (pack_fds) {
7926 const struct got_error *pack_err =
7927 got_repo_pack_fds_close(pack_fds);
7928 if (error == NULL)
7929 error = pack_err;
7931 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
7932 free(cwd);
7933 return error;
7936 __dead static void
7937 usage_remove(void)
7939 fprintf(stderr, "usage: %s remove [-fkR] [-s status-codes] path ...\n",
7940 getprogname());
7941 exit(1);
7944 static const struct got_error *
7945 print_remove_status(void *arg, unsigned char status,
7946 unsigned char staged_status, const char *path)
7948 while (path[0] == '/')
7949 path++;
7950 if (status == GOT_STATUS_NONEXISTENT)
7951 return NULL;
7952 if (status == staged_status && (status == GOT_STATUS_DELETE))
7953 status = GOT_STATUS_NO_CHANGE;
7954 printf("%c%c %s\n", status, staged_status, path);
7955 return NULL;
7958 static const struct got_error *
7959 cmd_remove(int argc, char *argv[])
7961 const struct got_error *error = NULL;
7962 struct got_worktree *worktree = NULL;
7963 struct got_repository *repo = NULL;
7964 const char *status_codes = NULL;
7965 char *cwd = NULL;
7966 struct got_pathlist_head paths;
7967 struct got_pathlist_entry *pe;
7968 int ch, delete_local_mods = 0, can_recurse = 0, keep_on_disk = 0, i;
7969 int ignore_missing_paths = 0;
7970 int *pack_fds = NULL;
7972 TAILQ_INIT(&paths);
7974 #ifndef PROFILE
7975 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
7976 NULL) == -1)
7977 err(1, "pledge");
7978 #endif
7980 while ((ch = getopt(argc, argv, "fkRs:")) != -1) {
7981 switch (ch) {
7982 case 'f':
7983 delete_local_mods = 1;
7984 ignore_missing_paths = 1;
7985 break;
7986 case 'k':
7987 keep_on_disk = 1;
7988 break;
7989 case 'R':
7990 can_recurse = 1;
7991 break;
7992 case 's':
7993 for (i = 0; optarg[i] != '\0'; i++) {
7994 switch (optarg[i]) {
7995 case GOT_STATUS_MODIFY:
7996 delete_local_mods = 1;
7997 break;
7998 case GOT_STATUS_MISSING:
7999 ignore_missing_paths = 1;
8000 break;
8001 default:
8002 errx(1, "invalid status code '%c'",
8003 optarg[i]);
8006 status_codes = optarg;
8007 break;
8008 default:
8009 usage_remove();
8010 /* NOTREACHED */
8014 argc -= optind;
8015 argv += optind;
8017 if (argc < 1)
8018 usage_remove();
8020 cwd = getcwd(NULL, 0);
8021 if (cwd == NULL) {
8022 error = got_error_from_errno("getcwd");
8023 goto done;
8026 error = got_repo_pack_fds_open(&pack_fds);
8027 if (error != NULL)
8028 goto done;
8030 error = got_worktree_open(&worktree, cwd);
8031 if (error) {
8032 if (error->code == GOT_ERR_NOT_WORKTREE)
8033 error = wrap_not_worktree_error(error, "remove", cwd);
8034 goto done;
8037 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
8038 NULL, pack_fds);
8039 if (error)
8040 goto done;
8042 error = apply_unveil(got_repo_get_path(repo), 1,
8043 got_worktree_get_root_path(worktree));
8044 if (error)
8045 goto done;
8047 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
8048 if (error)
8049 goto done;
8051 if (!can_recurse) {
8052 char *ondisk_path;
8053 struct stat sb;
8054 TAILQ_FOREACH(pe, &paths, entry) {
8055 if (asprintf(&ondisk_path, "%s/%s",
8056 got_worktree_get_root_path(worktree),
8057 pe->path) == -1) {
8058 error = got_error_from_errno("asprintf");
8059 goto done;
8061 if (lstat(ondisk_path, &sb) == -1) {
8062 if (errno == ENOENT) {
8063 free(ondisk_path);
8064 continue;
8066 error = got_error_from_errno2("lstat",
8067 ondisk_path);
8068 free(ondisk_path);
8069 goto done;
8071 free(ondisk_path);
8072 if (S_ISDIR(sb.st_mode)) {
8073 error = got_error_msg(GOT_ERR_BAD_PATH,
8074 "removing directories requires -R option");
8075 goto done;
8080 error = got_worktree_schedule_delete(worktree, &paths,
8081 delete_local_mods, status_codes, print_remove_status, NULL,
8082 repo, keep_on_disk, ignore_missing_paths);
8083 done:
8084 if (repo) {
8085 const struct got_error *close_err = got_repo_close(repo);
8086 if (error == NULL)
8087 error = close_err;
8089 if (worktree)
8090 got_worktree_close(worktree);
8091 if (pack_fds) {
8092 const struct got_error *pack_err =
8093 got_repo_pack_fds_close(pack_fds);
8094 if (error == NULL)
8095 error = pack_err;
8097 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
8098 free(cwd);
8099 return error;
8102 __dead static void
8103 usage_patch(void)
8105 fprintf(stderr, "usage: %s patch [-nR] [-c commit] [-p strip-count] "
8106 "[patchfile]\n", getprogname());
8107 exit(1);
8110 static const struct got_error *
8111 patch_from_stdin(int *patchfd)
8113 const struct got_error *err = NULL;
8114 ssize_t r;
8115 char buf[BUFSIZ];
8116 sig_t sighup, sigint, sigquit;
8118 *patchfd = got_opentempfd();
8119 if (*patchfd == -1)
8120 return got_error_from_errno("got_opentempfd");
8122 sighup = signal(SIGHUP, SIG_DFL);
8123 sigint = signal(SIGINT, SIG_DFL);
8124 sigquit = signal(SIGQUIT, SIG_DFL);
8126 for (;;) {
8127 r = read(0, buf, sizeof(buf));
8128 if (r == -1) {
8129 err = got_error_from_errno("read");
8130 break;
8132 if (r == 0)
8133 break;
8134 if (write(*patchfd, buf, r) == -1) {
8135 err = got_error_from_errno("write");
8136 break;
8140 signal(SIGHUP, sighup);
8141 signal(SIGINT, sigint);
8142 signal(SIGQUIT, sigquit);
8144 if (err == NULL && lseek(*patchfd, 0, SEEK_SET) == -1)
8145 err = got_error_from_errno("lseek");
8147 if (err != NULL) {
8148 close(*patchfd);
8149 *patchfd = -1;
8152 return err;
8155 struct got_patch_progress_arg {
8156 int did_something;
8157 int conflicts;
8158 int rejects;
8161 static const struct got_error *
8162 patch_progress(void *arg, const char *old, const char *new,
8163 unsigned char status, const struct got_error *error, int old_from,
8164 int old_lines, int new_from, int new_lines, int offset,
8165 int ws_mangled, const struct got_error *hunk_err)
8167 const char *path = new == NULL ? old : new;
8168 struct got_patch_progress_arg *a = arg;
8170 while (*path == '/')
8171 path++;
8173 if (status != GOT_STATUS_NO_CHANGE &&
8174 status != 0 /* per-hunk progress */) {
8175 printf("%c %s\n", status, path);
8176 a->did_something = 1;
8179 if (hunk_err == NULL) {
8180 if (status == GOT_STATUS_CANNOT_UPDATE)
8181 a->rejects++;
8182 else if (status == GOT_STATUS_CONFLICT)
8183 a->conflicts++;
8186 if (error != NULL)
8187 fprintf(stderr, "%s: %s\n", getprogname(), error->msg);
8189 if (offset != 0 || hunk_err != NULL || ws_mangled) {
8190 printf("@@ -%d,%d +%d,%d @@ ", old_from,
8191 old_lines, new_from, new_lines);
8192 if (hunk_err != NULL)
8193 printf("%s\n", hunk_err->msg);
8194 else if (offset != 0)
8195 printf("applied with offset %d\n", offset);
8196 else
8197 printf("hunk contains mangled whitespace\n");
8200 return NULL;
8203 static void
8204 print_patch_progress_stats(struct got_patch_progress_arg *ppa)
8206 if (!ppa->did_something)
8207 return;
8209 if (ppa->conflicts > 0)
8210 printf("Files with merge conflicts: %d\n", ppa->conflicts);
8212 if (ppa->rejects > 0) {
8213 printf("Files where patch failed to apply: %d\n",
8214 ppa->rejects);
8218 static const struct got_error *
8219 cmd_patch(int argc, char *argv[])
8221 const struct got_error *error = NULL, *close_error = NULL;
8222 struct got_worktree *worktree = NULL;
8223 struct got_repository *repo = NULL;
8224 struct got_reflist_head refs;
8225 struct got_object_id *commit_id = NULL;
8226 const char *commit_id_str = NULL;
8227 struct stat sb;
8228 const char *errstr;
8229 char *cwd = NULL;
8230 int ch, nop = 0, strip = -1, reverse = 0;
8231 int patchfd;
8232 int *pack_fds = NULL;
8233 struct got_patch_progress_arg ppa;
8235 TAILQ_INIT(&refs);
8237 #ifndef PROFILE
8238 if (pledge("stdio rpath wpath cpath fattr proc exec sendfd flock "
8239 "unveil", NULL) == -1)
8240 err(1, "pledge");
8241 #endif
8243 while ((ch = getopt(argc, argv, "c:np:R")) != -1) {
8244 switch (ch) {
8245 case 'c':
8246 commit_id_str = optarg;
8247 break;
8248 case 'n':
8249 nop = 1;
8250 break;
8251 case 'p':
8252 strip = strtonum(optarg, 0, INT_MAX, &errstr);
8253 if (errstr != NULL)
8254 errx(1, "pathname strip count is %s: %s",
8255 errstr, optarg);
8256 break;
8257 case 'R':
8258 reverse = 1;
8259 break;
8260 default:
8261 usage_patch();
8262 /* NOTREACHED */
8266 argc -= optind;
8267 argv += optind;
8269 if (argc == 0) {
8270 error = patch_from_stdin(&patchfd);
8271 if (error)
8272 return error;
8273 } else if (argc == 1) {
8274 patchfd = open(argv[0], O_RDONLY);
8275 if (patchfd == -1) {
8276 error = got_error_from_errno2("open", argv[0]);
8277 return error;
8279 if (fstat(patchfd, &sb) == -1) {
8280 error = got_error_from_errno2("fstat", argv[0]);
8281 goto done;
8283 if (!S_ISREG(sb.st_mode)) {
8284 error = got_error_path(argv[0], GOT_ERR_BAD_FILETYPE);
8285 goto done;
8287 } else
8288 usage_patch();
8290 if ((cwd = getcwd(NULL, 0)) == NULL) {
8291 error = got_error_from_errno("getcwd");
8292 goto done;
8295 error = got_repo_pack_fds_open(&pack_fds);
8296 if (error != NULL)
8297 goto done;
8299 error = got_worktree_open(&worktree, cwd);
8300 if (error != NULL)
8301 goto done;
8303 const char *repo_path = got_worktree_get_repo_path(worktree);
8304 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
8305 if (error != NULL)
8306 goto done;
8308 error = apply_unveil(got_repo_get_path(repo), 0,
8309 got_worktree_get_root_path(worktree));
8310 if (error != NULL)
8311 goto done;
8313 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
8314 if (error)
8315 goto done;
8317 if (commit_id_str != NULL) {
8318 error = got_repo_match_object_id(&commit_id, NULL,
8319 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
8320 if (error)
8321 goto done;
8324 memset(&ppa, 0, sizeof(ppa));
8325 error = got_patch(patchfd, worktree, repo, nop, strip, reverse,
8326 commit_id, patch_progress, &ppa, check_cancelled, NULL);
8327 print_patch_progress_stats(&ppa);
8328 done:
8329 got_ref_list_free(&refs);
8330 free(commit_id);
8331 if (repo) {
8332 close_error = got_repo_close(repo);
8333 if (error == NULL)
8334 error = close_error;
8336 if (worktree != NULL) {
8337 close_error = got_worktree_close(worktree);
8338 if (error == NULL)
8339 error = close_error;
8341 if (pack_fds) {
8342 const struct got_error *pack_err =
8343 got_repo_pack_fds_close(pack_fds);
8344 if (error == NULL)
8345 error = pack_err;
8347 free(cwd);
8348 return error;
8351 __dead static void
8352 usage_revert(void)
8354 fprintf(stderr, "usage: %s revert [-pR] [-F response-script] path ...\n",
8355 getprogname());
8356 exit(1);
8359 static const struct got_error *
8360 revert_progress(void *arg, unsigned char status, const char *path)
8362 if (status == GOT_STATUS_UNVERSIONED)
8363 return NULL;
8365 while (path[0] == '/')
8366 path++;
8367 printf("%c %s\n", status, path);
8368 return NULL;
8371 struct choose_patch_arg {
8372 FILE *patch_script_file;
8373 const char *action;
8376 static const struct got_error *
8377 show_change(unsigned char status, const char *path, FILE *patch_file, int n,
8378 int nchanges, const char *action)
8380 const struct got_error *err;
8381 char *line = NULL;
8382 size_t linesize = 0;
8383 ssize_t linelen;
8385 switch (status) {
8386 case GOT_STATUS_ADD:
8387 printf("A %s\n%s this addition? [y/n] ", path, action);
8388 break;
8389 case GOT_STATUS_DELETE:
8390 printf("D %s\n%s this deletion? [y/n] ", path, action);
8391 break;
8392 case GOT_STATUS_MODIFY:
8393 if (fseek(patch_file, 0L, SEEK_SET) == -1)
8394 return got_error_from_errno("fseek");
8395 printf(GOT_COMMIT_SEP_STR);
8396 while ((linelen = getline(&line, &linesize, patch_file)) != -1)
8397 printf("%s", line);
8398 if (linelen == -1 && ferror(patch_file)) {
8399 err = got_error_from_errno("getline");
8400 free(line);
8401 return err;
8403 free(line);
8404 printf(GOT_COMMIT_SEP_STR);
8405 printf("M %s (change %d of %d)\n%s this change? [y/n/q] ",
8406 path, n, nchanges, action);
8407 break;
8408 default:
8409 return got_error_path(path, GOT_ERR_FILE_STATUS);
8412 fflush(stdout);
8413 return NULL;
8416 static const struct got_error *
8417 choose_patch(int *choice, void *arg, unsigned char status, const char *path,
8418 FILE *patch_file, int n, int nchanges)
8420 const struct got_error *err = NULL;
8421 char *line = NULL;
8422 size_t linesize = 0;
8423 ssize_t linelen;
8424 int resp = ' ';
8425 struct choose_patch_arg *a = arg;
8427 *choice = GOT_PATCH_CHOICE_NONE;
8429 if (a->patch_script_file) {
8430 char *nl;
8431 err = show_change(status, path, patch_file, n, nchanges,
8432 a->action);
8433 if (err)
8434 return err;
8435 linelen = getline(&line, &linesize, a->patch_script_file);
8436 if (linelen == -1) {
8437 if (ferror(a->patch_script_file))
8438 return got_error_from_errno("getline");
8439 return NULL;
8441 nl = strchr(line, '\n');
8442 if (nl)
8443 *nl = '\0';
8444 if (strcmp(line, "y") == 0) {
8445 *choice = GOT_PATCH_CHOICE_YES;
8446 printf("y\n");
8447 } else if (strcmp(line, "n") == 0) {
8448 *choice = GOT_PATCH_CHOICE_NO;
8449 printf("n\n");
8450 } else if (strcmp(line, "q") == 0 &&
8451 status == GOT_STATUS_MODIFY) {
8452 *choice = GOT_PATCH_CHOICE_QUIT;
8453 printf("q\n");
8454 } else
8455 printf("invalid response '%s'\n", line);
8456 free(line);
8457 return NULL;
8460 while (resp != 'y' && resp != 'n' && resp != 'q') {
8461 err = show_change(status, path, patch_file, n, nchanges,
8462 a->action);
8463 if (err)
8464 return err;
8465 resp = getchar();
8466 if (resp == '\n')
8467 resp = getchar();
8468 if (status == GOT_STATUS_MODIFY) {
8469 if (resp != 'y' && resp != 'n' && resp != 'q') {
8470 printf("invalid response '%c'\n", resp);
8471 resp = ' ';
8473 } else if (resp != 'y' && resp != 'n') {
8474 printf("invalid response '%c'\n", resp);
8475 resp = ' ';
8479 if (resp == 'y')
8480 *choice = GOT_PATCH_CHOICE_YES;
8481 else if (resp == 'n')
8482 *choice = GOT_PATCH_CHOICE_NO;
8483 else if (resp == 'q' && status == GOT_STATUS_MODIFY)
8484 *choice = GOT_PATCH_CHOICE_QUIT;
8486 return NULL;
8489 struct wt_commitable_path_arg {
8490 struct got_pathlist_head *commit_paths;
8491 int *has_changes;
8495 * Shortcut work tree status callback to determine if the set of paths scanned
8496 * has at least one versioned path that is being modified and, if not NULL, is
8497 * in the arg->commit_paths list. Set arg and return GOT_ERR_FILE_MODIFIED as
8498 * soon as a path is passed with a status that satisfies this criteria.
8500 static const struct got_error *
8501 worktree_has_commitable_path(void *arg, unsigned char status,
8502 unsigned char staged_status, const char *path,
8503 struct got_object_id *blob_id, struct got_object_id *staged_blob_id,
8504 struct got_object_id *commit_id, int dirfd, const char *de_name)
8506 struct wt_commitable_path_arg *a = arg;
8508 if (status == staged_status && (status == GOT_STATUS_DELETE))
8509 status = GOT_STATUS_NO_CHANGE;
8511 if (!(status == GOT_STATUS_NO_CHANGE ||
8512 status == GOT_STATUS_UNVERSIONED) ||
8513 staged_status != GOT_STATUS_NO_CHANGE) {
8514 if (a->commit_paths != NULL) {
8515 struct got_pathlist_entry *pe;
8517 TAILQ_FOREACH(pe, a->commit_paths, entry) {
8518 if (strncmp(path, pe->path,
8519 pe->path_len) == 0) {
8520 *a->has_changes = 1;
8521 break;
8524 } else
8525 *a->has_changes = 1;
8527 if (*a->has_changes)
8528 return got_error(GOT_ERR_FILE_MODIFIED);
8531 return NULL;
8535 * Check that the changeset of the commit identified by id is
8536 * comprised of at least one modified path that is being committed.
8538 static const struct got_error *
8539 commit_path_changed_in_worktree(struct wt_commitable_path_arg *wcpa,
8540 struct got_object_id *id, struct got_worktree *worktree,
8541 struct got_repository *repo)
8543 const struct got_error *err;
8544 struct got_pathlist_head paths;
8545 struct got_commit_object *commit = NULL, *pcommit = NULL;
8546 struct got_tree_object *tree = NULL, *ptree = NULL;
8547 struct got_object_qid *pid;
8549 TAILQ_INIT(&paths);
8551 err = got_object_open_as_commit(&commit, repo, id);
8552 if (err)
8553 goto done;
8555 err = got_object_open_as_tree(&tree, repo,
8556 got_object_commit_get_tree_id(commit));
8557 if (err)
8558 goto done;
8560 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
8561 if (pid != NULL) {
8562 err = got_object_open_as_commit(&pcommit, repo, &pid->id);
8563 if (err)
8564 goto done;
8566 err = got_object_open_as_tree(&ptree, repo,
8567 got_object_commit_get_tree_id(pcommit));
8568 if (err)
8569 goto done;
8572 err = got_diff_tree(ptree, tree, NULL, NULL, -1, -1, "", "", repo,
8573 got_diff_tree_collect_changed_paths, &paths, 0);
8574 if (err)
8575 goto done;
8577 err = got_worktree_status(worktree, &paths, repo, 0,
8578 worktree_has_commitable_path, wcpa, check_cancelled, NULL);
8579 if (err && err->code == GOT_ERR_FILE_MODIFIED) {
8581 * At least one changed path in the referenced commit is
8582 * modified in the work tree, that's all we need to know!
8584 err = NULL;
8587 done:
8588 got_pathlist_free(&paths, GOT_PATHLIST_FREE_ALL);
8589 if (commit)
8590 got_object_commit_close(commit);
8591 if (pcommit)
8592 got_object_commit_close(pcommit);
8593 if (tree)
8594 got_object_tree_close(tree);
8595 if (ptree)
8596 got_object_tree_close(ptree);
8597 return err;
8601 * Remove any "logmsg" reference comprised entirely of paths that have
8602 * been reverted in this work tree. If any path in the logmsg ref changeset
8603 * remains in a changed state in the worktree, do not remove the reference.
8605 static const struct got_error *
8606 rm_logmsg_ref(struct got_worktree *worktree, struct got_repository *repo)
8608 const struct got_error *err;
8609 struct got_reflist_head refs;
8610 struct got_reflist_entry *re;
8611 struct got_commit_object *commit = NULL;
8612 struct got_object_id *commit_id = NULL;
8613 struct wt_commitable_path_arg wcpa;
8614 char *uuidstr = NULL;
8616 TAILQ_INIT(&refs);
8618 err = got_worktree_get_uuid(&uuidstr, worktree);
8619 if (err)
8620 goto done;
8622 err = got_ref_list(&refs, repo, "refs/got/worktree",
8623 got_ref_cmp_by_name, repo);
8624 if (err)
8625 goto done;
8627 TAILQ_FOREACH(re, &refs, entry) {
8628 const char *refname;
8629 int has_changes = 0;
8631 refname = got_ref_get_name(re->ref);
8633 if (!strncmp(refname, GOT_WORKTREE_CHERRYPICK_REF_PREFIX,
8634 GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN))
8635 refname += GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN + 1;
8636 else if (!strncmp(refname, GOT_WORKTREE_BACKOUT_REF_PREFIX,
8637 GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN))
8638 refname += GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN + 1;
8639 else
8640 continue;
8642 if (strncmp(refname, uuidstr, GOT_WORKTREE_UUID_STRLEN) == 0)
8643 refname += GOT_WORKTREE_UUID_STRLEN + 1; /* skip '-' */
8644 else
8645 continue;
8647 err = got_repo_match_object_id(&commit_id, NULL, refname,
8648 GOT_OBJ_TYPE_COMMIT, NULL, repo);
8649 if (err)
8650 goto done;
8652 err = got_object_open_as_commit(&commit, repo, commit_id);
8653 if (err)
8654 goto done;
8656 wcpa.commit_paths = NULL;
8657 wcpa.has_changes = &has_changes;
8659 err = commit_path_changed_in_worktree(&wcpa, commit_id,
8660 worktree, repo);
8661 if (err)
8662 goto done;
8664 if (!has_changes) {
8665 err = got_ref_delete(re->ref, repo);
8666 if (err)
8667 goto done;
8670 got_object_commit_close(commit);
8671 commit = NULL;
8672 free(commit_id);
8673 commit_id = NULL;
8676 done:
8677 free(uuidstr);
8678 free(commit_id);
8679 got_ref_list_free(&refs);
8680 if (commit)
8681 got_object_commit_close(commit);
8682 return err;
8685 static const struct got_error *
8686 cmd_revert(int argc, char *argv[])
8688 const struct got_error *error = NULL;
8689 struct got_worktree *worktree = NULL;
8690 struct got_repository *repo = NULL;
8691 char *cwd = NULL, *path = NULL;
8692 struct got_pathlist_head paths;
8693 struct got_pathlist_entry *pe;
8694 int ch, can_recurse = 0, pflag = 0;
8695 FILE *patch_script_file = NULL;
8696 const char *patch_script_path = NULL;
8697 struct choose_patch_arg cpa;
8698 int *pack_fds = NULL;
8700 TAILQ_INIT(&paths);
8702 #ifndef PROFILE
8703 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
8704 "unveil", NULL) == -1)
8705 err(1, "pledge");
8706 #endif
8708 while ((ch = getopt(argc, argv, "F:pR")) != -1) {
8709 switch (ch) {
8710 case 'F':
8711 patch_script_path = optarg;
8712 break;
8713 case 'p':
8714 pflag = 1;
8715 break;
8716 case 'R':
8717 can_recurse = 1;
8718 break;
8719 default:
8720 usage_revert();
8721 /* NOTREACHED */
8725 argc -= optind;
8726 argv += optind;
8728 if (argc < 1)
8729 usage_revert();
8730 if (patch_script_path && !pflag)
8731 errx(1, "-F option can only be used together with -p option");
8733 cwd = getcwd(NULL, 0);
8734 if (cwd == NULL) {
8735 error = got_error_from_errno("getcwd");
8736 goto done;
8739 error = got_repo_pack_fds_open(&pack_fds);
8740 if (error != NULL)
8741 goto done;
8743 error = got_worktree_open(&worktree, cwd);
8744 if (error) {
8745 if (error->code == GOT_ERR_NOT_WORKTREE)
8746 error = wrap_not_worktree_error(error, "revert", cwd);
8747 goto done;
8750 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
8751 NULL, pack_fds);
8752 if (error != NULL)
8753 goto done;
8755 if (patch_script_path) {
8756 patch_script_file = fopen(patch_script_path, "re");
8757 if (patch_script_file == NULL) {
8758 error = got_error_from_errno2("fopen",
8759 patch_script_path);
8760 goto done;
8765 * XXX "c" perm needed on repo dir to delete merge references.
8767 error = apply_unveil(got_repo_get_path(repo), 0,
8768 got_worktree_get_root_path(worktree));
8769 if (error)
8770 goto done;
8772 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
8773 if (error)
8774 goto done;
8776 if (!can_recurse) {
8777 char *ondisk_path;
8778 struct stat sb;
8779 TAILQ_FOREACH(pe, &paths, entry) {
8780 if (asprintf(&ondisk_path, "%s/%s",
8781 got_worktree_get_root_path(worktree),
8782 pe->path) == -1) {
8783 error = got_error_from_errno("asprintf");
8784 goto done;
8786 if (lstat(ondisk_path, &sb) == -1) {
8787 if (errno == ENOENT) {
8788 free(ondisk_path);
8789 continue;
8791 error = got_error_from_errno2("lstat",
8792 ondisk_path);
8793 free(ondisk_path);
8794 goto done;
8796 free(ondisk_path);
8797 if (S_ISDIR(sb.st_mode)) {
8798 error = got_error_msg(GOT_ERR_BAD_PATH,
8799 "reverting directories requires -R option");
8800 goto done;
8805 cpa.patch_script_file = patch_script_file;
8806 cpa.action = "revert";
8807 error = got_worktree_revert(worktree, &paths, revert_progress, NULL,
8808 pflag ? choose_patch : NULL, &cpa, repo);
8810 error = rm_logmsg_ref(worktree, repo);
8811 done:
8812 if (patch_script_file && fclose(patch_script_file) == EOF &&
8813 error == NULL)
8814 error = got_error_from_errno2("fclose", patch_script_path);
8815 if (repo) {
8816 const struct got_error *close_err = got_repo_close(repo);
8817 if (error == NULL)
8818 error = close_err;
8820 if (worktree)
8821 got_worktree_close(worktree);
8822 if (pack_fds) {
8823 const struct got_error *pack_err =
8824 got_repo_pack_fds_close(pack_fds);
8825 if (error == NULL)
8826 error = pack_err;
8828 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
8829 free(path);
8830 free(cwd);
8831 return error;
8834 __dead static void
8835 usage_commit(void)
8837 fprintf(stderr, "usage: %s commit [-CNnS] [-A author] [-F path] "
8838 "[-m message] [path ...]\n", getprogname());
8839 exit(1);
8842 struct collect_commit_logmsg_arg {
8843 const char *cmdline_log;
8844 const char *prepared_log;
8845 const char *merged_log;
8846 int non_interactive;
8847 const char *editor;
8848 const char *worktree_path;
8849 const char *branch_name;
8850 const char *repo_path;
8851 char *logmsg_path;
8855 static const struct got_error *
8856 read_prepared_logmsg(char **logmsg, const char *path)
8858 const struct got_error *err = NULL;
8859 FILE *f = NULL;
8860 struct stat sb;
8861 size_t r;
8863 *logmsg = NULL;
8864 memset(&sb, 0, sizeof(sb));
8866 f = fopen(path, "re");
8867 if (f == NULL)
8868 return got_error_from_errno2("fopen", path);
8870 if (fstat(fileno(f), &sb) == -1) {
8871 err = got_error_from_errno2("fstat", path);
8872 goto done;
8874 if (sb.st_size == 0) {
8875 err = got_error(GOT_ERR_COMMIT_MSG_EMPTY);
8876 goto done;
8879 *logmsg = malloc(sb.st_size + 1);
8880 if (*logmsg == NULL) {
8881 err = got_error_from_errno("malloc");
8882 goto done;
8885 r = fread(*logmsg, 1, sb.st_size, f);
8886 if (r != sb.st_size) {
8887 if (ferror(f))
8888 err = got_error_from_errno2("fread", path);
8889 else
8890 err = got_error(GOT_ERR_IO);
8891 goto done;
8893 (*logmsg)[sb.st_size] = '\0';
8894 done:
8895 if (fclose(f) == EOF && err == NULL)
8896 err = got_error_from_errno2("fclose", path);
8897 if (err) {
8898 free(*logmsg);
8899 *logmsg = NULL;
8901 return err;
8904 static const struct got_error *
8905 collect_commit_logmsg(struct got_pathlist_head *commitable_paths,
8906 const char *diff_path, char **logmsg, void *arg)
8908 char *initial_content = NULL;
8909 struct got_pathlist_entry *pe;
8910 const struct got_error *err = NULL;
8911 char *template = NULL;
8912 char *prepared_msg = NULL, *merged_msg = NULL;
8913 struct collect_commit_logmsg_arg *a = arg;
8914 int initial_content_len;
8915 int fd = -1;
8916 size_t len;
8918 /* if a message was specified on the command line, just use it */
8919 if (a->cmdline_log != NULL && *a->cmdline_log != '\0') {
8920 len = strlen(a->cmdline_log) + 1;
8921 *logmsg = malloc(len + 1);
8922 if (*logmsg == NULL)
8923 return got_error_from_errno("malloc");
8924 strlcpy(*logmsg, a->cmdline_log, len);
8925 return NULL;
8926 } else if (a->prepared_log != NULL && a->non_interactive)
8927 return read_prepared_logmsg(logmsg, a->prepared_log);
8929 if (asprintf(&template, "%s/logmsg", a->worktree_path) == -1)
8930 return got_error_from_errno("asprintf");
8932 err = got_opentemp_named_fd(&a->logmsg_path, &fd, template, "");
8933 if (err)
8934 goto done;
8936 if (a->prepared_log) {
8937 err = read_prepared_logmsg(&prepared_msg, a->prepared_log);
8938 if (err)
8939 goto done;
8940 } else if (a->merged_log) {
8941 err = read_prepared_logmsg(&merged_msg, a->merged_log);
8942 if (err)
8943 goto done;
8946 initial_content_len = asprintf(&initial_content,
8947 "%s%s\n# changes to be committed on branch %s:\n",
8948 prepared_msg ? prepared_msg : "",
8949 merged_msg ? merged_msg : "", a->branch_name);
8950 if (initial_content_len == -1) {
8951 err = got_error_from_errno("asprintf");
8952 goto done;
8955 if (write(fd, initial_content, initial_content_len) == -1) {
8956 err = got_error_from_errno2("write", a->logmsg_path);
8957 goto done;
8960 TAILQ_FOREACH(pe, commitable_paths, entry) {
8961 struct got_commitable *ct = pe->data;
8962 dprintf(fd, "# %c %s\n",
8963 got_commitable_get_status(ct),
8964 got_commitable_get_path(ct));
8967 if (diff_path) {
8968 dprintf(fd, "# detailed changes can be viewed in %s\n",
8969 diff_path);
8972 if (close(fd) == -1) {
8973 err = got_error_from_errno2("close", a->logmsg_path);
8974 goto done;
8976 fd = -1;
8978 err = edit_logmsg(logmsg, a->editor, a->logmsg_path, initial_content,
8979 initial_content_len, a->prepared_log ? 0 : 1);
8980 done:
8981 free(initial_content);
8982 free(template);
8983 free(prepared_msg);
8984 free(merged_msg);
8986 if (fd != -1 && close(fd) == -1 && err == NULL)
8987 err = got_error_from_errno2("close", a->logmsg_path);
8989 /* Editor is done; we can now apply unveil(2) */
8990 if (err == NULL)
8991 err = apply_unveil(a->repo_path, 0, a->worktree_path);
8992 if (err) {
8993 free(*logmsg);
8994 *logmsg = NULL;
8996 return err;
8999 static const struct got_error *
9000 cat_logmsg(FILE *f, struct got_commit_object *commit, const char *idstr,
9001 const char *type, int has_content)
9003 const struct got_error *err = NULL;
9004 char *logmsg = NULL;
9006 err = got_object_commit_get_logmsg(&logmsg, commit);
9007 if (err)
9008 return err;
9010 if (fprintf(f, "%s# log message of %s commit %s:%s",
9011 has_content ? "\n" : "", type, idstr, logmsg) < 0)
9012 err = got_ferror(f, GOT_ERR_IO);
9014 free(logmsg);
9015 return err;
9019 * Lookup "logmsg" references of backed-out and cherrypicked commits
9020 * belonging to the current work tree. If found, and the worktree has
9021 * at least one modified file that was changed in the referenced commit,
9022 * add its log message to a new temporary file at *logmsg_path.
9023 * Add all refs found to matched_refs to be scheduled for removal on
9024 * successful commit.
9026 static const struct got_error *
9027 lookup_logmsg_ref(char **logmsg_path, struct got_pathlist_head *paths,
9028 struct got_reflist_head *matched_refs, struct got_worktree *worktree,
9029 struct got_repository *repo)
9031 const struct got_error *err;
9032 struct got_commit_object *commit = NULL;
9033 struct got_object_id *id = NULL;
9034 struct got_reflist_head refs;
9035 struct got_reflist_entry *re, *re_match;
9036 FILE *f = NULL;
9037 char *uuidstr = NULL;
9038 int added_logmsg = 0;
9040 TAILQ_INIT(&refs);
9042 *logmsg_path = NULL;
9044 err = got_worktree_get_uuid(&uuidstr, worktree);
9045 if (err)
9046 goto done;
9048 err = got_ref_list(&refs, repo, "refs/got/worktree",
9049 got_ref_cmp_by_name, repo);
9050 if (err)
9051 goto done;
9053 TAILQ_FOREACH(re, &refs, entry) {
9054 const char *refname, *type;
9055 struct wt_commitable_path_arg wcpa;
9056 int add_logmsg = 0;
9058 refname = got_ref_get_name(re->ref);
9060 if (strncmp(refname, GOT_WORKTREE_CHERRYPICK_REF_PREFIX,
9061 GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN) == 0) {
9062 refname += GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN + 1;
9063 type = "cherrypicked";
9064 } else if (strncmp(refname, GOT_WORKTREE_BACKOUT_REF_PREFIX,
9065 GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN) == 0) {
9066 refname += GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN + 1;
9067 type = "backed-out";
9068 } else
9069 continue;
9071 if (strncmp(refname, uuidstr, GOT_WORKTREE_UUID_STRLEN) == 0)
9072 refname += GOT_WORKTREE_UUID_STRLEN + 1; /* skip '-' */
9073 else
9074 continue;
9076 err = got_repo_match_object_id(&id, NULL, refname,
9077 GOT_OBJ_TYPE_COMMIT, NULL, repo);
9078 if (err)
9079 goto done;
9081 err = got_object_open_as_commit(&commit, repo, id);
9082 if (err)
9083 goto done;
9085 wcpa.commit_paths = paths;
9086 wcpa.has_changes = &add_logmsg;
9088 err = commit_path_changed_in_worktree(&wcpa, id,
9089 worktree, repo);
9090 if (err)
9091 goto done;
9093 if (add_logmsg) {
9094 if (f == NULL) {
9095 err = got_opentemp_named(logmsg_path, &f,
9096 "got-commit-logmsg", "");
9097 if (err)
9098 goto done;
9100 err = cat_logmsg(f, commit, refname, type,
9101 added_logmsg);
9102 if (err)
9103 goto done;
9104 if (!added_logmsg)
9105 ++added_logmsg;
9107 err = got_reflist_entry_dup(&re_match, re);
9108 if (err)
9109 goto done;
9110 TAILQ_INSERT_HEAD(matched_refs, re_match, entry);
9113 got_object_commit_close(commit);
9114 commit = NULL;
9115 free(id);
9116 id = NULL;
9119 done:
9120 free(id);
9121 free(uuidstr);
9122 got_ref_list_free(&refs);
9123 if (commit)
9124 got_object_commit_close(commit);
9125 if (f && fclose(f) == EOF && err == NULL)
9126 err = got_error_from_errno("fclose");
9127 if (!added_logmsg) {
9128 if (*logmsg_path && unlink(*logmsg_path) != 0 && err == NULL)
9129 err = got_error_from_errno2("unlink", *logmsg_path);
9130 *logmsg_path = NULL;
9132 return err;
9135 static const struct got_error *
9136 cmd_commit(int argc, char *argv[])
9138 const struct got_error *error = NULL;
9139 struct got_worktree *worktree = NULL;
9140 struct got_repository *repo = NULL;
9141 char *cwd = NULL, *id_str = NULL;
9142 struct got_object_id *id = NULL;
9143 const char *logmsg = NULL;
9144 char *prepared_logmsg = NULL, *merged_logmsg = NULL;
9145 struct collect_commit_logmsg_arg cl_arg;
9146 const char *author = NULL;
9147 char *gitconfig_path = NULL, *editor = NULL, *committer = NULL;
9148 int ch, rebase_in_progress, histedit_in_progress, preserve_logmsg = 0;
9149 int allow_bad_symlinks = 0, non_interactive = 0, merge_in_progress = 0;
9150 int show_diff = 1, commit_conflicts = 0;
9151 struct got_pathlist_head paths;
9152 struct got_reflist_head refs;
9153 struct got_reflist_entry *re;
9154 int *pack_fds = NULL;
9156 TAILQ_INIT(&refs);
9157 TAILQ_INIT(&paths);
9158 cl_arg.logmsg_path = NULL;
9160 #ifndef PROFILE
9161 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
9162 "unveil", NULL) == -1)
9163 err(1, "pledge");
9164 #endif
9166 while ((ch = getopt(argc, argv, "A:CF:m:NnS")) != -1) {
9167 switch (ch) {
9168 case 'A':
9169 author = optarg;
9170 error = valid_author(author);
9171 if (error)
9172 return error;
9173 break;
9174 case 'C':
9175 commit_conflicts = 1;
9176 break;
9177 case 'F':
9178 if (logmsg != NULL)
9179 option_conflict('F', 'm');
9180 prepared_logmsg = realpath(optarg, NULL);
9181 if (prepared_logmsg == NULL)
9182 return got_error_from_errno2("realpath",
9183 optarg);
9184 break;
9185 case 'm':
9186 if (prepared_logmsg)
9187 option_conflict('m', 'F');
9188 logmsg = optarg;
9189 break;
9190 case 'N':
9191 non_interactive = 1;
9192 break;
9193 case 'n':
9194 show_diff = 0;
9195 break;
9196 case 'S':
9197 allow_bad_symlinks = 1;
9198 break;
9199 default:
9200 usage_commit();
9201 /* NOTREACHED */
9205 argc -= optind;
9206 argv += optind;
9208 cwd = getcwd(NULL, 0);
9209 if (cwd == NULL) {
9210 error = got_error_from_errno("getcwd");
9211 goto done;
9214 error = got_repo_pack_fds_open(&pack_fds);
9215 if (error != NULL)
9216 goto done;
9218 error = got_worktree_open(&worktree, cwd);
9219 if (error) {
9220 if (error->code == GOT_ERR_NOT_WORKTREE)
9221 error = wrap_not_worktree_error(error, "commit", cwd);
9222 goto done;
9225 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
9226 if (error)
9227 goto done;
9228 if (rebase_in_progress) {
9229 error = got_error(GOT_ERR_REBASING);
9230 goto done;
9233 error = got_worktree_histedit_in_progress(&histedit_in_progress,
9234 worktree);
9235 if (error)
9236 goto done;
9238 error = get_gitconfig_path(&gitconfig_path);
9239 if (error)
9240 goto done;
9241 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
9242 gitconfig_path, pack_fds);
9243 if (error != NULL)
9244 goto done;
9246 error = got_worktree_merge_in_progress(&merge_in_progress, worktree, repo);
9247 if (error)
9248 goto done;
9249 if (merge_in_progress) {
9250 error = got_error(GOT_ERR_MERGE_BUSY);
9251 goto done;
9254 error = get_author(&committer, repo, worktree);
9255 if (error)
9256 goto done;
9258 if (author == NULL)
9259 author = committer;
9262 * unveil(2) traverses exec(2); if an editor is used we have
9263 * to apply unveil after the log message has been written.
9265 if (logmsg == NULL || strlen(logmsg) == 0)
9266 error = get_editor(&editor);
9267 else
9268 error = apply_unveil(got_repo_get_path(repo), 0,
9269 got_worktree_get_root_path(worktree));
9270 if (error)
9271 goto done;
9273 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
9274 if (error)
9275 goto done;
9277 if (prepared_logmsg == NULL) {
9278 error = lookup_logmsg_ref(&merged_logmsg,
9279 argc > 0 ? &paths : NULL, &refs, worktree, repo);
9280 if (error)
9281 goto done;
9284 cl_arg.editor = editor;
9285 cl_arg.cmdline_log = logmsg;
9286 cl_arg.prepared_log = prepared_logmsg;
9287 cl_arg.merged_log = merged_logmsg;
9288 cl_arg.non_interactive = non_interactive;
9289 cl_arg.worktree_path = got_worktree_get_root_path(worktree);
9290 cl_arg.branch_name = got_worktree_get_head_ref_name(worktree);
9291 if (!histedit_in_progress) {
9292 if (strncmp(cl_arg.branch_name, "refs/heads/", 11) != 0) {
9293 error = got_error(GOT_ERR_COMMIT_BRANCH);
9294 goto done;
9296 cl_arg.branch_name += 11;
9298 cl_arg.repo_path = got_repo_get_path(repo);
9299 error = got_worktree_commit(&id, worktree, &paths, author, committer,
9300 allow_bad_symlinks, show_diff, commit_conflicts,
9301 collect_commit_logmsg, &cl_arg, print_status, NULL, repo);
9302 if (error) {
9303 if (error->code != GOT_ERR_COMMIT_MSG_EMPTY &&
9304 cl_arg.logmsg_path != NULL)
9305 preserve_logmsg = 1;
9306 goto done;
9309 error = got_object_id_str(&id_str, id);
9310 if (error)
9311 goto done;
9312 printf("Created commit %s\n", id_str);
9314 TAILQ_FOREACH(re, &refs, entry) {
9315 error = got_ref_delete(re->ref, repo);
9316 if (error)
9317 goto done;
9320 done:
9321 if (preserve_logmsg) {
9322 fprintf(stderr, "%s: log message preserved in %s\n",
9323 getprogname(), cl_arg.logmsg_path);
9324 } else if (cl_arg.logmsg_path && unlink(cl_arg.logmsg_path) == -1 &&
9325 error == NULL)
9326 error = got_error_from_errno2("unlink", cl_arg.logmsg_path);
9327 free(cl_arg.logmsg_path);
9328 if (merged_logmsg && unlink(merged_logmsg) == -1 && error == NULL)
9329 error = got_error_from_errno2("unlink", merged_logmsg);
9330 free(merged_logmsg);
9331 if (repo) {
9332 const struct got_error *close_err = got_repo_close(repo);
9333 if (error == NULL)
9334 error = close_err;
9336 if (worktree)
9337 got_worktree_close(worktree);
9338 if (pack_fds) {
9339 const struct got_error *pack_err =
9340 got_repo_pack_fds_close(pack_fds);
9341 if (error == NULL)
9342 error = pack_err;
9344 got_ref_list_free(&refs);
9345 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
9346 free(cwd);
9347 free(id_str);
9348 free(gitconfig_path);
9349 free(editor);
9350 free(committer);
9351 free(prepared_logmsg);
9352 return error;
9355 __dead static void
9356 usage_send(void)
9358 fprintf(stderr, "usage: %s send [-afqTv] [-b branch] [-d branch] "
9359 "[-r repository-path] [-t tag] [remote-repository]\n",
9360 getprogname());
9361 exit(1);
9364 static void
9365 print_load_info(int print_colored, int print_found, int print_trees,
9366 int ncolored, int nfound, int ntrees)
9368 if (print_colored) {
9369 printf("%d commit%s colored", ncolored,
9370 ncolored == 1 ? "" : "s");
9372 if (print_found) {
9373 printf("%s%d object%s found",
9374 ncolored > 0 ? "; " : "",
9375 nfound, nfound == 1 ? "" : "s");
9377 if (print_trees) {
9378 printf("; %d tree%s scanned", ntrees,
9379 ntrees == 1 ? "" : "s");
9383 struct got_send_progress_arg {
9384 char last_scaled_packsize[FMT_SCALED_STRSIZE];
9385 int verbosity;
9386 int last_ncolored;
9387 int last_nfound;
9388 int last_ntrees;
9389 int loading_done;
9390 int last_ncommits;
9391 int last_nobj_total;
9392 int last_p_deltify;
9393 int last_p_written;
9394 int last_p_sent;
9395 int printed_something;
9396 int sent_something;
9397 struct got_pathlist_head *delete_branches;
9400 static const struct got_error *
9401 send_progress(void *arg, int ncolored, int nfound, int ntrees,
9402 off_t packfile_size, int ncommits, int nobj_total, int nobj_deltify,
9403 int nobj_written, off_t bytes_sent, const char *refname,
9404 const char *errmsg, int success)
9406 struct got_send_progress_arg *a = arg;
9407 char scaled_packsize[FMT_SCALED_STRSIZE];
9408 char scaled_sent[FMT_SCALED_STRSIZE];
9409 int p_deltify = 0, p_written = 0, p_sent = 0;
9410 int print_colored = 0, print_found = 0, print_trees = 0;
9411 int print_searching = 0, print_total = 0;
9412 int print_deltify = 0, print_written = 0, print_sent = 0;
9414 if (a->verbosity < 0)
9415 return NULL;
9417 if (refname) {
9418 const char *status = success ? "accepted" : "rejected";
9420 if (success) {
9421 struct got_pathlist_entry *pe;
9422 TAILQ_FOREACH(pe, a->delete_branches, entry) {
9423 const char *branchname = pe->path;
9424 if (got_path_cmp(branchname, refname,
9425 strlen(branchname), strlen(refname)) == 0) {
9426 status = "deleted";
9427 a->sent_something = 1;
9428 break;
9433 if (a->printed_something)
9434 putchar('\n');
9435 printf("Server has %s %s", status, refname);
9436 if (errmsg)
9437 printf(": %s", errmsg);
9438 a->printed_something = 1;
9439 return NULL;
9442 if (a->last_ncolored != ncolored) {
9443 print_colored = 1;
9444 a->last_ncolored = ncolored;
9447 if (a->last_nfound != nfound) {
9448 print_colored = 1;
9449 print_found = 1;
9450 a->last_nfound = nfound;
9453 if (a->last_ntrees != ntrees) {
9454 print_colored = 1;
9455 print_found = 1;
9456 print_trees = 1;
9457 a->last_ntrees = ntrees;
9460 if ((print_colored || print_found || print_trees) &&
9461 !a->loading_done) {
9462 printf("\r");
9463 print_load_info(print_colored, print_found, print_trees,
9464 ncolored, nfound, ntrees);
9465 a->printed_something = 1;
9466 fflush(stdout);
9467 return NULL;
9468 } else if (!a->loading_done) {
9469 printf("\r");
9470 print_load_info(1, 1, 1, ncolored, nfound, ntrees);
9471 printf("\n");
9472 a->loading_done = 1;
9475 if (fmt_scaled(packfile_size, scaled_packsize) == -1)
9476 return got_error_from_errno("fmt_scaled");
9477 if (fmt_scaled(bytes_sent, scaled_sent) == -1)
9478 return got_error_from_errno("fmt_scaled");
9480 if (a->last_ncommits != ncommits) {
9481 print_searching = 1;
9482 a->last_ncommits = ncommits;
9485 if (a->last_nobj_total != nobj_total) {
9486 print_searching = 1;
9487 print_total = 1;
9488 a->last_nobj_total = nobj_total;
9491 if (packfile_size > 0 && (a->last_scaled_packsize[0] == '\0' ||
9492 strcmp(scaled_packsize, a->last_scaled_packsize)) != 0) {
9493 if (strlcpy(a->last_scaled_packsize, scaled_packsize,
9494 FMT_SCALED_STRSIZE) >= FMT_SCALED_STRSIZE)
9495 return got_error(GOT_ERR_NO_SPACE);
9498 if (nobj_deltify > 0 || nobj_written > 0) {
9499 if (nobj_deltify > 0) {
9500 p_deltify = (nobj_deltify * 100) / nobj_total;
9501 if (p_deltify != a->last_p_deltify) {
9502 a->last_p_deltify = p_deltify;
9503 print_searching = 1;
9504 print_total = 1;
9505 print_deltify = 1;
9508 if (nobj_written > 0) {
9509 p_written = (nobj_written * 100) / nobj_total;
9510 if (p_written != a->last_p_written) {
9511 a->last_p_written = p_written;
9512 print_searching = 1;
9513 print_total = 1;
9514 print_deltify = 1;
9515 print_written = 1;
9520 if (bytes_sent > 0) {
9521 p_sent = (bytes_sent * 100) / packfile_size;
9522 if (p_sent != a->last_p_sent) {
9523 a->last_p_sent = p_sent;
9524 print_searching = 1;
9525 print_total = 1;
9526 print_deltify = 1;
9527 print_written = 1;
9528 print_sent = 1;
9530 a->sent_something = 1;
9533 if (print_searching || print_total || print_deltify || print_written ||
9534 print_sent)
9535 printf("\r");
9536 if (print_searching)
9537 printf("packing %d reference%s", ncommits,
9538 ncommits == 1 ? "" : "s");
9539 if (print_total)
9540 printf("; %d object%s", nobj_total,
9541 nobj_total == 1 ? "" : "s");
9542 if (print_deltify)
9543 printf("; deltify: %d%%", p_deltify);
9544 if (print_sent)
9545 printf("; uploading pack: %*s %d%%", FMT_SCALED_STRSIZE - 2,
9546 scaled_packsize, p_sent);
9547 else if (print_written)
9548 printf("; writing pack: %*s %d%%", FMT_SCALED_STRSIZE - 2,
9549 scaled_packsize, p_written);
9550 if (print_searching || print_total || print_deltify ||
9551 print_written || print_sent) {
9552 a->printed_something = 1;
9553 fflush(stdout);
9555 return NULL;
9558 static const struct got_error *
9559 cmd_send(int argc, char *argv[])
9561 const struct got_error *error = NULL;
9562 char *cwd = NULL, *repo_path = NULL;
9563 const char *remote_name;
9564 char *proto = NULL, *host = NULL, *port = NULL;
9565 char *repo_name = NULL, *server_path = NULL;
9566 const struct got_remote_repo *remotes, *remote = NULL;
9567 int nremotes, nbranches = 0, ndelete_branches = 0;
9568 struct got_repository *repo = NULL;
9569 struct got_worktree *worktree = NULL;
9570 const struct got_gotconfig *repo_conf = NULL, *worktree_conf = NULL;
9571 struct got_pathlist_head branches;
9572 struct got_pathlist_head tags;
9573 struct got_reflist_head all_branches;
9574 struct got_reflist_head all_tags;
9575 struct got_pathlist_head delete_args;
9576 struct got_pathlist_head delete_branches;
9577 struct got_reflist_entry *re;
9578 struct got_pathlist_entry *pe;
9579 int i, ch, sendfd = -1, sendstatus;
9580 pid_t sendpid = -1;
9581 struct got_send_progress_arg spa;
9582 int verbosity = 0, overwrite_refs = 0;
9583 int send_all_branches = 0, send_all_tags = 0;
9584 struct got_reference *ref = NULL;
9585 int *pack_fds = NULL;
9587 TAILQ_INIT(&branches);
9588 TAILQ_INIT(&tags);
9589 TAILQ_INIT(&all_branches);
9590 TAILQ_INIT(&all_tags);
9591 TAILQ_INIT(&delete_args);
9592 TAILQ_INIT(&delete_branches);
9594 while ((ch = getopt(argc, argv, "ab:d:fqr:Tt:v")) != -1) {
9595 switch (ch) {
9596 case 'a':
9597 send_all_branches = 1;
9598 break;
9599 case 'b':
9600 error = got_pathlist_append(&branches, optarg, NULL);
9601 if (error)
9602 return error;
9603 nbranches++;
9604 break;
9605 case 'd':
9606 error = got_pathlist_append(&delete_args, optarg, NULL);
9607 if (error)
9608 return error;
9609 break;
9610 case 'f':
9611 overwrite_refs = 1;
9612 break;
9613 case 'q':
9614 verbosity = -1;
9615 break;
9616 case 'r':
9617 repo_path = realpath(optarg, NULL);
9618 if (repo_path == NULL)
9619 return got_error_from_errno2("realpath",
9620 optarg);
9621 got_path_strip_trailing_slashes(repo_path);
9622 break;
9623 case 'T':
9624 send_all_tags = 1;
9625 break;
9626 case 't':
9627 error = got_pathlist_append(&tags, optarg, NULL);
9628 if (error)
9629 return error;
9630 break;
9631 case 'v':
9632 if (verbosity < 0)
9633 verbosity = 0;
9634 else if (verbosity < 3)
9635 verbosity++;
9636 break;
9637 default:
9638 usage_send();
9639 /* NOTREACHED */
9642 argc -= optind;
9643 argv += optind;
9645 if (send_all_branches && !TAILQ_EMPTY(&branches))
9646 option_conflict('a', 'b');
9647 if (send_all_tags && !TAILQ_EMPTY(&tags))
9648 option_conflict('T', 't');
9651 if (argc == 0)
9652 remote_name = GOT_SEND_DEFAULT_REMOTE_NAME;
9653 else if (argc == 1)
9654 remote_name = argv[0];
9655 else
9656 usage_send();
9658 cwd = getcwd(NULL, 0);
9659 if (cwd == NULL) {
9660 error = got_error_from_errno("getcwd");
9661 goto done;
9664 error = got_repo_pack_fds_open(&pack_fds);
9665 if (error != NULL)
9666 goto done;
9668 if (repo_path == NULL) {
9669 error = got_worktree_open(&worktree, cwd);
9670 if (error && error->code != GOT_ERR_NOT_WORKTREE)
9671 goto done;
9672 else
9673 error = NULL;
9674 if (worktree) {
9675 repo_path =
9676 strdup(got_worktree_get_repo_path(worktree));
9677 if (repo_path == NULL)
9678 error = got_error_from_errno("strdup");
9679 if (error)
9680 goto done;
9681 } else {
9682 repo_path = strdup(cwd);
9683 if (repo_path == NULL) {
9684 error = got_error_from_errno("strdup");
9685 goto done;
9690 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
9691 if (error)
9692 goto done;
9694 if (worktree) {
9695 worktree_conf = got_worktree_get_gotconfig(worktree);
9696 if (worktree_conf) {
9697 got_gotconfig_get_remotes(&nremotes, &remotes,
9698 worktree_conf);
9699 for (i = 0; i < nremotes; i++) {
9700 if (strcmp(remotes[i].name, remote_name) == 0) {
9701 remote = &remotes[i];
9702 break;
9707 if (remote == NULL) {
9708 repo_conf = got_repo_get_gotconfig(repo);
9709 if (repo_conf) {
9710 got_gotconfig_get_remotes(&nremotes, &remotes,
9711 repo_conf);
9712 for (i = 0; i < nremotes; i++) {
9713 if (strcmp(remotes[i].name, remote_name) == 0) {
9714 remote = &remotes[i];
9715 break;
9720 if (remote == NULL) {
9721 got_repo_get_gitconfig_remotes(&nremotes, &remotes, repo);
9722 for (i = 0; i < nremotes; i++) {
9723 if (strcmp(remotes[i].name, remote_name) == 0) {
9724 remote = &remotes[i];
9725 break;
9729 if (remote == NULL) {
9730 error = got_error_path(remote_name, GOT_ERR_NO_REMOTE);
9731 goto done;
9734 error = got_dial_parse_uri(&proto, &host, &port, &server_path,
9735 &repo_name, remote->send_url);
9736 if (error)
9737 goto done;
9739 if (strcmp(proto, "git") == 0) {
9740 #ifndef PROFILE
9741 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
9742 "sendfd dns inet unveil", NULL) == -1)
9743 err(1, "pledge");
9744 #endif
9745 } else if (strcmp(proto, "git+ssh") == 0 ||
9746 strcmp(proto, "ssh") == 0) {
9747 #ifndef PROFILE
9748 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
9749 "sendfd unveil", NULL) == -1)
9750 err(1, "pledge");
9751 #endif
9752 } else if (strcmp(proto, "http") == 0 ||
9753 strcmp(proto, "git+http") == 0) {
9754 error = got_error_path(proto, GOT_ERR_NOT_IMPL);
9755 goto done;
9756 } else {
9757 error = got_error_path(proto, GOT_ERR_BAD_PROTO);
9758 goto done;
9761 error = got_dial_apply_unveil(proto);
9762 if (error)
9763 goto done;
9765 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
9766 if (error)
9767 goto done;
9769 if (send_all_branches) {
9770 error = got_ref_list(&all_branches, repo, "refs/heads",
9771 got_ref_cmp_by_name, NULL);
9772 if (error)
9773 goto done;
9774 TAILQ_FOREACH(re, &all_branches, entry) {
9775 const char *branchname = got_ref_get_name(re->ref);
9776 error = got_pathlist_append(&branches,
9777 branchname, NULL);
9778 if (error)
9779 goto done;
9780 nbranches++;
9782 } else if (nbranches == 0) {
9783 for (i = 0; i < remote->nsend_branches; i++) {
9784 error = got_pathlist_append(&branches,
9785 remote->send_branches[i], NULL);
9786 if (error)
9787 goto done;
9791 if (send_all_tags) {
9792 error = got_ref_list(&all_tags, repo, "refs/tags",
9793 got_ref_cmp_by_name, NULL);
9794 if (error)
9795 goto done;
9796 TAILQ_FOREACH(re, &all_tags, entry) {
9797 const char *tagname = got_ref_get_name(re->ref);
9798 error = got_pathlist_append(&tags,
9799 tagname, NULL);
9800 if (error)
9801 goto done;
9806 * To prevent accidents only branches in refs/heads/ can be deleted
9807 * with 'got send -d'.
9808 * Deleting anything else requires local repository access or Git.
9810 TAILQ_FOREACH(pe, &delete_args, entry) {
9811 const char *branchname = pe->path;
9812 char *s;
9813 struct got_pathlist_entry *new;
9814 if (strncmp(branchname, "refs/heads/", 11) == 0) {
9815 s = strdup(branchname);
9816 if (s == NULL) {
9817 error = got_error_from_errno("strdup");
9818 goto done;
9820 } else {
9821 if (asprintf(&s, "refs/heads/%s", branchname) == -1) {
9822 error = got_error_from_errno("asprintf");
9823 goto done;
9826 error = got_pathlist_insert(&new, &delete_branches, s, NULL);
9827 if (error || new == NULL /* duplicate */)
9828 free(s);
9829 if (error)
9830 goto done;
9831 ndelete_branches++;
9834 if (nbranches == 0 && ndelete_branches == 0) {
9835 struct got_reference *head_ref;
9836 if (worktree)
9837 error = got_ref_open(&head_ref, repo,
9838 got_worktree_get_head_ref_name(worktree), 0);
9839 else
9840 error = got_ref_open(&head_ref, repo, GOT_REF_HEAD, 0);
9841 if (error)
9842 goto done;
9843 if (got_ref_is_symbolic(head_ref)) {
9844 error = got_ref_resolve_symbolic(&ref, repo, head_ref);
9845 got_ref_close(head_ref);
9846 if (error)
9847 goto done;
9848 } else
9849 ref = head_ref;
9850 error = got_pathlist_append(&branches, got_ref_get_name(ref),
9851 NULL);
9852 if (error)
9853 goto done;
9854 nbranches++;
9857 if (verbosity >= 0) {
9858 printf("Connecting to \"%s\" %s://%s%s%s%s%s\n",
9859 remote->name, proto, host,
9860 port ? ":" : "", port ? port : "",
9861 *server_path == '/' ? "" : "/", server_path);
9864 error = got_send_connect(&sendpid, &sendfd, proto, host, port,
9865 server_path, verbosity);
9866 if (error)
9867 goto done;
9869 memset(&spa, 0, sizeof(spa));
9870 spa.last_scaled_packsize[0] = '\0';
9871 spa.last_p_deltify = -1;
9872 spa.last_p_written = -1;
9873 spa.verbosity = verbosity;
9874 spa.delete_branches = &delete_branches;
9875 error = got_send_pack(remote_name, &branches, &tags, &delete_branches,
9876 verbosity, overwrite_refs, sendfd, repo, send_progress, &spa,
9877 check_cancelled, NULL);
9878 if (spa.printed_something)
9879 putchar('\n');
9880 if (error)
9881 goto done;
9882 if (!spa.sent_something && verbosity >= 0)
9883 printf("Already up-to-date\n");
9884 done:
9885 if (sendpid > 0) {
9886 if (kill(sendpid, SIGTERM) == -1)
9887 error = got_error_from_errno("kill");
9888 if (waitpid(sendpid, &sendstatus, 0) == -1 && error == NULL)
9889 error = got_error_from_errno("waitpid");
9891 if (sendfd != -1 && close(sendfd) == -1 && error == NULL)
9892 error = got_error_from_errno("close");
9893 if (repo) {
9894 const struct got_error *close_err = got_repo_close(repo);
9895 if (error == NULL)
9896 error = close_err;
9898 if (worktree)
9899 got_worktree_close(worktree);
9900 if (pack_fds) {
9901 const struct got_error *pack_err =
9902 got_repo_pack_fds_close(pack_fds);
9903 if (error == NULL)
9904 error = pack_err;
9906 if (ref)
9907 got_ref_close(ref);
9908 got_pathlist_free(&branches, GOT_PATHLIST_FREE_NONE);
9909 got_pathlist_free(&tags, GOT_PATHLIST_FREE_NONE);
9910 got_ref_list_free(&all_branches);
9911 got_ref_list_free(&all_tags);
9912 got_pathlist_free(&delete_args, GOT_PATHLIST_FREE_NONE);
9913 got_pathlist_free(&delete_branches, GOT_PATHLIST_FREE_PATH);
9914 free(cwd);
9915 free(repo_path);
9916 free(proto);
9917 free(host);
9918 free(port);
9919 free(server_path);
9920 free(repo_name);
9921 return error;
9925 * Print and if delete is set delete all ref_prefix references.
9926 * If wanted_ref is not NULL, only print or delete this reference.
9928 static const struct got_error *
9929 process_logmsg_refs(const char *ref_prefix, size_t prefix_len,
9930 const char *wanted_ref, int delete, struct got_worktree *worktree,
9931 struct got_repository *repo)
9933 const struct got_error *err;
9934 struct got_pathlist_head paths;
9935 struct got_reflist_head refs;
9936 struct got_reflist_entry *re;
9937 struct got_reflist_object_id_map *refs_idmap = NULL;
9938 struct got_commit_object *commit = NULL;
9939 struct got_object_id *id = NULL;
9940 const char *header_prefix;
9941 char *uuidstr = NULL;
9942 int found = 0;
9944 TAILQ_INIT(&refs);
9945 TAILQ_INIT(&paths);
9947 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, repo);
9948 if (err)
9949 goto done;
9951 err = got_reflist_object_id_map_create(&refs_idmap, &refs, repo);
9952 if (err)
9953 goto done;
9955 if (worktree != NULL) {
9956 err = got_worktree_get_uuid(&uuidstr, worktree);
9957 if (err)
9958 goto done;
9961 if (wanted_ref) {
9962 if (strncmp(wanted_ref, "refs/heads/", 11) == 0)
9963 wanted_ref += 11;
9966 if (strcmp(ref_prefix, GOT_WORKTREE_BACKOUT_REF_PREFIX) == 0)
9967 header_prefix = "backout";
9968 else
9969 header_prefix = "cherrypick";
9971 TAILQ_FOREACH(re, &refs, entry) {
9972 const char *refname, *wt;
9974 refname = got_ref_get_name(re->ref);
9976 err = check_cancelled(NULL);
9977 if (err)
9978 goto done;
9980 if (strncmp(refname, ref_prefix, prefix_len) == 0)
9981 refname += prefix_len + 1; /* skip '-' delimiter */
9982 else
9983 continue;
9985 wt = refname;
9987 if (worktree == NULL || strncmp(refname, uuidstr,
9988 GOT_WORKTREE_UUID_STRLEN) == 0)
9989 refname += GOT_WORKTREE_UUID_STRLEN + 1; /* skip '-' */
9990 else
9991 continue;
9993 err = got_repo_match_object_id(&id, NULL, refname,
9994 GOT_OBJ_TYPE_COMMIT, NULL, repo);
9995 if (err)
9996 goto done;
9998 err = got_object_open_as_commit(&commit, repo, id);
9999 if (err)
10000 goto done;
10002 if (wanted_ref)
10003 found = strncmp(wanted_ref, refname,
10004 strlen(wanted_ref)) == 0;
10005 if (wanted_ref && !found) {
10006 struct got_reflist_head *ci_refs;
10008 ci_refs = got_reflist_object_id_map_lookup(refs_idmap,
10009 id);
10011 if (ci_refs) {
10012 char *refs_str = NULL;
10013 char const *r = NULL;
10015 err = build_refs_str(&refs_str, ci_refs, id,
10016 repo, 1);
10017 if (err)
10018 goto done;
10020 r = refs_str;
10021 while (r) {
10022 if (strncmp(r, wanted_ref,
10023 strlen(wanted_ref)) == 0) {
10024 found = 1;
10025 break;
10027 r = strchr(r, ' ');
10028 if (r)
10029 ++r;
10031 free(refs_str);
10035 if (wanted_ref == NULL || found) {
10036 if (delete) {
10037 err = got_ref_delete(re->ref, repo);
10038 if (err)
10039 goto done;
10040 printf("Deleted: ");
10041 err = print_commit_oneline(commit, id, repo,
10042 refs_idmap);
10043 } else {
10045 * Print paths modified by commit to help
10046 * associate commits with worktree changes.
10048 err = get_changed_paths(&paths, commit,
10049 repo, NULL);
10050 if (err)
10051 goto done;
10053 err = print_commit(commit, id, repo, NULL,
10054 &paths, NULL, 0, 0, refs_idmap, NULL,
10055 header_prefix);
10056 got_pathlist_free(&paths,
10057 GOT_PATHLIST_FREE_ALL);
10059 if (worktree == NULL)
10060 printf("work tree: %.*s\n\n",
10061 GOT_WORKTREE_UUID_STRLEN, wt);
10063 if (err || found)
10064 goto done;
10067 got_object_commit_close(commit);
10068 commit = NULL;
10069 free(id);
10070 id = NULL;
10073 if (wanted_ref != NULL && !found)
10074 err = got_error_fmt(GOT_ERR_NOT_REF, "%s", wanted_ref);
10076 done:
10077 free(id);
10078 free(uuidstr);
10079 got_ref_list_free(&refs);
10080 got_pathlist_free(&paths, GOT_PATHLIST_FREE_ALL);
10081 if (refs_idmap)
10082 got_reflist_object_id_map_free(refs_idmap);
10083 if (commit)
10084 got_object_commit_close(commit);
10085 return err;
10089 * Create new temp "logmsg" ref of the backed-out or cherrypicked commit
10090 * identified by id for log messages to prepopulate the editor on commit.
10092 static const struct got_error *
10093 logmsg_ref(struct got_object_id *id, const char *prefix,
10094 struct got_worktree *worktree, struct got_repository *repo)
10096 const struct got_error *err = NULL;
10097 char *idstr, *ref = NULL, *refname = NULL;
10098 int histedit_in_progress;
10099 int rebase_in_progress, merge_in_progress;
10102 * Silenty refuse to create merge reference if any histedit, merge,
10103 * or rebase operation is in progress.
10105 err = got_worktree_histedit_in_progress(&histedit_in_progress,
10106 worktree);
10107 if (err)
10108 return err;
10109 if (histedit_in_progress)
10110 return NULL;
10112 err = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
10113 if (err)
10114 return err;
10115 if (rebase_in_progress)
10116 return NULL;
10118 err = got_worktree_merge_in_progress(&merge_in_progress, worktree,
10119 repo);
10120 if (err)
10121 return err;
10122 if (merge_in_progress)
10123 return NULL;
10125 err = got_object_id_str(&idstr, id);
10126 if (err)
10127 return err;
10129 err = got_worktree_get_logmsg_ref_name(&refname, worktree, prefix);
10130 if (err)
10131 goto done;
10133 if (asprintf(&ref, "%s-%s", refname, idstr) == -1) {
10134 err = got_error_from_errno("asprintf");
10135 goto done;
10138 err = create_ref(ref, got_worktree_get_base_commit_id(worktree),
10139 -1, repo);
10140 done:
10141 free(ref);
10142 free(idstr);
10143 free(refname);
10144 return err;
10147 __dead static void
10148 usage_cherrypick(void)
10150 fprintf(stderr, "usage: %s cherrypick [-lX] [commit-id]\n",
10151 getprogname());
10152 exit(1);
10155 static const struct got_error *
10156 cmd_cherrypick(int argc, char *argv[])
10158 const struct got_error *error = NULL;
10159 struct got_worktree *worktree = NULL;
10160 struct got_repository *repo = NULL;
10161 char *cwd = NULL, *commit_id_str = NULL;
10162 struct got_object_id *commit_id = NULL;
10163 struct got_commit_object *commit = NULL;
10164 struct got_object_qid *pid;
10165 int ch, list_refs = 0, remove_refs = 0;
10166 struct got_update_progress_arg upa;
10167 int *pack_fds = NULL;
10169 #ifndef PROFILE
10170 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
10171 "unveil", NULL) == -1)
10172 err(1, "pledge");
10173 #endif
10175 while ((ch = getopt(argc, argv, "lX")) != -1) {
10176 switch (ch) {
10177 case 'l':
10178 list_refs = 1;
10179 break;
10180 case 'X':
10181 remove_refs = 1;
10182 break;
10183 default:
10184 usage_cherrypick();
10185 /* NOTREACHED */
10189 argc -= optind;
10190 argv += optind;
10192 if (list_refs || remove_refs) {
10193 if (argc != 0 && argc != 1)
10194 usage_cherrypick();
10195 } else if (argc != 1)
10196 usage_cherrypick();
10197 if (list_refs && remove_refs)
10198 option_conflict('l', 'X');
10200 cwd = getcwd(NULL, 0);
10201 if (cwd == NULL) {
10202 error = got_error_from_errno("getcwd");
10203 goto done;
10206 error = got_repo_pack_fds_open(&pack_fds);
10207 if (error != NULL)
10208 goto done;
10210 error = got_worktree_open(&worktree, cwd);
10211 if (error) {
10212 if (list_refs || remove_refs) {
10213 if (error->code != GOT_ERR_NOT_WORKTREE)
10214 goto done;
10215 } else {
10216 if (error->code == GOT_ERR_NOT_WORKTREE)
10217 error = wrap_not_worktree_error(error,
10218 "cherrypick", cwd);
10219 goto done;
10223 error = got_repo_open(&repo,
10224 worktree ? got_worktree_get_repo_path(worktree) : cwd,
10225 NULL, pack_fds);
10226 if (error != NULL)
10227 goto done;
10229 error = apply_unveil(got_repo_get_path(repo), 0,
10230 worktree ? got_worktree_get_root_path(worktree) : NULL);
10231 if (error)
10232 goto done;
10234 if (list_refs || remove_refs) {
10235 error = process_logmsg_refs(GOT_WORKTREE_CHERRYPICK_REF_PREFIX,
10236 GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN,
10237 argc == 1 ? argv[0] : NULL, remove_refs, worktree, repo);
10238 goto done;
10241 error = got_repo_match_object_id(&commit_id, NULL, argv[0],
10242 GOT_OBJ_TYPE_COMMIT, NULL, repo);
10243 if (error)
10244 goto done;
10245 error = got_object_id_str(&commit_id_str, commit_id);
10246 if (error)
10247 goto done;
10249 error = got_object_open_as_commit(&commit, repo, commit_id);
10250 if (error)
10251 goto done;
10252 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
10253 memset(&upa, 0, sizeof(upa));
10254 error = got_worktree_merge_files(worktree, pid ? &pid->id : NULL,
10255 commit_id, repo, update_progress, &upa, check_cancelled,
10256 NULL);
10257 if (error != NULL)
10258 goto done;
10260 if (upa.did_something) {
10261 error = logmsg_ref(commit_id,
10262 GOT_WORKTREE_CHERRYPICK_REF_PREFIX, worktree, repo);
10263 if (error)
10264 goto done;
10265 printf("Merged commit %s\n", commit_id_str);
10267 print_merge_progress_stats(&upa);
10268 done:
10269 free(cwd);
10270 if (commit)
10271 got_object_commit_close(commit);
10272 free(commit_id_str);
10273 if (worktree)
10274 got_worktree_close(worktree);
10275 if (repo) {
10276 const struct got_error *close_err = got_repo_close(repo);
10277 if (error == NULL)
10278 error = close_err;
10280 if (pack_fds) {
10281 const struct got_error *pack_err =
10282 got_repo_pack_fds_close(pack_fds);
10283 if (error == NULL)
10284 error = pack_err;
10287 return error;
10290 __dead static void
10291 usage_backout(void)
10293 fprintf(stderr, "usage: %s backout [-lX] [commit-id]\n", getprogname());
10294 exit(1);
10297 static const struct got_error *
10298 cmd_backout(int argc, char *argv[])
10300 const struct got_error *error = NULL;
10301 struct got_worktree *worktree = NULL;
10302 struct got_repository *repo = NULL;
10303 char *cwd = NULL, *commit_id_str = NULL;
10304 struct got_object_id *commit_id = NULL;
10305 struct got_commit_object *commit = NULL;
10306 struct got_object_qid *pid;
10307 int ch, list_refs = 0, remove_refs = 0;
10308 struct got_update_progress_arg upa;
10309 int *pack_fds = NULL;
10311 #ifndef PROFILE
10312 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
10313 "unveil", NULL) == -1)
10314 err(1, "pledge");
10315 #endif
10317 while ((ch = getopt(argc, argv, "lX")) != -1) {
10318 switch (ch) {
10319 case 'l':
10320 list_refs = 1;
10321 break;
10322 case 'X':
10323 remove_refs = 1;
10324 break;
10325 default:
10326 usage_backout();
10327 /* NOTREACHED */
10331 argc -= optind;
10332 argv += optind;
10334 if (list_refs || remove_refs) {
10335 if (argc != 0 && argc != 1)
10336 usage_backout();
10337 } else if (argc != 1)
10338 usage_backout();
10339 if (list_refs && remove_refs)
10340 option_conflict('l', 'X');
10342 cwd = getcwd(NULL, 0);
10343 if (cwd == NULL) {
10344 error = got_error_from_errno("getcwd");
10345 goto done;
10348 error = got_repo_pack_fds_open(&pack_fds);
10349 if (error != NULL)
10350 goto done;
10352 error = got_worktree_open(&worktree, cwd);
10353 if (error) {
10354 if (list_refs || remove_refs) {
10355 if (error->code != GOT_ERR_NOT_WORKTREE)
10356 goto done;
10357 } else {
10358 if (error->code == GOT_ERR_NOT_WORKTREE)
10359 error = wrap_not_worktree_error(error,
10360 "backout", cwd);
10361 goto done;
10365 error = got_repo_open(&repo,
10366 worktree ? got_worktree_get_repo_path(worktree) : cwd,
10367 NULL, pack_fds);
10368 if (error != NULL)
10369 goto done;
10371 error = apply_unveil(got_repo_get_path(repo), 0,
10372 worktree ? got_worktree_get_root_path(worktree) : NULL);
10373 if (error)
10374 goto done;
10376 if (list_refs || remove_refs) {
10377 error = process_logmsg_refs(GOT_WORKTREE_BACKOUT_REF_PREFIX,
10378 GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN,
10379 argc == 1 ? argv[0] : NULL, remove_refs, worktree, repo);
10380 goto done;
10383 error = got_repo_match_object_id(&commit_id, NULL, argv[0],
10384 GOT_OBJ_TYPE_COMMIT, NULL, repo);
10385 if (error)
10386 goto done;
10387 error = got_object_id_str(&commit_id_str, commit_id);
10388 if (error)
10389 goto done;
10391 error = got_object_open_as_commit(&commit, repo, commit_id);
10392 if (error)
10393 goto done;
10394 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
10395 if (pid == NULL) {
10396 error = got_error(GOT_ERR_ROOT_COMMIT);
10397 goto done;
10400 memset(&upa, 0, sizeof(upa));
10401 error = got_worktree_merge_files(worktree, commit_id, &pid->id,
10402 repo, update_progress, &upa, check_cancelled, NULL);
10403 if (error != NULL)
10404 goto done;
10406 if (upa.did_something) {
10407 error = logmsg_ref(commit_id, GOT_WORKTREE_BACKOUT_REF_PREFIX,
10408 worktree, repo);
10409 if (error)
10410 goto done;
10411 printf("Backed out commit %s\n", commit_id_str);
10413 print_merge_progress_stats(&upa);
10414 done:
10415 free(cwd);
10416 if (commit)
10417 got_object_commit_close(commit);
10418 free(commit_id_str);
10419 if (worktree)
10420 got_worktree_close(worktree);
10421 if (repo) {
10422 const struct got_error *close_err = got_repo_close(repo);
10423 if (error == NULL)
10424 error = close_err;
10426 if (pack_fds) {
10427 const struct got_error *pack_err =
10428 got_repo_pack_fds_close(pack_fds);
10429 if (error == NULL)
10430 error = pack_err;
10432 return error;
10435 __dead static void
10436 usage_rebase(void)
10438 fprintf(stderr, "usage: %s rebase [-aCclX] [branch]\n", getprogname());
10439 exit(1);
10442 static void
10443 trim_logmsg(char *logmsg, int limit)
10445 char *nl;
10446 size_t len;
10448 len = strlen(logmsg);
10449 if (len > limit)
10450 len = limit;
10451 logmsg[len] = '\0';
10452 nl = strchr(logmsg, '\n');
10453 if (nl)
10454 *nl = '\0';
10457 static const struct got_error *
10458 get_short_logmsg(char **logmsg, int limit, struct got_commit_object *commit)
10460 const struct got_error *err;
10461 char *logmsg0 = NULL;
10462 const char *s;
10464 err = got_object_commit_get_logmsg(&logmsg0, commit);
10465 if (err)
10466 return err;
10468 s = logmsg0;
10469 while (isspace((unsigned char)s[0]))
10470 s++;
10472 *logmsg = strdup(s);
10473 if (*logmsg == NULL) {
10474 err = got_error_from_errno("strdup");
10475 goto done;
10478 trim_logmsg(*logmsg, limit);
10479 done:
10480 free(logmsg0);
10481 return err;
10484 static const struct got_error *
10485 show_rebase_merge_conflict(struct got_object_id *id,
10486 struct got_repository *repo)
10488 const struct got_error *err;
10489 struct got_commit_object *commit = NULL;
10490 char *id_str = NULL, *logmsg = NULL;
10492 err = got_object_open_as_commit(&commit, repo, id);
10493 if (err)
10494 return err;
10496 err = got_object_id_str(&id_str, id);
10497 if (err)
10498 goto done;
10500 id_str[12] = '\0';
10502 err = get_short_logmsg(&logmsg, 42, commit);
10503 if (err)
10504 goto done;
10506 printf("%s -> merge conflict: %s\n", id_str, logmsg);
10507 done:
10508 free(id_str);
10509 got_object_commit_close(commit);
10510 free(logmsg);
10511 return err;
10514 static const struct got_error *
10515 show_rebase_progress(struct got_commit_object *commit,
10516 struct got_object_id *old_id, struct got_object_id *new_id)
10518 const struct got_error *err;
10519 char *old_id_str = NULL, *new_id_str = NULL, *logmsg = NULL;
10521 err = got_object_id_str(&old_id_str, old_id);
10522 if (err)
10523 goto done;
10525 if (new_id) {
10526 err = got_object_id_str(&new_id_str, new_id);
10527 if (err)
10528 goto done;
10531 old_id_str[12] = '\0';
10532 if (new_id_str)
10533 new_id_str[12] = '\0';
10535 err = get_short_logmsg(&logmsg, 42, commit);
10536 if (err)
10537 goto done;
10539 printf("%s -> %s: %s\n", old_id_str,
10540 new_id_str ? new_id_str : "no-op change", logmsg);
10541 done:
10542 free(old_id_str);
10543 free(new_id_str);
10544 free(logmsg);
10545 return err;
10548 static const struct got_error *
10549 rebase_complete(struct got_worktree *worktree, struct got_fileindex *fileindex,
10550 struct got_reference *branch, struct got_reference *tmp_branch,
10551 struct got_repository *repo, int create_backup)
10553 printf("Switching work tree to %s\n", got_ref_get_name(branch));
10554 return got_worktree_rebase_complete(worktree, fileindex,
10555 tmp_branch, branch, repo, create_backup);
10558 static const struct got_error *
10559 rebase_commit(struct got_pathlist_head *merged_paths,
10560 struct got_worktree *worktree, struct got_fileindex *fileindex,
10561 struct got_reference *tmp_branch, const char *committer,
10562 struct got_object_id *commit_id, int allow_conflict,
10563 struct got_repository *repo)
10565 const struct got_error *error;
10566 struct got_commit_object *commit;
10567 struct got_object_id *new_commit_id;
10569 error = got_object_open_as_commit(&commit, repo, commit_id);
10570 if (error)
10571 return error;
10573 error = got_worktree_rebase_commit(&new_commit_id, merged_paths,
10574 worktree, fileindex, tmp_branch, committer, commit, commit_id,
10575 allow_conflict, repo);
10576 if (error) {
10577 if (error->code != GOT_ERR_COMMIT_NO_CHANGES)
10578 goto done;
10579 error = show_rebase_progress(commit, commit_id, NULL);
10580 } else {
10581 error = show_rebase_progress(commit, commit_id, new_commit_id);
10582 free(new_commit_id);
10584 done:
10585 got_object_commit_close(commit);
10586 return error;
10589 struct check_path_prefix_arg {
10590 const char *path_prefix;
10591 size_t len;
10592 int errcode;
10595 static const struct got_error *
10596 check_path_prefix_in_diff(void *arg, struct got_blob_object *blob1,
10597 struct got_blob_object *blob2, FILE *f1, FILE *f2,
10598 struct got_object_id *id1, struct got_object_id *id2,
10599 const char *path1, const char *path2,
10600 mode_t mode1, mode_t mode2, struct got_repository *repo)
10602 struct check_path_prefix_arg *a = arg;
10604 if ((path1 && !got_path_is_child(path1, a->path_prefix, a->len)) ||
10605 (path2 && !got_path_is_child(path2, a->path_prefix, a->len)))
10606 return got_error(a->errcode);
10608 return NULL;
10611 static const struct got_error *
10612 check_path_prefix(struct got_object_id *parent_id,
10613 struct got_object_id *commit_id, const char *path_prefix,
10614 int errcode, struct got_repository *repo)
10616 const struct got_error *err;
10617 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
10618 struct got_commit_object *commit = NULL, *parent_commit = NULL;
10619 struct check_path_prefix_arg cpp_arg;
10621 if (got_path_is_root_dir(path_prefix))
10622 return NULL;
10624 err = got_object_open_as_commit(&commit, repo, commit_id);
10625 if (err)
10626 goto done;
10628 err = got_object_open_as_commit(&parent_commit, repo, parent_id);
10629 if (err)
10630 goto done;
10632 err = got_object_open_as_tree(&tree1, repo,
10633 got_object_commit_get_tree_id(parent_commit));
10634 if (err)
10635 goto done;
10637 err = got_object_open_as_tree(&tree2, repo,
10638 got_object_commit_get_tree_id(commit));
10639 if (err)
10640 goto done;
10642 cpp_arg.path_prefix = path_prefix;
10643 while (cpp_arg.path_prefix[0] == '/')
10644 cpp_arg.path_prefix++;
10645 cpp_arg.len = strlen(cpp_arg.path_prefix);
10646 cpp_arg.errcode = errcode;
10647 err = got_diff_tree(tree1, tree2, NULL, NULL, -1, -1, "", "", repo,
10648 check_path_prefix_in_diff, &cpp_arg, 0);
10649 done:
10650 if (tree1)
10651 got_object_tree_close(tree1);
10652 if (tree2)
10653 got_object_tree_close(tree2);
10654 if (commit)
10655 got_object_commit_close(commit);
10656 if (parent_commit)
10657 got_object_commit_close(parent_commit);
10658 return err;
10661 static const struct got_error *
10662 collect_commits(struct got_object_id_queue *commits,
10663 struct got_object_id *initial_commit_id,
10664 struct got_object_id *iter_start_id, struct got_object_id *iter_stop_id,
10665 const char *path_prefix, int path_prefix_errcode,
10666 struct got_repository *repo)
10668 const struct got_error *err = NULL;
10669 struct got_commit_graph *graph = NULL;
10670 struct got_object_id parent_id, commit_id;
10671 struct got_object_qid *qid;
10673 err = got_commit_graph_open(&graph, "/", 1);
10674 if (err)
10675 return err;
10677 err = got_commit_graph_iter_start(graph, iter_start_id, repo,
10678 check_cancelled, NULL);
10679 if (err)
10680 goto done;
10682 memcpy(&commit_id, initial_commit_id, sizeof(commit_id));
10683 while (got_object_id_cmp(&commit_id, iter_stop_id) != 0) {
10684 err = got_commit_graph_iter_next(&parent_id, graph, repo,
10685 check_cancelled, NULL);
10686 if (err) {
10687 if (err->code == GOT_ERR_ITER_COMPLETED) {
10688 err = got_error_msg(GOT_ERR_ANCESTRY,
10689 "ran out of commits to rebase before "
10690 "youngest common ancestor commit has "
10691 "been reached?!?");
10693 goto done;
10694 } else {
10695 err = check_path_prefix(&parent_id, &commit_id,
10696 path_prefix, path_prefix_errcode, repo);
10697 if (err)
10698 goto done;
10700 err = got_object_qid_alloc(&qid, &commit_id);
10701 if (err)
10702 goto done;
10703 STAILQ_INSERT_HEAD(commits, qid, entry);
10705 memcpy(&commit_id, &parent_id, sizeof(commit_id));
10708 done:
10709 got_commit_graph_close(graph);
10710 return err;
10713 static const struct got_error *
10714 get_commit_brief_str(char **brief_str, struct got_commit_object *commit)
10716 const struct got_error *err = NULL;
10717 time_t committer_time;
10718 struct tm tm;
10719 char datebuf[11]; /* YYYY-MM-DD + NUL */
10720 char *author0 = NULL, *author, *smallerthan;
10721 char *logmsg0 = NULL, *logmsg, *newline;
10723 committer_time = got_object_commit_get_committer_time(commit);
10724 if (gmtime_r(&committer_time, &tm) == NULL)
10725 return got_error_from_errno("gmtime_r");
10726 if (strftime(datebuf, sizeof(datebuf), "%G-%m-%d", &tm) == 0)
10727 return got_error(GOT_ERR_NO_SPACE);
10729 author0 = strdup(got_object_commit_get_author(commit));
10730 if (author0 == NULL)
10731 return got_error_from_errno("strdup");
10732 author = author0;
10733 smallerthan = strchr(author, '<');
10734 if (smallerthan && smallerthan[1] != '\0')
10735 author = smallerthan + 1;
10736 author[strcspn(author, "@>")] = '\0';
10738 err = got_object_commit_get_logmsg(&logmsg0, commit);
10739 if (err)
10740 goto done;
10741 logmsg = logmsg0;
10742 while (*logmsg == '\n')
10743 logmsg++;
10744 newline = strchr(logmsg, '\n');
10745 if (newline)
10746 *newline = '\0';
10748 if (asprintf(brief_str, "%s %s %s",
10749 datebuf, author, logmsg) == -1)
10750 err = got_error_from_errno("asprintf");
10751 done:
10752 free(author0);
10753 free(logmsg0);
10754 return err;
10757 static const struct got_error *
10758 delete_backup_ref(struct got_reference *ref, struct got_object_id *id,
10759 struct got_repository *repo)
10761 const struct got_error *err;
10762 char *id_str;
10764 err = got_object_id_str(&id_str, id);
10765 if (err)
10766 return err;
10768 err = got_ref_delete(ref, repo);
10769 if (err)
10770 goto done;
10772 printf("Deleted %s: %s\n", got_ref_get_name(ref), id_str);
10773 done:
10774 free(id_str);
10775 return err;
10778 static const struct got_error *
10779 print_backup_ref(const char *branch_name, const char *new_id_str,
10780 struct got_object_id *old_commit_id, struct got_commit_object *old_commit,
10781 struct got_reflist_object_id_map *refs_idmap,
10782 struct got_repository *repo)
10784 const struct got_error *err = NULL;
10785 struct got_reflist_head *refs;
10786 char *refs_str = NULL;
10787 struct got_object_id *new_commit_id = NULL;
10788 struct got_commit_object *new_commit = NULL;
10789 char *new_commit_brief_str = NULL;
10790 struct got_object_id *yca_id = NULL;
10791 struct got_commit_object *yca_commit = NULL;
10792 char *yca_id_str = NULL, *yca_brief_str = NULL;
10793 char *custom_refs_str;
10795 if (asprintf(&custom_refs_str, "formerly %s", branch_name) == -1)
10796 return got_error_from_errno("asprintf");
10798 err = print_commit(old_commit, old_commit_id, repo, NULL, NULL, NULL,
10799 0, 0, refs_idmap, custom_refs_str, NULL);
10800 if (err)
10801 goto done;
10803 err = got_object_resolve_id_str(&new_commit_id, repo, new_id_str);
10804 if (err)
10805 goto done;
10807 refs = got_reflist_object_id_map_lookup(refs_idmap, new_commit_id);
10808 if (refs) {
10809 err = build_refs_str(&refs_str, refs, new_commit_id, repo, 0);
10810 if (err)
10811 goto done;
10814 err = got_object_open_as_commit(&new_commit, repo, new_commit_id);
10815 if (err)
10816 goto done;
10818 err = get_commit_brief_str(&new_commit_brief_str, new_commit);
10819 if (err)
10820 goto done;
10822 err = got_commit_graph_find_youngest_common_ancestor(&yca_id,
10823 old_commit_id, new_commit_id, 1, repo, check_cancelled, NULL);
10824 if (err)
10825 goto done;
10827 printf("has become commit %s%s%s%s\n %s\n", new_id_str,
10828 refs_str ? " (" : "", refs_str ? refs_str : "",
10829 refs_str ? ")" : "", new_commit_brief_str);
10830 if (yca_id && got_object_id_cmp(yca_id, new_commit_id) != 0 &&
10831 got_object_id_cmp(yca_id, old_commit_id) != 0) {
10832 free(refs_str);
10833 refs_str = NULL;
10835 err = got_object_open_as_commit(&yca_commit, repo, yca_id);
10836 if (err)
10837 goto done;
10839 err = get_commit_brief_str(&yca_brief_str, yca_commit);
10840 if (err)
10841 goto done;
10843 err = got_object_id_str(&yca_id_str, yca_id);
10844 if (err)
10845 goto done;
10847 refs = got_reflist_object_id_map_lookup(refs_idmap, yca_id);
10848 if (refs) {
10849 err = build_refs_str(&refs_str, refs, yca_id, repo, 0);
10850 if (err)
10851 goto done;
10853 printf("history forked at %s%s%s%s\n %s\n",
10854 yca_id_str,
10855 refs_str ? " (" : "", refs_str ? refs_str : "",
10856 refs_str ? ")" : "", yca_brief_str);
10858 done:
10859 free(custom_refs_str);
10860 free(new_commit_id);
10861 free(refs_str);
10862 free(yca_id);
10863 free(yca_id_str);
10864 free(yca_brief_str);
10865 if (new_commit)
10866 got_object_commit_close(new_commit);
10867 if (yca_commit)
10868 got_object_commit_close(yca_commit);
10870 return err;
10873 static const struct got_error *
10874 worktree_has_logmsg_ref(const char *caller, struct got_worktree *worktree,
10875 struct got_repository *repo)
10877 const struct got_error *err;
10878 struct got_reflist_head refs;
10879 struct got_reflist_entry *re;
10880 char *uuidstr = NULL;
10881 static char msg[160];
10883 TAILQ_INIT(&refs);
10885 err = got_worktree_get_uuid(&uuidstr, worktree);
10886 if (err)
10887 goto done;
10889 err = got_ref_list(&refs, repo, "refs/got/worktree",
10890 got_ref_cmp_by_name, repo);
10891 if (err)
10892 goto done;
10894 TAILQ_FOREACH(re, &refs, entry) {
10895 const char *cmd, *refname, *type;
10897 refname = got_ref_get_name(re->ref);
10899 if (strncmp(refname, GOT_WORKTREE_CHERRYPICK_REF_PREFIX,
10900 GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN) == 0) {
10901 refname += GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN + 1;
10902 cmd = "cherrypick";
10903 type = "cherrypicked";
10904 } else if (strncmp(refname, GOT_WORKTREE_BACKOUT_REF_PREFIX,
10905 GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN) == 0) {
10906 refname += GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN + 1;
10907 cmd = "backout";
10908 type = "backed-out";
10909 } else
10910 continue;
10912 if (strncmp(refname, uuidstr, GOT_WORKTREE_UUID_STRLEN) != 0)
10913 continue;
10915 snprintf(msg, sizeof(msg),
10916 "work tree has references created by %s commits which "
10917 "must be removed with 'got %s -X' before running the %s "
10918 "command", type, cmd, caller);
10919 err = got_error_msg(GOT_ERR_WORKTREE_META, msg);
10920 goto done;
10923 done:
10924 free(uuidstr);
10925 got_ref_list_free(&refs);
10926 return err;
10929 static const struct got_error *
10930 process_backup_refs(const char *backup_ref_prefix,
10931 const char *wanted_branch_name,
10932 int delete, struct got_repository *repo)
10934 const struct got_error *err;
10935 struct got_reflist_head refs, backup_refs;
10936 struct got_reflist_entry *re;
10937 const size_t backup_ref_prefix_len = strlen(backup_ref_prefix);
10938 struct got_object_id *old_commit_id = NULL;
10939 char *branch_name = NULL;
10940 struct got_commit_object *old_commit = NULL;
10941 struct got_reflist_object_id_map *refs_idmap = NULL;
10942 int wanted_branch_found = 0;
10944 TAILQ_INIT(&refs);
10945 TAILQ_INIT(&backup_refs);
10947 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
10948 if (err)
10949 return err;
10951 err = got_reflist_object_id_map_create(&refs_idmap, &refs, repo);
10952 if (err)
10953 goto done;
10955 if (wanted_branch_name) {
10956 if (strncmp(wanted_branch_name, "refs/heads/", 11) == 0)
10957 wanted_branch_name += 11;
10960 err = got_ref_list(&backup_refs, repo, backup_ref_prefix,
10961 got_ref_cmp_by_commit_timestamp_descending, repo);
10962 if (err)
10963 goto done;
10965 TAILQ_FOREACH(re, &backup_refs, entry) {
10966 const char *refname = got_ref_get_name(re->ref);
10967 char *slash;
10969 err = check_cancelled(NULL);
10970 if (err)
10971 break;
10973 err = got_ref_resolve(&old_commit_id, repo, re->ref);
10974 if (err)
10975 break;
10977 err = got_object_open_as_commit(&old_commit, repo,
10978 old_commit_id);
10979 if (err)
10980 break;
10982 if (strncmp(backup_ref_prefix, refname,
10983 backup_ref_prefix_len) == 0)
10984 refname += backup_ref_prefix_len;
10986 while (refname[0] == '/')
10987 refname++;
10989 branch_name = strdup(refname);
10990 if (branch_name == NULL) {
10991 err = got_error_from_errno("strdup");
10992 break;
10994 slash = strrchr(branch_name, '/');
10995 if (slash) {
10996 *slash = '\0';
10997 refname += strlen(branch_name) + 1;
11000 if (wanted_branch_name == NULL ||
11001 strcmp(wanted_branch_name, branch_name) == 0) {
11002 wanted_branch_found = 1;
11003 if (delete) {
11004 err = delete_backup_ref(re->ref,
11005 old_commit_id, repo);
11006 } else {
11007 err = print_backup_ref(branch_name, refname,
11008 old_commit_id, old_commit, refs_idmap,
11009 repo);
11011 if (err)
11012 break;
11015 free(old_commit_id);
11016 old_commit_id = NULL;
11017 free(branch_name);
11018 branch_name = NULL;
11019 got_object_commit_close(old_commit);
11020 old_commit = NULL;
11023 if (wanted_branch_name && !wanted_branch_found) {
11024 err = got_error_fmt(GOT_ERR_NOT_REF,
11025 "%s/%s/", backup_ref_prefix, wanted_branch_name);
11027 done:
11028 if (refs_idmap)
11029 got_reflist_object_id_map_free(refs_idmap);
11030 got_ref_list_free(&refs);
11031 got_ref_list_free(&backup_refs);
11032 free(old_commit_id);
11033 free(branch_name);
11034 if (old_commit)
11035 got_object_commit_close(old_commit);
11036 return err;
11039 static const struct got_error *
11040 abort_progress(void *arg, unsigned char status, const char *path)
11043 * Unversioned files should not clutter progress output when
11044 * an operation is aborted.
11046 if (status == GOT_STATUS_UNVERSIONED)
11047 return NULL;
11049 return update_progress(arg, status, path);
11052 static const struct got_error *
11053 cmd_rebase(int argc, char *argv[])
11055 const struct got_error *error = NULL;
11056 struct got_worktree *worktree = NULL;
11057 struct got_repository *repo = NULL;
11058 struct got_fileindex *fileindex = NULL;
11059 char *cwd = NULL, *committer = NULL, *gitconfig_path = NULL;
11060 struct got_reference *branch = NULL;
11061 struct got_reference *new_base_branch = NULL, *tmp_branch = NULL;
11062 struct got_object_id *commit_id = NULL, *parent_id = NULL;
11063 struct got_object_id *resume_commit_id = NULL;
11064 struct got_object_id *branch_head_commit_id = NULL, *yca_id = NULL;
11065 struct got_object_id *head_commit_id = NULL;
11066 struct got_reference *head_ref = NULL;
11067 struct got_commit_object *commit = NULL;
11068 int ch, rebase_in_progress = 0, abort_rebase = 0, continue_rebase = 0;
11069 int histedit_in_progress = 0, merge_in_progress = 0;
11070 int create_backup = 1, list_backups = 0, delete_backups = 0;
11071 int allow_conflict = 0;
11072 struct got_object_id_queue commits;
11073 struct got_pathlist_head merged_paths;
11074 const struct got_object_id_queue *parent_ids;
11075 struct got_object_qid *qid, *pid;
11076 struct got_update_progress_arg upa;
11077 int *pack_fds = NULL;
11079 STAILQ_INIT(&commits);
11080 TAILQ_INIT(&merged_paths);
11081 memset(&upa, 0, sizeof(upa));
11083 #ifndef PROFILE
11084 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
11085 "unveil", NULL) == -1)
11086 err(1, "pledge");
11087 #endif
11089 while ((ch = getopt(argc, argv, "aCclX")) != -1) {
11090 switch (ch) {
11091 case 'a':
11092 abort_rebase = 1;
11093 break;
11094 case 'C':
11095 allow_conflict = 1;
11096 break;
11097 case 'c':
11098 continue_rebase = 1;
11099 break;
11100 case 'l':
11101 list_backups = 1;
11102 break;
11103 case 'X':
11104 delete_backups = 1;
11105 break;
11106 default:
11107 usage_rebase();
11108 /* NOTREACHED */
11112 argc -= optind;
11113 argv += optind;
11115 if (list_backups) {
11116 if (abort_rebase)
11117 option_conflict('l', 'a');
11118 if (allow_conflict)
11119 option_conflict('l', 'C');
11120 if (continue_rebase)
11121 option_conflict('l', 'c');
11122 if (delete_backups)
11123 option_conflict('l', 'X');
11124 if (argc != 0 && argc != 1)
11125 usage_rebase();
11126 } else if (delete_backups) {
11127 if (abort_rebase)
11128 option_conflict('X', 'a');
11129 if (allow_conflict)
11130 option_conflict('X', 'C');
11131 if (continue_rebase)
11132 option_conflict('X', 'c');
11133 if (list_backups)
11134 option_conflict('l', 'X');
11135 if (argc != 0 && argc != 1)
11136 usage_rebase();
11137 } else if (allow_conflict) {
11138 if (abort_rebase)
11139 option_conflict('C', 'a');
11140 if (!continue_rebase)
11141 errx(1, "-C option requires -c");
11142 } else {
11143 if (abort_rebase && continue_rebase)
11144 usage_rebase();
11145 else if (abort_rebase || continue_rebase) {
11146 if (argc != 0)
11147 usage_rebase();
11148 } else if (argc != 1)
11149 usage_rebase();
11152 cwd = getcwd(NULL, 0);
11153 if (cwd == NULL) {
11154 error = got_error_from_errno("getcwd");
11155 goto done;
11158 error = got_repo_pack_fds_open(&pack_fds);
11159 if (error != NULL)
11160 goto done;
11162 error = got_worktree_open(&worktree, cwd);
11163 if (error) {
11164 if (list_backups || delete_backups) {
11165 if (error->code != GOT_ERR_NOT_WORKTREE)
11166 goto done;
11167 } else {
11168 if (error->code == GOT_ERR_NOT_WORKTREE)
11169 error = wrap_not_worktree_error(error,
11170 "rebase", cwd);
11171 goto done;
11175 error = get_gitconfig_path(&gitconfig_path);
11176 if (error)
11177 goto done;
11178 error = got_repo_open(&repo,
11179 worktree ? got_worktree_get_repo_path(worktree) : cwd,
11180 gitconfig_path, pack_fds);
11181 if (error != NULL)
11182 goto done;
11184 if (worktree != NULL && !list_backups && !delete_backups) {
11185 error = worktree_has_logmsg_ref("rebase", worktree, repo);
11186 if (error)
11187 goto done;
11190 error = get_author(&committer, repo, worktree);
11191 if (error && error->code != GOT_ERR_COMMIT_NO_AUTHOR)
11192 goto done;
11194 error = apply_unveil(got_repo_get_path(repo), 0,
11195 worktree ? got_worktree_get_root_path(worktree) : NULL);
11196 if (error)
11197 goto done;
11199 if (list_backups || delete_backups) {
11200 error = process_backup_refs(
11201 GOT_WORKTREE_REBASE_BACKUP_REF_PREFIX,
11202 argc == 1 ? argv[0] : NULL, delete_backups, repo);
11203 goto done; /* nothing else to do */
11206 error = got_worktree_histedit_in_progress(&histedit_in_progress,
11207 worktree);
11208 if (error)
11209 goto done;
11210 if (histedit_in_progress) {
11211 error = got_error(GOT_ERR_HISTEDIT_BUSY);
11212 goto done;
11215 error = got_worktree_merge_in_progress(&merge_in_progress,
11216 worktree, repo);
11217 if (error)
11218 goto done;
11219 if (merge_in_progress) {
11220 error = got_error(GOT_ERR_MERGE_BUSY);
11221 goto done;
11224 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
11225 if (error)
11226 goto done;
11228 if (abort_rebase) {
11229 if (!rebase_in_progress) {
11230 error = got_error(GOT_ERR_NOT_REBASING);
11231 goto done;
11233 error = got_worktree_rebase_continue(&resume_commit_id,
11234 &new_base_branch, &tmp_branch, &branch, &fileindex,
11235 worktree, repo);
11236 if (error)
11237 goto done;
11238 printf("Switching work tree to %s\n",
11239 got_ref_get_symref_target(new_base_branch));
11240 error = got_worktree_rebase_abort(worktree, fileindex, repo,
11241 new_base_branch, abort_progress, &upa);
11242 if (error)
11243 goto done;
11244 printf("Rebase of %s aborted\n", got_ref_get_name(branch));
11245 print_merge_progress_stats(&upa);
11246 goto done; /* nothing else to do */
11249 if (continue_rebase) {
11250 if (!rebase_in_progress) {
11251 error = got_error(GOT_ERR_NOT_REBASING);
11252 goto done;
11254 error = got_worktree_rebase_continue(&resume_commit_id,
11255 &new_base_branch, &tmp_branch, &branch, &fileindex,
11256 worktree, repo);
11257 if (error)
11258 goto done;
11260 error = rebase_commit(NULL, worktree, fileindex, tmp_branch,
11261 committer, resume_commit_id, allow_conflict, repo);
11262 if (error)
11263 goto done;
11265 yca_id = got_object_id_dup(resume_commit_id);
11266 if (yca_id == NULL) {
11267 error = got_error_from_errno("got_object_id_dup");
11268 goto done;
11270 } else {
11271 error = got_ref_open(&branch, repo, argv[0], 0);
11272 if (error != NULL)
11273 goto done;
11274 if (strncmp(got_ref_get_name(branch), "refs/heads/", 11) != 0) {
11275 error = got_error_msg(GOT_ERR_COMMIT_BRANCH,
11276 "will not rebase a branch which lives outside "
11277 "the \"refs/heads/\" reference namespace");
11278 goto done;
11282 error = got_ref_resolve(&branch_head_commit_id, repo, branch);
11283 if (error)
11284 goto done;
11286 if (!continue_rebase) {
11287 struct got_object_id *base_commit_id;
11289 error = got_ref_open(&head_ref, repo,
11290 got_worktree_get_head_ref_name(worktree), 0);
11291 if (error)
11292 goto done;
11293 error = got_ref_resolve(&head_commit_id, repo, head_ref);
11294 if (error)
11295 goto done;
11296 base_commit_id = got_worktree_get_base_commit_id(worktree);
11297 if (got_object_id_cmp(base_commit_id, head_commit_id) != 0) {
11298 error = got_error(GOT_ERR_REBASE_OUT_OF_DATE);
11299 goto done;
11302 error = got_commit_graph_find_youngest_common_ancestor(&yca_id,
11303 base_commit_id, branch_head_commit_id, 1, repo,
11304 check_cancelled, NULL);
11305 if (error) {
11306 if (error->code == GOT_ERR_ANCESTRY) {
11307 error = got_error_msg(GOT_ERR_ANCESTRY,
11308 "specified branch shares no common "
11309 "ancestry with work tree's branch");
11311 goto done;
11314 if (got_object_id_cmp(base_commit_id, yca_id) == 0) {
11315 struct got_pathlist_head paths;
11316 printf("%s is already based on %s\n",
11317 got_ref_get_name(branch),
11318 got_worktree_get_head_ref_name(worktree));
11319 error = switch_head_ref(branch, branch_head_commit_id,
11320 worktree, repo);
11321 if (error)
11322 goto done;
11323 error = got_worktree_set_base_commit_id(worktree, repo,
11324 branch_head_commit_id);
11325 if (error)
11326 goto done;
11327 TAILQ_INIT(&paths);
11328 error = got_pathlist_append(&paths, "", NULL);
11329 if (error)
11330 goto done;
11331 error = got_worktree_checkout_files(worktree,
11332 &paths, repo, update_progress, &upa,
11333 check_cancelled, NULL);
11334 got_pathlist_free(&paths, GOT_PATHLIST_FREE_NONE);
11335 if (error)
11336 goto done;
11337 if (upa.did_something) {
11338 char *id_str;
11339 error = got_object_id_str(&id_str,
11340 branch_head_commit_id);
11341 if (error)
11342 goto done;
11343 printf("Updated to %s: %s\n",
11344 got_worktree_get_head_ref_name(worktree),
11345 id_str);
11346 free(id_str);
11347 } else
11348 printf("Already up-to-date\n");
11349 print_update_progress_stats(&upa);
11350 goto done;
11354 commit_id = branch_head_commit_id;
11355 error = got_object_open_as_commit(&commit, repo, commit_id);
11356 if (error)
11357 goto done;
11359 parent_ids = got_object_commit_get_parent_ids(commit);
11360 pid = STAILQ_FIRST(parent_ids);
11361 if (pid) {
11362 error = collect_commits(&commits, commit_id, &pid->id,
11363 yca_id, got_worktree_get_path_prefix(worktree),
11364 GOT_ERR_REBASE_PATH, repo);
11365 if (error)
11366 goto done;
11369 got_object_commit_close(commit);
11370 commit = NULL;
11372 if (!continue_rebase) {
11373 error = got_worktree_rebase_prepare(&new_base_branch,
11374 &tmp_branch, &fileindex, worktree, branch, repo);
11375 if (error)
11376 goto done;
11379 if (STAILQ_EMPTY(&commits)) {
11380 if (continue_rebase) {
11381 error = rebase_complete(worktree, fileindex,
11382 branch, tmp_branch, repo, create_backup);
11383 goto done;
11384 } else {
11385 /* Fast-forward the reference of the branch. */
11386 struct got_object_id *new_head_commit_id;
11387 char *id_str;
11388 error = got_ref_resolve(&new_head_commit_id, repo,
11389 new_base_branch);
11390 if (error)
11391 goto done;
11392 error = got_object_id_str(&id_str, new_head_commit_id);
11393 if (error)
11394 goto done;
11395 printf("Forwarding %s to commit %s\n",
11396 got_ref_get_name(branch), id_str);
11397 free(id_str);
11398 error = got_ref_change_ref(branch,
11399 new_head_commit_id);
11400 if (error)
11401 goto done;
11402 /* No backup needed since objects did not change. */
11403 create_backup = 0;
11407 pid = NULL;
11408 STAILQ_FOREACH(qid, &commits, entry) {
11410 commit_id = &qid->id;
11411 parent_id = pid ? &pid->id : yca_id;
11412 pid = qid;
11414 memset(&upa, 0, sizeof(upa));
11415 error = got_worktree_rebase_merge_files(&merged_paths,
11416 worktree, fileindex, parent_id, commit_id, repo,
11417 update_progress, &upa, check_cancelled, NULL);
11418 if (error)
11419 goto done;
11421 print_merge_progress_stats(&upa);
11422 if (upa.conflicts > 0 || upa.missing > 0 ||
11423 upa.not_deleted > 0 || upa.unversioned > 0) {
11424 if (upa.conflicts > 0) {
11425 error = show_rebase_merge_conflict(&qid->id,
11426 repo);
11427 if (error)
11428 goto done;
11430 got_pathlist_free(&merged_paths, GOT_PATHLIST_FREE_PATH);
11431 break;
11434 error = rebase_commit(&merged_paths, worktree, fileindex,
11435 tmp_branch, committer, commit_id, 0, repo);
11436 got_pathlist_free(&merged_paths, GOT_PATHLIST_FREE_PATH);
11437 if (error)
11438 goto done;
11441 if (upa.conflicts > 0 || upa.missing > 0 ||
11442 upa.not_deleted > 0 || upa.unversioned > 0) {
11443 error = got_worktree_rebase_postpone(worktree, fileindex);
11444 if (error)
11445 goto done;
11446 if (upa.conflicts > 0 && upa.missing == 0 &&
11447 upa.not_deleted == 0 && upa.unversioned == 0) {
11448 error = got_error_msg(GOT_ERR_CONFLICTS,
11449 "conflicts must be resolved before rebasing "
11450 "can continue");
11451 } else if (upa.conflicts > 0) {
11452 error = got_error_msg(GOT_ERR_CONFLICTS,
11453 "conflicts must be resolved before rebasing "
11454 "can continue; changes destined for some "
11455 "files were not yet merged and should be "
11456 "merged manually if required before the "
11457 "rebase operation is continued");
11458 } else {
11459 error = got_error_msg(GOT_ERR_CONFLICTS,
11460 "changes destined for some files were not "
11461 "yet merged and should be merged manually "
11462 "if required before the rebase operation "
11463 "is continued");
11465 } else
11466 error = rebase_complete(worktree, fileindex, branch,
11467 tmp_branch, repo, create_backup);
11468 done:
11469 free(cwd);
11470 free(committer);
11471 free(gitconfig_path);
11472 got_object_id_queue_free(&commits);
11473 free(branch_head_commit_id);
11474 free(resume_commit_id);
11475 free(head_commit_id);
11476 free(yca_id);
11477 if (commit)
11478 got_object_commit_close(commit);
11479 if (branch)
11480 got_ref_close(branch);
11481 if (new_base_branch)
11482 got_ref_close(new_base_branch);
11483 if (tmp_branch)
11484 got_ref_close(tmp_branch);
11485 if (head_ref)
11486 got_ref_close(head_ref);
11487 if (worktree)
11488 got_worktree_close(worktree);
11489 if (repo) {
11490 const struct got_error *close_err = got_repo_close(repo);
11491 if (error == NULL)
11492 error = close_err;
11494 if (pack_fds) {
11495 const struct got_error *pack_err =
11496 got_repo_pack_fds_close(pack_fds);
11497 if (error == NULL)
11498 error = pack_err;
11500 return error;
11503 __dead static void
11504 usage_histedit(void)
11506 fprintf(stderr, "usage: %s histedit [-aCcdeflmX] [-F histedit-script] "
11507 "[branch]\n", getprogname());
11508 exit(1);
11511 #define GOT_HISTEDIT_PICK 'p'
11512 #define GOT_HISTEDIT_EDIT 'e'
11513 #define GOT_HISTEDIT_FOLD 'f'
11514 #define GOT_HISTEDIT_DROP 'd'
11515 #define GOT_HISTEDIT_MESG 'm'
11517 static const struct got_histedit_cmd {
11518 unsigned char code;
11519 const char *name;
11520 const char *desc;
11521 } got_histedit_cmds[] = {
11522 { GOT_HISTEDIT_PICK, "pick", "use commit" },
11523 { GOT_HISTEDIT_EDIT, "edit", "use commit but stop for amending" },
11524 { GOT_HISTEDIT_FOLD, "fold", "combine with next commit that will "
11525 "be used" },
11526 { GOT_HISTEDIT_DROP, "drop", "remove commit from history" },
11527 { GOT_HISTEDIT_MESG, "mesg",
11528 "single-line log message for commit above (open editor if empty)" },
11531 struct got_histedit_list_entry {
11532 TAILQ_ENTRY(got_histedit_list_entry) entry;
11533 struct got_object_id *commit_id;
11534 const struct got_histedit_cmd *cmd;
11535 char *logmsg;
11537 TAILQ_HEAD(got_histedit_list, got_histedit_list_entry);
11539 static const struct got_error *
11540 histedit_write_commit(struct got_object_id *commit_id, const char *cmdname,
11541 FILE *f, struct got_repository *repo)
11543 const struct got_error *err = NULL;
11544 char *logmsg = NULL, *id_str = NULL;
11545 struct got_commit_object *commit = NULL;
11546 int n;
11548 err = got_object_open_as_commit(&commit, repo, commit_id);
11549 if (err)
11550 goto done;
11552 err = get_short_logmsg(&logmsg, 34, commit);
11553 if (err)
11554 goto done;
11556 err = got_object_id_str(&id_str, commit_id);
11557 if (err)
11558 goto done;
11560 n = fprintf(f, "%s %s %s\n", cmdname, id_str, logmsg);
11561 if (n < 0)
11562 err = got_ferror(f, GOT_ERR_IO);
11563 done:
11564 if (commit)
11565 got_object_commit_close(commit);
11566 free(id_str);
11567 free(logmsg);
11568 return err;
11571 static const struct got_error *
11572 histedit_write_commit_list(struct got_object_id_queue *commits,
11573 FILE *f, int edit_logmsg_only, int fold_only, int drop_only,
11574 int edit_only, struct got_repository *repo)
11576 const struct got_error *err = NULL;
11577 struct got_object_qid *qid;
11578 const char *histedit_cmd = NULL;
11580 if (STAILQ_EMPTY(commits))
11581 return got_error(GOT_ERR_EMPTY_HISTEDIT);
11583 STAILQ_FOREACH(qid, commits, entry) {
11584 histedit_cmd = got_histedit_cmds[0].name;
11585 if (drop_only)
11586 histedit_cmd = "drop";
11587 else if (edit_only)
11588 histedit_cmd = "edit";
11589 else if (fold_only && STAILQ_NEXT(qid, entry) != NULL)
11590 histedit_cmd = "fold";
11591 err = histedit_write_commit(&qid->id, histedit_cmd, f, repo);
11592 if (err)
11593 break;
11594 if (edit_logmsg_only) {
11595 int n = fprintf(f, "%c\n", GOT_HISTEDIT_MESG);
11596 if (n < 0) {
11597 err = got_ferror(f, GOT_ERR_IO);
11598 break;
11603 return err;
11606 static const struct got_error *
11607 write_cmd_list(FILE *f, const char *branch_name,
11608 struct got_object_id_queue *commits)
11610 const struct got_error *err = NULL;
11611 size_t i;
11612 int n;
11613 char *id_str;
11614 struct got_object_qid *qid;
11616 qid = STAILQ_FIRST(commits);
11617 err = got_object_id_str(&id_str, &qid->id);
11618 if (err)
11619 return err;
11621 n = fprintf(f,
11622 "# Editing the history of branch '%s' starting at\n"
11623 "# commit %s\n"
11624 "# Commits will be processed in order from top to "
11625 "bottom of this file.\n", branch_name, id_str);
11626 if (n < 0) {
11627 err = got_ferror(f, GOT_ERR_IO);
11628 goto done;
11631 n = fprintf(f, "# Available histedit commands:\n");
11632 if (n < 0) {
11633 err = got_ferror(f, GOT_ERR_IO);
11634 goto done;
11637 for (i = 0; i < nitems(got_histedit_cmds); i++) {
11638 const struct got_histedit_cmd *cmd = &got_histedit_cmds[i];
11639 n = fprintf(f, "# %s (%c): %s\n", cmd->name, cmd->code,
11640 cmd->desc);
11641 if (n < 0) {
11642 err = got_ferror(f, GOT_ERR_IO);
11643 break;
11646 done:
11647 free(id_str);
11648 return err;
11651 static const struct got_error *
11652 histedit_syntax_error(int lineno)
11654 static char msg[42];
11655 int ret;
11657 ret = snprintf(msg, sizeof(msg), "histedit syntax error on line %d",
11658 lineno);
11659 if (ret < 0 || (size_t)ret >= sizeof(msg))
11660 return got_error(GOT_ERR_HISTEDIT_SYNTAX);
11662 return got_error_msg(GOT_ERR_HISTEDIT_SYNTAX, msg);
11665 static const struct got_error *
11666 append_folded_commit_msg(char **new_msg, struct got_histedit_list_entry *hle,
11667 char *logmsg, struct got_repository *repo)
11669 const struct got_error *err;
11670 struct got_commit_object *folded_commit = NULL;
11671 char *id_str, *folded_logmsg = NULL;
11673 err = got_object_id_str(&id_str, hle->commit_id);
11674 if (err)
11675 return err;
11677 err = got_object_open_as_commit(&folded_commit, repo, hle->commit_id);
11678 if (err)
11679 goto done;
11681 err = got_object_commit_get_logmsg(&folded_logmsg, folded_commit);
11682 if (err)
11683 goto done;
11684 if (asprintf(new_msg, "%s%s# log message of folded commit %s: %s",
11685 logmsg ? logmsg : "", logmsg ? "\n" : "", id_str,
11686 folded_logmsg) == -1) {
11687 err = got_error_from_errno("asprintf");
11689 done:
11690 if (folded_commit)
11691 got_object_commit_close(folded_commit);
11692 free(id_str);
11693 free(folded_logmsg);
11694 return err;
11697 static struct got_histedit_list_entry *
11698 get_folded_commits(struct got_histedit_list_entry *hle)
11700 struct got_histedit_list_entry *prev, *folded = NULL;
11702 prev = TAILQ_PREV(hle, got_histedit_list, entry);
11703 while (prev && (prev->cmd->code == GOT_HISTEDIT_FOLD ||
11704 prev->cmd->code == GOT_HISTEDIT_DROP)) {
11705 if (prev->cmd->code == GOT_HISTEDIT_FOLD)
11706 folded = prev;
11707 prev = TAILQ_PREV(prev, got_histedit_list, entry);
11710 return folded;
11713 static const struct got_error *
11714 histedit_edit_logmsg(struct got_histedit_list_entry *hle,
11715 struct got_repository *repo)
11717 char *logmsg_path = NULL, *id_str = NULL, *orig_logmsg = NULL;
11718 char *logmsg = NULL, *new_msg = NULL, *editor = NULL;
11719 const struct got_error *err = NULL;
11720 struct got_commit_object *commit = NULL;
11721 int logmsg_len;
11722 int fd = -1;
11723 struct got_histedit_list_entry *folded = NULL;
11725 err = got_object_open_as_commit(&commit, repo, hle->commit_id);
11726 if (err)
11727 return err;
11729 folded = get_folded_commits(hle);
11730 if (folded) {
11731 while (folded != hle) {
11732 if (folded->cmd->code == GOT_HISTEDIT_DROP) {
11733 folded = TAILQ_NEXT(folded, entry);
11734 continue;
11736 err = append_folded_commit_msg(&new_msg, folded,
11737 logmsg, repo);
11738 if (err)
11739 goto done;
11740 free(logmsg);
11741 logmsg = new_msg;
11742 folded = TAILQ_NEXT(folded, entry);
11746 err = got_object_id_str(&id_str, hle->commit_id);
11747 if (err)
11748 goto done;
11749 err = got_object_commit_get_logmsg(&orig_logmsg, commit);
11750 if (err)
11751 goto done;
11752 logmsg_len = asprintf(&new_msg,
11753 "%s\n# original log message of commit %s: %s",
11754 logmsg ? logmsg : "", id_str, orig_logmsg);
11755 if (logmsg_len == -1) {
11756 err = got_error_from_errno("asprintf");
11757 goto done;
11759 free(logmsg);
11760 logmsg = new_msg;
11762 err = got_object_id_str(&id_str, hle->commit_id);
11763 if (err)
11764 goto done;
11766 err = got_opentemp_named_fd(&logmsg_path, &fd,
11767 GOT_TMPDIR_STR "/got-logmsg", "");
11768 if (err)
11769 goto done;
11771 if (write(fd, logmsg, logmsg_len) == -1) {
11772 err = got_error_from_errno2("write", logmsg_path);
11773 goto done;
11775 if (close(fd) == -1) {
11776 err = got_error_from_errno2("close", logmsg_path);
11777 goto done;
11779 fd = -1;
11781 err = get_editor(&editor);
11782 if (err)
11783 goto done;
11785 err = edit_logmsg(&hle->logmsg, editor, logmsg_path, logmsg,
11786 logmsg_len, 0);
11787 if (err) {
11788 if (err->code != GOT_ERR_COMMIT_MSG_EMPTY)
11789 goto done;
11790 err = NULL;
11791 hle->logmsg = strdup(new_msg);
11792 if (hle->logmsg == NULL)
11793 err = got_error_from_errno("strdup");
11795 done:
11796 if (fd != -1 && close(fd) == -1 && err == NULL)
11797 err = got_error_from_errno2("close", logmsg_path);
11798 if (logmsg_path && unlink(logmsg_path) != 0 && err == NULL)
11799 err = got_error_from_errno2("unlink", logmsg_path);
11800 free(logmsg_path);
11801 free(logmsg);
11802 free(orig_logmsg);
11803 free(editor);
11804 if (commit)
11805 got_object_commit_close(commit);
11806 return err;
11809 static const struct got_error *
11810 histedit_parse_list(struct got_histedit_list *histedit_cmds,
11811 FILE *f, struct got_repository *repo)
11813 const struct got_error *err = NULL;
11814 char *line = NULL, *p, *end;
11815 size_t i, linesize = 0;
11816 ssize_t linelen;
11817 int lineno = 0, lastcmd = -1;
11818 const struct got_histedit_cmd *cmd;
11819 struct got_object_id *commit_id = NULL;
11820 struct got_histedit_list_entry *hle = NULL;
11822 for (;;) {
11823 linelen = getline(&line, &linesize, f);
11824 if (linelen == -1) {
11825 const struct got_error *getline_err;
11826 if (feof(f))
11827 break;
11828 getline_err = got_error_from_errno("getline");
11829 err = got_ferror(f, getline_err->code);
11830 break;
11832 lineno++;
11833 p = line;
11834 while (isspace((unsigned char)p[0]))
11835 p++;
11836 if (p[0] == '#' || p[0] == '\0')
11837 continue;
11838 cmd = NULL;
11839 for (i = 0; i < nitems(got_histedit_cmds); i++) {
11840 cmd = &got_histedit_cmds[i];
11841 if (strncmp(cmd->name, p, strlen(cmd->name)) == 0 &&
11842 isspace((unsigned char)p[strlen(cmd->name)])) {
11843 p += strlen(cmd->name);
11844 break;
11846 if (p[0] == cmd->code && isspace((unsigned char)p[1])) {
11847 p++;
11848 break;
11851 if (i == nitems(got_histedit_cmds)) {
11852 err = histedit_syntax_error(lineno);
11853 break;
11855 while (isspace((unsigned char)p[0]))
11856 p++;
11857 if (cmd->code == GOT_HISTEDIT_MESG) {
11858 if (lastcmd != GOT_HISTEDIT_PICK &&
11859 lastcmd != GOT_HISTEDIT_EDIT) {
11860 err = got_error(GOT_ERR_HISTEDIT_CMD);
11861 break;
11863 if (p[0] == '\0') {
11864 err = histedit_edit_logmsg(hle, repo);
11865 if (err)
11866 break;
11867 } else {
11868 hle->logmsg = strdup(p);
11869 if (hle->logmsg == NULL) {
11870 err = got_error_from_errno("strdup");
11871 break;
11874 lastcmd = cmd->code;
11875 continue;
11876 } else {
11877 end = p;
11878 while (end[0] && !isspace((unsigned char)end[0]))
11879 end++;
11880 *end = '\0';
11882 err = got_object_resolve_id_str(&commit_id, repo, p);
11883 if (err) {
11884 /* override error code */
11885 err = histedit_syntax_error(lineno);
11886 break;
11889 hle = malloc(sizeof(*hle));
11890 if (hle == NULL) {
11891 err = got_error_from_errno("malloc");
11892 break;
11894 hle->cmd = cmd;
11895 hle->commit_id = commit_id;
11896 hle->logmsg = NULL;
11897 commit_id = NULL;
11898 TAILQ_INSERT_TAIL(histedit_cmds, hle, entry);
11899 lastcmd = cmd->code;
11902 free(line);
11903 free(commit_id);
11904 return err;
11907 static const struct got_error *
11908 histedit_check_script(struct got_histedit_list *histedit_cmds,
11909 struct got_object_id_queue *commits, struct got_repository *repo)
11911 const struct got_error *err = NULL;
11912 struct got_object_qid *qid;
11913 struct got_histedit_list_entry *hle;
11914 static char msg[92];
11915 char *id_str;
11917 if (TAILQ_EMPTY(histedit_cmds))
11918 return got_error_msg(GOT_ERR_EMPTY_HISTEDIT,
11919 "histedit script contains no commands");
11920 if (STAILQ_EMPTY(commits))
11921 return got_error(GOT_ERR_EMPTY_HISTEDIT);
11923 TAILQ_FOREACH(hle, histedit_cmds, entry) {
11924 struct got_histedit_list_entry *hle2;
11925 TAILQ_FOREACH(hle2, histedit_cmds, entry) {
11926 if (hle == hle2)
11927 continue;
11928 if (got_object_id_cmp(hle->commit_id,
11929 hle2->commit_id) != 0)
11930 continue;
11931 err = got_object_id_str(&id_str, hle->commit_id);
11932 if (err)
11933 return err;
11934 snprintf(msg, sizeof(msg), "commit %s is listed "
11935 "more than once in histedit script", id_str);
11936 free(id_str);
11937 return got_error_msg(GOT_ERR_HISTEDIT_CMD, msg);
11941 STAILQ_FOREACH(qid, commits, entry) {
11942 TAILQ_FOREACH(hle, histedit_cmds, entry) {
11943 if (got_object_id_cmp(&qid->id, hle->commit_id) == 0)
11944 break;
11946 if (hle == NULL) {
11947 err = got_object_id_str(&id_str, &qid->id);
11948 if (err)
11949 return err;
11950 snprintf(msg, sizeof(msg),
11951 "commit %s missing from histedit script", id_str);
11952 free(id_str);
11953 return got_error_msg(GOT_ERR_HISTEDIT_CMD, msg);
11957 hle = TAILQ_LAST(histedit_cmds, got_histedit_list);
11958 if (hle && hle->cmd->code == GOT_HISTEDIT_FOLD)
11959 return got_error_msg(GOT_ERR_HISTEDIT_CMD,
11960 "last commit in histedit script cannot be folded");
11962 return NULL;
11965 static const struct got_error *
11966 histedit_run_editor(struct got_histedit_list *histedit_cmds,
11967 const char *path, struct got_object_id_queue *commits,
11968 struct got_repository *repo)
11970 const struct got_error *err = NULL;
11971 char *editor;
11972 FILE *f = NULL;
11974 err = get_editor(&editor);
11975 if (err)
11976 return err;
11978 if (spawn_editor(editor, path) == -1) {
11979 err = got_error_from_errno("failed spawning editor");
11980 goto done;
11983 f = fopen(path, "re");
11984 if (f == NULL) {
11985 err = got_error_from_errno("fopen");
11986 goto done;
11988 err = histedit_parse_list(histedit_cmds, f, repo);
11989 if (err)
11990 goto done;
11992 err = histedit_check_script(histedit_cmds, commits, repo);
11993 done:
11994 if (f && fclose(f) == EOF && err == NULL)
11995 err = got_error_from_errno("fclose");
11996 free(editor);
11997 return err;
12000 static const struct got_error *
12001 histedit_edit_list_retry(struct got_histedit_list *, const struct got_error *,
12002 struct got_object_id_queue *, const char *, const char *,
12003 struct got_repository *);
12005 static const struct got_error *
12006 histedit_edit_script(struct got_histedit_list *histedit_cmds,
12007 struct got_object_id_queue *commits, const char *branch_name,
12008 int edit_logmsg_only, int fold_only, int drop_only, int edit_only,
12009 struct got_repository *repo)
12011 const struct got_error *err;
12012 FILE *f = NULL;
12013 char *path = NULL;
12015 err = got_opentemp_named(&path, &f, "got-histedit", "");
12016 if (err)
12017 return err;
12019 err = write_cmd_list(f, branch_name, commits);
12020 if (err)
12021 goto done;
12023 err = histedit_write_commit_list(commits, f, edit_logmsg_only,
12024 fold_only, drop_only, edit_only, repo);
12025 if (err)
12026 goto done;
12028 if (drop_only || edit_logmsg_only || fold_only || edit_only) {
12029 rewind(f);
12030 err = histedit_parse_list(histedit_cmds, f, repo);
12031 } else {
12032 if (fclose(f) == EOF) {
12033 err = got_error_from_errno("fclose");
12034 goto done;
12036 f = NULL;
12037 err = histedit_run_editor(histedit_cmds, path, commits, repo);
12038 if (err) {
12039 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
12040 err->code != GOT_ERR_HISTEDIT_CMD)
12041 goto done;
12042 err = histedit_edit_list_retry(histedit_cmds, err,
12043 commits, path, branch_name, repo);
12046 done:
12047 if (f && fclose(f) == EOF && err == NULL)
12048 err = got_error_from_errno("fclose");
12049 if (path && unlink(path) != 0 && err == NULL)
12050 err = got_error_from_errno2("unlink", path);
12051 free(path);
12052 return err;
12055 static const struct got_error *
12056 histedit_save_list(struct got_histedit_list *histedit_cmds,
12057 struct got_worktree *worktree, struct got_repository *repo)
12059 const struct got_error *err = NULL;
12060 char *path = NULL;
12061 FILE *f = NULL;
12062 struct got_histedit_list_entry *hle;
12063 struct got_commit_object *commit = NULL;
12065 err = got_worktree_get_histedit_script_path(&path, worktree);
12066 if (err)
12067 return err;
12069 f = fopen(path, "we");
12070 if (f == NULL) {
12071 err = got_error_from_errno2("fopen", path);
12072 goto done;
12074 TAILQ_FOREACH(hle, histedit_cmds, entry) {
12075 err = histedit_write_commit(hle->commit_id, hle->cmd->name, f,
12076 repo);
12077 if (err)
12078 break;
12080 if (hle->logmsg) {
12081 int n = fprintf(f, "%c %s\n",
12082 GOT_HISTEDIT_MESG, hle->logmsg);
12083 if (n < 0) {
12084 err = got_ferror(f, GOT_ERR_IO);
12085 break;
12089 done:
12090 if (f && fclose(f) == EOF && err == NULL)
12091 err = got_error_from_errno("fclose");
12092 free(path);
12093 if (commit)
12094 got_object_commit_close(commit);
12095 return err;
12098 static void
12099 histedit_free_list(struct got_histedit_list *histedit_cmds)
12101 struct got_histedit_list_entry *hle;
12103 while ((hle = TAILQ_FIRST(histedit_cmds))) {
12104 TAILQ_REMOVE(histedit_cmds, hle, entry);
12105 free(hle);
12109 static const struct got_error *
12110 histedit_load_list(struct got_histedit_list *histedit_cmds,
12111 const char *path, struct got_repository *repo)
12113 const struct got_error *err = NULL;
12114 FILE *f = NULL;
12116 f = fopen(path, "re");
12117 if (f == NULL) {
12118 err = got_error_from_errno2("fopen", path);
12119 goto done;
12122 err = histedit_parse_list(histedit_cmds, f, repo);
12123 done:
12124 if (f && fclose(f) == EOF && err == NULL)
12125 err = got_error_from_errno("fclose");
12126 return err;
12129 static const struct got_error *
12130 histedit_edit_list_retry(struct got_histedit_list *histedit_cmds,
12131 const struct got_error *edit_err, struct got_object_id_queue *commits,
12132 const char *path, const char *branch_name, struct got_repository *repo)
12134 const struct got_error *err = NULL, *prev_err = edit_err;
12135 int resp = ' ';
12137 while (resp != 'c' && resp != 'r' && resp != 'a') {
12138 printf("%s: %s\n(c)ontinue editing, (r)estart editing, "
12139 "or (a)bort: ", getprogname(), prev_err->msg);
12140 resp = getchar();
12141 if (resp == '\n')
12142 resp = getchar();
12143 if (resp == 'c') {
12144 histedit_free_list(histedit_cmds);
12145 err = histedit_run_editor(histedit_cmds, path, commits,
12146 repo);
12147 if (err) {
12148 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
12149 err->code != GOT_ERR_HISTEDIT_CMD)
12150 break;
12151 prev_err = err;
12152 resp = ' ';
12153 continue;
12155 break;
12156 } else if (resp == 'r') {
12157 histedit_free_list(histedit_cmds);
12158 err = histedit_edit_script(histedit_cmds,
12159 commits, branch_name, 0, 0, 0, 0, repo);
12160 if (err) {
12161 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
12162 err->code != GOT_ERR_HISTEDIT_CMD)
12163 break;
12164 prev_err = err;
12165 resp = ' ';
12166 continue;
12168 break;
12169 } else if (resp == 'a') {
12170 err = got_error(GOT_ERR_HISTEDIT_CANCEL);
12171 break;
12172 } else
12173 printf("invalid response '%c'\n", resp);
12176 return err;
12179 static const struct got_error *
12180 histedit_complete(struct got_worktree *worktree,
12181 struct got_fileindex *fileindex, struct got_reference *tmp_branch,
12182 struct got_reference *branch, struct got_repository *repo)
12184 printf("Switching work tree to %s\n",
12185 got_ref_get_symref_target(branch));
12186 return got_worktree_histedit_complete(worktree, fileindex, tmp_branch,
12187 branch, repo);
12190 static const struct got_error *
12191 show_histedit_progress(struct got_commit_object *commit,
12192 struct got_histedit_list_entry *hle, struct got_object_id *new_id)
12194 const struct got_error *err;
12195 char *old_id_str = NULL, *new_id_str = NULL, *logmsg = NULL;
12197 err = got_object_id_str(&old_id_str, hle->commit_id);
12198 if (err)
12199 goto done;
12201 if (new_id) {
12202 err = got_object_id_str(&new_id_str, new_id);
12203 if (err)
12204 goto done;
12207 old_id_str[12] = '\0';
12208 if (new_id_str)
12209 new_id_str[12] = '\0';
12211 if (hle->logmsg) {
12212 logmsg = strdup(hle->logmsg);
12213 if (logmsg == NULL) {
12214 err = got_error_from_errno("strdup");
12215 goto done;
12217 trim_logmsg(logmsg, 42);
12218 } else {
12219 err = get_short_logmsg(&logmsg, 42, commit);
12220 if (err)
12221 goto done;
12224 switch (hle->cmd->code) {
12225 case GOT_HISTEDIT_PICK:
12226 case GOT_HISTEDIT_EDIT:
12227 printf("%s -> %s: %s\n", old_id_str,
12228 new_id_str ? new_id_str : "no-op change", logmsg);
12229 break;
12230 case GOT_HISTEDIT_DROP:
12231 case GOT_HISTEDIT_FOLD:
12232 printf("%s -> %s commit: %s\n", old_id_str, hle->cmd->name,
12233 logmsg);
12234 break;
12235 default:
12236 break;
12238 done:
12239 free(old_id_str);
12240 free(new_id_str);
12241 return err;
12244 static const struct got_error *
12245 histedit_commit(struct got_pathlist_head *merged_paths,
12246 struct got_worktree *worktree, struct got_fileindex *fileindex,
12247 struct got_reference *tmp_branch, struct got_histedit_list_entry *hle,
12248 const char *committer, int allow_conflict, struct got_repository *repo)
12250 const struct got_error *err;
12251 struct got_commit_object *commit;
12252 struct got_object_id *new_commit_id;
12254 if ((hle->cmd->code == GOT_HISTEDIT_EDIT || get_folded_commits(hle))
12255 && hle->logmsg == NULL) {
12256 err = histedit_edit_logmsg(hle, repo);
12257 if (err)
12258 return err;
12261 err = got_object_open_as_commit(&commit, repo, hle->commit_id);
12262 if (err)
12263 return err;
12265 err = got_worktree_histedit_commit(&new_commit_id, merged_paths,
12266 worktree, fileindex, tmp_branch, committer, commit, hle->commit_id,
12267 hle->logmsg, allow_conflict, repo);
12268 if (err) {
12269 if (err->code != GOT_ERR_COMMIT_NO_CHANGES)
12270 goto done;
12271 err = show_histedit_progress(commit, hle, NULL);
12272 } else {
12273 err = show_histedit_progress(commit, hle, new_commit_id);
12274 free(new_commit_id);
12276 done:
12277 got_object_commit_close(commit);
12278 return err;
12281 static const struct got_error *
12282 histedit_skip_commit(struct got_histedit_list_entry *hle,
12283 struct got_worktree *worktree, struct got_repository *repo)
12285 const struct got_error *error;
12286 struct got_commit_object *commit;
12288 error = got_worktree_histedit_skip_commit(worktree, hle->commit_id,
12289 repo);
12290 if (error)
12291 return error;
12293 error = got_object_open_as_commit(&commit, repo, hle->commit_id);
12294 if (error)
12295 return error;
12297 error = show_histedit_progress(commit, hle, NULL);
12298 got_object_commit_close(commit);
12299 return error;
12302 static const struct got_error *
12303 check_local_changes(void *arg, unsigned char status,
12304 unsigned char staged_status, const char *path,
12305 struct got_object_id *blob_id, struct got_object_id *staged_blob_id,
12306 struct got_object_id *commit_id, int dirfd, const char *de_name)
12308 int *have_local_changes = arg;
12310 switch (status) {
12311 case GOT_STATUS_ADD:
12312 case GOT_STATUS_DELETE:
12313 case GOT_STATUS_MODIFY:
12314 case GOT_STATUS_CONFLICT:
12315 *have_local_changes = 1;
12316 return got_error(GOT_ERR_CANCELLED);
12317 default:
12318 break;
12321 switch (staged_status) {
12322 case GOT_STATUS_ADD:
12323 case GOT_STATUS_DELETE:
12324 case GOT_STATUS_MODIFY:
12325 *have_local_changes = 1;
12326 return got_error(GOT_ERR_CANCELLED);
12327 default:
12328 break;
12331 return NULL;
12334 static const struct got_error *
12335 cmd_histedit(int argc, char *argv[])
12337 const struct got_error *error = NULL;
12338 struct got_worktree *worktree = NULL;
12339 struct got_fileindex *fileindex = NULL;
12340 struct got_repository *repo = NULL;
12341 char *cwd = NULL, *committer = NULL, *gitconfig_path = NULL;
12342 struct got_reference *branch = NULL;
12343 struct got_reference *tmp_branch = NULL;
12344 struct got_object_id *resume_commit_id = NULL;
12345 struct got_object_id *base_commit_id = NULL;
12346 struct got_object_id *head_commit_id = NULL;
12347 struct got_commit_object *commit = NULL;
12348 int ch, rebase_in_progress = 0, merge_in_progress = 0;
12349 struct got_update_progress_arg upa;
12350 int edit_in_progress = 0, abort_edit = 0, continue_edit = 0;
12351 int drop_only = 0, edit_logmsg_only = 0, fold_only = 0, edit_only = 0;
12352 int allow_conflict = 0, list_backups = 0, delete_backups = 0;
12353 const char *edit_script_path = NULL;
12354 struct got_object_id_queue commits;
12355 struct got_pathlist_head merged_paths;
12356 const struct got_object_id_queue *parent_ids;
12357 struct got_object_qid *pid;
12358 struct got_histedit_list histedit_cmds;
12359 struct got_histedit_list_entry *hle;
12360 int *pack_fds = NULL;
12362 STAILQ_INIT(&commits);
12363 TAILQ_INIT(&histedit_cmds);
12364 TAILQ_INIT(&merged_paths);
12365 memset(&upa, 0, sizeof(upa));
12367 #ifndef PROFILE
12368 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
12369 "unveil", NULL) == -1)
12370 err(1, "pledge");
12371 #endif
12373 while ((ch = getopt(argc, argv, "aCcdeF:flmX")) != -1) {
12374 switch (ch) {
12375 case 'a':
12376 abort_edit = 1;
12377 break;
12378 case 'C':
12379 allow_conflict = 1;
12380 break;
12381 case 'c':
12382 continue_edit = 1;
12383 break;
12384 case 'd':
12385 drop_only = 1;
12386 break;
12387 case 'e':
12388 edit_only = 1;
12389 break;
12390 case 'F':
12391 edit_script_path = optarg;
12392 break;
12393 case 'f':
12394 fold_only = 1;
12395 break;
12396 case 'l':
12397 list_backups = 1;
12398 break;
12399 case 'm':
12400 edit_logmsg_only = 1;
12401 break;
12402 case 'X':
12403 delete_backups = 1;
12404 break;
12405 default:
12406 usage_histedit();
12407 /* NOTREACHED */
12411 argc -= optind;
12412 argv += optind;
12414 if (abort_edit && allow_conflict)
12415 option_conflict('a', 'C');
12416 if (abort_edit && continue_edit)
12417 option_conflict('a', 'c');
12418 if (edit_script_path && allow_conflict)
12419 option_conflict('F', 'C');
12420 if (edit_script_path && edit_logmsg_only)
12421 option_conflict('F', 'm');
12422 if (abort_edit && edit_logmsg_only)
12423 option_conflict('a', 'm');
12424 if (edit_logmsg_only && allow_conflict)
12425 option_conflict('m', 'C');
12426 if (continue_edit && edit_logmsg_only)
12427 option_conflict('c', 'm');
12428 if (abort_edit && fold_only)
12429 option_conflict('a', 'f');
12430 if (fold_only && allow_conflict)
12431 option_conflict('f', 'C');
12432 if (continue_edit && fold_only)
12433 option_conflict('c', 'f');
12434 if (fold_only && edit_logmsg_only)
12435 option_conflict('f', 'm');
12436 if (edit_script_path && fold_only)
12437 option_conflict('F', 'f');
12438 if (abort_edit && edit_only)
12439 option_conflict('a', 'e');
12440 if (continue_edit && edit_only)
12441 option_conflict('c', 'e');
12442 if (edit_only && edit_logmsg_only)
12443 option_conflict('e', 'm');
12444 if (edit_script_path && edit_only)
12445 option_conflict('F', 'e');
12446 if (fold_only && edit_only)
12447 option_conflict('f', 'e');
12448 if (drop_only && abort_edit)
12449 option_conflict('d', 'a');
12450 if (drop_only && allow_conflict)
12451 option_conflict('d', 'C');
12452 if (drop_only && continue_edit)
12453 option_conflict('d', 'c');
12454 if (drop_only && edit_logmsg_only)
12455 option_conflict('d', 'm');
12456 if (drop_only && edit_only)
12457 option_conflict('d', 'e');
12458 if (drop_only && edit_script_path)
12459 option_conflict('d', 'F');
12460 if (drop_only && fold_only)
12461 option_conflict('d', 'f');
12462 if (list_backups) {
12463 if (abort_edit)
12464 option_conflict('l', 'a');
12465 if (allow_conflict)
12466 option_conflict('l', 'C');
12467 if (continue_edit)
12468 option_conflict('l', 'c');
12469 if (edit_script_path)
12470 option_conflict('l', 'F');
12471 if (edit_logmsg_only)
12472 option_conflict('l', 'm');
12473 if (drop_only)
12474 option_conflict('l', 'd');
12475 if (fold_only)
12476 option_conflict('l', 'f');
12477 if (edit_only)
12478 option_conflict('l', 'e');
12479 if (delete_backups)
12480 option_conflict('l', 'X');
12481 if (argc != 0 && argc != 1)
12482 usage_histedit();
12483 } else if (delete_backups) {
12484 if (abort_edit)
12485 option_conflict('X', 'a');
12486 if (allow_conflict)
12487 option_conflict('X', 'C');
12488 if (continue_edit)
12489 option_conflict('X', 'c');
12490 if (drop_only)
12491 option_conflict('X', 'd');
12492 if (edit_script_path)
12493 option_conflict('X', 'F');
12494 if (edit_logmsg_only)
12495 option_conflict('X', 'm');
12496 if (fold_only)
12497 option_conflict('X', 'f');
12498 if (edit_only)
12499 option_conflict('X', 'e');
12500 if (list_backups)
12501 option_conflict('X', 'l');
12502 if (argc != 0 && argc != 1)
12503 usage_histedit();
12504 } else if (allow_conflict && !continue_edit)
12505 errx(1, "-C option requires -c");
12506 else if (argc != 0)
12507 usage_histedit();
12510 * This command cannot apply unveil(2) in all cases because the
12511 * user may choose to run an editor to edit the histedit script
12512 * and to edit individual commit log messages.
12513 * unveil(2) traverses exec(2); if an editor is used we have to
12514 * apply unveil after edit script and log messages have been written.
12515 * XXX TODO: Make use of unveil(2) where possible.
12518 cwd = getcwd(NULL, 0);
12519 if (cwd == NULL) {
12520 error = got_error_from_errno("getcwd");
12521 goto done;
12524 error = got_repo_pack_fds_open(&pack_fds);
12525 if (error != NULL)
12526 goto done;
12528 error = got_worktree_open(&worktree, cwd);
12529 if (error) {
12530 if (list_backups || delete_backups) {
12531 if (error->code != GOT_ERR_NOT_WORKTREE)
12532 goto done;
12533 } else {
12534 if (error->code == GOT_ERR_NOT_WORKTREE)
12535 error = wrap_not_worktree_error(error,
12536 "histedit", cwd);
12537 goto done;
12541 if (list_backups || delete_backups) {
12542 error = got_repo_open(&repo,
12543 worktree ? got_worktree_get_repo_path(worktree) : cwd,
12544 NULL, pack_fds);
12545 if (error != NULL)
12546 goto done;
12547 error = apply_unveil(got_repo_get_path(repo), 0,
12548 worktree ? got_worktree_get_root_path(worktree) : NULL);
12549 if (error)
12550 goto done;
12551 error = process_backup_refs(
12552 GOT_WORKTREE_HISTEDIT_BACKUP_REF_PREFIX,
12553 argc == 1 ? argv[0] : NULL, delete_backups, repo);
12554 goto done; /* nothing else to do */
12557 error = get_gitconfig_path(&gitconfig_path);
12558 if (error)
12559 goto done;
12560 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
12561 gitconfig_path, pack_fds);
12562 if (error != NULL)
12563 goto done;
12565 if (worktree != NULL && !list_backups && !delete_backups) {
12566 error = worktree_has_logmsg_ref("histedit", worktree, repo);
12567 if (error)
12568 goto done;
12571 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
12572 if (error)
12573 goto done;
12574 if (rebase_in_progress) {
12575 error = got_error(GOT_ERR_REBASING);
12576 goto done;
12579 error = got_worktree_merge_in_progress(&merge_in_progress, worktree,
12580 repo);
12581 if (error)
12582 goto done;
12583 if (merge_in_progress) {
12584 error = got_error(GOT_ERR_MERGE_BUSY);
12585 goto done;
12588 error = got_worktree_histedit_in_progress(&edit_in_progress, worktree);
12589 if (error)
12590 goto done;
12592 if (edit_in_progress && edit_logmsg_only) {
12593 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
12594 "histedit operation is in progress in this "
12595 "work tree and must be continued or aborted "
12596 "before the -m option can be used");
12597 goto done;
12599 if (edit_in_progress && drop_only) {
12600 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
12601 "histedit operation is in progress in this "
12602 "work tree and must be continued or aborted "
12603 "before the -d option can be used");
12604 goto done;
12606 if (edit_in_progress && fold_only) {
12607 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
12608 "histedit operation is in progress in this "
12609 "work tree and must be continued or aborted "
12610 "before the -f option can be used");
12611 goto done;
12613 if (edit_in_progress && edit_only) {
12614 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
12615 "histedit operation is in progress in this "
12616 "work tree and must be continued or aborted "
12617 "before the -e option can be used");
12618 goto done;
12621 if (edit_in_progress && abort_edit) {
12622 error = got_worktree_histedit_continue(&resume_commit_id,
12623 &tmp_branch, &branch, &base_commit_id, &fileindex,
12624 worktree, repo);
12625 if (error)
12626 goto done;
12627 printf("Switching work tree to %s\n",
12628 got_ref_get_symref_target(branch));
12629 error = got_worktree_histedit_abort(worktree, fileindex, repo,
12630 branch, base_commit_id, abort_progress, &upa);
12631 if (error)
12632 goto done;
12633 printf("Histedit of %s aborted\n",
12634 got_ref_get_symref_target(branch));
12635 print_merge_progress_stats(&upa);
12636 goto done; /* nothing else to do */
12637 } else if (abort_edit) {
12638 error = got_error(GOT_ERR_NOT_HISTEDIT);
12639 goto done;
12642 error = get_author(&committer, repo, worktree);
12643 if (error)
12644 goto done;
12646 if (continue_edit) {
12647 char *path;
12649 if (!edit_in_progress) {
12650 error = got_error(GOT_ERR_NOT_HISTEDIT);
12651 goto done;
12654 error = got_worktree_get_histedit_script_path(&path, worktree);
12655 if (error)
12656 goto done;
12658 error = histedit_load_list(&histedit_cmds, path, repo);
12659 free(path);
12660 if (error)
12661 goto done;
12663 error = got_worktree_histedit_continue(&resume_commit_id,
12664 &tmp_branch, &branch, &base_commit_id, &fileindex,
12665 worktree, repo);
12666 if (error)
12667 goto done;
12669 error = got_ref_resolve(&head_commit_id, repo, branch);
12670 if (error)
12671 goto done;
12673 error = got_object_open_as_commit(&commit, repo,
12674 head_commit_id);
12675 if (error)
12676 goto done;
12677 parent_ids = got_object_commit_get_parent_ids(commit);
12678 pid = STAILQ_FIRST(parent_ids);
12679 if (pid == NULL) {
12680 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
12681 goto done;
12683 error = collect_commits(&commits, head_commit_id, &pid->id,
12684 base_commit_id, got_worktree_get_path_prefix(worktree),
12685 GOT_ERR_HISTEDIT_PATH, repo);
12686 got_object_commit_close(commit);
12687 commit = NULL;
12688 if (error)
12689 goto done;
12690 } else {
12691 if (edit_in_progress) {
12692 error = got_error(GOT_ERR_HISTEDIT_BUSY);
12693 goto done;
12696 error = got_ref_open(&branch, repo,
12697 got_worktree_get_head_ref_name(worktree), 0);
12698 if (error != NULL)
12699 goto done;
12701 if (strncmp(got_ref_get_name(branch), "refs/heads/", 11) != 0) {
12702 error = got_error_msg(GOT_ERR_COMMIT_BRANCH,
12703 "will not edit commit history of a branch outside "
12704 "the \"refs/heads/\" reference namespace");
12705 goto done;
12708 error = got_ref_resolve(&head_commit_id, repo, branch);
12709 got_ref_close(branch);
12710 branch = NULL;
12711 if (error)
12712 goto done;
12714 error = got_object_open_as_commit(&commit, repo,
12715 head_commit_id);
12716 if (error)
12717 goto done;
12718 parent_ids = got_object_commit_get_parent_ids(commit);
12719 pid = STAILQ_FIRST(parent_ids);
12720 if (pid == NULL) {
12721 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
12722 goto done;
12724 error = collect_commits(&commits, head_commit_id, &pid->id,
12725 got_worktree_get_base_commit_id(worktree),
12726 got_worktree_get_path_prefix(worktree),
12727 GOT_ERR_HISTEDIT_PATH, repo);
12728 got_object_commit_close(commit);
12729 commit = NULL;
12730 if (error)
12731 goto done;
12733 if (STAILQ_EMPTY(&commits)) {
12734 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
12735 goto done;
12738 error = got_worktree_histedit_prepare(&tmp_branch, &branch,
12739 &base_commit_id, &fileindex, worktree, repo);
12740 if (error)
12741 goto done;
12743 if (edit_script_path) {
12744 error = histedit_load_list(&histedit_cmds,
12745 edit_script_path, repo);
12746 if (error) {
12747 got_worktree_histedit_abort(worktree, fileindex,
12748 repo, branch, base_commit_id,
12749 abort_progress, &upa);
12750 print_merge_progress_stats(&upa);
12751 goto done;
12753 } else {
12754 const char *branch_name;
12755 branch_name = got_ref_get_symref_target(branch);
12756 if (strncmp(branch_name, "refs/heads/", 11) == 0)
12757 branch_name += 11;
12758 error = histedit_edit_script(&histedit_cmds, &commits,
12759 branch_name, edit_logmsg_only, fold_only,
12760 drop_only, edit_only, repo);
12761 if (error) {
12762 got_worktree_histedit_abort(worktree, fileindex,
12763 repo, branch, base_commit_id,
12764 abort_progress, &upa);
12765 print_merge_progress_stats(&upa);
12766 goto done;
12771 error = histedit_save_list(&histedit_cmds, worktree,
12772 repo);
12773 if (error) {
12774 got_worktree_histedit_abort(worktree, fileindex,
12775 repo, branch, base_commit_id,
12776 abort_progress, &upa);
12777 print_merge_progress_stats(&upa);
12778 goto done;
12783 error = histedit_check_script(&histedit_cmds, &commits, repo);
12784 if (error)
12785 goto done;
12787 TAILQ_FOREACH(hle, &histedit_cmds, entry) {
12788 if (resume_commit_id) {
12789 if (got_object_id_cmp(hle->commit_id,
12790 resume_commit_id) != 0)
12791 continue;
12793 resume_commit_id = NULL;
12794 if (hle->cmd->code == GOT_HISTEDIT_DROP ||
12795 hle->cmd->code == GOT_HISTEDIT_FOLD) {
12796 error = histedit_skip_commit(hle, worktree,
12797 repo);
12798 if (error)
12799 goto done;
12800 } else {
12801 struct got_pathlist_head paths;
12802 int have_changes = 0;
12804 TAILQ_INIT(&paths);
12805 error = got_pathlist_append(&paths, "", NULL);
12806 if (error)
12807 goto done;
12808 error = got_worktree_status(worktree, &paths,
12809 repo, 0, check_local_changes, &have_changes,
12810 check_cancelled, NULL);
12811 got_pathlist_free(&paths,
12812 GOT_PATHLIST_FREE_NONE);
12813 if (error) {
12814 if (error->code != GOT_ERR_CANCELLED)
12815 goto done;
12816 if (sigint_received || sigpipe_received)
12817 goto done;
12819 if (have_changes) {
12820 error = histedit_commit(NULL, worktree,
12821 fileindex, tmp_branch, hle,
12822 committer, allow_conflict, repo);
12823 if (error)
12824 goto done;
12825 } else {
12826 error = got_object_open_as_commit(
12827 &commit, repo, hle->commit_id);
12828 if (error)
12829 goto done;
12830 error = show_histedit_progress(commit,
12831 hle, NULL);
12832 got_object_commit_close(commit);
12833 commit = NULL;
12834 if (error)
12835 goto done;
12838 continue;
12841 if (hle->cmd->code == GOT_HISTEDIT_DROP) {
12842 error = histedit_skip_commit(hle, worktree, repo);
12843 if (error)
12844 goto done;
12845 continue;
12848 error = got_object_open_as_commit(&commit, repo,
12849 hle->commit_id);
12850 if (error)
12851 goto done;
12852 parent_ids = got_object_commit_get_parent_ids(commit);
12853 pid = STAILQ_FIRST(parent_ids);
12855 error = got_worktree_histedit_merge_files(&merged_paths,
12856 worktree, fileindex, &pid->id, hle->commit_id, repo,
12857 update_progress, &upa, check_cancelled, NULL);
12858 if (error)
12859 goto done;
12860 got_object_commit_close(commit);
12861 commit = NULL;
12863 print_merge_progress_stats(&upa);
12864 if (upa.conflicts > 0 || upa.missing > 0 ||
12865 upa.not_deleted > 0 || upa.unversioned > 0) {
12866 if (upa.conflicts > 0) {
12867 error = show_rebase_merge_conflict(
12868 hle->commit_id, repo);
12869 if (error)
12870 goto done;
12872 got_pathlist_free(&merged_paths, GOT_PATHLIST_FREE_PATH);
12873 break;
12876 if (hle->cmd->code == GOT_HISTEDIT_EDIT) {
12877 char *id_str;
12878 error = got_object_id_str(&id_str, hle->commit_id);
12879 if (error)
12880 goto done;
12881 printf("Stopping histedit for amending commit %s\n",
12882 id_str);
12883 free(id_str);
12884 got_pathlist_free(&merged_paths, GOT_PATHLIST_FREE_PATH);
12885 error = got_worktree_histedit_postpone(worktree,
12886 fileindex);
12887 goto done;
12890 if (hle->cmd->code == GOT_HISTEDIT_FOLD) {
12891 error = histedit_skip_commit(hle, worktree, repo);
12892 if (error)
12893 goto done;
12894 continue;
12897 error = histedit_commit(&merged_paths, worktree, fileindex,
12898 tmp_branch, hle, committer, allow_conflict, repo);
12899 got_pathlist_free(&merged_paths, GOT_PATHLIST_FREE_PATH);
12900 if (error)
12901 goto done;
12904 if (upa.conflicts > 0 || upa.missing > 0 ||
12905 upa.not_deleted > 0 || upa.unversioned > 0) {
12906 error = got_worktree_histedit_postpone(worktree, fileindex);
12907 if (error)
12908 goto done;
12909 if (upa.conflicts > 0 && upa.missing == 0 &&
12910 upa.not_deleted == 0 && upa.unversioned == 0) {
12911 error = got_error_msg(GOT_ERR_CONFLICTS,
12912 "conflicts must be resolved before histedit "
12913 "can continue");
12914 } else if (upa.conflicts > 0) {
12915 error = got_error_msg(GOT_ERR_CONFLICTS,
12916 "conflicts must be resolved before histedit "
12917 "can continue; changes destined for some "
12918 "files were not yet merged and should be "
12919 "merged manually if required before the "
12920 "histedit operation is continued");
12921 } else {
12922 error = got_error_msg(GOT_ERR_CONFLICTS,
12923 "changes destined for some files were not "
12924 "yet merged and should be merged manually "
12925 "if required before the histedit operation "
12926 "is continued");
12928 } else
12929 error = histedit_complete(worktree, fileindex, tmp_branch,
12930 branch, repo);
12931 done:
12932 free(cwd);
12933 free(committer);
12934 free(gitconfig_path);
12935 got_object_id_queue_free(&commits);
12936 histedit_free_list(&histedit_cmds);
12937 free(head_commit_id);
12938 free(base_commit_id);
12939 free(resume_commit_id);
12940 if (commit)
12941 got_object_commit_close(commit);
12942 if (branch)
12943 got_ref_close(branch);
12944 if (tmp_branch)
12945 got_ref_close(tmp_branch);
12946 if (worktree)
12947 got_worktree_close(worktree);
12948 if (repo) {
12949 const struct got_error *close_err = got_repo_close(repo);
12950 if (error == NULL)
12951 error = close_err;
12953 if (pack_fds) {
12954 const struct got_error *pack_err =
12955 got_repo_pack_fds_close(pack_fds);
12956 if (error == NULL)
12957 error = pack_err;
12959 return error;
12962 __dead static void
12963 usage_integrate(void)
12965 fprintf(stderr, "usage: %s integrate branch\n", getprogname());
12966 exit(1);
12969 static const struct got_error *
12970 cmd_integrate(int argc, char *argv[])
12972 const struct got_error *error = NULL;
12973 struct got_repository *repo = NULL;
12974 struct got_worktree *worktree = NULL;
12975 char *cwd = NULL, *refname = NULL, *base_refname = NULL;
12976 const char *branch_arg = NULL;
12977 struct got_reference *branch_ref = NULL, *base_branch_ref = NULL;
12978 struct got_fileindex *fileindex = NULL;
12979 struct got_object_id *commit_id = NULL, *base_commit_id = NULL;
12980 int ch;
12981 struct got_update_progress_arg upa;
12982 int *pack_fds = NULL;
12984 #ifndef PROFILE
12985 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
12986 "unveil", NULL) == -1)
12987 err(1, "pledge");
12988 #endif
12990 while ((ch = getopt(argc, argv, "")) != -1) {
12991 switch (ch) {
12992 default:
12993 usage_integrate();
12994 /* NOTREACHED */
12998 argc -= optind;
12999 argv += optind;
13001 if (argc != 1)
13002 usage_integrate();
13003 branch_arg = argv[0];
13005 cwd = getcwd(NULL, 0);
13006 if (cwd == NULL) {
13007 error = got_error_from_errno("getcwd");
13008 goto done;
13011 error = got_repo_pack_fds_open(&pack_fds);
13012 if (error != NULL)
13013 goto done;
13015 error = got_worktree_open(&worktree, cwd);
13016 if (error) {
13017 if (error->code == GOT_ERR_NOT_WORKTREE)
13018 error = wrap_not_worktree_error(error, "integrate",
13019 cwd);
13020 goto done;
13023 error = check_rebase_or_histedit_in_progress(worktree);
13024 if (error)
13025 goto done;
13027 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
13028 NULL, pack_fds);
13029 if (error != NULL)
13030 goto done;
13032 error = apply_unveil(got_repo_get_path(repo), 0,
13033 got_worktree_get_root_path(worktree));
13034 if (error)
13035 goto done;
13037 error = check_merge_in_progress(worktree, repo);
13038 if (error)
13039 goto done;
13041 if (asprintf(&refname, "refs/heads/%s", branch_arg) == -1) {
13042 error = got_error_from_errno("asprintf");
13043 goto done;
13046 error = got_worktree_integrate_prepare(&fileindex, &branch_ref,
13047 &base_branch_ref, worktree, refname, repo);
13048 if (error)
13049 goto done;
13051 refname = strdup(got_ref_get_name(branch_ref));
13052 if (refname == NULL) {
13053 error = got_error_from_errno("strdup");
13054 got_worktree_integrate_abort(worktree, fileindex, repo,
13055 branch_ref, base_branch_ref);
13056 goto done;
13058 base_refname = strdup(got_ref_get_name(base_branch_ref));
13059 if (base_refname == NULL) {
13060 error = got_error_from_errno("strdup");
13061 got_worktree_integrate_abort(worktree, fileindex, repo,
13062 branch_ref, base_branch_ref);
13063 goto done;
13065 if (strncmp(base_refname, "refs/heads/", 11) != 0) {
13066 error = got_error(GOT_ERR_INTEGRATE_BRANCH);
13067 got_worktree_integrate_abort(worktree, fileindex, repo,
13068 branch_ref, base_branch_ref);
13069 goto done;
13072 error = got_ref_resolve(&commit_id, repo, branch_ref);
13073 if (error)
13074 goto done;
13076 error = got_ref_resolve(&base_commit_id, repo, base_branch_ref);
13077 if (error)
13078 goto done;
13080 if (got_object_id_cmp(commit_id, base_commit_id) == 0) {
13081 error = got_error_msg(GOT_ERR_SAME_BRANCH,
13082 "specified branch has already been integrated");
13083 got_worktree_integrate_abort(worktree, fileindex, repo,
13084 branch_ref, base_branch_ref);
13085 goto done;
13088 error = check_linear_ancestry(commit_id, base_commit_id, 1, repo);
13089 if (error) {
13090 if (error->code == GOT_ERR_ANCESTRY)
13091 error = got_error(GOT_ERR_REBASE_REQUIRED);
13092 got_worktree_integrate_abort(worktree, fileindex, repo,
13093 branch_ref, base_branch_ref);
13094 goto done;
13097 memset(&upa, 0, sizeof(upa));
13098 error = got_worktree_integrate_continue(worktree, fileindex, repo,
13099 branch_ref, base_branch_ref, update_progress, &upa,
13100 check_cancelled, NULL);
13101 if (error)
13102 goto done;
13104 printf("Integrated %s into %s\n", refname, base_refname);
13105 print_update_progress_stats(&upa);
13106 done:
13107 if (repo) {
13108 const struct got_error *close_err = got_repo_close(repo);
13109 if (error == NULL)
13110 error = close_err;
13112 if (worktree)
13113 got_worktree_close(worktree);
13114 if (pack_fds) {
13115 const struct got_error *pack_err =
13116 got_repo_pack_fds_close(pack_fds);
13117 if (error == NULL)
13118 error = pack_err;
13120 free(cwd);
13121 free(base_commit_id);
13122 free(commit_id);
13123 free(refname);
13124 free(base_refname);
13125 return error;
13128 __dead static void
13129 usage_merge(void)
13131 fprintf(stderr, "usage: %s merge [-aCcn] [branch]\n", getprogname());
13132 exit(1);
13135 static const struct got_error *
13136 cmd_merge(int argc, char *argv[])
13138 const struct got_error *error = NULL;
13139 struct got_worktree *worktree = NULL;
13140 struct got_repository *repo = NULL;
13141 struct got_fileindex *fileindex = NULL;
13142 char *cwd = NULL, *id_str = NULL, *author = NULL;
13143 char *gitconfig_path = NULL;
13144 struct got_reference *branch = NULL, *wt_branch = NULL;
13145 struct got_object_id *branch_tip = NULL, *yca_id = NULL;
13146 struct got_object_id *wt_branch_tip = NULL;
13147 int ch, merge_in_progress = 0, abort_merge = 0, continue_merge = 0;
13148 int allow_conflict = 0, prefer_fast_forward = 1, interrupt_merge = 0;
13149 struct got_update_progress_arg upa;
13150 struct got_object_id *merge_commit_id = NULL;
13151 char *branch_name = NULL;
13152 int *pack_fds = NULL;
13154 memset(&upa, 0, sizeof(upa));
13156 #ifndef PROFILE
13157 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
13158 "unveil", NULL) == -1)
13159 err(1, "pledge");
13160 #endif
13162 while ((ch = getopt(argc, argv, "aCcMn")) != -1) {
13163 switch (ch) {
13164 case 'a':
13165 abort_merge = 1;
13166 break;
13167 case 'C':
13168 allow_conflict = 1;
13169 break;
13170 case 'c':
13171 continue_merge = 1;
13172 break;
13173 case 'M':
13174 prefer_fast_forward = 0;
13175 break;
13176 case 'n':
13177 interrupt_merge = 1;
13178 break;
13179 default:
13180 usage_merge();
13181 /* NOTREACHED */
13185 argc -= optind;
13186 argv += optind;
13188 if (abort_merge) {
13189 if (continue_merge)
13190 option_conflict('a', 'c');
13191 if (!prefer_fast_forward)
13192 option_conflict('a', 'M');
13193 if (interrupt_merge)
13194 option_conflict('a', 'n');
13195 } else if (continue_merge) {
13196 if (!prefer_fast_forward)
13197 option_conflict('c', 'M');
13198 if (interrupt_merge)
13199 option_conflict('c', 'n');
13201 if (allow_conflict) {
13202 if (!continue_merge)
13203 errx(1, "-C option requires -c");
13205 if (abort_merge || continue_merge) {
13206 if (argc != 0)
13207 usage_merge();
13208 } else if (argc != 1)
13209 usage_merge();
13211 cwd = getcwd(NULL, 0);
13212 if (cwd == NULL) {
13213 error = got_error_from_errno("getcwd");
13214 goto done;
13217 error = got_repo_pack_fds_open(&pack_fds);
13218 if (error != NULL)
13219 goto done;
13221 error = got_worktree_open(&worktree, cwd);
13222 if (error) {
13223 if (error->code == GOT_ERR_NOT_WORKTREE)
13224 error = wrap_not_worktree_error(error,
13225 "merge", cwd);
13226 goto done;
13229 error = get_gitconfig_path(&gitconfig_path);
13230 if (error)
13231 goto done;
13232 error = got_repo_open(&repo,
13233 worktree ? got_worktree_get_repo_path(worktree) : cwd,
13234 gitconfig_path, pack_fds);
13235 if (error != NULL)
13236 goto done;
13238 if (worktree != NULL) {
13239 error = worktree_has_logmsg_ref("merge", worktree, repo);
13240 if (error)
13241 goto done;
13244 error = apply_unveil(got_repo_get_path(repo), 0,
13245 worktree ? got_worktree_get_root_path(worktree) : NULL);
13246 if (error)
13247 goto done;
13249 error = check_rebase_or_histedit_in_progress(worktree);
13250 if (error)
13251 goto done;
13253 error = got_worktree_merge_in_progress(&merge_in_progress, worktree,
13254 repo);
13255 if (error)
13256 goto done;
13258 if (merge_in_progress && !(abort_merge || continue_merge)) {
13259 error = got_error(GOT_ERR_MERGE_BUSY);
13260 goto done;
13263 if (!merge_in_progress && (abort_merge || continue_merge)) {
13264 error = got_error(GOT_ERR_NOT_MERGING);
13265 goto done;
13268 if (abort_merge) {
13269 error = got_worktree_merge_continue(&branch_name,
13270 &branch_tip, &fileindex, worktree, repo);
13271 if (error)
13272 goto done;
13273 error = got_worktree_merge_abort(worktree, fileindex, repo,
13274 abort_progress, &upa);
13275 if (error)
13276 goto done;
13277 printf("Merge of %s aborted\n", branch_name);
13278 goto done; /* nothing else to do */
13281 if (strncmp(got_worktree_get_head_ref_name(worktree),
13282 "refs/heads/", 11) != 0) {
13283 error = got_error_fmt(GOT_ERR_COMMIT_BRANCH,
13284 "work tree's current branch %s is outside the "
13285 "\"refs/heads/\" reference namespace; "
13286 "update -b required",
13287 got_worktree_get_head_ref_name(worktree));
13288 goto done;
13291 error = get_author(&author, repo, worktree);
13292 if (error)
13293 goto done;
13295 error = got_ref_open(&wt_branch, repo,
13296 got_worktree_get_head_ref_name(worktree), 0);
13297 if (error)
13298 goto done;
13299 error = got_ref_resolve(&wt_branch_tip, repo, wt_branch);
13300 if (error)
13301 goto done;
13303 if (continue_merge) {
13304 struct got_object_id *base_commit_id;
13305 base_commit_id = got_worktree_get_base_commit_id(worktree);
13306 if (got_object_id_cmp(wt_branch_tip, base_commit_id) != 0) {
13307 error = got_error(GOT_ERR_MERGE_COMMIT_OUT_OF_DATE);
13308 goto done;
13310 error = got_worktree_merge_continue(&branch_name,
13311 &branch_tip, &fileindex, worktree, repo);
13312 if (error)
13313 goto done;
13314 } else {
13315 error = got_ref_open(&branch, repo, argv[0], 0);
13316 if (error != NULL)
13317 goto done;
13318 branch_name = strdup(got_ref_get_name(branch));
13319 if (branch_name == NULL) {
13320 error = got_error_from_errno("strdup");
13321 goto done;
13323 error = got_ref_resolve(&branch_tip, repo, branch);
13324 if (error)
13325 goto done;
13328 error = got_commit_graph_find_youngest_common_ancestor(&yca_id,
13329 wt_branch_tip, branch_tip, 0, repo,
13330 check_cancelled, NULL);
13331 if (error && error->code != GOT_ERR_ANCESTRY)
13332 goto done;
13334 if (!continue_merge) {
13335 error = check_path_prefix(wt_branch_tip, branch_tip,
13336 got_worktree_get_path_prefix(worktree),
13337 GOT_ERR_MERGE_PATH, repo);
13338 if (error)
13339 goto done;
13340 error = got_worktree_merge_prepare(&fileindex, worktree, repo);
13341 if (error)
13342 goto done;
13343 if (prefer_fast_forward && yca_id &&
13344 got_object_id_cmp(wt_branch_tip, yca_id) == 0) {
13345 struct got_pathlist_head paths;
13346 if (interrupt_merge) {
13347 error = got_error_fmt(GOT_ERR_BAD_OPTION,
13348 "there are no changes to merge since %s "
13349 "is already based on %s; merge cannot be "
13350 "interrupted for amending; -n",
13351 branch_name, got_ref_get_name(wt_branch));
13352 goto done;
13354 printf("Forwarding %s to %s\n",
13355 got_ref_get_name(wt_branch), branch_name);
13356 error = got_ref_change_ref(wt_branch, branch_tip);
13357 if (error)
13358 goto done;
13359 error = got_ref_write(wt_branch, repo);
13360 if (error)
13361 goto done;
13362 error = got_worktree_set_base_commit_id(worktree, repo,
13363 branch_tip);
13364 if (error)
13365 goto done;
13366 TAILQ_INIT(&paths);
13367 error = got_pathlist_append(&paths, "", NULL);
13368 if (error)
13369 goto done;
13370 error = got_worktree_checkout_files(worktree,
13371 &paths, repo, update_progress, &upa,
13372 check_cancelled, NULL);
13373 got_pathlist_free(&paths, GOT_PATHLIST_FREE_NONE);
13374 if (error)
13375 goto done;
13376 if (upa.did_something) {
13377 char *id_str;
13378 error = got_object_id_str(&id_str, branch_tip);
13379 if (error)
13380 goto done;
13381 printf("Updated to commit %s\n", id_str);
13382 free(id_str);
13383 } else
13384 printf("Already up-to-date\n");
13385 print_update_progress_stats(&upa);
13386 goto done;
13388 error = got_worktree_merge_write_refs(worktree, branch, repo);
13389 if (error)
13390 goto done;
13392 error = got_worktree_merge_branch(worktree, fileindex,
13393 yca_id, branch_tip, repo, update_progress, &upa,
13394 check_cancelled, NULL);
13395 if (error)
13396 goto done;
13397 print_merge_progress_stats(&upa);
13398 if (!upa.did_something) {
13399 error = got_worktree_merge_abort(worktree, fileindex,
13400 repo, abort_progress, &upa);
13401 if (error)
13402 goto done;
13403 printf("Already up-to-date\n");
13404 goto done;
13408 if (interrupt_merge) {
13409 error = got_worktree_merge_postpone(worktree, fileindex);
13410 if (error)
13411 goto done;
13412 printf("Merge of %s interrupted on request\n", branch_name);
13413 } else if (upa.conflicts > 0 || upa.missing > 0 ||
13414 upa.not_deleted > 0 || upa.unversioned > 0) {
13415 error = got_worktree_merge_postpone(worktree, fileindex);
13416 if (error)
13417 goto done;
13418 if (upa.conflicts > 0 && upa.missing == 0 &&
13419 upa.not_deleted == 0 && upa.unversioned == 0) {
13420 error = got_error_msg(GOT_ERR_CONFLICTS,
13421 "conflicts must be resolved before merging "
13422 "can continue");
13423 } else if (upa.conflicts > 0) {
13424 error = got_error_msg(GOT_ERR_CONFLICTS,
13425 "conflicts must be resolved before merging "
13426 "can continue; changes destined for some "
13427 "files were not yet merged and "
13428 "should be merged manually if required before the "
13429 "merge operation is continued");
13430 } else {
13431 error = got_error_msg(GOT_ERR_CONFLICTS,
13432 "changes destined for some "
13433 "files were not yet merged and should be "
13434 "merged manually if required before the "
13435 "merge operation is continued");
13437 goto done;
13438 } else {
13439 error = got_worktree_merge_commit(&merge_commit_id, worktree,
13440 fileindex, author, NULL, 1, branch_tip, branch_name,
13441 allow_conflict, repo, continue_merge ? print_status : NULL,
13442 NULL);
13443 if (error)
13444 goto done;
13445 error = got_worktree_merge_complete(worktree, fileindex, repo);
13446 if (error)
13447 goto done;
13448 error = got_object_id_str(&id_str, merge_commit_id);
13449 if (error)
13450 goto done;
13451 printf("Merged %s into %s: %s\n", branch_name,
13452 got_worktree_get_head_ref_name(worktree),
13453 id_str);
13456 done:
13457 free(gitconfig_path);
13458 free(id_str);
13459 free(merge_commit_id);
13460 free(author);
13461 free(branch_tip);
13462 free(branch_name);
13463 free(yca_id);
13464 if (branch)
13465 got_ref_close(branch);
13466 if (wt_branch)
13467 got_ref_close(wt_branch);
13468 if (worktree)
13469 got_worktree_close(worktree);
13470 if (repo) {
13471 const struct got_error *close_err = got_repo_close(repo);
13472 if (error == NULL)
13473 error = close_err;
13475 if (pack_fds) {
13476 const struct got_error *pack_err =
13477 got_repo_pack_fds_close(pack_fds);
13478 if (error == NULL)
13479 error = pack_err;
13481 return error;
13484 __dead static void
13485 usage_stage(void)
13487 fprintf(stderr, "usage: %s stage [-lpS] [-F response-script] "
13488 "[path ...]\n", getprogname());
13489 exit(1);
13492 static const struct got_error *
13493 print_stage(void *arg, unsigned char status, unsigned char staged_status,
13494 const char *path, struct got_object_id *blob_id,
13495 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
13496 int dirfd, const char *de_name)
13498 const struct got_error *err = NULL;
13499 char *id_str = NULL;
13501 if (staged_status != GOT_STATUS_ADD &&
13502 staged_status != GOT_STATUS_MODIFY &&
13503 staged_status != GOT_STATUS_DELETE)
13504 return NULL;
13506 if (staged_status == GOT_STATUS_ADD ||
13507 staged_status == GOT_STATUS_MODIFY)
13508 err = got_object_id_str(&id_str, staged_blob_id);
13509 else
13510 err = got_object_id_str(&id_str, blob_id);
13511 if (err)
13512 return err;
13514 printf("%s %c %s\n", id_str, staged_status, path);
13515 free(id_str);
13516 return NULL;
13519 static const struct got_error *
13520 cmd_stage(int argc, char *argv[])
13522 const struct got_error *error = NULL;
13523 struct got_repository *repo = NULL;
13524 struct got_worktree *worktree = NULL;
13525 char *cwd = NULL;
13526 struct got_pathlist_head paths;
13527 int ch, list_stage = 0, pflag = 0, allow_bad_symlinks = 0;
13528 FILE *patch_script_file = NULL;
13529 const char *patch_script_path = NULL;
13530 struct choose_patch_arg cpa;
13531 int *pack_fds = NULL;
13533 TAILQ_INIT(&paths);
13535 #ifndef PROFILE
13536 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
13537 "unveil", NULL) == -1)
13538 err(1, "pledge");
13539 #endif
13541 while ((ch = getopt(argc, argv, "F:lpS")) != -1) {
13542 switch (ch) {
13543 case 'F':
13544 patch_script_path = optarg;
13545 break;
13546 case 'l':
13547 list_stage = 1;
13548 break;
13549 case 'p':
13550 pflag = 1;
13551 break;
13552 case 'S':
13553 allow_bad_symlinks = 1;
13554 break;
13555 default:
13556 usage_stage();
13557 /* NOTREACHED */
13561 argc -= optind;
13562 argv += optind;
13564 if (list_stage && (pflag || patch_script_path))
13565 errx(1, "-l option cannot be used with other options");
13566 if (patch_script_path && !pflag)
13567 errx(1, "-F option can only be used together with -p option");
13569 cwd = getcwd(NULL, 0);
13570 if (cwd == NULL) {
13571 error = got_error_from_errno("getcwd");
13572 goto done;
13575 error = got_repo_pack_fds_open(&pack_fds);
13576 if (error != NULL)
13577 goto done;
13579 error = got_worktree_open(&worktree, cwd);
13580 if (error) {
13581 if (error->code == GOT_ERR_NOT_WORKTREE)
13582 error = wrap_not_worktree_error(error, "stage", cwd);
13583 goto done;
13586 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
13587 NULL, pack_fds);
13588 if (error != NULL)
13589 goto done;
13591 if (patch_script_path) {
13592 patch_script_file = fopen(patch_script_path, "re");
13593 if (patch_script_file == NULL) {
13594 error = got_error_from_errno2("fopen",
13595 patch_script_path);
13596 goto done;
13599 error = apply_unveil(got_repo_get_path(repo), 0,
13600 got_worktree_get_root_path(worktree));
13601 if (error)
13602 goto done;
13604 error = check_merge_in_progress(worktree, repo);
13605 if (error)
13606 goto done;
13608 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
13609 if (error)
13610 goto done;
13612 if (list_stage)
13613 error = got_worktree_status(worktree, &paths, repo, 0,
13614 print_stage, NULL, check_cancelled, NULL);
13615 else {
13616 cpa.patch_script_file = patch_script_file;
13617 cpa.action = "stage";
13618 error = got_worktree_stage(worktree, &paths,
13619 pflag ? NULL : print_status, NULL,
13620 pflag ? choose_patch : NULL, &cpa,
13621 allow_bad_symlinks, repo);
13623 done:
13624 if (patch_script_file && fclose(patch_script_file) == EOF &&
13625 error == NULL)
13626 error = got_error_from_errno2("fclose", patch_script_path);
13627 if (repo) {
13628 const struct got_error *close_err = got_repo_close(repo);
13629 if (error == NULL)
13630 error = close_err;
13632 if (worktree)
13633 got_worktree_close(worktree);
13634 if (pack_fds) {
13635 const struct got_error *pack_err =
13636 got_repo_pack_fds_close(pack_fds);
13637 if (error == NULL)
13638 error = pack_err;
13640 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
13641 free(cwd);
13642 return error;
13645 __dead static void
13646 usage_unstage(void)
13648 fprintf(stderr, "usage: %s unstage [-p] [-F response-script] "
13649 "[path ...]\n", getprogname());
13650 exit(1);
13654 static const struct got_error *
13655 cmd_unstage(int argc, char *argv[])
13657 const struct got_error *error = NULL;
13658 struct got_repository *repo = NULL;
13659 struct got_worktree *worktree = NULL;
13660 char *cwd = NULL;
13661 struct got_pathlist_head paths;
13662 int ch, pflag = 0;
13663 struct got_update_progress_arg upa;
13664 FILE *patch_script_file = NULL;
13665 const char *patch_script_path = NULL;
13666 struct choose_patch_arg cpa;
13667 int *pack_fds = NULL;
13669 TAILQ_INIT(&paths);
13671 #ifndef PROFILE
13672 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
13673 "unveil", NULL) == -1)
13674 err(1, "pledge");
13675 #endif
13677 while ((ch = getopt(argc, argv, "F:p")) != -1) {
13678 switch (ch) {
13679 case 'F':
13680 patch_script_path = optarg;
13681 break;
13682 case 'p':
13683 pflag = 1;
13684 break;
13685 default:
13686 usage_unstage();
13687 /* NOTREACHED */
13691 argc -= optind;
13692 argv += optind;
13694 if (patch_script_path && !pflag)
13695 errx(1, "-F option can only be used together with -p option");
13697 cwd = getcwd(NULL, 0);
13698 if (cwd == NULL) {
13699 error = got_error_from_errno("getcwd");
13700 goto done;
13703 error = got_repo_pack_fds_open(&pack_fds);
13704 if (error != NULL)
13705 goto done;
13707 error = got_worktree_open(&worktree, cwd);
13708 if (error) {
13709 if (error->code == GOT_ERR_NOT_WORKTREE)
13710 error = wrap_not_worktree_error(error, "unstage", cwd);
13711 goto done;
13714 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
13715 NULL, pack_fds);
13716 if (error != NULL)
13717 goto done;
13719 if (patch_script_path) {
13720 patch_script_file = fopen(patch_script_path, "re");
13721 if (patch_script_file == NULL) {
13722 error = got_error_from_errno2("fopen",
13723 patch_script_path);
13724 goto done;
13728 error = apply_unveil(got_repo_get_path(repo), 0,
13729 got_worktree_get_root_path(worktree));
13730 if (error)
13731 goto done;
13733 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
13734 if (error)
13735 goto done;
13737 cpa.patch_script_file = patch_script_file;
13738 cpa.action = "unstage";
13739 memset(&upa, 0, sizeof(upa));
13740 error = got_worktree_unstage(worktree, &paths, update_progress,
13741 &upa, pflag ? choose_patch : NULL, &cpa, repo);
13742 if (!error)
13743 print_merge_progress_stats(&upa);
13744 done:
13745 if (patch_script_file && fclose(patch_script_file) == EOF &&
13746 error == NULL)
13747 error = got_error_from_errno2("fclose", patch_script_path);
13748 if (repo) {
13749 const struct got_error *close_err = got_repo_close(repo);
13750 if (error == NULL)
13751 error = close_err;
13753 if (worktree)
13754 got_worktree_close(worktree);
13755 if (pack_fds) {
13756 const struct got_error *pack_err =
13757 got_repo_pack_fds_close(pack_fds);
13758 if (error == NULL)
13759 error = pack_err;
13761 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
13762 free(cwd);
13763 return error;
13766 __dead static void
13767 usage_cat(void)
13769 fprintf(stderr, "usage: %s cat [-P] [-c commit] [-r repository-path] "
13770 "arg ...\n", getprogname());
13771 exit(1);
13774 static const struct got_error *
13775 cat_blob(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
13777 const struct got_error *err;
13778 struct got_blob_object *blob;
13779 int fd = -1;
13781 fd = got_opentempfd();
13782 if (fd == -1)
13783 return got_error_from_errno("got_opentempfd");
13785 err = got_object_open_as_blob(&blob, repo, id, 8192, fd);
13786 if (err)
13787 goto done;
13789 err = got_object_blob_dump_to_file(NULL, NULL, NULL, outfile, blob);
13790 done:
13791 if (fd != -1 && close(fd) == -1 && err == NULL)
13792 err = got_error_from_errno("close");
13793 if (blob)
13794 got_object_blob_close(blob);
13795 return err;
13798 static const struct got_error *
13799 cat_tree(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
13801 const struct got_error *err;
13802 struct got_tree_object *tree;
13803 int nentries, i;
13805 err = got_object_open_as_tree(&tree, repo, id);
13806 if (err)
13807 return err;
13809 nentries = got_object_tree_get_nentries(tree);
13810 for (i = 0; i < nentries; i++) {
13811 struct got_tree_entry *te;
13812 char *id_str;
13813 if (sigint_received || sigpipe_received)
13814 break;
13815 te = got_object_tree_get_entry(tree, i);
13816 err = got_object_id_str(&id_str, got_tree_entry_get_id(te));
13817 if (err)
13818 break;
13819 fprintf(outfile, "%s %.7o %s\n", id_str,
13820 got_tree_entry_get_mode(te),
13821 got_tree_entry_get_name(te));
13822 free(id_str);
13825 got_object_tree_close(tree);
13826 return err;
13829 static const struct got_error *
13830 cat_commit(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
13832 const struct got_error *err;
13833 struct got_commit_object *commit;
13834 const struct got_object_id_queue *parent_ids;
13835 struct got_object_qid *pid;
13836 char *id_str = NULL;
13837 const char *logmsg = NULL;
13838 char gmtoff[6];
13840 err = got_object_open_as_commit(&commit, repo, id);
13841 if (err)
13842 return err;
13844 err = got_object_id_str(&id_str, got_object_commit_get_tree_id(commit));
13845 if (err)
13846 goto done;
13848 fprintf(outfile, "%s%s\n", GOT_COMMIT_LABEL_TREE, id_str);
13849 parent_ids = got_object_commit_get_parent_ids(commit);
13850 fprintf(outfile, "numparents %d\n",
13851 got_object_commit_get_nparents(commit));
13852 STAILQ_FOREACH(pid, parent_ids, entry) {
13853 char *pid_str;
13854 err = got_object_id_str(&pid_str, &pid->id);
13855 if (err)
13856 goto done;
13857 fprintf(outfile, "%s%s\n", GOT_COMMIT_LABEL_PARENT, pid_str);
13858 free(pid_str);
13860 got_date_format_gmtoff(gmtoff, sizeof(gmtoff),
13861 got_object_commit_get_author_gmtoff(commit));
13862 fprintf(outfile, "%s%s %lld %s\n", GOT_COMMIT_LABEL_AUTHOR,
13863 got_object_commit_get_author(commit),
13864 (long long)got_object_commit_get_author_time(commit),
13865 gmtoff);
13867 got_date_format_gmtoff(gmtoff, sizeof(gmtoff),
13868 got_object_commit_get_committer_gmtoff(commit));
13869 fprintf(outfile, "%s%s %lld %s\n", GOT_COMMIT_LABEL_COMMITTER,
13870 got_object_commit_get_committer(commit),
13871 (long long)got_object_commit_get_committer_time(commit),
13872 gmtoff);
13874 logmsg = got_object_commit_get_logmsg_raw(commit);
13875 fprintf(outfile, "messagelen %zd\n", strlen(logmsg));
13876 fprintf(outfile, "%s", logmsg);
13877 done:
13878 free(id_str);
13879 got_object_commit_close(commit);
13880 return err;
13883 static const struct got_error *
13884 cat_tag(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
13886 const struct got_error *err;
13887 struct got_tag_object *tag;
13888 char *id_str = NULL;
13889 const char *tagmsg = NULL;
13890 char gmtoff[6];
13892 err = got_object_open_as_tag(&tag, repo, id);
13893 if (err)
13894 return err;
13896 err = got_object_id_str(&id_str, got_object_tag_get_object_id(tag));
13897 if (err)
13898 goto done;
13900 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_OBJECT, id_str);
13902 switch (got_object_tag_get_object_type(tag)) {
13903 case GOT_OBJ_TYPE_BLOB:
13904 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
13905 GOT_OBJ_LABEL_BLOB);
13906 break;
13907 case GOT_OBJ_TYPE_TREE:
13908 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
13909 GOT_OBJ_LABEL_TREE);
13910 break;
13911 case GOT_OBJ_TYPE_COMMIT:
13912 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
13913 GOT_OBJ_LABEL_COMMIT);
13914 break;
13915 case GOT_OBJ_TYPE_TAG:
13916 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
13917 GOT_OBJ_LABEL_TAG);
13918 break;
13919 default:
13920 break;
13923 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TAG,
13924 got_object_tag_get_name(tag));
13926 got_date_format_gmtoff(gmtoff, sizeof(gmtoff),
13927 got_object_tag_get_tagger_gmtoff(tag));
13928 fprintf(outfile, "%s%s %lld %s\n", GOT_TAG_LABEL_TAGGER,
13929 got_object_tag_get_tagger(tag),
13930 (long long)got_object_tag_get_tagger_time(tag),
13931 gmtoff);
13933 tagmsg = got_object_tag_get_message(tag);
13934 fprintf(outfile, "messagelen %zd\n", strlen(tagmsg));
13935 fprintf(outfile, "%s", tagmsg);
13936 done:
13937 free(id_str);
13938 got_object_tag_close(tag);
13939 return err;
13942 static const struct got_error *
13943 cmd_cat(int argc, char *argv[])
13945 const struct got_error *error;
13946 struct got_repository *repo = NULL;
13947 struct got_worktree *worktree = NULL;
13948 char *cwd = NULL, *repo_path = NULL, *label = NULL;
13949 const char *commit_id_str = NULL;
13950 struct got_object_id *id = NULL, *commit_id = NULL;
13951 struct got_commit_object *commit = NULL;
13952 int ch, obj_type, i, force_path = 0;
13953 struct got_reflist_head refs;
13954 int *pack_fds = NULL;
13956 TAILQ_INIT(&refs);
13958 #ifndef PROFILE
13959 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
13960 NULL) == -1)
13961 err(1, "pledge");
13962 #endif
13964 while ((ch = getopt(argc, argv, "c:Pr:")) != -1) {
13965 switch (ch) {
13966 case 'c':
13967 commit_id_str = optarg;
13968 break;
13969 case 'P':
13970 force_path = 1;
13971 break;
13972 case 'r':
13973 repo_path = realpath(optarg, NULL);
13974 if (repo_path == NULL)
13975 return got_error_from_errno2("realpath",
13976 optarg);
13977 got_path_strip_trailing_slashes(repo_path);
13978 break;
13979 default:
13980 usage_cat();
13981 /* NOTREACHED */
13985 argc -= optind;
13986 argv += optind;
13988 cwd = getcwd(NULL, 0);
13989 if (cwd == NULL) {
13990 error = got_error_from_errno("getcwd");
13991 goto done;
13994 error = got_repo_pack_fds_open(&pack_fds);
13995 if (error != NULL)
13996 goto done;
13998 if (repo_path == NULL) {
13999 error = got_worktree_open(&worktree, cwd);
14000 if (error && error->code != GOT_ERR_NOT_WORKTREE)
14001 goto done;
14002 if (worktree) {
14003 repo_path = strdup(
14004 got_worktree_get_repo_path(worktree));
14005 if (repo_path == NULL) {
14006 error = got_error_from_errno("strdup");
14007 goto done;
14010 /* Release work tree lock. */
14011 got_worktree_close(worktree);
14012 worktree = NULL;
14016 if (repo_path == NULL) {
14017 repo_path = strdup(cwd);
14018 if (repo_path == NULL)
14019 return got_error_from_errno("strdup");
14022 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
14023 free(repo_path);
14024 if (error != NULL)
14025 goto done;
14027 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
14028 if (error)
14029 goto done;
14031 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
14032 if (error)
14033 goto done;
14035 if (commit_id_str == NULL)
14036 commit_id_str = GOT_REF_HEAD;
14037 error = got_repo_match_object_id(&commit_id, NULL,
14038 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
14039 if (error)
14040 goto done;
14042 error = got_object_open_as_commit(&commit, repo, commit_id);
14043 if (error)
14044 goto done;
14046 for (i = 0; i < argc; i++) {
14047 if (force_path) {
14048 error = got_object_id_by_path(&id, repo, commit,
14049 argv[i]);
14050 if (error)
14051 break;
14052 } else {
14053 error = got_repo_match_object_id(&id, &label, argv[i],
14054 GOT_OBJ_TYPE_ANY, NULL /* do not resolve tags */,
14055 repo);
14056 if (error) {
14057 if (error->code != GOT_ERR_BAD_OBJ_ID_STR &&
14058 error->code != GOT_ERR_NOT_REF)
14059 break;
14060 error = got_object_id_by_path(&id, repo,
14061 commit, argv[i]);
14062 if (error)
14063 break;
14067 error = got_object_get_type(&obj_type, repo, id);
14068 if (error)
14069 break;
14071 switch (obj_type) {
14072 case GOT_OBJ_TYPE_BLOB:
14073 error = cat_blob(id, repo, stdout);
14074 break;
14075 case GOT_OBJ_TYPE_TREE:
14076 error = cat_tree(id, repo, stdout);
14077 break;
14078 case GOT_OBJ_TYPE_COMMIT:
14079 error = cat_commit(id, repo, stdout);
14080 break;
14081 case GOT_OBJ_TYPE_TAG:
14082 error = cat_tag(id, repo, stdout);
14083 break;
14084 default:
14085 error = got_error(GOT_ERR_OBJ_TYPE);
14086 break;
14088 if (error)
14089 break;
14090 free(label);
14091 label = NULL;
14092 free(id);
14093 id = NULL;
14095 done:
14096 free(label);
14097 free(id);
14098 free(commit_id);
14099 if (commit)
14100 got_object_commit_close(commit);
14101 if (worktree)
14102 got_worktree_close(worktree);
14103 if (repo) {
14104 const struct got_error *close_err = got_repo_close(repo);
14105 if (error == NULL)
14106 error = close_err;
14108 if (pack_fds) {
14109 const struct got_error *pack_err =
14110 got_repo_pack_fds_close(pack_fds);
14111 if (error == NULL)
14112 error = pack_err;
14115 got_ref_list_free(&refs);
14116 return error;
14119 __dead static void
14120 usage_info(void)
14122 fprintf(stderr, "usage: %s info [path ...]\n",
14123 getprogname());
14124 exit(1);
14127 static const struct got_error *
14128 print_path_info(void *arg, const char *path, mode_t mode, time_t mtime,
14129 struct got_object_id *blob_id, struct got_object_id *staged_blob_id,
14130 struct got_object_id *commit_id)
14132 const struct got_error *err = NULL;
14133 char *id_str = NULL;
14134 char datebuf[128];
14135 struct tm mytm, *tm;
14136 struct got_pathlist_head *paths = arg;
14137 struct got_pathlist_entry *pe;
14140 * Clear error indication from any of the path arguments which
14141 * would cause this file index entry to be displayed.
14143 TAILQ_FOREACH(pe, paths, entry) {
14144 if (got_path_cmp(path, pe->path, strlen(path),
14145 pe->path_len) == 0 ||
14146 got_path_is_child(path, pe->path, pe->path_len))
14147 pe->data = NULL; /* no error */
14150 printf(GOT_COMMIT_SEP_STR);
14151 if (S_ISLNK(mode))
14152 printf("symlink: %s\n", path);
14153 else if (S_ISREG(mode)) {
14154 printf("file: %s\n", path);
14155 printf("mode: %o\n", mode & (S_IRWXU | S_IRWXG | S_IRWXO));
14156 } else if (S_ISDIR(mode))
14157 printf("directory: %s\n", path);
14158 else
14159 printf("something: %s\n", path);
14161 tm = localtime_r(&mtime, &mytm);
14162 if (tm == NULL)
14163 return NULL;
14164 if (strftime(datebuf, sizeof(datebuf), "%c %Z", tm) == 0)
14165 return got_error(GOT_ERR_NO_SPACE);
14166 printf("timestamp: %s\n", datebuf);
14168 if (blob_id) {
14169 err = got_object_id_str(&id_str, blob_id);
14170 if (err)
14171 return err;
14172 printf("based on blob: %s\n", id_str);
14173 free(id_str);
14176 if (staged_blob_id) {
14177 err = got_object_id_str(&id_str, staged_blob_id);
14178 if (err)
14179 return err;
14180 printf("based on staged blob: %s\n", id_str);
14181 free(id_str);
14184 if (commit_id) {
14185 err = got_object_id_str(&id_str, commit_id);
14186 if (err)
14187 return err;
14188 printf("based on commit: %s\n", id_str);
14189 free(id_str);
14192 return NULL;
14195 static const struct got_error *
14196 cmd_info(int argc, char *argv[])
14198 const struct got_error *error = NULL;
14199 struct got_worktree *worktree = NULL;
14200 char *cwd = NULL, *id_str = NULL;
14201 struct got_pathlist_head paths;
14202 char *uuidstr = NULL;
14203 int ch, show_files = 0;
14205 TAILQ_INIT(&paths);
14207 #ifndef PROFILE
14208 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
14209 NULL) == -1)
14210 err(1, "pledge");
14211 #endif
14213 while ((ch = getopt(argc, argv, "")) != -1) {
14214 switch (ch) {
14215 default:
14216 usage_info();
14217 /* NOTREACHED */
14221 argc -= optind;
14222 argv += optind;
14224 cwd = getcwd(NULL, 0);
14225 if (cwd == NULL) {
14226 error = got_error_from_errno("getcwd");
14227 goto done;
14230 error = got_worktree_open(&worktree, cwd);
14231 if (error) {
14232 if (error->code == GOT_ERR_NOT_WORKTREE)
14233 error = wrap_not_worktree_error(error, "info", cwd);
14234 goto done;
14237 #ifndef PROFILE
14238 /* Remove "wpath cpath proc exec sendfd" promises. */
14239 if (pledge("stdio rpath flock unveil", NULL) == -1)
14240 err(1, "pledge");
14241 #endif
14242 error = apply_unveil(NULL, 0, got_worktree_get_root_path(worktree));
14243 if (error)
14244 goto done;
14246 if (argc >= 1) {
14247 error = get_worktree_paths_from_argv(&paths, argc, argv,
14248 worktree);
14249 if (error)
14250 goto done;
14251 show_files = 1;
14254 error = got_object_id_str(&id_str,
14255 got_worktree_get_base_commit_id(worktree));
14256 if (error)
14257 goto done;
14259 error = got_worktree_get_uuid(&uuidstr, worktree);
14260 if (error)
14261 goto done;
14263 printf("work tree: %s\n", got_worktree_get_root_path(worktree));
14264 printf("work tree base commit: %s\n", id_str);
14265 printf("work tree path prefix: %s\n",
14266 got_worktree_get_path_prefix(worktree));
14267 printf("work tree branch reference: %s\n",
14268 got_worktree_get_head_ref_name(worktree));
14269 printf("work tree UUID: %s\n", uuidstr);
14270 printf("repository: %s\n", got_worktree_get_repo_path(worktree));
14272 if (show_files) {
14273 struct got_pathlist_entry *pe;
14274 TAILQ_FOREACH(pe, &paths, entry) {
14275 if (pe->path_len == 0)
14276 continue;
14278 * Assume this path will fail. This will be corrected
14279 * in print_path_info() in case the path does suceeed.
14281 pe->data = (void *)got_error(GOT_ERR_BAD_PATH);
14283 error = got_worktree_path_info(worktree, &paths,
14284 print_path_info, &paths, check_cancelled, NULL);
14285 if (error)
14286 goto done;
14287 TAILQ_FOREACH(pe, &paths, entry) {
14288 if (pe->data != NULL) {
14289 const struct got_error *perr;
14291 perr = pe->data;
14292 error = got_error_fmt(perr->code, "%s",
14293 pe->path);
14294 break;
14298 done:
14299 if (worktree)
14300 got_worktree_close(worktree);
14301 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
14302 free(cwd);
14303 free(id_str);
14304 free(uuidstr);
14305 return error;