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 *editor, const char *repo_path)
7551 const struct got_error *err = NULL;
7552 char *template = NULL, *initial_content = NULL;
7553 int initial_content_len;
7554 int fd = -1;
7556 if (asprintf(&template, GOT_TMPDIR_STR "/got-tagmsg") == -1) {
7557 err = got_error_from_errno("asprintf");
7558 goto done;
7561 initial_content_len = asprintf(&initial_content,
7562 "\n# tagging commit %s as %s\n",
7563 commit_id_str, tag_name);
7564 if (initial_content_len == -1) {
7565 err = got_error_from_errno("asprintf");
7566 goto done;
7569 err = got_opentemp_named_fd(tagmsg_path, &fd, template, "");
7570 if (err)
7571 goto done;
7573 if (write(fd, initial_content, initial_content_len) == -1) {
7574 err = got_error_from_errno2("write", *tagmsg_path);
7575 goto done;
7577 if (close(fd) == -1) {
7578 err = got_error_from_errno2("close", *tagmsg_path);
7579 goto done;
7581 fd = -1;
7583 err = edit_logmsg(tagmsg, editor, *tagmsg_path, initial_content,
7584 initial_content_len, 1);
7585 done:
7586 free(initial_content);
7587 free(template);
7589 if (fd != -1 && close(fd) == -1 && err == NULL)
7590 err = got_error_from_errno2("close", *tagmsg_path);
7592 if (err) {
7593 free(*tagmsg);
7594 *tagmsg = NULL;
7596 return err;
7599 static const struct got_error *
7600 add_tag(struct got_repository *repo, const char *tagger,
7601 const char *tag_name, const char *commit_arg, const char *tagmsg_arg,
7602 const char *signer_id, const char *editor, int verbosity)
7604 const struct got_error *err = NULL;
7605 struct got_object_id *commit_id = NULL, *tag_id = NULL;
7606 char *label = NULL, *commit_id_str = NULL;
7607 struct got_reference *ref = NULL;
7608 char *refname = NULL, *tagmsg = NULL;
7609 char *tagmsg_path = NULL, *tag_id_str = NULL;
7610 int preserve_tagmsg = 0;
7611 struct got_reflist_head refs;
7613 TAILQ_INIT(&refs);
7616 * Don't let the user create a tag name with a leading '-'.
7617 * While technically a valid reference name, this case is usually
7618 * an unintended typo.
7620 if (tag_name[0] == '-')
7621 return got_error_path(tag_name, GOT_ERR_REF_NAME_MINUS);
7623 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
7624 if (err)
7625 goto done;
7627 err = got_repo_match_object_id(&commit_id, &label, commit_arg,
7628 GOT_OBJ_TYPE_COMMIT, &refs, repo);
7629 if (err)
7630 goto done;
7632 err = got_object_id_str(&commit_id_str, commit_id);
7633 if (err)
7634 goto done;
7636 err = get_tag_refname(&refname, tag_name);
7637 if (err)
7638 goto done;
7639 if (strncmp("refs/tags/", tag_name, 10) == 0)
7640 tag_name += 10;
7642 err = got_ref_open(&ref, repo, refname, 0);
7643 if (err == NULL) {
7644 err = got_error(GOT_ERR_TAG_EXISTS);
7645 goto done;
7646 } else if (err->code != GOT_ERR_NOT_REF)
7647 goto done;
7649 if (tagmsg_arg == NULL) {
7650 err = get_tag_message(&tagmsg, &tagmsg_path, commit_id_str,
7651 tag_name, editor, got_repo_get_path(repo));
7652 if (err) {
7653 if (err->code != GOT_ERR_COMMIT_MSG_EMPTY &&
7654 tagmsg_path != NULL)
7655 preserve_tagmsg = 1;
7656 goto done;
7660 err = got_object_tag_create(&tag_id, tag_name, commit_id,
7661 tagger, time(NULL), tagmsg ? tagmsg : tagmsg_arg, signer_id, repo,
7662 verbosity);
7663 if (err) {
7664 if (tagmsg_path)
7665 preserve_tagmsg = 1;
7666 goto done;
7669 err = got_ref_alloc(&ref, refname, tag_id);
7670 if (err) {
7671 if (tagmsg_path)
7672 preserve_tagmsg = 1;
7673 goto done;
7676 err = got_ref_write(ref, repo);
7677 if (err) {
7678 if (tagmsg_path)
7679 preserve_tagmsg = 1;
7680 goto done;
7683 err = got_object_id_str(&tag_id_str, tag_id);
7684 if (err) {
7685 if (tagmsg_path)
7686 preserve_tagmsg = 1;
7687 goto done;
7689 printf("Created tag %s\n", tag_id_str);
7690 done:
7691 if (preserve_tagmsg) {
7692 fprintf(stderr, "%s: tag message preserved in %s\n",
7693 getprogname(), tagmsg_path);
7694 } else if (tagmsg_path && unlink(tagmsg_path) == -1 && err == NULL)
7695 err = got_error_from_errno2("unlink", tagmsg_path);
7696 free(tag_id_str);
7697 if (ref)
7698 got_ref_close(ref);
7699 free(commit_id);
7700 free(commit_id_str);
7701 free(refname);
7702 free(tagmsg);
7703 free(tagmsg_path);
7704 got_ref_list_free(&refs);
7705 return err;
7708 static const struct got_error *
7709 cmd_tag(int argc, char *argv[])
7711 const struct got_error *error = NULL;
7712 struct got_repository *repo = NULL;
7713 struct got_worktree *worktree = NULL;
7714 char *cwd = NULL, *repo_path = NULL, *commit_id_str = NULL;
7715 char *gitconfig_path = NULL, *tagger = NULL, *keyword_idstr = NULL;
7716 char *allowed_signers = NULL, *revoked_signers = NULL, *editor = NULL;
7717 const char *signer_id = NULL;
7718 const char *tag_name = NULL, *commit_id_arg = NULL, *tagmsg = NULL;
7719 int ch, do_list = 0, verify_tags = 0, verbosity = 0;
7720 int *pack_fds = NULL;
7722 #ifndef PROFILE
7723 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
7724 "sendfd unveil", NULL) == -1)
7725 err(1, "pledge");
7726 #endif
7728 while ((ch = getopt(argc, argv, "c:lm:r:s:Vv")) != -1) {
7729 switch (ch) {
7730 case 'c':
7731 commit_id_arg = optarg;
7732 break;
7733 case 'l':
7734 do_list = 1;
7735 break;
7736 case 'm':
7737 tagmsg = optarg;
7738 break;
7739 case 'r':
7740 repo_path = realpath(optarg, NULL);
7741 if (repo_path == NULL) {
7742 error = got_error_from_errno2("realpath",
7743 optarg);
7744 goto done;
7746 got_path_strip_trailing_slashes(repo_path);
7747 break;
7748 case 's':
7749 signer_id = optarg;
7750 break;
7751 case 'V':
7752 verify_tags = 1;
7753 break;
7754 case 'v':
7755 if (verbosity < 0)
7756 verbosity = 0;
7757 else if (verbosity < 3)
7758 verbosity++;
7759 break;
7760 default:
7761 usage_tag();
7762 /* NOTREACHED */
7766 argc -= optind;
7767 argv += optind;
7769 if (do_list || verify_tags) {
7770 if (commit_id_arg != NULL)
7771 errx(1,
7772 "-c option can only be used when creating a tag");
7773 if (tagmsg) {
7774 if (do_list)
7775 option_conflict('l', 'm');
7776 else
7777 option_conflict('V', 'm');
7779 if (signer_id) {
7780 if (do_list)
7781 option_conflict('l', 's');
7782 else
7783 option_conflict('V', 's');
7785 if (argc > 1)
7786 usage_tag();
7787 } else if (argc != 1)
7788 usage_tag();
7790 if (argc == 1)
7791 tag_name = argv[0];
7793 cwd = getcwd(NULL, 0);
7794 if (cwd == NULL) {
7795 error = got_error_from_errno("getcwd");
7796 goto done;
7799 error = got_repo_pack_fds_open(&pack_fds);
7800 if (error != NULL)
7801 goto done;
7803 if (repo_path == NULL) {
7804 error = got_worktree_open(&worktree, cwd,
7805 GOT_WORKTREE_GOT_DIR);
7806 if (error && error->code != GOT_ERR_NOT_WORKTREE)
7807 goto done;
7808 else
7809 error = NULL;
7810 if (worktree) {
7811 repo_path =
7812 strdup(got_worktree_get_repo_path(worktree));
7813 if (repo_path == NULL)
7814 error = got_error_from_errno("strdup");
7815 if (error)
7816 goto done;
7817 } else {
7818 repo_path = strdup(cwd);
7819 if (repo_path == NULL) {
7820 error = got_error_from_errno("strdup");
7821 goto done;
7826 if (do_list || verify_tags) {
7827 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
7828 if (error != NULL)
7829 goto done;
7830 error = get_allowed_signers(&allowed_signers, repo, worktree);
7831 if (error)
7832 goto done;
7833 error = get_revoked_signers(&revoked_signers, repo, worktree);
7834 if (error)
7835 goto done;
7836 if (worktree) {
7837 /* Release work tree lock. */
7838 got_worktree_close(worktree);
7839 worktree = NULL;
7843 * Remove "cpath" promise unless needed for signature tmpfile
7844 * creation.
7846 if (verify_tags)
7847 got_sigs_apply_unveil();
7848 else {
7849 #ifndef PROFILE
7850 if (pledge("stdio rpath wpath flock proc exec sendfd "
7851 "unveil", NULL) == -1)
7852 err(1, "pledge");
7853 #endif
7855 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
7856 if (error)
7857 goto done;
7858 error = list_tags(repo, tag_name, verify_tags, allowed_signers,
7859 revoked_signers, verbosity);
7860 } else {
7861 error = get_gitconfig_path(&gitconfig_path);
7862 if (error)
7863 goto done;
7864 error = got_repo_open(&repo, repo_path, gitconfig_path,
7865 pack_fds);
7866 if (error != NULL)
7867 goto done;
7869 error = get_author(&tagger, repo, worktree);
7870 if (error)
7871 goto done;
7872 if (signer_id == NULL)
7873 signer_id = get_signer_id(repo, worktree);
7875 if (tagmsg == NULL) {
7876 error = get_editor(&editor);
7877 if (error)
7878 goto done;
7879 if (unveil(editor, "x") != 0) {
7880 error = got_error_from_errno2("unveil", editor);
7881 goto done;
7884 if (signer_id) {
7885 error = got_sigs_apply_unveil();
7886 if (error)
7887 goto done;
7889 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
7890 if (error)
7891 goto done;
7893 if (commit_id_arg == NULL) {
7894 struct got_reference *head_ref;
7895 struct got_object_id *commit_id;
7896 error = got_ref_open(&head_ref, repo,
7897 worktree ? got_worktree_get_head_ref_name(worktree)
7898 : GOT_REF_HEAD, 0);
7899 if (error)
7900 goto done;
7901 error = got_ref_resolve(&commit_id, repo, head_ref);
7902 got_ref_close(head_ref);
7903 if (error)
7904 goto done;
7905 error = got_object_id_str(&commit_id_str, commit_id);
7906 free(commit_id);
7907 if (error)
7908 goto done;
7909 } else {
7910 error = got_keyword_to_idstr(&keyword_idstr,
7911 commit_id_arg, repo, worktree);
7912 if (error != NULL)
7913 goto done;
7914 commit_id_str = keyword_idstr;
7917 if (worktree) {
7918 /* Release work tree lock. */
7919 got_worktree_close(worktree);
7920 worktree = NULL;
7923 error = add_tag(repo, tagger, tag_name,
7924 commit_id_str ? commit_id_str : commit_id_arg, tagmsg,
7925 signer_id, editor, verbosity);
7927 done:
7928 if (repo) {
7929 const struct got_error *close_err = got_repo_close(repo);
7930 if (error == NULL)
7931 error = close_err;
7933 if (worktree)
7934 got_worktree_close(worktree);
7935 if (pack_fds) {
7936 const struct got_error *pack_err =
7937 got_repo_pack_fds_close(pack_fds);
7938 if (error == NULL)
7939 error = pack_err;
7941 free(cwd);
7942 free(editor);
7943 free(repo_path);
7944 free(gitconfig_path);
7945 free(commit_id_str);
7946 free(tagger);
7947 free(allowed_signers);
7948 free(revoked_signers);
7949 return error;
7952 __dead static void
7953 usage_add(void)
7955 fprintf(stderr, "usage: %s add [-IR] path ...\n", getprogname());
7956 exit(1);
7959 static const struct got_error *
7960 add_progress(void *arg, unsigned char status, const char *path)
7962 while (path[0] == '/')
7963 path++;
7964 printf("%c %s\n", status, path);
7965 return NULL;
7968 static const struct got_error *
7969 cmd_add(int argc, char *argv[])
7971 const struct got_error *error = NULL;
7972 struct got_repository *repo = NULL;
7973 struct got_worktree *worktree = NULL;
7974 char *cwd = NULL;
7975 struct got_pathlist_head paths;
7976 struct got_pathlist_entry *pe;
7977 int ch, can_recurse = 0, no_ignores = 0;
7978 int *pack_fds = NULL;
7980 TAILQ_INIT(&paths);
7982 #ifndef PROFILE
7983 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
7984 NULL) == -1)
7985 err(1, "pledge");
7986 #endif
7988 while ((ch = getopt(argc, argv, "IR")) != -1) {
7989 switch (ch) {
7990 case 'I':
7991 no_ignores = 1;
7992 break;
7993 case 'R':
7994 can_recurse = 1;
7995 break;
7996 default:
7997 usage_add();
7998 /* NOTREACHED */
8002 argc -= optind;
8003 argv += optind;
8005 if (argc < 1)
8006 usage_add();
8008 cwd = getcwd(NULL, 0);
8009 if (cwd == NULL) {
8010 error = got_error_from_errno("getcwd");
8011 goto done;
8014 error = got_repo_pack_fds_open(&pack_fds);
8015 if (error != NULL)
8016 goto done;
8018 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
8019 if (error) {
8020 if (error->code == GOT_ERR_NOT_WORKTREE)
8021 error = wrap_not_worktree_error(error, "add", cwd);
8022 goto done;
8025 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
8026 NULL, pack_fds);
8027 if (error != NULL)
8028 goto done;
8030 error = apply_unveil(got_repo_get_path(repo), 1,
8031 got_worktree_get_root_path(worktree));
8032 if (error)
8033 goto done;
8035 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
8036 if (error)
8037 goto done;
8039 if (!can_recurse) {
8040 char *ondisk_path;
8041 struct stat sb;
8042 TAILQ_FOREACH(pe, &paths, entry) {
8043 if (asprintf(&ondisk_path, "%s/%s",
8044 got_worktree_get_root_path(worktree),
8045 pe->path) == -1) {
8046 error = got_error_from_errno("asprintf");
8047 goto done;
8049 if (lstat(ondisk_path, &sb) == -1) {
8050 if (errno == ENOENT) {
8051 free(ondisk_path);
8052 continue;
8054 error = got_error_from_errno2("lstat",
8055 ondisk_path);
8056 free(ondisk_path);
8057 goto done;
8059 free(ondisk_path);
8060 if (S_ISDIR(sb.st_mode)) {
8061 error = got_error_msg(GOT_ERR_BAD_PATH,
8062 "adding directories requires -R option");
8063 goto done;
8068 error = got_worktree_schedule_add(worktree, &paths, add_progress,
8069 NULL, repo, no_ignores);
8070 done:
8071 if (repo) {
8072 const struct got_error *close_err = got_repo_close(repo);
8073 if (error == NULL)
8074 error = close_err;
8076 if (worktree)
8077 got_worktree_close(worktree);
8078 if (pack_fds) {
8079 const struct got_error *pack_err =
8080 got_repo_pack_fds_close(pack_fds);
8081 if (error == NULL)
8082 error = pack_err;
8084 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
8085 free(cwd);
8086 return error;
8089 __dead static void
8090 usage_remove(void)
8092 fprintf(stderr, "usage: %s remove [-fkR] [-s status-codes] path ...\n",
8093 getprogname());
8094 exit(1);
8097 static const struct got_error *
8098 print_remove_status(void *arg, unsigned char status,
8099 unsigned char staged_status, const char *path)
8101 while (path[0] == '/')
8102 path++;
8103 if (status == GOT_STATUS_NONEXISTENT)
8104 return NULL;
8105 if (status == staged_status && (status == GOT_STATUS_DELETE))
8106 status = GOT_STATUS_NO_CHANGE;
8107 printf("%c%c %s\n", status, staged_status, path);
8108 return NULL;
8111 static const struct got_error *
8112 cmd_remove(int argc, char *argv[])
8114 const struct got_error *error = NULL;
8115 struct got_worktree *worktree = NULL;
8116 struct got_repository *repo = NULL;
8117 const char *status_codes = NULL;
8118 char *cwd = NULL;
8119 struct got_pathlist_head paths;
8120 struct got_pathlist_entry *pe;
8121 int ch, delete_local_mods = 0, can_recurse = 0, keep_on_disk = 0, i;
8122 int ignore_missing_paths = 0;
8123 int *pack_fds = NULL;
8125 TAILQ_INIT(&paths);
8127 #ifndef PROFILE
8128 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
8129 NULL) == -1)
8130 err(1, "pledge");
8131 #endif
8133 while ((ch = getopt(argc, argv, "fkRs:")) != -1) {
8134 switch (ch) {
8135 case 'f':
8136 delete_local_mods = 1;
8137 ignore_missing_paths = 1;
8138 break;
8139 case 'k':
8140 keep_on_disk = 1;
8141 break;
8142 case 'R':
8143 can_recurse = 1;
8144 break;
8145 case 's':
8146 for (i = 0; optarg[i] != '\0'; i++) {
8147 switch (optarg[i]) {
8148 case GOT_STATUS_MODIFY:
8149 delete_local_mods = 1;
8150 break;
8151 case GOT_STATUS_MISSING:
8152 ignore_missing_paths = 1;
8153 break;
8154 default:
8155 errx(1, "invalid status code '%c'",
8156 optarg[i]);
8159 status_codes = optarg;
8160 break;
8161 default:
8162 usage_remove();
8163 /* NOTREACHED */
8167 argc -= optind;
8168 argv += optind;
8170 if (argc < 1)
8171 usage_remove();
8173 cwd = getcwd(NULL, 0);
8174 if (cwd == NULL) {
8175 error = got_error_from_errno("getcwd");
8176 goto done;
8179 error = got_repo_pack_fds_open(&pack_fds);
8180 if (error != NULL)
8181 goto done;
8183 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
8184 if (error) {
8185 if (error->code == GOT_ERR_NOT_WORKTREE)
8186 error = wrap_not_worktree_error(error, "remove", cwd);
8187 goto done;
8190 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
8191 NULL, pack_fds);
8192 if (error)
8193 goto done;
8195 error = apply_unveil(got_repo_get_path(repo), 1,
8196 got_worktree_get_root_path(worktree));
8197 if (error)
8198 goto done;
8200 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
8201 if (error)
8202 goto done;
8204 if (!can_recurse) {
8205 char *ondisk_path;
8206 struct stat sb;
8207 TAILQ_FOREACH(pe, &paths, entry) {
8208 if (asprintf(&ondisk_path, "%s/%s",
8209 got_worktree_get_root_path(worktree),
8210 pe->path) == -1) {
8211 error = got_error_from_errno("asprintf");
8212 goto done;
8214 if (lstat(ondisk_path, &sb) == -1) {
8215 if (errno == ENOENT) {
8216 free(ondisk_path);
8217 continue;
8219 error = got_error_from_errno2("lstat",
8220 ondisk_path);
8221 free(ondisk_path);
8222 goto done;
8224 free(ondisk_path);
8225 if (S_ISDIR(sb.st_mode)) {
8226 error = got_error_msg(GOT_ERR_BAD_PATH,
8227 "removing directories requires -R option");
8228 goto done;
8233 error = got_worktree_schedule_delete(worktree, &paths,
8234 delete_local_mods, status_codes, print_remove_status, NULL,
8235 repo, keep_on_disk, ignore_missing_paths);
8236 done:
8237 if (repo) {
8238 const struct got_error *close_err = got_repo_close(repo);
8239 if (error == NULL)
8240 error = close_err;
8242 if (worktree)
8243 got_worktree_close(worktree);
8244 if (pack_fds) {
8245 const struct got_error *pack_err =
8246 got_repo_pack_fds_close(pack_fds);
8247 if (error == NULL)
8248 error = pack_err;
8250 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
8251 free(cwd);
8252 return error;
8255 __dead static void
8256 usage_patch(void)
8258 fprintf(stderr, "usage: %s patch [-nR] [-c commit] [-p strip-count] "
8259 "[patchfile]\n", getprogname());
8260 exit(1);
8263 static const struct got_error *
8264 patch_from_stdin(int *patchfd)
8266 const struct got_error *err = NULL;
8267 ssize_t r;
8268 char buf[BUFSIZ];
8269 sig_t sighup, sigint, sigquit;
8271 *patchfd = got_opentempfd();
8272 if (*patchfd == -1)
8273 return got_error_from_errno("got_opentempfd");
8275 sighup = signal(SIGHUP, SIG_DFL);
8276 sigint = signal(SIGINT, SIG_DFL);
8277 sigquit = signal(SIGQUIT, SIG_DFL);
8279 for (;;) {
8280 r = read(0, buf, sizeof(buf));
8281 if (r == -1) {
8282 err = got_error_from_errno("read");
8283 break;
8285 if (r == 0)
8286 break;
8287 if (write(*patchfd, buf, r) == -1) {
8288 err = got_error_from_errno("write");
8289 break;
8293 signal(SIGHUP, sighup);
8294 signal(SIGINT, sigint);
8295 signal(SIGQUIT, sigquit);
8297 if (err == NULL && lseek(*patchfd, 0, SEEK_SET) == -1)
8298 err = got_error_from_errno("lseek");
8300 if (err != NULL) {
8301 close(*patchfd);
8302 *patchfd = -1;
8305 return err;
8308 struct got_patch_progress_arg {
8309 int did_something;
8310 int conflicts;
8311 int rejects;
8314 static const struct got_error *
8315 patch_progress(void *arg, const char *old, const char *new,
8316 unsigned char status, const struct got_error *error, int old_from,
8317 int old_lines, int new_from, int new_lines, int offset,
8318 int ws_mangled, const struct got_error *hunk_err)
8320 const char *path = new == NULL ? old : new;
8321 struct got_patch_progress_arg *a = arg;
8323 while (*path == '/')
8324 path++;
8326 if (status != GOT_STATUS_NO_CHANGE &&
8327 status != 0 /* per-hunk progress */) {
8328 printf("%c %s\n", status, path);
8329 a->did_something = 1;
8332 if (hunk_err == NULL) {
8333 if (status == GOT_STATUS_CANNOT_UPDATE)
8334 a->rejects++;
8335 else if (status == GOT_STATUS_CONFLICT)
8336 a->conflicts++;
8339 if (error != NULL)
8340 fprintf(stderr, "%s: %s\n", getprogname(), error->msg);
8342 if (offset != 0 || hunk_err != NULL || ws_mangled) {
8343 printf("@@ -%d,%d +%d,%d @@ ", old_from,
8344 old_lines, new_from, new_lines);
8345 if (hunk_err != NULL)
8346 printf("%s\n", hunk_err->msg);
8347 else if (offset != 0)
8348 printf("applied with offset %d\n", offset);
8349 else
8350 printf("hunk contains mangled whitespace\n");
8353 return NULL;
8356 static void
8357 print_patch_progress_stats(struct got_patch_progress_arg *ppa)
8359 if (!ppa->did_something)
8360 return;
8362 if (ppa->conflicts > 0)
8363 printf("Files with merge conflicts: %d\n", ppa->conflicts);
8365 if (ppa->rejects > 0) {
8366 printf("Files where patch failed to apply: %d\n",
8367 ppa->rejects);
8371 static const struct got_error *
8372 cmd_patch(int argc, char *argv[])
8374 const struct got_error *error = NULL, *close_error = NULL;
8375 struct got_worktree *worktree = NULL;
8376 struct got_repository *repo = NULL;
8377 struct got_reflist_head refs;
8378 struct got_object_id *commit_id = NULL;
8379 const char *commit_id_str = NULL;
8380 struct stat sb;
8381 const char *errstr;
8382 char *cwd = NULL, *keyword_idstr = NULL;
8383 int ch, nop = 0, strip = -1, reverse = 0;
8384 int patchfd;
8385 int *pack_fds = NULL;
8386 struct got_patch_progress_arg ppa;
8388 TAILQ_INIT(&refs);
8390 #ifndef PROFILE
8391 if (pledge("stdio rpath wpath cpath fattr proc exec sendfd flock "
8392 "unveil", NULL) == -1)
8393 err(1, "pledge");
8394 #endif
8396 while ((ch = getopt(argc, argv, "c:np:R")) != -1) {
8397 switch (ch) {
8398 case 'c':
8399 commit_id_str = optarg;
8400 break;
8401 case 'n':
8402 nop = 1;
8403 break;
8404 case 'p':
8405 strip = strtonum(optarg, 0, INT_MAX, &errstr);
8406 if (errstr != NULL)
8407 errx(1, "pathname strip count is %s: %s",
8408 errstr, optarg);
8409 break;
8410 case 'R':
8411 reverse = 1;
8412 break;
8413 default:
8414 usage_patch();
8415 /* NOTREACHED */
8419 argc -= optind;
8420 argv += optind;
8422 if (argc == 0) {
8423 error = patch_from_stdin(&patchfd);
8424 if (error)
8425 return error;
8426 } else if (argc == 1) {
8427 patchfd = open(argv[0], O_RDONLY);
8428 if (patchfd == -1) {
8429 error = got_error_from_errno2("open", argv[0]);
8430 return error;
8432 if (fstat(patchfd, &sb) == -1) {
8433 error = got_error_from_errno2("fstat", argv[0]);
8434 goto done;
8436 if (!S_ISREG(sb.st_mode)) {
8437 error = got_error_path(argv[0], GOT_ERR_BAD_FILETYPE);
8438 goto done;
8440 } else
8441 usage_patch();
8443 if ((cwd = getcwd(NULL, 0)) == NULL) {
8444 error = got_error_from_errno("getcwd");
8445 goto done;
8448 error = got_repo_pack_fds_open(&pack_fds);
8449 if (error != NULL)
8450 goto done;
8452 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
8453 if (error != NULL)
8454 goto done;
8456 const char *repo_path = got_worktree_get_repo_path(worktree);
8457 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
8458 if (error != NULL)
8459 goto done;
8461 error = apply_unveil(got_repo_get_path(repo), 0,
8462 got_worktree_get_root_path(worktree));
8463 if (error != NULL)
8464 goto done;
8466 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
8467 if (error)
8468 goto done;
8470 if (commit_id_str != NULL) {
8471 error = got_keyword_to_idstr(&keyword_idstr, commit_id_str,
8472 repo, worktree);
8473 if (error != NULL)
8474 goto done;
8476 error = got_repo_match_object_id(&commit_id, NULL,
8477 keyword_idstr != NULL ? keyword_idstr : commit_id_str,
8478 GOT_OBJ_TYPE_COMMIT, &refs, repo);
8479 if (error)
8480 goto done;
8483 memset(&ppa, 0, sizeof(ppa));
8484 error = got_patch(patchfd, worktree, repo, nop, strip, reverse,
8485 commit_id, patch_progress, &ppa, check_cancelled, NULL);
8486 print_patch_progress_stats(&ppa);
8487 done:
8488 got_ref_list_free(&refs);
8489 free(keyword_idstr);
8490 free(commit_id);
8491 if (repo) {
8492 close_error = got_repo_close(repo);
8493 if (error == NULL)
8494 error = close_error;
8496 if (worktree != NULL) {
8497 close_error = got_worktree_close(worktree);
8498 if (error == NULL)
8499 error = close_error;
8501 if (pack_fds) {
8502 const struct got_error *pack_err =
8503 got_repo_pack_fds_close(pack_fds);
8504 if (error == NULL)
8505 error = pack_err;
8507 free(cwd);
8508 return error;
8511 __dead static void
8512 usage_revert(void)
8514 fprintf(stderr, "usage: %s revert [-pR] [-F response-script] path ...\n",
8515 getprogname());
8516 exit(1);
8519 static const struct got_error *
8520 revert_progress(void *arg, unsigned char status, const char *path)
8522 if (status == GOT_STATUS_UNVERSIONED)
8523 return NULL;
8525 while (path[0] == '/')
8526 path++;
8527 printf("%c %s\n", status, path);
8528 return NULL;
8531 struct choose_patch_arg {
8532 FILE *patch_script_file;
8533 const char *action;
8536 static const struct got_error *
8537 show_change(unsigned char status, const char *path, FILE *patch_file, int n,
8538 int nchanges, const char *action)
8540 const struct got_error *err;
8541 char *line = NULL;
8542 size_t linesize = 0;
8543 ssize_t linelen;
8545 switch (status) {
8546 case GOT_STATUS_ADD:
8547 printf("A %s\n%s this addition? [y/n] ", path, action);
8548 break;
8549 case GOT_STATUS_DELETE:
8550 printf("D %s\n%s this deletion? [y/n] ", path, action);
8551 break;
8552 case GOT_STATUS_MODIFY:
8553 if (fseek(patch_file, 0L, SEEK_SET) == -1)
8554 return got_error_from_errno("fseek");
8555 printf(GOT_COMMIT_SEP_STR);
8556 while ((linelen = getline(&line, &linesize, patch_file)) != -1)
8557 printf("%s", line);
8558 if (linelen == -1 && ferror(patch_file)) {
8559 err = got_error_from_errno("getline");
8560 free(line);
8561 return err;
8563 free(line);
8564 printf(GOT_COMMIT_SEP_STR);
8565 printf("M %s (change %d of %d)\n%s this change? [y/n/q] ",
8566 path, n, nchanges, action);
8567 break;
8568 default:
8569 return got_error_path(path, GOT_ERR_FILE_STATUS);
8572 fflush(stdout);
8573 return NULL;
8576 static const struct got_error *
8577 choose_patch(int *choice, void *arg, unsigned char status, const char *path,
8578 FILE *patch_file, int n, int nchanges)
8580 const struct got_error *err = NULL;
8581 char *line = NULL;
8582 size_t linesize = 0;
8583 ssize_t linelen;
8584 int resp = ' ';
8585 struct choose_patch_arg *a = arg;
8587 *choice = GOT_PATCH_CHOICE_NONE;
8589 if (a->patch_script_file) {
8590 char *nl;
8591 err = show_change(status, path, patch_file, n, nchanges,
8592 a->action);
8593 if (err)
8594 return err;
8595 linelen = getline(&line, &linesize, a->patch_script_file);
8596 if (linelen == -1) {
8597 if (ferror(a->patch_script_file))
8598 return got_error_from_errno("getline");
8599 return NULL;
8601 nl = strchr(line, '\n');
8602 if (nl)
8603 *nl = '\0';
8604 if (strcmp(line, "y") == 0) {
8605 *choice = GOT_PATCH_CHOICE_YES;
8606 printf("y\n");
8607 } else if (strcmp(line, "n") == 0) {
8608 *choice = GOT_PATCH_CHOICE_NO;
8609 printf("n\n");
8610 } else if (strcmp(line, "q") == 0 &&
8611 status == GOT_STATUS_MODIFY) {
8612 *choice = GOT_PATCH_CHOICE_QUIT;
8613 printf("q\n");
8614 } else
8615 printf("invalid response '%s'\n", line);
8616 free(line);
8617 return NULL;
8620 while (resp != 'y' && resp != 'n' && resp != 'q') {
8621 err = show_change(status, path, patch_file, n, nchanges,
8622 a->action);
8623 if (err)
8624 return err;
8625 resp = getchar();
8626 if (resp == '\n')
8627 resp = getchar();
8628 if (status == GOT_STATUS_MODIFY) {
8629 if (resp != 'y' && resp != 'n' && resp != 'q') {
8630 printf("invalid response '%c'\n", resp);
8631 resp = ' ';
8633 } else if (resp != 'y' && resp != 'n') {
8634 printf("invalid response '%c'\n", resp);
8635 resp = ' ';
8639 if (resp == 'y')
8640 *choice = GOT_PATCH_CHOICE_YES;
8641 else if (resp == 'n')
8642 *choice = GOT_PATCH_CHOICE_NO;
8643 else if (resp == 'q' && status == GOT_STATUS_MODIFY)
8644 *choice = GOT_PATCH_CHOICE_QUIT;
8646 return NULL;
8649 struct wt_commitable_path_arg {
8650 struct got_pathlist_head *commit_paths;
8651 int *has_changes;
8655 * Shortcut work tree status callback to determine if the set of paths scanned
8656 * has at least one versioned path that is being modified and, if not NULL, is
8657 * in the arg->commit_paths list. Set arg and return GOT_ERR_FILE_MODIFIED as
8658 * soon as a path is passed with a status that satisfies this criteria.
8660 static const struct got_error *
8661 worktree_has_commitable_path(void *arg, unsigned char status,
8662 unsigned char staged_status, const char *path,
8663 struct got_object_id *blob_id, struct got_object_id *staged_blob_id,
8664 struct got_object_id *commit_id, int dirfd, const char *de_name)
8666 struct wt_commitable_path_arg *a = arg;
8668 if (status == staged_status && (status == GOT_STATUS_DELETE))
8669 status = GOT_STATUS_NO_CHANGE;
8671 if (!(status == GOT_STATUS_NO_CHANGE ||
8672 status == GOT_STATUS_UNVERSIONED) ||
8673 staged_status != GOT_STATUS_NO_CHANGE) {
8674 if (a->commit_paths != NULL) {
8675 struct got_pathlist_entry *pe;
8677 TAILQ_FOREACH(pe, a->commit_paths, entry) {
8678 if (strncmp(path, pe->path,
8679 pe->path_len) == 0) {
8680 *a->has_changes = 1;
8681 break;
8684 } else
8685 *a->has_changes = 1;
8687 if (*a->has_changes)
8688 return got_error(GOT_ERR_FILE_MODIFIED);
8691 return NULL;
8695 * Check that the changeset of the commit identified by id is
8696 * comprised of at least one modified path that is being committed.
8698 static const struct got_error *
8699 commit_path_changed_in_worktree(struct wt_commitable_path_arg *wcpa,
8700 struct got_object_id *id, struct got_worktree *worktree,
8701 struct got_repository *repo)
8703 const struct got_error *err;
8704 struct got_pathlist_head paths;
8705 struct got_commit_object *commit = NULL, *pcommit = NULL;
8706 struct got_tree_object *tree = NULL, *ptree = NULL;
8707 struct got_object_qid *pid;
8709 TAILQ_INIT(&paths);
8711 err = got_object_open_as_commit(&commit, repo, id);
8712 if (err)
8713 goto done;
8715 err = got_object_open_as_tree(&tree, repo,
8716 got_object_commit_get_tree_id(commit));
8717 if (err)
8718 goto done;
8720 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
8721 if (pid != NULL) {
8722 err = got_object_open_as_commit(&pcommit, repo, &pid->id);
8723 if (err)
8724 goto done;
8726 err = got_object_open_as_tree(&ptree, repo,
8727 got_object_commit_get_tree_id(pcommit));
8728 if (err)
8729 goto done;
8732 err = got_diff_tree(ptree, tree, NULL, NULL, -1, -1, "", "", repo,
8733 got_diff_tree_collect_changed_paths, &paths, 0);
8734 if (err)
8735 goto done;
8737 err = got_worktree_status(worktree, &paths, repo, 0,
8738 worktree_has_commitable_path, wcpa, check_cancelled, NULL);
8739 if (err && err->code == GOT_ERR_FILE_MODIFIED) {
8741 * At least one changed path in the referenced commit is
8742 * modified in the work tree, that's all we need to know!
8744 err = NULL;
8747 done:
8748 got_pathlist_free(&paths, GOT_PATHLIST_FREE_ALL);
8749 if (commit)
8750 got_object_commit_close(commit);
8751 if (pcommit)
8752 got_object_commit_close(pcommit);
8753 if (tree)
8754 got_object_tree_close(tree);
8755 if (ptree)
8756 got_object_tree_close(ptree);
8757 return err;
8761 * Remove any "logmsg" reference comprised entirely of paths that have
8762 * been reverted in this work tree. If any path in the logmsg ref changeset
8763 * remains in a changed state in the worktree, do not remove the reference.
8765 static const struct got_error *
8766 rm_logmsg_ref(struct got_worktree *worktree, struct got_repository *repo)
8768 const struct got_error *err;
8769 struct got_reflist_head refs;
8770 struct got_reflist_entry *re;
8771 struct got_commit_object *commit = NULL;
8772 struct got_object_id *commit_id = NULL;
8773 struct wt_commitable_path_arg wcpa;
8774 char *uuidstr = NULL;
8776 TAILQ_INIT(&refs);
8778 err = got_worktree_get_uuid(&uuidstr, worktree);
8779 if (err)
8780 goto done;
8782 err = got_ref_list(&refs, repo, "refs/got/worktree",
8783 got_ref_cmp_by_name, repo);
8784 if (err)
8785 goto done;
8787 TAILQ_FOREACH(re, &refs, entry) {
8788 const char *refname;
8789 int has_changes = 0;
8791 refname = got_ref_get_name(re->ref);
8793 if (!strncmp(refname, GOT_WORKTREE_CHERRYPICK_REF_PREFIX,
8794 GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN))
8795 refname += GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN + 1;
8796 else if (!strncmp(refname, GOT_WORKTREE_BACKOUT_REF_PREFIX,
8797 GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN))
8798 refname += GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN + 1;
8799 else
8800 continue;
8802 if (strncmp(refname, uuidstr, GOT_WORKTREE_UUID_STRLEN) == 0)
8803 refname += GOT_WORKTREE_UUID_STRLEN + 1; /* skip '-' */
8804 else
8805 continue;
8807 err = got_repo_match_object_id(&commit_id, NULL, refname,
8808 GOT_OBJ_TYPE_COMMIT, NULL, repo);
8809 if (err)
8810 goto done;
8812 err = got_object_open_as_commit(&commit, repo, commit_id);
8813 if (err)
8814 goto done;
8816 wcpa.commit_paths = NULL;
8817 wcpa.has_changes = &has_changes;
8819 err = commit_path_changed_in_worktree(&wcpa, commit_id,
8820 worktree, repo);
8821 if (err)
8822 goto done;
8824 if (!has_changes) {
8825 err = got_ref_delete(re->ref, repo);
8826 if (err)
8827 goto done;
8830 got_object_commit_close(commit);
8831 commit = NULL;
8832 free(commit_id);
8833 commit_id = NULL;
8836 done:
8837 free(uuidstr);
8838 free(commit_id);
8839 got_ref_list_free(&refs);
8840 if (commit)
8841 got_object_commit_close(commit);
8842 return err;
8845 static const struct got_error *
8846 cmd_revert(int argc, char *argv[])
8848 const struct got_error *error = NULL;
8849 struct got_worktree *worktree = NULL;
8850 struct got_repository *repo = NULL;
8851 char *cwd = NULL, *path = NULL;
8852 struct got_pathlist_head paths;
8853 struct got_pathlist_entry *pe;
8854 int ch, can_recurse = 0, pflag = 0;
8855 FILE *patch_script_file = NULL;
8856 const char *patch_script_path = NULL;
8857 struct choose_patch_arg cpa;
8858 int *pack_fds = NULL;
8860 TAILQ_INIT(&paths);
8862 #ifndef PROFILE
8863 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
8864 "unveil", NULL) == -1)
8865 err(1, "pledge");
8866 #endif
8868 while ((ch = getopt(argc, argv, "F:pR")) != -1) {
8869 switch (ch) {
8870 case 'F':
8871 patch_script_path = optarg;
8872 break;
8873 case 'p':
8874 pflag = 1;
8875 break;
8876 case 'R':
8877 can_recurse = 1;
8878 break;
8879 default:
8880 usage_revert();
8881 /* NOTREACHED */
8885 argc -= optind;
8886 argv += optind;
8888 if (argc < 1)
8889 usage_revert();
8890 if (patch_script_path && !pflag)
8891 errx(1, "-F option can only be used together with -p option");
8893 cwd = getcwd(NULL, 0);
8894 if (cwd == NULL) {
8895 error = got_error_from_errno("getcwd");
8896 goto done;
8899 error = got_repo_pack_fds_open(&pack_fds);
8900 if (error != NULL)
8901 goto done;
8903 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
8904 if (error) {
8905 if (error->code == GOT_ERR_NOT_WORKTREE)
8906 error = wrap_not_worktree_error(error, "revert", cwd);
8907 goto done;
8910 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
8911 NULL, pack_fds);
8912 if (error != NULL)
8913 goto done;
8915 if (patch_script_path) {
8916 patch_script_file = fopen(patch_script_path, "re");
8917 if (patch_script_file == NULL) {
8918 error = got_error_from_errno2("fopen",
8919 patch_script_path);
8920 goto done;
8925 * XXX "c" perm needed on repo dir to delete merge references.
8927 error = apply_unveil(got_repo_get_path(repo), 0,
8928 got_worktree_get_root_path(worktree));
8929 if (error)
8930 goto done;
8932 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
8933 if (error)
8934 goto done;
8936 if (!can_recurse) {
8937 char *ondisk_path;
8938 struct stat sb;
8939 TAILQ_FOREACH(pe, &paths, entry) {
8940 if (asprintf(&ondisk_path, "%s/%s",
8941 got_worktree_get_root_path(worktree),
8942 pe->path) == -1) {
8943 error = got_error_from_errno("asprintf");
8944 goto done;
8946 if (lstat(ondisk_path, &sb) == -1) {
8947 if (errno == ENOENT) {
8948 free(ondisk_path);
8949 continue;
8951 error = got_error_from_errno2("lstat",
8952 ondisk_path);
8953 free(ondisk_path);
8954 goto done;
8956 free(ondisk_path);
8957 if (S_ISDIR(sb.st_mode)) {
8958 error = got_error_msg(GOT_ERR_BAD_PATH,
8959 "reverting directories requires -R option");
8960 goto done;
8965 cpa.patch_script_file = patch_script_file;
8966 cpa.action = "revert";
8967 error = got_worktree_revert(worktree, &paths, revert_progress, NULL,
8968 pflag ? choose_patch : NULL, &cpa, repo);
8970 error = rm_logmsg_ref(worktree, repo);
8971 done:
8972 if (patch_script_file && fclose(patch_script_file) == EOF &&
8973 error == NULL)
8974 error = got_error_from_errno2("fclose", patch_script_path);
8975 if (repo) {
8976 const struct got_error *close_err = got_repo_close(repo);
8977 if (error == NULL)
8978 error = close_err;
8980 if (worktree)
8981 got_worktree_close(worktree);
8982 if (pack_fds) {
8983 const struct got_error *pack_err =
8984 got_repo_pack_fds_close(pack_fds);
8985 if (error == NULL)
8986 error = pack_err;
8988 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
8989 free(path);
8990 free(cwd);
8991 return error;
8994 __dead static void
8995 usage_commit(void)
8997 fprintf(stderr, "usage: %s commit [-CNnS] [-A author] [-F path] "
8998 "[-m message] [path ...]\n", getprogname());
8999 exit(1);
9002 struct collect_commit_logmsg_arg {
9003 const char *cmdline_log;
9004 const char *prepared_log;
9005 const char *merged_log;
9006 int non_interactive;
9007 const char *editor;
9008 const char *worktree_path;
9009 const char *branch_name;
9010 const char *repo_path;
9011 char *logmsg_path;
9015 static const struct got_error *
9016 read_prepared_logmsg(char **logmsg, const char *path)
9018 const struct got_error *err = NULL;
9019 FILE *f = NULL;
9020 struct stat sb;
9021 size_t r;
9023 *logmsg = NULL;
9024 memset(&sb, 0, sizeof(sb));
9026 f = fopen(path, "re");
9027 if (f == NULL)
9028 return got_error_from_errno2("fopen", path);
9030 if (fstat(fileno(f), &sb) == -1) {
9031 err = got_error_from_errno2("fstat", path);
9032 goto done;
9034 if (sb.st_size == 0) {
9035 err = got_error(GOT_ERR_COMMIT_MSG_EMPTY);
9036 goto done;
9039 *logmsg = malloc(sb.st_size + 1);
9040 if (*logmsg == NULL) {
9041 err = got_error_from_errno("malloc");
9042 goto done;
9045 r = fread(*logmsg, 1, sb.st_size, f);
9046 if (r != sb.st_size) {
9047 if (ferror(f))
9048 err = got_error_from_errno2("fread", path);
9049 else
9050 err = got_error(GOT_ERR_IO);
9051 goto done;
9053 (*logmsg)[sb.st_size] = '\0';
9054 done:
9055 if (fclose(f) == EOF && err == NULL)
9056 err = got_error_from_errno2("fclose", path);
9057 if (err) {
9058 free(*logmsg);
9059 *logmsg = NULL;
9061 return err;
9064 static const struct got_error *
9065 collect_commit_logmsg(struct got_pathlist_head *commitable_paths,
9066 const char *diff_path, char **logmsg, void *arg)
9068 char *initial_content = NULL;
9069 struct got_pathlist_entry *pe;
9070 const struct got_error *err = NULL;
9071 char *template = NULL;
9072 char *prepared_msg = NULL, *merged_msg = NULL;
9073 struct collect_commit_logmsg_arg *a = arg;
9074 int initial_content_len;
9075 int fd = -1;
9076 size_t len;
9078 /* if a message was specified on the command line, just use it */
9079 if (a->cmdline_log != NULL && *a->cmdline_log != '\0') {
9080 len = strlen(a->cmdline_log) + 1;
9081 *logmsg = malloc(len + 1);
9082 if (*logmsg == NULL)
9083 return got_error_from_errno("malloc");
9084 strlcpy(*logmsg, a->cmdline_log, len);
9085 return NULL;
9086 } else if (a->prepared_log != NULL && a->non_interactive)
9087 return read_prepared_logmsg(logmsg, a->prepared_log);
9089 if (asprintf(&template, "%s/logmsg", a->worktree_path) == -1)
9090 return got_error_from_errno("asprintf");
9092 err = got_opentemp_named_fd(&a->logmsg_path, &fd, template, "");
9093 if (err)
9094 goto done;
9096 if (a->prepared_log) {
9097 err = read_prepared_logmsg(&prepared_msg, a->prepared_log);
9098 if (err)
9099 goto done;
9100 } else if (a->merged_log) {
9101 err = read_prepared_logmsg(&merged_msg, a->merged_log);
9102 if (err)
9103 goto done;
9106 initial_content_len = asprintf(&initial_content,
9107 "%s%s\n# changes to be committed on branch %s:\n",
9108 prepared_msg ? prepared_msg : "",
9109 merged_msg ? merged_msg : "", a->branch_name);
9110 if (initial_content_len == -1) {
9111 err = got_error_from_errno("asprintf");
9112 goto done;
9115 if (write(fd, initial_content, initial_content_len) == -1) {
9116 err = got_error_from_errno2("write", a->logmsg_path);
9117 goto done;
9120 TAILQ_FOREACH(pe, commitable_paths, entry) {
9121 struct got_commitable *ct = pe->data;
9122 dprintf(fd, "# %c %s\n",
9123 got_commitable_get_status(ct),
9124 got_commitable_get_path(ct));
9127 if (diff_path) {
9128 dprintf(fd, "# detailed changes can be viewed in %s\n",
9129 diff_path);
9132 if (close(fd) == -1) {
9133 err = got_error_from_errno2("close", a->logmsg_path);
9134 goto done;
9136 fd = -1;
9138 err = edit_logmsg(logmsg, a->editor, a->logmsg_path, initial_content,
9139 initial_content_len, a->prepared_log ? 0 : 1);
9140 done:
9141 free(initial_content);
9142 free(template);
9143 free(prepared_msg);
9144 free(merged_msg);
9146 if (fd != -1 && close(fd) == -1 && err == NULL)
9147 err = got_error_from_errno2("close", a->logmsg_path);
9148 if (err) {
9149 free(*logmsg);
9150 *logmsg = NULL;
9152 return err;
9155 static const struct got_error *
9156 cat_logmsg(FILE *f, struct got_commit_object *commit, const char *idstr,
9157 const char *type, int has_content)
9159 const struct got_error *err = NULL;
9160 char *logmsg = NULL;
9162 err = got_object_commit_get_logmsg(&logmsg, commit);
9163 if (err)
9164 return err;
9166 if (fprintf(f, "%s# log message of %s commit %s:%s",
9167 has_content ? "\n" : "", type, idstr, logmsg) < 0)
9168 err = got_ferror(f, GOT_ERR_IO);
9170 free(logmsg);
9171 return err;
9175 * Lookup "logmsg" references of backed-out and cherrypicked commits
9176 * belonging to the current work tree. If found, and the worktree has
9177 * at least one modified file that was changed in the referenced commit,
9178 * add its log message to a new temporary file at *logmsg_path.
9179 * Add all refs found to matched_refs to be scheduled for removal on
9180 * successful commit.
9182 static const struct got_error *
9183 lookup_logmsg_ref(char **logmsg_path, struct got_pathlist_head *paths,
9184 struct got_reflist_head *matched_refs, struct got_worktree *worktree,
9185 struct got_repository *repo)
9187 const struct got_error *err;
9188 struct got_commit_object *commit = NULL;
9189 struct got_object_id *id = NULL;
9190 struct got_reflist_head refs;
9191 struct got_reflist_entry *re, *re_match;
9192 FILE *f = NULL;
9193 char *uuidstr = NULL;
9194 int added_logmsg = 0;
9196 TAILQ_INIT(&refs);
9198 *logmsg_path = NULL;
9200 err = got_worktree_get_uuid(&uuidstr, worktree);
9201 if (err)
9202 goto done;
9204 err = got_ref_list(&refs, repo, "refs/got/worktree",
9205 got_ref_cmp_by_name, repo);
9206 if (err)
9207 goto done;
9209 TAILQ_FOREACH(re, &refs, entry) {
9210 const char *refname, *type;
9211 struct wt_commitable_path_arg wcpa;
9212 int add_logmsg = 0;
9214 refname = got_ref_get_name(re->ref);
9216 if (strncmp(refname, GOT_WORKTREE_CHERRYPICK_REF_PREFIX,
9217 GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN) == 0) {
9218 refname += GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN + 1;
9219 type = "cherrypicked";
9220 } else if (strncmp(refname, GOT_WORKTREE_BACKOUT_REF_PREFIX,
9221 GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN) == 0) {
9222 refname += GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN + 1;
9223 type = "backed-out";
9224 } else
9225 continue;
9227 if (strncmp(refname, uuidstr, GOT_WORKTREE_UUID_STRLEN) == 0)
9228 refname += GOT_WORKTREE_UUID_STRLEN + 1; /* skip '-' */
9229 else
9230 continue;
9232 err = got_repo_match_object_id(&id, NULL, refname,
9233 GOT_OBJ_TYPE_COMMIT, NULL, repo);
9234 if (err)
9235 goto done;
9237 err = got_object_open_as_commit(&commit, repo, id);
9238 if (err)
9239 goto done;
9241 wcpa.commit_paths = paths;
9242 wcpa.has_changes = &add_logmsg;
9244 err = commit_path_changed_in_worktree(&wcpa, id,
9245 worktree, repo);
9246 if (err)
9247 goto done;
9249 if (add_logmsg) {
9250 if (f == NULL) {
9251 err = got_opentemp_named(logmsg_path, &f,
9252 "got-commit-logmsg", "");
9253 if (err)
9254 goto done;
9256 err = cat_logmsg(f, commit, refname, type,
9257 added_logmsg);
9258 if (err)
9259 goto done;
9260 if (!added_logmsg)
9261 ++added_logmsg;
9263 err = got_reflist_entry_dup(&re_match, re);
9264 if (err)
9265 goto done;
9266 TAILQ_INSERT_HEAD(matched_refs, re_match, entry);
9269 got_object_commit_close(commit);
9270 commit = NULL;
9271 free(id);
9272 id = NULL;
9275 done:
9276 free(id);
9277 free(uuidstr);
9278 got_ref_list_free(&refs);
9279 if (commit)
9280 got_object_commit_close(commit);
9281 if (f && fclose(f) == EOF && err == NULL)
9282 err = got_error_from_errno("fclose");
9283 if (!added_logmsg) {
9284 if (*logmsg_path && unlink(*logmsg_path) != 0 && err == NULL)
9285 err = got_error_from_errno2("unlink", *logmsg_path);
9286 *logmsg_path = NULL;
9288 return err;
9291 static const struct got_error *
9292 cmd_commit(int argc, char *argv[])
9294 const struct got_error *error = NULL;
9295 struct got_worktree *worktree = NULL;
9296 struct got_repository *repo = NULL;
9297 char *cwd = NULL, *id_str = NULL;
9298 struct got_object_id *id = NULL;
9299 const char *logmsg = NULL;
9300 char *prepared_logmsg = NULL, *merged_logmsg = NULL;
9301 struct collect_commit_logmsg_arg cl_arg;
9302 const char *author = NULL;
9303 char *gitconfig_path = NULL, *editor = NULL, *committer = NULL;
9304 int ch, rebase_in_progress, histedit_in_progress, preserve_logmsg = 0;
9305 int allow_bad_symlinks = 0, non_interactive = 0, merge_in_progress = 0;
9306 int show_diff = 1, commit_conflicts = 0;
9307 struct got_pathlist_head paths;
9308 struct got_reflist_head refs;
9309 struct got_reflist_entry *re;
9310 int *pack_fds = NULL;
9312 TAILQ_INIT(&refs);
9313 TAILQ_INIT(&paths);
9314 cl_arg.logmsg_path = NULL;
9316 #ifndef PROFILE
9317 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
9318 "unveil", NULL) == -1)
9319 err(1, "pledge");
9320 #endif
9322 while ((ch = getopt(argc, argv, "A:CF:m:NnS")) != -1) {
9323 switch (ch) {
9324 case 'A':
9325 author = optarg;
9326 error = valid_author(author);
9327 if (error)
9328 return error;
9329 break;
9330 case 'C':
9331 commit_conflicts = 1;
9332 break;
9333 case 'F':
9334 if (logmsg != NULL)
9335 option_conflict('F', 'm');
9336 prepared_logmsg = realpath(optarg, NULL);
9337 if (prepared_logmsg == NULL)
9338 return got_error_from_errno2("realpath",
9339 optarg);
9340 break;
9341 case 'm':
9342 if (prepared_logmsg)
9343 option_conflict('m', 'F');
9344 logmsg = optarg;
9345 break;
9346 case 'N':
9347 non_interactive = 1;
9348 break;
9349 case 'n':
9350 show_diff = 0;
9351 break;
9352 case 'S':
9353 allow_bad_symlinks = 1;
9354 break;
9355 default:
9356 usage_commit();
9357 /* NOTREACHED */
9361 argc -= optind;
9362 argv += optind;
9364 cwd = getcwd(NULL, 0);
9365 if (cwd == NULL) {
9366 error = got_error_from_errno("getcwd");
9367 goto done;
9370 error = got_repo_pack_fds_open(&pack_fds);
9371 if (error != NULL)
9372 goto done;
9374 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
9375 if (error) {
9376 if (error->code == GOT_ERR_NOT_WORKTREE)
9377 error = wrap_not_worktree_error(error, "commit", cwd);
9378 goto done;
9381 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
9382 if (error)
9383 goto done;
9384 if (rebase_in_progress) {
9385 error = got_error(GOT_ERR_REBASING);
9386 goto done;
9389 error = got_worktree_histedit_in_progress(&histedit_in_progress,
9390 worktree);
9391 if (error)
9392 goto done;
9394 error = get_gitconfig_path(&gitconfig_path);
9395 if (error)
9396 goto done;
9397 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
9398 gitconfig_path, pack_fds);
9399 if (error != NULL)
9400 goto done;
9402 error = got_worktree_merge_in_progress(&merge_in_progress, worktree, repo);
9403 if (error)
9404 goto done;
9405 if (merge_in_progress) {
9406 error = got_error(GOT_ERR_MERGE_BUSY);
9407 goto done;
9410 error = get_author(&committer, repo, worktree);
9411 if (error)
9412 goto done;
9414 if (author == NULL)
9415 author = committer;
9417 if (logmsg == NULL || strlen(logmsg) == 0) {
9418 error = get_editor(&editor);
9419 if (error)
9420 goto done;
9421 if (unveil(editor, "x") != 0) {
9422 error = got_error_from_errno2("unveil", editor);
9423 goto done;
9427 error = apply_unveil(got_repo_get_path(repo), 0,
9428 got_worktree_get_root_path(worktree));
9429 if (error)
9430 goto done;
9432 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
9433 if (error)
9434 goto done;
9436 if (prepared_logmsg == NULL) {
9437 error = lookup_logmsg_ref(&merged_logmsg,
9438 argc > 0 ? &paths : NULL, &refs, worktree, repo);
9439 if (error)
9440 goto done;
9443 cl_arg.editor = editor;
9444 cl_arg.cmdline_log = logmsg;
9445 cl_arg.prepared_log = prepared_logmsg;
9446 cl_arg.merged_log = merged_logmsg;
9447 cl_arg.non_interactive = non_interactive;
9448 cl_arg.worktree_path = got_worktree_get_root_path(worktree);
9449 cl_arg.branch_name = got_worktree_get_head_ref_name(worktree);
9450 if (!histedit_in_progress) {
9451 if (strncmp(cl_arg.branch_name, "refs/heads/", 11) != 0) {
9452 error = got_error(GOT_ERR_COMMIT_BRANCH);
9453 goto done;
9455 cl_arg.branch_name += 11;
9457 cl_arg.repo_path = got_repo_get_path(repo);
9458 error = got_worktree_commit(&id, worktree, &paths, author, committer,
9459 allow_bad_symlinks, show_diff, commit_conflicts,
9460 collect_commit_logmsg, &cl_arg, print_status, NULL, repo);
9461 if (error) {
9462 if (error->code != GOT_ERR_COMMIT_MSG_EMPTY &&
9463 cl_arg.logmsg_path != NULL)
9464 preserve_logmsg = 1;
9465 goto done;
9468 error = got_object_id_str(&id_str, id);
9469 if (error)
9470 goto done;
9471 printf("Created commit %s\n", id_str);
9473 TAILQ_FOREACH(re, &refs, entry) {
9474 error = got_ref_delete(re->ref, repo);
9475 if (error)
9476 goto done;
9479 done:
9480 if (preserve_logmsg) {
9481 fprintf(stderr, "%s: log message preserved in %s\n",
9482 getprogname(), cl_arg.logmsg_path);
9483 } else if (cl_arg.logmsg_path && unlink(cl_arg.logmsg_path) == -1 &&
9484 error == NULL)
9485 error = got_error_from_errno2("unlink", cl_arg.logmsg_path);
9486 free(cl_arg.logmsg_path);
9487 if (merged_logmsg && unlink(merged_logmsg) == -1 && error == NULL)
9488 error = got_error_from_errno2("unlink", merged_logmsg);
9489 free(merged_logmsg);
9490 if (repo) {
9491 const struct got_error *close_err = got_repo_close(repo);
9492 if (error == NULL)
9493 error = close_err;
9495 if (worktree)
9496 got_worktree_close(worktree);
9497 if (pack_fds) {
9498 const struct got_error *pack_err =
9499 got_repo_pack_fds_close(pack_fds);
9500 if (error == NULL)
9501 error = pack_err;
9503 got_ref_list_free(&refs);
9504 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
9505 free(cwd);
9506 free(id_str);
9507 free(gitconfig_path);
9508 free(editor);
9509 free(committer);
9510 free(prepared_logmsg);
9511 return error;
9514 __dead static void
9515 usage_send(void)
9517 fprintf(stderr, "usage: %s send [-afqTv] [-b branch] [-d branch] "
9518 "[-r repository-path] [-t tag] [remote-repository]\n",
9519 getprogname());
9520 exit(1);
9523 static void
9524 print_load_info(int print_colored, int print_found, int print_trees,
9525 int ncolored, int nfound, int ntrees)
9527 if (print_colored) {
9528 printf("%d commit%s colored", ncolored,
9529 ncolored == 1 ? "" : "s");
9531 if (print_found) {
9532 printf("%s%d object%s found",
9533 ncolored > 0 ? "; " : "",
9534 nfound, nfound == 1 ? "" : "s");
9536 if (print_trees) {
9537 printf("; %d tree%s scanned", ntrees,
9538 ntrees == 1 ? "" : "s");
9542 struct got_send_progress_arg {
9543 char last_scaled_packsize[FMT_SCALED_STRSIZE];
9544 int verbosity;
9545 int last_ncolored;
9546 int last_nfound;
9547 int last_ntrees;
9548 int loading_done;
9549 int last_ncommits;
9550 int last_nobj_total;
9551 int last_p_deltify;
9552 int last_p_written;
9553 int last_p_sent;
9554 int printed_something;
9555 int sent_something;
9556 struct got_pathlist_head *delete_branches;
9559 static const struct got_error *
9560 send_progress(void *arg, int ncolored, int nfound, int ntrees,
9561 off_t packfile_size, int ncommits, int nobj_total, int nobj_deltify,
9562 int nobj_written, off_t bytes_sent, const char *refname,
9563 const char *errmsg, int success)
9565 struct got_send_progress_arg *a = arg;
9566 char scaled_packsize[FMT_SCALED_STRSIZE];
9567 char scaled_sent[FMT_SCALED_STRSIZE];
9568 int p_deltify = 0, p_written = 0, p_sent = 0;
9569 int print_colored = 0, print_found = 0, print_trees = 0;
9570 int print_searching = 0, print_total = 0;
9571 int print_deltify = 0, print_written = 0, print_sent = 0;
9573 if (a->verbosity < 0)
9574 return NULL;
9576 if (refname) {
9577 const char *status = success ? "accepted" : "rejected";
9579 if (success) {
9580 struct got_pathlist_entry *pe;
9581 TAILQ_FOREACH(pe, a->delete_branches, entry) {
9582 const char *branchname = pe->path;
9583 if (got_path_cmp(branchname, refname,
9584 strlen(branchname), strlen(refname)) == 0) {
9585 status = "deleted";
9586 a->sent_something = 1;
9587 break;
9592 if (a->printed_something)
9593 putchar('\n');
9594 printf("Server has %s %s", status, refname);
9595 if (errmsg)
9596 printf(": %s", errmsg);
9597 a->printed_something = 1;
9598 return NULL;
9601 if (a->last_ncolored != ncolored) {
9602 print_colored = 1;
9603 a->last_ncolored = ncolored;
9606 if (a->last_nfound != nfound) {
9607 print_colored = 1;
9608 print_found = 1;
9609 a->last_nfound = nfound;
9612 if (a->last_ntrees != ntrees) {
9613 print_colored = 1;
9614 print_found = 1;
9615 print_trees = 1;
9616 a->last_ntrees = ntrees;
9619 if ((print_colored || print_found || print_trees) &&
9620 !a->loading_done) {
9621 printf("\r");
9622 print_load_info(print_colored, print_found, print_trees,
9623 ncolored, nfound, ntrees);
9624 a->printed_something = 1;
9625 fflush(stdout);
9626 return NULL;
9627 } else if (!a->loading_done) {
9628 printf("\r");
9629 print_load_info(1, 1, 1, ncolored, nfound, ntrees);
9630 printf("\n");
9631 a->loading_done = 1;
9634 if (fmt_scaled(packfile_size, scaled_packsize) == -1)
9635 return got_error_from_errno("fmt_scaled");
9636 if (fmt_scaled(bytes_sent, scaled_sent) == -1)
9637 return got_error_from_errno("fmt_scaled");
9639 if (a->last_ncommits != ncommits) {
9640 print_searching = 1;
9641 a->last_ncommits = ncommits;
9644 if (a->last_nobj_total != nobj_total) {
9645 print_searching = 1;
9646 print_total = 1;
9647 a->last_nobj_total = nobj_total;
9650 if (packfile_size > 0 && (a->last_scaled_packsize[0] == '\0' ||
9651 strcmp(scaled_packsize, a->last_scaled_packsize)) != 0) {
9652 if (strlcpy(a->last_scaled_packsize, scaled_packsize,
9653 FMT_SCALED_STRSIZE) >= FMT_SCALED_STRSIZE)
9654 return got_error(GOT_ERR_NO_SPACE);
9657 if (nobj_deltify > 0 || nobj_written > 0) {
9658 if (nobj_deltify > 0) {
9659 p_deltify = (nobj_deltify * 100) / nobj_total;
9660 if (p_deltify != a->last_p_deltify) {
9661 a->last_p_deltify = p_deltify;
9662 print_searching = 1;
9663 print_total = 1;
9664 print_deltify = 1;
9667 if (nobj_written > 0) {
9668 p_written = (nobj_written * 100) / nobj_total;
9669 if (p_written != a->last_p_written) {
9670 a->last_p_written = p_written;
9671 print_searching = 1;
9672 print_total = 1;
9673 print_deltify = 1;
9674 print_written = 1;
9679 if (bytes_sent > 0) {
9680 p_sent = (bytes_sent * 100) / packfile_size;
9681 if (p_sent != a->last_p_sent) {
9682 a->last_p_sent = p_sent;
9683 print_searching = 1;
9684 print_total = 1;
9685 print_deltify = 1;
9686 print_written = 1;
9687 print_sent = 1;
9689 a->sent_something = 1;
9692 if (print_searching || print_total || print_deltify || print_written ||
9693 print_sent)
9694 printf("\r");
9695 if (print_searching)
9696 printf("packing %d reference%s", ncommits,
9697 ncommits == 1 ? "" : "s");
9698 if (print_total)
9699 printf("; %d object%s", nobj_total,
9700 nobj_total == 1 ? "" : "s");
9701 if (print_deltify)
9702 printf("; deltify: %d%%", p_deltify);
9703 if (print_sent)
9704 printf("; uploading pack: %*s %d%%", FMT_SCALED_STRSIZE - 2,
9705 scaled_packsize, p_sent);
9706 else if (print_written)
9707 printf("; writing pack: %*s %d%%", FMT_SCALED_STRSIZE - 2,
9708 scaled_packsize, p_written);
9709 if (print_searching || print_total || print_deltify ||
9710 print_written || print_sent) {
9711 a->printed_something = 1;
9712 fflush(stdout);
9714 return NULL;
9717 static const struct got_error *
9718 cmd_send(int argc, char *argv[])
9720 const struct got_error *error = NULL;
9721 char *cwd = NULL, *repo_path = NULL;
9722 const char *remote_name;
9723 char *proto = NULL, *host = NULL, *port = NULL;
9724 char *repo_name = NULL, *server_path = NULL;
9725 const struct got_remote_repo *remotes;
9726 struct got_remote_repo *remote = NULL;
9727 int nremotes, nbranches = 0, ndelete_branches = 0;
9728 struct got_repository *repo = NULL;
9729 struct got_worktree *worktree = NULL;
9730 const struct got_gotconfig *repo_conf = NULL, *worktree_conf = NULL;
9731 struct got_pathlist_head branches;
9732 struct got_pathlist_head tags;
9733 struct got_reflist_head all_branches;
9734 struct got_reflist_head all_tags;
9735 struct got_pathlist_head delete_args;
9736 struct got_pathlist_head delete_branches;
9737 struct got_reflist_entry *re;
9738 struct got_pathlist_entry *pe;
9739 int i, ch, sendfd = -1, sendstatus;
9740 pid_t sendpid = -1;
9741 struct got_send_progress_arg spa;
9742 int verbosity = 0, overwrite_refs = 0;
9743 int send_all_branches = 0, send_all_tags = 0;
9744 struct got_reference *ref = NULL;
9745 int *pack_fds = NULL;
9747 TAILQ_INIT(&branches);
9748 TAILQ_INIT(&tags);
9749 TAILQ_INIT(&all_branches);
9750 TAILQ_INIT(&all_tags);
9751 TAILQ_INIT(&delete_args);
9752 TAILQ_INIT(&delete_branches);
9754 while ((ch = getopt(argc, argv, "ab:d:fqr:Tt:v")) != -1) {
9755 switch (ch) {
9756 case 'a':
9757 send_all_branches = 1;
9758 break;
9759 case 'b':
9760 error = got_pathlist_append(&branches, optarg, NULL);
9761 if (error)
9762 return error;
9763 nbranches++;
9764 break;
9765 case 'd':
9766 error = got_pathlist_append(&delete_args, optarg, NULL);
9767 if (error)
9768 return error;
9769 break;
9770 case 'f':
9771 overwrite_refs = 1;
9772 break;
9773 case 'q':
9774 verbosity = -1;
9775 break;
9776 case 'r':
9777 repo_path = realpath(optarg, NULL);
9778 if (repo_path == NULL)
9779 return got_error_from_errno2("realpath",
9780 optarg);
9781 got_path_strip_trailing_slashes(repo_path);
9782 break;
9783 case 'T':
9784 send_all_tags = 1;
9785 break;
9786 case 't':
9787 error = got_pathlist_append(&tags, optarg, NULL);
9788 if (error)
9789 return error;
9790 break;
9791 case 'v':
9792 if (verbosity < 0)
9793 verbosity = 0;
9794 else if (verbosity < 3)
9795 verbosity++;
9796 break;
9797 default:
9798 usage_send();
9799 /* NOTREACHED */
9802 argc -= optind;
9803 argv += optind;
9805 if (send_all_branches && !TAILQ_EMPTY(&branches))
9806 option_conflict('a', 'b');
9807 if (send_all_tags && !TAILQ_EMPTY(&tags))
9808 option_conflict('T', 't');
9811 if (argc == 0)
9812 remote_name = GOT_SEND_DEFAULT_REMOTE_NAME;
9813 else if (argc == 1)
9814 remote_name = argv[0];
9815 else
9816 usage_send();
9818 cwd = getcwd(NULL, 0);
9819 if (cwd == NULL) {
9820 error = got_error_from_errno("getcwd");
9821 goto done;
9824 error = got_repo_pack_fds_open(&pack_fds);
9825 if (error != NULL)
9826 goto done;
9828 if (repo_path == NULL) {
9829 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
9830 if (error && error->code != GOT_ERR_NOT_WORKTREE)
9831 goto done;
9832 else
9833 error = NULL;
9834 if (worktree) {
9835 repo_path =
9836 strdup(got_worktree_get_repo_path(worktree));
9837 if (repo_path == NULL)
9838 error = got_error_from_errno("strdup");
9839 if (error)
9840 goto done;
9841 } else {
9842 repo_path = strdup(cwd);
9843 if (repo_path == NULL) {
9844 error = got_error_from_errno("strdup");
9845 goto done;
9850 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
9851 if (error)
9852 goto done;
9854 if (worktree) {
9855 worktree_conf = got_worktree_get_gotconfig(worktree);
9856 if (worktree_conf) {
9857 got_gotconfig_get_remotes(&nremotes, &remotes,
9858 worktree_conf);
9859 for (i = 0; i < nremotes; i++) {
9860 if (strcmp(remotes[i].name, remote_name) == 0) {
9861 error = got_repo_remote_repo_dup(&remote,
9862 &remotes[i]);
9863 if (error)
9864 goto done;
9865 break;
9870 if (remote == NULL) {
9871 repo_conf = got_repo_get_gotconfig(repo);
9872 if (repo_conf) {
9873 got_gotconfig_get_remotes(&nremotes, &remotes,
9874 repo_conf);
9875 for (i = 0; i < nremotes; i++) {
9876 if (strcmp(remotes[i].name, remote_name) == 0) {
9877 error = got_repo_remote_repo_dup(&remote,
9878 &remotes[i]);
9879 if (error)
9880 goto done;
9881 break;
9886 if (remote == NULL) {
9887 got_repo_get_gitconfig_remotes(&nremotes, &remotes, repo);
9888 for (i = 0; i < nremotes; i++) {
9889 if (strcmp(remotes[i].name, remote_name) == 0) {
9890 error = got_repo_remote_repo_dup(&remote,
9891 &remotes[i]);
9892 if (error)
9893 goto done;
9894 break;
9898 if (remote == NULL) {
9899 error = got_error_path(remote_name, GOT_ERR_NO_REMOTE);
9900 goto done;
9903 error = got_dial_parse_uri(&proto, &host, &port, &server_path,
9904 &repo_name, remote->send_url);
9905 if (error)
9906 goto done;
9908 if (strcmp(proto, "git") == 0) {
9909 #ifndef PROFILE
9910 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
9911 "sendfd dns inet unveil", NULL) == -1)
9912 err(1, "pledge");
9913 #endif
9914 } else if (strcmp(proto, "git+ssh") == 0 ||
9915 strcmp(proto, "ssh") == 0) {
9916 #ifndef PROFILE
9917 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
9918 "sendfd unveil", NULL) == -1)
9919 err(1, "pledge");
9920 #endif
9921 } else if (strcmp(proto, "http") == 0 ||
9922 strcmp(proto, "git+http") == 0) {
9923 error = got_error_path(proto, GOT_ERR_NOT_IMPL);
9924 goto done;
9925 } else {
9926 error = got_error_path(proto, GOT_ERR_BAD_PROTO);
9927 goto done;
9930 error = got_dial_apply_unveil(proto);
9931 if (error)
9932 goto done;
9934 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
9935 if (error)
9936 goto done;
9938 if (send_all_branches) {
9939 error = got_ref_list(&all_branches, repo, "refs/heads",
9940 got_ref_cmp_by_name, NULL);
9941 if (error)
9942 goto done;
9943 TAILQ_FOREACH(re, &all_branches, entry) {
9944 const char *branchname = got_ref_get_name(re->ref);
9945 error = got_pathlist_append(&branches,
9946 branchname, NULL);
9947 if (error)
9948 goto done;
9949 nbranches++;
9951 } else if (nbranches == 0) {
9952 for (i = 0; i < remote->nsend_branches; i++) {
9953 error = got_pathlist_append(&branches,
9954 remote->send_branches[i], NULL);
9955 if (error)
9956 goto done;
9960 if (send_all_tags) {
9961 error = got_ref_list(&all_tags, repo, "refs/tags",
9962 got_ref_cmp_by_name, NULL);
9963 if (error)
9964 goto done;
9965 TAILQ_FOREACH(re, &all_tags, entry) {
9966 const char *tagname = got_ref_get_name(re->ref);
9967 error = got_pathlist_append(&tags,
9968 tagname, NULL);
9969 if (error)
9970 goto done;
9975 * To prevent accidents only branches in refs/heads/ can be deleted
9976 * with 'got send -d'.
9977 * Deleting anything else requires local repository access or Git.
9979 TAILQ_FOREACH(pe, &delete_args, entry) {
9980 const char *branchname = pe->path;
9981 char *s;
9982 struct got_pathlist_entry *new;
9983 if (strncmp(branchname, "refs/heads/", 11) == 0) {
9984 s = strdup(branchname);
9985 if (s == NULL) {
9986 error = got_error_from_errno("strdup");
9987 goto done;
9989 } else {
9990 if (asprintf(&s, "refs/heads/%s", branchname) == -1) {
9991 error = got_error_from_errno("asprintf");
9992 goto done;
9995 error = got_pathlist_insert(&new, &delete_branches, s, NULL);
9996 if (error || new == NULL /* duplicate */)
9997 free(s);
9998 if (error)
9999 goto done;
10000 ndelete_branches++;
10003 if (nbranches == 0 && ndelete_branches == 0) {
10004 struct got_reference *head_ref;
10005 if (worktree)
10006 error = got_ref_open(&head_ref, repo,
10007 got_worktree_get_head_ref_name(worktree), 0);
10008 else
10009 error = got_ref_open(&head_ref, repo, GOT_REF_HEAD, 0);
10010 if (error)
10011 goto done;
10012 if (got_ref_is_symbolic(head_ref)) {
10013 error = got_ref_resolve_symbolic(&ref, repo, head_ref);
10014 got_ref_close(head_ref);
10015 if (error)
10016 goto done;
10017 } else
10018 ref = head_ref;
10019 error = got_pathlist_append(&branches, got_ref_get_name(ref),
10020 NULL);
10021 if (error)
10022 goto done;
10023 nbranches++;
10026 if (worktree) {
10027 /* Release work tree lock. */
10028 got_worktree_close(worktree);
10029 worktree = NULL;
10032 if (verbosity >= 0) {
10033 printf("Connecting to \"%s\" %s://%s%s%s%s%s\n",
10034 remote->name, proto, host,
10035 port ? ":" : "", port ? port : "",
10036 *server_path == '/' ? "" : "/", server_path);
10039 error = got_send_connect(&sendpid, &sendfd, proto, host, port,
10040 server_path, verbosity);
10041 if (error)
10042 goto done;
10044 memset(&spa, 0, sizeof(spa));
10045 spa.last_scaled_packsize[0] = '\0';
10046 spa.last_p_deltify = -1;
10047 spa.last_p_written = -1;
10048 spa.verbosity = verbosity;
10049 spa.delete_branches = &delete_branches;
10050 error = got_send_pack(remote_name, &branches, &tags, &delete_branches,
10051 verbosity, overwrite_refs, sendfd, repo, send_progress, &spa,
10052 check_cancelled, NULL);
10053 if (spa.printed_something)
10054 putchar('\n');
10055 if (error)
10056 goto done;
10057 if (!spa.sent_something && verbosity >= 0)
10058 printf("Already up-to-date\n");
10059 done:
10060 if (sendpid > 0) {
10061 if (kill(sendpid, SIGTERM) == -1)
10062 error = got_error_from_errno("kill");
10063 if (waitpid(sendpid, &sendstatus, 0) == -1 && error == NULL)
10064 error = got_error_from_errno("waitpid");
10066 if (sendfd != -1 && close(sendfd) == -1 && error == NULL)
10067 error = got_error_from_errno("close");
10068 if (repo) {
10069 const struct got_error *close_err = got_repo_close(repo);
10070 if (error == NULL)
10071 error = close_err;
10073 if (worktree)
10074 got_worktree_close(worktree);
10075 if (pack_fds) {
10076 const struct got_error *pack_err =
10077 got_repo_pack_fds_close(pack_fds);
10078 if (error == NULL)
10079 error = pack_err;
10081 if (ref)
10082 got_ref_close(ref);
10083 got_repo_free_remote_repo_data(remote);
10084 free(remote);
10085 got_pathlist_free(&branches, GOT_PATHLIST_FREE_NONE);
10086 got_pathlist_free(&tags, GOT_PATHLIST_FREE_NONE);
10087 got_ref_list_free(&all_branches);
10088 got_ref_list_free(&all_tags);
10089 got_pathlist_free(&delete_args, GOT_PATHLIST_FREE_NONE);
10090 got_pathlist_free(&delete_branches, GOT_PATHLIST_FREE_PATH);
10091 free(cwd);
10092 free(repo_path);
10093 free(proto);
10094 free(host);
10095 free(port);
10096 free(server_path);
10097 free(repo_name);
10098 return error;
10102 * Print and if delete is set delete all ref_prefix references.
10103 * If wanted_ref is not NULL, only print or delete this reference.
10105 static const struct got_error *
10106 process_logmsg_refs(const char *ref_prefix, size_t prefix_len,
10107 const char *wanted_ref, int delete, struct got_worktree *worktree,
10108 struct got_repository *repo)
10110 const struct got_error *err;
10111 struct got_pathlist_head paths;
10112 struct got_reflist_head refs;
10113 struct got_reflist_entry *re;
10114 struct got_reflist_object_id_map *refs_idmap = NULL;
10115 struct got_commit_object *commit = NULL;
10116 struct got_object_id *id = NULL;
10117 const char *header_prefix;
10118 char *uuidstr = NULL;
10119 int found = 0;
10121 TAILQ_INIT(&refs);
10122 TAILQ_INIT(&paths);
10124 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, repo);
10125 if (err)
10126 goto done;
10128 err = got_reflist_object_id_map_create(&refs_idmap, &refs, repo);
10129 if (err)
10130 goto done;
10132 if (worktree != NULL) {
10133 err = got_worktree_get_uuid(&uuidstr, worktree);
10134 if (err)
10135 goto done;
10138 if (wanted_ref) {
10139 if (strncmp(wanted_ref, "refs/heads/", 11) == 0)
10140 wanted_ref += 11;
10143 if (strcmp(ref_prefix, GOT_WORKTREE_BACKOUT_REF_PREFIX) == 0)
10144 header_prefix = "backout";
10145 else
10146 header_prefix = "cherrypick";
10148 TAILQ_FOREACH(re, &refs, entry) {
10149 const char *refname, *wt;
10151 refname = got_ref_get_name(re->ref);
10153 err = check_cancelled(NULL);
10154 if (err)
10155 goto done;
10157 if (strncmp(refname, ref_prefix, prefix_len) == 0)
10158 refname += prefix_len + 1; /* skip '-' delimiter */
10159 else
10160 continue;
10162 wt = refname;
10164 if (worktree == NULL || strncmp(refname, uuidstr,
10165 GOT_WORKTREE_UUID_STRLEN) == 0)
10166 refname += GOT_WORKTREE_UUID_STRLEN + 1; /* skip '-' */
10167 else
10168 continue;
10170 err = got_repo_match_object_id(&id, NULL, refname,
10171 GOT_OBJ_TYPE_COMMIT, NULL, repo);
10172 if (err)
10173 goto done;
10175 err = got_object_open_as_commit(&commit, repo, id);
10176 if (err)
10177 goto done;
10179 if (wanted_ref)
10180 found = strncmp(wanted_ref, refname,
10181 strlen(wanted_ref)) == 0;
10182 if (wanted_ref && !found) {
10183 struct got_reflist_head *ci_refs;
10185 ci_refs = got_reflist_object_id_map_lookup(refs_idmap,
10186 id);
10188 if (ci_refs) {
10189 char *refs_str = NULL;
10190 char const *r = NULL;
10192 err = build_refs_str(&refs_str, ci_refs, id,
10193 repo, 1);
10194 if (err)
10195 goto done;
10197 r = refs_str;
10198 while (r) {
10199 if (strncmp(r, wanted_ref,
10200 strlen(wanted_ref)) == 0) {
10201 found = 1;
10202 break;
10204 r = strchr(r, ' ');
10205 if (r)
10206 ++r;
10208 free(refs_str);
10212 if (wanted_ref == NULL || found) {
10213 if (delete) {
10214 err = got_ref_delete(re->ref, repo);
10215 if (err)
10216 goto done;
10217 printf("Deleted: ");
10218 err = print_commit_oneline(commit, id, repo,
10219 refs_idmap);
10220 } else {
10222 * Print paths modified by commit to help
10223 * associate commits with worktree changes.
10225 err = get_changed_paths(&paths, commit,
10226 repo, NULL);
10227 if (err)
10228 goto done;
10230 err = print_commit(commit, id, repo, NULL,
10231 &paths, NULL, 0, 0, refs_idmap, NULL,
10232 header_prefix);
10233 got_pathlist_free(&paths,
10234 GOT_PATHLIST_FREE_ALL);
10236 if (worktree == NULL)
10237 printf("work tree: %.*s\n\n",
10238 GOT_WORKTREE_UUID_STRLEN, wt);
10240 if (err || found)
10241 goto done;
10244 got_object_commit_close(commit);
10245 commit = NULL;
10246 free(id);
10247 id = NULL;
10250 if (wanted_ref != NULL && !found)
10251 err = got_error_fmt(GOT_ERR_NOT_REF, "%s", wanted_ref);
10253 done:
10254 free(id);
10255 free(uuidstr);
10256 got_ref_list_free(&refs);
10257 got_pathlist_free(&paths, GOT_PATHLIST_FREE_ALL);
10258 if (refs_idmap)
10259 got_reflist_object_id_map_free(refs_idmap);
10260 if (commit)
10261 got_object_commit_close(commit);
10262 return err;
10266 * Create new temp "logmsg" ref of the backed-out or cherrypicked commit
10267 * identified by id for log messages to prepopulate the editor on commit.
10269 static const struct got_error *
10270 logmsg_ref(struct got_object_id *id, const char *prefix,
10271 struct got_worktree *worktree, struct got_repository *repo)
10273 const struct got_error *err = NULL;
10274 char *idstr, *ref = NULL, *refname = NULL;
10275 int histedit_in_progress;
10276 int rebase_in_progress, merge_in_progress;
10279 * Silenty refuse to create merge reference if any histedit, merge,
10280 * or rebase operation is in progress.
10282 err = got_worktree_histedit_in_progress(&histedit_in_progress,
10283 worktree);
10284 if (err)
10285 return err;
10286 if (histedit_in_progress)
10287 return NULL;
10289 err = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
10290 if (err)
10291 return err;
10292 if (rebase_in_progress)
10293 return NULL;
10295 err = got_worktree_merge_in_progress(&merge_in_progress, worktree,
10296 repo);
10297 if (err)
10298 return err;
10299 if (merge_in_progress)
10300 return NULL;
10302 err = got_object_id_str(&idstr, id);
10303 if (err)
10304 return err;
10306 err = got_worktree_get_logmsg_ref_name(&refname, worktree, prefix);
10307 if (err)
10308 goto done;
10310 if (asprintf(&ref, "%s-%s", refname, idstr) == -1) {
10311 err = got_error_from_errno("asprintf");
10312 goto done;
10315 err = create_ref(ref, got_worktree_get_base_commit_id(worktree),
10316 -1, repo);
10317 done:
10318 free(ref);
10319 free(idstr);
10320 free(refname);
10321 return err;
10324 __dead static void
10325 usage_cherrypick(void)
10327 fprintf(stderr, "usage: %s cherrypick [-lX] [commit-id]\n",
10328 getprogname());
10329 exit(1);
10332 static const struct got_error *
10333 cmd_cherrypick(int argc, char *argv[])
10335 const struct got_error *error = NULL;
10336 struct got_worktree *worktree = NULL;
10337 struct got_repository *repo = NULL;
10338 char *cwd = NULL, *commit_id_str = NULL, *keyword_idstr = NULL;
10339 struct got_object_id *commit_id = NULL;
10340 struct got_commit_object *commit = NULL;
10341 struct got_object_qid *pid;
10342 int ch, list_refs = 0, remove_refs = 0;
10343 struct got_update_progress_arg upa;
10344 int *pack_fds = NULL;
10346 #ifndef PROFILE
10347 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
10348 "unveil", NULL) == -1)
10349 err(1, "pledge");
10350 #endif
10352 while ((ch = getopt(argc, argv, "lX")) != -1) {
10353 switch (ch) {
10354 case 'l':
10355 list_refs = 1;
10356 break;
10357 case 'X':
10358 remove_refs = 1;
10359 break;
10360 default:
10361 usage_cherrypick();
10362 /* NOTREACHED */
10366 argc -= optind;
10367 argv += optind;
10369 if (list_refs || remove_refs) {
10370 if (argc != 0 && argc != 1)
10371 usage_cherrypick();
10372 } else if (argc != 1)
10373 usage_cherrypick();
10374 if (list_refs && remove_refs)
10375 option_conflict('l', 'X');
10377 cwd = getcwd(NULL, 0);
10378 if (cwd == NULL) {
10379 error = got_error_from_errno("getcwd");
10380 goto done;
10383 error = got_repo_pack_fds_open(&pack_fds);
10384 if (error != NULL)
10385 goto done;
10387 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
10388 if (error) {
10389 if (list_refs || remove_refs) {
10390 if (error->code != GOT_ERR_NOT_WORKTREE)
10391 goto done;
10392 } else {
10393 if (error->code == GOT_ERR_NOT_WORKTREE)
10394 error = wrap_not_worktree_error(error,
10395 "cherrypick", cwd);
10396 goto done;
10400 error = got_repo_open(&repo,
10401 worktree ? got_worktree_get_repo_path(worktree) : cwd,
10402 NULL, pack_fds);
10403 if (error != NULL)
10404 goto done;
10406 error = apply_unveil(got_repo_get_path(repo), 0,
10407 worktree ? got_worktree_get_root_path(worktree) : NULL);
10408 if (error)
10409 goto done;
10411 if (list_refs || remove_refs) {
10412 error = process_logmsg_refs(GOT_WORKTREE_CHERRYPICK_REF_PREFIX,
10413 GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN,
10414 argc == 1 ? argv[0] : NULL, remove_refs, worktree, repo);
10415 goto done;
10418 error = got_keyword_to_idstr(&keyword_idstr, argv[0], repo, worktree);
10419 if (error != NULL)
10420 goto done;
10422 error = got_repo_match_object_id(&commit_id, NULL,
10423 keyword_idstr != NULL ? keyword_idstr : argv[0],
10424 GOT_OBJ_TYPE_COMMIT, NULL, repo);
10425 if (error)
10426 goto done;
10427 error = got_object_id_str(&commit_id_str, commit_id);
10428 if (error)
10429 goto done;
10431 error = got_object_open_as_commit(&commit, repo, commit_id);
10432 if (error)
10433 goto done;
10434 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
10435 memset(&upa, 0, sizeof(upa));
10436 error = got_worktree_merge_files(worktree, pid ? &pid->id : NULL,
10437 commit_id, repo, update_progress, &upa, check_cancelled,
10438 NULL);
10439 if (error != NULL)
10440 goto done;
10442 if (upa.did_something) {
10443 error = logmsg_ref(commit_id,
10444 GOT_WORKTREE_CHERRYPICK_REF_PREFIX, worktree, repo);
10445 if (error)
10446 goto done;
10447 printf("Merged commit %s\n", commit_id_str);
10449 print_merge_progress_stats(&upa);
10450 done:
10451 free(cwd);
10452 free(keyword_idstr);
10453 if (commit)
10454 got_object_commit_close(commit);
10455 free(commit_id_str);
10456 if (worktree)
10457 got_worktree_close(worktree);
10458 if (repo) {
10459 const struct got_error *close_err = got_repo_close(repo);
10460 if (error == NULL)
10461 error = close_err;
10463 if (pack_fds) {
10464 const struct got_error *pack_err =
10465 got_repo_pack_fds_close(pack_fds);
10466 if (error == NULL)
10467 error = pack_err;
10470 return error;
10473 __dead static void
10474 usage_backout(void)
10476 fprintf(stderr, "usage: %s backout [-lX] [commit-id]\n", getprogname());
10477 exit(1);
10480 static const struct got_error *
10481 cmd_backout(int argc, char *argv[])
10483 const struct got_error *error = NULL;
10484 struct got_worktree *worktree = NULL;
10485 struct got_repository *repo = NULL;
10486 char *cwd = NULL, *commit_id_str = NULL, *keyword_idstr = NULL;
10487 struct got_object_id *commit_id = NULL;
10488 struct got_commit_object *commit = NULL;
10489 struct got_object_qid *pid;
10490 int ch, list_refs = 0, remove_refs = 0;
10491 struct got_update_progress_arg upa;
10492 int *pack_fds = NULL;
10494 #ifndef PROFILE
10495 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
10496 "unveil", NULL) == -1)
10497 err(1, "pledge");
10498 #endif
10500 while ((ch = getopt(argc, argv, "lX")) != -1) {
10501 switch (ch) {
10502 case 'l':
10503 list_refs = 1;
10504 break;
10505 case 'X':
10506 remove_refs = 1;
10507 break;
10508 default:
10509 usage_backout();
10510 /* NOTREACHED */
10514 argc -= optind;
10515 argv += optind;
10517 if (list_refs || remove_refs) {
10518 if (argc != 0 && argc != 1)
10519 usage_backout();
10520 } else if (argc != 1)
10521 usage_backout();
10522 if (list_refs && remove_refs)
10523 option_conflict('l', 'X');
10525 cwd = getcwd(NULL, 0);
10526 if (cwd == NULL) {
10527 error = got_error_from_errno("getcwd");
10528 goto done;
10531 error = got_repo_pack_fds_open(&pack_fds);
10532 if (error != NULL)
10533 goto done;
10535 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
10536 if (error) {
10537 if (list_refs || remove_refs) {
10538 if (error->code != GOT_ERR_NOT_WORKTREE)
10539 goto done;
10540 } else {
10541 if (error->code == GOT_ERR_NOT_WORKTREE)
10542 error = wrap_not_worktree_error(error,
10543 "backout", cwd);
10544 goto done;
10548 error = got_repo_open(&repo,
10549 worktree ? got_worktree_get_repo_path(worktree) : cwd,
10550 NULL, pack_fds);
10551 if (error != NULL)
10552 goto done;
10554 error = apply_unveil(got_repo_get_path(repo), 0,
10555 worktree ? got_worktree_get_root_path(worktree) : NULL);
10556 if (error)
10557 goto done;
10559 if (list_refs || remove_refs) {
10560 error = process_logmsg_refs(GOT_WORKTREE_BACKOUT_REF_PREFIX,
10561 GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN,
10562 argc == 1 ? argv[0] : NULL, remove_refs, worktree, repo);
10563 goto done;
10566 error = got_keyword_to_idstr(&keyword_idstr, argv[0], repo, worktree);
10567 if (error != NULL)
10568 goto done;
10570 error = got_repo_match_object_id(&commit_id, NULL,
10571 keyword_idstr != NULL ? keyword_idstr : argv[0],
10572 GOT_OBJ_TYPE_COMMIT, NULL, repo);
10573 if (error)
10574 goto done;
10575 error = got_object_id_str(&commit_id_str, commit_id);
10576 if (error)
10577 goto done;
10579 error = got_object_open_as_commit(&commit, repo, commit_id);
10580 if (error)
10581 goto done;
10582 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
10583 if (pid == NULL) {
10584 error = got_error(GOT_ERR_ROOT_COMMIT);
10585 goto done;
10588 memset(&upa, 0, sizeof(upa));
10589 error = got_worktree_merge_files(worktree, commit_id, &pid->id,
10590 repo, update_progress, &upa, check_cancelled, NULL);
10591 if (error != NULL)
10592 goto done;
10594 if (upa.did_something) {
10595 error = logmsg_ref(commit_id, GOT_WORKTREE_BACKOUT_REF_PREFIX,
10596 worktree, repo);
10597 if (error)
10598 goto done;
10599 printf("Backed out commit %s\n", commit_id_str);
10601 print_merge_progress_stats(&upa);
10602 done:
10603 free(cwd);
10604 free(keyword_idstr);
10605 if (commit)
10606 got_object_commit_close(commit);
10607 free(commit_id_str);
10608 if (worktree)
10609 got_worktree_close(worktree);
10610 if (repo) {
10611 const struct got_error *close_err = got_repo_close(repo);
10612 if (error == NULL)
10613 error = close_err;
10615 if (pack_fds) {
10616 const struct got_error *pack_err =
10617 got_repo_pack_fds_close(pack_fds);
10618 if (error == NULL)
10619 error = pack_err;
10621 return error;
10624 __dead static void
10625 usage_rebase(void)
10627 fprintf(stderr, "usage: %s rebase [-aCclX] [branch]\n", getprogname());
10628 exit(1);
10631 static void
10632 trim_logmsg(char *logmsg, int limit)
10634 char *nl;
10635 size_t len;
10637 len = strlen(logmsg);
10638 if (len > limit)
10639 len = limit;
10640 logmsg[len] = '\0';
10641 nl = strchr(logmsg, '\n');
10642 if (nl)
10643 *nl = '\0';
10646 static const struct got_error *
10647 get_short_logmsg(char **logmsg, int limit, struct got_commit_object *commit)
10649 const struct got_error *err;
10650 char *logmsg0 = NULL;
10651 const char *s;
10653 err = got_object_commit_get_logmsg(&logmsg0, commit);
10654 if (err)
10655 return err;
10657 s = logmsg0;
10658 while (isspace((unsigned char)s[0]))
10659 s++;
10661 *logmsg = strdup(s);
10662 if (*logmsg == NULL) {
10663 err = got_error_from_errno("strdup");
10664 goto done;
10667 trim_logmsg(*logmsg, limit);
10668 done:
10669 free(logmsg0);
10670 return err;
10673 static const struct got_error *
10674 show_rebase_merge_conflict(struct got_object_id *id,
10675 struct got_repository *repo)
10677 const struct got_error *err;
10678 struct got_commit_object *commit = NULL;
10679 char *id_str = NULL, *logmsg = NULL;
10681 err = got_object_open_as_commit(&commit, repo, id);
10682 if (err)
10683 return err;
10685 err = got_object_id_str(&id_str, id);
10686 if (err)
10687 goto done;
10689 id_str[12] = '\0';
10691 err = get_short_logmsg(&logmsg, 42, commit);
10692 if (err)
10693 goto done;
10695 printf("%s -> merge conflict: %s\n", id_str, logmsg);
10696 done:
10697 free(id_str);
10698 got_object_commit_close(commit);
10699 free(logmsg);
10700 return err;
10703 static const struct got_error *
10704 show_rebase_progress(struct got_commit_object *commit,
10705 struct got_object_id *old_id, struct got_object_id *new_id)
10707 const struct got_error *err;
10708 char *old_id_str = NULL, *new_id_str = NULL, *logmsg = NULL;
10710 err = got_object_id_str(&old_id_str, old_id);
10711 if (err)
10712 goto done;
10714 if (new_id) {
10715 err = got_object_id_str(&new_id_str, new_id);
10716 if (err)
10717 goto done;
10720 old_id_str[12] = '\0';
10721 if (new_id_str)
10722 new_id_str[12] = '\0';
10724 err = get_short_logmsg(&logmsg, 42, commit);
10725 if (err)
10726 goto done;
10728 printf("%s -> %s: %s\n", old_id_str,
10729 new_id_str ? new_id_str : "no-op change", logmsg);
10730 done:
10731 free(old_id_str);
10732 free(new_id_str);
10733 free(logmsg);
10734 return err;
10737 static const struct got_error *
10738 rebase_complete(struct got_worktree *worktree, struct got_fileindex *fileindex,
10739 struct got_reference *branch, struct got_reference *tmp_branch,
10740 struct got_repository *repo, int create_backup)
10742 printf("Switching work tree to %s\n", got_ref_get_name(branch));
10743 return got_worktree_rebase_complete(worktree, fileindex,
10744 tmp_branch, branch, repo, create_backup);
10747 static const struct got_error *
10748 rebase_commit(struct got_pathlist_head *merged_paths,
10749 struct got_worktree *worktree, struct got_fileindex *fileindex,
10750 struct got_reference *tmp_branch, const char *committer,
10751 struct got_object_id *commit_id, int allow_conflict,
10752 struct got_repository *repo)
10754 const struct got_error *error;
10755 struct got_commit_object *commit;
10756 struct got_object_id *new_commit_id;
10758 error = got_object_open_as_commit(&commit, repo, commit_id);
10759 if (error)
10760 return error;
10762 error = got_worktree_rebase_commit(&new_commit_id, merged_paths,
10763 worktree, fileindex, tmp_branch, committer, commit, commit_id,
10764 allow_conflict, repo);
10765 if (error) {
10766 if (error->code != GOT_ERR_COMMIT_NO_CHANGES)
10767 goto done;
10768 error = show_rebase_progress(commit, commit_id, NULL);
10769 } else {
10770 error = show_rebase_progress(commit, commit_id, new_commit_id);
10771 free(new_commit_id);
10773 done:
10774 got_object_commit_close(commit);
10775 return error;
10778 struct check_path_prefix_arg {
10779 const char *path_prefix;
10780 size_t len;
10781 int errcode;
10784 static const struct got_error *
10785 check_path_prefix_in_diff(void *arg, struct got_blob_object *blob1,
10786 struct got_blob_object *blob2, FILE *f1, FILE *f2,
10787 struct got_object_id *id1, struct got_object_id *id2,
10788 const char *path1, const char *path2,
10789 mode_t mode1, mode_t mode2, struct got_repository *repo)
10791 struct check_path_prefix_arg *a = arg;
10793 if ((path1 && !got_path_is_child(path1, a->path_prefix, a->len)) ||
10794 (path2 && !got_path_is_child(path2, a->path_prefix, a->len)))
10795 return got_error(a->errcode);
10797 return NULL;
10800 static const struct got_error *
10801 check_path_prefix(struct got_object_id *parent_id,
10802 struct got_object_id *commit_id, const char *path_prefix,
10803 int errcode, struct got_repository *repo)
10805 const struct got_error *err;
10806 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
10807 struct got_commit_object *commit = NULL, *parent_commit = NULL;
10808 struct check_path_prefix_arg cpp_arg;
10810 if (got_path_is_root_dir(path_prefix))
10811 return NULL;
10813 err = got_object_open_as_commit(&commit, repo, commit_id);
10814 if (err)
10815 goto done;
10817 err = got_object_open_as_commit(&parent_commit, repo, parent_id);
10818 if (err)
10819 goto done;
10821 err = got_object_open_as_tree(&tree1, repo,
10822 got_object_commit_get_tree_id(parent_commit));
10823 if (err)
10824 goto done;
10826 err = got_object_open_as_tree(&tree2, repo,
10827 got_object_commit_get_tree_id(commit));
10828 if (err)
10829 goto done;
10831 cpp_arg.path_prefix = path_prefix;
10832 while (cpp_arg.path_prefix[0] == '/')
10833 cpp_arg.path_prefix++;
10834 cpp_arg.len = strlen(cpp_arg.path_prefix);
10835 cpp_arg.errcode = errcode;
10836 err = got_diff_tree(tree1, tree2, NULL, NULL, -1, -1, "", "", repo,
10837 check_path_prefix_in_diff, &cpp_arg, 0);
10838 done:
10839 if (tree1)
10840 got_object_tree_close(tree1);
10841 if (tree2)
10842 got_object_tree_close(tree2);
10843 if (commit)
10844 got_object_commit_close(commit);
10845 if (parent_commit)
10846 got_object_commit_close(parent_commit);
10847 return err;
10850 static const struct got_error *
10851 collect_commits(struct got_object_id_queue *commits,
10852 struct got_object_id *initial_commit_id,
10853 struct got_object_id *iter_start_id, struct got_object_id *iter_stop_id,
10854 const char *path_prefix, int path_prefix_errcode,
10855 struct got_repository *repo)
10857 const struct got_error *err = NULL;
10858 struct got_commit_graph *graph = NULL;
10859 struct got_object_id parent_id, commit_id;
10860 struct got_object_qid *qid;
10862 err = got_commit_graph_open(&graph, "/", 1);
10863 if (err)
10864 return err;
10866 err = got_commit_graph_bfsort(graph, iter_start_id, repo,
10867 check_cancelled, NULL);
10868 if (err)
10869 goto done;
10871 memcpy(&commit_id, initial_commit_id, sizeof(commit_id));
10872 while (got_object_id_cmp(&commit_id, iter_stop_id) != 0) {
10873 err = got_commit_graph_iter_next(&parent_id, graph, repo,
10874 check_cancelled, NULL);
10875 if (err) {
10876 if (err->code == GOT_ERR_ITER_COMPLETED) {
10877 err = got_error_msg(GOT_ERR_ANCESTRY,
10878 "ran out of commits to rebase before "
10879 "youngest common ancestor commit has "
10880 "been reached?!?");
10882 goto done;
10883 } else {
10884 err = check_path_prefix(&parent_id, &commit_id,
10885 path_prefix, path_prefix_errcode, repo);
10886 if (err)
10887 goto done;
10889 err = got_object_qid_alloc(&qid, &commit_id);
10890 if (err)
10891 goto done;
10892 STAILQ_INSERT_HEAD(commits, qid, entry);
10894 memcpy(&commit_id, &parent_id, sizeof(commit_id));
10897 done:
10898 got_commit_graph_close(graph);
10899 return err;
10902 static const struct got_error *
10903 get_commit_brief_str(char **brief_str, struct got_commit_object *commit)
10905 const struct got_error *err = NULL;
10906 time_t committer_time;
10907 struct tm tm;
10908 char datebuf[11]; /* YYYY-MM-DD + NUL */
10909 char *author0 = NULL, *author, *smallerthan;
10910 char *logmsg0 = NULL, *logmsg, *newline;
10912 committer_time = got_object_commit_get_committer_time(commit);
10913 if (gmtime_r(&committer_time, &tm) == NULL)
10914 return got_error_from_errno("gmtime_r");
10915 if (strftime(datebuf, sizeof(datebuf), "%G-%m-%d", &tm) == 0)
10916 return got_error(GOT_ERR_NO_SPACE);
10918 author0 = strdup(got_object_commit_get_author(commit));
10919 if (author0 == NULL)
10920 return got_error_from_errno("strdup");
10921 author = author0;
10922 smallerthan = strchr(author, '<');
10923 if (smallerthan && smallerthan[1] != '\0')
10924 author = smallerthan + 1;
10925 author[strcspn(author, "@>")] = '\0';
10927 err = got_object_commit_get_logmsg(&logmsg0, commit);
10928 if (err)
10929 goto done;
10930 logmsg = logmsg0;
10931 while (*logmsg == '\n')
10932 logmsg++;
10933 newline = strchr(logmsg, '\n');
10934 if (newline)
10935 *newline = '\0';
10937 if (asprintf(brief_str, "%s %s %s",
10938 datebuf, author, logmsg) == -1)
10939 err = got_error_from_errno("asprintf");
10940 done:
10941 free(author0);
10942 free(logmsg0);
10943 return err;
10946 static const struct got_error *
10947 delete_backup_ref(struct got_reference *ref, struct got_object_id *id,
10948 struct got_repository *repo)
10950 const struct got_error *err;
10951 char *id_str;
10953 err = got_object_id_str(&id_str, id);
10954 if (err)
10955 return err;
10957 err = got_ref_delete(ref, repo);
10958 if (err)
10959 goto done;
10961 printf("Deleted %s: %s\n", got_ref_get_name(ref), id_str);
10962 done:
10963 free(id_str);
10964 return err;
10967 static const struct got_error *
10968 print_backup_ref(const char *branch_name, const char *new_id_str,
10969 struct got_object_id *old_commit_id, struct got_commit_object *old_commit,
10970 struct got_reflist_object_id_map *refs_idmap,
10971 struct got_repository *repo)
10973 const struct got_error *err = NULL;
10974 struct got_reflist_head *refs;
10975 char *refs_str = NULL;
10976 struct got_object_id *new_commit_id = NULL;
10977 struct got_commit_object *new_commit = NULL;
10978 char *new_commit_brief_str = NULL;
10979 struct got_object_id *yca_id = NULL;
10980 struct got_commit_object *yca_commit = NULL;
10981 char *yca_id_str = NULL, *yca_brief_str = NULL;
10982 char *custom_refs_str;
10984 if (asprintf(&custom_refs_str, "formerly %s", branch_name) == -1)
10985 return got_error_from_errno("asprintf");
10987 err = print_commit(old_commit, old_commit_id, repo, NULL, NULL, NULL,
10988 0, 0, refs_idmap, custom_refs_str, NULL);
10989 if (err)
10990 goto done;
10992 err = got_object_resolve_id_str(&new_commit_id, repo, new_id_str);
10993 if (err)
10994 goto done;
10996 refs = got_reflist_object_id_map_lookup(refs_idmap, new_commit_id);
10997 if (refs) {
10998 err = build_refs_str(&refs_str, refs, new_commit_id, repo, 0);
10999 if (err)
11000 goto done;
11003 err = got_object_open_as_commit(&new_commit, repo, new_commit_id);
11004 if (err)
11005 goto done;
11007 err = get_commit_brief_str(&new_commit_brief_str, new_commit);
11008 if (err)
11009 goto done;
11011 err = got_commit_graph_find_youngest_common_ancestor(&yca_id,
11012 old_commit_id, new_commit_id, 1, 0, repo, check_cancelled, NULL);
11013 if (err)
11014 goto done;
11016 printf("has become commit %s%s%s%s\n %s\n", new_id_str,
11017 refs_str ? " (" : "", refs_str ? refs_str : "",
11018 refs_str ? ")" : "", new_commit_brief_str);
11019 if (yca_id && got_object_id_cmp(yca_id, new_commit_id) != 0 &&
11020 got_object_id_cmp(yca_id, old_commit_id) != 0) {
11021 free(refs_str);
11022 refs_str = NULL;
11024 err = got_object_open_as_commit(&yca_commit, repo, yca_id);
11025 if (err)
11026 goto done;
11028 err = get_commit_brief_str(&yca_brief_str, yca_commit);
11029 if (err)
11030 goto done;
11032 err = got_object_id_str(&yca_id_str, yca_id);
11033 if (err)
11034 goto done;
11036 refs = got_reflist_object_id_map_lookup(refs_idmap, yca_id);
11037 if (refs) {
11038 err = build_refs_str(&refs_str, refs, yca_id, repo, 0);
11039 if (err)
11040 goto done;
11042 printf("history forked at %s%s%s%s\n %s\n",
11043 yca_id_str,
11044 refs_str ? " (" : "", refs_str ? refs_str : "",
11045 refs_str ? ")" : "", yca_brief_str);
11047 done:
11048 free(custom_refs_str);
11049 free(new_commit_id);
11050 free(refs_str);
11051 free(yca_id);
11052 free(yca_id_str);
11053 free(yca_brief_str);
11054 if (new_commit)
11055 got_object_commit_close(new_commit);
11056 if (yca_commit)
11057 got_object_commit_close(yca_commit);
11059 return err;
11062 static const struct got_error *
11063 worktree_has_logmsg_ref(const char *caller, struct got_worktree *worktree,
11064 struct got_repository *repo)
11066 const struct got_error *err;
11067 struct got_reflist_head refs;
11068 struct got_reflist_entry *re;
11069 char *uuidstr = NULL;
11070 static char msg[160];
11072 TAILQ_INIT(&refs);
11074 err = got_worktree_get_uuid(&uuidstr, worktree);
11075 if (err)
11076 goto done;
11078 err = got_ref_list(&refs, repo, "refs/got/worktree",
11079 got_ref_cmp_by_name, repo);
11080 if (err)
11081 goto done;
11083 TAILQ_FOREACH(re, &refs, entry) {
11084 const char *cmd, *refname, *type;
11086 refname = got_ref_get_name(re->ref);
11088 if (strncmp(refname, GOT_WORKTREE_CHERRYPICK_REF_PREFIX,
11089 GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN) == 0) {
11090 refname += GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN + 1;
11091 cmd = "cherrypick";
11092 type = "cherrypicked";
11093 } else if (strncmp(refname, GOT_WORKTREE_BACKOUT_REF_PREFIX,
11094 GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN) == 0) {
11095 refname += GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN + 1;
11096 cmd = "backout";
11097 type = "backed-out";
11098 } else
11099 continue;
11101 if (strncmp(refname, uuidstr, GOT_WORKTREE_UUID_STRLEN) != 0)
11102 continue;
11104 snprintf(msg, sizeof(msg),
11105 "work tree has references created by %s commits which "
11106 "must be removed with 'got %s -X' before running the %s "
11107 "command", type, cmd, caller);
11108 err = got_error_msg(GOT_ERR_WORKTREE_META, msg);
11109 goto done;
11112 done:
11113 free(uuidstr);
11114 got_ref_list_free(&refs);
11115 return err;
11118 static const struct got_error *
11119 process_backup_refs(const char *backup_ref_prefix,
11120 const char *wanted_branch_name,
11121 int delete, struct got_repository *repo)
11123 const struct got_error *err;
11124 struct got_reflist_head refs, backup_refs;
11125 struct got_reflist_entry *re;
11126 const size_t backup_ref_prefix_len = strlen(backup_ref_prefix);
11127 struct got_object_id *old_commit_id = NULL;
11128 char *branch_name = NULL;
11129 struct got_commit_object *old_commit = NULL;
11130 struct got_reflist_object_id_map *refs_idmap = NULL;
11131 int wanted_branch_found = 0;
11133 TAILQ_INIT(&refs);
11134 TAILQ_INIT(&backup_refs);
11136 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
11137 if (err)
11138 return err;
11140 err = got_reflist_object_id_map_create(&refs_idmap, &refs, repo);
11141 if (err)
11142 goto done;
11144 if (wanted_branch_name) {
11145 if (strncmp(wanted_branch_name, "refs/heads/", 11) == 0)
11146 wanted_branch_name += 11;
11149 err = got_ref_list(&backup_refs, repo, backup_ref_prefix,
11150 got_ref_cmp_by_commit_timestamp_descending, repo);
11151 if (err)
11152 goto done;
11154 TAILQ_FOREACH(re, &backup_refs, entry) {
11155 const char *refname = got_ref_get_name(re->ref);
11156 char *slash;
11158 err = check_cancelled(NULL);
11159 if (err)
11160 break;
11162 err = got_ref_resolve(&old_commit_id, repo, re->ref);
11163 if (err)
11164 break;
11166 err = got_object_open_as_commit(&old_commit, repo,
11167 old_commit_id);
11168 if (err)
11169 break;
11171 if (strncmp(backup_ref_prefix, refname,
11172 backup_ref_prefix_len) == 0)
11173 refname += backup_ref_prefix_len;
11175 while (refname[0] == '/')
11176 refname++;
11178 branch_name = strdup(refname);
11179 if (branch_name == NULL) {
11180 err = got_error_from_errno("strdup");
11181 break;
11183 slash = strrchr(branch_name, '/');
11184 if (slash) {
11185 *slash = '\0';
11186 refname += strlen(branch_name) + 1;
11189 if (wanted_branch_name == NULL ||
11190 strcmp(wanted_branch_name, branch_name) == 0) {
11191 wanted_branch_found = 1;
11192 if (delete) {
11193 err = delete_backup_ref(re->ref,
11194 old_commit_id, repo);
11195 } else {
11196 err = print_backup_ref(branch_name, refname,
11197 old_commit_id, old_commit, refs_idmap,
11198 repo);
11200 if (err)
11201 break;
11204 free(old_commit_id);
11205 old_commit_id = NULL;
11206 free(branch_name);
11207 branch_name = NULL;
11208 got_object_commit_close(old_commit);
11209 old_commit = NULL;
11212 if (wanted_branch_name && !wanted_branch_found) {
11213 err = got_error_fmt(GOT_ERR_NOT_REF,
11214 "%s/%s/", backup_ref_prefix, wanted_branch_name);
11216 done:
11217 if (refs_idmap)
11218 got_reflist_object_id_map_free(refs_idmap);
11219 got_ref_list_free(&refs);
11220 got_ref_list_free(&backup_refs);
11221 free(old_commit_id);
11222 free(branch_name);
11223 if (old_commit)
11224 got_object_commit_close(old_commit);
11225 return err;
11228 static const struct got_error *
11229 abort_progress(void *arg, unsigned char status, const char *path)
11232 * Unversioned files should not clutter progress output when
11233 * an operation is aborted.
11235 if (status == GOT_STATUS_UNVERSIONED)
11236 return NULL;
11238 return update_progress(arg, status, path);
11241 static const struct got_error *
11242 find_merge_commit_yca(struct got_object_id **new_yca_id,
11243 struct got_object_id *branch_head_commit_id,
11244 struct got_object_id *yca_id,
11245 struct got_object_id *base_commit_id,
11246 struct got_repository *repo)
11248 const struct got_error *err = NULL;
11249 struct got_commit_graph *graph = NULL;
11250 struct got_commit_object *commit = NULL;
11252 *new_yca_id = NULL;
11254 err = got_commit_graph_open(&graph, "/", 1);
11255 if (err)
11256 return err;
11258 err = got_commit_graph_bfsort(graph, base_commit_id,
11259 repo, check_cancelled, NULL);
11260 if (err)
11261 goto done;
11263 for (;;) {
11264 struct got_object_id id;
11266 err = got_commit_graph_iter_next(&id, graph, repo,
11267 check_cancelled, NULL);
11268 if (err) {
11269 if (err->code == GOT_ERR_ITER_COMPLETED)
11270 err = NULL;
11271 break;
11274 err = got_object_open_as_commit(&commit, repo, &id);
11275 if (err)
11276 break;
11278 if (got_object_commit_get_nparents(commit) > 1) {
11279 /* Search for a better YCA using toposort. */
11280 err = got_commit_graph_find_youngest_common_ancestor(
11281 new_yca_id, base_commit_id, branch_head_commit_id,
11282 0, 1, repo, check_cancelled, NULL);
11283 break;
11286 if (got_object_id_cmp(&id, yca_id) == 0)
11287 break;
11288 got_object_commit_close(commit);
11289 commit = NULL;
11291 done:
11292 got_commit_graph_close(graph);
11293 if (commit)
11294 got_object_commit_close(commit);
11295 return err;
11298 static const struct got_error *
11299 cmd_rebase(int argc, char *argv[])
11301 const struct got_error *error = NULL;
11302 struct got_worktree *worktree = NULL;
11303 struct got_repository *repo = NULL;
11304 struct got_fileindex *fileindex = NULL;
11305 char *cwd = NULL, *committer = NULL, *gitconfig_path = NULL;
11306 struct got_reference *branch = NULL;
11307 struct got_reference *new_base_branch = NULL, *tmp_branch = NULL;
11308 struct got_object_id *commit_id = NULL, *parent_id = NULL;
11309 struct got_object_id *resume_commit_id = NULL;
11310 struct got_object_id *branch_head_commit_id = NULL, *yca_id = NULL;
11311 struct got_object_id *head_commit_id = NULL;
11312 struct got_reference *head_ref = NULL;
11313 struct got_commit_object *commit = NULL;
11314 int ch, rebase_in_progress = 0, abort_rebase = 0, continue_rebase = 0;
11315 int histedit_in_progress = 0, merge_in_progress = 0;
11316 int create_backup = 1, list_backups = 0, delete_backups = 0;
11317 int allow_conflict = 0;
11318 struct got_object_id_queue commits;
11319 struct got_pathlist_head merged_paths;
11320 const struct got_object_id_queue *parent_ids;
11321 struct got_object_qid *qid, *pid;
11322 struct got_update_progress_arg upa;
11323 int *pack_fds = NULL;
11325 STAILQ_INIT(&commits);
11326 TAILQ_INIT(&merged_paths);
11327 memset(&upa, 0, sizeof(upa));
11329 #ifndef PROFILE
11330 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
11331 "unveil", NULL) == -1)
11332 err(1, "pledge");
11333 #endif
11335 while ((ch = getopt(argc, argv, "aCclX")) != -1) {
11336 switch (ch) {
11337 case 'a':
11338 abort_rebase = 1;
11339 break;
11340 case 'C':
11341 allow_conflict = 1;
11342 break;
11343 case 'c':
11344 continue_rebase = 1;
11345 break;
11346 case 'l':
11347 list_backups = 1;
11348 break;
11349 case 'X':
11350 delete_backups = 1;
11351 break;
11352 default:
11353 usage_rebase();
11354 /* NOTREACHED */
11358 argc -= optind;
11359 argv += optind;
11361 if (list_backups) {
11362 if (abort_rebase)
11363 option_conflict('l', 'a');
11364 if (allow_conflict)
11365 option_conflict('l', 'C');
11366 if (continue_rebase)
11367 option_conflict('l', 'c');
11368 if (delete_backups)
11369 option_conflict('l', 'X');
11370 if (argc != 0 && argc != 1)
11371 usage_rebase();
11372 } else if (delete_backups) {
11373 if (abort_rebase)
11374 option_conflict('X', 'a');
11375 if (allow_conflict)
11376 option_conflict('X', 'C');
11377 if (continue_rebase)
11378 option_conflict('X', 'c');
11379 if (list_backups)
11380 option_conflict('l', 'X');
11381 if (argc != 0 && argc != 1)
11382 usage_rebase();
11383 } else if (allow_conflict) {
11384 if (abort_rebase)
11385 option_conflict('C', 'a');
11386 if (!continue_rebase)
11387 errx(1, "-C option requires -c");
11388 } else {
11389 if (abort_rebase && continue_rebase)
11390 usage_rebase();
11391 else if (abort_rebase || continue_rebase) {
11392 if (argc != 0)
11393 usage_rebase();
11394 } else if (argc != 1)
11395 usage_rebase();
11398 cwd = getcwd(NULL, 0);
11399 if (cwd == NULL) {
11400 error = got_error_from_errno("getcwd");
11401 goto done;
11404 error = got_repo_pack_fds_open(&pack_fds);
11405 if (error != NULL)
11406 goto done;
11408 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
11409 if (error) {
11410 if (list_backups || delete_backups) {
11411 if (error->code != GOT_ERR_NOT_WORKTREE)
11412 goto done;
11413 } else {
11414 if (error->code == GOT_ERR_NOT_WORKTREE)
11415 error = wrap_not_worktree_error(error,
11416 "rebase", cwd);
11417 goto done;
11421 error = get_gitconfig_path(&gitconfig_path);
11422 if (error)
11423 goto done;
11424 error = got_repo_open(&repo,
11425 worktree ? got_worktree_get_repo_path(worktree) : cwd,
11426 gitconfig_path, pack_fds);
11427 if (error != NULL)
11428 goto done;
11430 if (worktree != NULL && !list_backups && !delete_backups) {
11431 error = worktree_has_logmsg_ref("rebase", worktree, repo);
11432 if (error)
11433 goto done;
11436 error = get_author(&committer, repo, worktree);
11437 if (error && error->code != GOT_ERR_COMMIT_NO_AUTHOR)
11438 goto done;
11440 error = apply_unveil(got_repo_get_path(repo), 0,
11441 worktree ? got_worktree_get_root_path(worktree) : NULL);
11442 if (error)
11443 goto done;
11445 if (list_backups || delete_backups) {
11446 error = process_backup_refs(
11447 GOT_WORKTREE_REBASE_BACKUP_REF_PREFIX,
11448 argc == 1 ? argv[0] : NULL, delete_backups, repo);
11449 goto done; /* nothing else to do */
11452 error = got_worktree_histedit_in_progress(&histedit_in_progress,
11453 worktree);
11454 if (error)
11455 goto done;
11456 if (histedit_in_progress) {
11457 error = got_error(GOT_ERR_HISTEDIT_BUSY);
11458 goto done;
11461 error = got_worktree_merge_in_progress(&merge_in_progress,
11462 worktree, repo);
11463 if (error)
11464 goto done;
11465 if (merge_in_progress) {
11466 error = got_error(GOT_ERR_MERGE_BUSY);
11467 goto done;
11470 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
11471 if (error)
11472 goto done;
11474 if (abort_rebase) {
11475 if (!rebase_in_progress) {
11476 error = got_error(GOT_ERR_NOT_REBASING);
11477 goto done;
11479 error = got_worktree_rebase_continue(&resume_commit_id,
11480 &new_base_branch, &tmp_branch, &branch, &fileindex,
11481 worktree, repo);
11482 if (error)
11483 goto done;
11484 printf("Switching work tree to %s\n",
11485 got_ref_get_symref_target(new_base_branch));
11486 error = got_worktree_rebase_abort(worktree, fileindex, repo,
11487 new_base_branch, abort_progress, &upa);
11488 if (error)
11489 goto done;
11490 printf("Rebase of %s aborted\n", got_ref_get_name(branch));
11491 print_merge_progress_stats(&upa);
11492 goto done; /* nothing else to do */
11495 if (continue_rebase) {
11496 if (!rebase_in_progress) {
11497 error = got_error(GOT_ERR_NOT_REBASING);
11498 goto done;
11500 error = got_worktree_rebase_continue(&resume_commit_id,
11501 &new_base_branch, &tmp_branch, &branch, &fileindex,
11502 worktree, repo);
11503 if (error)
11504 goto done;
11506 error = rebase_commit(NULL, worktree, fileindex, tmp_branch,
11507 committer, resume_commit_id, allow_conflict, repo);
11508 if (error)
11509 goto done;
11511 yca_id = got_object_id_dup(resume_commit_id);
11512 if (yca_id == NULL) {
11513 error = got_error_from_errno("got_object_id_dup");
11514 goto done;
11516 } else {
11517 error = got_ref_open(&branch, repo, argv[0], 0);
11518 if (error != NULL)
11519 goto done;
11520 if (strncmp(got_ref_get_name(branch), "refs/heads/", 11) != 0) {
11521 error = got_error_msg(GOT_ERR_COMMIT_BRANCH,
11522 "will not rebase a branch which lives outside "
11523 "the \"refs/heads/\" reference namespace");
11524 goto done;
11528 error = got_ref_resolve(&branch_head_commit_id, repo, branch);
11529 if (error)
11530 goto done;
11532 if (!continue_rebase) {
11533 struct got_object_id *base_commit_id;
11535 error = got_ref_open(&head_ref, repo,
11536 got_worktree_get_head_ref_name(worktree), 0);
11537 if (error)
11538 goto done;
11539 error = got_ref_resolve(&head_commit_id, repo, head_ref);
11540 if (error)
11541 goto done;
11542 base_commit_id = got_worktree_get_base_commit_id(worktree);
11543 if (got_object_id_cmp(base_commit_id, head_commit_id) != 0) {
11544 error = got_error(GOT_ERR_REBASE_OUT_OF_DATE);
11545 goto done;
11548 error = got_commit_graph_find_youngest_common_ancestor(&yca_id,
11549 base_commit_id, branch_head_commit_id, 1, 0,
11550 repo, check_cancelled, NULL);
11551 if (error) {
11552 if (error->code == GOT_ERR_ANCESTRY) {
11553 error = got_error_msg(GOT_ERR_ANCESTRY,
11554 "specified branch shares no common "
11555 "ancestry with work tree's branch");
11557 goto done;
11561 * If a merge commit appears between the new base branch tip
11562 * and a YCA found via first-parent traversal then we might
11563 * find a better YCA using topologically sorted commits.
11565 if (got_object_id_cmp(base_commit_id, yca_id) != 0) {
11566 struct got_object_id *better_yca_id;
11567 error = find_merge_commit_yca(&better_yca_id,
11568 branch_head_commit_id, yca_id,
11569 base_commit_id, repo);
11570 if (error)
11571 goto done;
11572 if (better_yca_id) {
11573 free(yca_id);
11574 yca_id = better_yca_id;
11578 if (got_object_id_cmp(base_commit_id, yca_id) == 0) {
11579 struct got_pathlist_head paths;
11580 printf("%s is already based on %s\n",
11581 got_ref_get_name(branch),
11582 got_worktree_get_head_ref_name(worktree));
11583 error = switch_head_ref(branch, branch_head_commit_id,
11584 worktree, repo);
11585 if (error)
11586 goto done;
11587 error = got_worktree_set_base_commit_id(worktree, repo,
11588 branch_head_commit_id);
11589 if (error)
11590 goto done;
11591 TAILQ_INIT(&paths);
11592 error = got_pathlist_append(&paths, "", NULL);
11593 if (error)
11594 goto done;
11595 error = got_worktree_checkout_files(worktree,
11596 &paths, repo, update_progress, &upa,
11597 check_cancelled, NULL);
11598 got_pathlist_free(&paths, GOT_PATHLIST_FREE_NONE);
11599 if (error)
11600 goto done;
11601 if (upa.did_something) {
11602 char *id_str;
11603 error = got_object_id_str(&id_str,
11604 branch_head_commit_id);
11605 if (error)
11606 goto done;
11607 printf("Updated to %s: %s\n",
11608 got_worktree_get_head_ref_name(worktree),
11609 id_str);
11610 free(id_str);
11611 } else
11612 printf("Already up-to-date\n");
11613 print_update_progress_stats(&upa);
11614 goto done;
11618 commit_id = branch_head_commit_id;
11619 error = got_object_open_as_commit(&commit, repo, commit_id);
11620 if (error)
11621 goto done;
11623 parent_ids = got_object_commit_get_parent_ids(commit);
11624 pid = STAILQ_FIRST(parent_ids);
11625 if (pid) {
11626 error = collect_commits(&commits, commit_id, &pid->id,
11627 yca_id, got_worktree_get_path_prefix(worktree),
11628 GOT_ERR_REBASE_PATH, repo);
11629 if (error)
11630 goto done;
11633 got_object_commit_close(commit);
11634 commit = NULL;
11636 if (!continue_rebase) {
11637 error = got_worktree_rebase_prepare(&new_base_branch,
11638 &tmp_branch, &fileindex, worktree, branch, repo);
11639 if (error)
11640 goto done;
11643 if (STAILQ_EMPTY(&commits)) {
11644 if (continue_rebase) {
11645 error = rebase_complete(worktree, fileindex,
11646 branch, tmp_branch, repo, create_backup);
11647 goto done;
11648 } else {
11649 /* Fast-forward the reference of the branch. */
11650 struct got_object_id *new_head_commit_id;
11651 char *id_str;
11652 error = got_ref_resolve(&new_head_commit_id, repo,
11653 new_base_branch);
11654 if (error)
11655 goto done;
11656 error = got_object_id_str(&id_str, new_head_commit_id);
11657 if (error)
11658 goto done;
11659 printf("Forwarding %s to commit %s\n",
11660 got_ref_get_name(branch), id_str);
11661 free(id_str);
11662 error = got_ref_change_ref(branch,
11663 new_head_commit_id);
11664 if (error)
11665 goto done;
11666 /* No backup needed since objects did not change. */
11667 create_backup = 0;
11671 pid = NULL;
11672 STAILQ_FOREACH(qid, &commits, entry) {
11674 commit_id = &qid->id;
11675 parent_id = pid ? &pid->id : yca_id;
11676 pid = qid;
11678 memset(&upa, 0, sizeof(upa));
11679 error = got_worktree_rebase_merge_files(&merged_paths,
11680 worktree, fileindex, parent_id, commit_id, repo,
11681 update_progress, &upa, check_cancelled, NULL);
11682 if (error)
11683 goto done;
11685 print_merge_progress_stats(&upa);
11686 if (upa.conflicts > 0 || upa.missing > 0 ||
11687 upa.not_deleted > 0 || upa.unversioned > 0) {
11688 if (upa.conflicts > 0) {
11689 error = show_rebase_merge_conflict(&qid->id,
11690 repo);
11691 if (error)
11692 goto done;
11694 got_pathlist_free(&merged_paths, GOT_PATHLIST_FREE_PATH);
11695 break;
11698 error = rebase_commit(&merged_paths, worktree, fileindex,
11699 tmp_branch, committer, commit_id, 0, repo);
11700 got_pathlist_free(&merged_paths, GOT_PATHLIST_FREE_PATH);
11701 if (error)
11702 goto done;
11705 if (upa.conflicts > 0 || upa.missing > 0 ||
11706 upa.not_deleted > 0 || upa.unversioned > 0) {
11707 error = got_worktree_rebase_postpone(worktree, fileindex);
11708 if (error)
11709 goto done;
11710 if (upa.conflicts > 0 && upa.missing == 0 &&
11711 upa.not_deleted == 0 && upa.unversioned == 0) {
11712 error = got_error_msg(GOT_ERR_CONFLICTS,
11713 "conflicts must be resolved before rebasing "
11714 "can continue");
11715 } else if (upa.conflicts > 0) {
11716 error = got_error_msg(GOT_ERR_CONFLICTS,
11717 "conflicts must be resolved before rebasing "
11718 "can continue; changes destined for some "
11719 "files were not yet merged and should be "
11720 "merged manually if required before the "
11721 "rebase operation is continued");
11722 } else {
11723 error = got_error_msg(GOT_ERR_CONFLICTS,
11724 "changes destined for some files were not "
11725 "yet merged and should be merged manually "
11726 "if required before the rebase operation "
11727 "is continued");
11729 } else
11730 error = rebase_complete(worktree, fileindex, branch,
11731 tmp_branch, repo, create_backup);
11732 done:
11733 free(cwd);
11734 free(committer);
11735 free(gitconfig_path);
11736 got_object_id_queue_free(&commits);
11737 free(branch_head_commit_id);
11738 free(resume_commit_id);
11739 free(head_commit_id);
11740 free(yca_id);
11741 if (commit)
11742 got_object_commit_close(commit);
11743 if (branch)
11744 got_ref_close(branch);
11745 if (new_base_branch)
11746 got_ref_close(new_base_branch);
11747 if (tmp_branch)
11748 got_ref_close(tmp_branch);
11749 if (head_ref)
11750 got_ref_close(head_ref);
11751 if (worktree)
11752 got_worktree_close(worktree);
11753 if (repo) {
11754 const struct got_error *close_err = got_repo_close(repo);
11755 if (error == NULL)
11756 error = close_err;
11758 if (pack_fds) {
11759 const struct got_error *pack_err =
11760 got_repo_pack_fds_close(pack_fds);
11761 if (error == NULL)
11762 error = pack_err;
11764 return error;
11767 __dead static void
11768 usage_histedit(void)
11770 fprintf(stderr, "usage: %s histedit [-aCcdeflmX] [-F histedit-script] "
11771 "[branch]\n", getprogname());
11772 exit(1);
11775 #define GOT_HISTEDIT_PICK 'p'
11776 #define GOT_HISTEDIT_EDIT 'e'
11777 #define GOT_HISTEDIT_FOLD 'f'
11778 #define GOT_HISTEDIT_DROP 'd'
11779 #define GOT_HISTEDIT_MESG 'm'
11781 static const struct got_histedit_cmd {
11782 unsigned char code;
11783 const char *name;
11784 const char *desc;
11785 } got_histedit_cmds[] = {
11786 { GOT_HISTEDIT_PICK, "pick", "use commit" },
11787 { GOT_HISTEDIT_EDIT, "edit", "use commit but stop for amending" },
11788 { GOT_HISTEDIT_FOLD, "fold", "combine with next commit that will "
11789 "be used" },
11790 { GOT_HISTEDIT_DROP, "drop", "remove commit from history" },
11791 { GOT_HISTEDIT_MESG, "mesg", "open editor to edit the log message" },
11794 struct got_histedit_list_entry {
11795 TAILQ_ENTRY(got_histedit_list_entry) entry;
11796 struct got_object_id *commit_id;
11797 const struct got_histedit_cmd *cmd;
11798 char *logmsg;
11800 TAILQ_HEAD(got_histedit_list, got_histedit_list_entry);
11802 static const struct got_error *
11803 histedit_write_commit(struct got_object_id *commit_id, const char *cmdname,
11804 FILE *f, struct got_repository *repo)
11806 const struct got_error *err = NULL;
11807 char *logmsg = NULL, *id_str = NULL;
11808 struct got_commit_object *commit = NULL;
11809 int n;
11811 err = got_object_open_as_commit(&commit, repo, commit_id);
11812 if (err)
11813 goto done;
11815 err = get_short_logmsg(&logmsg, 34, commit);
11816 if (err)
11817 goto done;
11819 err = got_object_id_str(&id_str, commit_id);
11820 if (err)
11821 goto done;
11823 n = fprintf(f, "%s %s %s\n", cmdname, id_str, logmsg);
11824 if (n < 0)
11825 err = got_ferror(f, GOT_ERR_IO);
11826 done:
11827 if (commit)
11828 got_object_commit_close(commit);
11829 free(id_str);
11830 free(logmsg);
11831 return err;
11834 static const struct got_error *
11835 histedit_write_commit_list(struct got_object_id_queue *commits,
11836 FILE *f, int edit_logmsg_only, int fold_only, int drop_only,
11837 int edit_only, struct got_repository *repo)
11839 const struct got_error *err = NULL;
11840 struct got_object_qid *qid;
11841 const char *histedit_cmd = NULL;
11843 if (STAILQ_EMPTY(commits))
11844 return got_error(GOT_ERR_EMPTY_HISTEDIT);
11846 STAILQ_FOREACH(qid, commits, entry) {
11847 histedit_cmd = got_histedit_cmds[0].name;
11848 if (drop_only)
11849 histedit_cmd = "drop";
11850 else if (edit_only)
11851 histedit_cmd = "edit";
11852 else if (fold_only && STAILQ_NEXT(qid, entry) != NULL)
11853 histedit_cmd = "fold";
11854 else if (edit_logmsg_only)
11855 histedit_cmd = "mesg";
11856 err = histedit_write_commit(&qid->id, histedit_cmd, f, repo);
11857 if (err)
11858 break;
11861 return err;
11864 static const struct got_error *
11865 write_cmd_list(FILE *f, const char *branch_name,
11866 struct got_object_id_queue *commits)
11868 const struct got_error *err = NULL;
11869 size_t i;
11870 int n;
11871 char *id_str;
11872 struct got_object_qid *qid;
11874 qid = STAILQ_FIRST(commits);
11875 err = got_object_id_str(&id_str, &qid->id);
11876 if (err)
11877 return err;
11879 n = fprintf(f,
11880 "# Editing the history of branch '%s' starting at\n"
11881 "# commit %s\n"
11882 "# Commits will be processed in order from top to "
11883 "bottom of this file.\n", branch_name, id_str);
11884 if (n < 0) {
11885 err = got_ferror(f, GOT_ERR_IO);
11886 goto done;
11889 n = fprintf(f, "# Available histedit commands:\n");
11890 if (n < 0) {
11891 err = got_ferror(f, GOT_ERR_IO);
11892 goto done;
11895 for (i = 0; i < nitems(got_histedit_cmds); i++) {
11896 const struct got_histedit_cmd *cmd = &got_histedit_cmds[i];
11897 n = fprintf(f, "# %s (%c): %s\n", cmd->name, cmd->code,
11898 cmd->desc);
11899 if (n < 0) {
11900 err = got_ferror(f, GOT_ERR_IO);
11901 break;
11904 done:
11905 free(id_str);
11906 return err;
11909 static const struct got_error *
11910 histedit_syntax_error(int lineno)
11912 static char msg[42];
11913 int ret;
11915 ret = snprintf(msg, sizeof(msg), "histedit syntax error on line %d",
11916 lineno);
11917 if (ret < 0 || (size_t)ret >= sizeof(msg))
11918 return got_error(GOT_ERR_HISTEDIT_SYNTAX);
11920 return got_error_msg(GOT_ERR_HISTEDIT_SYNTAX, msg);
11923 static const struct got_error *
11924 append_folded_commit_msg(char **new_msg, struct got_histedit_list_entry *hle,
11925 char *logmsg, struct got_repository *repo)
11927 const struct got_error *err;
11928 struct got_commit_object *folded_commit = NULL;
11929 char *id_str, *folded_logmsg = NULL;
11931 err = got_object_id_str(&id_str, hle->commit_id);
11932 if (err)
11933 return err;
11935 err = got_object_open_as_commit(&folded_commit, repo, hle->commit_id);
11936 if (err)
11937 goto done;
11939 err = got_object_commit_get_logmsg(&folded_logmsg, folded_commit);
11940 if (err)
11941 goto done;
11942 if (asprintf(new_msg, "%s%s# log message of folded commit %s: %s",
11943 logmsg ? logmsg : "", logmsg ? "\n" : "", id_str,
11944 folded_logmsg) == -1) {
11945 err = got_error_from_errno("asprintf");
11947 done:
11948 if (folded_commit)
11949 got_object_commit_close(folded_commit);
11950 free(id_str);
11951 free(folded_logmsg);
11952 return err;
11955 static struct got_histedit_list_entry *
11956 get_folded_commits(struct got_histedit_list_entry *hle)
11958 struct got_histedit_list_entry *prev, *folded = NULL;
11960 prev = TAILQ_PREV(hle, got_histedit_list, entry);
11961 while (prev && (prev->cmd->code == GOT_HISTEDIT_FOLD ||
11962 prev->cmd->code == GOT_HISTEDIT_DROP)) {
11963 if (prev->cmd->code == GOT_HISTEDIT_FOLD)
11964 folded = prev;
11965 prev = TAILQ_PREV(prev, got_histedit_list, entry);
11968 return folded;
11971 static const struct got_error *
11972 histedit_edit_logmsg(struct got_histedit_list_entry *hle,
11973 const char *editor, struct got_repository *repo)
11975 char *logmsg_path = NULL, *id_str = NULL, *orig_logmsg = NULL;
11976 char *logmsg = NULL, *new_msg = NULL;
11977 const struct got_error *err = NULL;
11978 struct got_commit_object *commit = NULL;
11979 int logmsg_len;
11980 int fd = -1;
11981 struct got_histedit_list_entry *folded = NULL;
11983 err = got_object_open_as_commit(&commit, repo, hle->commit_id);
11984 if (err)
11985 return err;
11987 folded = get_folded_commits(hle);
11988 if (folded) {
11989 while (folded != hle) {
11990 if (folded->cmd->code == GOT_HISTEDIT_DROP) {
11991 folded = TAILQ_NEXT(folded, entry);
11992 continue;
11994 err = append_folded_commit_msg(&new_msg, folded,
11995 logmsg, repo);
11996 if (err)
11997 goto done;
11998 free(logmsg);
11999 logmsg = new_msg;
12000 folded = TAILQ_NEXT(folded, entry);
12004 err = got_object_id_str(&id_str, hle->commit_id);
12005 if (err)
12006 goto done;
12007 err = got_object_commit_get_logmsg(&orig_logmsg, commit);
12008 if (err)
12009 goto done;
12010 logmsg_len = asprintf(&new_msg,
12011 "%s\n# original log message of commit %s: %s",
12012 logmsg ? logmsg : "", id_str, orig_logmsg);
12013 if (logmsg_len == -1) {
12014 err = got_error_from_errno("asprintf");
12015 goto done;
12017 free(logmsg);
12018 logmsg = new_msg;
12020 err = got_object_id_str(&id_str, hle->commit_id);
12021 if (err)
12022 goto done;
12024 err = got_opentemp_named_fd(&logmsg_path, &fd,
12025 GOT_TMPDIR_STR "/got-logmsg", "");
12026 if (err)
12027 goto done;
12029 if (write(fd, logmsg, logmsg_len) == -1) {
12030 err = got_error_from_errno2("write", logmsg_path);
12031 goto done;
12033 if (close(fd) == -1) {
12034 err = got_error_from_errno2("close", logmsg_path);
12035 goto done;
12037 fd = -1;
12039 err = edit_logmsg(&hle->logmsg, editor, logmsg_path, logmsg,
12040 logmsg_len, 0);
12041 if (err) {
12042 if (err->code != GOT_ERR_COMMIT_MSG_EMPTY)
12043 goto done;
12044 err = NULL;
12045 hle->logmsg = strdup(new_msg);
12046 if (hle->logmsg == NULL)
12047 err = got_error_from_errno("strdup");
12049 done:
12050 if (fd != -1 && close(fd) == -1 && err == NULL)
12051 err = got_error_from_errno2("close", logmsg_path);
12052 if (logmsg_path && unlink(logmsg_path) != 0 && err == NULL)
12053 err = got_error_from_errno2("unlink", logmsg_path);
12054 free(logmsg_path);
12055 free(logmsg);
12056 free(orig_logmsg);
12057 if (commit)
12058 got_object_commit_close(commit);
12059 return err;
12062 static const struct got_error *
12063 histedit_parse_list(struct got_histedit_list *histedit_cmds,
12064 FILE *f, struct got_repository *repo)
12066 const struct got_error *err = NULL;
12067 char *line = NULL, *p, *end;
12068 size_t i, linesize = 0;
12069 ssize_t linelen;
12070 int lineno = 0;
12071 const struct got_histedit_cmd *cmd;
12072 struct got_object_id *commit_id = NULL;
12073 struct got_histedit_list_entry *hle = NULL;
12075 for (;;) {
12076 linelen = getline(&line, &linesize, f);
12077 if (linelen == -1) {
12078 const struct got_error *getline_err;
12079 if (feof(f))
12080 break;
12081 getline_err = got_error_from_errno("getline");
12082 err = got_ferror(f, getline_err->code);
12083 break;
12085 lineno++;
12086 p = line;
12087 while (isspace((unsigned char)p[0]))
12088 p++;
12089 if (p[0] == '#' || p[0] == '\0')
12090 continue;
12091 cmd = NULL;
12092 for (i = 0; i < nitems(got_histedit_cmds); i++) {
12093 cmd = &got_histedit_cmds[i];
12094 if (strncmp(cmd->name, p, strlen(cmd->name)) == 0 &&
12095 isspace((unsigned char)p[strlen(cmd->name)])) {
12096 p += strlen(cmd->name);
12097 break;
12099 if (p[0] == cmd->code && isspace((unsigned char)p[1])) {
12100 p++;
12101 break;
12104 if (i == nitems(got_histedit_cmds)) {
12105 err = histedit_syntax_error(lineno);
12106 break;
12108 while (isspace((unsigned char)p[0]))
12109 p++;
12110 end = p;
12111 while (end[0] && !isspace((unsigned char)end[0]))
12112 end++;
12113 *end = '\0';
12114 err = got_object_resolve_id_str(&commit_id, repo, p);
12115 if (err) {
12116 /* override error code */
12117 err = histedit_syntax_error(lineno);
12118 break;
12120 hle = malloc(sizeof(*hle));
12121 if (hle == NULL) {
12122 err = got_error_from_errno("malloc");
12123 break;
12125 hle->cmd = cmd;
12126 hle->commit_id = commit_id;
12127 hle->logmsg = NULL;
12128 commit_id = NULL;
12129 TAILQ_INSERT_TAIL(histedit_cmds, hle, entry);
12132 free(line);
12133 free(commit_id);
12134 return err;
12137 static const struct got_error *
12138 histedit_check_script(struct got_histedit_list *histedit_cmds,
12139 struct got_object_id_queue *commits, struct got_repository *repo)
12141 const struct got_error *err = NULL;
12142 struct got_object_qid *qid;
12143 struct got_histedit_list_entry *hle;
12144 static char msg[92];
12145 char *id_str;
12147 if (TAILQ_EMPTY(histedit_cmds))
12148 return got_error_msg(GOT_ERR_EMPTY_HISTEDIT,
12149 "histedit script contains no commands");
12150 if (STAILQ_EMPTY(commits))
12151 return got_error(GOT_ERR_EMPTY_HISTEDIT);
12153 TAILQ_FOREACH(hle, histedit_cmds, entry) {
12154 struct got_histedit_list_entry *hle2;
12155 TAILQ_FOREACH(hle2, histedit_cmds, entry) {
12156 if (hle == hle2)
12157 continue;
12158 if (got_object_id_cmp(hle->commit_id,
12159 hle2->commit_id) != 0)
12160 continue;
12161 err = got_object_id_str(&id_str, hle->commit_id);
12162 if (err)
12163 return err;
12164 snprintf(msg, sizeof(msg), "commit %s is listed "
12165 "more than once in histedit script", id_str);
12166 free(id_str);
12167 return got_error_msg(GOT_ERR_HISTEDIT_CMD, msg);
12171 STAILQ_FOREACH(qid, commits, entry) {
12172 TAILQ_FOREACH(hle, histedit_cmds, entry) {
12173 if (got_object_id_cmp(&qid->id, hle->commit_id) == 0)
12174 break;
12176 if (hle == NULL) {
12177 err = got_object_id_str(&id_str, &qid->id);
12178 if (err)
12179 return err;
12180 snprintf(msg, sizeof(msg),
12181 "commit %s missing from histedit script", id_str);
12182 free(id_str);
12183 return got_error_msg(GOT_ERR_HISTEDIT_CMD, msg);
12187 hle = TAILQ_LAST(histedit_cmds, got_histedit_list);
12188 if (hle && hle->cmd->code == GOT_HISTEDIT_FOLD)
12189 return got_error_msg(GOT_ERR_HISTEDIT_CMD,
12190 "last commit in histedit script cannot be folded");
12192 return NULL;
12195 static const struct got_error *
12196 histedit_run_editor(struct got_histedit_list *histedit_cmds,
12197 const char *editor, const char *path,
12198 struct got_object_id_queue *commits, struct got_repository *repo)
12200 const struct got_error *err = NULL;
12201 struct stat st, st2;
12202 struct timespec timeout;
12203 FILE *f = NULL;
12205 if (stat(path, &st) == -1) {
12206 err = got_error_from_errno2("stat", path);
12207 goto done;
12210 if (spawn_editor(editor, path) == -1) {
12211 err = got_error_from_errno("failed spawning editor");
12212 goto done;
12215 timeout.tv_sec = 0;
12216 timeout.tv_nsec = 1;
12217 nanosleep(&timeout, NULL);
12219 if (stat(path, &st2) == -1) {
12220 err = got_error_from_errno2("stat", path);
12221 goto done;
12224 if (st.st_size == st2.st_size &&
12225 timespeccmp(&st.st_mtim, &st2.st_mtim, ==)) {
12226 err = got_error_msg(GOT_ERR_EMPTY_HISTEDIT,
12227 "no changes made to histedit script, aborting");
12228 goto done;
12231 f = fopen(path, "re");
12232 if (f == NULL) {
12233 err = got_error_from_errno("fopen");
12234 goto done;
12236 err = histedit_parse_list(histedit_cmds, f, repo);
12237 if (err)
12238 goto done;
12240 err = histedit_check_script(histedit_cmds, commits, repo);
12241 done:
12242 if (f && fclose(f) == EOF && err == NULL)
12243 err = got_error_from_errno("fclose");
12244 return err;
12247 static const struct got_error *
12248 histedit_edit_list_retry(struct got_histedit_list *, const struct got_error *,
12249 struct got_object_id_queue *, const char *, const char *, const char *,
12250 struct got_repository *);
12252 static const struct got_error *
12253 histedit_edit_script(struct got_histedit_list *histedit_cmds,
12254 struct got_object_id_queue *commits, const char *branch_name,
12255 int edit_logmsg_only, int fold_only, int drop_only, int edit_only,
12256 const char *editor, struct got_repository *repo)
12258 const struct got_error *err;
12259 FILE *f = NULL;
12260 char *path = NULL;
12262 err = got_opentemp_named(&path, &f, "got-histedit", "");
12263 if (err)
12264 return err;
12266 err = write_cmd_list(f, branch_name, commits);
12267 if (err)
12268 goto done;
12270 err = histedit_write_commit_list(commits, f, edit_logmsg_only,
12271 fold_only, drop_only, edit_only, repo);
12272 if (err)
12273 goto done;
12275 if (drop_only || edit_logmsg_only || fold_only || edit_only) {
12276 rewind(f);
12277 err = histedit_parse_list(histedit_cmds, f, repo);
12278 } else {
12279 if (fclose(f) == EOF) {
12280 err = got_error_from_errno("fclose");
12281 goto done;
12283 f = NULL;
12284 err = histedit_run_editor(histedit_cmds, editor, path,
12285 commits, repo);
12286 if (err) {
12287 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
12288 err->code != GOT_ERR_HISTEDIT_CMD)
12289 goto done;
12290 err = histedit_edit_list_retry(histedit_cmds, err,
12291 commits, editor, path, branch_name, repo);
12294 done:
12295 if (f && fclose(f) == EOF && err == NULL)
12296 err = got_error_from_errno("fclose");
12297 if (path && unlink(path) != 0 && err == NULL)
12298 err = got_error_from_errno2("unlink", path);
12299 free(path);
12300 return err;
12303 static const struct got_error *
12304 histedit_save_list(struct got_histedit_list *histedit_cmds,
12305 struct got_worktree *worktree, struct got_repository *repo)
12307 const struct got_error *err = NULL;
12308 char *path = NULL;
12309 FILE *f = NULL;
12310 struct got_histedit_list_entry *hle;
12312 err = got_worktree_get_histedit_script_path(&path, worktree);
12313 if (err)
12314 return err;
12316 f = fopen(path, "we");
12317 if (f == NULL) {
12318 err = got_error_from_errno2("fopen", path);
12319 goto done;
12321 TAILQ_FOREACH(hle, histedit_cmds, entry) {
12322 err = histedit_write_commit(hle->commit_id, hle->cmd->name, f,
12323 repo);
12324 if (err)
12325 break;
12327 done:
12328 if (f && fclose(f) == EOF && err == NULL)
12329 err = got_error_from_errno("fclose");
12330 free(path);
12331 return err;
12334 static void
12335 histedit_free_list(struct got_histedit_list *histedit_cmds)
12337 struct got_histedit_list_entry *hle;
12339 while ((hle = TAILQ_FIRST(histedit_cmds))) {
12340 TAILQ_REMOVE(histedit_cmds, hle, entry);
12341 free(hle);
12345 static const struct got_error *
12346 histedit_load_list(struct got_histedit_list *histedit_cmds,
12347 const char *path, struct got_repository *repo)
12349 const struct got_error *err = NULL;
12350 FILE *f = NULL;
12352 f = fopen(path, "re");
12353 if (f == NULL) {
12354 err = got_error_from_errno2("fopen", path);
12355 goto done;
12358 err = histedit_parse_list(histedit_cmds, f, repo);
12359 done:
12360 if (f && fclose(f) == EOF && err == NULL)
12361 err = got_error_from_errno("fclose");
12362 return err;
12365 static const struct got_error *
12366 histedit_edit_list_retry(struct got_histedit_list *histedit_cmds,
12367 const struct got_error *edit_err, struct got_object_id_queue *commits,
12368 const char *editor, const char *path, const char *branch_name,
12369 struct got_repository *repo)
12371 const struct got_error *err = NULL, *prev_err = edit_err;
12372 int resp = ' ';
12374 while (resp != 'c' && resp != 'r' && resp != 'a') {
12375 printf("%s: %s\n(c)ontinue editing, (r)estart editing, "
12376 "or (a)bort: ", getprogname(), prev_err->msg);
12377 resp = getchar();
12378 if (resp == '\n')
12379 resp = getchar();
12380 if (resp == 'c') {
12381 histedit_free_list(histedit_cmds);
12382 err = histedit_run_editor(histedit_cmds, editor, path,
12383 commits, repo);
12384 if (err) {
12385 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
12386 err->code != GOT_ERR_HISTEDIT_CMD)
12387 break;
12388 prev_err = err;
12389 resp = ' ';
12390 continue;
12392 break;
12393 } else if (resp == 'r') {
12394 histedit_free_list(histedit_cmds);
12395 err = histedit_edit_script(histedit_cmds,
12396 commits, branch_name, 0, 0, 0, 0, editor, 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 == 'a') {
12407 err = got_error(GOT_ERR_HISTEDIT_CANCEL);
12408 break;
12409 } else
12410 printf("invalid response '%c'\n", resp);
12413 return err;
12416 static const struct got_error *
12417 histedit_complete(struct got_worktree *worktree,
12418 struct got_fileindex *fileindex, struct got_reference *tmp_branch,
12419 struct got_reference *branch, struct got_repository *repo)
12421 printf("Switching work tree to %s\n",
12422 got_ref_get_symref_target(branch));
12423 return got_worktree_histedit_complete(worktree, fileindex, tmp_branch,
12424 branch, repo);
12427 static const struct got_error *
12428 show_histedit_progress(struct got_commit_object *commit,
12429 struct got_histedit_list_entry *hle, struct got_object_id *new_id)
12431 const struct got_error *err;
12432 char *old_id_str = NULL, *new_id_str = NULL, *logmsg = NULL;
12434 err = got_object_id_str(&old_id_str, hle->commit_id);
12435 if (err)
12436 goto done;
12438 if (new_id) {
12439 err = got_object_id_str(&new_id_str, new_id);
12440 if (err)
12441 goto done;
12444 old_id_str[12] = '\0';
12445 if (new_id_str)
12446 new_id_str[12] = '\0';
12448 if (hle->logmsg) {
12449 logmsg = strdup(hle->logmsg);
12450 if (logmsg == NULL) {
12451 err = got_error_from_errno("strdup");
12452 goto done;
12454 trim_logmsg(logmsg, 42);
12455 } else {
12456 err = get_short_logmsg(&logmsg, 42, commit);
12457 if (err)
12458 goto done;
12461 switch (hle->cmd->code) {
12462 case GOT_HISTEDIT_PICK:
12463 case GOT_HISTEDIT_EDIT:
12464 case GOT_HISTEDIT_MESG:
12465 printf("%s -> %s: %s\n", old_id_str,
12466 new_id_str ? new_id_str : "no-op change", logmsg);
12467 break;
12468 case GOT_HISTEDIT_DROP:
12469 case GOT_HISTEDIT_FOLD:
12470 printf("%s -> %s commit: %s\n", old_id_str, hle->cmd->name,
12471 logmsg);
12472 break;
12473 default:
12474 break;
12476 done:
12477 free(old_id_str);
12478 free(new_id_str);
12479 return err;
12482 static const struct got_error *
12483 histedit_commit(struct got_pathlist_head *merged_paths,
12484 struct got_worktree *worktree, struct got_fileindex *fileindex,
12485 struct got_reference *tmp_branch, struct got_histedit_list_entry *hle,
12486 const char *committer, int allow_conflict, const char *editor,
12487 struct got_repository *repo)
12489 const struct got_error *err;
12490 struct got_commit_object *commit;
12491 struct got_object_id *new_commit_id;
12493 if ((hle->cmd->code == GOT_HISTEDIT_EDIT || get_folded_commits(hle))
12494 && hle->logmsg == NULL) {
12495 err = histedit_edit_logmsg(hle, editor, repo);
12496 if (err)
12497 return err;
12500 err = got_object_open_as_commit(&commit, repo, hle->commit_id);
12501 if (err)
12502 return err;
12504 err = got_worktree_histedit_commit(&new_commit_id, merged_paths,
12505 worktree, fileindex, tmp_branch, committer, commit, hle->commit_id,
12506 hle->logmsg, allow_conflict, repo);
12507 if (err) {
12508 if (err->code != GOT_ERR_COMMIT_NO_CHANGES)
12509 goto done;
12510 err = show_histedit_progress(commit, hle, NULL);
12511 } else {
12512 err = show_histedit_progress(commit, hle, new_commit_id);
12513 free(new_commit_id);
12515 done:
12516 got_object_commit_close(commit);
12517 return err;
12520 static const struct got_error *
12521 histedit_skip_commit(struct got_histedit_list_entry *hle,
12522 struct got_worktree *worktree, struct got_repository *repo)
12524 const struct got_error *error;
12525 struct got_commit_object *commit;
12527 error = got_worktree_histedit_skip_commit(worktree, hle->commit_id,
12528 repo);
12529 if (error)
12530 return error;
12532 error = got_object_open_as_commit(&commit, repo, hle->commit_id);
12533 if (error)
12534 return error;
12536 error = show_histedit_progress(commit, hle, NULL);
12537 got_object_commit_close(commit);
12538 return error;
12541 static const struct got_error *
12542 check_local_changes(void *arg, unsigned char status,
12543 unsigned char staged_status, const char *path,
12544 struct got_object_id *blob_id, struct got_object_id *staged_blob_id,
12545 struct got_object_id *commit_id, int dirfd, const char *de_name)
12547 int *have_local_changes = arg;
12549 switch (status) {
12550 case GOT_STATUS_ADD:
12551 case GOT_STATUS_DELETE:
12552 case GOT_STATUS_MODIFY:
12553 case GOT_STATUS_CONFLICT:
12554 *have_local_changes = 1;
12555 return got_error(GOT_ERR_CANCELLED);
12556 default:
12557 break;
12560 switch (staged_status) {
12561 case GOT_STATUS_ADD:
12562 case GOT_STATUS_DELETE:
12563 case GOT_STATUS_MODIFY:
12564 *have_local_changes = 1;
12565 return got_error(GOT_ERR_CANCELLED);
12566 default:
12567 break;
12570 return NULL;
12573 static const struct got_error *
12574 cmd_histedit(int argc, char *argv[])
12576 const struct got_error *error = NULL;
12577 struct got_worktree *worktree = NULL;
12578 struct got_fileindex *fileindex = NULL;
12579 struct got_repository *repo = NULL;
12580 char *cwd = NULL, *committer = NULL, *gitconfig_path = NULL;
12581 struct got_reference *branch = NULL;
12582 struct got_reference *tmp_branch = NULL;
12583 struct got_object_id *resume_commit_id = NULL;
12584 struct got_object_id *base_commit_id = NULL;
12585 struct got_object_id *head_commit_id = NULL;
12586 struct got_commit_object *commit = NULL;
12587 int ch, rebase_in_progress = 0, merge_in_progress = 0;
12588 struct got_update_progress_arg upa;
12589 int edit_in_progress = 0, abort_edit = 0, continue_edit = 0;
12590 int drop_only = 0, edit_logmsg_only = 0, fold_only = 0, edit_only = 0;
12591 int allow_conflict = 0, list_backups = 0, delete_backups = 0;
12592 const char *edit_script_path = NULL;
12593 char *editor = NULL;
12594 struct got_object_id_queue commits;
12595 struct got_pathlist_head merged_paths;
12596 const struct got_object_id_queue *parent_ids;
12597 struct got_object_qid *pid;
12598 struct got_histedit_list histedit_cmds;
12599 struct got_histedit_list_entry *hle;
12600 int *pack_fds = NULL;
12602 STAILQ_INIT(&commits);
12603 TAILQ_INIT(&histedit_cmds);
12604 TAILQ_INIT(&merged_paths);
12605 memset(&upa, 0, sizeof(upa));
12607 #ifndef PROFILE
12608 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
12609 "unveil", NULL) == -1)
12610 err(1, "pledge");
12611 #endif
12613 while ((ch = getopt(argc, argv, "aCcdeF:flmX")) != -1) {
12614 switch (ch) {
12615 case 'a':
12616 abort_edit = 1;
12617 break;
12618 case 'C':
12619 allow_conflict = 1;
12620 break;
12621 case 'c':
12622 continue_edit = 1;
12623 break;
12624 case 'd':
12625 drop_only = 1;
12626 break;
12627 case 'e':
12628 edit_only = 1;
12629 break;
12630 case 'F':
12631 edit_script_path = optarg;
12632 break;
12633 case 'f':
12634 fold_only = 1;
12635 break;
12636 case 'l':
12637 list_backups = 1;
12638 break;
12639 case 'm':
12640 edit_logmsg_only = 1;
12641 break;
12642 case 'X':
12643 delete_backups = 1;
12644 break;
12645 default:
12646 usage_histedit();
12647 /* NOTREACHED */
12651 argc -= optind;
12652 argv += optind;
12654 if (abort_edit && allow_conflict)
12655 option_conflict('a', 'C');
12656 if (abort_edit && continue_edit)
12657 option_conflict('a', 'c');
12658 if (edit_script_path && allow_conflict)
12659 option_conflict('F', 'C');
12660 if (edit_script_path && edit_logmsg_only)
12661 option_conflict('F', 'm');
12662 if (abort_edit && edit_logmsg_only)
12663 option_conflict('a', 'm');
12664 if (edit_logmsg_only && allow_conflict)
12665 option_conflict('m', 'C');
12666 if (continue_edit && edit_logmsg_only)
12667 option_conflict('c', 'm');
12668 if (abort_edit && fold_only)
12669 option_conflict('a', 'f');
12670 if (fold_only && allow_conflict)
12671 option_conflict('f', 'C');
12672 if (continue_edit && fold_only)
12673 option_conflict('c', 'f');
12674 if (fold_only && edit_logmsg_only)
12675 option_conflict('f', 'm');
12676 if (edit_script_path && fold_only)
12677 option_conflict('F', 'f');
12678 if (abort_edit && edit_only)
12679 option_conflict('a', 'e');
12680 if (continue_edit && edit_only)
12681 option_conflict('c', 'e');
12682 if (edit_only && edit_logmsg_only)
12683 option_conflict('e', 'm');
12684 if (edit_script_path && edit_only)
12685 option_conflict('F', 'e');
12686 if (fold_only && edit_only)
12687 option_conflict('f', 'e');
12688 if (drop_only && abort_edit)
12689 option_conflict('d', 'a');
12690 if (drop_only && allow_conflict)
12691 option_conflict('d', 'C');
12692 if (drop_only && continue_edit)
12693 option_conflict('d', 'c');
12694 if (drop_only && edit_logmsg_only)
12695 option_conflict('d', 'm');
12696 if (drop_only && edit_only)
12697 option_conflict('d', 'e');
12698 if (drop_only && edit_script_path)
12699 option_conflict('d', 'F');
12700 if (drop_only && fold_only)
12701 option_conflict('d', 'f');
12702 if (list_backups) {
12703 if (abort_edit)
12704 option_conflict('l', 'a');
12705 if (allow_conflict)
12706 option_conflict('l', 'C');
12707 if (continue_edit)
12708 option_conflict('l', 'c');
12709 if (edit_script_path)
12710 option_conflict('l', 'F');
12711 if (edit_logmsg_only)
12712 option_conflict('l', 'm');
12713 if (drop_only)
12714 option_conflict('l', 'd');
12715 if (fold_only)
12716 option_conflict('l', 'f');
12717 if (edit_only)
12718 option_conflict('l', 'e');
12719 if (delete_backups)
12720 option_conflict('l', 'X');
12721 if (argc != 0 && argc != 1)
12722 usage_histedit();
12723 } else if (delete_backups) {
12724 if (abort_edit)
12725 option_conflict('X', 'a');
12726 if (allow_conflict)
12727 option_conflict('X', 'C');
12728 if (continue_edit)
12729 option_conflict('X', 'c');
12730 if (drop_only)
12731 option_conflict('X', 'd');
12732 if (edit_script_path)
12733 option_conflict('X', 'F');
12734 if (edit_logmsg_only)
12735 option_conflict('X', 'm');
12736 if (fold_only)
12737 option_conflict('X', 'f');
12738 if (edit_only)
12739 option_conflict('X', 'e');
12740 if (list_backups)
12741 option_conflict('X', 'l');
12742 if (argc != 0 && argc != 1)
12743 usage_histedit();
12744 } else if (allow_conflict && !continue_edit)
12745 errx(1, "-C option requires -c");
12746 else if (argc != 0)
12747 usage_histedit();
12749 cwd = getcwd(NULL, 0);
12750 if (cwd == NULL) {
12751 error = got_error_from_errno("getcwd");
12752 goto done;
12755 error = got_repo_pack_fds_open(&pack_fds);
12756 if (error != NULL)
12757 goto done;
12759 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
12760 if (error) {
12761 if (list_backups || delete_backups) {
12762 if (error->code != GOT_ERR_NOT_WORKTREE)
12763 goto done;
12764 } else {
12765 if (error->code == GOT_ERR_NOT_WORKTREE)
12766 error = wrap_not_worktree_error(error,
12767 "histedit", cwd);
12768 goto done;
12772 if (list_backups || delete_backups) {
12773 error = got_repo_open(&repo,
12774 worktree ? got_worktree_get_repo_path(worktree) : cwd,
12775 NULL, pack_fds);
12776 if (error != NULL)
12777 goto done;
12778 error = apply_unveil(got_repo_get_path(repo), 0,
12779 worktree ? got_worktree_get_root_path(worktree) : NULL);
12780 if (error)
12781 goto done;
12782 error = process_backup_refs(
12783 GOT_WORKTREE_HISTEDIT_BACKUP_REF_PREFIX,
12784 argc == 1 ? argv[0] : NULL, delete_backups, repo);
12785 goto done; /* nothing else to do */
12786 } else {
12787 error = get_gitconfig_path(&gitconfig_path);
12788 if (error)
12789 goto done;
12790 error = got_repo_open(&repo,
12791 got_worktree_get_repo_path(worktree), gitconfig_path,
12792 pack_fds);
12793 if (error != NULL)
12794 goto done;
12795 error = get_editor(&editor);
12796 if (error)
12797 goto done;
12798 if (unveil(editor, "x") != 0) {
12799 error = got_error_from_errno2("unveil", editor);
12800 goto done;
12802 if (edit_script_path) {
12803 if (unveil(edit_script_path, "r") != 0) {
12804 error = got_error_from_errno2("unveil",
12805 edit_script_path);
12806 goto done;
12809 error = apply_unveil(got_repo_get_path(repo), 0,
12810 got_worktree_get_root_path(worktree));
12811 if (error)
12812 goto done;
12815 if (worktree != NULL && !list_backups && !delete_backups) {
12816 error = worktree_has_logmsg_ref("histedit", worktree, repo);
12817 if (error)
12818 goto done;
12821 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
12822 if (error)
12823 goto done;
12824 if (rebase_in_progress) {
12825 error = got_error(GOT_ERR_REBASING);
12826 goto done;
12829 error = got_worktree_merge_in_progress(&merge_in_progress, worktree,
12830 repo);
12831 if (error)
12832 goto done;
12833 if (merge_in_progress) {
12834 error = got_error(GOT_ERR_MERGE_BUSY);
12835 goto done;
12838 error = got_worktree_histedit_in_progress(&edit_in_progress, worktree);
12839 if (error)
12840 goto done;
12842 if (edit_in_progress && edit_logmsg_only) {
12843 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
12844 "histedit operation is in progress in this "
12845 "work tree and must be continued or aborted "
12846 "before the -m option can be used");
12847 goto done;
12849 if (edit_in_progress && drop_only) {
12850 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
12851 "histedit operation is in progress in this "
12852 "work tree and must be continued or aborted "
12853 "before the -d option can be used");
12854 goto done;
12856 if (edit_in_progress && fold_only) {
12857 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
12858 "histedit operation is in progress in this "
12859 "work tree and must be continued or aborted "
12860 "before the -f option can be used");
12861 goto done;
12863 if (edit_in_progress && edit_only) {
12864 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
12865 "histedit operation is in progress in this "
12866 "work tree and must be continued or aborted "
12867 "before the -e option can be used");
12868 goto done;
12871 if (edit_in_progress && abort_edit) {
12872 error = got_worktree_histedit_continue(&resume_commit_id,
12873 &tmp_branch, &branch, &base_commit_id, &fileindex,
12874 worktree, repo);
12875 if (error)
12876 goto done;
12877 printf("Switching work tree to %s\n",
12878 got_ref_get_symref_target(branch));
12879 error = got_worktree_histedit_abort(worktree, fileindex, repo,
12880 branch, base_commit_id, abort_progress, &upa);
12881 if (error)
12882 goto done;
12883 printf("Histedit of %s aborted\n",
12884 got_ref_get_symref_target(branch));
12885 print_merge_progress_stats(&upa);
12886 goto done; /* nothing else to do */
12887 } else if (abort_edit) {
12888 error = got_error(GOT_ERR_NOT_HISTEDIT);
12889 goto done;
12892 error = get_author(&committer, repo, worktree);
12893 if (error)
12894 goto done;
12896 if (continue_edit) {
12897 char *path;
12899 if (!edit_in_progress) {
12900 error = got_error(GOT_ERR_NOT_HISTEDIT);
12901 goto done;
12904 error = got_worktree_get_histedit_script_path(&path, worktree);
12905 if (error)
12906 goto done;
12908 error = histedit_load_list(&histedit_cmds, path, repo);
12909 free(path);
12910 if (error)
12911 goto done;
12913 error = got_worktree_histedit_continue(&resume_commit_id,
12914 &tmp_branch, &branch, &base_commit_id, &fileindex,
12915 worktree, repo);
12916 if (error)
12917 goto done;
12919 error = got_ref_resolve(&head_commit_id, repo, branch);
12920 if (error)
12921 goto done;
12923 error = got_object_open_as_commit(&commit, repo,
12924 head_commit_id);
12925 if (error)
12926 goto done;
12927 parent_ids = got_object_commit_get_parent_ids(commit);
12928 pid = STAILQ_FIRST(parent_ids);
12929 if (pid == NULL) {
12930 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
12931 goto done;
12933 error = collect_commits(&commits, head_commit_id, &pid->id,
12934 base_commit_id, got_worktree_get_path_prefix(worktree),
12935 GOT_ERR_HISTEDIT_PATH, repo);
12936 got_object_commit_close(commit);
12937 commit = NULL;
12938 if (error)
12939 goto done;
12940 } else {
12941 if (edit_in_progress) {
12942 error = got_error(GOT_ERR_HISTEDIT_BUSY);
12943 goto done;
12946 error = got_ref_open(&branch, repo,
12947 got_worktree_get_head_ref_name(worktree), 0);
12948 if (error != NULL)
12949 goto done;
12951 if (strncmp(got_ref_get_name(branch), "refs/heads/", 11) != 0) {
12952 error = got_error_msg(GOT_ERR_COMMIT_BRANCH,
12953 "will not edit commit history of a branch outside "
12954 "the \"refs/heads/\" reference namespace");
12955 goto done;
12958 error = got_ref_resolve(&head_commit_id, repo, branch);
12959 got_ref_close(branch);
12960 branch = NULL;
12961 if (error)
12962 goto done;
12964 error = got_object_open_as_commit(&commit, repo,
12965 head_commit_id);
12966 if (error)
12967 goto done;
12968 parent_ids = got_object_commit_get_parent_ids(commit);
12969 pid = STAILQ_FIRST(parent_ids);
12970 if (pid == NULL) {
12971 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
12972 goto done;
12974 error = collect_commits(&commits, head_commit_id, &pid->id,
12975 got_worktree_get_base_commit_id(worktree),
12976 got_worktree_get_path_prefix(worktree),
12977 GOT_ERR_HISTEDIT_PATH, repo);
12978 got_object_commit_close(commit);
12979 commit = NULL;
12980 if (error)
12981 goto done;
12983 if (STAILQ_EMPTY(&commits)) {
12984 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
12985 goto done;
12988 error = got_worktree_histedit_prepare(&tmp_branch, &branch,
12989 &base_commit_id, &fileindex, worktree, repo);
12990 if (error)
12991 goto done;
12993 if (edit_script_path) {
12994 error = histedit_load_list(&histedit_cmds,
12995 edit_script_path, repo);
12996 if (error) {
12997 got_worktree_histedit_abort(worktree, fileindex,
12998 repo, branch, base_commit_id,
12999 abort_progress, &upa);
13000 print_merge_progress_stats(&upa);
13001 goto done;
13003 } else {
13004 const char *branch_name;
13005 branch_name = got_ref_get_symref_target(branch);
13006 if (strncmp(branch_name, "refs/heads/", 11) == 0)
13007 branch_name += 11;
13008 error = histedit_edit_script(&histedit_cmds, &commits,
13009 branch_name, edit_logmsg_only, fold_only,
13010 drop_only, edit_only, editor, repo);
13011 if (error) {
13012 got_worktree_histedit_abort(worktree, fileindex,
13013 repo, branch, base_commit_id,
13014 abort_progress, &upa);
13015 print_merge_progress_stats(&upa);
13016 goto done;
13021 error = histedit_save_list(&histedit_cmds, worktree,
13022 repo);
13023 if (error) {
13024 got_worktree_histedit_abort(worktree, fileindex,
13025 repo, branch, base_commit_id,
13026 abort_progress, &upa);
13027 print_merge_progress_stats(&upa);
13028 goto done;
13033 error = histedit_check_script(&histedit_cmds, &commits, repo);
13034 if (error)
13035 goto done;
13037 TAILQ_FOREACH(hle, &histedit_cmds, entry) {
13038 if (resume_commit_id) {
13039 if (got_object_id_cmp(hle->commit_id,
13040 resume_commit_id) != 0)
13041 continue;
13043 resume_commit_id = NULL;
13044 if (hle->cmd->code == GOT_HISTEDIT_DROP ||
13045 hle->cmd->code == GOT_HISTEDIT_FOLD) {
13046 error = histedit_skip_commit(hle, worktree,
13047 repo);
13048 if (error)
13049 goto done;
13050 } else {
13051 struct got_pathlist_head paths;
13052 int have_changes = 0;
13054 TAILQ_INIT(&paths);
13055 error = got_pathlist_append(&paths, "", NULL);
13056 if (error)
13057 goto done;
13058 error = got_worktree_status(worktree, &paths,
13059 repo, 0, check_local_changes, &have_changes,
13060 check_cancelled, NULL);
13061 got_pathlist_free(&paths,
13062 GOT_PATHLIST_FREE_NONE);
13063 if (error) {
13064 if (error->code != GOT_ERR_CANCELLED)
13065 goto done;
13066 if (sigint_received || sigpipe_received)
13067 goto done;
13069 if (have_changes) {
13070 error = histedit_commit(NULL, worktree,
13071 fileindex, tmp_branch, hle,
13072 committer, allow_conflict, editor,
13073 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, editor, repo);
13145 if (error)
13146 goto done;
13149 error = histedit_commit(&merged_paths, worktree, fileindex,
13150 tmp_branch, hle, committer, allow_conflict, editor, 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(editor);
13186 free(committer);
13187 free(gitconfig_path);
13188 got_object_id_queue_free(&commits);
13189 histedit_free_list(&histedit_cmds);
13190 free(head_commit_id);
13191 free(base_commit_id);
13192 free(resume_commit_id);
13193 if (commit)
13194 got_object_commit_close(commit);
13195 if (branch)
13196 got_ref_close(branch);
13197 if (tmp_branch)
13198 got_ref_close(tmp_branch);
13199 if (worktree)
13200 got_worktree_close(worktree);
13201 if (repo) {
13202 const struct got_error *close_err = got_repo_close(repo);
13203 if (error == NULL)
13204 error = close_err;
13206 if (pack_fds) {
13207 const struct got_error *pack_err =
13208 got_repo_pack_fds_close(pack_fds);
13209 if (error == NULL)
13210 error = pack_err;
13212 return error;
13215 __dead static void
13216 usage_integrate(void)
13218 fprintf(stderr, "usage: %s integrate branch\n", getprogname());
13219 exit(1);
13222 static const struct got_error *
13223 cmd_integrate(int argc, char *argv[])
13225 const struct got_error *error = NULL;
13226 struct got_repository *repo = NULL;
13227 struct got_worktree *worktree = NULL;
13228 char *cwd = NULL, *refname = NULL, *base_refname = NULL;
13229 const char *branch_arg = NULL;
13230 struct got_reference *branch_ref = NULL, *base_branch_ref = NULL;
13231 struct got_fileindex *fileindex = NULL;
13232 struct got_object_id *commit_id = NULL, *base_commit_id = NULL;
13233 int ch;
13234 struct got_update_progress_arg upa;
13235 int *pack_fds = NULL;
13237 #ifndef PROFILE
13238 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
13239 "unveil", NULL) == -1)
13240 err(1, "pledge");
13241 #endif
13243 while ((ch = getopt(argc, argv, "")) != -1) {
13244 switch (ch) {
13245 default:
13246 usage_integrate();
13247 /* NOTREACHED */
13251 argc -= optind;
13252 argv += optind;
13254 if (argc != 1)
13255 usage_integrate();
13256 branch_arg = argv[0];
13258 cwd = getcwd(NULL, 0);
13259 if (cwd == NULL) {
13260 error = got_error_from_errno("getcwd");
13261 goto done;
13264 error = got_repo_pack_fds_open(&pack_fds);
13265 if (error != NULL)
13266 goto done;
13268 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
13269 if (error) {
13270 if (error->code == GOT_ERR_NOT_WORKTREE)
13271 error = wrap_not_worktree_error(error, "integrate",
13272 cwd);
13273 goto done;
13276 error = check_rebase_or_histedit_in_progress(worktree);
13277 if (error)
13278 goto done;
13280 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
13281 NULL, pack_fds);
13282 if (error != NULL)
13283 goto done;
13285 error = apply_unveil(got_repo_get_path(repo), 0,
13286 got_worktree_get_root_path(worktree));
13287 if (error)
13288 goto done;
13290 error = check_merge_in_progress(worktree, repo);
13291 if (error)
13292 goto done;
13294 if (asprintf(&refname, "refs/heads/%s", branch_arg) == -1) {
13295 error = got_error_from_errno("asprintf");
13296 goto done;
13299 error = got_worktree_integrate_prepare(&fileindex, &branch_ref,
13300 &base_branch_ref, worktree, refname, repo);
13301 if (error)
13302 goto done;
13304 refname = strdup(got_ref_get_name(branch_ref));
13305 if (refname == NULL) {
13306 error = got_error_from_errno("strdup");
13307 got_worktree_integrate_abort(worktree, fileindex, repo,
13308 branch_ref, base_branch_ref);
13309 goto done;
13311 base_refname = strdup(got_ref_get_name(base_branch_ref));
13312 if (base_refname == NULL) {
13313 error = got_error_from_errno("strdup");
13314 got_worktree_integrate_abort(worktree, fileindex, repo,
13315 branch_ref, base_branch_ref);
13316 goto done;
13318 if (strncmp(base_refname, "refs/heads/", 11) != 0) {
13319 error = got_error(GOT_ERR_INTEGRATE_BRANCH);
13320 got_worktree_integrate_abort(worktree, fileindex, repo,
13321 branch_ref, base_branch_ref);
13322 goto done;
13325 error = got_ref_resolve(&commit_id, repo, branch_ref);
13326 if (error)
13327 goto done;
13329 error = got_ref_resolve(&base_commit_id, repo, base_branch_ref);
13330 if (error)
13331 goto done;
13333 if (got_object_id_cmp(commit_id, base_commit_id) == 0) {
13334 error = got_error_msg(GOT_ERR_SAME_BRANCH,
13335 "specified branch has already been integrated");
13336 got_worktree_integrate_abort(worktree, fileindex, repo,
13337 branch_ref, base_branch_ref);
13338 goto done;
13341 error = check_linear_ancestry(commit_id, base_commit_id, 1, repo);
13342 if (error) {
13343 if (error->code == GOT_ERR_ANCESTRY)
13344 error = got_error(GOT_ERR_REBASE_REQUIRED);
13345 got_worktree_integrate_abort(worktree, fileindex, repo,
13346 branch_ref, base_branch_ref);
13347 goto done;
13350 memset(&upa, 0, sizeof(upa));
13351 error = got_worktree_integrate_continue(worktree, fileindex, repo,
13352 branch_ref, base_branch_ref, update_progress, &upa,
13353 check_cancelled, NULL);
13354 if (error)
13355 goto done;
13357 printf("Integrated %s into %s\n", refname, base_refname);
13358 print_update_progress_stats(&upa);
13359 done:
13360 if (repo) {
13361 const struct got_error *close_err = got_repo_close(repo);
13362 if (error == NULL)
13363 error = close_err;
13365 if (worktree)
13366 got_worktree_close(worktree);
13367 if (pack_fds) {
13368 const struct got_error *pack_err =
13369 got_repo_pack_fds_close(pack_fds);
13370 if (error == NULL)
13371 error = pack_err;
13373 free(cwd);
13374 free(base_commit_id);
13375 free(commit_id);
13376 free(refname);
13377 free(base_refname);
13378 return error;
13381 __dead static void
13382 usage_merge(void)
13384 fprintf(stderr, "usage: %s merge [-aCcn] [branch]\n", getprogname());
13385 exit(1);
13388 static const struct got_error *
13389 cmd_merge(int argc, char *argv[])
13391 const struct got_error *error = NULL;
13392 struct got_worktree *worktree = NULL;
13393 struct got_repository *repo = NULL;
13394 struct got_fileindex *fileindex = NULL;
13395 char *cwd = NULL, *id_str = NULL, *author = NULL;
13396 char *gitconfig_path = NULL;
13397 struct got_reference *branch = NULL, *wt_branch = NULL;
13398 struct got_object_id *branch_tip = NULL, *yca_id = NULL;
13399 struct got_object_id *wt_branch_tip = NULL;
13400 int ch, merge_in_progress = 0, abort_merge = 0, continue_merge = 0;
13401 int allow_conflict = 0, prefer_fast_forward = 1, interrupt_merge = 0;
13402 struct got_update_progress_arg upa;
13403 struct got_object_id *merge_commit_id = NULL;
13404 char *branch_name = NULL;
13405 int *pack_fds = NULL;
13407 memset(&upa, 0, sizeof(upa));
13409 #ifndef PROFILE
13410 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
13411 "unveil", NULL) == -1)
13412 err(1, "pledge");
13413 #endif
13415 while ((ch = getopt(argc, argv, "aCcMn")) != -1) {
13416 switch (ch) {
13417 case 'a':
13418 abort_merge = 1;
13419 break;
13420 case 'C':
13421 allow_conflict = 1;
13422 break;
13423 case 'c':
13424 continue_merge = 1;
13425 break;
13426 case 'M':
13427 prefer_fast_forward = 0;
13428 break;
13429 case 'n':
13430 interrupt_merge = 1;
13431 break;
13432 default:
13433 usage_merge();
13434 /* NOTREACHED */
13438 argc -= optind;
13439 argv += optind;
13441 if (abort_merge) {
13442 if (continue_merge)
13443 option_conflict('a', 'c');
13444 if (!prefer_fast_forward)
13445 option_conflict('a', 'M');
13446 if (interrupt_merge)
13447 option_conflict('a', 'n');
13448 } else if (continue_merge) {
13449 if (!prefer_fast_forward)
13450 option_conflict('c', 'M');
13451 if (interrupt_merge)
13452 option_conflict('c', 'n');
13454 if (allow_conflict) {
13455 if (!continue_merge)
13456 errx(1, "-C option requires -c");
13458 if (abort_merge || continue_merge) {
13459 if (argc != 0)
13460 usage_merge();
13461 } else if (argc != 1)
13462 usage_merge();
13464 cwd = getcwd(NULL, 0);
13465 if (cwd == NULL) {
13466 error = got_error_from_errno("getcwd");
13467 goto done;
13470 error = got_repo_pack_fds_open(&pack_fds);
13471 if (error != NULL)
13472 goto done;
13474 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
13475 if (error) {
13476 if (error->code == GOT_ERR_NOT_WORKTREE)
13477 error = wrap_not_worktree_error(error,
13478 "merge", cwd);
13479 goto done;
13482 error = get_gitconfig_path(&gitconfig_path);
13483 if (error)
13484 goto done;
13485 error = got_repo_open(&repo,
13486 worktree ? got_worktree_get_repo_path(worktree) : cwd,
13487 gitconfig_path, pack_fds);
13488 if (error != NULL)
13489 goto done;
13491 if (worktree != NULL) {
13492 error = worktree_has_logmsg_ref("merge", worktree, repo);
13493 if (error)
13494 goto done;
13497 error = apply_unveil(got_repo_get_path(repo), 0,
13498 worktree ? got_worktree_get_root_path(worktree) : NULL);
13499 if (error)
13500 goto done;
13502 error = check_rebase_or_histedit_in_progress(worktree);
13503 if (error)
13504 goto done;
13506 error = got_worktree_merge_in_progress(&merge_in_progress, worktree,
13507 repo);
13508 if (error)
13509 goto done;
13511 if (merge_in_progress && !(abort_merge || continue_merge)) {
13512 error = got_error(GOT_ERR_MERGE_BUSY);
13513 goto done;
13516 if (!merge_in_progress && (abort_merge || continue_merge)) {
13517 error = got_error(GOT_ERR_NOT_MERGING);
13518 goto done;
13521 if (abort_merge) {
13522 error = got_worktree_merge_continue(&branch_name,
13523 &branch_tip, &fileindex, worktree, repo);
13524 if (error)
13525 goto done;
13526 error = got_worktree_merge_abort(worktree, fileindex, repo,
13527 abort_progress, &upa);
13528 if (error)
13529 goto done;
13530 printf("Merge of %s aborted\n", branch_name);
13531 goto done; /* nothing else to do */
13534 if (strncmp(got_worktree_get_head_ref_name(worktree),
13535 "refs/heads/", 11) != 0) {
13536 error = got_error_fmt(GOT_ERR_COMMIT_BRANCH,
13537 "work tree's current branch %s is outside the "
13538 "\"refs/heads/\" reference namespace; "
13539 "update -b required",
13540 got_worktree_get_head_ref_name(worktree));
13541 goto done;
13544 error = get_author(&author, repo, worktree);
13545 if (error)
13546 goto done;
13548 error = got_ref_open(&wt_branch, repo,
13549 got_worktree_get_head_ref_name(worktree), 0);
13550 if (error)
13551 goto done;
13552 error = got_ref_resolve(&wt_branch_tip, repo, wt_branch);
13553 if (error)
13554 goto done;
13556 if (continue_merge) {
13557 struct got_object_id *base_commit_id;
13558 base_commit_id = got_worktree_get_base_commit_id(worktree);
13559 if (got_object_id_cmp(wt_branch_tip, base_commit_id) != 0) {
13560 error = got_error(GOT_ERR_MERGE_COMMIT_OUT_OF_DATE);
13561 goto done;
13563 error = got_worktree_merge_continue(&branch_name,
13564 &branch_tip, &fileindex, worktree, repo);
13565 if (error)
13566 goto done;
13567 } else {
13568 error = got_ref_open(&branch, repo, argv[0], 0);
13569 if (error != NULL)
13570 goto done;
13571 branch_name = strdup(got_ref_get_name(branch));
13572 if (branch_name == NULL) {
13573 error = got_error_from_errno("strdup");
13574 goto done;
13576 error = got_ref_resolve(&branch_tip, repo, branch);
13577 if (error)
13578 goto done;
13581 error = got_commit_graph_find_youngest_common_ancestor(&yca_id,
13582 wt_branch_tip, branch_tip, 0, 0, repo,
13583 check_cancelled, NULL);
13584 if (error && error->code != GOT_ERR_ANCESTRY)
13585 goto done;
13587 if (!continue_merge) {
13588 error = check_path_prefix(wt_branch_tip, branch_tip,
13589 got_worktree_get_path_prefix(worktree),
13590 GOT_ERR_MERGE_PATH, repo);
13591 if (error)
13592 goto done;
13593 error = got_worktree_merge_prepare(&fileindex, worktree, repo);
13594 if (error)
13595 goto done;
13596 if (prefer_fast_forward && yca_id &&
13597 got_object_id_cmp(wt_branch_tip, yca_id) == 0) {
13598 struct got_pathlist_head paths;
13599 if (interrupt_merge) {
13600 error = got_error_fmt(GOT_ERR_BAD_OPTION,
13601 "there are no changes to merge since %s "
13602 "is already based on %s; merge cannot be "
13603 "interrupted for amending; -n",
13604 branch_name, got_ref_get_name(wt_branch));
13605 goto done;
13607 printf("Forwarding %s to %s\n",
13608 got_ref_get_name(wt_branch), branch_name);
13609 error = got_ref_change_ref(wt_branch, branch_tip);
13610 if (error)
13611 goto done;
13612 error = got_ref_write(wt_branch, repo);
13613 if (error)
13614 goto done;
13615 error = got_worktree_set_base_commit_id(worktree, repo,
13616 branch_tip);
13617 if (error)
13618 goto done;
13619 TAILQ_INIT(&paths);
13620 error = got_pathlist_append(&paths, "", NULL);
13621 if (error)
13622 goto done;
13623 error = got_worktree_checkout_files(worktree,
13624 &paths, repo, update_progress, &upa,
13625 check_cancelled, NULL);
13626 got_pathlist_free(&paths, GOT_PATHLIST_FREE_NONE);
13627 if (error)
13628 goto done;
13629 if (upa.did_something) {
13630 char *id_str;
13631 error = got_object_id_str(&id_str, branch_tip);
13632 if (error)
13633 goto done;
13634 printf("Updated to commit %s\n", id_str);
13635 free(id_str);
13636 } else
13637 printf("Already up-to-date\n");
13638 print_update_progress_stats(&upa);
13639 goto done;
13641 error = got_worktree_merge_write_refs(worktree, branch, repo);
13642 if (error)
13643 goto done;
13645 error = got_worktree_merge_branch(worktree, fileindex,
13646 yca_id, branch_tip, repo, update_progress, &upa,
13647 check_cancelled, NULL);
13648 if (error)
13649 goto done;
13650 print_merge_progress_stats(&upa);
13651 if (!upa.did_something) {
13652 error = got_worktree_merge_abort(worktree, fileindex,
13653 repo, abort_progress, &upa);
13654 if (error)
13655 goto done;
13656 printf("Already up-to-date\n");
13657 goto done;
13661 if (interrupt_merge) {
13662 error = got_worktree_merge_postpone(worktree, fileindex);
13663 if (error)
13664 goto done;
13665 printf("Merge of %s interrupted on request\n", branch_name);
13666 } else if (upa.conflicts > 0 || upa.missing > 0 ||
13667 upa.not_deleted > 0 || upa.unversioned > 0) {
13668 error = got_worktree_merge_postpone(worktree, fileindex);
13669 if (error)
13670 goto done;
13671 if (upa.conflicts > 0 && upa.missing == 0 &&
13672 upa.not_deleted == 0 && upa.unversioned == 0) {
13673 error = got_error_msg(GOT_ERR_CONFLICTS,
13674 "conflicts must be resolved before merging "
13675 "can continue");
13676 } else if (upa.conflicts > 0) {
13677 error = got_error_msg(GOT_ERR_CONFLICTS,
13678 "conflicts must be resolved before merging "
13679 "can continue; changes destined for some "
13680 "files were not yet merged and "
13681 "should be merged manually if required before the "
13682 "merge operation is continued");
13683 } else {
13684 error = got_error_msg(GOT_ERR_CONFLICTS,
13685 "changes destined for some "
13686 "files were not yet merged and should be "
13687 "merged manually if required before the "
13688 "merge operation is continued");
13690 goto done;
13691 } else {
13692 error = got_worktree_merge_commit(&merge_commit_id, worktree,
13693 fileindex, author, NULL, 1, branch_tip, branch_name,
13694 allow_conflict, repo, continue_merge ? print_status : NULL,
13695 NULL);
13696 if (error)
13697 goto done;
13698 error = got_worktree_merge_complete(worktree, fileindex, repo);
13699 if (error)
13700 goto done;
13701 error = got_object_id_str(&id_str, merge_commit_id);
13702 if (error)
13703 goto done;
13704 printf("Merged %s into %s: %s\n", branch_name,
13705 got_worktree_get_head_ref_name(worktree),
13706 id_str);
13709 done:
13710 free(gitconfig_path);
13711 free(id_str);
13712 free(merge_commit_id);
13713 free(author);
13714 free(branch_tip);
13715 free(branch_name);
13716 free(yca_id);
13717 if (branch)
13718 got_ref_close(branch);
13719 if (wt_branch)
13720 got_ref_close(wt_branch);
13721 if (worktree)
13722 got_worktree_close(worktree);
13723 if (repo) {
13724 const struct got_error *close_err = got_repo_close(repo);
13725 if (error == NULL)
13726 error = close_err;
13728 if (pack_fds) {
13729 const struct got_error *pack_err =
13730 got_repo_pack_fds_close(pack_fds);
13731 if (error == NULL)
13732 error = pack_err;
13734 return error;
13737 __dead static void
13738 usage_stage(void)
13740 fprintf(stderr, "usage: %s stage [-lpS] [-F response-script] "
13741 "[path ...]\n", getprogname());
13742 exit(1);
13745 static const struct got_error *
13746 print_stage(void *arg, unsigned char status, unsigned char staged_status,
13747 const char *path, struct got_object_id *blob_id,
13748 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
13749 int dirfd, const char *de_name)
13751 const struct got_error *err = NULL;
13752 char *id_str = NULL;
13754 if (staged_status != GOT_STATUS_ADD &&
13755 staged_status != GOT_STATUS_MODIFY &&
13756 staged_status != GOT_STATUS_DELETE)
13757 return NULL;
13759 if (staged_status == GOT_STATUS_ADD ||
13760 staged_status == GOT_STATUS_MODIFY)
13761 err = got_object_id_str(&id_str, staged_blob_id);
13762 else
13763 err = got_object_id_str(&id_str, blob_id);
13764 if (err)
13765 return err;
13767 printf("%s %c %s\n", id_str, staged_status, path);
13768 free(id_str);
13769 return NULL;
13772 static const struct got_error *
13773 cmd_stage(int argc, char *argv[])
13775 const struct got_error *error = NULL;
13776 struct got_repository *repo = NULL;
13777 struct got_worktree *worktree = NULL;
13778 char *cwd = NULL;
13779 struct got_pathlist_head paths;
13780 int ch, list_stage = 0, pflag = 0, allow_bad_symlinks = 0;
13781 FILE *patch_script_file = NULL;
13782 const char *patch_script_path = NULL;
13783 struct choose_patch_arg cpa;
13784 int *pack_fds = NULL;
13786 TAILQ_INIT(&paths);
13788 #ifndef PROFILE
13789 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
13790 "unveil", NULL) == -1)
13791 err(1, "pledge");
13792 #endif
13794 while ((ch = getopt(argc, argv, "F:lpS")) != -1) {
13795 switch (ch) {
13796 case 'F':
13797 patch_script_path = optarg;
13798 break;
13799 case 'l':
13800 list_stage = 1;
13801 break;
13802 case 'p':
13803 pflag = 1;
13804 break;
13805 case 'S':
13806 allow_bad_symlinks = 1;
13807 break;
13808 default:
13809 usage_stage();
13810 /* NOTREACHED */
13814 argc -= optind;
13815 argv += optind;
13817 if (list_stage && (pflag || patch_script_path))
13818 errx(1, "-l option cannot be used with other options");
13819 if (patch_script_path && !pflag)
13820 errx(1, "-F option can only be used together with -p option");
13822 cwd = getcwd(NULL, 0);
13823 if (cwd == NULL) {
13824 error = got_error_from_errno("getcwd");
13825 goto done;
13828 error = got_repo_pack_fds_open(&pack_fds);
13829 if (error != NULL)
13830 goto done;
13832 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
13833 if (error) {
13834 if (error->code == GOT_ERR_NOT_WORKTREE)
13835 error = wrap_not_worktree_error(error, "stage", cwd);
13836 goto done;
13839 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
13840 NULL, pack_fds);
13841 if (error != NULL)
13842 goto done;
13844 if (patch_script_path) {
13845 patch_script_file = fopen(patch_script_path, "re");
13846 if (patch_script_file == NULL) {
13847 error = got_error_from_errno2("fopen",
13848 patch_script_path);
13849 goto done;
13852 error = apply_unveil(got_repo_get_path(repo), 0,
13853 got_worktree_get_root_path(worktree));
13854 if (error)
13855 goto done;
13857 error = check_merge_in_progress(worktree, repo);
13858 if (error)
13859 goto done;
13861 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
13862 if (error)
13863 goto done;
13865 if (list_stage)
13866 error = got_worktree_status(worktree, &paths, repo, 0,
13867 print_stage, NULL, check_cancelled, NULL);
13868 else {
13869 cpa.patch_script_file = patch_script_file;
13870 cpa.action = "stage";
13871 error = got_worktree_stage(worktree, &paths,
13872 pflag ? NULL : print_status, NULL,
13873 pflag ? choose_patch : NULL, &cpa,
13874 allow_bad_symlinks, repo);
13876 done:
13877 if (patch_script_file && fclose(patch_script_file) == EOF &&
13878 error == NULL)
13879 error = got_error_from_errno2("fclose", patch_script_path);
13880 if (repo) {
13881 const struct got_error *close_err = got_repo_close(repo);
13882 if (error == NULL)
13883 error = close_err;
13885 if (worktree)
13886 got_worktree_close(worktree);
13887 if (pack_fds) {
13888 const struct got_error *pack_err =
13889 got_repo_pack_fds_close(pack_fds);
13890 if (error == NULL)
13891 error = pack_err;
13893 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
13894 free(cwd);
13895 return error;
13898 __dead static void
13899 usage_unstage(void)
13901 fprintf(stderr, "usage: %s unstage [-p] [-F response-script] "
13902 "[path ...]\n", getprogname());
13903 exit(1);
13907 static const struct got_error *
13908 cmd_unstage(int argc, char *argv[])
13910 const struct got_error *error = NULL;
13911 struct got_repository *repo = NULL;
13912 struct got_worktree *worktree = NULL;
13913 char *cwd = NULL;
13914 struct got_pathlist_head paths;
13915 int ch, pflag = 0;
13916 struct got_update_progress_arg upa;
13917 FILE *patch_script_file = NULL;
13918 const char *patch_script_path = NULL;
13919 struct choose_patch_arg cpa;
13920 int *pack_fds = NULL;
13922 TAILQ_INIT(&paths);
13924 #ifndef PROFILE
13925 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
13926 "unveil", NULL) == -1)
13927 err(1, "pledge");
13928 #endif
13930 while ((ch = getopt(argc, argv, "F:p")) != -1) {
13931 switch (ch) {
13932 case 'F':
13933 patch_script_path = optarg;
13934 break;
13935 case 'p':
13936 pflag = 1;
13937 break;
13938 default:
13939 usage_unstage();
13940 /* NOTREACHED */
13944 argc -= optind;
13945 argv += optind;
13947 if (patch_script_path && !pflag)
13948 errx(1, "-F option can only be used together with -p option");
13950 cwd = getcwd(NULL, 0);
13951 if (cwd == NULL) {
13952 error = got_error_from_errno("getcwd");
13953 goto done;
13956 error = got_repo_pack_fds_open(&pack_fds);
13957 if (error != NULL)
13958 goto done;
13960 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
13961 if (error) {
13962 if (error->code == GOT_ERR_NOT_WORKTREE)
13963 error = wrap_not_worktree_error(error, "unstage", cwd);
13964 goto done;
13967 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
13968 NULL, pack_fds);
13969 if (error != NULL)
13970 goto done;
13972 if (patch_script_path) {
13973 patch_script_file = fopen(patch_script_path, "re");
13974 if (patch_script_file == NULL) {
13975 error = got_error_from_errno2("fopen",
13976 patch_script_path);
13977 goto done;
13981 error = apply_unveil(got_repo_get_path(repo), 0,
13982 got_worktree_get_root_path(worktree));
13983 if (error)
13984 goto done;
13986 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
13987 if (error)
13988 goto done;
13990 cpa.patch_script_file = patch_script_file;
13991 cpa.action = "unstage";
13992 memset(&upa, 0, sizeof(upa));
13993 error = got_worktree_unstage(worktree, &paths, update_progress,
13994 &upa, pflag ? choose_patch : NULL, &cpa, repo);
13995 if (!error)
13996 print_merge_progress_stats(&upa);
13997 done:
13998 if (patch_script_file && fclose(patch_script_file) == EOF &&
13999 error == NULL)
14000 error = got_error_from_errno2("fclose", patch_script_path);
14001 if (repo) {
14002 const struct got_error *close_err = got_repo_close(repo);
14003 if (error == NULL)
14004 error = close_err;
14006 if (worktree)
14007 got_worktree_close(worktree);
14008 if (pack_fds) {
14009 const struct got_error *pack_err =
14010 got_repo_pack_fds_close(pack_fds);
14011 if (error == NULL)
14012 error = pack_err;
14014 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
14015 free(cwd);
14016 return error;
14019 __dead static void
14020 usage_cat(void)
14022 fprintf(stderr, "usage: %s cat [-P] [-c commit] [-r repository-path] "
14023 "arg ...\n", getprogname());
14024 exit(1);
14027 static const struct got_error *
14028 cat_blob(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
14030 const struct got_error *err;
14031 struct got_blob_object *blob;
14032 int fd = -1;
14034 fd = got_opentempfd();
14035 if (fd == -1)
14036 return got_error_from_errno("got_opentempfd");
14038 err = got_object_open_as_blob(&blob, repo, id, 8192, fd);
14039 if (err)
14040 goto done;
14042 err = got_object_blob_dump_to_file(NULL, NULL, NULL, outfile, blob);
14043 done:
14044 if (fd != -1 && close(fd) == -1 && err == NULL)
14045 err = got_error_from_errno("close");
14046 if (blob)
14047 got_object_blob_close(blob);
14048 return err;
14051 static const struct got_error *
14052 cat_tree(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
14054 const struct got_error *err;
14055 struct got_tree_object *tree;
14056 int nentries, i;
14058 err = got_object_open_as_tree(&tree, repo, id);
14059 if (err)
14060 return err;
14062 nentries = got_object_tree_get_nentries(tree);
14063 for (i = 0; i < nentries; i++) {
14064 struct got_tree_entry *te;
14065 char *id_str;
14066 if (sigint_received || sigpipe_received)
14067 break;
14068 te = got_object_tree_get_entry(tree, i);
14069 err = got_object_id_str(&id_str, got_tree_entry_get_id(te));
14070 if (err)
14071 break;
14072 fprintf(outfile, "%s %.7o %s\n", id_str,
14073 got_tree_entry_get_mode(te),
14074 got_tree_entry_get_name(te));
14075 free(id_str);
14078 got_object_tree_close(tree);
14079 return err;
14082 static const struct got_error *
14083 cat_commit(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
14085 const struct got_error *err;
14086 struct got_commit_object *commit;
14087 const struct got_object_id_queue *parent_ids;
14088 struct got_object_qid *pid;
14089 char *id_str = NULL;
14090 const char *logmsg = NULL;
14091 char gmtoff[6];
14093 err = got_object_open_as_commit(&commit, repo, id);
14094 if (err)
14095 return err;
14097 err = got_object_id_str(&id_str, got_object_commit_get_tree_id(commit));
14098 if (err)
14099 goto done;
14101 fprintf(outfile, "%s%s\n", GOT_COMMIT_LABEL_TREE, id_str);
14102 parent_ids = got_object_commit_get_parent_ids(commit);
14103 fprintf(outfile, "numparents %d\n",
14104 got_object_commit_get_nparents(commit));
14105 STAILQ_FOREACH(pid, parent_ids, entry) {
14106 char *pid_str;
14107 err = got_object_id_str(&pid_str, &pid->id);
14108 if (err)
14109 goto done;
14110 fprintf(outfile, "%s%s\n", GOT_COMMIT_LABEL_PARENT, pid_str);
14111 free(pid_str);
14113 got_date_format_gmtoff(gmtoff, sizeof(gmtoff),
14114 got_object_commit_get_author_gmtoff(commit));
14115 fprintf(outfile, "%s%s %lld %s\n", GOT_COMMIT_LABEL_AUTHOR,
14116 got_object_commit_get_author(commit),
14117 (long long)got_object_commit_get_author_time(commit),
14118 gmtoff);
14120 got_date_format_gmtoff(gmtoff, sizeof(gmtoff),
14121 got_object_commit_get_committer_gmtoff(commit));
14122 fprintf(outfile, "%s%s %lld %s\n", GOT_COMMIT_LABEL_COMMITTER,
14123 got_object_commit_get_committer(commit),
14124 (long long)got_object_commit_get_committer_time(commit),
14125 gmtoff);
14127 logmsg = got_object_commit_get_logmsg_raw(commit);
14128 fprintf(outfile, "messagelen %zd\n", strlen(logmsg));
14129 fprintf(outfile, "%s", logmsg);
14130 done:
14131 free(id_str);
14132 got_object_commit_close(commit);
14133 return err;
14136 static const struct got_error *
14137 cat_tag(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
14139 const struct got_error *err;
14140 struct got_tag_object *tag;
14141 char *id_str = NULL;
14142 const char *tagmsg = NULL;
14143 char gmtoff[6];
14145 err = got_object_open_as_tag(&tag, repo, id);
14146 if (err)
14147 return err;
14149 err = got_object_id_str(&id_str, got_object_tag_get_object_id(tag));
14150 if (err)
14151 goto done;
14153 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_OBJECT, id_str);
14155 switch (got_object_tag_get_object_type(tag)) {
14156 case GOT_OBJ_TYPE_BLOB:
14157 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
14158 GOT_OBJ_LABEL_BLOB);
14159 break;
14160 case GOT_OBJ_TYPE_TREE:
14161 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
14162 GOT_OBJ_LABEL_TREE);
14163 break;
14164 case GOT_OBJ_TYPE_COMMIT:
14165 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
14166 GOT_OBJ_LABEL_COMMIT);
14167 break;
14168 case GOT_OBJ_TYPE_TAG:
14169 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
14170 GOT_OBJ_LABEL_TAG);
14171 break;
14172 default:
14173 break;
14176 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TAG,
14177 got_object_tag_get_name(tag));
14179 got_date_format_gmtoff(gmtoff, sizeof(gmtoff),
14180 got_object_tag_get_tagger_gmtoff(tag));
14181 fprintf(outfile, "%s%s %lld %s\n", GOT_TAG_LABEL_TAGGER,
14182 got_object_tag_get_tagger(tag),
14183 (long long)got_object_tag_get_tagger_time(tag),
14184 gmtoff);
14186 tagmsg = got_object_tag_get_message(tag);
14187 fprintf(outfile, "messagelen %zd\n", strlen(tagmsg));
14188 fprintf(outfile, "%s", tagmsg);
14189 done:
14190 free(id_str);
14191 got_object_tag_close(tag);
14192 return err;
14195 static const struct got_error *
14196 cmd_cat(int argc, char *argv[])
14198 const struct got_error *error;
14199 struct got_repository *repo = NULL;
14200 struct got_worktree *worktree = NULL;
14201 char *cwd = NULL, *repo_path = NULL, *label = NULL;
14202 char *keyword_idstr = NULL;
14203 const char *commit_id_str = NULL;
14204 struct got_object_id *id = NULL, *commit_id = NULL;
14205 struct got_commit_object *commit = NULL;
14206 int ch, obj_type, i, force_path = 0;
14207 struct got_reflist_head refs;
14208 int *pack_fds = NULL;
14210 TAILQ_INIT(&refs);
14212 #ifndef PROFILE
14213 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
14214 NULL) == -1)
14215 err(1, "pledge");
14216 #endif
14218 while ((ch = getopt(argc, argv, "c:Pr:")) != -1) {
14219 switch (ch) {
14220 case 'c':
14221 commit_id_str = optarg;
14222 break;
14223 case 'P':
14224 force_path = 1;
14225 break;
14226 case 'r':
14227 repo_path = realpath(optarg, NULL);
14228 if (repo_path == NULL)
14229 return got_error_from_errno2("realpath",
14230 optarg);
14231 got_path_strip_trailing_slashes(repo_path);
14232 break;
14233 default:
14234 usage_cat();
14235 /* NOTREACHED */
14239 argc -= optind;
14240 argv += optind;
14242 cwd = getcwd(NULL, 0);
14243 if (cwd == NULL) {
14244 error = got_error_from_errno("getcwd");
14245 goto done;
14248 error = got_repo_pack_fds_open(&pack_fds);
14249 if (error != NULL)
14250 goto done;
14252 if (repo_path == NULL) {
14253 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
14254 if (error && error->code != GOT_ERR_NOT_WORKTREE)
14255 goto done;
14256 if (worktree) {
14257 repo_path = strdup(
14258 got_worktree_get_repo_path(worktree));
14259 if (repo_path == NULL) {
14260 error = got_error_from_errno("strdup");
14261 goto done;
14264 if (commit_id_str == NULL) {
14265 /* Release work tree lock. */
14266 got_worktree_close(worktree);
14267 worktree = NULL;
14272 if (repo_path == NULL) {
14273 repo_path = strdup(cwd);
14274 if (repo_path == NULL)
14275 return got_error_from_errno("strdup");
14278 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
14279 free(repo_path);
14280 if (error != NULL)
14281 goto done;
14283 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
14284 if (error)
14285 goto done;
14287 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
14288 if (error)
14289 goto done;
14291 if (commit_id_str != NULL) {
14292 error = got_keyword_to_idstr(&keyword_idstr, commit_id_str,
14293 repo, worktree);
14294 if (error != NULL)
14295 goto done;
14296 if (keyword_idstr != NULL)
14297 commit_id_str = keyword_idstr;
14298 if (worktree != NULL) {
14299 got_worktree_close(worktree);
14300 worktree = NULL;
14302 } else
14303 commit_id_str = GOT_REF_HEAD;
14304 error = got_repo_match_object_id(&commit_id, NULL,
14305 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
14306 if (error)
14307 goto done;
14309 error = got_object_open_as_commit(&commit, repo, commit_id);
14310 if (error)
14311 goto done;
14313 for (i = 0; i < argc; i++) {
14314 if (force_path) {
14315 error = got_object_id_by_path(&id, repo, commit,
14316 argv[i]);
14317 if (error)
14318 break;
14319 } else {
14320 error = got_repo_match_object_id(&id, &label, argv[i],
14321 GOT_OBJ_TYPE_ANY, NULL /* do not resolve tags */,
14322 repo);
14323 if (error) {
14324 if (error->code != GOT_ERR_BAD_OBJ_ID_STR &&
14325 error->code != GOT_ERR_NOT_REF)
14326 break;
14327 error = got_object_id_by_path(&id, repo,
14328 commit, argv[i]);
14329 if (error)
14330 break;
14334 error = got_object_get_type(&obj_type, repo, id);
14335 if (error)
14336 break;
14338 switch (obj_type) {
14339 case GOT_OBJ_TYPE_BLOB:
14340 error = cat_blob(id, repo, stdout);
14341 break;
14342 case GOT_OBJ_TYPE_TREE:
14343 error = cat_tree(id, repo, stdout);
14344 break;
14345 case GOT_OBJ_TYPE_COMMIT:
14346 error = cat_commit(id, repo, stdout);
14347 break;
14348 case GOT_OBJ_TYPE_TAG:
14349 error = cat_tag(id, repo, stdout);
14350 break;
14351 default:
14352 error = got_error(GOT_ERR_OBJ_TYPE);
14353 break;
14355 if (error)
14356 break;
14357 free(label);
14358 label = NULL;
14359 free(id);
14360 id = NULL;
14362 done:
14363 free(label);
14364 free(id);
14365 free(commit_id);
14366 free(keyword_idstr);
14367 if (commit)
14368 got_object_commit_close(commit);
14369 if (worktree)
14370 got_worktree_close(worktree);
14371 if (repo) {
14372 const struct got_error *close_err = got_repo_close(repo);
14373 if (error == NULL)
14374 error = close_err;
14376 if (pack_fds) {
14377 const struct got_error *pack_err =
14378 got_repo_pack_fds_close(pack_fds);
14379 if (error == NULL)
14380 error = pack_err;
14383 got_ref_list_free(&refs);
14384 return error;
14387 __dead static void
14388 usage_info(void)
14390 fprintf(stderr, "usage: %s info [path ...]\n",
14391 getprogname());
14392 exit(1);
14395 static const struct got_error *
14396 print_path_info(void *arg, const char *path, mode_t mode, time_t mtime,
14397 struct got_object_id *blob_id, struct got_object_id *staged_blob_id,
14398 struct got_object_id *commit_id)
14400 const struct got_error *err = NULL;
14401 char *id_str = NULL;
14402 char datebuf[128];
14403 struct tm mytm, *tm;
14404 struct got_pathlist_head *paths = arg;
14405 struct got_pathlist_entry *pe;
14408 * Clear error indication from any of the path arguments which
14409 * would cause this file index entry to be displayed.
14411 TAILQ_FOREACH(pe, paths, entry) {
14412 if (got_path_cmp(path, pe->path, strlen(path),
14413 pe->path_len) == 0 ||
14414 got_path_is_child(path, pe->path, pe->path_len))
14415 pe->data = NULL; /* no error */
14418 printf(GOT_COMMIT_SEP_STR);
14419 if (S_ISLNK(mode))
14420 printf("symlink: %s\n", path);
14421 else if (S_ISREG(mode)) {
14422 printf("file: %s\n", path);
14423 printf("mode: %o\n", mode & (S_IRWXU | S_IRWXG | S_IRWXO));
14424 } else if (S_ISDIR(mode))
14425 printf("directory: %s\n", path);
14426 else
14427 printf("something: %s\n", path);
14429 tm = localtime_r(&mtime, &mytm);
14430 if (tm == NULL)
14431 return NULL;
14432 if (strftime(datebuf, sizeof(datebuf), "%c %Z", tm) == 0)
14433 return got_error(GOT_ERR_NO_SPACE);
14434 printf("timestamp: %s\n", datebuf);
14436 if (blob_id) {
14437 err = got_object_id_str(&id_str, blob_id);
14438 if (err)
14439 return err;
14440 printf("based on blob: %s\n", id_str);
14441 free(id_str);
14444 if (staged_blob_id) {
14445 err = got_object_id_str(&id_str, staged_blob_id);
14446 if (err)
14447 return err;
14448 printf("based on staged blob: %s\n", id_str);
14449 free(id_str);
14452 if (commit_id) {
14453 err = got_object_id_str(&id_str, commit_id);
14454 if (err)
14455 return err;
14456 printf("based on commit: %s\n", id_str);
14457 free(id_str);
14460 return NULL;
14463 static const struct got_error *
14464 cmd_info(int argc, char *argv[])
14466 const struct got_error *error = NULL;
14467 struct got_worktree *worktree = NULL;
14468 char *cwd = NULL, *id_str = NULL;
14469 struct got_pathlist_head paths;
14470 char *uuidstr = NULL;
14471 int ch, show_files = 0;
14473 TAILQ_INIT(&paths);
14475 #ifndef PROFILE
14476 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
14477 NULL) == -1)
14478 err(1, "pledge");
14479 #endif
14481 while ((ch = getopt(argc, argv, "")) != -1) {
14482 switch (ch) {
14483 default:
14484 usage_info();
14485 /* NOTREACHED */
14489 argc -= optind;
14490 argv += optind;
14492 cwd = getcwd(NULL, 0);
14493 if (cwd == NULL) {
14494 error = got_error_from_errno("getcwd");
14495 goto done;
14498 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
14499 if (error) {
14500 if (error->code == GOT_ERR_NOT_WORKTREE)
14501 error = wrap_not_worktree_error(error, "info", cwd);
14502 goto done;
14505 #ifndef PROFILE
14506 /* Remove "wpath cpath proc exec sendfd" promises. */
14507 if (pledge("stdio rpath flock unveil", NULL) == -1)
14508 err(1, "pledge");
14509 #endif
14510 error = apply_unveil(NULL, 0, got_worktree_get_root_path(worktree));
14511 if (error)
14512 goto done;
14514 if (argc >= 1) {
14515 error = get_worktree_paths_from_argv(&paths, argc, argv,
14516 worktree);
14517 if (error)
14518 goto done;
14519 show_files = 1;
14522 error = got_object_id_str(&id_str,
14523 got_worktree_get_base_commit_id(worktree));
14524 if (error)
14525 goto done;
14527 error = got_worktree_get_uuid(&uuidstr, worktree);
14528 if (error)
14529 goto done;
14531 printf("work tree: %s\n", got_worktree_get_root_path(worktree));
14532 printf("work tree base commit: %s\n", id_str);
14533 printf("work tree path prefix: %s\n",
14534 got_worktree_get_path_prefix(worktree));
14535 printf("work tree branch reference: %s\n",
14536 got_worktree_get_head_ref_name(worktree));
14537 printf("work tree UUID: %s\n", uuidstr);
14538 printf("repository: %s\n", got_worktree_get_repo_path(worktree));
14540 if (show_files) {
14541 struct got_pathlist_entry *pe;
14542 TAILQ_FOREACH(pe, &paths, entry) {
14543 if (pe->path_len == 0)
14544 continue;
14546 * Assume this path will fail. This will be corrected
14547 * in print_path_info() in case the path does suceeed.
14549 pe->data = (void *)got_error(GOT_ERR_BAD_PATH);
14551 error = got_worktree_path_info(worktree, &paths,
14552 print_path_info, &paths, check_cancelled, NULL);
14553 if (error)
14554 goto done;
14555 TAILQ_FOREACH(pe, &paths, entry) {
14556 if (pe->data != NULL) {
14557 const struct got_error *perr;
14559 perr = pe->data;
14560 error = got_error_fmt(perr->code, "%s",
14561 pe->path);
14562 break;
14566 done:
14567 if (worktree)
14568 got_worktree_close(worktree);
14569 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
14570 free(cwd);
14571 free(id_str);
14572 free(uuidstr);
14573 return error;