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 <sys/queue.h>
20 #include <sys/time.h>
21 #include <sys/types.h>
22 #include <sys/stat.h>
23 #include <sys/wait.h>
25 #include <err.h>
26 #include <errno.h>
27 #include <fcntl.h>
28 #include <limits.h>
29 #include <locale.h>
30 #include <ctype.h>
31 #include <sha1.h>
32 #include <signal.h>
33 #include <stdio.h>
34 #include <stdlib.h>
35 #include <string.h>
36 #include <unistd.h>
37 #include <libgen.h>
38 #include <time.h>
39 #include <paths.h>
40 #include <regex.h>
41 #include <getopt.h>
42 #include <util.h>
44 #include "got_version.h"
45 #include "got_error.h"
46 #include "got_object.h"
47 #include "got_reference.h"
48 #include "got_repository.h"
49 #include "got_path.h"
50 #include "got_cancel.h"
51 #include "got_worktree.h"
52 #include "got_diff.h"
53 #include "got_commit_graph.h"
54 #include "got_fetch.h"
55 #include "got_send.h"
56 #include "got_blame.h"
57 #include "got_privsep.h"
58 #include "got_opentemp.h"
59 #include "got_gotconfig.h"
60 #include "got_dial.h"
61 #include "got_patch.h"
62 #include "got_sigs.h"
63 #include "got_date.h"
65 #ifndef nitems
66 #define nitems(_a) (sizeof((_a)) / sizeof((_a)[0]))
67 #endif
69 static volatile sig_atomic_t sigint_received;
70 static volatile sig_atomic_t sigpipe_received;
72 static void
73 catch_sigint(int signo)
74 {
75 sigint_received = 1;
76 }
78 static void
79 catch_sigpipe(int signo)
80 {
81 sigpipe_received = 1;
82 }
85 struct got_cmd {
86 const char *cmd_name;
87 const struct got_error *(*cmd_main)(int, char *[]);
88 void (*cmd_usage)(void);
89 const char *cmd_alias;
90 };
92 __dead static void usage(int, int);
93 __dead static void usage_import(void);
94 __dead static void usage_clone(void);
95 __dead static void usage_fetch(void);
96 __dead static void usage_checkout(void);
97 __dead static void usage_update(void);
98 __dead static void usage_log(void);
99 __dead static void usage_diff(void);
100 __dead static void usage_blame(void);
101 __dead static void usage_tree(void);
102 __dead static void usage_status(void);
103 __dead static void usage_ref(void);
104 __dead static void usage_branch(void);
105 __dead static void usage_tag(void);
106 __dead static void usage_add(void);
107 __dead static void usage_remove(void);
108 __dead static void usage_patch(void);
109 __dead static void usage_revert(void);
110 __dead static void usage_commit(void);
111 __dead static void usage_send(void);
112 __dead static void usage_cherrypick(void);
113 __dead static void usage_backout(void);
114 __dead static void usage_rebase(void);
115 __dead static void usage_histedit(void);
116 __dead static void usage_integrate(void);
117 __dead static void usage_merge(void);
118 __dead static void usage_stage(void);
119 __dead static void usage_unstage(void);
120 __dead static void usage_cat(void);
121 __dead static void usage_info(void);
123 static const struct got_error* cmd_import(int, char *[]);
124 static const struct got_error* cmd_clone(int, char *[]);
125 static const struct got_error* cmd_fetch(int, char *[]);
126 static const struct got_error* cmd_checkout(int, char *[]);
127 static const struct got_error* cmd_update(int, char *[]);
128 static const struct got_error* cmd_log(int, char *[]);
129 static const struct got_error* cmd_diff(int, char *[]);
130 static const struct got_error* cmd_blame(int, char *[]);
131 static const struct got_error* cmd_tree(int, char *[]);
132 static const struct got_error* cmd_status(int, char *[]);
133 static const struct got_error* cmd_ref(int, char *[]);
134 static const struct got_error* cmd_branch(int, char *[]);
135 static const struct got_error* cmd_tag(int, char *[]);
136 static const struct got_error* cmd_add(int, char *[]);
137 static const struct got_error* cmd_remove(int, char *[]);
138 static const struct got_error* cmd_patch(int, char *[]);
139 static const struct got_error* cmd_revert(int, char *[]);
140 static const struct got_error* cmd_commit(int, char *[]);
141 static const struct got_error* cmd_send(int, char *[]);
142 static const struct got_error* cmd_cherrypick(int, char *[]);
143 static const struct got_error* cmd_backout(int, char *[]);
144 static const struct got_error* cmd_rebase(int, char *[]);
145 static const struct got_error* cmd_histedit(int, char *[]);
146 static const struct got_error* cmd_integrate(int, char *[]);
147 static const struct got_error* cmd_merge(int, char *[]);
148 static const struct got_error* cmd_stage(int, char *[]);
149 static const struct got_error* cmd_unstage(int, char *[]);
150 static const struct got_error* cmd_cat(int, char *[]);
151 static const struct got_error* cmd_info(int, char *[]);
153 static const struct got_cmd got_commands[] = {
154 { "import", cmd_import, usage_import, "im" },
155 { "clone", cmd_clone, usage_clone, "cl" },
156 { "fetch", cmd_fetch, usage_fetch, "fe" },
157 { "checkout", cmd_checkout, usage_checkout, "co" },
158 { "update", cmd_update, usage_update, "up" },
159 { "log", cmd_log, usage_log, "" },
160 { "diff", cmd_diff, usage_diff, "di" },
161 { "blame", cmd_blame, usage_blame, "bl" },
162 { "tree", cmd_tree, usage_tree, "tr" },
163 { "status", cmd_status, usage_status, "st" },
164 { "ref", cmd_ref, usage_ref, "" },
165 { "branch", cmd_branch, usage_branch, "br" },
166 { "tag", cmd_tag, usage_tag, "" },
167 { "add", cmd_add, usage_add, "" },
168 { "remove", cmd_remove, usage_remove, "rm" },
169 { "patch", cmd_patch, usage_patch, "pa" },
170 { "revert", cmd_revert, usage_revert, "rv" },
171 { "commit", cmd_commit, usage_commit, "ci" },
172 { "send", cmd_send, usage_send, "se" },
173 { "cherrypick", cmd_cherrypick, usage_cherrypick, "cy" },
174 { "backout", cmd_backout, usage_backout, "bo" },
175 { "rebase", cmd_rebase, usage_rebase, "rb" },
176 { "histedit", cmd_histedit, usage_histedit, "he" },
177 { "integrate", cmd_integrate, usage_integrate,"ig" },
178 { "merge", cmd_merge, usage_merge, "mg" },
179 { "stage", cmd_stage, usage_stage, "sg" },
180 { "unstage", cmd_unstage, usage_unstage, "ug" },
181 { "cat", cmd_cat, usage_cat, "" },
182 { "info", cmd_info, usage_info, "" },
183 };
185 static void
186 list_commands(FILE *fp)
188 size_t i;
190 fprintf(fp, "commands:");
191 for (i = 0; i < nitems(got_commands); i++) {
192 const struct got_cmd *cmd = &got_commands[i];
193 fprintf(fp, " %s", cmd->cmd_name);
195 fputc('\n', fp);
198 __dead static void
199 option_conflict(char a, char b)
201 errx(1, "-%c and -%c options are mutually exclusive", a, b);
204 int
205 main(int argc, char *argv[])
207 const struct got_cmd *cmd;
208 size_t i;
209 int ch;
210 int hflag = 0, Vflag = 0;
211 static const struct option longopts[] = {
212 { "version", no_argument, NULL, 'V' },
213 { NULL, 0, NULL, 0 }
214 };
216 setlocale(LC_CTYPE, "");
218 while ((ch = getopt_long(argc, argv, "+hV", longopts, NULL)) != -1) {
219 switch (ch) {
220 case 'h':
221 hflag = 1;
222 break;
223 case 'V':
224 Vflag = 1;
225 break;
226 default:
227 usage(hflag, 1);
228 /* NOTREACHED */
232 argc -= optind;
233 argv += optind;
234 optind = 1;
235 optreset = 1;
237 if (Vflag) {
238 got_version_print_str();
239 return 0;
242 if (argc <= 0)
243 usage(hflag, hflag ? 0 : 1);
245 signal(SIGINT, catch_sigint);
246 signal(SIGPIPE, catch_sigpipe);
248 for (i = 0; i < nitems(got_commands); i++) {
249 const struct got_error *error;
251 cmd = &got_commands[i];
253 if (strcmp(cmd->cmd_name, argv[0]) != 0 &&
254 strcmp(cmd->cmd_alias, argv[0]) != 0)
255 continue;
257 if (hflag)
258 cmd->cmd_usage();
260 error = cmd->cmd_main(argc, argv);
261 if (error && error->code != GOT_ERR_CANCELLED &&
262 error->code != GOT_ERR_PRIVSEP_EXIT &&
263 !(sigpipe_received &&
264 error->code == GOT_ERR_ERRNO && errno == EPIPE) &&
265 !(sigint_received &&
266 error->code == GOT_ERR_ERRNO && errno == EINTR)) {
267 fprintf(stderr, "%s: %s\n", getprogname(), error->msg);
268 return 1;
271 return 0;
274 fprintf(stderr, "%s: unknown command '%s'\n", getprogname(), argv[0]);
275 list_commands(stderr);
276 return 1;
279 __dead static void
280 usage(int hflag, int status)
282 FILE *fp = (status == 0) ? stdout : stderr;
284 fprintf(fp, "usage: %s [-h] [-V | --version] command [arg ...]\n",
285 getprogname());
286 if (hflag)
287 list_commands(fp);
288 exit(status);
291 static const struct got_error *
292 get_editor(char **abspath)
294 const struct got_error *err = NULL;
295 const char *editor;
297 *abspath = NULL;
299 editor = getenv("VISUAL");
300 if (editor == NULL)
301 editor = getenv("EDITOR");
303 if (editor) {
304 err = got_path_find_prog(abspath, editor);
305 if (err)
306 return err;
309 if (*abspath == NULL) {
310 *abspath = strdup("/bin/ed");
311 if (*abspath == NULL)
312 return got_error_from_errno("strdup");
315 return NULL;
318 static const struct got_error *
319 apply_unveil(const char *repo_path, int repo_read_only,
320 const char *worktree_path)
322 const struct got_error *err;
324 #ifdef PROFILE
325 if (unveil("gmon.out", "rwc") != 0)
326 return got_error_from_errno2("unveil", "gmon.out");
327 #endif
328 if (repo_path && unveil(repo_path, repo_read_only ? "r" : "rwc") != 0)
329 return got_error_from_errno2("unveil", repo_path);
331 if (worktree_path && unveil(worktree_path, "rwc") != 0)
332 return got_error_from_errno2("unveil", worktree_path);
334 if (unveil(GOT_TMPDIR_STR, "rwc") != 0)
335 return got_error_from_errno2("unveil", GOT_TMPDIR_STR);
337 err = got_privsep_unveil_exec_helpers();
338 if (err != NULL)
339 return err;
341 if (unveil(NULL, NULL) != 0)
342 return got_error_from_errno("unveil");
344 return NULL;
347 __dead static void
348 usage_import(void)
350 fprintf(stderr, "usage: %s import [-b branch] [-m message] "
351 "[-r repository-path] [-I pattern] path\n", getprogname());
352 exit(1);
355 static int
356 spawn_editor(const char *editor, const char *file)
358 pid_t pid;
359 sig_t sighup, sigint, sigquit;
360 int st = -1;
362 sighup = signal(SIGHUP, SIG_IGN);
363 sigint = signal(SIGINT, SIG_IGN);
364 sigquit = signal(SIGQUIT, SIG_IGN);
366 switch (pid = fork()) {
367 case -1:
368 goto doneediting;
369 case 0:
370 execl(editor, editor, file, (char *)NULL);
371 _exit(127);
374 while (waitpid(pid, &st, 0) == -1)
375 if (errno != EINTR)
376 break;
378 doneediting:
379 (void)signal(SIGHUP, sighup);
380 (void)signal(SIGINT, sigint);
381 (void)signal(SIGQUIT, sigquit);
383 if (!WIFEXITED(st)) {
384 errno = EINTR;
385 return -1;
388 return WEXITSTATUS(st);
391 static const struct got_error *
392 edit_logmsg(char **logmsg, const char *editor, const char *logmsg_path,
393 const char *initial_content, size_t initial_content_len,
394 int require_modification)
396 const struct got_error *err = NULL;
397 char *line = NULL;
398 size_t linesize = 0;
399 ssize_t linelen;
400 struct stat st, st2;
401 FILE *fp = NULL;
402 size_t len, logmsg_len;
403 char *initial_content_stripped = NULL, *buf = NULL, *s;
405 *logmsg = NULL;
407 if (stat(logmsg_path, &st) == -1)
408 return got_error_from_errno2("stat", logmsg_path);
410 if (spawn_editor(editor, logmsg_path) == -1)
411 return got_error_from_errno("failed spawning editor");
413 if (stat(logmsg_path, &st2) == -1)
414 return got_error_from_errno("stat");
416 if (require_modification &&
417 st.st_mtime == st2.st_mtime && st.st_size == st2.st_size)
418 return got_error_msg(GOT_ERR_COMMIT_MSG_EMPTY,
419 "no changes made to commit message, aborting");
421 /*
422 * Set up a stripped version of the initial content without comments
423 * and blank lines. We need this in order to check if the message
424 * has in fact been edited.
425 */
426 initial_content_stripped = malloc(initial_content_len + 1);
427 if (initial_content_stripped == NULL)
428 return got_error_from_errno("malloc");
429 initial_content_stripped[0] = '\0';
431 buf = strdup(initial_content);
432 if (buf == NULL) {
433 err = got_error_from_errno("strdup");
434 goto done;
436 s = buf;
437 len = 0;
438 while ((line = strsep(&s, "\n")) != NULL) {
439 if ((line[0] == '#' || (len == 0 && line[0] == '\n')))
440 continue; /* remove comments and leading empty lines */
441 len = strlcat(initial_content_stripped, line,
442 initial_content_len + 1);
443 if (len >= initial_content_len + 1) {
444 err = got_error(GOT_ERR_NO_SPACE);
445 goto done;
448 while (len > 0 && initial_content_stripped[len - 1] == '\n') {
449 initial_content_stripped[len - 1] = '\0';
450 len--;
453 logmsg_len = st2.st_size;
454 *logmsg = malloc(logmsg_len + 1);
455 if (*logmsg == NULL)
456 return got_error_from_errno("malloc");
457 (*logmsg)[0] = '\0';
459 fp = fopen(logmsg_path, "re");
460 if (fp == NULL) {
461 err = got_error_from_errno("fopen");
462 goto done;
465 len = 0;
466 while ((linelen = getline(&line, &linesize, fp)) != -1) {
467 if ((line[0] == '#' || (len == 0 && line[0] == '\n')))
468 continue; /* remove comments and leading empty lines */
469 len = strlcat(*logmsg, line, logmsg_len + 1);
470 if (len >= logmsg_len + 1) {
471 err = got_error(GOT_ERR_NO_SPACE);
472 goto done;
475 free(line);
476 if (ferror(fp)) {
477 err = got_ferror(fp, GOT_ERR_IO);
478 goto done;
480 while (len > 0 && (*logmsg)[len - 1] == '\n') {
481 (*logmsg)[len - 1] = '\0';
482 len--;
485 if (len == 0) {
486 err = got_error_msg(GOT_ERR_COMMIT_MSG_EMPTY,
487 "commit message cannot be empty, aborting");
488 goto done;
490 if (require_modification &&
491 strcmp(*logmsg, initial_content_stripped) == 0)
492 err = got_error_msg(GOT_ERR_COMMIT_MSG_EMPTY,
493 "no changes made to commit message, aborting");
494 done:
495 free(initial_content_stripped);
496 free(buf);
497 if (fp && fclose(fp) == EOF && err == NULL)
498 err = got_error_from_errno("fclose");
499 if (err) {
500 free(*logmsg);
501 *logmsg = NULL;
503 return err;
506 static const struct got_error *
507 collect_import_msg(char **logmsg, char **logmsg_path, const char *editor,
508 const char *path_dir, const char *branch_name)
510 char *initial_content = NULL;
511 const struct got_error *err = NULL;
512 int initial_content_len;
513 int fd = -1;
515 initial_content_len = asprintf(&initial_content,
516 "\n# %s to be imported to branch %s\n", path_dir,
517 branch_name);
518 if (initial_content_len == -1)
519 return got_error_from_errno("asprintf");
521 err = got_opentemp_named_fd(logmsg_path, &fd,
522 GOT_TMPDIR_STR "/got-importmsg");
523 if (err)
524 goto done;
526 if (write(fd, initial_content, initial_content_len) == -1) {
527 err = got_error_from_errno2("write", *logmsg_path);
528 goto done;
531 err = edit_logmsg(logmsg, editor, *logmsg_path, initial_content,
532 initial_content_len, 1);
533 done:
534 if (fd != -1 && close(fd) == -1 && err == NULL)
535 err = got_error_from_errno2("close", *logmsg_path);
536 free(initial_content);
537 if (err) {
538 free(*logmsg_path);
539 *logmsg_path = NULL;
541 return err;
544 static const struct got_error *
545 import_progress(void *arg, const char *path)
547 printf("A %s\n", path);
548 return NULL;
551 static int
552 valid_author(const char *author)
554 /*
555 * Really dumb email address check; we're only doing this to
556 * avoid git's object parser breaking on commits we create.
557 */
558 while (*author && *author != '<')
559 author++;
560 if (*author != '<')
561 return 0;
562 while (*author && *author != '@')
563 author++;
564 if (*author != '@')
565 return 0;
566 while (*author && *author != '>')
567 author++;
568 return *author == '>';
571 static const struct got_error *
572 get_author(char **author, struct got_repository *repo,
573 struct got_worktree *worktree)
575 const struct got_error *err = NULL;
576 const char *got_author = NULL, *name, *email;
577 const struct got_gotconfig *worktree_conf = NULL, *repo_conf = NULL;
579 *author = NULL;
581 if (worktree)
582 worktree_conf = got_worktree_get_gotconfig(worktree);
583 repo_conf = got_repo_get_gotconfig(repo);
585 /*
586 * Priority of potential author information sources, from most
587 * significant to least significant:
588 * 1) work tree's .got/got.conf file
589 * 2) repository's got.conf file
590 * 3) repository's git config file
591 * 4) environment variables
592 * 5) global git config files (in user's home directory or /etc)
593 */
595 if (worktree_conf)
596 got_author = got_gotconfig_get_author(worktree_conf);
597 if (got_author == NULL)
598 got_author = got_gotconfig_get_author(repo_conf);
599 if (got_author == NULL) {
600 name = got_repo_get_gitconfig_author_name(repo);
601 email = got_repo_get_gitconfig_author_email(repo);
602 if (name && email) {
603 if (asprintf(author, "%s <%s>", name, email) == -1)
604 return got_error_from_errno("asprintf");
605 return NULL;
608 got_author = getenv("GOT_AUTHOR");
609 if (got_author == NULL) {
610 name = got_repo_get_global_gitconfig_author_name(repo);
611 email = got_repo_get_global_gitconfig_author_email(
612 repo);
613 if (name && email) {
614 if (asprintf(author, "%s <%s>", name, email)
615 == -1)
616 return got_error_from_errno("asprintf");
617 return NULL;
619 /* TODO: Look up user in password database? */
620 return got_error(GOT_ERR_COMMIT_NO_AUTHOR);
624 *author = strdup(got_author);
625 if (*author == NULL)
626 return got_error_from_errno("strdup");
628 if (!valid_author(*author)) {
629 err = got_error_fmt(GOT_ERR_COMMIT_NO_EMAIL, "%s", *author);
630 free(*author);
631 *author = NULL;
633 return err;
636 static const struct got_error *
637 get_allowed_signers(char **allowed_signers, struct got_repository *repo,
638 struct got_worktree *worktree)
640 const char *got_allowed_signers = NULL;
641 const struct got_gotconfig *worktree_conf = NULL, *repo_conf = NULL;
643 *allowed_signers = NULL;
645 if (worktree)
646 worktree_conf = got_worktree_get_gotconfig(worktree);
647 repo_conf = got_repo_get_gotconfig(repo);
649 /*
650 * Priority of potential author information sources, from most
651 * significant to least significant:
652 * 1) work tree's .got/got.conf file
653 * 2) repository's got.conf file
654 */
656 if (worktree_conf)
657 got_allowed_signers = got_gotconfig_get_allowed_signers_file(
658 worktree_conf);
659 if (got_allowed_signers == NULL)
660 got_allowed_signers = got_gotconfig_get_allowed_signers_file(
661 repo_conf);
663 if (got_allowed_signers) {
664 *allowed_signers = strdup(got_allowed_signers);
665 if (*allowed_signers == NULL)
666 return got_error_from_errno("strdup");
668 return NULL;
671 static const struct got_error *
672 get_revoked_signers(char **revoked_signers, struct got_repository *repo,
673 struct got_worktree *worktree)
675 const char *got_revoked_signers = NULL;
676 const struct got_gotconfig *worktree_conf = NULL, *repo_conf = NULL;
678 *revoked_signers = NULL;
680 if (worktree)
681 worktree_conf = got_worktree_get_gotconfig(worktree);
682 repo_conf = got_repo_get_gotconfig(repo);
684 /*
685 * Priority of potential author information sources, from most
686 * significant to least significant:
687 * 1) work tree's .got/got.conf file
688 * 2) repository's got.conf file
689 */
691 if (worktree_conf)
692 got_revoked_signers = got_gotconfig_get_revoked_signers_file(
693 worktree_conf);
694 if (got_revoked_signers == NULL)
695 got_revoked_signers = got_gotconfig_get_revoked_signers_file(
696 repo_conf);
698 if (got_revoked_signers) {
699 *revoked_signers = strdup(got_revoked_signers);
700 if (*revoked_signers == NULL)
701 return got_error_from_errno("strdup");
703 return NULL;
706 static const struct got_error *
707 get_gitconfig_path(char **gitconfig_path)
709 const char *homedir = getenv("HOME");
711 *gitconfig_path = NULL;
712 if (homedir) {
713 if (asprintf(gitconfig_path, "%s/.gitconfig", homedir) == -1)
714 return got_error_from_errno("asprintf");
717 return NULL;
720 static const struct got_error *
721 cmd_import(int argc, char *argv[])
723 const struct got_error *error = NULL;
724 char *path_dir = NULL, *repo_path = NULL, *logmsg = NULL;
725 char *gitconfig_path = NULL, *editor = NULL, *author = NULL;
726 const char *branch_name = "main";
727 char *refname = NULL, *id_str = NULL, *logmsg_path = NULL;
728 struct got_repository *repo = NULL;
729 struct got_reference *branch_ref = NULL, *head_ref = NULL;
730 struct got_object_id *new_commit_id = NULL;
731 int ch;
732 struct got_pathlist_head ignores;
733 struct got_pathlist_entry *pe;
734 int preserve_logmsg = 0;
735 int *pack_fds = NULL;
737 TAILQ_INIT(&ignores);
739 while ((ch = getopt(argc, argv, "b:m:r:I:")) != -1) {
740 switch (ch) {
741 case 'b':
742 branch_name = optarg;
743 break;
744 case 'm':
745 logmsg = strdup(optarg);
746 if (logmsg == NULL) {
747 error = got_error_from_errno("strdup");
748 goto done;
750 break;
751 case 'r':
752 repo_path = realpath(optarg, NULL);
753 if (repo_path == NULL) {
754 error = got_error_from_errno2("realpath",
755 optarg);
756 goto done;
758 break;
759 case 'I':
760 if (optarg[0] == '\0')
761 break;
762 error = got_pathlist_insert(&pe, &ignores, optarg,
763 NULL);
764 if (error)
765 goto done;
766 break;
767 default:
768 usage_import();
769 /* NOTREACHED */
773 argc -= optind;
774 argv += optind;
776 #ifndef PROFILE
777 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
778 "unveil",
779 NULL) == -1)
780 err(1, "pledge");
781 #endif
782 if (argc != 1)
783 usage_import();
785 if (repo_path == NULL) {
786 repo_path = getcwd(NULL, 0);
787 if (repo_path == NULL)
788 return got_error_from_errno("getcwd");
790 got_path_strip_trailing_slashes(repo_path);
791 error = get_gitconfig_path(&gitconfig_path);
792 if (error)
793 goto done;
794 error = got_repo_pack_fds_open(&pack_fds);
795 if (error != NULL)
796 goto done;
797 error = got_repo_open(&repo, repo_path, gitconfig_path, pack_fds);
798 if (error)
799 goto done;
801 error = get_author(&author, repo, NULL);
802 if (error)
803 return error;
805 /*
806 * Don't let the user create a branch name with a leading '-'.
807 * While technically a valid reference name, this case is usually
808 * an unintended typo.
809 */
810 if (branch_name[0] == '-')
811 return got_error_path(branch_name, GOT_ERR_REF_NAME_MINUS);
813 if (asprintf(&refname, "refs/heads/%s", branch_name) == -1) {
814 error = got_error_from_errno("asprintf");
815 goto done;
818 error = got_ref_open(&branch_ref, repo, refname, 0);
819 if (error) {
820 if (error->code != GOT_ERR_NOT_REF)
821 goto done;
822 } else {
823 error = got_error_msg(GOT_ERR_BRANCH_EXISTS,
824 "import target branch already exists");
825 goto done;
828 path_dir = realpath(argv[0], NULL);
829 if (path_dir == NULL) {
830 error = got_error_from_errno2("realpath", argv[0]);
831 goto done;
833 got_path_strip_trailing_slashes(path_dir);
835 /*
836 * unveil(2) traverses exec(2); if an editor is used we have
837 * to apply unveil after the log message has been written.
838 */
839 if (logmsg == NULL || strlen(logmsg) == 0) {
840 error = get_editor(&editor);
841 if (error)
842 goto done;
843 free(logmsg);
844 error = collect_import_msg(&logmsg, &logmsg_path, editor,
845 path_dir, refname);
846 if (error) {
847 if (error->code != GOT_ERR_COMMIT_MSG_EMPTY &&
848 logmsg_path != NULL)
849 preserve_logmsg = 1;
850 goto done;
854 if (unveil(path_dir, "r") != 0) {
855 error = got_error_from_errno2("unveil", path_dir);
856 if (logmsg_path)
857 preserve_logmsg = 1;
858 goto done;
861 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
862 if (error) {
863 if (logmsg_path)
864 preserve_logmsg = 1;
865 goto done;
868 error = got_repo_import(&new_commit_id, path_dir, logmsg,
869 author, &ignores, repo, import_progress, NULL);
870 if (error) {
871 if (logmsg_path)
872 preserve_logmsg = 1;
873 goto done;
876 error = got_ref_alloc(&branch_ref, refname, new_commit_id);
877 if (error) {
878 if (logmsg_path)
879 preserve_logmsg = 1;
880 goto done;
883 error = got_ref_write(branch_ref, repo);
884 if (error) {
885 if (logmsg_path)
886 preserve_logmsg = 1;
887 goto done;
890 error = got_object_id_str(&id_str, new_commit_id);
891 if (error) {
892 if (logmsg_path)
893 preserve_logmsg = 1;
894 goto done;
897 error = got_ref_open(&head_ref, repo, GOT_REF_HEAD, 0);
898 if (error) {
899 if (error->code != GOT_ERR_NOT_REF) {
900 if (logmsg_path)
901 preserve_logmsg = 1;
902 goto done;
905 error = got_ref_alloc_symref(&head_ref, GOT_REF_HEAD,
906 branch_ref);
907 if (error) {
908 if (logmsg_path)
909 preserve_logmsg = 1;
910 goto done;
913 error = got_ref_write(head_ref, repo);
914 if (error) {
915 if (logmsg_path)
916 preserve_logmsg = 1;
917 goto done;
921 printf("Created branch %s with commit %s\n",
922 got_ref_get_name(branch_ref), id_str);
923 done:
924 if (pack_fds) {
925 const struct got_error *pack_err =
926 got_repo_pack_fds_close(pack_fds);
927 if (error == NULL)
928 error = pack_err;
930 if (preserve_logmsg) {
931 fprintf(stderr, "%s: log message preserved in %s\n",
932 getprogname(), logmsg_path);
933 } else if (logmsg_path && unlink(logmsg_path) == -1 && error == NULL)
934 error = got_error_from_errno2("unlink", logmsg_path);
935 free(logmsg);
936 free(logmsg_path);
937 free(repo_path);
938 free(editor);
939 free(refname);
940 free(new_commit_id);
941 free(id_str);
942 free(author);
943 free(gitconfig_path);
944 if (branch_ref)
945 got_ref_close(branch_ref);
946 if (head_ref)
947 got_ref_close(head_ref);
948 return error;
951 __dead static void
952 usage_clone(void)
954 fprintf(stderr, "usage: %s clone [-a] [-b branch] [-l] [-m] [-q] [-v] "
955 "[-R reference] repository-url [directory]\n", getprogname());
956 exit(1);
959 struct got_fetch_progress_arg {
960 char last_scaled_size[FMT_SCALED_STRSIZE];
961 int last_p_indexed;
962 int last_p_resolved;
963 int verbosity;
965 struct got_repository *repo;
967 int create_configs;
968 int configs_created;
969 struct {
970 struct got_pathlist_head *symrefs;
971 struct got_pathlist_head *wanted_branches;
972 struct got_pathlist_head *wanted_refs;
973 const char *proto;
974 const char *host;
975 const char *port;
976 const char *remote_repo_path;
977 const char *git_url;
978 int fetch_all_branches;
979 int mirror_references;
980 } config_info;
981 };
983 /* XXX forward declaration */
984 static const struct got_error *
985 create_config_files(const char *proto, const char *host, const char *port,
986 const char *remote_repo_path, const char *git_url, int fetch_all_branches,
987 int mirror_references, struct got_pathlist_head *symrefs,
988 struct got_pathlist_head *wanted_branches,
989 struct got_pathlist_head *wanted_refs, struct got_repository *repo);
991 static const struct got_error *
992 fetch_progress(void *arg, const char *message, off_t packfile_size,
993 int nobj_total, int nobj_indexed, int nobj_loose, int nobj_resolved)
995 const struct got_error *err = NULL;
996 struct got_fetch_progress_arg *a = arg;
997 char scaled_size[FMT_SCALED_STRSIZE];
998 int p_indexed, p_resolved;
999 int print_size = 0, print_indexed = 0, print_resolved = 0;
1002 * In order to allow a failed clone to be resumed with 'got fetch'
1003 * we try to create configuration files as soon as possible.
1004 * Once the server has sent information about its default branch
1005 * we have all required information.
1007 if (a->create_configs && !a->configs_created &&
1008 !TAILQ_EMPTY(a->config_info.symrefs)) {
1009 err = create_config_files(a->config_info.proto,
1010 a->config_info.host, a->config_info.port,
1011 a->config_info.remote_repo_path,
1012 a->config_info.git_url,
1013 a->config_info.fetch_all_branches,
1014 a->config_info.mirror_references,
1015 a->config_info.symrefs,
1016 a->config_info.wanted_branches,
1017 a->config_info.wanted_refs, a->repo);
1018 if (err)
1019 return err;
1020 a->configs_created = 1;
1023 if (a->verbosity < 0)
1024 return NULL;
1026 if (message && message[0] != '\0') {
1027 printf("\rserver: %s", message);
1028 fflush(stdout);
1029 return NULL;
1032 if (packfile_size > 0 || nobj_indexed > 0) {
1033 if (fmt_scaled(packfile_size, scaled_size) == 0 &&
1034 (a->last_scaled_size[0] == '\0' ||
1035 strcmp(scaled_size, a->last_scaled_size)) != 0) {
1036 print_size = 1;
1037 if (strlcpy(a->last_scaled_size, scaled_size,
1038 FMT_SCALED_STRSIZE) >= FMT_SCALED_STRSIZE)
1039 return got_error(GOT_ERR_NO_SPACE);
1041 if (nobj_indexed > 0) {
1042 p_indexed = (nobj_indexed * 100) / nobj_total;
1043 if (p_indexed != a->last_p_indexed) {
1044 a->last_p_indexed = p_indexed;
1045 print_indexed = 1;
1046 print_size = 1;
1049 if (nobj_resolved > 0) {
1050 p_resolved = (nobj_resolved * 100) /
1051 (nobj_total - nobj_loose);
1052 if (p_resolved != a->last_p_resolved) {
1053 a->last_p_resolved = p_resolved;
1054 print_resolved = 1;
1055 print_indexed = 1;
1056 print_size = 1;
1061 if (print_size || print_indexed || print_resolved)
1062 printf("\r");
1063 if (print_size)
1064 printf("%*s fetched", FMT_SCALED_STRSIZE - 2, scaled_size);
1065 if (print_indexed)
1066 printf("; indexing %d%%", p_indexed);
1067 if (print_resolved)
1068 printf("; resolving deltas %d%%", p_resolved);
1069 if (print_size || print_indexed || print_resolved)
1070 fflush(stdout);
1072 return NULL;
1075 static const struct got_error *
1076 create_symref(const char *refname, struct got_reference *target_ref,
1077 int verbosity, struct got_repository *repo)
1079 const struct got_error *err;
1080 struct got_reference *head_symref;
1082 err = got_ref_alloc_symref(&head_symref, refname, target_ref);
1083 if (err)
1084 return err;
1086 err = got_ref_write(head_symref, repo);
1087 if (err == NULL && verbosity > 0) {
1088 printf("Created reference %s: %s\n", GOT_REF_HEAD,
1089 got_ref_get_name(target_ref));
1091 got_ref_close(head_symref);
1092 return err;
1095 static const struct got_error *
1096 list_remote_refs(struct got_pathlist_head *symrefs,
1097 struct got_pathlist_head *refs)
1099 const struct got_error *err;
1100 struct got_pathlist_entry *pe;
1102 TAILQ_FOREACH(pe, symrefs, entry) {
1103 const char *refname = pe->path;
1104 const char *targetref = pe->data;
1106 printf("%s: %s\n", refname, targetref);
1109 TAILQ_FOREACH(pe, refs, entry) {
1110 const char *refname = pe->path;
1111 struct got_object_id *id = pe->data;
1112 char *id_str;
1114 err = got_object_id_str(&id_str, id);
1115 if (err)
1116 return err;
1117 printf("%s: %s\n", refname, id_str);
1118 free(id_str);
1121 return NULL;
1124 static const struct got_error *
1125 create_ref(const char *refname, struct got_object_id *id,
1126 int verbosity, struct got_repository *repo)
1128 const struct got_error *err = NULL;
1129 struct got_reference *ref;
1130 char *id_str;
1132 err = got_object_id_str(&id_str, id);
1133 if (err)
1134 return err;
1136 err = got_ref_alloc(&ref, refname, id);
1137 if (err)
1138 goto done;
1140 err = got_ref_write(ref, repo);
1141 got_ref_close(ref);
1143 if (err == NULL && verbosity >= 0)
1144 printf("Created reference %s: %s\n", refname, id_str);
1145 done:
1146 free(id_str);
1147 return err;
1150 static int
1151 match_wanted_ref(const char *refname, const char *wanted_ref)
1153 if (strncmp(refname, "refs/", 5) != 0)
1154 return 0;
1155 refname += 5;
1158 * Prevent fetching of references that won't make any
1159 * sense outside of the remote repository's context.
1161 if (strncmp(refname, "got/", 4) == 0)
1162 return 0;
1163 if (strncmp(refname, "remotes/", 8) == 0)
1164 return 0;
1166 if (strncmp(wanted_ref, "refs/", 5) == 0)
1167 wanted_ref += 5;
1169 /* Allow prefix match. */
1170 if (got_path_is_child(refname, wanted_ref, strlen(wanted_ref)))
1171 return 1;
1173 /* Allow exact match. */
1174 return (strcmp(refname, wanted_ref) == 0);
1177 static int
1178 is_wanted_ref(struct got_pathlist_head *wanted_refs, const char *refname)
1180 struct got_pathlist_entry *pe;
1182 TAILQ_FOREACH(pe, wanted_refs, entry) {
1183 if (match_wanted_ref(refname, pe->path))
1184 return 1;
1187 return 0;
1190 static const struct got_error *
1191 create_wanted_ref(const char *refname, struct got_object_id *id,
1192 const char *remote_repo_name, int verbosity, struct got_repository *repo)
1194 const struct got_error *err;
1195 char *remote_refname;
1197 if (strncmp("refs/", refname, 5) == 0)
1198 refname += 5;
1200 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
1201 remote_repo_name, refname) == -1)
1202 return got_error_from_errno("asprintf");
1204 err = create_ref(remote_refname, id, verbosity, repo);
1205 free(remote_refname);
1206 return err;
1209 static const struct got_error *
1210 create_gotconfig(const char *proto, const char *host, const char *port,
1211 const char *remote_repo_path, const char *default_branch,
1212 int fetch_all_branches, struct got_pathlist_head *wanted_branches,
1213 struct got_pathlist_head *wanted_refs, int mirror_references,
1214 struct got_repository *repo)
1216 const struct got_error *err = NULL;
1217 char *gotconfig_path = NULL;
1218 char *gotconfig = NULL;
1219 FILE *gotconfig_file = NULL;
1220 const char *branchname = NULL;
1221 char *branches = NULL, *refs = NULL;
1222 ssize_t n;
1224 if (!fetch_all_branches && !TAILQ_EMPTY(wanted_branches)) {
1225 struct got_pathlist_entry *pe;
1226 TAILQ_FOREACH(pe, wanted_branches, entry) {
1227 char *s;
1228 branchname = pe->path;
1229 if (strncmp(branchname, "refs/heads/", 11) == 0)
1230 branchname += 11;
1231 if (asprintf(&s, "%s\"%s\" ",
1232 branches ? branches : "", branchname) == -1) {
1233 err = got_error_from_errno("asprintf");
1234 goto done;
1236 free(branches);
1237 branches = s;
1239 } else if (!fetch_all_branches && default_branch) {
1240 branchname = default_branch;
1241 if (strncmp(branchname, "refs/heads/", 11) == 0)
1242 branchname += 11;
1243 if (asprintf(&branches, "\"%s\" ", branchname) == -1) {
1244 err = got_error_from_errno("asprintf");
1245 goto done;
1248 if (!TAILQ_EMPTY(wanted_refs)) {
1249 struct got_pathlist_entry *pe;
1250 TAILQ_FOREACH(pe, wanted_refs, entry) {
1251 char *s;
1252 const char *refname = pe->path;
1253 if (strncmp(refname, "refs/", 5) == 0)
1254 branchname += 5;
1255 if (asprintf(&s, "%s\"%s\" ",
1256 refs ? refs : "", refname) == -1) {
1257 err = got_error_from_errno("asprintf");
1258 goto done;
1260 free(refs);
1261 refs = s;
1265 /* Create got.conf(5). */
1266 gotconfig_path = got_repo_get_path_gotconfig(repo);
1267 if (gotconfig_path == NULL) {
1268 err = got_error_from_errno("got_repo_get_path_gotconfig");
1269 goto done;
1271 gotconfig_file = fopen(gotconfig_path, "ae");
1272 if (gotconfig_file == NULL) {
1273 err = got_error_from_errno2("fopen", gotconfig_path);
1274 goto done;
1276 if (asprintf(&gotconfig,
1277 "remote \"%s\" {\n"
1278 "\tserver %s\n"
1279 "\tprotocol %s\n"
1280 "%s%s%s"
1281 "\trepository \"%s\"\n"
1282 "%s%s%s"
1283 "%s%s%s"
1284 "%s"
1285 "%s"
1286 "}\n",
1287 GOT_FETCH_DEFAULT_REMOTE_NAME, host, proto,
1288 port ? "\tport " : "", port ? port : "", port ? "\n" : "",
1289 remote_repo_path, branches ? "\tbranch { " : "",
1290 branches ? branches : "", branches ? "}\n" : "",
1291 refs ? "\treference { " : "", refs ? refs : "", refs ? "}\n" : "",
1292 mirror_references ? "\tmirror_references yes\n" : "",
1293 fetch_all_branches ? "\tfetch_all_branches yes\n" : "") == -1) {
1294 err = got_error_from_errno("asprintf");
1295 goto done;
1297 n = fwrite(gotconfig, 1, strlen(gotconfig), gotconfig_file);
1298 if (n != strlen(gotconfig)) {
1299 err = got_ferror(gotconfig_file, GOT_ERR_IO);
1300 goto done;
1303 done:
1304 if (gotconfig_file && fclose(gotconfig_file) == EOF && err == NULL)
1305 err = got_error_from_errno2("fclose", gotconfig_path);
1306 free(gotconfig_path);
1307 free(branches);
1308 return err;
1311 static const struct got_error *
1312 create_gitconfig(const char *git_url, const char *default_branch,
1313 int fetch_all_branches, struct got_pathlist_head *wanted_branches,
1314 struct got_pathlist_head *wanted_refs, int mirror_references,
1315 struct got_repository *repo)
1317 const struct got_error *err = NULL;
1318 char *gitconfig_path = NULL;
1319 char *gitconfig = NULL;
1320 FILE *gitconfig_file = NULL;
1321 char *branches = NULL, *refs = NULL;
1322 const char *branchname;
1323 ssize_t n;
1325 /* Create a config file Git can understand. */
1326 gitconfig_path = got_repo_get_path_gitconfig(repo);
1327 if (gitconfig_path == NULL) {
1328 err = got_error_from_errno("got_repo_get_path_gitconfig");
1329 goto done;
1331 gitconfig_file = fopen(gitconfig_path, "ae");
1332 if (gitconfig_file == NULL) {
1333 err = got_error_from_errno2("fopen", gitconfig_path);
1334 goto done;
1336 if (fetch_all_branches) {
1337 if (mirror_references) {
1338 if (asprintf(&branches,
1339 "\tfetch = refs/heads/*:refs/heads/*\n") == -1) {
1340 err = got_error_from_errno("asprintf");
1341 goto done;
1343 } else if (asprintf(&branches,
1344 "\tfetch = refs/heads/*:refs/remotes/%s/*\n",
1345 GOT_FETCH_DEFAULT_REMOTE_NAME) == -1) {
1346 err = got_error_from_errno("asprintf");
1347 goto done;
1349 } else if (!TAILQ_EMPTY(wanted_branches)) {
1350 struct got_pathlist_entry *pe;
1351 TAILQ_FOREACH(pe, wanted_branches, entry) {
1352 char *s;
1353 branchname = pe->path;
1354 if (strncmp(branchname, "refs/heads/", 11) == 0)
1355 branchname += 11;
1356 if (mirror_references) {
1357 if (asprintf(&s,
1358 "%s\tfetch = refs/heads/%s:refs/heads/%s\n",
1359 branches ? branches : "",
1360 branchname, branchname) == -1) {
1361 err = got_error_from_errno("asprintf");
1362 goto done;
1364 } else if (asprintf(&s,
1365 "%s\tfetch = refs/heads/%s:refs/remotes/%s/%s\n",
1366 branches ? branches : "",
1367 branchname, GOT_FETCH_DEFAULT_REMOTE_NAME,
1368 branchname) == -1) {
1369 err = got_error_from_errno("asprintf");
1370 goto done;
1372 free(branches);
1373 branches = s;
1375 } else {
1377 * If the server specified a default branch, use just that one.
1378 * Otherwise fall back to fetching all branches on next fetch.
1380 if (default_branch) {
1381 branchname = default_branch;
1382 if (strncmp(branchname, "refs/heads/", 11) == 0)
1383 branchname += 11;
1384 } else
1385 branchname = "*"; /* fall back to all branches */
1386 if (mirror_references) {
1387 if (asprintf(&branches,
1388 "\tfetch = refs/heads/%s:refs/heads/%s\n",
1389 branchname, branchname) == -1) {
1390 err = got_error_from_errno("asprintf");
1391 goto done;
1393 } else if (asprintf(&branches,
1394 "\tfetch = refs/heads/%s:refs/remotes/%s/%s\n",
1395 branchname, GOT_FETCH_DEFAULT_REMOTE_NAME,
1396 branchname) == -1) {
1397 err = got_error_from_errno("asprintf");
1398 goto done;
1401 if (!TAILQ_EMPTY(wanted_refs)) {
1402 struct got_pathlist_entry *pe;
1403 TAILQ_FOREACH(pe, wanted_refs, entry) {
1404 char *s;
1405 const char *refname = pe->path;
1406 if (strncmp(refname, "refs/", 5) == 0)
1407 refname += 5;
1408 if (mirror_references) {
1409 if (asprintf(&s,
1410 "%s\tfetch = refs/%s:refs/%s\n",
1411 refs ? refs : "", refname, refname) == -1) {
1412 err = got_error_from_errno("asprintf");
1413 goto done;
1415 } else if (asprintf(&s,
1416 "%s\tfetch = refs/%s:refs/remotes/%s/%s\n",
1417 refs ? refs : "",
1418 refname, GOT_FETCH_DEFAULT_REMOTE_NAME,
1419 refname) == -1) {
1420 err = got_error_from_errno("asprintf");
1421 goto done;
1423 free(refs);
1424 refs = s;
1428 if (asprintf(&gitconfig,
1429 "[remote \"%s\"]\n"
1430 "\turl = %s\n"
1431 "%s"
1432 "%s"
1433 "\tfetch = refs/tags/*:refs/tags/*\n",
1434 GOT_FETCH_DEFAULT_REMOTE_NAME, git_url, branches ? branches : "",
1435 refs ? refs : "") == -1) {
1436 err = got_error_from_errno("asprintf");
1437 goto done;
1439 n = fwrite(gitconfig, 1, strlen(gitconfig), gitconfig_file);
1440 if (n != strlen(gitconfig)) {
1441 err = got_ferror(gitconfig_file, GOT_ERR_IO);
1442 goto done;
1444 done:
1445 if (gitconfig_file && fclose(gitconfig_file) == EOF && err == NULL)
1446 err = got_error_from_errno2("fclose", gitconfig_path);
1447 free(gitconfig_path);
1448 free(branches);
1449 return err;
1452 static const struct got_error *
1453 create_config_files(const char *proto, const char *host, const char *port,
1454 const char *remote_repo_path, const char *git_url, int fetch_all_branches,
1455 int mirror_references, struct got_pathlist_head *symrefs,
1456 struct got_pathlist_head *wanted_branches,
1457 struct got_pathlist_head *wanted_refs, struct got_repository *repo)
1459 const struct got_error *err = NULL;
1460 const char *default_branch = NULL;
1461 struct got_pathlist_entry *pe;
1464 * If we asked for a set of wanted branches then use the first
1465 * one of those.
1467 if (!TAILQ_EMPTY(wanted_branches)) {
1468 pe = TAILQ_FIRST(wanted_branches);
1469 default_branch = pe->path;
1470 } else {
1471 /* First HEAD ref listed by server is the default branch. */
1472 TAILQ_FOREACH(pe, symrefs, entry) {
1473 const char *refname = pe->path;
1474 const char *target = pe->data;
1476 if (strcmp(refname, GOT_REF_HEAD) != 0)
1477 continue;
1479 default_branch = target;
1480 break;
1484 /* Create got.conf(5). */
1485 err = create_gotconfig(proto, host, port, remote_repo_path,
1486 default_branch, fetch_all_branches, wanted_branches,
1487 wanted_refs, mirror_references, repo);
1488 if (err)
1489 return err;
1491 /* Create a config file Git can understand. */
1492 return create_gitconfig(git_url, default_branch, fetch_all_branches,
1493 wanted_branches, wanted_refs, mirror_references, repo);
1496 static const struct got_error *
1497 cmd_clone(int argc, char *argv[])
1499 const struct got_error *error = NULL;
1500 const char *uri, *dirname;
1501 char *proto, *host, *port, *repo_name, *server_path;
1502 char *default_destdir = NULL, *id_str = NULL;
1503 const char *repo_path;
1504 struct got_repository *repo = NULL;
1505 struct got_pathlist_head refs, symrefs, wanted_branches, wanted_refs;
1506 struct got_pathlist_entry *pe;
1507 struct got_object_id *pack_hash = NULL;
1508 int ch, fetchfd = -1, fetchstatus;
1509 pid_t fetchpid = -1;
1510 struct got_fetch_progress_arg fpa;
1511 char *git_url = NULL;
1512 int verbosity = 0, fetch_all_branches = 0, mirror_references = 0;
1513 int list_refs_only = 0;
1514 int *pack_fds = NULL;
1516 TAILQ_INIT(&refs);
1517 TAILQ_INIT(&symrefs);
1518 TAILQ_INIT(&wanted_branches);
1519 TAILQ_INIT(&wanted_refs);
1521 while ((ch = getopt(argc, argv, "ab:lmvqR:")) != -1) {
1522 switch (ch) {
1523 case 'a':
1524 fetch_all_branches = 1;
1525 break;
1526 case 'b':
1527 error = got_pathlist_append(&wanted_branches,
1528 optarg, NULL);
1529 if (error)
1530 return error;
1531 break;
1532 case 'l':
1533 list_refs_only = 1;
1534 break;
1535 case 'm':
1536 mirror_references = 1;
1537 break;
1538 case 'v':
1539 if (verbosity < 0)
1540 verbosity = 0;
1541 else if (verbosity < 3)
1542 verbosity++;
1543 break;
1544 case 'q':
1545 verbosity = -1;
1546 break;
1547 case 'R':
1548 error = got_pathlist_append(&wanted_refs,
1549 optarg, NULL);
1550 if (error)
1551 return error;
1552 break;
1553 default:
1554 usage_clone();
1555 break;
1558 argc -= optind;
1559 argv += optind;
1561 if (fetch_all_branches && !TAILQ_EMPTY(&wanted_branches))
1562 option_conflict('a', 'b');
1563 if (list_refs_only) {
1564 if (!TAILQ_EMPTY(&wanted_branches))
1565 option_conflict('l', 'b');
1566 if (fetch_all_branches)
1567 option_conflict('l', 'a');
1568 if (mirror_references)
1569 option_conflict('l', 'm');
1570 if (!TAILQ_EMPTY(&wanted_refs))
1571 option_conflict('l', 'R');
1574 uri = argv[0];
1576 if (argc == 1)
1577 dirname = NULL;
1578 else if (argc == 2)
1579 dirname = argv[1];
1580 else
1581 usage_clone();
1583 error = got_dial_parse_uri(&proto, &host, &port, &server_path,
1584 &repo_name, uri);
1585 if (error)
1586 goto done;
1588 if (asprintf(&git_url, "%s://%s%s%s%s%s", proto,
1589 host, port ? ":" : "", port ? port : "",
1590 server_path[0] != '/' ? "/" : "", server_path) == -1) {
1591 error = got_error_from_errno("asprintf");
1592 goto done;
1595 if (strcmp(proto, "git") == 0) {
1596 #ifndef PROFILE
1597 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
1598 "sendfd dns inet unveil", NULL) == -1)
1599 err(1, "pledge");
1600 #endif
1601 } else if (strcmp(proto, "git+ssh") == 0 ||
1602 strcmp(proto, "ssh") == 0) {
1603 #ifndef PROFILE
1604 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
1605 "sendfd unveil", NULL) == -1)
1606 err(1, "pledge");
1607 #endif
1608 } else if (strcmp(proto, "http") == 0 ||
1609 strcmp(proto, "git+http") == 0) {
1610 error = got_error_path(proto, GOT_ERR_NOT_IMPL);
1611 goto done;
1612 } else {
1613 error = got_error_path(proto, GOT_ERR_BAD_PROTO);
1614 goto done;
1616 if (dirname == NULL) {
1617 if (asprintf(&default_destdir, "%s.git", repo_name) == -1) {
1618 error = got_error_from_errno("asprintf");
1619 goto done;
1621 repo_path = default_destdir;
1622 } else
1623 repo_path = dirname;
1625 if (!list_refs_only) {
1626 error = got_path_mkdir(repo_path);
1627 if (error &&
1628 (!(error->code == GOT_ERR_ERRNO && errno == EISDIR) &&
1629 !(error->code == GOT_ERR_ERRNO && errno == EEXIST)))
1630 goto done;
1631 if (!got_path_dir_is_empty(repo_path)) {
1632 error = got_error_path(repo_path,
1633 GOT_ERR_DIR_NOT_EMPTY);
1634 goto done;
1638 error = got_dial_apply_unveil(proto);
1639 if (error)
1640 goto done;
1642 error = apply_unveil(repo_path, 0, NULL);
1643 if (error)
1644 goto done;
1646 if (verbosity >= 0)
1647 printf("Connecting to %s%s%s\n", host,
1648 port ? ":" : "", port ? port : "");
1650 error = got_fetch_connect(&fetchpid, &fetchfd, proto, host, port,
1651 server_path, verbosity);
1652 if (error)
1653 goto done;
1655 if (!list_refs_only) {
1656 error = got_repo_init(repo_path);
1657 if (error)
1658 goto done;
1659 error = got_repo_pack_fds_open(&pack_fds);
1660 if (error != NULL)
1661 goto done;
1662 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
1663 if (error)
1664 goto done;
1667 fpa.last_scaled_size[0] = '\0';
1668 fpa.last_p_indexed = -1;
1669 fpa.last_p_resolved = -1;
1670 fpa.verbosity = verbosity;
1671 fpa.create_configs = 1;
1672 fpa.configs_created = 0;
1673 fpa.repo = repo;
1674 fpa.config_info.symrefs = &symrefs;
1675 fpa.config_info.wanted_branches = &wanted_branches;
1676 fpa.config_info.wanted_refs = &wanted_refs;
1677 fpa.config_info.proto = proto;
1678 fpa.config_info.host = host;
1679 fpa.config_info.port = port;
1680 fpa.config_info.remote_repo_path = server_path;
1681 fpa.config_info.git_url = git_url;
1682 fpa.config_info.fetch_all_branches = fetch_all_branches;
1683 fpa.config_info.mirror_references = mirror_references;
1684 error = got_fetch_pack(&pack_hash, &refs, &symrefs,
1685 GOT_FETCH_DEFAULT_REMOTE_NAME, mirror_references,
1686 fetch_all_branches, &wanted_branches, &wanted_refs,
1687 list_refs_only, verbosity, fetchfd, repo,
1688 fetch_progress, &fpa);
1689 if (error)
1690 goto done;
1692 if (list_refs_only) {
1693 error = list_remote_refs(&symrefs, &refs);
1694 goto done;
1697 if (pack_hash == NULL) {
1698 error = got_error_fmt(GOT_ERR_FETCH_FAILED, "%s",
1699 "server sent an empty pack file");
1700 goto done;
1702 error = got_object_id_str(&id_str, pack_hash);
1703 if (error)
1704 goto done;
1705 if (verbosity >= 0)
1706 printf("\nFetched %s.pack\n", id_str);
1707 free(id_str);
1709 /* Set up references provided with the pack file. */
1710 TAILQ_FOREACH(pe, &refs, entry) {
1711 const char *refname = pe->path;
1712 struct got_object_id *id = pe->data;
1713 char *remote_refname;
1715 if (is_wanted_ref(&wanted_refs, refname) &&
1716 !mirror_references) {
1717 error = create_wanted_ref(refname, id,
1718 GOT_FETCH_DEFAULT_REMOTE_NAME,
1719 verbosity - 1, repo);
1720 if (error)
1721 goto done;
1722 continue;
1725 error = create_ref(refname, id, verbosity - 1, repo);
1726 if (error)
1727 goto done;
1729 if (mirror_references)
1730 continue;
1732 if (strncmp("refs/heads/", refname, 11) != 0)
1733 continue;
1735 if (asprintf(&remote_refname,
1736 "refs/remotes/%s/%s", GOT_FETCH_DEFAULT_REMOTE_NAME,
1737 refname + 11) == -1) {
1738 error = got_error_from_errno("asprintf");
1739 goto done;
1741 error = create_ref(remote_refname, id, verbosity - 1, repo);
1742 free(remote_refname);
1743 if (error)
1744 goto done;
1747 /* Set the HEAD reference if the server provided one. */
1748 TAILQ_FOREACH(pe, &symrefs, entry) {
1749 struct got_reference *target_ref;
1750 const char *refname = pe->path;
1751 const char *target = pe->data;
1752 char *remote_refname = NULL, *remote_target = NULL;
1754 if (strcmp(refname, GOT_REF_HEAD) != 0)
1755 continue;
1757 error = got_ref_open(&target_ref, repo, target, 0);
1758 if (error) {
1759 if (error->code == GOT_ERR_NOT_REF) {
1760 error = NULL;
1761 continue;
1763 goto done;
1766 error = create_symref(refname, target_ref, verbosity, repo);
1767 got_ref_close(target_ref);
1768 if (error)
1769 goto done;
1771 if (mirror_references)
1772 continue;
1774 if (strncmp("refs/heads/", target, 11) != 0)
1775 continue;
1777 if (asprintf(&remote_refname,
1778 "refs/remotes/%s/%s", GOT_FETCH_DEFAULT_REMOTE_NAME,
1779 refname) == -1) {
1780 error = got_error_from_errno("asprintf");
1781 goto done;
1783 if (asprintf(&remote_target,
1784 "refs/remotes/%s/%s", GOT_FETCH_DEFAULT_REMOTE_NAME,
1785 target + 11) == -1) {
1786 error = got_error_from_errno("asprintf");
1787 free(remote_refname);
1788 goto done;
1790 error = got_ref_open(&target_ref, repo, remote_target, 0);
1791 if (error) {
1792 free(remote_refname);
1793 free(remote_target);
1794 if (error->code == GOT_ERR_NOT_REF) {
1795 error = NULL;
1796 continue;
1798 goto done;
1800 error = create_symref(remote_refname, target_ref,
1801 verbosity - 1, repo);
1802 free(remote_refname);
1803 free(remote_target);
1804 got_ref_close(target_ref);
1805 if (error)
1806 goto done;
1808 if (pe == NULL) {
1810 * We failed to set the HEAD reference. If we asked for
1811 * a set of wanted branches use the first of one of those
1812 * which could be fetched instead.
1814 TAILQ_FOREACH(pe, &wanted_branches, entry) {
1815 const char *target = pe->path;
1816 struct got_reference *target_ref;
1818 error = got_ref_open(&target_ref, repo, target, 0);
1819 if (error) {
1820 if (error->code == GOT_ERR_NOT_REF) {
1821 error = NULL;
1822 continue;
1824 goto done;
1827 error = create_symref(GOT_REF_HEAD, target_ref,
1828 verbosity, repo);
1829 got_ref_close(target_ref);
1830 if (error)
1831 goto done;
1832 break;
1836 if (verbosity >= 0)
1837 printf("Created %s repository '%s'\n",
1838 mirror_references ? "mirrored" : "cloned", repo_path);
1839 done:
1840 if (pack_fds) {
1841 const struct got_error *pack_err =
1842 got_repo_pack_fds_close(pack_fds);
1843 if (error == NULL)
1844 error = pack_err;
1846 if (fetchpid > 0) {
1847 if (kill(fetchpid, SIGTERM) == -1)
1848 error = got_error_from_errno("kill");
1849 if (waitpid(fetchpid, &fetchstatus, 0) == -1 && error == NULL)
1850 error = got_error_from_errno("waitpid");
1852 if (fetchfd != -1 && close(fetchfd) == -1 && error == NULL)
1853 error = got_error_from_errno("close");
1854 if (repo) {
1855 const struct got_error *close_err = got_repo_close(repo);
1856 if (error == NULL)
1857 error = close_err;
1859 TAILQ_FOREACH(pe, &refs, entry) {
1860 free((void *)pe->path);
1861 free(pe->data);
1863 got_pathlist_free(&refs);
1864 TAILQ_FOREACH(pe, &symrefs, entry) {
1865 free((void *)pe->path);
1866 free(pe->data);
1868 got_pathlist_free(&symrefs);
1869 got_pathlist_free(&wanted_branches);
1870 got_pathlist_free(&wanted_refs);
1871 free(pack_hash);
1872 free(proto);
1873 free(host);
1874 free(port);
1875 free(server_path);
1876 free(repo_name);
1877 free(default_destdir);
1878 free(git_url);
1879 return error;
1882 static const struct got_error *
1883 update_ref(struct got_reference *ref, struct got_object_id *new_id,
1884 int replace_tags, int verbosity, struct got_repository *repo)
1886 const struct got_error *err = NULL;
1887 char *new_id_str = NULL;
1888 struct got_object_id *old_id = NULL;
1890 err = got_object_id_str(&new_id_str, new_id);
1891 if (err)
1892 goto done;
1894 if (!replace_tags &&
1895 strncmp(got_ref_get_name(ref), "refs/tags/", 10) == 0) {
1896 err = got_ref_resolve(&old_id, repo, ref);
1897 if (err)
1898 goto done;
1899 if (got_object_id_cmp(old_id, new_id) == 0)
1900 goto done;
1901 if (verbosity >= 0) {
1902 printf("Rejecting update of existing tag %s: %s\n",
1903 got_ref_get_name(ref), new_id_str);
1905 goto done;
1908 if (got_ref_is_symbolic(ref)) {
1909 if (verbosity >= 0) {
1910 printf("Replacing reference %s: %s\n",
1911 got_ref_get_name(ref),
1912 got_ref_get_symref_target(ref));
1914 err = got_ref_change_symref_to_ref(ref, new_id);
1915 if (err)
1916 goto done;
1917 err = got_ref_write(ref, repo);
1918 if (err)
1919 goto done;
1920 } else {
1921 err = got_ref_resolve(&old_id, repo, ref);
1922 if (err)
1923 goto done;
1924 if (got_object_id_cmp(old_id, new_id) == 0)
1925 goto done;
1927 err = got_ref_change_ref(ref, new_id);
1928 if (err)
1929 goto done;
1930 err = got_ref_write(ref, repo);
1931 if (err)
1932 goto done;
1935 if (verbosity >= 0)
1936 printf("Updated %s: %s\n", got_ref_get_name(ref),
1937 new_id_str);
1938 done:
1939 free(old_id);
1940 free(new_id_str);
1941 return err;
1944 static const struct got_error *
1945 update_symref(const char *refname, struct got_reference *target_ref,
1946 int verbosity, struct got_repository *repo)
1948 const struct got_error *err = NULL, *unlock_err;
1949 struct got_reference *symref;
1950 int symref_is_locked = 0;
1952 err = got_ref_open(&symref, repo, refname, 1);
1953 if (err) {
1954 if (err->code != GOT_ERR_NOT_REF)
1955 return err;
1956 err = got_ref_alloc_symref(&symref, refname, target_ref);
1957 if (err)
1958 goto done;
1960 err = got_ref_write(symref, repo);
1961 if (err)
1962 goto done;
1964 if (verbosity >= 0)
1965 printf("Created reference %s: %s\n",
1966 got_ref_get_name(symref),
1967 got_ref_get_symref_target(symref));
1968 } else {
1969 symref_is_locked = 1;
1971 if (strcmp(got_ref_get_symref_target(symref),
1972 got_ref_get_name(target_ref)) == 0)
1973 goto done;
1975 err = got_ref_change_symref(symref,
1976 got_ref_get_name(target_ref));
1977 if (err)
1978 goto done;
1980 err = got_ref_write(symref, repo);
1981 if (err)
1982 goto done;
1984 if (verbosity >= 0)
1985 printf("Updated %s: %s\n", got_ref_get_name(symref),
1986 got_ref_get_symref_target(symref));
1989 done:
1990 if (symref_is_locked) {
1991 unlock_err = got_ref_unlock(symref);
1992 if (unlock_err && err == NULL)
1993 err = unlock_err;
1995 got_ref_close(symref);
1996 return err;
1999 __dead static void
2000 usage_fetch(void)
2002 fprintf(stderr, "usage: %s fetch [-a] [-b branch] [-d] [-l] "
2003 "[-r repository-path] [-t] [-q] [-v] [-R reference] [-X] "
2004 "[remote-repository-name]\n",
2005 getprogname());
2006 exit(1);
2009 static const struct got_error *
2010 delete_missing_ref(struct got_reference *ref,
2011 int verbosity, struct got_repository *repo)
2013 const struct got_error *err = NULL;
2014 struct got_object_id *id = NULL;
2015 char *id_str = NULL;
2017 if (got_ref_is_symbolic(ref)) {
2018 err = got_ref_delete(ref, repo);
2019 if (err)
2020 return err;
2021 if (verbosity >= 0) {
2022 printf("Deleted %s: %s\n",
2023 got_ref_get_name(ref),
2024 got_ref_get_symref_target(ref));
2026 } else {
2027 err = got_ref_resolve(&id, repo, ref);
2028 if (err)
2029 return err;
2030 err = got_object_id_str(&id_str, id);
2031 if (err)
2032 goto done;
2034 err = got_ref_delete(ref, repo);
2035 if (err)
2036 goto done;
2037 if (verbosity >= 0) {
2038 printf("Deleted %s: %s\n",
2039 got_ref_get_name(ref), id_str);
2042 done:
2043 free(id);
2044 free(id_str);
2045 return NULL;
2048 static const struct got_error *
2049 delete_missing_refs(struct got_pathlist_head *their_refs,
2050 struct got_pathlist_head *their_symrefs,
2051 const struct got_remote_repo *remote,
2052 int verbosity, struct got_repository *repo)
2054 const struct got_error *err = NULL, *unlock_err;
2055 struct got_reflist_head my_refs;
2056 struct got_reflist_entry *re;
2057 struct got_pathlist_entry *pe;
2058 char *remote_namespace = NULL;
2059 char *local_refname = NULL;
2061 TAILQ_INIT(&my_refs);
2063 if (asprintf(&remote_namespace, "refs/remotes/%s/", remote->name)
2064 == -1)
2065 return got_error_from_errno("asprintf");
2067 err = got_ref_list(&my_refs, repo, NULL, got_ref_cmp_by_name, NULL);
2068 if (err)
2069 goto done;
2071 TAILQ_FOREACH(re, &my_refs, entry) {
2072 const char *refname = got_ref_get_name(re->ref);
2073 const char *their_refname;
2075 if (remote->mirror_references) {
2076 their_refname = refname;
2077 } else {
2078 if (strncmp(refname, remote_namespace,
2079 strlen(remote_namespace)) == 0) {
2080 if (strcmp(refname + strlen(remote_namespace),
2081 GOT_REF_HEAD) == 0)
2082 continue;
2083 if (asprintf(&local_refname, "refs/heads/%s",
2084 refname + strlen(remote_namespace)) == -1) {
2085 err = got_error_from_errno("asprintf");
2086 goto done;
2088 } else if (strncmp(refname, "refs/tags/", 10) != 0)
2089 continue;
2091 their_refname = local_refname;
2094 TAILQ_FOREACH(pe, their_refs, entry) {
2095 if (strcmp(their_refname, pe->path) == 0)
2096 break;
2098 if (pe != NULL)
2099 continue;
2101 TAILQ_FOREACH(pe, their_symrefs, entry) {
2102 if (strcmp(their_refname, pe->path) == 0)
2103 break;
2105 if (pe != NULL)
2106 continue;
2108 err = delete_missing_ref(re->ref, verbosity, repo);
2109 if (err)
2110 break;
2112 if (local_refname) {
2113 struct got_reference *ref;
2114 err = got_ref_open(&ref, repo, local_refname, 1);
2115 if (err) {
2116 if (err->code != GOT_ERR_NOT_REF)
2117 break;
2118 free(local_refname);
2119 local_refname = NULL;
2120 continue;
2122 err = delete_missing_ref(ref, verbosity, repo);
2123 if (err)
2124 break;
2125 unlock_err = got_ref_unlock(ref);
2126 got_ref_close(ref);
2127 if (unlock_err && err == NULL) {
2128 err = unlock_err;
2129 break;
2132 free(local_refname);
2133 local_refname = NULL;
2136 done:
2137 free(remote_namespace);
2138 free(local_refname);
2139 return err;
2142 static const struct got_error *
2143 update_wanted_ref(const char *refname, struct got_object_id *id,
2144 const char *remote_repo_name, int verbosity, struct got_repository *repo)
2146 const struct got_error *err, *unlock_err;
2147 char *remote_refname;
2148 struct got_reference *ref;
2150 if (strncmp("refs/", refname, 5) == 0)
2151 refname += 5;
2153 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
2154 remote_repo_name, refname) == -1)
2155 return got_error_from_errno("asprintf");
2157 err = got_ref_open(&ref, repo, remote_refname, 1);
2158 if (err) {
2159 if (err->code != GOT_ERR_NOT_REF)
2160 goto done;
2161 err = create_ref(remote_refname, id, verbosity, repo);
2162 } else {
2163 err = update_ref(ref, id, 0, verbosity, repo);
2164 unlock_err = got_ref_unlock(ref);
2165 if (unlock_err && err == NULL)
2166 err = unlock_err;
2167 got_ref_close(ref);
2169 done:
2170 free(remote_refname);
2171 return err;
2174 static const struct got_error *
2175 delete_ref(struct got_repository *repo, struct got_reference *ref)
2177 const struct got_error *err = NULL;
2178 struct got_object_id *id = NULL;
2179 char *id_str = NULL;
2180 const char *target;
2182 if (got_ref_is_symbolic(ref)) {
2183 target = got_ref_get_symref_target(ref);
2184 } else {
2185 err = got_ref_resolve(&id, repo, ref);
2186 if (err)
2187 goto done;
2188 err = got_object_id_str(&id_str, id);
2189 if (err)
2190 goto done;
2191 target = id_str;
2194 err = got_ref_delete(ref, repo);
2195 if (err)
2196 goto done;
2198 printf("Deleted %s: %s\n", got_ref_get_name(ref), target);
2199 done:
2200 free(id);
2201 free(id_str);
2202 return err;
2205 static const struct got_error *
2206 delete_refs_for_remote(struct got_repository *repo, const char *remote_name)
2208 const struct got_error *err = NULL;
2209 struct got_reflist_head refs;
2210 struct got_reflist_entry *re;
2211 char *prefix;
2213 TAILQ_INIT(&refs);
2215 if (asprintf(&prefix, "refs/remotes/%s", remote_name) == -1) {
2216 err = got_error_from_errno("asprintf");
2217 goto done;
2219 err = got_ref_list(&refs, repo, prefix, got_ref_cmp_by_name, NULL);
2220 if (err)
2221 goto done;
2223 TAILQ_FOREACH(re, &refs, entry)
2224 delete_ref(repo, re->ref);
2225 done:
2226 got_ref_list_free(&refs);
2227 return err;
2230 static const struct got_error *
2231 cmd_fetch(int argc, char *argv[])
2233 const struct got_error *error = NULL, *unlock_err;
2234 char *cwd = NULL, *repo_path = NULL;
2235 const char *remote_name;
2236 char *proto = NULL, *host = NULL, *port = NULL;
2237 char *repo_name = NULL, *server_path = NULL;
2238 const struct got_remote_repo *remotes, *remote = NULL;
2239 int nremotes;
2240 char *id_str = NULL;
2241 struct got_repository *repo = NULL;
2242 struct got_worktree *worktree = NULL;
2243 const struct got_gotconfig *repo_conf = NULL, *worktree_conf = NULL;
2244 struct got_pathlist_head refs, symrefs, wanted_branches, wanted_refs;
2245 struct got_pathlist_entry *pe;
2246 struct got_object_id *pack_hash = NULL;
2247 int i, ch, fetchfd = -1, fetchstatus;
2248 pid_t fetchpid = -1;
2249 struct got_fetch_progress_arg fpa;
2250 int verbosity = 0, fetch_all_branches = 0, list_refs_only = 0;
2251 int delete_refs = 0, replace_tags = 0, delete_remote = 0;
2252 int *pack_fds = NULL;
2254 TAILQ_INIT(&refs);
2255 TAILQ_INIT(&symrefs);
2256 TAILQ_INIT(&wanted_branches);
2257 TAILQ_INIT(&wanted_refs);
2259 while ((ch = getopt(argc, argv, "ab:dlr:tvqR:X")) != -1) {
2260 switch (ch) {
2261 case 'a':
2262 fetch_all_branches = 1;
2263 break;
2264 case 'b':
2265 error = got_pathlist_append(&wanted_branches,
2266 optarg, NULL);
2267 if (error)
2268 return error;
2269 break;
2270 case 'd':
2271 delete_refs = 1;
2272 break;
2273 case 'l':
2274 list_refs_only = 1;
2275 break;
2276 case 'r':
2277 repo_path = realpath(optarg, NULL);
2278 if (repo_path == NULL)
2279 return got_error_from_errno2("realpath",
2280 optarg);
2281 got_path_strip_trailing_slashes(repo_path);
2282 break;
2283 case 't':
2284 replace_tags = 1;
2285 break;
2286 case 'v':
2287 if (verbosity < 0)
2288 verbosity = 0;
2289 else if (verbosity < 3)
2290 verbosity++;
2291 break;
2292 case 'q':
2293 verbosity = -1;
2294 break;
2295 case 'R':
2296 error = got_pathlist_append(&wanted_refs,
2297 optarg, NULL);
2298 if (error)
2299 return error;
2300 break;
2301 case 'X':
2302 delete_remote = 1;
2303 break;
2304 default:
2305 usage_fetch();
2306 break;
2309 argc -= optind;
2310 argv += optind;
2312 if (fetch_all_branches && !TAILQ_EMPTY(&wanted_branches))
2313 option_conflict('a', 'b');
2314 if (list_refs_only) {
2315 if (!TAILQ_EMPTY(&wanted_branches))
2316 option_conflict('l', 'b');
2317 if (fetch_all_branches)
2318 option_conflict('l', 'a');
2319 if (delete_refs)
2320 option_conflict('l', 'd');
2321 if (delete_remote)
2322 option_conflict('l', 'X');
2324 if (delete_remote) {
2325 if (fetch_all_branches)
2326 option_conflict('X', 'a');
2327 if (!TAILQ_EMPTY(&wanted_branches))
2328 option_conflict('X', 'b');
2329 if (delete_refs)
2330 option_conflict('X', 'd');
2331 if (replace_tags)
2332 option_conflict('X', 't');
2333 if (!TAILQ_EMPTY(&wanted_refs))
2334 option_conflict('X', 'R');
2337 if (argc == 0) {
2338 if (delete_remote)
2339 errx(1, "-X option requires a remote name");
2340 remote_name = GOT_FETCH_DEFAULT_REMOTE_NAME;
2341 } else if (argc == 1)
2342 remote_name = argv[0];
2343 else
2344 usage_fetch();
2346 cwd = getcwd(NULL, 0);
2347 if (cwd == NULL) {
2348 error = got_error_from_errno("getcwd");
2349 goto done;
2352 error = got_repo_pack_fds_open(&pack_fds);
2353 if (error != NULL)
2354 goto done;
2356 if (repo_path == NULL) {
2357 error = got_worktree_open(&worktree, cwd);
2358 if (error && error->code != GOT_ERR_NOT_WORKTREE)
2359 goto done;
2360 else
2361 error = NULL;
2362 if (worktree) {
2363 repo_path =
2364 strdup(got_worktree_get_repo_path(worktree));
2365 if (repo_path == NULL)
2366 error = got_error_from_errno("strdup");
2367 if (error)
2368 goto done;
2369 } else {
2370 repo_path = strdup(cwd);
2371 if (repo_path == NULL) {
2372 error = got_error_from_errno("strdup");
2373 goto done;
2378 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
2379 if (error)
2380 goto done;
2382 if (delete_remote) {
2383 error = delete_refs_for_remote(repo, remote_name);
2384 goto done; /* nothing else to do */
2387 if (worktree) {
2388 worktree_conf = got_worktree_get_gotconfig(worktree);
2389 if (worktree_conf) {
2390 got_gotconfig_get_remotes(&nremotes, &remotes,
2391 worktree_conf);
2392 for (i = 0; i < nremotes; i++) {
2393 if (strcmp(remotes[i].name, remote_name) == 0) {
2394 remote = &remotes[i];
2395 break;
2400 if (remote == NULL) {
2401 repo_conf = got_repo_get_gotconfig(repo);
2402 if (repo_conf) {
2403 got_gotconfig_get_remotes(&nremotes, &remotes,
2404 repo_conf);
2405 for (i = 0; i < nremotes; i++) {
2406 if (strcmp(remotes[i].name, remote_name) == 0) {
2407 remote = &remotes[i];
2408 break;
2413 if (remote == NULL) {
2414 got_repo_get_gitconfig_remotes(&nremotes, &remotes, repo);
2415 for (i = 0; i < nremotes; i++) {
2416 if (strcmp(remotes[i].name, remote_name) == 0) {
2417 remote = &remotes[i];
2418 break;
2422 if (remote == NULL) {
2423 error = got_error_path(remote_name, GOT_ERR_NO_REMOTE);
2424 goto done;
2427 if (TAILQ_EMPTY(&wanted_branches)) {
2428 if (!fetch_all_branches)
2429 fetch_all_branches = remote->fetch_all_branches;
2430 for (i = 0; i < remote->nfetch_branches; i++) {
2431 got_pathlist_append(&wanted_branches,
2432 remote->fetch_branches[i], NULL);
2435 if (TAILQ_EMPTY(&wanted_refs)) {
2436 for (i = 0; i < remote->nfetch_refs; i++) {
2437 got_pathlist_append(&wanted_refs,
2438 remote->fetch_refs[i], NULL);
2442 error = got_dial_parse_uri(&proto, &host, &port, &server_path,
2443 &repo_name, remote->fetch_url);
2444 if (error)
2445 goto done;
2447 if (strcmp(proto, "git") == 0) {
2448 #ifndef PROFILE
2449 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
2450 "sendfd dns inet unveil", NULL) == -1)
2451 err(1, "pledge");
2452 #endif
2453 } else if (strcmp(proto, "git+ssh") == 0 ||
2454 strcmp(proto, "ssh") == 0) {
2455 #ifndef PROFILE
2456 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
2457 "sendfd unveil", NULL) == -1)
2458 err(1, "pledge");
2459 #endif
2460 } else if (strcmp(proto, "http") == 0 ||
2461 strcmp(proto, "git+http") == 0) {
2462 error = got_error_path(proto, GOT_ERR_NOT_IMPL);
2463 goto done;
2464 } else {
2465 error = got_error_path(proto, GOT_ERR_BAD_PROTO);
2466 goto done;
2469 error = got_dial_apply_unveil(proto);
2470 if (error)
2471 goto done;
2473 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
2474 if (error)
2475 goto done;
2477 if (verbosity >= 0)
2478 printf("Connecting to \"%s\" %s%s%s\n", remote->name, host,
2479 port ? ":" : "", port ? port : "");
2481 error = got_fetch_connect(&fetchpid, &fetchfd, proto, host, port,
2482 server_path, verbosity);
2483 if (error)
2484 goto done;
2486 fpa.last_scaled_size[0] = '\0';
2487 fpa.last_p_indexed = -1;
2488 fpa.last_p_resolved = -1;
2489 fpa.verbosity = verbosity;
2490 fpa.repo = repo;
2491 fpa.create_configs = 0;
2492 fpa.configs_created = 0;
2493 memset(&fpa.config_info, 0, sizeof(fpa.config_info));
2494 error = got_fetch_pack(&pack_hash, &refs, &symrefs, remote->name,
2495 remote->mirror_references, fetch_all_branches, &wanted_branches,
2496 &wanted_refs, list_refs_only, verbosity, fetchfd, repo,
2497 fetch_progress, &fpa);
2498 if (error)
2499 goto done;
2501 if (list_refs_only) {
2502 error = list_remote_refs(&symrefs, &refs);
2503 goto done;
2506 if (pack_hash == NULL) {
2507 if (verbosity >= 0)
2508 printf("Already up-to-date\n");
2509 } else if (verbosity >= 0) {
2510 error = got_object_id_str(&id_str, pack_hash);
2511 if (error)
2512 goto done;
2513 printf("\nFetched %s.pack\n", id_str);
2514 free(id_str);
2515 id_str = NULL;
2518 /* Update references provided with the pack file. */
2519 TAILQ_FOREACH(pe, &refs, entry) {
2520 const char *refname = pe->path;
2521 struct got_object_id *id = pe->data;
2522 struct got_reference *ref;
2523 char *remote_refname;
2525 if (is_wanted_ref(&wanted_refs, refname) &&
2526 !remote->mirror_references) {
2527 error = update_wanted_ref(refname, id,
2528 remote->name, verbosity, repo);
2529 if (error)
2530 goto done;
2531 continue;
2534 if (remote->mirror_references ||
2535 strncmp("refs/tags/", refname, 10) == 0) {
2536 error = got_ref_open(&ref, repo, refname, 1);
2537 if (error) {
2538 if (error->code != GOT_ERR_NOT_REF)
2539 goto done;
2540 error = create_ref(refname, id, verbosity,
2541 repo);
2542 if (error)
2543 goto done;
2544 } else {
2545 error = update_ref(ref, id, replace_tags,
2546 verbosity, repo);
2547 unlock_err = got_ref_unlock(ref);
2548 if (unlock_err && error == NULL)
2549 error = unlock_err;
2550 got_ref_close(ref);
2551 if (error)
2552 goto done;
2554 } else if (strncmp("refs/heads/", refname, 11) == 0) {
2555 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
2556 remote_name, refname + 11) == -1) {
2557 error = got_error_from_errno("asprintf");
2558 goto done;
2561 error = got_ref_open(&ref, repo, remote_refname, 1);
2562 if (error) {
2563 if (error->code != GOT_ERR_NOT_REF)
2564 goto done;
2565 error = create_ref(remote_refname, id,
2566 verbosity, repo);
2567 if (error)
2568 goto done;
2569 } else {
2570 error = update_ref(ref, id, replace_tags,
2571 verbosity, repo);
2572 unlock_err = got_ref_unlock(ref);
2573 if (unlock_err && error == NULL)
2574 error = unlock_err;
2575 got_ref_close(ref);
2576 if (error)
2577 goto done;
2580 /* Also create a local branch if none exists yet. */
2581 error = got_ref_open(&ref, repo, refname, 1);
2582 if (error) {
2583 if (error->code != GOT_ERR_NOT_REF)
2584 goto done;
2585 error = create_ref(refname, id, verbosity,
2586 repo);
2587 if (error)
2588 goto done;
2589 } else {
2590 unlock_err = got_ref_unlock(ref);
2591 if (unlock_err && error == NULL)
2592 error = unlock_err;
2593 got_ref_close(ref);
2597 if (delete_refs) {
2598 error = delete_missing_refs(&refs, &symrefs, remote,
2599 verbosity, repo);
2600 if (error)
2601 goto done;
2604 if (!remote->mirror_references) {
2605 /* Update remote HEAD reference if the server provided one. */
2606 TAILQ_FOREACH(pe, &symrefs, entry) {
2607 struct got_reference *target_ref;
2608 const char *refname = pe->path;
2609 const char *target = pe->data;
2610 char *remote_refname = NULL, *remote_target = NULL;
2612 if (strcmp(refname, GOT_REF_HEAD) != 0)
2613 continue;
2615 if (strncmp("refs/heads/", target, 11) != 0)
2616 continue;
2618 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
2619 remote->name, refname) == -1) {
2620 error = got_error_from_errno("asprintf");
2621 goto done;
2623 if (asprintf(&remote_target, "refs/remotes/%s/%s",
2624 remote->name, target + 11) == -1) {
2625 error = got_error_from_errno("asprintf");
2626 free(remote_refname);
2627 goto done;
2630 error = got_ref_open(&target_ref, repo, remote_target,
2631 0);
2632 if (error) {
2633 free(remote_refname);
2634 free(remote_target);
2635 if (error->code == GOT_ERR_NOT_REF) {
2636 error = NULL;
2637 continue;
2639 goto done;
2641 error = update_symref(remote_refname, target_ref,
2642 verbosity, repo);
2643 free(remote_refname);
2644 free(remote_target);
2645 got_ref_close(target_ref);
2646 if (error)
2647 goto done;
2650 done:
2651 if (fetchpid > 0) {
2652 if (kill(fetchpid, SIGTERM) == -1)
2653 error = got_error_from_errno("kill");
2654 if (waitpid(fetchpid, &fetchstatus, 0) == -1 && error == NULL)
2655 error = got_error_from_errno("waitpid");
2657 if (fetchfd != -1 && close(fetchfd) == -1 && error == NULL)
2658 error = got_error_from_errno("close");
2659 if (repo) {
2660 const struct got_error *close_err = got_repo_close(repo);
2661 if (error == NULL)
2662 error = close_err;
2664 if (worktree)
2665 got_worktree_close(worktree);
2666 if (pack_fds) {
2667 const struct got_error *pack_err =
2668 got_repo_pack_fds_close(pack_fds);
2669 if (error == NULL)
2670 error = pack_err;
2672 TAILQ_FOREACH(pe, &refs, entry) {
2673 free((void *)pe->path);
2674 free(pe->data);
2676 got_pathlist_free(&refs);
2677 TAILQ_FOREACH(pe, &symrefs, entry) {
2678 free((void *)pe->path);
2679 free(pe->data);
2681 got_pathlist_free(&symrefs);
2682 got_pathlist_free(&wanted_branches);
2683 got_pathlist_free(&wanted_refs);
2684 free(id_str);
2685 free(cwd);
2686 free(repo_path);
2687 free(pack_hash);
2688 free(proto);
2689 free(host);
2690 free(port);
2691 free(server_path);
2692 free(repo_name);
2693 return error;
2697 __dead static void
2698 usage_checkout(void)
2700 fprintf(stderr, "usage: %s checkout [-E] [-b branch] [-c commit] "
2701 "[-p prefix] [-q] repository-path [worktree-path]\n",
2702 getprogname());
2703 exit(1);
2706 static void
2707 show_worktree_base_ref_warning(void)
2709 fprintf(stderr, "%s: warning: could not create a reference "
2710 "to the work tree's base commit; the commit could be "
2711 "garbage-collected by Git or 'gotadmin cleanup'; making the "
2712 "repository writable and running 'got update' will prevent this\n",
2713 getprogname());
2716 struct got_checkout_progress_arg {
2717 const char *worktree_path;
2718 int had_base_commit_ref_error;
2719 int verbosity;
2722 static const struct got_error *
2723 checkout_progress(void *arg, unsigned char status, const char *path)
2725 struct got_checkout_progress_arg *a = arg;
2727 /* Base commit bump happens silently. */
2728 if (status == GOT_STATUS_BUMP_BASE)
2729 return NULL;
2731 if (status == GOT_STATUS_BASE_REF_ERR) {
2732 a->had_base_commit_ref_error = 1;
2733 return NULL;
2736 while (path[0] == '/')
2737 path++;
2739 if (a->verbosity >= 0)
2740 printf("%c %s/%s\n", status, a->worktree_path, path);
2742 return NULL;
2745 static const struct got_error *
2746 check_cancelled(void *arg)
2748 if (sigint_received || sigpipe_received)
2749 return got_error(GOT_ERR_CANCELLED);
2750 return NULL;
2753 static const struct got_error *
2754 check_linear_ancestry(struct got_object_id *commit_id,
2755 struct got_object_id *base_commit_id, int allow_forwards_in_time_only,
2756 struct got_repository *repo)
2758 const struct got_error *err = NULL;
2759 struct got_object_id *yca_id;
2761 err = got_commit_graph_find_youngest_common_ancestor(&yca_id,
2762 commit_id, base_commit_id, 1, repo, check_cancelled, NULL);
2763 if (err)
2764 return err;
2766 if (yca_id == NULL)
2767 return got_error(GOT_ERR_ANCESTRY);
2770 * Require a straight line of history between the target commit
2771 * and the work tree's base commit.
2773 * Non-linear situations such as this require a rebase:
2775 * (commit) D F (base_commit)
2776 * \ /
2777 * C E
2778 * \ /
2779 * B (yca)
2780 * |
2781 * A
2783 * 'got update' only handles linear cases:
2784 * Update forwards in time: A (base/yca) - B - C - D (commit)
2785 * Update backwards in time: D (base) - C - B - A (commit/yca)
2787 if (allow_forwards_in_time_only) {
2788 if (got_object_id_cmp(base_commit_id, yca_id) != 0)
2789 return got_error(GOT_ERR_ANCESTRY);
2790 } else if (got_object_id_cmp(commit_id, yca_id) != 0 &&
2791 got_object_id_cmp(base_commit_id, yca_id) != 0)
2792 return got_error(GOT_ERR_ANCESTRY);
2794 free(yca_id);
2795 return NULL;
2798 static const struct got_error *
2799 check_same_branch(struct got_object_id *commit_id,
2800 struct got_reference *head_ref, struct got_object_id *yca_id,
2801 struct got_repository *repo)
2803 const struct got_error *err = NULL;
2804 struct got_commit_graph *graph = NULL;
2805 struct got_object_id *head_commit_id = NULL;
2806 int is_same_branch = 0;
2808 err = got_ref_resolve(&head_commit_id, repo, head_ref);
2809 if (err)
2810 goto done;
2812 if (got_object_id_cmp(head_commit_id, commit_id) == 0) {
2813 is_same_branch = 1;
2814 goto done;
2816 if (yca_id && got_object_id_cmp(commit_id, yca_id) == 0) {
2817 is_same_branch = 1;
2818 goto done;
2821 err = got_commit_graph_open(&graph, "/", 1);
2822 if (err)
2823 goto done;
2825 err = got_commit_graph_iter_start(graph, head_commit_id, repo,
2826 check_cancelled, NULL);
2827 if (err)
2828 goto done;
2830 for (;;) {
2831 struct got_object_id *id;
2832 err = got_commit_graph_iter_next(&id, graph, repo,
2833 check_cancelled, NULL);
2834 if (err) {
2835 if (err->code == GOT_ERR_ITER_COMPLETED)
2836 err = NULL;
2837 break;
2840 if (id) {
2841 if (yca_id && got_object_id_cmp(id, yca_id) == 0)
2842 break;
2843 if (got_object_id_cmp(id, commit_id) == 0) {
2844 is_same_branch = 1;
2845 break;
2849 done:
2850 if (graph)
2851 got_commit_graph_close(graph);
2852 free(head_commit_id);
2853 if (!err && !is_same_branch)
2854 err = got_error(GOT_ERR_ANCESTRY);
2855 return err;
2858 static const struct got_error *
2859 checkout_ancestry_error(struct got_reference *ref, const char *commit_id_str)
2861 static char msg[512];
2862 const char *branch_name;
2864 if (got_ref_is_symbolic(ref))
2865 branch_name = got_ref_get_symref_target(ref);
2866 else
2867 branch_name = got_ref_get_name(ref);
2869 if (strncmp("refs/heads/", branch_name, 11) == 0)
2870 branch_name += 11;
2872 snprintf(msg, sizeof(msg),
2873 "target commit is not contained in branch '%s'; "
2874 "the branch to use must be specified with -b; "
2875 "if necessary a new branch can be created for "
2876 "this commit with 'got branch -c %s BRANCH_NAME'",
2877 branch_name, commit_id_str);
2879 return got_error_msg(GOT_ERR_ANCESTRY, msg);
2882 static const struct got_error *
2883 cmd_checkout(int argc, char *argv[])
2885 const struct got_error *error = NULL;
2886 struct got_repository *repo = NULL;
2887 struct got_reference *head_ref = NULL, *ref = NULL;
2888 struct got_worktree *worktree = NULL;
2889 char *repo_path = NULL;
2890 char *worktree_path = NULL;
2891 const char *path_prefix = "";
2892 const char *branch_name = GOT_REF_HEAD, *refname = NULL;
2893 char *commit_id_str = NULL;
2894 struct got_object_id *commit_id = NULL;
2895 char *cwd = NULL;
2896 int ch, same_path_prefix, allow_nonempty = 0, verbosity = 0;
2897 struct got_pathlist_head paths;
2898 struct got_checkout_progress_arg cpa;
2899 int *pack_fds = NULL;
2901 TAILQ_INIT(&paths);
2903 while ((ch = getopt(argc, argv, "b:c:Ep:q")) != -1) {
2904 switch (ch) {
2905 case 'b':
2906 branch_name = optarg;
2907 break;
2908 case 'c':
2909 commit_id_str = strdup(optarg);
2910 if (commit_id_str == NULL)
2911 return got_error_from_errno("strdup");
2912 break;
2913 case 'E':
2914 allow_nonempty = 1;
2915 break;
2916 case 'p':
2917 path_prefix = optarg;
2918 break;
2919 case 'q':
2920 verbosity = -1;
2921 break;
2922 default:
2923 usage_checkout();
2924 /* NOTREACHED */
2928 argc -= optind;
2929 argv += optind;
2931 #ifndef PROFILE
2932 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
2933 "unveil", NULL) == -1)
2934 err(1, "pledge");
2935 #endif
2936 if (argc == 1) {
2937 char *base, *dotgit;
2938 const char *path;
2939 repo_path = realpath(argv[0], NULL);
2940 if (repo_path == NULL)
2941 return got_error_from_errno2("realpath", argv[0]);
2942 cwd = getcwd(NULL, 0);
2943 if (cwd == NULL) {
2944 error = got_error_from_errno("getcwd");
2945 goto done;
2947 if (path_prefix[0])
2948 path = path_prefix;
2949 else
2950 path = repo_path;
2951 error = got_path_basename(&base, path);
2952 if (error)
2953 goto done;
2954 dotgit = strstr(base, ".git");
2955 if (dotgit)
2956 *dotgit = '\0';
2957 if (asprintf(&worktree_path, "%s/%s", cwd, base) == -1) {
2958 error = got_error_from_errno("asprintf");
2959 free(base);
2960 goto done;
2962 free(base);
2963 } else if (argc == 2) {
2964 repo_path = realpath(argv[0], NULL);
2965 if (repo_path == NULL) {
2966 error = got_error_from_errno2("realpath", argv[0]);
2967 goto done;
2969 worktree_path = realpath(argv[1], NULL);
2970 if (worktree_path == NULL) {
2971 if (errno != ENOENT) {
2972 error = got_error_from_errno2("realpath",
2973 argv[1]);
2974 goto done;
2976 worktree_path = strdup(argv[1]);
2977 if (worktree_path == NULL) {
2978 error = got_error_from_errno("strdup");
2979 goto done;
2982 } else
2983 usage_checkout();
2985 got_path_strip_trailing_slashes(repo_path);
2986 got_path_strip_trailing_slashes(worktree_path);
2988 error = got_repo_pack_fds_open(&pack_fds);
2989 if (error != NULL)
2990 goto done;
2992 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
2993 if (error != NULL)
2994 goto done;
2996 /* Pre-create work tree path for unveil(2) */
2997 error = got_path_mkdir(worktree_path);
2998 if (error) {
2999 if (!(error->code == GOT_ERR_ERRNO && errno == EISDIR) &&
3000 !(error->code == GOT_ERR_ERRNO && errno == EEXIST))
3001 goto done;
3002 if (!allow_nonempty &&
3003 !got_path_dir_is_empty(worktree_path)) {
3004 error = got_error_path(worktree_path,
3005 GOT_ERR_DIR_NOT_EMPTY);
3006 goto done;
3010 error = apply_unveil(got_repo_get_path(repo), 0, worktree_path);
3011 if (error)
3012 goto done;
3014 error = got_ref_open(&head_ref, repo, branch_name, 0);
3015 if (error != NULL)
3016 goto done;
3018 error = got_worktree_init(worktree_path, head_ref, path_prefix, repo);
3019 if (error != NULL && !(error->code == GOT_ERR_ERRNO && errno == EEXIST))
3020 goto done;
3022 error = got_worktree_open(&worktree, worktree_path);
3023 if (error != NULL)
3024 goto done;
3026 error = got_worktree_match_path_prefix(&same_path_prefix, worktree,
3027 path_prefix);
3028 if (error != NULL)
3029 goto done;
3030 if (!same_path_prefix) {
3031 error = got_error(GOT_ERR_PATH_PREFIX);
3032 goto done;
3035 if (commit_id_str) {
3036 struct got_reflist_head refs;
3037 TAILQ_INIT(&refs);
3038 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
3039 NULL);
3040 if (error)
3041 goto done;
3042 error = got_repo_match_object_id(&commit_id, NULL,
3043 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
3044 got_ref_list_free(&refs);
3045 if (error)
3046 goto done;
3047 error = check_linear_ancestry(commit_id,
3048 got_worktree_get_base_commit_id(worktree), 0, repo);
3049 if (error != NULL) {
3050 if (error->code == GOT_ERR_ANCESTRY) {
3051 error = checkout_ancestry_error(
3052 head_ref, commit_id_str);
3054 goto done;
3056 error = check_same_branch(commit_id, head_ref, NULL, repo);
3057 if (error) {
3058 if (error->code == GOT_ERR_ANCESTRY) {
3059 error = checkout_ancestry_error(
3060 head_ref, commit_id_str);
3062 goto done;
3064 error = got_worktree_set_base_commit_id(worktree, repo,
3065 commit_id);
3066 if (error)
3067 goto done;
3068 /* Expand potentially abbreviated commit ID string. */
3069 free(commit_id_str);
3070 error = got_object_id_str(&commit_id_str, commit_id);
3071 if (error)
3072 goto done;
3073 } else {
3074 commit_id = got_object_id_dup(
3075 got_worktree_get_base_commit_id(worktree));
3076 if (commit_id == NULL) {
3077 error = got_error_from_errno("got_object_id_dup");
3078 goto done;
3080 error = got_object_id_str(&commit_id_str, commit_id);
3081 if (error)
3082 goto done;
3085 error = got_pathlist_append(&paths, "", NULL);
3086 if (error)
3087 goto done;
3088 cpa.worktree_path = worktree_path;
3089 cpa.had_base_commit_ref_error = 0;
3090 cpa.verbosity = verbosity;
3091 error = got_worktree_checkout_files(worktree, &paths, repo,
3092 checkout_progress, &cpa, check_cancelled, NULL);
3093 if (error != NULL)
3094 goto done;
3096 if (got_ref_is_symbolic(head_ref)) {
3097 error = got_ref_resolve_symbolic(&ref, repo, head_ref);
3098 if (error)
3099 goto done;
3100 refname = got_ref_get_name(ref);
3101 } else
3102 refname = got_ref_get_name(head_ref);
3103 printf("Checked out %s: %s\n", refname, commit_id_str);
3104 printf("Now shut up and hack\n");
3105 if (cpa.had_base_commit_ref_error)
3106 show_worktree_base_ref_warning();
3107 done:
3108 if (pack_fds) {
3109 const struct got_error *pack_err =
3110 got_repo_pack_fds_close(pack_fds);
3111 if (error == NULL)
3112 error = pack_err;
3114 if (head_ref)
3115 got_ref_close(head_ref);
3116 if (ref)
3117 got_ref_close(ref);
3118 got_pathlist_free(&paths);
3119 free(commit_id_str);
3120 free(commit_id);
3121 free(repo_path);
3122 free(worktree_path);
3123 free(cwd);
3124 return error;
3127 struct got_update_progress_arg {
3128 int did_something;
3129 int conflicts;
3130 int obstructed;
3131 int not_updated;
3132 int missing;
3133 int not_deleted;
3134 int unversioned;
3135 int verbosity;
3138 static void
3139 print_update_progress_stats(struct got_update_progress_arg *upa)
3141 if (!upa->did_something)
3142 return;
3144 if (upa->conflicts > 0)
3145 printf("Files with new merge conflicts: %d\n", upa->conflicts);
3146 if (upa->obstructed > 0)
3147 printf("File paths obstructed by a non-regular file: %d\n",
3148 upa->obstructed);
3149 if (upa->not_updated > 0)
3150 printf("Files not updated because of existing merge "
3151 "conflicts: %d\n", upa->not_updated);
3155 * The meaning of some status codes differs between merge-style operations and
3156 * update operations. For example, the ! status code means "file was missing"
3157 * if changes were merged into the work tree, and "missing file was restored"
3158 * if the work tree was updated. This function should be used by any operation
3159 * which merges changes into the work tree without updating the work tree.
3161 static void
3162 print_merge_progress_stats(struct got_update_progress_arg *upa)
3164 if (!upa->did_something)
3165 return;
3167 if (upa->conflicts > 0)
3168 printf("Files with new merge conflicts: %d\n", upa->conflicts);
3169 if (upa->obstructed > 0)
3170 printf("File paths obstructed by a non-regular file: %d\n",
3171 upa->obstructed);
3172 if (upa->missing > 0)
3173 printf("Files which had incoming changes but could not be "
3174 "found in the work tree: %d\n", upa->missing);
3175 if (upa->not_deleted > 0)
3176 printf("Files not deleted due to differences in deleted "
3177 "content: %d\n", upa->not_deleted);
3178 if (upa->unversioned > 0)
3179 printf("Files not merged because an unversioned file was "
3180 "found in the work tree: %d\n", upa->unversioned);
3183 __dead static void
3184 usage_update(void)
3186 fprintf(stderr, "usage: %s update [-b branch] [-c commit] [-q] "
3187 "[path ...]\n",
3188 getprogname());
3189 exit(1);
3192 static const struct got_error *
3193 update_progress(void *arg, unsigned char status, const char *path)
3195 struct got_update_progress_arg *upa = arg;
3197 if (status == GOT_STATUS_EXISTS ||
3198 status == GOT_STATUS_BASE_REF_ERR)
3199 return NULL;
3201 upa->did_something = 1;
3203 /* Base commit bump happens silently. */
3204 if (status == GOT_STATUS_BUMP_BASE)
3205 return NULL;
3207 if (status == GOT_STATUS_CONFLICT)
3208 upa->conflicts++;
3209 if (status == GOT_STATUS_OBSTRUCTED)
3210 upa->obstructed++;
3211 if (status == GOT_STATUS_CANNOT_UPDATE)
3212 upa->not_updated++;
3213 if (status == GOT_STATUS_MISSING)
3214 upa->missing++;
3215 if (status == GOT_STATUS_CANNOT_DELETE)
3216 upa->not_deleted++;
3217 if (status == GOT_STATUS_UNVERSIONED)
3218 upa->unversioned++;
3220 while (path[0] == '/')
3221 path++;
3222 if (upa->verbosity >= 0)
3223 printf("%c %s\n", status, path);
3225 return NULL;
3228 static const struct got_error *
3229 switch_head_ref(struct got_reference *head_ref,
3230 struct got_object_id *commit_id, struct got_worktree *worktree,
3231 struct got_repository *repo)
3233 const struct got_error *err = NULL;
3234 char *base_id_str;
3235 int ref_has_moved = 0;
3237 /* Trivial case: switching between two different references. */
3238 if (strcmp(got_ref_get_name(head_ref),
3239 got_worktree_get_head_ref_name(worktree)) != 0) {
3240 printf("Switching work tree from %s to %s\n",
3241 got_worktree_get_head_ref_name(worktree),
3242 got_ref_get_name(head_ref));
3243 return got_worktree_set_head_ref(worktree, head_ref);
3246 err = check_linear_ancestry(commit_id,
3247 got_worktree_get_base_commit_id(worktree), 0, repo);
3248 if (err) {
3249 if (err->code != GOT_ERR_ANCESTRY)
3250 return err;
3251 ref_has_moved = 1;
3253 if (!ref_has_moved)
3254 return NULL;
3256 /* Switching to a rebased branch with the same reference name. */
3257 err = got_object_id_str(&base_id_str,
3258 got_worktree_get_base_commit_id(worktree));
3259 if (err)
3260 return err;
3261 printf("Reference %s now points at a different branch\n",
3262 got_worktree_get_head_ref_name(worktree));
3263 printf("Switching work tree from %s to %s\n", base_id_str,
3264 got_worktree_get_head_ref_name(worktree));
3265 return NULL;
3268 static const struct got_error *
3269 check_rebase_or_histedit_in_progress(struct got_worktree *worktree)
3271 const struct got_error *err;
3272 int in_progress;
3274 err = got_worktree_rebase_in_progress(&in_progress, worktree);
3275 if (err)
3276 return err;
3277 if (in_progress)
3278 return got_error(GOT_ERR_REBASING);
3280 err = got_worktree_histedit_in_progress(&in_progress, worktree);
3281 if (err)
3282 return err;
3283 if (in_progress)
3284 return got_error(GOT_ERR_HISTEDIT_BUSY);
3286 return NULL;
3289 static const struct got_error *
3290 check_merge_in_progress(struct got_worktree *worktree,
3291 struct got_repository *repo)
3293 const struct got_error *err;
3294 int in_progress;
3296 err = got_worktree_merge_in_progress(&in_progress, worktree, repo);
3297 if (err)
3298 return err;
3299 if (in_progress)
3300 return got_error(GOT_ERR_MERGE_BUSY);
3302 return NULL;
3305 static const struct got_error *
3306 get_worktree_paths_from_argv(struct got_pathlist_head *paths, int argc,
3307 char *argv[], struct got_worktree *worktree)
3309 const struct got_error *err = NULL;
3310 char *path;
3311 struct got_pathlist_entry *new;
3312 int i;
3314 if (argc == 0) {
3315 path = strdup("");
3316 if (path == NULL)
3317 return got_error_from_errno("strdup");
3318 return got_pathlist_append(paths, path, NULL);
3321 for (i = 0; i < argc; i++) {
3322 err = got_worktree_resolve_path(&path, worktree, argv[i]);
3323 if (err)
3324 break;
3325 err = got_pathlist_insert(&new, paths, path, NULL);
3326 if (err || new == NULL /* duplicate */) {
3327 free(path);
3328 if (err)
3329 break;
3333 return err;
3336 static const struct got_error *
3337 wrap_not_worktree_error(const struct got_error *orig_err,
3338 const char *cmdname, const char *path)
3340 const struct got_error *err;
3341 struct got_repository *repo;
3342 static char msg[512];
3343 int *pack_fds = NULL;
3345 err = got_repo_pack_fds_open(&pack_fds);
3346 if (err)
3347 return err;
3349 err = got_repo_open(&repo, path, NULL, pack_fds);
3350 if (err)
3351 return orig_err;
3353 snprintf(msg, sizeof(msg),
3354 "'got %s' needs a work tree in addition to a git repository\n"
3355 "Work trees can be checked out from this Git repository with "
3356 "'got checkout'.\n"
3357 "The got(1) manual page contains more information.", cmdname);
3358 err = got_error_msg(GOT_ERR_NOT_WORKTREE, msg);
3359 got_repo_close(repo);
3360 if (pack_fds) {
3361 const struct got_error *pack_err =
3362 got_repo_pack_fds_close(pack_fds);
3363 if (err == NULL)
3364 err = pack_err;
3366 return err;
3369 static const struct got_error *
3370 cmd_update(int argc, char *argv[])
3372 const struct got_error *error = NULL;
3373 struct got_repository *repo = NULL;
3374 struct got_worktree *worktree = NULL;
3375 char *worktree_path = NULL;
3376 struct got_object_id *commit_id = NULL;
3377 char *commit_id_str = NULL;
3378 const char *branch_name = NULL;
3379 struct got_reference *head_ref = NULL;
3380 struct got_pathlist_head paths;
3381 struct got_pathlist_entry *pe;
3382 int ch, verbosity = 0;
3383 struct got_update_progress_arg upa;
3384 int *pack_fds = NULL;
3386 TAILQ_INIT(&paths);
3388 while ((ch = getopt(argc, argv, "b:c:q")) != -1) {
3389 switch (ch) {
3390 case 'b':
3391 branch_name = optarg;
3392 break;
3393 case 'c':
3394 commit_id_str = strdup(optarg);
3395 if (commit_id_str == NULL)
3396 return got_error_from_errno("strdup");
3397 break;
3398 case 'q':
3399 verbosity = -1;
3400 break;
3401 default:
3402 usage_update();
3403 /* NOTREACHED */
3407 argc -= optind;
3408 argv += optind;
3410 #ifndef PROFILE
3411 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
3412 "unveil", NULL) == -1)
3413 err(1, "pledge");
3414 #endif
3415 worktree_path = getcwd(NULL, 0);
3416 if (worktree_path == NULL) {
3417 error = got_error_from_errno("getcwd");
3418 goto done;
3421 error = got_repo_pack_fds_open(&pack_fds);
3422 if (error != NULL)
3423 goto done;
3425 error = got_worktree_open(&worktree, worktree_path);
3426 if (error) {
3427 if (error->code == GOT_ERR_NOT_WORKTREE)
3428 error = wrap_not_worktree_error(error, "update",
3429 worktree_path);
3430 goto done;
3433 error = check_rebase_or_histedit_in_progress(worktree);
3434 if (error)
3435 goto done;
3437 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
3438 NULL, pack_fds);
3439 if (error != NULL)
3440 goto done;
3442 error = apply_unveil(got_repo_get_path(repo), 0,
3443 got_worktree_get_root_path(worktree));
3444 if (error)
3445 goto done;
3447 error = check_merge_in_progress(worktree, repo);
3448 if (error)
3449 goto done;
3451 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
3452 if (error)
3453 goto done;
3455 error = got_ref_open(&head_ref, repo, branch_name ? branch_name :
3456 got_worktree_get_head_ref_name(worktree), 0);
3457 if (error != NULL)
3458 goto done;
3459 if (commit_id_str == NULL) {
3460 error = got_ref_resolve(&commit_id, repo, head_ref);
3461 if (error != NULL)
3462 goto done;
3463 error = got_object_id_str(&commit_id_str, commit_id);
3464 if (error != NULL)
3465 goto done;
3466 } else {
3467 struct got_reflist_head refs;
3468 TAILQ_INIT(&refs);
3469 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
3470 NULL);
3471 if (error)
3472 goto done;
3473 error = got_repo_match_object_id(&commit_id, NULL,
3474 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
3475 got_ref_list_free(&refs);
3476 free(commit_id_str);
3477 commit_id_str = NULL;
3478 if (error)
3479 goto done;
3480 error = got_object_id_str(&commit_id_str, commit_id);
3481 if (error)
3482 goto done;
3485 if (branch_name) {
3486 struct got_object_id *head_commit_id;
3487 TAILQ_FOREACH(pe, &paths, entry) {
3488 if (pe->path_len == 0)
3489 continue;
3490 error = got_error_msg(GOT_ERR_BAD_PATH,
3491 "switching between branches requires that "
3492 "the entire work tree gets updated");
3493 goto done;
3495 error = got_ref_resolve(&head_commit_id, repo, head_ref);
3496 if (error)
3497 goto done;
3498 error = check_linear_ancestry(commit_id, head_commit_id, 0,
3499 repo);
3500 free(head_commit_id);
3501 if (error != NULL)
3502 goto done;
3503 error = check_same_branch(commit_id, head_ref, NULL, repo);
3504 if (error)
3505 goto done;
3506 error = switch_head_ref(head_ref, commit_id, worktree, repo);
3507 if (error)
3508 goto done;
3509 } else {
3510 error = check_linear_ancestry(commit_id,
3511 got_worktree_get_base_commit_id(worktree), 0, repo);
3512 if (error != NULL) {
3513 if (error->code == GOT_ERR_ANCESTRY)
3514 error = got_error(GOT_ERR_BRANCH_MOVED);
3515 goto done;
3517 error = check_same_branch(commit_id, head_ref, NULL, repo);
3518 if (error)
3519 goto done;
3522 if (got_object_id_cmp(got_worktree_get_base_commit_id(worktree),
3523 commit_id) != 0) {
3524 error = got_worktree_set_base_commit_id(worktree, repo,
3525 commit_id);
3526 if (error)
3527 goto done;
3530 memset(&upa, 0, sizeof(upa));
3531 upa.verbosity = verbosity;
3532 error = got_worktree_checkout_files(worktree, &paths, repo,
3533 update_progress, &upa, check_cancelled, NULL);
3534 if (error != NULL)
3535 goto done;
3537 if (upa.did_something) {
3538 printf("Updated to %s: %s\n",
3539 got_worktree_get_head_ref_name(worktree), commit_id_str);
3540 } else
3541 printf("Already up-to-date\n");
3543 print_update_progress_stats(&upa);
3544 done:
3545 if (pack_fds) {
3546 const struct got_error *pack_err =
3547 got_repo_pack_fds_close(pack_fds);
3548 if (error == NULL)
3549 error = pack_err;
3551 free(worktree_path);
3552 TAILQ_FOREACH(pe, &paths, entry)
3553 free((char *)pe->path);
3554 got_pathlist_free(&paths);
3555 free(commit_id);
3556 free(commit_id_str);
3557 return error;
3560 static const struct got_error *
3561 diff_blobs(struct got_object_id *blob_id1, struct got_object_id *blob_id2,
3562 const char *path, int diff_context, int ignore_whitespace,
3563 int force_text_diff, struct got_repository *repo, FILE *outfile)
3565 const struct got_error *err = NULL;
3566 struct got_blob_object *blob1 = NULL, *blob2 = NULL;
3567 FILE *f1 = NULL, *f2 = NULL;
3568 int fd1 = -1, fd2 = -1;
3570 fd1 = got_opentempfd();
3571 if (fd1 == -1)
3572 return got_error_from_errno("got_opentempfd");
3573 fd2 = got_opentempfd();
3574 if (fd2 == -1) {
3575 err = got_error_from_errno("got_opentempfd");
3576 goto done;
3579 if (blob_id1) {
3580 err = got_object_open_as_blob(&blob1, repo, blob_id1, 8192,
3581 fd1);
3582 if (err)
3583 goto done;
3586 err = got_object_open_as_blob(&blob2, repo, blob_id2, 8192, fd2);
3587 if (err)
3588 goto done;
3590 f1 = got_opentemp();
3591 if (f1 == NULL) {
3592 err = got_error_from_errno("got_opentemp");
3593 goto done;
3595 f2 = got_opentemp();
3596 if (f2 == NULL) {
3597 err = got_error_from_errno("got_opentemp");
3598 goto done;
3601 while (path[0] == '/')
3602 path++;
3603 err = got_diff_blob(NULL, NULL, blob1, blob2, f1, f2, path, path,
3604 GOT_DIFF_ALGORITHM_PATIENCE, diff_context, ignore_whitespace,
3605 force_text_diff, outfile);
3606 done:
3607 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
3608 err = got_error_from_errno("close");
3609 if (blob1)
3610 got_object_blob_close(blob1);
3611 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
3612 err = got_error_from_errno("close");
3613 got_object_blob_close(blob2);
3614 if (f1 && fclose(f1) == EOF && err == NULL)
3615 err = got_error_from_errno("fclose");
3616 if (f2 && fclose(f2) == EOF && err == NULL)
3617 err = got_error_from_errno("fclose");
3618 return err;
3621 static const struct got_error *
3622 diff_trees(struct got_object_id *tree_id1, struct got_object_id *tree_id2,
3623 const char *path, int diff_context, int ignore_whitespace,
3624 int force_text_diff, struct got_repository *repo, FILE *outfile)
3626 const struct got_error *err = NULL;
3627 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
3628 struct got_diff_blob_output_unidiff_arg arg;
3629 FILE *f1 = NULL, *f2 = NULL;
3630 int fd1 = -1, fd2 = -1;
3632 if (tree_id1) {
3633 err = got_object_open_as_tree(&tree1, repo, tree_id1);
3634 if (err)
3635 goto done;
3636 fd1 = got_opentempfd();
3637 if (fd1 == -1) {
3638 err = got_error_from_errno("got_opentempfd");
3639 goto done;
3643 err = got_object_open_as_tree(&tree2, repo, tree_id2);
3644 if (err)
3645 goto done;
3647 f1 = got_opentemp();
3648 if (f1 == NULL) {
3649 err = got_error_from_errno("got_opentemp");
3650 goto done;
3653 f2 = got_opentemp();
3654 if (f2 == NULL) {
3655 err = got_error_from_errno("got_opentemp");
3656 goto done;
3658 fd2 = got_opentempfd();
3659 if (fd2 == -1) {
3660 err = got_error_from_errno("got_opentempfd");
3661 goto done;
3663 arg.diff_context = diff_context;
3664 arg.ignore_whitespace = ignore_whitespace;
3665 arg.force_text_diff = force_text_diff;
3666 arg.diff_algo = GOT_DIFF_ALGORITHM_PATIENCE;
3667 arg.outfile = outfile;
3668 arg.line_offsets = NULL;
3669 arg.nlines = 0;
3670 while (path[0] == '/')
3671 path++;
3672 err = got_diff_tree(tree1, tree2, f1, f2, fd1, fd2, path, path, repo,
3673 got_diff_blob_output_unidiff, &arg, 1);
3674 done:
3675 if (tree1)
3676 got_object_tree_close(tree1);
3677 if (tree2)
3678 got_object_tree_close(tree2);
3679 if (f1 && fclose(f1) == EOF && err == NULL)
3680 err = got_error_from_errno("fclose");
3681 if (f2 && fclose(f2) == EOF && err == NULL)
3682 err = got_error_from_errno("fclose");
3683 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
3684 err = got_error_from_errno("close");
3685 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
3686 err = got_error_from_errno("close");
3687 return err;
3690 static const struct got_error *
3691 get_changed_paths(struct got_pathlist_head *paths,
3692 struct got_commit_object *commit, struct got_repository *repo)
3694 const struct got_error *err = NULL;
3695 struct got_object_id *tree_id1 = NULL, *tree_id2 = NULL;
3696 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
3697 struct got_object_qid *qid;
3699 qid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
3700 if (qid != NULL) {
3701 struct got_commit_object *pcommit;
3702 err = got_object_open_as_commit(&pcommit, repo,
3703 &qid->id);
3704 if (err)
3705 return err;
3707 tree_id1 = got_object_id_dup(
3708 got_object_commit_get_tree_id(pcommit));
3709 if (tree_id1 == NULL) {
3710 got_object_commit_close(pcommit);
3711 return got_error_from_errno("got_object_id_dup");
3713 got_object_commit_close(pcommit);
3717 if (tree_id1) {
3718 err = got_object_open_as_tree(&tree1, repo, tree_id1);
3719 if (err)
3720 goto done;
3723 tree_id2 = got_object_commit_get_tree_id(commit);
3724 err = got_object_open_as_tree(&tree2, repo, tree_id2);
3725 if (err)
3726 goto done;
3728 err = got_diff_tree(tree1, tree2, NULL, NULL, -1, -1, "", "", repo,
3729 got_diff_tree_collect_changed_paths, paths, 0);
3730 done:
3731 if (tree1)
3732 got_object_tree_close(tree1);
3733 if (tree2)
3734 got_object_tree_close(tree2);
3735 free(tree_id1);
3736 return err;
3739 static const struct got_error *
3740 print_patch(struct got_commit_object *commit, struct got_object_id *id,
3741 const char *path, int diff_context, struct got_repository *repo,
3742 FILE *outfile)
3744 const struct got_error *err = NULL;
3745 struct got_commit_object *pcommit = NULL;
3746 char *id_str1 = NULL, *id_str2 = NULL;
3747 struct got_object_id *obj_id1 = NULL, *obj_id2 = NULL;
3748 struct got_object_qid *qid;
3750 qid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
3751 if (qid != NULL) {
3752 err = got_object_open_as_commit(&pcommit, repo,
3753 &qid->id);
3754 if (err)
3755 return err;
3756 err = got_object_id_str(&id_str1, &qid->id);
3757 if (err)
3758 goto done;
3761 err = got_object_id_str(&id_str2, id);
3762 if (err)
3763 goto done;
3765 if (path && path[0] != '\0') {
3766 int obj_type;
3767 err = got_object_id_by_path(&obj_id2, repo, commit, path);
3768 if (err)
3769 goto done;
3770 if (pcommit) {
3771 err = got_object_id_by_path(&obj_id1, repo,
3772 pcommit, path);
3773 if (err) {
3774 if (err->code != GOT_ERR_NO_TREE_ENTRY) {
3775 free(obj_id2);
3776 goto done;
3780 err = got_object_get_type(&obj_type, repo, obj_id2);
3781 if (err) {
3782 free(obj_id2);
3783 goto done;
3785 fprintf(outfile,
3786 "diff %s %s\n", id_str1 ? id_str1 : "/dev/null", id_str2);
3787 fprintf(outfile, "commit - %s\n",
3788 id_str1 ? id_str1 : "/dev/null");
3789 fprintf(outfile, "commit + %s\n", id_str2);
3790 switch (obj_type) {
3791 case GOT_OBJ_TYPE_BLOB:
3792 err = diff_blobs(obj_id1, obj_id2, path, diff_context,
3793 0, 0, repo, outfile);
3794 break;
3795 case GOT_OBJ_TYPE_TREE:
3796 err = diff_trees(obj_id1, obj_id2, path, diff_context,
3797 0, 0, repo, outfile);
3798 break;
3799 default:
3800 err = got_error(GOT_ERR_OBJ_TYPE);
3801 break;
3803 free(obj_id1);
3804 free(obj_id2);
3805 } else {
3806 obj_id2 = got_object_commit_get_tree_id(commit);
3807 if (pcommit)
3808 obj_id1 = got_object_commit_get_tree_id(pcommit);
3809 fprintf(outfile,
3810 "diff %s %s\n", id_str1 ? id_str1 : "/dev/null", id_str2);
3811 fprintf(outfile, "commit - %s\n",
3812 id_str1 ? id_str1 : "/dev/null");
3813 fprintf(outfile, "commit + %s\n", id_str2);
3814 err = diff_trees(obj_id1, obj_id2, "", diff_context, 0, 0,
3815 repo, outfile);
3817 done:
3818 free(id_str1);
3819 free(id_str2);
3820 if (pcommit)
3821 got_object_commit_close(pcommit);
3822 return err;
3825 static char *
3826 get_datestr(time_t *time, char *datebuf)
3828 struct tm mytm, *tm;
3829 char *p, *s;
3831 tm = gmtime_r(time, &mytm);
3832 if (tm == NULL)
3833 return NULL;
3834 s = asctime_r(tm, datebuf);
3835 if (s == NULL)
3836 return NULL;
3837 p = strchr(s, '\n');
3838 if (p)
3839 *p = '\0';
3840 return s;
3843 static const struct got_error *
3844 match_commit(int *have_match, struct got_object_id *id,
3845 struct got_commit_object *commit, regex_t *regex)
3847 const struct got_error *err = NULL;
3848 regmatch_t regmatch;
3849 char *id_str = NULL, *logmsg = NULL;
3851 *have_match = 0;
3853 err = got_object_id_str(&id_str, id);
3854 if (err)
3855 return err;
3857 err = got_object_commit_get_logmsg(&logmsg, commit);
3858 if (err)
3859 goto done;
3861 if (regexec(regex, got_object_commit_get_author(commit), 1,
3862 &regmatch, 0) == 0 ||
3863 regexec(regex, got_object_commit_get_committer(commit), 1,
3864 &regmatch, 0) == 0 ||
3865 regexec(regex, id_str, 1, &regmatch, 0) == 0 ||
3866 regexec(regex, logmsg, 1, &regmatch, 0) == 0)
3867 *have_match = 1;
3868 done:
3869 free(id_str);
3870 free(logmsg);
3871 return err;
3874 static void
3875 match_changed_paths(int *have_match, struct got_pathlist_head *changed_paths,
3876 regex_t *regex)
3878 regmatch_t regmatch;
3879 struct got_pathlist_entry *pe;
3881 *have_match = 0;
3883 TAILQ_FOREACH(pe, changed_paths, entry) {
3884 if (regexec(regex, pe->path, 1, &regmatch, 0) == 0) {
3885 *have_match = 1;
3886 break;
3891 static const struct got_error *
3892 match_patch(int *have_match, struct got_commit_object *commit,
3893 struct got_object_id *id, const char *path, int diff_context,
3894 struct got_repository *repo, regex_t *regex, FILE *f)
3896 const struct got_error *err = NULL;
3897 char *line = NULL;
3898 size_t linesize = 0;
3899 ssize_t linelen;
3900 regmatch_t regmatch;
3902 *have_match = 0;
3904 err = got_opentemp_truncate(f);
3905 if (err)
3906 return err;
3908 err = print_patch(commit, id, path, diff_context, repo, f);
3909 if (err)
3910 goto done;
3912 if (fseeko(f, 0L, SEEK_SET) == -1) {
3913 err = got_error_from_errno("fseeko");
3914 goto done;
3917 while ((linelen = getline(&line, &linesize, f)) != -1) {
3918 if (regexec(regex, line, 1, &regmatch, 0) == 0) {
3919 *have_match = 1;
3920 break;
3923 done:
3924 free(line);
3925 return err;
3928 #define GOT_COMMIT_SEP_STR "-----------------------------------------------\n"
3930 static const struct got_error*
3931 build_refs_str(char **refs_str, struct got_reflist_head *refs,
3932 struct got_object_id *id, struct got_repository *repo,
3933 int local_only)
3935 static const struct got_error *err = NULL;
3936 struct got_reflist_entry *re;
3937 char *s;
3938 const char *name;
3940 *refs_str = NULL;
3942 TAILQ_FOREACH(re, refs, entry) {
3943 struct got_tag_object *tag = NULL;
3944 struct got_object_id *ref_id;
3945 int cmp;
3947 name = got_ref_get_name(re->ref);
3948 if (strcmp(name, GOT_REF_HEAD) == 0)
3949 continue;
3950 if (strncmp(name, "refs/", 5) == 0)
3951 name += 5;
3952 if (strncmp(name, "got/", 4) == 0)
3953 continue;
3954 if (strncmp(name, "heads/", 6) == 0)
3955 name += 6;
3956 if (strncmp(name, "remotes/", 8) == 0) {
3957 if (local_only)
3958 continue;
3959 name += 8;
3960 s = strstr(name, "/" GOT_REF_HEAD);
3961 if (s != NULL && s[strlen(s)] == '\0')
3962 continue;
3964 err = got_ref_resolve(&ref_id, repo, re->ref);
3965 if (err)
3966 break;
3967 if (strncmp(name, "tags/", 5) == 0) {
3968 err = got_object_open_as_tag(&tag, repo, ref_id);
3969 if (err) {
3970 if (err->code != GOT_ERR_OBJ_TYPE) {
3971 free(ref_id);
3972 break;
3974 /* Ref points at something other than a tag. */
3975 err = NULL;
3976 tag = NULL;
3979 cmp = got_object_id_cmp(tag ?
3980 got_object_tag_get_object_id(tag) : ref_id, id);
3981 free(ref_id);
3982 if (tag)
3983 got_object_tag_close(tag);
3984 if (cmp != 0)
3985 continue;
3986 s = *refs_str;
3987 if (asprintf(refs_str, "%s%s%s", s ? s : "",
3988 s ? ", " : "", name) == -1) {
3989 err = got_error_from_errno("asprintf");
3990 free(s);
3991 *refs_str = NULL;
3992 break;
3994 free(s);
3997 return err;
4000 static const struct got_error *
4001 print_commit_oneline(struct got_commit_object *commit, struct got_object_id *id,
4002 struct got_repository *repo, struct got_reflist_object_id_map *refs_idmap)
4004 const struct got_error *err = NULL;
4005 char *ref_str = NULL, *id_str = NULL, *logmsg0 = NULL;
4006 char *comma, *s, *nl;
4007 struct got_reflist_head *refs;
4008 char datebuf[12]; /* YYYY-MM-DD + SPACE + NUL */
4009 struct tm tm;
4010 time_t committer_time;
4012 refs = got_reflist_object_id_map_lookup(refs_idmap, id);
4013 if (refs) {
4014 err = build_refs_str(&ref_str, refs, id, repo, 1);
4015 if (err)
4016 return err;
4018 /* Display the first matching ref only. */
4019 if (ref_str && (comma = strchr(ref_str, ',')) != NULL)
4020 *comma = '\0';
4023 if (ref_str == NULL) {
4024 err = got_object_id_str(&id_str, id);
4025 if (err)
4026 return err;
4029 committer_time = got_object_commit_get_committer_time(commit);
4030 if (gmtime_r(&committer_time, &tm) == NULL) {
4031 err = got_error_from_errno("gmtime_r");
4032 goto done;
4034 if (strftime(datebuf, sizeof(datebuf), "%G-%m-%d ", &tm) == 0) {
4035 err = got_error(GOT_ERR_NO_SPACE);
4036 goto done;
4039 err = got_object_commit_get_logmsg(&logmsg0, commit);
4040 if (err)
4041 goto done;
4043 s = logmsg0;
4044 while (isspace((unsigned char)s[0]))
4045 s++;
4047 nl = strchr(s, '\n');
4048 if (nl) {
4049 *nl = '\0';
4052 if (ref_str)
4053 printf("%s%-7s %s\n", datebuf, ref_str, s);
4054 else
4055 printf("%s%.7s %s\n", datebuf, id_str, s);
4057 if (fflush(stdout) != 0 && err == NULL)
4058 err = got_error_from_errno("fflush");
4059 done:
4060 free(id_str);
4061 free(ref_str);
4062 free(logmsg0);
4063 return err;
4066 static const struct got_error *
4067 print_commit(struct got_commit_object *commit, struct got_object_id *id,
4068 struct got_repository *repo, const char *path,
4069 struct got_pathlist_head *changed_paths, int show_patch,
4070 int diff_context, struct got_reflist_object_id_map *refs_idmap,
4071 const char *custom_refs_str)
4073 const struct got_error *err = NULL;
4074 char *id_str, *datestr, *logmsg0, *logmsg, *line;
4075 char datebuf[26];
4076 time_t committer_time;
4077 const char *author, *committer;
4078 char *refs_str = NULL;
4080 err = got_object_id_str(&id_str, id);
4081 if (err)
4082 return err;
4084 if (custom_refs_str == NULL) {
4085 struct got_reflist_head *refs;
4086 refs = got_reflist_object_id_map_lookup(refs_idmap, id);
4087 if (refs) {
4088 err = build_refs_str(&refs_str, refs, id, repo, 0);
4089 if (err)
4090 goto done;
4094 printf(GOT_COMMIT_SEP_STR);
4095 if (custom_refs_str)
4096 printf("commit %s (%s)\n", id_str, custom_refs_str);
4097 else
4098 printf("commit %s%s%s%s\n", id_str, refs_str ? " (" : "",
4099 refs_str ? refs_str : "", refs_str ? ")" : "");
4100 free(id_str);
4101 id_str = NULL;
4102 free(refs_str);
4103 refs_str = NULL;
4104 printf("from: %s\n", got_object_commit_get_author(commit));
4105 committer_time = got_object_commit_get_committer_time(commit);
4106 datestr = get_datestr(&committer_time, datebuf);
4107 if (datestr)
4108 printf("date: %s UTC\n", datestr);
4109 author = got_object_commit_get_author(commit);
4110 committer = got_object_commit_get_committer(commit);
4111 if (strcmp(author, committer) != 0)
4112 printf("via: %s\n", committer);
4113 if (got_object_commit_get_nparents(commit) > 1) {
4114 const struct got_object_id_queue *parent_ids;
4115 struct got_object_qid *qid;
4116 int n = 1;
4117 parent_ids = got_object_commit_get_parent_ids(commit);
4118 STAILQ_FOREACH(qid, parent_ids, entry) {
4119 err = got_object_id_str(&id_str, &qid->id);
4120 if (err)
4121 goto done;
4122 printf("parent %d: %s\n", n++, id_str);
4123 free(id_str);
4124 id_str = NULL;
4128 err = got_object_commit_get_logmsg(&logmsg0, commit);
4129 if (err)
4130 goto done;
4132 logmsg = logmsg0;
4133 do {
4134 line = strsep(&logmsg, "\n");
4135 if (line)
4136 printf(" %s\n", line);
4137 } while (line);
4138 free(logmsg0);
4140 if (changed_paths) {
4141 struct got_pathlist_entry *pe;
4142 TAILQ_FOREACH(pe, changed_paths, entry) {
4143 struct got_diff_changed_path *cp = pe->data;
4144 printf(" %c %s\n", cp->status, pe->path);
4146 printf("\n");
4148 if (show_patch) {
4149 err = print_patch(commit, id, path, diff_context, repo, stdout);
4150 if (err == 0)
4151 printf("\n");
4154 if (fflush(stdout) != 0 && err == NULL)
4155 err = got_error_from_errno("fflush");
4156 done:
4157 free(id_str);
4158 free(refs_str);
4159 return err;
4162 static const struct got_error *
4163 print_commits(struct got_object_id *root_id, struct got_object_id *end_id,
4164 struct got_repository *repo, const char *path, int show_changed_paths,
4165 int show_patch, const char *search_pattern, int diff_context, int limit,
4166 int log_branches, int reverse_display_order,
4167 struct got_reflist_object_id_map *refs_idmap, int one_line,
4168 FILE *tmpfile)
4170 const struct got_error *err;
4171 struct got_commit_graph *graph;
4172 regex_t regex;
4173 int have_match;
4174 struct got_object_id_queue reversed_commits;
4175 struct got_object_qid *qid;
4176 struct got_commit_object *commit;
4177 struct got_pathlist_head changed_paths;
4178 struct got_pathlist_entry *pe;
4180 STAILQ_INIT(&reversed_commits);
4181 TAILQ_INIT(&changed_paths);
4183 if (search_pattern && regcomp(&regex, search_pattern,
4184 REG_EXTENDED | REG_NOSUB | REG_NEWLINE))
4185 return got_error_msg(GOT_ERR_REGEX, search_pattern);
4187 err = got_commit_graph_open(&graph, path, !log_branches);
4188 if (err)
4189 return err;
4190 err = got_commit_graph_iter_start(graph, root_id, repo,
4191 check_cancelled, NULL);
4192 if (err)
4193 goto done;
4194 for (;;) {
4195 struct got_object_id *id;
4197 if (sigint_received || sigpipe_received)
4198 break;
4200 err = got_commit_graph_iter_next(&id, graph, repo,
4201 check_cancelled, NULL);
4202 if (err) {
4203 if (err->code == GOT_ERR_ITER_COMPLETED)
4204 err = NULL;
4205 break;
4207 if (id == NULL)
4208 break;
4210 err = got_object_open_as_commit(&commit, repo, id);
4211 if (err)
4212 break;
4214 if (show_changed_paths && !reverse_display_order) {
4215 err = get_changed_paths(&changed_paths, commit, repo);
4216 if (err)
4217 break;
4220 if (search_pattern) {
4221 err = match_commit(&have_match, id, commit, &regex);
4222 if (err) {
4223 got_object_commit_close(commit);
4224 break;
4226 if (have_match == 0 && show_changed_paths)
4227 match_changed_paths(&have_match,
4228 &changed_paths, &regex);
4229 if (have_match == 0 && show_patch) {
4230 err = match_patch(&have_match, commit, id,
4231 path, diff_context, repo, &regex,
4232 tmpfile);
4233 if (err)
4234 break;
4236 if (have_match == 0) {
4237 got_object_commit_close(commit);
4238 TAILQ_FOREACH(pe, &changed_paths, entry) {
4239 free((char *)pe->path);
4240 free(pe->data);
4242 got_pathlist_free(&changed_paths);
4243 continue;
4247 if (reverse_display_order) {
4248 err = got_object_qid_alloc(&qid, id);
4249 if (err)
4250 break;
4251 STAILQ_INSERT_HEAD(&reversed_commits, qid, entry);
4252 got_object_commit_close(commit);
4253 } else {
4254 if (one_line)
4255 err = print_commit_oneline(commit, id,
4256 repo, refs_idmap);
4257 else
4258 err = print_commit(commit, id, repo, path,
4259 show_changed_paths ? &changed_paths : NULL,
4260 show_patch, diff_context, refs_idmap, NULL);
4261 got_object_commit_close(commit);
4262 if (err)
4263 break;
4265 if ((limit && --limit == 0) ||
4266 (end_id && got_object_id_cmp(id, end_id) == 0))
4267 break;
4269 TAILQ_FOREACH(pe, &changed_paths, entry) {
4270 free((char *)pe->path);
4271 free(pe->data);
4273 got_pathlist_free(&changed_paths);
4275 if (reverse_display_order) {
4276 STAILQ_FOREACH(qid, &reversed_commits, entry) {
4277 err = got_object_open_as_commit(&commit, repo,
4278 &qid->id);
4279 if (err)
4280 break;
4281 if (show_changed_paths) {
4282 err = get_changed_paths(&changed_paths,
4283 commit, repo);
4284 if (err)
4285 break;
4287 if (one_line)
4288 err = print_commit_oneline(commit, &qid->id,
4289 repo, refs_idmap);
4290 else
4291 err = print_commit(commit, &qid->id, repo, path,
4292 show_changed_paths ? &changed_paths : NULL,
4293 show_patch, diff_context, refs_idmap, NULL);
4294 got_object_commit_close(commit);
4295 if (err)
4296 break;
4297 TAILQ_FOREACH(pe, &changed_paths, entry) {
4298 free((char *)pe->path);
4299 free(pe->data);
4301 got_pathlist_free(&changed_paths);
4304 done:
4305 while (!STAILQ_EMPTY(&reversed_commits)) {
4306 qid = STAILQ_FIRST(&reversed_commits);
4307 STAILQ_REMOVE_HEAD(&reversed_commits, entry);
4308 got_object_qid_free(qid);
4310 TAILQ_FOREACH(pe, &changed_paths, entry) {
4311 free((char *)pe->path);
4312 free(pe->data);
4314 got_pathlist_free(&changed_paths);
4315 if (search_pattern)
4316 regfree(&regex);
4317 got_commit_graph_close(graph);
4318 return err;
4321 __dead static void
4322 usage_log(void)
4324 fprintf(stderr, "usage: %s log [-b] [-p] [-P] [-s] [-c commit] "
4325 "[-C number] [ -l N ] [-x commit] [-S search-pattern] "
4326 "[-r repository-path] [-R] [path]\n", getprogname());
4327 exit(1);
4330 static int
4331 get_default_log_limit(void)
4333 const char *got_default_log_limit;
4334 long long n;
4335 const char *errstr;
4337 got_default_log_limit = getenv("GOT_LOG_DEFAULT_LIMIT");
4338 if (got_default_log_limit == NULL)
4339 return 0;
4340 n = strtonum(got_default_log_limit, 0, INT_MAX, &errstr);
4341 if (errstr != NULL)
4342 return 0;
4343 return n;
4346 static const struct got_error *
4347 cmd_log(int argc, char *argv[])
4349 const struct got_error *error;
4350 struct got_repository *repo = NULL;
4351 struct got_worktree *worktree = NULL;
4352 struct got_object_id *start_id = NULL, *end_id = NULL;
4353 char *repo_path = NULL, *path = NULL, *cwd = NULL, *in_repo_path = NULL;
4354 const char *start_commit = NULL, *end_commit = NULL;
4355 const char *search_pattern = NULL;
4356 int diff_context = -1, ch;
4357 int show_changed_paths = 0, show_patch = 0, limit = 0, log_branches = 0;
4358 int reverse_display_order = 0, one_line = 0;
4359 const char *errstr;
4360 struct got_reflist_head refs;
4361 struct got_reflist_object_id_map *refs_idmap = NULL;
4362 FILE *tmpfile = NULL;
4363 int *pack_fds = NULL;
4365 TAILQ_INIT(&refs);
4367 #ifndef PROFILE
4368 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
4369 NULL)
4370 == -1)
4371 err(1, "pledge");
4372 #endif
4374 limit = get_default_log_limit();
4376 while ((ch = getopt(argc, argv, "bpPc:C:l:r:RsS:x:")) != -1) {
4377 switch (ch) {
4378 case 'p':
4379 show_patch = 1;
4380 break;
4381 case 'P':
4382 show_changed_paths = 1;
4383 break;
4384 case 'c':
4385 start_commit = optarg;
4386 break;
4387 case 'C':
4388 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
4389 &errstr);
4390 if (errstr != NULL)
4391 errx(1, "number of context lines is %s: %s",
4392 errstr, optarg);
4393 break;
4394 case 'l':
4395 limit = strtonum(optarg, 0, INT_MAX, &errstr);
4396 if (errstr != NULL)
4397 errx(1, "number of commits is %s: %s",
4398 errstr, optarg);
4399 break;
4400 case 'b':
4401 log_branches = 1;
4402 break;
4403 case 'r':
4404 repo_path = realpath(optarg, NULL);
4405 if (repo_path == NULL)
4406 return got_error_from_errno2("realpath",
4407 optarg);
4408 got_path_strip_trailing_slashes(repo_path);
4409 break;
4410 case 'R':
4411 reverse_display_order = 1;
4412 break;
4413 case 's':
4414 one_line = 1;
4415 break;
4416 case 'S':
4417 search_pattern = optarg;
4418 break;
4419 case 'x':
4420 end_commit = optarg;
4421 break;
4422 default:
4423 usage_log();
4424 /* NOTREACHED */
4428 argc -= optind;
4429 argv += optind;
4431 if (diff_context == -1)
4432 diff_context = 3;
4433 else if (!show_patch)
4434 errx(1, "-C requires -p");
4436 if (one_line && (show_patch || show_changed_paths))
4437 errx(1, "cannot use -s with -p or -P");
4439 cwd = getcwd(NULL, 0);
4440 if (cwd == NULL) {
4441 error = got_error_from_errno("getcwd");
4442 goto done;
4445 error = got_repo_pack_fds_open(&pack_fds);
4446 if (error != NULL)
4447 goto done;
4449 if (repo_path == NULL) {
4450 error = got_worktree_open(&worktree, cwd);
4451 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4452 goto done;
4453 error = NULL;
4456 if (argc == 1) {
4457 if (worktree) {
4458 error = got_worktree_resolve_path(&path, worktree,
4459 argv[0]);
4460 if (error)
4461 goto done;
4462 } else {
4463 path = strdup(argv[0]);
4464 if (path == NULL) {
4465 error = got_error_from_errno("strdup");
4466 goto done;
4469 } else if (argc != 0)
4470 usage_log();
4472 if (repo_path == NULL) {
4473 repo_path = worktree ?
4474 strdup(got_worktree_get_repo_path(worktree)) : strdup(cwd);
4476 if (repo_path == NULL) {
4477 error = got_error_from_errno("strdup");
4478 goto done;
4481 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
4482 if (error != NULL)
4483 goto done;
4485 error = apply_unveil(got_repo_get_path(repo), 1,
4486 worktree ? got_worktree_get_root_path(worktree) : NULL);
4487 if (error)
4488 goto done;
4490 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
4491 if (error)
4492 goto done;
4494 error = got_reflist_object_id_map_create(&refs_idmap, &refs, repo);
4495 if (error)
4496 goto done;
4498 if (start_commit == NULL) {
4499 struct got_reference *head_ref;
4500 struct got_commit_object *commit = NULL;
4501 error = got_ref_open(&head_ref, repo,
4502 worktree ? got_worktree_get_head_ref_name(worktree)
4503 : GOT_REF_HEAD, 0);
4504 if (error != NULL)
4505 goto done;
4506 error = got_ref_resolve(&start_id, repo, head_ref);
4507 got_ref_close(head_ref);
4508 if (error != NULL)
4509 goto done;
4510 error = got_object_open_as_commit(&commit, repo,
4511 start_id);
4512 if (error != NULL)
4513 goto done;
4514 got_object_commit_close(commit);
4515 } else {
4516 error = got_repo_match_object_id(&start_id, NULL,
4517 start_commit, GOT_OBJ_TYPE_COMMIT, &refs, repo);
4518 if (error != NULL)
4519 goto done;
4521 if (end_commit != NULL) {
4522 error = got_repo_match_object_id(&end_id, NULL,
4523 end_commit, GOT_OBJ_TYPE_COMMIT, &refs, repo);
4524 if (error != NULL)
4525 goto done;
4528 if (worktree) {
4530 * If a path was specified on the command line it was resolved
4531 * to a path in the work tree above. Prepend the work tree's
4532 * path prefix to obtain the corresponding in-repository path.
4534 if (path) {
4535 const char *prefix;
4536 prefix = got_worktree_get_path_prefix(worktree);
4537 if (asprintf(&in_repo_path, "%s%s%s", prefix,
4538 (path[0] != '\0') ? "/" : "", path) == -1) {
4539 error = got_error_from_errno("asprintf");
4540 goto done;
4543 } else
4544 error = got_repo_map_path(&in_repo_path, repo,
4545 path ? path : "");
4546 if (error != NULL)
4547 goto done;
4548 if (in_repo_path) {
4549 free(path);
4550 path = in_repo_path;
4553 if (worktree) {
4554 /* Release work tree lock. */
4555 got_worktree_close(worktree);
4556 worktree = NULL;
4559 if (search_pattern && show_patch) {
4560 tmpfile = got_opentemp();
4561 if (tmpfile == NULL) {
4562 error = got_error_from_errno("got_opentemp");
4563 goto done;
4567 error = print_commits(start_id, end_id, repo, path ? path : "",
4568 show_changed_paths, show_patch, search_pattern, diff_context,
4569 limit, log_branches, reverse_display_order, refs_idmap, one_line,
4570 tmpfile);
4571 done:
4572 free(path);
4573 free(repo_path);
4574 free(cwd);
4575 if (worktree)
4576 got_worktree_close(worktree);
4577 if (repo) {
4578 const struct got_error *close_err = got_repo_close(repo);
4579 if (error == NULL)
4580 error = close_err;
4582 if (pack_fds) {
4583 const struct got_error *pack_err =
4584 got_repo_pack_fds_close(pack_fds);
4585 if (error == NULL)
4586 error = pack_err;
4588 if (refs_idmap)
4589 got_reflist_object_id_map_free(refs_idmap);
4590 if (tmpfile && fclose(tmpfile) == EOF && error == NULL)
4591 error = got_error_from_errno("fclose");
4592 got_ref_list_free(&refs);
4593 return error;
4596 __dead static void
4597 usage_diff(void)
4599 fprintf(stderr, "usage: %s diff [-a] [-c commit] [-C number] "
4600 "[-r repository-path] [-s] [-w] [-P] "
4601 "[object1 object2 | path ...]\n", getprogname());
4602 exit(1);
4605 struct print_diff_arg {
4606 struct got_repository *repo;
4607 struct got_worktree *worktree;
4608 int diff_context;
4609 const char *id_str;
4610 int header_shown;
4611 int diff_staged;
4612 enum got_diff_algorithm diff_algo;
4613 int ignore_whitespace;
4614 int force_text_diff;
4615 FILE *f1;
4616 FILE *f2;
4620 * Create a file which contains the target path of a symlink so we can feed
4621 * it as content to the diff engine.
4623 static const struct got_error *
4624 get_symlink_target_file(int *fd, int dirfd, const char *de_name,
4625 const char *abspath)
4627 const struct got_error *err = NULL;
4628 char target_path[PATH_MAX];
4629 ssize_t target_len, outlen;
4631 *fd = -1;
4633 if (dirfd != -1) {
4634 target_len = readlinkat(dirfd, de_name, target_path, PATH_MAX);
4635 if (target_len == -1)
4636 return got_error_from_errno2("readlinkat", abspath);
4637 } else {
4638 target_len = readlink(abspath, target_path, PATH_MAX);
4639 if (target_len == -1)
4640 return got_error_from_errno2("readlink", abspath);
4643 *fd = got_opentempfd();
4644 if (*fd == -1)
4645 return got_error_from_errno("got_opentempfd");
4647 outlen = write(*fd, target_path, target_len);
4648 if (outlen == -1) {
4649 err = got_error_from_errno("got_opentempfd");
4650 goto done;
4653 if (lseek(*fd, 0, SEEK_SET) == -1) {
4654 err = got_error_from_errno2("lseek", abspath);
4655 goto done;
4657 done:
4658 if (err) {
4659 close(*fd);
4660 *fd = -1;
4662 return err;
4665 static const struct got_error *
4666 print_diff(void *arg, unsigned char status, unsigned char staged_status,
4667 const char *path, struct got_object_id *blob_id,
4668 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
4669 int dirfd, const char *de_name)
4671 struct print_diff_arg *a = arg;
4672 const struct got_error *err = NULL;
4673 struct got_blob_object *blob1 = NULL;
4674 int fd = -1, fd1 = -1, fd2 = -1;
4675 FILE *f2 = NULL;
4676 char *abspath = NULL, *label1 = NULL;
4677 struct stat sb;
4678 off_t size1 = 0;
4679 int f2_exists = 1;
4681 if (a->diff_staged) {
4682 if (staged_status != GOT_STATUS_MODIFY &&
4683 staged_status != GOT_STATUS_ADD &&
4684 staged_status != GOT_STATUS_DELETE)
4685 return NULL;
4686 } else {
4687 if (staged_status == GOT_STATUS_DELETE)
4688 return NULL;
4689 if (status == GOT_STATUS_NONEXISTENT)
4690 return got_error_set_errno(ENOENT, path);
4691 if (status != GOT_STATUS_MODIFY &&
4692 status != GOT_STATUS_ADD &&
4693 status != GOT_STATUS_DELETE &&
4694 status != GOT_STATUS_CONFLICT)
4695 return NULL;
4698 err = got_opentemp_truncate(a->f1);
4699 if (err)
4700 return got_error_from_errno("got_opentemp_truncate");
4701 err = got_opentemp_truncate(a->f2);
4702 if (err)
4703 return got_error_from_errno("got_opentemp_truncate");
4705 if (!a->header_shown) {
4706 printf("diff %s%s\n", a->diff_staged ? "-s " : "",
4707 got_worktree_get_root_path(a->worktree));
4708 printf("commit - %s\n", a->id_str);
4709 printf("path + %s%s\n",
4710 got_worktree_get_root_path(a->worktree),
4711 a->diff_staged ? " (staged changes)" : "");
4712 a->header_shown = 1;
4715 if (a->diff_staged) {
4716 const char *label1 = NULL, *label2 = NULL;
4717 switch (staged_status) {
4718 case GOT_STATUS_MODIFY:
4719 label1 = path;
4720 label2 = path;
4721 break;
4722 case GOT_STATUS_ADD:
4723 label2 = path;
4724 break;
4725 case GOT_STATUS_DELETE:
4726 label1 = path;
4727 break;
4728 default:
4729 return got_error(GOT_ERR_FILE_STATUS);
4731 fd1 = got_opentempfd();
4732 if (fd1 == -1) {
4733 err = got_error_from_errno("got_opentempfd");
4734 goto done;
4736 fd2 = got_opentempfd();
4737 if (fd2 == -1) {
4738 err = got_error_from_errno("got_opentempfd");
4739 goto done;
4741 err = got_diff_objects_as_blobs(NULL, NULL, a->f1, a->f2,
4742 fd1, fd2, blob_id, staged_blob_id, label1, label2,
4743 a->diff_algo, a->diff_context, a->ignore_whitespace,
4744 a->force_text_diff, a->repo, stdout);
4745 goto done;
4748 fd1 = got_opentempfd();
4749 if (fd1 == -1) {
4750 err = got_error_from_errno("got_opentempfd");
4751 goto done;
4754 if (staged_status == GOT_STATUS_ADD ||
4755 staged_status == GOT_STATUS_MODIFY) {
4756 char *id_str;
4757 err = got_object_open_as_blob(&blob1, a->repo, staged_blob_id,
4758 8192, fd1);
4759 if (err)
4760 goto done;
4761 err = got_object_id_str(&id_str, staged_blob_id);
4762 if (err)
4763 goto done;
4764 if (asprintf(&label1, "%s (staged)", id_str) == -1) {
4765 err = got_error_from_errno("asprintf");
4766 free(id_str);
4767 goto done;
4769 free(id_str);
4770 } else if (status != GOT_STATUS_ADD) {
4771 err = got_object_open_as_blob(&blob1, a->repo, blob_id, 8192,
4772 fd1);
4773 if (err)
4774 goto done;
4777 if (status != GOT_STATUS_DELETE) {
4778 if (asprintf(&abspath, "%s/%s",
4779 got_worktree_get_root_path(a->worktree), path) == -1) {
4780 err = got_error_from_errno("asprintf");
4781 goto done;
4784 if (dirfd != -1) {
4785 fd = openat(dirfd, de_name,
4786 O_RDONLY | O_NOFOLLOW | O_CLOEXEC);
4787 if (fd == -1) {
4788 if (!got_err_open_nofollow_on_symlink()) {
4789 err = got_error_from_errno2("openat",
4790 abspath);
4791 goto done;
4793 err = get_symlink_target_file(&fd, dirfd,
4794 de_name, abspath);
4795 if (err)
4796 goto done;
4798 } else {
4799 fd = open(abspath, O_RDONLY | O_NOFOLLOW | O_CLOEXEC);
4800 if (fd == -1) {
4801 if (!got_err_open_nofollow_on_symlink()) {
4802 err = got_error_from_errno2("open",
4803 abspath);
4804 goto done;
4806 err = get_symlink_target_file(&fd, dirfd,
4807 de_name, abspath);
4808 if (err)
4809 goto done;
4812 if (fstat(fd, &sb) == -1) {
4813 err = got_error_from_errno2("fstat", abspath);
4814 goto done;
4816 f2 = fdopen(fd, "r");
4817 if (f2 == NULL) {
4818 err = got_error_from_errno2("fdopen", abspath);
4819 goto done;
4821 fd = -1;
4822 } else {
4823 sb.st_size = 0;
4824 f2_exists = 0;
4827 if (blob1) {
4828 err = got_object_blob_dump_to_file(&size1, NULL, NULL,
4829 a->f1, blob1);
4830 if (err)
4831 goto done;
4834 err = got_diff_blob_file(blob1, a->f1, size1, label1, f2 ? f2 : a->f2,
4835 f2_exists, sb.st_size, path, GOT_DIFF_ALGORITHM_PATIENCE,
4836 a->diff_context, a->ignore_whitespace, a->force_text_diff, stdout);
4837 done:
4838 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
4839 err = got_error_from_errno("close");
4840 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
4841 err = got_error_from_errno("close");
4842 if (blob1)
4843 got_object_blob_close(blob1);
4844 if (fd != -1 && close(fd) == -1 && err == NULL)
4845 err = got_error_from_errno("close");
4846 if (f2 && fclose(f2) == EOF && err == NULL)
4847 err = got_error_from_errno("fclose");
4848 free(abspath);
4849 return err;
4852 static const struct got_error *
4853 cmd_diff(int argc, char *argv[])
4855 const struct got_error *error;
4856 struct got_repository *repo = NULL;
4857 struct got_worktree *worktree = NULL;
4858 char *cwd = NULL, *repo_path = NULL;
4859 const char *commit_args[2] = { NULL, NULL };
4860 int ncommit_args = 0;
4861 struct got_object_id *ids[2] = { NULL, NULL };
4862 char *labels[2] = { NULL, NULL };
4863 int type1 = GOT_OBJ_TYPE_ANY, type2 = GOT_OBJ_TYPE_ANY;
4864 int diff_context = 3, diff_staged = 0, ignore_whitespace = 0, ch, i;
4865 int force_text_diff = 0, force_path = 0, rflag = 0;
4866 const char *errstr;
4867 struct got_reflist_head refs;
4868 struct got_pathlist_head paths;
4869 struct got_pathlist_entry *pe;
4870 FILE *f1 = NULL, *f2 = NULL;
4871 int fd1 = -1, fd2 = -1;
4872 int *pack_fds = NULL;
4874 TAILQ_INIT(&refs);
4875 TAILQ_INIT(&paths);
4877 #ifndef PROFILE
4878 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
4879 NULL) == -1)
4880 err(1, "pledge");
4881 #endif
4883 while ((ch = getopt(argc, argv, "ac:C:r:swP")) != -1) {
4884 switch (ch) {
4885 case 'a':
4886 force_text_diff = 1;
4887 break;
4888 case 'c':
4889 if (ncommit_args >= 2)
4890 errx(1, "too many -c options used");
4891 commit_args[ncommit_args++] = optarg;
4892 break;
4893 case 'C':
4894 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
4895 &errstr);
4896 if (errstr != NULL)
4897 errx(1, "number of context lines is %s: %s",
4898 errstr, optarg);
4899 break;
4900 case 'r':
4901 repo_path = realpath(optarg, NULL);
4902 if (repo_path == NULL)
4903 return got_error_from_errno2("realpath",
4904 optarg);
4905 got_path_strip_trailing_slashes(repo_path);
4906 rflag = 1;
4907 break;
4908 case 's':
4909 diff_staged = 1;
4910 break;
4911 case 'w':
4912 ignore_whitespace = 1;
4913 break;
4914 case 'P':
4915 force_path = 1;
4916 break;
4917 default:
4918 usage_diff();
4919 /* NOTREACHED */
4923 argc -= optind;
4924 argv += optind;
4926 cwd = getcwd(NULL, 0);
4927 if (cwd == NULL) {
4928 error = got_error_from_errno("getcwd");
4929 goto done;
4932 error = got_repo_pack_fds_open(&pack_fds);
4933 if (error != NULL)
4934 goto done;
4936 if (repo_path == NULL) {
4937 error = got_worktree_open(&worktree, cwd);
4938 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4939 goto done;
4940 else
4941 error = NULL;
4942 if (worktree) {
4943 repo_path =
4944 strdup(got_worktree_get_repo_path(worktree));
4945 if (repo_path == NULL) {
4946 error = got_error_from_errno("strdup");
4947 goto done;
4949 } else {
4950 repo_path = strdup(cwd);
4951 if (repo_path == NULL) {
4952 error = got_error_from_errno("strdup");
4953 goto done;
4958 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
4959 free(repo_path);
4960 if (error != NULL)
4961 goto done;
4963 if (rflag || worktree == NULL || ncommit_args > 0) {
4964 if (force_path) {
4965 error = got_error_msg(GOT_ERR_NOT_IMPL,
4966 "-P option can only be used when diffing "
4967 "a work tree");
4968 goto done;
4970 if (diff_staged) {
4971 error = got_error_msg(GOT_ERR_NOT_IMPL,
4972 "-s option can only be used when diffing "
4973 "a work tree");
4974 goto done;
4978 error = apply_unveil(got_repo_get_path(repo), 1,
4979 worktree ? got_worktree_get_root_path(worktree) : NULL);
4980 if (error)
4981 goto done;
4983 if ((!force_path && argc == 2) || ncommit_args > 0) {
4984 int obj_type = (ncommit_args > 0 ?
4985 GOT_OBJ_TYPE_COMMIT : GOT_OBJ_TYPE_ANY);
4986 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
4987 NULL);
4988 if (error)
4989 goto done;
4990 for (i = 0; i < (ncommit_args > 0 ? ncommit_args : argc); i++) {
4991 const char *arg;
4992 if (ncommit_args > 0)
4993 arg = commit_args[i];
4994 else
4995 arg = argv[i];
4996 error = got_repo_match_object_id(&ids[i], &labels[i],
4997 arg, obj_type, &refs, repo);
4998 if (error) {
4999 if (error->code != GOT_ERR_NOT_REF &&
5000 error->code != GOT_ERR_NO_OBJ)
5001 goto done;
5002 if (ncommit_args > 0)
5003 goto done;
5004 error = NULL;
5005 break;
5010 f1 = got_opentemp();
5011 if (f1 == NULL) {
5012 error = got_error_from_errno("got_opentemp");
5013 goto done;
5016 f2 = got_opentemp();
5017 if (f2 == NULL) {
5018 error = got_error_from_errno("got_opentemp");
5019 goto done;
5022 if (ncommit_args == 0 && (ids[0] == NULL || ids[1] == NULL)) {
5023 struct print_diff_arg arg;
5024 char *id_str;
5026 if (worktree == NULL) {
5027 if (argc == 2 && ids[0] == NULL) {
5028 error = got_error_path(argv[0], GOT_ERR_NO_OBJ);
5029 goto done;
5030 } else if (argc == 2 && ids[1] == NULL) {
5031 error = got_error_path(argv[1], GOT_ERR_NO_OBJ);
5032 goto done;
5033 } else if (argc > 0) {
5034 error = got_error_fmt(GOT_ERR_NOT_WORKTREE,
5035 "%s", "specified paths cannot be resolved");
5036 goto done;
5037 } else {
5038 error = got_error(GOT_ERR_NOT_WORKTREE);
5039 goto done;
5043 error = get_worktree_paths_from_argv(&paths, argc, argv,
5044 worktree);
5045 if (error)
5046 goto done;
5048 error = got_object_id_str(&id_str,
5049 got_worktree_get_base_commit_id(worktree));
5050 if (error)
5051 goto done;
5052 arg.repo = repo;
5053 arg.worktree = worktree;
5054 arg.diff_algo = GOT_DIFF_ALGORITHM_PATIENCE;
5055 arg.diff_context = diff_context;
5056 arg.id_str = id_str;
5057 arg.header_shown = 0;
5058 arg.diff_staged = diff_staged;
5059 arg.ignore_whitespace = ignore_whitespace;
5060 arg.force_text_diff = force_text_diff;
5061 arg.f1 = f1;
5062 arg.f2 = f2;
5064 error = got_worktree_status(worktree, &paths, repo, 0,
5065 print_diff, &arg, check_cancelled, NULL);
5066 free(id_str);
5067 goto done;
5070 if (ncommit_args == 1) {
5071 struct got_commit_object *commit;
5072 error = got_object_open_as_commit(&commit, repo, ids[0]);
5073 if (error)
5074 goto done;
5076 labels[1] = labels[0];
5077 ids[1] = ids[0];
5078 if (got_object_commit_get_nparents(commit) > 0) {
5079 const struct got_object_id_queue *pids;
5080 struct got_object_qid *pid;
5081 pids = got_object_commit_get_parent_ids(commit);
5082 pid = STAILQ_FIRST(pids);
5083 ids[0] = got_object_id_dup(&pid->id);
5084 if (ids[0] == NULL) {
5085 error = got_error_from_errno(
5086 "got_object_id_dup");
5087 got_object_commit_close(commit);
5088 goto done;
5090 error = got_object_id_str(&labels[0], ids[0]);
5091 if (error) {
5092 got_object_commit_close(commit);
5093 goto done;
5095 } else {
5096 ids[0] = NULL;
5097 labels[0] = strdup("/dev/null");
5098 if (labels[0] == NULL) {
5099 error = got_error_from_errno("strdup");
5100 got_object_commit_close(commit);
5101 goto done;
5105 got_object_commit_close(commit);
5108 if (ncommit_args == 0 && argc > 2) {
5109 error = got_error_msg(GOT_ERR_BAD_PATH,
5110 "path arguments cannot be used when diffing two objects");
5111 goto done;
5114 if (ids[0]) {
5115 error = got_object_get_type(&type1, repo, ids[0]);
5116 if (error)
5117 goto done;
5120 error = got_object_get_type(&type2, repo, ids[1]);
5121 if (error)
5122 goto done;
5123 if (type1 != GOT_OBJ_TYPE_ANY && type1 != type2) {
5124 error = got_error(GOT_ERR_OBJ_TYPE);
5125 goto done;
5127 if (type1 == GOT_OBJ_TYPE_BLOB && argc > 0) {
5128 error = got_error_msg(GOT_ERR_OBJ_TYPE,
5129 "path arguments cannot be used when diffing blobs");
5130 goto done;
5133 for (i = 0; ncommit_args > 0 && i < argc; i++) {
5134 char *in_repo_path;
5135 struct got_pathlist_entry *new;
5136 if (worktree) {
5137 const char *prefix;
5138 char *p;
5139 error = got_worktree_resolve_path(&p, worktree,
5140 argv[i]);
5141 if (error)
5142 goto done;
5143 prefix = got_worktree_get_path_prefix(worktree);
5144 while (prefix[0] == '/')
5145 prefix++;
5146 if (asprintf(&in_repo_path, "%s%s%s", prefix,
5147 (p[0] != '\0' && prefix[0] != '\0') ? "/" : "",
5148 p) == -1) {
5149 error = got_error_from_errno("asprintf");
5150 free(p);
5151 goto done;
5153 free(p);
5154 } else {
5155 char *mapped_path, *s;
5156 error = got_repo_map_path(&mapped_path, repo, argv[i]);
5157 if (error)
5158 goto done;
5159 s = mapped_path;
5160 while (s[0] == '/')
5161 s++;
5162 in_repo_path = strdup(s);
5163 if (in_repo_path == NULL) {
5164 error = got_error_from_errno("asprintf");
5165 free(mapped_path);
5166 goto done;
5168 free(mapped_path);
5171 error = got_pathlist_insert(&new, &paths, in_repo_path, NULL);
5172 if (error || new == NULL /* duplicate */)
5173 free(in_repo_path);
5174 if (error)
5175 goto done;
5178 if (worktree) {
5179 /* Release work tree lock. */
5180 got_worktree_close(worktree);
5181 worktree = NULL;
5184 fd1 = got_opentempfd();
5185 if (fd1 == -1) {
5186 error = got_error_from_errno("got_opentempfd");
5187 goto done;
5190 fd2 = got_opentempfd();
5191 if (fd2 == -1) {
5192 error = got_error_from_errno("got_opentempfd");
5193 goto done;
5196 switch (type1 == GOT_OBJ_TYPE_ANY ? type2 : type1) {
5197 case GOT_OBJ_TYPE_BLOB:
5198 error = got_diff_objects_as_blobs(NULL, NULL, f1, f2,
5199 fd1, fd2, ids[0], ids[1], NULL, NULL,
5200 GOT_DIFF_ALGORITHM_PATIENCE, diff_context,
5201 ignore_whitespace, force_text_diff, repo, stdout);
5202 break;
5203 case GOT_OBJ_TYPE_TREE:
5204 error = got_diff_objects_as_trees(NULL, NULL, f1, f2, fd1, fd2,
5205 ids[0], ids[1], &paths, "", "",
5206 GOT_DIFF_ALGORITHM_PATIENCE, diff_context,
5207 ignore_whitespace, force_text_diff, repo, stdout);
5208 break;
5209 case GOT_OBJ_TYPE_COMMIT:
5210 printf("diff %s %s\n", labels[0], labels[1]);
5211 error = got_diff_objects_as_commits(NULL, NULL, f1, f2,
5212 fd1, fd2, ids[0], ids[1], &paths,
5213 GOT_DIFF_ALGORITHM_PATIENCE, diff_context,
5214 ignore_whitespace, force_text_diff, repo, stdout);
5215 break;
5216 default:
5217 error = got_error(GOT_ERR_OBJ_TYPE);
5219 done:
5220 free(labels[0]);
5221 free(labels[1]);
5222 free(ids[0]);
5223 free(ids[1]);
5224 if (worktree)
5225 got_worktree_close(worktree);
5226 if (repo) {
5227 const struct got_error *close_err = got_repo_close(repo);
5228 if (error == NULL)
5229 error = close_err;
5231 if (pack_fds) {
5232 const struct got_error *pack_err =
5233 got_repo_pack_fds_close(pack_fds);
5234 if (error == NULL)
5235 error = pack_err;
5237 TAILQ_FOREACH(pe, &paths, entry)
5238 free((char *)pe->path);
5239 got_pathlist_free(&paths);
5240 got_ref_list_free(&refs);
5241 if (f1 && fclose(f1) == EOF && error == NULL)
5242 error = got_error_from_errno("fclose");
5243 if (f2 && fclose(f2) == EOF && error == NULL)
5244 error = got_error_from_errno("fclose");
5245 if (fd1 != -1 && close(fd1) == -1 && error == NULL)
5246 error = got_error_from_errno("close");
5247 if (fd2 != -1 && close(fd2) == -1 && error == NULL)
5248 error = got_error_from_errno("close");
5249 return error;
5252 __dead static void
5253 usage_blame(void)
5255 fprintf(stderr,
5256 "usage: %s blame [-c commit] [-r repository-path] path\n",
5257 getprogname());
5258 exit(1);
5261 struct blame_line {
5262 int annotated;
5263 char *id_str;
5264 char *committer;
5265 char datebuf[11]; /* YYYY-MM-DD + NUL */
5268 struct blame_cb_args {
5269 struct blame_line *lines;
5270 int nlines;
5271 int nlines_prec;
5272 int lineno_cur;
5273 off_t *line_offsets;
5274 FILE *f;
5275 struct got_repository *repo;
5278 static const struct got_error *
5279 blame_cb(void *arg, int nlines, int lineno,
5280 struct got_commit_object *commit, struct got_object_id *id)
5282 const struct got_error *err = NULL;
5283 struct blame_cb_args *a = arg;
5284 struct blame_line *bline;
5285 char *line = NULL;
5286 size_t linesize = 0;
5287 off_t offset;
5288 struct tm tm;
5289 time_t committer_time;
5291 if (nlines != a->nlines ||
5292 (lineno != -1 && lineno < 1) || lineno > a->nlines)
5293 return got_error(GOT_ERR_RANGE);
5295 if (sigint_received)
5296 return got_error(GOT_ERR_ITER_COMPLETED);
5298 if (lineno == -1)
5299 return NULL; /* no change in this commit */
5301 /* Annotate this line. */
5302 bline = &a->lines[lineno - 1];
5303 if (bline->annotated)
5304 return NULL;
5305 err = got_object_id_str(&bline->id_str, id);
5306 if (err)
5307 return err;
5309 bline->committer = strdup(got_object_commit_get_committer(commit));
5310 if (bline->committer == NULL) {
5311 err = got_error_from_errno("strdup");
5312 goto done;
5315 committer_time = got_object_commit_get_committer_time(commit);
5316 if (gmtime_r(&committer_time, &tm) == NULL)
5317 return got_error_from_errno("gmtime_r");
5318 if (strftime(bline->datebuf, sizeof(bline->datebuf), "%G-%m-%d",
5319 &tm) == 0) {
5320 err = got_error(GOT_ERR_NO_SPACE);
5321 goto done;
5323 bline->annotated = 1;
5325 /* Print lines annotated so far. */
5326 bline = &a->lines[a->lineno_cur - 1];
5327 if (!bline->annotated)
5328 goto done;
5330 offset = a->line_offsets[a->lineno_cur - 1];
5331 if (fseeko(a->f, offset, SEEK_SET) == -1) {
5332 err = got_error_from_errno("fseeko");
5333 goto done;
5336 while (bline->annotated) {
5337 char *smallerthan, *at, *nl, *committer;
5338 size_t len;
5340 if (getline(&line, &linesize, a->f) == -1) {
5341 if (ferror(a->f))
5342 err = got_error_from_errno("getline");
5343 break;
5346 committer = bline->committer;
5347 smallerthan = strchr(committer, '<');
5348 if (smallerthan && smallerthan[1] != '\0')
5349 committer = smallerthan + 1;
5350 at = strchr(committer, '@');
5351 if (at)
5352 *at = '\0';
5353 len = strlen(committer);
5354 if (len >= 9)
5355 committer[8] = '\0';
5357 nl = strchr(line, '\n');
5358 if (nl)
5359 *nl = '\0';
5360 printf("%.*d) %.8s %s %-8s %s\n", a->nlines_prec, a->lineno_cur,
5361 bline->id_str, bline->datebuf, committer, line);
5363 a->lineno_cur++;
5364 bline = &a->lines[a->lineno_cur - 1];
5366 done:
5367 free(line);
5368 return err;
5371 static const struct got_error *
5372 cmd_blame(int argc, char *argv[])
5374 const struct got_error *error;
5375 struct got_repository *repo = NULL;
5376 struct got_worktree *worktree = NULL;
5377 char *path, *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
5378 char *link_target = NULL;
5379 struct got_object_id *obj_id = NULL;
5380 struct got_object_id *commit_id = NULL;
5381 struct got_commit_object *commit = NULL;
5382 struct got_blob_object *blob = NULL;
5383 char *commit_id_str = NULL;
5384 struct blame_cb_args bca;
5385 int ch, obj_type, i, fd1 = -1, fd2 = -1, fd3 = -1;
5386 off_t filesize;
5387 int *pack_fds = NULL;
5388 FILE *f1 = NULL, *f2 = NULL;
5390 fd1 = got_opentempfd();
5391 if (fd1 == -1)
5392 return got_error_from_errno("got_opentempfd");
5394 memset(&bca, 0, sizeof(bca));
5396 #ifndef PROFILE
5397 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
5398 NULL) == -1)
5399 err(1, "pledge");
5400 #endif
5402 while ((ch = getopt(argc, argv, "c:r:")) != -1) {
5403 switch (ch) {
5404 case 'c':
5405 commit_id_str = optarg;
5406 break;
5407 case 'r':
5408 repo_path = realpath(optarg, NULL);
5409 if (repo_path == NULL)
5410 return got_error_from_errno2("realpath",
5411 optarg);
5412 got_path_strip_trailing_slashes(repo_path);
5413 break;
5414 default:
5415 usage_blame();
5416 /* NOTREACHED */
5420 argc -= optind;
5421 argv += optind;
5423 if (argc == 1)
5424 path = argv[0];
5425 else
5426 usage_blame();
5428 cwd = getcwd(NULL, 0);
5429 if (cwd == NULL) {
5430 error = got_error_from_errno("getcwd");
5431 goto done;
5434 error = got_repo_pack_fds_open(&pack_fds);
5435 if (error != NULL)
5436 goto done;
5438 if (repo_path == NULL) {
5439 error = got_worktree_open(&worktree, cwd);
5440 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5441 goto done;
5442 else
5443 error = NULL;
5444 if (worktree) {
5445 repo_path =
5446 strdup(got_worktree_get_repo_path(worktree));
5447 if (repo_path == NULL) {
5448 error = got_error_from_errno("strdup");
5449 if (error)
5450 goto done;
5452 } else {
5453 repo_path = strdup(cwd);
5454 if (repo_path == NULL) {
5455 error = got_error_from_errno("strdup");
5456 goto done;
5461 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
5462 if (error != NULL)
5463 goto done;
5465 if (worktree) {
5466 const char *prefix = got_worktree_get_path_prefix(worktree);
5467 char *p;
5469 error = got_worktree_resolve_path(&p, worktree, path);
5470 if (error)
5471 goto done;
5472 if (asprintf(&in_repo_path, "%s%s%s", prefix,
5473 (p[0] != '\0' && !got_path_is_root_dir(prefix)) ? "/" : "",
5474 p) == -1) {
5475 error = got_error_from_errno("asprintf");
5476 free(p);
5477 goto done;
5479 free(p);
5480 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5481 } else {
5482 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5483 if (error)
5484 goto done;
5485 error = got_repo_map_path(&in_repo_path, repo, path);
5487 if (error)
5488 goto done;
5490 if (commit_id_str == NULL) {
5491 struct got_reference *head_ref;
5492 error = got_ref_open(&head_ref, repo, worktree ?
5493 got_worktree_get_head_ref_name(worktree) : GOT_REF_HEAD, 0);
5494 if (error != NULL)
5495 goto done;
5496 error = got_ref_resolve(&commit_id, repo, head_ref);
5497 got_ref_close(head_ref);
5498 if (error != NULL)
5499 goto done;
5500 } else {
5501 struct got_reflist_head refs;
5502 TAILQ_INIT(&refs);
5503 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
5504 NULL);
5505 if (error)
5506 goto done;
5507 error = got_repo_match_object_id(&commit_id, NULL,
5508 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
5509 got_ref_list_free(&refs);
5510 if (error)
5511 goto done;
5514 if (worktree) {
5515 /* Release work tree lock. */
5516 got_worktree_close(worktree);
5517 worktree = NULL;
5520 error = got_object_open_as_commit(&commit, repo, commit_id);
5521 if (error)
5522 goto done;
5524 error = got_object_resolve_symlinks(&link_target, in_repo_path,
5525 commit, repo);
5526 if (error)
5527 goto done;
5529 error = got_object_id_by_path(&obj_id, repo, commit,
5530 link_target ? link_target : in_repo_path);
5531 if (error)
5532 goto done;
5534 error = got_object_get_type(&obj_type, repo, obj_id);
5535 if (error)
5536 goto done;
5538 if (obj_type != GOT_OBJ_TYPE_BLOB) {
5539 error = got_error_path(link_target ? link_target : in_repo_path,
5540 GOT_ERR_OBJ_TYPE);
5541 goto done;
5544 error = got_object_open_as_blob(&blob, repo, obj_id, 8192, fd1);
5545 if (error)
5546 goto done;
5547 bca.f = got_opentemp();
5548 if (bca.f == NULL) {
5549 error = got_error_from_errno("got_opentemp");
5550 goto done;
5552 error = got_object_blob_dump_to_file(&filesize, &bca.nlines,
5553 &bca.line_offsets, bca.f, blob);
5554 if (error || bca.nlines == 0)
5555 goto done;
5557 /* Don't include \n at EOF in the blame line count. */
5558 if (bca.line_offsets[bca.nlines - 1] == filesize)
5559 bca.nlines--;
5561 bca.lines = calloc(bca.nlines, sizeof(*bca.lines));
5562 if (bca.lines == NULL) {
5563 error = got_error_from_errno("calloc");
5564 goto done;
5566 bca.lineno_cur = 1;
5567 bca.nlines_prec = 0;
5568 i = bca.nlines;
5569 while (i > 0) {
5570 i /= 10;
5571 bca.nlines_prec++;
5573 bca.repo = repo;
5575 fd2 = got_opentempfd();
5576 if (fd2 == -1) {
5577 error = got_error_from_errno("got_opentempfd");
5578 goto done;
5580 fd3 = got_opentempfd();
5581 if (fd3 == -1) {
5582 error = got_error_from_errno("got_opentempfd");
5583 goto done;
5585 f1 = got_opentemp();
5586 if (f1 == NULL) {
5587 error = got_error_from_errno("got_opentemp");
5588 goto done;
5590 f2 = got_opentemp();
5591 if (f2 == NULL) {
5592 error = got_error_from_errno("got_opentemp");
5593 goto done;
5595 error = got_blame(link_target ? link_target : in_repo_path, commit_id,
5596 repo, GOT_DIFF_ALGORITHM_PATIENCE, blame_cb, &bca,
5597 check_cancelled, NULL, fd2, fd3, f1, f2);
5598 done:
5599 free(in_repo_path);
5600 free(link_target);
5601 free(repo_path);
5602 free(cwd);
5603 free(commit_id);
5604 free(obj_id);
5605 if (commit)
5606 got_object_commit_close(commit);
5608 if (fd1 != -1 && close(fd1) == -1 && error == NULL)
5609 error = got_error_from_errno("close");
5610 if (fd2 != -1 && close(fd2) == -1 && error == NULL)
5611 error = got_error_from_errno("close");
5612 if (fd3 != -1 && close(fd3) == -1 && error == NULL)
5613 error = got_error_from_errno("close");
5614 if (f1 && fclose(f1) == EOF && error == NULL)
5615 error = got_error_from_errno("fclose");
5616 if (f2 && fclose(f2) == EOF && error == NULL)
5617 error = got_error_from_errno("fclose");
5619 if (blob)
5620 got_object_blob_close(blob);
5621 if (worktree)
5622 got_worktree_close(worktree);
5623 if (repo) {
5624 const struct got_error *close_err = got_repo_close(repo);
5625 if (error == NULL)
5626 error = close_err;
5628 if (pack_fds) {
5629 const struct got_error *pack_err =
5630 got_repo_pack_fds_close(pack_fds);
5631 if (error == NULL)
5632 error = pack_err;
5634 if (bca.lines) {
5635 for (i = 0; i < bca.nlines; i++) {
5636 struct blame_line *bline = &bca.lines[i];
5637 free(bline->id_str);
5638 free(bline->committer);
5640 free(bca.lines);
5642 free(bca.line_offsets);
5643 if (bca.f && fclose(bca.f) == EOF && error == NULL)
5644 error = got_error_from_errno("fclose");
5645 return error;
5648 __dead static void
5649 usage_tree(void)
5651 fprintf(stderr,
5652 "usage: %s tree [-c commit] [-r repository-path] [-iR] [path]\n",
5653 getprogname());
5654 exit(1);
5657 static const struct got_error *
5658 print_entry(struct got_tree_entry *te, const char *id, const char *path,
5659 const char *root_path, struct got_repository *repo)
5661 const struct got_error *err = NULL;
5662 int is_root_path = (strcmp(path, root_path) == 0);
5663 const char *modestr = "";
5664 mode_t mode = got_tree_entry_get_mode(te);
5665 char *link_target = NULL;
5667 path += strlen(root_path);
5668 while (path[0] == '/')
5669 path++;
5671 if (got_object_tree_entry_is_submodule(te))
5672 modestr = "$";
5673 else if (S_ISLNK(mode)) {
5674 int i;
5676 err = got_tree_entry_get_symlink_target(&link_target, te, repo);
5677 if (err)
5678 return err;
5679 for (i = 0; i < strlen(link_target); i++) {
5680 if (!isprint((unsigned char)link_target[i]))
5681 link_target[i] = '?';
5684 modestr = "@";
5686 else if (S_ISDIR(mode))
5687 modestr = "/";
5688 else if (mode & S_IXUSR)
5689 modestr = "*";
5691 printf("%s%s%s%s%s%s%s\n", id ? id : "", path,
5692 is_root_path ? "" : "/", got_tree_entry_get_name(te), modestr,
5693 link_target ? " -> ": "", link_target ? link_target : "");
5695 free(link_target);
5696 return NULL;
5699 static const struct got_error *
5700 print_tree(const char *path, struct got_commit_object *commit,
5701 int show_ids, int recurse, const char *root_path,
5702 struct got_repository *repo)
5704 const struct got_error *err = NULL;
5705 struct got_object_id *tree_id = NULL;
5706 struct got_tree_object *tree = NULL;
5707 int nentries, i;
5709 err = got_object_id_by_path(&tree_id, repo, commit, path);
5710 if (err)
5711 goto done;
5713 err = got_object_open_as_tree(&tree, repo, tree_id);
5714 if (err)
5715 goto done;
5716 nentries = got_object_tree_get_nentries(tree);
5717 for (i = 0; i < nentries; i++) {
5718 struct got_tree_entry *te;
5719 char *id = NULL;
5721 if (sigint_received || sigpipe_received)
5722 break;
5724 te = got_object_tree_get_entry(tree, i);
5725 if (show_ids) {
5726 char *id_str;
5727 err = got_object_id_str(&id_str,
5728 got_tree_entry_get_id(te));
5729 if (err)
5730 goto done;
5731 if (asprintf(&id, "%s ", id_str) == -1) {
5732 err = got_error_from_errno("asprintf");
5733 free(id_str);
5734 goto done;
5736 free(id_str);
5738 err = print_entry(te, id, path, root_path, repo);
5739 free(id);
5740 if (err)
5741 goto done;
5743 if (recurse && S_ISDIR(got_tree_entry_get_mode(te))) {
5744 char *child_path;
5745 if (asprintf(&child_path, "%s%s%s", path,
5746 path[0] == '/' && path[1] == '\0' ? "" : "/",
5747 got_tree_entry_get_name(te)) == -1) {
5748 err = got_error_from_errno("asprintf");
5749 goto done;
5751 err = print_tree(child_path, commit, show_ids, 1,
5752 root_path, repo);
5753 free(child_path);
5754 if (err)
5755 goto done;
5758 done:
5759 if (tree)
5760 got_object_tree_close(tree);
5761 free(tree_id);
5762 return err;
5765 static const struct got_error *
5766 cmd_tree(int argc, char *argv[])
5768 const struct got_error *error;
5769 struct got_repository *repo = NULL;
5770 struct got_worktree *worktree = NULL;
5771 const char *path, *refname = NULL;
5772 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
5773 struct got_object_id *commit_id = NULL;
5774 struct got_commit_object *commit = NULL;
5775 char *commit_id_str = NULL;
5776 int show_ids = 0, recurse = 0;
5777 int ch;
5778 int *pack_fds = NULL;
5780 #ifndef PROFILE
5781 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
5782 NULL) == -1)
5783 err(1, "pledge");
5784 #endif
5786 while ((ch = getopt(argc, argv, "c:r:iR")) != -1) {
5787 switch (ch) {
5788 case 'c':
5789 commit_id_str = optarg;
5790 break;
5791 case 'r':
5792 repo_path = realpath(optarg, NULL);
5793 if (repo_path == NULL)
5794 return got_error_from_errno2("realpath",
5795 optarg);
5796 got_path_strip_trailing_slashes(repo_path);
5797 break;
5798 case 'i':
5799 show_ids = 1;
5800 break;
5801 case 'R':
5802 recurse = 1;
5803 break;
5804 default:
5805 usage_tree();
5806 /* NOTREACHED */
5810 argc -= optind;
5811 argv += optind;
5813 if (argc == 1)
5814 path = argv[0];
5815 else if (argc > 1)
5816 usage_tree();
5817 else
5818 path = NULL;
5820 cwd = getcwd(NULL, 0);
5821 if (cwd == NULL) {
5822 error = got_error_from_errno("getcwd");
5823 goto done;
5826 error = got_repo_pack_fds_open(&pack_fds);
5827 if (error != NULL)
5828 goto done;
5830 if (repo_path == NULL) {
5831 error = got_worktree_open(&worktree, cwd);
5832 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5833 goto done;
5834 else
5835 error = NULL;
5836 if (worktree) {
5837 repo_path =
5838 strdup(got_worktree_get_repo_path(worktree));
5839 if (repo_path == NULL)
5840 error = got_error_from_errno("strdup");
5841 if (error)
5842 goto done;
5843 } else {
5844 repo_path = strdup(cwd);
5845 if (repo_path == NULL) {
5846 error = got_error_from_errno("strdup");
5847 goto done;
5852 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
5853 if (error != NULL)
5854 goto done;
5856 if (worktree) {
5857 const char *prefix = got_worktree_get_path_prefix(worktree);
5858 char *p;
5860 if (path == NULL)
5861 path = "";
5862 error = got_worktree_resolve_path(&p, worktree, path);
5863 if (error)
5864 goto done;
5865 if (asprintf(&in_repo_path, "%s%s%s", prefix,
5866 (p[0] != '\0' && !got_path_is_root_dir(prefix)) ? "/" : "",
5867 p) == -1) {
5868 error = got_error_from_errno("asprintf");
5869 free(p);
5870 goto done;
5872 free(p);
5873 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5874 if (error)
5875 goto done;
5876 } else {
5877 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5878 if (error)
5879 goto done;
5880 if (path == NULL)
5881 path = "/";
5882 error = got_repo_map_path(&in_repo_path, repo, path);
5883 if (error != NULL)
5884 goto done;
5887 if (commit_id_str == NULL) {
5888 struct got_reference *head_ref;
5889 if (worktree)
5890 refname = got_worktree_get_head_ref_name(worktree);
5891 else
5892 refname = GOT_REF_HEAD;
5893 error = got_ref_open(&head_ref, repo, refname, 0);
5894 if (error != NULL)
5895 goto done;
5896 error = got_ref_resolve(&commit_id, repo, head_ref);
5897 got_ref_close(head_ref);
5898 if (error != NULL)
5899 goto done;
5900 } else {
5901 struct got_reflist_head refs;
5902 TAILQ_INIT(&refs);
5903 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
5904 NULL);
5905 if (error)
5906 goto done;
5907 error = got_repo_match_object_id(&commit_id, NULL,
5908 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
5909 got_ref_list_free(&refs);
5910 if (error)
5911 goto done;
5914 if (worktree) {
5915 /* Release work tree lock. */
5916 got_worktree_close(worktree);
5917 worktree = NULL;
5920 error = got_object_open_as_commit(&commit, repo, commit_id);
5921 if (error)
5922 goto done;
5924 error = print_tree(in_repo_path, commit, show_ids, recurse,
5925 in_repo_path, repo);
5926 done:
5927 free(in_repo_path);
5928 free(repo_path);
5929 free(cwd);
5930 free(commit_id);
5931 if (commit)
5932 got_object_commit_close(commit);
5933 if (worktree)
5934 got_worktree_close(worktree);
5935 if (repo) {
5936 const struct got_error *close_err = got_repo_close(repo);
5937 if (error == NULL)
5938 error = close_err;
5940 if (pack_fds) {
5941 const struct got_error *pack_err =
5942 got_repo_pack_fds_close(pack_fds);
5943 if (error == NULL)
5944 error = pack_err;
5946 return error;
5949 __dead static void
5950 usage_status(void)
5952 fprintf(stderr, "usage: %s status [-I] [-s status-codes ] "
5953 "[-S status-codes] [path ...]\n", getprogname());
5954 exit(1);
5957 struct got_status_arg {
5958 char *status_codes;
5959 int suppress;
5962 static const struct got_error *
5963 print_status(void *arg, unsigned char status, unsigned char staged_status,
5964 const char *path, struct got_object_id *blob_id,
5965 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
5966 int dirfd, const char *de_name)
5968 struct got_status_arg *st = arg;
5970 if (status == staged_status && (status == GOT_STATUS_DELETE))
5971 status = GOT_STATUS_NO_CHANGE;
5972 if (st != NULL && st->status_codes) {
5973 size_t ncodes = strlen(st->status_codes);
5974 int i, j = 0;
5976 for (i = 0; i < ncodes ; i++) {
5977 if (st->suppress) {
5978 if (status == st->status_codes[i] ||
5979 staged_status == st->status_codes[i]) {
5980 j++;
5981 continue;
5983 } else {
5984 if (status == st->status_codes[i] ||
5985 staged_status == st->status_codes[i])
5986 break;
5990 if (st->suppress && j == 0)
5991 goto print;
5993 if (i == ncodes)
5994 return NULL;
5996 print:
5997 printf("%c%c %s\n", status, staged_status, path);
5998 return NULL;
6001 static const struct got_error *
6002 cmd_status(int argc, char *argv[])
6004 const struct got_error *error = NULL;
6005 struct got_repository *repo = NULL;
6006 struct got_worktree *worktree = NULL;
6007 struct got_status_arg st;
6008 char *cwd = NULL;
6009 struct got_pathlist_head paths;
6010 struct got_pathlist_entry *pe;
6011 int ch, i, no_ignores = 0;
6012 int *pack_fds = NULL;
6014 TAILQ_INIT(&paths);
6016 memset(&st, 0, sizeof(st));
6017 st.status_codes = NULL;
6018 st.suppress = 0;
6020 while ((ch = getopt(argc, argv, "Is:S:")) != -1) {
6021 switch (ch) {
6022 case 'I':
6023 no_ignores = 1;
6024 break;
6025 case 'S':
6026 if (st.status_codes != NULL && st.suppress == 0)
6027 option_conflict('S', 's');
6028 st.suppress = 1;
6029 /* fallthrough */
6030 case 's':
6031 for (i = 0; i < strlen(optarg); i++) {
6032 switch (optarg[i]) {
6033 case GOT_STATUS_MODIFY:
6034 case GOT_STATUS_ADD:
6035 case GOT_STATUS_DELETE:
6036 case GOT_STATUS_CONFLICT:
6037 case GOT_STATUS_MISSING:
6038 case GOT_STATUS_OBSTRUCTED:
6039 case GOT_STATUS_UNVERSIONED:
6040 case GOT_STATUS_MODE_CHANGE:
6041 case GOT_STATUS_NONEXISTENT:
6042 break;
6043 default:
6044 errx(1, "invalid status code '%c'",
6045 optarg[i]);
6048 if (ch == 's' && st.suppress)
6049 option_conflict('s', 'S');
6050 st.status_codes = optarg;
6051 break;
6052 default:
6053 usage_status();
6054 /* NOTREACHED */
6058 argc -= optind;
6059 argv += optind;
6061 #ifndef PROFILE
6062 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
6063 NULL) == -1)
6064 err(1, "pledge");
6065 #endif
6066 cwd = getcwd(NULL, 0);
6067 if (cwd == NULL) {
6068 error = got_error_from_errno("getcwd");
6069 goto done;
6072 error = got_repo_pack_fds_open(&pack_fds);
6073 if (error != NULL)
6074 goto done;
6076 error = got_worktree_open(&worktree, cwd);
6077 if (error) {
6078 if (error->code == GOT_ERR_NOT_WORKTREE)
6079 error = wrap_not_worktree_error(error, "status", cwd);
6080 goto done;
6083 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
6084 NULL, pack_fds);
6085 if (error != NULL)
6086 goto done;
6088 error = apply_unveil(got_repo_get_path(repo), 1,
6089 got_worktree_get_root_path(worktree));
6090 if (error)
6091 goto done;
6093 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
6094 if (error)
6095 goto done;
6097 error = got_worktree_status(worktree, &paths, repo, no_ignores,
6098 print_status, &st, check_cancelled, NULL);
6099 done:
6100 if (pack_fds) {
6101 const struct got_error *pack_err =
6102 got_repo_pack_fds_close(pack_fds);
6103 if (error == NULL)
6104 error = pack_err;
6107 TAILQ_FOREACH(pe, &paths, entry)
6108 free((char *)pe->path);
6109 got_pathlist_free(&paths);
6110 free(cwd);
6111 return error;
6114 __dead static void
6115 usage_ref(void)
6117 fprintf(stderr,
6118 "usage: %s ref [-r repository] [-l] [-t] [-c object] "
6119 "[-s reference] [-d] [name]\n",
6120 getprogname());
6121 exit(1);
6124 static const struct got_error *
6125 list_refs(struct got_repository *repo, const char *refname, int sort_by_time)
6127 static const struct got_error *err = NULL;
6128 struct got_reflist_head refs;
6129 struct got_reflist_entry *re;
6131 TAILQ_INIT(&refs);
6132 err = got_ref_list(&refs, repo, refname, sort_by_time ?
6133 got_ref_cmp_by_commit_timestamp_descending : got_ref_cmp_by_name,
6134 repo);
6135 if (err)
6136 return err;
6138 TAILQ_FOREACH(re, &refs, entry) {
6139 char *refstr;
6140 refstr = got_ref_to_str(re->ref);
6141 if (refstr == NULL) {
6142 err = got_error_from_errno("got_ref_to_str");
6143 break;
6145 printf("%s: %s\n", got_ref_get_name(re->ref), refstr);
6146 free(refstr);
6149 got_ref_list_free(&refs);
6150 return err;
6153 static const struct got_error *
6154 delete_ref_by_name(struct got_repository *repo, const char *refname)
6156 const struct got_error *err;
6157 struct got_reference *ref;
6159 err = got_ref_open(&ref, repo, refname, 0);
6160 if (err)
6161 return err;
6163 err = delete_ref(repo, ref);
6164 got_ref_close(ref);
6165 return err;
6168 static const struct got_error *
6169 add_ref(struct got_repository *repo, const char *refname, const char *target)
6171 const struct got_error *err = NULL;
6172 struct got_object_id *id = NULL;
6173 struct got_reference *ref = NULL;
6174 struct got_reflist_head refs;
6177 * Don't let the user create a reference name with a leading '-'.
6178 * While technically a valid reference name, this case is usually
6179 * an unintended typo.
6181 if (refname[0] == '-')
6182 return got_error_path(refname, GOT_ERR_REF_NAME_MINUS);
6184 TAILQ_INIT(&refs);
6185 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
6186 if (err)
6187 goto done;
6188 err = got_repo_match_object_id(&id, NULL, target, GOT_OBJ_TYPE_ANY,
6189 &refs, repo);
6190 got_ref_list_free(&refs);
6191 if (err)
6192 goto done;
6194 err = got_ref_alloc(&ref, refname, id);
6195 if (err)
6196 goto done;
6198 err = got_ref_write(ref, repo);
6199 done:
6200 if (ref)
6201 got_ref_close(ref);
6202 free(id);
6203 return err;
6206 static const struct got_error *
6207 add_symref(struct got_repository *repo, const char *refname, const char *target)
6209 const struct got_error *err = NULL;
6210 struct got_reference *ref = NULL;
6211 struct got_reference *target_ref = NULL;
6214 * Don't let the user create a reference name with a leading '-'.
6215 * While technically a valid reference name, this case is usually
6216 * an unintended typo.
6218 if (refname[0] == '-')
6219 return got_error_path(refname, GOT_ERR_REF_NAME_MINUS);
6221 err = got_ref_open(&target_ref, repo, target, 0);
6222 if (err)
6223 return err;
6225 err = got_ref_alloc_symref(&ref, refname, target_ref);
6226 if (err)
6227 goto done;
6229 err = got_ref_write(ref, repo);
6230 done:
6231 if (target_ref)
6232 got_ref_close(target_ref);
6233 if (ref)
6234 got_ref_close(ref);
6235 return err;
6238 static const struct got_error *
6239 cmd_ref(int argc, char *argv[])
6241 const struct got_error *error = NULL;
6242 struct got_repository *repo = NULL;
6243 struct got_worktree *worktree = NULL;
6244 char *cwd = NULL, *repo_path = NULL;
6245 int ch, do_list = 0, do_delete = 0, sort_by_time = 0;
6246 const char *obj_arg = NULL, *symref_target= NULL;
6247 char *refname = NULL;
6248 int *pack_fds = NULL;
6250 while ((ch = getopt(argc, argv, "c:dr:ls:t")) != -1) {
6251 switch (ch) {
6252 case 'c':
6253 obj_arg = optarg;
6254 break;
6255 case 'd':
6256 do_delete = 1;
6257 break;
6258 case 'r':
6259 repo_path = realpath(optarg, NULL);
6260 if (repo_path == NULL)
6261 return got_error_from_errno2("realpath",
6262 optarg);
6263 got_path_strip_trailing_slashes(repo_path);
6264 break;
6265 case 'l':
6266 do_list = 1;
6267 break;
6268 case 's':
6269 symref_target = optarg;
6270 break;
6271 case 't':
6272 sort_by_time = 1;
6273 break;
6274 default:
6275 usage_ref();
6276 /* NOTREACHED */
6280 if (obj_arg && do_list)
6281 option_conflict('c', 'l');
6282 if (obj_arg && do_delete)
6283 option_conflict('c', 'd');
6284 if (obj_arg && symref_target)
6285 option_conflict('c', 's');
6286 if (symref_target && do_delete)
6287 option_conflict('s', 'd');
6288 if (symref_target && do_list)
6289 option_conflict('s', 'l');
6290 if (do_delete && do_list)
6291 option_conflict('d', 'l');
6292 if (sort_by_time && !do_list)
6293 errx(1, "-t option requires -l option");
6295 argc -= optind;
6296 argv += optind;
6298 if (do_list) {
6299 if (argc != 0 && argc != 1)
6300 usage_ref();
6301 if (argc == 1) {
6302 refname = strdup(argv[0]);
6303 if (refname == NULL) {
6304 error = got_error_from_errno("strdup");
6305 goto done;
6308 } else {
6309 if (argc != 1)
6310 usage_ref();
6311 refname = strdup(argv[0]);
6312 if (refname == NULL) {
6313 error = got_error_from_errno("strdup");
6314 goto done;
6318 if (refname)
6319 got_path_strip_trailing_slashes(refname);
6321 #ifndef PROFILE
6322 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
6323 "sendfd unveil", NULL) == -1)
6324 err(1, "pledge");
6325 #endif
6326 cwd = getcwd(NULL, 0);
6327 if (cwd == NULL) {
6328 error = got_error_from_errno("getcwd");
6329 goto done;
6332 error = got_repo_pack_fds_open(&pack_fds);
6333 if (error != NULL)
6334 goto done;
6336 if (repo_path == NULL) {
6337 error = got_worktree_open(&worktree, cwd);
6338 if (error && error->code != GOT_ERR_NOT_WORKTREE)
6339 goto done;
6340 else
6341 error = NULL;
6342 if (worktree) {
6343 repo_path =
6344 strdup(got_worktree_get_repo_path(worktree));
6345 if (repo_path == NULL)
6346 error = got_error_from_errno("strdup");
6347 if (error)
6348 goto done;
6349 } else {
6350 repo_path = strdup(cwd);
6351 if (repo_path == NULL) {
6352 error = got_error_from_errno("strdup");
6353 goto done;
6358 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
6359 if (error != NULL)
6360 goto done;
6362 #ifndef PROFILE
6363 if (do_list) {
6364 /* Remove "cpath" promise. */
6365 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
6366 NULL) == -1)
6367 err(1, "pledge");
6369 #endif
6371 error = apply_unveil(got_repo_get_path(repo), do_list,
6372 worktree ? got_worktree_get_root_path(worktree) : NULL);
6373 if (error)
6374 goto done;
6376 if (do_list)
6377 error = list_refs(repo, refname, sort_by_time);
6378 else if (do_delete)
6379 error = delete_ref_by_name(repo, refname);
6380 else if (symref_target)
6381 error = add_symref(repo, refname, symref_target);
6382 else {
6383 if (obj_arg == NULL)
6384 usage_ref();
6385 error = add_ref(repo, refname, obj_arg);
6387 done:
6388 free(refname);
6389 if (repo) {
6390 const struct got_error *close_err = got_repo_close(repo);
6391 if (error == NULL)
6392 error = close_err;
6394 if (worktree)
6395 got_worktree_close(worktree);
6396 if (pack_fds) {
6397 const struct got_error *pack_err =
6398 got_repo_pack_fds_close(pack_fds);
6399 if (error == NULL)
6400 error = pack_err;
6402 free(cwd);
6403 free(repo_path);
6404 return error;
6407 __dead static void
6408 usage_branch(void)
6410 fprintf(stderr,
6411 "usage: %s branch [-c commit] [-d] [-r repository] [-l] [-t] "
6412 "[-n] [name]\n", getprogname());
6413 exit(1);
6416 static const struct got_error *
6417 list_branch(struct got_repository *repo, struct got_worktree *worktree,
6418 struct got_reference *ref)
6420 const struct got_error *err = NULL;
6421 const char *refname, *marker = " ";
6422 char *refstr;
6424 refname = got_ref_get_name(ref);
6425 if (worktree && strcmp(refname,
6426 got_worktree_get_head_ref_name(worktree)) == 0) {
6427 struct got_object_id *id = NULL;
6429 err = got_ref_resolve(&id, repo, ref);
6430 if (err)
6431 return err;
6432 if (got_object_id_cmp(id,
6433 got_worktree_get_base_commit_id(worktree)) == 0)
6434 marker = "* ";
6435 else
6436 marker = "~ ";
6437 free(id);
6440 if (strncmp(refname, "refs/heads/", 11) == 0)
6441 refname += 11;
6442 if (strncmp(refname, "refs/got/worktree/", 18) == 0)
6443 refname += 18;
6444 if (strncmp(refname, "refs/remotes/", 13) == 0)
6445 refname += 13;
6447 refstr = got_ref_to_str(ref);
6448 if (refstr == NULL)
6449 return got_error_from_errno("got_ref_to_str");
6451 printf("%s%s: %s\n", marker, refname, refstr);
6452 free(refstr);
6453 return NULL;
6456 static const struct got_error *
6457 show_current_branch(struct got_repository *repo, struct got_worktree *worktree)
6459 const char *refname;
6461 if (worktree == NULL)
6462 return got_error(GOT_ERR_NOT_WORKTREE);
6464 refname = got_worktree_get_head_ref_name(worktree);
6466 if (strncmp(refname, "refs/heads/", 11) == 0)
6467 refname += 11;
6468 if (strncmp(refname, "refs/got/worktree/", 18) == 0)
6469 refname += 18;
6471 printf("%s\n", refname);
6473 return NULL;
6476 static const struct got_error *
6477 list_branches(struct got_repository *repo, struct got_worktree *worktree,
6478 int sort_by_time)
6480 static const struct got_error *err = NULL;
6481 struct got_reflist_head refs;
6482 struct got_reflist_entry *re;
6483 struct got_reference *temp_ref = NULL;
6484 int rebase_in_progress, histedit_in_progress;
6486 TAILQ_INIT(&refs);
6488 if (worktree) {
6489 err = got_worktree_rebase_in_progress(&rebase_in_progress,
6490 worktree);
6491 if (err)
6492 return err;
6494 err = got_worktree_histedit_in_progress(&histedit_in_progress,
6495 worktree);
6496 if (err)
6497 return err;
6499 if (rebase_in_progress || histedit_in_progress) {
6500 err = got_ref_open(&temp_ref, repo,
6501 got_worktree_get_head_ref_name(worktree), 0);
6502 if (err)
6503 return err;
6504 list_branch(repo, worktree, temp_ref);
6505 got_ref_close(temp_ref);
6509 err = got_ref_list(&refs, repo, "refs/heads", sort_by_time ?
6510 got_ref_cmp_by_commit_timestamp_descending : got_ref_cmp_by_name,
6511 repo);
6512 if (err)
6513 return err;
6515 TAILQ_FOREACH(re, &refs, entry)
6516 list_branch(repo, worktree, re->ref);
6518 got_ref_list_free(&refs);
6520 err = got_ref_list(&refs, repo, "refs/remotes", sort_by_time ?
6521 got_ref_cmp_by_commit_timestamp_descending : got_ref_cmp_by_name,
6522 repo);
6523 if (err)
6524 return err;
6526 TAILQ_FOREACH(re, &refs, entry)
6527 list_branch(repo, worktree, re->ref);
6529 got_ref_list_free(&refs);
6531 return NULL;
6534 static const struct got_error *
6535 delete_branch(struct got_repository *repo, struct got_worktree *worktree,
6536 const char *branch_name)
6538 const struct got_error *err = NULL;
6539 struct got_reference *ref = NULL;
6540 char *refname, *remote_refname = NULL;
6542 if (strncmp(branch_name, "refs/", 5) == 0)
6543 branch_name += 5;
6544 if (strncmp(branch_name, "heads/", 6) == 0)
6545 branch_name += 6;
6546 else if (strncmp(branch_name, "remotes/", 8) == 0)
6547 branch_name += 8;
6549 if (asprintf(&refname, "refs/heads/%s", branch_name) == -1)
6550 return got_error_from_errno("asprintf");
6552 if (asprintf(&remote_refname, "refs/remotes/%s",
6553 branch_name) == -1) {
6554 err = got_error_from_errno("asprintf");
6555 goto done;
6558 err = got_ref_open(&ref, repo, refname, 0);
6559 if (err) {
6560 const struct got_error *err2;
6561 if (err->code != GOT_ERR_NOT_REF)
6562 goto done;
6564 * Keep 'err' intact such that if neither branch exists
6565 * we report "refs/heads" rather than "refs/remotes" in
6566 * our error message.
6568 err2 = got_ref_open(&ref, repo, remote_refname, 0);
6569 if (err2)
6570 goto done;
6571 err = NULL;
6574 if (worktree &&
6575 strcmp(got_worktree_get_head_ref_name(worktree),
6576 got_ref_get_name(ref)) == 0) {
6577 err = got_error_msg(GOT_ERR_SAME_BRANCH,
6578 "will not delete this work tree's current branch");
6579 goto done;
6582 err = delete_ref(repo, ref);
6583 done:
6584 if (ref)
6585 got_ref_close(ref);
6586 free(refname);
6587 free(remote_refname);
6588 return err;
6591 static const struct got_error *
6592 add_branch(struct got_repository *repo, const char *branch_name,
6593 struct got_object_id *base_commit_id)
6595 const struct got_error *err = NULL;
6596 struct got_reference *ref = NULL;
6597 char *base_refname = NULL, *refname = NULL;
6600 * Don't let the user create a branch name with a leading '-'.
6601 * While technically a valid reference name, this case is usually
6602 * an unintended typo.
6604 if (branch_name[0] == '-')
6605 return got_error_path(branch_name, GOT_ERR_REF_NAME_MINUS);
6607 if (strncmp(branch_name, "refs/heads/", 11) == 0)
6608 branch_name += 11;
6610 if (asprintf(&refname, "refs/heads/%s", branch_name) == -1) {
6611 err = got_error_from_errno("asprintf");
6612 goto done;
6615 err = got_ref_open(&ref, repo, refname, 0);
6616 if (err == NULL) {
6617 err = got_error(GOT_ERR_BRANCH_EXISTS);
6618 goto done;
6619 } else if (err->code != GOT_ERR_NOT_REF)
6620 goto done;
6622 err = got_ref_alloc(&ref, refname, base_commit_id);
6623 if (err)
6624 goto done;
6626 err = got_ref_write(ref, repo);
6627 done:
6628 if (ref)
6629 got_ref_close(ref);
6630 free(base_refname);
6631 free(refname);
6632 return err;
6635 static const struct got_error *
6636 cmd_branch(int argc, char *argv[])
6638 const struct got_error *error = NULL;
6639 struct got_repository *repo = NULL;
6640 struct got_worktree *worktree = NULL;
6641 char *cwd = NULL, *repo_path = NULL;
6642 int ch, do_list = 0, do_show = 0, do_update = 1, sort_by_time = 0;
6643 const char *delref = NULL, *commit_id_arg = NULL;
6644 struct got_reference *ref = NULL;
6645 struct got_pathlist_head paths;
6646 struct got_pathlist_entry *pe;
6647 struct got_object_id *commit_id = NULL;
6648 char *commit_id_str = NULL;
6649 int *pack_fds = NULL;
6651 TAILQ_INIT(&paths);
6653 while ((ch = getopt(argc, argv, "c:d:r:lnt")) != -1) {
6654 switch (ch) {
6655 case 'c':
6656 commit_id_arg = optarg;
6657 break;
6658 case 'd':
6659 delref = optarg;
6660 break;
6661 case 'r':
6662 repo_path = realpath(optarg, NULL);
6663 if (repo_path == NULL)
6664 return got_error_from_errno2("realpath",
6665 optarg);
6666 got_path_strip_trailing_slashes(repo_path);
6667 break;
6668 case 'l':
6669 do_list = 1;
6670 break;
6671 case 'n':
6672 do_update = 0;
6673 break;
6674 case 't':
6675 sort_by_time = 1;
6676 break;
6677 default:
6678 usage_branch();
6679 /* NOTREACHED */
6683 if (do_list && delref)
6684 option_conflict('l', 'd');
6685 if (sort_by_time && !do_list)
6686 errx(1, "-t option requires -l option");
6688 argc -= optind;
6689 argv += optind;
6691 if (!do_list && !delref && argc == 0)
6692 do_show = 1;
6694 if ((do_list || delref || do_show) && commit_id_arg != NULL)
6695 errx(1, "-c option can only be used when creating a branch");
6697 if (do_list || delref) {
6698 if (argc > 0)
6699 usage_branch();
6700 } else if (!do_show && argc != 1)
6701 usage_branch();
6703 #ifndef PROFILE
6704 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
6705 "sendfd unveil", NULL) == -1)
6706 err(1, "pledge");
6707 #endif
6708 cwd = getcwd(NULL, 0);
6709 if (cwd == NULL) {
6710 error = got_error_from_errno("getcwd");
6711 goto done;
6714 error = got_repo_pack_fds_open(&pack_fds);
6715 if (error != NULL)
6716 goto done;
6718 if (repo_path == NULL) {
6719 error = got_worktree_open(&worktree, cwd);
6720 if (error && error->code != GOT_ERR_NOT_WORKTREE)
6721 goto done;
6722 else
6723 error = NULL;
6724 if (worktree) {
6725 repo_path =
6726 strdup(got_worktree_get_repo_path(worktree));
6727 if (repo_path == NULL)
6728 error = got_error_from_errno("strdup");
6729 if (error)
6730 goto done;
6731 } else {
6732 repo_path = strdup(cwd);
6733 if (repo_path == NULL) {
6734 error = got_error_from_errno("strdup");
6735 goto done;
6740 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
6741 if (error != NULL)
6742 goto done;
6744 #ifndef PROFILE
6745 if (do_list || do_show) {
6746 /* Remove "cpath" promise. */
6747 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
6748 NULL) == -1)
6749 err(1, "pledge");
6751 #endif
6753 error = apply_unveil(got_repo_get_path(repo), do_list,
6754 worktree ? got_worktree_get_root_path(worktree) : NULL);
6755 if (error)
6756 goto done;
6758 if (do_show)
6759 error = show_current_branch(repo, worktree);
6760 else if (do_list)
6761 error = list_branches(repo, worktree, sort_by_time);
6762 else if (delref)
6763 error = delete_branch(repo, worktree, delref);
6764 else {
6765 struct got_reflist_head refs;
6766 TAILQ_INIT(&refs);
6767 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
6768 NULL);
6769 if (error)
6770 goto done;
6771 if (commit_id_arg == NULL)
6772 commit_id_arg = worktree ?
6773 got_worktree_get_head_ref_name(worktree) :
6774 GOT_REF_HEAD;
6775 error = got_repo_match_object_id(&commit_id, NULL,
6776 commit_id_arg, GOT_OBJ_TYPE_COMMIT, &refs, repo);
6777 got_ref_list_free(&refs);
6778 if (error)
6779 goto done;
6780 error = add_branch(repo, argv[0], commit_id);
6781 if (error)
6782 goto done;
6783 if (worktree && do_update) {
6784 struct got_update_progress_arg upa;
6785 char *branch_refname = NULL;
6787 error = got_object_id_str(&commit_id_str, commit_id);
6788 if (error)
6789 goto done;
6790 error = get_worktree_paths_from_argv(&paths, 0, NULL,
6791 worktree);
6792 if (error)
6793 goto done;
6794 if (asprintf(&branch_refname, "refs/heads/%s", argv[0])
6795 == -1) {
6796 error = got_error_from_errno("asprintf");
6797 goto done;
6799 error = got_ref_open(&ref, repo, branch_refname, 0);
6800 free(branch_refname);
6801 if (error)
6802 goto done;
6803 error = switch_head_ref(ref, commit_id, worktree,
6804 repo);
6805 if (error)
6806 goto done;
6807 error = got_worktree_set_base_commit_id(worktree, repo,
6808 commit_id);
6809 if (error)
6810 goto done;
6811 memset(&upa, 0, sizeof(upa));
6812 error = got_worktree_checkout_files(worktree, &paths,
6813 repo, update_progress, &upa, check_cancelled,
6814 NULL);
6815 if (error)
6816 goto done;
6817 if (upa.did_something) {
6818 printf("Updated to %s: %s\n",
6819 got_worktree_get_head_ref_name(worktree),
6820 commit_id_str);
6822 print_update_progress_stats(&upa);
6825 done:
6826 if (ref)
6827 got_ref_close(ref);
6828 if (repo) {
6829 const struct got_error *close_err = got_repo_close(repo);
6830 if (error == NULL)
6831 error = close_err;
6833 if (worktree)
6834 got_worktree_close(worktree);
6835 if (pack_fds) {
6836 const struct got_error *pack_err =
6837 got_repo_pack_fds_close(pack_fds);
6838 if (error == NULL)
6839 error = pack_err;
6841 free(cwd);
6842 free(repo_path);
6843 free(commit_id);
6844 free(commit_id_str);
6845 TAILQ_FOREACH(pe, &paths, entry)
6846 free((char *)pe->path);
6847 got_pathlist_free(&paths);
6848 return error;
6852 __dead static void
6853 usage_tag(void)
6855 fprintf(stderr,
6856 "usage: %s tag [-c commit] [-r repository] [-l] "
6857 "[-m message] [-s signer-id] [-v] [-V] name\n",
6858 getprogname());
6859 exit(1);
6862 #if 0
6863 static const struct got_error *
6864 sort_tags(struct got_reflist_head *sorted, struct got_reflist_head *tags)
6866 const struct got_error *err = NULL;
6867 struct got_reflist_entry *re, *se, *new;
6868 struct got_object_id *re_id, *se_id;
6869 struct got_tag_object *re_tag, *se_tag;
6870 time_t re_time, se_time;
6872 STAILQ_FOREACH(re, tags, entry) {
6873 se = STAILQ_FIRST(sorted);
6874 if (se == NULL) {
6875 err = got_reflist_entry_dup(&new, re);
6876 if (err)
6877 return err;
6878 STAILQ_INSERT_HEAD(sorted, new, entry);
6879 continue;
6880 } else {
6881 err = got_ref_resolve(&re_id, repo, re->ref);
6882 if (err)
6883 break;
6884 err = got_object_open_as_tag(&re_tag, repo, re_id);
6885 free(re_id);
6886 if (err)
6887 break;
6888 re_time = got_object_tag_get_tagger_time(re_tag);
6889 got_object_tag_close(re_tag);
6892 while (se) {
6893 err = got_ref_resolve(&se_id, repo, re->ref);
6894 if (err)
6895 break;
6896 err = got_object_open_as_tag(&se_tag, repo, se_id);
6897 free(se_id);
6898 if (err)
6899 break;
6900 se_time = got_object_tag_get_tagger_time(se_tag);
6901 got_object_tag_close(se_tag);
6903 if (se_time > re_time) {
6904 err = got_reflist_entry_dup(&new, re);
6905 if (err)
6906 return err;
6907 STAILQ_INSERT_AFTER(sorted, se, new, entry);
6908 break;
6910 se = STAILQ_NEXT(se, entry);
6911 continue;
6914 done:
6915 return err;
6917 #endif
6919 static const struct got_error *
6920 get_tag_refname(char **refname, const char *tag_name)
6922 const struct got_error *err;
6924 if (strncmp("refs/tags/", tag_name, 10) == 0) {
6925 *refname = strdup(tag_name);
6926 if (*refname == NULL)
6927 return got_error_from_errno("strdup");
6928 } else if (asprintf(refname, "refs/tags/%s", tag_name) == -1) {
6929 err = got_error_from_errno("asprintf");
6930 *refname = NULL;
6931 return err;
6934 return NULL;
6937 static const struct got_error *
6938 list_tags(struct got_repository *repo, const char *tag_name, int verify_tags,
6939 const char *allowed_signers, const char *revoked_signers, int verbosity)
6941 static const struct got_error *err = NULL;
6942 struct got_reflist_head refs;
6943 struct got_reflist_entry *re;
6944 char *wanted_refname = NULL;
6945 int bad_sigs = 0;
6947 TAILQ_INIT(&refs);
6949 err = got_ref_list(&refs, repo, "refs/tags", got_ref_cmp_tags, repo);
6950 if (err)
6951 return err;
6953 if (tag_name) {
6954 struct got_reference *ref;
6955 err = get_tag_refname(&wanted_refname, tag_name);
6956 if (err)
6957 goto done;
6958 /* Wanted tag reference should exist. */
6959 err = got_ref_open(&ref, repo, wanted_refname, 0);
6960 if (err)
6961 goto done;
6962 got_ref_close(ref);
6965 TAILQ_FOREACH(re, &refs, entry) {
6966 const char *refname;
6967 char *refstr, *tagmsg0, *tagmsg, *line, *id_str, *datestr;
6968 char datebuf[26];
6969 const char *tagger, *ssh_sig = NULL;
6970 char *sig_msg = NULL;
6971 time_t tagger_time;
6972 struct got_object_id *id;
6973 struct got_tag_object *tag;
6974 struct got_commit_object *commit = NULL;
6976 refname = got_ref_get_name(re->ref);
6977 if (strncmp(refname, "refs/tags/", 10) != 0 ||
6978 (wanted_refname && strcmp(refname, wanted_refname) != 0))
6979 continue;
6980 refname += 10;
6981 refstr = got_ref_to_str(re->ref);
6982 if (refstr == NULL) {
6983 err = got_error_from_errno("got_ref_to_str");
6984 break;
6987 err = got_ref_resolve(&id, repo, re->ref);
6988 if (err)
6989 break;
6990 err = got_object_open_as_tag(&tag, repo, id);
6991 if (err) {
6992 if (err->code != GOT_ERR_OBJ_TYPE) {
6993 free(id);
6994 break;
6996 /* "lightweight" tag */
6997 err = got_object_open_as_commit(&commit, repo, id);
6998 if (err) {
6999 free(id);
7000 break;
7002 tagger = got_object_commit_get_committer(commit);
7003 tagger_time =
7004 got_object_commit_get_committer_time(commit);
7005 err = got_object_id_str(&id_str, id);
7006 free(id);
7007 if (err)
7008 break;
7009 } else {
7010 free(id);
7011 tagger = got_object_tag_get_tagger(tag);
7012 tagger_time = got_object_tag_get_tagger_time(tag);
7013 err = got_object_id_str(&id_str,
7014 got_object_tag_get_object_id(tag));
7015 if (err)
7016 break;
7019 if (verify_tags) {
7020 ssh_sig = got_sigs_get_tagmsg_ssh_signature(
7021 got_object_tag_get_message(tag));
7022 if (ssh_sig && allowed_signers == NULL) {
7023 err = got_error_msg(
7024 GOT_ERR_VERIFY_TAG_SIGNATURE,
7025 "SSH signature verification requires "
7026 "setting allowed_signers in "
7027 "got.conf(5)");
7028 break;
7032 printf("%stag %s %s\n", GOT_COMMIT_SEP_STR, refname, refstr);
7033 free(refstr);
7034 printf("from: %s\n", tagger);
7035 datestr = get_datestr(&tagger_time, datebuf);
7036 if (datestr)
7037 printf("date: %s UTC\n", datestr);
7038 if (commit)
7039 printf("object: %s %s\n", GOT_OBJ_LABEL_COMMIT, id_str);
7040 else {
7041 switch (got_object_tag_get_object_type(tag)) {
7042 case GOT_OBJ_TYPE_BLOB:
7043 printf("object: %s %s\n", GOT_OBJ_LABEL_BLOB,
7044 id_str);
7045 break;
7046 case GOT_OBJ_TYPE_TREE:
7047 printf("object: %s %s\n", GOT_OBJ_LABEL_TREE,
7048 id_str);
7049 break;
7050 case GOT_OBJ_TYPE_COMMIT:
7051 printf("object: %s %s\n", GOT_OBJ_LABEL_COMMIT,
7052 id_str);
7053 break;
7054 case GOT_OBJ_TYPE_TAG:
7055 printf("object: %s %s\n", GOT_OBJ_LABEL_TAG,
7056 id_str);
7057 break;
7058 default:
7059 break;
7062 free(id_str);
7064 if (ssh_sig) {
7065 err = got_sigs_verify_tag_ssh(&sig_msg, tag, ssh_sig,
7066 allowed_signers, revoked_signers, verbosity);
7067 if (err && err->code == GOT_ERR_BAD_TAG_SIGNATURE)
7068 bad_sigs = 1;
7069 else if (err)
7070 break;
7071 printf("signature: %s", sig_msg);
7072 free(sig_msg);
7073 sig_msg = NULL;
7076 if (commit) {
7077 err = got_object_commit_get_logmsg(&tagmsg0, commit);
7078 if (err)
7079 break;
7080 got_object_commit_close(commit);
7081 } else {
7082 tagmsg0 = strdup(got_object_tag_get_message(tag));
7083 got_object_tag_close(tag);
7084 if (tagmsg0 == NULL) {
7085 err = got_error_from_errno("strdup");
7086 break;
7090 tagmsg = tagmsg0;
7091 do {
7092 line = strsep(&tagmsg, "\n");
7093 if (line)
7094 printf(" %s\n", line);
7095 } while (line);
7096 free(tagmsg0);
7098 done:
7099 got_ref_list_free(&refs);
7100 free(wanted_refname);
7102 if (err == NULL && bad_sigs)
7103 err = got_error(GOT_ERR_BAD_TAG_SIGNATURE);
7104 return err;
7107 static const struct got_error *
7108 get_tag_message(char **tagmsg, char **tagmsg_path, const char *commit_id_str,
7109 const char *tag_name, const char *repo_path)
7111 const struct got_error *err = NULL;
7112 char *template = NULL, *initial_content = NULL;
7113 char *editor = NULL;
7114 int initial_content_len;
7115 int fd = -1;
7117 if (asprintf(&template, GOT_TMPDIR_STR "/got-tagmsg") == -1) {
7118 err = got_error_from_errno("asprintf");
7119 goto done;
7122 initial_content_len = asprintf(&initial_content,
7123 "\n# tagging commit %s as %s\n",
7124 commit_id_str, tag_name);
7125 if (initial_content_len == -1) {
7126 err = got_error_from_errno("asprintf");
7127 goto done;
7130 err = got_opentemp_named_fd(tagmsg_path, &fd, template);
7131 if (err)
7132 goto done;
7134 if (write(fd, initial_content, initial_content_len) == -1) {
7135 err = got_error_from_errno2("write", *tagmsg_path);
7136 goto done;
7139 err = get_editor(&editor);
7140 if (err)
7141 goto done;
7142 err = edit_logmsg(tagmsg, editor, *tagmsg_path, initial_content,
7143 initial_content_len, 1);
7144 done:
7145 free(initial_content);
7146 free(template);
7147 free(editor);
7149 if (fd != -1 && close(fd) == -1 && err == NULL)
7150 err = got_error_from_errno2("close", *tagmsg_path);
7152 if (err) {
7153 free(*tagmsg);
7154 *tagmsg = NULL;
7156 return err;
7159 static const struct got_error *
7160 add_tag(struct got_repository *repo, const char *tagger,
7161 const char *tag_name, const char *commit_arg, const char *tagmsg_arg,
7162 const char *signer_id, int verbosity)
7164 const struct got_error *err = NULL;
7165 struct got_object_id *commit_id = NULL, *tag_id = NULL;
7166 char *label = NULL, *commit_id_str = NULL;
7167 struct got_reference *ref = NULL;
7168 char *refname = NULL, *tagmsg = NULL;
7169 char *tagmsg_path = NULL, *tag_id_str = NULL;
7170 int preserve_tagmsg = 0;
7171 struct got_reflist_head refs;
7173 TAILQ_INIT(&refs);
7176 * Don't let the user create a tag name with a leading '-'.
7177 * While technically a valid reference name, this case is usually
7178 * an unintended typo.
7180 if (tag_name[0] == '-')
7181 return got_error_path(tag_name, GOT_ERR_REF_NAME_MINUS);
7183 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
7184 if (err)
7185 goto done;
7187 err = got_repo_match_object_id(&commit_id, &label, commit_arg,
7188 GOT_OBJ_TYPE_COMMIT, &refs, repo);
7189 if (err)
7190 goto done;
7192 err = got_object_id_str(&commit_id_str, commit_id);
7193 if (err)
7194 goto done;
7196 err = get_tag_refname(&refname, tag_name);
7197 if (err)
7198 goto done;
7199 if (strncmp("refs/tags/", tag_name, 10) == 0)
7200 tag_name += 10;
7202 err = got_ref_open(&ref, repo, refname, 0);
7203 if (err == NULL) {
7204 err = got_error(GOT_ERR_TAG_EXISTS);
7205 goto done;
7206 } else if (err->code != GOT_ERR_NOT_REF)
7207 goto done;
7209 if (tagmsg_arg == NULL) {
7210 err = get_tag_message(&tagmsg, &tagmsg_path, commit_id_str,
7211 tag_name, got_repo_get_path(repo));
7212 if (err) {
7213 if (err->code != GOT_ERR_COMMIT_MSG_EMPTY &&
7214 tagmsg_path != NULL)
7215 preserve_tagmsg = 1;
7216 goto done;
7218 /* Editor is done; we can now apply unveil(2) */
7219 err = got_sigs_apply_unveil();
7220 if (err)
7221 goto done;
7222 err = apply_unveil(got_repo_get_path(repo), 0, NULL);
7223 if (err)
7224 goto done;
7227 err = got_object_tag_create(&tag_id, tag_name, commit_id,
7228 tagger, time(NULL), tagmsg ? tagmsg : tagmsg_arg, signer_id, repo,
7229 verbosity);
7230 if (err) {
7231 if (tagmsg_path)
7232 preserve_tagmsg = 1;
7233 goto done;
7236 err = got_ref_alloc(&ref, refname, tag_id);
7237 if (err) {
7238 if (tagmsg_path)
7239 preserve_tagmsg = 1;
7240 goto done;
7243 err = got_ref_write(ref, repo);
7244 if (err) {
7245 if (tagmsg_path)
7246 preserve_tagmsg = 1;
7247 goto done;
7250 err = got_object_id_str(&tag_id_str, tag_id);
7251 if (err) {
7252 if (tagmsg_path)
7253 preserve_tagmsg = 1;
7254 goto done;
7256 printf("Created tag %s\n", tag_id_str);
7257 done:
7258 if (preserve_tagmsg) {
7259 fprintf(stderr, "%s: tag message preserved in %s\n",
7260 getprogname(), tagmsg_path);
7261 } else if (tagmsg_path && unlink(tagmsg_path) == -1 && err == NULL)
7262 err = got_error_from_errno2("unlink", tagmsg_path);
7263 free(tag_id_str);
7264 if (ref)
7265 got_ref_close(ref);
7266 free(commit_id);
7267 free(commit_id_str);
7268 free(refname);
7269 free(tagmsg);
7270 free(tagmsg_path);
7271 got_ref_list_free(&refs);
7272 return err;
7275 static const struct got_error *
7276 cmd_tag(int argc, char *argv[])
7278 const struct got_error *error = NULL;
7279 struct got_repository *repo = NULL;
7280 struct got_worktree *worktree = NULL;
7281 char *cwd = NULL, *repo_path = NULL, *commit_id_str = NULL;
7282 char *gitconfig_path = NULL, *tagger = NULL;
7283 char *allowed_signers = NULL, *revoked_signers = NULL;
7284 const char *tag_name = NULL, *commit_id_arg = NULL, *tagmsg = NULL;
7285 int ch, do_list = 0, verify_tags = 0, verbosity = 0;
7286 const char *signer_id = NULL;
7287 int *pack_fds = NULL;
7289 while ((ch = getopt(argc, argv, "c:m:r:ls:Vv")) != -1) {
7290 switch (ch) {
7291 case 'c':
7292 commit_id_arg = optarg;
7293 break;
7294 case 'm':
7295 tagmsg = optarg;
7296 break;
7297 case 'r':
7298 repo_path = realpath(optarg, NULL);
7299 if (repo_path == NULL)
7300 return got_error_from_errno2("realpath",
7301 optarg);
7302 got_path_strip_trailing_slashes(repo_path);
7303 break;
7304 case 'l':
7305 do_list = 1;
7306 break;
7307 case 's':
7308 signer_id = optarg;
7309 break;
7310 case 'V':
7311 verify_tags = 1;
7312 break;
7313 case 'v':
7314 if (verbosity < 0)
7315 verbosity = 0;
7316 else if (verbosity < 3)
7317 verbosity++;
7318 break;
7319 default:
7320 usage_tag();
7321 /* NOTREACHED */
7325 argc -= optind;
7326 argv += optind;
7328 if (do_list || verify_tags) {
7329 if (commit_id_arg != NULL)
7330 errx(1,
7331 "-c option can only be used when creating a tag");
7332 if (tagmsg) {
7333 if (do_list)
7334 option_conflict('l', 'm');
7335 else
7336 option_conflict('V', 'm');
7338 if (signer_id) {
7339 if (do_list)
7340 option_conflict('l', 's');
7341 else
7342 option_conflict('V', 's');
7344 if (argc > 1)
7345 usage_tag();
7346 } else if (argc != 1)
7347 usage_tag();
7349 if (argc == 1)
7350 tag_name = argv[0];
7352 #ifndef PROFILE
7353 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
7354 "sendfd unveil", NULL) == -1)
7355 err(1, "pledge");
7356 #endif
7357 cwd = getcwd(NULL, 0);
7358 if (cwd == NULL) {
7359 error = got_error_from_errno("getcwd");
7360 goto done;
7363 error = got_repo_pack_fds_open(&pack_fds);
7364 if (error != NULL)
7365 goto done;
7367 if (repo_path == NULL) {
7368 error = got_worktree_open(&worktree, cwd);
7369 if (error && error->code != GOT_ERR_NOT_WORKTREE)
7370 goto done;
7371 else
7372 error = NULL;
7373 if (worktree) {
7374 repo_path =
7375 strdup(got_worktree_get_repo_path(worktree));
7376 if (repo_path == NULL)
7377 error = got_error_from_errno("strdup");
7378 if (error)
7379 goto done;
7380 } else {
7381 repo_path = strdup(cwd);
7382 if (repo_path == NULL) {
7383 error = got_error_from_errno("strdup");
7384 goto done;
7389 if (do_list || verify_tags) {
7390 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
7391 if (error != NULL)
7392 goto done;
7393 error = get_allowed_signers(&allowed_signers, repo, worktree);
7394 if (error)
7395 goto done;
7396 error = get_revoked_signers(&revoked_signers, repo, worktree);
7397 if (error)
7398 goto done;
7399 if (worktree) {
7400 /* Release work tree lock. */
7401 got_worktree_close(worktree);
7402 worktree = NULL;
7406 * Remove "cpath" promise unless needed for signature tmpfile
7407 * creation.
7409 if (verify_tags)
7410 got_sigs_apply_unveil();
7411 else {
7412 #ifndef PROFILE
7413 if (pledge("stdio rpath wpath flock proc exec sendfd "
7414 "unveil", NULL) == -1)
7415 err(1, "pledge");
7416 #endif
7418 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
7419 if (error)
7420 goto done;
7421 error = list_tags(repo, tag_name, verify_tags, allowed_signers,
7422 revoked_signers, verbosity);
7423 } else {
7424 error = get_gitconfig_path(&gitconfig_path);
7425 if (error)
7426 goto done;
7427 error = got_repo_open(&repo, repo_path, gitconfig_path,
7428 pack_fds);
7429 if (error != NULL)
7430 goto done;
7432 error = get_author(&tagger, repo, worktree);
7433 if (error)
7434 goto done;
7435 if (worktree) {
7436 /* Release work tree lock. */
7437 got_worktree_close(worktree);
7438 worktree = NULL;
7441 if (tagmsg) {
7442 if (signer_id) {
7443 error = got_sigs_apply_unveil();
7444 if (error)
7445 goto done;
7447 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
7448 if (error)
7449 goto done;
7452 if (commit_id_arg == NULL) {
7453 struct got_reference *head_ref;
7454 struct got_object_id *commit_id;
7455 error = got_ref_open(&head_ref, repo,
7456 worktree ? got_worktree_get_head_ref_name(worktree)
7457 : GOT_REF_HEAD, 0);
7458 if (error)
7459 goto done;
7460 error = got_ref_resolve(&commit_id, repo, head_ref);
7461 got_ref_close(head_ref);
7462 if (error)
7463 goto done;
7464 error = got_object_id_str(&commit_id_str, commit_id);
7465 free(commit_id);
7466 if (error)
7467 goto done;
7470 error = add_tag(repo, tagger, tag_name,
7471 commit_id_str ? commit_id_str : commit_id_arg, tagmsg,
7472 signer_id, verbosity);
7474 done:
7475 if (repo) {
7476 const struct got_error *close_err = got_repo_close(repo);
7477 if (error == NULL)
7478 error = close_err;
7480 if (worktree)
7481 got_worktree_close(worktree);
7482 if (pack_fds) {
7483 const struct got_error *pack_err =
7484 got_repo_pack_fds_close(pack_fds);
7485 if (error == NULL)
7486 error = pack_err;
7488 free(cwd);
7489 free(repo_path);
7490 free(gitconfig_path);
7491 free(commit_id_str);
7492 free(tagger);
7493 free(allowed_signers);
7494 free(revoked_signers);
7495 return error;
7498 __dead static void
7499 usage_add(void)
7501 fprintf(stderr, "usage: %s add [-R] [-I] path ...\n",
7502 getprogname());
7503 exit(1);
7506 static const struct got_error *
7507 add_progress(void *arg, unsigned char status, const char *path)
7509 while (path[0] == '/')
7510 path++;
7511 printf("%c %s\n", status, path);
7512 return NULL;
7515 static const struct got_error *
7516 cmd_add(int argc, char *argv[])
7518 const struct got_error *error = NULL;
7519 struct got_repository *repo = NULL;
7520 struct got_worktree *worktree = NULL;
7521 char *cwd = NULL;
7522 struct got_pathlist_head paths;
7523 struct got_pathlist_entry *pe;
7524 int ch, can_recurse = 0, no_ignores = 0;
7525 int *pack_fds = NULL;
7527 TAILQ_INIT(&paths);
7529 while ((ch = getopt(argc, argv, "IR")) != -1) {
7530 switch (ch) {
7531 case 'I':
7532 no_ignores = 1;
7533 break;
7534 case 'R':
7535 can_recurse = 1;
7536 break;
7537 default:
7538 usage_add();
7539 /* NOTREACHED */
7543 argc -= optind;
7544 argv += optind;
7546 #ifndef PROFILE
7547 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
7548 NULL) == -1)
7549 err(1, "pledge");
7550 #endif
7551 if (argc < 1)
7552 usage_add();
7554 cwd = getcwd(NULL, 0);
7555 if (cwd == NULL) {
7556 error = got_error_from_errno("getcwd");
7557 goto done;
7560 error = got_repo_pack_fds_open(&pack_fds);
7561 if (error != NULL)
7562 goto done;
7564 error = got_worktree_open(&worktree, cwd);
7565 if (error) {
7566 if (error->code == GOT_ERR_NOT_WORKTREE)
7567 error = wrap_not_worktree_error(error, "add", cwd);
7568 goto done;
7571 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
7572 NULL, pack_fds);
7573 if (error != NULL)
7574 goto done;
7576 error = apply_unveil(got_repo_get_path(repo), 1,
7577 got_worktree_get_root_path(worktree));
7578 if (error)
7579 goto done;
7581 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
7582 if (error)
7583 goto done;
7585 if (!can_recurse) {
7586 char *ondisk_path;
7587 struct stat sb;
7588 TAILQ_FOREACH(pe, &paths, entry) {
7589 if (asprintf(&ondisk_path, "%s/%s",
7590 got_worktree_get_root_path(worktree),
7591 pe->path) == -1) {
7592 error = got_error_from_errno("asprintf");
7593 goto done;
7595 if (lstat(ondisk_path, &sb) == -1) {
7596 if (errno == ENOENT) {
7597 free(ondisk_path);
7598 continue;
7600 error = got_error_from_errno2("lstat",
7601 ondisk_path);
7602 free(ondisk_path);
7603 goto done;
7605 free(ondisk_path);
7606 if (S_ISDIR(sb.st_mode)) {
7607 error = got_error_msg(GOT_ERR_BAD_PATH,
7608 "adding directories requires -R option");
7609 goto done;
7614 error = got_worktree_schedule_add(worktree, &paths, add_progress,
7615 NULL, repo, no_ignores);
7616 done:
7617 if (repo) {
7618 const struct got_error *close_err = got_repo_close(repo);
7619 if (error == NULL)
7620 error = close_err;
7622 if (worktree)
7623 got_worktree_close(worktree);
7624 if (pack_fds) {
7625 const struct got_error *pack_err =
7626 got_repo_pack_fds_close(pack_fds);
7627 if (error == NULL)
7628 error = pack_err;
7630 TAILQ_FOREACH(pe, &paths, entry)
7631 free((char *)pe->path);
7632 got_pathlist_free(&paths);
7633 free(cwd);
7634 return error;
7637 __dead static void
7638 usage_remove(void)
7640 fprintf(stderr, "usage: %s remove [-f] [-k] [-R] [-s status-codes] "
7641 "path ...\n", getprogname());
7642 exit(1);
7645 static const struct got_error *
7646 print_remove_status(void *arg, unsigned char status,
7647 unsigned char staged_status, const char *path)
7649 while (path[0] == '/')
7650 path++;
7651 if (status == GOT_STATUS_NONEXISTENT)
7652 return NULL;
7653 if (status == staged_status && (status == GOT_STATUS_DELETE))
7654 status = GOT_STATUS_NO_CHANGE;
7655 printf("%c%c %s\n", status, staged_status, path);
7656 return NULL;
7659 static const struct got_error *
7660 cmd_remove(int argc, char *argv[])
7662 const struct got_error *error = NULL;
7663 struct got_worktree *worktree = NULL;
7664 struct got_repository *repo = NULL;
7665 const char *status_codes = NULL;
7666 char *cwd = NULL;
7667 struct got_pathlist_head paths;
7668 struct got_pathlist_entry *pe;
7669 int ch, delete_local_mods = 0, can_recurse = 0, keep_on_disk = 0, i;
7670 int ignore_missing_paths = 0;
7671 int *pack_fds = NULL;
7673 TAILQ_INIT(&paths);
7675 while ((ch = getopt(argc, argv, "fkRs:")) != -1) {
7676 switch (ch) {
7677 case 'f':
7678 delete_local_mods = 1;
7679 ignore_missing_paths = 1;
7680 break;
7681 case 'k':
7682 keep_on_disk = 1;
7683 break;
7684 case 'R':
7685 can_recurse = 1;
7686 break;
7687 case 's':
7688 for (i = 0; i < strlen(optarg); i++) {
7689 switch (optarg[i]) {
7690 case GOT_STATUS_MODIFY:
7691 delete_local_mods = 1;
7692 break;
7693 case GOT_STATUS_MISSING:
7694 ignore_missing_paths = 1;
7695 break;
7696 default:
7697 errx(1, "invalid status code '%c'",
7698 optarg[i]);
7701 status_codes = optarg;
7702 break;
7703 default:
7704 usage_remove();
7705 /* NOTREACHED */
7709 argc -= optind;
7710 argv += optind;
7712 #ifndef PROFILE
7713 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
7714 NULL) == -1)
7715 err(1, "pledge");
7716 #endif
7717 if (argc < 1)
7718 usage_remove();
7720 cwd = getcwd(NULL, 0);
7721 if (cwd == NULL) {
7722 error = got_error_from_errno("getcwd");
7723 goto done;
7726 error = got_repo_pack_fds_open(&pack_fds);
7727 if (error != NULL)
7728 goto done;
7730 error = got_worktree_open(&worktree, cwd);
7731 if (error) {
7732 if (error->code == GOT_ERR_NOT_WORKTREE)
7733 error = wrap_not_worktree_error(error, "remove", cwd);
7734 goto done;
7737 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
7738 NULL, pack_fds);
7739 if (error)
7740 goto done;
7742 error = apply_unveil(got_repo_get_path(repo), 1,
7743 got_worktree_get_root_path(worktree));
7744 if (error)
7745 goto done;
7747 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
7748 if (error)
7749 goto done;
7751 if (!can_recurse) {
7752 char *ondisk_path;
7753 struct stat sb;
7754 TAILQ_FOREACH(pe, &paths, entry) {
7755 if (asprintf(&ondisk_path, "%s/%s",
7756 got_worktree_get_root_path(worktree),
7757 pe->path) == -1) {
7758 error = got_error_from_errno("asprintf");
7759 goto done;
7761 if (lstat(ondisk_path, &sb) == -1) {
7762 if (errno == ENOENT) {
7763 free(ondisk_path);
7764 continue;
7766 error = got_error_from_errno2("lstat",
7767 ondisk_path);
7768 free(ondisk_path);
7769 goto done;
7771 free(ondisk_path);
7772 if (S_ISDIR(sb.st_mode)) {
7773 error = got_error_msg(GOT_ERR_BAD_PATH,
7774 "removing directories requires -R option");
7775 goto done;
7780 error = got_worktree_schedule_delete(worktree, &paths,
7781 delete_local_mods, status_codes, print_remove_status, NULL,
7782 repo, keep_on_disk, ignore_missing_paths);
7783 done:
7784 if (repo) {
7785 const struct got_error *close_err = got_repo_close(repo);
7786 if (error == NULL)
7787 error = close_err;
7789 if (worktree)
7790 got_worktree_close(worktree);
7791 if (pack_fds) {
7792 const struct got_error *pack_err =
7793 got_repo_pack_fds_close(pack_fds);
7794 if (error == NULL)
7795 error = pack_err;
7797 TAILQ_FOREACH(pe, &paths, entry)
7798 free((char *)pe->path);
7799 got_pathlist_free(&paths);
7800 free(cwd);
7801 return error;
7804 __dead static void
7805 usage_patch(void)
7807 fprintf(stderr, "usage: %s patch [-n] [-p strip-count] "
7808 "[-R] [patchfile]\n", getprogname());
7809 exit(1);
7812 static const struct got_error *
7813 patch_from_stdin(int *patchfd)
7815 const struct got_error *err = NULL;
7816 ssize_t r;
7817 char *path, buf[BUFSIZ];
7818 sig_t sighup, sigint, sigquit;
7820 err = got_opentemp_named_fd(&path, patchfd,
7821 GOT_TMPDIR_STR "/got-patch");
7822 if (err)
7823 return err;
7824 unlink(path);
7825 free(path);
7827 sighup = signal(SIGHUP, SIG_DFL);
7828 sigint = signal(SIGINT, SIG_DFL);
7829 sigquit = signal(SIGQUIT, SIG_DFL);
7831 for (;;) {
7832 r = read(0, buf, sizeof(buf));
7833 if (r == -1) {
7834 err = got_error_from_errno("read");
7835 break;
7837 if (r == 0)
7838 break;
7839 if (write(*patchfd, buf, r) == -1) {
7840 err = got_error_from_errno("write");
7841 break;
7845 signal(SIGHUP, sighup);
7846 signal(SIGINT, sigint);
7847 signal(SIGQUIT, sigquit);
7849 if (err == NULL && lseek(*patchfd, 0, SEEK_SET) == -1)
7850 err = got_error_from_errno("lseek");
7852 if (err != NULL) {
7853 close(*patchfd);
7854 *patchfd = -1;
7857 return err;
7860 static const struct got_error *
7861 patch_progress(void *arg, const char *old, const char *new,
7862 unsigned char status, const struct got_error *error, int old_from,
7863 int old_lines, int new_from, int new_lines, int offset,
7864 int ws_mangled, const struct got_error *hunk_err)
7866 const char *path = new == NULL ? old : new;
7868 while (*path == '/')
7869 path++;
7871 if (status != 0)
7872 printf("%c %s\n", status, path);
7874 if (error != NULL)
7875 fprintf(stderr, "%s: %s\n", getprogname(), error->msg);
7877 if (offset != 0 || hunk_err != NULL || ws_mangled) {
7878 printf("@@ -%d,%d +%d,%d @@ ", old_from,
7879 old_lines, new_from, new_lines);
7880 if (hunk_err != NULL)
7881 printf("%s\n", hunk_err->msg);
7882 else if (offset != 0)
7883 printf("applied with offset %d\n", offset);
7884 else
7885 printf("hunk contains mangled whitespace\n");
7888 return NULL;
7891 static const struct got_error *
7892 cmd_patch(int argc, char *argv[])
7894 const struct got_error *error = NULL, *close_error = NULL;
7895 struct got_worktree *worktree = NULL;
7896 struct got_repository *repo = NULL;
7897 const char *errstr;
7898 char *cwd = NULL;
7899 int ch, nop = 0, strip = -1, reverse = 0;
7900 int patchfd;
7901 int *pack_fds = NULL;
7903 while ((ch = getopt(argc, argv, "np:R")) != -1) {
7904 switch (ch) {
7905 case 'n':
7906 nop = 1;
7907 break;
7908 case 'p':
7909 strip = strtonum(optarg, 0, INT_MAX, &errstr);
7910 if (errstr != NULL)
7911 errx(1, "pathname strip count is %s: %s",
7912 errstr, optarg);
7913 break;
7914 case 'R':
7915 reverse = 1;
7916 break;
7917 default:
7918 usage_patch();
7919 /* NOTREACHED */
7923 argc -= optind;
7924 argv += optind;
7926 if (argc == 0) {
7927 error = patch_from_stdin(&patchfd);
7928 if (error)
7929 return error;
7930 } else if (argc == 1) {
7931 patchfd = open(argv[0], O_RDONLY);
7932 if (patchfd == -1) {
7933 error = got_error_from_errno2("open", argv[0]);
7934 return error;
7936 } else
7937 usage_patch();
7939 if ((cwd = getcwd(NULL, 0)) == NULL) {
7940 error = got_error_from_errno("getcwd");
7941 goto done;
7944 error = got_repo_pack_fds_open(&pack_fds);
7945 if (error != NULL)
7946 goto done;
7948 error = got_worktree_open(&worktree, cwd);
7949 if (error != NULL)
7950 goto done;
7952 const char *repo_path = got_worktree_get_repo_path(worktree);
7953 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
7954 if (error != NULL)
7955 goto done;
7957 error = apply_unveil(got_repo_get_path(repo), 0,
7958 got_worktree_get_root_path(worktree));
7959 if (error != NULL)
7960 goto done;
7962 #ifndef PROFILE
7963 if (pledge("stdio rpath wpath cpath fattr proc exec sendfd flock",
7964 NULL) == -1)
7965 err(1, "pledge");
7966 #endif
7968 error = got_patch(patchfd, worktree, repo, nop, strip, reverse,
7969 &patch_progress, NULL, check_cancelled, NULL);
7971 done:
7972 if (repo) {
7973 close_error = got_repo_close(repo);
7974 if (error == NULL)
7975 error = close_error;
7977 if (worktree != NULL) {
7978 close_error = got_worktree_close(worktree);
7979 if (error == NULL)
7980 error = close_error;
7982 if (pack_fds) {
7983 const struct got_error *pack_err =
7984 got_repo_pack_fds_close(pack_fds);
7985 if (error == NULL)
7986 error = pack_err;
7988 free(cwd);
7989 return error;
7992 __dead static void
7993 usage_revert(void)
7995 fprintf(stderr, "usage: %s revert [-p] [-F response-script] [-R] "
7996 "path ...\n", getprogname());
7997 exit(1);
8000 static const struct got_error *
8001 revert_progress(void *arg, unsigned char status, const char *path)
8003 if (status == GOT_STATUS_UNVERSIONED)
8004 return NULL;
8006 while (path[0] == '/')
8007 path++;
8008 printf("%c %s\n", status, path);
8009 return NULL;
8012 struct choose_patch_arg {
8013 FILE *patch_script_file;
8014 const char *action;
8017 static const struct got_error *
8018 show_change(unsigned char status, const char *path, FILE *patch_file, int n,
8019 int nchanges, const char *action)
8021 const struct got_error *err;
8022 char *line = NULL;
8023 size_t linesize = 0;
8024 ssize_t linelen;
8026 switch (status) {
8027 case GOT_STATUS_ADD:
8028 printf("A %s\n%s this addition? [y/n] ", path, action);
8029 break;
8030 case GOT_STATUS_DELETE:
8031 printf("D %s\n%s this deletion? [y/n] ", path, action);
8032 break;
8033 case GOT_STATUS_MODIFY:
8034 if (fseek(patch_file, 0L, SEEK_SET) == -1)
8035 return got_error_from_errno("fseek");
8036 printf(GOT_COMMIT_SEP_STR);
8037 while ((linelen = getline(&line, &linesize, patch_file)) != -1)
8038 printf("%s", line);
8039 if (linelen == -1 && ferror(patch_file)) {
8040 err = got_error_from_errno("getline");
8041 free(line);
8042 return err;
8044 free(line);
8045 printf(GOT_COMMIT_SEP_STR);
8046 printf("M %s (change %d of %d)\n%s this change? [y/n/q] ",
8047 path, n, nchanges, action);
8048 break;
8049 default:
8050 return got_error_path(path, GOT_ERR_FILE_STATUS);
8053 return NULL;
8056 static const struct got_error *
8057 choose_patch(int *choice, void *arg, unsigned char status, const char *path,
8058 FILE *patch_file, int n, int nchanges)
8060 const struct got_error *err = NULL;
8061 char *line = NULL;
8062 size_t linesize = 0;
8063 ssize_t linelen;
8064 int resp = ' ';
8065 struct choose_patch_arg *a = arg;
8067 *choice = GOT_PATCH_CHOICE_NONE;
8069 if (a->patch_script_file) {
8070 char *nl;
8071 err = show_change(status, path, patch_file, n, nchanges,
8072 a->action);
8073 if (err)
8074 return err;
8075 linelen = getline(&line, &linesize, a->patch_script_file);
8076 if (linelen == -1) {
8077 if (ferror(a->patch_script_file))
8078 return got_error_from_errno("getline");
8079 return NULL;
8081 nl = strchr(line, '\n');
8082 if (nl)
8083 *nl = '\0';
8084 if (strcmp(line, "y") == 0) {
8085 *choice = GOT_PATCH_CHOICE_YES;
8086 printf("y\n");
8087 } else if (strcmp(line, "n") == 0) {
8088 *choice = GOT_PATCH_CHOICE_NO;
8089 printf("n\n");
8090 } else if (strcmp(line, "q") == 0 &&
8091 status == GOT_STATUS_MODIFY) {
8092 *choice = GOT_PATCH_CHOICE_QUIT;
8093 printf("q\n");
8094 } else
8095 printf("invalid response '%s'\n", line);
8096 free(line);
8097 return NULL;
8100 while (resp != 'y' && resp != 'n' && resp != 'q') {
8101 err = show_change(status, path, patch_file, n, nchanges,
8102 a->action);
8103 if (err)
8104 return err;
8105 resp = getchar();
8106 if (resp == '\n')
8107 resp = getchar();
8108 if (status == GOT_STATUS_MODIFY) {
8109 if (resp != 'y' && resp != 'n' && resp != 'q') {
8110 printf("invalid response '%c'\n", resp);
8111 resp = ' ';
8113 } else if (resp != 'y' && resp != 'n') {
8114 printf("invalid response '%c'\n", resp);
8115 resp = ' ';
8119 if (resp == 'y')
8120 *choice = GOT_PATCH_CHOICE_YES;
8121 else if (resp == 'n')
8122 *choice = GOT_PATCH_CHOICE_NO;
8123 else if (resp == 'q' && status == GOT_STATUS_MODIFY)
8124 *choice = GOT_PATCH_CHOICE_QUIT;
8126 return NULL;
8129 static const struct got_error *
8130 cmd_revert(int argc, char *argv[])
8132 const struct got_error *error = NULL;
8133 struct got_worktree *worktree = NULL;
8134 struct got_repository *repo = NULL;
8135 char *cwd = NULL, *path = NULL;
8136 struct got_pathlist_head paths;
8137 struct got_pathlist_entry *pe;
8138 int ch, can_recurse = 0, pflag = 0;
8139 FILE *patch_script_file = NULL;
8140 const char *patch_script_path = NULL;
8141 struct choose_patch_arg cpa;
8142 int *pack_fds = NULL;
8144 TAILQ_INIT(&paths);
8146 while ((ch = getopt(argc, argv, "pF:R")) != -1) {
8147 switch (ch) {
8148 case 'p':
8149 pflag = 1;
8150 break;
8151 case 'F':
8152 patch_script_path = optarg;
8153 break;
8154 case 'R':
8155 can_recurse = 1;
8156 break;
8157 default:
8158 usage_revert();
8159 /* NOTREACHED */
8163 argc -= optind;
8164 argv += optind;
8166 #ifndef PROFILE
8167 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
8168 "unveil", NULL) == -1)
8169 err(1, "pledge");
8170 #endif
8171 if (argc < 1)
8172 usage_revert();
8173 if (patch_script_path && !pflag)
8174 errx(1, "-F option can only be used together with -p option");
8176 cwd = getcwd(NULL, 0);
8177 if (cwd == NULL) {
8178 error = got_error_from_errno("getcwd");
8179 goto done;
8182 error = got_repo_pack_fds_open(&pack_fds);
8183 if (error != NULL)
8184 goto done;
8186 error = got_worktree_open(&worktree, cwd);
8187 if (error) {
8188 if (error->code == GOT_ERR_NOT_WORKTREE)
8189 error = wrap_not_worktree_error(error, "revert", cwd);
8190 goto done;
8193 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
8194 NULL, pack_fds);
8195 if (error != NULL)
8196 goto done;
8198 if (patch_script_path) {
8199 patch_script_file = fopen(patch_script_path, "re");
8200 if (patch_script_file == NULL) {
8201 error = got_error_from_errno2("fopen",
8202 patch_script_path);
8203 goto done;
8206 error = apply_unveil(got_repo_get_path(repo), 1,
8207 got_worktree_get_root_path(worktree));
8208 if (error)
8209 goto done;
8211 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
8212 if (error)
8213 goto done;
8215 if (!can_recurse) {
8216 char *ondisk_path;
8217 struct stat sb;
8218 TAILQ_FOREACH(pe, &paths, entry) {
8219 if (asprintf(&ondisk_path, "%s/%s",
8220 got_worktree_get_root_path(worktree),
8221 pe->path) == -1) {
8222 error = got_error_from_errno("asprintf");
8223 goto done;
8225 if (lstat(ondisk_path, &sb) == -1) {
8226 if (errno == ENOENT) {
8227 free(ondisk_path);
8228 continue;
8230 error = got_error_from_errno2("lstat",
8231 ondisk_path);
8232 free(ondisk_path);
8233 goto done;
8235 free(ondisk_path);
8236 if (S_ISDIR(sb.st_mode)) {
8237 error = got_error_msg(GOT_ERR_BAD_PATH,
8238 "reverting directories requires -R option");
8239 goto done;
8244 cpa.patch_script_file = patch_script_file;
8245 cpa.action = "revert";
8246 error = got_worktree_revert(worktree, &paths, revert_progress, NULL,
8247 pflag ? choose_patch : NULL, &cpa, repo);
8248 done:
8249 if (patch_script_file && fclose(patch_script_file) == EOF &&
8250 error == NULL)
8251 error = got_error_from_errno2("fclose", patch_script_path);
8252 if (repo) {
8253 const struct got_error *close_err = got_repo_close(repo);
8254 if (error == NULL)
8255 error = close_err;
8257 if (worktree)
8258 got_worktree_close(worktree);
8259 if (pack_fds) {
8260 const struct got_error *pack_err =
8261 got_repo_pack_fds_close(pack_fds);
8262 if (error == NULL)
8263 error = pack_err;
8265 free(path);
8266 free(cwd);
8267 return error;
8270 __dead static void
8271 usage_commit(void)
8273 fprintf(stderr, "usage: %s commit [-F path] [-m msg] [-N] [-S] "
8274 "[path ...]\n", getprogname());
8275 exit(1);
8278 struct collect_commit_logmsg_arg {
8279 const char *cmdline_log;
8280 const char *prepared_log;
8281 int non_interactive;
8282 const char *editor;
8283 const char *worktree_path;
8284 const char *branch_name;
8285 const char *repo_path;
8286 char *logmsg_path;
8290 static const struct got_error *
8291 read_prepared_logmsg(char **logmsg, const char *path)
8293 const struct got_error *err = NULL;
8294 FILE *f = NULL;
8295 struct stat sb;
8296 size_t r;
8298 *logmsg = NULL;
8299 memset(&sb, 0, sizeof(sb));
8301 f = fopen(path, "re");
8302 if (f == NULL)
8303 return got_error_from_errno2("fopen", path);
8305 if (fstat(fileno(f), &sb) == -1) {
8306 err = got_error_from_errno2("fstat", path);
8307 goto done;
8309 if (sb.st_size == 0) {
8310 err = got_error(GOT_ERR_COMMIT_MSG_EMPTY);
8311 goto done;
8314 *logmsg = malloc(sb.st_size + 1);
8315 if (*logmsg == NULL) {
8316 err = got_error_from_errno("malloc");
8317 goto done;
8320 r = fread(*logmsg, 1, sb.st_size, f);
8321 if (r != sb.st_size) {
8322 if (ferror(f))
8323 err = got_error_from_errno2("fread", path);
8324 else
8325 err = got_error(GOT_ERR_IO);
8326 goto done;
8328 (*logmsg)[sb.st_size] = '\0';
8329 done:
8330 if (fclose(f) == EOF && err == NULL)
8331 err = got_error_from_errno2("fclose", path);
8332 if (err) {
8333 free(*logmsg);
8334 *logmsg = NULL;
8336 return err;
8340 static const struct got_error *
8341 collect_commit_logmsg(struct got_pathlist_head *commitable_paths, char **logmsg,
8342 void *arg)
8344 char *initial_content = NULL;
8345 struct got_pathlist_entry *pe;
8346 const struct got_error *err = NULL;
8347 char *template = NULL;
8348 struct collect_commit_logmsg_arg *a = arg;
8349 int initial_content_len;
8350 int fd = -1;
8351 size_t len;
8353 /* if a message was specified on the command line, just use it */
8354 if (a->cmdline_log != NULL && strlen(a->cmdline_log) != 0) {
8355 len = strlen(a->cmdline_log) + 1;
8356 *logmsg = malloc(len + 1);
8357 if (*logmsg == NULL)
8358 return got_error_from_errno("malloc");
8359 strlcpy(*logmsg, a->cmdline_log, len);
8360 return NULL;
8361 } else if (a->prepared_log != NULL && a->non_interactive)
8362 return read_prepared_logmsg(logmsg, a->prepared_log);
8364 if (asprintf(&template, "%s/logmsg", a->worktree_path) == -1)
8365 return got_error_from_errno("asprintf");
8367 err = got_opentemp_named_fd(&a->logmsg_path, &fd, template);
8368 if (err)
8369 goto done;
8371 if (a->prepared_log) {
8372 char *msg;
8373 err = read_prepared_logmsg(&msg, a->prepared_log);
8374 if (err)
8375 goto done;
8376 if (write(fd, msg, strlen(msg)) == -1) {
8377 err = got_error_from_errno2("write", a->logmsg_path);
8378 free(msg);
8379 goto done;
8381 free(msg);
8384 initial_content_len = asprintf(&initial_content,
8385 "\n# changes to be committed on branch %s:\n",
8386 a->branch_name);
8387 if (initial_content_len == -1) {
8388 err = got_error_from_errno("asprintf");
8389 goto done;
8392 if (write(fd, initial_content, initial_content_len) == -1) {
8393 err = got_error_from_errno2("write", a->logmsg_path);
8394 goto done;
8397 TAILQ_FOREACH(pe, commitable_paths, entry) {
8398 struct got_commitable *ct = pe->data;
8399 dprintf(fd, "# %c %s\n",
8400 got_commitable_get_status(ct),
8401 got_commitable_get_path(ct));
8404 err = edit_logmsg(logmsg, a->editor, a->logmsg_path, initial_content,
8405 initial_content_len, a->prepared_log ? 0 : 1);
8406 done:
8407 free(initial_content);
8408 free(template);
8410 if (fd != -1 && close(fd) == -1 && err == NULL)
8411 err = got_error_from_errno2("close", a->logmsg_path);
8413 /* Editor is done; we can now apply unveil(2) */
8414 if (err == NULL)
8415 err = apply_unveil(a->repo_path, 0, a->worktree_path);
8416 if (err) {
8417 free(*logmsg);
8418 *logmsg = NULL;
8420 return err;
8423 static const struct got_error *
8424 cmd_commit(int argc, char *argv[])
8426 const struct got_error *error = NULL;
8427 struct got_worktree *worktree = NULL;
8428 struct got_repository *repo = NULL;
8429 char *cwd = NULL, *id_str = NULL;
8430 struct got_object_id *id = NULL;
8431 const char *logmsg = NULL;
8432 char *prepared_logmsg = NULL;
8433 struct collect_commit_logmsg_arg cl_arg;
8434 char *gitconfig_path = NULL, *editor = NULL, *author = NULL;
8435 int ch, rebase_in_progress, histedit_in_progress, preserve_logmsg = 0;
8436 int allow_bad_symlinks = 0, non_interactive = 0, merge_in_progress = 0;
8437 struct got_pathlist_head paths;
8438 int *pack_fds = NULL;
8440 TAILQ_INIT(&paths);
8441 cl_arg.logmsg_path = NULL;
8443 while ((ch = getopt(argc, argv, "F:m:NS")) != -1) {
8444 switch (ch) {
8445 case 'F':
8446 if (logmsg != NULL)
8447 option_conflict('F', 'm');
8448 prepared_logmsg = realpath(optarg, NULL);
8449 if (prepared_logmsg == NULL)
8450 return got_error_from_errno2("realpath",
8451 optarg);
8452 break;
8453 case 'm':
8454 if (prepared_logmsg)
8455 option_conflict('m', 'F');
8456 logmsg = optarg;
8457 break;
8458 case 'N':
8459 non_interactive = 1;
8460 break;
8461 case 'S':
8462 allow_bad_symlinks = 1;
8463 break;
8464 default:
8465 usage_commit();
8466 /* NOTREACHED */
8470 argc -= optind;
8471 argv += optind;
8473 #ifndef PROFILE
8474 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
8475 "unveil", NULL) == -1)
8476 err(1, "pledge");
8477 #endif
8478 cwd = getcwd(NULL, 0);
8479 if (cwd == NULL) {
8480 error = got_error_from_errno("getcwd");
8481 goto done;
8484 error = got_repo_pack_fds_open(&pack_fds);
8485 if (error != NULL)
8486 goto done;
8488 error = got_worktree_open(&worktree, cwd);
8489 if (error) {
8490 if (error->code == GOT_ERR_NOT_WORKTREE)
8491 error = wrap_not_worktree_error(error, "commit", cwd);
8492 goto done;
8495 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
8496 if (error)
8497 goto done;
8498 if (rebase_in_progress) {
8499 error = got_error(GOT_ERR_REBASING);
8500 goto done;
8503 error = got_worktree_histedit_in_progress(&histedit_in_progress,
8504 worktree);
8505 if (error)
8506 goto done;
8508 error = get_gitconfig_path(&gitconfig_path);
8509 if (error)
8510 goto done;
8511 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
8512 gitconfig_path, pack_fds);
8513 if (error != NULL)
8514 goto done;
8516 error = got_worktree_merge_in_progress(&merge_in_progress, worktree, repo);
8517 if (error)
8518 goto done;
8519 if (merge_in_progress) {
8520 error = got_error(GOT_ERR_MERGE_BUSY);
8521 goto done;
8524 error = get_author(&author, repo, worktree);
8525 if (error)
8526 return error;
8529 * unveil(2) traverses exec(2); if an editor is used we have
8530 * to apply unveil after the log message has been written.
8532 if (logmsg == NULL || strlen(logmsg) == 0)
8533 error = get_editor(&editor);
8534 else
8535 error = apply_unveil(got_repo_get_path(repo), 0,
8536 got_worktree_get_root_path(worktree));
8537 if (error)
8538 goto done;
8540 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
8541 if (error)
8542 goto done;
8544 cl_arg.editor = editor;
8545 cl_arg.cmdline_log = logmsg;
8546 cl_arg.prepared_log = prepared_logmsg;
8547 cl_arg.non_interactive = non_interactive;
8548 cl_arg.worktree_path = got_worktree_get_root_path(worktree);
8549 cl_arg.branch_name = got_worktree_get_head_ref_name(worktree);
8550 if (!histedit_in_progress) {
8551 if (strncmp(cl_arg.branch_name, "refs/heads/", 11) != 0) {
8552 error = got_error(GOT_ERR_COMMIT_BRANCH);
8553 goto done;
8555 cl_arg.branch_name += 11;
8557 cl_arg.repo_path = got_repo_get_path(repo);
8558 error = got_worktree_commit(&id, worktree, &paths, author, NULL,
8559 allow_bad_symlinks, collect_commit_logmsg, &cl_arg,
8560 print_status, NULL, repo);
8561 if (error) {
8562 if (error->code != GOT_ERR_COMMIT_MSG_EMPTY &&
8563 cl_arg.logmsg_path != NULL)
8564 preserve_logmsg = 1;
8565 goto done;
8568 error = got_object_id_str(&id_str, id);
8569 if (error)
8570 goto done;
8571 printf("Created commit %s\n", id_str);
8572 done:
8573 if (preserve_logmsg) {
8574 fprintf(stderr, "%s: log message preserved in %s\n",
8575 getprogname(), cl_arg.logmsg_path);
8576 } else if (cl_arg.logmsg_path && unlink(cl_arg.logmsg_path) == -1 &&
8577 error == NULL)
8578 error = got_error_from_errno2("unlink", cl_arg.logmsg_path);
8579 free(cl_arg.logmsg_path);
8580 if (repo) {
8581 const struct got_error *close_err = got_repo_close(repo);
8582 if (error == NULL)
8583 error = close_err;
8585 if (worktree)
8586 got_worktree_close(worktree);
8587 if (pack_fds) {
8588 const struct got_error *pack_err =
8589 got_repo_pack_fds_close(pack_fds);
8590 if (error == NULL)
8591 error = pack_err;
8593 free(cwd);
8594 free(id_str);
8595 free(gitconfig_path);
8596 free(editor);
8597 free(author);
8598 free(prepared_logmsg);
8599 return error;
8602 __dead static void
8603 usage_send(void)
8605 fprintf(stderr, "usage: %s send [-a] [-b branch] [-d branch] [-f] "
8606 "[-r repository-path] [-t tag] [-T] [-q] [-v] "
8607 "[remote-repository]\n", getprogname());
8608 exit(1);
8611 static void
8612 print_load_info(int print_colored, int print_found, int print_trees,
8613 int ncolored, int nfound, int ntrees)
8615 if (print_colored) {
8616 printf("%d commit%s colored", ncolored,
8617 ncolored == 1 ? "" : "s");
8619 if (print_found) {
8620 printf("%s%d object%s found",
8621 ncolored > 0 ? "; " : "",
8622 nfound, nfound == 1 ? "" : "s");
8624 if (print_trees) {
8625 printf("; %d tree%s scanned", ntrees,
8626 ntrees == 1 ? "" : "s");
8630 struct got_send_progress_arg {
8631 char last_scaled_packsize[FMT_SCALED_STRSIZE];
8632 int verbosity;
8633 int last_ncolored;
8634 int last_nfound;
8635 int last_ntrees;
8636 int loading_done;
8637 int last_ncommits;
8638 int last_nobj_total;
8639 int last_p_deltify;
8640 int last_p_written;
8641 int last_p_sent;
8642 int printed_something;
8643 int sent_something;
8644 struct got_pathlist_head *delete_branches;
8647 static const struct got_error *
8648 send_progress(void *arg, int ncolored, int nfound, int ntrees,
8649 off_t packfile_size, int ncommits, int nobj_total, int nobj_deltify,
8650 int nobj_written, off_t bytes_sent, const char *refname, int success)
8652 struct got_send_progress_arg *a = arg;
8653 char scaled_packsize[FMT_SCALED_STRSIZE];
8654 char scaled_sent[FMT_SCALED_STRSIZE];
8655 int p_deltify = 0, p_written = 0, p_sent = 0;
8656 int print_colored = 0, print_found = 0, print_trees = 0;
8657 int print_searching = 0, print_total = 0;
8658 int print_deltify = 0, print_written = 0, print_sent = 0;
8660 if (a->verbosity < 0)
8661 return NULL;
8663 if (refname) {
8664 const char *status = success ? "accepted" : "rejected";
8666 if (success) {
8667 struct got_pathlist_entry *pe;
8668 TAILQ_FOREACH(pe, a->delete_branches, entry) {
8669 const char *branchname = pe->path;
8670 if (got_path_cmp(branchname, refname,
8671 strlen(branchname), strlen(refname)) == 0) {
8672 status = "deleted";
8673 a->sent_something = 1;
8674 break;
8679 if (a->printed_something)
8680 putchar('\n');
8681 printf("Server has %s %s", status, refname);
8682 a->printed_something = 1;
8683 return NULL;
8686 if (a->last_ncolored != ncolored) {
8687 print_colored = 1;
8688 a->last_ncolored = ncolored;
8691 if (a->last_nfound != nfound) {
8692 print_colored = 1;
8693 print_found = 1;
8694 a->last_nfound = nfound;
8697 if (a->last_ntrees != ntrees) {
8698 print_colored = 1;
8699 print_found = 1;
8700 print_trees = 1;
8701 a->last_ntrees = ntrees;
8704 if ((print_colored || print_found || print_trees) &&
8705 !a->loading_done) {
8706 printf("\r");
8707 print_load_info(print_colored, print_found, print_trees,
8708 ncolored, nfound, ntrees);
8709 a->printed_something = 1;
8710 fflush(stdout);
8711 return NULL;
8712 } else if (!a->loading_done) {
8713 printf("\r");
8714 print_load_info(1, 1, 1, ncolored, nfound, ntrees);
8715 printf("\n");
8716 a->loading_done = 1;
8719 if (fmt_scaled(packfile_size, scaled_packsize) == -1)
8720 return got_error_from_errno("fmt_scaled");
8721 if (fmt_scaled(bytes_sent, scaled_sent) == -1)
8722 return got_error_from_errno("fmt_scaled");
8724 if (a->last_ncommits != ncommits) {
8725 print_searching = 1;
8726 a->last_ncommits = ncommits;
8729 if (a->last_nobj_total != nobj_total) {
8730 print_searching = 1;
8731 print_total = 1;
8732 a->last_nobj_total = nobj_total;
8735 if (packfile_size > 0 && (a->last_scaled_packsize[0] == '\0' ||
8736 strcmp(scaled_packsize, a->last_scaled_packsize)) != 0) {
8737 if (strlcpy(a->last_scaled_packsize, scaled_packsize,
8738 FMT_SCALED_STRSIZE) >= FMT_SCALED_STRSIZE)
8739 return got_error(GOT_ERR_NO_SPACE);
8742 if (nobj_deltify > 0 || nobj_written > 0) {
8743 if (nobj_deltify > 0) {
8744 p_deltify = (nobj_deltify * 100) / nobj_total;
8745 if (p_deltify != a->last_p_deltify) {
8746 a->last_p_deltify = p_deltify;
8747 print_searching = 1;
8748 print_total = 1;
8749 print_deltify = 1;
8752 if (nobj_written > 0) {
8753 p_written = (nobj_written * 100) / nobj_total;
8754 if (p_written != a->last_p_written) {
8755 a->last_p_written = p_written;
8756 print_searching = 1;
8757 print_total = 1;
8758 print_deltify = 1;
8759 print_written = 1;
8764 if (bytes_sent > 0) {
8765 p_sent = (bytes_sent * 100) / packfile_size;
8766 if (p_sent != a->last_p_sent) {
8767 a->last_p_sent = p_sent;
8768 print_searching = 1;
8769 print_total = 1;
8770 print_deltify = 1;
8771 print_written = 1;
8772 print_sent = 1;
8774 a->sent_something = 1;
8777 if (print_searching || print_total || print_deltify || print_written ||
8778 print_sent)
8779 printf("\r");
8780 if (print_searching)
8781 printf("packing %d reference%s", ncommits,
8782 ncommits == 1 ? "" : "s");
8783 if (print_total)
8784 printf("; %d object%s", nobj_total,
8785 nobj_total == 1 ? "" : "s");
8786 if (print_deltify)
8787 printf("; deltify: %d%%", p_deltify);
8788 if (print_sent)
8789 printf("; uploading pack: %*s %d%%", FMT_SCALED_STRSIZE - 2,
8790 scaled_packsize, p_sent);
8791 else if (print_written)
8792 printf("; writing pack: %*s %d%%", FMT_SCALED_STRSIZE - 2,
8793 scaled_packsize, p_written);
8794 if (print_searching || print_total || print_deltify ||
8795 print_written || print_sent) {
8796 a->printed_something = 1;
8797 fflush(stdout);
8799 return NULL;
8802 static const struct got_error *
8803 cmd_send(int argc, char *argv[])
8805 const struct got_error *error = NULL;
8806 char *cwd = NULL, *repo_path = NULL;
8807 const char *remote_name;
8808 char *proto = NULL, *host = NULL, *port = NULL;
8809 char *repo_name = NULL, *server_path = NULL;
8810 const struct got_remote_repo *remotes, *remote = NULL;
8811 int nremotes, nbranches = 0, ntags = 0, ndelete_branches = 0;
8812 struct got_repository *repo = NULL;
8813 struct got_worktree *worktree = NULL;
8814 const struct got_gotconfig *repo_conf = NULL, *worktree_conf = NULL;
8815 struct got_pathlist_head branches;
8816 struct got_pathlist_head tags;
8817 struct got_reflist_head all_branches;
8818 struct got_reflist_head all_tags;
8819 struct got_pathlist_head delete_args;
8820 struct got_pathlist_head delete_branches;
8821 struct got_reflist_entry *re;
8822 struct got_pathlist_entry *pe;
8823 int i, ch, sendfd = -1, sendstatus;
8824 pid_t sendpid = -1;
8825 struct got_send_progress_arg spa;
8826 int verbosity = 0, overwrite_refs = 0;
8827 int send_all_branches = 0, send_all_tags = 0;
8828 struct got_reference *ref = NULL;
8829 int *pack_fds = NULL;
8831 TAILQ_INIT(&branches);
8832 TAILQ_INIT(&tags);
8833 TAILQ_INIT(&all_branches);
8834 TAILQ_INIT(&all_tags);
8835 TAILQ_INIT(&delete_args);
8836 TAILQ_INIT(&delete_branches);
8838 while ((ch = getopt(argc, argv, "ab:d:fr:t:Tvq")) != -1) {
8839 switch (ch) {
8840 case 'a':
8841 send_all_branches = 1;
8842 break;
8843 case 'b':
8844 error = got_pathlist_append(&branches, optarg, NULL);
8845 if (error)
8846 return error;
8847 nbranches++;
8848 break;
8849 case 'd':
8850 error = got_pathlist_append(&delete_args, optarg, NULL);
8851 if (error)
8852 return error;
8853 break;
8854 case 'f':
8855 overwrite_refs = 1;
8856 break;
8857 case 'r':
8858 repo_path = realpath(optarg, NULL);
8859 if (repo_path == NULL)
8860 return got_error_from_errno2("realpath",
8861 optarg);
8862 got_path_strip_trailing_slashes(repo_path);
8863 break;
8864 case 't':
8865 error = got_pathlist_append(&tags, optarg, NULL);
8866 if (error)
8867 return error;
8868 ntags++;
8869 break;
8870 case 'T':
8871 send_all_tags = 1;
8872 break;
8873 case 'v':
8874 if (verbosity < 0)
8875 verbosity = 0;
8876 else if (verbosity < 3)
8877 verbosity++;
8878 break;
8879 case 'q':
8880 verbosity = -1;
8881 break;
8882 default:
8883 usage_send();
8884 /* NOTREACHED */
8887 argc -= optind;
8888 argv += optind;
8890 if (send_all_branches && !TAILQ_EMPTY(&branches))
8891 option_conflict('a', 'b');
8892 if (send_all_tags && !TAILQ_EMPTY(&tags))
8893 option_conflict('T', 't');
8896 if (argc == 0)
8897 remote_name = GOT_SEND_DEFAULT_REMOTE_NAME;
8898 else if (argc == 1)
8899 remote_name = argv[0];
8900 else
8901 usage_send();
8903 cwd = getcwd(NULL, 0);
8904 if (cwd == NULL) {
8905 error = got_error_from_errno("getcwd");
8906 goto done;
8909 error = got_repo_pack_fds_open(&pack_fds);
8910 if (error != NULL)
8911 goto done;
8913 if (repo_path == NULL) {
8914 error = got_worktree_open(&worktree, cwd);
8915 if (error && error->code != GOT_ERR_NOT_WORKTREE)
8916 goto done;
8917 else
8918 error = NULL;
8919 if (worktree) {
8920 repo_path =
8921 strdup(got_worktree_get_repo_path(worktree));
8922 if (repo_path == NULL)
8923 error = got_error_from_errno("strdup");
8924 if (error)
8925 goto done;
8926 } else {
8927 repo_path = strdup(cwd);
8928 if (repo_path == NULL) {
8929 error = got_error_from_errno("strdup");
8930 goto done;
8935 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
8936 if (error)
8937 goto done;
8939 if (worktree) {
8940 worktree_conf = got_worktree_get_gotconfig(worktree);
8941 if (worktree_conf) {
8942 got_gotconfig_get_remotes(&nremotes, &remotes,
8943 worktree_conf);
8944 for (i = 0; i < nremotes; i++) {
8945 if (strcmp(remotes[i].name, remote_name) == 0) {
8946 remote = &remotes[i];
8947 break;
8952 if (remote == NULL) {
8953 repo_conf = got_repo_get_gotconfig(repo);
8954 if (repo_conf) {
8955 got_gotconfig_get_remotes(&nremotes, &remotes,
8956 repo_conf);
8957 for (i = 0; i < nremotes; i++) {
8958 if (strcmp(remotes[i].name, remote_name) == 0) {
8959 remote = &remotes[i];
8960 break;
8965 if (remote == NULL) {
8966 got_repo_get_gitconfig_remotes(&nremotes, &remotes, repo);
8967 for (i = 0; i < nremotes; i++) {
8968 if (strcmp(remotes[i].name, remote_name) == 0) {
8969 remote = &remotes[i];
8970 break;
8974 if (remote == NULL) {
8975 error = got_error_path(remote_name, GOT_ERR_NO_REMOTE);
8976 goto done;
8979 error = got_dial_parse_uri(&proto, &host, &port, &server_path,
8980 &repo_name, remote->send_url);
8981 if (error)
8982 goto done;
8984 if (strcmp(proto, "git") == 0) {
8985 #ifndef PROFILE
8986 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
8987 "sendfd dns inet unveil", NULL) == -1)
8988 err(1, "pledge");
8989 #endif
8990 } else if (strcmp(proto, "git+ssh") == 0 ||
8991 strcmp(proto, "ssh") == 0) {
8992 #ifndef PROFILE
8993 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
8994 "sendfd unveil", NULL) == -1)
8995 err(1, "pledge");
8996 #endif
8997 } else if (strcmp(proto, "http") == 0 ||
8998 strcmp(proto, "git+http") == 0) {
8999 error = got_error_path(proto, GOT_ERR_NOT_IMPL);
9000 goto done;
9001 } else {
9002 error = got_error_path(proto, GOT_ERR_BAD_PROTO);
9003 goto done;
9006 error = got_dial_apply_unveil(proto);
9007 if (error)
9008 goto done;
9010 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
9011 if (error)
9012 goto done;
9014 if (send_all_branches) {
9015 error = got_ref_list(&all_branches, repo, "refs/heads",
9016 got_ref_cmp_by_name, NULL);
9017 if (error)
9018 goto done;
9019 TAILQ_FOREACH(re, &all_branches, entry) {
9020 const char *branchname = got_ref_get_name(re->ref);
9021 error = got_pathlist_append(&branches,
9022 branchname, NULL);
9023 if (error)
9024 goto done;
9025 nbranches++;
9027 } else if (nbranches == 0) {
9028 for (i = 0; i < remote->nsend_branches; i++) {
9029 got_pathlist_append(&branches,
9030 remote->send_branches[i], NULL);
9034 if (send_all_tags) {
9035 error = got_ref_list(&all_tags, repo, "refs/tags",
9036 got_ref_cmp_by_name, NULL);
9037 if (error)
9038 goto done;
9039 TAILQ_FOREACH(re, &all_tags, entry) {
9040 const char *tagname = got_ref_get_name(re->ref);
9041 error = got_pathlist_append(&tags,
9042 tagname, NULL);
9043 if (error)
9044 goto done;
9045 ntags++;
9050 * To prevent accidents only branches in refs/heads/ can be deleted
9051 * with 'got send -d'.
9052 * Deleting anything else requires local repository access or Git.
9054 TAILQ_FOREACH(pe, &delete_args, entry) {
9055 const char *branchname = pe->path;
9056 char *s;
9057 struct got_pathlist_entry *new;
9058 if (strncmp(branchname, "refs/heads/", 11) == 0) {
9059 s = strdup(branchname);
9060 if (s == NULL) {
9061 error = got_error_from_errno("strdup");
9062 goto done;
9064 } else {
9065 if (asprintf(&s, "refs/heads/%s", branchname) == -1) {
9066 error = got_error_from_errno("asprintf");
9067 goto done;
9070 error = got_pathlist_insert(&new, &delete_branches, s, NULL);
9071 if (error || new == NULL /* duplicate */)
9072 free(s);
9073 if (error)
9074 goto done;
9075 ndelete_branches++;
9078 if (nbranches == 0 && ndelete_branches == 0) {
9079 struct got_reference *head_ref;
9080 if (worktree)
9081 error = got_ref_open(&head_ref, repo,
9082 got_worktree_get_head_ref_name(worktree), 0);
9083 else
9084 error = got_ref_open(&head_ref, repo, GOT_REF_HEAD, 0);
9085 if (error)
9086 goto done;
9087 if (got_ref_is_symbolic(head_ref)) {
9088 error = got_ref_resolve_symbolic(&ref, repo, head_ref);
9089 got_ref_close(head_ref);
9090 if (error)
9091 goto done;
9092 } else
9093 ref = head_ref;
9094 error = got_pathlist_append(&branches, got_ref_get_name(ref),
9095 NULL);
9096 if (error)
9097 goto done;
9098 nbranches++;
9101 if (verbosity >= 0)
9102 printf("Connecting to \"%s\" %s%s%s\n", remote->name, host,
9103 port ? ":" : "", port ? port : "");
9105 error = got_send_connect(&sendpid, &sendfd, proto, host, port,
9106 server_path, verbosity);
9107 if (error)
9108 goto done;
9110 memset(&spa, 0, sizeof(spa));
9111 spa.last_scaled_packsize[0] = '\0';
9112 spa.last_p_deltify = -1;
9113 spa.last_p_written = -1;
9114 spa.verbosity = verbosity;
9115 spa.delete_branches = &delete_branches;
9116 error = got_send_pack(remote_name, &branches, &tags, &delete_branches,
9117 verbosity, overwrite_refs, sendfd, repo, send_progress, &spa,
9118 check_cancelled, NULL);
9119 if (spa.printed_something)
9120 putchar('\n');
9121 if (error)
9122 goto done;
9123 if (!spa.sent_something && verbosity >= 0)
9124 printf("Already up-to-date\n");
9125 done:
9126 if (sendpid > 0) {
9127 if (kill(sendpid, SIGTERM) == -1)
9128 error = got_error_from_errno("kill");
9129 if (waitpid(sendpid, &sendstatus, 0) == -1 && error == NULL)
9130 error = got_error_from_errno("waitpid");
9132 if (sendfd != -1 && close(sendfd) == -1 && error == NULL)
9133 error = got_error_from_errno("close");
9134 if (repo) {
9135 const struct got_error *close_err = got_repo_close(repo);
9136 if (error == NULL)
9137 error = close_err;
9139 if (worktree)
9140 got_worktree_close(worktree);
9141 if (pack_fds) {
9142 const struct got_error *pack_err =
9143 got_repo_pack_fds_close(pack_fds);
9144 if (error == NULL)
9145 error = pack_err;
9147 if (ref)
9148 got_ref_close(ref);
9149 got_pathlist_free(&branches);
9150 got_pathlist_free(&tags);
9151 got_ref_list_free(&all_branches);
9152 got_ref_list_free(&all_tags);
9153 got_pathlist_free(&delete_args);
9154 TAILQ_FOREACH(pe, &delete_branches, entry)
9155 free((char *)pe->path);
9156 got_pathlist_free(&delete_branches);
9157 free(cwd);
9158 free(repo_path);
9159 free(proto);
9160 free(host);
9161 free(port);
9162 free(server_path);
9163 free(repo_name);
9164 return error;
9167 __dead static void
9168 usage_cherrypick(void)
9170 fprintf(stderr, "usage: %s cherrypick commit-id\n", getprogname());
9171 exit(1);
9174 static const struct got_error *
9175 cmd_cherrypick(int argc, char *argv[])
9177 const struct got_error *error = NULL;
9178 struct got_worktree *worktree = NULL;
9179 struct got_repository *repo = NULL;
9180 char *cwd = NULL, *commit_id_str = NULL;
9181 struct got_object_id *commit_id = NULL;
9182 struct got_commit_object *commit = NULL;
9183 struct got_object_qid *pid;
9184 int ch;
9185 struct got_update_progress_arg upa;
9186 int *pack_fds = NULL;
9188 while ((ch = getopt(argc, argv, "")) != -1) {
9189 switch (ch) {
9190 default:
9191 usage_cherrypick();
9192 /* NOTREACHED */
9196 argc -= optind;
9197 argv += optind;
9199 #ifndef PROFILE
9200 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
9201 "unveil", NULL) == -1)
9202 err(1, "pledge");
9203 #endif
9204 if (argc != 1)
9205 usage_cherrypick();
9207 cwd = getcwd(NULL, 0);
9208 if (cwd == NULL) {
9209 error = got_error_from_errno("getcwd");
9210 goto done;
9213 error = got_repo_pack_fds_open(&pack_fds);
9214 if (error != NULL)
9215 goto done;
9217 error = got_worktree_open(&worktree, cwd);
9218 if (error) {
9219 if (error->code == GOT_ERR_NOT_WORKTREE)
9220 error = wrap_not_worktree_error(error, "cherrypick",
9221 cwd);
9222 goto done;
9225 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
9226 NULL, pack_fds);
9227 if (error != NULL)
9228 goto done;
9230 error = apply_unveil(got_repo_get_path(repo), 0,
9231 got_worktree_get_root_path(worktree));
9232 if (error)
9233 goto done;
9235 error = got_repo_match_object_id(&commit_id, NULL, argv[0],
9236 GOT_OBJ_TYPE_COMMIT, NULL, repo);
9237 if (error)
9238 goto done;
9239 error = got_object_id_str(&commit_id_str, commit_id);
9240 if (error)
9241 goto done;
9243 error = got_object_open_as_commit(&commit, repo, commit_id);
9244 if (error)
9245 goto done;
9246 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
9247 memset(&upa, 0, sizeof(upa));
9248 error = got_worktree_merge_files(worktree, pid ? &pid->id : NULL,
9249 commit_id, repo, update_progress, &upa, check_cancelled,
9250 NULL);
9251 if (error != NULL)
9252 goto done;
9254 if (upa.did_something)
9255 printf("Merged commit %s\n", commit_id_str);
9256 print_merge_progress_stats(&upa);
9257 done:
9258 if (commit)
9259 got_object_commit_close(commit);
9260 free(commit_id_str);
9261 if (worktree)
9262 got_worktree_close(worktree);
9263 if (repo) {
9264 const struct got_error *close_err = got_repo_close(repo);
9265 if (error == NULL)
9266 error = close_err;
9268 if (pack_fds) {
9269 const struct got_error *pack_err =
9270 got_repo_pack_fds_close(pack_fds);
9271 if (error == NULL)
9272 error = pack_err;
9275 return error;
9278 __dead static void
9279 usage_backout(void)
9281 fprintf(stderr, "usage: %s backout commit-id\n", getprogname());
9282 exit(1);
9285 static const struct got_error *
9286 cmd_backout(int argc, char *argv[])
9288 const struct got_error *error = NULL;
9289 struct got_worktree *worktree = NULL;
9290 struct got_repository *repo = NULL;
9291 char *cwd = NULL, *commit_id_str = NULL;
9292 struct got_object_id *commit_id = NULL;
9293 struct got_commit_object *commit = NULL;
9294 struct got_object_qid *pid;
9295 int ch;
9296 struct got_update_progress_arg upa;
9297 int *pack_fds = NULL;
9299 while ((ch = getopt(argc, argv, "")) != -1) {
9300 switch (ch) {
9301 default:
9302 usage_backout();
9303 /* NOTREACHED */
9307 argc -= optind;
9308 argv += optind;
9310 #ifndef PROFILE
9311 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
9312 "unveil", NULL) == -1)
9313 err(1, "pledge");
9314 #endif
9315 if (argc != 1)
9316 usage_backout();
9318 cwd = getcwd(NULL, 0);
9319 if (cwd == NULL) {
9320 error = got_error_from_errno("getcwd");
9321 goto done;
9324 error = got_repo_pack_fds_open(&pack_fds);
9325 if (error != NULL)
9326 goto done;
9328 error = got_worktree_open(&worktree, cwd);
9329 if (error) {
9330 if (error->code == GOT_ERR_NOT_WORKTREE)
9331 error = wrap_not_worktree_error(error, "backout", cwd);
9332 goto done;
9335 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
9336 NULL, pack_fds);
9337 if (error != NULL)
9338 goto done;
9340 error = apply_unveil(got_repo_get_path(repo), 0,
9341 got_worktree_get_root_path(worktree));
9342 if (error)
9343 goto done;
9345 error = got_repo_match_object_id(&commit_id, NULL, argv[0],
9346 GOT_OBJ_TYPE_COMMIT, NULL, repo);
9347 if (error)
9348 goto done;
9349 error = got_object_id_str(&commit_id_str, commit_id);
9350 if (error)
9351 goto done;
9353 error = got_object_open_as_commit(&commit, repo, commit_id);
9354 if (error)
9355 goto done;
9356 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
9357 if (pid == NULL) {
9358 error = got_error(GOT_ERR_ROOT_COMMIT);
9359 goto done;
9362 memset(&upa, 0, sizeof(upa));
9363 error = got_worktree_merge_files(worktree, commit_id, &pid->id,
9364 repo, update_progress, &upa, check_cancelled, NULL);
9365 if (error != NULL)
9366 goto done;
9368 if (upa.did_something)
9369 printf("Backed out commit %s\n", commit_id_str);
9370 print_merge_progress_stats(&upa);
9371 done:
9372 if (commit)
9373 got_object_commit_close(commit);
9374 free(commit_id_str);
9375 if (worktree)
9376 got_worktree_close(worktree);
9377 if (repo) {
9378 const struct got_error *close_err = got_repo_close(repo);
9379 if (error == NULL)
9380 error = close_err;
9382 if (pack_fds) {
9383 const struct got_error *pack_err =
9384 got_repo_pack_fds_close(pack_fds);
9385 if (error == NULL)
9386 error = pack_err;
9388 return error;
9391 __dead static void
9392 usage_rebase(void)
9394 fprintf(stderr, "usage: %s rebase [-a] [-c] [-l] [-X] [branch]\n",
9395 getprogname());
9396 exit(1);
9399 static void
9400 trim_logmsg(char *logmsg, int limit)
9402 char *nl;
9403 size_t len;
9405 len = strlen(logmsg);
9406 if (len > limit)
9407 len = limit;
9408 logmsg[len] = '\0';
9409 nl = strchr(logmsg, '\n');
9410 if (nl)
9411 *nl = '\0';
9414 static const struct got_error *
9415 get_short_logmsg(char **logmsg, int limit, struct got_commit_object *commit)
9417 const struct got_error *err;
9418 char *logmsg0 = NULL;
9419 const char *s;
9421 err = got_object_commit_get_logmsg(&logmsg0, commit);
9422 if (err)
9423 return err;
9425 s = logmsg0;
9426 while (isspace((unsigned char)s[0]))
9427 s++;
9429 *logmsg = strdup(s);
9430 if (*logmsg == NULL) {
9431 err = got_error_from_errno("strdup");
9432 goto done;
9435 trim_logmsg(*logmsg, limit);
9436 done:
9437 free(logmsg0);
9438 return err;
9441 static const struct got_error *
9442 show_rebase_merge_conflict(struct got_object_id *id,
9443 struct got_repository *repo)
9445 const struct got_error *err;
9446 struct got_commit_object *commit = NULL;
9447 char *id_str = NULL, *logmsg = NULL;
9449 err = got_object_open_as_commit(&commit, repo, id);
9450 if (err)
9451 return err;
9453 err = got_object_id_str(&id_str, id);
9454 if (err)
9455 goto done;
9457 id_str[12] = '\0';
9459 err = get_short_logmsg(&logmsg, 42, commit);
9460 if (err)
9461 goto done;
9463 printf("%s -> merge conflict: %s\n", id_str, logmsg);
9464 done:
9465 free(id_str);
9466 got_object_commit_close(commit);
9467 free(logmsg);
9468 return err;
9471 static const struct got_error *
9472 show_rebase_progress(struct got_commit_object *commit,
9473 struct got_object_id *old_id, struct got_object_id *new_id)
9475 const struct got_error *err;
9476 char *old_id_str = NULL, *new_id_str = NULL, *logmsg = NULL;
9478 err = got_object_id_str(&old_id_str, old_id);
9479 if (err)
9480 goto done;
9482 if (new_id) {
9483 err = got_object_id_str(&new_id_str, new_id);
9484 if (err)
9485 goto done;
9488 old_id_str[12] = '\0';
9489 if (new_id_str)
9490 new_id_str[12] = '\0';
9492 err = get_short_logmsg(&logmsg, 42, commit);
9493 if (err)
9494 goto done;
9496 printf("%s -> %s: %s\n", old_id_str,
9497 new_id_str ? new_id_str : "no-op change", logmsg);
9498 done:
9499 free(old_id_str);
9500 free(new_id_str);
9501 free(logmsg);
9502 return err;
9505 static const struct got_error *
9506 rebase_complete(struct got_worktree *worktree, struct got_fileindex *fileindex,
9507 struct got_reference *branch, struct got_reference *new_base_branch,
9508 struct got_reference *tmp_branch, struct got_repository *repo,
9509 int create_backup)
9511 printf("Switching work tree to %s\n", got_ref_get_name(branch));
9512 return got_worktree_rebase_complete(worktree, fileindex,
9513 new_base_branch, tmp_branch, branch, repo, create_backup);
9516 static const struct got_error *
9517 rebase_commit(struct got_pathlist_head *merged_paths,
9518 struct got_worktree *worktree, struct got_fileindex *fileindex,
9519 struct got_reference *tmp_branch,
9520 struct got_object_id *commit_id, struct got_repository *repo)
9522 const struct got_error *error;
9523 struct got_commit_object *commit;
9524 struct got_object_id *new_commit_id;
9526 error = got_object_open_as_commit(&commit, repo, commit_id);
9527 if (error)
9528 return error;
9530 error = got_worktree_rebase_commit(&new_commit_id, merged_paths,
9531 worktree, fileindex, tmp_branch, commit, commit_id, repo);
9532 if (error) {
9533 if (error->code != GOT_ERR_COMMIT_NO_CHANGES)
9534 goto done;
9535 error = show_rebase_progress(commit, commit_id, NULL);
9536 } else {
9537 error = show_rebase_progress(commit, commit_id, new_commit_id);
9538 free(new_commit_id);
9540 done:
9541 got_object_commit_close(commit);
9542 return error;
9545 struct check_path_prefix_arg {
9546 const char *path_prefix;
9547 size_t len;
9548 int errcode;
9551 static const struct got_error *
9552 check_path_prefix_in_diff(void *arg, struct got_blob_object *blob1,
9553 struct got_blob_object *blob2, FILE *f1, FILE *f2,
9554 struct got_object_id *id1, struct got_object_id *id2,
9555 const char *path1, const char *path2,
9556 mode_t mode1, mode_t mode2, struct got_repository *repo)
9558 struct check_path_prefix_arg *a = arg;
9560 if ((path1 && !got_path_is_child(path1, a->path_prefix, a->len)) ||
9561 (path2 && !got_path_is_child(path2, a->path_prefix, a->len)))
9562 return got_error(a->errcode);
9564 return NULL;
9567 static const struct got_error *
9568 check_path_prefix(struct got_object_id *parent_id,
9569 struct got_object_id *commit_id, const char *path_prefix,
9570 int errcode, struct got_repository *repo)
9572 const struct got_error *err;
9573 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
9574 struct got_commit_object *commit = NULL, *parent_commit = NULL;
9575 struct check_path_prefix_arg cpp_arg;
9577 if (got_path_is_root_dir(path_prefix))
9578 return NULL;
9580 err = got_object_open_as_commit(&commit, repo, commit_id);
9581 if (err)
9582 goto done;
9584 err = got_object_open_as_commit(&parent_commit, repo, parent_id);
9585 if (err)
9586 goto done;
9588 err = got_object_open_as_tree(&tree1, repo,
9589 got_object_commit_get_tree_id(parent_commit));
9590 if (err)
9591 goto done;
9593 err = got_object_open_as_tree(&tree2, repo,
9594 got_object_commit_get_tree_id(commit));
9595 if (err)
9596 goto done;
9598 cpp_arg.path_prefix = path_prefix;
9599 while (cpp_arg.path_prefix[0] == '/')
9600 cpp_arg.path_prefix++;
9601 cpp_arg.len = strlen(cpp_arg.path_prefix);
9602 cpp_arg.errcode = errcode;
9603 err = got_diff_tree(tree1, tree2, NULL, NULL, -1, -1, "", "", repo,
9604 check_path_prefix_in_diff, &cpp_arg, 0);
9605 done:
9606 if (tree1)
9607 got_object_tree_close(tree1);
9608 if (tree2)
9609 got_object_tree_close(tree2);
9610 if (commit)
9611 got_object_commit_close(commit);
9612 if (parent_commit)
9613 got_object_commit_close(parent_commit);
9614 return err;
9617 static const struct got_error *
9618 collect_commits(struct got_object_id_queue *commits,
9619 struct got_object_id *initial_commit_id,
9620 struct got_object_id *iter_start_id, struct got_object_id *iter_stop_id,
9621 const char *path_prefix, int path_prefix_errcode,
9622 struct got_repository *repo)
9624 const struct got_error *err = NULL;
9625 struct got_commit_graph *graph = NULL;
9626 struct got_object_id *parent_id = NULL;
9627 struct got_object_qid *qid;
9628 struct got_object_id *commit_id = initial_commit_id;
9630 err = got_commit_graph_open(&graph, "/", 1);
9631 if (err)
9632 return err;
9634 err = got_commit_graph_iter_start(graph, iter_start_id, repo,
9635 check_cancelled, NULL);
9636 if (err)
9637 goto done;
9638 while (got_object_id_cmp(commit_id, iter_stop_id) != 0) {
9639 err = got_commit_graph_iter_next(&parent_id, graph, repo,
9640 check_cancelled, NULL);
9641 if (err) {
9642 if (err->code == GOT_ERR_ITER_COMPLETED) {
9643 err = got_error_msg(GOT_ERR_ANCESTRY,
9644 "ran out of commits to rebase before "
9645 "youngest common ancestor commit has "
9646 "been reached?!?");
9648 goto done;
9649 } else {
9650 err = check_path_prefix(parent_id, commit_id,
9651 path_prefix, path_prefix_errcode, repo);
9652 if (err)
9653 goto done;
9655 err = got_object_qid_alloc(&qid, commit_id);
9656 if (err)
9657 goto done;
9658 STAILQ_INSERT_HEAD(commits, qid, entry);
9659 commit_id = parent_id;
9662 done:
9663 got_commit_graph_close(graph);
9664 return err;
9667 static const struct got_error *
9668 get_commit_brief_str(char **brief_str, struct got_commit_object *commit)
9670 const struct got_error *err = NULL;
9671 time_t committer_time;
9672 struct tm tm;
9673 char datebuf[11]; /* YYYY-MM-DD + NUL */
9674 char *author0 = NULL, *author, *smallerthan;
9675 char *logmsg0 = NULL, *logmsg, *newline;
9677 committer_time = got_object_commit_get_committer_time(commit);
9678 if (gmtime_r(&committer_time, &tm) == NULL)
9679 return got_error_from_errno("gmtime_r");
9680 if (strftime(datebuf, sizeof(datebuf), "%G-%m-%d", &tm) == 0)
9681 return got_error(GOT_ERR_NO_SPACE);
9683 author0 = strdup(got_object_commit_get_author(commit));
9684 if (author0 == NULL)
9685 return got_error_from_errno("strdup");
9686 author = author0;
9687 smallerthan = strchr(author, '<');
9688 if (smallerthan && smallerthan[1] != '\0')
9689 author = smallerthan + 1;
9690 author[strcspn(author, "@>")] = '\0';
9692 err = got_object_commit_get_logmsg(&logmsg0, commit);
9693 if (err)
9694 goto done;
9695 logmsg = logmsg0;
9696 while (*logmsg == '\n')
9697 logmsg++;
9698 newline = strchr(logmsg, '\n');
9699 if (newline)
9700 *newline = '\0';
9702 if (asprintf(brief_str, "%s %s %s",
9703 datebuf, author, logmsg) == -1)
9704 err = got_error_from_errno("asprintf");
9705 done:
9706 free(author0);
9707 free(logmsg0);
9708 return err;
9711 static const struct got_error *
9712 delete_backup_ref(struct got_reference *ref, struct got_object_id *id,
9713 struct got_repository *repo)
9715 const struct got_error *err;
9716 char *id_str;
9718 err = got_object_id_str(&id_str, id);
9719 if (err)
9720 return err;
9722 err = got_ref_delete(ref, repo);
9723 if (err)
9724 goto done;
9726 printf("Deleted %s: %s\n", got_ref_get_name(ref), id_str);
9727 done:
9728 free(id_str);
9729 return err;
9732 static const struct got_error *
9733 print_backup_ref(const char *branch_name, const char *new_id_str,
9734 struct got_object_id *old_commit_id, struct got_commit_object *old_commit,
9735 struct got_reflist_object_id_map *refs_idmap,
9736 struct got_repository *repo)
9738 const struct got_error *err = NULL;
9739 struct got_reflist_head *refs;
9740 char *refs_str = NULL;
9741 struct got_object_id *new_commit_id = NULL;
9742 struct got_commit_object *new_commit = NULL;
9743 char *new_commit_brief_str = NULL;
9744 struct got_object_id *yca_id = NULL;
9745 struct got_commit_object *yca_commit = NULL;
9746 char *yca_id_str = NULL, *yca_brief_str = NULL;
9747 char *custom_refs_str;
9749 if (asprintf(&custom_refs_str, "formerly %s", branch_name) == -1)
9750 return got_error_from_errno("asprintf");
9752 err = print_commit(old_commit, old_commit_id, repo, NULL, NULL,
9753 0, 0, refs_idmap, custom_refs_str);
9754 if (err)
9755 goto done;
9757 err = got_object_resolve_id_str(&new_commit_id, repo, new_id_str);
9758 if (err)
9759 goto done;
9761 refs = got_reflist_object_id_map_lookup(refs_idmap, new_commit_id);
9762 if (refs) {
9763 err = build_refs_str(&refs_str, refs, new_commit_id, repo, 0);
9764 if (err)
9765 goto done;
9768 err = got_object_open_as_commit(&new_commit, repo, new_commit_id);
9769 if (err)
9770 goto done;
9772 err = get_commit_brief_str(&new_commit_brief_str, new_commit);
9773 if (err)
9774 goto done;
9776 err = got_commit_graph_find_youngest_common_ancestor(&yca_id,
9777 old_commit_id, new_commit_id, 1, repo, check_cancelled, NULL);
9778 if (err)
9779 goto done;
9781 printf("has become commit %s%s%s%s\n %s\n", new_id_str,
9782 refs_str ? " (" : "", refs_str ? refs_str : "",
9783 refs_str ? ")" : "", new_commit_brief_str);
9784 if (yca_id && got_object_id_cmp(yca_id, new_commit_id) != 0 &&
9785 got_object_id_cmp(yca_id, old_commit_id) != 0) {
9786 free(refs_str);
9787 refs_str = NULL;
9789 err = got_object_open_as_commit(&yca_commit, repo, yca_id);
9790 if (err)
9791 goto done;
9793 err = get_commit_brief_str(&yca_brief_str, yca_commit);
9794 if (err)
9795 goto done;
9797 err = got_object_id_str(&yca_id_str, yca_id);
9798 if (err)
9799 goto done;
9801 refs = got_reflist_object_id_map_lookup(refs_idmap, yca_id);
9802 if (refs) {
9803 err = build_refs_str(&refs_str, refs, yca_id, repo, 0);
9804 if (err)
9805 goto done;
9807 printf("history forked at %s%s%s%s\n %s\n",
9808 yca_id_str,
9809 refs_str ? " (" : "", refs_str ? refs_str : "",
9810 refs_str ? ")" : "", yca_brief_str);
9812 done:
9813 free(custom_refs_str);
9814 free(new_commit_id);
9815 free(refs_str);
9816 free(yca_id);
9817 free(yca_id_str);
9818 free(yca_brief_str);
9819 if (new_commit)
9820 got_object_commit_close(new_commit);
9821 if (yca_commit)
9822 got_object_commit_close(yca_commit);
9824 return NULL;
9827 static const struct got_error *
9828 process_backup_refs(const char *backup_ref_prefix,
9829 const char *wanted_branch_name,
9830 int delete, struct got_repository *repo)
9832 const struct got_error *err;
9833 struct got_reflist_head refs, backup_refs;
9834 struct got_reflist_entry *re;
9835 const size_t backup_ref_prefix_len = strlen(backup_ref_prefix);
9836 struct got_object_id *old_commit_id = NULL;
9837 char *branch_name = NULL;
9838 struct got_commit_object *old_commit = NULL;
9839 struct got_reflist_object_id_map *refs_idmap = NULL;
9840 int wanted_branch_found = 0;
9842 TAILQ_INIT(&refs);
9843 TAILQ_INIT(&backup_refs);
9845 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
9846 if (err)
9847 return err;
9849 err = got_reflist_object_id_map_create(&refs_idmap, &refs, repo);
9850 if (err)
9851 goto done;
9853 if (wanted_branch_name) {
9854 if (strncmp(wanted_branch_name, "refs/heads/", 11) == 0)
9855 wanted_branch_name += 11;
9858 err = got_ref_list(&backup_refs, repo, backup_ref_prefix,
9859 got_ref_cmp_by_commit_timestamp_descending, repo);
9860 if (err)
9861 goto done;
9863 TAILQ_FOREACH(re, &backup_refs, entry) {
9864 const char *refname = got_ref_get_name(re->ref);
9865 char *slash;
9867 err = check_cancelled(NULL);
9868 if (err)
9869 break;
9871 err = got_ref_resolve(&old_commit_id, repo, re->ref);
9872 if (err)
9873 break;
9875 err = got_object_open_as_commit(&old_commit, repo,
9876 old_commit_id);
9877 if (err)
9878 break;
9880 if (strncmp(backup_ref_prefix, refname,
9881 backup_ref_prefix_len) == 0)
9882 refname += backup_ref_prefix_len;
9884 while (refname[0] == '/')
9885 refname++;
9887 branch_name = strdup(refname);
9888 if (branch_name == NULL) {
9889 err = got_error_from_errno("strdup");
9890 break;
9892 slash = strrchr(branch_name, '/');
9893 if (slash) {
9894 *slash = '\0';
9895 refname += strlen(branch_name) + 1;
9898 if (wanted_branch_name == NULL ||
9899 strcmp(wanted_branch_name, branch_name) == 0) {
9900 wanted_branch_found = 1;
9901 if (delete) {
9902 err = delete_backup_ref(re->ref,
9903 old_commit_id, repo);
9904 } else {
9905 err = print_backup_ref(branch_name, refname,
9906 old_commit_id, old_commit, refs_idmap,
9907 repo);
9909 if (err)
9910 break;
9913 free(old_commit_id);
9914 old_commit_id = NULL;
9915 free(branch_name);
9916 branch_name = NULL;
9917 got_object_commit_close(old_commit);
9918 old_commit = NULL;
9921 if (wanted_branch_name && !wanted_branch_found) {
9922 err = got_error_fmt(GOT_ERR_NOT_REF,
9923 "%s/%s/", backup_ref_prefix, wanted_branch_name);
9925 done:
9926 if (refs_idmap)
9927 got_reflist_object_id_map_free(refs_idmap);
9928 got_ref_list_free(&refs);
9929 got_ref_list_free(&backup_refs);
9930 free(old_commit_id);
9931 free(branch_name);
9932 if (old_commit)
9933 got_object_commit_close(old_commit);
9934 return err;
9937 static const struct got_error *
9938 abort_progress(void *arg, unsigned char status, const char *path)
9941 * Unversioned files should not clutter progress output when
9942 * an operation is aborted.
9944 if (status == GOT_STATUS_UNVERSIONED)
9945 return NULL;
9947 return update_progress(arg, status, path);
9950 static const struct got_error *
9951 cmd_rebase(int argc, char *argv[])
9953 const struct got_error *error = NULL;
9954 struct got_worktree *worktree = NULL;
9955 struct got_repository *repo = NULL;
9956 struct got_fileindex *fileindex = NULL;
9957 char *cwd = NULL;
9958 struct got_reference *branch = NULL;
9959 struct got_reference *new_base_branch = NULL, *tmp_branch = NULL;
9960 struct got_object_id *commit_id = NULL, *parent_id = NULL;
9961 struct got_object_id *resume_commit_id = NULL;
9962 struct got_object_id *branch_head_commit_id = NULL, *yca_id = NULL;
9963 struct got_commit_object *commit = NULL;
9964 int ch, rebase_in_progress = 0, abort_rebase = 0, continue_rebase = 0;
9965 int histedit_in_progress = 0, merge_in_progress = 0;
9966 int create_backup = 1, list_backups = 0, delete_backups = 0;
9967 struct got_object_id_queue commits;
9968 struct got_pathlist_head merged_paths;
9969 const struct got_object_id_queue *parent_ids;
9970 struct got_object_qid *qid, *pid;
9971 struct got_update_progress_arg upa;
9972 int *pack_fds = NULL;
9974 STAILQ_INIT(&commits);
9975 TAILQ_INIT(&merged_paths);
9976 memset(&upa, 0, sizeof(upa));
9978 while ((ch = getopt(argc, argv, "aclX")) != -1) {
9979 switch (ch) {
9980 case 'a':
9981 abort_rebase = 1;
9982 break;
9983 case 'c':
9984 continue_rebase = 1;
9985 break;
9986 case 'l':
9987 list_backups = 1;
9988 break;
9989 case 'X':
9990 delete_backups = 1;
9991 break;
9992 default:
9993 usage_rebase();
9994 /* NOTREACHED */
9998 argc -= optind;
9999 argv += optind;
10001 #ifndef PROFILE
10002 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
10003 "unveil", NULL) == -1)
10004 err(1, "pledge");
10005 #endif
10006 if (list_backups) {
10007 if (abort_rebase)
10008 option_conflict('l', 'a');
10009 if (continue_rebase)
10010 option_conflict('l', 'c');
10011 if (delete_backups)
10012 option_conflict('l', 'X');
10013 if (argc != 0 && argc != 1)
10014 usage_rebase();
10015 } else if (delete_backups) {
10016 if (abort_rebase)
10017 option_conflict('X', 'a');
10018 if (continue_rebase)
10019 option_conflict('X', 'c');
10020 if (list_backups)
10021 option_conflict('l', 'X');
10022 if (argc != 0 && argc != 1)
10023 usage_rebase();
10024 } else {
10025 if (abort_rebase && continue_rebase)
10026 usage_rebase();
10027 else if (abort_rebase || continue_rebase) {
10028 if (argc != 0)
10029 usage_rebase();
10030 } else if (argc != 1)
10031 usage_rebase();
10034 cwd = getcwd(NULL, 0);
10035 if (cwd == NULL) {
10036 error = got_error_from_errno("getcwd");
10037 goto done;
10040 error = got_repo_pack_fds_open(&pack_fds);
10041 if (error != NULL)
10042 goto done;
10044 error = got_worktree_open(&worktree, cwd);
10045 if (error) {
10046 if (list_backups || delete_backups) {
10047 if (error->code != GOT_ERR_NOT_WORKTREE)
10048 goto done;
10049 } else {
10050 if (error->code == GOT_ERR_NOT_WORKTREE)
10051 error = wrap_not_worktree_error(error,
10052 "rebase", cwd);
10053 goto done;
10057 error = got_repo_open(&repo,
10058 worktree ? got_worktree_get_repo_path(worktree) : cwd, NULL,
10059 pack_fds);
10060 if (error != NULL)
10061 goto done;
10063 error = apply_unveil(got_repo_get_path(repo), 0,
10064 worktree ? got_worktree_get_root_path(worktree) : NULL);
10065 if (error)
10066 goto done;
10068 if (list_backups || delete_backups) {
10069 error = process_backup_refs(
10070 GOT_WORKTREE_REBASE_BACKUP_REF_PREFIX,
10071 argc == 1 ? argv[0] : NULL, delete_backups, repo);
10072 goto done; /* nothing else to do */
10075 error = got_worktree_histedit_in_progress(&histedit_in_progress,
10076 worktree);
10077 if (error)
10078 goto done;
10079 if (histedit_in_progress) {
10080 error = got_error(GOT_ERR_HISTEDIT_BUSY);
10081 goto done;
10084 error = got_worktree_merge_in_progress(&merge_in_progress,
10085 worktree, repo);
10086 if (error)
10087 goto done;
10088 if (merge_in_progress) {
10089 error = got_error(GOT_ERR_MERGE_BUSY);
10090 goto done;
10093 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
10094 if (error)
10095 goto done;
10097 if (abort_rebase) {
10098 if (!rebase_in_progress) {
10099 error = got_error(GOT_ERR_NOT_REBASING);
10100 goto done;
10102 error = got_worktree_rebase_continue(&resume_commit_id,
10103 &new_base_branch, &tmp_branch, &branch, &fileindex,
10104 worktree, repo);
10105 if (error)
10106 goto done;
10107 printf("Switching work tree to %s\n",
10108 got_ref_get_symref_target(new_base_branch));
10109 error = got_worktree_rebase_abort(worktree, fileindex, repo,
10110 new_base_branch, abort_progress, &upa);
10111 if (error)
10112 goto done;
10113 printf("Rebase of %s aborted\n", got_ref_get_name(branch));
10114 print_merge_progress_stats(&upa);
10115 goto done; /* nothing else to do */
10118 if (continue_rebase) {
10119 if (!rebase_in_progress) {
10120 error = got_error(GOT_ERR_NOT_REBASING);
10121 goto done;
10123 error = got_worktree_rebase_continue(&resume_commit_id,
10124 &new_base_branch, &tmp_branch, &branch, &fileindex,
10125 worktree, repo);
10126 if (error)
10127 goto done;
10129 error = rebase_commit(NULL, worktree, fileindex, tmp_branch,
10130 resume_commit_id, repo);
10131 if (error)
10132 goto done;
10134 yca_id = got_object_id_dup(resume_commit_id);
10135 if (yca_id == NULL) {
10136 error = got_error_from_errno("got_object_id_dup");
10137 goto done;
10139 } else {
10140 error = got_ref_open(&branch, repo, argv[0], 0);
10141 if (error != NULL)
10142 goto done;
10145 error = got_ref_resolve(&branch_head_commit_id, repo, branch);
10146 if (error)
10147 goto done;
10149 if (!continue_rebase) {
10150 struct got_object_id *base_commit_id;
10152 base_commit_id = got_worktree_get_base_commit_id(worktree);
10153 error = got_commit_graph_find_youngest_common_ancestor(&yca_id,
10154 base_commit_id, branch_head_commit_id, 1, repo,
10155 check_cancelled, NULL);
10156 if (error)
10157 goto done;
10158 if (yca_id == NULL) {
10159 error = got_error_msg(GOT_ERR_ANCESTRY,
10160 "specified branch shares no common ancestry "
10161 "with work tree's branch");
10162 goto done;
10165 error = check_same_branch(base_commit_id, branch, yca_id, repo);
10166 if (error) {
10167 if (error->code != GOT_ERR_ANCESTRY)
10168 goto done;
10169 error = NULL;
10170 } else {
10171 struct got_pathlist_head paths;
10172 printf("%s is already based on %s\n",
10173 got_ref_get_name(branch),
10174 got_worktree_get_head_ref_name(worktree));
10175 error = switch_head_ref(branch, branch_head_commit_id,
10176 worktree, repo);
10177 if (error)
10178 goto done;
10179 error = got_worktree_set_base_commit_id(worktree, repo,
10180 branch_head_commit_id);
10181 if (error)
10182 goto done;
10183 TAILQ_INIT(&paths);
10184 error = got_pathlist_append(&paths, "", NULL);
10185 if (error)
10186 goto done;
10187 error = got_worktree_checkout_files(worktree,
10188 &paths, repo, update_progress, &upa,
10189 check_cancelled, NULL);
10190 got_pathlist_free(&paths);
10191 if (error)
10192 goto done;
10193 if (upa.did_something) {
10194 char *id_str;
10195 error = got_object_id_str(&id_str,
10196 branch_head_commit_id);
10197 if (error)
10198 goto done;
10199 printf("Updated to %s: %s\n",
10200 got_worktree_get_head_ref_name(worktree),
10201 id_str);
10202 free(id_str);
10203 } else
10204 printf("Already up-to-date\n");
10205 print_update_progress_stats(&upa);
10206 goto done;
10210 commit_id = branch_head_commit_id;
10211 error = got_object_open_as_commit(&commit, repo, commit_id);
10212 if (error)
10213 goto done;
10215 parent_ids = got_object_commit_get_parent_ids(commit);
10216 pid = STAILQ_FIRST(parent_ids);
10217 if (pid == NULL) {
10218 error = got_error(GOT_ERR_EMPTY_REBASE);
10219 goto done;
10221 error = collect_commits(&commits, commit_id, &pid->id,
10222 yca_id, got_worktree_get_path_prefix(worktree),
10223 GOT_ERR_REBASE_PATH, repo);
10224 got_object_commit_close(commit);
10225 commit = NULL;
10226 if (error)
10227 goto done;
10229 if (!continue_rebase) {
10230 error = got_worktree_rebase_prepare(&new_base_branch,
10231 &tmp_branch, &fileindex, worktree, branch, repo);
10232 if (error)
10233 goto done;
10236 if (STAILQ_EMPTY(&commits)) {
10237 if (continue_rebase) {
10238 error = rebase_complete(worktree, fileindex,
10239 branch, new_base_branch, tmp_branch, repo,
10240 create_backup);
10241 goto done;
10242 } else {
10243 /* Fast-forward the reference of the branch. */
10244 struct got_object_id *new_head_commit_id;
10245 char *id_str;
10246 error = got_ref_resolve(&new_head_commit_id, repo,
10247 new_base_branch);
10248 if (error)
10249 goto done;
10250 error = got_object_id_str(&id_str, new_head_commit_id);
10251 printf("Forwarding %s to commit %s\n",
10252 got_ref_get_name(branch), id_str);
10253 free(id_str);
10254 error = got_ref_change_ref(branch,
10255 new_head_commit_id);
10256 if (error)
10257 goto done;
10258 /* No backup needed since objects did not change. */
10259 create_backup = 0;
10263 pid = NULL;
10264 STAILQ_FOREACH(qid, &commits, entry) {
10266 commit_id = &qid->id;
10267 parent_id = pid ? &pid->id : yca_id;
10268 pid = qid;
10270 memset(&upa, 0, sizeof(upa));
10271 error = got_worktree_rebase_merge_files(&merged_paths,
10272 worktree, fileindex, parent_id, commit_id, repo,
10273 update_progress, &upa, check_cancelled, NULL);
10274 if (error)
10275 goto done;
10277 print_merge_progress_stats(&upa);
10278 if (upa.conflicts > 0 || upa.missing > 0 ||
10279 upa.not_deleted > 0 || upa.unversioned > 0) {
10280 if (upa.conflicts > 0) {
10281 error = show_rebase_merge_conflict(&qid->id,
10282 repo);
10283 if (error)
10284 goto done;
10286 got_worktree_rebase_pathlist_free(&merged_paths);
10287 break;
10290 error = rebase_commit(&merged_paths, worktree, fileindex,
10291 tmp_branch, commit_id, repo);
10292 got_worktree_rebase_pathlist_free(&merged_paths);
10293 if (error)
10294 goto done;
10297 if (upa.conflicts > 0 || upa.missing > 0 ||
10298 upa.not_deleted > 0 || upa.unversioned > 0) {
10299 error = got_worktree_rebase_postpone(worktree, fileindex);
10300 if (error)
10301 goto done;
10302 if (upa.conflicts > 0 && upa.missing == 0 &&
10303 upa.not_deleted == 0 && upa.unversioned == 0) {
10304 error = got_error_msg(GOT_ERR_CONFLICTS,
10305 "conflicts must be resolved before rebasing "
10306 "can continue");
10307 } else if (upa.conflicts > 0) {
10308 error = got_error_msg(GOT_ERR_CONFLICTS,
10309 "conflicts must be resolved before rebasing "
10310 "can continue; changes destined for some "
10311 "files were not yet merged and should be "
10312 "merged manually if required before the "
10313 "rebase operation is continued");
10314 } else {
10315 error = got_error_msg(GOT_ERR_CONFLICTS,
10316 "changes destined for some files were not "
10317 "yet merged and should be merged manually "
10318 "if required before the rebase operation "
10319 "is continued");
10321 } else
10322 error = rebase_complete(worktree, fileindex, branch,
10323 new_base_branch, tmp_branch, repo, create_backup);
10324 done:
10325 got_object_id_queue_free(&commits);
10326 free(branch_head_commit_id);
10327 free(resume_commit_id);
10328 free(yca_id);
10329 if (commit)
10330 got_object_commit_close(commit);
10331 if (branch)
10332 got_ref_close(branch);
10333 if (new_base_branch)
10334 got_ref_close(new_base_branch);
10335 if (tmp_branch)
10336 got_ref_close(tmp_branch);
10337 if (worktree)
10338 got_worktree_close(worktree);
10339 if (repo) {
10340 const struct got_error *close_err = got_repo_close(repo);
10341 if (error == NULL)
10342 error = close_err;
10344 if (pack_fds) {
10345 const struct got_error *pack_err =
10346 got_repo_pack_fds_close(pack_fds);
10347 if (error == NULL)
10348 error = pack_err;
10350 return error;
10353 __dead static void
10354 usage_histedit(void)
10356 fprintf(stderr, "usage: %s histedit [-a] [-c] [-e] [-f] "
10357 "[-F histedit-script] [-m] [-l] [-X] [branch]\n",
10358 getprogname());
10359 exit(1);
10362 #define GOT_HISTEDIT_PICK 'p'
10363 #define GOT_HISTEDIT_EDIT 'e'
10364 #define GOT_HISTEDIT_FOLD 'f'
10365 #define GOT_HISTEDIT_DROP 'd'
10366 #define GOT_HISTEDIT_MESG 'm'
10368 static const struct got_histedit_cmd {
10369 unsigned char code;
10370 const char *name;
10371 const char *desc;
10372 } got_histedit_cmds[] = {
10373 { GOT_HISTEDIT_PICK, "pick", "use commit" },
10374 { GOT_HISTEDIT_EDIT, "edit", "use commit but stop for amending" },
10375 { GOT_HISTEDIT_FOLD, "fold", "combine with next commit that will "
10376 "be used" },
10377 { GOT_HISTEDIT_DROP, "drop", "remove commit from history" },
10378 { GOT_HISTEDIT_MESG, "mesg",
10379 "single-line log message for commit above (open editor if empty)" },
10382 struct got_histedit_list_entry {
10383 TAILQ_ENTRY(got_histedit_list_entry) entry;
10384 struct got_object_id *commit_id;
10385 const struct got_histedit_cmd *cmd;
10386 char *logmsg;
10388 TAILQ_HEAD(got_histedit_list, got_histedit_list_entry);
10390 static const struct got_error *
10391 histedit_write_commit(struct got_object_id *commit_id, const char *cmdname,
10392 FILE *f, struct got_repository *repo)
10394 const struct got_error *err = NULL;
10395 char *logmsg = NULL, *id_str = NULL;
10396 struct got_commit_object *commit = NULL;
10397 int n;
10399 err = got_object_open_as_commit(&commit, repo, commit_id);
10400 if (err)
10401 goto done;
10403 err = get_short_logmsg(&logmsg, 34, commit);
10404 if (err)
10405 goto done;
10407 err = got_object_id_str(&id_str, commit_id);
10408 if (err)
10409 goto done;
10411 n = fprintf(f, "%s %s %s\n", cmdname, id_str, logmsg);
10412 if (n < 0)
10413 err = got_ferror(f, GOT_ERR_IO);
10414 done:
10415 if (commit)
10416 got_object_commit_close(commit);
10417 free(id_str);
10418 free(logmsg);
10419 return err;
10422 static const struct got_error *
10423 histedit_write_commit_list(struct got_object_id_queue *commits,
10424 FILE *f, int edit_logmsg_only, int fold_only, int edit_only,
10425 struct got_repository *repo)
10427 const struct got_error *err = NULL;
10428 struct got_object_qid *qid;
10429 const char *histedit_cmd = NULL;
10431 if (STAILQ_EMPTY(commits))
10432 return got_error(GOT_ERR_EMPTY_HISTEDIT);
10434 STAILQ_FOREACH(qid, commits, entry) {
10435 histedit_cmd = got_histedit_cmds[0].name;
10436 if (edit_only)
10437 histedit_cmd = "edit";
10438 else if (fold_only && STAILQ_NEXT(qid, entry) != NULL)
10439 histedit_cmd = "fold";
10440 err = histedit_write_commit(&qid->id, histedit_cmd, f, repo);
10441 if (err)
10442 break;
10443 if (edit_logmsg_only) {
10444 int n = fprintf(f, "%c\n", GOT_HISTEDIT_MESG);
10445 if (n < 0) {
10446 err = got_ferror(f, GOT_ERR_IO);
10447 break;
10452 return err;
10455 static const struct got_error *
10456 write_cmd_list(FILE *f, const char *branch_name,
10457 struct got_object_id_queue *commits)
10459 const struct got_error *err = NULL;
10460 size_t i;
10461 int n;
10462 char *id_str;
10463 struct got_object_qid *qid;
10465 qid = STAILQ_FIRST(commits);
10466 err = got_object_id_str(&id_str, &qid->id);
10467 if (err)
10468 return err;
10470 n = fprintf(f,
10471 "# Editing the history of branch '%s' starting at\n"
10472 "# commit %s\n"
10473 "# Commits will be processed in order from top to "
10474 "bottom of this file.\n", branch_name, id_str);
10475 if (n < 0) {
10476 err = got_ferror(f, GOT_ERR_IO);
10477 goto done;
10480 n = fprintf(f, "# Available histedit commands:\n");
10481 if (n < 0) {
10482 err = got_ferror(f, GOT_ERR_IO);
10483 goto done;
10486 for (i = 0; i < nitems(got_histedit_cmds); i++) {
10487 const struct got_histedit_cmd *cmd = &got_histedit_cmds[i];
10488 n = fprintf(f, "# %s (%c): %s\n", cmd->name, cmd->code,
10489 cmd->desc);
10490 if (n < 0) {
10491 err = got_ferror(f, GOT_ERR_IO);
10492 break;
10495 done:
10496 free(id_str);
10497 return err;
10500 static const struct got_error *
10501 histedit_syntax_error(int lineno)
10503 static char msg[42];
10504 int ret;
10506 ret = snprintf(msg, sizeof(msg), "histedit syntax error on line %d",
10507 lineno);
10508 if (ret == -1 || ret >= sizeof(msg))
10509 return got_error(GOT_ERR_HISTEDIT_SYNTAX);
10511 return got_error_msg(GOT_ERR_HISTEDIT_SYNTAX, msg);
10514 static const struct got_error *
10515 append_folded_commit_msg(char **new_msg, struct got_histedit_list_entry *hle,
10516 char *logmsg, struct got_repository *repo)
10518 const struct got_error *err;
10519 struct got_commit_object *folded_commit = NULL;
10520 char *id_str, *folded_logmsg = NULL;
10522 err = got_object_id_str(&id_str, hle->commit_id);
10523 if (err)
10524 return err;
10526 err = got_object_open_as_commit(&folded_commit, repo, hle->commit_id);
10527 if (err)
10528 goto done;
10530 err = got_object_commit_get_logmsg(&folded_logmsg, folded_commit);
10531 if (err)
10532 goto done;
10533 if (asprintf(new_msg, "%s%s# log message of folded commit %s: %s",
10534 logmsg ? logmsg : "", logmsg ? "\n" : "", id_str,
10535 folded_logmsg) == -1) {
10536 err = got_error_from_errno("asprintf");
10538 done:
10539 if (folded_commit)
10540 got_object_commit_close(folded_commit);
10541 free(id_str);
10542 free(folded_logmsg);
10543 return err;
10546 static struct got_histedit_list_entry *
10547 get_folded_commits(struct got_histedit_list_entry *hle)
10549 struct got_histedit_list_entry *prev, *folded = NULL;
10551 prev = TAILQ_PREV(hle, got_histedit_list, entry);
10552 while (prev && (prev->cmd->code == GOT_HISTEDIT_FOLD ||
10553 prev->cmd->code == GOT_HISTEDIT_DROP)) {
10554 if (prev->cmd->code == GOT_HISTEDIT_FOLD)
10555 folded = prev;
10556 prev = TAILQ_PREV(prev, got_histedit_list, entry);
10559 return folded;
10562 static const struct got_error *
10563 histedit_edit_logmsg(struct got_histedit_list_entry *hle,
10564 struct got_repository *repo)
10566 char *logmsg_path = NULL, *id_str = NULL, *orig_logmsg = NULL;
10567 char *logmsg = NULL, *new_msg = NULL, *editor = NULL;
10568 const struct got_error *err = NULL;
10569 struct got_commit_object *commit = NULL;
10570 int logmsg_len;
10571 int fd;
10572 struct got_histedit_list_entry *folded = NULL;
10574 err = got_object_open_as_commit(&commit, repo, hle->commit_id);
10575 if (err)
10576 return err;
10578 folded = get_folded_commits(hle);
10579 if (folded) {
10580 while (folded != hle) {
10581 if (folded->cmd->code == GOT_HISTEDIT_DROP) {
10582 folded = TAILQ_NEXT(folded, entry);
10583 continue;
10585 err = append_folded_commit_msg(&new_msg, folded,
10586 logmsg, repo);
10587 if (err)
10588 goto done;
10589 free(logmsg);
10590 logmsg = new_msg;
10591 folded = TAILQ_NEXT(folded, entry);
10595 err = got_object_id_str(&id_str, hle->commit_id);
10596 if (err)
10597 goto done;
10598 err = got_object_commit_get_logmsg(&orig_logmsg, commit);
10599 if (err)
10600 goto done;
10601 logmsg_len = asprintf(&new_msg,
10602 "%s\n# original log message of commit %s: %s",
10603 logmsg ? logmsg : "", id_str, orig_logmsg);
10604 if (logmsg_len == -1) {
10605 err = got_error_from_errno("asprintf");
10606 goto done;
10608 free(logmsg);
10609 logmsg = new_msg;
10611 err = got_object_id_str(&id_str, hle->commit_id);
10612 if (err)
10613 goto done;
10615 err = got_opentemp_named_fd(&logmsg_path, &fd,
10616 GOT_TMPDIR_STR "/got-logmsg");
10617 if (err)
10618 goto done;
10620 write(fd, logmsg, logmsg_len);
10621 close(fd);
10623 err = get_editor(&editor);
10624 if (err)
10625 goto done;
10627 err = edit_logmsg(&hle->logmsg, editor, logmsg_path, logmsg,
10628 logmsg_len, 0);
10629 if (err) {
10630 if (err->code != GOT_ERR_COMMIT_MSG_EMPTY)
10631 goto done;
10632 err = NULL;
10633 hle->logmsg = strdup(new_msg);
10634 if (hle->logmsg == NULL)
10635 err = got_error_from_errno("strdup");
10637 done:
10638 if (logmsg_path && unlink(logmsg_path) != 0 && err == NULL)
10639 err = got_error_from_errno2("unlink", logmsg_path);
10640 free(logmsg_path);
10641 free(logmsg);
10642 free(orig_logmsg);
10643 free(editor);
10644 if (commit)
10645 got_object_commit_close(commit);
10646 return err;
10649 static const struct got_error *
10650 histedit_parse_list(struct got_histedit_list *histedit_cmds,
10651 FILE *f, struct got_repository *repo)
10653 const struct got_error *err = NULL;
10654 char *line = NULL, *p, *end;
10655 size_t i, size;
10656 ssize_t len;
10657 int lineno = 0;
10658 const struct got_histedit_cmd *cmd;
10659 struct got_object_id *commit_id = NULL;
10660 struct got_histedit_list_entry *hle = NULL;
10662 for (;;) {
10663 len = getline(&line, &size, f);
10664 if (len == -1) {
10665 const struct got_error *getline_err;
10666 if (feof(f))
10667 break;
10668 getline_err = got_error_from_errno("getline");
10669 err = got_ferror(f, getline_err->code);
10670 break;
10672 lineno++;
10673 p = line;
10674 while (isspace((unsigned char)p[0]))
10675 p++;
10676 if (p[0] == '#' || p[0] == '\0') {
10677 free(line);
10678 line = NULL;
10679 continue;
10681 cmd = NULL;
10682 for (i = 0; i < nitems(got_histedit_cmds); i++) {
10683 cmd = &got_histedit_cmds[i];
10684 if (strncmp(cmd->name, p, strlen(cmd->name)) == 0 &&
10685 isspace((unsigned char)p[strlen(cmd->name)])) {
10686 p += strlen(cmd->name);
10687 break;
10689 if (p[0] == cmd->code && isspace((unsigned char)p[1])) {
10690 p++;
10691 break;
10694 if (i == nitems(got_histedit_cmds)) {
10695 err = histedit_syntax_error(lineno);
10696 break;
10698 while (isspace((unsigned char)p[0]))
10699 p++;
10700 if (cmd->code == GOT_HISTEDIT_MESG) {
10701 if (hle == NULL || hle->logmsg != NULL) {
10702 err = got_error(GOT_ERR_HISTEDIT_CMD);
10703 break;
10705 if (p[0] == '\0') {
10706 err = histedit_edit_logmsg(hle, repo);
10707 if (err)
10708 break;
10709 } else {
10710 hle->logmsg = strdup(p);
10711 if (hle->logmsg == NULL) {
10712 err = got_error_from_errno("strdup");
10713 break;
10716 free(line);
10717 line = NULL;
10718 continue;
10719 } else {
10720 end = p;
10721 while (end[0] && !isspace((unsigned char)end[0]))
10722 end++;
10723 *end = '\0';
10725 err = got_object_resolve_id_str(&commit_id, repo, p);
10726 if (err) {
10727 /* override error code */
10728 err = histedit_syntax_error(lineno);
10729 break;
10732 hle = malloc(sizeof(*hle));
10733 if (hle == NULL) {
10734 err = got_error_from_errno("malloc");
10735 break;
10737 hle->cmd = cmd;
10738 hle->commit_id = commit_id;
10739 hle->logmsg = NULL;
10740 commit_id = NULL;
10741 free(line);
10742 line = NULL;
10743 TAILQ_INSERT_TAIL(histedit_cmds, hle, entry);
10746 free(line);
10747 free(commit_id);
10748 return err;
10751 static const struct got_error *
10752 histedit_check_script(struct got_histedit_list *histedit_cmds,
10753 struct got_object_id_queue *commits, struct got_repository *repo)
10755 const struct got_error *err = NULL;
10756 struct got_object_qid *qid;
10757 struct got_histedit_list_entry *hle;
10758 static char msg[92];
10759 char *id_str;
10761 if (TAILQ_EMPTY(histedit_cmds))
10762 return got_error_msg(GOT_ERR_EMPTY_HISTEDIT,
10763 "histedit script contains no commands");
10764 if (STAILQ_EMPTY(commits))
10765 return got_error(GOT_ERR_EMPTY_HISTEDIT);
10767 TAILQ_FOREACH(hle, histedit_cmds, entry) {
10768 struct got_histedit_list_entry *hle2;
10769 TAILQ_FOREACH(hle2, histedit_cmds, entry) {
10770 if (hle == hle2)
10771 continue;
10772 if (got_object_id_cmp(hle->commit_id,
10773 hle2->commit_id) != 0)
10774 continue;
10775 err = got_object_id_str(&id_str, hle->commit_id);
10776 if (err)
10777 return err;
10778 snprintf(msg, sizeof(msg), "commit %s is listed "
10779 "more than once in histedit script", id_str);
10780 free(id_str);
10781 return got_error_msg(GOT_ERR_HISTEDIT_CMD, msg);
10785 STAILQ_FOREACH(qid, commits, entry) {
10786 TAILQ_FOREACH(hle, histedit_cmds, entry) {
10787 if (got_object_id_cmp(&qid->id, hle->commit_id) == 0)
10788 break;
10790 if (hle == NULL) {
10791 err = got_object_id_str(&id_str, &qid->id);
10792 if (err)
10793 return err;
10794 snprintf(msg, sizeof(msg),
10795 "commit %s missing from histedit script", id_str);
10796 free(id_str);
10797 return got_error_msg(GOT_ERR_HISTEDIT_CMD, msg);
10801 hle = TAILQ_LAST(histedit_cmds, got_histedit_list);
10802 if (hle && hle->cmd->code == GOT_HISTEDIT_FOLD)
10803 return got_error_msg(GOT_ERR_HISTEDIT_CMD,
10804 "last commit in histedit script cannot be folded");
10806 return NULL;
10809 static const struct got_error *
10810 histedit_run_editor(struct got_histedit_list *histedit_cmds,
10811 const char *path, struct got_object_id_queue *commits,
10812 struct got_repository *repo)
10814 const struct got_error *err = NULL;
10815 char *editor;
10816 FILE *f = NULL;
10818 err = get_editor(&editor);
10819 if (err)
10820 return err;
10822 if (spawn_editor(editor, path) == -1) {
10823 err = got_error_from_errno("failed spawning editor");
10824 goto done;
10827 f = fopen(path, "re");
10828 if (f == NULL) {
10829 err = got_error_from_errno("fopen");
10830 goto done;
10832 err = histedit_parse_list(histedit_cmds, f, repo);
10833 if (err)
10834 goto done;
10836 err = histedit_check_script(histedit_cmds, commits, repo);
10837 done:
10838 if (f && fclose(f) == EOF && err == NULL)
10839 err = got_error_from_errno("fclose");
10840 free(editor);
10841 return err;
10844 static const struct got_error *
10845 histedit_edit_list_retry(struct got_histedit_list *, const struct got_error *,
10846 struct got_object_id_queue *, const char *, const char *,
10847 struct got_repository *);
10849 static const struct got_error *
10850 histedit_edit_script(struct got_histedit_list *histedit_cmds,
10851 struct got_object_id_queue *commits, const char *branch_name,
10852 int edit_logmsg_only, int fold_only, int edit_only,
10853 struct got_repository *repo)
10855 const struct got_error *err;
10856 FILE *f = NULL;
10857 char *path = NULL;
10859 err = got_opentemp_named(&path, &f, "got-histedit");
10860 if (err)
10861 return err;
10863 err = write_cmd_list(f, branch_name, commits);
10864 if (err)
10865 goto done;
10867 err = histedit_write_commit_list(commits, f, edit_logmsg_only,
10868 fold_only, edit_only, repo);
10869 if (err)
10870 goto done;
10872 if (edit_logmsg_only || fold_only || edit_only) {
10873 rewind(f);
10874 err = histedit_parse_list(histedit_cmds, f, repo);
10875 } else {
10876 if (fclose(f) == EOF) {
10877 err = got_error_from_errno("fclose");
10878 goto done;
10880 f = NULL;
10881 err = histedit_run_editor(histedit_cmds, path, commits, repo);
10882 if (err) {
10883 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
10884 err->code != GOT_ERR_HISTEDIT_CMD)
10885 goto done;
10886 err = histedit_edit_list_retry(histedit_cmds, err,
10887 commits, path, branch_name, repo);
10890 done:
10891 if (f && fclose(f) == EOF && err == NULL)
10892 err = got_error_from_errno("fclose");
10893 if (path && unlink(path) != 0 && err == NULL)
10894 err = got_error_from_errno2("unlink", path);
10895 free(path);
10896 return err;
10899 static const struct got_error *
10900 histedit_save_list(struct got_histedit_list *histedit_cmds,
10901 struct got_worktree *worktree, struct got_repository *repo)
10903 const struct got_error *err = NULL;
10904 char *path = NULL;
10905 FILE *f = NULL;
10906 struct got_histedit_list_entry *hle;
10907 struct got_commit_object *commit = NULL;
10909 err = got_worktree_get_histedit_script_path(&path, worktree);
10910 if (err)
10911 return err;
10913 f = fopen(path, "we");
10914 if (f == NULL) {
10915 err = got_error_from_errno2("fopen", path);
10916 goto done;
10918 TAILQ_FOREACH(hle, histedit_cmds, entry) {
10919 err = histedit_write_commit(hle->commit_id, hle->cmd->name, f,
10920 repo);
10921 if (err)
10922 break;
10924 if (hle->logmsg) {
10925 int n = fprintf(f, "%c %s\n",
10926 GOT_HISTEDIT_MESG, hle->logmsg);
10927 if (n < 0) {
10928 err = got_ferror(f, GOT_ERR_IO);
10929 break;
10933 done:
10934 if (f && fclose(f) == EOF && err == NULL)
10935 err = got_error_from_errno("fclose");
10936 free(path);
10937 if (commit)
10938 got_object_commit_close(commit);
10939 return err;
10942 static void
10943 histedit_free_list(struct got_histedit_list *histedit_cmds)
10945 struct got_histedit_list_entry *hle;
10947 while ((hle = TAILQ_FIRST(histedit_cmds))) {
10948 TAILQ_REMOVE(histedit_cmds, hle, entry);
10949 free(hle);
10953 static const struct got_error *
10954 histedit_load_list(struct got_histedit_list *histedit_cmds,
10955 const char *path, struct got_repository *repo)
10957 const struct got_error *err = NULL;
10958 FILE *f = NULL;
10960 f = fopen(path, "re");
10961 if (f == NULL) {
10962 err = got_error_from_errno2("fopen", path);
10963 goto done;
10966 err = histedit_parse_list(histedit_cmds, f, repo);
10967 done:
10968 if (f && fclose(f) == EOF && err == NULL)
10969 err = got_error_from_errno("fclose");
10970 return err;
10973 static const struct got_error *
10974 histedit_edit_list_retry(struct got_histedit_list *histedit_cmds,
10975 const struct got_error *edit_err, struct got_object_id_queue *commits,
10976 const char *path, const char *branch_name, struct got_repository *repo)
10978 const struct got_error *err = NULL, *prev_err = edit_err;
10979 int resp = ' ';
10981 while (resp != 'c' && resp != 'r' && resp != 'a') {
10982 printf("%s: %s\n(c)ontinue editing, (r)estart editing, "
10983 "or (a)bort: ", getprogname(), prev_err->msg);
10984 resp = getchar();
10985 if (resp == '\n')
10986 resp = getchar();
10987 if (resp == 'c') {
10988 histedit_free_list(histedit_cmds);
10989 err = histedit_run_editor(histedit_cmds, path, commits,
10990 repo);
10991 if (err) {
10992 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
10993 err->code != GOT_ERR_HISTEDIT_CMD)
10994 break;
10995 prev_err = err;
10996 resp = ' ';
10997 continue;
10999 break;
11000 } else if (resp == 'r') {
11001 histedit_free_list(histedit_cmds);
11002 err = histedit_edit_script(histedit_cmds,
11003 commits, branch_name, 0, 0, 0, repo);
11004 if (err) {
11005 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
11006 err->code != GOT_ERR_HISTEDIT_CMD)
11007 break;
11008 prev_err = err;
11009 resp = ' ';
11010 continue;
11012 break;
11013 } else if (resp == 'a') {
11014 err = got_error(GOT_ERR_HISTEDIT_CANCEL);
11015 break;
11016 } else
11017 printf("invalid response '%c'\n", resp);
11020 return err;
11023 static const struct got_error *
11024 histedit_complete(struct got_worktree *worktree,
11025 struct got_fileindex *fileindex, struct got_reference *tmp_branch,
11026 struct got_reference *branch, struct got_repository *repo)
11028 printf("Switching work tree to %s\n",
11029 got_ref_get_symref_target(branch));
11030 return got_worktree_histedit_complete(worktree, fileindex, tmp_branch,
11031 branch, repo);
11034 static const struct got_error *
11035 show_histedit_progress(struct got_commit_object *commit,
11036 struct got_histedit_list_entry *hle, struct got_object_id *new_id)
11038 const struct got_error *err;
11039 char *old_id_str = NULL, *new_id_str = NULL, *logmsg = NULL;
11041 err = got_object_id_str(&old_id_str, hle->commit_id);
11042 if (err)
11043 goto done;
11045 if (new_id) {
11046 err = got_object_id_str(&new_id_str, new_id);
11047 if (err)
11048 goto done;
11051 old_id_str[12] = '\0';
11052 if (new_id_str)
11053 new_id_str[12] = '\0';
11055 if (hle->logmsg) {
11056 logmsg = strdup(hle->logmsg);
11057 if (logmsg == NULL) {
11058 err = got_error_from_errno("strdup");
11059 goto done;
11061 trim_logmsg(logmsg, 42);
11062 } else {
11063 err = get_short_logmsg(&logmsg, 42, commit);
11064 if (err)
11065 goto done;
11068 switch (hle->cmd->code) {
11069 case GOT_HISTEDIT_PICK:
11070 case GOT_HISTEDIT_EDIT:
11071 printf("%s -> %s: %s\n", old_id_str,
11072 new_id_str ? new_id_str : "no-op change", logmsg);
11073 break;
11074 case GOT_HISTEDIT_DROP:
11075 case GOT_HISTEDIT_FOLD:
11076 printf("%s -> %s commit: %s\n", old_id_str, hle->cmd->name,
11077 logmsg);
11078 break;
11079 default:
11080 break;
11082 done:
11083 free(old_id_str);
11084 free(new_id_str);
11085 return err;
11088 static const struct got_error *
11089 histedit_commit(struct got_pathlist_head *merged_paths,
11090 struct got_worktree *worktree, struct got_fileindex *fileindex,
11091 struct got_reference *tmp_branch, struct got_histedit_list_entry *hle,
11092 struct got_repository *repo)
11094 const struct got_error *err;
11095 struct got_commit_object *commit;
11096 struct got_object_id *new_commit_id;
11098 if ((hle->cmd->code == GOT_HISTEDIT_EDIT || get_folded_commits(hle))
11099 && hle->logmsg == NULL) {
11100 err = histedit_edit_logmsg(hle, repo);
11101 if (err)
11102 return err;
11105 err = got_object_open_as_commit(&commit, repo, hle->commit_id);
11106 if (err)
11107 return err;
11109 err = got_worktree_histedit_commit(&new_commit_id, merged_paths,
11110 worktree, fileindex, tmp_branch, commit, hle->commit_id,
11111 hle->logmsg, repo);
11112 if (err) {
11113 if (err->code != GOT_ERR_COMMIT_NO_CHANGES)
11114 goto done;
11115 err = show_histedit_progress(commit, hle, NULL);
11116 } else {
11117 err = show_histedit_progress(commit, hle, new_commit_id);
11118 free(new_commit_id);
11120 done:
11121 got_object_commit_close(commit);
11122 return err;
11125 static const struct got_error *
11126 histedit_skip_commit(struct got_histedit_list_entry *hle,
11127 struct got_worktree *worktree, struct got_repository *repo)
11129 const struct got_error *error;
11130 struct got_commit_object *commit;
11132 error = got_worktree_histedit_skip_commit(worktree, hle->commit_id,
11133 repo);
11134 if (error)
11135 return error;
11137 error = got_object_open_as_commit(&commit, repo, hle->commit_id);
11138 if (error)
11139 return error;
11141 error = show_histedit_progress(commit, hle, NULL);
11142 got_object_commit_close(commit);
11143 return error;
11146 static const struct got_error *
11147 check_local_changes(void *arg, unsigned char status,
11148 unsigned char staged_status, const char *path,
11149 struct got_object_id *blob_id, struct got_object_id *staged_blob_id,
11150 struct got_object_id *commit_id, int dirfd, const char *de_name)
11152 int *have_local_changes = arg;
11154 switch (status) {
11155 case GOT_STATUS_ADD:
11156 case GOT_STATUS_DELETE:
11157 case GOT_STATUS_MODIFY:
11158 case GOT_STATUS_CONFLICT:
11159 *have_local_changes = 1;
11160 return got_error(GOT_ERR_CANCELLED);
11161 default:
11162 break;
11165 switch (staged_status) {
11166 case GOT_STATUS_ADD:
11167 case GOT_STATUS_DELETE:
11168 case GOT_STATUS_MODIFY:
11169 *have_local_changes = 1;
11170 return got_error(GOT_ERR_CANCELLED);
11171 default:
11172 break;
11175 return NULL;
11178 static const struct got_error *
11179 cmd_histedit(int argc, char *argv[])
11181 const struct got_error *error = NULL;
11182 struct got_worktree *worktree = NULL;
11183 struct got_fileindex *fileindex = NULL;
11184 struct got_repository *repo = NULL;
11185 char *cwd = NULL;
11186 struct got_reference *branch = NULL;
11187 struct got_reference *tmp_branch = NULL;
11188 struct got_object_id *resume_commit_id = NULL;
11189 struct got_object_id *base_commit_id = NULL;
11190 struct got_object_id *head_commit_id = NULL;
11191 struct got_commit_object *commit = NULL;
11192 int ch, rebase_in_progress = 0, merge_in_progress = 0;
11193 struct got_update_progress_arg upa;
11194 int edit_in_progress = 0, abort_edit = 0, continue_edit = 0;
11195 int edit_logmsg_only = 0, fold_only = 0, edit_only = 0;
11196 int list_backups = 0, delete_backups = 0;
11197 const char *edit_script_path = NULL;
11198 struct got_object_id_queue commits;
11199 struct got_pathlist_head merged_paths;
11200 const struct got_object_id_queue *parent_ids;
11201 struct got_object_qid *pid;
11202 struct got_histedit_list histedit_cmds;
11203 struct got_histedit_list_entry *hle;
11204 int *pack_fds = NULL;
11206 STAILQ_INIT(&commits);
11207 TAILQ_INIT(&histedit_cmds);
11208 TAILQ_INIT(&merged_paths);
11209 memset(&upa, 0, sizeof(upa));
11211 while ((ch = getopt(argc, argv, "acefF:mlX")) != -1) {
11212 switch (ch) {
11213 case 'a':
11214 abort_edit = 1;
11215 break;
11216 case 'c':
11217 continue_edit = 1;
11218 break;
11219 case 'e':
11220 edit_only = 1;
11221 break;
11222 case 'f':
11223 fold_only = 1;
11224 break;
11225 case 'F':
11226 edit_script_path = optarg;
11227 break;
11228 case 'm':
11229 edit_logmsg_only = 1;
11230 break;
11231 case 'l':
11232 list_backups = 1;
11233 break;
11234 case 'X':
11235 delete_backups = 1;
11236 break;
11237 default:
11238 usage_histedit();
11239 /* NOTREACHED */
11243 argc -= optind;
11244 argv += optind;
11246 #ifndef PROFILE
11247 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
11248 "unveil", NULL) == -1)
11249 err(1, "pledge");
11250 #endif
11251 if (abort_edit && continue_edit)
11252 option_conflict('a', 'c');
11253 if (edit_script_path && edit_logmsg_only)
11254 option_conflict('F', 'm');
11255 if (abort_edit && edit_logmsg_only)
11256 option_conflict('a', 'm');
11257 if (continue_edit && edit_logmsg_only)
11258 option_conflict('c', 'm');
11259 if (abort_edit && fold_only)
11260 option_conflict('a', 'f');
11261 if (continue_edit && fold_only)
11262 option_conflict('c', 'f');
11263 if (fold_only && edit_logmsg_only)
11264 option_conflict('f', 'm');
11265 if (edit_script_path && fold_only)
11266 option_conflict('F', 'f');
11267 if (abort_edit && edit_only)
11268 option_conflict('a', 'e');
11269 if (continue_edit && edit_only)
11270 option_conflict('c', 'e');
11271 if (edit_only && edit_logmsg_only)
11272 option_conflict('e', 'm');
11273 if (edit_script_path && edit_only)
11274 option_conflict('F', 'e');
11275 if (list_backups) {
11276 if (abort_edit)
11277 option_conflict('l', 'a');
11278 if (continue_edit)
11279 option_conflict('l', 'c');
11280 if (edit_script_path)
11281 option_conflict('l', 'F');
11282 if (edit_logmsg_only)
11283 option_conflict('l', 'm');
11284 if (fold_only)
11285 option_conflict('l', 'f');
11286 if (edit_only)
11287 option_conflict('l', 'e');
11288 if (delete_backups)
11289 option_conflict('l', 'X');
11290 if (argc != 0 && argc != 1)
11291 usage_histedit();
11292 } else if (delete_backups) {
11293 if (abort_edit)
11294 option_conflict('X', 'a');
11295 if (continue_edit)
11296 option_conflict('X', 'c');
11297 if (edit_script_path)
11298 option_conflict('X', 'F');
11299 if (edit_logmsg_only)
11300 option_conflict('X', 'm');
11301 if (fold_only)
11302 option_conflict('X', 'f');
11303 if (edit_only)
11304 option_conflict('X', 'e');
11305 if (list_backups)
11306 option_conflict('X', 'l');
11307 if (argc != 0 && argc != 1)
11308 usage_histedit();
11309 } else if (argc != 0)
11310 usage_histedit();
11313 * This command cannot apply unveil(2) in all cases because the
11314 * user may choose to run an editor to edit the histedit script
11315 * and to edit individual commit log messages.
11316 * unveil(2) traverses exec(2); if an editor is used we have to
11317 * apply unveil after edit script and log messages have been written.
11318 * XXX TODO: Make use of unveil(2) where possible.
11321 cwd = getcwd(NULL, 0);
11322 if (cwd == NULL) {
11323 error = got_error_from_errno("getcwd");
11324 goto done;
11327 error = got_repo_pack_fds_open(&pack_fds);
11328 if (error != NULL)
11329 goto done;
11331 error = got_worktree_open(&worktree, cwd);
11332 if (error) {
11333 if (list_backups || delete_backups) {
11334 if (error->code != GOT_ERR_NOT_WORKTREE)
11335 goto done;
11336 } else {
11337 if (error->code == GOT_ERR_NOT_WORKTREE)
11338 error = wrap_not_worktree_error(error,
11339 "histedit", cwd);
11340 goto done;
11344 if (list_backups || delete_backups) {
11345 error = got_repo_open(&repo,
11346 worktree ? got_worktree_get_repo_path(worktree) : cwd,
11347 NULL, pack_fds);
11348 if (error != NULL)
11349 goto done;
11350 error = apply_unveil(got_repo_get_path(repo), 0,
11351 worktree ? got_worktree_get_root_path(worktree) : NULL);
11352 if (error)
11353 goto done;
11354 error = process_backup_refs(
11355 GOT_WORKTREE_HISTEDIT_BACKUP_REF_PREFIX,
11356 argc == 1 ? argv[0] : NULL, delete_backups, repo);
11357 goto done; /* nothing else to do */
11360 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
11361 NULL, pack_fds);
11362 if (error != NULL)
11363 goto done;
11365 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
11366 if (error)
11367 goto done;
11368 if (rebase_in_progress) {
11369 error = got_error(GOT_ERR_REBASING);
11370 goto done;
11373 error = got_worktree_merge_in_progress(&merge_in_progress, worktree,
11374 repo);
11375 if (error)
11376 goto done;
11377 if (merge_in_progress) {
11378 error = got_error(GOT_ERR_MERGE_BUSY);
11379 goto done;
11382 error = got_worktree_histedit_in_progress(&edit_in_progress, worktree);
11383 if (error)
11384 goto done;
11386 if (edit_in_progress && edit_logmsg_only) {
11387 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
11388 "histedit operation is in progress in this "
11389 "work tree and must be continued or aborted "
11390 "before the -m option can be used");
11391 goto done;
11393 if (edit_in_progress && fold_only) {
11394 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
11395 "histedit operation is in progress in this "
11396 "work tree and must be continued or aborted "
11397 "before the -f option can be used");
11398 goto done;
11400 if (edit_in_progress && edit_only) {
11401 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
11402 "histedit operation is in progress in this "
11403 "work tree and must be continued or aborted "
11404 "before the -e option can be used");
11405 goto done;
11408 if (edit_in_progress && abort_edit) {
11409 error = got_worktree_histedit_continue(&resume_commit_id,
11410 &tmp_branch, &branch, &base_commit_id, &fileindex,
11411 worktree, repo);
11412 if (error)
11413 goto done;
11414 printf("Switching work tree to %s\n",
11415 got_ref_get_symref_target(branch));
11416 error = got_worktree_histedit_abort(worktree, fileindex, repo,
11417 branch, base_commit_id, abort_progress, &upa);
11418 if (error)
11419 goto done;
11420 printf("Histedit of %s aborted\n",
11421 got_ref_get_symref_target(branch));
11422 print_merge_progress_stats(&upa);
11423 goto done; /* nothing else to do */
11424 } else if (abort_edit) {
11425 error = got_error(GOT_ERR_NOT_HISTEDIT);
11426 goto done;
11429 if (continue_edit) {
11430 char *path;
11432 if (!edit_in_progress) {
11433 error = got_error(GOT_ERR_NOT_HISTEDIT);
11434 goto done;
11437 error = got_worktree_get_histedit_script_path(&path, worktree);
11438 if (error)
11439 goto done;
11441 error = histedit_load_list(&histedit_cmds, path, repo);
11442 free(path);
11443 if (error)
11444 goto done;
11446 error = got_worktree_histedit_continue(&resume_commit_id,
11447 &tmp_branch, &branch, &base_commit_id, &fileindex,
11448 worktree, repo);
11449 if (error)
11450 goto done;
11452 error = got_ref_resolve(&head_commit_id, repo, branch);
11453 if (error)
11454 goto done;
11456 error = got_object_open_as_commit(&commit, repo,
11457 head_commit_id);
11458 if (error)
11459 goto done;
11460 parent_ids = got_object_commit_get_parent_ids(commit);
11461 pid = STAILQ_FIRST(parent_ids);
11462 if (pid == NULL) {
11463 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
11464 goto done;
11466 error = collect_commits(&commits, head_commit_id, &pid->id,
11467 base_commit_id, got_worktree_get_path_prefix(worktree),
11468 GOT_ERR_HISTEDIT_PATH, repo);
11469 got_object_commit_close(commit);
11470 commit = NULL;
11471 if (error)
11472 goto done;
11473 } else {
11474 if (edit_in_progress) {
11475 error = got_error(GOT_ERR_HISTEDIT_BUSY);
11476 goto done;
11479 error = got_ref_open(&branch, repo,
11480 got_worktree_get_head_ref_name(worktree), 0);
11481 if (error != NULL)
11482 goto done;
11484 if (strncmp(got_ref_get_name(branch), "refs/heads/", 11) != 0) {
11485 error = got_error_msg(GOT_ERR_COMMIT_BRANCH,
11486 "will not edit commit history of a branch outside "
11487 "the \"refs/heads/\" reference namespace");
11488 goto done;
11491 error = got_ref_resolve(&head_commit_id, repo, branch);
11492 got_ref_close(branch);
11493 branch = NULL;
11494 if (error)
11495 goto done;
11497 error = got_object_open_as_commit(&commit, repo,
11498 head_commit_id);
11499 if (error)
11500 goto done;
11501 parent_ids = got_object_commit_get_parent_ids(commit);
11502 pid = STAILQ_FIRST(parent_ids);
11503 if (pid == NULL) {
11504 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
11505 goto done;
11507 error = collect_commits(&commits, head_commit_id, &pid->id,
11508 got_worktree_get_base_commit_id(worktree),
11509 got_worktree_get_path_prefix(worktree),
11510 GOT_ERR_HISTEDIT_PATH, repo);
11511 got_object_commit_close(commit);
11512 commit = NULL;
11513 if (error)
11514 goto done;
11516 if (STAILQ_EMPTY(&commits)) {
11517 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
11518 goto done;
11521 error = got_worktree_histedit_prepare(&tmp_branch, &branch,
11522 &base_commit_id, &fileindex, worktree, repo);
11523 if (error)
11524 goto done;
11526 if (edit_script_path) {
11527 error = histedit_load_list(&histedit_cmds,
11528 edit_script_path, repo);
11529 if (error) {
11530 got_worktree_histedit_abort(worktree, fileindex,
11531 repo, branch, base_commit_id,
11532 abort_progress, &upa);
11533 print_merge_progress_stats(&upa);
11534 goto done;
11536 } else {
11537 const char *branch_name;
11538 branch_name = got_ref_get_symref_target(branch);
11539 if (strncmp(branch_name, "refs/heads/", 11) == 0)
11540 branch_name += 11;
11541 error = histedit_edit_script(&histedit_cmds, &commits,
11542 branch_name, edit_logmsg_only, fold_only,
11543 edit_only, repo);
11544 if (error) {
11545 got_worktree_histedit_abort(worktree, fileindex,
11546 repo, branch, base_commit_id,
11547 abort_progress, &upa);
11548 print_merge_progress_stats(&upa);
11549 goto done;
11554 error = histedit_save_list(&histedit_cmds, worktree,
11555 repo);
11556 if (error) {
11557 got_worktree_histedit_abort(worktree, fileindex,
11558 repo, branch, base_commit_id,
11559 abort_progress, &upa);
11560 print_merge_progress_stats(&upa);
11561 goto done;
11566 error = histedit_check_script(&histedit_cmds, &commits, repo);
11567 if (error)
11568 goto done;
11570 TAILQ_FOREACH(hle, &histedit_cmds, entry) {
11571 if (resume_commit_id) {
11572 if (got_object_id_cmp(hle->commit_id,
11573 resume_commit_id) != 0)
11574 continue;
11576 resume_commit_id = NULL;
11577 if (hle->cmd->code == GOT_HISTEDIT_DROP ||
11578 hle->cmd->code == GOT_HISTEDIT_FOLD) {
11579 error = histedit_skip_commit(hle, worktree,
11580 repo);
11581 if (error)
11582 goto done;
11583 } else {
11584 struct got_pathlist_head paths;
11585 int have_changes = 0;
11587 TAILQ_INIT(&paths);
11588 error = got_pathlist_append(&paths, "", NULL);
11589 if (error)
11590 goto done;
11591 error = got_worktree_status(worktree, &paths,
11592 repo, 0, check_local_changes, &have_changes,
11593 check_cancelled, NULL);
11594 got_pathlist_free(&paths);
11595 if (error) {
11596 if (error->code != GOT_ERR_CANCELLED)
11597 goto done;
11598 if (sigint_received || sigpipe_received)
11599 goto done;
11601 if (have_changes) {
11602 error = histedit_commit(NULL, worktree,
11603 fileindex, tmp_branch, hle, repo);
11604 if (error)
11605 goto done;
11606 } else {
11607 error = got_object_open_as_commit(
11608 &commit, repo, hle->commit_id);
11609 if (error)
11610 goto done;
11611 error = show_histedit_progress(commit,
11612 hle, NULL);
11613 got_object_commit_close(commit);
11614 commit = NULL;
11615 if (error)
11616 goto done;
11619 continue;
11622 if (hle->cmd->code == GOT_HISTEDIT_DROP) {
11623 error = histedit_skip_commit(hle, worktree, repo);
11624 if (error)
11625 goto done;
11626 continue;
11629 error = got_object_open_as_commit(&commit, repo,
11630 hle->commit_id);
11631 if (error)
11632 goto done;
11633 parent_ids = got_object_commit_get_parent_ids(commit);
11634 pid = STAILQ_FIRST(parent_ids);
11636 error = got_worktree_histedit_merge_files(&merged_paths,
11637 worktree, fileindex, &pid->id, hle->commit_id, repo,
11638 update_progress, &upa, check_cancelled, NULL);
11639 if (error)
11640 goto done;
11641 got_object_commit_close(commit);
11642 commit = NULL;
11644 print_merge_progress_stats(&upa);
11645 if (upa.conflicts > 0 || upa.missing > 0 ||
11646 upa.not_deleted > 0 || upa.unversioned > 0) {
11647 if (upa.conflicts > 0) {
11648 error = show_rebase_merge_conflict(
11649 hle->commit_id, repo);
11650 if (error)
11651 goto done;
11653 got_worktree_rebase_pathlist_free(&merged_paths);
11654 break;
11657 if (hle->cmd->code == GOT_HISTEDIT_EDIT) {
11658 char *id_str;
11659 error = got_object_id_str(&id_str, hle->commit_id);
11660 if (error)
11661 goto done;
11662 printf("Stopping histedit for amending commit %s\n",
11663 id_str);
11664 free(id_str);
11665 got_worktree_rebase_pathlist_free(&merged_paths);
11666 error = got_worktree_histedit_postpone(worktree,
11667 fileindex);
11668 goto done;
11671 if (hle->cmd->code == GOT_HISTEDIT_FOLD) {
11672 error = histedit_skip_commit(hle, worktree, repo);
11673 if (error)
11674 goto done;
11675 continue;
11678 error = histedit_commit(&merged_paths, worktree, fileindex,
11679 tmp_branch, hle, repo);
11680 got_worktree_rebase_pathlist_free(&merged_paths);
11681 if (error)
11682 goto done;
11685 if (upa.conflicts > 0 || upa.missing > 0 ||
11686 upa.not_deleted > 0 || upa.unversioned > 0) {
11687 error = got_worktree_histedit_postpone(worktree, fileindex);
11688 if (error)
11689 goto done;
11690 if (upa.conflicts > 0 && upa.missing == 0 &&
11691 upa.not_deleted == 0 && upa.unversioned == 0) {
11692 error = got_error_msg(GOT_ERR_CONFLICTS,
11693 "conflicts must be resolved before histedit "
11694 "can continue");
11695 } else if (upa.conflicts > 0) {
11696 error = got_error_msg(GOT_ERR_CONFLICTS,
11697 "conflicts must be resolved before histedit "
11698 "can continue; changes destined for some "
11699 "files were not yet merged and should be "
11700 "merged manually if required before the "
11701 "histedit operation is continued");
11702 } else {
11703 error = got_error_msg(GOT_ERR_CONFLICTS,
11704 "changes destined for some files were not "
11705 "yet merged and should be merged manually "
11706 "if required before the histedit operation "
11707 "is continued");
11709 } else
11710 error = histedit_complete(worktree, fileindex, tmp_branch,
11711 branch, repo);
11712 done:
11713 got_object_id_queue_free(&commits);
11714 histedit_free_list(&histedit_cmds);
11715 free(head_commit_id);
11716 free(base_commit_id);
11717 free(resume_commit_id);
11718 if (commit)
11719 got_object_commit_close(commit);
11720 if (branch)
11721 got_ref_close(branch);
11722 if (tmp_branch)
11723 got_ref_close(tmp_branch);
11724 if (worktree)
11725 got_worktree_close(worktree);
11726 if (repo) {
11727 const struct got_error *close_err = got_repo_close(repo);
11728 if (error == NULL)
11729 error = close_err;
11731 if (pack_fds) {
11732 const struct got_error *pack_err =
11733 got_repo_pack_fds_close(pack_fds);
11734 if (error == NULL)
11735 error = pack_err;
11737 return error;
11740 __dead static void
11741 usage_integrate(void)
11743 fprintf(stderr, "usage: %s integrate branch\n", getprogname());
11744 exit(1);
11747 static const struct got_error *
11748 cmd_integrate(int argc, char *argv[])
11750 const struct got_error *error = NULL;
11751 struct got_repository *repo = NULL;
11752 struct got_worktree *worktree = NULL;
11753 char *cwd = NULL, *refname = NULL, *base_refname = NULL;
11754 const char *branch_arg = NULL;
11755 struct got_reference *branch_ref = NULL, *base_branch_ref = NULL;
11756 struct got_fileindex *fileindex = NULL;
11757 struct got_object_id *commit_id = NULL, *base_commit_id = NULL;
11758 int ch;
11759 struct got_update_progress_arg upa;
11760 int *pack_fds = NULL;
11762 while ((ch = getopt(argc, argv, "")) != -1) {
11763 switch (ch) {
11764 default:
11765 usage_integrate();
11766 /* NOTREACHED */
11770 argc -= optind;
11771 argv += optind;
11773 if (argc != 1)
11774 usage_integrate();
11775 branch_arg = argv[0];
11776 #ifndef PROFILE
11777 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
11778 "unveil", NULL) == -1)
11779 err(1, "pledge");
11780 #endif
11781 cwd = getcwd(NULL, 0);
11782 if (cwd == NULL) {
11783 error = got_error_from_errno("getcwd");
11784 goto done;
11787 error = got_repo_pack_fds_open(&pack_fds);
11788 if (error != NULL)
11789 goto done;
11791 error = got_worktree_open(&worktree, cwd);
11792 if (error) {
11793 if (error->code == GOT_ERR_NOT_WORKTREE)
11794 error = wrap_not_worktree_error(error, "integrate",
11795 cwd);
11796 goto done;
11799 error = check_rebase_or_histedit_in_progress(worktree);
11800 if (error)
11801 goto done;
11803 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
11804 NULL, pack_fds);
11805 if (error != NULL)
11806 goto done;
11808 error = apply_unveil(got_repo_get_path(repo), 0,
11809 got_worktree_get_root_path(worktree));
11810 if (error)
11811 goto done;
11813 error = check_merge_in_progress(worktree, repo);
11814 if (error)
11815 goto done;
11817 if (asprintf(&refname, "refs/heads/%s", branch_arg) == -1) {
11818 error = got_error_from_errno("asprintf");
11819 goto done;
11822 error = got_worktree_integrate_prepare(&fileindex, &branch_ref,
11823 &base_branch_ref, worktree, refname, repo);
11824 if (error)
11825 goto done;
11827 refname = strdup(got_ref_get_name(branch_ref));
11828 if (refname == NULL) {
11829 error = got_error_from_errno("strdup");
11830 got_worktree_integrate_abort(worktree, fileindex, repo,
11831 branch_ref, base_branch_ref);
11832 goto done;
11834 base_refname = strdup(got_ref_get_name(base_branch_ref));
11835 if (base_refname == NULL) {
11836 error = got_error_from_errno("strdup");
11837 got_worktree_integrate_abort(worktree, fileindex, repo,
11838 branch_ref, base_branch_ref);
11839 goto done;
11842 error = got_ref_resolve(&commit_id, repo, branch_ref);
11843 if (error)
11844 goto done;
11846 error = got_ref_resolve(&base_commit_id, repo, base_branch_ref);
11847 if (error)
11848 goto done;
11850 if (got_object_id_cmp(commit_id, base_commit_id) == 0) {
11851 error = got_error_msg(GOT_ERR_SAME_BRANCH,
11852 "specified branch has already been integrated");
11853 got_worktree_integrate_abort(worktree, fileindex, repo,
11854 branch_ref, base_branch_ref);
11855 goto done;
11858 error = check_linear_ancestry(commit_id, base_commit_id, 1, repo);
11859 if (error) {
11860 if (error->code == GOT_ERR_ANCESTRY)
11861 error = got_error(GOT_ERR_REBASE_REQUIRED);
11862 got_worktree_integrate_abort(worktree, fileindex, repo,
11863 branch_ref, base_branch_ref);
11864 goto done;
11867 memset(&upa, 0, sizeof(upa));
11868 error = got_worktree_integrate_continue(worktree, fileindex, repo,
11869 branch_ref, base_branch_ref, update_progress, &upa,
11870 check_cancelled, NULL);
11871 if (error)
11872 goto done;
11874 printf("Integrated %s into %s\n", refname, base_refname);
11875 print_update_progress_stats(&upa);
11876 done:
11877 if (repo) {
11878 const struct got_error *close_err = got_repo_close(repo);
11879 if (error == NULL)
11880 error = close_err;
11882 if (worktree)
11883 got_worktree_close(worktree);
11884 if (pack_fds) {
11885 const struct got_error *pack_err =
11886 got_repo_pack_fds_close(pack_fds);
11887 if (error == NULL)
11888 error = pack_err;
11890 free(cwd);
11891 free(base_commit_id);
11892 free(commit_id);
11893 free(refname);
11894 free(base_refname);
11895 return error;
11898 __dead static void
11899 usage_merge(void)
11901 fprintf(stderr, "usage: %s merge [-a] [-c] [-n] [branch]\n",
11902 getprogname());
11903 exit(1);
11906 static const struct got_error *
11907 cmd_merge(int argc, char *argv[])
11909 const struct got_error *error = NULL;
11910 struct got_worktree *worktree = NULL;
11911 struct got_repository *repo = NULL;
11912 struct got_fileindex *fileindex = NULL;
11913 char *cwd = NULL, *id_str = NULL, *author = NULL;
11914 struct got_reference *branch = NULL, *wt_branch = NULL;
11915 struct got_object_id *branch_tip = NULL, *yca_id = NULL;
11916 struct got_object_id *wt_branch_tip = NULL;
11917 int ch, merge_in_progress = 0, abort_merge = 0, continue_merge = 0;
11918 int interrupt_merge = 0;
11919 struct got_update_progress_arg upa;
11920 struct got_object_id *merge_commit_id = NULL;
11921 char *branch_name = NULL;
11922 int *pack_fds = NULL;
11924 memset(&upa, 0, sizeof(upa));
11926 while ((ch = getopt(argc, argv, "acn")) != -1) {
11927 switch (ch) {
11928 case 'a':
11929 abort_merge = 1;
11930 break;
11931 case 'c':
11932 continue_merge = 1;
11933 break;
11934 case 'n':
11935 interrupt_merge = 1;
11936 break;
11937 default:
11938 usage_rebase();
11939 /* NOTREACHED */
11943 argc -= optind;
11944 argv += optind;
11946 #ifndef PROFILE
11947 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
11948 "unveil", NULL) == -1)
11949 err(1, "pledge");
11950 #endif
11952 if (abort_merge && continue_merge)
11953 option_conflict('a', 'c');
11954 if (abort_merge || continue_merge) {
11955 if (argc != 0)
11956 usage_merge();
11957 } else if (argc != 1)
11958 usage_merge();
11960 cwd = getcwd(NULL, 0);
11961 if (cwd == NULL) {
11962 error = got_error_from_errno("getcwd");
11963 goto done;
11966 error = got_repo_pack_fds_open(&pack_fds);
11967 if (error != NULL)
11968 goto done;
11970 error = got_worktree_open(&worktree, cwd);
11971 if (error) {
11972 if (error->code == GOT_ERR_NOT_WORKTREE)
11973 error = wrap_not_worktree_error(error,
11974 "merge", cwd);
11975 goto done;
11978 error = got_repo_open(&repo,
11979 worktree ? got_worktree_get_repo_path(worktree) : cwd, NULL,
11980 pack_fds);
11981 if (error != NULL)
11982 goto done;
11984 error = apply_unveil(got_repo_get_path(repo), 0,
11985 worktree ? got_worktree_get_root_path(worktree) : NULL);
11986 if (error)
11987 goto done;
11989 error = check_rebase_or_histedit_in_progress(worktree);
11990 if (error)
11991 goto done;
11993 error = got_worktree_merge_in_progress(&merge_in_progress, worktree,
11994 repo);
11995 if (error)
11996 goto done;
11998 if (abort_merge) {
11999 if (!merge_in_progress) {
12000 error = got_error(GOT_ERR_NOT_MERGING);
12001 goto done;
12003 error = got_worktree_merge_continue(&branch_name,
12004 &branch_tip, &fileindex, worktree, repo);
12005 if (error)
12006 goto done;
12007 error = got_worktree_merge_abort(worktree, fileindex, repo,
12008 abort_progress, &upa);
12009 if (error)
12010 goto done;
12011 printf("Merge of %s aborted\n", branch_name);
12012 goto done; /* nothing else to do */
12015 error = get_author(&author, repo, worktree);
12016 if (error)
12017 goto done;
12019 if (continue_merge) {
12020 if (!merge_in_progress) {
12021 error = got_error(GOT_ERR_NOT_MERGING);
12022 goto done;
12024 error = got_worktree_merge_continue(&branch_name,
12025 &branch_tip, &fileindex, worktree, repo);
12026 if (error)
12027 goto done;
12028 } else {
12029 error = got_ref_open(&branch, repo, argv[0], 0);
12030 if (error != NULL)
12031 goto done;
12032 branch_name = strdup(got_ref_get_name(branch));
12033 if (branch_name == NULL) {
12034 error = got_error_from_errno("strdup");
12035 goto done;
12037 error = got_ref_resolve(&branch_tip, repo, branch);
12038 if (error)
12039 goto done;
12042 error = got_ref_open(&wt_branch, repo,
12043 got_worktree_get_head_ref_name(worktree), 0);
12044 if (error)
12045 goto done;
12046 error = got_ref_resolve(&wt_branch_tip, repo, wt_branch);
12047 if (error)
12048 goto done;
12049 error = got_commit_graph_find_youngest_common_ancestor(&yca_id,
12050 wt_branch_tip, branch_tip, 0, repo,
12051 check_cancelled, NULL);
12052 if (error && error->code != GOT_ERR_ANCESTRY)
12053 goto done;
12055 if (!continue_merge) {
12056 error = check_path_prefix(wt_branch_tip, branch_tip,
12057 got_worktree_get_path_prefix(worktree),
12058 GOT_ERR_MERGE_PATH, repo);
12059 if (error)
12060 goto done;
12061 if (yca_id) {
12062 error = check_same_branch(wt_branch_tip, branch,
12063 yca_id, repo);
12064 if (error) {
12065 if (error->code != GOT_ERR_ANCESTRY)
12066 goto done;
12067 error = NULL;
12068 } else {
12069 static char msg[512];
12070 snprintf(msg, sizeof(msg),
12071 "cannot create a merge commit because "
12072 "%s is based on %s; %s can be integrated "
12073 "with 'got integrate' instead", branch_name,
12074 got_worktree_get_head_ref_name(worktree),
12075 branch_name);
12076 error = got_error_msg(GOT_ERR_SAME_BRANCH, msg);
12077 goto done;
12080 error = got_worktree_merge_prepare(&fileindex, worktree,
12081 branch, repo);
12082 if (error)
12083 goto done;
12085 error = got_worktree_merge_branch(worktree, fileindex,
12086 yca_id, branch_tip, repo, update_progress, &upa,
12087 check_cancelled, NULL);
12088 if (error)
12089 goto done;
12090 print_merge_progress_stats(&upa);
12091 if (!upa.did_something) {
12092 error = got_worktree_merge_abort(worktree, fileindex,
12093 repo, abort_progress, &upa);
12094 if (error)
12095 goto done;
12096 printf("Already up-to-date\n");
12097 goto done;
12101 if (interrupt_merge) {
12102 error = got_worktree_merge_postpone(worktree, fileindex);
12103 if (error)
12104 goto done;
12105 printf("Merge of %s interrupted on request\n", branch_name);
12106 } else if (upa.conflicts > 0 || upa.missing > 0 ||
12107 upa.not_deleted > 0 || upa.unversioned > 0) {
12108 error = got_worktree_merge_postpone(worktree, fileindex);
12109 if (error)
12110 goto done;
12111 if (upa.conflicts > 0 && upa.missing == 0 &&
12112 upa.not_deleted == 0 && upa.unversioned == 0) {
12113 error = got_error_msg(GOT_ERR_CONFLICTS,
12114 "conflicts must be resolved before merging "
12115 "can continue");
12116 } else if (upa.conflicts > 0) {
12117 error = got_error_msg(GOT_ERR_CONFLICTS,
12118 "conflicts must be resolved before merging "
12119 "can continue; changes destined for some "
12120 "files were not yet merged and "
12121 "should be merged manually if required before the "
12122 "merge operation is continued");
12123 } else {
12124 error = got_error_msg(GOT_ERR_CONFLICTS,
12125 "changes destined for some "
12126 "files were not yet merged and should be "
12127 "merged manually if required before the "
12128 "merge operation is continued");
12130 goto done;
12131 } else {
12132 error = got_worktree_merge_commit(&merge_commit_id, worktree,
12133 fileindex, author, NULL, 1, branch_tip, branch_name,
12134 repo, continue_merge ? print_status : NULL, NULL);
12135 if (error)
12136 goto done;
12137 error = got_worktree_merge_complete(worktree, fileindex, repo);
12138 if (error)
12139 goto done;
12140 error = got_object_id_str(&id_str, merge_commit_id);
12141 if (error)
12142 goto done;
12143 printf("Merged %s into %s: %s\n", branch_name,
12144 got_worktree_get_head_ref_name(worktree),
12145 id_str);
12148 done:
12149 free(id_str);
12150 free(merge_commit_id);
12151 free(author);
12152 free(branch_tip);
12153 free(branch_name);
12154 free(yca_id);
12155 if (branch)
12156 got_ref_close(branch);
12157 if (wt_branch)
12158 got_ref_close(wt_branch);
12159 if (worktree)
12160 got_worktree_close(worktree);
12161 if (repo) {
12162 const struct got_error *close_err = got_repo_close(repo);
12163 if (error == NULL)
12164 error = close_err;
12166 if (pack_fds) {
12167 const struct got_error *pack_err =
12168 got_repo_pack_fds_close(pack_fds);
12169 if (error == NULL)
12170 error = pack_err;
12172 return error;
12175 __dead static void
12176 usage_stage(void)
12178 fprintf(stderr, "usage: %s stage [-l] | [-p] [-F response-script] "
12179 "[-S] [file-path ...]\n",
12180 getprogname());
12181 exit(1);
12184 static const struct got_error *
12185 print_stage(void *arg, unsigned char status, unsigned char staged_status,
12186 const char *path, struct got_object_id *blob_id,
12187 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
12188 int dirfd, const char *de_name)
12190 const struct got_error *err = NULL;
12191 char *id_str = NULL;
12193 if (staged_status != GOT_STATUS_ADD &&
12194 staged_status != GOT_STATUS_MODIFY &&
12195 staged_status != GOT_STATUS_DELETE)
12196 return NULL;
12198 if (staged_status == GOT_STATUS_ADD ||
12199 staged_status == GOT_STATUS_MODIFY)
12200 err = got_object_id_str(&id_str, staged_blob_id);
12201 else
12202 err = got_object_id_str(&id_str, blob_id);
12203 if (err)
12204 return err;
12206 printf("%s %c %s\n", id_str, staged_status, path);
12207 free(id_str);
12208 return NULL;
12211 static const struct got_error *
12212 cmd_stage(int argc, char *argv[])
12214 const struct got_error *error = NULL;
12215 struct got_repository *repo = NULL;
12216 struct got_worktree *worktree = NULL;
12217 char *cwd = NULL;
12218 struct got_pathlist_head paths;
12219 struct got_pathlist_entry *pe;
12220 int ch, list_stage = 0, pflag = 0, allow_bad_symlinks = 0;
12221 FILE *patch_script_file = NULL;
12222 const char *patch_script_path = NULL;
12223 struct choose_patch_arg cpa;
12224 int *pack_fds = NULL;
12226 TAILQ_INIT(&paths);
12228 while ((ch = getopt(argc, argv, "lpF:S")) != -1) {
12229 switch (ch) {
12230 case 'l':
12231 list_stage = 1;
12232 break;
12233 case 'p':
12234 pflag = 1;
12235 break;
12236 case 'F':
12237 patch_script_path = optarg;
12238 break;
12239 case 'S':
12240 allow_bad_symlinks = 1;
12241 break;
12242 default:
12243 usage_stage();
12244 /* NOTREACHED */
12248 argc -= optind;
12249 argv += optind;
12251 #ifndef PROFILE
12252 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
12253 "unveil", NULL) == -1)
12254 err(1, "pledge");
12255 #endif
12256 if (list_stage && (pflag || patch_script_path))
12257 errx(1, "-l option cannot be used with other options");
12258 if (patch_script_path && !pflag)
12259 errx(1, "-F option can only be used together with -p option");
12261 cwd = getcwd(NULL, 0);
12262 if (cwd == NULL) {
12263 error = got_error_from_errno("getcwd");
12264 goto done;
12267 error = got_repo_pack_fds_open(&pack_fds);
12268 if (error != NULL)
12269 goto done;
12271 error = got_worktree_open(&worktree, cwd);
12272 if (error) {
12273 if (error->code == GOT_ERR_NOT_WORKTREE)
12274 error = wrap_not_worktree_error(error, "stage", cwd);
12275 goto done;
12278 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
12279 NULL, pack_fds);
12280 if (error != NULL)
12281 goto done;
12283 if (patch_script_path) {
12284 patch_script_file = fopen(patch_script_path, "re");
12285 if (patch_script_file == NULL) {
12286 error = got_error_from_errno2("fopen",
12287 patch_script_path);
12288 goto done;
12291 error = apply_unveil(got_repo_get_path(repo), 0,
12292 got_worktree_get_root_path(worktree));
12293 if (error)
12294 goto done;
12296 error = check_merge_in_progress(worktree, repo);
12297 if (error)
12298 goto done;
12300 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
12301 if (error)
12302 goto done;
12304 if (list_stage)
12305 error = got_worktree_status(worktree, &paths, repo, 0,
12306 print_stage, NULL, check_cancelled, NULL);
12307 else {
12308 cpa.patch_script_file = patch_script_file;
12309 cpa.action = "stage";
12310 error = got_worktree_stage(worktree, &paths,
12311 pflag ? NULL : print_status, NULL,
12312 pflag ? choose_patch : NULL, &cpa,
12313 allow_bad_symlinks, repo);
12315 done:
12316 if (patch_script_file && fclose(patch_script_file) == EOF &&
12317 error == NULL)
12318 error = got_error_from_errno2("fclose", patch_script_path);
12319 if (repo) {
12320 const struct got_error *close_err = got_repo_close(repo);
12321 if (error == NULL)
12322 error = close_err;
12324 if (worktree)
12325 got_worktree_close(worktree);
12326 if (pack_fds) {
12327 const struct got_error *pack_err =
12328 got_repo_pack_fds_close(pack_fds);
12329 if (error == NULL)
12330 error = pack_err;
12332 TAILQ_FOREACH(pe, &paths, entry)
12333 free((char *)pe->path);
12334 got_pathlist_free(&paths);
12335 free(cwd);
12336 return error;
12339 __dead static void
12340 usage_unstage(void)
12342 fprintf(stderr, "usage: %s unstage [-p] [-F response-script] "
12343 "[file-path ...]\n",
12344 getprogname());
12345 exit(1);
12349 static const struct got_error *
12350 cmd_unstage(int argc, char *argv[])
12352 const struct got_error *error = NULL;
12353 struct got_repository *repo = NULL;
12354 struct got_worktree *worktree = NULL;
12355 char *cwd = NULL;
12356 struct got_pathlist_head paths;
12357 struct got_pathlist_entry *pe;
12358 int ch, pflag = 0;
12359 struct got_update_progress_arg upa;
12360 FILE *patch_script_file = NULL;
12361 const char *patch_script_path = NULL;
12362 struct choose_patch_arg cpa;
12363 int *pack_fds = NULL;
12365 TAILQ_INIT(&paths);
12367 while ((ch = getopt(argc, argv, "pF:")) != -1) {
12368 switch (ch) {
12369 case 'p':
12370 pflag = 1;
12371 break;
12372 case 'F':
12373 patch_script_path = optarg;
12374 break;
12375 default:
12376 usage_unstage();
12377 /* NOTREACHED */
12381 argc -= optind;
12382 argv += optind;
12384 #ifndef PROFILE
12385 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
12386 "unveil", NULL) == -1)
12387 err(1, "pledge");
12388 #endif
12389 if (patch_script_path && !pflag)
12390 errx(1, "-F option can only be used together with -p option");
12392 cwd = getcwd(NULL, 0);
12393 if (cwd == NULL) {
12394 error = got_error_from_errno("getcwd");
12395 goto done;
12398 error = got_repo_pack_fds_open(&pack_fds);
12399 if (error != NULL)
12400 goto done;
12402 error = got_worktree_open(&worktree, cwd);
12403 if (error) {
12404 if (error->code == GOT_ERR_NOT_WORKTREE)
12405 error = wrap_not_worktree_error(error, "unstage", cwd);
12406 goto done;
12409 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
12410 NULL, pack_fds);
12411 if (error != NULL)
12412 goto done;
12414 if (patch_script_path) {
12415 patch_script_file = fopen(patch_script_path, "re");
12416 if (patch_script_file == NULL) {
12417 error = got_error_from_errno2("fopen",
12418 patch_script_path);
12419 goto done;
12423 error = apply_unveil(got_repo_get_path(repo), 0,
12424 got_worktree_get_root_path(worktree));
12425 if (error)
12426 goto done;
12428 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
12429 if (error)
12430 goto done;
12432 cpa.patch_script_file = patch_script_file;
12433 cpa.action = "unstage";
12434 memset(&upa, 0, sizeof(upa));
12435 error = got_worktree_unstage(worktree, &paths, update_progress,
12436 &upa, pflag ? choose_patch : NULL, &cpa, repo);
12437 if (!error)
12438 print_merge_progress_stats(&upa);
12439 done:
12440 if (patch_script_file && fclose(patch_script_file) == EOF &&
12441 error == NULL)
12442 error = got_error_from_errno2("fclose", patch_script_path);
12443 if (repo) {
12444 const struct got_error *close_err = got_repo_close(repo);
12445 if (error == NULL)
12446 error = close_err;
12448 if (worktree)
12449 got_worktree_close(worktree);
12450 if (pack_fds) {
12451 const struct got_error *pack_err =
12452 got_repo_pack_fds_close(pack_fds);
12453 if (error == NULL)
12454 error = pack_err;
12456 TAILQ_FOREACH(pe, &paths, entry)
12457 free((char *)pe->path);
12458 got_pathlist_free(&paths);
12459 free(cwd);
12460 return error;
12463 __dead static void
12464 usage_cat(void)
12466 fprintf(stderr, "usage: %s cat [-r repository ] [ -c commit ] [ -P ] "
12467 "arg1 [arg2 ...]\n", getprogname());
12468 exit(1);
12471 static const struct got_error *
12472 cat_blob(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
12474 const struct got_error *err;
12475 struct got_blob_object *blob;
12476 int fd = -1;
12478 fd = got_opentempfd();
12479 if (fd == -1)
12480 return got_error_from_errno("got_opentempfd");
12482 err = got_object_open_as_blob(&blob, repo, id, 8192, fd);
12483 if (err)
12484 goto done;
12486 err = got_object_blob_dump_to_file(NULL, NULL, NULL, outfile, blob);
12487 done:
12488 if (fd != -1 && close(fd) == -1 && err == NULL)
12489 err = got_error_from_errno("close");
12490 if (blob)
12491 got_object_blob_close(blob);
12492 return err;
12495 static const struct got_error *
12496 cat_tree(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
12498 const struct got_error *err;
12499 struct got_tree_object *tree;
12500 int nentries, i;
12502 err = got_object_open_as_tree(&tree, repo, id);
12503 if (err)
12504 return err;
12506 nentries = got_object_tree_get_nentries(tree);
12507 for (i = 0; i < nentries; i++) {
12508 struct got_tree_entry *te;
12509 char *id_str;
12510 if (sigint_received || sigpipe_received)
12511 break;
12512 te = got_object_tree_get_entry(tree, i);
12513 err = got_object_id_str(&id_str, got_tree_entry_get_id(te));
12514 if (err)
12515 break;
12516 fprintf(outfile, "%s %.7o %s\n", id_str,
12517 got_tree_entry_get_mode(te),
12518 got_tree_entry_get_name(te));
12519 free(id_str);
12522 got_object_tree_close(tree);
12523 return err;
12526 static const struct got_error *
12527 cat_commit(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
12529 const struct got_error *err;
12530 struct got_commit_object *commit;
12531 const struct got_object_id_queue *parent_ids;
12532 struct got_object_qid *pid;
12533 char *id_str = NULL;
12534 const char *logmsg = NULL;
12535 char gmtoff[6];
12537 err = got_object_open_as_commit(&commit, repo, id);
12538 if (err)
12539 return err;
12541 err = got_object_id_str(&id_str, got_object_commit_get_tree_id(commit));
12542 if (err)
12543 goto done;
12545 fprintf(outfile, "%s%s\n", GOT_COMMIT_LABEL_TREE, id_str);
12546 parent_ids = got_object_commit_get_parent_ids(commit);
12547 fprintf(outfile, "numparents %d\n",
12548 got_object_commit_get_nparents(commit));
12549 STAILQ_FOREACH(pid, parent_ids, entry) {
12550 char *pid_str;
12551 err = got_object_id_str(&pid_str, &pid->id);
12552 if (err)
12553 goto done;
12554 fprintf(outfile, "%s%s\n", GOT_COMMIT_LABEL_PARENT, pid_str);
12555 free(pid_str);
12557 got_date_format_gmtoff(gmtoff, sizeof(gmtoff),
12558 got_object_commit_get_author_gmtoff(commit));
12559 fprintf(outfile, "%s%s %lld %s\n", GOT_COMMIT_LABEL_AUTHOR,
12560 got_object_commit_get_author(commit),
12561 (long long)got_object_commit_get_author_time(commit),
12562 gmtoff);
12564 got_date_format_gmtoff(gmtoff, sizeof(gmtoff),
12565 got_object_commit_get_committer_gmtoff(commit));
12566 fprintf(outfile, "%s%s %lld %s\n", GOT_COMMIT_LABEL_COMMITTER,
12567 got_object_commit_get_author(commit),
12568 (long long)got_object_commit_get_committer_time(commit),
12569 gmtoff);
12571 logmsg = got_object_commit_get_logmsg_raw(commit);
12572 fprintf(outfile, "messagelen %zd\n", strlen(logmsg));
12573 fprintf(outfile, "%s", logmsg);
12574 done:
12575 free(id_str);
12576 got_object_commit_close(commit);
12577 return err;
12580 static const struct got_error *
12581 cat_tag(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
12583 const struct got_error *err;
12584 struct got_tag_object *tag;
12585 char *id_str = NULL;
12586 const char *tagmsg = NULL;
12587 char gmtoff[6];
12589 err = got_object_open_as_tag(&tag, repo, id);
12590 if (err)
12591 return err;
12593 err = got_object_id_str(&id_str, got_object_tag_get_object_id(tag));
12594 if (err)
12595 goto done;
12597 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_OBJECT, id_str);
12599 switch (got_object_tag_get_object_type(tag)) {
12600 case GOT_OBJ_TYPE_BLOB:
12601 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
12602 GOT_OBJ_LABEL_BLOB);
12603 break;
12604 case GOT_OBJ_TYPE_TREE:
12605 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
12606 GOT_OBJ_LABEL_TREE);
12607 break;
12608 case GOT_OBJ_TYPE_COMMIT:
12609 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
12610 GOT_OBJ_LABEL_COMMIT);
12611 break;
12612 case GOT_OBJ_TYPE_TAG:
12613 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
12614 GOT_OBJ_LABEL_TAG);
12615 break;
12616 default:
12617 break;
12620 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TAG,
12621 got_object_tag_get_name(tag));
12623 got_date_format_gmtoff(gmtoff, sizeof(gmtoff),
12624 got_object_tag_get_tagger_gmtoff(tag));
12625 fprintf(outfile, "%s%s %lld %s\n", GOT_TAG_LABEL_TAGGER,
12626 got_object_tag_get_tagger(tag),
12627 (long long)got_object_tag_get_tagger_time(tag),
12628 gmtoff);
12630 tagmsg = got_object_tag_get_message(tag);
12631 fprintf(outfile, "messagelen %zd\n", strlen(tagmsg));
12632 fprintf(outfile, "%s", tagmsg);
12633 done:
12634 free(id_str);
12635 got_object_tag_close(tag);
12636 return err;
12639 static const struct got_error *
12640 cmd_cat(int argc, char *argv[])
12642 const struct got_error *error;
12643 struct got_repository *repo = NULL;
12644 struct got_worktree *worktree = NULL;
12645 char *cwd = NULL, *repo_path = NULL, *label = NULL;
12646 const char *commit_id_str = NULL;
12647 struct got_object_id *id = NULL, *commit_id = NULL;
12648 struct got_commit_object *commit = NULL;
12649 int ch, obj_type, i, force_path = 0;
12650 struct got_reflist_head refs;
12651 int *pack_fds = NULL;
12653 TAILQ_INIT(&refs);
12655 #ifndef PROFILE
12656 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
12657 NULL) == -1)
12658 err(1, "pledge");
12659 #endif
12661 while ((ch = getopt(argc, argv, "c:r:P")) != -1) {
12662 switch (ch) {
12663 case 'c':
12664 commit_id_str = optarg;
12665 break;
12666 case 'r':
12667 repo_path = realpath(optarg, NULL);
12668 if (repo_path == NULL)
12669 return got_error_from_errno2("realpath",
12670 optarg);
12671 got_path_strip_trailing_slashes(repo_path);
12672 break;
12673 case 'P':
12674 force_path = 1;
12675 break;
12676 default:
12677 usage_cat();
12678 /* NOTREACHED */
12682 argc -= optind;
12683 argv += optind;
12685 cwd = getcwd(NULL, 0);
12686 if (cwd == NULL) {
12687 error = got_error_from_errno("getcwd");
12688 goto done;
12691 error = got_repo_pack_fds_open(&pack_fds);
12692 if (error != NULL)
12693 goto done;
12695 if (repo_path == NULL) {
12696 error = got_worktree_open(&worktree, cwd);
12697 if (error && error->code != GOT_ERR_NOT_WORKTREE)
12698 goto done;
12699 if (worktree) {
12700 repo_path = strdup(
12701 got_worktree_get_repo_path(worktree));
12702 if (repo_path == NULL) {
12703 error = got_error_from_errno("strdup");
12704 goto done;
12707 /* Release work tree lock. */
12708 got_worktree_close(worktree);
12709 worktree = NULL;
12713 if (repo_path == NULL) {
12714 repo_path = strdup(cwd);
12715 if (repo_path == NULL)
12716 return got_error_from_errno("strdup");
12719 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
12720 free(repo_path);
12721 if (error != NULL)
12722 goto done;
12724 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
12725 if (error)
12726 goto done;
12728 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
12729 if (error)
12730 goto done;
12732 if (commit_id_str == NULL)
12733 commit_id_str = GOT_REF_HEAD;
12734 error = got_repo_match_object_id(&commit_id, NULL,
12735 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
12736 if (error)
12737 goto done;
12739 error = got_object_open_as_commit(&commit, repo, commit_id);
12740 if (error)
12741 goto done;
12743 for (i = 0; i < argc; i++) {
12744 if (force_path) {
12745 error = got_object_id_by_path(&id, repo, commit,
12746 argv[i]);
12747 if (error)
12748 break;
12749 } else {
12750 error = got_repo_match_object_id(&id, &label, argv[i],
12751 GOT_OBJ_TYPE_ANY, NULL /* do not resolve tags */,
12752 repo);
12753 if (error) {
12754 if (error->code != GOT_ERR_BAD_OBJ_ID_STR &&
12755 error->code != GOT_ERR_NOT_REF)
12756 break;
12757 error = got_object_id_by_path(&id, repo,
12758 commit, argv[i]);
12759 if (error)
12760 break;
12764 error = got_object_get_type(&obj_type, repo, id);
12765 if (error)
12766 break;
12768 switch (obj_type) {
12769 case GOT_OBJ_TYPE_BLOB:
12770 error = cat_blob(id, repo, stdout);
12771 break;
12772 case GOT_OBJ_TYPE_TREE:
12773 error = cat_tree(id, repo, stdout);
12774 break;
12775 case GOT_OBJ_TYPE_COMMIT:
12776 error = cat_commit(id, repo, stdout);
12777 break;
12778 case GOT_OBJ_TYPE_TAG:
12779 error = cat_tag(id, repo, stdout);
12780 break;
12781 default:
12782 error = got_error(GOT_ERR_OBJ_TYPE);
12783 break;
12785 if (error)
12786 break;
12787 free(label);
12788 label = NULL;
12789 free(id);
12790 id = NULL;
12792 done:
12793 free(label);
12794 free(id);
12795 free(commit_id);
12796 if (commit)
12797 got_object_commit_close(commit);
12798 if (worktree)
12799 got_worktree_close(worktree);
12800 if (repo) {
12801 const struct got_error *close_err = got_repo_close(repo);
12802 if (error == NULL)
12803 error = close_err;
12805 if (pack_fds) {
12806 const struct got_error *pack_err =
12807 got_repo_pack_fds_close(pack_fds);
12808 if (error == NULL)
12809 error = pack_err;
12812 got_ref_list_free(&refs);
12813 return error;
12816 __dead static void
12817 usage_info(void)
12819 fprintf(stderr, "usage: %s info [path ...]\n",
12820 getprogname());
12821 exit(1);
12824 static const struct got_error *
12825 print_path_info(void *arg, const char *path, mode_t mode, time_t mtime,
12826 struct got_object_id *blob_id, struct got_object_id *staged_blob_id,
12827 struct got_object_id *commit_id)
12829 const struct got_error *err = NULL;
12830 char *id_str = NULL;
12831 char datebuf[128];
12832 struct tm mytm, *tm;
12833 struct got_pathlist_head *paths = arg;
12834 struct got_pathlist_entry *pe;
12837 * Clear error indication from any of the path arguments which
12838 * would cause this file index entry to be displayed.
12840 TAILQ_FOREACH(pe, paths, entry) {
12841 if (got_path_cmp(path, pe->path, strlen(path),
12842 pe->path_len) == 0 ||
12843 got_path_is_child(path, pe->path, pe->path_len))
12844 pe->data = NULL; /* no error */
12847 printf(GOT_COMMIT_SEP_STR);
12848 if (S_ISLNK(mode))
12849 printf("symlink: %s\n", path);
12850 else if (S_ISREG(mode)) {
12851 printf("file: %s\n", path);
12852 printf("mode: %o\n", mode & (S_IRWXU | S_IRWXG | S_IRWXO));
12853 } else if (S_ISDIR(mode))
12854 printf("directory: %s\n", path);
12855 else
12856 printf("something: %s\n", path);
12858 tm = localtime_r(&mtime, &mytm);
12859 if (tm == NULL)
12860 return NULL;
12861 if (strftime(datebuf, sizeof(datebuf), "%c %Z", tm) == 0)
12862 return got_error(GOT_ERR_NO_SPACE);
12863 printf("timestamp: %s\n", datebuf);
12865 if (blob_id) {
12866 err = got_object_id_str(&id_str, blob_id);
12867 if (err)
12868 return err;
12869 printf("based on blob: %s\n", id_str);
12870 free(id_str);
12873 if (staged_blob_id) {
12874 err = got_object_id_str(&id_str, staged_blob_id);
12875 if (err)
12876 return err;
12877 printf("based on staged blob: %s\n", id_str);
12878 free(id_str);
12881 if (commit_id) {
12882 err = got_object_id_str(&id_str, commit_id);
12883 if (err)
12884 return err;
12885 printf("based on commit: %s\n", id_str);
12886 free(id_str);
12889 return NULL;
12892 static const struct got_error *
12893 cmd_info(int argc, char *argv[])
12895 const struct got_error *error = NULL;
12896 struct got_worktree *worktree = NULL;
12897 char *cwd = NULL, *id_str = NULL;
12898 struct got_pathlist_head paths;
12899 struct got_pathlist_entry *pe;
12900 char *uuidstr = NULL;
12901 int ch, show_files = 0;
12902 int *pack_fds = NULL;
12904 TAILQ_INIT(&paths);
12906 while ((ch = getopt(argc, argv, "")) != -1) {
12907 switch (ch) {
12908 default:
12909 usage_info();
12910 /* NOTREACHED */
12914 argc -= optind;
12915 argv += optind;
12917 #ifndef PROFILE
12918 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
12919 NULL) == -1)
12920 err(1, "pledge");
12921 #endif
12922 cwd = getcwd(NULL, 0);
12923 if (cwd == NULL) {
12924 error = got_error_from_errno("getcwd");
12925 goto done;
12928 error = got_repo_pack_fds_open(&pack_fds);
12929 if (error != NULL)
12930 goto done;
12932 error = got_worktree_open(&worktree, cwd);
12933 if (error) {
12934 if (error->code == GOT_ERR_NOT_WORKTREE)
12935 error = wrap_not_worktree_error(error, "info", cwd);
12936 goto done;
12939 #ifndef PROFILE
12940 /* Remove "cpath" promise. */
12941 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
12942 NULL) == -1)
12943 err(1, "pledge");
12944 #endif
12945 error = apply_unveil(NULL, 0, got_worktree_get_root_path(worktree));
12946 if (error)
12947 goto done;
12949 if (argc >= 1) {
12950 error = get_worktree_paths_from_argv(&paths, argc, argv,
12951 worktree);
12952 if (error)
12953 goto done;
12954 show_files = 1;
12957 error = got_object_id_str(&id_str,
12958 got_worktree_get_base_commit_id(worktree));
12959 if (error)
12960 goto done;
12962 error = got_worktree_get_uuid(&uuidstr, worktree);
12963 if (error)
12964 goto done;
12966 printf("work tree: %s\n", got_worktree_get_root_path(worktree));
12967 printf("work tree base commit: %s\n", id_str);
12968 printf("work tree path prefix: %s\n",
12969 got_worktree_get_path_prefix(worktree));
12970 printf("work tree branch reference: %s\n",
12971 got_worktree_get_head_ref_name(worktree));
12972 printf("work tree UUID: %s\n", uuidstr);
12973 printf("repository: %s\n", got_worktree_get_repo_path(worktree));
12975 if (show_files) {
12976 struct got_pathlist_entry *pe;
12977 TAILQ_FOREACH(pe, &paths, entry) {
12978 if (pe->path_len == 0)
12979 continue;
12981 * Assume this path will fail. This will be corrected
12982 * in print_path_info() in case the path does suceeed.
12984 pe->data = (void *)got_error_path(pe->path,
12985 GOT_ERR_BAD_PATH);
12987 error = got_worktree_path_info(worktree, &paths,
12988 print_path_info, &paths, check_cancelled, NULL);
12989 if (error)
12990 goto done;
12991 TAILQ_FOREACH(pe, &paths, entry) {
12992 if (pe->data != NULL) {
12993 error = pe->data; /* bad path */
12994 break;
12998 done:
12999 if (pack_fds) {
13000 const struct got_error *pack_err =
13001 got_repo_pack_fds_close(pack_fds);
13002 if (error == NULL)
13003 error = pack_err;
13005 TAILQ_FOREACH(pe, &paths, entry)
13006 free((char *)pe->path);
13007 got_pathlist_free(&paths);
13008 free(cwd);
13009 free(id_str);
13010 free(uuidstr);
13011 return error;