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 || strlen(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_object_id *yca_id,
2905 struct got_repository *repo)
2907 const struct got_error *err = NULL;
2908 struct got_commit_graph *graph = NULL;
2909 struct got_object_id *head_commit_id = NULL;
2910 int is_same_branch = 0;
2912 err = got_ref_resolve(&head_commit_id, repo, head_ref);
2913 if (err)
2914 goto done;
2916 if (got_object_id_cmp(head_commit_id, commit_id) == 0) {
2917 is_same_branch = 1;
2918 goto done;
2920 if (yca_id && got_object_id_cmp(commit_id, yca_id) == 0) {
2921 is_same_branch = 1;
2922 goto done;
2925 err = got_commit_graph_open(&graph, "/", 1);
2926 if (err)
2927 goto done;
2929 err = got_commit_graph_iter_start(graph, head_commit_id, repo,
2930 check_cancelled, NULL);
2931 if (err)
2932 goto done;
2934 for (;;) {
2935 struct got_object_id id;
2937 err = got_commit_graph_iter_next(&id, graph, repo,
2938 check_cancelled, NULL);
2939 if (err) {
2940 if (err->code == GOT_ERR_ITER_COMPLETED)
2941 err = NULL;
2942 break;
2945 if (yca_id && got_object_id_cmp(&id, yca_id) == 0)
2946 break;
2947 if (got_object_id_cmp(&id, commit_id) == 0) {
2948 is_same_branch = 1;
2949 break;
2952 done:
2953 if (graph)
2954 got_commit_graph_close(graph);
2955 free(head_commit_id);
2956 if (!err && !is_same_branch)
2957 err = got_error(GOT_ERR_ANCESTRY);
2958 return err;
2961 static const struct got_error *
2962 checkout_ancestry_error(struct got_reference *ref, const char *commit_id_str)
2964 static char msg[512];
2965 const char *branch_name;
2967 if (got_ref_is_symbolic(ref))
2968 branch_name = got_ref_get_symref_target(ref);
2969 else
2970 branch_name = got_ref_get_name(ref);
2972 if (strncmp("refs/heads/", branch_name, 11) == 0)
2973 branch_name += 11;
2975 snprintf(msg, sizeof(msg),
2976 "target commit is not contained in branch '%s'; "
2977 "the branch to use must be specified with -b; "
2978 "if necessary a new branch can be created for "
2979 "this commit with 'got branch -c %s BRANCH_NAME'",
2980 branch_name, commit_id_str);
2982 return got_error_msg(GOT_ERR_ANCESTRY, msg);
2985 static const struct got_error *
2986 cmd_checkout(int argc, char *argv[])
2988 const struct got_error *error = NULL;
2989 struct got_repository *repo = NULL;
2990 struct got_reference *head_ref = NULL, *ref = NULL;
2991 struct got_worktree *worktree = NULL;
2992 char *repo_path = NULL;
2993 char *worktree_path = NULL;
2994 const char *path_prefix = "";
2995 const char *branch_name = GOT_REF_HEAD, *refname = NULL;
2996 char *commit_id_str = NULL;
2997 struct got_object_id *commit_id = NULL;
2998 char *cwd = NULL;
2999 int ch, same_path_prefix, allow_nonempty = 0, verbosity = 0;
3000 struct got_pathlist_head paths;
3001 struct got_checkout_progress_arg cpa;
3002 int *pack_fds = NULL;
3004 TAILQ_INIT(&paths);
3006 #ifndef PROFILE
3007 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
3008 "unveil", NULL) == -1)
3009 err(1, "pledge");
3010 #endif
3012 while ((ch = getopt(argc, argv, "b:c:Ep:q")) != -1) {
3013 switch (ch) {
3014 case 'b':
3015 branch_name = optarg;
3016 break;
3017 case 'c':
3018 commit_id_str = strdup(optarg);
3019 if (commit_id_str == NULL)
3020 return got_error_from_errno("strdup");
3021 break;
3022 case 'E':
3023 allow_nonempty = 1;
3024 break;
3025 case 'p':
3026 path_prefix = optarg;
3027 break;
3028 case 'q':
3029 verbosity = -1;
3030 break;
3031 default:
3032 usage_checkout();
3033 /* NOTREACHED */
3037 argc -= optind;
3038 argv += optind;
3040 if (argc == 1) {
3041 char *base, *dotgit;
3042 const char *path;
3043 repo_path = realpath(argv[0], NULL);
3044 if (repo_path == NULL)
3045 return got_error_from_errno2("realpath", argv[0]);
3046 cwd = getcwd(NULL, 0);
3047 if (cwd == NULL) {
3048 error = got_error_from_errno("getcwd");
3049 goto done;
3051 if (path_prefix[0])
3052 path = path_prefix;
3053 else
3054 path = repo_path;
3055 error = got_path_basename(&base, path);
3056 if (error)
3057 goto done;
3058 dotgit = strstr(base, ".git");
3059 if (dotgit)
3060 *dotgit = '\0';
3061 if (asprintf(&worktree_path, "%s/%s", cwd, base) == -1) {
3062 error = got_error_from_errno("asprintf");
3063 free(base);
3064 goto done;
3066 free(base);
3067 } else if (argc == 2) {
3068 repo_path = realpath(argv[0], NULL);
3069 if (repo_path == NULL) {
3070 error = got_error_from_errno2("realpath", argv[0]);
3071 goto done;
3073 worktree_path = realpath(argv[1], NULL);
3074 if (worktree_path == NULL) {
3075 if (errno != ENOENT) {
3076 error = got_error_from_errno2("realpath",
3077 argv[1]);
3078 goto done;
3080 worktree_path = strdup(argv[1]);
3081 if (worktree_path == NULL) {
3082 error = got_error_from_errno("strdup");
3083 goto done;
3086 } else
3087 usage_checkout();
3089 got_path_strip_trailing_slashes(repo_path);
3090 got_path_strip_trailing_slashes(worktree_path);
3092 error = got_repo_pack_fds_open(&pack_fds);
3093 if (error != NULL)
3094 goto done;
3096 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
3097 if (error != NULL)
3098 goto done;
3100 /* Pre-create work tree path for unveil(2) */
3101 error = got_path_mkdir(worktree_path);
3102 if (error) {
3103 if (!(error->code == GOT_ERR_ERRNO && errno == EISDIR) &&
3104 !(error->code == GOT_ERR_ERRNO && errno == EEXIST))
3105 goto done;
3106 if (!allow_nonempty &&
3107 !got_path_dir_is_empty(worktree_path)) {
3108 error = got_error_path(worktree_path,
3109 GOT_ERR_DIR_NOT_EMPTY);
3110 goto done;
3114 error = apply_unveil(got_repo_get_path(repo), 0, worktree_path);
3115 if (error)
3116 goto done;
3118 error = got_ref_open(&head_ref, repo, branch_name, 0);
3119 if (error != NULL)
3120 goto done;
3122 error = got_worktree_init(worktree_path, head_ref, path_prefix, repo);
3123 if (error != NULL && !(error->code == GOT_ERR_ERRNO && errno == EEXIST))
3124 goto done;
3126 error = got_worktree_open(&worktree, worktree_path);
3127 if (error != NULL)
3128 goto done;
3130 error = got_worktree_match_path_prefix(&same_path_prefix, worktree,
3131 path_prefix);
3132 if (error != NULL)
3133 goto done;
3134 if (!same_path_prefix) {
3135 error = got_error(GOT_ERR_PATH_PREFIX);
3136 goto done;
3139 if (commit_id_str) {
3140 struct got_reflist_head refs;
3141 TAILQ_INIT(&refs);
3142 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
3143 NULL);
3144 if (error)
3145 goto done;
3146 error = got_repo_match_object_id(&commit_id, NULL,
3147 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
3148 got_ref_list_free(&refs);
3149 if (error)
3150 goto done;
3151 error = check_linear_ancestry(commit_id,
3152 got_worktree_get_base_commit_id(worktree), 0, repo);
3153 if (error != NULL) {
3154 if (error->code == GOT_ERR_ANCESTRY) {
3155 error = checkout_ancestry_error(
3156 head_ref, commit_id_str);
3158 goto done;
3160 error = check_same_branch(commit_id, head_ref, NULL, repo);
3161 if (error) {
3162 if (error->code == GOT_ERR_ANCESTRY) {
3163 error = checkout_ancestry_error(
3164 head_ref, commit_id_str);
3166 goto done;
3168 error = got_worktree_set_base_commit_id(worktree, repo,
3169 commit_id);
3170 if (error)
3171 goto done;
3172 /* Expand potentially abbreviated commit ID string. */
3173 free(commit_id_str);
3174 error = got_object_id_str(&commit_id_str, commit_id);
3175 if (error)
3176 goto done;
3177 } else {
3178 commit_id = got_object_id_dup(
3179 got_worktree_get_base_commit_id(worktree));
3180 if (commit_id == NULL) {
3181 error = got_error_from_errno("got_object_id_dup");
3182 goto done;
3184 error = got_object_id_str(&commit_id_str, commit_id);
3185 if (error)
3186 goto done;
3189 error = got_pathlist_append(&paths, "", NULL);
3190 if (error)
3191 goto done;
3192 cpa.worktree_path = worktree_path;
3193 cpa.had_base_commit_ref_error = 0;
3194 cpa.verbosity = verbosity;
3195 error = got_worktree_checkout_files(worktree, &paths, repo,
3196 checkout_progress, &cpa, check_cancelled, NULL);
3197 if (error != NULL)
3198 goto done;
3200 if (got_ref_is_symbolic(head_ref)) {
3201 error = got_ref_resolve_symbolic(&ref, repo, head_ref);
3202 if (error)
3203 goto done;
3204 refname = got_ref_get_name(ref);
3205 } else
3206 refname = got_ref_get_name(head_ref);
3207 printf("Checked out %s: %s\n", refname, commit_id_str);
3208 printf("Now shut up and hack\n");
3209 if (cpa.had_base_commit_ref_error)
3210 show_worktree_base_ref_warning();
3211 done:
3212 if (pack_fds) {
3213 const struct got_error *pack_err =
3214 got_repo_pack_fds_close(pack_fds);
3215 if (error == NULL)
3216 error = pack_err;
3218 if (head_ref)
3219 got_ref_close(head_ref);
3220 if (ref)
3221 got_ref_close(ref);
3222 if (repo) {
3223 const struct got_error *close_err = got_repo_close(repo);
3224 if (error == NULL)
3225 error = close_err;
3227 got_pathlist_free(&paths, GOT_PATHLIST_FREE_NONE);
3228 free(commit_id_str);
3229 free(commit_id);
3230 free(repo_path);
3231 free(worktree_path);
3232 free(cwd);
3233 return error;
3236 struct got_update_progress_arg {
3237 int did_something;
3238 int conflicts;
3239 int obstructed;
3240 int not_updated;
3241 int missing;
3242 int not_deleted;
3243 int unversioned;
3244 int verbosity;
3247 static void
3248 print_update_progress_stats(struct got_update_progress_arg *upa)
3250 if (!upa->did_something)
3251 return;
3253 if (upa->conflicts > 0)
3254 printf("Files with new merge conflicts: %d\n", upa->conflicts);
3255 if (upa->obstructed > 0)
3256 printf("File paths obstructed by a non-regular file: %d\n",
3257 upa->obstructed);
3258 if (upa->not_updated > 0)
3259 printf("Files not updated because of existing merge "
3260 "conflicts: %d\n", upa->not_updated);
3264 * The meaning of some status codes differs between merge-style operations and
3265 * update operations. For example, the ! status code means "file was missing"
3266 * if changes were merged into the work tree, and "missing file was restored"
3267 * if the work tree was updated. This function should be used by any operation
3268 * which merges changes into the work tree without updating the work tree.
3270 static void
3271 print_merge_progress_stats(struct got_update_progress_arg *upa)
3273 if (!upa->did_something)
3274 return;
3276 if (upa->conflicts > 0)
3277 printf("Files with new merge conflicts: %d\n", upa->conflicts);
3278 if (upa->obstructed > 0)
3279 printf("File paths obstructed by a non-regular file: %d\n",
3280 upa->obstructed);
3281 if (upa->missing > 0)
3282 printf("Files which had incoming changes but could not be "
3283 "found in the work tree: %d\n", upa->missing);
3284 if (upa->not_deleted > 0)
3285 printf("Files not deleted due to differences in deleted "
3286 "content: %d\n", upa->not_deleted);
3287 if (upa->unversioned > 0)
3288 printf("Files not merged because an unversioned file was "
3289 "found in the work tree: %d\n", upa->unversioned);
3292 __dead static void
3293 usage_update(void)
3295 fprintf(stderr, "usage: %s update [-q] [-b branch] [-c commit] "
3296 "[path ...]\n", getprogname());
3297 exit(1);
3300 static const struct got_error *
3301 update_progress(void *arg, unsigned char status, const char *path)
3303 struct got_update_progress_arg *upa = arg;
3305 if (status == GOT_STATUS_EXISTS ||
3306 status == GOT_STATUS_BASE_REF_ERR)
3307 return NULL;
3309 upa->did_something = 1;
3311 /* Base commit bump happens silently. */
3312 if (status == GOT_STATUS_BUMP_BASE)
3313 return NULL;
3315 if (status == GOT_STATUS_CONFLICT)
3316 upa->conflicts++;
3317 if (status == GOT_STATUS_OBSTRUCTED)
3318 upa->obstructed++;
3319 if (status == GOT_STATUS_CANNOT_UPDATE)
3320 upa->not_updated++;
3321 if (status == GOT_STATUS_MISSING)
3322 upa->missing++;
3323 if (status == GOT_STATUS_CANNOT_DELETE)
3324 upa->not_deleted++;
3325 if (status == GOT_STATUS_UNVERSIONED)
3326 upa->unversioned++;
3328 while (path[0] == '/')
3329 path++;
3330 if (upa->verbosity >= 0)
3331 printf("%c %s\n", status, path);
3333 return NULL;
3336 static const struct got_error *
3337 switch_head_ref(struct got_reference *head_ref,
3338 struct got_object_id *commit_id, struct got_worktree *worktree,
3339 struct got_repository *repo)
3341 const struct got_error *err = NULL;
3342 char *base_id_str;
3343 int ref_has_moved = 0;
3345 /* Trivial case: switching between two different references. */
3346 if (strcmp(got_ref_get_name(head_ref),
3347 got_worktree_get_head_ref_name(worktree)) != 0) {
3348 printf("Switching work tree from %s to %s\n",
3349 got_worktree_get_head_ref_name(worktree),
3350 got_ref_get_name(head_ref));
3351 return got_worktree_set_head_ref(worktree, head_ref);
3354 err = check_linear_ancestry(commit_id,
3355 got_worktree_get_base_commit_id(worktree), 0, repo);
3356 if (err) {
3357 if (err->code != GOT_ERR_ANCESTRY)
3358 return err;
3359 ref_has_moved = 1;
3361 if (!ref_has_moved)
3362 return NULL;
3364 /* Switching to a rebased branch with the same reference name. */
3365 err = got_object_id_str(&base_id_str,
3366 got_worktree_get_base_commit_id(worktree));
3367 if (err)
3368 return err;
3369 printf("Reference %s now points at a different branch\n",
3370 got_worktree_get_head_ref_name(worktree));
3371 printf("Switching work tree from %s to %s\n", base_id_str,
3372 got_worktree_get_head_ref_name(worktree));
3373 return NULL;
3376 static const struct got_error *
3377 check_rebase_or_histedit_in_progress(struct got_worktree *worktree)
3379 const struct got_error *err;
3380 int in_progress;
3382 err = got_worktree_rebase_in_progress(&in_progress, worktree);
3383 if (err)
3384 return err;
3385 if (in_progress)
3386 return got_error(GOT_ERR_REBASING);
3388 err = got_worktree_histedit_in_progress(&in_progress, worktree);
3389 if (err)
3390 return err;
3391 if (in_progress)
3392 return got_error(GOT_ERR_HISTEDIT_BUSY);
3394 return NULL;
3397 static const struct got_error *
3398 check_merge_in_progress(struct got_worktree *worktree,
3399 struct got_repository *repo)
3401 const struct got_error *err;
3402 int in_progress;
3404 err = got_worktree_merge_in_progress(&in_progress, worktree, repo);
3405 if (err)
3406 return err;
3407 if (in_progress)
3408 return got_error(GOT_ERR_MERGE_BUSY);
3410 return NULL;
3413 static const struct got_error *
3414 get_worktree_paths_from_argv(struct got_pathlist_head *paths, int argc,
3415 char *argv[], struct got_worktree *worktree)
3417 const struct got_error *err = NULL;
3418 char *path;
3419 struct got_pathlist_entry *new;
3420 int i;
3422 if (argc == 0) {
3423 path = strdup("");
3424 if (path == NULL)
3425 return got_error_from_errno("strdup");
3426 return got_pathlist_append(paths, path, NULL);
3429 for (i = 0; i < argc; i++) {
3430 err = got_worktree_resolve_path(&path, worktree, argv[i]);
3431 if (err)
3432 break;
3433 err = got_pathlist_insert(&new, paths, path, NULL);
3434 if (err || new == NULL /* duplicate */) {
3435 free(path);
3436 if (err)
3437 break;
3441 return err;
3444 static const struct got_error *
3445 wrap_not_worktree_error(const struct got_error *orig_err,
3446 const char *cmdname, const char *path)
3448 const struct got_error *err;
3449 struct got_repository *repo;
3450 static char msg[512];
3451 int *pack_fds = NULL;
3453 err = got_repo_pack_fds_open(&pack_fds);
3454 if (err)
3455 return err;
3457 err = got_repo_open(&repo, path, NULL, pack_fds);
3458 if (err)
3459 return orig_err;
3461 snprintf(msg, sizeof(msg),
3462 "'got %s' needs a work tree in addition to a git repository\n"
3463 "Work trees can be checked out from this Git repository with "
3464 "'got checkout'.\n"
3465 "The got(1) manual page contains more information.", cmdname);
3466 err = got_error_msg(GOT_ERR_NOT_WORKTREE, msg);
3467 if (repo) {
3468 const struct got_error *close_err = got_repo_close(repo);
3469 if (close_err == NULL)
3470 err = close_err;
3472 if (pack_fds) {
3473 const struct got_error *pack_err =
3474 got_repo_pack_fds_close(pack_fds);
3475 if (err == NULL)
3476 err = pack_err;
3478 return err;
3481 static const struct got_error *
3482 cmd_update(int argc, char *argv[])
3484 const struct got_error *error = NULL;
3485 struct got_repository *repo = NULL;
3486 struct got_worktree *worktree = NULL;
3487 char *worktree_path = NULL;
3488 struct got_object_id *commit_id = NULL;
3489 char *commit_id_str = NULL;
3490 const char *branch_name = NULL;
3491 struct got_reference *head_ref = NULL;
3492 struct got_pathlist_head paths;
3493 struct got_pathlist_entry *pe;
3494 int ch, verbosity = 0;
3495 struct got_update_progress_arg upa;
3496 int *pack_fds = NULL;
3498 TAILQ_INIT(&paths);
3500 #ifndef PROFILE
3501 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
3502 "unveil", NULL) == -1)
3503 err(1, "pledge");
3504 #endif
3506 while ((ch = getopt(argc, argv, "b:c:q")) != -1) {
3507 switch (ch) {
3508 case 'b':
3509 branch_name = optarg;
3510 break;
3511 case 'c':
3512 commit_id_str = strdup(optarg);
3513 if (commit_id_str == NULL)
3514 return got_error_from_errno("strdup");
3515 break;
3516 case 'q':
3517 verbosity = -1;
3518 break;
3519 default:
3520 usage_update();
3521 /* NOTREACHED */
3525 argc -= optind;
3526 argv += optind;
3528 worktree_path = getcwd(NULL, 0);
3529 if (worktree_path == NULL) {
3530 error = got_error_from_errno("getcwd");
3531 goto done;
3534 error = got_repo_pack_fds_open(&pack_fds);
3535 if (error != NULL)
3536 goto done;
3538 error = got_worktree_open(&worktree, worktree_path);
3539 if (error) {
3540 if (error->code == GOT_ERR_NOT_WORKTREE)
3541 error = wrap_not_worktree_error(error, "update",
3542 worktree_path);
3543 goto done;
3546 error = check_rebase_or_histedit_in_progress(worktree);
3547 if (error)
3548 goto done;
3550 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
3551 NULL, pack_fds);
3552 if (error != NULL)
3553 goto done;
3555 error = apply_unveil(got_repo_get_path(repo), 0,
3556 got_worktree_get_root_path(worktree));
3557 if (error)
3558 goto done;
3560 error = check_merge_in_progress(worktree, repo);
3561 if (error)
3562 goto done;
3564 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
3565 if (error)
3566 goto done;
3568 error = got_ref_open(&head_ref, repo, branch_name ? branch_name :
3569 got_worktree_get_head_ref_name(worktree), 0);
3570 if (error != NULL)
3571 goto done;
3572 if (commit_id_str == NULL) {
3573 error = got_ref_resolve(&commit_id, repo, head_ref);
3574 if (error != NULL)
3575 goto done;
3576 error = got_object_id_str(&commit_id_str, commit_id);
3577 if (error != NULL)
3578 goto done;
3579 } else {
3580 struct got_reflist_head refs;
3581 TAILQ_INIT(&refs);
3582 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
3583 NULL);
3584 if (error)
3585 goto done;
3586 error = got_repo_match_object_id(&commit_id, NULL,
3587 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
3588 got_ref_list_free(&refs);
3589 free(commit_id_str);
3590 commit_id_str = NULL;
3591 if (error)
3592 goto done;
3593 error = got_object_id_str(&commit_id_str, commit_id);
3594 if (error)
3595 goto done;
3598 if (branch_name) {
3599 struct got_object_id *head_commit_id;
3600 TAILQ_FOREACH(pe, &paths, entry) {
3601 if (pe->path_len == 0)
3602 continue;
3603 error = got_error_msg(GOT_ERR_BAD_PATH,
3604 "switching between branches requires that "
3605 "the entire work tree gets updated");
3606 goto done;
3608 error = got_ref_resolve(&head_commit_id, repo, head_ref);
3609 if (error)
3610 goto done;
3611 error = check_linear_ancestry(commit_id, head_commit_id, 0,
3612 repo);
3613 free(head_commit_id);
3614 if (error != NULL)
3615 goto done;
3616 error = check_same_branch(commit_id, head_ref, NULL, repo);
3617 if (error)
3618 goto done;
3619 error = switch_head_ref(head_ref, commit_id, worktree, repo);
3620 if (error)
3621 goto done;
3622 } else {
3623 error = check_linear_ancestry(commit_id,
3624 got_worktree_get_base_commit_id(worktree), 0, repo);
3625 if (error != NULL) {
3626 if (error->code == GOT_ERR_ANCESTRY)
3627 error = got_error(GOT_ERR_BRANCH_MOVED);
3628 goto done;
3630 error = check_same_branch(commit_id, head_ref, NULL, repo);
3631 if (error)
3632 goto done;
3635 if (got_object_id_cmp(got_worktree_get_base_commit_id(worktree),
3636 commit_id) != 0) {
3637 error = got_worktree_set_base_commit_id(worktree, repo,
3638 commit_id);
3639 if (error)
3640 goto done;
3643 memset(&upa, 0, sizeof(upa));
3644 upa.verbosity = verbosity;
3645 error = got_worktree_checkout_files(worktree, &paths, repo,
3646 update_progress, &upa, check_cancelled, NULL);
3647 if (error != NULL)
3648 goto done;
3650 if (upa.did_something) {
3651 printf("Updated to %s: %s\n",
3652 got_worktree_get_head_ref_name(worktree), commit_id_str);
3653 } else
3654 printf("Already up-to-date\n");
3656 print_update_progress_stats(&upa);
3657 done:
3658 if (pack_fds) {
3659 const struct got_error *pack_err =
3660 got_repo_pack_fds_close(pack_fds);
3661 if (error == NULL)
3662 error = pack_err;
3664 if (repo) {
3665 const struct got_error *close_err = got_repo_close(repo);
3666 if (error == NULL)
3667 error = close_err;
3669 free(worktree_path);
3670 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
3671 free(commit_id);
3672 free(commit_id_str);
3673 return error;
3676 static const struct got_error *
3677 diff_blobs(struct got_object_id *blob_id1, struct got_object_id *blob_id2,
3678 const char *path, int diff_context, int ignore_whitespace,
3679 int force_text_diff, struct got_diffstat_cb_arg *dsa,
3680 struct got_repository *repo, FILE *outfile)
3682 const struct got_error *err = NULL;
3683 struct got_blob_object *blob1 = NULL, *blob2 = NULL;
3684 FILE *f1 = NULL, *f2 = NULL;
3685 int fd1 = -1, fd2 = -1;
3687 fd1 = got_opentempfd();
3688 if (fd1 == -1)
3689 return got_error_from_errno("got_opentempfd");
3690 fd2 = got_opentempfd();
3691 if (fd2 == -1) {
3692 err = got_error_from_errno("got_opentempfd");
3693 goto done;
3696 if (blob_id1) {
3697 err = got_object_open_as_blob(&blob1, repo, blob_id1, 8192,
3698 fd1);
3699 if (err)
3700 goto done;
3703 err = got_object_open_as_blob(&blob2, repo, blob_id2, 8192, fd2);
3704 if (err)
3705 goto done;
3707 f1 = got_opentemp();
3708 if (f1 == NULL) {
3709 err = got_error_from_errno("got_opentemp");
3710 goto done;
3712 f2 = got_opentemp();
3713 if (f2 == NULL) {
3714 err = got_error_from_errno("got_opentemp");
3715 goto done;
3718 while (path[0] == '/')
3719 path++;
3720 err = got_diff_blob(NULL, NULL, blob1, blob2, f1, f2, path, path,
3721 GOT_DIFF_ALGORITHM_PATIENCE, diff_context, ignore_whitespace,
3722 force_text_diff, dsa, outfile);
3723 done:
3724 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
3725 err = got_error_from_errno("close");
3726 if (blob1)
3727 got_object_blob_close(blob1);
3728 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
3729 err = got_error_from_errno("close");
3730 if (blob2)
3731 got_object_blob_close(blob2);
3732 if (f1 && fclose(f1) == EOF && err == NULL)
3733 err = got_error_from_errno("fclose");
3734 if (f2 && fclose(f2) == EOF && err == NULL)
3735 err = got_error_from_errno("fclose");
3736 return err;
3739 static const struct got_error *
3740 diff_trees(struct got_object_id *tree_id1, struct got_object_id *tree_id2,
3741 const char *path, int diff_context, int ignore_whitespace,
3742 int force_text_diff, struct got_diffstat_cb_arg *dsa,
3743 struct got_repository *repo, FILE *outfile)
3745 const struct got_error *err = NULL;
3746 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
3747 struct got_diff_blob_output_unidiff_arg arg;
3748 FILE *f1 = NULL, *f2 = NULL;
3749 int fd1 = -1, fd2 = -1;
3751 if (tree_id1) {
3752 err = got_object_open_as_tree(&tree1, repo, tree_id1);
3753 if (err)
3754 goto done;
3755 fd1 = got_opentempfd();
3756 if (fd1 == -1) {
3757 err = got_error_from_errno("got_opentempfd");
3758 goto done;
3762 err = got_object_open_as_tree(&tree2, repo, tree_id2);
3763 if (err)
3764 goto done;
3766 f1 = got_opentemp();
3767 if (f1 == NULL) {
3768 err = got_error_from_errno("got_opentemp");
3769 goto done;
3772 f2 = got_opentemp();
3773 if (f2 == NULL) {
3774 err = got_error_from_errno("got_opentemp");
3775 goto done;
3777 fd2 = got_opentempfd();
3778 if (fd2 == -1) {
3779 err = got_error_from_errno("got_opentempfd");
3780 goto done;
3782 arg.diff_context = diff_context;
3783 arg.ignore_whitespace = ignore_whitespace;
3784 arg.force_text_diff = force_text_diff;
3785 arg.diffstat = dsa;
3786 arg.diff_algo = GOT_DIFF_ALGORITHM_PATIENCE;
3787 arg.outfile = outfile;
3788 arg.lines = NULL;
3789 arg.nlines = 0;
3790 while (path[0] == '/')
3791 path++;
3792 err = got_diff_tree(tree1, tree2, f1, f2, fd1, fd2, path, path, repo,
3793 got_diff_blob_output_unidiff, &arg, 1);
3794 done:
3795 if (tree1)
3796 got_object_tree_close(tree1);
3797 if (tree2)
3798 got_object_tree_close(tree2);
3799 if (f1 && fclose(f1) == EOF && err == NULL)
3800 err = got_error_from_errno("fclose");
3801 if (f2 && fclose(f2) == EOF && err == NULL)
3802 err = got_error_from_errno("fclose");
3803 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
3804 err = got_error_from_errno("close");
3805 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
3806 err = got_error_from_errno("close");
3807 return err;
3810 static const struct got_error *
3811 get_changed_paths(struct got_pathlist_head *paths,
3812 struct got_commit_object *commit, struct got_repository *repo,
3813 struct got_diffstat_cb_arg *dsa)
3815 const struct got_error *err = NULL;
3816 struct got_object_id *tree_id1 = NULL, *tree_id2 = NULL;
3817 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
3818 struct got_object_qid *qid;
3819 got_diff_blob_cb cb = got_diff_tree_collect_changed_paths;
3820 FILE *f1 = NULL, *f2 = NULL;
3821 int fd1 = -1, fd2 = -1;
3823 if (dsa) {
3824 cb = got_diff_tree_compute_diffstat;
3826 f1 = got_opentemp();
3827 if (f1 == NULL) {
3828 err = got_error_from_errno("got_opentemp");
3829 goto done;
3831 f2 = got_opentemp();
3832 if (f2 == NULL) {
3833 err = got_error_from_errno("got_opentemp");
3834 goto done;
3836 fd1 = got_opentempfd();
3837 if (fd1 == -1) {
3838 err = got_error_from_errno("got_opentempfd");
3839 goto done;
3841 fd2 = got_opentempfd();
3842 if (fd2 == -1) {
3843 err = got_error_from_errno("got_opentempfd");
3844 goto done;
3848 qid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
3849 if (qid != NULL) {
3850 struct got_commit_object *pcommit;
3851 err = got_object_open_as_commit(&pcommit, repo,
3852 &qid->id);
3853 if (err)
3854 return err;
3856 tree_id1 = got_object_id_dup(
3857 got_object_commit_get_tree_id(pcommit));
3858 if (tree_id1 == NULL) {
3859 got_object_commit_close(pcommit);
3860 return got_error_from_errno("got_object_id_dup");
3862 got_object_commit_close(pcommit);
3866 if (tree_id1) {
3867 err = got_object_open_as_tree(&tree1, repo, tree_id1);
3868 if (err)
3869 goto done;
3872 tree_id2 = got_object_commit_get_tree_id(commit);
3873 err = got_object_open_as_tree(&tree2, repo, tree_id2);
3874 if (err)
3875 goto done;
3877 err = got_diff_tree(tree1, tree2, f1, f2, fd1, fd2, "", "", repo,
3878 cb, dsa ? (void *)dsa : paths, dsa ? 1 : 0);
3879 done:
3880 if (tree1)
3881 got_object_tree_close(tree1);
3882 if (tree2)
3883 got_object_tree_close(tree2);
3884 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
3885 err = got_error_from_errno("close");
3886 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
3887 err = got_error_from_errno("close");
3888 if (f1 && fclose(f1) == EOF && err == NULL)
3889 err = got_error_from_errno("fclose");
3890 if (f2 && fclose(f2) == EOF && err == NULL)
3891 err = got_error_from_errno("fclose");
3892 free(tree_id1);
3893 return err;
3896 static const struct got_error *
3897 print_patch(struct got_commit_object *commit, struct got_object_id *id,
3898 const char *path, int diff_context, struct got_diffstat_cb_arg *dsa,
3899 struct got_repository *repo, FILE *outfile)
3901 const struct got_error *err = NULL;
3902 struct got_commit_object *pcommit = NULL;
3903 char *id_str1 = NULL, *id_str2 = NULL;
3904 struct got_object_id *obj_id1 = NULL, *obj_id2 = NULL;
3905 struct got_object_qid *qid;
3907 qid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
3908 if (qid != NULL) {
3909 err = got_object_open_as_commit(&pcommit, repo,
3910 &qid->id);
3911 if (err)
3912 return err;
3913 err = got_object_id_str(&id_str1, &qid->id);
3914 if (err)
3915 goto done;
3918 err = got_object_id_str(&id_str2, id);
3919 if (err)
3920 goto done;
3922 if (path && path[0] != '\0') {
3923 int obj_type;
3924 err = got_object_id_by_path(&obj_id2, repo, commit, path);
3925 if (err)
3926 goto done;
3927 if (pcommit) {
3928 err = got_object_id_by_path(&obj_id1, repo,
3929 pcommit, path);
3930 if (err) {
3931 if (err->code != GOT_ERR_NO_TREE_ENTRY) {
3932 free(obj_id2);
3933 goto done;
3937 err = got_object_get_type(&obj_type, repo, obj_id2);
3938 if (err) {
3939 free(obj_id2);
3940 goto done;
3942 fprintf(outfile,
3943 "diff %s %s\n", id_str1 ? id_str1 : "/dev/null", id_str2);
3944 fprintf(outfile, "commit - %s\n",
3945 id_str1 ? id_str1 : "/dev/null");
3946 fprintf(outfile, "commit + %s\n", id_str2);
3947 switch (obj_type) {
3948 case GOT_OBJ_TYPE_BLOB:
3949 err = diff_blobs(obj_id1, obj_id2, path, diff_context,
3950 0, 0, dsa, repo, outfile);
3951 break;
3952 case GOT_OBJ_TYPE_TREE:
3953 err = diff_trees(obj_id1, obj_id2, path, diff_context,
3954 0, 0, dsa, repo, outfile);
3955 break;
3956 default:
3957 err = got_error(GOT_ERR_OBJ_TYPE);
3958 break;
3960 free(obj_id1);
3961 free(obj_id2);
3962 } else {
3963 obj_id2 = got_object_commit_get_tree_id(commit);
3964 if (pcommit)
3965 obj_id1 = got_object_commit_get_tree_id(pcommit);
3966 fprintf(outfile,
3967 "diff %s %s\n", id_str1 ? id_str1 : "/dev/null", id_str2);
3968 fprintf(outfile, "commit - %s\n",
3969 id_str1 ? id_str1 : "/dev/null");
3970 fprintf(outfile, "commit + %s\n", id_str2);
3971 err = diff_trees(obj_id1, obj_id2, "", diff_context, 0, 0,
3972 dsa, repo, outfile);
3974 done:
3975 free(id_str1);
3976 free(id_str2);
3977 if (pcommit)
3978 got_object_commit_close(pcommit);
3979 return err;
3982 static char *
3983 get_datestr(time_t *time, char *datebuf)
3985 struct tm mytm, *tm;
3986 char *p, *s;
3988 tm = gmtime_r(time, &mytm);
3989 if (tm == NULL)
3990 return NULL;
3991 s = asctime_r(tm, datebuf);
3992 if (s == NULL)
3993 return NULL;
3994 p = strchr(s, '\n');
3995 if (p)
3996 *p = '\0';
3997 return s;
4000 static const struct got_error *
4001 match_commit(int *have_match, struct got_object_id *id,
4002 struct got_commit_object *commit, regex_t *regex)
4004 const struct got_error *err = NULL;
4005 regmatch_t regmatch;
4006 char *id_str = NULL, *logmsg = NULL;
4008 *have_match = 0;
4010 err = got_object_id_str(&id_str, id);
4011 if (err)
4012 return err;
4014 err = got_object_commit_get_logmsg(&logmsg, commit);
4015 if (err)
4016 goto done;
4018 if (regexec(regex, got_object_commit_get_author(commit), 1,
4019 &regmatch, 0) == 0 ||
4020 regexec(regex, got_object_commit_get_committer(commit), 1,
4021 &regmatch, 0) == 0 ||
4022 regexec(regex, id_str, 1, &regmatch, 0) == 0 ||
4023 regexec(regex, logmsg, 1, &regmatch, 0) == 0)
4024 *have_match = 1;
4025 done:
4026 free(id_str);
4027 free(logmsg);
4028 return err;
4031 static void
4032 match_changed_paths(int *have_match, struct got_pathlist_head *changed_paths,
4033 regex_t *regex)
4035 regmatch_t regmatch;
4036 struct got_pathlist_entry *pe;
4038 *have_match = 0;
4040 TAILQ_FOREACH(pe, changed_paths, entry) {
4041 if (regexec(regex, pe->path, 1, &regmatch, 0) == 0) {
4042 *have_match = 1;
4043 break;
4048 static const struct got_error *
4049 match_patch(int *have_match, struct got_commit_object *commit,
4050 struct got_object_id *id, const char *path, int diff_context,
4051 struct got_repository *repo, regex_t *regex, FILE *f)
4053 const struct got_error *err = NULL;
4054 char *line = NULL;
4055 size_t linesize = 0;
4056 regmatch_t regmatch;
4058 *have_match = 0;
4060 err = got_opentemp_truncate(f);
4061 if (err)
4062 return err;
4064 err = print_patch(commit, id, path, diff_context, NULL, repo, f);
4065 if (err)
4066 goto done;
4068 if (fseeko(f, 0L, SEEK_SET) == -1) {
4069 err = got_error_from_errno("fseeko");
4070 goto done;
4073 while (getline(&line, &linesize, f) != -1) {
4074 if (regexec(regex, line, 1, &regmatch, 0) == 0) {
4075 *have_match = 1;
4076 break;
4079 done:
4080 free(line);
4081 return err;
4084 #define GOT_COMMIT_SEP_STR "-----------------------------------------------\n"
4086 static const struct got_error*
4087 build_refs_str(char **refs_str, struct got_reflist_head *refs,
4088 struct got_object_id *id, struct got_repository *repo,
4089 int local_only)
4091 static const struct got_error *err = NULL;
4092 struct got_reflist_entry *re;
4093 char *s;
4094 const char *name;
4096 *refs_str = NULL;
4098 TAILQ_FOREACH(re, refs, entry) {
4099 struct got_tag_object *tag = NULL;
4100 struct got_object_id *ref_id;
4101 int cmp;
4103 name = got_ref_get_name(re->ref);
4104 if (strcmp(name, GOT_REF_HEAD) == 0)
4105 continue;
4106 if (strncmp(name, "refs/", 5) == 0)
4107 name += 5;
4108 if (strncmp(name, "got/", 4) == 0)
4109 continue;
4110 if (strncmp(name, "heads/", 6) == 0)
4111 name += 6;
4112 if (strncmp(name, "remotes/", 8) == 0) {
4113 if (local_only)
4114 continue;
4115 name += 8;
4116 s = strstr(name, "/" GOT_REF_HEAD);
4117 if (s != NULL && s[strlen(s)] == '\0')
4118 continue;
4120 err = got_ref_resolve(&ref_id, repo, re->ref);
4121 if (err)
4122 break;
4123 if (strncmp(name, "tags/", 5) == 0) {
4124 err = got_object_open_as_tag(&tag, repo, ref_id);
4125 if (err) {
4126 if (err->code != GOT_ERR_OBJ_TYPE) {
4127 free(ref_id);
4128 break;
4130 /* Ref points at something other than a tag. */
4131 err = NULL;
4132 tag = NULL;
4135 cmp = got_object_id_cmp(tag ?
4136 got_object_tag_get_object_id(tag) : ref_id, id);
4137 free(ref_id);
4138 if (tag)
4139 got_object_tag_close(tag);
4140 if (cmp != 0)
4141 continue;
4142 s = *refs_str;
4143 if (asprintf(refs_str, "%s%s%s", s ? s : "",
4144 s ? ", " : "", name) == -1) {
4145 err = got_error_from_errno("asprintf");
4146 free(s);
4147 *refs_str = NULL;
4148 break;
4150 free(s);
4153 return err;
4156 static const struct got_error *
4157 print_commit_oneline(struct got_commit_object *commit, struct got_object_id *id,
4158 struct got_repository *repo, struct got_reflist_object_id_map *refs_idmap)
4160 const struct got_error *err = NULL;
4161 char *ref_str = NULL, *id_str = NULL, *logmsg0 = NULL;
4162 char *comma, *s, *nl;
4163 struct got_reflist_head *refs;
4164 char datebuf[12]; /* YYYY-MM-DD + SPACE + NUL */
4165 struct tm tm;
4166 time_t committer_time;
4168 refs = got_reflist_object_id_map_lookup(refs_idmap, id);
4169 if (refs) {
4170 err = build_refs_str(&ref_str, refs, id, repo, 1);
4171 if (err)
4172 return err;
4174 /* Display the first matching ref only. */
4175 if (ref_str && (comma = strchr(ref_str, ',')) != NULL)
4176 *comma = '\0';
4179 if (ref_str == NULL) {
4180 err = got_object_id_str(&id_str, id);
4181 if (err)
4182 return err;
4185 committer_time = got_object_commit_get_committer_time(commit);
4186 if (gmtime_r(&committer_time, &tm) == NULL) {
4187 err = got_error_from_errno("gmtime_r");
4188 goto done;
4190 if (strftime(datebuf, sizeof(datebuf), "%G-%m-%d ", &tm) == 0) {
4191 err = got_error(GOT_ERR_NO_SPACE);
4192 goto done;
4195 err = got_object_commit_get_logmsg(&logmsg0, commit);
4196 if (err)
4197 goto done;
4199 s = logmsg0;
4200 while (isspace((unsigned char)s[0]))
4201 s++;
4203 nl = strchr(s, '\n');
4204 if (nl) {
4205 *nl = '\0';
4208 if (ref_str)
4209 printf("%s%-7s %s\n", datebuf, ref_str, s);
4210 else
4211 printf("%s%.7s %s\n", datebuf, id_str, s);
4213 if (fflush(stdout) != 0 && err == NULL)
4214 err = got_error_from_errno("fflush");
4215 done:
4216 free(id_str);
4217 free(ref_str);
4218 free(logmsg0);
4219 return err;
4222 static const struct got_error *
4223 print_diffstat(struct got_diffstat_cb_arg *dsa, const char *header)
4225 struct got_pathlist_entry *pe;
4227 if (header != NULL)
4228 printf("%s\n", header);
4230 TAILQ_FOREACH(pe, dsa->paths, entry) {
4231 struct got_diff_changed_path *cp = pe->data;
4232 int pad = dsa->max_path_len - pe->path_len + 1;
4234 printf(" %c %s%*c | %*d+ %*d-\n", cp->status, pe->path, pad,
4235 ' ', dsa->add_cols + 1, cp->add, dsa->rm_cols + 1, cp->rm);
4237 printf("\n%d file%s changed, %d insertion%s(+), %d deletion%s(-)\n\n",
4238 dsa->nfiles, dsa->nfiles > 1 ? "s" : "", dsa->ins,
4239 dsa->ins != 1 ? "s" : "", dsa->del, dsa->del != 1 ? "s" : "");
4241 if (fflush(stdout) != 0)
4242 return got_error_from_errno("fflush");
4244 return NULL;
4247 static const struct got_error *
4248 printfile(FILE *f)
4250 char buf[8192];
4251 size_t r;
4253 if (fseeko(f, 0L, SEEK_SET) == -1)
4254 return got_error_from_errno("fseek");
4256 for (;;) {
4257 r = fread(buf, 1, sizeof(buf), f);
4258 if (r == 0) {
4259 if (ferror(f))
4260 return got_error_from_errno("fread");
4261 if (feof(f))
4262 break;
4264 if (fwrite(buf, 1, r, stdout) != r)
4265 return got_ferror(stdout, GOT_ERR_IO);
4268 return NULL;
4271 static const struct got_error *
4272 print_commit(struct got_commit_object *commit, struct got_object_id *id,
4273 struct got_repository *repo, const char *path,
4274 struct got_pathlist_head *changed_paths,
4275 struct got_diffstat_cb_arg *diffstat, int show_patch, int diff_context,
4276 struct got_reflist_object_id_map *refs_idmap, const char *custom_refs_str,
4277 const char *prefix)
4279 const struct got_error *err = NULL;
4280 FILE *f = NULL;
4281 char *id_str, *datestr, *logmsg0, *logmsg, *line;
4282 char datebuf[26];
4283 time_t committer_time;
4284 const char *author, *committer;
4285 char *refs_str = NULL;
4287 err = got_object_id_str(&id_str, id);
4288 if (err)
4289 return err;
4291 if (custom_refs_str == NULL) {
4292 struct got_reflist_head *refs;
4293 refs = got_reflist_object_id_map_lookup(refs_idmap, id);
4294 if (refs) {
4295 err = build_refs_str(&refs_str, refs, id, repo, 0);
4296 if (err)
4297 goto done;
4301 printf(GOT_COMMIT_SEP_STR);
4302 if (custom_refs_str)
4303 printf("%s %s (%s)\n", prefix ? prefix : "commit", id_str,
4304 custom_refs_str);
4305 else
4306 printf("%s %s%s%s%s\n", prefix ? prefix : "commit", id_str,
4307 refs_str ? " (" : "", refs_str ? refs_str : "",
4308 refs_str ? ")" : "");
4309 free(id_str);
4310 id_str = NULL;
4311 free(refs_str);
4312 refs_str = NULL;
4313 printf("from: %s\n", got_object_commit_get_author(commit));
4314 author = got_object_commit_get_author(commit);
4315 committer = got_object_commit_get_committer(commit);
4316 if (strcmp(author, committer) != 0)
4317 printf("via: %s\n", committer);
4318 committer_time = got_object_commit_get_committer_time(commit);
4319 datestr = get_datestr(&committer_time, datebuf);
4320 if (datestr)
4321 printf("date: %s UTC\n", datestr);
4322 if (got_object_commit_get_nparents(commit) > 1) {
4323 const struct got_object_id_queue *parent_ids;
4324 struct got_object_qid *qid;
4325 int n = 1;
4326 parent_ids = got_object_commit_get_parent_ids(commit);
4327 STAILQ_FOREACH(qid, parent_ids, entry) {
4328 err = got_object_id_str(&id_str, &qid->id);
4329 if (err)
4330 goto done;
4331 printf("parent %d: %s\n", n++, id_str);
4332 free(id_str);
4333 id_str = NULL;
4337 err = got_object_commit_get_logmsg(&logmsg0, commit);
4338 if (err)
4339 goto done;
4341 logmsg = logmsg0;
4342 do {
4343 line = strsep(&logmsg, "\n");
4344 if (line)
4345 printf(" %s\n", line);
4346 } while (line);
4347 free(logmsg0);
4349 if (changed_paths && diffstat == NULL) {
4350 struct got_pathlist_entry *pe;
4352 TAILQ_FOREACH(pe, changed_paths, entry) {
4353 struct got_diff_changed_path *cp = pe->data;
4355 printf(" %c %s\n", cp->status, pe->path);
4357 printf("\n");
4359 if (show_patch) {
4360 if (diffstat) {
4361 f = got_opentemp();
4362 if (f == NULL) {
4363 err = got_error_from_errno("got_opentemp");
4364 goto done;
4368 err = print_patch(commit, id, path, diff_context, diffstat,
4369 repo, diffstat == NULL ? stdout : f);
4370 if (err)
4371 goto done;
4373 if (diffstat) {
4374 err = print_diffstat(diffstat, NULL);
4375 if (err)
4376 goto done;
4377 if (show_patch) {
4378 err = printfile(f);
4379 if (err)
4380 goto done;
4383 if (show_patch)
4384 printf("\n");
4386 if (fflush(stdout) != 0 && err == NULL)
4387 err = got_error_from_errno("fflush");
4388 done:
4389 if (f && fclose(f) == EOF && err == NULL)
4390 err = got_error_from_errno("fclose");
4391 free(id_str);
4392 free(refs_str);
4393 return err;
4396 static const struct got_error *
4397 print_commits(struct got_object_id *root_id, struct got_object_id *end_id,
4398 struct got_repository *repo, const char *path, int show_changed_paths,
4399 int show_diffstat, int show_patch, const char *search_pattern,
4400 int diff_context, int limit, int log_branches, int reverse_display_order,
4401 struct got_reflist_object_id_map *refs_idmap, int one_line,
4402 FILE *tmpfile)
4404 const struct got_error *err;
4405 struct got_commit_graph *graph;
4406 regex_t regex;
4407 int have_match;
4408 struct got_object_id_queue reversed_commits;
4409 struct got_object_qid *qid;
4410 struct got_commit_object *commit;
4411 struct got_pathlist_head changed_paths;
4413 STAILQ_INIT(&reversed_commits);
4414 TAILQ_INIT(&changed_paths);
4416 if (search_pattern && regcomp(&regex, search_pattern,
4417 REG_EXTENDED | REG_NOSUB | REG_NEWLINE))
4418 return got_error_msg(GOT_ERR_REGEX, search_pattern);
4420 err = got_commit_graph_open(&graph, path, !log_branches);
4421 if (err)
4422 return err;
4423 err = got_commit_graph_iter_start(graph, root_id, repo,
4424 check_cancelled, NULL);
4425 if (err)
4426 goto done;
4427 for (;;) {
4428 struct got_object_id id;
4429 struct got_diffstat_cb_arg dsa = { 0, 0, 0, 0, 0, 0,
4430 &changed_paths, 0, 0, GOT_DIFF_ALGORITHM_PATIENCE };
4432 if (sigint_received || sigpipe_received)
4433 break;
4435 err = got_commit_graph_iter_next(&id, graph, repo,
4436 check_cancelled, NULL);
4437 if (err) {
4438 if (err->code == GOT_ERR_ITER_COMPLETED)
4439 err = NULL;
4440 break;
4443 err = got_object_open_as_commit(&commit, repo, &id);
4444 if (err)
4445 break;
4447 if ((show_changed_paths || (show_diffstat && !show_patch))
4448 && !reverse_display_order) {
4449 err = get_changed_paths(&changed_paths, commit, repo,
4450 show_diffstat ? &dsa : NULL);
4451 if (err)
4452 break;
4455 if (search_pattern) {
4456 err = match_commit(&have_match, &id, commit, &regex);
4457 if (err) {
4458 got_object_commit_close(commit);
4459 break;
4461 if (have_match == 0 && show_changed_paths)
4462 match_changed_paths(&have_match,
4463 &changed_paths, &regex);
4464 if (have_match == 0 && show_patch) {
4465 err = match_patch(&have_match, commit, &id,
4466 path, diff_context, repo, &regex, tmpfile);
4467 if (err)
4468 break;
4470 if (have_match == 0) {
4471 got_object_commit_close(commit);
4472 got_pathlist_free(&changed_paths,
4473 GOT_PATHLIST_FREE_ALL);
4474 continue;
4478 if (reverse_display_order) {
4479 err = got_object_qid_alloc(&qid, &id);
4480 if (err)
4481 break;
4482 STAILQ_INSERT_HEAD(&reversed_commits, qid, entry);
4483 got_object_commit_close(commit);
4484 } else {
4485 if (one_line)
4486 err = print_commit_oneline(commit, &id,
4487 repo, refs_idmap);
4488 else
4489 err = print_commit(commit, &id, repo, path,
4490 (show_changed_paths || show_diffstat) ?
4491 &changed_paths : NULL,
4492 show_diffstat ? &dsa : NULL, show_patch,
4493 diff_context, refs_idmap, NULL, NULL);
4494 got_object_commit_close(commit);
4495 if (err)
4496 break;
4498 if ((limit && --limit == 0) ||
4499 (end_id && got_object_id_cmp(&id, end_id) == 0))
4500 break;
4502 got_pathlist_free(&changed_paths, GOT_PATHLIST_FREE_ALL);
4504 if (reverse_display_order) {
4505 STAILQ_FOREACH(qid, &reversed_commits, entry) {
4506 struct got_diffstat_cb_arg dsa = { 0, 0, 0, 0, 0, 0,
4507 &changed_paths, 0, 0, GOT_DIFF_ALGORITHM_PATIENCE };
4509 err = got_object_open_as_commit(&commit, repo,
4510 &qid->id);
4511 if (err)
4512 break;
4513 if (show_changed_paths ||
4514 (show_diffstat && !show_patch)) {
4515 err = get_changed_paths(&changed_paths, commit,
4516 repo, show_diffstat ? &dsa : NULL);
4517 if (err)
4518 break;
4520 if (one_line)
4521 err = print_commit_oneline(commit, &qid->id,
4522 repo, refs_idmap);
4523 else
4524 err = print_commit(commit, &qid->id, repo, path,
4525 (show_changed_paths || show_diffstat) ?
4526 &changed_paths : NULL,
4527 show_diffstat ? &dsa : NULL, show_patch,
4528 diff_context, refs_idmap, NULL, NULL);
4529 got_object_commit_close(commit);
4530 if (err)
4531 break;
4532 got_pathlist_free(&changed_paths, GOT_PATHLIST_FREE_ALL);
4535 done:
4536 while (!STAILQ_EMPTY(&reversed_commits)) {
4537 qid = STAILQ_FIRST(&reversed_commits);
4538 STAILQ_REMOVE_HEAD(&reversed_commits, entry);
4539 got_object_qid_free(qid);
4541 got_pathlist_free(&changed_paths, GOT_PATHLIST_FREE_ALL);
4542 if (search_pattern)
4543 regfree(&regex);
4544 got_commit_graph_close(graph);
4545 return err;
4548 __dead static void
4549 usage_log(void)
4551 fprintf(stderr, "usage: %s log [-bdPpRs] [-C number] [-c commit] "
4552 "[-l N] [-r repository-path] [-S search-pattern] [-x commit] "
4553 "[path]\n", getprogname());
4554 exit(1);
4557 static int
4558 get_default_log_limit(void)
4560 const char *got_default_log_limit;
4561 long long n;
4562 const char *errstr;
4564 got_default_log_limit = getenv("GOT_LOG_DEFAULT_LIMIT");
4565 if (got_default_log_limit == NULL)
4566 return 0;
4567 n = strtonum(got_default_log_limit, 0, INT_MAX, &errstr);
4568 if (errstr != NULL)
4569 return 0;
4570 return n;
4573 static const struct got_error *
4574 cmd_log(int argc, char *argv[])
4576 const struct got_error *error;
4577 struct got_repository *repo = NULL;
4578 struct got_worktree *worktree = NULL;
4579 struct got_object_id *start_id = NULL, *end_id = NULL;
4580 char *repo_path = NULL, *path = NULL, *cwd = NULL, *in_repo_path = NULL;
4581 const char *start_commit = NULL, *end_commit = NULL;
4582 const char *search_pattern = NULL;
4583 int diff_context = -1, ch;
4584 int show_changed_paths = 0, show_patch = 0, limit = 0, log_branches = 0;
4585 int show_diffstat = 0, reverse_display_order = 0, one_line = 0;
4586 const char *errstr;
4587 struct got_reflist_head refs;
4588 struct got_reflist_object_id_map *refs_idmap = NULL;
4589 FILE *tmpfile = NULL;
4590 int *pack_fds = NULL;
4592 TAILQ_INIT(&refs);
4594 #ifndef PROFILE
4595 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
4596 NULL)
4597 == -1)
4598 err(1, "pledge");
4599 #endif
4601 limit = get_default_log_limit();
4603 while ((ch = getopt(argc, argv, "bC:c:dl:PpRr:S:sx:")) != -1) {
4604 switch (ch) {
4605 case 'b':
4606 log_branches = 1;
4607 break;
4608 case 'C':
4609 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
4610 &errstr);
4611 if (errstr != NULL)
4612 errx(1, "number of context lines is %s: %s",
4613 errstr, optarg);
4614 break;
4615 case 'c':
4616 start_commit = optarg;
4617 break;
4618 case 'd':
4619 show_diffstat = 1;
4620 break;
4621 case 'l':
4622 limit = strtonum(optarg, 0, INT_MAX, &errstr);
4623 if (errstr != NULL)
4624 errx(1, "number of commits is %s: %s",
4625 errstr, optarg);
4626 break;
4627 case 'P':
4628 show_changed_paths = 1;
4629 break;
4630 case 'p':
4631 show_patch = 1;
4632 break;
4633 case 'R':
4634 reverse_display_order = 1;
4635 break;
4636 case 'r':
4637 repo_path = realpath(optarg, NULL);
4638 if (repo_path == NULL)
4639 return got_error_from_errno2("realpath",
4640 optarg);
4641 got_path_strip_trailing_slashes(repo_path);
4642 break;
4643 case 'S':
4644 search_pattern = optarg;
4645 break;
4646 case 's':
4647 one_line = 1;
4648 break;
4649 case 'x':
4650 end_commit = optarg;
4651 break;
4652 default:
4653 usage_log();
4654 /* NOTREACHED */
4658 argc -= optind;
4659 argv += optind;
4661 if (diff_context == -1)
4662 diff_context = 3;
4663 else if (!show_patch)
4664 errx(1, "-C requires -p");
4666 if (one_line && (show_patch || show_changed_paths || show_diffstat))
4667 errx(1, "cannot use -s with -d, -p or -P");
4669 cwd = getcwd(NULL, 0);
4670 if (cwd == NULL) {
4671 error = got_error_from_errno("getcwd");
4672 goto done;
4675 error = got_repo_pack_fds_open(&pack_fds);
4676 if (error != NULL)
4677 goto done;
4679 if (repo_path == NULL) {
4680 error = got_worktree_open(&worktree, cwd);
4681 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4682 goto done;
4683 error = NULL;
4686 if (argc == 1) {
4687 if (worktree) {
4688 error = got_worktree_resolve_path(&path, worktree,
4689 argv[0]);
4690 if (error)
4691 goto done;
4692 } else {
4693 path = strdup(argv[0]);
4694 if (path == NULL) {
4695 error = got_error_from_errno("strdup");
4696 goto done;
4699 } else if (argc != 0)
4700 usage_log();
4702 if (repo_path == NULL) {
4703 repo_path = worktree ?
4704 strdup(got_worktree_get_repo_path(worktree)) : strdup(cwd);
4706 if (repo_path == NULL) {
4707 error = got_error_from_errno("strdup");
4708 goto done;
4711 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
4712 if (error != NULL)
4713 goto done;
4715 error = apply_unveil(got_repo_get_path(repo), 1,
4716 worktree ? got_worktree_get_root_path(worktree) : NULL);
4717 if (error)
4718 goto done;
4720 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
4721 if (error)
4722 goto done;
4724 error = got_reflist_object_id_map_create(&refs_idmap, &refs, repo);
4725 if (error)
4726 goto done;
4728 if (start_commit == NULL) {
4729 struct got_reference *head_ref;
4730 struct got_commit_object *commit = NULL;
4731 error = got_ref_open(&head_ref, repo,
4732 worktree ? got_worktree_get_head_ref_name(worktree)
4733 : GOT_REF_HEAD, 0);
4734 if (error != NULL)
4735 goto done;
4736 error = got_ref_resolve(&start_id, repo, head_ref);
4737 got_ref_close(head_ref);
4738 if (error != NULL)
4739 goto done;
4740 error = got_object_open_as_commit(&commit, repo,
4741 start_id);
4742 if (error != NULL)
4743 goto done;
4744 got_object_commit_close(commit);
4745 } else {
4746 error = got_repo_match_object_id(&start_id, NULL,
4747 start_commit, GOT_OBJ_TYPE_COMMIT, &refs, repo);
4748 if (error != NULL)
4749 goto done;
4751 if (end_commit != NULL) {
4752 error = got_repo_match_object_id(&end_id, NULL,
4753 end_commit, GOT_OBJ_TYPE_COMMIT, &refs, repo);
4754 if (error != NULL)
4755 goto done;
4758 if (worktree) {
4760 * If a path was specified on the command line it was resolved
4761 * to a path in the work tree above. Prepend the work tree's
4762 * path prefix to obtain the corresponding in-repository path.
4764 if (path) {
4765 const char *prefix;
4766 prefix = got_worktree_get_path_prefix(worktree);
4767 if (asprintf(&in_repo_path, "%s%s%s", prefix,
4768 (path[0] != '\0') ? "/" : "", path) == -1) {
4769 error = got_error_from_errno("asprintf");
4770 goto done;
4773 } else
4774 error = got_repo_map_path(&in_repo_path, repo,
4775 path ? path : "");
4776 if (error != NULL)
4777 goto done;
4778 if (in_repo_path) {
4779 free(path);
4780 path = in_repo_path;
4783 if (worktree) {
4784 /* Release work tree lock. */
4785 got_worktree_close(worktree);
4786 worktree = NULL;
4789 if (search_pattern && show_patch) {
4790 tmpfile = got_opentemp();
4791 if (tmpfile == NULL) {
4792 error = got_error_from_errno("got_opentemp");
4793 goto done;
4797 error = print_commits(start_id, end_id, repo, path ? path : "",
4798 show_changed_paths, show_diffstat, show_patch, search_pattern,
4799 diff_context, limit, log_branches, reverse_display_order,
4800 refs_idmap, one_line, tmpfile);
4801 done:
4802 free(path);
4803 free(repo_path);
4804 free(cwd);
4805 if (worktree)
4806 got_worktree_close(worktree);
4807 if (repo) {
4808 const struct got_error *close_err = got_repo_close(repo);
4809 if (error == NULL)
4810 error = close_err;
4812 if (pack_fds) {
4813 const struct got_error *pack_err =
4814 got_repo_pack_fds_close(pack_fds);
4815 if (error == NULL)
4816 error = pack_err;
4818 if (refs_idmap)
4819 got_reflist_object_id_map_free(refs_idmap);
4820 if (tmpfile && fclose(tmpfile) == EOF && error == NULL)
4821 error = got_error_from_errno("fclose");
4822 got_ref_list_free(&refs);
4823 return error;
4826 __dead static void
4827 usage_diff(void)
4829 fprintf(stderr, "usage: %s diff [-adPsw] [-C number] [-c commit] "
4830 "[-r repository-path] [object1 object2 | path ...]\n",
4831 getprogname());
4832 exit(1);
4835 struct print_diff_arg {
4836 struct got_repository *repo;
4837 struct got_worktree *worktree;
4838 struct got_diffstat_cb_arg *diffstat;
4839 int diff_context;
4840 const char *id_str;
4841 int header_shown;
4842 int diff_staged;
4843 enum got_diff_algorithm diff_algo;
4844 int ignore_whitespace;
4845 int force_text_diff;
4846 FILE *f1;
4847 FILE *f2;
4848 FILE *outfile;
4852 * Create a file which contains the target path of a symlink so we can feed
4853 * it as content to the diff engine.
4855 static const struct got_error *
4856 get_symlink_target_file(int *fd, int dirfd, const char *de_name,
4857 const char *abspath)
4859 const struct got_error *err = NULL;
4860 char target_path[PATH_MAX];
4861 ssize_t target_len, outlen;
4863 *fd = -1;
4865 if (dirfd != -1) {
4866 target_len = readlinkat(dirfd, de_name, target_path, PATH_MAX);
4867 if (target_len == -1)
4868 return got_error_from_errno2("readlinkat", abspath);
4869 } else {
4870 target_len = readlink(abspath, target_path, PATH_MAX);
4871 if (target_len == -1)
4872 return got_error_from_errno2("readlink", abspath);
4875 *fd = got_opentempfd();
4876 if (*fd == -1)
4877 return got_error_from_errno("got_opentempfd");
4879 outlen = write(*fd, target_path, target_len);
4880 if (outlen == -1) {
4881 err = got_error_from_errno("got_opentempfd");
4882 goto done;
4885 if (lseek(*fd, 0, SEEK_SET) == -1) {
4886 err = got_error_from_errno2("lseek", abspath);
4887 goto done;
4889 done:
4890 if (err) {
4891 close(*fd);
4892 *fd = -1;
4894 return err;
4897 static const struct got_error *
4898 print_diff(void *arg, unsigned char status, unsigned char staged_status,
4899 const char *path, struct got_object_id *blob_id,
4900 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
4901 int dirfd, const char *de_name)
4903 struct print_diff_arg *a = arg;
4904 const struct got_error *err = NULL;
4905 struct got_blob_object *blob1 = NULL;
4906 int fd = -1, fd1 = -1, fd2 = -1;
4907 FILE *f2 = NULL;
4908 char *abspath = NULL, *label1 = NULL;
4909 struct stat sb;
4910 off_t size1 = 0;
4911 int f2_exists = 0;
4913 memset(&sb, 0, sizeof(sb));
4915 if (a->diff_staged) {
4916 if (staged_status != GOT_STATUS_MODIFY &&
4917 staged_status != GOT_STATUS_ADD &&
4918 staged_status != GOT_STATUS_DELETE)
4919 return NULL;
4920 } else {
4921 if (staged_status == GOT_STATUS_DELETE)
4922 return NULL;
4923 if (status == GOT_STATUS_NONEXISTENT)
4924 return got_error_set_errno(ENOENT, path);
4925 if (status != GOT_STATUS_MODIFY &&
4926 status != GOT_STATUS_ADD &&
4927 status != GOT_STATUS_DELETE &&
4928 status != GOT_STATUS_CONFLICT)
4929 return NULL;
4932 err = got_opentemp_truncate(a->f1);
4933 if (err)
4934 return got_error_from_errno("got_opentemp_truncate");
4935 err = got_opentemp_truncate(a->f2);
4936 if (err)
4937 return got_error_from_errno("got_opentemp_truncate");
4939 if (!a->header_shown) {
4940 if (fprintf(a->outfile, "diff %s%s\n",
4941 a->diff_staged ? "-s " : "",
4942 got_worktree_get_root_path(a->worktree)) < 0) {
4943 err = got_error_from_errno("fprintf");
4944 goto done;
4946 if (fprintf(a->outfile, "commit - %s\n", a->id_str) < 0) {
4947 err = got_error_from_errno("fprintf");
4948 goto done;
4950 if (fprintf(a->outfile, "path + %s%s\n",
4951 got_worktree_get_root_path(a->worktree),
4952 a->diff_staged ? " (staged changes)" : "") < 0) {
4953 err = got_error_from_errno("fprintf");
4954 goto done;
4956 a->header_shown = 1;
4959 if (a->diff_staged) {
4960 const char *label1 = NULL, *label2 = NULL;
4961 switch (staged_status) {
4962 case GOT_STATUS_MODIFY:
4963 label1 = path;
4964 label2 = path;
4965 break;
4966 case GOT_STATUS_ADD:
4967 label2 = path;
4968 break;
4969 case GOT_STATUS_DELETE:
4970 label1 = path;
4971 break;
4972 default:
4973 return got_error(GOT_ERR_FILE_STATUS);
4975 fd1 = got_opentempfd();
4976 if (fd1 == -1) {
4977 err = got_error_from_errno("got_opentempfd");
4978 goto done;
4980 fd2 = got_opentempfd();
4981 if (fd2 == -1) {
4982 err = got_error_from_errno("got_opentempfd");
4983 goto done;
4985 err = got_diff_objects_as_blobs(NULL, NULL, a->f1, a->f2,
4986 fd1, fd2, blob_id, staged_blob_id, label1, label2,
4987 a->diff_algo, a->diff_context, a->ignore_whitespace,
4988 a->force_text_diff, a->diffstat, a->repo, a->outfile);
4989 goto done;
4992 fd1 = got_opentempfd();
4993 if (fd1 == -1) {
4994 err = got_error_from_errno("got_opentempfd");
4995 goto done;
4998 if (staged_status == GOT_STATUS_ADD ||
4999 staged_status == GOT_STATUS_MODIFY) {
5000 char *id_str;
5001 err = got_object_open_as_blob(&blob1, a->repo, staged_blob_id,
5002 8192, fd1);
5003 if (err)
5004 goto done;
5005 err = got_object_id_str(&id_str, staged_blob_id);
5006 if (err)
5007 goto done;
5008 if (asprintf(&label1, "%s (staged)", id_str) == -1) {
5009 err = got_error_from_errno("asprintf");
5010 free(id_str);
5011 goto done;
5013 free(id_str);
5014 } else if (status != GOT_STATUS_ADD) {
5015 err = got_object_open_as_blob(&blob1, a->repo, blob_id, 8192,
5016 fd1);
5017 if (err)
5018 goto done;
5021 if (status != GOT_STATUS_DELETE) {
5022 if (asprintf(&abspath, "%s/%s",
5023 got_worktree_get_root_path(a->worktree), path) == -1) {
5024 err = got_error_from_errno("asprintf");
5025 goto done;
5028 if (dirfd != -1) {
5029 fd = openat(dirfd, de_name,
5030 O_RDONLY | O_NOFOLLOW | O_CLOEXEC);
5031 if (fd == -1) {
5032 if (!got_err_open_nofollow_on_symlink()) {
5033 err = got_error_from_errno2("openat",
5034 abspath);
5035 goto done;
5037 err = get_symlink_target_file(&fd, dirfd,
5038 de_name, abspath);
5039 if (err)
5040 goto done;
5042 } else {
5043 fd = open(abspath, O_RDONLY | O_NOFOLLOW | O_CLOEXEC);
5044 if (fd == -1) {
5045 if (!got_err_open_nofollow_on_symlink()) {
5046 err = got_error_from_errno2("open",
5047 abspath);
5048 goto done;
5050 err = get_symlink_target_file(&fd, dirfd,
5051 de_name, abspath);
5052 if (err)
5053 goto done;
5056 if (fstatat(fd, abspath, &sb, AT_SYMLINK_NOFOLLOW) == -1) {
5057 err = got_error_from_errno2("fstatat", abspath);
5058 goto done;
5060 f2 = fdopen(fd, "r");
5061 if (f2 == NULL) {
5062 err = got_error_from_errno2("fdopen", abspath);
5063 goto done;
5065 fd = -1;
5066 f2_exists = 1;
5069 if (blob1) {
5070 err = got_object_blob_dump_to_file(&size1, NULL, NULL,
5071 a->f1, blob1);
5072 if (err)
5073 goto done;
5076 err = got_diff_blob_file(blob1, a->f1, size1, label1, f2 ? f2 : a->f2,
5077 f2_exists, &sb, path, GOT_DIFF_ALGORITHM_PATIENCE, a->diff_context,
5078 a->ignore_whitespace, a->force_text_diff, a->diffstat, a->outfile);
5079 done:
5080 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
5081 err = got_error_from_errno("close");
5082 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
5083 err = got_error_from_errno("close");
5084 if (blob1)
5085 got_object_blob_close(blob1);
5086 if (fd != -1 && close(fd) == -1 && err == NULL)
5087 err = got_error_from_errno("close");
5088 if (f2 && fclose(f2) == EOF && err == NULL)
5089 err = got_error_from_errno("fclose");
5090 free(abspath);
5091 return err;
5094 static const struct got_error *
5095 cmd_diff(int argc, char *argv[])
5097 const struct got_error *error;
5098 struct got_repository *repo = NULL;
5099 struct got_worktree *worktree = NULL;
5100 char *cwd = NULL, *repo_path = NULL;
5101 const char *commit_args[2] = { NULL, NULL };
5102 int ncommit_args = 0;
5103 struct got_object_id *ids[2] = { NULL, NULL };
5104 char *labels[2] = { NULL, NULL };
5105 int type1 = GOT_OBJ_TYPE_ANY, type2 = GOT_OBJ_TYPE_ANY;
5106 int diff_context = 3, diff_staged = 0, ignore_whitespace = 0, ch, i;
5107 int force_text_diff = 0, force_path = 0, rflag = 0, show_diffstat = 0;
5108 const char *errstr;
5109 struct got_reflist_head refs;
5110 struct got_pathlist_head diffstat_paths, paths;
5111 FILE *f1 = NULL, *f2 = NULL, *outfile = NULL;
5112 int fd1 = -1, fd2 = -1;
5113 int *pack_fds = NULL;
5114 struct got_diffstat_cb_arg dsa;
5116 memset(&dsa, 0, sizeof(dsa));
5118 TAILQ_INIT(&refs);
5119 TAILQ_INIT(&paths);
5120 TAILQ_INIT(&diffstat_paths);
5122 #ifndef PROFILE
5123 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
5124 NULL) == -1)
5125 err(1, "pledge");
5126 #endif
5128 while ((ch = getopt(argc, argv, "aC:c:dPr:sw")) != -1) {
5129 switch (ch) {
5130 case 'a':
5131 force_text_diff = 1;
5132 break;
5133 case 'C':
5134 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
5135 &errstr);
5136 if (errstr != NULL)
5137 errx(1, "number of context lines is %s: %s",
5138 errstr, optarg);
5139 break;
5140 case 'c':
5141 if (ncommit_args >= 2)
5142 errx(1, "too many -c options used");
5143 commit_args[ncommit_args++] = optarg;
5144 break;
5145 case 'd':
5146 show_diffstat = 1;
5147 break;
5148 case 'P':
5149 force_path = 1;
5150 break;
5151 case 'r':
5152 repo_path = realpath(optarg, NULL);
5153 if (repo_path == NULL)
5154 return got_error_from_errno2("realpath",
5155 optarg);
5156 got_path_strip_trailing_slashes(repo_path);
5157 rflag = 1;
5158 break;
5159 case 's':
5160 diff_staged = 1;
5161 break;
5162 case 'w':
5163 ignore_whitespace = 1;
5164 break;
5165 default:
5166 usage_diff();
5167 /* NOTREACHED */
5171 argc -= optind;
5172 argv += optind;
5174 cwd = getcwd(NULL, 0);
5175 if (cwd == NULL) {
5176 error = got_error_from_errno("getcwd");
5177 goto done;
5180 error = got_repo_pack_fds_open(&pack_fds);
5181 if (error != NULL)
5182 goto done;
5184 if (repo_path == NULL) {
5185 error = got_worktree_open(&worktree, cwd);
5186 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5187 goto done;
5188 else
5189 error = NULL;
5190 if (worktree) {
5191 repo_path =
5192 strdup(got_worktree_get_repo_path(worktree));
5193 if (repo_path == NULL) {
5194 error = got_error_from_errno("strdup");
5195 goto done;
5197 } else {
5198 repo_path = strdup(cwd);
5199 if (repo_path == NULL) {
5200 error = got_error_from_errno("strdup");
5201 goto done;
5206 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
5207 free(repo_path);
5208 if (error != NULL)
5209 goto done;
5211 if (show_diffstat) {
5212 dsa.paths = &diffstat_paths;
5213 dsa.force_text = force_text_diff;
5214 dsa.ignore_ws = ignore_whitespace;
5215 dsa.diff_algo = GOT_DIFF_ALGORITHM_PATIENCE;
5218 if (rflag || worktree == NULL || ncommit_args > 0) {
5219 if (force_path) {
5220 error = got_error_msg(GOT_ERR_NOT_IMPL,
5221 "-P option can only be used when diffing "
5222 "a work tree");
5223 goto done;
5225 if (diff_staged) {
5226 error = got_error_msg(GOT_ERR_NOT_IMPL,
5227 "-s option can only be used when diffing "
5228 "a work tree");
5229 goto done;
5233 error = apply_unveil(got_repo_get_path(repo), 1,
5234 worktree ? got_worktree_get_root_path(worktree) : NULL);
5235 if (error)
5236 goto done;
5238 if ((!force_path && argc == 2) || ncommit_args > 0) {
5239 int obj_type = (ncommit_args > 0 ?
5240 GOT_OBJ_TYPE_COMMIT : GOT_OBJ_TYPE_ANY);
5241 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
5242 NULL);
5243 if (error)
5244 goto done;
5245 for (i = 0; i < (ncommit_args > 0 ? ncommit_args : argc); i++) {
5246 const char *arg;
5247 if (ncommit_args > 0)
5248 arg = commit_args[i];
5249 else
5250 arg = argv[i];
5251 error = got_repo_match_object_id(&ids[i], &labels[i],
5252 arg, obj_type, &refs, repo);
5253 if (error) {
5254 if (error->code != GOT_ERR_NOT_REF &&
5255 error->code != GOT_ERR_NO_OBJ)
5256 goto done;
5257 if (ncommit_args > 0)
5258 goto done;
5259 error = NULL;
5260 break;
5265 f1 = got_opentemp();
5266 if (f1 == NULL) {
5267 error = got_error_from_errno("got_opentemp");
5268 goto done;
5271 f2 = got_opentemp();
5272 if (f2 == NULL) {
5273 error = got_error_from_errno("got_opentemp");
5274 goto done;
5277 outfile = got_opentemp();
5278 if (outfile == NULL) {
5279 error = got_error_from_errno("got_opentemp");
5280 goto done;
5283 if (ncommit_args == 0 && (ids[0] == NULL || ids[1] == NULL)) {
5284 struct print_diff_arg arg;
5285 char *id_str;
5287 if (worktree == NULL) {
5288 if (argc == 2 && ids[0] == NULL) {
5289 error = got_error_path(argv[0], GOT_ERR_NO_OBJ);
5290 goto done;
5291 } else if (argc == 2 && ids[1] == NULL) {
5292 error = got_error_path(argv[1], GOT_ERR_NO_OBJ);
5293 goto done;
5294 } else if (argc > 0) {
5295 error = got_error_fmt(GOT_ERR_NOT_WORKTREE,
5296 "%s", "specified paths cannot be resolved");
5297 goto done;
5298 } else {
5299 error = got_error(GOT_ERR_NOT_WORKTREE);
5300 goto done;
5304 error = get_worktree_paths_from_argv(&paths, argc, argv,
5305 worktree);
5306 if (error)
5307 goto done;
5309 error = got_object_id_str(&id_str,
5310 got_worktree_get_base_commit_id(worktree));
5311 if (error)
5312 goto done;
5313 arg.repo = repo;
5314 arg.worktree = worktree;
5315 arg.diff_algo = GOT_DIFF_ALGORITHM_PATIENCE;
5316 arg.diff_context = diff_context;
5317 arg.id_str = id_str;
5318 arg.header_shown = 0;
5319 arg.diff_staged = diff_staged;
5320 arg.ignore_whitespace = ignore_whitespace;
5321 arg.force_text_diff = force_text_diff;
5322 arg.diffstat = show_diffstat ? &dsa : NULL;
5323 arg.f1 = f1;
5324 arg.f2 = f2;
5325 arg.outfile = outfile;
5327 error = got_worktree_status(worktree, &paths, repo, 0,
5328 print_diff, &arg, check_cancelled, NULL);
5329 free(id_str);
5330 if (error)
5331 goto done;
5333 if (show_diffstat && dsa.nfiles > 0) {
5334 char *header;
5336 if (asprintf(&header, "diffstat %s%s",
5337 diff_staged ? "-s " : "",
5338 got_worktree_get_root_path(worktree)) == -1) {
5339 error = got_error_from_errno("asprintf");
5340 goto done;
5343 error = print_diffstat(&dsa, header);
5344 free(header);
5345 if (error)
5346 goto done;
5349 error = printfile(outfile);
5350 goto done;
5353 if (ncommit_args == 1) {
5354 struct got_commit_object *commit;
5355 error = got_object_open_as_commit(&commit, repo, ids[0]);
5356 if (error)
5357 goto done;
5359 labels[1] = labels[0];
5360 ids[1] = ids[0];
5361 if (got_object_commit_get_nparents(commit) > 0) {
5362 const struct got_object_id_queue *pids;
5363 struct got_object_qid *pid;
5364 pids = got_object_commit_get_parent_ids(commit);
5365 pid = STAILQ_FIRST(pids);
5366 ids[0] = got_object_id_dup(&pid->id);
5367 if (ids[0] == NULL) {
5368 error = got_error_from_errno(
5369 "got_object_id_dup");
5370 got_object_commit_close(commit);
5371 goto done;
5373 error = got_object_id_str(&labels[0], ids[0]);
5374 if (error) {
5375 got_object_commit_close(commit);
5376 goto done;
5378 } else {
5379 ids[0] = NULL;
5380 labels[0] = strdup("/dev/null");
5381 if (labels[0] == NULL) {
5382 error = got_error_from_errno("strdup");
5383 got_object_commit_close(commit);
5384 goto done;
5388 got_object_commit_close(commit);
5391 if (ncommit_args == 0 && argc > 2) {
5392 error = got_error_msg(GOT_ERR_BAD_PATH,
5393 "path arguments cannot be used when diffing two objects");
5394 goto done;
5397 if (ids[0]) {
5398 error = got_object_get_type(&type1, repo, ids[0]);
5399 if (error)
5400 goto done;
5403 error = got_object_get_type(&type2, repo, ids[1]);
5404 if (error)
5405 goto done;
5406 if (type1 != GOT_OBJ_TYPE_ANY && type1 != type2) {
5407 error = got_error(GOT_ERR_OBJ_TYPE);
5408 goto done;
5410 if (type1 == GOT_OBJ_TYPE_BLOB && argc > 2) {
5411 error = got_error_msg(GOT_ERR_OBJ_TYPE,
5412 "path arguments cannot be used when diffing blobs");
5413 goto done;
5416 for (i = 0; ncommit_args > 0 && i < argc; i++) {
5417 char *in_repo_path;
5418 struct got_pathlist_entry *new;
5419 if (worktree) {
5420 const char *prefix;
5421 char *p;
5422 error = got_worktree_resolve_path(&p, worktree,
5423 argv[i]);
5424 if (error)
5425 goto done;
5426 prefix = got_worktree_get_path_prefix(worktree);
5427 while (prefix[0] == '/')
5428 prefix++;
5429 if (asprintf(&in_repo_path, "%s%s%s", prefix,
5430 (p[0] != '\0' && prefix[0] != '\0') ? "/" : "",
5431 p) == -1) {
5432 error = got_error_from_errno("asprintf");
5433 free(p);
5434 goto done;
5436 free(p);
5437 } else {
5438 char *mapped_path, *s;
5439 error = got_repo_map_path(&mapped_path, repo, argv[i]);
5440 if (error)
5441 goto done;
5442 s = mapped_path;
5443 while (s[0] == '/')
5444 s++;
5445 in_repo_path = strdup(s);
5446 if (in_repo_path == NULL) {
5447 error = got_error_from_errno("asprintf");
5448 free(mapped_path);
5449 goto done;
5451 free(mapped_path);
5454 error = got_pathlist_insert(&new, &paths, in_repo_path, NULL);
5455 if (error || new == NULL /* duplicate */)
5456 free(in_repo_path);
5457 if (error)
5458 goto done;
5461 if (worktree) {
5462 /* Release work tree lock. */
5463 got_worktree_close(worktree);
5464 worktree = NULL;
5467 fd1 = got_opentempfd();
5468 if (fd1 == -1) {
5469 error = got_error_from_errno("got_opentempfd");
5470 goto done;
5473 fd2 = got_opentempfd();
5474 if (fd2 == -1) {
5475 error = got_error_from_errno("got_opentempfd");
5476 goto done;
5479 switch (type1 == GOT_OBJ_TYPE_ANY ? type2 : type1) {
5480 case GOT_OBJ_TYPE_BLOB:
5481 error = got_diff_objects_as_blobs(NULL, NULL, f1, f2,
5482 fd1, fd2, ids[0], ids[1], NULL, NULL,
5483 GOT_DIFF_ALGORITHM_PATIENCE, diff_context,
5484 ignore_whitespace, force_text_diff,
5485 show_diffstat ? &dsa : NULL, repo, outfile);
5486 break;
5487 case GOT_OBJ_TYPE_TREE:
5488 error = got_diff_objects_as_trees(NULL, NULL, f1, f2, fd1, fd2,
5489 ids[0], ids[1], &paths, "", "",
5490 GOT_DIFF_ALGORITHM_PATIENCE, diff_context,
5491 ignore_whitespace, force_text_diff,
5492 show_diffstat ? &dsa : NULL, repo, outfile);
5493 break;
5494 case GOT_OBJ_TYPE_COMMIT:
5495 fprintf(outfile, "diff %s %s\n", labels[0], labels[1]);
5496 error = got_diff_objects_as_commits(NULL, NULL, f1, f2,
5497 fd1, fd2, ids[0], ids[1], &paths,
5498 GOT_DIFF_ALGORITHM_PATIENCE, diff_context,
5499 ignore_whitespace, force_text_diff,
5500 show_diffstat ? &dsa : NULL, repo, outfile);
5501 break;
5502 default:
5503 error = got_error(GOT_ERR_OBJ_TYPE);
5505 if (error)
5506 goto done;
5508 if (show_diffstat && dsa.nfiles > 0) {
5509 char *header = NULL;
5511 if (asprintf(&header, "diffstat %s %s",
5512 labels[0], labels[1]) == -1) {
5513 error = got_error_from_errno("asprintf");
5514 goto done;
5517 error = print_diffstat(&dsa, header);
5518 free(header);
5519 if (error)
5520 goto done;
5523 error = printfile(outfile);
5525 done:
5526 free(labels[0]);
5527 free(labels[1]);
5528 free(ids[0]);
5529 free(ids[1]);
5530 if (worktree)
5531 got_worktree_close(worktree);
5532 if (repo) {
5533 const struct got_error *close_err = got_repo_close(repo);
5534 if (error == NULL)
5535 error = close_err;
5537 if (pack_fds) {
5538 const struct got_error *pack_err =
5539 got_repo_pack_fds_close(pack_fds);
5540 if (error == NULL)
5541 error = pack_err;
5543 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
5544 got_pathlist_free(&diffstat_paths, GOT_PATHLIST_FREE_ALL);
5545 got_ref_list_free(&refs);
5546 if (outfile && fclose(outfile) == EOF && error == NULL)
5547 error = got_error_from_errno("fclose");
5548 if (f1 && fclose(f1) == EOF && error == NULL)
5549 error = got_error_from_errno("fclose");
5550 if (f2 && fclose(f2) == EOF && error == NULL)
5551 error = got_error_from_errno("fclose");
5552 if (fd1 != -1 && close(fd1) == -1 && error == NULL)
5553 error = got_error_from_errno("close");
5554 if (fd2 != -1 && close(fd2) == -1 && error == NULL)
5555 error = got_error_from_errno("close");
5556 return error;
5559 __dead static void
5560 usage_blame(void)
5562 fprintf(stderr,
5563 "usage: %s blame [-c commit] [-r repository-path] path\n",
5564 getprogname());
5565 exit(1);
5568 struct blame_line {
5569 int annotated;
5570 char *id_str;
5571 char *committer;
5572 char datebuf[11]; /* YYYY-MM-DD + NUL */
5575 struct blame_cb_args {
5576 struct blame_line *lines;
5577 int nlines;
5578 int nlines_prec;
5579 int lineno_cur;
5580 off_t *line_offsets;
5581 FILE *f;
5582 struct got_repository *repo;
5585 static const struct got_error *
5586 blame_cb(void *arg, int nlines, int lineno,
5587 struct got_commit_object *commit, struct got_object_id *id)
5589 const struct got_error *err = NULL;
5590 struct blame_cb_args *a = arg;
5591 struct blame_line *bline;
5592 char *line = NULL;
5593 size_t linesize = 0;
5594 off_t offset;
5595 struct tm tm;
5596 time_t committer_time;
5598 if (nlines != a->nlines ||
5599 (lineno != -1 && lineno < 1) || lineno > a->nlines)
5600 return got_error(GOT_ERR_RANGE);
5602 if (sigint_received)
5603 return got_error(GOT_ERR_ITER_COMPLETED);
5605 if (lineno == -1)
5606 return NULL; /* no change in this commit */
5608 /* Annotate this line. */
5609 bline = &a->lines[lineno - 1];
5610 if (bline->annotated)
5611 return NULL;
5612 err = got_object_id_str(&bline->id_str, id);
5613 if (err)
5614 return err;
5616 bline->committer = strdup(got_object_commit_get_committer(commit));
5617 if (bline->committer == NULL) {
5618 err = got_error_from_errno("strdup");
5619 goto done;
5622 committer_time = got_object_commit_get_committer_time(commit);
5623 if (gmtime_r(&committer_time, &tm) == NULL)
5624 return got_error_from_errno("gmtime_r");
5625 if (strftime(bline->datebuf, sizeof(bline->datebuf), "%G-%m-%d",
5626 &tm) == 0) {
5627 err = got_error(GOT_ERR_NO_SPACE);
5628 goto done;
5630 bline->annotated = 1;
5632 /* Print lines annotated so far. */
5633 bline = &a->lines[a->lineno_cur - 1];
5634 if (!bline->annotated)
5635 goto done;
5637 offset = a->line_offsets[a->lineno_cur - 1];
5638 if (fseeko(a->f, offset, SEEK_SET) == -1) {
5639 err = got_error_from_errno("fseeko");
5640 goto done;
5643 while (a->lineno_cur <= a->nlines && bline->annotated) {
5644 char *smallerthan, *at, *nl, *committer;
5645 size_t len;
5647 if (getline(&line, &linesize, a->f) == -1) {
5648 if (ferror(a->f))
5649 err = got_error_from_errno("getline");
5650 break;
5653 committer = bline->committer;
5654 smallerthan = strchr(committer, '<');
5655 if (smallerthan && smallerthan[1] != '\0')
5656 committer = smallerthan + 1;
5657 at = strchr(committer, '@');
5658 if (at)
5659 *at = '\0';
5660 len = strlen(committer);
5661 if (len >= 9)
5662 committer[8] = '\0';
5664 nl = strchr(line, '\n');
5665 if (nl)
5666 *nl = '\0';
5667 printf("%.*d) %.8s %s %-8s %s\n", a->nlines_prec, a->lineno_cur,
5668 bline->id_str, bline->datebuf, committer, line);
5670 a->lineno_cur++;
5671 bline = &a->lines[a->lineno_cur - 1];
5673 done:
5674 free(line);
5675 return err;
5678 static const struct got_error *
5679 cmd_blame(int argc, char *argv[])
5681 const struct got_error *error;
5682 struct got_repository *repo = NULL;
5683 struct got_worktree *worktree = NULL;
5684 char *path, *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
5685 char *link_target = NULL;
5686 struct got_object_id *obj_id = NULL;
5687 struct got_object_id *commit_id = NULL;
5688 struct got_commit_object *commit = NULL;
5689 struct got_blob_object *blob = NULL;
5690 char *commit_id_str = NULL;
5691 struct blame_cb_args bca;
5692 int ch, obj_type, i, fd1 = -1, fd2 = -1, fd3 = -1;
5693 off_t filesize;
5694 int *pack_fds = NULL;
5695 FILE *f1 = NULL, *f2 = NULL;
5697 fd1 = got_opentempfd();
5698 if (fd1 == -1)
5699 return got_error_from_errno("got_opentempfd");
5701 memset(&bca, 0, sizeof(bca));
5703 #ifndef PROFILE
5704 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
5705 NULL) == -1)
5706 err(1, "pledge");
5707 #endif
5709 while ((ch = getopt(argc, argv, "c:r:")) != -1) {
5710 switch (ch) {
5711 case 'c':
5712 commit_id_str = optarg;
5713 break;
5714 case 'r':
5715 repo_path = realpath(optarg, NULL);
5716 if (repo_path == NULL)
5717 return got_error_from_errno2("realpath",
5718 optarg);
5719 got_path_strip_trailing_slashes(repo_path);
5720 break;
5721 default:
5722 usage_blame();
5723 /* NOTREACHED */
5727 argc -= optind;
5728 argv += optind;
5730 if (argc == 1)
5731 path = argv[0];
5732 else
5733 usage_blame();
5735 cwd = getcwd(NULL, 0);
5736 if (cwd == NULL) {
5737 error = got_error_from_errno("getcwd");
5738 goto done;
5741 error = got_repo_pack_fds_open(&pack_fds);
5742 if (error != NULL)
5743 goto done;
5745 if (repo_path == NULL) {
5746 error = got_worktree_open(&worktree, cwd);
5747 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5748 goto done;
5749 else
5750 error = NULL;
5751 if (worktree) {
5752 repo_path =
5753 strdup(got_worktree_get_repo_path(worktree));
5754 if (repo_path == NULL) {
5755 error = got_error_from_errno("strdup");
5756 if (error)
5757 goto done;
5759 } else {
5760 repo_path = strdup(cwd);
5761 if (repo_path == NULL) {
5762 error = got_error_from_errno("strdup");
5763 goto done;
5768 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
5769 if (error != NULL)
5770 goto done;
5772 if (worktree) {
5773 const char *prefix = got_worktree_get_path_prefix(worktree);
5774 char *p;
5776 error = got_worktree_resolve_path(&p, worktree, path);
5777 if (error)
5778 goto done;
5779 if (asprintf(&in_repo_path, "%s%s%s", prefix,
5780 (p[0] != '\0' && !got_path_is_root_dir(prefix)) ? "/" : "",
5781 p) == -1) {
5782 error = got_error_from_errno("asprintf");
5783 free(p);
5784 goto done;
5786 free(p);
5787 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5788 } else {
5789 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5790 if (error)
5791 goto done;
5792 error = got_repo_map_path(&in_repo_path, repo, path);
5794 if (error)
5795 goto done;
5797 if (commit_id_str == NULL) {
5798 struct got_reference *head_ref;
5799 error = got_ref_open(&head_ref, repo, worktree ?
5800 got_worktree_get_head_ref_name(worktree) : GOT_REF_HEAD, 0);
5801 if (error != NULL)
5802 goto done;
5803 error = got_ref_resolve(&commit_id, repo, head_ref);
5804 got_ref_close(head_ref);
5805 if (error != NULL)
5806 goto done;
5807 } else {
5808 struct got_reflist_head refs;
5809 TAILQ_INIT(&refs);
5810 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
5811 NULL);
5812 if (error)
5813 goto done;
5814 error = got_repo_match_object_id(&commit_id, NULL,
5815 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
5816 got_ref_list_free(&refs);
5817 if (error)
5818 goto done;
5821 if (worktree) {
5822 /* Release work tree lock. */
5823 got_worktree_close(worktree);
5824 worktree = NULL;
5827 error = got_object_open_as_commit(&commit, repo, commit_id);
5828 if (error)
5829 goto done;
5831 error = got_object_resolve_symlinks(&link_target, in_repo_path,
5832 commit, repo);
5833 if (error)
5834 goto done;
5836 error = got_object_id_by_path(&obj_id, repo, commit,
5837 link_target ? link_target : in_repo_path);
5838 if (error)
5839 goto done;
5841 error = got_object_get_type(&obj_type, repo, obj_id);
5842 if (error)
5843 goto done;
5845 if (obj_type != GOT_OBJ_TYPE_BLOB) {
5846 error = got_error_path(link_target ? link_target : in_repo_path,
5847 GOT_ERR_OBJ_TYPE);
5848 goto done;
5851 error = got_object_open_as_blob(&blob, repo, obj_id, 8192, fd1);
5852 if (error)
5853 goto done;
5854 bca.f = got_opentemp();
5855 if (bca.f == NULL) {
5856 error = got_error_from_errno("got_opentemp");
5857 goto done;
5859 error = got_object_blob_dump_to_file(&filesize, &bca.nlines,
5860 &bca.line_offsets, bca.f, blob);
5861 if (error || bca.nlines == 0)
5862 goto done;
5864 /* Don't include \n at EOF in the blame line count. */
5865 if (bca.line_offsets[bca.nlines - 1] == filesize)
5866 bca.nlines--;
5868 bca.lines = calloc(bca.nlines, sizeof(*bca.lines));
5869 if (bca.lines == NULL) {
5870 error = got_error_from_errno("calloc");
5871 goto done;
5873 bca.lineno_cur = 1;
5874 bca.nlines_prec = 0;
5875 i = bca.nlines;
5876 while (i > 0) {
5877 i /= 10;
5878 bca.nlines_prec++;
5880 bca.repo = repo;
5882 fd2 = got_opentempfd();
5883 if (fd2 == -1) {
5884 error = got_error_from_errno("got_opentempfd");
5885 goto done;
5887 fd3 = got_opentempfd();
5888 if (fd3 == -1) {
5889 error = got_error_from_errno("got_opentempfd");
5890 goto done;
5892 f1 = got_opentemp();
5893 if (f1 == NULL) {
5894 error = got_error_from_errno("got_opentemp");
5895 goto done;
5897 f2 = got_opentemp();
5898 if (f2 == NULL) {
5899 error = got_error_from_errno("got_opentemp");
5900 goto done;
5902 error = got_blame(link_target ? link_target : in_repo_path, commit_id,
5903 repo, GOT_DIFF_ALGORITHM_PATIENCE, blame_cb, &bca,
5904 check_cancelled, NULL, fd2, fd3, f1, f2);
5905 done:
5906 free(in_repo_path);
5907 free(link_target);
5908 free(repo_path);
5909 free(cwd);
5910 free(commit_id);
5911 free(obj_id);
5912 if (commit)
5913 got_object_commit_close(commit);
5915 if (fd1 != -1 && close(fd1) == -1 && error == NULL)
5916 error = got_error_from_errno("close");
5917 if (fd2 != -1 && close(fd2) == -1 && error == NULL)
5918 error = got_error_from_errno("close");
5919 if (fd3 != -1 && close(fd3) == -1 && error == NULL)
5920 error = got_error_from_errno("close");
5921 if (f1 && fclose(f1) == EOF && error == NULL)
5922 error = got_error_from_errno("fclose");
5923 if (f2 && fclose(f2) == EOF && error == NULL)
5924 error = got_error_from_errno("fclose");
5926 if (blob)
5927 got_object_blob_close(blob);
5928 if (worktree)
5929 got_worktree_close(worktree);
5930 if (repo) {
5931 const struct got_error *close_err = got_repo_close(repo);
5932 if (error == NULL)
5933 error = close_err;
5935 if (pack_fds) {
5936 const struct got_error *pack_err =
5937 got_repo_pack_fds_close(pack_fds);
5938 if (error == NULL)
5939 error = pack_err;
5941 if (bca.lines) {
5942 for (i = 0; i < bca.nlines; i++) {
5943 struct blame_line *bline = &bca.lines[i];
5944 free(bline->id_str);
5945 free(bline->committer);
5947 free(bca.lines);
5949 free(bca.line_offsets);
5950 if (bca.f && fclose(bca.f) == EOF && error == NULL)
5951 error = got_error_from_errno("fclose");
5952 return error;
5955 __dead static void
5956 usage_tree(void)
5958 fprintf(stderr, "usage: %s tree [-iR] [-c commit] [-r repository-path] "
5959 "[path]\n", getprogname());
5960 exit(1);
5963 static const struct got_error *
5964 print_entry(struct got_tree_entry *te, const char *id, const char *path,
5965 const char *root_path, struct got_repository *repo)
5967 const struct got_error *err = NULL;
5968 int is_root_path = (strcmp(path, root_path) == 0);
5969 const char *modestr = "";
5970 mode_t mode = got_tree_entry_get_mode(te);
5971 char *link_target = NULL;
5973 path += strlen(root_path);
5974 while (path[0] == '/')
5975 path++;
5977 if (got_object_tree_entry_is_submodule(te))
5978 modestr = "$";
5979 else if (S_ISLNK(mode)) {
5980 int i;
5982 err = got_tree_entry_get_symlink_target(&link_target, te, repo);
5983 if (err)
5984 return err;
5985 for (i = 0; i < strlen(link_target); i++) {
5986 if (!isprint((unsigned char)link_target[i]))
5987 link_target[i] = '?';
5990 modestr = "@";
5992 else if (S_ISDIR(mode))
5993 modestr = "/";
5994 else if (mode & S_IXUSR)
5995 modestr = "*";
5997 printf("%s%s%s%s%s%s%s\n", id ? id : "", path,
5998 is_root_path ? "" : "/", got_tree_entry_get_name(te), modestr,
5999 link_target ? " -> ": "", link_target ? link_target : "");
6001 free(link_target);
6002 return NULL;
6005 static const struct got_error *
6006 print_tree(const char *path, struct got_commit_object *commit,
6007 int show_ids, int recurse, const char *root_path,
6008 struct got_repository *repo)
6010 const struct got_error *err = NULL;
6011 struct got_object_id *tree_id = NULL;
6012 struct got_tree_object *tree = NULL;
6013 int nentries, i;
6015 err = got_object_id_by_path(&tree_id, repo, commit, path);
6016 if (err)
6017 goto done;
6019 err = got_object_open_as_tree(&tree, repo, tree_id);
6020 if (err)
6021 goto done;
6022 nentries = got_object_tree_get_nentries(tree);
6023 for (i = 0; i < nentries; i++) {
6024 struct got_tree_entry *te;
6025 char *id = NULL;
6027 if (sigint_received || sigpipe_received)
6028 break;
6030 te = got_object_tree_get_entry(tree, i);
6031 if (show_ids) {
6032 char *id_str;
6033 err = got_object_id_str(&id_str,
6034 got_tree_entry_get_id(te));
6035 if (err)
6036 goto done;
6037 if (asprintf(&id, "%s ", id_str) == -1) {
6038 err = got_error_from_errno("asprintf");
6039 free(id_str);
6040 goto done;
6042 free(id_str);
6044 err = print_entry(te, id, path, root_path, repo);
6045 free(id);
6046 if (err)
6047 goto done;
6049 if (recurse && S_ISDIR(got_tree_entry_get_mode(te))) {
6050 char *child_path;
6051 if (asprintf(&child_path, "%s%s%s", path,
6052 path[0] == '/' && path[1] == '\0' ? "" : "/",
6053 got_tree_entry_get_name(te)) == -1) {
6054 err = got_error_from_errno("asprintf");
6055 goto done;
6057 err = print_tree(child_path, commit, show_ids, 1,
6058 root_path, repo);
6059 free(child_path);
6060 if (err)
6061 goto done;
6064 done:
6065 if (tree)
6066 got_object_tree_close(tree);
6067 free(tree_id);
6068 return err;
6071 static const struct got_error *
6072 cmd_tree(int argc, char *argv[])
6074 const struct got_error *error;
6075 struct got_repository *repo = NULL;
6076 struct got_worktree *worktree = NULL;
6077 const char *path, *refname = NULL;
6078 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
6079 struct got_object_id *commit_id = NULL;
6080 struct got_commit_object *commit = NULL;
6081 char *commit_id_str = NULL;
6082 int show_ids = 0, recurse = 0;
6083 int ch;
6084 int *pack_fds = NULL;
6086 #ifndef PROFILE
6087 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
6088 NULL) == -1)
6089 err(1, "pledge");
6090 #endif
6092 while ((ch = getopt(argc, argv, "c:iRr:")) != -1) {
6093 switch (ch) {
6094 case 'c':
6095 commit_id_str = optarg;
6096 break;
6097 case 'i':
6098 show_ids = 1;
6099 break;
6100 case 'R':
6101 recurse = 1;
6102 break;
6103 case 'r':
6104 repo_path = realpath(optarg, NULL);
6105 if (repo_path == NULL)
6106 return got_error_from_errno2("realpath",
6107 optarg);
6108 got_path_strip_trailing_slashes(repo_path);
6109 break;
6110 default:
6111 usage_tree();
6112 /* NOTREACHED */
6116 argc -= optind;
6117 argv += optind;
6119 if (argc == 1)
6120 path = argv[0];
6121 else if (argc > 1)
6122 usage_tree();
6123 else
6124 path = NULL;
6126 cwd = getcwd(NULL, 0);
6127 if (cwd == NULL) {
6128 error = got_error_from_errno("getcwd");
6129 goto done;
6132 error = got_repo_pack_fds_open(&pack_fds);
6133 if (error != NULL)
6134 goto done;
6136 if (repo_path == NULL) {
6137 error = got_worktree_open(&worktree, cwd);
6138 if (error && error->code != GOT_ERR_NOT_WORKTREE)
6139 goto done;
6140 else
6141 error = NULL;
6142 if (worktree) {
6143 repo_path =
6144 strdup(got_worktree_get_repo_path(worktree));
6145 if (repo_path == NULL)
6146 error = got_error_from_errno("strdup");
6147 if (error)
6148 goto done;
6149 } else {
6150 repo_path = strdup(cwd);
6151 if (repo_path == NULL) {
6152 error = got_error_from_errno("strdup");
6153 goto done;
6158 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
6159 if (error != NULL)
6160 goto done;
6162 if (worktree) {
6163 const char *prefix = got_worktree_get_path_prefix(worktree);
6164 char *p;
6166 if (path == NULL)
6167 path = "";
6168 error = got_worktree_resolve_path(&p, worktree, path);
6169 if (error)
6170 goto done;
6171 if (asprintf(&in_repo_path, "%s%s%s", prefix,
6172 (p[0] != '\0' && !got_path_is_root_dir(prefix)) ? "/" : "",
6173 p) == -1) {
6174 error = got_error_from_errno("asprintf");
6175 free(p);
6176 goto done;
6178 free(p);
6179 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
6180 if (error)
6181 goto done;
6182 } else {
6183 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
6184 if (error)
6185 goto done;
6186 if (path == NULL)
6187 path = "/";
6188 error = got_repo_map_path(&in_repo_path, repo, path);
6189 if (error != NULL)
6190 goto done;
6193 if (commit_id_str == NULL) {
6194 struct got_reference *head_ref;
6195 if (worktree)
6196 refname = got_worktree_get_head_ref_name(worktree);
6197 else
6198 refname = GOT_REF_HEAD;
6199 error = got_ref_open(&head_ref, repo, refname, 0);
6200 if (error != NULL)
6201 goto done;
6202 error = got_ref_resolve(&commit_id, repo, head_ref);
6203 got_ref_close(head_ref);
6204 if (error != NULL)
6205 goto done;
6206 } else {
6207 struct got_reflist_head refs;
6208 TAILQ_INIT(&refs);
6209 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
6210 NULL);
6211 if (error)
6212 goto done;
6213 error = got_repo_match_object_id(&commit_id, NULL,
6214 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
6215 got_ref_list_free(&refs);
6216 if (error)
6217 goto done;
6220 if (worktree) {
6221 /* Release work tree lock. */
6222 got_worktree_close(worktree);
6223 worktree = NULL;
6226 error = got_object_open_as_commit(&commit, repo, commit_id);
6227 if (error)
6228 goto done;
6230 error = print_tree(in_repo_path, commit, show_ids, recurse,
6231 in_repo_path, repo);
6232 done:
6233 free(in_repo_path);
6234 free(repo_path);
6235 free(cwd);
6236 free(commit_id);
6237 if (commit)
6238 got_object_commit_close(commit);
6239 if (worktree)
6240 got_worktree_close(worktree);
6241 if (repo) {
6242 const struct got_error *close_err = got_repo_close(repo);
6243 if (error == NULL)
6244 error = close_err;
6246 if (pack_fds) {
6247 const struct got_error *pack_err =
6248 got_repo_pack_fds_close(pack_fds);
6249 if (error == NULL)
6250 error = pack_err;
6252 return error;
6255 __dead static void
6256 usage_status(void)
6258 fprintf(stderr, "usage: %s status [-I] [-S status-codes] "
6259 "[-s status-codes] [path ...]\n", getprogname());
6260 exit(1);
6263 struct got_status_arg {
6264 char *status_codes;
6265 int suppress;
6268 static const struct got_error *
6269 print_status(void *arg, unsigned char status, unsigned char staged_status,
6270 const char *path, struct got_object_id *blob_id,
6271 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
6272 int dirfd, const char *de_name)
6274 struct got_status_arg *st = arg;
6276 if (status == staged_status && (status == GOT_STATUS_DELETE))
6277 status = GOT_STATUS_NO_CHANGE;
6278 if (st != NULL && st->status_codes) {
6279 size_t ncodes = strlen(st->status_codes);
6280 int i, j = 0;
6282 for (i = 0; i < ncodes ; i++) {
6283 if (st->suppress) {
6284 if (status == st->status_codes[i] ||
6285 staged_status == st->status_codes[i]) {
6286 j++;
6287 continue;
6289 } else {
6290 if (status == st->status_codes[i] ||
6291 staged_status == st->status_codes[i])
6292 break;
6296 if (st->suppress && j == 0)
6297 goto print;
6299 if (i == ncodes)
6300 return NULL;
6302 print:
6303 printf("%c%c %s\n", status, staged_status, path);
6304 return NULL;
6307 static const struct got_error *
6308 cmd_status(int argc, char *argv[])
6310 const struct got_error *error = NULL;
6311 struct got_repository *repo = NULL;
6312 struct got_worktree *worktree = NULL;
6313 struct got_status_arg st;
6314 char *cwd = NULL;
6315 struct got_pathlist_head paths;
6316 int ch, i, no_ignores = 0;
6317 int *pack_fds = NULL;
6319 TAILQ_INIT(&paths);
6321 memset(&st, 0, sizeof(st));
6322 st.status_codes = NULL;
6323 st.suppress = 0;
6325 #ifndef PROFILE
6326 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
6327 NULL) == -1)
6328 err(1, "pledge");
6329 #endif
6331 while ((ch = getopt(argc, argv, "IS:s:")) != -1) {
6332 switch (ch) {
6333 case 'I':
6334 no_ignores = 1;
6335 break;
6336 case 'S':
6337 if (st.status_codes != NULL && st.suppress == 0)
6338 option_conflict('S', 's');
6339 st.suppress = 1;
6340 /* fallthrough */
6341 case 's':
6342 for (i = 0; i < strlen(optarg); i++) {
6343 switch (optarg[i]) {
6344 case GOT_STATUS_MODIFY:
6345 case GOT_STATUS_ADD:
6346 case GOT_STATUS_DELETE:
6347 case GOT_STATUS_CONFLICT:
6348 case GOT_STATUS_MISSING:
6349 case GOT_STATUS_OBSTRUCTED:
6350 case GOT_STATUS_UNVERSIONED:
6351 case GOT_STATUS_MODE_CHANGE:
6352 case GOT_STATUS_NONEXISTENT:
6353 break;
6354 default:
6355 errx(1, "invalid status code '%c'",
6356 optarg[i]);
6359 if (ch == 's' && st.suppress)
6360 option_conflict('s', 'S');
6361 st.status_codes = optarg;
6362 break;
6363 default:
6364 usage_status();
6365 /* NOTREACHED */
6369 argc -= optind;
6370 argv += optind;
6372 cwd = getcwd(NULL, 0);
6373 if (cwd == NULL) {
6374 error = got_error_from_errno("getcwd");
6375 goto done;
6378 error = got_repo_pack_fds_open(&pack_fds);
6379 if (error != NULL)
6380 goto done;
6382 error = got_worktree_open(&worktree, cwd);
6383 if (error) {
6384 if (error->code == GOT_ERR_NOT_WORKTREE)
6385 error = wrap_not_worktree_error(error, "status", cwd);
6386 goto done;
6389 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
6390 NULL, pack_fds);
6391 if (error != NULL)
6392 goto done;
6394 error = apply_unveil(got_repo_get_path(repo), 1,
6395 got_worktree_get_root_path(worktree));
6396 if (error)
6397 goto done;
6399 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
6400 if (error)
6401 goto done;
6403 error = got_worktree_status(worktree, &paths, repo, no_ignores,
6404 print_status, &st, check_cancelled, NULL);
6405 done:
6406 if (pack_fds) {
6407 const struct got_error *pack_err =
6408 got_repo_pack_fds_close(pack_fds);
6409 if (error == NULL)
6410 error = pack_err;
6412 if (repo) {
6413 const struct got_error *close_err = got_repo_close(repo);
6414 if (error == NULL)
6415 error = close_err;
6418 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
6419 free(cwd);
6420 return error;
6423 __dead static void
6424 usage_ref(void)
6426 fprintf(stderr, "usage: %s ref [-dlt] [-c object] [-r repository-path] "
6427 "[-s reference] [name]\n", getprogname());
6428 exit(1);
6431 static const struct got_error *
6432 list_refs(struct got_repository *repo, const char *refname, int sort_by_time)
6434 static const struct got_error *err = NULL;
6435 struct got_reflist_head refs;
6436 struct got_reflist_entry *re;
6438 TAILQ_INIT(&refs);
6439 err = got_ref_list(&refs, repo, refname, sort_by_time ?
6440 got_ref_cmp_by_commit_timestamp_descending : got_ref_cmp_by_name,
6441 repo);
6442 if (err)
6443 return err;
6445 TAILQ_FOREACH(re, &refs, entry) {
6446 char *refstr;
6447 refstr = got_ref_to_str(re->ref);
6448 if (refstr == NULL) {
6449 err = got_error_from_errno("got_ref_to_str");
6450 break;
6452 printf("%s: %s\n", got_ref_get_name(re->ref), refstr);
6453 free(refstr);
6456 got_ref_list_free(&refs);
6457 return err;
6460 static const struct got_error *
6461 delete_ref_by_name(struct got_repository *repo, const char *refname)
6463 const struct got_error *err;
6464 struct got_reference *ref;
6466 err = got_ref_open(&ref, repo, refname, 0);
6467 if (err)
6468 return err;
6470 err = delete_ref(repo, ref);
6471 got_ref_close(ref);
6472 return err;
6475 static const struct got_error *
6476 add_ref(struct got_repository *repo, const char *refname, const char *target)
6478 const struct got_error *err = NULL;
6479 struct got_object_id *id = NULL;
6480 struct got_reference *ref = NULL;
6481 struct got_reflist_head refs;
6484 * Don't let the user create a reference name with a leading '-'.
6485 * While technically a valid reference name, this case is usually
6486 * an unintended typo.
6488 if (refname[0] == '-')
6489 return got_error_path(refname, GOT_ERR_REF_NAME_MINUS);
6491 TAILQ_INIT(&refs);
6492 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
6493 if (err)
6494 goto done;
6495 err = got_repo_match_object_id(&id, NULL, target, GOT_OBJ_TYPE_ANY,
6496 &refs, repo);
6497 got_ref_list_free(&refs);
6498 if (err)
6499 goto done;
6501 err = got_ref_alloc(&ref, refname, id);
6502 if (err)
6503 goto done;
6505 err = got_ref_write(ref, repo);
6506 done:
6507 if (ref)
6508 got_ref_close(ref);
6509 free(id);
6510 return err;
6513 static const struct got_error *
6514 add_symref(struct got_repository *repo, const char *refname, const char *target)
6516 const struct got_error *err = NULL;
6517 struct got_reference *ref = NULL;
6518 struct got_reference *target_ref = NULL;
6521 * Don't let the user create a reference name with a leading '-'.
6522 * While technically a valid reference name, this case is usually
6523 * an unintended typo.
6525 if (refname[0] == '-')
6526 return got_error_path(refname, GOT_ERR_REF_NAME_MINUS);
6528 err = got_ref_open(&target_ref, repo, target, 0);
6529 if (err)
6530 return err;
6532 err = got_ref_alloc_symref(&ref, refname, target_ref);
6533 if (err)
6534 goto done;
6536 err = got_ref_write(ref, repo);
6537 done:
6538 if (target_ref)
6539 got_ref_close(target_ref);
6540 if (ref)
6541 got_ref_close(ref);
6542 return err;
6545 static const struct got_error *
6546 cmd_ref(int argc, char *argv[])
6548 const struct got_error *error = NULL;
6549 struct got_repository *repo = NULL;
6550 struct got_worktree *worktree = NULL;
6551 char *cwd = NULL, *repo_path = NULL;
6552 int ch, do_list = 0, do_delete = 0, sort_by_time = 0;
6553 const char *obj_arg = NULL, *symref_target= NULL;
6554 char *refname = NULL;
6555 int *pack_fds = NULL;
6557 #ifndef PROFILE
6558 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
6559 "sendfd unveil", NULL) == -1)
6560 err(1, "pledge");
6561 #endif
6563 while ((ch = getopt(argc, argv, "c:dlr:s:t")) != -1) {
6564 switch (ch) {
6565 case 'c':
6566 obj_arg = optarg;
6567 break;
6568 case 'd':
6569 do_delete = 1;
6570 break;
6571 case 'l':
6572 do_list = 1;
6573 break;
6574 case 'r':
6575 repo_path = realpath(optarg, NULL);
6576 if (repo_path == NULL)
6577 return got_error_from_errno2("realpath",
6578 optarg);
6579 got_path_strip_trailing_slashes(repo_path);
6580 break;
6581 case 's':
6582 symref_target = optarg;
6583 break;
6584 case 't':
6585 sort_by_time = 1;
6586 break;
6587 default:
6588 usage_ref();
6589 /* NOTREACHED */
6593 if (obj_arg && do_list)
6594 option_conflict('c', 'l');
6595 if (obj_arg && do_delete)
6596 option_conflict('c', 'd');
6597 if (obj_arg && symref_target)
6598 option_conflict('c', 's');
6599 if (symref_target && do_delete)
6600 option_conflict('s', 'd');
6601 if (symref_target && do_list)
6602 option_conflict('s', 'l');
6603 if (do_delete && do_list)
6604 option_conflict('d', 'l');
6605 if (sort_by_time && !do_list)
6606 errx(1, "-t option requires -l option");
6608 argc -= optind;
6609 argv += optind;
6611 if (do_list) {
6612 if (argc != 0 && argc != 1)
6613 usage_ref();
6614 if (argc == 1) {
6615 refname = strdup(argv[0]);
6616 if (refname == NULL) {
6617 error = got_error_from_errno("strdup");
6618 goto done;
6621 } else {
6622 if (argc != 1)
6623 usage_ref();
6624 refname = strdup(argv[0]);
6625 if (refname == NULL) {
6626 error = got_error_from_errno("strdup");
6627 goto done;
6631 if (refname)
6632 got_path_strip_trailing_slashes(refname);
6634 cwd = getcwd(NULL, 0);
6635 if (cwd == NULL) {
6636 error = got_error_from_errno("getcwd");
6637 goto done;
6640 error = got_repo_pack_fds_open(&pack_fds);
6641 if (error != NULL)
6642 goto done;
6644 if (repo_path == NULL) {
6645 error = got_worktree_open(&worktree, cwd);
6646 if (error && error->code != GOT_ERR_NOT_WORKTREE)
6647 goto done;
6648 else
6649 error = NULL;
6650 if (worktree) {
6651 repo_path =
6652 strdup(got_worktree_get_repo_path(worktree));
6653 if (repo_path == NULL)
6654 error = got_error_from_errno("strdup");
6655 if (error)
6656 goto done;
6657 } else {
6658 repo_path = strdup(cwd);
6659 if (repo_path == NULL) {
6660 error = got_error_from_errno("strdup");
6661 goto done;
6666 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
6667 if (error != NULL)
6668 goto done;
6670 #ifndef PROFILE
6671 if (do_list) {
6672 /* Remove "cpath" promise. */
6673 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
6674 NULL) == -1)
6675 err(1, "pledge");
6677 #endif
6679 error = apply_unveil(got_repo_get_path(repo), do_list,
6680 worktree ? got_worktree_get_root_path(worktree) : NULL);
6681 if (error)
6682 goto done;
6684 if (do_list)
6685 error = list_refs(repo, refname, sort_by_time);
6686 else if (do_delete)
6687 error = delete_ref_by_name(repo, refname);
6688 else if (symref_target)
6689 error = add_symref(repo, refname, symref_target);
6690 else {
6691 if (obj_arg == NULL)
6692 usage_ref();
6693 error = add_ref(repo, refname, obj_arg);
6695 done:
6696 free(refname);
6697 if (repo) {
6698 const struct got_error *close_err = got_repo_close(repo);
6699 if (error == NULL)
6700 error = close_err;
6702 if (worktree)
6703 got_worktree_close(worktree);
6704 if (pack_fds) {
6705 const struct got_error *pack_err =
6706 got_repo_pack_fds_close(pack_fds);
6707 if (error == NULL)
6708 error = pack_err;
6710 free(cwd);
6711 free(repo_path);
6712 return error;
6715 __dead static void
6716 usage_branch(void)
6718 fprintf(stderr, "usage: %s branch [-lnt] [-c commit] [-d name] "
6719 "[-r repository-path] [name]\n", getprogname());
6720 exit(1);
6723 static const struct got_error *
6724 list_branch(struct got_repository *repo, struct got_worktree *worktree,
6725 struct got_reference *ref)
6727 const struct got_error *err = NULL;
6728 const char *refname, *marker = " ";
6729 char *refstr;
6731 refname = got_ref_get_name(ref);
6732 if (worktree && strcmp(refname,
6733 got_worktree_get_head_ref_name(worktree)) == 0) {
6734 struct got_object_id *id = NULL;
6736 err = got_ref_resolve(&id, repo, ref);
6737 if (err)
6738 return err;
6739 if (got_object_id_cmp(id,
6740 got_worktree_get_base_commit_id(worktree)) == 0)
6741 marker = "* ";
6742 else
6743 marker = "~ ";
6744 free(id);
6747 if (strncmp(refname, "refs/heads/", 11) == 0)
6748 refname += 11;
6749 if (strncmp(refname, "refs/got/worktree/", 18) == 0)
6750 refname += 18;
6751 if (strncmp(refname, "refs/remotes/", 13) == 0)
6752 refname += 13;
6754 refstr = got_ref_to_str(ref);
6755 if (refstr == NULL)
6756 return got_error_from_errno("got_ref_to_str");
6758 printf("%s%s: %s\n", marker, refname, refstr);
6759 free(refstr);
6760 return NULL;
6763 static const struct got_error *
6764 show_current_branch(struct got_repository *repo, struct got_worktree *worktree)
6766 const char *refname;
6768 if (worktree == NULL)
6769 return got_error(GOT_ERR_NOT_WORKTREE);
6771 refname = got_worktree_get_head_ref_name(worktree);
6773 if (strncmp(refname, "refs/heads/", 11) == 0)
6774 refname += 11;
6775 if (strncmp(refname, "refs/got/worktree/", 18) == 0)
6776 refname += 18;
6778 printf("%s\n", refname);
6780 return NULL;
6783 static const struct got_error *
6784 list_branches(struct got_repository *repo, struct got_worktree *worktree,
6785 int sort_by_time)
6787 static const struct got_error *err = NULL;
6788 struct got_reflist_head refs;
6789 struct got_reflist_entry *re;
6790 struct got_reference *temp_ref = NULL;
6791 int rebase_in_progress, histedit_in_progress;
6793 TAILQ_INIT(&refs);
6795 if (worktree) {
6796 err = got_worktree_rebase_in_progress(&rebase_in_progress,
6797 worktree);
6798 if (err)
6799 return err;
6801 err = got_worktree_histedit_in_progress(&histedit_in_progress,
6802 worktree);
6803 if (err)
6804 return err;
6806 if (rebase_in_progress || histedit_in_progress) {
6807 err = got_ref_open(&temp_ref, repo,
6808 got_worktree_get_head_ref_name(worktree), 0);
6809 if (err)
6810 return err;
6811 list_branch(repo, worktree, temp_ref);
6812 got_ref_close(temp_ref);
6816 err = got_ref_list(&refs, repo, "refs/heads", sort_by_time ?
6817 got_ref_cmp_by_commit_timestamp_descending : got_ref_cmp_by_name,
6818 repo);
6819 if (err)
6820 return err;
6822 TAILQ_FOREACH(re, &refs, entry)
6823 list_branch(repo, worktree, re->ref);
6825 got_ref_list_free(&refs);
6827 err = got_ref_list(&refs, repo, "refs/remotes", sort_by_time ?
6828 got_ref_cmp_by_commit_timestamp_descending : got_ref_cmp_by_name,
6829 repo);
6830 if (err)
6831 return err;
6833 TAILQ_FOREACH(re, &refs, entry)
6834 list_branch(repo, worktree, re->ref);
6836 got_ref_list_free(&refs);
6838 return NULL;
6841 static const struct got_error *
6842 delete_branch(struct got_repository *repo, struct got_worktree *worktree,
6843 const char *branch_name)
6845 const struct got_error *err = NULL;
6846 struct got_reference *ref = NULL;
6847 char *refname, *remote_refname = NULL;
6849 if (strncmp(branch_name, "refs/", 5) == 0)
6850 branch_name += 5;
6851 if (strncmp(branch_name, "heads/", 6) == 0)
6852 branch_name += 6;
6853 else if (strncmp(branch_name, "remotes/", 8) == 0)
6854 branch_name += 8;
6856 if (asprintf(&refname, "refs/heads/%s", branch_name) == -1)
6857 return got_error_from_errno("asprintf");
6859 if (asprintf(&remote_refname, "refs/remotes/%s",
6860 branch_name) == -1) {
6861 err = got_error_from_errno("asprintf");
6862 goto done;
6865 err = got_ref_open(&ref, repo, refname, 0);
6866 if (err) {
6867 const struct got_error *err2;
6868 if (err->code != GOT_ERR_NOT_REF)
6869 goto done;
6871 * Keep 'err' intact such that if neither branch exists
6872 * we report "refs/heads" rather than "refs/remotes" in
6873 * our error message.
6875 err2 = got_ref_open(&ref, repo, remote_refname, 0);
6876 if (err2)
6877 goto done;
6878 err = NULL;
6881 if (worktree &&
6882 strcmp(got_worktree_get_head_ref_name(worktree),
6883 got_ref_get_name(ref)) == 0) {
6884 err = got_error_msg(GOT_ERR_SAME_BRANCH,
6885 "will not delete this work tree's current branch");
6886 goto done;
6889 err = delete_ref(repo, ref);
6890 done:
6891 if (ref)
6892 got_ref_close(ref);
6893 free(refname);
6894 free(remote_refname);
6895 return err;
6898 static const struct got_error *
6899 add_branch(struct got_repository *repo, const char *branch_name,
6900 struct got_object_id *base_commit_id)
6902 const struct got_error *err = NULL;
6903 struct got_reference *ref = NULL;
6904 char *refname = NULL;
6907 * Don't let the user create a branch name with a leading '-'.
6908 * While technically a valid reference name, this case is usually
6909 * an unintended typo.
6911 if (branch_name[0] == '-')
6912 return got_error_path(branch_name, GOT_ERR_REF_NAME_MINUS);
6914 if (strncmp(branch_name, "refs/heads/", 11) == 0)
6915 branch_name += 11;
6917 if (asprintf(&refname, "refs/heads/%s", branch_name) == -1) {
6918 err = got_error_from_errno("asprintf");
6919 goto done;
6922 err = got_ref_open(&ref, repo, refname, 0);
6923 if (err == NULL) {
6924 err = got_error(GOT_ERR_BRANCH_EXISTS);
6925 goto done;
6926 } else if (err->code != GOT_ERR_NOT_REF)
6927 goto done;
6929 err = got_ref_alloc(&ref, refname, base_commit_id);
6930 if (err)
6931 goto done;
6933 err = got_ref_write(ref, repo);
6934 done:
6935 if (ref)
6936 got_ref_close(ref);
6937 free(refname);
6938 return err;
6941 static const struct got_error *
6942 cmd_branch(int argc, char *argv[])
6944 const struct got_error *error = NULL;
6945 struct got_repository *repo = NULL;
6946 struct got_worktree *worktree = NULL;
6947 char *cwd = NULL, *repo_path = NULL;
6948 int ch, do_list = 0, do_show = 0, do_update = 1, sort_by_time = 0;
6949 const char *delref = NULL, *commit_id_arg = NULL;
6950 struct got_reference *ref = NULL;
6951 struct got_pathlist_head paths;
6952 struct got_object_id *commit_id = NULL;
6953 char *commit_id_str = NULL;
6954 int *pack_fds = NULL;
6956 TAILQ_INIT(&paths);
6958 #ifndef PROFILE
6959 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
6960 "sendfd unveil", NULL) == -1)
6961 err(1, "pledge");
6962 #endif
6964 while ((ch = getopt(argc, argv, "c:d:lnr:t")) != -1) {
6965 switch (ch) {
6966 case 'c':
6967 commit_id_arg = optarg;
6968 break;
6969 case 'd':
6970 delref = optarg;
6971 break;
6972 case 'l':
6973 do_list = 1;
6974 break;
6975 case 'n':
6976 do_update = 0;
6977 break;
6978 case 'r':
6979 repo_path = realpath(optarg, NULL);
6980 if (repo_path == NULL)
6981 return got_error_from_errno2("realpath",
6982 optarg);
6983 got_path_strip_trailing_slashes(repo_path);
6984 break;
6985 case 't':
6986 sort_by_time = 1;
6987 break;
6988 default:
6989 usage_branch();
6990 /* NOTREACHED */
6994 if (do_list && delref)
6995 option_conflict('l', 'd');
6996 if (sort_by_time && !do_list)
6997 errx(1, "-t option requires -l option");
6999 argc -= optind;
7000 argv += optind;
7002 if (!do_list && !delref && argc == 0)
7003 do_show = 1;
7005 if ((do_list || delref || do_show) && commit_id_arg != NULL)
7006 errx(1, "-c option can only be used when creating a branch");
7008 if (do_list || delref) {
7009 if (argc > 0)
7010 usage_branch();
7011 } else if (!do_show && argc != 1)
7012 usage_branch();
7014 cwd = getcwd(NULL, 0);
7015 if (cwd == NULL) {
7016 error = got_error_from_errno("getcwd");
7017 goto done;
7020 error = got_repo_pack_fds_open(&pack_fds);
7021 if (error != NULL)
7022 goto done;
7024 if (repo_path == NULL) {
7025 error = got_worktree_open(&worktree, cwd);
7026 if (error && error->code != GOT_ERR_NOT_WORKTREE)
7027 goto done;
7028 else
7029 error = NULL;
7030 if (worktree) {
7031 repo_path =
7032 strdup(got_worktree_get_repo_path(worktree));
7033 if (repo_path == NULL)
7034 error = got_error_from_errno("strdup");
7035 if (error)
7036 goto done;
7037 } else {
7038 repo_path = strdup(cwd);
7039 if (repo_path == NULL) {
7040 error = got_error_from_errno("strdup");
7041 goto done;
7046 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
7047 if (error != NULL)
7048 goto done;
7050 #ifndef PROFILE
7051 if (do_list || do_show) {
7052 /* Remove "cpath" promise. */
7053 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
7054 NULL) == -1)
7055 err(1, "pledge");
7057 #endif
7059 error = apply_unveil(got_repo_get_path(repo), do_list,
7060 worktree ? got_worktree_get_root_path(worktree) : NULL);
7061 if (error)
7062 goto done;
7064 if (do_show)
7065 error = show_current_branch(repo, worktree);
7066 else if (do_list)
7067 error = list_branches(repo, worktree, sort_by_time);
7068 else if (delref)
7069 error = delete_branch(repo, worktree, delref);
7070 else {
7071 struct got_reflist_head refs;
7072 TAILQ_INIT(&refs);
7073 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
7074 NULL);
7075 if (error)
7076 goto done;
7077 if (commit_id_arg == NULL)
7078 commit_id_arg = worktree ?
7079 got_worktree_get_head_ref_name(worktree) :
7080 GOT_REF_HEAD;
7081 error = got_repo_match_object_id(&commit_id, NULL,
7082 commit_id_arg, GOT_OBJ_TYPE_COMMIT, &refs, repo);
7083 got_ref_list_free(&refs);
7084 if (error)
7085 goto done;
7086 error = add_branch(repo, argv[0], commit_id);
7087 if (error)
7088 goto done;
7089 if (worktree && do_update) {
7090 struct got_update_progress_arg upa;
7091 char *branch_refname = NULL;
7093 error = got_object_id_str(&commit_id_str, commit_id);
7094 if (error)
7095 goto done;
7096 error = get_worktree_paths_from_argv(&paths, 0, NULL,
7097 worktree);
7098 if (error)
7099 goto done;
7100 if (asprintf(&branch_refname, "refs/heads/%s", argv[0])
7101 == -1) {
7102 error = got_error_from_errno("asprintf");
7103 goto done;
7105 error = got_ref_open(&ref, repo, branch_refname, 0);
7106 free(branch_refname);
7107 if (error)
7108 goto done;
7109 error = switch_head_ref(ref, commit_id, worktree,
7110 repo);
7111 if (error)
7112 goto done;
7113 error = got_worktree_set_base_commit_id(worktree, repo,
7114 commit_id);
7115 if (error)
7116 goto done;
7117 memset(&upa, 0, sizeof(upa));
7118 error = got_worktree_checkout_files(worktree, &paths,
7119 repo, update_progress, &upa, check_cancelled,
7120 NULL);
7121 if (error)
7122 goto done;
7123 if (upa.did_something) {
7124 printf("Updated to %s: %s\n",
7125 got_worktree_get_head_ref_name(worktree),
7126 commit_id_str);
7128 print_update_progress_stats(&upa);
7131 done:
7132 if (ref)
7133 got_ref_close(ref);
7134 if (repo) {
7135 const struct got_error *close_err = got_repo_close(repo);
7136 if (error == NULL)
7137 error = close_err;
7139 if (worktree)
7140 got_worktree_close(worktree);
7141 if (pack_fds) {
7142 const struct got_error *pack_err =
7143 got_repo_pack_fds_close(pack_fds);
7144 if (error == NULL)
7145 error = pack_err;
7147 free(cwd);
7148 free(repo_path);
7149 free(commit_id);
7150 free(commit_id_str);
7151 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
7152 return error;
7156 __dead static void
7157 usage_tag(void)
7159 fprintf(stderr, "usage: %s tag [-lVv] [-c commit] [-m message] "
7160 "[-r repository-path] [-s signer-id] name\n", getprogname());
7161 exit(1);
7164 #if 0
7165 static const struct got_error *
7166 sort_tags(struct got_reflist_head *sorted, struct got_reflist_head *tags)
7168 const struct got_error *err = NULL;
7169 struct got_reflist_entry *re, *se, *new;
7170 struct got_object_id *re_id, *se_id;
7171 struct got_tag_object *re_tag, *se_tag;
7172 time_t re_time, se_time;
7174 STAILQ_FOREACH(re, tags, entry) {
7175 se = STAILQ_FIRST(sorted);
7176 if (se == NULL) {
7177 err = got_reflist_entry_dup(&new, re);
7178 if (err)
7179 return err;
7180 STAILQ_INSERT_HEAD(sorted, new, entry);
7181 continue;
7182 } else {
7183 err = got_ref_resolve(&re_id, repo, re->ref);
7184 if (err)
7185 break;
7186 err = got_object_open_as_tag(&re_tag, repo, re_id);
7187 free(re_id);
7188 if (err)
7189 break;
7190 re_time = got_object_tag_get_tagger_time(re_tag);
7191 got_object_tag_close(re_tag);
7194 while (se) {
7195 err = got_ref_resolve(&se_id, repo, re->ref);
7196 if (err)
7197 break;
7198 err = got_object_open_as_tag(&se_tag, repo, se_id);
7199 free(se_id);
7200 if (err)
7201 break;
7202 se_time = got_object_tag_get_tagger_time(se_tag);
7203 got_object_tag_close(se_tag);
7205 if (se_time > re_time) {
7206 err = got_reflist_entry_dup(&new, re);
7207 if (err)
7208 return err;
7209 STAILQ_INSERT_AFTER(sorted, se, new, entry);
7210 break;
7212 se = STAILQ_NEXT(se, entry);
7213 continue;
7216 done:
7217 return err;
7219 #endif
7221 static const struct got_error *
7222 get_tag_refname(char **refname, const char *tag_name)
7224 const struct got_error *err;
7226 if (strncmp("refs/tags/", tag_name, 10) == 0) {
7227 *refname = strdup(tag_name);
7228 if (*refname == NULL)
7229 return got_error_from_errno("strdup");
7230 } else if (asprintf(refname, "refs/tags/%s", tag_name) == -1) {
7231 err = got_error_from_errno("asprintf");
7232 *refname = NULL;
7233 return err;
7236 return NULL;
7239 static const struct got_error *
7240 list_tags(struct got_repository *repo, const char *tag_name, int verify_tags,
7241 const char *allowed_signers, const char *revoked_signers, int verbosity)
7243 static const struct got_error *err = NULL;
7244 struct got_reflist_head refs;
7245 struct got_reflist_entry *re;
7246 char *wanted_refname = NULL;
7247 int bad_sigs = 0;
7249 TAILQ_INIT(&refs);
7251 err = got_ref_list(&refs, repo, "refs/tags", got_ref_cmp_tags, repo);
7252 if (err)
7253 return err;
7255 if (tag_name) {
7256 struct got_reference *ref;
7257 err = get_tag_refname(&wanted_refname, tag_name);
7258 if (err)
7259 goto done;
7260 /* Wanted tag reference should exist. */
7261 err = got_ref_open(&ref, repo, wanted_refname, 0);
7262 if (err)
7263 goto done;
7264 got_ref_close(ref);
7267 TAILQ_FOREACH(re, &refs, entry) {
7268 const char *refname;
7269 char *refstr, *tagmsg0, *tagmsg, *line, *id_str, *datestr;
7270 char datebuf[26];
7271 const char *tagger, *ssh_sig = NULL;
7272 char *sig_msg = NULL;
7273 time_t tagger_time;
7274 struct got_object_id *id;
7275 struct got_tag_object *tag;
7276 struct got_commit_object *commit = NULL;
7278 refname = got_ref_get_name(re->ref);
7279 if (strncmp(refname, "refs/tags/", 10) != 0 ||
7280 (wanted_refname && strcmp(refname, wanted_refname) != 0))
7281 continue;
7282 refname += 10;
7283 refstr = got_ref_to_str(re->ref);
7284 if (refstr == NULL) {
7285 err = got_error_from_errno("got_ref_to_str");
7286 break;
7289 err = got_ref_resolve(&id, repo, re->ref);
7290 if (err)
7291 break;
7292 err = got_object_open_as_tag(&tag, repo, id);
7293 if (err) {
7294 if (err->code != GOT_ERR_OBJ_TYPE) {
7295 free(id);
7296 break;
7298 /* "lightweight" tag */
7299 err = got_object_open_as_commit(&commit, repo, id);
7300 if (err) {
7301 free(id);
7302 break;
7304 tagger = got_object_commit_get_committer(commit);
7305 tagger_time =
7306 got_object_commit_get_committer_time(commit);
7307 err = got_object_id_str(&id_str, id);
7308 free(id);
7309 if (err)
7310 break;
7311 } else {
7312 free(id);
7313 tagger = got_object_tag_get_tagger(tag);
7314 tagger_time = got_object_tag_get_tagger_time(tag);
7315 err = got_object_id_str(&id_str,
7316 got_object_tag_get_object_id(tag));
7317 if (err)
7318 break;
7321 if (tag && verify_tags) {
7322 ssh_sig = got_sigs_get_tagmsg_ssh_signature(
7323 got_object_tag_get_message(tag));
7324 if (ssh_sig && allowed_signers == NULL) {
7325 err = got_error_msg(
7326 GOT_ERR_VERIFY_TAG_SIGNATURE,
7327 "SSH signature verification requires "
7328 "setting allowed_signers in "
7329 "got.conf(5)");
7330 break;
7334 printf("%stag %s %s\n", GOT_COMMIT_SEP_STR, refname, refstr);
7335 free(refstr);
7336 printf("from: %s\n", tagger);
7337 datestr = get_datestr(&tagger_time, datebuf);
7338 if (datestr)
7339 printf("date: %s UTC\n", datestr);
7340 if (commit)
7341 printf("object: %s %s\n", GOT_OBJ_LABEL_COMMIT, id_str);
7342 else {
7343 switch (got_object_tag_get_object_type(tag)) {
7344 case GOT_OBJ_TYPE_BLOB:
7345 printf("object: %s %s\n", GOT_OBJ_LABEL_BLOB,
7346 id_str);
7347 break;
7348 case GOT_OBJ_TYPE_TREE:
7349 printf("object: %s %s\n", GOT_OBJ_LABEL_TREE,
7350 id_str);
7351 break;
7352 case GOT_OBJ_TYPE_COMMIT:
7353 printf("object: %s %s\n", GOT_OBJ_LABEL_COMMIT,
7354 id_str);
7355 break;
7356 case GOT_OBJ_TYPE_TAG:
7357 printf("object: %s %s\n", GOT_OBJ_LABEL_TAG,
7358 id_str);
7359 break;
7360 default:
7361 break;
7364 free(id_str);
7366 if (ssh_sig) {
7367 err = got_sigs_verify_tag_ssh(&sig_msg, tag, ssh_sig,
7368 allowed_signers, revoked_signers, verbosity);
7369 if (err && err->code == GOT_ERR_BAD_TAG_SIGNATURE)
7370 bad_sigs = 1;
7371 else if (err)
7372 break;
7373 printf("signature: %s", sig_msg);
7374 free(sig_msg);
7375 sig_msg = NULL;
7378 if (commit) {
7379 err = got_object_commit_get_logmsg(&tagmsg0, commit);
7380 if (err)
7381 break;
7382 got_object_commit_close(commit);
7383 } else {
7384 tagmsg0 = strdup(got_object_tag_get_message(tag));
7385 got_object_tag_close(tag);
7386 if (tagmsg0 == NULL) {
7387 err = got_error_from_errno("strdup");
7388 break;
7392 tagmsg = tagmsg0;
7393 do {
7394 line = strsep(&tagmsg, "\n");
7395 if (line)
7396 printf(" %s\n", line);
7397 } while (line);
7398 free(tagmsg0);
7400 done:
7401 got_ref_list_free(&refs);
7402 free(wanted_refname);
7404 if (err == NULL && bad_sigs)
7405 err = got_error(GOT_ERR_BAD_TAG_SIGNATURE);
7406 return err;
7409 static const struct got_error *
7410 get_tag_message(char **tagmsg, char **tagmsg_path, const char *commit_id_str,
7411 const char *tag_name, const char *repo_path)
7413 const struct got_error *err = NULL;
7414 char *template = NULL, *initial_content = NULL;
7415 char *editor = NULL;
7416 int initial_content_len;
7417 int fd = -1;
7419 if (asprintf(&template, GOT_TMPDIR_STR "/got-tagmsg") == -1) {
7420 err = got_error_from_errno("asprintf");
7421 goto done;
7424 initial_content_len = asprintf(&initial_content,
7425 "\n# tagging commit %s as %s\n",
7426 commit_id_str, tag_name);
7427 if (initial_content_len == -1) {
7428 err = got_error_from_errno("asprintf");
7429 goto done;
7432 err = got_opentemp_named_fd(tagmsg_path, &fd, template, "");
7433 if (err)
7434 goto done;
7436 if (write(fd, initial_content, initial_content_len) == -1) {
7437 err = got_error_from_errno2("write", *tagmsg_path);
7438 goto done;
7440 if (close(fd) == -1) {
7441 err = got_error_from_errno2("close", *tagmsg_path);
7442 goto done;
7444 fd = -1;
7446 err = get_editor(&editor);
7447 if (err)
7448 goto done;
7449 err = edit_logmsg(tagmsg, editor, *tagmsg_path, initial_content,
7450 initial_content_len, 1);
7451 done:
7452 free(initial_content);
7453 free(template);
7454 free(editor);
7456 if (fd != -1 && close(fd) == -1 && err == NULL)
7457 err = got_error_from_errno2("close", *tagmsg_path);
7459 if (err) {
7460 free(*tagmsg);
7461 *tagmsg = NULL;
7463 return err;
7466 static const struct got_error *
7467 add_tag(struct got_repository *repo, const char *tagger,
7468 const char *tag_name, const char *commit_arg, const char *tagmsg_arg,
7469 const char *signer_id, int verbosity)
7471 const struct got_error *err = NULL;
7472 struct got_object_id *commit_id = NULL, *tag_id = NULL;
7473 char *label = NULL, *commit_id_str = NULL;
7474 struct got_reference *ref = NULL;
7475 char *refname = NULL, *tagmsg = NULL;
7476 char *tagmsg_path = NULL, *tag_id_str = NULL;
7477 int preserve_tagmsg = 0;
7478 struct got_reflist_head refs;
7480 TAILQ_INIT(&refs);
7483 * Don't let the user create a tag name with a leading '-'.
7484 * While technically a valid reference name, this case is usually
7485 * an unintended typo.
7487 if (tag_name[0] == '-')
7488 return got_error_path(tag_name, GOT_ERR_REF_NAME_MINUS);
7490 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
7491 if (err)
7492 goto done;
7494 err = got_repo_match_object_id(&commit_id, &label, commit_arg,
7495 GOT_OBJ_TYPE_COMMIT, &refs, repo);
7496 if (err)
7497 goto done;
7499 err = got_object_id_str(&commit_id_str, commit_id);
7500 if (err)
7501 goto done;
7503 err = get_tag_refname(&refname, tag_name);
7504 if (err)
7505 goto done;
7506 if (strncmp("refs/tags/", tag_name, 10) == 0)
7507 tag_name += 10;
7509 err = got_ref_open(&ref, repo, refname, 0);
7510 if (err == NULL) {
7511 err = got_error(GOT_ERR_TAG_EXISTS);
7512 goto done;
7513 } else if (err->code != GOT_ERR_NOT_REF)
7514 goto done;
7516 if (tagmsg_arg == NULL) {
7517 err = get_tag_message(&tagmsg, &tagmsg_path, commit_id_str,
7518 tag_name, got_repo_get_path(repo));
7519 if (err) {
7520 if (err->code != GOT_ERR_COMMIT_MSG_EMPTY &&
7521 tagmsg_path != NULL)
7522 preserve_tagmsg = 1;
7523 goto done;
7525 /* Editor is done; we can now apply unveil(2) */
7526 err = got_sigs_apply_unveil();
7527 if (err)
7528 goto done;
7529 err = apply_unveil(got_repo_get_path(repo), 0, NULL);
7530 if (err)
7531 goto done;
7534 err = got_object_tag_create(&tag_id, tag_name, commit_id,
7535 tagger, time(NULL), tagmsg ? tagmsg : tagmsg_arg, signer_id, repo,
7536 verbosity);
7537 if (err) {
7538 if (tagmsg_path)
7539 preserve_tagmsg = 1;
7540 goto done;
7543 err = got_ref_alloc(&ref, refname, tag_id);
7544 if (err) {
7545 if (tagmsg_path)
7546 preserve_tagmsg = 1;
7547 goto done;
7550 err = got_ref_write(ref, repo);
7551 if (err) {
7552 if (tagmsg_path)
7553 preserve_tagmsg = 1;
7554 goto done;
7557 err = got_object_id_str(&tag_id_str, tag_id);
7558 if (err) {
7559 if (tagmsg_path)
7560 preserve_tagmsg = 1;
7561 goto done;
7563 printf("Created tag %s\n", tag_id_str);
7564 done:
7565 if (preserve_tagmsg) {
7566 fprintf(stderr, "%s: tag message preserved in %s\n",
7567 getprogname(), tagmsg_path);
7568 } else if (tagmsg_path && unlink(tagmsg_path) == -1 && err == NULL)
7569 err = got_error_from_errno2("unlink", tagmsg_path);
7570 free(tag_id_str);
7571 if (ref)
7572 got_ref_close(ref);
7573 free(commit_id);
7574 free(commit_id_str);
7575 free(refname);
7576 free(tagmsg);
7577 free(tagmsg_path);
7578 got_ref_list_free(&refs);
7579 return err;
7582 static const struct got_error *
7583 cmd_tag(int argc, char *argv[])
7585 const struct got_error *error = NULL;
7586 struct got_repository *repo = NULL;
7587 struct got_worktree *worktree = NULL;
7588 char *cwd = NULL, *repo_path = NULL, *commit_id_str = NULL;
7589 char *gitconfig_path = NULL, *tagger = NULL;
7590 char *allowed_signers = NULL, *revoked_signers = NULL;
7591 const char *signer_id = NULL;
7592 const char *tag_name = NULL, *commit_id_arg = NULL, *tagmsg = NULL;
7593 int ch, do_list = 0, verify_tags = 0, verbosity = 0;
7594 int *pack_fds = NULL;
7596 #ifndef PROFILE
7597 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
7598 "sendfd unveil", NULL) == -1)
7599 err(1, "pledge");
7600 #endif
7602 while ((ch = getopt(argc, argv, "c:lm:r:s:Vv")) != -1) {
7603 switch (ch) {
7604 case 'c':
7605 commit_id_arg = optarg;
7606 break;
7607 case 'l':
7608 do_list = 1;
7609 break;
7610 case 'm':
7611 tagmsg = optarg;
7612 break;
7613 case 'r':
7614 repo_path = realpath(optarg, NULL);
7615 if (repo_path == NULL) {
7616 error = got_error_from_errno2("realpath",
7617 optarg);
7618 goto done;
7620 got_path_strip_trailing_slashes(repo_path);
7621 break;
7622 case 's':
7623 signer_id = optarg;
7624 break;
7625 case 'V':
7626 verify_tags = 1;
7627 break;
7628 case 'v':
7629 if (verbosity < 0)
7630 verbosity = 0;
7631 else if (verbosity < 3)
7632 verbosity++;
7633 break;
7634 default:
7635 usage_tag();
7636 /* NOTREACHED */
7640 argc -= optind;
7641 argv += optind;
7643 if (do_list || verify_tags) {
7644 if (commit_id_arg != NULL)
7645 errx(1,
7646 "-c option can only be used when creating a tag");
7647 if (tagmsg) {
7648 if (do_list)
7649 option_conflict('l', 'm');
7650 else
7651 option_conflict('V', 'm');
7653 if (signer_id) {
7654 if (do_list)
7655 option_conflict('l', 's');
7656 else
7657 option_conflict('V', 's');
7659 if (argc > 1)
7660 usage_tag();
7661 } else if (argc != 1)
7662 usage_tag();
7664 if (argc == 1)
7665 tag_name = argv[0];
7667 cwd = getcwd(NULL, 0);
7668 if (cwd == NULL) {
7669 error = got_error_from_errno("getcwd");
7670 goto done;
7673 error = got_repo_pack_fds_open(&pack_fds);
7674 if (error != NULL)
7675 goto done;
7677 if (repo_path == NULL) {
7678 error = got_worktree_open(&worktree, cwd);
7679 if (error && error->code != GOT_ERR_NOT_WORKTREE)
7680 goto done;
7681 else
7682 error = NULL;
7683 if (worktree) {
7684 repo_path =
7685 strdup(got_worktree_get_repo_path(worktree));
7686 if (repo_path == NULL)
7687 error = got_error_from_errno("strdup");
7688 if (error)
7689 goto done;
7690 } else {
7691 repo_path = strdup(cwd);
7692 if (repo_path == NULL) {
7693 error = got_error_from_errno("strdup");
7694 goto done;
7699 if (do_list || verify_tags) {
7700 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
7701 if (error != NULL)
7702 goto done;
7703 error = get_allowed_signers(&allowed_signers, repo, worktree);
7704 if (error)
7705 goto done;
7706 error = get_revoked_signers(&revoked_signers, repo, worktree);
7707 if (error)
7708 goto done;
7709 if (worktree) {
7710 /* Release work tree lock. */
7711 got_worktree_close(worktree);
7712 worktree = NULL;
7716 * Remove "cpath" promise unless needed for signature tmpfile
7717 * creation.
7719 if (verify_tags)
7720 got_sigs_apply_unveil();
7721 else {
7722 #ifndef PROFILE
7723 if (pledge("stdio rpath wpath flock proc exec sendfd "
7724 "unveil", NULL) == -1)
7725 err(1, "pledge");
7726 #endif
7728 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
7729 if (error)
7730 goto done;
7731 error = list_tags(repo, tag_name, verify_tags, allowed_signers,
7732 revoked_signers, verbosity);
7733 } else {
7734 error = get_gitconfig_path(&gitconfig_path);
7735 if (error)
7736 goto done;
7737 error = got_repo_open(&repo, repo_path, gitconfig_path,
7738 pack_fds);
7739 if (error != NULL)
7740 goto done;
7742 error = get_author(&tagger, repo, worktree);
7743 if (error)
7744 goto done;
7745 if (signer_id == NULL)
7746 signer_id = get_signer_id(repo, worktree);
7748 if (tagmsg) {
7749 if (signer_id) {
7750 error = got_sigs_apply_unveil();
7751 if (error)
7752 goto done;
7754 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
7755 if (error)
7756 goto done;
7759 if (commit_id_arg == NULL) {
7760 struct got_reference *head_ref;
7761 struct got_object_id *commit_id;
7762 error = got_ref_open(&head_ref, repo,
7763 worktree ? got_worktree_get_head_ref_name(worktree)
7764 : GOT_REF_HEAD, 0);
7765 if (error)
7766 goto done;
7767 error = got_ref_resolve(&commit_id, repo, head_ref);
7768 got_ref_close(head_ref);
7769 if (error)
7770 goto done;
7771 error = got_object_id_str(&commit_id_str, commit_id);
7772 free(commit_id);
7773 if (error)
7774 goto done;
7777 if (worktree) {
7778 /* Release work tree lock. */
7779 got_worktree_close(worktree);
7780 worktree = NULL;
7783 error = add_tag(repo, tagger, tag_name,
7784 commit_id_str ? commit_id_str : commit_id_arg, tagmsg,
7785 signer_id, verbosity);
7787 done:
7788 if (repo) {
7789 const struct got_error *close_err = got_repo_close(repo);
7790 if (error == NULL)
7791 error = close_err;
7793 if (worktree)
7794 got_worktree_close(worktree);
7795 if (pack_fds) {
7796 const struct got_error *pack_err =
7797 got_repo_pack_fds_close(pack_fds);
7798 if (error == NULL)
7799 error = pack_err;
7801 free(cwd);
7802 free(repo_path);
7803 free(gitconfig_path);
7804 free(commit_id_str);
7805 free(tagger);
7806 free(allowed_signers);
7807 free(revoked_signers);
7808 return error;
7811 __dead static void
7812 usage_add(void)
7814 fprintf(stderr, "usage: %s add [-IR] path ...\n", getprogname());
7815 exit(1);
7818 static const struct got_error *
7819 add_progress(void *arg, unsigned char status, const char *path)
7821 while (path[0] == '/')
7822 path++;
7823 printf("%c %s\n", status, path);
7824 return NULL;
7827 static const struct got_error *
7828 cmd_add(int argc, char *argv[])
7830 const struct got_error *error = NULL;
7831 struct got_repository *repo = NULL;
7832 struct got_worktree *worktree = NULL;
7833 char *cwd = NULL;
7834 struct got_pathlist_head paths;
7835 struct got_pathlist_entry *pe;
7836 int ch, can_recurse = 0, no_ignores = 0;
7837 int *pack_fds = NULL;
7839 TAILQ_INIT(&paths);
7841 #ifndef PROFILE
7842 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
7843 NULL) == -1)
7844 err(1, "pledge");
7845 #endif
7847 while ((ch = getopt(argc, argv, "IR")) != -1) {
7848 switch (ch) {
7849 case 'I':
7850 no_ignores = 1;
7851 break;
7852 case 'R':
7853 can_recurse = 1;
7854 break;
7855 default:
7856 usage_add();
7857 /* NOTREACHED */
7861 argc -= optind;
7862 argv += optind;
7864 if (argc < 1)
7865 usage_add();
7867 cwd = getcwd(NULL, 0);
7868 if (cwd == NULL) {
7869 error = got_error_from_errno("getcwd");
7870 goto done;
7873 error = got_repo_pack_fds_open(&pack_fds);
7874 if (error != NULL)
7875 goto done;
7877 error = got_worktree_open(&worktree, cwd);
7878 if (error) {
7879 if (error->code == GOT_ERR_NOT_WORKTREE)
7880 error = wrap_not_worktree_error(error, "add", cwd);
7881 goto done;
7884 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
7885 NULL, pack_fds);
7886 if (error != NULL)
7887 goto done;
7889 error = apply_unveil(got_repo_get_path(repo), 1,
7890 got_worktree_get_root_path(worktree));
7891 if (error)
7892 goto done;
7894 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
7895 if (error)
7896 goto done;
7898 if (!can_recurse) {
7899 char *ondisk_path;
7900 struct stat sb;
7901 TAILQ_FOREACH(pe, &paths, entry) {
7902 if (asprintf(&ondisk_path, "%s/%s",
7903 got_worktree_get_root_path(worktree),
7904 pe->path) == -1) {
7905 error = got_error_from_errno("asprintf");
7906 goto done;
7908 if (lstat(ondisk_path, &sb) == -1) {
7909 if (errno == ENOENT) {
7910 free(ondisk_path);
7911 continue;
7913 error = got_error_from_errno2("lstat",
7914 ondisk_path);
7915 free(ondisk_path);
7916 goto done;
7918 free(ondisk_path);
7919 if (S_ISDIR(sb.st_mode)) {
7920 error = got_error_msg(GOT_ERR_BAD_PATH,
7921 "adding directories requires -R option");
7922 goto done;
7927 error = got_worktree_schedule_add(worktree, &paths, add_progress,
7928 NULL, repo, no_ignores);
7929 done:
7930 if (repo) {
7931 const struct got_error *close_err = got_repo_close(repo);
7932 if (error == NULL)
7933 error = close_err;
7935 if (worktree)
7936 got_worktree_close(worktree);
7937 if (pack_fds) {
7938 const struct got_error *pack_err =
7939 got_repo_pack_fds_close(pack_fds);
7940 if (error == NULL)
7941 error = pack_err;
7943 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
7944 free(cwd);
7945 return error;
7948 __dead static void
7949 usage_remove(void)
7951 fprintf(stderr, "usage: %s remove [-fkR] [-s status-codes] path ...\n",
7952 getprogname());
7953 exit(1);
7956 static const struct got_error *
7957 print_remove_status(void *arg, unsigned char status,
7958 unsigned char staged_status, const char *path)
7960 while (path[0] == '/')
7961 path++;
7962 if (status == GOT_STATUS_NONEXISTENT)
7963 return NULL;
7964 if (status == staged_status && (status == GOT_STATUS_DELETE))
7965 status = GOT_STATUS_NO_CHANGE;
7966 printf("%c%c %s\n", status, staged_status, path);
7967 return NULL;
7970 static const struct got_error *
7971 cmd_remove(int argc, char *argv[])
7973 const struct got_error *error = NULL;
7974 struct got_worktree *worktree = NULL;
7975 struct got_repository *repo = NULL;
7976 const char *status_codes = NULL;
7977 char *cwd = NULL;
7978 struct got_pathlist_head paths;
7979 struct got_pathlist_entry *pe;
7980 int ch, delete_local_mods = 0, can_recurse = 0, keep_on_disk = 0, i;
7981 int ignore_missing_paths = 0;
7982 int *pack_fds = NULL;
7984 TAILQ_INIT(&paths);
7986 #ifndef PROFILE
7987 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
7988 NULL) == -1)
7989 err(1, "pledge");
7990 #endif
7992 while ((ch = getopt(argc, argv, "fkRs:")) != -1) {
7993 switch (ch) {
7994 case 'f':
7995 delete_local_mods = 1;
7996 ignore_missing_paths = 1;
7997 break;
7998 case 'k':
7999 keep_on_disk = 1;
8000 break;
8001 case 'R':
8002 can_recurse = 1;
8003 break;
8004 case 's':
8005 for (i = 0; i < strlen(optarg); i++) {
8006 switch (optarg[i]) {
8007 case GOT_STATUS_MODIFY:
8008 delete_local_mods = 1;
8009 break;
8010 case GOT_STATUS_MISSING:
8011 ignore_missing_paths = 1;
8012 break;
8013 default:
8014 errx(1, "invalid status code '%c'",
8015 optarg[i]);
8018 status_codes = optarg;
8019 break;
8020 default:
8021 usage_remove();
8022 /* NOTREACHED */
8026 argc -= optind;
8027 argv += optind;
8029 if (argc < 1)
8030 usage_remove();
8032 cwd = getcwd(NULL, 0);
8033 if (cwd == NULL) {
8034 error = got_error_from_errno("getcwd");
8035 goto done;
8038 error = got_repo_pack_fds_open(&pack_fds);
8039 if (error != NULL)
8040 goto done;
8042 error = got_worktree_open(&worktree, cwd);
8043 if (error) {
8044 if (error->code == GOT_ERR_NOT_WORKTREE)
8045 error = wrap_not_worktree_error(error, "remove", cwd);
8046 goto done;
8049 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
8050 NULL, pack_fds);
8051 if (error)
8052 goto done;
8054 error = apply_unveil(got_repo_get_path(repo), 1,
8055 got_worktree_get_root_path(worktree));
8056 if (error)
8057 goto done;
8059 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
8060 if (error)
8061 goto done;
8063 if (!can_recurse) {
8064 char *ondisk_path;
8065 struct stat sb;
8066 TAILQ_FOREACH(pe, &paths, entry) {
8067 if (asprintf(&ondisk_path, "%s/%s",
8068 got_worktree_get_root_path(worktree),
8069 pe->path) == -1) {
8070 error = got_error_from_errno("asprintf");
8071 goto done;
8073 if (lstat(ondisk_path, &sb) == -1) {
8074 if (errno == ENOENT) {
8075 free(ondisk_path);
8076 continue;
8078 error = got_error_from_errno2("lstat",
8079 ondisk_path);
8080 free(ondisk_path);
8081 goto done;
8083 free(ondisk_path);
8084 if (S_ISDIR(sb.st_mode)) {
8085 error = got_error_msg(GOT_ERR_BAD_PATH,
8086 "removing directories requires -R option");
8087 goto done;
8092 error = got_worktree_schedule_delete(worktree, &paths,
8093 delete_local_mods, status_codes, print_remove_status, NULL,
8094 repo, keep_on_disk, ignore_missing_paths);
8095 done:
8096 if (repo) {
8097 const struct got_error *close_err = got_repo_close(repo);
8098 if (error == NULL)
8099 error = close_err;
8101 if (worktree)
8102 got_worktree_close(worktree);
8103 if (pack_fds) {
8104 const struct got_error *pack_err =
8105 got_repo_pack_fds_close(pack_fds);
8106 if (error == NULL)
8107 error = pack_err;
8109 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
8110 free(cwd);
8111 return error;
8114 __dead static void
8115 usage_patch(void)
8117 fprintf(stderr, "usage: %s patch [-nR] [-c commit] [-p strip-count] "
8118 "[patchfile]\n", getprogname());
8119 exit(1);
8122 static const struct got_error *
8123 patch_from_stdin(int *patchfd)
8125 const struct got_error *err = NULL;
8126 ssize_t r;
8127 char buf[BUFSIZ];
8128 sig_t sighup, sigint, sigquit;
8130 *patchfd = got_opentempfd();
8131 if (*patchfd == -1)
8132 return got_error_from_errno("got_opentempfd");
8134 sighup = signal(SIGHUP, SIG_DFL);
8135 sigint = signal(SIGINT, SIG_DFL);
8136 sigquit = signal(SIGQUIT, SIG_DFL);
8138 for (;;) {
8139 r = read(0, buf, sizeof(buf));
8140 if (r == -1) {
8141 err = got_error_from_errno("read");
8142 break;
8144 if (r == 0)
8145 break;
8146 if (write(*patchfd, buf, r) == -1) {
8147 err = got_error_from_errno("write");
8148 break;
8152 signal(SIGHUP, sighup);
8153 signal(SIGINT, sigint);
8154 signal(SIGQUIT, sigquit);
8156 if (err == NULL && lseek(*patchfd, 0, SEEK_SET) == -1)
8157 err = got_error_from_errno("lseek");
8159 if (err != NULL) {
8160 close(*patchfd);
8161 *patchfd = -1;
8164 return err;
8167 struct got_patch_progress_arg {
8168 int did_something;
8169 int conflicts;
8170 int rejects;
8173 static const struct got_error *
8174 patch_progress(void *arg, const char *old, const char *new,
8175 unsigned char status, const struct got_error *error, int old_from,
8176 int old_lines, int new_from, int new_lines, int offset,
8177 int ws_mangled, const struct got_error *hunk_err)
8179 const char *path = new == NULL ? old : new;
8180 struct got_patch_progress_arg *a = arg;
8182 while (*path == '/')
8183 path++;
8185 if (status != GOT_STATUS_NO_CHANGE &&
8186 status != 0 /* per-hunk progress */) {
8187 printf("%c %s\n", status, path);
8188 a->did_something = 1;
8191 if (hunk_err == NULL) {
8192 if (status == GOT_STATUS_CANNOT_UPDATE)
8193 a->rejects++;
8194 else if (status == GOT_STATUS_CONFLICT)
8195 a->conflicts++;
8198 if (error != NULL)
8199 fprintf(stderr, "%s: %s\n", getprogname(), error->msg);
8201 if (offset != 0 || hunk_err != NULL || ws_mangled) {
8202 printf("@@ -%d,%d +%d,%d @@ ", old_from,
8203 old_lines, new_from, new_lines);
8204 if (hunk_err != NULL)
8205 printf("%s\n", hunk_err->msg);
8206 else if (offset != 0)
8207 printf("applied with offset %d\n", offset);
8208 else
8209 printf("hunk contains mangled whitespace\n");
8212 return NULL;
8215 static void
8216 print_patch_progress_stats(struct got_patch_progress_arg *ppa)
8218 if (!ppa->did_something)
8219 return;
8221 if (ppa->conflicts > 0)
8222 printf("Files with merge conflicts: %d\n", ppa->conflicts);
8224 if (ppa->rejects > 0) {
8225 printf("Files where patch failed to apply: %d\n",
8226 ppa->rejects);
8230 static const struct got_error *
8231 cmd_patch(int argc, char *argv[])
8233 const struct got_error *error = NULL, *close_error = NULL;
8234 struct got_worktree *worktree = NULL;
8235 struct got_repository *repo = NULL;
8236 struct got_reflist_head refs;
8237 struct got_object_id *commit_id = NULL;
8238 const char *commit_id_str = NULL;
8239 struct stat sb;
8240 const char *errstr;
8241 char *cwd = NULL;
8242 int ch, nop = 0, strip = -1, reverse = 0;
8243 int patchfd;
8244 int *pack_fds = NULL;
8245 struct got_patch_progress_arg ppa;
8247 TAILQ_INIT(&refs);
8249 #ifndef PROFILE
8250 if (pledge("stdio rpath wpath cpath fattr proc exec sendfd flock "
8251 "unveil", NULL) == -1)
8252 err(1, "pledge");
8253 #endif
8255 while ((ch = getopt(argc, argv, "c:np:R")) != -1) {
8256 switch (ch) {
8257 case 'c':
8258 commit_id_str = optarg;
8259 break;
8260 case 'n':
8261 nop = 1;
8262 break;
8263 case 'p':
8264 strip = strtonum(optarg, 0, INT_MAX, &errstr);
8265 if (errstr != NULL)
8266 errx(1, "pathname strip count is %s: %s",
8267 errstr, optarg);
8268 break;
8269 case 'R':
8270 reverse = 1;
8271 break;
8272 default:
8273 usage_patch();
8274 /* NOTREACHED */
8278 argc -= optind;
8279 argv += optind;
8281 if (argc == 0) {
8282 error = patch_from_stdin(&patchfd);
8283 if (error)
8284 return error;
8285 } else if (argc == 1) {
8286 patchfd = open(argv[0], O_RDONLY);
8287 if (patchfd == -1) {
8288 error = got_error_from_errno2("open", argv[0]);
8289 return error;
8291 if (fstat(patchfd, &sb) == -1) {
8292 error = got_error_from_errno2("fstat", argv[0]);
8293 goto done;
8295 if (!S_ISREG(sb.st_mode)) {
8296 error = got_error_path(argv[0], GOT_ERR_BAD_FILETYPE);
8297 goto done;
8299 } else
8300 usage_patch();
8302 if ((cwd = getcwd(NULL, 0)) == NULL) {
8303 error = got_error_from_errno("getcwd");
8304 goto done;
8307 error = got_repo_pack_fds_open(&pack_fds);
8308 if (error != NULL)
8309 goto done;
8311 error = got_worktree_open(&worktree, cwd);
8312 if (error != NULL)
8313 goto done;
8315 const char *repo_path = got_worktree_get_repo_path(worktree);
8316 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
8317 if (error != NULL)
8318 goto done;
8320 error = apply_unveil(got_repo_get_path(repo), 0,
8321 got_worktree_get_root_path(worktree));
8322 if (error != NULL)
8323 goto done;
8325 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
8326 if (error)
8327 goto done;
8329 if (commit_id_str != NULL) {
8330 error = got_repo_match_object_id(&commit_id, NULL,
8331 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
8332 if (error)
8333 goto done;
8336 memset(&ppa, 0, sizeof(ppa));
8337 error = got_patch(patchfd, worktree, repo, nop, strip, reverse,
8338 commit_id, patch_progress, &ppa, check_cancelled, NULL);
8339 print_patch_progress_stats(&ppa);
8340 done:
8341 got_ref_list_free(&refs);
8342 free(commit_id);
8343 if (repo) {
8344 close_error = got_repo_close(repo);
8345 if (error == NULL)
8346 error = close_error;
8348 if (worktree != NULL) {
8349 close_error = got_worktree_close(worktree);
8350 if (error == NULL)
8351 error = close_error;
8353 if (pack_fds) {
8354 const struct got_error *pack_err =
8355 got_repo_pack_fds_close(pack_fds);
8356 if (error == NULL)
8357 error = pack_err;
8359 free(cwd);
8360 return error;
8363 __dead static void
8364 usage_revert(void)
8366 fprintf(stderr, "usage: %s revert [-pR] [-F response-script] path ...\n",
8367 getprogname());
8368 exit(1);
8371 static const struct got_error *
8372 revert_progress(void *arg, unsigned char status, const char *path)
8374 if (status == GOT_STATUS_UNVERSIONED)
8375 return NULL;
8377 while (path[0] == '/')
8378 path++;
8379 printf("%c %s\n", status, path);
8380 return NULL;
8383 struct choose_patch_arg {
8384 FILE *patch_script_file;
8385 const char *action;
8388 static const struct got_error *
8389 show_change(unsigned char status, const char *path, FILE *patch_file, int n,
8390 int nchanges, const char *action)
8392 const struct got_error *err;
8393 char *line = NULL;
8394 size_t linesize = 0;
8395 ssize_t linelen;
8397 switch (status) {
8398 case GOT_STATUS_ADD:
8399 printf("A %s\n%s this addition? [y/n] ", path, action);
8400 break;
8401 case GOT_STATUS_DELETE:
8402 printf("D %s\n%s this deletion? [y/n] ", path, action);
8403 break;
8404 case GOT_STATUS_MODIFY:
8405 if (fseek(patch_file, 0L, SEEK_SET) == -1)
8406 return got_error_from_errno("fseek");
8407 printf(GOT_COMMIT_SEP_STR);
8408 while ((linelen = getline(&line, &linesize, patch_file)) != -1)
8409 printf("%s", line);
8410 if (linelen == -1 && ferror(patch_file)) {
8411 err = got_error_from_errno("getline");
8412 free(line);
8413 return err;
8415 free(line);
8416 printf(GOT_COMMIT_SEP_STR);
8417 printf("M %s (change %d of %d)\n%s this change? [y/n/q] ",
8418 path, n, nchanges, action);
8419 break;
8420 default:
8421 return got_error_path(path, GOT_ERR_FILE_STATUS);
8424 fflush(stdout);
8425 return NULL;
8428 static const struct got_error *
8429 choose_patch(int *choice, void *arg, unsigned char status, const char *path,
8430 FILE *patch_file, int n, int nchanges)
8432 const struct got_error *err = NULL;
8433 char *line = NULL;
8434 size_t linesize = 0;
8435 ssize_t linelen;
8436 int resp = ' ';
8437 struct choose_patch_arg *a = arg;
8439 *choice = GOT_PATCH_CHOICE_NONE;
8441 if (a->patch_script_file) {
8442 char *nl;
8443 err = show_change(status, path, patch_file, n, nchanges,
8444 a->action);
8445 if (err)
8446 return err;
8447 linelen = getline(&line, &linesize, a->patch_script_file);
8448 if (linelen == -1) {
8449 if (ferror(a->patch_script_file))
8450 return got_error_from_errno("getline");
8451 return NULL;
8453 nl = strchr(line, '\n');
8454 if (nl)
8455 *nl = '\0';
8456 if (strcmp(line, "y") == 0) {
8457 *choice = GOT_PATCH_CHOICE_YES;
8458 printf("y\n");
8459 } else if (strcmp(line, "n") == 0) {
8460 *choice = GOT_PATCH_CHOICE_NO;
8461 printf("n\n");
8462 } else if (strcmp(line, "q") == 0 &&
8463 status == GOT_STATUS_MODIFY) {
8464 *choice = GOT_PATCH_CHOICE_QUIT;
8465 printf("q\n");
8466 } else
8467 printf("invalid response '%s'\n", line);
8468 free(line);
8469 return NULL;
8472 while (resp != 'y' && resp != 'n' && resp != 'q') {
8473 err = show_change(status, path, patch_file, n, nchanges,
8474 a->action);
8475 if (err)
8476 return err;
8477 resp = getchar();
8478 if (resp == '\n')
8479 resp = getchar();
8480 if (status == GOT_STATUS_MODIFY) {
8481 if (resp != 'y' && resp != 'n' && resp != 'q') {
8482 printf("invalid response '%c'\n", resp);
8483 resp = ' ';
8485 } else if (resp != 'y' && resp != 'n') {
8486 printf("invalid response '%c'\n", resp);
8487 resp = ' ';
8491 if (resp == 'y')
8492 *choice = GOT_PATCH_CHOICE_YES;
8493 else if (resp == 'n')
8494 *choice = GOT_PATCH_CHOICE_NO;
8495 else if (resp == 'q' && status == GOT_STATUS_MODIFY)
8496 *choice = GOT_PATCH_CHOICE_QUIT;
8498 return NULL;
8501 struct wt_commitable_path_arg {
8502 struct got_pathlist_head *commit_paths;
8503 int *has_changes;
8507 * Shortcut work tree status callback to determine if the set of paths scanned
8508 * has at least one versioned path that is being modified and, if not NULL, is
8509 * in the arg->commit_paths list. Set arg and return GOT_ERR_FILE_MODIFIED as
8510 * soon as a path is passed with a status that satisfies this criteria.
8512 static const struct got_error *
8513 worktree_has_commitable_path(void *arg, unsigned char status,
8514 unsigned char staged_status, const char *path,
8515 struct got_object_id *blob_id, struct got_object_id *staged_blob_id,
8516 struct got_object_id *commit_id, int dirfd, const char *de_name)
8518 struct wt_commitable_path_arg *a = arg;
8520 if (status == staged_status && (status == GOT_STATUS_DELETE))
8521 status = GOT_STATUS_NO_CHANGE;
8523 if (!(status == GOT_STATUS_NO_CHANGE ||
8524 status == GOT_STATUS_UNVERSIONED) ||
8525 staged_status != GOT_STATUS_NO_CHANGE) {
8526 if (a->commit_paths != NULL) {
8527 struct got_pathlist_entry *pe;
8529 TAILQ_FOREACH(pe, a->commit_paths, entry) {
8530 if (strncmp(path, pe->path,
8531 pe->path_len) == 0) {
8532 *a->has_changes = 1;
8533 break;
8536 } else
8537 *a->has_changes = 1;
8539 if (*a->has_changes)
8540 return got_error(GOT_ERR_FILE_MODIFIED);
8543 return NULL;
8547 * Check that the changeset of the commit identified by id is
8548 * comprised of at least one modified path that is being committed.
8550 static const struct got_error *
8551 commit_path_changed_in_worktree(struct wt_commitable_path_arg *wcpa,
8552 struct got_object_id *id, struct got_worktree *worktree,
8553 struct got_repository *repo)
8555 const struct got_error *err;
8556 struct got_pathlist_head paths;
8557 struct got_commit_object *commit = NULL, *pcommit = NULL;
8558 struct got_tree_object *tree = NULL, *ptree = NULL;
8559 struct got_object_qid *pid;
8561 TAILQ_INIT(&paths);
8563 err = got_object_open_as_commit(&commit, repo, id);
8564 if (err)
8565 goto done;
8567 err = got_object_open_as_tree(&tree, repo,
8568 got_object_commit_get_tree_id(commit));
8569 if (err)
8570 goto done;
8572 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
8573 if (pid != NULL) {
8574 err = got_object_open_as_commit(&pcommit, repo, &pid->id);
8575 if (err)
8576 goto done;
8578 err = got_object_open_as_tree(&ptree, repo,
8579 got_object_commit_get_tree_id(pcommit));
8580 if (err)
8581 goto done;
8584 err = got_diff_tree(ptree, tree, NULL, NULL, -1, -1, "", "", repo,
8585 got_diff_tree_collect_changed_paths, &paths, 0);
8586 if (err)
8587 goto done;
8589 err = got_worktree_status(worktree, &paths, repo, 0,
8590 worktree_has_commitable_path, wcpa, check_cancelled, NULL);
8591 if (err && err->code == GOT_ERR_FILE_MODIFIED) {
8593 * At least one changed path in the referenced commit is
8594 * modified in the work tree, that's all we need to know!
8596 err = NULL;
8599 done:
8600 got_pathlist_free(&paths, GOT_PATHLIST_FREE_ALL);
8601 if (commit)
8602 got_object_commit_close(commit);
8603 if (pcommit)
8604 got_object_commit_close(pcommit);
8605 if (tree)
8606 got_object_tree_close(tree);
8607 if (ptree)
8608 got_object_tree_close(ptree);
8609 return err;
8613 * Remove any "logmsg" reference comprised entirely of paths that have
8614 * been reverted in this work tree. If any path in the logmsg ref changeset
8615 * remains in a changed state in the worktree, do not remove the reference.
8617 static const struct got_error *
8618 rm_logmsg_ref(struct got_worktree *worktree, struct got_repository *repo)
8620 const struct got_error *err;
8621 struct got_reflist_head refs;
8622 struct got_reflist_entry *re;
8623 struct got_commit_object *commit = NULL;
8624 struct got_object_id *commit_id = NULL;
8625 struct wt_commitable_path_arg wcpa;
8626 char *uuidstr = NULL;
8628 TAILQ_INIT(&refs);
8630 err = got_worktree_get_uuid(&uuidstr, worktree);
8631 if (err)
8632 goto done;
8634 err = got_ref_list(&refs, repo, "refs/got/worktree",
8635 got_ref_cmp_by_name, repo);
8636 if (err)
8637 goto done;
8639 TAILQ_FOREACH(re, &refs, entry) {
8640 const char *refname;
8641 int has_changes = 0;
8643 refname = got_ref_get_name(re->ref);
8645 if (!strncmp(refname, GOT_WORKTREE_CHERRYPICK_REF_PREFIX,
8646 GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN))
8647 refname += GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN + 1;
8648 else if (!strncmp(refname, GOT_WORKTREE_BACKOUT_REF_PREFIX,
8649 GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN))
8650 refname += GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN + 1;
8651 else
8652 continue;
8654 if (strncmp(refname, uuidstr, GOT_WORKTREE_UUID_STRLEN) == 0)
8655 refname += GOT_WORKTREE_UUID_STRLEN + 1; /* skip '-' */
8656 else
8657 continue;
8659 err = got_repo_match_object_id(&commit_id, NULL, refname,
8660 GOT_OBJ_TYPE_COMMIT, NULL, repo);
8661 if (err)
8662 goto done;
8664 err = got_object_open_as_commit(&commit, repo, commit_id);
8665 if (err)
8666 goto done;
8668 wcpa.commit_paths = NULL;
8669 wcpa.has_changes = &has_changes;
8671 err = commit_path_changed_in_worktree(&wcpa, commit_id,
8672 worktree, repo);
8673 if (err)
8674 goto done;
8676 if (!has_changes) {
8677 err = got_ref_delete(re->ref, repo);
8678 if (err)
8679 goto done;
8682 got_object_commit_close(commit);
8683 commit = NULL;
8684 free(commit_id);
8685 commit_id = NULL;
8688 done:
8689 free(uuidstr);
8690 free(commit_id);
8691 got_ref_list_free(&refs);
8692 if (commit)
8693 got_object_commit_close(commit);
8694 return err;
8697 static const struct got_error *
8698 cmd_revert(int argc, char *argv[])
8700 const struct got_error *error = NULL;
8701 struct got_worktree *worktree = NULL;
8702 struct got_repository *repo = NULL;
8703 char *cwd = NULL, *path = NULL;
8704 struct got_pathlist_head paths;
8705 struct got_pathlist_entry *pe;
8706 int ch, can_recurse = 0, pflag = 0;
8707 FILE *patch_script_file = NULL;
8708 const char *patch_script_path = NULL;
8709 struct choose_patch_arg cpa;
8710 int *pack_fds = NULL;
8712 TAILQ_INIT(&paths);
8714 #ifndef PROFILE
8715 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
8716 "unveil", NULL) == -1)
8717 err(1, "pledge");
8718 #endif
8720 while ((ch = getopt(argc, argv, "F:pR")) != -1) {
8721 switch (ch) {
8722 case 'F':
8723 patch_script_path = optarg;
8724 break;
8725 case 'p':
8726 pflag = 1;
8727 break;
8728 case 'R':
8729 can_recurse = 1;
8730 break;
8731 default:
8732 usage_revert();
8733 /* NOTREACHED */
8737 argc -= optind;
8738 argv += optind;
8740 if (argc < 1)
8741 usage_revert();
8742 if (patch_script_path && !pflag)
8743 errx(1, "-F option can only be used together with -p option");
8745 cwd = getcwd(NULL, 0);
8746 if (cwd == NULL) {
8747 error = got_error_from_errno("getcwd");
8748 goto done;
8751 error = got_repo_pack_fds_open(&pack_fds);
8752 if (error != NULL)
8753 goto done;
8755 error = got_worktree_open(&worktree, cwd);
8756 if (error) {
8757 if (error->code == GOT_ERR_NOT_WORKTREE)
8758 error = wrap_not_worktree_error(error, "revert", cwd);
8759 goto done;
8762 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
8763 NULL, pack_fds);
8764 if (error != NULL)
8765 goto done;
8767 if (patch_script_path) {
8768 patch_script_file = fopen(patch_script_path, "re");
8769 if (patch_script_file == NULL) {
8770 error = got_error_from_errno2("fopen",
8771 patch_script_path);
8772 goto done;
8777 * XXX "c" perm needed on repo dir to delete merge references.
8779 error = apply_unveil(got_repo_get_path(repo), 0,
8780 got_worktree_get_root_path(worktree));
8781 if (error)
8782 goto done;
8784 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
8785 if (error)
8786 goto done;
8788 if (!can_recurse) {
8789 char *ondisk_path;
8790 struct stat sb;
8791 TAILQ_FOREACH(pe, &paths, entry) {
8792 if (asprintf(&ondisk_path, "%s/%s",
8793 got_worktree_get_root_path(worktree),
8794 pe->path) == -1) {
8795 error = got_error_from_errno("asprintf");
8796 goto done;
8798 if (lstat(ondisk_path, &sb) == -1) {
8799 if (errno == ENOENT) {
8800 free(ondisk_path);
8801 continue;
8803 error = got_error_from_errno2("lstat",
8804 ondisk_path);
8805 free(ondisk_path);
8806 goto done;
8808 free(ondisk_path);
8809 if (S_ISDIR(sb.st_mode)) {
8810 error = got_error_msg(GOT_ERR_BAD_PATH,
8811 "reverting directories requires -R option");
8812 goto done;
8817 cpa.patch_script_file = patch_script_file;
8818 cpa.action = "revert";
8819 error = got_worktree_revert(worktree, &paths, revert_progress, NULL,
8820 pflag ? choose_patch : NULL, &cpa, repo);
8822 error = rm_logmsg_ref(worktree, repo);
8823 done:
8824 if (patch_script_file && fclose(patch_script_file) == EOF &&
8825 error == NULL)
8826 error = got_error_from_errno2("fclose", patch_script_path);
8827 if (repo) {
8828 const struct got_error *close_err = got_repo_close(repo);
8829 if (error == NULL)
8830 error = close_err;
8832 if (worktree)
8833 got_worktree_close(worktree);
8834 if (pack_fds) {
8835 const struct got_error *pack_err =
8836 got_repo_pack_fds_close(pack_fds);
8837 if (error == NULL)
8838 error = pack_err;
8840 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
8841 free(path);
8842 free(cwd);
8843 return error;
8846 __dead static void
8847 usage_commit(void)
8849 fprintf(stderr, "usage: %s commit [-CNnS] [-A author] [-F path] "
8850 "[-m message] [path ...]\n", getprogname());
8851 exit(1);
8854 struct collect_commit_logmsg_arg {
8855 const char *cmdline_log;
8856 const char *prepared_log;
8857 const char *merged_log;
8858 int non_interactive;
8859 const char *editor;
8860 const char *worktree_path;
8861 const char *branch_name;
8862 const char *repo_path;
8863 char *logmsg_path;
8867 static const struct got_error *
8868 read_prepared_logmsg(char **logmsg, const char *path)
8870 const struct got_error *err = NULL;
8871 FILE *f = NULL;
8872 struct stat sb;
8873 size_t r;
8875 *logmsg = NULL;
8876 memset(&sb, 0, sizeof(sb));
8878 f = fopen(path, "re");
8879 if (f == NULL)
8880 return got_error_from_errno2("fopen", path);
8882 if (fstat(fileno(f), &sb) == -1) {
8883 err = got_error_from_errno2("fstat", path);
8884 goto done;
8886 if (sb.st_size == 0) {
8887 err = got_error(GOT_ERR_COMMIT_MSG_EMPTY);
8888 goto done;
8891 *logmsg = malloc(sb.st_size + 1);
8892 if (*logmsg == NULL) {
8893 err = got_error_from_errno("malloc");
8894 goto done;
8897 r = fread(*logmsg, 1, sb.st_size, f);
8898 if (r != sb.st_size) {
8899 if (ferror(f))
8900 err = got_error_from_errno2("fread", path);
8901 else
8902 err = got_error(GOT_ERR_IO);
8903 goto done;
8905 (*logmsg)[sb.st_size] = '\0';
8906 done:
8907 if (fclose(f) == EOF && err == NULL)
8908 err = got_error_from_errno2("fclose", path);
8909 if (err) {
8910 free(*logmsg);
8911 *logmsg = NULL;
8913 return err;
8916 static const struct got_error *
8917 collect_commit_logmsg(struct got_pathlist_head *commitable_paths,
8918 const char *diff_path, char **logmsg, void *arg)
8920 char *initial_content = NULL;
8921 struct got_pathlist_entry *pe;
8922 const struct got_error *err = NULL;
8923 char *template = NULL;
8924 char *prepared_msg = NULL, *merged_msg = NULL;
8925 struct collect_commit_logmsg_arg *a = arg;
8926 int initial_content_len;
8927 int fd = -1;
8928 size_t len;
8930 /* if a message was specified on the command line, just use it */
8931 if (a->cmdline_log != NULL && strlen(a->cmdline_log) != 0) {
8932 len = strlen(a->cmdline_log) + 1;
8933 *logmsg = malloc(len + 1);
8934 if (*logmsg == NULL)
8935 return got_error_from_errno("malloc");
8936 strlcpy(*logmsg, a->cmdline_log, len);
8937 return NULL;
8938 } else if (a->prepared_log != NULL && a->non_interactive)
8939 return read_prepared_logmsg(logmsg, a->prepared_log);
8941 if (asprintf(&template, "%s/logmsg", a->worktree_path) == -1)
8942 return got_error_from_errno("asprintf");
8944 err = got_opentemp_named_fd(&a->logmsg_path, &fd, template, "");
8945 if (err)
8946 goto done;
8948 if (a->prepared_log) {
8949 err = read_prepared_logmsg(&prepared_msg, a->prepared_log);
8950 if (err)
8951 goto done;
8952 } else if (a->merged_log) {
8953 err = read_prepared_logmsg(&merged_msg, a->merged_log);
8954 if (err)
8955 goto done;
8958 initial_content_len = asprintf(&initial_content,
8959 "%s%s\n# changes to be committed on branch %s:\n",
8960 prepared_msg ? prepared_msg : "",
8961 merged_msg ? merged_msg : "", a->branch_name);
8962 if (initial_content_len == -1) {
8963 err = got_error_from_errno("asprintf");
8964 goto done;
8967 if (write(fd, initial_content, initial_content_len) == -1) {
8968 err = got_error_from_errno2("write", a->logmsg_path);
8969 goto done;
8972 TAILQ_FOREACH(pe, commitable_paths, entry) {
8973 struct got_commitable *ct = pe->data;
8974 dprintf(fd, "# %c %s\n",
8975 got_commitable_get_status(ct),
8976 got_commitable_get_path(ct));
8979 if (diff_path) {
8980 dprintf(fd, "# detailed changes can be viewed in %s\n",
8981 diff_path);
8984 if (close(fd) == -1) {
8985 err = got_error_from_errno2("close", a->logmsg_path);
8986 goto done;
8988 fd = -1;
8990 err = edit_logmsg(logmsg, a->editor, a->logmsg_path, initial_content,
8991 initial_content_len, a->prepared_log ? 0 : 1);
8992 done:
8993 free(initial_content);
8994 free(template);
8995 free(prepared_msg);
8996 free(merged_msg);
8998 if (fd != -1 && close(fd) == -1 && err == NULL)
8999 err = got_error_from_errno2("close", a->logmsg_path);
9001 /* Editor is done; we can now apply unveil(2) */
9002 if (err == NULL)
9003 err = apply_unveil(a->repo_path, 0, a->worktree_path);
9004 if (err) {
9005 free(*logmsg);
9006 *logmsg = NULL;
9008 return err;
9011 static const struct got_error *
9012 cat_logmsg(FILE *f, struct got_commit_object *commit, const char *idstr,
9013 const char *type, int has_content)
9015 const struct got_error *err = NULL;
9016 char *logmsg = NULL;
9018 err = got_object_commit_get_logmsg(&logmsg, commit);
9019 if (err)
9020 return err;
9022 if (fprintf(f, "%s# log message of %s commit %s:%s",
9023 has_content ? "\n" : "", type, idstr, logmsg) < 0)
9024 err = got_ferror(f, GOT_ERR_IO);
9026 free(logmsg);
9027 return err;
9031 * Lookup "logmsg" references of backed-out and cherrypicked commits
9032 * belonging to the current work tree. If found, and the worktree has
9033 * at least one modified file that was changed in the referenced commit,
9034 * add its log message to a new temporary file at *logmsg_path.
9035 * Add all refs found to matched_refs to be scheduled for removal on
9036 * successful commit.
9038 static const struct got_error *
9039 lookup_logmsg_ref(char **logmsg_path, struct got_pathlist_head *paths,
9040 struct got_reflist_head *matched_refs, struct got_worktree *worktree,
9041 struct got_repository *repo)
9043 const struct got_error *err;
9044 struct got_commit_object *commit = NULL;
9045 struct got_object_id *id = NULL;
9046 struct got_reflist_head refs;
9047 struct got_reflist_entry *re, *re_match;
9048 FILE *f = NULL;
9049 char *uuidstr = NULL;
9050 int added_logmsg = 0;
9052 TAILQ_INIT(&refs);
9054 *logmsg_path = NULL;
9056 err = got_worktree_get_uuid(&uuidstr, worktree);
9057 if (err)
9058 goto done;
9060 err = got_ref_list(&refs, repo, "refs/got/worktree",
9061 got_ref_cmp_by_name, repo);
9062 if (err)
9063 goto done;
9065 TAILQ_FOREACH(re, &refs, entry) {
9066 const char *refname, *type;
9067 struct wt_commitable_path_arg wcpa;
9068 int add_logmsg = 0;
9070 refname = got_ref_get_name(re->ref);
9072 if (strncmp(refname, GOT_WORKTREE_CHERRYPICK_REF_PREFIX,
9073 GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN) == 0) {
9074 refname += GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN + 1;
9075 type = "cherrypicked";
9076 } else if (strncmp(refname, GOT_WORKTREE_BACKOUT_REF_PREFIX,
9077 GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN) == 0) {
9078 refname += GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN + 1;
9079 type = "backed-out";
9080 } else
9081 continue;
9083 if (strncmp(refname, uuidstr, GOT_WORKTREE_UUID_STRLEN) == 0)
9084 refname += GOT_WORKTREE_UUID_STRLEN + 1; /* skip '-' */
9085 else
9086 continue;
9088 err = got_repo_match_object_id(&id, NULL, refname,
9089 GOT_OBJ_TYPE_COMMIT, NULL, repo);
9090 if (err)
9091 goto done;
9093 err = got_object_open_as_commit(&commit, repo, id);
9094 if (err)
9095 goto done;
9097 wcpa.commit_paths = paths;
9098 wcpa.has_changes = &add_logmsg;
9100 err = commit_path_changed_in_worktree(&wcpa, id,
9101 worktree, repo);
9102 if (err)
9103 goto done;
9105 if (add_logmsg) {
9106 if (f == NULL) {
9107 err = got_opentemp_named(logmsg_path, &f,
9108 "got-commit-logmsg", "");
9109 if (err)
9110 goto done;
9112 err = cat_logmsg(f, commit, refname, type,
9113 added_logmsg);
9114 if (err)
9115 goto done;
9116 if (!added_logmsg)
9117 ++added_logmsg;
9119 err = got_reflist_entry_dup(&re_match, re);
9120 if (err)
9121 goto done;
9122 TAILQ_INSERT_HEAD(matched_refs, re_match, entry);
9125 got_object_commit_close(commit);
9126 commit = NULL;
9127 free(id);
9128 id = NULL;
9131 done:
9132 free(id);
9133 free(uuidstr);
9134 got_ref_list_free(&refs);
9135 if (commit)
9136 got_object_commit_close(commit);
9137 if (f && fclose(f) == EOF && err == NULL)
9138 err = got_error_from_errno("fclose");
9139 if (!added_logmsg) {
9140 if (*logmsg_path && unlink(*logmsg_path) != 0 && err == NULL)
9141 err = got_error_from_errno2("unlink", *logmsg_path);
9142 *logmsg_path = NULL;
9144 return err;
9147 static const struct got_error *
9148 cmd_commit(int argc, char *argv[])
9150 const struct got_error *error = NULL;
9151 struct got_worktree *worktree = NULL;
9152 struct got_repository *repo = NULL;
9153 char *cwd = NULL, *id_str = NULL;
9154 struct got_object_id *id = NULL;
9155 const char *logmsg = NULL;
9156 char *prepared_logmsg = NULL, *merged_logmsg = NULL;
9157 struct collect_commit_logmsg_arg cl_arg;
9158 const char *author = NULL;
9159 char *gitconfig_path = NULL, *editor = NULL, *committer = NULL;
9160 int ch, rebase_in_progress, histedit_in_progress, preserve_logmsg = 0;
9161 int allow_bad_symlinks = 0, non_interactive = 0, merge_in_progress = 0;
9162 int show_diff = 1, commit_conflicts = 0;
9163 struct got_pathlist_head paths;
9164 struct got_reflist_head refs;
9165 struct got_reflist_entry *re;
9166 int *pack_fds = NULL;
9168 TAILQ_INIT(&refs);
9169 TAILQ_INIT(&paths);
9170 cl_arg.logmsg_path = NULL;
9172 #ifndef PROFILE
9173 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
9174 "unveil", NULL) == -1)
9175 err(1, "pledge");
9176 #endif
9178 while ((ch = getopt(argc, argv, "A:CF:m:NnS")) != -1) {
9179 switch (ch) {
9180 case 'A':
9181 author = optarg;
9182 error = valid_author(author);
9183 if (error)
9184 return error;
9185 break;
9186 case 'C':
9187 commit_conflicts = 1;
9188 break;
9189 case 'F':
9190 if (logmsg != NULL)
9191 option_conflict('F', 'm');
9192 prepared_logmsg = realpath(optarg, NULL);
9193 if (prepared_logmsg == NULL)
9194 return got_error_from_errno2("realpath",
9195 optarg);
9196 break;
9197 case 'm':
9198 if (prepared_logmsg)
9199 option_conflict('m', 'F');
9200 logmsg = optarg;
9201 break;
9202 case 'N':
9203 non_interactive = 1;
9204 break;
9205 case 'n':
9206 show_diff = 0;
9207 break;
9208 case 'S':
9209 allow_bad_symlinks = 1;
9210 break;
9211 default:
9212 usage_commit();
9213 /* NOTREACHED */
9217 argc -= optind;
9218 argv += optind;
9220 cwd = getcwd(NULL, 0);
9221 if (cwd == NULL) {
9222 error = got_error_from_errno("getcwd");
9223 goto done;
9226 error = got_repo_pack_fds_open(&pack_fds);
9227 if (error != NULL)
9228 goto done;
9230 error = got_worktree_open(&worktree, cwd);
9231 if (error) {
9232 if (error->code == GOT_ERR_NOT_WORKTREE)
9233 error = wrap_not_worktree_error(error, "commit", cwd);
9234 goto done;
9237 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
9238 if (error)
9239 goto done;
9240 if (rebase_in_progress) {
9241 error = got_error(GOT_ERR_REBASING);
9242 goto done;
9245 error = got_worktree_histedit_in_progress(&histedit_in_progress,
9246 worktree);
9247 if (error)
9248 goto done;
9250 error = get_gitconfig_path(&gitconfig_path);
9251 if (error)
9252 goto done;
9253 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
9254 gitconfig_path, pack_fds);
9255 if (error != NULL)
9256 goto done;
9258 error = got_worktree_merge_in_progress(&merge_in_progress, worktree, repo);
9259 if (error)
9260 goto done;
9261 if (merge_in_progress) {
9262 error = got_error(GOT_ERR_MERGE_BUSY);
9263 goto done;
9266 error = get_author(&committer, repo, worktree);
9267 if (error)
9268 goto done;
9270 if (author == NULL)
9271 author = committer;
9274 * unveil(2) traverses exec(2); if an editor is used we have
9275 * to apply unveil after the log message has been written.
9277 if (logmsg == NULL || strlen(logmsg) == 0)
9278 error = get_editor(&editor);
9279 else
9280 error = apply_unveil(got_repo_get_path(repo), 0,
9281 got_worktree_get_root_path(worktree));
9282 if (error)
9283 goto done;
9285 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
9286 if (error)
9287 goto done;
9289 if (prepared_logmsg == NULL) {
9290 error = lookup_logmsg_ref(&merged_logmsg,
9291 argc > 0 ? &paths : NULL, &refs, worktree, repo);
9292 if (error)
9293 goto done;
9296 cl_arg.editor = editor;
9297 cl_arg.cmdline_log = logmsg;
9298 cl_arg.prepared_log = prepared_logmsg;
9299 cl_arg.merged_log = merged_logmsg;
9300 cl_arg.non_interactive = non_interactive;
9301 cl_arg.worktree_path = got_worktree_get_root_path(worktree);
9302 cl_arg.branch_name = got_worktree_get_head_ref_name(worktree);
9303 if (!histedit_in_progress) {
9304 if (strncmp(cl_arg.branch_name, "refs/heads/", 11) != 0) {
9305 error = got_error(GOT_ERR_COMMIT_BRANCH);
9306 goto done;
9308 cl_arg.branch_name += 11;
9310 cl_arg.repo_path = got_repo_get_path(repo);
9311 error = got_worktree_commit(&id, worktree, &paths, author, committer,
9312 allow_bad_symlinks, show_diff, commit_conflicts,
9313 collect_commit_logmsg, &cl_arg, print_status, NULL, repo);
9314 if (error) {
9315 if (error->code != GOT_ERR_COMMIT_MSG_EMPTY &&
9316 cl_arg.logmsg_path != NULL)
9317 preserve_logmsg = 1;
9318 goto done;
9321 error = got_object_id_str(&id_str, id);
9322 if (error)
9323 goto done;
9324 printf("Created commit %s\n", id_str);
9326 TAILQ_FOREACH(re, &refs, entry) {
9327 error = got_ref_delete(re->ref, repo);
9328 if (error)
9329 goto done;
9332 done:
9333 if (preserve_logmsg) {
9334 fprintf(stderr, "%s: log message preserved in %s\n",
9335 getprogname(), cl_arg.logmsg_path);
9336 } else if (cl_arg.logmsg_path && unlink(cl_arg.logmsg_path) == -1 &&
9337 error == NULL)
9338 error = got_error_from_errno2("unlink", cl_arg.logmsg_path);
9339 free(cl_arg.logmsg_path);
9340 if (merged_logmsg && unlink(merged_logmsg) == -1 && error == NULL)
9341 error = got_error_from_errno2("unlink", merged_logmsg);
9342 free(merged_logmsg);
9343 if (repo) {
9344 const struct got_error *close_err = got_repo_close(repo);
9345 if (error == NULL)
9346 error = close_err;
9348 if (worktree)
9349 got_worktree_close(worktree);
9350 if (pack_fds) {
9351 const struct got_error *pack_err =
9352 got_repo_pack_fds_close(pack_fds);
9353 if (error == NULL)
9354 error = pack_err;
9356 got_ref_list_free(&refs);
9357 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
9358 free(cwd);
9359 free(id_str);
9360 free(gitconfig_path);
9361 free(editor);
9362 free(committer);
9363 free(prepared_logmsg);
9364 return error;
9367 __dead static void
9368 usage_send(void)
9370 fprintf(stderr, "usage: %s send [-afqTv] [-b branch] [-d branch] "
9371 "[-r repository-path] [-t tag] [remote-repository]\n",
9372 getprogname());
9373 exit(1);
9376 static void
9377 print_load_info(int print_colored, int print_found, int print_trees,
9378 int ncolored, int nfound, int ntrees)
9380 if (print_colored) {
9381 printf("%d commit%s colored", ncolored,
9382 ncolored == 1 ? "" : "s");
9384 if (print_found) {
9385 printf("%s%d object%s found",
9386 ncolored > 0 ? "; " : "",
9387 nfound, nfound == 1 ? "" : "s");
9389 if (print_trees) {
9390 printf("; %d tree%s scanned", ntrees,
9391 ntrees == 1 ? "" : "s");
9395 struct got_send_progress_arg {
9396 char last_scaled_packsize[FMT_SCALED_STRSIZE];
9397 int verbosity;
9398 int last_ncolored;
9399 int last_nfound;
9400 int last_ntrees;
9401 int loading_done;
9402 int last_ncommits;
9403 int last_nobj_total;
9404 int last_p_deltify;
9405 int last_p_written;
9406 int last_p_sent;
9407 int printed_something;
9408 int sent_something;
9409 struct got_pathlist_head *delete_branches;
9412 static const struct got_error *
9413 send_progress(void *arg, int ncolored, int nfound, int ntrees,
9414 off_t packfile_size, int ncommits, int nobj_total, int nobj_deltify,
9415 int nobj_written, off_t bytes_sent, const char *refname,
9416 const char *errmsg, int success)
9418 struct got_send_progress_arg *a = arg;
9419 char scaled_packsize[FMT_SCALED_STRSIZE];
9420 char scaled_sent[FMT_SCALED_STRSIZE];
9421 int p_deltify = 0, p_written = 0, p_sent = 0;
9422 int print_colored = 0, print_found = 0, print_trees = 0;
9423 int print_searching = 0, print_total = 0;
9424 int print_deltify = 0, print_written = 0, print_sent = 0;
9426 if (a->verbosity < 0)
9427 return NULL;
9429 if (refname) {
9430 const char *status = success ? "accepted" : "rejected";
9432 if (success) {
9433 struct got_pathlist_entry *pe;
9434 TAILQ_FOREACH(pe, a->delete_branches, entry) {
9435 const char *branchname = pe->path;
9436 if (got_path_cmp(branchname, refname,
9437 strlen(branchname), strlen(refname)) == 0) {
9438 status = "deleted";
9439 a->sent_something = 1;
9440 break;
9445 if (a->printed_something)
9446 putchar('\n');
9447 printf("Server has %s %s", status, refname);
9448 if (errmsg)
9449 printf(": %s", errmsg);
9450 a->printed_something = 1;
9451 return NULL;
9454 if (a->last_ncolored != ncolored) {
9455 print_colored = 1;
9456 a->last_ncolored = ncolored;
9459 if (a->last_nfound != nfound) {
9460 print_colored = 1;
9461 print_found = 1;
9462 a->last_nfound = nfound;
9465 if (a->last_ntrees != ntrees) {
9466 print_colored = 1;
9467 print_found = 1;
9468 print_trees = 1;
9469 a->last_ntrees = ntrees;
9472 if ((print_colored || print_found || print_trees) &&
9473 !a->loading_done) {
9474 printf("\r");
9475 print_load_info(print_colored, print_found, print_trees,
9476 ncolored, nfound, ntrees);
9477 a->printed_something = 1;
9478 fflush(stdout);
9479 return NULL;
9480 } else if (!a->loading_done) {
9481 printf("\r");
9482 print_load_info(1, 1, 1, ncolored, nfound, ntrees);
9483 printf("\n");
9484 a->loading_done = 1;
9487 if (fmt_scaled(packfile_size, scaled_packsize) == -1)
9488 return got_error_from_errno("fmt_scaled");
9489 if (fmt_scaled(bytes_sent, scaled_sent) == -1)
9490 return got_error_from_errno("fmt_scaled");
9492 if (a->last_ncommits != ncommits) {
9493 print_searching = 1;
9494 a->last_ncommits = ncommits;
9497 if (a->last_nobj_total != nobj_total) {
9498 print_searching = 1;
9499 print_total = 1;
9500 a->last_nobj_total = nobj_total;
9503 if (packfile_size > 0 && (a->last_scaled_packsize[0] == '\0' ||
9504 strcmp(scaled_packsize, a->last_scaled_packsize)) != 0) {
9505 if (strlcpy(a->last_scaled_packsize, scaled_packsize,
9506 FMT_SCALED_STRSIZE) >= FMT_SCALED_STRSIZE)
9507 return got_error(GOT_ERR_NO_SPACE);
9510 if (nobj_deltify > 0 || nobj_written > 0) {
9511 if (nobj_deltify > 0) {
9512 p_deltify = (nobj_deltify * 100) / nobj_total;
9513 if (p_deltify != a->last_p_deltify) {
9514 a->last_p_deltify = p_deltify;
9515 print_searching = 1;
9516 print_total = 1;
9517 print_deltify = 1;
9520 if (nobj_written > 0) {
9521 p_written = (nobj_written * 100) / nobj_total;
9522 if (p_written != a->last_p_written) {
9523 a->last_p_written = p_written;
9524 print_searching = 1;
9525 print_total = 1;
9526 print_deltify = 1;
9527 print_written = 1;
9532 if (bytes_sent > 0) {
9533 p_sent = (bytes_sent * 100) / packfile_size;
9534 if (p_sent != a->last_p_sent) {
9535 a->last_p_sent = p_sent;
9536 print_searching = 1;
9537 print_total = 1;
9538 print_deltify = 1;
9539 print_written = 1;
9540 print_sent = 1;
9542 a->sent_something = 1;
9545 if (print_searching || print_total || print_deltify || print_written ||
9546 print_sent)
9547 printf("\r");
9548 if (print_searching)
9549 printf("packing %d reference%s", ncommits,
9550 ncommits == 1 ? "" : "s");
9551 if (print_total)
9552 printf("; %d object%s", nobj_total,
9553 nobj_total == 1 ? "" : "s");
9554 if (print_deltify)
9555 printf("; deltify: %d%%", p_deltify);
9556 if (print_sent)
9557 printf("; uploading pack: %*s %d%%", FMT_SCALED_STRSIZE - 2,
9558 scaled_packsize, p_sent);
9559 else if (print_written)
9560 printf("; writing pack: %*s %d%%", FMT_SCALED_STRSIZE - 2,
9561 scaled_packsize, p_written);
9562 if (print_searching || print_total || print_deltify ||
9563 print_written || print_sent) {
9564 a->printed_something = 1;
9565 fflush(stdout);
9567 return NULL;
9570 static const struct got_error *
9571 cmd_send(int argc, char *argv[])
9573 const struct got_error *error = NULL;
9574 char *cwd = NULL, *repo_path = NULL;
9575 const char *remote_name;
9576 char *proto = NULL, *host = NULL, *port = NULL;
9577 char *repo_name = NULL, *server_path = NULL;
9578 const struct got_remote_repo *remotes, *remote = NULL;
9579 int nremotes, nbranches = 0, ndelete_branches = 0;
9580 struct got_repository *repo = NULL;
9581 struct got_worktree *worktree = NULL;
9582 const struct got_gotconfig *repo_conf = NULL, *worktree_conf = NULL;
9583 struct got_pathlist_head branches;
9584 struct got_pathlist_head tags;
9585 struct got_reflist_head all_branches;
9586 struct got_reflist_head all_tags;
9587 struct got_pathlist_head delete_args;
9588 struct got_pathlist_head delete_branches;
9589 struct got_reflist_entry *re;
9590 struct got_pathlist_entry *pe;
9591 int i, ch, sendfd = -1, sendstatus;
9592 pid_t sendpid = -1;
9593 struct got_send_progress_arg spa;
9594 int verbosity = 0, overwrite_refs = 0;
9595 int send_all_branches = 0, send_all_tags = 0;
9596 struct got_reference *ref = NULL;
9597 int *pack_fds = NULL;
9599 TAILQ_INIT(&branches);
9600 TAILQ_INIT(&tags);
9601 TAILQ_INIT(&all_branches);
9602 TAILQ_INIT(&all_tags);
9603 TAILQ_INIT(&delete_args);
9604 TAILQ_INIT(&delete_branches);
9606 while ((ch = getopt(argc, argv, "ab:d:fqr:Tt:v")) != -1) {
9607 switch (ch) {
9608 case 'a':
9609 send_all_branches = 1;
9610 break;
9611 case 'b':
9612 error = got_pathlist_append(&branches, optarg, NULL);
9613 if (error)
9614 return error;
9615 nbranches++;
9616 break;
9617 case 'd':
9618 error = got_pathlist_append(&delete_args, optarg, NULL);
9619 if (error)
9620 return error;
9621 break;
9622 case 'f':
9623 overwrite_refs = 1;
9624 break;
9625 case 'q':
9626 verbosity = -1;
9627 break;
9628 case 'r':
9629 repo_path = realpath(optarg, NULL);
9630 if (repo_path == NULL)
9631 return got_error_from_errno2("realpath",
9632 optarg);
9633 got_path_strip_trailing_slashes(repo_path);
9634 break;
9635 case 'T':
9636 send_all_tags = 1;
9637 break;
9638 case 't':
9639 error = got_pathlist_append(&tags, optarg, NULL);
9640 if (error)
9641 return error;
9642 break;
9643 case 'v':
9644 if (verbosity < 0)
9645 verbosity = 0;
9646 else if (verbosity < 3)
9647 verbosity++;
9648 break;
9649 default:
9650 usage_send();
9651 /* NOTREACHED */
9654 argc -= optind;
9655 argv += optind;
9657 if (send_all_branches && !TAILQ_EMPTY(&branches))
9658 option_conflict('a', 'b');
9659 if (send_all_tags && !TAILQ_EMPTY(&tags))
9660 option_conflict('T', 't');
9663 if (argc == 0)
9664 remote_name = GOT_SEND_DEFAULT_REMOTE_NAME;
9665 else if (argc == 1)
9666 remote_name = argv[0];
9667 else
9668 usage_send();
9670 cwd = getcwd(NULL, 0);
9671 if (cwd == NULL) {
9672 error = got_error_from_errno("getcwd");
9673 goto done;
9676 error = got_repo_pack_fds_open(&pack_fds);
9677 if (error != NULL)
9678 goto done;
9680 if (repo_path == NULL) {
9681 error = got_worktree_open(&worktree, cwd);
9682 if (error && error->code != GOT_ERR_NOT_WORKTREE)
9683 goto done;
9684 else
9685 error = NULL;
9686 if (worktree) {
9687 repo_path =
9688 strdup(got_worktree_get_repo_path(worktree));
9689 if (repo_path == NULL)
9690 error = got_error_from_errno("strdup");
9691 if (error)
9692 goto done;
9693 } else {
9694 repo_path = strdup(cwd);
9695 if (repo_path == NULL) {
9696 error = got_error_from_errno("strdup");
9697 goto done;
9702 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
9703 if (error)
9704 goto done;
9706 if (worktree) {
9707 worktree_conf = got_worktree_get_gotconfig(worktree);
9708 if (worktree_conf) {
9709 got_gotconfig_get_remotes(&nremotes, &remotes,
9710 worktree_conf);
9711 for (i = 0; i < nremotes; i++) {
9712 if (strcmp(remotes[i].name, remote_name) == 0) {
9713 remote = &remotes[i];
9714 break;
9719 if (remote == NULL) {
9720 repo_conf = got_repo_get_gotconfig(repo);
9721 if (repo_conf) {
9722 got_gotconfig_get_remotes(&nremotes, &remotes,
9723 repo_conf);
9724 for (i = 0; i < nremotes; i++) {
9725 if (strcmp(remotes[i].name, remote_name) == 0) {
9726 remote = &remotes[i];
9727 break;
9732 if (remote == NULL) {
9733 got_repo_get_gitconfig_remotes(&nremotes, &remotes, repo);
9734 for (i = 0; i < nremotes; i++) {
9735 if (strcmp(remotes[i].name, remote_name) == 0) {
9736 remote = &remotes[i];
9737 break;
9741 if (remote == NULL) {
9742 error = got_error_path(remote_name, GOT_ERR_NO_REMOTE);
9743 goto done;
9746 error = got_dial_parse_uri(&proto, &host, &port, &server_path,
9747 &repo_name, remote->send_url);
9748 if (error)
9749 goto done;
9751 if (strcmp(proto, "git") == 0) {
9752 #ifndef PROFILE
9753 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
9754 "sendfd dns inet unveil", NULL) == -1)
9755 err(1, "pledge");
9756 #endif
9757 } else if (strcmp(proto, "git+ssh") == 0 ||
9758 strcmp(proto, "ssh") == 0) {
9759 #ifndef PROFILE
9760 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
9761 "sendfd unveil", NULL) == -1)
9762 err(1, "pledge");
9763 #endif
9764 } else if (strcmp(proto, "http") == 0 ||
9765 strcmp(proto, "git+http") == 0) {
9766 error = got_error_path(proto, GOT_ERR_NOT_IMPL);
9767 goto done;
9768 } else {
9769 error = got_error_path(proto, GOT_ERR_BAD_PROTO);
9770 goto done;
9773 error = got_dial_apply_unveil(proto);
9774 if (error)
9775 goto done;
9777 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
9778 if (error)
9779 goto done;
9781 if (send_all_branches) {
9782 error = got_ref_list(&all_branches, repo, "refs/heads",
9783 got_ref_cmp_by_name, NULL);
9784 if (error)
9785 goto done;
9786 TAILQ_FOREACH(re, &all_branches, entry) {
9787 const char *branchname = got_ref_get_name(re->ref);
9788 error = got_pathlist_append(&branches,
9789 branchname, NULL);
9790 if (error)
9791 goto done;
9792 nbranches++;
9794 } else if (nbranches == 0) {
9795 for (i = 0; i < remote->nsend_branches; i++) {
9796 error = got_pathlist_append(&branches,
9797 remote->send_branches[i], NULL);
9798 if (error)
9799 goto done;
9803 if (send_all_tags) {
9804 error = got_ref_list(&all_tags, repo, "refs/tags",
9805 got_ref_cmp_by_name, NULL);
9806 if (error)
9807 goto done;
9808 TAILQ_FOREACH(re, &all_tags, entry) {
9809 const char *tagname = got_ref_get_name(re->ref);
9810 error = got_pathlist_append(&tags,
9811 tagname, NULL);
9812 if (error)
9813 goto done;
9818 * To prevent accidents only branches in refs/heads/ can be deleted
9819 * with 'got send -d'.
9820 * Deleting anything else requires local repository access or Git.
9822 TAILQ_FOREACH(pe, &delete_args, entry) {
9823 const char *branchname = pe->path;
9824 char *s;
9825 struct got_pathlist_entry *new;
9826 if (strncmp(branchname, "refs/heads/", 11) == 0) {
9827 s = strdup(branchname);
9828 if (s == NULL) {
9829 error = got_error_from_errno("strdup");
9830 goto done;
9832 } else {
9833 if (asprintf(&s, "refs/heads/%s", branchname) == -1) {
9834 error = got_error_from_errno("asprintf");
9835 goto done;
9838 error = got_pathlist_insert(&new, &delete_branches, s, NULL);
9839 if (error || new == NULL /* duplicate */)
9840 free(s);
9841 if (error)
9842 goto done;
9843 ndelete_branches++;
9846 if (nbranches == 0 && ndelete_branches == 0) {
9847 struct got_reference *head_ref;
9848 if (worktree)
9849 error = got_ref_open(&head_ref, repo,
9850 got_worktree_get_head_ref_name(worktree), 0);
9851 else
9852 error = got_ref_open(&head_ref, repo, GOT_REF_HEAD, 0);
9853 if (error)
9854 goto done;
9855 if (got_ref_is_symbolic(head_ref)) {
9856 error = got_ref_resolve_symbolic(&ref, repo, head_ref);
9857 got_ref_close(head_ref);
9858 if (error)
9859 goto done;
9860 } else
9861 ref = head_ref;
9862 error = got_pathlist_append(&branches, got_ref_get_name(ref),
9863 NULL);
9864 if (error)
9865 goto done;
9866 nbranches++;
9869 if (verbosity >= 0) {
9870 printf("Connecting to \"%s\" %s://%s%s%s%s%s\n",
9871 remote->name, proto, host,
9872 port ? ":" : "", port ? port : "",
9873 *server_path == '/' ? "" : "/", server_path);
9876 error = got_send_connect(&sendpid, &sendfd, proto, host, port,
9877 server_path, verbosity);
9878 if (error)
9879 goto done;
9881 memset(&spa, 0, sizeof(spa));
9882 spa.last_scaled_packsize[0] = '\0';
9883 spa.last_p_deltify = -1;
9884 spa.last_p_written = -1;
9885 spa.verbosity = verbosity;
9886 spa.delete_branches = &delete_branches;
9887 error = got_send_pack(remote_name, &branches, &tags, &delete_branches,
9888 verbosity, overwrite_refs, sendfd, repo, send_progress, &spa,
9889 check_cancelled, NULL);
9890 if (spa.printed_something)
9891 putchar('\n');
9892 if (error)
9893 goto done;
9894 if (!spa.sent_something && verbosity >= 0)
9895 printf("Already up-to-date\n");
9896 done:
9897 if (sendpid > 0) {
9898 if (kill(sendpid, SIGTERM) == -1)
9899 error = got_error_from_errno("kill");
9900 if (waitpid(sendpid, &sendstatus, 0) == -1 && error == NULL)
9901 error = got_error_from_errno("waitpid");
9903 if (sendfd != -1 && close(sendfd) == -1 && error == NULL)
9904 error = got_error_from_errno("close");
9905 if (repo) {
9906 const struct got_error *close_err = got_repo_close(repo);
9907 if (error == NULL)
9908 error = close_err;
9910 if (worktree)
9911 got_worktree_close(worktree);
9912 if (pack_fds) {
9913 const struct got_error *pack_err =
9914 got_repo_pack_fds_close(pack_fds);
9915 if (error == NULL)
9916 error = pack_err;
9918 if (ref)
9919 got_ref_close(ref);
9920 got_pathlist_free(&branches, GOT_PATHLIST_FREE_NONE);
9921 got_pathlist_free(&tags, GOT_PATHLIST_FREE_NONE);
9922 got_ref_list_free(&all_branches);
9923 got_ref_list_free(&all_tags);
9924 got_pathlist_free(&delete_args, GOT_PATHLIST_FREE_NONE);
9925 got_pathlist_free(&delete_branches, GOT_PATHLIST_FREE_PATH);
9926 free(cwd);
9927 free(repo_path);
9928 free(proto);
9929 free(host);
9930 free(port);
9931 free(server_path);
9932 free(repo_name);
9933 return error;
9937 * Print and if delete is set delete all ref_prefix references.
9938 * If wanted_ref is not NULL, only print or delete this reference.
9940 static const struct got_error *
9941 process_logmsg_refs(const char *ref_prefix, size_t prefix_len,
9942 const char *wanted_ref, int delete, struct got_worktree *worktree,
9943 struct got_repository *repo)
9945 const struct got_error *err;
9946 struct got_pathlist_head paths;
9947 struct got_reflist_head refs;
9948 struct got_reflist_entry *re;
9949 struct got_reflist_object_id_map *refs_idmap = NULL;
9950 struct got_commit_object *commit = NULL;
9951 struct got_object_id *id = NULL;
9952 const char *header_prefix;
9953 char *uuidstr = NULL;
9954 int found = 0;
9956 TAILQ_INIT(&refs);
9957 TAILQ_INIT(&paths);
9959 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, repo);
9960 if (err)
9961 goto done;
9963 err = got_reflist_object_id_map_create(&refs_idmap, &refs, repo);
9964 if (err)
9965 goto done;
9967 if (worktree != NULL) {
9968 err = got_worktree_get_uuid(&uuidstr, worktree);
9969 if (err)
9970 goto done;
9973 if (wanted_ref) {
9974 if (strncmp(wanted_ref, "refs/heads/", 11) == 0)
9975 wanted_ref += 11;
9978 if (strcmp(ref_prefix, GOT_WORKTREE_BACKOUT_REF_PREFIX) == 0)
9979 header_prefix = "backout";
9980 else
9981 header_prefix = "cherrypick";
9983 TAILQ_FOREACH(re, &refs, entry) {
9984 const char *refname, *wt;
9986 refname = got_ref_get_name(re->ref);
9988 err = check_cancelled(NULL);
9989 if (err)
9990 goto done;
9992 if (strncmp(refname, ref_prefix, prefix_len) == 0)
9993 refname += prefix_len + 1; /* skip '-' delimiter */
9994 else
9995 continue;
9997 wt = refname;
9999 if (worktree == NULL || strncmp(refname, uuidstr,
10000 GOT_WORKTREE_UUID_STRLEN) == 0)
10001 refname += GOT_WORKTREE_UUID_STRLEN + 1; /* skip '-' */
10002 else
10003 continue;
10005 err = got_repo_match_object_id(&id, NULL, refname,
10006 GOT_OBJ_TYPE_COMMIT, NULL, repo);
10007 if (err)
10008 goto done;
10010 err = got_object_open_as_commit(&commit, repo, id);
10011 if (err)
10012 goto done;
10014 if (wanted_ref)
10015 found = strncmp(wanted_ref, refname,
10016 strlen(wanted_ref)) == 0;
10017 if (wanted_ref && !found) {
10018 struct got_reflist_head *ci_refs;
10020 ci_refs = got_reflist_object_id_map_lookup(refs_idmap,
10021 id);
10023 if (ci_refs) {
10024 char *refs_str = NULL;
10025 char const *r = NULL;
10027 err = build_refs_str(&refs_str, ci_refs, id,
10028 repo, 1);
10029 if (err)
10030 goto done;
10032 r = refs_str;
10033 while (r) {
10034 if (strncmp(r, wanted_ref,
10035 strlen(wanted_ref)) == 0) {
10036 found = 1;
10037 break;
10039 r = strchr(r, ' ');
10040 if (r)
10041 ++r;
10043 free(refs_str);
10047 if (wanted_ref == NULL || found) {
10048 if (delete) {
10049 err = got_ref_delete(re->ref, repo);
10050 if (err)
10051 goto done;
10052 printf("Deleted: ");
10053 err = print_commit_oneline(commit, id, repo,
10054 refs_idmap);
10055 } else {
10057 * Print paths modified by commit to help
10058 * associate commits with worktree changes.
10060 err = get_changed_paths(&paths, commit,
10061 repo, NULL);
10062 if (err)
10063 goto done;
10065 err = print_commit(commit, id, repo, NULL,
10066 &paths, NULL, 0, 0, refs_idmap, NULL,
10067 header_prefix);
10068 got_pathlist_free(&paths,
10069 GOT_PATHLIST_FREE_ALL);
10071 if (worktree == NULL)
10072 printf("work tree: %.*s\n\n",
10073 GOT_WORKTREE_UUID_STRLEN, wt);
10075 if (err || found)
10076 goto done;
10079 got_object_commit_close(commit);
10080 commit = NULL;
10081 free(id);
10082 id = NULL;
10085 if (wanted_ref != NULL && !found)
10086 err = got_error_fmt(GOT_ERR_NOT_REF, "%s", wanted_ref);
10088 done:
10089 free(id);
10090 free(uuidstr);
10091 got_ref_list_free(&refs);
10092 got_pathlist_free(&paths, GOT_PATHLIST_FREE_ALL);
10093 if (refs_idmap)
10094 got_reflist_object_id_map_free(refs_idmap);
10095 if (commit)
10096 got_object_commit_close(commit);
10097 return err;
10101 * Create new temp "logmsg" ref of the backed-out or cherrypicked commit
10102 * identified by id for log messages to prepopulate the editor on commit.
10104 static const struct got_error *
10105 logmsg_ref(struct got_object_id *id, const char *prefix,
10106 struct got_worktree *worktree, struct got_repository *repo)
10108 const struct got_error *err = NULL;
10109 char *idstr, *ref = NULL, *refname = NULL;
10110 int histedit_in_progress;
10111 int rebase_in_progress, merge_in_progress;
10114 * Silenty refuse to create merge reference if any histedit, merge,
10115 * or rebase operation is in progress.
10117 err = got_worktree_histedit_in_progress(&histedit_in_progress,
10118 worktree);
10119 if (err)
10120 return err;
10121 if (histedit_in_progress)
10122 return NULL;
10124 err = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
10125 if (err)
10126 return err;
10127 if (rebase_in_progress)
10128 return NULL;
10130 err = got_worktree_merge_in_progress(&merge_in_progress, worktree,
10131 repo);
10132 if (err)
10133 return err;
10134 if (merge_in_progress)
10135 return NULL;
10137 err = got_object_id_str(&idstr, id);
10138 if (err)
10139 return err;
10141 err = got_worktree_get_logmsg_ref_name(&refname, worktree, prefix);
10142 if (err)
10143 goto done;
10145 if (asprintf(&ref, "%s-%s", refname, idstr) == -1) {
10146 err = got_error_from_errno("asprintf");
10147 goto done;
10150 err = create_ref(ref, got_worktree_get_base_commit_id(worktree),
10151 -1, repo);
10152 done:
10153 free(ref);
10154 free(idstr);
10155 free(refname);
10156 return err;
10159 __dead static void
10160 usage_cherrypick(void)
10162 fprintf(stderr, "usage: %s cherrypick [-lX] [commit-id]\n",
10163 getprogname());
10164 exit(1);
10167 static const struct got_error *
10168 cmd_cherrypick(int argc, char *argv[])
10170 const struct got_error *error = NULL;
10171 struct got_worktree *worktree = NULL;
10172 struct got_repository *repo = NULL;
10173 char *cwd = NULL, *commit_id_str = NULL;
10174 struct got_object_id *commit_id = NULL;
10175 struct got_commit_object *commit = NULL;
10176 struct got_object_qid *pid;
10177 int ch, list_refs = 0, remove_refs = 0;
10178 struct got_update_progress_arg upa;
10179 int *pack_fds = NULL;
10181 #ifndef PROFILE
10182 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
10183 "unveil", NULL) == -1)
10184 err(1, "pledge");
10185 #endif
10187 while ((ch = getopt(argc, argv, "lX")) != -1) {
10188 switch (ch) {
10189 case 'l':
10190 list_refs = 1;
10191 break;
10192 case 'X':
10193 remove_refs = 1;
10194 break;
10195 default:
10196 usage_cherrypick();
10197 /* NOTREACHED */
10201 argc -= optind;
10202 argv += optind;
10204 if (list_refs || remove_refs) {
10205 if (argc != 0 && argc != 1)
10206 usage_cherrypick();
10207 } else if (argc != 1)
10208 usage_cherrypick();
10209 if (list_refs && remove_refs)
10210 option_conflict('l', 'X');
10212 cwd = getcwd(NULL, 0);
10213 if (cwd == NULL) {
10214 error = got_error_from_errno("getcwd");
10215 goto done;
10218 error = got_repo_pack_fds_open(&pack_fds);
10219 if (error != NULL)
10220 goto done;
10222 error = got_worktree_open(&worktree, cwd);
10223 if (error) {
10224 if (list_refs || remove_refs) {
10225 if (error->code != GOT_ERR_NOT_WORKTREE)
10226 goto done;
10227 } else {
10228 if (error->code == GOT_ERR_NOT_WORKTREE)
10229 error = wrap_not_worktree_error(error,
10230 "cherrypick", cwd);
10231 goto done;
10235 error = got_repo_open(&repo,
10236 worktree ? got_worktree_get_repo_path(worktree) : cwd,
10237 NULL, pack_fds);
10238 if (error != NULL)
10239 goto done;
10241 error = apply_unveil(got_repo_get_path(repo), 0,
10242 worktree ? got_worktree_get_root_path(worktree) : NULL);
10243 if (error)
10244 goto done;
10246 if (list_refs || remove_refs) {
10247 error = process_logmsg_refs(GOT_WORKTREE_CHERRYPICK_REF_PREFIX,
10248 GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN,
10249 argc == 1 ? argv[0] : NULL, remove_refs, worktree, repo);
10250 goto done;
10253 error = got_repo_match_object_id(&commit_id, NULL, argv[0],
10254 GOT_OBJ_TYPE_COMMIT, NULL, repo);
10255 if (error)
10256 goto done;
10257 error = got_object_id_str(&commit_id_str, commit_id);
10258 if (error)
10259 goto done;
10261 error = got_object_open_as_commit(&commit, repo, commit_id);
10262 if (error)
10263 goto done;
10264 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
10265 memset(&upa, 0, sizeof(upa));
10266 error = got_worktree_merge_files(worktree, pid ? &pid->id : NULL,
10267 commit_id, repo, update_progress, &upa, check_cancelled,
10268 NULL);
10269 if (error != NULL)
10270 goto done;
10272 if (upa.did_something) {
10273 error = logmsg_ref(commit_id,
10274 GOT_WORKTREE_CHERRYPICK_REF_PREFIX, worktree, repo);
10275 if (error)
10276 goto done;
10277 printf("Merged commit %s\n", commit_id_str);
10279 print_merge_progress_stats(&upa);
10280 done:
10281 free(cwd);
10282 if (commit)
10283 got_object_commit_close(commit);
10284 free(commit_id_str);
10285 if (worktree)
10286 got_worktree_close(worktree);
10287 if (repo) {
10288 const struct got_error *close_err = got_repo_close(repo);
10289 if (error == NULL)
10290 error = close_err;
10292 if (pack_fds) {
10293 const struct got_error *pack_err =
10294 got_repo_pack_fds_close(pack_fds);
10295 if (error == NULL)
10296 error = pack_err;
10299 return error;
10302 __dead static void
10303 usage_backout(void)
10305 fprintf(stderr, "usage: %s backout [-lX] [commit-id]\n", getprogname());
10306 exit(1);
10309 static const struct got_error *
10310 cmd_backout(int argc, char *argv[])
10312 const struct got_error *error = NULL;
10313 struct got_worktree *worktree = NULL;
10314 struct got_repository *repo = NULL;
10315 char *cwd = NULL, *commit_id_str = NULL;
10316 struct got_object_id *commit_id = NULL;
10317 struct got_commit_object *commit = NULL;
10318 struct got_object_qid *pid;
10319 int ch, list_refs = 0, remove_refs = 0;
10320 struct got_update_progress_arg upa;
10321 int *pack_fds = NULL;
10323 #ifndef PROFILE
10324 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
10325 "unveil", NULL) == -1)
10326 err(1, "pledge");
10327 #endif
10329 while ((ch = getopt(argc, argv, "lX")) != -1) {
10330 switch (ch) {
10331 case 'l':
10332 list_refs = 1;
10333 break;
10334 case 'X':
10335 remove_refs = 1;
10336 break;
10337 default:
10338 usage_backout();
10339 /* NOTREACHED */
10343 argc -= optind;
10344 argv += optind;
10346 if (list_refs || remove_refs) {
10347 if (argc != 0 && argc != 1)
10348 usage_backout();
10349 } else if (argc != 1)
10350 usage_backout();
10351 if (list_refs && remove_refs)
10352 option_conflict('l', 'X');
10354 cwd = getcwd(NULL, 0);
10355 if (cwd == NULL) {
10356 error = got_error_from_errno("getcwd");
10357 goto done;
10360 error = got_repo_pack_fds_open(&pack_fds);
10361 if (error != NULL)
10362 goto done;
10364 error = got_worktree_open(&worktree, cwd);
10365 if (error) {
10366 if (list_refs || remove_refs) {
10367 if (error->code != GOT_ERR_NOT_WORKTREE)
10368 goto done;
10369 } else {
10370 if (error->code == GOT_ERR_NOT_WORKTREE)
10371 error = wrap_not_worktree_error(error,
10372 "backout", cwd);
10373 goto done;
10377 error = got_repo_open(&repo,
10378 worktree ? got_worktree_get_repo_path(worktree) : cwd,
10379 NULL, pack_fds);
10380 if (error != NULL)
10381 goto done;
10383 error = apply_unveil(got_repo_get_path(repo), 0,
10384 worktree ? got_worktree_get_root_path(worktree) : NULL);
10385 if (error)
10386 goto done;
10388 if (list_refs || remove_refs) {
10389 error = process_logmsg_refs(GOT_WORKTREE_BACKOUT_REF_PREFIX,
10390 GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN,
10391 argc == 1 ? argv[0] : NULL, remove_refs, worktree, repo);
10392 goto done;
10395 error = got_repo_match_object_id(&commit_id, NULL, argv[0],
10396 GOT_OBJ_TYPE_COMMIT, NULL, repo);
10397 if (error)
10398 goto done;
10399 error = got_object_id_str(&commit_id_str, commit_id);
10400 if (error)
10401 goto done;
10403 error = got_object_open_as_commit(&commit, repo, commit_id);
10404 if (error)
10405 goto done;
10406 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
10407 if (pid == NULL) {
10408 error = got_error(GOT_ERR_ROOT_COMMIT);
10409 goto done;
10412 memset(&upa, 0, sizeof(upa));
10413 error = got_worktree_merge_files(worktree, commit_id, &pid->id,
10414 repo, update_progress, &upa, check_cancelled, NULL);
10415 if (error != NULL)
10416 goto done;
10418 if (upa.did_something) {
10419 error = logmsg_ref(commit_id, GOT_WORKTREE_BACKOUT_REF_PREFIX,
10420 worktree, repo);
10421 if (error)
10422 goto done;
10423 printf("Backed out commit %s\n", commit_id_str);
10425 print_merge_progress_stats(&upa);
10426 done:
10427 free(cwd);
10428 if (commit)
10429 got_object_commit_close(commit);
10430 free(commit_id_str);
10431 if (worktree)
10432 got_worktree_close(worktree);
10433 if (repo) {
10434 const struct got_error *close_err = got_repo_close(repo);
10435 if (error == NULL)
10436 error = close_err;
10438 if (pack_fds) {
10439 const struct got_error *pack_err =
10440 got_repo_pack_fds_close(pack_fds);
10441 if (error == NULL)
10442 error = pack_err;
10444 return error;
10447 __dead static void
10448 usage_rebase(void)
10450 fprintf(stderr, "usage: %s rebase [-aCclX] [branch]\n", getprogname());
10451 exit(1);
10454 static void
10455 trim_logmsg(char *logmsg, int limit)
10457 char *nl;
10458 size_t len;
10460 len = strlen(logmsg);
10461 if (len > limit)
10462 len = limit;
10463 logmsg[len] = '\0';
10464 nl = strchr(logmsg, '\n');
10465 if (nl)
10466 *nl = '\0';
10469 static const struct got_error *
10470 get_short_logmsg(char **logmsg, int limit, struct got_commit_object *commit)
10472 const struct got_error *err;
10473 char *logmsg0 = NULL;
10474 const char *s;
10476 err = got_object_commit_get_logmsg(&logmsg0, commit);
10477 if (err)
10478 return err;
10480 s = logmsg0;
10481 while (isspace((unsigned char)s[0]))
10482 s++;
10484 *logmsg = strdup(s);
10485 if (*logmsg == NULL) {
10486 err = got_error_from_errno("strdup");
10487 goto done;
10490 trim_logmsg(*logmsg, limit);
10491 done:
10492 free(logmsg0);
10493 return err;
10496 static const struct got_error *
10497 show_rebase_merge_conflict(struct got_object_id *id,
10498 struct got_repository *repo)
10500 const struct got_error *err;
10501 struct got_commit_object *commit = NULL;
10502 char *id_str = NULL, *logmsg = NULL;
10504 err = got_object_open_as_commit(&commit, repo, id);
10505 if (err)
10506 return err;
10508 err = got_object_id_str(&id_str, id);
10509 if (err)
10510 goto done;
10512 id_str[12] = '\0';
10514 err = get_short_logmsg(&logmsg, 42, commit);
10515 if (err)
10516 goto done;
10518 printf("%s -> merge conflict: %s\n", id_str, logmsg);
10519 done:
10520 free(id_str);
10521 got_object_commit_close(commit);
10522 free(logmsg);
10523 return err;
10526 static const struct got_error *
10527 show_rebase_progress(struct got_commit_object *commit,
10528 struct got_object_id *old_id, struct got_object_id *new_id)
10530 const struct got_error *err;
10531 char *old_id_str = NULL, *new_id_str = NULL, *logmsg = NULL;
10533 err = got_object_id_str(&old_id_str, old_id);
10534 if (err)
10535 goto done;
10537 if (new_id) {
10538 err = got_object_id_str(&new_id_str, new_id);
10539 if (err)
10540 goto done;
10543 old_id_str[12] = '\0';
10544 if (new_id_str)
10545 new_id_str[12] = '\0';
10547 err = get_short_logmsg(&logmsg, 42, commit);
10548 if (err)
10549 goto done;
10551 printf("%s -> %s: %s\n", old_id_str,
10552 new_id_str ? new_id_str : "no-op change", logmsg);
10553 done:
10554 free(old_id_str);
10555 free(new_id_str);
10556 free(logmsg);
10557 return err;
10560 static const struct got_error *
10561 rebase_complete(struct got_worktree *worktree, struct got_fileindex *fileindex,
10562 struct got_reference *branch, struct got_reference *tmp_branch,
10563 struct got_repository *repo, int create_backup)
10565 printf("Switching work tree to %s\n", got_ref_get_name(branch));
10566 return got_worktree_rebase_complete(worktree, fileindex,
10567 tmp_branch, branch, repo, create_backup);
10570 static const struct got_error *
10571 rebase_commit(struct got_pathlist_head *merged_paths,
10572 struct got_worktree *worktree, struct got_fileindex *fileindex,
10573 struct got_reference *tmp_branch, const char *committer,
10574 struct got_object_id *commit_id, int allow_conflict,
10575 struct got_repository *repo)
10577 const struct got_error *error;
10578 struct got_commit_object *commit;
10579 struct got_object_id *new_commit_id;
10581 error = got_object_open_as_commit(&commit, repo, commit_id);
10582 if (error)
10583 return error;
10585 error = got_worktree_rebase_commit(&new_commit_id, merged_paths,
10586 worktree, fileindex, tmp_branch, committer, commit, commit_id,
10587 allow_conflict, repo);
10588 if (error) {
10589 if (error->code != GOT_ERR_COMMIT_NO_CHANGES)
10590 goto done;
10591 error = show_rebase_progress(commit, commit_id, NULL);
10592 } else {
10593 error = show_rebase_progress(commit, commit_id, new_commit_id);
10594 free(new_commit_id);
10596 done:
10597 got_object_commit_close(commit);
10598 return error;
10601 struct check_path_prefix_arg {
10602 const char *path_prefix;
10603 size_t len;
10604 int errcode;
10607 static const struct got_error *
10608 check_path_prefix_in_diff(void *arg, struct got_blob_object *blob1,
10609 struct got_blob_object *blob2, FILE *f1, FILE *f2,
10610 struct got_object_id *id1, struct got_object_id *id2,
10611 const char *path1, const char *path2,
10612 mode_t mode1, mode_t mode2, struct got_repository *repo)
10614 struct check_path_prefix_arg *a = arg;
10616 if ((path1 && !got_path_is_child(path1, a->path_prefix, a->len)) ||
10617 (path2 && !got_path_is_child(path2, a->path_prefix, a->len)))
10618 return got_error(a->errcode);
10620 return NULL;
10623 static const struct got_error *
10624 check_path_prefix(struct got_object_id *parent_id,
10625 struct got_object_id *commit_id, const char *path_prefix,
10626 int errcode, struct got_repository *repo)
10628 const struct got_error *err;
10629 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
10630 struct got_commit_object *commit = NULL, *parent_commit = NULL;
10631 struct check_path_prefix_arg cpp_arg;
10633 if (got_path_is_root_dir(path_prefix))
10634 return NULL;
10636 err = got_object_open_as_commit(&commit, repo, commit_id);
10637 if (err)
10638 goto done;
10640 err = got_object_open_as_commit(&parent_commit, repo, parent_id);
10641 if (err)
10642 goto done;
10644 err = got_object_open_as_tree(&tree1, repo,
10645 got_object_commit_get_tree_id(parent_commit));
10646 if (err)
10647 goto done;
10649 err = got_object_open_as_tree(&tree2, repo,
10650 got_object_commit_get_tree_id(commit));
10651 if (err)
10652 goto done;
10654 cpp_arg.path_prefix = path_prefix;
10655 while (cpp_arg.path_prefix[0] == '/')
10656 cpp_arg.path_prefix++;
10657 cpp_arg.len = strlen(cpp_arg.path_prefix);
10658 cpp_arg.errcode = errcode;
10659 err = got_diff_tree(tree1, tree2, NULL, NULL, -1, -1, "", "", repo,
10660 check_path_prefix_in_diff, &cpp_arg, 0);
10661 done:
10662 if (tree1)
10663 got_object_tree_close(tree1);
10664 if (tree2)
10665 got_object_tree_close(tree2);
10666 if (commit)
10667 got_object_commit_close(commit);
10668 if (parent_commit)
10669 got_object_commit_close(parent_commit);
10670 return err;
10673 static const struct got_error *
10674 collect_commits(struct got_object_id_queue *commits,
10675 struct got_object_id *initial_commit_id,
10676 struct got_object_id *iter_start_id, struct got_object_id *iter_stop_id,
10677 const char *path_prefix, int path_prefix_errcode,
10678 struct got_repository *repo)
10680 const struct got_error *err = NULL;
10681 struct got_commit_graph *graph = NULL;
10682 struct got_object_id parent_id, commit_id;
10683 struct got_object_qid *qid;
10685 err = got_commit_graph_open(&graph, "/", 1);
10686 if (err)
10687 return err;
10689 err = got_commit_graph_iter_start(graph, iter_start_id, repo,
10690 check_cancelled, NULL);
10691 if (err)
10692 goto done;
10694 memcpy(&commit_id, initial_commit_id, sizeof(commit_id));
10695 while (got_object_id_cmp(&commit_id, iter_stop_id) != 0) {
10696 err = got_commit_graph_iter_next(&parent_id, graph, repo,
10697 check_cancelled, NULL);
10698 if (err) {
10699 if (err->code == GOT_ERR_ITER_COMPLETED) {
10700 err = got_error_msg(GOT_ERR_ANCESTRY,
10701 "ran out of commits to rebase before "
10702 "youngest common ancestor commit has "
10703 "been reached?!?");
10705 goto done;
10706 } else {
10707 err = check_path_prefix(&parent_id, &commit_id,
10708 path_prefix, path_prefix_errcode, repo);
10709 if (err)
10710 goto done;
10712 err = got_object_qid_alloc(&qid, &commit_id);
10713 if (err)
10714 goto done;
10715 STAILQ_INSERT_HEAD(commits, qid, entry);
10717 memcpy(&commit_id, &parent_id, sizeof(commit_id));
10720 done:
10721 got_commit_graph_close(graph);
10722 return err;
10725 static const struct got_error *
10726 get_commit_brief_str(char **brief_str, struct got_commit_object *commit)
10728 const struct got_error *err = NULL;
10729 time_t committer_time;
10730 struct tm tm;
10731 char datebuf[11]; /* YYYY-MM-DD + NUL */
10732 char *author0 = NULL, *author, *smallerthan;
10733 char *logmsg0 = NULL, *logmsg, *newline;
10735 committer_time = got_object_commit_get_committer_time(commit);
10736 if (gmtime_r(&committer_time, &tm) == NULL)
10737 return got_error_from_errno("gmtime_r");
10738 if (strftime(datebuf, sizeof(datebuf), "%G-%m-%d", &tm) == 0)
10739 return got_error(GOT_ERR_NO_SPACE);
10741 author0 = strdup(got_object_commit_get_author(commit));
10742 if (author0 == NULL)
10743 return got_error_from_errno("strdup");
10744 author = author0;
10745 smallerthan = strchr(author, '<');
10746 if (smallerthan && smallerthan[1] != '\0')
10747 author = smallerthan + 1;
10748 author[strcspn(author, "@>")] = '\0';
10750 err = got_object_commit_get_logmsg(&logmsg0, commit);
10751 if (err)
10752 goto done;
10753 logmsg = logmsg0;
10754 while (*logmsg == '\n')
10755 logmsg++;
10756 newline = strchr(logmsg, '\n');
10757 if (newline)
10758 *newline = '\0';
10760 if (asprintf(brief_str, "%s %s %s",
10761 datebuf, author, logmsg) == -1)
10762 err = got_error_from_errno("asprintf");
10763 done:
10764 free(author0);
10765 free(logmsg0);
10766 return err;
10769 static const struct got_error *
10770 delete_backup_ref(struct got_reference *ref, struct got_object_id *id,
10771 struct got_repository *repo)
10773 const struct got_error *err;
10774 char *id_str;
10776 err = got_object_id_str(&id_str, id);
10777 if (err)
10778 return err;
10780 err = got_ref_delete(ref, repo);
10781 if (err)
10782 goto done;
10784 printf("Deleted %s: %s\n", got_ref_get_name(ref), id_str);
10785 done:
10786 free(id_str);
10787 return err;
10790 static const struct got_error *
10791 print_backup_ref(const char *branch_name, const char *new_id_str,
10792 struct got_object_id *old_commit_id, struct got_commit_object *old_commit,
10793 struct got_reflist_object_id_map *refs_idmap,
10794 struct got_repository *repo)
10796 const struct got_error *err = NULL;
10797 struct got_reflist_head *refs;
10798 char *refs_str = NULL;
10799 struct got_object_id *new_commit_id = NULL;
10800 struct got_commit_object *new_commit = NULL;
10801 char *new_commit_brief_str = NULL;
10802 struct got_object_id *yca_id = NULL;
10803 struct got_commit_object *yca_commit = NULL;
10804 char *yca_id_str = NULL, *yca_brief_str = NULL;
10805 char *custom_refs_str;
10807 if (asprintf(&custom_refs_str, "formerly %s", branch_name) == -1)
10808 return got_error_from_errno("asprintf");
10810 err = print_commit(old_commit, old_commit_id, repo, NULL, NULL, NULL,
10811 0, 0, refs_idmap, custom_refs_str, NULL);
10812 if (err)
10813 goto done;
10815 err = got_object_resolve_id_str(&new_commit_id, repo, new_id_str);
10816 if (err)
10817 goto done;
10819 refs = got_reflist_object_id_map_lookup(refs_idmap, new_commit_id);
10820 if (refs) {
10821 err = build_refs_str(&refs_str, refs, new_commit_id, repo, 0);
10822 if (err)
10823 goto done;
10826 err = got_object_open_as_commit(&new_commit, repo, new_commit_id);
10827 if (err)
10828 goto done;
10830 err = get_commit_brief_str(&new_commit_brief_str, new_commit);
10831 if (err)
10832 goto done;
10834 err = got_commit_graph_find_youngest_common_ancestor(&yca_id,
10835 old_commit_id, new_commit_id, 1, repo, check_cancelled, NULL);
10836 if (err)
10837 goto done;
10839 printf("has become commit %s%s%s%s\n %s\n", new_id_str,
10840 refs_str ? " (" : "", refs_str ? refs_str : "",
10841 refs_str ? ")" : "", new_commit_brief_str);
10842 if (yca_id && got_object_id_cmp(yca_id, new_commit_id) != 0 &&
10843 got_object_id_cmp(yca_id, old_commit_id) != 0) {
10844 free(refs_str);
10845 refs_str = NULL;
10847 err = got_object_open_as_commit(&yca_commit, repo, yca_id);
10848 if (err)
10849 goto done;
10851 err = get_commit_brief_str(&yca_brief_str, yca_commit);
10852 if (err)
10853 goto done;
10855 err = got_object_id_str(&yca_id_str, yca_id);
10856 if (err)
10857 goto done;
10859 refs = got_reflist_object_id_map_lookup(refs_idmap, yca_id);
10860 if (refs) {
10861 err = build_refs_str(&refs_str, refs, yca_id, repo, 0);
10862 if (err)
10863 goto done;
10865 printf("history forked at %s%s%s%s\n %s\n",
10866 yca_id_str,
10867 refs_str ? " (" : "", refs_str ? refs_str : "",
10868 refs_str ? ")" : "", yca_brief_str);
10870 done:
10871 free(custom_refs_str);
10872 free(new_commit_id);
10873 free(refs_str);
10874 free(yca_id);
10875 free(yca_id_str);
10876 free(yca_brief_str);
10877 if (new_commit)
10878 got_object_commit_close(new_commit);
10879 if (yca_commit)
10880 got_object_commit_close(yca_commit);
10882 return err;
10885 static const struct got_error *
10886 worktree_has_logmsg_ref(const char *caller, struct got_worktree *worktree,
10887 struct got_repository *repo)
10889 const struct got_error *err;
10890 struct got_reflist_head refs;
10891 struct got_reflist_entry *re;
10892 char *uuidstr = NULL;
10893 static char msg[160];
10895 TAILQ_INIT(&refs);
10897 err = got_worktree_get_uuid(&uuidstr, worktree);
10898 if (err)
10899 goto done;
10901 err = got_ref_list(&refs, repo, "refs/got/worktree",
10902 got_ref_cmp_by_name, repo);
10903 if (err)
10904 goto done;
10906 TAILQ_FOREACH(re, &refs, entry) {
10907 const char *cmd, *refname, *type;
10909 refname = got_ref_get_name(re->ref);
10911 if (strncmp(refname, GOT_WORKTREE_CHERRYPICK_REF_PREFIX,
10912 GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN) == 0) {
10913 refname += GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN + 1;
10914 cmd = "cherrypick";
10915 type = "cherrypicked";
10916 } else if (strncmp(refname, GOT_WORKTREE_BACKOUT_REF_PREFIX,
10917 GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN) == 0) {
10918 refname += GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN + 1;
10919 cmd = "backout";
10920 type = "backed-out";
10921 } else
10922 continue;
10924 if (strncmp(refname, uuidstr, GOT_WORKTREE_UUID_STRLEN) != 0)
10925 continue;
10927 snprintf(msg, sizeof(msg),
10928 "work tree has references created by %s commits which "
10929 "must be removed with 'got %s -X' before running the %s "
10930 "command", type, cmd, caller);
10931 err = got_error_msg(GOT_ERR_WORKTREE_META, msg);
10932 goto done;
10935 done:
10936 free(uuidstr);
10937 got_ref_list_free(&refs);
10938 return err;
10941 static const struct got_error *
10942 process_backup_refs(const char *backup_ref_prefix,
10943 const char *wanted_branch_name,
10944 int delete, struct got_repository *repo)
10946 const struct got_error *err;
10947 struct got_reflist_head refs, backup_refs;
10948 struct got_reflist_entry *re;
10949 const size_t backup_ref_prefix_len = strlen(backup_ref_prefix);
10950 struct got_object_id *old_commit_id = NULL;
10951 char *branch_name = NULL;
10952 struct got_commit_object *old_commit = NULL;
10953 struct got_reflist_object_id_map *refs_idmap = NULL;
10954 int wanted_branch_found = 0;
10956 TAILQ_INIT(&refs);
10957 TAILQ_INIT(&backup_refs);
10959 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
10960 if (err)
10961 return err;
10963 err = got_reflist_object_id_map_create(&refs_idmap, &refs, repo);
10964 if (err)
10965 goto done;
10967 if (wanted_branch_name) {
10968 if (strncmp(wanted_branch_name, "refs/heads/", 11) == 0)
10969 wanted_branch_name += 11;
10972 err = got_ref_list(&backup_refs, repo, backup_ref_prefix,
10973 got_ref_cmp_by_commit_timestamp_descending, repo);
10974 if (err)
10975 goto done;
10977 TAILQ_FOREACH(re, &backup_refs, entry) {
10978 const char *refname = got_ref_get_name(re->ref);
10979 char *slash;
10981 err = check_cancelled(NULL);
10982 if (err)
10983 break;
10985 err = got_ref_resolve(&old_commit_id, repo, re->ref);
10986 if (err)
10987 break;
10989 err = got_object_open_as_commit(&old_commit, repo,
10990 old_commit_id);
10991 if (err)
10992 break;
10994 if (strncmp(backup_ref_prefix, refname,
10995 backup_ref_prefix_len) == 0)
10996 refname += backup_ref_prefix_len;
10998 while (refname[0] == '/')
10999 refname++;
11001 branch_name = strdup(refname);
11002 if (branch_name == NULL) {
11003 err = got_error_from_errno("strdup");
11004 break;
11006 slash = strrchr(branch_name, '/');
11007 if (slash) {
11008 *slash = '\0';
11009 refname += strlen(branch_name) + 1;
11012 if (wanted_branch_name == NULL ||
11013 strcmp(wanted_branch_name, branch_name) == 0) {
11014 wanted_branch_found = 1;
11015 if (delete) {
11016 err = delete_backup_ref(re->ref,
11017 old_commit_id, repo);
11018 } else {
11019 err = print_backup_ref(branch_name, refname,
11020 old_commit_id, old_commit, refs_idmap,
11021 repo);
11023 if (err)
11024 break;
11027 free(old_commit_id);
11028 old_commit_id = NULL;
11029 free(branch_name);
11030 branch_name = NULL;
11031 got_object_commit_close(old_commit);
11032 old_commit = NULL;
11035 if (wanted_branch_name && !wanted_branch_found) {
11036 err = got_error_fmt(GOT_ERR_NOT_REF,
11037 "%s/%s/", backup_ref_prefix, wanted_branch_name);
11039 done:
11040 if (refs_idmap)
11041 got_reflist_object_id_map_free(refs_idmap);
11042 got_ref_list_free(&refs);
11043 got_ref_list_free(&backup_refs);
11044 free(old_commit_id);
11045 free(branch_name);
11046 if (old_commit)
11047 got_object_commit_close(old_commit);
11048 return err;
11051 static const struct got_error *
11052 abort_progress(void *arg, unsigned char status, const char *path)
11055 * Unversioned files should not clutter progress output when
11056 * an operation is aborted.
11058 if (status == GOT_STATUS_UNVERSIONED)
11059 return NULL;
11061 return update_progress(arg, status, path);
11064 static const struct got_error *
11065 cmd_rebase(int argc, char *argv[])
11067 const struct got_error *error = NULL;
11068 struct got_worktree *worktree = NULL;
11069 struct got_repository *repo = NULL;
11070 struct got_fileindex *fileindex = NULL;
11071 char *cwd = NULL, *committer = NULL, *gitconfig_path = NULL;
11072 struct got_reference *branch = NULL;
11073 struct got_reference *new_base_branch = NULL, *tmp_branch = NULL;
11074 struct got_object_id *commit_id = NULL, *parent_id = NULL;
11075 struct got_object_id *resume_commit_id = NULL;
11076 struct got_object_id *branch_head_commit_id = NULL, *yca_id = NULL;
11077 struct got_object_id *head_commit_id = NULL;
11078 struct got_reference *head_ref = NULL;
11079 struct got_commit_object *commit = NULL;
11080 int ch, rebase_in_progress = 0, abort_rebase = 0, continue_rebase = 0;
11081 int histedit_in_progress = 0, merge_in_progress = 0;
11082 int create_backup = 1, list_backups = 0, delete_backups = 0;
11083 int allow_conflict = 0;
11084 struct got_object_id_queue commits;
11085 struct got_pathlist_head merged_paths;
11086 const struct got_object_id_queue *parent_ids;
11087 struct got_object_qid *qid, *pid;
11088 struct got_update_progress_arg upa;
11089 int *pack_fds = NULL;
11091 STAILQ_INIT(&commits);
11092 TAILQ_INIT(&merged_paths);
11093 memset(&upa, 0, sizeof(upa));
11095 #ifndef PROFILE
11096 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
11097 "unveil", NULL) == -1)
11098 err(1, "pledge");
11099 #endif
11101 while ((ch = getopt(argc, argv, "aCclX")) != -1) {
11102 switch (ch) {
11103 case 'a':
11104 abort_rebase = 1;
11105 break;
11106 case 'C':
11107 allow_conflict = 1;
11108 break;
11109 case 'c':
11110 continue_rebase = 1;
11111 break;
11112 case 'l':
11113 list_backups = 1;
11114 break;
11115 case 'X':
11116 delete_backups = 1;
11117 break;
11118 default:
11119 usage_rebase();
11120 /* NOTREACHED */
11124 argc -= optind;
11125 argv += optind;
11127 if (list_backups) {
11128 if (abort_rebase)
11129 option_conflict('l', 'a');
11130 if (allow_conflict)
11131 option_conflict('l', 'C');
11132 if (continue_rebase)
11133 option_conflict('l', 'c');
11134 if (delete_backups)
11135 option_conflict('l', 'X');
11136 if (argc != 0 && argc != 1)
11137 usage_rebase();
11138 } else if (delete_backups) {
11139 if (abort_rebase)
11140 option_conflict('X', 'a');
11141 if (allow_conflict)
11142 option_conflict('X', 'C');
11143 if (continue_rebase)
11144 option_conflict('X', 'c');
11145 if (list_backups)
11146 option_conflict('l', 'X');
11147 if (argc != 0 && argc != 1)
11148 usage_rebase();
11149 } else if (allow_conflict) {
11150 if (abort_rebase)
11151 option_conflict('C', 'a');
11152 if (!continue_rebase)
11153 errx(1, "-C option requires -c");
11154 } else {
11155 if (abort_rebase && continue_rebase)
11156 usage_rebase();
11157 else if (abort_rebase || continue_rebase) {
11158 if (argc != 0)
11159 usage_rebase();
11160 } else if (argc != 1)
11161 usage_rebase();
11164 cwd = getcwd(NULL, 0);
11165 if (cwd == NULL) {
11166 error = got_error_from_errno("getcwd");
11167 goto done;
11170 error = got_repo_pack_fds_open(&pack_fds);
11171 if (error != NULL)
11172 goto done;
11174 error = got_worktree_open(&worktree, cwd);
11175 if (error) {
11176 if (list_backups || delete_backups) {
11177 if (error->code != GOT_ERR_NOT_WORKTREE)
11178 goto done;
11179 } else {
11180 if (error->code == GOT_ERR_NOT_WORKTREE)
11181 error = wrap_not_worktree_error(error,
11182 "rebase", cwd);
11183 goto done;
11187 error = get_gitconfig_path(&gitconfig_path);
11188 if (error)
11189 goto done;
11190 error = got_repo_open(&repo,
11191 worktree ? got_worktree_get_repo_path(worktree) : cwd,
11192 gitconfig_path, pack_fds);
11193 if (error != NULL)
11194 goto done;
11196 if (worktree != NULL && !list_backups && !delete_backups) {
11197 error = worktree_has_logmsg_ref("rebase", worktree, repo);
11198 if (error)
11199 goto done;
11202 error = get_author(&committer, repo, worktree);
11203 if (error && error->code != GOT_ERR_COMMIT_NO_AUTHOR)
11204 goto done;
11206 error = apply_unveil(got_repo_get_path(repo), 0,
11207 worktree ? got_worktree_get_root_path(worktree) : NULL);
11208 if (error)
11209 goto done;
11211 if (list_backups || delete_backups) {
11212 error = process_backup_refs(
11213 GOT_WORKTREE_REBASE_BACKUP_REF_PREFIX,
11214 argc == 1 ? argv[0] : NULL, delete_backups, repo);
11215 goto done; /* nothing else to do */
11218 error = got_worktree_histedit_in_progress(&histedit_in_progress,
11219 worktree);
11220 if (error)
11221 goto done;
11222 if (histedit_in_progress) {
11223 error = got_error(GOT_ERR_HISTEDIT_BUSY);
11224 goto done;
11227 error = got_worktree_merge_in_progress(&merge_in_progress,
11228 worktree, repo);
11229 if (error)
11230 goto done;
11231 if (merge_in_progress) {
11232 error = got_error(GOT_ERR_MERGE_BUSY);
11233 goto done;
11236 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
11237 if (error)
11238 goto done;
11240 if (abort_rebase) {
11241 if (!rebase_in_progress) {
11242 error = got_error(GOT_ERR_NOT_REBASING);
11243 goto done;
11245 error = got_worktree_rebase_continue(&resume_commit_id,
11246 &new_base_branch, &tmp_branch, &branch, &fileindex,
11247 worktree, repo);
11248 if (error)
11249 goto done;
11250 printf("Switching work tree to %s\n",
11251 got_ref_get_symref_target(new_base_branch));
11252 error = got_worktree_rebase_abort(worktree, fileindex, repo,
11253 new_base_branch, abort_progress, &upa);
11254 if (error)
11255 goto done;
11256 printf("Rebase of %s aborted\n", got_ref_get_name(branch));
11257 print_merge_progress_stats(&upa);
11258 goto done; /* nothing else to do */
11261 if (continue_rebase) {
11262 if (!rebase_in_progress) {
11263 error = got_error(GOT_ERR_NOT_REBASING);
11264 goto done;
11266 error = got_worktree_rebase_continue(&resume_commit_id,
11267 &new_base_branch, &tmp_branch, &branch, &fileindex,
11268 worktree, repo);
11269 if (error)
11270 goto done;
11272 error = rebase_commit(NULL, worktree, fileindex, tmp_branch,
11273 committer, resume_commit_id, allow_conflict, repo);
11274 if (error)
11275 goto done;
11277 yca_id = got_object_id_dup(resume_commit_id);
11278 if (yca_id == NULL) {
11279 error = got_error_from_errno("got_object_id_dup");
11280 goto done;
11282 } else {
11283 error = got_ref_open(&branch, repo, argv[0], 0);
11284 if (error != NULL)
11285 goto done;
11286 if (strncmp(got_ref_get_name(branch), "refs/heads/", 11) != 0) {
11287 error = got_error_msg(GOT_ERR_COMMIT_BRANCH,
11288 "will not rebase a branch which lives outside "
11289 "the \"refs/heads/\" reference namespace");
11290 goto done;
11294 error = got_ref_resolve(&branch_head_commit_id, repo, branch);
11295 if (error)
11296 goto done;
11298 if (!continue_rebase) {
11299 struct got_object_id *base_commit_id;
11301 error = got_ref_open(&head_ref, repo,
11302 got_worktree_get_head_ref_name(worktree), 0);
11303 if (error)
11304 goto done;
11305 error = got_ref_resolve(&head_commit_id, repo, head_ref);
11306 if (error)
11307 goto done;
11308 base_commit_id = got_worktree_get_base_commit_id(worktree);
11309 if (got_object_id_cmp(base_commit_id, head_commit_id) != 0) {
11310 error = got_error(GOT_ERR_REBASE_OUT_OF_DATE);
11311 goto done;
11314 error = got_commit_graph_find_youngest_common_ancestor(&yca_id,
11315 base_commit_id, branch_head_commit_id, 1, repo,
11316 check_cancelled, NULL);
11317 if (error) {
11318 if (error->code == GOT_ERR_ANCESTRY) {
11319 error = got_error_msg(GOT_ERR_ANCESTRY,
11320 "specified branch shares no common "
11321 "ancestry with work tree's branch");
11323 goto done;
11326 error = check_same_branch(base_commit_id, branch, yca_id, repo);
11327 if (error) {
11328 if (error->code != GOT_ERR_ANCESTRY)
11329 goto done;
11330 error = NULL;
11331 } else {
11332 struct got_pathlist_head paths;
11333 printf("%s is already based on %s\n",
11334 got_ref_get_name(branch),
11335 got_worktree_get_head_ref_name(worktree));
11336 error = switch_head_ref(branch, branch_head_commit_id,
11337 worktree, repo);
11338 if (error)
11339 goto done;
11340 error = got_worktree_set_base_commit_id(worktree, repo,
11341 branch_head_commit_id);
11342 if (error)
11343 goto done;
11344 TAILQ_INIT(&paths);
11345 error = got_pathlist_append(&paths, "", NULL);
11346 if (error)
11347 goto done;
11348 error = got_worktree_checkout_files(worktree,
11349 &paths, repo, update_progress, &upa,
11350 check_cancelled, NULL);
11351 got_pathlist_free(&paths, GOT_PATHLIST_FREE_NONE);
11352 if (error)
11353 goto done;
11354 if (upa.did_something) {
11355 char *id_str;
11356 error = got_object_id_str(&id_str,
11357 branch_head_commit_id);
11358 if (error)
11359 goto done;
11360 printf("Updated to %s: %s\n",
11361 got_worktree_get_head_ref_name(worktree),
11362 id_str);
11363 free(id_str);
11364 } else
11365 printf("Already up-to-date\n");
11366 print_update_progress_stats(&upa);
11367 goto done;
11371 commit_id = branch_head_commit_id;
11372 error = got_object_open_as_commit(&commit, repo, commit_id);
11373 if (error)
11374 goto done;
11376 parent_ids = got_object_commit_get_parent_ids(commit);
11377 pid = STAILQ_FIRST(parent_ids);
11378 if (pid) {
11379 error = collect_commits(&commits, commit_id, &pid->id,
11380 yca_id, got_worktree_get_path_prefix(worktree),
11381 GOT_ERR_REBASE_PATH, repo);
11382 if (error)
11383 goto done;
11386 got_object_commit_close(commit);
11387 commit = NULL;
11389 if (!continue_rebase) {
11390 error = got_worktree_rebase_prepare(&new_base_branch,
11391 &tmp_branch, &fileindex, worktree, branch, repo);
11392 if (error)
11393 goto done;
11396 if (STAILQ_EMPTY(&commits)) {
11397 if (continue_rebase) {
11398 error = rebase_complete(worktree, fileindex,
11399 branch, tmp_branch, repo, create_backup);
11400 goto done;
11401 } else {
11402 /* Fast-forward the reference of the branch. */
11403 struct got_object_id *new_head_commit_id;
11404 char *id_str;
11405 error = got_ref_resolve(&new_head_commit_id, repo,
11406 new_base_branch);
11407 if (error)
11408 goto done;
11409 error = got_object_id_str(&id_str, new_head_commit_id);
11410 if (error)
11411 goto done;
11412 printf("Forwarding %s to commit %s\n",
11413 got_ref_get_name(branch), id_str);
11414 free(id_str);
11415 error = got_ref_change_ref(branch,
11416 new_head_commit_id);
11417 if (error)
11418 goto done;
11419 /* No backup needed since objects did not change. */
11420 create_backup = 0;
11424 pid = NULL;
11425 STAILQ_FOREACH(qid, &commits, entry) {
11427 commit_id = &qid->id;
11428 parent_id = pid ? &pid->id : yca_id;
11429 pid = qid;
11431 memset(&upa, 0, sizeof(upa));
11432 error = got_worktree_rebase_merge_files(&merged_paths,
11433 worktree, fileindex, parent_id, commit_id, repo,
11434 update_progress, &upa, check_cancelled, NULL);
11435 if (error)
11436 goto done;
11438 print_merge_progress_stats(&upa);
11439 if (upa.conflicts > 0 || upa.missing > 0 ||
11440 upa.not_deleted > 0 || upa.unversioned > 0) {
11441 if (upa.conflicts > 0) {
11442 error = show_rebase_merge_conflict(&qid->id,
11443 repo);
11444 if (error)
11445 goto done;
11447 got_pathlist_free(&merged_paths, GOT_PATHLIST_FREE_PATH);
11448 break;
11451 error = rebase_commit(&merged_paths, worktree, fileindex,
11452 tmp_branch, committer, commit_id, 0, repo);
11453 got_pathlist_free(&merged_paths, GOT_PATHLIST_FREE_PATH);
11454 if (error)
11455 goto done;
11458 if (upa.conflicts > 0 || upa.missing > 0 ||
11459 upa.not_deleted > 0 || upa.unversioned > 0) {
11460 error = got_worktree_rebase_postpone(worktree, fileindex);
11461 if (error)
11462 goto done;
11463 if (upa.conflicts > 0 && upa.missing == 0 &&
11464 upa.not_deleted == 0 && upa.unversioned == 0) {
11465 error = got_error_msg(GOT_ERR_CONFLICTS,
11466 "conflicts must be resolved before rebasing "
11467 "can continue");
11468 } else if (upa.conflicts > 0) {
11469 error = got_error_msg(GOT_ERR_CONFLICTS,
11470 "conflicts must be resolved before rebasing "
11471 "can continue; changes destined for some "
11472 "files were not yet merged and should be "
11473 "merged manually if required before the "
11474 "rebase operation is continued");
11475 } else {
11476 error = got_error_msg(GOT_ERR_CONFLICTS,
11477 "changes destined for some files were not "
11478 "yet merged and should be merged manually "
11479 "if required before the rebase operation "
11480 "is continued");
11482 } else
11483 error = rebase_complete(worktree, fileindex, branch,
11484 tmp_branch, repo, create_backup);
11485 done:
11486 free(cwd);
11487 free(committer);
11488 free(gitconfig_path);
11489 got_object_id_queue_free(&commits);
11490 free(branch_head_commit_id);
11491 free(resume_commit_id);
11492 free(head_commit_id);
11493 free(yca_id);
11494 if (commit)
11495 got_object_commit_close(commit);
11496 if (branch)
11497 got_ref_close(branch);
11498 if (new_base_branch)
11499 got_ref_close(new_base_branch);
11500 if (tmp_branch)
11501 got_ref_close(tmp_branch);
11502 if (head_ref)
11503 got_ref_close(head_ref);
11504 if (worktree)
11505 got_worktree_close(worktree);
11506 if (repo) {
11507 const struct got_error *close_err = got_repo_close(repo);
11508 if (error == NULL)
11509 error = close_err;
11511 if (pack_fds) {
11512 const struct got_error *pack_err =
11513 got_repo_pack_fds_close(pack_fds);
11514 if (error == NULL)
11515 error = pack_err;
11517 return error;
11520 __dead static void
11521 usage_histedit(void)
11523 fprintf(stderr, "usage: %s histedit [-aCcdeflmX] [-F histedit-script] "
11524 "[branch]\n", getprogname());
11525 exit(1);
11528 #define GOT_HISTEDIT_PICK 'p'
11529 #define GOT_HISTEDIT_EDIT 'e'
11530 #define GOT_HISTEDIT_FOLD 'f'
11531 #define GOT_HISTEDIT_DROP 'd'
11532 #define GOT_HISTEDIT_MESG 'm'
11534 static const struct got_histedit_cmd {
11535 unsigned char code;
11536 const char *name;
11537 const char *desc;
11538 } got_histedit_cmds[] = {
11539 { GOT_HISTEDIT_PICK, "pick", "use commit" },
11540 { GOT_HISTEDIT_EDIT, "edit", "use commit but stop for amending" },
11541 { GOT_HISTEDIT_FOLD, "fold", "combine with next commit that will "
11542 "be used" },
11543 { GOT_HISTEDIT_DROP, "drop", "remove commit from history" },
11544 { GOT_HISTEDIT_MESG, "mesg",
11545 "single-line log message for commit above (open editor if empty)" },
11548 struct got_histedit_list_entry {
11549 TAILQ_ENTRY(got_histedit_list_entry) entry;
11550 struct got_object_id *commit_id;
11551 const struct got_histedit_cmd *cmd;
11552 char *logmsg;
11554 TAILQ_HEAD(got_histedit_list, got_histedit_list_entry);
11556 static const struct got_error *
11557 histedit_write_commit(struct got_object_id *commit_id, const char *cmdname,
11558 FILE *f, struct got_repository *repo)
11560 const struct got_error *err = NULL;
11561 char *logmsg = NULL, *id_str = NULL;
11562 struct got_commit_object *commit = NULL;
11563 int n;
11565 err = got_object_open_as_commit(&commit, repo, commit_id);
11566 if (err)
11567 goto done;
11569 err = get_short_logmsg(&logmsg, 34, commit);
11570 if (err)
11571 goto done;
11573 err = got_object_id_str(&id_str, commit_id);
11574 if (err)
11575 goto done;
11577 n = fprintf(f, "%s %s %s\n", cmdname, id_str, logmsg);
11578 if (n < 0)
11579 err = got_ferror(f, GOT_ERR_IO);
11580 done:
11581 if (commit)
11582 got_object_commit_close(commit);
11583 free(id_str);
11584 free(logmsg);
11585 return err;
11588 static const struct got_error *
11589 histedit_write_commit_list(struct got_object_id_queue *commits,
11590 FILE *f, int edit_logmsg_only, int fold_only, int drop_only,
11591 int edit_only, struct got_repository *repo)
11593 const struct got_error *err = NULL;
11594 struct got_object_qid *qid;
11595 const char *histedit_cmd = NULL;
11597 if (STAILQ_EMPTY(commits))
11598 return got_error(GOT_ERR_EMPTY_HISTEDIT);
11600 STAILQ_FOREACH(qid, commits, entry) {
11601 histedit_cmd = got_histedit_cmds[0].name;
11602 if (drop_only)
11603 histedit_cmd = "drop";
11604 else if (edit_only)
11605 histedit_cmd = "edit";
11606 else if (fold_only && STAILQ_NEXT(qid, entry) != NULL)
11607 histedit_cmd = "fold";
11608 err = histedit_write_commit(&qid->id, histedit_cmd, f, repo);
11609 if (err)
11610 break;
11611 if (edit_logmsg_only) {
11612 int n = fprintf(f, "%c\n", GOT_HISTEDIT_MESG);
11613 if (n < 0) {
11614 err = got_ferror(f, GOT_ERR_IO);
11615 break;
11620 return err;
11623 static const struct got_error *
11624 write_cmd_list(FILE *f, const char *branch_name,
11625 struct got_object_id_queue *commits)
11627 const struct got_error *err = NULL;
11628 size_t i;
11629 int n;
11630 char *id_str;
11631 struct got_object_qid *qid;
11633 qid = STAILQ_FIRST(commits);
11634 err = got_object_id_str(&id_str, &qid->id);
11635 if (err)
11636 return err;
11638 n = fprintf(f,
11639 "# Editing the history of branch '%s' starting at\n"
11640 "# commit %s\n"
11641 "# Commits will be processed in order from top to "
11642 "bottom of this file.\n", branch_name, id_str);
11643 if (n < 0) {
11644 err = got_ferror(f, GOT_ERR_IO);
11645 goto done;
11648 n = fprintf(f, "# Available histedit commands:\n");
11649 if (n < 0) {
11650 err = got_ferror(f, GOT_ERR_IO);
11651 goto done;
11654 for (i = 0; i < nitems(got_histedit_cmds); i++) {
11655 const struct got_histedit_cmd *cmd = &got_histedit_cmds[i];
11656 n = fprintf(f, "# %s (%c): %s\n", cmd->name, cmd->code,
11657 cmd->desc);
11658 if (n < 0) {
11659 err = got_ferror(f, GOT_ERR_IO);
11660 break;
11663 done:
11664 free(id_str);
11665 return err;
11668 static const struct got_error *
11669 histedit_syntax_error(int lineno)
11671 static char msg[42];
11672 int ret;
11674 ret = snprintf(msg, sizeof(msg), "histedit syntax error on line %d",
11675 lineno);
11676 if (ret < 0 || (size_t)ret >= sizeof(msg))
11677 return got_error(GOT_ERR_HISTEDIT_SYNTAX);
11679 return got_error_msg(GOT_ERR_HISTEDIT_SYNTAX, msg);
11682 static const struct got_error *
11683 append_folded_commit_msg(char **new_msg, struct got_histedit_list_entry *hle,
11684 char *logmsg, struct got_repository *repo)
11686 const struct got_error *err;
11687 struct got_commit_object *folded_commit = NULL;
11688 char *id_str, *folded_logmsg = NULL;
11690 err = got_object_id_str(&id_str, hle->commit_id);
11691 if (err)
11692 return err;
11694 err = got_object_open_as_commit(&folded_commit, repo, hle->commit_id);
11695 if (err)
11696 goto done;
11698 err = got_object_commit_get_logmsg(&folded_logmsg, folded_commit);
11699 if (err)
11700 goto done;
11701 if (asprintf(new_msg, "%s%s# log message of folded commit %s: %s",
11702 logmsg ? logmsg : "", logmsg ? "\n" : "", id_str,
11703 folded_logmsg) == -1) {
11704 err = got_error_from_errno("asprintf");
11706 done:
11707 if (folded_commit)
11708 got_object_commit_close(folded_commit);
11709 free(id_str);
11710 free(folded_logmsg);
11711 return err;
11714 static struct got_histedit_list_entry *
11715 get_folded_commits(struct got_histedit_list_entry *hle)
11717 struct got_histedit_list_entry *prev, *folded = NULL;
11719 prev = TAILQ_PREV(hle, got_histedit_list, entry);
11720 while (prev && (prev->cmd->code == GOT_HISTEDIT_FOLD ||
11721 prev->cmd->code == GOT_HISTEDIT_DROP)) {
11722 if (prev->cmd->code == GOT_HISTEDIT_FOLD)
11723 folded = prev;
11724 prev = TAILQ_PREV(prev, got_histedit_list, entry);
11727 return folded;
11730 static const struct got_error *
11731 histedit_edit_logmsg(struct got_histedit_list_entry *hle,
11732 struct got_repository *repo)
11734 char *logmsg_path = NULL, *id_str = NULL, *orig_logmsg = NULL;
11735 char *logmsg = NULL, *new_msg = NULL, *editor = NULL;
11736 const struct got_error *err = NULL;
11737 struct got_commit_object *commit = NULL;
11738 int logmsg_len;
11739 int fd = -1;
11740 struct got_histedit_list_entry *folded = NULL;
11742 err = got_object_open_as_commit(&commit, repo, hle->commit_id);
11743 if (err)
11744 return err;
11746 folded = get_folded_commits(hle);
11747 if (folded) {
11748 while (folded != hle) {
11749 if (folded->cmd->code == GOT_HISTEDIT_DROP) {
11750 folded = TAILQ_NEXT(folded, entry);
11751 continue;
11753 err = append_folded_commit_msg(&new_msg, folded,
11754 logmsg, repo);
11755 if (err)
11756 goto done;
11757 free(logmsg);
11758 logmsg = new_msg;
11759 folded = TAILQ_NEXT(folded, entry);
11763 err = got_object_id_str(&id_str, hle->commit_id);
11764 if (err)
11765 goto done;
11766 err = got_object_commit_get_logmsg(&orig_logmsg, commit);
11767 if (err)
11768 goto done;
11769 logmsg_len = asprintf(&new_msg,
11770 "%s\n# original log message of commit %s: %s",
11771 logmsg ? logmsg : "", id_str, orig_logmsg);
11772 if (logmsg_len == -1) {
11773 err = got_error_from_errno("asprintf");
11774 goto done;
11776 free(logmsg);
11777 logmsg = new_msg;
11779 err = got_object_id_str(&id_str, hle->commit_id);
11780 if (err)
11781 goto done;
11783 err = got_opentemp_named_fd(&logmsg_path, &fd,
11784 GOT_TMPDIR_STR "/got-logmsg", "");
11785 if (err)
11786 goto done;
11788 if (write(fd, logmsg, logmsg_len) == -1) {
11789 err = got_error_from_errno2("write", logmsg_path);
11790 goto done;
11792 if (close(fd) == -1) {
11793 err = got_error_from_errno2("close", logmsg_path);
11794 goto done;
11796 fd = -1;
11798 err = get_editor(&editor);
11799 if (err)
11800 goto done;
11802 err = edit_logmsg(&hle->logmsg, editor, logmsg_path, logmsg,
11803 logmsg_len, 0);
11804 if (err) {
11805 if (err->code != GOT_ERR_COMMIT_MSG_EMPTY)
11806 goto done;
11807 err = NULL;
11808 hle->logmsg = strdup(new_msg);
11809 if (hle->logmsg == NULL)
11810 err = got_error_from_errno("strdup");
11812 done:
11813 if (fd != -1 && close(fd) == -1 && err == NULL)
11814 err = got_error_from_errno2("close", logmsg_path);
11815 if (logmsg_path && unlink(logmsg_path) != 0 && err == NULL)
11816 err = got_error_from_errno2("unlink", logmsg_path);
11817 free(logmsg_path);
11818 free(logmsg);
11819 free(orig_logmsg);
11820 free(editor);
11821 if (commit)
11822 got_object_commit_close(commit);
11823 return err;
11826 static const struct got_error *
11827 histedit_parse_list(struct got_histedit_list *histedit_cmds,
11828 FILE *f, struct got_repository *repo)
11830 const struct got_error *err = NULL;
11831 char *line = NULL, *p, *end;
11832 size_t i, linesize = 0;
11833 ssize_t linelen;
11834 int lineno = 0, lastcmd = -1;
11835 const struct got_histedit_cmd *cmd;
11836 struct got_object_id *commit_id = NULL;
11837 struct got_histedit_list_entry *hle = NULL;
11839 for (;;) {
11840 linelen = getline(&line, &linesize, f);
11841 if (linelen == -1) {
11842 const struct got_error *getline_err;
11843 if (feof(f))
11844 break;
11845 getline_err = got_error_from_errno("getline");
11846 err = got_ferror(f, getline_err->code);
11847 break;
11849 lineno++;
11850 p = line;
11851 while (isspace((unsigned char)p[0]))
11852 p++;
11853 if (p[0] == '#' || p[0] == '\0')
11854 continue;
11855 cmd = NULL;
11856 for (i = 0; i < nitems(got_histedit_cmds); i++) {
11857 cmd = &got_histedit_cmds[i];
11858 if (strncmp(cmd->name, p, strlen(cmd->name)) == 0 &&
11859 isspace((unsigned char)p[strlen(cmd->name)])) {
11860 p += strlen(cmd->name);
11861 break;
11863 if (p[0] == cmd->code && isspace((unsigned char)p[1])) {
11864 p++;
11865 break;
11868 if (i == nitems(got_histedit_cmds)) {
11869 err = histedit_syntax_error(lineno);
11870 break;
11872 while (isspace((unsigned char)p[0]))
11873 p++;
11874 if (cmd->code == GOT_HISTEDIT_MESG) {
11875 if (lastcmd != GOT_HISTEDIT_PICK &&
11876 lastcmd != GOT_HISTEDIT_EDIT) {
11877 err = got_error(GOT_ERR_HISTEDIT_CMD);
11878 break;
11880 if (p[0] == '\0') {
11881 err = histedit_edit_logmsg(hle, repo);
11882 if (err)
11883 break;
11884 } else {
11885 hle->logmsg = strdup(p);
11886 if (hle->logmsg == NULL) {
11887 err = got_error_from_errno("strdup");
11888 break;
11891 lastcmd = cmd->code;
11892 continue;
11893 } else {
11894 end = p;
11895 while (end[0] && !isspace((unsigned char)end[0]))
11896 end++;
11897 *end = '\0';
11899 err = got_object_resolve_id_str(&commit_id, repo, p);
11900 if (err) {
11901 /* override error code */
11902 err = histedit_syntax_error(lineno);
11903 break;
11906 hle = malloc(sizeof(*hle));
11907 if (hle == NULL) {
11908 err = got_error_from_errno("malloc");
11909 break;
11911 hle->cmd = cmd;
11912 hle->commit_id = commit_id;
11913 hle->logmsg = NULL;
11914 commit_id = NULL;
11915 TAILQ_INSERT_TAIL(histedit_cmds, hle, entry);
11916 lastcmd = cmd->code;
11919 free(line);
11920 free(commit_id);
11921 return err;
11924 static const struct got_error *
11925 histedit_check_script(struct got_histedit_list *histedit_cmds,
11926 struct got_object_id_queue *commits, struct got_repository *repo)
11928 const struct got_error *err = NULL;
11929 struct got_object_qid *qid;
11930 struct got_histedit_list_entry *hle;
11931 static char msg[92];
11932 char *id_str;
11934 if (TAILQ_EMPTY(histedit_cmds))
11935 return got_error_msg(GOT_ERR_EMPTY_HISTEDIT,
11936 "histedit script contains no commands");
11937 if (STAILQ_EMPTY(commits))
11938 return got_error(GOT_ERR_EMPTY_HISTEDIT);
11940 TAILQ_FOREACH(hle, histedit_cmds, entry) {
11941 struct got_histedit_list_entry *hle2;
11942 TAILQ_FOREACH(hle2, histedit_cmds, entry) {
11943 if (hle == hle2)
11944 continue;
11945 if (got_object_id_cmp(hle->commit_id,
11946 hle2->commit_id) != 0)
11947 continue;
11948 err = got_object_id_str(&id_str, hle->commit_id);
11949 if (err)
11950 return err;
11951 snprintf(msg, sizeof(msg), "commit %s is listed "
11952 "more than once in histedit script", id_str);
11953 free(id_str);
11954 return got_error_msg(GOT_ERR_HISTEDIT_CMD, msg);
11958 STAILQ_FOREACH(qid, commits, entry) {
11959 TAILQ_FOREACH(hle, histedit_cmds, entry) {
11960 if (got_object_id_cmp(&qid->id, hle->commit_id) == 0)
11961 break;
11963 if (hle == NULL) {
11964 err = got_object_id_str(&id_str, &qid->id);
11965 if (err)
11966 return err;
11967 snprintf(msg, sizeof(msg),
11968 "commit %s missing from histedit script", id_str);
11969 free(id_str);
11970 return got_error_msg(GOT_ERR_HISTEDIT_CMD, msg);
11974 hle = TAILQ_LAST(histedit_cmds, got_histedit_list);
11975 if (hle && hle->cmd->code == GOT_HISTEDIT_FOLD)
11976 return got_error_msg(GOT_ERR_HISTEDIT_CMD,
11977 "last commit in histedit script cannot be folded");
11979 return NULL;
11982 static const struct got_error *
11983 histedit_run_editor(struct got_histedit_list *histedit_cmds,
11984 const char *path, struct got_object_id_queue *commits,
11985 struct got_repository *repo)
11987 const struct got_error *err = NULL;
11988 char *editor;
11989 FILE *f = NULL;
11991 err = get_editor(&editor);
11992 if (err)
11993 return err;
11995 if (spawn_editor(editor, path) == -1) {
11996 err = got_error_from_errno("failed spawning editor");
11997 goto done;
12000 f = fopen(path, "re");
12001 if (f == NULL) {
12002 err = got_error_from_errno("fopen");
12003 goto done;
12005 err = histedit_parse_list(histedit_cmds, f, repo);
12006 if (err)
12007 goto done;
12009 err = histedit_check_script(histedit_cmds, commits, repo);
12010 done:
12011 if (f && fclose(f) == EOF && err == NULL)
12012 err = got_error_from_errno("fclose");
12013 free(editor);
12014 return err;
12017 static const struct got_error *
12018 histedit_edit_list_retry(struct got_histedit_list *, const struct got_error *,
12019 struct got_object_id_queue *, const char *, const char *,
12020 struct got_repository *);
12022 static const struct got_error *
12023 histedit_edit_script(struct got_histedit_list *histedit_cmds,
12024 struct got_object_id_queue *commits, const char *branch_name,
12025 int edit_logmsg_only, int fold_only, int drop_only, int edit_only,
12026 struct got_repository *repo)
12028 const struct got_error *err;
12029 FILE *f = NULL;
12030 char *path = NULL;
12032 err = got_opentemp_named(&path, &f, "got-histedit", "");
12033 if (err)
12034 return err;
12036 err = write_cmd_list(f, branch_name, commits);
12037 if (err)
12038 goto done;
12040 err = histedit_write_commit_list(commits, f, edit_logmsg_only,
12041 fold_only, drop_only, edit_only, repo);
12042 if (err)
12043 goto done;
12045 if (drop_only || edit_logmsg_only || fold_only || edit_only) {
12046 rewind(f);
12047 err = histedit_parse_list(histedit_cmds, f, repo);
12048 } else {
12049 if (fclose(f) == EOF) {
12050 err = got_error_from_errno("fclose");
12051 goto done;
12053 f = NULL;
12054 err = histedit_run_editor(histedit_cmds, path, commits, repo);
12055 if (err) {
12056 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
12057 err->code != GOT_ERR_HISTEDIT_CMD)
12058 goto done;
12059 err = histedit_edit_list_retry(histedit_cmds, err,
12060 commits, path, branch_name, repo);
12063 done:
12064 if (f && fclose(f) == EOF && err == NULL)
12065 err = got_error_from_errno("fclose");
12066 if (path && unlink(path) != 0 && err == NULL)
12067 err = got_error_from_errno2("unlink", path);
12068 free(path);
12069 return err;
12072 static const struct got_error *
12073 histedit_save_list(struct got_histedit_list *histedit_cmds,
12074 struct got_worktree *worktree, struct got_repository *repo)
12076 const struct got_error *err = NULL;
12077 char *path = NULL;
12078 FILE *f = NULL;
12079 struct got_histedit_list_entry *hle;
12080 struct got_commit_object *commit = NULL;
12082 err = got_worktree_get_histedit_script_path(&path, worktree);
12083 if (err)
12084 return err;
12086 f = fopen(path, "we");
12087 if (f == NULL) {
12088 err = got_error_from_errno2("fopen", path);
12089 goto done;
12091 TAILQ_FOREACH(hle, histedit_cmds, entry) {
12092 err = histedit_write_commit(hle->commit_id, hle->cmd->name, f,
12093 repo);
12094 if (err)
12095 break;
12097 if (hle->logmsg) {
12098 int n = fprintf(f, "%c %s\n",
12099 GOT_HISTEDIT_MESG, hle->logmsg);
12100 if (n < 0) {
12101 err = got_ferror(f, GOT_ERR_IO);
12102 break;
12106 done:
12107 if (f && fclose(f) == EOF && err == NULL)
12108 err = got_error_from_errno("fclose");
12109 free(path);
12110 if (commit)
12111 got_object_commit_close(commit);
12112 return err;
12115 static void
12116 histedit_free_list(struct got_histedit_list *histedit_cmds)
12118 struct got_histedit_list_entry *hle;
12120 while ((hle = TAILQ_FIRST(histedit_cmds))) {
12121 TAILQ_REMOVE(histedit_cmds, hle, entry);
12122 free(hle);
12126 static const struct got_error *
12127 histedit_load_list(struct got_histedit_list *histedit_cmds,
12128 const char *path, struct got_repository *repo)
12130 const struct got_error *err = NULL;
12131 FILE *f = NULL;
12133 f = fopen(path, "re");
12134 if (f == NULL) {
12135 err = got_error_from_errno2("fopen", path);
12136 goto done;
12139 err = histedit_parse_list(histedit_cmds, f, repo);
12140 done:
12141 if (f && fclose(f) == EOF && err == NULL)
12142 err = got_error_from_errno("fclose");
12143 return err;
12146 static const struct got_error *
12147 histedit_edit_list_retry(struct got_histedit_list *histedit_cmds,
12148 const struct got_error *edit_err, struct got_object_id_queue *commits,
12149 const char *path, const char *branch_name, struct got_repository *repo)
12151 const struct got_error *err = NULL, *prev_err = edit_err;
12152 int resp = ' ';
12154 while (resp != 'c' && resp != 'r' && resp != 'a') {
12155 printf("%s: %s\n(c)ontinue editing, (r)estart editing, "
12156 "or (a)bort: ", getprogname(), prev_err->msg);
12157 resp = getchar();
12158 if (resp == '\n')
12159 resp = getchar();
12160 if (resp == 'c') {
12161 histedit_free_list(histedit_cmds);
12162 err = histedit_run_editor(histedit_cmds, path, commits,
12163 repo);
12164 if (err) {
12165 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
12166 err->code != GOT_ERR_HISTEDIT_CMD)
12167 break;
12168 prev_err = err;
12169 resp = ' ';
12170 continue;
12172 break;
12173 } else if (resp == 'r') {
12174 histedit_free_list(histedit_cmds);
12175 err = histedit_edit_script(histedit_cmds,
12176 commits, branch_name, 0, 0, 0, 0, repo);
12177 if (err) {
12178 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
12179 err->code != GOT_ERR_HISTEDIT_CMD)
12180 break;
12181 prev_err = err;
12182 resp = ' ';
12183 continue;
12185 break;
12186 } else if (resp == 'a') {
12187 err = got_error(GOT_ERR_HISTEDIT_CANCEL);
12188 break;
12189 } else
12190 printf("invalid response '%c'\n", resp);
12193 return err;
12196 static const struct got_error *
12197 histedit_complete(struct got_worktree *worktree,
12198 struct got_fileindex *fileindex, struct got_reference *tmp_branch,
12199 struct got_reference *branch, struct got_repository *repo)
12201 printf("Switching work tree to %s\n",
12202 got_ref_get_symref_target(branch));
12203 return got_worktree_histedit_complete(worktree, fileindex, tmp_branch,
12204 branch, repo);
12207 static const struct got_error *
12208 show_histedit_progress(struct got_commit_object *commit,
12209 struct got_histedit_list_entry *hle, struct got_object_id *new_id)
12211 const struct got_error *err;
12212 char *old_id_str = NULL, *new_id_str = NULL, *logmsg = NULL;
12214 err = got_object_id_str(&old_id_str, hle->commit_id);
12215 if (err)
12216 goto done;
12218 if (new_id) {
12219 err = got_object_id_str(&new_id_str, new_id);
12220 if (err)
12221 goto done;
12224 old_id_str[12] = '\0';
12225 if (new_id_str)
12226 new_id_str[12] = '\0';
12228 if (hle->logmsg) {
12229 logmsg = strdup(hle->logmsg);
12230 if (logmsg == NULL) {
12231 err = got_error_from_errno("strdup");
12232 goto done;
12234 trim_logmsg(logmsg, 42);
12235 } else {
12236 err = get_short_logmsg(&logmsg, 42, commit);
12237 if (err)
12238 goto done;
12241 switch (hle->cmd->code) {
12242 case GOT_HISTEDIT_PICK:
12243 case GOT_HISTEDIT_EDIT:
12244 printf("%s -> %s: %s\n", old_id_str,
12245 new_id_str ? new_id_str : "no-op change", logmsg);
12246 break;
12247 case GOT_HISTEDIT_DROP:
12248 case GOT_HISTEDIT_FOLD:
12249 printf("%s -> %s commit: %s\n", old_id_str, hle->cmd->name,
12250 logmsg);
12251 break;
12252 default:
12253 break;
12255 done:
12256 free(old_id_str);
12257 free(new_id_str);
12258 return err;
12261 static const struct got_error *
12262 histedit_commit(struct got_pathlist_head *merged_paths,
12263 struct got_worktree *worktree, struct got_fileindex *fileindex,
12264 struct got_reference *tmp_branch, struct got_histedit_list_entry *hle,
12265 const char *committer, int allow_conflict, struct got_repository *repo)
12267 const struct got_error *err;
12268 struct got_commit_object *commit;
12269 struct got_object_id *new_commit_id;
12271 if ((hle->cmd->code == GOT_HISTEDIT_EDIT || get_folded_commits(hle))
12272 && hle->logmsg == NULL) {
12273 err = histedit_edit_logmsg(hle, repo);
12274 if (err)
12275 return err;
12278 err = got_object_open_as_commit(&commit, repo, hle->commit_id);
12279 if (err)
12280 return err;
12282 err = got_worktree_histedit_commit(&new_commit_id, merged_paths,
12283 worktree, fileindex, tmp_branch, committer, commit, hle->commit_id,
12284 hle->logmsg, allow_conflict, repo);
12285 if (err) {
12286 if (err->code != GOT_ERR_COMMIT_NO_CHANGES)
12287 goto done;
12288 err = show_histedit_progress(commit, hle, NULL);
12289 } else {
12290 err = show_histedit_progress(commit, hle, new_commit_id);
12291 free(new_commit_id);
12293 done:
12294 got_object_commit_close(commit);
12295 return err;
12298 static const struct got_error *
12299 histedit_skip_commit(struct got_histedit_list_entry *hle,
12300 struct got_worktree *worktree, struct got_repository *repo)
12302 const struct got_error *error;
12303 struct got_commit_object *commit;
12305 error = got_worktree_histedit_skip_commit(worktree, hle->commit_id,
12306 repo);
12307 if (error)
12308 return error;
12310 error = got_object_open_as_commit(&commit, repo, hle->commit_id);
12311 if (error)
12312 return error;
12314 error = show_histedit_progress(commit, hle, NULL);
12315 got_object_commit_close(commit);
12316 return error;
12319 static const struct got_error *
12320 check_local_changes(void *arg, unsigned char status,
12321 unsigned char staged_status, const char *path,
12322 struct got_object_id *blob_id, struct got_object_id *staged_blob_id,
12323 struct got_object_id *commit_id, int dirfd, const char *de_name)
12325 int *have_local_changes = arg;
12327 switch (status) {
12328 case GOT_STATUS_ADD:
12329 case GOT_STATUS_DELETE:
12330 case GOT_STATUS_MODIFY:
12331 case GOT_STATUS_CONFLICT:
12332 *have_local_changes = 1;
12333 return got_error(GOT_ERR_CANCELLED);
12334 default:
12335 break;
12338 switch (staged_status) {
12339 case GOT_STATUS_ADD:
12340 case GOT_STATUS_DELETE:
12341 case GOT_STATUS_MODIFY:
12342 *have_local_changes = 1;
12343 return got_error(GOT_ERR_CANCELLED);
12344 default:
12345 break;
12348 return NULL;
12351 static const struct got_error *
12352 cmd_histedit(int argc, char *argv[])
12354 const struct got_error *error = NULL;
12355 struct got_worktree *worktree = NULL;
12356 struct got_fileindex *fileindex = NULL;
12357 struct got_repository *repo = NULL;
12358 char *cwd = NULL, *committer = NULL, *gitconfig_path = NULL;
12359 struct got_reference *branch = NULL;
12360 struct got_reference *tmp_branch = NULL;
12361 struct got_object_id *resume_commit_id = NULL;
12362 struct got_object_id *base_commit_id = NULL;
12363 struct got_object_id *head_commit_id = NULL;
12364 struct got_commit_object *commit = NULL;
12365 int ch, rebase_in_progress = 0, merge_in_progress = 0;
12366 struct got_update_progress_arg upa;
12367 int edit_in_progress = 0, abort_edit = 0, continue_edit = 0;
12368 int drop_only = 0, edit_logmsg_only = 0, fold_only = 0, edit_only = 0;
12369 int allow_conflict = 0, list_backups = 0, delete_backups = 0;
12370 const char *edit_script_path = NULL;
12371 struct got_object_id_queue commits;
12372 struct got_pathlist_head merged_paths;
12373 const struct got_object_id_queue *parent_ids;
12374 struct got_object_qid *pid;
12375 struct got_histedit_list histedit_cmds;
12376 struct got_histedit_list_entry *hle;
12377 int *pack_fds = NULL;
12379 STAILQ_INIT(&commits);
12380 TAILQ_INIT(&histedit_cmds);
12381 TAILQ_INIT(&merged_paths);
12382 memset(&upa, 0, sizeof(upa));
12384 #ifndef PROFILE
12385 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
12386 "unveil", NULL) == -1)
12387 err(1, "pledge");
12388 #endif
12390 while ((ch = getopt(argc, argv, "aCcdeF:flmX")) != -1) {
12391 switch (ch) {
12392 case 'a':
12393 abort_edit = 1;
12394 break;
12395 case 'C':
12396 allow_conflict = 1;
12397 break;
12398 case 'c':
12399 continue_edit = 1;
12400 break;
12401 case 'd':
12402 drop_only = 1;
12403 break;
12404 case 'e':
12405 edit_only = 1;
12406 break;
12407 case 'F':
12408 edit_script_path = optarg;
12409 break;
12410 case 'f':
12411 fold_only = 1;
12412 break;
12413 case 'l':
12414 list_backups = 1;
12415 break;
12416 case 'm':
12417 edit_logmsg_only = 1;
12418 break;
12419 case 'X':
12420 delete_backups = 1;
12421 break;
12422 default:
12423 usage_histedit();
12424 /* NOTREACHED */
12428 argc -= optind;
12429 argv += optind;
12431 if (abort_edit && allow_conflict)
12432 option_conflict('a', 'C');
12433 if (abort_edit && continue_edit)
12434 option_conflict('a', 'c');
12435 if (edit_script_path && allow_conflict)
12436 option_conflict('F', 'C');
12437 if (edit_script_path && edit_logmsg_only)
12438 option_conflict('F', 'm');
12439 if (abort_edit && edit_logmsg_only)
12440 option_conflict('a', 'm');
12441 if (edit_logmsg_only && allow_conflict)
12442 option_conflict('m', 'C');
12443 if (continue_edit && edit_logmsg_only)
12444 option_conflict('c', 'm');
12445 if (abort_edit && fold_only)
12446 option_conflict('a', 'f');
12447 if (fold_only && allow_conflict)
12448 option_conflict('f', 'C');
12449 if (continue_edit && fold_only)
12450 option_conflict('c', 'f');
12451 if (fold_only && edit_logmsg_only)
12452 option_conflict('f', 'm');
12453 if (edit_script_path && fold_only)
12454 option_conflict('F', 'f');
12455 if (abort_edit && edit_only)
12456 option_conflict('a', 'e');
12457 if (continue_edit && edit_only)
12458 option_conflict('c', 'e');
12459 if (edit_only && edit_logmsg_only)
12460 option_conflict('e', 'm');
12461 if (edit_script_path && edit_only)
12462 option_conflict('F', 'e');
12463 if (fold_only && edit_only)
12464 option_conflict('f', 'e');
12465 if (drop_only && abort_edit)
12466 option_conflict('d', 'a');
12467 if (drop_only && allow_conflict)
12468 option_conflict('d', 'C');
12469 if (drop_only && continue_edit)
12470 option_conflict('d', 'c');
12471 if (drop_only && edit_logmsg_only)
12472 option_conflict('d', 'm');
12473 if (drop_only && edit_only)
12474 option_conflict('d', 'e');
12475 if (drop_only && edit_script_path)
12476 option_conflict('d', 'F');
12477 if (drop_only && fold_only)
12478 option_conflict('d', 'f');
12479 if (list_backups) {
12480 if (abort_edit)
12481 option_conflict('l', 'a');
12482 if (allow_conflict)
12483 option_conflict('l', 'C');
12484 if (continue_edit)
12485 option_conflict('l', 'c');
12486 if (edit_script_path)
12487 option_conflict('l', 'F');
12488 if (edit_logmsg_only)
12489 option_conflict('l', 'm');
12490 if (drop_only)
12491 option_conflict('l', 'd');
12492 if (fold_only)
12493 option_conflict('l', 'f');
12494 if (edit_only)
12495 option_conflict('l', 'e');
12496 if (delete_backups)
12497 option_conflict('l', 'X');
12498 if (argc != 0 && argc != 1)
12499 usage_histedit();
12500 } else if (delete_backups) {
12501 if (abort_edit)
12502 option_conflict('X', 'a');
12503 if (allow_conflict)
12504 option_conflict('X', 'C');
12505 if (continue_edit)
12506 option_conflict('X', 'c');
12507 if (drop_only)
12508 option_conflict('X', 'd');
12509 if (edit_script_path)
12510 option_conflict('X', 'F');
12511 if (edit_logmsg_only)
12512 option_conflict('X', 'm');
12513 if (fold_only)
12514 option_conflict('X', 'f');
12515 if (edit_only)
12516 option_conflict('X', 'e');
12517 if (list_backups)
12518 option_conflict('X', 'l');
12519 if (argc != 0 && argc != 1)
12520 usage_histedit();
12521 } else if (allow_conflict && !continue_edit)
12522 errx(1, "-C option requires -c");
12523 else if (argc != 0)
12524 usage_histedit();
12527 * This command cannot apply unveil(2) in all cases because the
12528 * user may choose to run an editor to edit the histedit script
12529 * and to edit individual commit log messages.
12530 * unveil(2) traverses exec(2); if an editor is used we have to
12531 * apply unveil after edit script and log messages have been written.
12532 * XXX TODO: Make use of unveil(2) where possible.
12535 cwd = getcwd(NULL, 0);
12536 if (cwd == NULL) {
12537 error = got_error_from_errno("getcwd");
12538 goto done;
12541 error = got_repo_pack_fds_open(&pack_fds);
12542 if (error != NULL)
12543 goto done;
12545 error = got_worktree_open(&worktree, cwd);
12546 if (error) {
12547 if (list_backups || delete_backups) {
12548 if (error->code != GOT_ERR_NOT_WORKTREE)
12549 goto done;
12550 } else {
12551 if (error->code == GOT_ERR_NOT_WORKTREE)
12552 error = wrap_not_worktree_error(error,
12553 "histedit", cwd);
12554 goto done;
12558 if (list_backups || delete_backups) {
12559 error = got_repo_open(&repo,
12560 worktree ? got_worktree_get_repo_path(worktree) : cwd,
12561 NULL, pack_fds);
12562 if (error != NULL)
12563 goto done;
12564 error = apply_unveil(got_repo_get_path(repo), 0,
12565 worktree ? got_worktree_get_root_path(worktree) : NULL);
12566 if (error)
12567 goto done;
12568 error = process_backup_refs(
12569 GOT_WORKTREE_HISTEDIT_BACKUP_REF_PREFIX,
12570 argc == 1 ? argv[0] : NULL, delete_backups, repo);
12571 goto done; /* nothing else to do */
12574 error = get_gitconfig_path(&gitconfig_path);
12575 if (error)
12576 goto done;
12577 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
12578 gitconfig_path, pack_fds);
12579 if (error != NULL)
12580 goto done;
12582 if (worktree != NULL && !list_backups && !delete_backups) {
12583 error = worktree_has_logmsg_ref("histedit", worktree, repo);
12584 if (error)
12585 goto done;
12588 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
12589 if (error)
12590 goto done;
12591 if (rebase_in_progress) {
12592 error = got_error(GOT_ERR_REBASING);
12593 goto done;
12596 error = got_worktree_merge_in_progress(&merge_in_progress, worktree,
12597 repo);
12598 if (error)
12599 goto done;
12600 if (merge_in_progress) {
12601 error = got_error(GOT_ERR_MERGE_BUSY);
12602 goto done;
12605 error = got_worktree_histedit_in_progress(&edit_in_progress, worktree);
12606 if (error)
12607 goto done;
12609 if (edit_in_progress && edit_logmsg_only) {
12610 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
12611 "histedit operation is in progress in this "
12612 "work tree and must be continued or aborted "
12613 "before the -m option can be used");
12614 goto done;
12616 if (edit_in_progress && drop_only) {
12617 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
12618 "histedit operation is in progress in this "
12619 "work tree and must be continued or aborted "
12620 "before the -d option can be used");
12621 goto done;
12623 if (edit_in_progress && fold_only) {
12624 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
12625 "histedit operation is in progress in this "
12626 "work tree and must be continued or aborted "
12627 "before the -f option can be used");
12628 goto done;
12630 if (edit_in_progress && edit_only) {
12631 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
12632 "histedit operation is in progress in this "
12633 "work tree and must be continued or aborted "
12634 "before the -e option can be used");
12635 goto done;
12638 if (edit_in_progress && abort_edit) {
12639 error = got_worktree_histedit_continue(&resume_commit_id,
12640 &tmp_branch, &branch, &base_commit_id, &fileindex,
12641 worktree, repo);
12642 if (error)
12643 goto done;
12644 printf("Switching work tree to %s\n",
12645 got_ref_get_symref_target(branch));
12646 error = got_worktree_histedit_abort(worktree, fileindex, repo,
12647 branch, base_commit_id, abort_progress, &upa);
12648 if (error)
12649 goto done;
12650 printf("Histedit of %s aborted\n",
12651 got_ref_get_symref_target(branch));
12652 print_merge_progress_stats(&upa);
12653 goto done; /* nothing else to do */
12654 } else if (abort_edit) {
12655 error = got_error(GOT_ERR_NOT_HISTEDIT);
12656 goto done;
12659 error = get_author(&committer, repo, worktree);
12660 if (error)
12661 goto done;
12663 if (continue_edit) {
12664 char *path;
12666 if (!edit_in_progress) {
12667 error = got_error(GOT_ERR_NOT_HISTEDIT);
12668 goto done;
12671 error = got_worktree_get_histedit_script_path(&path, worktree);
12672 if (error)
12673 goto done;
12675 error = histedit_load_list(&histedit_cmds, path, repo);
12676 free(path);
12677 if (error)
12678 goto done;
12680 error = got_worktree_histedit_continue(&resume_commit_id,
12681 &tmp_branch, &branch, &base_commit_id, &fileindex,
12682 worktree, repo);
12683 if (error)
12684 goto done;
12686 error = got_ref_resolve(&head_commit_id, repo, branch);
12687 if (error)
12688 goto done;
12690 error = got_object_open_as_commit(&commit, repo,
12691 head_commit_id);
12692 if (error)
12693 goto done;
12694 parent_ids = got_object_commit_get_parent_ids(commit);
12695 pid = STAILQ_FIRST(parent_ids);
12696 if (pid == NULL) {
12697 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
12698 goto done;
12700 error = collect_commits(&commits, head_commit_id, &pid->id,
12701 base_commit_id, got_worktree_get_path_prefix(worktree),
12702 GOT_ERR_HISTEDIT_PATH, repo);
12703 got_object_commit_close(commit);
12704 commit = NULL;
12705 if (error)
12706 goto done;
12707 } else {
12708 if (edit_in_progress) {
12709 error = got_error(GOT_ERR_HISTEDIT_BUSY);
12710 goto done;
12713 error = got_ref_open(&branch, repo,
12714 got_worktree_get_head_ref_name(worktree), 0);
12715 if (error != NULL)
12716 goto done;
12718 if (strncmp(got_ref_get_name(branch), "refs/heads/", 11) != 0) {
12719 error = got_error_msg(GOT_ERR_COMMIT_BRANCH,
12720 "will not edit commit history of a branch outside "
12721 "the \"refs/heads/\" reference namespace");
12722 goto done;
12725 error = got_ref_resolve(&head_commit_id, repo, branch);
12726 got_ref_close(branch);
12727 branch = NULL;
12728 if (error)
12729 goto done;
12731 error = got_object_open_as_commit(&commit, repo,
12732 head_commit_id);
12733 if (error)
12734 goto done;
12735 parent_ids = got_object_commit_get_parent_ids(commit);
12736 pid = STAILQ_FIRST(parent_ids);
12737 if (pid == NULL) {
12738 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
12739 goto done;
12741 error = collect_commits(&commits, head_commit_id, &pid->id,
12742 got_worktree_get_base_commit_id(worktree),
12743 got_worktree_get_path_prefix(worktree),
12744 GOT_ERR_HISTEDIT_PATH, repo);
12745 got_object_commit_close(commit);
12746 commit = NULL;
12747 if (error)
12748 goto done;
12750 if (STAILQ_EMPTY(&commits)) {
12751 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
12752 goto done;
12755 error = got_worktree_histedit_prepare(&tmp_branch, &branch,
12756 &base_commit_id, &fileindex, worktree, repo);
12757 if (error)
12758 goto done;
12760 if (edit_script_path) {
12761 error = histedit_load_list(&histedit_cmds,
12762 edit_script_path, repo);
12763 if (error) {
12764 got_worktree_histedit_abort(worktree, fileindex,
12765 repo, branch, base_commit_id,
12766 abort_progress, &upa);
12767 print_merge_progress_stats(&upa);
12768 goto done;
12770 } else {
12771 const char *branch_name;
12772 branch_name = got_ref_get_symref_target(branch);
12773 if (strncmp(branch_name, "refs/heads/", 11) == 0)
12774 branch_name += 11;
12775 error = histedit_edit_script(&histedit_cmds, &commits,
12776 branch_name, edit_logmsg_only, fold_only,
12777 drop_only, edit_only, repo);
12778 if (error) {
12779 got_worktree_histedit_abort(worktree, fileindex,
12780 repo, branch, base_commit_id,
12781 abort_progress, &upa);
12782 print_merge_progress_stats(&upa);
12783 goto done;
12788 error = histedit_save_list(&histedit_cmds, worktree,
12789 repo);
12790 if (error) {
12791 got_worktree_histedit_abort(worktree, fileindex,
12792 repo, branch, base_commit_id,
12793 abort_progress, &upa);
12794 print_merge_progress_stats(&upa);
12795 goto done;
12800 error = histedit_check_script(&histedit_cmds, &commits, repo);
12801 if (error)
12802 goto done;
12804 TAILQ_FOREACH(hle, &histedit_cmds, entry) {
12805 if (resume_commit_id) {
12806 if (got_object_id_cmp(hle->commit_id,
12807 resume_commit_id) != 0)
12808 continue;
12810 resume_commit_id = NULL;
12811 if (hle->cmd->code == GOT_HISTEDIT_DROP ||
12812 hle->cmd->code == GOT_HISTEDIT_FOLD) {
12813 error = histedit_skip_commit(hle, worktree,
12814 repo);
12815 if (error)
12816 goto done;
12817 } else {
12818 struct got_pathlist_head paths;
12819 int have_changes = 0;
12821 TAILQ_INIT(&paths);
12822 error = got_pathlist_append(&paths, "", NULL);
12823 if (error)
12824 goto done;
12825 error = got_worktree_status(worktree, &paths,
12826 repo, 0, check_local_changes, &have_changes,
12827 check_cancelled, NULL);
12828 got_pathlist_free(&paths,
12829 GOT_PATHLIST_FREE_NONE);
12830 if (error) {
12831 if (error->code != GOT_ERR_CANCELLED)
12832 goto done;
12833 if (sigint_received || sigpipe_received)
12834 goto done;
12836 if (have_changes) {
12837 error = histedit_commit(NULL, worktree,
12838 fileindex, tmp_branch, hle,
12839 committer, allow_conflict, repo);
12840 if (error)
12841 goto done;
12842 } else {
12843 error = got_object_open_as_commit(
12844 &commit, repo, hle->commit_id);
12845 if (error)
12846 goto done;
12847 error = show_histedit_progress(commit,
12848 hle, NULL);
12849 got_object_commit_close(commit);
12850 commit = NULL;
12851 if (error)
12852 goto done;
12855 continue;
12858 if (hle->cmd->code == GOT_HISTEDIT_DROP) {
12859 error = histedit_skip_commit(hle, worktree, repo);
12860 if (error)
12861 goto done;
12862 continue;
12865 error = got_object_open_as_commit(&commit, repo,
12866 hle->commit_id);
12867 if (error)
12868 goto done;
12869 parent_ids = got_object_commit_get_parent_ids(commit);
12870 pid = STAILQ_FIRST(parent_ids);
12872 error = got_worktree_histedit_merge_files(&merged_paths,
12873 worktree, fileindex, &pid->id, hle->commit_id, repo,
12874 update_progress, &upa, check_cancelled, NULL);
12875 if (error)
12876 goto done;
12877 got_object_commit_close(commit);
12878 commit = NULL;
12880 print_merge_progress_stats(&upa);
12881 if (upa.conflicts > 0 || upa.missing > 0 ||
12882 upa.not_deleted > 0 || upa.unversioned > 0) {
12883 if (upa.conflicts > 0) {
12884 error = show_rebase_merge_conflict(
12885 hle->commit_id, repo);
12886 if (error)
12887 goto done;
12889 got_pathlist_free(&merged_paths, GOT_PATHLIST_FREE_PATH);
12890 break;
12893 if (hle->cmd->code == GOT_HISTEDIT_EDIT) {
12894 char *id_str;
12895 error = got_object_id_str(&id_str, hle->commit_id);
12896 if (error)
12897 goto done;
12898 printf("Stopping histedit for amending commit %s\n",
12899 id_str);
12900 free(id_str);
12901 got_pathlist_free(&merged_paths, GOT_PATHLIST_FREE_PATH);
12902 error = got_worktree_histedit_postpone(worktree,
12903 fileindex);
12904 goto done;
12907 if (hle->cmd->code == GOT_HISTEDIT_FOLD) {
12908 error = histedit_skip_commit(hle, worktree, repo);
12909 if (error)
12910 goto done;
12911 continue;
12914 error = histedit_commit(&merged_paths, worktree, fileindex,
12915 tmp_branch, hle, committer, allow_conflict, repo);
12916 got_pathlist_free(&merged_paths, GOT_PATHLIST_FREE_PATH);
12917 if (error)
12918 goto done;
12921 if (upa.conflicts > 0 || upa.missing > 0 ||
12922 upa.not_deleted > 0 || upa.unversioned > 0) {
12923 error = got_worktree_histedit_postpone(worktree, fileindex);
12924 if (error)
12925 goto done;
12926 if (upa.conflicts > 0 && upa.missing == 0 &&
12927 upa.not_deleted == 0 && upa.unversioned == 0) {
12928 error = got_error_msg(GOT_ERR_CONFLICTS,
12929 "conflicts must be resolved before histedit "
12930 "can continue");
12931 } else if (upa.conflicts > 0) {
12932 error = got_error_msg(GOT_ERR_CONFLICTS,
12933 "conflicts must be resolved before histedit "
12934 "can continue; changes destined for some "
12935 "files were not yet merged and should be "
12936 "merged manually if required before the "
12937 "histedit operation is continued");
12938 } else {
12939 error = got_error_msg(GOT_ERR_CONFLICTS,
12940 "changes destined for some files were not "
12941 "yet merged and should be merged manually "
12942 "if required before the histedit operation "
12943 "is continued");
12945 } else
12946 error = histedit_complete(worktree, fileindex, tmp_branch,
12947 branch, repo);
12948 done:
12949 free(cwd);
12950 free(committer);
12951 free(gitconfig_path);
12952 got_object_id_queue_free(&commits);
12953 histedit_free_list(&histedit_cmds);
12954 free(head_commit_id);
12955 free(base_commit_id);
12956 free(resume_commit_id);
12957 if (commit)
12958 got_object_commit_close(commit);
12959 if (branch)
12960 got_ref_close(branch);
12961 if (tmp_branch)
12962 got_ref_close(tmp_branch);
12963 if (worktree)
12964 got_worktree_close(worktree);
12965 if (repo) {
12966 const struct got_error *close_err = got_repo_close(repo);
12967 if (error == NULL)
12968 error = close_err;
12970 if (pack_fds) {
12971 const struct got_error *pack_err =
12972 got_repo_pack_fds_close(pack_fds);
12973 if (error == NULL)
12974 error = pack_err;
12976 return error;
12979 __dead static void
12980 usage_integrate(void)
12982 fprintf(stderr, "usage: %s integrate branch\n", getprogname());
12983 exit(1);
12986 static const struct got_error *
12987 cmd_integrate(int argc, char *argv[])
12989 const struct got_error *error = NULL;
12990 struct got_repository *repo = NULL;
12991 struct got_worktree *worktree = NULL;
12992 char *cwd = NULL, *refname = NULL, *base_refname = NULL;
12993 const char *branch_arg = NULL;
12994 struct got_reference *branch_ref = NULL, *base_branch_ref = NULL;
12995 struct got_fileindex *fileindex = NULL;
12996 struct got_object_id *commit_id = NULL, *base_commit_id = NULL;
12997 int ch;
12998 struct got_update_progress_arg upa;
12999 int *pack_fds = NULL;
13001 #ifndef PROFILE
13002 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
13003 "unveil", NULL) == -1)
13004 err(1, "pledge");
13005 #endif
13007 while ((ch = getopt(argc, argv, "")) != -1) {
13008 switch (ch) {
13009 default:
13010 usage_integrate();
13011 /* NOTREACHED */
13015 argc -= optind;
13016 argv += optind;
13018 if (argc != 1)
13019 usage_integrate();
13020 branch_arg = argv[0];
13022 cwd = getcwd(NULL, 0);
13023 if (cwd == NULL) {
13024 error = got_error_from_errno("getcwd");
13025 goto done;
13028 error = got_repo_pack_fds_open(&pack_fds);
13029 if (error != NULL)
13030 goto done;
13032 error = got_worktree_open(&worktree, cwd);
13033 if (error) {
13034 if (error->code == GOT_ERR_NOT_WORKTREE)
13035 error = wrap_not_worktree_error(error, "integrate",
13036 cwd);
13037 goto done;
13040 error = check_rebase_or_histedit_in_progress(worktree);
13041 if (error)
13042 goto done;
13044 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
13045 NULL, pack_fds);
13046 if (error != NULL)
13047 goto done;
13049 error = apply_unveil(got_repo_get_path(repo), 0,
13050 got_worktree_get_root_path(worktree));
13051 if (error)
13052 goto done;
13054 error = check_merge_in_progress(worktree, repo);
13055 if (error)
13056 goto done;
13058 if (asprintf(&refname, "refs/heads/%s", branch_arg) == -1) {
13059 error = got_error_from_errno("asprintf");
13060 goto done;
13063 error = got_worktree_integrate_prepare(&fileindex, &branch_ref,
13064 &base_branch_ref, worktree, refname, repo);
13065 if (error)
13066 goto done;
13068 refname = strdup(got_ref_get_name(branch_ref));
13069 if (refname == NULL) {
13070 error = got_error_from_errno("strdup");
13071 got_worktree_integrate_abort(worktree, fileindex, repo,
13072 branch_ref, base_branch_ref);
13073 goto done;
13075 base_refname = strdup(got_ref_get_name(base_branch_ref));
13076 if (base_refname == NULL) {
13077 error = got_error_from_errno("strdup");
13078 got_worktree_integrate_abort(worktree, fileindex, repo,
13079 branch_ref, base_branch_ref);
13080 goto done;
13082 if (strncmp(base_refname, "refs/heads/", 11) != 0) {
13083 error = got_error(GOT_ERR_INTEGRATE_BRANCH);
13084 got_worktree_integrate_abort(worktree, fileindex, repo,
13085 branch_ref, base_branch_ref);
13086 goto done;
13089 error = got_ref_resolve(&commit_id, repo, branch_ref);
13090 if (error)
13091 goto done;
13093 error = got_ref_resolve(&base_commit_id, repo, base_branch_ref);
13094 if (error)
13095 goto done;
13097 if (got_object_id_cmp(commit_id, base_commit_id) == 0) {
13098 error = got_error_msg(GOT_ERR_SAME_BRANCH,
13099 "specified branch has already been integrated");
13100 got_worktree_integrate_abort(worktree, fileindex, repo,
13101 branch_ref, base_branch_ref);
13102 goto done;
13105 error = check_linear_ancestry(commit_id, base_commit_id, 1, repo);
13106 if (error) {
13107 if (error->code == GOT_ERR_ANCESTRY)
13108 error = got_error(GOT_ERR_REBASE_REQUIRED);
13109 got_worktree_integrate_abort(worktree, fileindex, repo,
13110 branch_ref, base_branch_ref);
13111 goto done;
13114 memset(&upa, 0, sizeof(upa));
13115 error = got_worktree_integrate_continue(worktree, fileindex, repo,
13116 branch_ref, base_branch_ref, update_progress, &upa,
13117 check_cancelled, NULL);
13118 if (error)
13119 goto done;
13121 printf("Integrated %s into %s\n", refname, base_refname);
13122 print_update_progress_stats(&upa);
13123 done:
13124 if (repo) {
13125 const struct got_error *close_err = got_repo_close(repo);
13126 if (error == NULL)
13127 error = close_err;
13129 if (worktree)
13130 got_worktree_close(worktree);
13131 if (pack_fds) {
13132 const struct got_error *pack_err =
13133 got_repo_pack_fds_close(pack_fds);
13134 if (error == NULL)
13135 error = pack_err;
13137 free(cwd);
13138 free(base_commit_id);
13139 free(commit_id);
13140 free(refname);
13141 free(base_refname);
13142 return error;
13145 __dead static void
13146 usage_merge(void)
13148 fprintf(stderr, "usage: %s merge [-aCcn] [branch]\n", getprogname());
13149 exit(1);
13152 static const struct got_error *
13153 cmd_merge(int argc, char *argv[])
13155 const struct got_error *error = NULL;
13156 struct got_worktree *worktree = NULL;
13157 struct got_repository *repo = NULL;
13158 struct got_fileindex *fileindex = NULL;
13159 char *cwd = NULL, *id_str = NULL, *author = NULL;
13160 char *gitconfig_path = NULL;
13161 struct got_reference *branch = NULL, *wt_branch = NULL;
13162 struct got_object_id *branch_tip = NULL, *yca_id = NULL;
13163 struct got_object_id *wt_branch_tip = NULL;
13164 int ch, merge_in_progress = 0, abort_merge = 0, continue_merge = 0;
13165 int allow_conflict = 0, interrupt_merge = 0;
13166 struct got_update_progress_arg upa;
13167 struct got_object_id *merge_commit_id = NULL;
13168 char *branch_name = NULL;
13169 int *pack_fds = NULL;
13171 memset(&upa, 0, sizeof(upa));
13173 #ifndef PROFILE
13174 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
13175 "unveil", NULL) == -1)
13176 err(1, "pledge");
13177 #endif
13179 while ((ch = getopt(argc, argv, "aCcn")) != -1) {
13180 switch (ch) {
13181 case 'a':
13182 abort_merge = 1;
13183 break;
13184 case 'C':
13185 allow_conflict = 1;
13186 case 'c':
13187 continue_merge = 1;
13188 break;
13189 case 'n':
13190 interrupt_merge = 1;
13191 break;
13192 default:
13193 usage_merge();
13194 /* NOTREACHED */
13198 argc -= optind;
13199 argv += optind;
13201 if (allow_conflict) {
13202 if (abort_merge)
13203 option_conflict('a', 'C');
13204 if (!continue_merge)
13205 errx(1, "-C option requires -c");
13207 if (abort_merge && continue_merge)
13208 option_conflict('a', 'c');
13209 if (abort_merge || continue_merge) {
13210 if (argc != 0)
13211 usage_merge();
13212 } else if (argc != 1)
13213 usage_merge();
13215 cwd = getcwd(NULL, 0);
13216 if (cwd == NULL) {
13217 error = got_error_from_errno("getcwd");
13218 goto done;
13221 error = got_repo_pack_fds_open(&pack_fds);
13222 if (error != NULL)
13223 goto done;
13225 error = got_worktree_open(&worktree, cwd);
13226 if (error) {
13227 if (error->code == GOT_ERR_NOT_WORKTREE)
13228 error = wrap_not_worktree_error(error,
13229 "merge", cwd);
13230 goto done;
13233 error = get_gitconfig_path(&gitconfig_path);
13234 if (error)
13235 goto done;
13236 error = got_repo_open(&repo,
13237 worktree ? got_worktree_get_repo_path(worktree) : cwd,
13238 gitconfig_path, pack_fds);
13239 if (error != NULL)
13240 goto done;
13242 if (worktree != NULL) {
13243 error = worktree_has_logmsg_ref("merge", worktree, repo);
13244 if (error)
13245 goto done;
13248 error = apply_unveil(got_repo_get_path(repo), 0,
13249 worktree ? got_worktree_get_root_path(worktree) : NULL);
13250 if (error)
13251 goto done;
13253 error = check_rebase_or_histedit_in_progress(worktree);
13254 if (error)
13255 goto done;
13257 error = got_worktree_merge_in_progress(&merge_in_progress, worktree,
13258 repo);
13259 if (error)
13260 goto done;
13262 if (abort_merge) {
13263 if (!merge_in_progress) {
13264 error = got_error(GOT_ERR_NOT_MERGING);
13265 goto done;
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 error = get_author(&author, repo, worktree);
13280 if (error)
13281 goto done;
13283 if (continue_merge) {
13284 if (!merge_in_progress) {
13285 error = got_error(GOT_ERR_NOT_MERGING);
13286 goto done;
13288 error = got_worktree_merge_continue(&branch_name,
13289 &branch_tip, &fileindex, worktree, repo);
13290 if (error)
13291 goto done;
13292 } else {
13293 error = got_ref_open(&branch, repo, argv[0], 0);
13294 if (error != NULL)
13295 goto done;
13296 branch_name = strdup(got_ref_get_name(branch));
13297 if (branch_name == NULL) {
13298 error = got_error_from_errno("strdup");
13299 goto done;
13301 error = got_ref_resolve(&branch_tip, repo, branch);
13302 if (error)
13303 goto done;
13306 error = got_ref_open(&wt_branch, repo,
13307 got_worktree_get_head_ref_name(worktree), 0);
13308 if (error)
13309 goto done;
13310 error = got_ref_resolve(&wt_branch_tip, repo, wt_branch);
13311 if (error)
13312 goto done;
13313 error = got_commit_graph_find_youngest_common_ancestor(&yca_id,
13314 wt_branch_tip, branch_tip, 0, repo,
13315 check_cancelled, NULL);
13316 if (error && error->code != GOT_ERR_ANCESTRY)
13317 goto done;
13319 if (!continue_merge) {
13320 error = check_path_prefix(wt_branch_tip, branch_tip,
13321 got_worktree_get_path_prefix(worktree),
13322 GOT_ERR_MERGE_PATH, repo);
13323 if (error)
13324 goto done;
13325 if (yca_id) {
13326 error = check_same_branch(wt_branch_tip, branch,
13327 yca_id, repo);
13328 if (error) {
13329 if (error->code != GOT_ERR_ANCESTRY)
13330 goto done;
13331 error = NULL;
13332 } else {
13333 static char msg[512];
13334 snprintf(msg, sizeof(msg),
13335 "cannot create a merge commit because "
13336 "%s is based on %s; %s can be integrated "
13337 "with 'got integrate' instead", branch_name,
13338 got_worktree_get_head_ref_name(worktree),
13339 branch_name);
13340 error = got_error_msg(GOT_ERR_SAME_BRANCH, msg);
13341 goto done;
13344 error = got_worktree_merge_prepare(&fileindex, worktree,
13345 branch, repo);
13346 if (error)
13347 goto done;
13349 error = got_worktree_merge_branch(worktree, fileindex,
13350 yca_id, branch_tip, repo, update_progress, &upa,
13351 check_cancelled, NULL);
13352 if (error)
13353 goto done;
13354 print_merge_progress_stats(&upa);
13355 if (!upa.did_something) {
13356 error = got_worktree_merge_abort(worktree, fileindex,
13357 repo, abort_progress, &upa);
13358 if (error)
13359 goto done;
13360 printf("Already up-to-date\n");
13361 goto done;
13365 if (interrupt_merge) {
13366 error = got_worktree_merge_postpone(worktree, fileindex);
13367 if (error)
13368 goto done;
13369 printf("Merge of %s interrupted on request\n", branch_name);
13370 } else if (upa.conflicts > 0 || upa.missing > 0 ||
13371 upa.not_deleted > 0 || upa.unversioned > 0) {
13372 error = got_worktree_merge_postpone(worktree, fileindex);
13373 if (error)
13374 goto done;
13375 if (upa.conflicts > 0 && upa.missing == 0 &&
13376 upa.not_deleted == 0 && upa.unversioned == 0) {
13377 error = got_error_msg(GOT_ERR_CONFLICTS,
13378 "conflicts must be resolved before merging "
13379 "can continue");
13380 } else if (upa.conflicts > 0) {
13381 error = got_error_msg(GOT_ERR_CONFLICTS,
13382 "conflicts must be resolved before merging "
13383 "can continue; changes destined for some "
13384 "files were not yet merged and "
13385 "should be merged manually if required before the "
13386 "merge operation is continued");
13387 } else {
13388 error = got_error_msg(GOT_ERR_CONFLICTS,
13389 "changes destined for some "
13390 "files were not yet merged and should be "
13391 "merged manually if required before the "
13392 "merge operation is continued");
13394 goto done;
13395 } else {
13396 error = got_worktree_merge_commit(&merge_commit_id, worktree,
13397 fileindex, author, NULL, 1, branch_tip, branch_name,
13398 allow_conflict, repo, continue_merge ? print_status : NULL,
13399 NULL);
13400 if (error)
13401 goto done;
13402 error = got_worktree_merge_complete(worktree, fileindex, repo);
13403 if (error)
13404 goto done;
13405 error = got_object_id_str(&id_str, merge_commit_id);
13406 if (error)
13407 goto done;
13408 printf("Merged %s into %s: %s\n", branch_name,
13409 got_worktree_get_head_ref_name(worktree),
13410 id_str);
13413 done:
13414 free(gitconfig_path);
13415 free(id_str);
13416 free(merge_commit_id);
13417 free(author);
13418 free(branch_tip);
13419 free(branch_name);
13420 free(yca_id);
13421 if (branch)
13422 got_ref_close(branch);
13423 if (wt_branch)
13424 got_ref_close(wt_branch);
13425 if (worktree)
13426 got_worktree_close(worktree);
13427 if (repo) {
13428 const struct got_error *close_err = got_repo_close(repo);
13429 if (error == NULL)
13430 error = close_err;
13432 if (pack_fds) {
13433 const struct got_error *pack_err =
13434 got_repo_pack_fds_close(pack_fds);
13435 if (error == NULL)
13436 error = pack_err;
13438 return error;
13441 __dead static void
13442 usage_stage(void)
13444 fprintf(stderr, "usage: %s stage [-lpS] [-F response-script] "
13445 "[path ...]\n", getprogname());
13446 exit(1);
13449 static const struct got_error *
13450 print_stage(void *arg, unsigned char status, unsigned char staged_status,
13451 const char *path, struct got_object_id *blob_id,
13452 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
13453 int dirfd, const char *de_name)
13455 const struct got_error *err = NULL;
13456 char *id_str = NULL;
13458 if (staged_status != GOT_STATUS_ADD &&
13459 staged_status != GOT_STATUS_MODIFY &&
13460 staged_status != GOT_STATUS_DELETE)
13461 return NULL;
13463 if (staged_status == GOT_STATUS_ADD ||
13464 staged_status == GOT_STATUS_MODIFY)
13465 err = got_object_id_str(&id_str, staged_blob_id);
13466 else
13467 err = got_object_id_str(&id_str, blob_id);
13468 if (err)
13469 return err;
13471 printf("%s %c %s\n", id_str, staged_status, path);
13472 free(id_str);
13473 return NULL;
13476 static const struct got_error *
13477 cmd_stage(int argc, char *argv[])
13479 const struct got_error *error = NULL;
13480 struct got_repository *repo = NULL;
13481 struct got_worktree *worktree = NULL;
13482 char *cwd = NULL;
13483 struct got_pathlist_head paths;
13484 int ch, list_stage = 0, pflag = 0, allow_bad_symlinks = 0;
13485 FILE *patch_script_file = NULL;
13486 const char *patch_script_path = NULL;
13487 struct choose_patch_arg cpa;
13488 int *pack_fds = NULL;
13490 TAILQ_INIT(&paths);
13492 #ifndef PROFILE
13493 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
13494 "unveil", NULL) == -1)
13495 err(1, "pledge");
13496 #endif
13498 while ((ch = getopt(argc, argv, "F:lpS")) != -1) {
13499 switch (ch) {
13500 case 'F':
13501 patch_script_path = optarg;
13502 break;
13503 case 'l':
13504 list_stage = 1;
13505 break;
13506 case 'p':
13507 pflag = 1;
13508 break;
13509 case 'S':
13510 allow_bad_symlinks = 1;
13511 break;
13512 default:
13513 usage_stage();
13514 /* NOTREACHED */
13518 argc -= optind;
13519 argv += optind;
13521 if (list_stage && (pflag || patch_script_path))
13522 errx(1, "-l option cannot be used with other options");
13523 if (patch_script_path && !pflag)
13524 errx(1, "-F option can only be used together with -p option");
13526 cwd = getcwd(NULL, 0);
13527 if (cwd == NULL) {
13528 error = got_error_from_errno("getcwd");
13529 goto done;
13532 error = got_repo_pack_fds_open(&pack_fds);
13533 if (error != NULL)
13534 goto done;
13536 error = got_worktree_open(&worktree, cwd);
13537 if (error) {
13538 if (error->code == GOT_ERR_NOT_WORKTREE)
13539 error = wrap_not_worktree_error(error, "stage", cwd);
13540 goto done;
13543 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
13544 NULL, pack_fds);
13545 if (error != NULL)
13546 goto done;
13548 if (patch_script_path) {
13549 patch_script_file = fopen(patch_script_path, "re");
13550 if (patch_script_file == NULL) {
13551 error = got_error_from_errno2("fopen",
13552 patch_script_path);
13553 goto done;
13556 error = apply_unveil(got_repo_get_path(repo), 0,
13557 got_worktree_get_root_path(worktree));
13558 if (error)
13559 goto done;
13561 error = check_merge_in_progress(worktree, repo);
13562 if (error)
13563 goto done;
13565 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
13566 if (error)
13567 goto done;
13569 if (list_stage)
13570 error = got_worktree_status(worktree, &paths, repo, 0,
13571 print_stage, NULL, check_cancelled, NULL);
13572 else {
13573 cpa.patch_script_file = patch_script_file;
13574 cpa.action = "stage";
13575 error = got_worktree_stage(worktree, &paths,
13576 pflag ? NULL : print_status, NULL,
13577 pflag ? choose_patch : NULL, &cpa,
13578 allow_bad_symlinks, repo);
13580 done:
13581 if (patch_script_file && fclose(patch_script_file) == EOF &&
13582 error == NULL)
13583 error = got_error_from_errno2("fclose", patch_script_path);
13584 if (repo) {
13585 const struct got_error *close_err = got_repo_close(repo);
13586 if (error == NULL)
13587 error = close_err;
13589 if (worktree)
13590 got_worktree_close(worktree);
13591 if (pack_fds) {
13592 const struct got_error *pack_err =
13593 got_repo_pack_fds_close(pack_fds);
13594 if (error == NULL)
13595 error = pack_err;
13597 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
13598 free(cwd);
13599 return error;
13602 __dead static void
13603 usage_unstage(void)
13605 fprintf(stderr, "usage: %s unstage [-p] [-F response-script] "
13606 "[path ...]\n", getprogname());
13607 exit(1);
13611 static const struct got_error *
13612 cmd_unstage(int argc, char *argv[])
13614 const struct got_error *error = NULL;
13615 struct got_repository *repo = NULL;
13616 struct got_worktree *worktree = NULL;
13617 char *cwd = NULL;
13618 struct got_pathlist_head paths;
13619 int ch, pflag = 0;
13620 struct got_update_progress_arg upa;
13621 FILE *patch_script_file = NULL;
13622 const char *patch_script_path = NULL;
13623 struct choose_patch_arg cpa;
13624 int *pack_fds = NULL;
13626 TAILQ_INIT(&paths);
13628 #ifndef PROFILE
13629 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
13630 "unveil", NULL) == -1)
13631 err(1, "pledge");
13632 #endif
13634 while ((ch = getopt(argc, argv, "F:p")) != -1) {
13635 switch (ch) {
13636 case 'F':
13637 patch_script_path = optarg;
13638 break;
13639 case 'p':
13640 pflag = 1;
13641 break;
13642 default:
13643 usage_unstage();
13644 /* NOTREACHED */
13648 argc -= optind;
13649 argv += optind;
13651 if (patch_script_path && !pflag)
13652 errx(1, "-F option can only be used together with -p option");
13654 cwd = getcwd(NULL, 0);
13655 if (cwd == NULL) {
13656 error = got_error_from_errno("getcwd");
13657 goto done;
13660 error = got_repo_pack_fds_open(&pack_fds);
13661 if (error != NULL)
13662 goto done;
13664 error = got_worktree_open(&worktree, cwd);
13665 if (error) {
13666 if (error->code == GOT_ERR_NOT_WORKTREE)
13667 error = wrap_not_worktree_error(error, "unstage", cwd);
13668 goto done;
13671 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
13672 NULL, pack_fds);
13673 if (error != NULL)
13674 goto done;
13676 if (patch_script_path) {
13677 patch_script_file = fopen(patch_script_path, "re");
13678 if (patch_script_file == NULL) {
13679 error = got_error_from_errno2("fopen",
13680 patch_script_path);
13681 goto done;
13685 error = apply_unveil(got_repo_get_path(repo), 0,
13686 got_worktree_get_root_path(worktree));
13687 if (error)
13688 goto done;
13690 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
13691 if (error)
13692 goto done;
13694 cpa.patch_script_file = patch_script_file;
13695 cpa.action = "unstage";
13696 memset(&upa, 0, sizeof(upa));
13697 error = got_worktree_unstage(worktree, &paths, update_progress,
13698 &upa, pflag ? choose_patch : NULL, &cpa, repo);
13699 if (!error)
13700 print_merge_progress_stats(&upa);
13701 done:
13702 if (patch_script_file && fclose(patch_script_file) == EOF &&
13703 error == NULL)
13704 error = got_error_from_errno2("fclose", patch_script_path);
13705 if (repo) {
13706 const struct got_error *close_err = got_repo_close(repo);
13707 if (error == NULL)
13708 error = close_err;
13710 if (worktree)
13711 got_worktree_close(worktree);
13712 if (pack_fds) {
13713 const struct got_error *pack_err =
13714 got_repo_pack_fds_close(pack_fds);
13715 if (error == NULL)
13716 error = pack_err;
13718 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
13719 free(cwd);
13720 return error;
13723 __dead static void
13724 usage_cat(void)
13726 fprintf(stderr, "usage: %s cat [-P] [-c commit] [-r repository-path] "
13727 "arg ...\n", getprogname());
13728 exit(1);
13731 static const struct got_error *
13732 cat_blob(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
13734 const struct got_error *err;
13735 struct got_blob_object *blob;
13736 int fd = -1;
13738 fd = got_opentempfd();
13739 if (fd == -1)
13740 return got_error_from_errno("got_opentempfd");
13742 err = got_object_open_as_blob(&blob, repo, id, 8192, fd);
13743 if (err)
13744 goto done;
13746 err = got_object_blob_dump_to_file(NULL, NULL, NULL, outfile, blob);
13747 done:
13748 if (fd != -1 && close(fd) == -1 && err == NULL)
13749 err = got_error_from_errno("close");
13750 if (blob)
13751 got_object_blob_close(blob);
13752 return err;
13755 static const struct got_error *
13756 cat_tree(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
13758 const struct got_error *err;
13759 struct got_tree_object *tree;
13760 int nentries, i;
13762 err = got_object_open_as_tree(&tree, repo, id);
13763 if (err)
13764 return err;
13766 nentries = got_object_tree_get_nentries(tree);
13767 for (i = 0; i < nentries; i++) {
13768 struct got_tree_entry *te;
13769 char *id_str;
13770 if (sigint_received || sigpipe_received)
13771 break;
13772 te = got_object_tree_get_entry(tree, i);
13773 err = got_object_id_str(&id_str, got_tree_entry_get_id(te));
13774 if (err)
13775 break;
13776 fprintf(outfile, "%s %.7o %s\n", id_str,
13777 got_tree_entry_get_mode(te),
13778 got_tree_entry_get_name(te));
13779 free(id_str);
13782 got_object_tree_close(tree);
13783 return err;
13786 static const struct got_error *
13787 cat_commit(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
13789 const struct got_error *err;
13790 struct got_commit_object *commit;
13791 const struct got_object_id_queue *parent_ids;
13792 struct got_object_qid *pid;
13793 char *id_str = NULL;
13794 const char *logmsg = NULL;
13795 char gmtoff[6];
13797 err = got_object_open_as_commit(&commit, repo, id);
13798 if (err)
13799 return err;
13801 err = got_object_id_str(&id_str, got_object_commit_get_tree_id(commit));
13802 if (err)
13803 goto done;
13805 fprintf(outfile, "%s%s\n", GOT_COMMIT_LABEL_TREE, id_str);
13806 parent_ids = got_object_commit_get_parent_ids(commit);
13807 fprintf(outfile, "numparents %d\n",
13808 got_object_commit_get_nparents(commit));
13809 STAILQ_FOREACH(pid, parent_ids, entry) {
13810 char *pid_str;
13811 err = got_object_id_str(&pid_str, &pid->id);
13812 if (err)
13813 goto done;
13814 fprintf(outfile, "%s%s\n", GOT_COMMIT_LABEL_PARENT, pid_str);
13815 free(pid_str);
13817 got_date_format_gmtoff(gmtoff, sizeof(gmtoff),
13818 got_object_commit_get_author_gmtoff(commit));
13819 fprintf(outfile, "%s%s %lld %s\n", GOT_COMMIT_LABEL_AUTHOR,
13820 got_object_commit_get_author(commit),
13821 (long long)got_object_commit_get_author_time(commit),
13822 gmtoff);
13824 got_date_format_gmtoff(gmtoff, sizeof(gmtoff),
13825 got_object_commit_get_committer_gmtoff(commit));
13826 fprintf(outfile, "%s%s %lld %s\n", GOT_COMMIT_LABEL_COMMITTER,
13827 got_object_commit_get_committer(commit),
13828 (long long)got_object_commit_get_committer_time(commit),
13829 gmtoff);
13831 logmsg = got_object_commit_get_logmsg_raw(commit);
13832 fprintf(outfile, "messagelen %zd\n", strlen(logmsg));
13833 fprintf(outfile, "%s", logmsg);
13834 done:
13835 free(id_str);
13836 got_object_commit_close(commit);
13837 return err;
13840 static const struct got_error *
13841 cat_tag(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
13843 const struct got_error *err;
13844 struct got_tag_object *tag;
13845 char *id_str = NULL;
13846 const char *tagmsg = NULL;
13847 char gmtoff[6];
13849 err = got_object_open_as_tag(&tag, repo, id);
13850 if (err)
13851 return err;
13853 err = got_object_id_str(&id_str, got_object_tag_get_object_id(tag));
13854 if (err)
13855 goto done;
13857 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_OBJECT, id_str);
13859 switch (got_object_tag_get_object_type(tag)) {
13860 case GOT_OBJ_TYPE_BLOB:
13861 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
13862 GOT_OBJ_LABEL_BLOB);
13863 break;
13864 case GOT_OBJ_TYPE_TREE:
13865 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
13866 GOT_OBJ_LABEL_TREE);
13867 break;
13868 case GOT_OBJ_TYPE_COMMIT:
13869 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
13870 GOT_OBJ_LABEL_COMMIT);
13871 break;
13872 case GOT_OBJ_TYPE_TAG:
13873 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
13874 GOT_OBJ_LABEL_TAG);
13875 break;
13876 default:
13877 break;
13880 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TAG,
13881 got_object_tag_get_name(tag));
13883 got_date_format_gmtoff(gmtoff, sizeof(gmtoff),
13884 got_object_tag_get_tagger_gmtoff(tag));
13885 fprintf(outfile, "%s%s %lld %s\n", GOT_TAG_LABEL_TAGGER,
13886 got_object_tag_get_tagger(tag),
13887 (long long)got_object_tag_get_tagger_time(tag),
13888 gmtoff);
13890 tagmsg = got_object_tag_get_message(tag);
13891 fprintf(outfile, "messagelen %zd\n", strlen(tagmsg));
13892 fprintf(outfile, "%s", tagmsg);
13893 done:
13894 free(id_str);
13895 got_object_tag_close(tag);
13896 return err;
13899 static const struct got_error *
13900 cmd_cat(int argc, char *argv[])
13902 const struct got_error *error;
13903 struct got_repository *repo = NULL;
13904 struct got_worktree *worktree = NULL;
13905 char *cwd = NULL, *repo_path = NULL, *label = NULL;
13906 const char *commit_id_str = NULL;
13907 struct got_object_id *id = NULL, *commit_id = NULL;
13908 struct got_commit_object *commit = NULL;
13909 int ch, obj_type, i, force_path = 0;
13910 struct got_reflist_head refs;
13911 int *pack_fds = NULL;
13913 TAILQ_INIT(&refs);
13915 #ifndef PROFILE
13916 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
13917 NULL) == -1)
13918 err(1, "pledge");
13919 #endif
13921 while ((ch = getopt(argc, argv, "c:Pr:")) != -1) {
13922 switch (ch) {
13923 case 'c':
13924 commit_id_str = optarg;
13925 break;
13926 case 'P':
13927 force_path = 1;
13928 break;
13929 case 'r':
13930 repo_path = realpath(optarg, NULL);
13931 if (repo_path == NULL)
13932 return got_error_from_errno2("realpath",
13933 optarg);
13934 got_path_strip_trailing_slashes(repo_path);
13935 break;
13936 default:
13937 usage_cat();
13938 /* NOTREACHED */
13942 argc -= optind;
13943 argv += optind;
13945 cwd = getcwd(NULL, 0);
13946 if (cwd == NULL) {
13947 error = got_error_from_errno("getcwd");
13948 goto done;
13951 error = got_repo_pack_fds_open(&pack_fds);
13952 if (error != NULL)
13953 goto done;
13955 if (repo_path == NULL) {
13956 error = got_worktree_open(&worktree, cwd);
13957 if (error && error->code != GOT_ERR_NOT_WORKTREE)
13958 goto done;
13959 if (worktree) {
13960 repo_path = strdup(
13961 got_worktree_get_repo_path(worktree));
13962 if (repo_path == NULL) {
13963 error = got_error_from_errno("strdup");
13964 goto done;
13967 /* Release work tree lock. */
13968 got_worktree_close(worktree);
13969 worktree = NULL;
13973 if (repo_path == NULL) {
13974 repo_path = strdup(cwd);
13975 if (repo_path == NULL)
13976 return got_error_from_errno("strdup");
13979 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
13980 free(repo_path);
13981 if (error != NULL)
13982 goto done;
13984 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
13985 if (error)
13986 goto done;
13988 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
13989 if (error)
13990 goto done;
13992 if (commit_id_str == NULL)
13993 commit_id_str = GOT_REF_HEAD;
13994 error = got_repo_match_object_id(&commit_id, NULL,
13995 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
13996 if (error)
13997 goto done;
13999 error = got_object_open_as_commit(&commit, repo, commit_id);
14000 if (error)
14001 goto done;
14003 for (i = 0; i < argc; i++) {
14004 if (force_path) {
14005 error = got_object_id_by_path(&id, repo, commit,
14006 argv[i]);
14007 if (error)
14008 break;
14009 } else {
14010 error = got_repo_match_object_id(&id, &label, argv[i],
14011 GOT_OBJ_TYPE_ANY, NULL /* do not resolve tags */,
14012 repo);
14013 if (error) {
14014 if (error->code != GOT_ERR_BAD_OBJ_ID_STR &&
14015 error->code != GOT_ERR_NOT_REF)
14016 break;
14017 error = got_object_id_by_path(&id, repo,
14018 commit, argv[i]);
14019 if (error)
14020 break;
14024 error = got_object_get_type(&obj_type, repo, id);
14025 if (error)
14026 break;
14028 switch (obj_type) {
14029 case GOT_OBJ_TYPE_BLOB:
14030 error = cat_blob(id, repo, stdout);
14031 break;
14032 case GOT_OBJ_TYPE_TREE:
14033 error = cat_tree(id, repo, stdout);
14034 break;
14035 case GOT_OBJ_TYPE_COMMIT:
14036 error = cat_commit(id, repo, stdout);
14037 break;
14038 case GOT_OBJ_TYPE_TAG:
14039 error = cat_tag(id, repo, stdout);
14040 break;
14041 default:
14042 error = got_error(GOT_ERR_OBJ_TYPE);
14043 break;
14045 if (error)
14046 break;
14047 free(label);
14048 label = NULL;
14049 free(id);
14050 id = NULL;
14052 done:
14053 free(label);
14054 free(id);
14055 free(commit_id);
14056 if (commit)
14057 got_object_commit_close(commit);
14058 if (worktree)
14059 got_worktree_close(worktree);
14060 if (repo) {
14061 const struct got_error *close_err = got_repo_close(repo);
14062 if (error == NULL)
14063 error = close_err;
14065 if (pack_fds) {
14066 const struct got_error *pack_err =
14067 got_repo_pack_fds_close(pack_fds);
14068 if (error == NULL)
14069 error = pack_err;
14072 got_ref_list_free(&refs);
14073 return error;
14076 __dead static void
14077 usage_info(void)
14079 fprintf(stderr, "usage: %s info [path ...]\n",
14080 getprogname());
14081 exit(1);
14084 static const struct got_error *
14085 print_path_info(void *arg, const char *path, mode_t mode, time_t mtime,
14086 struct got_object_id *blob_id, struct got_object_id *staged_blob_id,
14087 struct got_object_id *commit_id)
14089 const struct got_error *err = NULL;
14090 char *id_str = NULL;
14091 char datebuf[128];
14092 struct tm mytm, *tm;
14093 struct got_pathlist_head *paths = arg;
14094 struct got_pathlist_entry *pe;
14097 * Clear error indication from any of the path arguments which
14098 * would cause this file index entry to be displayed.
14100 TAILQ_FOREACH(pe, paths, entry) {
14101 if (got_path_cmp(path, pe->path, strlen(path),
14102 pe->path_len) == 0 ||
14103 got_path_is_child(path, pe->path, pe->path_len))
14104 pe->data = NULL; /* no error */
14107 printf(GOT_COMMIT_SEP_STR);
14108 if (S_ISLNK(mode))
14109 printf("symlink: %s\n", path);
14110 else if (S_ISREG(mode)) {
14111 printf("file: %s\n", path);
14112 printf("mode: %o\n", mode & (S_IRWXU | S_IRWXG | S_IRWXO));
14113 } else if (S_ISDIR(mode))
14114 printf("directory: %s\n", path);
14115 else
14116 printf("something: %s\n", path);
14118 tm = localtime_r(&mtime, &mytm);
14119 if (tm == NULL)
14120 return NULL;
14121 if (strftime(datebuf, sizeof(datebuf), "%c %Z", tm) == 0)
14122 return got_error(GOT_ERR_NO_SPACE);
14123 printf("timestamp: %s\n", datebuf);
14125 if (blob_id) {
14126 err = got_object_id_str(&id_str, blob_id);
14127 if (err)
14128 return err;
14129 printf("based on blob: %s\n", id_str);
14130 free(id_str);
14133 if (staged_blob_id) {
14134 err = got_object_id_str(&id_str, staged_blob_id);
14135 if (err)
14136 return err;
14137 printf("based on staged blob: %s\n", id_str);
14138 free(id_str);
14141 if (commit_id) {
14142 err = got_object_id_str(&id_str, commit_id);
14143 if (err)
14144 return err;
14145 printf("based on commit: %s\n", id_str);
14146 free(id_str);
14149 return NULL;
14152 static const struct got_error *
14153 cmd_info(int argc, char *argv[])
14155 const struct got_error *error = NULL;
14156 struct got_worktree *worktree = NULL;
14157 char *cwd = NULL, *id_str = NULL;
14158 struct got_pathlist_head paths;
14159 char *uuidstr = NULL;
14160 int ch, show_files = 0;
14162 TAILQ_INIT(&paths);
14164 #ifndef PROFILE
14165 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
14166 NULL) == -1)
14167 err(1, "pledge");
14168 #endif
14170 while ((ch = getopt(argc, argv, "")) != -1) {
14171 switch (ch) {
14172 default:
14173 usage_info();
14174 /* NOTREACHED */
14178 argc -= optind;
14179 argv += optind;
14181 cwd = getcwd(NULL, 0);
14182 if (cwd == NULL) {
14183 error = got_error_from_errno("getcwd");
14184 goto done;
14187 error = got_worktree_open(&worktree, cwd);
14188 if (error) {
14189 if (error->code == GOT_ERR_NOT_WORKTREE)
14190 error = wrap_not_worktree_error(error, "info", cwd);
14191 goto done;
14194 #ifndef PROFILE
14195 /* Remove "wpath cpath proc exec sendfd" promises. */
14196 if (pledge("stdio rpath flock unveil", NULL) == -1)
14197 err(1, "pledge");
14198 #endif
14199 error = apply_unveil(NULL, 0, got_worktree_get_root_path(worktree));
14200 if (error)
14201 goto done;
14203 if (argc >= 1) {
14204 error = get_worktree_paths_from_argv(&paths, argc, argv,
14205 worktree);
14206 if (error)
14207 goto done;
14208 show_files = 1;
14211 error = got_object_id_str(&id_str,
14212 got_worktree_get_base_commit_id(worktree));
14213 if (error)
14214 goto done;
14216 error = got_worktree_get_uuid(&uuidstr, worktree);
14217 if (error)
14218 goto done;
14220 printf("work tree: %s\n", got_worktree_get_root_path(worktree));
14221 printf("work tree base commit: %s\n", id_str);
14222 printf("work tree path prefix: %s\n",
14223 got_worktree_get_path_prefix(worktree));
14224 printf("work tree branch reference: %s\n",
14225 got_worktree_get_head_ref_name(worktree));
14226 printf("work tree UUID: %s\n", uuidstr);
14227 printf("repository: %s\n", got_worktree_get_repo_path(worktree));
14229 if (show_files) {
14230 struct got_pathlist_entry *pe;
14231 TAILQ_FOREACH(pe, &paths, entry) {
14232 if (pe->path_len == 0)
14233 continue;
14235 * Assume this path will fail. This will be corrected
14236 * in print_path_info() in case the path does suceeed.
14238 pe->data = (void *)got_error(GOT_ERR_BAD_PATH);
14240 error = got_worktree_path_info(worktree, &paths,
14241 print_path_info, &paths, check_cancelled, NULL);
14242 if (error)
14243 goto done;
14244 TAILQ_FOREACH(pe, &paths, entry) {
14245 if (pe->data != NULL) {
14246 const struct got_error *perr;
14248 perr = pe->data;
14249 error = got_error_fmt(perr->code, "%s",
14250 pe->path);
14251 break;
14255 done:
14256 if (worktree)
14257 got_worktree_close(worktree);
14258 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
14259 free(cwd);
14260 free(id_str);
14261 free(uuidstr);
14262 return error;