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_errno("stat");
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 if (worktree)
4792 got_worktree_close(worktree);
4793 if (repo) {
4794 const struct got_error *close_err = got_repo_close(repo);
4795 if (error == NULL)
4796 error = close_err;
4798 if (pack_fds) {
4799 const struct got_error *pack_err =
4800 got_repo_pack_fds_close(pack_fds);
4801 if (error == NULL)
4802 error = pack_err;
4804 if (refs_idmap)
4805 got_reflist_object_id_map_free(refs_idmap);
4806 if (tmpfile && fclose(tmpfile) == EOF && error == NULL)
4807 error = got_error_from_errno("fclose");
4808 got_ref_list_free(&refs);
4809 return error;
4812 __dead static void
4813 usage_diff(void)
4815 fprintf(stderr, "usage: %s diff [-adPsw] [-C number] [-c commit] "
4816 "[-r repository-path] [object1 object2 | path ...]\n",
4817 getprogname());
4818 exit(1);
4821 struct print_diff_arg {
4822 struct got_repository *repo;
4823 struct got_worktree *worktree;
4824 struct got_diffstat_cb_arg *diffstat;
4825 int diff_context;
4826 const char *id_str;
4827 int header_shown;
4828 int diff_staged;
4829 enum got_diff_algorithm diff_algo;
4830 int ignore_whitespace;
4831 int force_text_diff;
4832 FILE *f1;
4833 FILE *f2;
4834 FILE *outfile;
4838 * Create a file which contains the target path of a symlink so we can feed
4839 * it as content to the diff engine.
4841 static const struct got_error *
4842 get_symlink_target_file(int *fd, int dirfd, const char *de_name,
4843 const char *abspath)
4845 const struct got_error *err = NULL;
4846 char target_path[PATH_MAX];
4847 ssize_t target_len, outlen;
4849 *fd = -1;
4851 if (dirfd != -1) {
4852 target_len = readlinkat(dirfd, de_name, target_path, PATH_MAX);
4853 if (target_len == -1)
4854 return got_error_from_errno2("readlinkat", abspath);
4855 } else {
4856 target_len = readlink(abspath, target_path, PATH_MAX);
4857 if (target_len == -1)
4858 return got_error_from_errno2("readlink", abspath);
4861 *fd = got_opentempfd();
4862 if (*fd == -1)
4863 return got_error_from_errno("got_opentempfd");
4865 outlen = write(*fd, target_path, target_len);
4866 if (outlen == -1) {
4867 err = got_error_from_errno("got_opentempfd");
4868 goto done;
4871 if (lseek(*fd, 0, SEEK_SET) == -1) {
4872 err = got_error_from_errno2("lseek", abspath);
4873 goto done;
4875 done:
4876 if (err) {
4877 close(*fd);
4878 *fd = -1;
4880 return err;
4883 static const struct got_error *
4884 print_diff(void *arg, unsigned char status, unsigned char staged_status,
4885 const char *path, struct got_object_id *blob_id,
4886 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
4887 int dirfd, const char *de_name)
4889 struct print_diff_arg *a = arg;
4890 const struct got_error *err = NULL;
4891 struct got_blob_object *blob1 = NULL;
4892 int fd = -1, fd1 = -1, fd2 = -1;
4893 FILE *f2 = NULL;
4894 char *abspath = NULL, *label1 = NULL;
4895 struct stat sb;
4896 off_t size1 = 0;
4897 int f2_exists = 0;
4899 memset(&sb, 0, sizeof(sb));
4901 if (a->diff_staged) {
4902 if (staged_status != GOT_STATUS_MODIFY &&
4903 staged_status != GOT_STATUS_ADD &&
4904 staged_status != GOT_STATUS_DELETE)
4905 return NULL;
4906 } else {
4907 if (staged_status == GOT_STATUS_DELETE)
4908 return NULL;
4909 if (status == GOT_STATUS_NONEXISTENT)
4910 return got_error_set_errno(ENOENT, path);
4911 if (status != GOT_STATUS_MODIFY &&
4912 status != GOT_STATUS_ADD &&
4913 status != GOT_STATUS_DELETE &&
4914 status != GOT_STATUS_CONFLICT)
4915 return NULL;
4918 err = got_opentemp_truncate(a->f1);
4919 if (err)
4920 return got_error_from_errno("got_opentemp_truncate");
4921 err = got_opentemp_truncate(a->f2);
4922 if (err)
4923 return got_error_from_errno("got_opentemp_truncate");
4925 if (!a->header_shown) {
4926 if (fprintf(a->outfile, "diff %s%s\n",
4927 a->diff_staged ? "-s " : "",
4928 got_worktree_get_root_path(a->worktree)) < 0) {
4929 err = got_error_from_errno("fprintf");
4930 goto done;
4932 if (fprintf(a->outfile, "commit - %s\n", a->id_str) < 0) {
4933 err = got_error_from_errno("fprintf");
4934 goto done;
4936 if (fprintf(a->outfile, "path + %s%s\n",
4937 got_worktree_get_root_path(a->worktree),
4938 a->diff_staged ? " (staged changes)" : "") < 0) {
4939 err = got_error_from_errno("fprintf");
4940 goto done;
4942 a->header_shown = 1;
4945 if (a->diff_staged) {
4946 const char *label1 = NULL, *label2 = NULL;
4947 switch (staged_status) {
4948 case GOT_STATUS_MODIFY:
4949 label1 = path;
4950 label2 = path;
4951 break;
4952 case GOT_STATUS_ADD:
4953 label2 = path;
4954 break;
4955 case GOT_STATUS_DELETE:
4956 label1 = path;
4957 break;
4958 default:
4959 return got_error(GOT_ERR_FILE_STATUS);
4961 fd1 = got_opentempfd();
4962 if (fd1 == -1) {
4963 err = got_error_from_errno("got_opentempfd");
4964 goto done;
4966 fd2 = got_opentempfd();
4967 if (fd2 == -1) {
4968 err = got_error_from_errno("got_opentempfd");
4969 goto done;
4971 err = got_diff_objects_as_blobs(NULL, NULL, a->f1, a->f2,
4972 fd1, fd2, blob_id, staged_blob_id, label1, label2,
4973 a->diff_algo, a->diff_context, a->ignore_whitespace,
4974 a->force_text_diff, a->diffstat, a->repo, a->outfile);
4975 goto done;
4978 fd1 = got_opentempfd();
4979 if (fd1 == -1) {
4980 err = got_error_from_errno("got_opentempfd");
4981 goto done;
4984 if (staged_status == GOT_STATUS_ADD ||
4985 staged_status == GOT_STATUS_MODIFY) {
4986 char *id_str;
4987 err = got_object_open_as_blob(&blob1, a->repo, staged_blob_id,
4988 8192, fd1);
4989 if (err)
4990 goto done;
4991 err = got_object_id_str(&id_str, staged_blob_id);
4992 if (err)
4993 goto done;
4994 if (asprintf(&label1, "%s (staged)", id_str) == -1) {
4995 err = got_error_from_errno("asprintf");
4996 free(id_str);
4997 goto done;
4999 free(id_str);
5000 } else if (status != GOT_STATUS_ADD) {
5001 err = got_object_open_as_blob(&blob1, a->repo, blob_id, 8192,
5002 fd1);
5003 if (err)
5004 goto done;
5007 if (status != GOT_STATUS_DELETE) {
5008 if (asprintf(&abspath, "%s/%s",
5009 got_worktree_get_root_path(a->worktree), path) == -1) {
5010 err = got_error_from_errno("asprintf");
5011 goto done;
5014 if (dirfd != -1) {
5015 fd = openat(dirfd, de_name,
5016 O_RDONLY | O_NOFOLLOW | O_CLOEXEC);
5017 if (fd == -1) {
5018 if (!got_err_open_nofollow_on_symlink()) {
5019 err = got_error_from_errno2("openat",
5020 abspath);
5021 goto done;
5023 err = get_symlink_target_file(&fd, dirfd,
5024 de_name, abspath);
5025 if (err)
5026 goto done;
5028 } else {
5029 fd = open(abspath, O_RDONLY | O_NOFOLLOW | O_CLOEXEC);
5030 if (fd == -1) {
5031 if (!got_err_open_nofollow_on_symlink()) {
5032 err = got_error_from_errno2("open",
5033 abspath);
5034 goto done;
5036 err = get_symlink_target_file(&fd, dirfd,
5037 de_name, abspath);
5038 if (err)
5039 goto done;
5042 if (fstatat(fd, abspath, &sb, AT_SYMLINK_NOFOLLOW) == -1) {
5043 err = got_error_from_errno2("fstatat", abspath);
5044 goto done;
5046 f2 = fdopen(fd, "r");
5047 if (f2 == NULL) {
5048 err = got_error_from_errno2("fdopen", abspath);
5049 goto done;
5051 fd = -1;
5052 f2_exists = 1;
5055 if (blob1) {
5056 err = got_object_blob_dump_to_file(&size1, NULL, NULL,
5057 a->f1, blob1);
5058 if (err)
5059 goto done;
5062 err = got_diff_blob_file(blob1, a->f1, size1, label1, f2 ? f2 : a->f2,
5063 f2_exists, &sb, path, GOT_DIFF_ALGORITHM_PATIENCE, a->diff_context,
5064 a->ignore_whitespace, a->force_text_diff, a->diffstat, a->outfile);
5065 done:
5066 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
5067 err = got_error_from_errno("close");
5068 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
5069 err = got_error_from_errno("close");
5070 if (blob1)
5071 got_object_blob_close(blob1);
5072 if (fd != -1 && close(fd) == -1 && err == NULL)
5073 err = got_error_from_errno("close");
5074 if (f2 && fclose(f2) == EOF && err == NULL)
5075 err = got_error_from_errno("fclose");
5076 free(abspath);
5077 return err;
5080 static const struct got_error *
5081 cmd_diff(int argc, char *argv[])
5083 const struct got_error *error;
5084 struct got_repository *repo = NULL;
5085 struct got_worktree *worktree = NULL;
5086 char *cwd = NULL, *repo_path = NULL;
5087 const char *commit_args[2] = { NULL, NULL };
5088 int ncommit_args = 0;
5089 struct got_object_id *ids[2] = { NULL, NULL };
5090 char *labels[2] = { NULL, NULL };
5091 int type1 = GOT_OBJ_TYPE_ANY, type2 = GOT_OBJ_TYPE_ANY;
5092 int diff_context = 3, diff_staged = 0, ignore_whitespace = 0, ch, i;
5093 int force_text_diff = 0, force_path = 0, rflag = 0, show_diffstat = 0;
5094 const char *errstr;
5095 struct got_reflist_head refs;
5096 struct got_pathlist_head diffstat_paths, paths;
5097 FILE *f1 = NULL, *f2 = NULL, *outfile = NULL;
5098 int fd1 = -1, fd2 = -1;
5099 int *pack_fds = NULL;
5100 struct got_diffstat_cb_arg dsa;
5102 memset(&dsa, 0, sizeof(dsa));
5104 TAILQ_INIT(&refs);
5105 TAILQ_INIT(&paths);
5106 TAILQ_INIT(&diffstat_paths);
5108 #ifndef PROFILE
5109 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
5110 NULL) == -1)
5111 err(1, "pledge");
5112 #endif
5114 while ((ch = getopt(argc, argv, "aC:c:dPr:sw")) != -1) {
5115 switch (ch) {
5116 case 'a':
5117 force_text_diff = 1;
5118 break;
5119 case 'C':
5120 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
5121 &errstr);
5122 if (errstr != NULL)
5123 errx(1, "number of context lines is %s: %s",
5124 errstr, optarg);
5125 break;
5126 case 'c':
5127 if (ncommit_args >= 2)
5128 errx(1, "too many -c options used");
5129 commit_args[ncommit_args++] = optarg;
5130 break;
5131 case 'd':
5132 show_diffstat = 1;
5133 break;
5134 case 'P':
5135 force_path = 1;
5136 break;
5137 case 'r':
5138 repo_path = realpath(optarg, NULL);
5139 if (repo_path == NULL)
5140 return got_error_from_errno2("realpath",
5141 optarg);
5142 got_path_strip_trailing_slashes(repo_path);
5143 rflag = 1;
5144 break;
5145 case 's':
5146 diff_staged = 1;
5147 break;
5148 case 'w':
5149 ignore_whitespace = 1;
5150 break;
5151 default:
5152 usage_diff();
5153 /* NOTREACHED */
5157 argc -= optind;
5158 argv += optind;
5160 cwd = getcwd(NULL, 0);
5161 if (cwd == NULL) {
5162 error = got_error_from_errno("getcwd");
5163 goto done;
5166 error = got_repo_pack_fds_open(&pack_fds);
5167 if (error != NULL)
5168 goto done;
5170 if (repo_path == NULL) {
5171 error = got_worktree_open(&worktree, cwd);
5172 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5173 goto done;
5174 else
5175 error = NULL;
5176 if (worktree) {
5177 repo_path =
5178 strdup(got_worktree_get_repo_path(worktree));
5179 if (repo_path == NULL) {
5180 error = got_error_from_errno("strdup");
5181 goto done;
5183 } else {
5184 repo_path = strdup(cwd);
5185 if (repo_path == NULL) {
5186 error = got_error_from_errno("strdup");
5187 goto done;
5192 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
5193 free(repo_path);
5194 if (error != NULL)
5195 goto done;
5197 if (show_diffstat) {
5198 dsa.paths = &diffstat_paths;
5199 dsa.force_text = force_text_diff;
5200 dsa.ignore_ws = ignore_whitespace;
5201 dsa.diff_algo = GOT_DIFF_ALGORITHM_PATIENCE;
5204 if (rflag || worktree == NULL || ncommit_args > 0) {
5205 if (force_path) {
5206 error = got_error_msg(GOT_ERR_NOT_IMPL,
5207 "-P option can only be used when diffing "
5208 "a work tree");
5209 goto done;
5211 if (diff_staged) {
5212 error = got_error_msg(GOT_ERR_NOT_IMPL,
5213 "-s option can only be used when diffing "
5214 "a work tree");
5215 goto done;
5219 error = apply_unveil(got_repo_get_path(repo), 1,
5220 worktree ? got_worktree_get_root_path(worktree) : NULL);
5221 if (error)
5222 goto done;
5224 if ((!force_path && argc == 2) || ncommit_args > 0) {
5225 int obj_type = (ncommit_args > 0 ?
5226 GOT_OBJ_TYPE_COMMIT : GOT_OBJ_TYPE_ANY);
5227 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
5228 NULL);
5229 if (error)
5230 goto done;
5231 for (i = 0; i < (ncommit_args > 0 ? ncommit_args : argc); i++) {
5232 const char *arg;
5233 if (ncommit_args > 0)
5234 arg = commit_args[i];
5235 else
5236 arg = argv[i];
5237 error = got_repo_match_object_id(&ids[i], &labels[i],
5238 arg, obj_type, &refs, repo);
5239 if (error) {
5240 if (error->code != GOT_ERR_NOT_REF &&
5241 error->code != GOT_ERR_NO_OBJ)
5242 goto done;
5243 if (ncommit_args > 0)
5244 goto done;
5245 error = NULL;
5246 break;
5251 f1 = got_opentemp();
5252 if (f1 == NULL) {
5253 error = got_error_from_errno("got_opentemp");
5254 goto done;
5257 f2 = got_opentemp();
5258 if (f2 == NULL) {
5259 error = got_error_from_errno("got_opentemp");
5260 goto done;
5263 outfile = got_opentemp();
5264 if (outfile == NULL) {
5265 error = got_error_from_errno("got_opentemp");
5266 goto done;
5269 if (ncommit_args == 0 && (ids[0] == NULL || ids[1] == NULL)) {
5270 struct print_diff_arg arg;
5271 char *id_str;
5273 if (worktree == NULL) {
5274 if (argc == 2 && ids[0] == NULL) {
5275 error = got_error_path(argv[0], GOT_ERR_NO_OBJ);
5276 goto done;
5277 } else if (argc == 2 && ids[1] == NULL) {
5278 error = got_error_path(argv[1], GOT_ERR_NO_OBJ);
5279 goto done;
5280 } else if (argc > 0) {
5281 error = got_error_fmt(GOT_ERR_NOT_WORKTREE,
5282 "%s", "specified paths cannot be resolved");
5283 goto done;
5284 } else {
5285 error = got_error(GOT_ERR_NOT_WORKTREE);
5286 goto done;
5290 error = get_worktree_paths_from_argv(&paths, argc, argv,
5291 worktree);
5292 if (error)
5293 goto done;
5295 error = got_object_id_str(&id_str,
5296 got_worktree_get_base_commit_id(worktree));
5297 if (error)
5298 goto done;
5299 arg.repo = repo;
5300 arg.worktree = worktree;
5301 arg.diff_algo = GOT_DIFF_ALGORITHM_PATIENCE;
5302 arg.diff_context = diff_context;
5303 arg.id_str = id_str;
5304 arg.header_shown = 0;
5305 arg.diff_staged = diff_staged;
5306 arg.ignore_whitespace = ignore_whitespace;
5307 arg.force_text_diff = force_text_diff;
5308 arg.diffstat = show_diffstat ? &dsa : NULL;
5309 arg.f1 = f1;
5310 arg.f2 = f2;
5311 arg.outfile = outfile;
5313 error = got_worktree_status(worktree, &paths, repo, 0,
5314 print_diff, &arg, check_cancelled, NULL);
5315 free(id_str);
5316 if (error)
5317 goto done;
5319 if (show_diffstat && dsa.nfiles > 0) {
5320 char *header;
5322 if (asprintf(&header, "diffstat %s%s",
5323 diff_staged ? "-s " : "",
5324 got_worktree_get_root_path(worktree)) == -1) {
5325 error = got_error_from_errno("asprintf");
5326 goto done;
5329 error = print_diffstat(&dsa, header);
5330 free(header);
5331 if (error)
5332 goto done;
5335 error = printfile(outfile);
5336 goto done;
5339 if (ncommit_args == 1) {
5340 struct got_commit_object *commit;
5341 error = got_object_open_as_commit(&commit, repo, ids[0]);
5342 if (error)
5343 goto done;
5345 labels[1] = labels[0];
5346 ids[1] = ids[0];
5347 if (got_object_commit_get_nparents(commit) > 0) {
5348 const struct got_object_id_queue *pids;
5349 struct got_object_qid *pid;
5350 pids = got_object_commit_get_parent_ids(commit);
5351 pid = STAILQ_FIRST(pids);
5352 ids[0] = got_object_id_dup(&pid->id);
5353 if (ids[0] == NULL) {
5354 error = got_error_from_errno(
5355 "got_object_id_dup");
5356 got_object_commit_close(commit);
5357 goto done;
5359 error = got_object_id_str(&labels[0], ids[0]);
5360 if (error) {
5361 got_object_commit_close(commit);
5362 goto done;
5364 } else {
5365 ids[0] = NULL;
5366 labels[0] = strdup("/dev/null");
5367 if (labels[0] == NULL) {
5368 error = got_error_from_errno("strdup");
5369 got_object_commit_close(commit);
5370 goto done;
5374 got_object_commit_close(commit);
5377 if (ncommit_args == 0 && argc > 2) {
5378 error = got_error_msg(GOT_ERR_BAD_PATH,
5379 "path arguments cannot be used when diffing two objects");
5380 goto done;
5383 if (ids[0]) {
5384 error = got_object_get_type(&type1, repo, ids[0]);
5385 if (error)
5386 goto done;
5389 error = got_object_get_type(&type2, repo, ids[1]);
5390 if (error)
5391 goto done;
5392 if (type1 != GOT_OBJ_TYPE_ANY && type1 != type2) {
5393 error = got_error(GOT_ERR_OBJ_TYPE);
5394 goto done;
5396 if (type1 == GOT_OBJ_TYPE_BLOB && argc > 2) {
5397 error = got_error_msg(GOT_ERR_OBJ_TYPE,
5398 "path arguments cannot be used when diffing blobs");
5399 goto done;
5402 for (i = 0; ncommit_args > 0 && i < argc; i++) {
5403 char *in_repo_path;
5404 struct got_pathlist_entry *new;
5405 if (worktree) {
5406 const char *prefix;
5407 char *p;
5408 error = got_worktree_resolve_path(&p, worktree,
5409 argv[i]);
5410 if (error)
5411 goto done;
5412 prefix = got_worktree_get_path_prefix(worktree);
5413 while (prefix[0] == '/')
5414 prefix++;
5415 if (asprintf(&in_repo_path, "%s%s%s", prefix,
5416 (p[0] != '\0' && prefix[0] != '\0') ? "/" : "",
5417 p) == -1) {
5418 error = got_error_from_errno("asprintf");
5419 free(p);
5420 goto done;
5422 free(p);
5423 } else {
5424 char *mapped_path, *s;
5425 error = got_repo_map_path(&mapped_path, repo, argv[i]);
5426 if (error)
5427 goto done;
5428 s = mapped_path;
5429 while (s[0] == '/')
5430 s++;
5431 in_repo_path = strdup(s);
5432 if (in_repo_path == NULL) {
5433 error = got_error_from_errno("asprintf");
5434 free(mapped_path);
5435 goto done;
5437 free(mapped_path);
5440 error = got_pathlist_insert(&new, &paths, in_repo_path, NULL);
5441 if (error || new == NULL /* duplicate */)
5442 free(in_repo_path);
5443 if (error)
5444 goto done;
5447 if (worktree) {
5448 /* Release work tree lock. */
5449 got_worktree_close(worktree);
5450 worktree = NULL;
5453 fd1 = got_opentempfd();
5454 if (fd1 == -1) {
5455 error = got_error_from_errno("got_opentempfd");
5456 goto done;
5459 fd2 = got_opentempfd();
5460 if (fd2 == -1) {
5461 error = got_error_from_errno("got_opentempfd");
5462 goto done;
5465 switch (type1 == GOT_OBJ_TYPE_ANY ? type2 : type1) {
5466 case GOT_OBJ_TYPE_BLOB:
5467 error = got_diff_objects_as_blobs(NULL, NULL, f1, f2,
5468 fd1, fd2, ids[0], ids[1], NULL, NULL,
5469 GOT_DIFF_ALGORITHM_PATIENCE, diff_context,
5470 ignore_whitespace, force_text_diff,
5471 show_diffstat ? &dsa : NULL, repo, outfile);
5472 break;
5473 case GOT_OBJ_TYPE_TREE:
5474 error = got_diff_objects_as_trees(NULL, NULL, f1, f2, fd1, fd2,
5475 ids[0], ids[1], &paths, "", "",
5476 GOT_DIFF_ALGORITHM_PATIENCE, diff_context,
5477 ignore_whitespace, force_text_diff,
5478 show_diffstat ? &dsa : NULL, repo, outfile);
5479 break;
5480 case GOT_OBJ_TYPE_COMMIT:
5481 fprintf(outfile, "diff %s %s\n", labels[0], labels[1]);
5482 error = got_diff_objects_as_commits(NULL, NULL, f1, f2,
5483 fd1, fd2, ids[0], ids[1], &paths,
5484 GOT_DIFF_ALGORITHM_PATIENCE, diff_context,
5485 ignore_whitespace, force_text_diff,
5486 show_diffstat ? &dsa : NULL, repo, outfile);
5487 break;
5488 default:
5489 error = got_error(GOT_ERR_OBJ_TYPE);
5491 if (error)
5492 goto done;
5494 if (show_diffstat && dsa.nfiles > 0) {
5495 char *header = NULL;
5497 if (asprintf(&header, "diffstat %s %s",
5498 labels[0], labels[1]) == -1) {
5499 error = got_error_from_errno("asprintf");
5500 goto done;
5503 error = print_diffstat(&dsa, header);
5504 free(header);
5505 if (error)
5506 goto done;
5509 error = printfile(outfile);
5511 done:
5512 free(labels[0]);
5513 free(labels[1]);
5514 free(ids[0]);
5515 free(ids[1]);
5516 if (worktree)
5517 got_worktree_close(worktree);
5518 if (repo) {
5519 const struct got_error *close_err = got_repo_close(repo);
5520 if (error == NULL)
5521 error = close_err;
5523 if (pack_fds) {
5524 const struct got_error *pack_err =
5525 got_repo_pack_fds_close(pack_fds);
5526 if (error == NULL)
5527 error = pack_err;
5529 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
5530 got_pathlist_free(&diffstat_paths, GOT_PATHLIST_FREE_ALL);
5531 got_ref_list_free(&refs);
5532 if (outfile && fclose(outfile) == EOF && error == NULL)
5533 error = got_error_from_errno("fclose");
5534 if (f1 && fclose(f1) == EOF && error == NULL)
5535 error = got_error_from_errno("fclose");
5536 if (f2 && fclose(f2) == EOF && error == NULL)
5537 error = got_error_from_errno("fclose");
5538 if (fd1 != -1 && close(fd1) == -1 && error == NULL)
5539 error = got_error_from_errno("close");
5540 if (fd2 != -1 && close(fd2) == -1 && error == NULL)
5541 error = got_error_from_errno("close");
5542 return error;
5545 __dead static void
5546 usage_blame(void)
5548 fprintf(stderr,
5549 "usage: %s blame [-c commit] [-r repository-path] path\n",
5550 getprogname());
5551 exit(1);
5554 struct blame_line {
5555 int annotated;
5556 char *id_str;
5557 char *committer;
5558 char datebuf[11]; /* YYYY-MM-DD + NUL */
5561 struct blame_cb_args {
5562 struct blame_line *lines;
5563 int nlines;
5564 int nlines_prec;
5565 int lineno_cur;
5566 off_t *line_offsets;
5567 FILE *f;
5568 struct got_repository *repo;
5571 static const struct got_error *
5572 blame_cb(void *arg, int nlines, int lineno,
5573 struct got_commit_object *commit, struct got_object_id *id)
5575 const struct got_error *err = NULL;
5576 struct blame_cb_args *a = arg;
5577 struct blame_line *bline;
5578 char *line = NULL;
5579 size_t linesize = 0;
5580 off_t offset;
5581 struct tm tm;
5582 time_t committer_time;
5584 if (nlines != a->nlines ||
5585 (lineno != -1 && lineno < 1) || lineno > a->nlines)
5586 return got_error(GOT_ERR_RANGE);
5588 if (sigint_received)
5589 return got_error(GOT_ERR_ITER_COMPLETED);
5591 if (lineno == -1)
5592 return NULL; /* no change in this commit */
5594 /* Annotate this line. */
5595 bline = &a->lines[lineno - 1];
5596 if (bline->annotated)
5597 return NULL;
5598 err = got_object_id_str(&bline->id_str, id);
5599 if (err)
5600 return err;
5602 bline->committer = strdup(got_object_commit_get_committer(commit));
5603 if (bline->committer == NULL) {
5604 err = got_error_from_errno("strdup");
5605 goto done;
5608 committer_time = got_object_commit_get_committer_time(commit);
5609 if (gmtime_r(&committer_time, &tm) == NULL)
5610 return got_error_from_errno("gmtime_r");
5611 if (strftime(bline->datebuf, sizeof(bline->datebuf), "%G-%m-%d",
5612 &tm) == 0) {
5613 err = got_error(GOT_ERR_NO_SPACE);
5614 goto done;
5616 bline->annotated = 1;
5618 /* Print lines annotated so far. */
5619 bline = &a->lines[a->lineno_cur - 1];
5620 if (!bline->annotated)
5621 goto done;
5623 offset = a->line_offsets[a->lineno_cur - 1];
5624 if (fseeko(a->f, offset, SEEK_SET) == -1) {
5625 err = got_error_from_errno("fseeko");
5626 goto done;
5629 while (a->lineno_cur <= a->nlines && bline->annotated) {
5630 char *smallerthan, *at, *nl, *committer;
5631 size_t len;
5633 if (getline(&line, &linesize, a->f) == -1) {
5634 if (ferror(a->f))
5635 err = got_error_from_errno("getline");
5636 break;
5639 committer = bline->committer;
5640 smallerthan = strchr(committer, '<');
5641 if (smallerthan && smallerthan[1] != '\0')
5642 committer = smallerthan + 1;
5643 at = strchr(committer, '@');
5644 if (at)
5645 *at = '\0';
5646 len = strlen(committer);
5647 if (len >= 9)
5648 committer[8] = '\0';
5650 nl = strchr(line, '\n');
5651 if (nl)
5652 *nl = '\0';
5653 printf("%.*d) %.8s %s %-8s %s\n", a->nlines_prec, a->lineno_cur,
5654 bline->id_str, bline->datebuf, committer, line);
5656 a->lineno_cur++;
5657 bline = &a->lines[a->lineno_cur - 1];
5659 done:
5660 free(line);
5661 return err;
5664 static const struct got_error *
5665 cmd_blame(int argc, char *argv[])
5667 const struct got_error *error;
5668 struct got_repository *repo = NULL;
5669 struct got_worktree *worktree = NULL;
5670 char *path, *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
5671 char *link_target = NULL;
5672 struct got_object_id *obj_id = NULL;
5673 struct got_object_id *commit_id = NULL;
5674 struct got_commit_object *commit = NULL;
5675 struct got_blob_object *blob = NULL;
5676 char *commit_id_str = NULL;
5677 struct blame_cb_args bca;
5678 int ch, obj_type, i, fd1 = -1, fd2 = -1, fd3 = -1;
5679 off_t filesize;
5680 int *pack_fds = NULL;
5681 FILE *f1 = NULL, *f2 = NULL;
5683 fd1 = got_opentempfd();
5684 if (fd1 == -1)
5685 return got_error_from_errno("got_opentempfd");
5687 memset(&bca, 0, sizeof(bca));
5689 #ifndef PROFILE
5690 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
5691 NULL) == -1)
5692 err(1, "pledge");
5693 #endif
5695 while ((ch = getopt(argc, argv, "c:r:")) != -1) {
5696 switch (ch) {
5697 case 'c':
5698 commit_id_str = optarg;
5699 break;
5700 case 'r':
5701 repo_path = realpath(optarg, NULL);
5702 if (repo_path == NULL)
5703 return got_error_from_errno2("realpath",
5704 optarg);
5705 got_path_strip_trailing_slashes(repo_path);
5706 break;
5707 default:
5708 usage_blame();
5709 /* NOTREACHED */
5713 argc -= optind;
5714 argv += optind;
5716 if (argc == 1)
5717 path = argv[0];
5718 else
5719 usage_blame();
5721 cwd = getcwd(NULL, 0);
5722 if (cwd == NULL) {
5723 error = got_error_from_errno("getcwd");
5724 goto done;
5727 error = got_repo_pack_fds_open(&pack_fds);
5728 if (error != NULL)
5729 goto done;
5731 if (repo_path == NULL) {
5732 error = got_worktree_open(&worktree, cwd);
5733 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5734 goto done;
5735 else
5736 error = NULL;
5737 if (worktree) {
5738 repo_path =
5739 strdup(got_worktree_get_repo_path(worktree));
5740 if (repo_path == NULL) {
5741 error = got_error_from_errno("strdup");
5742 if (error)
5743 goto done;
5745 } else {
5746 repo_path = strdup(cwd);
5747 if (repo_path == NULL) {
5748 error = got_error_from_errno("strdup");
5749 goto done;
5754 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
5755 if (error != NULL)
5756 goto done;
5758 if (worktree) {
5759 const char *prefix = got_worktree_get_path_prefix(worktree);
5760 char *p;
5762 error = got_worktree_resolve_path(&p, worktree, path);
5763 if (error)
5764 goto done;
5765 if (asprintf(&in_repo_path, "%s%s%s", prefix,
5766 (p[0] != '\0' && !got_path_is_root_dir(prefix)) ? "/" : "",
5767 p) == -1) {
5768 error = got_error_from_errno("asprintf");
5769 free(p);
5770 goto done;
5772 free(p);
5773 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5774 } else {
5775 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5776 if (error)
5777 goto done;
5778 error = got_repo_map_path(&in_repo_path, repo, path);
5780 if (error)
5781 goto done;
5783 if (commit_id_str == NULL) {
5784 struct got_reference *head_ref;
5785 error = got_ref_open(&head_ref, repo, worktree ?
5786 got_worktree_get_head_ref_name(worktree) : GOT_REF_HEAD, 0);
5787 if (error != NULL)
5788 goto done;
5789 error = got_ref_resolve(&commit_id, repo, head_ref);
5790 got_ref_close(head_ref);
5791 if (error != NULL)
5792 goto done;
5793 } else {
5794 struct got_reflist_head refs;
5795 TAILQ_INIT(&refs);
5796 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
5797 NULL);
5798 if (error)
5799 goto done;
5800 error = got_repo_match_object_id(&commit_id, NULL,
5801 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
5802 got_ref_list_free(&refs);
5803 if (error)
5804 goto done;
5807 if (worktree) {
5808 /* Release work tree lock. */
5809 got_worktree_close(worktree);
5810 worktree = NULL;
5813 error = got_object_open_as_commit(&commit, repo, commit_id);
5814 if (error)
5815 goto done;
5817 error = got_object_resolve_symlinks(&link_target, in_repo_path,
5818 commit, repo);
5819 if (error)
5820 goto done;
5822 error = got_object_id_by_path(&obj_id, repo, commit,
5823 link_target ? link_target : in_repo_path);
5824 if (error)
5825 goto done;
5827 error = got_object_get_type(&obj_type, repo, obj_id);
5828 if (error)
5829 goto done;
5831 if (obj_type != GOT_OBJ_TYPE_BLOB) {
5832 error = got_error_path(link_target ? link_target : in_repo_path,
5833 GOT_ERR_OBJ_TYPE);
5834 goto done;
5837 error = got_object_open_as_blob(&blob, repo, obj_id, 8192, fd1);
5838 if (error)
5839 goto done;
5840 bca.f = got_opentemp();
5841 if (bca.f == NULL) {
5842 error = got_error_from_errno("got_opentemp");
5843 goto done;
5845 error = got_object_blob_dump_to_file(&filesize, &bca.nlines,
5846 &bca.line_offsets, bca.f, blob);
5847 if (error || bca.nlines == 0)
5848 goto done;
5850 /* Don't include \n at EOF in the blame line count. */
5851 if (bca.line_offsets[bca.nlines - 1] == filesize)
5852 bca.nlines--;
5854 bca.lines = calloc(bca.nlines, sizeof(*bca.lines));
5855 if (bca.lines == NULL) {
5856 error = got_error_from_errno("calloc");
5857 goto done;
5859 bca.lineno_cur = 1;
5860 bca.nlines_prec = 0;
5861 i = bca.nlines;
5862 while (i > 0) {
5863 i /= 10;
5864 bca.nlines_prec++;
5866 bca.repo = repo;
5868 fd2 = got_opentempfd();
5869 if (fd2 == -1) {
5870 error = got_error_from_errno("got_opentempfd");
5871 goto done;
5873 fd3 = got_opentempfd();
5874 if (fd3 == -1) {
5875 error = got_error_from_errno("got_opentempfd");
5876 goto done;
5878 f1 = got_opentemp();
5879 if (f1 == NULL) {
5880 error = got_error_from_errno("got_opentemp");
5881 goto done;
5883 f2 = got_opentemp();
5884 if (f2 == NULL) {
5885 error = got_error_from_errno("got_opentemp");
5886 goto done;
5888 error = got_blame(link_target ? link_target : in_repo_path, commit_id,
5889 repo, GOT_DIFF_ALGORITHM_PATIENCE, blame_cb, &bca,
5890 check_cancelled, NULL, fd2, fd3, f1, f2);
5891 done:
5892 free(in_repo_path);
5893 free(link_target);
5894 free(repo_path);
5895 free(cwd);
5896 free(commit_id);
5897 free(obj_id);
5898 if (commit)
5899 got_object_commit_close(commit);
5901 if (fd1 != -1 && close(fd1) == -1 && error == NULL)
5902 error = got_error_from_errno("close");
5903 if (fd2 != -1 && close(fd2) == -1 && error == NULL)
5904 error = got_error_from_errno("close");
5905 if (fd3 != -1 && close(fd3) == -1 && error == NULL)
5906 error = got_error_from_errno("close");
5907 if (f1 && fclose(f1) == EOF && error == NULL)
5908 error = got_error_from_errno("fclose");
5909 if (f2 && fclose(f2) == EOF && error == NULL)
5910 error = got_error_from_errno("fclose");
5912 if (blob)
5913 got_object_blob_close(blob);
5914 if (worktree)
5915 got_worktree_close(worktree);
5916 if (repo) {
5917 const struct got_error *close_err = got_repo_close(repo);
5918 if (error == NULL)
5919 error = close_err;
5921 if (pack_fds) {
5922 const struct got_error *pack_err =
5923 got_repo_pack_fds_close(pack_fds);
5924 if (error == NULL)
5925 error = pack_err;
5927 if (bca.lines) {
5928 for (i = 0; i < bca.nlines; i++) {
5929 struct blame_line *bline = &bca.lines[i];
5930 free(bline->id_str);
5931 free(bline->committer);
5933 free(bca.lines);
5935 free(bca.line_offsets);
5936 if (bca.f && fclose(bca.f) == EOF && error == NULL)
5937 error = got_error_from_errno("fclose");
5938 return error;
5941 __dead static void
5942 usage_tree(void)
5944 fprintf(stderr, "usage: %s tree [-iR] [-c commit] [-r repository-path] "
5945 "[path]\n", getprogname());
5946 exit(1);
5949 static const struct got_error *
5950 print_entry(struct got_tree_entry *te, const char *id, const char *path,
5951 const char *root_path, struct got_repository *repo)
5953 const struct got_error *err = NULL;
5954 int is_root_path = (strcmp(path, root_path) == 0);
5955 const char *modestr = "";
5956 mode_t mode = got_tree_entry_get_mode(te);
5957 char *link_target = NULL;
5959 path += strlen(root_path);
5960 while (path[0] == '/')
5961 path++;
5963 if (got_object_tree_entry_is_submodule(te))
5964 modestr = "$";
5965 else if (S_ISLNK(mode)) {
5966 int i;
5968 err = got_tree_entry_get_symlink_target(&link_target, te, repo);
5969 if (err)
5970 return err;
5971 for (i = 0; link_target[i] != '\0'; i++) {
5972 if (!isprint((unsigned char)link_target[i]))
5973 link_target[i] = '?';
5976 modestr = "@";
5978 else if (S_ISDIR(mode))
5979 modestr = "/";
5980 else if (mode & S_IXUSR)
5981 modestr = "*";
5983 printf("%s%s%s%s%s%s%s\n", id ? id : "", path,
5984 is_root_path ? "" : "/", got_tree_entry_get_name(te), modestr,
5985 link_target ? " -> ": "", link_target ? link_target : "");
5987 free(link_target);
5988 return NULL;
5991 static const struct got_error *
5992 print_tree(const char *path, struct got_commit_object *commit,
5993 int show_ids, int recurse, const char *root_path,
5994 struct got_repository *repo)
5996 const struct got_error *err = NULL;
5997 struct got_object_id *tree_id = NULL;
5998 struct got_tree_object *tree = NULL;
5999 int nentries, i;
6001 err = got_object_id_by_path(&tree_id, repo, commit, path);
6002 if (err)
6003 goto done;
6005 err = got_object_open_as_tree(&tree, repo, tree_id);
6006 if (err)
6007 goto done;
6008 nentries = got_object_tree_get_nentries(tree);
6009 for (i = 0; i < nentries; i++) {
6010 struct got_tree_entry *te;
6011 char *id = NULL;
6013 if (sigint_received || sigpipe_received)
6014 break;
6016 te = got_object_tree_get_entry(tree, i);
6017 if (show_ids) {
6018 char *id_str;
6019 err = got_object_id_str(&id_str,
6020 got_tree_entry_get_id(te));
6021 if (err)
6022 goto done;
6023 if (asprintf(&id, "%s ", id_str) == -1) {
6024 err = got_error_from_errno("asprintf");
6025 free(id_str);
6026 goto done;
6028 free(id_str);
6030 err = print_entry(te, id, path, root_path, repo);
6031 free(id);
6032 if (err)
6033 goto done;
6035 if (recurse && S_ISDIR(got_tree_entry_get_mode(te))) {
6036 char *child_path;
6037 if (asprintf(&child_path, "%s%s%s", path,
6038 path[0] == '/' && path[1] == '\0' ? "" : "/",
6039 got_tree_entry_get_name(te)) == -1) {
6040 err = got_error_from_errno("asprintf");
6041 goto done;
6043 err = print_tree(child_path, commit, show_ids, 1,
6044 root_path, repo);
6045 free(child_path);
6046 if (err)
6047 goto done;
6050 done:
6051 if (tree)
6052 got_object_tree_close(tree);
6053 free(tree_id);
6054 return err;
6057 static const struct got_error *
6058 cmd_tree(int argc, char *argv[])
6060 const struct got_error *error;
6061 struct got_repository *repo = NULL;
6062 struct got_worktree *worktree = NULL;
6063 const char *path, *refname = NULL;
6064 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
6065 struct got_object_id *commit_id = NULL;
6066 struct got_commit_object *commit = NULL;
6067 char *commit_id_str = NULL;
6068 int show_ids = 0, recurse = 0;
6069 int ch;
6070 int *pack_fds = NULL;
6072 #ifndef PROFILE
6073 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
6074 NULL) == -1)
6075 err(1, "pledge");
6076 #endif
6078 while ((ch = getopt(argc, argv, "c:iRr:")) != -1) {
6079 switch (ch) {
6080 case 'c':
6081 commit_id_str = optarg;
6082 break;
6083 case 'i':
6084 show_ids = 1;
6085 break;
6086 case 'R':
6087 recurse = 1;
6088 break;
6089 case 'r':
6090 repo_path = realpath(optarg, NULL);
6091 if (repo_path == NULL)
6092 return got_error_from_errno2("realpath",
6093 optarg);
6094 got_path_strip_trailing_slashes(repo_path);
6095 break;
6096 default:
6097 usage_tree();
6098 /* NOTREACHED */
6102 argc -= optind;
6103 argv += optind;
6105 if (argc == 1)
6106 path = argv[0];
6107 else if (argc > 1)
6108 usage_tree();
6109 else
6110 path = NULL;
6112 cwd = getcwd(NULL, 0);
6113 if (cwd == NULL) {
6114 error = got_error_from_errno("getcwd");
6115 goto done;
6118 error = got_repo_pack_fds_open(&pack_fds);
6119 if (error != NULL)
6120 goto done;
6122 if (repo_path == NULL) {
6123 error = got_worktree_open(&worktree, cwd);
6124 if (error && error->code != GOT_ERR_NOT_WORKTREE)
6125 goto done;
6126 else
6127 error = NULL;
6128 if (worktree) {
6129 repo_path =
6130 strdup(got_worktree_get_repo_path(worktree));
6131 if (repo_path == NULL)
6132 error = got_error_from_errno("strdup");
6133 if (error)
6134 goto done;
6135 } else {
6136 repo_path = strdup(cwd);
6137 if (repo_path == NULL) {
6138 error = got_error_from_errno("strdup");
6139 goto done;
6144 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
6145 if (error != NULL)
6146 goto done;
6148 if (worktree) {
6149 const char *prefix = got_worktree_get_path_prefix(worktree);
6150 char *p;
6152 if (path == NULL || got_path_is_root_dir(path))
6153 path = "";
6154 error = got_worktree_resolve_path(&p, worktree, path);
6155 if (error)
6156 goto done;
6157 if (asprintf(&in_repo_path, "%s%s%s", prefix,
6158 (p[0] != '\0' && !got_path_is_root_dir(prefix)) ? "/" : "",
6159 p) == -1) {
6160 error = got_error_from_errno("asprintf");
6161 free(p);
6162 goto done;
6164 free(p);
6165 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
6166 if (error)
6167 goto done;
6168 } else {
6169 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
6170 if (error)
6171 goto done;
6172 if (path == NULL)
6173 path = "/";
6174 error = got_repo_map_path(&in_repo_path, repo, path);
6175 if (error != NULL)
6176 goto done;
6179 if (commit_id_str == NULL) {
6180 struct got_reference *head_ref;
6181 if (worktree)
6182 refname = got_worktree_get_head_ref_name(worktree);
6183 else
6184 refname = GOT_REF_HEAD;
6185 error = got_ref_open(&head_ref, repo, refname, 0);
6186 if (error != NULL)
6187 goto done;
6188 error = got_ref_resolve(&commit_id, repo, head_ref);
6189 got_ref_close(head_ref);
6190 if (error != NULL)
6191 goto done;
6192 } else {
6193 struct got_reflist_head refs;
6194 TAILQ_INIT(&refs);
6195 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
6196 NULL);
6197 if (error)
6198 goto done;
6199 error = got_repo_match_object_id(&commit_id, NULL,
6200 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
6201 got_ref_list_free(&refs);
6202 if (error)
6203 goto done;
6206 if (worktree) {
6207 /* Release work tree lock. */
6208 got_worktree_close(worktree);
6209 worktree = NULL;
6212 error = got_object_open_as_commit(&commit, repo, commit_id);
6213 if (error)
6214 goto done;
6216 error = print_tree(in_repo_path, commit, show_ids, recurse,
6217 in_repo_path, repo);
6218 done:
6219 free(in_repo_path);
6220 free(repo_path);
6221 free(cwd);
6222 free(commit_id);
6223 if (commit)
6224 got_object_commit_close(commit);
6225 if (worktree)
6226 got_worktree_close(worktree);
6227 if (repo) {
6228 const struct got_error *close_err = got_repo_close(repo);
6229 if (error == NULL)
6230 error = close_err;
6232 if (pack_fds) {
6233 const struct got_error *pack_err =
6234 got_repo_pack_fds_close(pack_fds);
6235 if (error == NULL)
6236 error = pack_err;
6238 return error;
6241 __dead static void
6242 usage_status(void)
6244 fprintf(stderr, "usage: %s status [-I] [-S status-codes] "
6245 "[-s status-codes] [path ...]\n", getprogname());
6246 exit(1);
6249 struct got_status_arg {
6250 char *status_codes;
6251 int suppress;
6254 static const struct got_error *
6255 print_status(void *arg, unsigned char status, unsigned char staged_status,
6256 const char *path, struct got_object_id *blob_id,
6257 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
6258 int dirfd, const char *de_name)
6260 struct got_status_arg *st = arg;
6262 if (status == staged_status && (status == GOT_STATUS_DELETE))
6263 status = GOT_STATUS_NO_CHANGE;
6264 if (st != NULL && st->status_codes) {
6265 size_t ncodes = strlen(st->status_codes);
6266 int i, j = 0;
6268 for (i = 0; i < ncodes ; i++) {
6269 if (st->suppress) {
6270 if (status == st->status_codes[i] ||
6271 staged_status == st->status_codes[i]) {
6272 j++;
6273 continue;
6275 } else {
6276 if (status == st->status_codes[i] ||
6277 staged_status == st->status_codes[i])
6278 break;
6282 if (st->suppress && j == 0)
6283 goto print;
6285 if (i == ncodes)
6286 return NULL;
6288 print:
6289 printf("%c%c %s\n", status, staged_status, path);
6290 return NULL;
6293 static const struct got_error *
6294 cmd_status(int argc, char *argv[])
6296 const struct got_error *error = NULL;
6297 struct got_repository *repo = NULL;
6298 struct got_worktree *worktree = NULL;
6299 struct got_status_arg st;
6300 char *cwd = NULL;
6301 struct got_pathlist_head paths;
6302 int ch, i, no_ignores = 0;
6303 int *pack_fds = NULL;
6305 TAILQ_INIT(&paths);
6307 memset(&st, 0, sizeof(st));
6308 st.status_codes = NULL;
6309 st.suppress = 0;
6311 #ifndef PROFILE
6312 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
6313 NULL) == -1)
6314 err(1, "pledge");
6315 #endif
6317 while ((ch = getopt(argc, argv, "IS:s:")) != -1) {
6318 switch (ch) {
6319 case 'I':
6320 no_ignores = 1;
6321 break;
6322 case 'S':
6323 if (st.status_codes != NULL && st.suppress == 0)
6324 option_conflict('S', 's');
6325 st.suppress = 1;
6326 /* fallthrough */
6327 case 's':
6328 for (i = 0; optarg[i] != '\0'; i++) {
6329 switch (optarg[i]) {
6330 case GOT_STATUS_MODIFY:
6331 case GOT_STATUS_ADD:
6332 case GOT_STATUS_DELETE:
6333 case GOT_STATUS_CONFLICT:
6334 case GOT_STATUS_MISSING:
6335 case GOT_STATUS_OBSTRUCTED:
6336 case GOT_STATUS_UNVERSIONED:
6337 case GOT_STATUS_MODE_CHANGE:
6338 case GOT_STATUS_NONEXISTENT:
6339 break;
6340 default:
6341 errx(1, "invalid status code '%c'",
6342 optarg[i]);
6345 if (ch == 's' && st.suppress)
6346 option_conflict('s', 'S');
6347 st.status_codes = optarg;
6348 break;
6349 default:
6350 usage_status();
6351 /* NOTREACHED */
6355 argc -= optind;
6356 argv += optind;
6358 cwd = getcwd(NULL, 0);
6359 if (cwd == NULL) {
6360 error = got_error_from_errno("getcwd");
6361 goto done;
6364 error = got_repo_pack_fds_open(&pack_fds);
6365 if (error != NULL)
6366 goto done;
6368 error = got_worktree_open(&worktree, cwd);
6369 if (error) {
6370 if (error->code == GOT_ERR_NOT_WORKTREE)
6371 error = wrap_not_worktree_error(error, "status", cwd);
6372 goto done;
6375 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
6376 NULL, pack_fds);
6377 if (error != NULL)
6378 goto done;
6380 error = apply_unveil(got_repo_get_path(repo), 1,
6381 got_worktree_get_root_path(worktree));
6382 if (error)
6383 goto done;
6385 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
6386 if (error)
6387 goto done;
6389 error = got_worktree_status(worktree, &paths, repo, no_ignores,
6390 print_status, &st, check_cancelled, NULL);
6391 done:
6392 if (pack_fds) {
6393 const struct got_error *pack_err =
6394 got_repo_pack_fds_close(pack_fds);
6395 if (error == NULL)
6396 error = pack_err;
6398 if (repo) {
6399 const struct got_error *close_err = got_repo_close(repo);
6400 if (error == NULL)
6401 error = close_err;
6404 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
6405 free(cwd);
6406 return error;
6409 __dead static void
6410 usage_ref(void)
6412 fprintf(stderr, "usage: %s ref [-dlt] [-c object] [-r repository-path] "
6413 "[-s reference] [name]\n", getprogname());
6414 exit(1);
6417 static const struct got_error *
6418 list_refs(struct got_repository *repo, const char *refname, int sort_by_time)
6420 static const struct got_error *err = NULL;
6421 struct got_reflist_head refs;
6422 struct got_reflist_entry *re;
6424 TAILQ_INIT(&refs);
6425 err = got_ref_list(&refs, repo, refname, sort_by_time ?
6426 got_ref_cmp_by_commit_timestamp_descending : got_ref_cmp_by_name,
6427 repo);
6428 if (err)
6429 return err;
6431 TAILQ_FOREACH(re, &refs, entry) {
6432 char *refstr;
6433 refstr = got_ref_to_str(re->ref);
6434 if (refstr == NULL) {
6435 err = got_error_from_errno("got_ref_to_str");
6436 break;
6438 printf("%s: %s\n", got_ref_get_name(re->ref), refstr);
6439 free(refstr);
6442 got_ref_list_free(&refs);
6443 return err;
6446 static const struct got_error *
6447 delete_ref_by_name(struct got_repository *repo, const char *refname)
6449 const struct got_error *err;
6450 struct got_reference *ref;
6452 err = got_ref_open(&ref, repo, refname, 0);
6453 if (err)
6454 return err;
6456 err = delete_ref(repo, ref);
6457 got_ref_close(ref);
6458 return err;
6461 static const struct got_error *
6462 add_ref(struct got_repository *repo, const char *refname, const char *target)
6464 const struct got_error *err = NULL;
6465 struct got_object_id *id = NULL;
6466 struct got_reference *ref = NULL;
6467 struct got_reflist_head refs;
6470 * Don't let the user create a reference name with a leading '-'.
6471 * While technically a valid reference name, this case is usually
6472 * an unintended typo.
6474 if (refname[0] == '-')
6475 return got_error_path(refname, GOT_ERR_REF_NAME_MINUS);
6477 TAILQ_INIT(&refs);
6478 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
6479 if (err)
6480 goto done;
6481 err = got_repo_match_object_id(&id, NULL, target, GOT_OBJ_TYPE_ANY,
6482 &refs, repo);
6483 got_ref_list_free(&refs);
6484 if (err)
6485 goto done;
6487 err = got_ref_alloc(&ref, refname, id);
6488 if (err)
6489 goto done;
6491 err = got_ref_write(ref, repo);
6492 done:
6493 if (ref)
6494 got_ref_close(ref);
6495 free(id);
6496 return err;
6499 static const struct got_error *
6500 add_symref(struct got_repository *repo, const char *refname, const char *target)
6502 const struct got_error *err = NULL;
6503 struct got_reference *ref = NULL;
6504 struct got_reference *target_ref = NULL;
6507 * Don't let the user create a reference name with a leading '-'.
6508 * While technically a valid reference name, this case is usually
6509 * an unintended typo.
6511 if (refname[0] == '-')
6512 return got_error_path(refname, GOT_ERR_REF_NAME_MINUS);
6514 err = got_ref_open(&target_ref, repo, target, 0);
6515 if (err)
6516 return err;
6518 err = got_ref_alloc_symref(&ref, refname, target_ref);
6519 if (err)
6520 goto done;
6522 err = got_ref_write(ref, repo);
6523 done:
6524 if (target_ref)
6525 got_ref_close(target_ref);
6526 if (ref)
6527 got_ref_close(ref);
6528 return err;
6531 static const struct got_error *
6532 cmd_ref(int argc, char *argv[])
6534 const struct got_error *error = NULL;
6535 struct got_repository *repo = NULL;
6536 struct got_worktree *worktree = NULL;
6537 char *cwd = NULL, *repo_path = NULL;
6538 int ch, do_list = 0, do_delete = 0, sort_by_time = 0;
6539 const char *obj_arg = NULL, *symref_target= NULL;
6540 char *refname = NULL;
6541 int *pack_fds = NULL;
6543 #ifndef PROFILE
6544 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
6545 "sendfd unveil", NULL) == -1)
6546 err(1, "pledge");
6547 #endif
6549 while ((ch = getopt(argc, argv, "c:dlr:s:t")) != -1) {
6550 switch (ch) {
6551 case 'c':
6552 obj_arg = optarg;
6553 break;
6554 case 'd':
6555 do_delete = 1;
6556 break;
6557 case 'l':
6558 do_list = 1;
6559 break;
6560 case 'r':
6561 repo_path = realpath(optarg, NULL);
6562 if (repo_path == NULL)
6563 return got_error_from_errno2("realpath",
6564 optarg);
6565 got_path_strip_trailing_slashes(repo_path);
6566 break;
6567 case 's':
6568 symref_target = optarg;
6569 break;
6570 case 't':
6571 sort_by_time = 1;
6572 break;
6573 default:
6574 usage_ref();
6575 /* NOTREACHED */
6579 if (obj_arg && do_list)
6580 option_conflict('c', 'l');
6581 if (obj_arg && do_delete)
6582 option_conflict('c', 'd');
6583 if (obj_arg && symref_target)
6584 option_conflict('c', 's');
6585 if (symref_target && do_delete)
6586 option_conflict('s', 'd');
6587 if (symref_target && do_list)
6588 option_conflict('s', 'l');
6589 if (do_delete && do_list)
6590 option_conflict('d', 'l');
6591 if (sort_by_time && !do_list)
6592 errx(1, "-t option requires -l option");
6594 argc -= optind;
6595 argv += optind;
6597 if (do_list) {
6598 if (argc != 0 && argc != 1)
6599 usage_ref();
6600 if (argc == 1) {
6601 refname = strdup(argv[0]);
6602 if (refname == NULL) {
6603 error = got_error_from_errno("strdup");
6604 goto done;
6607 } else {
6608 if (argc != 1)
6609 usage_ref();
6610 refname = strdup(argv[0]);
6611 if (refname == NULL) {
6612 error = got_error_from_errno("strdup");
6613 goto done;
6617 if (refname)
6618 got_path_strip_trailing_slashes(refname);
6620 cwd = getcwd(NULL, 0);
6621 if (cwd == NULL) {
6622 error = got_error_from_errno("getcwd");
6623 goto done;
6626 error = got_repo_pack_fds_open(&pack_fds);
6627 if (error != NULL)
6628 goto done;
6630 if (repo_path == NULL) {
6631 error = got_worktree_open(&worktree, cwd);
6632 if (error && error->code != GOT_ERR_NOT_WORKTREE)
6633 goto done;
6634 else
6635 error = NULL;
6636 if (worktree) {
6637 repo_path =
6638 strdup(got_worktree_get_repo_path(worktree));
6639 if (repo_path == NULL)
6640 error = got_error_from_errno("strdup");
6641 if (error)
6642 goto done;
6643 } else {
6644 repo_path = strdup(cwd);
6645 if (repo_path == NULL) {
6646 error = got_error_from_errno("strdup");
6647 goto done;
6652 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
6653 if (error != NULL)
6654 goto done;
6656 #ifndef PROFILE
6657 if (do_list) {
6658 /* Remove "cpath" promise. */
6659 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
6660 NULL) == -1)
6661 err(1, "pledge");
6663 #endif
6665 error = apply_unveil(got_repo_get_path(repo), do_list,
6666 worktree ? got_worktree_get_root_path(worktree) : NULL);
6667 if (error)
6668 goto done;
6670 if (do_list)
6671 error = list_refs(repo, refname, sort_by_time);
6672 else if (do_delete)
6673 error = delete_ref_by_name(repo, refname);
6674 else if (symref_target)
6675 error = add_symref(repo, refname, symref_target);
6676 else {
6677 if (obj_arg == NULL)
6678 usage_ref();
6679 error = add_ref(repo, refname, obj_arg);
6681 done:
6682 free(refname);
6683 if (repo) {
6684 const struct got_error *close_err = got_repo_close(repo);
6685 if (error == NULL)
6686 error = close_err;
6688 if (worktree)
6689 got_worktree_close(worktree);
6690 if (pack_fds) {
6691 const struct got_error *pack_err =
6692 got_repo_pack_fds_close(pack_fds);
6693 if (error == NULL)
6694 error = pack_err;
6696 free(cwd);
6697 free(repo_path);
6698 return error;
6701 __dead static void
6702 usage_branch(void)
6704 fprintf(stderr, "usage: %s branch [-lnt] [-c commit] [-d name] "
6705 "[-r repository-path] [name]\n", getprogname());
6706 exit(1);
6709 static const struct got_error *
6710 list_branch(struct got_repository *repo, struct got_worktree *worktree,
6711 struct got_reference *ref)
6713 const struct got_error *err = NULL;
6714 const char *refname, *marker = " ";
6715 char *refstr;
6717 refname = got_ref_get_name(ref);
6718 if (worktree && strcmp(refname,
6719 got_worktree_get_head_ref_name(worktree)) == 0) {
6720 struct got_object_id *id = NULL;
6722 err = got_ref_resolve(&id, repo, ref);
6723 if (err)
6724 return err;
6725 if (got_object_id_cmp(id,
6726 got_worktree_get_base_commit_id(worktree)) == 0)
6727 marker = "* ";
6728 else
6729 marker = "~ ";
6730 free(id);
6733 if (strncmp(refname, "refs/heads/", 11) == 0)
6734 refname += 11;
6735 if (strncmp(refname, "refs/got/worktree/", 18) == 0)
6736 refname += 18;
6737 if (strncmp(refname, "refs/remotes/", 13) == 0)
6738 refname += 13;
6740 refstr = got_ref_to_str(ref);
6741 if (refstr == NULL)
6742 return got_error_from_errno("got_ref_to_str");
6744 printf("%s%s: %s\n", marker, refname, refstr);
6745 free(refstr);
6746 return NULL;
6749 static const struct got_error *
6750 show_current_branch(struct got_repository *repo, struct got_worktree *worktree)
6752 const char *refname;
6754 if (worktree == NULL)
6755 return got_error(GOT_ERR_NOT_WORKTREE);
6757 refname = got_worktree_get_head_ref_name(worktree);
6759 if (strncmp(refname, "refs/heads/", 11) == 0)
6760 refname += 11;
6761 if (strncmp(refname, "refs/got/worktree/", 18) == 0)
6762 refname += 18;
6764 printf("%s\n", refname);
6766 return NULL;
6769 static const struct got_error *
6770 list_branches(struct got_repository *repo, struct got_worktree *worktree,
6771 int sort_by_time)
6773 static const struct got_error *err = NULL;
6774 struct got_reflist_head refs;
6775 struct got_reflist_entry *re;
6776 struct got_reference *temp_ref = NULL;
6777 int rebase_in_progress, histedit_in_progress;
6779 TAILQ_INIT(&refs);
6781 if (worktree) {
6782 err = got_worktree_rebase_in_progress(&rebase_in_progress,
6783 worktree);
6784 if (err)
6785 return err;
6787 err = got_worktree_histedit_in_progress(&histedit_in_progress,
6788 worktree);
6789 if (err)
6790 return err;
6792 if (rebase_in_progress || histedit_in_progress) {
6793 err = got_ref_open(&temp_ref, repo,
6794 got_worktree_get_head_ref_name(worktree), 0);
6795 if (err)
6796 return err;
6797 list_branch(repo, worktree, temp_ref);
6798 got_ref_close(temp_ref);
6802 err = got_ref_list(&refs, repo, "refs/heads", sort_by_time ?
6803 got_ref_cmp_by_commit_timestamp_descending : got_ref_cmp_by_name,
6804 repo);
6805 if (err)
6806 return err;
6808 TAILQ_FOREACH(re, &refs, entry)
6809 list_branch(repo, worktree, re->ref);
6811 got_ref_list_free(&refs);
6813 err = got_ref_list(&refs, repo, "refs/remotes", sort_by_time ?
6814 got_ref_cmp_by_commit_timestamp_descending : got_ref_cmp_by_name,
6815 repo);
6816 if (err)
6817 return err;
6819 TAILQ_FOREACH(re, &refs, entry)
6820 list_branch(repo, worktree, re->ref);
6822 got_ref_list_free(&refs);
6824 return NULL;
6827 static const struct got_error *
6828 delete_branch(struct got_repository *repo, struct got_worktree *worktree,
6829 const char *branch_name)
6831 const struct got_error *err = NULL;
6832 struct got_reference *ref = NULL;
6833 char *refname, *remote_refname = NULL;
6835 if (strncmp(branch_name, "refs/", 5) == 0)
6836 branch_name += 5;
6837 if (strncmp(branch_name, "heads/", 6) == 0)
6838 branch_name += 6;
6839 else if (strncmp(branch_name, "remotes/", 8) == 0)
6840 branch_name += 8;
6842 if (asprintf(&refname, "refs/heads/%s", branch_name) == -1)
6843 return got_error_from_errno("asprintf");
6845 if (asprintf(&remote_refname, "refs/remotes/%s",
6846 branch_name) == -1) {
6847 err = got_error_from_errno("asprintf");
6848 goto done;
6851 err = got_ref_open(&ref, repo, refname, 0);
6852 if (err) {
6853 const struct got_error *err2;
6854 if (err->code != GOT_ERR_NOT_REF)
6855 goto done;
6857 * Keep 'err' intact such that if neither branch exists
6858 * we report "refs/heads" rather than "refs/remotes" in
6859 * our error message.
6861 err2 = got_ref_open(&ref, repo, remote_refname, 0);
6862 if (err2)
6863 goto done;
6864 err = NULL;
6867 if (worktree &&
6868 strcmp(got_worktree_get_head_ref_name(worktree),
6869 got_ref_get_name(ref)) == 0) {
6870 err = got_error_msg(GOT_ERR_SAME_BRANCH,
6871 "will not delete this work tree's current branch");
6872 goto done;
6875 err = delete_ref(repo, ref);
6876 done:
6877 if (ref)
6878 got_ref_close(ref);
6879 free(refname);
6880 free(remote_refname);
6881 return err;
6884 static const struct got_error *
6885 add_branch(struct got_repository *repo, const char *branch_name,
6886 struct got_object_id *base_commit_id)
6888 const struct got_error *err = NULL;
6889 struct got_reference *ref = NULL;
6890 char *refname = NULL;
6893 * Don't let the user create a branch name with a leading '-'.
6894 * While technically a valid reference name, this case is usually
6895 * an unintended typo.
6897 if (branch_name[0] == '-')
6898 return got_error_path(branch_name, GOT_ERR_REF_NAME_MINUS);
6900 if (strncmp(branch_name, "refs/heads/", 11) == 0)
6901 branch_name += 11;
6903 if (asprintf(&refname, "refs/heads/%s", branch_name) == -1) {
6904 err = got_error_from_errno("asprintf");
6905 goto done;
6908 err = got_ref_open(&ref, repo, refname, 0);
6909 if (err == NULL) {
6910 err = got_error(GOT_ERR_BRANCH_EXISTS);
6911 goto done;
6912 } else if (err->code != GOT_ERR_NOT_REF)
6913 goto done;
6915 err = got_ref_alloc(&ref, refname, base_commit_id);
6916 if (err)
6917 goto done;
6919 err = got_ref_write(ref, repo);
6920 done:
6921 if (ref)
6922 got_ref_close(ref);
6923 free(refname);
6924 return err;
6927 static const struct got_error *
6928 cmd_branch(int argc, char *argv[])
6930 const struct got_error *error = NULL;
6931 struct got_repository *repo = NULL;
6932 struct got_worktree *worktree = NULL;
6933 char *cwd = NULL, *repo_path = NULL;
6934 int ch, do_list = 0, do_show = 0, do_update = 1, sort_by_time = 0;
6935 const char *delref = NULL, *commit_id_arg = NULL;
6936 struct got_reference *ref = NULL;
6937 struct got_pathlist_head paths;
6938 struct got_object_id *commit_id = NULL;
6939 char *commit_id_str = NULL;
6940 int *pack_fds = NULL;
6942 TAILQ_INIT(&paths);
6944 #ifndef PROFILE
6945 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
6946 "sendfd unveil", NULL) == -1)
6947 err(1, "pledge");
6948 #endif
6950 while ((ch = getopt(argc, argv, "c:d:lnr:t")) != -1) {
6951 switch (ch) {
6952 case 'c':
6953 commit_id_arg = optarg;
6954 break;
6955 case 'd':
6956 delref = optarg;
6957 break;
6958 case 'l':
6959 do_list = 1;
6960 break;
6961 case 'n':
6962 do_update = 0;
6963 break;
6964 case 'r':
6965 repo_path = realpath(optarg, NULL);
6966 if (repo_path == NULL)
6967 return got_error_from_errno2("realpath",
6968 optarg);
6969 got_path_strip_trailing_slashes(repo_path);
6970 break;
6971 case 't':
6972 sort_by_time = 1;
6973 break;
6974 default:
6975 usage_branch();
6976 /* NOTREACHED */
6980 if (do_list && delref)
6981 option_conflict('l', 'd');
6982 if (sort_by_time && !do_list)
6983 errx(1, "-t option requires -l option");
6985 argc -= optind;
6986 argv += optind;
6988 if (!do_list && !delref && argc == 0)
6989 do_show = 1;
6991 if ((do_list || delref || do_show) && commit_id_arg != NULL)
6992 errx(1, "-c option can only be used when creating a branch");
6994 if (do_list || delref) {
6995 if (argc > 0)
6996 usage_branch();
6997 } else if (!do_show && argc != 1)
6998 usage_branch();
7000 cwd = getcwd(NULL, 0);
7001 if (cwd == NULL) {
7002 error = got_error_from_errno("getcwd");
7003 goto done;
7006 error = got_repo_pack_fds_open(&pack_fds);
7007 if (error != NULL)
7008 goto done;
7010 if (repo_path == NULL) {
7011 error = got_worktree_open(&worktree, cwd);
7012 if (error && error->code != GOT_ERR_NOT_WORKTREE)
7013 goto done;
7014 else
7015 error = NULL;
7016 if (worktree) {
7017 repo_path =
7018 strdup(got_worktree_get_repo_path(worktree));
7019 if (repo_path == NULL)
7020 error = got_error_from_errno("strdup");
7021 if (error)
7022 goto done;
7023 } else {
7024 repo_path = strdup(cwd);
7025 if (repo_path == NULL) {
7026 error = got_error_from_errno("strdup");
7027 goto done;
7032 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
7033 if (error != NULL)
7034 goto done;
7036 #ifndef PROFILE
7037 if (do_list || do_show) {
7038 /* Remove "cpath" promise. */
7039 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
7040 NULL) == -1)
7041 err(1, "pledge");
7043 #endif
7045 error = apply_unveil(got_repo_get_path(repo), do_list,
7046 worktree ? got_worktree_get_root_path(worktree) : NULL);
7047 if (error)
7048 goto done;
7050 if (do_show)
7051 error = show_current_branch(repo, worktree);
7052 else if (do_list)
7053 error = list_branches(repo, worktree, sort_by_time);
7054 else if (delref)
7055 error = delete_branch(repo, worktree, delref);
7056 else {
7057 struct got_reflist_head refs;
7058 TAILQ_INIT(&refs);
7059 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
7060 NULL);
7061 if (error)
7062 goto done;
7063 if (commit_id_arg == NULL)
7064 commit_id_arg = worktree ?
7065 got_worktree_get_head_ref_name(worktree) :
7066 GOT_REF_HEAD;
7067 error = got_repo_match_object_id(&commit_id, NULL,
7068 commit_id_arg, GOT_OBJ_TYPE_COMMIT, &refs, repo);
7069 got_ref_list_free(&refs);
7070 if (error)
7071 goto done;
7072 error = add_branch(repo, argv[0], commit_id);
7073 if (error)
7074 goto done;
7075 if (worktree && do_update) {
7076 struct got_update_progress_arg upa;
7077 char *branch_refname = NULL;
7079 error = got_object_id_str(&commit_id_str, commit_id);
7080 if (error)
7081 goto done;
7082 error = get_worktree_paths_from_argv(&paths, 0, NULL,
7083 worktree);
7084 if (error)
7085 goto done;
7086 if (asprintf(&branch_refname, "refs/heads/%s", argv[0])
7087 == -1) {
7088 error = got_error_from_errno("asprintf");
7089 goto done;
7091 error = got_ref_open(&ref, repo, branch_refname, 0);
7092 free(branch_refname);
7093 if (error)
7094 goto done;
7095 error = switch_head_ref(ref, commit_id, worktree,
7096 repo);
7097 if (error)
7098 goto done;
7099 error = got_worktree_set_base_commit_id(worktree, repo,
7100 commit_id);
7101 if (error)
7102 goto done;
7103 memset(&upa, 0, sizeof(upa));
7104 error = got_worktree_checkout_files(worktree, &paths,
7105 repo, update_progress, &upa, check_cancelled,
7106 NULL);
7107 if (error)
7108 goto done;
7109 if (upa.did_something) {
7110 printf("Updated to %s: %s\n",
7111 got_worktree_get_head_ref_name(worktree),
7112 commit_id_str);
7114 print_update_progress_stats(&upa);
7117 done:
7118 if (ref)
7119 got_ref_close(ref);
7120 if (repo) {
7121 const struct got_error *close_err = got_repo_close(repo);
7122 if (error == NULL)
7123 error = close_err;
7125 if (worktree)
7126 got_worktree_close(worktree);
7127 if (pack_fds) {
7128 const struct got_error *pack_err =
7129 got_repo_pack_fds_close(pack_fds);
7130 if (error == NULL)
7131 error = pack_err;
7133 free(cwd);
7134 free(repo_path);
7135 free(commit_id);
7136 free(commit_id_str);
7137 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
7138 return error;
7142 __dead static void
7143 usage_tag(void)
7145 fprintf(stderr, "usage: %s tag [-lVv] [-c commit] [-m message] "
7146 "[-r repository-path] [-s signer-id] name\n", getprogname());
7147 exit(1);
7150 #if 0
7151 static const struct got_error *
7152 sort_tags(struct got_reflist_head *sorted, struct got_reflist_head *tags)
7154 const struct got_error *err = NULL;
7155 struct got_reflist_entry *re, *se, *new;
7156 struct got_object_id *re_id, *se_id;
7157 struct got_tag_object *re_tag, *se_tag;
7158 time_t re_time, se_time;
7160 STAILQ_FOREACH(re, tags, entry) {
7161 se = STAILQ_FIRST(sorted);
7162 if (se == NULL) {
7163 err = got_reflist_entry_dup(&new, re);
7164 if (err)
7165 return err;
7166 STAILQ_INSERT_HEAD(sorted, new, entry);
7167 continue;
7168 } else {
7169 err = got_ref_resolve(&re_id, repo, re->ref);
7170 if (err)
7171 break;
7172 err = got_object_open_as_tag(&re_tag, repo, re_id);
7173 free(re_id);
7174 if (err)
7175 break;
7176 re_time = got_object_tag_get_tagger_time(re_tag);
7177 got_object_tag_close(re_tag);
7180 while (se) {
7181 err = got_ref_resolve(&se_id, repo, re->ref);
7182 if (err)
7183 break;
7184 err = got_object_open_as_tag(&se_tag, repo, se_id);
7185 free(se_id);
7186 if (err)
7187 break;
7188 se_time = got_object_tag_get_tagger_time(se_tag);
7189 got_object_tag_close(se_tag);
7191 if (se_time > re_time) {
7192 err = got_reflist_entry_dup(&new, re);
7193 if (err)
7194 return err;
7195 STAILQ_INSERT_AFTER(sorted, se, new, entry);
7196 break;
7198 se = STAILQ_NEXT(se, entry);
7199 continue;
7202 done:
7203 return err;
7205 #endif
7207 static const struct got_error *
7208 get_tag_refname(char **refname, const char *tag_name)
7210 const struct got_error *err;
7212 if (strncmp("refs/tags/", tag_name, 10) == 0) {
7213 *refname = strdup(tag_name);
7214 if (*refname == NULL)
7215 return got_error_from_errno("strdup");
7216 } else if (asprintf(refname, "refs/tags/%s", tag_name) == -1) {
7217 err = got_error_from_errno("asprintf");
7218 *refname = NULL;
7219 return err;
7222 return NULL;
7225 static const struct got_error *
7226 list_tags(struct got_repository *repo, const char *tag_name, int verify_tags,
7227 const char *allowed_signers, const char *revoked_signers, int verbosity)
7229 static const struct got_error *err = NULL;
7230 struct got_reflist_head refs;
7231 struct got_reflist_entry *re;
7232 char *wanted_refname = NULL;
7233 int bad_sigs = 0;
7235 TAILQ_INIT(&refs);
7237 err = got_ref_list(&refs, repo, "refs/tags", got_ref_cmp_tags, repo);
7238 if (err)
7239 return err;
7241 if (tag_name) {
7242 struct got_reference *ref;
7243 err = get_tag_refname(&wanted_refname, tag_name);
7244 if (err)
7245 goto done;
7246 /* Wanted tag reference should exist. */
7247 err = got_ref_open(&ref, repo, wanted_refname, 0);
7248 if (err)
7249 goto done;
7250 got_ref_close(ref);
7253 TAILQ_FOREACH(re, &refs, entry) {
7254 const char *refname;
7255 char *refstr, *tagmsg0, *tagmsg, *line, *id_str, *datestr;
7256 char datebuf[26];
7257 const char *tagger, *ssh_sig = NULL;
7258 char *sig_msg = NULL;
7259 time_t tagger_time;
7260 struct got_object_id *id;
7261 struct got_tag_object *tag;
7262 struct got_commit_object *commit = NULL;
7264 refname = got_ref_get_name(re->ref);
7265 if (strncmp(refname, "refs/tags/", 10) != 0 ||
7266 (wanted_refname && strcmp(refname, wanted_refname) != 0))
7267 continue;
7268 refname += 10;
7269 refstr = got_ref_to_str(re->ref);
7270 if (refstr == NULL) {
7271 err = got_error_from_errno("got_ref_to_str");
7272 break;
7275 err = got_ref_resolve(&id, repo, re->ref);
7276 if (err)
7277 break;
7278 err = got_object_open_as_tag(&tag, repo, id);
7279 if (err) {
7280 if (err->code != GOT_ERR_OBJ_TYPE) {
7281 free(id);
7282 break;
7284 /* "lightweight" tag */
7285 err = got_object_open_as_commit(&commit, repo, id);
7286 if (err) {
7287 free(id);
7288 break;
7290 tagger = got_object_commit_get_committer(commit);
7291 tagger_time =
7292 got_object_commit_get_committer_time(commit);
7293 err = got_object_id_str(&id_str, id);
7294 free(id);
7295 if (err)
7296 break;
7297 } else {
7298 free(id);
7299 tagger = got_object_tag_get_tagger(tag);
7300 tagger_time = got_object_tag_get_tagger_time(tag);
7301 err = got_object_id_str(&id_str,
7302 got_object_tag_get_object_id(tag));
7303 if (err)
7304 break;
7307 if (tag && verify_tags) {
7308 ssh_sig = got_sigs_get_tagmsg_ssh_signature(
7309 got_object_tag_get_message(tag));
7310 if (ssh_sig && allowed_signers == NULL) {
7311 err = got_error_msg(
7312 GOT_ERR_VERIFY_TAG_SIGNATURE,
7313 "SSH signature verification requires "
7314 "setting allowed_signers in "
7315 "got.conf(5)");
7316 break;
7320 printf("%stag %s %s\n", GOT_COMMIT_SEP_STR, refname, refstr);
7321 free(refstr);
7322 printf("from: %s\n", tagger);
7323 datestr = get_datestr(&tagger_time, datebuf);
7324 if (datestr)
7325 printf("date: %s UTC\n", datestr);
7326 if (commit)
7327 printf("object: %s %s\n", GOT_OBJ_LABEL_COMMIT, id_str);
7328 else {
7329 switch (got_object_tag_get_object_type(tag)) {
7330 case GOT_OBJ_TYPE_BLOB:
7331 printf("object: %s %s\n", GOT_OBJ_LABEL_BLOB,
7332 id_str);
7333 break;
7334 case GOT_OBJ_TYPE_TREE:
7335 printf("object: %s %s\n", GOT_OBJ_LABEL_TREE,
7336 id_str);
7337 break;
7338 case GOT_OBJ_TYPE_COMMIT:
7339 printf("object: %s %s\n", GOT_OBJ_LABEL_COMMIT,
7340 id_str);
7341 break;
7342 case GOT_OBJ_TYPE_TAG:
7343 printf("object: %s %s\n", GOT_OBJ_LABEL_TAG,
7344 id_str);
7345 break;
7346 default:
7347 break;
7350 free(id_str);
7352 if (ssh_sig) {
7353 err = got_sigs_verify_tag_ssh(&sig_msg, tag, ssh_sig,
7354 allowed_signers, revoked_signers, verbosity);
7355 if (err && err->code == GOT_ERR_BAD_TAG_SIGNATURE)
7356 bad_sigs = 1;
7357 else if (err)
7358 break;
7359 printf("signature: %s", sig_msg);
7360 free(sig_msg);
7361 sig_msg = NULL;
7364 if (commit) {
7365 err = got_object_commit_get_logmsg(&tagmsg0, commit);
7366 if (err)
7367 break;
7368 got_object_commit_close(commit);
7369 } else {
7370 tagmsg0 = strdup(got_object_tag_get_message(tag));
7371 got_object_tag_close(tag);
7372 if (tagmsg0 == NULL) {
7373 err = got_error_from_errno("strdup");
7374 break;
7378 tagmsg = tagmsg0;
7379 do {
7380 line = strsep(&tagmsg, "\n");
7381 if (line)
7382 printf(" %s\n", line);
7383 } while (line);
7384 free(tagmsg0);
7386 done:
7387 got_ref_list_free(&refs);
7388 free(wanted_refname);
7390 if (err == NULL && bad_sigs)
7391 err = got_error(GOT_ERR_BAD_TAG_SIGNATURE);
7392 return err;
7395 static const struct got_error *
7396 get_tag_message(char **tagmsg, char **tagmsg_path, const char *commit_id_str,
7397 const char *tag_name, const char *repo_path)
7399 const struct got_error *err = NULL;
7400 char *template = NULL, *initial_content = NULL;
7401 char *editor = NULL;
7402 int initial_content_len;
7403 int fd = -1;
7405 if (asprintf(&template, GOT_TMPDIR_STR "/got-tagmsg") == -1) {
7406 err = got_error_from_errno("asprintf");
7407 goto done;
7410 initial_content_len = asprintf(&initial_content,
7411 "\n# tagging commit %s as %s\n",
7412 commit_id_str, tag_name);
7413 if (initial_content_len == -1) {
7414 err = got_error_from_errno("asprintf");
7415 goto done;
7418 err = got_opentemp_named_fd(tagmsg_path, &fd, template, "");
7419 if (err)
7420 goto done;
7422 if (write(fd, initial_content, initial_content_len) == -1) {
7423 err = got_error_from_errno2("write", *tagmsg_path);
7424 goto done;
7426 if (close(fd) == -1) {
7427 err = got_error_from_errno2("close", *tagmsg_path);
7428 goto done;
7430 fd = -1;
7432 err = get_editor(&editor);
7433 if (err)
7434 goto done;
7435 err = edit_logmsg(tagmsg, editor, *tagmsg_path, initial_content,
7436 initial_content_len, 1);
7437 done:
7438 free(initial_content);
7439 free(template);
7440 free(editor);
7442 if (fd != -1 && close(fd) == -1 && err == NULL)
7443 err = got_error_from_errno2("close", *tagmsg_path);
7445 if (err) {
7446 free(*tagmsg);
7447 *tagmsg = NULL;
7449 return err;
7452 static const struct got_error *
7453 add_tag(struct got_repository *repo, const char *tagger,
7454 const char *tag_name, const char *commit_arg, const char *tagmsg_arg,
7455 const char *signer_id, int verbosity)
7457 const struct got_error *err = NULL;
7458 struct got_object_id *commit_id = NULL, *tag_id = NULL;
7459 char *label = NULL, *commit_id_str = NULL;
7460 struct got_reference *ref = NULL;
7461 char *refname = NULL, *tagmsg = NULL;
7462 char *tagmsg_path = NULL, *tag_id_str = NULL;
7463 int preserve_tagmsg = 0;
7464 struct got_reflist_head refs;
7466 TAILQ_INIT(&refs);
7469 * Don't let the user create a tag name with a leading '-'.
7470 * While technically a valid reference name, this case is usually
7471 * an unintended typo.
7473 if (tag_name[0] == '-')
7474 return got_error_path(tag_name, GOT_ERR_REF_NAME_MINUS);
7476 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
7477 if (err)
7478 goto done;
7480 err = got_repo_match_object_id(&commit_id, &label, commit_arg,
7481 GOT_OBJ_TYPE_COMMIT, &refs, repo);
7482 if (err)
7483 goto done;
7485 err = got_object_id_str(&commit_id_str, commit_id);
7486 if (err)
7487 goto done;
7489 err = get_tag_refname(&refname, tag_name);
7490 if (err)
7491 goto done;
7492 if (strncmp("refs/tags/", tag_name, 10) == 0)
7493 tag_name += 10;
7495 err = got_ref_open(&ref, repo, refname, 0);
7496 if (err == NULL) {
7497 err = got_error(GOT_ERR_TAG_EXISTS);
7498 goto done;
7499 } else if (err->code != GOT_ERR_NOT_REF)
7500 goto done;
7502 if (tagmsg_arg == NULL) {
7503 err = get_tag_message(&tagmsg, &tagmsg_path, commit_id_str,
7504 tag_name, got_repo_get_path(repo));
7505 if (err) {
7506 if (err->code != GOT_ERR_COMMIT_MSG_EMPTY &&
7507 tagmsg_path != NULL)
7508 preserve_tagmsg = 1;
7509 goto done;
7511 /* Editor is done; we can now apply unveil(2) */
7512 err = got_sigs_apply_unveil();
7513 if (err)
7514 goto done;
7515 err = apply_unveil(got_repo_get_path(repo), 0, NULL);
7516 if (err)
7517 goto done;
7520 err = got_object_tag_create(&tag_id, tag_name, commit_id,
7521 tagger, time(NULL), tagmsg ? tagmsg : tagmsg_arg, signer_id, repo,
7522 verbosity);
7523 if (err) {
7524 if (tagmsg_path)
7525 preserve_tagmsg = 1;
7526 goto done;
7529 err = got_ref_alloc(&ref, refname, tag_id);
7530 if (err) {
7531 if (tagmsg_path)
7532 preserve_tagmsg = 1;
7533 goto done;
7536 err = got_ref_write(ref, repo);
7537 if (err) {
7538 if (tagmsg_path)
7539 preserve_tagmsg = 1;
7540 goto done;
7543 err = got_object_id_str(&tag_id_str, tag_id);
7544 if (err) {
7545 if (tagmsg_path)
7546 preserve_tagmsg = 1;
7547 goto done;
7549 printf("Created tag %s\n", tag_id_str);
7550 done:
7551 if (preserve_tagmsg) {
7552 fprintf(stderr, "%s: tag message preserved in %s\n",
7553 getprogname(), tagmsg_path);
7554 } else if (tagmsg_path && unlink(tagmsg_path) == -1 && err == NULL)
7555 err = got_error_from_errno2("unlink", tagmsg_path);
7556 free(tag_id_str);
7557 if (ref)
7558 got_ref_close(ref);
7559 free(commit_id);
7560 free(commit_id_str);
7561 free(refname);
7562 free(tagmsg);
7563 free(tagmsg_path);
7564 got_ref_list_free(&refs);
7565 return err;
7568 static const struct got_error *
7569 cmd_tag(int argc, char *argv[])
7571 const struct got_error *error = NULL;
7572 struct got_repository *repo = NULL;
7573 struct got_worktree *worktree = NULL;
7574 char *cwd = NULL, *repo_path = NULL, *commit_id_str = NULL;
7575 char *gitconfig_path = NULL, *tagger = NULL;
7576 char *allowed_signers = NULL, *revoked_signers = NULL;
7577 const char *signer_id = NULL;
7578 const char *tag_name = NULL, *commit_id_arg = NULL, *tagmsg = NULL;
7579 int ch, do_list = 0, verify_tags = 0, verbosity = 0;
7580 int *pack_fds = NULL;
7582 #ifndef PROFILE
7583 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
7584 "sendfd unveil", NULL) == -1)
7585 err(1, "pledge");
7586 #endif
7588 while ((ch = getopt(argc, argv, "c:lm:r:s:Vv")) != -1) {
7589 switch (ch) {
7590 case 'c':
7591 commit_id_arg = optarg;
7592 break;
7593 case 'l':
7594 do_list = 1;
7595 break;
7596 case 'm':
7597 tagmsg = optarg;
7598 break;
7599 case 'r':
7600 repo_path = realpath(optarg, NULL);
7601 if (repo_path == NULL) {
7602 error = got_error_from_errno2("realpath",
7603 optarg);
7604 goto done;
7606 got_path_strip_trailing_slashes(repo_path);
7607 break;
7608 case 's':
7609 signer_id = optarg;
7610 break;
7611 case 'V':
7612 verify_tags = 1;
7613 break;
7614 case 'v':
7615 if (verbosity < 0)
7616 verbosity = 0;
7617 else if (verbosity < 3)
7618 verbosity++;
7619 break;
7620 default:
7621 usage_tag();
7622 /* NOTREACHED */
7626 argc -= optind;
7627 argv += optind;
7629 if (do_list || verify_tags) {
7630 if (commit_id_arg != NULL)
7631 errx(1,
7632 "-c option can only be used when creating a tag");
7633 if (tagmsg) {
7634 if (do_list)
7635 option_conflict('l', 'm');
7636 else
7637 option_conflict('V', 'm');
7639 if (signer_id) {
7640 if (do_list)
7641 option_conflict('l', 's');
7642 else
7643 option_conflict('V', 's');
7645 if (argc > 1)
7646 usage_tag();
7647 } else if (argc != 1)
7648 usage_tag();
7650 if (argc == 1)
7651 tag_name = argv[0];
7653 cwd = getcwd(NULL, 0);
7654 if (cwd == NULL) {
7655 error = got_error_from_errno("getcwd");
7656 goto done;
7659 error = got_repo_pack_fds_open(&pack_fds);
7660 if (error != NULL)
7661 goto done;
7663 if (repo_path == NULL) {
7664 error = got_worktree_open(&worktree, cwd);
7665 if (error && error->code != GOT_ERR_NOT_WORKTREE)
7666 goto done;
7667 else
7668 error = NULL;
7669 if (worktree) {
7670 repo_path =
7671 strdup(got_worktree_get_repo_path(worktree));
7672 if (repo_path == NULL)
7673 error = got_error_from_errno("strdup");
7674 if (error)
7675 goto done;
7676 } else {
7677 repo_path = strdup(cwd);
7678 if (repo_path == NULL) {
7679 error = got_error_from_errno("strdup");
7680 goto done;
7685 if (do_list || verify_tags) {
7686 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
7687 if (error != NULL)
7688 goto done;
7689 error = get_allowed_signers(&allowed_signers, repo, worktree);
7690 if (error)
7691 goto done;
7692 error = get_revoked_signers(&revoked_signers, repo, worktree);
7693 if (error)
7694 goto done;
7695 if (worktree) {
7696 /* Release work tree lock. */
7697 got_worktree_close(worktree);
7698 worktree = NULL;
7702 * Remove "cpath" promise unless needed for signature tmpfile
7703 * creation.
7705 if (verify_tags)
7706 got_sigs_apply_unveil();
7707 else {
7708 #ifndef PROFILE
7709 if (pledge("stdio rpath wpath flock proc exec sendfd "
7710 "unveil", NULL) == -1)
7711 err(1, "pledge");
7712 #endif
7714 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
7715 if (error)
7716 goto done;
7717 error = list_tags(repo, tag_name, verify_tags, allowed_signers,
7718 revoked_signers, verbosity);
7719 } else {
7720 error = get_gitconfig_path(&gitconfig_path);
7721 if (error)
7722 goto done;
7723 error = got_repo_open(&repo, repo_path, gitconfig_path,
7724 pack_fds);
7725 if (error != NULL)
7726 goto done;
7728 error = get_author(&tagger, repo, worktree);
7729 if (error)
7730 goto done;
7731 if (signer_id == NULL)
7732 signer_id = get_signer_id(repo, worktree);
7734 if (tagmsg) {
7735 if (signer_id) {
7736 error = got_sigs_apply_unveil();
7737 if (error)
7738 goto done;
7740 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
7741 if (error)
7742 goto done;
7745 if (commit_id_arg == NULL) {
7746 struct got_reference *head_ref;
7747 struct got_object_id *commit_id;
7748 error = got_ref_open(&head_ref, repo,
7749 worktree ? got_worktree_get_head_ref_name(worktree)
7750 : GOT_REF_HEAD, 0);
7751 if (error)
7752 goto done;
7753 error = got_ref_resolve(&commit_id, repo, head_ref);
7754 got_ref_close(head_ref);
7755 if (error)
7756 goto done;
7757 error = got_object_id_str(&commit_id_str, commit_id);
7758 free(commit_id);
7759 if (error)
7760 goto done;
7763 if (worktree) {
7764 /* Release work tree lock. */
7765 got_worktree_close(worktree);
7766 worktree = NULL;
7769 error = add_tag(repo, tagger, tag_name,
7770 commit_id_str ? commit_id_str : commit_id_arg, tagmsg,
7771 signer_id, verbosity);
7773 done:
7774 if (repo) {
7775 const struct got_error *close_err = got_repo_close(repo);
7776 if (error == NULL)
7777 error = close_err;
7779 if (worktree)
7780 got_worktree_close(worktree);
7781 if (pack_fds) {
7782 const struct got_error *pack_err =
7783 got_repo_pack_fds_close(pack_fds);
7784 if (error == NULL)
7785 error = pack_err;
7787 free(cwd);
7788 free(repo_path);
7789 free(gitconfig_path);
7790 free(commit_id_str);
7791 free(tagger);
7792 free(allowed_signers);
7793 free(revoked_signers);
7794 return error;
7797 __dead static void
7798 usage_add(void)
7800 fprintf(stderr, "usage: %s add [-IR] path ...\n", getprogname());
7801 exit(1);
7804 static const struct got_error *
7805 add_progress(void *arg, unsigned char status, const char *path)
7807 while (path[0] == '/')
7808 path++;
7809 printf("%c %s\n", status, path);
7810 return NULL;
7813 static const struct got_error *
7814 cmd_add(int argc, char *argv[])
7816 const struct got_error *error = NULL;
7817 struct got_repository *repo = NULL;
7818 struct got_worktree *worktree = NULL;
7819 char *cwd = NULL;
7820 struct got_pathlist_head paths;
7821 struct got_pathlist_entry *pe;
7822 int ch, can_recurse = 0, no_ignores = 0;
7823 int *pack_fds = NULL;
7825 TAILQ_INIT(&paths);
7827 #ifndef PROFILE
7828 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
7829 NULL) == -1)
7830 err(1, "pledge");
7831 #endif
7833 while ((ch = getopt(argc, argv, "IR")) != -1) {
7834 switch (ch) {
7835 case 'I':
7836 no_ignores = 1;
7837 break;
7838 case 'R':
7839 can_recurse = 1;
7840 break;
7841 default:
7842 usage_add();
7843 /* NOTREACHED */
7847 argc -= optind;
7848 argv += optind;
7850 if (argc < 1)
7851 usage_add();
7853 cwd = getcwd(NULL, 0);
7854 if (cwd == NULL) {
7855 error = got_error_from_errno("getcwd");
7856 goto done;
7859 error = got_repo_pack_fds_open(&pack_fds);
7860 if (error != NULL)
7861 goto done;
7863 error = got_worktree_open(&worktree, cwd);
7864 if (error) {
7865 if (error->code == GOT_ERR_NOT_WORKTREE)
7866 error = wrap_not_worktree_error(error, "add", cwd);
7867 goto done;
7870 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
7871 NULL, pack_fds);
7872 if (error != NULL)
7873 goto done;
7875 error = apply_unveil(got_repo_get_path(repo), 1,
7876 got_worktree_get_root_path(worktree));
7877 if (error)
7878 goto done;
7880 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
7881 if (error)
7882 goto done;
7884 if (!can_recurse) {
7885 char *ondisk_path;
7886 struct stat sb;
7887 TAILQ_FOREACH(pe, &paths, entry) {
7888 if (asprintf(&ondisk_path, "%s/%s",
7889 got_worktree_get_root_path(worktree),
7890 pe->path) == -1) {
7891 error = got_error_from_errno("asprintf");
7892 goto done;
7894 if (lstat(ondisk_path, &sb) == -1) {
7895 if (errno == ENOENT) {
7896 free(ondisk_path);
7897 continue;
7899 error = got_error_from_errno2("lstat",
7900 ondisk_path);
7901 free(ondisk_path);
7902 goto done;
7904 free(ondisk_path);
7905 if (S_ISDIR(sb.st_mode)) {
7906 error = got_error_msg(GOT_ERR_BAD_PATH,
7907 "adding directories requires -R option");
7908 goto done;
7913 error = got_worktree_schedule_add(worktree, &paths, add_progress,
7914 NULL, repo, no_ignores);
7915 done:
7916 if (repo) {
7917 const struct got_error *close_err = got_repo_close(repo);
7918 if (error == NULL)
7919 error = close_err;
7921 if (worktree)
7922 got_worktree_close(worktree);
7923 if (pack_fds) {
7924 const struct got_error *pack_err =
7925 got_repo_pack_fds_close(pack_fds);
7926 if (error == NULL)
7927 error = pack_err;
7929 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
7930 free(cwd);
7931 return error;
7934 __dead static void
7935 usage_remove(void)
7937 fprintf(stderr, "usage: %s remove [-fkR] [-s status-codes] path ...\n",
7938 getprogname());
7939 exit(1);
7942 static const struct got_error *
7943 print_remove_status(void *arg, unsigned char status,
7944 unsigned char staged_status, const char *path)
7946 while (path[0] == '/')
7947 path++;
7948 if (status == GOT_STATUS_NONEXISTENT)
7949 return NULL;
7950 if (status == staged_status && (status == GOT_STATUS_DELETE))
7951 status = GOT_STATUS_NO_CHANGE;
7952 printf("%c%c %s\n", status, staged_status, path);
7953 return NULL;
7956 static const struct got_error *
7957 cmd_remove(int argc, char *argv[])
7959 const struct got_error *error = NULL;
7960 struct got_worktree *worktree = NULL;
7961 struct got_repository *repo = NULL;
7962 const char *status_codes = NULL;
7963 char *cwd = NULL;
7964 struct got_pathlist_head paths;
7965 struct got_pathlist_entry *pe;
7966 int ch, delete_local_mods = 0, can_recurse = 0, keep_on_disk = 0, i;
7967 int ignore_missing_paths = 0;
7968 int *pack_fds = NULL;
7970 TAILQ_INIT(&paths);
7972 #ifndef PROFILE
7973 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
7974 NULL) == -1)
7975 err(1, "pledge");
7976 #endif
7978 while ((ch = getopt(argc, argv, "fkRs:")) != -1) {
7979 switch (ch) {
7980 case 'f':
7981 delete_local_mods = 1;
7982 ignore_missing_paths = 1;
7983 break;
7984 case 'k':
7985 keep_on_disk = 1;
7986 break;
7987 case 'R':
7988 can_recurse = 1;
7989 break;
7990 case 's':
7991 for (i = 0; optarg[i] != '\0'; i++) {
7992 switch (optarg[i]) {
7993 case GOT_STATUS_MODIFY:
7994 delete_local_mods = 1;
7995 break;
7996 case GOT_STATUS_MISSING:
7997 ignore_missing_paths = 1;
7998 break;
7999 default:
8000 errx(1, "invalid status code '%c'",
8001 optarg[i]);
8004 status_codes = optarg;
8005 break;
8006 default:
8007 usage_remove();
8008 /* NOTREACHED */
8012 argc -= optind;
8013 argv += optind;
8015 if (argc < 1)
8016 usage_remove();
8018 cwd = getcwd(NULL, 0);
8019 if (cwd == NULL) {
8020 error = got_error_from_errno("getcwd");
8021 goto done;
8024 error = got_repo_pack_fds_open(&pack_fds);
8025 if (error != NULL)
8026 goto done;
8028 error = got_worktree_open(&worktree, cwd);
8029 if (error) {
8030 if (error->code == GOT_ERR_NOT_WORKTREE)
8031 error = wrap_not_worktree_error(error, "remove", cwd);
8032 goto done;
8035 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
8036 NULL, pack_fds);
8037 if (error)
8038 goto done;
8040 error = apply_unveil(got_repo_get_path(repo), 1,
8041 got_worktree_get_root_path(worktree));
8042 if (error)
8043 goto done;
8045 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
8046 if (error)
8047 goto done;
8049 if (!can_recurse) {
8050 char *ondisk_path;
8051 struct stat sb;
8052 TAILQ_FOREACH(pe, &paths, entry) {
8053 if (asprintf(&ondisk_path, "%s/%s",
8054 got_worktree_get_root_path(worktree),
8055 pe->path) == -1) {
8056 error = got_error_from_errno("asprintf");
8057 goto done;
8059 if (lstat(ondisk_path, &sb) == -1) {
8060 if (errno == ENOENT) {
8061 free(ondisk_path);
8062 continue;
8064 error = got_error_from_errno2("lstat",
8065 ondisk_path);
8066 free(ondisk_path);
8067 goto done;
8069 free(ondisk_path);
8070 if (S_ISDIR(sb.st_mode)) {
8071 error = got_error_msg(GOT_ERR_BAD_PATH,
8072 "removing directories requires -R option");
8073 goto done;
8078 error = got_worktree_schedule_delete(worktree, &paths,
8079 delete_local_mods, status_codes, print_remove_status, NULL,
8080 repo, keep_on_disk, ignore_missing_paths);
8081 done:
8082 if (repo) {
8083 const struct got_error *close_err = got_repo_close(repo);
8084 if (error == NULL)
8085 error = close_err;
8087 if (worktree)
8088 got_worktree_close(worktree);
8089 if (pack_fds) {
8090 const struct got_error *pack_err =
8091 got_repo_pack_fds_close(pack_fds);
8092 if (error == NULL)
8093 error = pack_err;
8095 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
8096 free(cwd);
8097 return error;
8100 __dead static void
8101 usage_patch(void)
8103 fprintf(stderr, "usage: %s patch [-nR] [-c commit] [-p strip-count] "
8104 "[patchfile]\n", getprogname());
8105 exit(1);
8108 static const struct got_error *
8109 patch_from_stdin(int *patchfd)
8111 const struct got_error *err = NULL;
8112 ssize_t r;
8113 char buf[BUFSIZ];
8114 sig_t sighup, sigint, sigquit;
8116 *patchfd = got_opentempfd();
8117 if (*patchfd == -1)
8118 return got_error_from_errno("got_opentempfd");
8120 sighup = signal(SIGHUP, SIG_DFL);
8121 sigint = signal(SIGINT, SIG_DFL);
8122 sigquit = signal(SIGQUIT, SIG_DFL);
8124 for (;;) {
8125 r = read(0, buf, sizeof(buf));
8126 if (r == -1) {
8127 err = got_error_from_errno("read");
8128 break;
8130 if (r == 0)
8131 break;
8132 if (write(*patchfd, buf, r) == -1) {
8133 err = got_error_from_errno("write");
8134 break;
8138 signal(SIGHUP, sighup);
8139 signal(SIGINT, sigint);
8140 signal(SIGQUIT, sigquit);
8142 if (err == NULL && lseek(*patchfd, 0, SEEK_SET) == -1)
8143 err = got_error_from_errno("lseek");
8145 if (err != NULL) {
8146 close(*patchfd);
8147 *patchfd = -1;
8150 return err;
8153 struct got_patch_progress_arg {
8154 int did_something;
8155 int conflicts;
8156 int rejects;
8159 static const struct got_error *
8160 patch_progress(void *arg, const char *old, const char *new,
8161 unsigned char status, const struct got_error *error, int old_from,
8162 int old_lines, int new_from, int new_lines, int offset,
8163 int ws_mangled, const struct got_error *hunk_err)
8165 const char *path = new == NULL ? old : new;
8166 struct got_patch_progress_arg *a = arg;
8168 while (*path == '/')
8169 path++;
8171 if (status != GOT_STATUS_NO_CHANGE &&
8172 status != 0 /* per-hunk progress */) {
8173 printf("%c %s\n", status, path);
8174 a->did_something = 1;
8177 if (hunk_err == NULL) {
8178 if (status == GOT_STATUS_CANNOT_UPDATE)
8179 a->rejects++;
8180 else if (status == GOT_STATUS_CONFLICT)
8181 a->conflicts++;
8184 if (error != NULL)
8185 fprintf(stderr, "%s: %s\n", getprogname(), error->msg);
8187 if (offset != 0 || hunk_err != NULL || ws_mangled) {
8188 printf("@@ -%d,%d +%d,%d @@ ", old_from,
8189 old_lines, new_from, new_lines);
8190 if (hunk_err != NULL)
8191 printf("%s\n", hunk_err->msg);
8192 else if (offset != 0)
8193 printf("applied with offset %d\n", offset);
8194 else
8195 printf("hunk contains mangled whitespace\n");
8198 return NULL;
8201 static void
8202 print_patch_progress_stats(struct got_patch_progress_arg *ppa)
8204 if (!ppa->did_something)
8205 return;
8207 if (ppa->conflicts > 0)
8208 printf("Files with merge conflicts: %d\n", ppa->conflicts);
8210 if (ppa->rejects > 0) {
8211 printf("Files where patch failed to apply: %d\n",
8212 ppa->rejects);
8216 static const struct got_error *
8217 cmd_patch(int argc, char *argv[])
8219 const struct got_error *error = NULL, *close_error = NULL;
8220 struct got_worktree *worktree = NULL;
8221 struct got_repository *repo = NULL;
8222 struct got_reflist_head refs;
8223 struct got_object_id *commit_id = NULL;
8224 const char *commit_id_str = NULL;
8225 struct stat sb;
8226 const char *errstr;
8227 char *cwd = NULL;
8228 int ch, nop = 0, strip = -1, reverse = 0;
8229 int patchfd;
8230 int *pack_fds = NULL;
8231 struct got_patch_progress_arg ppa;
8233 TAILQ_INIT(&refs);
8235 #ifndef PROFILE
8236 if (pledge("stdio rpath wpath cpath fattr proc exec sendfd flock "
8237 "unveil", NULL) == -1)
8238 err(1, "pledge");
8239 #endif
8241 while ((ch = getopt(argc, argv, "c:np:R")) != -1) {
8242 switch (ch) {
8243 case 'c':
8244 commit_id_str = optarg;
8245 break;
8246 case 'n':
8247 nop = 1;
8248 break;
8249 case 'p':
8250 strip = strtonum(optarg, 0, INT_MAX, &errstr);
8251 if (errstr != NULL)
8252 errx(1, "pathname strip count is %s: %s",
8253 errstr, optarg);
8254 break;
8255 case 'R':
8256 reverse = 1;
8257 break;
8258 default:
8259 usage_patch();
8260 /* NOTREACHED */
8264 argc -= optind;
8265 argv += optind;
8267 if (argc == 0) {
8268 error = patch_from_stdin(&patchfd);
8269 if (error)
8270 return error;
8271 } else if (argc == 1) {
8272 patchfd = open(argv[0], O_RDONLY);
8273 if (patchfd == -1) {
8274 error = got_error_from_errno2("open", argv[0]);
8275 return error;
8277 if (fstat(patchfd, &sb) == -1) {
8278 error = got_error_from_errno2("fstat", argv[0]);
8279 goto done;
8281 if (!S_ISREG(sb.st_mode)) {
8282 error = got_error_path(argv[0], GOT_ERR_BAD_FILETYPE);
8283 goto done;
8285 } else
8286 usage_patch();
8288 if ((cwd = getcwd(NULL, 0)) == NULL) {
8289 error = got_error_from_errno("getcwd");
8290 goto done;
8293 error = got_repo_pack_fds_open(&pack_fds);
8294 if (error != NULL)
8295 goto done;
8297 error = got_worktree_open(&worktree, cwd);
8298 if (error != NULL)
8299 goto done;
8301 const char *repo_path = got_worktree_get_repo_path(worktree);
8302 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
8303 if (error != NULL)
8304 goto done;
8306 error = apply_unveil(got_repo_get_path(repo), 0,
8307 got_worktree_get_root_path(worktree));
8308 if (error != NULL)
8309 goto done;
8311 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
8312 if (error)
8313 goto done;
8315 if (commit_id_str != NULL) {
8316 error = got_repo_match_object_id(&commit_id, NULL,
8317 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
8318 if (error)
8319 goto done;
8322 memset(&ppa, 0, sizeof(ppa));
8323 error = got_patch(patchfd, worktree, repo, nop, strip, reverse,
8324 commit_id, patch_progress, &ppa, check_cancelled, NULL);
8325 print_patch_progress_stats(&ppa);
8326 done:
8327 got_ref_list_free(&refs);
8328 free(commit_id);
8329 if (repo) {
8330 close_error = got_repo_close(repo);
8331 if (error == NULL)
8332 error = close_error;
8334 if (worktree != NULL) {
8335 close_error = got_worktree_close(worktree);
8336 if (error == NULL)
8337 error = close_error;
8339 if (pack_fds) {
8340 const struct got_error *pack_err =
8341 got_repo_pack_fds_close(pack_fds);
8342 if (error == NULL)
8343 error = pack_err;
8345 free(cwd);
8346 return error;
8349 __dead static void
8350 usage_revert(void)
8352 fprintf(stderr, "usage: %s revert [-pR] [-F response-script] path ...\n",
8353 getprogname());
8354 exit(1);
8357 static const struct got_error *
8358 revert_progress(void *arg, unsigned char status, const char *path)
8360 if (status == GOT_STATUS_UNVERSIONED)
8361 return NULL;
8363 while (path[0] == '/')
8364 path++;
8365 printf("%c %s\n", status, path);
8366 return NULL;
8369 struct choose_patch_arg {
8370 FILE *patch_script_file;
8371 const char *action;
8374 static const struct got_error *
8375 show_change(unsigned char status, const char *path, FILE *patch_file, int n,
8376 int nchanges, const char *action)
8378 const struct got_error *err;
8379 char *line = NULL;
8380 size_t linesize = 0;
8381 ssize_t linelen;
8383 switch (status) {
8384 case GOT_STATUS_ADD:
8385 printf("A %s\n%s this addition? [y/n] ", path, action);
8386 break;
8387 case GOT_STATUS_DELETE:
8388 printf("D %s\n%s this deletion? [y/n] ", path, action);
8389 break;
8390 case GOT_STATUS_MODIFY:
8391 if (fseek(patch_file, 0L, SEEK_SET) == -1)
8392 return got_error_from_errno("fseek");
8393 printf(GOT_COMMIT_SEP_STR);
8394 while ((linelen = getline(&line, &linesize, patch_file)) != -1)
8395 printf("%s", line);
8396 if (linelen == -1 && ferror(patch_file)) {
8397 err = got_error_from_errno("getline");
8398 free(line);
8399 return err;
8401 free(line);
8402 printf(GOT_COMMIT_SEP_STR);
8403 printf("M %s (change %d of %d)\n%s this change? [y/n/q] ",
8404 path, n, nchanges, action);
8405 break;
8406 default:
8407 return got_error_path(path, GOT_ERR_FILE_STATUS);
8410 fflush(stdout);
8411 return NULL;
8414 static const struct got_error *
8415 choose_patch(int *choice, void *arg, unsigned char status, const char *path,
8416 FILE *patch_file, int n, int nchanges)
8418 const struct got_error *err = NULL;
8419 char *line = NULL;
8420 size_t linesize = 0;
8421 ssize_t linelen;
8422 int resp = ' ';
8423 struct choose_patch_arg *a = arg;
8425 *choice = GOT_PATCH_CHOICE_NONE;
8427 if (a->patch_script_file) {
8428 char *nl;
8429 err = show_change(status, path, patch_file, n, nchanges,
8430 a->action);
8431 if (err)
8432 return err;
8433 linelen = getline(&line, &linesize, a->patch_script_file);
8434 if (linelen == -1) {
8435 if (ferror(a->patch_script_file))
8436 return got_error_from_errno("getline");
8437 return NULL;
8439 nl = strchr(line, '\n');
8440 if (nl)
8441 *nl = '\0';
8442 if (strcmp(line, "y") == 0) {
8443 *choice = GOT_PATCH_CHOICE_YES;
8444 printf("y\n");
8445 } else if (strcmp(line, "n") == 0) {
8446 *choice = GOT_PATCH_CHOICE_NO;
8447 printf("n\n");
8448 } else if (strcmp(line, "q") == 0 &&
8449 status == GOT_STATUS_MODIFY) {
8450 *choice = GOT_PATCH_CHOICE_QUIT;
8451 printf("q\n");
8452 } else
8453 printf("invalid response '%s'\n", line);
8454 free(line);
8455 return NULL;
8458 while (resp != 'y' && resp != 'n' && resp != 'q') {
8459 err = show_change(status, path, patch_file, n, nchanges,
8460 a->action);
8461 if (err)
8462 return err;
8463 resp = getchar();
8464 if (resp == '\n')
8465 resp = getchar();
8466 if (status == GOT_STATUS_MODIFY) {
8467 if (resp != 'y' && resp != 'n' && resp != 'q') {
8468 printf("invalid response '%c'\n", resp);
8469 resp = ' ';
8471 } else if (resp != 'y' && resp != 'n') {
8472 printf("invalid response '%c'\n", resp);
8473 resp = ' ';
8477 if (resp == 'y')
8478 *choice = GOT_PATCH_CHOICE_YES;
8479 else if (resp == 'n')
8480 *choice = GOT_PATCH_CHOICE_NO;
8481 else if (resp == 'q' && status == GOT_STATUS_MODIFY)
8482 *choice = GOT_PATCH_CHOICE_QUIT;
8484 return NULL;
8487 struct wt_commitable_path_arg {
8488 struct got_pathlist_head *commit_paths;
8489 int *has_changes;
8493 * Shortcut work tree status callback to determine if the set of paths scanned
8494 * has at least one versioned path that is being modified and, if not NULL, is
8495 * in the arg->commit_paths list. Set arg and return GOT_ERR_FILE_MODIFIED as
8496 * soon as a path is passed with a status that satisfies this criteria.
8498 static const struct got_error *
8499 worktree_has_commitable_path(void *arg, unsigned char status,
8500 unsigned char staged_status, const char *path,
8501 struct got_object_id *blob_id, struct got_object_id *staged_blob_id,
8502 struct got_object_id *commit_id, int dirfd, const char *de_name)
8504 struct wt_commitable_path_arg *a = arg;
8506 if (status == staged_status && (status == GOT_STATUS_DELETE))
8507 status = GOT_STATUS_NO_CHANGE;
8509 if (!(status == GOT_STATUS_NO_CHANGE ||
8510 status == GOT_STATUS_UNVERSIONED) ||
8511 staged_status != GOT_STATUS_NO_CHANGE) {
8512 if (a->commit_paths != NULL) {
8513 struct got_pathlist_entry *pe;
8515 TAILQ_FOREACH(pe, a->commit_paths, entry) {
8516 if (strncmp(path, pe->path,
8517 pe->path_len) == 0) {
8518 *a->has_changes = 1;
8519 break;
8522 } else
8523 *a->has_changes = 1;
8525 if (*a->has_changes)
8526 return got_error(GOT_ERR_FILE_MODIFIED);
8529 return NULL;
8533 * Check that the changeset of the commit identified by id is
8534 * comprised of at least one modified path that is being committed.
8536 static const struct got_error *
8537 commit_path_changed_in_worktree(struct wt_commitable_path_arg *wcpa,
8538 struct got_object_id *id, struct got_worktree *worktree,
8539 struct got_repository *repo)
8541 const struct got_error *err;
8542 struct got_pathlist_head paths;
8543 struct got_commit_object *commit = NULL, *pcommit = NULL;
8544 struct got_tree_object *tree = NULL, *ptree = NULL;
8545 struct got_object_qid *pid;
8547 TAILQ_INIT(&paths);
8549 err = got_object_open_as_commit(&commit, repo, id);
8550 if (err)
8551 goto done;
8553 err = got_object_open_as_tree(&tree, repo,
8554 got_object_commit_get_tree_id(commit));
8555 if (err)
8556 goto done;
8558 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
8559 if (pid != NULL) {
8560 err = got_object_open_as_commit(&pcommit, repo, &pid->id);
8561 if (err)
8562 goto done;
8564 err = got_object_open_as_tree(&ptree, repo,
8565 got_object_commit_get_tree_id(pcommit));
8566 if (err)
8567 goto done;
8570 err = got_diff_tree(ptree, tree, NULL, NULL, -1, -1, "", "", repo,
8571 got_diff_tree_collect_changed_paths, &paths, 0);
8572 if (err)
8573 goto done;
8575 err = got_worktree_status(worktree, &paths, repo, 0,
8576 worktree_has_commitable_path, wcpa, check_cancelled, NULL);
8577 if (err && err->code == GOT_ERR_FILE_MODIFIED) {
8579 * At least one changed path in the referenced commit is
8580 * modified in the work tree, that's all we need to know!
8582 err = NULL;
8585 done:
8586 got_pathlist_free(&paths, GOT_PATHLIST_FREE_ALL);
8587 if (commit)
8588 got_object_commit_close(commit);
8589 if (pcommit)
8590 got_object_commit_close(pcommit);
8591 if (tree)
8592 got_object_tree_close(tree);
8593 if (ptree)
8594 got_object_tree_close(ptree);
8595 return err;
8599 * Remove any "logmsg" reference comprised entirely of paths that have
8600 * been reverted in this work tree. If any path in the logmsg ref changeset
8601 * remains in a changed state in the worktree, do not remove the reference.
8603 static const struct got_error *
8604 rm_logmsg_ref(struct got_worktree *worktree, struct got_repository *repo)
8606 const struct got_error *err;
8607 struct got_reflist_head refs;
8608 struct got_reflist_entry *re;
8609 struct got_commit_object *commit = NULL;
8610 struct got_object_id *commit_id = NULL;
8611 struct wt_commitable_path_arg wcpa;
8612 char *uuidstr = NULL;
8614 TAILQ_INIT(&refs);
8616 err = got_worktree_get_uuid(&uuidstr, worktree);
8617 if (err)
8618 goto done;
8620 err = got_ref_list(&refs, repo, "refs/got/worktree",
8621 got_ref_cmp_by_name, repo);
8622 if (err)
8623 goto done;
8625 TAILQ_FOREACH(re, &refs, entry) {
8626 const char *refname;
8627 int has_changes = 0;
8629 refname = got_ref_get_name(re->ref);
8631 if (!strncmp(refname, GOT_WORKTREE_CHERRYPICK_REF_PREFIX,
8632 GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN))
8633 refname += GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN + 1;
8634 else if (!strncmp(refname, GOT_WORKTREE_BACKOUT_REF_PREFIX,
8635 GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN))
8636 refname += GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN + 1;
8637 else
8638 continue;
8640 if (strncmp(refname, uuidstr, GOT_WORKTREE_UUID_STRLEN) == 0)
8641 refname += GOT_WORKTREE_UUID_STRLEN + 1; /* skip '-' */
8642 else
8643 continue;
8645 err = got_repo_match_object_id(&commit_id, NULL, refname,
8646 GOT_OBJ_TYPE_COMMIT, NULL, repo);
8647 if (err)
8648 goto done;
8650 err = got_object_open_as_commit(&commit, repo, commit_id);
8651 if (err)
8652 goto done;
8654 wcpa.commit_paths = NULL;
8655 wcpa.has_changes = &has_changes;
8657 err = commit_path_changed_in_worktree(&wcpa, commit_id,
8658 worktree, repo);
8659 if (err)
8660 goto done;
8662 if (!has_changes) {
8663 err = got_ref_delete(re->ref, repo);
8664 if (err)
8665 goto done;
8668 got_object_commit_close(commit);
8669 commit = NULL;
8670 free(commit_id);
8671 commit_id = NULL;
8674 done:
8675 free(uuidstr);
8676 free(commit_id);
8677 got_ref_list_free(&refs);
8678 if (commit)
8679 got_object_commit_close(commit);
8680 return err;
8683 static const struct got_error *
8684 cmd_revert(int argc, char *argv[])
8686 const struct got_error *error = NULL;
8687 struct got_worktree *worktree = NULL;
8688 struct got_repository *repo = NULL;
8689 char *cwd = NULL, *path = NULL;
8690 struct got_pathlist_head paths;
8691 struct got_pathlist_entry *pe;
8692 int ch, can_recurse = 0, pflag = 0;
8693 FILE *patch_script_file = NULL;
8694 const char *patch_script_path = NULL;
8695 struct choose_patch_arg cpa;
8696 int *pack_fds = NULL;
8698 TAILQ_INIT(&paths);
8700 #ifndef PROFILE
8701 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
8702 "unveil", NULL) == -1)
8703 err(1, "pledge");
8704 #endif
8706 while ((ch = getopt(argc, argv, "F:pR")) != -1) {
8707 switch (ch) {
8708 case 'F':
8709 patch_script_path = optarg;
8710 break;
8711 case 'p':
8712 pflag = 1;
8713 break;
8714 case 'R':
8715 can_recurse = 1;
8716 break;
8717 default:
8718 usage_revert();
8719 /* NOTREACHED */
8723 argc -= optind;
8724 argv += optind;
8726 if (argc < 1)
8727 usage_revert();
8728 if (patch_script_path && !pflag)
8729 errx(1, "-F option can only be used together with -p option");
8731 cwd = getcwd(NULL, 0);
8732 if (cwd == NULL) {
8733 error = got_error_from_errno("getcwd");
8734 goto done;
8737 error = got_repo_pack_fds_open(&pack_fds);
8738 if (error != NULL)
8739 goto done;
8741 error = got_worktree_open(&worktree, cwd);
8742 if (error) {
8743 if (error->code == GOT_ERR_NOT_WORKTREE)
8744 error = wrap_not_worktree_error(error, "revert", cwd);
8745 goto done;
8748 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
8749 NULL, pack_fds);
8750 if (error != NULL)
8751 goto done;
8753 if (patch_script_path) {
8754 patch_script_file = fopen(patch_script_path, "re");
8755 if (patch_script_file == NULL) {
8756 error = got_error_from_errno2("fopen",
8757 patch_script_path);
8758 goto done;
8763 * XXX "c" perm needed on repo dir to delete merge references.
8765 error = apply_unveil(got_repo_get_path(repo), 0,
8766 got_worktree_get_root_path(worktree));
8767 if (error)
8768 goto done;
8770 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
8771 if (error)
8772 goto done;
8774 if (!can_recurse) {
8775 char *ondisk_path;
8776 struct stat sb;
8777 TAILQ_FOREACH(pe, &paths, entry) {
8778 if (asprintf(&ondisk_path, "%s/%s",
8779 got_worktree_get_root_path(worktree),
8780 pe->path) == -1) {
8781 error = got_error_from_errno("asprintf");
8782 goto done;
8784 if (lstat(ondisk_path, &sb) == -1) {
8785 if (errno == ENOENT) {
8786 free(ondisk_path);
8787 continue;
8789 error = got_error_from_errno2("lstat",
8790 ondisk_path);
8791 free(ondisk_path);
8792 goto done;
8794 free(ondisk_path);
8795 if (S_ISDIR(sb.st_mode)) {
8796 error = got_error_msg(GOT_ERR_BAD_PATH,
8797 "reverting directories requires -R option");
8798 goto done;
8803 cpa.patch_script_file = patch_script_file;
8804 cpa.action = "revert";
8805 error = got_worktree_revert(worktree, &paths, revert_progress, NULL,
8806 pflag ? choose_patch : NULL, &cpa, repo);
8808 error = rm_logmsg_ref(worktree, repo);
8809 done:
8810 if (patch_script_file && fclose(patch_script_file) == EOF &&
8811 error == NULL)
8812 error = got_error_from_errno2("fclose", patch_script_path);
8813 if (repo) {
8814 const struct got_error *close_err = got_repo_close(repo);
8815 if (error == NULL)
8816 error = close_err;
8818 if (worktree)
8819 got_worktree_close(worktree);
8820 if (pack_fds) {
8821 const struct got_error *pack_err =
8822 got_repo_pack_fds_close(pack_fds);
8823 if (error == NULL)
8824 error = pack_err;
8826 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
8827 free(path);
8828 free(cwd);
8829 return error;
8832 __dead static void
8833 usage_commit(void)
8835 fprintf(stderr, "usage: %s commit [-CNnS] [-A author] [-F path] "
8836 "[-m message] [path ...]\n", getprogname());
8837 exit(1);
8840 struct collect_commit_logmsg_arg {
8841 const char *cmdline_log;
8842 const char *prepared_log;
8843 const char *merged_log;
8844 int non_interactive;
8845 const char *editor;
8846 const char *worktree_path;
8847 const char *branch_name;
8848 const char *repo_path;
8849 char *logmsg_path;
8853 static const struct got_error *
8854 read_prepared_logmsg(char **logmsg, const char *path)
8856 const struct got_error *err = NULL;
8857 FILE *f = NULL;
8858 struct stat sb;
8859 size_t r;
8861 *logmsg = NULL;
8862 memset(&sb, 0, sizeof(sb));
8864 f = fopen(path, "re");
8865 if (f == NULL)
8866 return got_error_from_errno2("fopen", path);
8868 if (fstat(fileno(f), &sb) == -1) {
8869 err = got_error_from_errno2("fstat", path);
8870 goto done;
8872 if (sb.st_size == 0) {
8873 err = got_error(GOT_ERR_COMMIT_MSG_EMPTY);
8874 goto done;
8877 *logmsg = malloc(sb.st_size + 1);
8878 if (*logmsg == NULL) {
8879 err = got_error_from_errno("malloc");
8880 goto done;
8883 r = fread(*logmsg, 1, sb.st_size, f);
8884 if (r != sb.st_size) {
8885 if (ferror(f))
8886 err = got_error_from_errno2("fread", path);
8887 else
8888 err = got_error(GOT_ERR_IO);
8889 goto done;
8891 (*logmsg)[sb.st_size] = '\0';
8892 done:
8893 if (fclose(f) == EOF && err == NULL)
8894 err = got_error_from_errno2("fclose", path);
8895 if (err) {
8896 free(*logmsg);
8897 *logmsg = NULL;
8899 return err;
8902 static const struct got_error *
8903 collect_commit_logmsg(struct got_pathlist_head *commitable_paths,
8904 const char *diff_path, char **logmsg, void *arg)
8906 char *initial_content = NULL;
8907 struct got_pathlist_entry *pe;
8908 const struct got_error *err = NULL;
8909 char *template = NULL;
8910 char *prepared_msg = NULL, *merged_msg = NULL;
8911 struct collect_commit_logmsg_arg *a = arg;
8912 int initial_content_len;
8913 int fd = -1;
8914 size_t len;
8916 /* if a message was specified on the command line, just use it */
8917 if (a->cmdline_log != NULL && *a->cmdline_log != '\0') {
8918 len = strlen(a->cmdline_log) + 1;
8919 *logmsg = malloc(len + 1);
8920 if (*logmsg == NULL)
8921 return got_error_from_errno("malloc");
8922 strlcpy(*logmsg, a->cmdline_log, len);
8923 return NULL;
8924 } else if (a->prepared_log != NULL && a->non_interactive)
8925 return read_prepared_logmsg(logmsg, a->prepared_log);
8927 if (asprintf(&template, "%s/logmsg", a->worktree_path) == -1)
8928 return got_error_from_errno("asprintf");
8930 err = got_opentemp_named_fd(&a->logmsg_path, &fd, template, "");
8931 if (err)
8932 goto done;
8934 if (a->prepared_log) {
8935 err = read_prepared_logmsg(&prepared_msg, a->prepared_log);
8936 if (err)
8937 goto done;
8938 } else if (a->merged_log) {
8939 err = read_prepared_logmsg(&merged_msg, a->merged_log);
8940 if (err)
8941 goto done;
8944 initial_content_len = asprintf(&initial_content,
8945 "%s%s\n# changes to be committed on branch %s:\n",
8946 prepared_msg ? prepared_msg : "",
8947 merged_msg ? merged_msg : "", a->branch_name);
8948 if (initial_content_len == -1) {
8949 err = got_error_from_errno("asprintf");
8950 goto done;
8953 if (write(fd, initial_content, initial_content_len) == -1) {
8954 err = got_error_from_errno2("write", a->logmsg_path);
8955 goto done;
8958 TAILQ_FOREACH(pe, commitable_paths, entry) {
8959 struct got_commitable *ct = pe->data;
8960 dprintf(fd, "# %c %s\n",
8961 got_commitable_get_status(ct),
8962 got_commitable_get_path(ct));
8965 if (diff_path) {
8966 dprintf(fd, "# detailed changes can be viewed in %s\n",
8967 diff_path);
8970 if (close(fd) == -1) {
8971 err = got_error_from_errno2("close", a->logmsg_path);
8972 goto done;
8974 fd = -1;
8976 err = edit_logmsg(logmsg, a->editor, a->logmsg_path, initial_content,
8977 initial_content_len, a->prepared_log ? 0 : 1);
8978 done:
8979 free(initial_content);
8980 free(template);
8981 free(prepared_msg);
8982 free(merged_msg);
8984 if (fd != -1 && close(fd) == -1 && err == NULL)
8985 err = got_error_from_errno2("close", a->logmsg_path);
8987 /* Editor is done; we can now apply unveil(2) */
8988 if (err == NULL)
8989 err = apply_unveil(a->repo_path, 0, a->worktree_path);
8990 if (err) {
8991 free(*logmsg);
8992 *logmsg = NULL;
8994 return err;
8997 static const struct got_error *
8998 cat_logmsg(FILE *f, struct got_commit_object *commit, const char *idstr,
8999 const char *type, int has_content)
9001 const struct got_error *err = NULL;
9002 char *logmsg = NULL;
9004 err = got_object_commit_get_logmsg(&logmsg, commit);
9005 if (err)
9006 return err;
9008 if (fprintf(f, "%s# log message of %s commit %s:%s",
9009 has_content ? "\n" : "", type, idstr, logmsg) < 0)
9010 err = got_ferror(f, GOT_ERR_IO);
9012 free(logmsg);
9013 return err;
9017 * Lookup "logmsg" references of backed-out and cherrypicked commits
9018 * belonging to the current work tree. If found, and the worktree has
9019 * at least one modified file that was changed in the referenced commit,
9020 * add its log message to a new temporary file at *logmsg_path.
9021 * Add all refs found to matched_refs to be scheduled for removal on
9022 * successful commit.
9024 static const struct got_error *
9025 lookup_logmsg_ref(char **logmsg_path, struct got_pathlist_head *paths,
9026 struct got_reflist_head *matched_refs, struct got_worktree *worktree,
9027 struct got_repository *repo)
9029 const struct got_error *err;
9030 struct got_commit_object *commit = NULL;
9031 struct got_object_id *id = NULL;
9032 struct got_reflist_head refs;
9033 struct got_reflist_entry *re, *re_match;
9034 FILE *f = NULL;
9035 char *uuidstr = NULL;
9036 int added_logmsg = 0;
9038 TAILQ_INIT(&refs);
9040 *logmsg_path = NULL;
9042 err = got_worktree_get_uuid(&uuidstr, worktree);
9043 if (err)
9044 goto done;
9046 err = got_ref_list(&refs, repo, "refs/got/worktree",
9047 got_ref_cmp_by_name, repo);
9048 if (err)
9049 goto done;
9051 TAILQ_FOREACH(re, &refs, entry) {
9052 const char *refname, *type;
9053 struct wt_commitable_path_arg wcpa;
9054 int add_logmsg = 0;
9056 refname = got_ref_get_name(re->ref);
9058 if (strncmp(refname, GOT_WORKTREE_CHERRYPICK_REF_PREFIX,
9059 GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN) == 0) {
9060 refname += GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN + 1;
9061 type = "cherrypicked";
9062 } else if (strncmp(refname, GOT_WORKTREE_BACKOUT_REF_PREFIX,
9063 GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN) == 0) {
9064 refname += GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN + 1;
9065 type = "backed-out";
9066 } else
9067 continue;
9069 if (strncmp(refname, uuidstr, GOT_WORKTREE_UUID_STRLEN) == 0)
9070 refname += GOT_WORKTREE_UUID_STRLEN + 1; /* skip '-' */
9071 else
9072 continue;
9074 err = got_repo_match_object_id(&id, NULL, refname,
9075 GOT_OBJ_TYPE_COMMIT, NULL, repo);
9076 if (err)
9077 goto done;
9079 err = got_object_open_as_commit(&commit, repo, id);
9080 if (err)
9081 goto done;
9083 wcpa.commit_paths = paths;
9084 wcpa.has_changes = &add_logmsg;
9086 err = commit_path_changed_in_worktree(&wcpa, id,
9087 worktree, repo);
9088 if (err)
9089 goto done;
9091 if (add_logmsg) {
9092 if (f == NULL) {
9093 err = got_opentemp_named(logmsg_path, &f,
9094 "got-commit-logmsg", "");
9095 if (err)
9096 goto done;
9098 err = cat_logmsg(f, commit, refname, type,
9099 added_logmsg);
9100 if (err)
9101 goto done;
9102 if (!added_logmsg)
9103 ++added_logmsg;
9105 err = got_reflist_entry_dup(&re_match, re);
9106 if (err)
9107 goto done;
9108 TAILQ_INSERT_HEAD(matched_refs, re_match, entry);
9111 got_object_commit_close(commit);
9112 commit = NULL;
9113 free(id);
9114 id = NULL;
9117 done:
9118 free(id);
9119 free(uuidstr);
9120 got_ref_list_free(&refs);
9121 if (commit)
9122 got_object_commit_close(commit);
9123 if (f && fclose(f) == EOF && err == NULL)
9124 err = got_error_from_errno("fclose");
9125 if (!added_logmsg) {
9126 if (*logmsg_path && unlink(*logmsg_path) != 0 && err == NULL)
9127 err = got_error_from_errno2("unlink", *logmsg_path);
9128 *logmsg_path = NULL;
9130 return err;
9133 static const struct got_error *
9134 cmd_commit(int argc, char *argv[])
9136 const struct got_error *error = NULL;
9137 struct got_worktree *worktree = NULL;
9138 struct got_repository *repo = NULL;
9139 char *cwd = NULL, *id_str = NULL;
9140 struct got_object_id *id = NULL;
9141 const char *logmsg = NULL;
9142 char *prepared_logmsg = NULL, *merged_logmsg = NULL;
9143 struct collect_commit_logmsg_arg cl_arg;
9144 const char *author = NULL;
9145 char *gitconfig_path = NULL, *editor = NULL, *committer = NULL;
9146 int ch, rebase_in_progress, histedit_in_progress, preserve_logmsg = 0;
9147 int allow_bad_symlinks = 0, non_interactive = 0, merge_in_progress = 0;
9148 int show_diff = 1, commit_conflicts = 0;
9149 struct got_pathlist_head paths;
9150 struct got_reflist_head refs;
9151 struct got_reflist_entry *re;
9152 int *pack_fds = NULL;
9154 TAILQ_INIT(&refs);
9155 TAILQ_INIT(&paths);
9156 cl_arg.logmsg_path = NULL;
9158 #ifndef PROFILE
9159 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
9160 "unveil", NULL) == -1)
9161 err(1, "pledge");
9162 #endif
9164 while ((ch = getopt(argc, argv, "A:CF:m:NnS")) != -1) {
9165 switch (ch) {
9166 case 'A':
9167 author = optarg;
9168 error = valid_author(author);
9169 if (error)
9170 return error;
9171 break;
9172 case 'C':
9173 commit_conflicts = 1;
9174 break;
9175 case 'F':
9176 if (logmsg != NULL)
9177 option_conflict('F', 'm');
9178 prepared_logmsg = realpath(optarg, NULL);
9179 if (prepared_logmsg == NULL)
9180 return got_error_from_errno2("realpath",
9181 optarg);
9182 break;
9183 case 'm':
9184 if (prepared_logmsg)
9185 option_conflict('m', 'F');
9186 logmsg = optarg;
9187 break;
9188 case 'N':
9189 non_interactive = 1;
9190 break;
9191 case 'n':
9192 show_diff = 0;
9193 break;
9194 case 'S':
9195 allow_bad_symlinks = 1;
9196 break;
9197 default:
9198 usage_commit();
9199 /* NOTREACHED */
9203 argc -= optind;
9204 argv += optind;
9206 cwd = getcwd(NULL, 0);
9207 if (cwd == NULL) {
9208 error = got_error_from_errno("getcwd");
9209 goto done;
9212 error = got_repo_pack_fds_open(&pack_fds);
9213 if (error != NULL)
9214 goto done;
9216 error = got_worktree_open(&worktree, cwd);
9217 if (error) {
9218 if (error->code == GOT_ERR_NOT_WORKTREE)
9219 error = wrap_not_worktree_error(error, "commit", cwd);
9220 goto done;
9223 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
9224 if (error)
9225 goto done;
9226 if (rebase_in_progress) {
9227 error = got_error(GOT_ERR_REBASING);
9228 goto done;
9231 error = got_worktree_histedit_in_progress(&histedit_in_progress,
9232 worktree);
9233 if (error)
9234 goto done;
9236 error = get_gitconfig_path(&gitconfig_path);
9237 if (error)
9238 goto done;
9239 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
9240 gitconfig_path, pack_fds);
9241 if (error != NULL)
9242 goto done;
9244 error = got_worktree_merge_in_progress(&merge_in_progress, worktree, repo);
9245 if (error)
9246 goto done;
9247 if (merge_in_progress) {
9248 error = got_error(GOT_ERR_MERGE_BUSY);
9249 goto done;
9252 error = get_author(&committer, repo, worktree);
9253 if (error)
9254 goto done;
9256 if (author == NULL)
9257 author = committer;
9260 * unveil(2) traverses exec(2); if an editor is used we have
9261 * to apply unveil after the log message has been written.
9263 if (logmsg == NULL || strlen(logmsg) == 0)
9264 error = get_editor(&editor);
9265 else
9266 error = apply_unveil(got_repo_get_path(repo), 0,
9267 got_worktree_get_root_path(worktree));
9268 if (error)
9269 goto done;
9271 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
9272 if (error)
9273 goto done;
9275 if (prepared_logmsg == NULL) {
9276 error = lookup_logmsg_ref(&merged_logmsg,
9277 argc > 0 ? &paths : NULL, &refs, worktree, repo);
9278 if (error)
9279 goto done;
9282 cl_arg.editor = editor;
9283 cl_arg.cmdline_log = logmsg;
9284 cl_arg.prepared_log = prepared_logmsg;
9285 cl_arg.merged_log = merged_logmsg;
9286 cl_arg.non_interactive = non_interactive;
9287 cl_arg.worktree_path = got_worktree_get_root_path(worktree);
9288 cl_arg.branch_name = got_worktree_get_head_ref_name(worktree);
9289 if (!histedit_in_progress) {
9290 if (strncmp(cl_arg.branch_name, "refs/heads/", 11) != 0) {
9291 error = got_error(GOT_ERR_COMMIT_BRANCH);
9292 goto done;
9294 cl_arg.branch_name += 11;
9296 cl_arg.repo_path = got_repo_get_path(repo);
9297 error = got_worktree_commit(&id, worktree, &paths, author, committer,
9298 allow_bad_symlinks, show_diff, commit_conflicts,
9299 collect_commit_logmsg, &cl_arg, print_status, NULL, repo);
9300 if (error) {
9301 if (error->code != GOT_ERR_COMMIT_MSG_EMPTY &&
9302 cl_arg.logmsg_path != NULL)
9303 preserve_logmsg = 1;
9304 goto done;
9307 error = got_object_id_str(&id_str, id);
9308 if (error)
9309 goto done;
9310 printf("Created commit %s\n", id_str);
9312 TAILQ_FOREACH(re, &refs, entry) {
9313 error = got_ref_delete(re->ref, repo);
9314 if (error)
9315 goto done;
9318 done:
9319 if (preserve_logmsg) {
9320 fprintf(stderr, "%s: log message preserved in %s\n",
9321 getprogname(), cl_arg.logmsg_path);
9322 } else if (cl_arg.logmsg_path && unlink(cl_arg.logmsg_path) == -1 &&
9323 error == NULL)
9324 error = got_error_from_errno2("unlink", cl_arg.logmsg_path);
9325 free(cl_arg.logmsg_path);
9326 if (merged_logmsg && unlink(merged_logmsg) == -1 && error == NULL)
9327 error = got_error_from_errno2("unlink", merged_logmsg);
9328 free(merged_logmsg);
9329 if (repo) {
9330 const struct got_error *close_err = got_repo_close(repo);
9331 if (error == NULL)
9332 error = close_err;
9334 if (worktree)
9335 got_worktree_close(worktree);
9336 if (pack_fds) {
9337 const struct got_error *pack_err =
9338 got_repo_pack_fds_close(pack_fds);
9339 if (error == NULL)
9340 error = pack_err;
9342 got_ref_list_free(&refs);
9343 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
9344 free(cwd);
9345 free(id_str);
9346 free(gitconfig_path);
9347 free(editor);
9348 free(committer);
9349 free(prepared_logmsg);
9350 return error;
9353 __dead static void
9354 usage_send(void)
9356 fprintf(stderr, "usage: %s send [-afqTv] [-b branch] [-d branch] "
9357 "[-r repository-path] [-t tag] [remote-repository]\n",
9358 getprogname());
9359 exit(1);
9362 static void
9363 print_load_info(int print_colored, int print_found, int print_trees,
9364 int ncolored, int nfound, int ntrees)
9366 if (print_colored) {
9367 printf("%d commit%s colored", ncolored,
9368 ncolored == 1 ? "" : "s");
9370 if (print_found) {
9371 printf("%s%d object%s found",
9372 ncolored > 0 ? "; " : "",
9373 nfound, nfound == 1 ? "" : "s");
9375 if (print_trees) {
9376 printf("; %d tree%s scanned", ntrees,
9377 ntrees == 1 ? "" : "s");
9381 struct got_send_progress_arg {
9382 char last_scaled_packsize[FMT_SCALED_STRSIZE];
9383 int verbosity;
9384 int last_ncolored;
9385 int last_nfound;
9386 int last_ntrees;
9387 int loading_done;
9388 int last_ncommits;
9389 int last_nobj_total;
9390 int last_p_deltify;
9391 int last_p_written;
9392 int last_p_sent;
9393 int printed_something;
9394 int sent_something;
9395 struct got_pathlist_head *delete_branches;
9398 static const struct got_error *
9399 send_progress(void *arg, int ncolored, int nfound, int ntrees,
9400 off_t packfile_size, int ncommits, int nobj_total, int nobj_deltify,
9401 int nobj_written, off_t bytes_sent, const char *refname,
9402 const char *errmsg, int success)
9404 struct got_send_progress_arg *a = arg;
9405 char scaled_packsize[FMT_SCALED_STRSIZE];
9406 char scaled_sent[FMT_SCALED_STRSIZE];
9407 int p_deltify = 0, p_written = 0, p_sent = 0;
9408 int print_colored = 0, print_found = 0, print_trees = 0;
9409 int print_searching = 0, print_total = 0;
9410 int print_deltify = 0, print_written = 0, print_sent = 0;
9412 if (a->verbosity < 0)
9413 return NULL;
9415 if (refname) {
9416 const char *status = success ? "accepted" : "rejected";
9418 if (success) {
9419 struct got_pathlist_entry *pe;
9420 TAILQ_FOREACH(pe, a->delete_branches, entry) {
9421 const char *branchname = pe->path;
9422 if (got_path_cmp(branchname, refname,
9423 strlen(branchname), strlen(refname)) == 0) {
9424 status = "deleted";
9425 a->sent_something = 1;
9426 break;
9431 if (a->printed_something)
9432 putchar('\n');
9433 printf("Server has %s %s", status, refname);
9434 if (errmsg)
9435 printf(": %s", errmsg);
9436 a->printed_something = 1;
9437 return NULL;
9440 if (a->last_ncolored != ncolored) {
9441 print_colored = 1;
9442 a->last_ncolored = ncolored;
9445 if (a->last_nfound != nfound) {
9446 print_colored = 1;
9447 print_found = 1;
9448 a->last_nfound = nfound;
9451 if (a->last_ntrees != ntrees) {
9452 print_colored = 1;
9453 print_found = 1;
9454 print_trees = 1;
9455 a->last_ntrees = ntrees;
9458 if ((print_colored || print_found || print_trees) &&
9459 !a->loading_done) {
9460 printf("\r");
9461 print_load_info(print_colored, print_found, print_trees,
9462 ncolored, nfound, ntrees);
9463 a->printed_something = 1;
9464 fflush(stdout);
9465 return NULL;
9466 } else if (!a->loading_done) {
9467 printf("\r");
9468 print_load_info(1, 1, 1, ncolored, nfound, ntrees);
9469 printf("\n");
9470 a->loading_done = 1;
9473 if (fmt_scaled(packfile_size, scaled_packsize) == -1)
9474 return got_error_from_errno("fmt_scaled");
9475 if (fmt_scaled(bytes_sent, scaled_sent) == -1)
9476 return got_error_from_errno("fmt_scaled");
9478 if (a->last_ncommits != ncommits) {
9479 print_searching = 1;
9480 a->last_ncommits = ncommits;
9483 if (a->last_nobj_total != nobj_total) {
9484 print_searching = 1;
9485 print_total = 1;
9486 a->last_nobj_total = nobj_total;
9489 if (packfile_size > 0 && (a->last_scaled_packsize[0] == '\0' ||
9490 strcmp(scaled_packsize, a->last_scaled_packsize)) != 0) {
9491 if (strlcpy(a->last_scaled_packsize, scaled_packsize,
9492 FMT_SCALED_STRSIZE) >= FMT_SCALED_STRSIZE)
9493 return got_error(GOT_ERR_NO_SPACE);
9496 if (nobj_deltify > 0 || nobj_written > 0) {
9497 if (nobj_deltify > 0) {
9498 p_deltify = (nobj_deltify * 100) / nobj_total;
9499 if (p_deltify != a->last_p_deltify) {
9500 a->last_p_deltify = p_deltify;
9501 print_searching = 1;
9502 print_total = 1;
9503 print_deltify = 1;
9506 if (nobj_written > 0) {
9507 p_written = (nobj_written * 100) / nobj_total;
9508 if (p_written != a->last_p_written) {
9509 a->last_p_written = p_written;
9510 print_searching = 1;
9511 print_total = 1;
9512 print_deltify = 1;
9513 print_written = 1;
9518 if (bytes_sent > 0) {
9519 p_sent = (bytes_sent * 100) / packfile_size;
9520 if (p_sent != a->last_p_sent) {
9521 a->last_p_sent = p_sent;
9522 print_searching = 1;
9523 print_total = 1;
9524 print_deltify = 1;
9525 print_written = 1;
9526 print_sent = 1;
9528 a->sent_something = 1;
9531 if (print_searching || print_total || print_deltify || print_written ||
9532 print_sent)
9533 printf("\r");
9534 if (print_searching)
9535 printf("packing %d reference%s", ncommits,
9536 ncommits == 1 ? "" : "s");
9537 if (print_total)
9538 printf("; %d object%s", nobj_total,
9539 nobj_total == 1 ? "" : "s");
9540 if (print_deltify)
9541 printf("; deltify: %d%%", p_deltify);
9542 if (print_sent)
9543 printf("; uploading pack: %*s %d%%", FMT_SCALED_STRSIZE - 2,
9544 scaled_packsize, p_sent);
9545 else if (print_written)
9546 printf("; writing pack: %*s %d%%", FMT_SCALED_STRSIZE - 2,
9547 scaled_packsize, p_written);
9548 if (print_searching || print_total || print_deltify ||
9549 print_written || print_sent) {
9550 a->printed_something = 1;
9551 fflush(stdout);
9553 return NULL;
9556 static const struct got_error *
9557 cmd_send(int argc, char *argv[])
9559 const struct got_error *error = NULL;
9560 char *cwd = NULL, *repo_path = NULL;
9561 const char *remote_name;
9562 char *proto = NULL, *host = NULL, *port = NULL;
9563 char *repo_name = NULL, *server_path = NULL;
9564 const struct got_remote_repo *remotes, *remote = NULL;
9565 int nremotes, nbranches = 0, ndelete_branches = 0;
9566 struct got_repository *repo = NULL;
9567 struct got_worktree *worktree = NULL;
9568 const struct got_gotconfig *repo_conf = NULL, *worktree_conf = NULL;
9569 struct got_pathlist_head branches;
9570 struct got_pathlist_head tags;
9571 struct got_reflist_head all_branches;
9572 struct got_reflist_head all_tags;
9573 struct got_pathlist_head delete_args;
9574 struct got_pathlist_head delete_branches;
9575 struct got_reflist_entry *re;
9576 struct got_pathlist_entry *pe;
9577 int i, ch, sendfd = -1, sendstatus;
9578 pid_t sendpid = -1;
9579 struct got_send_progress_arg spa;
9580 int verbosity = 0, overwrite_refs = 0;
9581 int send_all_branches = 0, send_all_tags = 0;
9582 struct got_reference *ref = NULL;
9583 int *pack_fds = NULL;
9585 TAILQ_INIT(&branches);
9586 TAILQ_INIT(&tags);
9587 TAILQ_INIT(&all_branches);
9588 TAILQ_INIT(&all_tags);
9589 TAILQ_INIT(&delete_args);
9590 TAILQ_INIT(&delete_branches);
9592 while ((ch = getopt(argc, argv, "ab:d:fqr:Tt:v")) != -1) {
9593 switch (ch) {
9594 case 'a':
9595 send_all_branches = 1;
9596 break;
9597 case 'b':
9598 error = got_pathlist_append(&branches, optarg, NULL);
9599 if (error)
9600 return error;
9601 nbranches++;
9602 break;
9603 case 'd':
9604 error = got_pathlist_append(&delete_args, optarg, NULL);
9605 if (error)
9606 return error;
9607 break;
9608 case 'f':
9609 overwrite_refs = 1;
9610 break;
9611 case 'q':
9612 verbosity = -1;
9613 break;
9614 case 'r':
9615 repo_path = realpath(optarg, NULL);
9616 if (repo_path == NULL)
9617 return got_error_from_errno2("realpath",
9618 optarg);
9619 got_path_strip_trailing_slashes(repo_path);
9620 break;
9621 case 'T':
9622 send_all_tags = 1;
9623 break;
9624 case 't':
9625 error = got_pathlist_append(&tags, optarg, NULL);
9626 if (error)
9627 return error;
9628 break;
9629 case 'v':
9630 if (verbosity < 0)
9631 verbosity = 0;
9632 else if (verbosity < 3)
9633 verbosity++;
9634 break;
9635 default:
9636 usage_send();
9637 /* NOTREACHED */
9640 argc -= optind;
9641 argv += optind;
9643 if (send_all_branches && !TAILQ_EMPTY(&branches))
9644 option_conflict('a', 'b');
9645 if (send_all_tags && !TAILQ_EMPTY(&tags))
9646 option_conflict('T', 't');
9649 if (argc == 0)
9650 remote_name = GOT_SEND_DEFAULT_REMOTE_NAME;
9651 else if (argc == 1)
9652 remote_name = argv[0];
9653 else
9654 usage_send();
9656 cwd = getcwd(NULL, 0);
9657 if (cwd == NULL) {
9658 error = got_error_from_errno("getcwd");
9659 goto done;
9662 error = got_repo_pack_fds_open(&pack_fds);
9663 if (error != NULL)
9664 goto done;
9666 if (repo_path == NULL) {
9667 error = got_worktree_open(&worktree, cwd);
9668 if (error && error->code != GOT_ERR_NOT_WORKTREE)
9669 goto done;
9670 else
9671 error = NULL;
9672 if (worktree) {
9673 repo_path =
9674 strdup(got_worktree_get_repo_path(worktree));
9675 if (repo_path == NULL)
9676 error = got_error_from_errno("strdup");
9677 if (error)
9678 goto done;
9679 } else {
9680 repo_path = strdup(cwd);
9681 if (repo_path == NULL) {
9682 error = got_error_from_errno("strdup");
9683 goto done;
9688 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
9689 if (error)
9690 goto done;
9692 if (worktree) {
9693 worktree_conf = got_worktree_get_gotconfig(worktree);
9694 if (worktree_conf) {
9695 got_gotconfig_get_remotes(&nremotes, &remotes,
9696 worktree_conf);
9697 for (i = 0; i < nremotes; i++) {
9698 if (strcmp(remotes[i].name, remote_name) == 0) {
9699 remote = &remotes[i];
9700 break;
9705 if (remote == NULL) {
9706 repo_conf = got_repo_get_gotconfig(repo);
9707 if (repo_conf) {
9708 got_gotconfig_get_remotes(&nremotes, &remotes,
9709 repo_conf);
9710 for (i = 0; i < nremotes; i++) {
9711 if (strcmp(remotes[i].name, remote_name) == 0) {
9712 remote = &remotes[i];
9713 break;
9718 if (remote == NULL) {
9719 got_repo_get_gitconfig_remotes(&nremotes, &remotes, repo);
9720 for (i = 0; i < nremotes; i++) {
9721 if (strcmp(remotes[i].name, remote_name) == 0) {
9722 remote = &remotes[i];
9723 break;
9727 if (remote == NULL) {
9728 error = got_error_path(remote_name, GOT_ERR_NO_REMOTE);
9729 goto done;
9732 error = got_dial_parse_uri(&proto, &host, &port, &server_path,
9733 &repo_name, remote->send_url);
9734 if (error)
9735 goto done;
9737 if (strcmp(proto, "git") == 0) {
9738 #ifndef PROFILE
9739 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
9740 "sendfd dns inet unveil", NULL) == -1)
9741 err(1, "pledge");
9742 #endif
9743 } else if (strcmp(proto, "git+ssh") == 0 ||
9744 strcmp(proto, "ssh") == 0) {
9745 #ifndef PROFILE
9746 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
9747 "sendfd unveil", NULL) == -1)
9748 err(1, "pledge");
9749 #endif
9750 } else if (strcmp(proto, "http") == 0 ||
9751 strcmp(proto, "git+http") == 0) {
9752 error = got_error_path(proto, GOT_ERR_NOT_IMPL);
9753 goto done;
9754 } else {
9755 error = got_error_path(proto, GOT_ERR_BAD_PROTO);
9756 goto done;
9759 error = got_dial_apply_unveil(proto);
9760 if (error)
9761 goto done;
9763 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
9764 if (error)
9765 goto done;
9767 if (send_all_branches) {
9768 error = got_ref_list(&all_branches, repo, "refs/heads",
9769 got_ref_cmp_by_name, NULL);
9770 if (error)
9771 goto done;
9772 TAILQ_FOREACH(re, &all_branches, entry) {
9773 const char *branchname = got_ref_get_name(re->ref);
9774 error = got_pathlist_append(&branches,
9775 branchname, NULL);
9776 if (error)
9777 goto done;
9778 nbranches++;
9780 } else if (nbranches == 0) {
9781 for (i = 0; i < remote->nsend_branches; i++) {
9782 error = got_pathlist_append(&branches,
9783 remote->send_branches[i], NULL);
9784 if (error)
9785 goto done;
9789 if (send_all_tags) {
9790 error = got_ref_list(&all_tags, repo, "refs/tags",
9791 got_ref_cmp_by_name, NULL);
9792 if (error)
9793 goto done;
9794 TAILQ_FOREACH(re, &all_tags, entry) {
9795 const char *tagname = got_ref_get_name(re->ref);
9796 error = got_pathlist_append(&tags,
9797 tagname, NULL);
9798 if (error)
9799 goto done;
9804 * To prevent accidents only branches in refs/heads/ can be deleted
9805 * with 'got send -d'.
9806 * Deleting anything else requires local repository access or Git.
9808 TAILQ_FOREACH(pe, &delete_args, entry) {
9809 const char *branchname = pe->path;
9810 char *s;
9811 struct got_pathlist_entry *new;
9812 if (strncmp(branchname, "refs/heads/", 11) == 0) {
9813 s = strdup(branchname);
9814 if (s == NULL) {
9815 error = got_error_from_errno("strdup");
9816 goto done;
9818 } else {
9819 if (asprintf(&s, "refs/heads/%s", branchname) == -1) {
9820 error = got_error_from_errno("asprintf");
9821 goto done;
9824 error = got_pathlist_insert(&new, &delete_branches, s, NULL);
9825 if (error || new == NULL /* duplicate */)
9826 free(s);
9827 if (error)
9828 goto done;
9829 ndelete_branches++;
9832 if (nbranches == 0 && ndelete_branches == 0) {
9833 struct got_reference *head_ref;
9834 if (worktree)
9835 error = got_ref_open(&head_ref, repo,
9836 got_worktree_get_head_ref_name(worktree), 0);
9837 else
9838 error = got_ref_open(&head_ref, repo, GOT_REF_HEAD, 0);
9839 if (error)
9840 goto done;
9841 if (got_ref_is_symbolic(head_ref)) {
9842 error = got_ref_resolve_symbolic(&ref, repo, head_ref);
9843 got_ref_close(head_ref);
9844 if (error)
9845 goto done;
9846 } else
9847 ref = head_ref;
9848 error = got_pathlist_append(&branches, got_ref_get_name(ref),
9849 NULL);
9850 if (error)
9851 goto done;
9852 nbranches++;
9855 if (verbosity >= 0) {
9856 printf("Connecting to \"%s\" %s://%s%s%s%s%s\n",
9857 remote->name, proto, host,
9858 port ? ":" : "", port ? port : "",
9859 *server_path == '/' ? "" : "/", server_path);
9862 error = got_send_connect(&sendpid, &sendfd, proto, host, port,
9863 server_path, verbosity);
9864 if (error)
9865 goto done;
9867 memset(&spa, 0, sizeof(spa));
9868 spa.last_scaled_packsize[0] = '\0';
9869 spa.last_p_deltify = -1;
9870 spa.last_p_written = -1;
9871 spa.verbosity = verbosity;
9872 spa.delete_branches = &delete_branches;
9873 error = got_send_pack(remote_name, &branches, &tags, &delete_branches,
9874 verbosity, overwrite_refs, sendfd, repo, send_progress, &spa,
9875 check_cancelled, NULL);
9876 if (spa.printed_something)
9877 putchar('\n');
9878 if (error)
9879 goto done;
9880 if (!spa.sent_something && verbosity >= 0)
9881 printf("Already up-to-date\n");
9882 done:
9883 if (sendpid > 0) {
9884 if (kill(sendpid, SIGTERM) == -1)
9885 error = got_error_from_errno("kill");
9886 if (waitpid(sendpid, &sendstatus, 0) == -1 && error == NULL)
9887 error = got_error_from_errno("waitpid");
9889 if (sendfd != -1 && close(sendfd) == -1 && error == NULL)
9890 error = got_error_from_errno("close");
9891 if (repo) {
9892 const struct got_error *close_err = got_repo_close(repo);
9893 if (error == NULL)
9894 error = close_err;
9896 if (worktree)
9897 got_worktree_close(worktree);
9898 if (pack_fds) {
9899 const struct got_error *pack_err =
9900 got_repo_pack_fds_close(pack_fds);
9901 if (error == NULL)
9902 error = pack_err;
9904 if (ref)
9905 got_ref_close(ref);
9906 got_pathlist_free(&branches, GOT_PATHLIST_FREE_NONE);
9907 got_pathlist_free(&tags, GOT_PATHLIST_FREE_NONE);
9908 got_ref_list_free(&all_branches);
9909 got_ref_list_free(&all_tags);
9910 got_pathlist_free(&delete_args, GOT_PATHLIST_FREE_NONE);
9911 got_pathlist_free(&delete_branches, GOT_PATHLIST_FREE_PATH);
9912 free(cwd);
9913 free(repo_path);
9914 free(proto);
9915 free(host);
9916 free(port);
9917 free(server_path);
9918 free(repo_name);
9919 return error;
9923 * Print and if delete is set delete all ref_prefix references.
9924 * If wanted_ref is not NULL, only print or delete this reference.
9926 static const struct got_error *
9927 process_logmsg_refs(const char *ref_prefix, size_t prefix_len,
9928 const char *wanted_ref, int delete, struct got_worktree *worktree,
9929 struct got_repository *repo)
9931 const struct got_error *err;
9932 struct got_pathlist_head paths;
9933 struct got_reflist_head refs;
9934 struct got_reflist_entry *re;
9935 struct got_reflist_object_id_map *refs_idmap = NULL;
9936 struct got_commit_object *commit = NULL;
9937 struct got_object_id *id = NULL;
9938 const char *header_prefix;
9939 char *uuidstr = NULL;
9940 int found = 0;
9942 TAILQ_INIT(&refs);
9943 TAILQ_INIT(&paths);
9945 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, repo);
9946 if (err)
9947 goto done;
9949 err = got_reflist_object_id_map_create(&refs_idmap, &refs, repo);
9950 if (err)
9951 goto done;
9953 if (worktree != NULL) {
9954 err = got_worktree_get_uuid(&uuidstr, worktree);
9955 if (err)
9956 goto done;
9959 if (wanted_ref) {
9960 if (strncmp(wanted_ref, "refs/heads/", 11) == 0)
9961 wanted_ref += 11;
9964 if (strcmp(ref_prefix, GOT_WORKTREE_BACKOUT_REF_PREFIX) == 0)
9965 header_prefix = "backout";
9966 else
9967 header_prefix = "cherrypick";
9969 TAILQ_FOREACH(re, &refs, entry) {
9970 const char *refname, *wt;
9972 refname = got_ref_get_name(re->ref);
9974 err = check_cancelled(NULL);
9975 if (err)
9976 goto done;
9978 if (strncmp(refname, ref_prefix, prefix_len) == 0)
9979 refname += prefix_len + 1; /* skip '-' delimiter */
9980 else
9981 continue;
9983 wt = refname;
9985 if (worktree == NULL || strncmp(refname, uuidstr,
9986 GOT_WORKTREE_UUID_STRLEN) == 0)
9987 refname += GOT_WORKTREE_UUID_STRLEN + 1; /* skip '-' */
9988 else
9989 continue;
9991 err = got_repo_match_object_id(&id, NULL, refname,
9992 GOT_OBJ_TYPE_COMMIT, NULL, repo);
9993 if (err)
9994 goto done;
9996 err = got_object_open_as_commit(&commit, repo, id);
9997 if (err)
9998 goto done;
10000 if (wanted_ref)
10001 found = strncmp(wanted_ref, refname,
10002 strlen(wanted_ref)) == 0;
10003 if (wanted_ref && !found) {
10004 struct got_reflist_head *ci_refs;
10006 ci_refs = got_reflist_object_id_map_lookup(refs_idmap,
10007 id);
10009 if (ci_refs) {
10010 char *refs_str = NULL;
10011 char const *r = NULL;
10013 err = build_refs_str(&refs_str, ci_refs, id,
10014 repo, 1);
10015 if (err)
10016 goto done;
10018 r = refs_str;
10019 while (r) {
10020 if (strncmp(r, wanted_ref,
10021 strlen(wanted_ref)) == 0) {
10022 found = 1;
10023 break;
10025 r = strchr(r, ' ');
10026 if (r)
10027 ++r;
10029 free(refs_str);
10033 if (wanted_ref == NULL || found) {
10034 if (delete) {
10035 err = got_ref_delete(re->ref, repo);
10036 if (err)
10037 goto done;
10038 printf("Deleted: ");
10039 err = print_commit_oneline(commit, id, repo,
10040 refs_idmap);
10041 } else {
10043 * Print paths modified by commit to help
10044 * associate commits with worktree changes.
10046 err = get_changed_paths(&paths, commit,
10047 repo, NULL);
10048 if (err)
10049 goto done;
10051 err = print_commit(commit, id, repo, NULL,
10052 &paths, NULL, 0, 0, refs_idmap, NULL,
10053 header_prefix);
10054 got_pathlist_free(&paths,
10055 GOT_PATHLIST_FREE_ALL);
10057 if (worktree == NULL)
10058 printf("work tree: %.*s\n\n",
10059 GOT_WORKTREE_UUID_STRLEN, wt);
10061 if (err || found)
10062 goto done;
10065 got_object_commit_close(commit);
10066 commit = NULL;
10067 free(id);
10068 id = NULL;
10071 if (wanted_ref != NULL && !found)
10072 err = got_error_fmt(GOT_ERR_NOT_REF, "%s", wanted_ref);
10074 done:
10075 free(id);
10076 free(uuidstr);
10077 got_ref_list_free(&refs);
10078 got_pathlist_free(&paths, GOT_PATHLIST_FREE_ALL);
10079 if (refs_idmap)
10080 got_reflist_object_id_map_free(refs_idmap);
10081 if (commit)
10082 got_object_commit_close(commit);
10083 return err;
10087 * Create new temp "logmsg" ref of the backed-out or cherrypicked commit
10088 * identified by id for log messages to prepopulate the editor on commit.
10090 static const struct got_error *
10091 logmsg_ref(struct got_object_id *id, const char *prefix,
10092 struct got_worktree *worktree, struct got_repository *repo)
10094 const struct got_error *err = NULL;
10095 char *idstr, *ref = NULL, *refname = NULL;
10096 int histedit_in_progress;
10097 int rebase_in_progress, merge_in_progress;
10100 * Silenty refuse to create merge reference if any histedit, merge,
10101 * or rebase operation is in progress.
10103 err = got_worktree_histedit_in_progress(&histedit_in_progress,
10104 worktree);
10105 if (err)
10106 return err;
10107 if (histedit_in_progress)
10108 return NULL;
10110 err = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
10111 if (err)
10112 return err;
10113 if (rebase_in_progress)
10114 return NULL;
10116 err = got_worktree_merge_in_progress(&merge_in_progress, worktree,
10117 repo);
10118 if (err)
10119 return err;
10120 if (merge_in_progress)
10121 return NULL;
10123 err = got_object_id_str(&idstr, id);
10124 if (err)
10125 return err;
10127 err = got_worktree_get_logmsg_ref_name(&refname, worktree, prefix);
10128 if (err)
10129 goto done;
10131 if (asprintf(&ref, "%s-%s", refname, idstr) == -1) {
10132 err = got_error_from_errno("asprintf");
10133 goto done;
10136 err = create_ref(ref, got_worktree_get_base_commit_id(worktree),
10137 -1, repo);
10138 done:
10139 free(ref);
10140 free(idstr);
10141 free(refname);
10142 return err;
10145 __dead static void
10146 usage_cherrypick(void)
10148 fprintf(stderr, "usage: %s cherrypick [-lX] [commit-id]\n",
10149 getprogname());
10150 exit(1);
10153 static const struct got_error *
10154 cmd_cherrypick(int argc, char *argv[])
10156 const struct got_error *error = NULL;
10157 struct got_worktree *worktree = NULL;
10158 struct got_repository *repo = NULL;
10159 char *cwd = NULL, *commit_id_str = NULL;
10160 struct got_object_id *commit_id = NULL;
10161 struct got_commit_object *commit = NULL;
10162 struct got_object_qid *pid;
10163 int ch, list_refs = 0, remove_refs = 0;
10164 struct got_update_progress_arg upa;
10165 int *pack_fds = NULL;
10167 #ifndef PROFILE
10168 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
10169 "unveil", NULL) == -1)
10170 err(1, "pledge");
10171 #endif
10173 while ((ch = getopt(argc, argv, "lX")) != -1) {
10174 switch (ch) {
10175 case 'l':
10176 list_refs = 1;
10177 break;
10178 case 'X':
10179 remove_refs = 1;
10180 break;
10181 default:
10182 usage_cherrypick();
10183 /* NOTREACHED */
10187 argc -= optind;
10188 argv += optind;
10190 if (list_refs || remove_refs) {
10191 if (argc != 0 && argc != 1)
10192 usage_cherrypick();
10193 } else if (argc != 1)
10194 usage_cherrypick();
10195 if (list_refs && remove_refs)
10196 option_conflict('l', 'X');
10198 cwd = getcwd(NULL, 0);
10199 if (cwd == NULL) {
10200 error = got_error_from_errno("getcwd");
10201 goto done;
10204 error = got_repo_pack_fds_open(&pack_fds);
10205 if (error != NULL)
10206 goto done;
10208 error = got_worktree_open(&worktree, cwd);
10209 if (error) {
10210 if (list_refs || remove_refs) {
10211 if (error->code != GOT_ERR_NOT_WORKTREE)
10212 goto done;
10213 } else {
10214 if (error->code == GOT_ERR_NOT_WORKTREE)
10215 error = wrap_not_worktree_error(error,
10216 "cherrypick", cwd);
10217 goto done;
10221 error = got_repo_open(&repo,
10222 worktree ? got_worktree_get_repo_path(worktree) : cwd,
10223 NULL, pack_fds);
10224 if (error != NULL)
10225 goto done;
10227 error = apply_unveil(got_repo_get_path(repo), 0,
10228 worktree ? got_worktree_get_root_path(worktree) : NULL);
10229 if (error)
10230 goto done;
10232 if (list_refs || remove_refs) {
10233 error = process_logmsg_refs(GOT_WORKTREE_CHERRYPICK_REF_PREFIX,
10234 GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN,
10235 argc == 1 ? argv[0] : NULL, remove_refs, worktree, repo);
10236 goto done;
10239 error = got_repo_match_object_id(&commit_id, NULL, argv[0],
10240 GOT_OBJ_TYPE_COMMIT, NULL, repo);
10241 if (error)
10242 goto done;
10243 error = got_object_id_str(&commit_id_str, commit_id);
10244 if (error)
10245 goto done;
10247 error = got_object_open_as_commit(&commit, repo, commit_id);
10248 if (error)
10249 goto done;
10250 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
10251 memset(&upa, 0, sizeof(upa));
10252 error = got_worktree_merge_files(worktree, pid ? &pid->id : NULL,
10253 commit_id, repo, update_progress, &upa, check_cancelled,
10254 NULL);
10255 if (error != NULL)
10256 goto done;
10258 if (upa.did_something) {
10259 error = logmsg_ref(commit_id,
10260 GOT_WORKTREE_CHERRYPICK_REF_PREFIX, worktree, repo);
10261 if (error)
10262 goto done;
10263 printf("Merged commit %s\n", commit_id_str);
10265 print_merge_progress_stats(&upa);
10266 done:
10267 free(cwd);
10268 if (commit)
10269 got_object_commit_close(commit);
10270 free(commit_id_str);
10271 if (worktree)
10272 got_worktree_close(worktree);
10273 if (repo) {
10274 const struct got_error *close_err = got_repo_close(repo);
10275 if (error == NULL)
10276 error = close_err;
10278 if (pack_fds) {
10279 const struct got_error *pack_err =
10280 got_repo_pack_fds_close(pack_fds);
10281 if (error == NULL)
10282 error = pack_err;
10285 return error;
10288 __dead static void
10289 usage_backout(void)
10291 fprintf(stderr, "usage: %s backout [-lX] [commit-id]\n", getprogname());
10292 exit(1);
10295 static const struct got_error *
10296 cmd_backout(int argc, char *argv[])
10298 const struct got_error *error = NULL;
10299 struct got_worktree *worktree = NULL;
10300 struct got_repository *repo = NULL;
10301 char *cwd = NULL, *commit_id_str = NULL;
10302 struct got_object_id *commit_id = NULL;
10303 struct got_commit_object *commit = NULL;
10304 struct got_object_qid *pid;
10305 int ch, list_refs = 0, remove_refs = 0;
10306 struct got_update_progress_arg upa;
10307 int *pack_fds = NULL;
10309 #ifndef PROFILE
10310 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
10311 "unveil", NULL) == -1)
10312 err(1, "pledge");
10313 #endif
10315 while ((ch = getopt(argc, argv, "lX")) != -1) {
10316 switch (ch) {
10317 case 'l':
10318 list_refs = 1;
10319 break;
10320 case 'X':
10321 remove_refs = 1;
10322 break;
10323 default:
10324 usage_backout();
10325 /* NOTREACHED */
10329 argc -= optind;
10330 argv += optind;
10332 if (list_refs || remove_refs) {
10333 if (argc != 0 && argc != 1)
10334 usage_backout();
10335 } else if (argc != 1)
10336 usage_backout();
10337 if (list_refs && remove_refs)
10338 option_conflict('l', 'X');
10340 cwd = getcwd(NULL, 0);
10341 if (cwd == NULL) {
10342 error = got_error_from_errno("getcwd");
10343 goto done;
10346 error = got_repo_pack_fds_open(&pack_fds);
10347 if (error != NULL)
10348 goto done;
10350 error = got_worktree_open(&worktree, cwd);
10351 if (error) {
10352 if (list_refs || remove_refs) {
10353 if (error->code != GOT_ERR_NOT_WORKTREE)
10354 goto done;
10355 } else {
10356 if (error->code == GOT_ERR_NOT_WORKTREE)
10357 error = wrap_not_worktree_error(error,
10358 "backout", cwd);
10359 goto done;
10363 error = got_repo_open(&repo,
10364 worktree ? got_worktree_get_repo_path(worktree) : cwd,
10365 NULL, pack_fds);
10366 if (error != NULL)
10367 goto done;
10369 error = apply_unveil(got_repo_get_path(repo), 0,
10370 worktree ? got_worktree_get_root_path(worktree) : NULL);
10371 if (error)
10372 goto done;
10374 if (list_refs || remove_refs) {
10375 error = process_logmsg_refs(GOT_WORKTREE_BACKOUT_REF_PREFIX,
10376 GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN,
10377 argc == 1 ? argv[0] : NULL, remove_refs, worktree, repo);
10378 goto done;
10381 error = got_repo_match_object_id(&commit_id, NULL, argv[0],
10382 GOT_OBJ_TYPE_COMMIT, NULL, repo);
10383 if (error)
10384 goto done;
10385 error = got_object_id_str(&commit_id_str, commit_id);
10386 if (error)
10387 goto done;
10389 error = got_object_open_as_commit(&commit, repo, commit_id);
10390 if (error)
10391 goto done;
10392 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
10393 if (pid == NULL) {
10394 error = got_error(GOT_ERR_ROOT_COMMIT);
10395 goto done;
10398 memset(&upa, 0, sizeof(upa));
10399 error = got_worktree_merge_files(worktree, commit_id, &pid->id,
10400 repo, update_progress, &upa, check_cancelled, NULL);
10401 if (error != NULL)
10402 goto done;
10404 if (upa.did_something) {
10405 error = logmsg_ref(commit_id, GOT_WORKTREE_BACKOUT_REF_PREFIX,
10406 worktree, repo);
10407 if (error)
10408 goto done;
10409 printf("Backed out commit %s\n", commit_id_str);
10411 print_merge_progress_stats(&upa);
10412 done:
10413 free(cwd);
10414 if (commit)
10415 got_object_commit_close(commit);
10416 free(commit_id_str);
10417 if (worktree)
10418 got_worktree_close(worktree);
10419 if (repo) {
10420 const struct got_error *close_err = got_repo_close(repo);
10421 if (error == NULL)
10422 error = close_err;
10424 if (pack_fds) {
10425 const struct got_error *pack_err =
10426 got_repo_pack_fds_close(pack_fds);
10427 if (error == NULL)
10428 error = pack_err;
10430 return error;
10433 __dead static void
10434 usage_rebase(void)
10436 fprintf(stderr, "usage: %s rebase [-aCclX] [branch]\n", getprogname());
10437 exit(1);
10440 static void
10441 trim_logmsg(char *logmsg, int limit)
10443 char *nl;
10444 size_t len;
10446 len = strlen(logmsg);
10447 if (len > limit)
10448 len = limit;
10449 logmsg[len] = '\0';
10450 nl = strchr(logmsg, '\n');
10451 if (nl)
10452 *nl = '\0';
10455 static const struct got_error *
10456 get_short_logmsg(char **logmsg, int limit, struct got_commit_object *commit)
10458 const struct got_error *err;
10459 char *logmsg0 = NULL;
10460 const char *s;
10462 err = got_object_commit_get_logmsg(&logmsg0, commit);
10463 if (err)
10464 return err;
10466 s = logmsg0;
10467 while (isspace((unsigned char)s[0]))
10468 s++;
10470 *logmsg = strdup(s);
10471 if (*logmsg == NULL) {
10472 err = got_error_from_errno("strdup");
10473 goto done;
10476 trim_logmsg(*logmsg, limit);
10477 done:
10478 free(logmsg0);
10479 return err;
10482 static const struct got_error *
10483 show_rebase_merge_conflict(struct got_object_id *id,
10484 struct got_repository *repo)
10486 const struct got_error *err;
10487 struct got_commit_object *commit = NULL;
10488 char *id_str = NULL, *logmsg = NULL;
10490 err = got_object_open_as_commit(&commit, repo, id);
10491 if (err)
10492 return err;
10494 err = got_object_id_str(&id_str, id);
10495 if (err)
10496 goto done;
10498 id_str[12] = '\0';
10500 err = get_short_logmsg(&logmsg, 42, commit);
10501 if (err)
10502 goto done;
10504 printf("%s -> merge conflict: %s\n", id_str, logmsg);
10505 done:
10506 free(id_str);
10507 got_object_commit_close(commit);
10508 free(logmsg);
10509 return err;
10512 static const struct got_error *
10513 show_rebase_progress(struct got_commit_object *commit,
10514 struct got_object_id *old_id, struct got_object_id *new_id)
10516 const struct got_error *err;
10517 char *old_id_str = NULL, *new_id_str = NULL, *logmsg = NULL;
10519 err = got_object_id_str(&old_id_str, old_id);
10520 if (err)
10521 goto done;
10523 if (new_id) {
10524 err = got_object_id_str(&new_id_str, new_id);
10525 if (err)
10526 goto done;
10529 old_id_str[12] = '\0';
10530 if (new_id_str)
10531 new_id_str[12] = '\0';
10533 err = get_short_logmsg(&logmsg, 42, commit);
10534 if (err)
10535 goto done;
10537 printf("%s -> %s: %s\n", old_id_str,
10538 new_id_str ? new_id_str : "no-op change", logmsg);
10539 done:
10540 free(old_id_str);
10541 free(new_id_str);
10542 free(logmsg);
10543 return err;
10546 static const struct got_error *
10547 rebase_complete(struct got_worktree *worktree, struct got_fileindex *fileindex,
10548 struct got_reference *branch, struct got_reference *tmp_branch,
10549 struct got_repository *repo, int create_backup)
10551 printf("Switching work tree to %s\n", got_ref_get_name(branch));
10552 return got_worktree_rebase_complete(worktree, fileindex,
10553 tmp_branch, branch, repo, create_backup);
10556 static const struct got_error *
10557 rebase_commit(struct got_pathlist_head *merged_paths,
10558 struct got_worktree *worktree, struct got_fileindex *fileindex,
10559 struct got_reference *tmp_branch, const char *committer,
10560 struct got_object_id *commit_id, int allow_conflict,
10561 struct got_repository *repo)
10563 const struct got_error *error;
10564 struct got_commit_object *commit;
10565 struct got_object_id *new_commit_id;
10567 error = got_object_open_as_commit(&commit, repo, commit_id);
10568 if (error)
10569 return error;
10571 error = got_worktree_rebase_commit(&new_commit_id, merged_paths,
10572 worktree, fileindex, tmp_branch, committer, commit, commit_id,
10573 allow_conflict, repo);
10574 if (error) {
10575 if (error->code != GOT_ERR_COMMIT_NO_CHANGES)
10576 goto done;
10577 error = show_rebase_progress(commit, commit_id, NULL);
10578 } else {
10579 error = show_rebase_progress(commit, commit_id, new_commit_id);
10580 free(new_commit_id);
10582 done:
10583 got_object_commit_close(commit);
10584 return error;
10587 struct check_path_prefix_arg {
10588 const char *path_prefix;
10589 size_t len;
10590 int errcode;
10593 static const struct got_error *
10594 check_path_prefix_in_diff(void *arg, struct got_blob_object *blob1,
10595 struct got_blob_object *blob2, FILE *f1, FILE *f2,
10596 struct got_object_id *id1, struct got_object_id *id2,
10597 const char *path1, const char *path2,
10598 mode_t mode1, mode_t mode2, struct got_repository *repo)
10600 struct check_path_prefix_arg *a = arg;
10602 if ((path1 && !got_path_is_child(path1, a->path_prefix, a->len)) ||
10603 (path2 && !got_path_is_child(path2, a->path_prefix, a->len)))
10604 return got_error(a->errcode);
10606 return NULL;
10609 static const struct got_error *
10610 check_path_prefix(struct got_object_id *parent_id,
10611 struct got_object_id *commit_id, const char *path_prefix,
10612 int errcode, struct got_repository *repo)
10614 const struct got_error *err;
10615 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
10616 struct got_commit_object *commit = NULL, *parent_commit = NULL;
10617 struct check_path_prefix_arg cpp_arg;
10619 if (got_path_is_root_dir(path_prefix))
10620 return NULL;
10622 err = got_object_open_as_commit(&commit, repo, commit_id);
10623 if (err)
10624 goto done;
10626 err = got_object_open_as_commit(&parent_commit, repo, parent_id);
10627 if (err)
10628 goto done;
10630 err = got_object_open_as_tree(&tree1, repo,
10631 got_object_commit_get_tree_id(parent_commit));
10632 if (err)
10633 goto done;
10635 err = got_object_open_as_tree(&tree2, repo,
10636 got_object_commit_get_tree_id(commit));
10637 if (err)
10638 goto done;
10640 cpp_arg.path_prefix = path_prefix;
10641 while (cpp_arg.path_prefix[0] == '/')
10642 cpp_arg.path_prefix++;
10643 cpp_arg.len = strlen(cpp_arg.path_prefix);
10644 cpp_arg.errcode = errcode;
10645 err = got_diff_tree(tree1, tree2, NULL, NULL, -1, -1, "", "", repo,
10646 check_path_prefix_in_diff, &cpp_arg, 0);
10647 done:
10648 if (tree1)
10649 got_object_tree_close(tree1);
10650 if (tree2)
10651 got_object_tree_close(tree2);
10652 if (commit)
10653 got_object_commit_close(commit);
10654 if (parent_commit)
10655 got_object_commit_close(parent_commit);
10656 return err;
10659 static const struct got_error *
10660 collect_commits(struct got_object_id_queue *commits,
10661 struct got_object_id *initial_commit_id,
10662 struct got_object_id *iter_start_id, struct got_object_id *iter_stop_id,
10663 const char *path_prefix, int path_prefix_errcode,
10664 struct got_repository *repo)
10666 const struct got_error *err = NULL;
10667 struct got_commit_graph *graph = NULL;
10668 struct got_object_id parent_id, commit_id;
10669 struct got_object_qid *qid;
10671 err = got_commit_graph_open(&graph, "/", 1);
10672 if (err)
10673 return err;
10675 err = got_commit_graph_iter_start(graph, iter_start_id, repo,
10676 check_cancelled, NULL);
10677 if (err)
10678 goto done;
10680 memcpy(&commit_id, initial_commit_id, sizeof(commit_id));
10681 while (got_object_id_cmp(&commit_id, iter_stop_id) != 0) {
10682 err = got_commit_graph_iter_next(&parent_id, graph, repo,
10683 check_cancelled, NULL);
10684 if (err) {
10685 if (err->code == GOT_ERR_ITER_COMPLETED) {
10686 err = got_error_msg(GOT_ERR_ANCESTRY,
10687 "ran out of commits to rebase before "
10688 "youngest common ancestor commit has "
10689 "been reached?!?");
10691 goto done;
10692 } else {
10693 err = check_path_prefix(&parent_id, &commit_id,
10694 path_prefix, path_prefix_errcode, repo);
10695 if (err)
10696 goto done;
10698 err = got_object_qid_alloc(&qid, &commit_id);
10699 if (err)
10700 goto done;
10701 STAILQ_INSERT_HEAD(commits, qid, entry);
10703 memcpy(&commit_id, &parent_id, sizeof(commit_id));
10706 done:
10707 got_commit_graph_close(graph);
10708 return err;
10711 static const struct got_error *
10712 get_commit_brief_str(char **brief_str, struct got_commit_object *commit)
10714 const struct got_error *err = NULL;
10715 time_t committer_time;
10716 struct tm tm;
10717 char datebuf[11]; /* YYYY-MM-DD + NUL */
10718 char *author0 = NULL, *author, *smallerthan;
10719 char *logmsg0 = NULL, *logmsg, *newline;
10721 committer_time = got_object_commit_get_committer_time(commit);
10722 if (gmtime_r(&committer_time, &tm) == NULL)
10723 return got_error_from_errno("gmtime_r");
10724 if (strftime(datebuf, sizeof(datebuf), "%G-%m-%d", &tm) == 0)
10725 return got_error(GOT_ERR_NO_SPACE);
10727 author0 = strdup(got_object_commit_get_author(commit));
10728 if (author0 == NULL)
10729 return got_error_from_errno("strdup");
10730 author = author0;
10731 smallerthan = strchr(author, '<');
10732 if (smallerthan && smallerthan[1] != '\0')
10733 author = smallerthan + 1;
10734 author[strcspn(author, "@>")] = '\0';
10736 err = got_object_commit_get_logmsg(&logmsg0, commit);
10737 if (err)
10738 goto done;
10739 logmsg = logmsg0;
10740 while (*logmsg == '\n')
10741 logmsg++;
10742 newline = strchr(logmsg, '\n');
10743 if (newline)
10744 *newline = '\0';
10746 if (asprintf(brief_str, "%s %s %s",
10747 datebuf, author, logmsg) == -1)
10748 err = got_error_from_errno("asprintf");
10749 done:
10750 free(author0);
10751 free(logmsg0);
10752 return err;
10755 static const struct got_error *
10756 delete_backup_ref(struct got_reference *ref, struct got_object_id *id,
10757 struct got_repository *repo)
10759 const struct got_error *err;
10760 char *id_str;
10762 err = got_object_id_str(&id_str, id);
10763 if (err)
10764 return err;
10766 err = got_ref_delete(ref, repo);
10767 if (err)
10768 goto done;
10770 printf("Deleted %s: %s\n", got_ref_get_name(ref), id_str);
10771 done:
10772 free(id_str);
10773 return err;
10776 static const struct got_error *
10777 print_backup_ref(const char *branch_name, const char *new_id_str,
10778 struct got_object_id *old_commit_id, struct got_commit_object *old_commit,
10779 struct got_reflist_object_id_map *refs_idmap,
10780 struct got_repository *repo)
10782 const struct got_error *err = NULL;
10783 struct got_reflist_head *refs;
10784 char *refs_str = NULL;
10785 struct got_object_id *new_commit_id = NULL;
10786 struct got_commit_object *new_commit = NULL;
10787 char *new_commit_brief_str = NULL;
10788 struct got_object_id *yca_id = NULL;
10789 struct got_commit_object *yca_commit = NULL;
10790 char *yca_id_str = NULL, *yca_brief_str = NULL;
10791 char *custom_refs_str;
10793 if (asprintf(&custom_refs_str, "formerly %s", branch_name) == -1)
10794 return got_error_from_errno("asprintf");
10796 err = print_commit(old_commit, old_commit_id, repo, NULL, NULL, NULL,
10797 0, 0, refs_idmap, custom_refs_str, NULL);
10798 if (err)
10799 goto done;
10801 err = got_object_resolve_id_str(&new_commit_id, repo, new_id_str);
10802 if (err)
10803 goto done;
10805 refs = got_reflist_object_id_map_lookup(refs_idmap, new_commit_id);
10806 if (refs) {
10807 err = build_refs_str(&refs_str, refs, new_commit_id, repo, 0);
10808 if (err)
10809 goto done;
10812 err = got_object_open_as_commit(&new_commit, repo, new_commit_id);
10813 if (err)
10814 goto done;
10816 err = get_commit_brief_str(&new_commit_brief_str, new_commit);
10817 if (err)
10818 goto done;
10820 err = got_commit_graph_find_youngest_common_ancestor(&yca_id,
10821 old_commit_id, new_commit_id, 1, repo, check_cancelled, NULL);
10822 if (err)
10823 goto done;
10825 printf("has become commit %s%s%s%s\n %s\n", new_id_str,
10826 refs_str ? " (" : "", refs_str ? refs_str : "",
10827 refs_str ? ")" : "", new_commit_brief_str);
10828 if (yca_id && got_object_id_cmp(yca_id, new_commit_id) != 0 &&
10829 got_object_id_cmp(yca_id, old_commit_id) != 0) {
10830 free(refs_str);
10831 refs_str = NULL;
10833 err = got_object_open_as_commit(&yca_commit, repo, yca_id);
10834 if (err)
10835 goto done;
10837 err = get_commit_brief_str(&yca_brief_str, yca_commit);
10838 if (err)
10839 goto done;
10841 err = got_object_id_str(&yca_id_str, yca_id);
10842 if (err)
10843 goto done;
10845 refs = got_reflist_object_id_map_lookup(refs_idmap, yca_id);
10846 if (refs) {
10847 err = build_refs_str(&refs_str, refs, yca_id, repo, 0);
10848 if (err)
10849 goto done;
10851 printf("history forked at %s%s%s%s\n %s\n",
10852 yca_id_str,
10853 refs_str ? " (" : "", refs_str ? refs_str : "",
10854 refs_str ? ")" : "", yca_brief_str);
10856 done:
10857 free(custom_refs_str);
10858 free(new_commit_id);
10859 free(refs_str);
10860 free(yca_id);
10861 free(yca_id_str);
10862 free(yca_brief_str);
10863 if (new_commit)
10864 got_object_commit_close(new_commit);
10865 if (yca_commit)
10866 got_object_commit_close(yca_commit);
10868 return err;
10871 static const struct got_error *
10872 worktree_has_logmsg_ref(const char *caller, struct got_worktree *worktree,
10873 struct got_repository *repo)
10875 const struct got_error *err;
10876 struct got_reflist_head refs;
10877 struct got_reflist_entry *re;
10878 char *uuidstr = NULL;
10879 static char msg[160];
10881 TAILQ_INIT(&refs);
10883 err = got_worktree_get_uuid(&uuidstr, worktree);
10884 if (err)
10885 goto done;
10887 err = got_ref_list(&refs, repo, "refs/got/worktree",
10888 got_ref_cmp_by_name, repo);
10889 if (err)
10890 goto done;
10892 TAILQ_FOREACH(re, &refs, entry) {
10893 const char *cmd, *refname, *type;
10895 refname = got_ref_get_name(re->ref);
10897 if (strncmp(refname, GOT_WORKTREE_CHERRYPICK_REF_PREFIX,
10898 GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN) == 0) {
10899 refname += GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN + 1;
10900 cmd = "cherrypick";
10901 type = "cherrypicked";
10902 } else if (strncmp(refname, GOT_WORKTREE_BACKOUT_REF_PREFIX,
10903 GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN) == 0) {
10904 refname += GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN + 1;
10905 cmd = "backout";
10906 type = "backed-out";
10907 } else
10908 continue;
10910 if (strncmp(refname, uuidstr, GOT_WORKTREE_UUID_STRLEN) != 0)
10911 continue;
10913 snprintf(msg, sizeof(msg),
10914 "work tree has references created by %s commits which "
10915 "must be removed with 'got %s -X' before running the %s "
10916 "command", type, cmd, caller);
10917 err = got_error_msg(GOT_ERR_WORKTREE_META, msg);
10918 goto done;
10921 done:
10922 free(uuidstr);
10923 got_ref_list_free(&refs);
10924 return err;
10927 static const struct got_error *
10928 process_backup_refs(const char *backup_ref_prefix,
10929 const char *wanted_branch_name,
10930 int delete, struct got_repository *repo)
10932 const struct got_error *err;
10933 struct got_reflist_head refs, backup_refs;
10934 struct got_reflist_entry *re;
10935 const size_t backup_ref_prefix_len = strlen(backup_ref_prefix);
10936 struct got_object_id *old_commit_id = NULL;
10937 char *branch_name = NULL;
10938 struct got_commit_object *old_commit = NULL;
10939 struct got_reflist_object_id_map *refs_idmap = NULL;
10940 int wanted_branch_found = 0;
10942 TAILQ_INIT(&refs);
10943 TAILQ_INIT(&backup_refs);
10945 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
10946 if (err)
10947 return err;
10949 err = got_reflist_object_id_map_create(&refs_idmap, &refs, repo);
10950 if (err)
10951 goto done;
10953 if (wanted_branch_name) {
10954 if (strncmp(wanted_branch_name, "refs/heads/", 11) == 0)
10955 wanted_branch_name += 11;
10958 err = got_ref_list(&backup_refs, repo, backup_ref_prefix,
10959 got_ref_cmp_by_commit_timestamp_descending, repo);
10960 if (err)
10961 goto done;
10963 TAILQ_FOREACH(re, &backup_refs, entry) {
10964 const char *refname = got_ref_get_name(re->ref);
10965 char *slash;
10967 err = check_cancelled(NULL);
10968 if (err)
10969 break;
10971 err = got_ref_resolve(&old_commit_id, repo, re->ref);
10972 if (err)
10973 break;
10975 err = got_object_open_as_commit(&old_commit, repo,
10976 old_commit_id);
10977 if (err)
10978 break;
10980 if (strncmp(backup_ref_prefix, refname,
10981 backup_ref_prefix_len) == 0)
10982 refname += backup_ref_prefix_len;
10984 while (refname[0] == '/')
10985 refname++;
10987 branch_name = strdup(refname);
10988 if (branch_name == NULL) {
10989 err = got_error_from_errno("strdup");
10990 break;
10992 slash = strrchr(branch_name, '/');
10993 if (slash) {
10994 *slash = '\0';
10995 refname += strlen(branch_name) + 1;
10998 if (wanted_branch_name == NULL ||
10999 strcmp(wanted_branch_name, branch_name) == 0) {
11000 wanted_branch_found = 1;
11001 if (delete) {
11002 err = delete_backup_ref(re->ref,
11003 old_commit_id, repo);
11004 } else {
11005 err = print_backup_ref(branch_name, refname,
11006 old_commit_id, old_commit, refs_idmap,
11007 repo);
11009 if (err)
11010 break;
11013 free(old_commit_id);
11014 old_commit_id = NULL;
11015 free(branch_name);
11016 branch_name = NULL;
11017 got_object_commit_close(old_commit);
11018 old_commit = NULL;
11021 if (wanted_branch_name && !wanted_branch_found) {
11022 err = got_error_fmt(GOT_ERR_NOT_REF,
11023 "%s/%s/", backup_ref_prefix, wanted_branch_name);
11025 done:
11026 if (refs_idmap)
11027 got_reflist_object_id_map_free(refs_idmap);
11028 got_ref_list_free(&refs);
11029 got_ref_list_free(&backup_refs);
11030 free(old_commit_id);
11031 free(branch_name);
11032 if (old_commit)
11033 got_object_commit_close(old_commit);
11034 return err;
11037 static const struct got_error *
11038 abort_progress(void *arg, unsigned char status, const char *path)
11041 * Unversioned files should not clutter progress output when
11042 * an operation is aborted.
11044 if (status == GOT_STATUS_UNVERSIONED)
11045 return NULL;
11047 return update_progress(arg, status, path);
11050 static const struct got_error *
11051 cmd_rebase(int argc, char *argv[])
11053 const struct got_error *error = NULL;
11054 struct got_worktree *worktree = NULL;
11055 struct got_repository *repo = NULL;
11056 struct got_fileindex *fileindex = NULL;
11057 char *cwd = NULL, *committer = NULL, *gitconfig_path = NULL;
11058 struct got_reference *branch = NULL;
11059 struct got_reference *new_base_branch = NULL, *tmp_branch = NULL;
11060 struct got_object_id *commit_id = NULL, *parent_id = NULL;
11061 struct got_object_id *resume_commit_id = NULL;
11062 struct got_object_id *branch_head_commit_id = NULL, *yca_id = NULL;
11063 struct got_object_id *head_commit_id = NULL;
11064 struct got_reference *head_ref = NULL;
11065 struct got_commit_object *commit = NULL;
11066 int ch, rebase_in_progress = 0, abort_rebase = 0, continue_rebase = 0;
11067 int histedit_in_progress = 0, merge_in_progress = 0;
11068 int create_backup = 1, list_backups = 0, delete_backups = 0;
11069 int allow_conflict = 0;
11070 struct got_object_id_queue commits;
11071 struct got_pathlist_head merged_paths;
11072 const struct got_object_id_queue *parent_ids;
11073 struct got_object_qid *qid, *pid;
11074 struct got_update_progress_arg upa;
11075 int *pack_fds = NULL;
11077 STAILQ_INIT(&commits);
11078 TAILQ_INIT(&merged_paths);
11079 memset(&upa, 0, sizeof(upa));
11081 #ifndef PROFILE
11082 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
11083 "unveil", NULL) == -1)
11084 err(1, "pledge");
11085 #endif
11087 while ((ch = getopt(argc, argv, "aCclX")) != -1) {
11088 switch (ch) {
11089 case 'a':
11090 abort_rebase = 1;
11091 break;
11092 case 'C':
11093 allow_conflict = 1;
11094 break;
11095 case 'c':
11096 continue_rebase = 1;
11097 break;
11098 case 'l':
11099 list_backups = 1;
11100 break;
11101 case 'X':
11102 delete_backups = 1;
11103 break;
11104 default:
11105 usage_rebase();
11106 /* NOTREACHED */
11110 argc -= optind;
11111 argv += optind;
11113 if (list_backups) {
11114 if (abort_rebase)
11115 option_conflict('l', 'a');
11116 if (allow_conflict)
11117 option_conflict('l', 'C');
11118 if (continue_rebase)
11119 option_conflict('l', 'c');
11120 if (delete_backups)
11121 option_conflict('l', 'X');
11122 if (argc != 0 && argc != 1)
11123 usage_rebase();
11124 } else if (delete_backups) {
11125 if (abort_rebase)
11126 option_conflict('X', 'a');
11127 if (allow_conflict)
11128 option_conflict('X', 'C');
11129 if (continue_rebase)
11130 option_conflict('X', 'c');
11131 if (list_backups)
11132 option_conflict('l', 'X');
11133 if (argc != 0 && argc != 1)
11134 usage_rebase();
11135 } else if (allow_conflict) {
11136 if (abort_rebase)
11137 option_conflict('C', 'a');
11138 if (!continue_rebase)
11139 errx(1, "-C option requires -c");
11140 } else {
11141 if (abort_rebase && continue_rebase)
11142 usage_rebase();
11143 else if (abort_rebase || continue_rebase) {
11144 if (argc != 0)
11145 usage_rebase();
11146 } else if (argc != 1)
11147 usage_rebase();
11150 cwd = getcwd(NULL, 0);
11151 if (cwd == NULL) {
11152 error = got_error_from_errno("getcwd");
11153 goto done;
11156 error = got_repo_pack_fds_open(&pack_fds);
11157 if (error != NULL)
11158 goto done;
11160 error = got_worktree_open(&worktree, cwd);
11161 if (error) {
11162 if (list_backups || delete_backups) {
11163 if (error->code != GOT_ERR_NOT_WORKTREE)
11164 goto done;
11165 } else {
11166 if (error->code == GOT_ERR_NOT_WORKTREE)
11167 error = wrap_not_worktree_error(error,
11168 "rebase", cwd);
11169 goto done;
11173 error = get_gitconfig_path(&gitconfig_path);
11174 if (error)
11175 goto done;
11176 error = got_repo_open(&repo,
11177 worktree ? got_worktree_get_repo_path(worktree) : cwd,
11178 gitconfig_path, pack_fds);
11179 if (error != NULL)
11180 goto done;
11182 if (worktree != NULL && !list_backups && !delete_backups) {
11183 error = worktree_has_logmsg_ref("rebase", worktree, repo);
11184 if (error)
11185 goto done;
11188 error = get_author(&committer, repo, worktree);
11189 if (error && error->code != GOT_ERR_COMMIT_NO_AUTHOR)
11190 goto done;
11192 error = apply_unveil(got_repo_get_path(repo), 0,
11193 worktree ? got_worktree_get_root_path(worktree) : NULL);
11194 if (error)
11195 goto done;
11197 if (list_backups || delete_backups) {
11198 error = process_backup_refs(
11199 GOT_WORKTREE_REBASE_BACKUP_REF_PREFIX,
11200 argc == 1 ? argv[0] : NULL, delete_backups, repo);
11201 goto done; /* nothing else to do */
11204 error = got_worktree_histedit_in_progress(&histedit_in_progress,
11205 worktree);
11206 if (error)
11207 goto done;
11208 if (histedit_in_progress) {
11209 error = got_error(GOT_ERR_HISTEDIT_BUSY);
11210 goto done;
11213 error = got_worktree_merge_in_progress(&merge_in_progress,
11214 worktree, repo);
11215 if (error)
11216 goto done;
11217 if (merge_in_progress) {
11218 error = got_error(GOT_ERR_MERGE_BUSY);
11219 goto done;
11222 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
11223 if (error)
11224 goto done;
11226 if (abort_rebase) {
11227 if (!rebase_in_progress) {
11228 error = got_error(GOT_ERR_NOT_REBASING);
11229 goto done;
11231 error = got_worktree_rebase_continue(&resume_commit_id,
11232 &new_base_branch, &tmp_branch, &branch, &fileindex,
11233 worktree, repo);
11234 if (error)
11235 goto done;
11236 printf("Switching work tree to %s\n",
11237 got_ref_get_symref_target(new_base_branch));
11238 error = got_worktree_rebase_abort(worktree, fileindex, repo,
11239 new_base_branch, abort_progress, &upa);
11240 if (error)
11241 goto done;
11242 printf("Rebase of %s aborted\n", got_ref_get_name(branch));
11243 print_merge_progress_stats(&upa);
11244 goto done; /* nothing else to do */
11247 if (continue_rebase) {
11248 if (!rebase_in_progress) {
11249 error = got_error(GOT_ERR_NOT_REBASING);
11250 goto done;
11252 error = got_worktree_rebase_continue(&resume_commit_id,
11253 &new_base_branch, &tmp_branch, &branch, &fileindex,
11254 worktree, repo);
11255 if (error)
11256 goto done;
11258 error = rebase_commit(NULL, worktree, fileindex, tmp_branch,
11259 committer, resume_commit_id, allow_conflict, repo);
11260 if (error)
11261 goto done;
11263 yca_id = got_object_id_dup(resume_commit_id);
11264 if (yca_id == NULL) {
11265 error = got_error_from_errno("got_object_id_dup");
11266 goto done;
11268 } else {
11269 error = got_ref_open(&branch, repo, argv[0], 0);
11270 if (error != NULL)
11271 goto done;
11272 if (strncmp(got_ref_get_name(branch), "refs/heads/", 11) != 0) {
11273 error = got_error_msg(GOT_ERR_COMMIT_BRANCH,
11274 "will not rebase a branch which lives outside "
11275 "the \"refs/heads/\" reference namespace");
11276 goto done;
11280 error = got_ref_resolve(&branch_head_commit_id, repo, branch);
11281 if (error)
11282 goto done;
11284 if (!continue_rebase) {
11285 struct got_object_id *base_commit_id;
11287 error = got_ref_open(&head_ref, repo,
11288 got_worktree_get_head_ref_name(worktree), 0);
11289 if (error)
11290 goto done;
11291 error = got_ref_resolve(&head_commit_id, repo, head_ref);
11292 if (error)
11293 goto done;
11294 base_commit_id = got_worktree_get_base_commit_id(worktree);
11295 if (got_object_id_cmp(base_commit_id, head_commit_id) != 0) {
11296 error = got_error(GOT_ERR_REBASE_OUT_OF_DATE);
11297 goto done;
11300 error = got_commit_graph_find_youngest_common_ancestor(&yca_id,
11301 base_commit_id, branch_head_commit_id, 1, repo,
11302 check_cancelled, NULL);
11303 if (error) {
11304 if (error->code == GOT_ERR_ANCESTRY) {
11305 error = got_error_msg(GOT_ERR_ANCESTRY,
11306 "specified branch shares no common "
11307 "ancestry with work tree's branch");
11309 goto done;
11312 if (got_object_id_cmp(base_commit_id, yca_id) == 0) {
11313 struct got_pathlist_head paths;
11314 printf("%s is already based on %s\n",
11315 got_ref_get_name(branch),
11316 got_worktree_get_head_ref_name(worktree));
11317 error = switch_head_ref(branch, branch_head_commit_id,
11318 worktree, repo);
11319 if (error)
11320 goto done;
11321 error = got_worktree_set_base_commit_id(worktree, repo,
11322 branch_head_commit_id);
11323 if (error)
11324 goto done;
11325 TAILQ_INIT(&paths);
11326 error = got_pathlist_append(&paths, "", NULL);
11327 if (error)
11328 goto done;
11329 error = got_worktree_checkout_files(worktree,
11330 &paths, repo, update_progress, &upa,
11331 check_cancelled, NULL);
11332 got_pathlist_free(&paths, GOT_PATHLIST_FREE_NONE);
11333 if (error)
11334 goto done;
11335 if (upa.did_something) {
11336 char *id_str;
11337 error = got_object_id_str(&id_str,
11338 branch_head_commit_id);
11339 if (error)
11340 goto done;
11341 printf("Updated to %s: %s\n",
11342 got_worktree_get_head_ref_name(worktree),
11343 id_str);
11344 free(id_str);
11345 } else
11346 printf("Already up-to-date\n");
11347 print_update_progress_stats(&upa);
11348 goto done;
11352 commit_id = branch_head_commit_id;
11353 error = got_object_open_as_commit(&commit, repo, commit_id);
11354 if (error)
11355 goto done;
11357 parent_ids = got_object_commit_get_parent_ids(commit);
11358 pid = STAILQ_FIRST(parent_ids);
11359 if (pid) {
11360 error = collect_commits(&commits, commit_id, &pid->id,
11361 yca_id, got_worktree_get_path_prefix(worktree),
11362 GOT_ERR_REBASE_PATH, repo);
11363 if (error)
11364 goto done;
11367 got_object_commit_close(commit);
11368 commit = NULL;
11370 if (!continue_rebase) {
11371 error = got_worktree_rebase_prepare(&new_base_branch,
11372 &tmp_branch, &fileindex, worktree, branch, repo);
11373 if (error)
11374 goto done;
11377 if (STAILQ_EMPTY(&commits)) {
11378 if (continue_rebase) {
11379 error = rebase_complete(worktree, fileindex,
11380 branch, tmp_branch, repo, create_backup);
11381 goto done;
11382 } else {
11383 /* Fast-forward the reference of the branch. */
11384 struct got_object_id *new_head_commit_id;
11385 char *id_str;
11386 error = got_ref_resolve(&new_head_commit_id, repo,
11387 new_base_branch);
11388 if (error)
11389 goto done;
11390 error = got_object_id_str(&id_str, new_head_commit_id);
11391 if (error)
11392 goto done;
11393 printf("Forwarding %s to commit %s\n",
11394 got_ref_get_name(branch), id_str);
11395 free(id_str);
11396 error = got_ref_change_ref(branch,
11397 new_head_commit_id);
11398 if (error)
11399 goto done;
11400 /* No backup needed since objects did not change. */
11401 create_backup = 0;
11405 pid = NULL;
11406 STAILQ_FOREACH(qid, &commits, entry) {
11408 commit_id = &qid->id;
11409 parent_id = pid ? &pid->id : yca_id;
11410 pid = qid;
11412 memset(&upa, 0, sizeof(upa));
11413 error = got_worktree_rebase_merge_files(&merged_paths,
11414 worktree, fileindex, parent_id, commit_id, repo,
11415 update_progress, &upa, check_cancelled, NULL);
11416 if (error)
11417 goto done;
11419 print_merge_progress_stats(&upa);
11420 if (upa.conflicts > 0 || upa.missing > 0 ||
11421 upa.not_deleted > 0 || upa.unversioned > 0) {
11422 if (upa.conflicts > 0) {
11423 error = show_rebase_merge_conflict(&qid->id,
11424 repo);
11425 if (error)
11426 goto done;
11428 got_pathlist_free(&merged_paths, GOT_PATHLIST_FREE_PATH);
11429 break;
11432 error = rebase_commit(&merged_paths, worktree, fileindex,
11433 tmp_branch, committer, commit_id, 0, repo);
11434 got_pathlist_free(&merged_paths, GOT_PATHLIST_FREE_PATH);
11435 if (error)
11436 goto done;
11439 if (upa.conflicts > 0 || upa.missing > 0 ||
11440 upa.not_deleted > 0 || upa.unversioned > 0) {
11441 error = got_worktree_rebase_postpone(worktree, fileindex);
11442 if (error)
11443 goto done;
11444 if (upa.conflicts > 0 && upa.missing == 0 &&
11445 upa.not_deleted == 0 && upa.unversioned == 0) {
11446 error = got_error_msg(GOT_ERR_CONFLICTS,
11447 "conflicts must be resolved before rebasing "
11448 "can continue");
11449 } else if (upa.conflicts > 0) {
11450 error = got_error_msg(GOT_ERR_CONFLICTS,
11451 "conflicts must be resolved before rebasing "
11452 "can continue; changes destined for some "
11453 "files were not yet merged and should be "
11454 "merged manually if required before the "
11455 "rebase operation is continued");
11456 } else {
11457 error = got_error_msg(GOT_ERR_CONFLICTS,
11458 "changes destined for some files were not "
11459 "yet merged and should be merged manually "
11460 "if required before the rebase operation "
11461 "is continued");
11463 } else
11464 error = rebase_complete(worktree, fileindex, branch,
11465 tmp_branch, repo, create_backup);
11466 done:
11467 free(cwd);
11468 free(committer);
11469 free(gitconfig_path);
11470 got_object_id_queue_free(&commits);
11471 free(branch_head_commit_id);
11472 free(resume_commit_id);
11473 free(head_commit_id);
11474 free(yca_id);
11475 if (commit)
11476 got_object_commit_close(commit);
11477 if (branch)
11478 got_ref_close(branch);
11479 if (new_base_branch)
11480 got_ref_close(new_base_branch);
11481 if (tmp_branch)
11482 got_ref_close(tmp_branch);
11483 if (head_ref)
11484 got_ref_close(head_ref);
11485 if (worktree)
11486 got_worktree_close(worktree);
11487 if (repo) {
11488 const struct got_error *close_err = got_repo_close(repo);
11489 if (error == NULL)
11490 error = close_err;
11492 if (pack_fds) {
11493 const struct got_error *pack_err =
11494 got_repo_pack_fds_close(pack_fds);
11495 if (error == NULL)
11496 error = pack_err;
11498 return error;
11501 __dead static void
11502 usage_histedit(void)
11504 fprintf(stderr, "usage: %s histedit [-aCcdeflmX] [-F histedit-script] "
11505 "[branch]\n", getprogname());
11506 exit(1);
11509 #define GOT_HISTEDIT_PICK 'p'
11510 #define GOT_HISTEDIT_EDIT 'e'
11511 #define GOT_HISTEDIT_FOLD 'f'
11512 #define GOT_HISTEDIT_DROP 'd'
11513 #define GOT_HISTEDIT_MESG 'm'
11515 static const struct got_histedit_cmd {
11516 unsigned char code;
11517 const char *name;
11518 const char *desc;
11519 } got_histedit_cmds[] = {
11520 { GOT_HISTEDIT_PICK, "pick", "use commit" },
11521 { GOT_HISTEDIT_EDIT, "edit", "use commit but stop for amending" },
11522 { GOT_HISTEDIT_FOLD, "fold", "combine with next commit that will "
11523 "be used" },
11524 { GOT_HISTEDIT_DROP, "drop", "remove commit from history" },
11525 { GOT_HISTEDIT_MESG, "mesg",
11526 "single-line log message for commit above (open editor if empty)" },
11529 struct got_histedit_list_entry {
11530 TAILQ_ENTRY(got_histedit_list_entry) entry;
11531 struct got_object_id *commit_id;
11532 const struct got_histedit_cmd *cmd;
11533 char *logmsg;
11535 TAILQ_HEAD(got_histedit_list, got_histedit_list_entry);
11537 static const struct got_error *
11538 histedit_write_commit(struct got_object_id *commit_id, const char *cmdname,
11539 FILE *f, struct got_repository *repo)
11541 const struct got_error *err = NULL;
11542 char *logmsg = NULL, *id_str = NULL;
11543 struct got_commit_object *commit = NULL;
11544 int n;
11546 err = got_object_open_as_commit(&commit, repo, commit_id);
11547 if (err)
11548 goto done;
11550 err = get_short_logmsg(&logmsg, 34, commit);
11551 if (err)
11552 goto done;
11554 err = got_object_id_str(&id_str, commit_id);
11555 if (err)
11556 goto done;
11558 n = fprintf(f, "%s %s %s\n", cmdname, id_str, logmsg);
11559 if (n < 0)
11560 err = got_ferror(f, GOT_ERR_IO);
11561 done:
11562 if (commit)
11563 got_object_commit_close(commit);
11564 free(id_str);
11565 free(logmsg);
11566 return err;
11569 static const struct got_error *
11570 histedit_write_commit_list(struct got_object_id_queue *commits,
11571 FILE *f, int edit_logmsg_only, int fold_only, int drop_only,
11572 int edit_only, struct got_repository *repo)
11574 const struct got_error *err = NULL;
11575 struct got_object_qid *qid;
11576 const char *histedit_cmd = NULL;
11578 if (STAILQ_EMPTY(commits))
11579 return got_error(GOT_ERR_EMPTY_HISTEDIT);
11581 STAILQ_FOREACH(qid, commits, entry) {
11582 histedit_cmd = got_histedit_cmds[0].name;
11583 if (drop_only)
11584 histedit_cmd = "drop";
11585 else if (edit_only)
11586 histedit_cmd = "edit";
11587 else if (fold_only && STAILQ_NEXT(qid, entry) != NULL)
11588 histedit_cmd = "fold";
11589 err = histedit_write_commit(&qid->id, histedit_cmd, f, repo);
11590 if (err)
11591 break;
11592 if (edit_logmsg_only) {
11593 int n = fprintf(f, "%c\n", GOT_HISTEDIT_MESG);
11594 if (n < 0) {
11595 err = got_ferror(f, GOT_ERR_IO);
11596 break;
11601 return err;
11604 static const struct got_error *
11605 write_cmd_list(FILE *f, const char *branch_name,
11606 struct got_object_id_queue *commits)
11608 const struct got_error *err = NULL;
11609 size_t i;
11610 int n;
11611 char *id_str;
11612 struct got_object_qid *qid;
11614 qid = STAILQ_FIRST(commits);
11615 err = got_object_id_str(&id_str, &qid->id);
11616 if (err)
11617 return err;
11619 n = fprintf(f,
11620 "# Editing the history of branch '%s' starting at\n"
11621 "# commit %s\n"
11622 "# Commits will be processed in order from top to "
11623 "bottom of this file.\n", branch_name, id_str);
11624 if (n < 0) {
11625 err = got_ferror(f, GOT_ERR_IO);
11626 goto done;
11629 n = fprintf(f, "# Available histedit commands:\n");
11630 if (n < 0) {
11631 err = got_ferror(f, GOT_ERR_IO);
11632 goto done;
11635 for (i = 0; i < nitems(got_histedit_cmds); i++) {
11636 const struct got_histedit_cmd *cmd = &got_histedit_cmds[i];
11637 n = fprintf(f, "# %s (%c): %s\n", cmd->name, cmd->code,
11638 cmd->desc);
11639 if (n < 0) {
11640 err = got_ferror(f, GOT_ERR_IO);
11641 break;
11644 done:
11645 free(id_str);
11646 return err;
11649 static const struct got_error *
11650 histedit_syntax_error(int lineno)
11652 static char msg[42];
11653 int ret;
11655 ret = snprintf(msg, sizeof(msg), "histedit syntax error on line %d",
11656 lineno);
11657 if (ret < 0 || (size_t)ret >= sizeof(msg))
11658 return got_error(GOT_ERR_HISTEDIT_SYNTAX);
11660 return got_error_msg(GOT_ERR_HISTEDIT_SYNTAX, msg);
11663 static const struct got_error *
11664 append_folded_commit_msg(char **new_msg, struct got_histedit_list_entry *hle,
11665 char *logmsg, struct got_repository *repo)
11667 const struct got_error *err;
11668 struct got_commit_object *folded_commit = NULL;
11669 char *id_str, *folded_logmsg = NULL;
11671 err = got_object_id_str(&id_str, hle->commit_id);
11672 if (err)
11673 return err;
11675 err = got_object_open_as_commit(&folded_commit, repo, hle->commit_id);
11676 if (err)
11677 goto done;
11679 err = got_object_commit_get_logmsg(&folded_logmsg, folded_commit);
11680 if (err)
11681 goto done;
11682 if (asprintf(new_msg, "%s%s# log message of folded commit %s: %s",
11683 logmsg ? logmsg : "", logmsg ? "\n" : "", id_str,
11684 folded_logmsg) == -1) {
11685 err = got_error_from_errno("asprintf");
11687 done:
11688 if (folded_commit)
11689 got_object_commit_close(folded_commit);
11690 free(id_str);
11691 free(folded_logmsg);
11692 return err;
11695 static struct got_histedit_list_entry *
11696 get_folded_commits(struct got_histedit_list_entry *hle)
11698 struct got_histedit_list_entry *prev, *folded = NULL;
11700 prev = TAILQ_PREV(hle, got_histedit_list, entry);
11701 while (prev && (prev->cmd->code == GOT_HISTEDIT_FOLD ||
11702 prev->cmd->code == GOT_HISTEDIT_DROP)) {
11703 if (prev->cmd->code == GOT_HISTEDIT_FOLD)
11704 folded = prev;
11705 prev = TAILQ_PREV(prev, got_histedit_list, entry);
11708 return folded;
11711 static const struct got_error *
11712 histedit_edit_logmsg(struct got_histedit_list_entry *hle,
11713 struct got_repository *repo)
11715 char *logmsg_path = NULL, *id_str = NULL, *orig_logmsg = NULL;
11716 char *logmsg = NULL, *new_msg = NULL, *editor = NULL;
11717 const struct got_error *err = NULL;
11718 struct got_commit_object *commit = NULL;
11719 int logmsg_len;
11720 int fd = -1;
11721 struct got_histedit_list_entry *folded = NULL;
11723 err = got_object_open_as_commit(&commit, repo, hle->commit_id);
11724 if (err)
11725 return err;
11727 folded = get_folded_commits(hle);
11728 if (folded) {
11729 while (folded != hle) {
11730 if (folded->cmd->code == GOT_HISTEDIT_DROP) {
11731 folded = TAILQ_NEXT(folded, entry);
11732 continue;
11734 err = append_folded_commit_msg(&new_msg, folded,
11735 logmsg, repo);
11736 if (err)
11737 goto done;
11738 free(logmsg);
11739 logmsg = new_msg;
11740 folded = TAILQ_NEXT(folded, entry);
11744 err = got_object_id_str(&id_str, hle->commit_id);
11745 if (err)
11746 goto done;
11747 err = got_object_commit_get_logmsg(&orig_logmsg, commit);
11748 if (err)
11749 goto done;
11750 logmsg_len = asprintf(&new_msg,
11751 "%s\n# original log message of commit %s: %s",
11752 logmsg ? logmsg : "", id_str, orig_logmsg);
11753 if (logmsg_len == -1) {
11754 err = got_error_from_errno("asprintf");
11755 goto done;
11757 free(logmsg);
11758 logmsg = new_msg;
11760 err = got_object_id_str(&id_str, hle->commit_id);
11761 if (err)
11762 goto done;
11764 err = got_opentemp_named_fd(&logmsg_path, &fd,
11765 GOT_TMPDIR_STR "/got-logmsg", "");
11766 if (err)
11767 goto done;
11769 if (write(fd, logmsg, logmsg_len) == -1) {
11770 err = got_error_from_errno2("write", logmsg_path);
11771 goto done;
11773 if (close(fd) == -1) {
11774 err = got_error_from_errno2("close", logmsg_path);
11775 goto done;
11777 fd = -1;
11779 err = get_editor(&editor);
11780 if (err)
11781 goto done;
11783 err = edit_logmsg(&hle->logmsg, editor, logmsg_path, logmsg,
11784 logmsg_len, 0);
11785 if (err) {
11786 if (err->code != GOT_ERR_COMMIT_MSG_EMPTY)
11787 goto done;
11788 err = NULL;
11789 hle->logmsg = strdup(new_msg);
11790 if (hle->logmsg == NULL)
11791 err = got_error_from_errno("strdup");
11793 done:
11794 if (fd != -1 && close(fd) == -1 && err == NULL)
11795 err = got_error_from_errno2("close", logmsg_path);
11796 if (logmsg_path && unlink(logmsg_path) != 0 && err == NULL)
11797 err = got_error_from_errno2("unlink", logmsg_path);
11798 free(logmsg_path);
11799 free(logmsg);
11800 free(orig_logmsg);
11801 free(editor);
11802 if (commit)
11803 got_object_commit_close(commit);
11804 return err;
11807 static const struct got_error *
11808 histedit_parse_list(struct got_histedit_list *histedit_cmds,
11809 FILE *f, struct got_repository *repo)
11811 const struct got_error *err = NULL;
11812 char *line = NULL, *p, *end;
11813 size_t i, linesize = 0;
11814 ssize_t linelen;
11815 int lineno = 0, lastcmd = -1;
11816 const struct got_histedit_cmd *cmd;
11817 struct got_object_id *commit_id = NULL;
11818 struct got_histedit_list_entry *hle = NULL;
11820 for (;;) {
11821 linelen = getline(&line, &linesize, f);
11822 if (linelen == -1) {
11823 const struct got_error *getline_err;
11824 if (feof(f))
11825 break;
11826 getline_err = got_error_from_errno("getline");
11827 err = got_ferror(f, getline_err->code);
11828 break;
11830 lineno++;
11831 p = line;
11832 while (isspace((unsigned char)p[0]))
11833 p++;
11834 if (p[0] == '#' || p[0] == '\0')
11835 continue;
11836 cmd = NULL;
11837 for (i = 0; i < nitems(got_histedit_cmds); i++) {
11838 cmd = &got_histedit_cmds[i];
11839 if (strncmp(cmd->name, p, strlen(cmd->name)) == 0 &&
11840 isspace((unsigned char)p[strlen(cmd->name)])) {
11841 p += strlen(cmd->name);
11842 break;
11844 if (p[0] == cmd->code && isspace((unsigned char)p[1])) {
11845 p++;
11846 break;
11849 if (i == nitems(got_histedit_cmds)) {
11850 err = histedit_syntax_error(lineno);
11851 break;
11853 while (isspace((unsigned char)p[0]))
11854 p++;
11855 if (cmd->code == GOT_HISTEDIT_MESG) {
11856 if (lastcmd != GOT_HISTEDIT_PICK &&
11857 lastcmd != GOT_HISTEDIT_EDIT) {
11858 err = got_error(GOT_ERR_HISTEDIT_CMD);
11859 break;
11861 if (p[0] == '\0') {
11862 err = histedit_edit_logmsg(hle, repo);
11863 if (err)
11864 break;
11865 } else {
11866 hle->logmsg = strdup(p);
11867 if (hle->logmsg == NULL) {
11868 err = got_error_from_errno("strdup");
11869 break;
11872 lastcmd = cmd->code;
11873 continue;
11874 } else {
11875 end = p;
11876 while (end[0] && !isspace((unsigned char)end[0]))
11877 end++;
11878 *end = '\0';
11880 err = got_object_resolve_id_str(&commit_id, repo, p);
11881 if (err) {
11882 /* override error code */
11883 err = histedit_syntax_error(lineno);
11884 break;
11887 hle = malloc(sizeof(*hle));
11888 if (hle == NULL) {
11889 err = got_error_from_errno("malloc");
11890 break;
11892 hle->cmd = cmd;
11893 hle->commit_id = commit_id;
11894 hle->logmsg = NULL;
11895 commit_id = NULL;
11896 TAILQ_INSERT_TAIL(histedit_cmds, hle, entry);
11897 lastcmd = cmd->code;
11900 free(line);
11901 free(commit_id);
11902 return err;
11905 static const struct got_error *
11906 histedit_check_script(struct got_histedit_list *histedit_cmds,
11907 struct got_object_id_queue *commits, struct got_repository *repo)
11909 const struct got_error *err = NULL;
11910 struct got_object_qid *qid;
11911 struct got_histedit_list_entry *hle;
11912 static char msg[92];
11913 char *id_str;
11915 if (TAILQ_EMPTY(histedit_cmds))
11916 return got_error_msg(GOT_ERR_EMPTY_HISTEDIT,
11917 "histedit script contains no commands");
11918 if (STAILQ_EMPTY(commits))
11919 return got_error(GOT_ERR_EMPTY_HISTEDIT);
11921 TAILQ_FOREACH(hle, histedit_cmds, entry) {
11922 struct got_histedit_list_entry *hle2;
11923 TAILQ_FOREACH(hle2, histedit_cmds, entry) {
11924 if (hle == hle2)
11925 continue;
11926 if (got_object_id_cmp(hle->commit_id,
11927 hle2->commit_id) != 0)
11928 continue;
11929 err = got_object_id_str(&id_str, hle->commit_id);
11930 if (err)
11931 return err;
11932 snprintf(msg, sizeof(msg), "commit %s is listed "
11933 "more than once in histedit script", id_str);
11934 free(id_str);
11935 return got_error_msg(GOT_ERR_HISTEDIT_CMD, msg);
11939 STAILQ_FOREACH(qid, commits, entry) {
11940 TAILQ_FOREACH(hle, histedit_cmds, entry) {
11941 if (got_object_id_cmp(&qid->id, hle->commit_id) == 0)
11942 break;
11944 if (hle == NULL) {
11945 err = got_object_id_str(&id_str, &qid->id);
11946 if (err)
11947 return err;
11948 snprintf(msg, sizeof(msg),
11949 "commit %s missing from histedit script", id_str);
11950 free(id_str);
11951 return got_error_msg(GOT_ERR_HISTEDIT_CMD, msg);
11955 hle = TAILQ_LAST(histedit_cmds, got_histedit_list);
11956 if (hle && hle->cmd->code == GOT_HISTEDIT_FOLD)
11957 return got_error_msg(GOT_ERR_HISTEDIT_CMD,
11958 "last commit in histedit script cannot be folded");
11960 return NULL;
11963 static const struct got_error *
11964 histedit_run_editor(struct got_histedit_list *histedit_cmds,
11965 const char *path, struct got_object_id_queue *commits,
11966 struct got_repository *repo)
11968 const struct got_error *err = NULL;
11969 char *editor;
11970 FILE *f = NULL;
11972 err = get_editor(&editor);
11973 if (err)
11974 return err;
11976 if (spawn_editor(editor, path) == -1) {
11977 err = got_error_from_errno("failed spawning editor");
11978 goto done;
11981 f = fopen(path, "re");
11982 if (f == NULL) {
11983 err = got_error_from_errno("fopen");
11984 goto done;
11986 err = histedit_parse_list(histedit_cmds, f, repo);
11987 if (err)
11988 goto done;
11990 err = histedit_check_script(histedit_cmds, commits, repo);
11991 done:
11992 if (f && fclose(f) == EOF && err == NULL)
11993 err = got_error_from_errno("fclose");
11994 free(editor);
11995 return err;
11998 static const struct got_error *
11999 histedit_edit_list_retry(struct got_histedit_list *, const struct got_error *,
12000 struct got_object_id_queue *, const char *, const char *,
12001 struct got_repository *);
12003 static const struct got_error *
12004 histedit_edit_script(struct got_histedit_list *histedit_cmds,
12005 struct got_object_id_queue *commits, const char *branch_name,
12006 int edit_logmsg_only, int fold_only, int drop_only, int edit_only,
12007 struct got_repository *repo)
12009 const struct got_error *err;
12010 FILE *f = NULL;
12011 char *path = NULL;
12013 err = got_opentemp_named(&path, &f, "got-histedit", "");
12014 if (err)
12015 return err;
12017 err = write_cmd_list(f, branch_name, commits);
12018 if (err)
12019 goto done;
12021 err = histedit_write_commit_list(commits, f, edit_logmsg_only,
12022 fold_only, drop_only, edit_only, repo);
12023 if (err)
12024 goto done;
12026 if (drop_only || edit_logmsg_only || fold_only || edit_only) {
12027 rewind(f);
12028 err = histedit_parse_list(histedit_cmds, f, repo);
12029 } else {
12030 if (fclose(f) == EOF) {
12031 err = got_error_from_errno("fclose");
12032 goto done;
12034 f = NULL;
12035 err = histedit_run_editor(histedit_cmds, path, commits, repo);
12036 if (err) {
12037 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
12038 err->code != GOT_ERR_HISTEDIT_CMD)
12039 goto done;
12040 err = histedit_edit_list_retry(histedit_cmds, err,
12041 commits, path, branch_name, repo);
12044 done:
12045 if (f && fclose(f) == EOF && err == NULL)
12046 err = got_error_from_errno("fclose");
12047 if (path && unlink(path) != 0 && err == NULL)
12048 err = got_error_from_errno2("unlink", path);
12049 free(path);
12050 return err;
12053 static const struct got_error *
12054 histedit_save_list(struct got_histedit_list *histedit_cmds,
12055 struct got_worktree *worktree, struct got_repository *repo)
12057 const struct got_error *err = NULL;
12058 char *path = NULL;
12059 FILE *f = NULL;
12060 struct got_histedit_list_entry *hle;
12061 struct got_commit_object *commit = NULL;
12063 err = got_worktree_get_histedit_script_path(&path, worktree);
12064 if (err)
12065 return err;
12067 f = fopen(path, "we");
12068 if (f == NULL) {
12069 err = got_error_from_errno2("fopen", path);
12070 goto done;
12072 TAILQ_FOREACH(hle, histedit_cmds, entry) {
12073 err = histedit_write_commit(hle->commit_id, hle->cmd->name, f,
12074 repo);
12075 if (err)
12076 break;
12078 if (hle->logmsg) {
12079 int n = fprintf(f, "%c %s\n",
12080 GOT_HISTEDIT_MESG, hle->logmsg);
12081 if (n < 0) {
12082 err = got_ferror(f, GOT_ERR_IO);
12083 break;
12087 done:
12088 if (f && fclose(f) == EOF && err == NULL)
12089 err = got_error_from_errno("fclose");
12090 free(path);
12091 if (commit)
12092 got_object_commit_close(commit);
12093 return err;
12096 static void
12097 histedit_free_list(struct got_histedit_list *histedit_cmds)
12099 struct got_histedit_list_entry *hle;
12101 while ((hle = TAILQ_FIRST(histedit_cmds))) {
12102 TAILQ_REMOVE(histedit_cmds, hle, entry);
12103 free(hle);
12107 static const struct got_error *
12108 histedit_load_list(struct got_histedit_list *histedit_cmds,
12109 const char *path, struct got_repository *repo)
12111 const struct got_error *err = NULL;
12112 FILE *f = NULL;
12114 f = fopen(path, "re");
12115 if (f == NULL) {
12116 err = got_error_from_errno2("fopen", path);
12117 goto done;
12120 err = histedit_parse_list(histedit_cmds, f, repo);
12121 done:
12122 if (f && fclose(f) == EOF && err == NULL)
12123 err = got_error_from_errno("fclose");
12124 return err;
12127 static const struct got_error *
12128 histedit_edit_list_retry(struct got_histedit_list *histedit_cmds,
12129 const struct got_error *edit_err, struct got_object_id_queue *commits,
12130 const char *path, const char *branch_name, struct got_repository *repo)
12132 const struct got_error *err = NULL, *prev_err = edit_err;
12133 int resp = ' ';
12135 while (resp != 'c' && resp != 'r' && resp != 'a') {
12136 printf("%s: %s\n(c)ontinue editing, (r)estart editing, "
12137 "or (a)bort: ", getprogname(), prev_err->msg);
12138 resp = getchar();
12139 if (resp == '\n')
12140 resp = getchar();
12141 if (resp == 'c') {
12142 histedit_free_list(histedit_cmds);
12143 err = histedit_run_editor(histedit_cmds, path, commits,
12144 repo);
12145 if (err) {
12146 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
12147 err->code != GOT_ERR_HISTEDIT_CMD)
12148 break;
12149 prev_err = err;
12150 resp = ' ';
12151 continue;
12153 break;
12154 } else if (resp == 'r') {
12155 histedit_free_list(histedit_cmds);
12156 err = histedit_edit_script(histedit_cmds,
12157 commits, branch_name, 0, 0, 0, 0, repo);
12158 if (err) {
12159 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
12160 err->code != GOT_ERR_HISTEDIT_CMD)
12161 break;
12162 prev_err = err;
12163 resp = ' ';
12164 continue;
12166 break;
12167 } else if (resp == 'a') {
12168 err = got_error(GOT_ERR_HISTEDIT_CANCEL);
12169 break;
12170 } else
12171 printf("invalid response '%c'\n", resp);
12174 return err;
12177 static const struct got_error *
12178 histedit_complete(struct got_worktree *worktree,
12179 struct got_fileindex *fileindex, struct got_reference *tmp_branch,
12180 struct got_reference *branch, struct got_repository *repo)
12182 printf("Switching work tree to %s\n",
12183 got_ref_get_symref_target(branch));
12184 return got_worktree_histedit_complete(worktree, fileindex, tmp_branch,
12185 branch, repo);
12188 static const struct got_error *
12189 show_histedit_progress(struct got_commit_object *commit,
12190 struct got_histedit_list_entry *hle, struct got_object_id *new_id)
12192 const struct got_error *err;
12193 char *old_id_str = NULL, *new_id_str = NULL, *logmsg = NULL;
12195 err = got_object_id_str(&old_id_str, hle->commit_id);
12196 if (err)
12197 goto done;
12199 if (new_id) {
12200 err = got_object_id_str(&new_id_str, new_id);
12201 if (err)
12202 goto done;
12205 old_id_str[12] = '\0';
12206 if (new_id_str)
12207 new_id_str[12] = '\0';
12209 if (hle->logmsg) {
12210 logmsg = strdup(hle->logmsg);
12211 if (logmsg == NULL) {
12212 err = got_error_from_errno("strdup");
12213 goto done;
12215 trim_logmsg(logmsg, 42);
12216 } else {
12217 err = get_short_logmsg(&logmsg, 42, commit);
12218 if (err)
12219 goto done;
12222 switch (hle->cmd->code) {
12223 case GOT_HISTEDIT_PICK:
12224 case GOT_HISTEDIT_EDIT:
12225 printf("%s -> %s: %s\n", old_id_str,
12226 new_id_str ? new_id_str : "no-op change", logmsg);
12227 break;
12228 case GOT_HISTEDIT_DROP:
12229 case GOT_HISTEDIT_FOLD:
12230 printf("%s -> %s commit: %s\n", old_id_str, hle->cmd->name,
12231 logmsg);
12232 break;
12233 default:
12234 break;
12236 done:
12237 free(old_id_str);
12238 free(new_id_str);
12239 return err;
12242 static const struct got_error *
12243 histedit_commit(struct got_pathlist_head *merged_paths,
12244 struct got_worktree *worktree, struct got_fileindex *fileindex,
12245 struct got_reference *tmp_branch, struct got_histedit_list_entry *hle,
12246 const char *committer, int allow_conflict, struct got_repository *repo)
12248 const struct got_error *err;
12249 struct got_commit_object *commit;
12250 struct got_object_id *new_commit_id;
12252 if ((hle->cmd->code == GOT_HISTEDIT_EDIT || get_folded_commits(hle))
12253 && hle->logmsg == NULL) {
12254 err = histedit_edit_logmsg(hle, repo);
12255 if (err)
12256 return err;
12259 err = got_object_open_as_commit(&commit, repo, hle->commit_id);
12260 if (err)
12261 return err;
12263 err = got_worktree_histedit_commit(&new_commit_id, merged_paths,
12264 worktree, fileindex, tmp_branch, committer, commit, hle->commit_id,
12265 hle->logmsg, allow_conflict, repo);
12266 if (err) {
12267 if (err->code != GOT_ERR_COMMIT_NO_CHANGES)
12268 goto done;
12269 err = show_histedit_progress(commit, hle, NULL);
12270 } else {
12271 err = show_histedit_progress(commit, hle, new_commit_id);
12272 free(new_commit_id);
12274 done:
12275 got_object_commit_close(commit);
12276 return err;
12279 static const struct got_error *
12280 histedit_skip_commit(struct got_histedit_list_entry *hle,
12281 struct got_worktree *worktree, struct got_repository *repo)
12283 const struct got_error *error;
12284 struct got_commit_object *commit;
12286 error = got_worktree_histedit_skip_commit(worktree, hle->commit_id,
12287 repo);
12288 if (error)
12289 return error;
12291 error = got_object_open_as_commit(&commit, repo, hle->commit_id);
12292 if (error)
12293 return error;
12295 error = show_histedit_progress(commit, hle, NULL);
12296 got_object_commit_close(commit);
12297 return error;
12300 static const struct got_error *
12301 check_local_changes(void *arg, unsigned char status,
12302 unsigned char staged_status, const char *path,
12303 struct got_object_id *blob_id, struct got_object_id *staged_blob_id,
12304 struct got_object_id *commit_id, int dirfd, const char *de_name)
12306 int *have_local_changes = arg;
12308 switch (status) {
12309 case GOT_STATUS_ADD:
12310 case GOT_STATUS_DELETE:
12311 case GOT_STATUS_MODIFY:
12312 case GOT_STATUS_CONFLICT:
12313 *have_local_changes = 1;
12314 return got_error(GOT_ERR_CANCELLED);
12315 default:
12316 break;
12319 switch (staged_status) {
12320 case GOT_STATUS_ADD:
12321 case GOT_STATUS_DELETE:
12322 case GOT_STATUS_MODIFY:
12323 *have_local_changes = 1;
12324 return got_error(GOT_ERR_CANCELLED);
12325 default:
12326 break;
12329 return NULL;
12332 static const struct got_error *
12333 cmd_histedit(int argc, char *argv[])
12335 const struct got_error *error = NULL;
12336 struct got_worktree *worktree = NULL;
12337 struct got_fileindex *fileindex = NULL;
12338 struct got_repository *repo = NULL;
12339 char *cwd = NULL, *committer = NULL, *gitconfig_path = NULL;
12340 struct got_reference *branch = NULL;
12341 struct got_reference *tmp_branch = NULL;
12342 struct got_object_id *resume_commit_id = NULL;
12343 struct got_object_id *base_commit_id = NULL;
12344 struct got_object_id *head_commit_id = NULL;
12345 struct got_commit_object *commit = NULL;
12346 int ch, rebase_in_progress = 0, merge_in_progress = 0;
12347 struct got_update_progress_arg upa;
12348 int edit_in_progress = 0, abort_edit = 0, continue_edit = 0;
12349 int drop_only = 0, edit_logmsg_only = 0, fold_only = 0, edit_only = 0;
12350 int allow_conflict = 0, list_backups = 0, delete_backups = 0;
12351 const char *edit_script_path = NULL;
12352 struct got_object_id_queue commits;
12353 struct got_pathlist_head merged_paths;
12354 const struct got_object_id_queue *parent_ids;
12355 struct got_object_qid *pid;
12356 struct got_histedit_list histedit_cmds;
12357 struct got_histedit_list_entry *hle;
12358 int *pack_fds = NULL;
12360 STAILQ_INIT(&commits);
12361 TAILQ_INIT(&histedit_cmds);
12362 TAILQ_INIT(&merged_paths);
12363 memset(&upa, 0, sizeof(upa));
12365 #ifndef PROFILE
12366 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
12367 "unveil", NULL) == -1)
12368 err(1, "pledge");
12369 #endif
12371 while ((ch = getopt(argc, argv, "aCcdeF:flmX")) != -1) {
12372 switch (ch) {
12373 case 'a':
12374 abort_edit = 1;
12375 break;
12376 case 'C':
12377 allow_conflict = 1;
12378 break;
12379 case 'c':
12380 continue_edit = 1;
12381 break;
12382 case 'd':
12383 drop_only = 1;
12384 break;
12385 case 'e':
12386 edit_only = 1;
12387 break;
12388 case 'F':
12389 edit_script_path = optarg;
12390 break;
12391 case 'f':
12392 fold_only = 1;
12393 break;
12394 case 'l':
12395 list_backups = 1;
12396 break;
12397 case 'm':
12398 edit_logmsg_only = 1;
12399 break;
12400 case 'X':
12401 delete_backups = 1;
12402 break;
12403 default:
12404 usage_histedit();
12405 /* NOTREACHED */
12409 argc -= optind;
12410 argv += optind;
12412 if (abort_edit && allow_conflict)
12413 option_conflict('a', 'C');
12414 if (abort_edit && continue_edit)
12415 option_conflict('a', 'c');
12416 if (edit_script_path && allow_conflict)
12417 option_conflict('F', 'C');
12418 if (edit_script_path && edit_logmsg_only)
12419 option_conflict('F', 'm');
12420 if (abort_edit && edit_logmsg_only)
12421 option_conflict('a', 'm');
12422 if (edit_logmsg_only && allow_conflict)
12423 option_conflict('m', 'C');
12424 if (continue_edit && edit_logmsg_only)
12425 option_conflict('c', 'm');
12426 if (abort_edit && fold_only)
12427 option_conflict('a', 'f');
12428 if (fold_only && allow_conflict)
12429 option_conflict('f', 'C');
12430 if (continue_edit && fold_only)
12431 option_conflict('c', 'f');
12432 if (fold_only && edit_logmsg_only)
12433 option_conflict('f', 'm');
12434 if (edit_script_path && fold_only)
12435 option_conflict('F', 'f');
12436 if (abort_edit && edit_only)
12437 option_conflict('a', 'e');
12438 if (continue_edit && edit_only)
12439 option_conflict('c', 'e');
12440 if (edit_only && edit_logmsg_only)
12441 option_conflict('e', 'm');
12442 if (edit_script_path && edit_only)
12443 option_conflict('F', 'e');
12444 if (fold_only && edit_only)
12445 option_conflict('f', 'e');
12446 if (drop_only && abort_edit)
12447 option_conflict('d', 'a');
12448 if (drop_only && allow_conflict)
12449 option_conflict('d', 'C');
12450 if (drop_only && continue_edit)
12451 option_conflict('d', 'c');
12452 if (drop_only && edit_logmsg_only)
12453 option_conflict('d', 'm');
12454 if (drop_only && edit_only)
12455 option_conflict('d', 'e');
12456 if (drop_only && edit_script_path)
12457 option_conflict('d', 'F');
12458 if (drop_only && fold_only)
12459 option_conflict('d', 'f');
12460 if (list_backups) {
12461 if (abort_edit)
12462 option_conflict('l', 'a');
12463 if (allow_conflict)
12464 option_conflict('l', 'C');
12465 if (continue_edit)
12466 option_conflict('l', 'c');
12467 if (edit_script_path)
12468 option_conflict('l', 'F');
12469 if (edit_logmsg_only)
12470 option_conflict('l', 'm');
12471 if (drop_only)
12472 option_conflict('l', 'd');
12473 if (fold_only)
12474 option_conflict('l', 'f');
12475 if (edit_only)
12476 option_conflict('l', 'e');
12477 if (delete_backups)
12478 option_conflict('l', 'X');
12479 if (argc != 0 && argc != 1)
12480 usage_histedit();
12481 } else if (delete_backups) {
12482 if (abort_edit)
12483 option_conflict('X', 'a');
12484 if (allow_conflict)
12485 option_conflict('X', 'C');
12486 if (continue_edit)
12487 option_conflict('X', 'c');
12488 if (drop_only)
12489 option_conflict('X', 'd');
12490 if (edit_script_path)
12491 option_conflict('X', 'F');
12492 if (edit_logmsg_only)
12493 option_conflict('X', 'm');
12494 if (fold_only)
12495 option_conflict('X', 'f');
12496 if (edit_only)
12497 option_conflict('X', 'e');
12498 if (list_backups)
12499 option_conflict('X', 'l');
12500 if (argc != 0 && argc != 1)
12501 usage_histedit();
12502 } else if (allow_conflict && !continue_edit)
12503 errx(1, "-C option requires -c");
12504 else if (argc != 0)
12505 usage_histedit();
12508 * This command cannot apply unveil(2) in all cases because the
12509 * user may choose to run an editor to edit the histedit script
12510 * and to edit individual commit log messages.
12511 * unveil(2) traverses exec(2); if an editor is used we have to
12512 * apply unveil after edit script and log messages have been written.
12513 * XXX TODO: Make use of unveil(2) where possible.
12516 cwd = getcwd(NULL, 0);
12517 if (cwd == NULL) {
12518 error = got_error_from_errno("getcwd");
12519 goto done;
12522 error = got_repo_pack_fds_open(&pack_fds);
12523 if (error != NULL)
12524 goto done;
12526 error = got_worktree_open(&worktree, cwd);
12527 if (error) {
12528 if (list_backups || delete_backups) {
12529 if (error->code != GOT_ERR_NOT_WORKTREE)
12530 goto done;
12531 } else {
12532 if (error->code == GOT_ERR_NOT_WORKTREE)
12533 error = wrap_not_worktree_error(error,
12534 "histedit", cwd);
12535 goto done;
12539 if (list_backups || delete_backups) {
12540 error = got_repo_open(&repo,
12541 worktree ? got_worktree_get_repo_path(worktree) : cwd,
12542 NULL, pack_fds);
12543 if (error != NULL)
12544 goto done;
12545 error = apply_unveil(got_repo_get_path(repo), 0,
12546 worktree ? got_worktree_get_root_path(worktree) : NULL);
12547 if (error)
12548 goto done;
12549 error = process_backup_refs(
12550 GOT_WORKTREE_HISTEDIT_BACKUP_REF_PREFIX,
12551 argc == 1 ? argv[0] : NULL, delete_backups, repo);
12552 goto done; /* nothing else to do */
12555 error = get_gitconfig_path(&gitconfig_path);
12556 if (error)
12557 goto done;
12558 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
12559 gitconfig_path, pack_fds);
12560 if (error != NULL)
12561 goto done;
12563 if (worktree != NULL && !list_backups && !delete_backups) {
12564 error = worktree_has_logmsg_ref("histedit", worktree, repo);
12565 if (error)
12566 goto done;
12569 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
12570 if (error)
12571 goto done;
12572 if (rebase_in_progress) {
12573 error = got_error(GOT_ERR_REBASING);
12574 goto done;
12577 error = got_worktree_merge_in_progress(&merge_in_progress, worktree,
12578 repo);
12579 if (error)
12580 goto done;
12581 if (merge_in_progress) {
12582 error = got_error(GOT_ERR_MERGE_BUSY);
12583 goto done;
12586 error = got_worktree_histedit_in_progress(&edit_in_progress, worktree);
12587 if (error)
12588 goto done;
12590 if (edit_in_progress && edit_logmsg_only) {
12591 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
12592 "histedit operation is in progress in this "
12593 "work tree and must be continued or aborted "
12594 "before the -m option can be used");
12595 goto done;
12597 if (edit_in_progress && drop_only) {
12598 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
12599 "histedit operation is in progress in this "
12600 "work tree and must be continued or aborted "
12601 "before the -d option can be used");
12602 goto done;
12604 if (edit_in_progress && fold_only) {
12605 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
12606 "histedit operation is in progress in this "
12607 "work tree and must be continued or aborted "
12608 "before the -f option can be used");
12609 goto done;
12611 if (edit_in_progress && edit_only) {
12612 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
12613 "histedit operation is in progress in this "
12614 "work tree and must be continued or aborted "
12615 "before the -e option can be used");
12616 goto done;
12619 if (edit_in_progress && abort_edit) {
12620 error = got_worktree_histedit_continue(&resume_commit_id,
12621 &tmp_branch, &branch, &base_commit_id, &fileindex,
12622 worktree, repo);
12623 if (error)
12624 goto done;
12625 printf("Switching work tree to %s\n",
12626 got_ref_get_symref_target(branch));
12627 error = got_worktree_histedit_abort(worktree, fileindex, repo,
12628 branch, base_commit_id, abort_progress, &upa);
12629 if (error)
12630 goto done;
12631 printf("Histedit of %s aborted\n",
12632 got_ref_get_symref_target(branch));
12633 print_merge_progress_stats(&upa);
12634 goto done; /* nothing else to do */
12635 } else if (abort_edit) {
12636 error = got_error(GOT_ERR_NOT_HISTEDIT);
12637 goto done;
12640 error = get_author(&committer, repo, worktree);
12641 if (error)
12642 goto done;
12644 if (continue_edit) {
12645 char *path;
12647 if (!edit_in_progress) {
12648 error = got_error(GOT_ERR_NOT_HISTEDIT);
12649 goto done;
12652 error = got_worktree_get_histedit_script_path(&path, worktree);
12653 if (error)
12654 goto done;
12656 error = histedit_load_list(&histedit_cmds, path, repo);
12657 free(path);
12658 if (error)
12659 goto done;
12661 error = got_worktree_histedit_continue(&resume_commit_id,
12662 &tmp_branch, &branch, &base_commit_id, &fileindex,
12663 worktree, repo);
12664 if (error)
12665 goto done;
12667 error = got_ref_resolve(&head_commit_id, repo, branch);
12668 if (error)
12669 goto done;
12671 error = got_object_open_as_commit(&commit, repo,
12672 head_commit_id);
12673 if (error)
12674 goto done;
12675 parent_ids = got_object_commit_get_parent_ids(commit);
12676 pid = STAILQ_FIRST(parent_ids);
12677 if (pid == NULL) {
12678 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
12679 goto done;
12681 error = collect_commits(&commits, head_commit_id, &pid->id,
12682 base_commit_id, got_worktree_get_path_prefix(worktree),
12683 GOT_ERR_HISTEDIT_PATH, repo);
12684 got_object_commit_close(commit);
12685 commit = NULL;
12686 if (error)
12687 goto done;
12688 } else {
12689 if (edit_in_progress) {
12690 error = got_error(GOT_ERR_HISTEDIT_BUSY);
12691 goto done;
12694 error = got_ref_open(&branch, repo,
12695 got_worktree_get_head_ref_name(worktree), 0);
12696 if (error != NULL)
12697 goto done;
12699 if (strncmp(got_ref_get_name(branch), "refs/heads/", 11) != 0) {
12700 error = got_error_msg(GOT_ERR_COMMIT_BRANCH,
12701 "will not edit commit history of a branch outside "
12702 "the \"refs/heads/\" reference namespace");
12703 goto done;
12706 error = got_ref_resolve(&head_commit_id, repo, branch);
12707 got_ref_close(branch);
12708 branch = NULL;
12709 if (error)
12710 goto done;
12712 error = got_object_open_as_commit(&commit, repo,
12713 head_commit_id);
12714 if (error)
12715 goto done;
12716 parent_ids = got_object_commit_get_parent_ids(commit);
12717 pid = STAILQ_FIRST(parent_ids);
12718 if (pid == NULL) {
12719 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
12720 goto done;
12722 error = collect_commits(&commits, head_commit_id, &pid->id,
12723 got_worktree_get_base_commit_id(worktree),
12724 got_worktree_get_path_prefix(worktree),
12725 GOT_ERR_HISTEDIT_PATH, repo);
12726 got_object_commit_close(commit);
12727 commit = NULL;
12728 if (error)
12729 goto done;
12731 if (STAILQ_EMPTY(&commits)) {
12732 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
12733 goto done;
12736 error = got_worktree_histedit_prepare(&tmp_branch, &branch,
12737 &base_commit_id, &fileindex, worktree, repo);
12738 if (error)
12739 goto done;
12741 if (edit_script_path) {
12742 error = histedit_load_list(&histedit_cmds,
12743 edit_script_path, repo);
12744 if (error) {
12745 got_worktree_histedit_abort(worktree, fileindex,
12746 repo, branch, base_commit_id,
12747 abort_progress, &upa);
12748 print_merge_progress_stats(&upa);
12749 goto done;
12751 } else {
12752 const char *branch_name;
12753 branch_name = got_ref_get_symref_target(branch);
12754 if (strncmp(branch_name, "refs/heads/", 11) == 0)
12755 branch_name += 11;
12756 error = histedit_edit_script(&histedit_cmds, &commits,
12757 branch_name, edit_logmsg_only, fold_only,
12758 drop_only, edit_only, repo);
12759 if (error) {
12760 got_worktree_histedit_abort(worktree, fileindex,
12761 repo, branch, base_commit_id,
12762 abort_progress, &upa);
12763 print_merge_progress_stats(&upa);
12764 goto done;
12769 error = histedit_save_list(&histedit_cmds, worktree,
12770 repo);
12771 if (error) {
12772 got_worktree_histedit_abort(worktree, fileindex,
12773 repo, branch, base_commit_id,
12774 abort_progress, &upa);
12775 print_merge_progress_stats(&upa);
12776 goto done;
12781 error = histedit_check_script(&histedit_cmds, &commits, repo);
12782 if (error)
12783 goto done;
12785 TAILQ_FOREACH(hle, &histedit_cmds, entry) {
12786 if (resume_commit_id) {
12787 if (got_object_id_cmp(hle->commit_id,
12788 resume_commit_id) != 0)
12789 continue;
12791 resume_commit_id = NULL;
12792 if (hle->cmd->code == GOT_HISTEDIT_DROP ||
12793 hle->cmd->code == GOT_HISTEDIT_FOLD) {
12794 error = histedit_skip_commit(hle, worktree,
12795 repo);
12796 if (error)
12797 goto done;
12798 } else {
12799 struct got_pathlist_head paths;
12800 int have_changes = 0;
12802 TAILQ_INIT(&paths);
12803 error = got_pathlist_append(&paths, "", NULL);
12804 if (error)
12805 goto done;
12806 error = got_worktree_status(worktree, &paths,
12807 repo, 0, check_local_changes, &have_changes,
12808 check_cancelled, NULL);
12809 got_pathlist_free(&paths,
12810 GOT_PATHLIST_FREE_NONE);
12811 if (error) {
12812 if (error->code != GOT_ERR_CANCELLED)
12813 goto done;
12814 if (sigint_received || sigpipe_received)
12815 goto done;
12817 if (have_changes) {
12818 error = histedit_commit(NULL, worktree,
12819 fileindex, tmp_branch, hle,
12820 committer, allow_conflict, repo);
12821 if (error)
12822 goto done;
12823 } else {
12824 error = got_object_open_as_commit(
12825 &commit, repo, hle->commit_id);
12826 if (error)
12827 goto done;
12828 error = show_histedit_progress(commit,
12829 hle, NULL);
12830 got_object_commit_close(commit);
12831 commit = NULL;
12832 if (error)
12833 goto done;
12836 continue;
12839 if (hle->cmd->code == GOT_HISTEDIT_DROP) {
12840 error = histedit_skip_commit(hle, worktree, repo);
12841 if (error)
12842 goto done;
12843 continue;
12846 error = got_object_open_as_commit(&commit, repo,
12847 hle->commit_id);
12848 if (error)
12849 goto done;
12850 parent_ids = got_object_commit_get_parent_ids(commit);
12851 pid = STAILQ_FIRST(parent_ids);
12853 error = got_worktree_histedit_merge_files(&merged_paths,
12854 worktree, fileindex, &pid->id, hle->commit_id, repo,
12855 update_progress, &upa, check_cancelled, NULL);
12856 if (error)
12857 goto done;
12858 got_object_commit_close(commit);
12859 commit = NULL;
12861 print_merge_progress_stats(&upa);
12862 if (upa.conflicts > 0 || upa.missing > 0 ||
12863 upa.not_deleted > 0 || upa.unversioned > 0) {
12864 if (upa.conflicts > 0) {
12865 error = show_rebase_merge_conflict(
12866 hle->commit_id, repo);
12867 if (error)
12868 goto done;
12870 got_pathlist_free(&merged_paths, GOT_PATHLIST_FREE_PATH);
12871 break;
12874 if (hle->cmd->code == GOT_HISTEDIT_EDIT) {
12875 char *id_str;
12876 error = got_object_id_str(&id_str, hle->commit_id);
12877 if (error)
12878 goto done;
12879 printf("Stopping histedit for amending commit %s\n",
12880 id_str);
12881 free(id_str);
12882 got_pathlist_free(&merged_paths, GOT_PATHLIST_FREE_PATH);
12883 error = got_worktree_histedit_postpone(worktree,
12884 fileindex);
12885 goto done;
12888 if (hle->cmd->code == GOT_HISTEDIT_FOLD) {
12889 error = histedit_skip_commit(hle, worktree, repo);
12890 if (error)
12891 goto done;
12892 continue;
12895 error = histedit_commit(&merged_paths, worktree, fileindex,
12896 tmp_branch, hle, committer, allow_conflict, repo);
12897 got_pathlist_free(&merged_paths, GOT_PATHLIST_FREE_PATH);
12898 if (error)
12899 goto done;
12902 if (upa.conflicts > 0 || upa.missing > 0 ||
12903 upa.not_deleted > 0 || upa.unversioned > 0) {
12904 error = got_worktree_histedit_postpone(worktree, fileindex);
12905 if (error)
12906 goto done;
12907 if (upa.conflicts > 0 && upa.missing == 0 &&
12908 upa.not_deleted == 0 && upa.unversioned == 0) {
12909 error = got_error_msg(GOT_ERR_CONFLICTS,
12910 "conflicts must be resolved before histedit "
12911 "can continue");
12912 } else if (upa.conflicts > 0) {
12913 error = got_error_msg(GOT_ERR_CONFLICTS,
12914 "conflicts must be resolved before histedit "
12915 "can continue; changes destined for some "
12916 "files were not yet merged and should be "
12917 "merged manually if required before the "
12918 "histedit operation is continued");
12919 } else {
12920 error = got_error_msg(GOT_ERR_CONFLICTS,
12921 "changes destined for some files were not "
12922 "yet merged and should be merged manually "
12923 "if required before the histedit operation "
12924 "is continued");
12926 } else
12927 error = histedit_complete(worktree, fileindex, tmp_branch,
12928 branch, repo);
12929 done:
12930 free(cwd);
12931 free(committer);
12932 free(gitconfig_path);
12933 got_object_id_queue_free(&commits);
12934 histedit_free_list(&histedit_cmds);
12935 free(head_commit_id);
12936 free(base_commit_id);
12937 free(resume_commit_id);
12938 if (commit)
12939 got_object_commit_close(commit);
12940 if (branch)
12941 got_ref_close(branch);
12942 if (tmp_branch)
12943 got_ref_close(tmp_branch);
12944 if (worktree)
12945 got_worktree_close(worktree);
12946 if (repo) {
12947 const struct got_error *close_err = got_repo_close(repo);
12948 if (error == NULL)
12949 error = close_err;
12951 if (pack_fds) {
12952 const struct got_error *pack_err =
12953 got_repo_pack_fds_close(pack_fds);
12954 if (error == NULL)
12955 error = pack_err;
12957 return error;
12960 __dead static void
12961 usage_integrate(void)
12963 fprintf(stderr, "usage: %s integrate branch\n", getprogname());
12964 exit(1);
12967 static const struct got_error *
12968 cmd_integrate(int argc, char *argv[])
12970 const struct got_error *error = NULL;
12971 struct got_repository *repo = NULL;
12972 struct got_worktree *worktree = NULL;
12973 char *cwd = NULL, *refname = NULL, *base_refname = NULL;
12974 const char *branch_arg = NULL;
12975 struct got_reference *branch_ref = NULL, *base_branch_ref = NULL;
12976 struct got_fileindex *fileindex = NULL;
12977 struct got_object_id *commit_id = NULL, *base_commit_id = NULL;
12978 int ch;
12979 struct got_update_progress_arg upa;
12980 int *pack_fds = NULL;
12982 #ifndef PROFILE
12983 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
12984 "unveil", NULL) == -1)
12985 err(1, "pledge");
12986 #endif
12988 while ((ch = getopt(argc, argv, "")) != -1) {
12989 switch (ch) {
12990 default:
12991 usage_integrate();
12992 /* NOTREACHED */
12996 argc -= optind;
12997 argv += optind;
12999 if (argc != 1)
13000 usage_integrate();
13001 branch_arg = argv[0];
13003 cwd = getcwd(NULL, 0);
13004 if (cwd == NULL) {
13005 error = got_error_from_errno("getcwd");
13006 goto done;
13009 error = got_repo_pack_fds_open(&pack_fds);
13010 if (error != NULL)
13011 goto done;
13013 error = got_worktree_open(&worktree, cwd);
13014 if (error) {
13015 if (error->code == GOT_ERR_NOT_WORKTREE)
13016 error = wrap_not_worktree_error(error, "integrate",
13017 cwd);
13018 goto done;
13021 error = check_rebase_or_histedit_in_progress(worktree);
13022 if (error)
13023 goto done;
13025 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
13026 NULL, pack_fds);
13027 if (error != NULL)
13028 goto done;
13030 error = apply_unveil(got_repo_get_path(repo), 0,
13031 got_worktree_get_root_path(worktree));
13032 if (error)
13033 goto done;
13035 error = check_merge_in_progress(worktree, repo);
13036 if (error)
13037 goto done;
13039 if (asprintf(&refname, "refs/heads/%s", branch_arg) == -1) {
13040 error = got_error_from_errno("asprintf");
13041 goto done;
13044 error = got_worktree_integrate_prepare(&fileindex, &branch_ref,
13045 &base_branch_ref, worktree, refname, repo);
13046 if (error)
13047 goto done;
13049 refname = strdup(got_ref_get_name(branch_ref));
13050 if (refname == NULL) {
13051 error = got_error_from_errno("strdup");
13052 got_worktree_integrate_abort(worktree, fileindex, repo,
13053 branch_ref, base_branch_ref);
13054 goto done;
13056 base_refname = strdup(got_ref_get_name(base_branch_ref));
13057 if (base_refname == NULL) {
13058 error = got_error_from_errno("strdup");
13059 got_worktree_integrate_abort(worktree, fileindex, repo,
13060 branch_ref, base_branch_ref);
13061 goto done;
13063 if (strncmp(base_refname, "refs/heads/", 11) != 0) {
13064 error = got_error(GOT_ERR_INTEGRATE_BRANCH);
13065 got_worktree_integrate_abort(worktree, fileindex, repo,
13066 branch_ref, base_branch_ref);
13067 goto done;
13070 error = got_ref_resolve(&commit_id, repo, branch_ref);
13071 if (error)
13072 goto done;
13074 error = got_ref_resolve(&base_commit_id, repo, base_branch_ref);
13075 if (error)
13076 goto done;
13078 if (got_object_id_cmp(commit_id, base_commit_id) == 0) {
13079 error = got_error_msg(GOT_ERR_SAME_BRANCH,
13080 "specified branch has already been integrated");
13081 got_worktree_integrate_abort(worktree, fileindex, repo,
13082 branch_ref, base_branch_ref);
13083 goto done;
13086 error = check_linear_ancestry(commit_id, base_commit_id, 1, repo);
13087 if (error) {
13088 if (error->code == GOT_ERR_ANCESTRY)
13089 error = got_error(GOT_ERR_REBASE_REQUIRED);
13090 got_worktree_integrate_abort(worktree, fileindex, repo,
13091 branch_ref, base_branch_ref);
13092 goto done;
13095 memset(&upa, 0, sizeof(upa));
13096 error = got_worktree_integrate_continue(worktree, fileindex, repo,
13097 branch_ref, base_branch_ref, update_progress, &upa,
13098 check_cancelled, NULL);
13099 if (error)
13100 goto done;
13102 printf("Integrated %s into %s\n", refname, base_refname);
13103 print_update_progress_stats(&upa);
13104 done:
13105 if (repo) {
13106 const struct got_error *close_err = got_repo_close(repo);
13107 if (error == NULL)
13108 error = close_err;
13110 if (worktree)
13111 got_worktree_close(worktree);
13112 if (pack_fds) {
13113 const struct got_error *pack_err =
13114 got_repo_pack_fds_close(pack_fds);
13115 if (error == NULL)
13116 error = pack_err;
13118 free(cwd);
13119 free(base_commit_id);
13120 free(commit_id);
13121 free(refname);
13122 free(base_refname);
13123 return error;
13126 __dead static void
13127 usage_merge(void)
13129 fprintf(stderr, "usage: %s merge [-aCcn] [branch]\n", getprogname());
13130 exit(1);
13133 static const struct got_error *
13134 cmd_merge(int argc, char *argv[])
13136 const struct got_error *error = NULL;
13137 struct got_worktree *worktree = NULL;
13138 struct got_repository *repo = NULL;
13139 struct got_fileindex *fileindex = NULL;
13140 char *cwd = NULL, *id_str = NULL, *author = NULL;
13141 char *gitconfig_path = NULL;
13142 struct got_reference *branch = NULL, *wt_branch = NULL;
13143 struct got_object_id *branch_tip = NULL, *yca_id = NULL;
13144 struct got_object_id *wt_branch_tip = NULL;
13145 int ch, merge_in_progress = 0, abort_merge = 0, continue_merge = 0;
13146 int allow_conflict = 0, prefer_fast_forward = 1, interrupt_merge = 0;
13147 struct got_update_progress_arg upa;
13148 struct got_object_id *merge_commit_id = NULL;
13149 char *branch_name = NULL;
13150 int *pack_fds = NULL;
13152 memset(&upa, 0, sizeof(upa));
13154 #ifndef PROFILE
13155 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
13156 "unveil", NULL) == -1)
13157 err(1, "pledge");
13158 #endif
13160 while ((ch = getopt(argc, argv, "aCcMn")) != -1) {
13161 switch (ch) {
13162 case 'a':
13163 abort_merge = 1;
13164 break;
13165 case 'C':
13166 allow_conflict = 1;
13167 break;
13168 case 'c':
13169 continue_merge = 1;
13170 break;
13171 case 'M':
13172 prefer_fast_forward = 0;
13173 break;
13174 case 'n':
13175 interrupt_merge = 1;
13176 break;
13177 default:
13178 usage_merge();
13179 /* NOTREACHED */
13183 argc -= optind;
13184 argv += optind;
13186 if (abort_merge) {
13187 if (continue_merge)
13188 option_conflict('a', 'c');
13189 if (!prefer_fast_forward)
13190 option_conflict('a', 'M');
13191 if (interrupt_merge)
13192 option_conflict('a', 'n');
13193 } else if (continue_merge) {
13194 if (!prefer_fast_forward)
13195 option_conflict('c', 'M');
13196 if (interrupt_merge)
13197 option_conflict('c', 'n');
13199 if (allow_conflict) {
13200 if (!continue_merge)
13201 errx(1, "-C option requires -c");
13203 if (abort_merge || continue_merge) {
13204 if (argc != 0)
13205 usage_merge();
13206 } else if (argc != 1)
13207 usage_merge();
13209 cwd = getcwd(NULL, 0);
13210 if (cwd == NULL) {
13211 error = got_error_from_errno("getcwd");
13212 goto done;
13215 error = got_repo_pack_fds_open(&pack_fds);
13216 if (error != NULL)
13217 goto done;
13219 error = got_worktree_open(&worktree, cwd);
13220 if (error) {
13221 if (error->code == GOT_ERR_NOT_WORKTREE)
13222 error = wrap_not_worktree_error(error,
13223 "merge", cwd);
13224 goto done;
13227 error = get_gitconfig_path(&gitconfig_path);
13228 if (error)
13229 goto done;
13230 error = got_repo_open(&repo,
13231 worktree ? got_worktree_get_repo_path(worktree) : cwd,
13232 gitconfig_path, pack_fds);
13233 if (error != NULL)
13234 goto done;
13236 if (worktree != NULL) {
13237 error = worktree_has_logmsg_ref("merge", worktree, repo);
13238 if (error)
13239 goto done;
13242 error = apply_unveil(got_repo_get_path(repo), 0,
13243 worktree ? got_worktree_get_root_path(worktree) : NULL);
13244 if (error)
13245 goto done;
13247 error = check_rebase_or_histedit_in_progress(worktree);
13248 if (error)
13249 goto done;
13251 error = got_worktree_merge_in_progress(&merge_in_progress, worktree,
13252 repo);
13253 if (error)
13254 goto done;
13256 if (merge_in_progress && !(abort_merge || continue_merge)) {
13257 error = got_error(GOT_ERR_MERGE_BUSY);
13258 goto done;
13261 if (!merge_in_progress && (abort_merge || continue_merge)) {
13262 error = got_error(GOT_ERR_NOT_MERGING);
13263 goto done;
13266 if (abort_merge) {
13267 error = got_worktree_merge_continue(&branch_name,
13268 &branch_tip, &fileindex, worktree, repo);
13269 if (error)
13270 goto done;
13271 error = got_worktree_merge_abort(worktree, fileindex, repo,
13272 abort_progress, &upa);
13273 if (error)
13274 goto done;
13275 printf("Merge of %s aborted\n", branch_name);
13276 goto done; /* nothing else to do */
13279 if (strncmp(got_worktree_get_head_ref_name(worktree),
13280 "refs/heads/", 11) != 0) {
13281 error = got_error_fmt(GOT_ERR_COMMIT_BRANCH,
13282 "work tree's current branch %s is outside the "
13283 "\"refs/heads/\" reference namespace; "
13284 "update -b required",
13285 got_worktree_get_head_ref_name(worktree));
13286 goto done;
13289 error = get_author(&author, repo, worktree);
13290 if (error)
13291 goto done;
13293 error = got_ref_open(&wt_branch, repo,
13294 got_worktree_get_head_ref_name(worktree), 0);
13295 if (error)
13296 goto done;
13297 error = got_ref_resolve(&wt_branch_tip, repo, wt_branch);
13298 if (error)
13299 goto done;
13301 if (continue_merge) {
13302 struct got_object_id *base_commit_id;
13303 base_commit_id = got_worktree_get_base_commit_id(worktree);
13304 if (got_object_id_cmp(wt_branch_tip, base_commit_id) != 0) {
13305 error = got_error(GOT_ERR_MERGE_COMMIT_OUT_OF_DATE);
13306 goto done;
13308 error = got_worktree_merge_continue(&branch_name,
13309 &branch_tip, &fileindex, worktree, repo);
13310 if (error)
13311 goto done;
13312 } else {
13313 error = got_ref_open(&branch, repo, argv[0], 0);
13314 if (error != NULL)
13315 goto done;
13316 branch_name = strdup(got_ref_get_name(branch));
13317 if (branch_name == NULL) {
13318 error = got_error_from_errno("strdup");
13319 goto done;
13321 error = got_ref_resolve(&branch_tip, repo, branch);
13322 if (error)
13323 goto done;
13326 error = got_commit_graph_find_youngest_common_ancestor(&yca_id,
13327 wt_branch_tip, branch_tip, 0, repo,
13328 check_cancelled, NULL);
13329 if (error && error->code != GOT_ERR_ANCESTRY)
13330 goto done;
13332 if (!continue_merge) {
13333 error = check_path_prefix(wt_branch_tip, branch_tip,
13334 got_worktree_get_path_prefix(worktree),
13335 GOT_ERR_MERGE_PATH, repo);
13336 if (error)
13337 goto done;
13338 error = got_worktree_merge_prepare(&fileindex, worktree, repo);
13339 if (error)
13340 goto done;
13341 if (prefer_fast_forward && yca_id &&
13342 got_object_id_cmp(wt_branch_tip, yca_id) == 0) {
13343 struct got_pathlist_head paths;
13344 if (interrupt_merge) {
13345 error = got_error_fmt(GOT_ERR_BAD_OPTION,
13346 "there are no changes to merge since %s "
13347 "is already based on %s; merge cannot be "
13348 "interrupted for amending; -n",
13349 branch_name, got_ref_get_name(wt_branch));
13350 goto done;
13352 printf("Forwarding %s to %s\n",
13353 got_ref_get_name(wt_branch), branch_name);
13354 error = got_ref_change_ref(wt_branch, branch_tip);
13355 if (error)
13356 goto done;
13357 error = got_ref_write(wt_branch, repo);
13358 if (error)
13359 goto done;
13360 error = got_worktree_set_base_commit_id(worktree, repo,
13361 branch_tip);
13362 if (error)
13363 goto done;
13364 TAILQ_INIT(&paths);
13365 error = got_pathlist_append(&paths, "", NULL);
13366 if (error)
13367 goto done;
13368 error = got_worktree_checkout_files(worktree,
13369 &paths, repo, update_progress, &upa,
13370 check_cancelled, NULL);
13371 got_pathlist_free(&paths, GOT_PATHLIST_FREE_NONE);
13372 if (error)
13373 goto done;
13374 if (upa.did_something) {
13375 char *id_str;
13376 error = got_object_id_str(&id_str, branch_tip);
13377 if (error)
13378 goto done;
13379 printf("Updated to commit %s\n", id_str);
13380 free(id_str);
13381 } else
13382 printf("Already up-to-date\n");
13383 print_update_progress_stats(&upa);
13384 goto done;
13386 error = got_worktree_merge_write_refs(worktree, branch, repo);
13387 if (error)
13388 goto done;
13390 error = got_worktree_merge_branch(worktree, fileindex,
13391 yca_id, branch_tip, repo, update_progress, &upa,
13392 check_cancelled, NULL);
13393 if (error)
13394 goto done;
13395 print_merge_progress_stats(&upa);
13396 if (!upa.did_something) {
13397 error = got_worktree_merge_abort(worktree, fileindex,
13398 repo, abort_progress, &upa);
13399 if (error)
13400 goto done;
13401 printf("Already up-to-date\n");
13402 goto done;
13406 if (interrupt_merge) {
13407 error = got_worktree_merge_postpone(worktree, fileindex);
13408 if (error)
13409 goto done;
13410 printf("Merge of %s interrupted on request\n", branch_name);
13411 } else if (upa.conflicts > 0 || upa.missing > 0 ||
13412 upa.not_deleted > 0 || upa.unversioned > 0) {
13413 error = got_worktree_merge_postpone(worktree, fileindex);
13414 if (error)
13415 goto done;
13416 if (upa.conflicts > 0 && upa.missing == 0 &&
13417 upa.not_deleted == 0 && upa.unversioned == 0) {
13418 error = got_error_msg(GOT_ERR_CONFLICTS,
13419 "conflicts must be resolved before merging "
13420 "can continue");
13421 } else if (upa.conflicts > 0) {
13422 error = got_error_msg(GOT_ERR_CONFLICTS,
13423 "conflicts must be resolved before merging "
13424 "can continue; changes destined for some "
13425 "files were not yet merged and "
13426 "should be merged manually if required before the "
13427 "merge operation is continued");
13428 } else {
13429 error = got_error_msg(GOT_ERR_CONFLICTS,
13430 "changes destined for some "
13431 "files were not yet merged and should be "
13432 "merged manually if required before the "
13433 "merge operation is continued");
13435 goto done;
13436 } else {
13437 error = got_worktree_merge_commit(&merge_commit_id, worktree,
13438 fileindex, author, NULL, 1, branch_tip, branch_name,
13439 allow_conflict, repo, continue_merge ? print_status : NULL,
13440 NULL);
13441 if (error)
13442 goto done;
13443 error = got_worktree_merge_complete(worktree, fileindex, repo);
13444 if (error)
13445 goto done;
13446 error = got_object_id_str(&id_str, merge_commit_id);
13447 if (error)
13448 goto done;
13449 printf("Merged %s into %s: %s\n", branch_name,
13450 got_worktree_get_head_ref_name(worktree),
13451 id_str);
13454 done:
13455 free(gitconfig_path);
13456 free(id_str);
13457 free(merge_commit_id);
13458 free(author);
13459 free(branch_tip);
13460 free(branch_name);
13461 free(yca_id);
13462 if (branch)
13463 got_ref_close(branch);
13464 if (wt_branch)
13465 got_ref_close(wt_branch);
13466 if (worktree)
13467 got_worktree_close(worktree);
13468 if (repo) {
13469 const struct got_error *close_err = got_repo_close(repo);
13470 if (error == NULL)
13471 error = close_err;
13473 if (pack_fds) {
13474 const struct got_error *pack_err =
13475 got_repo_pack_fds_close(pack_fds);
13476 if (error == NULL)
13477 error = pack_err;
13479 return error;
13482 __dead static void
13483 usage_stage(void)
13485 fprintf(stderr, "usage: %s stage [-lpS] [-F response-script] "
13486 "[path ...]\n", getprogname());
13487 exit(1);
13490 static const struct got_error *
13491 print_stage(void *arg, unsigned char status, unsigned char staged_status,
13492 const char *path, struct got_object_id *blob_id,
13493 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
13494 int dirfd, const char *de_name)
13496 const struct got_error *err = NULL;
13497 char *id_str = NULL;
13499 if (staged_status != GOT_STATUS_ADD &&
13500 staged_status != GOT_STATUS_MODIFY &&
13501 staged_status != GOT_STATUS_DELETE)
13502 return NULL;
13504 if (staged_status == GOT_STATUS_ADD ||
13505 staged_status == GOT_STATUS_MODIFY)
13506 err = got_object_id_str(&id_str, staged_blob_id);
13507 else
13508 err = got_object_id_str(&id_str, blob_id);
13509 if (err)
13510 return err;
13512 printf("%s %c %s\n", id_str, staged_status, path);
13513 free(id_str);
13514 return NULL;
13517 static const struct got_error *
13518 cmd_stage(int argc, char *argv[])
13520 const struct got_error *error = NULL;
13521 struct got_repository *repo = NULL;
13522 struct got_worktree *worktree = NULL;
13523 char *cwd = NULL;
13524 struct got_pathlist_head paths;
13525 int ch, list_stage = 0, pflag = 0, allow_bad_symlinks = 0;
13526 FILE *patch_script_file = NULL;
13527 const char *patch_script_path = NULL;
13528 struct choose_patch_arg cpa;
13529 int *pack_fds = NULL;
13531 TAILQ_INIT(&paths);
13533 #ifndef PROFILE
13534 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
13535 "unveil", NULL) == -1)
13536 err(1, "pledge");
13537 #endif
13539 while ((ch = getopt(argc, argv, "F:lpS")) != -1) {
13540 switch (ch) {
13541 case 'F':
13542 patch_script_path = optarg;
13543 break;
13544 case 'l':
13545 list_stage = 1;
13546 break;
13547 case 'p':
13548 pflag = 1;
13549 break;
13550 case 'S':
13551 allow_bad_symlinks = 1;
13552 break;
13553 default:
13554 usage_stage();
13555 /* NOTREACHED */
13559 argc -= optind;
13560 argv += optind;
13562 if (list_stage && (pflag || patch_script_path))
13563 errx(1, "-l option cannot be used with other options");
13564 if (patch_script_path && !pflag)
13565 errx(1, "-F option can only be used together with -p option");
13567 cwd = getcwd(NULL, 0);
13568 if (cwd == NULL) {
13569 error = got_error_from_errno("getcwd");
13570 goto done;
13573 error = got_repo_pack_fds_open(&pack_fds);
13574 if (error != NULL)
13575 goto done;
13577 error = got_worktree_open(&worktree, cwd);
13578 if (error) {
13579 if (error->code == GOT_ERR_NOT_WORKTREE)
13580 error = wrap_not_worktree_error(error, "stage", cwd);
13581 goto done;
13584 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
13585 NULL, pack_fds);
13586 if (error != NULL)
13587 goto done;
13589 if (patch_script_path) {
13590 patch_script_file = fopen(patch_script_path, "re");
13591 if (patch_script_file == NULL) {
13592 error = got_error_from_errno2("fopen",
13593 patch_script_path);
13594 goto done;
13597 error = apply_unveil(got_repo_get_path(repo), 0,
13598 got_worktree_get_root_path(worktree));
13599 if (error)
13600 goto done;
13602 error = check_merge_in_progress(worktree, repo);
13603 if (error)
13604 goto done;
13606 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
13607 if (error)
13608 goto done;
13610 if (list_stage)
13611 error = got_worktree_status(worktree, &paths, repo, 0,
13612 print_stage, NULL, check_cancelled, NULL);
13613 else {
13614 cpa.patch_script_file = patch_script_file;
13615 cpa.action = "stage";
13616 error = got_worktree_stage(worktree, &paths,
13617 pflag ? NULL : print_status, NULL,
13618 pflag ? choose_patch : NULL, &cpa,
13619 allow_bad_symlinks, repo);
13621 done:
13622 if (patch_script_file && fclose(patch_script_file) == EOF &&
13623 error == NULL)
13624 error = got_error_from_errno2("fclose", patch_script_path);
13625 if (repo) {
13626 const struct got_error *close_err = got_repo_close(repo);
13627 if (error == NULL)
13628 error = close_err;
13630 if (worktree)
13631 got_worktree_close(worktree);
13632 if (pack_fds) {
13633 const struct got_error *pack_err =
13634 got_repo_pack_fds_close(pack_fds);
13635 if (error == NULL)
13636 error = pack_err;
13638 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
13639 free(cwd);
13640 return error;
13643 __dead static void
13644 usage_unstage(void)
13646 fprintf(stderr, "usage: %s unstage [-p] [-F response-script] "
13647 "[path ...]\n", getprogname());
13648 exit(1);
13652 static const struct got_error *
13653 cmd_unstage(int argc, char *argv[])
13655 const struct got_error *error = NULL;
13656 struct got_repository *repo = NULL;
13657 struct got_worktree *worktree = NULL;
13658 char *cwd = NULL;
13659 struct got_pathlist_head paths;
13660 int ch, pflag = 0;
13661 struct got_update_progress_arg upa;
13662 FILE *patch_script_file = NULL;
13663 const char *patch_script_path = NULL;
13664 struct choose_patch_arg cpa;
13665 int *pack_fds = NULL;
13667 TAILQ_INIT(&paths);
13669 #ifndef PROFILE
13670 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
13671 "unveil", NULL) == -1)
13672 err(1, "pledge");
13673 #endif
13675 while ((ch = getopt(argc, argv, "F:p")) != -1) {
13676 switch (ch) {
13677 case 'F':
13678 patch_script_path = optarg;
13679 break;
13680 case 'p':
13681 pflag = 1;
13682 break;
13683 default:
13684 usage_unstage();
13685 /* NOTREACHED */
13689 argc -= optind;
13690 argv += optind;
13692 if (patch_script_path && !pflag)
13693 errx(1, "-F option can only be used together with -p option");
13695 cwd = getcwd(NULL, 0);
13696 if (cwd == NULL) {
13697 error = got_error_from_errno("getcwd");
13698 goto done;
13701 error = got_repo_pack_fds_open(&pack_fds);
13702 if (error != NULL)
13703 goto done;
13705 error = got_worktree_open(&worktree, cwd);
13706 if (error) {
13707 if (error->code == GOT_ERR_NOT_WORKTREE)
13708 error = wrap_not_worktree_error(error, "unstage", cwd);
13709 goto done;
13712 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
13713 NULL, pack_fds);
13714 if (error != NULL)
13715 goto done;
13717 if (patch_script_path) {
13718 patch_script_file = fopen(patch_script_path, "re");
13719 if (patch_script_file == NULL) {
13720 error = got_error_from_errno2("fopen",
13721 patch_script_path);
13722 goto done;
13726 error = apply_unveil(got_repo_get_path(repo), 0,
13727 got_worktree_get_root_path(worktree));
13728 if (error)
13729 goto done;
13731 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
13732 if (error)
13733 goto done;
13735 cpa.patch_script_file = patch_script_file;
13736 cpa.action = "unstage";
13737 memset(&upa, 0, sizeof(upa));
13738 error = got_worktree_unstage(worktree, &paths, update_progress,
13739 &upa, pflag ? choose_patch : NULL, &cpa, repo);
13740 if (!error)
13741 print_merge_progress_stats(&upa);
13742 done:
13743 if (patch_script_file && fclose(patch_script_file) == EOF &&
13744 error == NULL)
13745 error = got_error_from_errno2("fclose", patch_script_path);
13746 if (repo) {
13747 const struct got_error *close_err = got_repo_close(repo);
13748 if (error == NULL)
13749 error = close_err;
13751 if (worktree)
13752 got_worktree_close(worktree);
13753 if (pack_fds) {
13754 const struct got_error *pack_err =
13755 got_repo_pack_fds_close(pack_fds);
13756 if (error == NULL)
13757 error = pack_err;
13759 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
13760 free(cwd);
13761 return error;
13764 __dead static void
13765 usage_cat(void)
13767 fprintf(stderr, "usage: %s cat [-P] [-c commit] [-r repository-path] "
13768 "arg ...\n", getprogname());
13769 exit(1);
13772 static const struct got_error *
13773 cat_blob(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
13775 const struct got_error *err;
13776 struct got_blob_object *blob;
13777 int fd = -1;
13779 fd = got_opentempfd();
13780 if (fd == -1)
13781 return got_error_from_errno("got_opentempfd");
13783 err = got_object_open_as_blob(&blob, repo, id, 8192, fd);
13784 if (err)
13785 goto done;
13787 err = got_object_blob_dump_to_file(NULL, NULL, NULL, outfile, blob);
13788 done:
13789 if (fd != -1 && close(fd) == -1 && err == NULL)
13790 err = got_error_from_errno("close");
13791 if (blob)
13792 got_object_blob_close(blob);
13793 return err;
13796 static const struct got_error *
13797 cat_tree(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
13799 const struct got_error *err;
13800 struct got_tree_object *tree;
13801 int nentries, i;
13803 err = got_object_open_as_tree(&tree, repo, id);
13804 if (err)
13805 return err;
13807 nentries = got_object_tree_get_nentries(tree);
13808 for (i = 0; i < nentries; i++) {
13809 struct got_tree_entry *te;
13810 char *id_str;
13811 if (sigint_received || sigpipe_received)
13812 break;
13813 te = got_object_tree_get_entry(tree, i);
13814 err = got_object_id_str(&id_str, got_tree_entry_get_id(te));
13815 if (err)
13816 break;
13817 fprintf(outfile, "%s %.7o %s\n", id_str,
13818 got_tree_entry_get_mode(te),
13819 got_tree_entry_get_name(te));
13820 free(id_str);
13823 got_object_tree_close(tree);
13824 return err;
13827 static const struct got_error *
13828 cat_commit(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
13830 const struct got_error *err;
13831 struct got_commit_object *commit;
13832 const struct got_object_id_queue *parent_ids;
13833 struct got_object_qid *pid;
13834 char *id_str = NULL;
13835 const char *logmsg = NULL;
13836 char gmtoff[6];
13838 err = got_object_open_as_commit(&commit, repo, id);
13839 if (err)
13840 return err;
13842 err = got_object_id_str(&id_str, got_object_commit_get_tree_id(commit));
13843 if (err)
13844 goto done;
13846 fprintf(outfile, "%s%s\n", GOT_COMMIT_LABEL_TREE, id_str);
13847 parent_ids = got_object_commit_get_parent_ids(commit);
13848 fprintf(outfile, "numparents %d\n",
13849 got_object_commit_get_nparents(commit));
13850 STAILQ_FOREACH(pid, parent_ids, entry) {
13851 char *pid_str;
13852 err = got_object_id_str(&pid_str, &pid->id);
13853 if (err)
13854 goto done;
13855 fprintf(outfile, "%s%s\n", GOT_COMMIT_LABEL_PARENT, pid_str);
13856 free(pid_str);
13858 got_date_format_gmtoff(gmtoff, sizeof(gmtoff),
13859 got_object_commit_get_author_gmtoff(commit));
13860 fprintf(outfile, "%s%s %lld %s\n", GOT_COMMIT_LABEL_AUTHOR,
13861 got_object_commit_get_author(commit),
13862 (long long)got_object_commit_get_author_time(commit),
13863 gmtoff);
13865 got_date_format_gmtoff(gmtoff, sizeof(gmtoff),
13866 got_object_commit_get_committer_gmtoff(commit));
13867 fprintf(outfile, "%s%s %lld %s\n", GOT_COMMIT_LABEL_COMMITTER,
13868 got_object_commit_get_committer(commit),
13869 (long long)got_object_commit_get_committer_time(commit),
13870 gmtoff);
13872 logmsg = got_object_commit_get_logmsg_raw(commit);
13873 fprintf(outfile, "messagelen %zd\n", strlen(logmsg));
13874 fprintf(outfile, "%s", logmsg);
13875 done:
13876 free(id_str);
13877 got_object_commit_close(commit);
13878 return err;
13881 static const struct got_error *
13882 cat_tag(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
13884 const struct got_error *err;
13885 struct got_tag_object *tag;
13886 char *id_str = NULL;
13887 const char *tagmsg = NULL;
13888 char gmtoff[6];
13890 err = got_object_open_as_tag(&tag, repo, id);
13891 if (err)
13892 return err;
13894 err = got_object_id_str(&id_str, got_object_tag_get_object_id(tag));
13895 if (err)
13896 goto done;
13898 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_OBJECT, id_str);
13900 switch (got_object_tag_get_object_type(tag)) {
13901 case GOT_OBJ_TYPE_BLOB:
13902 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
13903 GOT_OBJ_LABEL_BLOB);
13904 break;
13905 case GOT_OBJ_TYPE_TREE:
13906 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
13907 GOT_OBJ_LABEL_TREE);
13908 break;
13909 case GOT_OBJ_TYPE_COMMIT:
13910 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
13911 GOT_OBJ_LABEL_COMMIT);
13912 break;
13913 case GOT_OBJ_TYPE_TAG:
13914 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
13915 GOT_OBJ_LABEL_TAG);
13916 break;
13917 default:
13918 break;
13921 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TAG,
13922 got_object_tag_get_name(tag));
13924 got_date_format_gmtoff(gmtoff, sizeof(gmtoff),
13925 got_object_tag_get_tagger_gmtoff(tag));
13926 fprintf(outfile, "%s%s %lld %s\n", GOT_TAG_LABEL_TAGGER,
13927 got_object_tag_get_tagger(tag),
13928 (long long)got_object_tag_get_tagger_time(tag),
13929 gmtoff);
13931 tagmsg = got_object_tag_get_message(tag);
13932 fprintf(outfile, "messagelen %zd\n", strlen(tagmsg));
13933 fprintf(outfile, "%s", tagmsg);
13934 done:
13935 free(id_str);
13936 got_object_tag_close(tag);
13937 return err;
13940 static const struct got_error *
13941 cmd_cat(int argc, char *argv[])
13943 const struct got_error *error;
13944 struct got_repository *repo = NULL;
13945 struct got_worktree *worktree = NULL;
13946 char *cwd = NULL, *repo_path = NULL, *label = NULL;
13947 const char *commit_id_str = NULL;
13948 struct got_object_id *id = NULL, *commit_id = NULL;
13949 struct got_commit_object *commit = NULL;
13950 int ch, obj_type, i, force_path = 0;
13951 struct got_reflist_head refs;
13952 int *pack_fds = NULL;
13954 TAILQ_INIT(&refs);
13956 #ifndef PROFILE
13957 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
13958 NULL) == -1)
13959 err(1, "pledge");
13960 #endif
13962 while ((ch = getopt(argc, argv, "c:Pr:")) != -1) {
13963 switch (ch) {
13964 case 'c':
13965 commit_id_str = optarg;
13966 break;
13967 case 'P':
13968 force_path = 1;
13969 break;
13970 case 'r':
13971 repo_path = realpath(optarg, NULL);
13972 if (repo_path == NULL)
13973 return got_error_from_errno2("realpath",
13974 optarg);
13975 got_path_strip_trailing_slashes(repo_path);
13976 break;
13977 default:
13978 usage_cat();
13979 /* NOTREACHED */
13983 argc -= optind;
13984 argv += optind;
13986 cwd = getcwd(NULL, 0);
13987 if (cwd == NULL) {
13988 error = got_error_from_errno("getcwd");
13989 goto done;
13992 error = got_repo_pack_fds_open(&pack_fds);
13993 if (error != NULL)
13994 goto done;
13996 if (repo_path == NULL) {
13997 error = got_worktree_open(&worktree, cwd);
13998 if (error && error->code != GOT_ERR_NOT_WORKTREE)
13999 goto done;
14000 if (worktree) {
14001 repo_path = strdup(
14002 got_worktree_get_repo_path(worktree));
14003 if (repo_path == NULL) {
14004 error = got_error_from_errno("strdup");
14005 goto done;
14008 /* Release work tree lock. */
14009 got_worktree_close(worktree);
14010 worktree = NULL;
14014 if (repo_path == NULL) {
14015 repo_path = strdup(cwd);
14016 if (repo_path == NULL)
14017 return got_error_from_errno("strdup");
14020 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
14021 free(repo_path);
14022 if (error != NULL)
14023 goto done;
14025 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
14026 if (error)
14027 goto done;
14029 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
14030 if (error)
14031 goto done;
14033 if (commit_id_str == NULL)
14034 commit_id_str = GOT_REF_HEAD;
14035 error = got_repo_match_object_id(&commit_id, NULL,
14036 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
14037 if (error)
14038 goto done;
14040 error = got_object_open_as_commit(&commit, repo, commit_id);
14041 if (error)
14042 goto done;
14044 for (i = 0; i < argc; i++) {
14045 if (force_path) {
14046 error = got_object_id_by_path(&id, repo, commit,
14047 argv[i]);
14048 if (error)
14049 break;
14050 } else {
14051 error = got_repo_match_object_id(&id, &label, argv[i],
14052 GOT_OBJ_TYPE_ANY, NULL /* do not resolve tags */,
14053 repo);
14054 if (error) {
14055 if (error->code != GOT_ERR_BAD_OBJ_ID_STR &&
14056 error->code != GOT_ERR_NOT_REF)
14057 break;
14058 error = got_object_id_by_path(&id, repo,
14059 commit, argv[i]);
14060 if (error)
14061 break;
14065 error = got_object_get_type(&obj_type, repo, id);
14066 if (error)
14067 break;
14069 switch (obj_type) {
14070 case GOT_OBJ_TYPE_BLOB:
14071 error = cat_blob(id, repo, stdout);
14072 break;
14073 case GOT_OBJ_TYPE_TREE:
14074 error = cat_tree(id, repo, stdout);
14075 break;
14076 case GOT_OBJ_TYPE_COMMIT:
14077 error = cat_commit(id, repo, stdout);
14078 break;
14079 case GOT_OBJ_TYPE_TAG:
14080 error = cat_tag(id, repo, stdout);
14081 break;
14082 default:
14083 error = got_error(GOT_ERR_OBJ_TYPE);
14084 break;
14086 if (error)
14087 break;
14088 free(label);
14089 label = NULL;
14090 free(id);
14091 id = NULL;
14093 done:
14094 free(label);
14095 free(id);
14096 free(commit_id);
14097 if (commit)
14098 got_object_commit_close(commit);
14099 if (worktree)
14100 got_worktree_close(worktree);
14101 if (repo) {
14102 const struct got_error *close_err = got_repo_close(repo);
14103 if (error == NULL)
14104 error = close_err;
14106 if (pack_fds) {
14107 const struct got_error *pack_err =
14108 got_repo_pack_fds_close(pack_fds);
14109 if (error == NULL)
14110 error = pack_err;
14113 got_ref_list_free(&refs);
14114 return error;
14117 __dead static void
14118 usage_info(void)
14120 fprintf(stderr, "usage: %s info [path ...]\n",
14121 getprogname());
14122 exit(1);
14125 static const struct got_error *
14126 print_path_info(void *arg, const char *path, mode_t mode, time_t mtime,
14127 struct got_object_id *blob_id, struct got_object_id *staged_blob_id,
14128 struct got_object_id *commit_id)
14130 const struct got_error *err = NULL;
14131 char *id_str = NULL;
14132 char datebuf[128];
14133 struct tm mytm, *tm;
14134 struct got_pathlist_head *paths = arg;
14135 struct got_pathlist_entry *pe;
14138 * Clear error indication from any of the path arguments which
14139 * would cause this file index entry to be displayed.
14141 TAILQ_FOREACH(pe, paths, entry) {
14142 if (got_path_cmp(path, pe->path, strlen(path),
14143 pe->path_len) == 0 ||
14144 got_path_is_child(path, pe->path, pe->path_len))
14145 pe->data = NULL; /* no error */
14148 printf(GOT_COMMIT_SEP_STR);
14149 if (S_ISLNK(mode))
14150 printf("symlink: %s\n", path);
14151 else if (S_ISREG(mode)) {
14152 printf("file: %s\n", path);
14153 printf("mode: %o\n", mode & (S_IRWXU | S_IRWXG | S_IRWXO));
14154 } else if (S_ISDIR(mode))
14155 printf("directory: %s\n", path);
14156 else
14157 printf("something: %s\n", path);
14159 tm = localtime_r(&mtime, &mytm);
14160 if (tm == NULL)
14161 return NULL;
14162 if (strftime(datebuf, sizeof(datebuf), "%c %Z", tm) == 0)
14163 return got_error(GOT_ERR_NO_SPACE);
14164 printf("timestamp: %s\n", datebuf);
14166 if (blob_id) {
14167 err = got_object_id_str(&id_str, blob_id);
14168 if (err)
14169 return err;
14170 printf("based on blob: %s\n", id_str);
14171 free(id_str);
14174 if (staged_blob_id) {
14175 err = got_object_id_str(&id_str, staged_blob_id);
14176 if (err)
14177 return err;
14178 printf("based on staged blob: %s\n", id_str);
14179 free(id_str);
14182 if (commit_id) {
14183 err = got_object_id_str(&id_str, commit_id);
14184 if (err)
14185 return err;
14186 printf("based on commit: %s\n", id_str);
14187 free(id_str);
14190 return NULL;
14193 static const struct got_error *
14194 cmd_info(int argc, char *argv[])
14196 const struct got_error *error = NULL;
14197 struct got_worktree *worktree = NULL;
14198 char *cwd = NULL, *id_str = NULL;
14199 struct got_pathlist_head paths;
14200 char *uuidstr = NULL;
14201 int ch, show_files = 0;
14203 TAILQ_INIT(&paths);
14205 #ifndef PROFILE
14206 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
14207 NULL) == -1)
14208 err(1, "pledge");
14209 #endif
14211 while ((ch = getopt(argc, argv, "")) != -1) {
14212 switch (ch) {
14213 default:
14214 usage_info();
14215 /* NOTREACHED */
14219 argc -= optind;
14220 argv += optind;
14222 cwd = getcwd(NULL, 0);
14223 if (cwd == NULL) {
14224 error = got_error_from_errno("getcwd");
14225 goto done;
14228 error = got_worktree_open(&worktree, cwd);
14229 if (error) {
14230 if (error->code == GOT_ERR_NOT_WORKTREE)
14231 error = wrap_not_worktree_error(error, "info", cwd);
14232 goto done;
14235 #ifndef PROFILE
14236 /* Remove "wpath cpath proc exec sendfd" promises. */
14237 if (pledge("stdio rpath flock unveil", NULL) == -1)
14238 err(1, "pledge");
14239 #endif
14240 error = apply_unveil(NULL, 0, got_worktree_get_root_path(worktree));
14241 if (error)
14242 goto done;
14244 if (argc >= 1) {
14245 error = get_worktree_paths_from_argv(&paths, argc, argv,
14246 worktree);
14247 if (error)
14248 goto done;
14249 show_files = 1;
14252 error = got_object_id_str(&id_str,
14253 got_worktree_get_base_commit_id(worktree));
14254 if (error)
14255 goto done;
14257 error = got_worktree_get_uuid(&uuidstr, worktree);
14258 if (error)
14259 goto done;
14261 printf("work tree: %s\n", got_worktree_get_root_path(worktree));
14262 printf("work tree base commit: %s\n", id_str);
14263 printf("work tree path prefix: %s\n",
14264 got_worktree_get_path_prefix(worktree));
14265 printf("work tree branch reference: %s\n",
14266 got_worktree_get_head_ref_name(worktree));
14267 printf("work tree UUID: %s\n", uuidstr);
14268 printf("repository: %s\n", got_worktree_get_repo_path(worktree));
14270 if (show_files) {
14271 struct got_pathlist_entry *pe;
14272 TAILQ_FOREACH(pe, &paths, entry) {
14273 if (pe->path_len == 0)
14274 continue;
14276 * Assume this path will fail. This will be corrected
14277 * in print_path_info() in case the path does suceeed.
14279 pe->data = (void *)got_error(GOT_ERR_BAD_PATH);
14281 error = got_worktree_path_info(worktree, &paths,
14282 print_path_info, &paths, check_cancelled, NULL);
14283 if (error)
14284 goto done;
14285 TAILQ_FOREACH(pe, &paths, entry) {
14286 if (pe->data != NULL) {
14287 const struct got_error *perr;
14289 perr = pe->data;
14290 error = got_error_fmt(perr->code, "%s",
14291 pe->path);
14292 break;
14296 done:
14297 if (worktree)
14298 got_worktree_close(worktree);
14299 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
14300 free(cwd);
14301 free(id_str);
14302 free(uuidstr);
14303 return error;