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 strcmp(proto, "git+http") == 0 ||
1650 strcmp(proto, "http") == 0 ||
1651 strcmp(proto, "git+https") == 0 ||
1652 strcmp(proto, "https") == 0) {
1653 #ifndef PROFILE
1654 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
1655 "sendfd unveil", NULL) == -1)
1656 err(1, "pledge");
1657 #endif
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 #ifndef PROFILE
1701 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd",
1702 NULL) == -1)
1703 err(1, "pledge");
1704 #endif
1705 if (!list_refs_only) {
1706 error = got_repo_init(repo_path, NULL);
1707 if (error)
1708 goto done;
1709 error = got_repo_pack_fds_open(&pack_fds);
1710 if (error != NULL)
1711 goto done;
1712 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
1713 if (error)
1714 goto done;
1717 fpa.last_scaled_size[0] = '\0';
1718 fpa.last_p_indexed = -1;
1719 fpa.last_p_resolved = -1;
1720 fpa.verbosity = verbosity;
1721 fpa.create_configs = 1;
1722 fpa.configs_created = 0;
1723 fpa.repo = repo;
1724 fpa.config_info.symrefs = &symrefs;
1725 fpa.config_info.wanted_branches = &wanted_branches;
1726 fpa.config_info.wanted_refs = &wanted_refs;
1727 fpa.config_info.proto = proto;
1728 fpa.config_info.host = host;
1729 fpa.config_info.port = port;
1730 fpa.config_info.remote_repo_path = server_path;
1731 fpa.config_info.git_url = git_url;
1732 fpa.config_info.fetch_all_branches = fetch_all_branches;
1733 fpa.config_info.mirror_references = mirror_references;
1734 error = got_fetch_pack(&pack_hash, &refs, &symrefs,
1735 GOT_FETCH_DEFAULT_REMOTE_NAME, mirror_references,
1736 fetch_all_branches, &wanted_branches, &wanted_refs,
1737 list_refs_only, verbosity, fetchfd, repo, NULL, NULL, bflag,
1738 fetch_progress, &fpa);
1739 if (error)
1740 goto done;
1742 if (list_refs_only) {
1743 error = list_remote_refs(&symrefs, &refs);
1744 goto done;
1747 if (pack_hash == NULL) {
1748 error = got_error_fmt(GOT_ERR_FETCH_FAILED, "%s",
1749 "server sent an empty pack file");
1750 goto done;
1752 error = got_object_id_str(&id_str, pack_hash);
1753 if (error)
1754 goto done;
1755 if (verbosity >= 0)
1756 printf("\nFetched %s.pack\n", id_str);
1757 free(id_str);
1759 /* Set up references provided with the pack file. */
1760 TAILQ_FOREACH(pe, &refs, entry) {
1761 const char *refname = pe->path;
1762 struct got_object_id *id = pe->data;
1763 char *remote_refname;
1765 if (is_wanted_ref(&wanted_refs, refname) &&
1766 !mirror_references) {
1767 error = create_wanted_ref(refname, id,
1768 GOT_FETCH_DEFAULT_REMOTE_NAME,
1769 verbosity - 1, repo);
1770 if (error)
1771 goto done;
1772 continue;
1775 error = create_ref(refname, id, verbosity - 1, repo);
1776 if (error)
1777 goto done;
1779 if (mirror_references)
1780 continue;
1782 if (strncmp("refs/heads/", refname, 11) != 0)
1783 continue;
1785 if (asprintf(&remote_refname,
1786 "refs/remotes/%s/%s", GOT_FETCH_DEFAULT_REMOTE_NAME,
1787 refname + 11) == -1) {
1788 error = got_error_from_errno("asprintf");
1789 goto done;
1791 error = create_ref(remote_refname, id, verbosity - 1, repo);
1792 free(remote_refname);
1793 if (error)
1794 goto done;
1797 /* Set the HEAD reference if the server provided one. */
1798 TAILQ_FOREACH(pe, &symrefs, entry) {
1799 struct got_reference *target_ref;
1800 const char *refname = pe->path;
1801 const char *target = pe->data;
1802 char *remote_refname = NULL, *remote_target = NULL;
1804 if (strcmp(refname, GOT_REF_HEAD) != 0)
1805 continue;
1807 error = got_ref_open(&target_ref, repo, target, 0);
1808 if (error) {
1809 if (error->code == GOT_ERR_NOT_REF) {
1810 error = NULL;
1811 continue;
1813 goto done;
1816 error = create_symref(refname, target_ref, verbosity, repo);
1817 got_ref_close(target_ref);
1818 if (error)
1819 goto done;
1821 if (mirror_references)
1822 continue;
1824 if (strncmp("refs/heads/", target, 11) != 0)
1825 continue;
1827 if (asprintf(&remote_refname,
1828 "refs/remotes/%s/%s", GOT_FETCH_DEFAULT_REMOTE_NAME,
1829 refname) == -1) {
1830 error = got_error_from_errno("asprintf");
1831 goto done;
1833 if (asprintf(&remote_target,
1834 "refs/remotes/%s/%s", GOT_FETCH_DEFAULT_REMOTE_NAME,
1835 target + 11) == -1) {
1836 error = got_error_from_errno("asprintf");
1837 free(remote_refname);
1838 goto done;
1840 error = got_ref_open(&target_ref, repo, remote_target, 0);
1841 if (error) {
1842 free(remote_refname);
1843 free(remote_target);
1844 if (error->code == GOT_ERR_NOT_REF) {
1845 error = NULL;
1846 continue;
1848 goto done;
1850 error = create_symref(remote_refname, target_ref,
1851 verbosity - 1, repo);
1852 free(remote_refname);
1853 free(remote_target);
1854 got_ref_close(target_ref);
1855 if (error)
1856 goto done;
1858 if (pe == NULL) {
1860 * We failed to set the HEAD reference. If we asked for
1861 * a set of wanted branches use the first of one of those
1862 * which could be fetched instead.
1864 TAILQ_FOREACH(pe, &wanted_branches, entry) {
1865 const char *target = pe->path;
1866 struct got_reference *target_ref;
1868 error = got_ref_open(&target_ref, repo, target, 0);
1869 if (error) {
1870 if (error->code == GOT_ERR_NOT_REF) {
1871 error = NULL;
1872 continue;
1874 goto done;
1877 error = create_symref(GOT_REF_HEAD, target_ref,
1878 verbosity, repo);
1879 got_ref_close(target_ref);
1880 if (error)
1881 goto done;
1882 break;
1885 if (!fpa.configs_created && pe != NULL) {
1886 error = create_config_files(fpa.config_info.proto,
1887 fpa.config_info.host, fpa.config_info.port,
1888 fpa.config_info.remote_repo_path,
1889 fpa.config_info.git_url,
1890 fpa.config_info.fetch_all_branches,
1891 fpa.config_info.mirror_references,
1892 fpa.config_info.symrefs,
1893 fpa.config_info.wanted_branches,
1894 fpa.config_info.wanted_refs, fpa.repo);
1895 if (error)
1896 goto done;
1900 if (verbosity >= 0)
1901 printf("Created %s repository '%s'\n",
1902 mirror_references ? "mirrored" : "cloned", repo_path);
1903 done:
1904 if (pack_fds) {
1905 const struct got_error *pack_err =
1906 got_repo_pack_fds_close(pack_fds);
1907 if (error == NULL)
1908 error = pack_err;
1910 if (fetchpid > 0) {
1911 if (kill(fetchpid, SIGTERM) == -1)
1912 error = got_error_from_errno("kill");
1913 if (waitpid(fetchpid, &fetchstatus, 0) == -1 && error == NULL)
1914 error = got_error_from_errno("waitpid");
1916 if (fetchfd != -1 && close(fetchfd) == -1 && error == NULL)
1917 error = got_error_from_errno("close");
1918 if (repo) {
1919 const struct got_error *close_err = got_repo_close(repo);
1920 if (error == NULL)
1921 error = close_err;
1923 got_pathlist_free(&refs, GOT_PATHLIST_FREE_ALL);
1924 got_pathlist_free(&symrefs, GOT_PATHLIST_FREE_ALL);
1925 got_pathlist_free(&wanted_branches, GOT_PATHLIST_FREE_NONE);
1926 got_pathlist_free(&wanted_refs, GOT_PATHLIST_FREE_NONE);
1927 free(pack_hash);
1928 free(proto);
1929 free(host);
1930 free(port);
1931 free(server_path);
1932 free(repo_name);
1933 free(default_destdir);
1934 free(git_url);
1935 return error;
1938 static const struct got_error *
1939 update_ref(struct got_reference *ref, struct got_object_id *new_id,
1940 int replace_tags, int verbosity, struct got_repository *repo)
1942 const struct got_error *err = NULL;
1943 char *new_id_str = NULL;
1944 struct got_object_id *old_id = NULL;
1946 err = got_object_id_str(&new_id_str, new_id);
1947 if (err)
1948 goto done;
1950 if (!replace_tags &&
1951 strncmp(got_ref_get_name(ref), "refs/tags/", 10) == 0) {
1952 err = got_ref_resolve(&old_id, repo, ref);
1953 if (err)
1954 goto done;
1955 if (got_object_id_cmp(old_id, new_id) == 0)
1956 goto done;
1957 if (verbosity >= 0) {
1958 printf("Rejecting update of existing tag %s: %s\n",
1959 got_ref_get_name(ref), new_id_str);
1961 goto done;
1964 if (got_ref_is_symbolic(ref)) {
1965 if (verbosity >= 0) {
1966 printf("Replacing reference %s: %s\n",
1967 got_ref_get_name(ref),
1968 got_ref_get_symref_target(ref));
1970 err = got_ref_change_symref_to_ref(ref, new_id);
1971 if (err)
1972 goto done;
1973 err = got_ref_write(ref, repo);
1974 if (err)
1975 goto done;
1976 } else {
1977 err = got_ref_resolve(&old_id, repo, ref);
1978 if (err)
1979 goto done;
1980 if (got_object_id_cmp(old_id, new_id) == 0)
1981 goto done;
1983 err = got_ref_change_ref(ref, new_id);
1984 if (err)
1985 goto done;
1986 err = got_ref_write(ref, repo);
1987 if (err)
1988 goto done;
1991 if (verbosity >= 0)
1992 printf("Updated %s: %s\n", got_ref_get_name(ref),
1993 new_id_str);
1994 done:
1995 free(old_id);
1996 free(new_id_str);
1997 return err;
2000 static const struct got_error *
2001 update_symref(const char *refname, struct got_reference *target_ref,
2002 int verbosity, struct got_repository *repo)
2004 const struct got_error *err = NULL, *unlock_err;
2005 struct got_reference *symref;
2006 int symref_is_locked = 0;
2008 err = got_ref_open(&symref, repo, refname, 1);
2009 if (err) {
2010 if (err->code != GOT_ERR_NOT_REF)
2011 return err;
2012 err = got_ref_alloc_symref(&symref, refname, target_ref);
2013 if (err)
2014 goto done;
2016 err = got_ref_write(symref, repo);
2017 if (err)
2018 goto done;
2020 if (verbosity >= 0)
2021 printf("Created reference %s: %s\n",
2022 got_ref_get_name(symref),
2023 got_ref_get_symref_target(symref));
2024 } else {
2025 symref_is_locked = 1;
2027 if (strcmp(got_ref_get_symref_target(symref),
2028 got_ref_get_name(target_ref)) == 0)
2029 goto done;
2031 err = got_ref_change_symref(symref,
2032 got_ref_get_name(target_ref));
2033 if (err)
2034 goto done;
2036 err = got_ref_write(symref, repo);
2037 if (err)
2038 goto done;
2040 if (verbosity >= 0)
2041 printf("Updated %s: %s\n", got_ref_get_name(symref),
2042 got_ref_get_symref_target(symref));
2045 done:
2046 if (symref_is_locked) {
2047 unlock_err = got_ref_unlock(symref);
2048 if (unlock_err && err == NULL)
2049 err = unlock_err;
2051 got_ref_close(symref);
2052 return err;
2055 __dead static void
2056 usage_fetch(void)
2058 fprintf(stderr, "usage: %s fetch [-adlqtvX] [-b branch] "
2059 "[-R reference] [-r repository-path] [remote-repository]\n",
2060 getprogname());
2061 exit(1);
2064 static const struct got_error *
2065 delete_missing_ref(struct got_reference *ref,
2066 int verbosity, struct got_repository *repo)
2068 const struct got_error *err = NULL;
2069 struct got_object_id *id = NULL;
2070 char *id_str = NULL;
2072 if (got_ref_is_symbolic(ref)) {
2073 err = got_ref_delete(ref, repo);
2074 if (err)
2075 return err;
2076 if (verbosity >= 0) {
2077 printf("Deleted %s: %s\n",
2078 got_ref_get_name(ref),
2079 got_ref_get_symref_target(ref));
2081 } else {
2082 err = got_ref_resolve(&id, repo, ref);
2083 if (err)
2084 return err;
2085 err = got_object_id_str(&id_str, id);
2086 if (err)
2087 goto done;
2089 err = got_ref_delete(ref, repo);
2090 if (err)
2091 goto done;
2092 if (verbosity >= 0) {
2093 printf("Deleted %s: %s\n",
2094 got_ref_get_name(ref), id_str);
2097 done:
2098 free(id);
2099 free(id_str);
2100 return err;
2103 static const struct got_error *
2104 delete_missing_refs(struct got_pathlist_head *their_refs,
2105 struct got_pathlist_head *their_symrefs,
2106 const struct got_remote_repo *remote,
2107 int verbosity, struct got_repository *repo)
2109 const struct got_error *err = NULL, *unlock_err;
2110 struct got_reflist_head my_refs;
2111 struct got_reflist_entry *re;
2112 struct got_pathlist_entry *pe;
2113 char *remote_namespace = NULL;
2114 char *local_refname = NULL;
2116 TAILQ_INIT(&my_refs);
2118 if (asprintf(&remote_namespace, "refs/remotes/%s/", remote->name)
2119 == -1)
2120 return got_error_from_errno("asprintf");
2122 err = got_ref_list(&my_refs, repo, NULL, got_ref_cmp_by_name, NULL);
2123 if (err)
2124 goto done;
2126 TAILQ_FOREACH(re, &my_refs, entry) {
2127 const char *refname = got_ref_get_name(re->ref);
2128 const char *their_refname;
2130 if (remote->mirror_references) {
2131 their_refname = refname;
2132 } else {
2133 if (strncmp(refname, remote_namespace,
2134 strlen(remote_namespace)) == 0) {
2135 if (strcmp(refname + strlen(remote_namespace),
2136 GOT_REF_HEAD) == 0)
2137 continue;
2138 if (asprintf(&local_refname, "refs/heads/%s",
2139 refname + strlen(remote_namespace)) == -1) {
2140 err = got_error_from_errno("asprintf");
2141 goto done;
2143 } else if (strncmp(refname, "refs/tags/", 10) != 0)
2144 continue;
2146 their_refname = local_refname;
2149 TAILQ_FOREACH(pe, their_refs, entry) {
2150 if (strcmp(their_refname, pe->path) == 0)
2151 break;
2153 if (pe != NULL)
2154 continue;
2156 TAILQ_FOREACH(pe, their_symrefs, entry) {
2157 if (strcmp(their_refname, pe->path) == 0)
2158 break;
2160 if (pe != NULL)
2161 continue;
2163 err = delete_missing_ref(re->ref, verbosity, repo);
2164 if (err)
2165 break;
2167 if (local_refname) {
2168 struct got_reference *ref;
2169 err = got_ref_open(&ref, repo, local_refname, 1);
2170 if (err) {
2171 if (err->code != GOT_ERR_NOT_REF)
2172 break;
2173 free(local_refname);
2174 local_refname = NULL;
2175 continue;
2177 err = delete_missing_ref(ref, verbosity, repo);
2178 if (err)
2179 break;
2180 unlock_err = got_ref_unlock(ref);
2181 got_ref_close(ref);
2182 if (unlock_err && err == NULL) {
2183 err = unlock_err;
2184 break;
2187 free(local_refname);
2188 local_refname = NULL;
2191 done:
2192 got_ref_list_free(&my_refs);
2193 free(remote_namespace);
2194 free(local_refname);
2195 return err;
2198 static const struct got_error *
2199 update_wanted_ref(const char *refname, struct got_object_id *id,
2200 const char *remote_repo_name, int verbosity, struct got_repository *repo)
2202 const struct got_error *err, *unlock_err;
2203 char *remote_refname;
2204 struct got_reference *ref;
2206 if (strncmp("refs/", refname, 5) == 0)
2207 refname += 5;
2209 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
2210 remote_repo_name, refname) == -1)
2211 return got_error_from_errno("asprintf");
2213 err = got_ref_open(&ref, repo, remote_refname, 1);
2214 if (err) {
2215 if (err->code != GOT_ERR_NOT_REF)
2216 goto done;
2217 err = create_ref(remote_refname, id, verbosity, repo);
2218 } else {
2219 err = update_ref(ref, id, 0, verbosity, repo);
2220 unlock_err = got_ref_unlock(ref);
2221 if (unlock_err && err == NULL)
2222 err = unlock_err;
2223 got_ref_close(ref);
2225 done:
2226 free(remote_refname);
2227 return err;
2230 static const struct got_error *
2231 delete_ref(struct got_repository *repo, struct got_reference *ref)
2233 const struct got_error *err = NULL;
2234 struct got_object_id *id = NULL;
2235 char *id_str = NULL;
2236 const char *target;
2238 if (got_ref_is_symbolic(ref)) {
2239 target = got_ref_get_symref_target(ref);
2240 } else {
2241 err = got_ref_resolve(&id, repo, ref);
2242 if (err)
2243 goto done;
2244 err = got_object_id_str(&id_str, id);
2245 if (err)
2246 goto done;
2247 target = id_str;
2250 err = got_ref_delete(ref, repo);
2251 if (err)
2252 goto done;
2254 printf("Deleted %s: %s\n", got_ref_get_name(ref), target);
2255 done:
2256 free(id);
2257 free(id_str);
2258 return err;
2261 static const struct got_error *
2262 delete_refs_for_remote(struct got_repository *repo, const char *remote_name)
2264 const struct got_error *err = NULL;
2265 struct got_reflist_head refs;
2266 struct got_reflist_entry *re;
2267 char *prefix;
2269 TAILQ_INIT(&refs);
2271 if (asprintf(&prefix, "refs/remotes/%s", remote_name) == -1) {
2272 err = got_error_from_errno("asprintf");
2273 goto done;
2275 err = got_ref_list(&refs, repo, prefix, got_ref_cmp_by_name, NULL);
2276 if (err)
2277 goto done;
2279 TAILQ_FOREACH(re, &refs, entry)
2280 delete_ref(repo, re->ref);
2281 done:
2282 got_ref_list_free(&refs);
2283 return err;
2286 static const struct got_error *
2287 cmd_fetch(int argc, char *argv[])
2289 const struct got_error *error = NULL, *unlock_err;
2290 char *cwd = NULL, *repo_path = NULL;
2291 const char *remote_name;
2292 char *proto = NULL, *host = NULL, *port = NULL;
2293 char *repo_name = NULL, *server_path = NULL;
2294 const struct got_remote_repo *remotes;
2295 struct got_remote_repo *remote = NULL;
2296 int nremotes;
2297 char *id_str = NULL;
2298 struct got_repository *repo = NULL;
2299 struct got_worktree *worktree = NULL;
2300 const struct got_gotconfig *repo_conf = NULL, *worktree_conf = NULL;
2301 struct got_pathlist_head refs, symrefs, wanted_branches, wanted_refs;
2302 char *head_refname = NULL;
2303 struct got_pathlist_entry *pe;
2304 struct got_reflist_head remote_refs;
2305 struct got_reflist_entry *re;
2306 struct got_object_id *pack_hash = NULL;
2307 int i, ch, fetchfd = -1, fetchstatus;
2308 pid_t fetchpid = -1;
2309 struct got_fetch_progress_arg fpa;
2310 int verbosity = 0, fetch_all_branches = 0, list_refs_only = 0;
2311 int delete_refs = 0, replace_tags = 0, delete_remote = 0;
2312 int *pack_fds = NULL, have_bflag = 0;
2313 const char *remote_head = NULL, *worktree_branch = NULL;
2315 TAILQ_INIT(&refs);
2316 TAILQ_INIT(&symrefs);
2317 TAILQ_INIT(&remote_refs);
2318 TAILQ_INIT(&wanted_branches);
2319 TAILQ_INIT(&wanted_refs);
2321 while ((ch = getopt(argc, argv, "ab:dlqR:r:tvX")) != -1) {
2322 switch (ch) {
2323 case 'a':
2324 fetch_all_branches = 1;
2325 break;
2326 case 'b':
2327 error = got_pathlist_append(&wanted_branches,
2328 optarg, NULL);
2329 if (error)
2330 return error;
2331 have_bflag = 1;
2332 break;
2333 case 'd':
2334 delete_refs = 1;
2335 break;
2336 case 'l':
2337 list_refs_only = 1;
2338 break;
2339 case 'q':
2340 verbosity = -1;
2341 break;
2342 case 'R':
2343 error = got_pathlist_append(&wanted_refs,
2344 optarg, NULL);
2345 if (error)
2346 return error;
2347 break;
2348 case 'r':
2349 repo_path = realpath(optarg, NULL);
2350 if (repo_path == NULL)
2351 return got_error_from_errno2("realpath",
2352 optarg);
2353 got_path_strip_trailing_slashes(repo_path);
2354 break;
2355 case 't':
2356 replace_tags = 1;
2357 break;
2358 case 'v':
2359 if (verbosity < 0)
2360 verbosity = 0;
2361 else if (verbosity < 3)
2362 verbosity++;
2363 break;
2364 case 'X':
2365 delete_remote = 1;
2366 break;
2367 default:
2368 usage_fetch();
2369 break;
2372 argc -= optind;
2373 argv += optind;
2375 if (fetch_all_branches && !TAILQ_EMPTY(&wanted_branches))
2376 option_conflict('a', 'b');
2377 if (list_refs_only) {
2378 if (!TAILQ_EMPTY(&wanted_branches))
2379 option_conflict('l', 'b');
2380 if (fetch_all_branches)
2381 option_conflict('l', 'a');
2382 if (delete_refs)
2383 option_conflict('l', 'd');
2384 if (delete_remote)
2385 option_conflict('l', 'X');
2387 if (delete_remote) {
2388 if (fetch_all_branches)
2389 option_conflict('X', 'a');
2390 if (!TAILQ_EMPTY(&wanted_branches))
2391 option_conflict('X', 'b');
2392 if (delete_refs)
2393 option_conflict('X', 'd');
2394 if (replace_tags)
2395 option_conflict('X', 't');
2396 if (!TAILQ_EMPTY(&wanted_refs))
2397 option_conflict('X', 'R');
2400 if (argc == 0) {
2401 if (delete_remote)
2402 errx(1, "-X option requires a remote name");
2403 remote_name = GOT_FETCH_DEFAULT_REMOTE_NAME;
2404 } else if (argc == 1)
2405 remote_name = argv[0];
2406 else
2407 usage_fetch();
2409 cwd = getcwd(NULL, 0);
2410 if (cwd == NULL) {
2411 error = got_error_from_errno("getcwd");
2412 goto done;
2415 error = got_repo_pack_fds_open(&pack_fds);
2416 if (error != NULL)
2417 goto done;
2419 if (repo_path == NULL) {
2420 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
2421 if (error && error->code != GOT_ERR_NOT_WORKTREE)
2422 goto done;
2423 else
2424 error = NULL;
2425 if (worktree) {
2426 repo_path =
2427 strdup(got_worktree_get_repo_path(worktree));
2428 if (repo_path == NULL)
2429 error = got_error_from_errno("strdup");
2430 if (error)
2431 goto done;
2432 } else {
2433 repo_path = strdup(cwd);
2434 if (repo_path == NULL) {
2435 error = got_error_from_errno("strdup");
2436 goto done;
2441 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
2442 if (error)
2443 goto done;
2445 if (delete_remote) {
2446 error = delete_refs_for_remote(repo, remote_name);
2447 goto done; /* nothing else to do */
2450 if (worktree) {
2451 worktree_conf = got_worktree_get_gotconfig(worktree);
2452 if (worktree_conf) {
2453 got_gotconfig_get_remotes(&nremotes, &remotes,
2454 worktree_conf);
2455 for (i = 0; i < nremotes; i++) {
2456 if (strcmp(remotes[i].name, remote_name) == 0) {
2457 error = got_repo_remote_repo_dup(&remote,
2458 &remotes[i]);
2459 if (error)
2460 goto done;
2461 break;
2466 if (remote == NULL) {
2467 repo_conf = got_repo_get_gotconfig(repo);
2468 if (repo_conf) {
2469 got_gotconfig_get_remotes(&nremotes, &remotes,
2470 repo_conf);
2471 for (i = 0; i < nremotes; i++) {
2472 if (strcmp(remotes[i].name, remote_name) == 0) {
2473 error = got_repo_remote_repo_dup(&remote,
2474 &remotes[i]);
2475 if (error)
2476 goto done;
2477 break;
2482 if (remote == NULL) {
2483 got_repo_get_gitconfig_remotes(&nremotes, &remotes, repo);
2484 for (i = 0; i < nremotes; i++) {
2485 if (strcmp(remotes[i].name, remote_name) == 0) {
2486 error = got_repo_remote_repo_dup(&remote,
2487 &remotes[i]);
2488 if (error)
2489 goto done;
2490 break;
2494 if (remote == NULL) {
2495 error = got_error_path(remote_name, GOT_ERR_NO_REMOTE);
2496 goto done;
2499 if (TAILQ_EMPTY(&wanted_branches)) {
2500 if (!fetch_all_branches)
2501 fetch_all_branches = remote->fetch_all_branches;
2502 for (i = 0; i < remote->nfetch_branches; i++) {
2503 error = got_pathlist_append(&wanted_branches,
2504 remote->fetch_branches[i], NULL);
2505 if (error)
2506 goto done;
2509 if (TAILQ_EMPTY(&wanted_refs)) {
2510 for (i = 0; i < remote->nfetch_refs; i++) {
2511 error = got_pathlist_append(&wanted_refs,
2512 remote->fetch_refs[i], NULL);
2513 if (error)
2514 goto done;
2518 error = got_dial_parse_uri(&proto, &host, &port, &server_path,
2519 &repo_name, remote->fetch_url);
2520 if (error)
2521 goto done;
2523 if (strcmp(proto, "git") == 0) {
2524 #ifndef PROFILE
2525 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
2526 "sendfd dns inet unveil", NULL) == -1)
2527 err(1, "pledge");
2528 #endif
2529 } else if (strcmp(proto, "git+ssh") == 0 ||
2530 strcmp(proto, "ssh") == 0 ||
2531 strcmp(proto, "git+http") == 0 ||
2532 strcmp(proto, "http") == 0 ||
2533 strcmp(proto, "git+https") == 0 ||
2534 strcmp(proto, "https") == 0) {
2535 #ifndef PROFILE
2536 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
2537 "sendfd unveil", NULL) == -1)
2538 err(1, "pledge");
2539 #endif
2540 } else {
2541 error = got_error_path(proto, GOT_ERR_BAD_PROTO);
2542 goto done;
2545 error = got_dial_apply_unveil(proto);
2546 if (error)
2547 goto done;
2549 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
2550 if (error)
2551 goto done;
2553 if (worktree) {
2554 head_refname = strdup(got_worktree_get_head_ref_name(worktree));
2555 if (head_refname == NULL) {
2556 error = got_error_from_errno("strdup");
2557 goto done;
2560 /* Release work tree lock. */
2561 got_worktree_close(worktree);
2562 worktree = NULL;
2565 if (verbosity >= 0) {
2566 printf("Connecting to \"%s\" %s://%s%s%s%s%s\n",
2567 remote->name, proto, host,
2568 port ? ":" : "", port ? port : "",
2569 *server_path == '/' ? "" : "/", server_path);
2572 error = got_fetch_connect(&fetchpid, &fetchfd, proto, host, port,
2573 server_path, verbosity);
2574 if (error)
2575 goto done;
2576 #ifndef PROFILE
2577 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd",
2578 NULL) == -1)
2579 err(1, "pledge");
2580 #endif
2581 if (!have_bflag) {
2583 * If set, get this remote's HEAD ref target so
2584 * if it has changed on the server we can fetch it.
2586 error = got_ref_list(&remote_refs, repo, "refs/remotes",
2587 got_ref_cmp_by_name, repo);
2588 if (error)
2589 goto done;
2591 TAILQ_FOREACH(re, &remote_refs, entry) {
2592 const char *remote_refname, *remote_target;
2593 size_t remote_name_len;
2595 if (!got_ref_is_symbolic(re->ref))
2596 continue;
2598 remote_name_len = strlen(remote->name);
2599 remote_refname = got_ref_get_name(re->ref);
2601 /* we only want refs/remotes/$remote->name/HEAD */
2602 if (strncmp(remote_refname + 13, remote->name,
2603 remote_name_len) != 0)
2604 continue;
2606 if (strcmp(remote_refname + remote_name_len + 14,
2607 GOT_REF_HEAD) != 0)
2608 continue;
2611 * Take the name itself because we already
2612 * only match with refs/heads/ in fetch_pack().
2614 remote_target = got_ref_get_symref_target(re->ref);
2615 remote_head = remote_target + remote_name_len + 14;
2616 break;
2619 if (head_refname &&
2620 strncmp(head_refname, "refs/heads/", 11) == 0)
2621 worktree_branch = head_refname;
2624 fpa.last_scaled_size[0] = '\0';
2625 fpa.last_p_indexed = -1;
2626 fpa.last_p_resolved = -1;
2627 fpa.verbosity = verbosity;
2628 fpa.repo = repo;
2629 fpa.create_configs = 0;
2630 fpa.configs_created = 0;
2631 memset(&fpa.config_info, 0, sizeof(fpa.config_info));
2633 error = got_fetch_pack(&pack_hash, &refs, &symrefs, remote->name,
2634 remote->mirror_references, fetch_all_branches, &wanted_branches,
2635 &wanted_refs, list_refs_only, verbosity, fetchfd, repo,
2636 worktree_branch, remote_head, have_bflag, fetch_progress, &fpa);
2637 if (error)
2638 goto done;
2640 if (list_refs_only) {
2641 error = list_remote_refs(&symrefs, &refs);
2642 goto done;
2645 if (pack_hash == NULL) {
2646 if (verbosity >= 0)
2647 printf("Already up-to-date\n");
2648 } else if (verbosity >= 0) {
2649 error = got_object_id_str(&id_str, pack_hash);
2650 if (error)
2651 goto done;
2652 printf("\nFetched %s.pack\n", id_str);
2653 free(id_str);
2654 id_str = NULL;
2657 /* Update references provided with the pack file. */
2658 TAILQ_FOREACH(pe, &refs, entry) {
2659 const char *refname = pe->path;
2660 struct got_object_id *id = pe->data;
2661 struct got_reference *ref;
2662 char *remote_refname;
2664 if (is_wanted_ref(&wanted_refs, refname) &&
2665 !remote->mirror_references) {
2666 error = update_wanted_ref(refname, id,
2667 remote->name, verbosity, repo);
2668 if (error)
2669 goto done;
2670 continue;
2673 if (remote->mirror_references ||
2674 strncmp("refs/tags/", refname, 10) == 0) {
2675 error = got_ref_open(&ref, repo, refname, 1);
2676 if (error) {
2677 if (error->code != GOT_ERR_NOT_REF)
2678 goto done;
2679 error = create_ref(refname, id, verbosity,
2680 repo);
2681 if (error)
2682 goto done;
2683 } else {
2684 error = update_ref(ref, id, replace_tags,
2685 verbosity, repo);
2686 unlock_err = got_ref_unlock(ref);
2687 if (unlock_err && error == NULL)
2688 error = unlock_err;
2689 got_ref_close(ref);
2690 if (error)
2691 goto done;
2693 } else if (strncmp("refs/heads/", refname, 11) == 0) {
2694 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
2695 remote_name, refname + 11) == -1) {
2696 error = got_error_from_errno("asprintf");
2697 goto done;
2700 error = got_ref_open(&ref, repo, remote_refname, 1);
2701 if (error) {
2702 if (error->code != GOT_ERR_NOT_REF)
2703 goto done;
2704 error = create_ref(remote_refname, id,
2705 verbosity, repo);
2706 if (error)
2707 goto done;
2708 } else {
2709 error = update_ref(ref, id, replace_tags,
2710 verbosity, repo);
2711 unlock_err = got_ref_unlock(ref);
2712 if (unlock_err && error == NULL)
2713 error = unlock_err;
2714 got_ref_close(ref);
2715 if (error)
2716 goto done;
2719 /* Also create a local branch if none exists yet. */
2720 error = got_ref_open(&ref, repo, refname, 1);
2721 if (error) {
2722 if (error->code != GOT_ERR_NOT_REF)
2723 goto done;
2724 error = create_ref(refname, id, verbosity,
2725 repo);
2726 if (error)
2727 goto done;
2728 } else {
2729 unlock_err = got_ref_unlock(ref);
2730 if (unlock_err && error == NULL)
2731 error = unlock_err;
2732 got_ref_close(ref);
2736 if (delete_refs) {
2737 error = delete_missing_refs(&refs, &symrefs, remote,
2738 verbosity, repo);
2739 if (error)
2740 goto done;
2743 if (!remote->mirror_references) {
2744 /* Update remote HEAD reference if the server provided one. */
2745 TAILQ_FOREACH(pe, &symrefs, entry) {
2746 struct got_reference *target_ref;
2747 const char *refname = pe->path;
2748 const char *target = pe->data;
2749 char *remote_refname = NULL, *remote_target = NULL;
2751 if (strcmp(refname, GOT_REF_HEAD) != 0)
2752 continue;
2754 if (strncmp("refs/heads/", target, 11) != 0)
2755 continue;
2757 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
2758 remote->name, refname) == -1) {
2759 error = got_error_from_errno("asprintf");
2760 goto done;
2762 if (asprintf(&remote_target, "refs/remotes/%s/%s",
2763 remote->name, target + 11) == -1) {
2764 error = got_error_from_errno("asprintf");
2765 free(remote_refname);
2766 goto done;
2769 error = got_ref_open(&target_ref, repo, remote_target,
2770 0);
2771 if (error) {
2772 free(remote_refname);
2773 free(remote_target);
2774 if (error->code == GOT_ERR_NOT_REF) {
2775 error = NULL;
2776 continue;
2778 goto done;
2780 error = update_symref(remote_refname, target_ref,
2781 verbosity, repo);
2782 free(remote_refname);
2783 free(remote_target);
2784 got_ref_close(target_ref);
2785 if (error)
2786 goto done;
2789 done:
2790 if (fetchpid > 0) {
2791 if (kill(fetchpid, SIGTERM) == -1)
2792 error = got_error_from_errno("kill");
2793 if (waitpid(fetchpid, &fetchstatus, 0) == -1 && error == NULL)
2794 error = got_error_from_errno("waitpid");
2796 if (fetchfd != -1 && close(fetchfd) == -1 && error == NULL)
2797 error = got_error_from_errno("close");
2798 if (repo) {
2799 const struct got_error *close_err = got_repo_close(repo);
2800 if (error == NULL)
2801 error = close_err;
2803 if (worktree)
2804 got_worktree_close(worktree);
2805 if (pack_fds) {
2806 const struct got_error *pack_err =
2807 got_repo_pack_fds_close(pack_fds);
2808 if (error == NULL)
2809 error = pack_err;
2811 got_pathlist_free(&refs, GOT_PATHLIST_FREE_ALL);
2812 got_pathlist_free(&symrefs, GOT_PATHLIST_FREE_ALL);
2813 got_pathlist_free(&wanted_branches, GOT_PATHLIST_FREE_NONE);
2814 got_pathlist_free(&wanted_refs, GOT_PATHLIST_FREE_NONE);
2815 got_ref_list_free(&remote_refs);
2816 got_repo_free_remote_repo_data(remote);
2817 free(remote);
2818 free(head_refname);
2819 free(id_str);
2820 free(cwd);
2821 free(repo_path);
2822 free(pack_hash);
2823 free(proto);
2824 free(host);
2825 free(port);
2826 free(server_path);
2827 free(repo_name);
2828 return error;
2832 __dead static void
2833 usage_checkout(void)
2835 fprintf(stderr, "usage: %s checkout [-Eq] [-b branch] [-c commit] "
2836 "[-p path-prefix] repository-path [work-tree-path]\n",
2837 getprogname());
2838 exit(1);
2841 static void
2842 show_worktree_base_ref_warning(void)
2844 fprintf(stderr, "%s: warning: could not create a reference "
2845 "to the work tree's base commit; the commit could be "
2846 "garbage-collected by Git or 'gotadmin cleanup'; making the "
2847 "repository writable and running 'got update' will prevent this\n",
2848 getprogname());
2851 struct got_checkout_progress_arg {
2852 const char *worktree_path;
2853 int had_base_commit_ref_error;
2854 int verbosity;
2857 static const struct got_error *
2858 checkout_progress(void *arg, unsigned char status, const char *path)
2860 struct got_checkout_progress_arg *a = arg;
2862 /* Base commit bump happens silently. */
2863 if (status == GOT_STATUS_BUMP_BASE)
2864 return NULL;
2866 if (status == GOT_STATUS_BASE_REF_ERR) {
2867 a->had_base_commit_ref_error = 1;
2868 return NULL;
2871 while (path[0] == '/')
2872 path++;
2874 if (a->verbosity >= 0)
2875 printf("%c %s/%s\n", status, a->worktree_path, path);
2877 return NULL;
2880 static const struct got_error *
2881 check_cancelled(void *arg)
2883 if (sigint_received || sigpipe_received)
2884 return got_error(GOT_ERR_CANCELLED);
2885 return NULL;
2888 static const struct got_error *
2889 check_linear_ancestry(struct got_object_id *commit_id,
2890 struct got_object_id *base_commit_id, int allow_forwards_in_time_only,
2891 struct got_repository *repo)
2893 const struct got_error *err = NULL;
2894 struct got_object_id *yca_id;
2896 err = got_commit_graph_find_youngest_common_ancestor(&yca_id,
2897 commit_id, base_commit_id, 1, 0, repo, check_cancelled, NULL);
2898 if (err)
2899 return err;
2901 if (yca_id == NULL)
2902 return got_error(GOT_ERR_ANCESTRY);
2905 * Require a straight line of history between the target commit
2906 * and the work tree's base commit.
2908 * Non-linear situations such as this require a rebase:
2910 * (commit) D F (base_commit)
2911 * \ /
2912 * C E
2913 * \ /
2914 * B (yca)
2915 * |
2916 * A
2918 * 'got update' only handles linear cases:
2919 * Update forwards in time: A (base/yca) - B - C - D (commit)
2920 * Update backwards in time: D (base) - C - B - A (commit/yca)
2922 if (allow_forwards_in_time_only) {
2923 if (got_object_id_cmp(base_commit_id, yca_id) != 0)
2924 return got_error(GOT_ERR_ANCESTRY);
2925 } else if (got_object_id_cmp(commit_id, yca_id) != 0 &&
2926 got_object_id_cmp(base_commit_id, yca_id) != 0)
2927 return got_error(GOT_ERR_ANCESTRY);
2929 free(yca_id);
2930 return NULL;
2933 static const struct got_error *
2934 check_same_branch(struct got_object_id *commit_id,
2935 struct got_reference *head_ref, struct got_repository *repo)
2937 const struct got_error *err = NULL;
2938 struct got_commit_graph *graph = NULL;
2939 struct got_object_id *head_commit_id = NULL;
2941 err = got_ref_resolve(&head_commit_id, repo, head_ref);
2942 if (err)
2943 goto done;
2945 if (got_object_id_cmp(head_commit_id, commit_id) == 0)
2946 goto done;
2948 err = got_commit_graph_open(&graph, "/", 1);
2949 if (err)
2950 goto done;
2952 err = got_commit_graph_bfsort(graph, head_commit_id, repo,
2953 check_cancelled, NULL);
2954 if (err)
2955 goto done;
2957 for (;;) {
2958 struct got_object_id id;
2960 err = got_commit_graph_iter_next(&id, graph, repo,
2961 check_cancelled, NULL);
2962 if (err) {
2963 if (err->code == GOT_ERR_ITER_COMPLETED)
2964 err = got_error(GOT_ERR_ANCESTRY);
2965 break;
2968 if (got_object_id_cmp(&id, commit_id) == 0)
2969 break;
2971 done:
2972 if (graph)
2973 got_commit_graph_close(graph);
2974 free(head_commit_id);
2975 return err;
2978 static const struct got_error *
2979 checkout_ancestry_error(struct got_reference *ref, const char *commit_id_str)
2981 static char msg[512];
2982 const char *branch_name;
2984 if (got_ref_is_symbolic(ref))
2985 branch_name = got_ref_get_symref_target(ref);
2986 else
2987 branch_name = got_ref_get_name(ref);
2989 if (strncmp("refs/heads/", branch_name, 11) == 0)
2990 branch_name += 11;
2992 snprintf(msg, sizeof(msg),
2993 "target commit is not contained in branch '%s'; "
2994 "the branch to use must be specified with -b; "
2995 "if necessary a new branch can be created for "
2996 "this commit with 'got branch -c %s BRANCH_NAME'",
2997 branch_name, commit_id_str);
2999 return got_error_msg(GOT_ERR_ANCESTRY, msg);
3002 static const struct got_error *
3003 cmd_checkout(int argc, char *argv[])
3005 const struct got_error *close_err, *error = NULL;
3006 struct got_repository *repo = NULL;
3007 struct got_reference *head_ref = NULL, *ref = NULL;
3008 struct got_worktree *worktree = NULL;
3009 char *repo_path = NULL;
3010 char *worktree_path = NULL;
3011 const char *path_prefix = "";
3012 const char *branch_name = GOT_REF_HEAD, *refname = NULL;
3013 char *commit_id_str = NULL, *keyword_idstr = NULL;
3014 struct got_object_id *commit_id = NULL;
3015 char *cwd = NULL;
3016 int ch, same_path_prefix, allow_nonempty = 0, verbosity = 0;
3017 struct got_pathlist_head paths;
3018 struct got_checkout_progress_arg cpa;
3019 int *pack_fds = NULL;
3021 TAILQ_INIT(&paths);
3023 #ifndef PROFILE
3024 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
3025 "unveil", NULL) == -1)
3026 err(1, "pledge");
3027 #endif
3029 while ((ch = getopt(argc, argv, "b:c:Ep:q")) != -1) {
3030 switch (ch) {
3031 case 'b':
3032 branch_name = optarg;
3033 break;
3034 case 'c':
3035 commit_id_str = strdup(optarg);
3036 if (commit_id_str == NULL)
3037 return got_error_from_errno("strdup");
3038 break;
3039 case 'E':
3040 allow_nonempty = 1;
3041 break;
3042 case 'p':
3043 path_prefix = optarg;
3044 break;
3045 case 'q':
3046 verbosity = -1;
3047 break;
3048 default:
3049 usage_checkout();
3050 /* NOTREACHED */
3054 argc -= optind;
3055 argv += optind;
3057 if (argc == 1) {
3058 char *base, *dotgit;
3059 const char *path;
3060 repo_path = realpath(argv[0], NULL);
3061 if (repo_path == NULL)
3062 return got_error_from_errno2("realpath", argv[0]);
3063 cwd = getcwd(NULL, 0);
3064 if (cwd == NULL) {
3065 error = got_error_from_errno("getcwd");
3066 goto done;
3068 if (path_prefix[0])
3069 path = path_prefix;
3070 else
3071 path = repo_path;
3072 error = got_path_basename(&base, path);
3073 if (error)
3074 goto done;
3075 dotgit = strstr(base, ".git");
3076 if (dotgit)
3077 *dotgit = '\0';
3078 if (asprintf(&worktree_path, "%s/%s", cwd, base) == -1) {
3079 error = got_error_from_errno("asprintf");
3080 free(base);
3081 goto done;
3083 free(base);
3084 } else if (argc == 2) {
3085 repo_path = realpath(argv[0], NULL);
3086 if (repo_path == NULL) {
3087 error = got_error_from_errno2("realpath", argv[0]);
3088 goto done;
3090 worktree_path = realpath(argv[1], NULL);
3091 if (worktree_path == NULL) {
3092 if (errno != ENOENT) {
3093 error = got_error_from_errno2("realpath",
3094 argv[1]);
3095 goto done;
3097 worktree_path = strdup(argv[1]);
3098 if (worktree_path == NULL) {
3099 error = got_error_from_errno("strdup");
3100 goto done;
3103 } else
3104 usage_checkout();
3106 got_path_strip_trailing_slashes(repo_path);
3107 got_path_strip_trailing_slashes(worktree_path);
3109 if (got_path_is_child(worktree_path, repo_path, strlen(repo_path)) ||
3110 got_path_is_child(repo_path, worktree_path,
3111 strlen(worktree_path))) {
3112 error = got_error_fmt(GOT_ERR_BAD_PATH,
3113 "work tree and repository paths may not overlap: %s",
3114 worktree_path);
3115 goto done;
3118 error = got_repo_pack_fds_open(&pack_fds);
3119 if (error != NULL)
3120 goto done;
3122 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
3123 if (error != NULL)
3124 goto done;
3126 /* Pre-create work tree path for unveil(2) */
3127 error = got_path_mkdir(worktree_path);
3128 if (error) {
3129 if (!(error->code == GOT_ERR_ERRNO && errno == EISDIR) &&
3130 !(error->code == GOT_ERR_ERRNO && errno == EEXIST))
3131 goto done;
3132 if (!allow_nonempty &&
3133 !got_path_dir_is_empty(worktree_path)) {
3134 error = got_error_path(worktree_path,
3135 GOT_ERR_DIR_NOT_EMPTY);
3136 goto done;
3140 error = apply_unveil(got_repo_get_path(repo), 0, worktree_path);
3141 if (error)
3142 goto done;
3144 error = got_ref_open(&head_ref, repo, branch_name, 0);
3145 if (error != NULL)
3146 goto done;
3148 error = got_worktree_init(worktree_path, head_ref, path_prefix,
3149 GOT_WORKTREE_GOT_DIR, repo);
3150 if (error != NULL && !(error->code == GOT_ERR_ERRNO && errno == EEXIST))
3151 goto done;
3153 error = got_worktree_open(&worktree, worktree_path,
3154 GOT_WORKTREE_GOT_DIR);
3155 if (error != NULL)
3156 goto done;
3158 error = got_worktree_match_path_prefix(&same_path_prefix, worktree,
3159 path_prefix);
3160 if (error != NULL)
3161 goto done;
3162 if (!same_path_prefix) {
3163 error = got_error(GOT_ERR_PATH_PREFIX);
3164 goto done;
3167 if (commit_id_str) {
3168 struct got_reflist_head refs;
3169 TAILQ_INIT(&refs);
3170 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
3171 NULL);
3172 if (error)
3173 goto done;
3175 error = got_keyword_to_idstr(&keyword_idstr, commit_id_str,
3176 repo, worktree);
3177 if (error != NULL)
3178 goto done;
3179 if (keyword_idstr != NULL) {
3180 free(commit_id_str);
3181 commit_id_str = keyword_idstr;
3184 error = got_repo_match_object_id(&commit_id, NULL,
3185 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
3186 got_ref_list_free(&refs);
3187 if (error)
3188 goto done;
3189 error = check_linear_ancestry(commit_id,
3190 got_worktree_get_base_commit_id(worktree), 0, repo);
3191 if (error != NULL) {
3192 if (error->code == GOT_ERR_ANCESTRY) {
3193 error = checkout_ancestry_error(
3194 head_ref, commit_id_str);
3196 goto done;
3198 error = check_same_branch(commit_id, head_ref, repo);
3199 if (error) {
3200 if (error->code == GOT_ERR_ANCESTRY) {
3201 error = checkout_ancestry_error(
3202 head_ref, commit_id_str);
3204 goto done;
3206 error = got_worktree_set_base_commit_id(worktree, repo,
3207 commit_id);
3208 if (error)
3209 goto done;
3210 /* Expand potentially abbreviated commit ID string. */
3211 free(commit_id_str);
3212 error = got_object_id_str(&commit_id_str, commit_id);
3213 if (error)
3214 goto done;
3215 } else {
3216 commit_id = got_object_id_dup(
3217 got_worktree_get_base_commit_id(worktree));
3218 if (commit_id == NULL) {
3219 error = got_error_from_errno("got_object_id_dup");
3220 goto done;
3222 error = got_object_id_str(&commit_id_str, commit_id);
3223 if (error)
3224 goto done;
3227 error = got_pathlist_append(&paths, "", NULL);
3228 if (error)
3229 goto done;
3230 cpa.worktree_path = worktree_path;
3231 cpa.had_base_commit_ref_error = 0;
3232 cpa.verbosity = verbosity;
3233 error = got_worktree_checkout_files(worktree, &paths, repo,
3234 checkout_progress, &cpa, check_cancelled, NULL);
3235 if (error != NULL)
3236 goto done;
3238 if (got_ref_is_symbolic(head_ref)) {
3239 error = got_ref_resolve_symbolic(&ref, repo, head_ref);
3240 if (error)
3241 goto done;
3242 refname = got_ref_get_name(ref);
3243 } else
3244 refname = got_ref_get_name(head_ref);
3245 printf("Checked out %s: %s\n", refname, commit_id_str);
3246 printf("Now shut up and hack\n");
3247 if (cpa.had_base_commit_ref_error)
3248 show_worktree_base_ref_warning();
3249 done:
3250 if (pack_fds) {
3251 const struct got_error *pack_err =
3252 got_repo_pack_fds_close(pack_fds);
3253 if (error == NULL)
3254 error = pack_err;
3256 if (head_ref)
3257 got_ref_close(head_ref);
3258 if (ref)
3259 got_ref_close(ref);
3260 if (repo) {
3261 close_err = got_repo_close(repo);
3262 if (error == NULL)
3263 error = close_err;
3265 if (worktree != NULL) {
3266 close_err = got_worktree_close(worktree);
3267 if (error == NULL)
3268 error = close_err;
3270 got_pathlist_free(&paths, GOT_PATHLIST_FREE_NONE);
3271 free(commit_id_str);
3272 free(commit_id);
3273 free(repo_path);
3274 free(worktree_path);
3275 free(cwd);
3276 return error;
3279 struct got_update_progress_arg {
3280 int did_something;
3281 int conflicts;
3282 int obstructed;
3283 int not_updated;
3284 int missing;
3285 int not_deleted;
3286 int unversioned;
3287 int verbosity;
3290 static void
3291 print_update_progress_stats(struct got_update_progress_arg *upa)
3293 if (!upa->did_something)
3294 return;
3296 if (upa->conflicts > 0)
3297 printf("Files with new merge conflicts: %d\n", upa->conflicts);
3298 if (upa->obstructed > 0)
3299 printf("File paths obstructed by a non-regular file: %d\n",
3300 upa->obstructed);
3301 if (upa->not_updated > 0)
3302 printf("Files not updated because of existing merge "
3303 "conflicts: %d\n", upa->not_updated);
3307 * The meaning of some status codes differs between merge-style operations and
3308 * update operations. For example, the ! status code means "file was missing"
3309 * if changes were merged into the work tree, and "missing file was restored"
3310 * if the work tree was updated. This function should be used by any operation
3311 * which merges changes into the work tree without updating the work tree.
3313 static void
3314 print_merge_progress_stats(struct got_update_progress_arg *upa)
3316 if (!upa->did_something)
3317 return;
3319 if (upa->conflicts > 0)
3320 printf("Files with new merge conflicts: %d\n", upa->conflicts);
3321 if (upa->obstructed > 0)
3322 printf("File paths obstructed by a non-regular file: %d\n",
3323 upa->obstructed);
3324 if (upa->missing > 0)
3325 printf("Files which had incoming changes but could not be "
3326 "found in the work tree: %d\n", upa->missing);
3327 if (upa->not_deleted > 0)
3328 printf("Files not deleted due to differences in deleted "
3329 "content: %d\n", upa->not_deleted);
3330 if (upa->unversioned > 0)
3331 printf("Files not merged because an unversioned file was "
3332 "found in the work tree: %d\n", upa->unversioned);
3335 __dead static void
3336 usage_update(void)
3338 fprintf(stderr, "usage: %s update [-q] [-b branch] [-c commit] "
3339 "[path ...]\n", getprogname());
3340 exit(1);
3343 static const struct got_error *
3344 update_progress(void *arg, unsigned char status, const char *path)
3346 struct got_update_progress_arg *upa = arg;
3348 if (status == GOT_STATUS_EXISTS ||
3349 status == GOT_STATUS_BASE_REF_ERR)
3350 return NULL;
3352 upa->did_something = 1;
3354 /* Base commit bump happens silently. */
3355 if (status == GOT_STATUS_BUMP_BASE)
3356 return NULL;
3358 if (status == GOT_STATUS_CONFLICT)
3359 upa->conflicts++;
3360 if (status == GOT_STATUS_OBSTRUCTED)
3361 upa->obstructed++;
3362 if (status == GOT_STATUS_CANNOT_UPDATE)
3363 upa->not_updated++;
3364 if (status == GOT_STATUS_MISSING)
3365 upa->missing++;
3366 if (status == GOT_STATUS_CANNOT_DELETE)
3367 upa->not_deleted++;
3368 if (status == GOT_STATUS_UNVERSIONED)
3369 upa->unversioned++;
3371 while (path[0] == '/')
3372 path++;
3373 if (upa->verbosity >= 0)
3374 printf("%c %s\n", status, path);
3376 return NULL;
3379 static const struct got_error *
3380 switch_head_ref(struct got_reference *head_ref,
3381 struct got_object_id *commit_id, struct got_worktree *worktree,
3382 struct got_repository *repo)
3384 const struct got_error *err = NULL;
3385 char *base_id_str;
3386 int ref_has_moved = 0;
3388 /* Trivial case: switching between two different references. */
3389 if (strcmp(got_ref_get_name(head_ref),
3390 got_worktree_get_head_ref_name(worktree)) != 0) {
3391 printf("Switching work tree from %s to %s\n",
3392 got_worktree_get_head_ref_name(worktree),
3393 got_ref_get_name(head_ref));
3394 return got_worktree_set_head_ref(worktree, head_ref);
3397 err = check_linear_ancestry(commit_id,
3398 got_worktree_get_base_commit_id(worktree), 0, repo);
3399 if (err) {
3400 if (err->code != GOT_ERR_ANCESTRY)
3401 return err;
3402 ref_has_moved = 1;
3404 if (!ref_has_moved)
3405 return NULL;
3407 /* Switching to a rebased branch with the same reference name. */
3408 err = got_object_id_str(&base_id_str,
3409 got_worktree_get_base_commit_id(worktree));
3410 if (err)
3411 return err;
3412 printf("Reference %s now points at a different branch\n",
3413 got_worktree_get_head_ref_name(worktree));
3414 printf("Switching work tree from %s to %s\n", base_id_str,
3415 got_worktree_get_head_ref_name(worktree));
3416 return NULL;
3419 static const struct got_error *
3420 check_rebase_or_histedit_in_progress(struct got_worktree *worktree)
3422 const struct got_error *err;
3423 int in_progress;
3425 err = got_worktree_rebase_in_progress(&in_progress, worktree);
3426 if (err)
3427 return err;
3428 if (in_progress)
3429 return got_error(GOT_ERR_REBASING);
3431 err = got_worktree_histedit_in_progress(&in_progress, worktree);
3432 if (err)
3433 return err;
3434 if (in_progress)
3435 return got_error(GOT_ERR_HISTEDIT_BUSY);
3437 return NULL;
3440 static const struct got_error *
3441 check_merge_in_progress(struct got_worktree *worktree,
3442 struct got_repository *repo)
3444 const struct got_error *err;
3445 int in_progress;
3447 err = got_worktree_merge_in_progress(&in_progress, worktree, repo);
3448 if (err)
3449 return err;
3450 if (in_progress)
3451 return got_error(GOT_ERR_MERGE_BUSY);
3453 return NULL;
3456 static const struct got_error *
3457 get_worktree_paths_from_argv(struct got_pathlist_head *paths, int argc,
3458 char *argv[], struct got_worktree *worktree)
3460 const struct got_error *err = NULL;
3461 char *path;
3462 struct got_pathlist_entry *new;
3463 int i;
3465 if (argc == 0) {
3466 path = strdup("");
3467 if (path == NULL)
3468 return got_error_from_errno("strdup");
3469 return got_pathlist_append(paths, path, NULL);
3472 for (i = 0; i < argc; i++) {
3473 err = got_worktree_resolve_path(&path, worktree, argv[i]);
3474 if (err)
3475 break;
3476 err = got_pathlist_insert(&new, paths, path, NULL);
3477 if (err || new == NULL /* duplicate */) {
3478 free(path);
3479 if (err)
3480 break;
3484 return err;
3487 static const struct got_error *
3488 wrap_not_worktree_error(const struct got_error *orig_err,
3489 const char *cmdname, const char *path)
3491 const struct got_error *err;
3492 struct got_repository *repo;
3493 static char msg[512];
3494 int *pack_fds = NULL;
3496 err = got_repo_pack_fds_open(&pack_fds);
3497 if (err)
3498 return err;
3500 err = got_repo_open(&repo, path, NULL, pack_fds);
3501 if (err)
3502 return orig_err;
3504 snprintf(msg, sizeof(msg),
3505 "'got %s' needs a work tree in addition to a git repository\n"
3506 "Work trees can be checked out from this Git repository with "
3507 "'got checkout'.\n"
3508 "The got(1) manual page contains more information.", cmdname);
3509 err = got_error_msg(GOT_ERR_NOT_WORKTREE, msg);
3510 if (repo) {
3511 const struct got_error *close_err = got_repo_close(repo);
3512 if (err == NULL)
3513 err = close_err;
3515 if (pack_fds) {
3516 const struct got_error *pack_err =
3517 got_repo_pack_fds_close(pack_fds);
3518 if (err == NULL)
3519 err = pack_err;
3521 return err;
3524 static const struct got_error *
3525 cmd_update(int argc, char *argv[])
3527 const struct got_error *close_err, *error = NULL;
3528 struct got_repository *repo = NULL;
3529 struct got_worktree *worktree = NULL;
3530 char *worktree_path = NULL;
3531 struct got_object_id *commit_id = NULL;
3532 char *commit_id_str = NULL;
3533 const char *branch_name = NULL;
3534 struct got_reference *head_ref = NULL;
3535 struct got_pathlist_head paths;
3536 struct got_pathlist_entry *pe;
3537 int ch, verbosity = 0;
3538 struct got_update_progress_arg upa;
3539 int *pack_fds = NULL;
3541 TAILQ_INIT(&paths);
3543 #ifndef PROFILE
3544 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
3545 "unveil", NULL) == -1)
3546 err(1, "pledge");
3547 #endif
3549 while ((ch = getopt(argc, argv, "b:c:q")) != -1) {
3550 switch (ch) {
3551 case 'b':
3552 branch_name = optarg;
3553 break;
3554 case 'c':
3555 commit_id_str = strdup(optarg);
3556 if (commit_id_str == NULL)
3557 return got_error_from_errno("strdup");
3558 break;
3559 case 'q':
3560 verbosity = -1;
3561 break;
3562 default:
3563 usage_update();
3564 /* NOTREACHED */
3568 argc -= optind;
3569 argv += optind;
3571 worktree_path = getcwd(NULL, 0);
3572 if (worktree_path == NULL) {
3573 error = got_error_from_errno("getcwd");
3574 goto done;
3577 error = got_repo_pack_fds_open(&pack_fds);
3578 if (error != NULL)
3579 goto done;
3581 error = got_worktree_open(&worktree, worktree_path,
3582 GOT_WORKTREE_GOT_DIR);
3583 if (error) {
3584 if (error->code == GOT_ERR_NOT_WORKTREE)
3585 error = wrap_not_worktree_error(error, "update",
3586 worktree_path);
3587 goto done;
3590 error = check_rebase_or_histedit_in_progress(worktree);
3591 if (error)
3592 goto done;
3594 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
3595 NULL, pack_fds);
3596 if (error != NULL)
3597 goto done;
3599 error = apply_unveil(got_repo_get_path(repo), 0,
3600 got_worktree_get_root_path(worktree));
3601 if (error)
3602 goto done;
3604 error = check_merge_in_progress(worktree, repo);
3605 if (error)
3606 goto done;
3608 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
3609 if (error)
3610 goto done;
3612 error = got_ref_open(&head_ref, repo, branch_name ? branch_name :
3613 got_worktree_get_head_ref_name(worktree), 0);
3614 if (error != NULL)
3615 goto done;
3616 if (commit_id_str == NULL) {
3617 error = got_ref_resolve(&commit_id, repo, head_ref);
3618 if (error != NULL)
3619 goto done;
3620 error = got_object_id_str(&commit_id_str, commit_id);
3621 if (error != NULL)
3622 goto done;
3623 } else {
3624 struct got_reflist_head refs;
3625 char *keyword_idstr = NULL;
3627 TAILQ_INIT(&refs);
3629 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
3630 NULL);
3631 if (error)
3632 goto done;
3634 error = got_keyword_to_idstr(&keyword_idstr, commit_id_str,
3635 repo, worktree);
3636 if (error != NULL)
3637 goto done;
3638 if (keyword_idstr != NULL) {
3639 free(commit_id_str);
3640 commit_id_str = keyword_idstr;
3643 error = got_repo_match_object_id(&commit_id, NULL,
3644 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
3645 got_ref_list_free(&refs);
3646 free(commit_id_str);
3647 commit_id_str = NULL;
3648 if (error)
3649 goto done;
3650 error = got_object_id_str(&commit_id_str, commit_id);
3651 if (error)
3652 goto done;
3655 if (branch_name) {
3656 struct got_object_id *head_commit_id;
3657 TAILQ_FOREACH(pe, &paths, entry) {
3658 if (pe->path_len == 0)
3659 continue;
3660 error = got_error_msg(GOT_ERR_BAD_PATH,
3661 "switching between branches requires that "
3662 "the entire work tree gets updated");
3663 goto done;
3665 error = got_ref_resolve(&head_commit_id, repo, head_ref);
3666 if (error)
3667 goto done;
3668 error = check_linear_ancestry(commit_id, head_commit_id, 0,
3669 repo);
3670 free(head_commit_id);
3671 if (error != NULL)
3672 goto done;
3673 error = check_same_branch(commit_id, head_ref, repo);
3674 if (error)
3675 goto done;
3676 error = switch_head_ref(head_ref, commit_id, worktree, repo);
3677 if (error)
3678 goto done;
3679 } else {
3680 error = check_linear_ancestry(commit_id,
3681 got_worktree_get_base_commit_id(worktree), 0, repo);
3682 if (error != NULL) {
3683 if (error->code == GOT_ERR_ANCESTRY)
3684 error = got_error(GOT_ERR_BRANCH_MOVED);
3685 goto done;
3687 error = check_same_branch(commit_id, head_ref, repo);
3688 if (error)
3689 goto done;
3692 if (got_object_id_cmp(got_worktree_get_base_commit_id(worktree),
3693 commit_id) != 0) {
3694 error = got_worktree_set_base_commit_id(worktree, repo,
3695 commit_id);
3696 if (error)
3697 goto done;
3700 memset(&upa, 0, sizeof(upa));
3701 upa.verbosity = verbosity;
3702 error = got_worktree_checkout_files(worktree, &paths, repo,
3703 update_progress, &upa, check_cancelled, NULL);
3704 if (error != NULL)
3705 goto done;
3707 if (upa.did_something) {
3708 printf("Updated to %s: %s\n",
3709 got_worktree_get_head_ref_name(worktree), commit_id_str);
3710 } else
3711 printf("Already up-to-date\n");
3713 print_update_progress_stats(&upa);
3714 done:
3715 if (pack_fds) {
3716 const struct got_error *pack_err =
3717 got_repo_pack_fds_close(pack_fds);
3718 if (error == NULL)
3719 error = pack_err;
3721 if (repo) {
3722 close_err = got_repo_close(repo);
3723 if (error == NULL)
3724 error = close_err;
3726 if (worktree != NULL) {
3727 close_err = got_worktree_close(worktree);
3728 if (error == NULL)
3729 error = close_err;
3731 if (head_ref != NULL)
3732 got_ref_close(head_ref);
3733 free(worktree_path);
3734 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
3735 free(commit_id);
3736 free(commit_id_str);
3737 return error;
3740 static const struct got_error *
3741 diff_blobs(struct got_object_id *blob_id1, struct got_object_id *blob_id2,
3742 const char *path, int diff_context, int ignore_whitespace,
3743 int force_text_diff, struct got_diffstat_cb_arg *dsa,
3744 struct got_repository *repo, FILE *outfile)
3746 const struct got_error *err = NULL;
3747 struct got_blob_object *blob1 = NULL, *blob2 = NULL;
3748 FILE *f1 = NULL, *f2 = NULL;
3749 int fd1 = -1, fd2 = -1;
3751 fd1 = got_opentempfd();
3752 if (fd1 == -1)
3753 return got_error_from_errno("got_opentempfd");
3754 fd2 = got_opentempfd();
3755 if (fd2 == -1) {
3756 err = got_error_from_errno("got_opentempfd");
3757 goto done;
3760 if (blob_id1) {
3761 err = got_object_open_as_blob(&blob1, repo, blob_id1, 8192,
3762 fd1);
3763 if (err)
3764 goto done;
3767 err = got_object_open_as_blob(&blob2, repo, blob_id2, 8192, fd2);
3768 if (err)
3769 goto done;
3771 f1 = got_opentemp();
3772 if (f1 == NULL) {
3773 err = got_error_from_errno("got_opentemp");
3774 goto done;
3776 f2 = got_opentemp();
3777 if (f2 == NULL) {
3778 err = got_error_from_errno("got_opentemp");
3779 goto done;
3782 while (path[0] == '/')
3783 path++;
3784 err = got_diff_blob(NULL, NULL, blob1, blob2, f1, f2, path, path,
3785 GOT_DIFF_ALGORITHM_PATIENCE, diff_context, ignore_whitespace,
3786 force_text_diff, dsa, outfile);
3787 done:
3788 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
3789 err = got_error_from_errno("close");
3790 if (blob1)
3791 got_object_blob_close(blob1);
3792 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
3793 err = got_error_from_errno("close");
3794 if (blob2)
3795 got_object_blob_close(blob2);
3796 if (f1 && fclose(f1) == EOF && err == NULL)
3797 err = got_error_from_errno("fclose");
3798 if (f2 && fclose(f2) == EOF && err == NULL)
3799 err = got_error_from_errno("fclose");
3800 return err;
3803 static const struct got_error *
3804 diff_trees(struct got_object_id *tree_id1, struct got_object_id *tree_id2,
3805 const char *path, int diff_context, int ignore_whitespace,
3806 int force_text_diff, struct got_diffstat_cb_arg *dsa,
3807 struct got_repository *repo, FILE *outfile)
3809 const struct got_error *err = NULL;
3810 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
3811 struct got_diff_blob_output_unidiff_arg arg;
3812 FILE *f1 = NULL, *f2 = NULL;
3813 int fd1 = -1, fd2 = -1;
3815 if (tree_id1) {
3816 err = got_object_open_as_tree(&tree1, repo, tree_id1);
3817 if (err)
3818 goto done;
3819 fd1 = got_opentempfd();
3820 if (fd1 == -1) {
3821 err = got_error_from_errno("got_opentempfd");
3822 goto done;
3826 err = got_object_open_as_tree(&tree2, repo, tree_id2);
3827 if (err)
3828 goto done;
3830 f1 = got_opentemp();
3831 if (f1 == NULL) {
3832 err = got_error_from_errno("got_opentemp");
3833 goto done;
3836 f2 = got_opentemp();
3837 if (f2 == NULL) {
3838 err = got_error_from_errno("got_opentemp");
3839 goto done;
3841 fd2 = got_opentempfd();
3842 if (fd2 == -1) {
3843 err = got_error_from_errno("got_opentempfd");
3844 goto done;
3846 arg.diff_context = diff_context;
3847 arg.ignore_whitespace = ignore_whitespace;
3848 arg.force_text_diff = force_text_diff;
3849 arg.diffstat = dsa;
3850 arg.diff_algo = GOT_DIFF_ALGORITHM_PATIENCE;
3851 arg.outfile = outfile;
3852 arg.lines = NULL;
3853 arg.nlines = 0;
3854 while (path[0] == '/')
3855 path++;
3856 err = got_diff_tree(tree1, tree2, f1, f2, fd1, fd2, path, path, repo,
3857 got_diff_blob_output_unidiff, &arg, 1);
3858 done:
3859 if (tree1)
3860 got_object_tree_close(tree1);
3861 if (tree2)
3862 got_object_tree_close(tree2);
3863 if (f1 && fclose(f1) == EOF && err == NULL)
3864 err = got_error_from_errno("fclose");
3865 if (f2 && fclose(f2) == EOF && err == NULL)
3866 err = got_error_from_errno("fclose");
3867 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
3868 err = got_error_from_errno("close");
3869 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
3870 err = got_error_from_errno("close");
3871 return err;
3874 static const struct got_error *
3875 get_changed_paths(struct got_pathlist_head *paths,
3876 struct got_commit_object *commit, struct got_repository *repo,
3877 struct got_diffstat_cb_arg *dsa)
3879 const struct got_error *err = NULL;
3880 struct got_object_id *tree_id1 = NULL, *tree_id2 = NULL;
3881 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
3882 struct got_object_qid *qid;
3883 got_diff_blob_cb cb = got_diff_tree_collect_changed_paths;
3884 FILE *f1 = NULL, *f2 = NULL;
3885 int fd1 = -1, fd2 = -1;
3887 if (dsa) {
3888 cb = got_diff_tree_compute_diffstat;
3890 f1 = got_opentemp();
3891 if (f1 == NULL) {
3892 err = got_error_from_errno("got_opentemp");
3893 goto done;
3895 f2 = got_opentemp();
3896 if (f2 == NULL) {
3897 err = got_error_from_errno("got_opentemp");
3898 goto done;
3900 fd1 = got_opentempfd();
3901 if (fd1 == -1) {
3902 err = got_error_from_errno("got_opentempfd");
3903 goto done;
3905 fd2 = got_opentempfd();
3906 if (fd2 == -1) {
3907 err = got_error_from_errno("got_opentempfd");
3908 goto done;
3912 qid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
3913 if (qid != NULL) {
3914 struct got_commit_object *pcommit;
3915 err = got_object_open_as_commit(&pcommit, repo,
3916 &qid->id);
3917 if (err)
3918 return err;
3920 tree_id1 = got_object_id_dup(
3921 got_object_commit_get_tree_id(pcommit));
3922 if (tree_id1 == NULL) {
3923 got_object_commit_close(pcommit);
3924 return got_error_from_errno("got_object_id_dup");
3926 got_object_commit_close(pcommit);
3930 if (tree_id1) {
3931 err = got_object_open_as_tree(&tree1, repo, tree_id1);
3932 if (err)
3933 goto done;
3936 tree_id2 = got_object_commit_get_tree_id(commit);
3937 err = got_object_open_as_tree(&tree2, repo, tree_id2);
3938 if (err)
3939 goto done;
3941 err = got_diff_tree(tree1, tree2, f1, f2, fd1, fd2, "", "", repo,
3942 cb, dsa ? (void *)dsa : paths, dsa ? 1 : 0);
3943 done:
3944 if (tree1)
3945 got_object_tree_close(tree1);
3946 if (tree2)
3947 got_object_tree_close(tree2);
3948 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
3949 err = got_error_from_errno("close");
3950 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
3951 err = got_error_from_errno("close");
3952 if (f1 && fclose(f1) == EOF && err == NULL)
3953 err = got_error_from_errno("fclose");
3954 if (f2 && fclose(f2) == EOF && err == NULL)
3955 err = got_error_from_errno("fclose");
3956 free(tree_id1);
3957 return err;
3960 static const struct got_error *
3961 print_patch(struct got_commit_object *commit, struct got_object_id *id,
3962 const char *path, int diff_context, struct got_diffstat_cb_arg *dsa,
3963 struct got_repository *repo, FILE *outfile)
3965 const struct got_error *err = NULL;
3966 struct got_commit_object *pcommit = NULL;
3967 char *id_str1 = NULL, *id_str2 = NULL;
3968 struct got_object_id *obj_id1 = NULL, *obj_id2 = NULL;
3969 struct got_object_qid *qid;
3971 qid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
3972 if (qid != NULL) {
3973 err = got_object_open_as_commit(&pcommit, repo,
3974 &qid->id);
3975 if (err)
3976 return err;
3977 err = got_object_id_str(&id_str1, &qid->id);
3978 if (err)
3979 goto done;
3982 err = got_object_id_str(&id_str2, id);
3983 if (err)
3984 goto done;
3986 if (path && path[0] != '\0') {
3987 int obj_type;
3988 err = got_object_id_by_path(&obj_id2, repo, commit, path);
3989 if (err)
3990 goto done;
3991 if (pcommit) {
3992 err = got_object_id_by_path(&obj_id1, repo,
3993 pcommit, path);
3994 if (err) {
3995 if (err->code != GOT_ERR_NO_TREE_ENTRY) {
3996 free(obj_id2);
3997 goto done;
4001 err = got_object_get_type(&obj_type, repo, obj_id2);
4002 if (err) {
4003 free(obj_id2);
4004 goto done;
4006 fprintf(outfile,
4007 "diff %s %s\n", id_str1 ? id_str1 : "/dev/null", id_str2);
4008 fprintf(outfile, "commit - %s\n",
4009 id_str1 ? id_str1 : "/dev/null");
4010 fprintf(outfile, "commit + %s\n", id_str2);
4011 switch (obj_type) {
4012 case GOT_OBJ_TYPE_BLOB:
4013 err = diff_blobs(obj_id1, obj_id2, path, diff_context,
4014 0, 0, dsa, repo, outfile);
4015 break;
4016 case GOT_OBJ_TYPE_TREE:
4017 err = diff_trees(obj_id1, obj_id2, path, diff_context,
4018 0, 0, dsa, repo, outfile);
4019 break;
4020 default:
4021 err = got_error(GOT_ERR_OBJ_TYPE);
4022 break;
4024 free(obj_id1);
4025 free(obj_id2);
4026 } else {
4027 obj_id2 = got_object_commit_get_tree_id(commit);
4028 if (pcommit)
4029 obj_id1 = got_object_commit_get_tree_id(pcommit);
4030 fprintf(outfile,
4031 "diff %s %s\n", id_str1 ? id_str1 : "/dev/null", id_str2);
4032 fprintf(outfile, "commit - %s\n",
4033 id_str1 ? id_str1 : "/dev/null");
4034 fprintf(outfile, "commit + %s\n", id_str2);
4035 err = diff_trees(obj_id1, obj_id2, "", diff_context, 0, 0,
4036 dsa, repo, outfile);
4038 done:
4039 free(id_str1);
4040 free(id_str2);
4041 if (pcommit)
4042 got_object_commit_close(pcommit);
4043 return err;
4046 static char *
4047 get_datestr(time_t *time, char *datebuf)
4049 struct tm mytm, *tm;
4050 char *p, *s;
4052 tm = gmtime_r(time, &mytm);
4053 if (tm == NULL)
4054 return NULL;
4055 s = asctime_r(tm, datebuf);
4056 if (s == NULL)
4057 return NULL;
4058 p = strchr(s, '\n');
4059 if (p)
4060 *p = '\0';
4061 return s;
4064 static const struct got_error *
4065 match_commit(int *have_match, struct got_object_id *id,
4066 struct got_commit_object *commit, regex_t *regex)
4068 const struct got_error *err = NULL;
4069 regmatch_t regmatch;
4070 char *id_str = NULL, *logmsg = NULL;
4072 *have_match = 0;
4074 err = got_object_id_str(&id_str, id);
4075 if (err)
4076 return err;
4078 err = got_object_commit_get_logmsg(&logmsg, commit);
4079 if (err)
4080 goto done;
4082 if (regexec(regex, got_object_commit_get_author(commit), 1,
4083 &regmatch, 0) == 0 ||
4084 regexec(regex, got_object_commit_get_committer(commit), 1,
4085 &regmatch, 0) == 0 ||
4086 regexec(regex, id_str, 1, &regmatch, 0) == 0 ||
4087 regexec(regex, logmsg, 1, &regmatch, 0) == 0)
4088 *have_match = 1;
4089 done:
4090 free(id_str);
4091 free(logmsg);
4092 return err;
4095 static void
4096 match_changed_paths(int *have_match, struct got_pathlist_head *changed_paths,
4097 regex_t *regex)
4099 regmatch_t regmatch;
4100 struct got_pathlist_entry *pe;
4102 *have_match = 0;
4104 TAILQ_FOREACH(pe, changed_paths, entry) {
4105 if (regexec(regex, pe->path, 1, &regmatch, 0) == 0) {
4106 *have_match = 1;
4107 break;
4112 static const struct got_error *
4113 match_patch(int *have_match, struct got_commit_object *commit,
4114 struct got_object_id *id, const char *path, int diff_context,
4115 struct got_repository *repo, regex_t *regex, FILE *f)
4117 const struct got_error *err = NULL;
4118 char *line = NULL;
4119 size_t linesize = 0;
4120 regmatch_t regmatch;
4122 *have_match = 0;
4124 err = got_opentemp_truncate(f);
4125 if (err)
4126 return err;
4128 err = print_patch(commit, id, path, diff_context, NULL, repo, f);
4129 if (err)
4130 goto done;
4132 if (fseeko(f, 0L, SEEK_SET) == -1) {
4133 err = got_error_from_errno("fseeko");
4134 goto done;
4137 while (getline(&line, &linesize, f) != -1) {
4138 if (regexec(regex, line, 1, &regmatch, 0) == 0) {
4139 *have_match = 1;
4140 break;
4143 done:
4144 free(line);
4145 return err;
4148 #define GOT_COMMIT_SEP_STR "-----------------------------------------------\n"
4150 static const struct got_error*
4151 build_refs_str(char **refs_str, struct got_reflist_head *refs,
4152 struct got_object_id *id, struct got_repository *repo,
4153 int local_only)
4155 static const struct got_error *err = NULL;
4156 struct got_reflist_entry *re;
4157 char *s;
4158 const char *name;
4160 *refs_str = NULL;
4162 TAILQ_FOREACH(re, refs, entry) {
4163 struct got_tag_object *tag = NULL;
4164 struct got_object_id *ref_id;
4165 int cmp;
4167 name = got_ref_get_name(re->ref);
4168 if (strcmp(name, GOT_REF_HEAD) == 0)
4169 continue;
4170 if (strncmp(name, "refs/", 5) == 0)
4171 name += 5;
4172 if (strncmp(name, "got/", 4) == 0)
4173 continue;
4174 if (strncmp(name, "heads/", 6) == 0)
4175 name += 6;
4176 if (strncmp(name, "remotes/", 8) == 0) {
4177 if (local_only)
4178 continue;
4179 name += 8;
4180 s = strstr(name, "/" GOT_REF_HEAD);
4181 if (s != NULL && strcmp(s, "/" GOT_REF_HEAD) == 0)
4182 continue;
4184 err = got_ref_resolve(&ref_id, repo, re->ref);
4185 if (err)
4186 break;
4187 if (strncmp(name, "tags/", 5) == 0) {
4188 err = got_object_open_as_tag(&tag, repo, ref_id);
4189 if (err) {
4190 if (err->code != GOT_ERR_OBJ_TYPE) {
4191 free(ref_id);
4192 break;
4194 /* Ref points at something other than a tag. */
4195 err = NULL;
4196 tag = NULL;
4199 cmp = got_object_id_cmp(tag ?
4200 got_object_tag_get_object_id(tag) : ref_id, id);
4201 free(ref_id);
4202 if (tag)
4203 got_object_tag_close(tag);
4204 if (cmp != 0)
4205 continue;
4206 s = *refs_str;
4207 if (asprintf(refs_str, "%s%s%s", s ? s : "",
4208 s ? ", " : "", name) == -1) {
4209 err = got_error_from_errno("asprintf");
4210 free(s);
4211 *refs_str = NULL;
4212 break;
4214 free(s);
4217 return err;
4220 static const struct got_error *
4221 print_commit_oneline(struct got_commit_object *commit, struct got_object_id *id,
4222 struct got_repository *repo, struct got_reflist_object_id_map *refs_idmap)
4224 const struct got_error *err = NULL;
4225 char *ref_str = NULL, *id_str = NULL, *logmsg0 = NULL;
4226 char *comma, *s, *nl;
4227 struct got_reflist_head *refs;
4228 char datebuf[12]; /* YYYY-MM-DD + SPACE + NUL */
4229 struct tm tm;
4230 time_t committer_time;
4232 refs = got_reflist_object_id_map_lookup(refs_idmap, id);
4233 if (refs) {
4234 err = build_refs_str(&ref_str, refs, id, repo, 1);
4235 if (err)
4236 return err;
4238 /* Display the first matching ref only. */
4239 if (ref_str && (comma = strchr(ref_str, ',')) != NULL)
4240 *comma = '\0';
4243 if (ref_str == NULL) {
4244 err = got_object_id_str(&id_str, id);
4245 if (err)
4246 return err;
4249 committer_time = got_object_commit_get_committer_time(commit);
4250 if (gmtime_r(&committer_time, &tm) == NULL) {
4251 err = got_error_from_errno("gmtime_r");
4252 goto done;
4254 if (strftime(datebuf, sizeof(datebuf), "%G-%m-%d ", &tm) == 0) {
4255 err = got_error(GOT_ERR_NO_SPACE);
4256 goto done;
4259 err = got_object_commit_get_logmsg(&logmsg0, commit);
4260 if (err)
4261 goto done;
4263 s = logmsg0;
4264 while (isspace((unsigned char)s[0]))
4265 s++;
4267 nl = strchr(s, '\n');
4268 if (nl) {
4269 *nl = '\0';
4272 if (ref_str)
4273 printf("%s%-7s %s\n", datebuf, ref_str, s);
4274 else
4275 printf("%s%.7s %s\n", datebuf, id_str, s);
4277 if (fflush(stdout) != 0 && err == NULL)
4278 err = got_error_from_errno("fflush");
4279 done:
4280 free(id_str);
4281 free(ref_str);
4282 free(logmsg0);
4283 return err;
4286 static const struct got_error *
4287 print_diffstat(struct got_diffstat_cb_arg *dsa, const char *header)
4289 struct got_pathlist_entry *pe;
4291 if (header != NULL)
4292 printf("%s\n", header);
4294 TAILQ_FOREACH(pe, dsa->paths, entry) {
4295 struct got_diff_changed_path *cp = pe->data;
4296 int pad = dsa->max_path_len - pe->path_len + 1;
4298 printf(" %c %s%*c | %*d+ %*d-\n", cp->status, pe->path, pad,
4299 ' ', dsa->add_cols + 1, cp->add, dsa->rm_cols + 1, cp->rm);
4301 printf("\n%d file%s changed, %d insertion%s(+), %d deletion%s(-)\n\n",
4302 dsa->nfiles, dsa->nfiles > 1 ? "s" : "", dsa->ins,
4303 dsa->ins != 1 ? "s" : "", dsa->del, dsa->del != 1 ? "s" : "");
4305 if (fflush(stdout) != 0)
4306 return got_error_from_errno("fflush");
4308 return NULL;
4311 static const struct got_error *
4312 printfile(FILE *f)
4314 char buf[8192];
4315 size_t r;
4317 if (fseeko(f, 0L, SEEK_SET) == -1)
4318 return got_error_from_errno("fseek");
4320 for (;;) {
4321 r = fread(buf, 1, sizeof(buf), f);
4322 if (r == 0) {
4323 if (ferror(f))
4324 return got_error_from_errno("fread");
4325 if (feof(f))
4326 break;
4328 if (fwrite(buf, 1, r, stdout) != r)
4329 return got_ferror(stdout, GOT_ERR_IO);
4332 return NULL;
4335 static const struct got_error *
4336 print_commit(struct got_commit_object *commit, struct got_object_id *id,
4337 struct got_repository *repo, const char *path,
4338 struct got_pathlist_head *changed_paths,
4339 struct got_diffstat_cb_arg *diffstat, int show_patch, int diff_context,
4340 struct got_reflist_object_id_map *refs_idmap, const char *custom_refs_str,
4341 const char *prefix)
4343 const struct got_error *err = NULL;
4344 FILE *f = NULL;
4345 char *id_str, *datestr, *logmsg0, *logmsg, *line;
4346 char datebuf[26];
4347 time_t committer_time;
4348 const char *author, *committer;
4349 char *refs_str = NULL;
4351 err = got_object_id_str(&id_str, id);
4352 if (err)
4353 return err;
4355 if (custom_refs_str == NULL) {
4356 struct got_reflist_head *refs;
4357 refs = got_reflist_object_id_map_lookup(refs_idmap, id);
4358 if (refs) {
4359 err = build_refs_str(&refs_str, refs, id, repo, 0);
4360 if (err)
4361 goto done;
4365 printf(GOT_COMMIT_SEP_STR);
4366 if (custom_refs_str)
4367 printf("%s %s (%s)\n", prefix ? prefix : "commit", id_str,
4368 custom_refs_str);
4369 else
4370 printf("%s %s%s%s%s\n", prefix ? prefix : "commit", id_str,
4371 refs_str ? " (" : "", refs_str ? refs_str : "",
4372 refs_str ? ")" : "");
4373 free(id_str);
4374 id_str = NULL;
4375 free(refs_str);
4376 refs_str = NULL;
4377 printf("from: %s\n", got_object_commit_get_author(commit));
4378 author = got_object_commit_get_author(commit);
4379 committer = got_object_commit_get_committer(commit);
4380 if (strcmp(author, committer) != 0)
4381 printf("via: %s\n", committer);
4382 committer_time = got_object_commit_get_committer_time(commit);
4383 datestr = get_datestr(&committer_time, datebuf);
4384 if (datestr)
4385 printf("date: %s UTC\n", datestr);
4386 if (got_object_commit_get_nparents(commit) > 1) {
4387 const struct got_object_id_queue *parent_ids;
4388 struct got_object_qid *qid;
4389 int n = 1;
4390 parent_ids = got_object_commit_get_parent_ids(commit);
4391 STAILQ_FOREACH(qid, parent_ids, entry) {
4392 err = got_object_id_str(&id_str, &qid->id);
4393 if (err)
4394 goto done;
4395 printf("parent %d: %s\n", n++, id_str);
4396 free(id_str);
4397 id_str = NULL;
4401 err = got_object_commit_get_logmsg(&logmsg0, commit);
4402 if (err)
4403 goto done;
4405 logmsg = logmsg0;
4406 do {
4407 line = strsep(&logmsg, "\n");
4408 if (line)
4409 printf(" %s\n", line);
4410 } while (line);
4411 free(logmsg0);
4413 if (changed_paths && diffstat == NULL) {
4414 struct got_pathlist_entry *pe;
4416 TAILQ_FOREACH(pe, changed_paths, entry) {
4417 struct got_diff_changed_path *cp = pe->data;
4419 printf(" %c %s\n", cp->status, pe->path);
4421 printf("\n");
4423 if (show_patch) {
4424 if (diffstat) {
4425 f = got_opentemp();
4426 if (f == NULL) {
4427 err = got_error_from_errno("got_opentemp");
4428 goto done;
4432 err = print_patch(commit, id, path, diff_context, diffstat,
4433 repo, diffstat == NULL ? stdout : f);
4434 if (err)
4435 goto done;
4437 if (diffstat) {
4438 err = print_diffstat(diffstat, NULL);
4439 if (err)
4440 goto done;
4441 if (show_patch) {
4442 err = printfile(f);
4443 if (err)
4444 goto done;
4447 if (show_patch)
4448 printf("\n");
4450 if (fflush(stdout) != 0 && err == NULL)
4451 err = got_error_from_errno("fflush");
4452 done:
4453 if (f && fclose(f) == EOF && err == NULL)
4454 err = got_error_from_errno("fclose");
4455 free(id_str);
4456 free(refs_str);
4457 return err;
4460 static const struct got_error *
4461 print_commits(struct got_object_id *root_id, struct got_object_id *end_id,
4462 struct got_repository *repo, const char *path, int show_changed_paths,
4463 int show_diffstat, int show_patch, const char *search_pattern,
4464 int diff_context, int limit, int log_branches, int reverse_display_order,
4465 struct got_reflist_object_id_map *refs_idmap, int one_line, int toposort,
4466 FILE *tmpfile)
4468 const struct got_error *err;
4469 struct got_commit_graph *graph;
4470 regex_t regex;
4471 int have_match;
4472 struct got_object_id_queue reversed_commits;
4473 struct got_object_qid *qid;
4474 struct got_commit_object *commit;
4475 struct got_pathlist_head changed_paths;
4477 STAILQ_INIT(&reversed_commits);
4478 TAILQ_INIT(&changed_paths);
4480 if (search_pattern && regcomp(&regex, search_pattern,
4481 REG_EXTENDED | REG_NOSUB | REG_NEWLINE))
4482 return got_error_msg(GOT_ERR_REGEX, search_pattern);
4484 err = got_commit_graph_open(&graph, path, !log_branches);
4485 if (err)
4486 return err;
4487 if (log_branches && toposort) {
4488 err = got_commit_graph_toposort(graph, root_id, repo,
4489 check_cancelled, NULL);
4490 } else {
4491 err = got_commit_graph_bfsort(graph, root_id, repo,
4492 check_cancelled, NULL);
4494 if (err)
4495 goto done;
4496 for (;;) {
4497 struct got_object_id id;
4498 struct got_diffstat_cb_arg dsa = { 0, 0, 0, 0, 0, 0,
4499 &changed_paths, 0, 0, GOT_DIFF_ALGORITHM_PATIENCE };
4501 if (sigint_received || sigpipe_received)
4502 break;
4504 err = got_commit_graph_iter_next(&id, graph, repo,
4505 check_cancelled, NULL);
4506 if (err) {
4507 if (err->code == GOT_ERR_ITER_COMPLETED)
4508 err = NULL;
4509 break;
4512 err = got_object_open_as_commit(&commit, repo, &id);
4513 if (err)
4514 break;
4516 if (((show_changed_paths && !show_diffstat) ||
4517 (show_diffstat && !show_patch))
4518 && !reverse_display_order) {
4519 err = get_changed_paths(&changed_paths, commit, repo,
4520 show_diffstat ? &dsa : NULL);
4521 if (err)
4522 break;
4525 if (search_pattern) {
4526 err = match_commit(&have_match, &id, commit, &regex);
4527 if (err) {
4528 got_object_commit_close(commit);
4529 break;
4531 if (have_match == 0 && show_changed_paths)
4532 match_changed_paths(&have_match,
4533 &changed_paths, &regex);
4534 if (have_match == 0 && show_patch) {
4535 err = match_patch(&have_match, commit, &id,
4536 path, diff_context, repo, &regex, tmpfile);
4537 if (err)
4538 break;
4540 if (have_match == 0) {
4541 got_object_commit_close(commit);
4542 got_pathlist_free(&changed_paths,
4543 GOT_PATHLIST_FREE_ALL);
4544 continue;
4548 if (reverse_display_order) {
4549 err = got_object_qid_alloc(&qid, &id);
4550 if (err)
4551 break;
4552 STAILQ_INSERT_HEAD(&reversed_commits, qid, entry);
4553 got_object_commit_close(commit);
4554 } else {
4555 if (one_line)
4556 err = print_commit_oneline(commit, &id,
4557 repo, refs_idmap);
4558 else
4559 err = print_commit(commit, &id, repo, path,
4560 (show_changed_paths || show_diffstat) ?
4561 &changed_paths : NULL,
4562 show_diffstat ? &dsa : NULL, show_patch,
4563 diff_context, refs_idmap, NULL, NULL);
4564 got_object_commit_close(commit);
4565 if (err)
4566 break;
4568 if ((limit && --limit == 0) ||
4569 (end_id && got_object_id_cmp(&id, end_id) == 0))
4570 break;
4572 got_pathlist_free(&changed_paths, GOT_PATHLIST_FREE_ALL);
4574 if (reverse_display_order) {
4575 STAILQ_FOREACH(qid, &reversed_commits, entry) {
4576 struct got_diffstat_cb_arg dsa = { 0, 0, 0, 0, 0, 0,
4577 &changed_paths, 0, 0, GOT_DIFF_ALGORITHM_PATIENCE };
4579 err = got_object_open_as_commit(&commit, repo,
4580 &qid->id);
4581 if (err)
4582 break;
4583 if ((show_changed_paths && !show_diffstat) ||
4584 (show_diffstat && !show_patch)) {
4585 err = get_changed_paths(&changed_paths, commit,
4586 repo, show_diffstat ? &dsa : NULL);
4587 if (err)
4588 break;
4590 if (one_line)
4591 err = print_commit_oneline(commit, &qid->id,
4592 repo, refs_idmap);
4593 else
4594 err = print_commit(commit, &qid->id, repo, path,
4595 (show_changed_paths || show_diffstat) ?
4596 &changed_paths : NULL,
4597 show_diffstat ? &dsa : NULL, show_patch,
4598 diff_context, refs_idmap, NULL, NULL);
4599 got_object_commit_close(commit);
4600 if (err)
4601 break;
4602 got_pathlist_free(&changed_paths, GOT_PATHLIST_FREE_ALL);
4605 done:
4606 while (!STAILQ_EMPTY(&reversed_commits)) {
4607 qid = STAILQ_FIRST(&reversed_commits);
4608 STAILQ_REMOVE_HEAD(&reversed_commits, entry);
4609 got_object_qid_free(qid);
4611 got_pathlist_free(&changed_paths, GOT_PATHLIST_FREE_ALL);
4612 if (search_pattern)
4613 regfree(&regex);
4614 got_commit_graph_close(graph);
4615 return err;
4618 __dead static void
4619 usage_log(void)
4621 fprintf(stderr, "usage: %s log [-bdPpRst] [-C number] [-c commit] "
4622 "[-l N] [-r repository-path] [-S search-pattern] [-x commit] "
4623 "[path]\n", getprogname());
4624 exit(1);
4627 static int
4628 get_default_log_limit(void)
4630 const char *got_default_log_limit;
4631 long long n;
4632 const char *errstr;
4634 got_default_log_limit = getenv("GOT_LOG_DEFAULT_LIMIT");
4635 if (got_default_log_limit == NULL)
4636 return 0;
4637 n = strtonum(got_default_log_limit, 0, INT_MAX, &errstr);
4638 if (errstr != NULL)
4639 return 0;
4640 return n;
4643 static const struct got_error *
4644 cmd_log(int argc, char *argv[])
4646 const struct got_error *error;
4647 struct got_repository *repo = NULL;
4648 struct got_worktree *worktree = NULL;
4649 struct got_object_id *start_id = NULL, *end_id = NULL;
4650 char *repo_path = NULL, *path = NULL, *cwd = NULL, *in_repo_path = NULL;
4651 char *keyword_idstr = NULL;
4652 const char *start_commit = NULL, *end_commit = NULL;
4653 const char *search_pattern = NULL;
4654 int diff_context = -1, ch;
4655 int show_changed_paths = 0, show_patch = 0, limit = 0, log_branches = 0;
4656 int show_diffstat = 0, reverse_display_order = 0, one_line = 0;
4657 int toposort = 0;
4658 const char *errstr;
4659 struct got_reflist_head refs;
4660 struct got_reflist_object_id_map *refs_idmap = NULL;
4661 FILE *tmpfile = NULL;
4662 int *pack_fds = NULL;
4664 TAILQ_INIT(&refs);
4666 #ifndef PROFILE
4667 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
4668 NULL)
4669 == -1)
4670 err(1, "pledge");
4671 #endif
4673 limit = get_default_log_limit();
4675 while ((ch = getopt(argc, argv, "bC:c:dl:PpRr:S:stx:")) != -1) {
4676 switch (ch) {
4677 case 'b':
4678 log_branches = 1;
4679 break;
4680 case 'C':
4681 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
4682 &errstr);
4683 if (errstr != NULL)
4684 errx(1, "number of context lines is %s: %s",
4685 errstr, optarg);
4686 break;
4687 case 'c':
4688 start_commit = optarg;
4689 break;
4690 case 'd':
4691 show_diffstat = 1;
4692 break;
4693 case 'l':
4694 limit = strtonum(optarg, 0, INT_MAX, &errstr);
4695 if (errstr != NULL)
4696 errx(1, "number of commits is %s: %s",
4697 errstr, optarg);
4698 break;
4699 case 'P':
4700 show_changed_paths = 1;
4701 break;
4702 case 'p':
4703 show_patch = 1;
4704 break;
4705 case 'R':
4706 reverse_display_order = 1;
4707 break;
4708 case 'r':
4709 repo_path = realpath(optarg, NULL);
4710 if (repo_path == NULL)
4711 return got_error_from_errno2("realpath",
4712 optarg);
4713 got_path_strip_trailing_slashes(repo_path);
4714 break;
4715 case 'S':
4716 search_pattern = optarg;
4717 break;
4718 case 's':
4719 one_line = 1;
4720 break;
4721 case 't':
4722 toposort = 1;
4723 break;
4724 case 'x':
4725 end_commit = optarg;
4726 break;
4727 default:
4728 usage_log();
4729 /* NOTREACHED */
4733 argc -= optind;
4734 argv += optind;
4736 if (diff_context == -1)
4737 diff_context = 3;
4738 else if (!show_patch)
4739 errx(1, "-C requires -p");
4741 if (one_line && (show_patch || show_changed_paths || show_diffstat))
4742 errx(1, "cannot use -s with -d, -p or -P");
4744 cwd = getcwd(NULL, 0);
4745 if (cwd == NULL) {
4746 error = got_error_from_errno("getcwd");
4747 goto done;
4750 error = got_repo_pack_fds_open(&pack_fds);
4751 if (error != NULL)
4752 goto done;
4754 if (repo_path == NULL) {
4755 error = got_worktree_open(&worktree, cwd,
4756 GOT_WORKTREE_GOT_DIR);
4757 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4758 goto done;
4759 error = NULL;
4762 if (argc == 1) {
4763 if (worktree) {
4764 error = got_worktree_resolve_path(&path, worktree,
4765 argv[0]);
4766 if (error)
4767 goto done;
4768 } else {
4769 path = strdup(argv[0]);
4770 if (path == NULL) {
4771 error = got_error_from_errno("strdup");
4772 goto done;
4775 } else if (argc != 0)
4776 usage_log();
4778 if (repo_path == NULL) {
4779 repo_path = worktree ?
4780 strdup(got_worktree_get_repo_path(worktree)) : strdup(cwd);
4782 if (repo_path == NULL) {
4783 error = got_error_from_errno("strdup");
4784 goto done;
4787 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
4788 if (error != NULL)
4789 goto done;
4791 error = apply_unveil(got_repo_get_path(repo), 1,
4792 worktree ? got_worktree_get_root_path(worktree) : NULL);
4793 if (error)
4794 goto done;
4796 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
4797 if (error)
4798 goto done;
4800 error = got_reflist_object_id_map_create(&refs_idmap, &refs, repo);
4801 if (error)
4802 goto done;
4804 if (start_commit == NULL) {
4805 struct got_reference *head_ref;
4806 struct got_commit_object *commit = NULL;
4807 error = got_ref_open(&head_ref, repo,
4808 worktree ? got_worktree_get_head_ref_name(worktree)
4809 : GOT_REF_HEAD, 0);
4810 if (error != NULL)
4811 goto done;
4812 error = got_ref_resolve(&start_id, repo, head_ref);
4813 got_ref_close(head_ref);
4814 if (error != NULL)
4815 goto done;
4816 error = got_object_open_as_commit(&commit, repo,
4817 start_id);
4818 if (error != NULL)
4819 goto done;
4820 got_object_commit_close(commit);
4821 } else {
4822 error = got_keyword_to_idstr(&keyword_idstr, start_commit,
4823 repo, worktree);
4824 if (error != NULL)
4825 goto done;
4826 if (keyword_idstr != NULL)
4827 start_commit = keyword_idstr;
4829 error = got_repo_match_object_id(&start_id, NULL,
4830 start_commit, GOT_OBJ_TYPE_COMMIT, &refs, repo);
4831 if (error != NULL)
4832 goto done;
4834 if (end_commit != NULL) {
4835 error = got_keyword_to_idstr(&keyword_idstr, end_commit,
4836 repo, worktree);
4837 if (error != NULL)
4838 goto done;
4839 if (keyword_idstr != NULL)
4840 end_commit = keyword_idstr;
4842 error = got_repo_match_object_id(&end_id, NULL,
4843 end_commit, GOT_OBJ_TYPE_COMMIT, &refs, repo);
4844 if (error != NULL)
4845 goto done;
4848 if (worktree) {
4850 * If a path was specified on the command line it was resolved
4851 * to a path in the work tree above. Prepend the work tree's
4852 * path prefix to obtain the corresponding in-repository path.
4854 if (path) {
4855 const char *prefix;
4856 prefix = got_worktree_get_path_prefix(worktree);
4857 if (asprintf(&in_repo_path, "%s%s%s", prefix,
4858 (path[0] != '\0') ? "/" : "", path) == -1) {
4859 error = got_error_from_errno("asprintf");
4860 goto done;
4863 } else
4864 error = got_repo_map_path(&in_repo_path, repo,
4865 path ? path : "");
4866 if (error != NULL)
4867 goto done;
4868 if (in_repo_path) {
4869 free(path);
4870 path = in_repo_path;
4873 if (worktree) {
4874 /* Release work tree lock. */
4875 got_worktree_close(worktree);
4876 worktree = NULL;
4879 if (search_pattern && show_patch) {
4880 tmpfile = got_opentemp();
4881 if (tmpfile == NULL) {
4882 error = got_error_from_errno("got_opentemp");
4883 goto done;
4887 error = print_commits(start_id, end_id, repo, path ? path : "",
4888 show_changed_paths, show_diffstat, show_patch, search_pattern,
4889 diff_context, limit, log_branches, reverse_display_order,
4890 refs_idmap, one_line, toposort, tmpfile);
4891 done:
4892 free(path);
4893 free(repo_path);
4894 free(cwd);
4895 free(start_id);
4896 free(end_id);
4897 free(keyword_idstr);
4898 if (worktree)
4899 got_worktree_close(worktree);
4900 if (repo) {
4901 const struct got_error *close_err = got_repo_close(repo);
4902 if (error == NULL)
4903 error = close_err;
4905 if (pack_fds) {
4906 const struct got_error *pack_err =
4907 got_repo_pack_fds_close(pack_fds);
4908 if (error == NULL)
4909 error = pack_err;
4911 if (refs_idmap)
4912 got_reflist_object_id_map_free(refs_idmap);
4913 if (tmpfile && fclose(tmpfile) == EOF && error == NULL)
4914 error = got_error_from_errno("fclose");
4915 got_ref_list_free(&refs);
4916 return error;
4919 __dead static void
4920 usage_diff(void)
4922 fprintf(stderr, "usage: %s diff [-adPsw] [-C number] [-c commit] "
4923 "[-r repository-path] [object1 object2 | path ...]\n",
4924 getprogname());
4925 exit(1);
4928 struct print_diff_arg {
4929 struct got_repository *repo;
4930 struct got_worktree *worktree;
4931 struct got_diffstat_cb_arg *diffstat;
4932 int diff_context;
4933 const char *id_str;
4934 int header_shown;
4935 int diff_staged;
4936 enum got_diff_algorithm diff_algo;
4937 int ignore_whitespace;
4938 int force_text_diff;
4939 FILE *f1;
4940 FILE *f2;
4941 FILE *outfile;
4945 * Create a file which contains the target path of a symlink so we can feed
4946 * it as content to the diff engine.
4948 static const struct got_error *
4949 get_symlink_target_file(int *fd, int dirfd, const char *de_name,
4950 const char *abspath)
4952 const struct got_error *err = NULL;
4953 char target_path[PATH_MAX];
4954 ssize_t target_len, outlen;
4956 *fd = -1;
4958 if (dirfd != -1) {
4959 target_len = readlinkat(dirfd, de_name, target_path, PATH_MAX);
4960 if (target_len == -1)
4961 return got_error_from_errno2("readlinkat", abspath);
4962 } else {
4963 target_len = readlink(abspath, target_path, PATH_MAX);
4964 if (target_len == -1)
4965 return got_error_from_errno2("readlink", abspath);
4968 *fd = got_opentempfd();
4969 if (*fd == -1)
4970 return got_error_from_errno("got_opentempfd");
4972 outlen = write(*fd, target_path, target_len);
4973 if (outlen == -1) {
4974 err = got_error_from_errno("got_opentempfd");
4975 goto done;
4978 if (lseek(*fd, 0, SEEK_SET) == -1) {
4979 err = got_error_from_errno2("lseek", abspath);
4980 goto done;
4982 done:
4983 if (err) {
4984 close(*fd);
4985 *fd = -1;
4987 return err;
4990 static const struct got_error *
4991 print_diff(void *arg, unsigned char status, unsigned char staged_status,
4992 const char *path, struct got_object_id *blob_id,
4993 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
4994 int dirfd, const char *de_name)
4996 struct print_diff_arg *a = arg;
4997 const struct got_error *err = NULL;
4998 struct got_blob_object *blob1 = NULL;
4999 int fd = -1, fd1 = -1, fd2 = -1;
5000 FILE *f2 = NULL;
5001 char *abspath = NULL, *label1 = NULL;
5002 struct stat sb;
5003 off_t size1 = 0;
5004 int f2_exists = 0;
5006 memset(&sb, 0, sizeof(sb));
5008 if (a->diff_staged) {
5009 if (staged_status != GOT_STATUS_MODIFY &&
5010 staged_status != GOT_STATUS_ADD &&
5011 staged_status != GOT_STATUS_DELETE)
5012 return NULL;
5013 } else {
5014 if (staged_status == GOT_STATUS_DELETE)
5015 return NULL;
5016 if (status == GOT_STATUS_NONEXISTENT)
5017 return got_error_set_errno(ENOENT, path);
5018 if (status != GOT_STATUS_MODIFY &&
5019 status != GOT_STATUS_ADD &&
5020 status != GOT_STATUS_DELETE &&
5021 status != GOT_STATUS_CONFLICT)
5022 return NULL;
5025 err = got_opentemp_truncate(a->f1);
5026 if (err)
5027 return got_error_from_errno("got_opentemp_truncate");
5028 err = got_opentemp_truncate(a->f2);
5029 if (err)
5030 return got_error_from_errno("got_opentemp_truncate");
5032 if (!a->header_shown) {
5033 if (fprintf(a->outfile, "diff %s%s\n",
5034 a->diff_staged ? "-s " : "",
5035 got_worktree_get_root_path(a->worktree)) < 0) {
5036 err = got_error_from_errno("fprintf");
5037 goto done;
5039 if (fprintf(a->outfile, "commit - %s\n", a->id_str) < 0) {
5040 err = got_error_from_errno("fprintf");
5041 goto done;
5043 if (fprintf(a->outfile, "path + %s%s\n",
5044 got_worktree_get_root_path(a->worktree),
5045 a->diff_staged ? " (staged changes)" : "") < 0) {
5046 err = got_error_from_errno("fprintf");
5047 goto done;
5049 a->header_shown = 1;
5052 if (a->diff_staged) {
5053 const char *label1 = NULL, *label2 = NULL;
5054 switch (staged_status) {
5055 case GOT_STATUS_MODIFY:
5056 label1 = path;
5057 label2 = path;
5058 break;
5059 case GOT_STATUS_ADD:
5060 label2 = path;
5061 break;
5062 case GOT_STATUS_DELETE:
5063 label1 = path;
5064 break;
5065 default:
5066 return got_error(GOT_ERR_FILE_STATUS);
5068 fd1 = got_opentempfd();
5069 if (fd1 == -1) {
5070 err = got_error_from_errno("got_opentempfd");
5071 goto done;
5073 fd2 = got_opentempfd();
5074 if (fd2 == -1) {
5075 err = got_error_from_errno("got_opentempfd");
5076 goto done;
5078 err = got_diff_objects_as_blobs(NULL, NULL, a->f1, a->f2,
5079 fd1, fd2, blob_id, staged_blob_id, label1, label2,
5080 a->diff_algo, a->diff_context, a->ignore_whitespace,
5081 a->force_text_diff, a->diffstat, a->repo, a->outfile);
5082 goto done;
5085 fd1 = got_opentempfd();
5086 if (fd1 == -1) {
5087 err = got_error_from_errno("got_opentempfd");
5088 goto done;
5091 if (staged_status == GOT_STATUS_ADD ||
5092 staged_status == GOT_STATUS_MODIFY) {
5093 char *id_str;
5094 err = got_object_open_as_blob(&blob1, a->repo, staged_blob_id,
5095 8192, fd1);
5096 if (err)
5097 goto done;
5098 err = got_object_id_str(&id_str, staged_blob_id);
5099 if (err)
5100 goto done;
5101 if (asprintf(&label1, "%s (staged)", id_str) == -1) {
5102 err = got_error_from_errno("asprintf");
5103 free(id_str);
5104 goto done;
5106 free(id_str);
5107 } else if (status != GOT_STATUS_ADD) {
5108 err = got_object_open_as_blob(&blob1, a->repo, blob_id, 8192,
5109 fd1);
5110 if (err)
5111 goto done;
5114 if (status != GOT_STATUS_DELETE) {
5115 if (asprintf(&abspath, "%s/%s",
5116 got_worktree_get_root_path(a->worktree), path) == -1) {
5117 err = got_error_from_errno("asprintf");
5118 goto done;
5121 if (dirfd != -1) {
5122 fd = openat(dirfd, de_name,
5123 O_RDONLY | O_NOFOLLOW | O_CLOEXEC);
5124 if (fd == -1) {
5125 if (!got_err_open_nofollow_on_symlink()) {
5126 err = got_error_from_errno2("openat",
5127 abspath);
5128 goto done;
5130 err = get_symlink_target_file(&fd, dirfd,
5131 de_name, abspath);
5132 if (err)
5133 goto done;
5135 } else {
5136 fd = open(abspath, O_RDONLY | O_NOFOLLOW | O_CLOEXEC);
5137 if (fd == -1) {
5138 if (!got_err_open_nofollow_on_symlink()) {
5139 err = got_error_from_errno2("open",
5140 abspath);
5141 goto done;
5143 err = get_symlink_target_file(&fd, dirfd,
5144 de_name, abspath);
5145 if (err)
5146 goto done;
5149 if (fstatat(fd, abspath, &sb, AT_SYMLINK_NOFOLLOW) == -1) {
5150 err = got_error_from_errno2("fstatat", abspath);
5151 goto done;
5153 f2 = fdopen(fd, "r");
5154 if (f2 == NULL) {
5155 err = got_error_from_errno2("fdopen", abspath);
5156 goto done;
5158 fd = -1;
5159 f2_exists = 1;
5162 if (blob1) {
5163 err = got_object_blob_dump_to_file(&size1, NULL, NULL,
5164 a->f1, blob1);
5165 if (err)
5166 goto done;
5169 err = got_diff_blob_file(blob1, a->f1, size1, label1, f2 ? f2 : a->f2,
5170 f2_exists, &sb, path, GOT_DIFF_ALGORITHM_PATIENCE, a->diff_context,
5171 a->ignore_whitespace, a->force_text_diff, a->diffstat, a->outfile);
5172 done:
5173 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
5174 err = got_error_from_errno("close");
5175 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
5176 err = got_error_from_errno("close");
5177 if (blob1)
5178 got_object_blob_close(blob1);
5179 if (fd != -1 && close(fd) == -1 && err == NULL)
5180 err = got_error_from_errno("close");
5181 if (f2 && fclose(f2) == EOF && err == NULL)
5182 err = got_error_from_errno("fclose");
5183 free(abspath);
5184 return err;
5187 static const struct got_error *
5188 cmd_diff(int argc, char *argv[])
5190 const struct got_error *error;
5191 struct got_repository *repo = NULL;
5192 struct got_worktree *worktree = NULL;
5193 char *cwd = NULL, *repo_path = NULL;
5194 const char *commit_args[2] = { NULL, NULL };
5195 int ncommit_args = 0;
5196 struct got_object_id *ids[2] = { NULL, NULL };
5197 char *labels[2] = { NULL, NULL };
5198 int type1 = GOT_OBJ_TYPE_ANY, type2 = GOT_OBJ_TYPE_ANY;
5199 int diff_context = 3, diff_staged = 0, ignore_whitespace = 0, ch, i;
5200 int force_text_diff = 0, force_path = 0, rflag = 0, show_diffstat = 0;
5201 const char *errstr;
5202 struct got_reflist_head refs;
5203 struct got_pathlist_head diffstat_paths, paths;
5204 FILE *f1 = NULL, *f2 = NULL, *outfile = NULL;
5205 int fd1 = -1, fd2 = -1;
5206 int *pack_fds = NULL;
5207 struct got_diffstat_cb_arg dsa;
5209 memset(&dsa, 0, sizeof(dsa));
5211 TAILQ_INIT(&refs);
5212 TAILQ_INIT(&paths);
5213 TAILQ_INIT(&diffstat_paths);
5215 #ifndef PROFILE
5216 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
5217 NULL) == -1)
5218 err(1, "pledge");
5219 #endif
5221 while ((ch = getopt(argc, argv, "aC:c:dPr:sw")) != -1) {
5222 switch (ch) {
5223 case 'a':
5224 force_text_diff = 1;
5225 break;
5226 case 'C':
5227 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
5228 &errstr);
5229 if (errstr != NULL)
5230 errx(1, "number of context lines is %s: %s",
5231 errstr, optarg);
5232 break;
5233 case 'c':
5234 if (ncommit_args >= 2)
5235 errx(1, "too many -c options used");
5236 commit_args[ncommit_args++] = optarg;
5237 break;
5238 case 'd':
5239 show_diffstat = 1;
5240 break;
5241 case 'P':
5242 force_path = 1;
5243 break;
5244 case 'r':
5245 repo_path = realpath(optarg, NULL);
5246 if (repo_path == NULL)
5247 return got_error_from_errno2("realpath",
5248 optarg);
5249 got_path_strip_trailing_slashes(repo_path);
5250 rflag = 1;
5251 break;
5252 case 's':
5253 diff_staged = 1;
5254 break;
5255 case 'w':
5256 ignore_whitespace = 1;
5257 break;
5258 default:
5259 usage_diff();
5260 /* NOTREACHED */
5264 argc -= optind;
5265 argv += optind;
5267 cwd = getcwd(NULL, 0);
5268 if (cwd == NULL) {
5269 error = got_error_from_errno("getcwd");
5270 goto done;
5273 error = got_repo_pack_fds_open(&pack_fds);
5274 if (error != NULL)
5275 goto done;
5277 if (repo_path == NULL) {
5278 error = got_worktree_open(&worktree, cwd,
5279 GOT_WORKTREE_GOT_DIR);
5280 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5281 goto done;
5282 else
5283 error = NULL;
5284 if (worktree) {
5285 repo_path =
5286 strdup(got_worktree_get_repo_path(worktree));
5287 if (repo_path == NULL) {
5288 error = got_error_from_errno("strdup");
5289 goto done;
5291 } else {
5292 repo_path = strdup(cwd);
5293 if (repo_path == NULL) {
5294 error = got_error_from_errno("strdup");
5295 goto done;
5300 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
5301 free(repo_path);
5302 if (error != NULL)
5303 goto done;
5305 if (show_diffstat) {
5306 dsa.paths = &diffstat_paths;
5307 dsa.force_text = force_text_diff;
5308 dsa.ignore_ws = ignore_whitespace;
5309 dsa.diff_algo = GOT_DIFF_ALGORITHM_PATIENCE;
5312 if (rflag || worktree == NULL || ncommit_args > 0) {
5313 if (force_path) {
5314 error = got_error_msg(GOT_ERR_NOT_IMPL,
5315 "-P option can only be used when diffing "
5316 "a work tree");
5317 goto done;
5319 if (diff_staged) {
5320 error = got_error_msg(GOT_ERR_NOT_IMPL,
5321 "-s option can only be used when diffing "
5322 "a work tree");
5323 goto done;
5327 error = apply_unveil(got_repo_get_path(repo), 1,
5328 worktree ? got_worktree_get_root_path(worktree) : NULL);
5329 if (error)
5330 goto done;
5332 if ((!force_path && argc == 2) || ncommit_args > 0) {
5333 int obj_type = (ncommit_args > 0 ?
5334 GOT_OBJ_TYPE_COMMIT : GOT_OBJ_TYPE_ANY);
5335 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
5336 NULL);
5337 if (error)
5338 goto done;
5339 for (i = 0; i < (ncommit_args > 0 ? ncommit_args : argc); i++) {
5340 const char *arg;
5341 char *keyword_idstr = NULL;
5343 if (ncommit_args > 0)
5344 arg = commit_args[i];
5345 else
5346 arg = argv[i];
5348 error = got_keyword_to_idstr(&keyword_idstr, arg,
5349 repo, worktree);
5350 if (error != NULL)
5351 goto done;
5352 if (keyword_idstr != NULL)
5353 arg = keyword_idstr;
5355 error = got_repo_match_object_id(&ids[i], &labels[i],
5356 arg, obj_type, &refs, repo);
5357 free(keyword_idstr);
5358 if (error) {
5359 if (error->code != GOT_ERR_NOT_REF &&
5360 error->code != GOT_ERR_NO_OBJ)
5361 goto done;
5362 if (ncommit_args > 0)
5363 goto done;
5364 error = NULL;
5365 break;
5370 f1 = got_opentemp();
5371 if (f1 == NULL) {
5372 error = got_error_from_errno("got_opentemp");
5373 goto done;
5376 f2 = got_opentemp();
5377 if (f2 == NULL) {
5378 error = got_error_from_errno("got_opentemp");
5379 goto done;
5382 outfile = got_opentemp();
5383 if (outfile == NULL) {
5384 error = got_error_from_errno("got_opentemp");
5385 goto done;
5388 if (ncommit_args == 0 && (ids[0] == NULL || ids[1] == NULL)) {
5389 struct print_diff_arg arg;
5390 char *id_str;
5392 if (worktree == NULL) {
5393 if (argc == 2 && ids[0] == NULL) {
5394 error = got_error_path(argv[0], GOT_ERR_NO_OBJ);
5395 goto done;
5396 } else if (argc == 2 && ids[1] == NULL) {
5397 error = got_error_path(argv[1], GOT_ERR_NO_OBJ);
5398 goto done;
5399 } else if (argc > 0) {
5400 error = got_error_fmt(GOT_ERR_NOT_WORKTREE,
5401 "%s", "specified paths cannot be resolved");
5402 goto done;
5403 } else {
5404 error = got_error(GOT_ERR_NOT_WORKTREE);
5405 goto done;
5409 error = get_worktree_paths_from_argv(&paths, argc, argv,
5410 worktree);
5411 if (error)
5412 goto done;
5414 error = got_object_id_str(&id_str,
5415 got_worktree_get_base_commit_id(worktree));
5416 if (error)
5417 goto done;
5418 arg.repo = repo;
5419 arg.worktree = worktree;
5420 arg.diff_algo = GOT_DIFF_ALGORITHM_PATIENCE;
5421 arg.diff_context = diff_context;
5422 arg.id_str = id_str;
5423 arg.header_shown = 0;
5424 arg.diff_staged = diff_staged;
5425 arg.ignore_whitespace = ignore_whitespace;
5426 arg.force_text_diff = force_text_diff;
5427 arg.diffstat = show_diffstat ? &dsa : NULL;
5428 arg.f1 = f1;
5429 arg.f2 = f2;
5430 arg.outfile = outfile;
5432 error = got_worktree_status(worktree, &paths, repo, 0,
5433 print_diff, &arg, check_cancelled, NULL);
5434 free(id_str);
5435 if (error)
5436 goto done;
5438 if (show_diffstat && dsa.nfiles > 0) {
5439 char *header;
5441 if (asprintf(&header, "diffstat %s%s",
5442 diff_staged ? "-s " : "",
5443 got_worktree_get_root_path(worktree)) == -1) {
5444 error = got_error_from_errno("asprintf");
5445 goto done;
5448 error = print_diffstat(&dsa, header);
5449 free(header);
5450 if (error)
5451 goto done;
5454 error = printfile(outfile);
5455 goto done;
5458 if (ncommit_args == 1) {
5459 struct got_commit_object *commit;
5460 error = got_object_open_as_commit(&commit, repo, ids[0]);
5461 if (error)
5462 goto done;
5464 labels[1] = labels[0];
5465 ids[1] = ids[0];
5466 if (got_object_commit_get_nparents(commit) > 0) {
5467 const struct got_object_id_queue *pids;
5468 struct got_object_qid *pid;
5469 pids = got_object_commit_get_parent_ids(commit);
5470 pid = STAILQ_FIRST(pids);
5471 ids[0] = got_object_id_dup(&pid->id);
5472 if (ids[0] == NULL) {
5473 error = got_error_from_errno(
5474 "got_object_id_dup");
5475 got_object_commit_close(commit);
5476 goto done;
5478 error = got_object_id_str(&labels[0], ids[0]);
5479 if (error) {
5480 got_object_commit_close(commit);
5481 goto done;
5483 } else {
5484 ids[0] = NULL;
5485 labels[0] = strdup("/dev/null");
5486 if (labels[0] == NULL) {
5487 error = got_error_from_errno("strdup");
5488 got_object_commit_close(commit);
5489 goto done;
5493 got_object_commit_close(commit);
5496 if (ncommit_args == 0 && argc > 2) {
5497 error = got_error_msg(GOT_ERR_BAD_PATH,
5498 "path arguments cannot be used when diffing two objects");
5499 goto done;
5502 if (ids[0]) {
5503 error = got_object_get_type(&type1, repo, ids[0]);
5504 if (error)
5505 goto done;
5508 error = got_object_get_type(&type2, repo, ids[1]);
5509 if (error)
5510 goto done;
5511 if (type1 != GOT_OBJ_TYPE_ANY && type1 != type2) {
5512 error = got_error(GOT_ERR_OBJ_TYPE);
5513 goto done;
5515 if (type1 == GOT_OBJ_TYPE_BLOB && argc > 2) {
5516 error = got_error_msg(GOT_ERR_OBJ_TYPE,
5517 "path arguments cannot be used when diffing blobs");
5518 goto done;
5521 for (i = 0; ncommit_args > 0 && i < argc; i++) {
5522 char *in_repo_path;
5523 struct got_pathlist_entry *new;
5524 if (worktree) {
5525 const char *prefix;
5526 char *p;
5527 error = got_worktree_resolve_path(&p, worktree,
5528 argv[i]);
5529 if (error)
5530 goto done;
5531 prefix = got_worktree_get_path_prefix(worktree);
5532 while (prefix[0] == '/')
5533 prefix++;
5534 if (asprintf(&in_repo_path, "%s%s%s", prefix,
5535 (p[0] != '\0' && prefix[0] != '\0') ? "/" : "",
5536 p) == -1) {
5537 error = got_error_from_errno("asprintf");
5538 free(p);
5539 goto done;
5541 free(p);
5542 } else {
5543 char *mapped_path, *s;
5544 error = got_repo_map_path(&mapped_path, repo, argv[i]);
5545 if (error)
5546 goto done;
5547 s = mapped_path;
5548 while (s[0] == '/')
5549 s++;
5550 in_repo_path = strdup(s);
5551 if (in_repo_path == NULL) {
5552 error = got_error_from_errno("asprintf");
5553 free(mapped_path);
5554 goto done;
5556 free(mapped_path);
5559 error = got_pathlist_insert(&new, &paths, in_repo_path, NULL);
5560 if (error || new == NULL /* duplicate */)
5561 free(in_repo_path);
5562 if (error)
5563 goto done;
5566 if (worktree) {
5567 /* Release work tree lock. */
5568 got_worktree_close(worktree);
5569 worktree = NULL;
5572 fd1 = got_opentempfd();
5573 if (fd1 == -1) {
5574 error = got_error_from_errno("got_opentempfd");
5575 goto done;
5578 fd2 = got_opentempfd();
5579 if (fd2 == -1) {
5580 error = got_error_from_errno("got_opentempfd");
5581 goto done;
5584 switch (type1 == GOT_OBJ_TYPE_ANY ? type2 : type1) {
5585 case GOT_OBJ_TYPE_BLOB:
5586 error = got_diff_objects_as_blobs(NULL, NULL, f1, f2,
5587 fd1, fd2, ids[0], ids[1], NULL, NULL,
5588 GOT_DIFF_ALGORITHM_PATIENCE, diff_context,
5589 ignore_whitespace, force_text_diff,
5590 show_diffstat ? &dsa : NULL, repo, outfile);
5591 break;
5592 case GOT_OBJ_TYPE_TREE:
5593 error = got_diff_objects_as_trees(NULL, NULL, f1, f2, fd1, fd2,
5594 ids[0], ids[1], &paths, "", "",
5595 GOT_DIFF_ALGORITHM_PATIENCE, diff_context,
5596 ignore_whitespace, force_text_diff,
5597 show_diffstat ? &dsa : NULL, repo, outfile);
5598 break;
5599 case GOT_OBJ_TYPE_COMMIT:
5600 fprintf(outfile, "diff %s %s\n", labels[0], labels[1]);
5601 error = got_diff_objects_as_commits(NULL, NULL, f1, f2,
5602 fd1, fd2, ids[0], ids[1], &paths,
5603 GOT_DIFF_ALGORITHM_PATIENCE, diff_context,
5604 ignore_whitespace, force_text_diff,
5605 show_diffstat ? &dsa : NULL, repo, outfile);
5606 break;
5607 default:
5608 error = got_error(GOT_ERR_OBJ_TYPE);
5610 if (error)
5611 goto done;
5613 if (show_diffstat && dsa.nfiles > 0) {
5614 char *header = NULL;
5616 if (asprintf(&header, "diffstat %s %s",
5617 labels[0], labels[1]) == -1) {
5618 error = got_error_from_errno("asprintf");
5619 goto done;
5622 error = print_diffstat(&dsa, header);
5623 free(header);
5624 if (error)
5625 goto done;
5628 error = printfile(outfile);
5630 done:
5631 free(labels[0]);
5632 free(labels[1]);
5633 free(ids[0]);
5634 free(ids[1]);
5635 if (worktree)
5636 got_worktree_close(worktree);
5637 if (repo) {
5638 const struct got_error *close_err = got_repo_close(repo);
5639 if (error == NULL)
5640 error = close_err;
5642 if (pack_fds) {
5643 const struct got_error *pack_err =
5644 got_repo_pack_fds_close(pack_fds);
5645 if (error == NULL)
5646 error = pack_err;
5648 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
5649 got_pathlist_free(&diffstat_paths, GOT_PATHLIST_FREE_ALL);
5650 got_ref_list_free(&refs);
5651 if (outfile && fclose(outfile) == EOF && error == NULL)
5652 error = got_error_from_errno("fclose");
5653 if (f1 && fclose(f1) == EOF && error == NULL)
5654 error = got_error_from_errno("fclose");
5655 if (f2 && fclose(f2) == EOF && error == NULL)
5656 error = got_error_from_errno("fclose");
5657 if (fd1 != -1 && close(fd1) == -1 && error == NULL)
5658 error = got_error_from_errno("close");
5659 if (fd2 != -1 && close(fd2) == -1 && error == NULL)
5660 error = got_error_from_errno("close");
5661 return error;
5664 __dead static void
5665 usage_blame(void)
5667 fprintf(stderr,
5668 "usage: %s blame [-c commit] [-r repository-path] path\n",
5669 getprogname());
5670 exit(1);
5673 struct blame_line {
5674 int annotated;
5675 char *id_str;
5676 char *committer;
5677 char datebuf[11]; /* YYYY-MM-DD + NUL */
5680 struct blame_cb_args {
5681 struct blame_line *lines;
5682 int nlines;
5683 int nlines_prec;
5684 int lineno_cur;
5685 off_t *line_offsets;
5686 FILE *f;
5687 struct got_repository *repo;
5690 static const struct got_error *
5691 blame_cb(void *arg, int nlines, int lineno,
5692 struct got_commit_object *commit, struct got_object_id *id)
5694 const struct got_error *err = NULL;
5695 struct blame_cb_args *a = arg;
5696 struct blame_line *bline;
5697 char *line = NULL;
5698 size_t linesize = 0;
5699 off_t offset;
5700 struct tm tm;
5701 time_t committer_time;
5703 if (nlines != a->nlines ||
5704 (lineno != -1 && lineno < 1) || lineno > a->nlines)
5705 return got_error(GOT_ERR_RANGE);
5707 if (sigint_received)
5708 return got_error(GOT_ERR_ITER_COMPLETED);
5710 if (lineno == -1)
5711 return NULL; /* no change in this commit */
5713 /* Annotate this line. */
5714 bline = &a->lines[lineno - 1];
5715 if (bline->annotated)
5716 return NULL;
5717 err = got_object_id_str(&bline->id_str, id);
5718 if (err)
5719 return err;
5721 bline->committer = strdup(got_object_commit_get_committer(commit));
5722 if (bline->committer == NULL) {
5723 err = got_error_from_errno("strdup");
5724 goto done;
5727 committer_time = got_object_commit_get_committer_time(commit);
5728 if (gmtime_r(&committer_time, &tm) == NULL)
5729 return got_error_from_errno("gmtime_r");
5730 if (strftime(bline->datebuf, sizeof(bline->datebuf), "%G-%m-%d",
5731 &tm) == 0) {
5732 err = got_error(GOT_ERR_NO_SPACE);
5733 goto done;
5735 bline->annotated = 1;
5737 /* Print lines annotated so far. */
5738 bline = &a->lines[a->lineno_cur - 1];
5739 if (!bline->annotated)
5740 goto done;
5742 offset = a->line_offsets[a->lineno_cur - 1];
5743 if (fseeko(a->f, offset, SEEK_SET) == -1) {
5744 err = got_error_from_errno("fseeko");
5745 goto done;
5748 while (a->lineno_cur <= a->nlines && bline->annotated) {
5749 char *smallerthan, *at, *nl, *committer;
5750 size_t len;
5752 if (getline(&line, &linesize, a->f) == -1) {
5753 if (ferror(a->f))
5754 err = got_error_from_errno("getline");
5755 break;
5758 committer = bline->committer;
5759 smallerthan = strchr(committer, '<');
5760 if (smallerthan && smallerthan[1] != '\0')
5761 committer = smallerthan + 1;
5762 at = strchr(committer, '@');
5763 if (at)
5764 *at = '\0';
5765 len = strlen(committer);
5766 if (len >= 9)
5767 committer[8] = '\0';
5769 nl = strchr(line, '\n');
5770 if (nl)
5771 *nl = '\0';
5772 printf("%.*d) %.8s %s %-8s %s\n", a->nlines_prec, a->lineno_cur,
5773 bline->id_str, bline->datebuf, committer, line);
5775 a->lineno_cur++;
5776 bline = &a->lines[a->lineno_cur - 1];
5778 done:
5779 free(line);
5780 return err;
5783 static const struct got_error *
5784 cmd_blame(int argc, char *argv[])
5786 const struct got_error *error;
5787 struct got_repository *repo = NULL;
5788 struct got_worktree *worktree = NULL;
5789 char *path, *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
5790 char *link_target = NULL;
5791 struct got_object_id *obj_id = NULL;
5792 struct got_object_id *commit_id = NULL;
5793 struct got_commit_object *commit = NULL;
5794 struct got_blob_object *blob = NULL;
5795 char *commit_id_str = NULL, *keyword_idstr = NULL;
5796 struct blame_cb_args bca;
5797 int ch, obj_type, i, fd1 = -1, fd2 = -1, fd3 = -1;
5798 off_t filesize;
5799 int *pack_fds = NULL;
5800 FILE *f1 = NULL, *f2 = NULL;
5802 fd1 = got_opentempfd();
5803 if (fd1 == -1)
5804 return got_error_from_errno("got_opentempfd");
5806 memset(&bca, 0, sizeof(bca));
5808 #ifndef PROFILE
5809 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
5810 NULL) == -1)
5811 err(1, "pledge");
5812 #endif
5814 while ((ch = getopt(argc, argv, "c:r:")) != -1) {
5815 switch (ch) {
5816 case 'c':
5817 commit_id_str = optarg;
5818 break;
5819 case 'r':
5820 repo_path = realpath(optarg, NULL);
5821 if (repo_path == NULL)
5822 return got_error_from_errno2("realpath",
5823 optarg);
5824 got_path_strip_trailing_slashes(repo_path);
5825 break;
5826 default:
5827 usage_blame();
5828 /* NOTREACHED */
5832 argc -= optind;
5833 argv += optind;
5835 if (argc == 1)
5836 path = argv[0];
5837 else
5838 usage_blame();
5840 cwd = getcwd(NULL, 0);
5841 if (cwd == NULL) {
5842 error = got_error_from_errno("getcwd");
5843 goto done;
5846 error = got_repo_pack_fds_open(&pack_fds);
5847 if (error != NULL)
5848 goto done;
5850 if (repo_path == NULL) {
5851 error = got_worktree_open(&worktree, cwd,
5852 GOT_WORKTREE_GOT_DIR);
5853 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5854 goto done;
5855 else
5856 error = NULL;
5857 if (worktree) {
5858 repo_path =
5859 strdup(got_worktree_get_repo_path(worktree));
5860 if (repo_path == NULL) {
5861 error = got_error_from_errno("strdup");
5862 if (error)
5863 goto done;
5865 } else {
5866 repo_path = strdup(cwd);
5867 if (repo_path == NULL) {
5868 error = got_error_from_errno("strdup");
5869 goto done;
5874 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
5875 if (error != NULL)
5876 goto done;
5878 if (worktree) {
5879 const char *prefix = got_worktree_get_path_prefix(worktree);
5880 char *p;
5882 error = got_worktree_resolve_path(&p, worktree, path);
5883 if (error)
5884 goto done;
5885 if (asprintf(&in_repo_path, "%s%s%s", prefix,
5886 (p[0] != '\0' && !got_path_is_root_dir(prefix)) ? "/" : "",
5887 p) == -1) {
5888 error = got_error_from_errno("asprintf");
5889 free(p);
5890 goto done;
5892 free(p);
5893 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5894 } else {
5895 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5896 if (error)
5897 goto done;
5898 error = got_repo_map_path(&in_repo_path, repo, path);
5900 if (error)
5901 goto done;
5903 if (commit_id_str == NULL) {
5904 struct got_reference *head_ref;
5905 error = got_ref_open(&head_ref, repo, worktree ?
5906 got_worktree_get_head_ref_name(worktree) : GOT_REF_HEAD, 0);
5907 if (error != NULL)
5908 goto done;
5909 error = got_ref_resolve(&commit_id, repo, head_ref);
5910 got_ref_close(head_ref);
5911 if (error != NULL)
5912 goto done;
5913 } else {
5914 struct got_reflist_head refs;
5916 TAILQ_INIT(&refs);
5917 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
5918 NULL);
5919 if (error)
5920 goto done;
5922 error = got_keyword_to_idstr(&keyword_idstr, commit_id_str,
5923 repo, worktree);
5924 if (error != NULL)
5925 goto done;
5926 if (keyword_idstr != NULL)
5927 commit_id_str = keyword_idstr;
5929 error = got_repo_match_object_id(&commit_id, NULL,
5930 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
5931 got_ref_list_free(&refs);
5932 if (error)
5933 goto done;
5936 if (worktree) {
5937 /* Release work tree lock. */
5938 got_worktree_close(worktree);
5939 worktree = NULL;
5942 error = got_object_open_as_commit(&commit, repo, commit_id);
5943 if (error)
5944 goto done;
5946 error = got_object_resolve_symlinks(&link_target, in_repo_path,
5947 commit, repo);
5948 if (error)
5949 goto done;
5951 error = got_object_id_by_path(&obj_id, repo, commit,
5952 link_target ? link_target : in_repo_path);
5953 if (error)
5954 goto done;
5956 error = got_object_get_type(&obj_type, repo, obj_id);
5957 if (error)
5958 goto done;
5960 if (obj_type != GOT_OBJ_TYPE_BLOB) {
5961 error = got_error_path(link_target ? link_target : in_repo_path,
5962 GOT_ERR_OBJ_TYPE);
5963 goto done;
5966 error = got_object_open_as_blob(&blob, repo, obj_id, 8192, fd1);
5967 if (error)
5968 goto done;
5969 bca.f = got_opentemp();
5970 if (bca.f == NULL) {
5971 error = got_error_from_errno("got_opentemp");
5972 goto done;
5974 error = got_object_blob_dump_to_file(&filesize, &bca.nlines,
5975 &bca.line_offsets, bca.f, blob);
5976 if (error || bca.nlines == 0)
5977 goto done;
5979 /* Don't include \n at EOF in the blame line count. */
5980 if (bca.line_offsets[bca.nlines - 1] == filesize)
5981 bca.nlines--;
5983 bca.lines = calloc(bca.nlines, sizeof(*bca.lines));
5984 if (bca.lines == NULL) {
5985 error = got_error_from_errno("calloc");
5986 goto done;
5988 bca.lineno_cur = 1;
5989 bca.nlines_prec = 0;
5990 i = bca.nlines;
5991 while (i > 0) {
5992 i /= 10;
5993 bca.nlines_prec++;
5995 bca.repo = repo;
5997 fd2 = got_opentempfd();
5998 if (fd2 == -1) {
5999 error = got_error_from_errno("got_opentempfd");
6000 goto done;
6002 fd3 = got_opentempfd();
6003 if (fd3 == -1) {
6004 error = got_error_from_errno("got_opentempfd");
6005 goto done;
6007 f1 = got_opentemp();
6008 if (f1 == NULL) {
6009 error = got_error_from_errno("got_opentemp");
6010 goto done;
6012 f2 = got_opentemp();
6013 if (f2 == NULL) {
6014 error = got_error_from_errno("got_opentemp");
6015 goto done;
6017 error = got_blame(link_target ? link_target : in_repo_path, commit_id,
6018 repo, GOT_DIFF_ALGORITHM_PATIENCE, blame_cb, &bca,
6019 check_cancelled, NULL, fd2, fd3, f1, f2);
6020 done:
6021 free(keyword_idstr);
6022 free(in_repo_path);
6023 free(link_target);
6024 free(repo_path);
6025 free(cwd);
6026 free(commit_id);
6027 free(obj_id);
6028 if (commit)
6029 got_object_commit_close(commit);
6031 if (fd1 != -1 && close(fd1) == -1 && error == NULL)
6032 error = got_error_from_errno("close");
6033 if (fd2 != -1 && close(fd2) == -1 && error == NULL)
6034 error = got_error_from_errno("close");
6035 if (fd3 != -1 && close(fd3) == -1 && error == NULL)
6036 error = got_error_from_errno("close");
6037 if (f1 && fclose(f1) == EOF && error == NULL)
6038 error = got_error_from_errno("fclose");
6039 if (f2 && fclose(f2) == EOF && error == NULL)
6040 error = got_error_from_errno("fclose");
6042 if (blob)
6043 got_object_blob_close(blob);
6044 if (worktree)
6045 got_worktree_close(worktree);
6046 if (repo) {
6047 const struct got_error *close_err = got_repo_close(repo);
6048 if (error == NULL)
6049 error = close_err;
6051 if (pack_fds) {
6052 const struct got_error *pack_err =
6053 got_repo_pack_fds_close(pack_fds);
6054 if (error == NULL)
6055 error = pack_err;
6057 if (bca.lines) {
6058 for (i = 0; i < bca.nlines; i++) {
6059 struct blame_line *bline = &bca.lines[i];
6060 free(bline->id_str);
6061 free(bline->committer);
6063 free(bca.lines);
6065 free(bca.line_offsets);
6066 if (bca.f && fclose(bca.f) == EOF && error == NULL)
6067 error = got_error_from_errno("fclose");
6068 return error;
6071 __dead static void
6072 usage_tree(void)
6074 fprintf(stderr, "usage: %s tree [-iR] [-c commit] [-r repository-path] "
6075 "[path]\n", getprogname());
6076 exit(1);
6079 static const struct got_error *
6080 print_entry(struct got_tree_entry *te, const char *id, const char *path,
6081 const char *root_path, struct got_repository *repo)
6083 const struct got_error *err = NULL;
6084 int is_root_path = (strcmp(path, root_path) == 0);
6085 const char *modestr = "";
6086 mode_t mode = got_tree_entry_get_mode(te);
6087 char *link_target = NULL;
6089 path += strlen(root_path);
6090 while (path[0] == '/')
6091 path++;
6093 if (got_object_tree_entry_is_submodule(te))
6094 modestr = "$";
6095 else if (S_ISLNK(mode)) {
6096 int i;
6098 err = got_tree_entry_get_symlink_target(&link_target, te, repo);
6099 if (err)
6100 return err;
6101 for (i = 0; link_target[i] != '\0'; i++) {
6102 if (!isprint((unsigned char)link_target[i]))
6103 link_target[i] = '?';
6106 modestr = "@";
6108 else if (S_ISDIR(mode))
6109 modestr = "/";
6110 else if (mode & S_IXUSR)
6111 modestr = "*";
6113 printf("%s%s%s%s%s%s%s\n", id ? id : "", path,
6114 is_root_path ? "" : "/", got_tree_entry_get_name(te), modestr,
6115 link_target ? " -> ": "", link_target ? link_target : "");
6117 free(link_target);
6118 return NULL;
6121 static const struct got_error *
6122 print_tree(const char *path, struct got_commit_object *commit,
6123 int show_ids, int recurse, const char *root_path,
6124 struct got_repository *repo)
6126 const struct got_error *err = NULL;
6127 struct got_object_id *tree_id = NULL;
6128 struct got_tree_object *tree = NULL;
6129 int nentries, i;
6131 err = got_object_id_by_path(&tree_id, repo, commit, path);
6132 if (err)
6133 goto done;
6135 err = got_object_open_as_tree(&tree, repo, tree_id);
6136 if (err)
6137 goto done;
6138 nentries = got_object_tree_get_nentries(tree);
6139 for (i = 0; i < nentries; i++) {
6140 struct got_tree_entry *te;
6141 char *id = NULL;
6143 if (sigint_received || sigpipe_received)
6144 break;
6146 te = got_object_tree_get_entry(tree, i);
6147 if (show_ids) {
6148 char *id_str;
6149 err = got_object_id_str(&id_str,
6150 got_tree_entry_get_id(te));
6151 if (err)
6152 goto done;
6153 if (asprintf(&id, "%s ", id_str) == -1) {
6154 err = got_error_from_errno("asprintf");
6155 free(id_str);
6156 goto done;
6158 free(id_str);
6160 err = print_entry(te, id, path, root_path, repo);
6161 free(id);
6162 if (err)
6163 goto done;
6165 if (recurse && S_ISDIR(got_tree_entry_get_mode(te))) {
6166 char *child_path;
6167 if (asprintf(&child_path, "%s%s%s", path,
6168 path[0] == '/' && path[1] == '\0' ? "" : "/",
6169 got_tree_entry_get_name(te)) == -1) {
6170 err = got_error_from_errno("asprintf");
6171 goto done;
6173 err = print_tree(child_path, commit, show_ids, 1,
6174 root_path, repo);
6175 free(child_path);
6176 if (err)
6177 goto done;
6180 done:
6181 if (tree)
6182 got_object_tree_close(tree);
6183 free(tree_id);
6184 return err;
6187 static const struct got_error *
6188 cmd_tree(int argc, char *argv[])
6190 const struct got_error *error;
6191 struct got_repository *repo = NULL;
6192 struct got_worktree *worktree = NULL;
6193 const char *path, *refname = NULL;
6194 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
6195 struct got_object_id *commit_id = NULL;
6196 struct got_commit_object *commit = NULL;
6197 char *commit_id_str = NULL, *keyword_idstr = NULL;
6198 int show_ids = 0, recurse = 0;
6199 int ch;
6200 int *pack_fds = NULL;
6202 #ifndef PROFILE
6203 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
6204 NULL) == -1)
6205 err(1, "pledge");
6206 #endif
6208 while ((ch = getopt(argc, argv, "c:iRr:")) != -1) {
6209 switch (ch) {
6210 case 'c':
6211 commit_id_str = optarg;
6212 break;
6213 case 'i':
6214 show_ids = 1;
6215 break;
6216 case 'R':
6217 recurse = 1;
6218 break;
6219 case 'r':
6220 repo_path = realpath(optarg, NULL);
6221 if (repo_path == NULL)
6222 return got_error_from_errno2("realpath",
6223 optarg);
6224 got_path_strip_trailing_slashes(repo_path);
6225 break;
6226 default:
6227 usage_tree();
6228 /* NOTREACHED */
6232 argc -= optind;
6233 argv += optind;
6235 if (argc == 1)
6236 path = argv[0];
6237 else if (argc > 1)
6238 usage_tree();
6239 else
6240 path = NULL;
6242 cwd = getcwd(NULL, 0);
6243 if (cwd == NULL) {
6244 error = got_error_from_errno("getcwd");
6245 goto done;
6248 error = got_repo_pack_fds_open(&pack_fds);
6249 if (error != NULL)
6250 goto done;
6252 if (repo_path == NULL) {
6253 error = got_worktree_open(&worktree, cwd,
6254 GOT_WORKTREE_GOT_DIR);
6255 if (error && error->code != GOT_ERR_NOT_WORKTREE)
6256 goto done;
6257 else
6258 error = NULL;
6259 if (worktree) {
6260 repo_path =
6261 strdup(got_worktree_get_repo_path(worktree));
6262 if (repo_path == NULL)
6263 error = got_error_from_errno("strdup");
6264 if (error)
6265 goto done;
6266 } else {
6267 repo_path = strdup(cwd);
6268 if (repo_path == NULL) {
6269 error = got_error_from_errno("strdup");
6270 goto done;
6275 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
6276 if (error != NULL)
6277 goto done;
6279 if (worktree) {
6280 const char *prefix = got_worktree_get_path_prefix(worktree);
6281 char *p;
6283 if (path == NULL || got_path_is_root_dir(path))
6284 path = "";
6285 error = got_worktree_resolve_path(&p, worktree, path);
6286 if (error)
6287 goto done;
6288 if (asprintf(&in_repo_path, "%s%s%s", prefix,
6289 (p[0] != '\0' && !got_path_is_root_dir(prefix)) ? "/" : "",
6290 p) == -1) {
6291 error = got_error_from_errno("asprintf");
6292 free(p);
6293 goto done;
6295 free(p);
6296 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
6297 if (error)
6298 goto done;
6299 } else {
6300 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
6301 if (error)
6302 goto done;
6303 if (path == NULL)
6304 path = "/";
6305 error = got_repo_map_path(&in_repo_path, repo, path);
6306 if (error != NULL)
6307 goto done;
6310 if (commit_id_str == NULL) {
6311 struct got_reference *head_ref;
6312 if (worktree)
6313 refname = got_worktree_get_head_ref_name(worktree);
6314 else
6315 refname = GOT_REF_HEAD;
6316 error = got_ref_open(&head_ref, repo, refname, 0);
6317 if (error != NULL)
6318 goto done;
6319 error = got_ref_resolve(&commit_id, repo, head_ref);
6320 got_ref_close(head_ref);
6321 if (error != NULL)
6322 goto done;
6323 } else {
6324 struct got_reflist_head refs;
6326 TAILQ_INIT(&refs);
6327 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
6328 NULL);
6329 if (error)
6330 goto done;
6332 error = got_keyword_to_idstr(&keyword_idstr, commit_id_str,
6333 repo, worktree);
6334 if (error != NULL)
6335 goto done;
6336 if (keyword_idstr != NULL)
6337 commit_id_str = keyword_idstr;
6339 error = got_repo_match_object_id(&commit_id, NULL,
6340 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
6341 got_ref_list_free(&refs);
6342 if (error)
6343 goto done;
6346 if (worktree) {
6347 /* Release work tree lock. */
6348 got_worktree_close(worktree);
6349 worktree = NULL;
6352 error = got_object_open_as_commit(&commit, repo, commit_id);
6353 if (error)
6354 goto done;
6356 error = print_tree(in_repo_path, commit, show_ids, recurse,
6357 in_repo_path, repo);
6358 done:
6359 free(keyword_idstr);
6360 free(in_repo_path);
6361 free(repo_path);
6362 free(cwd);
6363 free(commit_id);
6364 if (commit)
6365 got_object_commit_close(commit);
6366 if (worktree)
6367 got_worktree_close(worktree);
6368 if (repo) {
6369 const struct got_error *close_err = got_repo_close(repo);
6370 if (error == NULL)
6371 error = close_err;
6373 if (pack_fds) {
6374 const struct got_error *pack_err =
6375 got_repo_pack_fds_close(pack_fds);
6376 if (error == NULL)
6377 error = pack_err;
6379 return error;
6382 __dead static void
6383 usage_status(void)
6385 fprintf(stderr, "usage: %s status [-I] [-S status-codes] "
6386 "[-s status-codes] [path ...]\n", getprogname());
6387 exit(1);
6390 struct got_status_arg {
6391 char *status_codes;
6392 int suppress;
6395 static const struct got_error *
6396 print_status(void *arg, unsigned char status, unsigned char staged_status,
6397 const char *path, struct got_object_id *blob_id,
6398 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
6399 int dirfd, const char *de_name)
6401 struct got_status_arg *st = arg;
6403 if (status == staged_status && (status == GOT_STATUS_DELETE))
6404 status = GOT_STATUS_NO_CHANGE;
6405 if (st != NULL && st->status_codes) {
6406 size_t ncodes = strlen(st->status_codes);
6407 int i, j = 0;
6409 for (i = 0; i < ncodes ; i++) {
6410 if (st->suppress) {
6411 if (status == st->status_codes[i] ||
6412 staged_status == st->status_codes[i]) {
6413 j++;
6414 continue;
6416 } else {
6417 if (status == st->status_codes[i] ||
6418 staged_status == st->status_codes[i])
6419 break;
6423 if (st->suppress && j == 0)
6424 goto print;
6426 if (i == ncodes)
6427 return NULL;
6429 print:
6430 printf("%c%c %s\n", status, staged_status, path);
6431 return NULL;
6434 static const struct got_error *
6435 show_operation_in_progress(struct got_worktree *worktree,
6436 struct got_repository *repo)
6438 const struct got_error *err;
6439 char *new_base_branch_name = NULL;
6440 char *branch_name = NULL;
6441 int rebase_in_progress, histedit_in_progress, merge_in_progress;
6443 err = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
6444 if (err)
6445 return err;
6446 if (rebase_in_progress) {
6447 err = got_worktree_rebase_info(&new_base_branch_name,
6448 &branch_name, worktree, repo);
6449 if (err)
6450 return err;
6451 printf("Work tree is rebasing %s onto %s\n",
6452 branch_name, new_base_branch_name);
6455 err = got_worktree_histedit_in_progress(&histedit_in_progress,
6456 worktree);
6457 if (err)
6458 return err;
6459 if (histedit_in_progress) {
6460 err = got_worktree_histedit_info(&branch_name, worktree, repo);
6461 if (err)
6462 return err;
6463 printf("Work tree is editing the history of %s\n", branch_name);
6466 err = got_worktree_merge_in_progress(&merge_in_progress,
6467 worktree, repo);
6468 if (err)
6469 return err;
6470 if (merge_in_progress) {
6471 err = got_worktree_merge_info(&branch_name, worktree,
6472 repo);
6473 if (err)
6474 return err;
6475 printf("Work tree is merging %s into %s\n", branch_name,
6476 got_worktree_get_head_ref_name(worktree));
6479 free(new_base_branch_name);
6480 free(branch_name);
6481 return NULL;
6484 static const struct got_error *
6485 cmd_status(int argc, char *argv[])
6487 const struct got_error *close_err, *error = NULL;
6488 struct got_repository *repo = NULL;
6489 struct got_worktree *worktree = NULL;
6490 struct got_status_arg st;
6491 char *cwd = NULL;
6492 struct got_pathlist_head paths;
6493 int ch, i, no_ignores = 0;
6494 int *pack_fds = NULL;
6496 TAILQ_INIT(&paths);
6498 memset(&st, 0, sizeof(st));
6499 st.status_codes = NULL;
6500 st.suppress = 0;
6502 #ifndef PROFILE
6503 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
6504 NULL) == -1)
6505 err(1, "pledge");
6506 #endif
6508 while ((ch = getopt(argc, argv, "IS:s:")) != -1) {
6509 switch (ch) {
6510 case 'I':
6511 no_ignores = 1;
6512 break;
6513 case 'S':
6514 if (st.status_codes != NULL && st.suppress == 0)
6515 option_conflict('S', 's');
6516 st.suppress = 1;
6517 /* fallthrough */
6518 case 's':
6519 for (i = 0; optarg[i] != '\0'; i++) {
6520 switch (optarg[i]) {
6521 case GOT_STATUS_MODIFY:
6522 case GOT_STATUS_ADD:
6523 case GOT_STATUS_DELETE:
6524 case GOT_STATUS_CONFLICT:
6525 case GOT_STATUS_MISSING:
6526 case GOT_STATUS_OBSTRUCTED:
6527 case GOT_STATUS_UNVERSIONED:
6528 case GOT_STATUS_MODE_CHANGE:
6529 case GOT_STATUS_NONEXISTENT:
6530 break;
6531 default:
6532 errx(1, "invalid status code '%c'",
6533 optarg[i]);
6536 if (ch == 's' && st.suppress)
6537 option_conflict('s', 'S');
6538 st.status_codes = optarg;
6539 break;
6540 default:
6541 usage_status();
6542 /* NOTREACHED */
6546 argc -= optind;
6547 argv += optind;
6549 cwd = getcwd(NULL, 0);
6550 if (cwd == NULL) {
6551 error = got_error_from_errno("getcwd");
6552 goto done;
6555 error = got_repo_pack_fds_open(&pack_fds);
6556 if (error != NULL)
6557 goto done;
6559 error = got_worktree_open(&worktree, cwd,
6560 GOT_WORKTREE_GOT_DIR);
6561 if (error) {
6562 if (error->code == GOT_ERR_NOT_WORKTREE)
6563 error = wrap_not_worktree_error(error, "status", cwd);
6564 goto done;
6567 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
6568 NULL, pack_fds);
6569 if (error != NULL)
6570 goto done;
6572 error = apply_unveil(got_repo_get_path(repo), 1,
6573 got_worktree_get_root_path(worktree));
6574 if (error)
6575 goto done;
6577 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
6578 if (error)
6579 goto done;
6581 error = got_worktree_status(worktree, &paths, repo, no_ignores,
6582 print_status, &st, check_cancelled, NULL);
6583 if (error)
6584 goto done;
6586 error = show_operation_in_progress(worktree, repo);
6587 done:
6588 if (pack_fds) {
6589 const struct got_error *pack_err =
6590 got_repo_pack_fds_close(pack_fds);
6591 if (error == NULL)
6592 error = pack_err;
6594 if (repo) {
6595 close_err = got_repo_close(repo);
6596 if (error == NULL)
6597 error = close_err;
6599 if (worktree != NULL) {
6600 close_err = got_worktree_close(worktree);
6601 if (error == NULL)
6602 error = close_err;
6605 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
6606 free(cwd);
6607 return error;
6610 __dead static void
6611 usage_ref(void)
6613 fprintf(stderr, "usage: %s ref [-dlt] [-c object] [-r repository-path] "
6614 "[-s reference] [name]\n", getprogname());
6615 exit(1);
6618 static const struct got_error *
6619 list_refs(struct got_repository *repo, const char *refname, int sort_by_time)
6621 static const struct got_error *err = NULL;
6622 struct got_reflist_head refs;
6623 struct got_reflist_entry *re;
6625 TAILQ_INIT(&refs);
6626 err = got_ref_list(&refs, repo, refname, sort_by_time ?
6627 got_ref_cmp_by_commit_timestamp_descending : got_ref_cmp_by_name,
6628 repo);
6629 if (err)
6630 return err;
6632 TAILQ_FOREACH(re, &refs, entry) {
6633 char *refstr;
6634 refstr = got_ref_to_str(re->ref);
6635 if (refstr == NULL) {
6636 err = got_error_from_errno("got_ref_to_str");
6637 break;
6639 printf("%s: %s\n", got_ref_get_name(re->ref), refstr);
6640 free(refstr);
6643 got_ref_list_free(&refs);
6644 return err;
6647 static const struct got_error *
6648 delete_ref_by_name(struct got_repository *repo, const char *refname)
6650 const struct got_error *err;
6651 struct got_reference *ref;
6653 err = got_ref_open(&ref, repo, refname, 0);
6654 if (err)
6655 return err;
6657 err = delete_ref(repo, ref);
6658 got_ref_close(ref);
6659 return err;
6662 static const struct got_error *
6663 add_ref(struct got_repository *repo, const char *refname, const char *target)
6665 const struct got_error *err = NULL;
6666 struct got_object_id *id = NULL;
6667 struct got_reference *ref = NULL;
6668 struct got_reflist_head refs;
6671 * Don't let the user create a reference name with a leading '-'.
6672 * While technically a valid reference name, this case is usually
6673 * an unintended typo.
6675 if (refname[0] == '-')
6676 return got_error_path(refname, GOT_ERR_REF_NAME_MINUS);
6678 TAILQ_INIT(&refs);
6679 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
6680 if (err)
6681 goto done;
6682 err = got_repo_match_object_id(&id, NULL, target, GOT_OBJ_TYPE_ANY,
6683 &refs, repo);
6684 got_ref_list_free(&refs);
6685 if (err)
6686 goto done;
6688 err = got_ref_alloc(&ref, refname, id);
6689 if (err)
6690 goto done;
6692 err = got_ref_write(ref, repo);
6693 done:
6694 if (ref)
6695 got_ref_close(ref);
6696 free(id);
6697 return err;
6700 static const struct got_error *
6701 add_symref(struct got_repository *repo, const char *refname, const char *target)
6703 const struct got_error *err = NULL;
6704 struct got_reference *ref = NULL;
6705 struct got_reference *target_ref = NULL;
6708 * Don't let the user create a reference name with a leading '-'.
6709 * While technically a valid reference name, this case is usually
6710 * an unintended typo.
6712 if (refname[0] == '-')
6713 return got_error_path(refname, GOT_ERR_REF_NAME_MINUS);
6715 err = got_ref_open(&target_ref, repo, target, 0);
6716 if (err)
6717 return err;
6719 err = got_ref_alloc_symref(&ref, refname, target_ref);
6720 if (err)
6721 goto done;
6723 err = got_ref_write(ref, repo);
6724 done:
6725 if (target_ref)
6726 got_ref_close(target_ref);
6727 if (ref)
6728 got_ref_close(ref);
6729 return err;
6732 static const struct got_error *
6733 cmd_ref(int argc, char *argv[])
6735 const struct got_error *error = NULL;
6736 struct got_repository *repo = NULL;
6737 struct got_worktree *worktree = NULL;
6738 char *cwd = NULL, *repo_path = NULL;
6739 int ch, do_list = 0, do_delete = 0, sort_by_time = 0;
6740 const char *obj_arg = NULL, *symref_target= NULL;
6741 char *refname = NULL, *keyword_idstr = NULL;
6742 int *pack_fds = NULL;
6744 #ifndef PROFILE
6745 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
6746 "sendfd unveil", NULL) == -1)
6747 err(1, "pledge");
6748 #endif
6750 while ((ch = getopt(argc, argv, "c:dlr:s:t")) != -1) {
6751 switch (ch) {
6752 case 'c':
6753 obj_arg = optarg;
6754 break;
6755 case 'd':
6756 do_delete = 1;
6757 break;
6758 case 'l':
6759 do_list = 1;
6760 break;
6761 case 'r':
6762 repo_path = realpath(optarg, NULL);
6763 if (repo_path == NULL)
6764 return got_error_from_errno2("realpath",
6765 optarg);
6766 got_path_strip_trailing_slashes(repo_path);
6767 break;
6768 case 's':
6769 symref_target = optarg;
6770 break;
6771 case 't':
6772 sort_by_time = 1;
6773 break;
6774 default:
6775 usage_ref();
6776 /* NOTREACHED */
6780 if (obj_arg && do_list)
6781 option_conflict('c', 'l');
6782 if (obj_arg && do_delete)
6783 option_conflict('c', 'd');
6784 if (obj_arg && symref_target)
6785 option_conflict('c', 's');
6786 if (symref_target && do_delete)
6787 option_conflict('s', 'd');
6788 if (symref_target && do_list)
6789 option_conflict('s', 'l');
6790 if (do_delete && do_list)
6791 option_conflict('d', 'l');
6792 if (sort_by_time && !do_list)
6793 errx(1, "-t option requires -l option");
6795 argc -= optind;
6796 argv += optind;
6798 if (do_list) {
6799 if (argc != 0 && argc != 1)
6800 usage_ref();
6801 if (argc == 1) {
6802 refname = strdup(argv[0]);
6803 if (refname == NULL) {
6804 error = got_error_from_errno("strdup");
6805 goto done;
6808 } else {
6809 if (argc != 1)
6810 usage_ref();
6811 refname = strdup(argv[0]);
6812 if (refname == NULL) {
6813 error = got_error_from_errno("strdup");
6814 goto done;
6818 if (refname)
6819 got_path_strip_trailing_slashes(refname);
6821 cwd = getcwd(NULL, 0);
6822 if (cwd == NULL) {
6823 error = got_error_from_errno("getcwd");
6824 goto done;
6827 error = got_repo_pack_fds_open(&pack_fds);
6828 if (error != NULL)
6829 goto done;
6831 if (repo_path == NULL) {
6832 error = got_worktree_open(&worktree, cwd,
6833 GOT_WORKTREE_GOT_DIR);
6834 if (error && error->code != GOT_ERR_NOT_WORKTREE)
6835 goto done;
6836 else
6837 error = NULL;
6838 if (worktree) {
6839 repo_path =
6840 strdup(got_worktree_get_repo_path(worktree));
6841 if (repo_path == NULL)
6842 error = got_error_from_errno("strdup");
6843 if (error)
6844 goto done;
6845 } else {
6846 repo_path = strdup(cwd);
6847 if (repo_path == NULL) {
6848 error = got_error_from_errno("strdup");
6849 goto done;
6854 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
6855 if (error != NULL)
6856 goto done;
6858 #ifndef PROFILE
6859 if (do_list) {
6860 /* Remove "cpath" promise. */
6861 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
6862 NULL) == -1)
6863 err(1, "pledge");
6865 #endif
6867 error = apply_unveil(got_repo_get_path(repo), do_list,
6868 worktree ? got_worktree_get_root_path(worktree) : NULL);
6869 if (error)
6870 goto done;
6872 if (do_list)
6873 error = list_refs(repo, refname, sort_by_time);
6874 else if (do_delete)
6875 error = delete_ref_by_name(repo, refname);
6876 else if (symref_target)
6877 error = add_symref(repo, refname, symref_target);
6878 else {
6879 if (obj_arg == NULL)
6880 usage_ref();
6882 error = got_keyword_to_idstr(&keyword_idstr, obj_arg,
6883 repo, worktree);
6884 if (error != NULL)
6885 goto done;
6886 if (keyword_idstr != NULL)
6887 obj_arg = keyword_idstr;
6889 error = add_ref(repo, refname, obj_arg);
6891 done:
6892 free(refname);
6893 if (repo) {
6894 const struct got_error *close_err = got_repo_close(repo);
6895 if (error == NULL)
6896 error = close_err;
6898 if (worktree)
6899 got_worktree_close(worktree);
6900 if (pack_fds) {
6901 const struct got_error *pack_err =
6902 got_repo_pack_fds_close(pack_fds);
6903 if (error == NULL)
6904 error = pack_err;
6906 free(cwd);
6907 free(repo_path);
6908 free(keyword_idstr);
6909 return error;
6912 __dead static void
6913 usage_branch(void)
6915 fprintf(stderr, "usage: %s branch [-lnt] [-c commit] [-d name] "
6916 "[-r repository-path] [name]\n", getprogname());
6917 exit(1);
6920 static const struct got_error *
6921 list_branch(struct got_repository *repo, struct got_worktree *worktree,
6922 struct got_reference *ref)
6924 const struct got_error *err = NULL;
6925 const char *refname;
6926 char *refstr;
6927 char marker = ' ';
6929 refname = got_ref_get_name(ref);
6930 if (worktree && strcmp(refname,
6931 got_worktree_get_head_ref_name(worktree)) == 0) {
6932 err = got_worktree_get_state(&marker, repo, worktree,
6933 check_cancelled, NULL);
6934 if (err != NULL)
6935 return err;
6938 if (strncmp(refname, "refs/heads/", 11) == 0)
6939 refname += 11;
6940 if (strncmp(refname, "refs/got/worktree/", 18) == 0)
6941 refname += 18;
6942 if (strncmp(refname, "refs/remotes/", 13) == 0)
6943 refname += 13;
6945 refstr = got_ref_to_str(ref);
6946 if (refstr == NULL)
6947 return got_error_from_errno("got_ref_to_str");
6949 printf("%c %s: %s\n", marker, refname, refstr);
6950 free(refstr);
6951 return NULL;
6954 static const struct got_error *
6955 show_current_branch(struct got_repository *repo, struct got_worktree *worktree)
6957 const char *refname;
6959 if (worktree == NULL)
6960 return got_error(GOT_ERR_NOT_WORKTREE);
6962 refname = got_worktree_get_head_ref_name(worktree);
6964 if (strncmp(refname, "refs/heads/", 11) == 0)
6965 refname += 11;
6966 if (strncmp(refname, "refs/got/worktree/", 18) == 0)
6967 refname += 18;
6969 printf("%s\n", refname);
6971 return NULL;
6974 static const struct got_error *
6975 list_branches(struct got_repository *repo, struct got_worktree *worktree,
6976 int sort_by_time)
6978 static const struct got_error *err = NULL;
6979 struct got_reflist_head refs;
6980 struct got_reflist_entry *re;
6981 struct got_reference *temp_ref = NULL;
6982 int rebase_in_progress, histedit_in_progress;
6984 TAILQ_INIT(&refs);
6986 if (worktree) {
6987 err = got_worktree_rebase_in_progress(&rebase_in_progress,
6988 worktree);
6989 if (err)
6990 return err;
6992 err = got_worktree_histedit_in_progress(&histedit_in_progress,
6993 worktree);
6994 if (err)
6995 return err;
6997 if (rebase_in_progress || histedit_in_progress) {
6998 err = got_ref_open(&temp_ref, repo,
6999 got_worktree_get_head_ref_name(worktree), 0);
7000 if (err)
7001 return err;
7002 list_branch(repo, worktree, temp_ref);
7003 got_ref_close(temp_ref);
7007 err = got_ref_list(&refs, repo, "refs/heads", sort_by_time ?
7008 got_ref_cmp_by_commit_timestamp_descending : got_ref_cmp_by_name,
7009 repo);
7010 if (err)
7011 return err;
7013 TAILQ_FOREACH(re, &refs, entry)
7014 list_branch(repo, worktree, re->ref);
7016 got_ref_list_free(&refs);
7018 err = got_ref_list(&refs, repo, "refs/remotes", sort_by_time ?
7019 got_ref_cmp_by_commit_timestamp_descending : got_ref_cmp_by_name,
7020 repo);
7021 if (err)
7022 return err;
7024 TAILQ_FOREACH(re, &refs, entry)
7025 list_branch(repo, worktree, re->ref);
7027 got_ref_list_free(&refs);
7029 return NULL;
7032 static const struct got_error *
7033 delete_branch(struct got_repository *repo, struct got_worktree *worktree,
7034 const char *branch_name)
7036 const struct got_error *err = NULL;
7037 struct got_reference *ref = NULL;
7038 char *refname, *remote_refname = NULL;
7040 if (strncmp(branch_name, "refs/", 5) == 0)
7041 branch_name += 5;
7042 if (strncmp(branch_name, "heads/", 6) == 0)
7043 branch_name += 6;
7044 else if (strncmp(branch_name, "remotes/", 8) == 0)
7045 branch_name += 8;
7047 if (asprintf(&refname, "refs/heads/%s", branch_name) == -1)
7048 return got_error_from_errno("asprintf");
7050 if (asprintf(&remote_refname, "refs/remotes/%s",
7051 branch_name) == -1) {
7052 err = got_error_from_errno("asprintf");
7053 goto done;
7056 err = got_ref_open(&ref, repo, refname, 0);
7057 if (err) {
7058 const struct got_error *err2;
7059 if (err->code != GOT_ERR_NOT_REF)
7060 goto done;
7062 * Keep 'err' intact such that if neither branch exists
7063 * we report "refs/heads" rather than "refs/remotes" in
7064 * our error message.
7066 err2 = got_ref_open(&ref, repo, remote_refname, 0);
7067 if (err2)
7068 goto done;
7069 err = NULL;
7072 if (worktree &&
7073 strcmp(got_worktree_get_head_ref_name(worktree),
7074 got_ref_get_name(ref)) == 0) {
7075 err = got_error_msg(GOT_ERR_SAME_BRANCH,
7076 "will not delete this work tree's current branch");
7077 goto done;
7080 err = delete_ref(repo, ref);
7081 done:
7082 if (ref)
7083 got_ref_close(ref);
7084 free(refname);
7085 free(remote_refname);
7086 return err;
7089 static const struct got_error *
7090 add_branch(struct got_repository *repo, const char *branch_name,
7091 struct got_object_id *base_commit_id)
7093 const struct got_error *err = NULL;
7094 struct got_reference *ref = NULL;
7095 char *refname = NULL;
7098 * Don't let the user create a branch name with a leading '-'.
7099 * While technically a valid reference name, this case is usually
7100 * an unintended typo.
7102 if (branch_name[0] == '-')
7103 return got_error_path(branch_name, GOT_ERR_REF_NAME_MINUS);
7105 if (strncmp(branch_name, "refs/heads/", 11) == 0)
7106 branch_name += 11;
7108 if (asprintf(&refname, "refs/heads/%s", branch_name) == -1) {
7109 err = got_error_from_errno("asprintf");
7110 goto done;
7113 err = got_ref_open(&ref, repo, refname, 0);
7114 if (err == NULL) {
7115 err = got_error(GOT_ERR_BRANCH_EXISTS);
7116 goto done;
7117 } else if (err->code != GOT_ERR_NOT_REF)
7118 goto done;
7120 err = got_ref_alloc(&ref, refname, base_commit_id);
7121 if (err)
7122 goto done;
7124 err = got_ref_write(ref, repo);
7125 done:
7126 if (ref)
7127 got_ref_close(ref);
7128 free(refname);
7129 return err;
7132 static const struct got_error *
7133 cmd_branch(int argc, char *argv[])
7135 const struct got_error *error = NULL;
7136 struct got_repository *repo = NULL;
7137 struct got_worktree *worktree = NULL;
7138 char *cwd = NULL, *repo_path = NULL;
7139 int ch, do_list = 0, do_show = 0, do_update = 1, sort_by_time = 0;
7140 const char *delref = NULL, *commit_id_arg = NULL;
7141 struct got_reference *ref = NULL;
7142 struct got_pathlist_head paths;
7143 struct got_object_id *commit_id = NULL;
7144 char *commit_id_str = NULL, *keyword_idstr = NULL;;
7145 int *pack_fds = NULL;
7147 TAILQ_INIT(&paths);
7149 #ifndef PROFILE
7150 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
7151 "sendfd unveil", NULL) == -1)
7152 err(1, "pledge");
7153 #endif
7155 while ((ch = getopt(argc, argv, "c:d:lnr:t")) != -1) {
7156 switch (ch) {
7157 case 'c':
7158 commit_id_arg = optarg;
7159 break;
7160 case 'd':
7161 delref = optarg;
7162 break;
7163 case 'l':
7164 do_list = 1;
7165 break;
7166 case 'n':
7167 do_update = 0;
7168 break;
7169 case 'r':
7170 repo_path = realpath(optarg, NULL);
7171 if (repo_path == NULL)
7172 return got_error_from_errno2("realpath",
7173 optarg);
7174 got_path_strip_trailing_slashes(repo_path);
7175 break;
7176 case 't':
7177 sort_by_time = 1;
7178 break;
7179 default:
7180 usage_branch();
7181 /* NOTREACHED */
7185 if (do_list && delref)
7186 option_conflict('l', 'd');
7187 if (sort_by_time && !do_list)
7188 errx(1, "-t option requires -l option");
7190 argc -= optind;
7191 argv += optind;
7193 if (!do_list && !delref && argc == 0)
7194 do_show = 1;
7196 if ((do_list || delref || do_show) && commit_id_arg != NULL)
7197 errx(1, "-c option can only be used when creating a branch");
7199 if (do_list || delref) {
7200 if (argc > 0)
7201 usage_branch();
7202 } else if (!do_show && argc != 1)
7203 usage_branch();
7205 cwd = getcwd(NULL, 0);
7206 if (cwd == NULL) {
7207 error = got_error_from_errno("getcwd");
7208 goto done;
7211 error = got_repo_pack_fds_open(&pack_fds);
7212 if (error != NULL)
7213 goto done;
7215 if (repo_path == NULL) {
7216 error = got_worktree_open(&worktree, cwd,
7217 GOT_WORKTREE_GOT_DIR);
7218 if (error && error->code != GOT_ERR_NOT_WORKTREE)
7219 goto done;
7220 else
7221 error = NULL;
7222 if (worktree) {
7223 repo_path =
7224 strdup(got_worktree_get_repo_path(worktree));
7225 if (repo_path == NULL)
7226 error = got_error_from_errno("strdup");
7227 if (error)
7228 goto done;
7229 } else {
7230 repo_path = strdup(cwd);
7231 if (repo_path == NULL) {
7232 error = got_error_from_errno("strdup");
7233 goto done;
7238 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
7239 if (error != NULL)
7240 goto done;
7242 #ifndef PROFILE
7243 if (do_list || do_show) {
7244 /* Remove "cpath" promise. */
7245 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
7246 NULL) == -1)
7247 err(1, "pledge");
7249 #endif
7251 error = apply_unveil(got_repo_get_path(repo), do_list,
7252 worktree ? got_worktree_get_root_path(worktree) : NULL);
7253 if (error)
7254 goto done;
7256 if (do_show)
7257 error = show_current_branch(repo, worktree);
7258 else if (do_list)
7259 error = list_branches(repo, worktree, sort_by_time);
7260 else if (delref)
7261 error = delete_branch(repo, worktree, delref);
7262 else {
7263 struct got_reflist_head refs;
7264 TAILQ_INIT(&refs);
7265 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
7266 NULL);
7267 if (error)
7268 goto done;
7269 if (commit_id_arg == NULL)
7270 commit_id_arg = worktree ?
7271 got_worktree_get_head_ref_name(worktree) :
7272 GOT_REF_HEAD;
7273 else {
7274 error = got_keyword_to_idstr(&keyword_idstr,
7275 commit_id_arg, repo, worktree);
7276 if (error != NULL)
7277 goto done;
7278 if (keyword_idstr != NULL)
7279 commit_id_arg = keyword_idstr;
7281 error = got_repo_match_object_id(&commit_id, NULL,
7282 commit_id_arg, GOT_OBJ_TYPE_COMMIT, &refs, repo);
7283 got_ref_list_free(&refs);
7284 if (error)
7285 goto done;
7286 error = add_branch(repo, argv[0], commit_id);
7287 if (error)
7288 goto done;
7289 if (worktree && do_update) {
7290 struct got_update_progress_arg upa;
7291 char *branch_refname = NULL;
7293 error = got_object_id_str(&commit_id_str, commit_id);
7294 if (error)
7295 goto done;
7296 error = get_worktree_paths_from_argv(&paths, 0, NULL,
7297 worktree);
7298 if (error)
7299 goto done;
7300 if (asprintf(&branch_refname, "refs/heads/%s", argv[0])
7301 == -1) {
7302 error = got_error_from_errno("asprintf");
7303 goto done;
7305 error = got_ref_open(&ref, repo, branch_refname, 0);
7306 free(branch_refname);
7307 if (error)
7308 goto done;
7309 error = switch_head_ref(ref, commit_id, worktree,
7310 repo);
7311 if (error)
7312 goto done;
7313 error = got_worktree_set_base_commit_id(worktree, repo,
7314 commit_id);
7315 if (error)
7316 goto done;
7317 memset(&upa, 0, sizeof(upa));
7318 error = got_worktree_checkout_files(worktree, &paths,
7319 repo, update_progress, &upa, check_cancelled,
7320 NULL);
7321 if (error)
7322 goto done;
7323 if (upa.did_something) {
7324 printf("Updated to %s: %s\n",
7325 got_worktree_get_head_ref_name(worktree),
7326 commit_id_str);
7328 print_update_progress_stats(&upa);
7331 done:
7332 free(keyword_idstr);
7333 if (ref)
7334 got_ref_close(ref);
7335 if (repo) {
7336 const struct got_error *close_err = got_repo_close(repo);
7337 if (error == NULL)
7338 error = close_err;
7340 if (worktree)
7341 got_worktree_close(worktree);
7342 if (pack_fds) {
7343 const struct got_error *pack_err =
7344 got_repo_pack_fds_close(pack_fds);
7345 if (error == NULL)
7346 error = pack_err;
7348 free(cwd);
7349 free(repo_path);
7350 free(commit_id);
7351 free(commit_id_str);
7352 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
7353 return error;
7357 __dead static void
7358 usage_tag(void)
7360 fprintf(stderr, "usage: %s tag [-lVv] [-c commit] [-m message] "
7361 "[-r repository-path] [-s signer-id] name\n", getprogname());
7362 exit(1);
7365 #if 0
7366 static const struct got_error *
7367 sort_tags(struct got_reflist_head *sorted, struct got_reflist_head *tags)
7369 const struct got_error *err = NULL;
7370 struct got_reflist_entry *re, *se, *new;
7371 struct got_object_id *re_id, *se_id;
7372 struct got_tag_object *re_tag, *se_tag;
7373 time_t re_time, se_time;
7375 STAILQ_FOREACH(re, tags, entry) {
7376 se = STAILQ_FIRST(sorted);
7377 if (se == NULL) {
7378 err = got_reflist_entry_dup(&new, re);
7379 if (err)
7380 return err;
7381 STAILQ_INSERT_HEAD(sorted, new, entry);
7382 continue;
7383 } else {
7384 err = got_ref_resolve(&re_id, repo, re->ref);
7385 if (err)
7386 break;
7387 err = got_object_open_as_tag(&re_tag, repo, re_id);
7388 free(re_id);
7389 if (err)
7390 break;
7391 re_time = got_object_tag_get_tagger_time(re_tag);
7392 got_object_tag_close(re_tag);
7395 while (se) {
7396 err = got_ref_resolve(&se_id, repo, re->ref);
7397 if (err)
7398 break;
7399 err = got_object_open_as_tag(&se_tag, repo, se_id);
7400 free(se_id);
7401 if (err)
7402 break;
7403 se_time = got_object_tag_get_tagger_time(se_tag);
7404 got_object_tag_close(se_tag);
7406 if (se_time > re_time) {
7407 err = got_reflist_entry_dup(&new, re);
7408 if (err)
7409 return err;
7410 STAILQ_INSERT_AFTER(sorted, se, new, entry);
7411 break;
7413 se = STAILQ_NEXT(se, entry);
7414 continue;
7417 done:
7418 return err;
7420 #endif
7422 static const struct got_error *
7423 get_tag_refname(char **refname, const char *tag_name)
7425 const struct got_error *err;
7427 if (strncmp("refs/tags/", tag_name, 10) == 0) {
7428 *refname = strdup(tag_name);
7429 if (*refname == NULL)
7430 return got_error_from_errno("strdup");
7431 } else if (asprintf(refname, "refs/tags/%s", tag_name) == -1) {
7432 err = got_error_from_errno("asprintf");
7433 *refname = NULL;
7434 return err;
7437 return NULL;
7440 static const struct got_error *
7441 list_tags(struct got_repository *repo, const char *tag_name, int verify_tags,
7442 const char *allowed_signers, const char *revoked_signers, int verbosity)
7444 static const struct got_error *err = NULL;
7445 struct got_reflist_head refs;
7446 struct got_reflist_entry *re;
7447 char *wanted_refname = NULL;
7448 int bad_sigs = 0;
7450 TAILQ_INIT(&refs);
7452 err = got_ref_list(&refs, repo, "refs/tags", got_ref_cmp_tags, repo);
7453 if (err)
7454 return err;
7456 if (tag_name) {
7457 struct got_reference *ref;
7458 err = get_tag_refname(&wanted_refname, tag_name);
7459 if (err)
7460 goto done;
7461 /* Wanted tag reference should exist. */
7462 err = got_ref_open(&ref, repo, wanted_refname, 0);
7463 if (err)
7464 goto done;
7465 got_ref_close(ref);
7468 TAILQ_FOREACH(re, &refs, entry) {
7469 const char *refname;
7470 char *refstr, *tagmsg0, *tagmsg, *line, *id_str, *datestr;
7471 char datebuf[26];
7472 const char *tagger, *ssh_sig = NULL;
7473 char *sig_msg = NULL;
7474 time_t tagger_time;
7475 struct got_object_id *id;
7476 struct got_tag_object *tag;
7477 struct got_commit_object *commit = NULL;
7479 refname = got_ref_get_name(re->ref);
7480 if (strncmp(refname, "refs/tags/", 10) != 0 ||
7481 (wanted_refname && strcmp(refname, wanted_refname) != 0))
7482 continue;
7483 refname += 10;
7484 refstr = got_ref_to_str(re->ref);
7485 if (refstr == NULL) {
7486 err = got_error_from_errno("got_ref_to_str");
7487 break;
7490 err = got_ref_resolve(&id, repo, re->ref);
7491 if (err)
7492 break;
7493 err = got_object_open_as_tag(&tag, repo, id);
7494 if (err) {
7495 if (err->code != GOT_ERR_OBJ_TYPE) {
7496 free(id);
7497 break;
7499 /* "lightweight" tag */
7500 err = got_object_open_as_commit(&commit, repo, id);
7501 if (err) {
7502 free(id);
7503 break;
7505 tagger = got_object_commit_get_committer(commit);
7506 tagger_time =
7507 got_object_commit_get_committer_time(commit);
7508 err = got_object_id_str(&id_str, id);
7509 free(id);
7510 if (err)
7511 break;
7512 } else {
7513 free(id);
7514 tagger = got_object_tag_get_tagger(tag);
7515 tagger_time = got_object_tag_get_tagger_time(tag);
7516 err = got_object_id_str(&id_str,
7517 got_object_tag_get_object_id(tag));
7518 if (err)
7519 break;
7522 if (tag && verify_tags) {
7523 ssh_sig = got_sigs_get_tagmsg_ssh_signature(
7524 got_object_tag_get_message(tag));
7525 if (ssh_sig && allowed_signers == NULL) {
7526 err = got_error_msg(
7527 GOT_ERR_VERIFY_TAG_SIGNATURE,
7528 "SSH signature verification requires "
7529 "setting allowed_signers in "
7530 "got.conf(5)");
7531 break;
7535 printf("%stag %s %s\n", GOT_COMMIT_SEP_STR, refname, refstr);
7536 free(refstr);
7537 printf("from: %s\n", tagger);
7538 datestr = get_datestr(&tagger_time, datebuf);
7539 if (datestr)
7540 printf("date: %s UTC\n", datestr);
7541 if (commit)
7542 printf("object: %s %s\n", GOT_OBJ_LABEL_COMMIT, id_str);
7543 else {
7544 switch (got_object_tag_get_object_type(tag)) {
7545 case GOT_OBJ_TYPE_BLOB:
7546 printf("object: %s %s\n", GOT_OBJ_LABEL_BLOB,
7547 id_str);
7548 break;
7549 case GOT_OBJ_TYPE_TREE:
7550 printf("object: %s %s\n", GOT_OBJ_LABEL_TREE,
7551 id_str);
7552 break;
7553 case GOT_OBJ_TYPE_COMMIT:
7554 printf("object: %s %s\n", GOT_OBJ_LABEL_COMMIT,
7555 id_str);
7556 break;
7557 case GOT_OBJ_TYPE_TAG:
7558 printf("object: %s %s\n", GOT_OBJ_LABEL_TAG,
7559 id_str);
7560 break;
7561 default:
7562 break;
7565 free(id_str);
7567 if (ssh_sig) {
7568 err = got_sigs_verify_tag_ssh(&sig_msg, tag, ssh_sig,
7569 allowed_signers, revoked_signers, verbosity);
7570 if (err && err->code == GOT_ERR_BAD_TAG_SIGNATURE)
7571 bad_sigs = 1;
7572 else if (err)
7573 break;
7574 printf("signature: %s", sig_msg);
7575 free(sig_msg);
7576 sig_msg = NULL;
7579 if (commit) {
7580 err = got_object_commit_get_logmsg(&tagmsg0, commit);
7581 if (err)
7582 break;
7583 got_object_commit_close(commit);
7584 } else {
7585 tagmsg0 = strdup(got_object_tag_get_message(tag));
7586 got_object_tag_close(tag);
7587 if (tagmsg0 == NULL) {
7588 err = got_error_from_errno("strdup");
7589 break;
7593 tagmsg = tagmsg0;
7594 do {
7595 line = strsep(&tagmsg, "\n");
7596 if (line)
7597 printf(" %s\n", line);
7598 } while (line);
7599 free(tagmsg0);
7601 done:
7602 got_ref_list_free(&refs);
7603 free(wanted_refname);
7605 if (err == NULL && bad_sigs)
7606 err = got_error(GOT_ERR_BAD_TAG_SIGNATURE);
7607 return err;
7610 static const struct got_error *
7611 get_tag_message(char **tagmsg, char **tagmsg_path, const char *commit_id_str,
7612 const char *tag_name, const char *editor, const char *repo_path)
7614 const struct got_error *err = NULL;
7615 char *template = NULL, *initial_content = NULL;
7616 int initial_content_len;
7617 int fd = -1;
7619 if (asprintf(&template, GOT_TMPDIR_STR "/got-tagmsg") == -1) {
7620 err = got_error_from_errno("asprintf");
7621 goto done;
7624 initial_content_len = asprintf(&initial_content,
7625 "\n# tagging commit %s as %s\n",
7626 commit_id_str, tag_name);
7627 if (initial_content_len == -1) {
7628 err = got_error_from_errno("asprintf");
7629 goto done;
7632 err = got_opentemp_named_fd(tagmsg_path, &fd, template, "");
7633 if (err)
7634 goto done;
7636 if (write(fd, initial_content, initial_content_len) == -1) {
7637 err = got_error_from_errno2("write", *tagmsg_path);
7638 goto done;
7640 if (close(fd) == -1) {
7641 err = got_error_from_errno2("close", *tagmsg_path);
7642 goto done;
7644 fd = -1;
7646 err = edit_logmsg(tagmsg, editor, *tagmsg_path, initial_content,
7647 initial_content_len, 1);
7648 done:
7649 free(initial_content);
7650 free(template);
7652 if (fd != -1 && close(fd) == -1 && err == NULL)
7653 err = got_error_from_errno2("close", *tagmsg_path);
7655 if (err) {
7656 free(*tagmsg);
7657 *tagmsg = NULL;
7659 return err;
7662 static const struct got_error *
7663 add_tag(struct got_repository *repo, const char *tagger,
7664 const char *tag_name, const char *commit_arg, const char *tagmsg_arg,
7665 const char *signer_id, const char *editor, int verbosity)
7667 const struct got_error *err = NULL;
7668 struct got_object_id *commit_id = NULL, *tag_id = NULL;
7669 char *label = NULL, *commit_id_str = NULL;
7670 struct got_reference *ref = NULL;
7671 char *refname = NULL, *tagmsg = NULL;
7672 char *tagmsg_path = NULL, *tag_id_str = NULL;
7673 int preserve_tagmsg = 0;
7674 struct got_reflist_head refs;
7676 TAILQ_INIT(&refs);
7679 * Don't let the user create a tag name with a leading '-'.
7680 * While technically a valid reference name, this case is usually
7681 * an unintended typo.
7683 if (tag_name[0] == '-')
7684 return got_error_path(tag_name, GOT_ERR_REF_NAME_MINUS);
7686 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
7687 if (err)
7688 goto done;
7690 err = got_repo_match_object_id(&commit_id, &label, commit_arg,
7691 GOT_OBJ_TYPE_COMMIT, &refs, repo);
7692 if (err)
7693 goto done;
7695 err = got_object_id_str(&commit_id_str, commit_id);
7696 if (err)
7697 goto done;
7699 err = get_tag_refname(&refname, tag_name);
7700 if (err)
7701 goto done;
7702 if (strncmp("refs/tags/", tag_name, 10) == 0)
7703 tag_name += 10;
7705 err = got_ref_open(&ref, repo, refname, 0);
7706 if (err == NULL) {
7707 err = got_error(GOT_ERR_TAG_EXISTS);
7708 goto done;
7709 } else if (err->code != GOT_ERR_NOT_REF)
7710 goto done;
7712 if (tagmsg_arg == NULL) {
7713 err = get_tag_message(&tagmsg, &tagmsg_path, commit_id_str,
7714 tag_name, editor, got_repo_get_path(repo));
7715 if (err) {
7716 if (err->code != GOT_ERR_COMMIT_MSG_EMPTY &&
7717 tagmsg_path != NULL)
7718 preserve_tagmsg = 1;
7719 goto done;
7723 err = got_object_tag_create(&tag_id, tag_name, commit_id,
7724 tagger, time(NULL), tagmsg ? tagmsg : tagmsg_arg, signer_id, repo,
7725 verbosity);
7726 if (err) {
7727 if (tagmsg_path)
7728 preserve_tagmsg = 1;
7729 goto done;
7732 err = got_ref_alloc(&ref, refname, tag_id);
7733 if (err) {
7734 if (tagmsg_path)
7735 preserve_tagmsg = 1;
7736 goto done;
7739 err = got_ref_write(ref, repo);
7740 if (err) {
7741 if (tagmsg_path)
7742 preserve_tagmsg = 1;
7743 goto done;
7746 err = got_object_id_str(&tag_id_str, tag_id);
7747 if (err) {
7748 if (tagmsg_path)
7749 preserve_tagmsg = 1;
7750 goto done;
7752 printf("Created tag %s\n", tag_id_str);
7753 done:
7754 if (preserve_tagmsg) {
7755 fprintf(stderr, "%s: tag message preserved in %s\n",
7756 getprogname(), tagmsg_path);
7757 } else if (tagmsg_path && unlink(tagmsg_path) == -1 && err == NULL)
7758 err = got_error_from_errno2("unlink", tagmsg_path);
7759 free(tag_id_str);
7760 if (ref)
7761 got_ref_close(ref);
7762 free(commit_id);
7763 free(commit_id_str);
7764 free(refname);
7765 free(tagmsg);
7766 free(tagmsg_path);
7767 got_ref_list_free(&refs);
7768 return err;
7771 static const struct got_error *
7772 cmd_tag(int argc, char *argv[])
7774 const struct got_error *error = NULL;
7775 struct got_repository *repo = NULL;
7776 struct got_worktree *worktree = NULL;
7777 char *cwd = NULL, *repo_path = NULL, *commit_id_str = NULL;
7778 char *gitconfig_path = NULL, *tagger = NULL, *keyword_idstr = NULL;
7779 char *allowed_signers = NULL, *revoked_signers = NULL, *editor = NULL;
7780 const char *signer_id = NULL;
7781 const char *tag_name = NULL, *commit_id_arg = NULL, *tagmsg = NULL;
7782 int ch, do_list = 0, verify_tags = 0, verbosity = 0;
7783 int *pack_fds = NULL;
7785 #ifndef PROFILE
7786 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
7787 "sendfd unveil", NULL) == -1)
7788 err(1, "pledge");
7789 #endif
7791 while ((ch = getopt(argc, argv, "c:lm:r:s:Vv")) != -1) {
7792 switch (ch) {
7793 case 'c':
7794 commit_id_arg = optarg;
7795 break;
7796 case 'l':
7797 do_list = 1;
7798 break;
7799 case 'm':
7800 tagmsg = optarg;
7801 break;
7802 case 'r':
7803 repo_path = realpath(optarg, NULL);
7804 if (repo_path == NULL) {
7805 error = got_error_from_errno2("realpath",
7806 optarg);
7807 goto done;
7809 got_path_strip_trailing_slashes(repo_path);
7810 break;
7811 case 's':
7812 signer_id = optarg;
7813 break;
7814 case 'V':
7815 verify_tags = 1;
7816 break;
7817 case 'v':
7818 if (verbosity < 0)
7819 verbosity = 0;
7820 else if (verbosity < 3)
7821 verbosity++;
7822 break;
7823 default:
7824 usage_tag();
7825 /* NOTREACHED */
7829 argc -= optind;
7830 argv += optind;
7832 if (do_list || verify_tags) {
7833 if (commit_id_arg != NULL)
7834 errx(1,
7835 "-c option can only be used when creating a tag");
7836 if (tagmsg) {
7837 if (do_list)
7838 option_conflict('l', 'm');
7839 else
7840 option_conflict('V', 'm');
7842 if (signer_id) {
7843 if (do_list)
7844 option_conflict('l', 's');
7845 else
7846 option_conflict('V', 's');
7848 if (argc > 1)
7849 usage_tag();
7850 } else if (argc != 1)
7851 usage_tag();
7853 if (argc == 1)
7854 tag_name = argv[0];
7856 cwd = getcwd(NULL, 0);
7857 if (cwd == NULL) {
7858 error = got_error_from_errno("getcwd");
7859 goto done;
7862 error = got_repo_pack_fds_open(&pack_fds);
7863 if (error != NULL)
7864 goto done;
7866 if (repo_path == NULL) {
7867 error = got_worktree_open(&worktree, cwd,
7868 GOT_WORKTREE_GOT_DIR);
7869 if (error && error->code != GOT_ERR_NOT_WORKTREE)
7870 goto done;
7871 else
7872 error = NULL;
7873 if (worktree) {
7874 repo_path =
7875 strdup(got_worktree_get_repo_path(worktree));
7876 if (repo_path == NULL)
7877 error = got_error_from_errno("strdup");
7878 if (error)
7879 goto done;
7880 } else {
7881 repo_path = strdup(cwd);
7882 if (repo_path == NULL) {
7883 error = got_error_from_errno("strdup");
7884 goto done;
7889 if (do_list || verify_tags) {
7890 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
7891 if (error != NULL)
7892 goto done;
7893 error = get_allowed_signers(&allowed_signers, repo, worktree);
7894 if (error)
7895 goto done;
7896 error = get_revoked_signers(&revoked_signers, repo, worktree);
7897 if (error)
7898 goto done;
7899 if (worktree) {
7900 /* Release work tree lock. */
7901 got_worktree_close(worktree);
7902 worktree = NULL;
7906 * Remove "cpath" promise unless needed for signature tmpfile
7907 * creation.
7909 if (verify_tags)
7910 got_sigs_apply_unveil();
7911 else {
7912 #ifndef PROFILE
7913 if (pledge("stdio rpath wpath flock proc exec sendfd "
7914 "unveil", NULL) == -1)
7915 err(1, "pledge");
7916 #endif
7918 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
7919 if (error)
7920 goto done;
7921 error = list_tags(repo, tag_name, verify_tags, allowed_signers,
7922 revoked_signers, verbosity);
7923 } else {
7924 error = get_gitconfig_path(&gitconfig_path);
7925 if (error)
7926 goto done;
7927 error = got_repo_open(&repo, repo_path, gitconfig_path,
7928 pack_fds);
7929 if (error != NULL)
7930 goto done;
7932 error = get_author(&tagger, repo, worktree);
7933 if (error)
7934 goto done;
7935 if (signer_id == NULL)
7936 signer_id = get_signer_id(repo, worktree);
7938 if (tagmsg == NULL) {
7939 error = get_editor(&editor);
7940 if (error)
7941 goto done;
7942 if (unveil(editor, "x") != 0) {
7943 error = got_error_from_errno2("unveil", editor);
7944 goto done;
7947 if (signer_id) {
7948 error = got_sigs_apply_unveil();
7949 if (error)
7950 goto done;
7952 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
7953 if (error)
7954 goto done;
7956 if (commit_id_arg == NULL) {
7957 struct got_reference *head_ref;
7958 struct got_object_id *commit_id;
7959 error = got_ref_open(&head_ref, repo,
7960 worktree ? got_worktree_get_head_ref_name(worktree)
7961 : GOT_REF_HEAD, 0);
7962 if (error)
7963 goto done;
7964 error = got_ref_resolve(&commit_id, repo, head_ref);
7965 got_ref_close(head_ref);
7966 if (error)
7967 goto done;
7968 error = got_object_id_str(&commit_id_str, commit_id);
7969 free(commit_id);
7970 if (error)
7971 goto done;
7972 } else {
7973 error = got_keyword_to_idstr(&keyword_idstr,
7974 commit_id_arg, repo, worktree);
7975 if (error != NULL)
7976 goto done;
7977 commit_id_str = keyword_idstr;
7980 if (worktree) {
7981 /* Release work tree lock. */
7982 got_worktree_close(worktree);
7983 worktree = NULL;
7986 error = add_tag(repo, tagger, tag_name,
7987 commit_id_str ? commit_id_str : commit_id_arg, tagmsg,
7988 signer_id, editor, verbosity);
7990 done:
7991 if (repo) {
7992 const struct got_error *close_err = got_repo_close(repo);
7993 if (error == NULL)
7994 error = close_err;
7996 if (worktree)
7997 got_worktree_close(worktree);
7998 if (pack_fds) {
7999 const struct got_error *pack_err =
8000 got_repo_pack_fds_close(pack_fds);
8001 if (error == NULL)
8002 error = pack_err;
8004 free(cwd);
8005 free(editor);
8006 free(repo_path);
8007 free(gitconfig_path);
8008 free(commit_id_str);
8009 free(tagger);
8010 free(allowed_signers);
8011 free(revoked_signers);
8012 return error;
8015 __dead static void
8016 usage_add(void)
8018 fprintf(stderr, "usage: %s add [-IR] path ...\n", getprogname());
8019 exit(1);
8022 static const struct got_error *
8023 add_progress(void *arg, unsigned char status, const char *path)
8025 while (path[0] == '/')
8026 path++;
8027 printf("%c %s\n", status, path);
8028 return NULL;
8031 static const struct got_error *
8032 check_paths_contains_dir(int *contains_dir, struct got_worktree *worktree,
8033 struct got_pathlist_head *paths)
8035 const struct got_error *error = NULL;
8036 struct got_pathlist_entry *pe;
8037 struct stat sb;
8038 char *ondisk_path;
8040 *contains_dir = 0;
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 return got_error_from_errno("asprintf");
8048 if (lstat(ondisk_path, &sb) == -1) {
8049 if (errno == ENOENT) {
8050 free(ondisk_path);
8051 continue;
8053 error = got_error_from_errno2("lstat",
8054 ondisk_path);
8055 free(ondisk_path);
8056 return error;
8058 free(ondisk_path);
8059 if (S_ISDIR(sb.st_mode)) {
8060 *contains_dir = 1;
8061 return NULL;
8064 return NULL;
8067 static const struct got_error *
8068 cmd_add(int argc, char *argv[])
8070 const struct got_error *error = NULL;
8071 struct got_repository *repo = NULL;
8072 struct got_worktree *worktree = NULL;
8073 char *cwd = NULL;
8074 struct got_pathlist_head paths;
8075 int ch, contains_dir, can_recurse = 0, no_ignores = 0;
8076 int *pack_fds = NULL;
8078 TAILQ_INIT(&paths);
8080 #ifndef PROFILE
8081 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
8082 NULL) == -1)
8083 err(1, "pledge");
8084 #endif
8086 while ((ch = getopt(argc, argv, "IR")) != -1) {
8087 switch (ch) {
8088 case 'I':
8089 no_ignores = 1;
8090 break;
8091 case 'R':
8092 can_recurse = 1;
8093 break;
8094 default:
8095 usage_add();
8096 /* NOTREACHED */
8100 argc -= optind;
8101 argv += optind;
8103 if (argc < 1)
8104 usage_add();
8106 cwd = getcwd(NULL, 0);
8107 if (cwd == NULL) {
8108 error = got_error_from_errno("getcwd");
8109 goto done;
8112 error = got_repo_pack_fds_open(&pack_fds);
8113 if (error != NULL)
8114 goto done;
8116 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
8117 if (error) {
8118 if (error->code == GOT_ERR_NOT_WORKTREE)
8119 error = wrap_not_worktree_error(error, "add", cwd);
8120 goto done;
8123 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
8124 NULL, pack_fds);
8125 if (error != NULL)
8126 goto done;
8128 error = apply_unveil(got_repo_get_path(repo), 1,
8129 got_worktree_get_root_path(worktree));
8130 if (error)
8131 goto done;
8133 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
8134 if (error)
8135 goto done;
8137 if (!can_recurse) {
8138 error = check_paths_contains_dir(&contains_dir, worktree, &paths);
8139 if (error != NULL)
8140 goto done;
8142 if (contains_dir) {
8143 error = got_error_msg(GOT_ERR_BAD_PATH,
8144 "adding directories requires -R option");
8145 goto done;
8149 error = got_worktree_schedule_add(worktree, &paths, add_progress,
8150 NULL, repo, no_ignores);
8151 done:
8152 if (repo) {
8153 const struct got_error *close_err = got_repo_close(repo);
8154 if (error == NULL)
8155 error = close_err;
8157 if (worktree)
8158 got_worktree_close(worktree);
8159 if (pack_fds) {
8160 const struct got_error *pack_err =
8161 got_repo_pack_fds_close(pack_fds);
8162 if (error == NULL)
8163 error = pack_err;
8165 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
8166 free(cwd);
8167 return error;
8170 __dead static void
8171 usage_remove(void)
8173 fprintf(stderr, "usage: %s remove [-fkR] [-s status-codes] path ...\n",
8174 getprogname());
8175 exit(1);
8178 static const struct got_error *
8179 print_remove_status(void *arg, unsigned char status,
8180 unsigned char staged_status, const char *path)
8182 while (path[0] == '/')
8183 path++;
8184 if (status == GOT_STATUS_NONEXISTENT)
8185 return NULL;
8186 if (status == staged_status && (status == GOT_STATUS_DELETE))
8187 status = GOT_STATUS_NO_CHANGE;
8188 printf("%c%c %s\n", status, staged_status, path);
8189 return NULL;
8192 static const struct got_error *
8193 cmd_remove(int argc, char *argv[])
8195 const struct got_error *error = NULL;
8196 struct got_worktree *worktree = NULL;
8197 struct got_repository *repo = NULL;
8198 const char *status_codes = NULL;
8199 char *cwd = NULL;
8200 struct got_pathlist_head paths;
8201 int contains_dir, ch, i, delete_local_mods = 0, can_recurse = 0;
8202 int ignore_missing_paths = 0, keep_on_disk = 0;
8203 int *pack_fds = NULL;
8205 TAILQ_INIT(&paths);
8207 #ifndef PROFILE
8208 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
8209 NULL) == -1)
8210 err(1, "pledge");
8211 #endif
8213 while ((ch = getopt(argc, argv, "fkRs:")) != -1) {
8214 switch (ch) {
8215 case 'f':
8216 delete_local_mods = 1;
8217 ignore_missing_paths = 1;
8218 break;
8219 case 'k':
8220 keep_on_disk = 1;
8221 break;
8222 case 'R':
8223 can_recurse = 1;
8224 break;
8225 case 's':
8226 for (i = 0; optarg[i] != '\0'; i++) {
8227 switch (optarg[i]) {
8228 case GOT_STATUS_MODIFY:
8229 delete_local_mods = 1;
8230 break;
8231 case GOT_STATUS_MISSING:
8232 ignore_missing_paths = 1;
8233 break;
8234 default:
8235 errx(1, "invalid status code '%c'",
8236 optarg[i]);
8239 status_codes = optarg;
8240 break;
8241 default:
8242 usage_remove();
8243 /* NOTREACHED */
8247 argc -= optind;
8248 argv += optind;
8250 if (argc < 1)
8251 usage_remove();
8253 cwd = getcwd(NULL, 0);
8254 if (cwd == NULL) {
8255 error = got_error_from_errno("getcwd");
8256 goto done;
8259 error = got_repo_pack_fds_open(&pack_fds);
8260 if (error != NULL)
8261 goto done;
8263 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
8264 if (error) {
8265 if (error->code == GOT_ERR_NOT_WORKTREE)
8266 error = wrap_not_worktree_error(error, "remove", cwd);
8267 goto done;
8270 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
8271 NULL, pack_fds);
8272 if (error)
8273 goto done;
8275 error = apply_unveil(got_repo_get_path(repo), 1,
8276 got_worktree_get_root_path(worktree));
8277 if (error)
8278 goto done;
8280 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
8281 if (error)
8282 goto done;
8284 if (!can_recurse) {
8285 error = check_paths_contains_dir(&contains_dir, worktree, &paths);
8286 if (error != NULL)
8287 goto done;
8289 if (contains_dir) {
8290 error = got_error_msg(GOT_ERR_BAD_PATH,
8291 "removing directories requires -R option");
8292 goto done;
8296 error = got_worktree_schedule_delete(worktree, &paths,
8297 delete_local_mods, status_codes, print_remove_status, NULL,
8298 repo, keep_on_disk, ignore_missing_paths);
8299 done:
8300 if (repo) {
8301 const struct got_error *close_err = got_repo_close(repo);
8302 if (error == NULL)
8303 error = close_err;
8305 if (worktree)
8306 got_worktree_close(worktree);
8307 if (pack_fds) {
8308 const struct got_error *pack_err =
8309 got_repo_pack_fds_close(pack_fds);
8310 if (error == NULL)
8311 error = pack_err;
8313 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
8314 free(cwd);
8315 return error;
8318 __dead static void
8319 usage_patch(void)
8321 fprintf(stderr, "usage: %s patch [-nR] [-c commit] [-p strip-count] "
8322 "[patchfile]\n", getprogname());
8323 exit(1);
8326 static const struct got_error *
8327 patch_from_stdin(int *patchfd)
8329 const struct got_error *err = NULL;
8330 ssize_t r;
8331 char buf[BUFSIZ];
8332 sig_t sighup, sigint, sigquit;
8334 *patchfd = got_opentempfd();
8335 if (*patchfd == -1)
8336 return got_error_from_errno("got_opentempfd");
8338 sighup = signal(SIGHUP, SIG_DFL);
8339 sigint = signal(SIGINT, SIG_DFL);
8340 sigquit = signal(SIGQUIT, SIG_DFL);
8342 for (;;) {
8343 r = read(0, buf, sizeof(buf));
8344 if (r == -1) {
8345 err = got_error_from_errno("read");
8346 break;
8348 if (r == 0)
8349 break;
8350 if (write(*patchfd, buf, r) == -1) {
8351 err = got_error_from_errno("write");
8352 break;
8356 signal(SIGHUP, sighup);
8357 signal(SIGINT, sigint);
8358 signal(SIGQUIT, sigquit);
8360 if (err == NULL && lseek(*patchfd, 0, SEEK_SET) == -1)
8361 err = got_error_from_errno("lseek");
8363 if (err != NULL) {
8364 close(*patchfd);
8365 *patchfd = -1;
8368 return err;
8371 struct got_patch_progress_arg {
8372 int did_something;
8373 int conflicts;
8374 int rejects;
8377 static const struct got_error *
8378 patch_progress(void *arg, const char *old, const char *new,
8379 unsigned char status, const struct got_error *error, int old_from,
8380 int old_lines, int new_from, int new_lines, int offset,
8381 int ws_mangled, const struct got_error *hunk_err)
8383 const char *path = new == NULL ? old : new;
8384 struct got_patch_progress_arg *a = arg;
8386 while (*path == '/')
8387 path++;
8389 if (status != GOT_STATUS_NO_CHANGE &&
8390 status != 0 /* per-hunk progress */) {
8391 printf("%c %s\n", status, path);
8392 a->did_something = 1;
8395 if (hunk_err == NULL) {
8396 if (status == GOT_STATUS_CANNOT_UPDATE)
8397 a->rejects++;
8398 else if (status == GOT_STATUS_CONFLICT)
8399 a->conflicts++;
8402 if (error != NULL)
8403 fprintf(stderr, "%s: %s\n", getprogname(), error->msg);
8405 if (offset != 0 || hunk_err != NULL || ws_mangled) {
8406 printf("@@ -%d,%d +%d,%d @@ ", old_from,
8407 old_lines, new_from, new_lines);
8408 if (hunk_err != NULL)
8409 printf("%s\n", hunk_err->msg);
8410 else if (offset != 0)
8411 printf("applied with offset %d\n", offset);
8412 else
8413 printf("hunk contains mangled whitespace\n");
8416 return NULL;
8419 static void
8420 print_patch_progress_stats(struct got_patch_progress_arg *ppa)
8422 if (!ppa->did_something)
8423 return;
8425 if (ppa->conflicts > 0)
8426 printf("Files with merge conflicts: %d\n", ppa->conflicts);
8428 if (ppa->rejects > 0) {
8429 printf("Files where patch failed to apply: %d\n",
8430 ppa->rejects);
8434 static const struct got_error *
8435 cmd_patch(int argc, char *argv[])
8437 const struct got_error *error = NULL, *close_error = NULL;
8438 struct got_worktree *worktree = NULL;
8439 struct got_repository *repo = NULL;
8440 struct got_reflist_head refs;
8441 struct got_object_id *commit_id = NULL;
8442 const char *commit_id_str = NULL;
8443 struct stat sb;
8444 const char *errstr;
8445 char *cwd = NULL, *keyword_idstr = NULL;
8446 int ch, nop = 0, strip = -1, reverse = 0;
8447 int patchfd;
8448 int *pack_fds = NULL;
8449 struct got_patch_progress_arg ppa;
8451 TAILQ_INIT(&refs);
8453 #ifndef PROFILE
8454 if (pledge("stdio rpath wpath cpath fattr proc exec sendfd flock "
8455 "unveil", NULL) == -1)
8456 err(1, "pledge");
8457 #endif
8459 while ((ch = getopt(argc, argv, "c:np:R")) != -1) {
8460 switch (ch) {
8461 case 'c':
8462 commit_id_str = optarg;
8463 break;
8464 case 'n':
8465 nop = 1;
8466 break;
8467 case 'p':
8468 strip = strtonum(optarg, 0, INT_MAX, &errstr);
8469 if (errstr != NULL)
8470 errx(1, "pathname strip count is %s: %s",
8471 errstr, optarg);
8472 break;
8473 case 'R':
8474 reverse = 1;
8475 break;
8476 default:
8477 usage_patch();
8478 /* NOTREACHED */
8482 argc -= optind;
8483 argv += optind;
8485 if (argc == 0) {
8486 error = patch_from_stdin(&patchfd);
8487 if (error)
8488 return error;
8489 } else if (argc == 1) {
8490 patchfd = open(argv[0], O_RDONLY);
8491 if (patchfd == -1) {
8492 error = got_error_from_errno2("open", argv[0]);
8493 return error;
8495 if (fstat(patchfd, &sb) == -1) {
8496 error = got_error_from_errno2("fstat", argv[0]);
8497 goto done;
8499 if (!S_ISREG(sb.st_mode)) {
8500 error = got_error_path(argv[0], GOT_ERR_BAD_FILETYPE);
8501 goto done;
8503 } else
8504 usage_patch();
8506 if ((cwd = getcwd(NULL, 0)) == NULL) {
8507 error = got_error_from_errno("getcwd");
8508 goto done;
8511 error = got_repo_pack_fds_open(&pack_fds);
8512 if (error != NULL)
8513 goto done;
8515 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
8516 if (error != NULL)
8517 goto done;
8519 const char *repo_path = got_worktree_get_repo_path(worktree);
8520 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
8521 if (error != NULL)
8522 goto done;
8524 error = apply_unveil(got_repo_get_path(repo), 0,
8525 got_worktree_get_root_path(worktree));
8526 if (error != NULL)
8527 goto done;
8529 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
8530 if (error)
8531 goto done;
8533 if (commit_id_str != NULL) {
8534 error = got_keyword_to_idstr(&keyword_idstr, commit_id_str,
8535 repo, worktree);
8536 if (error != NULL)
8537 goto done;
8539 error = got_repo_match_object_id(&commit_id, NULL,
8540 keyword_idstr != NULL ? keyword_idstr : commit_id_str,
8541 GOT_OBJ_TYPE_COMMIT, &refs, repo);
8542 if (error)
8543 goto done;
8546 memset(&ppa, 0, sizeof(ppa));
8547 error = got_patch(patchfd, worktree, repo, nop, strip, reverse,
8548 commit_id, patch_progress, &ppa, check_cancelled, NULL);
8549 print_patch_progress_stats(&ppa);
8550 done:
8551 got_ref_list_free(&refs);
8552 free(keyword_idstr);
8553 free(commit_id);
8554 if (repo) {
8555 close_error = got_repo_close(repo);
8556 if (error == NULL)
8557 error = close_error;
8559 if (worktree != NULL) {
8560 close_error = got_worktree_close(worktree);
8561 if (error == NULL)
8562 error = close_error;
8564 if (pack_fds) {
8565 const struct got_error *pack_err =
8566 got_repo_pack_fds_close(pack_fds);
8567 if (error == NULL)
8568 error = pack_err;
8570 free(cwd);
8571 return error;
8574 __dead static void
8575 usage_revert(void)
8577 fprintf(stderr, "usage: %s revert [-pR] [-F response-script] path ...\n",
8578 getprogname());
8579 exit(1);
8582 static const struct got_error *
8583 revert_progress(void *arg, unsigned char status, const char *path)
8585 if (status == GOT_STATUS_UNVERSIONED)
8586 return NULL;
8588 while (path[0] == '/')
8589 path++;
8590 printf("%c %s\n", status, path);
8591 return NULL;
8594 struct choose_patch_arg {
8595 FILE *patch_script_file;
8596 const char *action;
8599 static const struct got_error *
8600 show_change(unsigned char status, const char *path, FILE *patch_file, int n,
8601 int nchanges, const char *action)
8603 const struct got_error *err;
8604 char *line = NULL;
8605 size_t linesize = 0;
8606 ssize_t linelen;
8608 switch (status) {
8609 case GOT_STATUS_ADD:
8610 printf("A %s\n%s this addition? [y/n] ", path, action);
8611 break;
8612 case GOT_STATUS_DELETE:
8613 printf("D %s\n%s this deletion? [y/n] ", path, action);
8614 break;
8615 case GOT_STATUS_MODIFY:
8616 if (fseek(patch_file, 0L, SEEK_SET) == -1)
8617 return got_error_from_errno("fseek");
8618 printf(GOT_COMMIT_SEP_STR);
8619 while ((linelen = getline(&line, &linesize, patch_file)) != -1)
8620 printf("%s", line);
8621 if (linelen == -1 && ferror(patch_file)) {
8622 err = got_error_from_errno("getline");
8623 free(line);
8624 return err;
8626 free(line);
8627 printf(GOT_COMMIT_SEP_STR);
8628 printf("M %s (change %d of %d)\n%s this change? [y/n/q] ",
8629 path, n, nchanges, action);
8630 break;
8631 default:
8632 return got_error_path(path, GOT_ERR_FILE_STATUS);
8635 fflush(stdout);
8636 return NULL;
8639 static const struct got_error *
8640 choose_patch(int *choice, void *arg, unsigned char status, const char *path,
8641 FILE *patch_file, int n, int nchanges)
8643 const struct got_error *err = NULL;
8644 char *line = NULL;
8645 size_t linesize = 0;
8646 ssize_t linelen;
8647 int resp = ' ';
8648 struct choose_patch_arg *a = arg;
8650 *choice = GOT_PATCH_CHOICE_NONE;
8652 if (a->patch_script_file) {
8653 char *nl;
8654 err = show_change(status, path, patch_file, n, nchanges,
8655 a->action);
8656 if (err)
8657 return err;
8658 linelen = getline(&line, &linesize, a->patch_script_file);
8659 if (linelen == -1) {
8660 if (ferror(a->patch_script_file))
8661 return got_error_from_errno("getline");
8662 return NULL;
8664 nl = strchr(line, '\n');
8665 if (nl)
8666 *nl = '\0';
8667 if (strcmp(line, "y") == 0) {
8668 *choice = GOT_PATCH_CHOICE_YES;
8669 printf("y\n");
8670 } else if (strcmp(line, "n") == 0) {
8671 *choice = GOT_PATCH_CHOICE_NO;
8672 printf("n\n");
8673 } else if (strcmp(line, "q") == 0 &&
8674 status == GOT_STATUS_MODIFY) {
8675 *choice = GOT_PATCH_CHOICE_QUIT;
8676 printf("q\n");
8677 } else
8678 printf("invalid response '%s'\n", line);
8679 free(line);
8680 return NULL;
8683 while (resp != 'y' && resp != 'n' && resp != 'q') {
8684 err = show_change(status, path, patch_file, n, nchanges,
8685 a->action);
8686 if (err)
8687 return err;
8688 resp = getchar();
8689 if (resp == '\n')
8690 resp = getchar();
8691 if (status == GOT_STATUS_MODIFY) {
8692 if (resp != 'y' && resp != 'n' && resp != 'q') {
8693 printf("invalid response '%c'\n", resp);
8694 resp = ' ';
8696 } else if (resp != 'y' && resp != 'n') {
8697 printf("invalid response '%c'\n", resp);
8698 resp = ' ';
8702 if (resp == 'y')
8703 *choice = GOT_PATCH_CHOICE_YES;
8704 else if (resp == 'n')
8705 *choice = GOT_PATCH_CHOICE_NO;
8706 else if (resp == 'q' && status == GOT_STATUS_MODIFY)
8707 *choice = GOT_PATCH_CHOICE_QUIT;
8709 return NULL;
8712 struct wt_commitable_path_arg {
8713 struct got_pathlist_head *commit_paths;
8714 int *has_changes;
8718 * Shortcut work tree status callback to determine if the set of paths scanned
8719 * has at least one versioned path that is being modified and, if not NULL, is
8720 * in the arg->commit_paths list. Set arg and return GOT_ERR_FILE_MODIFIED as
8721 * soon as a path is passed with a status that satisfies this criteria.
8723 static const struct got_error *
8724 worktree_has_commitable_path(void *arg, unsigned char status,
8725 unsigned char staged_status, const char *path,
8726 struct got_object_id *blob_id, struct got_object_id *staged_blob_id,
8727 struct got_object_id *commit_id, int dirfd, const char *de_name)
8729 struct wt_commitable_path_arg *a = arg;
8731 if (status == staged_status && (status == GOT_STATUS_DELETE))
8732 status = GOT_STATUS_NO_CHANGE;
8734 if (!(status == GOT_STATUS_NO_CHANGE ||
8735 status == GOT_STATUS_UNVERSIONED) ||
8736 staged_status != GOT_STATUS_NO_CHANGE) {
8737 if (a->commit_paths != NULL) {
8738 struct got_pathlist_entry *pe;
8740 TAILQ_FOREACH(pe, a->commit_paths, entry) {
8741 if (strncmp(path, pe->path,
8742 pe->path_len) == 0) {
8743 *a->has_changes = 1;
8744 break;
8747 } else
8748 *a->has_changes = 1;
8750 if (*a->has_changes)
8751 return got_error(GOT_ERR_FILE_MODIFIED);
8754 return NULL;
8758 * Check that the changeset of the commit identified by id is
8759 * comprised of at least one modified path that is being committed.
8761 static const struct got_error *
8762 commit_path_changed_in_worktree(struct wt_commitable_path_arg *wcpa,
8763 struct got_object_id *id, struct got_worktree *worktree,
8764 struct got_repository *repo)
8766 const struct got_error *err;
8767 struct got_pathlist_head paths;
8768 struct got_commit_object *commit = NULL, *pcommit = NULL;
8769 struct got_tree_object *tree = NULL, *ptree = NULL;
8770 struct got_object_qid *pid;
8772 TAILQ_INIT(&paths);
8774 err = got_object_open_as_commit(&commit, repo, id);
8775 if (err)
8776 goto done;
8778 err = got_object_open_as_tree(&tree, repo,
8779 got_object_commit_get_tree_id(commit));
8780 if (err)
8781 goto done;
8783 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
8784 if (pid != NULL) {
8785 err = got_object_open_as_commit(&pcommit, repo, &pid->id);
8786 if (err)
8787 goto done;
8789 err = got_object_open_as_tree(&ptree, repo,
8790 got_object_commit_get_tree_id(pcommit));
8791 if (err)
8792 goto done;
8795 err = got_diff_tree(ptree, tree, NULL, NULL, -1, -1, "", "", repo,
8796 got_diff_tree_collect_changed_paths, &paths, 0);
8797 if (err)
8798 goto done;
8800 err = got_worktree_status(worktree, &paths, repo, 0,
8801 worktree_has_commitable_path, wcpa, check_cancelled, NULL);
8802 if (err && err->code == GOT_ERR_FILE_MODIFIED) {
8804 * At least one changed path in the referenced commit is
8805 * modified in the work tree, that's all we need to know!
8807 err = NULL;
8810 done:
8811 got_pathlist_free(&paths, GOT_PATHLIST_FREE_ALL);
8812 if (commit)
8813 got_object_commit_close(commit);
8814 if (pcommit)
8815 got_object_commit_close(pcommit);
8816 if (tree)
8817 got_object_tree_close(tree);
8818 if (ptree)
8819 got_object_tree_close(ptree);
8820 return err;
8824 * Remove any "logmsg" reference comprised entirely of paths that have
8825 * been reverted in this work tree. If any path in the logmsg ref changeset
8826 * remains in a changed state in the worktree, do not remove the reference.
8828 static const struct got_error *
8829 rm_logmsg_ref(struct got_worktree *worktree, struct got_repository *repo)
8831 const struct got_error *err;
8832 struct got_reflist_head refs;
8833 struct got_reflist_entry *re;
8834 struct got_commit_object *commit = NULL;
8835 struct got_object_id *commit_id = NULL;
8836 struct wt_commitable_path_arg wcpa;
8837 char *uuidstr = NULL;
8839 TAILQ_INIT(&refs);
8841 err = got_worktree_get_uuid(&uuidstr, worktree);
8842 if (err)
8843 goto done;
8845 err = got_ref_list(&refs, repo, "refs/got/worktree",
8846 got_ref_cmp_by_name, repo);
8847 if (err)
8848 goto done;
8850 TAILQ_FOREACH(re, &refs, entry) {
8851 const char *refname;
8852 int has_changes = 0;
8854 refname = got_ref_get_name(re->ref);
8856 if (!strncmp(refname, GOT_WORKTREE_CHERRYPICK_REF_PREFIX,
8857 GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN))
8858 refname += GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN + 1;
8859 else if (!strncmp(refname, GOT_WORKTREE_BACKOUT_REF_PREFIX,
8860 GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN))
8861 refname += GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN + 1;
8862 else
8863 continue;
8865 if (strncmp(refname, uuidstr, GOT_WORKTREE_UUID_STRLEN) == 0)
8866 refname += GOT_WORKTREE_UUID_STRLEN + 1; /* skip '-' */
8867 else
8868 continue;
8870 err = got_repo_match_object_id(&commit_id, NULL, refname,
8871 GOT_OBJ_TYPE_COMMIT, NULL, repo);
8872 if (err)
8873 goto done;
8875 err = got_object_open_as_commit(&commit, repo, commit_id);
8876 if (err)
8877 goto done;
8879 wcpa.commit_paths = NULL;
8880 wcpa.has_changes = &has_changes;
8882 err = commit_path_changed_in_worktree(&wcpa, commit_id,
8883 worktree, repo);
8884 if (err)
8885 goto done;
8887 if (!has_changes) {
8888 err = got_ref_delete(re->ref, repo);
8889 if (err)
8890 goto done;
8893 got_object_commit_close(commit);
8894 commit = NULL;
8895 free(commit_id);
8896 commit_id = NULL;
8899 done:
8900 free(uuidstr);
8901 free(commit_id);
8902 got_ref_list_free(&refs);
8903 if (commit)
8904 got_object_commit_close(commit);
8905 return err;
8908 static const struct got_error *
8909 cmd_revert(int argc, char *argv[])
8911 const struct got_error *error = NULL;
8912 struct got_worktree *worktree = NULL;
8913 struct got_repository *repo = NULL;
8914 char *cwd = NULL, *path = NULL;
8915 struct got_pathlist_head paths;
8916 int ch, contains_dir, can_recurse = 0, pflag = 0;
8917 FILE *patch_script_file = NULL;
8918 const char *patch_script_path = NULL;
8919 struct choose_patch_arg cpa;
8920 int *pack_fds = NULL;
8922 TAILQ_INIT(&paths);
8924 #ifndef PROFILE
8925 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
8926 "unveil", NULL) == -1)
8927 err(1, "pledge");
8928 #endif
8930 while ((ch = getopt(argc, argv, "F:pR")) != -1) {
8931 switch (ch) {
8932 case 'F':
8933 patch_script_path = optarg;
8934 break;
8935 case 'p':
8936 pflag = 1;
8937 break;
8938 case 'R':
8939 can_recurse = 1;
8940 break;
8941 default:
8942 usage_revert();
8943 /* NOTREACHED */
8947 argc -= optind;
8948 argv += optind;
8950 if (argc < 1)
8951 usage_revert();
8952 if (patch_script_path && !pflag)
8953 errx(1, "-F option can only be used together with -p option");
8955 cwd = getcwd(NULL, 0);
8956 if (cwd == NULL) {
8957 error = got_error_from_errno("getcwd");
8958 goto done;
8961 error = got_repo_pack_fds_open(&pack_fds);
8962 if (error != NULL)
8963 goto done;
8965 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
8966 if (error) {
8967 if (error->code == GOT_ERR_NOT_WORKTREE)
8968 error = wrap_not_worktree_error(error, "revert", cwd);
8969 goto done;
8972 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
8973 NULL, pack_fds);
8974 if (error != NULL)
8975 goto done;
8977 if (patch_script_path) {
8978 patch_script_file = fopen(patch_script_path, "re");
8979 if (patch_script_file == NULL) {
8980 error = got_error_from_errno2("fopen",
8981 patch_script_path);
8982 goto done;
8987 * XXX "c" perm needed on repo dir to delete merge references.
8989 error = apply_unveil(got_repo_get_path(repo), 0,
8990 got_worktree_get_root_path(worktree));
8991 if (error)
8992 goto done;
8994 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
8995 if (error)
8996 goto done;
8998 if (!can_recurse) {
8999 error = check_paths_contains_dir(&contains_dir, worktree, &paths);
9000 if (error != NULL)
9001 goto done;
9003 if (contains_dir) {
9004 error = got_error_msg(GOT_ERR_BAD_PATH,
9005 "reverting directories requires -R option");
9006 goto done;
9010 cpa.patch_script_file = patch_script_file;
9011 cpa.action = "revert";
9012 error = got_worktree_revert(worktree, &paths, revert_progress, NULL,
9013 pflag ? choose_patch : NULL, &cpa, repo);
9015 error = rm_logmsg_ref(worktree, repo);
9016 done:
9017 if (patch_script_file && fclose(patch_script_file) == EOF &&
9018 error == NULL)
9019 error = got_error_from_errno2("fclose", patch_script_path);
9020 if (repo) {
9021 const struct got_error *close_err = got_repo_close(repo);
9022 if (error == NULL)
9023 error = close_err;
9025 if (worktree)
9026 got_worktree_close(worktree);
9027 if (pack_fds) {
9028 const struct got_error *pack_err =
9029 got_repo_pack_fds_close(pack_fds);
9030 if (error == NULL)
9031 error = pack_err;
9033 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
9034 free(path);
9035 free(cwd);
9036 return error;
9039 __dead static void
9040 usage_commit(void)
9042 fprintf(stderr, "usage: %s commit [-CNnS] [-A author] [-F path] "
9043 "[-m message] [path ...]\n", getprogname());
9044 exit(1);
9047 struct collect_commit_logmsg_arg {
9048 const char *cmdline_log;
9049 const char *prepared_log;
9050 const char *merged_log;
9051 int non_interactive;
9052 const char *editor;
9053 const char *worktree_path;
9054 const char *branch_name;
9055 const char *repo_path;
9056 char *logmsg_path;
9060 static const struct got_error *
9061 read_prepared_logmsg(char **logmsg, const char *path)
9063 const struct got_error *err = NULL;
9064 FILE *f = NULL;
9065 struct stat sb;
9066 size_t r;
9068 *logmsg = NULL;
9069 memset(&sb, 0, sizeof(sb));
9071 f = fopen(path, "re");
9072 if (f == NULL)
9073 return got_error_from_errno2("fopen", path);
9075 if (fstat(fileno(f), &sb) == -1) {
9076 err = got_error_from_errno2("fstat", path);
9077 goto done;
9079 if (sb.st_size == 0) {
9080 err = got_error(GOT_ERR_COMMIT_MSG_EMPTY);
9081 goto done;
9084 *logmsg = malloc(sb.st_size + 1);
9085 if (*logmsg == NULL) {
9086 err = got_error_from_errno("malloc");
9087 goto done;
9090 r = fread(*logmsg, 1, sb.st_size, f);
9091 if (r != sb.st_size) {
9092 if (ferror(f))
9093 err = got_error_from_errno2("fread", path);
9094 else
9095 err = got_error(GOT_ERR_IO);
9096 goto done;
9098 (*logmsg)[sb.st_size] = '\0';
9099 done:
9100 if (fclose(f) == EOF && err == NULL)
9101 err = got_error_from_errno2("fclose", path);
9102 if (err) {
9103 free(*logmsg);
9104 *logmsg = NULL;
9106 return err;
9109 static const struct got_error *
9110 collect_commit_logmsg(struct got_pathlist_head *commitable_paths,
9111 const char *diff_path, char **logmsg, void *arg)
9113 char *initial_content = NULL;
9114 struct got_pathlist_entry *pe;
9115 const struct got_error *err = NULL;
9116 char *template = NULL;
9117 char *prepared_msg = NULL, *merged_msg = NULL;
9118 struct collect_commit_logmsg_arg *a = arg;
9119 int initial_content_len;
9120 int fd = -1;
9121 size_t len;
9123 /* if a message was specified on the command line, just use it */
9124 if (a->cmdline_log != NULL && *a->cmdline_log != '\0') {
9125 len = strlen(a->cmdline_log) + 1;
9126 *logmsg = malloc(len + 1);
9127 if (*logmsg == NULL)
9128 return got_error_from_errno("malloc");
9129 strlcpy(*logmsg, a->cmdline_log, len);
9130 return NULL;
9131 } else if (a->prepared_log != NULL && a->non_interactive)
9132 return read_prepared_logmsg(logmsg, a->prepared_log);
9134 if (asprintf(&template, "%s/logmsg", a->worktree_path) == -1)
9135 return got_error_from_errno("asprintf");
9137 err = got_opentemp_named_fd(&a->logmsg_path, &fd, template, "");
9138 if (err)
9139 goto done;
9141 if (a->prepared_log) {
9142 err = read_prepared_logmsg(&prepared_msg, a->prepared_log);
9143 if (err)
9144 goto done;
9145 } else if (a->merged_log) {
9146 err = read_prepared_logmsg(&merged_msg, a->merged_log);
9147 if (err)
9148 goto done;
9151 initial_content_len = asprintf(&initial_content,
9152 "%s%s\n# changes to be committed on branch %s:\n",
9153 prepared_msg ? prepared_msg : "",
9154 merged_msg ? merged_msg : "", a->branch_name);
9155 if (initial_content_len == -1) {
9156 err = got_error_from_errno("asprintf");
9157 goto done;
9160 if (write(fd, initial_content, initial_content_len) == -1) {
9161 err = got_error_from_errno2("write", a->logmsg_path);
9162 goto done;
9165 TAILQ_FOREACH(pe, commitable_paths, entry) {
9166 struct got_commitable *ct = pe->data;
9167 dprintf(fd, "# %c %s\n",
9168 got_commitable_get_status(ct),
9169 got_commitable_get_path(ct));
9172 if (diff_path) {
9173 dprintf(fd, "# detailed changes can be viewed in %s\n",
9174 diff_path);
9177 if (close(fd) == -1) {
9178 err = got_error_from_errno2("close", a->logmsg_path);
9179 goto done;
9181 fd = -1;
9183 err = edit_logmsg(logmsg, a->editor, a->logmsg_path, initial_content,
9184 initial_content_len, a->prepared_log ? 0 : 1);
9185 done:
9186 free(initial_content);
9187 free(template);
9188 free(prepared_msg);
9189 free(merged_msg);
9191 if (fd != -1 && close(fd) == -1 && err == NULL)
9192 err = got_error_from_errno2("close", a->logmsg_path);
9193 if (err) {
9194 free(*logmsg);
9195 *logmsg = NULL;
9197 return err;
9200 static const struct got_error *
9201 cat_logmsg(FILE *f, struct got_commit_object *commit, const char *idstr,
9202 const char *type, int has_content)
9204 const struct got_error *err = NULL;
9205 char *logmsg = NULL;
9207 err = got_object_commit_get_logmsg(&logmsg, commit);
9208 if (err)
9209 return err;
9211 if (fprintf(f, "%s# log message of %s commit %s:%s",
9212 has_content ? "\n" : "", type, idstr, logmsg) < 0)
9213 err = got_ferror(f, GOT_ERR_IO);
9215 free(logmsg);
9216 return err;
9220 * Lookup "logmsg" references of backed-out and cherrypicked commits
9221 * belonging to the current work tree. If found, and the worktree has
9222 * at least one modified file that was changed in the referenced commit,
9223 * add its log message to a new temporary file at *logmsg_path.
9224 * Add all refs found to matched_refs to be scheduled for removal on
9225 * successful commit.
9227 static const struct got_error *
9228 lookup_logmsg_ref(char **logmsg_path, struct got_pathlist_head *paths,
9229 struct got_reflist_head *matched_refs, struct got_worktree *worktree,
9230 struct got_repository *repo)
9232 const struct got_error *err;
9233 struct got_commit_object *commit = NULL;
9234 struct got_object_id *id = NULL;
9235 struct got_reflist_head refs;
9236 struct got_reflist_entry *re, *re_match;
9237 FILE *f = NULL;
9238 char *uuidstr = NULL;
9239 int added_logmsg = 0;
9241 TAILQ_INIT(&refs);
9243 *logmsg_path = NULL;
9245 err = got_worktree_get_uuid(&uuidstr, worktree);
9246 if (err)
9247 goto done;
9249 err = got_ref_list(&refs, repo, "refs/got/worktree",
9250 got_ref_cmp_by_name, repo);
9251 if (err)
9252 goto done;
9254 TAILQ_FOREACH(re, &refs, entry) {
9255 const char *refname, *type;
9256 struct wt_commitable_path_arg wcpa;
9257 int add_logmsg = 0;
9259 refname = got_ref_get_name(re->ref);
9261 if (strncmp(refname, GOT_WORKTREE_CHERRYPICK_REF_PREFIX,
9262 GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN) == 0) {
9263 refname += GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN + 1;
9264 type = "cherrypicked";
9265 } else if (strncmp(refname, GOT_WORKTREE_BACKOUT_REF_PREFIX,
9266 GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN) == 0) {
9267 refname += GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN + 1;
9268 type = "backed-out";
9269 } else
9270 continue;
9272 if (strncmp(refname, uuidstr, GOT_WORKTREE_UUID_STRLEN) == 0)
9273 refname += GOT_WORKTREE_UUID_STRLEN + 1; /* skip '-' */
9274 else
9275 continue;
9277 err = got_repo_match_object_id(&id, NULL, refname,
9278 GOT_OBJ_TYPE_COMMIT, NULL, repo);
9279 if (err)
9280 goto done;
9282 err = got_object_open_as_commit(&commit, repo, id);
9283 if (err)
9284 goto done;
9286 wcpa.commit_paths = paths;
9287 wcpa.has_changes = &add_logmsg;
9289 err = commit_path_changed_in_worktree(&wcpa, id,
9290 worktree, repo);
9291 if (err)
9292 goto done;
9294 if (add_logmsg) {
9295 if (f == NULL) {
9296 err = got_opentemp_named(logmsg_path, &f,
9297 "got-commit-logmsg", "");
9298 if (err)
9299 goto done;
9301 err = cat_logmsg(f, commit, refname, type,
9302 added_logmsg);
9303 if (err)
9304 goto done;
9305 if (!added_logmsg)
9306 ++added_logmsg;
9308 err = got_reflist_entry_dup(&re_match, re);
9309 if (err)
9310 goto done;
9311 TAILQ_INSERT_HEAD(matched_refs, re_match, entry);
9314 got_object_commit_close(commit);
9315 commit = NULL;
9316 free(id);
9317 id = NULL;
9320 done:
9321 free(id);
9322 free(uuidstr);
9323 got_ref_list_free(&refs);
9324 if (commit)
9325 got_object_commit_close(commit);
9326 if (f && fclose(f) == EOF && err == NULL)
9327 err = got_error_from_errno("fclose");
9328 if (!added_logmsg) {
9329 if (*logmsg_path && unlink(*logmsg_path) != 0 && err == NULL)
9330 err = got_error_from_errno2("unlink", *logmsg_path);
9331 *logmsg_path = NULL;
9333 return err;
9336 static const struct got_error *
9337 cmd_commit(int argc, char *argv[])
9339 const struct got_error *error = NULL;
9340 struct got_worktree *worktree = NULL;
9341 struct got_repository *repo = NULL;
9342 char *cwd = NULL, *id_str = NULL;
9343 struct got_object_id *id = NULL;
9344 const char *logmsg = NULL;
9345 char *prepared_logmsg = NULL, *merged_logmsg = NULL;
9346 struct collect_commit_logmsg_arg cl_arg;
9347 const char *author = NULL;
9348 char *gitconfig_path = NULL, *editor = NULL, *committer = NULL;
9349 int ch, rebase_in_progress, histedit_in_progress, preserve_logmsg = 0;
9350 int allow_bad_symlinks = 0, non_interactive = 0, merge_in_progress = 0;
9351 int show_diff = 1, commit_conflicts = 0;
9352 struct got_pathlist_head paths;
9353 struct got_reflist_head refs;
9354 struct got_reflist_entry *re;
9355 int *pack_fds = NULL;
9357 TAILQ_INIT(&refs);
9358 TAILQ_INIT(&paths);
9359 cl_arg.logmsg_path = NULL;
9361 #ifndef PROFILE
9362 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
9363 "unveil", NULL) == -1)
9364 err(1, "pledge");
9365 #endif
9367 while ((ch = getopt(argc, argv, "A:CF:m:NnS")) != -1) {
9368 switch (ch) {
9369 case 'A':
9370 author = optarg;
9371 error = valid_author(author);
9372 if (error)
9373 return error;
9374 break;
9375 case 'C':
9376 commit_conflicts = 1;
9377 break;
9378 case 'F':
9379 if (logmsg != NULL)
9380 option_conflict('F', 'm');
9381 prepared_logmsg = realpath(optarg, NULL);
9382 if (prepared_logmsg == NULL)
9383 return got_error_from_errno2("realpath",
9384 optarg);
9385 break;
9386 case 'm':
9387 if (prepared_logmsg)
9388 option_conflict('m', 'F');
9389 logmsg = optarg;
9390 break;
9391 case 'N':
9392 non_interactive = 1;
9393 break;
9394 case 'n':
9395 show_diff = 0;
9396 break;
9397 case 'S':
9398 allow_bad_symlinks = 1;
9399 break;
9400 default:
9401 usage_commit();
9402 /* NOTREACHED */
9406 argc -= optind;
9407 argv += optind;
9409 cwd = getcwd(NULL, 0);
9410 if (cwd == NULL) {
9411 error = got_error_from_errno("getcwd");
9412 goto done;
9415 error = got_repo_pack_fds_open(&pack_fds);
9416 if (error != NULL)
9417 goto done;
9419 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
9420 if (error) {
9421 if (error->code == GOT_ERR_NOT_WORKTREE)
9422 error = wrap_not_worktree_error(error, "commit", cwd);
9423 goto done;
9426 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
9427 if (error)
9428 goto done;
9429 if (rebase_in_progress) {
9430 error = got_error(GOT_ERR_REBASING);
9431 goto done;
9434 error = got_worktree_histedit_in_progress(&histedit_in_progress,
9435 worktree);
9436 if (error)
9437 goto done;
9439 error = get_gitconfig_path(&gitconfig_path);
9440 if (error)
9441 goto done;
9442 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
9443 gitconfig_path, pack_fds);
9444 if (error != NULL)
9445 goto done;
9447 error = got_worktree_merge_in_progress(&merge_in_progress, worktree, repo);
9448 if (error)
9449 goto done;
9450 if (merge_in_progress) {
9451 error = got_error(GOT_ERR_MERGE_BUSY);
9452 goto done;
9455 error = get_author(&committer, repo, worktree);
9456 if (error)
9457 goto done;
9459 if (author == NULL)
9460 author = committer;
9462 if (logmsg == NULL || strlen(logmsg) == 0) {
9463 error = get_editor(&editor);
9464 if (error)
9465 goto done;
9466 if (unveil(editor, "x") != 0) {
9467 error = got_error_from_errno2("unveil", editor);
9468 goto done;
9471 if (prepared_logmsg) {
9472 if (unveil(prepared_logmsg, "r") != 0) {
9473 error = got_error_from_errno2("unveil",
9474 prepared_logmsg);
9475 goto done;
9479 error = apply_unveil(got_repo_get_path(repo), 0,
9480 got_worktree_get_root_path(worktree));
9481 if (error)
9482 goto done;
9484 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
9485 if (error)
9486 goto done;
9488 if (prepared_logmsg == NULL) {
9489 error = lookup_logmsg_ref(&merged_logmsg,
9490 argc > 0 ? &paths : NULL, &refs, worktree, repo);
9491 if (error)
9492 goto done;
9495 cl_arg.editor = editor;
9496 cl_arg.cmdline_log = logmsg;
9497 cl_arg.prepared_log = prepared_logmsg;
9498 cl_arg.merged_log = merged_logmsg;
9499 cl_arg.non_interactive = non_interactive;
9500 cl_arg.worktree_path = got_worktree_get_root_path(worktree);
9501 cl_arg.branch_name = got_worktree_get_head_ref_name(worktree);
9502 if (!histedit_in_progress) {
9503 if (strncmp(cl_arg.branch_name, "refs/heads/", 11) != 0) {
9504 error = got_error(GOT_ERR_COMMIT_BRANCH);
9505 goto done;
9507 cl_arg.branch_name += 11;
9509 cl_arg.repo_path = got_repo_get_path(repo);
9510 error = got_worktree_commit(&id, worktree, &paths, author, committer,
9511 allow_bad_symlinks, show_diff, commit_conflicts,
9512 collect_commit_logmsg, &cl_arg, print_status, NULL, repo);
9513 if (error) {
9514 if (error->code != GOT_ERR_COMMIT_MSG_EMPTY &&
9515 cl_arg.logmsg_path != NULL)
9516 preserve_logmsg = 1;
9517 goto done;
9520 error = got_object_id_str(&id_str, id);
9521 if (error)
9522 goto done;
9523 printf("Created commit %s\n", id_str);
9525 TAILQ_FOREACH(re, &refs, entry) {
9526 error = got_ref_delete(re->ref, repo);
9527 if (error)
9528 goto done;
9531 done:
9532 if (preserve_logmsg) {
9533 fprintf(stderr, "%s: log message preserved in %s\n",
9534 getprogname(), cl_arg.logmsg_path);
9535 } else if (cl_arg.logmsg_path && unlink(cl_arg.logmsg_path) == -1 &&
9536 error == NULL)
9537 error = got_error_from_errno2("unlink", cl_arg.logmsg_path);
9538 free(cl_arg.logmsg_path);
9539 if (merged_logmsg && unlink(merged_logmsg) == -1 && error == NULL)
9540 error = got_error_from_errno2("unlink", merged_logmsg);
9541 free(merged_logmsg);
9542 if (repo) {
9543 const struct got_error *close_err = got_repo_close(repo);
9544 if (error == NULL)
9545 error = close_err;
9547 if (worktree)
9548 got_worktree_close(worktree);
9549 if (pack_fds) {
9550 const struct got_error *pack_err =
9551 got_repo_pack_fds_close(pack_fds);
9552 if (error == NULL)
9553 error = pack_err;
9555 got_ref_list_free(&refs);
9556 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
9557 free(cwd);
9558 free(id_str);
9559 free(gitconfig_path);
9560 free(editor);
9561 free(committer);
9562 free(prepared_logmsg);
9563 return error;
9566 __dead static void
9567 usage_send(void)
9569 fprintf(stderr, "usage: %s send [-afqTv] [-b branch] [-d branch] "
9570 "[-r repository-path] [-t tag] [remote-repository]\n",
9571 getprogname());
9572 exit(1);
9575 static void
9576 print_load_info(int print_colored, int print_found, int print_trees,
9577 int ncolored, int nfound, int ntrees)
9579 if (print_colored) {
9580 printf("%d commit%s colored", ncolored,
9581 ncolored == 1 ? "" : "s");
9583 if (print_found) {
9584 printf("%s%d object%s found",
9585 ncolored > 0 ? "; " : "",
9586 nfound, nfound == 1 ? "" : "s");
9588 if (print_trees) {
9589 printf("; %d tree%s scanned", ntrees,
9590 ntrees == 1 ? "" : "s");
9594 struct got_send_progress_arg {
9595 char last_scaled_packsize[FMT_SCALED_STRSIZE];
9596 int verbosity;
9597 int last_ncolored;
9598 int last_nfound;
9599 int last_ntrees;
9600 int loading_done;
9601 int last_ncommits;
9602 int last_nobj_total;
9603 int last_p_deltify;
9604 int last_p_written;
9605 int last_p_sent;
9606 int printed_something;
9607 int sent_something;
9608 struct got_pathlist_head *delete_branches;
9611 static const struct got_error *
9612 send_progress(void *arg, int ncolored, int nfound, int ntrees,
9613 off_t packfile_size, int ncommits, int nobj_total, int nobj_deltify,
9614 int nobj_written, off_t bytes_sent, const char *refname,
9615 const char *errmsg, int success)
9617 struct got_send_progress_arg *a = arg;
9618 char scaled_packsize[FMT_SCALED_STRSIZE];
9619 char scaled_sent[FMT_SCALED_STRSIZE];
9620 int p_deltify = 0, p_written = 0, p_sent = 0;
9621 int print_colored = 0, print_found = 0, print_trees = 0;
9622 int print_searching = 0, print_total = 0;
9623 int print_deltify = 0, print_written = 0, print_sent = 0;
9625 if (a->verbosity < 0)
9626 return NULL;
9628 if (refname) {
9629 const char *status = success ? "accepted" : "rejected";
9631 if (success) {
9632 struct got_pathlist_entry *pe;
9633 TAILQ_FOREACH(pe, a->delete_branches, entry) {
9634 const char *branchname = pe->path;
9635 if (got_path_cmp(branchname, refname,
9636 strlen(branchname), strlen(refname)) == 0) {
9637 status = "deleted";
9638 a->sent_something = 1;
9639 break;
9644 if (a->printed_something)
9645 putchar('\n');
9646 printf("Server has %s %s", status, refname);
9647 if (errmsg)
9648 printf(": %s", errmsg);
9649 a->printed_something = 1;
9650 return NULL;
9653 if (a->last_ncolored != ncolored) {
9654 print_colored = 1;
9655 a->last_ncolored = ncolored;
9658 if (a->last_nfound != nfound) {
9659 print_colored = 1;
9660 print_found = 1;
9661 a->last_nfound = nfound;
9664 if (a->last_ntrees != ntrees) {
9665 print_colored = 1;
9666 print_found = 1;
9667 print_trees = 1;
9668 a->last_ntrees = ntrees;
9671 if ((print_colored || print_found || print_trees) &&
9672 !a->loading_done) {
9673 printf("\r");
9674 print_load_info(print_colored, print_found, print_trees,
9675 ncolored, nfound, ntrees);
9676 a->printed_something = 1;
9677 fflush(stdout);
9678 return NULL;
9679 } else if (!a->loading_done) {
9680 printf("\r");
9681 print_load_info(1, 1, 1, ncolored, nfound, ntrees);
9682 printf("\n");
9683 a->loading_done = 1;
9686 if (fmt_scaled(packfile_size, scaled_packsize) == -1)
9687 return got_error_from_errno("fmt_scaled");
9688 if (fmt_scaled(bytes_sent, scaled_sent) == -1)
9689 return got_error_from_errno("fmt_scaled");
9691 if (a->last_ncommits != ncommits) {
9692 print_searching = 1;
9693 a->last_ncommits = ncommits;
9696 if (a->last_nobj_total != nobj_total) {
9697 print_searching = 1;
9698 print_total = 1;
9699 a->last_nobj_total = nobj_total;
9702 if (packfile_size > 0 && (a->last_scaled_packsize[0] == '\0' ||
9703 strcmp(scaled_packsize, a->last_scaled_packsize)) != 0) {
9704 if (strlcpy(a->last_scaled_packsize, scaled_packsize,
9705 FMT_SCALED_STRSIZE) >= FMT_SCALED_STRSIZE)
9706 return got_error(GOT_ERR_NO_SPACE);
9709 if (nobj_deltify > 0 || nobj_written > 0) {
9710 if (nobj_deltify > 0) {
9711 p_deltify = (nobj_deltify * 100) / nobj_total;
9712 if (p_deltify != a->last_p_deltify) {
9713 a->last_p_deltify = p_deltify;
9714 print_searching = 1;
9715 print_total = 1;
9716 print_deltify = 1;
9719 if (nobj_written > 0) {
9720 p_written = (nobj_written * 100) / nobj_total;
9721 if (p_written != a->last_p_written) {
9722 a->last_p_written = p_written;
9723 print_searching = 1;
9724 print_total = 1;
9725 print_deltify = 1;
9726 print_written = 1;
9731 if (bytes_sent > 0) {
9732 p_sent = (bytes_sent * 100) / packfile_size;
9733 if (p_sent != a->last_p_sent) {
9734 a->last_p_sent = p_sent;
9735 print_searching = 1;
9736 print_total = 1;
9737 print_deltify = 1;
9738 print_written = 1;
9739 print_sent = 1;
9741 a->sent_something = 1;
9744 if (print_searching || print_total || print_deltify || print_written ||
9745 print_sent)
9746 printf("\r");
9747 if (print_searching)
9748 printf("packing %d reference%s", ncommits,
9749 ncommits == 1 ? "" : "s");
9750 if (print_total)
9751 printf("; %d object%s", nobj_total,
9752 nobj_total == 1 ? "" : "s");
9753 if (print_deltify)
9754 printf("; deltify: %d%%", p_deltify);
9755 if (print_sent)
9756 printf("; uploading pack: %*s %d%%", FMT_SCALED_STRSIZE - 2,
9757 scaled_packsize, p_sent);
9758 else if (print_written)
9759 printf("; writing pack: %*s %d%%", FMT_SCALED_STRSIZE - 2,
9760 scaled_packsize, p_written);
9761 if (print_searching || print_total || print_deltify ||
9762 print_written || print_sent) {
9763 a->printed_something = 1;
9764 fflush(stdout);
9766 return NULL;
9769 static const struct got_error *
9770 cmd_send(int argc, char *argv[])
9772 const struct got_error *error = NULL;
9773 char *cwd = NULL, *repo_path = NULL;
9774 const char *remote_name;
9775 char *proto = NULL, *host = NULL, *port = NULL;
9776 char *repo_name = NULL, *server_path = NULL;
9777 const struct got_remote_repo *remotes;
9778 struct got_remote_repo *remote = NULL;
9779 int nremotes, nbranches = 0, ndelete_branches = 0;
9780 struct got_repository *repo = NULL;
9781 struct got_worktree *worktree = NULL;
9782 const struct got_gotconfig *repo_conf = NULL, *worktree_conf = NULL;
9783 struct got_pathlist_head branches;
9784 struct got_pathlist_head tags;
9785 struct got_reflist_head all_branches;
9786 struct got_reflist_head all_tags;
9787 struct got_pathlist_head delete_args;
9788 struct got_pathlist_head delete_branches;
9789 struct got_reflist_entry *re;
9790 struct got_pathlist_entry *pe;
9791 int i, ch, sendfd = -1, sendstatus;
9792 pid_t sendpid = -1;
9793 struct got_send_progress_arg spa;
9794 int verbosity = 0, overwrite_refs = 0;
9795 int send_all_branches = 0, send_all_tags = 0;
9796 struct got_reference *ref = NULL;
9797 int *pack_fds = NULL;
9799 TAILQ_INIT(&branches);
9800 TAILQ_INIT(&tags);
9801 TAILQ_INIT(&all_branches);
9802 TAILQ_INIT(&all_tags);
9803 TAILQ_INIT(&delete_args);
9804 TAILQ_INIT(&delete_branches);
9806 while ((ch = getopt(argc, argv, "ab:d:fqr:Tt:v")) != -1) {
9807 switch (ch) {
9808 case 'a':
9809 send_all_branches = 1;
9810 break;
9811 case 'b':
9812 error = got_pathlist_append(&branches, optarg, NULL);
9813 if (error)
9814 return error;
9815 nbranches++;
9816 break;
9817 case 'd':
9818 error = got_pathlist_append(&delete_args, optarg, NULL);
9819 if (error)
9820 return error;
9821 break;
9822 case 'f':
9823 overwrite_refs = 1;
9824 break;
9825 case 'q':
9826 verbosity = -1;
9827 break;
9828 case 'r':
9829 repo_path = realpath(optarg, NULL);
9830 if (repo_path == NULL)
9831 return got_error_from_errno2("realpath",
9832 optarg);
9833 got_path_strip_trailing_slashes(repo_path);
9834 break;
9835 case 'T':
9836 send_all_tags = 1;
9837 break;
9838 case 't':
9839 error = got_pathlist_append(&tags, optarg, NULL);
9840 if (error)
9841 return error;
9842 break;
9843 case 'v':
9844 if (verbosity < 0)
9845 verbosity = 0;
9846 else if (verbosity < 3)
9847 verbosity++;
9848 break;
9849 default:
9850 usage_send();
9851 /* NOTREACHED */
9854 argc -= optind;
9855 argv += optind;
9857 if (send_all_branches && !TAILQ_EMPTY(&branches))
9858 option_conflict('a', 'b');
9859 if (send_all_tags && !TAILQ_EMPTY(&tags))
9860 option_conflict('T', 't');
9863 if (argc == 0)
9864 remote_name = GOT_SEND_DEFAULT_REMOTE_NAME;
9865 else if (argc == 1)
9866 remote_name = argv[0];
9867 else
9868 usage_send();
9870 cwd = getcwd(NULL, 0);
9871 if (cwd == NULL) {
9872 error = got_error_from_errno("getcwd");
9873 goto done;
9876 error = got_repo_pack_fds_open(&pack_fds);
9877 if (error != NULL)
9878 goto done;
9880 if (repo_path == NULL) {
9881 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
9882 if (error && error->code != GOT_ERR_NOT_WORKTREE)
9883 goto done;
9884 else
9885 error = NULL;
9886 if (worktree) {
9887 repo_path =
9888 strdup(got_worktree_get_repo_path(worktree));
9889 if (repo_path == NULL)
9890 error = got_error_from_errno("strdup");
9891 if (error)
9892 goto done;
9893 } else {
9894 repo_path = strdup(cwd);
9895 if (repo_path == NULL) {
9896 error = got_error_from_errno("strdup");
9897 goto done;
9902 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
9903 if (error)
9904 goto done;
9906 if (worktree) {
9907 worktree_conf = got_worktree_get_gotconfig(worktree);
9908 if (worktree_conf) {
9909 got_gotconfig_get_remotes(&nremotes, &remotes,
9910 worktree_conf);
9911 for (i = 0; i < nremotes; i++) {
9912 if (strcmp(remotes[i].name, remote_name) == 0) {
9913 error = got_repo_remote_repo_dup(&remote,
9914 &remotes[i]);
9915 if (error)
9916 goto done;
9917 break;
9922 if (remote == NULL) {
9923 repo_conf = got_repo_get_gotconfig(repo);
9924 if (repo_conf) {
9925 got_gotconfig_get_remotes(&nremotes, &remotes,
9926 repo_conf);
9927 for (i = 0; i < nremotes; i++) {
9928 if (strcmp(remotes[i].name, remote_name) == 0) {
9929 error = got_repo_remote_repo_dup(&remote,
9930 &remotes[i]);
9931 if (error)
9932 goto done;
9933 break;
9938 if (remote == NULL) {
9939 got_repo_get_gitconfig_remotes(&nremotes, &remotes, repo);
9940 for (i = 0; i < nremotes; i++) {
9941 if (strcmp(remotes[i].name, remote_name) == 0) {
9942 error = got_repo_remote_repo_dup(&remote,
9943 &remotes[i]);
9944 if (error)
9945 goto done;
9946 break;
9950 if (remote == NULL) {
9951 error = got_error_path(remote_name, GOT_ERR_NO_REMOTE);
9952 goto done;
9955 error = got_dial_parse_uri(&proto, &host, &port, &server_path,
9956 &repo_name, remote->send_url);
9957 if (error)
9958 goto done;
9960 if (strcmp(proto, "git") == 0) {
9961 #ifndef PROFILE
9962 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
9963 "sendfd dns inet unveil", NULL) == -1)
9964 err(1, "pledge");
9965 #endif
9966 } else if (strcmp(proto, "git+ssh") == 0 ||
9967 strcmp(proto, "ssh") == 0) {
9968 #ifndef PROFILE
9969 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
9970 "sendfd unveil", NULL) == -1)
9971 err(1, "pledge");
9972 #endif
9973 } else if (strcmp(proto, "http") == 0 ||
9974 strcmp(proto, "git+http") == 0) {
9975 error = got_error_path(proto, GOT_ERR_NOT_IMPL);
9976 goto done;
9977 } else {
9978 error = got_error_path(proto, GOT_ERR_BAD_PROTO);
9979 goto done;
9982 error = got_dial_apply_unveil(proto);
9983 if (error)
9984 goto done;
9986 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
9987 if (error)
9988 goto done;
9990 if (send_all_branches) {
9991 error = got_ref_list(&all_branches, repo, "refs/heads",
9992 got_ref_cmp_by_name, NULL);
9993 if (error)
9994 goto done;
9995 TAILQ_FOREACH(re, &all_branches, entry) {
9996 const char *branchname = got_ref_get_name(re->ref);
9997 error = got_pathlist_append(&branches,
9998 branchname, NULL);
9999 if (error)
10000 goto done;
10001 nbranches++;
10003 } else if (nbranches == 0) {
10004 for (i = 0; i < remote->nsend_branches; i++) {
10005 error = got_pathlist_append(&branches,
10006 remote->send_branches[i], NULL);
10007 if (error)
10008 goto done;
10012 if (send_all_tags) {
10013 error = got_ref_list(&all_tags, repo, "refs/tags",
10014 got_ref_cmp_by_name, NULL);
10015 if (error)
10016 goto done;
10017 TAILQ_FOREACH(re, &all_tags, entry) {
10018 const char *tagname = got_ref_get_name(re->ref);
10019 error = got_pathlist_append(&tags,
10020 tagname, NULL);
10021 if (error)
10022 goto done;
10027 * To prevent accidents only branches in refs/heads/ can be deleted
10028 * with 'got send -d'.
10029 * Deleting anything else requires local repository access or Git.
10031 TAILQ_FOREACH(pe, &delete_args, entry) {
10032 const char *branchname = pe->path;
10033 char *s;
10034 struct got_pathlist_entry *new;
10035 if (strncmp(branchname, "refs/heads/", 11) == 0) {
10036 s = strdup(branchname);
10037 if (s == NULL) {
10038 error = got_error_from_errno("strdup");
10039 goto done;
10041 } else {
10042 if (asprintf(&s, "refs/heads/%s", branchname) == -1) {
10043 error = got_error_from_errno("asprintf");
10044 goto done;
10047 error = got_pathlist_insert(&new, &delete_branches, s, NULL);
10048 if (error || new == NULL /* duplicate */)
10049 free(s);
10050 if (error)
10051 goto done;
10052 ndelete_branches++;
10055 if (nbranches == 0 && ndelete_branches == 0) {
10056 struct got_reference *head_ref;
10057 if (worktree)
10058 error = got_ref_open(&head_ref, repo,
10059 got_worktree_get_head_ref_name(worktree), 0);
10060 else
10061 error = got_ref_open(&head_ref, repo, GOT_REF_HEAD, 0);
10062 if (error)
10063 goto done;
10064 if (got_ref_is_symbolic(head_ref)) {
10065 error = got_ref_resolve_symbolic(&ref, repo, head_ref);
10066 got_ref_close(head_ref);
10067 if (error)
10068 goto done;
10069 } else
10070 ref = head_ref;
10071 error = got_pathlist_append(&branches, got_ref_get_name(ref),
10072 NULL);
10073 if (error)
10074 goto done;
10075 nbranches++;
10078 if (worktree) {
10079 /* Release work tree lock. */
10080 got_worktree_close(worktree);
10081 worktree = NULL;
10084 if (verbosity >= 0) {
10085 printf("Connecting to \"%s\" %s://%s%s%s%s%s\n",
10086 remote->name, proto, host,
10087 port ? ":" : "", port ? port : "",
10088 *server_path == '/' ? "" : "/", server_path);
10091 error = got_send_connect(&sendpid, &sendfd, proto, host, port,
10092 server_path, verbosity);
10093 if (error)
10094 goto done;
10096 memset(&spa, 0, sizeof(spa));
10097 spa.last_scaled_packsize[0] = '\0';
10098 spa.last_p_deltify = -1;
10099 spa.last_p_written = -1;
10100 spa.verbosity = verbosity;
10101 spa.delete_branches = &delete_branches;
10102 error = got_send_pack(remote_name, &branches, &tags, &delete_branches,
10103 verbosity, overwrite_refs, sendfd, repo, send_progress, &spa,
10104 check_cancelled, NULL);
10105 if (spa.printed_something)
10106 putchar('\n');
10107 if (error)
10108 goto done;
10109 if (!spa.sent_something && verbosity >= 0)
10110 printf("Already up-to-date\n");
10111 done:
10112 if (sendpid > 0) {
10113 if (kill(sendpid, SIGTERM) == -1)
10114 error = got_error_from_errno("kill");
10115 if (waitpid(sendpid, &sendstatus, 0) == -1 && error == NULL)
10116 error = got_error_from_errno("waitpid");
10118 if (sendfd != -1 && close(sendfd) == -1 && error == NULL)
10119 error = got_error_from_errno("close");
10120 if (repo) {
10121 const struct got_error *close_err = got_repo_close(repo);
10122 if (error == NULL)
10123 error = close_err;
10125 if (worktree)
10126 got_worktree_close(worktree);
10127 if (pack_fds) {
10128 const struct got_error *pack_err =
10129 got_repo_pack_fds_close(pack_fds);
10130 if (error == NULL)
10131 error = pack_err;
10133 if (ref)
10134 got_ref_close(ref);
10135 got_repo_free_remote_repo_data(remote);
10136 free(remote);
10137 got_pathlist_free(&branches, GOT_PATHLIST_FREE_NONE);
10138 got_pathlist_free(&tags, GOT_PATHLIST_FREE_NONE);
10139 got_ref_list_free(&all_branches);
10140 got_ref_list_free(&all_tags);
10141 got_pathlist_free(&delete_args, GOT_PATHLIST_FREE_NONE);
10142 got_pathlist_free(&delete_branches, GOT_PATHLIST_FREE_PATH);
10143 free(cwd);
10144 free(repo_path);
10145 free(proto);
10146 free(host);
10147 free(port);
10148 free(server_path);
10149 free(repo_name);
10150 return error;
10154 * Print and if delete is set delete all ref_prefix references.
10155 * If wanted_ref is not NULL, only print or delete this reference.
10157 static const struct got_error *
10158 process_logmsg_refs(const char *ref_prefix, size_t prefix_len,
10159 const char *wanted_ref, int delete, struct got_worktree *worktree,
10160 struct got_repository *repo)
10162 const struct got_error *err;
10163 struct got_pathlist_head paths;
10164 struct got_reflist_head refs;
10165 struct got_reflist_entry *re;
10166 struct got_reflist_object_id_map *refs_idmap = NULL;
10167 struct got_commit_object *commit = NULL;
10168 struct got_object_id *id = NULL;
10169 const char *header_prefix;
10170 char *uuidstr = NULL;
10171 int found = 0;
10173 TAILQ_INIT(&refs);
10174 TAILQ_INIT(&paths);
10176 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, repo);
10177 if (err)
10178 goto done;
10180 err = got_reflist_object_id_map_create(&refs_idmap, &refs, repo);
10181 if (err)
10182 goto done;
10184 if (worktree != NULL) {
10185 err = got_worktree_get_uuid(&uuidstr, worktree);
10186 if (err)
10187 goto done;
10190 if (wanted_ref) {
10191 if (strncmp(wanted_ref, "refs/heads/", 11) == 0)
10192 wanted_ref += 11;
10195 if (strcmp(ref_prefix, GOT_WORKTREE_BACKOUT_REF_PREFIX) == 0)
10196 header_prefix = "backout";
10197 else
10198 header_prefix = "cherrypick";
10200 TAILQ_FOREACH(re, &refs, entry) {
10201 const char *refname, *wt;
10203 refname = got_ref_get_name(re->ref);
10205 err = check_cancelled(NULL);
10206 if (err)
10207 goto done;
10209 if (strncmp(refname, ref_prefix, prefix_len) == 0)
10210 refname += prefix_len + 1; /* skip '-' delimiter */
10211 else
10212 continue;
10214 wt = refname;
10216 if (worktree == NULL || strncmp(refname, uuidstr,
10217 GOT_WORKTREE_UUID_STRLEN) == 0)
10218 refname += GOT_WORKTREE_UUID_STRLEN + 1; /* skip '-' */
10219 else
10220 continue;
10222 err = got_repo_match_object_id(&id, NULL, refname,
10223 GOT_OBJ_TYPE_COMMIT, NULL, repo);
10224 if (err)
10225 goto done;
10227 err = got_object_open_as_commit(&commit, repo, id);
10228 if (err)
10229 goto done;
10231 if (wanted_ref)
10232 found = strncmp(wanted_ref, refname,
10233 strlen(wanted_ref)) == 0;
10234 if (wanted_ref && !found) {
10235 struct got_reflist_head *ci_refs;
10237 ci_refs = got_reflist_object_id_map_lookup(refs_idmap,
10238 id);
10240 if (ci_refs) {
10241 char *refs_str = NULL;
10242 char const *r = NULL;
10244 err = build_refs_str(&refs_str, ci_refs, id,
10245 repo, 1);
10246 if (err)
10247 goto done;
10249 r = refs_str;
10250 while (r) {
10251 if (strncmp(r, wanted_ref,
10252 strlen(wanted_ref)) == 0) {
10253 found = 1;
10254 break;
10256 r = strchr(r, ' ');
10257 if (r)
10258 ++r;
10260 free(refs_str);
10264 if (wanted_ref == NULL || found) {
10265 if (delete) {
10266 err = got_ref_delete(re->ref, repo);
10267 if (err)
10268 goto done;
10269 printf("Deleted: ");
10270 err = print_commit_oneline(commit, id, repo,
10271 refs_idmap);
10272 } else {
10274 * Print paths modified by commit to help
10275 * associate commits with worktree changes.
10277 err = get_changed_paths(&paths, commit,
10278 repo, NULL);
10279 if (err)
10280 goto done;
10282 err = print_commit(commit, id, repo, NULL,
10283 &paths, NULL, 0, 0, refs_idmap, NULL,
10284 header_prefix);
10285 got_pathlist_free(&paths,
10286 GOT_PATHLIST_FREE_ALL);
10288 if (worktree == NULL)
10289 printf("work tree: %.*s\n\n",
10290 GOT_WORKTREE_UUID_STRLEN, wt);
10292 if (err || found)
10293 goto done;
10296 got_object_commit_close(commit);
10297 commit = NULL;
10298 free(id);
10299 id = NULL;
10302 if (wanted_ref != NULL && !found)
10303 err = got_error_fmt(GOT_ERR_NOT_REF, "%s", wanted_ref);
10305 done:
10306 free(id);
10307 free(uuidstr);
10308 got_ref_list_free(&refs);
10309 got_pathlist_free(&paths, GOT_PATHLIST_FREE_ALL);
10310 if (refs_idmap)
10311 got_reflist_object_id_map_free(refs_idmap);
10312 if (commit)
10313 got_object_commit_close(commit);
10314 return err;
10318 * Create new temp "logmsg" ref of the backed-out or cherrypicked commit
10319 * identified by id for log messages to prepopulate the editor on commit.
10321 static const struct got_error *
10322 logmsg_ref(struct got_object_id *id, const char *prefix,
10323 struct got_worktree *worktree, struct got_repository *repo)
10325 const struct got_error *err = NULL;
10326 char *idstr, *ref = NULL, *refname = NULL;
10327 int histedit_in_progress;
10328 int rebase_in_progress, merge_in_progress;
10331 * Silenty refuse to create merge reference if any histedit, merge,
10332 * or rebase operation is in progress.
10334 err = got_worktree_histedit_in_progress(&histedit_in_progress,
10335 worktree);
10336 if (err)
10337 return err;
10338 if (histedit_in_progress)
10339 return NULL;
10341 err = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
10342 if (err)
10343 return err;
10344 if (rebase_in_progress)
10345 return NULL;
10347 err = got_worktree_merge_in_progress(&merge_in_progress, worktree,
10348 repo);
10349 if (err)
10350 return err;
10351 if (merge_in_progress)
10352 return NULL;
10354 err = got_object_id_str(&idstr, id);
10355 if (err)
10356 return err;
10358 err = got_worktree_get_logmsg_ref_name(&refname, worktree, prefix);
10359 if (err)
10360 goto done;
10362 if (asprintf(&ref, "%s-%s", refname, idstr) == -1) {
10363 err = got_error_from_errno("asprintf");
10364 goto done;
10367 err = create_ref(ref, got_worktree_get_base_commit_id(worktree),
10368 -1, repo);
10369 done:
10370 free(ref);
10371 free(idstr);
10372 free(refname);
10373 return err;
10376 __dead static void
10377 usage_cherrypick(void)
10379 fprintf(stderr, "usage: %s cherrypick [-lX] [commit-id]\n",
10380 getprogname());
10381 exit(1);
10384 static const struct got_error *
10385 cmd_cherrypick(int argc, char *argv[])
10387 const struct got_error *error = NULL;
10388 struct got_worktree *worktree = NULL;
10389 struct got_repository *repo = NULL;
10390 char *cwd = NULL, *commit_id_str = NULL, *keyword_idstr = NULL;
10391 struct got_object_id *commit_id = NULL;
10392 struct got_commit_object *commit = NULL;
10393 struct got_object_qid *pid;
10394 int ch, list_refs = 0, remove_refs = 0;
10395 struct got_update_progress_arg upa;
10396 int *pack_fds = NULL;
10398 #ifndef PROFILE
10399 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
10400 "unveil", NULL) == -1)
10401 err(1, "pledge");
10402 #endif
10404 while ((ch = getopt(argc, argv, "lX")) != -1) {
10405 switch (ch) {
10406 case 'l':
10407 list_refs = 1;
10408 break;
10409 case 'X':
10410 remove_refs = 1;
10411 break;
10412 default:
10413 usage_cherrypick();
10414 /* NOTREACHED */
10418 argc -= optind;
10419 argv += optind;
10421 if (list_refs || remove_refs) {
10422 if (argc != 0 && argc != 1)
10423 usage_cherrypick();
10424 } else if (argc != 1)
10425 usage_cherrypick();
10426 if (list_refs && remove_refs)
10427 option_conflict('l', 'X');
10429 cwd = getcwd(NULL, 0);
10430 if (cwd == NULL) {
10431 error = got_error_from_errno("getcwd");
10432 goto done;
10435 error = got_repo_pack_fds_open(&pack_fds);
10436 if (error != NULL)
10437 goto done;
10439 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
10440 if (error) {
10441 if (list_refs || remove_refs) {
10442 if (error->code != GOT_ERR_NOT_WORKTREE)
10443 goto done;
10444 } else {
10445 if (error->code == GOT_ERR_NOT_WORKTREE)
10446 error = wrap_not_worktree_error(error,
10447 "cherrypick", cwd);
10448 goto done;
10452 error = got_repo_open(&repo,
10453 worktree ? got_worktree_get_repo_path(worktree) : cwd,
10454 NULL, pack_fds);
10455 if (error != NULL)
10456 goto done;
10458 error = apply_unveil(got_repo_get_path(repo), 0,
10459 worktree ? got_worktree_get_root_path(worktree) : NULL);
10460 if (error)
10461 goto done;
10463 if (list_refs || remove_refs) {
10464 error = process_logmsg_refs(GOT_WORKTREE_CHERRYPICK_REF_PREFIX,
10465 GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN,
10466 argc == 1 ? argv[0] : NULL, remove_refs, worktree, repo);
10467 goto done;
10470 error = got_keyword_to_idstr(&keyword_idstr, argv[0], repo, worktree);
10471 if (error != NULL)
10472 goto done;
10474 error = got_repo_match_object_id(&commit_id, NULL,
10475 keyword_idstr != NULL ? keyword_idstr : argv[0],
10476 GOT_OBJ_TYPE_COMMIT, NULL, repo);
10477 if (error)
10478 goto done;
10479 error = got_object_id_str(&commit_id_str, commit_id);
10480 if (error)
10481 goto done;
10483 error = got_object_open_as_commit(&commit, repo, commit_id);
10484 if (error)
10485 goto done;
10486 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
10487 memset(&upa, 0, sizeof(upa));
10488 error = got_worktree_merge_files(worktree, pid ? &pid->id : NULL,
10489 commit_id, repo, update_progress, &upa, check_cancelled,
10490 NULL);
10491 if (error != NULL)
10492 goto done;
10494 if (upa.did_something) {
10495 error = logmsg_ref(commit_id,
10496 GOT_WORKTREE_CHERRYPICK_REF_PREFIX, worktree, repo);
10497 if (error)
10498 goto done;
10499 printf("Merged commit %s\n", commit_id_str);
10501 print_merge_progress_stats(&upa);
10502 done:
10503 free(cwd);
10504 free(keyword_idstr);
10505 if (commit)
10506 got_object_commit_close(commit);
10507 free(commit_id_str);
10508 if (worktree)
10509 got_worktree_close(worktree);
10510 if (repo) {
10511 const struct got_error *close_err = got_repo_close(repo);
10512 if (error == NULL)
10513 error = close_err;
10515 if (pack_fds) {
10516 const struct got_error *pack_err =
10517 got_repo_pack_fds_close(pack_fds);
10518 if (error == NULL)
10519 error = pack_err;
10522 return error;
10525 __dead static void
10526 usage_backout(void)
10528 fprintf(stderr, "usage: %s backout [-lX] [commit-id]\n", getprogname());
10529 exit(1);
10532 static const struct got_error *
10533 cmd_backout(int argc, char *argv[])
10535 const struct got_error *error = NULL;
10536 struct got_worktree *worktree = NULL;
10537 struct got_repository *repo = NULL;
10538 char *cwd = NULL, *commit_id_str = NULL, *keyword_idstr = NULL;
10539 struct got_object_id *commit_id = NULL;
10540 struct got_commit_object *commit = NULL;
10541 struct got_object_qid *pid;
10542 int ch, list_refs = 0, remove_refs = 0;
10543 struct got_update_progress_arg upa;
10544 int *pack_fds = NULL;
10546 #ifndef PROFILE
10547 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
10548 "unveil", NULL) == -1)
10549 err(1, "pledge");
10550 #endif
10552 while ((ch = getopt(argc, argv, "lX")) != -1) {
10553 switch (ch) {
10554 case 'l':
10555 list_refs = 1;
10556 break;
10557 case 'X':
10558 remove_refs = 1;
10559 break;
10560 default:
10561 usage_backout();
10562 /* NOTREACHED */
10566 argc -= optind;
10567 argv += optind;
10569 if (list_refs || remove_refs) {
10570 if (argc != 0 && argc != 1)
10571 usage_backout();
10572 } else if (argc != 1)
10573 usage_backout();
10574 if (list_refs && remove_refs)
10575 option_conflict('l', 'X');
10577 cwd = getcwd(NULL, 0);
10578 if (cwd == NULL) {
10579 error = got_error_from_errno("getcwd");
10580 goto done;
10583 error = got_repo_pack_fds_open(&pack_fds);
10584 if (error != NULL)
10585 goto done;
10587 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
10588 if (error) {
10589 if (list_refs || remove_refs) {
10590 if (error->code != GOT_ERR_NOT_WORKTREE)
10591 goto done;
10592 } else {
10593 if (error->code == GOT_ERR_NOT_WORKTREE)
10594 error = wrap_not_worktree_error(error,
10595 "backout", cwd);
10596 goto done;
10600 error = got_repo_open(&repo,
10601 worktree ? got_worktree_get_repo_path(worktree) : cwd,
10602 NULL, pack_fds);
10603 if (error != NULL)
10604 goto done;
10606 error = apply_unveil(got_repo_get_path(repo), 0,
10607 worktree ? got_worktree_get_root_path(worktree) : NULL);
10608 if (error)
10609 goto done;
10611 if (list_refs || remove_refs) {
10612 error = process_logmsg_refs(GOT_WORKTREE_BACKOUT_REF_PREFIX,
10613 GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN,
10614 argc == 1 ? argv[0] : NULL, remove_refs, worktree, repo);
10615 goto done;
10618 error = got_keyword_to_idstr(&keyword_idstr, argv[0], repo, worktree);
10619 if (error != NULL)
10620 goto done;
10622 error = got_repo_match_object_id(&commit_id, NULL,
10623 keyword_idstr != NULL ? keyword_idstr : argv[0],
10624 GOT_OBJ_TYPE_COMMIT, NULL, repo);
10625 if (error)
10626 goto done;
10627 error = got_object_id_str(&commit_id_str, commit_id);
10628 if (error)
10629 goto done;
10631 error = got_object_open_as_commit(&commit, repo, commit_id);
10632 if (error)
10633 goto done;
10634 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
10635 if (pid == NULL) {
10636 error = got_error(GOT_ERR_ROOT_COMMIT);
10637 goto done;
10640 memset(&upa, 0, sizeof(upa));
10641 error = got_worktree_merge_files(worktree, commit_id, &pid->id,
10642 repo, update_progress, &upa, check_cancelled, NULL);
10643 if (error != NULL)
10644 goto done;
10646 if (upa.did_something) {
10647 error = logmsg_ref(commit_id, GOT_WORKTREE_BACKOUT_REF_PREFIX,
10648 worktree, repo);
10649 if (error)
10650 goto done;
10651 printf("Backed out commit %s\n", commit_id_str);
10653 print_merge_progress_stats(&upa);
10654 done:
10655 free(cwd);
10656 free(keyword_idstr);
10657 if (commit)
10658 got_object_commit_close(commit);
10659 free(commit_id_str);
10660 if (worktree)
10661 got_worktree_close(worktree);
10662 if (repo) {
10663 const struct got_error *close_err = got_repo_close(repo);
10664 if (error == NULL)
10665 error = close_err;
10667 if (pack_fds) {
10668 const struct got_error *pack_err =
10669 got_repo_pack_fds_close(pack_fds);
10670 if (error == NULL)
10671 error = pack_err;
10673 return error;
10676 __dead static void
10677 usage_rebase(void)
10679 fprintf(stderr, "usage: %s rebase [-aCclX] [branch]\n", getprogname());
10680 exit(1);
10683 static void
10684 trim_logmsg(char *logmsg, int limit)
10686 char *nl;
10687 size_t len;
10689 len = strlen(logmsg);
10690 if (len > limit)
10691 len = limit;
10692 logmsg[len] = '\0';
10693 nl = strchr(logmsg, '\n');
10694 if (nl)
10695 *nl = '\0';
10698 static const struct got_error *
10699 get_short_logmsg(char **logmsg, int limit, struct got_commit_object *commit)
10701 const struct got_error *err;
10702 char *logmsg0 = NULL;
10703 const char *s;
10705 err = got_object_commit_get_logmsg(&logmsg0, commit);
10706 if (err)
10707 return err;
10709 s = logmsg0;
10710 while (isspace((unsigned char)s[0]))
10711 s++;
10713 *logmsg = strdup(s);
10714 if (*logmsg == NULL) {
10715 err = got_error_from_errno("strdup");
10716 goto done;
10719 trim_logmsg(*logmsg, limit);
10720 done:
10721 free(logmsg0);
10722 return err;
10725 static const struct got_error *
10726 show_rebase_merge_conflict(struct got_object_id *id,
10727 struct got_repository *repo)
10729 const struct got_error *err;
10730 struct got_commit_object *commit = NULL;
10731 char *id_str = NULL, *logmsg = NULL;
10733 err = got_object_open_as_commit(&commit, repo, id);
10734 if (err)
10735 return err;
10737 err = got_object_id_str(&id_str, id);
10738 if (err)
10739 goto done;
10741 id_str[12] = '\0';
10743 err = get_short_logmsg(&logmsg, 42, commit);
10744 if (err)
10745 goto done;
10747 printf("%s -> merge conflict: %s\n", id_str, logmsg);
10748 done:
10749 free(id_str);
10750 got_object_commit_close(commit);
10751 free(logmsg);
10752 return err;
10755 static const struct got_error *
10756 show_rebase_progress(struct got_commit_object *commit,
10757 struct got_object_id *old_id, struct got_object_id *new_id)
10759 const struct got_error *err;
10760 char *old_id_str = NULL, *new_id_str = NULL, *logmsg = NULL;
10762 err = got_object_id_str(&old_id_str, old_id);
10763 if (err)
10764 goto done;
10766 if (new_id) {
10767 err = got_object_id_str(&new_id_str, new_id);
10768 if (err)
10769 goto done;
10772 old_id_str[12] = '\0';
10773 if (new_id_str)
10774 new_id_str[12] = '\0';
10776 err = get_short_logmsg(&logmsg, 42, commit);
10777 if (err)
10778 goto done;
10780 printf("%s -> %s: %s\n", old_id_str,
10781 new_id_str ? new_id_str : "no-op change", logmsg);
10782 done:
10783 free(old_id_str);
10784 free(new_id_str);
10785 free(logmsg);
10786 return err;
10789 static const struct got_error *
10790 rebase_complete(struct got_worktree *worktree, struct got_fileindex *fileindex,
10791 struct got_reference *branch, struct got_reference *tmp_branch,
10792 struct got_repository *repo, int create_backup)
10794 printf("Switching work tree to %s\n", got_ref_get_name(branch));
10795 return got_worktree_rebase_complete(worktree, fileindex,
10796 tmp_branch, branch, repo, create_backup);
10799 static const struct got_error *
10800 rebase_commit(struct got_pathlist_head *merged_paths,
10801 struct got_worktree *worktree, struct got_fileindex *fileindex,
10802 struct got_reference *tmp_branch, const char *committer,
10803 struct got_object_id *commit_id, int allow_conflict,
10804 struct got_repository *repo)
10806 const struct got_error *error;
10807 struct got_commit_object *commit;
10808 struct got_object_id *new_commit_id;
10810 error = got_object_open_as_commit(&commit, repo, commit_id);
10811 if (error)
10812 return error;
10814 error = got_worktree_rebase_commit(&new_commit_id, merged_paths,
10815 worktree, fileindex, tmp_branch, committer, commit, commit_id,
10816 allow_conflict, repo);
10817 if (error) {
10818 if (error->code != GOT_ERR_COMMIT_NO_CHANGES)
10819 goto done;
10820 error = show_rebase_progress(commit, commit_id, NULL);
10821 } else {
10822 error = show_rebase_progress(commit, commit_id, new_commit_id);
10823 free(new_commit_id);
10825 done:
10826 got_object_commit_close(commit);
10827 return error;
10830 struct check_path_prefix_arg {
10831 const char *path_prefix;
10832 size_t len;
10833 int errcode;
10836 static const struct got_error *
10837 check_path_prefix_in_diff(void *arg, struct got_blob_object *blob1,
10838 struct got_blob_object *blob2, FILE *f1, FILE *f2,
10839 struct got_object_id *id1, struct got_object_id *id2,
10840 const char *path1, const char *path2,
10841 mode_t mode1, mode_t mode2, struct got_repository *repo)
10843 struct check_path_prefix_arg *a = arg;
10845 if ((path1 && !got_path_is_child(path1, a->path_prefix, a->len)) ||
10846 (path2 && !got_path_is_child(path2, a->path_prefix, a->len)))
10847 return got_error(a->errcode);
10849 return NULL;
10852 static const struct got_error *
10853 check_path_prefix(struct got_object_id *parent_id,
10854 struct got_object_id *commit_id, const char *path_prefix,
10855 int errcode, struct got_repository *repo)
10857 const struct got_error *err;
10858 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
10859 struct got_commit_object *commit = NULL, *parent_commit = NULL;
10860 struct check_path_prefix_arg cpp_arg;
10862 if (got_path_is_root_dir(path_prefix))
10863 return NULL;
10865 err = got_object_open_as_commit(&commit, repo, commit_id);
10866 if (err)
10867 goto done;
10869 err = got_object_open_as_commit(&parent_commit, repo, parent_id);
10870 if (err)
10871 goto done;
10873 err = got_object_open_as_tree(&tree1, repo,
10874 got_object_commit_get_tree_id(parent_commit));
10875 if (err)
10876 goto done;
10878 err = got_object_open_as_tree(&tree2, repo,
10879 got_object_commit_get_tree_id(commit));
10880 if (err)
10881 goto done;
10883 cpp_arg.path_prefix = path_prefix;
10884 while (cpp_arg.path_prefix[0] == '/')
10885 cpp_arg.path_prefix++;
10886 cpp_arg.len = strlen(cpp_arg.path_prefix);
10887 cpp_arg.errcode = errcode;
10888 err = got_diff_tree(tree1, tree2, NULL, NULL, -1, -1, "", "", repo,
10889 check_path_prefix_in_diff, &cpp_arg, 0);
10890 done:
10891 if (tree1)
10892 got_object_tree_close(tree1);
10893 if (tree2)
10894 got_object_tree_close(tree2);
10895 if (commit)
10896 got_object_commit_close(commit);
10897 if (parent_commit)
10898 got_object_commit_close(parent_commit);
10899 return err;
10902 static const struct got_error *
10903 collect_commits(struct got_object_id_queue *commits,
10904 struct got_object_id *initial_commit_id,
10905 struct got_object_id *iter_start_id, struct got_object_id *iter_stop_id,
10906 const char *path_prefix, int path_prefix_errcode,
10907 struct got_repository *repo)
10909 const struct got_error *err = NULL;
10910 struct got_commit_graph *graph = NULL;
10911 struct got_object_id parent_id, commit_id;
10912 struct got_object_qid *qid;
10914 err = got_commit_graph_open(&graph, "/", 1);
10915 if (err)
10916 return err;
10918 err = got_commit_graph_bfsort(graph, iter_start_id, repo,
10919 check_cancelled, NULL);
10920 if (err)
10921 goto done;
10923 memcpy(&commit_id, initial_commit_id, sizeof(commit_id));
10924 while (got_object_id_cmp(&commit_id, iter_stop_id) != 0) {
10925 err = got_commit_graph_iter_next(&parent_id, graph, repo,
10926 check_cancelled, NULL);
10927 if (err) {
10928 if (err->code == GOT_ERR_ITER_COMPLETED) {
10929 err = got_error_msg(GOT_ERR_ANCESTRY,
10930 "ran out of commits to rebase before "
10931 "youngest common ancestor commit has "
10932 "been reached?!?");
10934 goto done;
10935 } else {
10936 err = check_path_prefix(&parent_id, &commit_id,
10937 path_prefix, path_prefix_errcode, repo);
10938 if (err)
10939 goto done;
10941 err = got_object_qid_alloc(&qid, &commit_id);
10942 if (err)
10943 goto done;
10944 STAILQ_INSERT_HEAD(commits, qid, entry);
10946 memcpy(&commit_id, &parent_id, sizeof(commit_id));
10949 done:
10950 got_commit_graph_close(graph);
10951 return err;
10954 static const struct got_error *
10955 get_commit_brief_str(char **brief_str, struct got_commit_object *commit)
10957 const struct got_error *err = NULL;
10958 time_t committer_time;
10959 struct tm tm;
10960 char datebuf[11]; /* YYYY-MM-DD + NUL */
10961 char *author0 = NULL, *author, *smallerthan;
10962 char *logmsg0 = NULL, *logmsg, *newline;
10964 committer_time = got_object_commit_get_committer_time(commit);
10965 if (gmtime_r(&committer_time, &tm) == NULL)
10966 return got_error_from_errno("gmtime_r");
10967 if (strftime(datebuf, sizeof(datebuf), "%G-%m-%d", &tm) == 0)
10968 return got_error(GOT_ERR_NO_SPACE);
10970 author0 = strdup(got_object_commit_get_author(commit));
10971 if (author0 == NULL)
10972 return got_error_from_errno("strdup");
10973 author = author0;
10974 smallerthan = strchr(author, '<');
10975 if (smallerthan && smallerthan[1] != '\0')
10976 author = smallerthan + 1;
10977 author[strcspn(author, "@>")] = '\0';
10979 err = got_object_commit_get_logmsg(&logmsg0, commit);
10980 if (err)
10981 goto done;
10982 logmsg = logmsg0;
10983 while (*logmsg == '\n')
10984 logmsg++;
10985 newline = strchr(logmsg, '\n');
10986 if (newline)
10987 *newline = '\0';
10989 if (asprintf(brief_str, "%s %s %s",
10990 datebuf, author, logmsg) == -1)
10991 err = got_error_from_errno("asprintf");
10992 done:
10993 free(author0);
10994 free(logmsg0);
10995 return err;
10998 static const struct got_error *
10999 delete_backup_ref(struct got_reference *ref, struct got_object_id *id,
11000 struct got_repository *repo)
11002 const struct got_error *err;
11003 char *id_str;
11005 err = got_object_id_str(&id_str, id);
11006 if (err)
11007 return err;
11009 err = got_ref_delete(ref, repo);
11010 if (err)
11011 goto done;
11013 printf("Deleted %s: %s\n", got_ref_get_name(ref), id_str);
11014 done:
11015 free(id_str);
11016 return err;
11019 static const struct got_error *
11020 print_backup_ref(const char *branch_name, const char *new_id_str,
11021 struct got_object_id *old_commit_id, struct got_commit_object *old_commit,
11022 struct got_reflist_object_id_map *refs_idmap,
11023 struct got_repository *repo)
11025 const struct got_error *err = NULL;
11026 struct got_reflist_head *refs;
11027 char *refs_str = NULL;
11028 struct got_object_id *new_commit_id = NULL;
11029 struct got_commit_object *new_commit = NULL;
11030 char *new_commit_brief_str = NULL;
11031 struct got_object_id *yca_id = NULL;
11032 struct got_commit_object *yca_commit = NULL;
11033 char *yca_id_str = NULL, *yca_brief_str = NULL;
11034 char *custom_refs_str;
11036 if (asprintf(&custom_refs_str, "formerly %s", branch_name) == -1)
11037 return got_error_from_errno("asprintf");
11039 err = print_commit(old_commit, old_commit_id, repo, NULL, NULL, NULL,
11040 0, 0, refs_idmap, custom_refs_str, NULL);
11041 if (err)
11042 goto done;
11044 err = got_object_resolve_id_str(&new_commit_id, repo, new_id_str);
11045 if (err)
11046 goto done;
11048 refs = got_reflist_object_id_map_lookup(refs_idmap, new_commit_id);
11049 if (refs) {
11050 err = build_refs_str(&refs_str, refs, new_commit_id, repo, 0);
11051 if (err)
11052 goto done;
11055 err = got_object_open_as_commit(&new_commit, repo, new_commit_id);
11056 if (err)
11057 goto done;
11059 err = get_commit_brief_str(&new_commit_brief_str, new_commit);
11060 if (err)
11061 goto done;
11063 err = got_commit_graph_find_youngest_common_ancestor(&yca_id,
11064 old_commit_id, new_commit_id, 1, 0, repo, check_cancelled, NULL);
11065 if (err)
11066 goto done;
11068 printf("has become commit %s%s%s%s\n %s\n", new_id_str,
11069 refs_str ? " (" : "", refs_str ? refs_str : "",
11070 refs_str ? ")" : "", new_commit_brief_str);
11071 if (yca_id && got_object_id_cmp(yca_id, new_commit_id) != 0 &&
11072 got_object_id_cmp(yca_id, old_commit_id) != 0) {
11073 free(refs_str);
11074 refs_str = NULL;
11076 err = got_object_open_as_commit(&yca_commit, repo, yca_id);
11077 if (err)
11078 goto done;
11080 err = get_commit_brief_str(&yca_brief_str, yca_commit);
11081 if (err)
11082 goto done;
11084 err = got_object_id_str(&yca_id_str, yca_id);
11085 if (err)
11086 goto done;
11088 refs = got_reflist_object_id_map_lookup(refs_idmap, yca_id);
11089 if (refs) {
11090 err = build_refs_str(&refs_str, refs, yca_id, repo, 0);
11091 if (err)
11092 goto done;
11094 printf("history forked at %s%s%s%s\n %s\n",
11095 yca_id_str,
11096 refs_str ? " (" : "", refs_str ? refs_str : "",
11097 refs_str ? ")" : "", yca_brief_str);
11099 done:
11100 free(custom_refs_str);
11101 free(new_commit_id);
11102 free(refs_str);
11103 free(yca_id);
11104 free(yca_id_str);
11105 free(yca_brief_str);
11106 if (new_commit)
11107 got_object_commit_close(new_commit);
11108 if (yca_commit)
11109 got_object_commit_close(yca_commit);
11111 return err;
11114 static const struct got_error *
11115 worktree_has_logmsg_ref(const char *caller, struct got_worktree *worktree,
11116 struct got_repository *repo)
11118 const struct got_error *err;
11119 struct got_reflist_head refs;
11120 struct got_reflist_entry *re;
11121 char *uuidstr = NULL;
11122 static char msg[160];
11124 TAILQ_INIT(&refs);
11126 err = got_worktree_get_uuid(&uuidstr, worktree);
11127 if (err)
11128 goto done;
11130 err = got_ref_list(&refs, repo, "refs/got/worktree",
11131 got_ref_cmp_by_name, repo);
11132 if (err)
11133 goto done;
11135 TAILQ_FOREACH(re, &refs, entry) {
11136 const char *cmd, *refname, *type;
11138 refname = got_ref_get_name(re->ref);
11140 if (strncmp(refname, GOT_WORKTREE_CHERRYPICK_REF_PREFIX,
11141 GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN) == 0) {
11142 refname += GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN + 1;
11143 cmd = "cherrypick";
11144 type = "cherrypicked";
11145 } else if (strncmp(refname, GOT_WORKTREE_BACKOUT_REF_PREFIX,
11146 GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN) == 0) {
11147 refname += GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN + 1;
11148 cmd = "backout";
11149 type = "backed-out";
11150 } else
11151 continue;
11153 if (strncmp(refname, uuidstr, GOT_WORKTREE_UUID_STRLEN) != 0)
11154 continue;
11156 snprintf(msg, sizeof(msg),
11157 "work tree has references created by %s commits which "
11158 "must be removed with 'got %s -X' before running the %s "
11159 "command", type, cmd, caller);
11160 err = got_error_msg(GOT_ERR_WORKTREE_META, msg);
11161 goto done;
11164 done:
11165 free(uuidstr);
11166 got_ref_list_free(&refs);
11167 return err;
11170 static const struct got_error *
11171 process_backup_refs(const char *backup_ref_prefix,
11172 const char *wanted_branch_name,
11173 int delete, struct got_repository *repo)
11175 const struct got_error *err;
11176 struct got_reflist_head refs, backup_refs;
11177 struct got_reflist_entry *re;
11178 const size_t backup_ref_prefix_len = strlen(backup_ref_prefix);
11179 struct got_object_id *old_commit_id = NULL;
11180 char *branch_name = NULL;
11181 struct got_commit_object *old_commit = NULL;
11182 struct got_reflist_object_id_map *refs_idmap = NULL;
11183 int wanted_branch_found = 0;
11185 TAILQ_INIT(&refs);
11186 TAILQ_INIT(&backup_refs);
11188 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
11189 if (err)
11190 return err;
11192 err = got_reflist_object_id_map_create(&refs_idmap, &refs, repo);
11193 if (err)
11194 goto done;
11196 if (wanted_branch_name) {
11197 if (strncmp(wanted_branch_name, "refs/heads/", 11) == 0)
11198 wanted_branch_name += 11;
11201 err = got_ref_list(&backup_refs, repo, backup_ref_prefix,
11202 got_ref_cmp_by_commit_timestamp_descending, repo);
11203 if (err)
11204 goto done;
11206 TAILQ_FOREACH(re, &backup_refs, entry) {
11207 const char *refname = got_ref_get_name(re->ref);
11208 char *slash;
11210 err = check_cancelled(NULL);
11211 if (err)
11212 break;
11214 err = got_ref_resolve(&old_commit_id, repo, re->ref);
11215 if (err)
11216 break;
11218 err = got_object_open_as_commit(&old_commit, repo,
11219 old_commit_id);
11220 if (err)
11221 break;
11223 if (strncmp(backup_ref_prefix, refname,
11224 backup_ref_prefix_len) == 0)
11225 refname += backup_ref_prefix_len;
11227 while (refname[0] == '/')
11228 refname++;
11230 branch_name = strdup(refname);
11231 if (branch_name == NULL) {
11232 err = got_error_from_errno("strdup");
11233 break;
11235 slash = strrchr(branch_name, '/');
11236 if (slash) {
11237 *slash = '\0';
11238 refname += strlen(branch_name) + 1;
11241 if (wanted_branch_name == NULL ||
11242 strcmp(wanted_branch_name, branch_name) == 0) {
11243 wanted_branch_found = 1;
11244 if (delete) {
11245 err = delete_backup_ref(re->ref,
11246 old_commit_id, repo);
11247 } else {
11248 err = print_backup_ref(branch_name, refname,
11249 old_commit_id, old_commit, refs_idmap,
11250 repo);
11252 if (err)
11253 break;
11256 free(old_commit_id);
11257 old_commit_id = NULL;
11258 free(branch_name);
11259 branch_name = NULL;
11260 got_object_commit_close(old_commit);
11261 old_commit = NULL;
11264 if (wanted_branch_name && !wanted_branch_found) {
11265 err = got_error_fmt(GOT_ERR_NOT_REF,
11266 "%s/%s/", backup_ref_prefix, wanted_branch_name);
11268 done:
11269 if (refs_idmap)
11270 got_reflist_object_id_map_free(refs_idmap);
11271 got_ref_list_free(&refs);
11272 got_ref_list_free(&backup_refs);
11273 free(old_commit_id);
11274 free(branch_name);
11275 if (old_commit)
11276 got_object_commit_close(old_commit);
11277 return err;
11280 static const struct got_error *
11281 abort_progress(void *arg, unsigned char status, const char *path)
11284 * Unversioned files should not clutter progress output when
11285 * an operation is aborted.
11287 if (status == GOT_STATUS_UNVERSIONED)
11288 return NULL;
11290 return update_progress(arg, status, path);
11293 static const struct got_error *
11294 find_merge_commit_yca(struct got_object_id **new_yca_id,
11295 struct got_object_id *branch_head_commit_id,
11296 struct got_object_id *yca_id,
11297 struct got_object_id *base_commit_id,
11298 struct got_repository *repo)
11300 const struct got_error *err = NULL;
11301 struct got_commit_graph *graph = NULL;
11302 struct got_commit_object *commit = NULL;
11304 *new_yca_id = NULL;
11306 err = got_commit_graph_open(&graph, "/", 1);
11307 if (err)
11308 return err;
11310 err = got_commit_graph_bfsort(graph, base_commit_id,
11311 repo, check_cancelled, NULL);
11312 if (err)
11313 goto done;
11315 for (;;) {
11316 struct got_object_id id;
11318 err = got_commit_graph_iter_next(&id, graph, repo,
11319 check_cancelled, NULL);
11320 if (err) {
11321 if (err->code == GOT_ERR_ITER_COMPLETED)
11322 err = NULL;
11323 break;
11326 err = got_object_open_as_commit(&commit, repo, &id);
11327 if (err)
11328 break;
11330 if (got_object_commit_get_nparents(commit) > 1) {
11331 /* Search for a better YCA using toposort. */
11332 err = got_commit_graph_find_youngest_common_ancestor(
11333 new_yca_id, base_commit_id, branch_head_commit_id,
11334 0, 1, repo, check_cancelled, NULL);
11335 break;
11338 if (got_object_id_cmp(&id, yca_id) == 0)
11339 break;
11340 got_object_commit_close(commit);
11341 commit = NULL;
11343 done:
11344 got_commit_graph_close(graph);
11345 if (commit)
11346 got_object_commit_close(commit);
11347 return err;
11350 static const struct got_error *
11351 cmd_rebase(int argc, char *argv[])
11353 const struct got_error *error = NULL;
11354 struct got_worktree *worktree = NULL;
11355 struct got_repository *repo = NULL;
11356 struct got_fileindex *fileindex = NULL;
11357 char *cwd = NULL, *committer = NULL, *gitconfig_path = NULL;
11358 struct got_reference *branch = NULL;
11359 struct got_reference *new_base_branch = NULL, *tmp_branch = NULL;
11360 struct got_object_id *commit_id = NULL, *parent_id = NULL;
11361 struct got_object_id *resume_commit_id = NULL;
11362 struct got_object_id *branch_head_commit_id = NULL, *yca_id = NULL;
11363 struct got_object_id *head_commit_id = NULL;
11364 struct got_reference *head_ref = NULL;
11365 struct got_commit_object *commit = NULL;
11366 int ch, rebase_in_progress = 0, abort_rebase = 0, continue_rebase = 0;
11367 int histedit_in_progress = 0, merge_in_progress = 0;
11368 int create_backup = 1, list_backups = 0, delete_backups = 0;
11369 int allow_conflict = 0;
11370 struct got_object_id_queue commits;
11371 struct got_pathlist_head merged_paths;
11372 const struct got_object_id_queue *parent_ids;
11373 struct got_object_qid *qid, *pid;
11374 struct got_update_progress_arg upa;
11375 int *pack_fds = NULL;
11377 STAILQ_INIT(&commits);
11378 TAILQ_INIT(&merged_paths);
11379 memset(&upa, 0, sizeof(upa));
11381 #ifndef PROFILE
11382 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
11383 "unveil", NULL) == -1)
11384 err(1, "pledge");
11385 #endif
11387 while ((ch = getopt(argc, argv, "aCclX")) != -1) {
11388 switch (ch) {
11389 case 'a':
11390 abort_rebase = 1;
11391 break;
11392 case 'C':
11393 allow_conflict = 1;
11394 break;
11395 case 'c':
11396 continue_rebase = 1;
11397 break;
11398 case 'l':
11399 list_backups = 1;
11400 break;
11401 case 'X':
11402 delete_backups = 1;
11403 break;
11404 default:
11405 usage_rebase();
11406 /* NOTREACHED */
11410 argc -= optind;
11411 argv += optind;
11413 if (list_backups) {
11414 if (abort_rebase)
11415 option_conflict('l', 'a');
11416 if (allow_conflict)
11417 option_conflict('l', 'C');
11418 if (continue_rebase)
11419 option_conflict('l', 'c');
11420 if (delete_backups)
11421 option_conflict('l', 'X');
11422 if (argc != 0 && argc != 1)
11423 usage_rebase();
11424 } else if (delete_backups) {
11425 if (abort_rebase)
11426 option_conflict('X', 'a');
11427 if (allow_conflict)
11428 option_conflict('X', 'C');
11429 if (continue_rebase)
11430 option_conflict('X', 'c');
11431 if (list_backups)
11432 option_conflict('l', 'X');
11433 if (argc != 0 && argc != 1)
11434 usage_rebase();
11435 } else if (allow_conflict) {
11436 if (abort_rebase)
11437 option_conflict('C', 'a');
11438 if (!continue_rebase)
11439 errx(1, "-C option requires -c");
11440 } else {
11441 if (abort_rebase && continue_rebase)
11442 usage_rebase();
11443 else if (abort_rebase || continue_rebase) {
11444 if (argc != 0)
11445 usage_rebase();
11446 } else if (argc != 1)
11447 usage_rebase();
11450 cwd = getcwd(NULL, 0);
11451 if (cwd == NULL) {
11452 error = got_error_from_errno("getcwd");
11453 goto done;
11456 error = got_repo_pack_fds_open(&pack_fds);
11457 if (error != NULL)
11458 goto done;
11460 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
11461 if (error) {
11462 if (list_backups || delete_backups) {
11463 if (error->code != GOT_ERR_NOT_WORKTREE)
11464 goto done;
11465 } else {
11466 if (error->code == GOT_ERR_NOT_WORKTREE)
11467 error = wrap_not_worktree_error(error,
11468 "rebase", cwd);
11469 goto done;
11473 error = get_gitconfig_path(&gitconfig_path);
11474 if (error)
11475 goto done;
11476 error = got_repo_open(&repo,
11477 worktree ? got_worktree_get_repo_path(worktree) : cwd,
11478 gitconfig_path, pack_fds);
11479 if (error != NULL)
11480 goto done;
11482 if (worktree != NULL && !list_backups && !delete_backups) {
11483 error = worktree_has_logmsg_ref("rebase", worktree, repo);
11484 if (error)
11485 goto done;
11488 error = get_author(&committer, repo, worktree);
11489 if (error && error->code != GOT_ERR_COMMIT_NO_AUTHOR)
11490 goto done;
11492 error = apply_unveil(got_repo_get_path(repo), 0,
11493 worktree ? got_worktree_get_root_path(worktree) : NULL);
11494 if (error)
11495 goto done;
11497 if (list_backups || delete_backups) {
11498 error = process_backup_refs(
11499 GOT_WORKTREE_REBASE_BACKUP_REF_PREFIX,
11500 argc == 1 ? argv[0] : NULL, delete_backups, repo);
11501 goto done; /* nothing else to do */
11504 error = got_worktree_histedit_in_progress(&histedit_in_progress,
11505 worktree);
11506 if (error)
11507 goto done;
11508 if (histedit_in_progress) {
11509 error = got_error(GOT_ERR_HISTEDIT_BUSY);
11510 goto done;
11513 error = got_worktree_merge_in_progress(&merge_in_progress,
11514 worktree, repo);
11515 if (error)
11516 goto done;
11517 if (merge_in_progress) {
11518 error = got_error(GOT_ERR_MERGE_BUSY);
11519 goto done;
11522 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
11523 if (error)
11524 goto done;
11526 if (abort_rebase) {
11527 if (!rebase_in_progress) {
11528 error = got_error(GOT_ERR_NOT_REBASING);
11529 goto done;
11531 error = got_worktree_rebase_continue(&resume_commit_id,
11532 &new_base_branch, &tmp_branch, &branch, &fileindex,
11533 worktree, repo);
11534 if (error)
11535 goto done;
11536 printf("Switching work tree to %s\n",
11537 got_ref_get_symref_target(new_base_branch));
11538 error = got_worktree_rebase_abort(worktree, fileindex, repo,
11539 new_base_branch, abort_progress, &upa);
11540 if (error)
11541 goto done;
11542 printf("Rebase of %s aborted\n", got_ref_get_name(branch));
11543 print_merge_progress_stats(&upa);
11544 goto done; /* nothing else to do */
11547 if (continue_rebase) {
11548 if (!rebase_in_progress) {
11549 error = got_error(GOT_ERR_NOT_REBASING);
11550 goto done;
11552 error = got_worktree_rebase_continue(&resume_commit_id,
11553 &new_base_branch, &tmp_branch, &branch, &fileindex,
11554 worktree, repo);
11555 if (error)
11556 goto done;
11558 error = rebase_commit(NULL, worktree, fileindex, tmp_branch,
11559 committer, resume_commit_id, allow_conflict, repo);
11560 if (error)
11561 goto done;
11563 yca_id = got_object_id_dup(resume_commit_id);
11564 if (yca_id == NULL) {
11565 error = got_error_from_errno("got_object_id_dup");
11566 goto done;
11568 } else {
11569 error = got_ref_open(&branch, repo, argv[0], 0);
11570 if (error != NULL)
11571 goto done;
11572 if (strncmp(got_ref_get_name(branch), "refs/heads/", 11) != 0) {
11573 error = got_error_msg(GOT_ERR_COMMIT_BRANCH,
11574 "will not rebase a branch which lives outside "
11575 "the \"refs/heads/\" reference namespace");
11576 goto done;
11580 error = got_ref_resolve(&branch_head_commit_id, repo, branch);
11581 if (error)
11582 goto done;
11584 if (!continue_rebase) {
11585 struct got_object_id *base_commit_id;
11587 error = got_ref_open(&head_ref, repo,
11588 got_worktree_get_head_ref_name(worktree), 0);
11589 if (error)
11590 goto done;
11591 error = got_ref_resolve(&head_commit_id, repo, head_ref);
11592 if (error)
11593 goto done;
11594 base_commit_id = got_worktree_get_base_commit_id(worktree);
11595 if (got_object_id_cmp(base_commit_id, head_commit_id) != 0) {
11596 error = got_error(GOT_ERR_REBASE_OUT_OF_DATE);
11597 goto done;
11600 error = got_commit_graph_find_youngest_common_ancestor(&yca_id,
11601 base_commit_id, branch_head_commit_id, 1, 0,
11602 repo, check_cancelled, NULL);
11603 if (error) {
11604 if (error->code == GOT_ERR_ANCESTRY) {
11605 error = got_error_msg(GOT_ERR_ANCESTRY,
11606 "specified branch shares no common "
11607 "ancestry with work tree's branch");
11609 goto done;
11613 * If a merge commit appears between the new base branch tip
11614 * and a YCA found via first-parent traversal then we might
11615 * find a better YCA using topologically sorted commits.
11617 if (got_object_id_cmp(base_commit_id, yca_id) != 0) {
11618 struct got_object_id *better_yca_id;
11619 error = find_merge_commit_yca(&better_yca_id,
11620 branch_head_commit_id, yca_id,
11621 base_commit_id, repo);
11622 if (error)
11623 goto done;
11624 if (better_yca_id) {
11625 free(yca_id);
11626 yca_id = better_yca_id;
11630 if (got_object_id_cmp(base_commit_id, yca_id) == 0) {
11631 struct got_pathlist_head paths;
11632 printf("%s is already based on %s\n",
11633 got_ref_get_name(branch),
11634 got_worktree_get_head_ref_name(worktree));
11635 error = switch_head_ref(branch, branch_head_commit_id,
11636 worktree, repo);
11637 if (error)
11638 goto done;
11639 error = got_worktree_set_base_commit_id(worktree, repo,
11640 branch_head_commit_id);
11641 if (error)
11642 goto done;
11643 TAILQ_INIT(&paths);
11644 error = got_pathlist_append(&paths, "", NULL);
11645 if (error)
11646 goto done;
11647 error = got_worktree_checkout_files(worktree,
11648 &paths, repo, update_progress, &upa,
11649 check_cancelled, NULL);
11650 got_pathlist_free(&paths, GOT_PATHLIST_FREE_NONE);
11651 if (error)
11652 goto done;
11653 if (upa.did_something) {
11654 char *id_str;
11655 error = got_object_id_str(&id_str,
11656 branch_head_commit_id);
11657 if (error)
11658 goto done;
11659 printf("Updated to %s: %s\n",
11660 got_worktree_get_head_ref_name(worktree),
11661 id_str);
11662 free(id_str);
11663 } else
11664 printf("Already up-to-date\n");
11665 print_update_progress_stats(&upa);
11666 goto done;
11670 commit_id = branch_head_commit_id;
11671 error = got_object_open_as_commit(&commit, repo, commit_id);
11672 if (error)
11673 goto done;
11675 parent_ids = got_object_commit_get_parent_ids(commit);
11676 pid = STAILQ_FIRST(parent_ids);
11677 if (pid) {
11678 error = collect_commits(&commits, commit_id, &pid->id,
11679 yca_id, got_worktree_get_path_prefix(worktree),
11680 GOT_ERR_REBASE_PATH, repo);
11681 if (error)
11682 goto done;
11685 got_object_commit_close(commit);
11686 commit = NULL;
11688 if (!continue_rebase) {
11689 error = got_worktree_rebase_prepare(&new_base_branch,
11690 &tmp_branch, &fileindex, worktree, branch, repo);
11691 if (error)
11692 goto done;
11695 if (STAILQ_EMPTY(&commits)) {
11696 if (continue_rebase) {
11697 error = rebase_complete(worktree, fileindex,
11698 branch, tmp_branch, repo, create_backup);
11699 goto done;
11700 } else {
11701 /* Fast-forward the reference of the branch. */
11702 struct got_object_id *new_head_commit_id;
11703 char *id_str;
11704 error = got_ref_resolve(&new_head_commit_id, repo,
11705 new_base_branch);
11706 if (error)
11707 goto done;
11708 error = got_object_id_str(&id_str, new_head_commit_id);
11709 if (error)
11710 goto done;
11711 printf("Forwarding %s to commit %s\n",
11712 got_ref_get_name(branch), id_str);
11713 free(id_str);
11714 error = got_ref_change_ref(branch,
11715 new_head_commit_id);
11716 if (error)
11717 goto done;
11718 /* No backup needed since objects did not change. */
11719 create_backup = 0;
11723 pid = NULL;
11724 STAILQ_FOREACH(qid, &commits, entry) {
11726 commit_id = &qid->id;
11727 parent_id = pid ? &pid->id : yca_id;
11728 pid = qid;
11730 memset(&upa, 0, sizeof(upa));
11731 error = got_worktree_rebase_merge_files(&merged_paths,
11732 worktree, fileindex, parent_id, commit_id, repo,
11733 update_progress, &upa, check_cancelled, NULL);
11734 if (error)
11735 goto done;
11737 print_merge_progress_stats(&upa);
11738 if (upa.conflicts > 0 || upa.missing > 0 ||
11739 upa.not_deleted > 0 || upa.unversioned > 0) {
11740 if (upa.conflicts > 0) {
11741 error = show_rebase_merge_conflict(&qid->id,
11742 repo);
11743 if (error)
11744 goto done;
11746 got_pathlist_free(&merged_paths, GOT_PATHLIST_FREE_PATH);
11747 break;
11750 error = rebase_commit(&merged_paths, worktree, fileindex,
11751 tmp_branch, committer, commit_id, 0, repo);
11752 got_pathlist_free(&merged_paths, GOT_PATHLIST_FREE_PATH);
11753 if (error)
11754 goto done;
11757 if (upa.conflicts > 0 || upa.missing > 0 ||
11758 upa.not_deleted > 0 || upa.unversioned > 0) {
11759 error = got_worktree_rebase_postpone(worktree, fileindex);
11760 if (error)
11761 goto done;
11762 if (upa.conflicts > 0 && upa.missing == 0 &&
11763 upa.not_deleted == 0 && upa.unversioned == 0) {
11764 error = got_error_msg(GOT_ERR_CONFLICTS,
11765 "conflicts must be resolved before rebasing "
11766 "can continue");
11767 } else if (upa.conflicts > 0) {
11768 error = got_error_msg(GOT_ERR_CONFLICTS,
11769 "conflicts must be resolved before rebasing "
11770 "can continue; changes destined for some "
11771 "files were not yet merged and should be "
11772 "merged manually if required before the "
11773 "rebase operation is continued");
11774 } else {
11775 error = got_error_msg(GOT_ERR_CONFLICTS,
11776 "changes destined for some files were not "
11777 "yet merged and should be merged manually "
11778 "if required before the rebase operation "
11779 "is continued");
11781 } else
11782 error = rebase_complete(worktree, fileindex, branch,
11783 tmp_branch, repo, create_backup);
11784 done:
11785 free(cwd);
11786 free(committer);
11787 free(gitconfig_path);
11788 got_object_id_queue_free(&commits);
11789 free(branch_head_commit_id);
11790 free(resume_commit_id);
11791 free(head_commit_id);
11792 free(yca_id);
11793 if (commit)
11794 got_object_commit_close(commit);
11795 if (branch)
11796 got_ref_close(branch);
11797 if (new_base_branch)
11798 got_ref_close(new_base_branch);
11799 if (tmp_branch)
11800 got_ref_close(tmp_branch);
11801 if (head_ref)
11802 got_ref_close(head_ref);
11803 if (worktree)
11804 got_worktree_close(worktree);
11805 if (repo) {
11806 const struct got_error *close_err = got_repo_close(repo);
11807 if (error == NULL)
11808 error = close_err;
11810 if (pack_fds) {
11811 const struct got_error *pack_err =
11812 got_repo_pack_fds_close(pack_fds);
11813 if (error == NULL)
11814 error = pack_err;
11816 return error;
11819 __dead static void
11820 usage_histedit(void)
11822 fprintf(stderr, "usage: %s histedit [-aCcdeflmX] [-F histedit-script] "
11823 "[branch]\n", getprogname());
11824 exit(1);
11827 #define GOT_HISTEDIT_PICK 'p'
11828 #define GOT_HISTEDIT_EDIT 'e'
11829 #define GOT_HISTEDIT_FOLD 'f'
11830 #define GOT_HISTEDIT_DROP 'd'
11831 #define GOT_HISTEDIT_MESG 'm'
11833 static const struct got_histedit_cmd {
11834 unsigned char code;
11835 const char *name;
11836 const char *desc;
11837 } got_histedit_cmds[] = {
11838 { GOT_HISTEDIT_PICK, "pick", "use commit" },
11839 { GOT_HISTEDIT_EDIT, "edit", "use commit but stop for amending" },
11840 { GOT_HISTEDIT_FOLD, "fold", "combine with next commit that will "
11841 "be used" },
11842 { GOT_HISTEDIT_DROP, "drop", "remove commit from history" },
11843 { GOT_HISTEDIT_MESG, "mesg", "open editor to edit the log message" },
11846 struct got_histedit_list_entry {
11847 TAILQ_ENTRY(got_histedit_list_entry) entry;
11848 struct got_object_id *commit_id;
11849 const struct got_histedit_cmd *cmd;
11850 char *logmsg;
11852 TAILQ_HEAD(got_histedit_list, got_histedit_list_entry);
11854 static const struct got_error *
11855 histedit_write_commit(struct got_object_id *commit_id, const char *cmdname,
11856 FILE *f, struct got_repository *repo)
11858 const struct got_error *err = NULL;
11859 char *logmsg = NULL, *id_str = NULL;
11860 struct got_commit_object *commit = NULL;
11861 int n;
11863 err = got_object_open_as_commit(&commit, repo, commit_id);
11864 if (err)
11865 goto done;
11867 err = get_short_logmsg(&logmsg, 34, commit);
11868 if (err)
11869 goto done;
11871 err = got_object_id_str(&id_str, commit_id);
11872 if (err)
11873 goto done;
11875 n = fprintf(f, "%s %s %s\n", cmdname, id_str, logmsg);
11876 if (n < 0)
11877 err = got_ferror(f, GOT_ERR_IO);
11878 done:
11879 if (commit)
11880 got_object_commit_close(commit);
11881 free(id_str);
11882 free(logmsg);
11883 return err;
11886 static const struct got_error *
11887 histedit_write_commit_list(struct got_object_id_queue *commits,
11888 FILE *f, int edit_logmsg_only, int fold_only, int drop_only,
11889 int edit_only, struct got_repository *repo)
11891 const struct got_error *err = NULL;
11892 struct got_object_qid *qid;
11893 const char *histedit_cmd = NULL;
11895 if (STAILQ_EMPTY(commits))
11896 return got_error(GOT_ERR_EMPTY_HISTEDIT);
11898 STAILQ_FOREACH(qid, commits, entry) {
11899 histedit_cmd = got_histedit_cmds[0].name;
11900 if (drop_only)
11901 histedit_cmd = "drop";
11902 else if (edit_only)
11903 histedit_cmd = "edit";
11904 else if (fold_only && STAILQ_NEXT(qid, entry) != NULL)
11905 histedit_cmd = "fold";
11906 else if (edit_logmsg_only)
11907 histedit_cmd = "mesg";
11908 err = histedit_write_commit(&qid->id, histedit_cmd, f, repo);
11909 if (err)
11910 break;
11913 return err;
11916 static const struct got_error *
11917 write_cmd_list(FILE *f, const char *branch_name,
11918 struct got_object_id_queue *commits)
11920 const struct got_error *err = NULL;
11921 size_t i;
11922 int n;
11923 char *id_str;
11924 struct got_object_qid *qid;
11926 qid = STAILQ_FIRST(commits);
11927 err = got_object_id_str(&id_str, &qid->id);
11928 if (err)
11929 return err;
11931 n = fprintf(f,
11932 "# Editing the history of branch '%s' starting at\n"
11933 "# commit %s\n"
11934 "# Commits will be processed in order from top to "
11935 "bottom of this file.\n", branch_name, id_str);
11936 if (n < 0) {
11937 err = got_ferror(f, GOT_ERR_IO);
11938 goto done;
11941 n = fprintf(f, "# Available histedit commands:\n");
11942 if (n < 0) {
11943 err = got_ferror(f, GOT_ERR_IO);
11944 goto done;
11947 for (i = 0; i < nitems(got_histedit_cmds); i++) {
11948 const struct got_histedit_cmd *cmd = &got_histedit_cmds[i];
11949 n = fprintf(f, "# %s (%c): %s\n", cmd->name, cmd->code,
11950 cmd->desc);
11951 if (n < 0) {
11952 err = got_ferror(f, GOT_ERR_IO);
11953 break;
11956 done:
11957 free(id_str);
11958 return err;
11961 static const struct got_error *
11962 histedit_syntax_error(int lineno)
11964 static char msg[42];
11965 int ret;
11967 ret = snprintf(msg, sizeof(msg), "histedit syntax error on line %d",
11968 lineno);
11969 if (ret < 0 || (size_t)ret >= sizeof(msg))
11970 return got_error(GOT_ERR_HISTEDIT_SYNTAX);
11972 return got_error_msg(GOT_ERR_HISTEDIT_SYNTAX, msg);
11975 static const struct got_error *
11976 append_folded_commit_msg(char **new_msg, struct got_histedit_list_entry *hle,
11977 char *logmsg, struct got_repository *repo)
11979 const struct got_error *err;
11980 struct got_commit_object *folded_commit = NULL;
11981 char *id_str, *folded_logmsg = NULL;
11983 err = got_object_id_str(&id_str, hle->commit_id);
11984 if (err)
11985 return err;
11987 err = got_object_open_as_commit(&folded_commit, repo, hle->commit_id);
11988 if (err)
11989 goto done;
11991 err = got_object_commit_get_logmsg(&folded_logmsg, folded_commit);
11992 if (err)
11993 goto done;
11994 if (asprintf(new_msg, "%s%s# log message of folded commit %s: %s",
11995 logmsg ? logmsg : "", logmsg ? "\n" : "", id_str,
11996 folded_logmsg) == -1) {
11997 err = got_error_from_errno("asprintf");
11999 done:
12000 if (folded_commit)
12001 got_object_commit_close(folded_commit);
12002 free(id_str);
12003 free(folded_logmsg);
12004 return err;
12007 static struct got_histedit_list_entry *
12008 get_folded_commits(struct got_histedit_list_entry *hle)
12010 struct got_histedit_list_entry *prev, *folded = NULL;
12012 prev = TAILQ_PREV(hle, got_histedit_list, entry);
12013 while (prev && (prev->cmd->code == GOT_HISTEDIT_FOLD ||
12014 prev->cmd->code == GOT_HISTEDIT_DROP)) {
12015 if (prev->cmd->code == GOT_HISTEDIT_FOLD)
12016 folded = prev;
12017 prev = TAILQ_PREV(prev, got_histedit_list, entry);
12020 return folded;
12023 static const struct got_error *
12024 histedit_edit_logmsg(struct got_histedit_list_entry *hle,
12025 const char *editor, struct got_repository *repo)
12027 char *logmsg_path = NULL, *id_str = NULL, *orig_logmsg = NULL;
12028 char *logmsg = NULL, *new_msg = NULL;
12029 const struct got_error *err = NULL;
12030 struct got_commit_object *commit = NULL;
12031 int logmsg_len;
12032 int fd = -1;
12033 struct got_histedit_list_entry *folded = NULL;
12035 err = got_object_open_as_commit(&commit, repo, hle->commit_id);
12036 if (err)
12037 return err;
12039 folded = get_folded_commits(hle);
12040 if (folded) {
12041 while (folded != hle) {
12042 if (folded->cmd->code == GOT_HISTEDIT_DROP) {
12043 folded = TAILQ_NEXT(folded, entry);
12044 continue;
12046 err = append_folded_commit_msg(&new_msg, folded,
12047 logmsg, repo);
12048 if (err)
12049 goto done;
12050 free(logmsg);
12051 logmsg = new_msg;
12052 folded = TAILQ_NEXT(folded, entry);
12056 err = got_object_id_str(&id_str, hle->commit_id);
12057 if (err)
12058 goto done;
12059 err = got_object_commit_get_logmsg(&orig_logmsg, commit);
12060 if (err)
12061 goto done;
12062 logmsg_len = asprintf(&new_msg,
12063 "%s\n# original log message of commit %s: %s",
12064 logmsg ? logmsg : "", id_str, orig_logmsg);
12065 if (logmsg_len == -1) {
12066 err = got_error_from_errno("asprintf");
12067 goto done;
12069 free(logmsg);
12070 logmsg = new_msg;
12072 err = got_object_id_str(&id_str, hle->commit_id);
12073 if (err)
12074 goto done;
12076 err = got_opentemp_named_fd(&logmsg_path, &fd,
12077 GOT_TMPDIR_STR "/got-logmsg", "");
12078 if (err)
12079 goto done;
12081 if (write(fd, logmsg, logmsg_len) == -1) {
12082 err = got_error_from_errno2("write", logmsg_path);
12083 goto done;
12085 if (close(fd) == -1) {
12086 err = got_error_from_errno2("close", logmsg_path);
12087 goto done;
12089 fd = -1;
12091 err = edit_logmsg(&hle->logmsg, editor, logmsg_path, logmsg,
12092 logmsg_len, 0);
12093 if (err) {
12094 if (err->code != GOT_ERR_COMMIT_MSG_EMPTY)
12095 goto done;
12096 err = NULL;
12097 hle->logmsg = strdup(new_msg);
12098 if (hle->logmsg == NULL)
12099 err = got_error_from_errno("strdup");
12101 done:
12102 if (fd != -1 && close(fd) == -1 && err == NULL)
12103 err = got_error_from_errno2("close", logmsg_path);
12104 if (logmsg_path && unlink(logmsg_path) != 0 && err == NULL)
12105 err = got_error_from_errno2("unlink", logmsg_path);
12106 free(logmsg_path);
12107 free(logmsg);
12108 free(orig_logmsg);
12109 if (commit)
12110 got_object_commit_close(commit);
12111 return err;
12114 static const struct got_error *
12115 histedit_parse_list(struct got_histedit_list *histedit_cmds,
12116 FILE *f, struct got_repository *repo)
12118 const struct got_error *err = NULL;
12119 char *line = NULL, *p, *end;
12120 size_t i, linesize = 0;
12121 ssize_t linelen;
12122 int lineno = 0;
12123 const struct got_histedit_cmd *cmd;
12124 struct got_object_id *commit_id = NULL;
12125 struct got_histedit_list_entry *hle = NULL;
12127 for (;;) {
12128 linelen = getline(&line, &linesize, f);
12129 if (linelen == -1) {
12130 const struct got_error *getline_err;
12131 if (feof(f))
12132 break;
12133 getline_err = got_error_from_errno("getline");
12134 err = got_ferror(f, getline_err->code);
12135 break;
12137 lineno++;
12138 p = line;
12139 while (isspace((unsigned char)p[0]))
12140 p++;
12141 if (p[0] == '#' || p[0] == '\0')
12142 continue;
12143 cmd = NULL;
12144 for (i = 0; i < nitems(got_histedit_cmds); i++) {
12145 cmd = &got_histedit_cmds[i];
12146 if (strncmp(cmd->name, p, strlen(cmd->name)) == 0 &&
12147 isspace((unsigned char)p[strlen(cmd->name)])) {
12148 p += strlen(cmd->name);
12149 break;
12151 if (p[0] == cmd->code && isspace((unsigned char)p[1])) {
12152 p++;
12153 break;
12156 if (i == nitems(got_histedit_cmds)) {
12157 err = histedit_syntax_error(lineno);
12158 break;
12160 while (isspace((unsigned char)p[0]))
12161 p++;
12162 end = p;
12163 while (end[0] && !isspace((unsigned char)end[0]))
12164 end++;
12165 *end = '\0';
12166 err = got_object_resolve_id_str(&commit_id, repo, p);
12167 if (err) {
12168 /* override error code */
12169 err = histedit_syntax_error(lineno);
12170 break;
12172 hle = malloc(sizeof(*hle));
12173 if (hle == NULL) {
12174 err = got_error_from_errno("malloc");
12175 break;
12177 hle->cmd = cmd;
12178 hle->commit_id = commit_id;
12179 hle->logmsg = NULL;
12180 commit_id = NULL;
12181 TAILQ_INSERT_TAIL(histedit_cmds, hle, entry);
12184 free(line);
12185 free(commit_id);
12186 return err;
12189 static const struct got_error *
12190 histedit_check_script(struct got_histedit_list *histedit_cmds,
12191 struct got_object_id_queue *commits, struct got_repository *repo)
12193 const struct got_error *err = NULL;
12194 struct got_object_qid *qid;
12195 struct got_histedit_list_entry *hle;
12196 static char msg[92];
12197 char *id_str;
12199 if (TAILQ_EMPTY(histedit_cmds))
12200 return got_error_msg(GOT_ERR_EMPTY_HISTEDIT,
12201 "histedit script contains no commands");
12202 if (STAILQ_EMPTY(commits))
12203 return got_error(GOT_ERR_EMPTY_HISTEDIT);
12205 TAILQ_FOREACH(hle, histedit_cmds, entry) {
12206 struct got_histedit_list_entry *hle2;
12207 TAILQ_FOREACH(hle2, histedit_cmds, entry) {
12208 if (hle == hle2)
12209 continue;
12210 if (got_object_id_cmp(hle->commit_id,
12211 hle2->commit_id) != 0)
12212 continue;
12213 err = got_object_id_str(&id_str, hle->commit_id);
12214 if (err)
12215 return err;
12216 snprintf(msg, sizeof(msg), "commit %s is listed "
12217 "more than once in histedit script", id_str);
12218 free(id_str);
12219 return got_error_msg(GOT_ERR_HISTEDIT_CMD, msg);
12223 STAILQ_FOREACH(qid, commits, entry) {
12224 TAILQ_FOREACH(hle, histedit_cmds, entry) {
12225 if (got_object_id_cmp(&qid->id, hle->commit_id) == 0)
12226 break;
12228 if (hle == NULL) {
12229 err = got_object_id_str(&id_str, &qid->id);
12230 if (err)
12231 return err;
12232 snprintf(msg, sizeof(msg),
12233 "commit %s missing from histedit script", id_str);
12234 free(id_str);
12235 return got_error_msg(GOT_ERR_HISTEDIT_CMD, msg);
12239 hle = TAILQ_LAST(histedit_cmds, got_histedit_list);
12240 if (hle && hle->cmd->code == GOT_HISTEDIT_FOLD)
12241 return got_error_msg(GOT_ERR_HISTEDIT_CMD,
12242 "last commit in histedit script cannot be folded");
12244 return NULL;
12247 static const struct got_error *
12248 histedit_run_editor(struct got_histedit_list *histedit_cmds,
12249 const char *editor, const char *path,
12250 struct got_object_id_queue *commits, struct got_repository *repo)
12252 const struct got_error *err = NULL;
12253 struct stat st, st2;
12254 struct timespec timeout;
12255 FILE *f = NULL;
12257 if (stat(path, &st) == -1) {
12258 err = got_error_from_errno2("stat", path);
12259 goto done;
12262 if (spawn_editor(editor, path) == -1) {
12263 err = got_error_from_errno("failed spawning editor");
12264 goto done;
12267 timeout.tv_sec = 0;
12268 timeout.tv_nsec = 1;
12269 nanosleep(&timeout, NULL);
12271 if (stat(path, &st2) == -1) {
12272 err = got_error_from_errno2("stat", path);
12273 goto done;
12276 if (st.st_size == st2.st_size &&
12277 timespeccmp(&st.st_mtim, &st2.st_mtim, ==)) {
12278 err = got_error_msg(GOT_ERR_EMPTY_HISTEDIT,
12279 "no changes made to histedit script, aborting");
12280 goto done;
12283 f = fopen(path, "re");
12284 if (f == NULL) {
12285 err = got_error_from_errno("fopen");
12286 goto done;
12288 err = histedit_parse_list(histedit_cmds, f, repo);
12289 if (err)
12290 goto done;
12292 err = histedit_check_script(histedit_cmds, commits, repo);
12293 done:
12294 if (f && fclose(f) == EOF && err == NULL)
12295 err = got_error_from_errno("fclose");
12296 return err;
12299 static const struct got_error *
12300 histedit_edit_list_retry(struct got_histedit_list *, const struct got_error *,
12301 struct got_object_id_queue *, const char *, const char *, const char *,
12302 struct got_repository *);
12304 static const struct got_error *
12305 histedit_edit_script(struct got_histedit_list *histedit_cmds,
12306 struct got_object_id_queue *commits, const char *branch_name,
12307 int edit_logmsg_only, int fold_only, int drop_only, int edit_only,
12308 const char *editor, struct got_repository *repo)
12310 const struct got_error *err;
12311 FILE *f = NULL;
12312 char *path = NULL;
12314 err = got_opentemp_named(&path, &f, "got-histedit", "");
12315 if (err)
12316 return err;
12318 err = write_cmd_list(f, branch_name, commits);
12319 if (err)
12320 goto done;
12322 err = histedit_write_commit_list(commits, f, edit_logmsg_only,
12323 fold_only, drop_only, edit_only, repo);
12324 if (err)
12325 goto done;
12327 if (drop_only || edit_logmsg_only || fold_only || edit_only) {
12328 rewind(f);
12329 err = histedit_parse_list(histedit_cmds, f, repo);
12330 } else {
12331 if (fclose(f) == EOF) {
12332 err = got_error_from_errno("fclose");
12333 goto done;
12335 f = NULL;
12336 err = histedit_run_editor(histedit_cmds, editor, path,
12337 commits, repo);
12338 if (err) {
12339 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
12340 err->code != GOT_ERR_HISTEDIT_CMD)
12341 goto done;
12342 err = histedit_edit_list_retry(histedit_cmds, err,
12343 commits, editor, path, branch_name, repo);
12346 done:
12347 if (f && fclose(f) == EOF && err == NULL)
12348 err = got_error_from_errno("fclose");
12349 if (path && unlink(path) != 0 && err == NULL)
12350 err = got_error_from_errno2("unlink", path);
12351 free(path);
12352 return err;
12355 static const struct got_error *
12356 histedit_save_list(struct got_histedit_list *histedit_cmds,
12357 struct got_worktree *worktree, struct got_repository *repo)
12359 const struct got_error *err = NULL;
12360 char *path = NULL;
12361 FILE *f = NULL;
12362 struct got_histedit_list_entry *hle;
12364 err = got_worktree_get_histedit_script_path(&path, worktree);
12365 if (err)
12366 return err;
12368 f = fopen(path, "we");
12369 if (f == NULL) {
12370 err = got_error_from_errno2("fopen", path);
12371 goto done;
12373 TAILQ_FOREACH(hle, histedit_cmds, entry) {
12374 err = histedit_write_commit(hle->commit_id, hle->cmd->name, f,
12375 repo);
12376 if (err)
12377 break;
12379 done:
12380 if (f && fclose(f) == EOF && err == NULL)
12381 err = got_error_from_errno("fclose");
12382 free(path);
12383 return err;
12386 static void
12387 histedit_free_list(struct got_histedit_list *histedit_cmds)
12389 struct got_histedit_list_entry *hle;
12391 while ((hle = TAILQ_FIRST(histedit_cmds))) {
12392 TAILQ_REMOVE(histedit_cmds, hle, entry);
12393 free(hle);
12397 static const struct got_error *
12398 histedit_load_list(struct got_histedit_list *histedit_cmds,
12399 const char *path, struct got_repository *repo)
12401 const struct got_error *err = NULL;
12402 FILE *f = NULL;
12404 f = fopen(path, "re");
12405 if (f == NULL) {
12406 err = got_error_from_errno2("fopen", path);
12407 goto done;
12410 err = histedit_parse_list(histedit_cmds, f, repo);
12411 done:
12412 if (f && fclose(f) == EOF && err == NULL)
12413 err = got_error_from_errno("fclose");
12414 return err;
12417 static const struct got_error *
12418 histedit_edit_list_retry(struct got_histedit_list *histedit_cmds,
12419 const struct got_error *edit_err, struct got_object_id_queue *commits,
12420 const char *editor, const char *path, const char *branch_name,
12421 struct got_repository *repo)
12423 const struct got_error *err = NULL, *prev_err = edit_err;
12424 int resp = ' ';
12426 while (resp != 'c' && resp != 'r' && resp != 'a') {
12427 printf("%s: %s\n(c)ontinue editing, (r)estart editing, "
12428 "or (a)bort: ", getprogname(), prev_err->msg);
12429 resp = getchar();
12430 if (resp == '\n')
12431 resp = getchar();
12432 if (resp == 'c') {
12433 histedit_free_list(histedit_cmds);
12434 err = histedit_run_editor(histedit_cmds, editor, path,
12435 commits, repo);
12436 if (err) {
12437 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
12438 err->code != GOT_ERR_HISTEDIT_CMD)
12439 break;
12440 prev_err = err;
12441 resp = ' ';
12442 continue;
12444 break;
12445 } else if (resp == 'r') {
12446 histedit_free_list(histedit_cmds);
12447 err = histedit_edit_script(histedit_cmds,
12448 commits, branch_name, 0, 0, 0, 0, editor, repo);
12449 if (err) {
12450 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
12451 err->code != GOT_ERR_HISTEDIT_CMD)
12452 break;
12453 prev_err = err;
12454 resp = ' ';
12455 continue;
12457 break;
12458 } else if (resp == 'a') {
12459 err = got_error(GOT_ERR_HISTEDIT_CANCEL);
12460 break;
12461 } else
12462 printf("invalid response '%c'\n", resp);
12465 return err;
12468 static const struct got_error *
12469 histedit_complete(struct got_worktree *worktree,
12470 struct got_fileindex *fileindex, struct got_reference *tmp_branch,
12471 struct got_reference *branch, struct got_repository *repo)
12473 printf("Switching work tree to %s\n",
12474 got_ref_get_symref_target(branch));
12475 return got_worktree_histedit_complete(worktree, fileindex, tmp_branch,
12476 branch, repo);
12479 static const struct got_error *
12480 show_histedit_progress(struct got_commit_object *commit,
12481 struct got_histedit_list_entry *hle, struct got_object_id *new_id)
12483 const struct got_error *err;
12484 char *old_id_str = NULL, *new_id_str = NULL, *logmsg = NULL;
12486 err = got_object_id_str(&old_id_str, hle->commit_id);
12487 if (err)
12488 goto done;
12490 if (new_id) {
12491 err = got_object_id_str(&new_id_str, new_id);
12492 if (err)
12493 goto done;
12496 old_id_str[12] = '\0';
12497 if (new_id_str)
12498 new_id_str[12] = '\0';
12500 if (hle->logmsg) {
12501 logmsg = strdup(hle->logmsg);
12502 if (logmsg == NULL) {
12503 err = got_error_from_errno("strdup");
12504 goto done;
12506 trim_logmsg(logmsg, 42);
12507 } else {
12508 err = get_short_logmsg(&logmsg, 42, commit);
12509 if (err)
12510 goto done;
12513 switch (hle->cmd->code) {
12514 case GOT_HISTEDIT_PICK:
12515 case GOT_HISTEDIT_EDIT:
12516 case GOT_HISTEDIT_MESG:
12517 printf("%s -> %s: %s\n", old_id_str,
12518 new_id_str ? new_id_str : "no-op change", logmsg);
12519 break;
12520 case GOT_HISTEDIT_DROP:
12521 case GOT_HISTEDIT_FOLD:
12522 printf("%s -> %s commit: %s\n", old_id_str, hle->cmd->name,
12523 logmsg);
12524 break;
12525 default:
12526 break;
12528 done:
12529 free(old_id_str);
12530 free(new_id_str);
12531 return err;
12534 static const struct got_error *
12535 histedit_commit(struct got_pathlist_head *merged_paths,
12536 struct got_worktree *worktree, struct got_fileindex *fileindex,
12537 struct got_reference *tmp_branch, struct got_histedit_list_entry *hle,
12538 const char *committer, int allow_conflict, const char *editor,
12539 struct got_repository *repo)
12541 const struct got_error *err;
12542 struct got_commit_object *commit;
12543 struct got_object_id *new_commit_id;
12545 if ((hle->cmd->code == GOT_HISTEDIT_EDIT || get_folded_commits(hle))
12546 && hle->logmsg == NULL) {
12547 err = histedit_edit_logmsg(hle, editor, repo);
12548 if (err)
12549 return err;
12552 err = got_object_open_as_commit(&commit, repo, hle->commit_id);
12553 if (err)
12554 return err;
12556 err = got_worktree_histedit_commit(&new_commit_id, merged_paths,
12557 worktree, fileindex, tmp_branch, committer, commit, hle->commit_id,
12558 hle->logmsg, allow_conflict, repo);
12559 if (err) {
12560 if (err->code != GOT_ERR_COMMIT_NO_CHANGES)
12561 goto done;
12562 err = show_histedit_progress(commit, hle, NULL);
12563 } else {
12564 err = show_histedit_progress(commit, hle, new_commit_id);
12565 free(new_commit_id);
12567 done:
12568 got_object_commit_close(commit);
12569 return err;
12572 static const struct got_error *
12573 histedit_skip_commit(struct got_histedit_list_entry *hle,
12574 struct got_worktree *worktree, struct got_repository *repo)
12576 const struct got_error *error;
12577 struct got_commit_object *commit;
12579 error = got_worktree_histedit_skip_commit(worktree, hle->commit_id,
12580 repo);
12581 if (error)
12582 return error;
12584 error = got_object_open_as_commit(&commit, repo, hle->commit_id);
12585 if (error)
12586 return error;
12588 error = show_histedit_progress(commit, hle, NULL);
12589 got_object_commit_close(commit);
12590 return error;
12593 static const struct got_error *
12594 check_local_changes(void *arg, unsigned char status,
12595 unsigned char staged_status, const char *path,
12596 struct got_object_id *blob_id, struct got_object_id *staged_blob_id,
12597 struct got_object_id *commit_id, int dirfd, const char *de_name)
12599 int *have_local_changes = arg;
12601 switch (status) {
12602 case GOT_STATUS_ADD:
12603 case GOT_STATUS_DELETE:
12604 case GOT_STATUS_MODIFY:
12605 case GOT_STATUS_CONFLICT:
12606 *have_local_changes = 1;
12607 return got_error(GOT_ERR_CANCELLED);
12608 default:
12609 break;
12612 switch (staged_status) {
12613 case GOT_STATUS_ADD:
12614 case GOT_STATUS_DELETE:
12615 case GOT_STATUS_MODIFY:
12616 *have_local_changes = 1;
12617 return got_error(GOT_ERR_CANCELLED);
12618 default:
12619 break;
12622 return NULL;
12625 static const struct got_error *
12626 cmd_histedit(int argc, char *argv[])
12628 const struct got_error *error = NULL;
12629 struct got_worktree *worktree = NULL;
12630 struct got_fileindex *fileindex = NULL;
12631 struct got_repository *repo = NULL;
12632 char *cwd = NULL, *committer = NULL, *gitconfig_path = NULL;
12633 struct got_reference *branch = NULL;
12634 struct got_reference *tmp_branch = NULL;
12635 struct got_object_id *resume_commit_id = NULL;
12636 struct got_object_id *base_commit_id = NULL;
12637 struct got_object_id *head_commit_id = NULL;
12638 struct got_commit_object *commit = NULL;
12639 int ch, rebase_in_progress = 0, merge_in_progress = 0;
12640 struct got_update_progress_arg upa;
12641 int edit_in_progress = 0, abort_edit = 0, continue_edit = 0;
12642 int drop_only = 0, edit_logmsg_only = 0, fold_only = 0, edit_only = 0;
12643 int allow_conflict = 0, list_backups = 0, delete_backups = 0;
12644 const char *edit_script_path = NULL;
12645 char *editor = NULL;
12646 struct got_object_id_queue commits;
12647 struct got_pathlist_head merged_paths;
12648 const struct got_object_id_queue *parent_ids;
12649 struct got_object_qid *pid;
12650 struct got_histedit_list histedit_cmds;
12651 struct got_histedit_list_entry *hle;
12652 int *pack_fds = NULL;
12654 STAILQ_INIT(&commits);
12655 TAILQ_INIT(&histedit_cmds);
12656 TAILQ_INIT(&merged_paths);
12657 memset(&upa, 0, sizeof(upa));
12659 #ifndef PROFILE
12660 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
12661 "unveil", NULL) == -1)
12662 err(1, "pledge");
12663 #endif
12665 while ((ch = getopt(argc, argv, "aCcdeF:flmX")) != -1) {
12666 switch (ch) {
12667 case 'a':
12668 abort_edit = 1;
12669 break;
12670 case 'C':
12671 allow_conflict = 1;
12672 break;
12673 case 'c':
12674 continue_edit = 1;
12675 break;
12676 case 'd':
12677 drop_only = 1;
12678 break;
12679 case 'e':
12680 edit_only = 1;
12681 break;
12682 case 'F':
12683 edit_script_path = optarg;
12684 break;
12685 case 'f':
12686 fold_only = 1;
12687 break;
12688 case 'l':
12689 list_backups = 1;
12690 break;
12691 case 'm':
12692 edit_logmsg_only = 1;
12693 break;
12694 case 'X':
12695 delete_backups = 1;
12696 break;
12697 default:
12698 usage_histedit();
12699 /* NOTREACHED */
12703 argc -= optind;
12704 argv += optind;
12706 if (abort_edit && allow_conflict)
12707 option_conflict('a', 'C');
12708 if (abort_edit && continue_edit)
12709 option_conflict('a', 'c');
12710 if (edit_script_path && allow_conflict)
12711 option_conflict('F', 'C');
12712 if (edit_script_path && edit_logmsg_only)
12713 option_conflict('F', 'm');
12714 if (abort_edit && edit_logmsg_only)
12715 option_conflict('a', 'm');
12716 if (edit_logmsg_only && allow_conflict)
12717 option_conflict('m', 'C');
12718 if (continue_edit && edit_logmsg_only)
12719 option_conflict('c', 'm');
12720 if (abort_edit && fold_only)
12721 option_conflict('a', 'f');
12722 if (fold_only && allow_conflict)
12723 option_conflict('f', 'C');
12724 if (continue_edit && fold_only)
12725 option_conflict('c', 'f');
12726 if (fold_only && edit_logmsg_only)
12727 option_conflict('f', 'm');
12728 if (edit_script_path && fold_only)
12729 option_conflict('F', 'f');
12730 if (abort_edit && edit_only)
12731 option_conflict('a', 'e');
12732 if (continue_edit && edit_only)
12733 option_conflict('c', 'e');
12734 if (edit_only && edit_logmsg_only)
12735 option_conflict('e', 'm');
12736 if (edit_script_path && edit_only)
12737 option_conflict('F', 'e');
12738 if (fold_only && edit_only)
12739 option_conflict('f', 'e');
12740 if (drop_only && abort_edit)
12741 option_conflict('d', 'a');
12742 if (drop_only && allow_conflict)
12743 option_conflict('d', 'C');
12744 if (drop_only && continue_edit)
12745 option_conflict('d', 'c');
12746 if (drop_only && edit_logmsg_only)
12747 option_conflict('d', 'm');
12748 if (drop_only && edit_only)
12749 option_conflict('d', 'e');
12750 if (drop_only && edit_script_path)
12751 option_conflict('d', 'F');
12752 if (drop_only && fold_only)
12753 option_conflict('d', 'f');
12754 if (list_backups) {
12755 if (abort_edit)
12756 option_conflict('l', 'a');
12757 if (allow_conflict)
12758 option_conflict('l', 'C');
12759 if (continue_edit)
12760 option_conflict('l', 'c');
12761 if (edit_script_path)
12762 option_conflict('l', 'F');
12763 if (edit_logmsg_only)
12764 option_conflict('l', 'm');
12765 if (drop_only)
12766 option_conflict('l', 'd');
12767 if (fold_only)
12768 option_conflict('l', 'f');
12769 if (edit_only)
12770 option_conflict('l', 'e');
12771 if (delete_backups)
12772 option_conflict('l', 'X');
12773 if (argc != 0 && argc != 1)
12774 usage_histedit();
12775 } else if (delete_backups) {
12776 if (abort_edit)
12777 option_conflict('X', 'a');
12778 if (allow_conflict)
12779 option_conflict('X', 'C');
12780 if (continue_edit)
12781 option_conflict('X', 'c');
12782 if (drop_only)
12783 option_conflict('X', 'd');
12784 if (edit_script_path)
12785 option_conflict('X', 'F');
12786 if (edit_logmsg_only)
12787 option_conflict('X', 'm');
12788 if (fold_only)
12789 option_conflict('X', 'f');
12790 if (edit_only)
12791 option_conflict('X', 'e');
12792 if (list_backups)
12793 option_conflict('X', 'l');
12794 if (argc != 0 && argc != 1)
12795 usage_histedit();
12796 } else if (allow_conflict && !continue_edit)
12797 errx(1, "-C option requires -c");
12798 else if (argc != 0)
12799 usage_histedit();
12801 cwd = getcwd(NULL, 0);
12802 if (cwd == NULL) {
12803 error = got_error_from_errno("getcwd");
12804 goto done;
12807 error = got_repo_pack_fds_open(&pack_fds);
12808 if (error != NULL)
12809 goto done;
12811 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
12812 if (error) {
12813 if (list_backups || delete_backups) {
12814 if (error->code != GOT_ERR_NOT_WORKTREE)
12815 goto done;
12816 } else {
12817 if (error->code == GOT_ERR_NOT_WORKTREE)
12818 error = wrap_not_worktree_error(error,
12819 "histedit", cwd);
12820 goto done;
12824 if (list_backups || delete_backups) {
12825 error = got_repo_open(&repo,
12826 worktree ? got_worktree_get_repo_path(worktree) : cwd,
12827 NULL, pack_fds);
12828 if (error != NULL)
12829 goto done;
12830 error = apply_unveil(got_repo_get_path(repo), 0,
12831 worktree ? got_worktree_get_root_path(worktree) : NULL);
12832 if (error)
12833 goto done;
12834 error = process_backup_refs(
12835 GOT_WORKTREE_HISTEDIT_BACKUP_REF_PREFIX,
12836 argc == 1 ? argv[0] : NULL, delete_backups, repo);
12837 goto done; /* nothing else to do */
12838 } else {
12839 error = get_gitconfig_path(&gitconfig_path);
12840 if (error)
12841 goto done;
12842 error = got_repo_open(&repo,
12843 got_worktree_get_repo_path(worktree), gitconfig_path,
12844 pack_fds);
12845 if (error != NULL)
12846 goto done;
12847 error = get_editor(&editor);
12848 if (error)
12849 goto done;
12850 if (unveil(editor, "x") != 0) {
12851 error = got_error_from_errno2("unveil", editor);
12852 goto done;
12854 if (edit_script_path) {
12855 if (unveil(edit_script_path, "r") != 0) {
12856 error = got_error_from_errno2("unveil",
12857 edit_script_path);
12858 goto done;
12861 error = apply_unveil(got_repo_get_path(repo), 0,
12862 got_worktree_get_root_path(worktree));
12863 if (error)
12864 goto done;
12867 if (worktree != NULL && !list_backups && !delete_backups) {
12868 error = worktree_has_logmsg_ref("histedit", worktree, repo);
12869 if (error)
12870 goto done;
12873 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
12874 if (error)
12875 goto done;
12876 if (rebase_in_progress) {
12877 error = got_error(GOT_ERR_REBASING);
12878 goto done;
12881 error = got_worktree_merge_in_progress(&merge_in_progress, worktree,
12882 repo);
12883 if (error)
12884 goto done;
12885 if (merge_in_progress) {
12886 error = got_error(GOT_ERR_MERGE_BUSY);
12887 goto done;
12890 error = got_worktree_histedit_in_progress(&edit_in_progress, worktree);
12891 if (error)
12892 goto done;
12894 if (edit_in_progress && edit_logmsg_only) {
12895 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
12896 "histedit operation is in progress in this "
12897 "work tree and must be continued or aborted "
12898 "before the -m option can be used");
12899 goto done;
12901 if (edit_in_progress && drop_only) {
12902 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
12903 "histedit operation is in progress in this "
12904 "work tree and must be continued or aborted "
12905 "before the -d option can be used");
12906 goto done;
12908 if (edit_in_progress && fold_only) {
12909 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
12910 "histedit operation is in progress in this "
12911 "work tree and must be continued or aborted "
12912 "before the -f option can be used");
12913 goto done;
12915 if (edit_in_progress && edit_only) {
12916 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
12917 "histedit operation is in progress in this "
12918 "work tree and must be continued or aborted "
12919 "before the -e option can be used");
12920 goto done;
12923 if (edit_in_progress && abort_edit) {
12924 error = got_worktree_histedit_continue(&resume_commit_id,
12925 &tmp_branch, &branch, &base_commit_id, &fileindex,
12926 worktree, repo);
12927 if (error)
12928 goto done;
12929 printf("Switching work tree to %s\n",
12930 got_ref_get_symref_target(branch));
12931 error = got_worktree_histedit_abort(worktree, fileindex, repo,
12932 branch, base_commit_id, abort_progress, &upa);
12933 if (error)
12934 goto done;
12935 printf("Histedit of %s aborted\n",
12936 got_ref_get_symref_target(branch));
12937 print_merge_progress_stats(&upa);
12938 goto done; /* nothing else to do */
12939 } else if (abort_edit) {
12940 error = got_error(GOT_ERR_NOT_HISTEDIT);
12941 goto done;
12944 error = get_author(&committer, repo, worktree);
12945 if (error)
12946 goto done;
12948 if (continue_edit) {
12949 char *path;
12951 if (!edit_in_progress) {
12952 error = got_error(GOT_ERR_NOT_HISTEDIT);
12953 goto done;
12956 error = got_worktree_get_histedit_script_path(&path, worktree);
12957 if (error)
12958 goto done;
12960 error = histedit_load_list(&histedit_cmds, path, repo);
12961 free(path);
12962 if (error)
12963 goto done;
12965 error = got_worktree_histedit_continue(&resume_commit_id,
12966 &tmp_branch, &branch, &base_commit_id, &fileindex,
12967 worktree, repo);
12968 if (error)
12969 goto done;
12971 error = got_ref_resolve(&head_commit_id, repo, branch);
12972 if (error)
12973 goto done;
12975 error = got_object_open_as_commit(&commit, repo,
12976 head_commit_id);
12977 if (error)
12978 goto done;
12979 parent_ids = got_object_commit_get_parent_ids(commit);
12980 pid = STAILQ_FIRST(parent_ids);
12981 if (pid == NULL) {
12982 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
12983 goto done;
12985 error = collect_commits(&commits, head_commit_id, &pid->id,
12986 base_commit_id, got_worktree_get_path_prefix(worktree),
12987 GOT_ERR_HISTEDIT_PATH, repo);
12988 got_object_commit_close(commit);
12989 commit = NULL;
12990 if (error)
12991 goto done;
12992 } else {
12993 if (edit_in_progress) {
12994 error = got_error(GOT_ERR_HISTEDIT_BUSY);
12995 goto done;
12998 error = got_ref_open(&branch, repo,
12999 got_worktree_get_head_ref_name(worktree), 0);
13000 if (error != NULL)
13001 goto done;
13003 if (strncmp(got_ref_get_name(branch), "refs/heads/", 11) != 0) {
13004 error = got_error_msg(GOT_ERR_COMMIT_BRANCH,
13005 "will not edit commit history of a branch outside "
13006 "the \"refs/heads/\" reference namespace");
13007 goto done;
13010 error = got_ref_resolve(&head_commit_id, repo, branch);
13011 got_ref_close(branch);
13012 branch = NULL;
13013 if (error)
13014 goto done;
13016 error = got_object_open_as_commit(&commit, repo,
13017 head_commit_id);
13018 if (error)
13019 goto done;
13020 parent_ids = got_object_commit_get_parent_ids(commit);
13021 pid = STAILQ_FIRST(parent_ids);
13022 if (pid == NULL) {
13023 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
13024 goto done;
13026 error = collect_commits(&commits, head_commit_id, &pid->id,
13027 got_worktree_get_base_commit_id(worktree),
13028 got_worktree_get_path_prefix(worktree),
13029 GOT_ERR_HISTEDIT_PATH, repo);
13030 got_object_commit_close(commit);
13031 commit = NULL;
13032 if (error)
13033 goto done;
13035 if (STAILQ_EMPTY(&commits)) {
13036 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
13037 goto done;
13040 error = got_worktree_histedit_prepare(&tmp_branch, &branch,
13041 &base_commit_id, &fileindex, worktree, repo);
13042 if (error)
13043 goto done;
13045 if (edit_script_path) {
13046 error = histedit_load_list(&histedit_cmds,
13047 edit_script_path, repo);
13048 if (error) {
13049 got_worktree_histedit_abort(worktree, fileindex,
13050 repo, branch, base_commit_id,
13051 abort_progress, &upa);
13052 print_merge_progress_stats(&upa);
13053 goto done;
13055 } else {
13056 const char *branch_name;
13057 branch_name = got_ref_get_symref_target(branch);
13058 if (strncmp(branch_name, "refs/heads/", 11) == 0)
13059 branch_name += 11;
13060 error = histedit_edit_script(&histedit_cmds, &commits,
13061 branch_name, edit_logmsg_only, fold_only,
13062 drop_only, edit_only, editor, repo);
13063 if (error) {
13064 got_worktree_histedit_abort(worktree, fileindex,
13065 repo, branch, base_commit_id,
13066 abort_progress, &upa);
13067 print_merge_progress_stats(&upa);
13068 goto done;
13073 error = histedit_save_list(&histedit_cmds, worktree,
13074 repo);
13075 if (error) {
13076 got_worktree_histedit_abort(worktree, fileindex,
13077 repo, branch, base_commit_id,
13078 abort_progress, &upa);
13079 print_merge_progress_stats(&upa);
13080 goto done;
13085 error = histedit_check_script(&histedit_cmds, &commits, repo);
13086 if (error)
13087 goto done;
13089 TAILQ_FOREACH(hle, &histedit_cmds, entry) {
13090 if (resume_commit_id) {
13091 if (got_object_id_cmp(hle->commit_id,
13092 resume_commit_id) != 0)
13093 continue;
13095 resume_commit_id = NULL;
13096 if (hle->cmd->code == GOT_HISTEDIT_DROP ||
13097 hle->cmd->code == GOT_HISTEDIT_FOLD) {
13098 error = histedit_skip_commit(hle, worktree,
13099 repo);
13100 if (error)
13101 goto done;
13102 } else {
13103 struct got_pathlist_head paths;
13104 int have_changes = 0;
13106 TAILQ_INIT(&paths);
13107 error = got_pathlist_append(&paths, "", NULL);
13108 if (error)
13109 goto done;
13110 error = got_worktree_status(worktree, &paths,
13111 repo, 0, check_local_changes, &have_changes,
13112 check_cancelled, NULL);
13113 got_pathlist_free(&paths,
13114 GOT_PATHLIST_FREE_NONE);
13115 if (error) {
13116 if (error->code != GOT_ERR_CANCELLED)
13117 goto done;
13118 if (sigint_received || sigpipe_received)
13119 goto done;
13121 if (have_changes) {
13122 error = histedit_commit(NULL, worktree,
13123 fileindex, tmp_branch, hle,
13124 committer, allow_conflict, editor,
13125 repo);
13126 if (error)
13127 goto done;
13128 } else {
13129 error = got_object_open_as_commit(
13130 &commit, repo, hle->commit_id);
13131 if (error)
13132 goto done;
13133 error = show_histedit_progress(commit,
13134 hle, NULL);
13135 got_object_commit_close(commit);
13136 commit = NULL;
13137 if (error)
13138 goto done;
13141 continue;
13144 if (hle->cmd->code == GOT_HISTEDIT_DROP) {
13145 error = histedit_skip_commit(hle, worktree, repo);
13146 if (error)
13147 goto done;
13148 continue;
13150 error = got_object_open_as_commit(&commit, repo,
13151 hle->commit_id);
13152 if (error)
13153 goto done;
13154 parent_ids = got_object_commit_get_parent_ids(commit);
13155 pid = STAILQ_FIRST(parent_ids);
13157 error = got_worktree_histedit_merge_files(&merged_paths,
13158 worktree, fileindex, &pid->id, hle->commit_id, repo,
13159 update_progress, &upa, check_cancelled, NULL);
13160 if (error)
13161 goto done;
13162 got_object_commit_close(commit);
13163 commit = NULL;
13165 print_merge_progress_stats(&upa);
13166 if (upa.conflicts > 0 || upa.missing > 0 ||
13167 upa.not_deleted > 0 || upa.unversioned > 0) {
13168 if (upa.conflicts > 0) {
13169 error = show_rebase_merge_conflict(
13170 hle->commit_id, repo);
13171 if (error)
13172 goto done;
13174 got_pathlist_free(&merged_paths, GOT_PATHLIST_FREE_PATH);
13175 break;
13178 if (hle->cmd->code == GOT_HISTEDIT_EDIT) {
13179 char *id_str;
13180 error = got_object_id_str(&id_str, hle->commit_id);
13181 if (error)
13182 goto done;
13183 printf("Stopping histedit for amending commit %s\n",
13184 id_str);
13185 free(id_str);
13186 got_pathlist_free(&merged_paths, GOT_PATHLIST_FREE_PATH);
13187 error = got_worktree_histedit_postpone(worktree,
13188 fileindex);
13189 goto done;
13190 } else if (hle->cmd->code == GOT_HISTEDIT_FOLD) {
13191 error = histedit_skip_commit(hle, worktree, repo);
13192 if (error)
13193 goto done;
13194 continue;
13195 } else if (hle->cmd->code == GOT_HISTEDIT_MESG) {
13196 error = histedit_edit_logmsg(hle, editor, repo);
13197 if (error)
13198 goto done;
13201 error = histedit_commit(&merged_paths, worktree, fileindex,
13202 tmp_branch, hle, committer, allow_conflict, editor, repo);
13203 got_pathlist_free(&merged_paths, GOT_PATHLIST_FREE_PATH);
13204 if (error)
13205 goto done;
13208 if (upa.conflicts > 0 || upa.missing > 0 ||
13209 upa.not_deleted > 0 || upa.unversioned > 0) {
13210 error = got_worktree_histedit_postpone(worktree, fileindex);
13211 if (error)
13212 goto done;
13213 if (upa.conflicts > 0 && upa.missing == 0 &&
13214 upa.not_deleted == 0 && upa.unversioned == 0) {
13215 error = got_error_msg(GOT_ERR_CONFLICTS,
13216 "conflicts must be resolved before histedit "
13217 "can continue");
13218 } else if (upa.conflicts > 0) {
13219 error = got_error_msg(GOT_ERR_CONFLICTS,
13220 "conflicts must be resolved before histedit "
13221 "can continue; changes destined for some "
13222 "files were not yet merged and should be "
13223 "merged manually if required before the "
13224 "histedit operation is continued");
13225 } else {
13226 error = got_error_msg(GOT_ERR_CONFLICTS,
13227 "changes destined for some files were not "
13228 "yet merged and should be merged manually "
13229 "if required before the histedit operation "
13230 "is continued");
13232 } else
13233 error = histedit_complete(worktree, fileindex, tmp_branch,
13234 branch, repo);
13235 done:
13236 free(cwd);
13237 free(editor);
13238 free(committer);
13239 free(gitconfig_path);
13240 got_object_id_queue_free(&commits);
13241 histedit_free_list(&histedit_cmds);
13242 free(head_commit_id);
13243 free(base_commit_id);
13244 free(resume_commit_id);
13245 if (commit)
13246 got_object_commit_close(commit);
13247 if (branch)
13248 got_ref_close(branch);
13249 if (tmp_branch)
13250 got_ref_close(tmp_branch);
13251 if (worktree)
13252 got_worktree_close(worktree);
13253 if (repo) {
13254 const struct got_error *close_err = got_repo_close(repo);
13255 if (error == NULL)
13256 error = close_err;
13258 if (pack_fds) {
13259 const struct got_error *pack_err =
13260 got_repo_pack_fds_close(pack_fds);
13261 if (error == NULL)
13262 error = pack_err;
13264 return error;
13267 __dead static void
13268 usage_integrate(void)
13270 fprintf(stderr, "usage: %s integrate branch\n", getprogname());
13271 exit(1);
13274 static const struct got_error *
13275 cmd_integrate(int argc, char *argv[])
13277 const struct got_error *error = NULL;
13278 struct got_repository *repo = NULL;
13279 struct got_worktree *worktree = NULL;
13280 char *cwd = NULL, *refname = NULL, *base_refname = NULL;
13281 const char *branch_arg = NULL;
13282 struct got_reference *branch_ref = NULL, *base_branch_ref = NULL;
13283 struct got_fileindex *fileindex = NULL;
13284 struct got_object_id *commit_id = NULL, *base_commit_id = NULL;
13285 int ch;
13286 struct got_update_progress_arg upa;
13287 int *pack_fds = NULL;
13289 #ifndef PROFILE
13290 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
13291 "unveil", NULL) == -1)
13292 err(1, "pledge");
13293 #endif
13295 while ((ch = getopt(argc, argv, "")) != -1) {
13296 switch (ch) {
13297 default:
13298 usage_integrate();
13299 /* NOTREACHED */
13303 argc -= optind;
13304 argv += optind;
13306 if (argc != 1)
13307 usage_integrate();
13308 branch_arg = argv[0];
13310 cwd = getcwd(NULL, 0);
13311 if (cwd == NULL) {
13312 error = got_error_from_errno("getcwd");
13313 goto done;
13316 error = got_repo_pack_fds_open(&pack_fds);
13317 if (error != NULL)
13318 goto done;
13320 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
13321 if (error) {
13322 if (error->code == GOT_ERR_NOT_WORKTREE)
13323 error = wrap_not_worktree_error(error, "integrate",
13324 cwd);
13325 goto done;
13328 error = check_rebase_or_histedit_in_progress(worktree);
13329 if (error)
13330 goto done;
13332 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
13333 NULL, pack_fds);
13334 if (error != NULL)
13335 goto done;
13337 error = apply_unveil(got_repo_get_path(repo), 0,
13338 got_worktree_get_root_path(worktree));
13339 if (error)
13340 goto done;
13342 error = check_merge_in_progress(worktree, repo);
13343 if (error)
13344 goto done;
13346 if (asprintf(&refname, "refs/heads/%s", branch_arg) == -1) {
13347 error = got_error_from_errno("asprintf");
13348 goto done;
13351 error = got_worktree_integrate_prepare(&fileindex, &branch_ref,
13352 &base_branch_ref, worktree, refname, repo);
13353 if (error)
13354 goto done;
13356 refname = strdup(got_ref_get_name(branch_ref));
13357 if (refname == NULL) {
13358 error = got_error_from_errno("strdup");
13359 got_worktree_integrate_abort(worktree, fileindex, repo,
13360 branch_ref, base_branch_ref);
13361 goto done;
13363 base_refname = strdup(got_ref_get_name(base_branch_ref));
13364 if (base_refname == NULL) {
13365 error = got_error_from_errno("strdup");
13366 got_worktree_integrate_abort(worktree, fileindex, repo,
13367 branch_ref, base_branch_ref);
13368 goto done;
13370 if (strncmp(base_refname, "refs/heads/", 11) != 0) {
13371 error = got_error(GOT_ERR_INTEGRATE_BRANCH);
13372 got_worktree_integrate_abort(worktree, fileindex, repo,
13373 branch_ref, base_branch_ref);
13374 goto done;
13377 error = got_ref_resolve(&commit_id, repo, branch_ref);
13378 if (error)
13379 goto done;
13381 error = got_ref_resolve(&base_commit_id, repo, base_branch_ref);
13382 if (error)
13383 goto done;
13385 if (got_object_id_cmp(commit_id, base_commit_id) == 0) {
13386 error = got_error_msg(GOT_ERR_SAME_BRANCH,
13387 "specified branch has already been integrated");
13388 got_worktree_integrate_abort(worktree, fileindex, repo,
13389 branch_ref, base_branch_ref);
13390 goto done;
13393 error = check_linear_ancestry(commit_id, base_commit_id, 1, repo);
13394 if (error) {
13395 if (error->code == GOT_ERR_ANCESTRY)
13396 error = got_error(GOT_ERR_REBASE_REQUIRED);
13397 got_worktree_integrate_abort(worktree, fileindex, repo,
13398 branch_ref, base_branch_ref);
13399 goto done;
13402 memset(&upa, 0, sizeof(upa));
13403 error = got_worktree_integrate_continue(worktree, fileindex, repo,
13404 branch_ref, base_branch_ref, update_progress, &upa,
13405 check_cancelled, NULL);
13406 if (error)
13407 goto done;
13409 printf("Integrated %s into %s\n", refname, base_refname);
13410 print_update_progress_stats(&upa);
13411 done:
13412 if (repo) {
13413 const struct got_error *close_err = got_repo_close(repo);
13414 if (error == NULL)
13415 error = close_err;
13417 if (worktree)
13418 got_worktree_close(worktree);
13419 if (pack_fds) {
13420 const struct got_error *pack_err =
13421 got_repo_pack_fds_close(pack_fds);
13422 if (error == NULL)
13423 error = pack_err;
13425 free(cwd);
13426 free(base_commit_id);
13427 free(commit_id);
13428 free(refname);
13429 free(base_refname);
13430 return error;
13433 __dead static void
13434 usage_merge(void)
13436 fprintf(stderr, "usage: %s merge [-aCcn] [branch]\n", getprogname());
13437 exit(1);
13440 static const struct got_error *
13441 cmd_merge(int argc, char *argv[])
13443 const struct got_error *error = NULL;
13444 struct got_worktree *worktree = NULL;
13445 struct got_repository *repo = NULL;
13446 struct got_fileindex *fileindex = NULL;
13447 char *cwd = NULL, *id_str = NULL, *author = NULL;
13448 char *gitconfig_path = NULL;
13449 struct got_reference *branch = NULL, *wt_branch = NULL;
13450 struct got_object_id *branch_tip = NULL, *yca_id = NULL;
13451 struct got_object_id *wt_branch_tip = NULL;
13452 int ch, merge_in_progress = 0, abort_merge = 0, continue_merge = 0;
13453 int allow_conflict = 0, prefer_fast_forward = 1, interrupt_merge = 0;
13454 struct got_update_progress_arg upa;
13455 struct got_object_id *merge_commit_id = NULL;
13456 char *branch_name = NULL;
13457 int *pack_fds = NULL;
13459 memset(&upa, 0, sizeof(upa));
13461 #ifndef PROFILE
13462 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
13463 "unveil", NULL) == -1)
13464 err(1, "pledge");
13465 #endif
13467 while ((ch = getopt(argc, argv, "aCcMn")) != -1) {
13468 switch (ch) {
13469 case 'a':
13470 abort_merge = 1;
13471 break;
13472 case 'C':
13473 allow_conflict = 1;
13474 break;
13475 case 'c':
13476 continue_merge = 1;
13477 break;
13478 case 'M':
13479 prefer_fast_forward = 0;
13480 break;
13481 case 'n':
13482 interrupt_merge = 1;
13483 break;
13484 default:
13485 usage_merge();
13486 /* NOTREACHED */
13490 argc -= optind;
13491 argv += optind;
13493 if (abort_merge) {
13494 if (continue_merge)
13495 option_conflict('a', 'c');
13496 if (!prefer_fast_forward)
13497 option_conflict('a', 'M');
13498 if (interrupt_merge)
13499 option_conflict('a', 'n');
13500 } else if (continue_merge) {
13501 if (!prefer_fast_forward)
13502 option_conflict('c', 'M');
13503 if (interrupt_merge)
13504 option_conflict('c', 'n');
13506 if (allow_conflict) {
13507 if (!continue_merge)
13508 errx(1, "-C option requires -c");
13510 if (abort_merge || continue_merge) {
13511 if (argc != 0)
13512 usage_merge();
13513 } else if (argc != 1)
13514 usage_merge();
13516 cwd = getcwd(NULL, 0);
13517 if (cwd == NULL) {
13518 error = got_error_from_errno("getcwd");
13519 goto done;
13522 error = got_repo_pack_fds_open(&pack_fds);
13523 if (error != NULL)
13524 goto done;
13526 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
13527 if (error) {
13528 if (error->code == GOT_ERR_NOT_WORKTREE)
13529 error = wrap_not_worktree_error(error,
13530 "merge", cwd);
13531 goto done;
13534 error = get_gitconfig_path(&gitconfig_path);
13535 if (error)
13536 goto done;
13537 error = got_repo_open(&repo,
13538 worktree ? got_worktree_get_repo_path(worktree) : cwd,
13539 gitconfig_path, pack_fds);
13540 if (error != NULL)
13541 goto done;
13543 if (worktree != NULL) {
13544 error = worktree_has_logmsg_ref("merge", worktree, repo);
13545 if (error)
13546 goto done;
13549 error = apply_unveil(got_repo_get_path(repo), 0,
13550 worktree ? got_worktree_get_root_path(worktree) : NULL);
13551 if (error)
13552 goto done;
13554 error = check_rebase_or_histedit_in_progress(worktree);
13555 if (error)
13556 goto done;
13558 error = got_worktree_merge_in_progress(&merge_in_progress, worktree,
13559 repo);
13560 if (error)
13561 goto done;
13563 if (merge_in_progress && !(abort_merge || continue_merge)) {
13564 error = got_error(GOT_ERR_MERGE_BUSY);
13565 goto done;
13568 if (!merge_in_progress && (abort_merge || continue_merge)) {
13569 error = got_error(GOT_ERR_NOT_MERGING);
13570 goto done;
13573 if (abort_merge) {
13574 error = got_worktree_merge_continue(&branch_name,
13575 &branch_tip, &fileindex, worktree, repo);
13576 if (error)
13577 goto done;
13578 error = got_worktree_merge_abort(worktree, fileindex, repo,
13579 abort_progress, &upa);
13580 if (error)
13581 goto done;
13582 printf("Merge of %s aborted\n", branch_name);
13583 goto done; /* nothing else to do */
13586 if (strncmp(got_worktree_get_head_ref_name(worktree),
13587 "refs/heads/", 11) != 0) {
13588 error = got_error_fmt(GOT_ERR_COMMIT_BRANCH,
13589 "work tree's current branch %s is outside the "
13590 "\"refs/heads/\" reference namespace; "
13591 "update -b required",
13592 got_worktree_get_head_ref_name(worktree));
13593 goto done;
13596 error = get_author(&author, repo, worktree);
13597 if (error)
13598 goto done;
13600 error = got_ref_open(&wt_branch, repo,
13601 got_worktree_get_head_ref_name(worktree), 0);
13602 if (error)
13603 goto done;
13604 error = got_ref_resolve(&wt_branch_tip, repo, wt_branch);
13605 if (error)
13606 goto done;
13608 if (continue_merge) {
13609 struct got_object_id *base_commit_id;
13610 base_commit_id = got_worktree_get_base_commit_id(worktree);
13611 if (got_object_id_cmp(wt_branch_tip, base_commit_id) != 0) {
13612 error = got_error(GOT_ERR_MERGE_COMMIT_OUT_OF_DATE);
13613 goto done;
13615 error = got_worktree_merge_continue(&branch_name,
13616 &branch_tip, &fileindex, worktree, repo);
13617 if (error)
13618 goto done;
13619 } else {
13620 error = got_ref_open(&branch, repo, argv[0], 0);
13621 if (error != NULL)
13622 goto done;
13623 branch_name = strdup(got_ref_get_name(branch));
13624 if (branch_name == NULL) {
13625 error = got_error_from_errno("strdup");
13626 goto done;
13628 error = got_ref_resolve(&branch_tip, repo, branch);
13629 if (error)
13630 goto done;
13633 error = got_commit_graph_find_youngest_common_ancestor(&yca_id,
13634 wt_branch_tip, branch_tip, 0, 0, repo,
13635 check_cancelled, NULL);
13636 if (error && error->code != GOT_ERR_ANCESTRY)
13637 goto done;
13639 if (!continue_merge) {
13640 error = check_path_prefix(wt_branch_tip, branch_tip,
13641 got_worktree_get_path_prefix(worktree),
13642 GOT_ERR_MERGE_PATH, repo);
13643 if (error)
13644 goto done;
13645 error = got_worktree_merge_prepare(&fileindex, worktree, repo);
13646 if (error)
13647 goto done;
13648 if (prefer_fast_forward && yca_id &&
13649 got_object_id_cmp(wt_branch_tip, yca_id) == 0) {
13650 struct got_pathlist_head paths;
13651 if (interrupt_merge) {
13652 error = got_error_fmt(GOT_ERR_BAD_OPTION,
13653 "there are no changes to merge since %s "
13654 "is already based on %s; merge cannot be "
13655 "interrupted for amending; -n",
13656 branch_name, got_ref_get_name(wt_branch));
13657 goto done;
13659 printf("Forwarding %s to %s\n",
13660 got_ref_get_name(wt_branch), branch_name);
13661 error = got_ref_change_ref(wt_branch, branch_tip);
13662 if (error)
13663 goto done;
13664 error = got_ref_write(wt_branch, repo);
13665 if (error)
13666 goto done;
13667 error = got_worktree_set_base_commit_id(worktree, repo,
13668 branch_tip);
13669 if (error)
13670 goto done;
13671 TAILQ_INIT(&paths);
13672 error = got_pathlist_append(&paths, "", NULL);
13673 if (error)
13674 goto done;
13675 error = got_worktree_checkout_files(worktree,
13676 &paths, repo, update_progress, &upa,
13677 check_cancelled, NULL);
13678 got_pathlist_free(&paths, GOT_PATHLIST_FREE_NONE);
13679 if (error)
13680 goto done;
13681 if (upa.did_something) {
13682 char *id_str;
13683 error = got_object_id_str(&id_str, branch_tip);
13684 if (error)
13685 goto done;
13686 printf("Updated to commit %s\n", id_str);
13687 free(id_str);
13688 } else
13689 printf("Already up-to-date\n");
13690 print_update_progress_stats(&upa);
13691 goto done;
13693 error = got_worktree_merge_write_refs(worktree, branch, repo);
13694 if (error)
13695 goto done;
13697 error = got_worktree_merge_branch(worktree, fileindex,
13698 yca_id, branch_tip, repo, update_progress, &upa,
13699 check_cancelled, NULL);
13700 if (error)
13701 goto done;
13702 print_merge_progress_stats(&upa);
13703 if (!upa.did_something) {
13704 error = got_worktree_merge_abort(worktree, fileindex,
13705 repo, abort_progress, &upa);
13706 if (error)
13707 goto done;
13708 printf("Already up-to-date\n");
13709 goto done;
13713 if (interrupt_merge) {
13714 error = got_worktree_merge_postpone(worktree, fileindex);
13715 if (error)
13716 goto done;
13717 printf("Merge of %s interrupted on request\n", branch_name);
13718 } else if (upa.conflicts > 0 || upa.missing > 0 ||
13719 upa.not_deleted > 0 || upa.unversioned > 0) {
13720 error = got_worktree_merge_postpone(worktree, fileindex);
13721 if (error)
13722 goto done;
13723 if (upa.conflicts > 0 && upa.missing == 0 &&
13724 upa.not_deleted == 0 && upa.unversioned == 0) {
13725 error = got_error_msg(GOT_ERR_CONFLICTS,
13726 "conflicts must be resolved before merging "
13727 "can continue");
13728 } else if (upa.conflicts > 0) {
13729 error = got_error_msg(GOT_ERR_CONFLICTS,
13730 "conflicts must be resolved before merging "
13731 "can continue; changes destined for some "
13732 "files were not yet merged and "
13733 "should be merged manually if required before the "
13734 "merge operation is continued");
13735 } else {
13736 error = got_error_msg(GOT_ERR_CONFLICTS,
13737 "changes destined for some "
13738 "files were not yet merged and should be "
13739 "merged manually if required before the "
13740 "merge operation is continued");
13742 goto done;
13743 } else {
13744 error = got_worktree_merge_commit(&merge_commit_id, worktree,
13745 fileindex, author, NULL, 1, branch_tip, branch_name,
13746 allow_conflict, repo, continue_merge ? print_status : NULL,
13747 NULL);
13748 if (error)
13749 goto done;
13750 error = got_worktree_merge_complete(worktree, fileindex, repo);
13751 if (error)
13752 goto done;
13753 error = got_object_id_str(&id_str, merge_commit_id);
13754 if (error)
13755 goto done;
13756 printf("Merged %s into %s: %s\n", branch_name,
13757 got_worktree_get_head_ref_name(worktree),
13758 id_str);
13761 done:
13762 free(gitconfig_path);
13763 free(id_str);
13764 free(merge_commit_id);
13765 free(author);
13766 free(branch_tip);
13767 free(branch_name);
13768 free(yca_id);
13769 if (branch)
13770 got_ref_close(branch);
13771 if (wt_branch)
13772 got_ref_close(wt_branch);
13773 if (worktree)
13774 got_worktree_close(worktree);
13775 if (repo) {
13776 const struct got_error *close_err = got_repo_close(repo);
13777 if (error == NULL)
13778 error = close_err;
13780 if (pack_fds) {
13781 const struct got_error *pack_err =
13782 got_repo_pack_fds_close(pack_fds);
13783 if (error == NULL)
13784 error = pack_err;
13786 return error;
13789 __dead static void
13790 usage_stage(void)
13792 fprintf(stderr, "usage: %s stage [-lpRS] [-F response-script] "
13793 "[path ...]\n", getprogname());
13794 exit(1);
13797 static const struct got_error *
13798 print_stage(void *arg, unsigned char status, unsigned char staged_status,
13799 const char *path, struct got_object_id *blob_id,
13800 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
13801 int dirfd, const char *de_name)
13803 const struct got_error *err = NULL;
13804 char *id_str = NULL;
13806 if (staged_status != GOT_STATUS_ADD &&
13807 staged_status != GOT_STATUS_MODIFY &&
13808 staged_status != GOT_STATUS_DELETE)
13809 return NULL;
13811 if (staged_status == GOT_STATUS_ADD ||
13812 staged_status == GOT_STATUS_MODIFY)
13813 err = got_object_id_str(&id_str, staged_blob_id);
13814 else
13815 err = got_object_id_str(&id_str, blob_id);
13816 if (err)
13817 return err;
13819 printf("%s %c %s\n", id_str, staged_status, path);
13820 free(id_str);
13821 return NULL;
13824 static const struct got_error *
13825 cmd_stage(int argc, char *argv[])
13827 const struct got_error *error = NULL;
13828 struct got_repository *repo = NULL;
13829 struct got_worktree *worktree = NULL;
13830 char *cwd = NULL;
13831 struct got_pathlist_head paths;
13832 int ch, contains_dir;
13833 int can_recurse = 0, list_stage = 0, pflag = 0, allow_bad_symlinks = 0;
13834 FILE *patch_script_file = NULL;
13835 const char *patch_script_path = NULL;
13836 struct choose_patch_arg cpa;
13837 int *pack_fds = NULL;
13839 TAILQ_INIT(&paths);
13841 #ifndef PROFILE
13842 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
13843 "unveil", NULL) == -1)
13844 err(1, "pledge");
13845 #endif
13847 while ((ch = getopt(argc, argv, "F:lpRS")) != -1) {
13848 switch (ch) {
13849 case 'F':
13850 patch_script_path = optarg;
13851 break;
13852 case 'l':
13853 list_stage = 1;
13854 break;
13855 case 'p':
13856 pflag = 1;
13857 break;
13858 case 'R':
13859 can_recurse = 1;
13860 break;
13861 case 'S':
13862 allow_bad_symlinks = 1;
13863 break;
13864 default:
13865 usage_stage();
13866 /* NOTREACHED */
13870 argc -= optind;
13871 argv += optind;
13873 if (list_stage && (pflag || patch_script_path))
13874 errx(1, "-l option cannot be used with other options");
13875 if (patch_script_path && !pflag)
13876 errx(1, "-F option can only be used together with -p option");
13878 cwd = getcwd(NULL, 0);
13879 if (cwd == NULL) {
13880 error = got_error_from_errno("getcwd");
13881 goto done;
13884 error = got_repo_pack_fds_open(&pack_fds);
13885 if (error != NULL)
13886 goto done;
13888 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
13889 if (error) {
13890 if (error->code == GOT_ERR_NOT_WORKTREE)
13891 error = wrap_not_worktree_error(error, "stage", cwd);
13892 goto done;
13895 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
13896 NULL, pack_fds);
13897 if (error != NULL)
13898 goto done;
13900 if (patch_script_path) {
13901 patch_script_file = fopen(patch_script_path, "re");
13902 if (patch_script_file == NULL) {
13903 error = got_error_from_errno2("fopen",
13904 patch_script_path);
13905 goto done;
13908 error = apply_unveil(got_repo_get_path(repo), 0,
13909 got_worktree_get_root_path(worktree));
13910 if (error)
13911 goto done;
13913 error = check_merge_in_progress(worktree, repo);
13914 if (error)
13915 goto done;
13917 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
13918 if (error)
13919 goto done;
13921 if (list_stage)
13922 error = got_worktree_status(worktree, &paths, repo, 0,
13923 print_stage, NULL, check_cancelled, NULL);
13924 else {
13925 if (!can_recurse) {
13926 error = check_paths_contains_dir(&contains_dir,
13927 worktree, &paths);
13928 if (error != NULL)
13929 goto done;
13931 if (contains_dir) {
13932 error = got_error_msg(GOT_ERR_BAD_PATH,
13933 "staging directories requires -R option");
13934 goto done;
13937 cpa.patch_script_file = patch_script_file;
13938 cpa.action = "stage";
13939 error = got_worktree_stage(worktree, &paths,
13940 pflag ? NULL : print_status, NULL,
13941 pflag ? choose_patch : NULL, &cpa,
13942 allow_bad_symlinks, repo);
13944 done:
13945 if (patch_script_file && fclose(patch_script_file) == EOF &&
13946 error == NULL)
13947 error = got_error_from_errno2("fclose", patch_script_path);
13948 if (repo) {
13949 const struct got_error *close_err = got_repo_close(repo);
13950 if (error == NULL)
13951 error = close_err;
13953 if (worktree)
13954 got_worktree_close(worktree);
13955 if (pack_fds) {
13956 const struct got_error *pack_err =
13957 got_repo_pack_fds_close(pack_fds);
13958 if (error == NULL)
13959 error = pack_err;
13961 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
13962 free(cwd);
13963 return error;
13966 __dead static void
13967 usage_unstage(void)
13969 fprintf(stderr, "usage: %s unstage [-pR] [-F response-script] "
13970 "[path ...]\n", getprogname());
13971 exit(1);
13975 static const struct got_error *
13976 cmd_unstage(int argc, char *argv[])
13978 const struct got_error *error = NULL;
13979 struct got_repository *repo = NULL;
13980 struct got_worktree *worktree = NULL;
13981 char *cwd = NULL;
13982 struct got_pathlist_head paths;
13983 int ch, contains_dir, can_recurse = 0, pflag = 0;
13984 struct got_update_progress_arg upa;
13985 FILE *patch_script_file = NULL;
13986 const char *patch_script_path = NULL;
13987 struct choose_patch_arg cpa;
13988 int *pack_fds = NULL;
13990 TAILQ_INIT(&paths);
13992 #ifndef PROFILE
13993 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
13994 "unveil", NULL) == -1)
13995 err(1, "pledge");
13996 #endif
13998 while ((ch = getopt(argc, argv, "F:Rp")) != -1) {
13999 switch (ch) {
14000 case 'F':
14001 patch_script_path = optarg;
14002 break;
14003 case 'R':
14004 can_recurse = 1;
14005 break;
14006 case 'p':
14007 pflag = 1;
14008 break;
14009 default:
14010 usage_unstage();
14011 /* NOTREACHED */
14015 argc -= optind;
14016 argv += optind;
14018 if (patch_script_path && !pflag)
14019 errx(1, "-F option can only be used together with -p option");
14021 cwd = getcwd(NULL, 0);
14022 if (cwd == NULL) {
14023 error = got_error_from_errno("getcwd");
14024 goto done;
14027 error = got_repo_pack_fds_open(&pack_fds);
14028 if (error != NULL)
14029 goto done;
14031 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
14032 if (error) {
14033 if (error->code == GOT_ERR_NOT_WORKTREE)
14034 error = wrap_not_worktree_error(error, "unstage", cwd);
14035 goto done;
14038 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
14039 NULL, pack_fds);
14040 if (error != NULL)
14041 goto done;
14043 if (patch_script_path) {
14044 patch_script_file = fopen(patch_script_path, "re");
14045 if (patch_script_file == NULL) {
14046 error = got_error_from_errno2("fopen",
14047 patch_script_path);
14048 goto done;
14052 error = apply_unveil(got_repo_get_path(repo), 0,
14053 got_worktree_get_root_path(worktree));
14054 if (error)
14055 goto done;
14057 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
14058 if (error)
14059 goto done;
14061 if (!can_recurse) {
14062 error = check_paths_contains_dir(&contains_dir,
14063 worktree, &paths);
14064 if (error != NULL)
14065 goto done;
14067 if (contains_dir) {
14068 error = got_error_msg(GOT_ERR_BAD_PATH,
14069 "unstaging directories requires -R option");
14070 goto done;
14074 cpa.patch_script_file = patch_script_file;
14075 cpa.action = "unstage";
14076 memset(&upa, 0, sizeof(upa));
14077 error = got_worktree_unstage(worktree, &paths, update_progress,
14078 &upa, pflag ? choose_patch : NULL, &cpa, repo);
14079 if (!error)
14080 print_merge_progress_stats(&upa);
14081 done:
14082 if (patch_script_file && fclose(patch_script_file) == EOF &&
14083 error == NULL)
14084 error = got_error_from_errno2("fclose", patch_script_path);
14085 if (repo) {
14086 const struct got_error *close_err = got_repo_close(repo);
14087 if (error == NULL)
14088 error = close_err;
14090 if (worktree)
14091 got_worktree_close(worktree);
14092 if (pack_fds) {
14093 const struct got_error *pack_err =
14094 got_repo_pack_fds_close(pack_fds);
14095 if (error == NULL)
14096 error = pack_err;
14098 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
14099 free(cwd);
14100 return error;
14103 __dead static void
14104 usage_cat(void)
14106 fprintf(stderr, "usage: %s cat [-P] [-c commit] [-r repository-path] "
14107 "arg ...\n", getprogname());
14108 exit(1);
14111 static const struct got_error *
14112 cat_blob(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
14114 const struct got_error *err;
14115 struct got_blob_object *blob;
14116 int fd = -1;
14118 fd = got_opentempfd();
14119 if (fd == -1)
14120 return got_error_from_errno("got_opentempfd");
14122 err = got_object_open_as_blob(&blob, repo, id, 8192, fd);
14123 if (err)
14124 goto done;
14126 err = got_object_blob_dump_to_file(NULL, NULL, NULL, outfile, blob);
14127 done:
14128 if (fd != -1 && close(fd) == -1 && err == NULL)
14129 err = got_error_from_errno("close");
14130 if (blob)
14131 got_object_blob_close(blob);
14132 return err;
14135 static const struct got_error *
14136 cat_tree(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
14138 const struct got_error *err;
14139 struct got_tree_object *tree;
14140 int nentries, i;
14142 err = got_object_open_as_tree(&tree, repo, id);
14143 if (err)
14144 return err;
14146 nentries = got_object_tree_get_nentries(tree);
14147 for (i = 0; i < nentries; i++) {
14148 struct got_tree_entry *te;
14149 char *id_str;
14150 if (sigint_received || sigpipe_received)
14151 break;
14152 te = got_object_tree_get_entry(tree, i);
14153 err = got_object_id_str(&id_str, got_tree_entry_get_id(te));
14154 if (err)
14155 break;
14156 fprintf(outfile, "%s %.7o %s\n", id_str,
14157 got_tree_entry_get_mode(te),
14158 got_tree_entry_get_name(te));
14159 free(id_str);
14162 got_object_tree_close(tree);
14163 return err;
14166 static const struct got_error *
14167 cat_commit(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
14169 const struct got_error *err;
14170 struct got_commit_object *commit;
14171 const struct got_object_id_queue *parent_ids;
14172 struct got_object_qid *pid;
14173 char *id_str = NULL;
14174 const char *logmsg = NULL;
14175 char gmtoff[6];
14177 err = got_object_open_as_commit(&commit, repo, id);
14178 if (err)
14179 return err;
14181 err = got_object_id_str(&id_str, got_object_commit_get_tree_id(commit));
14182 if (err)
14183 goto done;
14185 fprintf(outfile, "%s%s\n", GOT_COMMIT_LABEL_TREE, id_str);
14186 parent_ids = got_object_commit_get_parent_ids(commit);
14187 fprintf(outfile, "numparents %d\n",
14188 got_object_commit_get_nparents(commit));
14189 STAILQ_FOREACH(pid, parent_ids, entry) {
14190 char *pid_str;
14191 err = got_object_id_str(&pid_str, &pid->id);
14192 if (err)
14193 goto done;
14194 fprintf(outfile, "%s%s\n", GOT_COMMIT_LABEL_PARENT, pid_str);
14195 free(pid_str);
14197 got_date_format_gmtoff(gmtoff, sizeof(gmtoff),
14198 got_object_commit_get_author_gmtoff(commit));
14199 fprintf(outfile, "%s%s %lld %s\n", GOT_COMMIT_LABEL_AUTHOR,
14200 got_object_commit_get_author(commit),
14201 (long long)got_object_commit_get_author_time(commit),
14202 gmtoff);
14204 got_date_format_gmtoff(gmtoff, sizeof(gmtoff),
14205 got_object_commit_get_committer_gmtoff(commit));
14206 fprintf(outfile, "%s%s %lld %s\n", GOT_COMMIT_LABEL_COMMITTER,
14207 got_object_commit_get_committer(commit),
14208 (long long)got_object_commit_get_committer_time(commit),
14209 gmtoff);
14211 logmsg = got_object_commit_get_logmsg_raw(commit);
14212 fprintf(outfile, "messagelen %zd\n", strlen(logmsg));
14213 fprintf(outfile, "%s", logmsg);
14214 done:
14215 free(id_str);
14216 got_object_commit_close(commit);
14217 return err;
14220 static const struct got_error *
14221 cat_tag(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
14223 const struct got_error *err;
14224 struct got_tag_object *tag;
14225 char *id_str = NULL;
14226 const char *tagmsg = NULL;
14227 char gmtoff[6];
14229 err = got_object_open_as_tag(&tag, repo, id);
14230 if (err)
14231 return err;
14233 err = got_object_id_str(&id_str, got_object_tag_get_object_id(tag));
14234 if (err)
14235 goto done;
14237 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_OBJECT, id_str);
14239 switch (got_object_tag_get_object_type(tag)) {
14240 case GOT_OBJ_TYPE_BLOB:
14241 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
14242 GOT_OBJ_LABEL_BLOB);
14243 break;
14244 case GOT_OBJ_TYPE_TREE:
14245 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
14246 GOT_OBJ_LABEL_TREE);
14247 break;
14248 case GOT_OBJ_TYPE_COMMIT:
14249 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
14250 GOT_OBJ_LABEL_COMMIT);
14251 break;
14252 case GOT_OBJ_TYPE_TAG:
14253 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
14254 GOT_OBJ_LABEL_TAG);
14255 break;
14256 default:
14257 break;
14260 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TAG,
14261 got_object_tag_get_name(tag));
14263 got_date_format_gmtoff(gmtoff, sizeof(gmtoff),
14264 got_object_tag_get_tagger_gmtoff(tag));
14265 fprintf(outfile, "%s%s %lld %s\n", GOT_TAG_LABEL_TAGGER,
14266 got_object_tag_get_tagger(tag),
14267 (long long)got_object_tag_get_tagger_time(tag),
14268 gmtoff);
14270 tagmsg = got_object_tag_get_message(tag);
14271 fprintf(outfile, "messagelen %zd\n", strlen(tagmsg));
14272 fprintf(outfile, "%s", tagmsg);
14273 done:
14274 free(id_str);
14275 got_object_tag_close(tag);
14276 return err;
14279 static const struct got_error *
14280 cmd_cat(int argc, char *argv[])
14282 const struct got_error *error;
14283 struct got_repository *repo = NULL;
14284 struct got_worktree *worktree = NULL;
14285 char *cwd = NULL, *repo_path = NULL, *label = NULL;
14286 char *keyword_idstr = NULL;
14287 const char *commit_id_str = NULL;
14288 struct got_object_id *id = NULL, *commit_id = NULL;
14289 struct got_commit_object *commit = NULL;
14290 int ch, obj_type, i, force_path = 0;
14291 struct got_reflist_head refs;
14292 int *pack_fds = NULL;
14294 TAILQ_INIT(&refs);
14296 #ifndef PROFILE
14297 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
14298 NULL) == -1)
14299 err(1, "pledge");
14300 #endif
14302 while ((ch = getopt(argc, argv, "c:Pr:")) != -1) {
14303 switch (ch) {
14304 case 'c':
14305 commit_id_str = optarg;
14306 break;
14307 case 'P':
14308 force_path = 1;
14309 break;
14310 case 'r':
14311 repo_path = realpath(optarg, NULL);
14312 if (repo_path == NULL)
14313 return got_error_from_errno2("realpath",
14314 optarg);
14315 got_path_strip_trailing_slashes(repo_path);
14316 break;
14317 default:
14318 usage_cat();
14319 /* NOTREACHED */
14323 argc -= optind;
14324 argv += optind;
14326 cwd = getcwd(NULL, 0);
14327 if (cwd == NULL) {
14328 error = got_error_from_errno("getcwd");
14329 goto done;
14332 error = got_repo_pack_fds_open(&pack_fds);
14333 if (error != NULL)
14334 goto done;
14336 if (repo_path == NULL) {
14337 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
14338 if (error && error->code != GOT_ERR_NOT_WORKTREE)
14339 goto done;
14340 if (worktree) {
14341 repo_path = strdup(
14342 got_worktree_get_repo_path(worktree));
14343 if (repo_path == NULL) {
14344 error = got_error_from_errno("strdup");
14345 goto done;
14348 if (commit_id_str == NULL) {
14349 /* Release work tree lock. */
14350 got_worktree_close(worktree);
14351 worktree = NULL;
14356 if (repo_path == NULL) {
14357 repo_path = strdup(cwd);
14358 if (repo_path == NULL)
14359 return got_error_from_errno("strdup");
14362 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
14363 free(repo_path);
14364 if (error != NULL)
14365 goto done;
14367 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
14368 if (error)
14369 goto done;
14371 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
14372 if (error)
14373 goto done;
14375 if (commit_id_str != NULL) {
14376 error = got_keyword_to_idstr(&keyword_idstr, commit_id_str,
14377 repo, worktree);
14378 if (error != NULL)
14379 goto done;
14380 if (keyword_idstr != NULL)
14381 commit_id_str = keyword_idstr;
14382 if (worktree != NULL) {
14383 got_worktree_close(worktree);
14384 worktree = NULL;
14386 } else
14387 commit_id_str = GOT_REF_HEAD;
14388 error = got_repo_match_object_id(&commit_id, NULL,
14389 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
14390 if (error)
14391 goto done;
14393 error = got_object_open_as_commit(&commit, repo, commit_id);
14394 if (error)
14395 goto done;
14397 for (i = 0; i < argc; i++) {
14398 if (force_path) {
14399 error = got_object_id_by_path(&id, repo, commit,
14400 argv[i]);
14401 if (error)
14402 break;
14403 } else {
14404 error = got_repo_match_object_id(&id, &label, argv[i],
14405 GOT_OBJ_TYPE_ANY, NULL /* do not resolve tags */,
14406 repo);
14407 if (error) {
14408 if (error->code != GOT_ERR_BAD_OBJ_ID_STR &&
14409 error->code != GOT_ERR_NOT_REF)
14410 break;
14411 error = got_object_id_by_path(&id, repo,
14412 commit, argv[i]);
14413 if (error)
14414 break;
14418 error = got_object_get_type(&obj_type, repo, id);
14419 if (error)
14420 break;
14422 switch (obj_type) {
14423 case GOT_OBJ_TYPE_BLOB:
14424 error = cat_blob(id, repo, stdout);
14425 break;
14426 case GOT_OBJ_TYPE_TREE:
14427 error = cat_tree(id, repo, stdout);
14428 break;
14429 case GOT_OBJ_TYPE_COMMIT:
14430 error = cat_commit(id, repo, stdout);
14431 break;
14432 case GOT_OBJ_TYPE_TAG:
14433 error = cat_tag(id, repo, stdout);
14434 break;
14435 default:
14436 error = got_error(GOT_ERR_OBJ_TYPE);
14437 break;
14439 if (error)
14440 break;
14441 free(label);
14442 label = NULL;
14443 free(id);
14444 id = NULL;
14446 done:
14447 free(label);
14448 free(id);
14449 free(commit_id);
14450 free(keyword_idstr);
14451 if (commit)
14452 got_object_commit_close(commit);
14453 if (worktree)
14454 got_worktree_close(worktree);
14455 if (repo) {
14456 const struct got_error *close_err = got_repo_close(repo);
14457 if (error == NULL)
14458 error = close_err;
14460 if (pack_fds) {
14461 const struct got_error *pack_err =
14462 got_repo_pack_fds_close(pack_fds);
14463 if (error == NULL)
14464 error = pack_err;
14467 got_ref_list_free(&refs);
14468 return error;
14471 __dead static void
14472 usage_info(void)
14474 fprintf(stderr, "usage: %s info [path ...]\n",
14475 getprogname());
14476 exit(1);
14479 static const struct got_error *
14480 print_path_info(void *arg, const char *path, mode_t mode, time_t mtime,
14481 struct got_object_id *blob_id, struct got_object_id *staged_blob_id,
14482 struct got_object_id *commit_id)
14484 const struct got_error *err = NULL;
14485 char *id_str = NULL;
14486 char datebuf[128];
14487 struct tm mytm, *tm;
14488 struct got_pathlist_head *paths = arg;
14489 struct got_pathlist_entry *pe;
14492 * Clear error indication from any of the path arguments which
14493 * would cause this file index entry to be displayed.
14495 TAILQ_FOREACH(pe, paths, entry) {
14496 if (got_path_cmp(path, pe->path, strlen(path),
14497 pe->path_len) == 0 ||
14498 got_path_is_child(path, pe->path, pe->path_len))
14499 pe->data = NULL; /* no error */
14502 printf(GOT_COMMIT_SEP_STR);
14503 if (S_ISLNK(mode))
14504 printf("symlink: %s\n", path);
14505 else if (S_ISREG(mode)) {
14506 printf("file: %s\n", path);
14507 printf("mode: %o\n", mode & (S_IRWXU | S_IRWXG | S_IRWXO));
14508 } else if (S_ISDIR(mode))
14509 printf("directory: %s\n", path);
14510 else
14511 printf("something: %s\n", path);
14513 tm = localtime_r(&mtime, &mytm);
14514 if (tm == NULL)
14515 return NULL;
14516 if (strftime(datebuf, sizeof(datebuf), "%c %Z", tm) == 0)
14517 return got_error(GOT_ERR_NO_SPACE);
14518 printf("timestamp: %s\n", datebuf);
14520 if (blob_id) {
14521 err = got_object_id_str(&id_str, blob_id);
14522 if (err)
14523 return err;
14524 printf("based on blob: %s\n", id_str);
14525 free(id_str);
14528 if (staged_blob_id) {
14529 err = got_object_id_str(&id_str, staged_blob_id);
14530 if (err)
14531 return err;
14532 printf("based on staged blob: %s\n", id_str);
14533 free(id_str);
14536 if (commit_id) {
14537 err = got_object_id_str(&id_str, commit_id);
14538 if (err)
14539 return err;
14540 printf("based on commit: %s\n", id_str);
14541 free(id_str);
14544 return NULL;
14547 static const struct got_error *
14548 cmd_info(int argc, char *argv[])
14550 const struct got_error *error = NULL;
14551 struct got_worktree *worktree = NULL;
14552 char *cwd = NULL, *id_str = NULL;
14553 struct got_pathlist_head paths;
14554 char *uuidstr = NULL;
14555 int ch, show_files = 0;
14557 TAILQ_INIT(&paths);
14559 #ifndef PROFILE
14560 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
14561 NULL) == -1)
14562 err(1, "pledge");
14563 #endif
14565 while ((ch = getopt(argc, argv, "")) != -1) {
14566 switch (ch) {
14567 default:
14568 usage_info();
14569 /* NOTREACHED */
14573 argc -= optind;
14574 argv += optind;
14576 cwd = getcwd(NULL, 0);
14577 if (cwd == NULL) {
14578 error = got_error_from_errno("getcwd");
14579 goto done;
14582 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
14583 if (error) {
14584 if (error->code == GOT_ERR_NOT_WORKTREE)
14585 error = wrap_not_worktree_error(error, "info", cwd);
14586 goto done;
14589 #ifndef PROFILE
14590 /* Remove "wpath cpath proc exec sendfd" promises. */
14591 if (pledge("stdio rpath flock unveil", NULL) == -1)
14592 err(1, "pledge");
14593 #endif
14594 error = apply_unveil(NULL, 0, got_worktree_get_root_path(worktree));
14595 if (error)
14596 goto done;
14598 if (argc >= 1) {
14599 error = get_worktree_paths_from_argv(&paths, argc, argv,
14600 worktree);
14601 if (error)
14602 goto done;
14603 show_files = 1;
14606 error = got_object_id_str(&id_str,
14607 got_worktree_get_base_commit_id(worktree));
14608 if (error)
14609 goto done;
14611 error = got_worktree_get_uuid(&uuidstr, worktree);
14612 if (error)
14613 goto done;
14615 printf("work tree: %s\n", got_worktree_get_root_path(worktree));
14616 printf("work tree base commit: %s\n", id_str);
14617 printf("work tree path prefix: %s\n",
14618 got_worktree_get_path_prefix(worktree));
14619 printf("work tree branch reference: %s\n",
14620 got_worktree_get_head_ref_name(worktree));
14621 printf("work tree UUID: %s\n", uuidstr);
14622 printf("repository: %s\n", got_worktree_get_repo_path(worktree));
14624 if (show_files) {
14625 struct got_pathlist_entry *pe;
14626 TAILQ_FOREACH(pe, &paths, entry) {
14627 if (pe->path_len == 0)
14628 continue;
14630 * Assume this path will fail. This will be corrected
14631 * in print_path_info() in case the path does suceeed.
14633 pe->data = (void *)got_error(GOT_ERR_BAD_PATH);
14635 error = got_worktree_path_info(worktree, &paths,
14636 print_path_info, &paths, check_cancelled, NULL);
14637 if (error)
14638 goto done;
14639 TAILQ_FOREACH(pe, &paths, entry) {
14640 if (pe->data != NULL) {
14641 const struct got_error *perr;
14643 perr = pe->data;
14644 error = got_error_fmt(perr->code, "%s",
14645 pe->path);
14646 break;
14650 done:
14651 if (worktree)
14652 got_worktree_close(worktree);
14653 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
14654 free(cwd);
14655 free(id_str);
14656 free(uuidstr);
14657 return error;