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 static const struct got_error *
8168 patch_progress(void *arg, const char *old, const char *new,
8169 unsigned char status, const struct got_error *error, int old_from,
8170 int old_lines, int new_from, int new_lines, int offset,
8171 int ws_mangled, const struct got_error *hunk_err)
8173 const char *path = new == NULL ? old : new;
8175 while (*path == '/')
8176 path++;
8178 if (status != 0)
8179 printf("%c %s\n", status, path);
8181 if (error != NULL)
8182 fprintf(stderr, "%s: %s\n", getprogname(), error->msg);
8184 if (offset != 0 || hunk_err != NULL || ws_mangled) {
8185 printf("@@ -%d,%d +%d,%d @@ ", old_from,
8186 old_lines, new_from, new_lines);
8187 if (hunk_err != NULL)
8188 printf("%s\n", hunk_err->msg);
8189 else if (offset != 0)
8190 printf("applied with offset %d\n", offset);
8191 else
8192 printf("hunk contains mangled whitespace\n");
8195 return NULL;
8198 static const struct got_error *
8199 cmd_patch(int argc, char *argv[])
8201 const struct got_error *error = NULL, *close_error = NULL;
8202 struct got_worktree *worktree = NULL;
8203 struct got_repository *repo = NULL;
8204 struct got_reflist_head refs;
8205 struct got_object_id *commit_id = NULL;
8206 const char *commit_id_str = NULL;
8207 struct stat sb;
8208 const char *errstr;
8209 char *cwd = NULL;
8210 int ch, nop = 0, strip = -1, reverse = 0;
8211 int patchfd;
8212 int *pack_fds = NULL;
8214 TAILQ_INIT(&refs);
8216 #ifndef PROFILE
8217 if (pledge("stdio rpath wpath cpath fattr proc exec sendfd flock "
8218 "unveil", NULL) == -1)
8219 err(1, "pledge");
8220 #endif
8222 while ((ch = getopt(argc, argv, "c:np:R")) != -1) {
8223 switch (ch) {
8224 case 'c':
8225 commit_id_str = optarg;
8226 break;
8227 case 'n':
8228 nop = 1;
8229 break;
8230 case 'p':
8231 strip = strtonum(optarg, 0, INT_MAX, &errstr);
8232 if (errstr != NULL)
8233 errx(1, "pathname strip count is %s: %s",
8234 errstr, optarg);
8235 break;
8236 case 'R':
8237 reverse = 1;
8238 break;
8239 default:
8240 usage_patch();
8241 /* NOTREACHED */
8245 argc -= optind;
8246 argv += optind;
8248 if (argc == 0) {
8249 error = patch_from_stdin(&patchfd);
8250 if (error)
8251 return error;
8252 } else if (argc == 1) {
8253 patchfd = open(argv[0], O_RDONLY);
8254 if (patchfd == -1) {
8255 error = got_error_from_errno2("open", argv[0]);
8256 return error;
8258 if (fstat(patchfd, &sb) == -1) {
8259 error = got_error_from_errno2("fstat", argv[0]);
8260 goto done;
8262 if (!S_ISREG(sb.st_mode)) {
8263 error = got_error_path(argv[0], GOT_ERR_BAD_FILETYPE);
8264 goto done;
8266 } else
8267 usage_patch();
8269 if ((cwd = getcwd(NULL, 0)) == NULL) {
8270 error = got_error_from_errno("getcwd");
8271 goto done;
8274 error = got_repo_pack_fds_open(&pack_fds);
8275 if (error != NULL)
8276 goto done;
8278 error = got_worktree_open(&worktree, cwd);
8279 if (error != NULL)
8280 goto done;
8282 const char *repo_path = got_worktree_get_repo_path(worktree);
8283 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
8284 if (error != NULL)
8285 goto done;
8287 error = apply_unveil(got_repo_get_path(repo), 0,
8288 got_worktree_get_root_path(worktree));
8289 if (error != NULL)
8290 goto done;
8292 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
8293 if (error)
8294 goto done;
8296 if (commit_id_str != NULL) {
8297 error = got_repo_match_object_id(&commit_id, NULL,
8298 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
8299 if (error)
8300 goto done;
8303 error = got_patch(patchfd, worktree, repo, nop, strip, reverse,
8304 commit_id, &patch_progress, NULL, check_cancelled, NULL);
8306 done:
8307 got_ref_list_free(&refs);
8308 free(commit_id);
8309 if (repo) {
8310 close_error = got_repo_close(repo);
8311 if (error == NULL)
8312 error = close_error;
8314 if (worktree != NULL) {
8315 close_error = got_worktree_close(worktree);
8316 if (error == NULL)
8317 error = close_error;
8319 if (pack_fds) {
8320 const struct got_error *pack_err =
8321 got_repo_pack_fds_close(pack_fds);
8322 if (error == NULL)
8323 error = pack_err;
8325 free(cwd);
8326 return error;
8329 __dead static void
8330 usage_revert(void)
8332 fprintf(stderr, "usage: %s revert [-pR] [-F response-script] path ...\n",
8333 getprogname());
8334 exit(1);
8337 static const struct got_error *
8338 revert_progress(void *arg, unsigned char status, const char *path)
8340 if (status == GOT_STATUS_UNVERSIONED)
8341 return NULL;
8343 while (path[0] == '/')
8344 path++;
8345 printf("%c %s\n", status, path);
8346 return NULL;
8349 struct choose_patch_arg {
8350 FILE *patch_script_file;
8351 const char *action;
8354 static const struct got_error *
8355 show_change(unsigned char status, const char *path, FILE *patch_file, int n,
8356 int nchanges, const char *action)
8358 const struct got_error *err;
8359 char *line = NULL;
8360 size_t linesize = 0;
8361 ssize_t linelen;
8363 switch (status) {
8364 case GOT_STATUS_ADD:
8365 printf("A %s\n%s this addition? [y/n] ", path, action);
8366 break;
8367 case GOT_STATUS_DELETE:
8368 printf("D %s\n%s this deletion? [y/n] ", path, action);
8369 break;
8370 case GOT_STATUS_MODIFY:
8371 if (fseek(patch_file, 0L, SEEK_SET) == -1)
8372 return got_error_from_errno("fseek");
8373 printf(GOT_COMMIT_SEP_STR);
8374 while ((linelen = getline(&line, &linesize, patch_file)) != -1)
8375 printf("%s", line);
8376 if (linelen == -1 && ferror(patch_file)) {
8377 err = got_error_from_errno("getline");
8378 free(line);
8379 return err;
8381 free(line);
8382 printf(GOT_COMMIT_SEP_STR);
8383 printf("M %s (change %d of %d)\n%s this change? [y/n/q] ",
8384 path, n, nchanges, action);
8385 break;
8386 default:
8387 return got_error_path(path, GOT_ERR_FILE_STATUS);
8390 fflush(stdout);
8391 return NULL;
8394 static const struct got_error *
8395 choose_patch(int *choice, void *arg, unsigned char status, const char *path,
8396 FILE *patch_file, int n, int nchanges)
8398 const struct got_error *err = NULL;
8399 char *line = NULL;
8400 size_t linesize = 0;
8401 ssize_t linelen;
8402 int resp = ' ';
8403 struct choose_patch_arg *a = arg;
8405 *choice = GOT_PATCH_CHOICE_NONE;
8407 if (a->patch_script_file) {
8408 char *nl;
8409 err = show_change(status, path, patch_file, n, nchanges,
8410 a->action);
8411 if (err)
8412 return err;
8413 linelen = getline(&line, &linesize, a->patch_script_file);
8414 if (linelen == -1) {
8415 if (ferror(a->patch_script_file))
8416 return got_error_from_errno("getline");
8417 return NULL;
8419 nl = strchr(line, '\n');
8420 if (nl)
8421 *nl = '\0';
8422 if (strcmp(line, "y") == 0) {
8423 *choice = GOT_PATCH_CHOICE_YES;
8424 printf("y\n");
8425 } else if (strcmp(line, "n") == 0) {
8426 *choice = GOT_PATCH_CHOICE_NO;
8427 printf("n\n");
8428 } else if (strcmp(line, "q") == 0 &&
8429 status == GOT_STATUS_MODIFY) {
8430 *choice = GOT_PATCH_CHOICE_QUIT;
8431 printf("q\n");
8432 } else
8433 printf("invalid response '%s'\n", line);
8434 free(line);
8435 return NULL;
8438 while (resp != 'y' && resp != 'n' && resp != 'q') {
8439 err = show_change(status, path, patch_file, n, nchanges,
8440 a->action);
8441 if (err)
8442 return err;
8443 resp = getchar();
8444 if (resp == '\n')
8445 resp = getchar();
8446 if (status == GOT_STATUS_MODIFY) {
8447 if (resp != 'y' && resp != 'n' && resp != 'q') {
8448 printf("invalid response '%c'\n", resp);
8449 resp = ' ';
8451 } else if (resp != 'y' && resp != 'n') {
8452 printf("invalid response '%c'\n", resp);
8453 resp = ' ';
8457 if (resp == 'y')
8458 *choice = GOT_PATCH_CHOICE_YES;
8459 else if (resp == 'n')
8460 *choice = GOT_PATCH_CHOICE_NO;
8461 else if (resp == 'q' && status == GOT_STATUS_MODIFY)
8462 *choice = GOT_PATCH_CHOICE_QUIT;
8464 return NULL;
8467 struct wt_commitable_path_arg {
8468 struct got_pathlist_head *commit_paths;
8469 int *has_changes;
8473 * Shortcut work tree status callback to determine if the set of paths scanned
8474 * has at least one versioned path that is being modified and, if not NULL, is
8475 * in the arg->commit_paths list. Set arg and return GOT_ERR_FILE_MODIFIED as
8476 * soon as a path is passed with a status that satisfies this criteria.
8478 static const struct got_error *
8479 worktree_has_commitable_path(void *arg, unsigned char status,
8480 unsigned char staged_status, const char *path,
8481 struct got_object_id *blob_id, struct got_object_id *staged_blob_id,
8482 struct got_object_id *commit_id, int dirfd, const char *de_name)
8484 struct wt_commitable_path_arg *a = arg;
8486 if (status == staged_status && (status == GOT_STATUS_DELETE))
8487 status = GOT_STATUS_NO_CHANGE;
8489 if (!(status == GOT_STATUS_NO_CHANGE ||
8490 status == GOT_STATUS_UNVERSIONED) ||
8491 staged_status != GOT_STATUS_NO_CHANGE) {
8492 if (a->commit_paths != NULL) {
8493 struct got_pathlist_entry *pe;
8495 TAILQ_FOREACH(pe, a->commit_paths, entry) {
8496 if (strncmp(path, pe->path,
8497 pe->path_len) == 0) {
8498 *a->has_changes = 1;
8499 break;
8502 } else
8503 *a->has_changes = 1;
8505 if (*a->has_changes)
8506 return got_error(GOT_ERR_FILE_MODIFIED);
8509 return NULL;
8513 * Check that the changeset of the commit identified by id is
8514 * comprised of at least one modified path that is being committed.
8516 static const struct got_error *
8517 commit_path_changed_in_worktree(struct wt_commitable_path_arg *wcpa,
8518 struct got_object_id *id, struct got_worktree *worktree,
8519 struct got_repository *repo)
8521 const struct got_error *err;
8522 struct got_pathlist_head paths;
8523 struct got_commit_object *commit = NULL, *pcommit = NULL;
8524 struct got_tree_object *tree = NULL, *ptree = NULL;
8525 struct got_object_qid *pid;
8527 TAILQ_INIT(&paths);
8529 err = got_object_open_as_commit(&commit, repo, id);
8530 if (err)
8531 goto done;
8533 err = got_object_open_as_tree(&tree, repo,
8534 got_object_commit_get_tree_id(commit));
8535 if (err)
8536 goto done;
8538 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
8539 if (pid != NULL) {
8540 err = got_object_open_as_commit(&pcommit, repo, &pid->id);
8541 if (err)
8542 goto done;
8544 err = got_object_open_as_tree(&ptree, repo,
8545 got_object_commit_get_tree_id(pcommit));
8546 if (err)
8547 goto done;
8550 err = got_diff_tree(ptree, tree, NULL, NULL, -1, -1, "", "", repo,
8551 got_diff_tree_collect_changed_paths, &paths, 0);
8552 if (err)
8553 goto done;
8555 err = got_worktree_status(worktree, &paths, repo, 0,
8556 worktree_has_commitable_path, wcpa, check_cancelled, NULL);
8557 if (err && err->code == GOT_ERR_FILE_MODIFIED) {
8559 * At least one changed path in the referenced commit is
8560 * modified in the work tree, that's all we need to know!
8562 err = NULL;
8565 done:
8566 got_pathlist_free(&paths, GOT_PATHLIST_FREE_ALL);
8567 if (commit)
8568 got_object_commit_close(commit);
8569 if (pcommit)
8570 got_object_commit_close(pcommit);
8571 if (tree)
8572 got_object_tree_close(tree);
8573 if (ptree)
8574 got_object_tree_close(ptree);
8575 return err;
8579 * Remove any "logmsg" reference comprised entirely of paths that have
8580 * been reverted in this work tree. If any path in the logmsg ref changeset
8581 * remains in a changed state in the worktree, do not remove the reference.
8583 static const struct got_error *
8584 rm_logmsg_ref(struct got_worktree *worktree, struct got_repository *repo)
8586 const struct got_error *err;
8587 struct got_reflist_head refs;
8588 struct got_reflist_entry *re;
8589 struct got_commit_object *commit = NULL;
8590 struct got_object_id *commit_id = NULL;
8591 struct wt_commitable_path_arg wcpa;
8592 char *uuidstr = NULL;
8594 TAILQ_INIT(&refs);
8596 err = got_worktree_get_uuid(&uuidstr, worktree);
8597 if (err)
8598 goto done;
8600 err = got_ref_list(&refs, repo, "refs/got/worktree",
8601 got_ref_cmp_by_name, repo);
8602 if (err)
8603 goto done;
8605 TAILQ_FOREACH(re, &refs, entry) {
8606 const char *refname;
8607 int has_changes = 0;
8609 refname = got_ref_get_name(re->ref);
8611 if (!strncmp(refname, GOT_WORKTREE_CHERRYPICK_REF_PREFIX,
8612 GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN))
8613 refname += GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN + 1;
8614 else if (!strncmp(refname, GOT_WORKTREE_BACKOUT_REF_PREFIX,
8615 GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN))
8616 refname += GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN + 1;
8617 else
8618 continue;
8620 if (strncmp(refname, uuidstr, GOT_WORKTREE_UUID_STRLEN) == 0)
8621 refname += GOT_WORKTREE_UUID_STRLEN + 1; /* skip '-' */
8622 else
8623 continue;
8625 err = got_repo_match_object_id(&commit_id, NULL, refname,
8626 GOT_OBJ_TYPE_COMMIT, NULL, repo);
8627 if (err)
8628 goto done;
8630 err = got_object_open_as_commit(&commit, repo, commit_id);
8631 if (err)
8632 goto done;
8634 wcpa.commit_paths = NULL;
8635 wcpa.has_changes = &has_changes;
8637 err = commit_path_changed_in_worktree(&wcpa, commit_id,
8638 worktree, repo);
8639 if (err)
8640 goto done;
8642 if (!has_changes) {
8643 err = got_ref_delete(re->ref, repo);
8644 if (err)
8645 goto done;
8648 got_object_commit_close(commit);
8649 commit = NULL;
8650 free(commit_id);
8651 commit_id = NULL;
8654 done:
8655 free(uuidstr);
8656 free(commit_id);
8657 got_ref_list_free(&refs);
8658 if (commit)
8659 got_object_commit_close(commit);
8660 return err;
8663 static const struct got_error *
8664 cmd_revert(int argc, char *argv[])
8666 const struct got_error *error = NULL;
8667 struct got_worktree *worktree = NULL;
8668 struct got_repository *repo = NULL;
8669 char *cwd = NULL, *path = NULL;
8670 struct got_pathlist_head paths;
8671 struct got_pathlist_entry *pe;
8672 int ch, can_recurse = 0, pflag = 0;
8673 FILE *patch_script_file = NULL;
8674 const char *patch_script_path = NULL;
8675 struct choose_patch_arg cpa;
8676 int *pack_fds = NULL;
8678 TAILQ_INIT(&paths);
8680 #ifndef PROFILE
8681 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
8682 "unveil", NULL) == -1)
8683 err(1, "pledge");
8684 #endif
8686 while ((ch = getopt(argc, argv, "F:pR")) != -1) {
8687 switch (ch) {
8688 case 'F':
8689 patch_script_path = optarg;
8690 break;
8691 case 'p':
8692 pflag = 1;
8693 break;
8694 case 'R':
8695 can_recurse = 1;
8696 break;
8697 default:
8698 usage_revert();
8699 /* NOTREACHED */
8703 argc -= optind;
8704 argv += optind;
8706 if (argc < 1)
8707 usage_revert();
8708 if (patch_script_path && !pflag)
8709 errx(1, "-F option can only be used together with -p option");
8711 cwd = getcwd(NULL, 0);
8712 if (cwd == NULL) {
8713 error = got_error_from_errno("getcwd");
8714 goto done;
8717 error = got_repo_pack_fds_open(&pack_fds);
8718 if (error != NULL)
8719 goto done;
8721 error = got_worktree_open(&worktree, cwd);
8722 if (error) {
8723 if (error->code == GOT_ERR_NOT_WORKTREE)
8724 error = wrap_not_worktree_error(error, "revert", cwd);
8725 goto done;
8728 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
8729 NULL, pack_fds);
8730 if (error != NULL)
8731 goto done;
8733 if (patch_script_path) {
8734 patch_script_file = fopen(patch_script_path, "re");
8735 if (patch_script_file == NULL) {
8736 error = got_error_from_errno2("fopen",
8737 patch_script_path);
8738 goto done;
8743 * XXX "c" perm needed on repo dir to delete merge references.
8745 error = apply_unveil(got_repo_get_path(repo), 0,
8746 got_worktree_get_root_path(worktree));
8747 if (error)
8748 goto done;
8750 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
8751 if (error)
8752 goto done;
8754 if (!can_recurse) {
8755 char *ondisk_path;
8756 struct stat sb;
8757 TAILQ_FOREACH(pe, &paths, entry) {
8758 if (asprintf(&ondisk_path, "%s/%s",
8759 got_worktree_get_root_path(worktree),
8760 pe->path) == -1) {
8761 error = got_error_from_errno("asprintf");
8762 goto done;
8764 if (lstat(ondisk_path, &sb) == -1) {
8765 if (errno == ENOENT) {
8766 free(ondisk_path);
8767 continue;
8769 error = got_error_from_errno2("lstat",
8770 ondisk_path);
8771 free(ondisk_path);
8772 goto done;
8774 free(ondisk_path);
8775 if (S_ISDIR(sb.st_mode)) {
8776 error = got_error_msg(GOT_ERR_BAD_PATH,
8777 "reverting directories requires -R option");
8778 goto done;
8783 cpa.patch_script_file = patch_script_file;
8784 cpa.action = "revert";
8785 error = got_worktree_revert(worktree, &paths, revert_progress, NULL,
8786 pflag ? choose_patch : NULL, &cpa, repo);
8788 error = rm_logmsg_ref(worktree, repo);
8789 done:
8790 if (patch_script_file && fclose(patch_script_file) == EOF &&
8791 error == NULL)
8792 error = got_error_from_errno2("fclose", patch_script_path);
8793 if (repo) {
8794 const struct got_error *close_err = got_repo_close(repo);
8795 if (error == NULL)
8796 error = close_err;
8798 if (worktree)
8799 got_worktree_close(worktree);
8800 if (pack_fds) {
8801 const struct got_error *pack_err =
8802 got_repo_pack_fds_close(pack_fds);
8803 if (error == NULL)
8804 error = pack_err;
8806 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
8807 free(path);
8808 free(cwd);
8809 return error;
8812 __dead static void
8813 usage_commit(void)
8815 fprintf(stderr, "usage: %s commit [-CNnS] [-A author] [-F path] "
8816 "[-m message] [path ...]\n", getprogname());
8817 exit(1);
8820 struct collect_commit_logmsg_arg {
8821 const char *cmdline_log;
8822 const char *prepared_log;
8823 const char *merged_log;
8824 int non_interactive;
8825 const char *editor;
8826 const char *worktree_path;
8827 const char *branch_name;
8828 const char *repo_path;
8829 char *logmsg_path;
8833 static const struct got_error *
8834 read_prepared_logmsg(char **logmsg, const char *path)
8836 const struct got_error *err = NULL;
8837 FILE *f = NULL;
8838 struct stat sb;
8839 size_t r;
8841 *logmsg = NULL;
8842 memset(&sb, 0, sizeof(sb));
8844 f = fopen(path, "re");
8845 if (f == NULL)
8846 return got_error_from_errno2("fopen", path);
8848 if (fstat(fileno(f), &sb) == -1) {
8849 err = got_error_from_errno2("fstat", path);
8850 goto done;
8852 if (sb.st_size == 0) {
8853 err = got_error(GOT_ERR_COMMIT_MSG_EMPTY);
8854 goto done;
8857 *logmsg = malloc(sb.st_size + 1);
8858 if (*logmsg == NULL) {
8859 err = got_error_from_errno("malloc");
8860 goto done;
8863 r = fread(*logmsg, 1, sb.st_size, f);
8864 if (r != sb.st_size) {
8865 if (ferror(f))
8866 err = got_error_from_errno2("fread", path);
8867 else
8868 err = got_error(GOT_ERR_IO);
8869 goto done;
8871 (*logmsg)[sb.st_size] = '\0';
8872 done:
8873 if (fclose(f) == EOF && err == NULL)
8874 err = got_error_from_errno2("fclose", path);
8875 if (err) {
8876 free(*logmsg);
8877 *logmsg = NULL;
8879 return err;
8882 static const struct got_error *
8883 collect_commit_logmsg(struct got_pathlist_head *commitable_paths,
8884 const char *diff_path, char **logmsg, void *arg)
8886 char *initial_content = NULL;
8887 struct got_pathlist_entry *pe;
8888 const struct got_error *err = NULL;
8889 char *template = NULL;
8890 char *prepared_msg = NULL, *merged_msg = NULL;
8891 struct collect_commit_logmsg_arg *a = arg;
8892 int initial_content_len;
8893 int fd = -1;
8894 size_t len;
8896 /* if a message was specified on the command line, just use it */
8897 if (a->cmdline_log != NULL && strlen(a->cmdline_log) != 0) {
8898 len = strlen(a->cmdline_log) + 1;
8899 *logmsg = malloc(len + 1);
8900 if (*logmsg == NULL)
8901 return got_error_from_errno("malloc");
8902 strlcpy(*logmsg, a->cmdline_log, len);
8903 return NULL;
8904 } else if (a->prepared_log != NULL && a->non_interactive)
8905 return read_prepared_logmsg(logmsg, a->prepared_log);
8907 if (asprintf(&template, "%s/logmsg", a->worktree_path) == -1)
8908 return got_error_from_errno("asprintf");
8910 err = got_opentemp_named_fd(&a->logmsg_path, &fd, template, "");
8911 if (err)
8912 goto done;
8914 if (a->prepared_log) {
8915 err = read_prepared_logmsg(&prepared_msg, a->prepared_log);
8916 if (err)
8917 goto done;
8918 } else if (a->merged_log) {
8919 err = read_prepared_logmsg(&merged_msg, a->merged_log);
8920 if (err)
8921 goto done;
8924 initial_content_len = asprintf(&initial_content,
8925 "%s%s\n# changes to be committed on branch %s:\n",
8926 prepared_msg ? prepared_msg : "",
8927 merged_msg ? merged_msg : "", a->branch_name);
8928 if (initial_content_len == -1) {
8929 err = got_error_from_errno("asprintf");
8930 goto done;
8933 if (write(fd, initial_content, initial_content_len) == -1) {
8934 err = got_error_from_errno2("write", a->logmsg_path);
8935 goto done;
8938 TAILQ_FOREACH(pe, commitable_paths, entry) {
8939 struct got_commitable *ct = pe->data;
8940 dprintf(fd, "# %c %s\n",
8941 got_commitable_get_status(ct),
8942 got_commitable_get_path(ct));
8945 if (diff_path) {
8946 dprintf(fd, "# detailed changes can be viewed in %s\n",
8947 diff_path);
8950 if (close(fd) == -1) {
8951 err = got_error_from_errno2("close", a->logmsg_path);
8952 goto done;
8954 fd = -1;
8956 err = edit_logmsg(logmsg, a->editor, a->logmsg_path, initial_content,
8957 initial_content_len, a->prepared_log ? 0 : 1);
8958 done:
8959 free(initial_content);
8960 free(template);
8961 free(prepared_msg);
8962 free(merged_msg);
8964 if (fd != -1 && close(fd) == -1 && err == NULL)
8965 err = got_error_from_errno2("close", a->logmsg_path);
8967 /* Editor is done; we can now apply unveil(2) */
8968 if (err == NULL)
8969 err = apply_unveil(a->repo_path, 0, a->worktree_path);
8970 if (err) {
8971 free(*logmsg);
8972 *logmsg = NULL;
8974 return err;
8977 static const struct got_error *
8978 cat_logmsg(FILE *f, struct got_commit_object *commit, const char *idstr,
8979 const char *type, int has_content)
8981 const struct got_error *err = NULL;
8982 char *logmsg = NULL;
8984 err = got_object_commit_get_logmsg(&logmsg, commit);
8985 if (err)
8986 return err;
8988 if (fprintf(f, "%s# log message of %s commit %s:%s",
8989 has_content ? "\n" : "", type, idstr, logmsg) < 0)
8990 err = got_ferror(f, GOT_ERR_IO);
8992 free(logmsg);
8993 return err;
8997 * Lookup "logmsg" references of backed-out and cherrypicked commits
8998 * belonging to the current work tree. If found, and the worktree has
8999 * at least one modified file that was changed in the referenced commit,
9000 * add its log message to a new temporary file at *logmsg_path.
9001 * Add all refs found to matched_refs to be scheduled for removal on
9002 * successful commit.
9004 static const struct got_error *
9005 lookup_logmsg_ref(char **logmsg_path, struct got_pathlist_head *paths,
9006 struct got_reflist_head *matched_refs, struct got_worktree *worktree,
9007 struct got_repository *repo)
9009 const struct got_error *err;
9010 struct got_commit_object *commit = NULL;
9011 struct got_object_id *id = NULL;
9012 struct got_reflist_head refs;
9013 struct got_reflist_entry *re, *re_match;
9014 FILE *f = NULL;
9015 char *uuidstr = NULL;
9016 int added_logmsg = 0;
9018 TAILQ_INIT(&refs);
9020 *logmsg_path = NULL;
9022 err = got_worktree_get_uuid(&uuidstr, worktree);
9023 if (err)
9024 goto done;
9026 err = got_ref_list(&refs, repo, "refs/got/worktree",
9027 got_ref_cmp_by_name, repo);
9028 if (err)
9029 goto done;
9031 TAILQ_FOREACH(re, &refs, entry) {
9032 const char *refname, *type;
9033 struct wt_commitable_path_arg wcpa;
9034 int add_logmsg = 0;
9036 refname = got_ref_get_name(re->ref);
9038 if (strncmp(refname, GOT_WORKTREE_CHERRYPICK_REF_PREFIX,
9039 GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN) == 0) {
9040 refname += GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN + 1;
9041 type = "cherrypicked";
9042 } else if (strncmp(refname, GOT_WORKTREE_BACKOUT_REF_PREFIX,
9043 GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN) == 0) {
9044 refname += GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN + 1;
9045 type = "backed-out";
9046 } else
9047 continue;
9049 if (strncmp(refname, uuidstr, GOT_WORKTREE_UUID_STRLEN) == 0)
9050 refname += GOT_WORKTREE_UUID_STRLEN + 1; /* skip '-' */
9051 else
9052 continue;
9054 err = got_repo_match_object_id(&id, NULL, refname,
9055 GOT_OBJ_TYPE_COMMIT, NULL, repo);
9056 if (err)
9057 goto done;
9059 err = got_object_open_as_commit(&commit, repo, id);
9060 if (err)
9061 goto done;
9063 wcpa.commit_paths = paths;
9064 wcpa.has_changes = &add_logmsg;
9066 err = commit_path_changed_in_worktree(&wcpa, id,
9067 worktree, repo);
9068 if (err)
9069 goto done;
9071 if (add_logmsg) {
9072 if (f == NULL) {
9073 err = got_opentemp_named(logmsg_path, &f,
9074 "got-commit-logmsg", "");
9075 if (err)
9076 goto done;
9078 err = cat_logmsg(f, commit, refname, type,
9079 added_logmsg);
9080 if (err)
9081 goto done;
9082 if (!added_logmsg)
9083 ++added_logmsg;
9085 err = got_reflist_entry_dup(&re_match, re);
9086 if (err)
9087 goto done;
9088 TAILQ_INSERT_HEAD(matched_refs, re_match, entry);
9091 got_object_commit_close(commit);
9092 commit = NULL;
9093 free(id);
9094 id = NULL;
9097 done:
9098 free(id);
9099 free(uuidstr);
9100 got_ref_list_free(&refs);
9101 if (commit)
9102 got_object_commit_close(commit);
9103 if (f && fclose(f) == EOF && err == NULL)
9104 err = got_error_from_errno("fclose");
9105 if (!added_logmsg) {
9106 if (*logmsg_path && unlink(*logmsg_path) != 0 && err == NULL)
9107 err = got_error_from_errno2("unlink", *logmsg_path);
9108 *logmsg_path = NULL;
9110 return err;
9113 static const struct got_error *
9114 cmd_commit(int argc, char *argv[])
9116 const struct got_error *error = NULL;
9117 struct got_worktree *worktree = NULL;
9118 struct got_repository *repo = NULL;
9119 char *cwd = NULL, *id_str = NULL;
9120 struct got_object_id *id = NULL;
9121 const char *logmsg = NULL;
9122 char *prepared_logmsg = NULL, *merged_logmsg = NULL;
9123 struct collect_commit_logmsg_arg cl_arg;
9124 const char *author = NULL;
9125 char *gitconfig_path = NULL, *editor = NULL, *committer = NULL;
9126 int ch, rebase_in_progress, histedit_in_progress, preserve_logmsg = 0;
9127 int allow_bad_symlinks = 0, non_interactive = 0, merge_in_progress = 0;
9128 int show_diff = 1, commit_conflicts = 0;
9129 struct got_pathlist_head paths;
9130 struct got_reflist_head refs;
9131 struct got_reflist_entry *re;
9132 int *pack_fds = NULL;
9134 TAILQ_INIT(&refs);
9135 TAILQ_INIT(&paths);
9136 cl_arg.logmsg_path = NULL;
9138 #ifndef PROFILE
9139 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
9140 "unveil", NULL) == -1)
9141 err(1, "pledge");
9142 #endif
9144 while ((ch = getopt(argc, argv, "A:CF:m:NnS")) != -1) {
9145 switch (ch) {
9146 case 'A':
9147 author = optarg;
9148 error = valid_author(author);
9149 if (error)
9150 return error;
9151 break;
9152 case 'C':
9153 commit_conflicts = 1;
9154 break;
9155 case 'F':
9156 if (logmsg != NULL)
9157 option_conflict('F', 'm');
9158 prepared_logmsg = realpath(optarg, NULL);
9159 if (prepared_logmsg == NULL)
9160 return got_error_from_errno2("realpath",
9161 optarg);
9162 break;
9163 case 'm':
9164 if (prepared_logmsg)
9165 option_conflict('m', 'F');
9166 logmsg = optarg;
9167 break;
9168 case 'N':
9169 non_interactive = 1;
9170 break;
9171 case 'n':
9172 show_diff = 0;
9173 break;
9174 case 'S':
9175 allow_bad_symlinks = 1;
9176 break;
9177 default:
9178 usage_commit();
9179 /* NOTREACHED */
9183 argc -= optind;
9184 argv += optind;
9186 cwd = getcwd(NULL, 0);
9187 if (cwd == NULL) {
9188 error = got_error_from_errno("getcwd");
9189 goto done;
9192 error = got_repo_pack_fds_open(&pack_fds);
9193 if (error != NULL)
9194 goto done;
9196 error = got_worktree_open(&worktree, cwd);
9197 if (error) {
9198 if (error->code == GOT_ERR_NOT_WORKTREE)
9199 error = wrap_not_worktree_error(error, "commit", cwd);
9200 goto done;
9203 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
9204 if (error)
9205 goto done;
9206 if (rebase_in_progress) {
9207 error = got_error(GOT_ERR_REBASING);
9208 goto done;
9211 error = got_worktree_histedit_in_progress(&histedit_in_progress,
9212 worktree);
9213 if (error)
9214 goto done;
9216 error = get_gitconfig_path(&gitconfig_path);
9217 if (error)
9218 goto done;
9219 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
9220 gitconfig_path, pack_fds);
9221 if (error != NULL)
9222 goto done;
9224 error = got_worktree_merge_in_progress(&merge_in_progress, worktree, repo);
9225 if (error)
9226 goto done;
9227 if (merge_in_progress) {
9228 error = got_error(GOT_ERR_MERGE_BUSY);
9229 goto done;
9232 error = get_author(&committer, repo, worktree);
9233 if (error)
9234 goto done;
9236 if (author == NULL)
9237 author = committer;
9240 * unveil(2) traverses exec(2); if an editor is used we have
9241 * to apply unveil after the log message has been written.
9243 if (logmsg == NULL || strlen(logmsg) == 0)
9244 error = get_editor(&editor);
9245 else
9246 error = apply_unveil(got_repo_get_path(repo), 0,
9247 got_worktree_get_root_path(worktree));
9248 if (error)
9249 goto done;
9251 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
9252 if (error)
9253 goto done;
9255 if (prepared_logmsg == NULL) {
9256 error = lookup_logmsg_ref(&merged_logmsg,
9257 argc > 0 ? &paths : NULL, &refs, worktree, repo);
9258 if (error)
9259 goto done;
9262 cl_arg.editor = editor;
9263 cl_arg.cmdline_log = logmsg;
9264 cl_arg.prepared_log = prepared_logmsg;
9265 cl_arg.merged_log = merged_logmsg;
9266 cl_arg.non_interactive = non_interactive;
9267 cl_arg.worktree_path = got_worktree_get_root_path(worktree);
9268 cl_arg.branch_name = got_worktree_get_head_ref_name(worktree);
9269 if (!histedit_in_progress) {
9270 if (strncmp(cl_arg.branch_name, "refs/heads/", 11) != 0) {
9271 error = got_error(GOT_ERR_COMMIT_BRANCH);
9272 goto done;
9274 cl_arg.branch_name += 11;
9276 cl_arg.repo_path = got_repo_get_path(repo);
9277 error = got_worktree_commit(&id, worktree, &paths, author, committer,
9278 allow_bad_symlinks, show_diff, commit_conflicts,
9279 collect_commit_logmsg, &cl_arg, print_status, NULL, repo);
9280 if (error) {
9281 if (error->code != GOT_ERR_COMMIT_MSG_EMPTY &&
9282 cl_arg.logmsg_path != NULL)
9283 preserve_logmsg = 1;
9284 goto done;
9287 error = got_object_id_str(&id_str, id);
9288 if (error)
9289 goto done;
9290 printf("Created commit %s\n", id_str);
9292 TAILQ_FOREACH(re, &refs, entry) {
9293 error = got_ref_delete(re->ref, repo);
9294 if (error)
9295 goto done;
9298 done:
9299 if (preserve_logmsg) {
9300 fprintf(stderr, "%s: log message preserved in %s\n",
9301 getprogname(), cl_arg.logmsg_path);
9302 } else if (cl_arg.logmsg_path && unlink(cl_arg.logmsg_path) == -1 &&
9303 error == NULL)
9304 error = got_error_from_errno2("unlink", cl_arg.logmsg_path);
9305 free(cl_arg.logmsg_path);
9306 if (merged_logmsg && unlink(merged_logmsg) == -1 && error == NULL)
9307 error = got_error_from_errno2("unlink", merged_logmsg);
9308 free(merged_logmsg);
9309 if (repo) {
9310 const struct got_error *close_err = got_repo_close(repo);
9311 if (error == NULL)
9312 error = close_err;
9314 if (worktree)
9315 got_worktree_close(worktree);
9316 if (pack_fds) {
9317 const struct got_error *pack_err =
9318 got_repo_pack_fds_close(pack_fds);
9319 if (error == NULL)
9320 error = pack_err;
9322 got_ref_list_free(&refs);
9323 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
9324 free(cwd);
9325 free(id_str);
9326 free(gitconfig_path);
9327 free(editor);
9328 free(committer);
9329 free(prepared_logmsg);
9330 return error;
9333 __dead static void
9334 usage_send(void)
9336 fprintf(stderr, "usage: %s send [-afqTv] [-b branch] [-d branch] "
9337 "[-r repository-path] [-t tag] [remote-repository]\n",
9338 getprogname());
9339 exit(1);
9342 static void
9343 print_load_info(int print_colored, int print_found, int print_trees,
9344 int ncolored, int nfound, int ntrees)
9346 if (print_colored) {
9347 printf("%d commit%s colored", ncolored,
9348 ncolored == 1 ? "" : "s");
9350 if (print_found) {
9351 printf("%s%d object%s found",
9352 ncolored > 0 ? "; " : "",
9353 nfound, nfound == 1 ? "" : "s");
9355 if (print_trees) {
9356 printf("; %d tree%s scanned", ntrees,
9357 ntrees == 1 ? "" : "s");
9361 struct got_send_progress_arg {
9362 char last_scaled_packsize[FMT_SCALED_STRSIZE];
9363 int verbosity;
9364 int last_ncolored;
9365 int last_nfound;
9366 int last_ntrees;
9367 int loading_done;
9368 int last_ncommits;
9369 int last_nobj_total;
9370 int last_p_deltify;
9371 int last_p_written;
9372 int last_p_sent;
9373 int printed_something;
9374 int sent_something;
9375 struct got_pathlist_head *delete_branches;
9378 static const struct got_error *
9379 send_progress(void *arg, int ncolored, int nfound, int ntrees,
9380 off_t packfile_size, int ncommits, int nobj_total, int nobj_deltify,
9381 int nobj_written, off_t bytes_sent, const char *refname,
9382 const char *errmsg, int success)
9384 struct got_send_progress_arg *a = arg;
9385 char scaled_packsize[FMT_SCALED_STRSIZE];
9386 char scaled_sent[FMT_SCALED_STRSIZE];
9387 int p_deltify = 0, p_written = 0, p_sent = 0;
9388 int print_colored = 0, print_found = 0, print_trees = 0;
9389 int print_searching = 0, print_total = 0;
9390 int print_deltify = 0, print_written = 0, print_sent = 0;
9392 if (a->verbosity < 0)
9393 return NULL;
9395 if (refname) {
9396 const char *status = success ? "accepted" : "rejected";
9398 if (success) {
9399 struct got_pathlist_entry *pe;
9400 TAILQ_FOREACH(pe, a->delete_branches, entry) {
9401 const char *branchname = pe->path;
9402 if (got_path_cmp(branchname, refname,
9403 strlen(branchname), strlen(refname)) == 0) {
9404 status = "deleted";
9405 a->sent_something = 1;
9406 break;
9411 if (a->printed_something)
9412 putchar('\n');
9413 printf("Server has %s %s", status, refname);
9414 if (errmsg)
9415 printf(": %s", errmsg);
9416 a->printed_something = 1;
9417 return NULL;
9420 if (a->last_ncolored != ncolored) {
9421 print_colored = 1;
9422 a->last_ncolored = ncolored;
9425 if (a->last_nfound != nfound) {
9426 print_colored = 1;
9427 print_found = 1;
9428 a->last_nfound = nfound;
9431 if (a->last_ntrees != ntrees) {
9432 print_colored = 1;
9433 print_found = 1;
9434 print_trees = 1;
9435 a->last_ntrees = ntrees;
9438 if ((print_colored || print_found || print_trees) &&
9439 !a->loading_done) {
9440 printf("\r");
9441 print_load_info(print_colored, print_found, print_trees,
9442 ncolored, nfound, ntrees);
9443 a->printed_something = 1;
9444 fflush(stdout);
9445 return NULL;
9446 } else if (!a->loading_done) {
9447 printf("\r");
9448 print_load_info(1, 1, 1, ncolored, nfound, ntrees);
9449 printf("\n");
9450 a->loading_done = 1;
9453 if (fmt_scaled(packfile_size, scaled_packsize) == -1)
9454 return got_error_from_errno("fmt_scaled");
9455 if (fmt_scaled(bytes_sent, scaled_sent) == -1)
9456 return got_error_from_errno("fmt_scaled");
9458 if (a->last_ncommits != ncommits) {
9459 print_searching = 1;
9460 a->last_ncommits = ncommits;
9463 if (a->last_nobj_total != nobj_total) {
9464 print_searching = 1;
9465 print_total = 1;
9466 a->last_nobj_total = nobj_total;
9469 if (packfile_size > 0 && (a->last_scaled_packsize[0] == '\0' ||
9470 strcmp(scaled_packsize, a->last_scaled_packsize)) != 0) {
9471 if (strlcpy(a->last_scaled_packsize, scaled_packsize,
9472 FMT_SCALED_STRSIZE) >= FMT_SCALED_STRSIZE)
9473 return got_error(GOT_ERR_NO_SPACE);
9476 if (nobj_deltify > 0 || nobj_written > 0) {
9477 if (nobj_deltify > 0) {
9478 p_deltify = (nobj_deltify * 100) / nobj_total;
9479 if (p_deltify != a->last_p_deltify) {
9480 a->last_p_deltify = p_deltify;
9481 print_searching = 1;
9482 print_total = 1;
9483 print_deltify = 1;
9486 if (nobj_written > 0) {
9487 p_written = (nobj_written * 100) / nobj_total;
9488 if (p_written != a->last_p_written) {
9489 a->last_p_written = p_written;
9490 print_searching = 1;
9491 print_total = 1;
9492 print_deltify = 1;
9493 print_written = 1;
9498 if (bytes_sent > 0) {
9499 p_sent = (bytes_sent * 100) / packfile_size;
9500 if (p_sent != a->last_p_sent) {
9501 a->last_p_sent = p_sent;
9502 print_searching = 1;
9503 print_total = 1;
9504 print_deltify = 1;
9505 print_written = 1;
9506 print_sent = 1;
9508 a->sent_something = 1;
9511 if (print_searching || print_total || print_deltify || print_written ||
9512 print_sent)
9513 printf("\r");
9514 if (print_searching)
9515 printf("packing %d reference%s", ncommits,
9516 ncommits == 1 ? "" : "s");
9517 if (print_total)
9518 printf("; %d object%s", nobj_total,
9519 nobj_total == 1 ? "" : "s");
9520 if (print_deltify)
9521 printf("; deltify: %d%%", p_deltify);
9522 if (print_sent)
9523 printf("; uploading pack: %*s %d%%", FMT_SCALED_STRSIZE - 2,
9524 scaled_packsize, p_sent);
9525 else if (print_written)
9526 printf("; writing pack: %*s %d%%", FMT_SCALED_STRSIZE - 2,
9527 scaled_packsize, p_written);
9528 if (print_searching || print_total || print_deltify ||
9529 print_written || print_sent) {
9530 a->printed_something = 1;
9531 fflush(stdout);
9533 return NULL;
9536 static const struct got_error *
9537 cmd_send(int argc, char *argv[])
9539 const struct got_error *error = NULL;
9540 char *cwd = NULL, *repo_path = NULL;
9541 const char *remote_name;
9542 char *proto = NULL, *host = NULL, *port = NULL;
9543 char *repo_name = NULL, *server_path = NULL;
9544 const struct got_remote_repo *remotes, *remote = NULL;
9545 int nremotes, nbranches = 0, ndelete_branches = 0;
9546 struct got_repository *repo = NULL;
9547 struct got_worktree *worktree = NULL;
9548 const struct got_gotconfig *repo_conf = NULL, *worktree_conf = NULL;
9549 struct got_pathlist_head branches;
9550 struct got_pathlist_head tags;
9551 struct got_reflist_head all_branches;
9552 struct got_reflist_head all_tags;
9553 struct got_pathlist_head delete_args;
9554 struct got_pathlist_head delete_branches;
9555 struct got_reflist_entry *re;
9556 struct got_pathlist_entry *pe;
9557 int i, ch, sendfd = -1, sendstatus;
9558 pid_t sendpid = -1;
9559 struct got_send_progress_arg spa;
9560 int verbosity = 0, overwrite_refs = 0;
9561 int send_all_branches = 0, send_all_tags = 0;
9562 struct got_reference *ref = NULL;
9563 int *pack_fds = NULL;
9565 TAILQ_INIT(&branches);
9566 TAILQ_INIT(&tags);
9567 TAILQ_INIT(&all_branches);
9568 TAILQ_INIT(&all_tags);
9569 TAILQ_INIT(&delete_args);
9570 TAILQ_INIT(&delete_branches);
9572 while ((ch = getopt(argc, argv, "ab:d:fqr:Tt:v")) != -1) {
9573 switch (ch) {
9574 case 'a':
9575 send_all_branches = 1;
9576 break;
9577 case 'b':
9578 error = got_pathlist_append(&branches, optarg, NULL);
9579 if (error)
9580 return error;
9581 nbranches++;
9582 break;
9583 case 'd':
9584 error = got_pathlist_append(&delete_args, optarg, NULL);
9585 if (error)
9586 return error;
9587 break;
9588 case 'f':
9589 overwrite_refs = 1;
9590 break;
9591 case 'q':
9592 verbosity = -1;
9593 break;
9594 case 'r':
9595 repo_path = realpath(optarg, NULL);
9596 if (repo_path == NULL)
9597 return got_error_from_errno2("realpath",
9598 optarg);
9599 got_path_strip_trailing_slashes(repo_path);
9600 break;
9601 case 'T':
9602 send_all_tags = 1;
9603 break;
9604 case 't':
9605 error = got_pathlist_append(&tags, optarg, NULL);
9606 if (error)
9607 return error;
9608 break;
9609 case 'v':
9610 if (verbosity < 0)
9611 verbosity = 0;
9612 else if (verbosity < 3)
9613 verbosity++;
9614 break;
9615 default:
9616 usage_send();
9617 /* NOTREACHED */
9620 argc -= optind;
9621 argv += optind;
9623 if (send_all_branches && !TAILQ_EMPTY(&branches))
9624 option_conflict('a', 'b');
9625 if (send_all_tags && !TAILQ_EMPTY(&tags))
9626 option_conflict('T', 't');
9629 if (argc == 0)
9630 remote_name = GOT_SEND_DEFAULT_REMOTE_NAME;
9631 else if (argc == 1)
9632 remote_name = argv[0];
9633 else
9634 usage_send();
9636 cwd = getcwd(NULL, 0);
9637 if (cwd == NULL) {
9638 error = got_error_from_errno("getcwd");
9639 goto done;
9642 error = got_repo_pack_fds_open(&pack_fds);
9643 if (error != NULL)
9644 goto done;
9646 if (repo_path == NULL) {
9647 error = got_worktree_open(&worktree, cwd);
9648 if (error && error->code != GOT_ERR_NOT_WORKTREE)
9649 goto done;
9650 else
9651 error = NULL;
9652 if (worktree) {
9653 repo_path =
9654 strdup(got_worktree_get_repo_path(worktree));
9655 if (repo_path == NULL)
9656 error = got_error_from_errno("strdup");
9657 if (error)
9658 goto done;
9659 } else {
9660 repo_path = strdup(cwd);
9661 if (repo_path == NULL) {
9662 error = got_error_from_errno("strdup");
9663 goto done;
9668 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
9669 if (error)
9670 goto done;
9672 if (worktree) {
9673 worktree_conf = got_worktree_get_gotconfig(worktree);
9674 if (worktree_conf) {
9675 got_gotconfig_get_remotes(&nremotes, &remotes,
9676 worktree_conf);
9677 for (i = 0; i < nremotes; i++) {
9678 if (strcmp(remotes[i].name, remote_name) == 0) {
9679 remote = &remotes[i];
9680 break;
9685 if (remote == NULL) {
9686 repo_conf = got_repo_get_gotconfig(repo);
9687 if (repo_conf) {
9688 got_gotconfig_get_remotes(&nremotes, &remotes,
9689 repo_conf);
9690 for (i = 0; i < nremotes; i++) {
9691 if (strcmp(remotes[i].name, remote_name) == 0) {
9692 remote = &remotes[i];
9693 break;
9698 if (remote == NULL) {
9699 got_repo_get_gitconfig_remotes(&nremotes, &remotes, repo);
9700 for (i = 0; i < nremotes; i++) {
9701 if (strcmp(remotes[i].name, remote_name) == 0) {
9702 remote = &remotes[i];
9703 break;
9707 if (remote == NULL) {
9708 error = got_error_path(remote_name, GOT_ERR_NO_REMOTE);
9709 goto done;
9712 error = got_dial_parse_uri(&proto, &host, &port, &server_path,
9713 &repo_name, remote->send_url);
9714 if (error)
9715 goto done;
9717 if (strcmp(proto, "git") == 0) {
9718 #ifndef PROFILE
9719 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
9720 "sendfd dns inet unveil", NULL) == -1)
9721 err(1, "pledge");
9722 #endif
9723 } else if (strcmp(proto, "git+ssh") == 0 ||
9724 strcmp(proto, "ssh") == 0) {
9725 #ifndef PROFILE
9726 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
9727 "sendfd unveil", NULL) == -1)
9728 err(1, "pledge");
9729 #endif
9730 } else if (strcmp(proto, "http") == 0 ||
9731 strcmp(proto, "git+http") == 0) {
9732 error = got_error_path(proto, GOT_ERR_NOT_IMPL);
9733 goto done;
9734 } else {
9735 error = got_error_path(proto, GOT_ERR_BAD_PROTO);
9736 goto done;
9739 error = got_dial_apply_unveil(proto);
9740 if (error)
9741 goto done;
9743 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
9744 if (error)
9745 goto done;
9747 if (send_all_branches) {
9748 error = got_ref_list(&all_branches, repo, "refs/heads",
9749 got_ref_cmp_by_name, NULL);
9750 if (error)
9751 goto done;
9752 TAILQ_FOREACH(re, &all_branches, entry) {
9753 const char *branchname = got_ref_get_name(re->ref);
9754 error = got_pathlist_append(&branches,
9755 branchname, NULL);
9756 if (error)
9757 goto done;
9758 nbranches++;
9760 } else if (nbranches == 0) {
9761 for (i = 0; i < remote->nsend_branches; i++) {
9762 error = got_pathlist_append(&branches,
9763 remote->send_branches[i], NULL);
9764 if (error)
9765 goto done;
9769 if (send_all_tags) {
9770 error = got_ref_list(&all_tags, repo, "refs/tags",
9771 got_ref_cmp_by_name, NULL);
9772 if (error)
9773 goto done;
9774 TAILQ_FOREACH(re, &all_tags, entry) {
9775 const char *tagname = got_ref_get_name(re->ref);
9776 error = got_pathlist_append(&tags,
9777 tagname, NULL);
9778 if (error)
9779 goto done;
9784 * To prevent accidents only branches in refs/heads/ can be deleted
9785 * with 'got send -d'.
9786 * Deleting anything else requires local repository access or Git.
9788 TAILQ_FOREACH(pe, &delete_args, entry) {
9789 const char *branchname = pe->path;
9790 char *s;
9791 struct got_pathlist_entry *new;
9792 if (strncmp(branchname, "refs/heads/", 11) == 0) {
9793 s = strdup(branchname);
9794 if (s == NULL) {
9795 error = got_error_from_errno("strdup");
9796 goto done;
9798 } else {
9799 if (asprintf(&s, "refs/heads/%s", branchname) == -1) {
9800 error = got_error_from_errno("asprintf");
9801 goto done;
9804 error = got_pathlist_insert(&new, &delete_branches, s, NULL);
9805 if (error || new == NULL /* duplicate */)
9806 free(s);
9807 if (error)
9808 goto done;
9809 ndelete_branches++;
9812 if (nbranches == 0 && ndelete_branches == 0) {
9813 struct got_reference *head_ref;
9814 if (worktree)
9815 error = got_ref_open(&head_ref, repo,
9816 got_worktree_get_head_ref_name(worktree), 0);
9817 else
9818 error = got_ref_open(&head_ref, repo, GOT_REF_HEAD, 0);
9819 if (error)
9820 goto done;
9821 if (got_ref_is_symbolic(head_ref)) {
9822 error = got_ref_resolve_symbolic(&ref, repo, head_ref);
9823 got_ref_close(head_ref);
9824 if (error)
9825 goto done;
9826 } else
9827 ref = head_ref;
9828 error = got_pathlist_append(&branches, got_ref_get_name(ref),
9829 NULL);
9830 if (error)
9831 goto done;
9832 nbranches++;
9835 if (verbosity >= 0) {
9836 printf("Connecting to \"%s\" %s://%s%s%s%s%s\n",
9837 remote->name, proto, host,
9838 port ? ":" : "", port ? port : "",
9839 *server_path == '/' ? "" : "/", server_path);
9842 error = got_send_connect(&sendpid, &sendfd, proto, host, port,
9843 server_path, verbosity);
9844 if (error)
9845 goto done;
9847 memset(&spa, 0, sizeof(spa));
9848 spa.last_scaled_packsize[0] = '\0';
9849 spa.last_p_deltify = -1;
9850 spa.last_p_written = -1;
9851 spa.verbosity = verbosity;
9852 spa.delete_branches = &delete_branches;
9853 error = got_send_pack(remote_name, &branches, &tags, &delete_branches,
9854 verbosity, overwrite_refs, sendfd, repo, send_progress, &spa,
9855 check_cancelled, NULL);
9856 if (spa.printed_something)
9857 putchar('\n');
9858 if (error)
9859 goto done;
9860 if (!spa.sent_something && verbosity >= 0)
9861 printf("Already up-to-date\n");
9862 done:
9863 if (sendpid > 0) {
9864 if (kill(sendpid, SIGTERM) == -1)
9865 error = got_error_from_errno("kill");
9866 if (waitpid(sendpid, &sendstatus, 0) == -1 && error == NULL)
9867 error = got_error_from_errno("waitpid");
9869 if (sendfd != -1 && close(sendfd) == -1 && error == NULL)
9870 error = got_error_from_errno("close");
9871 if (repo) {
9872 const struct got_error *close_err = got_repo_close(repo);
9873 if (error == NULL)
9874 error = close_err;
9876 if (worktree)
9877 got_worktree_close(worktree);
9878 if (pack_fds) {
9879 const struct got_error *pack_err =
9880 got_repo_pack_fds_close(pack_fds);
9881 if (error == NULL)
9882 error = pack_err;
9884 if (ref)
9885 got_ref_close(ref);
9886 got_pathlist_free(&branches, GOT_PATHLIST_FREE_NONE);
9887 got_pathlist_free(&tags, GOT_PATHLIST_FREE_NONE);
9888 got_ref_list_free(&all_branches);
9889 got_ref_list_free(&all_tags);
9890 got_pathlist_free(&delete_args, GOT_PATHLIST_FREE_NONE);
9891 got_pathlist_free(&delete_branches, GOT_PATHLIST_FREE_PATH);
9892 free(cwd);
9893 free(repo_path);
9894 free(proto);
9895 free(host);
9896 free(port);
9897 free(server_path);
9898 free(repo_name);
9899 return error;
9903 * Print and if delete is set delete all ref_prefix references.
9904 * If wanted_ref is not NULL, only print or delete this reference.
9906 static const struct got_error *
9907 process_logmsg_refs(const char *ref_prefix, size_t prefix_len,
9908 const char *wanted_ref, int delete, struct got_worktree *worktree,
9909 struct got_repository *repo)
9911 const struct got_error *err;
9912 struct got_pathlist_head paths;
9913 struct got_reflist_head refs;
9914 struct got_reflist_entry *re;
9915 struct got_reflist_object_id_map *refs_idmap = NULL;
9916 struct got_commit_object *commit = NULL;
9917 struct got_object_id *id = NULL;
9918 const char *header_prefix;
9919 char *uuidstr = NULL;
9920 int found = 0;
9922 TAILQ_INIT(&refs);
9923 TAILQ_INIT(&paths);
9925 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, repo);
9926 if (err)
9927 goto done;
9929 err = got_reflist_object_id_map_create(&refs_idmap, &refs, repo);
9930 if (err)
9931 goto done;
9933 if (worktree != NULL) {
9934 err = got_worktree_get_uuid(&uuidstr, worktree);
9935 if (err)
9936 goto done;
9939 if (wanted_ref) {
9940 if (strncmp(wanted_ref, "refs/heads/", 11) == 0)
9941 wanted_ref += 11;
9944 if (strcmp(ref_prefix, GOT_WORKTREE_BACKOUT_REF_PREFIX) == 0)
9945 header_prefix = "backout";
9946 else
9947 header_prefix = "cherrypick";
9949 TAILQ_FOREACH(re, &refs, entry) {
9950 const char *refname, *wt;
9952 refname = got_ref_get_name(re->ref);
9954 err = check_cancelled(NULL);
9955 if (err)
9956 goto done;
9958 if (strncmp(refname, ref_prefix, prefix_len) == 0)
9959 refname += prefix_len + 1; /* skip '-' delimiter */
9960 else
9961 continue;
9963 wt = refname;
9965 if (worktree == NULL || strncmp(refname, uuidstr,
9966 GOT_WORKTREE_UUID_STRLEN) == 0)
9967 refname += GOT_WORKTREE_UUID_STRLEN + 1; /* skip '-' */
9968 else
9969 continue;
9971 err = got_repo_match_object_id(&id, NULL, refname,
9972 GOT_OBJ_TYPE_COMMIT, NULL, repo);
9973 if (err)
9974 goto done;
9976 err = got_object_open_as_commit(&commit, repo, id);
9977 if (err)
9978 goto done;
9980 if (wanted_ref)
9981 found = strncmp(wanted_ref, refname,
9982 strlen(wanted_ref)) == 0;
9983 if (wanted_ref && !found) {
9984 struct got_reflist_head *ci_refs;
9986 ci_refs = got_reflist_object_id_map_lookup(refs_idmap,
9987 id);
9989 if (ci_refs) {
9990 char *refs_str = NULL;
9991 char const *r = NULL;
9993 err = build_refs_str(&refs_str, ci_refs, id,
9994 repo, 1);
9995 if (err)
9996 goto done;
9998 r = refs_str;
9999 while (r) {
10000 if (strncmp(r, wanted_ref,
10001 strlen(wanted_ref)) == 0) {
10002 found = 1;
10003 break;
10005 r = strchr(r, ' ');
10006 if (r)
10007 ++r;
10009 free(refs_str);
10013 if (wanted_ref == NULL || found) {
10014 if (delete) {
10015 err = got_ref_delete(re->ref, repo);
10016 if (err)
10017 goto done;
10018 printf("Deleted: ");
10019 err = print_commit_oneline(commit, id, repo,
10020 refs_idmap);
10021 } else {
10023 * Print paths modified by commit to help
10024 * associate commits with worktree changes.
10026 err = get_changed_paths(&paths, commit,
10027 repo, NULL);
10028 if (err)
10029 goto done;
10031 err = print_commit(commit, id, repo, NULL,
10032 &paths, NULL, 0, 0, refs_idmap, NULL,
10033 header_prefix);
10034 got_pathlist_free(&paths,
10035 GOT_PATHLIST_FREE_ALL);
10037 if (worktree == NULL)
10038 printf("work tree: %.*s\n\n",
10039 GOT_WORKTREE_UUID_STRLEN, wt);
10041 if (err || found)
10042 goto done;
10045 got_object_commit_close(commit);
10046 commit = NULL;
10047 free(id);
10048 id = NULL;
10051 if (wanted_ref != NULL && !found)
10052 err = got_error_fmt(GOT_ERR_NOT_REF, "%s", wanted_ref);
10054 done:
10055 free(id);
10056 free(uuidstr);
10057 got_ref_list_free(&refs);
10058 got_pathlist_free(&paths, GOT_PATHLIST_FREE_ALL);
10059 if (refs_idmap)
10060 got_reflist_object_id_map_free(refs_idmap);
10061 if (commit)
10062 got_object_commit_close(commit);
10063 return err;
10067 * Create new temp "logmsg" ref of the backed-out or cherrypicked commit
10068 * identified by id for log messages to prepopulate the editor on commit.
10070 static const struct got_error *
10071 logmsg_ref(struct got_object_id *id, const char *prefix,
10072 struct got_worktree *worktree, struct got_repository *repo)
10074 const struct got_error *err = NULL;
10075 char *idstr, *ref = NULL, *refname = NULL;
10076 int histedit_in_progress;
10077 int rebase_in_progress, merge_in_progress;
10080 * Silenty refuse to create merge reference if any histedit, merge,
10081 * or rebase operation is in progress.
10083 err = got_worktree_histedit_in_progress(&histedit_in_progress,
10084 worktree);
10085 if (err)
10086 return err;
10087 if (histedit_in_progress)
10088 return NULL;
10090 err = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
10091 if (err)
10092 return err;
10093 if (rebase_in_progress)
10094 return NULL;
10096 err = got_worktree_merge_in_progress(&merge_in_progress, worktree,
10097 repo);
10098 if (err)
10099 return err;
10100 if (merge_in_progress)
10101 return NULL;
10103 err = got_object_id_str(&idstr, id);
10104 if (err)
10105 return err;
10107 err = got_worktree_get_logmsg_ref_name(&refname, worktree, prefix);
10108 if (err)
10109 goto done;
10111 if (asprintf(&ref, "%s-%s", refname, idstr) == -1) {
10112 err = got_error_from_errno("asprintf");
10113 goto done;
10116 err = create_ref(ref, got_worktree_get_base_commit_id(worktree),
10117 -1, repo);
10118 done:
10119 free(ref);
10120 free(idstr);
10121 free(refname);
10122 return err;
10125 __dead static void
10126 usage_cherrypick(void)
10128 fprintf(stderr, "usage: %s cherrypick [-lX] [commit-id]\n",
10129 getprogname());
10130 exit(1);
10133 static const struct got_error *
10134 cmd_cherrypick(int argc, char *argv[])
10136 const struct got_error *error = NULL;
10137 struct got_worktree *worktree = NULL;
10138 struct got_repository *repo = NULL;
10139 char *cwd = NULL, *commit_id_str = NULL;
10140 struct got_object_id *commit_id = NULL;
10141 struct got_commit_object *commit = NULL;
10142 struct got_object_qid *pid;
10143 int ch, list_refs = 0, remove_refs = 0;
10144 struct got_update_progress_arg upa;
10145 int *pack_fds = NULL;
10147 #ifndef PROFILE
10148 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
10149 "unveil", NULL) == -1)
10150 err(1, "pledge");
10151 #endif
10153 while ((ch = getopt(argc, argv, "lX")) != -1) {
10154 switch (ch) {
10155 case 'l':
10156 list_refs = 1;
10157 break;
10158 case 'X':
10159 remove_refs = 1;
10160 break;
10161 default:
10162 usage_cherrypick();
10163 /* NOTREACHED */
10167 argc -= optind;
10168 argv += optind;
10170 if (list_refs || remove_refs) {
10171 if (argc != 0 && argc != 1)
10172 usage_cherrypick();
10173 } else if (argc != 1)
10174 usage_cherrypick();
10175 if (list_refs && remove_refs)
10176 option_conflict('l', 'X');
10178 cwd = getcwd(NULL, 0);
10179 if (cwd == NULL) {
10180 error = got_error_from_errno("getcwd");
10181 goto done;
10184 error = got_repo_pack_fds_open(&pack_fds);
10185 if (error != NULL)
10186 goto done;
10188 error = got_worktree_open(&worktree, cwd);
10189 if (error) {
10190 if (list_refs || remove_refs) {
10191 if (error->code != GOT_ERR_NOT_WORKTREE)
10192 goto done;
10193 } else {
10194 if (error->code == GOT_ERR_NOT_WORKTREE)
10195 error = wrap_not_worktree_error(error,
10196 "cherrypick", cwd);
10197 goto done;
10201 error = got_repo_open(&repo,
10202 worktree ? got_worktree_get_repo_path(worktree) : cwd,
10203 NULL, pack_fds);
10204 if (error != NULL)
10205 goto done;
10207 error = apply_unveil(got_repo_get_path(repo), 0,
10208 worktree ? got_worktree_get_root_path(worktree) : NULL);
10209 if (error)
10210 goto done;
10212 if (list_refs || remove_refs) {
10213 error = process_logmsg_refs(GOT_WORKTREE_CHERRYPICK_REF_PREFIX,
10214 GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN,
10215 argc == 1 ? argv[0] : NULL, remove_refs, worktree, repo);
10216 goto done;
10219 error = got_repo_match_object_id(&commit_id, NULL, argv[0],
10220 GOT_OBJ_TYPE_COMMIT, NULL, repo);
10221 if (error)
10222 goto done;
10223 error = got_object_id_str(&commit_id_str, commit_id);
10224 if (error)
10225 goto done;
10227 error = got_object_open_as_commit(&commit, repo, commit_id);
10228 if (error)
10229 goto done;
10230 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
10231 memset(&upa, 0, sizeof(upa));
10232 error = got_worktree_merge_files(worktree, pid ? &pid->id : NULL,
10233 commit_id, repo, update_progress, &upa, check_cancelled,
10234 NULL);
10235 if (error != NULL)
10236 goto done;
10238 if (upa.did_something) {
10239 error = logmsg_ref(commit_id,
10240 GOT_WORKTREE_CHERRYPICK_REF_PREFIX, worktree, repo);
10241 if (error)
10242 goto done;
10243 printf("Merged commit %s\n", commit_id_str);
10245 print_merge_progress_stats(&upa);
10246 done:
10247 free(cwd);
10248 if (commit)
10249 got_object_commit_close(commit);
10250 free(commit_id_str);
10251 if (worktree)
10252 got_worktree_close(worktree);
10253 if (repo) {
10254 const struct got_error *close_err = got_repo_close(repo);
10255 if (error == NULL)
10256 error = close_err;
10258 if (pack_fds) {
10259 const struct got_error *pack_err =
10260 got_repo_pack_fds_close(pack_fds);
10261 if (error == NULL)
10262 error = pack_err;
10265 return error;
10268 __dead static void
10269 usage_backout(void)
10271 fprintf(stderr, "usage: %s backout [-lX] [commit-id]\n", getprogname());
10272 exit(1);
10275 static const struct got_error *
10276 cmd_backout(int argc, char *argv[])
10278 const struct got_error *error = NULL;
10279 struct got_worktree *worktree = NULL;
10280 struct got_repository *repo = NULL;
10281 char *cwd = NULL, *commit_id_str = NULL;
10282 struct got_object_id *commit_id = NULL;
10283 struct got_commit_object *commit = NULL;
10284 struct got_object_qid *pid;
10285 int ch, list_refs = 0, remove_refs = 0;
10286 struct got_update_progress_arg upa;
10287 int *pack_fds = NULL;
10289 #ifndef PROFILE
10290 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
10291 "unveil", NULL) == -1)
10292 err(1, "pledge");
10293 #endif
10295 while ((ch = getopt(argc, argv, "lX")) != -1) {
10296 switch (ch) {
10297 case 'l':
10298 list_refs = 1;
10299 break;
10300 case 'X':
10301 remove_refs = 1;
10302 break;
10303 default:
10304 usage_backout();
10305 /* NOTREACHED */
10309 argc -= optind;
10310 argv += optind;
10312 if (list_refs || remove_refs) {
10313 if (argc != 0 && argc != 1)
10314 usage_backout();
10315 } else if (argc != 1)
10316 usage_backout();
10317 if (list_refs && remove_refs)
10318 option_conflict('l', 'X');
10320 cwd = getcwd(NULL, 0);
10321 if (cwd == NULL) {
10322 error = got_error_from_errno("getcwd");
10323 goto done;
10326 error = got_repo_pack_fds_open(&pack_fds);
10327 if (error != NULL)
10328 goto done;
10330 error = got_worktree_open(&worktree, cwd);
10331 if (error) {
10332 if (list_refs || remove_refs) {
10333 if (error->code != GOT_ERR_NOT_WORKTREE)
10334 goto done;
10335 } else {
10336 if (error->code == GOT_ERR_NOT_WORKTREE)
10337 error = wrap_not_worktree_error(error,
10338 "backout", cwd);
10339 goto done;
10343 error = got_repo_open(&repo,
10344 worktree ? got_worktree_get_repo_path(worktree) : cwd,
10345 NULL, pack_fds);
10346 if (error != NULL)
10347 goto done;
10349 error = apply_unveil(got_repo_get_path(repo), 0,
10350 worktree ? got_worktree_get_root_path(worktree) : NULL);
10351 if (error)
10352 goto done;
10354 if (list_refs || remove_refs) {
10355 error = process_logmsg_refs(GOT_WORKTREE_BACKOUT_REF_PREFIX,
10356 GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN,
10357 argc == 1 ? argv[0] : NULL, remove_refs, worktree, repo);
10358 goto done;
10361 error = got_repo_match_object_id(&commit_id, NULL, argv[0],
10362 GOT_OBJ_TYPE_COMMIT, NULL, repo);
10363 if (error)
10364 goto done;
10365 error = got_object_id_str(&commit_id_str, commit_id);
10366 if (error)
10367 goto done;
10369 error = got_object_open_as_commit(&commit, repo, commit_id);
10370 if (error)
10371 goto done;
10372 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
10373 if (pid == NULL) {
10374 error = got_error(GOT_ERR_ROOT_COMMIT);
10375 goto done;
10378 memset(&upa, 0, sizeof(upa));
10379 error = got_worktree_merge_files(worktree, commit_id, &pid->id,
10380 repo, update_progress, &upa, check_cancelled, NULL);
10381 if (error != NULL)
10382 goto done;
10384 if (upa.did_something) {
10385 error = logmsg_ref(commit_id, GOT_WORKTREE_BACKOUT_REF_PREFIX,
10386 worktree, repo);
10387 if (error)
10388 goto done;
10389 printf("Backed out commit %s\n", commit_id_str);
10391 print_merge_progress_stats(&upa);
10392 done:
10393 free(cwd);
10394 if (commit)
10395 got_object_commit_close(commit);
10396 free(commit_id_str);
10397 if (worktree)
10398 got_worktree_close(worktree);
10399 if (repo) {
10400 const struct got_error *close_err = got_repo_close(repo);
10401 if (error == NULL)
10402 error = close_err;
10404 if (pack_fds) {
10405 const struct got_error *pack_err =
10406 got_repo_pack_fds_close(pack_fds);
10407 if (error == NULL)
10408 error = pack_err;
10410 return error;
10413 __dead static void
10414 usage_rebase(void)
10416 fprintf(stderr, "usage: %s rebase [-aCclX] [branch]\n", getprogname());
10417 exit(1);
10420 static void
10421 trim_logmsg(char *logmsg, int limit)
10423 char *nl;
10424 size_t len;
10426 len = strlen(logmsg);
10427 if (len > limit)
10428 len = limit;
10429 logmsg[len] = '\0';
10430 nl = strchr(logmsg, '\n');
10431 if (nl)
10432 *nl = '\0';
10435 static const struct got_error *
10436 get_short_logmsg(char **logmsg, int limit, struct got_commit_object *commit)
10438 const struct got_error *err;
10439 char *logmsg0 = NULL;
10440 const char *s;
10442 err = got_object_commit_get_logmsg(&logmsg0, commit);
10443 if (err)
10444 return err;
10446 s = logmsg0;
10447 while (isspace((unsigned char)s[0]))
10448 s++;
10450 *logmsg = strdup(s);
10451 if (*logmsg == NULL) {
10452 err = got_error_from_errno("strdup");
10453 goto done;
10456 trim_logmsg(*logmsg, limit);
10457 done:
10458 free(logmsg0);
10459 return err;
10462 static const struct got_error *
10463 show_rebase_merge_conflict(struct got_object_id *id,
10464 struct got_repository *repo)
10466 const struct got_error *err;
10467 struct got_commit_object *commit = NULL;
10468 char *id_str = NULL, *logmsg = NULL;
10470 err = got_object_open_as_commit(&commit, repo, id);
10471 if (err)
10472 return err;
10474 err = got_object_id_str(&id_str, id);
10475 if (err)
10476 goto done;
10478 id_str[12] = '\0';
10480 err = get_short_logmsg(&logmsg, 42, commit);
10481 if (err)
10482 goto done;
10484 printf("%s -> merge conflict: %s\n", id_str, logmsg);
10485 done:
10486 free(id_str);
10487 got_object_commit_close(commit);
10488 free(logmsg);
10489 return err;
10492 static const struct got_error *
10493 show_rebase_progress(struct got_commit_object *commit,
10494 struct got_object_id *old_id, struct got_object_id *new_id)
10496 const struct got_error *err;
10497 char *old_id_str = NULL, *new_id_str = NULL, *logmsg = NULL;
10499 err = got_object_id_str(&old_id_str, old_id);
10500 if (err)
10501 goto done;
10503 if (new_id) {
10504 err = got_object_id_str(&new_id_str, new_id);
10505 if (err)
10506 goto done;
10509 old_id_str[12] = '\0';
10510 if (new_id_str)
10511 new_id_str[12] = '\0';
10513 err = get_short_logmsg(&logmsg, 42, commit);
10514 if (err)
10515 goto done;
10517 printf("%s -> %s: %s\n", old_id_str,
10518 new_id_str ? new_id_str : "no-op change", logmsg);
10519 done:
10520 free(old_id_str);
10521 free(new_id_str);
10522 free(logmsg);
10523 return err;
10526 static const struct got_error *
10527 rebase_complete(struct got_worktree *worktree, struct got_fileindex *fileindex,
10528 struct got_reference *branch, struct got_reference *tmp_branch,
10529 struct got_repository *repo, int create_backup)
10531 printf("Switching work tree to %s\n", got_ref_get_name(branch));
10532 return got_worktree_rebase_complete(worktree, fileindex,
10533 tmp_branch, branch, repo, create_backup);
10536 static const struct got_error *
10537 rebase_commit(struct got_pathlist_head *merged_paths,
10538 struct got_worktree *worktree, struct got_fileindex *fileindex,
10539 struct got_reference *tmp_branch, const char *committer,
10540 struct got_object_id *commit_id, int allow_conflict,
10541 struct got_repository *repo)
10543 const struct got_error *error;
10544 struct got_commit_object *commit;
10545 struct got_object_id *new_commit_id;
10547 error = got_object_open_as_commit(&commit, repo, commit_id);
10548 if (error)
10549 return error;
10551 error = got_worktree_rebase_commit(&new_commit_id, merged_paths,
10552 worktree, fileindex, tmp_branch, committer, commit, commit_id,
10553 allow_conflict, repo);
10554 if (error) {
10555 if (error->code != GOT_ERR_COMMIT_NO_CHANGES)
10556 goto done;
10557 error = show_rebase_progress(commit, commit_id, NULL);
10558 } else {
10559 error = show_rebase_progress(commit, commit_id, new_commit_id);
10560 free(new_commit_id);
10562 done:
10563 got_object_commit_close(commit);
10564 return error;
10567 struct check_path_prefix_arg {
10568 const char *path_prefix;
10569 size_t len;
10570 int errcode;
10573 static const struct got_error *
10574 check_path_prefix_in_diff(void *arg, struct got_blob_object *blob1,
10575 struct got_blob_object *blob2, FILE *f1, FILE *f2,
10576 struct got_object_id *id1, struct got_object_id *id2,
10577 const char *path1, const char *path2,
10578 mode_t mode1, mode_t mode2, struct got_repository *repo)
10580 struct check_path_prefix_arg *a = arg;
10582 if ((path1 && !got_path_is_child(path1, a->path_prefix, a->len)) ||
10583 (path2 && !got_path_is_child(path2, a->path_prefix, a->len)))
10584 return got_error(a->errcode);
10586 return NULL;
10589 static const struct got_error *
10590 check_path_prefix(struct got_object_id *parent_id,
10591 struct got_object_id *commit_id, const char *path_prefix,
10592 int errcode, struct got_repository *repo)
10594 const struct got_error *err;
10595 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
10596 struct got_commit_object *commit = NULL, *parent_commit = NULL;
10597 struct check_path_prefix_arg cpp_arg;
10599 if (got_path_is_root_dir(path_prefix))
10600 return NULL;
10602 err = got_object_open_as_commit(&commit, repo, commit_id);
10603 if (err)
10604 goto done;
10606 err = got_object_open_as_commit(&parent_commit, repo, parent_id);
10607 if (err)
10608 goto done;
10610 err = got_object_open_as_tree(&tree1, repo,
10611 got_object_commit_get_tree_id(parent_commit));
10612 if (err)
10613 goto done;
10615 err = got_object_open_as_tree(&tree2, repo,
10616 got_object_commit_get_tree_id(commit));
10617 if (err)
10618 goto done;
10620 cpp_arg.path_prefix = path_prefix;
10621 while (cpp_arg.path_prefix[0] == '/')
10622 cpp_arg.path_prefix++;
10623 cpp_arg.len = strlen(cpp_arg.path_prefix);
10624 cpp_arg.errcode = errcode;
10625 err = got_diff_tree(tree1, tree2, NULL, NULL, -1, -1, "", "", repo,
10626 check_path_prefix_in_diff, &cpp_arg, 0);
10627 done:
10628 if (tree1)
10629 got_object_tree_close(tree1);
10630 if (tree2)
10631 got_object_tree_close(tree2);
10632 if (commit)
10633 got_object_commit_close(commit);
10634 if (parent_commit)
10635 got_object_commit_close(parent_commit);
10636 return err;
10639 static const struct got_error *
10640 collect_commits(struct got_object_id_queue *commits,
10641 struct got_object_id *initial_commit_id,
10642 struct got_object_id *iter_start_id, struct got_object_id *iter_stop_id,
10643 const char *path_prefix, int path_prefix_errcode,
10644 struct got_repository *repo)
10646 const struct got_error *err = NULL;
10647 struct got_commit_graph *graph = NULL;
10648 struct got_object_id parent_id, commit_id;
10649 struct got_object_qid *qid;
10651 err = got_commit_graph_open(&graph, "/", 1);
10652 if (err)
10653 return err;
10655 err = got_commit_graph_iter_start(graph, iter_start_id, repo,
10656 check_cancelled, NULL);
10657 if (err)
10658 goto done;
10660 memcpy(&commit_id, initial_commit_id, sizeof(commit_id));
10661 while (got_object_id_cmp(&commit_id, iter_stop_id) != 0) {
10662 err = got_commit_graph_iter_next(&parent_id, graph, repo,
10663 check_cancelled, NULL);
10664 if (err) {
10665 if (err->code == GOT_ERR_ITER_COMPLETED) {
10666 err = got_error_msg(GOT_ERR_ANCESTRY,
10667 "ran out of commits to rebase before "
10668 "youngest common ancestor commit has "
10669 "been reached?!?");
10671 goto done;
10672 } else {
10673 err = check_path_prefix(&parent_id, &commit_id,
10674 path_prefix, path_prefix_errcode, repo);
10675 if (err)
10676 goto done;
10678 err = got_object_qid_alloc(&qid, &commit_id);
10679 if (err)
10680 goto done;
10681 STAILQ_INSERT_HEAD(commits, qid, entry);
10683 memcpy(&commit_id, &parent_id, sizeof(commit_id));
10686 done:
10687 got_commit_graph_close(graph);
10688 return err;
10691 static const struct got_error *
10692 get_commit_brief_str(char **brief_str, struct got_commit_object *commit)
10694 const struct got_error *err = NULL;
10695 time_t committer_time;
10696 struct tm tm;
10697 char datebuf[11]; /* YYYY-MM-DD + NUL */
10698 char *author0 = NULL, *author, *smallerthan;
10699 char *logmsg0 = NULL, *logmsg, *newline;
10701 committer_time = got_object_commit_get_committer_time(commit);
10702 if (gmtime_r(&committer_time, &tm) == NULL)
10703 return got_error_from_errno("gmtime_r");
10704 if (strftime(datebuf, sizeof(datebuf), "%G-%m-%d", &tm) == 0)
10705 return got_error(GOT_ERR_NO_SPACE);
10707 author0 = strdup(got_object_commit_get_author(commit));
10708 if (author0 == NULL)
10709 return got_error_from_errno("strdup");
10710 author = author0;
10711 smallerthan = strchr(author, '<');
10712 if (smallerthan && smallerthan[1] != '\0')
10713 author = smallerthan + 1;
10714 author[strcspn(author, "@>")] = '\0';
10716 err = got_object_commit_get_logmsg(&logmsg0, commit);
10717 if (err)
10718 goto done;
10719 logmsg = logmsg0;
10720 while (*logmsg == '\n')
10721 logmsg++;
10722 newline = strchr(logmsg, '\n');
10723 if (newline)
10724 *newline = '\0';
10726 if (asprintf(brief_str, "%s %s %s",
10727 datebuf, author, logmsg) == -1)
10728 err = got_error_from_errno("asprintf");
10729 done:
10730 free(author0);
10731 free(logmsg0);
10732 return err;
10735 static const struct got_error *
10736 delete_backup_ref(struct got_reference *ref, struct got_object_id *id,
10737 struct got_repository *repo)
10739 const struct got_error *err;
10740 char *id_str;
10742 err = got_object_id_str(&id_str, id);
10743 if (err)
10744 return err;
10746 err = got_ref_delete(ref, repo);
10747 if (err)
10748 goto done;
10750 printf("Deleted %s: %s\n", got_ref_get_name(ref), id_str);
10751 done:
10752 free(id_str);
10753 return err;
10756 static const struct got_error *
10757 print_backup_ref(const char *branch_name, const char *new_id_str,
10758 struct got_object_id *old_commit_id, struct got_commit_object *old_commit,
10759 struct got_reflist_object_id_map *refs_idmap,
10760 struct got_repository *repo)
10762 const struct got_error *err = NULL;
10763 struct got_reflist_head *refs;
10764 char *refs_str = NULL;
10765 struct got_object_id *new_commit_id = NULL;
10766 struct got_commit_object *new_commit = NULL;
10767 char *new_commit_brief_str = NULL;
10768 struct got_object_id *yca_id = NULL;
10769 struct got_commit_object *yca_commit = NULL;
10770 char *yca_id_str = NULL, *yca_brief_str = NULL;
10771 char *custom_refs_str;
10773 if (asprintf(&custom_refs_str, "formerly %s", branch_name) == -1)
10774 return got_error_from_errno("asprintf");
10776 err = print_commit(old_commit, old_commit_id, repo, NULL, NULL, NULL,
10777 0, 0, refs_idmap, custom_refs_str, NULL);
10778 if (err)
10779 goto done;
10781 err = got_object_resolve_id_str(&new_commit_id, repo, new_id_str);
10782 if (err)
10783 goto done;
10785 refs = got_reflist_object_id_map_lookup(refs_idmap, new_commit_id);
10786 if (refs) {
10787 err = build_refs_str(&refs_str, refs, new_commit_id, repo, 0);
10788 if (err)
10789 goto done;
10792 err = got_object_open_as_commit(&new_commit, repo, new_commit_id);
10793 if (err)
10794 goto done;
10796 err = get_commit_brief_str(&new_commit_brief_str, new_commit);
10797 if (err)
10798 goto done;
10800 err = got_commit_graph_find_youngest_common_ancestor(&yca_id,
10801 old_commit_id, new_commit_id, 1, repo, check_cancelled, NULL);
10802 if (err)
10803 goto done;
10805 printf("has become commit %s%s%s%s\n %s\n", new_id_str,
10806 refs_str ? " (" : "", refs_str ? refs_str : "",
10807 refs_str ? ")" : "", new_commit_brief_str);
10808 if (yca_id && got_object_id_cmp(yca_id, new_commit_id) != 0 &&
10809 got_object_id_cmp(yca_id, old_commit_id) != 0) {
10810 free(refs_str);
10811 refs_str = NULL;
10813 err = got_object_open_as_commit(&yca_commit, repo, yca_id);
10814 if (err)
10815 goto done;
10817 err = get_commit_brief_str(&yca_brief_str, yca_commit);
10818 if (err)
10819 goto done;
10821 err = got_object_id_str(&yca_id_str, yca_id);
10822 if (err)
10823 goto done;
10825 refs = got_reflist_object_id_map_lookup(refs_idmap, yca_id);
10826 if (refs) {
10827 err = build_refs_str(&refs_str, refs, yca_id, repo, 0);
10828 if (err)
10829 goto done;
10831 printf("history forked at %s%s%s%s\n %s\n",
10832 yca_id_str,
10833 refs_str ? " (" : "", refs_str ? refs_str : "",
10834 refs_str ? ")" : "", yca_brief_str);
10836 done:
10837 free(custom_refs_str);
10838 free(new_commit_id);
10839 free(refs_str);
10840 free(yca_id);
10841 free(yca_id_str);
10842 free(yca_brief_str);
10843 if (new_commit)
10844 got_object_commit_close(new_commit);
10845 if (yca_commit)
10846 got_object_commit_close(yca_commit);
10848 return err;
10851 static const struct got_error *
10852 worktree_has_logmsg_ref(const char *caller, struct got_worktree *worktree,
10853 struct got_repository *repo)
10855 const struct got_error *err;
10856 struct got_reflist_head refs;
10857 struct got_reflist_entry *re;
10858 char *uuidstr = NULL;
10859 static char msg[160];
10861 TAILQ_INIT(&refs);
10863 err = got_worktree_get_uuid(&uuidstr, worktree);
10864 if (err)
10865 goto done;
10867 err = got_ref_list(&refs, repo, "refs/got/worktree",
10868 got_ref_cmp_by_name, repo);
10869 if (err)
10870 goto done;
10872 TAILQ_FOREACH(re, &refs, entry) {
10873 const char *cmd, *refname, *type;
10875 refname = got_ref_get_name(re->ref);
10877 if (strncmp(refname, GOT_WORKTREE_CHERRYPICK_REF_PREFIX,
10878 GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN) == 0) {
10879 refname += GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN + 1;
10880 cmd = "cherrypick";
10881 type = "cherrypicked";
10882 } else if (strncmp(refname, GOT_WORKTREE_BACKOUT_REF_PREFIX,
10883 GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN) == 0) {
10884 refname += GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN + 1;
10885 cmd = "backout";
10886 type = "backed-out";
10887 } else
10888 continue;
10890 if (strncmp(refname, uuidstr, GOT_WORKTREE_UUID_STRLEN) != 0)
10891 continue;
10893 snprintf(msg, sizeof(msg),
10894 "work tree has references created by %s commits which "
10895 "must be removed with 'got %s -X' before running the %s "
10896 "command", type, cmd, caller);
10897 err = got_error_msg(GOT_ERR_WORKTREE_META, msg);
10898 goto done;
10901 done:
10902 free(uuidstr);
10903 got_ref_list_free(&refs);
10904 return err;
10907 static const struct got_error *
10908 process_backup_refs(const char *backup_ref_prefix,
10909 const char *wanted_branch_name,
10910 int delete, struct got_repository *repo)
10912 const struct got_error *err;
10913 struct got_reflist_head refs, backup_refs;
10914 struct got_reflist_entry *re;
10915 const size_t backup_ref_prefix_len = strlen(backup_ref_prefix);
10916 struct got_object_id *old_commit_id = NULL;
10917 char *branch_name = NULL;
10918 struct got_commit_object *old_commit = NULL;
10919 struct got_reflist_object_id_map *refs_idmap = NULL;
10920 int wanted_branch_found = 0;
10922 TAILQ_INIT(&refs);
10923 TAILQ_INIT(&backup_refs);
10925 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
10926 if (err)
10927 return err;
10929 err = got_reflist_object_id_map_create(&refs_idmap, &refs, repo);
10930 if (err)
10931 goto done;
10933 if (wanted_branch_name) {
10934 if (strncmp(wanted_branch_name, "refs/heads/", 11) == 0)
10935 wanted_branch_name += 11;
10938 err = got_ref_list(&backup_refs, repo, backup_ref_prefix,
10939 got_ref_cmp_by_commit_timestamp_descending, repo);
10940 if (err)
10941 goto done;
10943 TAILQ_FOREACH(re, &backup_refs, entry) {
10944 const char *refname = got_ref_get_name(re->ref);
10945 char *slash;
10947 err = check_cancelled(NULL);
10948 if (err)
10949 break;
10951 err = got_ref_resolve(&old_commit_id, repo, re->ref);
10952 if (err)
10953 break;
10955 err = got_object_open_as_commit(&old_commit, repo,
10956 old_commit_id);
10957 if (err)
10958 break;
10960 if (strncmp(backup_ref_prefix, refname,
10961 backup_ref_prefix_len) == 0)
10962 refname += backup_ref_prefix_len;
10964 while (refname[0] == '/')
10965 refname++;
10967 branch_name = strdup(refname);
10968 if (branch_name == NULL) {
10969 err = got_error_from_errno("strdup");
10970 break;
10972 slash = strrchr(branch_name, '/');
10973 if (slash) {
10974 *slash = '\0';
10975 refname += strlen(branch_name) + 1;
10978 if (wanted_branch_name == NULL ||
10979 strcmp(wanted_branch_name, branch_name) == 0) {
10980 wanted_branch_found = 1;
10981 if (delete) {
10982 err = delete_backup_ref(re->ref,
10983 old_commit_id, repo);
10984 } else {
10985 err = print_backup_ref(branch_name, refname,
10986 old_commit_id, old_commit, refs_idmap,
10987 repo);
10989 if (err)
10990 break;
10993 free(old_commit_id);
10994 old_commit_id = NULL;
10995 free(branch_name);
10996 branch_name = NULL;
10997 got_object_commit_close(old_commit);
10998 old_commit = NULL;
11001 if (wanted_branch_name && !wanted_branch_found) {
11002 err = got_error_fmt(GOT_ERR_NOT_REF,
11003 "%s/%s/", backup_ref_prefix, wanted_branch_name);
11005 done:
11006 if (refs_idmap)
11007 got_reflist_object_id_map_free(refs_idmap);
11008 got_ref_list_free(&refs);
11009 got_ref_list_free(&backup_refs);
11010 free(old_commit_id);
11011 free(branch_name);
11012 if (old_commit)
11013 got_object_commit_close(old_commit);
11014 return err;
11017 static const struct got_error *
11018 abort_progress(void *arg, unsigned char status, const char *path)
11021 * Unversioned files should not clutter progress output when
11022 * an operation is aborted.
11024 if (status == GOT_STATUS_UNVERSIONED)
11025 return NULL;
11027 return update_progress(arg, status, path);
11030 static const struct got_error *
11031 cmd_rebase(int argc, char *argv[])
11033 const struct got_error *error = NULL;
11034 struct got_worktree *worktree = NULL;
11035 struct got_repository *repo = NULL;
11036 struct got_fileindex *fileindex = NULL;
11037 char *cwd = NULL, *committer = NULL, *gitconfig_path = NULL;
11038 struct got_reference *branch = NULL;
11039 struct got_reference *new_base_branch = NULL, *tmp_branch = NULL;
11040 struct got_object_id *commit_id = NULL, *parent_id = NULL;
11041 struct got_object_id *resume_commit_id = NULL;
11042 struct got_object_id *branch_head_commit_id = NULL, *yca_id = NULL;
11043 struct got_object_id *head_commit_id = NULL;
11044 struct got_reference *head_ref = NULL;
11045 struct got_commit_object *commit = NULL;
11046 int ch, rebase_in_progress = 0, abort_rebase = 0, continue_rebase = 0;
11047 int histedit_in_progress = 0, merge_in_progress = 0;
11048 int create_backup = 1, list_backups = 0, delete_backups = 0;
11049 int allow_conflict = 0;
11050 struct got_object_id_queue commits;
11051 struct got_pathlist_head merged_paths;
11052 const struct got_object_id_queue *parent_ids;
11053 struct got_object_qid *qid, *pid;
11054 struct got_update_progress_arg upa;
11055 int *pack_fds = NULL;
11057 STAILQ_INIT(&commits);
11058 TAILQ_INIT(&merged_paths);
11059 memset(&upa, 0, sizeof(upa));
11061 #ifndef PROFILE
11062 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
11063 "unveil", NULL) == -1)
11064 err(1, "pledge");
11065 #endif
11067 while ((ch = getopt(argc, argv, "aCclX")) != -1) {
11068 switch (ch) {
11069 case 'a':
11070 abort_rebase = 1;
11071 break;
11072 case 'C':
11073 allow_conflict = 1;
11074 break;
11075 case 'c':
11076 continue_rebase = 1;
11077 break;
11078 case 'l':
11079 list_backups = 1;
11080 break;
11081 case 'X':
11082 delete_backups = 1;
11083 break;
11084 default:
11085 usage_rebase();
11086 /* NOTREACHED */
11090 argc -= optind;
11091 argv += optind;
11093 if (list_backups) {
11094 if (abort_rebase)
11095 option_conflict('l', 'a');
11096 if (allow_conflict)
11097 option_conflict('l', 'C');
11098 if (continue_rebase)
11099 option_conflict('l', 'c');
11100 if (delete_backups)
11101 option_conflict('l', 'X');
11102 if (argc != 0 && argc != 1)
11103 usage_rebase();
11104 } else if (delete_backups) {
11105 if (abort_rebase)
11106 option_conflict('X', 'a');
11107 if (allow_conflict)
11108 option_conflict('X', 'C');
11109 if (continue_rebase)
11110 option_conflict('X', 'c');
11111 if (list_backups)
11112 option_conflict('l', 'X');
11113 if (argc != 0 && argc != 1)
11114 usage_rebase();
11115 } else if (allow_conflict) {
11116 if (abort_rebase)
11117 option_conflict('C', 'a');
11118 if (!continue_rebase)
11119 errx(1, "-C option requires -c");
11120 } else {
11121 if (abort_rebase && continue_rebase)
11122 usage_rebase();
11123 else if (abort_rebase || continue_rebase) {
11124 if (argc != 0)
11125 usage_rebase();
11126 } else if (argc != 1)
11127 usage_rebase();
11130 cwd = getcwd(NULL, 0);
11131 if (cwd == NULL) {
11132 error = got_error_from_errno("getcwd");
11133 goto done;
11136 error = got_repo_pack_fds_open(&pack_fds);
11137 if (error != NULL)
11138 goto done;
11140 error = got_worktree_open(&worktree, cwd);
11141 if (error) {
11142 if (list_backups || delete_backups) {
11143 if (error->code != GOT_ERR_NOT_WORKTREE)
11144 goto done;
11145 } else {
11146 if (error->code == GOT_ERR_NOT_WORKTREE)
11147 error = wrap_not_worktree_error(error,
11148 "rebase", cwd);
11149 goto done;
11153 error = get_gitconfig_path(&gitconfig_path);
11154 if (error)
11155 goto done;
11156 error = got_repo_open(&repo,
11157 worktree ? got_worktree_get_repo_path(worktree) : cwd,
11158 gitconfig_path, pack_fds);
11159 if (error != NULL)
11160 goto done;
11162 if (worktree != NULL && !list_backups && !delete_backups) {
11163 error = worktree_has_logmsg_ref("rebase", worktree, repo);
11164 if (error)
11165 goto done;
11168 error = get_author(&committer, repo, worktree);
11169 if (error && error->code != GOT_ERR_COMMIT_NO_AUTHOR)
11170 goto done;
11172 error = apply_unveil(got_repo_get_path(repo), 0,
11173 worktree ? got_worktree_get_root_path(worktree) : NULL);
11174 if (error)
11175 goto done;
11177 if (list_backups || delete_backups) {
11178 error = process_backup_refs(
11179 GOT_WORKTREE_REBASE_BACKUP_REF_PREFIX,
11180 argc == 1 ? argv[0] : NULL, delete_backups, repo);
11181 goto done; /* nothing else to do */
11184 error = got_worktree_histedit_in_progress(&histedit_in_progress,
11185 worktree);
11186 if (error)
11187 goto done;
11188 if (histedit_in_progress) {
11189 error = got_error(GOT_ERR_HISTEDIT_BUSY);
11190 goto done;
11193 error = got_worktree_merge_in_progress(&merge_in_progress,
11194 worktree, repo);
11195 if (error)
11196 goto done;
11197 if (merge_in_progress) {
11198 error = got_error(GOT_ERR_MERGE_BUSY);
11199 goto done;
11202 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
11203 if (error)
11204 goto done;
11206 if (abort_rebase) {
11207 if (!rebase_in_progress) {
11208 error = got_error(GOT_ERR_NOT_REBASING);
11209 goto done;
11211 error = got_worktree_rebase_continue(&resume_commit_id,
11212 &new_base_branch, &tmp_branch, &branch, &fileindex,
11213 worktree, repo);
11214 if (error)
11215 goto done;
11216 printf("Switching work tree to %s\n",
11217 got_ref_get_symref_target(new_base_branch));
11218 error = got_worktree_rebase_abort(worktree, fileindex, repo,
11219 new_base_branch, abort_progress, &upa);
11220 if (error)
11221 goto done;
11222 printf("Rebase of %s aborted\n", got_ref_get_name(branch));
11223 print_merge_progress_stats(&upa);
11224 goto done; /* nothing else to do */
11227 if (continue_rebase) {
11228 if (!rebase_in_progress) {
11229 error = got_error(GOT_ERR_NOT_REBASING);
11230 goto done;
11232 error = got_worktree_rebase_continue(&resume_commit_id,
11233 &new_base_branch, &tmp_branch, &branch, &fileindex,
11234 worktree, repo);
11235 if (error)
11236 goto done;
11238 error = rebase_commit(NULL, worktree, fileindex, tmp_branch,
11239 committer, resume_commit_id, allow_conflict, repo);
11240 if (error)
11241 goto done;
11243 yca_id = got_object_id_dup(resume_commit_id);
11244 if (yca_id == NULL) {
11245 error = got_error_from_errno("got_object_id_dup");
11246 goto done;
11248 } else {
11249 error = got_ref_open(&branch, repo, argv[0], 0);
11250 if (error != NULL)
11251 goto done;
11252 if (strncmp(got_ref_get_name(branch), "refs/heads/", 11) != 0) {
11253 error = got_error_msg(GOT_ERR_COMMIT_BRANCH,
11254 "will not rebase a branch which lives outside "
11255 "the \"refs/heads/\" reference namespace");
11256 goto done;
11260 error = got_ref_resolve(&branch_head_commit_id, repo, branch);
11261 if (error)
11262 goto done;
11264 if (!continue_rebase) {
11265 struct got_object_id *base_commit_id;
11267 error = got_ref_open(&head_ref, repo,
11268 got_worktree_get_head_ref_name(worktree), 0);
11269 if (error)
11270 goto done;
11271 error = got_ref_resolve(&head_commit_id, repo, head_ref);
11272 if (error)
11273 goto done;
11274 base_commit_id = got_worktree_get_base_commit_id(worktree);
11275 if (got_object_id_cmp(base_commit_id, head_commit_id) != 0) {
11276 error = got_error(GOT_ERR_REBASE_OUT_OF_DATE);
11277 goto done;
11280 error = got_commit_graph_find_youngest_common_ancestor(&yca_id,
11281 base_commit_id, branch_head_commit_id, 1, repo,
11282 check_cancelled, NULL);
11283 if (error) {
11284 if (error->code == GOT_ERR_ANCESTRY) {
11285 error = got_error_msg(GOT_ERR_ANCESTRY,
11286 "specified branch shares no common "
11287 "ancestry with work tree's branch");
11289 goto done;
11292 error = check_same_branch(base_commit_id, branch, yca_id, repo);
11293 if (error) {
11294 if (error->code != GOT_ERR_ANCESTRY)
11295 goto done;
11296 error = NULL;
11297 } else {
11298 struct got_pathlist_head paths;
11299 printf("%s is already based on %s\n",
11300 got_ref_get_name(branch),
11301 got_worktree_get_head_ref_name(worktree));
11302 error = switch_head_ref(branch, branch_head_commit_id,
11303 worktree, repo);
11304 if (error)
11305 goto done;
11306 error = got_worktree_set_base_commit_id(worktree, repo,
11307 branch_head_commit_id);
11308 if (error)
11309 goto done;
11310 TAILQ_INIT(&paths);
11311 error = got_pathlist_append(&paths, "", NULL);
11312 if (error)
11313 goto done;
11314 error = got_worktree_checkout_files(worktree,
11315 &paths, repo, update_progress, &upa,
11316 check_cancelled, NULL);
11317 got_pathlist_free(&paths, GOT_PATHLIST_FREE_NONE);
11318 if (error)
11319 goto done;
11320 if (upa.did_something) {
11321 char *id_str;
11322 error = got_object_id_str(&id_str,
11323 branch_head_commit_id);
11324 if (error)
11325 goto done;
11326 printf("Updated to %s: %s\n",
11327 got_worktree_get_head_ref_name(worktree),
11328 id_str);
11329 free(id_str);
11330 } else
11331 printf("Already up-to-date\n");
11332 print_update_progress_stats(&upa);
11333 goto done;
11337 commit_id = branch_head_commit_id;
11338 error = got_object_open_as_commit(&commit, repo, commit_id);
11339 if (error)
11340 goto done;
11342 parent_ids = got_object_commit_get_parent_ids(commit);
11343 pid = STAILQ_FIRST(parent_ids);
11344 if (pid) {
11345 error = collect_commits(&commits, commit_id, &pid->id,
11346 yca_id, got_worktree_get_path_prefix(worktree),
11347 GOT_ERR_REBASE_PATH, repo);
11348 if (error)
11349 goto done;
11352 got_object_commit_close(commit);
11353 commit = NULL;
11355 if (!continue_rebase) {
11356 error = got_worktree_rebase_prepare(&new_base_branch,
11357 &tmp_branch, &fileindex, worktree, branch, repo);
11358 if (error)
11359 goto done;
11362 if (STAILQ_EMPTY(&commits)) {
11363 if (continue_rebase) {
11364 error = rebase_complete(worktree, fileindex,
11365 branch, tmp_branch, repo, create_backup);
11366 goto done;
11367 } else {
11368 /* Fast-forward the reference of the branch. */
11369 struct got_object_id *new_head_commit_id;
11370 char *id_str;
11371 error = got_ref_resolve(&new_head_commit_id, repo,
11372 new_base_branch);
11373 if (error)
11374 goto done;
11375 error = got_object_id_str(&id_str, new_head_commit_id);
11376 if (error)
11377 goto done;
11378 printf("Forwarding %s to commit %s\n",
11379 got_ref_get_name(branch), id_str);
11380 free(id_str);
11381 error = got_ref_change_ref(branch,
11382 new_head_commit_id);
11383 if (error)
11384 goto done;
11385 /* No backup needed since objects did not change. */
11386 create_backup = 0;
11390 pid = NULL;
11391 STAILQ_FOREACH(qid, &commits, entry) {
11393 commit_id = &qid->id;
11394 parent_id = pid ? &pid->id : yca_id;
11395 pid = qid;
11397 memset(&upa, 0, sizeof(upa));
11398 error = got_worktree_rebase_merge_files(&merged_paths,
11399 worktree, fileindex, parent_id, commit_id, repo,
11400 update_progress, &upa, check_cancelled, NULL);
11401 if (error)
11402 goto done;
11404 print_merge_progress_stats(&upa);
11405 if (upa.conflicts > 0 || upa.missing > 0 ||
11406 upa.not_deleted > 0 || upa.unversioned > 0) {
11407 if (upa.conflicts > 0) {
11408 error = show_rebase_merge_conflict(&qid->id,
11409 repo);
11410 if (error)
11411 goto done;
11413 got_pathlist_free(&merged_paths, GOT_PATHLIST_FREE_PATH);
11414 break;
11417 error = rebase_commit(&merged_paths, worktree, fileindex,
11418 tmp_branch, committer, commit_id, 0, repo);
11419 got_pathlist_free(&merged_paths, GOT_PATHLIST_FREE_PATH);
11420 if (error)
11421 goto done;
11424 if (upa.conflicts > 0 || upa.missing > 0 ||
11425 upa.not_deleted > 0 || upa.unversioned > 0) {
11426 error = got_worktree_rebase_postpone(worktree, fileindex);
11427 if (error)
11428 goto done;
11429 if (upa.conflicts > 0 && upa.missing == 0 &&
11430 upa.not_deleted == 0 && upa.unversioned == 0) {
11431 error = got_error_msg(GOT_ERR_CONFLICTS,
11432 "conflicts must be resolved before rebasing "
11433 "can continue");
11434 } else if (upa.conflicts > 0) {
11435 error = got_error_msg(GOT_ERR_CONFLICTS,
11436 "conflicts must be resolved before rebasing "
11437 "can continue; changes destined for some "
11438 "files were not yet merged and should be "
11439 "merged manually if required before the "
11440 "rebase operation is continued");
11441 } else {
11442 error = got_error_msg(GOT_ERR_CONFLICTS,
11443 "changes destined for some files were not "
11444 "yet merged and should be merged manually "
11445 "if required before the rebase operation "
11446 "is continued");
11448 } else
11449 error = rebase_complete(worktree, fileindex, branch,
11450 tmp_branch, repo, create_backup);
11451 done:
11452 free(cwd);
11453 free(committer);
11454 free(gitconfig_path);
11455 got_object_id_queue_free(&commits);
11456 free(branch_head_commit_id);
11457 free(resume_commit_id);
11458 free(head_commit_id);
11459 free(yca_id);
11460 if (commit)
11461 got_object_commit_close(commit);
11462 if (branch)
11463 got_ref_close(branch);
11464 if (new_base_branch)
11465 got_ref_close(new_base_branch);
11466 if (tmp_branch)
11467 got_ref_close(tmp_branch);
11468 if (head_ref)
11469 got_ref_close(head_ref);
11470 if (worktree)
11471 got_worktree_close(worktree);
11472 if (repo) {
11473 const struct got_error *close_err = got_repo_close(repo);
11474 if (error == NULL)
11475 error = close_err;
11477 if (pack_fds) {
11478 const struct got_error *pack_err =
11479 got_repo_pack_fds_close(pack_fds);
11480 if (error == NULL)
11481 error = pack_err;
11483 return error;
11486 __dead static void
11487 usage_histedit(void)
11489 fprintf(stderr, "usage: %s histedit [-aCcdeflmX] [-F histedit-script] "
11490 "[branch]\n", getprogname());
11491 exit(1);
11494 #define GOT_HISTEDIT_PICK 'p'
11495 #define GOT_HISTEDIT_EDIT 'e'
11496 #define GOT_HISTEDIT_FOLD 'f'
11497 #define GOT_HISTEDIT_DROP 'd'
11498 #define GOT_HISTEDIT_MESG 'm'
11500 static const struct got_histedit_cmd {
11501 unsigned char code;
11502 const char *name;
11503 const char *desc;
11504 } got_histedit_cmds[] = {
11505 { GOT_HISTEDIT_PICK, "pick", "use commit" },
11506 { GOT_HISTEDIT_EDIT, "edit", "use commit but stop for amending" },
11507 { GOT_HISTEDIT_FOLD, "fold", "combine with next commit that will "
11508 "be used" },
11509 { GOT_HISTEDIT_DROP, "drop", "remove commit from history" },
11510 { GOT_HISTEDIT_MESG, "mesg",
11511 "single-line log message for commit above (open editor if empty)" },
11514 struct got_histedit_list_entry {
11515 TAILQ_ENTRY(got_histedit_list_entry) entry;
11516 struct got_object_id *commit_id;
11517 const struct got_histedit_cmd *cmd;
11518 char *logmsg;
11520 TAILQ_HEAD(got_histedit_list, got_histedit_list_entry);
11522 static const struct got_error *
11523 histedit_write_commit(struct got_object_id *commit_id, const char *cmdname,
11524 FILE *f, struct got_repository *repo)
11526 const struct got_error *err = NULL;
11527 char *logmsg = NULL, *id_str = NULL;
11528 struct got_commit_object *commit = NULL;
11529 int n;
11531 err = got_object_open_as_commit(&commit, repo, commit_id);
11532 if (err)
11533 goto done;
11535 err = get_short_logmsg(&logmsg, 34, commit);
11536 if (err)
11537 goto done;
11539 err = got_object_id_str(&id_str, commit_id);
11540 if (err)
11541 goto done;
11543 n = fprintf(f, "%s %s %s\n", cmdname, id_str, logmsg);
11544 if (n < 0)
11545 err = got_ferror(f, GOT_ERR_IO);
11546 done:
11547 if (commit)
11548 got_object_commit_close(commit);
11549 free(id_str);
11550 free(logmsg);
11551 return err;
11554 static const struct got_error *
11555 histedit_write_commit_list(struct got_object_id_queue *commits,
11556 FILE *f, int edit_logmsg_only, int fold_only, int drop_only,
11557 int edit_only, struct got_repository *repo)
11559 const struct got_error *err = NULL;
11560 struct got_object_qid *qid;
11561 const char *histedit_cmd = NULL;
11563 if (STAILQ_EMPTY(commits))
11564 return got_error(GOT_ERR_EMPTY_HISTEDIT);
11566 STAILQ_FOREACH(qid, commits, entry) {
11567 histedit_cmd = got_histedit_cmds[0].name;
11568 if (drop_only)
11569 histedit_cmd = "drop";
11570 else if (edit_only)
11571 histedit_cmd = "edit";
11572 else if (fold_only && STAILQ_NEXT(qid, entry) != NULL)
11573 histedit_cmd = "fold";
11574 err = histedit_write_commit(&qid->id, histedit_cmd, f, repo);
11575 if (err)
11576 break;
11577 if (edit_logmsg_only) {
11578 int n = fprintf(f, "%c\n", GOT_HISTEDIT_MESG);
11579 if (n < 0) {
11580 err = got_ferror(f, GOT_ERR_IO);
11581 break;
11586 return err;
11589 static const struct got_error *
11590 write_cmd_list(FILE *f, const char *branch_name,
11591 struct got_object_id_queue *commits)
11593 const struct got_error *err = NULL;
11594 size_t i;
11595 int n;
11596 char *id_str;
11597 struct got_object_qid *qid;
11599 qid = STAILQ_FIRST(commits);
11600 err = got_object_id_str(&id_str, &qid->id);
11601 if (err)
11602 return err;
11604 n = fprintf(f,
11605 "# Editing the history of branch '%s' starting at\n"
11606 "# commit %s\n"
11607 "# Commits will be processed in order from top to "
11608 "bottom of this file.\n", branch_name, id_str);
11609 if (n < 0) {
11610 err = got_ferror(f, GOT_ERR_IO);
11611 goto done;
11614 n = fprintf(f, "# Available histedit commands:\n");
11615 if (n < 0) {
11616 err = got_ferror(f, GOT_ERR_IO);
11617 goto done;
11620 for (i = 0; i < nitems(got_histedit_cmds); i++) {
11621 const struct got_histedit_cmd *cmd = &got_histedit_cmds[i];
11622 n = fprintf(f, "# %s (%c): %s\n", cmd->name, cmd->code,
11623 cmd->desc);
11624 if (n < 0) {
11625 err = got_ferror(f, GOT_ERR_IO);
11626 break;
11629 done:
11630 free(id_str);
11631 return err;
11634 static const struct got_error *
11635 histedit_syntax_error(int lineno)
11637 static char msg[42];
11638 int ret;
11640 ret = snprintf(msg, sizeof(msg), "histedit syntax error on line %d",
11641 lineno);
11642 if (ret < 0 || (size_t)ret >= sizeof(msg))
11643 return got_error(GOT_ERR_HISTEDIT_SYNTAX);
11645 return got_error_msg(GOT_ERR_HISTEDIT_SYNTAX, msg);
11648 static const struct got_error *
11649 append_folded_commit_msg(char **new_msg, struct got_histedit_list_entry *hle,
11650 char *logmsg, struct got_repository *repo)
11652 const struct got_error *err;
11653 struct got_commit_object *folded_commit = NULL;
11654 char *id_str, *folded_logmsg = NULL;
11656 err = got_object_id_str(&id_str, hle->commit_id);
11657 if (err)
11658 return err;
11660 err = got_object_open_as_commit(&folded_commit, repo, hle->commit_id);
11661 if (err)
11662 goto done;
11664 err = got_object_commit_get_logmsg(&folded_logmsg, folded_commit);
11665 if (err)
11666 goto done;
11667 if (asprintf(new_msg, "%s%s# log message of folded commit %s: %s",
11668 logmsg ? logmsg : "", logmsg ? "\n" : "", id_str,
11669 folded_logmsg) == -1) {
11670 err = got_error_from_errno("asprintf");
11672 done:
11673 if (folded_commit)
11674 got_object_commit_close(folded_commit);
11675 free(id_str);
11676 free(folded_logmsg);
11677 return err;
11680 static struct got_histedit_list_entry *
11681 get_folded_commits(struct got_histedit_list_entry *hle)
11683 struct got_histedit_list_entry *prev, *folded = NULL;
11685 prev = TAILQ_PREV(hle, got_histedit_list, entry);
11686 while (prev && (prev->cmd->code == GOT_HISTEDIT_FOLD ||
11687 prev->cmd->code == GOT_HISTEDIT_DROP)) {
11688 if (prev->cmd->code == GOT_HISTEDIT_FOLD)
11689 folded = prev;
11690 prev = TAILQ_PREV(prev, got_histedit_list, entry);
11693 return folded;
11696 static const struct got_error *
11697 histedit_edit_logmsg(struct got_histedit_list_entry *hle,
11698 struct got_repository *repo)
11700 char *logmsg_path = NULL, *id_str = NULL, *orig_logmsg = NULL;
11701 char *logmsg = NULL, *new_msg = NULL, *editor = NULL;
11702 const struct got_error *err = NULL;
11703 struct got_commit_object *commit = NULL;
11704 int logmsg_len;
11705 int fd = -1;
11706 struct got_histedit_list_entry *folded = NULL;
11708 err = got_object_open_as_commit(&commit, repo, hle->commit_id);
11709 if (err)
11710 return err;
11712 folded = get_folded_commits(hle);
11713 if (folded) {
11714 while (folded != hle) {
11715 if (folded->cmd->code == GOT_HISTEDIT_DROP) {
11716 folded = TAILQ_NEXT(folded, entry);
11717 continue;
11719 err = append_folded_commit_msg(&new_msg, folded,
11720 logmsg, repo);
11721 if (err)
11722 goto done;
11723 free(logmsg);
11724 logmsg = new_msg;
11725 folded = TAILQ_NEXT(folded, entry);
11729 err = got_object_id_str(&id_str, hle->commit_id);
11730 if (err)
11731 goto done;
11732 err = got_object_commit_get_logmsg(&orig_logmsg, commit);
11733 if (err)
11734 goto done;
11735 logmsg_len = asprintf(&new_msg,
11736 "%s\n# original log message of commit %s: %s",
11737 logmsg ? logmsg : "", id_str, orig_logmsg);
11738 if (logmsg_len == -1) {
11739 err = got_error_from_errno("asprintf");
11740 goto done;
11742 free(logmsg);
11743 logmsg = new_msg;
11745 err = got_object_id_str(&id_str, hle->commit_id);
11746 if (err)
11747 goto done;
11749 err = got_opentemp_named_fd(&logmsg_path, &fd,
11750 GOT_TMPDIR_STR "/got-logmsg", "");
11751 if (err)
11752 goto done;
11754 if (write(fd, logmsg, logmsg_len) == -1) {
11755 err = got_error_from_errno2("write", logmsg_path);
11756 goto done;
11758 if (close(fd) == -1) {
11759 err = got_error_from_errno2("close", logmsg_path);
11760 goto done;
11762 fd = -1;
11764 err = get_editor(&editor);
11765 if (err)
11766 goto done;
11768 err = edit_logmsg(&hle->logmsg, editor, logmsg_path, logmsg,
11769 logmsg_len, 0);
11770 if (err) {
11771 if (err->code != GOT_ERR_COMMIT_MSG_EMPTY)
11772 goto done;
11773 err = NULL;
11774 hle->logmsg = strdup(new_msg);
11775 if (hle->logmsg == NULL)
11776 err = got_error_from_errno("strdup");
11778 done:
11779 if (fd != -1 && close(fd) == -1 && err == NULL)
11780 err = got_error_from_errno2("close", logmsg_path);
11781 if (logmsg_path && unlink(logmsg_path) != 0 && err == NULL)
11782 err = got_error_from_errno2("unlink", logmsg_path);
11783 free(logmsg_path);
11784 free(logmsg);
11785 free(orig_logmsg);
11786 free(editor);
11787 if (commit)
11788 got_object_commit_close(commit);
11789 return err;
11792 static const struct got_error *
11793 histedit_parse_list(struct got_histedit_list *histedit_cmds,
11794 FILE *f, struct got_repository *repo)
11796 const struct got_error *err = NULL;
11797 char *line = NULL, *p, *end;
11798 size_t i, linesize = 0;
11799 ssize_t linelen;
11800 int lineno = 0, lastcmd = -1;
11801 const struct got_histedit_cmd *cmd;
11802 struct got_object_id *commit_id = NULL;
11803 struct got_histedit_list_entry *hle = NULL;
11805 for (;;) {
11806 linelen = getline(&line, &linesize, f);
11807 if (linelen == -1) {
11808 const struct got_error *getline_err;
11809 if (feof(f))
11810 break;
11811 getline_err = got_error_from_errno("getline");
11812 err = got_ferror(f, getline_err->code);
11813 break;
11815 lineno++;
11816 p = line;
11817 while (isspace((unsigned char)p[0]))
11818 p++;
11819 if (p[0] == '#' || p[0] == '\0')
11820 continue;
11821 cmd = NULL;
11822 for (i = 0; i < nitems(got_histedit_cmds); i++) {
11823 cmd = &got_histedit_cmds[i];
11824 if (strncmp(cmd->name, p, strlen(cmd->name)) == 0 &&
11825 isspace((unsigned char)p[strlen(cmd->name)])) {
11826 p += strlen(cmd->name);
11827 break;
11829 if (p[0] == cmd->code && isspace((unsigned char)p[1])) {
11830 p++;
11831 break;
11834 if (i == nitems(got_histedit_cmds)) {
11835 err = histedit_syntax_error(lineno);
11836 break;
11838 while (isspace((unsigned char)p[0]))
11839 p++;
11840 if (cmd->code == GOT_HISTEDIT_MESG) {
11841 if (lastcmd != GOT_HISTEDIT_PICK &&
11842 lastcmd != GOT_HISTEDIT_EDIT) {
11843 err = got_error(GOT_ERR_HISTEDIT_CMD);
11844 break;
11846 if (p[0] == '\0') {
11847 err = histedit_edit_logmsg(hle, repo);
11848 if (err)
11849 break;
11850 } else {
11851 hle->logmsg = strdup(p);
11852 if (hle->logmsg == NULL) {
11853 err = got_error_from_errno("strdup");
11854 break;
11857 lastcmd = cmd->code;
11858 continue;
11859 } else {
11860 end = p;
11861 while (end[0] && !isspace((unsigned char)end[0]))
11862 end++;
11863 *end = '\0';
11865 err = got_object_resolve_id_str(&commit_id, repo, p);
11866 if (err) {
11867 /* override error code */
11868 err = histedit_syntax_error(lineno);
11869 break;
11872 hle = malloc(sizeof(*hle));
11873 if (hle == NULL) {
11874 err = got_error_from_errno("malloc");
11875 break;
11877 hle->cmd = cmd;
11878 hle->commit_id = commit_id;
11879 hle->logmsg = NULL;
11880 commit_id = NULL;
11881 TAILQ_INSERT_TAIL(histedit_cmds, hle, entry);
11882 lastcmd = cmd->code;
11885 free(line);
11886 free(commit_id);
11887 return err;
11890 static const struct got_error *
11891 histedit_check_script(struct got_histedit_list *histedit_cmds,
11892 struct got_object_id_queue *commits, struct got_repository *repo)
11894 const struct got_error *err = NULL;
11895 struct got_object_qid *qid;
11896 struct got_histedit_list_entry *hle;
11897 static char msg[92];
11898 char *id_str;
11900 if (TAILQ_EMPTY(histedit_cmds))
11901 return got_error_msg(GOT_ERR_EMPTY_HISTEDIT,
11902 "histedit script contains no commands");
11903 if (STAILQ_EMPTY(commits))
11904 return got_error(GOT_ERR_EMPTY_HISTEDIT);
11906 TAILQ_FOREACH(hle, histedit_cmds, entry) {
11907 struct got_histedit_list_entry *hle2;
11908 TAILQ_FOREACH(hle2, histedit_cmds, entry) {
11909 if (hle == hle2)
11910 continue;
11911 if (got_object_id_cmp(hle->commit_id,
11912 hle2->commit_id) != 0)
11913 continue;
11914 err = got_object_id_str(&id_str, hle->commit_id);
11915 if (err)
11916 return err;
11917 snprintf(msg, sizeof(msg), "commit %s is listed "
11918 "more than once in histedit script", id_str);
11919 free(id_str);
11920 return got_error_msg(GOT_ERR_HISTEDIT_CMD, msg);
11924 STAILQ_FOREACH(qid, commits, entry) {
11925 TAILQ_FOREACH(hle, histedit_cmds, entry) {
11926 if (got_object_id_cmp(&qid->id, hle->commit_id) == 0)
11927 break;
11929 if (hle == NULL) {
11930 err = got_object_id_str(&id_str, &qid->id);
11931 if (err)
11932 return err;
11933 snprintf(msg, sizeof(msg),
11934 "commit %s missing from histedit script", id_str);
11935 free(id_str);
11936 return got_error_msg(GOT_ERR_HISTEDIT_CMD, msg);
11940 hle = TAILQ_LAST(histedit_cmds, got_histedit_list);
11941 if (hle && hle->cmd->code == GOT_HISTEDIT_FOLD)
11942 return got_error_msg(GOT_ERR_HISTEDIT_CMD,
11943 "last commit in histedit script cannot be folded");
11945 return NULL;
11948 static const struct got_error *
11949 histedit_run_editor(struct got_histedit_list *histedit_cmds,
11950 const char *path, struct got_object_id_queue *commits,
11951 struct got_repository *repo)
11953 const struct got_error *err = NULL;
11954 char *editor;
11955 FILE *f = NULL;
11957 err = get_editor(&editor);
11958 if (err)
11959 return err;
11961 if (spawn_editor(editor, path) == -1) {
11962 err = got_error_from_errno("failed spawning editor");
11963 goto done;
11966 f = fopen(path, "re");
11967 if (f == NULL) {
11968 err = got_error_from_errno("fopen");
11969 goto done;
11971 err = histedit_parse_list(histedit_cmds, f, repo);
11972 if (err)
11973 goto done;
11975 err = histedit_check_script(histedit_cmds, commits, repo);
11976 done:
11977 if (f && fclose(f) == EOF && err == NULL)
11978 err = got_error_from_errno("fclose");
11979 free(editor);
11980 return err;
11983 static const struct got_error *
11984 histedit_edit_list_retry(struct got_histedit_list *, const struct got_error *,
11985 struct got_object_id_queue *, const char *, const char *,
11986 struct got_repository *);
11988 static const struct got_error *
11989 histedit_edit_script(struct got_histedit_list *histedit_cmds,
11990 struct got_object_id_queue *commits, const char *branch_name,
11991 int edit_logmsg_only, int fold_only, int drop_only, int edit_only,
11992 struct got_repository *repo)
11994 const struct got_error *err;
11995 FILE *f = NULL;
11996 char *path = NULL;
11998 err = got_opentemp_named(&path, &f, "got-histedit", "");
11999 if (err)
12000 return err;
12002 err = write_cmd_list(f, branch_name, commits);
12003 if (err)
12004 goto done;
12006 err = histedit_write_commit_list(commits, f, edit_logmsg_only,
12007 fold_only, drop_only, edit_only, repo);
12008 if (err)
12009 goto done;
12011 if (drop_only || edit_logmsg_only || fold_only || edit_only) {
12012 rewind(f);
12013 err = histedit_parse_list(histedit_cmds, f, repo);
12014 } else {
12015 if (fclose(f) == EOF) {
12016 err = got_error_from_errno("fclose");
12017 goto done;
12019 f = NULL;
12020 err = histedit_run_editor(histedit_cmds, path, commits, repo);
12021 if (err) {
12022 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
12023 err->code != GOT_ERR_HISTEDIT_CMD)
12024 goto done;
12025 err = histedit_edit_list_retry(histedit_cmds, err,
12026 commits, path, branch_name, repo);
12029 done:
12030 if (f && fclose(f) == EOF && err == NULL)
12031 err = got_error_from_errno("fclose");
12032 if (path && unlink(path) != 0 && err == NULL)
12033 err = got_error_from_errno2("unlink", path);
12034 free(path);
12035 return err;
12038 static const struct got_error *
12039 histedit_save_list(struct got_histedit_list *histedit_cmds,
12040 struct got_worktree *worktree, struct got_repository *repo)
12042 const struct got_error *err = NULL;
12043 char *path = NULL;
12044 FILE *f = NULL;
12045 struct got_histedit_list_entry *hle;
12046 struct got_commit_object *commit = NULL;
12048 err = got_worktree_get_histedit_script_path(&path, worktree);
12049 if (err)
12050 return err;
12052 f = fopen(path, "we");
12053 if (f == NULL) {
12054 err = got_error_from_errno2("fopen", path);
12055 goto done;
12057 TAILQ_FOREACH(hle, histedit_cmds, entry) {
12058 err = histedit_write_commit(hle->commit_id, hle->cmd->name, f,
12059 repo);
12060 if (err)
12061 break;
12063 if (hle->logmsg) {
12064 int n = fprintf(f, "%c %s\n",
12065 GOT_HISTEDIT_MESG, hle->logmsg);
12066 if (n < 0) {
12067 err = got_ferror(f, GOT_ERR_IO);
12068 break;
12072 done:
12073 if (f && fclose(f) == EOF && err == NULL)
12074 err = got_error_from_errno("fclose");
12075 free(path);
12076 if (commit)
12077 got_object_commit_close(commit);
12078 return err;
12081 static void
12082 histedit_free_list(struct got_histedit_list *histedit_cmds)
12084 struct got_histedit_list_entry *hle;
12086 while ((hle = TAILQ_FIRST(histedit_cmds))) {
12087 TAILQ_REMOVE(histedit_cmds, hle, entry);
12088 free(hle);
12092 static const struct got_error *
12093 histedit_load_list(struct got_histedit_list *histedit_cmds,
12094 const char *path, struct got_repository *repo)
12096 const struct got_error *err = NULL;
12097 FILE *f = NULL;
12099 f = fopen(path, "re");
12100 if (f == NULL) {
12101 err = got_error_from_errno2("fopen", path);
12102 goto done;
12105 err = histedit_parse_list(histedit_cmds, f, repo);
12106 done:
12107 if (f && fclose(f) == EOF && err == NULL)
12108 err = got_error_from_errno("fclose");
12109 return err;
12112 static const struct got_error *
12113 histedit_edit_list_retry(struct got_histedit_list *histedit_cmds,
12114 const struct got_error *edit_err, struct got_object_id_queue *commits,
12115 const char *path, const char *branch_name, struct got_repository *repo)
12117 const struct got_error *err = NULL, *prev_err = edit_err;
12118 int resp = ' ';
12120 while (resp != 'c' && resp != 'r' && resp != 'a') {
12121 printf("%s: %s\n(c)ontinue editing, (r)estart editing, "
12122 "or (a)bort: ", getprogname(), prev_err->msg);
12123 resp = getchar();
12124 if (resp == '\n')
12125 resp = getchar();
12126 if (resp == 'c') {
12127 histedit_free_list(histedit_cmds);
12128 err = histedit_run_editor(histedit_cmds, path, commits,
12129 repo);
12130 if (err) {
12131 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
12132 err->code != GOT_ERR_HISTEDIT_CMD)
12133 break;
12134 prev_err = err;
12135 resp = ' ';
12136 continue;
12138 break;
12139 } else if (resp == 'r') {
12140 histedit_free_list(histedit_cmds);
12141 err = histedit_edit_script(histedit_cmds,
12142 commits, branch_name, 0, 0, 0, 0, repo);
12143 if (err) {
12144 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
12145 err->code != GOT_ERR_HISTEDIT_CMD)
12146 break;
12147 prev_err = err;
12148 resp = ' ';
12149 continue;
12151 break;
12152 } else if (resp == 'a') {
12153 err = got_error(GOT_ERR_HISTEDIT_CANCEL);
12154 break;
12155 } else
12156 printf("invalid response '%c'\n", resp);
12159 return err;
12162 static const struct got_error *
12163 histedit_complete(struct got_worktree *worktree,
12164 struct got_fileindex *fileindex, struct got_reference *tmp_branch,
12165 struct got_reference *branch, struct got_repository *repo)
12167 printf("Switching work tree to %s\n",
12168 got_ref_get_symref_target(branch));
12169 return got_worktree_histedit_complete(worktree, fileindex, tmp_branch,
12170 branch, repo);
12173 static const struct got_error *
12174 show_histedit_progress(struct got_commit_object *commit,
12175 struct got_histedit_list_entry *hle, struct got_object_id *new_id)
12177 const struct got_error *err;
12178 char *old_id_str = NULL, *new_id_str = NULL, *logmsg = NULL;
12180 err = got_object_id_str(&old_id_str, hle->commit_id);
12181 if (err)
12182 goto done;
12184 if (new_id) {
12185 err = got_object_id_str(&new_id_str, new_id);
12186 if (err)
12187 goto done;
12190 old_id_str[12] = '\0';
12191 if (new_id_str)
12192 new_id_str[12] = '\0';
12194 if (hle->logmsg) {
12195 logmsg = strdup(hle->logmsg);
12196 if (logmsg == NULL) {
12197 err = got_error_from_errno("strdup");
12198 goto done;
12200 trim_logmsg(logmsg, 42);
12201 } else {
12202 err = get_short_logmsg(&logmsg, 42, commit);
12203 if (err)
12204 goto done;
12207 switch (hle->cmd->code) {
12208 case GOT_HISTEDIT_PICK:
12209 case GOT_HISTEDIT_EDIT:
12210 printf("%s -> %s: %s\n", old_id_str,
12211 new_id_str ? new_id_str : "no-op change", logmsg);
12212 break;
12213 case GOT_HISTEDIT_DROP:
12214 case GOT_HISTEDIT_FOLD:
12215 printf("%s -> %s commit: %s\n", old_id_str, hle->cmd->name,
12216 logmsg);
12217 break;
12218 default:
12219 break;
12221 done:
12222 free(old_id_str);
12223 free(new_id_str);
12224 return err;
12227 static const struct got_error *
12228 histedit_commit(struct got_pathlist_head *merged_paths,
12229 struct got_worktree *worktree, struct got_fileindex *fileindex,
12230 struct got_reference *tmp_branch, struct got_histedit_list_entry *hle,
12231 const char *committer, int allow_conflict, struct got_repository *repo)
12233 const struct got_error *err;
12234 struct got_commit_object *commit;
12235 struct got_object_id *new_commit_id;
12237 if ((hle->cmd->code == GOT_HISTEDIT_EDIT || get_folded_commits(hle))
12238 && hle->logmsg == NULL) {
12239 err = histedit_edit_logmsg(hle, repo);
12240 if (err)
12241 return err;
12244 err = got_object_open_as_commit(&commit, repo, hle->commit_id);
12245 if (err)
12246 return err;
12248 err = got_worktree_histedit_commit(&new_commit_id, merged_paths,
12249 worktree, fileindex, tmp_branch, committer, commit, hle->commit_id,
12250 hle->logmsg, allow_conflict, repo);
12251 if (err) {
12252 if (err->code != GOT_ERR_COMMIT_NO_CHANGES)
12253 goto done;
12254 err = show_histedit_progress(commit, hle, NULL);
12255 } else {
12256 err = show_histedit_progress(commit, hle, new_commit_id);
12257 free(new_commit_id);
12259 done:
12260 got_object_commit_close(commit);
12261 return err;
12264 static const struct got_error *
12265 histedit_skip_commit(struct got_histedit_list_entry *hle,
12266 struct got_worktree *worktree, struct got_repository *repo)
12268 const struct got_error *error;
12269 struct got_commit_object *commit;
12271 error = got_worktree_histedit_skip_commit(worktree, hle->commit_id,
12272 repo);
12273 if (error)
12274 return error;
12276 error = got_object_open_as_commit(&commit, repo, hle->commit_id);
12277 if (error)
12278 return error;
12280 error = show_histedit_progress(commit, hle, NULL);
12281 got_object_commit_close(commit);
12282 return error;
12285 static const struct got_error *
12286 check_local_changes(void *arg, unsigned char status,
12287 unsigned char staged_status, const char *path,
12288 struct got_object_id *blob_id, struct got_object_id *staged_blob_id,
12289 struct got_object_id *commit_id, int dirfd, const char *de_name)
12291 int *have_local_changes = arg;
12293 switch (status) {
12294 case GOT_STATUS_ADD:
12295 case GOT_STATUS_DELETE:
12296 case GOT_STATUS_MODIFY:
12297 case GOT_STATUS_CONFLICT:
12298 *have_local_changes = 1;
12299 return got_error(GOT_ERR_CANCELLED);
12300 default:
12301 break;
12304 switch (staged_status) {
12305 case GOT_STATUS_ADD:
12306 case GOT_STATUS_DELETE:
12307 case GOT_STATUS_MODIFY:
12308 *have_local_changes = 1;
12309 return got_error(GOT_ERR_CANCELLED);
12310 default:
12311 break;
12314 return NULL;
12317 static const struct got_error *
12318 cmd_histedit(int argc, char *argv[])
12320 const struct got_error *error = NULL;
12321 struct got_worktree *worktree = NULL;
12322 struct got_fileindex *fileindex = NULL;
12323 struct got_repository *repo = NULL;
12324 char *cwd = NULL, *committer = NULL, *gitconfig_path = NULL;
12325 struct got_reference *branch = NULL;
12326 struct got_reference *tmp_branch = NULL;
12327 struct got_object_id *resume_commit_id = NULL;
12328 struct got_object_id *base_commit_id = NULL;
12329 struct got_object_id *head_commit_id = NULL;
12330 struct got_commit_object *commit = NULL;
12331 int ch, rebase_in_progress = 0, merge_in_progress = 0;
12332 struct got_update_progress_arg upa;
12333 int edit_in_progress = 0, abort_edit = 0, continue_edit = 0;
12334 int drop_only = 0, edit_logmsg_only = 0, fold_only = 0, edit_only = 0;
12335 int allow_conflict = 0, list_backups = 0, delete_backups = 0;
12336 const char *edit_script_path = NULL;
12337 struct got_object_id_queue commits;
12338 struct got_pathlist_head merged_paths;
12339 const struct got_object_id_queue *parent_ids;
12340 struct got_object_qid *pid;
12341 struct got_histedit_list histedit_cmds;
12342 struct got_histedit_list_entry *hle;
12343 int *pack_fds = NULL;
12345 STAILQ_INIT(&commits);
12346 TAILQ_INIT(&histedit_cmds);
12347 TAILQ_INIT(&merged_paths);
12348 memset(&upa, 0, sizeof(upa));
12350 #ifndef PROFILE
12351 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
12352 "unveil", NULL) == -1)
12353 err(1, "pledge");
12354 #endif
12356 while ((ch = getopt(argc, argv, "aCcdeF:flmX")) != -1) {
12357 switch (ch) {
12358 case 'a':
12359 abort_edit = 1;
12360 break;
12361 case 'C':
12362 allow_conflict = 1;
12363 break;
12364 case 'c':
12365 continue_edit = 1;
12366 break;
12367 case 'd':
12368 drop_only = 1;
12369 break;
12370 case 'e':
12371 edit_only = 1;
12372 break;
12373 case 'F':
12374 edit_script_path = optarg;
12375 break;
12376 case 'f':
12377 fold_only = 1;
12378 break;
12379 case 'l':
12380 list_backups = 1;
12381 break;
12382 case 'm':
12383 edit_logmsg_only = 1;
12384 break;
12385 case 'X':
12386 delete_backups = 1;
12387 break;
12388 default:
12389 usage_histedit();
12390 /* NOTREACHED */
12394 argc -= optind;
12395 argv += optind;
12397 if (abort_edit && allow_conflict)
12398 option_conflict('a', 'C');
12399 if (abort_edit && continue_edit)
12400 option_conflict('a', 'c');
12401 if (edit_script_path && allow_conflict)
12402 option_conflict('F', 'C');
12403 if (edit_script_path && edit_logmsg_only)
12404 option_conflict('F', 'm');
12405 if (abort_edit && edit_logmsg_only)
12406 option_conflict('a', 'm');
12407 if (edit_logmsg_only && allow_conflict)
12408 option_conflict('m', 'C');
12409 if (continue_edit && edit_logmsg_only)
12410 option_conflict('c', 'm');
12411 if (abort_edit && fold_only)
12412 option_conflict('a', 'f');
12413 if (fold_only && allow_conflict)
12414 option_conflict('f', 'C');
12415 if (continue_edit && fold_only)
12416 option_conflict('c', 'f');
12417 if (fold_only && edit_logmsg_only)
12418 option_conflict('f', 'm');
12419 if (edit_script_path && fold_only)
12420 option_conflict('F', 'f');
12421 if (abort_edit && edit_only)
12422 option_conflict('a', 'e');
12423 if (continue_edit && edit_only)
12424 option_conflict('c', 'e');
12425 if (edit_only && edit_logmsg_only)
12426 option_conflict('e', 'm');
12427 if (edit_script_path && edit_only)
12428 option_conflict('F', 'e');
12429 if (fold_only && edit_only)
12430 option_conflict('f', 'e');
12431 if (drop_only && abort_edit)
12432 option_conflict('d', 'a');
12433 if (drop_only && allow_conflict)
12434 option_conflict('d', 'C');
12435 if (drop_only && continue_edit)
12436 option_conflict('d', 'c');
12437 if (drop_only && edit_logmsg_only)
12438 option_conflict('d', 'm');
12439 if (drop_only && edit_only)
12440 option_conflict('d', 'e');
12441 if (drop_only && edit_script_path)
12442 option_conflict('d', 'F');
12443 if (drop_only && fold_only)
12444 option_conflict('d', 'f');
12445 if (list_backups) {
12446 if (abort_edit)
12447 option_conflict('l', 'a');
12448 if (allow_conflict)
12449 option_conflict('l', 'C');
12450 if (continue_edit)
12451 option_conflict('l', 'c');
12452 if (edit_script_path)
12453 option_conflict('l', 'F');
12454 if (edit_logmsg_only)
12455 option_conflict('l', 'm');
12456 if (drop_only)
12457 option_conflict('l', 'd');
12458 if (fold_only)
12459 option_conflict('l', 'f');
12460 if (edit_only)
12461 option_conflict('l', 'e');
12462 if (delete_backups)
12463 option_conflict('l', 'X');
12464 if (argc != 0 && argc != 1)
12465 usage_histedit();
12466 } else if (delete_backups) {
12467 if (abort_edit)
12468 option_conflict('X', 'a');
12469 if (allow_conflict)
12470 option_conflict('X', 'C');
12471 if (continue_edit)
12472 option_conflict('X', 'c');
12473 if (drop_only)
12474 option_conflict('X', 'd');
12475 if (edit_script_path)
12476 option_conflict('X', 'F');
12477 if (edit_logmsg_only)
12478 option_conflict('X', 'm');
12479 if (fold_only)
12480 option_conflict('X', 'f');
12481 if (edit_only)
12482 option_conflict('X', 'e');
12483 if (list_backups)
12484 option_conflict('X', 'l');
12485 if (argc != 0 && argc != 1)
12486 usage_histedit();
12487 } else if (allow_conflict && !continue_edit)
12488 errx(1, "-C option requires -c");
12489 else if (argc != 0)
12490 usage_histedit();
12493 * This command cannot apply unveil(2) in all cases because the
12494 * user may choose to run an editor to edit the histedit script
12495 * and to edit individual commit log messages.
12496 * unveil(2) traverses exec(2); if an editor is used we have to
12497 * apply unveil after edit script and log messages have been written.
12498 * XXX TODO: Make use of unveil(2) where possible.
12501 cwd = getcwd(NULL, 0);
12502 if (cwd == NULL) {
12503 error = got_error_from_errno("getcwd");
12504 goto done;
12507 error = got_repo_pack_fds_open(&pack_fds);
12508 if (error != NULL)
12509 goto done;
12511 error = got_worktree_open(&worktree, cwd);
12512 if (error) {
12513 if (list_backups || delete_backups) {
12514 if (error->code != GOT_ERR_NOT_WORKTREE)
12515 goto done;
12516 } else {
12517 if (error->code == GOT_ERR_NOT_WORKTREE)
12518 error = wrap_not_worktree_error(error,
12519 "histedit", cwd);
12520 goto done;
12524 if (list_backups || delete_backups) {
12525 error = got_repo_open(&repo,
12526 worktree ? got_worktree_get_repo_path(worktree) : cwd,
12527 NULL, pack_fds);
12528 if (error != NULL)
12529 goto done;
12530 error = apply_unveil(got_repo_get_path(repo), 0,
12531 worktree ? got_worktree_get_root_path(worktree) : NULL);
12532 if (error)
12533 goto done;
12534 error = process_backup_refs(
12535 GOT_WORKTREE_HISTEDIT_BACKUP_REF_PREFIX,
12536 argc == 1 ? argv[0] : NULL, delete_backups, repo);
12537 goto done; /* nothing else to do */
12540 error = get_gitconfig_path(&gitconfig_path);
12541 if (error)
12542 goto done;
12543 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
12544 gitconfig_path, pack_fds);
12545 if (error != NULL)
12546 goto done;
12548 if (worktree != NULL && !list_backups && !delete_backups) {
12549 error = worktree_has_logmsg_ref("histedit", worktree, repo);
12550 if (error)
12551 goto done;
12554 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
12555 if (error)
12556 goto done;
12557 if (rebase_in_progress) {
12558 error = got_error(GOT_ERR_REBASING);
12559 goto done;
12562 error = got_worktree_merge_in_progress(&merge_in_progress, worktree,
12563 repo);
12564 if (error)
12565 goto done;
12566 if (merge_in_progress) {
12567 error = got_error(GOT_ERR_MERGE_BUSY);
12568 goto done;
12571 error = got_worktree_histedit_in_progress(&edit_in_progress, worktree);
12572 if (error)
12573 goto done;
12575 if (edit_in_progress && edit_logmsg_only) {
12576 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
12577 "histedit operation is in progress in this "
12578 "work tree and must be continued or aborted "
12579 "before the -m option can be used");
12580 goto done;
12582 if (edit_in_progress && drop_only) {
12583 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
12584 "histedit operation is in progress in this "
12585 "work tree and must be continued or aborted "
12586 "before the -d option can be used");
12587 goto done;
12589 if (edit_in_progress && fold_only) {
12590 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
12591 "histedit operation is in progress in this "
12592 "work tree and must be continued or aborted "
12593 "before the -f option can be used");
12594 goto done;
12596 if (edit_in_progress && edit_only) {
12597 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
12598 "histedit operation is in progress in this "
12599 "work tree and must be continued or aborted "
12600 "before the -e option can be used");
12601 goto done;
12604 if (edit_in_progress && abort_edit) {
12605 error = got_worktree_histedit_continue(&resume_commit_id,
12606 &tmp_branch, &branch, &base_commit_id, &fileindex,
12607 worktree, repo);
12608 if (error)
12609 goto done;
12610 printf("Switching work tree to %s\n",
12611 got_ref_get_symref_target(branch));
12612 error = got_worktree_histedit_abort(worktree, fileindex, repo,
12613 branch, base_commit_id, abort_progress, &upa);
12614 if (error)
12615 goto done;
12616 printf("Histedit of %s aborted\n",
12617 got_ref_get_symref_target(branch));
12618 print_merge_progress_stats(&upa);
12619 goto done; /* nothing else to do */
12620 } else if (abort_edit) {
12621 error = got_error(GOT_ERR_NOT_HISTEDIT);
12622 goto done;
12625 error = get_author(&committer, repo, worktree);
12626 if (error)
12627 goto done;
12629 if (continue_edit) {
12630 char *path;
12632 if (!edit_in_progress) {
12633 error = got_error(GOT_ERR_NOT_HISTEDIT);
12634 goto done;
12637 error = got_worktree_get_histedit_script_path(&path, worktree);
12638 if (error)
12639 goto done;
12641 error = histedit_load_list(&histedit_cmds, path, repo);
12642 free(path);
12643 if (error)
12644 goto done;
12646 error = got_worktree_histedit_continue(&resume_commit_id,
12647 &tmp_branch, &branch, &base_commit_id, &fileindex,
12648 worktree, repo);
12649 if (error)
12650 goto done;
12652 error = got_ref_resolve(&head_commit_id, repo, branch);
12653 if (error)
12654 goto done;
12656 error = got_object_open_as_commit(&commit, repo,
12657 head_commit_id);
12658 if (error)
12659 goto done;
12660 parent_ids = got_object_commit_get_parent_ids(commit);
12661 pid = STAILQ_FIRST(parent_ids);
12662 if (pid == NULL) {
12663 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
12664 goto done;
12666 error = collect_commits(&commits, head_commit_id, &pid->id,
12667 base_commit_id, got_worktree_get_path_prefix(worktree),
12668 GOT_ERR_HISTEDIT_PATH, repo);
12669 got_object_commit_close(commit);
12670 commit = NULL;
12671 if (error)
12672 goto done;
12673 } else {
12674 if (edit_in_progress) {
12675 error = got_error(GOT_ERR_HISTEDIT_BUSY);
12676 goto done;
12679 error = got_ref_open(&branch, repo,
12680 got_worktree_get_head_ref_name(worktree), 0);
12681 if (error != NULL)
12682 goto done;
12684 if (strncmp(got_ref_get_name(branch), "refs/heads/", 11) != 0) {
12685 error = got_error_msg(GOT_ERR_COMMIT_BRANCH,
12686 "will not edit commit history of a branch outside "
12687 "the \"refs/heads/\" reference namespace");
12688 goto done;
12691 error = got_ref_resolve(&head_commit_id, repo, branch);
12692 got_ref_close(branch);
12693 branch = NULL;
12694 if (error)
12695 goto done;
12697 error = got_object_open_as_commit(&commit, repo,
12698 head_commit_id);
12699 if (error)
12700 goto done;
12701 parent_ids = got_object_commit_get_parent_ids(commit);
12702 pid = STAILQ_FIRST(parent_ids);
12703 if (pid == NULL) {
12704 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
12705 goto done;
12707 error = collect_commits(&commits, head_commit_id, &pid->id,
12708 got_worktree_get_base_commit_id(worktree),
12709 got_worktree_get_path_prefix(worktree),
12710 GOT_ERR_HISTEDIT_PATH, repo);
12711 got_object_commit_close(commit);
12712 commit = NULL;
12713 if (error)
12714 goto done;
12716 if (STAILQ_EMPTY(&commits)) {
12717 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
12718 goto done;
12721 error = got_worktree_histedit_prepare(&tmp_branch, &branch,
12722 &base_commit_id, &fileindex, worktree, repo);
12723 if (error)
12724 goto done;
12726 if (edit_script_path) {
12727 error = histedit_load_list(&histedit_cmds,
12728 edit_script_path, repo);
12729 if (error) {
12730 got_worktree_histedit_abort(worktree, fileindex,
12731 repo, branch, base_commit_id,
12732 abort_progress, &upa);
12733 print_merge_progress_stats(&upa);
12734 goto done;
12736 } else {
12737 const char *branch_name;
12738 branch_name = got_ref_get_symref_target(branch);
12739 if (strncmp(branch_name, "refs/heads/", 11) == 0)
12740 branch_name += 11;
12741 error = histedit_edit_script(&histedit_cmds, &commits,
12742 branch_name, edit_logmsg_only, fold_only,
12743 drop_only, edit_only, repo);
12744 if (error) {
12745 got_worktree_histedit_abort(worktree, fileindex,
12746 repo, branch, base_commit_id,
12747 abort_progress, &upa);
12748 print_merge_progress_stats(&upa);
12749 goto done;
12754 error = histedit_save_list(&histedit_cmds, worktree,
12755 repo);
12756 if (error) {
12757 got_worktree_histedit_abort(worktree, fileindex,
12758 repo, branch, base_commit_id,
12759 abort_progress, &upa);
12760 print_merge_progress_stats(&upa);
12761 goto done;
12766 error = histedit_check_script(&histedit_cmds, &commits, repo);
12767 if (error)
12768 goto done;
12770 TAILQ_FOREACH(hle, &histedit_cmds, entry) {
12771 if (resume_commit_id) {
12772 if (got_object_id_cmp(hle->commit_id,
12773 resume_commit_id) != 0)
12774 continue;
12776 resume_commit_id = NULL;
12777 if (hle->cmd->code == GOT_HISTEDIT_DROP ||
12778 hle->cmd->code == GOT_HISTEDIT_FOLD) {
12779 error = histedit_skip_commit(hle, worktree,
12780 repo);
12781 if (error)
12782 goto done;
12783 } else {
12784 struct got_pathlist_head paths;
12785 int have_changes = 0;
12787 TAILQ_INIT(&paths);
12788 error = got_pathlist_append(&paths, "", NULL);
12789 if (error)
12790 goto done;
12791 error = got_worktree_status(worktree, &paths,
12792 repo, 0, check_local_changes, &have_changes,
12793 check_cancelled, NULL);
12794 got_pathlist_free(&paths,
12795 GOT_PATHLIST_FREE_NONE);
12796 if (error) {
12797 if (error->code != GOT_ERR_CANCELLED)
12798 goto done;
12799 if (sigint_received || sigpipe_received)
12800 goto done;
12802 if (have_changes) {
12803 error = histedit_commit(NULL, worktree,
12804 fileindex, tmp_branch, hle,
12805 committer, allow_conflict, repo);
12806 if (error)
12807 goto done;
12808 } else {
12809 error = got_object_open_as_commit(
12810 &commit, repo, hle->commit_id);
12811 if (error)
12812 goto done;
12813 error = show_histedit_progress(commit,
12814 hle, NULL);
12815 got_object_commit_close(commit);
12816 commit = NULL;
12817 if (error)
12818 goto done;
12821 continue;
12824 if (hle->cmd->code == GOT_HISTEDIT_DROP) {
12825 error = histedit_skip_commit(hle, worktree, repo);
12826 if (error)
12827 goto done;
12828 continue;
12831 error = got_object_open_as_commit(&commit, repo,
12832 hle->commit_id);
12833 if (error)
12834 goto done;
12835 parent_ids = got_object_commit_get_parent_ids(commit);
12836 pid = STAILQ_FIRST(parent_ids);
12838 error = got_worktree_histedit_merge_files(&merged_paths,
12839 worktree, fileindex, &pid->id, hle->commit_id, repo,
12840 update_progress, &upa, check_cancelled, NULL);
12841 if (error)
12842 goto done;
12843 got_object_commit_close(commit);
12844 commit = NULL;
12846 print_merge_progress_stats(&upa);
12847 if (upa.conflicts > 0 || upa.missing > 0 ||
12848 upa.not_deleted > 0 || upa.unversioned > 0) {
12849 if (upa.conflicts > 0) {
12850 error = show_rebase_merge_conflict(
12851 hle->commit_id, repo);
12852 if (error)
12853 goto done;
12855 got_pathlist_free(&merged_paths, GOT_PATHLIST_FREE_PATH);
12856 break;
12859 if (hle->cmd->code == GOT_HISTEDIT_EDIT) {
12860 char *id_str;
12861 error = got_object_id_str(&id_str, hle->commit_id);
12862 if (error)
12863 goto done;
12864 printf("Stopping histedit for amending commit %s\n",
12865 id_str);
12866 free(id_str);
12867 got_pathlist_free(&merged_paths, GOT_PATHLIST_FREE_PATH);
12868 error = got_worktree_histedit_postpone(worktree,
12869 fileindex);
12870 goto done;
12873 if (hle->cmd->code == GOT_HISTEDIT_FOLD) {
12874 error = histedit_skip_commit(hle, worktree, repo);
12875 if (error)
12876 goto done;
12877 continue;
12880 error = histedit_commit(&merged_paths, worktree, fileindex,
12881 tmp_branch, hle, committer, allow_conflict, repo);
12882 got_pathlist_free(&merged_paths, GOT_PATHLIST_FREE_PATH);
12883 if (error)
12884 goto done;
12887 if (upa.conflicts > 0 || upa.missing > 0 ||
12888 upa.not_deleted > 0 || upa.unversioned > 0) {
12889 error = got_worktree_histedit_postpone(worktree, fileindex);
12890 if (error)
12891 goto done;
12892 if (upa.conflicts > 0 && upa.missing == 0 &&
12893 upa.not_deleted == 0 && upa.unversioned == 0) {
12894 error = got_error_msg(GOT_ERR_CONFLICTS,
12895 "conflicts must be resolved before histedit "
12896 "can continue");
12897 } else if (upa.conflicts > 0) {
12898 error = got_error_msg(GOT_ERR_CONFLICTS,
12899 "conflicts must be resolved before histedit "
12900 "can continue; changes destined for some "
12901 "files were not yet merged and should be "
12902 "merged manually if required before the "
12903 "histedit operation is continued");
12904 } else {
12905 error = got_error_msg(GOT_ERR_CONFLICTS,
12906 "changes destined for some files were not "
12907 "yet merged and should be merged manually "
12908 "if required before the histedit operation "
12909 "is continued");
12911 } else
12912 error = histedit_complete(worktree, fileindex, tmp_branch,
12913 branch, repo);
12914 done:
12915 free(cwd);
12916 free(committer);
12917 free(gitconfig_path);
12918 got_object_id_queue_free(&commits);
12919 histedit_free_list(&histedit_cmds);
12920 free(head_commit_id);
12921 free(base_commit_id);
12922 free(resume_commit_id);
12923 if (commit)
12924 got_object_commit_close(commit);
12925 if (branch)
12926 got_ref_close(branch);
12927 if (tmp_branch)
12928 got_ref_close(tmp_branch);
12929 if (worktree)
12930 got_worktree_close(worktree);
12931 if (repo) {
12932 const struct got_error *close_err = got_repo_close(repo);
12933 if (error == NULL)
12934 error = close_err;
12936 if (pack_fds) {
12937 const struct got_error *pack_err =
12938 got_repo_pack_fds_close(pack_fds);
12939 if (error == NULL)
12940 error = pack_err;
12942 return error;
12945 __dead static void
12946 usage_integrate(void)
12948 fprintf(stderr, "usage: %s integrate branch\n", getprogname());
12949 exit(1);
12952 static const struct got_error *
12953 cmd_integrate(int argc, char *argv[])
12955 const struct got_error *error = NULL;
12956 struct got_repository *repo = NULL;
12957 struct got_worktree *worktree = NULL;
12958 char *cwd = NULL, *refname = NULL, *base_refname = NULL;
12959 const char *branch_arg = NULL;
12960 struct got_reference *branch_ref = NULL, *base_branch_ref = NULL;
12961 struct got_fileindex *fileindex = NULL;
12962 struct got_object_id *commit_id = NULL, *base_commit_id = NULL;
12963 int ch;
12964 struct got_update_progress_arg upa;
12965 int *pack_fds = NULL;
12967 #ifndef PROFILE
12968 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
12969 "unveil", NULL) == -1)
12970 err(1, "pledge");
12971 #endif
12973 while ((ch = getopt(argc, argv, "")) != -1) {
12974 switch (ch) {
12975 default:
12976 usage_integrate();
12977 /* NOTREACHED */
12981 argc -= optind;
12982 argv += optind;
12984 if (argc != 1)
12985 usage_integrate();
12986 branch_arg = argv[0];
12988 cwd = getcwd(NULL, 0);
12989 if (cwd == NULL) {
12990 error = got_error_from_errno("getcwd");
12991 goto done;
12994 error = got_repo_pack_fds_open(&pack_fds);
12995 if (error != NULL)
12996 goto done;
12998 error = got_worktree_open(&worktree, cwd);
12999 if (error) {
13000 if (error->code == GOT_ERR_NOT_WORKTREE)
13001 error = wrap_not_worktree_error(error, "integrate",
13002 cwd);
13003 goto done;
13006 error = check_rebase_or_histedit_in_progress(worktree);
13007 if (error)
13008 goto done;
13010 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
13011 NULL, pack_fds);
13012 if (error != NULL)
13013 goto done;
13015 error = apply_unveil(got_repo_get_path(repo), 0,
13016 got_worktree_get_root_path(worktree));
13017 if (error)
13018 goto done;
13020 error = check_merge_in_progress(worktree, repo);
13021 if (error)
13022 goto done;
13024 if (asprintf(&refname, "refs/heads/%s", branch_arg) == -1) {
13025 error = got_error_from_errno("asprintf");
13026 goto done;
13029 error = got_worktree_integrate_prepare(&fileindex, &branch_ref,
13030 &base_branch_ref, worktree, refname, repo);
13031 if (error)
13032 goto done;
13034 refname = strdup(got_ref_get_name(branch_ref));
13035 if (refname == NULL) {
13036 error = got_error_from_errno("strdup");
13037 got_worktree_integrate_abort(worktree, fileindex, repo,
13038 branch_ref, base_branch_ref);
13039 goto done;
13041 base_refname = strdup(got_ref_get_name(base_branch_ref));
13042 if (base_refname == NULL) {
13043 error = got_error_from_errno("strdup");
13044 got_worktree_integrate_abort(worktree, fileindex, repo,
13045 branch_ref, base_branch_ref);
13046 goto done;
13048 if (strncmp(base_refname, "refs/heads/", 11) != 0) {
13049 error = got_error(GOT_ERR_INTEGRATE_BRANCH);
13050 got_worktree_integrate_abort(worktree, fileindex, repo,
13051 branch_ref, base_branch_ref);
13052 goto done;
13055 error = got_ref_resolve(&commit_id, repo, branch_ref);
13056 if (error)
13057 goto done;
13059 error = got_ref_resolve(&base_commit_id, repo, base_branch_ref);
13060 if (error)
13061 goto done;
13063 if (got_object_id_cmp(commit_id, base_commit_id) == 0) {
13064 error = got_error_msg(GOT_ERR_SAME_BRANCH,
13065 "specified branch has already been integrated");
13066 got_worktree_integrate_abort(worktree, fileindex, repo,
13067 branch_ref, base_branch_ref);
13068 goto done;
13071 error = check_linear_ancestry(commit_id, base_commit_id, 1, repo);
13072 if (error) {
13073 if (error->code == GOT_ERR_ANCESTRY)
13074 error = got_error(GOT_ERR_REBASE_REQUIRED);
13075 got_worktree_integrate_abort(worktree, fileindex, repo,
13076 branch_ref, base_branch_ref);
13077 goto done;
13080 memset(&upa, 0, sizeof(upa));
13081 error = got_worktree_integrate_continue(worktree, fileindex, repo,
13082 branch_ref, base_branch_ref, update_progress, &upa,
13083 check_cancelled, NULL);
13084 if (error)
13085 goto done;
13087 printf("Integrated %s into %s\n", refname, base_refname);
13088 print_update_progress_stats(&upa);
13089 done:
13090 if (repo) {
13091 const struct got_error *close_err = got_repo_close(repo);
13092 if (error == NULL)
13093 error = close_err;
13095 if (worktree)
13096 got_worktree_close(worktree);
13097 if (pack_fds) {
13098 const struct got_error *pack_err =
13099 got_repo_pack_fds_close(pack_fds);
13100 if (error == NULL)
13101 error = pack_err;
13103 free(cwd);
13104 free(base_commit_id);
13105 free(commit_id);
13106 free(refname);
13107 free(base_refname);
13108 return error;
13111 __dead static void
13112 usage_merge(void)
13114 fprintf(stderr, "usage: %s merge [-aCcn] [branch]\n", getprogname());
13115 exit(1);
13118 static const struct got_error *
13119 cmd_merge(int argc, char *argv[])
13121 const struct got_error *error = NULL;
13122 struct got_worktree *worktree = NULL;
13123 struct got_repository *repo = NULL;
13124 struct got_fileindex *fileindex = NULL;
13125 char *cwd = NULL, *id_str = NULL, *author = NULL;
13126 char *gitconfig_path = NULL;
13127 struct got_reference *branch = NULL, *wt_branch = NULL;
13128 struct got_object_id *branch_tip = NULL, *yca_id = NULL;
13129 struct got_object_id *wt_branch_tip = NULL;
13130 int ch, merge_in_progress = 0, abort_merge = 0, continue_merge = 0;
13131 int allow_conflict = 0, interrupt_merge = 0;
13132 struct got_update_progress_arg upa;
13133 struct got_object_id *merge_commit_id = NULL;
13134 char *branch_name = NULL;
13135 int *pack_fds = NULL;
13137 memset(&upa, 0, sizeof(upa));
13139 #ifndef PROFILE
13140 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
13141 "unveil", NULL) == -1)
13142 err(1, "pledge");
13143 #endif
13145 while ((ch = getopt(argc, argv, "aCcn")) != -1) {
13146 switch (ch) {
13147 case 'a':
13148 abort_merge = 1;
13149 break;
13150 case 'C':
13151 allow_conflict = 1;
13152 case 'c':
13153 continue_merge = 1;
13154 break;
13155 case 'n':
13156 interrupt_merge = 1;
13157 break;
13158 default:
13159 usage_merge();
13160 /* NOTREACHED */
13164 argc -= optind;
13165 argv += optind;
13167 if (allow_conflict) {
13168 if (abort_merge)
13169 option_conflict('a', 'C');
13170 if (!continue_merge)
13171 errx(1, "-C option requires -c");
13173 if (abort_merge && continue_merge)
13174 option_conflict('a', 'c');
13175 if (abort_merge || continue_merge) {
13176 if (argc != 0)
13177 usage_merge();
13178 } else if (argc != 1)
13179 usage_merge();
13181 cwd = getcwd(NULL, 0);
13182 if (cwd == NULL) {
13183 error = got_error_from_errno("getcwd");
13184 goto done;
13187 error = got_repo_pack_fds_open(&pack_fds);
13188 if (error != NULL)
13189 goto done;
13191 error = got_worktree_open(&worktree, cwd);
13192 if (error) {
13193 if (error->code == GOT_ERR_NOT_WORKTREE)
13194 error = wrap_not_worktree_error(error,
13195 "merge", cwd);
13196 goto done;
13199 error = get_gitconfig_path(&gitconfig_path);
13200 if (error)
13201 goto done;
13202 error = got_repo_open(&repo,
13203 worktree ? got_worktree_get_repo_path(worktree) : cwd,
13204 gitconfig_path, pack_fds);
13205 if (error != NULL)
13206 goto done;
13208 if (worktree != NULL) {
13209 error = worktree_has_logmsg_ref("merge", worktree, repo);
13210 if (error)
13211 goto done;
13214 error = apply_unveil(got_repo_get_path(repo), 0,
13215 worktree ? got_worktree_get_root_path(worktree) : NULL);
13216 if (error)
13217 goto done;
13219 error = check_rebase_or_histedit_in_progress(worktree);
13220 if (error)
13221 goto done;
13223 error = got_worktree_merge_in_progress(&merge_in_progress, worktree,
13224 repo);
13225 if (error)
13226 goto done;
13228 if (abort_merge) {
13229 if (!merge_in_progress) {
13230 error = got_error(GOT_ERR_NOT_MERGING);
13231 goto done;
13233 error = got_worktree_merge_continue(&branch_name,
13234 &branch_tip, &fileindex, worktree, repo);
13235 if (error)
13236 goto done;
13237 error = got_worktree_merge_abort(worktree, fileindex, repo,
13238 abort_progress, &upa);
13239 if (error)
13240 goto done;
13241 printf("Merge of %s aborted\n", branch_name);
13242 goto done; /* nothing else to do */
13245 error = get_author(&author, repo, worktree);
13246 if (error)
13247 goto done;
13249 if (continue_merge) {
13250 if (!merge_in_progress) {
13251 error = got_error(GOT_ERR_NOT_MERGING);
13252 goto done;
13254 error = got_worktree_merge_continue(&branch_name,
13255 &branch_tip, &fileindex, worktree, repo);
13256 if (error)
13257 goto done;
13258 } else {
13259 error = got_ref_open(&branch, repo, argv[0], 0);
13260 if (error != NULL)
13261 goto done;
13262 branch_name = strdup(got_ref_get_name(branch));
13263 if (branch_name == NULL) {
13264 error = got_error_from_errno("strdup");
13265 goto done;
13267 error = got_ref_resolve(&branch_tip, repo, branch);
13268 if (error)
13269 goto done;
13272 error = got_ref_open(&wt_branch, repo,
13273 got_worktree_get_head_ref_name(worktree), 0);
13274 if (error)
13275 goto done;
13276 error = got_ref_resolve(&wt_branch_tip, repo, wt_branch);
13277 if (error)
13278 goto done;
13279 error = got_commit_graph_find_youngest_common_ancestor(&yca_id,
13280 wt_branch_tip, branch_tip, 0, repo,
13281 check_cancelled, NULL);
13282 if (error && error->code != GOT_ERR_ANCESTRY)
13283 goto done;
13285 if (!continue_merge) {
13286 error = check_path_prefix(wt_branch_tip, branch_tip,
13287 got_worktree_get_path_prefix(worktree),
13288 GOT_ERR_MERGE_PATH, repo);
13289 if (error)
13290 goto done;
13291 if (yca_id) {
13292 error = check_same_branch(wt_branch_tip, branch,
13293 yca_id, repo);
13294 if (error) {
13295 if (error->code != GOT_ERR_ANCESTRY)
13296 goto done;
13297 error = NULL;
13298 } else {
13299 static char msg[512];
13300 snprintf(msg, sizeof(msg),
13301 "cannot create a merge commit because "
13302 "%s is based on %s; %s can be integrated "
13303 "with 'got integrate' instead", branch_name,
13304 got_worktree_get_head_ref_name(worktree),
13305 branch_name);
13306 error = got_error_msg(GOT_ERR_SAME_BRANCH, msg);
13307 goto done;
13310 error = got_worktree_merge_prepare(&fileindex, worktree,
13311 branch, repo);
13312 if (error)
13313 goto done;
13315 error = got_worktree_merge_branch(worktree, fileindex,
13316 yca_id, branch_tip, repo, update_progress, &upa,
13317 check_cancelled, NULL);
13318 if (error)
13319 goto done;
13320 print_merge_progress_stats(&upa);
13321 if (!upa.did_something) {
13322 error = got_worktree_merge_abort(worktree, fileindex,
13323 repo, abort_progress, &upa);
13324 if (error)
13325 goto done;
13326 printf("Already up-to-date\n");
13327 goto done;
13331 if (interrupt_merge) {
13332 error = got_worktree_merge_postpone(worktree, fileindex);
13333 if (error)
13334 goto done;
13335 printf("Merge of %s interrupted on request\n", branch_name);
13336 } else if (upa.conflicts > 0 || upa.missing > 0 ||
13337 upa.not_deleted > 0 || upa.unversioned > 0) {
13338 error = got_worktree_merge_postpone(worktree, fileindex);
13339 if (error)
13340 goto done;
13341 if (upa.conflicts > 0 && upa.missing == 0 &&
13342 upa.not_deleted == 0 && upa.unversioned == 0) {
13343 error = got_error_msg(GOT_ERR_CONFLICTS,
13344 "conflicts must be resolved before merging "
13345 "can continue");
13346 } else if (upa.conflicts > 0) {
13347 error = got_error_msg(GOT_ERR_CONFLICTS,
13348 "conflicts must be resolved before merging "
13349 "can continue; changes destined for some "
13350 "files were not yet merged and "
13351 "should be merged manually if required before the "
13352 "merge operation is continued");
13353 } else {
13354 error = got_error_msg(GOT_ERR_CONFLICTS,
13355 "changes destined for some "
13356 "files were not yet merged and should be "
13357 "merged manually if required before the "
13358 "merge operation is continued");
13360 goto done;
13361 } else {
13362 error = got_worktree_merge_commit(&merge_commit_id, worktree,
13363 fileindex, author, NULL, 1, branch_tip, branch_name,
13364 allow_conflict, repo, continue_merge ? print_status : NULL,
13365 NULL);
13366 if (error)
13367 goto done;
13368 error = got_worktree_merge_complete(worktree, fileindex, repo);
13369 if (error)
13370 goto done;
13371 error = got_object_id_str(&id_str, merge_commit_id);
13372 if (error)
13373 goto done;
13374 printf("Merged %s into %s: %s\n", branch_name,
13375 got_worktree_get_head_ref_name(worktree),
13376 id_str);
13379 done:
13380 free(gitconfig_path);
13381 free(id_str);
13382 free(merge_commit_id);
13383 free(author);
13384 free(branch_tip);
13385 free(branch_name);
13386 free(yca_id);
13387 if (branch)
13388 got_ref_close(branch);
13389 if (wt_branch)
13390 got_ref_close(wt_branch);
13391 if (worktree)
13392 got_worktree_close(worktree);
13393 if (repo) {
13394 const struct got_error *close_err = got_repo_close(repo);
13395 if (error == NULL)
13396 error = close_err;
13398 if (pack_fds) {
13399 const struct got_error *pack_err =
13400 got_repo_pack_fds_close(pack_fds);
13401 if (error == NULL)
13402 error = pack_err;
13404 return error;
13407 __dead static void
13408 usage_stage(void)
13410 fprintf(stderr, "usage: %s stage [-lpS] [-F response-script] "
13411 "[path ...]\n", getprogname());
13412 exit(1);
13415 static const struct got_error *
13416 print_stage(void *arg, unsigned char status, unsigned char staged_status,
13417 const char *path, struct got_object_id *blob_id,
13418 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
13419 int dirfd, const char *de_name)
13421 const struct got_error *err = NULL;
13422 char *id_str = NULL;
13424 if (staged_status != GOT_STATUS_ADD &&
13425 staged_status != GOT_STATUS_MODIFY &&
13426 staged_status != GOT_STATUS_DELETE)
13427 return NULL;
13429 if (staged_status == GOT_STATUS_ADD ||
13430 staged_status == GOT_STATUS_MODIFY)
13431 err = got_object_id_str(&id_str, staged_blob_id);
13432 else
13433 err = got_object_id_str(&id_str, blob_id);
13434 if (err)
13435 return err;
13437 printf("%s %c %s\n", id_str, staged_status, path);
13438 free(id_str);
13439 return NULL;
13442 static const struct got_error *
13443 cmd_stage(int argc, char *argv[])
13445 const struct got_error *error = NULL;
13446 struct got_repository *repo = NULL;
13447 struct got_worktree *worktree = NULL;
13448 char *cwd = NULL;
13449 struct got_pathlist_head paths;
13450 int ch, list_stage = 0, pflag = 0, allow_bad_symlinks = 0;
13451 FILE *patch_script_file = NULL;
13452 const char *patch_script_path = NULL;
13453 struct choose_patch_arg cpa;
13454 int *pack_fds = NULL;
13456 TAILQ_INIT(&paths);
13458 #ifndef PROFILE
13459 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
13460 "unveil", NULL) == -1)
13461 err(1, "pledge");
13462 #endif
13464 while ((ch = getopt(argc, argv, "F:lpS")) != -1) {
13465 switch (ch) {
13466 case 'F':
13467 patch_script_path = optarg;
13468 break;
13469 case 'l':
13470 list_stage = 1;
13471 break;
13472 case 'p':
13473 pflag = 1;
13474 break;
13475 case 'S':
13476 allow_bad_symlinks = 1;
13477 break;
13478 default:
13479 usage_stage();
13480 /* NOTREACHED */
13484 argc -= optind;
13485 argv += optind;
13487 if (list_stage && (pflag || patch_script_path))
13488 errx(1, "-l option cannot be used with other options");
13489 if (patch_script_path && !pflag)
13490 errx(1, "-F option can only be used together with -p option");
13492 cwd = getcwd(NULL, 0);
13493 if (cwd == NULL) {
13494 error = got_error_from_errno("getcwd");
13495 goto done;
13498 error = got_repo_pack_fds_open(&pack_fds);
13499 if (error != NULL)
13500 goto done;
13502 error = got_worktree_open(&worktree, cwd);
13503 if (error) {
13504 if (error->code == GOT_ERR_NOT_WORKTREE)
13505 error = wrap_not_worktree_error(error, "stage", cwd);
13506 goto done;
13509 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
13510 NULL, pack_fds);
13511 if (error != NULL)
13512 goto done;
13514 if (patch_script_path) {
13515 patch_script_file = fopen(patch_script_path, "re");
13516 if (patch_script_file == NULL) {
13517 error = got_error_from_errno2("fopen",
13518 patch_script_path);
13519 goto done;
13522 error = apply_unveil(got_repo_get_path(repo), 0,
13523 got_worktree_get_root_path(worktree));
13524 if (error)
13525 goto done;
13527 error = check_merge_in_progress(worktree, repo);
13528 if (error)
13529 goto done;
13531 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
13532 if (error)
13533 goto done;
13535 if (list_stage)
13536 error = got_worktree_status(worktree, &paths, repo, 0,
13537 print_stage, NULL, check_cancelled, NULL);
13538 else {
13539 cpa.patch_script_file = patch_script_file;
13540 cpa.action = "stage";
13541 error = got_worktree_stage(worktree, &paths,
13542 pflag ? NULL : print_status, NULL,
13543 pflag ? choose_patch : NULL, &cpa,
13544 allow_bad_symlinks, repo);
13546 done:
13547 if (patch_script_file && fclose(patch_script_file) == EOF &&
13548 error == NULL)
13549 error = got_error_from_errno2("fclose", patch_script_path);
13550 if (repo) {
13551 const struct got_error *close_err = got_repo_close(repo);
13552 if (error == NULL)
13553 error = close_err;
13555 if (worktree)
13556 got_worktree_close(worktree);
13557 if (pack_fds) {
13558 const struct got_error *pack_err =
13559 got_repo_pack_fds_close(pack_fds);
13560 if (error == NULL)
13561 error = pack_err;
13563 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
13564 free(cwd);
13565 return error;
13568 __dead static void
13569 usage_unstage(void)
13571 fprintf(stderr, "usage: %s unstage [-p] [-F response-script] "
13572 "[path ...]\n", getprogname());
13573 exit(1);
13577 static const struct got_error *
13578 cmd_unstage(int argc, char *argv[])
13580 const struct got_error *error = NULL;
13581 struct got_repository *repo = NULL;
13582 struct got_worktree *worktree = NULL;
13583 char *cwd = NULL;
13584 struct got_pathlist_head paths;
13585 int ch, pflag = 0;
13586 struct got_update_progress_arg upa;
13587 FILE *patch_script_file = NULL;
13588 const char *patch_script_path = NULL;
13589 struct choose_patch_arg cpa;
13590 int *pack_fds = NULL;
13592 TAILQ_INIT(&paths);
13594 #ifndef PROFILE
13595 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
13596 "unveil", NULL) == -1)
13597 err(1, "pledge");
13598 #endif
13600 while ((ch = getopt(argc, argv, "F:p")) != -1) {
13601 switch (ch) {
13602 case 'F':
13603 patch_script_path = optarg;
13604 break;
13605 case 'p':
13606 pflag = 1;
13607 break;
13608 default:
13609 usage_unstage();
13610 /* NOTREACHED */
13614 argc -= optind;
13615 argv += optind;
13617 if (patch_script_path && !pflag)
13618 errx(1, "-F option can only be used together with -p option");
13620 cwd = getcwd(NULL, 0);
13621 if (cwd == NULL) {
13622 error = got_error_from_errno("getcwd");
13623 goto done;
13626 error = got_repo_pack_fds_open(&pack_fds);
13627 if (error != NULL)
13628 goto done;
13630 error = got_worktree_open(&worktree, cwd);
13631 if (error) {
13632 if (error->code == GOT_ERR_NOT_WORKTREE)
13633 error = wrap_not_worktree_error(error, "unstage", cwd);
13634 goto done;
13637 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
13638 NULL, pack_fds);
13639 if (error != NULL)
13640 goto done;
13642 if (patch_script_path) {
13643 patch_script_file = fopen(patch_script_path, "re");
13644 if (patch_script_file == NULL) {
13645 error = got_error_from_errno2("fopen",
13646 patch_script_path);
13647 goto done;
13651 error = apply_unveil(got_repo_get_path(repo), 0,
13652 got_worktree_get_root_path(worktree));
13653 if (error)
13654 goto done;
13656 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
13657 if (error)
13658 goto done;
13660 cpa.patch_script_file = patch_script_file;
13661 cpa.action = "unstage";
13662 memset(&upa, 0, sizeof(upa));
13663 error = got_worktree_unstage(worktree, &paths, update_progress,
13664 &upa, pflag ? choose_patch : NULL, &cpa, repo);
13665 if (!error)
13666 print_merge_progress_stats(&upa);
13667 done:
13668 if (patch_script_file && fclose(patch_script_file) == EOF &&
13669 error == NULL)
13670 error = got_error_from_errno2("fclose", patch_script_path);
13671 if (repo) {
13672 const struct got_error *close_err = got_repo_close(repo);
13673 if (error == NULL)
13674 error = close_err;
13676 if (worktree)
13677 got_worktree_close(worktree);
13678 if (pack_fds) {
13679 const struct got_error *pack_err =
13680 got_repo_pack_fds_close(pack_fds);
13681 if (error == NULL)
13682 error = pack_err;
13684 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
13685 free(cwd);
13686 return error;
13689 __dead static void
13690 usage_cat(void)
13692 fprintf(stderr, "usage: %s cat [-P] [-c commit] [-r repository-path] "
13693 "arg ...\n", getprogname());
13694 exit(1);
13697 static const struct got_error *
13698 cat_blob(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
13700 const struct got_error *err;
13701 struct got_blob_object *blob;
13702 int fd = -1;
13704 fd = got_opentempfd();
13705 if (fd == -1)
13706 return got_error_from_errno("got_opentempfd");
13708 err = got_object_open_as_blob(&blob, repo, id, 8192, fd);
13709 if (err)
13710 goto done;
13712 err = got_object_blob_dump_to_file(NULL, NULL, NULL, outfile, blob);
13713 done:
13714 if (fd != -1 && close(fd) == -1 && err == NULL)
13715 err = got_error_from_errno("close");
13716 if (blob)
13717 got_object_blob_close(blob);
13718 return err;
13721 static const struct got_error *
13722 cat_tree(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
13724 const struct got_error *err;
13725 struct got_tree_object *tree;
13726 int nentries, i;
13728 err = got_object_open_as_tree(&tree, repo, id);
13729 if (err)
13730 return err;
13732 nentries = got_object_tree_get_nentries(tree);
13733 for (i = 0; i < nentries; i++) {
13734 struct got_tree_entry *te;
13735 char *id_str;
13736 if (sigint_received || sigpipe_received)
13737 break;
13738 te = got_object_tree_get_entry(tree, i);
13739 err = got_object_id_str(&id_str, got_tree_entry_get_id(te));
13740 if (err)
13741 break;
13742 fprintf(outfile, "%s %.7o %s\n", id_str,
13743 got_tree_entry_get_mode(te),
13744 got_tree_entry_get_name(te));
13745 free(id_str);
13748 got_object_tree_close(tree);
13749 return err;
13752 static const struct got_error *
13753 cat_commit(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
13755 const struct got_error *err;
13756 struct got_commit_object *commit;
13757 const struct got_object_id_queue *parent_ids;
13758 struct got_object_qid *pid;
13759 char *id_str = NULL;
13760 const char *logmsg = NULL;
13761 char gmtoff[6];
13763 err = got_object_open_as_commit(&commit, repo, id);
13764 if (err)
13765 return err;
13767 err = got_object_id_str(&id_str, got_object_commit_get_tree_id(commit));
13768 if (err)
13769 goto done;
13771 fprintf(outfile, "%s%s\n", GOT_COMMIT_LABEL_TREE, id_str);
13772 parent_ids = got_object_commit_get_parent_ids(commit);
13773 fprintf(outfile, "numparents %d\n",
13774 got_object_commit_get_nparents(commit));
13775 STAILQ_FOREACH(pid, parent_ids, entry) {
13776 char *pid_str;
13777 err = got_object_id_str(&pid_str, &pid->id);
13778 if (err)
13779 goto done;
13780 fprintf(outfile, "%s%s\n", GOT_COMMIT_LABEL_PARENT, pid_str);
13781 free(pid_str);
13783 got_date_format_gmtoff(gmtoff, sizeof(gmtoff),
13784 got_object_commit_get_author_gmtoff(commit));
13785 fprintf(outfile, "%s%s %lld %s\n", GOT_COMMIT_LABEL_AUTHOR,
13786 got_object_commit_get_author(commit),
13787 (long long)got_object_commit_get_author_time(commit),
13788 gmtoff);
13790 got_date_format_gmtoff(gmtoff, sizeof(gmtoff),
13791 got_object_commit_get_committer_gmtoff(commit));
13792 fprintf(outfile, "%s%s %lld %s\n", GOT_COMMIT_LABEL_COMMITTER,
13793 got_object_commit_get_committer(commit),
13794 (long long)got_object_commit_get_committer_time(commit),
13795 gmtoff);
13797 logmsg = got_object_commit_get_logmsg_raw(commit);
13798 fprintf(outfile, "messagelen %zd\n", strlen(logmsg));
13799 fprintf(outfile, "%s", logmsg);
13800 done:
13801 free(id_str);
13802 got_object_commit_close(commit);
13803 return err;
13806 static const struct got_error *
13807 cat_tag(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
13809 const struct got_error *err;
13810 struct got_tag_object *tag;
13811 char *id_str = NULL;
13812 const char *tagmsg = NULL;
13813 char gmtoff[6];
13815 err = got_object_open_as_tag(&tag, repo, id);
13816 if (err)
13817 return err;
13819 err = got_object_id_str(&id_str, got_object_tag_get_object_id(tag));
13820 if (err)
13821 goto done;
13823 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_OBJECT, id_str);
13825 switch (got_object_tag_get_object_type(tag)) {
13826 case GOT_OBJ_TYPE_BLOB:
13827 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
13828 GOT_OBJ_LABEL_BLOB);
13829 break;
13830 case GOT_OBJ_TYPE_TREE:
13831 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
13832 GOT_OBJ_LABEL_TREE);
13833 break;
13834 case GOT_OBJ_TYPE_COMMIT:
13835 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
13836 GOT_OBJ_LABEL_COMMIT);
13837 break;
13838 case GOT_OBJ_TYPE_TAG:
13839 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
13840 GOT_OBJ_LABEL_TAG);
13841 break;
13842 default:
13843 break;
13846 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TAG,
13847 got_object_tag_get_name(tag));
13849 got_date_format_gmtoff(gmtoff, sizeof(gmtoff),
13850 got_object_tag_get_tagger_gmtoff(tag));
13851 fprintf(outfile, "%s%s %lld %s\n", GOT_TAG_LABEL_TAGGER,
13852 got_object_tag_get_tagger(tag),
13853 (long long)got_object_tag_get_tagger_time(tag),
13854 gmtoff);
13856 tagmsg = got_object_tag_get_message(tag);
13857 fprintf(outfile, "messagelen %zd\n", strlen(tagmsg));
13858 fprintf(outfile, "%s", tagmsg);
13859 done:
13860 free(id_str);
13861 got_object_tag_close(tag);
13862 return err;
13865 static const struct got_error *
13866 cmd_cat(int argc, char *argv[])
13868 const struct got_error *error;
13869 struct got_repository *repo = NULL;
13870 struct got_worktree *worktree = NULL;
13871 char *cwd = NULL, *repo_path = NULL, *label = NULL;
13872 const char *commit_id_str = NULL;
13873 struct got_object_id *id = NULL, *commit_id = NULL;
13874 struct got_commit_object *commit = NULL;
13875 int ch, obj_type, i, force_path = 0;
13876 struct got_reflist_head refs;
13877 int *pack_fds = NULL;
13879 TAILQ_INIT(&refs);
13881 #ifndef PROFILE
13882 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
13883 NULL) == -1)
13884 err(1, "pledge");
13885 #endif
13887 while ((ch = getopt(argc, argv, "c:Pr:")) != -1) {
13888 switch (ch) {
13889 case 'c':
13890 commit_id_str = optarg;
13891 break;
13892 case 'P':
13893 force_path = 1;
13894 break;
13895 case 'r':
13896 repo_path = realpath(optarg, NULL);
13897 if (repo_path == NULL)
13898 return got_error_from_errno2("realpath",
13899 optarg);
13900 got_path_strip_trailing_slashes(repo_path);
13901 break;
13902 default:
13903 usage_cat();
13904 /* NOTREACHED */
13908 argc -= optind;
13909 argv += optind;
13911 cwd = getcwd(NULL, 0);
13912 if (cwd == NULL) {
13913 error = got_error_from_errno("getcwd");
13914 goto done;
13917 error = got_repo_pack_fds_open(&pack_fds);
13918 if (error != NULL)
13919 goto done;
13921 if (repo_path == NULL) {
13922 error = got_worktree_open(&worktree, cwd);
13923 if (error && error->code != GOT_ERR_NOT_WORKTREE)
13924 goto done;
13925 if (worktree) {
13926 repo_path = strdup(
13927 got_worktree_get_repo_path(worktree));
13928 if (repo_path == NULL) {
13929 error = got_error_from_errno("strdup");
13930 goto done;
13933 /* Release work tree lock. */
13934 got_worktree_close(worktree);
13935 worktree = NULL;
13939 if (repo_path == NULL) {
13940 repo_path = strdup(cwd);
13941 if (repo_path == NULL)
13942 return got_error_from_errno("strdup");
13945 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
13946 free(repo_path);
13947 if (error != NULL)
13948 goto done;
13950 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
13951 if (error)
13952 goto done;
13954 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
13955 if (error)
13956 goto done;
13958 if (commit_id_str == NULL)
13959 commit_id_str = GOT_REF_HEAD;
13960 error = got_repo_match_object_id(&commit_id, NULL,
13961 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
13962 if (error)
13963 goto done;
13965 error = got_object_open_as_commit(&commit, repo, commit_id);
13966 if (error)
13967 goto done;
13969 for (i = 0; i < argc; i++) {
13970 if (force_path) {
13971 error = got_object_id_by_path(&id, repo, commit,
13972 argv[i]);
13973 if (error)
13974 break;
13975 } else {
13976 error = got_repo_match_object_id(&id, &label, argv[i],
13977 GOT_OBJ_TYPE_ANY, NULL /* do not resolve tags */,
13978 repo);
13979 if (error) {
13980 if (error->code != GOT_ERR_BAD_OBJ_ID_STR &&
13981 error->code != GOT_ERR_NOT_REF)
13982 break;
13983 error = got_object_id_by_path(&id, repo,
13984 commit, argv[i]);
13985 if (error)
13986 break;
13990 error = got_object_get_type(&obj_type, repo, id);
13991 if (error)
13992 break;
13994 switch (obj_type) {
13995 case GOT_OBJ_TYPE_BLOB:
13996 error = cat_blob(id, repo, stdout);
13997 break;
13998 case GOT_OBJ_TYPE_TREE:
13999 error = cat_tree(id, repo, stdout);
14000 break;
14001 case GOT_OBJ_TYPE_COMMIT:
14002 error = cat_commit(id, repo, stdout);
14003 break;
14004 case GOT_OBJ_TYPE_TAG:
14005 error = cat_tag(id, repo, stdout);
14006 break;
14007 default:
14008 error = got_error(GOT_ERR_OBJ_TYPE);
14009 break;
14011 if (error)
14012 break;
14013 free(label);
14014 label = NULL;
14015 free(id);
14016 id = NULL;
14018 done:
14019 free(label);
14020 free(id);
14021 free(commit_id);
14022 if (commit)
14023 got_object_commit_close(commit);
14024 if (worktree)
14025 got_worktree_close(worktree);
14026 if (repo) {
14027 const struct got_error *close_err = got_repo_close(repo);
14028 if (error == NULL)
14029 error = close_err;
14031 if (pack_fds) {
14032 const struct got_error *pack_err =
14033 got_repo_pack_fds_close(pack_fds);
14034 if (error == NULL)
14035 error = pack_err;
14038 got_ref_list_free(&refs);
14039 return error;
14042 __dead static void
14043 usage_info(void)
14045 fprintf(stderr, "usage: %s info [path ...]\n",
14046 getprogname());
14047 exit(1);
14050 static const struct got_error *
14051 print_path_info(void *arg, const char *path, mode_t mode, time_t mtime,
14052 struct got_object_id *blob_id, struct got_object_id *staged_blob_id,
14053 struct got_object_id *commit_id)
14055 const struct got_error *err = NULL;
14056 char *id_str = NULL;
14057 char datebuf[128];
14058 struct tm mytm, *tm;
14059 struct got_pathlist_head *paths = arg;
14060 struct got_pathlist_entry *pe;
14063 * Clear error indication from any of the path arguments which
14064 * would cause this file index entry to be displayed.
14066 TAILQ_FOREACH(pe, paths, entry) {
14067 if (got_path_cmp(path, pe->path, strlen(path),
14068 pe->path_len) == 0 ||
14069 got_path_is_child(path, pe->path, pe->path_len))
14070 pe->data = NULL; /* no error */
14073 printf(GOT_COMMIT_SEP_STR);
14074 if (S_ISLNK(mode))
14075 printf("symlink: %s\n", path);
14076 else if (S_ISREG(mode)) {
14077 printf("file: %s\n", path);
14078 printf("mode: %o\n", mode & (S_IRWXU | S_IRWXG | S_IRWXO));
14079 } else if (S_ISDIR(mode))
14080 printf("directory: %s\n", path);
14081 else
14082 printf("something: %s\n", path);
14084 tm = localtime_r(&mtime, &mytm);
14085 if (tm == NULL)
14086 return NULL;
14087 if (strftime(datebuf, sizeof(datebuf), "%c %Z", tm) == 0)
14088 return got_error(GOT_ERR_NO_SPACE);
14089 printf("timestamp: %s\n", datebuf);
14091 if (blob_id) {
14092 err = got_object_id_str(&id_str, blob_id);
14093 if (err)
14094 return err;
14095 printf("based on blob: %s\n", id_str);
14096 free(id_str);
14099 if (staged_blob_id) {
14100 err = got_object_id_str(&id_str, staged_blob_id);
14101 if (err)
14102 return err;
14103 printf("based on staged blob: %s\n", id_str);
14104 free(id_str);
14107 if (commit_id) {
14108 err = got_object_id_str(&id_str, commit_id);
14109 if (err)
14110 return err;
14111 printf("based on commit: %s\n", id_str);
14112 free(id_str);
14115 return NULL;
14118 static const struct got_error *
14119 cmd_info(int argc, char *argv[])
14121 const struct got_error *error = NULL;
14122 struct got_worktree *worktree = NULL;
14123 char *cwd = NULL, *id_str = NULL;
14124 struct got_pathlist_head paths;
14125 char *uuidstr = NULL;
14126 int ch, show_files = 0;
14128 TAILQ_INIT(&paths);
14130 #ifndef PROFILE
14131 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
14132 NULL) == -1)
14133 err(1, "pledge");
14134 #endif
14136 while ((ch = getopt(argc, argv, "")) != -1) {
14137 switch (ch) {
14138 default:
14139 usage_info();
14140 /* NOTREACHED */
14144 argc -= optind;
14145 argv += optind;
14147 cwd = getcwd(NULL, 0);
14148 if (cwd == NULL) {
14149 error = got_error_from_errno("getcwd");
14150 goto done;
14153 error = got_worktree_open(&worktree, cwd);
14154 if (error) {
14155 if (error->code == GOT_ERR_NOT_WORKTREE)
14156 error = wrap_not_worktree_error(error, "info", cwd);
14157 goto done;
14160 #ifndef PROFILE
14161 /* Remove "wpath cpath proc exec sendfd" promises. */
14162 if (pledge("stdio rpath flock unveil", NULL) == -1)
14163 err(1, "pledge");
14164 #endif
14165 error = apply_unveil(NULL, 0, got_worktree_get_root_path(worktree));
14166 if (error)
14167 goto done;
14169 if (argc >= 1) {
14170 error = get_worktree_paths_from_argv(&paths, argc, argv,
14171 worktree);
14172 if (error)
14173 goto done;
14174 show_files = 1;
14177 error = got_object_id_str(&id_str,
14178 got_worktree_get_base_commit_id(worktree));
14179 if (error)
14180 goto done;
14182 error = got_worktree_get_uuid(&uuidstr, worktree);
14183 if (error)
14184 goto done;
14186 printf("work tree: %s\n", got_worktree_get_root_path(worktree));
14187 printf("work tree base commit: %s\n", id_str);
14188 printf("work tree path prefix: %s\n",
14189 got_worktree_get_path_prefix(worktree));
14190 printf("work tree branch reference: %s\n",
14191 got_worktree_get_head_ref_name(worktree));
14192 printf("work tree UUID: %s\n", uuidstr);
14193 printf("repository: %s\n", got_worktree_get_repo_path(worktree));
14195 if (show_files) {
14196 struct got_pathlist_entry *pe;
14197 TAILQ_FOREACH(pe, &paths, entry) {
14198 if (pe->path_len == 0)
14199 continue;
14201 * Assume this path will fail. This will be corrected
14202 * in print_path_info() in case the path does suceeed.
14204 pe->data = (void *)got_error(GOT_ERR_BAD_PATH);
14206 error = got_worktree_path_info(worktree, &paths,
14207 print_path_info, &paths, check_cancelled, NULL);
14208 if (error)
14209 goto done;
14210 TAILQ_FOREACH(pe, &paths, entry) {
14211 if (pe->data != NULL) {
14212 const struct got_error *perr;
14214 perr = pe->data;
14215 error = got_error_fmt(perr->code, "%s",
14216 pe->path);
14217 break;
14221 done:
14222 if (worktree)
14223 got_worktree_close(worktree);
14224 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
14225 free(cwd);
14226 free(id_str);
14227 free(uuidstr);
14228 return error;