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"
64 #include "got_keyword.h"
66 #ifndef nitems
67 #define nitems(_a) (sizeof((_a)) / sizeof((_a)[0]))
68 #endif
70 #ifndef GOT_DEFAULT_EDITOR
71 #define GOT_DEFAULT_EDITOR "/usr/bin/vi"
72 #endif
74 static volatile sig_atomic_t sigint_received;
75 static volatile sig_atomic_t sigpipe_received;
77 static void
78 catch_sigint(int signo)
79 {
80 sigint_received = 1;
81 }
83 static void
84 catch_sigpipe(int signo)
85 {
86 sigpipe_received = 1;
87 }
90 struct got_cmd {
91 const char *cmd_name;
92 const struct got_error *(*cmd_main)(int, char *[]);
93 void (*cmd_usage)(void);
94 const char *cmd_alias;
95 };
97 __dead static void usage(int, int);
98 __dead static void usage_import(void);
99 __dead static void usage_clone(void);
100 __dead static void usage_fetch(void);
101 __dead static void usage_checkout(void);
102 __dead static void usage_update(void);
103 __dead static void usage_log(void);
104 __dead static void usage_diff(void);
105 __dead static void usage_blame(void);
106 __dead static void usage_tree(void);
107 __dead static void usage_status(void);
108 __dead static void usage_ref(void);
109 __dead static void usage_branch(void);
110 __dead static void usage_tag(void);
111 __dead static void usage_add(void);
112 __dead static void usage_remove(void);
113 __dead static void usage_patch(void);
114 __dead static void usage_revert(void);
115 __dead static void usage_commit(void);
116 __dead static void usage_send(void);
117 __dead static void usage_cherrypick(void);
118 __dead static void usage_backout(void);
119 __dead static void usage_rebase(void);
120 __dead static void usage_histedit(void);
121 __dead static void usage_integrate(void);
122 __dead static void usage_merge(void);
123 __dead static void usage_stage(void);
124 __dead static void usage_unstage(void);
125 __dead static void usage_cat(void);
126 __dead static void usage_info(void);
128 static const struct got_error* cmd_import(int, char *[]);
129 static const struct got_error* cmd_clone(int, char *[]);
130 static const struct got_error* cmd_fetch(int, char *[]);
131 static const struct got_error* cmd_checkout(int, char *[]);
132 static const struct got_error* cmd_update(int, char *[]);
133 static const struct got_error* cmd_log(int, char *[]);
134 static const struct got_error* cmd_diff(int, char *[]);
135 static const struct got_error* cmd_blame(int, char *[]);
136 static const struct got_error* cmd_tree(int, char *[]);
137 static const struct got_error* cmd_status(int, char *[]);
138 static const struct got_error* cmd_ref(int, char *[]);
139 static const struct got_error* cmd_branch(int, char *[]);
140 static const struct got_error* cmd_tag(int, char *[]);
141 static const struct got_error* cmd_add(int, char *[]);
142 static const struct got_error* cmd_remove(int, char *[]);
143 static const struct got_error* cmd_patch(int, char *[]);
144 static const struct got_error* cmd_revert(int, char *[]);
145 static const struct got_error* cmd_commit(int, char *[]);
146 static const struct got_error* cmd_send(int, char *[]);
147 static const struct got_error* cmd_cherrypick(int, char *[]);
148 static const struct got_error* cmd_backout(int, char *[]);
149 static const struct got_error* cmd_rebase(int, char *[]);
150 static const struct got_error* cmd_histedit(int, char *[]);
151 static const struct got_error* cmd_integrate(int, char *[]);
152 static const struct got_error* cmd_merge(int, char *[]);
153 static const struct got_error* cmd_stage(int, char *[]);
154 static const struct got_error* cmd_unstage(int, char *[]);
155 static const struct got_error* cmd_cat(int, char *[]);
156 static const struct got_error* cmd_info(int, char *[]);
158 static const struct got_cmd got_commands[] = {
159 { "import", cmd_import, usage_import, "im" },
160 { "clone", cmd_clone, usage_clone, "cl" },
161 { "fetch", cmd_fetch, usage_fetch, "fe" },
162 { "checkout", cmd_checkout, usage_checkout, "co" },
163 { "update", cmd_update, usage_update, "up" },
164 { "log", cmd_log, usage_log, "" },
165 { "diff", cmd_diff, usage_diff, "di" },
166 { "blame", cmd_blame, usage_blame, "bl" },
167 { "tree", cmd_tree, usage_tree, "tr" },
168 { "status", cmd_status, usage_status, "st" },
169 { "ref", cmd_ref, usage_ref, "" },
170 { "branch", cmd_branch, usage_branch, "br" },
171 { "tag", cmd_tag, usage_tag, "" },
172 { "add", cmd_add, usage_add, "" },
173 { "remove", cmd_remove, usage_remove, "rm" },
174 { "patch", cmd_patch, usage_patch, "pa" },
175 { "revert", cmd_revert, usage_revert, "rv" },
176 { "commit", cmd_commit, usage_commit, "ci" },
177 { "send", cmd_send, usage_send, "se" },
178 { "cherrypick", cmd_cherrypick, usage_cherrypick, "cy" },
179 { "backout", cmd_backout, usage_backout, "bo" },
180 { "rebase", cmd_rebase, usage_rebase, "rb" },
181 { "histedit", cmd_histedit, usage_histedit, "he" },
182 { "integrate", cmd_integrate, usage_integrate,"ig" },
183 { "merge", cmd_merge, usage_merge, "mg" },
184 { "stage", cmd_stage, usage_stage, "sg" },
185 { "unstage", cmd_unstage, usage_unstage, "ug" },
186 { "cat", cmd_cat, usage_cat, "" },
187 { "info", cmd_info, usage_info, "" },
188 };
190 static void
191 list_commands(FILE *fp)
193 size_t i;
195 fprintf(fp, "commands:");
196 for (i = 0; i < nitems(got_commands); i++) {
197 const struct got_cmd *cmd = &got_commands[i];
198 fprintf(fp, " %s", cmd->cmd_name);
200 fputc('\n', fp);
203 __dead static void
204 option_conflict(char a, char b)
206 errx(1, "-%c and -%c options are mutually exclusive", a, b);
209 int
210 main(int argc, char *argv[])
212 const struct got_cmd *cmd;
213 size_t i;
214 int ch;
215 int hflag = 0, Vflag = 0;
216 static const struct option longopts[] = {
217 { "version", no_argument, NULL, 'V' },
218 { NULL, 0, NULL, 0 }
219 };
221 setlocale(LC_CTYPE, "");
223 while ((ch = getopt_long(argc, argv, "+hV", longopts, NULL)) != -1) {
224 switch (ch) {
225 case 'h':
226 hflag = 1;
227 break;
228 case 'V':
229 Vflag = 1;
230 break;
231 default:
232 usage(hflag, 1);
233 /* NOTREACHED */
237 argc -= optind;
238 argv += optind;
239 optind = 1;
240 optreset = 1;
242 if (Vflag) {
243 got_version_print_str();
244 return 0;
247 if (argc <= 0)
248 usage(hflag, hflag ? 0 : 1);
250 signal(SIGINT, catch_sigint);
251 signal(SIGPIPE, catch_sigpipe);
253 for (i = 0; i < nitems(got_commands); i++) {
254 const struct got_error *error;
256 cmd = &got_commands[i];
258 if (strcmp(cmd->cmd_name, argv[0]) != 0 &&
259 strcmp(cmd->cmd_alias, argv[0]) != 0)
260 continue;
262 if (hflag)
263 cmd->cmd_usage();
265 error = cmd->cmd_main(argc, argv);
266 if (error && error->code != GOT_ERR_CANCELLED &&
267 error->code != GOT_ERR_PRIVSEP_EXIT &&
268 !(sigpipe_received &&
269 error->code == GOT_ERR_ERRNO && errno == EPIPE) &&
270 !(sigint_received &&
271 error->code == GOT_ERR_ERRNO && errno == EINTR)) {
272 fflush(stdout);
273 fprintf(stderr, "%s: %s\n", getprogname(), error->msg);
274 return 1;
277 return 0;
280 fprintf(stderr, "%s: unknown command '%s'\n", getprogname(), argv[0]);
281 list_commands(stderr);
282 return 1;
285 __dead static void
286 usage(int hflag, int status)
288 FILE *fp = (status == 0) ? stdout : stderr;
290 fprintf(fp, "usage: %s [-hV] command [arg ...]\n",
291 getprogname());
292 if (hflag)
293 list_commands(fp);
294 exit(status);
297 static const struct got_error *
298 get_editor(char **abspath)
300 const struct got_error *err = NULL;
301 const char *editor;
303 *abspath = NULL;
305 editor = getenv("VISUAL");
306 if (editor == NULL)
307 editor = getenv("EDITOR");
309 if (editor) {
310 err = got_path_find_prog(abspath, editor);
311 if (err)
312 return err;
315 if (*abspath == NULL) {
316 *abspath = strdup(GOT_DEFAULT_EDITOR);
317 if (*abspath == NULL)
318 return got_error_from_errno("strdup");
321 return NULL;
324 static const struct got_error *
325 apply_unveil(const char *repo_path, int repo_read_only,
326 const char *worktree_path)
328 const struct got_error *err;
330 #ifdef PROFILE
331 if (unveil("gmon.out", "rwc") != 0)
332 return got_error_from_errno2("unveil", "gmon.out");
333 #endif
334 if (repo_path && unveil(repo_path, repo_read_only ? "r" : "rwc") != 0)
335 return got_error_from_errno2("unveil", repo_path);
337 if (worktree_path && unveil(worktree_path, "rwc") != 0)
338 return got_error_from_errno2("unveil", worktree_path);
340 if (unveil(GOT_TMPDIR_STR, "rwc") != 0)
341 return got_error_from_errno2("unveil", GOT_TMPDIR_STR);
343 err = got_privsep_unveil_exec_helpers();
344 if (err != NULL)
345 return err;
347 if (unveil(NULL, NULL) != 0)
348 return got_error_from_errno("unveil");
350 return NULL;
353 __dead static void
354 usage_import(void)
356 fprintf(stderr, "usage: %s import [-b branch] [-I pattern] [-m message] "
357 "[-r repository-path] directory\n", getprogname());
358 exit(1);
361 static int
362 spawn_editor(const char *editor, const char *file)
364 pid_t pid;
365 sig_t sighup, sigint, sigquit;
366 int st = -1;
368 sighup = signal(SIGHUP, SIG_IGN);
369 sigint = signal(SIGINT, SIG_IGN);
370 sigquit = signal(SIGQUIT, SIG_IGN);
372 switch (pid = fork()) {
373 case -1:
374 goto doneediting;
375 case 0:
376 execl(editor, editor, file, (char *)NULL);
377 _exit(127);
380 while (waitpid(pid, &st, 0) == -1)
381 if (errno != EINTR)
382 break;
384 doneediting:
385 (void)signal(SIGHUP, sighup);
386 (void)signal(SIGINT, sigint);
387 (void)signal(SIGQUIT, sigquit);
389 if (!WIFEXITED(st)) {
390 errno = EINTR;
391 return -1;
394 return WEXITSTATUS(st);
397 static const struct got_error *
398 read_logmsg(char **logmsg, size_t *len, FILE *fp, size_t filesize)
400 const struct got_error *err = NULL;
401 char *line = NULL;
402 size_t linesize = 0;
404 *logmsg = NULL;
405 *len = 0;
407 if (fseeko(fp, 0L, SEEK_SET) == -1)
408 return got_error_from_errno("fseeko");
410 *logmsg = malloc(filesize + 1);
411 if (*logmsg == NULL)
412 return got_error_from_errno("malloc");
413 (*logmsg)[0] = '\0';
415 while (getline(&line, &linesize, fp) != -1) {
416 if (line[0] == '#' || (*len == 0 && line[0] == '\n'))
417 continue; /* remove comments and leading empty lines */
418 *len = strlcat(*logmsg, line, filesize + 1);
419 if (*len >= filesize + 1) {
420 err = got_error(GOT_ERR_NO_SPACE);
421 goto done;
424 if (ferror(fp)) {
425 err = got_ferror(fp, GOT_ERR_IO);
426 goto done;
429 while (*len > 0 && (*logmsg)[*len - 1] == '\n') {
430 (*logmsg)[*len - 1] = '\0';
431 (*len)--;
433 done:
434 free(line);
435 if (err) {
436 free(*logmsg);
437 *logmsg = NULL;
438 *len = 0;
440 return err;
443 static const struct got_error *
444 edit_logmsg(char **logmsg, const char *editor, const char *logmsg_path,
445 const char *initial_content, size_t initial_content_len,
446 int require_modification)
448 const struct got_error *err = NULL;
449 struct stat st, st2;
450 FILE *fp = NULL;
451 size_t logmsg_len;
453 *logmsg = NULL;
455 if (stat(logmsg_path, &st) == -1)
456 return got_error_from_errno2("stat", logmsg_path);
458 if (spawn_editor(editor, logmsg_path) == -1)
459 return got_error_from_errno("failed spawning editor");
461 if (require_modification) {
462 struct timespec timeout;
464 timeout.tv_sec = 0;
465 timeout.tv_nsec = 1;
466 nanosleep(&timeout, NULL);
469 if (stat(logmsg_path, &st2) == -1)
470 return got_error_from_errno2("stat", logmsg_path);
472 if (require_modification && st.st_size == st2.st_size &&
473 timespeccmp(&st.st_mtim, &st2.st_mtim, ==))
474 return got_error_msg(GOT_ERR_COMMIT_MSG_EMPTY,
475 "no changes made to commit message, aborting");
477 fp = fopen(logmsg_path, "re");
478 if (fp == NULL) {
479 err = got_error_from_errno("fopen");
480 goto done;
483 /* strip comments and leading/trailing newlines */
484 err = read_logmsg(logmsg, &logmsg_len, fp, st2.st_size);
485 if (err)
486 goto done;
487 if (logmsg_len == 0) {
488 err = got_error_msg(GOT_ERR_COMMIT_MSG_EMPTY,
489 "commit message cannot be empty, aborting");
490 goto done;
492 done:
493 if (fp && fclose(fp) == EOF && err == NULL)
494 err = got_error_from_errno("fclose");
495 if (err) {
496 free(*logmsg);
497 *logmsg = NULL;
499 return err;
502 static const struct got_error *
503 collect_import_msg(char **logmsg, char **logmsg_path, const char *editor,
504 const char *path_dir, const char *branch_name)
506 char *initial_content = NULL;
507 const struct got_error *err = NULL;
508 int initial_content_len;
509 int fd = -1;
511 initial_content_len = asprintf(&initial_content,
512 "\n# %s to be imported to branch %s\n", path_dir,
513 branch_name);
514 if (initial_content_len == -1)
515 return got_error_from_errno("asprintf");
517 err = got_opentemp_named_fd(logmsg_path, &fd,
518 GOT_TMPDIR_STR "/got-importmsg", "");
519 if (err)
520 goto done;
522 if (write(fd, initial_content, initial_content_len) == -1) {
523 err = got_error_from_errno2("write", *logmsg_path);
524 goto done;
526 if (close(fd) == -1) {
527 err = got_error_from_errno2("close", *logmsg_path);
528 goto done;
530 fd = -1;
532 err = edit_logmsg(logmsg, editor, *logmsg_path, initial_content,
533 initial_content_len, 1);
534 done:
535 if (fd != -1 && close(fd) == -1 && err == NULL)
536 err = got_error_from_errno2("close", *logmsg_path);
537 free(initial_content);
538 if (err) {
539 free(*logmsg_path);
540 *logmsg_path = NULL;
542 return err;
545 static const struct got_error *
546 import_progress(void *arg, const char *path)
548 printf("A %s\n", path);
549 return NULL;
552 static const struct got_error *
553 valid_author(const char *author)
555 const char *email = author;
557 /*
558 * Git' expects the author (or committer) to be in the form
559 * "name <email>", which are mostly free form (see the
560 * "committer" description in git-fast-import(1)). We're only
561 * doing this to avoid git's object parser breaking on commits
562 * we create.
563 */
565 while (*author && *author != '\n' && *author != '<' && *author != '>')
566 author++;
567 if (author != email && *author == '<' && *(author - 1) != ' ')
568 return got_error_fmt(GOT_ERR_COMMIT_BAD_AUTHOR, "%s: space "
569 "between author name and email required", email);
570 if (*author++ != '<')
571 return got_error_fmt(GOT_ERR_COMMIT_NO_EMAIL, "%s", email);
572 while (*author && *author != '\n' && *author != '<' && *author != '>')
573 author++;
574 if (strcmp(author, ">") != 0)
575 return got_error_fmt(GOT_ERR_COMMIT_NO_EMAIL, "%s", email);
576 return NULL;
579 static const struct got_error *
580 get_author(char **author, struct got_repository *repo,
581 struct got_worktree *worktree)
583 const struct got_error *err = NULL;
584 const char *got_author = NULL, *name, *email;
585 const struct got_gotconfig *worktree_conf = NULL, *repo_conf = NULL;
587 *author = NULL;
589 if (worktree)
590 worktree_conf = got_worktree_get_gotconfig(worktree);
591 repo_conf = got_repo_get_gotconfig(repo);
593 /*
594 * Priority of potential author information sources, from most
595 * significant to least significant:
596 * 1) work tree's .got/got.conf file
597 * 2) repository's got.conf file
598 * 3) repository's git config file
599 * 4) environment variables
600 * 5) global git config files (in user's home directory or /etc)
601 */
603 if (worktree_conf)
604 got_author = got_gotconfig_get_author(worktree_conf);
605 if (got_author == NULL)
606 got_author = got_gotconfig_get_author(repo_conf);
607 if (got_author == NULL) {
608 name = got_repo_get_gitconfig_author_name(repo);
609 email = got_repo_get_gitconfig_author_email(repo);
610 if (name && email) {
611 if (asprintf(author, "%s <%s>", name, email) == -1)
612 return got_error_from_errno("asprintf");
613 return NULL;
616 got_author = getenv("GOT_AUTHOR");
617 if (got_author == NULL) {
618 name = got_repo_get_global_gitconfig_author_name(repo);
619 email = got_repo_get_global_gitconfig_author_email(
620 repo);
621 if (name && email) {
622 if (asprintf(author, "%s <%s>", name, email)
623 == -1)
624 return got_error_from_errno("asprintf");
625 return NULL;
627 /* TODO: Look up user in password database? */
628 return got_error(GOT_ERR_COMMIT_NO_AUTHOR);
632 *author = strdup(got_author);
633 if (*author == NULL)
634 return got_error_from_errno("strdup");
636 err = valid_author(*author);
637 if (err) {
638 free(*author);
639 *author = NULL;
641 return err;
644 static const struct got_error *
645 get_allowed_signers(char **allowed_signers, struct got_repository *repo,
646 struct got_worktree *worktree)
648 const char *got_allowed_signers = NULL;
649 const struct got_gotconfig *worktree_conf = NULL, *repo_conf = NULL;
651 *allowed_signers = NULL;
653 if (worktree)
654 worktree_conf = got_worktree_get_gotconfig(worktree);
655 repo_conf = got_repo_get_gotconfig(repo);
657 /*
658 * Priority of potential author information sources, from most
659 * significant to least significant:
660 * 1) work tree's .got/got.conf file
661 * 2) repository's got.conf file
662 */
664 if (worktree_conf)
665 got_allowed_signers = got_gotconfig_get_allowed_signers_file(
666 worktree_conf);
667 if (got_allowed_signers == NULL)
668 got_allowed_signers = got_gotconfig_get_allowed_signers_file(
669 repo_conf);
671 if (got_allowed_signers) {
672 *allowed_signers = strdup(got_allowed_signers);
673 if (*allowed_signers == NULL)
674 return got_error_from_errno("strdup");
676 return NULL;
679 static const struct got_error *
680 get_revoked_signers(char **revoked_signers, struct got_repository *repo,
681 struct got_worktree *worktree)
683 const char *got_revoked_signers = NULL;
684 const struct got_gotconfig *worktree_conf = NULL, *repo_conf = NULL;
686 *revoked_signers = NULL;
688 if (worktree)
689 worktree_conf = got_worktree_get_gotconfig(worktree);
690 repo_conf = got_repo_get_gotconfig(repo);
692 /*
693 * Priority of potential author information sources, from most
694 * significant to least significant:
695 * 1) work tree's .got/got.conf file
696 * 2) repository's got.conf file
697 */
699 if (worktree_conf)
700 got_revoked_signers = got_gotconfig_get_revoked_signers_file(
701 worktree_conf);
702 if (got_revoked_signers == NULL)
703 got_revoked_signers = got_gotconfig_get_revoked_signers_file(
704 repo_conf);
706 if (got_revoked_signers) {
707 *revoked_signers = strdup(got_revoked_signers);
708 if (*revoked_signers == NULL)
709 return got_error_from_errno("strdup");
711 return NULL;
714 static const char *
715 get_signer_id(struct got_repository *repo, struct got_worktree *worktree)
717 const char *got_signer_id = NULL;
718 const struct got_gotconfig *worktree_conf = NULL, *repo_conf = NULL;
720 if (worktree)
721 worktree_conf = got_worktree_get_gotconfig(worktree);
722 repo_conf = got_repo_get_gotconfig(repo);
724 /*
725 * Priority of potential author information sources, from most
726 * significant to least significant:
727 * 1) work tree's .got/got.conf file
728 * 2) repository's got.conf file
729 */
731 if (worktree_conf)
732 got_signer_id = got_gotconfig_get_signer_id(worktree_conf);
733 if (got_signer_id == NULL)
734 got_signer_id = got_gotconfig_get_signer_id(repo_conf);
736 return got_signer_id;
739 static const struct got_error *
740 get_gitconfig_path(char **gitconfig_path)
742 const char *homedir = getenv("HOME");
744 *gitconfig_path = NULL;
745 if (homedir) {
746 if (asprintf(gitconfig_path, "%s/.gitconfig", homedir) == -1)
747 return got_error_from_errno("asprintf");
750 return NULL;
753 static const struct got_error *
754 cmd_import(int argc, char *argv[])
756 const struct got_error *error = NULL;
757 char *path_dir = NULL, *repo_path = NULL, *logmsg = NULL;
758 char *gitconfig_path = NULL, *editor = NULL, *author = NULL;
759 const char *branch_name = NULL;
760 char *id_str = NULL, *logmsg_path = NULL;
761 char refname[PATH_MAX] = "refs/heads/";
762 struct got_repository *repo = NULL;
763 struct got_reference *branch_ref = NULL, *head_ref = NULL;
764 struct got_object_id *new_commit_id = NULL;
765 int ch, n = 0;
766 struct got_pathlist_head ignores;
767 struct got_pathlist_entry *pe;
768 int preserve_logmsg = 0;
769 int *pack_fds = NULL;
771 TAILQ_INIT(&ignores);
773 #ifndef PROFILE
774 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
775 "unveil",
776 NULL) == -1)
777 err(1, "pledge");
778 #endif
780 while ((ch = getopt(argc, argv, "b:I:m:r:")) != -1) {
781 switch (ch) {
782 case 'b':
783 branch_name = optarg;
784 break;
785 case 'I':
786 if (optarg[0] == '\0')
787 break;
788 error = got_pathlist_insert(&pe, &ignores, optarg,
789 NULL);
790 if (error)
791 goto done;
792 break;
793 case 'm':
794 logmsg = strdup(optarg);
795 if (logmsg == NULL) {
796 error = got_error_from_errno("strdup");
797 goto done;
799 break;
800 case 'r':
801 repo_path = realpath(optarg, NULL);
802 if (repo_path == NULL) {
803 error = got_error_from_errno2("realpath",
804 optarg);
805 goto done;
807 break;
808 default:
809 usage_import();
810 /* NOTREACHED */
814 argc -= optind;
815 argv += optind;
817 if (argc != 1)
818 usage_import();
820 if (repo_path == NULL) {
821 repo_path = getcwd(NULL, 0);
822 if (repo_path == NULL)
823 return got_error_from_errno("getcwd");
825 got_path_strip_trailing_slashes(repo_path);
826 error = get_gitconfig_path(&gitconfig_path);
827 if (error)
828 goto done;
829 error = got_repo_pack_fds_open(&pack_fds);
830 if (error != NULL)
831 goto done;
832 error = got_repo_open(&repo, repo_path, gitconfig_path, pack_fds);
833 if (error)
834 goto done;
836 path_dir = realpath(argv[0], NULL);
837 if (path_dir == NULL) {
838 error = got_error_from_errno2("realpath", argv[0]);
839 goto done;
841 got_path_strip_trailing_slashes(path_dir);
843 error = get_editor(&editor);
844 if (error)
845 goto done;
847 if (unveil(path_dir, "r") != 0) {
848 error = got_error_from_errno2("unveil", path_dir);
849 goto done;
851 if (unveil(editor, "x") != 0) {
852 error = got_error_from_errno2("unveil", editor);
853 goto done;
855 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
856 if (error)
857 goto done;
859 error = get_author(&author, repo, NULL);
860 if (error)
861 return error;
863 /*
864 * Don't let the user create a branch name with a leading '-'.
865 * While technically a valid reference name, this case is usually
866 * an unintended typo.
867 */
868 if (branch_name && branch_name[0] == '-')
869 return got_error_path(branch_name, GOT_ERR_REF_NAME_MINUS);
871 error = got_ref_open(&head_ref, repo, GOT_REF_HEAD, 0);
872 if (error && error->code != GOT_ERR_NOT_REF)
873 goto done;
875 if (branch_name)
876 n = strlcat(refname, branch_name, sizeof(refname));
877 else if (head_ref && got_ref_is_symbolic(head_ref))
878 n = strlcpy(refname, got_ref_get_symref_target(head_ref),
879 sizeof(refname));
880 else
881 n = strlcat(refname, "main", sizeof(refname));
882 if (n >= sizeof(refname)) {
883 error = got_error(GOT_ERR_NO_SPACE);
884 goto done;
887 error = got_ref_open(&branch_ref, repo, refname, 0);
888 if (error) {
889 if (error->code != GOT_ERR_NOT_REF)
890 goto done;
891 } else {
892 error = got_error_msg(GOT_ERR_BRANCH_EXISTS,
893 "import target branch already exists");
894 goto done;
897 if (logmsg == NULL || *logmsg == '\0') {
898 free(logmsg);
899 error = collect_import_msg(&logmsg, &logmsg_path, editor,
900 path_dir, refname);
901 if (error) {
902 if (error->code != GOT_ERR_COMMIT_MSG_EMPTY &&
903 logmsg_path != NULL)
904 preserve_logmsg = 1;
905 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;
2290 struct got_remote_repo *remote = NULL;
2291 int nremotes;
2292 char *id_str = NULL;
2293 struct got_repository *repo = NULL;
2294 struct got_worktree *worktree = NULL;
2295 const struct got_gotconfig *repo_conf = NULL, *worktree_conf = NULL;
2296 struct got_pathlist_head refs, symrefs, wanted_branches, wanted_refs;
2297 char *head_refname = NULL;
2298 struct got_pathlist_entry *pe;
2299 struct got_reflist_head remote_refs;
2300 struct got_reflist_entry *re;
2301 struct got_object_id *pack_hash = NULL;
2302 int i, ch, fetchfd = -1, fetchstatus;
2303 pid_t fetchpid = -1;
2304 struct got_fetch_progress_arg fpa;
2305 int verbosity = 0, fetch_all_branches = 0, list_refs_only = 0;
2306 int delete_refs = 0, replace_tags = 0, delete_remote = 0;
2307 int *pack_fds = NULL, have_bflag = 0;
2308 const char *remote_head = NULL, *worktree_branch = NULL;
2310 TAILQ_INIT(&refs);
2311 TAILQ_INIT(&symrefs);
2312 TAILQ_INIT(&remote_refs);
2313 TAILQ_INIT(&wanted_branches);
2314 TAILQ_INIT(&wanted_refs);
2316 while ((ch = getopt(argc, argv, "ab:dlqR:r:tvX")) != -1) {
2317 switch (ch) {
2318 case 'a':
2319 fetch_all_branches = 1;
2320 break;
2321 case 'b':
2322 error = got_pathlist_append(&wanted_branches,
2323 optarg, NULL);
2324 if (error)
2325 return error;
2326 have_bflag = 1;
2327 break;
2328 case 'd':
2329 delete_refs = 1;
2330 break;
2331 case 'l':
2332 list_refs_only = 1;
2333 break;
2334 case 'q':
2335 verbosity = -1;
2336 break;
2337 case 'R':
2338 error = got_pathlist_append(&wanted_refs,
2339 optarg, NULL);
2340 if (error)
2341 return error;
2342 break;
2343 case 'r':
2344 repo_path = realpath(optarg, NULL);
2345 if (repo_path == NULL)
2346 return got_error_from_errno2("realpath",
2347 optarg);
2348 got_path_strip_trailing_slashes(repo_path);
2349 break;
2350 case 't':
2351 replace_tags = 1;
2352 break;
2353 case 'v':
2354 if (verbosity < 0)
2355 verbosity = 0;
2356 else if (verbosity < 3)
2357 verbosity++;
2358 break;
2359 case 'X':
2360 delete_remote = 1;
2361 break;
2362 default:
2363 usage_fetch();
2364 break;
2367 argc -= optind;
2368 argv += optind;
2370 if (fetch_all_branches && !TAILQ_EMPTY(&wanted_branches))
2371 option_conflict('a', 'b');
2372 if (list_refs_only) {
2373 if (!TAILQ_EMPTY(&wanted_branches))
2374 option_conflict('l', 'b');
2375 if (fetch_all_branches)
2376 option_conflict('l', 'a');
2377 if (delete_refs)
2378 option_conflict('l', 'd');
2379 if (delete_remote)
2380 option_conflict('l', 'X');
2382 if (delete_remote) {
2383 if (fetch_all_branches)
2384 option_conflict('X', 'a');
2385 if (!TAILQ_EMPTY(&wanted_branches))
2386 option_conflict('X', 'b');
2387 if (delete_refs)
2388 option_conflict('X', 'd');
2389 if (replace_tags)
2390 option_conflict('X', 't');
2391 if (!TAILQ_EMPTY(&wanted_refs))
2392 option_conflict('X', 'R');
2395 if (argc == 0) {
2396 if (delete_remote)
2397 errx(1, "-X option requires a remote name");
2398 remote_name = GOT_FETCH_DEFAULT_REMOTE_NAME;
2399 } else if (argc == 1)
2400 remote_name = argv[0];
2401 else
2402 usage_fetch();
2404 cwd = getcwd(NULL, 0);
2405 if (cwd == NULL) {
2406 error = got_error_from_errno("getcwd");
2407 goto done;
2410 error = got_repo_pack_fds_open(&pack_fds);
2411 if (error != NULL)
2412 goto done;
2414 if (repo_path == NULL) {
2415 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
2416 if (error && error->code != GOT_ERR_NOT_WORKTREE)
2417 goto done;
2418 else
2419 error = NULL;
2420 if (worktree) {
2421 repo_path =
2422 strdup(got_worktree_get_repo_path(worktree));
2423 if (repo_path == NULL)
2424 error = got_error_from_errno("strdup");
2425 if (error)
2426 goto done;
2427 } else {
2428 repo_path = strdup(cwd);
2429 if (repo_path == NULL) {
2430 error = got_error_from_errno("strdup");
2431 goto done;
2436 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
2437 if (error)
2438 goto done;
2440 if (delete_remote) {
2441 error = delete_refs_for_remote(repo, remote_name);
2442 goto done; /* nothing else to do */
2445 if (worktree) {
2446 worktree_conf = got_worktree_get_gotconfig(worktree);
2447 if (worktree_conf) {
2448 got_gotconfig_get_remotes(&nremotes, &remotes,
2449 worktree_conf);
2450 for (i = 0; i < nremotes; i++) {
2451 if (strcmp(remotes[i].name, remote_name) == 0) {
2452 error = got_repo_remote_repo_dup(&remote,
2453 &remotes[i]);
2454 if (error)
2455 goto done;
2456 break;
2461 if (remote == NULL) {
2462 repo_conf = got_repo_get_gotconfig(repo);
2463 if (repo_conf) {
2464 got_gotconfig_get_remotes(&nremotes, &remotes,
2465 repo_conf);
2466 for (i = 0; i < nremotes; i++) {
2467 if (strcmp(remotes[i].name, remote_name) == 0) {
2468 error = got_repo_remote_repo_dup(&remote,
2469 &remotes[i]);
2470 if (error)
2471 goto done;
2472 break;
2477 if (remote == NULL) {
2478 got_repo_get_gitconfig_remotes(&nremotes, &remotes, repo);
2479 for (i = 0; i < nremotes; i++) {
2480 if (strcmp(remotes[i].name, remote_name) == 0) {
2481 error = got_repo_remote_repo_dup(&remote,
2482 &remotes[i]);
2483 if (error)
2484 goto done;
2485 break;
2489 if (remote == NULL) {
2490 error = got_error_path(remote_name, GOT_ERR_NO_REMOTE);
2491 goto done;
2494 if (TAILQ_EMPTY(&wanted_branches)) {
2495 if (!fetch_all_branches)
2496 fetch_all_branches = remote->fetch_all_branches;
2497 for (i = 0; i < remote->nfetch_branches; i++) {
2498 error = got_pathlist_append(&wanted_branches,
2499 remote->fetch_branches[i], NULL);
2500 if (error)
2501 goto done;
2504 if (TAILQ_EMPTY(&wanted_refs)) {
2505 for (i = 0; i < remote->nfetch_refs; i++) {
2506 error = got_pathlist_append(&wanted_refs,
2507 remote->fetch_refs[i], NULL);
2508 if (error)
2509 goto done;
2513 error = got_dial_parse_uri(&proto, &host, &port, &server_path,
2514 &repo_name, remote->fetch_url);
2515 if (error)
2516 goto done;
2518 if (strcmp(proto, "git") == 0) {
2519 #ifndef PROFILE
2520 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
2521 "sendfd dns inet unveil", NULL) == -1)
2522 err(1, "pledge");
2523 #endif
2524 } else if (strcmp(proto, "git+ssh") == 0 ||
2525 strcmp(proto, "ssh") == 0) {
2526 #ifndef PROFILE
2527 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
2528 "sendfd unveil", NULL) == -1)
2529 err(1, "pledge");
2530 #endif
2531 } else if (strcmp(proto, "http") == 0 ||
2532 strcmp(proto, "git+http") == 0) {
2533 error = got_error_path(proto, GOT_ERR_NOT_IMPL);
2534 goto done;
2535 } else {
2536 error = got_error_path(proto, GOT_ERR_BAD_PROTO);
2537 goto done;
2540 error = got_dial_apply_unveil(proto);
2541 if (error)
2542 goto done;
2544 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
2545 if (error)
2546 goto done;
2548 if (worktree) {
2549 head_refname = strdup(got_worktree_get_head_ref_name(worktree));
2550 if (head_refname == NULL) {
2551 error = got_error_from_errno("strdup");
2552 goto done;
2555 /* Release work tree lock. */
2556 got_worktree_close(worktree);
2557 worktree = NULL;
2560 if (verbosity >= 0) {
2561 printf("Connecting to \"%s\" %s://%s%s%s%s%s\n",
2562 remote->name, proto, host,
2563 port ? ":" : "", port ? port : "",
2564 *server_path == '/' ? "" : "/", server_path);
2567 error = got_fetch_connect(&fetchpid, &fetchfd, proto, host, port,
2568 server_path, verbosity);
2569 if (error)
2570 goto done;
2572 if (!have_bflag) {
2574 * If set, get this remote's HEAD ref target so
2575 * if it has changed on the server we can fetch it.
2577 error = got_ref_list(&remote_refs, repo, "refs/remotes",
2578 got_ref_cmp_by_name, repo);
2579 if (error)
2580 goto done;
2582 TAILQ_FOREACH(re, &remote_refs, entry) {
2583 const char *remote_refname, *remote_target;
2584 size_t remote_name_len;
2586 if (!got_ref_is_symbolic(re->ref))
2587 continue;
2589 remote_name_len = strlen(remote->name);
2590 remote_refname = got_ref_get_name(re->ref);
2592 /* we only want refs/remotes/$remote->name/HEAD */
2593 if (strncmp(remote_refname + 13, remote->name,
2594 remote_name_len) != 0)
2595 continue;
2597 if (strcmp(remote_refname + remote_name_len + 14,
2598 GOT_REF_HEAD) != 0)
2599 continue;
2602 * Take the name itself because we already
2603 * only match with refs/heads/ in fetch_pack().
2605 remote_target = got_ref_get_symref_target(re->ref);
2606 remote_head = remote_target + remote_name_len + 14;
2607 break;
2610 if (head_refname &&
2611 strncmp(head_refname, "refs/heads/", 11) == 0)
2612 worktree_branch = head_refname;
2615 fpa.last_scaled_size[0] = '\0';
2616 fpa.last_p_indexed = -1;
2617 fpa.last_p_resolved = -1;
2618 fpa.verbosity = verbosity;
2619 fpa.repo = repo;
2620 fpa.create_configs = 0;
2621 fpa.configs_created = 0;
2622 memset(&fpa.config_info, 0, sizeof(fpa.config_info));
2624 error = got_fetch_pack(&pack_hash, &refs, &symrefs, remote->name,
2625 remote->mirror_references, fetch_all_branches, &wanted_branches,
2626 &wanted_refs, list_refs_only, verbosity, fetchfd, repo,
2627 worktree_branch, remote_head, have_bflag, fetch_progress, &fpa);
2628 if (error)
2629 goto done;
2631 if (list_refs_only) {
2632 error = list_remote_refs(&symrefs, &refs);
2633 goto done;
2636 if (pack_hash == NULL) {
2637 if (verbosity >= 0)
2638 printf("Already up-to-date\n");
2639 } else if (verbosity >= 0) {
2640 error = got_object_id_str(&id_str, pack_hash);
2641 if (error)
2642 goto done;
2643 printf("\nFetched %s.pack\n", id_str);
2644 free(id_str);
2645 id_str = NULL;
2648 /* Update references provided with the pack file. */
2649 TAILQ_FOREACH(pe, &refs, entry) {
2650 const char *refname = pe->path;
2651 struct got_object_id *id = pe->data;
2652 struct got_reference *ref;
2653 char *remote_refname;
2655 if (is_wanted_ref(&wanted_refs, refname) &&
2656 !remote->mirror_references) {
2657 error = update_wanted_ref(refname, id,
2658 remote->name, verbosity, repo);
2659 if (error)
2660 goto done;
2661 continue;
2664 if (remote->mirror_references ||
2665 strncmp("refs/tags/", refname, 10) == 0) {
2666 error = got_ref_open(&ref, repo, refname, 1);
2667 if (error) {
2668 if (error->code != GOT_ERR_NOT_REF)
2669 goto done;
2670 error = create_ref(refname, id, verbosity,
2671 repo);
2672 if (error)
2673 goto done;
2674 } else {
2675 error = update_ref(ref, id, replace_tags,
2676 verbosity, repo);
2677 unlock_err = got_ref_unlock(ref);
2678 if (unlock_err && error == NULL)
2679 error = unlock_err;
2680 got_ref_close(ref);
2681 if (error)
2682 goto done;
2684 } else if (strncmp("refs/heads/", refname, 11) == 0) {
2685 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
2686 remote_name, refname + 11) == -1) {
2687 error = got_error_from_errno("asprintf");
2688 goto done;
2691 error = got_ref_open(&ref, repo, remote_refname, 1);
2692 if (error) {
2693 if (error->code != GOT_ERR_NOT_REF)
2694 goto done;
2695 error = create_ref(remote_refname, id,
2696 verbosity, repo);
2697 if (error)
2698 goto done;
2699 } else {
2700 error = update_ref(ref, id, replace_tags,
2701 verbosity, repo);
2702 unlock_err = got_ref_unlock(ref);
2703 if (unlock_err && error == NULL)
2704 error = unlock_err;
2705 got_ref_close(ref);
2706 if (error)
2707 goto done;
2710 /* Also create a local branch if none exists yet. */
2711 error = got_ref_open(&ref, repo, refname, 1);
2712 if (error) {
2713 if (error->code != GOT_ERR_NOT_REF)
2714 goto done;
2715 error = create_ref(refname, id, verbosity,
2716 repo);
2717 if (error)
2718 goto done;
2719 } else {
2720 unlock_err = got_ref_unlock(ref);
2721 if (unlock_err && error == NULL)
2722 error = unlock_err;
2723 got_ref_close(ref);
2727 if (delete_refs) {
2728 error = delete_missing_refs(&refs, &symrefs, remote,
2729 verbosity, repo);
2730 if (error)
2731 goto done;
2734 if (!remote->mirror_references) {
2735 /* Update remote HEAD reference if the server provided one. */
2736 TAILQ_FOREACH(pe, &symrefs, entry) {
2737 struct got_reference *target_ref;
2738 const char *refname = pe->path;
2739 const char *target = pe->data;
2740 char *remote_refname = NULL, *remote_target = NULL;
2742 if (strcmp(refname, GOT_REF_HEAD) != 0)
2743 continue;
2745 if (strncmp("refs/heads/", target, 11) != 0)
2746 continue;
2748 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
2749 remote->name, refname) == -1) {
2750 error = got_error_from_errno("asprintf");
2751 goto done;
2753 if (asprintf(&remote_target, "refs/remotes/%s/%s",
2754 remote->name, target + 11) == -1) {
2755 error = got_error_from_errno("asprintf");
2756 free(remote_refname);
2757 goto done;
2760 error = got_ref_open(&target_ref, repo, remote_target,
2761 0);
2762 if (error) {
2763 free(remote_refname);
2764 free(remote_target);
2765 if (error->code == GOT_ERR_NOT_REF) {
2766 error = NULL;
2767 continue;
2769 goto done;
2771 error = update_symref(remote_refname, target_ref,
2772 verbosity, repo);
2773 free(remote_refname);
2774 free(remote_target);
2775 got_ref_close(target_ref);
2776 if (error)
2777 goto done;
2780 done:
2781 if (fetchpid > 0) {
2782 if (kill(fetchpid, SIGTERM) == -1)
2783 error = got_error_from_errno("kill");
2784 if (waitpid(fetchpid, &fetchstatus, 0) == -1 && error == NULL)
2785 error = got_error_from_errno("waitpid");
2787 if (fetchfd != -1 && close(fetchfd) == -1 && error == NULL)
2788 error = got_error_from_errno("close");
2789 if (repo) {
2790 const struct got_error *close_err = got_repo_close(repo);
2791 if (error == NULL)
2792 error = close_err;
2794 if (worktree)
2795 got_worktree_close(worktree);
2796 if (pack_fds) {
2797 const struct got_error *pack_err =
2798 got_repo_pack_fds_close(pack_fds);
2799 if (error == NULL)
2800 error = pack_err;
2802 got_pathlist_free(&refs, GOT_PATHLIST_FREE_ALL);
2803 got_pathlist_free(&symrefs, GOT_PATHLIST_FREE_ALL);
2804 got_pathlist_free(&wanted_branches, GOT_PATHLIST_FREE_NONE);
2805 got_pathlist_free(&wanted_refs, GOT_PATHLIST_FREE_NONE);
2806 got_ref_list_free(&remote_refs);
2807 got_repo_free_remote_repo_data(remote);
2808 free(remote);
2809 free(head_refname);
2810 free(id_str);
2811 free(cwd);
2812 free(repo_path);
2813 free(pack_hash);
2814 free(proto);
2815 free(host);
2816 free(port);
2817 free(server_path);
2818 free(repo_name);
2819 return error;
2823 __dead static void
2824 usage_checkout(void)
2826 fprintf(stderr, "usage: %s checkout [-Eq] [-b branch] [-c commit] "
2827 "[-p path-prefix] repository-path [work-tree-path]\n",
2828 getprogname());
2829 exit(1);
2832 static void
2833 show_worktree_base_ref_warning(void)
2835 fprintf(stderr, "%s: warning: could not create a reference "
2836 "to the work tree's base commit; the commit could be "
2837 "garbage-collected by Git or 'gotadmin cleanup'; making the "
2838 "repository writable and running 'got update' will prevent this\n",
2839 getprogname());
2842 struct got_checkout_progress_arg {
2843 const char *worktree_path;
2844 int had_base_commit_ref_error;
2845 int verbosity;
2848 static const struct got_error *
2849 checkout_progress(void *arg, unsigned char status, const char *path)
2851 struct got_checkout_progress_arg *a = arg;
2853 /* Base commit bump happens silently. */
2854 if (status == GOT_STATUS_BUMP_BASE)
2855 return NULL;
2857 if (status == GOT_STATUS_BASE_REF_ERR) {
2858 a->had_base_commit_ref_error = 1;
2859 return NULL;
2862 while (path[0] == '/')
2863 path++;
2865 if (a->verbosity >= 0)
2866 printf("%c %s/%s\n", status, a->worktree_path, path);
2868 return NULL;
2871 static const struct got_error *
2872 check_cancelled(void *arg)
2874 if (sigint_received || sigpipe_received)
2875 return got_error(GOT_ERR_CANCELLED);
2876 return NULL;
2879 static const struct got_error *
2880 check_linear_ancestry(struct got_object_id *commit_id,
2881 struct got_object_id *base_commit_id, int allow_forwards_in_time_only,
2882 struct got_repository *repo)
2884 const struct got_error *err = NULL;
2885 struct got_object_id *yca_id;
2887 err = got_commit_graph_find_youngest_common_ancestor(&yca_id,
2888 commit_id, base_commit_id, 1, 0, repo, check_cancelled, NULL);
2889 if (err)
2890 return err;
2892 if (yca_id == NULL)
2893 return got_error(GOT_ERR_ANCESTRY);
2896 * Require a straight line of history between the target commit
2897 * and the work tree's base commit.
2899 * Non-linear situations such as this require a rebase:
2901 * (commit) D F (base_commit)
2902 * \ /
2903 * C E
2904 * \ /
2905 * B (yca)
2906 * |
2907 * A
2909 * 'got update' only handles linear cases:
2910 * Update forwards in time: A (base/yca) - B - C - D (commit)
2911 * Update backwards in time: D (base) - C - B - A (commit/yca)
2913 if (allow_forwards_in_time_only) {
2914 if (got_object_id_cmp(base_commit_id, yca_id) != 0)
2915 return got_error(GOT_ERR_ANCESTRY);
2916 } else if (got_object_id_cmp(commit_id, yca_id) != 0 &&
2917 got_object_id_cmp(base_commit_id, yca_id) != 0)
2918 return got_error(GOT_ERR_ANCESTRY);
2920 free(yca_id);
2921 return NULL;
2924 static const struct got_error *
2925 check_same_branch(struct got_object_id *commit_id,
2926 struct got_reference *head_ref, struct got_repository *repo)
2928 const struct got_error *err = NULL;
2929 struct got_commit_graph *graph = NULL;
2930 struct got_object_id *head_commit_id = NULL;
2932 err = got_ref_resolve(&head_commit_id, repo, head_ref);
2933 if (err)
2934 goto done;
2936 if (got_object_id_cmp(head_commit_id, commit_id) == 0)
2937 goto done;
2939 err = got_commit_graph_open(&graph, "/", 1);
2940 if (err)
2941 goto done;
2943 err = got_commit_graph_bfsort(graph, head_commit_id, repo,
2944 check_cancelled, NULL);
2945 if (err)
2946 goto done;
2948 for (;;) {
2949 struct got_object_id id;
2951 err = got_commit_graph_iter_next(&id, graph, repo,
2952 check_cancelled, NULL);
2953 if (err) {
2954 if (err->code == GOT_ERR_ITER_COMPLETED)
2955 err = got_error(GOT_ERR_ANCESTRY);
2956 break;
2959 if (got_object_id_cmp(&id, commit_id) == 0)
2960 break;
2962 done:
2963 if (graph)
2964 got_commit_graph_close(graph);
2965 free(head_commit_id);
2966 return err;
2969 static const struct got_error *
2970 checkout_ancestry_error(struct got_reference *ref, const char *commit_id_str)
2972 static char msg[512];
2973 const char *branch_name;
2975 if (got_ref_is_symbolic(ref))
2976 branch_name = got_ref_get_symref_target(ref);
2977 else
2978 branch_name = got_ref_get_name(ref);
2980 if (strncmp("refs/heads/", branch_name, 11) == 0)
2981 branch_name += 11;
2983 snprintf(msg, sizeof(msg),
2984 "target commit is not contained in branch '%s'; "
2985 "the branch to use must be specified with -b; "
2986 "if necessary a new branch can be created for "
2987 "this commit with 'got branch -c %s BRANCH_NAME'",
2988 branch_name, commit_id_str);
2990 return got_error_msg(GOT_ERR_ANCESTRY, msg);
2993 static const struct got_error *
2994 cmd_checkout(int argc, char *argv[])
2996 const struct got_error *close_err, *error = NULL;
2997 struct got_repository *repo = NULL;
2998 struct got_reference *head_ref = NULL, *ref = NULL;
2999 struct got_worktree *worktree = NULL;
3000 char *repo_path = NULL;
3001 char *worktree_path = NULL;
3002 const char *path_prefix = "";
3003 const char *branch_name = GOT_REF_HEAD, *refname = NULL;
3004 char *commit_id_str = NULL, *keyword_idstr = NULL;
3005 struct got_object_id *commit_id = NULL;
3006 char *cwd = NULL;
3007 int ch, same_path_prefix, allow_nonempty = 0, verbosity = 0;
3008 struct got_pathlist_head paths;
3009 struct got_checkout_progress_arg cpa;
3010 int *pack_fds = NULL;
3012 TAILQ_INIT(&paths);
3014 #ifndef PROFILE
3015 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
3016 "unveil", NULL) == -1)
3017 err(1, "pledge");
3018 #endif
3020 while ((ch = getopt(argc, argv, "b:c:Ep:q")) != -1) {
3021 switch (ch) {
3022 case 'b':
3023 branch_name = optarg;
3024 break;
3025 case 'c':
3026 commit_id_str = strdup(optarg);
3027 if (commit_id_str == NULL)
3028 return got_error_from_errno("strdup");
3029 break;
3030 case 'E':
3031 allow_nonempty = 1;
3032 break;
3033 case 'p':
3034 path_prefix = optarg;
3035 break;
3036 case 'q':
3037 verbosity = -1;
3038 break;
3039 default:
3040 usage_checkout();
3041 /* NOTREACHED */
3045 argc -= optind;
3046 argv += optind;
3048 if (argc == 1) {
3049 char *base, *dotgit;
3050 const char *path;
3051 repo_path = realpath(argv[0], NULL);
3052 if (repo_path == NULL)
3053 return got_error_from_errno2("realpath", argv[0]);
3054 cwd = getcwd(NULL, 0);
3055 if (cwd == NULL) {
3056 error = got_error_from_errno("getcwd");
3057 goto done;
3059 if (path_prefix[0])
3060 path = path_prefix;
3061 else
3062 path = repo_path;
3063 error = got_path_basename(&base, path);
3064 if (error)
3065 goto done;
3066 dotgit = strstr(base, ".git");
3067 if (dotgit)
3068 *dotgit = '\0';
3069 if (asprintf(&worktree_path, "%s/%s", cwd, base) == -1) {
3070 error = got_error_from_errno("asprintf");
3071 free(base);
3072 goto done;
3074 free(base);
3075 } else if (argc == 2) {
3076 repo_path = realpath(argv[0], NULL);
3077 if (repo_path == NULL) {
3078 error = got_error_from_errno2("realpath", argv[0]);
3079 goto done;
3081 worktree_path = realpath(argv[1], NULL);
3082 if (worktree_path == NULL) {
3083 if (errno != ENOENT) {
3084 error = got_error_from_errno2("realpath",
3085 argv[1]);
3086 goto done;
3088 worktree_path = strdup(argv[1]);
3089 if (worktree_path == NULL) {
3090 error = got_error_from_errno("strdup");
3091 goto done;
3094 } else
3095 usage_checkout();
3097 got_path_strip_trailing_slashes(repo_path);
3098 got_path_strip_trailing_slashes(worktree_path);
3100 if (got_path_is_child(worktree_path, repo_path, strlen(repo_path)) ||
3101 got_path_is_child(repo_path, worktree_path,
3102 strlen(worktree_path))) {
3103 error = got_error_fmt(GOT_ERR_BAD_PATH,
3104 "work tree and repository paths may not overlap: %s",
3105 worktree_path);
3106 goto done;
3109 error = got_repo_pack_fds_open(&pack_fds);
3110 if (error != NULL)
3111 goto done;
3113 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
3114 if (error != NULL)
3115 goto done;
3117 /* Pre-create work tree path for unveil(2) */
3118 error = got_path_mkdir(worktree_path);
3119 if (error) {
3120 if (!(error->code == GOT_ERR_ERRNO && errno == EISDIR) &&
3121 !(error->code == GOT_ERR_ERRNO && errno == EEXIST))
3122 goto done;
3123 if (!allow_nonempty &&
3124 !got_path_dir_is_empty(worktree_path)) {
3125 error = got_error_path(worktree_path,
3126 GOT_ERR_DIR_NOT_EMPTY);
3127 goto done;
3131 error = apply_unveil(got_repo_get_path(repo), 0, worktree_path);
3132 if (error)
3133 goto done;
3135 error = got_ref_open(&head_ref, repo, branch_name, 0);
3136 if (error != NULL)
3137 goto done;
3139 error = got_worktree_init(worktree_path, head_ref, path_prefix,
3140 GOT_WORKTREE_GOT_DIR, repo);
3141 if (error != NULL && !(error->code == GOT_ERR_ERRNO && errno == EEXIST))
3142 goto done;
3144 error = got_worktree_open(&worktree, worktree_path,
3145 GOT_WORKTREE_GOT_DIR);
3146 if (error != NULL)
3147 goto done;
3149 error = got_worktree_match_path_prefix(&same_path_prefix, worktree,
3150 path_prefix);
3151 if (error != NULL)
3152 goto done;
3153 if (!same_path_prefix) {
3154 error = got_error(GOT_ERR_PATH_PREFIX);
3155 goto done;
3158 if (commit_id_str) {
3159 struct got_reflist_head refs;
3160 TAILQ_INIT(&refs);
3161 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
3162 NULL);
3163 if (error)
3164 goto done;
3166 error = got_keyword_to_idstr(&keyword_idstr, commit_id_str,
3167 repo, worktree);
3168 if (error != NULL)
3169 goto done;
3170 if (keyword_idstr != NULL) {
3171 free(commit_id_str);
3172 commit_id_str = keyword_idstr;
3175 error = got_repo_match_object_id(&commit_id, NULL,
3176 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
3177 got_ref_list_free(&refs);
3178 if (error)
3179 goto done;
3180 error = check_linear_ancestry(commit_id,
3181 got_worktree_get_base_commit_id(worktree), 0, repo);
3182 if (error != NULL) {
3183 if (error->code == GOT_ERR_ANCESTRY) {
3184 error = checkout_ancestry_error(
3185 head_ref, commit_id_str);
3187 goto done;
3189 error = check_same_branch(commit_id, head_ref, repo);
3190 if (error) {
3191 if (error->code == GOT_ERR_ANCESTRY) {
3192 error = checkout_ancestry_error(
3193 head_ref, commit_id_str);
3195 goto done;
3197 error = got_worktree_set_base_commit_id(worktree, repo,
3198 commit_id);
3199 if (error)
3200 goto done;
3201 /* Expand potentially abbreviated commit ID string. */
3202 free(commit_id_str);
3203 error = got_object_id_str(&commit_id_str, commit_id);
3204 if (error)
3205 goto done;
3206 } else {
3207 commit_id = got_object_id_dup(
3208 got_worktree_get_base_commit_id(worktree));
3209 if (commit_id == NULL) {
3210 error = got_error_from_errno("got_object_id_dup");
3211 goto done;
3213 error = got_object_id_str(&commit_id_str, commit_id);
3214 if (error)
3215 goto done;
3218 error = got_pathlist_append(&paths, "", NULL);
3219 if (error)
3220 goto done;
3221 cpa.worktree_path = worktree_path;
3222 cpa.had_base_commit_ref_error = 0;
3223 cpa.verbosity = verbosity;
3224 error = got_worktree_checkout_files(worktree, &paths, repo,
3225 checkout_progress, &cpa, check_cancelled, NULL);
3226 if (error != NULL)
3227 goto done;
3229 if (got_ref_is_symbolic(head_ref)) {
3230 error = got_ref_resolve_symbolic(&ref, repo, head_ref);
3231 if (error)
3232 goto done;
3233 refname = got_ref_get_name(ref);
3234 } else
3235 refname = got_ref_get_name(head_ref);
3236 printf("Checked out %s: %s\n", refname, commit_id_str);
3237 printf("Now shut up and hack\n");
3238 if (cpa.had_base_commit_ref_error)
3239 show_worktree_base_ref_warning();
3240 done:
3241 if (pack_fds) {
3242 const struct got_error *pack_err =
3243 got_repo_pack_fds_close(pack_fds);
3244 if (error == NULL)
3245 error = pack_err;
3247 if (head_ref)
3248 got_ref_close(head_ref);
3249 if (ref)
3250 got_ref_close(ref);
3251 if (repo) {
3252 close_err = got_repo_close(repo);
3253 if (error == NULL)
3254 error = close_err;
3256 if (worktree != NULL) {
3257 close_err = got_worktree_close(worktree);
3258 if (error == NULL)
3259 error = close_err;
3261 got_pathlist_free(&paths, GOT_PATHLIST_FREE_NONE);
3262 free(commit_id_str);
3263 free(commit_id);
3264 free(repo_path);
3265 free(worktree_path);
3266 free(cwd);
3267 return error;
3270 struct got_update_progress_arg {
3271 int did_something;
3272 int conflicts;
3273 int obstructed;
3274 int not_updated;
3275 int missing;
3276 int not_deleted;
3277 int unversioned;
3278 int verbosity;
3281 static void
3282 print_update_progress_stats(struct got_update_progress_arg *upa)
3284 if (!upa->did_something)
3285 return;
3287 if (upa->conflicts > 0)
3288 printf("Files with new merge conflicts: %d\n", upa->conflicts);
3289 if (upa->obstructed > 0)
3290 printf("File paths obstructed by a non-regular file: %d\n",
3291 upa->obstructed);
3292 if (upa->not_updated > 0)
3293 printf("Files not updated because of existing merge "
3294 "conflicts: %d\n", upa->not_updated);
3298 * The meaning of some status codes differs between merge-style operations and
3299 * update operations. For example, the ! status code means "file was missing"
3300 * if changes were merged into the work tree, and "missing file was restored"
3301 * if the work tree was updated. This function should be used by any operation
3302 * which merges changes into the work tree without updating the work tree.
3304 static void
3305 print_merge_progress_stats(struct got_update_progress_arg *upa)
3307 if (!upa->did_something)
3308 return;
3310 if (upa->conflicts > 0)
3311 printf("Files with new merge conflicts: %d\n", upa->conflicts);
3312 if (upa->obstructed > 0)
3313 printf("File paths obstructed by a non-regular file: %d\n",
3314 upa->obstructed);
3315 if (upa->missing > 0)
3316 printf("Files which had incoming changes but could not be "
3317 "found in the work tree: %d\n", upa->missing);
3318 if (upa->not_deleted > 0)
3319 printf("Files not deleted due to differences in deleted "
3320 "content: %d\n", upa->not_deleted);
3321 if (upa->unversioned > 0)
3322 printf("Files not merged because an unversioned file was "
3323 "found in the work tree: %d\n", upa->unversioned);
3326 __dead static void
3327 usage_update(void)
3329 fprintf(stderr, "usage: %s update [-q] [-b branch] [-c commit] "
3330 "[path ...]\n", getprogname());
3331 exit(1);
3334 static const struct got_error *
3335 update_progress(void *arg, unsigned char status, const char *path)
3337 struct got_update_progress_arg *upa = arg;
3339 if (status == GOT_STATUS_EXISTS ||
3340 status == GOT_STATUS_BASE_REF_ERR)
3341 return NULL;
3343 upa->did_something = 1;
3345 /* Base commit bump happens silently. */
3346 if (status == GOT_STATUS_BUMP_BASE)
3347 return NULL;
3349 if (status == GOT_STATUS_CONFLICT)
3350 upa->conflicts++;
3351 if (status == GOT_STATUS_OBSTRUCTED)
3352 upa->obstructed++;
3353 if (status == GOT_STATUS_CANNOT_UPDATE)
3354 upa->not_updated++;
3355 if (status == GOT_STATUS_MISSING)
3356 upa->missing++;
3357 if (status == GOT_STATUS_CANNOT_DELETE)
3358 upa->not_deleted++;
3359 if (status == GOT_STATUS_UNVERSIONED)
3360 upa->unversioned++;
3362 while (path[0] == '/')
3363 path++;
3364 if (upa->verbosity >= 0)
3365 printf("%c %s\n", status, path);
3367 return NULL;
3370 static const struct got_error *
3371 switch_head_ref(struct got_reference *head_ref,
3372 struct got_object_id *commit_id, struct got_worktree *worktree,
3373 struct got_repository *repo)
3375 const struct got_error *err = NULL;
3376 char *base_id_str;
3377 int ref_has_moved = 0;
3379 /* Trivial case: switching between two different references. */
3380 if (strcmp(got_ref_get_name(head_ref),
3381 got_worktree_get_head_ref_name(worktree)) != 0) {
3382 printf("Switching work tree from %s to %s\n",
3383 got_worktree_get_head_ref_name(worktree),
3384 got_ref_get_name(head_ref));
3385 return got_worktree_set_head_ref(worktree, head_ref);
3388 err = check_linear_ancestry(commit_id,
3389 got_worktree_get_base_commit_id(worktree), 0, repo);
3390 if (err) {
3391 if (err->code != GOT_ERR_ANCESTRY)
3392 return err;
3393 ref_has_moved = 1;
3395 if (!ref_has_moved)
3396 return NULL;
3398 /* Switching to a rebased branch with the same reference name. */
3399 err = got_object_id_str(&base_id_str,
3400 got_worktree_get_base_commit_id(worktree));
3401 if (err)
3402 return err;
3403 printf("Reference %s now points at a different branch\n",
3404 got_worktree_get_head_ref_name(worktree));
3405 printf("Switching work tree from %s to %s\n", base_id_str,
3406 got_worktree_get_head_ref_name(worktree));
3407 return NULL;
3410 static const struct got_error *
3411 check_rebase_or_histedit_in_progress(struct got_worktree *worktree)
3413 const struct got_error *err;
3414 int in_progress;
3416 err = got_worktree_rebase_in_progress(&in_progress, worktree);
3417 if (err)
3418 return err;
3419 if (in_progress)
3420 return got_error(GOT_ERR_REBASING);
3422 err = got_worktree_histedit_in_progress(&in_progress, worktree);
3423 if (err)
3424 return err;
3425 if (in_progress)
3426 return got_error(GOT_ERR_HISTEDIT_BUSY);
3428 return NULL;
3431 static const struct got_error *
3432 check_merge_in_progress(struct got_worktree *worktree,
3433 struct got_repository *repo)
3435 const struct got_error *err;
3436 int in_progress;
3438 err = got_worktree_merge_in_progress(&in_progress, worktree, repo);
3439 if (err)
3440 return err;
3441 if (in_progress)
3442 return got_error(GOT_ERR_MERGE_BUSY);
3444 return NULL;
3447 static const struct got_error *
3448 get_worktree_paths_from_argv(struct got_pathlist_head *paths, int argc,
3449 char *argv[], struct got_worktree *worktree)
3451 const struct got_error *err = NULL;
3452 char *path;
3453 struct got_pathlist_entry *new;
3454 int i;
3456 if (argc == 0) {
3457 path = strdup("");
3458 if (path == NULL)
3459 return got_error_from_errno("strdup");
3460 return got_pathlist_append(paths, path, NULL);
3463 for (i = 0; i < argc; i++) {
3464 err = got_worktree_resolve_path(&path, worktree, argv[i]);
3465 if (err)
3466 break;
3467 err = got_pathlist_insert(&new, paths, path, NULL);
3468 if (err || new == NULL /* duplicate */) {
3469 free(path);
3470 if (err)
3471 break;
3475 return err;
3478 static const struct got_error *
3479 wrap_not_worktree_error(const struct got_error *orig_err,
3480 const char *cmdname, const char *path)
3482 const struct got_error *err;
3483 struct got_repository *repo;
3484 static char msg[512];
3485 int *pack_fds = NULL;
3487 err = got_repo_pack_fds_open(&pack_fds);
3488 if (err)
3489 return err;
3491 err = got_repo_open(&repo, path, NULL, pack_fds);
3492 if (err)
3493 return orig_err;
3495 snprintf(msg, sizeof(msg),
3496 "'got %s' needs a work tree in addition to a git repository\n"
3497 "Work trees can be checked out from this Git repository with "
3498 "'got checkout'.\n"
3499 "The got(1) manual page contains more information.", cmdname);
3500 err = got_error_msg(GOT_ERR_NOT_WORKTREE, msg);
3501 if (repo) {
3502 const struct got_error *close_err = got_repo_close(repo);
3503 if (err == NULL)
3504 err = close_err;
3506 if (pack_fds) {
3507 const struct got_error *pack_err =
3508 got_repo_pack_fds_close(pack_fds);
3509 if (err == NULL)
3510 err = pack_err;
3512 return err;
3515 static const struct got_error *
3516 cmd_update(int argc, char *argv[])
3518 const struct got_error *close_err, *error = NULL;
3519 struct got_repository *repo = NULL;
3520 struct got_worktree *worktree = NULL;
3521 char *worktree_path = NULL;
3522 struct got_object_id *commit_id = NULL;
3523 char *commit_id_str = NULL;
3524 const char *branch_name = NULL;
3525 struct got_reference *head_ref = NULL;
3526 struct got_pathlist_head paths;
3527 struct got_pathlist_entry *pe;
3528 int ch, verbosity = 0;
3529 struct got_update_progress_arg upa;
3530 int *pack_fds = NULL;
3532 TAILQ_INIT(&paths);
3534 #ifndef PROFILE
3535 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
3536 "unveil", NULL) == -1)
3537 err(1, "pledge");
3538 #endif
3540 while ((ch = getopt(argc, argv, "b:c:q")) != -1) {
3541 switch (ch) {
3542 case 'b':
3543 branch_name = optarg;
3544 break;
3545 case 'c':
3546 commit_id_str = strdup(optarg);
3547 if (commit_id_str == NULL)
3548 return got_error_from_errno("strdup");
3549 break;
3550 case 'q':
3551 verbosity = -1;
3552 break;
3553 default:
3554 usage_update();
3555 /* NOTREACHED */
3559 argc -= optind;
3560 argv += optind;
3562 worktree_path = getcwd(NULL, 0);
3563 if (worktree_path == NULL) {
3564 error = got_error_from_errno("getcwd");
3565 goto done;
3568 error = got_repo_pack_fds_open(&pack_fds);
3569 if (error != NULL)
3570 goto done;
3572 error = got_worktree_open(&worktree, worktree_path,
3573 GOT_WORKTREE_GOT_DIR);
3574 if (error) {
3575 if (error->code == GOT_ERR_NOT_WORKTREE)
3576 error = wrap_not_worktree_error(error, "update",
3577 worktree_path);
3578 goto done;
3581 error = check_rebase_or_histedit_in_progress(worktree);
3582 if (error)
3583 goto done;
3585 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
3586 NULL, pack_fds);
3587 if (error != NULL)
3588 goto done;
3590 error = apply_unveil(got_repo_get_path(repo), 0,
3591 got_worktree_get_root_path(worktree));
3592 if (error)
3593 goto done;
3595 error = check_merge_in_progress(worktree, repo);
3596 if (error)
3597 goto done;
3599 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
3600 if (error)
3601 goto done;
3603 error = got_ref_open(&head_ref, repo, branch_name ? branch_name :
3604 got_worktree_get_head_ref_name(worktree), 0);
3605 if (error != NULL)
3606 goto done;
3607 if (commit_id_str == NULL) {
3608 error = got_ref_resolve(&commit_id, repo, head_ref);
3609 if (error != NULL)
3610 goto done;
3611 error = got_object_id_str(&commit_id_str, commit_id);
3612 if (error != NULL)
3613 goto done;
3614 } else {
3615 struct got_reflist_head refs;
3616 char *keyword_idstr = NULL;
3618 TAILQ_INIT(&refs);
3620 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
3621 NULL);
3622 if (error)
3623 goto done;
3625 error = got_keyword_to_idstr(&keyword_idstr, commit_id_str,
3626 repo, worktree);
3627 if (error != NULL)
3628 goto done;
3629 if (keyword_idstr != NULL) {
3630 free(commit_id_str);
3631 commit_id_str = keyword_idstr;
3634 error = got_repo_match_object_id(&commit_id, NULL,
3635 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
3636 got_ref_list_free(&refs);
3637 free(commit_id_str);
3638 commit_id_str = NULL;
3639 if (error)
3640 goto done;
3641 error = got_object_id_str(&commit_id_str, commit_id);
3642 if (error)
3643 goto done;
3646 if (branch_name) {
3647 struct got_object_id *head_commit_id;
3648 TAILQ_FOREACH(pe, &paths, entry) {
3649 if (pe->path_len == 0)
3650 continue;
3651 error = got_error_msg(GOT_ERR_BAD_PATH,
3652 "switching between branches requires that "
3653 "the entire work tree gets updated");
3654 goto done;
3656 error = got_ref_resolve(&head_commit_id, repo, head_ref);
3657 if (error)
3658 goto done;
3659 error = check_linear_ancestry(commit_id, head_commit_id, 0,
3660 repo);
3661 free(head_commit_id);
3662 if (error != NULL)
3663 goto done;
3664 error = check_same_branch(commit_id, head_ref, repo);
3665 if (error)
3666 goto done;
3667 error = switch_head_ref(head_ref, commit_id, worktree, repo);
3668 if (error)
3669 goto done;
3670 } else {
3671 error = check_linear_ancestry(commit_id,
3672 got_worktree_get_base_commit_id(worktree), 0, repo);
3673 if (error != NULL) {
3674 if (error->code == GOT_ERR_ANCESTRY)
3675 error = got_error(GOT_ERR_BRANCH_MOVED);
3676 goto done;
3678 error = check_same_branch(commit_id, head_ref, repo);
3679 if (error)
3680 goto done;
3683 if (got_object_id_cmp(got_worktree_get_base_commit_id(worktree),
3684 commit_id) != 0) {
3685 error = got_worktree_set_base_commit_id(worktree, repo,
3686 commit_id);
3687 if (error)
3688 goto done;
3691 memset(&upa, 0, sizeof(upa));
3692 upa.verbosity = verbosity;
3693 error = got_worktree_checkout_files(worktree, &paths, repo,
3694 update_progress, &upa, check_cancelled, NULL);
3695 if (error != NULL)
3696 goto done;
3698 if (upa.did_something) {
3699 printf("Updated to %s: %s\n",
3700 got_worktree_get_head_ref_name(worktree), commit_id_str);
3701 } else
3702 printf("Already up-to-date\n");
3704 print_update_progress_stats(&upa);
3705 done:
3706 if (pack_fds) {
3707 const struct got_error *pack_err =
3708 got_repo_pack_fds_close(pack_fds);
3709 if (error == NULL)
3710 error = pack_err;
3712 if (repo) {
3713 close_err = got_repo_close(repo);
3714 if (error == NULL)
3715 error = close_err;
3717 if (worktree != NULL) {
3718 close_err = got_worktree_close(worktree);
3719 if (error == NULL)
3720 error = close_err;
3722 if (head_ref != NULL)
3723 got_ref_close(head_ref);
3724 free(worktree_path);
3725 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
3726 free(commit_id);
3727 free(commit_id_str);
3728 return error;
3731 static const struct got_error *
3732 diff_blobs(struct got_object_id *blob_id1, struct got_object_id *blob_id2,
3733 const char *path, int diff_context, int ignore_whitespace,
3734 int force_text_diff, struct got_diffstat_cb_arg *dsa,
3735 struct got_repository *repo, FILE *outfile)
3737 const struct got_error *err = NULL;
3738 struct got_blob_object *blob1 = NULL, *blob2 = NULL;
3739 FILE *f1 = NULL, *f2 = NULL;
3740 int fd1 = -1, fd2 = -1;
3742 fd1 = got_opentempfd();
3743 if (fd1 == -1)
3744 return got_error_from_errno("got_opentempfd");
3745 fd2 = got_opentempfd();
3746 if (fd2 == -1) {
3747 err = got_error_from_errno("got_opentempfd");
3748 goto done;
3751 if (blob_id1) {
3752 err = got_object_open_as_blob(&blob1, repo, blob_id1, 8192,
3753 fd1);
3754 if (err)
3755 goto done;
3758 err = got_object_open_as_blob(&blob2, repo, blob_id2, 8192, fd2);
3759 if (err)
3760 goto done;
3762 f1 = got_opentemp();
3763 if (f1 == NULL) {
3764 err = got_error_from_errno("got_opentemp");
3765 goto done;
3767 f2 = got_opentemp();
3768 if (f2 == NULL) {
3769 err = got_error_from_errno("got_opentemp");
3770 goto done;
3773 while (path[0] == '/')
3774 path++;
3775 err = got_diff_blob(NULL, NULL, blob1, blob2, f1, f2, path, path,
3776 GOT_DIFF_ALGORITHM_PATIENCE, diff_context, ignore_whitespace,
3777 force_text_diff, dsa, outfile);
3778 done:
3779 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
3780 err = got_error_from_errno("close");
3781 if (blob1)
3782 got_object_blob_close(blob1);
3783 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
3784 err = got_error_from_errno("close");
3785 if (blob2)
3786 got_object_blob_close(blob2);
3787 if (f1 && fclose(f1) == EOF && err == NULL)
3788 err = got_error_from_errno("fclose");
3789 if (f2 && fclose(f2) == EOF && err == NULL)
3790 err = got_error_from_errno("fclose");
3791 return err;
3794 static const struct got_error *
3795 diff_trees(struct got_object_id *tree_id1, struct got_object_id *tree_id2,
3796 const char *path, int diff_context, int ignore_whitespace,
3797 int force_text_diff, struct got_diffstat_cb_arg *dsa,
3798 struct got_repository *repo, FILE *outfile)
3800 const struct got_error *err = NULL;
3801 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
3802 struct got_diff_blob_output_unidiff_arg arg;
3803 FILE *f1 = NULL, *f2 = NULL;
3804 int fd1 = -1, fd2 = -1;
3806 if (tree_id1) {
3807 err = got_object_open_as_tree(&tree1, repo, tree_id1);
3808 if (err)
3809 goto done;
3810 fd1 = got_opentempfd();
3811 if (fd1 == -1) {
3812 err = got_error_from_errno("got_opentempfd");
3813 goto done;
3817 err = got_object_open_as_tree(&tree2, repo, tree_id2);
3818 if (err)
3819 goto done;
3821 f1 = got_opentemp();
3822 if (f1 == NULL) {
3823 err = got_error_from_errno("got_opentemp");
3824 goto done;
3827 f2 = got_opentemp();
3828 if (f2 == NULL) {
3829 err = got_error_from_errno("got_opentemp");
3830 goto done;
3832 fd2 = got_opentempfd();
3833 if (fd2 == -1) {
3834 err = got_error_from_errno("got_opentempfd");
3835 goto done;
3837 arg.diff_context = diff_context;
3838 arg.ignore_whitespace = ignore_whitespace;
3839 arg.force_text_diff = force_text_diff;
3840 arg.diffstat = dsa;
3841 arg.diff_algo = GOT_DIFF_ALGORITHM_PATIENCE;
3842 arg.outfile = outfile;
3843 arg.lines = NULL;
3844 arg.nlines = 0;
3845 while (path[0] == '/')
3846 path++;
3847 err = got_diff_tree(tree1, tree2, f1, f2, fd1, fd2, path, path, repo,
3848 got_diff_blob_output_unidiff, &arg, 1);
3849 done:
3850 if (tree1)
3851 got_object_tree_close(tree1);
3852 if (tree2)
3853 got_object_tree_close(tree2);
3854 if (f1 && fclose(f1) == EOF && err == NULL)
3855 err = got_error_from_errno("fclose");
3856 if (f2 && fclose(f2) == EOF && err == NULL)
3857 err = got_error_from_errno("fclose");
3858 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
3859 err = got_error_from_errno("close");
3860 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
3861 err = got_error_from_errno("close");
3862 return err;
3865 static const struct got_error *
3866 get_changed_paths(struct got_pathlist_head *paths,
3867 struct got_commit_object *commit, struct got_repository *repo,
3868 struct got_diffstat_cb_arg *dsa)
3870 const struct got_error *err = NULL;
3871 struct got_object_id *tree_id1 = NULL, *tree_id2 = NULL;
3872 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
3873 struct got_object_qid *qid;
3874 got_diff_blob_cb cb = got_diff_tree_collect_changed_paths;
3875 FILE *f1 = NULL, *f2 = NULL;
3876 int fd1 = -1, fd2 = -1;
3878 if (dsa) {
3879 cb = got_diff_tree_compute_diffstat;
3881 f1 = got_opentemp();
3882 if (f1 == NULL) {
3883 err = got_error_from_errno("got_opentemp");
3884 goto done;
3886 f2 = got_opentemp();
3887 if (f2 == NULL) {
3888 err = got_error_from_errno("got_opentemp");
3889 goto done;
3891 fd1 = got_opentempfd();
3892 if (fd1 == -1) {
3893 err = got_error_from_errno("got_opentempfd");
3894 goto done;
3896 fd2 = got_opentempfd();
3897 if (fd2 == -1) {
3898 err = got_error_from_errno("got_opentempfd");
3899 goto done;
3903 qid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
3904 if (qid != NULL) {
3905 struct got_commit_object *pcommit;
3906 err = got_object_open_as_commit(&pcommit, repo,
3907 &qid->id);
3908 if (err)
3909 return err;
3911 tree_id1 = got_object_id_dup(
3912 got_object_commit_get_tree_id(pcommit));
3913 if (tree_id1 == NULL) {
3914 got_object_commit_close(pcommit);
3915 return got_error_from_errno("got_object_id_dup");
3917 got_object_commit_close(pcommit);
3921 if (tree_id1) {
3922 err = got_object_open_as_tree(&tree1, repo, tree_id1);
3923 if (err)
3924 goto done;
3927 tree_id2 = got_object_commit_get_tree_id(commit);
3928 err = got_object_open_as_tree(&tree2, repo, tree_id2);
3929 if (err)
3930 goto done;
3932 err = got_diff_tree(tree1, tree2, f1, f2, fd1, fd2, "", "", repo,
3933 cb, dsa ? (void *)dsa : paths, dsa ? 1 : 0);
3934 done:
3935 if (tree1)
3936 got_object_tree_close(tree1);
3937 if (tree2)
3938 got_object_tree_close(tree2);
3939 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
3940 err = got_error_from_errno("close");
3941 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
3942 err = got_error_from_errno("close");
3943 if (f1 && fclose(f1) == EOF && err == NULL)
3944 err = got_error_from_errno("fclose");
3945 if (f2 && fclose(f2) == EOF && err == NULL)
3946 err = got_error_from_errno("fclose");
3947 free(tree_id1);
3948 return err;
3951 static const struct got_error *
3952 print_patch(struct got_commit_object *commit, struct got_object_id *id,
3953 const char *path, int diff_context, struct got_diffstat_cb_arg *dsa,
3954 struct got_repository *repo, FILE *outfile)
3956 const struct got_error *err = NULL;
3957 struct got_commit_object *pcommit = NULL;
3958 char *id_str1 = NULL, *id_str2 = NULL;
3959 struct got_object_id *obj_id1 = NULL, *obj_id2 = NULL;
3960 struct got_object_qid *qid;
3962 qid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
3963 if (qid != NULL) {
3964 err = got_object_open_as_commit(&pcommit, repo,
3965 &qid->id);
3966 if (err)
3967 return err;
3968 err = got_object_id_str(&id_str1, &qid->id);
3969 if (err)
3970 goto done;
3973 err = got_object_id_str(&id_str2, id);
3974 if (err)
3975 goto done;
3977 if (path && path[0] != '\0') {
3978 int obj_type;
3979 err = got_object_id_by_path(&obj_id2, repo, commit, path);
3980 if (err)
3981 goto done;
3982 if (pcommit) {
3983 err = got_object_id_by_path(&obj_id1, repo,
3984 pcommit, path);
3985 if (err) {
3986 if (err->code != GOT_ERR_NO_TREE_ENTRY) {
3987 free(obj_id2);
3988 goto done;
3992 err = got_object_get_type(&obj_type, repo, obj_id2);
3993 if (err) {
3994 free(obj_id2);
3995 goto done;
3997 fprintf(outfile,
3998 "diff %s %s\n", id_str1 ? id_str1 : "/dev/null", id_str2);
3999 fprintf(outfile, "commit - %s\n",
4000 id_str1 ? id_str1 : "/dev/null");
4001 fprintf(outfile, "commit + %s\n", id_str2);
4002 switch (obj_type) {
4003 case GOT_OBJ_TYPE_BLOB:
4004 err = diff_blobs(obj_id1, obj_id2, path, diff_context,
4005 0, 0, dsa, repo, outfile);
4006 break;
4007 case GOT_OBJ_TYPE_TREE:
4008 err = diff_trees(obj_id1, obj_id2, path, diff_context,
4009 0, 0, dsa, repo, outfile);
4010 break;
4011 default:
4012 err = got_error(GOT_ERR_OBJ_TYPE);
4013 break;
4015 free(obj_id1);
4016 free(obj_id2);
4017 } else {
4018 obj_id2 = got_object_commit_get_tree_id(commit);
4019 if (pcommit)
4020 obj_id1 = got_object_commit_get_tree_id(pcommit);
4021 fprintf(outfile,
4022 "diff %s %s\n", id_str1 ? id_str1 : "/dev/null", id_str2);
4023 fprintf(outfile, "commit - %s\n",
4024 id_str1 ? id_str1 : "/dev/null");
4025 fprintf(outfile, "commit + %s\n", id_str2);
4026 err = diff_trees(obj_id1, obj_id2, "", diff_context, 0, 0,
4027 dsa, repo, outfile);
4029 done:
4030 free(id_str1);
4031 free(id_str2);
4032 if (pcommit)
4033 got_object_commit_close(pcommit);
4034 return err;
4037 static char *
4038 get_datestr(time_t *time, char *datebuf)
4040 struct tm mytm, *tm;
4041 char *p, *s;
4043 tm = gmtime_r(time, &mytm);
4044 if (tm == NULL)
4045 return NULL;
4046 s = asctime_r(tm, datebuf);
4047 if (s == NULL)
4048 return NULL;
4049 p = strchr(s, '\n');
4050 if (p)
4051 *p = '\0';
4052 return s;
4055 static const struct got_error *
4056 match_commit(int *have_match, struct got_object_id *id,
4057 struct got_commit_object *commit, regex_t *regex)
4059 const struct got_error *err = NULL;
4060 regmatch_t regmatch;
4061 char *id_str = NULL, *logmsg = NULL;
4063 *have_match = 0;
4065 err = got_object_id_str(&id_str, id);
4066 if (err)
4067 return err;
4069 err = got_object_commit_get_logmsg(&logmsg, commit);
4070 if (err)
4071 goto done;
4073 if (regexec(regex, got_object_commit_get_author(commit), 1,
4074 &regmatch, 0) == 0 ||
4075 regexec(regex, got_object_commit_get_committer(commit), 1,
4076 &regmatch, 0) == 0 ||
4077 regexec(regex, id_str, 1, &regmatch, 0) == 0 ||
4078 regexec(regex, logmsg, 1, &regmatch, 0) == 0)
4079 *have_match = 1;
4080 done:
4081 free(id_str);
4082 free(logmsg);
4083 return err;
4086 static void
4087 match_changed_paths(int *have_match, struct got_pathlist_head *changed_paths,
4088 regex_t *regex)
4090 regmatch_t regmatch;
4091 struct got_pathlist_entry *pe;
4093 *have_match = 0;
4095 TAILQ_FOREACH(pe, changed_paths, entry) {
4096 if (regexec(regex, pe->path, 1, &regmatch, 0) == 0) {
4097 *have_match = 1;
4098 break;
4103 static const struct got_error *
4104 match_patch(int *have_match, struct got_commit_object *commit,
4105 struct got_object_id *id, const char *path, int diff_context,
4106 struct got_repository *repo, regex_t *regex, FILE *f)
4108 const struct got_error *err = NULL;
4109 char *line = NULL;
4110 size_t linesize = 0;
4111 regmatch_t regmatch;
4113 *have_match = 0;
4115 err = got_opentemp_truncate(f);
4116 if (err)
4117 return err;
4119 err = print_patch(commit, id, path, diff_context, NULL, repo, f);
4120 if (err)
4121 goto done;
4123 if (fseeko(f, 0L, SEEK_SET) == -1) {
4124 err = got_error_from_errno("fseeko");
4125 goto done;
4128 while (getline(&line, &linesize, f) != -1) {
4129 if (regexec(regex, line, 1, &regmatch, 0) == 0) {
4130 *have_match = 1;
4131 break;
4134 done:
4135 free(line);
4136 return err;
4139 #define GOT_COMMIT_SEP_STR "-----------------------------------------------\n"
4141 static const struct got_error*
4142 build_refs_str(char **refs_str, struct got_reflist_head *refs,
4143 struct got_object_id *id, struct got_repository *repo,
4144 int local_only)
4146 static const struct got_error *err = NULL;
4147 struct got_reflist_entry *re;
4148 char *s;
4149 const char *name;
4151 *refs_str = NULL;
4153 TAILQ_FOREACH(re, refs, entry) {
4154 struct got_tag_object *tag = NULL;
4155 struct got_object_id *ref_id;
4156 int cmp;
4158 name = got_ref_get_name(re->ref);
4159 if (strcmp(name, GOT_REF_HEAD) == 0)
4160 continue;
4161 if (strncmp(name, "refs/", 5) == 0)
4162 name += 5;
4163 if (strncmp(name, "got/", 4) == 0)
4164 continue;
4165 if (strncmp(name, "heads/", 6) == 0)
4166 name += 6;
4167 if (strncmp(name, "remotes/", 8) == 0) {
4168 if (local_only)
4169 continue;
4170 name += 8;
4171 s = strstr(name, "/" GOT_REF_HEAD);
4172 if (s != NULL && strcmp(s, "/" GOT_REF_HEAD) == 0)
4173 continue;
4175 err = got_ref_resolve(&ref_id, repo, re->ref);
4176 if (err)
4177 break;
4178 if (strncmp(name, "tags/", 5) == 0) {
4179 err = got_object_open_as_tag(&tag, repo, ref_id);
4180 if (err) {
4181 if (err->code != GOT_ERR_OBJ_TYPE) {
4182 free(ref_id);
4183 break;
4185 /* Ref points at something other than a tag. */
4186 err = NULL;
4187 tag = NULL;
4190 cmp = got_object_id_cmp(tag ?
4191 got_object_tag_get_object_id(tag) : ref_id, id);
4192 free(ref_id);
4193 if (tag)
4194 got_object_tag_close(tag);
4195 if (cmp != 0)
4196 continue;
4197 s = *refs_str;
4198 if (asprintf(refs_str, "%s%s%s", s ? s : "",
4199 s ? ", " : "", name) == -1) {
4200 err = got_error_from_errno("asprintf");
4201 free(s);
4202 *refs_str = NULL;
4203 break;
4205 free(s);
4208 return err;
4211 static const struct got_error *
4212 print_commit_oneline(struct got_commit_object *commit, struct got_object_id *id,
4213 struct got_repository *repo, struct got_reflist_object_id_map *refs_idmap)
4215 const struct got_error *err = NULL;
4216 char *ref_str = NULL, *id_str = NULL, *logmsg0 = NULL;
4217 char *comma, *s, *nl;
4218 struct got_reflist_head *refs;
4219 char datebuf[12]; /* YYYY-MM-DD + SPACE + NUL */
4220 struct tm tm;
4221 time_t committer_time;
4223 refs = got_reflist_object_id_map_lookup(refs_idmap, id);
4224 if (refs) {
4225 err = build_refs_str(&ref_str, refs, id, repo, 1);
4226 if (err)
4227 return err;
4229 /* Display the first matching ref only. */
4230 if (ref_str && (comma = strchr(ref_str, ',')) != NULL)
4231 *comma = '\0';
4234 if (ref_str == NULL) {
4235 err = got_object_id_str(&id_str, id);
4236 if (err)
4237 return err;
4240 committer_time = got_object_commit_get_committer_time(commit);
4241 if (gmtime_r(&committer_time, &tm) == NULL) {
4242 err = got_error_from_errno("gmtime_r");
4243 goto done;
4245 if (strftime(datebuf, sizeof(datebuf), "%G-%m-%d ", &tm) == 0) {
4246 err = got_error(GOT_ERR_NO_SPACE);
4247 goto done;
4250 err = got_object_commit_get_logmsg(&logmsg0, commit);
4251 if (err)
4252 goto done;
4254 s = logmsg0;
4255 while (isspace((unsigned char)s[0]))
4256 s++;
4258 nl = strchr(s, '\n');
4259 if (nl) {
4260 *nl = '\0';
4263 if (ref_str)
4264 printf("%s%-7s %s\n", datebuf, ref_str, s);
4265 else
4266 printf("%s%.7s %s\n", datebuf, id_str, s);
4268 if (fflush(stdout) != 0 && err == NULL)
4269 err = got_error_from_errno("fflush");
4270 done:
4271 free(id_str);
4272 free(ref_str);
4273 free(logmsg0);
4274 return err;
4277 static const struct got_error *
4278 print_diffstat(struct got_diffstat_cb_arg *dsa, const char *header)
4280 struct got_pathlist_entry *pe;
4282 if (header != NULL)
4283 printf("%s\n", header);
4285 TAILQ_FOREACH(pe, dsa->paths, entry) {
4286 struct got_diff_changed_path *cp = pe->data;
4287 int pad = dsa->max_path_len - pe->path_len + 1;
4289 printf(" %c %s%*c | %*d+ %*d-\n", cp->status, pe->path, pad,
4290 ' ', dsa->add_cols + 1, cp->add, dsa->rm_cols + 1, cp->rm);
4292 printf("\n%d file%s changed, %d insertion%s(+), %d deletion%s(-)\n\n",
4293 dsa->nfiles, dsa->nfiles > 1 ? "s" : "", dsa->ins,
4294 dsa->ins != 1 ? "s" : "", dsa->del, dsa->del != 1 ? "s" : "");
4296 if (fflush(stdout) != 0)
4297 return got_error_from_errno("fflush");
4299 return NULL;
4302 static const struct got_error *
4303 printfile(FILE *f)
4305 char buf[8192];
4306 size_t r;
4308 if (fseeko(f, 0L, SEEK_SET) == -1)
4309 return got_error_from_errno("fseek");
4311 for (;;) {
4312 r = fread(buf, 1, sizeof(buf), f);
4313 if (r == 0) {
4314 if (ferror(f))
4315 return got_error_from_errno("fread");
4316 if (feof(f))
4317 break;
4319 if (fwrite(buf, 1, r, stdout) != r)
4320 return got_ferror(stdout, GOT_ERR_IO);
4323 return NULL;
4326 static const struct got_error *
4327 print_commit(struct got_commit_object *commit, struct got_object_id *id,
4328 struct got_repository *repo, const char *path,
4329 struct got_pathlist_head *changed_paths,
4330 struct got_diffstat_cb_arg *diffstat, int show_patch, int diff_context,
4331 struct got_reflist_object_id_map *refs_idmap, const char *custom_refs_str,
4332 const char *prefix)
4334 const struct got_error *err = NULL;
4335 FILE *f = NULL;
4336 char *id_str, *datestr, *logmsg0, *logmsg, *line;
4337 char datebuf[26];
4338 time_t committer_time;
4339 const char *author, *committer;
4340 char *refs_str = NULL;
4342 err = got_object_id_str(&id_str, id);
4343 if (err)
4344 return err;
4346 if (custom_refs_str == NULL) {
4347 struct got_reflist_head *refs;
4348 refs = got_reflist_object_id_map_lookup(refs_idmap, id);
4349 if (refs) {
4350 err = build_refs_str(&refs_str, refs, id, repo, 0);
4351 if (err)
4352 goto done;
4356 printf(GOT_COMMIT_SEP_STR);
4357 if (custom_refs_str)
4358 printf("%s %s (%s)\n", prefix ? prefix : "commit", id_str,
4359 custom_refs_str);
4360 else
4361 printf("%s %s%s%s%s\n", prefix ? prefix : "commit", id_str,
4362 refs_str ? " (" : "", refs_str ? refs_str : "",
4363 refs_str ? ")" : "");
4364 free(id_str);
4365 id_str = NULL;
4366 free(refs_str);
4367 refs_str = NULL;
4368 printf("from: %s\n", got_object_commit_get_author(commit));
4369 author = got_object_commit_get_author(commit);
4370 committer = got_object_commit_get_committer(commit);
4371 if (strcmp(author, committer) != 0)
4372 printf("via: %s\n", committer);
4373 committer_time = got_object_commit_get_committer_time(commit);
4374 datestr = get_datestr(&committer_time, datebuf);
4375 if (datestr)
4376 printf("date: %s UTC\n", datestr);
4377 if (got_object_commit_get_nparents(commit) > 1) {
4378 const struct got_object_id_queue *parent_ids;
4379 struct got_object_qid *qid;
4380 int n = 1;
4381 parent_ids = got_object_commit_get_parent_ids(commit);
4382 STAILQ_FOREACH(qid, parent_ids, entry) {
4383 err = got_object_id_str(&id_str, &qid->id);
4384 if (err)
4385 goto done;
4386 printf("parent %d: %s\n", n++, id_str);
4387 free(id_str);
4388 id_str = NULL;
4392 err = got_object_commit_get_logmsg(&logmsg0, commit);
4393 if (err)
4394 goto done;
4396 logmsg = logmsg0;
4397 do {
4398 line = strsep(&logmsg, "\n");
4399 if (line)
4400 printf(" %s\n", line);
4401 } while (line);
4402 free(logmsg0);
4404 if (changed_paths && diffstat == NULL) {
4405 struct got_pathlist_entry *pe;
4407 TAILQ_FOREACH(pe, changed_paths, entry) {
4408 struct got_diff_changed_path *cp = pe->data;
4410 printf(" %c %s\n", cp->status, pe->path);
4412 printf("\n");
4414 if (show_patch) {
4415 if (diffstat) {
4416 f = got_opentemp();
4417 if (f == NULL) {
4418 err = got_error_from_errno("got_opentemp");
4419 goto done;
4423 err = print_patch(commit, id, path, diff_context, diffstat,
4424 repo, diffstat == NULL ? stdout : f);
4425 if (err)
4426 goto done;
4428 if (diffstat) {
4429 err = print_diffstat(diffstat, NULL);
4430 if (err)
4431 goto done;
4432 if (show_patch) {
4433 err = printfile(f);
4434 if (err)
4435 goto done;
4438 if (show_patch)
4439 printf("\n");
4441 if (fflush(stdout) != 0 && err == NULL)
4442 err = got_error_from_errno("fflush");
4443 done:
4444 if (f && fclose(f) == EOF && err == NULL)
4445 err = got_error_from_errno("fclose");
4446 free(id_str);
4447 free(refs_str);
4448 return err;
4451 static const struct got_error *
4452 print_commits(struct got_object_id *root_id, struct got_object_id *end_id,
4453 struct got_repository *repo, const char *path, int show_changed_paths,
4454 int show_diffstat, int show_patch, const char *search_pattern,
4455 int diff_context, int limit, int log_branches, int reverse_display_order,
4456 struct got_reflist_object_id_map *refs_idmap, int one_line, int toposort,
4457 FILE *tmpfile)
4459 const struct got_error *err;
4460 struct got_commit_graph *graph;
4461 regex_t regex;
4462 int have_match;
4463 struct got_object_id_queue reversed_commits;
4464 struct got_object_qid *qid;
4465 struct got_commit_object *commit;
4466 struct got_pathlist_head changed_paths;
4468 STAILQ_INIT(&reversed_commits);
4469 TAILQ_INIT(&changed_paths);
4471 if (search_pattern && regcomp(&regex, search_pattern,
4472 REG_EXTENDED | REG_NOSUB | REG_NEWLINE))
4473 return got_error_msg(GOT_ERR_REGEX, search_pattern);
4475 err = got_commit_graph_open(&graph, path, !log_branches);
4476 if (err)
4477 return err;
4478 if (log_branches && toposort) {
4479 err = got_commit_graph_toposort(graph, root_id, repo,
4480 check_cancelled, NULL);
4481 } else {
4482 err = got_commit_graph_bfsort(graph, root_id, repo,
4483 check_cancelled, NULL);
4485 if (err)
4486 goto done;
4487 for (;;) {
4488 struct got_object_id id;
4489 struct got_diffstat_cb_arg dsa = { 0, 0, 0, 0, 0, 0,
4490 &changed_paths, 0, 0, GOT_DIFF_ALGORITHM_PATIENCE };
4492 if (sigint_received || sigpipe_received)
4493 break;
4495 err = got_commit_graph_iter_next(&id, graph, repo,
4496 check_cancelled, NULL);
4497 if (err) {
4498 if (err->code == GOT_ERR_ITER_COMPLETED)
4499 err = NULL;
4500 break;
4503 err = got_object_open_as_commit(&commit, repo, &id);
4504 if (err)
4505 break;
4507 if (((show_changed_paths && !show_diffstat) ||
4508 (show_diffstat && !show_patch))
4509 && !reverse_display_order) {
4510 err = get_changed_paths(&changed_paths, commit, repo,
4511 show_diffstat ? &dsa : NULL);
4512 if (err)
4513 break;
4516 if (search_pattern) {
4517 err = match_commit(&have_match, &id, commit, &regex);
4518 if (err) {
4519 got_object_commit_close(commit);
4520 break;
4522 if (have_match == 0 && show_changed_paths)
4523 match_changed_paths(&have_match,
4524 &changed_paths, &regex);
4525 if (have_match == 0 && show_patch) {
4526 err = match_patch(&have_match, commit, &id,
4527 path, diff_context, repo, &regex, tmpfile);
4528 if (err)
4529 break;
4531 if (have_match == 0) {
4532 got_object_commit_close(commit);
4533 got_pathlist_free(&changed_paths,
4534 GOT_PATHLIST_FREE_ALL);
4535 continue;
4539 if (reverse_display_order) {
4540 err = got_object_qid_alloc(&qid, &id);
4541 if (err)
4542 break;
4543 STAILQ_INSERT_HEAD(&reversed_commits, qid, entry);
4544 got_object_commit_close(commit);
4545 } else {
4546 if (one_line)
4547 err = print_commit_oneline(commit, &id,
4548 repo, refs_idmap);
4549 else
4550 err = print_commit(commit, &id, repo, path,
4551 (show_changed_paths || show_diffstat) ?
4552 &changed_paths : NULL,
4553 show_diffstat ? &dsa : NULL, show_patch,
4554 diff_context, refs_idmap, NULL, NULL);
4555 got_object_commit_close(commit);
4556 if (err)
4557 break;
4559 if ((limit && --limit == 0) ||
4560 (end_id && got_object_id_cmp(&id, end_id) == 0))
4561 break;
4563 got_pathlist_free(&changed_paths, GOT_PATHLIST_FREE_ALL);
4565 if (reverse_display_order) {
4566 STAILQ_FOREACH(qid, &reversed_commits, entry) {
4567 struct got_diffstat_cb_arg dsa = { 0, 0, 0, 0, 0, 0,
4568 &changed_paths, 0, 0, GOT_DIFF_ALGORITHM_PATIENCE };
4570 err = got_object_open_as_commit(&commit, repo,
4571 &qid->id);
4572 if (err)
4573 break;
4574 if ((show_changed_paths && !show_diffstat) ||
4575 (show_diffstat && !show_patch)) {
4576 err = get_changed_paths(&changed_paths, commit,
4577 repo, show_diffstat ? &dsa : NULL);
4578 if (err)
4579 break;
4581 if (one_line)
4582 err = print_commit_oneline(commit, &qid->id,
4583 repo, refs_idmap);
4584 else
4585 err = print_commit(commit, &qid->id, repo, path,
4586 (show_changed_paths || show_diffstat) ?
4587 &changed_paths : NULL,
4588 show_diffstat ? &dsa : NULL, show_patch,
4589 diff_context, refs_idmap, NULL, NULL);
4590 got_object_commit_close(commit);
4591 if (err)
4592 break;
4593 got_pathlist_free(&changed_paths, GOT_PATHLIST_FREE_ALL);
4596 done:
4597 while (!STAILQ_EMPTY(&reversed_commits)) {
4598 qid = STAILQ_FIRST(&reversed_commits);
4599 STAILQ_REMOVE_HEAD(&reversed_commits, entry);
4600 got_object_qid_free(qid);
4602 got_pathlist_free(&changed_paths, GOT_PATHLIST_FREE_ALL);
4603 if (search_pattern)
4604 regfree(&regex);
4605 got_commit_graph_close(graph);
4606 return err;
4609 __dead static void
4610 usage_log(void)
4612 fprintf(stderr, "usage: %s log [-bdPpRst] [-C number] [-c commit] "
4613 "[-l N] [-r repository-path] [-S search-pattern] [-x commit] "
4614 "[path]\n", getprogname());
4615 exit(1);
4618 static int
4619 get_default_log_limit(void)
4621 const char *got_default_log_limit;
4622 long long n;
4623 const char *errstr;
4625 got_default_log_limit = getenv("GOT_LOG_DEFAULT_LIMIT");
4626 if (got_default_log_limit == NULL)
4627 return 0;
4628 n = strtonum(got_default_log_limit, 0, INT_MAX, &errstr);
4629 if (errstr != NULL)
4630 return 0;
4631 return n;
4634 static const struct got_error *
4635 cmd_log(int argc, char *argv[])
4637 const struct got_error *error;
4638 struct got_repository *repo = NULL;
4639 struct got_worktree *worktree = NULL;
4640 struct got_object_id *start_id = NULL, *end_id = NULL;
4641 char *repo_path = NULL, *path = NULL, *cwd = NULL, *in_repo_path = NULL;
4642 char *keyword_idstr = NULL;
4643 const char *start_commit = NULL, *end_commit = NULL;
4644 const char *search_pattern = NULL;
4645 int diff_context = -1, ch;
4646 int show_changed_paths = 0, show_patch = 0, limit = 0, log_branches = 0;
4647 int show_diffstat = 0, reverse_display_order = 0, one_line = 0;
4648 int toposort = 0;
4649 const char *errstr;
4650 struct got_reflist_head refs;
4651 struct got_reflist_object_id_map *refs_idmap = NULL;
4652 FILE *tmpfile = NULL;
4653 int *pack_fds = NULL;
4655 TAILQ_INIT(&refs);
4657 #ifndef PROFILE
4658 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
4659 NULL)
4660 == -1)
4661 err(1, "pledge");
4662 #endif
4664 limit = get_default_log_limit();
4666 while ((ch = getopt(argc, argv, "bC:c:dl:PpRr:S:stx:")) != -1) {
4667 switch (ch) {
4668 case 'b':
4669 log_branches = 1;
4670 break;
4671 case 'C':
4672 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
4673 &errstr);
4674 if (errstr != NULL)
4675 errx(1, "number of context lines is %s: %s",
4676 errstr, optarg);
4677 break;
4678 case 'c':
4679 start_commit = optarg;
4680 break;
4681 case 'd':
4682 show_diffstat = 1;
4683 break;
4684 case 'l':
4685 limit = strtonum(optarg, 0, INT_MAX, &errstr);
4686 if (errstr != NULL)
4687 errx(1, "number of commits is %s: %s",
4688 errstr, optarg);
4689 break;
4690 case 'P':
4691 show_changed_paths = 1;
4692 break;
4693 case 'p':
4694 show_patch = 1;
4695 break;
4696 case 'R':
4697 reverse_display_order = 1;
4698 break;
4699 case 'r':
4700 repo_path = realpath(optarg, NULL);
4701 if (repo_path == NULL)
4702 return got_error_from_errno2("realpath",
4703 optarg);
4704 got_path_strip_trailing_slashes(repo_path);
4705 break;
4706 case 'S':
4707 search_pattern = optarg;
4708 break;
4709 case 's':
4710 one_line = 1;
4711 break;
4712 case 't':
4713 toposort = 1;
4714 break;
4715 case 'x':
4716 end_commit = optarg;
4717 break;
4718 default:
4719 usage_log();
4720 /* NOTREACHED */
4724 argc -= optind;
4725 argv += optind;
4727 if (diff_context == -1)
4728 diff_context = 3;
4729 else if (!show_patch)
4730 errx(1, "-C requires -p");
4732 if (one_line && (show_patch || show_changed_paths || show_diffstat))
4733 errx(1, "cannot use -s with -d, -p or -P");
4735 cwd = getcwd(NULL, 0);
4736 if (cwd == NULL) {
4737 error = got_error_from_errno("getcwd");
4738 goto done;
4741 error = got_repo_pack_fds_open(&pack_fds);
4742 if (error != NULL)
4743 goto done;
4745 if (repo_path == NULL) {
4746 error = got_worktree_open(&worktree, cwd,
4747 GOT_WORKTREE_GOT_DIR);
4748 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4749 goto done;
4750 error = NULL;
4753 if (argc == 1) {
4754 if (worktree) {
4755 error = got_worktree_resolve_path(&path, worktree,
4756 argv[0]);
4757 if (error)
4758 goto done;
4759 } else {
4760 path = strdup(argv[0]);
4761 if (path == NULL) {
4762 error = got_error_from_errno("strdup");
4763 goto done;
4766 } else if (argc != 0)
4767 usage_log();
4769 if (repo_path == NULL) {
4770 repo_path = worktree ?
4771 strdup(got_worktree_get_repo_path(worktree)) : strdup(cwd);
4773 if (repo_path == NULL) {
4774 error = got_error_from_errno("strdup");
4775 goto done;
4778 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
4779 if (error != NULL)
4780 goto done;
4782 error = apply_unveil(got_repo_get_path(repo), 1,
4783 worktree ? got_worktree_get_root_path(worktree) : NULL);
4784 if (error)
4785 goto done;
4787 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
4788 if (error)
4789 goto done;
4791 error = got_reflist_object_id_map_create(&refs_idmap, &refs, repo);
4792 if (error)
4793 goto done;
4795 if (start_commit == NULL) {
4796 struct got_reference *head_ref;
4797 struct got_commit_object *commit = NULL;
4798 error = got_ref_open(&head_ref, repo,
4799 worktree ? got_worktree_get_head_ref_name(worktree)
4800 : GOT_REF_HEAD, 0);
4801 if (error != NULL)
4802 goto done;
4803 error = got_ref_resolve(&start_id, repo, head_ref);
4804 got_ref_close(head_ref);
4805 if (error != NULL)
4806 goto done;
4807 error = got_object_open_as_commit(&commit, repo,
4808 start_id);
4809 if (error != NULL)
4810 goto done;
4811 got_object_commit_close(commit);
4812 } else {
4813 error = got_keyword_to_idstr(&keyword_idstr, start_commit,
4814 repo, worktree);
4815 if (error != NULL)
4816 goto done;
4817 if (keyword_idstr != NULL)
4818 start_commit = keyword_idstr;
4820 error = got_repo_match_object_id(&start_id, NULL,
4821 start_commit, GOT_OBJ_TYPE_COMMIT, &refs, repo);
4822 if (error != NULL)
4823 goto done;
4825 if (end_commit != NULL) {
4826 error = got_keyword_to_idstr(&keyword_idstr, end_commit,
4827 repo, worktree);
4828 if (error != NULL)
4829 goto done;
4830 if (keyword_idstr != NULL)
4831 end_commit = keyword_idstr;
4833 error = got_repo_match_object_id(&end_id, NULL,
4834 end_commit, GOT_OBJ_TYPE_COMMIT, &refs, repo);
4835 if (error != NULL)
4836 goto done;
4839 if (worktree) {
4841 * If a path was specified on the command line it was resolved
4842 * to a path in the work tree above. Prepend the work tree's
4843 * path prefix to obtain the corresponding in-repository path.
4845 if (path) {
4846 const char *prefix;
4847 prefix = got_worktree_get_path_prefix(worktree);
4848 if (asprintf(&in_repo_path, "%s%s%s", prefix,
4849 (path[0] != '\0') ? "/" : "", path) == -1) {
4850 error = got_error_from_errno("asprintf");
4851 goto done;
4854 } else
4855 error = got_repo_map_path(&in_repo_path, repo,
4856 path ? path : "");
4857 if (error != NULL)
4858 goto done;
4859 if (in_repo_path) {
4860 free(path);
4861 path = in_repo_path;
4864 if (worktree) {
4865 /* Release work tree lock. */
4866 got_worktree_close(worktree);
4867 worktree = NULL;
4870 if (search_pattern && show_patch) {
4871 tmpfile = got_opentemp();
4872 if (tmpfile == NULL) {
4873 error = got_error_from_errno("got_opentemp");
4874 goto done;
4878 error = print_commits(start_id, end_id, repo, path ? path : "",
4879 show_changed_paths, show_diffstat, show_patch, search_pattern,
4880 diff_context, limit, log_branches, reverse_display_order,
4881 refs_idmap, one_line, toposort, tmpfile);
4882 done:
4883 free(path);
4884 free(repo_path);
4885 free(cwd);
4886 free(start_id);
4887 free(end_id);
4888 free(keyword_idstr);
4889 if (worktree)
4890 got_worktree_close(worktree);
4891 if (repo) {
4892 const struct got_error *close_err = got_repo_close(repo);
4893 if (error == NULL)
4894 error = close_err;
4896 if (pack_fds) {
4897 const struct got_error *pack_err =
4898 got_repo_pack_fds_close(pack_fds);
4899 if (error == NULL)
4900 error = pack_err;
4902 if (refs_idmap)
4903 got_reflist_object_id_map_free(refs_idmap);
4904 if (tmpfile && fclose(tmpfile) == EOF && error == NULL)
4905 error = got_error_from_errno("fclose");
4906 got_ref_list_free(&refs);
4907 return error;
4910 __dead static void
4911 usage_diff(void)
4913 fprintf(stderr, "usage: %s diff [-adPsw] [-C number] [-c commit] "
4914 "[-r repository-path] [object1 object2 | path ...]\n",
4915 getprogname());
4916 exit(1);
4919 struct print_diff_arg {
4920 struct got_repository *repo;
4921 struct got_worktree *worktree;
4922 struct got_diffstat_cb_arg *diffstat;
4923 int diff_context;
4924 const char *id_str;
4925 int header_shown;
4926 int diff_staged;
4927 enum got_diff_algorithm diff_algo;
4928 int ignore_whitespace;
4929 int force_text_diff;
4930 FILE *f1;
4931 FILE *f2;
4932 FILE *outfile;
4936 * Create a file which contains the target path of a symlink so we can feed
4937 * it as content to the diff engine.
4939 static const struct got_error *
4940 get_symlink_target_file(int *fd, int dirfd, const char *de_name,
4941 const char *abspath)
4943 const struct got_error *err = NULL;
4944 char target_path[PATH_MAX];
4945 ssize_t target_len, outlen;
4947 *fd = -1;
4949 if (dirfd != -1) {
4950 target_len = readlinkat(dirfd, de_name, target_path, PATH_MAX);
4951 if (target_len == -1)
4952 return got_error_from_errno2("readlinkat", abspath);
4953 } else {
4954 target_len = readlink(abspath, target_path, PATH_MAX);
4955 if (target_len == -1)
4956 return got_error_from_errno2("readlink", abspath);
4959 *fd = got_opentempfd();
4960 if (*fd == -1)
4961 return got_error_from_errno("got_opentempfd");
4963 outlen = write(*fd, target_path, target_len);
4964 if (outlen == -1) {
4965 err = got_error_from_errno("got_opentempfd");
4966 goto done;
4969 if (lseek(*fd, 0, SEEK_SET) == -1) {
4970 err = got_error_from_errno2("lseek", abspath);
4971 goto done;
4973 done:
4974 if (err) {
4975 close(*fd);
4976 *fd = -1;
4978 return err;
4981 static const struct got_error *
4982 print_diff(void *arg, unsigned char status, unsigned char staged_status,
4983 const char *path, struct got_object_id *blob_id,
4984 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
4985 int dirfd, const char *de_name)
4987 struct print_diff_arg *a = arg;
4988 const struct got_error *err = NULL;
4989 struct got_blob_object *blob1 = NULL;
4990 int fd = -1, fd1 = -1, fd2 = -1;
4991 FILE *f2 = NULL;
4992 char *abspath = NULL, *label1 = NULL;
4993 struct stat sb;
4994 off_t size1 = 0;
4995 int f2_exists = 0;
4997 memset(&sb, 0, sizeof(sb));
4999 if (a->diff_staged) {
5000 if (staged_status != GOT_STATUS_MODIFY &&
5001 staged_status != GOT_STATUS_ADD &&
5002 staged_status != GOT_STATUS_DELETE)
5003 return NULL;
5004 } else {
5005 if (staged_status == GOT_STATUS_DELETE)
5006 return NULL;
5007 if (status == GOT_STATUS_NONEXISTENT)
5008 return got_error_set_errno(ENOENT, path);
5009 if (status != GOT_STATUS_MODIFY &&
5010 status != GOT_STATUS_ADD &&
5011 status != GOT_STATUS_DELETE &&
5012 status != GOT_STATUS_CONFLICT)
5013 return NULL;
5016 err = got_opentemp_truncate(a->f1);
5017 if (err)
5018 return got_error_from_errno("got_opentemp_truncate");
5019 err = got_opentemp_truncate(a->f2);
5020 if (err)
5021 return got_error_from_errno("got_opentemp_truncate");
5023 if (!a->header_shown) {
5024 if (fprintf(a->outfile, "diff %s%s\n",
5025 a->diff_staged ? "-s " : "",
5026 got_worktree_get_root_path(a->worktree)) < 0) {
5027 err = got_error_from_errno("fprintf");
5028 goto done;
5030 if (fprintf(a->outfile, "commit - %s\n", a->id_str) < 0) {
5031 err = got_error_from_errno("fprintf");
5032 goto done;
5034 if (fprintf(a->outfile, "path + %s%s\n",
5035 got_worktree_get_root_path(a->worktree),
5036 a->diff_staged ? " (staged changes)" : "") < 0) {
5037 err = got_error_from_errno("fprintf");
5038 goto done;
5040 a->header_shown = 1;
5043 if (a->diff_staged) {
5044 const char *label1 = NULL, *label2 = NULL;
5045 switch (staged_status) {
5046 case GOT_STATUS_MODIFY:
5047 label1 = path;
5048 label2 = path;
5049 break;
5050 case GOT_STATUS_ADD:
5051 label2 = path;
5052 break;
5053 case GOT_STATUS_DELETE:
5054 label1 = path;
5055 break;
5056 default:
5057 return got_error(GOT_ERR_FILE_STATUS);
5059 fd1 = got_opentempfd();
5060 if (fd1 == -1) {
5061 err = got_error_from_errno("got_opentempfd");
5062 goto done;
5064 fd2 = got_opentempfd();
5065 if (fd2 == -1) {
5066 err = got_error_from_errno("got_opentempfd");
5067 goto done;
5069 err = got_diff_objects_as_blobs(NULL, NULL, a->f1, a->f2,
5070 fd1, fd2, blob_id, staged_blob_id, label1, label2,
5071 a->diff_algo, a->diff_context, a->ignore_whitespace,
5072 a->force_text_diff, a->diffstat, a->repo, a->outfile);
5073 goto done;
5076 fd1 = got_opentempfd();
5077 if (fd1 == -1) {
5078 err = got_error_from_errno("got_opentempfd");
5079 goto done;
5082 if (staged_status == GOT_STATUS_ADD ||
5083 staged_status == GOT_STATUS_MODIFY) {
5084 char *id_str;
5085 err = got_object_open_as_blob(&blob1, a->repo, staged_blob_id,
5086 8192, fd1);
5087 if (err)
5088 goto done;
5089 err = got_object_id_str(&id_str, staged_blob_id);
5090 if (err)
5091 goto done;
5092 if (asprintf(&label1, "%s (staged)", id_str) == -1) {
5093 err = got_error_from_errno("asprintf");
5094 free(id_str);
5095 goto done;
5097 free(id_str);
5098 } else if (status != GOT_STATUS_ADD) {
5099 err = got_object_open_as_blob(&blob1, a->repo, blob_id, 8192,
5100 fd1);
5101 if (err)
5102 goto done;
5105 if (status != GOT_STATUS_DELETE) {
5106 if (asprintf(&abspath, "%s/%s",
5107 got_worktree_get_root_path(a->worktree), path) == -1) {
5108 err = got_error_from_errno("asprintf");
5109 goto done;
5112 if (dirfd != -1) {
5113 fd = openat(dirfd, de_name,
5114 O_RDONLY | O_NOFOLLOW | O_CLOEXEC);
5115 if (fd == -1) {
5116 if (!got_err_open_nofollow_on_symlink()) {
5117 err = got_error_from_errno2("openat",
5118 abspath);
5119 goto done;
5121 err = get_symlink_target_file(&fd, dirfd,
5122 de_name, abspath);
5123 if (err)
5124 goto done;
5126 } else {
5127 fd = open(abspath, O_RDONLY | O_NOFOLLOW | O_CLOEXEC);
5128 if (fd == -1) {
5129 if (!got_err_open_nofollow_on_symlink()) {
5130 err = got_error_from_errno2("open",
5131 abspath);
5132 goto done;
5134 err = get_symlink_target_file(&fd, dirfd,
5135 de_name, abspath);
5136 if (err)
5137 goto done;
5140 if (fstatat(fd, abspath, &sb, AT_SYMLINK_NOFOLLOW) == -1) {
5141 err = got_error_from_errno2("fstatat", abspath);
5142 goto done;
5144 f2 = fdopen(fd, "r");
5145 if (f2 == NULL) {
5146 err = got_error_from_errno2("fdopen", abspath);
5147 goto done;
5149 fd = -1;
5150 f2_exists = 1;
5153 if (blob1) {
5154 err = got_object_blob_dump_to_file(&size1, NULL, NULL,
5155 a->f1, blob1);
5156 if (err)
5157 goto done;
5160 err = got_diff_blob_file(blob1, a->f1, size1, label1, f2 ? f2 : a->f2,
5161 f2_exists, &sb, path, GOT_DIFF_ALGORITHM_PATIENCE, a->diff_context,
5162 a->ignore_whitespace, a->force_text_diff, a->diffstat, a->outfile);
5163 done:
5164 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
5165 err = got_error_from_errno("close");
5166 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
5167 err = got_error_from_errno("close");
5168 if (blob1)
5169 got_object_blob_close(blob1);
5170 if (fd != -1 && close(fd) == -1 && err == NULL)
5171 err = got_error_from_errno("close");
5172 if (f2 && fclose(f2) == EOF && err == NULL)
5173 err = got_error_from_errno("fclose");
5174 free(abspath);
5175 return err;
5178 static const struct got_error *
5179 cmd_diff(int argc, char *argv[])
5181 const struct got_error *error;
5182 struct got_repository *repo = NULL;
5183 struct got_worktree *worktree = NULL;
5184 char *cwd = NULL, *repo_path = NULL;
5185 const char *commit_args[2] = { NULL, NULL };
5186 int ncommit_args = 0;
5187 struct got_object_id *ids[2] = { NULL, NULL };
5188 char *labels[2] = { NULL, NULL };
5189 int type1 = GOT_OBJ_TYPE_ANY, type2 = GOT_OBJ_TYPE_ANY;
5190 int diff_context = 3, diff_staged = 0, ignore_whitespace = 0, ch, i;
5191 int force_text_diff = 0, force_path = 0, rflag = 0, show_diffstat = 0;
5192 const char *errstr;
5193 struct got_reflist_head refs;
5194 struct got_pathlist_head diffstat_paths, paths;
5195 FILE *f1 = NULL, *f2 = NULL, *outfile = NULL;
5196 int fd1 = -1, fd2 = -1;
5197 int *pack_fds = NULL;
5198 struct got_diffstat_cb_arg dsa;
5200 memset(&dsa, 0, sizeof(dsa));
5202 TAILQ_INIT(&refs);
5203 TAILQ_INIT(&paths);
5204 TAILQ_INIT(&diffstat_paths);
5206 #ifndef PROFILE
5207 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
5208 NULL) == -1)
5209 err(1, "pledge");
5210 #endif
5212 while ((ch = getopt(argc, argv, "aC:c:dPr:sw")) != -1) {
5213 switch (ch) {
5214 case 'a':
5215 force_text_diff = 1;
5216 break;
5217 case 'C':
5218 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
5219 &errstr);
5220 if (errstr != NULL)
5221 errx(1, "number of context lines is %s: %s",
5222 errstr, optarg);
5223 break;
5224 case 'c':
5225 if (ncommit_args >= 2)
5226 errx(1, "too many -c options used");
5227 commit_args[ncommit_args++] = optarg;
5228 break;
5229 case 'd':
5230 show_diffstat = 1;
5231 break;
5232 case 'P':
5233 force_path = 1;
5234 break;
5235 case 'r':
5236 repo_path = realpath(optarg, NULL);
5237 if (repo_path == NULL)
5238 return got_error_from_errno2("realpath",
5239 optarg);
5240 got_path_strip_trailing_slashes(repo_path);
5241 rflag = 1;
5242 break;
5243 case 's':
5244 diff_staged = 1;
5245 break;
5246 case 'w':
5247 ignore_whitespace = 1;
5248 break;
5249 default:
5250 usage_diff();
5251 /* NOTREACHED */
5255 argc -= optind;
5256 argv += optind;
5258 cwd = getcwd(NULL, 0);
5259 if (cwd == NULL) {
5260 error = got_error_from_errno("getcwd");
5261 goto done;
5264 error = got_repo_pack_fds_open(&pack_fds);
5265 if (error != NULL)
5266 goto done;
5268 if (repo_path == NULL) {
5269 error = got_worktree_open(&worktree, cwd,
5270 GOT_WORKTREE_GOT_DIR);
5271 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5272 goto done;
5273 else
5274 error = NULL;
5275 if (worktree) {
5276 repo_path =
5277 strdup(got_worktree_get_repo_path(worktree));
5278 if (repo_path == NULL) {
5279 error = got_error_from_errno("strdup");
5280 goto done;
5282 } else {
5283 repo_path = strdup(cwd);
5284 if (repo_path == NULL) {
5285 error = got_error_from_errno("strdup");
5286 goto done;
5291 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
5292 free(repo_path);
5293 if (error != NULL)
5294 goto done;
5296 if (show_diffstat) {
5297 dsa.paths = &diffstat_paths;
5298 dsa.force_text = force_text_diff;
5299 dsa.ignore_ws = ignore_whitespace;
5300 dsa.diff_algo = GOT_DIFF_ALGORITHM_PATIENCE;
5303 if (rflag || worktree == NULL || ncommit_args > 0) {
5304 if (force_path) {
5305 error = got_error_msg(GOT_ERR_NOT_IMPL,
5306 "-P option can only be used when diffing "
5307 "a work tree");
5308 goto done;
5310 if (diff_staged) {
5311 error = got_error_msg(GOT_ERR_NOT_IMPL,
5312 "-s option can only be used when diffing "
5313 "a work tree");
5314 goto done;
5318 error = apply_unveil(got_repo_get_path(repo), 1,
5319 worktree ? got_worktree_get_root_path(worktree) : NULL);
5320 if (error)
5321 goto done;
5323 if ((!force_path && argc == 2) || ncommit_args > 0) {
5324 int obj_type = (ncommit_args > 0 ?
5325 GOT_OBJ_TYPE_COMMIT : GOT_OBJ_TYPE_ANY);
5326 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
5327 NULL);
5328 if (error)
5329 goto done;
5330 for (i = 0; i < (ncommit_args > 0 ? ncommit_args : argc); i++) {
5331 const char *arg;
5332 char *keyword_idstr = NULL;
5334 if (ncommit_args > 0)
5335 arg = commit_args[i];
5336 else
5337 arg = argv[i];
5339 error = got_keyword_to_idstr(&keyword_idstr, arg,
5340 repo, worktree);
5341 if (error != NULL)
5342 goto done;
5343 if (keyword_idstr != NULL)
5344 arg = keyword_idstr;
5346 error = got_repo_match_object_id(&ids[i], &labels[i],
5347 arg, obj_type, &refs, repo);
5348 free(keyword_idstr);
5349 if (error) {
5350 if (error->code != GOT_ERR_NOT_REF &&
5351 error->code != GOT_ERR_NO_OBJ)
5352 goto done;
5353 if (ncommit_args > 0)
5354 goto done;
5355 error = NULL;
5356 break;
5361 f1 = got_opentemp();
5362 if (f1 == NULL) {
5363 error = got_error_from_errno("got_opentemp");
5364 goto done;
5367 f2 = got_opentemp();
5368 if (f2 == NULL) {
5369 error = got_error_from_errno("got_opentemp");
5370 goto done;
5373 outfile = got_opentemp();
5374 if (outfile == NULL) {
5375 error = got_error_from_errno("got_opentemp");
5376 goto done;
5379 if (ncommit_args == 0 && (ids[0] == NULL || ids[1] == NULL)) {
5380 struct print_diff_arg arg;
5381 char *id_str;
5383 if (worktree == NULL) {
5384 if (argc == 2 && ids[0] == NULL) {
5385 error = got_error_path(argv[0], GOT_ERR_NO_OBJ);
5386 goto done;
5387 } else if (argc == 2 && ids[1] == NULL) {
5388 error = got_error_path(argv[1], GOT_ERR_NO_OBJ);
5389 goto done;
5390 } else if (argc > 0) {
5391 error = got_error_fmt(GOT_ERR_NOT_WORKTREE,
5392 "%s", "specified paths cannot be resolved");
5393 goto done;
5394 } else {
5395 error = got_error(GOT_ERR_NOT_WORKTREE);
5396 goto done;
5400 error = get_worktree_paths_from_argv(&paths, argc, argv,
5401 worktree);
5402 if (error)
5403 goto done;
5405 error = got_object_id_str(&id_str,
5406 got_worktree_get_base_commit_id(worktree));
5407 if (error)
5408 goto done;
5409 arg.repo = repo;
5410 arg.worktree = worktree;
5411 arg.diff_algo = GOT_DIFF_ALGORITHM_PATIENCE;
5412 arg.diff_context = diff_context;
5413 arg.id_str = id_str;
5414 arg.header_shown = 0;
5415 arg.diff_staged = diff_staged;
5416 arg.ignore_whitespace = ignore_whitespace;
5417 arg.force_text_diff = force_text_diff;
5418 arg.diffstat = show_diffstat ? &dsa : NULL;
5419 arg.f1 = f1;
5420 arg.f2 = f2;
5421 arg.outfile = outfile;
5423 error = got_worktree_status(worktree, &paths, repo, 0,
5424 print_diff, &arg, check_cancelled, NULL);
5425 free(id_str);
5426 if (error)
5427 goto done;
5429 if (show_diffstat && dsa.nfiles > 0) {
5430 char *header;
5432 if (asprintf(&header, "diffstat %s%s",
5433 diff_staged ? "-s " : "",
5434 got_worktree_get_root_path(worktree)) == -1) {
5435 error = got_error_from_errno("asprintf");
5436 goto done;
5439 error = print_diffstat(&dsa, header);
5440 free(header);
5441 if (error)
5442 goto done;
5445 error = printfile(outfile);
5446 goto done;
5449 if (ncommit_args == 1) {
5450 struct got_commit_object *commit;
5451 error = got_object_open_as_commit(&commit, repo, ids[0]);
5452 if (error)
5453 goto done;
5455 labels[1] = labels[0];
5456 ids[1] = ids[0];
5457 if (got_object_commit_get_nparents(commit) > 0) {
5458 const struct got_object_id_queue *pids;
5459 struct got_object_qid *pid;
5460 pids = got_object_commit_get_parent_ids(commit);
5461 pid = STAILQ_FIRST(pids);
5462 ids[0] = got_object_id_dup(&pid->id);
5463 if (ids[0] == NULL) {
5464 error = got_error_from_errno(
5465 "got_object_id_dup");
5466 got_object_commit_close(commit);
5467 goto done;
5469 error = got_object_id_str(&labels[0], ids[0]);
5470 if (error) {
5471 got_object_commit_close(commit);
5472 goto done;
5474 } else {
5475 ids[0] = NULL;
5476 labels[0] = strdup("/dev/null");
5477 if (labels[0] == NULL) {
5478 error = got_error_from_errno("strdup");
5479 got_object_commit_close(commit);
5480 goto done;
5484 got_object_commit_close(commit);
5487 if (ncommit_args == 0 && argc > 2) {
5488 error = got_error_msg(GOT_ERR_BAD_PATH,
5489 "path arguments cannot be used when diffing two objects");
5490 goto done;
5493 if (ids[0]) {
5494 error = got_object_get_type(&type1, repo, ids[0]);
5495 if (error)
5496 goto done;
5499 error = got_object_get_type(&type2, repo, ids[1]);
5500 if (error)
5501 goto done;
5502 if (type1 != GOT_OBJ_TYPE_ANY && type1 != type2) {
5503 error = got_error(GOT_ERR_OBJ_TYPE);
5504 goto done;
5506 if (type1 == GOT_OBJ_TYPE_BLOB && argc > 2) {
5507 error = got_error_msg(GOT_ERR_OBJ_TYPE,
5508 "path arguments cannot be used when diffing blobs");
5509 goto done;
5512 for (i = 0; ncommit_args > 0 && i < argc; i++) {
5513 char *in_repo_path;
5514 struct got_pathlist_entry *new;
5515 if (worktree) {
5516 const char *prefix;
5517 char *p;
5518 error = got_worktree_resolve_path(&p, worktree,
5519 argv[i]);
5520 if (error)
5521 goto done;
5522 prefix = got_worktree_get_path_prefix(worktree);
5523 while (prefix[0] == '/')
5524 prefix++;
5525 if (asprintf(&in_repo_path, "%s%s%s", prefix,
5526 (p[0] != '\0' && prefix[0] != '\0') ? "/" : "",
5527 p) == -1) {
5528 error = got_error_from_errno("asprintf");
5529 free(p);
5530 goto done;
5532 free(p);
5533 } else {
5534 char *mapped_path, *s;
5535 error = got_repo_map_path(&mapped_path, repo, argv[i]);
5536 if (error)
5537 goto done;
5538 s = mapped_path;
5539 while (s[0] == '/')
5540 s++;
5541 in_repo_path = strdup(s);
5542 if (in_repo_path == NULL) {
5543 error = got_error_from_errno("asprintf");
5544 free(mapped_path);
5545 goto done;
5547 free(mapped_path);
5550 error = got_pathlist_insert(&new, &paths, in_repo_path, NULL);
5551 if (error || new == NULL /* duplicate */)
5552 free(in_repo_path);
5553 if (error)
5554 goto done;
5557 if (worktree) {
5558 /* Release work tree lock. */
5559 got_worktree_close(worktree);
5560 worktree = NULL;
5563 fd1 = got_opentempfd();
5564 if (fd1 == -1) {
5565 error = got_error_from_errno("got_opentempfd");
5566 goto done;
5569 fd2 = got_opentempfd();
5570 if (fd2 == -1) {
5571 error = got_error_from_errno("got_opentempfd");
5572 goto done;
5575 switch (type1 == GOT_OBJ_TYPE_ANY ? type2 : type1) {
5576 case GOT_OBJ_TYPE_BLOB:
5577 error = got_diff_objects_as_blobs(NULL, NULL, f1, f2,
5578 fd1, fd2, ids[0], ids[1], NULL, NULL,
5579 GOT_DIFF_ALGORITHM_PATIENCE, diff_context,
5580 ignore_whitespace, force_text_diff,
5581 show_diffstat ? &dsa : NULL, repo, outfile);
5582 break;
5583 case GOT_OBJ_TYPE_TREE:
5584 error = got_diff_objects_as_trees(NULL, NULL, f1, f2, fd1, fd2,
5585 ids[0], ids[1], &paths, "", "",
5586 GOT_DIFF_ALGORITHM_PATIENCE, diff_context,
5587 ignore_whitespace, force_text_diff,
5588 show_diffstat ? &dsa : NULL, repo, outfile);
5589 break;
5590 case GOT_OBJ_TYPE_COMMIT:
5591 fprintf(outfile, "diff %s %s\n", labels[0], labels[1]);
5592 error = got_diff_objects_as_commits(NULL, NULL, f1, f2,
5593 fd1, fd2, ids[0], ids[1], &paths,
5594 GOT_DIFF_ALGORITHM_PATIENCE, diff_context,
5595 ignore_whitespace, force_text_diff,
5596 show_diffstat ? &dsa : NULL, repo, outfile);
5597 break;
5598 default:
5599 error = got_error(GOT_ERR_OBJ_TYPE);
5601 if (error)
5602 goto done;
5604 if (show_diffstat && dsa.nfiles > 0) {
5605 char *header = NULL;
5607 if (asprintf(&header, "diffstat %s %s",
5608 labels[0], labels[1]) == -1) {
5609 error = got_error_from_errno("asprintf");
5610 goto done;
5613 error = print_diffstat(&dsa, header);
5614 free(header);
5615 if (error)
5616 goto done;
5619 error = printfile(outfile);
5621 done:
5622 free(labels[0]);
5623 free(labels[1]);
5624 free(ids[0]);
5625 free(ids[1]);
5626 if (worktree)
5627 got_worktree_close(worktree);
5628 if (repo) {
5629 const struct got_error *close_err = got_repo_close(repo);
5630 if (error == NULL)
5631 error = close_err;
5633 if (pack_fds) {
5634 const struct got_error *pack_err =
5635 got_repo_pack_fds_close(pack_fds);
5636 if (error == NULL)
5637 error = pack_err;
5639 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
5640 got_pathlist_free(&diffstat_paths, GOT_PATHLIST_FREE_ALL);
5641 got_ref_list_free(&refs);
5642 if (outfile && fclose(outfile) == EOF && error == NULL)
5643 error = got_error_from_errno("fclose");
5644 if (f1 && fclose(f1) == EOF && error == NULL)
5645 error = got_error_from_errno("fclose");
5646 if (f2 && fclose(f2) == EOF && error == NULL)
5647 error = got_error_from_errno("fclose");
5648 if (fd1 != -1 && close(fd1) == -1 && error == NULL)
5649 error = got_error_from_errno("close");
5650 if (fd2 != -1 && close(fd2) == -1 && error == NULL)
5651 error = got_error_from_errno("close");
5652 return error;
5655 __dead static void
5656 usage_blame(void)
5658 fprintf(stderr,
5659 "usage: %s blame [-c commit] [-r repository-path] path\n",
5660 getprogname());
5661 exit(1);
5664 struct blame_line {
5665 int annotated;
5666 char *id_str;
5667 char *committer;
5668 char datebuf[11]; /* YYYY-MM-DD + NUL */
5671 struct blame_cb_args {
5672 struct blame_line *lines;
5673 int nlines;
5674 int nlines_prec;
5675 int lineno_cur;
5676 off_t *line_offsets;
5677 FILE *f;
5678 struct got_repository *repo;
5681 static const struct got_error *
5682 blame_cb(void *arg, int nlines, int lineno,
5683 struct got_commit_object *commit, struct got_object_id *id)
5685 const struct got_error *err = NULL;
5686 struct blame_cb_args *a = arg;
5687 struct blame_line *bline;
5688 char *line = NULL;
5689 size_t linesize = 0;
5690 off_t offset;
5691 struct tm tm;
5692 time_t committer_time;
5694 if (nlines != a->nlines ||
5695 (lineno != -1 && lineno < 1) || lineno > a->nlines)
5696 return got_error(GOT_ERR_RANGE);
5698 if (sigint_received)
5699 return got_error(GOT_ERR_ITER_COMPLETED);
5701 if (lineno == -1)
5702 return NULL; /* no change in this commit */
5704 /* Annotate this line. */
5705 bline = &a->lines[lineno - 1];
5706 if (bline->annotated)
5707 return NULL;
5708 err = got_object_id_str(&bline->id_str, id);
5709 if (err)
5710 return err;
5712 bline->committer = strdup(got_object_commit_get_committer(commit));
5713 if (bline->committer == NULL) {
5714 err = got_error_from_errno("strdup");
5715 goto done;
5718 committer_time = got_object_commit_get_committer_time(commit);
5719 if (gmtime_r(&committer_time, &tm) == NULL)
5720 return got_error_from_errno("gmtime_r");
5721 if (strftime(bline->datebuf, sizeof(bline->datebuf), "%G-%m-%d",
5722 &tm) == 0) {
5723 err = got_error(GOT_ERR_NO_SPACE);
5724 goto done;
5726 bline->annotated = 1;
5728 /* Print lines annotated so far. */
5729 bline = &a->lines[a->lineno_cur - 1];
5730 if (!bline->annotated)
5731 goto done;
5733 offset = a->line_offsets[a->lineno_cur - 1];
5734 if (fseeko(a->f, offset, SEEK_SET) == -1) {
5735 err = got_error_from_errno("fseeko");
5736 goto done;
5739 while (a->lineno_cur <= a->nlines && bline->annotated) {
5740 char *smallerthan, *at, *nl, *committer;
5741 size_t len;
5743 if (getline(&line, &linesize, a->f) == -1) {
5744 if (ferror(a->f))
5745 err = got_error_from_errno("getline");
5746 break;
5749 committer = bline->committer;
5750 smallerthan = strchr(committer, '<');
5751 if (smallerthan && smallerthan[1] != '\0')
5752 committer = smallerthan + 1;
5753 at = strchr(committer, '@');
5754 if (at)
5755 *at = '\0';
5756 len = strlen(committer);
5757 if (len >= 9)
5758 committer[8] = '\0';
5760 nl = strchr(line, '\n');
5761 if (nl)
5762 *nl = '\0';
5763 printf("%.*d) %.8s %s %-8s %s\n", a->nlines_prec, a->lineno_cur,
5764 bline->id_str, bline->datebuf, committer, line);
5766 a->lineno_cur++;
5767 bline = &a->lines[a->lineno_cur - 1];
5769 done:
5770 free(line);
5771 return err;
5774 static const struct got_error *
5775 cmd_blame(int argc, char *argv[])
5777 const struct got_error *error;
5778 struct got_repository *repo = NULL;
5779 struct got_worktree *worktree = NULL;
5780 char *path, *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
5781 char *link_target = NULL;
5782 struct got_object_id *obj_id = NULL;
5783 struct got_object_id *commit_id = NULL;
5784 struct got_commit_object *commit = NULL;
5785 struct got_blob_object *blob = NULL;
5786 char *commit_id_str = NULL, *keyword_idstr = NULL;
5787 struct blame_cb_args bca;
5788 int ch, obj_type, i, fd1 = -1, fd2 = -1, fd3 = -1;
5789 off_t filesize;
5790 int *pack_fds = NULL;
5791 FILE *f1 = NULL, *f2 = NULL;
5793 fd1 = got_opentempfd();
5794 if (fd1 == -1)
5795 return got_error_from_errno("got_opentempfd");
5797 memset(&bca, 0, sizeof(bca));
5799 #ifndef PROFILE
5800 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
5801 NULL) == -1)
5802 err(1, "pledge");
5803 #endif
5805 while ((ch = getopt(argc, argv, "c:r:")) != -1) {
5806 switch (ch) {
5807 case 'c':
5808 commit_id_str = optarg;
5809 break;
5810 case 'r':
5811 repo_path = realpath(optarg, NULL);
5812 if (repo_path == NULL)
5813 return got_error_from_errno2("realpath",
5814 optarg);
5815 got_path_strip_trailing_slashes(repo_path);
5816 break;
5817 default:
5818 usage_blame();
5819 /* NOTREACHED */
5823 argc -= optind;
5824 argv += optind;
5826 if (argc == 1)
5827 path = argv[0];
5828 else
5829 usage_blame();
5831 cwd = getcwd(NULL, 0);
5832 if (cwd == NULL) {
5833 error = got_error_from_errno("getcwd");
5834 goto done;
5837 error = got_repo_pack_fds_open(&pack_fds);
5838 if (error != NULL)
5839 goto done;
5841 if (repo_path == NULL) {
5842 error = got_worktree_open(&worktree, cwd,
5843 GOT_WORKTREE_GOT_DIR);
5844 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5845 goto done;
5846 else
5847 error = NULL;
5848 if (worktree) {
5849 repo_path =
5850 strdup(got_worktree_get_repo_path(worktree));
5851 if (repo_path == NULL) {
5852 error = got_error_from_errno("strdup");
5853 if (error)
5854 goto done;
5856 } else {
5857 repo_path = strdup(cwd);
5858 if (repo_path == NULL) {
5859 error = got_error_from_errno("strdup");
5860 goto done;
5865 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
5866 if (error != NULL)
5867 goto done;
5869 if (worktree) {
5870 const char *prefix = got_worktree_get_path_prefix(worktree);
5871 char *p;
5873 error = got_worktree_resolve_path(&p, worktree, path);
5874 if (error)
5875 goto done;
5876 if (asprintf(&in_repo_path, "%s%s%s", prefix,
5877 (p[0] != '\0' && !got_path_is_root_dir(prefix)) ? "/" : "",
5878 p) == -1) {
5879 error = got_error_from_errno("asprintf");
5880 free(p);
5881 goto done;
5883 free(p);
5884 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5885 } else {
5886 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5887 if (error)
5888 goto done;
5889 error = got_repo_map_path(&in_repo_path, repo, path);
5891 if (error)
5892 goto done;
5894 if (commit_id_str == NULL) {
5895 struct got_reference *head_ref;
5896 error = got_ref_open(&head_ref, repo, worktree ?
5897 got_worktree_get_head_ref_name(worktree) : GOT_REF_HEAD, 0);
5898 if (error != NULL)
5899 goto done;
5900 error = got_ref_resolve(&commit_id, repo, head_ref);
5901 got_ref_close(head_ref);
5902 if (error != NULL)
5903 goto done;
5904 } else {
5905 struct got_reflist_head refs;
5907 TAILQ_INIT(&refs);
5908 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
5909 NULL);
5910 if (error)
5911 goto done;
5913 error = got_keyword_to_idstr(&keyword_idstr, commit_id_str,
5914 repo, worktree);
5915 if (error != NULL)
5916 goto done;
5917 if (keyword_idstr != NULL)
5918 commit_id_str = keyword_idstr;
5920 error = got_repo_match_object_id(&commit_id, NULL,
5921 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
5922 got_ref_list_free(&refs);
5923 if (error)
5924 goto done;
5927 if (worktree) {
5928 /* Release work tree lock. */
5929 got_worktree_close(worktree);
5930 worktree = NULL;
5933 error = got_object_open_as_commit(&commit, repo, commit_id);
5934 if (error)
5935 goto done;
5937 error = got_object_resolve_symlinks(&link_target, in_repo_path,
5938 commit, repo);
5939 if (error)
5940 goto done;
5942 error = got_object_id_by_path(&obj_id, repo, commit,
5943 link_target ? link_target : in_repo_path);
5944 if (error)
5945 goto done;
5947 error = got_object_get_type(&obj_type, repo, obj_id);
5948 if (error)
5949 goto done;
5951 if (obj_type != GOT_OBJ_TYPE_BLOB) {
5952 error = got_error_path(link_target ? link_target : in_repo_path,
5953 GOT_ERR_OBJ_TYPE);
5954 goto done;
5957 error = got_object_open_as_blob(&blob, repo, obj_id, 8192, fd1);
5958 if (error)
5959 goto done;
5960 bca.f = got_opentemp();
5961 if (bca.f == NULL) {
5962 error = got_error_from_errno("got_opentemp");
5963 goto done;
5965 error = got_object_blob_dump_to_file(&filesize, &bca.nlines,
5966 &bca.line_offsets, bca.f, blob);
5967 if (error || bca.nlines == 0)
5968 goto done;
5970 /* Don't include \n at EOF in the blame line count. */
5971 if (bca.line_offsets[bca.nlines - 1] == filesize)
5972 bca.nlines--;
5974 bca.lines = calloc(bca.nlines, sizeof(*bca.lines));
5975 if (bca.lines == NULL) {
5976 error = got_error_from_errno("calloc");
5977 goto done;
5979 bca.lineno_cur = 1;
5980 bca.nlines_prec = 0;
5981 i = bca.nlines;
5982 while (i > 0) {
5983 i /= 10;
5984 bca.nlines_prec++;
5986 bca.repo = repo;
5988 fd2 = got_opentempfd();
5989 if (fd2 == -1) {
5990 error = got_error_from_errno("got_opentempfd");
5991 goto done;
5993 fd3 = got_opentempfd();
5994 if (fd3 == -1) {
5995 error = got_error_from_errno("got_opentempfd");
5996 goto done;
5998 f1 = got_opentemp();
5999 if (f1 == NULL) {
6000 error = got_error_from_errno("got_opentemp");
6001 goto done;
6003 f2 = got_opentemp();
6004 if (f2 == NULL) {
6005 error = got_error_from_errno("got_opentemp");
6006 goto done;
6008 error = got_blame(link_target ? link_target : in_repo_path, commit_id,
6009 repo, GOT_DIFF_ALGORITHM_PATIENCE, blame_cb, &bca,
6010 check_cancelled, NULL, fd2, fd3, f1, f2);
6011 done:
6012 free(keyword_idstr);
6013 free(in_repo_path);
6014 free(link_target);
6015 free(repo_path);
6016 free(cwd);
6017 free(commit_id);
6018 free(obj_id);
6019 if (commit)
6020 got_object_commit_close(commit);
6022 if (fd1 != -1 && close(fd1) == -1 && error == NULL)
6023 error = got_error_from_errno("close");
6024 if (fd2 != -1 && close(fd2) == -1 && error == NULL)
6025 error = got_error_from_errno("close");
6026 if (fd3 != -1 && close(fd3) == -1 && error == NULL)
6027 error = got_error_from_errno("close");
6028 if (f1 && fclose(f1) == EOF && error == NULL)
6029 error = got_error_from_errno("fclose");
6030 if (f2 && fclose(f2) == EOF && error == NULL)
6031 error = got_error_from_errno("fclose");
6033 if (blob)
6034 got_object_blob_close(blob);
6035 if (worktree)
6036 got_worktree_close(worktree);
6037 if (repo) {
6038 const struct got_error *close_err = got_repo_close(repo);
6039 if (error == NULL)
6040 error = close_err;
6042 if (pack_fds) {
6043 const struct got_error *pack_err =
6044 got_repo_pack_fds_close(pack_fds);
6045 if (error == NULL)
6046 error = pack_err;
6048 if (bca.lines) {
6049 for (i = 0; i < bca.nlines; i++) {
6050 struct blame_line *bline = &bca.lines[i];
6051 free(bline->id_str);
6052 free(bline->committer);
6054 free(bca.lines);
6056 free(bca.line_offsets);
6057 if (bca.f && fclose(bca.f) == EOF && error == NULL)
6058 error = got_error_from_errno("fclose");
6059 return error;
6062 __dead static void
6063 usage_tree(void)
6065 fprintf(stderr, "usage: %s tree [-iR] [-c commit] [-r repository-path] "
6066 "[path]\n", getprogname());
6067 exit(1);
6070 static const struct got_error *
6071 print_entry(struct got_tree_entry *te, const char *id, const char *path,
6072 const char *root_path, struct got_repository *repo)
6074 const struct got_error *err = NULL;
6075 int is_root_path = (strcmp(path, root_path) == 0);
6076 const char *modestr = "";
6077 mode_t mode = got_tree_entry_get_mode(te);
6078 char *link_target = NULL;
6080 path += strlen(root_path);
6081 while (path[0] == '/')
6082 path++;
6084 if (got_object_tree_entry_is_submodule(te))
6085 modestr = "$";
6086 else if (S_ISLNK(mode)) {
6087 int i;
6089 err = got_tree_entry_get_symlink_target(&link_target, te, repo);
6090 if (err)
6091 return err;
6092 for (i = 0; link_target[i] != '\0'; i++) {
6093 if (!isprint((unsigned char)link_target[i]))
6094 link_target[i] = '?';
6097 modestr = "@";
6099 else if (S_ISDIR(mode))
6100 modestr = "/";
6101 else if (mode & S_IXUSR)
6102 modestr = "*";
6104 printf("%s%s%s%s%s%s%s\n", id ? id : "", path,
6105 is_root_path ? "" : "/", got_tree_entry_get_name(te), modestr,
6106 link_target ? " -> ": "", link_target ? link_target : "");
6108 free(link_target);
6109 return NULL;
6112 static const struct got_error *
6113 print_tree(const char *path, struct got_commit_object *commit,
6114 int show_ids, int recurse, const char *root_path,
6115 struct got_repository *repo)
6117 const struct got_error *err = NULL;
6118 struct got_object_id *tree_id = NULL;
6119 struct got_tree_object *tree = NULL;
6120 int nentries, i;
6122 err = got_object_id_by_path(&tree_id, repo, commit, path);
6123 if (err)
6124 goto done;
6126 err = got_object_open_as_tree(&tree, repo, tree_id);
6127 if (err)
6128 goto done;
6129 nentries = got_object_tree_get_nentries(tree);
6130 for (i = 0; i < nentries; i++) {
6131 struct got_tree_entry *te;
6132 char *id = NULL;
6134 if (sigint_received || sigpipe_received)
6135 break;
6137 te = got_object_tree_get_entry(tree, i);
6138 if (show_ids) {
6139 char *id_str;
6140 err = got_object_id_str(&id_str,
6141 got_tree_entry_get_id(te));
6142 if (err)
6143 goto done;
6144 if (asprintf(&id, "%s ", id_str) == -1) {
6145 err = got_error_from_errno("asprintf");
6146 free(id_str);
6147 goto done;
6149 free(id_str);
6151 err = print_entry(te, id, path, root_path, repo);
6152 free(id);
6153 if (err)
6154 goto done;
6156 if (recurse && S_ISDIR(got_tree_entry_get_mode(te))) {
6157 char *child_path;
6158 if (asprintf(&child_path, "%s%s%s", path,
6159 path[0] == '/' && path[1] == '\0' ? "" : "/",
6160 got_tree_entry_get_name(te)) == -1) {
6161 err = got_error_from_errno("asprintf");
6162 goto done;
6164 err = print_tree(child_path, commit, show_ids, 1,
6165 root_path, repo);
6166 free(child_path);
6167 if (err)
6168 goto done;
6171 done:
6172 if (tree)
6173 got_object_tree_close(tree);
6174 free(tree_id);
6175 return err;
6178 static const struct got_error *
6179 cmd_tree(int argc, char *argv[])
6181 const struct got_error *error;
6182 struct got_repository *repo = NULL;
6183 struct got_worktree *worktree = NULL;
6184 const char *path, *refname = NULL;
6185 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
6186 struct got_object_id *commit_id = NULL;
6187 struct got_commit_object *commit = NULL;
6188 char *commit_id_str = NULL, *keyword_idstr = NULL;
6189 int show_ids = 0, recurse = 0;
6190 int ch;
6191 int *pack_fds = NULL;
6193 #ifndef PROFILE
6194 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
6195 NULL) == -1)
6196 err(1, "pledge");
6197 #endif
6199 while ((ch = getopt(argc, argv, "c:iRr:")) != -1) {
6200 switch (ch) {
6201 case 'c':
6202 commit_id_str = optarg;
6203 break;
6204 case 'i':
6205 show_ids = 1;
6206 break;
6207 case 'R':
6208 recurse = 1;
6209 break;
6210 case 'r':
6211 repo_path = realpath(optarg, NULL);
6212 if (repo_path == NULL)
6213 return got_error_from_errno2("realpath",
6214 optarg);
6215 got_path_strip_trailing_slashes(repo_path);
6216 break;
6217 default:
6218 usage_tree();
6219 /* NOTREACHED */
6223 argc -= optind;
6224 argv += optind;
6226 if (argc == 1)
6227 path = argv[0];
6228 else if (argc > 1)
6229 usage_tree();
6230 else
6231 path = NULL;
6233 cwd = getcwd(NULL, 0);
6234 if (cwd == NULL) {
6235 error = got_error_from_errno("getcwd");
6236 goto done;
6239 error = got_repo_pack_fds_open(&pack_fds);
6240 if (error != NULL)
6241 goto done;
6243 if (repo_path == NULL) {
6244 error = got_worktree_open(&worktree, cwd,
6245 GOT_WORKTREE_GOT_DIR);
6246 if (error && error->code != GOT_ERR_NOT_WORKTREE)
6247 goto done;
6248 else
6249 error = NULL;
6250 if (worktree) {
6251 repo_path =
6252 strdup(got_worktree_get_repo_path(worktree));
6253 if (repo_path == NULL)
6254 error = got_error_from_errno("strdup");
6255 if (error)
6256 goto done;
6257 } else {
6258 repo_path = strdup(cwd);
6259 if (repo_path == NULL) {
6260 error = got_error_from_errno("strdup");
6261 goto done;
6266 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
6267 if (error != NULL)
6268 goto done;
6270 if (worktree) {
6271 const char *prefix = got_worktree_get_path_prefix(worktree);
6272 char *p;
6274 if (path == NULL || got_path_is_root_dir(path))
6275 path = "";
6276 error = got_worktree_resolve_path(&p, worktree, path);
6277 if (error)
6278 goto done;
6279 if (asprintf(&in_repo_path, "%s%s%s", prefix,
6280 (p[0] != '\0' && !got_path_is_root_dir(prefix)) ? "/" : "",
6281 p) == -1) {
6282 error = got_error_from_errno("asprintf");
6283 free(p);
6284 goto done;
6286 free(p);
6287 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
6288 if (error)
6289 goto done;
6290 } else {
6291 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
6292 if (error)
6293 goto done;
6294 if (path == NULL)
6295 path = "/";
6296 error = got_repo_map_path(&in_repo_path, repo, path);
6297 if (error != NULL)
6298 goto done;
6301 if (commit_id_str == NULL) {
6302 struct got_reference *head_ref;
6303 if (worktree)
6304 refname = got_worktree_get_head_ref_name(worktree);
6305 else
6306 refname = GOT_REF_HEAD;
6307 error = got_ref_open(&head_ref, repo, refname, 0);
6308 if (error != NULL)
6309 goto done;
6310 error = got_ref_resolve(&commit_id, repo, head_ref);
6311 got_ref_close(head_ref);
6312 if (error != NULL)
6313 goto done;
6314 } else {
6315 struct got_reflist_head refs;
6317 TAILQ_INIT(&refs);
6318 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
6319 NULL);
6320 if (error)
6321 goto done;
6323 error = got_keyword_to_idstr(&keyword_idstr, commit_id_str,
6324 repo, worktree);
6325 if (error != NULL)
6326 goto done;
6327 if (keyword_idstr != NULL)
6328 commit_id_str = keyword_idstr;
6330 error = got_repo_match_object_id(&commit_id, NULL,
6331 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
6332 got_ref_list_free(&refs);
6333 if (error)
6334 goto done;
6337 if (worktree) {
6338 /* Release work tree lock. */
6339 got_worktree_close(worktree);
6340 worktree = NULL;
6343 error = got_object_open_as_commit(&commit, repo, commit_id);
6344 if (error)
6345 goto done;
6347 error = print_tree(in_repo_path, commit, show_ids, recurse,
6348 in_repo_path, repo);
6349 done:
6350 free(keyword_idstr);
6351 free(in_repo_path);
6352 free(repo_path);
6353 free(cwd);
6354 free(commit_id);
6355 if (commit)
6356 got_object_commit_close(commit);
6357 if (worktree)
6358 got_worktree_close(worktree);
6359 if (repo) {
6360 const struct got_error *close_err = got_repo_close(repo);
6361 if (error == NULL)
6362 error = close_err;
6364 if (pack_fds) {
6365 const struct got_error *pack_err =
6366 got_repo_pack_fds_close(pack_fds);
6367 if (error == NULL)
6368 error = pack_err;
6370 return error;
6373 __dead static void
6374 usage_status(void)
6376 fprintf(stderr, "usage: %s status [-I] [-S status-codes] "
6377 "[-s status-codes] [path ...]\n", getprogname());
6378 exit(1);
6381 struct got_status_arg {
6382 char *status_codes;
6383 int suppress;
6386 static const struct got_error *
6387 print_status(void *arg, unsigned char status, unsigned char staged_status,
6388 const char *path, struct got_object_id *blob_id,
6389 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
6390 int dirfd, const char *de_name)
6392 struct got_status_arg *st = arg;
6394 if (status == staged_status && (status == GOT_STATUS_DELETE))
6395 status = GOT_STATUS_NO_CHANGE;
6396 if (st != NULL && st->status_codes) {
6397 size_t ncodes = strlen(st->status_codes);
6398 int i, j = 0;
6400 for (i = 0; i < ncodes ; i++) {
6401 if (st->suppress) {
6402 if (status == st->status_codes[i] ||
6403 staged_status == st->status_codes[i]) {
6404 j++;
6405 continue;
6407 } else {
6408 if (status == st->status_codes[i] ||
6409 staged_status == st->status_codes[i])
6410 break;
6414 if (st->suppress && j == 0)
6415 goto print;
6417 if (i == ncodes)
6418 return NULL;
6420 print:
6421 printf("%c%c %s\n", status, staged_status, path);
6422 return NULL;
6425 static const struct got_error *
6426 cmd_status(int argc, char *argv[])
6428 const struct got_error *close_err, *error = NULL;
6429 struct got_repository *repo = NULL;
6430 struct got_worktree *worktree = NULL;
6431 struct got_status_arg st;
6432 char *cwd = NULL;
6433 struct got_pathlist_head paths;
6434 int ch, i, no_ignores = 0;
6435 int *pack_fds = NULL;
6437 TAILQ_INIT(&paths);
6439 memset(&st, 0, sizeof(st));
6440 st.status_codes = NULL;
6441 st.suppress = 0;
6443 #ifndef PROFILE
6444 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
6445 NULL) == -1)
6446 err(1, "pledge");
6447 #endif
6449 while ((ch = getopt(argc, argv, "IS:s:")) != -1) {
6450 switch (ch) {
6451 case 'I':
6452 no_ignores = 1;
6453 break;
6454 case 'S':
6455 if (st.status_codes != NULL && st.suppress == 0)
6456 option_conflict('S', 's');
6457 st.suppress = 1;
6458 /* fallthrough */
6459 case 's':
6460 for (i = 0; optarg[i] != '\0'; i++) {
6461 switch (optarg[i]) {
6462 case GOT_STATUS_MODIFY:
6463 case GOT_STATUS_ADD:
6464 case GOT_STATUS_DELETE:
6465 case GOT_STATUS_CONFLICT:
6466 case GOT_STATUS_MISSING:
6467 case GOT_STATUS_OBSTRUCTED:
6468 case GOT_STATUS_UNVERSIONED:
6469 case GOT_STATUS_MODE_CHANGE:
6470 case GOT_STATUS_NONEXISTENT:
6471 break;
6472 default:
6473 errx(1, "invalid status code '%c'",
6474 optarg[i]);
6477 if (ch == 's' && st.suppress)
6478 option_conflict('s', 'S');
6479 st.status_codes = optarg;
6480 break;
6481 default:
6482 usage_status();
6483 /* NOTREACHED */
6487 argc -= optind;
6488 argv += optind;
6490 cwd = getcwd(NULL, 0);
6491 if (cwd == NULL) {
6492 error = got_error_from_errno("getcwd");
6493 goto done;
6496 error = got_repo_pack_fds_open(&pack_fds);
6497 if (error != NULL)
6498 goto done;
6500 error = got_worktree_open(&worktree, cwd,
6501 GOT_WORKTREE_GOT_DIR);
6502 if (error) {
6503 if (error->code == GOT_ERR_NOT_WORKTREE)
6504 error = wrap_not_worktree_error(error, "status", cwd);
6505 goto done;
6508 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
6509 NULL, pack_fds);
6510 if (error != NULL)
6511 goto done;
6513 error = apply_unveil(got_repo_get_path(repo), 1,
6514 got_worktree_get_root_path(worktree));
6515 if (error)
6516 goto done;
6518 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
6519 if (error)
6520 goto done;
6522 error = got_worktree_status(worktree, &paths, repo, no_ignores,
6523 print_status, &st, check_cancelled, NULL);
6524 done:
6525 if (pack_fds) {
6526 const struct got_error *pack_err =
6527 got_repo_pack_fds_close(pack_fds);
6528 if (error == NULL)
6529 error = pack_err;
6531 if (repo) {
6532 close_err = got_repo_close(repo);
6533 if (error == NULL)
6534 error = close_err;
6536 if (worktree != NULL) {
6537 close_err = got_worktree_close(worktree);
6538 if (error == NULL)
6539 error = close_err;
6542 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
6543 free(cwd);
6544 return error;
6547 __dead static void
6548 usage_ref(void)
6550 fprintf(stderr, "usage: %s ref [-dlt] [-c object] [-r repository-path] "
6551 "[-s reference] [name]\n", getprogname());
6552 exit(1);
6555 static const struct got_error *
6556 list_refs(struct got_repository *repo, const char *refname, int sort_by_time)
6558 static const struct got_error *err = NULL;
6559 struct got_reflist_head refs;
6560 struct got_reflist_entry *re;
6562 TAILQ_INIT(&refs);
6563 err = got_ref_list(&refs, repo, refname, sort_by_time ?
6564 got_ref_cmp_by_commit_timestamp_descending : got_ref_cmp_by_name,
6565 repo);
6566 if (err)
6567 return err;
6569 TAILQ_FOREACH(re, &refs, entry) {
6570 char *refstr;
6571 refstr = got_ref_to_str(re->ref);
6572 if (refstr == NULL) {
6573 err = got_error_from_errno("got_ref_to_str");
6574 break;
6576 printf("%s: %s\n", got_ref_get_name(re->ref), refstr);
6577 free(refstr);
6580 got_ref_list_free(&refs);
6581 return err;
6584 static const struct got_error *
6585 delete_ref_by_name(struct got_repository *repo, const char *refname)
6587 const struct got_error *err;
6588 struct got_reference *ref;
6590 err = got_ref_open(&ref, repo, refname, 0);
6591 if (err)
6592 return err;
6594 err = delete_ref(repo, ref);
6595 got_ref_close(ref);
6596 return err;
6599 static const struct got_error *
6600 add_ref(struct got_repository *repo, const char *refname, const char *target)
6602 const struct got_error *err = NULL;
6603 struct got_object_id *id = NULL;
6604 struct got_reference *ref = NULL;
6605 struct got_reflist_head refs;
6608 * Don't let the user create a reference name with a leading '-'.
6609 * While technically a valid reference name, this case is usually
6610 * an unintended typo.
6612 if (refname[0] == '-')
6613 return got_error_path(refname, GOT_ERR_REF_NAME_MINUS);
6615 TAILQ_INIT(&refs);
6616 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
6617 if (err)
6618 goto done;
6619 err = got_repo_match_object_id(&id, NULL, target, GOT_OBJ_TYPE_ANY,
6620 &refs, repo);
6621 got_ref_list_free(&refs);
6622 if (err)
6623 goto done;
6625 err = got_ref_alloc(&ref, refname, id);
6626 if (err)
6627 goto done;
6629 err = got_ref_write(ref, repo);
6630 done:
6631 if (ref)
6632 got_ref_close(ref);
6633 free(id);
6634 return err;
6637 static const struct got_error *
6638 add_symref(struct got_repository *repo, const char *refname, const char *target)
6640 const struct got_error *err = NULL;
6641 struct got_reference *ref = NULL;
6642 struct got_reference *target_ref = NULL;
6645 * Don't let the user create a reference name with a leading '-'.
6646 * While technically a valid reference name, this case is usually
6647 * an unintended typo.
6649 if (refname[0] == '-')
6650 return got_error_path(refname, GOT_ERR_REF_NAME_MINUS);
6652 err = got_ref_open(&target_ref, repo, target, 0);
6653 if (err)
6654 return err;
6656 err = got_ref_alloc_symref(&ref, refname, target_ref);
6657 if (err)
6658 goto done;
6660 err = got_ref_write(ref, repo);
6661 done:
6662 if (target_ref)
6663 got_ref_close(target_ref);
6664 if (ref)
6665 got_ref_close(ref);
6666 return err;
6669 static const struct got_error *
6670 cmd_ref(int argc, char *argv[])
6672 const struct got_error *error = NULL;
6673 struct got_repository *repo = NULL;
6674 struct got_worktree *worktree = NULL;
6675 char *cwd = NULL, *repo_path = NULL;
6676 int ch, do_list = 0, do_delete = 0, sort_by_time = 0;
6677 const char *obj_arg = NULL, *symref_target= NULL;
6678 char *refname = NULL, *keyword_idstr = NULL;
6679 int *pack_fds = NULL;
6681 #ifndef PROFILE
6682 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
6683 "sendfd unveil", NULL) == -1)
6684 err(1, "pledge");
6685 #endif
6687 while ((ch = getopt(argc, argv, "c:dlr:s:t")) != -1) {
6688 switch (ch) {
6689 case 'c':
6690 obj_arg = optarg;
6691 break;
6692 case 'd':
6693 do_delete = 1;
6694 break;
6695 case 'l':
6696 do_list = 1;
6697 break;
6698 case 'r':
6699 repo_path = realpath(optarg, NULL);
6700 if (repo_path == NULL)
6701 return got_error_from_errno2("realpath",
6702 optarg);
6703 got_path_strip_trailing_slashes(repo_path);
6704 break;
6705 case 's':
6706 symref_target = optarg;
6707 break;
6708 case 't':
6709 sort_by_time = 1;
6710 break;
6711 default:
6712 usage_ref();
6713 /* NOTREACHED */
6717 if (obj_arg && do_list)
6718 option_conflict('c', 'l');
6719 if (obj_arg && do_delete)
6720 option_conflict('c', 'd');
6721 if (obj_arg && symref_target)
6722 option_conflict('c', 's');
6723 if (symref_target && do_delete)
6724 option_conflict('s', 'd');
6725 if (symref_target && do_list)
6726 option_conflict('s', 'l');
6727 if (do_delete && do_list)
6728 option_conflict('d', 'l');
6729 if (sort_by_time && !do_list)
6730 errx(1, "-t option requires -l option");
6732 argc -= optind;
6733 argv += optind;
6735 if (do_list) {
6736 if (argc != 0 && argc != 1)
6737 usage_ref();
6738 if (argc == 1) {
6739 refname = strdup(argv[0]);
6740 if (refname == NULL) {
6741 error = got_error_from_errno("strdup");
6742 goto done;
6745 } else {
6746 if (argc != 1)
6747 usage_ref();
6748 refname = strdup(argv[0]);
6749 if (refname == NULL) {
6750 error = got_error_from_errno("strdup");
6751 goto done;
6755 if (refname)
6756 got_path_strip_trailing_slashes(refname);
6758 cwd = getcwd(NULL, 0);
6759 if (cwd == NULL) {
6760 error = got_error_from_errno("getcwd");
6761 goto done;
6764 error = got_repo_pack_fds_open(&pack_fds);
6765 if (error != NULL)
6766 goto done;
6768 if (repo_path == NULL) {
6769 error = got_worktree_open(&worktree, cwd,
6770 GOT_WORKTREE_GOT_DIR);
6771 if (error && error->code != GOT_ERR_NOT_WORKTREE)
6772 goto done;
6773 else
6774 error = NULL;
6775 if (worktree) {
6776 repo_path =
6777 strdup(got_worktree_get_repo_path(worktree));
6778 if (repo_path == NULL)
6779 error = got_error_from_errno("strdup");
6780 if (error)
6781 goto done;
6782 } else {
6783 repo_path = strdup(cwd);
6784 if (repo_path == NULL) {
6785 error = got_error_from_errno("strdup");
6786 goto done;
6791 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
6792 if (error != NULL)
6793 goto done;
6795 #ifndef PROFILE
6796 if (do_list) {
6797 /* Remove "cpath" promise. */
6798 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
6799 NULL) == -1)
6800 err(1, "pledge");
6802 #endif
6804 error = apply_unveil(got_repo_get_path(repo), do_list,
6805 worktree ? got_worktree_get_root_path(worktree) : NULL);
6806 if (error)
6807 goto done;
6809 if (do_list)
6810 error = list_refs(repo, refname, sort_by_time);
6811 else if (do_delete)
6812 error = delete_ref_by_name(repo, refname);
6813 else if (symref_target)
6814 error = add_symref(repo, refname, symref_target);
6815 else {
6816 if (obj_arg == NULL)
6817 usage_ref();
6819 error = got_keyword_to_idstr(&keyword_idstr, obj_arg,
6820 repo, worktree);
6821 if (error != NULL)
6822 goto done;
6823 if (keyword_idstr != NULL)
6824 obj_arg = keyword_idstr;
6826 error = add_ref(repo, refname, obj_arg);
6828 done:
6829 free(refname);
6830 if (repo) {
6831 const struct got_error *close_err = got_repo_close(repo);
6832 if (error == NULL)
6833 error = close_err;
6835 if (worktree)
6836 got_worktree_close(worktree);
6837 if (pack_fds) {
6838 const struct got_error *pack_err =
6839 got_repo_pack_fds_close(pack_fds);
6840 if (error == NULL)
6841 error = pack_err;
6843 free(cwd);
6844 free(repo_path);
6845 free(keyword_idstr);
6846 return error;
6849 __dead static void
6850 usage_branch(void)
6852 fprintf(stderr, "usage: %s branch [-lnt] [-c commit] [-d name] "
6853 "[-r repository-path] [name]\n", getprogname());
6854 exit(1);
6857 static const struct got_error *
6858 list_branch(struct got_repository *repo, struct got_worktree *worktree,
6859 struct got_reference *ref)
6861 const struct got_error *err = NULL;
6862 const char *refname;
6863 char *refstr;
6864 char marker = ' ';
6866 refname = got_ref_get_name(ref);
6867 if (worktree && strcmp(refname,
6868 got_worktree_get_head_ref_name(worktree)) == 0) {
6869 err = got_worktree_get_state(&marker, repo, worktree,
6870 check_cancelled, NULL);
6871 if (err != NULL)
6872 return err;
6875 if (strncmp(refname, "refs/heads/", 11) == 0)
6876 refname += 11;
6877 if (strncmp(refname, "refs/got/worktree/", 18) == 0)
6878 refname += 18;
6879 if (strncmp(refname, "refs/remotes/", 13) == 0)
6880 refname += 13;
6882 refstr = got_ref_to_str(ref);
6883 if (refstr == NULL)
6884 return got_error_from_errno("got_ref_to_str");
6886 printf("%c %s: %s\n", marker, refname, refstr);
6887 free(refstr);
6888 return NULL;
6891 static const struct got_error *
6892 show_current_branch(struct got_repository *repo, struct got_worktree *worktree)
6894 const char *refname;
6896 if (worktree == NULL)
6897 return got_error(GOT_ERR_NOT_WORKTREE);
6899 refname = got_worktree_get_head_ref_name(worktree);
6901 if (strncmp(refname, "refs/heads/", 11) == 0)
6902 refname += 11;
6903 if (strncmp(refname, "refs/got/worktree/", 18) == 0)
6904 refname += 18;
6906 printf("%s\n", refname);
6908 return NULL;
6911 static const struct got_error *
6912 list_branches(struct got_repository *repo, struct got_worktree *worktree,
6913 int sort_by_time)
6915 static const struct got_error *err = NULL;
6916 struct got_reflist_head refs;
6917 struct got_reflist_entry *re;
6918 struct got_reference *temp_ref = NULL;
6919 int rebase_in_progress, histedit_in_progress;
6921 TAILQ_INIT(&refs);
6923 if (worktree) {
6924 err = got_worktree_rebase_in_progress(&rebase_in_progress,
6925 worktree);
6926 if (err)
6927 return err;
6929 err = got_worktree_histedit_in_progress(&histedit_in_progress,
6930 worktree);
6931 if (err)
6932 return err;
6934 if (rebase_in_progress || histedit_in_progress) {
6935 err = got_ref_open(&temp_ref, repo,
6936 got_worktree_get_head_ref_name(worktree), 0);
6937 if (err)
6938 return err;
6939 list_branch(repo, worktree, temp_ref);
6940 got_ref_close(temp_ref);
6944 err = got_ref_list(&refs, repo, "refs/heads", sort_by_time ?
6945 got_ref_cmp_by_commit_timestamp_descending : got_ref_cmp_by_name,
6946 repo);
6947 if (err)
6948 return err;
6950 TAILQ_FOREACH(re, &refs, entry)
6951 list_branch(repo, worktree, re->ref);
6953 got_ref_list_free(&refs);
6955 err = got_ref_list(&refs, repo, "refs/remotes", sort_by_time ?
6956 got_ref_cmp_by_commit_timestamp_descending : got_ref_cmp_by_name,
6957 repo);
6958 if (err)
6959 return err;
6961 TAILQ_FOREACH(re, &refs, entry)
6962 list_branch(repo, worktree, re->ref);
6964 got_ref_list_free(&refs);
6966 return NULL;
6969 static const struct got_error *
6970 delete_branch(struct got_repository *repo, struct got_worktree *worktree,
6971 const char *branch_name)
6973 const struct got_error *err = NULL;
6974 struct got_reference *ref = NULL;
6975 char *refname, *remote_refname = NULL;
6977 if (strncmp(branch_name, "refs/", 5) == 0)
6978 branch_name += 5;
6979 if (strncmp(branch_name, "heads/", 6) == 0)
6980 branch_name += 6;
6981 else if (strncmp(branch_name, "remotes/", 8) == 0)
6982 branch_name += 8;
6984 if (asprintf(&refname, "refs/heads/%s", branch_name) == -1)
6985 return got_error_from_errno("asprintf");
6987 if (asprintf(&remote_refname, "refs/remotes/%s",
6988 branch_name) == -1) {
6989 err = got_error_from_errno("asprintf");
6990 goto done;
6993 err = got_ref_open(&ref, repo, refname, 0);
6994 if (err) {
6995 const struct got_error *err2;
6996 if (err->code != GOT_ERR_NOT_REF)
6997 goto done;
6999 * Keep 'err' intact such that if neither branch exists
7000 * we report "refs/heads" rather than "refs/remotes" in
7001 * our error message.
7003 err2 = got_ref_open(&ref, repo, remote_refname, 0);
7004 if (err2)
7005 goto done;
7006 err = NULL;
7009 if (worktree &&
7010 strcmp(got_worktree_get_head_ref_name(worktree),
7011 got_ref_get_name(ref)) == 0) {
7012 err = got_error_msg(GOT_ERR_SAME_BRANCH,
7013 "will not delete this work tree's current branch");
7014 goto done;
7017 err = delete_ref(repo, ref);
7018 done:
7019 if (ref)
7020 got_ref_close(ref);
7021 free(refname);
7022 free(remote_refname);
7023 return err;
7026 static const struct got_error *
7027 add_branch(struct got_repository *repo, const char *branch_name,
7028 struct got_object_id *base_commit_id)
7030 const struct got_error *err = NULL;
7031 struct got_reference *ref = NULL;
7032 char *refname = NULL;
7035 * Don't let the user create a branch name with a leading '-'.
7036 * While technically a valid reference name, this case is usually
7037 * an unintended typo.
7039 if (branch_name[0] == '-')
7040 return got_error_path(branch_name, GOT_ERR_REF_NAME_MINUS);
7042 if (strncmp(branch_name, "refs/heads/", 11) == 0)
7043 branch_name += 11;
7045 if (asprintf(&refname, "refs/heads/%s", branch_name) == -1) {
7046 err = got_error_from_errno("asprintf");
7047 goto done;
7050 err = got_ref_open(&ref, repo, refname, 0);
7051 if (err == NULL) {
7052 err = got_error(GOT_ERR_BRANCH_EXISTS);
7053 goto done;
7054 } else if (err->code != GOT_ERR_NOT_REF)
7055 goto done;
7057 err = got_ref_alloc(&ref, refname, base_commit_id);
7058 if (err)
7059 goto done;
7061 err = got_ref_write(ref, repo);
7062 done:
7063 if (ref)
7064 got_ref_close(ref);
7065 free(refname);
7066 return err;
7069 static const struct got_error *
7070 cmd_branch(int argc, char *argv[])
7072 const struct got_error *error = NULL;
7073 struct got_repository *repo = NULL;
7074 struct got_worktree *worktree = NULL;
7075 char *cwd = NULL, *repo_path = NULL;
7076 int ch, do_list = 0, do_show = 0, do_update = 1, sort_by_time = 0;
7077 const char *delref = NULL, *commit_id_arg = NULL;
7078 struct got_reference *ref = NULL;
7079 struct got_pathlist_head paths;
7080 struct got_object_id *commit_id = NULL;
7081 char *commit_id_str = NULL, *keyword_idstr = NULL;;
7082 int *pack_fds = NULL;
7084 TAILQ_INIT(&paths);
7086 #ifndef PROFILE
7087 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
7088 "sendfd unveil", NULL) == -1)
7089 err(1, "pledge");
7090 #endif
7092 while ((ch = getopt(argc, argv, "c:d:lnr:t")) != -1) {
7093 switch (ch) {
7094 case 'c':
7095 commit_id_arg = optarg;
7096 break;
7097 case 'd':
7098 delref = optarg;
7099 break;
7100 case 'l':
7101 do_list = 1;
7102 break;
7103 case 'n':
7104 do_update = 0;
7105 break;
7106 case 'r':
7107 repo_path = realpath(optarg, NULL);
7108 if (repo_path == NULL)
7109 return got_error_from_errno2("realpath",
7110 optarg);
7111 got_path_strip_trailing_slashes(repo_path);
7112 break;
7113 case 't':
7114 sort_by_time = 1;
7115 break;
7116 default:
7117 usage_branch();
7118 /* NOTREACHED */
7122 if (do_list && delref)
7123 option_conflict('l', 'd');
7124 if (sort_by_time && !do_list)
7125 errx(1, "-t option requires -l option");
7127 argc -= optind;
7128 argv += optind;
7130 if (!do_list && !delref && argc == 0)
7131 do_show = 1;
7133 if ((do_list || delref || do_show) && commit_id_arg != NULL)
7134 errx(1, "-c option can only be used when creating a branch");
7136 if (do_list || delref) {
7137 if (argc > 0)
7138 usage_branch();
7139 } else if (!do_show && argc != 1)
7140 usage_branch();
7142 cwd = getcwd(NULL, 0);
7143 if (cwd == NULL) {
7144 error = got_error_from_errno("getcwd");
7145 goto done;
7148 error = got_repo_pack_fds_open(&pack_fds);
7149 if (error != NULL)
7150 goto done;
7152 if (repo_path == NULL) {
7153 error = got_worktree_open(&worktree, cwd,
7154 GOT_WORKTREE_GOT_DIR);
7155 if (error && error->code != GOT_ERR_NOT_WORKTREE)
7156 goto done;
7157 else
7158 error = NULL;
7159 if (worktree) {
7160 repo_path =
7161 strdup(got_worktree_get_repo_path(worktree));
7162 if (repo_path == NULL)
7163 error = got_error_from_errno("strdup");
7164 if (error)
7165 goto done;
7166 } else {
7167 repo_path = strdup(cwd);
7168 if (repo_path == NULL) {
7169 error = got_error_from_errno("strdup");
7170 goto done;
7175 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
7176 if (error != NULL)
7177 goto done;
7179 #ifndef PROFILE
7180 if (do_list || do_show) {
7181 /* Remove "cpath" promise. */
7182 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
7183 NULL) == -1)
7184 err(1, "pledge");
7186 #endif
7188 error = apply_unveil(got_repo_get_path(repo), do_list,
7189 worktree ? got_worktree_get_root_path(worktree) : NULL);
7190 if (error)
7191 goto done;
7193 if (do_show)
7194 error = show_current_branch(repo, worktree);
7195 else if (do_list)
7196 error = list_branches(repo, worktree, sort_by_time);
7197 else if (delref)
7198 error = delete_branch(repo, worktree, delref);
7199 else {
7200 struct got_reflist_head refs;
7201 TAILQ_INIT(&refs);
7202 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
7203 NULL);
7204 if (error)
7205 goto done;
7206 if (commit_id_arg == NULL)
7207 commit_id_arg = worktree ?
7208 got_worktree_get_head_ref_name(worktree) :
7209 GOT_REF_HEAD;
7210 else {
7211 error = got_keyword_to_idstr(&keyword_idstr,
7212 commit_id_arg, repo, worktree);
7213 if (error != NULL)
7214 goto done;
7215 if (keyword_idstr != NULL)
7216 commit_id_arg = keyword_idstr;
7218 error = got_repo_match_object_id(&commit_id, NULL,
7219 commit_id_arg, GOT_OBJ_TYPE_COMMIT, &refs, repo);
7220 got_ref_list_free(&refs);
7221 if (error)
7222 goto done;
7223 error = add_branch(repo, argv[0], commit_id);
7224 if (error)
7225 goto done;
7226 if (worktree && do_update) {
7227 struct got_update_progress_arg upa;
7228 char *branch_refname = NULL;
7230 error = got_object_id_str(&commit_id_str, commit_id);
7231 if (error)
7232 goto done;
7233 error = get_worktree_paths_from_argv(&paths, 0, NULL,
7234 worktree);
7235 if (error)
7236 goto done;
7237 if (asprintf(&branch_refname, "refs/heads/%s", argv[0])
7238 == -1) {
7239 error = got_error_from_errno("asprintf");
7240 goto done;
7242 error = got_ref_open(&ref, repo, branch_refname, 0);
7243 free(branch_refname);
7244 if (error)
7245 goto done;
7246 error = switch_head_ref(ref, commit_id, worktree,
7247 repo);
7248 if (error)
7249 goto done;
7250 error = got_worktree_set_base_commit_id(worktree, repo,
7251 commit_id);
7252 if (error)
7253 goto done;
7254 memset(&upa, 0, sizeof(upa));
7255 error = got_worktree_checkout_files(worktree, &paths,
7256 repo, update_progress, &upa, check_cancelled,
7257 NULL);
7258 if (error)
7259 goto done;
7260 if (upa.did_something) {
7261 printf("Updated to %s: %s\n",
7262 got_worktree_get_head_ref_name(worktree),
7263 commit_id_str);
7265 print_update_progress_stats(&upa);
7268 done:
7269 free(keyword_idstr);
7270 if (ref)
7271 got_ref_close(ref);
7272 if (repo) {
7273 const struct got_error *close_err = got_repo_close(repo);
7274 if (error == NULL)
7275 error = close_err;
7277 if (worktree)
7278 got_worktree_close(worktree);
7279 if (pack_fds) {
7280 const struct got_error *pack_err =
7281 got_repo_pack_fds_close(pack_fds);
7282 if (error == NULL)
7283 error = pack_err;
7285 free(cwd);
7286 free(repo_path);
7287 free(commit_id);
7288 free(commit_id_str);
7289 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
7290 return error;
7294 __dead static void
7295 usage_tag(void)
7297 fprintf(stderr, "usage: %s tag [-lVv] [-c commit] [-m message] "
7298 "[-r repository-path] [-s signer-id] name\n", getprogname());
7299 exit(1);
7302 #if 0
7303 static const struct got_error *
7304 sort_tags(struct got_reflist_head *sorted, struct got_reflist_head *tags)
7306 const struct got_error *err = NULL;
7307 struct got_reflist_entry *re, *se, *new;
7308 struct got_object_id *re_id, *se_id;
7309 struct got_tag_object *re_tag, *se_tag;
7310 time_t re_time, se_time;
7312 STAILQ_FOREACH(re, tags, entry) {
7313 se = STAILQ_FIRST(sorted);
7314 if (se == NULL) {
7315 err = got_reflist_entry_dup(&new, re);
7316 if (err)
7317 return err;
7318 STAILQ_INSERT_HEAD(sorted, new, entry);
7319 continue;
7320 } else {
7321 err = got_ref_resolve(&re_id, repo, re->ref);
7322 if (err)
7323 break;
7324 err = got_object_open_as_tag(&re_tag, repo, re_id);
7325 free(re_id);
7326 if (err)
7327 break;
7328 re_time = got_object_tag_get_tagger_time(re_tag);
7329 got_object_tag_close(re_tag);
7332 while (se) {
7333 err = got_ref_resolve(&se_id, repo, re->ref);
7334 if (err)
7335 break;
7336 err = got_object_open_as_tag(&se_tag, repo, se_id);
7337 free(se_id);
7338 if (err)
7339 break;
7340 se_time = got_object_tag_get_tagger_time(se_tag);
7341 got_object_tag_close(se_tag);
7343 if (se_time > re_time) {
7344 err = got_reflist_entry_dup(&new, re);
7345 if (err)
7346 return err;
7347 STAILQ_INSERT_AFTER(sorted, se, new, entry);
7348 break;
7350 se = STAILQ_NEXT(se, entry);
7351 continue;
7354 done:
7355 return err;
7357 #endif
7359 static const struct got_error *
7360 get_tag_refname(char **refname, const char *tag_name)
7362 const struct got_error *err;
7364 if (strncmp("refs/tags/", tag_name, 10) == 0) {
7365 *refname = strdup(tag_name);
7366 if (*refname == NULL)
7367 return got_error_from_errno("strdup");
7368 } else if (asprintf(refname, "refs/tags/%s", tag_name) == -1) {
7369 err = got_error_from_errno("asprintf");
7370 *refname = NULL;
7371 return err;
7374 return NULL;
7377 static const struct got_error *
7378 list_tags(struct got_repository *repo, const char *tag_name, int verify_tags,
7379 const char *allowed_signers, const char *revoked_signers, int verbosity)
7381 static const struct got_error *err = NULL;
7382 struct got_reflist_head refs;
7383 struct got_reflist_entry *re;
7384 char *wanted_refname = NULL;
7385 int bad_sigs = 0;
7387 TAILQ_INIT(&refs);
7389 err = got_ref_list(&refs, repo, "refs/tags", got_ref_cmp_tags, repo);
7390 if (err)
7391 return err;
7393 if (tag_name) {
7394 struct got_reference *ref;
7395 err = get_tag_refname(&wanted_refname, tag_name);
7396 if (err)
7397 goto done;
7398 /* Wanted tag reference should exist. */
7399 err = got_ref_open(&ref, repo, wanted_refname, 0);
7400 if (err)
7401 goto done;
7402 got_ref_close(ref);
7405 TAILQ_FOREACH(re, &refs, entry) {
7406 const char *refname;
7407 char *refstr, *tagmsg0, *tagmsg, *line, *id_str, *datestr;
7408 char datebuf[26];
7409 const char *tagger, *ssh_sig = NULL;
7410 char *sig_msg = NULL;
7411 time_t tagger_time;
7412 struct got_object_id *id;
7413 struct got_tag_object *tag;
7414 struct got_commit_object *commit = NULL;
7416 refname = got_ref_get_name(re->ref);
7417 if (strncmp(refname, "refs/tags/", 10) != 0 ||
7418 (wanted_refname && strcmp(refname, wanted_refname) != 0))
7419 continue;
7420 refname += 10;
7421 refstr = got_ref_to_str(re->ref);
7422 if (refstr == NULL) {
7423 err = got_error_from_errno("got_ref_to_str");
7424 break;
7427 err = got_ref_resolve(&id, repo, re->ref);
7428 if (err)
7429 break;
7430 err = got_object_open_as_tag(&tag, repo, id);
7431 if (err) {
7432 if (err->code != GOT_ERR_OBJ_TYPE) {
7433 free(id);
7434 break;
7436 /* "lightweight" tag */
7437 err = got_object_open_as_commit(&commit, repo, id);
7438 if (err) {
7439 free(id);
7440 break;
7442 tagger = got_object_commit_get_committer(commit);
7443 tagger_time =
7444 got_object_commit_get_committer_time(commit);
7445 err = got_object_id_str(&id_str, id);
7446 free(id);
7447 if (err)
7448 break;
7449 } else {
7450 free(id);
7451 tagger = got_object_tag_get_tagger(tag);
7452 tagger_time = got_object_tag_get_tagger_time(tag);
7453 err = got_object_id_str(&id_str,
7454 got_object_tag_get_object_id(tag));
7455 if (err)
7456 break;
7459 if (tag && verify_tags) {
7460 ssh_sig = got_sigs_get_tagmsg_ssh_signature(
7461 got_object_tag_get_message(tag));
7462 if (ssh_sig && allowed_signers == NULL) {
7463 err = got_error_msg(
7464 GOT_ERR_VERIFY_TAG_SIGNATURE,
7465 "SSH signature verification requires "
7466 "setting allowed_signers in "
7467 "got.conf(5)");
7468 break;
7472 printf("%stag %s %s\n", GOT_COMMIT_SEP_STR, refname, refstr);
7473 free(refstr);
7474 printf("from: %s\n", tagger);
7475 datestr = get_datestr(&tagger_time, datebuf);
7476 if (datestr)
7477 printf("date: %s UTC\n", datestr);
7478 if (commit)
7479 printf("object: %s %s\n", GOT_OBJ_LABEL_COMMIT, id_str);
7480 else {
7481 switch (got_object_tag_get_object_type(tag)) {
7482 case GOT_OBJ_TYPE_BLOB:
7483 printf("object: %s %s\n", GOT_OBJ_LABEL_BLOB,
7484 id_str);
7485 break;
7486 case GOT_OBJ_TYPE_TREE:
7487 printf("object: %s %s\n", GOT_OBJ_LABEL_TREE,
7488 id_str);
7489 break;
7490 case GOT_OBJ_TYPE_COMMIT:
7491 printf("object: %s %s\n", GOT_OBJ_LABEL_COMMIT,
7492 id_str);
7493 break;
7494 case GOT_OBJ_TYPE_TAG:
7495 printf("object: %s %s\n", GOT_OBJ_LABEL_TAG,
7496 id_str);
7497 break;
7498 default:
7499 break;
7502 free(id_str);
7504 if (ssh_sig) {
7505 err = got_sigs_verify_tag_ssh(&sig_msg, tag, ssh_sig,
7506 allowed_signers, revoked_signers, verbosity);
7507 if (err && err->code == GOT_ERR_BAD_TAG_SIGNATURE)
7508 bad_sigs = 1;
7509 else if (err)
7510 break;
7511 printf("signature: %s", sig_msg);
7512 free(sig_msg);
7513 sig_msg = NULL;
7516 if (commit) {
7517 err = got_object_commit_get_logmsg(&tagmsg0, commit);
7518 if (err)
7519 break;
7520 got_object_commit_close(commit);
7521 } else {
7522 tagmsg0 = strdup(got_object_tag_get_message(tag));
7523 got_object_tag_close(tag);
7524 if (tagmsg0 == NULL) {
7525 err = got_error_from_errno("strdup");
7526 break;
7530 tagmsg = tagmsg0;
7531 do {
7532 line = strsep(&tagmsg, "\n");
7533 if (line)
7534 printf(" %s\n", line);
7535 } while (line);
7536 free(tagmsg0);
7538 done:
7539 got_ref_list_free(&refs);
7540 free(wanted_refname);
7542 if (err == NULL && bad_sigs)
7543 err = got_error(GOT_ERR_BAD_TAG_SIGNATURE);
7544 return err;
7547 static const struct got_error *
7548 get_tag_message(char **tagmsg, char **tagmsg_path, const char *commit_id_str,
7549 const char *tag_name, const char *repo_path)
7551 const struct got_error *err = NULL;
7552 char *template = NULL, *initial_content = NULL;
7553 char *editor = NULL;
7554 int initial_content_len;
7555 int fd = -1;
7557 if (asprintf(&template, GOT_TMPDIR_STR "/got-tagmsg") == -1) {
7558 err = got_error_from_errno("asprintf");
7559 goto done;
7562 initial_content_len = asprintf(&initial_content,
7563 "\n# tagging commit %s as %s\n",
7564 commit_id_str, tag_name);
7565 if (initial_content_len == -1) {
7566 err = got_error_from_errno("asprintf");
7567 goto done;
7570 err = got_opentemp_named_fd(tagmsg_path, &fd, template, "");
7571 if (err)
7572 goto done;
7574 if (write(fd, initial_content, initial_content_len) == -1) {
7575 err = got_error_from_errno2("write", *tagmsg_path);
7576 goto done;
7578 if (close(fd) == -1) {
7579 err = got_error_from_errno2("close", *tagmsg_path);
7580 goto done;
7582 fd = -1;
7584 err = get_editor(&editor);
7585 if (err)
7586 goto done;
7587 err = edit_logmsg(tagmsg, editor, *tagmsg_path, initial_content,
7588 initial_content_len, 1);
7589 done:
7590 free(initial_content);
7591 free(template);
7592 free(editor);
7594 if (fd != -1 && close(fd) == -1 && err == NULL)
7595 err = got_error_from_errno2("close", *tagmsg_path);
7597 if (err) {
7598 free(*tagmsg);
7599 *tagmsg = NULL;
7601 return err;
7604 static const struct got_error *
7605 add_tag(struct got_repository *repo, const char *tagger,
7606 const char *tag_name, const char *commit_arg, const char *tagmsg_arg,
7607 const char *signer_id, int verbosity)
7609 const struct got_error *err = NULL;
7610 struct got_object_id *commit_id = NULL, *tag_id = NULL;
7611 char *label = NULL, *commit_id_str = NULL;
7612 struct got_reference *ref = NULL;
7613 char *refname = NULL, *tagmsg = NULL;
7614 char *tagmsg_path = NULL, *tag_id_str = NULL;
7615 int preserve_tagmsg = 0;
7616 struct got_reflist_head refs;
7618 TAILQ_INIT(&refs);
7621 * Don't let the user create a tag name with a leading '-'.
7622 * While technically a valid reference name, this case is usually
7623 * an unintended typo.
7625 if (tag_name[0] == '-')
7626 return got_error_path(tag_name, GOT_ERR_REF_NAME_MINUS);
7628 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
7629 if (err)
7630 goto done;
7632 err = got_repo_match_object_id(&commit_id, &label, commit_arg,
7633 GOT_OBJ_TYPE_COMMIT, &refs, repo);
7634 if (err)
7635 goto done;
7637 err = got_object_id_str(&commit_id_str, commit_id);
7638 if (err)
7639 goto done;
7641 err = get_tag_refname(&refname, tag_name);
7642 if (err)
7643 goto done;
7644 if (strncmp("refs/tags/", tag_name, 10) == 0)
7645 tag_name += 10;
7647 err = got_ref_open(&ref, repo, refname, 0);
7648 if (err == NULL) {
7649 err = got_error(GOT_ERR_TAG_EXISTS);
7650 goto done;
7651 } else if (err->code != GOT_ERR_NOT_REF)
7652 goto done;
7654 if (tagmsg_arg == NULL) {
7655 err = get_tag_message(&tagmsg, &tagmsg_path, commit_id_str,
7656 tag_name, got_repo_get_path(repo));
7657 if (err) {
7658 if (err->code != GOT_ERR_COMMIT_MSG_EMPTY &&
7659 tagmsg_path != NULL)
7660 preserve_tagmsg = 1;
7661 goto done;
7663 /* Editor is done; we can now apply unveil(2) */
7664 err = got_sigs_apply_unveil();
7665 if (err)
7666 goto done;
7667 err = apply_unveil(got_repo_get_path(repo), 0, NULL);
7668 if (err)
7669 goto done;
7672 err = got_object_tag_create(&tag_id, tag_name, commit_id,
7673 tagger, time(NULL), tagmsg ? tagmsg : tagmsg_arg, signer_id, repo,
7674 verbosity);
7675 if (err) {
7676 if (tagmsg_path)
7677 preserve_tagmsg = 1;
7678 goto done;
7681 err = got_ref_alloc(&ref, refname, tag_id);
7682 if (err) {
7683 if (tagmsg_path)
7684 preserve_tagmsg = 1;
7685 goto done;
7688 err = got_ref_write(ref, repo);
7689 if (err) {
7690 if (tagmsg_path)
7691 preserve_tagmsg = 1;
7692 goto done;
7695 err = got_object_id_str(&tag_id_str, tag_id);
7696 if (err) {
7697 if (tagmsg_path)
7698 preserve_tagmsg = 1;
7699 goto done;
7701 printf("Created tag %s\n", tag_id_str);
7702 done:
7703 if (preserve_tagmsg) {
7704 fprintf(stderr, "%s: tag message preserved in %s\n",
7705 getprogname(), tagmsg_path);
7706 } else if (tagmsg_path && unlink(tagmsg_path) == -1 && err == NULL)
7707 err = got_error_from_errno2("unlink", tagmsg_path);
7708 free(tag_id_str);
7709 if (ref)
7710 got_ref_close(ref);
7711 free(commit_id);
7712 free(commit_id_str);
7713 free(refname);
7714 free(tagmsg);
7715 free(tagmsg_path);
7716 got_ref_list_free(&refs);
7717 return err;
7720 static const struct got_error *
7721 cmd_tag(int argc, char *argv[])
7723 const struct got_error *error = NULL;
7724 struct got_repository *repo = NULL;
7725 struct got_worktree *worktree = NULL;
7726 char *cwd = NULL, *repo_path = NULL, *commit_id_str = NULL;
7727 char *gitconfig_path = NULL, *tagger = NULL, *keyword_idstr = NULL;
7728 char *allowed_signers = NULL, *revoked_signers = NULL;
7729 const char *signer_id = NULL;
7730 const char *tag_name = NULL, *commit_id_arg = NULL, *tagmsg = NULL;
7731 int ch, do_list = 0, verify_tags = 0, verbosity = 0;
7732 int *pack_fds = NULL;
7734 #ifndef PROFILE
7735 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
7736 "sendfd unveil", NULL) == -1)
7737 err(1, "pledge");
7738 #endif
7740 while ((ch = getopt(argc, argv, "c:lm:r:s:Vv")) != -1) {
7741 switch (ch) {
7742 case 'c':
7743 commit_id_arg = optarg;
7744 break;
7745 case 'l':
7746 do_list = 1;
7747 break;
7748 case 'm':
7749 tagmsg = optarg;
7750 break;
7751 case 'r':
7752 repo_path = realpath(optarg, NULL);
7753 if (repo_path == NULL) {
7754 error = got_error_from_errno2("realpath",
7755 optarg);
7756 goto done;
7758 got_path_strip_trailing_slashes(repo_path);
7759 break;
7760 case 's':
7761 signer_id = optarg;
7762 break;
7763 case 'V':
7764 verify_tags = 1;
7765 break;
7766 case 'v':
7767 if (verbosity < 0)
7768 verbosity = 0;
7769 else if (verbosity < 3)
7770 verbosity++;
7771 break;
7772 default:
7773 usage_tag();
7774 /* NOTREACHED */
7778 argc -= optind;
7779 argv += optind;
7781 if (do_list || verify_tags) {
7782 if (commit_id_arg != NULL)
7783 errx(1,
7784 "-c option can only be used when creating a tag");
7785 if (tagmsg) {
7786 if (do_list)
7787 option_conflict('l', 'm');
7788 else
7789 option_conflict('V', 'm');
7791 if (signer_id) {
7792 if (do_list)
7793 option_conflict('l', 's');
7794 else
7795 option_conflict('V', 's');
7797 if (argc > 1)
7798 usage_tag();
7799 } else if (argc != 1)
7800 usage_tag();
7802 if (argc == 1)
7803 tag_name = argv[0];
7805 cwd = getcwd(NULL, 0);
7806 if (cwd == NULL) {
7807 error = got_error_from_errno("getcwd");
7808 goto done;
7811 error = got_repo_pack_fds_open(&pack_fds);
7812 if (error != NULL)
7813 goto done;
7815 if (repo_path == NULL) {
7816 error = got_worktree_open(&worktree, cwd,
7817 GOT_WORKTREE_GOT_DIR);
7818 if (error && error->code != GOT_ERR_NOT_WORKTREE)
7819 goto done;
7820 else
7821 error = NULL;
7822 if (worktree) {
7823 repo_path =
7824 strdup(got_worktree_get_repo_path(worktree));
7825 if (repo_path == NULL)
7826 error = got_error_from_errno("strdup");
7827 if (error)
7828 goto done;
7829 } else {
7830 repo_path = strdup(cwd);
7831 if (repo_path == NULL) {
7832 error = got_error_from_errno("strdup");
7833 goto done;
7838 if (do_list || verify_tags) {
7839 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
7840 if (error != NULL)
7841 goto done;
7842 error = get_allowed_signers(&allowed_signers, repo, worktree);
7843 if (error)
7844 goto done;
7845 error = get_revoked_signers(&revoked_signers, repo, worktree);
7846 if (error)
7847 goto done;
7848 if (worktree) {
7849 /* Release work tree lock. */
7850 got_worktree_close(worktree);
7851 worktree = NULL;
7855 * Remove "cpath" promise unless needed for signature tmpfile
7856 * creation.
7858 if (verify_tags)
7859 got_sigs_apply_unveil();
7860 else {
7861 #ifndef PROFILE
7862 if (pledge("stdio rpath wpath flock proc exec sendfd "
7863 "unveil", NULL) == -1)
7864 err(1, "pledge");
7865 #endif
7867 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
7868 if (error)
7869 goto done;
7870 error = list_tags(repo, tag_name, verify_tags, allowed_signers,
7871 revoked_signers, verbosity);
7872 } else {
7873 error = get_gitconfig_path(&gitconfig_path);
7874 if (error)
7875 goto done;
7876 error = got_repo_open(&repo, repo_path, gitconfig_path,
7877 pack_fds);
7878 if (error != NULL)
7879 goto done;
7881 error = get_author(&tagger, repo, worktree);
7882 if (error)
7883 goto done;
7884 if (signer_id == NULL)
7885 signer_id = get_signer_id(repo, worktree);
7887 if (tagmsg) {
7888 if (signer_id) {
7889 error = got_sigs_apply_unveil();
7890 if (error)
7891 goto done;
7893 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
7894 if (error)
7895 goto done;
7898 if (commit_id_arg == NULL) {
7899 struct got_reference *head_ref;
7900 struct got_object_id *commit_id;
7901 error = got_ref_open(&head_ref, repo,
7902 worktree ? got_worktree_get_head_ref_name(worktree)
7903 : GOT_REF_HEAD, 0);
7904 if (error)
7905 goto done;
7906 error = got_ref_resolve(&commit_id, repo, head_ref);
7907 got_ref_close(head_ref);
7908 if (error)
7909 goto done;
7910 error = got_object_id_str(&commit_id_str, commit_id);
7911 free(commit_id);
7912 if (error)
7913 goto done;
7914 } else {
7915 error = got_keyword_to_idstr(&keyword_idstr,
7916 commit_id_arg, repo, worktree);
7917 if (error != NULL)
7918 goto done;
7919 commit_id_str = keyword_idstr;
7922 if (worktree) {
7923 /* Release work tree lock. */
7924 got_worktree_close(worktree);
7925 worktree = NULL;
7928 error = add_tag(repo, tagger, tag_name,
7929 commit_id_str ? commit_id_str : commit_id_arg, tagmsg,
7930 signer_id, verbosity);
7932 done:
7933 if (repo) {
7934 const struct got_error *close_err = got_repo_close(repo);
7935 if (error == NULL)
7936 error = close_err;
7938 if (worktree)
7939 got_worktree_close(worktree);
7940 if (pack_fds) {
7941 const struct got_error *pack_err =
7942 got_repo_pack_fds_close(pack_fds);
7943 if (error == NULL)
7944 error = pack_err;
7946 free(cwd);
7947 free(repo_path);
7948 free(gitconfig_path);
7949 free(commit_id_str);
7950 free(tagger);
7951 free(allowed_signers);
7952 free(revoked_signers);
7953 return error;
7956 __dead static void
7957 usage_add(void)
7959 fprintf(stderr, "usage: %s add [-IR] path ...\n", getprogname());
7960 exit(1);
7963 static const struct got_error *
7964 add_progress(void *arg, unsigned char status, const char *path)
7966 while (path[0] == '/')
7967 path++;
7968 printf("%c %s\n", status, path);
7969 return NULL;
7972 static const struct got_error *
7973 cmd_add(int argc, char *argv[])
7975 const struct got_error *error = NULL;
7976 struct got_repository *repo = NULL;
7977 struct got_worktree *worktree = NULL;
7978 char *cwd = NULL;
7979 struct got_pathlist_head paths;
7980 struct got_pathlist_entry *pe;
7981 int ch, can_recurse = 0, no_ignores = 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, "IR")) != -1) {
7993 switch (ch) {
7994 case 'I':
7995 no_ignores = 1;
7996 break;
7997 case 'R':
7998 can_recurse = 1;
7999 break;
8000 default:
8001 usage_add();
8002 /* NOTREACHED */
8006 argc -= optind;
8007 argv += optind;
8009 if (argc < 1)
8010 usage_add();
8012 cwd = getcwd(NULL, 0);
8013 if (cwd == NULL) {
8014 error = got_error_from_errno("getcwd");
8015 goto done;
8018 error = got_repo_pack_fds_open(&pack_fds);
8019 if (error != NULL)
8020 goto done;
8022 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
8023 if (error) {
8024 if (error->code == GOT_ERR_NOT_WORKTREE)
8025 error = wrap_not_worktree_error(error, "add", cwd);
8026 goto done;
8029 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
8030 NULL, pack_fds);
8031 if (error != NULL)
8032 goto done;
8034 error = apply_unveil(got_repo_get_path(repo), 1,
8035 got_worktree_get_root_path(worktree));
8036 if (error)
8037 goto done;
8039 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
8040 if (error)
8041 goto done;
8043 if (!can_recurse) {
8044 char *ondisk_path;
8045 struct stat sb;
8046 TAILQ_FOREACH(pe, &paths, entry) {
8047 if (asprintf(&ondisk_path, "%s/%s",
8048 got_worktree_get_root_path(worktree),
8049 pe->path) == -1) {
8050 error = got_error_from_errno("asprintf");
8051 goto done;
8053 if (lstat(ondisk_path, &sb) == -1) {
8054 if (errno == ENOENT) {
8055 free(ondisk_path);
8056 continue;
8058 error = got_error_from_errno2("lstat",
8059 ondisk_path);
8060 free(ondisk_path);
8061 goto done;
8063 free(ondisk_path);
8064 if (S_ISDIR(sb.st_mode)) {
8065 error = got_error_msg(GOT_ERR_BAD_PATH,
8066 "adding directories requires -R option");
8067 goto done;
8072 error = got_worktree_schedule_add(worktree, &paths, add_progress,
8073 NULL, repo, no_ignores);
8074 done:
8075 if (repo) {
8076 const struct got_error *close_err = got_repo_close(repo);
8077 if (error == NULL)
8078 error = close_err;
8080 if (worktree)
8081 got_worktree_close(worktree);
8082 if (pack_fds) {
8083 const struct got_error *pack_err =
8084 got_repo_pack_fds_close(pack_fds);
8085 if (error == NULL)
8086 error = pack_err;
8088 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
8089 free(cwd);
8090 return error;
8093 __dead static void
8094 usage_remove(void)
8096 fprintf(stderr, "usage: %s remove [-fkR] [-s status-codes] path ...\n",
8097 getprogname());
8098 exit(1);
8101 static const struct got_error *
8102 print_remove_status(void *arg, unsigned char status,
8103 unsigned char staged_status, const char *path)
8105 while (path[0] == '/')
8106 path++;
8107 if (status == GOT_STATUS_NONEXISTENT)
8108 return NULL;
8109 if (status == staged_status && (status == GOT_STATUS_DELETE))
8110 status = GOT_STATUS_NO_CHANGE;
8111 printf("%c%c %s\n", status, staged_status, path);
8112 return NULL;
8115 static const struct got_error *
8116 cmd_remove(int argc, char *argv[])
8118 const struct got_error *error = NULL;
8119 struct got_worktree *worktree = NULL;
8120 struct got_repository *repo = NULL;
8121 const char *status_codes = NULL;
8122 char *cwd = NULL;
8123 struct got_pathlist_head paths;
8124 struct got_pathlist_entry *pe;
8125 int ch, delete_local_mods = 0, can_recurse = 0, keep_on_disk = 0, i;
8126 int ignore_missing_paths = 0;
8127 int *pack_fds = NULL;
8129 TAILQ_INIT(&paths);
8131 #ifndef PROFILE
8132 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
8133 NULL) == -1)
8134 err(1, "pledge");
8135 #endif
8137 while ((ch = getopt(argc, argv, "fkRs:")) != -1) {
8138 switch (ch) {
8139 case 'f':
8140 delete_local_mods = 1;
8141 ignore_missing_paths = 1;
8142 break;
8143 case 'k':
8144 keep_on_disk = 1;
8145 break;
8146 case 'R':
8147 can_recurse = 1;
8148 break;
8149 case 's':
8150 for (i = 0; optarg[i] != '\0'; i++) {
8151 switch (optarg[i]) {
8152 case GOT_STATUS_MODIFY:
8153 delete_local_mods = 1;
8154 break;
8155 case GOT_STATUS_MISSING:
8156 ignore_missing_paths = 1;
8157 break;
8158 default:
8159 errx(1, "invalid status code '%c'",
8160 optarg[i]);
8163 status_codes = optarg;
8164 break;
8165 default:
8166 usage_remove();
8167 /* NOTREACHED */
8171 argc -= optind;
8172 argv += optind;
8174 if (argc < 1)
8175 usage_remove();
8177 cwd = getcwd(NULL, 0);
8178 if (cwd == NULL) {
8179 error = got_error_from_errno("getcwd");
8180 goto done;
8183 error = got_repo_pack_fds_open(&pack_fds);
8184 if (error != NULL)
8185 goto done;
8187 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
8188 if (error) {
8189 if (error->code == GOT_ERR_NOT_WORKTREE)
8190 error = wrap_not_worktree_error(error, "remove", cwd);
8191 goto done;
8194 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
8195 NULL, pack_fds);
8196 if (error)
8197 goto done;
8199 error = apply_unveil(got_repo_get_path(repo), 1,
8200 got_worktree_get_root_path(worktree));
8201 if (error)
8202 goto done;
8204 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
8205 if (error)
8206 goto done;
8208 if (!can_recurse) {
8209 char *ondisk_path;
8210 struct stat sb;
8211 TAILQ_FOREACH(pe, &paths, entry) {
8212 if (asprintf(&ondisk_path, "%s/%s",
8213 got_worktree_get_root_path(worktree),
8214 pe->path) == -1) {
8215 error = got_error_from_errno("asprintf");
8216 goto done;
8218 if (lstat(ondisk_path, &sb) == -1) {
8219 if (errno == ENOENT) {
8220 free(ondisk_path);
8221 continue;
8223 error = got_error_from_errno2("lstat",
8224 ondisk_path);
8225 free(ondisk_path);
8226 goto done;
8228 free(ondisk_path);
8229 if (S_ISDIR(sb.st_mode)) {
8230 error = got_error_msg(GOT_ERR_BAD_PATH,
8231 "removing directories requires -R option");
8232 goto done;
8237 error = got_worktree_schedule_delete(worktree, &paths,
8238 delete_local_mods, status_codes, print_remove_status, NULL,
8239 repo, keep_on_disk, ignore_missing_paths);
8240 done:
8241 if (repo) {
8242 const struct got_error *close_err = got_repo_close(repo);
8243 if (error == NULL)
8244 error = close_err;
8246 if (worktree)
8247 got_worktree_close(worktree);
8248 if (pack_fds) {
8249 const struct got_error *pack_err =
8250 got_repo_pack_fds_close(pack_fds);
8251 if (error == NULL)
8252 error = pack_err;
8254 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
8255 free(cwd);
8256 return error;
8259 __dead static void
8260 usage_patch(void)
8262 fprintf(stderr, "usage: %s patch [-nR] [-c commit] [-p strip-count] "
8263 "[patchfile]\n", getprogname());
8264 exit(1);
8267 static const struct got_error *
8268 patch_from_stdin(int *patchfd)
8270 const struct got_error *err = NULL;
8271 ssize_t r;
8272 char buf[BUFSIZ];
8273 sig_t sighup, sigint, sigquit;
8275 *patchfd = got_opentempfd();
8276 if (*patchfd == -1)
8277 return got_error_from_errno("got_opentempfd");
8279 sighup = signal(SIGHUP, SIG_DFL);
8280 sigint = signal(SIGINT, SIG_DFL);
8281 sigquit = signal(SIGQUIT, SIG_DFL);
8283 for (;;) {
8284 r = read(0, buf, sizeof(buf));
8285 if (r == -1) {
8286 err = got_error_from_errno("read");
8287 break;
8289 if (r == 0)
8290 break;
8291 if (write(*patchfd, buf, r) == -1) {
8292 err = got_error_from_errno("write");
8293 break;
8297 signal(SIGHUP, sighup);
8298 signal(SIGINT, sigint);
8299 signal(SIGQUIT, sigquit);
8301 if (err == NULL && lseek(*patchfd, 0, SEEK_SET) == -1)
8302 err = got_error_from_errno("lseek");
8304 if (err != NULL) {
8305 close(*patchfd);
8306 *patchfd = -1;
8309 return err;
8312 struct got_patch_progress_arg {
8313 int did_something;
8314 int conflicts;
8315 int rejects;
8318 static const struct got_error *
8319 patch_progress(void *arg, const char *old, const char *new,
8320 unsigned char status, const struct got_error *error, int old_from,
8321 int old_lines, int new_from, int new_lines, int offset,
8322 int ws_mangled, const struct got_error *hunk_err)
8324 const char *path = new == NULL ? old : new;
8325 struct got_patch_progress_arg *a = arg;
8327 while (*path == '/')
8328 path++;
8330 if (status != GOT_STATUS_NO_CHANGE &&
8331 status != 0 /* per-hunk progress */) {
8332 printf("%c %s\n", status, path);
8333 a->did_something = 1;
8336 if (hunk_err == NULL) {
8337 if (status == GOT_STATUS_CANNOT_UPDATE)
8338 a->rejects++;
8339 else if (status == GOT_STATUS_CONFLICT)
8340 a->conflicts++;
8343 if (error != NULL)
8344 fprintf(stderr, "%s: %s\n", getprogname(), error->msg);
8346 if (offset != 0 || hunk_err != NULL || ws_mangled) {
8347 printf("@@ -%d,%d +%d,%d @@ ", old_from,
8348 old_lines, new_from, new_lines);
8349 if (hunk_err != NULL)
8350 printf("%s\n", hunk_err->msg);
8351 else if (offset != 0)
8352 printf("applied with offset %d\n", offset);
8353 else
8354 printf("hunk contains mangled whitespace\n");
8357 return NULL;
8360 static void
8361 print_patch_progress_stats(struct got_patch_progress_arg *ppa)
8363 if (!ppa->did_something)
8364 return;
8366 if (ppa->conflicts > 0)
8367 printf("Files with merge conflicts: %d\n", ppa->conflicts);
8369 if (ppa->rejects > 0) {
8370 printf("Files where patch failed to apply: %d\n",
8371 ppa->rejects);
8375 static const struct got_error *
8376 cmd_patch(int argc, char *argv[])
8378 const struct got_error *error = NULL, *close_error = NULL;
8379 struct got_worktree *worktree = NULL;
8380 struct got_repository *repo = NULL;
8381 struct got_reflist_head refs;
8382 struct got_object_id *commit_id = NULL;
8383 const char *commit_id_str = NULL;
8384 struct stat sb;
8385 const char *errstr;
8386 char *cwd = NULL, *keyword_idstr = NULL;
8387 int ch, nop = 0, strip = -1, reverse = 0;
8388 int patchfd;
8389 int *pack_fds = NULL;
8390 struct got_patch_progress_arg ppa;
8392 TAILQ_INIT(&refs);
8394 #ifndef PROFILE
8395 if (pledge("stdio rpath wpath cpath fattr proc exec sendfd flock "
8396 "unveil", NULL) == -1)
8397 err(1, "pledge");
8398 #endif
8400 while ((ch = getopt(argc, argv, "c:np:R")) != -1) {
8401 switch (ch) {
8402 case 'c':
8403 commit_id_str = optarg;
8404 break;
8405 case 'n':
8406 nop = 1;
8407 break;
8408 case 'p':
8409 strip = strtonum(optarg, 0, INT_MAX, &errstr);
8410 if (errstr != NULL)
8411 errx(1, "pathname strip count is %s: %s",
8412 errstr, optarg);
8413 break;
8414 case 'R':
8415 reverse = 1;
8416 break;
8417 default:
8418 usage_patch();
8419 /* NOTREACHED */
8423 argc -= optind;
8424 argv += optind;
8426 if (argc == 0) {
8427 error = patch_from_stdin(&patchfd);
8428 if (error)
8429 return error;
8430 } else if (argc == 1) {
8431 patchfd = open(argv[0], O_RDONLY);
8432 if (patchfd == -1) {
8433 error = got_error_from_errno2("open", argv[0]);
8434 return error;
8436 if (fstat(patchfd, &sb) == -1) {
8437 error = got_error_from_errno2("fstat", argv[0]);
8438 goto done;
8440 if (!S_ISREG(sb.st_mode)) {
8441 error = got_error_path(argv[0], GOT_ERR_BAD_FILETYPE);
8442 goto done;
8444 } else
8445 usage_patch();
8447 if ((cwd = getcwd(NULL, 0)) == NULL) {
8448 error = got_error_from_errno("getcwd");
8449 goto done;
8452 error = got_repo_pack_fds_open(&pack_fds);
8453 if (error != NULL)
8454 goto done;
8456 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
8457 if (error != NULL)
8458 goto done;
8460 const char *repo_path = got_worktree_get_repo_path(worktree);
8461 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
8462 if (error != NULL)
8463 goto done;
8465 error = apply_unveil(got_repo_get_path(repo), 0,
8466 got_worktree_get_root_path(worktree));
8467 if (error != NULL)
8468 goto done;
8470 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
8471 if (error)
8472 goto done;
8474 if (commit_id_str != NULL) {
8475 error = got_keyword_to_idstr(&keyword_idstr, commit_id_str,
8476 repo, worktree);
8477 if (error != NULL)
8478 goto done;
8480 error = got_repo_match_object_id(&commit_id, NULL,
8481 keyword_idstr != NULL ? keyword_idstr : commit_id_str,
8482 GOT_OBJ_TYPE_COMMIT, &refs, repo);
8483 if (error)
8484 goto done;
8487 memset(&ppa, 0, sizeof(ppa));
8488 error = got_patch(patchfd, worktree, repo, nop, strip, reverse,
8489 commit_id, patch_progress, &ppa, check_cancelled, NULL);
8490 print_patch_progress_stats(&ppa);
8491 done:
8492 got_ref_list_free(&refs);
8493 free(keyword_idstr);
8494 free(commit_id);
8495 if (repo) {
8496 close_error = got_repo_close(repo);
8497 if (error == NULL)
8498 error = close_error;
8500 if (worktree != NULL) {
8501 close_error = got_worktree_close(worktree);
8502 if (error == NULL)
8503 error = close_error;
8505 if (pack_fds) {
8506 const struct got_error *pack_err =
8507 got_repo_pack_fds_close(pack_fds);
8508 if (error == NULL)
8509 error = pack_err;
8511 free(cwd);
8512 return error;
8515 __dead static void
8516 usage_revert(void)
8518 fprintf(stderr, "usage: %s revert [-pR] [-F response-script] path ...\n",
8519 getprogname());
8520 exit(1);
8523 static const struct got_error *
8524 revert_progress(void *arg, unsigned char status, const char *path)
8526 if (status == GOT_STATUS_UNVERSIONED)
8527 return NULL;
8529 while (path[0] == '/')
8530 path++;
8531 printf("%c %s\n", status, path);
8532 return NULL;
8535 struct choose_patch_arg {
8536 FILE *patch_script_file;
8537 const char *action;
8540 static const struct got_error *
8541 show_change(unsigned char status, const char *path, FILE *patch_file, int n,
8542 int nchanges, const char *action)
8544 const struct got_error *err;
8545 char *line = NULL;
8546 size_t linesize = 0;
8547 ssize_t linelen;
8549 switch (status) {
8550 case GOT_STATUS_ADD:
8551 printf("A %s\n%s this addition? [y/n] ", path, action);
8552 break;
8553 case GOT_STATUS_DELETE:
8554 printf("D %s\n%s this deletion? [y/n] ", path, action);
8555 break;
8556 case GOT_STATUS_MODIFY:
8557 if (fseek(patch_file, 0L, SEEK_SET) == -1)
8558 return got_error_from_errno("fseek");
8559 printf(GOT_COMMIT_SEP_STR);
8560 while ((linelen = getline(&line, &linesize, patch_file)) != -1)
8561 printf("%s", line);
8562 if (linelen == -1 && ferror(patch_file)) {
8563 err = got_error_from_errno("getline");
8564 free(line);
8565 return err;
8567 free(line);
8568 printf(GOT_COMMIT_SEP_STR);
8569 printf("M %s (change %d of %d)\n%s this change? [y/n/q] ",
8570 path, n, nchanges, action);
8571 break;
8572 default:
8573 return got_error_path(path, GOT_ERR_FILE_STATUS);
8576 fflush(stdout);
8577 return NULL;
8580 static const struct got_error *
8581 choose_patch(int *choice, void *arg, unsigned char status, const char *path,
8582 FILE *patch_file, int n, int nchanges)
8584 const struct got_error *err = NULL;
8585 char *line = NULL;
8586 size_t linesize = 0;
8587 ssize_t linelen;
8588 int resp = ' ';
8589 struct choose_patch_arg *a = arg;
8591 *choice = GOT_PATCH_CHOICE_NONE;
8593 if (a->patch_script_file) {
8594 char *nl;
8595 err = show_change(status, path, patch_file, n, nchanges,
8596 a->action);
8597 if (err)
8598 return err;
8599 linelen = getline(&line, &linesize, a->patch_script_file);
8600 if (linelen == -1) {
8601 if (ferror(a->patch_script_file))
8602 return got_error_from_errno("getline");
8603 return NULL;
8605 nl = strchr(line, '\n');
8606 if (nl)
8607 *nl = '\0';
8608 if (strcmp(line, "y") == 0) {
8609 *choice = GOT_PATCH_CHOICE_YES;
8610 printf("y\n");
8611 } else if (strcmp(line, "n") == 0) {
8612 *choice = GOT_PATCH_CHOICE_NO;
8613 printf("n\n");
8614 } else if (strcmp(line, "q") == 0 &&
8615 status == GOT_STATUS_MODIFY) {
8616 *choice = GOT_PATCH_CHOICE_QUIT;
8617 printf("q\n");
8618 } else
8619 printf("invalid response '%s'\n", line);
8620 free(line);
8621 return NULL;
8624 while (resp != 'y' && resp != 'n' && resp != 'q') {
8625 err = show_change(status, path, patch_file, n, nchanges,
8626 a->action);
8627 if (err)
8628 return err;
8629 resp = getchar();
8630 if (resp == '\n')
8631 resp = getchar();
8632 if (status == GOT_STATUS_MODIFY) {
8633 if (resp != 'y' && resp != 'n' && resp != 'q') {
8634 printf("invalid response '%c'\n", resp);
8635 resp = ' ';
8637 } else if (resp != 'y' && resp != 'n') {
8638 printf("invalid response '%c'\n", resp);
8639 resp = ' ';
8643 if (resp == 'y')
8644 *choice = GOT_PATCH_CHOICE_YES;
8645 else if (resp == 'n')
8646 *choice = GOT_PATCH_CHOICE_NO;
8647 else if (resp == 'q' && status == GOT_STATUS_MODIFY)
8648 *choice = GOT_PATCH_CHOICE_QUIT;
8650 return NULL;
8653 struct wt_commitable_path_arg {
8654 struct got_pathlist_head *commit_paths;
8655 int *has_changes;
8659 * Shortcut work tree status callback to determine if the set of paths scanned
8660 * has at least one versioned path that is being modified and, if not NULL, is
8661 * in the arg->commit_paths list. Set arg and return GOT_ERR_FILE_MODIFIED as
8662 * soon as a path is passed with a status that satisfies this criteria.
8664 static const struct got_error *
8665 worktree_has_commitable_path(void *arg, unsigned char status,
8666 unsigned char staged_status, const char *path,
8667 struct got_object_id *blob_id, struct got_object_id *staged_blob_id,
8668 struct got_object_id *commit_id, int dirfd, const char *de_name)
8670 struct wt_commitable_path_arg *a = arg;
8672 if (status == staged_status && (status == GOT_STATUS_DELETE))
8673 status = GOT_STATUS_NO_CHANGE;
8675 if (!(status == GOT_STATUS_NO_CHANGE ||
8676 status == GOT_STATUS_UNVERSIONED) ||
8677 staged_status != GOT_STATUS_NO_CHANGE) {
8678 if (a->commit_paths != NULL) {
8679 struct got_pathlist_entry *pe;
8681 TAILQ_FOREACH(pe, a->commit_paths, entry) {
8682 if (strncmp(path, pe->path,
8683 pe->path_len) == 0) {
8684 *a->has_changes = 1;
8685 break;
8688 } else
8689 *a->has_changes = 1;
8691 if (*a->has_changes)
8692 return got_error(GOT_ERR_FILE_MODIFIED);
8695 return NULL;
8699 * Check that the changeset of the commit identified by id is
8700 * comprised of at least one modified path that is being committed.
8702 static const struct got_error *
8703 commit_path_changed_in_worktree(struct wt_commitable_path_arg *wcpa,
8704 struct got_object_id *id, struct got_worktree *worktree,
8705 struct got_repository *repo)
8707 const struct got_error *err;
8708 struct got_pathlist_head paths;
8709 struct got_commit_object *commit = NULL, *pcommit = NULL;
8710 struct got_tree_object *tree = NULL, *ptree = NULL;
8711 struct got_object_qid *pid;
8713 TAILQ_INIT(&paths);
8715 err = got_object_open_as_commit(&commit, repo, id);
8716 if (err)
8717 goto done;
8719 err = got_object_open_as_tree(&tree, repo,
8720 got_object_commit_get_tree_id(commit));
8721 if (err)
8722 goto done;
8724 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
8725 if (pid != NULL) {
8726 err = got_object_open_as_commit(&pcommit, repo, &pid->id);
8727 if (err)
8728 goto done;
8730 err = got_object_open_as_tree(&ptree, repo,
8731 got_object_commit_get_tree_id(pcommit));
8732 if (err)
8733 goto done;
8736 err = got_diff_tree(ptree, tree, NULL, NULL, -1, -1, "", "", repo,
8737 got_diff_tree_collect_changed_paths, &paths, 0);
8738 if (err)
8739 goto done;
8741 err = got_worktree_status(worktree, &paths, repo, 0,
8742 worktree_has_commitable_path, wcpa, check_cancelled, NULL);
8743 if (err && err->code == GOT_ERR_FILE_MODIFIED) {
8745 * At least one changed path in the referenced commit is
8746 * modified in the work tree, that's all we need to know!
8748 err = NULL;
8751 done:
8752 got_pathlist_free(&paths, GOT_PATHLIST_FREE_ALL);
8753 if (commit)
8754 got_object_commit_close(commit);
8755 if (pcommit)
8756 got_object_commit_close(pcommit);
8757 if (tree)
8758 got_object_tree_close(tree);
8759 if (ptree)
8760 got_object_tree_close(ptree);
8761 return err;
8765 * Remove any "logmsg" reference comprised entirely of paths that have
8766 * been reverted in this work tree. If any path in the logmsg ref changeset
8767 * remains in a changed state in the worktree, do not remove the reference.
8769 static const struct got_error *
8770 rm_logmsg_ref(struct got_worktree *worktree, struct got_repository *repo)
8772 const struct got_error *err;
8773 struct got_reflist_head refs;
8774 struct got_reflist_entry *re;
8775 struct got_commit_object *commit = NULL;
8776 struct got_object_id *commit_id = NULL;
8777 struct wt_commitable_path_arg wcpa;
8778 char *uuidstr = NULL;
8780 TAILQ_INIT(&refs);
8782 err = got_worktree_get_uuid(&uuidstr, worktree);
8783 if (err)
8784 goto done;
8786 err = got_ref_list(&refs, repo, "refs/got/worktree",
8787 got_ref_cmp_by_name, repo);
8788 if (err)
8789 goto done;
8791 TAILQ_FOREACH(re, &refs, entry) {
8792 const char *refname;
8793 int has_changes = 0;
8795 refname = got_ref_get_name(re->ref);
8797 if (!strncmp(refname, GOT_WORKTREE_CHERRYPICK_REF_PREFIX,
8798 GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN))
8799 refname += GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN + 1;
8800 else if (!strncmp(refname, GOT_WORKTREE_BACKOUT_REF_PREFIX,
8801 GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN))
8802 refname += GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN + 1;
8803 else
8804 continue;
8806 if (strncmp(refname, uuidstr, GOT_WORKTREE_UUID_STRLEN) == 0)
8807 refname += GOT_WORKTREE_UUID_STRLEN + 1; /* skip '-' */
8808 else
8809 continue;
8811 err = got_repo_match_object_id(&commit_id, NULL, refname,
8812 GOT_OBJ_TYPE_COMMIT, NULL, repo);
8813 if (err)
8814 goto done;
8816 err = got_object_open_as_commit(&commit, repo, commit_id);
8817 if (err)
8818 goto done;
8820 wcpa.commit_paths = NULL;
8821 wcpa.has_changes = &has_changes;
8823 err = commit_path_changed_in_worktree(&wcpa, commit_id,
8824 worktree, repo);
8825 if (err)
8826 goto done;
8828 if (!has_changes) {
8829 err = got_ref_delete(re->ref, repo);
8830 if (err)
8831 goto done;
8834 got_object_commit_close(commit);
8835 commit = NULL;
8836 free(commit_id);
8837 commit_id = NULL;
8840 done:
8841 free(uuidstr);
8842 free(commit_id);
8843 got_ref_list_free(&refs);
8844 if (commit)
8845 got_object_commit_close(commit);
8846 return err;
8849 static const struct got_error *
8850 cmd_revert(int argc, char *argv[])
8852 const struct got_error *error = NULL;
8853 struct got_worktree *worktree = NULL;
8854 struct got_repository *repo = NULL;
8855 char *cwd = NULL, *path = NULL;
8856 struct got_pathlist_head paths;
8857 struct got_pathlist_entry *pe;
8858 int ch, can_recurse = 0, pflag = 0;
8859 FILE *patch_script_file = NULL;
8860 const char *patch_script_path = NULL;
8861 struct choose_patch_arg cpa;
8862 int *pack_fds = NULL;
8864 TAILQ_INIT(&paths);
8866 #ifndef PROFILE
8867 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
8868 "unveil", NULL) == -1)
8869 err(1, "pledge");
8870 #endif
8872 while ((ch = getopt(argc, argv, "F:pR")) != -1) {
8873 switch (ch) {
8874 case 'F':
8875 patch_script_path = optarg;
8876 break;
8877 case 'p':
8878 pflag = 1;
8879 break;
8880 case 'R':
8881 can_recurse = 1;
8882 break;
8883 default:
8884 usage_revert();
8885 /* NOTREACHED */
8889 argc -= optind;
8890 argv += optind;
8892 if (argc < 1)
8893 usage_revert();
8894 if (patch_script_path && !pflag)
8895 errx(1, "-F option can only be used together with -p option");
8897 cwd = getcwd(NULL, 0);
8898 if (cwd == NULL) {
8899 error = got_error_from_errno("getcwd");
8900 goto done;
8903 error = got_repo_pack_fds_open(&pack_fds);
8904 if (error != NULL)
8905 goto done;
8907 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
8908 if (error) {
8909 if (error->code == GOT_ERR_NOT_WORKTREE)
8910 error = wrap_not_worktree_error(error, "revert", cwd);
8911 goto done;
8914 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
8915 NULL, pack_fds);
8916 if (error != NULL)
8917 goto done;
8919 if (patch_script_path) {
8920 patch_script_file = fopen(patch_script_path, "re");
8921 if (patch_script_file == NULL) {
8922 error = got_error_from_errno2("fopen",
8923 patch_script_path);
8924 goto done;
8929 * XXX "c" perm needed on repo dir to delete merge references.
8931 error = apply_unveil(got_repo_get_path(repo), 0,
8932 got_worktree_get_root_path(worktree));
8933 if (error)
8934 goto done;
8936 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
8937 if (error)
8938 goto done;
8940 if (!can_recurse) {
8941 char *ondisk_path;
8942 struct stat sb;
8943 TAILQ_FOREACH(pe, &paths, entry) {
8944 if (asprintf(&ondisk_path, "%s/%s",
8945 got_worktree_get_root_path(worktree),
8946 pe->path) == -1) {
8947 error = got_error_from_errno("asprintf");
8948 goto done;
8950 if (lstat(ondisk_path, &sb) == -1) {
8951 if (errno == ENOENT) {
8952 free(ondisk_path);
8953 continue;
8955 error = got_error_from_errno2("lstat",
8956 ondisk_path);
8957 free(ondisk_path);
8958 goto done;
8960 free(ondisk_path);
8961 if (S_ISDIR(sb.st_mode)) {
8962 error = got_error_msg(GOT_ERR_BAD_PATH,
8963 "reverting directories requires -R option");
8964 goto done;
8969 cpa.patch_script_file = patch_script_file;
8970 cpa.action = "revert";
8971 error = got_worktree_revert(worktree, &paths, revert_progress, NULL,
8972 pflag ? choose_patch : NULL, &cpa, repo);
8974 error = rm_logmsg_ref(worktree, repo);
8975 done:
8976 if (patch_script_file && fclose(patch_script_file) == EOF &&
8977 error == NULL)
8978 error = got_error_from_errno2("fclose", patch_script_path);
8979 if (repo) {
8980 const struct got_error *close_err = got_repo_close(repo);
8981 if (error == NULL)
8982 error = close_err;
8984 if (worktree)
8985 got_worktree_close(worktree);
8986 if (pack_fds) {
8987 const struct got_error *pack_err =
8988 got_repo_pack_fds_close(pack_fds);
8989 if (error == NULL)
8990 error = pack_err;
8992 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
8993 free(path);
8994 free(cwd);
8995 return error;
8998 __dead static void
8999 usage_commit(void)
9001 fprintf(stderr, "usage: %s commit [-CNnS] [-A author] [-F path] "
9002 "[-m message] [path ...]\n", getprogname());
9003 exit(1);
9006 struct collect_commit_logmsg_arg {
9007 const char *cmdline_log;
9008 const char *prepared_log;
9009 const char *merged_log;
9010 int non_interactive;
9011 const char *editor;
9012 const char *worktree_path;
9013 const char *branch_name;
9014 const char *repo_path;
9015 char *logmsg_path;
9019 static const struct got_error *
9020 read_prepared_logmsg(char **logmsg, const char *path)
9022 const struct got_error *err = NULL;
9023 FILE *f = NULL;
9024 struct stat sb;
9025 size_t r;
9027 *logmsg = NULL;
9028 memset(&sb, 0, sizeof(sb));
9030 f = fopen(path, "re");
9031 if (f == NULL)
9032 return got_error_from_errno2("fopen", path);
9034 if (fstat(fileno(f), &sb) == -1) {
9035 err = got_error_from_errno2("fstat", path);
9036 goto done;
9038 if (sb.st_size == 0) {
9039 err = got_error(GOT_ERR_COMMIT_MSG_EMPTY);
9040 goto done;
9043 *logmsg = malloc(sb.st_size + 1);
9044 if (*logmsg == NULL) {
9045 err = got_error_from_errno("malloc");
9046 goto done;
9049 r = fread(*logmsg, 1, sb.st_size, f);
9050 if (r != sb.st_size) {
9051 if (ferror(f))
9052 err = got_error_from_errno2("fread", path);
9053 else
9054 err = got_error(GOT_ERR_IO);
9055 goto done;
9057 (*logmsg)[sb.st_size] = '\0';
9058 done:
9059 if (fclose(f) == EOF && err == NULL)
9060 err = got_error_from_errno2("fclose", path);
9061 if (err) {
9062 free(*logmsg);
9063 *logmsg = NULL;
9065 return err;
9068 static const struct got_error *
9069 collect_commit_logmsg(struct got_pathlist_head *commitable_paths,
9070 const char *diff_path, char **logmsg, void *arg)
9072 char *initial_content = NULL;
9073 struct got_pathlist_entry *pe;
9074 const struct got_error *err = NULL;
9075 char *template = NULL;
9076 char *prepared_msg = NULL, *merged_msg = NULL;
9077 struct collect_commit_logmsg_arg *a = arg;
9078 int initial_content_len;
9079 int fd = -1;
9080 size_t len;
9082 /* if a message was specified on the command line, just use it */
9083 if (a->cmdline_log != NULL && *a->cmdline_log != '\0') {
9084 len = strlen(a->cmdline_log) + 1;
9085 *logmsg = malloc(len + 1);
9086 if (*logmsg == NULL)
9087 return got_error_from_errno("malloc");
9088 strlcpy(*logmsg, a->cmdline_log, len);
9089 return NULL;
9090 } else if (a->prepared_log != NULL && a->non_interactive)
9091 return read_prepared_logmsg(logmsg, a->prepared_log);
9093 if (asprintf(&template, "%s/logmsg", a->worktree_path) == -1)
9094 return got_error_from_errno("asprintf");
9096 err = got_opentemp_named_fd(&a->logmsg_path, &fd, template, "");
9097 if (err)
9098 goto done;
9100 if (a->prepared_log) {
9101 err = read_prepared_logmsg(&prepared_msg, a->prepared_log);
9102 if (err)
9103 goto done;
9104 } else if (a->merged_log) {
9105 err = read_prepared_logmsg(&merged_msg, a->merged_log);
9106 if (err)
9107 goto done;
9110 initial_content_len = asprintf(&initial_content,
9111 "%s%s\n# changes to be committed on branch %s:\n",
9112 prepared_msg ? prepared_msg : "",
9113 merged_msg ? merged_msg : "", a->branch_name);
9114 if (initial_content_len == -1) {
9115 err = got_error_from_errno("asprintf");
9116 goto done;
9119 if (write(fd, initial_content, initial_content_len) == -1) {
9120 err = got_error_from_errno2("write", a->logmsg_path);
9121 goto done;
9124 TAILQ_FOREACH(pe, commitable_paths, entry) {
9125 struct got_commitable *ct = pe->data;
9126 dprintf(fd, "# %c %s\n",
9127 got_commitable_get_status(ct),
9128 got_commitable_get_path(ct));
9131 if (diff_path) {
9132 dprintf(fd, "# detailed changes can be viewed in %s\n",
9133 diff_path);
9136 if (close(fd) == -1) {
9137 err = got_error_from_errno2("close", a->logmsg_path);
9138 goto done;
9140 fd = -1;
9142 err = edit_logmsg(logmsg, a->editor, a->logmsg_path, initial_content,
9143 initial_content_len, a->prepared_log ? 0 : 1);
9144 done:
9145 free(initial_content);
9146 free(template);
9147 free(prepared_msg);
9148 free(merged_msg);
9150 if (fd != -1 && close(fd) == -1 && err == NULL)
9151 err = got_error_from_errno2("close", a->logmsg_path);
9152 if (err) {
9153 free(*logmsg);
9154 *logmsg = NULL;
9156 return err;
9159 static const struct got_error *
9160 cat_logmsg(FILE *f, struct got_commit_object *commit, const char *idstr,
9161 const char *type, int has_content)
9163 const struct got_error *err = NULL;
9164 char *logmsg = NULL;
9166 err = got_object_commit_get_logmsg(&logmsg, commit);
9167 if (err)
9168 return err;
9170 if (fprintf(f, "%s# log message of %s commit %s:%s",
9171 has_content ? "\n" : "", type, idstr, logmsg) < 0)
9172 err = got_ferror(f, GOT_ERR_IO);
9174 free(logmsg);
9175 return err;
9179 * Lookup "logmsg" references of backed-out and cherrypicked commits
9180 * belonging to the current work tree. If found, and the worktree has
9181 * at least one modified file that was changed in the referenced commit,
9182 * add its log message to a new temporary file at *logmsg_path.
9183 * Add all refs found to matched_refs to be scheduled for removal on
9184 * successful commit.
9186 static const struct got_error *
9187 lookup_logmsg_ref(char **logmsg_path, struct got_pathlist_head *paths,
9188 struct got_reflist_head *matched_refs, struct got_worktree *worktree,
9189 struct got_repository *repo)
9191 const struct got_error *err;
9192 struct got_commit_object *commit = NULL;
9193 struct got_object_id *id = NULL;
9194 struct got_reflist_head refs;
9195 struct got_reflist_entry *re, *re_match;
9196 FILE *f = NULL;
9197 char *uuidstr = NULL;
9198 int added_logmsg = 0;
9200 TAILQ_INIT(&refs);
9202 *logmsg_path = NULL;
9204 err = got_worktree_get_uuid(&uuidstr, worktree);
9205 if (err)
9206 goto done;
9208 err = got_ref_list(&refs, repo, "refs/got/worktree",
9209 got_ref_cmp_by_name, repo);
9210 if (err)
9211 goto done;
9213 TAILQ_FOREACH(re, &refs, entry) {
9214 const char *refname, *type;
9215 struct wt_commitable_path_arg wcpa;
9216 int add_logmsg = 0;
9218 refname = got_ref_get_name(re->ref);
9220 if (strncmp(refname, GOT_WORKTREE_CHERRYPICK_REF_PREFIX,
9221 GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN) == 0) {
9222 refname += GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN + 1;
9223 type = "cherrypicked";
9224 } else if (strncmp(refname, GOT_WORKTREE_BACKOUT_REF_PREFIX,
9225 GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN) == 0) {
9226 refname += GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN + 1;
9227 type = "backed-out";
9228 } else
9229 continue;
9231 if (strncmp(refname, uuidstr, GOT_WORKTREE_UUID_STRLEN) == 0)
9232 refname += GOT_WORKTREE_UUID_STRLEN + 1; /* skip '-' */
9233 else
9234 continue;
9236 err = got_repo_match_object_id(&id, NULL, refname,
9237 GOT_OBJ_TYPE_COMMIT, NULL, repo);
9238 if (err)
9239 goto done;
9241 err = got_object_open_as_commit(&commit, repo, id);
9242 if (err)
9243 goto done;
9245 wcpa.commit_paths = paths;
9246 wcpa.has_changes = &add_logmsg;
9248 err = commit_path_changed_in_worktree(&wcpa, id,
9249 worktree, repo);
9250 if (err)
9251 goto done;
9253 if (add_logmsg) {
9254 if (f == NULL) {
9255 err = got_opentemp_named(logmsg_path, &f,
9256 "got-commit-logmsg", "");
9257 if (err)
9258 goto done;
9260 err = cat_logmsg(f, commit, refname, type,
9261 added_logmsg);
9262 if (err)
9263 goto done;
9264 if (!added_logmsg)
9265 ++added_logmsg;
9267 err = got_reflist_entry_dup(&re_match, re);
9268 if (err)
9269 goto done;
9270 TAILQ_INSERT_HEAD(matched_refs, re_match, entry);
9273 got_object_commit_close(commit);
9274 commit = NULL;
9275 free(id);
9276 id = NULL;
9279 done:
9280 free(id);
9281 free(uuidstr);
9282 got_ref_list_free(&refs);
9283 if (commit)
9284 got_object_commit_close(commit);
9285 if (f && fclose(f) == EOF && err == NULL)
9286 err = got_error_from_errno("fclose");
9287 if (!added_logmsg) {
9288 if (*logmsg_path && unlink(*logmsg_path) != 0 && err == NULL)
9289 err = got_error_from_errno2("unlink", *logmsg_path);
9290 *logmsg_path = NULL;
9292 return err;
9295 static const struct got_error *
9296 cmd_commit(int argc, char *argv[])
9298 const struct got_error *error = NULL;
9299 struct got_worktree *worktree = NULL;
9300 struct got_repository *repo = NULL;
9301 char *cwd = NULL, *id_str = NULL;
9302 struct got_object_id *id = NULL;
9303 const char *logmsg = NULL;
9304 char *prepared_logmsg = NULL, *merged_logmsg = NULL;
9305 struct collect_commit_logmsg_arg cl_arg;
9306 const char *author = NULL;
9307 char *gitconfig_path = NULL, *editor = NULL, *committer = NULL;
9308 int ch, rebase_in_progress, histedit_in_progress, preserve_logmsg = 0;
9309 int allow_bad_symlinks = 0, non_interactive = 0, merge_in_progress = 0;
9310 int show_diff = 1, commit_conflicts = 0;
9311 struct got_pathlist_head paths;
9312 struct got_reflist_head refs;
9313 struct got_reflist_entry *re;
9314 int *pack_fds = NULL;
9316 TAILQ_INIT(&refs);
9317 TAILQ_INIT(&paths);
9318 cl_arg.logmsg_path = NULL;
9320 #ifndef PROFILE
9321 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
9322 "unveil", NULL) == -1)
9323 err(1, "pledge");
9324 #endif
9326 while ((ch = getopt(argc, argv, "A:CF:m:NnS")) != -1) {
9327 switch (ch) {
9328 case 'A':
9329 author = optarg;
9330 error = valid_author(author);
9331 if (error)
9332 return error;
9333 break;
9334 case 'C':
9335 commit_conflicts = 1;
9336 break;
9337 case 'F':
9338 if (logmsg != NULL)
9339 option_conflict('F', 'm');
9340 prepared_logmsg = realpath(optarg, NULL);
9341 if (prepared_logmsg == NULL)
9342 return got_error_from_errno2("realpath",
9343 optarg);
9344 break;
9345 case 'm':
9346 if (prepared_logmsg)
9347 option_conflict('m', 'F');
9348 logmsg = optarg;
9349 break;
9350 case 'N':
9351 non_interactive = 1;
9352 break;
9353 case 'n':
9354 show_diff = 0;
9355 break;
9356 case 'S':
9357 allow_bad_symlinks = 1;
9358 break;
9359 default:
9360 usage_commit();
9361 /* NOTREACHED */
9365 argc -= optind;
9366 argv += optind;
9368 cwd = getcwd(NULL, 0);
9369 if (cwd == NULL) {
9370 error = got_error_from_errno("getcwd");
9371 goto done;
9374 error = got_repo_pack_fds_open(&pack_fds);
9375 if (error != NULL)
9376 goto done;
9378 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
9379 if (error) {
9380 if (error->code == GOT_ERR_NOT_WORKTREE)
9381 error = wrap_not_worktree_error(error, "commit", cwd);
9382 goto done;
9385 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
9386 if (error)
9387 goto done;
9388 if (rebase_in_progress) {
9389 error = got_error(GOT_ERR_REBASING);
9390 goto done;
9393 error = got_worktree_histedit_in_progress(&histedit_in_progress,
9394 worktree);
9395 if (error)
9396 goto done;
9398 error = get_gitconfig_path(&gitconfig_path);
9399 if (error)
9400 goto done;
9401 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
9402 gitconfig_path, pack_fds);
9403 if (error != NULL)
9404 goto done;
9406 error = got_worktree_merge_in_progress(&merge_in_progress, worktree, repo);
9407 if (error)
9408 goto done;
9409 if (merge_in_progress) {
9410 error = got_error(GOT_ERR_MERGE_BUSY);
9411 goto done;
9414 error = get_author(&committer, repo, worktree);
9415 if (error)
9416 goto done;
9418 if (author == NULL)
9419 author = committer;
9421 if (logmsg == NULL || strlen(logmsg) == 0) {
9422 error = get_editor(&editor);
9423 if (error)
9424 goto done;
9425 if (unveil(editor, "x") != 0) {
9426 error = got_error_from_errno2("unveil", editor);
9427 goto done;
9431 error = apply_unveil(got_repo_get_path(repo), 0,
9432 got_worktree_get_root_path(worktree));
9433 if (error)
9434 goto done;
9436 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
9437 if (error)
9438 goto done;
9440 if (prepared_logmsg == NULL) {
9441 error = lookup_logmsg_ref(&merged_logmsg,
9442 argc > 0 ? &paths : NULL, &refs, worktree, repo);
9443 if (error)
9444 goto done;
9447 cl_arg.editor = editor;
9448 cl_arg.cmdline_log = logmsg;
9449 cl_arg.prepared_log = prepared_logmsg;
9450 cl_arg.merged_log = merged_logmsg;
9451 cl_arg.non_interactive = non_interactive;
9452 cl_arg.worktree_path = got_worktree_get_root_path(worktree);
9453 cl_arg.branch_name = got_worktree_get_head_ref_name(worktree);
9454 if (!histedit_in_progress) {
9455 if (strncmp(cl_arg.branch_name, "refs/heads/", 11) != 0) {
9456 error = got_error(GOT_ERR_COMMIT_BRANCH);
9457 goto done;
9459 cl_arg.branch_name += 11;
9461 cl_arg.repo_path = got_repo_get_path(repo);
9462 error = got_worktree_commit(&id, worktree, &paths, author, committer,
9463 allow_bad_symlinks, show_diff, commit_conflicts,
9464 collect_commit_logmsg, &cl_arg, print_status, NULL, repo);
9465 if (error) {
9466 if (error->code != GOT_ERR_COMMIT_MSG_EMPTY &&
9467 cl_arg.logmsg_path != NULL)
9468 preserve_logmsg = 1;
9469 goto done;
9472 error = got_object_id_str(&id_str, id);
9473 if (error)
9474 goto done;
9475 printf("Created commit %s\n", id_str);
9477 TAILQ_FOREACH(re, &refs, entry) {
9478 error = got_ref_delete(re->ref, repo);
9479 if (error)
9480 goto done;
9483 done:
9484 if (preserve_logmsg) {
9485 fprintf(stderr, "%s: log message preserved in %s\n",
9486 getprogname(), cl_arg.logmsg_path);
9487 } else if (cl_arg.logmsg_path && unlink(cl_arg.logmsg_path) == -1 &&
9488 error == NULL)
9489 error = got_error_from_errno2("unlink", cl_arg.logmsg_path);
9490 free(cl_arg.logmsg_path);
9491 if (merged_logmsg && unlink(merged_logmsg) == -1 && error == NULL)
9492 error = got_error_from_errno2("unlink", merged_logmsg);
9493 free(merged_logmsg);
9494 if (repo) {
9495 const struct got_error *close_err = got_repo_close(repo);
9496 if (error == NULL)
9497 error = close_err;
9499 if (worktree)
9500 got_worktree_close(worktree);
9501 if (pack_fds) {
9502 const struct got_error *pack_err =
9503 got_repo_pack_fds_close(pack_fds);
9504 if (error == NULL)
9505 error = pack_err;
9507 got_ref_list_free(&refs);
9508 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
9509 free(cwd);
9510 free(id_str);
9511 free(gitconfig_path);
9512 free(editor);
9513 free(committer);
9514 free(prepared_logmsg);
9515 return error;
9518 __dead static void
9519 usage_send(void)
9521 fprintf(stderr, "usage: %s send [-afqTv] [-b branch] [-d branch] "
9522 "[-r repository-path] [-t tag] [remote-repository]\n",
9523 getprogname());
9524 exit(1);
9527 static void
9528 print_load_info(int print_colored, int print_found, int print_trees,
9529 int ncolored, int nfound, int ntrees)
9531 if (print_colored) {
9532 printf("%d commit%s colored", ncolored,
9533 ncolored == 1 ? "" : "s");
9535 if (print_found) {
9536 printf("%s%d object%s found",
9537 ncolored > 0 ? "; " : "",
9538 nfound, nfound == 1 ? "" : "s");
9540 if (print_trees) {
9541 printf("; %d tree%s scanned", ntrees,
9542 ntrees == 1 ? "" : "s");
9546 struct got_send_progress_arg {
9547 char last_scaled_packsize[FMT_SCALED_STRSIZE];
9548 int verbosity;
9549 int last_ncolored;
9550 int last_nfound;
9551 int last_ntrees;
9552 int loading_done;
9553 int last_ncommits;
9554 int last_nobj_total;
9555 int last_p_deltify;
9556 int last_p_written;
9557 int last_p_sent;
9558 int printed_something;
9559 int sent_something;
9560 struct got_pathlist_head *delete_branches;
9563 static const struct got_error *
9564 send_progress(void *arg, int ncolored, int nfound, int ntrees,
9565 off_t packfile_size, int ncommits, int nobj_total, int nobj_deltify,
9566 int nobj_written, off_t bytes_sent, const char *refname,
9567 const char *errmsg, int success)
9569 struct got_send_progress_arg *a = arg;
9570 char scaled_packsize[FMT_SCALED_STRSIZE];
9571 char scaled_sent[FMT_SCALED_STRSIZE];
9572 int p_deltify = 0, p_written = 0, p_sent = 0;
9573 int print_colored = 0, print_found = 0, print_trees = 0;
9574 int print_searching = 0, print_total = 0;
9575 int print_deltify = 0, print_written = 0, print_sent = 0;
9577 if (a->verbosity < 0)
9578 return NULL;
9580 if (refname) {
9581 const char *status = success ? "accepted" : "rejected";
9583 if (success) {
9584 struct got_pathlist_entry *pe;
9585 TAILQ_FOREACH(pe, a->delete_branches, entry) {
9586 const char *branchname = pe->path;
9587 if (got_path_cmp(branchname, refname,
9588 strlen(branchname), strlen(refname)) == 0) {
9589 status = "deleted";
9590 a->sent_something = 1;
9591 break;
9596 if (a->printed_something)
9597 putchar('\n');
9598 printf("Server has %s %s", status, refname);
9599 if (errmsg)
9600 printf(": %s", errmsg);
9601 a->printed_something = 1;
9602 return NULL;
9605 if (a->last_ncolored != ncolored) {
9606 print_colored = 1;
9607 a->last_ncolored = ncolored;
9610 if (a->last_nfound != nfound) {
9611 print_colored = 1;
9612 print_found = 1;
9613 a->last_nfound = nfound;
9616 if (a->last_ntrees != ntrees) {
9617 print_colored = 1;
9618 print_found = 1;
9619 print_trees = 1;
9620 a->last_ntrees = ntrees;
9623 if ((print_colored || print_found || print_trees) &&
9624 !a->loading_done) {
9625 printf("\r");
9626 print_load_info(print_colored, print_found, print_trees,
9627 ncolored, nfound, ntrees);
9628 a->printed_something = 1;
9629 fflush(stdout);
9630 return NULL;
9631 } else if (!a->loading_done) {
9632 printf("\r");
9633 print_load_info(1, 1, 1, ncolored, nfound, ntrees);
9634 printf("\n");
9635 a->loading_done = 1;
9638 if (fmt_scaled(packfile_size, scaled_packsize) == -1)
9639 return got_error_from_errno("fmt_scaled");
9640 if (fmt_scaled(bytes_sent, scaled_sent) == -1)
9641 return got_error_from_errno("fmt_scaled");
9643 if (a->last_ncommits != ncommits) {
9644 print_searching = 1;
9645 a->last_ncommits = ncommits;
9648 if (a->last_nobj_total != nobj_total) {
9649 print_searching = 1;
9650 print_total = 1;
9651 a->last_nobj_total = nobj_total;
9654 if (packfile_size > 0 && (a->last_scaled_packsize[0] == '\0' ||
9655 strcmp(scaled_packsize, a->last_scaled_packsize)) != 0) {
9656 if (strlcpy(a->last_scaled_packsize, scaled_packsize,
9657 FMT_SCALED_STRSIZE) >= FMT_SCALED_STRSIZE)
9658 return got_error(GOT_ERR_NO_SPACE);
9661 if (nobj_deltify > 0 || nobj_written > 0) {
9662 if (nobj_deltify > 0) {
9663 p_deltify = (nobj_deltify * 100) / nobj_total;
9664 if (p_deltify != a->last_p_deltify) {
9665 a->last_p_deltify = p_deltify;
9666 print_searching = 1;
9667 print_total = 1;
9668 print_deltify = 1;
9671 if (nobj_written > 0) {
9672 p_written = (nobj_written * 100) / nobj_total;
9673 if (p_written != a->last_p_written) {
9674 a->last_p_written = p_written;
9675 print_searching = 1;
9676 print_total = 1;
9677 print_deltify = 1;
9678 print_written = 1;
9683 if (bytes_sent > 0) {
9684 p_sent = (bytes_sent * 100) / packfile_size;
9685 if (p_sent != a->last_p_sent) {
9686 a->last_p_sent = p_sent;
9687 print_searching = 1;
9688 print_total = 1;
9689 print_deltify = 1;
9690 print_written = 1;
9691 print_sent = 1;
9693 a->sent_something = 1;
9696 if (print_searching || print_total || print_deltify || print_written ||
9697 print_sent)
9698 printf("\r");
9699 if (print_searching)
9700 printf("packing %d reference%s", ncommits,
9701 ncommits == 1 ? "" : "s");
9702 if (print_total)
9703 printf("; %d object%s", nobj_total,
9704 nobj_total == 1 ? "" : "s");
9705 if (print_deltify)
9706 printf("; deltify: %d%%", p_deltify);
9707 if (print_sent)
9708 printf("; uploading pack: %*s %d%%", FMT_SCALED_STRSIZE - 2,
9709 scaled_packsize, p_sent);
9710 else if (print_written)
9711 printf("; writing pack: %*s %d%%", FMT_SCALED_STRSIZE - 2,
9712 scaled_packsize, p_written);
9713 if (print_searching || print_total || print_deltify ||
9714 print_written || print_sent) {
9715 a->printed_something = 1;
9716 fflush(stdout);
9718 return NULL;
9721 static const struct got_error *
9722 cmd_send(int argc, char *argv[])
9724 const struct got_error *error = NULL;
9725 char *cwd = NULL, *repo_path = NULL;
9726 const char *remote_name;
9727 char *proto = NULL, *host = NULL, *port = NULL;
9728 char *repo_name = NULL, *server_path = NULL;
9729 const struct got_remote_repo *remotes;
9730 struct got_remote_repo *remote = NULL;
9731 int nremotes, nbranches = 0, ndelete_branches = 0;
9732 struct got_repository *repo = NULL;
9733 struct got_worktree *worktree = NULL;
9734 const struct got_gotconfig *repo_conf = NULL, *worktree_conf = NULL;
9735 struct got_pathlist_head branches;
9736 struct got_pathlist_head tags;
9737 struct got_reflist_head all_branches;
9738 struct got_reflist_head all_tags;
9739 struct got_pathlist_head delete_args;
9740 struct got_pathlist_head delete_branches;
9741 struct got_reflist_entry *re;
9742 struct got_pathlist_entry *pe;
9743 int i, ch, sendfd = -1, sendstatus;
9744 pid_t sendpid = -1;
9745 struct got_send_progress_arg spa;
9746 int verbosity = 0, overwrite_refs = 0;
9747 int send_all_branches = 0, send_all_tags = 0;
9748 struct got_reference *ref = NULL;
9749 int *pack_fds = NULL;
9751 TAILQ_INIT(&branches);
9752 TAILQ_INIT(&tags);
9753 TAILQ_INIT(&all_branches);
9754 TAILQ_INIT(&all_tags);
9755 TAILQ_INIT(&delete_args);
9756 TAILQ_INIT(&delete_branches);
9758 while ((ch = getopt(argc, argv, "ab:d:fqr:Tt:v")) != -1) {
9759 switch (ch) {
9760 case 'a':
9761 send_all_branches = 1;
9762 break;
9763 case 'b':
9764 error = got_pathlist_append(&branches, optarg, NULL);
9765 if (error)
9766 return error;
9767 nbranches++;
9768 break;
9769 case 'd':
9770 error = got_pathlist_append(&delete_args, optarg, NULL);
9771 if (error)
9772 return error;
9773 break;
9774 case 'f':
9775 overwrite_refs = 1;
9776 break;
9777 case 'q':
9778 verbosity = -1;
9779 break;
9780 case 'r':
9781 repo_path = realpath(optarg, NULL);
9782 if (repo_path == NULL)
9783 return got_error_from_errno2("realpath",
9784 optarg);
9785 got_path_strip_trailing_slashes(repo_path);
9786 break;
9787 case 'T':
9788 send_all_tags = 1;
9789 break;
9790 case 't':
9791 error = got_pathlist_append(&tags, optarg, NULL);
9792 if (error)
9793 return error;
9794 break;
9795 case 'v':
9796 if (verbosity < 0)
9797 verbosity = 0;
9798 else if (verbosity < 3)
9799 verbosity++;
9800 break;
9801 default:
9802 usage_send();
9803 /* NOTREACHED */
9806 argc -= optind;
9807 argv += optind;
9809 if (send_all_branches && !TAILQ_EMPTY(&branches))
9810 option_conflict('a', 'b');
9811 if (send_all_tags && !TAILQ_EMPTY(&tags))
9812 option_conflict('T', 't');
9815 if (argc == 0)
9816 remote_name = GOT_SEND_DEFAULT_REMOTE_NAME;
9817 else if (argc == 1)
9818 remote_name = argv[0];
9819 else
9820 usage_send();
9822 cwd = getcwd(NULL, 0);
9823 if (cwd == NULL) {
9824 error = got_error_from_errno("getcwd");
9825 goto done;
9828 error = got_repo_pack_fds_open(&pack_fds);
9829 if (error != NULL)
9830 goto done;
9832 if (repo_path == NULL) {
9833 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
9834 if (error && error->code != GOT_ERR_NOT_WORKTREE)
9835 goto done;
9836 else
9837 error = NULL;
9838 if (worktree) {
9839 repo_path =
9840 strdup(got_worktree_get_repo_path(worktree));
9841 if (repo_path == NULL)
9842 error = got_error_from_errno("strdup");
9843 if (error)
9844 goto done;
9845 } else {
9846 repo_path = strdup(cwd);
9847 if (repo_path == NULL) {
9848 error = got_error_from_errno("strdup");
9849 goto done;
9854 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
9855 if (error)
9856 goto done;
9858 if (worktree) {
9859 worktree_conf = got_worktree_get_gotconfig(worktree);
9860 if (worktree_conf) {
9861 got_gotconfig_get_remotes(&nremotes, &remotes,
9862 worktree_conf);
9863 for (i = 0; i < nremotes; i++) {
9864 if (strcmp(remotes[i].name, remote_name) == 0) {
9865 error = got_repo_remote_repo_dup(&remote,
9866 &remotes[i]);
9867 if (error)
9868 goto done;
9869 break;
9874 if (remote == NULL) {
9875 repo_conf = got_repo_get_gotconfig(repo);
9876 if (repo_conf) {
9877 got_gotconfig_get_remotes(&nremotes, &remotes,
9878 repo_conf);
9879 for (i = 0; i < nremotes; i++) {
9880 if (strcmp(remotes[i].name, remote_name) == 0) {
9881 error = got_repo_remote_repo_dup(&remote,
9882 &remotes[i]);
9883 if (error)
9884 goto done;
9885 break;
9890 if (remote == NULL) {
9891 got_repo_get_gitconfig_remotes(&nremotes, &remotes, repo);
9892 for (i = 0; i < nremotes; i++) {
9893 if (strcmp(remotes[i].name, remote_name) == 0) {
9894 error = got_repo_remote_repo_dup(&remote,
9895 &remotes[i]);
9896 if (error)
9897 goto done;
9898 break;
9902 if (remote == NULL) {
9903 error = got_error_path(remote_name, GOT_ERR_NO_REMOTE);
9904 goto done;
9907 error = got_dial_parse_uri(&proto, &host, &port, &server_path,
9908 &repo_name, remote->send_url);
9909 if (error)
9910 goto done;
9912 if (strcmp(proto, "git") == 0) {
9913 #ifndef PROFILE
9914 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
9915 "sendfd dns inet unveil", NULL) == -1)
9916 err(1, "pledge");
9917 #endif
9918 } else if (strcmp(proto, "git+ssh") == 0 ||
9919 strcmp(proto, "ssh") == 0) {
9920 #ifndef PROFILE
9921 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
9922 "sendfd unveil", NULL) == -1)
9923 err(1, "pledge");
9924 #endif
9925 } else if (strcmp(proto, "http") == 0 ||
9926 strcmp(proto, "git+http") == 0) {
9927 error = got_error_path(proto, GOT_ERR_NOT_IMPL);
9928 goto done;
9929 } else {
9930 error = got_error_path(proto, GOT_ERR_BAD_PROTO);
9931 goto done;
9934 error = got_dial_apply_unveil(proto);
9935 if (error)
9936 goto done;
9938 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
9939 if (error)
9940 goto done;
9942 if (send_all_branches) {
9943 error = got_ref_list(&all_branches, repo, "refs/heads",
9944 got_ref_cmp_by_name, NULL);
9945 if (error)
9946 goto done;
9947 TAILQ_FOREACH(re, &all_branches, entry) {
9948 const char *branchname = got_ref_get_name(re->ref);
9949 error = got_pathlist_append(&branches,
9950 branchname, NULL);
9951 if (error)
9952 goto done;
9953 nbranches++;
9955 } else if (nbranches == 0) {
9956 for (i = 0; i < remote->nsend_branches; i++) {
9957 error = got_pathlist_append(&branches,
9958 remote->send_branches[i], NULL);
9959 if (error)
9960 goto done;
9964 if (send_all_tags) {
9965 error = got_ref_list(&all_tags, repo, "refs/tags",
9966 got_ref_cmp_by_name, NULL);
9967 if (error)
9968 goto done;
9969 TAILQ_FOREACH(re, &all_tags, entry) {
9970 const char *tagname = got_ref_get_name(re->ref);
9971 error = got_pathlist_append(&tags,
9972 tagname, NULL);
9973 if (error)
9974 goto done;
9979 * To prevent accidents only branches in refs/heads/ can be deleted
9980 * with 'got send -d'.
9981 * Deleting anything else requires local repository access or Git.
9983 TAILQ_FOREACH(pe, &delete_args, entry) {
9984 const char *branchname = pe->path;
9985 char *s;
9986 struct got_pathlist_entry *new;
9987 if (strncmp(branchname, "refs/heads/", 11) == 0) {
9988 s = strdup(branchname);
9989 if (s == NULL) {
9990 error = got_error_from_errno("strdup");
9991 goto done;
9993 } else {
9994 if (asprintf(&s, "refs/heads/%s", branchname) == -1) {
9995 error = got_error_from_errno("asprintf");
9996 goto done;
9999 error = got_pathlist_insert(&new, &delete_branches, s, NULL);
10000 if (error || new == NULL /* duplicate */)
10001 free(s);
10002 if (error)
10003 goto done;
10004 ndelete_branches++;
10007 if (nbranches == 0 && ndelete_branches == 0) {
10008 struct got_reference *head_ref;
10009 if (worktree)
10010 error = got_ref_open(&head_ref, repo,
10011 got_worktree_get_head_ref_name(worktree), 0);
10012 else
10013 error = got_ref_open(&head_ref, repo, GOT_REF_HEAD, 0);
10014 if (error)
10015 goto done;
10016 if (got_ref_is_symbolic(head_ref)) {
10017 error = got_ref_resolve_symbolic(&ref, repo, head_ref);
10018 got_ref_close(head_ref);
10019 if (error)
10020 goto done;
10021 } else
10022 ref = head_ref;
10023 error = got_pathlist_append(&branches, got_ref_get_name(ref),
10024 NULL);
10025 if (error)
10026 goto done;
10027 nbranches++;
10030 if (worktree) {
10031 /* Release work tree lock. */
10032 got_worktree_close(worktree);
10033 worktree = NULL;
10036 if (verbosity >= 0) {
10037 printf("Connecting to \"%s\" %s://%s%s%s%s%s\n",
10038 remote->name, proto, host,
10039 port ? ":" : "", port ? port : "",
10040 *server_path == '/' ? "" : "/", server_path);
10043 error = got_send_connect(&sendpid, &sendfd, proto, host, port,
10044 server_path, verbosity);
10045 if (error)
10046 goto done;
10048 memset(&spa, 0, sizeof(spa));
10049 spa.last_scaled_packsize[0] = '\0';
10050 spa.last_p_deltify = -1;
10051 spa.last_p_written = -1;
10052 spa.verbosity = verbosity;
10053 spa.delete_branches = &delete_branches;
10054 error = got_send_pack(remote_name, &branches, &tags, &delete_branches,
10055 verbosity, overwrite_refs, sendfd, repo, send_progress, &spa,
10056 check_cancelled, NULL);
10057 if (spa.printed_something)
10058 putchar('\n');
10059 if (error)
10060 goto done;
10061 if (!spa.sent_something && verbosity >= 0)
10062 printf("Already up-to-date\n");
10063 done:
10064 if (sendpid > 0) {
10065 if (kill(sendpid, SIGTERM) == -1)
10066 error = got_error_from_errno("kill");
10067 if (waitpid(sendpid, &sendstatus, 0) == -1 && error == NULL)
10068 error = got_error_from_errno("waitpid");
10070 if (sendfd != -1 && close(sendfd) == -1 && error == NULL)
10071 error = got_error_from_errno("close");
10072 if (repo) {
10073 const struct got_error *close_err = got_repo_close(repo);
10074 if (error == NULL)
10075 error = close_err;
10077 if (worktree)
10078 got_worktree_close(worktree);
10079 if (pack_fds) {
10080 const struct got_error *pack_err =
10081 got_repo_pack_fds_close(pack_fds);
10082 if (error == NULL)
10083 error = pack_err;
10085 if (ref)
10086 got_ref_close(ref);
10087 got_repo_free_remote_repo_data(remote);
10088 free(remote);
10089 got_pathlist_free(&branches, GOT_PATHLIST_FREE_NONE);
10090 got_pathlist_free(&tags, GOT_PATHLIST_FREE_NONE);
10091 got_ref_list_free(&all_branches);
10092 got_ref_list_free(&all_tags);
10093 got_pathlist_free(&delete_args, GOT_PATHLIST_FREE_NONE);
10094 got_pathlist_free(&delete_branches, GOT_PATHLIST_FREE_PATH);
10095 free(cwd);
10096 free(repo_path);
10097 free(proto);
10098 free(host);
10099 free(port);
10100 free(server_path);
10101 free(repo_name);
10102 return error;
10106 * Print and if delete is set delete all ref_prefix references.
10107 * If wanted_ref is not NULL, only print or delete this reference.
10109 static const struct got_error *
10110 process_logmsg_refs(const char *ref_prefix, size_t prefix_len,
10111 const char *wanted_ref, int delete, struct got_worktree *worktree,
10112 struct got_repository *repo)
10114 const struct got_error *err;
10115 struct got_pathlist_head paths;
10116 struct got_reflist_head refs;
10117 struct got_reflist_entry *re;
10118 struct got_reflist_object_id_map *refs_idmap = NULL;
10119 struct got_commit_object *commit = NULL;
10120 struct got_object_id *id = NULL;
10121 const char *header_prefix;
10122 char *uuidstr = NULL;
10123 int found = 0;
10125 TAILQ_INIT(&refs);
10126 TAILQ_INIT(&paths);
10128 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, repo);
10129 if (err)
10130 goto done;
10132 err = got_reflist_object_id_map_create(&refs_idmap, &refs, repo);
10133 if (err)
10134 goto done;
10136 if (worktree != NULL) {
10137 err = got_worktree_get_uuid(&uuidstr, worktree);
10138 if (err)
10139 goto done;
10142 if (wanted_ref) {
10143 if (strncmp(wanted_ref, "refs/heads/", 11) == 0)
10144 wanted_ref += 11;
10147 if (strcmp(ref_prefix, GOT_WORKTREE_BACKOUT_REF_PREFIX) == 0)
10148 header_prefix = "backout";
10149 else
10150 header_prefix = "cherrypick";
10152 TAILQ_FOREACH(re, &refs, entry) {
10153 const char *refname, *wt;
10155 refname = got_ref_get_name(re->ref);
10157 err = check_cancelled(NULL);
10158 if (err)
10159 goto done;
10161 if (strncmp(refname, ref_prefix, prefix_len) == 0)
10162 refname += prefix_len + 1; /* skip '-' delimiter */
10163 else
10164 continue;
10166 wt = refname;
10168 if (worktree == NULL || strncmp(refname, uuidstr,
10169 GOT_WORKTREE_UUID_STRLEN) == 0)
10170 refname += GOT_WORKTREE_UUID_STRLEN + 1; /* skip '-' */
10171 else
10172 continue;
10174 err = got_repo_match_object_id(&id, NULL, refname,
10175 GOT_OBJ_TYPE_COMMIT, NULL, repo);
10176 if (err)
10177 goto done;
10179 err = got_object_open_as_commit(&commit, repo, id);
10180 if (err)
10181 goto done;
10183 if (wanted_ref)
10184 found = strncmp(wanted_ref, refname,
10185 strlen(wanted_ref)) == 0;
10186 if (wanted_ref && !found) {
10187 struct got_reflist_head *ci_refs;
10189 ci_refs = got_reflist_object_id_map_lookup(refs_idmap,
10190 id);
10192 if (ci_refs) {
10193 char *refs_str = NULL;
10194 char const *r = NULL;
10196 err = build_refs_str(&refs_str, ci_refs, id,
10197 repo, 1);
10198 if (err)
10199 goto done;
10201 r = refs_str;
10202 while (r) {
10203 if (strncmp(r, wanted_ref,
10204 strlen(wanted_ref)) == 0) {
10205 found = 1;
10206 break;
10208 r = strchr(r, ' ');
10209 if (r)
10210 ++r;
10212 free(refs_str);
10216 if (wanted_ref == NULL || found) {
10217 if (delete) {
10218 err = got_ref_delete(re->ref, repo);
10219 if (err)
10220 goto done;
10221 printf("Deleted: ");
10222 err = print_commit_oneline(commit, id, repo,
10223 refs_idmap);
10224 } else {
10226 * Print paths modified by commit to help
10227 * associate commits with worktree changes.
10229 err = get_changed_paths(&paths, commit,
10230 repo, NULL);
10231 if (err)
10232 goto done;
10234 err = print_commit(commit, id, repo, NULL,
10235 &paths, NULL, 0, 0, refs_idmap, NULL,
10236 header_prefix);
10237 got_pathlist_free(&paths,
10238 GOT_PATHLIST_FREE_ALL);
10240 if (worktree == NULL)
10241 printf("work tree: %.*s\n\n",
10242 GOT_WORKTREE_UUID_STRLEN, wt);
10244 if (err || found)
10245 goto done;
10248 got_object_commit_close(commit);
10249 commit = NULL;
10250 free(id);
10251 id = NULL;
10254 if (wanted_ref != NULL && !found)
10255 err = got_error_fmt(GOT_ERR_NOT_REF, "%s", wanted_ref);
10257 done:
10258 free(id);
10259 free(uuidstr);
10260 got_ref_list_free(&refs);
10261 got_pathlist_free(&paths, GOT_PATHLIST_FREE_ALL);
10262 if (refs_idmap)
10263 got_reflist_object_id_map_free(refs_idmap);
10264 if (commit)
10265 got_object_commit_close(commit);
10266 return err;
10270 * Create new temp "logmsg" ref of the backed-out or cherrypicked commit
10271 * identified by id for log messages to prepopulate the editor on commit.
10273 static const struct got_error *
10274 logmsg_ref(struct got_object_id *id, const char *prefix,
10275 struct got_worktree *worktree, struct got_repository *repo)
10277 const struct got_error *err = NULL;
10278 char *idstr, *ref = NULL, *refname = NULL;
10279 int histedit_in_progress;
10280 int rebase_in_progress, merge_in_progress;
10283 * Silenty refuse to create merge reference if any histedit, merge,
10284 * or rebase operation is in progress.
10286 err = got_worktree_histedit_in_progress(&histedit_in_progress,
10287 worktree);
10288 if (err)
10289 return err;
10290 if (histedit_in_progress)
10291 return NULL;
10293 err = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
10294 if (err)
10295 return err;
10296 if (rebase_in_progress)
10297 return NULL;
10299 err = got_worktree_merge_in_progress(&merge_in_progress, worktree,
10300 repo);
10301 if (err)
10302 return err;
10303 if (merge_in_progress)
10304 return NULL;
10306 err = got_object_id_str(&idstr, id);
10307 if (err)
10308 return err;
10310 err = got_worktree_get_logmsg_ref_name(&refname, worktree, prefix);
10311 if (err)
10312 goto done;
10314 if (asprintf(&ref, "%s-%s", refname, idstr) == -1) {
10315 err = got_error_from_errno("asprintf");
10316 goto done;
10319 err = create_ref(ref, got_worktree_get_base_commit_id(worktree),
10320 -1, repo);
10321 done:
10322 free(ref);
10323 free(idstr);
10324 free(refname);
10325 return err;
10328 __dead static void
10329 usage_cherrypick(void)
10331 fprintf(stderr, "usage: %s cherrypick [-lX] [commit-id]\n",
10332 getprogname());
10333 exit(1);
10336 static const struct got_error *
10337 cmd_cherrypick(int argc, char *argv[])
10339 const struct got_error *error = NULL;
10340 struct got_worktree *worktree = NULL;
10341 struct got_repository *repo = NULL;
10342 char *cwd = NULL, *commit_id_str = NULL, *keyword_idstr = NULL;
10343 struct got_object_id *commit_id = NULL;
10344 struct got_commit_object *commit = NULL;
10345 struct got_object_qid *pid;
10346 int ch, list_refs = 0, remove_refs = 0;
10347 struct got_update_progress_arg upa;
10348 int *pack_fds = NULL;
10350 #ifndef PROFILE
10351 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
10352 "unveil", NULL) == -1)
10353 err(1, "pledge");
10354 #endif
10356 while ((ch = getopt(argc, argv, "lX")) != -1) {
10357 switch (ch) {
10358 case 'l':
10359 list_refs = 1;
10360 break;
10361 case 'X':
10362 remove_refs = 1;
10363 break;
10364 default:
10365 usage_cherrypick();
10366 /* NOTREACHED */
10370 argc -= optind;
10371 argv += optind;
10373 if (list_refs || remove_refs) {
10374 if (argc != 0 && argc != 1)
10375 usage_cherrypick();
10376 } else if (argc != 1)
10377 usage_cherrypick();
10378 if (list_refs && remove_refs)
10379 option_conflict('l', 'X');
10381 cwd = getcwd(NULL, 0);
10382 if (cwd == NULL) {
10383 error = got_error_from_errno("getcwd");
10384 goto done;
10387 error = got_repo_pack_fds_open(&pack_fds);
10388 if (error != NULL)
10389 goto done;
10391 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
10392 if (error) {
10393 if (list_refs || remove_refs) {
10394 if (error->code != GOT_ERR_NOT_WORKTREE)
10395 goto done;
10396 } else {
10397 if (error->code == GOT_ERR_NOT_WORKTREE)
10398 error = wrap_not_worktree_error(error,
10399 "cherrypick", cwd);
10400 goto done;
10404 error = got_repo_open(&repo,
10405 worktree ? got_worktree_get_repo_path(worktree) : cwd,
10406 NULL, pack_fds);
10407 if (error != NULL)
10408 goto done;
10410 error = apply_unveil(got_repo_get_path(repo), 0,
10411 worktree ? got_worktree_get_root_path(worktree) : NULL);
10412 if (error)
10413 goto done;
10415 if (list_refs || remove_refs) {
10416 error = process_logmsg_refs(GOT_WORKTREE_CHERRYPICK_REF_PREFIX,
10417 GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN,
10418 argc == 1 ? argv[0] : NULL, remove_refs, worktree, repo);
10419 goto done;
10422 error = got_keyword_to_idstr(&keyword_idstr, argv[0], repo, worktree);
10423 if (error != NULL)
10424 goto done;
10426 error = got_repo_match_object_id(&commit_id, NULL,
10427 keyword_idstr != NULL ? keyword_idstr : argv[0],
10428 GOT_OBJ_TYPE_COMMIT, NULL, repo);
10429 if (error)
10430 goto done;
10431 error = got_object_id_str(&commit_id_str, commit_id);
10432 if (error)
10433 goto done;
10435 error = got_object_open_as_commit(&commit, repo, commit_id);
10436 if (error)
10437 goto done;
10438 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
10439 memset(&upa, 0, sizeof(upa));
10440 error = got_worktree_merge_files(worktree, pid ? &pid->id : NULL,
10441 commit_id, repo, update_progress, &upa, check_cancelled,
10442 NULL);
10443 if (error != NULL)
10444 goto done;
10446 if (upa.did_something) {
10447 error = logmsg_ref(commit_id,
10448 GOT_WORKTREE_CHERRYPICK_REF_PREFIX, worktree, repo);
10449 if (error)
10450 goto done;
10451 printf("Merged commit %s\n", commit_id_str);
10453 print_merge_progress_stats(&upa);
10454 done:
10455 free(cwd);
10456 free(keyword_idstr);
10457 if (commit)
10458 got_object_commit_close(commit);
10459 free(commit_id_str);
10460 if (worktree)
10461 got_worktree_close(worktree);
10462 if (repo) {
10463 const struct got_error *close_err = got_repo_close(repo);
10464 if (error == NULL)
10465 error = close_err;
10467 if (pack_fds) {
10468 const struct got_error *pack_err =
10469 got_repo_pack_fds_close(pack_fds);
10470 if (error == NULL)
10471 error = pack_err;
10474 return error;
10477 __dead static void
10478 usage_backout(void)
10480 fprintf(stderr, "usage: %s backout [-lX] [commit-id]\n", getprogname());
10481 exit(1);
10484 static const struct got_error *
10485 cmd_backout(int argc, char *argv[])
10487 const struct got_error *error = NULL;
10488 struct got_worktree *worktree = NULL;
10489 struct got_repository *repo = NULL;
10490 char *cwd = NULL, *commit_id_str = NULL, *keyword_idstr = NULL;
10491 struct got_object_id *commit_id = NULL;
10492 struct got_commit_object *commit = NULL;
10493 struct got_object_qid *pid;
10494 int ch, list_refs = 0, remove_refs = 0;
10495 struct got_update_progress_arg upa;
10496 int *pack_fds = NULL;
10498 #ifndef PROFILE
10499 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
10500 "unveil", NULL) == -1)
10501 err(1, "pledge");
10502 #endif
10504 while ((ch = getopt(argc, argv, "lX")) != -1) {
10505 switch (ch) {
10506 case 'l':
10507 list_refs = 1;
10508 break;
10509 case 'X':
10510 remove_refs = 1;
10511 break;
10512 default:
10513 usage_backout();
10514 /* NOTREACHED */
10518 argc -= optind;
10519 argv += optind;
10521 if (list_refs || remove_refs) {
10522 if (argc != 0 && argc != 1)
10523 usage_backout();
10524 } else if (argc != 1)
10525 usage_backout();
10526 if (list_refs && remove_refs)
10527 option_conflict('l', 'X');
10529 cwd = getcwd(NULL, 0);
10530 if (cwd == NULL) {
10531 error = got_error_from_errno("getcwd");
10532 goto done;
10535 error = got_repo_pack_fds_open(&pack_fds);
10536 if (error != NULL)
10537 goto done;
10539 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
10540 if (error) {
10541 if (list_refs || remove_refs) {
10542 if (error->code != GOT_ERR_NOT_WORKTREE)
10543 goto done;
10544 } else {
10545 if (error->code == GOT_ERR_NOT_WORKTREE)
10546 error = wrap_not_worktree_error(error,
10547 "backout", cwd);
10548 goto done;
10552 error = got_repo_open(&repo,
10553 worktree ? got_worktree_get_repo_path(worktree) : cwd,
10554 NULL, pack_fds);
10555 if (error != NULL)
10556 goto done;
10558 error = apply_unveil(got_repo_get_path(repo), 0,
10559 worktree ? got_worktree_get_root_path(worktree) : NULL);
10560 if (error)
10561 goto done;
10563 if (list_refs || remove_refs) {
10564 error = process_logmsg_refs(GOT_WORKTREE_BACKOUT_REF_PREFIX,
10565 GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN,
10566 argc == 1 ? argv[0] : NULL, remove_refs, worktree, repo);
10567 goto done;
10570 error = got_keyword_to_idstr(&keyword_idstr, argv[0], repo, worktree);
10571 if (error != NULL)
10572 goto done;
10574 error = got_repo_match_object_id(&commit_id, NULL,
10575 keyword_idstr != NULL ? keyword_idstr : argv[0],
10576 GOT_OBJ_TYPE_COMMIT, NULL, repo);
10577 if (error)
10578 goto done;
10579 error = got_object_id_str(&commit_id_str, commit_id);
10580 if (error)
10581 goto done;
10583 error = got_object_open_as_commit(&commit, repo, commit_id);
10584 if (error)
10585 goto done;
10586 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
10587 if (pid == NULL) {
10588 error = got_error(GOT_ERR_ROOT_COMMIT);
10589 goto done;
10592 memset(&upa, 0, sizeof(upa));
10593 error = got_worktree_merge_files(worktree, commit_id, &pid->id,
10594 repo, update_progress, &upa, check_cancelled, NULL);
10595 if (error != NULL)
10596 goto done;
10598 if (upa.did_something) {
10599 error = logmsg_ref(commit_id, GOT_WORKTREE_BACKOUT_REF_PREFIX,
10600 worktree, repo);
10601 if (error)
10602 goto done;
10603 printf("Backed out commit %s\n", commit_id_str);
10605 print_merge_progress_stats(&upa);
10606 done:
10607 free(cwd);
10608 free(keyword_idstr);
10609 if (commit)
10610 got_object_commit_close(commit);
10611 free(commit_id_str);
10612 if (worktree)
10613 got_worktree_close(worktree);
10614 if (repo) {
10615 const struct got_error *close_err = got_repo_close(repo);
10616 if (error == NULL)
10617 error = close_err;
10619 if (pack_fds) {
10620 const struct got_error *pack_err =
10621 got_repo_pack_fds_close(pack_fds);
10622 if (error == NULL)
10623 error = pack_err;
10625 return error;
10628 __dead static void
10629 usage_rebase(void)
10631 fprintf(stderr, "usage: %s rebase [-aCclX] [branch]\n", getprogname());
10632 exit(1);
10635 static void
10636 trim_logmsg(char *logmsg, int limit)
10638 char *nl;
10639 size_t len;
10641 len = strlen(logmsg);
10642 if (len > limit)
10643 len = limit;
10644 logmsg[len] = '\0';
10645 nl = strchr(logmsg, '\n');
10646 if (nl)
10647 *nl = '\0';
10650 static const struct got_error *
10651 get_short_logmsg(char **logmsg, int limit, struct got_commit_object *commit)
10653 const struct got_error *err;
10654 char *logmsg0 = NULL;
10655 const char *s;
10657 err = got_object_commit_get_logmsg(&logmsg0, commit);
10658 if (err)
10659 return err;
10661 s = logmsg0;
10662 while (isspace((unsigned char)s[0]))
10663 s++;
10665 *logmsg = strdup(s);
10666 if (*logmsg == NULL) {
10667 err = got_error_from_errno("strdup");
10668 goto done;
10671 trim_logmsg(*logmsg, limit);
10672 done:
10673 free(logmsg0);
10674 return err;
10677 static const struct got_error *
10678 show_rebase_merge_conflict(struct got_object_id *id,
10679 struct got_repository *repo)
10681 const struct got_error *err;
10682 struct got_commit_object *commit = NULL;
10683 char *id_str = NULL, *logmsg = NULL;
10685 err = got_object_open_as_commit(&commit, repo, id);
10686 if (err)
10687 return err;
10689 err = got_object_id_str(&id_str, id);
10690 if (err)
10691 goto done;
10693 id_str[12] = '\0';
10695 err = get_short_logmsg(&logmsg, 42, commit);
10696 if (err)
10697 goto done;
10699 printf("%s -> merge conflict: %s\n", id_str, logmsg);
10700 done:
10701 free(id_str);
10702 got_object_commit_close(commit);
10703 free(logmsg);
10704 return err;
10707 static const struct got_error *
10708 show_rebase_progress(struct got_commit_object *commit,
10709 struct got_object_id *old_id, struct got_object_id *new_id)
10711 const struct got_error *err;
10712 char *old_id_str = NULL, *new_id_str = NULL, *logmsg = NULL;
10714 err = got_object_id_str(&old_id_str, old_id);
10715 if (err)
10716 goto done;
10718 if (new_id) {
10719 err = got_object_id_str(&new_id_str, new_id);
10720 if (err)
10721 goto done;
10724 old_id_str[12] = '\0';
10725 if (new_id_str)
10726 new_id_str[12] = '\0';
10728 err = get_short_logmsg(&logmsg, 42, commit);
10729 if (err)
10730 goto done;
10732 printf("%s -> %s: %s\n", old_id_str,
10733 new_id_str ? new_id_str : "no-op change", logmsg);
10734 done:
10735 free(old_id_str);
10736 free(new_id_str);
10737 free(logmsg);
10738 return err;
10741 static const struct got_error *
10742 rebase_complete(struct got_worktree *worktree, struct got_fileindex *fileindex,
10743 struct got_reference *branch, struct got_reference *tmp_branch,
10744 struct got_repository *repo, int create_backup)
10746 printf("Switching work tree to %s\n", got_ref_get_name(branch));
10747 return got_worktree_rebase_complete(worktree, fileindex,
10748 tmp_branch, branch, repo, create_backup);
10751 static const struct got_error *
10752 rebase_commit(struct got_pathlist_head *merged_paths,
10753 struct got_worktree *worktree, struct got_fileindex *fileindex,
10754 struct got_reference *tmp_branch, const char *committer,
10755 struct got_object_id *commit_id, int allow_conflict,
10756 struct got_repository *repo)
10758 const struct got_error *error;
10759 struct got_commit_object *commit;
10760 struct got_object_id *new_commit_id;
10762 error = got_object_open_as_commit(&commit, repo, commit_id);
10763 if (error)
10764 return error;
10766 error = got_worktree_rebase_commit(&new_commit_id, merged_paths,
10767 worktree, fileindex, tmp_branch, committer, commit, commit_id,
10768 allow_conflict, repo);
10769 if (error) {
10770 if (error->code != GOT_ERR_COMMIT_NO_CHANGES)
10771 goto done;
10772 error = show_rebase_progress(commit, commit_id, NULL);
10773 } else {
10774 error = show_rebase_progress(commit, commit_id, new_commit_id);
10775 free(new_commit_id);
10777 done:
10778 got_object_commit_close(commit);
10779 return error;
10782 struct check_path_prefix_arg {
10783 const char *path_prefix;
10784 size_t len;
10785 int errcode;
10788 static const struct got_error *
10789 check_path_prefix_in_diff(void *arg, struct got_blob_object *blob1,
10790 struct got_blob_object *blob2, FILE *f1, FILE *f2,
10791 struct got_object_id *id1, struct got_object_id *id2,
10792 const char *path1, const char *path2,
10793 mode_t mode1, mode_t mode2, struct got_repository *repo)
10795 struct check_path_prefix_arg *a = arg;
10797 if ((path1 && !got_path_is_child(path1, a->path_prefix, a->len)) ||
10798 (path2 && !got_path_is_child(path2, a->path_prefix, a->len)))
10799 return got_error(a->errcode);
10801 return NULL;
10804 static const struct got_error *
10805 check_path_prefix(struct got_object_id *parent_id,
10806 struct got_object_id *commit_id, const char *path_prefix,
10807 int errcode, struct got_repository *repo)
10809 const struct got_error *err;
10810 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
10811 struct got_commit_object *commit = NULL, *parent_commit = NULL;
10812 struct check_path_prefix_arg cpp_arg;
10814 if (got_path_is_root_dir(path_prefix))
10815 return NULL;
10817 err = got_object_open_as_commit(&commit, repo, commit_id);
10818 if (err)
10819 goto done;
10821 err = got_object_open_as_commit(&parent_commit, repo, parent_id);
10822 if (err)
10823 goto done;
10825 err = got_object_open_as_tree(&tree1, repo,
10826 got_object_commit_get_tree_id(parent_commit));
10827 if (err)
10828 goto done;
10830 err = got_object_open_as_tree(&tree2, repo,
10831 got_object_commit_get_tree_id(commit));
10832 if (err)
10833 goto done;
10835 cpp_arg.path_prefix = path_prefix;
10836 while (cpp_arg.path_prefix[0] == '/')
10837 cpp_arg.path_prefix++;
10838 cpp_arg.len = strlen(cpp_arg.path_prefix);
10839 cpp_arg.errcode = errcode;
10840 err = got_diff_tree(tree1, tree2, NULL, NULL, -1, -1, "", "", repo,
10841 check_path_prefix_in_diff, &cpp_arg, 0);
10842 done:
10843 if (tree1)
10844 got_object_tree_close(tree1);
10845 if (tree2)
10846 got_object_tree_close(tree2);
10847 if (commit)
10848 got_object_commit_close(commit);
10849 if (parent_commit)
10850 got_object_commit_close(parent_commit);
10851 return err;
10854 static const struct got_error *
10855 collect_commits(struct got_object_id_queue *commits,
10856 struct got_object_id *initial_commit_id,
10857 struct got_object_id *iter_start_id, struct got_object_id *iter_stop_id,
10858 const char *path_prefix, int path_prefix_errcode,
10859 struct got_repository *repo)
10861 const struct got_error *err = NULL;
10862 struct got_commit_graph *graph = NULL;
10863 struct got_object_id parent_id, commit_id;
10864 struct got_object_qid *qid;
10866 err = got_commit_graph_open(&graph, "/", 1);
10867 if (err)
10868 return err;
10870 err = got_commit_graph_bfsort(graph, iter_start_id, repo,
10871 check_cancelled, NULL);
10872 if (err)
10873 goto done;
10875 memcpy(&commit_id, initial_commit_id, sizeof(commit_id));
10876 while (got_object_id_cmp(&commit_id, iter_stop_id) != 0) {
10877 err = got_commit_graph_iter_next(&parent_id, graph, repo,
10878 check_cancelled, NULL);
10879 if (err) {
10880 if (err->code == GOT_ERR_ITER_COMPLETED) {
10881 err = got_error_msg(GOT_ERR_ANCESTRY,
10882 "ran out of commits to rebase before "
10883 "youngest common ancestor commit has "
10884 "been reached?!?");
10886 goto done;
10887 } else {
10888 err = check_path_prefix(&parent_id, &commit_id,
10889 path_prefix, path_prefix_errcode, repo);
10890 if (err)
10891 goto done;
10893 err = got_object_qid_alloc(&qid, &commit_id);
10894 if (err)
10895 goto done;
10896 STAILQ_INSERT_HEAD(commits, qid, entry);
10898 memcpy(&commit_id, &parent_id, sizeof(commit_id));
10901 done:
10902 got_commit_graph_close(graph);
10903 return err;
10906 static const struct got_error *
10907 get_commit_brief_str(char **brief_str, struct got_commit_object *commit)
10909 const struct got_error *err = NULL;
10910 time_t committer_time;
10911 struct tm tm;
10912 char datebuf[11]; /* YYYY-MM-DD + NUL */
10913 char *author0 = NULL, *author, *smallerthan;
10914 char *logmsg0 = NULL, *logmsg, *newline;
10916 committer_time = got_object_commit_get_committer_time(commit);
10917 if (gmtime_r(&committer_time, &tm) == NULL)
10918 return got_error_from_errno("gmtime_r");
10919 if (strftime(datebuf, sizeof(datebuf), "%G-%m-%d", &tm) == 0)
10920 return got_error(GOT_ERR_NO_SPACE);
10922 author0 = strdup(got_object_commit_get_author(commit));
10923 if (author0 == NULL)
10924 return got_error_from_errno("strdup");
10925 author = author0;
10926 smallerthan = strchr(author, '<');
10927 if (smallerthan && smallerthan[1] != '\0')
10928 author = smallerthan + 1;
10929 author[strcspn(author, "@>")] = '\0';
10931 err = got_object_commit_get_logmsg(&logmsg0, commit);
10932 if (err)
10933 goto done;
10934 logmsg = logmsg0;
10935 while (*logmsg == '\n')
10936 logmsg++;
10937 newline = strchr(logmsg, '\n');
10938 if (newline)
10939 *newline = '\0';
10941 if (asprintf(brief_str, "%s %s %s",
10942 datebuf, author, logmsg) == -1)
10943 err = got_error_from_errno("asprintf");
10944 done:
10945 free(author0);
10946 free(logmsg0);
10947 return err;
10950 static const struct got_error *
10951 delete_backup_ref(struct got_reference *ref, struct got_object_id *id,
10952 struct got_repository *repo)
10954 const struct got_error *err;
10955 char *id_str;
10957 err = got_object_id_str(&id_str, id);
10958 if (err)
10959 return err;
10961 err = got_ref_delete(ref, repo);
10962 if (err)
10963 goto done;
10965 printf("Deleted %s: %s\n", got_ref_get_name(ref), id_str);
10966 done:
10967 free(id_str);
10968 return err;
10971 static const struct got_error *
10972 print_backup_ref(const char *branch_name, const char *new_id_str,
10973 struct got_object_id *old_commit_id, struct got_commit_object *old_commit,
10974 struct got_reflist_object_id_map *refs_idmap,
10975 struct got_repository *repo)
10977 const struct got_error *err = NULL;
10978 struct got_reflist_head *refs;
10979 char *refs_str = NULL;
10980 struct got_object_id *new_commit_id = NULL;
10981 struct got_commit_object *new_commit = NULL;
10982 char *new_commit_brief_str = NULL;
10983 struct got_object_id *yca_id = NULL;
10984 struct got_commit_object *yca_commit = NULL;
10985 char *yca_id_str = NULL, *yca_brief_str = NULL;
10986 char *custom_refs_str;
10988 if (asprintf(&custom_refs_str, "formerly %s", branch_name) == -1)
10989 return got_error_from_errno("asprintf");
10991 err = print_commit(old_commit, old_commit_id, repo, NULL, NULL, NULL,
10992 0, 0, refs_idmap, custom_refs_str, NULL);
10993 if (err)
10994 goto done;
10996 err = got_object_resolve_id_str(&new_commit_id, repo, new_id_str);
10997 if (err)
10998 goto done;
11000 refs = got_reflist_object_id_map_lookup(refs_idmap, new_commit_id);
11001 if (refs) {
11002 err = build_refs_str(&refs_str, refs, new_commit_id, repo, 0);
11003 if (err)
11004 goto done;
11007 err = got_object_open_as_commit(&new_commit, repo, new_commit_id);
11008 if (err)
11009 goto done;
11011 err = get_commit_brief_str(&new_commit_brief_str, new_commit);
11012 if (err)
11013 goto done;
11015 err = got_commit_graph_find_youngest_common_ancestor(&yca_id,
11016 old_commit_id, new_commit_id, 1, 0, repo, check_cancelled, NULL);
11017 if (err)
11018 goto done;
11020 printf("has become commit %s%s%s%s\n %s\n", new_id_str,
11021 refs_str ? " (" : "", refs_str ? refs_str : "",
11022 refs_str ? ")" : "", new_commit_brief_str);
11023 if (yca_id && got_object_id_cmp(yca_id, new_commit_id) != 0 &&
11024 got_object_id_cmp(yca_id, old_commit_id) != 0) {
11025 free(refs_str);
11026 refs_str = NULL;
11028 err = got_object_open_as_commit(&yca_commit, repo, yca_id);
11029 if (err)
11030 goto done;
11032 err = get_commit_brief_str(&yca_brief_str, yca_commit);
11033 if (err)
11034 goto done;
11036 err = got_object_id_str(&yca_id_str, yca_id);
11037 if (err)
11038 goto done;
11040 refs = got_reflist_object_id_map_lookup(refs_idmap, yca_id);
11041 if (refs) {
11042 err = build_refs_str(&refs_str, refs, yca_id, repo, 0);
11043 if (err)
11044 goto done;
11046 printf("history forked at %s%s%s%s\n %s\n",
11047 yca_id_str,
11048 refs_str ? " (" : "", refs_str ? refs_str : "",
11049 refs_str ? ")" : "", yca_brief_str);
11051 done:
11052 free(custom_refs_str);
11053 free(new_commit_id);
11054 free(refs_str);
11055 free(yca_id);
11056 free(yca_id_str);
11057 free(yca_brief_str);
11058 if (new_commit)
11059 got_object_commit_close(new_commit);
11060 if (yca_commit)
11061 got_object_commit_close(yca_commit);
11063 return err;
11066 static const struct got_error *
11067 worktree_has_logmsg_ref(const char *caller, struct got_worktree *worktree,
11068 struct got_repository *repo)
11070 const struct got_error *err;
11071 struct got_reflist_head refs;
11072 struct got_reflist_entry *re;
11073 char *uuidstr = NULL;
11074 static char msg[160];
11076 TAILQ_INIT(&refs);
11078 err = got_worktree_get_uuid(&uuidstr, worktree);
11079 if (err)
11080 goto done;
11082 err = got_ref_list(&refs, repo, "refs/got/worktree",
11083 got_ref_cmp_by_name, repo);
11084 if (err)
11085 goto done;
11087 TAILQ_FOREACH(re, &refs, entry) {
11088 const char *cmd, *refname, *type;
11090 refname = got_ref_get_name(re->ref);
11092 if (strncmp(refname, GOT_WORKTREE_CHERRYPICK_REF_PREFIX,
11093 GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN) == 0) {
11094 refname += GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN + 1;
11095 cmd = "cherrypick";
11096 type = "cherrypicked";
11097 } else if (strncmp(refname, GOT_WORKTREE_BACKOUT_REF_PREFIX,
11098 GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN) == 0) {
11099 refname += GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN + 1;
11100 cmd = "backout";
11101 type = "backed-out";
11102 } else
11103 continue;
11105 if (strncmp(refname, uuidstr, GOT_WORKTREE_UUID_STRLEN) != 0)
11106 continue;
11108 snprintf(msg, sizeof(msg),
11109 "work tree has references created by %s commits which "
11110 "must be removed with 'got %s -X' before running the %s "
11111 "command", type, cmd, caller);
11112 err = got_error_msg(GOT_ERR_WORKTREE_META, msg);
11113 goto done;
11116 done:
11117 free(uuidstr);
11118 got_ref_list_free(&refs);
11119 return err;
11122 static const struct got_error *
11123 process_backup_refs(const char *backup_ref_prefix,
11124 const char *wanted_branch_name,
11125 int delete, struct got_repository *repo)
11127 const struct got_error *err;
11128 struct got_reflist_head refs, backup_refs;
11129 struct got_reflist_entry *re;
11130 const size_t backup_ref_prefix_len = strlen(backup_ref_prefix);
11131 struct got_object_id *old_commit_id = NULL;
11132 char *branch_name = NULL;
11133 struct got_commit_object *old_commit = NULL;
11134 struct got_reflist_object_id_map *refs_idmap = NULL;
11135 int wanted_branch_found = 0;
11137 TAILQ_INIT(&refs);
11138 TAILQ_INIT(&backup_refs);
11140 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
11141 if (err)
11142 return err;
11144 err = got_reflist_object_id_map_create(&refs_idmap, &refs, repo);
11145 if (err)
11146 goto done;
11148 if (wanted_branch_name) {
11149 if (strncmp(wanted_branch_name, "refs/heads/", 11) == 0)
11150 wanted_branch_name += 11;
11153 err = got_ref_list(&backup_refs, repo, backup_ref_prefix,
11154 got_ref_cmp_by_commit_timestamp_descending, repo);
11155 if (err)
11156 goto done;
11158 TAILQ_FOREACH(re, &backup_refs, entry) {
11159 const char *refname = got_ref_get_name(re->ref);
11160 char *slash;
11162 err = check_cancelled(NULL);
11163 if (err)
11164 break;
11166 err = got_ref_resolve(&old_commit_id, repo, re->ref);
11167 if (err)
11168 break;
11170 err = got_object_open_as_commit(&old_commit, repo,
11171 old_commit_id);
11172 if (err)
11173 break;
11175 if (strncmp(backup_ref_prefix, refname,
11176 backup_ref_prefix_len) == 0)
11177 refname += backup_ref_prefix_len;
11179 while (refname[0] == '/')
11180 refname++;
11182 branch_name = strdup(refname);
11183 if (branch_name == NULL) {
11184 err = got_error_from_errno("strdup");
11185 break;
11187 slash = strrchr(branch_name, '/');
11188 if (slash) {
11189 *slash = '\0';
11190 refname += strlen(branch_name) + 1;
11193 if (wanted_branch_name == NULL ||
11194 strcmp(wanted_branch_name, branch_name) == 0) {
11195 wanted_branch_found = 1;
11196 if (delete) {
11197 err = delete_backup_ref(re->ref,
11198 old_commit_id, repo);
11199 } else {
11200 err = print_backup_ref(branch_name, refname,
11201 old_commit_id, old_commit, refs_idmap,
11202 repo);
11204 if (err)
11205 break;
11208 free(old_commit_id);
11209 old_commit_id = NULL;
11210 free(branch_name);
11211 branch_name = NULL;
11212 got_object_commit_close(old_commit);
11213 old_commit = NULL;
11216 if (wanted_branch_name && !wanted_branch_found) {
11217 err = got_error_fmt(GOT_ERR_NOT_REF,
11218 "%s/%s/", backup_ref_prefix, wanted_branch_name);
11220 done:
11221 if (refs_idmap)
11222 got_reflist_object_id_map_free(refs_idmap);
11223 got_ref_list_free(&refs);
11224 got_ref_list_free(&backup_refs);
11225 free(old_commit_id);
11226 free(branch_name);
11227 if (old_commit)
11228 got_object_commit_close(old_commit);
11229 return err;
11232 static const struct got_error *
11233 abort_progress(void *arg, unsigned char status, const char *path)
11236 * Unversioned files should not clutter progress output when
11237 * an operation is aborted.
11239 if (status == GOT_STATUS_UNVERSIONED)
11240 return NULL;
11242 return update_progress(arg, status, path);
11245 static const struct got_error *
11246 find_merge_commit_yca(struct got_object_id **new_yca_id,
11247 struct got_object_id *branch_head_commit_id,
11248 struct got_object_id *yca_id,
11249 struct got_object_id *base_commit_id,
11250 struct got_repository *repo)
11252 const struct got_error *err = NULL;
11253 struct got_commit_graph *graph = NULL;
11254 struct got_commit_object *commit = NULL;
11256 *new_yca_id = NULL;
11258 err = got_commit_graph_open(&graph, "/", 1);
11259 if (err)
11260 return err;
11262 err = got_commit_graph_bfsort(graph, base_commit_id,
11263 repo, check_cancelled, NULL);
11264 if (err)
11265 goto done;
11267 for (;;) {
11268 struct got_object_id id;
11270 err = got_commit_graph_iter_next(&id, graph, repo,
11271 check_cancelled, NULL);
11272 if (err) {
11273 if (err->code == GOT_ERR_ITER_COMPLETED)
11274 err = NULL;
11275 break;
11278 err = got_object_open_as_commit(&commit, repo, &id);
11279 if (err)
11280 break;
11282 if (got_object_commit_get_nparents(commit) > 1) {
11283 /* Search for a better YCA using toposort. */
11284 err = got_commit_graph_find_youngest_common_ancestor(
11285 new_yca_id, base_commit_id, branch_head_commit_id,
11286 0, 1, repo, check_cancelled, NULL);
11287 break;
11290 if (got_object_id_cmp(&id, yca_id) == 0)
11291 break;
11292 got_object_commit_close(commit);
11293 commit = NULL;
11295 done:
11296 got_commit_graph_close(graph);
11297 if (commit)
11298 got_object_commit_close(commit);
11299 return err;
11302 static const struct got_error *
11303 cmd_rebase(int argc, char *argv[])
11305 const struct got_error *error = NULL;
11306 struct got_worktree *worktree = NULL;
11307 struct got_repository *repo = NULL;
11308 struct got_fileindex *fileindex = NULL;
11309 char *cwd = NULL, *committer = NULL, *gitconfig_path = NULL;
11310 struct got_reference *branch = NULL;
11311 struct got_reference *new_base_branch = NULL, *tmp_branch = NULL;
11312 struct got_object_id *commit_id = NULL, *parent_id = NULL;
11313 struct got_object_id *resume_commit_id = NULL;
11314 struct got_object_id *branch_head_commit_id = NULL, *yca_id = NULL;
11315 struct got_object_id *head_commit_id = NULL;
11316 struct got_reference *head_ref = NULL;
11317 struct got_commit_object *commit = NULL;
11318 int ch, rebase_in_progress = 0, abort_rebase = 0, continue_rebase = 0;
11319 int histedit_in_progress = 0, merge_in_progress = 0;
11320 int create_backup = 1, list_backups = 0, delete_backups = 0;
11321 int allow_conflict = 0;
11322 struct got_object_id_queue commits;
11323 struct got_pathlist_head merged_paths;
11324 const struct got_object_id_queue *parent_ids;
11325 struct got_object_qid *qid, *pid;
11326 struct got_update_progress_arg upa;
11327 int *pack_fds = NULL;
11329 STAILQ_INIT(&commits);
11330 TAILQ_INIT(&merged_paths);
11331 memset(&upa, 0, sizeof(upa));
11333 #ifndef PROFILE
11334 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
11335 "unveil", NULL) == -1)
11336 err(1, "pledge");
11337 #endif
11339 while ((ch = getopt(argc, argv, "aCclX")) != -1) {
11340 switch (ch) {
11341 case 'a':
11342 abort_rebase = 1;
11343 break;
11344 case 'C':
11345 allow_conflict = 1;
11346 break;
11347 case 'c':
11348 continue_rebase = 1;
11349 break;
11350 case 'l':
11351 list_backups = 1;
11352 break;
11353 case 'X':
11354 delete_backups = 1;
11355 break;
11356 default:
11357 usage_rebase();
11358 /* NOTREACHED */
11362 argc -= optind;
11363 argv += optind;
11365 if (list_backups) {
11366 if (abort_rebase)
11367 option_conflict('l', 'a');
11368 if (allow_conflict)
11369 option_conflict('l', 'C');
11370 if (continue_rebase)
11371 option_conflict('l', 'c');
11372 if (delete_backups)
11373 option_conflict('l', 'X');
11374 if (argc != 0 && argc != 1)
11375 usage_rebase();
11376 } else if (delete_backups) {
11377 if (abort_rebase)
11378 option_conflict('X', 'a');
11379 if (allow_conflict)
11380 option_conflict('X', 'C');
11381 if (continue_rebase)
11382 option_conflict('X', 'c');
11383 if (list_backups)
11384 option_conflict('l', 'X');
11385 if (argc != 0 && argc != 1)
11386 usage_rebase();
11387 } else if (allow_conflict) {
11388 if (abort_rebase)
11389 option_conflict('C', 'a');
11390 if (!continue_rebase)
11391 errx(1, "-C option requires -c");
11392 } else {
11393 if (abort_rebase && continue_rebase)
11394 usage_rebase();
11395 else if (abort_rebase || continue_rebase) {
11396 if (argc != 0)
11397 usage_rebase();
11398 } else if (argc != 1)
11399 usage_rebase();
11402 cwd = getcwd(NULL, 0);
11403 if (cwd == NULL) {
11404 error = got_error_from_errno("getcwd");
11405 goto done;
11408 error = got_repo_pack_fds_open(&pack_fds);
11409 if (error != NULL)
11410 goto done;
11412 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
11413 if (error) {
11414 if (list_backups || delete_backups) {
11415 if (error->code != GOT_ERR_NOT_WORKTREE)
11416 goto done;
11417 } else {
11418 if (error->code == GOT_ERR_NOT_WORKTREE)
11419 error = wrap_not_worktree_error(error,
11420 "rebase", cwd);
11421 goto done;
11425 error = get_gitconfig_path(&gitconfig_path);
11426 if (error)
11427 goto done;
11428 error = got_repo_open(&repo,
11429 worktree ? got_worktree_get_repo_path(worktree) : cwd,
11430 gitconfig_path, pack_fds);
11431 if (error != NULL)
11432 goto done;
11434 if (worktree != NULL && !list_backups && !delete_backups) {
11435 error = worktree_has_logmsg_ref("rebase", worktree, repo);
11436 if (error)
11437 goto done;
11440 error = get_author(&committer, repo, worktree);
11441 if (error && error->code != GOT_ERR_COMMIT_NO_AUTHOR)
11442 goto done;
11444 error = apply_unveil(got_repo_get_path(repo), 0,
11445 worktree ? got_worktree_get_root_path(worktree) : NULL);
11446 if (error)
11447 goto done;
11449 if (list_backups || delete_backups) {
11450 error = process_backup_refs(
11451 GOT_WORKTREE_REBASE_BACKUP_REF_PREFIX,
11452 argc == 1 ? argv[0] : NULL, delete_backups, repo);
11453 goto done; /* nothing else to do */
11456 error = got_worktree_histedit_in_progress(&histedit_in_progress,
11457 worktree);
11458 if (error)
11459 goto done;
11460 if (histedit_in_progress) {
11461 error = got_error(GOT_ERR_HISTEDIT_BUSY);
11462 goto done;
11465 error = got_worktree_merge_in_progress(&merge_in_progress,
11466 worktree, repo);
11467 if (error)
11468 goto done;
11469 if (merge_in_progress) {
11470 error = got_error(GOT_ERR_MERGE_BUSY);
11471 goto done;
11474 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
11475 if (error)
11476 goto done;
11478 if (abort_rebase) {
11479 if (!rebase_in_progress) {
11480 error = got_error(GOT_ERR_NOT_REBASING);
11481 goto done;
11483 error = got_worktree_rebase_continue(&resume_commit_id,
11484 &new_base_branch, &tmp_branch, &branch, &fileindex,
11485 worktree, repo);
11486 if (error)
11487 goto done;
11488 printf("Switching work tree to %s\n",
11489 got_ref_get_symref_target(new_base_branch));
11490 error = got_worktree_rebase_abort(worktree, fileindex, repo,
11491 new_base_branch, abort_progress, &upa);
11492 if (error)
11493 goto done;
11494 printf("Rebase of %s aborted\n", got_ref_get_name(branch));
11495 print_merge_progress_stats(&upa);
11496 goto done; /* nothing else to do */
11499 if (continue_rebase) {
11500 if (!rebase_in_progress) {
11501 error = got_error(GOT_ERR_NOT_REBASING);
11502 goto done;
11504 error = got_worktree_rebase_continue(&resume_commit_id,
11505 &new_base_branch, &tmp_branch, &branch, &fileindex,
11506 worktree, repo);
11507 if (error)
11508 goto done;
11510 error = rebase_commit(NULL, worktree, fileindex, tmp_branch,
11511 committer, resume_commit_id, allow_conflict, repo);
11512 if (error)
11513 goto done;
11515 yca_id = got_object_id_dup(resume_commit_id);
11516 if (yca_id == NULL) {
11517 error = got_error_from_errno("got_object_id_dup");
11518 goto done;
11520 } else {
11521 error = got_ref_open(&branch, repo, argv[0], 0);
11522 if (error != NULL)
11523 goto done;
11524 if (strncmp(got_ref_get_name(branch), "refs/heads/", 11) != 0) {
11525 error = got_error_msg(GOT_ERR_COMMIT_BRANCH,
11526 "will not rebase a branch which lives outside "
11527 "the \"refs/heads/\" reference namespace");
11528 goto done;
11532 error = got_ref_resolve(&branch_head_commit_id, repo, branch);
11533 if (error)
11534 goto done;
11536 if (!continue_rebase) {
11537 struct got_object_id *base_commit_id;
11539 error = got_ref_open(&head_ref, repo,
11540 got_worktree_get_head_ref_name(worktree), 0);
11541 if (error)
11542 goto done;
11543 error = got_ref_resolve(&head_commit_id, repo, head_ref);
11544 if (error)
11545 goto done;
11546 base_commit_id = got_worktree_get_base_commit_id(worktree);
11547 if (got_object_id_cmp(base_commit_id, head_commit_id) != 0) {
11548 error = got_error(GOT_ERR_REBASE_OUT_OF_DATE);
11549 goto done;
11552 error = got_commit_graph_find_youngest_common_ancestor(&yca_id,
11553 base_commit_id, branch_head_commit_id, 1, 0,
11554 repo, check_cancelled, NULL);
11555 if (error) {
11556 if (error->code == GOT_ERR_ANCESTRY) {
11557 error = got_error_msg(GOT_ERR_ANCESTRY,
11558 "specified branch shares no common "
11559 "ancestry with work tree's branch");
11561 goto done;
11565 * If a merge commit appears between the new base branch tip
11566 * and a YCA found via first-parent traversal then we might
11567 * find a better YCA using topologically sorted commits.
11569 if (got_object_id_cmp(base_commit_id, yca_id) != 0) {
11570 struct got_object_id *better_yca_id;
11571 error = find_merge_commit_yca(&better_yca_id,
11572 branch_head_commit_id, yca_id,
11573 base_commit_id, repo);
11574 if (error)
11575 goto done;
11576 if (better_yca_id) {
11577 free(yca_id);
11578 yca_id = better_yca_id;
11582 if (got_object_id_cmp(base_commit_id, yca_id) == 0) {
11583 struct got_pathlist_head paths;
11584 printf("%s is already based on %s\n",
11585 got_ref_get_name(branch),
11586 got_worktree_get_head_ref_name(worktree));
11587 error = switch_head_ref(branch, branch_head_commit_id,
11588 worktree, repo);
11589 if (error)
11590 goto done;
11591 error = got_worktree_set_base_commit_id(worktree, repo,
11592 branch_head_commit_id);
11593 if (error)
11594 goto done;
11595 TAILQ_INIT(&paths);
11596 error = got_pathlist_append(&paths, "", NULL);
11597 if (error)
11598 goto done;
11599 error = got_worktree_checkout_files(worktree,
11600 &paths, repo, update_progress, &upa,
11601 check_cancelled, NULL);
11602 got_pathlist_free(&paths, GOT_PATHLIST_FREE_NONE);
11603 if (error)
11604 goto done;
11605 if (upa.did_something) {
11606 char *id_str;
11607 error = got_object_id_str(&id_str,
11608 branch_head_commit_id);
11609 if (error)
11610 goto done;
11611 printf("Updated to %s: %s\n",
11612 got_worktree_get_head_ref_name(worktree),
11613 id_str);
11614 free(id_str);
11615 } else
11616 printf("Already up-to-date\n");
11617 print_update_progress_stats(&upa);
11618 goto done;
11622 commit_id = branch_head_commit_id;
11623 error = got_object_open_as_commit(&commit, repo, commit_id);
11624 if (error)
11625 goto done;
11627 parent_ids = got_object_commit_get_parent_ids(commit);
11628 pid = STAILQ_FIRST(parent_ids);
11629 if (pid) {
11630 error = collect_commits(&commits, commit_id, &pid->id,
11631 yca_id, got_worktree_get_path_prefix(worktree),
11632 GOT_ERR_REBASE_PATH, repo);
11633 if (error)
11634 goto done;
11637 got_object_commit_close(commit);
11638 commit = NULL;
11640 if (!continue_rebase) {
11641 error = got_worktree_rebase_prepare(&new_base_branch,
11642 &tmp_branch, &fileindex, worktree, branch, repo);
11643 if (error)
11644 goto done;
11647 if (STAILQ_EMPTY(&commits)) {
11648 if (continue_rebase) {
11649 error = rebase_complete(worktree, fileindex,
11650 branch, tmp_branch, repo, create_backup);
11651 goto done;
11652 } else {
11653 /* Fast-forward the reference of the branch. */
11654 struct got_object_id *new_head_commit_id;
11655 char *id_str;
11656 error = got_ref_resolve(&new_head_commit_id, repo,
11657 new_base_branch);
11658 if (error)
11659 goto done;
11660 error = got_object_id_str(&id_str, new_head_commit_id);
11661 if (error)
11662 goto done;
11663 printf("Forwarding %s to commit %s\n",
11664 got_ref_get_name(branch), id_str);
11665 free(id_str);
11666 error = got_ref_change_ref(branch,
11667 new_head_commit_id);
11668 if (error)
11669 goto done;
11670 /* No backup needed since objects did not change. */
11671 create_backup = 0;
11675 pid = NULL;
11676 STAILQ_FOREACH(qid, &commits, entry) {
11678 commit_id = &qid->id;
11679 parent_id = pid ? &pid->id : yca_id;
11680 pid = qid;
11682 memset(&upa, 0, sizeof(upa));
11683 error = got_worktree_rebase_merge_files(&merged_paths,
11684 worktree, fileindex, parent_id, commit_id, repo,
11685 update_progress, &upa, check_cancelled, NULL);
11686 if (error)
11687 goto done;
11689 print_merge_progress_stats(&upa);
11690 if (upa.conflicts > 0 || upa.missing > 0 ||
11691 upa.not_deleted > 0 || upa.unversioned > 0) {
11692 if (upa.conflicts > 0) {
11693 error = show_rebase_merge_conflict(&qid->id,
11694 repo);
11695 if (error)
11696 goto done;
11698 got_pathlist_free(&merged_paths, GOT_PATHLIST_FREE_PATH);
11699 break;
11702 error = rebase_commit(&merged_paths, worktree, fileindex,
11703 tmp_branch, committer, commit_id, 0, repo);
11704 got_pathlist_free(&merged_paths, GOT_PATHLIST_FREE_PATH);
11705 if (error)
11706 goto done;
11709 if (upa.conflicts > 0 || upa.missing > 0 ||
11710 upa.not_deleted > 0 || upa.unversioned > 0) {
11711 error = got_worktree_rebase_postpone(worktree, fileindex);
11712 if (error)
11713 goto done;
11714 if (upa.conflicts > 0 && upa.missing == 0 &&
11715 upa.not_deleted == 0 && upa.unversioned == 0) {
11716 error = got_error_msg(GOT_ERR_CONFLICTS,
11717 "conflicts must be resolved before rebasing "
11718 "can continue");
11719 } else if (upa.conflicts > 0) {
11720 error = got_error_msg(GOT_ERR_CONFLICTS,
11721 "conflicts must be resolved before rebasing "
11722 "can continue; changes destined for some "
11723 "files were not yet merged and should be "
11724 "merged manually if required before the "
11725 "rebase operation is continued");
11726 } else {
11727 error = got_error_msg(GOT_ERR_CONFLICTS,
11728 "changes destined for some files were not "
11729 "yet merged and should be merged manually "
11730 "if required before the rebase operation "
11731 "is continued");
11733 } else
11734 error = rebase_complete(worktree, fileindex, branch,
11735 tmp_branch, repo, create_backup);
11736 done:
11737 free(cwd);
11738 free(committer);
11739 free(gitconfig_path);
11740 got_object_id_queue_free(&commits);
11741 free(branch_head_commit_id);
11742 free(resume_commit_id);
11743 free(head_commit_id);
11744 free(yca_id);
11745 if (commit)
11746 got_object_commit_close(commit);
11747 if (branch)
11748 got_ref_close(branch);
11749 if (new_base_branch)
11750 got_ref_close(new_base_branch);
11751 if (tmp_branch)
11752 got_ref_close(tmp_branch);
11753 if (head_ref)
11754 got_ref_close(head_ref);
11755 if (worktree)
11756 got_worktree_close(worktree);
11757 if (repo) {
11758 const struct got_error *close_err = got_repo_close(repo);
11759 if (error == NULL)
11760 error = close_err;
11762 if (pack_fds) {
11763 const struct got_error *pack_err =
11764 got_repo_pack_fds_close(pack_fds);
11765 if (error == NULL)
11766 error = pack_err;
11768 return error;
11771 __dead static void
11772 usage_histedit(void)
11774 fprintf(stderr, "usage: %s histedit [-aCcdeflmX] [-F histedit-script] "
11775 "[branch]\n", getprogname());
11776 exit(1);
11779 #define GOT_HISTEDIT_PICK 'p'
11780 #define GOT_HISTEDIT_EDIT 'e'
11781 #define GOT_HISTEDIT_FOLD 'f'
11782 #define GOT_HISTEDIT_DROP 'd'
11783 #define GOT_HISTEDIT_MESG 'm'
11785 static const struct got_histedit_cmd {
11786 unsigned char code;
11787 const char *name;
11788 const char *desc;
11789 } got_histedit_cmds[] = {
11790 { GOT_HISTEDIT_PICK, "pick", "use commit" },
11791 { GOT_HISTEDIT_EDIT, "edit", "use commit but stop for amending" },
11792 { GOT_HISTEDIT_FOLD, "fold", "combine with next commit that will "
11793 "be used" },
11794 { GOT_HISTEDIT_DROP, "drop", "remove commit from history" },
11795 { GOT_HISTEDIT_MESG, "mesg", "open editor to edit the log message" },
11798 struct got_histedit_list_entry {
11799 TAILQ_ENTRY(got_histedit_list_entry) entry;
11800 struct got_object_id *commit_id;
11801 const struct got_histedit_cmd *cmd;
11802 char *logmsg;
11804 TAILQ_HEAD(got_histedit_list, got_histedit_list_entry);
11806 static const struct got_error *
11807 histedit_write_commit(struct got_object_id *commit_id, const char *cmdname,
11808 FILE *f, struct got_repository *repo)
11810 const struct got_error *err = NULL;
11811 char *logmsg = NULL, *id_str = NULL;
11812 struct got_commit_object *commit = NULL;
11813 int n;
11815 err = got_object_open_as_commit(&commit, repo, commit_id);
11816 if (err)
11817 goto done;
11819 err = get_short_logmsg(&logmsg, 34, commit);
11820 if (err)
11821 goto done;
11823 err = got_object_id_str(&id_str, commit_id);
11824 if (err)
11825 goto done;
11827 n = fprintf(f, "%s %s %s\n", cmdname, id_str, logmsg);
11828 if (n < 0)
11829 err = got_ferror(f, GOT_ERR_IO);
11830 done:
11831 if (commit)
11832 got_object_commit_close(commit);
11833 free(id_str);
11834 free(logmsg);
11835 return err;
11838 static const struct got_error *
11839 histedit_write_commit_list(struct got_object_id_queue *commits,
11840 FILE *f, int edit_logmsg_only, int fold_only, int drop_only,
11841 int edit_only, struct got_repository *repo)
11843 const struct got_error *err = NULL;
11844 struct got_object_qid *qid;
11845 const char *histedit_cmd = NULL;
11847 if (STAILQ_EMPTY(commits))
11848 return got_error(GOT_ERR_EMPTY_HISTEDIT);
11850 STAILQ_FOREACH(qid, commits, entry) {
11851 histedit_cmd = got_histedit_cmds[0].name;
11852 if (drop_only)
11853 histedit_cmd = "drop";
11854 else if (edit_only)
11855 histedit_cmd = "edit";
11856 else if (fold_only && STAILQ_NEXT(qid, entry) != NULL)
11857 histedit_cmd = "fold";
11858 else if (edit_logmsg_only)
11859 histedit_cmd = "mesg";
11860 err = histedit_write_commit(&qid->id, histedit_cmd, f, repo);
11861 if (err)
11862 break;
11865 return err;
11868 static const struct got_error *
11869 write_cmd_list(FILE *f, const char *branch_name,
11870 struct got_object_id_queue *commits)
11872 const struct got_error *err = NULL;
11873 size_t i;
11874 int n;
11875 char *id_str;
11876 struct got_object_qid *qid;
11878 qid = STAILQ_FIRST(commits);
11879 err = got_object_id_str(&id_str, &qid->id);
11880 if (err)
11881 return err;
11883 n = fprintf(f,
11884 "# Editing the history of branch '%s' starting at\n"
11885 "# commit %s\n"
11886 "# Commits will be processed in order from top to "
11887 "bottom of this file.\n", branch_name, id_str);
11888 if (n < 0) {
11889 err = got_ferror(f, GOT_ERR_IO);
11890 goto done;
11893 n = fprintf(f, "# Available histedit commands:\n");
11894 if (n < 0) {
11895 err = got_ferror(f, GOT_ERR_IO);
11896 goto done;
11899 for (i = 0; i < nitems(got_histedit_cmds); i++) {
11900 const struct got_histedit_cmd *cmd = &got_histedit_cmds[i];
11901 n = fprintf(f, "# %s (%c): %s\n", cmd->name, cmd->code,
11902 cmd->desc);
11903 if (n < 0) {
11904 err = got_ferror(f, GOT_ERR_IO);
11905 break;
11908 done:
11909 free(id_str);
11910 return err;
11913 static const struct got_error *
11914 histedit_syntax_error(int lineno)
11916 static char msg[42];
11917 int ret;
11919 ret = snprintf(msg, sizeof(msg), "histedit syntax error on line %d",
11920 lineno);
11921 if (ret < 0 || (size_t)ret >= sizeof(msg))
11922 return got_error(GOT_ERR_HISTEDIT_SYNTAX);
11924 return got_error_msg(GOT_ERR_HISTEDIT_SYNTAX, msg);
11927 static const struct got_error *
11928 append_folded_commit_msg(char **new_msg, struct got_histedit_list_entry *hle,
11929 char *logmsg, struct got_repository *repo)
11931 const struct got_error *err;
11932 struct got_commit_object *folded_commit = NULL;
11933 char *id_str, *folded_logmsg = NULL;
11935 err = got_object_id_str(&id_str, hle->commit_id);
11936 if (err)
11937 return err;
11939 err = got_object_open_as_commit(&folded_commit, repo, hle->commit_id);
11940 if (err)
11941 goto done;
11943 err = got_object_commit_get_logmsg(&folded_logmsg, folded_commit);
11944 if (err)
11945 goto done;
11946 if (asprintf(new_msg, "%s%s# log message of folded commit %s: %s",
11947 logmsg ? logmsg : "", logmsg ? "\n" : "", id_str,
11948 folded_logmsg) == -1) {
11949 err = got_error_from_errno("asprintf");
11951 done:
11952 if (folded_commit)
11953 got_object_commit_close(folded_commit);
11954 free(id_str);
11955 free(folded_logmsg);
11956 return err;
11959 static struct got_histedit_list_entry *
11960 get_folded_commits(struct got_histedit_list_entry *hle)
11962 struct got_histedit_list_entry *prev, *folded = NULL;
11964 prev = TAILQ_PREV(hle, got_histedit_list, entry);
11965 while (prev && (prev->cmd->code == GOT_HISTEDIT_FOLD ||
11966 prev->cmd->code == GOT_HISTEDIT_DROP)) {
11967 if (prev->cmd->code == GOT_HISTEDIT_FOLD)
11968 folded = prev;
11969 prev = TAILQ_PREV(prev, got_histedit_list, entry);
11972 return folded;
11975 static const struct got_error *
11976 histedit_edit_logmsg(struct got_histedit_list_entry *hle,
11977 struct got_repository *repo)
11979 char *logmsg_path = NULL, *id_str = NULL, *orig_logmsg = NULL;
11980 char *logmsg = NULL, *new_msg = NULL, *editor = NULL;
11981 const struct got_error *err = NULL;
11982 struct got_commit_object *commit = NULL;
11983 int logmsg_len;
11984 int fd = -1;
11985 struct got_histedit_list_entry *folded = NULL;
11987 err = got_object_open_as_commit(&commit, repo, hle->commit_id);
11988 if (err)
11989 return err;
11991 folded = get_folded_commits(hle);
11992 if (folded) {
11993 while (folded != hle) {
11994 if (folded->cmd->code == GOT_HISTEDIT_DROP) {
11995 folded = TAILQ_NEXT(folded, entry);
11996 continue;
11998 err = append_folded_commit_msg(&new_msg, folded,
11999 logmsg, repo);
12000 if (err)
12001 goto done;
12002 free(logmsg);
12003 logmsg = new_msg;
12004 folded = TAILQ_NEXT(folded, entry);
12008 err = got_object_id_str(&id_str, hle->commit_id);
12009 if (err)
12010 goto done;
12011 err = got_object_commit_get_logmsg(&orig_logmsg, commit);
12012 if (err)
12013 goto done;
12014 logmsg_len = asprintf(&new_msg,
12015 "%s\n# original log message of commit %s: %s",
12016 logmsg ? logmsg : "", id_str, orig_logmsg);
12017 if (logmsg_len == -1) {
12018 err = got_error_from_errno("asprintf");
12019 goto done;
12021 free(logmsg);
12022 logmsg = new_msg;
12024 err = got_object_id_str(&id_str, hle->commit_id);
12025 if (err)
12026 goto done;
12028 err = got_opentemp_named_fd(&logmsg_path, &fd,
12029 GOT_TMPDIR_STR "/got-logmsg", "");
12030 if (err)
12031 goto done;
12033 if (write(fd, logmsg, logmsg_len) == -1) {
12034 err = got_error_from_errno2("write", logmsg_path);
12035 goto done;
12037 if (close(fd) == -1) {
12038 err = got_error_from_errno2("close", logmsg_path);
12039 goto done;
12041 fd = -1;
12043 err = get_editor(&editor);
12044 if (err)
12045 goto done;
12047 err = edit_logmsg(&hle->logmsg, editor, logmsg_path, logmsg,
12048 logmsg_len, 0);
12049 if (err) {
12050 if (err->code != GOT_ERR_COMMIT_MSG_EMPTY)
12051 goto done;
12052 err = NULL;
12053 hle->logmsg = strdup(new_msg);
12054 if (hle->logmsg == NULL)
12055 err = got_error_from_errno("strdup");
12057 done:
12058 if (fd != -1 && close(fd) == -1 && err == NULL)
12059 err = got_error_from_errno2("close", logmsg_path);
12060 if (logmsg_path && unlink(logmsg_path) != 0 && err == NULL)
12061 err = got_error_from_errno2("unlink", logmsg_path);
12062 free(logmsg_path);
12063 free(logmsg);
12064 free(orig_logmsg);
12065 free(editor);
12066 if (commit)
12067 got_object_commit_close(commit);
12068 return err;
12071 static const struct got_error *
12072 histedit_parse_list(struct got_histedit_list *histedit_cmds,
12073 FILE *f, struct got_repository *repo)
12075 const struct got_error *err = NULL;
12076 char *line = NULL, *p, *end;
12077 size_t i, linesize = 0;
12078 ssize_t linelen;
12079 int lineno = 0;
12080 const struct got_histedit_cmd *cmd;
12081 struct got_object_id *commit_id = NULL;
12082 struct got_histedit_list_entry *hle = NULL;
12084 for (;;) {
12085 linelen = getline(&line, &linesize, f);
12086 if (linelen == -1) {
12087 const struct got_error *getline_err;
12088 if (feof(f))
12089 break;
12090 getline_err = got_error_from_errno("getline");
12091 err = got_ferror(f, getline_err->code);
12092 break;
12094 lineno++;
12095 p = line;
12096 while (isspace((unsigned char)p[0]))
12097 p++;
12098 if (p[0] == '#' || p[0] == '\0')
12099 continue;
12100 cmd = NULL;
12101 for (i = 0; i < nitems(got_histedit_cmds); i++) {
12102 cmd = &got_histedit_cmds[i];
12103 if (strncmp(cmd->name, p, strlen(cmd->name)) == 0 &&
12104 isspace((unsigned char)p[strlen(cmd->name)])) {
12105 p += strlen(cmd->name);
12106 break;
12108 if (p[0] == cmd->code && isspace((unsigned char)p[1])) {
12109 p++;
12110 break;
12113 if (i == nitems(got_histedit_cmds)) {
12114 err = histedit_syntax_error(lineno);
12115 break;
12117 while (isspace((unsigned char)p[0]))
12118 p++;
12119 end = p;
12120 while (end[0] && !isspace((unsigned char)end[0]))
12121 end++;
12122 *end = '\0';
12123 err = got_object_resolve_id_str(&commit_id, repo, p);
12124 if (err) {
12125 /* override error code */
12126 err = histedit_syntax_error(lineno);
12127 break;
12129 hle = malloc(sizeof(*hle));
12130 if (hle == NULL) {
12131 err = got_error_from_errno("malloc");
12132 break;
12134 hle->cmd = cmd;
12135 hle->commit_id = commit_id;
12136 hle->logmsg = NULL;
12137 commit_id = NULL;
12138 TAILQ_INSERT_TAIL(histedit_cmds, hle, entry);
12141 free(line);
12142 free(commit_id);
12143 return err;
12146 static const struct got_error *
12147 histedit_check_script(struct got_histedit_list *histedit_cmds,
12148 struct got_object_id_queue *commits, struct got_repository *repo)
12150 const struct got_error *err = NULL;
12151 struct got_object_qid *qid;
12152 struct got_histedit_list_entry *hle;
12153 static char msg[92];
12154 char *id_str;
12156 if (TAILQ_EMPTY(histedit_cmds))
12157 return got_error_msg(GOT_ERR_EMPTY_HISTEDIT,
12158 "histedit script contains no commands");
12159 if (STAILQ_EMPTY(commits))
12160 return got_error(GOT_ERR_EMPTY_HISTEDIT);
12162 TAILQ_FOREACH(hle, histedit_cmds, entry) {
12163 struct got_histedit_list_entry *hle2;
12164 TAILQ_FOREACH(hle2, histedit_cmds, entry) {
12165 if (hle == hle2)
12166 continue;
12167 if (got_object_id_cmp(hle->commit_id,
12168 hle2->commit_id) != 0)
12169 continue;
12170 err = got_object_id_str(&id_str, hle->commit_id);
12171 if (err)
12172 return err;
12173 snprintf(msg, sizeof(msg), "commit %s is listed "
12174 "more than once in histedit script", id_str);
12175 free(id_str);
12176 return got_error_msg(GOT_ERR_HISTEDIT_CMD, msg);
12180 STAILQ_FOREACH(qid, commits, entry) {
12181 TAILQ_FOREACH(hle, histedit_cmds, entry) {
12182 if (got_object_id_cmp(&qid->id, hle->commit_id) == 0)
12183 break;
12185 if (hle == NULL) {
12186 err = got_object_id_str(&id_str, &qid->id);
12187 if (err)
12188 return err;
12189 snprintf(msg, sizeof(msg),
12190 "commit %s missing from histedit script", id_str);
12191 free(id_str);
12192 return got_error_msg(GOT_ERR_HISTEDIT_CMD, msg);
12196 hle = TAILQ_LAST(histedit_cmds, got_histedit_list);
12197 if (hle && hle->cmd->code == GOT_HISTEDIT_FOLD)
12198 return got_error_msg(GOT_ERR_HISTEDIT_CMD,
12199 "last commit in histedit script cannot be folded");
12201 return NULL;
12204 static const struct got_error *
12205 histedit_run_editor(struct got_histedit_list *histedit_cmds,
12206 const char *path, struct got_object_id_queue *commits,
12207 struct got_repository *repo)
12209 const struct got_error *err = NULL;
12210 struct stat st, st2;
12211 struct timespec timeout;
12212 char *editor;
12213 FILE *f = NULL;
12215 err = get_editor(&editor);
12216 if (err)
12217 return err;
12219 if (stat(path, &st) == -1) {
12220 err = got_error_from_errno2("stat", path);
12221 goto done;
12224 if (spawn_editor(editor, path) == -1) {
12225 err = got_error_from_errno("failed spawning editor");
12226 goto done;
12229 timeout.tv_sec = 0;
12230 timeout.tv_nsec = 1;
12231 nanosleep(&timeout, NULL);
12233 if (stat(path, &st2) == -1) {
12234 err = got_error_from_errno2("stat", path);
12235 goto done;
12238 if (st.st_size == st2.st_size &&
12239 timespeccmp(&st.st_mtim, &st2.st_mtim, ==)) {
12240 err = got_error_msg(GOT_ERR_EMPTY_HISTEDIT,
12241 "no changes made to histedit script, aborting");
12242 goto done;
12245 f = fopen(path, "re");
12246 if (f == NULL) {
12247 err = got_error_from_errno("fopen");
12248 goto done;
12250 err = histedit_parse_list(histedit_cmds, f, repo);
12251 if (err)
12252 goto done;
12254 err = histedit_check_script(histedit_cmds, commits, repo);
12255 done:
12256 if (f && fclose(f) == EOF && err == NULL)
12257 err = got_error_from_errno("fclose");
12258 free(editor);
12259 return err;
12262 static const struct got_error *
12263 histedit_edit_list_retry(struct got_histedit_list *, const struct got_error *,
12264 struct got_object_id_queue *, const char *, const char *,
12265 struct got_repository *);
12267 static const struct got_error *
12268 histedit_edit_script(struct got_histedit_list *histedit_cmds,
12269 struct got_object_id_queue *commits, const char *branch_name,
12270 int edit_logmsg_only, int fold_only, int drop_only, int edit_only,
12271 struct got_repository *repo)
12273 const struct got_error *err;
12274 FILE *f = NULL;
12275 char *path = NULL;
12277 err = got_opentemp_named(&path, &f, "got-histedit", "");
12278 if (err)
12279 return err;
12281 err = write_cmd_list(f, branch_name, commits);
12282 if (err)
12283 goto done;
12285 err = histedit_write_commit_list(commits, f, edit_logmsg_only,
12286 fold_only, drop_only, edit_only, repo);
12287 if (err)
12288 goto done;
12290 if (drop_only || edit_logmsg_only || fold_only || edit_only) {
12291 rewind(f);
12292 err = histedit_parse_list(histedit_cmds, f, repo);
12293 } else {
12294 if (fclose(f) == EOF) {
12295 err = got_error_from_errno("fclose");
12296 goto done;
12298 f = NULL;
12299 err = histedit_run_editor(histedit_cmds, path, commits, repo);
12300 if (err) {
12301 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
12302 err->code != GOT_ERR_HISTEDIT_CMD)
12303 goto done;
12304 err = histedit_edit_list_retry(histedit_cmds, err,
12305 commits, path, branch_name, repo);
12308 done:
12309 if (f && fclose(f) == EOF && err == NULL)
12310 err = got_error_from_errno("fclose");
12311 if (path && unlink(path) != 0 && err == NULL)
12312 err = got_error_from_errno2("unlink", path);
12313 free(path);
12314 return err;
12317 static const struct got_error *
12318 histedit_save_list(struct got_histedit_list *histedit_cmds,
12319 struct got_worktree *worktree, struct got_repository *repo)
12321 const struct got_error *err = NULL;
12322 char *path = NULL;
12323 FILE *f = NULL;
12324 struct got_histedit_list_entry *hle;
12326 err = got_worktree_get_histedit_script_path(&path, worktree);
12327 if (err)
12328 return err;
12330 f = fopen(path, "we");
12331 if (f == NULL) {
12332 err = got_error_from_errno2("fopen", path);
12333 goto done;
12335 TAILQ_FOREACH(hle, histedit_cmds, entry) {
12336 err = histedit_write_commit(hle->commit_id, hle->cmd->name, f,
12337 repo);
12338 if (err)
12339 break;
12341 done:
12342 if (f && fclose(f) == EOF && err == NULL)
12343 err = got_error_from_errno("fclose");
12344 free(path);
12345 return err;
12348 static void
12349 histedit_free_list(struct got_histedit_list *histedit_cmds)
12351 struct got_histedit_list_entry *hle;
12353 while ((hle = TAILQ_FIRST(histedit_cmds))) {
12354 TAILQ_REMOVE(histedit_cmds, hle, entry);
12355 free(hle);
12359 static const struct got_error *
12360 histedit_load_list(struct got_histedit_list *histedit_cmds,
12361 const char *path, struct got_repository *repo)
12363 const struct got_error *err = NULL;
12364 FILE *f = NULL;
12366 f = fopen(path, "re");
12367 if (f == NULL) {
12368 err = got_error_from_errno2("fopen", path);
12369 goto done;
12372 err = histedit_parse_list(histedit_cmds, f, repo);
12373 done:
12374 if (f && fclose(f) == EOF && err == NULL)
12375 err = got_error_from_errno("fclose");
12376 return err;
12379 static const struct got_error *
12380 histedit_edit_list_retry(struct got_histedit_list *histedit_cmds,
12381 const struct got_error *edit_err, struct got_object_id_queue *commits,
12382 const char *path, const char *branch_name, struct got_repository *repo)
12384 const struct got_error *err = NULL, *prev_err = edit_err;
12385 int resp = ' ';
12387 while (resp != 'c' && resp != 'r' && resp != 'a') {
12388 printf("%s: %s\n(c)ontinue editing, (r)estart editing, "
12389 "or (a)bort: ", getprogname(), prev_err->msg);
12390 resp = getchar();
12391 if (resp == '\n')
12392 resp = getchar();
12393 if (resp == 'c') {
12394 histedit_free_list(histedit_cmds);
12395 err = histedit_run_editor(histedit_cmds, path, commits,
12396 repo);
12397 if (err) {
12398 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
12399 err->code != GOT_ERR_HISTEDIT_CMD)
12400 break;
12401 prev_err = err;
12402 resp = ' ';
12403 continue;
12405 break;
12406 } else if (resp == 'r') {
12407 histedit_free_list(histedit_cmds);
12408 err = histedit_edit_script(histedit_cmds,
12409 commits, branch_name, 0, 0, 0, 0, repo);
12410 if (err) {
12411 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
12412 err->code != GOT_ERR_HISTEDIT_CMD)
12413 break;
12414 prev_err = err;
12415 resp = ' ';
12416 continue;
12418 break;
12419 } else if (resp == 'a') {
12420 err = got_error(GOT_ERR_HISTEDIT_CANCEL);
12421 break;
12422 } else
12423 printf("invalid response '%c'\n", resp);
12426 return err;
12429 static const struct got_error *
12430 histedit_complete(struct got_worktree *worktree,
12431 struct got_fileindex *fileindex, struct got_reference *tmp_branch,
12432 struct got_reference *branch, struct got_repository *repo)
12434 printf("Switching work tree to %s\n",
12435 got_ref_get_symref_target(branch));
12436 return got_worktree_histedit_complete(worktree, fileindex, tmp_branch,
12437 branch, repo);
12440 static const struct got_error *
12441 show_histedit_progress(struct got_commit_object *commit,
12442 struct got_histedit_list_entry *hle, struct got_object_id *new_id)
12444 const struct got_error *err;
12445 char *old_id_str = NULL, *new_id_str = NULL, *logmsg = NULL;
12447 err = got_object_id_str(&old_id_str, hle->commit_id);
12448 if (err)
12449 goto done;
12451 if (new_id) {
12452 err = got_object_id_str(&new_id_str, new_id);
12453 if (err)
12454 goto done;
12457 old_id_str[12] = '\0';
12458 if (new_id_str)
12459 new_id_str[12] = '\0';
12461 if (hle->logmsg) {
12462 logmsg = strdup(hle->logmsg);
12463 if (logmsg == NULL) {
12464 err = got_error_from_errno("strdup");
12465 goto done;
12467 trim_logmsg(logmsg, 42);
12468 } else {
12469 err = get_short_logmsg(&logmsg, 42, commit);
12470 if (err)
12471 goto done;
12474 switch (hle->cmd->code) {
12475 case GOT_HISTEDIT_PICK:
12476 case GOT_HISTEDIT_EDIT:
12477 case GOT_HISTEDIT_MESG:
12478 printf("%s -> %s: %s\n", old_id_str,
12479 new_id_str ? new_id_str : "no-op change", logmsg);
12480 break;
12481 case GOT_HISTEDIT_DROP:
12482 case GOT_HISTEDIT_FOLD:
12483 printf("%s -> %s commit: %s\n", old_id_str, hle->cmd->name,
12484 logmsg);
12485 break;
12486 default:
12487 break;
12489 done:
12490 free(old_id_str);
12491 free(new_id_str);
12492 return err;
12495 static const struct got_error *
12496 histedit_commit(struct got_pathlist_head *merged_paths,
12497 struct got_worktree *worktree, struct got_fileindex *fileindex,
12498 struct got_reference *tmp_branch, struct got_histedit_list_entry *hle,
12499 const char *committer, int allow_conflict, struct got_repository *repo)
12501 const struct got_error *err;
12502 struct got_commit_object *commit;
12503 struct got_object_id *new_commit_id;
12505 if ((hle->cmd->code == GOT_HISTEDIT_EDIT || get_folded_commits(hle))
12506 && hle->logmsg == NULL) {
12507 err = histedit_edit_logmsg(hle, repo);
12508 if (err)
12509 return err;
12512 err = got_object_open_as_commit(&commit, repo, hle->commit_id);
12513 if (err)
12514 return err;
12516 err = got_worktree_histedit_commit(&new_commit_id, merged_paths,
12517 worktree, fileindex, tmp_branch, committer, commit, hle->commit_id,
12518 hle->logmsg, allow_conflict, repo);
12519 if (err) {
12520 if (err->code != GOT_ERR_COMMIT_NO_CHANGES)
12521 goto done;
12522 err = show_histedit_progress(commit, hle, NULL);
12523 } else {
12524 err = show_histedit_progress(commit, hle, new_commit_id);
12525 free(new_commit_id);
12527 done:
12528 got_object_commit_close(commit);
12529 return err;
12532 static const struct got_error *
12533 histedit_skip_commit(struct got_histedit_list_entry *hle,
12534 struct got_worktree *worktree, struct got_repository *repo)
12536 const struct got_error *error;
12537 struct got_commit_object *commit;
12539 error = got_worktree_histedit_skip_commit(worktree, hle->commit_id,
12540 repo);
12541 if (error)
12542 return error;
12544 error = got_object_open_as_commit(&commit, repo, hle->commit_id);
12545 if (error)
12546 return error;
12548 error = show_histedit_progress(commit, hle, NULL);
12549 got_object_commit_close(commit);
12550 return error;
12553 static const struct got_error *
12554 check_local_changes(void *arg, unsigned char status,
12555 unsigned char staged_status, const char *path,
12556 struct got_object_id *blob_id, struct got_object_id *staged_blob_id,
12557 struct got_object_id *commit_id, int dirfd, const char *de_name)
12559 int *have_local_changes = arg;
12561 switch (status) {
12562 case GOT_STATUS_ADD:
12563 case GOT_STATUS_DELETE:
12564 case GOT_STATUS_MODIFY:
12565 case GOT_STATUS_CONFLICT:
12566 *have_local_changes = 1;
12567 return got_error(GOT_ERR_CANCELLED);
12568 default:
12569 break;
12572 switch (staged_status) {
12573 case GOT_STATUS_ADD:
12574 case GOT_STATUS_DELETE:
12575 case GOT_STATUS_MODIFY:
12576 *have_local_changes = 1;
12577 return got_error(GOT_ERR_CANCELLED);
12578 default:
12579 break;
12582 return NULL;
12585 static const struct got_error *
12586 cmd_histedit(int argc, char *argv[])
12588 const struct got_error *error = NULL;
12589 struct got_worktree *worktree = NULL;
12590 struct got_fileindex *fileindex = NULL;
12591 struct got_repository *repo = NULL;
12592 char *cwd = NULL, *committer = NULL, *gitconfig_path = NULL;
12593 struct got_reference *branch = NULL;
12594 struct got_reference *tmp_branch = NULL;
12595 struct got_object_id *resume_commit_id = NULL;
12596 struct got_object_id *base_commit_id = NULL;
12597 struct got_object_id *head_commit_id = NULL;
12598 struct got_commit_object *commit = NULL;
12599 int ch, rebase_in_progress = 0, merge_in_progress = 0;
12600 struct got_update_progress_arg upa;
12601 int edit_in_progress = 0, abort_edit = 0, continue_edit = 0;
12602 int drop_only = 0, edit_logmsg_only = 0, fold_only = 0, edit_only = 0;
12603 int allow_conflict = 0, list_backups = 0, delete_backups = 0;
12604 const char *edit_script_path = NULL;
12605 struct got_object_id_queue commits;
12606 struct got_pathlist_head merged_paths;
12607 const struct got_object_id_queue *parent_ids;
12608 struct got_object_qid *pid;
12609 struct got_histedit_list histedit_cmds;
12610 struct got_histedit_list_entry *hle;
12611 int *pack_fds = NULL;
12613 STAILQ_INIT(&commits);
12614 TAILQ_INIT(&histedit_cmds);
12615 TAILQ_INIT(&merged_paths);
12616 memset(&upa, 0, sizeof(upa));
12618 #ifndef PROFILE
12619 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
12620 "unveil", NULL) == -1)
12621 err(1, "pledge");
12622 #endif
12624 while ((ch = getopt(argc, argv, "aCcdeF:flmX")) != -1) {
12625 switch (ch) {
12626 case 'a':
12627 abort_edit = 1;
12628 break;
12629 case 'C':
12630 allow_conflict = 1;
12631 break;
12632 case 'c':
12633 continue_edit = 1;
12634 break;
12635 case 'd':
12636 drop_only = 1;
12637 break;
12638 case 'e':
12639 edit_only = 1;
12640 break;
12641 case 'F':
12642 edit_script_path = optarg;
12643 break;
12644 case 'f':
12645 fold_only = 1;
12646 break;
12647 case 'l':
12648 list_backups = 1;
12649 break;
12650 case 'm':
12651 edit_logmsg_only = 1;
12652 break;
12653 case 'X':
12654 delete_backups = 1;
12655 break;
12656 default:
12657 usage_histedit();
12658 /* NOTREACHED */
12662 argc -= optind;
12663 argv += optind;
12665 if (abort_edit && allow_conflict)
12666 option_conflict('a', 'C');
12667 if (abort_edit && continue_edit)
12668 option_conflict('a', 'c');
12669 if (edit_script_path && allow_conflict)
12670 option_conflict('F', 'C');
12671 if (edit_script_path && edit_logmsg_only)
12672 option_conflict('F', 'm');
12673 if (abort_edit && edit_logmsg_only)
12674 option_conflict('a', 'm');
12675 if (edit_logmsg_only && allow_conflict)
12676 option_conflict('m', 'C');
12677 if (continue_edit && edit_logmsg_only)
12678 option_conflict('c', 'm');
12679 if (abort_edit && fold_only)
12680 option_conflict('a', 'f');
12681 if (fold_only && allow_conflict)
12682 option_conflict('f', 'C');
12683 if (continue_edit && fold_only)
12684 option_conflict('c', 'f');
12685 if (fold_only && edit_logmsg_only)
12686 option_conflict('f', 'm');
12687 if (edit_script_path && fold_only)
12688 option_conflict('F', 'f');
12689 if (abort_edit && edit_only)
12690 option_conflict('a', 'e');
12691 if (continue_edit && edit_only)
12692 option_conflict('c', 'e');
12693 if (edit_only && edit_logmsg_only)
12694 option_conflict('e', 'm');
12695 if (edit_script_path && edit_only)
12696 option_conflict('F', 'e');
12697 if (fold_only && edit_only)
12698 option_conflict('f', 'e');
12699 if (drop_only && abort_edit)
12700 option_conflict('d', 'a');
12701 if (drop_only && allow_conflict)
12702 option_conflict('d', 'C');
12703 if (drop_only && continue_edit)
12704 option_conflict('d', 'c');
12705 if (drop_only && edit_logmsg_only)
12706 option_conflict('d', 'm');
12707 if (drop_only && edit_only)
12708 option_conflict('d', 'e');
12709 if (drop_only && edit_script_path)
12710 option_conflict('d', 'F');
12711 if (drop_only && fold_only)
12712 option_conflict('d', 'f');
12713 if (list_backups) {
12714 if (abort_edit)
12715 option_conflict('l', 'a');
12716 if (allow_conflict)
12717 option_conflict('l', 'C');
12718 if (continue_edit)
12719 option_conflict('l', 'c');
12720 if (edit_script_path)
12721 option_conflict('l', 'F');
12722 if (edit_logmsg_only)
12723 option_conflict('l', 'm');
12724 if (drop_only)
12725 option_conflict('l', 'd');
12726 if (fold_only)
12727 option_conflict('l', 'f');
12728 if (edit_only)
12729 option_conflict('l', 'e');
12730 if (delete_backups)
12731 option_conflict('l', 'X');
12732 if (argc != 0 && argc != 1)
12733 usage_histedit();
12734 } else if (delete_backups) {
12735 if (abort_edit)
12736 option_conflict('X', 'a');
12737 if (allow_conflict)
12738 option_conflict('X', 'C');
12739 if (continue_edit)
12740 option_conflict('X', 'c');
12741 if (drop_only)
12742 option_conflict('X', 'd');
12743 if (edit_script_path)
12744 option_conflict('X', 'F');
12745 if (edit_logmsg_only)
12746 option_conflict('X', 'm');
12747 if (fold_only)
12748 option_conflict('X', 'f');
12749 if (edit_only)
12750 option_conflict('X', 'e');
12751 if (list_backups)
12752 option_conflict('X', 'l');
12753 if (argc != 0 && argc != 1)
12754 usage_histedit();
12755 } else if (allow_conflict && !continue_edit)
12756 errx(1, "-C option requires -c");
12757 else if (argc != 0)
12758 usage_histedit();
12761 * This command cannot apply unveil(2) in all cases because the
12762 * user may choose to run an editor to edit the histedit script
12763 * and to edit individual commit log messages.
12764 * unveil(2) traverses exec(2); if an editor is used we have to
12765 * apply unveil after edit script and log messages have been written.
12766 * XXX TODO: Make use of unveil(2) where possible.
12769 cwd = getcwd(NULL, 0);
12770 if (cwd == NULL) {
12771 error = got_error_from_errno("getcwd");
12772 goto done;
12775 error = got_repo_pack_fds_open(&pack_fds);
12776 if (error != NULL)
12777 goto done;
12779 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
12780 if (error) {
12781 if (list_backups || delete_backups) {
12782 if (error->code != GOT_ERR_NOT_WORKTREE)
12783 goto done;
12784 } else {
12785 if (error->code == GOT_ERR_NOT_WORKTREE)
12786 error = wrap_not_worktree_error(error,
12787 "histedit", cwd);
12788 goto done;
12792 if (list_backups || delete_backups) {
12793 error = got_repo_open(&repo,
12794 worktree ? got_worktree_get_repo_path(worktree) : cwd,
12795 NULL, pack_fds);
12796 if (error != NULL)
12797 goto done;
12798 error = apply_unveil(got_repo_get_path(repo), 0,
12799 worktree ? got_worktree_get_root_path(worktree) : NULL);
12800 if (error)
12801 goto done;
12802 error = process_backup_refs(
12803 GOT_WORKTREE_HISTEDIT_BACKUP_REF_PREFIX,
12804 argc == 1 ? argv[0] : NULL, delete_backups, repo);
12805 goto done; /* nothing else to do */
12808 error = get_gitconfig_path(&gitconfig_path);
12809 if (error)
12810 goto done;
12811 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
12812 gitconfig_path, pack_fds);
12813 if (error != NULL)
12814 goto done;
12816 if (worktree != NULL && !list_backups && !delete_backups) {
12817 error = worktree_has_logmsg_ref("histedit", worktree, repo);
12818 if (error)
12819 goto done;
12822 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
12823 if (error)
12824 goto done;
12825 if (rebase_in_progress) {
12826 error = got_error(GOT_ERR_REBASING);
12827 goto done;
12830 error = got_worktree_merge_in_progress(&merge_in_progress, worktree,
12831 repo);
12832 if (error)
12833 goto done;
12834 if (merge_in_progress) {
12835 error = got_error(GOT_ERR_MERGE_BUSY);
12836 goto done;
12839 error = got_worktree_histedit_in_progress(&edit_in_progress, worktree);
12840 if (error)
12841 goto done;
12843 if (edit_in_progress && edit_logmsg_only) {
12844 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
12845 "histedit operation is in progress in this "
12846 "work tree and must be continued or aborted "
12847 "before the -m option can be used");
12848 goto done;
12850 if (edit_in_progress && drop_only) {
12851 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
12852 "histedit operation is in progress in this "
12853 "work tree and must be continued or aborted "
12854 "before the -d option can be used");
12855 goto done;
12857 if (edit_in_progress && fold_only) {
12858 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
12859 "histedit operation is in progress in this "
12860 "work tree and must be continued or aborted "
12861 "before the -f option can be used");
12862 goto done;
12864 if (edit_in_progress && edit_only) {
12865 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
12866 "histedit operation is in progress in this "
12867 "work tree and must be continued or aborted "
12868 "before the -e option can be used");
12869 goto done;
12872 if (edit_in_progress && abort_edit) {
12873 error = got_worktree_histedit_continue(&resume_commit_id,
12874 &tmp_branch, &branch, &base_commit_id, &fileindex,
12875 worktree, repo);
12876 if (error)
12877 goto done;
12878 printf("Switching work tree to %s\n",
12879 got_ref_get_symref_target(branch));
12880 error = got_worktree_histedit_abort(worktree, fileindex, repo,
12881 branch, base_commit_id, abort_progress, &upa);
12882 if (error)
12883 goto done;
12884 printf("Histedit of %s aborted\n",
12885 got_ref_get_symref_target(branch));
12886 print_merge_progress_stats(&upa);
12887 goto done; /* nothing else to do */
12888 } else if (abort_edit) {
12889 error = got_error(GOT_ERR_NOT_HISTEDIT);
12890 goto done;
12893 error = get_author(&committer, repo, worktree);
12894 if (error)
12895 goto done;
12897 if (continue_edit) {
12898 char *path;
12900 if (!edit_in_progress) {
12901 error = got_error(GOT_ERR_NOT_HISTEDIT);
12902 goto done;
12905 error = got_worktree_get_histedit_script_path(&path, worktree);
12906 if (error)
12907 goto done;
12909 error = histedit_load_list(&histedit_cmds, path, repo);
12910 free(path);
12911 if (error)
12912 goto done;
12914 error = got_worktree_histedit_continue(&resume_commit_id,
12915 &tmp_branch, &branch, &base_commit_id, &fileindex,
12916 worktree, repo);
12917 if (error)
12918 goto done;
12920 error = got_ref_resolve(&head_commit_id, repo, branch);
12921 if (error)
12922 goto done;
12924 error = got_object_open_as_commit(&commit, repo,
12925 head_commit_id);
12926 if (error)
12927 goto done;
12928 parent_ids = got_object_commit_get_parent_ids(commit);
12929 pid = STAILQ_FIRST(parent_ids);
12930 if (pid == NULL) {
12931 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
12932 goto done;
12934 error = collect_commits(&commits, head_commit_id, &pid->id,
12935 base_commit_id, got_worktree_get_path_prefix(worktree),
12936 GOT_ERR_HISTEDIT_PATH, repo);
12937 got_object_commit_close(commit);
12938 commit = NULL;
12939 if (error)
12940 goto done;
12941 } else {
12942 if (edit_in_progress) {
12943 error = got_error(GOT_ERR_HISTEDIT_BUSY);
12944 goto done;
12947 error = got_ref_open(&branch, repo,
12948 got_worktree_get_head_ref_name(worktree), 0);
12949 if (error != NULL)
12950 goto done;
12952 if (strncmp(got_ref_get_name(branch), "refs/heads/", 11) != 0) {
12953 error = got_error_msg(GOT_ERR_COMMIT_BRANCH,
12954 "will not edit commit history of a branch outside "
12955 "the \"refs/heads/\" reference namespace");
12956 goto done;
12959 error = got_ref_resolve(&head_commit_id, repo, branch);
12960 got_ref_close(branch);
12961 branch = NULL;
12962 if (error)
12963 goto done;
12965 error = got_object_open_as_commit(&commit, repo,
12966 head_commit_id);
12967 if (error)
12968 goto done;
12969 parent_ids = got_object_commit_get_parent_ids(commit);
12970 pid = STAILQ_FIRST(parent_ids);
12971 if (pid == NULL) {
12972 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
12973 goto done;
12975 error = collect_commits(&commits, head_commit_id, &pid->id,
12976 got_worktree_get_base_commit_id(worktree),
12977 got_worktree_get_path_prefix(worktree),
12978 GOT_ERR_HISTEDIT_PATH, repo);
12979 got_object_commit_close(commit);
12980 commit = NULL;
12981 if (error)
12982 goto done;
12984 if (STAILQ_EMPTY(&commits)) {
12985 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
12986 goto done;
12989 error = got_worktree_histedit_prepare(&tmp_branch, &branch,
12990 &base_commit_id, &fileindex, worktree, repo);
12991 if (error)
12992 goto done;
12994 if (edit_script_path) {
12995 error = histedit_load_list(&histedit_cmds,
12996 edit_script_path, repo);
12997 if (error) {
12998 got_worktree_histedit_abort(worktree, fileindex,
12999 repo, branch, base_commit_id,
13000 abort_progress, &upa);
13001 print_merge_progress_stats(&upa);
13002 goto done;
13004 } else {
13005 const char *branch_name;
13006 branch_name = got_ref_get_symref_target(branch);
13007 if (strncmp(branch_name, "refs/heads/", 11) == 0)
13008 branch_name += 11;
13009 error = histedit_edit_script(&histedit_cmds, &commits,
13010 branch_name, edit_logmsg_only, fold_only,
13011 drop_only, edit_only, repo);
13012 if (error) {
13013 got_worktree_histedit_abort(worktree, fileindex,
13014 repo, branch, base_commit_id,
13015 abort_progress, &upa);
13016 print_merge_progress_stats(&upa);
13017 goto done;
13022 error = histedit_save_list(&histedit_cmds, worktree,
13023 repo);
13024 if (error) {
13025 got_worktree_histedit_abort(worktree, fileindex,
13026 repo, branch, base_commit_id,
13027 abort_progress, &upa);
13028 print_merge_progress_stats(&upa);
13029 goto done;
13034 error = histedit_check_script(&histedit_cmds, &commits, repo);
13035 if (error)
13036 goto done;
13038 TAILQ_FOREACH(hle, &histedit_cmds, entry) {
13039 if (resume_commit_id) {
13040 if (got_object_id_cmp(hle->commit_id,
13041 resume_commit_id) != 0)
13042 continue;
13044 resume_commit_id = NULL;
13045 if (hle->cmd->code == GOT_HISTEDIT_DROP ||
13046 hle->cmd->code == GOT_HISTEDIT_FOLD) {
13047 error = histedit_skip_commit(hle, worktree,
13048 repo);
13049 if (error)
13050 goto done;
13051 } else {
13052 struct got_pathlist_head paths;
13053 int have_changes = 0;
13055 TAILQ_INIT(&paths);
13056 error = got_pathlist_append(&paths, "", NULL);
13057 if (error)
13058 goto done;
13059 error = got_worktree_status(worktree, &paths,
13060 repo, 0, check_local_changes, &have_changes,
13061 check_cancelled, NULL);
13062 got_pathlist_free(&paths,
13063 GOT_PATHLIST_FREE_NONE);
13064 if (error) {
13065 if (error->code != GOT_ERR_CANCELLED)
13066 goto done;
13067 if (sigint_received || sigpipe_received)
13068 goto done;
13070 if (have_changes) {
13071 error = histedit_commit(NULL, worktree,
13072 fileindex, tmp_branch, hle,
13073 committer, allow_conflict, repo);
13074 if (error)
13075 goto done;
13076 } else {
13077 error = got_object_open_as_commit(
13078 &commit, repo, hle->commit_id);
13079 if (error)
13080 goto done;
13081 error = show_histedit_progress(commit,
13082 hle, NULL);
13083 got_object_commit_close(commit);
13084 commit = NULL;
13085 if (error)
13086 goto done;
13089 continue;
13092 if (hle->cmd->code == GOT_HISTEDIT_DROP) {
13093 error = histedit_skip_commit(hle, worktree, repo);
13094 if (error)
13095 goto done;
13096 continue;
13098 error = got_object_open_as_commit(&commit, repo,
13099 hle->commit_id);
13100 if (error)
13101 goto done;
13102 parent_ids = got_object_commit_get_parent_ids(commit);
13103 pid = STAILQ_FIRST(parent_ids);
13105 error = got_worktree_histedit_merge_files(&merged_paths,
13106 worktree, fileindex, &pid->id, hle->commit_id, repo,
13107 update_progress, &upa, check_cancelled, NULL);
13108 if (error)
13109 goto done;
13110 got_object_commit_close(commit);
13111 commit = NULL;
13113 print_merge_progress_stats(&upa);
13114 if (upa.conflicts > 0 || upa.missing > 0 ||
13115 upa.not_deleted > 0 || upa.unversioned > 0) {
13116 if (upa.conflicts > 0) {
13117 error = show_rebase_merge_conflict(
13118 hle->commit_id, repo);
13119 if (error)
13120 goto done;
13122 got_pathlist_free(&merged_paths, GOT_PATHLIST_FREE_PATH);
13123 break;
13126 if (hle->cmd->code == GOT_HISTEDIT_EDIT) {
13127 char *id_str;
13128 error = got_object_id_str(&id_str, hle->commit_id);
13129 if (error)
13130 goto done;
13131 printf("Stopping histedit for amending commit %s\n",
13132 id_str);
13133 free(id_str);
13134 got_pathlist_free(&merged_paths, GOT_PATHLIST_FREE_PATH);
13135 error = got_worktree_histedit_postpone(worktree,
13136 fileindex);
13137 goto done;
13138 } else if (hle->cmd->code == GOT_HISTEDIT_FOLD) {
13139 error = histedit_skip_commit(hle, worktree, repo);
13140 if (error)
13141 goto done;
13142 continue;
13143 } else if (hle->cmd->code == GOT_HISTEDIT_MESG) {
13144 error = histedit_edit_logmsg(hle, repo);
13145 if (error)
13146 goto done;
13149 error = histedit_commit(&merged_paths, worktree, fileindex,
13150 tmp_branch, hle, committer, allow_conflict, repo);
13151 got_pathlist_free(&merged_paths, GOT_PATHLIST_FREE_PATH);
13152 if (error)
13153 goto done;
13156 if (upa.conflicts > 0 || upa.missing > 0 ||
13157 upa.not_deleted > 0 || upa.unversioned > 0) {
13158 error = got_worktree_histedit_postpone(worktree, fileindex);
13159 if (error)
13160 goto done;
13161 if (upa.conflicts > 0 && upa.missing == 0 &&
13162 upa.not_deleted == 0 && upa.unversioned == 0) {
13163 error = got_error_msg(GOT_ERR_CONFLICTS,
13164 "conflicts must be resolved before histedit "
13165 "can continue");
13166 } else if (upa.conflicts > 0) {
13167 error = got_error_msg(GOT_ERR_CONFLICTS,
13168 "conflicts must be resolved before histedit "
13169 "can continue; changes destined for some "
13170 "files were not yet merged and should be "
13171 "merged manually if required before the "
13172 "histedit operation is continued");
13173 } else {
13174 error = got_error_msg(GOT_ERR_CONFLICTS,
13175 "changes destined for some files were not "
13176 "yet merged and should be merged manually "
13177 "if required before the histedit operation "
13178 "is continued");
13180 } else
13181 error = histedit_complete(worktree, fileindex, tmp_branch,
13182 branch, repo);
13183 done:
13184 free(cwd);
13185 free(committer);
13186 free(gitconfig_path);
13187 got_object_id_queue_free(&commits);
13188 histedit_free_list(&histedit_cmds);
13189 free(head_commit_id);
13190 free(base_commit_id);
13191 free(resume_commit_id);
13192 if (commit)
13193 got_object_commit_close(commit);
13194 if (branch)
13195 got_ref_close(branch);
13196 if (tmp_branch)
13197 got_ref_close(tmp_branch);
13198 if (worktree)
13199 got_worktree_close(worktree);
13200 if (repo) {
13201 const struct got_error *close_err = got_repo_close(repo);
13202 if (error == NULL)
13203 error = close_err;
13205 if (pack_fds) {
13206 const struct got_error *pack_err =
13207 got_repo_pack_fds_close(pack_fds);
13208 if (error == NULL)
13209 error = pack_err;
13211 return error;
13214 __dead static void
13215 usage_integrate(void)
13217 fprintf(stderr, "usage: %s integrate branch\n", getprogname());
13218 exit(1);
13221 static const struct got_error *
13222 cmd_integrate(int argc, char *argv[])
13224 const struct got_error *error = NULL;
13225 struct got_repository *repo = NULL;
13226 struct got_worktree *worktree = NULL;
13227 char *cwd = NULL, *refname = NULL, *base_refname = NULL;
13228 const char *branch_arg = NULL;
13229 struct got_reference *branch_ref = NULL, *base_branch_ref = NULL;
13230 struct got_fileindex *fileindex = NULL;
13231 struct got_object_id *commit_id = NULL, *base_commit_id = NULL;
13232 int ch;
13233 struct got_update_progress_arg upa;
13234 int *pack_fds = NULL;
13236 #ifndef PROFILE
13237 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
13238 "unveil", NULL) == -1)
13239 err(1, "pledge");
13240 #endif
13242 while ((ch = getopt(argc, argv, "")) != -1) {
13243 switch (ch) {
13244 default:
13245 usage_integrate();
13246 /* NOTREACHED */
13250 argc -= optind;
13251 argv += optind;
13253 if (argc != 1)
13254 usage_integrate();
13255 branch_arg = argv[0];
13257 cwd = getcwd(NULL, 0);
13258 if (cwd == NULL) {
13259 error = got_error_from_errno("getcwd");
13260 goto done;
13263 error = got_repo_pack_fds_open(&pack_fds);
13264 if (error != NULL)
13265 goto done;
13267 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
13268 if (error) {
13269 if (error->code == GOT_ERR_NOT_WORKTREE)
13270 error = wrap_not_worktree_error(error, "integrate",
13271 cwd);
13272 goto done;
13275 error = check_rebase_or_histedit_in_progress(worktree);
13276 if (error)
13277 goto done;
13279 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
13280 NULL, pack_fds);
13281 if (error != NULL)
13282 goto done;
13284 error = apply_unveil(got_repo_get_path(repo), 0,
13285 got_worktree_get_root_path(worktree));
13286 if (error)
13287 goto done;
13289 error = check_merge_in_progress(worktree, repo);
13290 if (error)
13291 goto done;
13293 if (asprintf(&refname, "refs/heads/%s", branch_arg) == -1) {
13294 error = got_error_from_errno("asprintf");
13295 goto done;
13298 error = got_worktree_integrate_prepare(&fileindex, &branch_ref,
13299 &base_branch_ref, worktree, refname, repo);
13300 if (error)
13301 goto done;
13303 refname = strdup(got_ref_get_name(branch_ref));
13304 if (refname == NULL) {
13305 error = got_error_from_errno("strdup");
13306 got_worktree_integrate_abort(worktree, fileindex, repo,
13307 branch_ref, base_branch_ref);
13308 goto done;
13310 base_refname = strdup(got_ref_get_name(base_branch_ref));
13311 if (base_refname == NULL) {
13312 error = got_error_from_errno("strdup");
13313 got_worktree_integrate_abort(worktree, fileindex, repo,
13314 branch_ref, base_branch_ref);
13315 goto done;
13317 if (strncmp(base_refname, "refs/heads/", 11) != 0) {
13318 error = got_error(GOT_ERR_INTEGRATE_BRANCH);
13319 got_worktree_integrate_abort(worktree, fileindex, repo,
13320 branch_ref, base_branch_ref);
13321 goto done;
13324 error = got_ref_resolve(&commit_id, repo, branch_ref);
13325 if (error)
13326 goto done;
13328 error = got_ref_resolve(&base_commit_id, repo, base_branch_ref);
13329 if (error)
13330 goto done;
13332 if (got_object_id_cmp(commit_id, base_commit_id) == 0) {
13333 error = got_error_msg(GOT_ERR_SAME_BRANCH,
13334 "specified branch has already been integrated");
13335 got_worktree_integrate_abort(worktree, fileindex, repo,
13336 branch_ref, base_branch_ref);
13337 goto done;
13340 error = check_linear_ancestry(commit_id, base_commit_id, 1, repo);
13341 if (error) {
13342 if (error->code == GOT_ERR_ANCESTRY)
13343 error = got_error(GOT_ERR_REBASE_REQUIRED);
13344 got_worktree_integrate_abort(worktree, fileindex, repo,
13345 branch_ref, base_branch_ref);
13346 goto done;
13349 memset(&upa, 0, sizeof(upa));
13350 error = got_worktree_integrate_continue(worktree, fileindex, repo,
13351 branch_ref, base_branch_ref, update_progress, &upa,
13352 check_cancelled, NULL);
13353 if (error)
13354 goto done;
13356 printf("Integrated %s into %s\n", refname, base_refname);
13357 print_update_progress_stats(&upa);
13358 done:
13359 if (repo) {
13360 const struct got_error *close_err = got_repo_close(repo);
13361 if (error == NULL)
13362 error = close_err;
13364 if (worktree)
13365 got_worktree_close(worktree);
13366 if (pack_fds) {
13367 const struct got_error *pack_err =
13368 got_repo_pack_fds_close(pack_fds);
13369 if (error == NULL)
13370 error = pack_err;
13372 free(cwd);
13373 free(base_commit_id);
13374 free(commit_id);
13375 free(refname);
13376 free(base_refname);
13377 return error;
13380 __dead static void
13381 usage_merge(void)
13383 fprintf(stderr, "usage: %s merge [-aCcn] [branch]\n", getprogname());
13384 exit(1);
13387 static const struct got_error *
13388 cmd_merge(int argc, char *argv[])
13390 const struct got_error *error = NULL;
13391 struct got_worktree *worktree = NULL;
13392 struct got_repository *repo = NULL;
13393 struct got_fileindex *fileindex = NULL;
13394 char *cwd = NULL, *id_str = NULL, *author = NULL;
13395 char *gitconfig_path = NULL;
13396 struct got_reference *branch = NULL, *wt_branch = NULL;
13397 struct got_object_id *branch_tip = NULL, *yca_id = NULL;
13398 struct got_object_id *wt_branch_tip = NULL;
13399 int ch, merge_in_progress = 0, abort_merge = 0, continue_merge = 0;
13400 int allow_conflict = 0, prefer_fast_forward = 1, interrupt_merge = 0;
13401 struct got_update_progress_arg upa;
13402 struct got_object_id *merge_commit_id = NULL;
13403 char *branch_name = NULL;
13404 int *pack_fds = NULL;
13406 memset(&upa, 0, sizeof(upa));
13408 #ifndef PROFILE
13409 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
13410 "unveil", NULL) == -1)
13411 err(1, "pledge");
13412 #endif
13414 while ((ch = getopt(argc, argv, "aCcMn")) != -1) {
13415 switch (ch) {
13416 case 'a':
13417 abort_merge = 1;
13418 break;
13419 case 'C':
13420 allow_conflict = 1;
13421 break;
13422 case 'c':
13423 continue_merge = 1;
13424 break;
13425 case 'M':
13426 prefer_fast_forward = 0;
13427 break;
13428 case 'n':
13429 interrupt_merge = 1;
13430 break;
13431 default:
13432 usage_merge();
13433 /* NOTREACHED */
13437 argc -= optind;
13438 argv += optind;
13440 if (abort_merge) {
13441 if (continue_merge)
13442 option_conflict('a', 'c');
13443 if (!prefer_fast_forward)
13444 option_conflict('a', 'M');
13445 if (interrupt_merge)
13446 option_conflict('a', 'n');
13447 } else if (continue_merge) {
13448 if (!prefer_fast_forward)
13449 option_conflict('c', 'M');
13450 if (interrupt_merge)
13451 option_conflict('c', 'n');
13453 if (allow_conflict) {
13454 if (!continue_merge)
13455 errx(1, "-C option requires -c");
13457 if (abort_merge || continue_merge) {
13458 if (argc != 0)
13459 usage_merge();
13460 } else if (argc != 1)
13461 usage_merge();
13463 cwd = getcwd(NULL, 0);
13464 if (cwd == NULL) {
13465 error = got_error_from_errno("getcwd");
13466 goto done;
13469 error = got_repo_pack_fds_open(&pack_fds);
13470 if (error != NULL)
13471 goto done;
13473 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
13474 if (error) {
13475 if (error->code == GOT_ERR_NOT_WORKTREE)
13476 error = wrap_not_worktree_error(error,
13477 "merge", cwd);
13478 goto done;
13481 error = get_gitconfig_path(&gitconfig_path);
13482 if (error)
13483 goto done;
13484 error = got_repo_open(&repo,
13485 worktree ? got_worktree_get_repo_path(worktree) : cwd,
13486 gitconfig_path, pack_fds);
13487 if (error != NULL)
13488 goto done;
13490 if (worktree != NULL) {
13491 error = worktree_has_logmsg_ref("merge", worktree, repo);
13492 if (error)
13493 goto done;
13496 error = apply_unveil(got_repo_get_path(repo), 0,
13497 worktree ? got_worktree_get_root_path(worktree) : NULL);
13498 if (error)
13499 goto done;
13501 error = check_rebase_or_histedit_in_progress(worktree);
13502 if (error)
13503 goto done;
13505 error = got_worktree_merge_in_progress(&merge_in_progress, worktree,
13506 repo);
13507 if (error)
13508 goto done;
13510 if (merge_in_progress && !(abort_merge || continue_merge)) {
13511 error = got_error(GOT_ERR_MERGE_BUSY);
13512 goto done;
13515 if (!merge_in_progress && (abort_merge || continue_merge)) {
13516 error = got_error(GOT_ERR_NOT_MERGING);
13517 goto done;
13520 if (abort_merge) {
13521 error = got_worktree_merge_continue(&branch_name,
13522 &branch_tip, &fileindex, worktree, repo);
13523 if (error)
13524 goto done;
13525 error = got_worktree_merge_abort(worktree, fileindex, repo,
13526 abort_progress, &upa);
13527 if (error)
13528 goto done;
13529 printf("Merge of %s aborted\n", branch_name);
13530 goto done; /* nothing else to do */
13533 if (strncmp(got_worktree_get_head_ref_name(worktree),
13534 "refs/heads/", 11) != 0) {
13535 error = got_error_fmt(GOT_ERR_COMMIT_BRANCH,
13536 "work tree's current branch %s is outside the "
13537 "\"refs/heads/\" reference namespace; "
13538 "update -b required",
13539 got_worktree_get_head_ref_name(worktree));
13540 goto done;
13543 error = get_author(&author, repo, worktree);
13544 if (error)
13545 goto done;
13547 error = got_ref_open(&wt_branch, repo,
13548 got_worktree_get_head_ref_name(worktree), 0);
13549 if (error)
13550 goto done;
13551 error = got_ref_resolve(&wt_branch_tip, repo, wt_branch);
13552 if (error)
13553 goto done;
13555 if (continue_merge) {
13556 struct got_object_id *base_commit_id;
13557 base_commit_id = got_worktree_get_base_commit_id(worktree);
13558 if (got_object_id_cmp(wt_branch_tip, base_commit_id) != 0) {
13559 error = got_error(GOT_ERR_MERGE_COMMIT_OUT_OF_DATE);
13560 goto done;
13562 error = got_worktree_merge_continue(&branch_name,
13563 &branch_tip, &fileindex, worktree, repo);
13564 if (error)
13565 goto done;
13566 } else {
13567 error = got_ref_open(&branch, repo, argv[0], 0);
13568 if (error != NULL)
13569 goto done;
13570 branch_name = strdup(got_ref_get_name(branch));
13571 if (branch_name == NULL) {
13572 error = got_error_from_errno("strdup");
13573 goto done;
13575 error = got_ref_resolve(&branch_tip, repo, branch);
13576 if (error)
13577 goto done;
13580 error = got_commit_graph_find_youngest_common_ancestor(&yca_id,
13581 wt_branch_tip, branch_tip, 0, 0, repo,
13582 check_cancelled, NULL);
13583 if (error && error->code != GOT_ERR_ANCESTRY)
13584 goto done;
13586 if (!continue_merge) {
13587 error = check_path_prefix(wt_branch_tip, branch_tip,
13588 got_worktree_get_path_prefix(worktree),
13589 GOT_ERR_MERGE_PATH, repo);
13590 if (error)
13591 goto done;
13592 error = got_worktree_merge_prepare(&fileindex, worktree, repo);
13593 if (error)
13594 goto done;
13595 if (prefer_fast_forward && yca_id &&
13596 got_object_id_cmp(wt_branch_tip, yca_id) == 0) {
13597 struct got_pathlist_head paths;
13598 if (interrupt_merge) {
13599 error = got_error_fmt(GOT_ERR_BAD_OPTION,
13600 "there are no changes to merge since %s "
13601 "is already based on %s; merge cannot be "
13602 "interrupted for amending; -n",
13603 branch_name, got_ref_get_name(wt_branch));
13604 goto done;
13606 printf("Forwarding %s to %s\n",
13607 got_ref_get_name(wt_branch), branch_name);
13608 error = got_ref_change_ref(wt_branch, branch_tip);
13609 if (error)
13610 goto done;
13611 error = got_ref_write(wt_branch, repo);
13612 if (error)
13613 goto done;
13614 error = got_worktree_set_base_commit_id(worktree, repo,
13615 branch_tip);
13616 if (error)
13617 goto done;
13618 TAILQ_INIT(&paths);
13619 error = got_pathlist_append(&paths, "", NULL);
13620 if (error)
13621 goto done;
13622 error = got_worktree_checkout_files(worktree,
13623 &paths, repo, update_progress, &upa,
13624 check_cancelled, NULL);
13625 got_pathlist_free(&paths, GOT_PATHLIST_FREE_NONE);
13626 if (error)
13627 goto done;
13628 if (upa.did_something) {
13629 char *id_str;
13630 error = got_object_id_str(&id_str, branch_tip);
13631 if (error)
13632 goto done;
13633 printf("Updated to commit %s\n", id_str);
13634 free(id_str);
13635 } else
13636 printf("Already up-to-date\n");
13637 print_update_progress_stats(&upa);
13638 goto done;
13640 error = got_worktree_merge_write_refs(worktree, branch, repo);
13641 if (error)
13642 goto done;
13644 error = got_worktree_merge_branch(worktree, fileindex,
13645 yca_id, branch_tip, repo, update_progress, &upa,
13646 check_cancelled, NULL);
13647 if (error)
13648 goto done;
13649 print_merge_progress_stats(&upa);
13650 if (!upa.did_something) {
13651 error = got_worktree_merge_abort(worktree, fileindex,
13652 repo, abort_progress, &upa);
13653 if (error)
13654 goto done;
13655 printf("Already up-to-date\n");
13656 goto done;
13660 if (interrupt_merge) {
13661 error = got_worktree_merge_postpone(worktree, fileindex);
13662 if (error)
13663 goto done;
13664 printf("Merge of %s interrupted on request\n", branch_name);
13665 } else if (upa.conflicts > 0 || upa.missing > 0 ||
13666 upa.not_deleted > 0 || upa.unversioned > 0) {
13667 error = got_worktree_merge_postpone(worktree, fileindex);
13668 if (error)
13669 goto done;
13670 if (upa.conflicts > 0 && upa.missing == 0 &&
13671 upa.not_deleted == 0 && upa.unversioned == 0) {
13672 error = got_error_msg(GOT_ERR_CONFLICTS,
13673 "conflicts must be resolved before merging "
13674 "can continue");
13675 } else if (upa.conflicts > 0) {
13676 error = got_error_msg(GOT_ERR_CONFLICTS,
13677 "conflicts must be resolved before merging "
13678 "can continue; changes destined for some "
13679 "files were not yet merged and "
13680 "should be merged manually if required before the "
13681 "merge operation is continued");
13682 } else {
13683 error = got_error_msg(GOT_ERR_CONFLICTS,
13684 "changes destined for some "
13685 "files were not yet merged and should be "
13686 "merged manually if required before the "
13687 "merge operation is continued");
13689 goto done;
13690 } else {
13691 error = got_worktree_merge_commit(&merge_commit_id, worktree,
13692 fileindex, author, NULL, 1, branch_tip, branch_name,
13693 allow_conflict, repo, continue_merge ? print_status : NULL,
13694 NULL);
13695 if (error)
13696 goto done;
13697 error = got_worktree_merge_complete(worktree, fileindex, repo);
13698 if (error)
13699 goto done;
13700 error = got_object_id_str(&id_str, merge_commit_id);
13701 if (error)
13702 goto done;
13703 printf("Merged %s into %s: %s\n", branch_name,
13704 got_worktree_get_head_ref_name(worktree),
13705 id_str);
13708 done:
13709 free(gitconfig_path);
13710 free(id_str);
13711 free(merge_commit_id);
13712 free(author);
13713 free(branch_tip);
13714 free(branch_name);
13715 free(yca_id);
13716 if (branch)
13717 got_ref_close(branch);
13718 if (wt_branch)
13719 got_ref_close(wt_branch);
13720 if (worktree)
13721 got_worktree_close(worktree);
13722 if (repo) {
13723 const struct got_error *close_err = got_repo_close(repo);
13724 if (error == NULL)
13725 error = close_err;
13727 if (pack_fds) {
13728 const struct got_error *pack_err =
13729 got_repo_pack_fds_close(pack_fds);
13730 if (error == NULL)
13731 error = pack_err;
13733 return error;
13736 __dead static void
13737 usage_stage(void)
13739 fprintf(stderr, "usage: %s stage [-lpS] [-F response-script] "
13740 "[path ...]\n", getprogname());
13741 exit(1);
13744 static const struct got_error *
13745 print_stage(void *arg, unsigned char status, unsigned char staged_status,
13746 const char *path, struct got_object_id *blob_id,
13747 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
13748 int dirfd, const char *de_name)
13750 const struct got_error *err = NULL;
13751 char *id_str = NULL;
13753 if (staged_status != GOT_STATUS_ADD &&
13754 staged_status != GOT_STATUS_MODIFY &&
13755 staged_status != GOT_STATUS_DELETE)
13756 return NULL;
13758 if (staged_status == GOT_STATUS_ADD ||
13759 staged_status == GOT_STATUS_MODIFY)
13760 err = got_object_id_str(&id_str, staged_blob_id);
13761 else
13762 err = got_object_id_str(&id_str, blob_id);
13763 if (err)
13764 return err;
13766 printf("%s %c %s\n", id_str, staged_status, path);
13767 free(id_str);
13768 return NULL;
13771 static const struct got_error *
13772 cmd_stage(int argc, char *argv[])
13774 const struct got_error *error = NULL;
13775 struct got_repository *repo = NULL;
13776 struct got_worktree *worktree = NULL;
13777 char *cwd = NULL;
13778 struct got_pathlist_head paths;
13779 int ch, list_stage = 0, pflag = 0, allow_bad_symlinks = 0;
13780 FILE *patch_script_file = NULL;
13781 const char *patch_script_path = NULL;
13782 struct choose_patch_arg cpa;
13783 int *pack_fds = NULL;
13785 TAILQ_INIT(&paths);
13787 #ifndef PROFILE
13788 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
13789 "unveil", NULL) == -1)
13790 err(1, "pledge");
13791 #endif
13793 while ((ch = getopt(argc, argv, "F:lpS")) != -1) {
13794 switch (ch) {
13795 case 'F':
13796 patch_script_path = optarg;
13797 break;
13798 case 'l':
13799 list_stage = 1;
13800 break;
13801 case 'p':
13802 pflag = 1;
13803 break;
13804 case 'S':
13805 allow_bad_symlinks = 1;
13806 break;
13807 default:
13808 usage_stage();
13809 /* NOTREACHED */
13813 argc -= optind;
13814 argv += optind;
13816 if (list_stage && (pflag || patch_script_path))
13817 errx(1, "-l option cannot be used with other options");
13818 if (patch_script_path && !pflag)
13819 errx(1, "-F option can only be used together with -p option");
13821 cwd = getcwd(NULL, 0);
13822 if (cwd == NULL) {
13823 error = got_error_from_errno("getcwd");
13824 goto done;
13827 error = got_repo_pack_fds_open(&pack_fds);
13828 if (error != NULL)
13829 goto done;
13831 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
13832 if (error) {
13833 if (error->code == GOT_ERR_NOT_WORKTREE)
13834 error = wrap_not_worktree_error(error, "stage", cwd);
13835 goto done;
13838 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
13839 NULL, pack_fds);
13840 if (error != NULL)
13841 goto done;
13843 if (patch_script_path) {
13844 patch_script_file = fopen(patch_script_path, "re");
13845 if (patch_script_file == NULL) {
13846 error = got_error_from_errno2("fopen",
13847 patch_script_path);
13848 goto done;
13851 error = apply_unveil(got_repo_get_path(repo), 0,
13852 got_worktree_get_root_path(worktree));
13853 if (error)
13854 goto done;
13856 error = check_merge_in_progress(worktree, repo);
13857 if (error)
13858 goto done;
13860 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
13861 if (error)
13862 goto done;
13864 if (list_stage)
13865 error = got_worktree_status(worktree, &paths, repo, 0,
13866 print_stage, NULL, check_cancelled, NULL);
13867 else {
13868 cpa.patch_script_file = patch_script_file;
13869 cpa.action = "stage";
13870 error = got_worktree_stage(worktree, &paths,
13871 pflag ? NULL : print_status, NULL,
13872 pflag ? choose_patch : NULL, &cpa,
13873 allow_bad_symlinks, repo);
13875 done:
13876 if (patch_script_file && fclose(patch_script_file) == EOF &&
13877 error == NULL)
13878 error = got_error_from_errno2("fclose", patch_script_path);
13879 if (repo) {
13880 const struct got_error *close_err = got_repo_close(repo);
13881 if (error == NULL)
13882 error = close_err;
13884 if (worktree)
13885 got_worktree_close(worktree);
13886 if (pack_fds) {
13887 const struct got_error *pack_err =
13888 got_repo_pack_fds_close(pack_fds);
13889 if (error == NULL)
13890 error = pack_err;
13892 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
13893 free(cwd);
13894 return error;
13897 __dead static void
13898 usage_unstage(void)
13900 fprintf(stderr, "usage: %s unstage [-p] [-F response-script] "
13901 "[path ...]\n", getprogname());
13902 exit(1);
13906 static const struct got_error *
13907 cmd_unstage(int argc, char *argv[])
13909 const struct got_error *error = NULL;
13910 struct got_repository *repo = NULL;
13911 struct got_worktree *worktree = NULL;
13912 char *cwd = NULL;
13913 struct got_pathlist_head paths;
13914 int ch, pflag = 0;
13915 struct got_update_progress_arg upa;
13916 FILE *patch_script_file = NULL;
13917 const char *patch_script_path = NULL;
13918 struct choose_patch_arg cpa;
13919 int *pack_fds = NULL;
13921 TAILQ_INIT(&paths);
13923 #ifndef PROFILE
13924 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
13925 "unveil", NULL) == -1)
13926 err(1, "pledge");
13927 #endif
13929 while ((ch = getopt(argc, argv, "F:p")) != -1) {
13930 switch (ch) {
13931 case 'F':
13932 patch_script_path = optarg;
13933 break;
13934 case 'p':
13935 pflag = 1;
13936 break;
13937 default:
13938 usage_unstage();
13939 /* NOTREACHED */
13943 argc -= optind;
13944 argv += optind;
13946 if (patch_script_path && !pflag)
13947 errx(1, "-F option can only be used together with -p option");
13949 cwd = getcwd(NULL, 0);
13950 if (cwd == NULL) {
13951 error = got_error_from_errno("getcwd");
13952 goto done;
13955 error = got_repo_pack_fds_open(&pack_fds);
13956 if (error != NULL)
13957 goto done;
13959 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
13960 if (error) {
13961 if (error->code == GOT_ERR_NOT_WORKTREE)
13962 error = wrap_not_worktree_error(error, "unstage", cwd);
13963 goto done;
13966 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
13967 NULL, pack_fds);
13968 if (error != NULL)
13969 goto done;
13971 if (patch_script_path) {
13972 patch_script_file = fopen(patch_script_path, "re");
13973 if (patch_script_file == NULL) {
13974 error = got_error_from_errno2("fopen",
13975 patch_script_path);
13976 goto done;
13980 error = apply_unveil(got_repo_get_path(repo), 0,
13981 got_worktree_get_root_path(worktree));
13982 if (error)
13983 goto done;
13985 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
13986 if (error)
13987 goto done;
13989 cpa.patch_script_file = patch_script_file;
13990 cpa.action = "unstage";
13991 memset(&upa, 0, sizeof(upa));
13992 error = got_worktree_unstage(worktree, &paths, update_progress,
13993 &upa, pflag ? choose_patch : NULL, &cpa, repo);
13994 if (!error)
13995 print_merge_progress_stats(&upa);
13996 done:
13997 if (patch_script_file && fclose(patch_script_file) == EOF &&
13998 error == NULL)
13999 error = got_error_from_errno2("fclose", patch_script_path);
14000 if (repo) {
14001 const struct got_error *close_err = got_repo_close(repo);
14002 if (error == NULL)
14003 error = close_err;
14005 if (worktree)
14006 got_worktree_close(worktree);
14007 if (pack_fds) {
14008 const struct got_error *pack_err =
14009 got_repo_pack_fds_close(pack_fds);
14010 if (error == NULL)
14011 error = pack_err;
14013 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
14014 free(cwd);
14015 return error;
14018 __dead static void
14019 usage_cat(void)
14021 fprintf(stderr, "usage: %s cat [-P] [-c commit] [-r repository-path] "
14022 "arg ...\n", getprogname());
14023 exit(1);
14026 static const struct got_error *
14027 cat_blob(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
14029 const struct got_error *err;
14030 struct got_blob_object *blob;
14031 int fd = -1;
14033 fd = got_opentempfd();
14034 if (fd == -1)
14035 return got_error_from_errno("got_opentempfd");
14037 err = got_object_open_as_blob(&blob, repo, id, 8192, fd);
14038 if (err)
14039 goto done;
14041 err = got_object_blob_dump_to_file(NULL, NULL, NULL, outfile, blob);
14042 done:
14043 if (fd != -1 && close(fd) == -1 && err == NULL)
14044 err = got_error_from_errno("close");
14045 if (blob)
14046 got_object_blob_close(blob);
14047 return err;
14050 static const struct got_error *
14051 cat_tree(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
14053 const struct got_error *err;
14054 struct got_tree_object *tree;
14055 int nentries, i;
14057 err = got_object_open_as_tree(&tree, repo, id);
14058 if (err)
14059 return err;
14061 nentries = got_object_tree_get_nentries(tree);
14062 for (i = 0; i < nentries; i++) {
14063 struct got_tree_entry *te;
14064 char *id_str;
14065 if (sigint_received || sigpipe_received)
14066 break;
14067 te = got_object_tree_get_entry(tree, i);
14068 err = got_object_id_str(&id_str, got_tree_entry_get_id(te));
14069 if (err)
14070 break;
14071 fprintf(outfile, "%s %.7o %s\n", id_str,
14072 got_tree_entry_get_mode(te),
14073 got_tree_entry_get_name(te));
14074 free(id_str);
14077 got_object_tree_close(tree);
14078 return err;
14081 static const struct got_error *
14082 cat_commit(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
14084 const struct got_error *err;
14085 struct got_commit_object *commit;
14086 const struct got_object_id_queue *parent_ids;
14087 struct got_object_qid *pid;
14088 char *id_str = NULL;
14089 const char *logmsg = NULL;
14090 char gmtoff[6];
14092 err = got_object_open_as_commit(&commit, repo, id);
14093 if (err)
14094 return err;
14096 err = got_object_id_str(&id_str, got_object_commit_get_tree_id(commit));
14097 if (err)
14098 goto done;
14100 fprintf(outfile, "%s%s\n", GOT_COMMIT_LABEL_TREE, id_str);
14101 parent_ids = got_object_commit_get_parent_ids(commit);
14102 fprintf(outfile, "numparents %d\n",
14103 got_object_commit_get_nparents(commit));
14104 STAILQ_FOREACH(pid, parent_ids, entry) {
14105 char *pid_str;
14106 err = got_object_id_str(&pid_str, &pid->id);
14107 if (err)
14108 goto done;
14109 fprintf(outfile, "%s%s\n", GOT_COMMIT_LABEL_PARENT, pid_str);
14110 free(pid_str);
14112 got_date_format_gmtoff(gmtoff, sizeof(gmtoff),
14113 got_object_commit_get_author_gmtoff(commit));
14114 fprintf(outfile, "%s%s %lld %s\n", GOT_COMMIT_LABEL_AUTHOR,
14115 got_object_commit_get_author(commit),
14116 (long long)got_object_commit_get_author_time(commit),
14117 gmtoff);
14119 got_date_format_gmtoff(gmtoff, sizeof(gmtoff),
14120 got_object_commit_get_committer_gmtoff(commit));
14121 fprintf(outfile, "%s%s %lld %s\n", GOT_COMMIT_LABEL_COMMITTER,
14122 got_object_commit_get_committer(commit),
14123 (long long)got_object_commit_get_committer_time(commit),
14124 gmtoff);
14126 logmsg = got_object_commit_get_logmsg_raw(commit);
14127 fprintf(outfile, "messagelen %zd\n", strlen(logmsg));
14128 fprintf(outfile, "%s", logmsg);
14129 done:
14130 free(id_str);
14131 got_object_commit_close(commit);
14132 return err;
14135 static const struct got_error *
14136 cat_tag(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
14138 const struct got_error *err;
14139 struct got_tag_object *tag;
14140 char *id_str = NULL;
14141 const char *tagmsg = NULL;
14142 char gmtoff[6];
14144 err = got_object_open_as_tag(&tag, repo, id);
14145 if (err)
14146 return err;
14148 err = got_object_id_str(&id_str, got_object_tag_get_object_id(tag));
14149 if (err)
14150 goto done;
14152 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_OBJECT, id_str);
14154 switch (got_object_tag_get_object_type(tag)) {
14155 case GOT_OBJ_TYPE_BLOB:
14156 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
14157 GOT_OBJ_LABEL_BLOB);
14158 break;
14159 case GOT_OBJ_TYPE_TREE:
14160 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
14161 GOT_OBJ_LABEL_TREE);
14162 break;
14163 case GOT_OBJ_TYPE_COMMIT:
14164 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
14165 GOT_OBJ_LABEL_COMMIT);
14166 break;
14167 case GOT_OBJ_TYPE_TAG:
14168 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
14169 GOT_OBJ_LABEL_TAG);
14170 break;
14171 default:
14172 break;
14175 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TAG,
14176 got_object_tag_get_name(tag));
14178 got_date_format_gmtoff(gmtoff, sizeof(gmtoff),
14179 got_object_tag_get_tagger_gmtoff(tag));
14180 fprintf(outfile, "%s%s %lld %s\n", GOT_TAG_LABEL_TAGGER,
14181 got_object_tag_get_tagger(tag),
14182 (long long)got_object_tag_get_tagger_time(tag),
14183 gmtoff);
14185 tagmsg = got_object_tag_get_message(tag);
14186 fprintf(outfile, "messagelen %zd\n", strlen(tagmsg));
14187 fprintf(outfile, "%s", tagmsg);
14188 done:
14189 free(id_str);
14190 got_object_tag_close(tag);
14191 return err;
14194 static const struct got_error *
14195 cmd_cat(int argc, char *argv[])
14197 const struct got_error *error;
14198 struct got_repository *repo = NULL;
14199 struct got_worktree *worktree = NULL;
14200 char *cwd = NULL, *repo_path = NULL, *label = NULL;
14201 char *keyword_idstr = NULL;
14202 const char *commit_id_str = NULL;
14203 struct got_object_id *id = NULL, *commit_id = NULL;
14204 struct got_commit_object *commit = NULL;
14205 int ch, obj_type, i, force_path = 0;
14206 struct got_reflist_head refs;
14207 int *pack_fds = NULL;
14209 TAILQ_INIT(&refs);
14211 #ifndef PROFILE
14212 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
14213 NULL) == -1)
14214 err(1, "pledge");
14215 #endif
14217 while ((ch = getopt(argc, argv, "c:Pr:")) != -1) {
14218 switch (ch) {
14219 case 'c':
14220 commit_id_str = optarg;
14221 break;
14222 case 'P':
14223 force_path = 1;
14224 break;
14225 case 'r':
14226 repo_path = realpath(optarg, NULL);
14227 if (repo_path == NULL)
14228 return got_error_from_errno2("realpath",
14229 optarg);
14230 got_path_strip_trailing_slashes(repo_path);
14231 break;
14232 default:
14233 usage_cat();
14234 /* NOTREACHED */
14238 argc -= optind;
14239 argv += optind;
14241 cwd = getcwd(NULL, 0);
14242 if (cwd == NULL) {
14243 error = got_error_from_errno("getcwd");
14244 goto done;
14247 error = got_repo_pack_fds_open(&pack_fds);
14248 if (error != NULL)
14249 goto done;
14251 if (repo_path == NULL) {
14252 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
14253 if (error && error->code != GOT_ERR_NOT_WORKTREE)
14254 goto done;
14255 if (worktree) {
14256 repo_path = strdup(
14257 got_worktree_get_repo_path(worktree));
14258 if (repo_path == NULL) {
14259 error = got_error_from_errno("strdup");
14260 goto done;
14263 if (commit_id_str == NULL) {
14264 /* Release work tree lock. */
14265 got_worktree_close(worktree);
14266 worktree = NULL;
14271 if (repo_path == NULL) {
14272 repo_path = strdup(cwd);
14273 if (repo_path == NULL)
14274 return got_error_from_errno("strdup");
14277 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
14278 free(repo_path);
14279 if (error != NULL)
14280 goto done;
14282 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
14283 if (error)
14284 goto done;
14286 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
14287 if (error)
14288 goto done;
14290 if (commit_id_str != NULL) {
14291 error = got_keyword_to_idstr(&keyword_idstr, commit_id_str,
14292 repo, worktree);
14293 if (error != NULL)
14294 goto done;
14295 if (keyword_idstr != NULL)
14296 commit_id_str = keyword_idstr;
14297 if (worktree != NULL) {
14298 got_worktree_close(worktree);
14299 worktree = NULL;
14301 } else
14302 commit_id_str = GOT_REF_HEAD;
14303 error = got_repo_match_object_id(&commit_id, NULL,
14304 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
14305 if (error)
14306 goto done;
14308 error = got_object_open_as_commit(&commit, repo, commit_id);
14309 if (error)
14310 goto done;
14312 for (i = 0; i < argc; i++) {
14313 if (force_path) {
14314 error = got_object_id_by_path(&id, repo, commit,
14315 argv[i]);
14316 if (error)
14317 break;
14318 } else {
14319 error = got_repo_match_object_id(&id, &label, argv[i],
14320 GOT_OBJ_TYPE_ANY, NULL /* do not resolve tags */,
14321 repo);
14322 if (error) {
14323 if (error->code != GOT_ERR_BAD_OBJ_ID_STR &&
14324 error->code != GOT_ERR_NOT_REF)
14325 break;
14326 error = got_object_id_by_path(&id, repo,
14327 commit, argv[i]);
14328 if (error)
14329 break;
14333 error = got_object_get_type(&obj_type, repo, id);
14334 if (error)
14335 break;
14337 switch (obj_type) {
14338 case GOT_OBJ_TYPE_BLOB:
14339 error = cat_blob(id, repo, stdout);
14340 break;
14341 case GOT_OBJ_TYPE_TREE:
14342 error = cat_tree(id, repo, stdout);
14343 break;
14344 case GOT_OBJ_TYPE_COMMIT:
14345 error = cat_commit(id, repo, stdout);
14346 break;
14347 case GOT_OBJ_TYPE_TAG:
14348 error = cat_tag(id, repo, stdout);
14349 break;
14350 default:
14351 error = got_error(GOT_ERR_OBJ_TYPE);
14352 break;
14354 if (error)
14355 break;
14356 free(label);
14357 label = NULL;
14358 free(id);
14359 id = NULL;
14361 done:
14362 free(label);
14363 free(id);
14364 free(commit_id);
14365 free(keyword_idstr);
14366 if (commit)
14367 got_object_commit_close(commit);
14368 if (worktree)
14369 got_worktree_close(worktree);
14370 if (repo) {
14371 const struct got_error *close_err = got_repo_close(repo);
14372 if (error == NULL)
14373 error = close_err;
14375 if (pack_fds) {
14376 const struct got_error *pack_err =
14377 got_repo_pack_fds_close(pack_fds);
14378 if (error == NULL)
14379 error = pack_err;
14382 got_ref_list_free(&refs);
14383 return error;
14386 __dead static void
14387 usage_info(void)
14389 fprintf(stderr, "usage: %s info [path ...]\n",
14390 getprogname());
14391 exit(1);
14394 static const struct got_error *
14395 print_path_info(void *arg, const char *path, mode_t mode, time_t mtime,
14396 struct got_object_id *blob_id, struct got_object_id *staged_blob_id,
14397 struct got_object_id *commit_id)
14399 const struct got_error *err = NULL;
14400 char *id_str = NULL;
14401 char datebuf[128];
14402 struct tm mytm, *tm;
14403 struct got_pathlist_head *paths = arg;
14404 struct got_pathlist_entry *pe;
14407 * Clear error indication from any of the path arguments which
14408 * would cause this file index entry to be displayed.
14410 TAILQ_FOREACH(pe, paths, entry) {
14411 if (got_path_cmp(path, pe->path, strlen(path),
14412 pe->path_len) == 0 ||
14413 got_path_is_child(path, pe->path, pe->path_len))
14414 pe->data = NULL; /* no error */
14417 printf(GOT_COMMIT_SEP_STR);
14418 if (S_ISLNK(mode))
14419 printf("symlink: %s\n", path);
14420 else if (S_ISREG(mode)) {
14421 printf("file: %s\n", path);
14422 printf("mode: %o\n", mode & (S_IRWXU | S_IRWXG | S_IRWXO));
14423 } else if (S_ISDIR(mode))
14424 printf("directory: %s\n", path);
14425 else
14426 printf("something: %s\n", path);
14428 tm = localtime_r(&mtime, &mytm);
14429 if (tm == NULL)
14430 return NULL;
14431 if (strftime(datebuf, sizeof(datebuf), "%c %Z", tm) == 0)
14432 return got_error(GOT_ERR_NO_SPACE);
14433 printf("timestamp: %s\n", datebuf);
14435 if (blob_id) {
14436 err = got_object_id_str(&id_str, blob_id);
14437 if (err)
14438 return err;
14439 printf("based on blob: %s\n", id_str);
14440 free(id_str);
14443 if (staged_blob_id) {
14444 err = got_object_id_str(&id_str, staged_blob_id);
14445 if (err)
14446 return err;
14447 printf("based on staged blob: %s\n", id_str);
14448 free(id_str);
14451 if (commit_id) {
14452 err = got_object_id_str(&id_str, commit_id);
14453 if (err)
14454 return err;
14455 printf("based on commit: %s\n", id_str);
14456 free(id_str);
14459 return NULL;
14462 static const struct got_error *
14463 cmd_info(int argc, char *argv[])
14465 const struct got_error *error = NULL;
14466 struct got_worktree *worktree = NULL;
14467 char *cwd = NULL, *id_str = NULL;
14468 struct got_pathlist_head paths;
14469 char *uuidstr = NULL;
14470 int ch, show_files = 0;
14472 TAILQ_INIT(&paths);
14474 #ifndef PROFILE
14475 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
14476 NULL) == -1)
14477 err(1, "pledge");
14478 #endif
14480 while ((ch = getopt(argc, argv, "")) != -1) {
14481 switch (ch) {
14482 default:
14483 usage_info();
14484 /* NOTREACHED */
14488 argc -= optind;
14489 argv += optind;
14491 cwd = getcwd(NULL, 0);
14492 if (cwd == NULL) {
14493 error = got_error_from_errno("getcwd");
14494 goto done;
14497 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
14498 if (error) {
14499 if (error->code == GOT_ERR_NOT_WORKTREE)
14500 error = wrap_not_worktree_error(error, "info", cwd);
14501 goto done;
14504 #ifndef PROFILE
14505 /* Remove "wpath cpath proc exec sendfd" promises. */
14506 if (pledge("stdio rpath flock unveil", NULL) == -1)
14507 err(1, "pledge");
14508 #endif
14509 error = apply_unveil(NULL, 0, got_worktree_get_root_path(worktree));
14510 if (error)
14511 goto done;
14513 if (argc >= 1) {
14514 error = get_worktree_paths_from_argv(&paths, argc, argv,
14515 worktree);
14516 if (error)
14517 goto done;
14518 show_files = 1;
14521 error = got_object_id_str(&id_str,
14522 got_worktree_get_base_commit_id(worktree));
14523 if (error)
14524 goto done;
14526 error = got_worktree_get_uuid(&uuidstr, worktree);
14527 if (error)
14528 goto done;
14530 printf("work tree: %s\n", got_worktree_get_root_path(worktree));
14531 printf("work tree base commit: %s\n", id_str);
14532 printf("work tree path prefix: %s\n",
14533 got_worktree_get_path_prefix(worktree));
14534 printf("work tree branch reference: %s\n",
14535 got_worktree_get_head_ref_name(worktree));
14536 printf("work tree UUID: %s\n", uuidstr);
14537 printf("repository: %s\n", got_worktree_get_repo_path(worktree));
14539 if (show_files) {
14540 struct got_pathlist_entry *pe;
14541 TAILQ_FOREACH(pe, &paths, entry) {
14542 if (pe->path_len == 0)
14543 continue;
14545 * Assume this path will fail. This will be corrected
14546 * in print_path_info() in case the path does suceeed.
14548 pe->data = (void *)got_error(GOT_ERR_BAD_PATH);
14550 error = got_worktree_path_info(worktree, &paths,
14551 print_path_info, &paths, check_cancelled, NULL);
14552 if (error)
14553 goto done;
14554 TAILQ_FOREACH(pe, &paths, entry) {
14555 if (pe->data != NULL) {
14556 const struct got_error *perr;
14558 perr = pe->data;
14559 error = got_error_fmt(perr->code, "%s",
14560 pe->path);
14561 break;
14565 done:
14566 if (worktree)
14567 got_worktree_close(worktree);
14568 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
14569 free(cwd);
14570 free(id_str);
14571 free(uuidstr);
14572 return error;