Blob


1 /*
2 * Copyright (c) 2017 Martin Pieuchot <mpi@openbsd.org>
3 * Copyright (c) 2018, 2019, 2020 Stefan Sperling <stsp@openbsd.org>
4 * Copyright (c) 2020 Ori Bernstein <ori@openbsd.org>
5 *
6 * Permission to use, copy, modify, and distribute this software for any
7 * purpose with or without fee is hereby granted, provided that the above
8 * copyright notice and this permission notice appear in all copies.
9 *
10 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
11 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
12 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
13 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
14 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
15 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
16 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
17 */
19 #include "got_compat.h"
21 #include <sys/queue.h>
22 #include <sys/time.h>
23 #include <sys/types.h>
24 #include <sys/stat.h>
25 #include <sys/wait.h>
27 #include <err.h>
28 #include <errno.h>
29 #include <fcntl.h>
30 #include <limits.h>
31 #include <locale.h>
32 #include <ctype.h>
33 #include <signal.h>
34 #include <stdio.h>
35 #include <stdlib.h>
36 #include <string.h>
37 #include <unistd.h>
38 #include <libgen.h>
39 #include <time.h>
40 #include <paths.h>
41 #include <regex.h>
42 #include <getopt.h>
44 #include "got_version.h"
45 #include "got_error.h"
46 #include "got_object.h"
47 #include "got_reference.h"
48 #include "got_repository.h"
49 #include "got_path.h"
50 #include "got_cancel.h"
51 #include "got_worktree.h"
52 #include "got_diff.h"
53 #include "got_commit_graph.h"
54 #include "got_fetch.h"
55 #include "got_send.h"
56 #include "got_blame.h"
57 #include "got_privsep.h"
58 #include "got_opentemp.h"
59 #include "got_gotconfig.h"
60 #include "got_dial.h"
61 #include "got_patch.h"
62 #include "got_sigs.h"
63 #include "got_date.h"
64 #include "got_keyword.h"
66 #ifndef nitems
67 #define nitems(_a) (sizeof((_a)) / sizeof((_a)[0]))
68 #endif
70 #ifndef GOT_DEFAULT_EDITOR
71 #define GOT_DEFAULT_EDITOR "/usr/bin/vi"
72 #endif
74 static volatile sig_atomic_t sigint_received;
75 static volatile sig_atomic_t sigpipe_received;
77 static void
78 catch_sigint(int signo)
79 {
80 sigint_received = 1;
81 }
83 static void
84 catch_sigpipe(int signo)
85 {
86 sigpipe_received = 1;
87 }
90 struct got_cmd {
91 const char *cmd_name;
92 const struct got_error *(*cmd_main)(int, char *[]);
93 void (*cmd_usage)(void);
94 const char *cmd_alias;
95 };
97 __dead static void usage(int, int);
98 __dead static void usage_import(void);
99 __dead static void usage_clone(void);
100 __dead static void usage_fetch(void);
101 __dead static void usage_checkout(void);
102 __dead static void usage_update(void);
103 __dead static void usage_log(void);
104 __dead static void usage_diff(void);
105 __dead static void usage_blame(void);
106 __dead static void usage_tree(void);
107 __dead static void usage_status(void);
108 __dead static void usage_ref(void);
109 __dead static void usage_branch(void);
110 __dead static void usage_tag(void);
111 __dead static void usage_add(void);
112 __dead static void usage_remove(void);
113 __dead static void usage_patch(void);
114 __dead static void usage_revert(void);
115 __dead static void usage_commit(void);
116 __dead static void usage_send(void);
117 __dead static void usage_cherrypick(void);
118 __dead static void usage_backout(void);
119 __dead static void usage_rebase(void);
120 __dead static void usage_histedit(void);
121 __dead static void usage_integrate(void);
122 __dead static void usage_merge(void);
123 __dead static void usage_stage(void);
124 __dead static void usage_unstage(void);
125 __dead static void usage_cat(void);
126 __dead static void usage_info(void);
128 static const struct got_error* cmd_import(int, char *[]);
129 static const struct got_error* cmd_clone(int, char *[]);
130 static const struct got_error* cmd_fetch(int, char *[]);
131 static const struct got_error* cmd_checkout(int, char *[]);
132 static const struct got_error* cmd_update(int, char *[]);
133 static const struct got_error* cmd_log(int, char *[]);
134 static const struct got_error* cmd_diff(int, char *[]);
135 static const struct got_error* cmd_blame(int, char *[]);
136 static const struct got_error* cmd_tree(int, char *[]);
137 static const struct got_error* cmd_status(int, char *[]);
138 static const struct got_error* cmd_ref(int, char *[]);
139 static const struct got_error* cmd_branch(int, char *[]);
140 static const struct got_error* cmd_tag(int, char *[]);
141 static const struct got_error* cmd_add(int, char *[]);
142 static const struct got_error* cmd_remove(int, char *[]);
143 static const struct got_error* cmd_patch(int, char *[]);
144 static const struct got_error* cmd_revert(int, char *[]);
145 static const struct got_error* cmd_commit(int, char *[]);
146 static const struct got_error* cmd_send(int, char *[]);
147 static const struct got_error* cmd_cherrypick(int, char *[]);
148 static const struct got_error* cmd_backout(int, char *[]);
149 static const struct got_error* cmd_rebase(int, char *[]);
150 static const struct got_error* cmd_histedit(int, char *[]);
151 static const struct got_error* cmd_integrate(int, char *[]);
152 static const struct got_error* cmd_merge(int, char *[]);
153 static const struct got_error* cmd_stage(int, char *[]);
154 static const struct got_error* cmd_unstage(int, char *[]);
155 static const struct got_error* cmd_cat(int, char *[]);
156 static const struct got_error* cmd_info(int, char *[]);
158 static const struct got_cmd got_commands[] = {
159 { "import", cmd_import, usage_import, "im" },
160 { "clone", cmd_clone, usage_clone, "cl" },
161 { "fetch", cmd_fetch, usage_fetch, "fe" },
162 { "checkout", cmd_checkout, usage_checkout, "co" },
163 { "update", cmd_update, usage_update, "up" },
164 { "log", cmd_log, usage_log, "" },
165 { "diff", cmd_diff, usage_diff, "di" },
166 { "blame", cmd_blame, usage_blame, "bl" },
167 { "tree", cmd_tree, usage_tree, "tr" },
168 { "status", cmd_status, usage_status, "st" },
169 { "ref", cmd_ref, usage_ref, "" },
170 { "branch", cmd_branch, usage_branch, "br" },
171 { "tag", cmd_tag, usage_tag, "" },
172 { "add", cmd_add, usage_add, "" },
173 { "remove", cmd_remove, usage_remove, "rm" },
174 { "patch", cmd_patch, usage_patch, "pa" },
175 { "revert", cmd_revert, usage_revert, "rv" },
176 { "commit", cmd_commit, usage_commit, "ci" },
177 { "send", cmd_send, usage_send, "se" },
178 { "cherrypick", cmd_cherrypick, usage_cherrypick, "cy" },
179 { "backout", cmd_backout, usage_backout, "bo" },
180 { "rebase", cmd_rebase, usage_rebase, "rb" },
181 { "histedit", cmd_histedit, usage_histedit, "he" },
182 { "integrate", cmd_integrate, usage_integrate,"ig" },
183 { "merge", cmd_merge, usage_merge, "mg" },
184 { "stage", cmd_stage, usage_stage, "sg" },
185 { "unstage", cmd_unstage, usage_unstage, "ug" },
186 { "cat", cmd_cat, usage_cat, "" },
187 { "info", cmd_info, usage_info, "" },
188 };
190 static void
191 list_commands(FILE *fp)
193 size_t i;
195 fprintf(fp, "commands:");
196 for (i = 0; i < nitems(got_commands); i++) {
197 const struct got_cmd *cmd = &got_commands[i];
198 fprintf(fp, " %s", cmd->cmd_name);
200 fputc('\n', fp);
203 __dead static void
204 option_conflict(char a, char b)
206 errx(1, "-%c and -%c options are mutually exclusive", a, b);
209 int
210 main(int argc, char *argv[])
212 const struct got_cmd *cmd;
213 size_t i;
214 int ch;
215 int hflag = 0, Vflag = 0;
216 static const struct option longopts[] = {
217 { "version", no_argument, NULL, 'V' },
218 { NULL, 0, NULL, 0 }
219 };
221 setlocale(LC_CTYPE, "");
223 while ((ch = getopt_long(argc, argv, "+hV", longopts, NULL)) != -1) {
224 switch (ch) {
225 case 'h':
226 hflag = 1;
227 break;
228 case 'V':
229 Vflag = 1;
230 break;
231 default:
232 usage(hflag, 1);
233 /* NOTREACHED */
237 argc -= optind;
238 argv += optind;
239 optind = 1;
240 optreset = 1;
242 if (Vflag) {
243 got_version_print_str();
244 return 0;
247 if (argc <= 0)
248 usage(hflag, hflag ? 0 : 1);
250 signal(SIGINT, catch_sigint);
251 signal(SIGPIPE, catch_sigpipe);
253 for (i = 0; i < nitems(got_commands); i++) {
254 const struct got_error *error;
256 cmd = &got_commands[i];
258 if (strcmp(cmd->cmd_name, argv[0]) != 0 &&
259 strcmp(cmd->cmd_alias, argv[0]) != 0)
260 continue;
262 if (hflag)
263 cmd->cmd_usage();
265 error = cmd->cmd_main(argc, argv);
266 if (error && error->code != GOT_ERR_CANCELLED &&
267 error->code != GOT_ERR_PRIVSEP_EXIT &&
268 !(sigpipe_received &&
269 error->code == GOT_ERR_ERRNO && errno == EPIPE) &&
270 !(sigint_received &&
271 error->code == GOT_ERR_ERRNO && errno == EINTR)) {
272 fflush(stdout);
273 fprintf(stderr, "%s: %s\n", getprogname(), error->msg);
274 return 1;
277 return 0;
280 fprintf(stderr, "%s: unknown command '%s'\n", getprogname(), argv[0]);
281 list_commands(stderr);
282 return 1;
285 __dead static void
286 usage(int hflag, int status)
288 FILE *fp = (status == 0) ? stdout : stderr;
290 fprintf(fp, "usage: %s [-hV] command [arg ...]\n",
291 getprogname());
292 if (hflag)
293 list_commands(fp);
294 exit(status);
297 static const struct got_error *
298 get_editor(char **abspath)
300 const struct got_error *err = NULL;
301 const char *editor;
303 *abspath = NULL;
305 editor = getenv("VISUAL");
306 if (editor == NULL)
307 editor = getenv("EDITOR");
309 if (editor) {
310 err = got_path_find_prog(abspath, editor);
311 if (err)
312 return err;
315 if (*abspath == NULL) {
316 *abspath = strdup(GOT_DEFAULT_EDITOR);
317 if (*abspath == NULL)
318 return got_error_from_errno("strdup");
321 return NULL;
324 static const struct got_error *
325 apply_unveil(const char *repo_path, int repo_read_only,
326 const char *worktree_path)
328 const struct got_error *err;
330 #ifdef PROFILE
331 if (unveil("gmon.out", "rwc") != 0)
332 return got_error_from_errno2("unveil", "gmon.out");
333 #endif
334 if (repo_path && unveil(repo_path, repo_read_only ? "r" : "rwc") != 0)
335 return got_error_from_errno2("unveil", repo_path);
337 if (worktree_path && unveil(worktree_path, "rwc") != 0)
338 return got_error_from_errno2("unveil", worktree_path);
340 if (unveil(GOT_TMPDIR_STR, "rwc") != 0)
341 return got_error_from_errno2("unveil", GOT_TMPDIR_STR);
343 err = got_privsep_unveil_exec_helpers();
344 if (err != NULL)
345 return err;
347 if (unveil(NULL, NULL) != 0)
348 return got_error_from_errno("unveil");
350 return NULL;
353 __dead static void
354 usage_import(void)
356 fprintf(stderr, "usage: %s import [-b branch] [-I pattern] [-m message] "
357 "[-r repository-path] directory\n", getprogname());
358 exit(1);
361 static int
362 spawn_editor(const char *editor, const char *file)
364 pid_t pid;
365 sig_t sighup, sigint, sigquit;
366 int st = -1;
368 sighup = signal(SIGHUP, SIG_IGN);
369 sigint = signal(SIGINT, SIG_IGN);
370 sigquit = signal(SIGQUIT, SIG_IGN);
372 switch (pid = fork()) {
373 case -1:
374 goto doneediting;
375 case 0:
376 execl(editor, editor, file, (char *)NULL);
377 _exit(127);
380 while (waitpid(pid, &st, 0) == -1)
381 if (errno != EINTR)
382 break;
384 doneediting:
385 (void)signal(SIGHUP, sighup);
386 (void)signal(SIGINT, sigint);
387 (void)signal(SIGQUIT, sigquit);
389 if (!WIFEXITED(st)) {
390 errno = EINTR;
391 return -1;
394 return WEXITSTATUS(st);
397 static const struct got_error *
398 read_logmsg(char **logmsg, size_t *len, FILE *fp, size_t filesize)
400 const struct got_error *err = NULL;
401 char *line = NULL;
402 size_t linesize = 0;
404 *logmsg = NULL;
405 *len = 0;
407 if (fseeko(fp, 0L, SEEK_SET) == -1)
408 return got_error_from_errno("fseeko");
410 *logmsg = malloc(filesize + 1);
411 if (*logmsg == NULL)
412 return got_error_from_errno("malloc");
413 (*logmsg)[0] = '\0';
415 while (getline(&line, &linesize, fp) != -1) {
416 if (line[0] == '#' || (*len == 0 && line[0] == '\n'))
417 continue; /* remove comments and leading empty lines */
418 *len = strlcat(*logmsg, line, filesize + 1);
419 if (*len >= filesize + 1) {
420 err = got_error(GOT_ERR_NO_SPACE);
421 goto done;
424 if (ferror(fp)) {
425 err = got_ferror(fp, GOT_ERR_IO);
426 goto done;
429 while (*len > 0 && (*logmsg)[*len - 1] == '\n') {
430 (*logmsg)[*len - 1] = '\0';
431 (*len)--;
433 done:
434 free(line);
435 if (err) {
436 free(*logmsg);
437 *logmsg = NULL;
438 *len = 0;
440 return err;
443 static const struct got_error *
444 edit_logmsg(char **logmsg, const char *editor, const char *logmsg_path,
445 const char *initial_content, size_t initial_content_len,
446 int require_modification)
448 const struct got_error *err = NULL;
449 struct stat st, st2;
450 FILE *fp = NULL;
451 size_t logmsg_len;
453 *logmsg = NULL;
455 if (stat(logmsg_path, &st) == -1)
456 return got_error_from_errno2("stat", logmsg_path);
458 if (spawn_editor(editor, logmsg_path) == -1)
459 return got_error_from_errno("failed spawning editor");
461 if (require_modification) {
462 struct timespec timeout;
464 timeout.tv_sec = 0;
465 timeout.tv_nsec = 1;
466 nanosleep(&timeout, NULL);
469 if (stat(logmsg_path, &st2) == -1)
470 return got_error_from_errno2("stat", logmsg_path);
472 if (require_modification && st.st_size == st2.st_size &&
473 timespeccmp(&st.st_mtim, &st2.st_mtim, ==))
474 return got_error_msg(GOT_ERR_COMMIT_MSG_EMPTY,
475 "no changes made to commit message, aborting");
477 fp = fopen(logmsg_path, "re");
478 if (fp == NULL) {
479 err = got_error_from_errno("fopen");
480 goto done;
483 /* strip comments and leading/trailing newlines */
484 err = read_logmsg(logmsg, &logmsg_len, fp, st2.st_size);
485 if (err)
486 goto done;
487 if (logmsg_len == 0) {
488 err = got_error_msg(GOT_ERR_COMMIT_MSG_EMPTY,
489 "commit message cannot be empty, aborting");
490 goto done;
492 done:
493 if (fp && fclose(fp) == EOF && err == NULL)
494 err = got_error_from_errno("fclose");
495 if (err) {
496 free(*logmsg);
497 *logmsg = NULL;
499 return err;
502 static const struct got_error *
503 collect_import_msg(char **logmsg, char **logmsg_path, const char *editor,
504 const char *path_dir, const char *branch_name)
506 char *initial_content = NULL;
507 const struct got_error *err = NULL;
508 int initial_content_len;
509 int fd = -1;
511 initial_content_len = asprintf(&initial_content,
512 "\n# %s to be imported to branch %s\n", path_dir,
513 branch_name);
514 if (initial_content_len == -1)
515 return got_error_from_errno("asprintf");
517 err = got_opentemp_named_fd(logmsg_path, &fd,
518 GOT_TMPDIR_STR "/got-importmsg", "");
519 if (err)
520 goto done;
522 if (write(fd, initial_content, initial_content_len) == -1) {
523 err = got_error_from_errno2("write", *logmsg_path);
524 goto done;
526 if (close(fd) == -1) {
527 err = got_error_from_errno2("close", *logmsg_path);
528 goto done;
530 fd = -1;
532 err = edit_logmsg(logmsg, editor, *logmsg_path, initial_content,
533 initial_content_len, 1);
534 done:
535 if (fd != -1 && close(fd) == -1 && err == NULL)
536 err = got_error_from_errno2("close", *logmsg_path);
537 free(initial_content);
538 if (err) {
539 free(*logmsg_path);
540 *logmsg_path = NULL;
542 return err;
545 static const struct got_error *
546 import_progress(void *arg, const char *path)
548 printf("A %s\n", path);
549 return NULL;
552 static const struct got_error *
553 valid_author(const char *author)
555 const char *email = author;
557 /*
558 * Git' expects the author (or committer) to be in the form
559 * "name <email>", which are mostly free form (see the
560 * "committer" description in git-fast-import(1)). We're only
561 * doing this to avoid git's object parser breaking on commits
562 * we create.
563 */
565 while (*author && *author != '\n' && *author != '<' && *author != '>')
566 author++;
567 if (author != email && *author == '<' && *(author - 1) != ' ')
568 return got_error_fmt(GOT_ERR_COMMIT_BAD_AUTHOR, "%s: space "
569 "between author name and email required", email);
570 if (*author++ != '<')
571 return got_error_fmt(GOT_ERR_COMMIT_NO_EMAIL, "%s", email);
572 while (*author && *author != '\n' && *author != '<' && *author != '>')
573 author++;
574 if (strcmp(author, ">") != 0)
575 return got_error_fmt(GOT_ERR_COMMIT_NO_EMAIL, "%s", email);
576 return NULL;
579 static const struct got_error *
580 get_author(char **author, struct got_repository *repo,
581 struct got_worktree *worktree)
583 const struct got_error *err = NULL;
584 const char *got_author = NULL, *name, *email;
585 const struct got_gotconfig *worktree_conf = NULL, *repo_conf = NULL;
587 *author = NULL;
589 if (worktree)
590 worktree_conf = got_worktree_get_gotconfig(worktree);
591 repo_conf = got_repo_get_gotconfig(repo);
593 /*
594 * Priority of potential author information sources, from most
595 * significant to least significant:
596 * 1) work tree's .got/got.conf file
597 * 2) repository's got.conf file
598 * 3) repository's git config file
599 * 4) environment variables
600 * 5) global git config files (in user's home directory or /etc)
601 */
603 if (worktree_conf)
604 got_author = got_gotconfig_get_author(worktree_conf);
605 if (got_author == NULL)
606 got_author = got_gotconfig_get_author(repo_conf);
607 if (got_author == NULL) {
608 name = got_repo_get_gitconfig_author_name(repo);
609 email = got_repo_get_gitconfig_author_email(repo);
610 if (name && email) {
611 if (asprintf(author, "%s <%s>", name, email) == -1)
612 return got_error_from_errno("asprintf");
613 return NULL;
616 got_author = getenv("GOT_AUTHOR");
617 if (got_author == NULL) {
618 name = got_repo_get_global_gitconfig_author_name(repo);
619 email = got_repo_get_global_gitconfig_author_email(
620 repo);
621 if (name && email) {
622 if (asprintf(author, "%s <%s>", name, email)
623 == -1)
624 return got_error_from_errno("asprintf");
625 return NULL;
627 /* TODO: Look up user in password database? */
628 return got_error(GOT_ERR_COMMIT_NO_AUTHOR);
632 *author = strdup(got_author);
633 if (*author == NULL)
634 return got_error_from_errno("strdup");
636 err = valid_author(*author);
637 if (err) {
638 free(*author);
639 *author = NULL;
641 return err;
644 static const struct got_error *
645 get_allowed_signers(char **allowed_signers, struct got_repository *repo,
646 struct got_worktree *worktree)
648 const char *got_allowed_signers = NULL;
649 const struct got_gotconfig *worktree_conf = NULL, *repo_conf = NULL;
651 *allowed_signers = NULL;
653 if (worktree)
654 worktree_conf = got_worktree_get_gotconfig(worktree);
655 repo_conf = got_repo_get_gotconfig(repo);
657 /*
658 * Priority of potential author information sources, from most
659 * significant to least significant:
660 * 1) work tree's .got/got.conf file
661 * 2) repository's got.conf file
662 */
664 if (worktree_conf)
665 got_allowed_signers = got_gotconfig_get_allowed_signers_file(
666 worktree_conf);
667 if (got_allowed_signers == NULL)
668 got_allowed_signers = got_gotconfig_get_allowed_signers_file(
669 repo_conf);
671 if (got_allowed_signers) {
672 *allowed_signers = strdup(got_allowed_signers);
673 if (*allowed_signers == NULL)
674 return got_error_from_errno("strdup");
676 return NULL;
679 static const struct got_error *
680 get_revoked_signers(char **revoked_signers, struct got_repository *repo,
681 struct got_worktree *worktree)
683 const char *got_revoked_signers = NULL;
684 const struct got_gotconfig *worktree_conf = NULL, *repo_conf = NULL;
686 *revoked_signers = NULL;
688 if (worktree)
689 worktree_conf = got_worktree_get_gotconfig(worktree);
690 repo_conf = got_repo_get_gotconfig(repo);
692 /*
693 * Priority of potential author information sources, from most
694 * significant to least significant:
695 * 1) work tree's .got/got.conf file
696 * 2) repository's got.conf file
697 */
699 if (worktree_conf)
700 got_revoked_signers = got_gotconfig_get_revoked_signers_file(
701 worktree_conf);
702 if (got_revoked_signers == NULL)
703 got_revoked_signers = got_gotconfig_get_revoked_signers_file(
704 repo_conf);
706 if (got_revoked_signers) {
707 *revoked_signers = strdup(got_revoked_signers);
708 if (*revoked_signers == NULL)
709 return got_error_from_errno("strdup");
711 return NULL;
714 static const char *
715 get_signer_id(struct got_repository *repo, struct got_worktree *worktree)
717 const char *got_signer_id = NULL;
718 const struct got_gotconfig *worktree_conf = NULL, *repo_conf = NULL;
720 if (worktree)
721 worktree_conf = got_worktree_get_gotconfig(worktree);
722 repo_conf = got_repo_get_gotconfig(repo);
724 /*
725 * Priority of potential author information sources, from most
726 * significant to least significant:
727 * 1) work tree's .got/got.conf file
728 * 2) repository's got.conf file
729 */
731 if (worktree_conf)
732 got_signer_id = got_gotconfig_get_signer_id(worktree_conf);
733 if (got_signer_id == NULL)
734 got_signer_id = got_gotconfig_get_signer_id(repo_conf);
736 return got_signer_id;
739 static const struct got_error *
740 get_gitconfig_path(char **gitconfig_path)
742 const char *homedir = getenv("HOME");
744 *gitconfig_path = NULL;
745 if (homedir) {
746 if (asprintf(gitconfig_path, "%s/.gitconfig", homedir) == -1)
747 return got_error_from_errno("asprintf");
750 return NULL;
753 static const struct got_error *
754 cmd_import(int argc, char *argv[])
756 const struct got_error *error = NULL;
757 char *path_dir = NULL, *repo_path = NULL, *logmsg = NULL;
758 char *gitconfig_path = NULL, *editor = NULL, *author = NULL;
759 const char *branch_name = NULL;
760 char *id_str = NULL, *logmsg_path = NULL;
761 char refname[PATH_MAX] = "refs/heads/";
762 struct got_repository *repo = NULL;
763 struct got_reference *branch_ref = NULL, *head_ref = NULL;
764 struct got_object_id *new_commit_id = NULL;
765 int ch, n = 0;
766 struct got_pathlist_head ignores;
767 struct got_pathlist_entry *pe;
768 int preserve_logmsg = 0;
769 int *pack_fds = NULL;
771 TAILQ_INIT(&ignores);
773 #ifndef PROFILE
774 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
775 "unveil",
776 NULL) == -1)
777 err(1, "pledge");
778 #endif
780 while ((ch = getopt(argc, argv, "b:I:m:r:")) != -1) {
781 switch (ch) {
782 case 'b':
783 branch_name = optarg;
784 break;
785 case 'I':
786 if (optarg[0] == '\0')
787 break;
788 error = got_pathlist_insert(&pe, &ignores, optarg,
789 NULL);
790 if (error)
791 goto done;
792 break;
793 case 'm':
794 logmsg = strdup(optarg);
795 if (logmsg == NULL) {
796 error = got_error_from_errno("strdup");
797 goto done;
799 break;
800 case 'r':
801 repo_path = realpath(optarg, NULL);
802 if (repo_path == NULL) {
803 error = got_error_from_errno2("realpath",
804 optarg);
805 goto done;
807 break;
808 default:
809 usage_import();
810 /* NOTREACHED */
814 argc -= optind;
815 argv += optind;
817 if (argc != 1)
818 usage_import();
820 if (repo_path == NULL) {
821 repo_path = getcwd(NULL, 0);
822 if (repo_path == NULL)
823 return got_error_from_errno("getcwd");
825 got_path_strip_trailing_slashes(repo_path);
826 error = get_gitconfig_path(&gitconfig_path);
827 if (error)
828 goto done;
829 error = got_repo_pack_fds_open(&pack_fds);
830 if (error != NULL)
831 goto done;
832 error = got_repo_open(&repo, repo_path, gitconfig_path, pack_fds);
833 if (error)
834 goto done;
836 path_dir = realpath(argv[0], NULL);
837 if (path_dir == NULL) {
838 error = got_error_from_errno2("realpath", argv[0]);
839 goto done;
841 got_path_strip_trailing_slashes(path_dir);
843 error = get_editor(&editor);
844 if (error)
845 goto done;
847 if (unveil(path_dir, "r") != 0) {
848 error = got_error_from_errno2("unveil", path_dir);
849 goto done;
851 if (unveil(editor, "x") != 0) {
852 error = got_error_from_errno2("unveil", editor);
853 goto done;
855 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
856 if (error)
857 goto done;
859 error = get_author(&author, repo, NULL);
860 if (error)
861 return error;
863 /*
864 * Don't let the user create a branch name with a leading '-'.
865 * While technically a valid reference name, this case is usually
866 * an unintended typo.
867 */
868 if (branch_name && branch_name[0] == '-')
869 return got_error_path(branch_name, GOT_ERR_REF_NAME_MINUS);
871 error = got_ref_open(&head_ref, repo, GOT_REF_HEAD, 0);
872 if (error && error->code != GOT_ERR_NOT_REF)
873 goto done;
875 if (branch_name)
876 n = strlcat(refname, branch_name, sizeof(refname));
877 else if (head_ref && got_ref_is_symbolic(head_ref))
878 n = strlcpy(refname, got_ref_get_symref_target(head_ref),
879 sizeof(refname));
880 else
881 n = strlcat(refname, "main", sizeof(refname));
882 if (n >= sizeof(refname)) {
883 error = got_error(GOT_ERR_NO_SPACE);
884 goto done;
887 error = got_ref_open(&branch_ref, repo, refname, 0);
888 if (error) {
889 if (error->code != GOT_ERR_NOT_REF)
890 goto done;
891 } else {
892 error = got_error_msg(GOT_ERR_BRANCH_EXISTS,
893 "import target branch already exists");
894 goto done;
897 if (logmsg == NULL || *logmsg == '\0') {
898 free(logmsg);
899 error = collect_import_msg(&logmsg, &logmsg_path, editor,
900 path_dir, refname);
901 if (error) {
902 if (error->code != GOT_ERR_COMMIT_MSG_EMPTY &&
903 logmsg_path != NULL)
904 preserve_logmsg = 1;
905 goto done;
909 error = got_repo_import(&new_commit_id, path_dir, logmsg,
910 author, &ignores, repo, import_progress, NULL);
911 if (error) {
912 if (logmsg_path)
913 preserve_logmsg = 1;
914 goto done;
917 error = got_ref_alloc(&branch_ref, refname, new_commit_id);
918 if (error) {
919 if (logmsg_path)
920 preserve_logmsg = 1;
921 goto done;
924 error = got_ref_write(branch_ref, repo);
925 if (error) {
926 if (logmsg_path)
927 preserve_logmsg = 1;
928 goto done;
931 error = got_object_id_str(&id_str, new_commit_id);
932 if (error) {
933 if (logmsg_path)
934 preserve_logmsg = 1;
935 goto done;
938 error = got_ref_open(&head_ref, repo, GOT_REF_HEAD, 0);
939 if (error) {
940 if (error->code != GOT_ERR_NOT_REF) {
941 if (logmsg_path)
942 preserve_logmsg = 1;
943 goto done;
946 error = got_ref_alloc_symref(&head_ref, GOT_REF_HEAD,
947 branch_ref);
948 if (error) {
949 if (logmsg_path)
950 preserve_logmsg = 1;
951 goto done;
954 error = got_ref_write(head_ref, repo);
955 if (error) {
956 if (logmsg_path)
957 preserve_logmsg = 1;
958 goto done;
962 printf("Created branch %s with commit %s\n",
963 got_ref_get_name(branch_ref), id_str);
964 done:
965 if (pack_fds) {
966 const struct got_error *pack_err =
967 got_repo_pack_fds_close(pack_fds);
968 if (error == NULL)
969 error = pack_err;
971 if (repo) {
972 const struct got_error *close_err = got_repo_close(repo);
973 if (error == NULL)
974 error = close_err;
976 if (preserve_logmsg) {
977 fprintf(stderr, "%s: log message preserved in %s\n",
978 getprogname(), logmsg_path);
979 } else if (logmsg_path && unlink(logmsg_path) == -1 && error == NULL)
980 error = got_error_from_errno2("unlink", logmsg_path);
981 free(logmsg);
982 free(logmsg_path);
983 free(repo_path);
984 free(editor);
985 free(new_commit_id);
986 free(id_str);
987 free(author);
988 free(gitconfig_path);
989 if (branch_ref)
990 got_ref_close(branch_ref);
991 if (head_ref)
992 got_ref_close(head_ref);
993 return error;
996 __dead static void
997 usage_clone(void)
999 fprintf(stderr, "usage: %s clone [-almqv] [-b branch] [-R reference] "
1000 "repository-URL [directory]\n", getprogname());
1001 exit(1);
1004 struct got_fetch_progress_arg {
1005 char last_scaled_size[FMT_SCALED_STRSIZE];
1006 int last_p_indexed;
1007 int last_p_resolved;
1008 int verbosity;
1010 struct got_repository *repo;
1012 int create_configs;
1013 int configs_created;
1014 struct {
1015 struct got_pathlist_head *symrefs;
1016 struct got_pathlist_head *wanted_branches;
1017 struct got_pathlist_head *wanted_refs;
1018 const char *proto;
1019 const char *host;
1020 const char *port;
1021 const char *remote_repo_path;
1022 const char *git_url;
1023 int fetch_all_branches;
1024 int mirror_references;
1025 } config_info;
1028 /* XXX forward declaration */
1029 static const struct got_error *
1030 create_config_files(const char *proto, const char *host, const char *port,
1031 const char *remote_repo_path, const char *git_url, int fetch_all_branches,
1032 int mirror_references, struct got_pathlist_head *symrefs,
1033 struct got_pathlist_head *wanted_branches,
1034 struct got_pathlist_head *wanted_refs, struct got_repository *repo);
1036 static const struct got_error *
1037 fetch_progress(void *arg, const char *message, off_t packfile_size,
1038 int nobj_total, int nobj_indexed, int nobj_loose, int nobj_resolved)
1040 const struct got_error *err = NULL;
1041 struct got_fetch_progress_arg *a = arg;
1042 char scaled_size[FMT_SCALED_STRSIZE];
1043 int p_indexed, p_resolved;
1044 int print_size = 0, print_indexed = 0, print_resolved = 0;
1047 * In order to allow a failed clone to be resumed with 'got fetch'
1048 * we try to create configuration files as soon as possible.
1049 * Once the server has sent information about its default branch
1050 * we have all required information.
1052 if (a->create_configs && !a->configs_created &&
1053 !TAILQ_EMPTY(a->config_info.symrefs)) {
1054 err = create_config_files(a->config_info.proto,
1055 a->config_info.host, a->config_info.port,
1056 a->config_info.remote_repo_path,
1057 a->config_info.git_url,
1058 a->config_info.fetch_all_branches,
1059 a->config_info.mirror_references,
1060 a->config_info.symrefs,
1061 a->config_info.wanted_branches,
1062 a->config_info.wanted_refs, a->repo);
1063 if (err)
1064 return err;
1065 a->configs_created = 1;
1068 if (a->verbosity < 0)
1069 return NULL;
1071 if (message && message[0] != '\0') {
1072 printf("\rserver: %s", message);
1073 fflush(stdout);
1074 return NULL;
1077 if (packfile_size > 0 || nobj_indexed > 0) {
1078 if (fmt_scaled(packfile_size, scaled_size) == 0 &&
1079 (a->last_scaled_size[0] == '\0' ||
1080 strcmp(scaled_size, a->last_scaled_size)) != 0) {
1081 print_size = 1;
1082 if (strlcpy(a->last_scaled_size, scaled_size,
1083 FMT_SCALED_STRSIZE) >= FMT_SCALED_STRSIZE)
1084 return got_error(GOT_ERR_NO_SPACE);
1086 if (nobj_indexed > 0) {
1087 p_indexed = (nobj_indexed * 100) / nobj_total;
1088 if (p_indexed != a->last_p_indexed) {
1089 a->last_p_indexed = p_indexed;
1090 print_indexed = 1;
1091 print_size = 1;
1094 if (nobj_resolved > 0) {
1095 p_resolved = (nobj_resolved * 100) /
1096 (nobj_total - nobj_loose);
1097 if (p_resolved != a->last_p_resolved) {
1098 a->last_p_resolved = p_resolved;
1099 print_resolved = 1;
1100 print_indexed = 1;
1101 print_size = 1;
1106 if (print_size || print_indexed || print_resolved)
1107 printf("\r");
1108 if (print_size)
1109 printf("%*s fetched", FMT_SCALED_STRSIZE - 2, scaled_size);
1110 if (print_indexed)
1111 printf("; indexing %d%%", p_indexed);
1112 if (print_resolved)
1113 printf("; resolving deltas %d%%", p_resolved);
1114 if (print_size || print_indexed || print_resolved)
1115 fflush(stdout);
1117 return NULL;
1120 static const struct got_error *
1121 create_symref(const char *refname, struct got_reference *target_ref,
1122 int verbosity, struct got_repository *repo)
1124 const struct got_error *err;
1125 struct got_reference *head_symref;
1127 err = got_ref_alloc_symref(&head_symref, refname, target_ref);
1128 if (err)
1129 return err;
1131 err = got_ref_write(head_symref, repo);
1132 if (err == NULL && verbosity > 0) {
1133 printf("Created reference %s: %s\n", GOT_REF_HEAD,
1134 got_ref_get_name(target_ref));
1136 got_ref_close(head_symref);
1137 return err;
1140 static const struct got_error *
1141 list_remote_refs(struct got_pathlist_head *symrefs,
1142 struct got_pathlist_head *refs)
1144 const struct got_error *err;
1145 struct got_pathlist_entry *pe;
1147 TAILQ_FOREACH(pe, symrefs, entry) {
1148 const char *refname = pe->path;
1149 const char *targetref = pe->data;
1151 printf("%s: %s\n", refname, targetref);
1154 TAILQ_FOREACH(pe, refs, entry) {
1155 const char *refname = pe->path;
1156 struct got_object_id *id = pe->data;
1157 char *id_str;
1159 err = got_object_id_str(&id_str, id);
1160 if (err)
1161 return err;
1162 printf("%s: %s\n", refname, id_str);
1163 free(id_str);
1166 return NULL;
1169 static const struct got_error *
1170 create_ref(const char *refname, struct got_object_id *id,
1171 int verbosity, struct got_repository *repo)
1173 const struct got_error *err = NULL;
1174 struct got_reference *ref;
1175 char *id_str;
1177 err = got_object_id_str(&id_str, id);
1178 if (err)
1179 return err;
1181 err = got_ref_alloc(&ref, refname, id);
1182 if (err)
1183 goto done;
1185 err = got_ref_write(ref, repo);
1186 got_ref_close(ref);
1188 if (err == NULL && verbosity >= 0)
1189 printf("Created reference %s: %s\n", refname, id_str);
1190 done:
1191 free(id_str);
1192 return err;
1195 static int
1196 match_wanted_ref(const char *refname, const char *wanted_ref)
1198 if (strncmp(refname, "refs/", 5) != 0)
1199 return 0;
1200 refname += 5;
1203 * Prevent fetching of references that won't make any
1204 * sense outside of the remote repository's context.
1206 if (strncmp(refname, "got/", 4) == 0)
1207 return 0;
1208 if (strncmp(refname, "remotes/", 8) == 0)
1209 return 0;
1211 if (strncmp(wanted_ref, "refs/", 5) == 0)
1212 wanted_ref += 5;
1214 /* Allow prefix match. */
1215 if (got_path_is_child(refname, wanted_ref, strlen(wanted_ref)))
1216 return 1;
1218 /* Allow exact match. */
1219 return (strcmp(refname, wanted_ref) == 0);
1222 static int
1223 is_wanted_ref(struct got_pathlist_head *wanted_refs, const char *refname)
1225 struct got_pathlist_entry *pe;
1227 TAILQ_FOREACH(pe, wanted_refs, entry) {
1228 if (match_wanted_ref(refname, pe->path))
1229 return 1;
1232 return 0;
1235 static const struct got_error *
1236 create_wanted_ref(const char *refname, struct got_object_id *id,
1237 const char *remote_repo_name, int verbosity, struct got_repository *repo)
1239 const struct got_error *err;
1240 char *remote_refname;
1242 if (strncmp("refs/", refname, 5) == 0)
1243 refname += 5;
1245 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
1246 remote_repo_name, refname) == -1)
1247 return got_error_from_errno("asprintf");
1249 err = create_ref(remote_refname, id, verbosity, repo);
1250 free(remote_refname);
1251 return err;
1254 static const struct got_error *
1255 create_gotconfig(const char *proto, const char *host, const char *port,
1256 const char *remote_repo_path, const char *default_branch,
1257 int fetch_all_branches, struct got_pathlist_head *wanted_branches,
1258 struct got_pathlist_head *wanted_refs, int mirror_references,
1259 struct got_repository *repo)
1261 const struct got_error *err = NULL;
1262 char *gotconfig_path = NULL;
1263 char *gotconfig = NULL;
1264 FILE *gotconfig_file = NULL;
1265 const char *branchname = NULL;
1266 char *branches = NULL, *refs = NULL;
1267 ssize_t n;
1269 if (!fetch_all_branches && !TAILQ_EMPTY(wanted_branches)) {
1270 struct got_pathlist_entry *pe;
1271 TAILQ_FOREACH(pe, wanted_branches, entry) {
1272 char *s;
1273 branchname = pe->path;
1274 if (strncmp(branchname, "refs/heads/", 11) == 0)
1275 branchname += 11;
1276 if (asprintf(&s, "%s\"%s\" ",
1277 branches ? branches : "", branchname) == -1) {
1278 err = got_error_from_errno("asprintf");
1279 goto done;
1281 free(branches);
1282 branches = s;
1284 } else if (!fetch_all_branches && default_branch) {
1285 branchname = default_branch;
1286 if (strncmp(branchname, "refs/heads/", 11) == 0)
1287 branchname += 11;
1288 if (asprintf(&branches, "\"%s\" ", branchname) == -1) {
1289 err = got_error_from_errno("asprintf");
1290 goto done;
1293 if (!TAILQ_EMPTY(wanted_refs)) {
1294 struct got_pathlist_entry *pe;
1295 TAILQ_FOREACH(pe, wanted_refs, entry) {
1296 char *s;
1297 const char *refname = pe->path;
1298 if (strncmp(refname, "refs/", 5) == 0)
1299 branchname += 5;
1300 if (asprintf(&s, "%s\"%s\" ",
1301 refs ? refs : "", refname) == -1) {
1302 err = got_error_from_errno("asprintf");
1303 goto done;
1305 free(refs);
1306 refs = s;
1310 /* Create got.conf(5). */
1311 gotconfig_path = got_repo_get_path_gotconfig(repo);
1312 if (gotconfig_path == NULL) {
1313 err = got_error_from_errno("got_repo_get_path_gotconfig");
1314 goto done;
1316 gotconfig_file = fopen(gotconfig_path, "ae");
1317 if (gotconfig_file == NULL) {
1318 err = got_error_from_errno2("fopen", gotconfig_path);
1319 goto done;
1321 if (asprintf(&gotconfig,
1322 "remote \"%s\" {\n"
1323 "\tserver %s\n"
1324 "\tprotocol %s\n"
1325 "%s%s%s"
1326 "\trepository \"%s\"\n"
1327 "%s%s%s"
1328 "%s%s%s"
1329 "%s"
1330 "%s"
1331 "}\n",
1332 GOT_FETCH_DEFAULT_REMOTE_NAME, host, proto,
1333 port ? "\tport " : "", port ? port : "", port ? "\n" : "",
1334 remote_repo_path, branches ? "\tbranch { " : "",
1335 branches ? branches : "", branches ? "}\n" : "",
1336 refs ? "\treference { " : "", refs ? refs : "", refs ? "}\n" : "",
1337 mirror_references ? "\tmirror_references yes\n" : "",
1338 fetch_all_branches ? "\tfetch_all_branches yes\n" : "") == -1) {
1339 err = got_error_from_errno("asprintf");
1340 goto done;
1342 n = fwrite(gotconfig, 1, strlen(gotconfig), gotconfig_file);
1343 if (n != strlen(gotconfig)) {
1344 err = got_ferror(gotconfig_file, GOT_ERR_IO);
1345 goto done;
1348 done:
1349 if (gotconfig_file && fclose(gotconfig_file) == EOF && err == NULL)
1350 err = got_error_from_errno2("fclose", gotconfig_path);
1351 free(gotconfig_path);
1352 free(branches);
1353 return err;
1356 static const struct got_error *
1357 create_gitconfig(const char *git_url, const char *default_branch,
1358 int fetch_all_branches, struct got_pathlist_head *wanted_branches,
1359 struct got_pathlist_head *wanted_refs, int mirror_references,
1360 struct got_repository *repo)
1362 const struct got_error *err = NULL;
1363 char *gitconfig_path = NULL;
1364 char *gitconfig = NULL;
1365 FILE *gitconfig_file = NULL;
1366 char *branches = NULL, *refs = NULL;
1367 const char *branchname;
1368 ssize_t n;
1370 /* Create a config file Git can understand. */
1371 gitconfig_path = got_repo_get_path_gitconfig(repo);
1372 if (gitconfig_path == NULL) {
1373 err = got_error_from_errno("got_repo_get_path_gitconfig");
1374 goto done;
1376 gitconfig_file = fopen(gitconfig_path, "ae");
1377 if (gitconfig_file == NULL) {
1378 err = got_error_from_errno2("fopen", gitconfig_path);
1379 goto done;
1381 if (fetch_all_branches) {
1382 if (mirror_references) {
1383 if (asprintf(&branches,
1384 "\tfetch = refs/heads/*:refs/heads/*\n") == -1) {
1385 err = got_error_from_errno("asprintf");
1386 goto done;
1388 } else if (asprintf(&branches,
1389 "\tfetch = refs/heads/*:refs/remotes/%s/*\n",
1390 GOT_FETCH_DEFAULT_REMOTE_NAME) == -1) {
1391 err = got_error_from_errno("asprintf");
1392 goto done;
1394 } else if (!TAILQ_EMPTY(wanted_branches)) {
1395 struct got_pathlist_entry *pe;
1396 TAILQ_FOREACH(pe, wanted_branches, entry) {
1397 char *s;
1398 branchname = pe->path;
1399 if (strncmp(branchname, "refs/heads/", 11) == 0)
1400 branchname += 11;
1401 if (mirror_references) {
1402 if (asprintf(&s,
1403 "%s\tfetch = refs/heads/%s:refs/heads/%s\n",
1404 branches ? branches : "",
1405 branchname, branchname) == -1) {
1406 err = got_error_from_errno("asprintf");
1407 goto done;
1409 } else if (asprintf(&s,
1410 "%s\tfetch = refs/heads/%s:refs/remotes/%s/%s\n",
1411 branches ? branches : "",
1412 branchname, GOT_FETCH_DEFAULT_REMOTE_NAME,
1413 branchname) == -1) {
1414 err = got_error_from_errno("asprintf");
1415 goto done;
1417 free(branches);
1418 branches = s;
1420 } else {
1422 * If the server specified a default branch, use just that one.
1423 * Otherwise fall back to fetching all branches on next fetch.
1425 if (default_branch) {
1426 branchname = default_branch;
1427 if (strncmp(branchname, "refs/heads/", 11) == 0)
1428 branchname += 11;
1429 } else
1430 branchname = "*"; /* fall back to all branches */
1431 if (mirror_references) {
1432 if (asprintf(&branches,
1433 "\tfetch = refs/heads/%s:refs/heads/%s\n",
1434 branchname, branchname) == -1) {
1435 err = got_error_from_errno("asprintf");
1436 goto done;
1438 } else if (asprintf(&branches,
1439 "\tfetch = refs/heads/%s:refs/remotes/%s/%s\n",
1440 branchname, GOT_FETCH_DEFAULT_REMOTE_NAME,
1441 branchname) == -1) {
1442 err = got_error_from_errno("asprintf");
1443 goto done;
1446 if (!TAILQ_EMPTY(wanted_refs)) {
1447 struct got_pathlist_entry *pe;
1448 TAILQ_FOREACH(pe, wanted_refs, entry) {
1449 char *s;
1450 const char *refname = pe->path;
1451 if (strncmp(refname, "refs/", 5) == 0)
1452 refname += 5;
1453 if (mirror_references) {
1454 if (asprintf(&s,
1455 "%s\tfetch = refs/%s:refs/%s\n",
1456 refs ? refs : "", refname, refname) == -1) {
1457 err = got_error_from_errno("asprintf");
1458 goto done;
1460 } else if (asprintf(&s,
1461 "%s\tfetch = refs/%s:refs/remotes/%s/%s\n",
1462 refs ? refs : "",
1463 refname, GOT_FETCH_DEFAULT_REMOTE_NAME,
1464 refname) == -1) {
1465 err = got_error_from_errno("asprintf");
1466 goto done;
1468 free(refs);
1469 refs = s;
1473 if (asprintf(&gitconfig,
1474 "[remote \"%s\"]\n"
1475 "\turl = %s\n"
1476 "%s"
1477 "%s"
1478 "\tfetch = refs/tags/*:refs/tags/*\n",
1479 GOT_FETCH_DEFAULT_REMOTE_NAME, git_url, branches ? branches : "",
1480 refs ? refs : "") == -1) {
1481 err = got_error_from_errno("asprintf");
1482 goto done;
1484 n = fwrite(gitconfig, 1, strlen(gitconfig), gitconfig_file);
1485 if (n != strlen(gitconfig)) {
1486 err = got_ferror(gitconfig_file, GOT_ERR_IO);
1487 goto done;
1489 done:
1490 if (gitconfig_file && fclose(gitconfig_file) == EOF && err == NULL)
1491 err = got_error_from_errno2("fclose", gitconfig_path);
1492 free(gitconfig_path);
1493 free(branches);
1494 return err;
1497 static const struct got_error *
1498 create_config_files(const char *proto, const char *host, const char *port,
1499 const char *remote_repo_path, const char *git_url, int fetch_all_branches,
1500 int mirror_references, struct got_pathlist_head *symrefs,
1501 struct got_pathlist_head *wanted_branches,
1502 struct got_pathlist_head *wanted_refs, struct got_repository *repo)
1504 const struct got_error *err = NULL;
1505 const char *default_branch = NULL;
1506 struct got_pathlist_entry *pe;
1509 * If we asked for a set of wanted branches then use the first
1510 * one of those.
1512 if (!TAILQ_EMPTY(wanted_branches)) {
1513 pe = TAILQ_FIRST(wanted_branches);
1514 default_branch = pe->path;
1515 } else {
1516 /* First HEAD ref listed by server is the default branch. */
1517 TAILQ_FOREACH(pe, symrefs, entry) {
1518 const char *refname = pe->path;
1519 const char *target = pe->data;
1521 if (strcmp(refname, GOT_REF_HEAD) != 0)
1522 continue;
1524 default_branch = target;
1525 break;
1529 /* Create got.conf(5). */
1530 err = create_gotconfig(proto, host, port, remote_repo_path,
1531 default_branch, fetch_all_branches, wanted_branches,
1532 wanted_refs, mirror_references, repo);
1533 if (err)
1534 return err;
1536 /* Create a config file Git can understand. */
1537 return create_gitconfig(git_url, default_branch, fetch_all_branches,
1538 wanted_branches, wanted_refs, mirror_references, repo);
1541 static const struct got_error *
1542 cmd_clone(int argc, char *argv[])
1544 const struct got_error *error = NULL;
1545 const char *uri, *dirname;
1546 char *proto, *host, *port, *repo_name, *server_path;
1547 char *default_destdir = NULL, *id_str = NULL;
1548 const char *repo_path;
1549 struct got_repository *repo = NULL;
1550 struct got_pathlist_head refs, symrefs, wanted_branches, wanted_refs;
1551 struct got_pathlist_entry *pe;
1552 struct got_object_id *pack_hash = NULL;
1553 int ch, fetchfd = -1, fetchstatus;
1554 pid_t fetchpid = -1;
1555 struct got_fetch_progress_arg fpa;
1556 char *git_url = NULL;
1557 int verbosity = 0, fetch_all_branches = 0, mirror_references = 0;
1558 int bflag = 0, list_refs_only = 0;
1559 int *pack_fds = NULL;
1561 TAILQ_INIT(&refs);
1562 TAILQ_INIT(&symrefs);
1563 TAILQ_INIT(&wanted_branches);
1564 TAILQ_INIT(&wanted_refs);
1566 while ((ch = getopt(argc, argv, "ab:lmqR:v")) != -1) {
1567 switch (ch) {
1568 case 'a':
1569 fetch_all_branches = 1;
1570 break;
1571 case 'b':
1572 error = got_pathlist_append(&wanted_branches,
1573 optarg, NULL);
1574 if (error)
1575 return error;
1576 bflag = 1;
1577 break;
1578 case 'l':
1579 list_refs_only = 1;
1580 break;
1581 case 'm':
1582 mirror_references = 1;
1583 break;
1584 case 'q':
1585 verbosity = -1;
1586 break;
1587 case 'R':
1588 error = got_pathlist_append(&wanted_refs,
1589 optarg, NULL);
1590 if (error)
1591 return error;
1592 break;
1593 case 'v':
1594 if (verbosity < 0)
1595 verbosity = 0;
1596 else if (verbosity < 3)
1597 verbosity++;
1598 break;
1599 default:
1600 usage_clone();
1601 break;
1604 argc -= optind;
1605 argv += optind;
1607 if (fetch_all_branches && !TAILQ_EMPTY(&wanted_branches))
1608 option_conflict('a', 'b');
1609 if (list_refs_only) {
1610 if (!TAILQ_EMPTY(&wanted_branches))
1611 option_conflict('l', 'b');
1612 if (fetch_all_branches)
1613 option_conflict('l', 'a');
1614 if (mirror_references)
1615 option_conflict('l', 'm');
1616 if (!TAILQ_EMPTY(&wanted_refs))
1617 option_conflict('l', 'R');
1620 uri = argv[0];
1622 if (argc == 1)
1623 dirname = NULL;
1624 else if (argc == 2)
1625 dirname = argv[1];
1626 else
1627 usage_clone();
1629 error = got_dial_parse_uri(&proto, &host, &port, &server_path,
1630 &repo_name, uri);
1631 if (error)
1632 goto done;
1634 if (asprintf(&git_url, "%s://%s%s%s%s%s", proto,
1635 host, port ? ":" : "", port ? port : "",
1636 server_path[0] != '/' ? "/" : "", server_path) == -1) {
1637 error = got_error_from_errno("asprintf");
1638 goto done;
1641 if (strcmp(proto, "git") == 0) {
1642 #ifndef PROFILE
1643 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
1644 "sendfd dns inet unveil", NULL) == -1)
1645 err(1, "pledge");
1646 #endif
1647 } else if (strcmp(proto, "git+ssh") == 0 ||
1648 strcmp(proto, "ssh") == 0) {
1649 #ifndef PROFILE
1650 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
1651 "sendfd unveil", NULL) == -1)
1652 err(1, "pledge");
1653 #endif
1654 } else if (strcmp(proto, "http") == 0 ||
1655 strcmp(proto, "git+http") == 0) {
1656 error = got_error_path(proto, GOT_ERR_NOT_IMPL);
1657 goto done;
1658 } else {
1659 error = got_error_path(proto, GOT_ERR_BAD_PROTO);
1660 goto done;
1662 if (dirname == NULL) {
1663 if (asprintf(&default_destdir, "%s.git", repo_name) == -1) {
1664 error = got_error_from_errno("asprintf");
1665 goto done;
1667 repo_path = default_destdir;
1668 } else
1669 repo_path = dirname;
1671 if (!list_refs_only) {
1672 error = got_path_mkdir(repo_path);
1673 if (error &&
1674 (!(error->code == GOT_ERR_ERRNO && errno == EISDIR) &&
1675 !(error->code == GOT_ERR_ERRNO && errno == EEXIST)))
1676 goto done;
1677 if (!got_path_dir_is_empty(repo_path)) {
1678 error = got_error_path(repo_path,
1679 GOT_ERR_DIR_NOT_EMPTY);
1680 goto done;
1684 error = got_dial_apply_unveil(proto);
1685 if (error)
1686 goto done;
1688 error = apply_unveil(repo_path, 0, NULL);
1689 if (error)
1690 goto done;
1692 if (verbosity >= 0)
1693 printf("Connecting to %s\n", git_url);
1695 error = got_fetch_connect(&fetchpid, &fetchfd, proto, host, port,
1696 server_path, verbosity);
1697 if (error)
1698 goto done;
1700 if (!list_refs_only) {
1701 error = got_repo_init(repo_path, NULL);
1702 if (error)
1703 goto done;
1704 error = got_repo_pack_fds_open(&pack_fds);
1705 if (error != NULL)
1706 goto done;
1707 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
1708 if (error)
1709 goto done;
1712 fpa.last_scaled_size[0] = '\0';
1713 fpa.last_p_indexed = -1;
1714 fpa.last_p_resolved = -1;
1715 fpa.verbosity = verbosity;
1716 fpa.create_configs = 1;
1717 fpa.configs_created = 0;
1718 fpa.repo = repo;
1719 fpa.config_info.symrefs = &symrefs;
1720 fpa.config_info.wanted_branches = &wanted_branches;
1721 fpa.config_info.wanted_refs = &wanted_refs;
1722 fpa.config_info.proto = proto;
1723 fpa.config_info.host = host;
1724 fpa.config_info.port = port;
1725 fpa.config_info.remote_repo_path = server_path;
1726 fpa.config_info.git_url = git_url;
1727 fpa.config_info.fetch_all_branches = fetch_all_branches;
1728 fpa.config_info.mirror_references = mirror_references;
1729 error = got_fetch_pack(&pack_hash, &refs, &symrefs,
1730 GOT_FETCH_DEFAULT_REMOTE_NAME, mirror_references,
1731 fetch_all_branches, &wanted_branches, &wanted_refs,
1732 list_refs_only, verbosity, fetchfd, repo, NULL, NULL, bflag,
1733 fetch_progress, &fpa);
1734 if (error)
1735 goto done;
1737 if (list_refs_only) {
1738 error = list_remote_refs(&symrefs, &refs);
1739 goto done;
1742 if (pack_hash == NULL) {
1743 error = got_error_fmt(GOT_ERR_FETCH_FAILED, "%s",
1744 "server sent an empty pack file");
1745 goto done;
1747 error = got_object_id_str(&id_str, pack_hash);
1748 if (error)
1749 goto done;
1750 if (verbosity >= 0)
1751 printf("\nFetched %s.pack\n", id_str);
1752 free(id_str);
1754 /* Set up references provided with the pack file. */
1755 TAILQ_FOREACH(pe, &refs, entry) {
1756 const char *refname = pe->path;
1757 struct got_object_id *id = pe->data;
1758 char *remote_refname;
1760 if (is_wanted_ref(&wanted_refs, refname) &&
1761 !mirror_references) {
1762 error = create_wanted_ref(refname, id,
1763 GOT_FETCH_DEFAULT_REMOTE_NAME,
1764 verbosity - 1, repo);
1765 if (error)
1766 goto done;
1767 continue;
1770 error = create_ref(refname, id, verbosity - 1, repo);
1771 if (error)
1772 goto done;
1774 if (mirror_references)
1775 continue;
1777 if (strncmp("refs/heads/", refname, 11) != 0)
1778 continue;
1780 if (asprintf(&remote_refname,
1781 "refs/remotes/%s/%s", GOT_FETCH_DEFAULT_REMOTE_NAME,
1782 refname + 11) == -1) {
1783 error = got_error_from_errno("asprintf");
1784 goto done;
1786 error = create_ref(remote_refname, id, verbosity - 1, repo);
1787 free(remote_refname);
1788 if (error)
1789 goto done;
1792 /* Set the HEAD reference if the server provided one. */
1793 TAILQ_FOREACH(pe, &symrefs, entry) {
1794 struct got_reference *target_ref;
1795 const char *refname = pe->path;
1796 const char *target = pe->data;
1797 char *remote_refname = NULL, *remote_target = NULL;
1799 if (strcmp(refname, GOT_REF_HEAD) != 0)
1800 continue;
1802 error = got_ref_open(&target_ref, repo, target, 0);
1803 if (error) {
1804 if (error->code == GOT_ERR_NOT_REF) {
1805 error = NULL;
1806 continue;
1808 goto done;
1811 error = create_symref(refname, target_ref, verbosity, repo);
1812 got_ref_close(target_ref);
1813 if (error)
1814 goto done;
1816 if (mirror_references)
1817 continue;
1819 if (strncmp("refs/heads/", target, 11) != 0)
1820 continue;
1822 if (asprintf(&remote_refname,
1823 "refs/remotes/%s/%s", GOT_FETCH_DEFAULT_REMOTE_NAME,
1824 refname) == -1) {
1825 error = got_error_from_errno("asprintf");
1826 goto done;
1828 if (asprintf(&remote_target,
1829 "refs/remotes/%s/%s", GOT_FETCH_DEFAULT_REMOTE_NAME,
1830 target + 11) == -1) {
1831 error = got_error_from_errno("asprintf");
1832 free(remote_refname);
1833 goto done;
1835 error = got_ref_open(&target_ref, repo, remote_target, 0);
1836 if (error) {
1837 free(remote_refname);
1838 free(remote_target);
1839 if (error->code == GOT_ERR_NOT_REF) {
1840 error = NULL;
1841 continue;
1843 goto done;
1845 error = create_symref(remote_refname, target_ref,
1846 verbosity - 1, repo);
1847 free(remote_refname);
1848 free(remote_target);
1849 got_ref_close(target_ref);
1850 if (error)
1851 goto done;
1853 if (pe == NULL) {
1855 * We failed to set the HEAD reference. If we asked for
1856 * a set of wanted branches use the first of one of those
1857 * which could be fetched instead.
1859 TAILQ_FOREACH(pe, &wanted_branches, entry) {
1860 const char *target = pe->path;
1861 struct got_reference *target_ref;
1863 error = got_ref_open(&target_ref, repo, target, 0);
1864 if (error) {
1865 if (error->code == GOT_ERR_NOT_REF) {
1866 error = NULL;
1867 continue;
1869 goto done;
1872 error = create_symref(GOT_REF_HEAD, target_ref,
1873 verbosity, repo);
1874 got_ref_close(target_ref);
1875 if (error)
1876 goto done;
1877 break;
1880 if (!fpa.configs_created && pe != NULL) {
1881 error = create_config_files(fpa.config_info.proto,
1882 fpa.config_info.host, fpa.config_info.port,
1883 fpa.config_info.remote_repo_path,
1884 fpa.config_info.git_url,
1885 fpa.config_info.fetch_all_branches,
1886 fpa.config_info.mirror_references,
1887 fpa.config_info.symrefs,
1888 fpa.config_info.wanted_branches,
1889 fpa.config_info.wanted_refs, fpa.repo);
1890 if (error)
1891 goto done;
1895 if (verbosity >= 0)
1896 printf("Created %s repository '%s'\n",
1897 mirror_references ? "mirrored" : "cloned", repo_path);
1898 done:
1899 if (pack_fds) {
1900 const struct got_error *pack_err =
1901 got_repo_pack_fds_close(pack_fds);
1902 if (error == NULL)
1903 error = pack_err;
1905 if (fetchpid > 0) {
1906 if (kill(fetchpid, SIGTERM) == -1)
1907 error = got_error_from_errno("kill");
1908 if (waitpid(fetchpid, &fetchstatus, 0) == -1 && error == NULL)
1909 error = got_error_from_errno("waitpid");
1911 if (fetchfd != -1 && close(fetchfd) == -1 && error == NULL)
1912 error = got_error_from_errno("close");
1913 if (repo) {
1914 const struct got_error *close_err = got_repo_close(repo);
1915 if (error == NULL)
1916 error = close_err;
1918 got_pathlist_free(&refs, GOT_PATHLIST_FREE_ALL);
1919 got_pathlist_free(&symrefs, GOT_PATHLIST_FREE_ALL);
1920 got_pathlist_free(&wanted_branches, GOT_PATHLIST_FREE_NONE);
1921 got_pathlist_free(&wanted_refs, GOT_PATHLIST_FREE_NONE);
1922 free(pack_hash);
1923 free(proto);
1924 free(host);
1925 free(port);
1926 free(server_path);
1927 free(repo_name);
1928 free(default_destdir);
1929 free(git_url);
1930 return error;
1933 static const struct got_error *
1934 update_ref(struct got_reference *ref, struct got_object_id *new_id,
1935 int replace_tags, int verbosity, struct got_repository *repo)
1937 const struct got_error *err = NULL;
1938 char *new_id_str = NULL;
1939 struct got_object_id *old_id = NULL;
1941 err = got_object_id_str(&new_id_str, new_id);
1942 if (err)
1943 goto done;
1945 if (!replace_tags &&
1946 strncmp(got_ref_get_name(ref), "refs/tags/", 10) == 0) {
1947 err = got_ref_resolve(&old_id, repo, ref);
1948 if (err)
1949 goto done;
1950 if (got_object_id_cmp(old_id, new_id) == 0)
1951 goto done;
1952 if (verbosity >= 0) {
1953 printf("Rejecting update of existing tag %s: %s\n",
1954 got_ref_get_name(ref), new_id_str);
1956 goto done;
1959 if (got_ref_is_symbolic(ref)) {
1960 if (verbosity >= 0) {
1961 printf("Replacing reference %s: %s\n",
1962 got_ref_get_name(ref),
1963 got_ref_get_symref_target(ref));
1965 err = got_ref_change_symref_to_ref(ref, new_id);
1966 if (err)
1967 goto done;
1968 err = got_ref_write(ref, repo);
1969 if (err)
1970 goto done;
1971 } else {
1972 err = got_ref_resolve(&old_id, repo, ref);
1973 if (err)
1974 goto done;
1975 if (got_object_id_cmp(old_id, new_id) == 0)
1976 goto done;
1978 err = got_ref_change_ref(ref, new_id);
1979 if (err)
1980 goto done;
1981 err = got_ref_write(ref, repo);
1982 if (err)
1983 goto done;
1986 if (verbosity >= 0)
1987 printf("Updated %s: %s\n", got_ref_get_name(ref),
1988 new_id_str);
1989 done:
1990 free(old_id);
1991 free(new_id_str);
1992 return err;
1995 static const struct got_error *
1996 update_symref(const char *refname, struct got_reference *target_ref,
1997 int verbosity, struct got_repository *repo)
1999 const struct got_error *err = NULL, *unlock_err;
2000 struct got_reference *symref;
2001 int symref_is_locked = 0;
2003 err = got_ref_open(&symref, repo, refname, 1);
2004 if (err) {
2005 if (err->code != GOT_ERR_NOT_REF)
2006 return err;
2007 err = got_ref_alloc_symref(&symref, refname, target_ref);
2008 if (err)
2009 goto done;
2011 err = got_ref_write(symref, repo);
2012 if (err)
2013 goto done;
2015 if (verbosity >= 0)
2016 printf("Created reference %s: %s\n",
2017 got_ref_get_name(symref),
2018 got_ref_get_symref_target(symref));
2019 } else {
2020 symref_is_locked = 1;
2022 if (strcmp(got_ref_get_symref_target(symref),
2023 got_ref_get_name(target_ref)) == 0)
2024 goto done;
2026 err = got_ref_change_symref(symref,
2027 got_ref_get_name(target_ref));
2028 if (err)
2029 goto done;
2031 err = got_ref_write(symref, repo);
2032 if (err)
2033 goto done;
2035 if (verbosity >= 0)
2036 printf("Updated %s: %s\n", got_ref_get_name(symref),
2037 got_ref_get_symref_target(symref));
2040 done:
2041 if (symref_is_locked) {
2042 unlock_err = got_ref_unlock(symref);
2043 if (unlock_err && err == NULL)
2044 err = unlock_err;
2046 got_ref_close(symref);
2047 return err;
2050 __dead static void
2051 usage_fetch(void)
2053 fprintf(stderr, "usage: %s fetch [-adlqtvX] [-b branch] "
2054 "[-R reference] [-r repository-path] [remote-repository]\n",
2055 getprogname());
2056 exit(1);
2059 static const struct got_error *
2060 delete_missing_ref(struct got_reference *ref,
2061 int verbosity, struct got_repository *repo)
2063 const struct got_error *err = NULL;
2064 struct got_object_id *id = NULL;
2065 char *id_str = NULL;
2067 if (got_ref_is_symbolic(ref)) {
2068 err = got_ref_delete(ref, repo);
2069 if (err)
2070 return err;
2071 if (verbosity >= 0) {
2072 printf("Deleted %s: %s\n",
2073 got_ref_get_name(ref),
2074 got_ref_get_symref_target(ref));
2076 } else {
2077 err = got_ref_resolve(&id, repo, ref);
2078 if (err)
2079 return err;
2080 err = got_object_id_str(&id_str, id);
2081 if (err)
2082 goto done;
2084 err = got_ref_delete(ref, repo);
2085 if (err)
2086 goto done;
2087 if (verbosity >= 0) {
2088 printf("Deleted %s: %s\n",
2089 got_ref_get_name(ref), id_str);
2092 done:
2093 free(id);
2094 free(id_str);
2095 return err;
2098 static const struct got_error *
2099 delete_missing_refs(struct got_pathlist_head *their_refs,
2100 struct got_pathlist_head *their_symrefs,
2101 const struct got_remote_repo *remote,
2102 int verbosity, struct got_repository *repo)
2104 const struct got_error *err = NULL, *unlock_err;
2105 struct got_reflist_head my_refs;
2106 struct got_reflist_entry *re;
2107 struct got_pathlist_entry *pe;
2108 char *remote_namespace = NULL;
2109 char *local_refname = NULL;
2111 TAILQ_INIT(&my_refs);
2113 if (asprintf(&remote_namespace, "refs/remotes/%s/", remote->name)
2114 == -1)
2115 return got_error_from_errno("asprintf");
2117 err = got_ref_list(&my_refs, repo, NULL, got_ref_cmp_by_name, NULL);
2118 if (err)
2119 goto done;
2121 TAILQ_FOREACH(re, &my_refs, entry) {
2122 const char *refname = got_ref_get_name(re->ref);
2123 const char *their_refname;
2125 if (remote->mirror_references) {
2126 their_refname = refname;
2127 } else {
2128 if (strncmp(refname, remote_namespace,
2129 strlen(remote_namespace)) == 0) {
2130 if (strcmp(refname + strlen(remote_namespace),
2131 GOT_REF_HEAD) == 0)
2132 continue;
2133 if (asprintf(&local_refname, "refs/heads/%s",
2134 refname + strlen(remote_namespace)) == -1) {
2135 err = got_error_from_errno("asprintf");
2136 goto done;
2138 } else if (strncmp(refname, "refs/tags/", 10) != 0)
2139 continue;
2141 their_refname = local_refname;
2144 TAILQ_FOREACH(pe, their_refs, entry) {
2145 if (strcmp(their_refname, pe->path) == 0)
2146 break;
2148 if (pe != NULL)
2149 continue;
2151 TAILQ_FOREACH(pe, their_symrefs, entry) {
2152 if (strcmp(their_refname, pe->path) == 0)
2153 break;
2155 if (pe != NULL)
2156 continue;
2158 err = delete_missing_ref(re->ref, verbosity, repo);
2159 if (err)
2160 break;
2162 if (local_refname) {
2163 struct got_reference *ref;
2164 err = got_ref_open(&ref, repo, local_refname, 1);
2165 if (err) {
2166 if (err->code != GOT_ERR_NOT_REF)
2167 break;
2168 free(local_refname);
2169 local_refname = NULL;
2170 continue;
2172 err = delete_missing_ref(ref, verbosity, repo);
2173 if (err)
2174 break;
2175 unlock_err = got_ref_unlock(ref);
2176 got_ref_close(ref);
2177 if (unlock_err && err == NULL) {
2178 err = unlock_err;
2179 break;
2182 free(local_refname);
2183 local_refname = NULL;
2186 done:
2187 got_ref_list_free(&my_refs);
2188 free(remote_namespace);
2189 free(local_refname);
2190 return err;
2193 static const struct got_error *
2194 update_wanted_ref(const char *refname, struct got_object_id *id,
2195 const char *remote_repo_name, int verbosity, struct got_repository *repo)
2197 const struct got_error *err, *unlock_err;
2198 char *remote_refname;
2199 struct got_reference *ref;
2201 if (strncmp("refs/", refname, 5) == 0)
2202 refname += 5;
2204 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
2205 remote_repo_name, refname) == -1)
2206 return got_error_from_errno("asprintf");
2208 err = got_ref_open(&ref, repo, remote_refname, 1);
2209 if (err) {
2210 if (err->code != GOT_ERR_NOT_REF)
2211 goto done;
2212 err = create_ref(remote_refname, id, verbosity, repo);
2213 } else {
2214 err = update_ref(ref, id, 0, verbosity, repo);
2215 unlock_err = got_ref_unlock(ref);
2216 if (unlock_err && err == NULL)
2217 err = unlock_err;
2218 got_ref_close(ref);
2220 done:
2221 free(remote_refname);
2222 return err;
2225 static const struct got_error *
2226 delete_ref(struct got_repository *repo, struct got_reference *ref)
2228 const struct got_error *err = NULL;
2229 struct got_object_id *id = NULL;
2230 char *id_str = NULL;
2231 const char *target;
2233 if (got_ref_is_symbolic(ref)) {
2234 target = got_ref_get_symref_target(ref);
2235 } else {
2236 err = got_ref_resolve(&id, repo, ref);
2237 if (err)
2238 goto done;
2239 err = got_object_id_str(&id_str, id);
2240 if (err)
2241 goto done;
2242 target = id_str;
2245 err = got_ref_delete(ref, repo);
2246 if (err)
2247 goto done;
2249 printf("Deleted %s: %s\n", got_ref_get_name(ref), target);
2250 done:
2251 free(id);
2252 free(id_str);
2253 return err;
2256 static const struct got_error *
2257 delete_refs_for_remote(struct got_repository *repo, const char *remote_name)
2259 const struct got_error *err = NULL;
2260 struct got_reflist_head refs;
2261 struct got_reflist_entry *re;
2262 char *prefix;
2264 TAILQ_INIT(&refs);
2266 if (asprintf(&prefix, "refs/remotes/%s", remote_name) == -1) {
2267 err = got_error_from_errno("asprintf");
2268 goto done;
2270 err = got_ref_list(&refs, repo, prefix, got_ref_cmp_by_name, NULL);
2271 if (err)
2272 goto done;
2274 TAILQ_FOREACH(re, &refs, entry)
2275 delete_ref(repo, re->ref);
2276 done:
2277 got_ref_list_free(&refs);
2278 return err;
2281 static const struct got_error *
2282 cmd_fetch(int argc, char *argv[])
2284 const struct got_error *error = NULL, *unlock_err;
2285 char *cwd = NULL, *repo_path = NULL;
2286 const char *remote_name;
2287 char *proto = NULL, *host = NULL, *port = NULL;
2288 char *repo_name = NULL, *server_path = NULL;
2289 const struct got_remote_repo *remotes;
2290 struct got_remote_repo *remote = NULL;
2291 int nremotes;
2292 char *id_str = NULL;
2293 struct got_repository *repo = NULL;
2294 struct got_worktree *worktree = NULL;
2295 const struct got_gotconfig *repo_conf = NULL, *worktree_conf = NULL;
2296 struct got_pathlist_head refs, symrefs, wanted_branches, wanted_refs;
2297 char *head_refname = NULL;
2298 struct got_pathlist_entry *pe;
2299 struct got_reflist_head remote_refs;
2300 struct got_reflist_entry *re;
2301 struct got_object_id *pack_hash = NULL;
2302 int i, ch, fetchfd = -1, fetchstatus;
2303 pid_t fetchpid = -1;
2304 struct got_fetch_progress_arg fpa;
2305 int verbosity = 0, fetch_all_branches = 0, list_refs_only = 0;
2306 int delete_refs = 0, replace_tags = 0, delete_remote = 0;
2307 int *pack_fds = NULL, have_bflag = 0;
2308 const char *remote_head = NULL, *worktree_branch = NULL;
2310 TAILQ_INIT(&refs);
2311 TAILQ_INIT(&symrefs);
2312 TAILQ_INIT(&remote_refs);
2313 TAILQ_INIT(&wanted_branches);
2314 TAILQ_INIT(&wanted_refs);
2316 while ((ch = getopt(argc, argv, "ab:dlqR:r:tvX")) != -1) {
2317 switch (ch) {
2318 case 'a':
2319 fetch_all_branches = 1;
2320 break;
2321 case 'b':
2322 error = got_pathlist_append(&wanted_branches,
2323 optarg, NULL);
2324 if (error)
2325 return error;
2326 have_bflag = 1;
2327 break;
2328 case 'd':
2329 delete_refs = 1;
2330 break;
2331 case 'l':
2332 list_refs_only = 1;
2333 break;
2334 case 'q':
2335 verbosity = -1;
2336 break;
2337 case 'R':
2338 error = got_pathlist_append(&wanted_refs,
2339 optarg, NULL);
2340 if (error)
2341 return error;
2342 break;
2343 case 'r':
2344 repo_path = realpath(optarg, NULL);
2345 if (repo_path == NULL)
2346 return got_error_from_errno2("realpath",
2347 optarg);
2348 got_path_strip_trailing_slashes(repo_path);
2349 break;
2350 case 't':
2351 replace_tags = 1;
2352 break;
2353 case 'v':
2354 if (verbosity < 0)
2355 verbosity = 0;
2356 else if (verbosity < 3)
2357 verbosity++;
2358 break;
2359 case 'X':
2360 delete_remote = 1;
2361 break;
2362 default:
2363 usage_fetch();
2364 break;
2367 argc -= optind;
2368 argv += optind;
2370 if (fetch_all_branches && !TAILQ_EMPTY(&wanted_branches))
2371 option_conflict('a', 'b');
2372 if (list_refs_only) {
2373 if (!TAILQ_EMPTY(&wanted_branches))
2374 option_conflict('l', 'b');
2375 if (fetch_all_branches)
2376 option_conflict('l', 'a');
2377 if (delete_refs)
2378 option_conflict('l', 'd');
2379 if (delete_remote)
2380 option_conflict('l', 'X');
2382 if (delete_remote) {
2383 if (fetch_all_branches)
2384 option_conflict('X', 'a');
2385 if (!TAILQ_EMPTY(&wanted_branches))
2386 option_conflict('X', 'b');
2387 if (delete_refs)
2388 option_conflict('X', 'd');
2389 if (replace_tags)
2390 option_conflict('X', 't');
2391 if (!TAILQ_EMPTY(&wanted_refs))
2392 option_conflict('X', 'R');
2395 if (argc == 0) {
2396 if (delete_remote)
2397 errx(1, "-X option requires a remote name");
2398 remote_name = GOT_FETCH_DEFAULT_REMOTE_NAME;
2399 } else if (argc == 1)
2400 remote_name = argv[0];
2401 else
2402 usage_fetch();
2404 cwd = getcwd(NULL, 0);
2405 if (cwd == NULL) {
2406 error = got_error_from_errno("getcwd");
2407 goto done;
2410 error = got_repo_pack_fds_open(&pack_fds);
2411 if (error != NULL)
2412 goto done;
2414 if (repo_path == NULL) {
2415 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
2416 if (error && error->code != GOT_ERR_NOT_WORKTREE)
2417 goto done;
2418 else
2419 error = NULL;
2420 if (worktree) {
2421 repo_path =
2422 strdup(got_worktree_get_repo_path(worktree));
2423 if (repo_path == NULL)
2424 error = got_error_from_errno("strdup");
2425 if (error)
2426 goto done;
2427 } else {
2428 repo_path = strdup(cwd);
2429 if (repo_path == NULL) {
2430 error = got_error_from_errno("strdup");
2431 goto done;
2436 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
2437 if (error)
2438 goto done;
2440 if (delete_remote) {
2441 error = delete_refs_for_remote(repo, remote_name);
2442 goto done; /* nothing else to do */
2445 if (worktree) {
2446 worktree_conf = got_worktree_get_gotconfig(worktree);
2447 if (worktree_conf) {
2448 got_gotconfig_get_remotes(&nremotes, &remotes,
2449 worktree_conf);
2450 for (i = 0; i < nremotes; i++) {
2451 if (strcmp(remotes[i].name, remote_name) == 0) {
2452 error = got_repo_remote_repo_dup(&remote,
2453 &remotes[i]);
2454 if (error)
2455 goto done;
2456 break;
2461 if (remote == NULL) {
2462 repo_conf = got_repo_get_gotconfig(repo);
2463 if (repo_conf) {
2464 got_gotconfig_get_remotes(&nremotes, &remotes,
2465 repo_conf);
2466 for (i = 0; i < nremotes; i++) {
2467 if (strcmp(remotes[i].name, remote_name) == 0) {
2468 error = got_repo_remote_repo_dup(&remote,
2469 &remotes[i]);
2470 if (error)
2471 goto done;
2472 break;
2477 if (remote == NULL) {
2478 got_repo_get_gitconfig_remotes(&nremotes, &remotes, repo);
2479 for (i = 0; i < nremotes; i++) {
2480 if (strcmp(remotes[i].name, remote_name) == 0) {
2481 error = got_repo_remote_repo_dup(&remote,
2482 &remotes[i]);
2483 if (error)
2484 goto done;
2485 break;
2489 if (remote == NULL) {
2490 error = got_error_path(remote_name, GOT_ERR_NO_REMOTE);
2491 goto done;
2494 if (TAILQ_EMPTY(&wanted_branches)) {
2495 if (!fetch_all_branches)
2496 fetch_all_branches = remote->fetch_all_branches;
2497 for (i = 0; i < remote->nfetch_branches; i++) {
2498 error = got_pathlist_append(&wanted_branches,
2499 remote->fetch_branches[i], NULL);
2500 if (error)
2501 goto done;
2504 if (TAILQ_EMPTY(&wanted_refs)) {
2505 for (i = 0; i < remote->nfetch_refs; i++) {
2506 error = got_pathlist_append(&wanted_refs,
2507 remote->fetch_refs[i], NULL);
2508 if (error)
2509 goto done;
2513 error = got_dial_parse_uri(&proto, &host, &port, &server_path,
2514 &repo_name, remote->fetch_url);
2515 if (error)
2516 goto done;
2518 if (strcmp(proto, "git") == 0) {
2519 #ifndef PROFILE
2520 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
2521 "sendfd dns inet unveil", NULL) == -1)
2522 err(1, "pledge");
2523 #endif
2524 } else if (strcmp(proto, "git+ssh") == 0 ||
2525 strcmp(proto, "ssh") == 0) {
2526 #ifndef PROFILE
2527 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
2528 "sendfd unveil", NULL) == -1)
2529 err(1, "pledge");
2530 #endif
2531 } else if (strcmp(proto, "http") == 0 ||
2532 strcmp(proto, "git+http") == 0) {
2533 error = got_error_path(proto, GOT_ERR_NOT_IMPL);
2534 goto done;
2535 } else {
2536 error = got_error_path(proto, GOT_ERR_BAD_PROTO);
2537 goto done;
2540 error = got_dial_apply_unveil(proto);
2541 if (error)
2542 goto done;
2544 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
2545 if (error)
2546 goto done;
2548 if (worktree) {
2549 head_refname = strdup(got_worktree_get_head_ref_name(worktree));
2550 if (head_refname == NULL) {
2551 error = got_error_from_errno("strdup");
2552 goto done;
2555 /* Release work tree lock. */
2556 got_worktree_close(worktree);
2557 worktree = NULL;
2560 if (verbosity >= 0) {
2561 printf("Connecting to \"%s\" %s://%s%s%s%s%s\n",
2562 remote->name, proto, host,
2563 port ? ":" : "", port ? port : "",
2564 *server_path == '/' ? "" : "/", server_path);
2567 error = got_fetch_connect(&fetchpid, &fetchfd, proto, host, port,
2568 server_path, verbosity);
2569 if (error)
2570 goto done;
2572 if (!have_bflag) {
2574 * If set, get this remote's HEAD ref target so
2575 * if it has changed on the server we can fetch it.
2577 error = got_ref_list(&remote_refs, repo, "refs/remotes",
2578 got_ref_cmp_by_name, repo);
2579 if (error)
2580 goto done;
2582 TAILQ_FOREACH(re, &remote_refs, entry) {
2583 const char *remote_refname, *remote_target;
2584 size_t remote_name_len;
2586 if (!got_ref_is_symbolic(re->ref))
2587 continue;
2589 remote_name_len = strlen(remote->name);
2590 remote_refname = got_ref_get_name(re->ref);
2592 /* we only want refs/remotes/$remote->name/HEAD */
2593 if (strncmp(remote_refname + 13, remote->name,
2594 remote_name_len) != 0)
2595 continue;
2597 if (strcmp(remote_refname + remote_name_len + 14,
2598 GOT_REF_HEAD) != 0)
2599 continue;
2602 * Take the name itself because we already
2603 * only match with refs/heads/ in fetch_pack().
2605 remote_target = got_ref_get_symref_target(re->ref);
2606 remote_head = remote_target + remote_name_len + 14;
2607 break;
2610 if (head_refname &&
2611 strncmp(head_refname, "refs/heads/", 11) == 0)
2612 worktree_branch = head_refname;
2615 fpa.last_scaled_size[0] = '\0';
2616 fpa.last_p_indexed = -1;
2617 fpa.last_p_resolved = -1;
2618 fpa.verbosity = verbosity;
2619 fpa.repo = repo;
2620 fpa.create_configs = 0;
2621 fpa.configs_created = 0;
2622 memset(&fpa.config_info, 0, sizeof(fpa.config_info));
2624 error = got_fetch_pack(&pack_hash, &refs, &symrefs, remote->name,
2625 remote->mirror_references, fetch_all_branches, &wanted_branches,
2626 &wanted_refs, list_refs_only, verbosity, fetchfd, repo,
2627 worktree_branch, remote_head, have_bflag, fetch_progress, &fpa);
2628 if (error)
2629 goto done;
2631 if (list_refs_only) {
2632 error = list_remote_refs(&symrefs, &refs);
2633 goto done;
2636 if (pack_hash == NULL) {
2637 if (verbosity >= 0)
2638 printf("Already up-to-date\n");
2639 } else if (verbosity >= 0) {
2640 error = got_object_id_str(&id_str, pack_hash);
2641 if (error)
2642 goto done;
2643 printf("\nFetched %s.pack\n", id_str);
2644 free(id_str);
2645 id_str = NULL;
2648 /* Update references provided with the pack file. */
2649 TAILQ_FOREACH(pe, &refs, entry) {
2650 const char *refname = pe->path;
2651 struct got_object_id *id = pe->data;
2652 struct got_reference *ref;
2653 char *remote_refname;
2655 if (is_wanted_ref(&wanted_refs, refname) &&
2656 !remote->mirror_references) {
2657 error = update_wanted_ref(refname, id,
2658 remote->name, verbosity, repo);
2659 if (error)
2660 goto done;
2661 continue;
2664 if (remote->mirror_references ||
2665 strncmp("refs/tags/", refname, 10) == 0) {
2666 error = got_ref_open(&ref, repo, refname, 1);
2667 if (error) {
2668 if (error->code != GOT_ERR_NOT_REF)
2669 goto done;
2670 error = create_ref(refname, id, verbosity,
2671 repo);
2672 if (error)
2673 goto done;
2674 } else {
2675 error = update_ref(ref, id, replace_tags,
2676 verbosity, repo);
2677 unlock_err = got_ref_unlock(ref);
2678 if (unlock_err && error == NULL)
2679 error = unlock_err;
2680 got_ref_close(ref);
2681 if (error)
2682 goto done;
2684 } else if (strncmp("refs/heads/", refname, 11) == 0) {
2685 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
2686 remote_name, refname + 11) == -1) {
2687 error = got_error_from_errno("asprintf");
2688 goto done;
2691 error = got_ref_open(&ref, repo, remote_refname, 1);
2692 if (error) {
2693 if (error->code != GOT_ERR_NOT_REF)
2694 goto done;
2695 error = create_ref(remote_refname, id,
2696 verbosity, repo);
2697 if (error)
2698 goto done;
2699 } else {
2700 error = update_ref(ref, id, replace_tags,
2701 verbosity, repo);
2702 unlock_err = got_ref_unlock(ref);
2703 if (unlock_err && error == NULL)
2704 error = unlock_err;
2705 got_ref_close(ref);
2706 if (error)
2707 goto done;
2710 /* Also create a local branch if none exists yet. */
2711 error = got_ref_open(&ref, repo, refname, 1);
2712 if (error) {
2713 if (error->code != GOT_ERR_NOT_REF)
2714 goto done;
2715 error = create_ref(refname, id, verbosity,
2716 repo);
2717 if (error)
2718 goto done;
2719 } else {
2720 unlock_err = got_ref_unlock(ref);
2721 if (unlock_err && error == NULL)
2722 error = unlock_err;
2723 got_ref_close(ref);
2727 if (delete_refs) {
2728 error = delete_missing_refs(&refs, &symrefs, remote,
2729 verbosity, repo);
2730 if (error)
2731 goto done;
2734 if (!remote->mirror_references) {
2735 /* Update remote HEAD reference if the server provided one. */
2736 TAILQ_FOREACH(pe, &symrefs, entry) {
2737 struct got_reference *target_ref;
2738 const char *refname = pe->path;
2739 const char *target = pe->data;
2740 char *remote_refname = NULL, *remote_target = NULL;
2742 if (strcmp(refname, GOT_REF_HEAD) != 0)
2743 continue;
2745 if (strncmp("refs/heads/", target, 11) != 0)
2746 continue;
2748 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
2749 remote->name, refname) == -1) {
2750 error = got_error_from_errno("asprintf");
2751 goto done;
2753 if (asprintf(&remote_target, "refs/remotes/%s/%s",
2754 remote->name, target + 11) == -1) {
2755 error = got_error_from_errno("asprintf");
2756 free(remote_refname);
2757 goto done;
2760 error = got_ref_open(&target_ref, repo, remote_target,
2761 0);
2762 if (error) {
2763 free(remote_refname);
2764 free(remote_target);
2765 if (error->code == GOT_ERR_NOT_REF) {
2766 error = NULL;
2767 continue;
2769 goto done;
2771 error = update_symref(remote_refname, target_ref,
2772 verbosity, repo);
2773 free(remote_refname);
2774 free(remote_target);
2775 got_ref_close(target_ref);
2776 if (error)
2777 goto done;
2780 done:
2781 if (fetchpid > 0) {
2782 if (kill(fetchpid, SIGTERM) == -1)
2783 error = got_error_from_errno("kill");
2784 if (waitpid(fetchpid, &fetchstatus, 0) == -1 && error == NULL)
2785 error = got_error_from_errno("waitpid");
2787 if (fetchfd != -1 && close(fetchfd) == -1 && error == NULL)
2788 error = got_error_from_errno("close");
2789 if (repo) {
2790 const struct got_error *close_err = got_repo_close(repo);
2791 if (error == NULL)
2792 error = close_err;
2794 if (worktree)
2795 got_worktree_close(worktree);
2796 if (pack_fds) {
2797 const struct got_error *pack_err =
2798 got_repo_pack_fds_close(pack_fds);
2799 if (error == NULL)
2800 error = pack_err;
2802 got_pathlist_free(&refs, GOT_PATHLIST_FREE_ALL);
2803 got_pathlist_free(&symrefs, GOT_PATHLIST_FREE_ALL);
2804 got_pathlist_free(&wanted_branches, GOT_PATHLIST_FREE_NONE);
2805 got_pathlist_free(&wanted_refs, GOT_PATHLIST_FREE_NONE);
2806 got_ref_list_free(&remote_refs);
2807 got_repo_free_remote_repo_data(remote);
2808 free(remote);
2809 free(head_refname);
2810 free(id_str);
2811 free(cwd);
2812 free(repo_path);
2813 free(pack_hash);
2814 free(proto);
2815 free(host);
2816 free(port);
2817 free(server_path);
2818 free(repo_name);
2819 return error;
2823 __dead static void
2824 usage_checkout(void)
2826 fprintf(stderr, "usage: %s checkout [-Eq] [-b branch] [-c commit] "
2827 "[-p path-prefix] repository-path [work-tree-path]\n",
2828 getprogname());
2829 exit(1);
2832 static void
2833 show_worktree_base_ref_warning(void)
2835 fprintf(stderr, "%s: warning: could not create a reference "
2836 "to the work tree's base commit; the commit could be "
2837 "garbage-collected by Git or 'gotadmin cleanup'; making the "
2838 "repository writable and running 'got update' will prevent this\n",
2839 getprogname());
2842 struct got_checkout_progress_arg {
2843 const char *worktree_path;
2844 int had_base_commit_ref_error;
2845 int verbosity;
2848 static const struct got_error *
2849 checkout_progress(void *arg, unsigned char status, const char *path)
2851 struct got_checkout_progress_arg *a = arg;
2853 /* Base commit bump happens silently. */
2854 if (status == GOT_STATUS_BUMP_BASE)
2855 return NULL;
2857 if (status == GOT_STATUS_BASE_REF_ERR) {
2858 a->had_base_commit_ref_error = 1;
2859 return NULL;
2862 while (path[0] == '/')
2863 path++;
2865 if (a->verbosity >= 0)
2866 printf("%c %s/%s\n", status, a->worktree_path, path);
2868 return NULL;
2871 static const struct got_error *
2872 check_cancelled(void *arg)
2874 if (sigint_received || sigpipe_received)
2875 return got_error(GOT_ERR_CANCELLED);
2876 return NULL;
2879 static const struct got_error *
2880 check_linear_ancestry(struct got_object_id *commit_id,
2881 struct got_object_id *base_commit_id, int allow_forwards_in_time_only,
2882 struct got_repository *repo)
2884 const struct got_error *err = NULL;
2885 struct got_object_id *yca_id;
2887 err = got_commit_graph_find_youngest_common_ancestor(&yca_id,
2888 commit_id, base_commit_id, 1, 0, repo, check_cancelled, NULL);
2889 if (err)
2890 return err;
2892 if (yca_id == NULL)
2893 return got_error(GOT_ERR_ANCESTRY);
2896 * Require a straight line of history between the target commit
2897 * and the work tree's base commit.
2899 * Non-linear situations such as this require a rebase:
2901 * (commit) D F (base_commit)
2902 * \ /
2903 * C E
2904 * \ /
2905 * B (yca)
2906 * |
2907 * A
2909 * 'got update' only handles linear cases:
2910 * Update forwards in time: A (base/yca) - B - C - D (commit)
2911 * Update backwards in time: D (base) - C - B - A (commit/yca)
2913 if (allow_forwards_in_time_only) {
2914 if (got_object_id_cmp(base_commit_id, yca_id) != 0)
2915 return got_error(GOT_ERR_ANCESTRY);
2916 } else if (got_object_id_cmp(commit_id, yca_id) != 0 &&
2917 got_object_id_cmp(base_commit_id, yca_id) != 0)
2918 return got_error(GOT_ERR_ANCESTRY);
2920 free(yca_id);
2921 return NULL;
2924 static const struct got_error *
2925 check_same_branch(struct got_object_id *commit_id,
2926 struct got_reference *head_ref, struct got_repository *repo)
2928 const struct got_error *err = NULL;
2929 struct got_commit_graph *graph = NULL;
2930 struct got_object_id *head_commit_id = NULL;
2932 err = got_ref_resolve(&head_commit_id, repo, head_ref);
2933 if (err)
2934 goto done;
2936 if (got_object_id_cmp(head_commit_id, commit_id) == 0)
2937 goto done;
2939 err = got_commit_graph_open(&graph, "/", 1);
2940 if (err)
2941 goto done;
2943 err = got_commit_graph_bfsort(graph, head_commit_id, repo,
2944 check_cancelled, NULL);
2945 if (err)
2946 goto done;
2948 for (;;) {
2949 struct got_object_id id;
2951 err = got_commit_graph_iter_next(&id, graph, repo,
2952 check_cancelled, NULL);
2953 if (err) {
2954 if (err->code == GOT_ERR_ITER_COMPLETED)
2955 err = got_error(GOT_ERR_ANCESTRY);
2956 break;
2959 if (got_object_id_cmp(&id, commit_id) == 0)
2960 break;
2962 done:
2963 if (graph)
2964 got_commit_graph_close(graph);
2965 free(head_commit_id);
2966 return err;
2969 static const struct got_error *
2970 checkout_ancestry_error(struct got_reference *ref, const char *commit_id_str)
2972 static char msg[512];
2973 const char *branch_name;
2975 if (got_ref_is_symbolic(ref))
2976 branch_name = got_ref_get_symref_target(ref);
2977 else
2978 branch_name = got_ref_get_name(ref);
2980 if (strncmp("refs/heads/", branch_name, 11) == 0)
2981 branch_name += 11;
2983 snprintf(msg, sizeof(msg),
2984 "target commit is not contained in branch '%s'; "
2985 "the branch to use must be specified with -b; "
2986 "if necessary a new branch can be created for "
2987 "this commit with 'got branch -c %s BRANCH_NAME'",
2988 branch_name, commit_id_str);
2990 return got_error_msg(GOT_ERR_ANCESTRY, msg);
2993 static const struct got_error *
2994 cmd_checkout(int argc, char *argv[])
2996 const struct got_error *close_err, *error = NULL;
2997 struct got_repository *repo = NULL;
2998 struct got_reference *head_ref = NULL, *ref = NULL;
2999 struct got_worktree *worktree = NULL;
3000 char *repo_path = NULL;
3001 char *worktree_path = NULL;
3002 const char *path_prefix = "";
3003 const char *branch_name = GOT_REF_HEAD, *refname = NULL;
3004 char *commit_id_str = NULL, *keyword_idstr = NULL;
3005 struct got_object_id *commit_id = NULL;
3006 char *cwd = NULL;
3007 int ch, same_path_prefix, allow_nonempty = 0, verbosity = 0;
3008 struct got_pathlist_head paths;
3009 struct got_checkout_progress_arg cpa;
3010 int *pack_fds = NULL;
3012 TAILQ_INIT(&paths);
3014 #ifndef PROFILE
3015 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
3016 "unveil", NULL) == -1)
3017 err(1, "pledge");
3018 #endif
3020 while ((ch = getopt(argc, argv, "b:c:Ep:q")) != -1) {
3021 switch (ch) {
3022 case 'b':
3023 branch_name = optarg;
3024 break;
3025 case 'c':
3026 commit_id_str = strdup(optarg);
3027 if (commit_id_str == NULL)
3028 return got_error_from_errno("strdup");
3029 break;
3030 case 'E':
3031 allow_nonempty = 1;
3032 break;
3033 case 'p':
3034 path_prefix = optarg;
3035 break;
3036 case 'q':
3037 verbosity = -1;
3038 break;
3039 default:
3040 usage_checkout();
3041 /* NOTREACHED */
3045 argc -= optind;
3046 argv += optind;
3048 if (argc == 1) {
3049 char *base, *dotgit;
3050 const char *path;
3051 repo_path = realpath(argv[0], NULL);
3052 if (repo_path == NULL)
3053 return got_error_from_errno2("realpath", argv[0]);
3054 cwd = getcwd(NULL, 0);
3055 if (cwd == NULL) {
3056 error = got_error_from_errno("getcwd");
3057 goto done;
3059 if (path_prefix[0])
3060 path = path_prefix;
3061 else
3062 path = repo_path;
3063 error = got_path_basename(&base, path);
3064 if (error)
3065 goto done;
3066 dotgit = strstr(base, ".git");
3067 if (dotgit)
3068 *dotgit = '\0';
3069 if (asprintf(&worktree_path, "%s/%s", cwd, base) == -1) {
3070 error = got_error_from_errno("asprintf");
3071 free(base);
3072 goto done;
3074 free(base);
3075 } else if (argc == 2) {
3076 repo_path = realpath(argv[0], NULL);
3077 if (repo_path == NULL) {
3078 error = got_error_from_errno2("realpath", argv[0]);
3079 goto done;
3081 worktree_path = realpath(argv[1], NULL);
3082 if (worktree_path == NULL) {
3083 if (errno != ENOENT) {
3084 error = got_error_from_errno2("realpath",
3085 argv[1]);
3086 goto done;
3088 worktree_path = strdup(argv[1]);
3089 if (worktree_path == NULL) {
3090 error = got_error_from_errno("strdup");
3091 goto done;
3094 } else
3095 usage_checkout();
3097 got_path_strip_trailing_slashes(repo_path);
3098 got_path_strip_trailing_slashes(worktree_path);
3100 if (got_path_is_child(worktree_path, repo_path, strlen(repo_path)) ||
3101 got_path_is_child(repo_path, worktree_path,
3102 strlen(worktree_path))) {
3103 error = got_error_fmt(GOT_ERR_BAD_PATH,
3104 "work tree and repository paths may not overlap: %s",
3105 worktree_path);
3106 goto done;
3109 error = got_repo_pack_fds_open(&pack_fds);
3110 if (error != NULL)
3111 goto done;
3113 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
3114 if (error != NULL)
3115 goto done;
3117 /* Pre-create work tree path for unveil(2) */
3118 error = got_path_mkdir(worktree_path);
3119 if (error) {
3120 if (!(error->code == GOT_ERR_ERRNO && errno == EISDIR) &&
3121 !(error->code == GOT_ERR_ERRNO && errno == EEXIST))
3122 goto done;
3123 if (!allow_nonempty &&
3124 !got_path_dir_is_empty(worktree_path)) {
3125 error = got_error_path(worktree_path,
3126 GOT_ERR_DIR_NOT_EMPTY);
3127 goto done;
3131 error = apply_unveil(got_repo_get_path(repo), 0, worktree_path);
3132 if (error)
3133 goto done;
3135 error = got_ref_open(&head_ref, repo, branch_name, 0);
3136 if (error != NULL)
3137 goto done;
3139 error = got_worktree_init(worktree_path, head_ref, path_prefix,
3140 GOT_WORKTREE_GOT_DIR, repo);
3141 if (error != NULL && !(error->code == GOT_ERR_ERRNO && errno == EEXIST))
3142 goto done;
3144 error = got_worktree_open(&worktree, worktree_path,
3145 GOT_WORKTREE_GOT_DIR);
3146 if (error != NULL)
3147 goto done;
3149 error = got_worktree_match_path_prefix(&same_path_prefix, worktree,
3150 path_prefix);
3151 if (error != NULL)
3152 goto done;
3153 if (!same_path_prefix) {
3154 error = got_error(GOT_ERR_PATH_PREFIX);
3155 goto done;
3158 if (commit_id_str) {
3159 struct got_reflist_head refs;
3160 TAILQ_INIT(&refs);
3161 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
3162 NULL);
3163 if (error)
3164 goto done;
3166 error = got_keyword_to_idstr(&keyword_idstr, commit_id_str,
3167 repo, worktree);
3168 if (error != NULL)
3169 goto done;
3170 if (keyword_idstr != NULL) {
3171 free(commit_id_str);
3172 commit_id_str = keyword_idstr;
3175 error = got_repo_match_object_id(&commit_id, NULL,
3176 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
3177 got_ref_list_free(&refs);
3178 if (error)
3179 goto done;
3180 error = check_linear_ancestry(commit_id,
3181 got_worktree_get_base_commit_id(worktree), 0, repo);
3182 if (error != NULL) {
3183 if (error->code == GOT_ERR_ANCESTRY) {
3184 error = checkout_ancestry_error(
3185 head_ref, commit_id_str);
3187 goto done;
3189 error = check_same_branch(commit_id, head_ref, repo);
3190 if (error) {
3191 if (error->code == GOT_ERR_ANCESTRY) {
3192 error = checkout_ancestry_error(
3193 head_ref, commit_id_str);
3195 goto done;
3197 error = got_worktree_set_base_commit_id(worktree, repo,
3198 commit_id);
3199 if (error)
3200 goto done;
3201 /* Expand potentially abbreviated commit ID string. */
3202 free(commit_id_str);
3203 error = got_object_id_str(&commit_id_str, commit_id);
3204 if (error)
3205 goto done;
3206 } else {
3207 commit_id = got_object_id_dup(
3208 got_worktree_get_base_commit_id(worktree));
3209 if (commit_id == NULL) {
3210 error = got_error_from_errno("got_object_id_dup");
3211 goto done;
3213 error = got_object_id_str(&commit_id_str, commit_id);
3214 if (error)
3215 goto done;
3218 error = got_pathlist_append(&paths, "", NULL);
3219 if (error)
3220 goto done;
3221 cpa.worktree_path = worktree_path;
3222 cpa.had_base_commit_ref_error = 0;
3223 cpa.verbosity = verbosity;
3224 error = got_worktree_checkout_files(worktree, &paths, repo,
3225 checkout_progress, &cpa, check_cancelled, NULL);
3226 if (error != NULL)
3227 goto done;
3229 if (got_ref_is_symbolic(head_ref)) {
3230 error = got_ref_resolve_symbolic(&ref, repo, head_ref);
3231 if (error)
3232 goto done;
3233 refname = got_ref_get_name(ref);
3234 } else
3235 refname = got_ref_get_name(head_ref);
3236 printf("Checked out %s: %s\n", refname, commit_id_str);
3237 printf("Now shut up and hack\n");
3238 if (cpa.had_base_commit_ref_error)
3239 show_worktree_base_ref_warning();
3240 done:
3241 if (pack_fds) {
3242 const struct got_error *pack_err =
3243 got_repo_pack_fds_close(pack_fds);
3244 if (error == NULL)
3245 error = pack_err;
3247 if (head_ref)
3248 got_ref_close(head_ref);
3249 if (ref)
3250 got_ref_close(ref);
3251 if (repo) {
3252 close_err = got_repo_close(repo);
3253 if (error == NULL)
3254 error = close_err;
3256 if (worktree != NULL) {
3257 close_err = got_worktree_close(worktree);
3258 if (error == NULL)
3259 error = close_err;
3261 got_pathlist_free(&paths, GOT_PATHLIST_FREE_NONE);
3262 free(commit_id_str);
3263 free(commit_id);
3264 free(repo_path);
3265 free(worktree_path);
3266 free(cwd);
3267 return error;
3270 struct got_update_progress_arg {
3271 int did_something;
3272 int conflicts;
3273 int obstructed;
3274 int not_updated;
3275 int missing;
3276 int not_deleted;
3277 int unversioned;
3278 int verbosity;
3281 static void
3282 print_update_progress_stats(struct got_update_progress_arg *upa)
3284 if (!upa->did_something)
3285 return;
3287 if (upa->conflicts > 0)
3288 printf("Files with new merge conflicts: %d\n", upa->conflicts);
3289 if (upa->obstructed > 0)
3290 printf("File paths obstructed by a non-regular file: %d\n",
3291 upa->obstructed);
3292 if (upa->not_updated > 0)
3293 printf("Files not updated because of existing merge "
3294 "conflicts: %d\n", upa->not_updated);
3298 * The meaning of some status codes differs between merge-style operations and
3299 * update operations. For example, the ! status code means "file was missing"
3300 * if changes were merged into the work tree, and "missing file was restored"
3301 * if the work tree was updated. This function should be used by any operation
3302 * which merges changes into the work tree without updating the work tree.
3304 static void
3305 print_merge_progress_stats(struct got_update_progress_arg *upa)
3307 if (!upa->did_something)
3308 return;
3310 if (upa->conflicts > 0)
3311 printf("Files with new merge conflicts: %d\n", upa->conflicts);
3312 if (upa->obstructed > 0)
3313 printf("File paths obstructed by a non-regular file: %d\n",
3314 upa->obstructed);
3315 if (upa->missing > 0)
3316 printf("Files which had incoming changes but could not be "
3317 "found in the work tree: %d\n", upa->missing);
3318 if (upa->not_deleted > 0)
3319 printf("Files not deleted due to differences in deleted "
3320 "content: %d\n", upa->not_deleted);
3321 if (upa->unversioned > 0)
3322 printf("Files not merged because an unversioned file was "
3323 "found in the work tree: %d\n", upa->unversioned);
3326 __dead static void
3327 usage_update(void)
3329 fprintf(stderr, "usage: %s update [-q] [-b branch] [-c commit] "
3330 "[path ...]\n", getprogname());
3331 exit(1);
3334 static const struct got_error *
3335 update_progress(void *arg, unsigned char status, const char *path)
3337 struct got_update_progress_arg *upa = arg;
3339 if (status == GOT_STATUS_EXISTS ||
3340 status == GOT_STATUS_BASE_REF_ERR)
3341 return NULL;
3343 upa->did_something = 1;
3345 /* Base commit bump happens silently. */
3346 if (status == GOT_STATUS_BUMP_BASE)
3347 return NULL;
3349 if (status == GOT_STATUS_CONFLICT)
3350 upa->conflicts++;
3351 if (status == GOT_STATUS_OBSTRUCTED)
3352 upa->obstructed++;
3353 if (status == GOT_STATUS_CANNOT_UPDATE)
3354 upa->not_updated++;
3355 if (status == GOT_STATUS_MISSING)
3356 upa->missing++;
3357 if (status == GOT_STATUS_CANNOT_DELETE)
3358 upa->not_deleted++;
3359 if (status == GOT_STATUS_UNVERSIONED)
3360 upa->unversioned++;
3362 while (path[0] == '/')
3363 path++;
3364 if (upa->verbosity >= 0)
3365 printf("%c %s\n", status, path);
3367 return NULL;
3370 static const struct got_error *
3371 switch_head_ref(struct got_reference *head_ref,
3372 struct got_object_id *commit_id, struct got_worktree *worktree,
3373 struct got_repository *repo)
3375 const struct got_error *err = NULL;
3376 char *base_id_str;
3377 int ref_has_moved = 0;
3379 /* Trivial case: switching between two different references. */
3380 if (strcmp(got_ref_get_name(head_ref),
3381 got_worktree_get_head_ref_name(worktree)) != 0) {
3382 printf("Switching work tree from %s to %s\n",
3383 got_worktree_get_head_ref_name(worktree),
3384 got_ref_get_name(head_ref));
3385 return got_worktree_set_head_ref(worktree, head_ref);
3388 err = check_linear_ancestry(commit_id,
3389 got_worktree_get_base_commit_id(worktree), 0, repo);
3390 if (err) {
3391 if (err->code != GOT_ERR_ANCESTRY)
3392 return err;
3393 ref_has_moved = 1;
3395 if (!ref_has_moved)
3396 return NULL;
3398 /* Switching to a rebased branch with the same reference name. */
3399 err = got_object_id_str(&base_id_str,
3400 got_worktree_get_base_commit_id(worktree));
3401 if (err)
3402 return err;
3403 printf("Reference %s now points at a different branch\n",
3404 got_worktree_get_head_ref_name(worktree));
3405 printf("Switching work tree from %s to %s\n", base_id_str,
3406 got_worktree_get_head_ref_name(worktree));
3407 return NULL;
3410 static const struct got_error *
3411 check_rebase_or_histedit_in_progress(struct got_worktree *worktree)
3413 const struct got_error *err;
3414 int in_progress;
3416 err = got_worktree_rebase_in_progress(&in_progress, worktree);
3417 if (err)
3418 return err;
3419 if (in_progress)
3420 return got_error(GOT_ERR_REBASING);
3422 err = got_worktree_histedit_in_progress(&in_progress, worktree);
3423 if (err)
3424 return err;
3425 if (in_progress)
3426 return got_error(GOT_ERR_HISTEDIT_BUSY);
3428 return NULL;
3431 static const struct got_error *
3432 check_merge_in_progress(struct got_worktree *worktree,
3433 struct got_repository *repo)
3435 const struct got_error *err;
3436 int in_progress;
3438 err = got_worktree_merge_in_progress(&in_progress, worktree, repo);
3439 if (err)
3440 return err;
3441 if (in_progress)
3442 return got_error(GOT_ERR_MERGE_BUSY);
3444 return NULL;
3447 static const struct got_error *
3448 get_worktree_paths_from_argv(struct got_pathlist_head *paths, int argc,
3449 char *argv[], struct got_worktree *worktree)
3451 const struct got_error *err = NULL;
3452 char *path;
3453 struct got_pathlist_entry *new;
3454 int i;
3456 if (argc == 0) {
3457 path = strdup("");
3458 if (path == NULL)
3459 return got_error_from_errno("strdup");
3460 return got_pathlist_append(paths, path, NULL);
3463 for (i = 0; i < argc; i++) {
3464 err = got_worktree_resolve_path(&path, worktree, argv[i]);
3465 if (err)
3466 break;
3467 err = got_pathlist_insert(&new, paths, path, NULL);
3468 if (err || new == NULL /* duplicate */) {
3469 free(path);
3470 if (err)
3471 break;
3475 return err;
3478 static const struct got_error *
3479 wrap_not_worktree_error(const struct got_error *orig_err,
3480 const char *cmdname, const char *path)
3482 const struct got_error *err;
3483 struct got_repository *repo;
3484 static char msg[512];
3485 int *pack_fds = NULL;
3487 err = got_repo_pack_fds_open(&pack_fds);
3488 if (err)
3489 return err;
3491 err = got_repo_open(&repo, path, NULL, pack_fds);
3492 if (err)
3493 return orig_err;
3495 snprintf(msg, sizeof(msg),
3496 "'got %s' needs a work tree in addition to a git repository\n"
3497 "Work trees can be checked out from this Git repository with "
3498 "'got checkout'.\n"
3499 "The got(1) manual page contains more information.", cmdname);
3500 err = got_error_msg(GOT_ERR_NOT_WORKTREE, msg);
3501 if (repo) {
3502 const struct got_error *close_err = got_repo_close(repo);
3503 if (err == NULL)
3504 err = close_err;
3506 if (pack_fds) {
3507 const struct got_error *pack_err =
3508 got_repo_pack_fds_close(pack_fds);
3509 if (err == NULL)
3510 err = pack_err;
3512 return err;
3515 static const struct got_error *
3516 cmd_update(int argc, char *argv[])
3518 const struct got_error *close_err, *error = NULL;
3519 struct got_repository *repo = NULL;
3520 struct got_worktree *worktree = NULL;
3521 char *worktree_path = NULL;
3522 struct got_object_id *commit_id = NULL;
3523 char *commit_id_str = NULL;
3524 const char *branch_name = NULL;
3525 struct got_reference *head_ref = NULL;
3526 struct got_pathlist_head paths;
3527 struct got_pathlist_entry *pe;
3528 int ch, verbosity = 0;
3529 struct got_update_progress_arg upa;
3530 int *pack_fds = NULL;
3532 TAILQ_INIT(&paths);
3534 #ifndef PROFILE
3535 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
3536 "unveil", NULL) == -1)
3537 err(1, "pledge");
3538 #endif
3540 while ((ch = getopt(argc, argv, "b:c:q")) != -1) {
3541 switch (ch) {
3542 case 'b':
3543 branch_name = optarg;
3544 break;
3545 case 'c':
3546 commit_id_str = strdup(optarg);
3547 if (commit_id_str == NULL)
3548 return got_error_from_errno("strdup");
3549 break;
3550 case 'q':
3551 verbosity = -1;
3552 break;
3553 default:
3554 usage_update();
3555 /* NOTREACHED */
3559 argc -= optind;
3560 argv += optind;
3562 worktree_path = getcwd(NULL, 0);
3563 if (worktree_path == NULL) {
3564 error = got_error_from_errno("getcwd");
3565 goto done;
3568 error = got_repo_pack_fds_open(&pack_fds);
3569 if (error != NULL)
3570 goto done;
3572 error = got_worktree_open(&worktree, worktree_path,
3573 GOT_WORKTREE_GOT_DIR);
3574 if (error) {
3575 if (error->code == GOT_ERR_NOT_WORKTREE)
3576 error = wrap_not_worktree_error(error, "update",
3577 worktree_path);
3578 goto done;
3581 error = check_rebase_or_histedit_in_progress(worktree);
3582 if (error)
3583 goto done;
3585 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
3586 NULL, pack_fds);
3587 if (error != NULL)
3588 goto done;
3590 error = apply_unveil(got_repo_get_path(repo), 0,
3591 got_worktree_get_root_path(worktree));
3592 if (error)
3593 goto done;
3595 error = check_merge_in_progress(worktree, repo);
3596 if (error)
3597 goto done;
3599 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
3600 if (error)
3601 goto done;
3603 error = got_ref_open(&head_ref, repo, branch_name ? branch_name :
3604 got_worktree_get_head_ref_name(worktree), 0);
3605 if (error != NULL)
3606 goto done;
3607 if (commit_id_str == NULL) {
3608 error = got_ref_resolve(&commit_id, repo, head_ref);
3609 if (error != NULL)
3610 goto done;
3611 error = got_object_id_str(&commit_id_str, commit_id);
3612 if (error != NULL)
3613 goto done;
3614 } else {
3615 struct got_reflist_head refs;
3616 char *keyword_idstr = NULL;
3618 TAILQ_INIT(&refs);
3620 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
3621 NULL);
3622 if (error)
3623 goto done;
3625 error = got_keyword_to_idstr(&keyword_idstr, commit_id_str,
3626 repo, worktree);
3627 if (error != NULL)
3628 goto done;
3629 if (keyword_idstr != NULL) {
3630 free(commit_id_str);
3631 commit_id_str = keyword_idstr;
3634 error = got_repo_match_object_id(&commit_id, NULL,
3635 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
3636 got_ref_list_free(&refs);
3637 free(commit_id_str);
3638 commit_id_str = NULL;
3639 if (error)
3640 goto done;
3641 error = got_object_id_str(&commit_id_str, commit_id);
3642 if (error)
3643 goto done;
3646 if (branch_name) {
3647 struct got_object_id *head_commit_id;
3648 TAILQ_FOREACH(pe, &paths, entry) {
3649 if (pe->path_len == 0)
3650 continue;
3651 error = got_error_msg(GOT_ERR_BAD_PATH,
3652 "switching between branches requires that "
3653 "the entire work tree gets updated");
3654 goto done;
3656 error = got_ref_resolve(&head_commit_id, repo, head_ref);
3657 if (error)
3658 goto done;
3659 error = check_linear_ancestry(commit_id, head_commit_id, 0,
3660 repo);
3661 free(head_commit_id);
3662 if (error != NULL)
3663 goto done;
3664 error = check_same_branch(commit_id, head_ref, repo);
3665 if (error)
3666 goto done;
3667 error = switch_head_ref(head_ref, commit_id, worktree, repo);
3668 if (error)
3669 goto done;
3670 } else {
3671 error = check_linear_ancestry(commit_id,
3672 got_worktree_get_base_commit_id(worktree), 0, repo);
3673 if (error != NULL) {
3674 if (error->code == GOT_ERR_ANCESTRY)
3675 error = got_error(GOT_ERR_BRANCH_MOVED);
3676 goto done;
3678 error = check_same_branch(commit_id, head_ref, repo);
3679 if (error)
3680 goto done;
3683 if (got_object_id_cmp(got_worktree_get_base_commit_id(worktree),
3684 commit_id) != 0) {
3685 error = got_worktree_set_base_commit_id(worktree, repo,
3686 commit_id);
3687 if (error)
3688 goto done;
3691 memset(&upa, 0, sizeof(upa));
3692 upa.verbosity = verbosity;
3693 error = got_worktree_checkout_files(worktree, &paths, repo,
3694 update_progress, &upa, check_cancelled, NULL);
3695 if (error != NULL)
3696 goto done;
3698 if (upa.did_something) {
3699 printf("Updated to %s: %s\n",
3700 got_worktree_get_head_ref_name(worktree), commit_id_str);
3701 } else
3702 printf("Already up-to-date\n");
3704 print_update_progress_stats(&upa);
3705 done:
3706 if (pack_fds) {
3707 const struct got_error *pack_err =
3708 got_repo_pack_fds_close(pack_fds);
3709 if (error == NULL)
3710 error = pack_err;
3712 if (repo) {
3713 close_err = got_repo_close(repo);
3714 if (error == NULL)
3715 error = close_err;
3717 if (worktree != NULL) {
3718 close_err = got_worktree_close(worktree);
3719 if (error == NULL)
3720 error = close_err;
3722 if (head_ref != NULL)
3723 got_ref_close(head_ref);
3724 free(worktree_path);
3725 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
3726 free(commit_id);
3727 free(commit_id_str);
3728 return error;
3731 static const struct got_error *
3732 diff_blobs(struct got_object_id *blob_id1, struct got_object_id *blob_id2,
3733 const char *path, int diff_context, int ignore_whitespace,
3734 int force_text_diff, struct got_diffstat_cb_arg *dsa,
3735 struct got_repository *repo, FILE *outfile)
3737 const struct got_error *err = NULL;
3738 struct got_blob_object *blob1 = NULL, *blob2 = NULL;
3739 FILE *f1 = NULL, *f2 = NULL;
3740 int fd1 = -1, fd2 = -1;
3742 fd1 = got_opentempfd();
3743 if (fd1 == -1)
3744 return got_error_from_errno("got_opentempfd");
3745 fd2 = got_opentempfd();
3746 if (fd2 == -1) {
3747 err = got_error_from_errno("got_opentempfd");
3748 goto done;
3751 if (blob_id1) {
3752 err = got_object_open_as_blob(&blob1, repo, blob_id1, 8192,
3753 fd1);
3754 if (err)
3755 goto done;
3758 err = got_object_open_as_blob(&blob2, repo, blob_id2, 8192, fd2);
3759 if (err)
3760 goto done;
3762 f1 = got_opentemp();
3763 if (f1 == NULL) {
3764 err = got_error_from_errno("got_opentemp");
3765 goto done;
3767 f2 = got_opentemp();
3768 if (f2 == NULL) {
3769 err = got_error_from_errno("got_opentemp");
3770 goto done;
3773 while (path[0] == '/')
3774 path++;
3775 err = got_diff_blob(NULL, NULL, blob1, blob2, f1, f2, path, path,
3776 GOT_DIFF_ALGORITHM_PATIENCE, diff_context, ignore_whitespace,
3777 force_text_diff, dsa, outfile);
3778 done:
3779 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
3780 err = got_error_from_errno("close");
3781 if (blob1)
3782 got_object_blob_close(blob1);
3783 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
3784 err = got_error_from_errno("close");
3785 if (blob2)
3786 got_object_blob_close(blob2);
3787 if (f1 && fclose(f1) == EOF && err == NULL)
3788 err = got_error_from_errno("fclose");
3789 if (f2 && fclose(f2) == EOF && err == NULL)
3790 err = got_error_from_errno("fclose");
3791 return err;
3794 static const struct got_error *
3795 diff_trees(struct got_object_id *tree_id1, struct got_object_id *tree_id2,
3796 const char *path, int diff_context, int ignore_whitespace,
3797 int force_text_diff, struct got_diffstat_cb_arg *dsa,
3798 struct got_repository *repo, FILE *outfile)
3800 const struct got_error *err = NULL;
3801 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
3802 struct got_diff_blob_output_unidiff_arg arg;
3803 FILE *f1 = NULL, *f2 = NULL;
3804 int fd1 = -1, fd2 = -1;
3806 if (tree_id1) {
3807 err = got_object_open_as_tree(&tree1, repo, tree_id1);
3808 if (err)
3809 goto done;
3810 fd1 = got_opentempfd();
3811 if (fd1 == -1) {
3812 err = got_error_from_errno("got_opentempfd");
3813 goto done;
3817 err = got_object_open_as_tree(&tree2, repo, tree_id2);
3818 if (err)
3819 goto done;
3821 f1 = got_opentemp();
3822 if (f1 == NULL) {
3823 err = got_error_from_errno("got_opentemp");
3824 goto done;
3827 f2 = got_opentemp();
3828 if (f2 == NULL) {
3829 err = got_error_from_errno("got_opentemp");
3830 goto done;
3832 fd2 = got_opentempfd();
3833 if (fd2 == -1) {
3834 err = got_error_from_errno("got_opentempfd");
3835 goto done;
3837 arg.diff_context = diff_context;
3838 arg.ignore_whitespace = ignore_whitespace;
3839 arg.force_text_diff = force_text_diff;
3840 arg.diffstat = dsa;
3841 arg.diff_algo = GOT_DIFF_ALGORITHM_PATIENCE;
3842 arg.outfile = outfile;
3843 arg.lines = NULL;
3844 arg.nlines = 0;
3845 while (path[0] == '/')
3846 path++;
3847 err = got_diff_tree(tree1, tree2, f1, f2, fd1, fd2, path, path, repo,
3848 got_diff_blob_output_unidiff, &arg, 1);
3849 done:
3850 if (tree1)
3851 got_object_tree_close(tree1);
3852 if (tree2)
3853 got_object_tree_close(tree2);
3854 if (f1 && fclose(f1) == EOF && err == NULL)
3855 err = got_error_from_errno("fclose");
3856 if (f2 && fclose(f2) == EOF && err == NULL)
3857 err = got_error_from_errno("fclose");
3858 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
3859 err = got_error_from_errno("close");
3860 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
3861 err = got_error_from_errno("close");
3862 return err;
3865 static const struct got_error *
3866 get_changed_paths(struct got_pathlist_head *paths,
3867 struct got_commit_object *commit, struct got_repository *repo,
3868 struct got_diffstat_cb_arg *dsa)
3870 const struct got_error *err = NULL;
3871 struct got_object_id *tree_id1 = NULL, *tree_id2 = NULL;
3872 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
3873 struct got_object_qid *qid;
3874 got_diff_blob_cb cb = got_diff_tree_collect_changed_paths;
3875 FILE *f1 = NULL, *f2 = NULL;
3876 int fd1 = -1, fd2 = -1;
3878 if (dsa) {
3879 cb = got_diff_tree_compute_diffstat;
3881 f1 = got_opentemp();
3882 if (f1 == NULL) {
3883 err = got_error_from_errno("got_opentemp");
3884 goto done;
3886 f2 = got_opentemp();
3887 if (f2 == NULL) {
3888 err = got_error_from_errno("got_opentemp");
3889 goto done;
3891 fd1 = got_opentempfd();
3892 if (fd1 == -1) {
3893 err = got_error_from_errno("got_opentempfd");
3894 goto done;
3896 fd2 = got_opentempfd();
3897 if (fd2 == -1) {
3898 err = got_error_from_errno("got_opentempfd");
3899 goto done;
3903 qid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
3904 if (qid != NULL) {
3905 struct got_commit_object *pcommit;
3906 err = got_object_open_as_commit(&pcommit, repo,
3907 &qid->id);
3908 if (err)
3909 return err;
3911 tree_id1 = got_object_id_dup(
3912 got_object_commit_get_tree_id(pcommit));
3913 if (tree_id1 == NULL) {
3914 got_object_commit_close(pcommit);
3915 return got_error_from_errno("got_object_id_dup");
3917 got_object_commit_close(pcommit);
3921 if (tree_id1) {
3922 err = got_object_open_as_tree(&tree1, repo, tree_id1);
3923 if (err)
3924 goto done;
3927 tree_id2 = got_object_commit_get_tree_id(commit);
3928 err = got_object_open_as_tree(&tree2, repo, tree_id2);
3929 if (err)
3930 goto done;
3932 err = got_diff_tree(tree1, tree2, f1, f2, fd1, fd2, "", "", repo,
3933 cb, dsa ? (void *)dsa : paths, dsa ? 1 : 0);
3934 done:
3935 if (tree1)
3936 got_object_tree_close(tree1);
3937 if (tree2)
3938 got_object_tree_close(tree2);
3939 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
3940 err = got_error_from_errno("close");
3941 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
3942 err = got_error_from_errno("close");
3943 if (f1 && fclose(f1) == EOF && err == NULL)
3944 err = got_error_from_errno("fclose");
3945 if (f2 && fclose(f2) == EOF && err == NULL)
3946 err = got_error_from_errno("fclose");
3947 free(tree_id1);
3948 return err;
3951 static const struct got_error *
3952 print_patch(struct got_commit_object *commit, struct got_object_id *id,
3953 const char *path, int diff_context, struct got_diffstat_cb_arg *dsa,
3954 struct got_repository *repo, FILE *outfile)
3956 const struct got_error *err = NULL;
3957 struct got_commit_object *pcommit = NULL;
3958 char *id_str1 = NULL, *id_str2 = NULL;
3959 struct got_object_id *obj_id1 = NULL, *obj_id2 = NULL;
3960 struct got_object_qid *qid;
3962 qid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
3963 if (qid != NULL) {
3964 err = got_object_open_as_commit(&pcommit, repo,
3965 &qid->id);
3966 if (err)
3967 return err;
3968 err = got_object_id_str(&id_str1, &qid->id);
3969 if (err)
3970 goto done;
3973 err = got_object_id_str(&id_str2, id);
3974 if (err)
3975 goto done;
3977 if (path && path[0] != '\0') {
3978 int obj_type;
3979 err = got_object_id_by_path(&obj_id2, repo, commit, path);
3980 if (err)
3981 goto done;
3982 if (pcommit) {
3983 err = got_object_id_by_path(&obj_id1, repo,
3984 pcommit, path);
3985 if (err) {
3986 if (err->code != GOT_ERR_NO_TREE_ENTRY) {
3987 free(obj_id2);
3988 goto done;
3992 err = got_object_get_type(&obj_type, repo, obj_id2);
3993 if (err) {
3994 free(obj_id2);
3995 goto done;
3997 fprintf(outfile,
3998 "diff %s %s\n", id_str1 ? id_str1 : "/dev/null", id_str2);
3999 fprintf(outfile, "commit - %s\n",
4000 id_str1 ? id_str1 : "/dev/null");
4001 fprintf(outfile, "commit + %s\n", id_str2);
4002 switch (obj_type) {
4003 case GOT_OBJ_TYPE_BLOB:
4004 err = diff_blobs(obj_id1, obj_id2, path, diff_context,
4005 0, 0, dsa, repo, outfile);
4006 break;
4007 case GOT_OBJ_TYPE_TREE:
4008 err = diff_trees(obj_id1, obj_id2, path, diff_context,
4009 0, 0, dsa, repo, outfile);
4010 break;
4011 default:
4012 err = got_error(GOT_ERR_OBJ_TYPE);
4013 break;
4015 free(obj_id1);
4016 free(obj_id2);
4017 } else {
4018 obj_id2 = got_object_commit_get_tree_id(commit);
4019 if (pcommit)
4020 obj_id1 = got_object_commit_get_tree_id(pcommit);
4021 fprintf(outfile,
4022 "diff %s %s\n", id_str1 ? id_str1 : "/dev/null", id_str2);
4023 fprintf(outfile, "commit - %s\n",
4024 id_str1 ? id_str1 : "/dev/null");
4025 fprintf(outfile, "commit + %s\n", id_str2);
4026 err = diff_trees(obj_id1, obj_id2, "", diff_context, 0, 0,
4027 dsa, repo, outfile);
4029 done:
4030 free(id_str1);
4031 free(id_str2);
4032 if (pcommit)
4033 got_object_commit_close(pcommit);
4034 return err;
4037 static char *
4038 get_datestr(time_t *time, char *datebuf)
4040 struct tm mytm, *tm;
4041 char *p, *s;
4043 tm = gmtime_r(time, &mytm);
4044 if (tm == NULL)
4045 return NULL;
4046 s = asctime_r(tm, datebuf);
4047 if (s == NULL)
4048 return NULL;
4049 p = strchr(s, '\n');
4050 if (p)
4051 *p = '\0';
4052 return s;
4055 static const struct got_error *
4056 match_commit(int *have_match, struct got_object_id *id,
4057 struct got_commit_object *commit, regex_t *regex)
4059 const struct got_error *err = NULL;
4060 regmatch_t regmatch;
4061 char *id_str = NULL, *logmsg = NULL;
4063 *have_match = 0;
4065 err = got_object_id_str(&id_str, id);
4066 if (err)
4067 return err;
4069 err = got_object_commit_get_logmsg(&logmsg, commit);
4070 if (err)
4071 goto done;
4073 if (regexec(regex, got_object_commit_get_author(commit), 1,
4074 &regmatch, 0) == 0 ||
4075 regexec(regex, got_object_commit_get_committer(commit), 1,
4076 &regmatch, 0) == 0 ||
4077 regexec(regex, id_str, 1, &regmatch, 0) == 0 ||
4078 regexec(regex, logmsg, 1, &regmatch, 0) == 0)
4079 *have_match = 1;
4080 done:
4081 free(id_str);
4082 free(logmsg);
4083 return err;
4086 static void
4087 match_changed_paths(int *have_match, struct got_pathlist_head *changed_paths,
4088 regex_t *regex)
4090 regmatch_t regmatch;
4091 struct got_pathlist_entry *pe;
4093 *have_match = 0;
4095 TAILQ_FOREACH(pe, changed_paths, entry) {
4096 if (regexec(regex, pe->path, 1, &regmatch, 0) == 0) {
4097 *have_match = 1;
4098 break;
4103 static const struct got_error *
4104 match_patch(int *have_match, struct got_commit_object *commit,
4105 struct got_object_id *id, const char *path, int diff_context,
4106 struct got_repository *repo, regex_t *regex, FILE *f)
4108 const struct got_error *err = NULL;
4109 char *line = NULL;
4110 size_t linesize = 0;
4111 regmatch_t regmatch;
4113 *have_match = 0;
4115 err = got_opentemp_truncate(f);
4116 if (err)
4117 return err;
4119 err = print_patch(commit, id, path, diff_context, NULL, repo, f);
4120 if (err)
4121 goto done;
4123 if (fseeko(f, 0L, SEEK_SET) == -1) {
4124 err = got_error_from_errno("fseeko");
4125 goto done;
4128 while (getline(&line, &linesize, f) != -1) {
4129 if (regexec(regex, line, 1, &regmatch, 0) == 0) {
4130 *have_match = 1;
4131 break;
4134 done:
4135 free(line);
4136 return err;
4139 #define GOT_COMMIT_SEP_STR "-----------------------------------------------\n"
4141 static const struct got_error*
4142 build_refs_str(char **refs_str, struct got_reflist_head *refs,
4143 struct got_object_id *id, struct got_repository *repo,
4144 int local_only)
4146 static const struct got_error *err = NULL;
4147 struct got_reflist_entry *re;
4148 char *s;
4149 const char *name;
4151 *refs_str = NULL;
4153 TAILQ_FOREACH(re, refs, entry) {
4154 struct got_tag_object *tag = NULL;
4155 struct got_object_id *ref_id;
4156 int cmp;
4158 name = got_ref_get_name(re->ref);
4159 if (strcmp(name, GOT_REF_HEAD) == 0)
4160 continue;
4161 if (strncmp(name, "refs/", 5) == 0)
4162 name += 5;
4163 if (strncmp(name, "got/", 4) == 0)
4164 continue;
4165 if (strncmp(name, "heads/", 6) == 0)
4166 name += 6;
4167 if (strncmp(name, "remotes/", 8) == 0) {
4168 if (local_only)
4169 continue;
4170 name += 8;
4171 s = strstr(name, "/" GOT_REF_HEAD);
4172 if (s != NULL && strcmp(s, "/" GOT_REF_HEAD) == 0)
4173 continue;
4175 err = got_ref_resolve(&ref_id, repo, re->ref);
4176 if (err)
4177 break;
4178 if (strncmp(name, "tags/", 5) == 0) {
4179 err = got_object_open_as_tag(&tag, repo, ref_id);
4180 if (err) {
4181 if (err->code != GOT_ERR_OBJ_TYPE) {
4182 free(ref_id);
4183 break;
4185 /* Ref points at something other than a tag. */
4186 err = NULL;
4187 tag = NULL;
4190 cmp = got_object_id_cmp(tag ?
4191 got_object_tag_get_object_id(tag) : ref_id, id);
4192 free(ref_id);
4193 if (tag)
4194 got_object_tag_close(tag);
4195 if (cmp != 0)
4196 continue;
4197 s = *refs_str;
4198 if (asprintf(refs_str, "%s%s%s", s ? s : "",
4199 s ? ", " : "", name) == -1) {
4200 err = got_error_from_errno("asprintf");
4201 free(s);
4202 *refs_str = NULL;
4203 break;
4205 free(s);
4208 return err;
4211 static const struct got_error *
4212 print_commit_oneline(struct got_commit_object *commit, struct got_object_id *id,
4213 struct got_repository *repo, struct got_reflist_object_id_map *refs_idmap)
4215 const struct got_error *err = NULL;
4216 char *ref_str = NULL, *id_str = NULL, *logmsg0 = NULL;
4217 char *comma, *s, *nl;
4218 struct got_reflist_head *refs;
4219 char datebuf[12]; /* YYYY-MM-DD + SPACE + NUL */
4220 struct tm tm;
4221 time_t committer_time;
4223 refs = got_reflist_object_id_map_lookup(refs_idmap, id);
4224 if (refs) {
4225 err = build_refs_str(&ref_str, refs, id, repo, 1);
4226 if (err)
4227 return err;
4229 /* Display the first matching ref only. */
4230 if (ref_str && (comma = strchr(ref_str, ',')) != NULL)
4231 *comma = '\0';
4234 if (ref_str == NULL) {
4235 err = got_object_id_str(&id_str, id);
4236 if (err)
4237 return err;
4240 committer_time = got_object_commit_get_committer_time(commit);
4241 if (gmtime_r(&committer_time, &tm) == NULL) {
4242 err = got_error_from_errno("gmtime_r");
4243 goto done;
4245 if (strftime(datebuf, sizeof(datebuf), "%G-%m-%d ", &tm) == 0) {
4246 err = got_error(GOT_ERR_NO_SPACE);
4247 goto done;
4250 err = got_object_commit_get_logmsg(&logmsg0, commit);
4251 if (err)
4252 goto done;
4254 s = logmsg0;
4255 while (isspace((unsigned char)s[0]))
4256 s++;
4258 nl = strchr(s, '\n');
4259 if (nl) {
4260 *nl = '\0';
4263 if (ref_str)
4264 printf("%s%-7s %s\n", datebuf, ref_str, s);
4265 else
4266 printf("%s%.7s %s\n", datebuf, id_str, s);
4268 if (fflush(stdout) != 0 && err == NULL)
4269 err = got_error_from_errno("fflush");
4270 done:
4271 free(id_str);
4272 free(ref_str);
4273 free(logmsg0);
4274 return err;
4277 static const struct got_error *
4278 print_diffstat(struct got_diffstat_cb_arg *dsa, const char *header)
4280 struct got_pathlist_entry *pe;
4282 if (header != NULL)
4283 printf("%s\n", header);
4285 TAILQ_FOREACH(pe, dsa->paths, entry) {
4286 struct got_diff_changed_path *cp = pe->data;
4287 int pad = dsa->max_path_len - pe->path_len + 1;
4289 printf(" %c %s%*c | %*d+ %*d-\n", cp->status, pe->path, pad,
4290 ' ', dsa->add_cols + 1, cp->add, dsa->rm_cols + 1, cp->rm);
4292 printf("\n%d file%s changed, %d insertion%s(+), %d deletion%s(-)\n\n",
4293 dsa->nfiles, dsa->nfiles > 1 ? "s" : "", dsa->ins,
4294 dsa->ins != 1 ? "s" : "", dsa->del, dsa->del != 1 ? "s" : "");
4296 if (fflush(stdout) != 0)
4297 return got_error_from_errno("fflush");
4299 return NULL;
4302 static const struct got_error *
4303 printfile(FILE *f)
4305 char buf[8192];
4306 size_t r;
4308 if (fseeko(f, 0L, SEEK_SET) == -1)
4309 return got_error_from_errno("fseek");
4311 for (;;) {
4312 r = fread(buf, 1, sizeof(buf), f);
4313 if (r == 0) {
4314 if (ferror(f))
4315 return got_error_from_errno("fread");
4316 if (feof(f))
4317 break;
4319 if (fwrite(buf, 1, r, stdout) != r)
4320 return got_ferror(stdout, GOT_ERR_IO);
4323 return NULL;
4326 static const struct got_error *
4327 print_commit(struct got_commit_object *commit, struct got_object_id *id,
4328 struct got_repository *repo, const char *path,
4329 struct got_pathlist_head *changed_paths,
4330 struct got_diffstat_cb_arg *diffstat, int show_patch, int diff_context,
4331 struct got_reflist_object_id_map *refs_idmap, const char *custom_refs_str,
4332 const char *prefix)
4334 const struct got_error *err = NULL;
4335 FILE *f = NULL;
4336 char *id_str, *datestr, *logmsg0, *logmsg, *line;
4337 char datebuf[26];
4338 time_t committer_time;
4339 const char *author, *committer;
4340 char *refs_str = NULL;
4342 err = got_object_id_str(&id_str, id);
4343 if (err)
4344 return err;
4346 if (custom_refs_str == NULL) {
4347 struct got_reflist_head *refs;
4348 refs = got_reflist_object_id_map_lookup(refs_idmap, id);
4349 if (refs) {
4350 err = build_refs_str(&refs_str, refs, id, repo, 0);
4351 if (err)
4352 goto done;
4356 printf(GOT_COMMIT_SEP_STR);
4357 if (custom_refs_str)
4358 printf("%s %s (%s)\n", prefix ? prefix : "commit", id_str,
4359 custom_refs_str);
4360 else
4361 printf("%s %s%s%s%s\n", prefix ? prefix : "commit", id_str,
4362 refs_str ? " (" : "", refs_str ? refs_str : "",
4363 refs_str ? ")" : "");
4364 free(id_str);
4365 id_str = NULL;
4366 free(refs_str);
4367 refs_str = NULL;
4368 printf("from: %s\n", got_object_commit_get_author(commit));
4369 author = got_object_commit_get_author(commit);
4370 committer = got_object_commit_get_committer(commit);
4371 if (strcmp(author, committer) != 0)
4372 printf("via: %s\n", committer);
4373 committer_time = got_object_commit_get_committer_time(commit);
4374 datestr = get_datestr(&committer_time, datebuf);
4375 if (datestr)
4376 printf("date: %s UTC\n", datestr);
4377 if (got_object_commit_get_nparents(commit) > 1) {
4378 const struct got_object_id_queue *parent_ids;
4379 struct got_object_qid *qid;
4380 int n = 1;
4381 parent_ids = got_object_commit_get_parent_ids(commit);
4382 STAILQ_FOREACH(qid, parent_ids, entry) {
4383 err = got_object_id_str(&id_str, &qid->id);
4384 if (err)
4385 goto done;
4386 printf("parent %d: %s\n", n++, id_str);
4387 free(id_str);
4388 id_str = NULL;
4392 err = got_object_commit_get_logmsg(&logmsg0, commit);
4393 if (err)
4394 goto done;
4396 logmsg = logmsg0;
4397 do {
4398 line = strsep(&logmsg, "\n");
4399 if (line)
4400 printf(" %s\n", line);
4401 } while (line);
4402 free(logmsg0);
4404 if (changed_paths && diffstat == NULL) {
4405 struct got_pathlist_entry *pe;
4407 TAILQ_FOREACH(pe, changed_paths, entry) {
4408 struct got_diff_changed_path *cp = pe->data;
4410 printf(" %c %s\n", cp->status, pe->path);
4412 printf("\n");
4414 if (show_patch) {
4415 if (diffstat) {
4416 f = got_opentemp();
4417 if (f == NULL) {
4418 err = got_error_from_errno("got_opentemp");
4419 goto done;
4423 err = print_patch(commit, id, path, diff_context, diffstat,
4424 repo, diffstat == NULL ? stdout : f);
4425 if (err)
4426 goto done;
4428 if (diffstat) {
4429 err = print_diffstat(diffstat, NULL);
4430 if (err)
4431 goto done;
4432 if (show_patch) {
4433 err = printfile(f);
4434 if (err)
4435 goto done;
4438 if (show_patch)
4439 printf("\n");
4441 if (fflush(stdout) != 0 && err == NULL)
4442 err = got_error_from_errno("fflush");
4443 done:
4444 if (f && fclose(f) == EOF && err == NULL)
4445 err = got_error_from_errno("fclose");
4446 free(id_str);
4447 free(refs_str);
4448 return err;
4451 static const struct got_error *
4452 print_commits(struct got_object_id *root_id, struct got_object_id *end_id,
4453 struct got_repository *repo, const char *path, int show_changed_paths,
4454 int show_diffstat, int show_patch, const char *search_pattern,
4455 int diff_context, int limit, int log_branches, int reverse_display_order,
4456 struct got_reflist_object_id_map *refs_idmap, int one_line, int toposort,
4457 FILE *tmpfile)
4459 const struct got_error *err;
4460 struct got_commit_graph *graph;
4461 regex_t regex;
4462 int have_match;
4463 struct got_object_id_queue reversed_commits;
4464 struct got_object_qid *qid;
4465 struct got_commit_object *commit;
4466 struct got_pathlist_head changed_paths;
4468 STAILQ_INIT(&reversed_commits);
4469 TAILQ_INIT(&changed_paths);
4471 if (search_pattern && regcomp(&regex, search_pattern,
4472 REG_EXTENDED | REG_NOSUB | REG_NEWLINE))
4473 return got_error_msg(GOT_ERR_REGEX, search_pattern);
4475 err = got_commit_graph_open(&graph, path, !log_branches);
4476 if (err)
4477 return err;
4478 if (log_branches && toposort) {
4479 err = got_commit_graph_toposort(graph, root_id, repo,
4480 check_cancelled, NULL);
4481 } else {
4482 err = got_commit_graph_bfsort(graph, root_id, repo,
4483 check_cancelled, NULL);
4485 if (err)
4486 goto done;
4487 for (;;) {
4488 struct got_object_id id;
4489 struct got_diffstat_cb_arg dsa = { 0, 0, 0, 0, 0, 0,
4490 &changed_paths, 0, 0, GOT_DIFF_ALGORITHM_PATIENCE };
4492 if (sigint_received || sigpipe_received)
4493 break;
4495 err = got_commit_graph_iter_next(&id, graph, repo,
4496 check_cancelled, NULL);
4497 if (err) {
4498 if (err->code == GOT_ERR_ITER_COMPLETED)
4499 err = NULL;
4500 break;
4503 err = got_object_open_as_commit(&commit, repo, &id);
4504 if (err)
4505 break;
4507 if (((show_changed_paths && !show_diffstat) ||
4508 (show_diffstat && !show_patch))
4509 && !reverse_display_order) {
4510 err = get_changed_paths(&changed_paths, commit, repo,
4511 show_diffstat ? &dsa : NULL);
4512 if (err)
4513 break;
4516 if (search_pattern) {
4517 err = match_commit(&have_match, &id, commit, &regex);
4518 if (err) {
4519 got_object_commit_close(commit);
4520 break;
4522 if (have_match == 0 && show_changed_paths)
4523 match_changed_paths(&have_match,
4524 &changed_paths, &regex);
4525 if (have_match == 0 && show_patch) {
4526 err = match_patch(&have_match, commit, &id,
4527 path, diff_context, repo, &regex, tmpfile);
4528 if (err)
4529 break;
4531 if (have_match == 0) {
4532 got_object_commit_close(commit);
4533 got_pathlist_free(&changed_paths,
4534 GOT_PATHLIST_FREE_ALL);
4535 continue;
4539 if (reverse_display_order) {
4540 err = got_object_qid_alloc(&qid, &id);
4541 if (err)
4542 break;
4543 STAILQ_INSERT_HEAD(&reversed_commits, qid, entry);
4544 got_object_commit_close(commit);
4545 } else {
4546 if (one_line)
4547 err = print_commit_oneline(commit, &id,
4548 repo, refs_idmap);
4549 else
4550 err = print_commit(commit, &id, repo, path,
4551 (show_changed_paths || show_diffstat) ?
4552 &changed_paths : NULL,
4553 show_diffstat ? &dsa : NULL, show_patch,
4554 diff_context, refs_idmap, NULL, NULL);
4555 got_object_commit_close(commit);
4556 if (err)
4557 break;
4559 if ((limit && --limit == 0) ||
4560 (end_id && got_object_id_cmp(&id, end_id) == 0))
4561 break;
4563 got_pathlist_free(&changed_paths, GOT_PATHLIST_FREE_ALL);
4565 if (reverse_display_order) {
4566 STAILQ_FOREACH(qid, &reversed_commits, entry) {
4567 struct got_diffstat_cb_arg dsa = { 0, 0, 0, 0, 0, 0,
4568 &changed_paths, 0, 0, GOT_DIFF_ALGORITHM_PATIENCE };
4570 err = got_object_open_as_commit(&commit, repo,
4571 &qid->id);
4572 if (err)
4573 break;
4574 if ((show_changed_paths && !show_diffstat) ||
4575 (show_diffstat && !show_patch)) {
4576 err = get_changed_paths(&changed_paths, commit,
4577 repo, show_diffstat ? &dsa : NULL);
4578 if (err)
4579 break;
4581 if (one_line)
4582 err = print_commit_oneline(commit, &qid->id,
4583 repo, refs_idmap);
4584 else
4585 err = print_commit(commit, &qid->id, repo, path,
4586 (show_changed_paths || show_diffstat) ?
4587 &changed_paths : NULL,
4588 show_diffstat ? &dsa : NULL, show_patch,
4589 diff_context, refs_idmap, NULL, NULL);
4590 got_object_commit_close(commit);
4591 if (err)
4592 break;
4593 got_pathlist_free(&changed_paths, GOT_PATHLIST_FREE_ALL);
4596 done:
4597 while (!STAILQ_EMPTY(&reversed_commits)) {
4598 qid = STAILQ_FIRST(&reversed_commits);
4599 STAILQ_REMOVE_HEAD(&reversed_commits, entry);
4600 got_object_qid_free(qid);
4602 got_pathlist_free(&changed_paths, GOT_PATHLIST_FREE_ALL);
4603 if (search_pattern)
4604 regfree(&regex);
4605 got_commit_graph_close(graph);
4606 return err;
4609 __dead static void
4610 usage_log(void)
4612 fprintf(stderr, "usage: %s log [-bdPpRst] [-C number] [-c commit] "
4613 "[-l N] [-r repository-path] [-S search-pattern] [-x commit] "
4614 "[path]\n", getprogname());
4615 exit(1);
4618 static int
4619 get_default_log_limit(void)
4621 const char *got_default_log_limit;
4622 long long n;
4623 const char *errstr;
4625 got_default_log_limit = getenv("GOT_LOG_DEFAULT_LIMIT");
4626 if (got_default_log_limit == NULL)
4627 return 0;
4628 n = strtonum(got_default_log_limit, 0, INT_MAX, &errstr);
4629 if (errstr != NULL)
4630 return 0;
4631 return n;
4634 static const struct got_error *
4635 cmd_log(int argc, char *argv[])
4637 const struct got_error *error;
4638 struct got_repository *repo = NULL;
4639 struct got_worktree *worktree = NULL;
4640 struct got_object_id *start_id = NULL, *end_id = NULL;
4641 char *repo_path = NULL, *path = NULL, *cwd = NULL, *in_repo_path = NULL;
4642 char *keyword_idstr = NULL;
4643 const char *start_commit = NULL, *end_commit = NULL;
4644 const char *search_pattern = NULL;
4645 int diff_context = -1, ch;
4646 int show_changed_paths = 0, show_patch = 0, limit = 0, log_branches = 0;
4647 int show_diffstat = 0, reverse_display_order = 0, one_line = 0;
4648 int toposort = 0;
4649 const char *errstr;
4650 struct got_reflist_head refs;
4651 struct got_reflist_object_id_map *refs_idmap = NULL;
4652 FILE *tmpfile = NULL;
4653 int *pack_fds = NULL;
4655 TAILQ_INIT(&refs);
4657 #ifndef PROFILE
4658 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
4659 NULL)
4660 == -1)
4661 err(1, "pledge");
4662 #endif
4664 limit = get_default_log_limit();
4666 while ((ch = getopt(argc, argv, "bC:c:dl:PpRr:S:stx:")) != -1) {
4667 switch (ch) {
4668 case 'b':
4669 log_branches = 1;
4670 break;
4671 case 'C':
4672 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
4673 &errstr);
4674 if (errstr != NULL)
4675 errx(1, "number of context lines is %s: %s",
4676 errstr, optarg);
4677 break;
4678 case 'c':
4679 start_commit = optarg;
4680 break;
4681 case 'd':
4682 show_diffstat = 1;
4683 break;
4684 case 'l':
4685 limit = strtonum(optarg, 0, INT_MAX, &errstr);
4686 if (errstr != NULL)
4687 errx(1, "number of commits is %s: %s",
4688 errstr, optarg);
4689 break;
4690 case 'P':
4691 show_changed_paths = 1;
4692 break;
4693 case 'p':
4694 show_patch = 1;
4695 break;
4696 case 'R':
4697 reverse_display_order = 1;
4698 break;
4699 case 'r':
4700 repo_path = realpath(optarg, NULL);
4701 if (repo_path == NULL)
4702 return got_error_from_errno2("realpath",
4703 optarg);
4704 got_path_strip_trailing_slashes(repo_path);
4705 break;
4706 case 'S':
4707 search_pattern = optarg;
4708 break;
4709 case 's':
4710 one_line = 1;
4711 break;
4712 case 't':
4713 toposort = 1;
4714 break;
4715 case 'x':
4716 end_commit = optarg;
4717 break;
4718 default:
4719 usage_log();
4720 /* NOTREACHED */
4724 argc -= optind;
4725 argv += optind;
4727 if (diff_context == -1)
4728 diff_context = 3;
4729 else if (!show_patch)
4730 errx(1, "-C requires -p");
4732 if (one_line && (show_patch || show_changed_paths || show_diffstat))
4733 errx(1, "cannot use -s with -d, -p or -P");
4735 cwd = getcwd(NULL, 0);
4736 if (cwd == NULL) {
4737 error = got_error_from_errno("getcwd");
4738 goto done;
4741 error = got_repo_pack_fds_open(&pack_fds);
4742 if (error != NULL)
4743 goto done;
4745 if (repo_path == NULL) {
4746 error = got_worktree_open(&worktree, cwd,
4747 GOT_WORKTREE_GOT_DIR);
4748 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4749 goto done;
4750 error = NULL;
4753 if (argc == 1) {
4754 if (worktree) {
4755 error = got_worktree_resolve_path(&path, worktree,
4756 argv[0]);
4757 if (error)
4758 goto done;
4759 } else {
4760 path = strdup(argv[0]);
4761 if (path == NULL) {
4762 error = got_error_from_errno("strdup");
4763 goto done;
4766 } else if (argc != 0)
4767 usage_log();
4769 if (repo_path == NULL) {
4770 repo_path = worktree ?
4771 strdup(got_worktree_get_repo_path(worktree)) : strdup(cwd);
4773 if (repo_path == NULL) {
4774 error = got_error_from_errno("strdup");
4775 goto done;
4778 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
4779 if (error != NULL)
4780 goto done;
4782 error = apply_unveil(got_repo_get_path(repo), 1,
4783 worktree ? got_worktree_get_root_path(worktree) : NULL);
4784 if (error)
4785 goto done;
4787 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
4788 if (error)
4789 goto done;
4791 error = got_reflist_object_id_map_create(&refs_idmap, &refs, repo);
4792 if (error)
4793 goto done;
4795 if (start_commit == NULL) {
4796 struct got_reference *head_ref;
4797 struct got_commit_object *commit = NULL;
4798 error = got_ref_open(&head_ref, repo,
4799 worktree ? got_worktree_get_head_ref_name(worktree)
4800 : GOT_REF_HEAD, 0);
4801 if (error != NULL)
4802 goto done;
4803 error = got_ref_resolve(&start_id, repo, head_ref);
4804 got_ref_close(head_ref);
4805 if (error != NULL)
4806 goto done;
4807 error = got_object_open_as_commit(&commit, repo,
4808 start_id);
4809 if (error != NULL)
4810 goto done;
4811 got_object_commit_close(commit);
4812 } else {
4813 error = got_keyword_to_idstr(&keyword_idstr, start_commit,
4814 repo, worktree);
4815 if (error != NULL)
4816 goto done;
4817 if (keyword_idstr != NULL)
4818 start_commit = keyword_idstr;
4820 error = got_repo_match_object_id(&start_id, NULL,
4821 start_commit, GOT_OBJ_TYPE_COMMIT, &refs, repo);
4822 if (error != NULL)
4823 goto done;
4825 if (end_commit != NULL) {
4826 error = got_keyword_to_idstr(&keyword_idstr, end_commit,
4827 repo, worktree);
4828 if (error != NULL)
4829 goto done;
4830 if (keyword_idstr != NULL)
4831 end_commit = keyword_idstr;
4833 error = got_repo_match_object_id(&end_id, NULL,
4834 end_commit, GOT_OBJ_TYPE_COMMIT, &refs, repo);
4835 if (error != NULL)
4836 goto done;
4839 if (worktree) {
4841 * If a path was specified on the command line it was resolved
4842 * to a path in the work tree above. Prepend the work tree's
4843 * path prefix to obtain the corresponding in-repository path.
4845 if (path) {
4846 const char *prefix;
4847 prefix = got_worktree_get_path_prefix(worktree);
4848 if (asprintf(&in_repo_path, "%s%s%s", prefix,
4849 (path[0] != '\0') ? "/" : "", path) == -1) {
4850 error = got_error_from_errno("asprintf");
4851 goto done;
4854 } else
4855 error = got_repo_map_path(&in_repo_path, repo,
4856 path ? path : "");
4857 if (error != NULL)
4858 goto done;
4859 if (in_repo_path) {
4860 free(path);
4861 path = in_repo_path;
4864 if (worktree) {
4865 /* Release work tree lock. */
4866 got_worktree_close(worktree);
4867 worktree = NULL;
4870 if (search_pattern && show_patch) {
4871 tmpfile = got_opentemp();
4872 if (tmpfile == NULL) {
4873 error = got_error_from_errno("got_opentemp");
4874 goto done;
4878 error = print_commits(start_id, end_id, repo, path ? path : "",
4879 show_changed_paths, show_diffstat, show_patch, search_pattern,
4880 diff_context, limit, log_branches, reverse_display_order,
4881 refs_idmap, one_line, toposort, tmpfile);
4882 done:
4883 free(path);
4884 free(repo_path);
4885 free(cwd);
4886 free(start_id);
4887 free(end_id);
4888 free(keyword_idstr);
4889 if (worktree)
4890 got_worktree_close(worktree);
4891 if (repo) {
4892 const struct got_error *close_err = got_repo_close(repo);
4893 if (error == NULL)
4894 error = close_err;
4896 if (pack_fds) {
4897 const struct got_error *pack_err =
4898 got_repo_pack_fds_close(pack_fds);
4899 if (error == NULL)
4900 error = pack_err;
4902 if (refs_idmap)
4903 got_reflist_object_id_map_free(refs_idmap);
4904 if (tmpfile && fclose(tmpfile) == EOF && error == NULL)
4905 error = got_error_from_errno("fclose");
4906 got_ref_list_free(&refs);
4907 return error;
4910 __dead static void
4911 usage_diff(void)
4913 fprintf(stderr, "usage: %s diff [-adPsw] [-C number] [-c commit] "
4914 "[-r repository-path] [object1 object2 | path ...]\n",
4915 getprogname());
4916 exit(1);
4919 struct print_diff_arg {
4920 struct got_repository *repo;
4921 struct got_worktree *worktree;
4922 struct got_diffstat_cb_arg *diffstat;
4923 int diff_context;
4924 const char *id_str;
4925 int header_shown;
4926 int diff_staged;
4927 enum got_diff_algorithm diff_algo;
4928 int ignore_whitespace;
4929 int force_text_diff;
4930 FILE *f1;
4931 FILE *f2;
4932 FILE *outfile;
4936 * Create a file which contains the target path of a symlink so we can feed
4937 * it as content to the diff engine.
4939 static const struct got_error *
4940 get_symlink_target_file(int *fd, int dirfd, const char *de_name,
4941 const char *abspath)
4943 const struct got_error *err = NULL;
4944 char target_path[PATH_MAX];
4945 ssize_t target_len, outlen;
4947 *fd = -1;
4949 if (dirfd != -1) {
4950 target_len = readlinkat(dirfd, de_name, target_path, PATH_MAX);
4951 if (target_len == -1)
4952 return got_error_from_errno2("readlinkat", abspath);
4953 } else {
4954 target_len = readlink(abspath, target_path, PATH_MAX);
4955 if (target_len == -1)
4956 return got_error_from_errno2("readlink", abspath);
4959 *fd = got_opentempfd();
4960 if (*fd == -1)
4961 return got_error_from_errno("got_opentempfd");
4963 outlen = write(*fd, target_path, target_len);
4964 if (outlen == -1) {
4965 err = got_error_from_errno("got_opentempfd");
4966 goto done;
4969 if (lseek(*fd, 0, SEEK_SET) == -1) {
4970 err = got_error_from_errno2("lseek", abspath);
4971 goto done;
4973 done:
4974 if (err) {
4975 close(*fd);
4976 *fd = -1;
4978 return err;
4981 static const struct got_error *
4982 print_diff(void *arg, unsigned char status, unsigned char staged_status,
4983 const char *path, struct got_object_id *blob_id,
4984 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
4985 int dirfd, const char *de_name)
4987 struct print_diff_arg *a = arg;
4988 const struct got_error *err = NULL;
4989 struct got_blob_object *blob1 = NULL;
4990 int fd = -1, fd1 = -1, fd2 = -1;
4991 FILE *f2 = NULL;
4992 char *abspath = NULL, *label1 = NULL;
4993 struct stat sb;
4994 off_t size1 = 0;
4995 int f2_exists = 0;
4997 memset(&sb, 0, sizeof(sb));
4999 if (a->diff_staged) {
5000 if (staged_status != GOT_STATUS_MODIFY &&
5001 staged_status != GOT_STATUS_ADD &&
5002 staged_status != GOT_STATUS_DELETE)
5003 return NULL;
5004 } else {
5005 if (staged_status == GOT_STATUS_DELETE)
5006 return NULL;
5007 if (status == GOT_STATUS_NONEXISTENT)
5008 return got_error_set_errno(ENOENT, path);
5009 if (status != GOT_STATUS_MODIFY &&
5010 status != GOT_STATUS_ADD &&
5011 status != GOT_STATUS_DELETE &&
5012 status != GOT_STATUS_CONFLICT)
5013 return NULL;
5016 err = got_opentemp_truncate(a->f1);
5017 if (err)
5018 return got_error_from_errno("got_opentemp_truncate");
5019 err = got_opentemp_truncate(a->f2);
5020 if (err)
5021 return got_error_from_errno("got_opentemp_truncate");
5023 if (!a->header_shown) {
5024 if (fprintf(a->outfile, "diff %s%s\n",
5025 a->diff_staged ? "-s " : "",
5026 got_worktree_get_root_path(a->worktree)) < 0) {
5027 err = got_error_from_errno("fprintf");
5028 goto done;
5030 if (fprintf(a->outfile, "commit - %s\n", a->id_str) < 0) {
5031 err = got_error_from_errno("fprintf");
5032 goto done;
5034 if (fprintf(a->outfile, "path + %s%s\n",
5035 got_worktree_get_root_path(a->worktree),
5036 a->diff_staged ? " (staged changes)" : "") < 0) {
5037 err = got_error_from_errno("fprintf");
5038 goto done;
5040 a->header_shown = 1;
5043 if (a->diff_staged) {
5044 const char *label1 = NULL, *label2 = NULL;
5045 switch (staged_status) {
5046 case GOT_STATUS_MODIFY:
5047 label1 = path;
5048 label2 = path;
5049 break;
5050 case GOT_STATUS_ADD:
5051 label2 = path;
5052 break;
5053 case GOT_STATUS_DELETE:
5054 label1 = path;
5055 break;
5056 default:
5057 return got_error(GOT_ERR_FILE_STATUS);
5059 fd1 = got_opentempfd();
5060 if (fd1 == -1) {
5061 err = got_error_from_errno("got_opentempfd");
5062 goto done;
5064 fd2 = got_opentempfd();
5065 if (fd2 == -1) {
5066 err = got_error_from_errno("got_opentempfd");
5067 goto done;
5069 err = got_diff_objects_as_blobs(NULL, NULL, a->f1, a->f2,
5070 fd1, fd2, blob_id, staged_blob_id, label1, label2,
5071 a->diff_algo, a->diff_context, a->ignore_whitespace,
5072 a->force_text_diff, a->diffstat, a->repo, a->outfile);
5073 goto done;
5076 fd1 = got_opentempfd();
5077 if (fd1 == -1) {
5078 err = got_error_from_errno("got_opentempfd");
5079 goto done;
5082 if (staged_status == GOT_STATUS_ADD ||
5083 staged_status == GOT_STATUS_MODIFY) {
5084 char *id_str;
5085 err = got_object_open_as_blob(&blob1, a->repo, staged_blob_id,
5086 8192, fd1);
5087 if (err)
5088 goto done;
5089 err = got_object_id_str(&id_str, staged_blob_id);
5090 if (err)
5091 goto done;
5092 if (asprintf(&label1, "%s (staged)", id_str) == -1) {
5093 err = got_error_from_errno("asprintf");
5094 free(id_str);
5095 goto done;
5097 free(id_str);
5098 } else if (status != GOT_STATUS_ADD) {
5099 err = got_object_open_as_blob(&blob1, a->repo, blob_id, 8192,
5100 fd1);
5101 if (err)
5102 goto done;
5105 if (status != GOT_STATUS_DELETE) {
5106 if (asprintf(&abspath, "%s/%s",
5107 got_worktree_get_root_path(a->worktree), path) == -1) {
5108 err = got_error_from_errno("asprintf");
5109 goto done;
5112 if (dirfd != -1) {
5113 fd = openat(dirfd, de_name,
5114 O_RDONLY | O_NOFOLLOW | O_CLOEXEC);
5115 if (fd == -1) {
5116 if (!got_err_open_nofollow_on_symlink()) {
5117 err = got_error_from_errno2("openat",
5118 abspath);
5119 goto done;
5121 err = get_symlink_target_file(&fd, dirfd,
5122 de_name, abspath);
5123 if (err)
5124 goto done;
5126 } else {
5127 fd = open(abspath, O_RDONLY | O_NOFOLLOW | O_CLOEXEC);
5128 if (fd == -1) {
5129 if (!got_err_open_nofollow_on_symlink()) {
5130 err = got_error_from_errno2("open",
5131 abspath);
5132 goto done;
5134 err = get_symlink_target_file(&fd, dirfd,
5135 de_name, abspath);
5136 if (err)
5137 goto done;
5140 if (fstatat(fd, abspath, &sb, AT_SYMLINK_NOFOLLOW) == -1) {
5141 err = got_error_from_errno2("fstatat", abspath);
5142 goto done;
5144 f2 = fdopen(fd, "r");
5145 if (f2 == NULL) {
5146 err = got_error_from_errno2("fdopen", abspath);
5147 goto done;
5149 fd = -1;
5150 f2_exists = 1;
5153 if (blob1) {
5154 err = got_object_blob_dump_to_file(&size1, NULL, NULL,
5155 a->f1, blob1);
5156 if (err)
5157 goto done;
5160 err = got_diff_blob_file(blob1, a->f1, size1, label1, f2 ? f2 : a->f2,
5161 f2_exists, &sb, path, GOT_DIFF_ALGORITHM_PATIENCE, a->diff_context,
5162 a->ignore_whitespace, a->force_text_diff, a->diffstat, a->outfile);
5163 done:
5164 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
5165 err = got_error_from_errno("close");
5166 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
5167 err = got_error_from_errno("close");
5168 if (blob1)
5169 got_object_blob_close(blob1);
5170 if (fd != -1 && close(fd) == -1 && err == NULL)
5171 err = got_error_from_errno("close");
5172 if (f2 && fclose(f2) == EOF && err == NULL)
5173 err = got_error_from_errno("fclose");
5174 free(abspath);
5175 return err;
5178 static const struct got_error *
5179 cmd_diff(int argc, char *argv[])
5181 const struct got_error *error;
5182 struct got_repository *repo = NULL;
5183 struct got_worktree *worktree = NULL;
5184 char *cwd = NULL, *repo_path = NULL;
5185 const char *commit_args[2] = { NULL, NULL };
5186 int ncommit_args = 0;
5187 struct got_object_id *ids[2] = { NULL, NULL };
5188 char *labels[2] = { NULL, NULL };
5189 int type1 = GOT_OBJ_TYPE_ANY, type2 = GOT_OBJ_TYPE_ANY;
5190 int diff_context = 3, diff_staged = 0, ignore_whitespace = 0, ch, i;
5191 int force_text_diff = 0, force_path = 0, rflag = 0, show_diffstat = 0;
5192 const char *errstr;
5193 struct got_reflist_head refs;
5194 struct got_pathlist_head diffstat_paths, paths;
5195 FILE *f1 = NULL, *f2 = NULL, *outfile = NULL;
5196 int fd1 = -1, fd2 = -1;
5197 int *pack_fds = NULL;
5198 struct got_diffstat_cb_arg dsa;
5200 memset(&dsa, 0, sizeof(dsa));
5202 TAILQ_INIT(&refs);
5203 TAILQ_INIT(&paths);
5204 TAILQ_INIT(&diffstat_paths);
5206 #ifndef PROFILE
5207 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
5208 NULL) == -1)
5209 err(1, "pledge");
5210 #endif
5212 while ((ch = getopt(argc, argv, "aC:c:dPr:sw")) != -1) {
5213 switch (ch) {
5214 case 'a':
5215 force_text_diff = 1;
5216 break;
5217 case 'C':
5218 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
5219 &errstr);
5220 if (errstr != NULL)
5221 errx(1, "number of context lines is %s: %s",
5222 errstr, optarg);
5223 break;
5224 case 'c':
5225 if (ncommit_args >= 2)
5226 errx(1, "too many -c options used");
5227 commit_args[ncommit_args++] = optarg;
5228 break;
5229 case 'd':
5230 show_diffstat = 1;
5231 break;
5232 case 'P':
5233 force_path = 1;
5234 break;
5235 case 'r':
5236 repo_path = realpath(optarg, NULL);
5237 if (repo_path == NULL)
5238 return got_error_from_errno2("realpath",
5239 optarg);
5240 got_path_strip_trailing_slashes(repo_path);
5241 rflag = 1;
5242 break;
5243 case 's':
5244 diff_staged = 1;
5245 break;
5246 case 'w':
5247 ignore_whitespace = 1;
5248 break;
5249 default:
5250 usage_diff();
5251 /* NOTREACHED */
5255 argc -= optind;
5256 argv += optind;
5258 cwd = getcwd(NULL, 0);
5259 if (cwd == NULL) {
5260 error = got_error_from_errno("getcwd");
5261 goto done;
5264 error = got_repo_pack_fds_open(&pack_fds);
5265 if (error != NULL)
5266 goto done;
5268 if (repo_path == NULL) {
5269 error = got_worktree_open(&worktree, cwd,
5270 GOT_WORKTREE_GOT_DIR);
5271 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5272 goto done;
5273 else
5274 error = NULL;
5275 if (worktree) {
5276 repo_path =
5277 strdup(got_worktree_get_repo_path(worktree));
5278 if (repo_path == NULL) {
5279 error = got_error_from_errno("strdup");
5280 goto done;
5282 } else {
5283 repo_path = strdup(cwd);
5284 if (repo_path == NULL) {
5285 error = got_error_from_errno("strdup");
5286 goto done;
5291 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
5292 free(repo_path);
5293 if (error != NULL)
5294 goto done;
5296 if (show_diffstat) {
5297 dsa.paths = &diffstat_paths;
5298 dsa.force_text = force_text_diff;
5299 dsa.ignore_ws = ignore_whitespace;
5300 dsa.diff_algo = GOT_DIFF_ALGORITHM_PATIENCE;
5303 if (rflag || worktree == NULL || ncommit_args > 0) {
5304 if (force_path) {
5305 error = got_error_msg(GOT_ERR_NOT_IMPL,
5306 "-P option can only be used when diffing "
5307 "a work tree");
5308 goto done;
5310 if (diff_staged) {
5311 error = got_error_msg(GOT_ERR_NOT_IMPL,
5312 "-s option can only be used when diffing "
5313 "a work tree");
5314 goto done;
5318 error = apply_unveil(got_repo_get_path(repo), 1,
5319 worktree ? got_worktree_get_root_path(worktree) : NULL);
5320 if (error)
5321 goto done;
5323 if ((!force_path && argc == 2) || ncommit_args > 0) {
5324 int obj_type = (ncommit_args > 0 ?
5325 GOT_OBJ_TYPE_COMMIT : GOT_OBJ_TYPE_ANY);
5326 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
5327 NULL);
5328 if (error)
5329 goto done;
5330 for (i = 0; i < (ncommit_args > 0 ? ncommit_args : argc); i++) {
5331 const char *arg;
5332 char *keyword_idstr = NULL;
5334 if (ncommit_args > 0)
5335 arg = commit_args[i];
5336 else
5337 arg = argv[i];
5339 error = got_keyword_to_idstr(&keyword_idstr, arg,
5340 repo, worktree);
5341 if (error != NULL)
5342 goto done;
5343 if (keyword_idstr != NULL)
5344 arg = keyword_idstr;
5346 error = got_repo_match_object_id(&ids[i], &labels[i],
5347 arg, obj_type, &refs, repo);
5348 free(keyword_idstr);
5349 if (error) {
5350 if (error->code != GOT_ERR_NOT_REF &&
5351 error->code != GOT_ERR_NO_OBJ)
5352 goto done;
5353 if (ncommit_args > 0)
5354 goto done;
5355 error = NULL;
5356 break;
5361 f1 = got_opentemp();
5362 if (f1 == NULL) {
5363 error = got_error_from_errno("got_opentemp");
5364 goto done;
5367 f2 = got_opentemp();
5368 if (f2 == NULL) {
5369 error = got_error_from_errno("got_opentemp");
5370 goto done;
5373 outfile = got_opentemp();
5374 if (outfile == NULL) {
5375 error = got_error_from_errno("got_opentemp");
5376 goto done;
5379 if (ncommit_args == 0 && (ids[0] == NULL || ids[1] == NULL)) {
5380 struct print_diff_arg arg;
5381 char *id_str;
5383 if (worktree == NULL) {
5384 if (argc == 2 && ids[0] == NULL) {
5385 error = got_error_path(argv[0], GOT_ERR_NO_OBJ);
5386 goto done;
5387 } else if (argc == 2 && ids[1] == NULL) {
5388 error = got_error_path(argv[1], GOT_ERR_NO_OBJ);
5389 goto done;
5390 } else if (argc > 0) {
5391 error = got_error_fmt(GOT_ERR_NOT_WORKTREE,
5392 "%s", "specified paths cannot be resolved");
5393 goto done;
5394 } else {
5395 error = got_error(GOT_ERR_NOT_WORKTREE);
5396 goto done;
5400 error = get_worktree_paths_from_argv(&paths, argc, argv,
5401 worktree);
5402 if (error)
5403 goto done;
5405 error = got_object_id_str(&id_str,
5406 got_worktree_get_base_commit_id(worktree));
5407 if (error)
5408 goto done;
5409 arg.repo = repo;
5410 arg.worktree = worktree;
5411 arg.diff_algo = GOT_DIFF_ALGORITHM_PATIENCE;
5412 arg.diff_context = diff_context;
5413 arg.id_str = id_str;
5414 arg.header_shown = 0;
5415 arg.diff_staged = diff_staged;
5416 arg.ignore_whitespace = ignore_whitespace;
5417 arg.force_text_diff = force_text_diff;
5418 arg.diffstat = show_diffstat ? &dsa : NULL;
5419 arg.f1 = f1;
5420 arg.f2 = f2;
5421 arg.outfile = outfile;
5423 error = got_worktree_status(worktree, &paths, repo, 0,
5424 print_diff, &arg, check_cancelled, NULL);
5425 free(id_str);
5426 if (error)
5427 goto done;
5429 if (show_diffstat && dsa.nfiles > 0) {
5430 char *header;
5432 if (asprintf(&header, "diffstat %s%s",
5433 diff_staged ? "-s " : "",
5434 got_worktree_get_root_path(worktree)) == -1) {
5435 error = got_error_from_errno("asprintf");
5436 goto done;
5439 error = print_diffstat(&dsa, header);
5440 free(header);
5441 if (error)
5442 goto done;
5445 error = printfile(outfile);
5446 goto done;
5449 if (ncommit_args == 1) {
5450 struct got_commit_object *commit;
5451 error = got_object_open_as_commit(&commit, repo, ids[0]);
5452 if (error)
5453 goto done;
5455 labels[1] = labels[0];
5456 ids[1] = ids[0];
5457 if (got_object_commit_get_nparents(commit) > 0) {
5458 const struct got_object_id_queue *pids;
5459 struct got_object_qid *pid;
5460 pids = got_object_commit_get_parent_ids(commit);
5461 pid = STAILQ_FIRST(pids);
5462 ids[0] = got_object_id_dup(&pid->id);
5463 if (ids[0] == NULL) {
5464 error = got_error_from_errno(
5465 "got_object_id_dup");
5466 got_object_commit_close(commit);
5467 goto done;
5469 error = got_object_id_str(&labels[0], ids[0]);
5470 if (error) {
5471 got_object_commit_close(commit);
5472 goto done;
5474 } else {
5475 ids[0] = NULL;
5476 labels[0] = strdup("/dev/null");
5477 if (labels[0] == NULL) {
5478 error = got_error_from_errno("strdup");
5479 got_object_commit_close(commit);
5480 goto done;
5484 got_object_commit_close(commit);
5487 if (ncommit_args == 0 && argc > 2) {
5488 error = got_error_msg(GOT_ERR_BAD_PATH,
5489 "path arguments cannot be used when diffing two objects");
5490 goto done;
5493 if (ids[0]) {
5494 error = got_object_get_type(&type1, repo, ids[0]);
5495 if (error)
5496 goto done;
5499 error = got_object_get_type(&type2, repo, ids[1]);
5500 if (error)
5501 goto done;
5502 if (type1 != GOT_OBJ_TYPE_ANY && type1 != type2) {
5503 error = got_error(GOT_ERR_OBJ_TYPE);
5504 goto done;
5506 if (type1 == GOT_OBJ_TYPE_BLOB && argc > 2) {
5507 error = got_error_msg(GOT_ERR_OBJ_TYPE,
5508 "path arguments cannot be used when diffing blobs");
5509 goto done;
5512 for (i = 0; ncommit_args > 0 && i < argc; i++) {
5513 char *in_repo_path;
5514 struct got_pathlist_entry *new;
5515 if (worktree) {
5516 const char *prefix;
5517 char *p;
5518 error = got_worktree_resolve_path(&p, worktree,
5519 argv[i]);
5520 if (error)
5521 goto done;
5522 prefix = got_worktree_get_path_prefix(worktree);
5523 while (prefix[0] == '/')
5524 prefix++;
5525 if (asprintf(&in_repo_path, "%s%s%s", prefix,
5526 (p[0] != '\0' && prefix[0] != '\0') ? "/" : "",
5527 p) == -1) {
5528 error = got_error_from_errno("asprintf");
5529 free(p);
5530 goto done;
5532 free(p);
5533 } else {
5534 char *mapped_path, *s;
5535 error = got_repo_map_path(&mapped_path, repo, argv[i]);
5536 if (error)
5537 goto done;
5538 s = mapped_path;
5539 while (s[0] == '/')
5540 s++;
5541 in_repo_path = strdup(s);
5542 if (in_repo_path == NULL) {
5543 error = got_error_from_errno("asprintf");
5544 free(mapped_path);
5545 goto done;
5547 free(mapped_path);
5550 error = got_pathlist_insert(&new, &paths, in_repo_path, NULL);
5551 if (error || new == NULL /* duplicate */)
5552 free(in_repo_path);
5553 if (error)
5554 goto done;
5557 if (worktree) {
5558 /* Release work tree lock. */
5559 got_worktree_close(worktree);
5560 worktree = NULL;
5563 fd1 = got_opentempfd();
5564 if (fd1 == -1) {
5565 error = got_error_from_errno("got_opentempfd");
5566 goto done;
5569 fd2 = got_opentempfd();
5570 if (fd2 == -1) {
5571 error = got_error_from_errno("got_opentempfd");
5572 goto done;
5575 switch (type1 == GOT_OBJ_TYPE_ANY ? type2 : type1) {
5576 case GOT_OBJ_TYPE_BLOB:
5577 error = got_diff_objects_as_blobs(NULL, NULL, f1, f2,
5578 fd1, fd2, ids[0], ids[1], NULL, NULL,
5579 GOT_DIFF_ALGORITHM_PATIENCE, diff_context,
5580 ignore_whitespace, force_text_diff,
5581 show_diffstat ? &dsa : NULL, repo, outfile);
5582 break;
5583 case GOT_OBJ_TYPE_TREE:
5584 error = got_diff_objects_as_trees(NULL, NULL, f1, f2, fd1, fd2,
5585 ids[0], ids[1], &paths, "", "",
5586 GOT_DIFF_ALGORITHM_PATIENCE, diff_context,
5587 ignore_whitespace, force_text_diff,
5588 show_diffstat ? &dsa : NULL, repo, outfile);
5589 break;
5590 case GOT_OBJ_TYPE_COMMIT:
5591 fprintf(outfile, "diff %s %s\n", labels[0], labels[1]);
5592 error = got_diff_objects_as_commits(NULL, NULL, f1, f2,
5593 fd1, fd2, ids[0], ids[1], &paths,
5594 GOT_DIFF_ALGORITHM_PATIENCE, diff_context,
5595 ignore_whitespace, force_text_diff,
5596 show_diffstat ? &dsa : NULL, repo, outfile);
5597 break;
5598 default:
5599 error = got_error(GOT_ERR_OBJ_TYPE);
5601 if (error)
5602 goto done;
5604 if (show_diffstat && dsa.nfiles > 0) {
5605 char *header = NULL;
5607 if (asprintf(&header, "diffstat %s %s",
5608 labels[0], labels[1]) == -1) {
5609 error = got_error_from_errno("asprintf");
5610 goto done;
5613 error = print_diffstat(&dsa, header);
5614 free(header);
5615 if (error)
5616 goto done;
5619 error = printfile(outfile);
5621 done:
5622 free(labels[0]);
5623 free(labels[1]);
5624 free(ids[0]);
5625 free(ids[1]);
5626 if (worktree)
5627 got_worktree_close(worktree);
5628 if (repo) {
5629 const struct got_error *close_err = got_repo_close(repo);
5630 if (error == NULL)
5631 error = close_err;
5633 if (pack_fds) {
5634 const struct got_error *pack_err =
5635 got_repo_pack_fds_close(pack_fds);
5636 if (error == NULL)
5637 error = pack_err;
5639 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
5640 got_pathlist_free(&diffstat_paths, GOT_PATHLIST_FREE_ALL);
5641 got_ref_list_free(&refs);
5642 if (outfile && fclose(outfile) == EOF && error == NULL)
5643 error = got_error_from_errno("fclose");
5644 if (f1 && fclose(f1) == EOF && error == NULL)
5645 error = got_error_from_errno("fclose");
5646 if (f2 && fclose(f2) == EOF && error == NULL)
5647 error = got_error_from_errno("fclose");
5648 if (fd1 != -1 && close(fd1) == -1 && error == NULL)
5649 error = got_error_from_errno("close");
5650 if (fd2 != -1 && close(fd2) == -1 && error == NULL)
5651 error = got_error_from_errno("close");
5652 return error;
5655 __dead static void
5656 usage_blame(void)
5658 fprintf(stderr,
5659 "usage: %s blame [-c commit] [-r repository-path] path\n",
5660 getprogname());
5661 exit(1);
5664 struct blame_line {
5665 int annotated;
5666 char *id_str;
5667 char *committer;
5668 char datebuf[11]; /* YYYY-MM-DD + NUL */
5671 struct blame_cb_args {
5672 struct blame_line *lines;
5673 int nlines;
5674 int nlines_prec;
5675 int lineno_cur;
5676 off_t *line_offsets;
5677 FILE *f;
5678 struct got_repository *repo;
5681 static const struct got_error *
5682 blame_cb(void *arg, int nlines, int lineno,
5683 struct got_commit_object *commit, struct got_object_id *id)
5685 const struct got_error *err = NULL;
5686 struct blame_cb_args *a = arg;
5687 struct blame_line *bline;
5688 char *line = NULL;
5689 size_t linesize = 0;
5690 off_t offset;
5691 struct tm tm;
5692 time_t committer_time;
5694 if (nlines != a->nlines ||
5695 (lineno != -1 && lineno < 1) || lineno > a->nlines)
5696 return got_error(GOT_ERR_RANGE);
5698 if (sigint_received)
5699 return got_error(GOT_ERR_ITER_COMPLETED);
5701 if (lineno == -1)
5702 return NULL; /* no change in this commit */
5704 /* Annotate this line. */
5705 bline = &a->lines[lineno - 1];
5706 if (bline->annotated)
5707 return NULL;
5708 err = got_object_id_str(&bline->id_str, id);
5709 if (err)
5710 return err;
5712 bline->committer = strdup(got_object_commit_get_committer(commit));
5713 if (bline->committer == NULL) {
5714 err = got_error_from_errno("strdup");
5715 goto done;
5718 committer_time = got_object_commit_get_committer_time(commit);
5719 if (gmtime_r(&committer_time, &tm) == NULL)
5720 return got_error_from_errno("gmtime_r");
5721 if (strftime(bline->datebuf, sizeof(bline->datebuf), "%G-%m-%d",
5722 &tm) == 0) {
5723 err = got_error(GOT_ERR_NO_SPACE);
5724 goto done;
5726 bline->annotated = 1;
5728 /* Print lines annotated so far. */
5729 bline = &a->lines[a->lineno_cur - 1];
5730 if (!bline->annotated)
5731 goto done;
5733 offset = a->line_offsets[a->lineno_cur - 1];
5734 if (fseeko(a->f, offset, SEEK_SET) == -1) {
5735 err = got_error_from_errno("fseeko");
5736 goto done;
5739 while (a->lineno_cur <= a->nlines && bline->annotated) {
5740 char *smallerthan, *at, *nl, *committer;
5741 size_t len;
5743 if (getline(&line, &linesize, a->f) == -1) {
5744 if (ferror(a->f))
5745 err = got_error_from_errno("getline");
5746 break;
5749 committer = bline->committer;
5750 smallerthan = strchr(committer, '<');
5751 if (smallerthan && smallerthan[1] != '\0')
5752 committer = smallerthan + 1;
5753 at = strchr(committer, '@');
5754 if (at)
5755 *at = '\0';
5756 len = strlen(committer);
5757 if (len >= 9)
5758 committer[8] = '\0';
5760 nl = strchr(line, '\n');
5761 if (nl)
5762 *nl = '\0';
5763 printf("%.*d) %.8s %s %-8s %s\n", a->nlines_prec, a->lineno_cur,
5764 bline->id_str, bline->datebuf, committer, line);
5766 a->lineno_cur++;
5767 bline = &a->lines[a->lineno_cur - 1];
5769 done:
5770 free(line);
5771 return err;
5774 static const struct got_error *
5775 cmd_blame(int argc, char *argv[])
5777 const struct got_error *error;
5778 struct got_repository *repo = NULL;
5779 struct got_worktree *worktree = NULL;
5780 char *path, *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
5781 char *link_target = NULL;
5782 struct got_object_id *obj_id = NULL;
5783 struct got_object_id *commit_id = NULL;
5784 struct got_commit_object *commit = NULL;
5785 struct got_blob_object *blob = NULL;
5786 char *commit_id_str = NULL, *keyword_idstr = NULL;
5787 struct blame_cb_args bca;
5788 int ch, obj_type, i, fd1 = -1, fd2 = -1, fd3 = -1;
5789 off_t filesize;
5790 int *pack_fds = NULL;
5791 FILE *f1 = NULL, *f2 = NULL;
5793 fd1 = got_opentempfd();
5794 if (fd1 == -1)
5795 return got_error_from_errno("got_opentempfd");
5797 memset(&bca, 0, sizeof(bca));
5799 #ifndef PROFILE
5800 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
5801 NULL) == -1)
5802 err(1, "pledge");
5803 #endif
5805 while ((ch = getopt(argc, argv, "c:r:")) != -1) {
5806 switch (ch) {
5807 case 'c':
5808 commit_id_str = optarg;
5809 break;
5810 case 'r':
5811 repo_path = realpath(optarg, NULL);
5812 if (repo_path == NULL)
5813 return got_error_from_errno2("realpath",
5814 optarg);
5815 got_path_strip_trailing_slashes(repo_path);
5816 break;
5817 default:
5818 usage_blame();
5819 /* NOTREACHED */
5823 argc -= optind;
5824 argv += optind;
5826 if (argc == 1)
5827 path = argv[0];
5828 else
5829 usage_blame();
5831 cwd = getcwd(NULL, 0);
5832 if (cwd == NULL) {
5833 error = got_error_from_errno("getcwd");
5834 goto done;
5837 error = got_repo_pack_fds_open(&pack_fds);
5838 if (error != NULL)
5839 goto done;
5841 if (repo_path == NULL) {
5842 error = got_worktree_open(&worktree, cwd,
5843 GOT_WORKTREE_GOT_DIR);
5844 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5845 goto done;
5846 else
5847 error = NULL;
5848 if (worktree) {
5849 repo_path =
5850 strdup(got_worktree_get_repo_path(worktree));
5851 if (repo_path == NULL) {
5852 error = got_error_from_errno("strdup");
5853 if (error)
5854 goto done;
5856 } else {
5857 repo_path = strdup(cwd);
5858 if (repo_path == NULL) {
5859 error = got_error_from_errno("strdup");
5860 goto done;
5865 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
5866 if (error != NULL)
5867 goto done;
5869 if (worktree) {
5870 const char *prefix = got_worktree_get_path_prefix(worktree);
5871 char *p;
5873 error = got_worktree_resolve_path(&p, worktree, path);
5874 if (error)
5875 goto done;
5876 if (asprintf(&in_repo_path, "%s%s%s", prefix,
5877 (p[0] != '\0' && !got_path_is_root_dir(prefix)) ? "/" : "",
5878 p) == -1) {
5879 error = got_error_from_errno("asprintf");
5880 free(p);
5881 goto done;
5883 free(p);
5884 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5885 } else {
5886 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5887 if (error)
5888 goto done;
5889 error = got_repo_map_path(&in_repo_path, repo, path);
5891 if (error)
5892 goto done;
5894 if (commit_id_str == NULL) {
5895 struct got_reference *head_ref;
5896 error = got_ref_open(&head_ref, repo, worktree ?
5897 got_worktree_get_head_ref_name(worktree) : GOT_REF_HEAD, 0);
5898 if (error != NULL)
5899 goto done;
5900 error = got_ref_resolve(&commit_id, repo, head_ref);
5901 got_ref_close(head_ref);
5902 if (error != NULL)
5903 goto done;
5904 } else {
5905 struct got_reflist_head refs;
5907 TAILQ_INIT(&refs);
5908 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
5909 NULL);
5910 if (error)
5911 goto done;
5913 error = got_keyword_to_idstr(&keyword_idstr, commit_id_str,
5914 repo, worktree);
5915 if (error != NULL)
5916 goto done;
5917 if (keyword_idstr != NULL)
5918 commit_id_str = keyword_idstr;
5920 error = got_repo_match_object_id(&commit_id, NULL,
5921 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
5922 got_ref_list_free(&refs);
5923 if (error)
5924 goto done;
5927 if (worktree) {
5928 /* Release work tree lock. */
5929 got_worktree_close(worktree);
5930 worktree = NULL;
5933 error = got_object_open_as_commit(&commit, repo, commit_id);
5934 if (error)
5935 goto done;
5937 error = got_object_resolve_symlinks(&link_target, in_repo_path,
5938 commit, repo);
5939 if (error)
5940 goto done;
5942 error = got_object_id_by_path(&obj_id, repo, commit,
5943 link_target ? link_target : in_repo_path);
5944 if (error)
5945 goto done;
5947 error = got_object_get_type(&obj_type, repo, obj_id);
5948 if (error)
5949 goto done;
5951 if (obj_type != GOT_OBJ_TYPE_BLOB) {
5952 error = got_error_path(link_target ? link_target : in_repo_path,
5953 GOT_ERR_OBJ_TYPE);
5954 goto done;
5957 error = got_object_open_as_blob(&blob, repo, obj_id, 8192, fd1);
5958 if (error)
5959 goto done;
5960 bca.f = got_opentemp();
5961 if (bca.f == NULL) {
5962 error = got_error_from_errno("got_opentemp");
5963 goto done;
5965 error = got_object_blob_dump_to_file(&filesize, &bca.nlines,
5966 &bca.line_offsets, bca.f, blob);
5967 if (error || bca.nlines == 0)
5968 goto done;
5970 /* Don't include \n at EOF in the blame line count. */
5971 if (bca.line_offsets[bca.nlines - 1] == filesize)
5972 bca.nlines--;
5974 bca.lines = calloc(bca.nlines, sizeof(*bca.lines));
5975 if (bca.lines == NULL) {
5976 error = got_error_from_errno("calloc");
5977 goto done;
5979 bca.lineno_cur = 1;
5980 bca.nlines_prec = 0;
5981 i = bca.nlines;
5982 while (i > 0) {
5983 i /= 10;
5984 bca.nlines_prec++;
5986 bca.repo = repo;
5988 fd2 = got_opentempfd();
5989 if (fd2 == -1) {
5990 error = got_error_from_errno("got_opentempfd");
5991 goto done;
5993 fd3 = got_opentempfd();
5994 if (fd3 == -1) {
5995 error = got_error_from_errno("got_opentempfd");
5996 goto done;
5998 f1 = got_opentemp();
5999 if (f1 == NULL) {
6000 error = got_error_from_errno("got_opentemp");
6001 goto done;
6003 f2 = got_opentemp();
6004 if (f2 == NULL) {
6005 error = got_error_from_errno("got_opentemp");
6006 goto done;
6008 error = got_blame(link_target ? link_target : in_repo_path, commit_id,
6009 repo, GOT_DIFF_ALGORITHM_PATIENCE, blame_cb, &bca,
6010 check_cancelled, NULL, fd2, fd3, f1, f2);
6011 done:
6012 free(keyword_idstr);
6013 free(in_repo_path);
6014 free(link_target);
6015 free(repo_path);
6016 free(cwd);
6017 free(commit_id);
6018 free(obj_id);
6019 if (commit)
6020 got_object_commit_close(commit);
6022 if (fd1 != -1 && close(fd1) == -1 && error == NULL)
6023 error = got_error_from_errno("close");
6024 if (fd2 != -1 && close(fd2) == -1 && error == NULL)
6025 error = got_error_from_errno("close");
6026 if (fd3 != -1 && close(fd3) == -1 && error == NULL)
6027 error = got_error_from_errno("close");
6028 if (f1 && fclose(f1) == EOF && error == NULL)
6029 error = got_error_from_errno("fclose");
6030 if (f2 && fclose(f2) == EOF && error == NULL)
6031 error = got_error_from_errno("fclose");
6033 if (blob)
6034 got_object_blob_close(blob);
6035 if (worktree)
6036 got_worktree_close(worktree);
6037 if (repo) {
6038 const struct got_error *close_err = got_repo_close(repo);
6039 if (error == NULL)
6040 error = close_err;
6042 if (pack_fds) {
6043 const struct got_error *pack_err =
6044 got_repo_pack_fds_close(pack_fds);
6045 if (error == NULL)
6046 error = pack_err;
6048 if (bca.lines) {
6049 for (i = 0; i < bca.nlines; i++) {
6050 struct blame_line *bline = &bca.lines[i];
6051 free(bline->id_str);
6052 free(bline->committer);
6054 free(bca.lines);
6056 free(bca.line_offsets);
6057 if (bca.f && fclose(bca.f) == EOF && error == NULL)
6058 error = got_error_from_errno("fclose");
6059 return error;
6062 __dead static void
6063 usage_tree(void)
6065 fprintf(stderr, "usage: %s tree [-iR] [-c commit] [-r repository-path] "
6066 "[path]\n", getprogname());
6067 exit(1);
6070 static const struct got_error *
6071 print_entry(struct got_tree_entry *te, const char *id, const char *path,
6072 const char *root_path, struct got_repository *repo)
6074 const struct got_error *err = NULL;
6075 int is_root_path = (strcmp(path, root_path) == 0);
6076 const char *modestr = "";
6077 mode_t mode = got_tree_entry_get_mode(te);
6078 char *link_target = NULL;
6080 path += strlen(root_path);
6081 while (path[0] == '/')
6082 path++;
6084 if (got_object_tree_entry_is_submodule(te))
6085 modestr = "$";
6086 else if (S_ISLNK(mode)) {
6087 int i;
6089 err = got_tree_entry_get_symlink_target(&link_target, te, repo);
6090 if (err)
6091 return err;
6092 for (i = 0; link_target[i] != '\0'; i++) {
6093 if (!isprint((unsigned char)link_target[i]))
6094 link_target[i] = '?';
6097 modestr = "@";
6099 else if (S_ISDIR(mode))
6100 modestr = "/";
6101 else if (mode & S_IXUSR)
6102 modestr = "*";
6104 printf("%s%s%s%s%s%s%s\n", id ? id : "", path,
6105 is_root_path ? "" : "/", got_tree_entry_get_name(te), modestr,
6106 link_target ? " -> ": "", link_target ? link_target : "");
6108 free(link_target);
6109 return NULL;
6112 static const struct got_error *
6113 print_tree(const char *path, struct got_commit_object *commit,
6114 int show_ids, int recurse, const char *root_path,
6115 struct got_repository *repo)
6117 const struct got_error *err = NULL;
6118 struct got_object_id *tree_id = NULL;
6119 struct got_tree_object *tree = NULL;
6120 int nentries, i;
6122 err = got_object_id_by_path(&tree_id, repo, commit, path);
6123 if (err)
6124 goto done;
6126 err = got_object_open_as_tree(&tree, repo, tree_id);
6127 if (err)
6128 goto done;
6129 nentries = got_object_tree_get_nentries(tree);
6130 for (i = 0; i < nentries; i++) {
6131 struct got_tree_entry *te;
6132 char *id = NULL;
6134 if (sigint_received || sigpipe_received)
6135 break;
6137 te = got_object_tree_get_entry(tree, i);
6138 if (show_ids) {
6139 char *id_str;
6140 err = got_object_id_str(&id_str,
6141 got_tree_entry_get_id(te));
6142 if (err)
6143 goto done;
6144 if (asprintf(&id, "%s ", id_str) == -1) {
6145 err = got_error_from_errno("asprintf");
6146 free(id_str);
6147 goto done;
6149 free(id_str);
6151 err = print_entry(te, id, path, root_path, repo);
6152 free(id);
6153 if (err)
6154 goto done;
6156 if (recurse && S_ISDIR(got_tree_entry_get_mode(te))) {
6157 char *child_path;
6158 if (asprintf(&child_path, "%s%s%s", path,
6159 path[0] == '/' && path[1] == '\0' ? "" : "/",
6160 got_tree_entry_get_name(te)) == -1) {
6161 err = got_error_from_errno("asprintf");
6162 goto done;
6164 err = print_tree(child_path, commit, show_ids, 1,
6165 root_path, repo);
6166 free(child_path);
6167 if (err)
6168 goto done;
6171 done:
6172 if (tree)
6173 got_object_tree_close(tree);
6174 free(tree_id);
6175 return err;
6178 static const struct got_error *
6179 cmd_tree(int argc, char *argv[])
6181 const struct got_error *error;
6182 struct got_repository *repo = NULL;
6183 struct got_worktree *worktree = NULL;
6184 const char *path, *refname = NULL;
6185 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
6186 struct got_object_id *commit_id = NULL;
6187 struct got_commit_object *commit = NULL;
6188 char *commit_id_str = NULL, *keyword_idstr = NULL;
6189 int show_ids = 0, recurse = 0;
6190 int ch;
6191 int *pack_fds = NULL;
6193 #ifndef PROFILE
6194 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
6195 NULL) == -1)
6196 err(1, "pledge");
6197 #endif
6199 while ((ch = getopt(argc, argv, "c:iRr:")) != -1) {
6200 switch (ch) {
6201 case 'c':
6202 commit_id_str = optarg;
6203 break;
6204 case 'i':
6205 show_ids = 1;
6206 break;
6207 case 'R':
6208 recurse = 1;
6209 break;
6210 case 'r':
6211 repo_path = realpath(optarg, NULL);
6212 if (repo_path == NULL)
6213 return got_error_from_errno2("realpath",
6214 optarg);
6215 got_path_strip_trailing_slashes(repo_path);
6216 break;
6217 default:
6218 usage_tree();
6219 /* NOTREACHED */
6223 argc -= optind;
6224 argv += optind;
6226 if (argc == 1)
6227 path = argv[0];
6228 else if (argc > 1)
6229 usage_tree();
6230 else
6231 path = NULL;
6233 cwd = getcwd(NULL, 0);
6234 if (cwd == NULL) {
6235 error = got_error_from_errno("getcwd");
6236 goto done;
6239 error = got_repo_pack_fds_open(&pack_fds);
6240 if (error != NULL)
6241 goto done;
6243 if (repo_path == NULL) {
6244 error = got_worktree_open(&worktree, cwd,
6245 GOT_WORKTREE_GOT_DIR);
6246 if (error && error->code != GOT_ERR_NOT_WORKTREE)
6247 goto done;
6248 else
6249 error = NULL;
6250 if (worktree) {
6251 repo_path =
6252 strdup(got_worktree_get_repo_path(worktree));
6253 if (repo_path == NULL)
6254 error = got_error_from_errno("strdup");
6255 if (error)
6256 goto done;
6257 } else {
6258 repo_path = strdup(cwd);
6259 if (repo_path == NULL) {
6260 error = got_error_from_errno("strdup");
6261 goto done;
6266 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
6267 if (error != NULL)
6268 goto done;
6270 if (worktree) {
6271 const char *prefix = got_worktree_get_path_prefix(worktree);
6272 char *p;
6274 if (path == NULL || got_path_is_root_dir(path))
6275 path = "";
6276 error = got_worktree_resolve_path(&p, worktree, path);
6277 if (error)
6278 goto done;
6279 if (asprintf(&in_repo_path, "%s%s%s", prefix,
6280 (p[0] != '\0' && !got_path_is_root_dir(prefix)) ? "/" : "",
6281 p) == -1) {
6282 error = got_error_from_errno("asprintf");
6283 free(p);
6284 goto done;
6286 free(p);
6287 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
6288 if (error)
6289 goto done;
6290 } else {
6291 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
6292 if (error)
6293 goto done;
6294 if (path == NULL)
6295 path = "/";
6296 error = got_repo_map_path(&in_repo_path, repo, path);
6297 if (error != NULL)
6298 goto done;
6301 if (commit_id_str == NULL) {
6302 struct got_reference *head_ref;
6303 if (worktree)
6304 refname = got_worktree_get_head_ref_name(worktree);
6305 else
6306 refname = GOT_REF_HEAD;
6307 error = got_ref_open(&head_ref, repo, refname, 0);
6308 if (error != NULL)
6309 goto done;
6310 error = got_ref_resolve(&commit_id, repo, head_ref);
6311 got_ref_close(head_ref);
6312 if (error != NULL)
6313 goto done;
6314 } else {
6315 struct got_reflist_head refs;
6317 TAILQ_INIT(&refs);
6318 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
6319 NULL);
6320 if (error)
6321 goto done;
6323 error = got_keyword_to_idstr(&keyword_idstr, commit_id_str,
6324 repo, worktree);
6325 if (error != NULL)
6326 goto done;
6327 if (keyword_idstr != NULL)
6328 commit_id_str = keyword_idstr;
6330 error = got_repo_match_object_id(&commit_id, NULL,
6331 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
6332 got_ref_list_free(&refs);
6333 if (error)
6334 goto done;
6337 if (worktree) {
6338 /* Release work tree lock. */
6339 got_worktree_close(worktree);
6340 worktree = NULL;
6343 error = got_object_open_as_commit(&commit, repo, commit_id);
6344 if (error)
6345 goto done;
6347 error = print_tree(in_repo_path, commit, show_ids, recurse,
6348 in_repo_path, repo);
6349 done:
6350 free(keyword_idstr);
6351 free(in_repo_path);
6352 free(repo_path);
6353 free(cwd);
6354 free(commit_id);
6355 if (commit)
6356 got_object_commit_close(commit);
6357 if (worktree)
6358 got_worktree_close(worktree);
6359 if (repo) {
6360 const struct got_error *close_err = got_repo_close(repo);
6361 if (error == NULL)
6362 error = close_err;
6364 if (pack_fds) {
6365 const struct got_error *pack_err =
6366 got_repo_pack_fds_close(pack_fds);
6367 if (error == NULL)
6368 error = pack_err;
6370 return error;
6373 __dead static void
6374 usage_status(void)
6376 fprintf(stderr, "usage: %s status [-I] [-S status-codes] "
6377 "[-s status-codes] [path ...]\n", getprogname());
6378 exit(1);
6381 struct got_status_arg {
6382 char *status_codes;
6383 int suppress;
6386 static const struct got_error *
6387 print_status(void *arg, unsigned char status, unsigned char staged_status,
6388 const char *path, struct got_object_id *blob_id,
6389 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
6390 int dirfd, const char *de_name)
6392 struct got_status_arg *st = arg;
6394 if (status == staged_status && (status == GOT_STATUS_DELETE))
6395 status = GOT_STATUS_NO_CHANGE;
6396 if (st != NULL && st->status_codes) {
6397 size_t ncodes = strlen(st->status_codes);
6398 int i, j = 0;
6400 for (i = 0; i < ncodes ; i++) {
6401 if (st->suppress) {
6402 if (status == st->status_codes[i] ||
6403 staged_status == st->status_codes[i]) {
6404 j++;
6405 continue;
6407 } else {
6408 if (status == st->status_codes[i] ||
6409 staged_status == st->status_codes[i])
6410 break;
6414 if (st->suppress && j == 0)
6415 goto print;
6417 if (i == ncodes)
6418 return NULL;
6420 print:
6421 printf("%c%c %s\n", status, staged_status, path);
6422 return NULL;
6425 static const struct got_error *
6426 show_operation_in_progress(struct got_worktree *worktree,
6427 struct got_repository *repo)
6429 const struct got_error *err;
6430 char *new_base_branch_name = NULL;
6431 char *branch_name = NULL;
6432 int rebase_in_progress, histedit_in_progress, merge_in_progress;
6434 err = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
6435 if (err)
6436 return err;
6437 if (rebase_in_progress) {
6438 err = got_worktree_rebase_info(&new_base_branch_name,
6439 &branch_name, worktree, repo);
6440 if (err)
6441 return err;
6442 printf("Work tree is rebasing %s onto %s\n",
6443 branch_name, new_base_branch_name);
6446 err = got_worktree_histedit_in_progress(&histedit_in_progress,
6447 worktree);
6448 if (err)
6449 return err;
6450 if (histedit_in_progress) {
6451 err = got_worktree_histedit_info(&branch_name, worktree, repo);
6452 if (err)
6453 return err;
6454 printf("Work tree is editing the history of %s\n", branch_name);
6457 err = got_worktree_merge_in_progress(&merge_in_progress,
6458 worktree, repo);
6459 if (err)
6460 return err;
6461 if (merge_in_progress) {
6462 err = got_worktree_merge_info(&branch_name, worktree,
6463 repo);
6464 if (err)
6465 return err;
6466 printf("Work tree is merging %s into %s\n", branch_name,
6467 got_worktree_get_head_ref_name(worktree));
6470 free(new_base_branch_name);
6471 free(branch_name);
6472 return NULL;
6475 static const struct got_error *
6476 cmd_status(int argc, char *argv[])
6478 const struct got_error *close_err, *error = NULL;
6479 struct got_repository *repo = NULL;
6480 struct got_worktree *worktree = NULL;
6481 struct got_status_arg st;
6482 char *cwd = NULL;
6483 struct got_pathlist_head paths;
6484 int ch, i, no_ignores = 0;
6485 int *pack_fds = NULL;
6487 TAILQ_INIT(&paths);
6489 memset(&st, 0, sizeof(st));
6490 st.status_codes = NULL;
6491 st.suppress = 0;
6493 #ifndef PROFILE
6494 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
6495 NULL) == -1)
6496 err(1, "pledge");
6497 #endif
6499 while ((ch = getopt(argc, argv, "IS:s:")) != -1) {
6500 switch (ch) {
6501 case 'I':
6502 no_ignores = 1;
6503 break;
6504 case 'S':
6505 if (st.status_codes != NULL && st.suppress == 0)
6506 option_conflict('S', 's');
6507 st.suppress = 1;
6508 /* fallthrough */
6509 case 's':
6510 for (i = 0; optarg[i] != '\0'; i++) {
6511 switch (optarg[i]) {
6512 case GOT_STATUS_MODIFY:
6513 case GOT_STATUS_ADD:
6514 case GOT_STATUS_DELETE:
6515 case GOT_STATUS_CONFLICT:
6516 case GOT_STATUS_MISSING:
6517 case GOT_STATUS_OBSTRUCTED:
6518 case GOT_STATUS_UNVERSIONED:
6519 case GOT_STATUS_MODE_CHANGE:
6520 case GOT_STATUS_NONEXISTENT:
6521 break;
6522 default:
6523 errx(1, "invalid status code '%c'",
6524 optarg[i]);
6527 if (ch == 's' && st.suppress)
6528 option_conflict('s', 'S');
6529 st.status_codes = optarg;
6530 break;
6531 default:
6532 usage_status();
6533 /* NOTREACHED */
6537 argc -= optind;
6538 argv += optind;
6540 cwd = getcwd(NULL, 0);
6541 if (cwd == NULL) {
6542 error = got_error_from_errno("getcwd");
6543 goto done;
6546 error = got_repo_pack_fds_open(&pack_fds);
6547 if (error != NULL)
6548 goto done;
6550 error = got_worktree_open(&worktree, cwd,
6551 GOT_WORKTREE_GOT_DIR);
6552 if (error) {
6553 if (error->code == GOT_ERR_NOT_WORKTREE)
6554 error = wrap_not_worktree_error(error, "status", cwd);
6555 goto done;
6558 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
6559 NULL, pack_fds);
6560 if (error != NULL)
6561 goto done;
6563 error = apply_unveil(got_repo_get_path(repo), 1,
6564 got_worktree_get_root_path(worktree));
6565 if (error)
6566 goto done;
6568 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
6569 if (error)
6570 goto done;
6572 error = got_worktree_status(worktree, &paths, repo, no_ignores,
6573 print_status, &st, check_cancelled, NULL);
6574 if (error)
6575 goto done;
6577 error = show_operation_in_progress(worktree, repo);
6578 done:
6579 if (pack_fds) {
6580 const struct got_error *pack_err =
6581 got_repo_pack_fds_close(pack_fds);
6582 if (error == NULL)
6583 error = pack_err;
6585 if (repo) {
6586 close_err = got_repo_close(repo);
6587 if (error == NULL)
6588 error = close_err;
6590 if (worktree != NULL) {
6591 close_err = got_worktree_close(worktree);
6592 if (error == NULL)
6593 error = close_err;
6596 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
6597 free(cwd);
6598 return error;
6601 __dead static void
6602 usage_ref(void)
6604 fprintf(stderr, "usage: %s ref [-dlt] [-c object] [-r repository-path] "
6605 "[-s reference] [name]\n", getprogname());
6606 exit(1);
6609 static const struct got_error *
6610 list_refs(struct got_repository *repo, const char *refname, int sort_by_time)
6612 static const struct got_error *err = NULL;
6613 struct got_reflist_head refs;
6614 struct got_reflist_entry *re;
6616 TAILQ_INIT(&refs);
6617 err = got_ref_list(&refs, repo, refname, sort_by_time ?
6618 got_ref_cmp_by_commit_timestamp_descending : got_ref_cmp_by_name,
6619 repo);
6620 if (err)
6621 return err;
6623 TAILQ_FOREACH(re, &refs, entry) {
6624 char *refstr;
6625 refstr = got_ref_to_str(re->ref);
6626 if (refstr == NULL) {
6627 err = got_error_from_errno("got_ref_to_str");
6628 break;
6630 printf("%s: %s\n", got_ref_get_name(re->ref), refstr);
6631 free(refstr);
6634 got_ref_list_free(&refs);
6635 return err;
6638 static const struct got_error *
6639 delete_ref_by_name(struct got_repository *repo, const char *refname)
6641 const struct got_error *err;
6642 struct got_reference *ref;
6644 err = got_ref_open(&ref, repo, refname, 0);
6645 if (err)
6646 return err;
6648 err = delete_ref(repo, ref);
6649 got_ref_close(ref);
6650 return err;
6653 static const struct got_error *
6654 add_ref(struct got_repository *repo, const char *refname, const char *target)
6656 const struct got_error *err = NULL;
6657 struct got_object_id *id = NULL;
6658 struct got_reference *ref = NULL;
6659 struct got_reflist_head refs;
6662 * Don't let the user create a reference name with a leading '-'.
6663 * While technically a valid reference name, this case is usually
6664 * an unintended typo.
6666 if (refname[0] == '-')
6667 return got_error_path(refname, GOT_ERR_REF_NAME_MINUS);
6669 TAILQ_INIT(&refs);
6670 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
6671 if (err)
6672 goto done;
6673 err = got_repo_match_object_id(&id, NULL, target, GOT_OBJ_TYPE_ANY,
6674 &refs, repo);
6675 got_ref_list_free(&refs);
6676 if (err)
6677 goto done;
6679 err = got_ref_alloc(&ref, refname, id);
6680 if (err)
6681 goto done;
6683 err = got_ref_write(ref, repo);
6684 done:
6685 if (ref)
6686 got_ref_close(ref);
6687 free(id);
6688 return err;
6691 static const struct got_error *
6692 add_symref(struct got_repository *repo, const char *refname, const char *target)
6694 const struct got_error *err = NULL;
6695 struct got_reference *ref = NULL;
6696 struct got_reference *target_ref = NULL;
6699 * Don't let the user create a reference name with a leading '-'.
6700 * While technically a valid reference name, this case is usually
6701 * an unintended typo.
6703 if (refname[0] == '-')
6704 return got_error_path(refname, GOT_ERR_REF_NAME_MINUS);
6706 err = got_ref_open(&target_ref, repo, target, 0);
6707 if (err)
6708 return err;
6710 err = got_ref_alloc_symref(&ref, refname, target_ref);
6711 if (err)
6712 goto done;
6714 err = got_ref_write(ref, repo);
6715 done:
6716 if (target_ref)
6717 got_ref_close(target_ref);
6718 if (ref)
6719 got_ref_close(ref);
6720 return err;
6723 static const struct got_error *
6724 cmd_ref(int argc, char *argv[])
6726 const struct got_error *error = NULL;
6727 struct got_repository *repo = NULL;
6728 struct got_worktree *worktree = NULL;
6729 char *cwd = NULL, *repo_path = NULL;
6730 int ch, do_list = 0, do_delete = 0, sort_by_time = 0;
6731 const char *obj_arg = NULL, *symref_target= NULL;
6732 char *refname = NULL, *keyword_idstr = NULL;
6733 int *pack_fds = NULL;
6735 #ifndef PROFILE
6736 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
6737 "sendfd unveil", NULL) == -1)
6738 err(1, "pledge");
6739 #endif
6741 while ((ch = getopt(argc, argv, "c:dlr:s:t")) != -1) {
6742 switch (ch) {
6743 case 'c':
6744 obj_arg = optarg;
6745 break;
6746 case 'd':
6747 do_delete = 1;
6748 break;
6749 case 'l':
6750 do_list = 1;
6751 break;
6752 case 'r':
6753 repo_path = realpath(optarg, NULL);
6754 if (repo_path == NULL)
6755 return got_error_from_errno2("realpath",
6756 optarg);
6757 got_path_strip_trailing_slashes(repo_path);
6758 break;
6759 case 's':
6760 symref_target = optarg;
6761 break;
6762 case 't':
6763 sort_by_time = 1;
6764 break;
6765 default:
6766 usage_ref();
6767 /* NOTREACHED */
6771 if (obj_arg && do_list)
6772 option_conflict('c', 'l');
6773 if (obj_arg && do_delete)
6774 option_conflict('c', 'd');
6775 if (obj_arg && symref_target)
6776 option_conflict('c', 's');
6777 if (symref_target && do_delete)
6778 option_conflict('s', 'd');
6779 if (symref_target && do_list)
6780 option_conflict('s', 'l');
6781 if (do_delete && do_list)
6782 option_conflict('d', 'l');
6783 if (sort_by_time && !do_list)
6784 errx(1, "-t option requires -l option");
6786 argc -= optind;
6787 argv += optind;
6789 if (do_list) {
6790 if (argc != 0 && argc != 1)
6791 usage_ref();
6792 if (argc == 1) {
6793 refname = strdup(argv[0]);
6794 if (refname == NULL) {
6795 error = got_error_from_errno("strdup");
6796 goto done;
6799 } else {
6800 if (argc != 1)
6801 usage_ref();
6802 refname = strdup(argv[0]);
6803 if (refname == NULL) {
6804 error = got_error_from_errno("strdup");
6805 goto done;
6809 if (refname)
6810 got_path_strip_trailing_slashes(refname);
6812 cwd = getcwd(NULL, 0);
6813 if (cwd == NULL) {
6814 error = got_error_from_errno("getcwd");
6815 goto done;
6818 error = got_repo_pack_fds_open(&pack_fds);
6819 if (error != NULL)
6820 goto done;
6822 if (repo_path == NULL) {
6823 error = got_worktree_open(&worktree, cwd,
6824 GOT_WORKTREE_GOT_DIR);
6825 if (error && error->code != GOT_ERR_NOT_WORKTREE)
6826 goto done;
6827 else
6828 error = NULL;
6829 if (worktree) {
6830 repo_path =
6831 strdup(got_worktree_get_repo_path(worktree));
6832 if (repo_path == NULL)
6833 error = got_error_from_errno("strdup");
6834 if (error)
6835 goto done;
6836 } else {
6837 repo_path = strdup(cwd);
6838 if (repo_path == NULL) {
6839 error = got_error_from_errno("strdup");
6840 goto done;
6845 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
6846 if (error != NULL)
6847 goto done;
6849 #ifndef PROFILE
6850 if (do_list) {
6851 /* Remove "cpath" promise. */
6852 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
6853 NULL) == -1)
6854 err(1, "pledge");
6856 #endif
6858 error = apply_unveil(got_repo_get_path(repo), do_list,
6859 worktree ? got_worktree_get_root_path(worktree) : NULL);
6860 if (error)
6861 goto done;
6863 if (do_list)
6864 error = list_refs(repo, refname, sort_by_time);
6865 else if (do_delete)
6866 error = delete_ref_by_name(repo, refname);
6867 else if (symref_target)
6868 error = add_symref(repo, refname, symref_target);
6869 else {
6870 if (obj_arg == NULL)
6871 usage_ref();
6873 error = got_keyword_to_idstr(&keyword_idstr, obj_arg,
6874 repo, worktree);
6875 if (error != NULL)
6876 goto done;
6877 if (keyword_idstr != NULL)
6878 obj_arg = keyword_idstr;
6880 error = add_ref(repo, refname, obj_arg);
6882 done:
6883 free(refname);
6884 if (repo) {
6885 const struct got_error *close_err = got_repo_close(repo);
6886 if (error == NULL)
6887 error = close_err;
6889 if (worktree)
6890 got_worktree_close(worktree);
6891 if (pack_fds) {
6892 const struct got_error *pack_err =
6893 got_repo_pack_fds_close(pack_fds);
6894 if (error == NULL)
6895 error = pack_err;
6897 free(cwd);
6898 free(repo_path);
6899 free(keyword_idstr);
6900 return error;
6903 __dead static void
6904 usage_branch(void)
6906 fprintf(stderr, "usage: %s branch [-lnt] [-c commit] [-d name] "
6907 "[-r repository-path] [name]\n", getprogname());
6908 exit(1);
6911 static const struct got_error *
6912 list_branch(struct got_repository *repo, struct got_worktree *worktree,
6913 struct got_reference *ref)
6915 const struct got_error *err = NULL;
6916 const char *refname;
6917 char *refstr;
6918 char marker = ' ';
6920 refname = got_ref_get_name(ref);
6921 if (worktree && strcmp(refname,
6922 got_worktree_get_head_ref_name(worktree)) == 0) {
6923 err = got_worktree_get_state(&marker, repo, worktree,
6924 check_cancelled, NULL);
6925 if (err != NULL)
6926 return err;
6929 if (strncmp(refname, "refs/heads/", 11) == 0)
6930 refname += 11;
6931 if (strncmp(refname, "refs/got/worktree/", 18) == 0)
6932 refname += 18;
6933 if (strncmp(refname, "refs/remotes/", 13) == 0)
6934 refname += 13;
6936 refstr = got_ref_to_str(ref);
6937 if (refstr == NULL)
6938 return got_error_from_errno("got_ref_to_str");
6940 printf("%c %s: %s\n", marker, refname, refstr);
6941 free(refstr);
6942 return NULL;
6945 static const struct got_error *
6946 show_current_branch(struct got_repository *repo, struct got_worktree *worktree)
6948 const char *refname;
6950 if (worktree == NULL)
6951 return got_error(GOT_ERR_NOT_WORKTREE);
6953 refname = got_worktree_get_head_ref_name(worktree);
6955 if (strncmp(refname, "refs/heads/", 11) == 0)
6956 refname += 11;
6957 if (strncmp(refname, "refs/got/worktree/", 18) == 0)
6958 refname += 18;
6960 printf("%s\n", refname);
6962 return NULL;
6965 static const struct got_error *
6966 list_branches(struct got_repository *repo, struct got_worktree *worktree,
6967 int sort_by_time)
6969 static const struct got_error *err = NULL;
6970 struct got_reflist_head refs;
6971 struct got_reflist_entry *re;
6972 struct got_reference *temp_ref = NULL;
6973 int rebase_in_progress, histedit_in_progress;
6975 TAILQ_INIT(&refs);
6977 if (worktree) {
6978 err = got_worktree_rebase_in_progress(&rebase_in_progress,
6979 worktree);
6980 if (err)
6981 return err;
6983 err = got_worktree_histedit_in_progress(&histedit_in_progress,
6984 worktree);
6985 if (err)
6986 return err;
6988 if (rebase_in_progress || histedit_in_progress) {
6989 err = got_ref_open(&temp_ref, repo,
6990 got_worktree_get_head_ref_name(worktree), 0);
6991 if (err)
6992 return err;
6993 list_branch(repo, worktree, temp_ref);
6994 got_ref_close(temp_ref);
6998 err = got_ref_list(&refs, repo, "refs/heads", sort_by_time ?
6999 got_ref_cmp_by_commit_timestamp_descending : got_ref_cmp_by_name,
7000 repo);
7001 if (err)
7002 return err;
7004 TAILQ_FOREACH(re, &refs, entry)
7005 list_branch(repo, worktree, re->ref);
7007 got_ref_list_free(&refs);
7009 err = got_ref_list(&refs, repo, "refs/remotes", sort_by_time ?
7010 got_ref_cmp_by_commit_timestamp_descending : got_ref_cmp_by_name,
7011 repo);
7012 if (err)
7013 return err;
7015 TAILQ_FOREACH(re, &refs, entry)
7016 list_branch(repo, worktree, re->ref);
7018 got_ref_list_free(&refs);
7020 return NULL;
7023 static const struct got_error *
7024 delete_branch(struct got_repository *repo, struct got_worktree *worktree,
7025 const char *branch_name)
7027 const struct got_error *err = NULL;
7028 struct got_reference *ref = NULL;
7029 char *refname, *remote_refname = NULL;
7031 if (strncmp(branch_name, "refs/", 5) == 0)
7032 branch_name += 5;
7033 if (strncmp(branch_name, "heads/", 6) == 0)
7034 branch_name += 6;
7035 else if (strncmp(branch_name, "remotes/", 8) == 0)
7036 branch_name += 8;
7038 if (asprintf(&refname, "refs/heads/%s", branch_name) == -1)
7039 return got_error_from_errno("asprintf");
7041 if (asprintf(&remote_refname, "refs/remotes/%s",
7042 branch_name) == -1) {
7043 err = got_error_from_errno("asprintf");
7044 goto done;
7047 err = got_ref_open(&ref, repo, refname, 0);
7048 if (err) {
7049 const struct got_error *err2;
7050 if (err->code != GOT_ERR_NOT_REF)
7051 goto done;
7053 * Keep 'err' intact such that if neither branch exists
7054 * we report "refs/heads" rather than "refs/remotes" in
7055 * our error message.
7057 err2 = got_ref_open(&ref, repo, remote_refname, 0);
7058 if (err2)
7059 goto done;
7060 err = NULL;
7063 if (worktree &&
7064 strcmp(got_worktree_get_head_ref_name(worktree),
7065 got_ref_get_name(ref)) == 0) {
7066 err = got_error_msg(GOT_ERR_SAME_BRANCH,
7067 "will not delete this work tree's current branch");
7068 goto done;
7071 err = delete_ref(repo, ref);
7072 done:
7073 if (ref)
7074 got_ref_close(ref);
7075 free(refname);
7076 free(remote_refname);
7077 return err;
7080 static const struct got_error *
7081 add_branch(struct got_repository *repo, const char *branch_name,
7082 struct got_object_id *base_commit_id)
7084 const struct got_error *err = NULL;
7085 struct got_reference *ref = NULL;
7086 char *refname = NULL;
7089 * Don't let the user create a branch name with a leading '-'.
7090 * While technically a valid reference name, this case is usually
7091 * an unintended typo.
7093 if (branch_name[0] == '-')
7094 return got_error_path(branch_name, GOT_ERR_REF_NAME_MINUS);
7096 if (strncmp(branch_name, "refs/heads/", 11) == 0)
7097 branch_name += 11;
7099 if (asprintf(&refname, "refs/heads/%s", branch_name) == -1) {
7100 err = got_error_from_errno("asprintf");
7101 goto done;
7104 err = got_ref_open(&ref, repo, refname, 0);
7105 if (err == NULL) {
7106 err = got_error(GOT_ERR_BRANCH_EXISTS);
7107 goto done;
7108 } else if (err->code != GOT_ERR_NOT_REF)
7109 goto done;
7111 err = got_ref_alloc(&ref, refname, base_commit_id);
7112 if (err)
7113 goto done;
7115 err = got_ref_write(ref, repo);
7116 done:
7117 if (ref)
7118 got_ref_close(ref);
7119 free(refname);
7120 return err;
7123 static const struct got_error *
7124 cmd_branch(int argc, char *argv[])
7126 const struct got_error *error = NULL;
7127 struct got_repository *repo = NULL;
7128 struct got_worktree *worktree = NULL;
7129 char *cwd = NULL, *repo_path = NULL;
7130 int ch, do_list = 0, do_show = 0, do_update = 1, sort_by_time = 0;
7131 const char *delref = NULL, *commit_id_arg = NULL;
7132 struct got_reference *ref = NULL;
7133 struct got_pathlist_head paths;
7134 struct got_object_id *commit_id = NULL;
7135 char *commit_id_str = NULL, *keyword_idstr = NULL;;
7136 int *pack_fds = NULL;
7138 TAILQ_INIT(&paths);
7140 #ifndef PROFILE
7141 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
7142 "sendfd unveil", NULL) == -1)
7143 err(1, "pledge");
7144 #endif
7146 while ((ch = getopt(argc, argv, "c:d:lnr:t")) != -1) {
7147 switch (ch) {
7148 case 'c':
7149 commit_id_arg = optarg;
7150 break;
7151 case 'd':
7152 delref = optarg;
7153 break;
7154 case 'l':
7155 do_list = 1;
7156 break;
7157 case 'n':
7158 do_update = 0;
7159 break;
7160 case 'r':
7161 repo_path = realpath(optarg, NULL);
7162 if (repo_path == NULL)
7163 return got_error_from_errno2("realpath",
7164 optarg);
7165 got_path_strip_trailing_slashes(repo_path);
7166 break;
7167 case 't':
7168 sort_by_time = 1;
7169 break;
7170 default:
7171 usage_branch();
7172 /* NOTREACHED */
7176 if (do_list && delref)
7177 option_conflict('l', 'd');
7178 if (sort_by_time && !do_list)
7179 errx(1, "-t option requires -l option");
7181 argc -= optind;
7182 argv += optind;
7184 if (!do_list && !delref && argc == 0)
7185 do_show = 1;
7187 if ((do_list || delref || do_show) && commit_id_arg != NULL)
7188 errx(1, "-c option can only be used when creating a branch");
7190 if (do_list || delref) {
7191 if (argc > 0)
7192 usage_branch();
7193 } else if (!do_show && argc != 1)
7194 usage_branch();
7196 cwd = getcwd(NULL, 0);
7197 if (cwd == NULL) {
7198 error = got_error_from_errno("getcwd");
7199 goto done;
7202 error = got_repo_pack_fds_open(&pack_fds);
7203 if (error != NULL)
7204 goto done;
7206 if (repo_path == NULL) {
7207 error = got_worktree_open(&worktree, cwd,
7208 GOT_WORKTREE_GOT_DIR);
7209 if (error && error->code != GOT_ERR_NOT_WORKTREE)
7210 goto done;
7211 else
7212 error = NULL;
7213 if (worktree) {
7214 repo_path =
7215 strdup(got_worktree_get_repo_path(worktree));
7216 if (repo_path == NULL)
7217 error = got_error_from_errno("strdup");
7218 if (error)
7219 goto done;
7220 } else {
7221 repo_path = strdup(cwd);
7222 if (repo_path == NULL) {
7223 error = got_error_from_errno("strdup");
7224 goto done;
7229 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
7230 if (error != NULL)
7231 goto done;
7233 #ifndef PROFILE
7234 if (do_list || do_show) {
7235 /* Remove "cpath" promise. */
7236 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
7237 NULL) == -1)
7238 err(1, "pledge");
7240 #endif
7242 error = apply_unveil(got_repo_get_path(repo), do_list,
7243 worktree ? got_worktree_get_root_path(worktree) : NULL);
7244 if (error)
7245 goto done;
7247 if (do_show)
7248 error = show_current_branch(repo, worktree);
7249 else if (do_list)
7250 error = list_branches(repo, worktree, sort_by_time);
7251 else if (delref)
7252 error = delete_branch(repo, worktree, delref);
7253 else {
7254 struct got_reflist_head refs;
7255 TAILQ_INIT(&refs);
7256 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
7257 NULL);
7258 if (error)
7259 goto done;
7260 if (commit_id_arg == NULL)
7261 commit_id_arg = worktree ?
7262 got_worktree_get_head_ref_name(worktree) :
7263 GOT_REF_HEAD;
7264 else {
7265 error = got_keyword_to_idstr(&keyword_idstr,
7266 commit_id_arg, repo, worktree);
7267 if (error != NULL)
7268 goto done;
7269 if (keyword_idstr != NULL)
7270 commit_id_arg = keyword_idstr;
7272 error = got_repo_match_object_id(&commit_id, NULL,
7273 commit_id_arg, GOT_OBJ_TYPE_COMMIT, &refs, repo);
7274 got_ref_list_free(&refs);
7275 if (error)
7276 goto done;
7277 error = add_branch(repo, argv[0], commit_id);
7278 if (error)
7279 goto done;
7280 if (worktree && do_update) {
7281 struct got_update_progress_arg upa;
7282 char *branch_refname = NULL;
7284 error = got_object_id_str(&commit_id_str, commit_id);
7285 if (error)
7286 goto done;
7287 error = get_worktree_paths_from_argv(&paths, 0, NULL,
7288 worktree);
7289 if (error)
7290 goto done;
7291 if (asprintf(&branch_refname, "refs/heads/%s", argv[0])
7292 == -1) {
7293 error = got_error_from_errno("asprintf");
7294 goto done;
7296 error = got_ref_open(&ref, repo, branch_refname, 0);
7297 free(branch_refname);
7298 if (error)
7299 goto done;
7300 error = switch_head_ref(ref, commit_id, worktree,
7301 repo);
7302 if (error)
7303 goto done;
7304 error = got_worktree_set_base_commit_id(worktree, repo,
7305 commit_id);
7306 if (error)
7307 goto done;
7308 memset(&upa, 0, sizeof(upa));
7309 error = got_worktree_checkout_files(worktree, &paths,
7310 repo, update_progress, &upa, check_cancelled,
7311 NULL);
7312 if (error)
7313 goto done;
7314 if (upa.did_something) {
7315 printf("Updated to %s: %s\n",
7316 got_worktree_get_head_ref_name(worktree),
7317 commit_id_str);
7319 print_update_progress_stats(&upa);
7322 done:
7323 free(keyword_idstr);
7324 if (ref)
7325 got_ref_close(ref);
7326 if (repo) {
7327 const struct got_error *close_err = got_repo_close(repo);
7328 if (error == NULL)
7329 error = close_err;
7331 if (worktree)
7332 got_worktree_close(worktree);
7333 if (pack_fds) {
7334 const struct got_error *pack_err =
7335 got_repo_pack_fds_close(pack_fds);
7336 if (error == NULL)
7337 error = pack_err;
7339 free(cwd);
7340 free(repo_path);
7341 free(commit_id);
7342 free(commit_id_str);
7343 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
7344 return error;
7348 __dead static void
7349 usage_tag(void)
7351 fprintf(stderr, "usage: %s tag [-lVv] [-c commit] [-m message] "
7352 "[-r repository-path] [-s signer-id] name\n", getprogname());
7353 exit(1);
7356 #if 0
7357 static const struct got_error *
7358 sort_tags(struct got_reflist_head *sorted, struct got_reflist_head *tags)
7360 const struct got_error *err = NULL;
7361 struct got_reflist_entry *re, *se, *new;
7362 struct got_object_id *re_id, *se_id;
7363 struct got_tag_object *re_tag, *se_tag;
7364 time_t re_time, se_time;
7366 STAILQ_FOREACH(re, tags, entry) {
7367 se = STAILQ_FIRST(sorted);
7368 if (se == NULL) {
7369 err = got_reflist_entry_dup(&new, re);
7370 if (err)
7371 return err;
7372 STAILQ_INSERT_HEAD(sorted, new, entry);
7373 continue;
7374 } else {
7375 err = got_ref_resolve(&re_id, repo, re->ref);
7376 if (err)
7377 break;
7378 err = got_object_open_as_tag(&re_tag, repo, re_id);
7379 free(re_id);
7380 if (err)
7381 break;
7382 re_time = got_object_tag_get_tagger_time(re_tag);
7383 got_object_tag_close(re_tag);
7386 while (se) {
7387 err = got_ref_resolve(&se_id, repo, re->ref);
7388 if (err)
7389 break;
7390 err = got_object_open_as_tag(&se_tag, repo, se_id);
7391 free(se_id);
7392 if (err)
7393 break;
7394 se_time = got_object_tag_get_tagger_time(se_tag);
7395 got_object_tag_close(se_tag);
7397 if (se_time > re_time) {
7398 err = got_reflist_entry_dup(&new, re);
7399 if (err)
7400 return err;
7401 STAILQ_INSERT_AFTER(sorted, se, new, entry);
7402 break;
7404 se = STAILQ_NEXT(se, entry);
7405 continue;
7408 done:
7409 return err;
7411 #endif
7413 static const struct got_error *
7414 get_tag_refname(char **refname, const char *tag_name)
7416 const struct got_error *err;
7418 if (strncmp("refs/tags/", tag_name, 10) == 0) {
7419 *refname = strdup(tag_name);
7420 if (*refname == NULL)
7421 return got_error_from_errno("strdup");
7422 } else if (asprintf(refname, "refs/tags/%s", tag_name) == -1) {
7423 err = got_error_from_errno("asprintf");
7424 *refname = NULL;
7425 return err;
7428 return NULL;
7431 static const struct got_error *
7432 list_tags(struct got_repository *repo, const char *tag_name, int verify_tags,
7433 const char *allowed_signers, const char *revoked_signers, int verbosity)
7435 static const struct got_error *err = NULL;
7436 struct got_reflist_head refs;
7437 struct got_reflist_entry *re;
7438 char *wanted_refname = NULL;
7439 int bad_sigs = 0;
7441 TAILQ_INIT(&refs);
7443 err = got_ref_list(&refs, repo, "refs/tags", got_ref_cmp_tags, repo);
7444 if (err)
7445 return err;
7447 if (tag_name) {
7448 struct got_reference *ref;
7449 err = get_tag_refname(&wanted_refname, tag_name);
7450 if (err)
7451 goto done;
7452 /* Wanted tag reference should exist. */
7453 err = got_ref_open(&ref, repo, wanted_refname, 0);
7454 if (err)
7455 goto done;
7456 got_ref_close(ref);
7459 TAILQ_FOREACH(re, &refs, entry) {
7460 const char *refname;
7461 char *refstr, *tagmsg0, *tagmsg, *line, *id_str, *datestr;
7462 char datebuf[26];
7463 const char *tagger, *ssh_sig = NULL;
7464 char *sig_msg = NULL;
7465 time_t tagger_time;
7466 struct got_object_id *id;
7467 struct got_tag_object *tag;
7468 struct got_commit_object *commit = NULL;
7470 refname = got_ref_get_name(re->ref);
7471 if (strncmp(refname, "refs/tags/", 10) != 0 ||
7472 (wanted_refname && strcmp(refname, wanted_refname) != 0))
7473 continue;
7474 refname += 10;
7475 refstr = got_ref_to_str(re->ref);
7476 if (refstr == NULL) {
7477 err = got_error_from_errno("got_ref_to_str");
7478 break;
7481 err = got_ref_resolve(&id, repo, re->ref);
7482 if (err)
7483 break;
7484 err = got_object_open_as_tag(&tag, repo, id);
7485 if (err) {
7486 if (err->code != GOT_ERR_OBJ_TYPE) {
7487 free(id);
7488 break;
7490 /* "lightweight" tag */
7491 err = got_object_open_as_commit(&commit, repo, id);
7492 if (err) {
7493 free(id);
7494 break;
7496 tagger = got_object_commit_get_committer(commit);
7497 tagger_time =
7498 got_object_commit_get_committer_time(commit);
7499 err = got_object_id_str(&id_str, id);
7500 free(id);
7501 if (err)
7502 break;
7503 } else {
7504 free(id);
7505 tagger = got_object_tag_get_tagger(tag);
7506 tagger_time = got_object_tag_get_tagger_time(tag);
7507 err = got_object_id_str(&id_str,
7508 got_object_tag_get_object_id(tag));
7509 if (err)
7510 break;
7513 if (tag && verify_tags) {
7514 ssh_sig = got_sigs_get_tagmsg_ssh_signature(
7515 got_object_tag_get_message(tag));
7516 if (ssh_sig && allowed_signers == NULL) {
7517 err = got_error_msg(
7518 GOT_ERR_VERIFY_TAG_SIGNATURE,
7519 "SSH signature verification requires "
7520 "setting allowed_signers in "
7521 "got.conf(5)");
7522 break;
7526 printf("%stag %s %s\n", GOT_COMMIT_SEP_STR, refname, refstr);
7527 free(refstr);
7528 printf("from: %s\n", tagger);
7529 datestr = get_datestr(&tagger_time, datebuf);
7530 if (datestr)
7531 printf("date: %s UTC\n", datestr);
7532 if (commit)
7533 printf("object: %s %s\n", GOT_OBJ_LABEL_COMMIT, id_str);
7534 else {
7535 switch (got_object_tag_get_object_type(tag)) {
7536 case GOT_OBJ_TYPE_BLOB:
7537 printf("object: %s %s\n", GOT_OBJ_LABEL_BLOB,
7538 id_str);
7539 break;
7540 case GOT_OBJ_TYPE_TREE:
7541 printf("object: %s %s\n", GOT_OBJ_LABEL_TREE,
7542 id_str);
7543 break;
7544 case GOT_OBJ_TYPE_COMMIT:
7545 printf("object: %s %s\n", GOT_OBJ_LABEL_COMMIT,
7546 id_str);
7547 break;
7548 case GOT_OBJ_TYPE_TAG:
7549 printf("object: %s %s\n", GOT_OBJ_LABEL_TAG,
7550 id_str);
7551 break;
7552 default:
7553 break;
7556 free(id_str);
7558 if (ssh_sig) {
7559 err = got_sigs_verify_tag_ssh(&sig_msg, tag, ssh_sig,
7560 allowed_signers, revoked_signers, verbosity);
7561 if (err && err->code == GOT_ERR_BAD_TAG_SIGNATURE)
7562 bad_sigs = 1;
7563 else if (err)
7564 break;
7565 printf("signature: %s", sig_msg);
7566 free(sig_msg);
7567 sig_msg = NULL;
7570 if (commit) {
7571 err = got_object_commit_get_logmsg(&tagmsg0, commit);
7572 if (err)
7573 break;
7574 got_object_commit_close(commit);
7575 } else {
7576 tagmsg0 = strdup(got_object_tag_get_message(tag));
7577 got_object_tag_close(tag);
7578 if (tagmsg0 == NULL) {
7579 err = got_error_from_errno("strdup");
7580 break;
7584 tagmsg = tagmsg0;
7585 do {
7586 line = strsep(&tagmsg, "\n");
7587 if (line)
7588 printf(" %s\n", line);
7589 } while (line);
7590 free(tagmsg0);
7592 done:
7593 got_ref_list_free(&refs);
7594 free(wanted_refname);
7596 if (err == NULL && bad_sigs)
7597 err = got_error(GOT_ERR_BAD_TAG_SIGNATURE);
7598 return err;
7601 static const struct got_error *
7602 get_tag_message(char **tagmsg, char **tagmsg_path, const char *commit_id_str,
7603 const char *tag_name, const char *editor, const char *repo_path)
7605 const struct got_error *err = NULL;
7606 char *template = NULL, *initial_content = NULL;
7607 int initial_content_len;
7608 int fd = -1;
7610 if (asprintf(&template, GOT_TMPDIR_STR "/got-tagmsg") == -1) {
7611 err = got_error_from_errno("asprintf");
7612 goto done;
7615 initial_content_len = asprintf(&initial_content,
7616 "\n# tagging commit %s as %s\n",
7617 commit_id_str, tag_name);
7618 if (initial_content_len == -1) {
7619 err = got_error_from_errno("asprintf");
7620 goto done;
7623 err = got_opentemp_named_fd(tagmsg_path, &fd, template, "");
7624 if (err)
7625 goto done;
7627 if (write(fd, initial_content, initial_content_len) == -1) {
7628 err = got_error_from_errno2("write", *tagmsg_path);
7629 goto done;
7631 if (close(fd) == -1) {
7632 err = got_error_from_errno2("close", *tagmsg_path);
7633 goto done;
7635 fd = -1;
7637 err = edit_logmsg(tagmsg, editor, *tagmsg_path, initial_content,
7638 initial_content_len, 1);
7639 done:
7640 free(initial_content);
7641 free(template);
7643 if (fd != -1 && close(fd) == -1 && err == NULL)
7644 err = got_error_from_errno2("close", *tagmsg_path);
7646 if (err) {
7647 free(*tagmsg);
7648 *tagmsg = NULL;
7650 return err;
7653 static const struct got_error *
7654 add_tag(struct got_repository *repo, const char *tagger,
7655 const char *tag_name, const char *commit_arg, const char *tagmsg_arg,
7656 const char *signer_id, const char *editor, int verbosity)
7658 const struct got_error *err = NULL;
7659 struct got_object_id *commit_id = NULL, *tag_id = NULL;
7660 char *label = NULL, *commit_id_str = NULL;
7661 struct got_reference *ref = NULL;
7662 char *refname = NULL, *tagmsg = NULL;
7663 char *tagmsg_path = NULL, *tag_id_str = NULL;
7664 int preserve_tagmsg = 0;
7665 struct got_reflist_head refs;
7667 TAILQ_INIT(&refs);
7670 * Don't let the user create a tag name with a leading '-'.
7671 * While technically a valid reference name, this case is usually
7672 * an unintended typo.
7674 if (tag_name[0] == '-')
7675 return got_error_path(tag_name, GOT_ERR_REF_NAME_MINUS);
7677 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
7678 if (err)
7679 goto done;
7681 err = got_repo_match_object_id(&commit_id, &label, commit_arg,
7682 GOT_OBJ_TYPE_COMMIT, &refs, repo);
7683 if (err)
7684 goto done;
7686 err = got_object_id_str(&commit_id_str, commit_id);
7687 if (err)
7688 goto done;
7690 err = get_tag_refname(&refname, tag_name);
7691 if (err)
7692 goto done;
7693 if (strncmp("refs/tags/", tag_name, 10) == 0)
7694 tag_name += 10;
7696 err = got_ref_open(&ref, repo, refname, 0);
7697 if (err == NULL) {
7698 err = got_error(GOT_ERR_TAG_EXISTS);
7699 goto done;
7700 } else if (err->code != GOT_ERR_NOT_REF)
7701 goto done;
7703 if (tagmsg_arg == NULL) {
7704 err = get_tag_message(&tagmsg, &tagmsg_path, commit_id_str,
7705 tag_name, editor, got_repo_get_path(repo));
7706 if (err) {
7707 if (err->code != GOT_ERR_COMMIT_MSG_EMPTY &&
7708 tagmsg_path != NULL)
7709 preserve_tagmsg = 1;
7710 goto done;
7714 err = got_object_tag_create(&tag_id, tag_name, commit_id,
7715 tagger, time(NULL), tagmsg ? tagmsg : tagmsg_arg, signer_id, repo,
7716 verbosity);
7717 if (err) {
7718 if (tagmsg_path)
7719 preserve_tagmsg = 1;
7720 goto done;
7723 err = got_ref_alloc(&ref, refname, tag_id);
7724 if (err) {
7725 if (tagmsg_path)
7726 preserve_tagmsg = 1;
7727 goto done;
7730 err = got_ref_write(ref, repo);
7731 if (err) {
7732 if (tagmsg_path)
7733 preserve_tagmsg = 1;
7734 goto done;
7737 err = got_object_id_str(&tag_id_str, tag_id);
7738 if (err) {
7739 if (tagmsg_path)
7740 preserve_tagmsg = 1;
7741 goto done;
7743 printf("Created tag %s\n", tag_id_str);
7744 done:
7745 if (preserve_tagmsg) {
7746 fprintf(stderr, "%s: tag message preserved in %s\n",
7747 getprogname(), tagmsg_path);
7748 } else if (tagmsg_path && unlink(tagmsg_path) == -1 && err == NULL)
7749 err = got_error_from_errno2("unlink", tagmsg_path);
7750 free(tag_id_str);
7751 if (ref)
7752 got_ref_close(ref);
7753 free(commit_id);
7754 free(commit_id_str);
7755 free(refname);
7756 free(tagmsg);
7757 free(tagmsg_path);
7758 got_ref_list_free(&refs);
7759 return err;
7762 static const struct got_error *
7763 cmd_tag(int argc, char *argv[])
7765 const struct got_error *error = NULL;
7766 struct got_repository *repo = NULL;
7767 struct got_worktree *worktree = NULL;
7768 char *cwd = NULL, *repo_path = NULL, *commit_id_str = NULL;
7769 char *gitconfig_path = NULL, *tagger = NULL, *keyword_idstr = NULL;
7770 char *allowed_signers = NULL, *revoked_signers = NULL, *editor = NULL;
7771 const char *signer_id = NULL;
7772 const char *tag_name = NULL, *commit_id_arg = NULL, *tagmsg = NULL;
7773 int ch, do_list = 0, verify_tags = 0, verbosity = 0;
7774 int *pack_fds = NULL;
7776 #ifndef PROFILE
7777 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
7778 "sendfd unveil", NULL) == -1)
7779 err(1, "pledge");
7780 #endif
7782 while ((ch = getopt(argc, argv, "c:lm:r:s:Vv")) != -1) {
7783 switch (ch) {
7784 case 'c':
7785 commit_id_arg = optarg;
7786 break;
7787 case 'l':
7788 do_list = 1;
7789 break;
7790 case 'm':
7791 tagmsg = optarg;
7792 break;
7793 case 'r':
7794 repo_path = realpath(optarg, NULL);
7795 if (repo_path == NULL) {
7796 error = got_error_from_errno2("realpath",
7797 optarg);
7798 goto done;
7800 got_path_strip_trailing_slashes(repo_path);
7801 break;
7802 case 's':
7803 signer_id = optarg;
7804 break;
7805 case 'V':
7806 verify_tags = 1;
7807 break;
7808 case 'v':
7809 if (verbosity < 0)
7810 verbosity = 0;
7811 else if (verbosity < 3)
7812 verbosity++;
7813 break;
7814 default:
7815 usage_tag();
7816 /* NOTREACHED */
7820 argc -= optind;
7821 argv += optind;
7823 if (do_list || verify_tags) {
7824 if (commit_id_arg != NULL)
7825 errx(1,
7826 "-c option can only be used when creating a tag");
7827 if (tagmsg) {
7828 if (do_list)
7829 option_conflict('l', 'm');
7830 else
7831 option_conflict('V', 'm');
7833 if (signer_id) {
7834 if (do_list)
7835 option_conflict('l', 's');
7836 else
7837 option_conflict('V', 's');
7839 if (argc > 1)
7840 usage_tag();
7841 } else if (argc != 1)
7842 usage_tag();
7844 if (argc == 1)
7845 tag_name = argv[0];
7847 cwd = getcwd(NULL, 0);
7848 if (cwd == NULL) {
7849 error = got_error_from_errno("getcwd");
7850 goto done;
7853 error = got_repo_pack_fds_open(&pack_fds);
7854 if (error != NULL)
7855 goto done;
7857 if (repo_path == NULL) {
7858 error = got_worktree_open(&worktree, cwd,
7859 GOT_WORKTREE_GOT_DIR);
7860 if (error && error->code != GOT_ERR_NOT_WORKTREE)
7861 goto done;
7862 else
7863 error = NULL;
7864 if (worktree) {
7865 repo_path =
7866 strdup(got_worktree_get_repo_path(worktree));
7867 if (repo_path == NULL)
7868 error = got_error_from_errno("strdup");
7869 if (error)
7870 goto done;
7871 } else {
7872 repo_path = strdup(cwd);
7873 if (repo_path == NULL) {
7874 error = got_error_from_errno("strdup");
7875 goto done;
7880 if (do_list || verify_tags) {
7881 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
7882 if (error != NULL)
7883 goto done;
7884 error = get_allowed_signers(&allowed_signers, repo, worktree);
7885 if (error)
7886 goto done;
7887 error = get_revoked_signers(&revoked_signers, repo, worktree);
7888 if (error)
7889 goto done;
7890 if (worktree) {
7891 /* Release work tree lock. */
7892 got_worktree_close(worktree);
7893 worktree = NULL;
7897 * Remove "cpath" promise unless needed for signature tmpfile
7898 * creation.
7900 if (verify_tags)
7901 got_sigs_apply_unveil();
7902 else {
7903 #ifndef PROFILE
7904 if (pledge("stdio rpath wpath flock proc exec sendfd "
7905 "unveil", NULL) == -1)
7906 err(1, "pledge");
7907 #endif
7909 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
7910 if (error)
7911 goto done;
7912 error = list_tags(repo, tag_name, verify_tags, allowed_signers,
7913 revoked_signers, verbosity);
7914 } else {
7915 error = get_gitconfig_path(&gitconfig_path);
7916 if (error)
7917 goto done;
7918 error = got_repo_open(&repo, repo_path, gitconfig_path,
7919 pack_fds);
7920 if (error != NULL)
7921 goto done;
7923 error = get_author(&tagger, repo, worktree);
7924 if (error)
7925 goto done;
7926 if (signer_id == NULL)
7927 signer_id = get_signer_id(repo, worktree);
7929 if (tagmsg == NULL) {
7930 error = get_editor(&editor);
7931 if (error)
7932 goto done;
7933 if (unveil(editor, "x") != 0) {
7934 error = got_error_from_errno2("unveil", editor);
7935 goto done;
7938 if (signer_id) {
7939 error = got_sigs_apply_unveil();
7940 if (error)
7941 goto done;
7943 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
7944 if (error)
7945 goto done;
7947 if (commit_id_arg == NULL) {
7948 struct got_reference *head_ref;
7949 struct got_object_id *commit_id;
7950 error = got_ref_open(&head_ref, repo,
7951 worktree ? got_worktree_get_head_ref_name(worktree)
7952 : GOT_REF_HEAD, 0);
7953 if (error)
7954 goto done;
7955 error = got_ref_resolve(&commit_id, repo, head_ref);
7956 got_ref_close(head_ref);
7957 if (error)
7958 goto done;
7959 error = got_object_id_str(&commit_id_str, commit_id);
7960 free(commit_id);
7961 if (error)
7962 goto done;
7963 } else {
7964 error = got_keyword_to_idstr(&keyword_idstr,
7965 commit_id_arg, repo, worktree);
7966 if (error != NULL)
7967 goto done;
7968 commit_id_str = keyword_idstr;
7971 if (worktree) {
7972 /* Release work tree lock. */
7973 got_worktree_close(worktree);
7974 worktree = NULL;
7977 error = add_tag(repo, tagger, tag_name,
7978 commit_id_str ? commit_id_str : commit_id_arg, tagmsg,
7979 signer_id, editor, verbosity);
7981 done:
7982 if (repo) {
7983 const struct got_error *close_err = got_repo_close(repo);
7984 if (error == NULL)
7985 error = close_err;
7987 if (worktree)
7988 got_worktree_close(worktree);
7989 if (pack_fds) {
7990 const struct got_error *pack_err =
7991 got_repo_pack_fds_close(pack_fds);
7992 if (error == NULL)
7993 error = pack_err;
7995 free(cwd);
7996 free(editor);
7997 free(repo_path);
7998 free(gitconfig_path);
7999 free(commit_id_str);
8000 free(tagger);
8001 free(allowed_signers);
8002 free(revoked_signers);
8003 return error;
8006 __dead static void
8007 usage_add(void)
8009 fprintf(stderr, "usage: %s add [-IR] path ...\n", getprogname());
8010 exit(1);
8013 static const struct got_error *
8014 add_progress(void *arg, unsigned char status, const char *path)
8016 while (path[0] == '/')
8017 path++;
8018 printf("%c %s\n", status, path);
8019 return NULL;
8022 static const struct got_error *
8023 cmd_add(int argc, char *argv[])
8025 const struct got_error *error = NULL;
8026 struct got_repository *repo = NULL;
8027 struct got_worktree *worktree = NULL;
8028 char *cwd = NULL;
8029 struct got_pathlist_head paths;
8030 struct got_pathlist_entry *pe;
8031 int ch, can_recurse = 0, no_ignores = 0;
8032 int *pack_fds = NULL;
8034 TAILQ_INIT(&paths);
8036 #ifndef PROFILE
8037 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
8038 NULL) == -1)
8039 err(1, "pledge");
8040 #endif
8042 while ((ch = getopt(argc, argv, "IR")) != -1) {
8043 switch (ch) {
8044 case 'I':
8045 no_ignores = 1;
8046 break;
8047 case 'R':
8048 can_recurse = 1;
8049 break;
8050 default:
8051 usage_add();
8052 /* NOTREACHED */
8056 argc -= optind;
8057 argv += optind;
8059 if (argc < 1)
8060 usage_add();
8062 cwd = getcwd(NULL, 0);
8063 if (cwd == NULL) {
8064 error = got_error_from_errno("getcwd");
8065 goto done;
8068 error = got_repo_pack_fds_open(&pack_fds);
8069 if (error != NULL)
8070 goto done;
8072 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
8073 if (error) {
8074 if (error->code == GOT_ERR_NOT_WORKTREE)
8075 error = wrap_not_worktree_error(error, "add", cwd);
8076 goto done;
8079 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
8080 NULL, pack_fds);
8081 if (error != NULL)
8082 goto done;
8084 error = apply_unveil(got_repo_get_path(repo), 1,
8085 got_worktree_get_root_path(worktree));
8086 if (error)
8087 goto done;
8089 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
8090 if (error)
8091 goto done;
8093 if (!can_recurse) {
8094 char *ondisk_path;
8095 struct stat sb;
8096 TAILQ_FOREACH(pe, &paths, entry) {
8097 if (asprintf(&ondisk_path, "%s/%s",
8098 got_worktree_get_root_path(worktree),
8099 pe->path) == -1) {
8100 error = got_error_from_errno("asprintf");
8101 goto done;
8103 if (lstat(ondisk_path, &sb) == -1) {
8104 if (errno == ENOENT) {
8105 free(ondisk_path);
8106 continue;
8108 error = got_error_from_errno2("lstat",
8109 ondisk_path);
8110 free(ondisk_path);
8111 goto done;
8113 free(ondisk_path);
8114 if (S_ISDIR(sb.st_mode)) {
8115 error = got_error_msg(GOT_ERR_BAD_PATH,
8116 "adding directories requires -R option");
8117 goto done;
8122 error = got_worktree_schedule_add(worktree, &paths, add_progress,
8123 NULL, repo, no_ignores);
8124 done:
8125 if (repo) {
8126 const struct got_error *close_err = got_repo_close(repo);
8127 if (error == NULL)
8128 error = close_err;
8130 if (worktree)
8131 got_worktree_close(worktree);
8132 if (pack_fds) {
8133 const struct got_error *pack_err =
8134 got_repo_pack_fds_close(pack_fds);
8135 if (error == NULL)
8136 error = pack_err;
8138 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
8139 free(cwd);
8140 return error;
8143 __dead static void
8144 usage_remove(void)
8146 fprintf(stderr, "usage: %s remove [-fkR] [-s status-codes] path ...\n",
8147 getprogname());
8148 exit(1);
8151 static const struct got_error *
8152 print_remove_status(void *arg, unsigned char status,
8153 unsigned char staged_status, const char *path)
8155 while (path[0] == '/')
8156 path++;
8157 if (status == GOT_STATUS_NONEXISTENT)
8158 return NULL;
8159 if (status == staged_status && (status == GOT_STATUS_DELETE))
8160 status = GOT_STATUS_NO_CHANGE;
8161 printf("%c%c %s\n", status, staged_status, path);
8162 return NULL;
8165 static const struct got_error *
8166 cmd_remove(int argc, char *argv[])
8168 const struct got_error *error = NULL;
8169 struct got_worktree *worktree = NULL;
8170 struct got_repository *repo = NULL;
8171 const char *status_codes = NULL;
8172 char *cwd = NULL;
8173 struct got_pathlist_head paths;
8174 struct got_pathlist_entry *pe;
8175 int ch, delete_local_mods = 0, can_recurse = 0, keep_on_disk = 0, i;
8176 int ignore_missing_paths = 0;
8177 int *pack_fds = NULL;
8179 TAILQ_INIT(&paths);
8181 #ifndef PROFILE
8182 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
8183 NULL) == -1)
8184 err(1, "pledge");
8185 #endif
8187 while ((ch = getopt(argc, argv, "fkRs:")) != -1) {
8188 switch (ch) {
8189 case 'f':
8190 delete_local_mods = 1;
8191 ignore_missing_paths = 1;
8192 break;
8193 case 'k':
8194 keep_on_disk = 1;
8195 break;
8196 case 'R':
8197 can_recurse = 1;
8198 break;
8199 case 's':
8200 for (i = 0; optarg[i] != '\0'; i++) {
8201 switch (optarg[i]) {
8202 case GOT_STATUS_MODIFY:
8203 delete_local_mods = 1;
8204 break;
8205 case GOT_STATUS_MISSING:
8206 ignore_missing_paths = 1;
8207 break;
8208 default:
8209 errx(1, "invalid status code '%c'",
8210 optarg[i]);
8213 status_codes = optarg;
8214 break;
8215 default:
8216 usage_remove();
8217 /* NOTREACHED */
8221 argc -= optind;
8222 argv += optind;
8224 if (argc < 1)
8225 usage_remove();
8227 cwd = getcwd(NULL, 0);
8228 if (cwd == NULL) {
8229 error = got_error_from_errno("getcwd");
8230 goto done;
8233 error = got_repo_pack_fds_open(&pack_fds);
8234 if (error != NULL)
8235 goto done;
8237 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
8238 if (error) {
8239 if (error->code == GOT_ERR_NOT_WORKTREE)
8240 error = wrap_not_worktree_error(error, "remove", cwd);
8241 goto done;
8244 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
8245 NULL, pack_fds);
8246 if (error)
8247 goto done;
8249 error = apply_unveil(got_repo_get_path(repo), 1,
8250 got_worktree_get_root_path(worktree));
8251 if (error)
8252 goto done;
8254 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
8255 if (error)
8256 goto done;
8258 if (!can_recurse) {
8259 char *ondisk_path;
8260 struct stat sb;
8261 TAILQ_FOREACH(pe, &paths, entry) {
8262 if (asprintf(&ondisk_path, "%s/%s",
8263 got_worktree_get_root_path(worktree),
8264 pe->path) == -1) {
8265 error = got_error_from_errno("asprintf");
8266 goto done;
8268 if (lstat(ondisk_path, &sb) == -1) {
8269 if (errno == ENOENT) {
8270 free(ondisk_path);
8271 continue;
8273 error = got_error_from_errno2("lstat",
8274 ondisk_path);
8275 free(ondisk_path);
8276 goto done;
8278 free(ondisk_path);
8279 if (S_ISDIR(sb.st_mode)) {
8280 error = got_error_msg(GOT_ERR_BAD_PATH,
8281 "removing directories requires -R option");
8282 goto done;
8287 error = got_worktree_schedule_delete(worktree, &paths,
8288 delete_local_mods, status_codes, print_remove_status, NULL,
8289 repo, keep_on_disk, ignore_missing_paths);
8290 done:
8291 if (repo) {
8292 const struct got_error *close_err = got_repo_close(repo);
8293 if (error == NULL)
8294 error = close_err;
8296 if (worktree)
8297 got_worktree_close(worktree);
8298 if (pack_fds) {
8299 const struct got_error *pack_err =
8300 got_repo_pack_fds_close(pack_fds);
8301 if (error == NULL)
8302 error = pack_err;
8304 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
8305 free(cwd);
8306 return error;
8309 __dead static void
8310 usage_patch(void)
8312 fprintf(stderr, "usage: %s patch [-nR] [-c commit] [-p strip-count] "
8313 "[patchfile]\n", getprogname());
8314 exit(1);
8317 static const struct got_error *
8318 patch_from_stdin(int *patchfd)
8320 const struct got_error *err = NULL;
8321 ssize_t r;
8322 char buf[BUFSIZ];
8323 sig_t sighup, sigint, sigquit;
8325 *patchfd = got_opentempfd();
8326 if (*patchfd == -1)
8327 return got_error_from_errno("got_opentempfd");
8329 sighup = signal(SIGHUP, SIG_DFL);
8330 sigint = signal(SIGINT, SIG_DFL);
8331 sigquit = signal(SIGQUIT, SIG_DFL);
8333 for (;;) {
8334 r = read(0, buf, sizeof(buf));
8335 if (r == -1) {
8336 err = got_error_from_errno("read");
8337 break;
8339 if (r == 0)
8340 break;
8341 if (write(*patchfd, buf, r) == -1) {
8342 err = got_error_from_errno("write");
8343 break;
8347 signal(SIGHUP, sighup);
8348 signal(SIGINT, sigint);
8349 signal(SIGQUIT, sigquit);
8351 if (err == NULL && lseek(*patchfd, 0, SEEK_SET) == -1)
8352 err = got_error_from_errno("lseek");
8354 if (err != NULL) {
8355 close(*patchfd);
8356 *patchfd = -1;
8359 return err;
8362 struct got_patch_progress_arg {
8363 int did_something;
8364 int conflicts;
8365 int rejects;
8368 static const struct got_error *
8369 patch_progress(void *arg, const char *old, const char *new,
8370 unsigned char status, const struct got_error *error, int old_from,
8371 int old_lines, int new_from, int new_lines, int offset,
8372 int ws_mangled, const struct got_error *hunk_err)
8374 const char *path = new == NULL ? old : new;
8375 struct got_patch_progress_arg *a = arg;
8377 while (*path == '/')
8378 path++;
8380 if (status != GOT_STATUS_NO_CHANGE &&
8381 status != 0 /* per-hunk progress */) {
8382 printf("%c %s\n", status, path);
8383 a->did_something = 1;
8386 if (hunk_err == NULL) {
8387 if (status == GOT_STATUS_CANNOT_UPDATE)
8388 a->rejects++;
8389 else if (status == GOT_STATUS_CONFLICT)
8390 a->conflicts++;
8393 if (error != NULL)
8394 fprintf(stderr, "%s: %s\n", getprogname(), error->msg);
8396 if (offset != 0 || hunk_err != NULL || ws_mangled) {
8397 printf("@@ -%d,%d +%d,%d @@ ", old_from,
8398 old_lines, new_from, new_lines);
8399 if (hunk_err != NULL)
8400 printf("%s\n", hunk_err->msg);
8401 else if (offset != 0)
8402 printf("applied with offset %d\n", offset);
8403 else
8404 printf("hunk contains mangled whitespace\n");
8407 return NULL;
8410 static void
8411 print_patch_progress_stats(struct got_patch_progress_arg *ppa)
8413 if (!ppa->did_something)
8414 return;
8416 if (ppa->conflicts > 0)
8417 printf("Files with merge conflicts: %d\n", ppa->conflicts);
8419 if (ppa->rejects > 0) {
8420 printf("Files where patch failed to apply: %d\n",
8421 ppa->rejects);
8425 static const struct got_error *
8426 cmd_patch(int argc, char *argv[])
8428 const struct got_error *error = NULL, *close_error = NULL;
8429 struct got_worktree *worktree = NULL;
8430 struct got_repository *repo = NULL;
8431 struct got_reflist_head refs;
8432 struct got_object_id *commit_id = NULL;
8433 const char *commit_id_str = NULL;
8434 struct stat sb;
8435 const char *errstr;
8436 char *cwd = NULL, *keyword_idstr = NULL;
8437 int ch, nop = 0, strip = -1, reverse = 0;
8438 int patchfd;
8439 int *pack_fds = NULL;
8440 struct got_patch_progress_arg ppa;
8442 TAILQ_INIT(&refs);
8444 #ifndef PROFILE
8445 if (pledge("stdio rpath wpath cpath fattr proc exec sendfd flock "
8446 "unveil", NULL) == -1)
8447 err(1, "pledge");
8448 #endif
8450 while ((ch = getopt(argc, argv, "c:np:R")) != -1) {
8451 switch (ch) {
8452 case 'c':
8453 commit_id_str = optarg;
8454 break;
8455 case 'n':
8456 nop = 1;
8457 break;
8458 case 'p':
8459 strip = strtonum(optarg, 0, INT_MAX, &errstr);
8460 if (errstr != NULL)
8461 errx(1, "pathname strip count is %s: %s",
8462 errstr, optarg);
8463 break;
8464 case 'R':
8465 reverse = 1;
8466 break;
8467 default:
8468 usage_patch();
8469 /* NOTREACHED */
8473 argc -= optind;
8474 argv += optind;
8476 if (argc == 0) {
8477 error = patch_from_stdin(&patchfd);
8478 if (error)
8479 return error;
8480 } else if (argc == 1) {
8481 patchfd = open(argv[0], O_RDONLY);
8482 if (patchfd == -1) {
8483 error = got_error_from_errno2("open", argv[0]);
8484 return error;
8486 if (fstat(patchfd, &sb) == -1) {
8487 error = got_error_from_errno2("fstat", argv[0]);
8488 goto done;
8490 if (!S_ISREG(sb.st_mode)) {
8491 error = got_error_path(argv[0], GOT_ERR_BAD_FILETYPE);
8492 goto done;
8494 } else
8495 usage_patch();
8497 if ((cwd = getcwd(NULL, 0)) == NULL) {
8498 error = got_error_from_errno("getcwd");
8499 goto done;
8502 error = got_repo_pack_fds_open(&pack_fds);
8503 if (error != NULL)
8504 goto done;
8506 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
8507 if (error != NULL)
8508 goto done;
8510 const char *repo_path = got_worktree_get_repo_path(worktree);
8511 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
8512 if (error != NULL)
8513 goto done;
8515 error = apply_unveil(got_repo_get_path(repo), 0,
8516 got_worktree_get_root_path(worktree));
8517 if (error != NULL)
8518 goto done;
8520 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
8521 if (error)
8522 goto done;
8524 if (commit_id_str != NULL) {
8525 error = got_keyword_to_idstr(&keyword_idstr, commit_id_str,
8526 repo, worktree);
8527 if (error != NULL)
8528 goto done;
8530 error = got_repo_match_object_id(&commit_id, NULL,
8531 keyword_idstr != NULL ? keyword_idstr : commit_id_str,
8532 GOT_OBJ_TYPE_COMMIT, &refs, repo);
8533 if (error)
8534 goto done;
8537 memset(&ppa, 0, sizeof(ppa));
8538 error = got_patch(patchfd, worktree, repo, nop, strip, reverse,
8539 commit_id, patch_progress, &ppa, check_cancelled, NULL);
8540 print_patch_progress_stats(&ppa);
8541 done:
8542 got_ref_list_free(&refs);
8543 free(keyword_idstr);
8544 free(commit_id);
8545 if (repo) {
8546 close_error = got_repo_close(repo);
8547 if (error == NULL)
8548 error = close_error;
8550 if (worktree != NULL) {
8551 close_error = got_worktree_close(worktree);
8552 if (error == NULL)
8553 error = close_error;
8555 if (pack_fds) {
8556 const struct got_error *pack_err =
8557 got_repo_pack_fds_close(pack_fds);
8558 if (error == NULL)
8559 error = pack_err;
8561 free(cwd);
8562 return error;
8565 __dead static void
8566 usage_revert(void)
8568 fprintf(stderr, "usage: %s revert [-pR] [-F response-script] path ...\n",
8569 getprogname());
8570 exit(1);
8573 static const struct got_error *
8574 revert_progress(void *arg, unsigned char status, const char *path)
8576 if (status == GOT_STATUS_UNVERSIONED)
8577 return NULL;
8579 while (path[0] == '/')
8580 path++;
8581 printf("%c %s\n", status, path);
8582 return NULL;
8585 struct choose_patch_arg {
8586 FILE *patch_script_file;
8587 const char *action;
8590 static const struct got_error *
8591 show_change(unsigned char status, const char *path, FILE *patch_file, int n,
8592 int nchanges, const char *action)
8594 const struct got_error *err;
8595 char *line = NULL;
8596 size_t linesize = 0;
8597 ssize_t linelen;
8599 switch (status) {
8600 case GOT_STATUS_ADD:
8601 printf("A %s\n%s this addition? [y/n] ", path, action);
8602 break;
8603 case GOT_STATUS_DELETE:
8604 printf("D %s\n%s this deletion? [y/n] ", path, action);
8605 break;
8606 case GOT_STATUS_MODIFY:
8607 if (fseek(patch_file, 0L, SEEK_SET) == -1)
8608 return got_error_from_errno("fseek");
8609 printf(GOT_COMMIT_SEP_STR);
8610 while ((linelen = getline(&line, &linesize, patch_file)) != -1)
8611 printf("%s", line);
8612 if (linelen == -1 && ferror(patch_file)) {
8613 err = got_error_from_errno("getline");
8614 free(line);
8615 return err;
8617 free(line);
8618 printf(GOT_COMMIT_SEP_STR);
8619 printf("M %s (change %d of %d)\n%s this change? [y/n/q] ",
8620 path, n, nchanges, action);
8621 break;
8622 default:
8623 return got_error_path(path, GOT_ERR_FILE_STATUS);
8626 fflush(stdout);
8627 return NULL;
8630 static const struct got_error *
8631 choose_patch(int *choice, void *arg, unsigned char status, const char *path,
8632 FILE *patch_file, int n, int nchanges)
8634 const struct got_error *err = NULL;
8635 char *line = NULL;
8636 size_t linesize = 0;
8637 ssize_t linelen;
8638 int resp = ' ';
8639 struct choose_patch_arg *a = arg;
8641 *choice = GOT_PATCH_CHOICE_NONE;
8643 if (a->patch_script_file) {
8644 char *nl;
8645 err = show_change(status, path, patch_file, n, nchanges,
8646 a->action);
8647 if (err)
8648 return err;
8649 linelen = getline(&line, &linesize, a->patch_script_file);
8650 if (linelen == -1) {
8651 if (ferror(a->patch_script_file))
8652 return got_error_from_errno("getline");
8653 return NULL;
8655 nl = strchr(line, '\n');
8656 if (nl)
8657 *nl = '\0';
8658 if (strcmp(line, "y") == 0) {
8659 *choice = GOT_PATCH_CHOICE_YES;
8660 printf("y\n");
8661 } else if (strcmp(line, "n") == 0) {
8662 *choice = GOT_PATCH_CHOICE_NO;
8663 printf("n\n");
8664 } else if (strcmp(line, "q") == 0 &&
8665 status == GOT_STATUS_MODIFY) {
8666 *choice = GOT_PATCH_CHOICE_QUIT;
8667 printf("q\n");
8668 } else
8669 printf("invalid response '%s'\n", line);
8670 free(line);
8671 return NULL;
8674 while (resp != 'y' && resp != 'n' && resp != 'q') {
8675 err = show_change(status, path, patch_file, n, nchanges,
8676 a->action);
8677 if (err)
8678 return err;
8679 resp = getchar();
8680 if (resp == '\n')
8681 resp = getchar();
8682 if (status == GOT_STATUS_MODIFY) {
8683 if (resp != 'y' && resp != 'n' && resp != 'q') {
8684 printf("invalid response '%c'\n", resp);
8685 resp = ' ';
8687 } else if (resp != 'y' && resp != 'n') {
8688 printf("invalid response '%c'\n", resp);
8689 resp = ' ';
8693 if (resp == 'y')
8694 *choice = GOT_PATCH_CHOICE_YES;
8695 else if (resp == 'n')
8696 *choice = GOT_PATCH_CHOICE_NO;
8697 else if (resp == 'q' && status == GOT_STATUS_MODIFY)
8698 *choice = GOT_PATCH_CHOICE_QUIT;
8700 return NULL;
8703 struct wt_commitable_path_arg {
8704 struct got_pathlist_head *commit_paths;
8705 int *has_changes;
8709 * Shortcut work tree status callback to determine if the set of paths scanned
8710 * has at least one versioned path that is being modified and, if not NULL, is
8711 * in the arg->commit_paths list. Set arg and return GOT_ERR_FILE_MODIFIED as
8712 * soon as a path is passed with a status that satisfies this criteria.
8714 static const struct got_error *
8715 worktree_has_commitable_path(void *arg, unsigned char status,
8716 unsigned char staged_status, const char *path,
8717 struct got_object_id *blob_id, struct got_object_id *staged_blob_id,
8718 struct got_object_id *commit_id, int dirfd, const char *de_name)
8720 struct wt_commitable_path_arg *a = arg;
8722 if (status == staged_status && (status == GOT_STATUS_DELETE))
8723 status = GOT_STATUS_NO_CHANGE;
8725 if (!(status == GOT_STATUS_NO_CHANGE ||
8726 status == GOT_STATUS_UNVERSIONED) ||
8727 staged_status != GOT_STATUS_NO_CHANGE) {
8728 if (a->commit_paths != NULL) {
8729 struct got_pathlist_entry *pe;
8731 TAILQ_FOREACH(pe, a->commit_paths, entry) {
8732 if (strncmp(path, pe->path,
8733 pe->path_len) == 0) {
8734 *a->has_changes = 1;
8735 break;
8738 } else
8739 *a->has_changes = 1;
8741 if (*a->has_changes)
8742 return got_error(GOT_ERR_FILE_MODIFIED);
8745 return NULL;
8749 * Check that the changeset of the commit identified by id is
8750 * comprised of at least one modified path that is being committed.
8752 static const struct got_error *
8753 commit_path_changed_in_worktree(struct wt_commitable_path_arg *wcpa,
8754 struct got_object_id *id, struct got_worktree *worktree,
8755 struct got_repository *repo)
8757 const struct got_error *err;
8758 struct got_pathlist_head paths;
8759 struct got_commit_object *commit = NULL, *pcommit = NULL;
8760 struct got_tree_object *tree = NULL, *ptree = NULL;
8761 struct got_object_qid *pid;
8763 TAILQ_INIT(&paths);
8765 err = got_object_open_as_commit(&commit, repo, id);
8766 if (err)
8767 goto done;
8769 err = got_object_open_as_tree(&tree, repo,
8770 got_object_commit_get_tree_id(commit));
8771 if (err)
8772 goto done;
8774 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
8775 if (pid != NULL) {
8776 err = got_object_open_as_commit(&pcommit, repo, &pid->id);
8777 if (err)
8778 goto done;
8780 err = got_object_open_as_tree(&ptree, repo,
8781 got_object_commit_get_tree_id(pcommit));
8782 if (err)
8783 goto done;
8786 err = got_diff_tree(ptree, tree, NULL, NULL, -1, -1, "", "", repo,
8787 got_diff_tree_collect_changed_paths, &paths, 0);
8788 if (err)
8789 goto done;
8791 err = got_worktree_status(worktree, &paths, repo, 0,
8792 worktree_has_commitable_path, wcpa, check_cancelled, NULL);
8793 if (err && err->code == GOT_ERR_FILE_MODIFIED) {
8795 * At least one changed path in the referenced commit is
8796 * modified in the work tree, that's all we need to know!
8798 err = NULL;
8801 done:
8802 got_pathlist_free(&paths, GOT_PATHLIST_FREE_ALL);
8803 if (commit)
8804 got_object_commit_close(commit);
8805 if (pcommit)
8806 got_object_commit_close(pcommit);
8807 if (tree)
8808 got_object_tree_close(tree);
8809 if (ptree)
8810 got_object_tree_close(ptree);
8811 return err;
8815 * Remove any "logmsg" reference comprised entirely of paths that have
8816 * been reverted in this work tree. If any path in the logmsg ref changeset
8817 * remains in a changed state in the worktree, do not remove the reference.
8819 static const struct got_error *
8820 rm_logmsg_ref(struct got_worktree *worktree, struct got_repository *repo)
8822 const struct got_error *err;
8823 struct got_reflist_head refs;
8824 struct got_reflist_entry *re;
8825 struct got_commit_object *commit = NULL;
8826 struct got_object_id *commit_id = NULL;
8827 struct wt_commitable_path_arg wcpa;
8828 char *uuidstr = NULL;
8830 TAILQ_INIT(&refs);
8832 err = got_worktree_get_uuid(&uuidstr, worktree);
8833 if (err)
8834 goto done;
8836 err = got_ref_list(&refs, repo, "refs/got/worktree",
8837 got_ref_cmp_by_name, repo);
8838 if (err)
8839 goto done;
8841 TAILQ_FOREACH(re, &refs, entry) {
8842 const char *refname;
8843 int has_changes = 0;
8845 refname = got_ref_get_name(re->ref);
8847 if (!strncmp(refname, GOT_WORKTREE_CHERRYPICK_REF_PREFIX,
8848 GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN))
8849 refname += GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN + 1;
8850 else if (!strncmp(refname, GOT_WORKTREE_BACKOUT_REF_PREFIX,
8851 GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN))
8852 refname += GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN + 1;
8853 else
8854 continue;
8856 if (strncmp(refname, uuidstr, GOT_WORKTREE_UUID_STRLEN) == 0)
8857 refname += GOT_WORKTREE_UUID_STRLEN + 1; /* skip '-' */
8858 else
8859 continue;
8861 err = got_repo_match_object_id(&commit_id, NULL, refname,
8862 GOT_OBJ_TYPE_COMMIT, NULL, repo);
8863 if (err)
8864 goto done;
8866 err = got_object_open_as_commit(&commit, repo, commit_id);
8867 if (err)
8868 goto done;
8870 wcpa.commit_paths = NULL;
8871 wcpa.has_changes = &has_changes;
8873 err = commit_path_changed_in_worktree(&wcpa, commit_id,
8874 worktree, repo);
8875 if (err)
8876 goto done;
8878 if (!has_changes) {
8879 err = got_ref_delete(re->ref, repo);
8880 if (err)
8881 goto done;
8884 got_object_commit_close(commit);
8885 commit = NULL;
8886 free(commit_id);
8887 commit_id = NULL;
8890 done:
8891 free(uuidstr);
8892 free(commit_id);
8893 got_ref_list_free(&refs);
8894 if (commit)
8895 got_object_commit_close(commit);
8896 return err;
8899 static const struct got_error *
8900 cmd_revert(int argc, char *argv[])
8902 const struct got_error *error = NULL;
8903 struct got_worktree *worktree = NULL;
8904 struct got_repository *repo = NULL;
8905 char *cwd = NULL, *path = NULL;
8906 struct got_pathlist_head paths;
8907 struct got_pathlist_entry *pe;
8908 int ch, can_recurse = 0, pflag = 0;
8909 FILE *patch_script_file = NULL;
8910 const char *patch_script_path = NULL;
8911 struct choose_patch_arg cpa;
8912 int *pack_fds = NULL;
8914 TAILQ_INIT(&paths);
8916 #ifndef PROFILE
8917 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
8918 "unveil", NULL) == -1)
8919 err(1, "pledge");
8920 #endif
8922 while ((ch = getopt(argc, argv, "F:pR")) != -1) {
8923 switch (ch) {
8924 case 'F':
8925 patch_script_path = optarg;
8926 break;
8927 case 'p':
8928 pflag = 1;
8929 break;
8930 case 'R':
8931 can_recurse = 1;
8932 break;
8933 default:
8934 usage_revert();
8935 /* NOTREACHED */
8939 argc -= optind;
8940 argv += optind;
8942 if (argc < 1)
8943 usage_revert();
8944 if (patch_script_path && !pflag)
8945 errx(1, "-F option can only be used together with -p option");
8947 cwd = getcwd(NULL, 0);
8948 if (cwd == NULL) {
8949 error = got_error_from_errno("getcwd");
8950 goto done;
8953 error = got_repo_pack_fds_open(&pack_fds);
8954 if (error != NULL)
8955 goto done;
8957 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
8958 if (error) {
8959 if (error->code == GOT_ERR_NOT_WORKTREE)
8960 error = wrap_not_worktree_error(error, "revert", cwd);
8961 goto done;
8964 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
8965 NULL, pack_fds);
8966 if (error != NULL)
8967 goto done;
8969 if (patch_script_path) {
8970 patch_script_file = fopen(patch_script_path, "re");
8971 if (patch_script_file == NULL) {
8972 error = got_error_from_errno2("fopen",
8973 patch_script_path);
8974 goto done;
8979 * XXX "c" perm needed on repo dir to delete merge references.
8981 error = apply_unveil(got_repo_get_path(repo), 0,
8982 got_worktree_get_root_path(worktree));
8983 if (error)
8984 goto done;
8986 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
8987 if (error)
8988 goto done;
8990 if (!can_recurse) {
8991 char *ondisk_path;
8992 struct stat sb;
8993 TAILQ_FOREACH(pe, &paths, entry) {
8994 if (asprintf(&ondisk_path, "%s/%s",
8995 got_worktree_get_root_path(worktree),
8996 pe->path) == -1) {
8997 error = got_error_from_errno("asprintf");
8998 goto done;
9000 if (lstat(ondisk_path, &sb) == -1) {
9001 if (errno == ENOENT) {
9002 free(ondisk_path);
9003 continue;
9005 error = got_error_from_errno2("lstat",
9006 ondisk_path);
9007 free(ondisk_path);
9008 goto done;
9010 free(ondisk_path);
9011 if (S_ISDIR(sb.st_mode)) {
9012 error = got_error_msg(GOT_ERR_BAD_PATH,
9013 "reverting directories requires -R option");
9014 goto done;
9019 cpa.patch_script_file = patch_script_file;
9020 cpa.action = "revert";
9021 error = got_worktree_revert(worktree, &paths, revert_progress, NULL,
9022 pflag ? choose_patch : NULL, &cpa, repo);
9024 error = rm_logmsg_ref(worktree, repo);
9025 done:
9026 if (patch_script_file && fclose(patch_script_file) == EOF &&
9027 error == NULL)
9028 error = got_error_from_errno2("fclose", patch_script_path);
9029 if (repo) {
9030 const struct got_error *close_err = got_repo_close(repo);
9031 if (error == NULL)
9032 error = close_err;
9034 if (worktree)
9035 got_worktree_close(worktree);
9036 if (pack_fds) {
9037 const struct got_error *pack_err =
9038 got_repo_pack_fds_close(pack_fds);
9039 if (error == NULL)
9040 error = pack_err;
9042 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
9043 free(path);
9044 free(cwd);
9045 return error;
9048 __dead static void
9049 usage_commit(void)
9051 fprintf(stderr, "usage: %s commit [-CNnS] [-A author] [-F path] "
9052 "[-m message] [path ...]\n", getprogname());
9053 exit(1);
9056 struct collect_commit_logmsg_arg {
9057 const char *cmdline_log;
9058 const char *prepared_log;
9059 const char *merged_log;
9060 int non_interactive;
9061 const char *editor;
9062 const char *worktree_path;
9063 const char *branch_name;
9064 const char *repo_path;
9065 char *logmsg_path;
9069 static const struct got_error *
9070 read_prepared_logmsg(char **logmsg, const char *path)
9072 const struct got_error *err = NULL;
9073 FILE *f = NULL;
9074 struct stat sb;
9075 size_t r;
9077 *logmsg = NULL;
9078 memset(&sb, 0, sizeof(sb));
9080 f = fopen(path, "re");
9081 if (f == NULL)
9082 return got_error_from_errno2("fopen", path);
9084 if (fstat(fileno(f), &sb) == -1) {
9085 err = got_error_from_errno2("fstat", path);
9086 goto done;
9088 if (sb.st_size == 0) {
9089 err = got_error(GOT_ERR_COMMIT_MSG_EMPTY);
9090 goto done;
9093 *logmsg = malloc(sb.st_size + 1);
9094 if (*logmsg == NULL) {
9095 err = got_error_from_errno("malloc");
9096 goto done;
9099 r = fread(*logmsg, 1, sb.st_size, f);
9100 if (r != sb.st_size) {
9101 if (ferror(f))
9102 err = got_error_from_errno2("fread", path);
9103 else
9104 err = got_error(GOT_ERR_IO);
9105 goto done;
9107 (*logmsg)[sb.st_size] = '\0';
9108 done:
9109 if (fclose(f) == EOF && err == NULL)
9110 err = got_error_from_errno2("fclose", path);
9111 if (err) {
9112 free(*logmsg);
9113 *logmsg = NULL;
9115 return err;
9118 static const struct got_error *
9119 collect_commit_logmsg(struct got_pathlist_head *commitable_paths,
9120 const char *diff_path, char **logmsg, void *arg)
9122 char *initial_content = NULL;
9123 struct got_pathlist_entry *pe;
9124 const struct got_error *err = NULL;
9125 char *template = NULL;
9126 char *prepared_msg = NULL, *merged_msg = NULL;
9127 struct collect_commit_logmsg_arg *a = arg;
9128 int initial_content_len;
9129 int fd = -1;
9130 size_t len;
9132 /* if a message was specified on the command line, just use it */
9133 if (a->cmdline_log != NULL && *a->cmdline_log != '\0') {
9134 len = strlen(a->cmdline_log) + 1;
9135 *logmsg = malloc(len + 1);
9136 if (*logmsg == NULL)
9137 return got_error_from_errno("malloc");
9138 strlcpy(*logmsg, a->cmdline_log, len);
9139 return NULL;
9140 } else if (a->prepared_log != NULL && a->non_interactive)
9141 return read_prepared_logmsg(logmsg, a->prepared_log);
9143 if (asprintf(&template, "%s/logmsg", a->worktree_path) == -1)
9144 return got_error_from_errno("asprintf");
9146 err = got_opentemp_named_fd(&a->logmsg_path, &fd, template, "");
9147 if (err)
9148 goto done;
9150 if (a->prepared_log) {
9151 err = read_prepared_logmsg(&prepared_msg, a->prepared_log);
9152 if (err)
9153 goto done;
9154 } else if (a->merged_log) {
9155 err = read_prepared_logmsg(&merged_msg, a->merged_log);
9156 if (err)
9157 goto done;
9160 initial_content_len = asprintf(&initial_content,
9161 "%s%s\n# changes to be committed on branch %s:\n",
9162 prepared_msg ? prepared_msg : "",
9163 merged_msg ? merged_msg : "", a->branch_name);
9164 if (initial_content_len == -1) {
9165 err = got_error_from_errno("asprintf");
9166 goto done;
9169 if (write(fd, initial_content, initial_content_len) == -1) {
9170 err = got_error_from_errno2("write", a->logmsg_path);
9171 goto done;
9174 TAILQ_FOREACH(pe, commitable_paths, entry) {
9175 struct got_commitable *ct = pe->data;
9176 dprintf(fd, "# %c %s\n",
9177 got_commitable_get_status(ct),
9178 got_commitable_get_path(ct));
9181 if (diff_path) {
9182 dprintf(fd, "# detailed changes can be viewed in %s\n",
9183 diff_path);
9186 if (close(fd) == -1) {
9187 err = got_error_from_errno2("close", a->logmsg_path);
9188 goto done;
9190 fd = -1;
9192 err = edit_logmsg(logmsg, a->editor, a->logmsg_path, initial_content,
9193 initial_content_len, a->prepared_log ? 0 : 1);
9194 done:
9195 free(initial_content);
9196 free(template);
9197 free(prepared_msg);
9198 free(merged_msg);
9200 if (fd != -1 && close(fd) == -1 && err == NULL)
9201 err = got_error_from_errno2("close", a->logmsg_path);
9202 if (err) {
9203 free(*logmsg);
9204 *logmsg = NULL;
9206 return err;
9209 static const struct got_error *
9210 cat_logmsg(FILE *f, struct got_commit_object *commit, const char *idstr,
9211 const char *type, int has_content)
9213 const struct got_error *err = NULL;
9214 char *logmsg = NULL;
9216 err = got_object_commit_get_logmsg(&logmsg, commit);
9217 if (err)
9218 return err;
9220 if (fprintf(f, "%s# log message of %s commit %s:%s",
9221 has_content ? "\n" : "", type, idstr, logmsg) < 0)
9222 err = got_ferror(f, GOT_ERR_IO);
9224 free(logmsg);
9225 return err;
9229 * Lookup "logmsg" references of backed-out and cherrypicked commits
9230 * belonging to the current work tree. If found, and the worktree has
9231 * at least one modified file that was changed in the referenced commit,
9232 * add its log message to a new temporary file at *logmsg_path.
9233 * Add all refs found to matched_refs to be scheduled for removal on
9234 * successful commit.
9236 static const struct got_error *
9237 lookup_logmsg_ref(char **logmsg_path, struct got_pathlist_head *paths,
9238 struct got_reflist_head *matched_refs, struct got_worktree *worktree,
9239 struct got_repository *repo)
9241 const struct got_error *err;
9242 struct got_commit_object *commit = NULL;
9243 struct got_object_id *id = NULL;
9244 struct got_reflist_head refs;
9245 struct got_reflist_entry *re, *re_match;
9246 FILE *f = NULL;
9247 char *uuidstr = NULL;
9248 int added_logmsg = 0;
9250 TAILQ_INIT(&refs);
9252 *logmsg_path = NULL;
9254 err = got_worktree_get_uuid(&uuidstr, worktree);
9255 if (err)
9256 goto done;
9258 err = got_ref_list(&refs, repo, "refs/got/worktree",
9259 got_ref_cmp_by_name, repo);
9260 if (err)
9261 goto done;
9263 TAILQ_FOREACH(re, &refs, entry) {
9264 const char *refname, *type;
9265 struct wt_commitable_path_arg wcpa;
9266 int add_logmsg = 0;
9268 refname = got_ref_get_name(re->ref);
9270 if (strncmp(refname, GOT_WORKTREE_CHERRYPICK_REF_PREFIX,
9271 GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN) == 0) {
9272 refname += GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN + 1;
9273 type = "cherrypicked";
9274 } else if (strncmp(refname, GOT_WORKTREE_BACKOUT_REF_PREFIX,
9275 GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN) == 0) {
9276 refname += GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN + 1;
9277 type = "backed-out";
9278 } else
9279 continue;
9281 if (strncmp(refname, uuidstr, GOT_WORKTREE_UUID_STRLEN) == 0)
9282 refname += GOT_WORKTREE_UUID_STRLEN + 1; /* skip '-' */
9283 else
9284 continue;
9286 err = got_repo_match_object_id(&id, NULL, refname,
9287 GOT_OBJ_TYPE_COMMIT, NULL, repo);
9288 if (err)
9289 goto done;
9291 err = got_object_open_as_commit(&commit, repo, id);
9292 if (err)
9293 goto done;
9295 wcpa.commit_paths = paths;
9296 wcpa.has_changes = &add_logmsg;
9298 err = commit_path_changed_in_worktree(&wcpa, id,
9299 worktree, repo);
9300 if (err)
9301 goto done;
9303 if (add_logmsg) {
9304 if (f == NULL) {
9305 err = got_opentemp_named(logmsg_path, &f,
9306 "got-commit-logmsg", "");
9307 if (err)
9308 goto done;
9310 err = cat_logmsg(f, commit, refname, type,
9311 added_logmsg);
9312 if (err)
9313 goto done;
9314 if (!added_logmsg)
9315 ++added_logmsg;
9317 err = got_reflist_entry_dup(&re_match, re);
9318 if (err)
9319 goto done;
9320 TAILQ_INSERT_HEAD(matched_refs, re_match, entry);
9323 got_object_commit_close(commit);
9324 commit = NULL;
9325 free(id);
9326 id = NULL;
9329 done:
9330 free(id);
9331 free(uuidstr);
9332 got_ref_list_free(&refs);
9333 if (commit)
9334 got_object_commit_close(commit);
9335 if (f && fclose(f) == EOF && err == NULL)
9336 err = got_error_from_errno("fclose");
9337 if (!added_logmsg) {
9338 if (*logmsg_path && unlink(*logmsg_path) != 0 && err == NULL)
9339 err = got_error_from_errno2("unlink", *logmsg_path);
9340 *logmsg_path = NULL;
9342 return err;
9345 static const struct got_error *
9346 cmd_commit(int argc, char *argv[])
9348 const struct got_error *error = NULL;
9349 struct got_worktree *worktree = NULL;
9350 struct got_repository *repo = NULL;
9351 char *cwd = NULL, *id_str = NULL;
9352 struct got_object_id *id = NULL;
9353 const char *logmsg = NULL;
9354 char *prepared_logmsg = NULL, *merged_logmsg = NULL;
9355 struct collect_commit_logmsg_arg cl_arg;
9356 const char *author = NULL;
9357 char *gitconfig_path = NULL, *editor = NULL, *committer = NULL;
9358 int ch, rebase_in_progress, histedit_in_progress, preserve_logmsg = 0;
9359 int allow_bad_symlinks = 0, non_interactive = 0, merge_in_progress = 0;
9360 int show_diff = 1, commit_conflicts = 0;
9361 struct got_pathlist_head paths;
9362 struct got_reflist_head refs;
9363 struct got_reflist_entry *re;
9364 int *pack_fds = NULL;
9366 TAILQ_INIT(&refs);
9367 TAILQ_INIT(&paths);
9368 cl_arg.logmsg_path = NULL;
9370 #ifndef PROFILE
9371 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
9372 "unveil", NULL) == -1)
9373 err(1, "pledge");
9374 #endif
9376 while ((ch = getopt(argc, argv, "A:CF:m:NnS")) != -1) {
9377 switch (ch) {
9378 case 'A':
9379 author = optarg;
9380 error = valid_author(author);
9381 if (error)
9382 return error;
9383 break;
9384 case 'C':
9385 commit_conflicts = 1;
9386 break;
9387 case 'F':
9388 if (logmsg != NULL)
9389 option_conflict('F', 'm');
9390 prepared_logmsg = realpath(optarg, NULL);
9391 if (prepared_logmsg == NULL)
9392 return got_error_from_errno2("realpath",
9393 optarg);
9394 break;
9395 case 'm':
9396 if (prepared_logmsg)
9397 option_conflict('m', 'F');
9398 logmsg = optarg;
9399 break;
9400 case 'N':
9401 non_interactive = 1;
9402 break;
9403 case 'n':
9404 show_diff = 0;
9405 break;
9406 case 'S':
9407 allow_bad_symlinks = 1;
9408 break;
9409 default:
9410 usage_commit();
9411 /* NOTREACHED */
9415 argc -= optind;
9416 argv += optind;
9418 cwd = getcwd(NULL, 0);
9419 if (cwd == NULL) {
9420 error = got_error_from_errno("getcwd");
9421 goto done;
9424 error = got_repo_pack_fds_open(&pack_fds);
9425 if (error != NULL)
9426 goto done;
9428 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
9429 if (error) {
9430 if (error->code == GOT_ERR_NOT_WORKTREE)
9431 error = wrap_not_worktree_error(error, "commit", cwd);
9432 goto done;
9435 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
9436 if (error)
9437 goto done;
9438 if (rebase_in_progress) {
9439 error = got_error(GOT_ERR_REBASING);
9440 goto done;
9443 error = got_worktree_histedit_in_progress(&histedit_in_progress,
9444 worktree);
9445 if (error)
9446 goto done;
9448 error = get_gitconfig_path(&gitconfig_path);
9449 if (error)
9450 goto done;
9451 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
9452 gitconfig_path, pack_fds);
9453 if (error != NULL)
9454 goto done;
9456 error = got_worktree_merge_in_progress(&merge_in_progress, worktree, repo);
9457 if (error)
9458 goto done;
9459 if (merge_in_progress) {
9460 error = got_error(GOT_ERR_MERGE_BUSY);
9461 goto done;
9464 error = get_author(&committer, repo, worktree);
9465 if (error)
9466 goto done;
9468 if (author == NULL)
9469 author = committer;
9471 if (logmsg == NULL || strlen(logmsg) == 0) {
9472 error = get_editor(&editor);
9473 if (error)
9474 goto done;
9475 if (unveil(editor, "x") != 0) {
9476 error = got_error_from_errno2("unveil", editor);
9477 goto done;
9480 if (prepared_logmsg) {
9481 if (unveil(prepared_logmsg, "r") != 0) {
9482 error = got_error_from_errno2("unveil",
9483 prepared_logmsg);
9484 goto done;
9488 error = apply_unveil(got_repo_get_path(repo), 0,
9489 got_worktree_get_root_path(worktree));
9490 if (error)
9491 goto done;
9493 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
9494 if (error)
9495 goto done;
9497 if (prepared_logmsg == NULL) {
9498 error = lookup_logmsg_ref(&merged_logmsg,
9499 argc > 0 ? &paths : NULL, &refs, worktree, repo);
9500 if (error)
9501 goto done;
9504 cl_arg.editor = editor;
9505 cl_arg.cmdline_log = logmsg;
9506 cl_arg.prepared_log = prepared_logmsg;
9507 cl_arg.merged_log = merged_logmsg;
9508 cl_arg.non_interactive = non_interactive;
9509 cl_arg.worktree_path = got_worktree_get_root_path(worktree);
9510 cl_arg.branch_name = got_worktree_get_head_ref_name(worktree);
9511 if (!histedit_in_progress) {
9512 if (strncmp(cl_arg.branch_name, "refs/heads/", 11) != 0) {
9513 error = got_error(GOT_ERR_COMMIT_BRANCH);
9514 goto done;
9516 cl_arg.branch_name += 11;
9518 cl_arg.repo_path = got_repo_get_path(repo);
9519 error = got_worktree_commit(&id, worktree, &paths, author, committer,
9520 allow_bad_symlinks, show_diff, commit_conflicts,
9521 collect_commit_logmsg, &cl_arg, print_status, NULL, repo);
9522 if (error) {
9523 if (error->code != GOT_ERR_COMMIT_MSG_EMPTY &&
9524 cl_arg.logmsg_path != NULL)
9525 preserve_logmsg = 1;
9526 goto done;
9529 error = got_object_id_str(&id_str, id);
9530 if (error)
9531 goto done;
9532 printf("Created commit %s\n", id_str);
9534 TAILQ_FOREACH(re, &refs, entry) {
9535 error = got_ref_delete(re->ref, repo);
9536 if (error)
9537 goto done;
9540 done:
9541 if (preserve_logmsg) {
9542 fprintf(stderr, "%s: log message preserved in %s\n",
9543 getprogname(), cl_arg.logmsg_path);
9544 } else if (cl_arg.logmsg_path && unlink(cl_arg.logmsg_path) == -1 &&
9545 error == NULL)
9546 error = got_error_from_errno2("unlink", cl_arg.logmsg_path);
9547 free(cl_arg.logmsg_path);
9548 if (merged_logmsg && unlink(merged_logmsg) == -1 && error == NULL)
9549 error = got_error_from_errno2("unlink", merged_logmsg);
9550 free(merged_logmsg);
9551 if (repo) {
9552 const struct got_error *close_err = got_repo_close(repo);
9553 if (error == NULL)
9554 error = close_err;
9556 if (worktree)
9557 got_worktree_close(worktree);
9558 if (pack_fds) {
9559 const struct got_error *pack_err =
9560 got_repo_pack_fds_close(pack_fds);
9561 if (error == NULL)
9562 error = pack_err;
9564 got_ref_list_free(&refs);
9565 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
9566 free(cwd);
9567 free(id_str);
9568 free(gitconfig_path);
9569 free(editor);
9570 free(committer);
9571 free(prepared_logmsg);
9572 return error;
9575 __dead static void
9576 usage_send(void)
9578 fprintf(stderr, "usage: %s send [-afqTv] [-b branch] [-d branch] "
9579 "[-r repository-path] [-t tag] [remote-repository]\n",
9580 getprogname());
9581 exit(1);
9584 static void
9585 print_load_info(int print_colored, int print_found, int print_trees,
9586 int ncolored, int nfound, int ntrees)
9588 if (print_colored) {
9589 printf("%d commit%s colored", ncolored,
9590 ncolored == 1 ? "" : "s");
9592 if (print_found) {
9593 printf("%s%d object%s found",
9594 ncolored > 0 ? "; " : "",
9595 nfound, nfound == 1 ? "" : "s");
9597 if (print_trees) {
9598 printf("; %d tree%s scanned", ntrees,
9599 ntrees == 1 ? "" : "s");
9603 struct got_send_progress_arg {
9604 char last_scaled_packsize[FMT_SCALED_STRSIZE];
9605 int verbosity;
9606 int last_ncolored;
9607 int last_nfound;
9608 int last_ntrees;
9609 int loading_done;
9610 int last_ncommits;
9611 int last_nobj_total;
9612 int last_p_deltify;
9613 int last_p_written;
9614 int last_p_sent;
9615 int printed_something;
9616 int sent_something;
9617 struct got_pathlist_head *delete_branches;
9620 static const struct got_error *
9621 send_progress(void *arg, int ncolored, int nfound, int ntrees,
9622 off_t packfile_size, int ncommits, int nobj_total, int nobj_deltify,
9623 int nobj_written, off_t bytes_sent, const char *refname,
9624 const char *errmsg, int success)
9626 struct got_send_progress_arg *a = arg;
9627 char scaled_packsize[FMT_SCALED_STRSIZE];
9628 char scaled_sent[FMT_SCALED_STRSIZE];
9629 int p_deltify = 0, p_written = 0, p_sent = 0;
9630 int print_colored = 0, print_found = 0, print_trees = 0;
9631 int print_searching = 0, print_total = 0;
9632 int print_deltify = 0, print_written = 0, print_sent = 0;
9634 if (a->verbosity < 0)
9635 return NULL;
9637 if (refname) {
9638 const char *status = success ? "accepted" : "rejected";
9640 if (success) {
9641 struct got_pathlist_entry *pe;
9642 TAILQ_FOREACH(pe, a->delete_branches, entry) {
9643 const char *branchname = pe->path;
9644 if (got_path_cmp(branchname, refname,
9645 strlen(branchname), strlen(refname)) == 0) {
9646 status = "deleted";
9647 a->sent_something = 1;
9648 break;
9653 if (a->printed_something)
9654 putchar('\n');
9655 printf("Server has %s %s", status, refname);
9656 if (errmsg)
9657 printf(": %s", errmsg);
9658 a->printed_something = 1;
9659 return NULL;
9662 if (a->last_ncolored != ncolored) {
9663 print_colored = 1;
9664 a->last_ncolored = ncolored;
9667 if (a->last_nfound != nfound) {
9668 print_colored = 1;
9669 print_found = 1;
9670 a->last_nfound = nfound;
9673 if (a->last_ntrees != ntrees) {
9674 print_colored = 1;
9675 print_found = 1;
9676 print_trees = 1;
9677 a->last_ntrees = ntrees;
9680 if ((print_colored || print_found || print_trees) &&
9681 !a->loading_done) {
9682 printf("\r");
9683 print_load_info(print_colored, print_found, print_trees,
9684 ncolored, nfound, ntrees);
9685 a->printed_something = 1;
9686 fflush(stdout);
9687 return NULL;
9688 } else if (!a->loading_done) {
9689 printf("\r");
9690 print_load_info(1, 1, 1, ncolored, nfound, ntrees);
9691 printf("\n");
9692 a->loading_done = 1;
9695 if (fmt_scaled(packfile_size, scaled_packsize) == -1)
9696 return got_error_from_errno("fmt_scaled");
9697 if (fmt_scaled(bytes_sent, scaled_sent) == -1)
9698 return got_error_from_errno("fmt_scaled");
9700 if (a->last_ncommits != ncommits) {
9701 print_searching = 1;
9702 a->last_ncommits = ncommits;
9705 if (a->last_nobj_total != nobj_total) {
9706 print_searching = 1;
9707 print_total = 1;
9708 a->last_nobj_total = nobj_total;
9711 if (packfile_size > 0 && (a->last_scaled_packsize[0] == '\0' ||
9712 strcmp(scaled_packsize, a->last_scaled_packsize)) != 0) {
9713 if (strlcpy(a->last_scaled_packsize, scaled_packsize,
9714 FMT_SCALED_STRSIZE) >= FMT_SCALED_STRSIZE)
9715 return got_error(GOT_ERR_NO_SPACE);
9718 if (nobj_deltify > 0 || nobj_written > 0) {
9719 if (nobj_deltify > 0) {
9720 p_deltify = (nobj_deltify * 100) / nobj_total;
9721 if (p_deltify != a->last_p_deltify) {
9722 a->last_p_deltify = p_deltify;
9723 print_searching = 1;
9724 print_total = 1;
9725 print_deltify = 1;
9728 if (nobj_written > 0) {
9729 p_written = (nobj_written * 100) / nobj_total;
9730 if (p_written != a->last_p_written) {
9731 a->last_p_written = p_written;
9732 print_searching = 1;
9733 print_total = 1;
9734 print_deltify = 1;
9735 print_written = 1;
9740 if (bytes_sent > 0) {
9741 p_sent = (bytes_sent * 100) / packfile_size;
9742 if (p_sent != a->last_p_sent) {
9743 a->last_p_sent = p_sent;
9744 print_searching = 1;
9745 print_total = 1;
9746 print_deltify = 1;
9747 print_written = 1;
9748 print_sent = 1;
9750 a->sent_something = 1;
9753 if (print_searching || print_total || print_deltify || print_written ||
9754 print_sent)
9755 printf("\r");
9756 if (print_searching)
9757 printf("packing %d reference%s", ncommits,
9758 ncommits == 1 ? "" : "s");
9759 if (print_total)
9760 printf("; %d object%s", nobj_total,
9761 nobj_total == 1 ? "" : "s");
9762 if (print_deltify)
9763 printf("; deltify: %d%%", p_deltify);
9764 if (print_sent)
9765 printf("; uploading pack: %*s %d%%", FMT_SCALED_STRSIZE - 2,
9766 scaled_packsize, p_sent);
9767 else if (print_written)
9768 printf("; writing pack: %*s %d%%", FMT_SCALED_STRSIZE - 2,
9769 scaled_packsize, p_written);
9770 if (print_searching || print_total || print_deltify ||
9771 print_written || print_sent) {
9772 a->printed_something = 1;
9773 fflush(stdout);
9775 return NULL;
9778 static const struct got_error *
9779 cmd_send(int argc, char *argv[])
9781 const struct got_error *error = NULL;
9782 char *cwd = NULL, *repo_path = NULL;
9783 const char *remote_name;
9784 char *proto = NULL, *host = NULL, *port = NULL;
9785 char *repo_name = NULL, *server_path = NULL;
9786 const struct got_remote_repo *remotes;
9787 struct got_remote_repo *remote = NULL;
9788 int nremotes, nbranches = 0, ndelete_branches = 0;
9789 struct got_repository *repo = NULL;
9790 struct got_worktree *worktree = NULL;
9791 const struct got_gotconfig *repo_conf = NULL, *worktree_conf = NULL;
9792 struct got_pathlist_head branches;
9793 struct got_pathlist_head tags;
9794 struct got_reflist_head all_branches;
9795 struct got_reflist_head all_tags;
9796 struct got_pathlist_head delete_args;
9797 struct got_pathlist_head delete_branches;
9798 struct got_reflist_entry *re;
9799 struct got_pathlist_entry *pe;
9800 int i, ch, sendfd = -1, sendstatus;
9801 pid_t sendpid = -1;
9802 struct got_send_progress_arg spa;
9803 int verbosity = 0, overwrite_refs = 0;
9804 int send_all_branches = 0, send_all_tags = 0;
9805 struct got_reference *ref = NULL;
9806 int *pack_fds = NULL;
9808 TAILQ_INIT(&branches);
9809 TAILQ_INIT(&tags);
9810 TAILQ_INIT(&all_branches);
9811 TAILQ_INIT(&all_tags);
9812 TAILQ_INIT(&delete_args);
9813 TAILQ_INIT(&delete_branches);
9815 while ((ch = getopt(argc, argv, "ab:d:fqr:Tt:v")) != -1) {
9816 switch (ch) {
9817 case 'a':
9818 send_all_branches = 1;
9819 break;
9820 case 'b':
9821 error = got_pathlist_append(&branches, optarg, NULL);
9822 if (error)
9823 return error;
9824 nbranches++;
9825 break;
9826 case 'd':
9827 error = got_pathlist_append(&delete_args, optarg, NULL);
9828 if (error)
9829 return error;
9830 break;
9831 case 'f':
9832 overwrite_refs = 1;
9833 break;
9834 case 'q':
9835 verbosity = -1;
9836 break;
9837 case 'r':
9838 repo_path = realpath(optarg, NULL);
9839 if (repo_path == NULL)
9840 return got_error_from_errno2("realpath",
9841 optarg);
9842 got_path_strip_trailing_slashes(repo_path);
9843 break;
9844 case 'T':
9845 send_all_tags = 1;
9846 break;
9847 case 't':
9848 error = got_pathlist_append(&tags, optarg, NULL);
9849 if (error)
9850 return error;
9851 break;
9852 case 'v':
9853 if (verbosity < 0)
9854 verbosity = 0;
9855 else if (verbosity < 3)
9856 verbosity++;
9857 break;
9858 default:
9859 usage_send();
9860 /* NOTREACHED */
9863 argc -= optind;
9864 argv += optind;
9866 if (send_all_branches && !TAILQ_EMPTY(&branches))
9867 option_conflict('a', 'b');
9868 if (send_all_tags && !TAILQ_EMPTY(&tags))
9869 option_conflict('T', 't');
9872 if (argc == 0)
9873 remote_name = GOT_SEND_DEFAULT_REMOTE_NAME;
9874 else if (argc == 1)
9875 remote_name = argv[0];
9876 else
9877 usage_send();
9879 cwd = getcwd(NULL, 0);
9880 if (cwd == NULL) {
9881 error = got_error_from_errno("getcwd");
9882 goto done;
9885 error = got_repo_pack_fds_open(&pack_fds);
9886 if (error != NULL)
9887 goto done;
9889 if (repo_path == NULL) {
9890 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
9891 if (error && error->code != GOT_ERR_NOT_WORKTREE)
9892 goto done;
9893 else
9894 error = NULL;
9895 if (worktree) {
9896 repo_path =
9897 strdup(got_worktree_get_repo_path(worktree));
9898 if (repo_path == NULL)
9899 error = got_error_from_errno("strdup");
9900 if (error)
9901 goto done;
9902 } else {
9903 repo_path = strdup(cwd);
9904 if (repo_path == NULL) {
9905 error = got_error_from_errno("strdup");
9906 goto done;
9911 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
9912 if (error)
9913 goto done;
9915 if (worktree) {
9916 worktree_conf = got_worktree_get_gotconfig(worktree);
9917 if (worktree_conf) {
9918 got_gotconfig_get_remotes(&nremotes, &remotes,
9919 worktree_conf);
9920 for (i = 0; i < nremotes; i++) {
9921 if (strcmp(remotes[i].name, remote_name) == 0) {
9922 error = got_repo_remote_repo_dup(&remote,
9923 &remotes[i]);
9924 if (error)
9925 goto done;
9926 break;
9931 if (remote == NULL) {
9932 repo_conf = got_repo_get_gotconfig(repo);
9933 if (repo_conf) {
9934 got_gotconfig_get_remotes(&nremotes, &remotes,
9935 repo_conf);
9936 for (i = 0; i < nremotes; i++) {
9937 if (strcmp(remotes[i].name, remote_name) == 0) {
9938 error = got_repo_remote_repo_dup(&remote,
9939 &remotes[i]);
9940 if (error)
9941 goto done;
9942 break;
9947 if (remote == NULL) {
9948 got_repo_get_gitconfig_remotes(&nremotes, &remotes, repo);
9949 for (i = 0; i < nremotes; i++) {
9950 if (strcmp(remotes[i].name, remote_name) == 0) {
9951 error = got_repo_remote_repo_dup(&remote,
9952 &remotes[i]);
9953 if (error)
9954 goto done;
9955 break;
9959 if (remote == NULL) {
9960 error = got_error_path(remote_name, GOT_ERR_NO_REMOTE);
9961 goto done;
9964 error = got_dial_parse_uri(&proto, &host, &port, &server_path,
9965 &repo_name, remote->send_url);
9966 if (error)
9967 goto done;
9969 if (strcmp(proto, "git") == 0) {
9970 #ifndef PROFILE
9971 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
9972 "sendfd dns inet unveil", NULL) == -1)
9973 err(1, "pledge");
9974 #endif
9975 } else if (strcmp(proto, "git+ssh") == 0 ||
9976 strcmp(proto, "ssh") == 0) {
9977 #ifndef PROFILE
9978 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
9979 "sendfd unveil", NULL) == -1)
9980 err(1, "pledge");
9981 #endif
9982 } else if (strcmp(proto, "http") == 0 ||
9983 strcmp(proto, "git+http") == 0) {
9984 error = got_error_path(proto, GOT_ERR_NOT_IMPL);
9985 goto done;
9986 } else {
9987 error = got_error_path(proto, GOT_ERR_BAD_PROTO);
9988 goto done;
9991 error = got_dial_apply_unveil(proto);
9992 if (error)
9993 goto done;
9995 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
9996 if (error)
9997 goto done;
9999 if (send_all_branches) {
10000 error = got_ref_list(&all_branches, repo, "refs/heads",
10001 got_ref_cmp_by_name, NULL);
10002 if (error)
10003 goto done;
10004 TAILQ_FOREACH(re, &all_branches, entry) {
10005 const char *branchname = got_ref_get_name(re->ref);
10006 error = got_pathlist_append(&branches,
10007 branchname, NULL);
10008 if (error)
10009 goto done;
10010 nbranches++;
10012 } else if (nbranches == 0) {
10013 for (i = 0; i < remote->nsend_branches; i++) {
10014 error = got_pathlist_append(&branches,
10015 remote->send_branches[i], NULL);
10016 if (error)
10017 goto done;
10021 if (send_all_tags) {
10022 error = got_ref_list(&all_tags, repo, "refs/tags",
10023 got_ref_cmp_by_name, NULL);
10024 if (error)
10025 goto done;
10026 TAILQ_FOREACH(re, &all_tags, entry) {
10027 const char *tagname = got_ref_get_name(re->ref);
10028 error = got_pathlist_append(&tags,
10029 tagname, NULL);
10030 if (error)
10031 goto done;
10036 * To prevent accidents only branches in refs/heads/ can be deleted
10037 * with 'got send -d'.
10038 * Deleting anything else requires local repository access or Git.
10040 TAILQ_FOREACH(pe, &delete_args, entry) {
10041 const char *branchname = pe->path;
10042 char *s;
10043 struct got_pathlist_entry *new;
10044 if (strncmp(branchname, "refs/heads/", 11) == 0) {
10045 s = strdup(branchname);
10046 if (s == NULL) {
10047 error = got_error_from_errno("strdup");
10048 goto done;
10050 } else {
10051 if (asprintf(&s, "refs/heads/%s", branchname) == -1) {
10052 error = got_error_from_errno("asprintf");
10053 goto done;
10056 error = got_pathlist_insert(&new, &delete_branches, s, NULL);
10057 if (error || new == NULL /* duplicate */)
10058 free(s);
10059 if (error)
10060 goto done;
10061 ndelete_branches++;
10064 if (nbranches == 0 && ndelete_branches == 0) {
10065 struct got_reference *head_ref;
10066 if (worktree)
10067 error = got_ref_open(&head_ref, repo,
10068 got_worktree_get_head_ref_name(worktree), 0);
10069 else
10070 error = got_ref_open(&head_ref, repo, GOT_REF_HEAD, 0);
10071 if (error)
10072 goto done;
10073 if (got_ref_is_symbolic(head_ref)) {
10074 error = got_ref_resolve_symbolic(&ref, repo, head_ref);
10075 got_ref_close(head_ref);
10076 if (error)
10077 goto done;
10078 } else
10079 ref = head_ref;
10080 error = got_pathlist_append(&branches, got_ref_get_name(ref),
10081 NULL);
10082 if (error)
10083 goto done;
10084 nbranches++;
10087 if (worktree) {
10088 /* Release work tree lock. */
10089 got_worktree_close(worktree);
10090 worktree = NULL;
10093 if (verbosity >= 0) {
10094 printf("Connecting to \"%s\" %s://%s%s%s%s%s\n",
10095 remote->name, proto, host,
10096 port ? ":" : "", port ? port : "",
10097 *server_path == '/' ? "" : "/", server_path);
10100 error = got_send_connect(&sendpid, &sendfd, proto, host, port,
10101 server_path, verbosity);
10102 if (error)
10103 goto done;
10105 memset(&spa, 0, sizeof(spa));
10106 spa.last_scaled_packsize[0] = '\0';
10107 spa.last_p_deltify = -1;
10108 spa.last_p_written = -1;
10109 spa.verbosity = verbosity;
10110 spa.delete_branches = &delete_branches;
10111 error = got_send_pack(remote_name, &branches, &tags, &delete_branches,
10112 verbosity, overwrite_refs, sendfd, repo, send_progress, &spa,
10113 check_cancelled, NULL);
10114 if (spa.printed_something)
10115 putchar('\n');
10116 if (error)
10117 goto done;
10118 if (!spa.sent_something && verbosity >= 0)
10119 printf("Already up-to-date\n");
10120 done:
10121 if (sendpid > 0) {
10122 if (kill(sendpid, SIGTERM) == -1)
10123 error = got_error_from_errno("kill");
10124 if (waitpid(sendpid, &sendstatus, 0) == -1 && error == NULL)
10125 error = got_error_from_errno("waitpid");
10127 if (sendfd != -1 && close(sendfd) == -1 && error == NULL)
10128 error = got_error_from_errno("close");
10129 if (repo) {
10130 const struct got_error *close_err = got_repo_close(repo);
10131 if (error == NULL)
10132 error = close_err;
10134 if (worktree)
10135 got_worktree_close(worktree);
10136 if (pack_fds) {
10137 const struct got_error *pack_err =
10138 got_repo_pack_fds_close(pack_fds);
10139 if (error == NULL)
10140 error = pack_err;
10142 if (ref)
10143 got_ref_close(ref);
10144 got_repo_free_remote_repo_data(remote);
10145 free(remote);
10146 got_pathlist_free(&branches, GOT_PATHLIST_FREE_NONE);
10147 got_pathlist_free(&tags, GOT_PATHLIST_FREE_NONE);
10148 got_ref_list_free(&all_branches);
10149 got_ref_list_free(&all_tags);
10150 got_pathlist_free(&delete_args, GOT_PATHLIST_FREE_NONE);
10151 got_pathlist_free(&delete_branches, GOT_PATHLIST_FREE_PATH);
10152 free(cwd);
10153 free(repo_path);
10154 free(proto);
10155 free(host);
10156 free(port);
10157 free(server_path);
10158 free(repo_name);
10159 return error;
10163 * Print and if delete is set delete all ref_prefix references.
10164 * If wanted_ref is not NULL, only print or delete this reference.
10166 static const struct got_error *
10167 process_logmsg_refs(const char *ref_prefix, size_t prefix_len,
10168 const char *wanted_ref, int delete, struct got_worktree *worktree,
10169 struct got_repository *repo)
10171 const struct got_error *err;
10172 struct got_pathlist_head paths;
10173 struct got_reflist_head refs;
10174 struct got_reflist_entry *re;
10175 struct got_reflist_object_id_map *refs_idmap = NULL;
10176 struct got_commit_object *commit = NULL;
10177 struct got_object_id *id = NULL;
10178 const char *header_prefix;
10179 char *uuidstr = NULL;
10180 int found = 0;
10182 TAILQ_INIT(&refs);
10183 TAILQ_INIT(&paths);
10185 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, repo);
10186 if (err)
10187 goto done;
10189 err = got_reflist_object_id_map_create(&refs_idmap, &refs, repo);
10190 if (err)
10191 goto done;
10193 if (worktree != NULL) {
10194 err = got_worktree_get_uuid(&uuidstr, worktree);
10195 if (err)
10196 goto done;
10199 if (wanted_ref) {
10200 if (strncmp(wanted_ref, "refs/heads/", 11) == 0)
10201 wanted_ref += 11;
10204 if (strcmp(ref_prefix, GOT_WORKTREE_BACKOUT_REF_PREFIX) == 0)
10205 header_prefix = "backout";
10206 else
10207 header_prefix = "cherrypick";
10209 TAILQ_FOREACH(re, &refs, entry) {
10210 const char *refname, *wt;
10212 refname = got_ref_get_name(re->ref);
10214 err = check_cancelled(NULL);
10215 if (err)
10216 goto done;
10218 if (strncmp(refname, ref_prefix, prefix_len) == 0)
10219 refname += prefix_len + 1; /* skip '-' delimiter */
10220 else
10221 continue;
10223 wt = refname;
10225 if (worktree == NULL || strncmp(refname, uuidstr,
10226 GOT_WORKTREE_UUID_STRLEN) == 0)
10227 refname += GOT_WORKTREE_UUID_STRLEN + 1; /* skip '-' */
10228 else
10229 continue;
10231 err = got_repo_match_object_id(&id, NULL, refname,
10232 GOT_OBJ_TYPE_COMMIT, NULL, repo);
10233 if (err)
10234 goto done;
10236 err = got_object_open_as_commit(&commit, repo, id);
10237 if (err)
10238 goto done;
10240 if (wanted_ref)
10241 found = strncmp(wanted_ref, refname,
10242 strlen(wanted_ref)) == 0;
10243 if (wanted_ref && !found) {
10244 struct got_reflist_head *ci_refs;
10246 ci_refs = got_reflist_object_id_map_lookup(refs_idmap,
10247 id);
10249 if (ci_refs) {
10250 char *refs_str = NULL;
10251 char const *r = NULL;
10253 err = build_refs_str(&refs_str, ci_refs, id,
10254 repo, 1);
10255 if (err)
10256 goto done;
10258 r = refs_str;
10259 while (r) {
10260 if (strncmp(r, wanted_ref,
10261 strlen(wanted_ref)) == 0) {
10262 found = 1;
10263 break;
10265 r = strchr(r, ' ');
10266 if (r)
10267 ++r;
10269 free(refs_str);
10273 if (wanted_ref == NULL || found) {
10274 if (delete) {
10275 err = got_ref_delete(re->ref, repo);
10276 if (err)
10277 goto done;
10278 printf("Deleted: ");
10279 err = print_commit_oneline(commit, id, repo,
10280 refs_idmap);
10281 } else {
10283 * Print paths modified by commit to help
10284 * associate commits with worktree changes.
10286 err = get_changed_paths(&paths, commit,
10287 repo, NULL);
10288 if (err)
10289 goto done;
10291 err = print_commit(commit, id, repo, NULL,
10292 &paths, NULL, 0, 0, refs_idmap, NULL,
10293 header_prefix);
10294 got_pathlist_free(&paths,
10295 GOT_PATHLIST_FREE_ALL);
10297 if (worktree == NULL)
10298 printf("work tree: %.*s\n\n",
10299 GOT_WORKTREE_UUID_STRLEN, wt);
10301 if (err || found)
10302 goto done;
10305 got_object_commit_close(commit);
10306 commit = NULL;
10307 free(id);
10308 id = NULL;
10311 if (wanted_ref != NULL && !found)
10312 err = got_error_fmt(GOT_ERR_NOT_REF, "%s", wanted_ref);
10314 done:
10315 free(id);
10316 free(uuidstr);
10317 got_ref_list_free(&refs);
10318 got_pathlist_free(&paths, GOT_PATHLIST_FREE_ALL);
10319 if (refs_idmap)
10320 got_reflist_object_id_map_free(refs_idmap);
10321 if (commit)
10322 got_object_commit_close(commit);
10323 return err;
10327 * Create new temp "logmsg" ref of the backed-out or cherrypicked commit
10328 * identified by id for log messages to prepopulate the editor on commit.
10330 static const struct got_error *
10331 logmsg_ref(struct got_object_id *id, const char *prefix,
10332 struct got_worktree *worktree, struct got_repository *repo)
10334 const struct got_error *err = NULL;
10335 char *idstr, *ref = NULL, *refname = NULL;
10336 int histedit_in_progress;
10337 int rebase_in_progress, merge_in_progress;
10340 * Silenty refuse to create merge reference if any histedit, merge,
10341 * or rebase operation is in progress.
10343 err = got_worktree_histedit_in_progress(&histedit_in_progress,
10344 worktree);
10345 if (err)
10346 return err;
10347 if (histedit_in_progress)
10348 return NULL;
10350 err = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
10351 if (err)
10352 return err;
10353 if (rebase_in_progress)
10354 return NULL;
10356 err = got_worktree_merge_in_progress(&merge_in_progress, worktree,
10357 repo);
10358 if (err)
10359 return err;
10360 if (merge_in_progress)
10361 return NULL;
10363 err = got_object_id_str(&idstr, id);
10364 if (err)
10365 return err;
10367 err = got_worktree_get_logmsg_ref_name(&refname, worktree, prefix);
10368 if (err)
10369 goto done;
10371 if (asprintf(&ref, "%s-%s", refname, idstr) == -1) {
10372 err = got_error_from_errno("asprintf");
10373 goto done;
10376 err = create_ref(ref, got_worktree_get_base_commit_id(worktree),
10377 -1, repo);
10378 done:
10379 free(ref);
10380 free(idstr);
10381 free(refname);
10382 return err;
10385 __dead static void
10386 usage_cherrypick(void)
10388 fprintf(stderr, "usage: %s cherrypick [-lX] [commit-id]\n",
10389 getprogname());
10390 exit(1);
10393 static const struct got_error *
10394 cmd_cherrypick(int argc, char *argv[])
10396 const struct got_error *error = NULL;
10397 struct got_worktree *worktree = NULL;
10398 struct got_repository *repo = NULL;
10399 char *cwd = NULL, *commit_id_str = NULL, *keyword_idstr = NULL;
10400 struct got_object_id *commit_id = NULL;
10401 struct got_commit_object *commit = NULL;
10402 struct got_object_qid *pid;
10403 int ch, list_refs = 0, remove_refs = 0;
10404 struct got_update_progress_arg upa;
10405 int *pack_fds = NULL;
10407 #ifndef PROFILE
10408 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
10409 "unveil", NULL) == -1)
10410 err(1, "pledge");
10411 #endif
10413 while ((ch = getopt(argc, argv, "lX")) != -1) {
10414 switch (ch) {
10415 case 'l':
10416 list_refs = 1;
10417 break;
10418 case 'X':
10419 remove_refs = 1;
10420 break;
10421 default:
10422 usage_cherrypick();
10423 /* NOTREACHED */
10427 argc -= optind;
10428 argv += optind;
10430 if (list_refs || remove_refs) {
10431 if (argc != 0 && argc != 1)
10432 usage_cherrypick();
10433 } else if (argc != 1)
10434 usage_cherrypick();
10435 if (list_refs && remove_refs)
10436 option_conflict('l', 'X');
10438 cwd = getcwd(NULL, 0);
10439 if (cwd == NULL) {
10440 error = got_error_from_errno("getcwd");
10441 goto done;
10444 error = got_repo_pack_fds_open(&pack_fds);
10445 if (error != NULL)
10446 goto done;
10448 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
10449 if (error) {
10450 if (list_refs || remove_refs) {
10451 if (error->code != GOT_ERR_NOT_WORKTREE)
10452 goto done;
10453 } else {
10454 if (error->code == GOT_ERR_NOT_WORKTREE)
10455 error = wrap_not_worktree_error(error,
10456 "cherrypick", cwd);
10457 goto done;
10461 error = got_repo_open(&repo,
10462 worktree ? got_worktree_get_repo_path(worktree) : cwd,
10463 NULL, pack_fds);
10464 if (error != NULL)
10465 goto done;
10467 error = apply_unveil(got_repo_get_path(repo), 0,
10468 worktree ? got_worktree_get_root_path(worktree) : NULL);
10469 if (error)
10470 goto done;
10472 if (list_refs || remove_refs) {
10473 error = process_logmsg_refs(GOT_WORKTREE_CHERRYPICK_REF_PREFIX,
10474 GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN,
10475 argc == 1 ? argv[0] : NULL, remove_refs, worktree, repo);
10476 goto done;
10479 error = got_keyword_to_idstr(&keyword_idstr, argv[0], repo, worktree);
10480 if (error != NULL)
10481 goto done;
10483 error = got_repo_match_object_id(&commit_id, NULL,
10484 keyword_idstr != NULL ? keyword_idstr : argv[0],
10485 GOT_OBJ_TYPE_COMMIT, NULL, repo);
10486 if (error)
10487 goto done;
10488 error = got_object_id_str(&commit_id_str, commit_id);
10489 if (error)
10490 goto done;
10492 error = got_object_open_as_commit(&commit, repo, commit_id);
10493 if (error)
10494 goto done;
10495 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
10496 memset(&upa, 0, sizeof(upa));
10497 error = got_worktree_merge_files(worktree, pid ? &pid->id : NULL,
10498 commit_id, repo, update_progress, &upa, check_cancelled,
10499 NULL);
10500 if (error != NULL)
10501 goto done;
10503 if (upa.did_something) {
10504 error = logmsg_ref(commit_id,
10505 GOT_WORKTREE_CHERRYPICK_REF_PREFIX, worktree, repo);
10506 if (error)
10507 goto done;
10508 printf("Merged commit %s\n", commit_id_str);
10510 print_merge_progress_stats(&upa);
10511 done:
10512 free(cwd);
10513 free(keyword_idstr);
10514 if (commit)
10515 got_object_commit_close(commit);
10516 free(commit_id_str);
10517 if (worktree)
10518 got_worktree_close(worktree);
10519 if (repo) {
10520 const struct got_error *close_err = got_repo_close(repo);
10521 if (error == NULL)
10522 error = close_err;
10524 if (pack_fds) {
10525 const struct got_error *pack_err =
10526 got_repo_pack_fds_close(pack_fds);
10527 if (error == NULL)
10528 error = pack_err;
10531 return error;
10534 __dead static void
10535 usage_backout(void)
10537 fprintf(stderr, "usage: %s backout [-lX] [commit-id]\n", getprogname());
10538 exit(1);
10541 static const struct got_error *
10542 cmd_backout(int argc, char *argv[])
10544 const struct got_error *error = NULL;
10545 struct got_worktree *worktree = NULL;
10546 struct got_repository *repo = NULL;
10547 char *cwd = NULL, *commit_id_str = NULL, *keyword_idstr = NULL;
10548 struct got_object_id *commit_id = NULL;
10549 struct got_commit_object *commit = NULL;
10550 struct got_object_qid *pid;
10551 int ch, list_refs = 0, remove_refs = 0;
10552 struct got_update_progress_arg upa;
10553 int *pack_fds = NULL;
10555 #ifndef PROFILE
10556 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
10557 "unveil", NULL) == -1)
10558 err(1, "pledge");
10559 #endif
10561 while ((ch = getopt(argc, argv, "lX")) != -1) {
10562 switch (ch) {
10563 case 'l':
10564 list_refs = 1;
10565 break;
10566 case 'X':
10567 remove_refs = 1;
10568 break;
10569 default:
10570 usage_backout();
10571 /* NOTREACHED */
10575 argc -= optind;
10576 argv += optind;
10578 if (list_refs || remove_refs) {
10579 if (argc != 0 && argc != 1)
10580 usage_backout();
10581 } else if (argc != 1)
10582 usage_backout();
10583 if (list_refs && remove_refs)
10584 option_conflict('l', 'X');
10586 cwd = getcwd(NULL, 0);
10587 if (cwd == NULL) {
10588 error = got_error_from_errno("getcwd");
10589 goto done;
10592 error = got_repo_pack_fds_open(&pack_fds);
10593 if (error != NULL)
10594 goto done;
10596 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
10597 if (error) {
10598 if (list_refs || remove_refs) {
10599 if (error->code != GOT_ERR_NOT_WORKTREE)
10600 goto done;
10601 } else {
10602 if (error->code == GOT_ERR_NOT_WORKTREE)
10603 error = wrap_not_worktree_error(error,
10604 "backout", cwd);
10605 goto done;
10609 error = got_repo_open(&repo,
10610 worktree ? got_worktree_get_repo_path(worktree) : cwd,
10611 NULL, pack_fds);
10612 if (error != NULL)
10613 goto done;
10615 error = apply_unveil(got_repo_get_path(repo), 0,
10616 worktree ? got_worktree_get_root_path(worktree) : NULL);
10617 if (error)
10618 goto done;
10620 if (list_refs || remove_refs) {
10621 error = process_logmsg_refs(GOT_WORKTREE_BACKOUT_REF_PREFIX,
10622 GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN,
10623 argc == 1 ? argv[0] : NULL, remove_refs, worktree, repo);
10624 goto done;
10627 error = got_keyword_to_idstr(&keyword_idstr, argv[0], repo, worktree);
10628 if (error != NULL)
10629 goto done;
10631 error = got_repo_match_object_id(&commit_id, NULL,
10632 keyword_idstr != NULL ? keyword_idstr : argv[0],
10633 GOT_OBJ_TYPE_COMMIT, NULL, repo);
10634 if (error)
10635 goto done;
10636 error = got_object_id_str(&commit_id_str, commit_id);
10637 if (error)
10638 goto done;
10640 error = got_object_open_as_commit(&commit, repo, commit_id);
10641 if (error)
10642 goto done;
10643 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
10644 if (pid == NULL) {
10645 error = got_error(GOT_ERR_ROOT_COMMIT);
10646 goto done;
10649 memset(&upa, 0, sizeof(upa));
10650 error = got_worktree_merge_files(worktree, commit_id, &pid->id,
10651 repo, update_progress, &upa, check_cancelled, NULL);
10652 if (error != NULL)
10653 goto done;
10655 if (upa.did_something) {
10656 error = logmsg_ref(commit_id, GOT_WORKTREE_BACKOUT_REF_PREFIX,
10657 worktree, repo);
10658 if (error)
10659 goto done;
10660 printf("Backed out commit %s\n", commit_id_str);
10662 print_merge_progress_stats(&upa);
10663 done:
10664 free(cwd);
10665 free(keyword_idstr);
10666 if (commit)
10667 got_object_commit_close(commit);
10668 free(commit_id_str);
10669 if (worktree)
10670 got_worktree_close(worktree);
10671 if (repo) {
10672 const struct got_error *close_err = got_repo_close(repo);
10673 if (error == NULL)
10674 error = close_err;
10676 if (pack_fds) {
10677 const struct got_error *pack_err =
10678 got_repo_pack_fds_close(pack_fds);
10679 if (error == NULL)
10680 error = pack_err;
10682 return error;
10685 __dead static void
10686 usage_rebase(void)
10688 fprintf(stderr, "usage: %s rebase [-aCclX] [branch]\n", getprogname());
10689 exit(1);
10692 static void
10693 trim_logmsg(char *logmsg, int limit)
10695 char *nl;
10696 size_t len;
10698 len = strlen(logmsg);
10699 if (len > limit)
10700 len = limit;
10701 logmsg[len] = '\0';
10702 nl = strchr(logmsg, '\n');
10703 if (nl)
10704 *nl = '\0';
10707 static const struct got_error *
10708 get_short_logmsg(char **logmsg, int limit, struct got_commit_object *commit)
10710 const struct got_error *err;
10711 char *logmsg0 = NULL;
10712 const char *s;
10714 err = got_object_commit_get_logmsg(&logmsg0, commit);
10715 if (err)
10716 return err;
10718 s = logmsg0;
10719 while (isspace((unsigned char)s[0]))
10720 s++;
10722 *logmsg = strdup(s);
10723 if (*logmsg == NULL) {
10724 err = got_error_from_errno("strdup");
10725 goto done;
10728 trim_logmsg(*logmsg, limit);
10729 done:
10730 free(logmsg0);
10731 return err;
10734 static const struct got_error *
10735 show_rebase_merge_conflict(struct got_object_id *id,
10736 struct got_repository *repo)
10738 const struct got_error *err;
10739 struct got_commit_object *commit = NULL;
10740 char *id_str = NULL, *logmsg = NULL;
10742 err = got_object_open_as_commit(&commit, repo, id);
10743 if (err)
10744 return err;
10746 err = got_object_id_str(&id_str, id);
10747 if (err)
10748 goto done;
10750 id_str[12] = '\0';
10752 err = get_short_logmsg(&logmsg, 42, commit);
10753 if (err)
10754 goto done;
10756 printf("%s -> merge conflict: %s\n", id_str, logmsg);
10757 done:
10758 free(id_str);
10759 got_object_commit_close(commit);
10760 free(logmsg);
10761 return err;
10764 static const struct got_error *
10765 show_rebase_progress(struct got_commit_object *commit,
10766 struct got_object_id *old_id, struct got_object_id *new_id)
10768 const struct got_error *err;
10769 char *old_id_str = NULL, *new_id_str = NULL, *logmsg = NULL;
10771 err = got_object_id_str(&old_id_str, old_id);
10772 if (err)
10773 goto done;
10775 if (new_id) {
10776 err = got_object_id_str(&new_id_str, new_id);
10777 if (err)
10778 goto done;
10781 old_id_str[12] = '\0';
10782 if (new_id_str)
10783 new_id_str[12] = '\0';
10785 err = get_short_logmsg(&logmsg, 42, commit);
10786 if (err)
10787 goto done;
10789 printf("%s -> %s: %s\n", old_id_str,
10790 new_id_str ? new_id_str : "no-op change", logmsg);
10791 done:
10792 free(old_id_str);
10793 free(new_id_str);
10794 free(logmsg);
10795 return err;
10798 static const struct got_error *
10799 rebase_complete(struct got_worktree *worktree, struct got_fileindex *fileindex,
10800 struct got_reference *branch, struct got_reference *tmp_branch,
10801 struct got_repository *repo, int create_backup)
10803 printf("Switching work tree to %s\n", got_ref_get_name(branch));
10804 return got_worktree_rebase_complete(worktree, fileindex,
10805 tmp_branch, branch, repo, create_backup);
10808 static const struct got_error *
10809 rebase_commit(struct got_pathlist_head *merged_paths,
10810 struct got_worktree *worktree, struct got_fileindex *fileindex,
10811 struct got_reference *tmp_branch, const char *committer,
10812 struct got_object_id *commit_id, int allow_conflict,
10813 struct got_repository *repo)
10815 const struct got_error *error;
10816 struct got_commit_object *commit;
10817 struct got_object_id *new_commit_id;
10819 error = got_object_open_as_commit(&commit, repo, commit_id);
10820 if (error)
10821 return error;
10823 error = got_worktree_rebase_commit(&new_commit_id, merged_paths,
10824 worktree, fileindex, tmp_branch, committer, commit, commit_id,
10825 allow_conflict, repo);
10826 if (error) {
10827 if (error->code != GOT_ERR_COMMIT_NO_CHANGES)
10828 goto done;
10829 error = show_rebase_progress(commit, commit_id, NULL);
10830 } else {
10831 error = show_rebase_progress(commit, commit_id, new_commit_id);
10832 free(new_commit_id);
10834 done:
10835 got_object_commit_close(commit);
10836 return error;
10839 struct check_path_prefix_arg {
10840 const char *path_prefix;
10841 size_t len;
10842 int errcode;
10845 static const struct got_error *
10846 check_path_prefix_in_diff(void *arg, struct got_blob_object *blob1,
10847 struct got_blob_object *blob2, FILE *f1, FILE *f2,
10848 struct got_object_id *id1, struct got_object_id *id2,
10849 const char *path1, const char *path2,
10850 mode_t mode1, mode_t mode2, struct got_repository *repo)
10852 struct check_path_prefix_arg *a = arg;
10854 if ((path1 && !got_path_is_child(path1, a->path_prefix, a->len)) ||
10855 (path2 && !got_path_is_child(path2, a->path_prefix, a->len)))
10856 return got_error(a->errcode);
10858 return NULL;
10861 static const struct got_error *
10862 check_path_prefix(struct got_object_id *parent_id,
10863 struct got_object_id *commit_id, const char *path_prefix,
10864 int errcode, struct got_repository *repo)
10866 const struct got_error *err;
10867 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
10868 struct got_commit_object *commit = NULL, *parent_commit = NULL;
10869 struct check_path_prefix_arg cpp_arg;
10871 if (got_path_is_root_dir(path_prefix))
10872 return NULL;
10874 err = got_object_open_as_commit(&commit, repo, commit_id);
10875 if (err)
10876 goto done;
10878 err = got_object_open_as_commit(&parent_commit, repo, parent_id);
10879 if (err)
10880 goto done;
10882 err = got_object_open_as_tree(&tree1, repo,
10883 got_object_commit_get_tree_id(parent_commit));
10884 if (err)
10885 goto done;
10887 err = got_object_open_as_tree(&tree2, repo,
10888 got_object_commit_get_tree_id(commit));
10889 if (err)
10890 goto done;
10892 cpp_arg.path_prefix = path_prefix;
10893 while (cpp_arg.path_prefix[0] == '/')
10894 cpp_arg.path_prefix++;
10895 cpp_arg.len = strlen(cpp_arg.path_prefix);
10896 cpp_arg.errcode = errcode;
10897 err = got_diff_tree(tree1, tree2, NULL, NULL, -1, -1, "", "", repo,
10898 check_path_prefix_in_diff, &cpp_arg, 0);
10899 done:
10900 if (tree1)
10901 got_object_tree_close(tree1);
10902 if (tree2)
10903 got_object_tree_close(tree2);
10904 if (commit)
10905 got_object_commit_close(commit);
10906 if (parent_commit)
10907 got_object_commit_close(parent_commit);
10908 return err;
10911 static const struct got_error *
10912 collect_commits(struct got_object_id_queue *commits,
10913 struct got_object_id *initial_commit_id,
10914 struct got_object_id *iter_start_id, struct got_object_id *iter_stop_id,
10915 const char *path_prefix, int path_prefix_errcode,
10916 struct got_repository *repo)
10918 const struct got_error *err = NULL;
10919 struct got_commit_graph *graph = NULL;
10920 struct got_object_id parent_id, commit_id;
10921 struct got_object_qid *qid;
10923 err = got_commit_graph_open(&graph, "/", 1);
10924 if (err)
10925 return err;
10927 err = got_commit_graph_bfsort(graph, iter_start_id, repo,
10928 check_cancelled, NULL);
10929 if (err)
10930 goto done;
10932 memcpy(&commit_id, initial_commit_id, sizeof(commit_id));
10933 while (got_object_id_cmp(&commit_id, iter_stop_id) != 0) {
10934 err = got_commit_graph_iter_next(&parent_id, graph, repo,
10935 check_cancelled, NULL);
10936 if (err) {
10937 if (err->code == GOT_ERR_ITER_COMPLETED) {
10938 err = got_error_msg(GOT_ERR_ANCESTRY,
10939 "ran out of commits to rebase before "
10940 "youngest common ancestor commit has "
10941 "been reached?!?");
10943 goto done;
10944 } else {
10945 err = check_path_prefix(&parent_id, &commit_id,
10946 path_prefix, path_prefix_errcode, repo);
10947 if (err)
10948 goto done;
10950 err = got_object_qid_alloc(&qid, &commit_id);
10951 if (err)
10952 goto done;
10953 STAILQ_INSERT_HEAD(commits, qid, entry);
10955 memcpy(&commit_id, &parent_id, sizeof(commit_id));
10958 done:
10959 got_commit_graph_close(graph);
10960 return err;
10963 static const struct got_error *
10964 get_commit_brief_str(char **brief_str, struct got_commit_object *commit)
10966 const struct got_error *err = NULL;
10967 time_t committer_time;
10968 struct tm tm;
10969 char datebuf[11]; /* YYYY-MM-DD + NUL */
10970 char *author0 = NULL, *author, *smallerthan;
10971 char *logmsg0 = NULL, *logmsg, *newline;
10973 committer_time = got_object_commit_get_committer_time(commit);
10974 if (gmtime_r(&committer_time, &tm) == NULL)
10975 return got_error_from_errno("gmtime_r");
10976 if (strftime(datebuf, sizeof(datebuf), "%G-%m-%d", &tm) == 0)
10977 return got_error(GOT_ERR_NO_SPACE);
10979 author0 = strdup(got_object_commit_get_author(commit));
10980 if (author0 == NULL)
10981 return got_error_from_errno("strdup");
10982 author = author0;
10983 smallerthan = strchr(author, '<');
10984 if (smallerthan && smallerthan[1] != '\0')
10985 author = smallerthan + 1;
10986 author[strcspn(author, "@>")] = '\0';
10988 err = got_object_commit_get_logmsg(&logmsg0, commit);
10989 if (err)
10990 goto done;
10991 logmsg = logmsg0;
10992 while (*logmsg == '\n')
10993 logmsg++;
10994 newline = strchr(logmsg, '\n');
10995 if (newline)
10996 *newline = '\0';
10998 if (asprintf(brief_str, "%s %s %s",
10999 datebuf, author, logmsg) == -1)
11000 err = got_error_from_errno("asprintf");
11001 done:
11002 free(author0);
11003 free(logmsg0);
11004 return err;
11007 static const struct got_error *
11008 delete_backup_ref(struct got_reference *ref, struct got_object_id *id,
11009 struct got_repository *repo)
11011 const struct got_error *err;
11012 char *id_str;
11014 err = got_object_id_str(&id_str, id);
11015 if (err)
11016 return err;
11018 err = got_ref_delete(ref, repo);
11019 if (err)
11020 goto done;
11022 printf("Deleted %s: %s\n", got_ref_get_name(ref), id_str);
11023 done:
11024 free(id_str);
11025 return err;
11028 static const struct got_error *
11029 print_backup_ref(const char *branch_name, const char *new_id_str,
11030 struct got_object_id *old_commit_id, struct got_commit_object *old_commit,
11031 struct got_reflist_object_id_map *refs_idmap,
11032 struct got_repository *repo)
11034 const struct got_error *err = NULL;
11035 struct got_reflist_head *refs;
11036 char *refs_str = NULL;
11037 struct got_object_id *new_commit_id = NULL;
11038 struct got_commit_object *new_commit = NULL;
11039 char *new_commit_brief_str = NULL;
11040 struct got_object_id *yca_id = NULL;
11041 struct got_commit_object *yca_commit = NULL;
11042 char *yca_id_str = NULL, *yca_brief_str = NULL;
11043 char *custom_refs_str;
11045 if (asprintf(&custom_refs_str, "formerly %s", branch_name) == -1)
11046 return got_error_from_errno("asprintf");
11048 err = print_commit(old_commit, old_commit_id, repo, NULL, NULL, NULL,
11049 0, 0, refs_idmap, custom_refs_str, NULL);
11050 if (err)
11051 goto done;
11053 err = got_object_resolve_id_str(&new_commit_id, repo, new_id_str);
11054 if (err)
11055 goto done;
11057 refs = got_reflist_object_id_map_lookup(refs_idmap, new_commit_id);
11058 if (refs) {
11059 err = build_refs_str(&refs_str, refs, new_commit_id, repo, 0);
11060 if (err)
11061 goto done;
11064 err = got_object_open_as_commit(&new_commit, repo, new_commit_id);
11065 if (err)
11066 goto done;
11068 err = get_commit_brief_str(&new_commit_brief_str, new_commit);
11069 if (err)
11070 goto done;
11072 err = got_commit_graph_find_youngest_common_ancestor(&yca_id,
11073 old_commit_id, new_commit_id, 1, 0, repo, check_cancelled, NULL);
11074 if (err)
11075 goto done;
11077 printf("has become commit %s%s%s%s\n %s\n", new_id_str,
11078 refs_str ? " (" : "", refs_str ? refs_str : "",
11079 refs_str ? ")" : "", new_commit_brief_str);
11080 if (yca_id && got_object_id_cmp(yca_id, new_commit_id) != 0 &&
11081 got_object_id_cmp(yca_id, old_commit_id) != 0) {
11082 free(refs_str);
11083 refs_str = NULL;
11085 err = got_object_open_as_commit(&yca_commit, repo, yca_id);
11086 if (err)
11087 goto done;
11089 err = get_commit_brief_str(&yca_brief_str, yca_commit);
11090 if (err)
11091 goto done;
11093 err = got_object_id_str(&yca_id_str, yca_id);
11094 if (err)
11095 goto done;
11097 refs = got_reflist_object_id_map_lookup(refs_idmap, yca_id);
11098 if (refs) {
11099 err = build_refs_str(&refs_str, refs, yca_id, repo, 0);
11100 if (err)
11101 goto done;
11103 printf("history forked at %s%s%s%s\n %s\n",
11104 yca_id_str,
11105 refs_str ? " (" : "", refs_str ? refs_str : "",
11106 refs_str ? ")" : "", yca_brief_str);
11108 done:
11109 free(custom_refs_str);
11110 free(new_commit_id);
11111 free(refs_str);
11112 free(yca_id);
11113 free(yca_id_str);
11114 free(yca_brief_str);
11115 if (new_commit)
11116 got_object_commit_close(new_commit);
11117 if (yca_commit)
11118 got_object_commit_close(yca_commit);
11120 return err;
11123 static const struct got_error *
11124 worktree_has_logmsg_ref(const char *caller, struct got_worktree *worktree,
11125 struct got_repository *repo)
11127 const struct got_error *err;
11128 struct got_reflist_head refs;
11129 struct got_reflist_entry *re;
11130 char *uuidstr = NULL;
11131 static char msg[160];
11133 TAILQ_INIT(&refs);
11135 err = got_worktree_get_uuid(&uuidstr, worktree);
11136 if (err)
11137 goto done;
11139 err = got_ref_list(&refs, repo, "refs/got/worktree",
11140 got_ref_cmp_by_name, repo);
11141 if (err)
11142 goto done;
11144 TAILQ_FOREACH(re, &refs, entry) {
11145 const char *cmd, *refname, *type;
11147 refname = got_ref_get_name(re->ref);
11149 if (strncmp(refname, GOT_WORKTREE_CHERRYPICK_REF_PREFIX,
11150 GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN) == 0) {
11151 refname += GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN + 1;
11152 cmd = "cherrypick";
11153 type = "cherrypicked";
11154 } else if (strncmp(refname, GOT_WORKTREE_BACKOUT_REF_PREFIX,
11155 GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN) == 0) {
11156 refname += GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN + 1;
11157 cmd = "backout";
11158 type = "backed-out";
11159 } else
11160 continue;
11162 if (strncmp(refname, uuidstr, GOT_WORKTREE_UUID_STRLEN) != 0)
11163 continue;
11165 snprintf(msg, sizeof(msg),
11166 "work tree has references created by %s commits which "
11167 "must be removed with 'got %s -X' before running the %s "
11168 "command", type, cmd, caller);
11169 err = got_error_msg(GOT_ERR_WORKTREE_META, msg);
11170 goto done;
11173 done:
11174 free(uuidstr);
11175 got_ref_list_free(&refs);
11176 return err;
11179 static const struct got_error *
11180 process_backup_refs(const char *backup_ref_prefix,
11181 const char *wanted_branch_name,
11182 int delete, struct got_repository *repo)
11184 const struct got_error *err;
11185 struct got_reflist_head refs, backup_refs;
11186 struct got_reflist_entry *re;
11187 const size_t backup_ref_prefix_len = strlen(backup_ref_prefix);
11188 struct got_object_id *old_commit_id = NULL;
11189 char *branch_name = NULL;
11190 struct got_commit_object *old_commit = NULL;
11191 struct got_reflist_object_id_map *refs_idmap = NULL;
11192 int wanted_branch_found = 0;
11194 TAILQ_INIT(&refs);
11195 TAILQ_INIT(&backup_refs);
11197 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
11198 if (err)
11199 return err;
11201 err = got_reflist_object_id_map_create(&refs_idmap, &refs, repo);
11202 if (err)
11203 goto done;
11205 if (wanted_branch_name) {
11206 if (strncmp(wanted_branch_name, "refs/heads/", 11) == 0)
11207 wanted_branch_name += 11;
11210 err = got_ref_list(&backup_refs, repo, backup_ref_prefix,
11211 got_ref_cmp_by_commit_timestamp_descending, repo);
11212 if (err)
11213 goto done;
11215 TAILQ_FOREACH(re, &backup_refs, entry) {
11216 const char *refname = got_ref_get_name(re->ref);
11217 char *slash;
11219 err = check_cancelled(NULL);
11220 if (err)
11221 break;
11223 err = got_ref_resolve(&old_commit_id, repo, re->ref);
11224 if (err)
11225 break;
11227 err = got_object_open_as_commit(&old_commit, repo,
11228 old_commit_id);
11229 if (err)
11230 break;
11232 if (strncmp(backup_ref_prefix, refname,
11233 backup_ref_prefix_len) == 0)
11234 refname += backup_ref_prefix_len;
11236 while (refname[0] == '/')
11237 refname++;
11239 branch_name = strdup(refname);
11240 if (branch_name == NULL) {
11241 err = got_error_from_errno("strdup");
11242 break;
11244 slash = strrchr(branch_name, '/');
11245 if (slash) {
11246 *slash = '\0';
11247 refname += strlen(branch_name) + 1;
11250 if (wanted_branch_name == NULL ||
11251 strcmp(wanted_branch_name, branch_name) == 0) {
11252 wanted_branch_found = 1;
11253 if (delete) {
11254 err = delete_backup_ref(re->ref,
11255 old_commit_id, repo);
11256 } else {
11257 err = print_backup_ref(branch_name, refname,
11258 old_commit_id, old_commit, refs_idmap,
11259 repo);
11261 if (err)
11262 break;
11265 free(old_commit_id);
11266 old_commit_id = NULL;
11267 free(branch_name);
11268 branch_name = NULL;
11269 got_object_commit_close(old_commit);
11270 old_commit = NULL;
11273 if (wanted_branch_name && !wanted_branch_found) {
11274 err = got_error_fmt(GOT_ERR_NOT_REF,
11275 "%s/%s/", backup_ref_prefix, wanted_branch_name);
11277 done:
11278 if (refs_idmap)
11279 got_reflist_object_id_map_free(refs_idmap);
11280 got_ref_list_free(&refs);
11281 got_ref_list_free(&backup_refs);
11282 free(old_commit_id);
11283 free(branch_name);
11284 if (old_commit)
11285 got_object_commit_close(old_commit);
11286 return err;
11289 static const struct got_error *
11290 abort_progress(void *arg, unsigned char status, const char *path)
11293 * Unversioned files should not clutter progress output when
11294 * an operation is aborted.
11296 if (status == GOT_STATUS_UNVERSIONED)
11297 return NULL;
11299 return update_progress(arg, status, path);
11302 static const struct got_error *
11303 find_merge_commit_yca(struct got_object_id **new_yca_id,
11304 struct got_object_id *branch_head_commit_id,
11305 struct got_object_id *yca_id,
11306 struct got_object_id *base_commit_id,
11307 struct got_repository *repo)
11309 const struct got_error *err = NULL;
11310 struct got_commit_graph *graph = NULL;
11311 struct got_commit_object *commit = NULL;
11313 *new_yca_id = NULL;
11315 err = got_commit_graph_open(&graph, "/", 1);
11316 if (err)
11317 return err;
11319 err = got_commit_graph_bfsort(graph, base_commit_id,
11320 repo, check_cancelled, NULL);
11321 if (err)
11322 goto done;
11324 for (;;) {
11325 struct got_object_id id;
11327 err = got_commit_graph_iter_next(&id, graph, repo,
11328 check_cancelled, NULL);
11329 if (err) {
11330 if (err->code == GOT_ERR_ITER_COMPLETED)
11331 err = NULL;
11332 break;
11335 err = got_object_open_as_commit(&commit, repo, &id);
11336 if (err)
11337 break;
11339 if (got_object_commit_get_nparents(commit) > 1) {
11340 /* Search for a better YCA using toposort. */
11341 err = got_commit_graph_find_youngest_common_ancestor(
11342 new_yca_id, base_commit_id, branch_head_commit_id,
11343 0, 1, repo, check_cancelled, NULL);
11344 break;
11347 if (got_object_id_cmp(&id, yca_id) == 0)
11348 break;
11349 got_object_commit_close(commit);
11350 commit = NULL;
11352 done:
11353 got_commit_graph_close(graph);
11354 if (commit)
11355 got_object_commit_close(commit);
11356 return err;
11359 static const struct got_error *
11360 cmd_rebase(int argc, char *argv[])
11362 const struct got_error *error = NULL;
11363 struct got_worktree *worktree = NULL;
11364 struct got_repository *repo = NULL;
11365 struct got_fileindex *fileindex = NULL;
11366 char *cwd = NULL, *committer = NULL, *gitconfig_path = NULL;
11367 struct got_reference *branch = NULL;
11368 struct got_reference *new_base_branch = NULL, *tmp_branch = NULL;
11369 struct got_object_id *commit_id = NULL, *parent_id = NULL;
11370 struct got_object_id *resume_commit_id = NULL;
11371 struct got_object_id *branch_head_commit_id = NULL, *yca_id = NULL;
11372 struct got_object_id *head_commit_id = NULL;
11373 struct got_reference *head_ref = NULL;
11374 struct got_commit_object *commit = NULL;
11375 int ch, rebase_in_progress = 0, abort_rebase = 0, continue_rebase = 0;
11376 int histedit_in_progress = 0, merge_in_progress = 0;
11377 int create_backup = 1, list_backups = 0, delete_backups = 0;
11378 int allow_conflict = 0;
11379 struct got_object_id_queue commits;
11380 struct got_pathlist_head merged_paths;
11381 const struct got_object_id_queue *parent_ids;
11382 struct got_object_qid *qid, *pid;
11383 struct got_update_progress_arg upa;
11384 int *pack_fds = NULL;
11386 STAILQ_INIT(&commits);
11387 TAILQ_INIT(&merged_paths);
11388 memset(&upa, 0, sizeof(upa));
11390 #ifndef PROFILE
11391 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
11392 "unveil", NULL) == -1)
11393 err(1, "pledge");
11394 #endif
11396 while ((ch = getopt(argc, argv, "aCclX")) != -1) {
11397 switch (ch) {
11398 case 'a':
11399 abort_rebase = 1;
11400 break;
11401 case 'C':
11402 allow_conflict = 1;
11403 break;
11404 case 'c':
11405 continue_rebase = 1;
11406 break;
11407 case 'l':
11408 list_backups = 1;
11409 break;
11410 case 'X':
11411 delete_backups = 1;
11412 break;
11413 default:
11414 usage_rebase();
11415 /* NOTREACHED */
11419 argc -= optind;
11420 argv += optind;
11422 if (list_backups) {
11423 if (abort_rebase)
11424 option_conflict('l', 'a');
11425 if (allow_conflict)
11426 option_conflict('l', 'C');
11427 if (continue_rebase)
11428 option_conflict('l', 'c');
11429 if (delete_backups)
11430 option_conflict('l', 'X');
11431 if (argc != 0 && argc != 1)
11432 usage_rebase();
11433 } else if (delete_backups) {
11434 if (abort_rebase)
11435 option_conflict('X', 'a');
11436 if (allow_conflict)
11437 option_conflict('X', 'C');
11438 if (continue_rebase)
11439 option_conflict('X', 'c');
11440 if (list_backups)
11441 option_conflict('l', 'X');
11442 if (argc != 0 && argc != 1)
11443 usage_rebase();
11444 } else if (allow_conflict) {
11445 if (abort_rebase)
11446 option_conflict('C', 'a');
11447 if (!continue_rebase)
11448 errx(1, "-C option requires -c");
11449 } else {
11450 if (abort_rebase && continue_rebase)
11451 usage_rebase();
11452 else if (abort_rebase || continue_rebase) {
11453 if (argc != 0)
11454 usage_rebase();
11455 } else if (argc != 1)
11456 usage_rebase();
11459 cwd = getcwd(NULL, 0);
11460 if (cwd == NULL) {
11461 error = got_error_from_errno("getcwd");
11462 goto done;
11465 error = got_repo_pack_fds_open(&pack_fds);
11466 if (error != NULL)
11467 goto done;
11469 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
11470 if (error) {
11471 if (list_backups || delete_backups) {
11472 if (error->code != GOT_ERR_NOT_WORKTREE)
11473 goto done;
11474 } else {
11475 if (error->code == GOT_ERR_NOT_WORKTREE)
11476 error = wrap_not_worktree_error(error,
11477 "rebase", cwd);
11478 goto done;
11482 error = get_gitconfig_path(&gitconfig_path);
11483 if (error)
11484 goto done;
11485 error = got_repo_open(&repo,
11486 worktree ? got_worktree_get_repo_path(worktree) : cwd,
11487 gitconfig_path, pack_fds);
11488 if (error != NULL)
11489 goto done;
11491 if (worktree != NULL && !list_backups && !delete_backups) {
11492 error = worktree_has_logmsg_ref("rebase", worktree, repo);
11493 if (error)
11494 goto done;
11497 error = get_author(&committer, repo, worktree);
11498 if (error && error->code != GOT_ERR_COMMIT_NO_AUTHOR)
11499 goto done;
11501 error = apply_unveil(got_repo_get_path(repo), 0,
11502 worktree ? got_worktree_get_root_path(worktree) : NULL);
11503 if (error)
11504 goto done;
11506 if (list_backups || delete_backups) {
11507 error = process_backup_refs(
11508 GOT_WORKTREE_REBASE_BACKUP_REF_PREFIX,
11509 argc == 1 ? argv[0] : NULL, delete_backups, repo);
11510 goto done; /* nothing else to do */
11513 error = got_worktree_histedit_in_progress(&histedit_in_progress,
11514 worktree);
11515 if (error)
11516 goto done;
11517 if (histedit_in_progress) {
11518 error = got_error(GOT_ERR_HISTEDIT_BUSY);
11519 goto done;
11522 error = got_worktree_merge_in_progress(&merge_in_progress,
11523 worktree, repo);
11524 if (error)
11525 goto done;
11526 if (merge_in_progress) {
11527 error = got_error(GOT_ERR_MERGE_BUSY);
11528 goto done;
11531 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
11532 if (error)
11533 goto done;
11535 if (abort_rebase) {
11536 if (!rebase_in_progress) {
11537 error = got_error(GOT_ERR_NOT_REBASING);
11538 goto done;
11540 error = got_worktree_rebase_continue(&resume_commit_id,
11541 &new_base_branch, &tmp_branch, &branch, &fileindex,
11542 worktree, repo);
11543 if (error)
11544 goto done;
11545 printf("Switching work tree to %s\n",
11546 got_ref_get_symref_target(new_base_branch));
11547 error = got_worktree_rebase_abort(worktree, fileindex, repo,
11548 new_base_branch, abort_progress, &upa);
11549 if (error)
11550 goto done;
11551 printf("Rebase of %s aborted\n", got_ref_get_name(branch));
11552 print_merge_progress_stats(&upa);
11553 goto done; /* nothing else to do */
11556 if (continue_rebase) {
11557 if (!rebase_in_progress) {
11558 error = got_error(GOT_ERR_NOT_REBASING);
11559 goto done;
11561 error = got_worktree_rebase_continue(&resume_commit_id,
11562 &new_base_branch, &tmp_branch, &branch, &fileindex,
11563 worktree, repo);
11564 if (error)
11565 goto done;
11567 error = rebase_commit(NULL, worktree, fileindex, tmp_branch,
11568 committer, resume_commit_id, allow_conflict, repo);
11569 if (error)
11570 goto done;
11572 yca_id = got_object_id_dup(resume_commit_id);
11573 if (yca_id == NULL) {
11574 error = got_error_from_errno("got_object_id_dup");
11575 goto done;
11577 } else {
11578 error = got_ref_open(&branch, repo, argv[0], 0);
11579 if (error != NULL)
11580 goto done;
11581 if (strncmp(got_ref_get_name(branch), "refs/heads/", 11) != 0) {
11582 error = got_error_msg(GOT_ERR_COMMIT_BRANCH,
11583 "will not rebase a branch which lives outside "
11584 "the \"refs/heads/\" reference namespace");
11585 goto done;
11589 error = got_ref_resolve(&branch_head_commit_id, repo, branch);
11590 if (error)
11591 goto done;
11593 if (!continue_rebase) {
11594 struct got_object_id *base_commit_id;
11596 error = got_ref_open(&head_ref, repo,
11597 got_worktree_get_head_ref_name(worktree), 0);
11598 if (error)
11599 goto done;
11600 error = got_ref_resolve(&head_commit_id, repo, head_ref);
11601 if (error)
11602 goto done;
11603 base_commit_id = got_worktree_get_base_commit_id(worktree);
11604 if (got_object_id_cmp(base_commit_id, head_commit_id) != 0) {
11605 error = got_error(GOT_ERR_REBASE_OUT_OF_DATE);
11606 goto done;
11609 error = got_commit_graph_find_youngest_common_ancestor(&yca_id,
11610 base_commit_id, branch_head_commit_id, 1, 0,
11611 repo, check_cancelled, NULL);
11612 if (error) {
11613 if (error->code == GOT_ERR_ANCESTRY) {
11614 error = got_error_msg(GOT_ERR_ANCESTRY,
11615 "specified branch shares no common "
11616 "ancestry with work tree's branch");
11618 goto done;
11622 * If a merge commit appears between the new base branch tip
11623 * and a YCA found via first-parent traversal then we might
11624 * find a better YCA using topologically sorted commits.
11626 if (got_object_id_cmp(base_commit_id, yca_id) != 0) {
11627 struct got_object_id *better_yca_id;
11628 error = find_merge_commit_yca(&better_yca_id,
11629 branch_head_commit_id, yca_id,
11630 base_commit_id, repo);
11631 if (error)
11632 goto done;
11633 if (better_yca_id) {
11634 free(yca_id);
11635 yca_id = better_yca_id;
11639 if (got_object_id_cmp(base_commit_id, yca_id) == 0) {
11640 struct got_pathlist_head paths;
11641 printf("%s is already based on %s\n",
11642 got_ref_get_name(branch),
11643 got_worktree_get_head_ref_name(worktree));
11644 error = switch_head_ref(branch, branch_head_commit_id,
11645 worktree, repo);
11646 if (error)
11647 goto done;
11648 error = got_worktree_set_base_commit_id(worktree, repo,
11649 branch_head_commit_id);
11650 if (error)
11651 goto done;
11652 TAILQ_INIT(&paths);
11653 error = got_pathlist_append(&paths, "", NULL);
11654 if (error)
11655 goto done;
11656 error = got_worktree_checkout_files(worktree,
11657 &paths, repo, update_progress, &upa,
11658 check_cancelled, NULL);
11659 got_pathlist_free(&paths, GOT_PATHLIST_FREE_NONE);
11660 if (error)
11661 goto done;
11662 if (upa.did_something) {
11663 char *id_str;
11664 error = got_object_id_str(&id_str,
11665 branch_head_commit_id);
11666 if (error)
11667 goto done;
11668 printf("Updated to %s: %s\n",
11669 got_worktree_get_head_ref_name(worktree),
11670 id_str);
11671 free(id_str);
11672 } else
11673 printf("Already up-to-date\n");
11674 print_update_progress_stats(&upa);
11675 goto done;
11679 commit_id = branch_head_commit_id;
11680 error = got_object_open_as_commit(&commit, repo, commit_id);
11681 if (error)
11682 goto done;
11684 parent_ids = got_object_commit_get_parent_ids(commit);
11685 pid = STAILQ_FIRST(parent_ids);
11686 if (pid) {
11687 error = collect_commits(&commits, commit_id, &pid->id,
11688 yca_id, got_worktree_get_path_prefix(worktree),
11689 GOT_ERR_REBASE_PATH, repo);
11690 if (error)
11691 goto done;
11694 got_object_commit_close(commit);
11695 commit = NULL;
11697 if (!continue_rebase) {
11698 error = got_worktree_rebase_prepare(&new_base_branch,
11699 &tmp_branch, &fileindex, worktree, branch, repo);
11700 if (error)
11701 goto done;
11704 if (STAILQ_EMPTY(&commits)) {
11705 if (continue_rebase) {
11706 error = rebase_complete(worktree, fileindex,
11707 branch, tmp_branch, repo, create_backup);
11708 goto done;
11709 } else {
11710 /* Fast-forward the reference of the branch. */
11711 struct got_object_id *new_head_commit_id;
11712 char *id_str;
11713 error = got_ref_resolve(&new_head_commit_id, repo,
11714 new_base_branch);
11715 if (error)
11716 goto done;
11717 error = got_object_id_str(&id_str, new_head_commit_id);
11718 if (error)
11719 goto done;
11720 printf("Forwarding %s to commit %s\n",
11721 got_ref_get_name(branch), id_str);
11722 free(id_str);
11723 error = got_ref_change_ref(branch,
11724 new_head_commit_id);
11725 if (error)
11726 goto done;
11727 /* No backup needed since objects did not change. */
11728 create_backup = 0;
11732 pid = NULL;
11733 STAILQ_FOREACH(qid, &commits, entry) {
11735 commit_id = &qid->id;
11736 parent_id = pid ? &pid->id : yca_id;
11737 pid = qid;
11739 memset(&upa, 0, sizeof(upa));
11740 error = got_worktree_rebase_merge_files(&merged_paths,
11741 worktree, fileindex, parent_id, commit_id, repo,
11742 update_progress, &upa, check_cancelled, NULL);
11743 if (error)
11744 goto done;
11746 print_merge_progress_stats(&upa);
11747 if (upa.conflicts > 0 || upa.missing > 0 ||
11748 upa.not_deleted > 0 || upa.unversioned > 0) {
11749 if (upa.conflicts > 0) {
11750 error = show_rebase_merge_conflict(&qid->id,
11751 repo);
11752 if (error)
11753 goto done;
11755 got_pathlist_free(&merged_paths, GOT_PATHLIST_FREE_PATH);
11756 break;
11759 error = rebase_commit(&merged_paths, worktree, fileindex,
11760 tmp_branch, committer, commit_id, 0, repo);
11761 got_pathlist_free(&merged_paths, GOT_PATHLIST_FREE_PATH);
11762 if (error)
11763 goto done;
11766 if (upa.conflicts > 0 || upa.missing > 0 ||
11767 upa.not_deleted > 0 || upa.unversioned > 0) {
11768 error = got_worktree_rebase_postpone(worktree, fileindex);
11769 if (error)
11770 goto done;
11771 if (upa.conflicts > 0 && upa.missing == 0 &&
11772 upa.not_deleted == 0 && upa.unversioned == 0) {
11773 error = got_error_msg(GOT_ERR_CONFLICTS,
11774 "conflicts must be resolved before rebasing "
11775 "can continue");
11776 } else if (upa.conflicts > 0) {
11777 error = got_error_msg(GOT_ERR_CONFLICTS,
11778 "conflicts must be resolved before rebasing "
11779 "can continue; changes destined for some "
11780 "files were not yet merged and should be "
11781 "merged manually if required before the "
11782 "rebase operation is continued");
11783 } else {
11784 error = got_error_msg(GOT_ERR_CONFLICTS,
11785 "changes destined for some files were not "
11786 "yet merged and should be merged manually "
11787 "if required before the rebase operation "
11788 "is continued");
11790 } else
11791 error = rebase_complete(worktree, fileindex, branch,
11792 tmp_branch, repo, create_backup);
11793 done:
11794 free(cwd);
11795 free(committer);
11796 free(gitconfig_path);
11797 got_object_id_queue_free(&commits);
11798 free(branch_head_commit_id);
11799 free(resume_commit_id);
11800 free(head_commit_id);
11801 free(yca_id);
11802 if (commit)
11803 got_object_commit_close(commit);
11804 if (branch)
11805 got_ref_close(branch);
11806 if (new_base_branch)
11807 got_ref_close(new_base_branch);
11808 if (tmp_branch)
11809 got_ref_close(tmp_branch);
11810 if (head_ref)
11811 got_ref_close(head_ref);
11812 if (worktree)
11813 got_worktree_close(worktree);
11814 if (repo) {
11815 const struct got_error *close_err = got_repo_close(repo);
11816 if (error == NULL)
11817 error = close_err;
11819 if (pack_fds) {
11820 const struct got_error *pack_err =
11821 got_repo_pack_fds_close(pack_fds);
11822 if (error == NULL)
11823 error = pack_err;
11825 return error;
11828 __dead static void
11829 usage_histedit(void)
11831 fprintf(stderr, "usage: %s histedit [-aCcdeflmX] [-F histedit-script] "
11832 "[branch]\n", getprogname());
11833 exit(1);
11836 #define GOT_HISTEDIT_PICK 'p'
11837 #define GOT_HISTEDIT_EDIT 'e'
11838 #define GOT_HISTEDIT_FOLD 'f'
11839 #define GOT_HISTEDIT_DROP 'd'
11840 #define GOT_HISTEDIT_MESG 'm'
11842 static const struct got_histedit_cmd {
11843 unsigned char code;
11844 const char *name;
11845 const char *desc;
11846 } got_histedit_cmds[] = {
11847 { GOT_HISTEDIT_PICK, "pick", "use commit" },
11848 { GOT_HISTEDIT_EDIT, "edit", "use commit but stop for amending" },
11849 { GOT_HISTEDIT_FOLD, "fold", "combine with next commit that will "
11850 "be used" },
11851 { GOT_HISTEDIT_DROP, "drop", "remove commit from history" },
11852 { GOT_HISTEDIT_MESG, "mesg", "open editor to edit the log message" },
11855 struct got_histedit_list_entry {
11856 TAILQ_ENTRY(got_histedit_list_entry) entry;
11857 struct got_object_id *commit_id;
11858 const struct got_histedit_cmd *cmd;
11859 char *logmsg;
11861 TAILQ_HEAD(got_histedit_list, got_histedit_list_entry);
11863 static const struct got_error *
11864 histedit_write_commit(struct got_object_id *commit_id, const char *cmdname,
11865 FILE *f, struct got_repository *repo)
11867 const struct got_error *err = NULL;
11868 char *logmsg = NULL, *id_str = NULL;
11869 struct got_commit_object *commit = NULL;
11870 int n;
11872 err = got_object_open_as_commit(&commit, repo, commit_id);
11873 if (err)
11874 goto done;
11876 err = get_short_logmsg(&logmsg, 34, commit);
11877 if (err)
11878 goto done;
11880 err = got_object_id_str(&id_str, commit_id);
11881 if (err)
11882 goto done;
11884 n = fprintf(f, "%s %s %s\n", cmdname, id_str, logmsg);
11885 if (n < 0)
11886 err = got_ferror(f, GOT_ERR_IO);
11887 done:
11888 if (commit)
11889 got_object_commit_close(commit);
11890 free(id_str);
11891 free(logmsg);
11892 return err;
11895 static const struct got_error *
11896 histedit_write_commit_list(struct got_object_id_queue *commits,
11897 FILE *f, int edit_logmsg_only, int fold_only, int drop_only,
11898 int edit_only, struct got_repository *repo)
11900 const struct got_error *err = NULL;
11901 struct got_object_qid *qid;
11902 const char *histedit_cmd = NULL;
11904 if (STAILQ_EMPTY(commits))
11905 return got_error(GOT_ERR_EMPTY_HISTEDIT);
11907 STAILQ_FOREACH(qid, commits, entry) {
11908 histedit_cmd = got_histedit_cmds[0].name;
11909 if (drop_only)
11910 histedit_cmd = "drop";
11911 else if (edit_only)
11912 histedit_cmd = "edit";
11913 else if (fold_only && STAILQ_NEXT(qid, entry) != NULL)
11914 histedit_cmd = "fold";
11915 else if (edit_logmsg_only)
11916 histedit_cmd = "mesg";
11917 err = histedit_write_commit(&qid->id, histedit_cmd, f, repo);
11918 if (err)
11919 break;
11922 return err;
11925 static const struct got_error *
11926 write_cmd_list(FILE *f, const char *branch_name,
11927 struct got_object_id_queue *commits)
11929 const struct got_error *err = NULL;
11930 size_t i;
11931 int n;
11932 char *id_str;
11933 struct got_object_qid *qid;
11935 qid = STAILQ_FIRST(commits);
11936 err = got_object_id_str(&id_str, &qid->id);
11937 if (err)
11938 return err;
11940 n = fprintf(f,
11941 "# Editing the history of branch '%s' starting at\n"
11942 "# commit %s\n"
11943 "# Commits will be processed in order from top to "
11944 "bottom of this file.\n", branch_name, id_str);
11945 if (n < 0) {
11946 err = got_ferror(f, GOT_ERR_IO);
11947 goto done;
11950 n = fprintf(f, "# Available histedit commands:\n");
11951 if (n < 0) {
11952 err = got_ferror(f, GOT_ERR_IO);
11953 goto done;
11956 for (i = 0; i < nitems(got_histedit_cmds); i++) {
11957 const struct got_histedit_cmd *cmd = &got_histedit_cmds[i];
11958 n = fprintf(f, "# %s (%c): %s\n", cmd->name, cmd->code,
11959 cmd->desc);
11960 if (n < 0) {
11961 err = got_ferror(f, GOT_ERR_IO);
11962 break;
11965 done:
11966 free(id_str);
11967 return err;
11970 static const struct got_error *
11971 histedit_syntax_error(int lineno)
11973 static char msg[42];
11974 int ret;
11976 ret = snprintf(msg, sizeof(msg), "histedit syntax error on line %d",
11977 lineno);
11978 if (ret < 0 || (size_t)ret >= sizeof(msg))
11979 return got_error(GOT_ERR_HISTEDIT_SYNTAX);
11981 return got_error_msg(GOT_ERR_HISTEDIT_SYNTAX, msg);
11984 static const struct got_error *
11985 append_folded_commit_msg(char **new_msg, struct got_histedit_list_entry *hle,
11986 char *logmsg, struct got_repository *repo)
11988 const struct got_error *err;
11989 struct got_commit_object *folded_commit = NULL;
11990 char *id_str, *folded_logmsg = NULL;
11992 err = got_object_id_str(&id_str, hle->commit_id);
11993 if (err)
11994 return err;
11996 err = got_object_open_as_commit(&folded_commit, repo, hle->commit_id);
11997 if (err)
11998 goto done;
12000 err = got_object_commit_get_logmsg(&folded_logmsg, folded_commit);
12001 if (err)
12002 goto done;
12003 if (asprintf(new_msg, "%s%s# log message of folded commit %s: %s",
12004 logmsg ? logmsg : "", logmsg ? "\n" : "", id_str,
12005 folded_logmsg) == -1) {
12006 err = got_error_from_errno("asprintf");
12008 done:
12009 if (folded_commit)
12010 got_object_commit_close(folded_commit);
12011 free(id_str);
12012 free(folded_logmsg);
12013 return err;
12016 static struct got_histedit_list_entry *
12017 get_folded_commits(struct got_histedit_list_entry *hle)
12019 struct got_histedit_list_entry *prev, *folded = NULL;
12021 prev = TAILQ_PREV(hle, got_histedit_list, entry);
12022 while (prev && (prev->cmd->code == GOT_HISTEDIT_FOLD ||
12023 prev->cmd->code == GOT_HISTEDIT_DROP)) {
12024 if (prev->cmd->code == GOT_HISTEDIT_FOLD)
12025 folded = prev;
12026 prev = TAILQ_PREV(prev, got_histedit_list, entry);
12029 return folded;
12032 static const struct got_error *
12033 histedit_edit_logmsg(struct got_histedit_list_entry *hle,
12034 const char *editor, struct got_repository *repo)
12036 char *logmsg_path = NULL, *id_str = NULL, *orig_logmsg = NULL;
12037 char *logmsg = NULL, *new_msg = NULL;
12038 const struct got_error *err = NULL;
12039 struct got_commit_object *commit = NULL;
12040 int logmsg_len;
12041 int fd = -1;
12042 struct got_histedit_list_entry *folded = NULL;
12044 err = got_object_open_as_commit(&commit, repo, hle->commit_id);
12045 if (err)
12046 return err;
12048 folded = get_folded_commits(hle);
12049 if (folded) {
12050 while (folded != hle) {
12051 if (folded->cmd->code == GOT_HISTEDIT_DROP) {
12052 folded = TAILQ_NEXT(folded, entry);
12053 continue;
12055 err = append_folded_commit_msg(&new_msg, folded,
12056 logmsg, repo);
12057 if (err)
12058 goto done;
12059 free(logmsg);
12060 logmsg = new_msg;
12061 folded = TAILQ_NEXT(folded, entry);
12065 err = got_object_id_str(&id_str, hle->commit_id);
12066 if (err)
12067 goto done;
12068 err = got_object_commit_get_logmsg(&orig_logmsg, commit);
12069 if (err)
12070 goto done;
12071 logmsg_len = asprintf(&new_msg,
12072 "%s\n# original log message of commit %s: %s",
12073 logmsg ? logmsg : "", id_str, orig_logmsg);
12074 if (logmsg_len == -1) {
12075 err = got_error_from_errno("asprintf");
12076 goto done;
12078 free(logmsg);
12079 logmsg = new_msg;
12081 err = got_object_id_str(&id_str, hle->commit_id);
12082 if (err)
12083 goto done;
12085 err = got_opentemp_named_fd(&logmsg_path, &fd,
12086 GOT_TMPDIR_STR "/got-logmsg", "");
12087 if (err)
12088 goto done;
12090 if (write(fd, logmsg, logmsg_len) == -1) {
12091 err = got_error_from_errno2("write", logmsg_path);
12092 goto done;
12094 if (close(fd) == -1) {
12095 err = got_error_from_errno2("close", logmsg_path);
12096 goto done;
12098 fd = -1;
12100 err = edit_logmsg(&hle->logmsg, editor, logmsg_path, logmsg,
12101 logmsg_len, 0);
12102 if (err) {
12103 if (err->code != GOT_ERR_COMMIT_MSG_EMPTY)
12104 goto done;
12105 err = NULL;
12106 hle->logmsg = strdup(new_msg);
12107 if (hle->logmsg == NULL)
12108 err = got_error_from_errno("strdup");
12110 done:
12111 if (fd != -1 && close(fd) == -1 && err == NULL)
12112 err = got_error_from_errno2("close", logmsg_path);
12113 if (logmsg_path && unlink(logmsg_path) != 0 && err == NULL)
12114 err = got_error_from_errno2("unlink", logmsg_path);
12115 free(logmsg_path);
12116 free(logmsg);
12117 free(orig_logmsg);
12118 if (commit)
12119 got_object_commit_close(commit);
12120 return err;
12123 static const struct got_error *
12124 histedit_parse_list(struct got_histedit_list *histedit_cmds,
12125 FILE *f, struct got_repository *repo)
12127 const struct got_error *err = NULL;
12128 char *line = NULL, *p, *end;
12129 size_t i, linesize = 0;
12130 ssize_t linelen;
12131 int lineno = 0;
12132 const struct got_histedit_cmd *cmd;
12133 struct got_object_id *commit_id = NULL;
12134 struct got_histedit_list_entry *hle = NULL;
12136 for (;;) {
12137 linelen = getline(&line, &linesize, f);
12138 if (linelen == -1) {
12139 const struct got_error *getline_err;
12140 if (feof(f))
12141 break;
12142 getline_err = got_error_from_errno("getline");
12143 err = got_ferror(f, getline_err->code);
12144 break;
12146 lineno++;
12147 p = line;
12148 while (isspace((unsigned char)p[0]))
12149 p++;
12150 if (p[0] == '#' || p[0] == '\0')
12151 continue;
12152 cmd = NULL;
12153 for (i = 0; i < nitems(got_histedit_cmds); i++) {
12154 cmd = &got_histedit_cmds[i];
12155 if (strncmp(cmd->name, p, strlen(cmd->name)) == 0 &&
12156 isspace((unsigned char)p[strlen(cmd->name)])) {
12157 p += strlen(cmd->name);
12158 break;
12160 if (p[0] == cmd->code && isspace((unsigned char)p[1])) {
12161 p++;
12162 break;
12165 if (i == nitems(got_histedit_cmds)) {
12166 err = histedit_syntax_error(lineno);
12167 break;
12169 while (isspace((unsigned char)p[0]))
12170 p++;
12171 end = p;
12172 while (end[0] && !isspace((unsigned char)end[0]))
12173 end++;
12174 *end = '\0';
12175 err = got_object_resolve_id_str(&commit_id, repo, p);
12176 if (err) {
12177 /* override error code */
12178 err = histedit_syntax_error(lineno);
12179 break;
12181 hle = malloc(sizeof(*hle));
12182 if (hle == NULL) {
12183 err = got_error_from_errno("malloc");
12184 break;
12186 hle->cmd = cmd;
12187 hle->commit_id = commit_id;
12188 hle->logmsg = NULL;
12189 commit_id = NULL;
12190 TAILQ_INSERT_TAIL(histedit_cmds, hle, entry);
12193 free(line);
12194 free(commit_id);
12195 return err;
12198 static const struct got_error *
12199 histedit_check_script(struct got_histedit_list *histedit_cmds,
12200 struct got_object_id_queue *commits, struct got_repository *repo)
12202 const struct got_error *err = NULL;
12203 struct got_object_qid *qid;
12204 struct got_histedit_list_entry *hle;
12205 static char msg[92];
12206 char *id_str;
12208 if (TAILQ_EMPTY(histedit_cmds))
12209 return got_error_msg(GOT_ERR_EMPTY_HISTEDIT,
12210 "histedit script contains no commands");
12211 if (STAILQ_EMPTY(commits))
12212 return got_error(GOT_ERR_EMPTY_HISTEDIT);
12214 TAILQ_FOREACH(hle, histedit_cmds, entry) {
12215 struct got_histedit_list_entry *hle2;
12216 TAILQ_FOREACH(hle2, histedit_cmds, entry) {
12217 if (hle == hle2)
12218 continue;
12219 if (got_object_id_cmp(hle->commit_id,
12220 hle2->commit_id) != 0)
12221 continue;
12222 err = got_object_id_str(&id_str, hle->commit_id);
12223 if (err)
12224 return err;
12225 snprintf(msg, sizeof(msg), "commit %s is listed "
12226 "more than once in histedit script", id_str);
12227 free(id_str);
12228 return got_error_msg(GOT_ERR_HISTEDIT_CMD, msg);
12232 STAILQ_FOREACH(qid, commits, entry) {
12233 TAILQ_FOREACH(hle, histedit_cmds, entry) {
12234 if (got_object_id_cmp(&qid->id, hle->commit_id) == 0)
12235 break;
12237 if (hle == NULL) {
12238 err = got_object_id_str(&id_str, &qid->id);
12239 if (err)
12240 return err;
12241 snprintf(msg, sizeof(msg),
12242 "commit %s missing from histedit script", id_str);
12243 free(id_str);
12244 return got_error_msg(GOT_ERR_HISTEDIT_CMD, msg);
12248 hle = TAILQ_LAST(histedit_cmds, got_histedit_list);
12249 if (hle && hle->cmd->code == GOT_HISTEDIT_FOLD)
12250 return got_error_msg(GOT_ERR_HISTEDIT_CMD,
12251 "last commit in histedit script cannot be folded");
12253 return NULL;
12256 static const struct got_error *
12257 histedit_run_editor(struct got_histedit_list *histedit_cmds,
12258 const char *editor, const char *path,
12259 struct got_object_id_queue *commits, struct got_repository *repo)
12261 const struct got_error *err = NULL;
12262 struct stat st, st2;
12263 struct timespec timeout;
12264 FILE *f = NULL;
12266 if (stat(path, &st) == -1) {
12267 err = got_error_from_errno2("stat", path);
12268 goto done;
12271 if (spawn_editor(editor, path) == -1) {
12272 err = got_error_from_errno("failed spawning editor");
12273 goto done;
12276 timeout.tv_sec = 0;
12277 timeout.tv_nsec = 1;
12278 nanosleep(&timeout, NULL);
12280 if (stat(path, &st2) == -1) {
12281 err = got_error_from_errno2("stat", path);
12282 goto done;
12285 if (st.st_size == st2.st_size &&
12286 timespeccmp(&st.st_mtim, &st2.st_mtim, ==)) {
12287 err = got_error_msg(GOT_ERR_EMPTY_HISTEDIT,
12288 "no changes made to histedit script, aborting");
12289 goto done;
12292 f = fopen(path, "re");
12293 if (f == NULL) {
12294 err = got_error_from_errno("fopen");
12295 goto done;
12297 err = histedit_parse_list(histedit_cmds, f, repo);
12298 if (err)
12299 goto done;
12301 err = histedit_check_script(histedit_cmds, commits, repo);
12302 done:
12303 if (f && fclose(f) == EOF && err == NULL)
12304 err = got_error_from_errno("fclose");
12305 return err;
12308 static const struct got_error *
12309 histedit_edit_list_retry(struct got_histedit_list *, const struct got_error *,
12310 struct got_object_id_queue *, const char *, const char *, const char *,
12311 struct got_repository *);
12313 static const struct got_error *
12314 histedit_edit_script(struct got_histedit_list *histedit_cmds,
12315 struct got_object_id_queue *commits, const char *branch_name,
12316 int edit_logmsg_only, int fold_only, int drop_only, int edit_only,
12317 const char *editor, struct got_repository *repo)
12319 const struct got_error *err;
12320 FILE *f = NULL;
12321 char *path = NULL;
12323 err = got_opentemp_named(&path, &f, "got-histedit", "");
12324 if (err)
12325 return err;
12327 err = write_cmd_list(f, branch_name, commits);
12328 if (err)
12329 goto done;
12331 err = histedit_write_commit_list(commits, f, edit_logmsg_only,
12332 fold_only, drop_only, edit_only, repo);
12333 if (err)
12334 goto done;
12336 if (drop_only || edit_logmsg_only || fold_only || edit_only) {
12337 rewind(f);
12338 err = histedit_parse_list(histedit_cmds, f, repo);
12339 } else {
12340 if (fclose(f) == EOF) {
12341 err = got_error_from_errno("fclose");
12342 goto done;
12344 f = NULL;
12345 err = histedit_run_editor(histedit_cmds, editor, path,
12346 commits, repo);
12347 if (err) {
12348 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
12349 err->code != GOT_ERR_HISTEDIT_CMD)
12350 goto done;
12351 err = histedit_edit_list_retry(histedit_cmds, err,
12352 commits, editor, path, branch_name, repo);
12355 done:
12356 if (f && fclose(f) == EOF && err == NULL)
12357 err = got_error_from_errno("fclose");
12358 if (path && unlink(path) != 0 && err == NULL)
12359 err = got_error_from_errno2("unlink", path);
12360 free(path);
12361 return err;
12364 static const struct got_error *
12365 histedit_save_list(struct got_histedit_list *histedit_cmds,
12366 struct got_worktree *worktree, struct got_repository *repo)
12368 const struct got_error *err = NULL;
12369 char *path = NULL;
12370 FILE *f = NULL;
12371 struct got_histedit_list_entry *hle;
12373 err = got_worktree_get_histedit_script_path(&path, worktree);
12374 if (err)
12375 return err;
12377 f = fopen(path, "we");
12378 if (f == NULL) {
12379 err = got_error_from_errno2("fopen", path);
12380 goto done;
12382 TAILQ_FOREACH(hle, histedit_cmds, entry) {
12383 err = histedit_write_commit(hle->commit_id, hle->cmd->name, f,
12384 repo);
12385 if (err)
12386 break;
12388 done:
12389 if (f && fclose(f) == EOF && err == NULL)
12390 err = got_error_from_errno("fclose");
12391 free(path);
12392 return err;
12395 static void
12396 histedit_free_list(struct got_histedit_list *histedit_cmds)
12398 struct got_histedit_list_entry *hle;
12400 while ((hle = TAILQ_FIRST(histedit_cmds))) {
12401 TAILQ_REMOVE(histedit_cmds, hle, entry);
12402 free(hle);
12406 static const struct got_error *
12407 histedit_load_list(struct got_histedit_list *histedit_cmds,
12408 const char *path, struct got_repository *repo)
12410 const struct got_error *err = NULL;
12411 FILE *f = NULL;
12413 f = fopen(path, "re");
12414 if (f == NULL) {
12415 err = got_error_from_errno2("fopen", path);
12416 goto done;
12419 err = histedit_parse_list(histedit_cmds, f, repo);
12420 done:
12421 if (f && fclose(f) == EOF && err == NULL)
12422 err = got_error_from_errno("fclose");
12423 return err;
12426 static const struct got_error *
12427 histedit_edit_list_retry(struct got_histedit_list *histedit_cmds,
12428 const struct got_error *edit_err, struct got_object_id_queue *commits,
12429 const char *editor, const char *path, const char *branch_name,
12430 struct got_repository *repo)
12432 const struct got_error *err = NULL, *prev_err = edit_err;
12433 int resp = ' ';
12435 while (resp != 'c' && resp != 'r' && resp != 'a') {
12436 printf("%s: %s\n(c)ontinue editing, (r)estart editing, "
12437 "or (a)bort: ", getprogname(), prev_err->msg);
12438 resp = getchar();
12439 if (resp == '\n')
12440 resp = getchar();
12441 if (resp == 'c') {
12442 histedit_free_list(histedit_cmds);
12443 err = histedit_run_editor(histedit_cmds, editor, path,
12444 commits, repo);
12445 if (err) {
12446 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
12447 err->code != GOT_ERR_HISTEDIT_CMD)
12448 break;
12449 prev_err = err;
12450 resp = ' ';
12451 continue;
12453 break;
12454 } else if (resp == 'r') {
12455 histedit_free_list(histedit_cmds);
12456 err = histedit_edit_script(histedit_cmds,
12457 commits, branch_name, 0, 0, 0, 0, editor, repo);
12458 if (err) {
12459 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
12460 err->code != GOT_ERR_HISTEDIT_CMD)
12461 break;
12462 prev_err = err;
12463 resp = ' ';
12464 continue;
12466 break;
12467 } else if (resp == 'a') {
12468 err = got_error(GOT_ERR_HISTEDIT_CANCEL);
12469 break;
12470 } else
12471 printf("invalid response '%c'\n", resp);
12474 return err;
12477 static const struct got_error *
12478 histedit_complete(struct got_worktree *worktree,
12479 struct got_fileindex *fileindex, struct got_reference *tmp_branch,
12480 struct got_reference *branch, struct got_repository *repo)
12482 printf("Switching work tree to %s\n",
12483 got_ref_get_symref_target(branch));
12484 return got_worktree_histedit_complete(worktree, fileindex, tmp_branch,
12485 branch, repo);
12488 static const struct got_error *
12489 show_histedit_progress(struct got_commit_object *commit,
12490 struct got_histedit_list_entry *hle, struct got_object_id *new_id)
12492 const struct got_error *err;
12493 char *old_id_str = NULL, *new_id_str = NULL, *logmsg = NULL;
12495 err = got_object_id_str(&old_id_str, hle->commit_id);
12496 if (err)
12497 goto done;
12499 if (new_id) {
12500 err = got_object_id_str(&new_id_str, new_id);
12501 if (err)
12502 goto done;
12505 old_id_str[12] = '\0';
12506 if (new_id_str)
12507 new_id_str[12] = '\0';
12509 if (hle->logmsg) {
12510 logmsg = strdup(hle->logmsg);
12511 if (logmsg == NULL) {
12512 err = got_error_from_errno("strdup");
12513 goto done;
12515 trim_logmsg(logmsg, 42);
12516 } else {
12517 err = get_short_logmsg(&logmsg, 42, commit);
12518 if (err)
12519 goto done;
12522 switch (hle->cmd->code) {
12523 case GOT_HISTEDIT_PICK:
12524 case GOT_HISTEDIT_EDIT:
12525 case GOT_HISTEDIT_MESG:
12526 printf("%s -> %s: %s\n", old_id_str,
12527 new_id_str ? new_id_str : "no-op change", logmsg);
12528 break;
12529 case GOT_HISTEDIT_DROP:
12530 case GOT_HISTEDIT_FOLD:
12531 printf("%s -> %s commit: %s\n", old_id_str, hle->cmd->name,
12532 logmsg);
12533 break;
12534 default:
12535 break;
12537 done:
12538 free(old_id_str);
12539 free(new_id_str);
12540 return err;
12543 static const struct got_error *
12544 histedit_commit(struct got_pathlist_head *merged_paths,
12545 struct got_worktree *worktree, struct got_fileindex *fileindex,
12546 struct got_reference *tmp_branch, struct got_histedit_list_entry *hle,
12547 const char *committer, int allow_conflict, const char *editor,
12548 struct got_repository *repo)
12550 const struct got_error *err;
12551 struct got_commit_object *commit;
12552 struct got_object_id *new_commit_id;
12554 if ((hle->cmd->code == GOT_HISTEDIT_EDIT || get_folded_commits(hle))
12555 && hle->logmsg == NULL) {
12556 err = histedit_edit_logmsg(hle, editor, repo);
12557 if (err)
12558 return err;
12561 err = got_object_open_as_commit(&commit, repo, hle->commit_id);
12562 if (err)
12563 return err;
12565 err = got_worktree_histedit_commit(&new_commit_id, merged_paths,
12566 worktree, fileindex, tmp_branch, committer, commit, hle->commit_id,
12567 hle->logmsg, allow_conflict, repo);
12568 if (err) {
12569 if (err->code != GOT_ERR_COMMIT_NO_CHANGES)
12570 goto done;
12571 err = show_histedit_progress(commit, hle, NULL);
12572 } else {
12573 err = show_histedit_progress(commit, hle, new_commit_id);
12574 free(new_commit_id);
12576 done:
12577 got_object_commit_close(commit);
12578 return err;
12581 static const struct got_error *
12582 histedit_skip_commit(struct got_histedit_list_entry *hle,
12583 struct got_worktree *worktree, struct got_repository *repo)
12585 const struct got_error *error;
12586 struct got_commit_object *commit;
12588 error = got_worktree_histedit_skip_commit(worktree, hle->commit_id,
12589 repo);
12590 if (error)
12591 return error;
12593 error = got_object_open_as_commit(&commit, repo, hle->commit_id);
12594 if (error)
12595 return error;
12597 error = show_histedit_progress(commit, hle, NULL);
12598 got_object_commit_close(commit);
12599 return error;
12602 static const struct got_error *
12603 check_local_changes(void *arg, unsigned char status,
12604 unsigned char staged_status, const char *path,
12605 struct got_object_id *blob_id, struct got_object_id *staged_blob_id,
12606 struct got_object_id *commit_id, int dirfd, const char *de_name)
12608 int *have_local_changes = arg;
12610 switch (status) {
12611 case GOT_STATUS_ADD:
12612 case GOT_STATUS_DELETE:
12613 case GOT_STATUS_MODIFY:
12614 case GOT_STATUS_CONFLICT:
12615 *have_local_changes = 1;
12616 return got_error(GOT_ERR_CANCELLED);
12617 default:
12618 break;
12621 switch (staged_status) {
12622 case GOT_STATUS_ADD:
12623 case GOT_STATUS_DELETE:
12624 case GOT_STATUS_MODIFY:
12625 *have_local_changes = 1;
12626 return got_error(GOT_ERR_CANCELLED);
12627 default:
12628 break;
12631 return NULL;
12634 static const struct got_error *
12635 cmd_histedit(int argc, char *argv[])
12637 const struct got_error *error = NULL;
12638 struct got_worktree *worktree = NULL;
12639 struct got_fileindex *fileindex = NULL;
12640 struct got_repository *repo = NULL;
12641 char *cwd = NULL, *committer = NULL, *gitconfig_path = NULL;
12642 struct got_reference *branch = NULL;
12643 struct got_reference *tmp_branch = NULL;
12644 struct got_object_id *resume_commit_id = NULL;
12645 struct got_object_id *base_commit_id = NULL;
12646 struct got_object_id *head_commit_id = NULL;
12647 struct got_commit_object *commit = NULL;
12648 int ch, rebase_in_progress = 0, merge_in_progress = 0;
12649 struct got_update_progress_arg upa;
12650 int edit_in_progress = 0, abort_edit = 0, continue_edit = 0;
12651 int drop_only = 0, edit_logmsg_only = 0, fold_only = 0, edit_only = 0;
12652 int allow_conflict = 0, list_backups = 0, delete_backups = 0;
12653 const char *edit_script_path = NULL;
12654 char *editor = NULL;
12655 struct got_object_id_queue commits;
12656 struct got_pathlist_head merged_paths;
12657 const struct got_object_id_queue *parent_ids;
12658 struct got_object_qid *pid;
12659 struct got_histedit_list histedit_cmds;
12660 struct got_histedit_list_entry *hle;
12661 int *pack_fds = NULL;
12663 STAILQ_INIT(&commits);
12664 TAILQ_INIT(&histedit_cmds);
12665 TAILQ_INIT(&merged_paths);
12666 memset(&upa, 0, sizeof(upa));
12668 #ifndef PROFILE
12669 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
12670 "unveil", NULL) == -1)
12671 err(1, "pledge");
12672 #endif
12674 while ((ch = getopt(argc, argv, "aCcdeF:flmX")) != -1) {
12675 switch (ch) {
12676 case 'a':
12677 abort_edit = 1;
12678 break;
12679 case 'C':
12680 allow_conflict = 1;
12681 break;
12682 case 'c':
12683 continue_edit = 1;
12684 break;
12685 case 'd':
12686 drop_only = 1;
12687 break;
12688 case 'e':
12689 edit_only = 1;
12690 break;
12691 case 'F':
12692 edit_script_path = optarg;
12693 break;
12694 case 'f':
12695 fold_only = 1;
12696 break;
12697 case 'l':
12698 list_backups = 1;
12699 break;
12700 case 'm':
12701 edit_logmsg_only = 1;
12702 break;
12703 case 'X':
12704 delete_backups = 1;
12705 break;
12706 default:
12707 usage_histedit();
12708 /* NOTREACHED */
12712 argc -= optind;
12713 argv += optind;
12715 if (abort_edit && allow_conflict)
12716 option_conflict('a', 'C');
12717 if (abort_edit && continue_edit)
12718 option_conflict('a', 'c');
12719 if (edit_script_path && allow_conflict)
12720 option_conflict('F', 'C');
12721 if (edit_script_path && edit_logmsg_only)
12722 option_conflict('F', 'm');
12723 if (abort_edit && edit_logmsg_only)
12724 option_conflict('a', 'm');
12725 if (edit_logmsg_only && allow_conflict)
12726 option_conflict('m', 'C');
12727 if (continue_edit && edit_logmsg_only)
12728 option_conflict('c', 'm');
12729 if (abort_edit && fold_only)
12730 option_conflict('a', 'f');
12731 if (fold_only && allow_conflict)
12732 option_conflict('f', 'C');
12733 if (continue_edit && fold_only)
12734 option_conflict('c', 'f');
12735 if (fold_only && edit_logmsg_only)
12736 option_conflict('f', 'm');
12737 if (edit_script_path && fold_only)
12738 option_conflict('F', 'f');
12739 if (abort_edit && edit_only)
12740 option_conflict('a', 'e');
12741 if (continue_edit && edit_only)
12742 option_conflict('c', 'e');
12743 if (edit_only && edit_logmsg_only)
12744 option_conflict('e', 'm');
12745 if (edit_script_path && edit_only)
12746 option_conflict('F', 'e');
12747 if (fold_only && edit_only)
12748 option_conflict('f', 'e');
12749 if (drop_only && abort_edit)
12750 option_conflict('d', 'a');
12751 if (drop_only && allow_conflict)
12752 option_conflict('d', 'C');
12753 if (drop_only && continue_edit)
12754 option_conflict('d', 'c');
12755 if (drop_only && edit_logmsg_only)
12756 option_conflict('d', 'm');
12757 if (drop_only && edit_only)
12758 option_conflict('d', 'e');
12759 if (drop_only && edit_script_path)
12760 option_conflict('d', 'F');
12761 if (drop_only && fold_only)
12762 option_conflict('d', 'f');
12763 if (list_backups) {
12764 if (abort_edit)
12765 option_conflict('l', 'a');
12766 if (allow_conflict)
12767 option_conflict('l', 'C');
12768 if (continue_edit)
12769 option_conflict('l', 'c');
12770 if (edit_script_path)
12771 option_conflict('l', 'F');
12772 if (edit_logmsg_only)
12773 option_conflict('l', 'm');
12774 if (drop_only)
12775 option_conflict('l', 'd');
12776 if (fold_only)
12777 option_conflict('l', 'f');
12778 if (edit_only)
12779 option_conflict('l', 'e');
12780 if (delete_backups)
12781 option_conflict('l', 'X');
12782 if (argc != 0 && argc != 1)
12783 usage_histedit();
12784 } else if (delete_backups) {
12785 if (abort_edit)
12786 option_conflict('X', 'a');
12787 if (allow_conflict)
12788 option_conflict('X', 'C');
12789 if (continue_edit)
12790 option_conflict('X', 'c');
12791 if (drop_only)
12792 option_conflict('X', 'd');
12793 if (edit_script_path)
12794 option_conflict('X', 'F');
12795 if (edit_logmsg_only)
12796 option_conflict('X', 'm');
12797 if (fold_only)
12798 option_conflict('X', 'f');
12799 if (edit_only)
12800 option_conflict('X', 'e');
12801 if (list_backups)
12802 option_conflict('X', 'l');
12803 if (argc != 0 && argc != 1)
12804 usage_histedit();
12805 } else if (allow_conflict && !continue_edit)
12806 errx(1, "-C option requires -c");
12807 else if (argc != 0)
12808 usage_histedit();
12810 cwd = getcwd(NULL, 0);
12811 if (cwd == NULL) {
12812 error = got_error_from_errno("getcwd");
12813 goto done;
12816 error = got_repo_pack_fds_open(&pack_fds);
12817 if (error != NULL)
12818 goto done;
12820 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
12821 if (error) {
12822 if (list_backups || delete_backups) {
12823 if (error->code != GOT_ERR_NOT_WORKTREE)
12824 goto done;
12825 } else {
12826 if (error->code == GOT_ERR_NOT_WORKTREE)
12827 error = wrap_not_worktree_error(error,
12828 "histedit", cwd);
12829 goto done;
12833 if (list_backups || delete_backups) {
12834 error = got_repo_open(&repo,
12835 worktree ? got_worktree_get_repo_path(worktree) : cwd,
12836 NULL, pack_fds);
12837 if (error != NULL)
12838 goto done;
12839 error = apply_unveil(got_repo_get_path(repo), 0,
12840 worktree ? got_worktree_get_root_path(worktree) : NULL);
12841 if (error)
12842 goto done;
12843 error = process_backup_refs(
12844 GOT_WORKTREE_HISTEDIT_BACKUP_REF_PREFIX,
12845 argc == 1 ? argv[0] : NULL, delete_backups, repo);
12846 goto done; /* nothing else to do */
12847 } else {
12848 error = get_gitconfig_path(&gitconfig_path);
12849 if (error)
12850 goto done;
12851 error = got_repo_open(&repo,
12852 got_worktree_get_repo_path(worktree), gitconfig_path,
12853 pack_fds);
12854 if (error != NULL)
12855 goto done;
12856 error = get_editor(&editor);
12857 if (error)
12858 goto done;
12859 if (unveil(editor, "x") != 0) {
12860 error = got_error_from_errno2("unveil", editor);
12861 goto done;
12863 if (edit_script_path) {
12864 if (unveil(edit_script_path, "r") != 0) {
12865 error = got_error_from_errno2("unveil",
12866 edit_script_path);
12867 goto done;
12870 error = apply_unveil(got_repo_get_path(repo), 0,
12871 got_worktree_get_root_path(worktree));
12872 if (error)
12873 goto done;
12876 if (worktree != NULL && !list_backups && !delete_backups) {
12877 error = worktree_has_logmsg_ref("histedit", worktree, repo);
12878 if (error)
12879 goto done;
12882 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
12883 if (error)
12884 goto done;
12885 if (rebase_in_progress) {
12886 error = got_error(GOT_ERR_REBASING);
12887 goto done;
12890 error = got_worktree_merge_in_progress(&merge_in_progress, worktree,
12891 repo);
12892 if (error)
12893 goto done;
12894 if (merge_in_progress) {
12895 error = got_error(GOT_ERR_MERGE_BUSY);
12896 goto done;
12899 error = got_worktree_histedit_in_progress(&edit_in_progress, worktree);
12900 if (error)
12901 goto done;
12903 if (edit_in_progress && edit_logmsg_only) {
12904 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
12905 "histedit operation is in progress in this "
12906 "work tree and must be continued or aborted "
12907 "before the -m option can be used");
12908 goto done;
12910 if (edit_in_progress && drop_only) {
12911 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
12912 "histedit operation is in progress in this "
12913 "work tree and must be continued or aborted "
12914 "before the -d option can be used");
12915 goto done;
12917 if (edit_in_progress && fold_only) {
12918 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
12919 "histedit operation is in progress in this "
12920 "work tree and must be continued or aborted "
12921 "before the -f option can be used");
12922 goto done;
12924 if (edit_in_progress && edit_only) {
12925 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
12926 "histedit operation is in progress in this "
12927 "work tree and must be continued or aborted "
12928 "before the -e option can be used");
12929 goto done;
12932 if (edit_in_progress && abort_edit) {
12933 error = got_worktree_histedit_continue(&resume_commit_id,
12934 &tmp_branch, &branch, &base_commit_id, &fileindex,
12935 worktree, repo);
12936 if (error)
12937 goto done;
12938 printf("Switching work tree to %s\n",
12939 got_ref_get_symref_target(branch));
12940 error = got_worktree_histedit_abort(worktree, fileindex, repo,
12941 branch, base_commit_id, abort_progress, &upa);
12942 if (error)
12943 goto done;
12944 printf("Histedit of %s aborted\n",
12945 got_ref_get_symref_target(branch));
12946 print_merge_progress_stats(&upa);
12947 goto done; /* nothing else to do */
12948 } else if (abort_edit) {
12949 error = got_error(GOT_ERR_NOT_HISTEDIT);
12950 goto done;
12953 error = get_author(&committer, repo, worktree);
12954 if (error)
12955 goto done;
12957 if (continue_edit) {
12958 char *path;
12960 if (!edit_in_progress) {
12961 error = got_error(GOT_ERR_NOT_HISTEDIT);
12962 goto done;
12965 error = got_worktree_get_histedit_script_path(&path, worktree);
12966 if (error)
12967 goto done;
12969 error = histedit_load_list(&histedit_cmds, path, repo);
12970 free(path);
12971 if (error)
12972 goto done;
12974 error = got_worktree_histedit_continue(&resume_commit_id,
12975 &tmp_branch, &branch, &base_commit_id, &fileindex,
12976 worktree, repo);
12977 if (error)
12978 goto done;
12980 error = got_ref_resolve(&head_commit_id, repo, branch);
12981 if (error)
12982 goto done;
12984 error = got_object_open_as_commit(&commit, repo,
12985 head_commit_id);
12986 if (error)
12987 goto done;
12988 parent_ids = got_object_commit_get_parent_ids(commit);
12989 pid = STAILQ_FIRST(parent_ids);
12990 if (pid == NULL) {
12991 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
12992 goto done;
12994 error = collect_commits(&commits, head_commit_id, &pid->id,
12995 base_commit_id, got_worktree_get_path_prefix(worktree),
12996 GOT_ERR_HISTEDIT_PATH, repo);
12997 got_object_commit_close(commit);
12998 commit = NULL;
12999 if (error)
13000 goto done;
13001 } else {
13002 if (edit_in_progress) {
13003 error = got_error(GOT_ERR_HISTEDIT_BUSY);
13004 goto done;
13007 error = got_ref_open(&branch, repo,
13008 got_worktree_get_head_ref_name(worktree), 0);
13009 if (error != NULL)
13010 goto done;
13012 if (strncmp(got_ref_get_name(branch), "refs/heads/", 11) != 0) {
13013 error = got_error_msg(GOT_ERR_COMMIT_BRANCH,
13014 "will not edit commit history of a branch outside "
13015 "the \"refs/heads/\" reference namespace");
13016 goto done;
13019 error = got_ref_resolve(&head_commit_id, repo, branch);
13020 got_ref_close(branch);
13021 branch = NULL;
13022 if (error)
13023 goto done;
13025 error = got_object_open_as_commit(&commit, repo,
13026 head_commit_id);
13027 if (error)
13028 goto done;
13029 parent_ids = got_object_commit_get_parent_ids(commit);
13030 pid = STAILQ_FIRST(parent_ids);
13031 if (pid == NULL) {
13032 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
13033 goto done;
13035 error = collect_commits(&commits, head_commit_id, &pid->id,
13036 got_worktree_get_base_commit_id(worktree),
13037 got_worktree_get_path_prefix(worktree),
13038 GOT_ERR_HISTEDIT_PATH, repo);
13039 got_object_commit_close(commit);
13040 commit = NULL;
13041 if (error)
13042 goto done;
13044 if (STAILQ_EMPTY(&commits)) {
13045 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
13046 goto done;
13049 error = got_worktree_histedit_prepare(&tmp_branch, &branch,
13050 &base_commit_id, &fileindex, worktree, repo);
13051 if (error)
13052 goto done;
13054 if (edit_script_path) {
13055 error = histedit_load_list(&histedit_cmds,
13056 edit_script_path, repo);
13057 if (error) {
13058 got_worktree_histedit_abort(worktree, fileindex,
13059 repo, branch, base_commit_id,
13060 abort_progress, &upa);
13061 print_merge_progress_stats(&upa);
13062 goto done;
13064 } else {
13065 const char *branch_name;
13066 branch_name = got_ref_get_symref_target(branch);
13067 if (strncmp(branch_name, "refs/heads/", 11) == 0)
13068 branch_name += 11;
13069 error = histedit_edit_script(&histedit_cmds, &commits,
13070 branch_name, edit_logmsg_only, fold_only,
13071 drop_only, edit_only, editor, repo);
13072 if (error) {
13073 got_worktree_histedit_abort(worktree, fileindex,
13074 repo, branch, base_commit_id,
13075 abort_progress, &upa);
13076 print_merge_progress_stats(&upa);
13077 goto done;
13082 error = histedit_save_list(&histedit_cmds, worktree,
13083 repo);
13084 if (error) {
13085 got_worktree_histedit_abort(worktree, fileindex,
13086 repo, branch, base_commit_id,
13087 abort_progress, &upa);
13088 print_merge_progress_stats(&upa);
13089 goto done;
13094 error = histedit_check_script(&histedit_cmds, &commits, repo);
13095 if (error)
13096 goto done;
13098 TAILQ_FOREACH(hle, &histedit_cmds, entry) {
13099 if (resume_commit_id) {
13100 if (got_object_id_cmp(hle->commit_id,
13101 resume_commit_id) != 0)
13102 continue;
13104 resume_commit_id = NULL;
13105 if (hle->cmd->code == GOT_HISTEDIT_DROP ||
13106 hle->cmd->code == GOT_HISTEDIT_FOLD) {
13107 error = histedit_skip_commit(hle, worktree,
13108 repo);
13109 if (error)
13110 goto done;
13111 } else {
13112 struct got_pathlist_head paths;
13113 int have_changes = 0;
13115 TAILQ_INIT(&paths);
13116 error = got_pathlist_append(&paths, "", NULL);
13117 if (error)
13118 goto done;
13119 error = got_worktree_status(worktree, &paths,
13120 repo, 0, check_local_changes, &have_changes,
13121 check_cancelled, NULL);
13122 got_pathlist_free(&paths,
13123 GOT_PATHLIST_FREE_NONE);
13124 if (error) {
13125 if (error->code != GOT_ERR_CANCELLED)
13126 goto done;
13127 if (sigint_received || sigpipe_received)
13128 goto done;
13130 if (have_changes) {
13131 error = histedit_commit(NULL, worktree,
13132 fileindex, tmp_branch, hle,
13133 committer, allow_conflict, editor,
13134 repo);
13135 if (error)
13136 goto done;
13137 } else {
13138 error = got_object_open_as_commit(
13139 &commit, repo, hle->commit_id);
13140 if (error)
13141 goto done;
13142 error = show_histedit_progress(commit,
13143 hle, NULL);
13144 got_object_commit_close(commit);
13145 commit = NULL;
13146 if (error)
13147 goto done;
13150 continue;
13153 if (hle->cmd->code == GOT_HISTEDIT_DROP) {
13154 error = histedit_skip_commit(hle, worktree, repo);
13155 if (error)
13156 goto done;
13157 continue;
13159 error = got_object_open_as_commit(&commit, repo,
13160 hle->commit_id);
13161 if (error)
13162 goto done;
13163 parent_ids = got_object_commit_get_parent_ids(commit);
13164 pid = STAILQ_FIRST(parent_ids);
13166 error = got_worktree_histedit_merge_files(&merged_paths,
13167 worktree, fileindex, &pid->id, hle->commit_id, repo,
13168 update_progress, &upa, check_cancelled, NULL);
13169 if (error)
13170 goto done;
13171 got_object_commit_close(commit);
13172 commit = NULL;
13174 print_merge_progress_stats(&upa);
13175 if (upa.conflicts > 0 || upa.missing > 0 ||
13176 upa.not_deleted > 0 || upa.unversioned > 0) {
13177 if (upa.conflicts > 0) {
13178 error = show_rebase_merge_conflict(
13179 hle->commit_id, repo);
13180 if (error)
13181 goto done;
13183 got_pathlist_free(&merged_paths, GOT_PATHLIST_FREE_PATH);
13184 break;
13187 if (hle->cmd->code == GOT_HISTEDIT_EDIT) {
13188 char *id_str;
13189 error = got_object_id_str(&id_str, hle->commit_id);
13190 if (error)
13191 goto done;
13192 printf("Stopping histedit for amending commit %s\n",
13193 id_str);
13194 free(id_str);
13195 got_pathlist_free(&merged_paths, GOT_PATHLIST_FREE_PATH);
13196 error = got_worktree_histedit_postpone(worktree,
13197 fileindex);
13198 goto done;
13199 } else if (hle->cmd->code == GOT_HISTEDIT_FOLD) {
13200 error = histedit_skip_commit(hle, worktree, repo);
13201 if (error)
13202 goto done;
13203 continue;
13204 } else if (hle->cmd->code == GOT_HISTEDIT_MESG) {
13205 error = histedit_edit_logmsg(hle, editor, repo);
13206 if (error)
13207 goto done;
13210 error = histedit_commit(&merged_paths, worktree, fileindex,
13211 tmp_branch, hle, committer, allow_conflict, editor, repo);
13212 got_pathlist_free(&merged_paths, GOT_PATHLIST_FREE_PATH);
13213 if (error)
13214 goto done;
13217 if (upa.conflicts > 0 || upa.missing > 0 ||
13218 upa.not_deleted > 0 || upa.unversioned > 0) {
13219 error = got_worktree_histedit_postpone(worktree, fileindex);
13220 if (error)
13221 goto done;
13222 if (upa.conflicts > 0 && upa.missing == 0 &&
13223 upa.not_deleted == 0 && upa.unversioned == 0) {
13224 error = got_error_msg(GOT_ERR_CONFLICTS,
13225 "conflicts must be resolved before histedit "
13226 "can continue");
13227 } else if (upa.conflicts > 0) {
13228 error = got_error_msg(GOT_ERR_CONFLICTS,
13229 "conflicts must be resolved before histedit "
13230 "can continue; changes destined for some "
13231 "files were not yet merged and should be "
13232 "merged manually if required before the "
13233 "histedit operation is continued");
13234 } else {
13235 error = got_error_msg(GOT_ERR_CONFLICTS,
13236 "changes destined for some files were not "
13237 "yet merged and should be merged manually "
13238 "if required before the histedit operation "
13239 "is continued");
13241 } else
13242 error = histedit_complete(worktree, fileindex, tmp_branch,
13243 branch, repo);
13244 done:
13245 free(cwd);
13246 free(editor);
13247 free(committer);
13248 free(gitconfig_path);
13249 got_object_id_queue_free(&commits);
13250 histedit_free_list(&histedit_cmds);
13251 free(head_commit_id);
13252 free(base_commit_id);
13253 free(resume_commit_id);
13254 if (commit)
13255 got_object_commit_close(commit);
13256 if (branch)
13257 got_ref_close(branch);
13258 if (tmp_branch)
13259 got_ref_close(tmp_branch);
13260 if (worktree)
13261 got_worktree_close(worktree);
13262 if (repo) {
13263 const struct got_error *close_err = got_repo_close(repo);
13264 if (error == NULL)
13265 error = close_err;
13267 if (pack_fds) {
13268 const struct got_error *pack_err =
13269 got_repo_pack_fds_close(pack_fds);
13270 if (error == NULL)
13271 error = pack_err;
13273 return error;
13276 __dead static void
13277 usage_integrate(void)
13279 fprintf(stderr, "usage: %s integrate branch\n", getprogname());
13280 exit(1);
13283 static const struct got_error *
13284 cmd_integrate(int argc, char *argv[])
13286 const struct got_error *error = NULL;
13287 struct got_repository *repo = NULL;
13288 struct got_worktree *worktree = NULL;
13289 char *cwd = NULL, *refname = NULL, *base_refname = NULL;
13290 const char *branch_arg = NULL;
13291 struct got_reference *branch_ref = NULL, *base_branch_ref = NULL;
13292 struct got_fileindex *fileindex = NULL;
13293 struct got_object_id *commit_id = NULL, *base_commit_id = NULL;
13294 int ch;
13295 struct got_update_progress_arg upa;
13296 int *pack_fds = NULL;
13298 #ifndef PROFILE
13299 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
13300 "unveil", NULL) == -1)
13301 err(1, "pledge");
13302 #endif
13304 while ((ch = getopt(argc, argv, "")) != -1) {
13305 switch (ch) {
13306 default:
13307 usage_integrate();
13308 /* NOTREACHED */
13312 argc -= optind;
13313 argv += optind;
13315 if (argc != 1)
13316 usage_integrate();
13317 branch_arg = argv[0];
13319 cwd = getcwd(NULL, 0);
13320 if (cwd == NULL) {
13321 error = got_error_from_errno("getcwd");
13322 goto done;
13325 error = got_repo_pack_fds_open(&pack_fds);
13326 if (error != NULL)
13327 goto done;
13329 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
13330 if (error) {
13331 if (error->code == GOT_ERR_NOT_WORKTREE)
13332 error = wrap_not_worktree_error(error, "integrate",
13333 cwd);
13334 goto done;
13337 error = check_rebase_or_histedit_in_progress(worktree);
13338 if (error)
13339 goto done;
13341 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
13342 NULL, pack_fds);
13343 if (error != NULL)
13344 goto done;
13346 error = apply_unveil(got_repo_get_path(repo), 0,
13347 got_worktree_get_root_path(worktree));
13348 if (error)
13349 goto done;
13351 error = check_merge_in_progress(worktree, repo);
13352 if (error)
13353 goto done;
13355 if (asprintf(&refname, "refs/heads/%s", branch_arg) == -1) {
13356 error = got_error_from_errno("asprintf");
13357 goto done;
13360 error = got_worktree_integrate_prepare(&fileindex, &branch_ref,
13361 &base_branch_ref, worktree, refname, repo);
13362 if (error)
13363 goto done;
13365 refname = strdup(got_ref_get_name(branch_ref));
13366 if (refname == NULL) {
13367 error = got_error_from_errno("strdup");
13368 got_worktree_integrate_abort(worktree, fileindex, repo,
13369 branch_ref, base_branch_ref);
13370 goto done;
13372 base_refname = strdup(got_ref_get_name(base_branch_ref));
13373 if (base_refname == NULL) {
13374 error = got_error_from_errno("strdup");
13375 got_worktree_integrate_abort(worktree, fileindex, repo,
13376 branch_ref, base_branch_ref);
13377 goto done;
13379 if (strncmp(base_refname, "refs/heads/", 11) != 0) {
13380 error = got_error(GOT_ERR_INTEGRATE_BRANCH);
13381 got_worktree_integrate_abort(worktree, fileindex, repo,
13382 branch_ref, base_branch_ref);
13383 goto done;
13386 error = got_ref_resolve(&commit_id, repo, branch_ref);
13387 if (error)
13388 goto done;
13390 error = got_ref_resolve(&base_commit_id, repo, base_branch_ref);
13391 if (error)
13392 goto done;
13394 if (got_object_id_cmp(commit_id, base_commit_id) == 0) {
13395 error = got_error_msg(GOT_ERR_SAME_BRANCH,
13396 "specified branch has already been integrated");
13397 got_worktree_integrate_abort(worktree, fileindex, repo,
13398 branch_ref, base_branch_ref);
13399 goto done;
13402 error = check_linear_ancestry(commit_id, base_commit_id, 1, repo);
13403 if (error) {
13404 if (error->code == GOT_ERR_ANCESTRY)
13405 error = got_error(GOT_ERR_REBASE_REQUIRED);
13406 got_worktree_integrate_abort(worktree, fileindex, repo,
13407 branch_ref, base_branch_ref);
13408 goto done;
13411 memset(&upa, 0, sizeof(upa));
13412 error = got_worktree_integrate_continue(worktree, fileindex, repo,
13413 branch_ref, base_branch_ref, update_progress, &upa,
13414 check_cancelled, NULL);
13415 if (error)
13416 goto done;
13418 printf("Integrated %s into %s\n", refname, base_refname);
13419 print_update_progress_stats(&upa);
13420 done:
13421 if (repo) {
13422 const struct got_error *close_err = got_repo_close(repo);
13423 if (error == NULL)
13424 error = close_err;
13426 if (worktree)
13427 got_worktree_close(worktree);
13428 if (pack_fds) {
13429 const struct got_error *pack_err =
13430 got_repo_pack_fds_close(pack_fds);
13431 if (error == NULL)
13432 error = pack_err;
13434 free(cwd);
13435 free(base_commit_id);
13436 free(commit_id);
13437 free(refname);
13438 free(base_refname);
13439 return error;
13442 __dead static void
13443 usage_merge(void)
13445 fprintf(stderr, "usage: %s merge [-aCcn] [branch]\n", getprogname());
13446 exit(1);
13449 static const struct got_error *
13450 cmd_merge(int argc, char *argv[])
13452 const struct got_error *error = NULL;
13453 struct got_worktree *worktree = NULL;
13454 struct got_repository *repo = NULL;
13455 struct got_fileindex *fileindex = NULL;
13456 char *cwd = NULL, *id_str = NULL, *author = NULL;
13457 char *gitconfig_path = NULL;
13458 struct got_reference *branch = NULL, *wt_branch = NULL;
13459 struct got_object_id *branch_tip = NULL, *yca_id = NULL;
13460 struct got_object_id *wt_branch_tip = NULL;
13461 int ch, merge_in_progress = 0, abort_merge = 0, continue_merge = 0;
13462 int allow_conflict = 0, prefer_fast_forward = 1, interrupt_merge = 0;
13463 struct got_update_progress_arg upa;
13464 struct got_object_id *merge_commit_id = NULL;
13465 char *branch_name = NULL;
13466 int *pack_fds = NULL;
13468 memset(&upa, 0, sizeof(upa));
13470 #ifndef PROFILE
13471 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
13472 "unveil", NULL) == -1)
13473 err(1, "pledge");
13474 #endif
13476 while ((ch = getopt(argc, argv, "aCcMn")) != -1) {
13477 switch (ch) {
13478 case 'a':
13479 abort_merge = 1;
13480 break;
13481 case 'C':
13482 allow_conflict = 1;
13483 break;
13484 case 'c':
13485 continue_merge = 1;
13486 break;
13487 case 'M':
13488 prefer_fast_forward = 0;
13489 break;
13490 case 'n':
13491 interrupt_merge = 1;
13492 break;
13493 default:
13494 usage_merge();
13495 /* NOTREACHED */
13499 argc -= optind;
13500 argv += optind;
13502 if (abort_merge) {
13503 if (continue_merge)
13504 option_conflict('a', 'c');
13505 if (!prefer_fast_forward)
13506 option_conflict('a', 'M');
13507 if (interrupt_merge)
13508 option_conflict('a', 'n');
13509 } else if (continue_merge) {
13510 if (!prefer_fast_forward)
13511 option_conflict('c', 'M');
13512 if (interrupt_merge)
13513 option_conflict('c', 'n');
13515 if (allow_conflict) {
13516 if (!continue_merge)
13517 errx(1, "-C option requires -c");
13519 if (abort_merge || continue_merge) {
13520 if (argc != 0)
13521 usage_merge();
13522 } else if (argc != 1)
13523 usage_merge();
13525 cwd = getcwd(NULL, 0);
13526 if (cwd == NULL) {
13527 error = got_error_from_errno("getcwd");
13528 goto done;
13531 error = got_repo_pack_fds_open(&pack_fds);
13532 if (error != NULL)
13533 goto done;
13535 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
13536 if (error) {
13537 if (error->code == GOT_ERR_NOT_WORKTREE)
13538 error = wrap_not_worktree_error(error,
13539 "merge", cwd);
13540 goto done;
13543 error = get_gitconfig_path(&gitconfig_path);
13544 if (error)
13545 goto done;
13546 error = got_repo_open(&repo,
13547 worktree ? got_worktree_get_repo_path(worktree) : cwd,
13548 gitconfig_path, pack_fds);
13549 if (error != NULL)
13550 goto done;
13552 if (worktree != NULL) {
13553 error = worktree_has_logmsg_ref("merge", worktree, repo);
13554 if (error)
13555 goto done;
13558 error = apply_unveil(got_repo_get_path(repo), 0,
13559 worktree ? got_worktree_get_root_path(worktree) : NULL);
13560 if (error)
13561 goto done;
13563 error = check_rebase_or_histedit_in_progress(worktree);
13564 if (error)
13565 goto done;
13567 error = got_worktree_merge_in_progress(&merge_in_progress, worktree,
13568 repo);
13569 if (error)
13570 goto done;
13572 if (merge_in_progress && !(abort_merge || continue_merge)) {
13573 error = got_error(GOT_ERR_MERGE_BUSY);
13574 goto done;
13577 if (!merge_in_progress && (abort_merge || continue_merge)) {
13578 error = got_error(GOT_ERR_NOT_MERGING);
13579 goto done;
13582 if (abort_merge) {
13583 error = got_worktree_merge_continue(&branch_name,
13584 &branch_tip, &fileindex, worktree, repo);
13585 if (error)
13586 goto done;
13587 error = got_worktree_merge_abort(worktree, fileindex, repo,
13588 abort_progress, &upa);
13589 if (error)
13590 goto done;
13591 printf("Merge of %s aborted\n", branch_name);
13592 goto done; /* nothing else to do */
13595 if (strncmp(got_worktree_get_head_ref_name(worktree),
13596 "refs/heads/", 11) != 0) {
13597 error = got_error_fmt(GOT_ERR_COMMIT_BRANCH,
13598 "work tree's current branch %s is outside the "
13599 "\"refs/heads/\" reference namespace; "
13600 "update -b required",
13601 got_worktree_get_head_ref_name(worktree));
13602 goto done;
13605 error = get_author(&author, repo, worktree);
13606 if (error)
13607 goto done;
13609 error = got_ref_open(&wt_branch, repo,
13610 got_worktree_get_head_ref_name(worktree), 0);
13611 if (error)
13612 goto done;
13613 error = got_ref_resolve(&wt_branch_tip, repo, wt_branch);
13614 if (error)
13615 goto done;
13617 if (continue_merge) {
13618 struct got_object_id *base_commit_id;
13619 base_commit_id = got_worktree_get_base_commit_id(worktree);
13620 if (got_object_id_cmp(wt_branch_tip, base_commit_id) != 0) {
13621 error = got_error(GOT_ERR_MERGE_COMMIT_OUT_OF_DATE);
13622 goto done;
13624 error = got_worktree_merge_continue(&branch_name,
13625 &branch_tip, &fileindex, worktree, repo);
13626 if (error)
13627 goto done;
13628 } else {
13629 error = got_ref_open(&branch, repo, argv[0], 0);
13630 if (error != NULL)
13631 goto done;
13632 branch_name = strdup(got_ref_get_name(branch));
13633 if (branch_name == NULL) {
13634 error = got_error_from_errno("strdup");
13635 goto done;
13637 error = got_ref_resolve(&branch_tip, repo, branch);
13638 if (error)
13639 goto done;
13642 error = got_commit_graph_find_youngest_common_ancestor(&yca_id,
13643 wt_branch_tip, branch_tip, 0, 0, repo,
13644 check_cancelled, NULL);
13645 if (error && error->code != GOT_ERR_ANCESTRY)
13646 goto done;
13648 if (!continue_merge) {
13649 error = check_path_prefix(wt_branch_tip, branch_tip,
13650 got_worktree_get_path_prefix(worktree),
13651 GOT_ERR_MERGE_PATH, repo);
13652 if (error)
13653 goto done;
13654 error = got_worktree_merge_prepare(&fileindex, worktree, repo);
13655 if (error)
13656 goto done;
13657 if (prefer_fast_forward && yca_id &&
13658 got_object_id_cmp(wt_branch_tip, yca_id) == 0) {
13659 struct got_pathlist_head paths;
13660 if (interrupt_merge) {
13661 error = got_error_fmt(GOT_ERR_BAD_OPTION,
13662 "there are no changes to merge since %s "
13663 "is already based on %s; merge cannot be "
13664 "interrupted for amending; -n",
13665 branch_name, got_ref_get_name(wt_branch));
13666 goto done;
13668 printf("Forwarding %s to %s\n",
13669 got_ref_get_name(wt_branch), branch_name);
13670 error = got_ref_change_ref(wt_branch, branch_tip);
13671 if (error)
13672 goto done;
13673 error = got_ref_write(wt_branch, repo);
13674 if (error)
13675 goto done;
13676 error = got_worktree_set_base_commit_id(worktree, repo,
13677 branch_tip);
13678 if (error)
13679 goto done;
13680 TAILQ_INIT(&paths);
13681 error = got_pathlist_append(&paths, "", NULL);
13682 if (error)
13683 goto done;
13684 error = got_worktree_checkout_files(worktree,
13685 &paths, repo, update_progress, &upa,
13686 check_cancelled, NULL);
13687 got_pathlist_free(&paths, GOT_PATHLIST_FREE_NONE);
13688 if (error)
13689 goto done;
13690 if (upa.did_something) {
13691 char *id_str;
13692 error = got_object_id_str(&id_str, branch_tip);
13693 if (error)
13694 goto done;
13695 printf("Updated to commit %s\n", id_str);
13696 free(id_str);
13697 } else
13698 printf("Already up-to-date\n");
13699 print_update_progress_stats(&upa);
13700 goto done;
13702 error = got_worktree_merge_write_refs(worktree, branch, repo);
13703 if (error)
13704 goto done;
13706 error = got_worktree_merge_branch(worktree, fileindex,
13707 yca_id, branch_tip, repo, update_progress, &upa,
13708 check_cancelled, NULL);
13709 if (error)
13710 goto done;
13711 print_merge_progress_stats(&upa);
13712 if (!upa.did_something) {
13713 error = got_worktree_merge_abort(worktree, fileindex,
13714 repo, abort_progress, &upa);
13715 if (error)
13716 goto done;
13717 printf("Already up-to-date\n");
13718 goto done;
13722 if (interrupt_merge) {
13723 error = got_worktree_merge_postpone(worktree, fileindex);
13724 if (error)
13725 goto done;
13726 printf("Merge of %s interrupted on request\n", branch_name);
13727 } else if (upa.conflicts > 0 || upa.missing > 0 ||
13728 upa.not_deleted > 0 || upa.unversioned > 0) {
13729 error = got_worktree_merge_postpone(worktree, fileindex);
13730 if (error)
13731 goto done;
13732 if (upa.conflicts > 0 && upa.missing == 0 &&
13733 upa.not_deleted == 0 && upa.unversioned == 0) {
13734 error = got_error_msg(GOT_ERR_CONFLICTS,
13735 "conflicts must be resolved before merging "
13736 "can continue");
13737 } else if (upa.conflicts > 0) {
13738 error = got_error_msg(GOT_ERR_CONFLICTS,
13739 "conflicts must be resolved before merging "
13740 "can continue; changes destined for some "
13741 "files were not yet merged and "
13742 "should be merged manually if required before the "
13743 "merge operation is continued");
13744 } else {
13745 error = got_error_msg(GOT_ERR_CONFLICTS,
13746 "changes destined for some "
13747 "files were not yet merged and should be "
13748 "merged manually if required before the "
13749 "merge operation is continued");
13751 goto done;
13752 } else {
13753 error = got_worktree_merge_commit(&merge_commit_id, worktree,
13754 fileindex, author, NULL, 1, branch_tip, branch_name,
13755 allow_conflict, repo, continue_merge ? print_status : NULL,
13756 NULL);
13757 if (error)
13758 goto done;
13759 error = got_worktree_merge_complete(worktree, fileindex, repo);
13760 if (error)
13761 goto done;
13762 error = got_object_id_str(&id_str, merge_commit_id);
13763 if (error)
13764 goto done;
13765 printf("Merged %s into %s: %s\n", branch_name,
13766 got_worktree_get_head_ref_name(worktree),
13767 id_str);
13770 done:
13771 free(gitconfig_path);
13772 free(id_str);
13773 free(merge_commit_id);
13774 free(author);
13775 free(branch_tip);
13776 free(branch_name);
13777 free(yca_id);
13778 if (branch)
13779 got_ref_close(branch);
13780 if (wt_branch)
13781 got_ref_close(wt_branch);
13782 if (worktree)
13783 got_worktree_close(worktree);
13784 if (repo) {
13785 const struct got_error *close_err = got_repo_close(repo);
13786 if (error == NULL)
13787 error = close_err;
13789 if (pack_fds) {
13790 const struct got_error *pack_err =
13791 got_repo_pack_fds_close(pack_fds);
13792 if (error == NULL)
13793 error = pack_err;
13795 return error;
13798 __dead static void
13799 usage_stage(void)
13801 fprintf(stderr, "usage: %s stage [-lpS] [-F response-script] "
13802 "[path ...]\n", getprogname());
13803 exit(1);
13806 static const struct got_error *
13807 print_stage(void *arg, unsigned char status, unsigned char staged_status,
13808 const char *path, struct got_object_id *blob_id,
13809 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
13810 int dirfd, const char *de_name)
13812 const struct got_error *err = NULL;
13813 char *id_str = NULL;
13815 if (staged_status != GOT_STATUS_ADD &&
13816 staged_status != GOT_STATUS_MODIFY &&
13817 staged_status != GOT_STATUS_DELETE)
13818 return NULL;
13820 if (staged_status == GOT_STATUS_ADD ||
13821 staged_status == GOT_STATUS_MODIFY)
13822 err = got_object_id_str(&id_str, staged_blob_id);
13823 else
13824 err = got_object_id_str(&id_str, blob_id);
13825 if (err)
13826 return err;
13828 printf("%s %c %s\n", id_str, staged_status, path);
13829 free(id_str);
13830 return NULL;
13833 static const struct got_error *
13834 cmd_stage(int argc, char *argv[])
13836 const struct got_error *error = NULL;
13837 struct got_repository *repo = NULL;
13838 struct got_worktree *worktree = NULL;
13839 char *cwd = NULL;
13840 struct got_pathlist_head paths;
13841 int ch, list_stage = 0, pflag = 0, allow_bad_symlinks = 0;
13842 FILE *patch_script_file = NULL;
13843 const char *patch_script_path = NULL;
13844 struct choose_patch_arg cpa;
13845 int *pack_fds = NULL;
13847 TAILQ_INIT(&paths);
13849 #ifndef PROFILE
13850 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
13851 "unveil", NULL) == -1)
13852 err(1, "pledge");
13853 #endif
13855 while ((ch = getopt(argc, argv, "F:lpS")) != -1) {
13856 switch (ch) {
13857 case 'F':
13858 patch_script_path = optarg;
13859 break;
13860 case 'l':
13861 list_stage = 1;
13862 break;
13863 case 'p':
13864 pflag = 1;
13865 break;
13866 case 'S':
13867 allow_bad_symlinks = 1;
13868 break;
13869 default:
13870 usage_stage();
13871 /* NOTREACHED */
13875 argc -= optind;
13876 argv += optind;
13878 if (list_stage && (pflag || patch_script_path))
13879 errx(1, "-l option cannot be used with other options");
13880 if (patch_script_path && !pflag)
13881 errx(1, "-F option can only be used together with -p option");
13883 cwd = getcwd(NULL, 0);
13884 if (cwd == NULL) {
13885 error = got_error_from_errno("getcwd");
13886 goto done;
13889 error = got_repo_pack_fds_open(&pack_fds);
13890 if (error != NULL)
13891 goto done;
13893 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
13894 if (error) {
13895 if (error->code == GOT_ERR_NOT_WORKTREE)
13896 error = wrap_not_worktree_error(error, "stage", cwd);
13897 goto done;
13900 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
13901 NULL, pack_fds);
13902 if (error != NULL)
13903 goto done;
13905 if (patch_script_path) {
13906 patch_script_file = fopen(patch_script_path, "re");
13907 if (patch_script_file == NULL) {
13908 error = got_error_from_errno2("fopen",
13909 patch_script_path);
13910 goto done;
13913 error = apply_unveil(got_repo_get_path(repo), 0,
13914 got_worktree_get_root_path(worktree));
13915 if (error)
13916 goto done;
13918 error = check_merge_in_progress(worktree, repo);
13919 if (error)
13920 goto done;
13922 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
13923 if (error)
13924 goto done;
13926 if (list_stage)
13927 error = got_worktree_status(worktree, &paths, repo, 0,
13928 print_stage, NULL, check_cancelled, NULL);
13929 else {
13930 cpa.patch_script_file = patch_script_file;
13931 cpa.action = "stage";
13932 error = got_worktree_stage(worktree, &paths,
13933 pflag ? NULL : print_status, NULL,
13934 pflag ? choose_patch : NULL, &cpa,
13935 allow_bad_symlinks, repo);
13937 done:
13938 if (patch_script_file && fclose(patch_script_file) == EOF &&
13939 error == NULL)
13940 error = got_error_from_errno2("fclose", patch_script_path);
13941 if (repo) {
13942 const struct got_error *close_err = got_repo_close(repo);
13943 if (error == NULL)
13944 error = close_err;
13946 if (worktree)
13947 got_worktree_close(worktree);
13948 if (pack_fds) {
13949 const struct got_error *pack_err =
13950 got_repo_pack_fds_close(pack_fds);
13951 if (error == NULL)
13952 error = pack_err;
13954 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
13955 free(cwd);
13956 return error;
13959 __dead static void
13960 usage_unstage(void)
13962 fprintf(stderr, "usage: %s unstage [-p] [-F response-script] "
13963 "[path ...]\n", getprogname());
13964 exit(1);
13968 static const struct got_error *
13969 cmd_unstage(int argc, char *argv[])
13971 const struct got_error *error = NULL;
13972 struct got_repository *repo = NULL;
13973 struct got_worktree *worktree = NULL;
13974 char *cwd = NULL;
13975 struct got_pathlist_head paths;
13976 int ch, pflag = 0;
13977 struct got_update_progress_arg upa;
13978 FILE *patch_script_file = NULL;
13979 const char *patch_script_path = NULL;
13980 struct choose_patch_arg cpa;
13981 int *pack_fds = NULL;
13983 TAILQ_INIT(&paths);
13985 #ifndef PROFILE
13986 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
13987 "unveil", NULL) == -1)
13988 err(1, "pledge");
13989 #endif
13991 while ((ch = getopt(argc, argv, "F:p")) != -1) {
13992 switch (ch) {
13993 case 'F':
13994 patch_script_path = optarg;
13995 break;
13996 case 'p':
13997 pflag = 1;
13998 break;
13999 default:
14000 usage_unstage();
14001 /* NOTREACHED */
14005 argc -= optind;
14006 argv += optind;
14008 if (patch_script_path && !pflag)
14009 errx(1, "-F option can only be used together with -p option");
14011 cwd = getcwd(NULL, 0);
14012 if (cwd == NULL) {
14013 error = got_error_from_errno("getcwd");
14014 goto done;
14017 error = got_repo_pack_fds_open(&pack_fds);
14018 if (error != NULL)
14019 goto done;
14021 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
14022 if (error) {
14023 if (error->code == GOT_ERR_NOT_WORKTREE)
14024 error = wrap_not_worktree_error(error, "unstage", cwd);
14025 goto done;
14028 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
14029 NULL, pack_fds);
14030 if (error != NULL)
14031 goto done;
14033 if (patch_script_path) {
14034 patch_script_file = fopen(patch_script_path, "re");
14035 if (patch_script_file == NULL) {
14036 error = got_error_from_errno2("fopen",
14037 patch_script_path);
14038 goto done;
14042 error = apply_unveil(got_repo_get_path(repo), 0,
14043 got_worktree_get_root_path(worktree));
14044 if (error)
14045 goto done;
14047 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
14048 if (error)
14049 goto done;
14051 cpa.patch_script_file = patch_script_file;
14052 cpa.action = "unstage";
14053 memset(&upa, 0, sizeof(upa));
14054 error = got_worktree_unstage(worktree, &paths, update_progress,
14055 &upa, pflag ? choose_patch : NULL, &cpa, repo);
14056 if (!error)
14057 print_merge_progress_stats(&upa);
14058 done:
14059 if (patch_script_file && fclose(patch_script_file) == EOF &&
14060 error == NULL)
14061 error = got_error_from_errno2("fclose", patch_script_path);
14062 if (repo) {
14063 const struct got_error *close_err = got_repo_close(repo);
14064 if (error == NULL)
14065 error = close_err;
14067 if (worktree)
14068 got_worktree_close(worktree);
14069 if (pack_fds) {
14070 const struct got_error *pack_err =
14071 got_repo_pack_fds_close(pack_fds);
14072 if (error == NULL)
14073 error = pack_err;
14075 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
14076 free(cwd);
14077 return error;
14080 __dead static void
14081 usage_cat(void)
14083 fprintf(stderr, "usage: %s cat [-P] [-c commit] [-r repository-path] "
14084 "arg ...\n", getprogname());
14085 exit(1);
14088 static const struct got_error *
14089 cat_blob(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
14091 const struct got_error *err;
14092 struct got_blob_object *blob;
14093 int fd = -1;
14095 fd = got_opentempfd();
14096 if (fd == -1)
14097 return got_error_from_errno("got_opentempfd");
14099 err = got_object_open_as_blob(&blob, repo, id, 8192, fd);
14100 if (err)
14101 goto done;
14103 err = got_object_blob_dump_to_file(NULL, NULL, NULL, outfile, blob);
14104 done:
14105 if (fd != -1 && close(fd) == -1 && err == NULL)
14106 err = got_error_from_errno("close");
14107 if (blob)
14108 got_object_blob_close(blob);
14109 return err;
14112 static const struct got_error *
14113 cat_tree(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
14115 const struct got_error *err;
14116 struct got_tree_object *tree;
14117 int nentries, i;
14119 err = got_object_open_as_tree(&tree, repo, id);
14120 if (err)
14121 return err;
14123 nentries = got_object_tree_get_nentries(tree);
14124 for (i = 0; i < nentries; i++) {
14125 struct got_tree_entry *te;
14126 char *id_str;
14127 if (sigint_received || sigpipe_received)
14128 break;
14129 te = got_object_tree_get_entry(tree, i);
14130 err = got_object_id_str(&id_str, got_tree_entry_get_id(te));
14131 if (err)
14132 break;
14133 fprintf(outfile, "%s %.7o %s\n", id_str,
14134 got_tree_entry_get_mode(te),
14135 got_tree_entry_get_name(te));
14136 free(id_str);
14139 got_object_tree_close(tree);
14140 return err;
14143 static const struct got_error *
14144 cat_commit(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
14146 const struct got_error *err;
14147 struct got_commit_object *commit;
14148 const struct got_object_id_queue *parent_ids;
14149 struct got_object_qid *pid;
14150 char *id_str = NULL;
14151 const char *logmsg = NULL;
14152 char gmtoff[6];
14154 err = got_object_open_as_commit(&commit, repo, id);
14155 if (err)
14156 return err;
14158 err = got_object_id_str(&id_str, got_object_commit_get_tree_id(commit));
14159 if (err)
14160 goto done;
14162 fprintf(outfile, "%s%s\n", GOT_COMMIT_LABEL_TREE, id_str);
14163 parent_ids = got_object_commit_get_parent_ids(commit);
14164 fprintf(outfile, "numparents %d\n",
14165 got_object_commit_get_nparents(commit));
14166 STAILQ_FOREACH(pid, parent_ids, entry) {
14167 char *pid_str;
14168 err = got_object_id_str(&pid_str, &pid->id);
14169 if (err)
14170 goto done;
14171 fprintf(outfile, "%s%s\n", GOT_COMMIT_LABEL_PARENT, pid_str);
14172 free(pid_str);
14174 got_date_format_gmtoff(gmtoff, sizeof(gmtoff),
14175 got_object_commit_get_author_gmtoff(commit));
14176 fprintf(outfile, "%s%s %lld %s\n", GOT_COMMIT_LABEL_AUTHOR,
14177 got_object_commit_get_author(commit),
14178 (long long)got_object_commit_get_author_time(commit),
14179 gmtoff);
14181 got_date_format_gmtoff(gmtoff, sizeof(gmtoff),
14182 got_object_commit_get_committer_gmtoff(commit));
14183 fprintf(outfile, "%s%s %lld %s\n", GOT_COMMIT_LABEL_COMMITTER,
14184 got_object_commit_get_committer(commit),
14185 (long long)got_object_commit_get_committer_time(commit),
14186 gmtoff);
14188 logmsg = got_object_commit_get_logmsg_raw(commit);
14189 fprintf(outfile, "messagelen %zd\n", strlen(logmsg));
14190 fprintf(outfile, "%s", logmsg);
14191 done:
14192 free(id_str);
14193 got_object_commit_close(commit);
14194 return err;
14197 static const struct got_error *
14198 cat_tag(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
14200 const struct got_error *err;
14201 struct got_tag_object *tag;
14202 char *id_str = NULL;
14203 const char *tagmsg = NULL;
14204 char gmtoff[6];
14206 err = got_object_open_as_tag(&tag, repo, id);
14207 if (err)
14208 return err;
14210 err = got_object_id_str(&id_str, got_object_tag_get_object_id(tag));
14211 if (err)
14212 goto done;
14214 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_OBJECT, id_str);
14216 switch (got_object_tag_get_object_type(tag)) {
14217 case GOT_OBJ_TYPE_BLOB:
14218 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
14219 GOT_OBJ_LABEL_BLOB);
14220 break;
14221 case GOT_OBJ_TYPE_TREE:
14222 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
14223 GOT_OBJ_LABEL_TREE);
14224 break;
14225 case GOT_OBJ_TYPE_COMMIT:
14226 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
14227 GOT_OBJ_LABEL_COMMIT);
14228 break;
14229 case GOT_OBJ_TYPE_TAG:
14230 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
14231 GOT_OBJ_LABEL_TAG);
14232 break;
14233 default:
14234 break;
14237 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TAG,
14238 got_object_tag_get_name(tag));
14240 got_date_format_gmtoff(gmtoff, sizeof(gmtoff),
14241 got_object_tag_get_tagger_gmtoff(tag));
14242 fprintf(outfile, "%s%s %lld %s\n", GOT_TAG_LABEL_TAGGER,
14243 got_object_tag_get_tagger(tag),
14244 (long long)got_object_tag_get_tagger_time(tag),
14245 gmtoff);
14247 tagmsg = got_object_tag_get_message(tag);
14248 fprintf(outfile, "messagelen %zd\n", strlen(tagmsg));
14249 fprintf(outfile, "%s", tagmsg);
14250 done:
14251 free(id_str);
14252 got_object_tag_close(tag);
14253 return err;
14256 static const struct got_error *
14257 cmd_cat(int argc, char *argv[])
14259 const struct got_error *error;
14260 struct got_repository *repo = NULL;
14261 struct got_worktree *worktree = NULL;
14262 char *cwd = NULL, *repo_path = NULL, *label = NULL;
14263 char *keyword_idstr = NULL;
14264 const char *commit_id_str = NULL;
14265 struct got_object_id *id = NULL, *commit_id = NULL;
14266 struct got_commit_object *commit = NULL;
14267 int ch, obj_type, i, force_path = 0;
14268 struct got_reflist_head refs;
14269 int *pack_fds = NULL;
14271 TAILQ_INIT(&refs);
14273 #ifndef PROFILE
14274 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
14275 NULL) == -1)
14276 err(1, "pledge");
14277 #endif
14279 while ((ch = getopt(argc, argv, "c:Pr:")) != -1) {
14280 switch (ch) {
14281 case 'c':
14282 commit_id_str = optarg;
14283 break;
14284 case 'P':
14285 force_path = 1;
14286 break;
14287 case 'r':
14288 repo_path = realpath(optarg, NULL);
14289 if (repo_path == NULL)
14290 return got_error_from_errno2("realpath",
14291 optarg);
14292 got_path_strip_trailing_slashes(repo_path);
14293 break;
14294 default:
14295 usage_cat();
14296 /* NOTREACHED */
14300 argc -= optind;
14301 argv += optind;
14303 cwd = getcwd(NULL, 0);
14304 if (cwd == NULL) {
14305 error = got_error_from_errno("getcwd");
14306 goto done;
14309 error = got_repo_pack_fds_open(&pack_fds);
14310 if (error != NULL)
14311 goto done;
14313 if (repo_path == NULL) {
14314 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
14315 if (error && error->code != GOT_ERR_NOT_WORKTREE)
14316 goto done;
14317 if (worktree) {
14318 repo_path = strdup(
14319 got_worktree_get_repo_path(worktree));
14320 if (repo_path == NULL) {
14321 error = got_error_from_errno("strdup");
14322 goto done;
14325 if (commit_id_str == NULL) {
14326 /* Release work tree lock. */
14327 got_worktree_close(worktree);
14328 worktree = NULL;
14333 if (repo_path == NULL) {
14334 repo_path = strdup(cwd);
14335 if (repo_path == NULL)
14336 return got_error_from_errno("strdup");
14339 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
14340 free(repo_path);
14341 if (error != NULL)
14342 goto done;
14344 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
14345 if (error)
14346 goto done;
14348 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
14349 if (error)
14350 goto done;
14352 if (commit_id_str != NULL) {
14353 error = got_keyword_to_idstr(&keyword_idstr, commit_id_str,
14354 repo, worktree);
14355 if (error != NULL)
14356 goto done;
14357 if (keyword_idstr != NULL)
14358 commit_id_str = keyword_idstr;
14359 if (worktree != NULL) {
14360 got_worktree_close(worktree);
14361 worktree = NULL;
14363 } else
14364 commit_id_str = GOT_REF_HEAD;
14365 error = got_repo_match_object_id(&commit_id, NULL,
14366 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
14367 if (error)
14368 goto done;
14370 error = got_object_open_as_commit(&commit, repo, commit_id);
14371 if (error)
14372 goto done;
14374 for (i = 0; i < argc; i++) {
14375 if (force_path) {
14376 error = got_object_id_by_path(&id, repo, commit,
14377 argv[i]);
14378 if (error)
14379 break;
14380 } else {
14381 error = got_repo_match_object_id(&id, &label, argv[i],
14382 GOT_OBJ_TYPE_ANY, NULL /* do not resolve tags */,
14383 repo);
14384 if (error) {
14385 if (error->code != GOT_ERR_BAD_OBJ_ID_STR &&
14386 error->code != GOT_ERR_NOT_REF)
14387 break;
14388 error = got_object_id_by_path(&id, repo,
14389 commit, argv[i]);
14390 if (error)
14391 break;
14395 error = got_object_get_type(&obj_type, repo, id);
14396 if (error)
14397 break;
14399 switch (obj_type) {
14400 case GOT_OBJ_TYPE_BLOB:
14401 error = cat_blob(id, repo, stdout);
14402 break;
14403 case GOT_OBJ_TYPE_TREE:
14404 error = cat_tree(id, repo, stdout);
14405 break;
14406 case GOT_OBJ_TYPE_COMMIT:
14407 error = cat_commit(id, repo, stdout);
14408 break;
14409 case GOT_OBJ_TYPE_TAG:
14410 error = cat_tag(id, repo, stdout);
14411 break;
14412 default:
14413 error = got_error(GOT_ERR_OBJ_TYPE);
14414 break;
14416 if (error)
14417 break;
14418 free(label);
14419 label = NULL;
14420 free(id);
14421 id = NULL;
14423 done:
14424 free(label);
14425 free(id);
14426 free(commit_id);
14427 free(keyword_idstr);
14428 if (commit)
14429 got_object_commit_close(commit);
14430 if (worktree)
14431 got_worktree_close(worktree);
14432 if (repo) {
14433 const struct got_error *close_err = got_repo_close(repo);
14434 if (error == NULL)
14435 error = close_err;
14437 if (pack_fds) {
14438 const struct got_error *pack_err =
14439 got_repo_pack_fds_close(pack_fds);
14440 if (error == NULL)
14441 error = pack_err;
14444 got_ref_list_free(&refs);
14445 return error;
14448 __dead static void
14449 usage_info(void)
14451 fprintf(stderr, "usage: %s info [path ...]\n",
14452 getprogname());
14453 exit(1);
14456 static const struct got_error *
14457 print_path_info(void *arg, const char *path, mode_t mode, time_t mtime,
14458 struct got_object_id *blob_id, struct got_object_id *staged_blob_id,
14459 struct got_object_id *commit_id)
14461 const struct got_error *err = NULL;
14462 char *id_str = NULL;
14463 char datebuf[128];
14464 struct tm mytm, *tm;
14465 struct got_pathlist_head *paths = arg;
14466 struct got_pathlist_entry *pe;
14469 * Clear error indication from any of the path arguments which
14470 * would cause this file index entry to be displayed.
14472 TAILQ_FOREACH(pe, paths, entry) {
14473 if (got_path_cmp(path, pe->path, strlen(path),
14474 pe->path_len) == 0 ||
14475 got_path_is_child(path, pe->path, pe->path_len))
14476 pe->data = NULL; /* no error */
14479 printf(GOT_COMMIT_SEP_STR);
14480 if (S_ISLNK(mode))
14481 printf("symlink: %s\n", path);
14482 else if (S_ISREG(mode)) {
14483 printf("file: %s\n", path);
14484 printf("mode: %o\n", mode & (S_IRWXU | S_IRWXG | S_IRWXO));
14485 } else if (S_ISDIR(mode))
14486 printf("directory: %s\n", path);
14487 else
14488 printf("something: %s\n", path);
14490 tm = localtime_r(&mtime, &mytm);
14491 if (tm == NULL)
14492 return NULL;
14493 if (strftime(datebuf, sizeof(datebuf), "%c %Z", tm) == 0)
14494 return got_error(GOT_ERR_NO_SPACE);
14495 printf("timestamp: %s\n", datebuf);
14497 if (blob_id) {
14498 err = got_object_id_str(&id_str, blob_id);
14499 if (err)
14500 return err;
14501 printf("based on blob: %s\n", id_str);
14502 free(id_str);
14505 if (staged_blob_id) {
14506 err = got_object_id_str(&id_str, staged_blob_id);
14507 if (err)
14508 return err;
14509 printf("based on staged blob: %s\n", id_str);
14510 free(id_str);
14513 if (commit_id) {
14514 err = got_object_id_str(&id_str, commit_id);
14515 if (err)
14516 return err;
14517 printf("based on commit: %s\n", id_str);
14518 free(id_str);
14521 return NULL;
14524 static const struct got_error *
14525 cmd_info(int argc, char *argv[])
14527 const struct got_error *error = NULL;
14528 struct got_worktree *worktree = NULL;
14529 char *cwd = NULL, *id_str = NULL;
14530 struct got_pathlist_head paths;
14531 char *uuidstr = NULL;
14532 int ch, show_files = 0;
14534 TAILQ_INIT(&paths);
14536 #ifndef PROFILE
14537 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
14538 NULL) == -1)
14539 err(1, "pledge");
14540 #endif
14542 while ((ch = getopt(argc, argv, "")) != -1) {
14543 switch (ch) {
14544 default:
14545 usage_info();
14546 /* NOTREACHED */
14550 argc -= optind;
14551 argv += optind;
14553 cwd = getcwd(NULL, 0);
14554 if (cwd == NULL) {
14555 error = got_error_from_errno("getcwd");
14556 goto done;
14559 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
14560 if (error) {
14561 if (error->code == GOT_ERR_NOT_WORKTREE)
14562 error = wrap_not_worktree_error(error, "info", cwd);
14563 goto done;
14566 #ifndef PROFILE
14567 /* Remove "wpath cpath proc exec sendfd" promises. */
14568 if (pledge("stdio rpath flock unveil", NULL) == -1)
14569 err(1, "pledge");
14570 #endif
14571 error = apply_unveil(NULL, 0, got_worktree_get_root_path(worktree));
14572 if (error)
14573 goto done;
14575 if (argc >= 1) {
14576 error = get_worktree_paths_from_argv(&paths, argc, argv,
14577 worktree);
14578 if (error)
14579 goto done;
14580 show_files = 1;
14583 error = got_object_id_str(&id_str,
14584 got_worktree_get_base_commit_id(worktree));
14585 if (error)
14586 goto done;
14588 error = got_worktree_get_uuid(&uuidstr, worktree);
14589 if (error)
14590 goto done;
14592 printf("work tree: %s\n", got_worktree_get_root_path(worktree));
14593 printf("work tree base commit: %s\n", id_str);
14594 printf("work tree path prefix: %s\n",
14595 got_worktree_get_path_prefix(worktree));
14596 printf("work tree branch reference: %s\n",
14597 got_worktree_get_head_ref_name(worktree));
14598 printf("work tree UUID: %s\n", uuidstr);
14599 printf("repository: %s\n", got_worktree_get_repo_path(worktree));
14601 if (show_files) {
14602 struct got_pathlist_entry *pe;
14603 TAILQ_FOREACH(pe, &paths, entry) {
14604 if (pe->path_len == 0)
14605 continue;
14607 * Assume this path will fail. This will be corrected
14608 * in print_path_info() in case the path does suceeed.
14610 pe->data = (void *)got_error(GOT_ERR_BAD_PATH);
14612 error = got_worktree_path_info(worktree, &paths,
14613 print_path_info, &paths, check_cancelled, NULL);
14614 if (error)
14615 goto done;
14616 TAILQ_FOREACH(pe, &paths, entry) {
14617 if (pe->data != NULL) {
14618 const struct got_error *perr;
14620 perr = pe->data;
14621 error = got_error_fmt(perr->code, "%s",
14622 pe->path);
14623 break;
14627 done:
14628 if (worktree)
14629 got_worktree_close(worktree);
14630 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
14631 free(cwd);
14632 free(id_str);
14633 free(uuidstr);
14634 return error;