portable: set next version
[got-portable.git] / got / got.c
blob7578e3c914d6acd6881cd996f0fbd10c94745f47
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>
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.
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.
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 <signal.h>
32 #include <stdio.h>
33 #include <stdlib.h>
34 #include <string.h>
35 #include <unistd.h>
36 #include <libgen.h>
37 #include <time.h>
38 #include <paths.h>
39 #include <regex.h>
40 #include <getopt.h>
42 #include "got_compat.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)
75 sigint_received = 1;
78 static void
79 catch_sigpipe(int signo)
81 sigpipe_received = 1;
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;
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, "" },
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);
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 }
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 [-hV] 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] [-I pattern] [-m message] "
351 "[-r repository-path] directory\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 struct stat st, st2;
400 FILE *fp = NULL;
401 size_t len, logmsg_len;
402 char *initial_content_stripped = NULL, *buf = NULL, *s;
404 *logmsg = NULL;
406 if (stat(logmsg_path, &st) == -1)
407 return got_error_from_errno2("stat", logmsg_path);
409 if (spawn_editor(editor, logmsg_path) == -1)
410 return got_error_from_errno("failed spawning editor");
412 if (stat(logmsg_path, &st2) == -1)
413 return got_error_from_errno("stat");
415 if (require_modification &&
416 st.st_mtime == st2.st_mtime && st.st_size == st2.st_size)
417 return got_error_msg(GOT_ERR_COMMIT_MSG_EMPTY,
418 "no changes made to commit message, aborting");
421 * Set up a stripped version of the initial content without comments
422 * and blank lines. We need this in order to check if the message
423 * has in fact been edited.
425 initial_content_stripped = malloc(initial_content_len + 1);
426 if (initial_content_stripped == NULL)
427 return got_error_from_errno("malloc");
428 initial_content_stripped[0] = '\0';
430 buf = strdup(initial_content);
431 if (buf == NULL) {
432 err = got_error_from_errno("strdup");
433 goto done;
435 s = buf;
436 len = 0;
437 while ((line = strsep(&s, "\n")) != NULL) {
438 if ((line[0] == '#' || (len == 0 && line[0] == '\n')))
439 continue; /* remove comments and leading empty lines */
440 len = strlcat(initial_content_stripped, line,
441 initial_content_len + 1);
442 if (len >= initial_content_len + 1) {
443 err = got_error(GOT_ERR_NO_SPACE);
444 goto done;
447 while (len > 0 && initial_content_stripped[len - 1] == '\n') {
448 initial_content_stripped[len - 1] = '\0';
449 len--;
452 logmsg_len = st2.st_size;
453 *logmsg = malloc(logmsg_len + 1);
454 if (*logmsg == NULL)
455 return got_error_from_errno("malloc");
456 (*logmsg)[0] = '\0';
458 fp = fopen(logmsg_path, "re");
459 if (fp == NULL) {
460 err = got_error_from_errno("fopen");
461 goto done;
464 len = 0;
465 while (getline(&line, &linesize, fp) != -1) {
466 if ((line[0] == '#' || (len == 0 && line[0] == '\n')))
467 continue; /* remove comments and leading empty lines */
468 len = strlcat(*logmsg, line, logmsg_len + 1);
469 if (len >= logmsg_len + 1) {
470 err = got_error(GOT_ERR_NO_SPACE);
471 goto done;
474 free(line);
475 if (ferror(fp)) {
476 err = got_ferror(fp, GOT_ERR_IO);
477 goto done;
479 while (len > 0 && (*logmsg)[len - 1] == '\n') {
480 (*logmsg)[len - 1] = '\0';
481 len--;
484 if (len == 0) {
485 err = got_error_msg(GOT_ERR_COMMIT_MSG_EMPTY,
486 "commit message cannot be empty, aborting");
487 goto done;
489 if (require_modification &&
490 strcmp(*logmsg, initial_content_stripped) == 0)
491 err = got_error_msg(GOT_ERR_COMMIT_MSG_EMPTY,
492 "no changes made to commit message, aborting");
493 done:
494 free(initial_content_stripped);
495 free(buf);
496 if (fp && fclose(fp) == EOF && err == NULL)
497 err = got_error_from_errno("fclose");
498 if (err) {
499 free(*logmsg);
500 *logmsg = NULL;
502 return err;
505 static const struct got_error *
506 collect_import_msg(char **logmsg, char **logmsg_path, const char *editor,
507 const char *path_dir, const char *branch_name)
509 char *initial_content = NULL;
510 const struct got_error *err = NULL;
511 int initial_content_len;
512 int fd = -1;
514 initial_content_len = asprintf(&initial_content,
515 "\n# %s to be imported to branch %s\n", path_dir,
516 branch_name);
517 if (initial_content_len == -1)
518 return got_error_from_errno("asprintf");
520 err = got_opentemp_named_fd(logmsg_path, &fd,
521 GOT_TMPDIR_STR "/got-importmsg", "");
522 if (err)
523 goto done;
525 if (write(fd, initial_content, initial_content_len) == -1) {
526 err = got_error_from_errno2("write", *logmsg_path);
527 goto done;
530 err = edit_logmsg(logmsg, editor, *logmsg_path, initial_content,
531 initial_content_len, 1);
532 done:
533 if (fd != -1 && close(fd) == -1 && err == NULL)
534 err = got_error_from_errno2("close", *logmsg_path);
535 free(initial_content);
536 if (err) {
537 free(*logmsg_path);
538 *logmsg_path = NULL;
540 return err;
543 static const struct got_error *
544 import_progress(void *arg, const char *path)
546 printf("A %s\n", path);
547 return NULL;
550 static const struct got_error *
551 valid_author(const char *author)
553 const char *email = author;
556 * Git' expects the author (or committer) to be in the form
557 * "name <email>", which are mostly free form (see the
558 * "committer" description in git-fast-import(1)). We're only
559 * doing this to avoid git's object parser breaking on commits
560 * we create.
563 while (*author && *author != '\n' && *author != '<' && *author != '>')
564 author++;
565 if (author != email && *author == '<' && *(author - 1) != ' ')
566 return got_error_fmt(GOT_ERR_COMMIT_BAD_AUTHOR, "%s: space "
567 "between author name and email required", email);
568 if (*author++ != '<')
569 return got_error_fmt(GOT_ERR_COMMIT_NO_EMAIL, "%s", email);
570 while (*author && *author != '\n' && *author != '<' && *author != '>')
571 author++;
572 if (strcmp(author, ">") != 0)
573 return got_error_fmt(GOT_ERR_COMMIT_NO_EMAIL, "%s", email);
574 return NULL;
577 static const struct got_error *
578 get_author(char **author, struct got_repository *repo,
579 struct got_worktree *worktree)
581 const struct got_error *err = NULL;
582 const char *got_author = NULL, *name, *email;
583 const struct got_gotconfig *worktree_conf = NULL, *repo_conf = NULL;
585 *author = NULL;
587 if (worktree)
588 worktree_conf = got_worktree_get_gotconfig(worktree);
589 repo_conf = got_repo_get_gotconfig(repo);
592 * Priority of potential author information sources, from most
593 * significant to least significant:
594 * 1) work tree's .got/got.conf file
595 * 2) repository's got.conf file
596 * 3) repository's git config file
597 * 4) environment variables
598 * 5) global git config files (in user's home directory or /etc)
601 if (worktree_conf)
602 got_author = got_gotconfig_get_author(worktree_conf);
603 if (got_author == NULL)
604 got_author = got_gotconfig_get_author(repo_conf);
605 if (got_author == NULL) {
606 name = got_repo_get_gitconfig_author_name(repo);
607 email = got_repo_get_gitconfig_author_email(repo);
608 if (name && email) {
609 if (asprintf(author, "%s <%s>", name, email) == -1)
610 return got_error_from_errno("asprintf");
611 return NULL;
614 got_author = getenv("GOT_AUTHOR");
615 if (got_author == NULL) {
616 name = got_repo_get_global_gitconfig_author_name(repo);
617 email = got_repo_get_global_gitconfig_author_email(
618 repo);
619 if (name && email) {
620 if (asprintf(author, "%s <%s>", name, email)
621 == -1)
622 return got_error_from_errno("asprintf");
623 return NULL;
625 /* TODO: Look up user in password database? */
626 return got_error(GOT_ERR_COMMIT_NO_AUTHOR);
630 *author = strdup(got_author);
631 if (*author == NULL)
632 return got_error_from_errno("strdup");
634 err = valid_author(*author);
635 if (err) {
636 free(*author);
637 *author = NULL;
639 return err;
642 static const struct got_error *
643 get_allowed_signers(char **allowed_signers, struct got_repository *repo,
644 struct got_worktree *worktree)
646 const char *got_allowed_signers = NULL;
647 const struct got_gotconfig *worktree_conf = NULL, *repo_conf = NULL;
649 *allowed_signers = NULL;
651 if (worktree)
652 worktree_conf = got_worktree_get_gotconfig(worktree);
653 repo_conf = got_repo_get_gotconfig(repo);
656 * Priority of potential author information sources, from most
657 * significant to least significant:
658 * 1) work tree's .got/got.conf file
659 * 2) repository's got.conf file
662 if (worktree_conf)
663 got_allowed_signers = got_gotconfig_get_allowed_signers_file(
664 worktree_conf);
665 if (got_allowed_signers == NULL)
666 got_allowed_signers = got_gotconfig_get_allowed_signers_file(
667 repo_conf);
669 if (got_allowed_signers) {
670 *allowed_signers = strdup(got_allowed_signers);
671 if (*allowed_signers == NULL)
672 return got_error_from_errno("strdup");
674 return NULL;
677 static const struct got_error *
678 get_revoked_signers(char **revoked_signers, struct got_repository *repo,
679 struct got_worktree *worktree)
681 const char *got_revoked_signers = NULL;
682 const struct got_gotconfig *worktree_conf = NULL, *repo_conf = NULL;
684 *revoked_signers = NULL;
686 if (worktree)
687 worktree_conf = got_worktree_get_gotconfig(worktree);
688 repo_conf = got_repo_get_gotconfig(repo);
691 * Priority of potential author information sources, from most
692 * significant to least significant:
693 * 1) work tree's .got/got.conf file
694 * 2) repository's got.conf file
697 if (worktree_conf)
698 got_revoked_signers = got_gotconfig_get_revoked_signers_file(
699 worktree_conf);
700 if (got_revoked_signers == NULL)
701 got_revoked_signers = got_gotconfig_get_revoked_signers_file(
702 repo_conf);
704 if (got_revoked_signers) {
705 *revoked_signers = strdup(got_revoked_signers);
706 if (*revoked_signers == NULL)
707 return got_error_from_errno("strdup");
709 return NULL;
712 static const struct got_error *
713 get_signer_id(char **signer_id, struct got_repository *repo,
714 struct got_worktree *worktree)
716 const char *got_signer_id = NULL;
717 const struct got_gotconfig *worktree_conf = NULL, *repo_conf = NULL;
719 *signer_id = NULL;
721 if (worktree)
722 worktree_conf = got_worktree_get_gotconfig(worktree);
723 repo_conf = got_repo_get_gotconfig(repo);
726 * Priority of potential author information sources, from most
727 * significant to least significant:
728 * 1) work tree's .got/got.conf file
729 * 2) repository's got.conf file
732 if (worktree_conf)
733 got_signer_id = got_gotconfig_get_signer_id(worktree_conf);
734 if (got_signer_id == NULL)
735 got_signer_id = got_gotconfig_get_signer_id(repo_conf);
737 if (got_signer_id) {
738 *signer_id = strdup(got_signer_id);
739 if (*signer_id == NULL)
740 return got_error_from_errno("strdup");
742 return NULL;
745 static const struct got_error *
746 get_gitconfig_path(char **gitconfig_path)
748 const char *homedir = getenv("HOME");
750 *gitconfig_path = NULL;
751 if (homedir) {
752 if (asprintf(gitconfig_path, "%s/.gitconfig", homedir) == -1)
753 return got_error_from_errno("asprintf");
756 return NULL;
759 static const struct got_error *
760 cmd_import(int argc, char *argv[])
762 const struct got_error *error = NULL;
763 char *path_dir = NULL, *repo_path = NULL, *logmsg = NULL;
764 char *gitconfig_path = NULL, *editor = NULL, *author = NULL;
765 const char *branch_name = NULL;
766 char *id_str = NULL, *logmsg_path = NULL;
767 char refname[PATH_MAX] = "refs/heads/";
768 struct got_repository *repo = NULL;
769 struct got_reference *branch_ref = NULL, *head_ref = NULL;
770 struct got_object_id *new_commit_id = NULL;
771 int ch, n = 0;
772 struct got_pathlist_head ignores;
773 struct got_pathlist_entry *pe;
774 int preserve_logmsg = 0;
775 int *pack_fds = NULL;
777 TAILQ_INIT(&ignores);
779 while ((ch = getopt(argc, argv, "b:I:m:r:")) != -1) {
780 switch (ch) {
781 case 'b':
782 branch_name = optarg;
783 break;
784 case 'I':
785 if (optarg[0] == '\0')
786 break;
787 error = got_pathlist_insert(&pe, &ignores, optarg,
788 NULL);
789 if (error)
790 goto done;
791 break;
792 case 'm':
793 logmsg = strdup(optarg);
794 if (logmsg == NULL) {
795 error = got_error_from_errno("strdup");
796 goto done;
798 break;
799 case 'r':
800 repo_path = realpath(optarg, NULL);
801 if (repo_path == NULL) {
802 error = got_error_from_errno2("realpath",
803 optarg);
804 goto done;
806 break;
807 default:
808 usage_import();
809 /* NOTREACHED */
813 argc -= optind;
814 argv += optind;
816 #ifndef PROFILE
817 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
818 "unveil",
819 NULL) == -1)
820 err(1, "pledge");
821 #endif
822 if (argc != 1)
823 usage_import();
825 if (repo_path == NULL) {
826 repo_path = getcwd(NULL, 0);
827 if (repo_path == NULL)
828 return got_error_from_errno("getcwd");
830 got_path_strip_trailing_slashes(repo_path);
831 error = get_gitconfig_path(&gitconfig_path);
832 if (error)
833 goto done;
834 error = got_repo_pack_fds_open(&pack_fds);
835 if (error != NULL)
836 goto done;
837 error = got_repo_open(&repo, repo_path, gitconfig_path, pack_fds);
838 if (error)
839 goto done;
841 error = get_author(&author, repo, NULL);
842 if (error)
843 return error;
846 * Don't let the user create a branch name with a leading '-'.
847 * While technically a valid reference name, this case is usually
848 * an unintended typo.
850 if (branch_name && branch_name[0] == '-')
851 return got_error_path(branch_name, GOT_ERR_REF_NAME_MINUS);
853 error = got_ref_open(&head_ref, repo, GOT_REF_HEAD, 0);
854 if (error && error->code != GOT_ERR_NOT_REF)
855 goto done;
857 if (branch_name)
858 n = strlcat(refname, branch_name, sizeof(refname));
859 else if (head_ref && got_ref_is_symbolic(head_ref))
860 n = strlcpy(refname, got_ref_get_symref_target(head_ref),
861 sizeof(refname));
862 else
863 n = strlcat(refname, "main", sizeof(refname));
864 if (n >= sizeof(refname)) {
865 error = got_error(GOT_ERR_NO_SPACE);
866 goto done;
869 error = got_ref_open(&branch_ref, repo, refname, 0);
870 if (error) {
871 if (error->code != GOT_ERR_NOT_REF)
872 goto done;
873 } else {
874 error = got_error_msg(GOT_ERR_BRANCH_EXISTS,
875 "import target branch already exists");
876 goto done;
879 path_dir = realpath(argv[0], NULL);
880 if (path_dir == NULL) {
881 error = got_error_from_errno2("realpath", argv[0]);
882 goto done;
884 got_path_strip_trailing_slashes(path_dir);
887 * unveil(2) traverses exec(2); if an editor is used we have
888 * to apply unveil after the log message has been written.
890 if (logmsg == NULL || strlen(logmsg) == 0) {
891 error = get_editor(&editor);
892 if (error)
893 goto done;
894 free(logmsg);
895 error = collect_import_msg(&logmsg, &logmsg_path, editor,
896 path_dir, refname);
897 if (error) {
898 if (error->code != GOT_ERR_COMMIT_MSG_EMPTY &&
899 logmsg_path != NULL)
900 preserve_logmsg = 1;
901 goto done;
905 if (unveil(path_dir, "r") != 0) {
906 error = got_error_from_errno2("unveil", path_dir);
907 if (logmsg_path)
908 preserve_logmsg = 1;
909 goto done;
912 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
913 if (error) {
914 if (logmsg_path)
915 preserve_logmsg = 1;
916 goto done;
919 error = got_repo_import(&new_commit_id, path_dir, logmsg,
920 author, &ignores, repo, import_progress, NULL);
921 if (error) {
922 if (logmsg_path)
923 preserve_logmsg = 1;
924 goto done;
927 error = got_ref_alloc(&branch_ref, refname, new_commit_id);
928 if (error) {
929 if (logmsg_path)
930 preserve_logmsg = 1;
931 goto done;
934 error = got_ref_write(branch_ref, repo);
935 if (error) {
936 if (logmsg_path)
937 preserve_logmsg = 1;
938 goto done;
941 error = got_object_id_str(&id_str, new_commit_id);
942 if (error) {
943 if (logmsg_path)
944 preserve_logmsg = 1;
945 goto done;
948 error = got_ref_open(&head_ref, repo, GOT_REF_HEAD, 0);
949 if (error) {
950 if (error->code != GOT_ERR_NOT_REF) {
951 if (logmsg_path)
952 preserve_logmsg = 1;
953 goto done;
956 error = got_ref_alloc_symref(&head_ref, GOT_REF_HEAD,
957 branch_ref);
958 if (error) {
959 if (logmsg_path)
960 preserve_logmsg = 1;
961 goto done;
964 error = got_ref_write(head_ref, repo);
965 if (error) {
966 if (logmsg_path)
967 preserve_logmsg = 1;
968 goto done;
972 printf("Created branch %s with commit %s\n",
973 got_ref_get_name(branch_ref), id_str);
974 done:
975 if (pack_fds) {
976 const struct got_error *pack_err =
977 got_repo_pack_fds_close(pack_fds);
978 if (error == NULL)
979 error = pack_err;
981 if (preserve_logmsg) {
982 fprintf(stderr, "%s: log message preserved in %s\n",
983 getprogname(), logmsg_path);
984 } else if (logmsg_path && unlink(logmsg_path) == -1 && error == NULL)
985 error = got_error_from_errno2("unlink", logmsg_path);
986 free(logmsg);
987 free(logmsg_path);
988 free(repo_path);
989 free(editor);
990 free(new_commit_id);
991 free(id_str);
992 free(author);
993 free(gitconfig_path);
994 if (branch_ref)
995 got_ref_close(branch_ref);
996 if (head_ref)
997 got_ref_close(head_ref);
998 return error;
1001 __dead static void
1002 usage_clone(void)
1004 fprintf(stderr, "usage: %s clone [-almqv] [-b branch] [-R reference] "
1005 "repository-URL [directory]\n", getprogname());
1006 exit(1);
1009 struct got_fetch_progress_arg {
1010 char last_scaled_size[FMT_SCALED_STRSIZE];
1011 int last_p_indexed;
1012 int last_p_resolved;
1013 int verbosity;
1015 struct got_repository *repo;
1017 int create_configs;
1018 int configs_created;
1019 struct {
1020 struct got_pathlist_head *symrefs;
1021 struct got_pathlist_head *wanted_branches;
1022 struct got_pathlist_head *wanted_refs;
1023 const char *proto;
1024 const char *host;
1025 const char *port;
1026 const char *remote_repo_path;
1027 const char *git_url;
1028 int fetch_all_branches;
1029 int mirror_references;
1030 } config_info;
1033 /* XXX forward declaration */
1034 static const struct got_error *
1035 create_config_files(const char *proto, const char *host, const char *port,
1036 const char *remote_repo_path, const char *git_url, int fetch_all_branches,
1037 int mirror_references, struct got_pathlist_head *symrefs,
1038 struct got_pathlist_head *wanted_branches,
1039 struct got_pathlist_head *wanted_refs, struct got_repository *repo);
1041 static const struct got_error *
1042 fetch_progress(void *arg, const char *message, off_t packfile_size,
1043 int nobj_total, int nobj_indexed, int nobj_loose, int nobj_resolved)
1045 const struct got_error *err = NULL;
1046 struct got_fetch_progress_arg *a = arg;
1047 char scaled_size[FMT_SCALED_STRSIZE];
1048 int p_indexed, p_resolved;
1049 int print_size = 0, print_indexed = 0, print_resolved = 0;
1052 * In order to allow a failed clone to be resumed with 'got fetch'
1053 * we try to create configuration files as soon as possible.
1054 * Once the server has sent information about its default branch
1055 * we have all required information.
1057 if (a->create_configs && !a->configs_created &&
1058 !TAILQ_EMPTY(a->config_info.symrefs)) {
1059 err = create_config_files(a->config_info.proto,
1060 a->config_info.host, a->config_info.port,
1061 a->config_info.remote_repo_path,
1062 a->config_info.git_url,
1063 a->config_info.fetch_all_branches,
1064 a->config_info.mirror_references,
1065 a->config_info.symrefs,
1066 a->config_info.wanted_branches,
1067 a->config_info.wanted_refs, a->repo);
1068 if (err)
1069 return err;
1070 a->configs_created = 1;
1073 if (a->verbosity < 0)
1074 return NULL;
1076 if (message && message[0] != '\0') {
1077 printf("\rserver: %s", message);
1078 fflush(stdout);
1079 return NULL;
1082 if (packfile_size > 0 || nobj_indexed > 0) {
1083 if (fmt_scaled(packfile_size, scaled_size) == 0 &&
1084 (a->last_scaled_size[0] == '\0' ||
1085 strcmp(scaled_size, a->last_scaled_size)) != 0) {
1086 print_size = 1;
1087 if (strlcpy(a->last_scaled_size, scaled_size,
1088 FMT_SCALED_STRSIZE) >= FMT_SCALED_STRSIZE)
1089 return got_error(GOT_ERR_NO_SPACE);
1091 if (nobj_indexed > 0) {
1092 p_indexed = (nobj_indexed * 100) / nobj_total;
1093 if (p_indexed != a->last_p_indexed) {
1094 a->last_p_indexed = p_indexed;
1095 print_indexed = 1;
1096 print_size = 1;
1099 if (nobj_resolved > 0) {
1100 p_resolved = (nobj_resolved * 100) /
1101 (nobj_total - nobj_loose);
1102 if (p_resolved != a->last_p_resolved) {
1103 a->last_p_resolved = p_resolved;
1104 print_resolved = 1;
1105 print_indexed = 1;
1106 print_size = 1;
1111 if (print_size || print_indexed || print_resolved)
1112 printf("\r");
1113 if (print_size)
1114 printf("%*s fetched", FMT_SCALED_STRSIZE - 2, scaled_size);
1115 if (print_indexed)
1116 printf("; indexing %d%%", p_indexed);
1117 if (print_resolved)
1118 printf("; resolving deltas %d%%", p_resolved);
1119 if (print_size || print_indexed || print_resolved)
1120 fflush(stdout);
1122 return NULL;
1125 static const struct got_error *
1126 create_symref(const char *refname, struct got_reference *target_ref,
1127 int verbosity, struct got_repository *repo)
1129 const struct got_error *err;
1130 struct got_reference *head_symref;
1132 err = got_ref_alloc_symref(&head_symref, refname, target_ref);
1133 if (err)
1134 return err;
1136 err = got_ref_write(head_symref, repo);
1137 if (err == NULL && verbosity > 0) {
1138 printf("Created reference %s: %s\n", GOT_REF_HEAD,
1139 got_ref_get_name(target_ref));
1141 got_ref_close(head_symref);
1142 return err;
1145 static const struct got_error *
1146 list_remote_refs(struct got_pathlist_head *symrefs,
1147 struct got_pathlist_head *refs)
1149 const struct got_error *err;
1150 struct got_pathlist_entry *pe;
1152 TAILQ_FOREACH(pe, symrefs, entry) {
1153 const char *refname = pe->path;
1154 const char *targetref = pe->data;
1156 printf("%s: %s\n", refname, targetref);
1159 TAILQ_FOREACH(pe, refs, entry) {
1160 const char *refname = pe->path;
1161 struct got_object_id *id = pe->data;
1162 char *id_str;
1164 err = got_object_id_str(&id_str, id);
1165 if (err)
1166 return err;
1167 printf("%s: %s\n", refname, id_str);
1168 free(id_str);
1171 return NULL;
1174 static const struct got_error *
1175 create_ref(const char *refname, struct got_object_id *id,
1176 int verbosity, struct got_repository *repo)
1178 const struct got_error *err = NULL;
1179 struct got_reference *ref;
1180 char *id_str;
1182 err = got_object_id_str(&id_str, id);
1183 if (err)
1184 return err;
1186 err = got_ref_alloc(&ref, refname, id);
1187 if (err)
1188 goto done;
1190 err = got_ref_write(ref, repo);
1191 got_ref_close(ref);
1193 if (err == NULL && verbosity >= 0)
1194 printf("Created reference %s: %s\n", refname, id_str);
1195 done:
1196 free(id_str);
1197 return err;
1200 static int
1201 match_wanted_ref(const char *refname, const char *wanted_ref)
1203 if (strncmp(refname, "refs/", 5) != 0)
1204 return 0;
1205 refname += 5;
1208 * Prevent fetching of references that won't make any
1209 * sense outside of the remote repository's context.
1211 if (strncmp(refname, "got/", 4) == 0)
1212 return 0;
1213 if (strncmp(refname, "remotes/", 8) == 0)
1214 return 0;
1216 if (strncmp(wanted_ref, "refs/", 5) == 0)
1217 wanted_ref += 5;
1219 /* Allow prefix match. */
1220 if (got_path_is_child(refname, wanted_ref, strlen(wanted_ref)))
1221 return 1;
1223 /* Allow exact match. */
1224 return (strcmp(refname, wanted_ref) == 0);
1227 static int
1228 is_wanted_ref(struct got_pathlist_head *wanted_refs, const char *refname)
1230 struct got_pathlist_entry *pe;
1232 TAILQ_FOREACH(pe, wanted_refs, entry) {
1233 if (match_wanted_ref(refname, pe->path))
1234 return 1;
1237 return 0;
1240 static const struct got_error *
1241 create_wanted_ref(const char *refname, struct got_object_id *id,
1242 const char *remote_repo_name, int verbosity, struct got_repository *repo)
1244 const struct got_error *err;
1245 char *remote_refname;
1247 if (strncmp("refs/", refname, 5) == 0)
1248 refname += 5;
1250 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
1251 remote_repo_name, refname) == -1)
1252 return got_error_from_errno("asprintf");
1254 err = create_ref(remote_refname, id, verbosity, repo);
1255 free(remote_refname);
1256 return err;
1259 static const struct got_error *
1260 create_gotconfig(const char *proto, const char *host, const char *port,
1261 const char *remote_repo_path, const char *default_branch,
1262 int fetch_all_branches, struct got_pathlist_head *wanted_branches,
1263 struct got_pathlist_head *wanted_refs, int mirror_references,
1264 struct got_repository *repo)
1266 const struct got_error *err = NULL;
1267 char *gotconfig_path = NULL;
1268 char *gotconfig = NULL;
1269 FILE *gotconfig_file = NULL;
1270 const char *branchname = NULL;
1271 char *branches = NULL, *refs = NULL;
1272 ssize_t n;
1274 if (!fetch_all_branches && !TAILQ_EMPTY(wanted_branches)) {
1275 struct got_pathlist_entry *pe;
1276 TAILQ_FOREACH(pe, wanted_branches, entry) {
1277 char *s;
1278 branchname = pe->path;
1279 if (strncmp(branchname, "refs/heads/", 11) == 0)
1280 branchname += 11;
1281 if (asprintf(&s, "%s\"%s\" ",
1282 branches ? branches : "", branchname) == -1) {
1283 err = got_error_from_errno("asprintf");
1284 goto done;
1286 free(branches);
1287 branches = s;
1289 } else if (!fetch_all_branches && default_branch) {
1290 branchname = default_branch;
1291 if (strncmp(branchname, "refs/heads/", 11) == 0)
1292 branchname += 11;
1293 if (asprintf(&branches, "\"%s\" ", branchname) == -1) {
1294 err = got_error_from_errno("asprintf");
1295 goto done;
1298 if (!TAILQ_EMPTY(wanted_refs)) {
1299 struct got_pathlist_entry *pe;
1300 TAILQ_FOREACH(pe, wanted_refs, entry) {
1301 char *s;
1302 const char *refname = pe->path;
1303 if (strncmp(refname, "refs/", 5) == 0)
1304 branchname += 5;
1305 if (asprintf(&s, "%s\"%s\" ",
1306 refs ? refs : "", refname) == -1) {
1307 err = got_error_from_errno("asprintf");
1308 goto done;
1310 free(refs);
1311 refs = s;
1315 /* Create got.conf(5). */
1316 gotconfig_path = got_repo_get_path_gotconfig(repo);
1317 if (gotconfig_path == NULL) {
1318 err = got_error_from_errno("got_repo_get_path_gotconfig");
1319 goto done;
1321 gotconfig_file = fopen(gotconfig_path, "ae");
1322 if (gotconfig_file == NULL) {
1323 err = got_error_from_errno2("fopen", gotconfig_path);
1324 goto done;
1326 if (asprintf(&gotconfig,
1327 "remote \"%s\" {\n"
1328 "\tserver %s\n"
1329 "\tprotocol %s\n"
1330 "%s%s%s"
1331 "\trepository \"%s\"\n"
1332 "%s%s%s"
1333 "%s%s%s"
1334 "%s"
1335 "%s"
1336 "}\n",
1337 GOT_FETCH_DEFAULT_REMOTE_NAME, host, proto,
1338 port ? "\tport " : "", port ? port : "", port ? "\n" : "",
1339 remote_repo_path, branches ? "\tbranch { " : "",
1340 branches ? branches : "", branches ? "}\n" : "",
1341 refs ? "\treference { " : "", refs ? refs : "", refs ? "}\n" : "",
1342 mirror_references ? "\tmirror_references yes\n" : "",
1343 fetch_all_branches ? "\tfetch_all_branches yes\n" : "") == -1) {
1344 err = got_error_from_errno("asprintf");
1345 goto done;
1347 n = fwrite(gotconfig, 1, strlen(gotconfig), gotconfig_file);
1348 if (n != strlen(gotconfig)) {
1349 err = got_ferror(gotconfig_file, GOT_ERR_IO);
1350 goto done;
1353 done:
1354 if (gotconfig_file && fclose(gotconfig_file) == EOF && err == NULL)
1355 err = got_error_from_errno2("fclose", gotconfig_path);
1356 free(gotconfig_path);
1357 free(branches);
1358 return err;
1361 static const struct got_error *
1362 create_gitconfig(const char *git_url, const char *default_branch,
1363 int fetch_all_branches, struct got_pathlist_head *wanted_branches,
1364 struct got_pathlist_head *wanted_refs, int mirror_references,
1365 struct got_repository *repo)
1367 const struct got_error *err = NULL;
1368 char *gitconfig_path = NULL;
1369 char *gitconfig = NULL;
1370 FILE *gitconfig_file = NULL;
1371 char *branches = NULL, *refs = NULL;
1372 const char *branchname;
1373 ssize_t n;
1375 /* Create a config file Git can understand. */
1376 gitconfig_path = got_repo_get_path_gitconfig(repo);
1377 if (gitconfig_path == NULL) {
1378 err = got_error_from_errno("got_repo_get_path_gitconfig");
1379 goto done;
1381 gitconfig_file = fopen(gitconfig_path, "ae");
1382 if (gitconfig_file == NULL) {
1383 err = got_error_from_errno2("fopen", gitconfig_path);
1384 goto done;
1386 if (fetch_all_branches) {
1387 if (mirror_references) {
1388 if (asprintf(&branches,
1389 "\tfetch = refs/heads/*:refs/heads/*\n") == -1) {
1390 err = got_error_from_errno("asprintf");
1391 goto done;
1393 } else if (asprintf(&branches,
1394 "\tfetch = refs/heads/*:refs/remotes/%s/*\n",
1395 GOT_FETCH_DEFAULT_REMOTE_NAME) == -1) {
1396 err = got_error_from_errno("asprintf");
1397 goto done;
1399 } else if (!TAILQ_EMPTY(wanted_branches)) {
1400 struct got_pathlist_entry *pe;
1401 TAILQ_FOREACH(pe, wanted_branches, entry) {
1402 char *s;
1403 branchname = pe->path;
1404 if (strncmp(branchname, "refs/heads/", 11) == 0)
1405 branchname += 11;
1406 if (mirror_references) {
1407 if (asprintf(&s,
1408 "%s\tfetch = refs/heads/%s:refs/heads/%s\n",
1409 branches ? branches : "",
1410 branchname, branchname) == -1) {
1411 err = got_error_from_errno("asprintf");
1412 goto done;
1414 } else if (asprintf(&s,
1415 "%s\tfetch = refs/heads/%s:refs/remotes/%s/%s\n",
1416 branches ? branches : "",
1417 branchname, GOT_FETCH_DEFAULT_REMOTE_NAME,
1418 branchname) == -1) {
1419 err = got_error_from_errno("asprintf");
1420 goto done;
1422 free(branches);
1423 branches = s;
1425 } else {
1427 * If the server specified a default branch, use just that one.
1428 * Otherwise fall back to fetching all branches on next fetch.
1430 if (default_branch) {
1431 branchname = default_branch;
1432 if (strncmp(branchname, "refs/heads/", 11) == 0)
1433 branchname += 11;
1434 } else
1435 branchname = "*"; /* fall back to all branches */
1436 if (mirror_references) {
1437 if (asprintf(&branches,
1438 "\tfetch = refs/heads/%s:refs/heads/%s\n",
1439 branchname, branchname) == -1) {
1440 err = got_error_from_errno("asprintf");
1441 goto done;
1443 } else if (asprintf(&branches,
1444 "\tfetch = refs/heads/%s:refs/remotes/%s/%s\n",
1445 branchname, GOT_FETCH_DEFAULT_REMOTE_NAME,
1446 branchname) == -1) {
1447 err = got_error_from_errno("asprintf");
1448 goto done;
1451 if (!TAILQ_EMPTY(wanted_refs)) {
1452 struct got_pathlist_entry *pe;
1453 TAILQ_FOREACH(pe, wanted_refs, entry) {
1454 char *s;
1455 const char *refname = pe->path;
1456 if (strncmp(refname, "refs/", 5) == 0)
1457 refname += 5;
1458 if (mirror_references) {
1459 if (asprintf(&s,
1460 "%s\tfetch = refs/%s:refs/%s\n",
1461 refs ? refs : "", refname, refname) == -1) {
1462 err = got_error_from_errno("asprintf");
1463 goto done;
1465 } else if (asprintf(&s,
1466 "%s\tfetch = refs/%s:refs/remotes/%s/%s\n",
1467 refs ? refs : "",
1468 refname, GOT_FETCH_DEFAULT_REMOTE_NAME,
1469 refname) == -1) {
1470 err = got_error_from_errno("asprintf");
1471 goto done;
1473 free(refs);
1474 refs = s;
1478 if (asprintf(&gitconfig,
1479 "[remote \"%s\"]\n"
1480 "\turl = %s\n"
1481 "%s"
1482 "%s"
1483 "\tfetch = refs/tags/*:refs/tags/*\n",
1484 GOT_FETCH_DEFAULT_REMOTE_NAME, git_url, branches ? branches : "",
1485 refs ? refs : "") == -1) {
1486 err = got_error_from_errno("asprintf");
1487 goto done;
1489 n = fwrite(gitconfig, 1, strlen(gitconfig), gitconfig_file);
1490 if (n != strlen(gitconfig)) {
1491 err = got_ferror(gitconfig_file, GOT_ERR_IO);
1492 goto done;
1494 done:
1495 if (gitconfig_file && fclose(gitconfig_file) == EOF && err == NULL)
1496 err = got_error_from_errno2("fclose", gitconfig_path);
1497 free(gitconfig_path);
1498 free(branches);
1499 return err;
1502 static const struct got_error *
1503 create_config_files(const char *proto, const char *host, const char *port,
1504 const char *remote_repo_path, const char *git_url, int fetch_all_branches,
1505 int mirror_references, struct got_pathlist_head *symrefs,
1506 struct got_pathlist_head *wanted_branches,
1507 struct got_pathlist_head *wanted_refs, struct got_repository *repo)
1509 const struct got_error *err = NULL;
1510 const char *default_branch = NULL;
1511 struct got_pathlist_entry *pe;
1514 * If we asked for a set of wanted branches then use the first
1515 * one of those.
1517 if (!TAILQ_EMPTY(wanted_branches)) {
1518 pe = TAILQ_FIRST(wanted_branches);
1519 default_branch = pe->path;
1520 } else {
1521 /* First HEAD ref listed by server is the default branch. */
1522 TAILQ_FOREACH(pe, symrefs, entry) {
1523 const char *refname = pe->path;
1524 const char *target = pe->data;
1526 if (strcmp(refname, GOT_REF_HEAD) != 0)
1527 continue;
1529 default_branch = target;
1530 break;
1534 /* Create got.conf(5). */
1535 err = create_gotconfig(proto, host, port, remote_repo_path,
1536 default_branch, fetch_all_branches, wanted_branches,
1537 wanted_refs, mirror_references, repo);
1538 if (err)
1539 return err;
1541 /* Create a config file Git can understand. */
1542 return create_gitconfig(git_url, default_branch, fetch_all_branches,
1543 wanted_branches, wanted_refs, mirror_references, repo);
1546 static const struct got_error *
1547 cmd_clone(int argc, char *argv[])
1549 const struct got_error *error = NULL;
1550 const char *uri, *dirname;
1551 char *proto, *host, *port, *repo_name, *server_path;
1552 char *default_destdir = NULL, *id_str = NULL;
1553 const char *repo_path;
1554 struct got_repository *repo = NULL;
1555 struct got_pathlist_head refs, symrefs, wanted_branches, wanted_refs;
1556 struct got_pathlist_entry *pe;
1557 struct got_object_id *pack_hash = NULL;
1558 int ch, fetchfd = -1, fetchstatus;
1559 pid_t fetchpid = -1;
1560 struct got_fetch_progress_arg fpa;
1561 char *git_url = NULL;
1562 int verbosity = 0, fetch_all_branches = 0, mirror_references = 0;
1563 int list_refs_only = 0;
1564 int *pack_fds = NULL;
1566 TAILQ_INIT(&refs);
1567 TAILQ_INIT(&symrefs);
1568 TAILQ_INIT(&wanted_branches);
1569 TAILQ_INIT(&wanted_refs);
1571 while ((ch = getopt(argc, argv, "ab:lmqR:v")) != -1) {
1572 switch (ch) {
1573 case 'a':
1574 fetch_all_branches = 1;
1575 break;
1576 case 'b':
1577 error = got_pathlist_append(&wanted_branches,
1578 optarg, NULL);
1579 if (error)
1580 return error;
1581 break;
1582 case 'l':
1583 list_refs_only = 1;
1584 break;
1585 case 'm':
1586 mirror_references = 1;
1587 break;
1588 case 'q':
1589 verbosity = -1;
1590 break;
1591 case 'R':
1592 error = got_pathlist_append(&wanted_refs,
1593 optarg, NULL);
1594 if (error)
1595 return error;
1596 break;
1597 case 'v':
1598 if (verbosity < 0)
1599 verbosity = 0;
1600 else if (verbosity < 3)
1601 verbosity++;
1602 break;
1603 default:
1604 usage_clone();
1605 break;
1608 argc -= optind;
1609 argv += optind;
1611 if (fetch_all_branches && !TAILQ_EMPTY(&wanted_branches))
1612 option_conflict('a', 'b');
1613 if (list_refs_only) {
1614 if (!TAILQ_EMPTY(&wanted_branches))
1615 option_conflict('l', 'b');
1616 if (fetch_all_branches)
1617 option_conflict('l', 'a');
1618 if (mirror_references)
1619 option_conflict('l', 'm');
1620 if (!TAILQ_EMPTY(&wanted_refs))
1621 option_conflict('l', 'R');
1624 uri = argv[0];
1626 if (argc == 1)
1627 dirname = NULL;
1628 else if (argc == 2)
1629 dirname = argv[1];
1630 else
1631 usage_clone();
1633 error = got_dial_parse_uri(&proto, &host, &port, &server_path,
1634 &repo_name, uri);
1635 if (error)
1636 goto done;
1638 if (asprintf(&git_url, "%s://%s%s%s%s%s", proto,
1639 host, port ? ":" : "", port ? port : "",
1640 server_path[0] != '/' ? "/" : "", server_path) == -1) {
1641 error = got_error_from_errno("asprintf");
1642 goto done;
1645 if (strcmp(proto, "git") == 0) {
1646 #ifndef PROFILE
1647 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
1648 "sendfd dns inet unveil", NULL) == -1)
1649 err(1, "pledge");
1650 #endif
1651 } else if (strcmp(proto, "git+ssh") == 0 ||
1652 strcmp(proto, "ssh") == 0) {
1653 #ifndef PROFILE
1654 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
1655 "sendfd unveil", NULL) == -1)
1656 err(1, "pledge");
1657 #endif
1658 } else if (strcmp(proto, "http") == 0 ||
1659 strcmp(proto, "git+http") == 0) {
1660 error = got_error_path(proto, GOT_ERR_NOT_IMPL);
1661 goto done;
1662 } else {
1663 error = got_error_path(proto, GOT_ERR_BAD_PROTO);
1664 goto done;
1666 if (dirname == NULL) {
1667 if (asprintf(&default_destdir, "%s.git", repo_name) == -1) {
1668 error = got_error_from_errno("asprintf");
1669 goto done;
1671 repo_path = default_destdir;
1672 } else
1673 repo_path = dirname;
1675 if (!list_refs_only) {
1676 error = got_path_mkdir(repo_path);
1677 if (error &&
1678 (!(error->code == GOT_ERR_ERRNO && errno == EISDIR) &&
1679 !(error->code == GOT_ERR_ERRNO && errno == EEXIST)))
1680 goto done;
1681 if (!got_path_dir_is_empty(repo_path)) {
1682 error = got_error_path(repo_path,
1683 GOT_ERR_DIR_NOT_EMPTY);
1684 goto done;
1688 error = got_dial_apply_unveil(proto);
1689 if (error)
1690 goto done;
1692 error = apply_unveil(repo_path, 0, NULL);
1693 if (error)
1694 goto done;
1696 if (verbosity >= 0)
1697 printf("Connecting to %s%s%s\n", host,
1698 port ? ":" : "", port ? port : "");
1700 error = got_fetch_connect(&fetchpid, &fetchfd, proto, host, port,
1701 server_path, verbosity);
1702 if (error)
1703 goto done;
1705 if (!list_refs_only) {
1706 error = got_repo_init(repo_path, NULL);
1707 if (error)
1708 goto done;
1709 error = got_repo_pack_fds_open(&pack_fds);
1710 if (error != NULL)
1711 goto done;
1712 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
1713 if (error)
1714 goto done;
1717 fpa.last_scaled_size[0] = '\0';
1718 fpa.last_p_indexed = -1;
1719 fpa.last_p_resolved = -1;
1720 fpa.verbosity = verbosity;
1721 fpa.create_configs = 1;
1722 fpa.configs_created = 0;
1723 fpa.repo = repo;
1724 fpa.config_info.symrefs = &symrefs;
1725 fpa.config_info.wanted_branches = &wanted_branches;
1726 fpa.config_info.wanted_refs = &wanted_refs;
1727 fpa.config_info.proto = proto;
1728 fpa.config_info.host = host;
1729 fpa.config_info.port = port;
1730 fpa.config_info.remote_repo_path = server_path;
1731 fpa.config_info.git_url = git_url;
1732 fpa.config_info.fetch_all_branches = fetch_all_branches;
1733 fpa.config_info.mirror_references = mirror_references;
1734 error = got_fetch_pack(&pack_hash, &refs, &symrefs,
1735 GOT_FETCH_DEFAULT_REMOTE_NAME, mirror_references,
1736 fetch_all_branches, &wanted_branches, &wanted_refs,
1737 list_refs_only, verbosity, fetchfd, repo,
1738 fetch_progress, &fpa);
1739 if (error)
1740 goto done;
1742 if (list_refs_only) {
1743 error = list_remote_refs(&symrefs, &refs);
1744 goto done;
1747 if (pack_hash == NULL) {
1748 error = got_error_fmt(GOT_ERR_FETCH_FAILED, "%s",
1749 "server sent an empty pack file");
1750 goto done;
1752 error = got_object_id_str(&id_str, pack_hash);
1753 if (error)
1754 goto done;
1755 if (verbosity >= 0)
1756 printf("\nFetched %s.pack\n", id_str);
1757 free(id_str);
1759 /* Set up references provided with the pack file. */
1760 TAILQ_FOREACH(pe, &refs, entry) {
1761 const char *refname = pe->path;
1762 struct got_object_id *id = pe->data;
1763 char *remote_refname;
1765 if (is_wanted_ref(&wanted_refs, refname) &&
1766 !mirror_references) {
1767 error = create_wanted_ref(refname, id,
1768 GOT_FETCH_DEFAULT_REMOTE_NAME,
1769 verbosity - 1, repo);
1770 if (error)
1771 goto done;
1772 continue;
1775 error = create_ref(refname, id, verbosity - 1, repo);
1776 if (error)
1777 goto done;
1779 if (mirror_references)
1780 continue;
1782 if (strncmp("refs/heads/", refname, 11) != 0)
1783 continue;
1785 if (asprintf(&remote_refname,
1786 "refs/remotes/%s/%s", GOT_FETCH_DEFAULT_REMOTE_NAME,
1787 refname + 11) == -1) {
1788 error = got_error_from_errno("asprintf");
1789 goto done;
1791 error = create_ref(remote_refname, id, verbosity - 1, repo);
1792 free(remote_refname);
1793 if (error)
1794 goto done;
1797 /* Set the HEAD reference if the server provided one. */
1798 TAILQ_FOREACH(pe, &symrefs, entry) {
1799 struct got_reference *target_ref;
1800 const char *refname = pe->path;
1801 const char *target = pe->data;
1802 char *remote_refname = NULL, *remote_target = NULL;
1804 if (strcmp(refname, GOT_REF_HEAD) != 0)
1805 continue;
1807 error = got_ref_open(&target_ref, repo, target, 0);
1808 if (error) {
1809 if (error->code == GOT_ERR_NOT_REF) {
1810 error = NULL;
1811 continue;
1813 goto done;
1816 error = create_symref(refname, target_ref, verbosity, repo);
1817 got_ref_close(target_ref);
1818 if (error)
1819 goto done;
1821 if (mirror_references)
1822 continue;
1824 if (strncmp("refs/heads/", target, 11) != 0)
1825 continue;
1827 if (asprintf(&remote_refname,
1828 "refs/remotes/%s/%s", GOT_FETCH_DEFAULT_REMOTE_NAME,
1829 refname) == -1) {
1830 error = got_error_from_errno("asprintf");
1831 goto done;
1833 if (asprintf(&remote_target,
1834 "refs/remotes/%s/%s", GOT_FETCH_DEFAULT_REMOTE_NAME,
1835 target + 11) == -1) {
1836 error = got_error_from_errno("asprintf");
1837 free(remote_refname);
1838 goto done;
1840 error = got_ref_open(&target_ref, repo, remote_target, 0);
1841 if (error) {
1842 free(remote_refname);
1843 free(remote_target);
1844 if (error->code == GOT_ERR_NOT_REF) {
1845 error = NULL;
1846 continue;
1848 goto done;
1850 error = create_symref(remote_refname, target_ref,
1851 verbosity - 1, repo);
1852 free(remote_refname);
1853 free(remote_target);
1854 got_ref_close(target_ref);
1855 if (error)
1856 goto done;
1858 if (pe == NULL) {
1860 * We failed to set the HEAD reference. If we asked for
1861 * a set of wanted branches use the first of one of those
1862 * which could be fetched instead.
1864 TAILQ_FOREACH(pe, &wanted_branches, entry) {
1865 const char *target = pe->path;
1866 struct got_reference *target_ref;
1868 error = got_ref_open(&target_ref, repo, target, 0);
1869 if (error) {
1870 if (error->code == GOT_ERR_NOT_REF) {
1871 error = NULL;
1872 continue;
1874 goto done;
1877 error = create_symref(GOT_REF_HEAD, target_ref,
1878 verbosity, repo);
1879 got_ref_close(target_ref);
1880 if (error)
1881 goto done;
1882 break;
1886 if (verbosity >= 0)
1887 printf("Created %s repository '%s'\n",
1888 mirror_references ? "mirrored" : "cloned", repo_path);
1889 done:
1890 if (pack_fds) {
1891 const struct got_error *pack_err =
1892 got_repo_pack_fds_close(pack_fds);
1893 if (error == NULL)
1894 error = pack_err;
1896 if (fetchpid > 0) {
1897 if (kill(fetchpid, SIGTERM) == -1)
1898 error = got_error_from_errno("kill");
1899 if (waitpid(fetchpid, &fetchstatus, 0) == -1 && error == NULL)
1900 error = got_error_from_errno("waitpid");
1902 if (fetchfd != -1 && close(fetchfd) == -1 && error == NULL)
1903 error = got_error_from_errno("close");
1904 if (repo) {
1905 const struct got_error *close_err = got_repo_close(repo);
1906 if (error == NULL)
1907 error = close_err;
1909 TAILQ_FOREACH(pe, &refs, entry) {
1910 free((void *)pe->path);
1911 free(pe->data);
1913 got_pathlist_free(&refs);
1914 TAILQ_FOREACH(pe, &symrefs, entry) {
1915 free((void *)pe->path);
1916 free(pe->data);
1918 got_pathlist_free(&symrefs);
1919 got_pathlist_free(&wanted_branches);
1920 got_pathlist_free(&wanted_refs);
1921 free(pack_hash);
1922 free(proto);
1923 free(host);
1924 free(port);
1925 free(server_path);
1926 free(repo_name);
1927 free(default_destdir);
1928 free(git_url);
1929 return error;
1932 static const struct got_error *
1933 update_ref(struct got_reference *ref, struct got_object_id *new_id,
1934 int replace_tags, int verbosity, struct got_repository *repo)
1936 const struct got_error *err = NULL;
1937 char *new_id_str = NULL;
1938 struct got_object_id *old_id = NULL;
1940 err = got_object_id_str(&new_id_str, new_id);
1941 if (err)
1942 goto done;
1944 if (!replace_tags &&
1945 strncmp(got_ref_get_name(ref), "refs/tags/", 10) == 0) {
1946 err = got_ref_resolve(&old_id, repo, ref);
1947 if (err)
1948 goto done;
1949 if (got_object_id_cmp(old_id, new_id) == 0)
1950 goto done;
1951 if (verbosity >= 0) {
1952 printf("Rejecting update of existing tag %s: %s\n",
1953 got_ref_get_name(ref), new_id_str);
1955 goto done;
1958 if (got_ref_is_symbolic(ref)) {
1959 if (verbosity >= 0) {
1960 printf("Replacing reference %s: %s\n",
1961 got_ref_get_name(ref),
1962 got_ref_get_symref_target(ref));
1964 err = got_ref_change_symref_to_ref(ref, new_id);
1965 if (err)
1966 goto done;
1967 err = got_ref_write(ref, repo);
1968 if (err)
1969 goto done;
1970 } else {
1971 err = got_ref_resolve(&old_id, repo, ref);
1972 if (err)
1973 goto done;
1974 if (got_object_id_cmp(old_id, new_id) == 0)
1975 goto done;
1977 err = got_ref_change_ref(ref, new_id);
1978 if (err)
1979 goto done;
1980 err = got_ref_write(ref, repo);
1981 if (err)
1982 goto done;
1985 if (verbosity >= 0)
1986 printf("Updated %s: %s\n", got_ref_get_name(ref),
1987 new_id_str);
1988 done:
1989 free(old_id);
1990 free(new_id_str);
1991 return err;
1994 static const struct got_error *
1995 update_symref(const char *refname, struct got_reference *target_ref,
1996 int verbosity, struct got_repository *repo)
1998 const struct got_error *err = NULL, *unlock_err;
1999 struct got_reference *symref;
2000 int symref_is_locked = 0;
2002 err = got_ref_open(&symref, repo, refname, 1);
2003 if (err) {
2004 if (err->code != GOT_ERR_NOT_REF)
2005 return err;
2006 err = got_ref_alloc_symref(&symref, refname, target_ref);
2007 if (err)
2008 goto done;
2010 err = got_ref_write(symref, repo);
2011 if (err)
2012 goto done;
2014 if (verbosity >= 0)
2015 printf("Created reference %s: %s\n",
2016 got_ref_get_name(symref),
2017 got_ref_get_symref_target(symref));
2018 } else {
2019 symref_is_locked = 1;
2021 if (strcmp(got_ref_get_symref_target(symref),
2022 got_ref_get_name(target_ref)) == 0)
2023 goto done;
2025 err = got_ref_change_symref(symref,
2026 got_ref_get_name(target_ref));
2027 if (err)
2028 goto done;
2030 err = got_ref_write(symref, repo);
2031 if (err)
2032 goto done;
2034 if (verbosity >= 0)
2035 printf("Updated %s: %s\n", got_ref_get_name(symref),
2036 got_ref_get_symref_target(symref));
2039 done:
2040 if (symref_is_locked) {
2041 unlock_err = got_ref_unlock(symref);
2042 if (unlock_err && err == NULL)
2043 err = unlock_err;
2045 got_ref_close(symref);
2046 return err;
2049 __dead static void
2050 usage_fetch(void)
2052 fprintf(stderr, "usage: %s fetch [-adlqtvX] [-b branch] "
2053 "[-R reference] [-r repository-path] [remote-repository]\n",
2054 getprogname());
2055 exit(1);
2058 static const struct got_error *
2059 delete_missing_ref(struct got_reference *ref,
2060 int verbosity, struct got_repository *repo)
2062 const struct got_error *err = NULL;
2063 struct got_object_id *id = NULL;
2064 char *id_str = NULL;
2066 if (got_ref_is_symbolic(ref)) {
2067 err = got_ref_delete(ref, repo);
2068 if (err)
2069 return err;
2070 if (verbosity >= 0) {
2071 printf("Deleted %s: %s\n",
2072 got_ref_get_name(ref),
2073 got_ref_get_symref_target(ref));
2075 } else {
2076 err = got_ref_resolve(&id, repo, ref);
2077 if (err)
2078 return err;
2079 err = got_object_id_str(&id_str, id);
2080 if (err)
2081 goto done;
2083 err = got_ref_delete(ref, repo);
2084 if (err)
2085 goto done;
2086 if (verbosity >= 0) {
2087 printf("Deleted %s: %s\n",
2088 got_ref_get_name(ref), id_str);
2091 done:
2092 free(id);
2093 free(id_str);
2094 return NULL;
2097 static const struct got_error *
2098 delete_missing_refs(struct got_pathlist_head *their_refs,
2099 struct got_pathlist_head *their_symrefs,
2100 const struct got_remote_repo *remote,
2101 int verbosity, struct got_repository *repo)
2103 const struct got_error *err = NULL, *unlock_err;
2104 struct got_reflist_head my_refs;
2105 struct got_reflist_entry *re;
2106 struct got_pathlist_entry *pe;
2107 char *remote_namespace = NULL;
2108 char *local_refname = NULL;
2110 TAILQ_INIT(&my_refs);
2112 if (asprintf(&remote_namespace, "refs/remotes/%s/", remote->name)
2113 == -1)
2114 return got_error_from_errno("asprintf");
2116 err = got_ref_list(&my_refs, repo, NULL, got_ref_cmp_by_name, NULL);
2117 if (err)
2118 goto done;
2120 TAILQ_FOREACH(re, &my_refs, entry) {
2121 const char *refname = got_ref_get_name(re->ref);
2122 const char *their_refname;
2124 if (remote->mirror_references) {
2125 their_refname = refname;
2126 } else {
2127 if (strncmp(refname, remote_namespace,
2128 strlen(remote_namespace)) == 0) {
2129 if (strcmp(refname + strlen(remote_namespace),
2130 GOT_REF_HEAD) == 0)
2131 continue;
2132 if (asprintf(&local_refname, "refs/heads/%s",
2133 refname + strlen(remote_namespace)) == -1) {
2134 err = got_error_from_errno("asprintf");
2135 goto done;
2137 } else if (strncmp(refname, "refs/tags/", 10) != 0)
2138 continue;
2140 their_refname = local_refname;
2143 TAILQ_FOREACH(pe, their_refs, entry) {
2144 if (strcmp(their_refname, pe->path) == 0)
2145 break;
2147 if (pe != NULL)
2148 continue;
2150 TAILQ_FOREACH(pe, their_symrefs, entry) {
2151 if (strcmp(their_refname, pe->path) == 0)
2152 break;
2154 if (pe != NULL)
2155 continue;
2157 err = delete_missing_ref(re->ref, verbosity, repo);
2158 if (err)
2159 break;
2161 if (local_refname) {
2162 struct got_reference *ref;
2163 err = got_ref_open(&ref, repo, local_refname, 1);
2164 if (err) {
2165 if (err->code != GOT_ERR_NOT_REF)
2166 break;
2167 free(local_refname);
2168 local_refname = NULL;
2169 continue;
2171 err = delete_missing_ref(ref, verbosity, repo);
2172 if (err)
2173 break;
2174 unlock_err = got_ref_unlock(ref);
2175 got_ref_close(ref);
2176 if (unlock_err && err == NULL) {
2177 err = unlock_err;
2178 break;
2181 free(local_refname);
2182 local_refname = NULL;
2185 done:
2186 got_ref_list_free(&my_refs);
2187 free(remote_namespace);
2188 free(local_refname);
2189 return err;
2192 static const struct got_error *
2193 update_wanted_ref(const char *refname, struct got_object_id *id,
2194 const char *remote_repo_name, int verbosity, struct got_repository *repo)
2196 const struct got_error *err, *unlock_err;
2197 char *remote_refname;
2198 struct got_reference *ref;
2200 if (strncmp("refs/", refname, 5) == 0)
2201 refname += 5;
2203 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
2204 remote_repo_name, refname) == -1)
2205 return got_error_from_errno("asprintf");
2207 err = got_ref_open(&ref, repo, remote_refname, 1);
2208 if (err) {
2209 if (err->code != GOT_ERR_NOT_REF)
2210 goto done;
2211 err = create_ref(remote_refname, id, verbosity, repo);
2212 } else {
2213 err = update_ref(ref, id, 0, verbosity, repo);
2214 unlock_err = got_ref_unlock(ref);
2215 if (unlock_err && err == NULL)
2216 err = unlock_err;
2217 got_ref_close(ref);
2219 done:
2220 free(remote_refname);
2221 return err;
2224 static const struct got_error *
2225 delete_ref(struct got_repository *repo, struct got_reference *ref)
2227 const struct got_error *err = NULL;
2228 struct got_object_id *id = NULL;
2229 char *id_str = NULL;
2230 const char *target;
2232 if (got_ref_is_symbolic(ref)) {
2233 target = got_ref_get_symref_target(ref);
2234 } else {
2235 err = got_ref_resolve(&id, repo, ref);
2236 if (err)
2237 goto done;
2238 err = got_object_id_str(&id_str, id);
2239 if (err)
2240 goto done;
2241 target = id_str;
2244 err = got_ref_delete(ref, repo);
2245 if (err)
2246 goto done;
2248 printf("Deleted %s: %s\n", got_ref_get_name(ref), target);
2249 done:
2250 free(id);
2251 free(id_str);
2252 return err;
2255 static const struct got_error *
2256 delete_refs_for_remote(struct got_repository *repo, const char *remote_name)
2258 const struct got_error *err = NULL;
2259 struct got_reflist_head refs;
2260 struct got_reflist_entry *re;
2261 char *prefix;
2263 TAILQ_INIT(&refs);
2265 if (asprintf(&prefix, "refs/remotes/%s", remote_name) == -1) {
2266 err = got_error_from_errno("asprintf");
2267 goto done;
2269 err = got_ref_list(&refs, repo, prefix, got_ref_cmp_by_name, NULL);
2270 if (err)
2271 goto done;
2273 TAILQ_FOREACH(re, &refs, entry)
2274 delete_ref(repo, re->ref);
2275 done:
2276 got_ref_list_free(&refs);
2277 return err;
2280 static const struct got_error *
2281 cmd_fetch(int argc, char *argv[])
2283 const struct got_error *error = NULL, *unlock_err;
2284 char *cwd = NULL, *repo_path = NULL;
2285 const char *remote_name;
2286 char *proto = NULL, *host = NULL, *port = NULL;
2287 char *repo_name = NULL, *server_path = NULL;
2288 const struct got_remote_repo *remotes, *remote = NULL;
2289 int nremotes;
2290 char *id_str = NULL;
2291 struct got_repository *repo = NULL;
2292 struct got_worktree *worktree = NULL;
2293 const struct got_gotconfig *repo_conf = NULL, *worktree_conf = NULL;
2294 struct got_pathlist_head refs, symrefs, wanted_branches, wanted_refs;
2295 struct got_pathlist_entry *pe;
2296 struct got_object_id *pack_hash = NULL;
2297 int i, ch, fetchfd = -1, fetchstatus;
2298 pid_t fetchpid = -1;
2299 struct got_fetch_progress_arg fpa;
2300 int verbosity = 0, fetch_all_branches = 0, list_refs_only = 0;
2301 int delete_refs = 0, replace_tags = 0, delete_remote = 0;
2302 int *pack_fds = NULL;
2304 TAILQ_INIT(&refs);
2305 TAILQ_INIT(&symrefs);
2306 TAILQ_INIT(&wanted_branches);
2307 TAILQ_INIT(&wanted_refs);
2309 while ((ch = getopt(argc, argv, "ab:dlqR:r:tvX")) != -1) {
2310 switch (ch) {
2311 case 'a':
2312 fetch_all_branches = 1;
2313 break;
2314 case 'b':
2315 error = got_pathlist_append(&wanted_branches,
2316 optarg, NULL);
2317 if (error)
2318 return error;
2319 break;
2320 case 'd':
2321 delete_refs = 1;
2322 break;
2323 case 'l':
2324 list_refs_only = 1;
2325 break;
2326 case 'q':
2327 verbosity = -1;
2328 break;
2329 case 'R':
2330 error = got_pathlist_append(&wanted_refs,
2331 optarg, NULL);
2332 if (error)
2333 return error;
2334 break;
2335 case 'r':
2336 repo_path = realpath(optarg, NULL);
2337 if (repo_path == NULL)
2338 return got_error_from_errno2("realpath",
2339 optarg);
2340 got_path_strip_trailing_slashes(repo_path);
2341 break;
2342 case 't':
2343 replace_tags = 1;
2344 break;
2345 case 'v':
2346 if (verbosity < 0)
2347 verbosity = 0;
2348 else if (verbosity < 3)
2349 verbosity++;
2350 break;
2351 case 'X':
2352 delete_remote = 1;
2353 break;
2354 default:
2355 usage_fetch();
2356 break;
2359 argc -= optind;
2360 argv += optind;
2362 if (fetch_all_branches && !TAILQ_EMPTY(&wanted_branches))
2363 option_conflict('a', 'b');
2364 if (list_refs_only) {
2365 if (!TAILQ_EMPTY(&wanted_branches))
2366 option_conflict('l', 'b');
2367 if (fetch_all_branches)
2368 option_conflict('l', 'a');
2369 if (delete_refs)
2370 option_conflict('l', 'd');
2371 if (delete_remote)
2372 option_conflict('l', 'X');
2374 if (delete_remote) {
2375 if (fetch_all_branches)
2376 option_conflict('X', 'a');
2377 if (!TAILQ_EMPTY(&wanted_branches))
2378 option_conflict('X', 'b');
2379 if (delete_refs)
2380 option_conflict('X', 'd');
2381 if (replace_tags)
2382 option_conflict('X', 't');
2383 if (!TAILQ_EMPTY(&wanted_refs))
2384 option_conflict('X', 'R');
2387 if (argc == 0) {
2388 if (delete_remote)
2389 errx(1, "-X option requires a remote name");
2390 remote_name = GOT_FETCH_DEFAULT_REMOTE_NAME;
2391 } else if (argc == 1)
2392 remote_name = argv[0];
2393 else
2394 usage_fetch();
2396 cwd = getcwd(NULL, 0);
2397 if (cwd == NULL) {
2398 error = got_error_from_errno("getcwd");
2399 goto done;
2402 error = got_repo_pack_fds_open(&pack_fds);
2403 if (error != NULL)
2404 goto done;
2406 if (repo_path == NULL) {
2407 error = got_worktree_open(&worktree, cwd);
2408 if (error && error->code != GOT_ERR_NOT_WORKTREE)
2409 goto done;
2410 else
2411 error = NULL;
2412 if (worktree) {
2413 repo_path =
2414 strdup(got_worktree_get_repo_path(worktree));
2415 if (repo_path == NULL)
2416 error = got_error_from_errno("strdup");
2417 if (error)
2418 goto done;
2419 } else {
2420 repo_path = strdup(cwd);
2421 if (repo_path == NULL) {
2422 error = got_error_from_errno("strdup");
2423 goto done;
2428 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
2429 if (error)
2430 goto done;
2432 if (delete_remote) {
2433 error = delete_refs_for_remote(repo, remote_name);
2434 goto done; /* nothing else to do */
2437 if (worktree) {
2438 worktree_conf = got_worktree_get_gotconfig(worktree);
2439 if (worktree_conf) {
2440 got_gotconfig_get_remotes(&nremotes, &remotes,
2441 worktree_conf);
2442 for (i = 0; i < nremotes; i++) {
2443 if (strcmp(remotes[i].name, remote_name) == 0) {
2444 remote = &remotes[i];
2445 break;
2450 if (remote == NULL) {
2451 repo_conf = got_repo_get_gotconfig(repo);
2452 if (repo_conf) {
2453 got_gotconfig_get_remotes(&nremotes, &remotes,
2454 repo_conf);
2455 for (i = 0; i < nremotes; i++) {
2456 if (strcmp(remotes[i].name, remote_name) == 0) {
2457 remote = &remotes[i];
2458 break;
2463 if (remote == NULL) {
2464 got_repo_get_gitconfig_remotes(&nremotes, &remotes, repo);
2465 for (i = 0; i < nremotes; i++) {
2466 if (strcmp(remotes[i].name, remote_name) == 0) {
2467 remote = &remotes[i];
2468 break;
2472 if (remote == NULL) {
2473 error = got_error_path(remote_name, GOT_ERR_NO_REMOTE);
2474 goto done;
2477 if (TAILQ_EMPTY(&wanted_branches)) {
2478 if (!fetch_all_branches)
2479 fetch_all_branches = remote->fetch_all_branches;
2480 for (i = 0; i < remote->nfetch_branches; i++) {
2481 got_pathlist_append(&wanted_branches,
2482 remote->fetch_branches[i], NULL);
2485 if (TAILQ_EMPTY(&wanted_refs)) {
2486 for (i = 0; i < remote->nfetch_refs; i++) {
2487 got_pathlist_append(&wanted_refs,
2488 remote->fetch_refs[i], NULL);
2492 error = got_dial_parse_uri(&proto, &host, &port, &server_path,
2493 &repo_name, remote->fetch_url);
2494 if (error)
2495 goto done;
2497 if (strcmp(proto, "git") == 0) {
2498 #ifndef PROFILE
2499 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
2500 "sendfd dns inet unveil", NULL) == -1)
2501 err(1, "pledge");
2502 #endif
2503 } else if (strcmp(proto, "git+ssh") == 0 ||
2504 strcmp(proto, "ssh") == 0) {
2505 #ifndef PROFILE
2506 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
2507 "sendfd unveil", NULL) == -1)
2508 err(1, "pledge");
2509 #endif
2510 } else if (strcmp(proto, "http") == 0 ||
2511 strcmp(proto, "git+http") == 0) {
2512 error = got_error_path(proto, GOT_ERR_NOT_IMPL);
2513 goto done;
2514 } else {
2515 error = got_error_path(proto, GOT_ERR_BAD_PROTO);
2516 goto done;
2519 error = got_dial_apply_unveil(proto);
2520 if (error)
2521 goto done;
2523 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
2524 if (error)
2525 goto done;
2527 if (verbosity >= 0)
2528 printf("Connecting to \"%s\" %s%s%s\n", remote->name, host,
2529 port ? ":" : "", port ? port : "");
2531 error = got_fetch_connect(&fetchpid, &fetchfd, proto, host, port,
2532 server_path, verbosity);
2533 if (error)
2534 goto done;
2536 fpa.last_scaled_size[0] = '\0';
2537 fpa.last_p_indexed = -1;
2538 fpa.last_p_resolved = -1;
2539 fpa.verbosity = verbosity;
2540 fpa.repo = repo;
2541 fpa.create_configs = 0;
2542 fpa.configs_created = 0;
2543 memset(&fpa.config_info, 0, sizeof(fpa.config_info));
2544 error = got_fetch_pack(&pack_hash, &refs, &symrefs, remote->name,
2545 remote->mirror_references, fetch_all_branches, &wanted_branches,
2546 &wanted_refs, list_refs_only, verbosity, fetchfd, repo,
2547 fetch_progress, &fpa);
2548 if (error)
2549 goto done;
2551 if (list_refs_only) {
2552 error = list_remote_refs(&symrefs, &refs);
2553 goto done;
2556 if (pack_hash == NULL) {
2557 if (verbosity >= 0)
2558 printf("Already up-to-date\n");
2559 } else if (verbosity >= 0) {
2560 error = got_object_id_str(&id_str, pack_hash);
2561 if (error)
2562 goto done;
2563 printf("\nFetched %s.pack\n", id_str);
2564 free(id_str);
2565 id_str = NULL;
2568 /* Update references provided with the pack file. */
2569 TAILQ_FOREACH(pe, &refs, entry) {
2570 const char *refname = pe->path;
2571 struct got_object_id *id = pe->data;
2572 struct got_reference *ref;
2573 char *remote_refname;
2575 if (is_wanted_ref(&wanted_refs, refname) &&
2576 !remote->mirror_references) {
2577 error = update_wanted_ref(refname, id,
2578 remote->name, verbosity, repo);
2579 if (error)
2580 goto done;
2581 continue;
2584 if (remote->mirror_references ||
2585 strncmp("refs/tags/", refname, 10) == 0) {
2586 error = got_ref_open(&ref, repo, refname, 1);
2587 if (error) {
2588 if (error->code != GOT_ERR_NOT_REF)
2589 goto done;
2590 error = create_ref(refname, id, verbosity,
2591 repo);
2592 if (error)
2593 goto done;
2594 } else {
2595 error = update_ref(ref, id, replace_tags,
2596 verbosity, repo);
2597 unlock_err = got_ref_unlock(ref);
2598 if (unlock_err && error == NULL)
2599 error = unlock_err;
2600 got_ref_close(ref);
2601 if (error)
2602 goto done;
2604 } else if (strncmp("refs/heads/", refname, 11) == 0) {
2605 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
2606 remote_name, refname + 11) == -1) {
2607 error = got_error_from_errno("asprintf");
2608 goto done;
2611 error = got_ref_open(&ref, repo, remote_refname, 1);
2612 if (error) {
2613 if (error->code != GOT_ERR_NOT_REF)
2614 goto done;
2615 error = create_ref(remote_refname, id,
2616 verbosity, repo);
2617 if (error)
2618 goto done;
2619 } else {
2620 error = update_ref(ref, id, replace_tags,
2621 verbosity, repo);
2622 unlock_err = got_ref_unlock(ref);
2623 if (unlock_err && error == NULL)
2624 error = unlock_err;
2625 got_ref_close(ref);
2626 if (error)
2627 goto done;
2630 /* Also create a local branch if none exists yet. */
2631 error = got_ref_open(&ref, repo, refname, 1);
2632 if (error) {
2633 if (error->code != GOT_ERR_NOT_REF)
2634 goto done;
2635 error = create_ref(refname, id, verbosity,
2636 repo);
2637 if (error)
2638 goto done;
2639 } else {
2640 unlock_err = got_ref_unlock(ref);
2641 if (unlock_err && error == NULL)
2642 error = unlock_err;
2643 got_ref_close(ref);
2647 if (delete_refs) {
2648 error = delete_missing_refs(&refs, &symrefs, remote,
2649 verbosity, repo);
2650 if (error)
2651 goto done;
2654 if (!remote->mirror_references) {
2655 /* Update remote HEAD reference if the server provided one. */
2656 TAILQ_FOREACH(pe, &symrefs, entry) {
2657 struct got_reference *target_ref;
2658 const char *refname = pe->path;
2659 const char *target = pe->data;
2660 char *remote_refname = NULL, *remote_target = NULL;
2662 if (strcmp(refname, GOT_REF_HEAD) != 0)
2663 continue;
2665 if (strncmp("refs/heads/", target, 11) != 0)
2666 continue;
2668 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
2669 remote->name, refname) == -1) {
2670 error = got_error_from_errno("asprintf");
2671 goto done;
2673 if (asprintf(&remote_target, "refs/remotes/%s/%s",
2674 remote->name, target + 11) == -1) {
2675 error = got_error_from_errno("asprintf");
2676 free(remote_refname);
2677 goto done;
2680 error = got_ref_open(&target_ref, repo, remote_target,
2682 if (error) {
2683 free(remote_refname);
2684 free(remote_target);
2685 if (error->code == GOT_ERR_NOT_REF) {
2686 error = NULL;
2687 continue;
2689 goto done;
2691 error = update_symref(remote_refname, target_ref,
2692 verbosity, repo);
2693 free(remote_refname);
2694 free(remote_target);
2695 got_ref_close(target_ref);
2696 if (error)
2697 goto done;
2700 done:
2701 if (fetchpid > 0) {
2702 if (kill(fetchpid, SIGTERM) == -1)
2703 error = got_error_from_errno("kill");
2704 if (waitpid(fetchpid, &fetchstatus, 0) == -1 && error == NULL)
2705 error = got_error_from_errno("waitpid");
2707 if (fetchfd != -1 && close(fetchfd) == -1 && error == NULL)
2708 error = got_error_from_errno("close");
2709 if (repo) {
2710 const struct got_error *close_err = got_repo_close(repo);
2711 if (error == NULL)
2712 error = close_err;
2714 if (worktree)
2715 got_worktree_close(worktree);
2716 if (pack_fds) {
2717 const struct got_error *pack_err =
2718 got_repo_pack_fds_close(pack_fds);
2719 if (error == NULL)
2720 error = pack_err;
2722 TAILQ_FOREACH(pe, &refs, entry) {
2723 free((void *)pe->path);
2724 free(pe->data);
2726 got_pathlist_free(&refs);
2727 TAILQ_FOREACH(pe, &symrefs, entry) {
2728 free((void *)pe->path);
2729 free(pe->data);
2731 got_pathlist_free(&symrefs);
2732 got_pathlist_free(&wanted_branches);
2733 got_pathlist_free(&wanted_refs);
2734 free(id_str);
2735 free(cwd);
2736 free(repo_path);
2737 free(pack_hash);
2738 free(proto);
2739 free(host);
2740 free(port);
2741 free(server_path);
2742 free(repo_name);
2743 return error;
2747 __dead static void
2748 usage_checkout(void)
2750 fprintf(stderr, "usage: %s checkout [-Eq] [-b branch] [-c commit] "
2751 "[-p path-prefix] repository-path [work-tree-path]\n",
2752 getprogname());
2753 exit(1);
2756 static void
2757 show_worktree_base_ref_warning(void)
2759 fprintf(stderr, "%s: warning: could not create a reference "
2760 "to the work tree's base commit; the commit could be "
2761 "garbage-collected by Git or 'gotadmin cleanup'; making the "
2762 "repository writable and running 'got update' will prevent this\n",
2763 getprogname());
2766 struct got_checkout_progress_arg {
2767 const char *worktree_path;
2768 int had_base_commit_ref_error;
2769 int verbosity;
2772 static const struct got_error *
2773 checkout_progress(void *arg, unsigned char status, const char *path)
2775 struct got_checkout_progress_arg *a = arg;
2777 /* Base commit bump happens silently. */
2778 if (status == GOT_STATUS_BUMP_BASE)
2779 return NULL;
2781 if (status == GOT_STATUS_BASE_REF_ERR) {
2782 a->had_base_commit_ref_error = 1;
2783 return NULL;
2786 while (path[0] == '/')
2787 path++;
2789 if (a->verbosity >= 0)
2790 printf("%c %s/%s\n", status, a->worktree_path, path);
2792 return NULL;
2795 static const struct got_error *
2796 check_cancelled(void *arg)
2798 if (sigint_received || sigpipe_received)
2799 return got_error(GOT_ERR_CANCELLED);
2800 return NULL;
2803 static const struct got_error *
2804 check_linear_ancestry(struct got_object_id *commit_id,
2805 struct got_object_id *base_commit_id, int allow_forwards_in_time_only,
2806 struct got_repository *repo)
2808 const struct got_error *err = NULL;
2809 struct got_object_id *yca_id;
2811 err = got_commit_graph_find_youngest_common_ancestor(&yca_id,
2812 commit_id, base_commit_id, 1, repo, check_cancelled, NULL);
2813 if (err)
2814 return err;
2816 if (yca_id == NULL)
2817 return got_error(GOT_ERR_ANCESTRY);
2820 * Require a straight line of history between the target commit
2821 * and the work tree's base commit.
2823 * Non-linear situations such as this require a rebase:
2825 * (commit) D F (base_commit)
2826 * \ /
2827 * C E
2828 * \ /
2829 * B (yca)
2833 * 'got update' only handles linear cases:
2834 * Update forwards in time: A (base/yca) - B - C - D (commit)
2835 * Update backwards in time: D (base) - C - B - A (commit/yca)
2837 if (allow_forwards_in_time_only) {
2838 if (got_object_id_cmp(base_commit_id, yca_id) != 0)
2839 return got_error(GOT_ERR_ANCESTRY);
2840 } else if (got_object_id_cmp(commit_id, yca_id) != 0 &&
2841 got_object_id_cmp(base_commit_id, yca_id) != 0)
2842 return got_error(GOT_ERR_ANCESTRY);
2844 free(yca_id);
2845 return NULL;
2848 static const struct got_error *
2849 check_same_branch(struct got_object_id *commit_id,
2850 struct got_reference *head_ref, struct got_object_id *yca_id,
2851 struct got_repository *repo)
2853 const struct got_error *err = NULL;
2854 struct got_commit_graph *graph = NULL;
2855 struct got_object_id *head_commit_id = NULL;
2856 int is_same_branch = 0;
2858 err = got_ref_resolve(&head_commit_id, repo, head_ref);
2859 if (err)
2860 goto done;
2862 if (got_object_id_cmp(head_commit_id, commit_id) == 0) {
2863 is_same_branch = 1;
2864 goto done;
2866 if (yca_id && got_object_id_cmp(commit_id, yca_id) == 0) {
2867 is_same_branch = 1;
2868 goto done;
2871 err = got_commit_graph_open(&graph, "/", 1);
2872 if (err)
2873 goto done;
2875 err = got_commit_graph_iter_start(graph, head_commit_id, repo,
2876 check_cancelled, NULL);
2877 if (err)
2878 goto done;
2880 for (;;) {
2881 struct got_object_id id;
2883 err = got_commit_graph_iter_next(&id, graph, repo,
2884 check_cancelled, NULL);
2885 if (err) {
2886 if (err->code == GOT_ERR_ITER_COMPLETED)
2887 err = NULL;
2888 break;
2891 if (yca_id && got_object_id_cmp(&id, yca_id) == 0)
2892 break;
2893 if (got_object_id_cmp(&id, commit_id) == 0) {
2894 is_same_branch = 1;
2895 break;
2898 done:
2899 if (graph)
2900 got_commit_graph_close(graph);
2901 free(head_commit_id);
2902 if (!err && !is_same_branch)
2903 err = got_error(GOT_ERR_ANCESTRY);
2904 return err;
2907 static const struct got_error *
2908 checkout_ancestry_error(struct got_reference *ref, const char *commit_id_str)
2910 static char msg[512];
2911 const char *branch_name;
2913 if (got_ref_is_symbolic(ref))
2914 branch_name = got_ref_get_symref_target(ref);
2915 else
2916 branch_name = got_ref_get_name(ref);
2918 if (strncmp("refs/heads/", branch_name, 11) == 0)
2919 branch_name += 11;
2921 snprintf(msg, sizeof(msg),
2922 "target commit is not contained in branch '%s'; "
2923 "the branch to use must be specified with -b; "
2924 "if necessary a new branch can be created for "
2925 "this commit with 'got branch -c %s BRANCH_NAME'",
2926 branch_name, commit_id_str);
2928 return got_error_msg(GOT_ERR_ANCESTRY, msg);
2931 static const struct got_error *
2932 cmd_checkout(int argc, char *argv[])
2934 const struct got_error *error = NULL;
2935 struct got_repository *repo = NULL;
2936 struct got_reference *head_ref = NULL, *ref = NULL;
2937 struct got_worktree *worktree = NULL;
2938 char *repo_path = NULL;
2939 char *worktree_path = NULL;
2940 const char *path_prefix = "";
2941 const char *branch_name = GOT_REF_HEAD, *refname = NULL;
2942 char *commit_id_str = NULL;
2943 struct got_object_id *commit_id = NULL;
2944 char *cwd = NULL;
2945 int ch, same_path_prefix, allow_nonempty = 0, verbosity = 0;
2946 struct got_pathlist_head paths;
2947 struct got_checkout_progress_arg cpa;
2948 int *pack_fds = NULL;
2950 TAILQ_INIT(&paths);
2952 while ((ch = getopt(argc, argv, "b:c:Ep:q")) != -1) {
2953 switch (ch) {
2954 case 'b':
2955 branch_name = optarg;
2956 break;
2957 case 'c':
2958 commit_id_str = strdup(optarg);
2959 if (commit_id_str == NULL)
2960 return got_error_from_errno("strdup");
2961 break;
2962 case 'E':
2963 allow_nonempty = 1;
2964 break;
2965 case 'p':
2966 path_prefix = optarg;
2967 break;
2968 case 'q':
2969 verbosity = -1;
2970 break;
2971 default:
2972 usage_checkout();
2973 /* NOTREACHED */
2977 argc -= optind;
2978 argv += optind;
2980 #ifndef PROFILE
2981 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
2982 "unveil", NULL) == -1)
2983 err(1, "pledge");
2984 #endif
2985 if (argc == 1) {
2986 char *base, *dotgit;
2987 const char *path;
2988 repo_path = realpath(argv[0], NULL);
2989 if (repo_path == NULL)
2990 return got_error_from_errno2("realpath", argv[0]);
2991 cwd = getcwd(NULL, 0);
2992 if (cwd == NULL) {
2993 error = got_error_from_errno("getcwd");
2994 goto done;
2996 if (path_prefix[0])
2997 path = path_prefix;
2998 else
2999 path = repo_path;
3000 error = got_path_basename(&base, path);
3001 if (error)
3002 goto done;
3003 dotgit = strstr(base, ".git");
3004 if (dotgit)
3005 *dotgit = '\0';
3006 if (asprintf(&worktree_path, "%s/%s", cwd, base) == -1) {
3007 error = got_error_from_errno("asprintf");
3008 free(base);
3009 goto done;
3011 free(base);
3012 } else if (argc == 2) {
3013 repo_path = realpath(argv[0], NULL);
3014 if (repo_path == NULL) {
3015 error = got_error_from_errno2("realpath", argv[0]);
3016 goto done;
3018 worktree_path = realpath(argv[1], NULL);
3019 if (worktree_path == NULL) {
3020 if (errno != ENOENT) {
3021 error = got_error_from_errno2("realpath",
3022 argv[1]);
3023 goto done;
3025 worktree_path = strdup(argv[1]);
3026 if (worktree_path == NULL) {
3027 error = got_error_from_errno("strdup");
3028 goto done;
3031 } else
3032 usage_checkout();
3034 got_path_strip_trailing_slashes(repo_path);
3035 got_path_strip_trailing_slashes(worktree_path);
3037 error = got_repo_pack_fds_open(&pack_fds);
3038 if (error != NULL)
3039 goto done;
3041 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
3042 if (error != NULL)
3043 goto done;
3045 /* Pre-create work tree path for unveil(2) */
3046 error = got_path_mkdir(worktree_path);
3047 if (error) {
3048 if (!(error->code == GOT_ERR_ERRNO && errno == EISDIR) &&
3049 !(error->code == GOT_ERR_ERRNO && errno == EEXIST))
3050 goto done;
3051 if (!allow_nonempty &&
3052 !got_path_dir_is_empty(worktree_path)) {
3053 error = got_error_path(worktree_path,
3054 GOT_ERR_DIR_NOT_EMPTY);
3055 goto done;
3059 error = apply_unveil(got_repo_get_path(repo), 0, worktree_path);
3060 if (error)
3061 goto done;
3063 error = got_ref_open(&head_ref, repo, branch_name, 0);
3064 if (error != NULL)
3065 goto done;
3067 error = got_worktree_init(worktree_path, head_ref, path_prefix, repo);
3068 if (error != NULL && !(error->code == GOT_ERR_ERRNO && errno == EEXIST))
3069 goto done;
3071 error = got_worktree_open(&worktree, worktree_path);
3072 if (error != NULL)
3073 goto done;
3075 error = got_worktree_match_path_prefix(&same_path_prefix, worktree,
3076 path_prefix);
3077 if (error != NULL)
3078 goto done;
3079 if (!same_path_prefix) {
3080 error = got_error(GOT_ERR_PATH_PREFIX);
3081 goto done;
3084 if (commit_id_str) {
3085 struct got_reflist_head refs;
3086 TAILQ_INIT(&refs);
3087 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
3088 NULL);
3089 if (error)
3090 goto done;
3091 error = got_repo_match_object_id(&commit_id, NULL,
3092 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
3093 got_ref_list_free(&refs);
3094 if (error)
3095 goto done;
3096 error = check_linear_ancestry(commit_id,
3097 got_worktree_get_base_commit_id(worktree), 0, repo);
3098 if (error != NULL) {
3099 if (error->code == GOT_ERR_ANCESTRY) {
3100 error = checkout_ancestry_error(
3101 head_ref, commit_id_str);
3103 goto done;
3105 error = check_same_branch(commit_id, head_ref, NULL, repo);
3106 if (error) {
3107 if (error->code == GOT_ERR_ANCESTRY) {
3108 error = checkout_ancestry_error(
3109 head_ref, commit_id_str);
3111 goto done;
3113 error = got_worktree_set_base_commit_id(worktree, repo,
3114 commit_id);
3115 if (error)
3116 goto done;
3117 /* Expand potentially abbreviated commit ID string. */
3118 free(commit_id_str);
3119 error = got_object_id_str(&commit_id_str, commit_id);
3120 if (error)
3121 goto done;
3122 } else {
3123 commit_id = got_object_id_dup(
3124 got_worktree_get_base_commit_id(worktree));
3125 if (commit_id == NULL) {
3126 error = got_error_from_errno("got_object_id_dup");
3127 goto done;
3129 error = got_object_id_str(&commit_id_str, commit_id);
3130 if (error)
3131 goto done;
3134 error = got_pathlist_append(&paths, "", NULL);
3135 if (error)
3136 goto done;
3137 cpa.worktree_path = worktree_path;
3138 cpa.had_base_commit_ref_error = 0;
3139 cpa.verbosity = verbosity;
3140 error = got_worktree_checkout_files(worktree, &paths, repo,
3141 checkout_progress, &cpa, check_cancelled, NULL);
3142 if (error != NULL)
3143 goto done;
3145 if (got_ref_is_symbolic(head_ref)) {
3146 error = got_ref_resolve_symbolic(&ref, repo, head_ref);
3147 if (error)
3148 goto done;
3149 refname = got_ref_get_name(ref);
3150 } else
3151 refname = got_ref_get_name(head_ref);
3152 printf("Checked out %s: %s\n", refname, commit_id_str);
3153 printf("Now shut up and hack\n");
3154 if (cpa.had_base_commit_ref_error)
3155 show_worktree_base_ref_warning();
3156 done:
3157 if (pack_fds) {
3158 const struct got_error *pack_err =
3159 got_repo_pack_fds_close(pack_fds);
3160 if (error == NULL)
3161 error = pack_err;
3163 if (head_ref)
3164 got_ref_close(head_ref);
3165 if (ref)
3166 got_ref_close(ref);
3167 got_pathlist_free(&paths);
3168 free(commit_id_str);
3169 free(commit_id);
3170 free(repo_path);
3171 free(worktree_path);
3172 free(cwd);
3173 return error;
3176 struct got_update_progress_arg {
3177 int did_something;
3178 int conflicts;
3179 int obstructed;
3180 int not_updated;
3181 int missing;
3182 int not_deleted;
3183 int unversioned;
3184 int verbosity;
3187 static void
3188 print_update_progress_stats(struct got_update_progress_arg *upa)
3190 if (!upa->did_something)
3191 return;
3193 if (upa->conflicts > 0)
3194 printf("Files with new merge conflicts: %d\n", upa->conflicts);
3195 if (upa->obstructed > 0)
3196 printf("File paths obstructed by a non-regular file: %d\n",
3197 upa->obstructed);
3198 if (upa->not_updated > 0)
3199 printf("Files not updated because of existing merge "
3200 "conflicts: %d\n", upa->not_updated);
3204 * The meaning of some status codes differs between merge-style operations and
3205 * update operations. For example, the ! status code means "file was missing"
3206 * if changes were merged into the work tree, and "missing file was restored"
3207 * if the work tree was updated. This function should be used by any operation
3208 * which merges changes into the work tree without updating the work tree.
3210 static void
3211 print_merge_progress_stats(struct got_update_progress_arg *upa)
3213 if (!upa->did_something)
3214 return;
3216 if (upa->conflicts > 0)
3217 printf("Files with new merge conflicts: %d\n", upa->conflicts);
3218 if (upa->obstructed > 0)
3219 printf("File paths obstructed by a non-regular file: %d\n",
3220 upa->obstructed);
3221 if (upa->missing > 0)
3222 printf("Files which had incoming changes but could not be "
3223 "found in the work tree: %d\n", upa->missing);
3224 if (upa->not_deleted > 0)
3225 printf("Files not deleted due to differences in deleted "
3226 "content: %d\n", upa->not_deleted);
3227 if (upa->unversioned > 0)
3228 printf("Files not merged because an unversioned file was "
3229 "found in the work tree: %d\n", upa->unversioned);
3232 __dead static void
3233 usage_update(void)
3235 fprintf(stderr, "usage: %s update [-q] [-b branch] [-c commit] "
3236 "[path ...]\n", getprogname());
3237 exit(1);
3240 static const struct got_error *
3241 update_progress(void *arg, unsigned char status, const char *path)
3243 struct got_update_progress_arg *upa = arg;
3245 if (status == GOT_STATUS_EXISTS ||
3246 status == GOT_STATUS_BASE_REF_ERR)
3247 return NULL;
3249 upa->did_something = 1;
3251 /* Base commit bump happens silently. */
3252 if (status == GOT_STATUS_BUMP_BASE)
3253 return NULL;
3255 if (status == GOT_STATUS_CONFLICT)
3256 upa->conflicts++;
3257 if (status == GOT_STATUS_OBSTRUCTED)
3258 upa->obstructed++;
3259 if (status == GOT_STATUS_CANNOT_UPDATE)
3260 upa->not_updated++;
3261 if (status == GOT_STATUS_MISSING)
3262 upa->missing++;
3263 if (status == GOT_STATUS_CANNOT_DELETE)
3264 upa->not_deleted++;
3265 if (status == GOT_STATUS_UNVERSIONED)
3266 upa->unversioned++;
3268 while (path[0] == '/')
3269 path++;
3270 if (upa->verbosity >= 0)
3271 printf("%c %s\n", status, path);
3273 return NULL;
3276 static const struct got_error *
3277 switch_head_ref(struct got_reference *head_ref,
3278 struct got_object_id *commit_id, struct got_worktree *worktree,
3279 struct got_repository *repo)
3281 const struct got_error *err = NULL;
3282 char *base_id_str;
3283 int ref_has_moved = 0;
3285 /* Trivial case: switching between two different references. */
3286 if (strcmp(got_ref_get_name(head_ref),
3287 got_worktree_get_head_ref_name(worktree)) != 0) {
3288 printf("Switching work tree from %s to %s\n",
3289 got_worktree_get_head_ref_name(worktree),
3290 got_ref_get_name(head_ref));
3291 return got_worktree_set_head_ref(worktree, head_ref);
3294 err = check_linear_ancestry(commit_id,
3295 got_worktree_get_base_commit_id(worktree), 0, repo);
3296 if (err) {
3297 if (err->code != GOT_ERR_ANCESTRY)
3298 return err;
3299 ref_has_moved = 1;
3301 if (!ref_has_moved)
3302 return NULL;
3304 /* Switching to a rebased branch with the same reference name. */
3305 err = got_object_id_str(&base_id_str,
3306 got_worktree_get_base_commit_id(worktree));
3307 if (err)
3308 return err;
3309 printf("Reference %s now points at a different branch\n",
3310 got_worktree_get_head_ref_name(worktree));
3311 printf("Switching work tree from %s to %s\n", base_id_str,
3312 got_worktree_get_head_ref_name(worktree));
3313 return NULL;
3316 static const struct got_error *
3317 check_rebase_or_histedit_in_progress(struct got_worktree *worktree)
3319 const struct got_error *err;
3320 int in_progress;
3322 err = got_worktree_rebase_in_progress(&in_progress, worktree);
3323 if (err)
3324 return err;
3325 if (in_progress)
3326 return got_error(GOT_ERR_REBASING);
3328 err = got_worktree_histedit_in_progress(&in_progress, worktree);
3329 if (err)
3330 return err;
3331 if (in_progress)
3332 return got_error(GOT_ERR_HISTEDIT_BUSY);
3334 return NULL;
3337 static const struct got_error *
3338 check_merge_in_progress(struct got_worktree *worktree,
3339 struct got_repository *repo)
3341 const struct got_error *err;
3342 int in_progress;
3344 err = got_worktree_merge_in_progress(&in_progress, worktree, repo);
3345 if (err)
3346 return err;
3347 if (in_progress)
3348 return got_error(GOT_ERR_MERGE_BUSY);
3350 return NULL;
3353 static const struct got_error *
3354 get_worktree_paths_from_argv(struct got_pathlist_head *paths, int argc,
3355 char *argv[], struct got_worktree *worktree)
3357 const struct got_error *err = NULL;
3358 char *path;
3359 struct got_pathlist_entry *new;
3360 int i;
3362 if (argc == 0) {
3363 path = strdup("");
3364 if (path == NULL)
3365 return got_error_from_errno("strdup");
3366 return got_pathlist_append(paths, path, NULL);
3369 for (i = 0; i < argc; i++) {
3370 err = got_worktree_resolve_path(&path, worktree, argv[i]);
3371 if (err)
3372 break;
3373 err = got_pathlist_insert(&new, paths, path, NULL);
3374 if (err || new == NULL /* duplicate */) {
3375 free(path);
3376 if (err)
3377 break;
3381 return err;
3384 static const struct got_error *
3385 wrap_not_worktree_error(const struct got_error *orig_err,
3386 const char *cmdname, const char *path)
3388 const struct got_error *err;
3389 struct got_repository *repo;
3390 static char msg[512];
3391 int *pack_fds = NULL;
3393 err = got_repo_pack_fds_open(&pack_fds);
3394 if (err)
3395 return err;
3397 err = got_repo_open(&repo, path, NULL, pack_fds);
3398 if (err)
3399 return orig_err;
3401 snprintf(msg, sizeof(msg),
3402 "'got %s' needs a work tree in addition to a git repository\n"
3403 "Work trees can be checked out from this Git repository with "
3404 "'got checkout'.\n"
3405 "The got(1) manual page contains more information.", cmdname);
3406 err = got_error_msg(GOT_ERR_NOT_WORKTREE, msg);
3407 got_repo_close(repo);
3408 if (pack_fds) {
3409 const struct got_error *pack_err =
3410 got_repo_pack_fds_close(pack_fds);
3411 if (err == NULL)
3412 err = pack_err;
3414 return err;
3417 static const struct got_error *
3418 cmd_update(int argc, char *argv[])
3420 const struct got_error *error = NULL;
3421 struct got_repository *repo = NULL;
3422 struct got_worktree *worktree = NULL;
3423 char *worktree_path = NULL;
3424 struct got_object_id *commit_id = NULL;
3425 char *commit_id_str = NULL;
3426 const char *branch_name = NULL;
3427 struct got_reference *head_ref = NULL;
3428 struct got_pathlist_head paths;
3429 struct got_pathlist_entry *pe;
3430 int ch, verbosity = 0;
3431 struct got_update_progress_arg upa;
3432 int *pack_fds = NULL;
3434 TAILQ_INIT(&paths);
3436 while ((ch = getopt(argc, argv, "b:c:q")) != -1) {
3437 switch (ch) {
3438 case 'b':
3439 branch_name = optarg;
3440 break;
3441 case 'c':
3442 commit_id_str = strdup(optarg);
3443 if (commit_id_str == NULL)
3444 return got_error_from_errno("strdup");
3445 break;
3446 case 'q':
3447 verbosity = -1;
3448 break;
3449 default:
3450 usage_update();
3451 /* NOTREACHED */
3455 argc -= optind;
3456 argv += optind;
3458 #ifndef PROFILE
3459 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
3460 "unveil", NULL) == -1)
3461 err(1, "pledge");
3462 #endif
3463 worktree_path = getcwd(NULL, 0);
3464 if (worktree_path == NULL) {
3465 error = got_error_from_errno("getcwd");
3466 goto done;
3469 error = got_repo_pack_fds_open(&pack_fds);
3470 if (error != NULL)
3471 goto done;
3473 error = got_worktree_open(&worktree, worktree_path);
3474 if (error) {
3475 if (error->code == GOT_ERR_NOT_WORKTREE)
3476 error = wrap_not_worktree_error(error, "update",
3477 worktree_path);
3478 goto done;
3481 error = check_rebase_or_histedit_in_progress(worktree);
3482 if (error)
3483 goto done;
3485 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
3486 NULL, pack_fds);
3487 if (error != NULL)
3488 goto done;
3490 error = apply_unveil(got_repo_get_path(repo), 0,
3491 got_worktree_get_root_path(worktree));
3492 if (error)
3493 goto done;
3495 error = check_merge_in_progress(worktree, repo);
3496 if (error)
3497 goto done;
3499 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
3500 if (error)
3501 goto done;
3503 error = got_ref_open(&head_ref, repo, branch_name ? branch_name :
3504 got_worktree_get_head_ref_name(worktree), 0);
3505 if (error != NULL)
3506 goto done;
3507 if (commit_id_str == NULL) {
3508 error = got_ref_resolve(&commit_id, repo, head_ref);
3509 if (error != NULL)
3510 goto done;
3511 error = got_object_id_str(&commit_id_str, commit_id);
3512 if (error != NULL)
3513 goto done;
3514 } else {
3515 struct got_reflist_head refs;
3516 TAILQ_INIT(&refs);
3517 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
3518 NULL);
3519 if (error)
3520 goto done;
3521 error = got_repo_match_object_id(&commit_id, NULL,
3522 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
3523 got_ref_list_free(&refs);
3524 free(commit_id_str);
3525 commit_id_str = NULL;
3526 if (error)
3527 goto done;
3528 error = got_object_id_str(&commit_id_str, commit_id);
3529 if (error)
3530 goto done;
3533 if (branch_name) {
3534 struct got_object_id *head_commit_id;
3535 TAILQ_FOREACH(pe, &paths, entry) {
3536 if (pe->path_len == 0)
3537 continue;
3538 error = got_error_msg(GOT_ERR_BAD_PATH,
3539 "switching between branches requires that "
3540 "the entire work tree gets updated");
3541 goto done;
3543 error = got_ref_resolve(&head_commit_id, repo, head_ref);
3544 if (error)
3545 goto done;
3546 error = check_linear_ancestry(commit_id, head_commit_id, 0,
3547 repo);
3548 free(head_commit_id);
3549 if (error != NULL)
3550 goto done;
3551 error = check_same_branch(commit_id, head_ref, NULL, repo);
3552 if (error)
3553 goto done;
3554 error = switch_head_ref(head_ref, commit_id, worktree, repo);
3555 if (error)
3556 goto done;
3557 } else {
3558 error = check_linear_ancestry(commit_id,
3559 got_worktree_get_base_commit_id(worktree), 0, repo);
3560 if (error != NULL) {
3561 if (error->code == GOT_ERR_ANCESTRY)
3562 error = got_error(GOT_ERR_BRANCH_MOVED);
3563 goto done;
3565 error = check_same_branch(commit_id, head_ref, NULL, repo);
3566 if (error)
3567 goto done;
3570 if (got_object_id_cmp(got_worktree_get_base_commit_id(worktree),
3571 commit_id) != 0) {
3572 error = got_worktree_set_base_commit_id(worktree, repo,
3573 commit_id);
3574 if (error)
3575 goto done;
3578 memset(&upa, 0, sizeof(upa));
3579 upa.verbosity = verbosity;
3580 error = got_worktree_checkout_files(worktree, &paths, repo,
3581 update_progress, &upa, check_cancelled, NULL);
3582 if (error != NULL)
3583 goto done;
3585 if (upa.did_something) {
3586 printf("Updated to %s: %s\n",
3587 got_worktree_get_head_ref_name(worktree), commit_id_str);
3588 } else
3589 printf("Already up-to-date\n");
3591 print_update_progress_stats(&upa);
3592 done:
3593 if (pack_fds) {
3594 const struct got_error *pack_err =
3595 got_repo_pack_fds_close(pack_fds);
3596 if (error == NULL)
3597 error = pack_err;
3599 free(worktree_path);
3600 TAILQ_FOREACH(pe, &paths, entry)
3601 free((char *)pe->path);
3602 got_pathlist_free(&paths);
3603 free(commit_id);
3604 free(commit_id_str);
3605 return error;
3608 static const struct got_error *
3609 diff_blobs(struct got_object_id *blob_id1, struct got_object_id *blob_id2,
3610 const char *path, int diff_context, int ignore_whitespace,
3611 int force_text_diff, struct got_repository *repo, FILE *outfile)
3613 const struct got_error *err = NULL;
3614 struct got_blob_object *blob1 = NULL, *blob2 = NULL;
3615 FILE *f1 = NULL, *f2 = NULL;
3616 int fd1 = -1, fd2 = -1;
3618 fd1 = got_opentempfd();
3619 if (fd1 == -1)
3620 return got_error_from_errno("got_opentempfd");
3621 fd2 = got_opentempfd();
3622 if (fd2 == -1) {
3623 err = got_error_from_errno("got_opentempfd");
3624 goto done;
3627 if (blob_id1) {
3628 err = got_object_open_as_blob(&blob1, repo, blob_id1, 8192,
3629 fd1);
3630 if (err)
3631 goto done;
3634 err = got_object_open_as_blob(&blob2, repo, blob_id2, 8192, fd2);
3635 if (err)
3636 goto done;
3638 f1 = got_opentemp();
3639 if (f1 == NULL) {
3640 err = got_error_from_errno("got_opentemp");
3641 goto done;
3643 f2 = got_opentemp();
3644 if (f2 == NULL) {
3645 err = got_error_from_errno("got_opentemp");
3646 goto done;
3649 while (path[0] == '/')
3650 path++;
3651 err = got_diff_blob(NULL, NULL, blob1, blob2, f1, f2, path, path,
3652 GOT_DIFF_ALGORITHM_PATIENCE, diff_context, ignore_whitespace,
3653 force_text_diff, outfile);
3654 done:
3655 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
3656 err = got_error_from_errno("close");
3657 if (blob1)
3658 got_object_blob_close(blob1);
3659 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
3660 err = got_error_from_errno("close");
3661 got_object_blob_close(blob2);
3662 if (f1 && fclose(f1) == EOF && err == NULL)
3663 err = got_error_from_errno("fclose");
3664 if (f2 && fclose(f2) == EOF && err == NULL)
3665 err = got_error_from_errno("fclose");
3666 return err;
3669 static const struct got_error *
3670 diff_trees(struct got_object_id *tree_id1, struct got_object_id *tree_id2,
3671 const char *path, int diff_context, int ignore_whitespace,
3672 int force_text_diff, struct got_repository *repo, FILE *outfile)
3674 const struct got_error *err = NULL;
3675 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
3676 struct got_diff_blob_output_unidiff_arg arg;
3677 FILE *f1 = NULL, *f2 = NULL;
3678 int fd1 = -1, fd2 = -1;
3680 if (tree_id1) {
3681 err = got_object_open_as_tree(&tree1, repo, tree_id1);
3682 if (err)
3683 goto done;
3684 fd1 = got_opentempfd();
3685 if (fd1 == -1) {
3686 err = got_error_from_errno("got_opentempfd");
3687 goto done;
3691 err = got_object_open_as_tree(&tree2, repo, tree_id2);
3692 if (err)
3693 goto done;
3695 f1 = got_opentemp();
3696 if (f1 == NULL) {
3697 err = got_error_from_errno("got_opentemp");
3698 goto done;
3701 f2 = got_opentemp();
3702 if (f2 == NULL) {
3703 err = got_error_from_errno("got_opentemp");
3704 goto done;
3706 fd2 = got_opentempfd();
3707 if (fd2 == -1) {
3708 err = got_error_from_errno("got_opentempfd");
3709 goto done;
3711 arg.diff_context = diff_context;
3712 arg.ignore_whitespace = ignore_whitespace;
3713 arg.force_text_diff = force_text_diff;
3714 arg.diff_algo = GOT_DIFF_ALGORITHM_PATIENCE;
3715 arg.outfile = outfile;
3716 arg.lines = NULL;
3717 arg.nlines = 0;
3718 while (path[0] == '/')
3719 path++;
3720 err = got_diff_tree(tree1, tree2, f1, f2, fd1, fd2, path, path, repo,
3721 got_diff_blob_output_unidiff, &arg, 1);
3722 done:
3723 if (tree1)
3724 got_object_tree_close(tree1);
3725 if (tree2)
3726 got_object_tree_close(tree2);
3727 if (f1 && fclose(f1) == EOF && err == NULL)
3728 err = got_error_from_errno("fclose");
3729 if (f2 && fclose(f2) == EOF && err == NULL)
3730 err = got_error_from_errno("fclose");
3731 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
3732 err = got_error_from_errno("close");
3733 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
3734 err = got_error_from_errno("close");
3735 return err;
3738 static const struct got_error *
3739 get_changed_paths(struct got_pathlist_head *paths,
3740 struct got_commit_object *commit, struct got_repository *repo)
3742 const struct got_error *err = NULL;
3743 struct got_object_id *tree_id1 = NULL, *tree_id2 = NULL;
3744 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
3745 struct got_object_qid *qid;
3747 qid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
3748 if (qid != NULL) {
3749 struct got_commit_object *pcommit;
3750 err = got_object_open_as_commit(&pcommit, repo,
3751 &qid->id);
3752 if (err)
3753 return err;
3755 tree_id1 = got_object_id_dup(
3756 got_object_commit_get_tree_id(pcommit));
3757 if (tree_id1 == NULL) {
3758 got_object_commit_close(pcommit);
3759 return got_error_from_errno("got_object_id_dup");
3761 got_object_commit_close(pcommit);
3765 if (tree_id1) {
3766 err = got_object_open_as_tree(&tree1, repo, tree_id1);
3767 if (err)
3768 goto done;
3771 tree_id2 = got_object_commit_get_tree_id(commit);
3772 err = got_object_open_as_tree(&tree2, repo, tree_id2);
3773 if (err)
3774 goto done;
3776 err = got_diff_tree(tree1, tree2, NULL, NULL, -1, -1, "", "", repo,
3777 got_diff_tree_collect_changed_paths, paths, 0);
3778 done:
3779 if (tree1)
3780 got_object_tree_close(tree1);
3781 if (tree2)
3782 got_object_tree_close(tree2);
3783 free(tree_id1);
3784 return err;
3787 static const struct got_error *
3788 print_patch(struct got_commit_object *commit, struct got_object_id *id,
3789 const char *path, int diff_context, struct got_repository *repo,
3790 FILE *outfile)
3792 const struct got_error *err = NULL;
3793 struct got_commit_object *pcommit = NULL;
3794 char *id_str1 = NULL, *id_str2 = NULL;
3795 struct got_object_id *obj_id1 = NULL, *obj_id2 = NULL;
3796 struct got_object_qid *qid;
3798 qid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
3799 if (qid != NULL) {
3800 err = got_object_open_as_commit(&pcommit, repo,
3801 &qid->id);
3802 if (err)
3803 return err;
3804 err = got_object_id_str(&id_str1, &qid->id);
3805 if (err)
3806 goto done;
3809 err = got_object_id_str(&id_str2, id);
3810 if (err)
3811 goto done;
3813 if (path && path[0] != '\0') {
3814 int obj_type;
3815 err = got_object_id_by_path(&obj_id2, repo, commit, path);
3816 if (err)
3817 goto done;
3818 if (pcommit) {
3819 err = got_object_id_by_path(&obj_id1, repo,
3820 pcommit, path);
3821 if (err) {
3822 if (err->code != GOT_ERR_NO_TREE_ENTRY) {
3823 free(obj_id2);
3824 goto done;
3828 err = got_object_get_type(&obj_type, repo, obj_id2);
3829 if (err) {
3830 free(obj_id2);
3831 goto done;
3833 fprintf(outfile,
3834 "diff %s %s\n", id_str1 ? id_str1 : "/dev/null", id_str2);
3835 fprintf(outfile, "commit - %s\n",
3836 id_str1 ? id_str1 : "/dev/null");
3837 fprintf(outfile, "commit + %s\n", id_str2);
3838 switch (obj_type) {
3839 case GOT_OBJ_TYPE_BLOB:
3840 err = diff_blobs(obj_id1, obj_id2, path, diff_context,
3841 0, 0, repo, outfile);
3842 break;
3843 case GOT_OBJ_TYPE_TREE:
3844 err = diff_trees(obj_id1, obj_id2, path, diff_context,
3845 0, 0, repo, outfile);
3846 break;
3847 default:
3848 err = got_error(GOT_ERR_OBJ_TYPE);
3849 break;
3851 free(obj_id1);
3852 free(obj_id2);
3853 } else {
3854 obj_id2 = got_object_commit_get_tree_id(commit);
3855 if (pcommit)
3856 obj_id1 = got_object_commit_get_tree_id(pcommit);
3857 fprintf(outfile,
3858 "diff %s %s\n", id_str1 ? id_str1 : "/dev/null", id_str2);
3859 fprintf(outfile, "commit - %s\n",
3860 id_str1 ? id_str1 : "/dev/null");
3861 fprintf(outfile, "commit + %s\n", id_str2);
3862 err = diff_trees(obj_id1, obj_id2, "", diff_context, 0, 0,
3863 repo, outfile);
3865 done:
3866 free(id_str1);
3867 free(id_str2);
3868 if (pcommit)
3869 got_object_commit_close(pcommit);
3870 return err;
3873 static char *
3874 get_datestr(time_t *time, char *datebuf)
3876 struct tm mytm, *tm;
3877 char *p, *s;
3879 tm = gmtime_r(time, &mytm);
3880 if (tm == NULL)
3881 return NULL;
3882 s = asctime_r(tm, datebuf);
3883 if (s == NULL)
3884 return NULL;
3885 p = strchr(s, '\n');
3886 if (p)
3887 *p = '\0';
3888 return s;
3891 static const struct got_error *
3892 match_commit(int *have_match, struct got_object_id *id,
3893 struct got_commit_object *commit, regex_t *regex)
3895 const struct got_error *err = NULL;
3896 regmatch_t regmatch;
3897 char *id_str = NULL, *logmsg = NULL;
3899 *have_match = 0;
3901 err = got_object_id_str(&id_str, id);
3902 if (err)
3903 return err;
3905 err = got_object_commit_get_logmsg(&logmsg, commit);
3906 if (err)
3907 goto done;
3909 if (regexec(regex, got_object_commit_get_author(commit), 1,
3910 &regmatch, 0) == 0 ||
3911 regexec(regex, got_object_commit_get_committer(commit), 1,
3912 &regmatch, 0) == 0 ||
3913 regexec(regex, id_str, 1, &regmatch, 0) == 0 ||
3914 regexec(regex, logmsg, 1, &regmatch, 0) == 0)
3915 *have_match = 1;
3916 done:
3917 free(id_str);
3918 free(logmsg);
3919 return err;
3922 static void
3923 match_changed_paths(int *have_match, struct got_pathlist_head *changed_paths,
3924 regex_t *regex)
3926 regmatch_t regmatch;
3927 struct got_pathlist_entry *pe;
3929 *have_match = 0;
3931 TAILQ_FOREACH(pe, changed_paths, entry) {
3932 if (regexec(regex, pe->path, 1, &regmatch, 0) == 0) {
3933 *have_match = 1;
3934 break;
3939 static const struct got_error *
3940 match_patch(int *have_match, struct got_commit_object *commit,
3941 struct got_object_id *id, const char *path, int diff_context,
3942 struct got_repository *repo, regex_t *regex, FILE *f)
3944 const struct got_error *err = NULL;
3945 char *line = NULL;
3946 size_t linesize = 0;
3947 regmatch_t regmatch;
3949 *have_match = 0;
3951 err = got_opentemp_truncate(f);
3952 if (err)
3953 return err;
3955 err = print_patch(commit, id, path, diff_context, repo, f);
3956 if (err)
3957 goto done;
3959 if (fseeko(f, 0L, SEEK_SET) == -1) {
3960 err = got_error_from_errno("fseeko");
3961 goto done;
3964 while (getline(&line, &linesize, f) != -1) {
3965 if (regexec(regex, line, 1, &regmatch, 0) == 0) {
3966 *have_match = 1;
3967 break;
3970 done:
3971 free(line);
3972 return err;
3975 #define GOT_COMMIT_SEP_STR "-----------------------------------------------\n"
3977 static const struct got_error*
3978 build_refs_str(char **refs_str, struct got_reflist_head *refs,
3979 struct got_object_id *id, struct got_repository *repo,
3980 int local_only)
3982 static const struct got_error *err = NULL;
3983 struct got_reflist_entry *re;
3984 char *s;
3985 const char *name;
3987 *refs_str = NULL;
3989 TAILQ_FOREACH(re, refs, entry) {
3990 struct got_tag_object *tag = NULL;
3991 struct got_object_id *ref_id;
3992 int cmp;
3994 name = got_ref_get_name(re->ref);
3995 if (strcmp(name, GOT_REF_HEAD) == 0)
3996 continue;
3997 if (strncmp(name, "refs/", 5) == 0)
3998 name += 5;
3999 if (strncmp(name, "got/", 4) == 0)
4000 continue;
4001 if (strncmp(name, "heads/", 6) == 0)
4002 name += 6;
4003 if (strncmp(name, "remotes/", 8) == 0) {
4004 if (local_only)
4005 continue;
4006 name += 8;
4007 s = strstr(name, "/" GOT_REF_HEAD);
4008 if (s != NULL && s[strlen(s)] == '\0')
4009 continue;
4011 err = got_ref_resolve(&ref_id, repo, re->ref);
4012 if (err)
4013 break;
4014 if (strncmp(name, "tags/", 5) == 0) {
4015 err = got_object_open_as_tag(&tag, repo, ref_id);
4016 if (err) {
4017 if (err->code != GOT_ERR_OBJ_TYPE) {
4018 free(ref_id);
4019 break;
4021 /* Ref points at something other than a tag. */
4022 err = NULL;
4023 tag = NULL;
4026 cmp = got_object_id_cmp(tag ?
4027 got_object_tag_get_object_id(tag) : ref_id, id);
4028 free(ref_id);
4029 if (tag)
4030 got_object_tag_close(tag);
4031 if (cmp != 0)
4032 continue;
4033 s = *refs_str;
4034 if (asprintf(refs_str, "%s%s%s", s ? s : "",
4035 s ? ", " : "", name) == -1) {
4036 err = got_error_from_errno("asprintf");
4037 free(s);
4038 *refs_str = NULL;
4039 break;
4041 free(s);
4044 return err;
4047 static const struct got_error *
4048 print_commit_oneline(struct got_commit_object *commit, struct got_object_id *id,
4049 struct got_repository *repo, struct got_reflist_object_id_map *refs_idmap)
4051 const struct got_error *err = NULL;
4052 char *ref_str = NULL, *id_str = NULL, *logmsg0 = NULL;
4053 char *comma, *s, *nl;
4054 struct got_reflist_head *refs;
4055 char datebuf[12]; /* YYYY-MM-DD + SPACE + NUL */
4056 struct tm tm;
4057 time_t committer_time;
4059 refs = got_reflist_object_id_map_lookup(refs_idmap, id);
4060 if (refs) {
4061 err = build_refs_str(&ref_str, refs, id, repo, 1);
4062 if (err)
4063 return err;
4065 /* Display the first matching ref only. */
4066 if (ref_str && (comma = strchr(ref_str, ',')) != NULL)
4067 *comma = '\0';
4070 if (ref_str == NULL) {
4071 err = got_object_id_str(&id_str, id);
4072 if (err)
4073 return err;
4076 committer_time = got_object_commit_get_committer_time(commit);
4077 if (gmtime_r(&committer_time, &tm) == NULL) {
4078 err = got_error_from_errno("gmtime_r");
4079 goto done;
4081 if (strftime(datebuf, sizeof(datebuf), "%G-%m-%d ", &tm) == 0) {
4082 err = got_error(GOT_ERR_NO_SPACE);
4083 goto done;
4086 err = got_object_commit_get_logmsg(&logmsg0, commit);
4087 if (err)
4088 goto done;
4090 s = logmsg0;
4091 while (isspace((unsigned char)s[0]))
4092 s++;
4094 nl = strchr(s, '\n');
4095 if (nl) {
4096 *nl = '\0';
4099 if (ref_str)
4100 printf("%s%-7s %s\n", datebuf, ref_str, s);
4101 else
4102 printf("%s%.7s %s\n", datebuf, id_str, s);
4104 if (fflush(stdout) != 0 && err == NULL)
4105 err = got_error_from_errno("fflush");
4106 done:
4107 free(id_str);
4108 free(ref_str);
4109 free(logmsg0);
4110 return err;
4113 static const struct got_error *
4114 print_commit(struct got_commit_object *commit, struct got_object_id *id,
4115 struct got_repository *repo, const char *path,
4116 struct got_pathlist_head *changed_paths, int show_patch,
4117 int diff_context, struct got_reflist_object_id_map *refs_idmap,
4118 const char *custom_refs_str)
4120 const struct got_error *err = NULL;
4121 char *id_str, *datestr, *logmsg0, *logmsg, *line;
4122 char datebuf[26];
4123 time_t committer_time;
4124 const char *author, *committer;
4125 char *refs_str = NULL;
4127 err = got_object_id_str(&id_str, id);
4128 if (err)
4129 return err;
4131 if (custom_refs_str == NULL) {
4132 struct got_reflist_head *refs;
4133 refs = got_reflist_object_id_map_lookup(refs_idmap, id);
4134 if (refs) {
4135 err = build_refs_str(&refs_str, refs, id, repo, 0);
4136 if (err)
4137 goto done;
4141 printf(GOT_COMMIT_SEP_STR);
4142 if (custom_refs_str)
4143 printf("commit %s (%s)\n", id_str, custom_refs_str);
4144 else
4145 printf("commit %s%s%s%s\n", id_str, refs_str ? " (" : "",
4146 refs_str ? refs_str : "", refs_str ? ")" : "");
4147 free(id_str);
4148 id_str = NULL;
4149 free(refs_str);
4150 refs_str = NULL;
4151 printf("from: %s\n", got_object_commit_get_author(commit));
4152 committer_time = got_object_commit_get_committer_time(commit);
4153 datestr = get_datestr(&committer_time, datebuf);
4154 if (datestr)
4155 printf("date: %s UTC\n", datestr);
4156 author = got_object_commit_get_author(commit);
4157 committer = got_object_commit_get_committer(commit);
4158 if (strcmp(author, committer) != 0)
4159 printf("via: %s\n", committer);
4160 if (got_object_commit_get_nparents(commit) > 1) {
4161 const struct got_object_id_queue *parent_ids;
4162 struct got_object_qid *qid;
4163 int n = 1;
4164 parent_ids = got_object_commit_get_parent_ids(commit);
4165 STAILQ_FOREACH(qid, parent_ids, entry) {
4166 err = got_object_id_str(&id_str, &qid->id);
4167 if (err)
4168 goto done;
4169 printf("parent %d: %s\n", n++, id_str);
4170 free(id_str);
4171 id_str = NULL;
4175 err = got_object_commit_get_logmsg(&logmsg0, commit);
4176 if (err)
4177 goto done;
4179 logmsg = logmsg0;
4180 do {
4181 line = strsep(&logmsg, "\n");
4182 if (line)
4183 printf(" %s\n", line);
4184 } while (line);
4185 free(logmsg0);
4187 if (changed_paths) {
4188 struct got_pathlist_entry *pe;
4189 TAILQ_FOREACH(pe, changed_paths, entry) {
4190 struct got_diff_changed_path *cp = pe->data;
4191 printf(" %c %s\n", cp->status, pe->path);
4193 printf("\n");
4195 if (show_patch) {
4196 err = print_patch(commit, id, path, diff_context, repo, stdout);
4197 if (err == 0)
4198 printf("\n");
4201 if (fflush(stdout) != 0 && err == NULL)
4202 err = got_error_from_errno("fflush");
4203 done:
4204 free(id_str);
4205 free(refs_str);
4206 return err;
4209 static const struct got_error *
4210 print_commits(struct got_object_id *root_id, struct got_object_id *end_id,
4211 struct got_repository *repo, const char *path, int show_changed_paths,
4212 int show_patch, const char *search_pattern, int diff_context, int limit,
4213 int log_branches, int reverse_display_order,
4214 struct got_reflist_object_id_map *refs_idmap, int one_line,
4215 FILE *tmpfile)
4217 const struct got_error *err;
4218 struct got_commit_graph *graph;
4219 regex_t regex;
4220 int have_match;
4221 struct got_object_id_queue reversed_commits;
4222 struct got_object_qid *qid;
4223 struct got_commit_object *commit;
4224 struct got_pathlist_head changed_paths;
4225 struct got_pathlist_entry *pe;
4227 STAILQ_INIT(&reversed_commits);
4228 TAILQ_INIT(&changed_paths);
4230 if (search_pattern && regcomp(&regex, search_pattern,
4231 REG_EXTENDED | REG_NOSUB | REG_NEWLINE))
4232 return got_error_msg(GOT_ERR_REGEX, search_pattern);
4234 err = got_commit_graph_open(&graph, path, !log_branches);
4235 if (err)
4236 return err;
4237 err = got_commit_graph_iter_start(graph, root_id, repo,
4238 check_cancelled, NULL);
4239 if (err)
4240 goto done;
4241 for (;;) {
4242 struct got_object_id id;
4244 if (sigint_received || sigpipe_received)
4245 break;
4247 err = got_commit_graph_iter_next(&id, graph, repo,
4248 check_cancelled, NULL);
4249 if (err) {
4250 if (err->code == GOT_ERR_ITER_COMPLETED)
4251 err = NULL;
4252 break;
4255 err = got_object_open_as_commit(&commit, repo, &id);
4256 if (err)
4257 break;
4259 if (show_changed_paths && !reverse_display_order) {
4260 err = get_changed_paths(&changed_paths, commit, repo);
4261 if (err)
4262 break;
4265 if (search_pattern) {
4266 err = match_commit(&have_match, &id, commit, &regex);
4267 if (err) {
4268 got_object_commit_close(commit);
4269 break;
4271 if (have_match == 0 && show_changed_paths)
4272 match_changed_paths(&have_match,
4273 &changed_paths, &regex);
4274 if (have_match == 0 && show_patch) {
4275 err = match_patch(&have_match, commit, &id,
4276 path, diff_context, repo, &regex,
4277 tmpfile);
4278 if (err)
4279 break;
4281 if (have_match == 0) {
4282 got_object_commit_close(commit);
4283 TAILQ_FOREACH(pe, &changed_paths, entry) {
4284 free((char *)pe->path);
4285 free(pe->data);
4287 got_pathlist_free(&changed_paths);
4288 continue;
4292 if (reverse_display_order) {
4293 err = got_object_qid_alloc(&qid, &id);
4294 if (err)
4295 break;
4296 STAILQ_INSERT_HEAD(&reversed_commits, qid, entry);
4297 got_object_commit_close(commit);
4298 } else {
4299 if (one_line)
4300 err = print_commit_oneline(commit, &id,
4301 repo, refs_idmap);
4302 else
4303 err = print_commit(commit, &id, repo, path,
4304 show_changed_paths ? &changed_paths : NULL,
4305 show_patch, diff_context, refs_idmap, NULL);
4306 got_object_commit_close(commit);
4307 if (err)
4308 break;
4310 if ((limit && --limit == 0) ||
4311 (end_id && got_object_id_cmp(&id, end_id) == 0))
4312 break;
4314 TAILQ_FOREACH(pe, &changed_paths, entry) {
4315 free((char *)pe->path);
4316 free(pe->data);
4318 got_pathlist_free(&changed_paths);
4320 if (reverse_display_order) {
4321 STAILQ_FOREACH(qid, &reversed_commits, entry) {
4322 err = got_object_open_as_commit(&commit, repo,
4323 &qid->id);
4324 if (err)
4325 break;
4326 if (show_changed_paths) {
4327 err = get_changed_paths(&changed_paths,
4328 commit, repo);
4329 if (err)
4330 break;
4332 if (one_line)
4333 err = print_commit_oneline(commit, &qid->id,
4334 repo, refs_idmap);
4335 else
4336 err = print_commit(commit, &qid->id, repo, path,
4337 show_changed_paths ? &changed_paths : NULL,
4338 show_patch, diff_context, refs_idmap, NULL);
4339 got_object_commit_close(commit);
4340 if (err)
4341 break;
4342 TAILQ_FOREACH(pe, &changed_paths, entry) {
4343 free((char *)pe->path);
4344 free(pe->data);
4346 got_pathlist_free(&changed_paths);
4349 done:
4350 while (!STAILQ_EMPTY(&reversed_commits)) {
4351 qid = STAILQ_FIRST(&reversed_commits);
4352 STAILQ_REMOVE_HEAD(&reversed_commits, entry);
4353 got_object_qid_free(qid);
4355 TAILQ_FOREACH(pe, &changed_paths, entry) {
4356 free((char *)pe->path);
4357 free(pe->data);
4359 got_pathlist_free(&changed_paths);
4360 if (search_pattern)
4361 regfree(&regex);
4362 got_commit_graph_close(graph);
4363 return err;
4366 __dead static void
4367 usage_log(void)
4369 fprintf(stderr, "usage: %s log [-bPpRs] [-C number] [-c commit] [-l N] "
4370 "[-r repository-path] [-S search-pattern] [-x commit] [path]\n",
4371 getprogname());
4372 exit(1);
4375 static int
4376 get_default_log_limit(void)
4378 const char *got_default_log_limit;
4379 long long n;
4380 const char *errstr;
4382 got_default_log_limit = getenv("GOT_LOG_DEFAULT_LIMIT");
4383 if (got_default_log_limit == NULL)
4384 return 0;
4385 n = strtonum(got_default_log_limit, 0, INT_MAX, &errstr);
4386 if (errstr != NULL)
4387 return 0;
4388 return n;
4391 static const struct got_error *
4392 cmd_log(int argc, char *argv[])
4394 const struct got_error *error;
4395 struct got_repository *repo = NULL;
4396 struct got_worktree *worktree = NULL;
4397 struct got_object_id *start_id = NULL, *end_id = NULL;
4398 char *repo_path = NULL, *path = NULL, *cwd = NULL, *in_repo_path = NULL;
4399 const char *start_commit = NULL, *end_commit = NULL;
4400 const char *search_pattern = NULL;
4401 int diff_context = -1, ch;
4402 int show_changed_paths = 0, show_patch = 0, limit = 0, log_branches = 0;
4403 int reverse_display_order = 0, one_line = 0;
4404 const char *errstr;
4405 struct got_reflist_head refs;
4406 struct got_reflist_object_id_map *refs_idmap = NULL;
4407 FILE *tmpfile = NULL;
4408 int *pack_fds = NULL;
4410 TAILQ_INIT(&refs);
4412 #ifndef PROFILE
4413 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
4414 NULL)
4415 == -1)
4416 err(1, "pledge");
4417 #endif
4419 limit = get_default_log_limit();
4421 while ((ch = getopt(argc, argv, "bC:c:l:PpRr:S:sx:")) != -1) {
4422 switch (ch) {
4423 case 'b':
4424 log_branches = 1;
4425 break;
4426 case 'C':
4427 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
4428 &errstr);
4429 if (errstr != NULL)
4430 errx(1, "number of context lines is %s: %s",
4431 errstr, optarg);
4432 break;
4433 case 'c':
4434 start_commit = optarg;
4435 break;
4436 case 'l':
4437 limit = strtonum(optarg, 0, INT_MAX, &errstr);
4438 if (errstr != NULL)
4439 errx(1, "number of commits is %s: %s",
4440 errstr, optarg);
4441 break;
4442 case 'P':
4443 show_changed_paths = 1;
4444 break;
4445 case 'p':
4446 show_patch = 1;
4447 break;
4448 case 'R':
4449 reverse_display_order = 1;
4450 break;
4451 case 'r':
4452 repo_path = realpath(optarg, NULL);
4453 if (repo_path == NULL)
4454 return got_error_from_errno2("realpath",
4455 optarg);
4456 got_path_strip_trailing_slashes(repo_path);
4457 break;
4458 case 'S':
4459 search_pattern = optarg;
4460 break;
4461 case 's':
4462 one_line = 1;
4463 break;
4464 case 'x':
4465 end_commit = optarg;
4466 break;
4467 default:
4468 usage_log();
4469 /* NOTREACHED */
4473 argc -= optind;
4474 argv += optind;
4476 if (diff_context == -1)
4477 diff_context = 3;
4478 else if (!show_patch)
4479 errx(1, "-C requires -p");
4481 if (one_line && (show_patch || show_changed_paths))
4482 errx(1, "cannot use -s with -p or -P");
4484 cwd = getcwd(NULL, 0);
4485 if (cwd == NULL) {
4486 error = got_error_from_errno("getcwd");
4487 goto done;
4490 error = got_repo_pack_fds_open(&pack_fds);
4491 if (error != NULL)
4492 goto done;
4494 if (repo_path == NULL) {
4495 error = got_worktree_open(&worktree, cwd);
4496 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4497 goto done;
4498 error = NULL;
4501 if (argc == 1) {
4502 if (worktree) {
4503 error = got_worktree_resolve_path(&path, worktree,
4504 argv[0]);
4505 if (error)
4506 goto done;
4507 } else {
4508 path = strdup(argv[0]);
4509 if (path == NULL) {
4510 error = got_error_from_errno("strdup");
4511 goto done;
4514 } else if (argc != 0)
4515 usage_log();
4517 if (repo_path == NULL) {
4518 repo_path = worktree ?
4519 strdup(got_worktree_get_repo_path(worktree)) : strdup(cwd);
4521 if (repo_path == NULL) {
4522 error = got_error_from_errno("strdup");
4523 goto done;
4526 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
4527 if (error != NULL)
4528 goto done;
4530 error = apply_unveil(got_repo_get_path(repo), 1,
4531 worktree ? got_worktree_get_root_path(worktree) : NULL);
4532 if (error)
4533 goto done;
4535 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
4536 if (error)
4537 goto done;
4539 error = got_reflist_object_id_map_create(&refs_idmap, &refs, repo);
4540 if (error)
4541 goto done;
4543 if (start_commit == NULL) {
4544 struct got_reference *head_ref;
4545 struct got_commit_object *commit = NULL;
4546 error = got_ref_open(&head_ref, repo,
4547 worktree ? got_worktree_get_head_ref_name(worktree)
4548 : GOT_REF_HEAD, 0);
4549 if (error != NULL)
4550 goto done;
4551 error = got_ref_resolve(&start_id, repo, head_ref);
4552 got_ref_close(head_ref);
4553 if (error != NULL)
4554 goto done;
4555 error = got_object_open_as_commit(&commit, repo,
4556 start_id);
4557 if (error != NULL)
4558 goto done;
4559 got_object_commit_close(commit);
4560 } else {
4561 error = got_repo_match_object_id(&start_id, NULL,
4562 start_commit, GOT_OBJ_TYPE_COMMIT, &refs, repo);
4563 if (error != NULL)
4564 goto done;
4566 if (end_commit != NULL) {
4567 error = got_repo_match_object_id(&end_id, NULL,
4568 end_commit, GOT_OBJ_TYPE_COMMIT, &refs, repo);
4569 if (error != NULL)
4570 goto done;
4573 if (worktree) {
4575 * If a path was specified on the command line it was resolved
4576 * to a path in the work tree above. Prepend the work tree's
4577 * path prefix to obtain the corresponding in-repository path.
4579 if (path) {
4580 const char *prefix;
4581 prefix = got_worktree_get_path_prefix(worktree);
4582 if (asprintf(&in_repo_path, "%s%s%s", prefix,
4583 (path[0] != '\0') ? "/" : "", path) == -1) {
4584 error = got_error_from_errno("asprintf");
4585 goto done;
4588 } else
4589 error = got_repo_map_path(&in_repo_path, repo,
4590 path ? path : "");
4591 if (error != NULL)
4592 goto done;
4593 if (in_repo_path) {
4594 free(path);
4595 path = in_repo_path;
4598 if (worktree) {
4599 /* Release work tree lock. */
4600 got_worktree_close(worktree);
4601 worktree = NULL;
4604 if (search_pattern && show_patch) {
4605 tmpfile = got_opentemp();
4606 if (tmpfile == NULL) {
4607 error = got_error_from_errno("got_opentemp");
4608 goto done;
4612 error = print_commits(start_id, end_id, repo, path ? path : "",
4613 show_changed_paths, show_patch, search_pattern, diff_context,
4614 limit, log_branches, reverse_display_order, refs_idmap, one_line,
4615 tmpfile);
4616 done:
4617 free(path);
4618 free(repo_path);
4619 free(cwd);
4620 if (worktree)
4621 got_worktree_close(worktree);
4622 if (repo) {
4623 const struct got_error *close_err = got_repo_close(repo);
4624 if (error == NULL)
4625 error = close_err;
4627 if (pack_fds) {
4628 const struct got_error *pack_err =
4629 got_repo_pack_fds_close(pack_fds);
4630 if (error == NULL)
4631 error = pack_err;
4633 if (refs_idmap)
4634 got_reflist_object_id_map_free(refs_idmap);
4635 if (tmpfile && fclose(tmpfile) == EOF && error == NULL)
4636 error = got_error_from_errno("fclose");
4637 got_ref_list_free(&refs);
4638 return error;
4641 __dead static void
4642 usage_diff(void)
4644 fprintf(stderr, "usage: %s diff [-aPsw] [-C number] [-c commit] "
4645 "[-r repository-path] [object1 object2 | path ...]\n",
4646 getprogname());
4647 exit(1);
4650 struct print_diff_arg {
4651 struct got_repository *repo;
4652 struct got_worktree *worktree;
4653 int diff_context;
4654 const char *id_str;
4655 int header_shown;
4656 int diff_staged;
4657 enum got_diff_algorithm diff_algo;
4658 int ignore_whitespace;
4659 int force_text_diff;
4660 FILE *f1;
4661 FILE *f2;
4665 * Create a file which contains the target path of a symlink so we can feed
4666 * it as content to the diff engine.
4668 static const struct got_error *
4669 get_symlink_target_file(int *fd, int dirfd, const char *de_name,
4670 const char *abspath)
4672 const struct got_error *err = NULL;
4673 char target_path[PATH_MAX];
4674 ssize_t target_len, outlen;
4676 *fd = -1;
4678 if (dirfd != -1) {
4679 target_len = readlinkat(dirfd, de_name, target_path, PATH_MAX);
4680 if (target_len == -1)
4681 return got_error_from_errno2("readlinkat", abspath);
4682 } else {
4683 target_len = readlink(abspath, target_path, PATH_MAX);
4684 if (target_len == -1)
4685 return got_error_from_errno2("readlink", abspath);
4688 *fd = got_opentempfd();
4689 if (*fd == -1)
4690 return got_error_from_errno("got_opentempfd");
4692 outlen = write(*fd, target_path, target_len);
4693 if (outlen == -1) {
4694 err = got_error_from_errno("got_opentempfd");
4695 goto done;
4698 if (lseek(*fd, 0, SEEK_SET) == -1) {
4699 err = got_error_from_errno2("lseek", abspath);
4700 goto done;
4702 done:
4703 if (err) {
4704 close(*fd);
4705 *fd = -1;
4707 return err;
4710 static const struct got_error *
4711 print_diff(void *arg, unsigned char status, unsigned char staged_status,
4712 const char *path, struct got_object_id *blob_id,
4713 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
4714 int dirfd, const char *de_name)
4716 struct print_diff_arg *a = arg;
4717 const struct got_error *err = NULL;
4718 struct got_blob_object *blob1 = NULL;
4719 int fd = -1, fd1 = -1, fd2 = -1;
4720 FILE *f2 = NULL;
4721 char *abspath = NULL, *label1 = NULL;
4722 struct stat sb;
4723 off_t size1 = 0;
4724 int f2_exists = 0;
4726 memset(&sb, 0, sizeof(sb));
4728 if (a->diff_staged) {
4729 if (staged_status != GOT_STATUS_MODIFY &&
4730 staged_status != GOT_STATUS_ADD &&
4731 staged_status != GOT_STATUS_DELETE)
4732 return NULL;
4733 } else {
4734 if (staged_status == GOT_STATUS_DELETE)
4735 return NULL;
4736 if (status == GOT_STATUS_NONEXISTENT)
4737 return got_error_set_errno(ENOENT, path);
4738 if (status != GOT_STATUS_MODIFY &&
4739 status != GOT_STATUS_ADD &&
4740 status != GOT_STATUS_DELETE &&
4741 status != GOT_STATUS_CONFLICT)
4742 return NULL;
4745 err = got_opentemp_truncate(a->f1);
4746 if (err)
4747 return got_error_from_errno("got_opentemp_truncate");
4748 err = got_opentemp_truncate(a->f2);
4749 if (err)
4750 return got_error_from_errno("got_opentemp_truncate");
4752 if (!a->header_shown) {
4753 printf("diff %s%s\n", a->diff_staged ? "-s " : "",
4754 got_worktree_get_root_path(a->worktree));
4755 printf("commit - %s\n", a->id_str);
4756 printf("path + %s%s\n",
4757 got_worktree_get_root_path(a->worktree),
4758 a->diff_staged ? " (staged changes)" : "");
4759 a->header_shown = 1;
4762 if (a->diff_staged) {
4763 const char *label1 = NULL, *label2 = NULL;
4764 switch (staged_status) {
4765 case GOT_STATUS_MODIFY:
4766 label1 = path;
4767 label2 = path;
4768 break;
4769 case GOT_STATUS_ADD:
4770 label2 = path;
4771 break;
4772 case GOT_STATUS_DELETE:
4773 label1 = path;
4774 break;
4775 default:
4776 return got_error(GOT_ERR_FILE_STATUS);
4778 fd1 = got_opentempfd();
4779 if (fd1 == -1) {
4780 err = got_error_from_errno("got_opentempfd");
4781 goto done;
4783 fd2 = got_opentempfd();
4784 if (fd2 == -1) {
4785 err = got_error_from_errno("got_opentempfd");
4786 goto done;
4788 err = got_diff_objects_as_blobs(NULL, NULL, a->f1, a->f2,
4789 fd1, fd2, blob_id, staged_blob_id, label1, label2,
4790 a->diff_algo, a->diff_context, a->ignore_whitespace,
4791 a->force_text_diff, a->repo, stdout);
4792 goto done;
4795 fd1 = got_opentempfd();
4796 if (fd1 == -1) {
4797 err = got_error_from_errno("got_opentempfd");
4798 goto done;
4801 if (staged_status == GOT_STATUS_ADD ||
4802 staged_status == GOT_STATUS_MODIFY) {
4803 char *id_str;
4804 err = got_object_open_as_blob(&blob1, a->repo, staged_blob_id,
4805 8192, fd1);
4806 if (err)
4807 goto done;
4808 err = got_object_id_str(&id_str, staged_blob_id);
4809 if (err)
4810 goto done;
4811 if (asprintf(&label1, "%s (staged)", id_str) == -1) {
4812 err = got_error_from_errno("asprintf");
4813 free(id_str);
4814 goto done;
4816 free(id_str);
4817 } else if (status != GOT_STATUS_ADD) {
4818 err = got_object_open_as_blob(&blob1, a->repo, blob_id, 8192,
4819 fd1);
4820 if (err)
4821 goto done;
4824 if (status != GOT_STATUS_DELETE) {
4825 if (asprintf(&abspath, "%s/%s",
4826 got_worktree_get_root_path(a->worktree), path) == -1) {
4827 err = got_error_from_errno("asprintf");
4828 goto done;
4831 if (dirfd != -1) {
4832 fd = openat(dirfd, de_name,
4833 O_RDONLY | O_NOFOLLOW | O_CLOEXEC);
4834 if (fd == -1) {
4835 if (!got_err_open_nofollow_on_symlink()) {
4836 err = got_error_from_errno2("openat",
4837 abspath);
4838 goto done;
4840 err = get_symlink_target_file(&fd, dirfd,
4841 de_name, abspath);
4842 if (err)
4843 goto done;
4845 } else {
4846 fd = open(abspath, O_RDONLY | O_NOFOLLOW | O_CLOEXEC);
4847 if (fd == -1) {
4848 if (!got_err_open_nofollow_on_symlink()) {
4849 err = got_error_from_errno2("open",
4850 abspath);
4851 goto done;
4853 err = get_symlink_target_file(&fd, dirfd,
4854 de_name, abspath);
4855 if (err)
4856 goto done;
4859 if (fstatat(fd, abspath, &sb, AT_SYMLINK_NOFOLLOW) == -1) {
4860 err = got_error_from_errno2("fstatat", abspath);
4861 goto done;
4863 f2 = fdopen(fd, "r");
4864 if (f2 == NULL) {
4865 err = got_error_from_errno2("fdopen", abspath);
4866 goto done;
4868 fd = -1;
4869 f2_exists = 1;
4872 if (blob1) {
4873 err = got_object_blob_dump_to_file(&size1, NULL, NULL,
4874 a->f1, blob1);
4875 if (err)
4876 goto done;
4879 err = got_diff_blob_file(blob1, a->f1, size1, label1, f2 ? f2 : a->f2,
4880 f2_exists, &sb, path, GOT_DIFF_ALGORITHM_PATIENCE, a->diff_context,
4881 a->ignore_whitespace, a->force_text_diff, stdout);
4882 done:
4883 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
4884 err = got_error_from_errno("close");
4885 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
4886 err = got_error_from_errno("close");
4887 if (blob1)
4888 got_object_blob_close(blob1);
4889 if (fd != -1 && close(fd) == -1 && err == NULL)
4890 err = got_error_from_errno("close");
4891 if (f2 && fclose(f2) == EOF && err == NULL)
4892 err = got_error_from_errno("fclose");
4893 free(abspath);
4894 return err;
4897 static const struct got_error *
4898 cmd_diff(int argc, char *argv[])
4900 const struct got_error *error;
4901 struct got_repository *repo = NULL;
4902 struct got_worktree *worktree = NULL;
4903 char *cwd = NULL, *repo_path = NULL;
4904 const char *commit_args[2] = { NULL, NULL };
4905 int ncommit_args = 0;
4906 struct got_object_id *ids[2] = { NULL, NULL };
4907 char *labels[2] = { NULL, NULL };
4908 int type1 = GOT_OBJ_TYPE_ANY, type2 = GOT_OBJ_TYPE_ANY;
4909 int diff_context = 3, diff_staged = 0, ignore_whitespace = 0, ch, i;
4910 int force_text_diff = 0, force_path = 0, rflag = 0;
4911 const char *errstr;
4912 struct got_reflist_head refs;
4913 struct got_pathlist_head paths;
4914 struct got_pathlist_entry *pe;
4915 FILE *f1 = NULL, *f2 = NULL;
4916 int fd1 = -1, fd2 = -1;
4917 int *pack_fds = NULL;
4919 TAILQ_INIT(&refs);
4920 TAILQ_INIT(&paths);
4922 #ifndef PROFILE
4923 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
4924 NULL) == -1)
4925 err(1, "pledge");
4926 #endif
4928 while ((ch = getopt(argc, argv, "aC:c:Pr:sw")) != -1) {
4929 switch (ch) {
4930 case 'a':
4931 force_text_diff = 1;
4932 break;
4933 case 'C':
4934 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
4935 &errstr);
4936 if (errstr != NULL)
4937 errx(1, "number of context lines is %s: %s",
4938 errstr, optarg);
4939 break;
4940 case 'c':
4941 if (ncommit_args >= 2)
4942 errx(1, "too many -c options used");
4943 commit_args[ncommit_args++] = optarg;
4944 break;
4945 case 'P':
4946 force_path = 1;
4947 break;
4948 case 'r':
4949 repo_path = realpath(optarg, NULL);
4950 if (repo_path == NULL)
4951 return got_error_from_errno2("realpath",
4952 optarg);
4953 got_path_strip_trailing_slashes(repo_path);
4954 rflag = 1;
4955 break;
4956 case 's':
4957 diff_staged = 1;
4958 break;
4959 case 'w':
4960 ignore_whitespace = 1;
4961 break;
4962 default:
4963 usage_diff();
4964 /* NOTREACHED */
4968 argc -= optind;
4969 argv += optind;
4971 cwd = getcwd(NULL, 0);
4972 if (cwd == NULL) {
4973 error = got_error_from_errno("getcwd");
4974 goto done;
4977 error = got_repo_pack_fds_open(&pack_fds);
4978 if (error != NULL)
4979 goto done;
4981 if (repo_path == NULL) {
4982 error = got_worktree_open(&worktree, cwd);
4983 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4984 goto done;
4985 else
4986 error = NULL;
4987 if (worktree) {
4988 repo_path =
4989 strdup(got_worktree_get_repo_path(worktree));
4990 if (repo_path == NULL) {
4991 error = got_error_from_errno("strdup");
4992 goto done;
4994 } else {
4995 repo_path = strdup(cwd);
4996 if (repo_path == NULL) {
4997 error = got_error_from_errno("strdup");
4998 goto done;
5003 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
5004 free(repo_path);
5005 if (error != NULL)
5006 goto done;
5008 if (rflag || worktree == NULL || ncommit_args > 0) {
5009 if (force_path) {
5010 error = got_error_msg(GOT_ERR_NOT_IMPL,
5011 "-P option can only be used when diffing "
5012 "a work tree");
5013 goto done;
5015 if (diff_staged) {
5016 error = got_error_msg(GOT_ERR_NOT_IMPL,
5017 "-s option can only be used when diffing "
5018 "a work tree");
5019 goto done;
5023 error = apply_unveil(got_repo_get_path(repo), 1,
5024 worktree ? got_worktree_get_root_path(worktree) : NULL);
5025 if (error)
5026 goto done;
5028 if ((!force_path && argc == 2) || ncommit_args > 0) {
5029 int obj_type = (ncommit_args > 0 ?
5030 GOT_OBJ_TYPE_COMMIT : GOT_OBJ_TYPE_ANY);
5031 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
5032 NULL);
5033 if (error)
5034 goto done;
5035 for (i = 0; i < (ncommit_args > 0 ? ncommit_args : argc); i++) {
5036 const char *arg;
5037 if (ncommit_args > 0)
5038 arg = commit_args[i];
5039 else
5040 arg = argv[i];
5041 error = got_repo_match_object_id(&ids[i], &labels[i],
5042 arg, obj_type, &refs, repo);
5043 if (error) {
5044 if (error->code != GOT_ERR_NOT_REF &&
5045 error->code != GOT_ERR_NO_OBJ)
5046 goto done;
5047 if (ncommit_args > 0)
5048 goto done;
5049 error = NULL;
5050 break;
5055 f1 = got_opentemp();
5056 if (f1 == NULL) {
5057 error = got_error_from_errno("got_opentemp");
5058 goto done;
5061 f2 = got_opentemp();
5062 if (f2 == NULL) {
5063 error = got_error_from_errno("got_opentemp");
5064 goto done;
5067 if (ncommit_args == 0 && (ids[0] == NULL || ids[1] == NULL)) {
5068 struct print_diff_arg arg;
5069 char *id_str;
5071 if (worktree == NULL) {
5072 if (argc == 2 && ids[0] == NULL) {
5073 error = got_error_path(argv[0], GOT_ERR_NO_OBJ);
5074 goto done;
5075 } else if (argc == 2 && ids[1] == NULL) {
5076 error = got_error_path(argv[1], GOT_ERR_NO_OBJ);
5077 goto done;
5078 } else if (argc > 0) {
5079 error = got_error_fmt(GOT_ERR_NOT_WORKTREE,
5080 "%s", "specified paths cannot be resolved");
5081 goto done;
5082 } else {
5083 error = got_error(GOT_ERR_NOT_WORKTREE);
5084 goto done;
5088 error = get_worktree_paths_from_argv(&paths, argc, argv,
5089 worktree);
5090 if (error)
5091 goto done;
5093 error = got_object_id_str(&id_str,
5094 got_worktree_get_base_commit_id(worktree));
5095 if (error)
5096 goto done;
5097 arg.repo = repo;
5098 arg.worktree = worktree;
5099 arg.diff_algo = GOT_DIFF_ALGORITHM_PATIENCE;
5100 arg.diff_context = diff_context;
5101 arg.id_str = id_str;
5102 arg.header_shown = 0;
5103 arg.diff_staged = diff_staged;
5104 arg.ignore_whitespace = ignore_whitespace;
5105 arg.force_text_diff = force_text_diff;
5106 arg.f1 = f1;
5107 arg.f2 = f2;
5109 error = got_worktree_status(worktree, &paths, repo, 0,
5110 print_diff, &arg, check_cancelled, NULL);
5111 free(id_str);
5112 goto done;
5115 if (ncommit_args == 1) {
5116 struct got_commit_object *commit;
5117 error = got_object_open_as_commit(&commit, repo, ids[0]);
5118 if (error)
5119 goto done;
5121 labels[1] = labels[0];
5122 ids[1] = ids[0];
5123 if (got_object_commit_get_nparents(commit) > 0) {
5124 const struct got_object_id_queue *pids;
5125 struct got_object_qid *pid;
5126 pids = got_object_commit_get_parent_ids(commit);
5127 pid = STAILQ_FIRST(pids);
5128 ids[0] = got_object_id_dup(&pid->id);
5129 if (ids[0] == NULL) {
5130 error = got_error_from_errno(
5131 "got_object_id_dup");
5132 got_object_commit_close(commit);
5133 goto done;
5135 error = got_object_id_str(&labels[0], ids[0]);
5136 if (error) {
5137 got_object_commit_close(commit);
5138 goto done;
5140 } else {
5141 ids[0] = NULL;
5142 labels[0] = strdup("/dev/null");
5143 if (labels[0] == NULL) {
5144 error = got_error_from_errno("strdup");
5145 got_object_commit_close(commit);
5146 goto done;
5150 got_object_commit_close(commit);
5153 if (ncommit_args == 0 && argc > 2) {
5154 error = got_error_msg(GOT_ERR_BAD_PATH,
5155 "path arguments cannot be used when diffing two objects");
5156 goto done;
5159 if (ids[0]) {
5160 error = got_object_get_type(&type1, repo, ids[0]);
5161 if (error)
5162 goto done;
5165 error = got_object_get_type(&type2, repo, ids[1]);
5166 if (error)
5167 goto done;
5168 if (type1 != GOT_OBJ_TYPE_ANY && type1 != type2) {
5169 error = got_error(GOT_ERR_OBJ_TYPE);
5170 goto done;
5172 if (type1 == GOT_OBJ_TYPE_BLOB && argc > 2) {
5173 error = got_error_msg(GOT_ERR_OBJ_TYPE,
5174 "path arguments cannot be used when diffing blobs");
5175 goto done;
5178 for (i = 0; ncommit_args > 0 && i < argc; i++) {
5179 char *in_repo_path;
5180 struct got_pathlist_entry *new;
5181 if (worktree) {
5182 const char *prefix;
5183 char *p;
5184 error = got_worktree_resolve_path(&p, worktree,
5185 argv[i]);
5186 if (error)
5187 goto done;
5188 prefix = got_worktree_get_path_prefix(worktree);
5189 while (prefix[0] == '/')
5190 prefix++;
5191 if (asprintf(&in_repo_path, "%s%s%s", prefix,
5192 (p[0] != '\0' && prefix[0] != '\0') ? "/" : "",
5193 p) == -1) {
5194 error = got_error_from_errno("asprintf");
5195 free(p);
5196 goto done;
5198 free(p);
5199 } else {
5200 char *mapped_path, *s;
5201 error = got_repo_map_path(&mapped_path, repo, argv[i]);
5202 if (error)
5203 goto done;
5204 s = mapped_path;
5205 while (s[0] == '/')
5206 s++;
5207 in_repo_path = strdup(s);
5208 if (in_repo_path == NULL) {
5209 error = got_error_from_errno("asprintf");
5210 free(mapped_path);
5211 goto done;
5213 free(mapped_path);
5216 error = got_pathlist_insert(&new, &paths, in_repo_path, NULL);
5217 if (error || new == NULL /* duplicate */)
5218 free(in_repo_path);
5219 if (error)
5220 goto done;
5223 if (worktree) {
5224 /* Release work tree lock. */
5225 got_worktree_close(worktree);
5226 worktree = NULL;
5229 fd1 = got_opentempfd();
5230 if (fd1 == -1) {
5231 error = got_error_from_errno("got_opentempfd");
5232 goto done;
5235 fd2 = got_opentempfd();
5236 if (fd2 == -1) {
5237 error = got_error_from_errno("got_opentempfd");
5238 goto done;
5241 switch (type1 == GOT_OBJ_TYPE_ANY ? type2 : type1) {
5242 case GOT_OBJ_TYPE_BLOB:
5243 error = got_diff_objects_as_blobs(NULL, NULL, f1, f2,
5244 fd1, fd2, ids[0], ids[1], NULL, NULL,
5245 GOT_DIFF_ALGORITHM_PATIENCE, diff_context,
5246 ignore_whitespace, force_text_diff, repo, stdout);
5247 break;
5248 case GOT_OBJ_TYPE_TREE:
5249 error = got_diff_objects_as_trees(NULL, NULL, f1, f2, fd1, fd2,
5250 ids[0], ids[1], &paths, "", "",
5251 GOT_DIFF_ALGORITHM_PATIENCE, diff_context,
5252 ignore_whitespace, force_text_diff, repo, stdout);
5253 break;
5254 case GOT_OBJ_TYPE_COMMIT:
5255 printf("diff %s %s\n", labels[0], labels[1]);
5256 error = got_diff_objects_as_commits(NULL, NULL, f1, f2,
5257 fd1, fd2, ids[0], ids[1], &paths,
5258 GOT_DIFF_ALGORITHM_PATIENCE, diff_context,
5259 ignore_whitespace, force_text_diff, repo, stdout);
5260 break;
5261 default:
5262 error = got_error(GOT_ERR_OBJ_TYPE);
5264 done:
5265 free(labels[0]);
5266 free(labels[1]);
5267 free(ids[0]);
5268 free(ids[1]);
5269 if (worktree)
5270 got_worktree_close(worktree);
5271 if (repo) {
5272 const struct got_error *close_err = got_repo_close(repo);
5273 if (error == NULL)
5274 error = close_err;
5276 if (pack_fds) {
5277 const struct got_error *pack_err =
5278 got_repo_pack_fds_close(pack_fds);
5279 if (error == NULL)
5280 error = pack_err;
5282 TAILQ_FOREACH(pe, &paths, entry)
5283 free((char *)pe->path);
5284 got_pathlist_free(&paths);
5285 got_ref_list_free(&refs);
5286 if (f1 && fclose(f1) == EOF && error == NULL)
5287 error = got_error_from_errno("fclose");
5288 if (f2 && fclose(f2) == EOF && error == NULL)
5289 error = got_error_from_errno("fclose");
5290 if (fd1 != -1 && close(fd1) == -1 && error == NULL)
5291 error = got_error_from_errno("close");
5292 if (fd2 != -1 && close(fd2) == -1 && error == NULL)
5293 error = got_error_from_errno("close");
5294 return error;
5297 __dead static void
5298 usage_blame(void)
5300 fprintf(stderr,
5301 "usage: %s blame [-c commit] [-r repository-path] path\n",
5302 getprogname());
5303 exit(1);
5306 struct blame_line {
5307 int annotated;
5308 char *id_str;
5309 char *committer;
5310 char datebuf[11]; /* YYYY-MM-DD + NUL */
5313 struct blame_cb_args {
5314 struct blame_line *lines;
5315 int nlines;
5316 int nlines_prec;
5317 int lineno_cur;
5318 off_t *line_offsets;
5319 FILE *f;
5320 struct got_repository *repo;
5323 static const struct got_error *
5324 blame_cb(void *arg, int nlines, int lineno,
5325 struct got_commit_object *commit, struct got_object_id *id)
5327 const struct got_error *err = NULL;
5328 struct blame_cb_args *a = arg;
5329 struct blame_line *bline;
5330 char *line = NULL;
5331 size_t linesize = 0;
5332 off_t offset;
5333 struct tm tm;
5334 time_t committer_time;
5336 if (nlines != a->nlines ||
5337 (lineno != -1 && lineno < 1) || lineno > a->nlines)
5338 return got_error(GOT_ERR_RANGE);
5340 if (sigint_received)
5341 return got_error(GOT_ERR_ITER_COMPLETED);
5343 if (lineno == -1)
5344 return NULL; /* no change in this commit */
5346 /* Annotate this line. */
5347 bline = &a->lines[lineno - 1];
5348 if (bline->annotated)
5349 return NULL;
5350 err = got_object_id_str(&bline->id_str, id);
5351 if (err)
5352 return err;
5354 bline->committer = strdup(got_object_commit_get_committer(commit));
5355 if (bline->committer == NULL) {
5356 err = got_error_from_errno("strdup");
5357 goto done;
5360 committer_time = got_object_commit_get_committer_time(commit);
5361 if (gmtime_r(&committer_time, &tm) == NULL)
5362 return got_error_from_errno("gmtime_r");
5363 if (strftime(bline->datebuf, sizeof(bline->datebuf), "%G-%m-%d",
5364 &tm) == 0) {
5365 err = got_error(GOT_ERR_NO_SPACE);
5366 goto done;
5368 bline->annotated = 1;
5370 /* Print lines annotated so far. */
5371 bline = &a->lines[a->lineno_cur - 1];
5372 if (!bline->annotated)
5373 goto done;
5375 offset = a->line_offsets[a->lineno_cur - 1];
5376 if (fseeko(a->f, offset, SEEK_SET) == -1) {
5377 err = got_error_from_errno("fseeko");
5378 goto done;
5381 while (a->lineno_cur <= a->nlines && bline->annotated) {
5382 char *smallerthan, *at, *nl, *committer;
5383 size_t len;
5385 if (getline(&line, &linesize, a->f) == -1) {
5386 if (ferror(a->f))
5387 err = got_error_from_errno("getline");
5388 break;
5391 committer = bline->committer;
5392 smallerthan = strchr(committer, '<');
5393 if (smallerthan && smallerthan[1] != '\0')
5394 committer = smallerthan + 1;
5395 at = strchr(committer, '@');
5396 if (at)
5397 *at = '\0';
5398 len = strlen(committer);
5399 if (len >= 9)
5400 committer[8] = '\0';
5402 nl = strchr(line, '\n');
5403 if (nl)
5404 *nl = '\0';
5405 printf("%.*d) %.8s %s %-8s %s\n", a->nlines_prec, a->lineno_cur,
5406 bline->id_str, bline->datebuf, committer, line);
5408 a->lineno_cur++;
5409 bline = &a->lines[a->lineno_cur - 1];
5411 done:
5412 free(line);
5413 return err;
5416 static const struct got_error *
5417 cmd_blame(int argc, char *argv[])
5419 const struct got_error *error;
5420 struct got_repository *repo = NULL;
5421 struct got_worktree *worktree = NULL;
5422 char *path, *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
5423 char *link_target = NULL;
5424 struct got_object_id *obj_id = NULL;
5425 struct got_object_id *commit_id = NULL;
5426 struct got_commit_object *commit = NULL;
5427 struct got_blob_object *blob = NULL;
5428 char *commit_id_str = NULL;
5429 struct blame_cb_args bca;
5430 int ch, obj_type, i, fd1 = -1, fd2 = -1, fd3 = -1;
5431 off_t filesize;
5432 int *pack_fds = NULL;
5433 FILE *f1 = NULL, *f2 = NULL;
5435 fd1 = got_opentempfd();
5436 if (fd1 == -1)
5437 return got_error_from_errno("got_opentempfd");
5439 memset(&bca, 0, sizeof(bca));
5441 #ifndef PROFILE
5442 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
5443 NULL) == -1)
5444 err(1, "pledge");
5445 #endif
5447 while ((ch = getopt(argc, argv, "c:r:")) != -1) {
5448 switch (ch) {
5449 case 'c':
5450 commit_id_str = optarg;
5451 break;
5452 case 'r':
5453 repo_path = realpath(optarg, NULL);
5454 if (repo_path == NULL)
5455 return got_error_from_errno2("realpath",
5456 optarg);
5457 got_path_strip_trailing_slashes(repo_path);
5458 break;
5459 default:
5460 usage_blame();
5461 /* NOTREACHED */
5465 argc -= optind;
5466 argv += optind;
5468 if (argc == 1)
5469 path = argv[0];
5470 else
5471 usage_blame();
5473 cwd = getcwd(NULL, 0);
5474 if (cwd == NULL) {
5475 error = got_error_from_errno("getcwd");
5476 goto done;
5479 error = got_repo_pack_fds_open(&pack_fds);
5480 if (error != NULL)
5481 goto done;
5483 if (repo_path == NULL) {
5484 error = got_worktree_open(&worktree, cwd);
5485 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5486 goto done;
5487 else
5488 error = NULL;
5489 if (worktree) {
5490 repo_path =
5491 strdup(got_worktree_get_repo_path(worktree));
5492 if (repo_path == NULL) {
5493 error = got_error_from_errno("strdup");
5494 if (error)
5495 goto done;
5497 } else {
5498 repo_path = strdup(cwd);
5499 if (repo_path == NULL) {
5500 error = got_error_from_errno("strdup");
5501 goto done;
5506 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
5507 if (error != NULL)
5508 goto done;
5510 if (worktree) {
5511 const char *prefix = got_worktree_get_path_prefix(worktree);
5512 char *p;
5514 error = got_worktree_resolve_path(&p, worktree, path);
5515 if (error)
5516 goto done;
5517 if (asprintf(&in_repo_path, "%s%s%s", prefix,
5518 (p[0] != '\0' && !got_path_is_root_dir(prefix)) ? "/" : "",
5519 p) == -1) {
5520 error = got_error_from_errno("asprintf");
5521 free(p);
5522 goto done;
5524 free(p);
5525 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5526 } else {
5527 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5528 if (error)
5529 goto done;
5530 error = got_repo_map_path(&in_repo_path, repo, path);
5532 if (error)
5533 goto done;
5535 if (commit_id_str == NULL) {
5536 struct got_reference *head_ref;
5537 error = got_ref_open(&head_ref, repo, worktree ?
5538 got_worktree_get_head_ref_name(worktree) : GOT_REF_HEAD, 0);
5539 if (error != NULL)
5540 goto done;
5541 error = got_ref_resolve(&commit_id, repo, head_ref);
5542 got_ref_close(head_ref);
5543 if (error != NULL)
5544 goto done;
5545 } else {
5546 struct got_reflist_head refs;
5547 TAILQ_INIT(&refs);
5548 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
5549 NULL);
5550 if (error)
5551 goto done;
5552 error = got_repo_match_object_id(&commit_id, NULL,
5553 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
5554 got_ref_list_free(&refs);
5555 if (error)
5556 goto done;
5559 if (worktree) {
5560 /* Release work tree lock. */
5561 got_worktree_close(worktree);
5562 worktree = NULL;
5565 error = got_object_open_as_commit(&commit, repo, commit_id);
5566 if (error)
5567 goto done;
5569 error = got_object_resolve_symlinks(&link_target, in_repo_path,
5570 commit, repo);
5571 if (error)
5572 goto done;
5574 error = got_object_id_by_path(&obj_id, repo, commit,
5575 link_target ? link_target : in_repo_path);
5576 if (error)
5577 goto done;
5579 error = got_object_get_type(&obj_type, repo, obj_id);
5580 if (error)
5581 goto done;
5583 if (obj_type != GOT_OBJ_TYPE_BLOB) {
5584 error = got_error_path(link_target ? link_target : in_repo_path,
5585 GOT_ERR_OBJ_TYPE);
5586 goto done;
5589 error = got_object_open_as_blob(&blob, repo, obj_id, 8192, fd1);
5590 if (error)
5591 goto done;
5592 bca.f = got_opentemp();
5593 if (bca.f == NULL) {
5594 error = got_error_from_errno("got_opentemp");
5595 goto done;
5597 error = got_object_blob_dump_to_file(&filesize, &bca.nlines,
5598 &bca.line_offsets, bca.f, blob);
5599 if (error || bca.nlines == 0)
5600 goto done;
5602 /* Don't include \n at EOF in the blame line count. */
5603 if (bca.line_offsets[bca.nlines - 1] == filesize)
5604 bca.nlines--;
5606 bca.lines = calloc(bca.nlines, sizeof(*bca.lines));
5607 if (bca.lines == NULL) {
5608 error = got_error_from_errno("calloc");
5609 goto done;
5611 bca.lineno_cur = 1;
5612 bca.nlines_prec = 0;
5613 i = bca.nlines;
5614 while (i > 0) {
5615 i /= 10;
5616 bca.nlines_prec++;
5618 bca.repo = repo;
5620 fd2 = got_opentempfd();
5621 if (fd2 == -1) {
5622 error = got_error_from_errno("got_opentempfd");
5623 goto done;
5625 fd3 = got_opentempfd();
5626 if (fd3 == -1) {
5627 error = got_error_from_errno("got_opentempfd");
5628 goto done;
5630 f1 = got_opentemp();
5631 if (f1 == NULL) {
5632 error = got_error_from_errno("got_opentemp");
5633 goto done;
5635 f2 = got_opentemp();
5636 if (f2 == NULL) {
5637 error = got_error_from_errno("got_opentemp");
5638 goto done;
5640 error = got_blame(link_target ? link_target : in_repo_path, commit_id,
5641 repo, GOT_DIFF_ALGORITHM_PATIENCE, blame_cb, &bca,
5642 check_cancelled, NULL, fd2, fd3, f1, f2);
5643 done:
5644 free(in_repo_path);
5645 free(link_target);
5646 free(repo_path);
5647 free(cwd);
5648 free(commit_id);
5649 free(obj_id);
5650 if (commit)
5651 got_object_commit_close(commit);
5653 if (fd1 != -1 && close(fd1) == -1 && error == NULL)
5654 error = got_error_from_errno("close");
5655 if (fd2 != -1 && close(fd2) == -1 && error == NULL)
5656 error = got_error_from_errno("close");
5657 if (fd3 != -1 && close(fd3) == -1 && error == NULL)
5658 error = got_error_from_errno("close");
5659 if (f1 && fclose(f1) == EOF && error == NULL)
5660 error = got_error_from_errno("fclose");
5661 if (f2 && fclose(f2) == EOF && error == NULL)
5662 error = got_error_from_errno("fclose");
5664 if (blob)
5665 got_object_blob_close(blob);
5666 if (worktree)
5667 got_worktree_close(worktree);
5668 if (repo) {
5669 const struct got_error *close_err = got_repo_close(repo);
5670 if (error == NULL)
5671 error = close_err;
5673 if (pack_fds) {
5674 const struct got_error *pack_err =
5675 got_repo_pack_fds_close(pack_fds);
5676 if (error == NULL)
5677 error = pack_err;
5679 if (bca.lines) {
5680 for (i = 0; i < bca.nlines; i++) {
5681 struct blame_line *bline = &bca.lines[i];
5682 free(bline->id_str);
5683 free(bline->committer);
5685 free(bca.lines);
5687 free(bca.line_offsets);
5688 if (bca.f && fclose(bca.f) == EOF && error == NULL)
5689 error = got_error_from_errno("fclose");
5690 return error;
5693 __dead static void
5694 usage_tree(void)
5696 fprintf(stderr, "usage: %s tree [-iR] [-c commit] [-r repository-path] "
5697 "[path]\n", getprogname());
5698 exit(1);
5701 static const struct got_error *
5702 print_entry(struct got_tree_entry *te, const char *id, const char *path,
5703 const char *root_path, struct got_repository *repo)
5705 const struct got_error *err = NULL;
5706 int is_root_path = (strcmp(path, root_path) == 0);
5707 const char *modestr = "";
5708 mode_t mode = got_tree_entry_get_mode(te);
5709 char *link_target = NULL;
5711 path += strlen(root_path);
5712 while (path[0] == '/')
5713 path++;
5715 if (got_object_tree_entry_is_submodule(te))
5716 modestr = "$";
5717 else if (S_ISLNK(mode)) {
5718 int i;
5720 err = got_tree_entry_get_symlink_target(&link_target, te, repo);
5721 if (err)
5722 return err;
5723 for (i = 0; i < strlen(link_target); i++) {
5724 if (!isprint((unsigned char)link_target[i]))
5725 link_target[i] = '?';
5728 modestr = "@";
5730 else if (S_ISDIR(mode))
5731 modestr = "/";
5732 else if (mode & S_IXUSR)
5733 modestr = "*";
5735 printf("%s%s%s%s%s%s%s\n", id ? id : "", path,
5736 is_root_path ? "" : "/", got_tree_entry_get_name(te), modestr,
5737 link_target ? " -> ": "", link_target ? link_target : "");
5739 free(link_target);
5740 return NULL;
5743 static const struct got_error *
5744 print_tree(const char *path, struct got_commit_object *commit,
5745 int show_ids, int recurse, const char *root_path,
5746 struct got_repository *repo)
5748 const struct got_error *err = NULL;
5749 struct got_object_id *tree_id = NULL;
5750 struct got_tree_object *tree = NULL;
5751 int nentries, i;
5753 err = got_object_id_by_path(&tree_id, repo, commit, path);
5754 if (err)
5755 goto done;
5757 err = got_object_open_as_tree(&tree, repo, tree_id);
5758 if (err)
5759 goto done;
5760 nentries = got_object_tree_get_nentries(tree);
5761 for (i = 0; i < nentries; i++) {
5762 struct got_tree_entry *te;
5763 char *id = NULL;
5765 if (sigint_received || sigpipe_received)
5766 break;
5768 te = got_object_tree_get_entry(tree, i);
5769 if (show_ids) {
5770 char *id_str;
5771 err = got_object_id_str(&id_str,
5772 got_tree_entry_get_id(te));
5773 if (err)
5774 goto done;
5775 if (asprintf(&id, "%s ", id_str) == -1) {
5776 err = got_error_from_errno("asprintf");
5777 free(id_str);
5778 goto done;
5780 free(id_str);
5782 err = print_entry(te, id, path, root_path, repo);
5783 free(id);
5784 if (err)
5785 goto done;
5787 if (recurse && S_ISDIR(got_tree_entry_get_mode(te))) {
5788 char *child_path;
5789 if (asprintf(&child_path, "%s%s%s", path,
5790 path[0] == '/' && path[1] == '\0' ? "" : "/",
5791 got_tree_entry_get_name(te)) == -1) {
5792 err = got_error_from_errno("asprintf");
5793 goto done;
5795 err = print_tree(child_path, commit, show_ids, 1,
5796 root_path, repo);
5797 free(child_path);
5798 if (err)
5799 goto done;
5802 done:
5803 if (tree)
5804 got_object_tree_close(tree);
5805 free(tree_id);
5806 return err;
5809 static const struct got_error *
5810 cmd_tree(int argc, char *argv[])
5812 const struct got_error *error;
5813 struct got_repository *repo = NULL;
5814 struct got_worktree *worktree = NULL;
5815 const char *path, *refname = NULL;
5816 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
5817 struct got_object_id *commit_id = NULL;
5818 struct got_commit_object *commit = NULL;
5819 char *commit_id_str = NULL;
5820 int show_ids = 0, recurse = 0;
5821 int ch;
5822 int *pack_fds = NULL;
5824 #ifndef PROFILE
5825 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
5826 NULL) == -1)
5827 err(1, "pledge");
5828 #endif
5830 while ((ch = getopt(argc, argv, "c:iRr:")) != -1) {
5831 switch (ch) {
5832 case 'c':
5833 commit_id_str = optarg;
5834 break;
5835 case 'i':
5836 show_ids = 1;
5837 break;
5838 case 'R':
5839 recurse = 1;
5840 break;
5841 case 'r':
5842 repo_path = realpath(optarg, NULL);
5843 if (repo_path == NULL)
5844 return got_error_from_errno2("realpath",
5845 optarg);
5846 got_path_strip_trailing_slashes(repo_path);
5847 break;
5848 default:
5849 usage_tree();
5850 /* NOTREACHED */
5854 argc -= optind;
5855 argv += optind;
5857 if (argc == 1)
5858 path = argv[0];
5859 else if (argc > 1)
5860 usage_tree();
5861 else
5862 path = NULL;
5864 cwd = getcwd(NULL, 0);
5865 if (cwd == NULL) {
5866 error = got_error_from_errno("getcwd");
5867 goto done;
5870 error = got_repo_pack_fds_open(&pack_fds);
5871 if (error != NULL)
5872 goto done;
5874 if (repo_path == NULL) {
5875 error = got_worktree_open(&worktree, cwd);
5876 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5877 goto done;
5878 else
5879 error = NULL;
5880 if (worktree) {
5881 repo_path =
5882 strdup(got_worktree_get_repo_path(worktree));
5883 if (repo_path == NULL)
5884 error = got_error_from_errno("strdup");
5885 if (error)
5886 goto done;
5887 } else {
5888 repo_path = strdup(cwd);
5889 if (repo_path == NULL) {
5890 error = got_error_from_errno("strdup");
5891 goto done;
5896 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
5897 if (error != NULL)
5898 goto done;
5900 if (worktree) {
5901 const char *prefix = got_worktree_get_path_prefix(worktree);
5902 char *p;
5904 if (path == NULL)
5905 path = "";
5906 error = got_worktree_resolve_path(&p, worktree, path);
5907 if (error)
5908 goto done;
5909 if (asprintf(&in_repo_path, "%s%s%s", prefix,
5910 (p[0] != '\0' && !got_path_is_root_dir(prefix)) ? "/" : "",
5911 p) == -1) {
5912 error = got_error_from_errno("asprintf");
5913 free(p);
5914 goto done;
5916 free(p);
5917 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5918 if (error)
5919 goto done;
5920 } else {
5921 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5922 if (error)
5923 goto done;
5924 if (path == NULL)
5925 path = "/";
5926 error = got_repo_map_path(&in_repo_path, repo, path);
5927 if (error != NULL)
5928 goto done;
5931 if (commit_id_str == NULL) {
5932 struct got_reference *head_ref;
5933 if (worktree)
5934 refname = got_worktree_get_head_ref_name(worktree);
5935 else
5936 refname = GOT_REF_HEAD;
5937 error = got_ref_open(&head_ref, repo, refname, 0);
5938 if (error != NULL)
5939 goto done;
5940 error = got_ref_resolve(&commit_id, repo, head_ref);
5941 got_ref_close(head_ref);
5942 if (error != NULL)
5943 goto done;
5944 } else {
5945 struct got_reflist_head refs;
5946 TAILQ_INIT(&refs);
5947 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
5948 NULL);
5949 if (error)
5950 goto done;
5951 error = got_repo_match_object_id(&commit_id, NULL,
5952 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
5953 got_ref_list_free(&refs);
5954 if (error)
5955 goto done;
5958 if (worktree) {
5959 /* Release work tree lock. */
5960 got_worktree_close(worktree);
5961 worktree = NULL;
5964 error = got_object_open_as_commit(&commit, repo, commit_id);
5965 if (error)
5966 goto done;
5968 error = print_tree(in_repo_path, commit, show_ids, recurse,
5969 in_repo_path, repo);
5970 done:
5971 free(in_repo_path);
5972 free(repo_path);
5973 free(cwd);
5974 free(commit_id);
5975 if (commit)
5976 got_object_commit_close(commit);
5977 if (worktree)
5978 got_worktree_close(worktree);
5979 if (repo) {
5980 const struct got_error *close_err = got_repo_close(repo);
5981 if (error == NULL)
5982 error = close_err;
5984 if (pack_fds) {
5985 const struct got_error *pack_err =
5986 got_repo_pack_fds_close(pack_fds);
5987 if (error == NULL)
5988 error = pack_err;
5990 return error;
5993 __dead static void
5994 usage_status(void)
5996 fprintf(stderr, "usage: %s status [-I] [-S status-codes] "
5997 "[-s status-codes] [path ...]\n", getprogname());
5998 exit(1);
6001 struct got_status_arg {
6002 char *status_codes;
6003 int suppress;
6006 static const struct got_error *
6007 print_status(void *arg, unsigned char status, unsigned char staged_status,
6008 const char *path, struct got_object_id *blob_id,
6009 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
6010 int dirfd, const char *de_name)
6012 struct got_status_arg *st = arg;
6014 if (status == staged_status && (status == GOT_STATUS_DELETE))
6015 status = GOT_STATUS_NO_CHANGE;
6016 if (st != NULL && st->status_codes) {
6017 size_t ncodes = strlen(st->status_codes);
6018 int i, j = 0;
6020 for (i = 0; i < ncodes ; i++) {
6021 if (st->suppress) {
6022 if (status == st->status_codes[i] ||
6023 staged_status == st->status_codes[i]) {
6024 j++;
6025 continue;
6027 } else {
6028 if (status == st->status_codes[i] ||
6029 staged_status == st->status_codes[i])
6030 break;
6034 if (st->suppress && j == 0)
6035 goto print;
6037 if (i == ncodes)
6038 return NULL;
6040 print:
6041 printf("%c%c %s\n", status, staged_status, path);
6042 return NULL;
6045 static const struct got_error *
6046 cmd_status(int argc, char *argv[])
6048 const struct got_error *error = NULL;
6049 struct got_repository *repo = NULL;
6050 struct got_worktree *worktree = NULL;
6051 struct got_status_arg st;
6052 char *cwd = NULL;
6053 struct got_pathlist_head paths;
6054 struct got_pathlist_entry *pe;
6055 int ch, i, no_ignores = 0;
6056 int *pack_fds = NULL;
6058 TAILQ_INIT(&paths);
6060 memset(&st, 0, sizeof(st));
6061 st.status_codes = NULL;
6062 st.suppress = 0;
6064 while ((ch = getopt(argc, argv, "IS:s:")) != -1) {
6065 switch (ch) {
6066 case 'I':
6067 no_ignores = 1;
6068 break;
6069 case 'S':
6070 if (st.status_codes != NULL && st.suppress == 0)
6071 option_conflict('S', 's');
6072 st.suppress = 1;
6073 /* fallthrough */
6074 case 's':
6075 for (i = 0; i < strlen(optarg); i++) {
6076 switch (optarg[i]) {
6077 case GOT_STATUS_MODIFY:
6078 case GOT_STATUS_ADD:
6079 case GOT_STATUS_DELETE:
6080 case GOT_STATUS_CONFLICT:
6081 case GOT_STATUS_MISSING:
6082 case GOT_STATUS_OBSTRUCTED:
6083 case GOT_STATUS_UNVERSIONED:
6084 case GOT_STATUS_MODE_CHANGE:
6085 case GOT_STATUS_NONEXISTENT:
6086 break;
6087 default:
6088 errx(1, "invalid status code '%c'",
6089 optarg[i]);
6092 if (ch == 's' && st.suppress)
6093 option_conflict('s', 'S');
6094 st.status_codes = optarg;
6095 break;
6096 default:
6097 usage_status();
6098 /* NOTREACHED */
6102 argc -= optind;
6103 argv += optind;
6105 #ifndef PROFILE
6106 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
6107 NULL) == -1)
6108 err(1, "pledge");
6109 #endif
6110 cwd = getcwd(NULL, 0);
6111 if (cwd == NULL) {
6112 error = got_error_from_errno("getcwd");
6113 goto done;
6116 error = got_repo_pack_fds_open(&pack_fds);
6117 if (error != NULL)
6118 goto done;
6120 error = got_worktree_open(&worktree, cwd);
6121 if (error) {
6122 if (error->code == GOT_ERR_NOT_WORKTREE)
6123 error = wrap_not_worktree_error(error, "status", cwd);
6124 goto done;
6127 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
6128 NULL, pack_fds);
6129 if (error != NULL)
6130 goto done;
6132 error = apply_unveil(got_repo_get_path(repo), 1,
6133 got_worktree_get_root_path(worktree));
6134 if (error)
6135 goto done;
6137 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
6138 if (error)
6139 goto done;
6141 error = got_worktree_status(worktree, &paths, repo, no_ignores,
6142 print_status, &st, check_cancelled, NULL);
6143 done:
6144 if (pack_fds) {
6145 const struct got_error *pack_err =
6146 got_repo_pack_fds_close(pack_fds);
6147 if (error == NULL)
6148 error = pack_err;
6151 TAILQ_FOREACH(pe, &paths, entry)
6152 free((char *)pe->path);
6153 got_pathlist_free(&paths);
6154 free(cwd);
6155 return error;
6158 __dead static void
6159 usage_ref(void)
6161 fprintf(stderr, "usage: %s ref [-dlt] [-c object] [-r repository-path] "
6162 "[-s reference] [name]\n", getprogname());
6163 exit(1);
6166 static const struct got_error *
6167 list_refs(struct got_repository *repo, const char *refname, int sort_by_time)
6169 static const struct got_error *err = NULL;
6170 struct got_reflist_head refs;
6171 struct got_reflist_entry *re;
6173 TAILQ_INIT(&refs);
6174 err = got_ref_list(&refs, repo, refname, sort_by_time ?
6175 got_ref_cmp_by_commit_timestamp_descending : got_ref_cmp_by_name,
6176 repo);
6177 if (err)
6178 return err;
6180 TAILQ_FOREACH(re, &refs, entry) {
6181 char *refstr;
6182 refstr = got_ref_to_str(re->ref);
6183 if (refstr == NULL) {
6184 err = got_error_from_errno("got_ref_to_str");
6185 break;
6187 printf("%s: %s\n", got_ref_get_name(re->ref), refstr);
6188 free(refstr);
6191 got_ref_list_free(&refs);
6192 return err;
6195 static const struct got_error *
6196 delete_ref_by_name(struct got_repository *repo, const char *refname)
6198 const struct got_error *err;
6199 struct got_reference *ref;
6201 err = got_ref_open(&ref, repo, refname, 0);
6202 if (err)
6203 return err;
6205 err = delete_ref(repo, ref);
6206 got_ref_close(ref);
6207 return err;
6210 static const struct got_error *
6211 add_ref(struct got_repository *repo, const char *refname, const char *target)
6213 const struct got_error *err = NULL;
6214 struct got_object_id *id = NULL;
6215 struct got_reference *ref = NULL;
6216 struct got_reflist_head refs;
6219 * Don't let the user create a reference name with a leading '-'.
6220 * While technically a valid reference name, this case is usually
6221 * an unintended typo.
6223 if (refname[0] == '-')
6224 return got_error_path(refname, GOT_ERR_REF_NAME_MINUS);
6226 TAILQ_INIT(&refs);
6227 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
6228 if (err)
6229 goto done;
6230 err = got_repo_match_object_id(&id, NULL, target, GOT_OBJ_TYPE_ANY,
6231 &refs, repo);
6232 got_ref_list_free(&refs);
6233 if (err)
6234 goto done;
6236 err = got_ref_alloc(&ref, refname, id);
6237 if (err)
6238 goto done;
6240 err = got_ref_write(ref, repo);
6241 done:
6242 if (ref)
6243 got_ref_close(ref);
6244 free(id);
6245 return err;
6248 static const struct got_error *
6249 add_symref(struct got_repository *repo, const char *refname, const char *target)
6251 const struct got_error *err = NULL;
6252 struct got_reference *ref = NULL;
6253 struct got_reference *target_ref = NULL;
6256 * Don't let the user create a reference name with a leading '-'.
6257 * While technically a valid reference name, this case is usually
6258 * an unintended typo.
6260 if (refname[0] == '-')
6261 return got_error_path(refname, GOT_ERR_REF_NAME_MINUS);
6263 err = got_ref_open(&target_ref, repo, target, 0);
6264 if (err)
6265 return err;
6267 err = got_ref_alloc_symref(&ref, refname, target_ref);
6268 if (err)
6269 goto done;
6271 err = got_ref_write(ref, repo);
6272 done:
6273 if (target_ref)
6274 got_ref_close(target_ref);
6275 if (ref)
6276 got_ref_close(ref);
6277 return err;
6280 static const struct got_error *
6281 cmd_ref(int argc, char *argv[])
6283 const struct got_error *error = NULL;
6284 struct got_repository *repo = NULL;
6285 struct got_worktree *worktree = NULL;
6286 char *cwd = NULL, *repo_path = NULL;
6287 int ch, do_list = 0, do_delete = 0, sort_by_time = 0;
6288 const char *obj_arg = NULL, *symref_target= NULL;
6289 char *refname = NULL;
6290 int *pack_fds = NULL;
6292 while ((ch = getopt(argc, argv, "c:dlr:s:t")) != -1) {
6293 switch (ch) {
6294 case 'c':
6295 obj_arg = optarg;
6296 break;
6297 case 'd':
6298 do_delete = 1;
6299 break;
6300 case 'l':
6301 do_list = 1;
6302 break;
6303 case 'r':
6304 repo_path = realpath(optarg, NULL);
6305 if (repo_path == NULL)
6306 return got_error_from_errno2("realpath",
6307 optarg);
6308 got_path_strip_trailing_slashes(repo_path);
6309 break;
6310 case 's':
6311 symref_target = optarg;
6312 break;
6313 case 't':
6314 sort_by_time = 1;
6315 break;
6316 default:
6317 usage_ref();
6318 /* NOTREACHED */
6322 if (obj_arg && do_list)
6323 option_conflict('c', 'l');
6324 if (obj_arg && do_delete)
6325 option_conflict('c', 'd');
6326 if (obj_arg && symref_target)
6327 option_conflict('c', 's');
6328 if (symref_target && do_delete)
6329 option_conflict('s', 'd');
6330 if (symref_target && do_list)
6331 option_conflict('s', 'l');
6332 if (do_delete && do_list)
6333 option_conflict('d', 'l');
6334 if (sort_by_time && !do_list)
6335 errx(1, "-t option requires -l option");
6337 argc -= optind;
6338 argv += optind;
6340 if (do_list) {
6341 if (argc != 0 && argc != 1)
6342 usage_ref();
6343 if (argc == 1) {
6344 refname = strdup(argv[0]);
6345 if (refname == NULL) {
6346 error = got_error_from_errno("strdup");
6347 goto done;
6350 } else {
6351 if (argc != 1)
6352 usage_ref();
6353 refname = strdup(argv[0]);
6354 if (refname == NULL) {
6355 error = got_error_from_errno("strdup");
6356 goto done;
6360 if (refname)
6361 got_path_strip_trailing_slashes(refname);
6363 #ifndef PROFILE
6364 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
6365 "sendfd unveil", NULL) == -1)
6366 err(1, "pledge");
6367 #endif
6368 cwd = getcwd(NULL, 0);
6369 if (cwd == NULL) {
6370 error = got_error_from_errno("getcwd");
6371 goto done;
6374 error = got_repo_pack_fds_open(&pack_fds);
6375 if (error != NULL)
6376 goto done;
6378 if (repo_path == NULL) {
6379 error = got_worktree_open(&worktree, cwd);
6380 if (error && error->code != GOT_ERR_NOT_WORKTREE)
6381 goto done;
6382 else
6383 error = NULL;
6384 if (worktree) {
6385 repo_path =
6386 strdup(got_worktree_get_repo_path(worktree));
6387 if (repo_path == NULL)
6388 error = got_error_from_errno("strdup");
6389 if (error)
6390 goto done;
6391 } else {
6392 repo_path = strdup(cwd);
6393 if (repo_path == NULL) {
6394 error = got_error_from_errno("strdup");
6395 goto done;
6400 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
6401 if (error != NULL)
6402 goto done;
6404 #ifndef PROFILE
6405 if (do_list) {
6406 /* Remove "cpath" promise. */
6407 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
6408 NULL) == -1)
6409 err(1, "pledge");
6411 #endif
6413 error = apply_unveil(got_repo_get_path(repo), do_list,
6414 worktree ? got_worktree_get_root_path(worktree) : NULL);
6415 if (error)
6416 goto done;
6418 if (do_list)
6419 error = list_refs(repo, refname, sort_by_time);
6420 else if (do_delete)
6421 error = delete_ref_by_name(repo, refname);
6422 else if (symref_target)
6423 error = add_symref(repo, refname, symref_target);
6424 else {
6425 if (obj_arg == NULL)
6426 usage_ref();
6427 error = add_ref(repo, refname, obj_arg);
6429 done:
6430 free(refname);
6431 if (repo) {
6432 const struct got_error *close_err = got_repo_close(repo);
6433 if (error == NULL)
6434 error = close_err;
6436 if (worktree)
6437 got_worktree_close(worktree);
6438 if (pack_fds) {
6439 const struct got_error *pack_err =
6440 got_repo_pack_fds_close(pack_fds);
6441 if (error == NULL)
6442 error = pack_err;
6444 free(cwd);
6445 free(repo_path);
6446 return error;
6449 __dead static void
6450 usage_branch(void)
6452 fprintf(stderr, "usage: %s branch [-lnt] [-c commit] [-d name] "
6453 "[-r repository-path] [name]\n", getprogname());
6454 exit(1);
6457 static const struct got_error *
6458 list_branch(struct got_repository *repo, struct got_worktree *worktree,
6459 struct got_reference *ref)
6461 const struct got_error *err = NULL;
6462 const char *refname, *marker = " ";
6463 char *refstr;
6465 refname = got_ref_get_name(ref);
6466 if (worktree && strcmp(refname,
6467 got_worktree_get_head_ref_name(worktree)) == 0) {
6468 struct got_object_id *id = NULL;
6470 err = got_ref_resolve(&id, repo, ref);
6471 if (err)
6472 return err;
6473 if (got_object_id_cmp(id,
6474 got_worktree_get_base_commit_id(worktree)) == 0)
6475 marker = "* ";
6476 else
6477 marker = "~ ";
6478 free(id);
6481 if (strncmp(refname, "refs/heads/", 11) == 0)
6482 refname += 11;
6483 if (strncmp(refname, "refs/got/worktree/", 18) == 0)
6484 refname += 18;
6485 if (strncmp(refname, "refs/remotes/", 13) == 0)
6486 refname += 13;
6488 refstr = got_ref_to_str(ref);
6489 if (refstr == NULL)
6490 return got_error_from_errno("got_ref_to_str");
6492 printf("%s%s: %s\n", marker, refname, refstr);
6493 free(refstr);
6494 return NULL;
6497 static const struct got_error *
6498 show_current_branch(struct got_repository *repo, struct got_worktree *worktree)
6500 const char *refname;
6502 if (worktree == NULL)
6503 return got_error(GOT_ERR_NOT_WORKTREE);
6505 refname = got_worktree_get_head_ref_name(worktree);
6507 if (strncmp(refname, "refs/heads/", 11) == 0)
6508 refname += 11;
6509 if (strncmp(refname, "refs/got/worktree/", 18) == 0)
6510 refname += 18;
6512 printf("%s\n", refname);
6514 return NULL;
6517 static const struct got_error *
6518 list_branches(struct got_repository *repo, struct got_worktree *worktree,
6519 int sort_by_time)
6521 static const struct got_error *err = NULL;
6522 struct got_reflist_head refs;
6523 struct got_reflist_entry *re;
6524 struct got_reference *temp_ref = NULL;
6525 int rebase_in_progress, histedit_in_progress;
6527 TAILQ_INIT(&refs);
6529 if (worktree) {
6530 err = got_worktree_rebase_in_progress(&rebase_in_progress,
6531 worktree);
6532 if (err)
6533 return err;
6535 err = got_worktree_histedit_in_progress(&histedit_in_progress,
6536 worktree);
6537 if (err)
6538 return err;
6540 if (rebase_in_progress || histedit_in_progress) {
6541 err = got_ref_open(&temp_ref, repo,
6542 got_worktree_get_head_ref_name(worktree), 0);
6543 if (err)
6544 return err;
6545 list_branch(repo, worktree, temp_ref);
6546 got_ref_close(temp_ref);
6550 err = got_ref_list(&refs, repo, "refs/heads", sort_by_time ?
6551 got_ref_cmp_by_commit_timestamp_descending : got_ref_cmp_by_name,
6552 repo);
6553 if (err)
6554 return err;
6556 TAILQ_FOREACH(re, &refs, entry)
6557 list_branch(repo, worktree, re->ref);
6559 got_ref_list_free(&refs);
6561 err = got_ref_list(&refs, repo, "refs/remotes", sort_by_time ?
6562 got_ref_cmp_by_commit_timestamp_descending : got_ref_cmp_by_name,
6563 repo);
6564 if (err)
6565 return err;
6567 TAILQ_FOREACH(re, &refs, entry)
6568 list_branch(repo, worktree, re->ref);
6570 got_ref_list_free(&refs);
6572 return NULL;
6575 static const struct got_error *
6576 delete_branch(struct got_repository *repo, struct got_worktree *worktree,
6577 const char *branch_name)
6579 const struct got_error *err = NULL;
6580 struct got_reference *ref = NULL;
6581 char *refname, *remote_refname = NULL;
6583 if (strncmp(branch_name, "refs/", 5) == 0)
6584 branch_name += 5;
6585 if (strncmp(branch_name, "heads/", 6) == 0)
6586 branch_name += 6;
6587 else if (strncmp(branch_name, "remotes/", 8) == 0)
6588 branch_name += 8;
6590 if (asprintf(&refname, "refs/heads/%s", branch_name) == -1)
6591 return got_error_from_errno("asprintf");
6593 if (asprintf(&remote_refname, "refs/remotes/%s",
6594 branch_name) == -1) {
6595 err = got_error_from_errno("asprintf");
6596 goto done;
6599 err = got_ref_open(&ref, repo, refname, 0);
6600 if (err) {
6601 const struct got_error *err2;
6602 if (err->code != GOT_ERR_NOT_REF)
6603 goto done;
6605 * Keep 'err' intact such that if neither branch exists
6606 * we report "refs/heads" rather than "refs/remotes" in
6607 * our error message.
6609 err2 = got_ref_open(&ref, repo, remote_refname, 0);
6610 if (err2)
6611 goto done;
6612 err = NULL;
6615 if (worktree &&
6616 strcmp(got_worktree_get_head_ref_name(worktree),
6617 got_ref_get_name(ref)) == 0) {
6618 err = got_error_msg(GOT_ERR_SAME_BRANCH,
6619 "will not delete this work tree's current branch");
6620 goto done;
6623 err = delete_ref(repo, ref);
6624 done:
6625 if (ref)
6626 got_ref_close(ref);
6627 free(refname);
6628 free(remote_refname);
6629 return err;
6632 static const struct got_error *
6633 add_branch(struct got_repository *repo, const char *branch_name,
6634 struct got_object_id *base_commit_id)
6636 const struct got_error *err = NULL;
6637 struct got_reference *ref = NULL;
6638 char *base_refname = NULL, *refname = NULL;
6641 * Don't let the user create a branch name with a leading '-'.
6642 * While technically a valid reference name, this case is usually
6643 * an unintended typo.
6645 if (branch_name[0] == '-')
6646 return got_error_path(branch_name, GOT_ERR_REF_NAME_MINUS);
6648 if (strncmp(branch_name, "refs/heads/", 11) == 0)
6649 branch_name += 11;
6651 if (asprintf(&refname, "refs/heads/%s", branch_name) == -1) {
6652 err = got_error_from_errno("asprintf");
6653 goto done;
6656 err = got_ref_open(&ref, repo, refname, 0);
6657 if (err == NULL) {
6658 err = got_error(GOT_ERR_BRANCH_EXISTS);
6659 goto done;
6660 } else if (err->code != GOT_ERR_NOT_REF)
6661 goto done;
6663 err = got_ref_alloc(&ref, refname, base_commit_id);
6664 if (err)
6665 goto done;
6667 err = got_ref_write(ref, repo);
6668 done:
6669 if (ref)
6670 got_ref_close(ref);
6671 free(base_refname);
6672 free(refname);
6673 return err;
6676 static const struct got_error *
6677 cmd_branch(int argc, char *argv[])
6679 const struct got_error *error = NULL;
6680 struct got_repository *repo = NULL;
6681 struct got_worktree *worktree = NULL;
6682 char *cwd = NULL, *repo_path = NULL;
6683 int ch, do_list = 0, do_show = 0, do_update = 1, sort_by_time = 0;
6684 const char *delref = NULL, *commit_id_arg = NULL;
6685 struct got_reference *ref = NULL;
6686 struct got_pathlist_head paths;
6687 struct got_pathlist_entry *pe;
6688 struct got_object_id *commit_id = NULL;
6689 char *commit_id_str = NULL;
6690 int *pack_fds = NULL;
6692 TAILQ_INIT(&paths);
6694 while ((ch = getopt(argc, argv, "c:d:lnr:t")) != -1) {
6695 switch (ch) {
6696 case 'c':
6697 commit_id_arg = optarg;
6698 break;
6699 case 'd':
6700 delref = optarg;
6701 break;
6702 case 'l':
6703 do_list = 1;
6704 break;
6705 case 'n':
6706 do_update = 0;
6707 break;
6708 case 'r':
6709 repo_path = realpath(optarg, NULL);
6710 if (repo_path == NULL)
6711 return got_error_from_errno2("realpath",
6712 optarg);
6713 got_path_strip_trailing_slashes(repo_path);
6714 break;
6715 case 't':
6716 sort_by_time = 1;
6717 break;
6718 default:
6719 usage_branch();
6720 /* NOTREACHED */
6724 if (do_list && delref)
6725 option_conflict('l', 'd');
6726 if (sort_by_time && !do_list)
6727 errx(1, "-t option requires -l option");
6729 argc -= optind;
6730 argv += optind;
6732 if (!do_list && !delref && argc == 0)
6733 do_show = 1;
6735 if ((do_list || delref || do_show) && commit_id_arg != NULL)
6736 errx(1, "-c option can only be used when creating a branch");
6738 if (do_list || delref) {
6739 if (argc > 0)
6740 usage_branch();
6741 } else if (!do_show && argc != 1)
6742 usage_branch();
6744 #ifndef PROFILE
6745 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
6746 "sendfd unveil", NULL) == -1)
6747 err(1, "pledge");
6748 #endif
6749 cwd = getcwd(NULL, 0);
6750 if (cwd == NULL) {
6751 error = got_error_from_errno("getcwd");
6752 goto done;
6755 error = got_repo_pack_fds_open(&pack_fds);
6756 if (error != NULL)
6757 goto done;
6759 if (repo_path == NULL) {
6760 error = got_worktree_open(&worktree, cwd);
6761 if (error && error->code != GOT_ERR_NOT_WORKTREE)
6762 goto done;
6763 else
6764 error = NULL;
6765 if (worktree) {
6766 repo_path =
6767 strdup(got_worktree_get_repo_path(worktree));
6768 if (repo_path == NULL)
6769 error = got_error_from_errno("strdup");
6770 if (error)
6771 goto done;
6772 } else {
6773 repo_path = strdup(cwd);
6774 if (repo_path == NULL) {
6775 error = got_error_from_errno("strdup");
6776 goto done;
6781 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
6782 if (error != NULL)
6783 goto done;
6785 #ifndef PROFILE
6786 if (do_list || do_show) {
6787 /* Remove "cpath" promise. */
6788 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
6789 NULL) == -1)
6790 err(1, "pledge");
6792 #endif
6794 error = apply_unveil(got_repo_get_path(repo), do_list,
6795 worktree ? got_worktree_get_root_path(worktree) : NULL);
6796 if (error)
6797 goto done;
6799 if (do_show)
6800 error = show_current_branch(repo, worktree);
6801 else if (do_list)
6802 error = list_branches(repo, worktree, sort_by_time);
6803 else if (delref)
6804 error = delete_branch(repo, worktree, delref);
6805 else {
6806 struct got_reflist_head refs;
6807 TAILQ_INIT(&refs);
6808 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
6809 NULL);
6810 if (error)
6811 goto done;
6812 if (commit_id_arg == NULL)
6813 commit_id_arg = worktree ?
6814 got_worktree_get_head_ref_name(worktree) :
6815 GOT_REF_HEAD;
6816 error = got_repo_match_object_id(&commit_id, NULL,
6817 commit_id_arg, GOT_OBJ_TYPE_COMMIT, &refs, repo);
6818 got_ref_list_free(&refs);
6819 if (error)
6820 goto done;
6821 error = add_branch(repo, argv[0], commit_id);
6822 if (error)
6823 goto done;
6824 if (worktree && do_update) {
6825 struct got_update_progress_arg upa;
6826 char *branch_refname = NULL;
6828 error = got_object_id_str(&commit_id_str, commit_id);
6829 if (error)
6830 goto done;
6831 error = get_worktree_paths_from_argv(&paths, 0, NULL,
6832 worktree);
6833 if (error)
6834 goto done;
6835 if (asprintf(&branch_refname, "refs/heads/%s", argv[0])
6836 == -1) {
6837 error = got_error_from_errno("asprintf");
6838 goto done;
6840 error = got_ref_open(&ref, repo, branch_refname, 0);
6841 free(branch_refname);
6842 if (error)
6843 goto done;
6844 error = switch_head_ref(ref, commit_id, worktree,
6845 repo);
6846 if (error)
6847 goto done;
6848 error = got_worktree_set_base_commit_id(worktree, repo,
6849 commit_id);
6850 if (error)
6851 goto done;
6852 memset(&upa, 0, sizeof(upa));
6853 error = got_worktree_checkout_files(worktree, &paths,
6854 repo, update_progress, &upa, check_cancelled,
6855 NULL);
6856 if (error)
6857 goto done;
6858 if (upa.did_something) {
6859 printf("Updated to %s: %s\n",
6860 got_worktree_get_head_ref_name(worktree),
6861 commit_id_str);
6863 print_update_progress_stats(&upa);
6866 done:
6867 if (ref)
6868 got_ref_close(ref);
6869 if (repo) {
6870 const struct got_error *close_err = got_repo_close(repo);
6871 if (error == NULL)
6872 error = close_err;
6874 if (worktree)
6875 got_worktree_close(worktree);
6876 if (pack_fds) {
6877 const struct got_error *pack_err =
6878 got_repo_pack_fds_close(pack_fds);
6879 if (error == NULL)
6880 error = pack_err;
6882 free(cwd);
6883 free(repo_path);
6884 free(commit_id);
6885 free(commit_id_str);
6886 TAILQ_FOREACH(pe, &paths, entry)
6887 free((char *)pe->path);
6888 got_pathlist_free(&paths);
6889 return error;
6893 __dead static void
6894 usage_tag(void)
6896 fprintf(stderr, "usage: %s tag [-lVv] [-c commit] [-m message] "
6897 "[-r repository-path] [-s signer-id] name\n", getprogname());
6898 exit(1);
6901 #if 0
6902 static const struct got_error *
6903 sort_tags(struct got_reflist_head *sorted, struct got_reflist_head *tags)
6905 const struct got_error *err = NULL;
6906 struct got_reflist_entry *re, *se, *new;
6907 struct got_object_id *re_id, *se_id;
6908 struct got_tag_object *re_tag, *se_tag;
6909 time_t re_time, se_time;
6911 STAILQ_FOREACH(re, tags, entry) {
6912 se = STAILQ_FIRST(sorted);
6913 if (se == NULL) {
6914 err = got_reflist_entry_dup(&new, re);
6915 if (err)
6916 return err;
6917 STAILQ_INSERT_HEAD(sorted, new, entry);
6918 continue;
6919 } else {
6920 err = got_ref_resolve(&re_id, repo, re->ref);
6921 if (err)
6922 break;
6923 err = got_object_open_as_tag(&re_tag, repo, re_id);
6924 free(re_id);
6925 if (err)
6926 break;
6927 re_time = got_object_tag_get_tagger_time(re_tag);
6928 got_object_tag_close(re_tag);
6931 while (se) {
6932 err = got_ref_resolve(&se_id, repo, re->ref);
6933 if (err)
6934 break;
6935 err = got_object_open_as_tag(&se_tag, repo, se_id);
6936 free(se_id);
6937 if (err)
6938 break;
6939 se_time = got_object_tag_get_tagger_time(se_tag);
6940 got_object_tag_close(se_tag);
6942 if (se_time > re_time) {
6943 err = got_reflist_entry_dup(&new, re);
6944 if (err)
6945 return err;
6946 STAILQ_INSERT_AFTER(sorted, se, new, entry);
6947 break;
6949 se = STAILQ_NEXT(se, entry);
6950 continue;
6953 done:
6954 return err;
6956 #endif
6958 static const struct got_error *
6959 get_tag_refname(char **refname, const char *tag_name)
6961 const struct got_error *err;
6963 if (strncmp("refs/tags/", tag_name, 10) == 0) {
6964 *refname = strdup(tag_name);
6965 if (*refname == NULL)
6966 return got_error_from_errno("strdup");
6967 } else if (asprintf(refname, "refs/tags/%s", tag_name) == -1) {
6968 err = got_error_from_errno("asprintf");
6969 *refname = NULL;
6970 return err;
6973 return NULL;
6976 static const struct got_error *
6977 list_tags(struct got_repository *repo, const char *tag_name, int verify_tags,
6978 const char *allowed_signers, const char *revoked_signers, int verbosity)
6980 static const struct got_error *err = NULL;
6981 struct got_reflist_head refs;
6982 struct got_reflist_entry *re;
6983 char *wanted_refname = NULL;
6984 int bad_sigs = 0;
6986 TAILQ_INIT(&refs);
6988 err = got_ref_list(&refs, repo, "refs/tags", got_ref_cmp_tags, repo);
6989 if (err)
6990 return err;
6992 if (tag_name) {
6993 struct got_reference *ref;
6994 err = get_tag_refname(&wanted_refname, tag_name);
6995 if (err)
6996 goto done;
6997 /* Wanted tag reference should exist. */
6998 err = got_ref_open(&ref, repo, wanted_refname, 0);
6999 if (err)
7000 goto done;
7001 got_ref_close(ref);
7004 TAILQ_FOREACH(re, &refs, entry) {
7005 const char *refname;
7006 char *refstr, *tagmsg0, *tagmsg, *line, *id_str, *datestr;
7007 char datebuf[26];
7008 const char *tagger, *ssh_sig = NULL;
7009 char *sig_msg = NULL;
7010 time_t tagger_time;
7011 struct got_object_id *id;
7012 struct got_tag_object *tag;
7013 struct got_commit_object *commit = NULL;
7015 refname = got_ref_get_name(re->ref);
7016 if (strncmp(refname, "refs/tags/", 10) != 0 ||
7017 (wanted_refname && strcmp(refname, wanted_refname) != 0))
7018 continue;
7019 refname += 10;
7020 refstr = got_ref_to_str(re->ref);
7021 if (refstr == NULL) {
7022 err = got_error_from_errno("got_ref_to_str");
7023 break;
7026 err = got_ref_resolve(&id, repo, re->ref);
7027 if (err)
7028 break;
7029 err = got_object_open_as_tag(&tag, repo, id);
7030 if (err) {
7031 if (err->code != GOT_ERR_OBJ_TYPE) {
7032 free(id);
7033 break;
7035 /* "lightweight" tag */
7036 err = got_object_open_as_commit(&commit, repo, id);
7037 if (err) {
7038 free(id);
7039 break;
7041 tagger = got_object_commit_get_committer(commit);
7042 tagger_time =
7043 got_object_commit_get_committer_time(commit);
7044 err = got_object_id_str(&id_str, id);
7045 free(id);
7046 if (err)
7047 break;
7048 } else {
7049 free(id);
7050 tagger = got_object_tag_get_tagger(tag);
7051 tagger_time = got_object_tag_get_tagger_time(tag);
7052 err = got_object_id_str(&id_str,
7053 got_object_tag_get_object_id(tag));
7054 if (err)
7055 break;
7058 if (tag && verify_tags) {
7059 ssh_sig = got_sigs_get_tagmsg_ssh_signature(
7060 got_object_tag_get_message(tag));
7061 if (ssh_sig && allowed_signers == NULL) {
7062 err = got_error_msg(
7063 GOT_ERR_VERIFY_TAG_SIGNATURE,
7064 "SSH signature verification requires "
7065 "setting allowed_signers in "
7066 "got.conf(5)");
7067 break;
7071 printf("%stag %s %s\n", GOT_COMMIT_SEP_STR, refname, refstr);
7072 free(refstr);
7073 printf("from: %s\n", tagger);
7074 datestr = get_datestr(&tagger_time, datebuf);
7075 if (datestr)
7076 printf("date: %s UTC\n", datestr);
7077 if (commit)
7078 printf("object: %s %s\n", GOT_OBJ_LABEL_COMMIT, id_str);
7079 else {
7080 switch (got_object_tag_get_object_type(tag)) {
7081 case GOT_OBJ_TYPE_BLOB:
7082 printf("object: %s %s\n", GOT_OBJ_LABEL_BLOB,
7083 id_str);
7084 break;
7085 case GOT_OBJ_TYPE_TREE:
7086 printf("object: %s %s\n", GOT_OBJ_LABEL_TREE,
7087 id_str);
7088 break;
7089 case GOT_OBJ_TYPE_COMMIT:
7090 printf("object: %s %s\n", GOT_OBJ_LABEL_COMMIT,
7091 id_str);
7092 break;
7093 case GOT_OBJ_TYPE_TAG:
7094 printf("object: %s %s\n", GOT_OBJ_LABEL_TAG,
7095 id_str);
7096 break;
7097 default:
7098 break;
7101 free(id_str);
7103 if (ssh_sig) {
7104 err = got_sigs_verify_tag_ssh(&sig_msg, tag, ssh_sig,
7105 allowed_signers, revoked_signers, verbosity);
7106 if (err && err->code == GOT_ERR_BAD_TAG_SIGNATURE)
7107 bad_sigs = 1;
7108 else if (err)
7109 break;
7110 printf("signature: %s", sig_msg);
7111 free(sig_msg);
7112 sig_msg = NULL;
7115 if (commit) {
7116 err = got_object_commit_get_logmsg(&tagmsg0, commit);
7117 if (err)
7118 break;
7119 got_object_commit_close(commit);
7120 } else {
7121 tagmsg0 = strdup(got_object_tag_get_message(tag));
7122 got_object_tag_close(tag);
7123 if (tagmsg0 == NULL) {
7124 err = got_error_from_errno("strdup");
7125 break;
7129 tagmsg = tagmsg0;
7130 do {
7131 line = strsep(&tagmsg, "\n");
7132 if (line)
7133 printf(" %s\n", line);
7134 } while (line);
7135 free(tagmsg0);
7137 done:
7138 got_ref_list_free(&refs);
7139 free(wanted_refname);
7141 if (err == NULL && bad_sigs)
7142 err = got_error(GOT_ERR_BAD_TAG_SIGNATURE);
7143 return err;
7146 static const struct got_error *
7147 get_tag_message(char **tagmsg, char **tagmsg_path, const char *commit_id_str,
7148 const char *tag_name, const char *repo_path)
7150 const struct got_error *err = NULL;
7151 char *template = NULL, *initial_content = NULL;
7152 char *editor = NULL;
7153 int initial_content_len;
7154 int fd = -1;
7156 if (asprintf(&template, GOT_TMPDIR_STR "/got-tagmsg") == -1) {
7157 err = got_error_from_errno("asprintf");
7158 goto done;
7161 initial_content_len = asprintf(&initial_content,
7162 "\n# tagging commit %s as %s\n",
7163 commit_id_str, tag_name);
7164 if (initial_content_len == -1) {
7165 err = got_error_from_errno("asprintf");
7166 goto done;
7169 err = got_opentemp_named_fd(tagmsg_path, &fd, template, "");
7170 if (err)
7171 goto done;
7173 if (write(fd, initial_content, initial_content_len) == -1) {
7174 err = got_error_from_errno2("write", *tagmsg_path);
7175 goto done;
7178 err = get_editor(&editor);
7179 if (err)
7180 goto done;
7181 err = edit_logmsg(tagmsg, editor, *tagmsg_path, initial_content,
7182 initial_content_len, 1);
7183 done:
7184 free(initial_content);
7185 free(template);
7186 free(editor);
7188 if (fd != -1 && close(fd) == -1 && err == NULL)
7189 err = got_error_from_errno2("close", *tagmsg_path);
7191 if (err) {
7192 free(*tagmsg);
7193 *tagmsg = NULL;
7195 return err;
7198 static const struct got_error *
7199 add_tag(struct got_repository *repo, const char *tagger,
7200 const char *tag_name, const char *commit_arg, const char *tagmsg_arg,
7201 const char *signer_id, int verbosity)
7203 const struct got_error *err = NULL;
7204 struct got_object_id *commit_id = NULL, *tag_id = NULL;
7205 char *label = NULL, *commit_id_str = NULL;
7206 struct got_reference *ref = NULL;
7207 char *refname = NULL, *tagmsg = NULL;
7208 char *tagmsg_path = NULL, *tag_id_str = NULL;
7209 int preserve_tagmsg = 0;
7210 struct got_reflist_head refs;
7212 TAILQ_INIT(&refs);
7215 * Don't let the user create a tag name with a leading '-'.
7216 * While technically a valid reference name, this case is usually
7217 * an unintended typo.
7219 if (tag_name[0] == '-')
7220 return got_error_path(tag_name, GOT_ERR_REF_NAME_MINUS);
7222 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
7223 if (err)
7224 goto done;
7226 err = got_repo_match_object_id(&commit_id, &label, commit_arg,
7227 GOT_OBJ_TYPE_COMMIT, &refs, repo);
7228 if (err)
7229 goto done;
7231 err = got_object_id_str(&commit_id_str, commit_id);
7232 if (err)
7233 goto done;
7235 err = get_tag_refname(&refname, tag_name);
7236 if (err)
7237 goto done;
7238 if (strncmp("refs/tags/", tag_name, 10) == 0)
7239 tag_name += 10;
7241 err = got_ref_open(&ref, repo, refname, 0);
7242 if (err == NULL) {
7243 err = got_error(GOT_ERR_TAG_EXISTS);
7244 goto done;
7245 } else if (err->code != GOT_ERR_NOT_REF)
7246 goto done;
7248 if (tagmsg_arg == NULL) {
7249 err = get_tag_message(&tagmsg, &tagmsg_path, commit_id_str,
7250 tag_name, got_repo_get_path(repo));
7251 if (err) {
7252 if (err->code != GOT_ERR_COMMIT_MSG_EMPTY &&
7253 tagmsg_path != NULL)
7254 preserve_tagmsg = 1;
7255 goto done;
7257 /* Editor is done; we can now apply unveil(2) */
7258 err = got_sigs_apply_unveil();
7259 if (err)
7260 goto done;
7261 err = apply_unveil(got_repo_get_path(repo), 0, NULL);
7262 if (err)
7263 goto done;
7266 err = got_object_tag_create(&tag_id, tag_name, commit_id,
7267 tagger, time(NULL), tagmsg ? tagmsg : tagmsg_arg, signer_id, repo,
7268 verbosity);
7269 if (err) {
7270 if (tagmsg_path)
7271 preserve_tagmsg = 1;
7272 goto done;
7275 err = got_ref_alloc(&ref, refname, tag_id);
7276 if (err) {
7277 if (tagmsg_path)
7278 preserve_tagmsg = 1;
7279 goto done;
7282 err = got_ref_write(ref, repo);
7283 if (err) {
7284 if (tagmsg_path)
7285 preserve_tagmsg = 1;
7286 goto done;
7289 err = got_object_id_str(&tag_id_str, tag_id);
7290 if (err) {
7291 if (tagmsg_path)
7292 preserve_tagmsg = 1;
7293 goto done;
7295 printf("Created tag %s\n", tag_id_str);
7296 done:
7297 if (preserve_tagmsg) {
7298 fprintf(stderr, "%s: tag message preserved in %s\n",
7299 getprogname(), tagmsg_path);
7300 } else if (tagmsg_path && unlink(tagmsg_path) == -1 && err == NULL)
7301 err = got_error_from_errno2("unlink", tagmsg_path);
7302 free(tag_id_str);
7303 if (ref)
7304 got_ref_close(ref);
7305 free(commit_id);
7306 free(commit_id_str);
7307 free(refname);
7308 free(tagmsg);
7309 free(tagmsg_path);
7310 got_ref_list_free(&refs);
7311 return err;
7314 static const struct got_error *
7315 cmd_tag(int argc, char *argv[])
7317 const struct got_error *error = NULL;
7318 struct got_repository *repo = NULL;
7319 struct got_worktree *worktree = NULL;
7320 char *cwd = NULL, *repo_path = NULL, *commit_id_str = NULL;
7321 char *gitconfig_path = NULL, *tagger = NULL;
7322 char *allowed_signers = NULL, *revoked_signers = NULL;
7323 char *signer_id = NULL;
7324 const char *tag_name = NULL, *commit_id_arg = NULL, *tagmsg = NULL;
7325 int ch, do_list = 0, verify_tags = 0, verbosity = 0;
7326 int *pack_fds = NULL;
7328 while ((ch = getopt(argc, argv, "c:lm:r:s:Vv")) != -1) {
7329 switch (ch) {
7330 case 'c':
7331 commit_id_arg = optarg;
7332 break;
7333 case 'l':
7334 do_list = 1;
7335 break;
7336 case 'm':
7337 tagmsg = optarg;
7338 break;
7339 case 'r':
7340 repo_path = realpath(optarg, NULL);
7341 if (repo_path == NULL) {
7342 error = got_error_from_errno2("realpath",
7343 optarg);
7344 goto done;
7346 got_path_strip_trailing_slashes(repo_path);
7347 break;
7348 case 's':
7349 signer_id = strdup(optarg);
7350 if (signer_id == NULL) {
7351 error = got_error_from_errno("strdup");
7352 goto done;
7354 break;
7355 case 'V':
7356 verify_tags = 1;
7357 break;
7358 case 'v':
7359 if (verbosity < 0)
7360 verbosity = 0;
7361 else if (verbosity < 3)
7362 verbosity++;
7363 break;
7364 default:
7365 usage_tag();
7366 /* NOTREACHED */
7370 argc -= optind;
7371 argv += optind;
7373 if (do_list || verify_tags) {
7374 if (commit_id_arg != NULL)
7375 errx(1,
7376 "-c option can only be used when creating a tag");
7377 if (tagmsg) {
7378 if (do_list)
7379 option_conflict('l', 'm');
7380 else
7381 option_conflict('V', 'm');
7383 if (signer_id) {
7384 if (do_list)
7385 option_conflict('l', 's');
7386 else
7387 option_conflict('V', 's');
7389 if (argc > 1)
7390 usage_tag();
7391 } else if (argc != 1)
7392 usage_tag();
7394 if (argc == 1)
7395 tag_name = argv[0];
7397 #ifndef PROFILE
7398 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
7399 "sendfd unveil", NULL) == -1)
7400 err(1, "pledge");
7401 #endif
7402 cwd = getcwd(NULL, 0);
7403 if (cwd == NULL) {
7404 error = got_error_from_errno("getcwd");
7405 goto done;
7408 error = got_repo_pack_fds_open(&pack_fds);
7409 if (error != NULL)
7410 goto done;
7412 if (repo_path == NULL) {
7413 error = got_worktree_open(&worktree, cwd);
7414 if (error && error->code != GOT_ERR_NOT_WORKTREE)
7415 goto done;
7416 else
7417 error = NULL;
7418 if (worktree) {
7419 repo_path =
7420 strdup(got_worktree_get_repo_path(worktree));
7421 if (repo_path == NULL)
7422 error = got_error_from_errno("strdup");
7423 if (error)
7424 goto done;
7425 } else {
7426 repo_path = strdup(cwd);
7427 if (repo_path == NULL) {
7428 error = got_error_from_errno("strdup");
7429 goto done;
7434 if (do_list || verify_tags) {
7435 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
7436 if (error != NULL)
7437 goto done;
7438 error = get_allowed_signers(&allowed_signers, repo, worktree);
7439 if (error)
7440 goto done;
7441 error = get_revoked_signers(&revoked_signers, repo, worktree);
7442 if (error)
7443 goto done;
7444 if (worktree) {
7445 /* Release work tree lock. */
7446 got_worktree_close(worktree);
7447 worktree = NULL;
7451 * Remove "cpath" promise unless needed for signature tmpfile
7452 * creation.
7454 if (verify_tags)
7455 got_sigs_apply_unveil();
7456 else {
7457 #ifndef PROFILE
7458 if (pledge("stdio rpath wpath flock proc exec sendfd "
7459 "unveil", NULL) == -1)
7460 err(1, "pledge");
7461 #endif
7463 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
7464 if (error)
7465 goto done;
7466 error = list_tags(repo, tag_name, verify_tags, allowed_signers,
7467 revoked_signers, verbosity);
7468 } else {
7469 error = get_gitconfig_path(&gitconfig_path);
7470 if (error)
7471 goto done;
7472 error = got_repo_open(&repo, repo_path, gitconfig_path,
7473 pack_fds);
7474 if (error != NULL)
7475 goto done;
7477 error = get_author(&tagger, repo, worktree);
7478 if (error)
7479 goto done;
7480 if (signer_id == NULL) {
7481 error = get_signer_id(&signer_id, repo, worktree);
7482 if (error)
7483 goto done;
7486 if (tagmsg) {
7487 if (signer_id) {
7488 error = got_sigs_apply_unveil();
7489 if (error)
7490 goto done;
7492 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
7493 if (error)
7494 goto done;
7497 if (commit_id_arg == NULL) {
7498 struct got_reference *head_ref;
7499 struct got_object_id *commit_id;
7500 error = got_ref_open(&head_ref, repo,
7501 worktree ? got_worktree_get_head_ref_name(worktree)
7502 : GOT_REF_HEAD, 0);
7503 if (error)
7504 goto done;
7505 error = got_ref_resolve(&commit_id, repo, head_ref);
7506 got_ref_close(head_ref);
7507 if (error)
7508 goto done;
7509 error = got_object_id_str(&commit_id_str, commit_id);
7510 free(commit_id);
7511 if (error)
7512 goto done;
7515 if (worktree) {
7516 /* Release work tree lock. */
7517 got_worktree_close(worktree);
7518 worktree = NULL;
7521 error = add_tag(repo, tagger, tag_name,
7522 commit_id_str ? commit_id_str : commit_id_arg, tagmsg,
7523 signer_id, verbosity);
7525 done:
7526 if (repo) {
7527 const struct got_error *close_err = got_repo_close(repo);
7528 if (error == NULL)
7529 error = close_err;
7531 if (worktree)
7532 got_worktree_close(worktree);
7533 if (pack_fds) {
7534 const struct got_error *pack_err =
7535 got_repo_pack_fds_close(pack_fds);
7536 if (error == NULL)
7537 error = pack_err;
7539 free(cwd);
7540 free(repo_path);
7541 free(gitconfig_path);
7542 free(commit_id_str);
7543 free(tagger);
7544 free(allowed_signers);
7545 free(revoked_signers);
7546 free(signer_id);
7547 return error;
7550 __dead static void
7551 usage_add(void)
7553 fprintf(stderr, "usage: %s add [-IR] path ...\n", getprogname());
7554 exit(1);
7557 static const struct got_error *
7558 add_progress(void *arg, unsigned char status, const char *path)
7560 while (path[0] == '/')
7561 path++;
7562 printf("%c %s\n", status, path);
7563 return NULL;
7566 static const struct got_error *
7567 cmd_add(int argc, char *argv[])
7569 const struct got_error *error = NULL;
7570 struct got_repository *repo = NULL;
7571 struct got_worktree *worktree = NULL;
7572 char *cwd = NULL;
7573 struct got_pathlist_head paths;
7574 struct got_pathlist_entry *pe;
7575 int ch, can_recurse = 0, no_ignores = 0;
7576 int *pack_fds = NULL;
7578 TAILQ_INIT(&paths);
7580 while ((ch = getopt(argc, argv, "IR")) != -1) {
7581 switch (ch) {
7582 case 'I':
7583 no_ignores = 1;
7584 break;
7585 case 'R':
7586 can_recurse = 1;
7587 break;
7588 default:
7589 usage_add();
7590 /* NOTREACHED */
7594 argc -= optind;
7595 argv += optind;
7597 #ifndef PROFILE
7598 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
7599 NULL) == -1)
7600 err(1, "pledge");
7601 #endif
7602 if (argc < 1)
7603 usage_add();
7605 cwd = getcwd(NULL, 0);
7606 if (cwd == NULL) {
7607 error = got_error_from_errno("getcwd");
7608 goto done;
7611 error = got_repo_pack_fds_open(&pack_fds);
7612 if (error != NULL)
7613 goto done;
7615 error = got_worktree_open(&worktree, cwd);
7616 if (error) {
7617 if (error->code == GOT_ERR_NOT_WORKTREE)
7618 error = wrap_not_worktree_error(error, "add", cwd);
7619 goto done;
7622 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
7623 NULL, pack_fds);
7624 if (error != NULL)
7625 goto done;
7627 error = apply_unveil(got_repo_get_path(repo), 1,
7628 got_worktree_get_root_path(worktree));
7629 if (error)
7630 goto done;
7632 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
7633 if (error)
7634 goto done;
7636 if (!can_recurse) {
7637 char *ondisk_path;
7638 struct stat sb;
7639 TAILQ_FOREACH(pe, &paths, entry) {
7640 if (asprintf(&ondisk_path, "%s/%s",
7641 got_worktree_get_root_path(worktree),
7642 pe->path) == -1) {
7643 error = got_error_from_errno("asprintf");
7644 goto done;
7646 if (lstat(ondisk_path, &sb) == -1) {
7647 if (errno == ENOENT) {
7648 free(ondisk_path);
7649 continue;
7651 error = got_error_from_errno2("lstat",
7652 ondisk_path);
7653 free(ondisk_path);
7654 goto done;
7656 free(ondisk_path);
7657 if (S_ISDIR(sb.st_mode)) {
7658 error = got_error_msg(GOT_ERR_BAD_PATH,
7659 "adding directories requires -R option");
7660 goto done;
7665 error = got_worktree_schedule_add(worktree, &paths, add_progress,
7666 NULL, repo, no_ignores);
7667 done:
7668 if (repo) {
7669 const struct got_error *close_err = got_repo_close(repo);
7670 if (error == NULL)
7671 error = close_err;
7673 if (worktree)
7674 got_worktree_close(worktree);
7675 if (pack_fds) {
7676 const struct got_error *pack_err =
7677 got_repo_pack_fds_close(pack_fds);
7678 if (error == NULL)
7679 error = pack_err;
7681 TAILQ_FOREACH(pe, &paths, entry)
7682 free((char *)pe->path);
7683 got_pathlist_free(&paths);
7684 free(cwd);
7685 return error;
7688 __dead static void
7689 usage_remove(void)
7691 fprintf(stderr, "usage: %s remove [-fkR] [-s status-codes] path ...\n",
7692 getprogname());
7693 exit(1);
7696 static const struct got_error *
7697 print_remove_status(void *arg, unsigned char status,
7698 unsigned char staged_status, const char *path)
7700 while (path[0] == '/')
7701 path++;
7702 if (status == GOT_STATUS_NONEXISTENT)
7703 return NULL;
7704 if (status == staged_status && (status == GOT_STATUS_DELETE))
7705 status = GOT_STATUS_NO_CHANGE;
7706 printf("%c%c %s\n", status, staged_status, path);
7707 return NULL;
7710 static const struct got_error *
7711 cmd_remove(int argc, char *argv[])
7713 const struct got_error *error = NULL;
7714 struct got_worktree *worktree = NULL;
7715 struct got_repository *repo = NULL;
7716 const char *status_codes = NULL;
7717 char *cwd = NULL;
7718 struct got_pathlist_head paths;
7719 struct got_pathlist_entry *pe;
7720 int ch, delete_local_mods = 0, can_recurse = 0, keep_on_disk = 0, i;
7721 int ignore_missing_paths = 0;
7722 int *pack_fds = NULL;
7724 TAILQ_INIT(&paths);
7726 while ((ch = getopt(argc, argv, "fkRs:")) != -1) {
7727 switch (ch) {
7728 case 'f':
7729 delete_local_mods = 1;
7730 ignore_missing_paths = 1;
7731 break;
7732 case 'k':
7733 keep_on_disk = 1;
7734 break;
7735 case 'R':
7736 can_recurse = 1;
7737 break;
7738 case 's':
7739 for (i = 0; i < strlen(optarg); i++) {
7740 switch (optarg[i]) {
7741 case GOT_STATUS_MODIFY:
7742 delete_local_mods = 1;
7743 break;
7744 case GOT_STATUS_MISSING:
7745 ignore_missing_paths = 1;
7746 break;
7747 default:
7748 errx(1, "invalid status code '%c'",
7749 optarg[i]);
7752 status_codes = optarg;
7753 break;
7754 default:
7755 usage_remove();
7756 /* NOTREACHED */
7760 argc -= optind;
7761 argv += optind;
7763 #ifndef PROFILE
7764 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
7765 NULL) == -1)
7766 err(1, "pledge");
7767 #endif
7768 if (argc < 1)
7769 usage_remove();
7771 cwd = getcwd(NULL, 0);
7772 if (cwd == NULL) {
7773 error = got_error_from_errno("getcwd");
7774 goto done;
7777 error = got_repo_pack_fds_open(&pack_fds);
7778 if (error != NULL)
7779 goto done;
7781 error = got_worktree_open(&worktree, cwd);
7782 if (error) {
7783 if (error->code == GOT_ERR_NOT_WORKTREE)
7784 error = wrap_not_worktree_error(error, "remove", cwd);
7785 goto done;
7788 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
7789 NULL, pack_fds);
7790 if (error)
7791 goto done;
7793 error = apply_unveil(got_repo_get_path(repo), 1,
7794 got_worktree_get_root_path(worktree));
7795 if (error)
7796 goto done;
7798 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
7799 if (error)
7800 goto done;
7802 if (!can_recurse) {
7803 char *ondisk_path;
7804 struct stat sb;
7805 TAILQ_FOREACH(pe, &paths, entry) {
7806 if (asprintf(&ondisk_path, "%s/%s",
7807 got_worktree_get_root_path(worktree),
7808 pe->path) == -1) {
7809 error = got_error_from_errno("asprintf");
7810 goto done;
7812 if (lstat(ondisk_path, &sb) == -1) {
7813 if (errno == ENOENT) {
7814 free(ondisk_path);
7815 continue;
7817 error = got_error_from_errno2("lstat",
7818 ondisk_path);
7819 free(ondisk_path);
7820 goto done;
7822 free(ondisk_path);
7823 if (S_ISDIR(sb.st_mode)) {
7824 error = got_error_msg(GOT_ERR_BAD_PATH,
7825 "removing directories requires -R option");
7826 goto done;
7831 error = got_worktree_schedule_delete(worktree, &paths,
7832 delete_local_mods, status_codes, print_remove_status, NULL,
7833 repo, keep_on_disk, ignore_missing_paths);
7834 done:
7835 if (repo) {
7836 const struct got_error *close_err = got_repo_close(repo);
7837 if (error == NULL)
7838 error = close_err;
7840 if (worktree)
7841 got_worktree_close(worktree);
7842 if (pack_fds) {
7843 const struct got_error *pack_err =
7844 got_repo_pack_fds_close(pack_fds);
7845 if (error == NULL)
7846 error = pack_err;
7848 TAILQ_FOREACH(pe, &paths, entry)
7849 free((char *)pe->path);
7850 got_pathlist_free(&paths);
7851 free(cwd);
7852 return error;
7855 __dead static void
7856 usage_patch(void)
7858 fprintf(stderr, "usage: %s patch [-nR] [-c commit] [-p strip-count] "
7859 "[patchfile]\n", getprogname());
7860 exit(1);
7863 static const struct got_error *
7864 patch_from_stdin(int *patchfd)
7866 const struct got_error *err = NULL;
7867 ssize_t r;
7868 char buf[BUFSIZ];
7869 sig_t sighup, sigint, sigquit;
7871 *patchfd = got_opentempfd();
7872 if (*patchfd == -1)
7873 return got_error_from_errno("got_opentempfd");
7875 sighup = signal(SIGHUP, SIG_DFL);
7876 sigint = signal(SIGINT, SIG_DFL);
7877 sigquit = signal(SIGQUIT, SIG_DFL);
7879 for (;;) {
7880 r = read(0, buf, sizeof(buf));
7881 if (r == -1) {
7882 err = got_error_from_errno("read");
7883 break;
7885 if (r == 0)
7886 break;
7887 if (write(*patchfd, buf, r) == -1) {
7888 err = got_error_from_errno("write");
7889 break;
7893 signal(SIGHUP, sighup);
7894 signal(SIGINT, sigint);
7895 signal(SIGQUIT, sigquit);
7897 if (err == NULL && lseek(*patchfd, 0, SEEK_SET) == -1)
7898 err = got_error_from_errno("lseek");
7900 if (err != NULL) {
7901 close(*patchfd);
7902 *patchfd = -1;
7905 return err;
7908 static const struct got_error *
7909 patch_progress(void *arg, const char *old, const char *new,
7910 unsigned char status, const struct got_error *error, int old_from,
7911 int old_lines, int new_from, int new_lines, int offset,
7912 int ws_mangled, const struct got_error *hunk_err)
7914 const char *path = new == NULL ? old : new;
7916 while (*path == '/')
7917 path++;
7919 if (status != 0)
7920 printf("%c %s\n", status, path);
7922 if (error != NULL)
7923 fprintf(stderr, "%s: %s\n", getprogname(), error->msg);
7925 if (offset != 0 || hunk_err != NULL || ws_mangled) {
7926 printf("@@ -%d,%d +%d,%d @@ ", old_from,
7927 old_lines, new_from, new_lines);
7928 if (hunk_err != NULL)
7929 printf("%s\n", hunk_err->msg);
7930 else if (offset != 0)
7931 printf("applied with offset %d\n", offset);
7932 else
7933 printf("hunk contains mangled whitespace\n");
7936 return NULL;
7939 static const struct got_error *
7940 cmd_patch(int argc, char *argv[])
7942 const struct got_error *error = NULL, *close_error = NULL;
7943 struct got_worktree *worktree = NULL;
7944 struct got_repository *repo = NULL;
7945 struct got_reflist_head refs;
7946 struct got_object_id *commit_id = NULL;
7947 const char *commit_id_str = NULL;
7948 struct stat sb;
7949 const char *errstr;
7950 char *cwd = NULL;
7951 int ch, nop = 0, strip = -1, reverse = 0;
7952 int patchfd;
7953 int *pack_fds = NULL;
7955 TAILQ_INIT(&refs);
7957 #ifndef PROFILE
7958 if (pledge("stdio rpath wpath cpath fattr proc exec sendfd flock "
7959 "unveil", NULL) == -1)
7960 err(1, "pledge");
7961 #endif
7963 while ((ch = getopt(argc, argv, "c:np:R")) != -1) {
7964 switch (ch) {
7965 case 'c':
7966 commit_id_str = optarg;
7967 break;
7968 case 'n':
7969 nop = 1;
7970 break;
7971 case 'p':
7972 strip = strtonum(optarg, 0, INT_MAX, &errstr);
7973 if (errstr != NULL)
7974 errx(1, "pathname strip count is %s: %s",
7975 errstr, optarg);
7976 break;
7977 case 'R':
7978 reverse = 1;
7979 break;
7980 default:
7981 usage_patch();
7982 /* NOTREACHED */
7986 argc -= optind;
7987 argv += optind;
7989 if (argc == 0) {
7990 error = patch_from_stdin(&patchfd);
7991 if (error)
7992 return error;
7993 } else if (argc == 1) {
7994 patchfd = open(argv[0], O_RDONLY);
7995 if (patchfd == -1) {
7996 error = got_error_from_errno2("open", argv[0]);
7997 return error;
7999 if (fstat(patchfd, &sb) == -1) {
8000 error = got_error_from_errno2("fstat", argv[0]);
8001 goto done;
8003 if (!S_ISREG(sb.st_mode)) {
8004 error = got_error_path(argv[0], GOT_ERR_BAD_FILETYPE);
8005 goto done;
8007 } else
8008 usage_patch();
8010 if ((cwd = getcwd(NULL, 0)) == NULL) {
8011 error = got_error_from_errno("getcwd");
8012 goto done;
8015 error = got_repo_pack_fds_open(&pack_fds);
8016 if (error != NULL)
8017 goto done;
8019 error = got_worktree_open(&worktree, cwd);
8020 if (error != NULL)
8021 goto done;
8023 const char *repo_path = got_worktree_get_repo_path(worktree);
8024 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
8025 if (error != NULL)
8026 goto done;
8028 error = apply_unveil(got_repo_get_path(repo), 0,
8029 got_worktree_get_root_path(worktree));
8030 if (error != NULL)
8031 goto done;
8033 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
8034 if (error)
8035 goto done;
8037 if (commit_id_str != NULL) {
8038 error = got_repo_match_object_id(&commit_id, NULL,
8039 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
8040 if (error)
8041 goto done;
8044 error = got_patch(patchfd, worktree, repo, nop, strip, reverse,
8045 commit_id, &patch_progress, NULL, check_cancelled, NULL);
8047 done:
8048 got_ref_list_free(&refs);
8049 free(commit_id);
8050 if (repo) {
8051 close_error = got_repo_close(repo);
8052 if (error == NULL)
8053 error = close_error;
8055 if (worktree != NULL) {
8056 close_error = got_worktree_close(worktree);
8057 if (error == NULL)
8058 error = close_error;
8060 if (pack_fds) {
8061 const struct got_error *pack_err =
8062 got_repo_pack_fds_close(pack_fds);
8063 if (error == NULL)
8064 error = pack_err;
8066 free(cwd);
8067 return error;
8070 __dead static void
8071 usage_revert(void)
8073 fprintf(stderr, "usage: %s revert [-pR] [-F response-script] path ...\n",
8074 getprogname());
8075 exit(1);
8078 static const struct got_error *
8079 revert_progress(void *arg, unsigned char status, const char *path)
8081 if (status == GOT_STATUS_UNVERSIONED)
8082 return NULL;
8084 while (path[0] == '/')
8085 path++;
8086 printf("%c %s\n", status, path);
8087 return NULL;
8090 struct choose_patch_arg {
8091 FILE *patch_script_file;
8092 const char *action;
8095 static const struct got_error *
8096 show_change(unsigned char status, const char *path, FILE *patch_file, int n,
8097 int nchanges, const char *action)
8099 const struct got_error *err;
8100 char *line = NULL;
8101 size_t linesize = 0;
8102 ssize_t linelen;
8104 switch (status) {
8105 case GOT_STATUS_ADD:
8106 printf("A %s\n%s this addition? [y/n] ", path, action);
8107 break;
8108 case GOT_STATUS_DELETE:
8109 printf("D %s\n%s this deletion? [y/n] ", path, action);
8110 break;
8111 case GOT_STATUS_MODIFY:
8112 if (fseek(patch_file, 0L, SEEK_SET) == -1)
8113 return got_error_from_errno("fseek");
8114 printf(GOT_COMMIT_SEP_STR);
8115 while ((linelen = getline(&line, &linesize, patch_file)) != -1)
8116 printf("%s", line);
8117 if (linelen == -1 && ferror(patch_file)) {
8118 err = got_error_from_errno("getline");
8119 free(line);
8120 return err;
8122 free(line);
8123 printf(GOT_COMMIT_SEP_STR);
8124 printf("M %s (change %d of %d)\n%s this change? [y/n/q] ",
8125 path, n, nchanges, action);
8126 break;
8127 default:
8128 return got_error_path(path, GOT_ERR_FILE_STATUS);
8131 fflush(stdout);
8132 return NULL;
8135 static const struct got_error *
8136 choose_patch(int *choice, void *arg, unsigned char status, const char *path,
8137 FILE *patch_file, int n, int nchanges)
8139 const struct got_error *err = NULL;
8140 char *line = NULL;
8141 size_t linesize = 0;
8142 ssize_t linelen;
8143 int resp = ' ';
8144 struct choose_patch_arg *a = arg;
8146 *choice = GOT_PATCH_CHOICE_NONE;
8148 if (a->patch_script_file) {
8149 char *nl;
8150 err = show_change(status, path, patch_file, n, nchanges,
8151 a->action);
8152 if (err)
8153 return err;
8154 linelen = getline(&line, &linesize, a->patch_script_file);
8155 if (linelen == -1) {
8156 if (ferror(a->patch_script_file))
8157 return got_error_from_errno("getline");
8158 return NULL;
8160 nl = strchr(line, '\n');
8161 if (nl)
8162 *nl = '\0';
8163 if (strcmp(line, "y") == 0) {
8164 *choice = GOT_PATCH_CHOICE_YES;
8165 printf("y\n");
8166 } else if (strcmp(line, "n") == 0) {
8167 *choice = GOT_PATCH_CHOICE_NO;
8168 printf("n\n");
8169 } else if (strcmp(line, "q") == 0 &&
8170 status == GOT_STATUS_MODIFY) {
8171 *choice = GOT_PATCH_CHOICE_QUIT;
8172 printf("q\n");
8173 } else
8174 printf("invalid response '%s'\n", line);
8175 free(line);
8176 return NULL;
8179 while (resp != 'y' && resp != 'n' && resp != 'q') {
8180 err = show_change(status, path, patch_file, n, nchanges,
8181 a->action);
8182 if (err)
8183 return err;
8184 resp = getchar();
8185 if (resp == '\n')
8186 resp = getchar();
8187 if (status == GOT_STATUS_MODIFY) {
8188 if (resp != 'y' && resp != 'n' && resp != 'q') {
8189 printf("invalid response '%c'\n", resp);
8190 resp = ' ';
8192 } else if (resp != 'y' && resp != 'n') {
8193 printf("invalid response '%c'\n", resp);
8194 resp = ' ';
8198 if (resp == 'y')
8199 *choice = GOT_PATCH_CHOICE_YES;
8200 else if (resp == 'n')
8201 *choice = GOT_PATCH_CHOICE_NO;
8202 else if (resp == 'q' && status == GOT_STATUS_MODIFY)
8203 *choice = GOT_PATCH_CHOICE_QUIT;
8205 return NULL;
8208 static const struct got_error *
8209 cmd_revert(int argc, char *argv[])
8211 const struct got_error *error = NULL;
8212 struct got_worktree *worktree = NULL;
8213 struct got_repository *repo = NULL;
8214 char *cwd = NULL, *path = NULL;
8215 struct got_pathlist_head paths;
8216 struct got_pathlist_entry *pe;
8217 int ch, can_recurse = 0, pflag = 0;
8218 FILE *patch_script_file = NULL;
8219 const char *patch_script_path = NULL;
8220 struct choose_patch_arg cpa;
8221 int *pack_fds = NULL;
8223 TAILQ_INIT(&paths);
8225 while ((ch = getopt(argc, argv, "F:pR")) != -1) {
8226 switch (ch) {
8227 case 'F':
8228 patch_script_path = optarg;
8229 break;
8230 case 'p':
8231 pflag = 1;
8232 break;
8233 case 'R':
8234 can_recurse = 1;
8235 break;
8236 default:
8237 usage_revert();
8238 /* NOTREACHED */
8242 argc -= optind;
8243 argv += optind;
8245 #ifndef PROFILE
8246 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
8247 "unveil", NULL) == -1)
8248 err(1, "pledge");
8249 #endif
8250 if (argc < 1)
8251 usage_revert();
8252 if (patch_script_path && !pflag)
8253 errx(1, "-F option can only be used together with -p option");
8255 cwd = getcwd(NULL, 0);
8256 if (cwd == NULL) {
8257 error = got_error_from_errno("getcwd");
8258 goto done;
8261 error = got_repo_pack_fds_open(&pack_fds);
8262 if (error != NULL)
8263 goto done;
8265 error = got_worktree_open(&worktree, cwd);
8266 if (error) {
8267 if (error->code == GOT_ERR_NOT_WORKTREE)
8268 error = wrap_not_worktree_error(error, "revert", cwd);
8269 goto done;
8272 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
8273 NULL, pack_fds);
8274 if (error != NULL)
8275 goto done;
8277 if (patch_script_path) {
8278 patch_script_file = fopen(patch_script_path, "re");
8279 if (patch_script_file == NULL) {
8280 error = got_error_from_errno2("fopen",
8281 patch_script_path);
8282 goto done;
8285 error = apply_unveil(got_repo_get_path(repo), 1,
8286 got_worktree_get_root_path(worktree));
8287 if (error)
8288 goto done;
8290 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
8291 if (error)
8292 goto done;
8294 if (!can_recurse) {
8295 char *ondisk_path;
8296 struct stat sb;
8297 TAILQ_FOREACH(pe, &paths, entry) {
8298 if (asprintf(&ondisk_path, "%s/%s",
8299 got_worktree_get_root_path(worktree),
8300 pe->path) == -1) {
8301 error = got_error_from_errno("asprintf");
8302 goto done;
8304 if (lstat(ondisk_path, &sb) == -1) {
8305 if (errno == ENOENT) {
8306 free(ondisk_path);
8307 continue;
8309 error = got_error_from_errno2("lstat",
8310 ondisk_path);
8311 free(ondisk_path);
8312 goto done;
8314 free(ondisk_path);
8315 if (S_ISDIR(sb.st_mode)) {
8316 error = got_error_msg(GOT_ERR_BAD_PATH,
8317 "reverting directories requires -R option");
8318 goto done;
8323 cpa.patch_script_file = patch_script_file;
8324 cpa.action = "revert";
8325 error = got_worktree_revert(worktree, &paths, revert_progress, NULL,
8326 pflag ? choose_patch : NULL, &cpa, repo);
8327 done:
8328 if (patch_script_file && fclose(patch_script_file) == EOF &&
8329 error == NULL)
8330 error = got_error_from_errno2("fclose", patch_script_path);
8331 if (repo) {
8332 const struct got_error *close_err = got_repo_close(repo);
8333 if (error == NULL)
8334 error = close_err;
8336 if (worktree)
8337 got_worktree_close(worktree);
8338 if (pack_fds) {
8339 const struct got_error *pack_err =
8340 got_repo_pack_fds_close(pack_fds);
8341 if (error == NULL)
8342 error = pack_err;
8344 free(path);
8345 free(cwd);
8346 return error;
8349 __dead static void
8350 usage_commit(void)
8352 fprintf(stderr, "usage: %s commit [-NS] [-A author] [-F path] "
8353 "[-m message] [path ...]\n", getprogname());
8354 exit(1);
8357 struct collect_commit_logmsg_arg {
8358 const char *cmdline_log;
8359 const char *prepared_log;
8360 int non_interactive;
8361 const char *editor;
8362 const char *worktree_path;
8363 const char *branch_name;
8364 const char *repo_path;
8365 char *logmsg_path;
8369 static const struct got_error *
8370 read_prepared_logmsg(char **logmsg, const char *path)
8372 const struct got_error *err = NULL;
8373 FILE *f = NULL;
8374 struct stat sb;
8375 size_t r;
8377 *logmsg = NULL;
8378 memset(&sb, 0, sizeof(sb));
8380 f = fopen(path, "re");
8381 if (f == NULL)
8382 return got_error_from_errno2("fopen", path);
8384 if (fstat(fileno(f), &sb) == -1) {
8385 err = got_error_from_errno2("fstat", path);
8386 goto done;
8388 if (sb.st_size == 0) {
8389 err = got_error(GOT_ERR_COMMIT_MSG_EMPTY);
8390 goto done;
8393 *logmsg = malloc(sb.st_size + 1);
8394 if (*logmsg == NULL) {
8395 err = got_error_from_errno("malloc");
8396 goto done;
8399 r = fread(*logmsg, 1, sb.st_size, f);
8400 if (r != sb.st_size) {
8401 if (ferror(f))
8402 err = got_error_from_errno2("fread", path);
8403 else
8404 err = got_error(GOT_ERR_IO);
8405 goto done;
8407 (*logmsg)[sb.st_size] = '\0';
8408 done:
8409 if (fclose(f) == EOF && err == NULL)
8410 err = got_error_from_errno2("fclose", path);
8411 if (err) {
8412 free(*logmsg);
8413 *logmsg = NULL;
8415 return err;
8418 static const struct got_error *
8419 collect_commit_logmsg(struct got_pathlist_head *commitable_paths,
8420 const char *diff_path, char **logmsg, void *arg)
8422 char *initial_content = NULL;
8423 struct got_pathlist_entry *pe;
8424 const struct got_error *err = NULL;
8425 char *template = NULL;
8426 struct collect_commit_logmsg_arg *a = arg;
8427 int initial_content_len;
8428 int fd = -1;
8429 size_t len;
8431 /* if a message was specified on the command line, just use it */
8432 if (a->cmdline_log != NULL && strlen(a->cmdline_log) != 0) {
8433 len = strlen(a->cmdline_log) + 1;
8434 *logmsg = malloc(len + 1);
8435 if (*logmsg == NULL)
8436 return got_error_from_errno("malloc");
8437 strlcpy(*logmsg, a->cmdline_log, len);
8438 return NULL;
8439 } else if (a->prepared_log != NULL && a->non_interactive)
8440 return read_prepared_logmsg(logmsg, a->prepared_log);
8442 if (asprintf(&template, "%s/logmsg", a->worktree_path) == -1)
8443 return got_error_from_errno("asprintf");
8445 err = got_opentemp_named_fd(&a->logmsg_path, &fd, template, "");
8446 if (err)
8447 goto done;
8449 if (a->prepared_log) {
8450 char *msg;
8451 err = read_prepared_logmsg(&msg, a->prepared_log);
8452 if (err)
8453 goto done;
8454 if (write(fd, msg, strlen(msg)) == -1) {
8455 err = got_error_from_errno2("write", a->logmsg_path);
8456 free(msg);
8457 goto done;
8459 free(msg);
8462 initial_content_len = asprintf(&initial_content,
8463 "\n# changes to be committed on branch %s:\n",
8464 a->branch_name);
8465 if (initial_content_len == -1) {
8466 err = got_error_from_errno("asprintf");
8467 goto done;
8470 if (write(fd, initial_content, initial_content_len) == -1) {
8471 err = got_error_from_errno2("write", a->logmsg_path);
8472 goto done;
8475 TAILQ_FOREACH(pe, commitable_paths, entry) {
8476 struct got_commitable *ct = pe->data;
8477 dprintf(fd, "# %c %s\n",
8478 got_commitable_get_status(ct),
8479 got_commitable_get_path(ct));
8482 if (diff_path) {
8483 dprintf(fd, "# detailed changes can be viewed in %s\n",
8484 diff_path);
8487 err = edit_logmsg(logmsg, a->editor, a->logmsg_path, initial_content,
8488 initial_content_len, a->prepared_log ? 0 : 1);
8489 done:
8490 free(initial_content);
8491 free(template);
8493 if (fd != -1 && close(fd) == -1 && err == NULL)
8494 err = got_error_from_errno2("close", a->logmsg_path);
8496 /* Editor is done; we can now apply unveil(2) */
8497 if (err == NULL)
8498 err = apply_unveil(a->repo_path, 0, a->worktree_path);
8499 if (err) {
8500 free(*logmsg);
8501 *logmsg = NULL;
8503 return err;
8506 static const struct got_error *
8507 cmd_commit(int argc, char *argv[])
8509 const struct got_error *error = NULL;
8510 struct got_worktree *worktree = NULL;
8511 struct got_repository *repo = NULL;
8512 char *cwd = NULL, *id_str = NULL;
8513 struct got_object_id *id = NULL;
8514 const char *logmsg = NULL;
8515 char *prepared_logmsg = NULL;
8516 struct collect_commit_logmsg_arg cl_arg;
8517 const char *author = NULL;
8518 char *gitconfig_path = NULL, *editor = NULL, *committer = NULL;
8519 int ch, rebase_in_progress, histedit_in_progress, preserve_logmsg = 0;
8520 int allow_bad_symlinks = 0, non_interactive = 0, merge_in_progress = 0;
8521 int show_diff = 1;
8522 struct got_pathlist_head paths;
8523 int *pack_fds = NULL;
8525 TAILQ_INIT(&paths);
8526 cl_arg.logmsg_path = NULL;
8528 while ((ch = getopt(argc, argv, "A:F:m:NnS")) != -1) {
8529 switch (ch) {
8530 case 'A':
8531 author = optarg;
8532 error = valid_author(author);
8533 if (error)
8534 return error;
8535 break;
8536 case 'F':
8537 if (logmsg != NULL)
8538 option_conflict('F', 'm');
8539 prepared_logmsg = realpath(optarg, NULL);
8540 if (prepared_logmsg == NULL)
8541 return got_error_from_errno2("realpath",
8542 optarg);
8543 break;
8544 case 'm':
8545 if (prepared_logmsg)
8546 option_conflict('m', 'F');
8547 logmsg = optarg;
8548 break;
8549 case 'N':
8550 non_interactive = 1;
8551 break;
8552 case 'n':
8553 show_diff = 0;
8554 break;
8555 case 'S':
8556 allow_bad_symlinks = 1;
8557 break;
8558 default:
8559 usage_commit();
8560 /* NOTREACHED */
8564 argc -= optind;
8565 argv += optind;
8567 #ifndef PROFILE
8568 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
8569 "unveil", NULL) == -1)
8570 err(1, "pledge");
8571 #endif
8572 cwd = getcwd(NULL, 0);
8573 if (cwd == NULL) {
8574 error = got_error_from_errno("getcwd");
8575 goto done;
8578 error = got_repo_pack_fds_open(&pack_fds);
8579 if (error != NULL)
8580 goto done;
8582 error = got_worktree_open(&worktree, cwd);
8583 if (error) {
8584 if (error->code == GOT_ERR_NOT_WORKTREE)
8585 error = wrap_not_worktree_error(error, "commit", cwd);
8586 goto done;
8589 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
8590 if (error)
8591 goto done;
8592 if (rebase_in_progress) {
8593 error = got_error(GOT_ERR_REBASING);
8594 goto done;
8597 error = got_worktree_histedit_in_progress(&histedit_in_progress,
8598 worktree);
8599 if (error)
8600 goto done;
8602 error = get_gitconfig_path(&gitconfig_path);
8603 if (error)
8604 goto done;
8605 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
8606 gitconfig_path, pack_fds);
8607 if (error != NULL)
8608 goto done;
8610 error = got_worktree_merge_in_progress(&merge_in_progress, worktree, repo);
8611 if (error)
8612 goto done;
8613 if (merge_in_progress) {
8614 error = got_error(GOT_ERR_MERGE_BUSY);
8615 goto done;
8618 error = get_author(&committer, repo, worktree);
8619 if (error)
8620 goto done;
8622 if (author != NULL && !strcmp(committer, author)) {
8623 error = got_error(GOT_ERR_COMMIT_REDUNDANT_AUTHOR);
8624 goto done;
8627 if (author == NULL)
8628 author = committer;
8631 * unveil(2) traverses exec(2); if an editor is used we have
8632 * to apply unveil after the log message has been written.
8634 if (logmsg == NULL || strlen(logmsg) == 0)
8635 error = get_editor(&editor);
8636 else
8637 error = apply_unveil(got_repo_get_path(repo), 0,
8638 got_worktree_get_root_path(worktree));
8639 if (error)
8640 goto done;
8642 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
8643 if (error)
8644 goto done;
8646 cl_arg.editor = editor;
8647 cl_arg.cmdline_log = logmsg;
8648 cl_arg.prepared_log = prepared_logmsg;
8649 cl_arg.non_interactive = non_interactive;
8650 cl_arg.worktree_path = got_worktree_get_root_path(worktree);
8651 cl_arg.branch_name = got_worktree_get_head_ref_name(worktree);
8652 if (!histedit_in_progress) {
8653 if (strncmp(cl_arg.branch_name, "refs/heads/", 11) != 0) {
8654 error = got_error(GOT_ERR_COMMIT_BRANCH);
8655 goto done;
8657 cl_arg.branch_name += 11;
8659 cl_arg.repo_path = got_repo_get_path(repo);
8660 error = got_worktree_commit(&id, worktree, &paths, author, committer,
8661 allow_bad_symlinks, show_diff, collect_commit_logmsg, &cl_arg,
8662 print_status, NULL, repo);
8663 if (error) {
8664 if (error->code != GOT_ERR_COMMIT_MSG_EMPTY &&
8665 cl_arg.logmsg_path != NULL)
8666 preserve_logmsg = 1;
8667 goto done;
8670 error = got_object_id_str(&id_str, id);
8671 if (error)
8672 goto done;
8673 printf("Created commit %s\n", id_str);
8674 done:
8675 if (preserve_logmsg) {
8676 fprintf(stderr, "%s: log message preserved in %s\n",
8677 getprogname(), cl_arg.logmsg_path);
8678 } else if (cl_arg.logmsg_path && unlink(cl_arg.logmsg_path) == -1 &&
8679 error == NULL)
8680 error = got_error_from_errno2("unlink", cl_arg.logmsg_path);
8681 free(cl_arg.logmsg_path);
8682 if (repo) {
8683 const struct got_error *close_err = got_repo_close(repo);
8684 if (error == NULL)
8685 error = close_err;
8687 if (worktree)
8688 got_worktree_close(worktree);
8689 if (pack_fds) {
8690 const struct got_error *pack_err =
8691 got_repo_pack_fds_close(pack_fds);
8692 if (error == NULL)
8693 error = pack_err;
8695 free(cwd);
8696 free(id_str);
8697 free(gitconfig_path);
8698 free(editor);
8699 free(committer);
8700 free(prepared_logmsg);
8701 return error;
8704 __dead static void
8705 usage_send(void)
8707 fprintf(stderr, "usage: %s send [-afqTv] [-b branch] [-d branch] "
8708 "[-r repository-path] [-t tag] [remote-repository]\n",
8709 getprogname());
8710 exit(1);
8713 static void
8714 print_load_info(int print_colored, int print_found, int print_trees,
8715 int ncolored, int nfound, int ntrees)
8717 if (print_colored) {
8718 printf("%d commit%s colored", ncolored,
8719 ncolored == 1 ? "" : "s");
8721 if (print_found) {
8722 printf("%s%d object%s found",
8723 ncolored > 0 ? "; " : "",
8724 nfound, nfound == 1 ? "" : "s");
8726 if (print_trees) {
8727 printf("; %d tree%s scanned", ntrees,
8728 ntrees == 1 ? "" : "s");
8732 struct got_send_progress_arg {
8733 char last_scaled_packsize[FMT_SCALED_STRSIZE];
8734 int verbosity;
8735 int last_ncolored;
8736 int last_nfound;
8737 int last_ntrees;
8738 int loading_done;
8739 int last_ncommits;
8740 int last_nobj_total;
8741 int last_p_deltify;
8742 int last_p_written;
8743 int last_p_sent;
8744 int printed_something;
8745 int sent_something;
8746 struct got_pathlist_head *delete_branches;
8749 static const struct got_error *
8750 send_progress(void *arg, int ncolored, int nfound, int ntrees,
8751 off_t packfile_size, int ncommits, int nobj_total, int nobj_deltify,
8752 int nobj_written, off_t bytes_sent, const char *refname, int success)
8754 struct got_send_progress_arg *a = arg;
8755 char scaled_packsize[FMT_SCALED_STRSIZE];
8756 char scaled_sent[FMT_SCALED_STRSIZE];
8757 int p_deltify = 0, p_written = 0, p_sent = 0;
8758 int print_colored = 0, print_found = 0, print_trees = 0;
8759 int print_searching = 0, print_total = 0;
8760 int print_deltify = 0, print_written = 0, print_sent = 0;
8762 if (a->verbosity < 0)
8763 return NULL;
8765 if (refname) {
8766 const char *status = success ? "accepted" : "rejected";
8768 if (success) {
8769 struct got_pathlist_entry *pe;
8770 TAILQ_FOREACH(pe, a->delete_branches, entry) {
8771 const char *branchname = pe->path;
8772 if (got_path_cmp(branchname, refname,
8773 strlen(branchname), strlen(refname)) == 0) {
8774 status = "deleted";
8775 a->sent_something = 1;
8776 break;
8781 if (a->printed_something)
8782 putchar('\n');
8783 printf("Server has %s %s", status, refname);
8784 a->printed_something = 1;
8785 return NULL;
8788 if (a->last_ncolored != ncolored) {
8789 print_colored = 1;
8790 a->last_ncolored = ncolored;
8793 if (a->last_nfound != nfound) {
8794 print_colored = 1;
8795 print_found = 1;
8796 a->last_nfound = nfound;
8799 if (a->last_ntrees != ntrees) {
8800 print_colored = 1;
8801 print_found = 1;
8802 print_trees = 1;
8803 a->last_ntrees = ntrees;
8806 if ((print_colored || print_found || print_trees) &&
8807 !a->loading_done) {
8808 printf("\r");
8809 print_load_info(print_colored, print_found, print_trees,
8810 ncolored, nfound, ntrees);
8811 a->printed_something = 1;
8812 fflush(stdout);
8813 return NULL;
8814 } else if (!a->loading_done) {
8815 printf("\r");
8816 print_load_info(1, 1, 1, ncolored, nfound, ntrees);
8817 printf("\n");
8818 a->loading_done = 1;
8821 if (fmt_scaled(packfile_size, scaled_packsize) == -1)
8822 return got_error_from_errno("fmt_scaled");
8823 if (fmt_scaled(bytes_sent, scaled_sent) == -1)
8824 return got_error_from_errno("fmt_scaled");
8826 if (a->last_ncommits != ncommits) {
8827 print_searching = 1;
8828 a->last_ncommits = ncommits;
8831 if (a->last_nobj_total != nobj_total) {
8832 print_searching = 1;
8833 print_total = 1;
8834 a->last_nobj_total = nobj_total;
8837 if (packfile_size > 0 && (a->last_scaled_packsize[0] == '\0' ||
8838 strcmp(scaled_packsize, a->last_scaled_packsize)) != 0) {
8839 if (strlcpy(a->last_scaled_packsize, scaled_packsize,
8840 FMT_SCALED_STRSIZE) >= FMT_SCALED_STRSIZE)
8841 return got_error(GOT_ERR_NO_SPACE);
8844 if (nobj_deltify > 0 || nobj_written > 0) {
8845 if (nobj_deltify > 0) {
8846 p_deltify = (nobj_deltify * 100) / nobj_total;
8847 if (p_deltify != a->last_p_deltify) {
8848 a->last_p_deltify = p_deltify;
8849 print_searching = 1;
8850 print_total = 1;
8851 print_deltify = 1;
8854 if (nobj_written > 0) {
8855 p_written = (nobj_written * 100) / nobj_total;
8856 if (p_written != a->last_p_written) {
8857 a->last_p_written = p_written;
8858 print_searching = 1;
8859 print_total = 1;
8860 print_deltify = 1;
8861 print_written = 1;
8866 if (bytes_sent > 0) {
8867 p_sent = (bytes_sent * 100) / packfile_size;
8868 if (p_sent != a->last_p_sent) {
8869 a->last_p_sent = p_sent;
8870 print_searching = 1;
8871 print_total = 1;
8872 print_deltify = 1;
8873 print_written = 1;
8874 print_sent = 1;
8876 a->sent_something = 1;
8879 if (print_searching || print_total || print_deltify || print_written ||
8880 print_sent)
8881 printf("\r");
8882 if (print_searching)
8883 printf("packing %d reference%s", ncommits,
8884 ncommits == 1 ? "" : "s");
8885 if (print_total)
8886 printf("; %d object%s", nobj_total,
8887 nobj_total == 1 ? "" : "s");
8888 if (print_deltify)
8889 printf("; deltify: %d%%", p_deltify);
8890 if (print_sent)
8891 printf("; uploading pack: %*s %d%%", FMT_SCALED_STRSIZE - 2,
8892 scaled_packsize, p_sent);
8893 else if (print_written)
8894 printf("; writing pack: %*s %d%%", FMT_SCALED_STRSIZE - 2,
8895 scaled_packsize, p_written);
8896 if (print_searching || print_total || print_deltify ||
8897 print_written || print_sent) {
8898 a->printed_something = 1;
8899 fflush(stdout);
8901 return NULL;
8904 static const struct got_error *
8905 cmd_send(int argc, char *argv[])
8907 const struct got_error *error = NULL;
8908 char *cwd = NULL, *repo_path = NULL;
8909 const char *remote_name;
8910 char *proto = NULL, *host = NULL, *port = NULL;
8911 char *repo_name = NULL, *server_path = NULL;
8912 const struct got_remote_repo *remotes, *remote = NULL;
8913 int nremotes, nbranches = 0, ndelete_branches = 0;
8914 struct got_repository *repo = NULL;
8915 struct got_worktree *worktree = NULL;
8916 const struct got_gotconfig *repo_conf = NULL, *worktree_conf = NULL;
8917 struct got_pathlist_head branches;
8918 struct got_pathlist_head tags;
8919 struct got_reflist_head all_branches;
8920 struct got_reflist_head all_tags;
8921 struct got_pathlist_head delete_args;
8922 struct got_pathlist_head delete_branches;
8923 struct got_reflist_entry *re;
8924 struct got_pathlist_entry *pe;
8925 int i, ch, sendfd = -1, sendstatus;
8926 pid_t sendpid = -1;
8927 struct got_send_progress_arg spa;
8928 int verbosity = 0, overwrite_refs = 0;
8929 int send_all_branches = 0, send_all_tags = 0;
8930 struct got_reference *ref = NULL;
8931 int *pack_fds = NULL;
8933 TAILQ_INIT(&branches);
8934 TAILQ_INIT(&tags);
8935 TAILQ_INIT(&all_branches);
8936 TAILQ_INIT(&all_tags);
8937 TAILQ_INIT(&delete_args);
8938 TAILQ_INIT(&delete_branches);
8940 while ((ch = getopt(argc, argv, "ab:d:fqr:Tt:v")) != -1) {
8941 switch (ch) {
8942 case 'a':
8943 send_all_branches = 1;
8944 break;
8945 case 'b':
8946 error = got_pathlist_append(&branches, optarg, NULL);
8947 if (error)
8948 return error;
8949 nbranches++;
8950 break;
8951 case 'd':
8952 error = got_pathlist_append(&delete_args, optarg, NULL);
8953 if (error)
8954 return error;
8955 break;
8956 case 'f':
8957 overwrite_refs = 1;
8958 break;
8959 case 'q':
8960 verbosity = -1;
8961 break;
8962 case 'r':
8963 repo_path = realpath(optarg, NULL);
8964 if (repo_path == NULL)
8965 return got_error_from_errno2("realpath",
8966 optarg);
8967 got_path_strip_trailing_slashes(repo_path);
8968 break;
8969 case 'T':
8970 send_all_tags = 1;
8971 break;
8972 case 't':
8973 error = got_pathlist_append(&tags, optarg, NULL);
8974 if (error)
8975 return error;
8976 break;
8977 case 'v':
8978 if (verbosity < 0)
8979 verbosity = 0;
8980 else if (verbosity < 3)
8981 verbosity++;
8982 break;
8983 default:
8984 usage_send();
8985 /* NOTREACHED */
8988 argc -= optind;
8989 argv += optind;
8991 if (send_all_branches && !TAILQ_EMPTY(&branches))
8992 option_conflict('a', 'b');
8993 if (send_all_tags && !TAILQ_EMPTY(&tags))
8994 option_conflict('T', 't');
8997 if (argc == 0)
8998 remote_name = GOT_SEND_DEFAULT_REMOTE_NAME;
8999 else if (argc == 1)
9000 remote_name = argv[0];
9001 else
9002 usage_send();
9004 cwd = getcwd(NULL, 0);
9005 if (cwd == NULL) {
9006 error = got_error_from_errno("getcwd");
9007 goto done;
9010 error = got_repo_pack_fds_open(&pack_fds);
9011 if (error != NULL)
9012 goto done;
9014 if (repo_path == NULL) {
9015 error = got_worktree_open(&worktree, cwd);
9016 if (error && error->code != GOT_ERR_NOT_WORKTREE)
9017 goto done;
9018 else
9019 error = NULL;
9020 if (worktree) {
9021 repo_path =
9022 strdup(got_worktree_get_repo_path(worktree));
9023 if (repo_path == NULL)
9024 error = got_error_from_errno("strdup");
9025 if (error)
9026 goto done;
9027 } else {
9028 repo_path = strdup(cwd);
9029 if (repo_path == NULL) {
9030 error = got_error_from_errno("strdup");
9031 goto done;
9036 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
9037 if (error)
9038 goto done;
9040 if (worktree) {
9041 worktree_conf = got_worktree_get_gotconfig(worktree);
9042 if (worktree_conf) {
9043 got_gotconfig_get_remotes(&nremotes, &remotes,
9044 worktree_conf);
9045 for (i = 0; i < nremotes; i++) {
9046 if (strcmp(remotes[i].name, remote_name) == 0) {
9047 remote = &remotes[i];
9048 break;
9053 if (remote == NULL) {
9054 repo_conf = got_repo_get_gotconfig(repo);
9055 if (repo_conf) {
9056 got_gotconfig_get_remotes(&nremotes, &remotes,
9057 repo_conf);
9058 for (i = 0; i < nremotes; i++) {
9059 if (strcmp(remotes[i].name, remote_name) == 0) {
9060 remote = &remotes[i];
9061 break;
9066 if (remote == NULL) {
9067 got_repo_get_gitconfig_remotes(&nremotes, &remotes, repo);
9068 for (i = 0; i < nremotes; i++) {
9069 if (strcmp(remotes[i].name, remote_name) == 0) {
9070 remote = &remotes[i];
9071 break;
9075 if (remote == NULL) {
9076 error = got_error_path(remote_name, GOT_ERR_NO_REMOTE);
9077 goto done;
9080 error = got_dial_parse_uri(&proto, &host, &port, &server_path,
9081 &repo_name, remote->send_url);
9082 if (error)
9083 goto done;
9085 if (strcmp(proto, "git") == 0) {
9086 #ifndef PROFILE
9087 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
9088 "sendfd dns inet unveil", NULL) == -1)
9089 err(1, "pledge");
9090 #endif
9091 } else if (strcmp(proto, "git+ssh") == 0 ||
9092 strcmp(proto, "ssh") == 0) {
9093 #ifndef PROFILE
9094 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
9095 "sendfd unveil", NULL) == -1)
9096 err(1, "pledge");
9097 #endif
9098 } else if (strcmp(proto, "http") == 0 ||
9099 strcmp(proto, "git+http") == 0) {
9100 error = got_error_path(proto, GOT_ERR_NOT_IMPL);
9101 goto done;
9102 } else {
9103 error = got_error_path(proto, GOT_ERR_BAD_PROTO);
9104 goto done;
9107 error = got_dial_apply_unveil(proto);
9108 if (error)
9109 goto done;
9111 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
9112 if (error)
9113 goto done;
9115 if (send_all_branches) {
9116 error = got_ref_list(&all_branches, repo, "refs/heads",
9117 got_ref_cmp_by_name, NULL);
9118 if (error)
9119 goto done;
9120 TAILQ_FOREACH(re, &all_branches, entry) {
9121 const char *branchname = got_ref_get_name(re->ref);
9122 error = got_pathlist_append(&branches,
9123 branchname, NULL);
9124 if (error)
9125 goto done;
9126 nbranches++;
9128 } else if (nbranches == 0) {
9129 for (i = 0; i < remote->nsend_branches; i++) {
9130 got_pathlist_append(&branches,
9131 remote->send_branches[i], NULL);
9135 if (send_all_tags) {
9136 error = got_ref_list(&all_tags, repo, "refs/tags",
9137 got_ref_cmp_by_name, NULL);
9138 if (error)
9139 goto done;
9140 TAILQ_FOREACH(re, &all_tags, entry) {
9141 const char *tagname = got_ref_get_name(re->ref);
9142 error = got_pathlist_append(&tags,
9143 tagname, NULL);
9144 if (error)
9145 goto done;
9150 * To prevent accidents only branches in refs/heads/ can be deleted
9151 * with 'got send -d'.
9152 * Deleting anything else requires local repository access or Git.
9154 TAILQ_FOREACH(pe, &delete_args, entry) {
9155 const char *branchname = pe->path;
9156 char *s;
9157 struct got_pathlist_entry *new;
9158 if (strncmp(branchname, "refs/heads/", 11) == 0) {
9159 s = strdup(branchname);
9160 if (s == NULL) {
9161 error = got_error_from_errno("strdup");
9162 goto done;
9164 } else {
9165 if (asprintf(&s, "refs/heads/%s", branchname) == -1) {
9166 error = got_error_from_errno("asprintf");
9167 goto done;
9170 error = got_pathlist_insert(&new, &delete_branches, s, NULL);
9171 if (error || new == NULL /* duplicate */)
9172 free(s);
9173 if (error)
9174 goto done;
9175 ndelete_branches++;
9178 if (nbranches == 0 && ndelete_branches == 0) {
9179 struct got_reference *head_ref;
9180 if (worktree)
9181 error = got_ref_open(&head_ref, repo,
9182 got_worktree_get_head_ref_name(worktree), 0);
9183 else
9184 error = got_ref_open(&head_ref, repo, GOT_REF_HEAD, 0);
9185 if (error)
9186 goto done;
9187 if (got_ref_is_symbolic(head_ref)) {
9188 error = got_ref_resolve_symbolic(&ref, repo, head_ref);
9189 got_ref_close(head_ref);
9190 if (error)
9191 goto done;
9192 } else
9193 ref = head_ref;
9194 error = got_pathlist_append(&branches, got_ref_get_name(ref),
9195 NULL);
9196 if (error)
9197 goto done;
9198 nbranches++;
9201 if (verbosity >= 0)
9202 printf("Connecting to \"%s\" %s%s%s\n", remote->name, host,
9203 port ? ":" : "", port ? port : "");
9205 error = got_send_connect(&sendpid, &sendfd, proto, host, port,
9206 server_path, verbosity);
9207 if (error)
9208 goto done;
9210 memset(&spa, 0, sizeof(spa));
9211 spa.last_scaled_packsize[0] = '\0';
9212 spa.last_p_deltify = -1;
9213 spa.last_p_written = -1;
9214 spa.verbosity = verbosity;
9215 spa.delete_branches = &delete_branches;
9216 error = got_send_pack(remote_name, &branches, &tags, &delete_branches,
9217 verbosity, overwrite_refs, sendfd, repo, send_progress, &spa,
9218 check_cancelled, NULL);
9219 if (spa.printed_something)
9220 putchar('\n');
9221 if (error)
9222 goto done;
9223 if (!spa.sent_something && verbosity >= 0)
9224 printf("Already up-to-date\n");
9225 done:
9226 if (sendpid > 0) {
9227 if (kill(sendpid, SIGTERM) == -1)
9228 error = got_error_from_errno("kill");
9229 if (waitpid(sendpid, &sendstatus, 0) == -1 && error == NULL)
9230 error = got_error_from_errno("waitpid");
9232 if (sendfd != -1 && close(sendfd) == -1 && error == NULL)
9233 error = got_error_from_errno("close");
9234 if (repo) {
9235 const struct got_error *close_err = got_repo_close(repo);
9236 if (error == NULL)
9237 error = close_err;
9239 if (worktree)
9240 got_worktree_close(worktree);
9241 if (pack_fds) {
9242 const struct got_error *pack_err =
9243 got_repo_pack_fds_close(pack_fds);
9244 if (error == NULL)
9245 error = pack_err;
9247 if (ref)
9248 got_ref_close(ref);
9249 got_pathlist_free(&branches);
9250 got_pathlist_free(&tags);
9251 got_ref_list_free(&all_branches);
9252 got_ref_list_free(&all_tags);
9253 got_pathlist_free(&delete_args);
9254 TAILQ_FOREACH(pe, &delete_branches, entry)
9255 free((char *)pe->path);
9256 got_pathlist_free(&delete_branches);
9257 free(cwd);
9258 free(repo_path);
9259 free(proto);
9260 free(host);
9261 free(port);
9262 free(server_path);
9263 free(repo_name);
9264 return error;
9267 __dead static void
9268 usage_cherrypick(void)
9270 fprintf(stderr, "usage: %s cherrypick commit-id\n", getprogname());
9271 exit(1);
9274 static const struct got_error *
9275 cmd_cherrypick(int argc, char *argv[])
9277 const struct got_error *error = NULL;
9278 struct got_worktree *worktree = NULL;
9279 struct got_repository *repo = NULL;
9280 char *cwd = NULL, *commit_id_str = NULL;
9281 struct got_object_id *commit_id = NULL;
9282 struct got_commit_object *commit = NULL;
9283 struct got_object_qid *pid;
9284 int ch;
9285 struct got_update_progress_arg upa;
9286 int *pack_fds = NULL;
9288 while ((ch = getopt(argc, argv, "")) != -1) {
9289 switch (ch) {
9290 default:
9291 usage_cherrypick();
9292 /* NOTREACHED */
9296 argc -= optind;
9297 argv += optind;
9299 #ifndef PROFILE
9300 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
9301 "unveil", NULL) == -1)
9302 err(1, "pledge");
9303 #endif
9304 if (argc != 1)
9305 usage_cherrypick();
9307 cwd = getcwd(NULL, 0);
9308 if (cwd == NULL) {
9309 error = got_error_from_errno("getcwd");
9310 goto done;
9313 error = got_repo_pack_fds_open(&pack_fds);
9314 if (error != NULL)
9315 goto done;
9317 error = got_worktree_open(&worktree, cwd);
9318 if (error) {
9319 if (error->code == GOT_ERR_NOT_WORKTREE)
9320 error = wrap_not_worktree_error(error, "cherrypick",
9321 cwd);
9322 goto done;
9325 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
9326 NULL, pack_fds);
9327 if (error != NULL)
9328 goto done;
9330 error = apply_unveil(got_repo_get_path(repo), 0,
9331 got_worktree_get_root_path(worktree));
9332 if (error)
9333 goto done;
9335 error = got_repo_match_object_id(&commit_id, NULL, argv[0],
9336 GOT_OBJ_TYPE_COMMIT, NULL, repo);
9337 if (error)
9338 goto done;
9339 error = got_object_id_str(&commit_id_str, commit_id);
9340 if (error)
9341 goto done;
9343 error = got_object_open_as_commit(&commit, repo, commit_id);
9344 if (error)
9345 goto done;
9346 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
9347 memset(&upa, 0, sizeof(upa));
9348 error = got_worktree_merge_files(worktree, pid ? &pid->id : NULL,
9349 commit_id, repo, update_progress, &upa, check_cancelled,
9350 NULL);
9351 if (error != NULL)
9352 goto done;
9354 if (upa.did_something)
9355 printf("Merged commit %s\n", commit_id_str);
9356 print_merge_progress_stats(&upa);
9357 done:
9358 if (commit)
9359 got_object_commit_close(commit);
9360 free(commit_id_str);
9361 if (worktree)
9362 got_worktree_close(worktree);
9363 if (repo) {
9364 const struct got_error *close_err = got_repo_close(repo);
9365 if (error == NULL)
9366 error = close_err;
9368 if (pack_fds) {
9369 const struct got_error *pack_err =
9370 got_repo_pack_fds_close(pack_fds);
9371 if (error == NULL)
9372 error = pack_err;
9375 return error;
9378 __dead static void
9379 usage_backout(void)
9381 fprintf(stderr, "usage: %s backout commit-id\n", getprogname());
9382 exit(1);
9385 static const struct got_error *
9386 cmd_backout(int argc, char *argv[])
9388 const struct got_error *error = NULL;
9389 struct got_worktree *worktree = NULL;
9390 struct got_repository *repo = NULL;
9391 char *cwd = NULL, *commit_id_str = NULL;
9392 struct got_object_id *commit_id = NULL;
9393 struct got_commit_object *commit = NULL;
9394 struct got_object_qid *pid;
9395 int ch;
9396 struct got_update_progress_arg upa;
9397 int *pack_fds = NULL;
9399 while ((ch = getopt(argc, argv, "")) != -1) {
9400 switch (ch) {
9401 default:
9402 usage_backout();
9403 /* NOTREACHED */
9407 argc -= optind;
9408 argv += optind;
9410 #ifndef PROFILE
9411 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
9412 "unveil", NULL) == -1)
9413 err(1, "pledge");
9414 #endif
9415 if (argc != 1)
9416 usage_backout();
9418 cwd = getcwd(NULL, 0);
9419 if (cwd == NULL) {
9420 error = got_error_from_errno("getcwd");
9421 goto done;
9424 error = got_repo_pack_fds_open(&pack_fds);
9425 if (error != NULL)
9426 goto done;
9428 error = got_worktree_open(&worktree, cwd);
9429 if (error) {
9430 if (error->code == GOT_ERR_NOT_WORKTREE)
9431 error = wrap_not_worktree_error(error, "backout", cwd);
9432 goto done;
9435 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
9436 NULL, pack_fds);
9437 if (error != NULL)
9438 goto done;
9440 error = apply_unveil(got_repo_get_path(repo), 0,
9441 got_worktree_get_root_path(worktree));
9442 if (error)
9443 goto done;
9445 error = got_repo_match_object_id(&commit_id, NULL, argv[0],
9446 GOT_OBJ_TYPE_COMMIT, NULL, repo);
9447 if (error)
9448 goto done;
9449 error = got_object_id_str(&commit_id_str, commit_id);
9450 if (error)
9451 goto done;
9453 error = got_object_open_as_commit(&commit, repo, commit_id);
9454 if (error)
9455 goto done;
9456 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
9457 if (pid == NULL) {
9458 error = got_error(GOT_ERR_ROOT_COMMIT);
9459 goto done;
9462 memset(&upa, 0, sizeof(upa));
9463 error = got_worktree_merge_files(worktree, commit_id, &pid->id,
9464 repo, update_progress, &upa, check_cancelled, NULL);
9465 if (error != NULL)
9466 goto done;
9468 if (upa.did_something)
9469 printf("Backed out commit %s\n", commit_id_str);
9470 print_merge_progress_stats(&upa);
9471 done:
9472 if (commit)
9473 got_object_commit_close(commit);
9474 free(commit_id_str);
9475 if (worktree)
9476 got_worktree_close(worktree);
9477 if (repo) {
9478 const struct got_error *close_err = got_repo_close(repo);
9479 if (error == NULL)
9480 error = close_err;
9482 if (pack_fds) {
9483 const struct got_error *pack_err =
9484 got_repo_pack_fds_close(pack_fds);
9485 if (error == NULL)
9486 error = pack_err;
9488 return error;
9491 __dead static void
9492 usage_rebase(void)
9494 fprintf(stderr, "usage: %s rebase [-aclX] [branch]\n", getprogname());
9495 exit(1);
9498 static void
9499 trim_logmsg(char *logmsg, int limit)
9501 char *nl;
9502 size_t len;
9504 len = strlen(logmsg);
9505 if (len > limit)
9506 len = limit;
9507 logmsg[len] = '\0';
9508 nl = strchr(logmsg, '\n');
9509 if (nl)
9510 *nl = '\0';
9513 static const struct got_error *
9514 get_short_logmsg(char **logmsg, int limit, struct got_commit_object *commit)
9516 const struct got_error *err;
9517 char *logmsg0 = NULL;
9518 const char *s;
9520 err = got_object_commit_get_logmsg(&logmsg0, commit);
9521 if (err)
9522 return err;
9524 s = logmsg0;
9525 while (isspace((unsigned char)s[0]))
9526 s++;
9528 *logmsg = strdup(s);
9529 if (*logmsg == NULL) {
9530 err = got_error_from_errno("strdup");
9531 goto done;
9534 trim_logmsg(*logmsg, limit);
9535 done:
9536 free(logmsg0);
9537 return err;
9540 static const struct got_error *
9541 show_rebase_merge_conflict(struct got_object_id *id,
9542 struct got_repository *repo)
9544 const struct got_error *err;
9545 struct got_commit_object *commit = NULL;
9546 char *id_str = NULL, *logmsg = NULL;
9548 err = got_object_open_as_commit(&commit, repo, id);
9549 if (err)
9550 return err;
9552 err = got_object_id_str(&id_str, id);
9553 if (err)
9554 goto done;
9556 id_str[12] = '\0';
9558 err = get_short_logmsg(&logmsg, 42, commit);
9559 if (err)
9560 goto done;
9562 printf("%s -> merge conflict: %s\n", id_str, logmsg);
9563 done:
9564 free(id_str);
9565 got_object_commit_close(commit);
9566 free(logmsg);
9567 return err;
9570 static const struct got_error *
9571 show_rebase_progress(struct got_commit_object *commit,
9572 struct got_object_id *old_id, struct got_object_id *new_id)
9574 const struct got_error *err;
9575 char *old_id_str = NULL, *new_id_str = NULL, *logmsg = NULL;
9577 err = got_object_id_str(&old_id_str, old_id);
9578 if (err)
9579 goto done;
9581 if (new_id) {
9582 err = got_object_id_str(&new_id_str, new_id);
9583 if (err)
9584 goto done;
9587 old_id_str[12] = '\0';
9588 if (new_id_str)
9589 new_id_str[12] = '\0';
9591 err = get_short_logmsg(&logmsg, 42, commit);
9592 if (err)
9593 goto done;
9595 printf("%s -> %s: %s\n", old_id_str,
9596 new_id_str ? new_id_str : "no-op change", logmsg);
9597 done:
9598 free(old_id_str);
9599 free(new_id_str);
9600 free(logmsg);
9601 return err;
9604 static const struct got_error *
9605 rebase_complete(struct got_worktree *worktree, struct got_fileindex *fileindex,
9606 struct got_reference *branch, struct got_reference *new_base_branch,
9607 struct got_reference *tmp_branch, struct got_repository *repo,
9608 int create_backup)
9610 printf("Switching work tree to %s\n", got_ref_get_name(branch));
9611 return got_worktree_rebase_complete(worktree, fileindex,
9612 new_base_branch, tmp_branch, branch, repo, create_backup);
9615 static const struct got_error *
9616 rebase_commit(struct got_pathlist_head *merged_paths,
9617 struct got_worktree *worktree, struct got_fileindex *fileindex,
9618 struct got_reference *tmp_branch, const char *committer,
9619 struct got_object_id *commit_id, struct got_repository *repo)
9621 const struct got_error *error;
9622 struct got_commit_object *commit;
9623 struct got_object_id *new_commit_id;
9625 error = got_object_open_as_commit(&commit, repo, commit_id);
9626 if (error)
9627 return error;
9629 error = got_worktree_rebase_commit(&new_commit_id, merged_paths,
9630 worktree, fileindex, tmp_branch, committer, commit, commit_id,
9631 repo);
9632 if (error) {
9633 if (error->code != GOT_ERR_COMMIT_NO_CHANGES)
9634 goto done;
9635 error = show_rebase_progress(commit, commit_id, NULL);
9636 } else {
9637 error = show_rebase_progress(commit, commit_id, new_commit_id);
9638 free(new_commit_id);
9640 done:
9641 got_object_commit_close(commit);
9642 return error;
9645 struct check_path_prefix_arg {
9646 const char *path_prefix;
9647 size_t len;
9648 int errcode;
9651 static const struct got_error *
9652 check_path_prefix_in_diff(void *arg, struct got_blob_object *blob1,
9653 struct got_blob_object *blob2, FILE *f1, FILE *f2,
9654 struct got_object_id *id1, struct got_object_id *id2,
9655 const char *path1, const char *path2,
9656 mode_t mode1, mode_t mode2, struct got_repository *repo)
9658 struct check_path_prefix_arg *a = arg;
9660 if ((path1 && !got_path_is_child(path1, a->path_prefix, a->len)) ||
9661 (path2 && !got_path_is_child(path2, a->path_prefix, a->len)))
9662 return got_error(a->errcode);
9664 return NULL;
9667 static const struct got_error *
9668 check_path_prefix(struct got_object_id *parent_id,
9669 struct got_object_id *commit_id, const char *path_prefix,
9670 int errcode, struct got_repository *repo)
9672 const struct got_error *err;
9673 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
9674 struct got_commit_object *commit = NULL, *parent_commit = NULL;
9675 struct check_path_prefix_arg cpp_arg;
9677 if (got_path_is_root_dir(path_prefix))
9678 return NULL;
9680 err = got_object_open_as_commit(&commit, repo, commit_id);
9681 if (err)
9682 goto done;
9684 err = got_object_open_as_commit(&parent_commit, repo, parent_id);
9685 if (err)
9686 goto done;
9688 err = got_object_open_as_tree(&tree1, repo,
9689 got_object_commit_get_tree_id(parent_commit));
9690 if (err)
9691 goto done;
9693 err = got_object_open_as_tree(&tree2, repo,
9694 got_object_commit_get_tree_id(commit));
9695 if (err)
9696 goto done;
9698 cpp_arg.path_prefix = path_prefix;
9699 while (cpp_arg.path_prefix[0] == '/')
9700 cpp_arg.path_prefix++;
9701 cpp_arg.len = strlen(cpp_arg.path_prefix);
9702 cpp_arg.errcode = errcode;
9703 err = got_diff_tree(tree1, tree2, NULL, NULL, -1, -1, "", "", repo,
9704 check_path_prefix_in_diff, &cpp_arg, 0);
9705 done:
9706 if (tree1)
9707 got_object_tree_close(tree1);
9708 if (tree2)
9709 got_object_tree_close(tree2);
9710 if (commit)
9711 got_object_commit_close(commit);
9712 if (parent_commit)
9713 got_object_commit_close(parent_commit);
9714 return err;
9717 static const struct got_error *
9718 collect_commits(struct got_object_id_queue *commits,
9719 struct got_object_id *initial_commit_id,
9720 struct got_object_id *iter_start_id, struct got_object_id *iter_stop_id,
9721 const char *path_prefix, int path_prefix_errcode,
9722 struct got_repository *repo)
9724 const struct got_error *err = NULL;
9725 struct got_commit_graph *graph = NULL;
9726 struct got_object_id parent_id, commit_id;
9727 struct got_object_qid *qid;
9729 err = got_commit_graph_open(&graph, "/", 1);
9730 if (err)
9731 return err;
9733 err = got_commit_graph_iter_start(graph, iter_start_id, repo,
9734 check_cancelled, NULL);
9735 if (err)
9736 goto done;
9738 memcpy(&commit_id, initial_commit_id, sizeof(commit_id));
9739 while (got_object_id_cmp(&commit_id, iter_stop_id) != 0) {
9740 err = got_commit_graph_iter_next(&parent_id, graph, repo,
9741 check_cancelled, NULL);
9742 if (err) {
9743 if (err->code == GOT_ERR_ITER_COMPLETED) {
9744 err = got_error_msg(GOT_ERR_ANCESTRY,
9745 "ran out of commits to rebase before "
9746 "youngest common ancestor commit has "
9747 "been reached?!?");
9749 goto done;
9750 } else {
9751 err = check_path_prefix(&parent_id, &commit_id,
9752 path_prefix, path_prefix_errcode, repo);
9753 if (err)
9754 goto done;
9756 err = got_object_qid_alloc(&qid, &commit_id);
9757 if (err)
9758 goto done;
9759 STAILQ_INSERT_HEAD(commits, qid, entry);
9761 memcpy(&commit_id, &parent_id, sizeof(commit_id));
9764 done:
9765 got_commit_graph_close(graph);
9766 return err;
9769 static const struct got_error *
9770 get_commit_brief_str(char **brief_str, struct got_commit_object *commit)
9772 const struct got_error *err = NULL;
9773 time_t committer_time;
9774 struct tm tm;
9775 char datebuf[11]; /* YYYY-MM-DD + NUL */
9776 char *author0 = NULL, *author, *smallerthan;
9777 char *logmsg0 = NULL, *logmsg, *newline;
9779 committer_time = got_object_commit_get_committer_time(commit);
9780 if (gmtime_r(&committer_time, &tm) == NULL)
9781 return got_error_from_errno("gmtime_r");
9782 if (strftime(datebuf, sizeof(datebuf), "%G-%m-%d", &tm) == 0)
9783 return got_error(GOT_ERR_NO_SPACE);
9785 author0 = strdup(got_object_commit_get_author(commit));
9786 if (author0 == NULL)
9787 return got_error_from_errno("strdup");
9788 author = author0;
9789 smallerthan = strchr(author, '<');
9790 if (smallerthan && smallerthan[1] != '\0')
9791 author = smallerthan + 1;
9792 author[strcspn(author, "@>")] = '\0';
9794 err = got_object_commit_get_logmsg(&logmsg0, commit);
9795 if (err)
9796 goto done;
9797 logmsg = logmsg0;
9798 while (*logmsg == '\n')
9799 logmsg++;
9800 newline = strchr(logmsg, '\n');
9801 if (newline)
9802 *newline = '\0';
9804 if (asprintf(brief_str, "%s %s %s",
9805 datebuf, author, logmsg) == -1)
9806 err = got_error_from_errno("asprintf");
9807 done:
9808 free(author0);
9809 free(logmsg0);
9810 return err;
9813 static const struct got_error *
9814 delete_backup_ref(struct got_reference *ref, struct got_object_id *id,
9815 struct got_repository *repo)
9817 const struct got_error *err;
9818 char *id_str;
9820 err = got_object_id_str(&id_str, id);
9821 if (err)
9822 return err;
9824 err = got_ref_delete(ref, repo);
9825 if (err)
9826 goto done;
9828 printf("Deleted %s: %s\n", got_ref_get_name(ref), id_str);
9829 done:
9830 free(id_str);
9831 return err;
9834 static const struct got_error *
9835 print_backup_ref(const char *branch_name, const char *new_id_str,
9836 struct got_object_id *old_commit_id, struct got_commit_object *old_commit,
9837 struct got_reflist_object_id_map *refs_idmap,
9838 struct got_repository *repo)
9840 const struct got_error *err = NULL;
9841 struct got_reflist_head *refs;
9842 char *refs_str = NULL;
9843 struct got_object_id *new_commit_id = NULL;
9844 struct got_commit_object *new_commit = NULL;
9845 char *new_commit_brief_str = NULL;
9846 struct got_object_id *yca_id = NULL;
9847 struct got_commit_object *yca_commit = NULL;
9848 char *yca_id_str = NULL, *yca_brief_str = NULL;
9849 char *custom_refs_str;
9851 if (asprintf(&custom_refs_str, "formerly %s", branch_name) == -1)
9852 return got_error_from_errno("asprintf");
9854 err = print_commit(old_commit, old_commit_id, repo, NULL, NULL,
9855 0, 0, refs_idmap, custom_refs_str);
9856 if (err)
9857 goto done;
9859 err = got_object_resolve_id_str(&new_commit_id, repo, new_id_str);
9860 if (err)
9861 goto done;
9863 refs = got_reflist_object_id_map_lookup(refs_idmap, new_commit_id);
9864 if (refs) {
9865 err = build_refs_str(&refs_str, refs, new_commit_id, repo, 0);
9866 if (err)
9867 goto done;
9870 err = got_object_open_as_commit(&new_commit, repo, new_commit_id);
9871 if (err)
9872 goto done;
9874 err = get_commit_brief_str(&new_commit_brief_str, new_commit);
9875 if (err)
9876 goto done;
9878 err = got_commit_graph_find_youngest_common_ancestor(&yca_id,
9879 old_commit_id, new_commit_id, 1, repo, check_cancelled, NULL);
9880 if (err)
9881 goto done;
9883 printf("has become commit %s%s%s%s\n %s\n", new_id_str,
9884 refs_str ? " (" : "", refs_str ? refs_str : "",
9885 refs_str ? ")" : "", new_commit_brief_str);
9886 if (yca_id && got_object_id_cmp(yca_id, new_commit_id) != 0 &&
9887 got_object_id_cmp(yca_id, old_commit_id) != 0) {
9888 free(refs_str);
9889 refs_str = NULL;
9891 err = got_object_open_as_commit(&yca_commit, repo, yca_id);
9892 if (err)
9893 goto done;
9895 err = get_commit_brief_str(&yca_brief_str, yca_commit);
9896 if (err)
9897 goto done;
9899 err = got_object_id_str(&yca_id_str, yca_id);
9900 if (err)
9901 goto done;
9903 refs = got_reflist_object_id_map_lookup(refs_idmap, yca_id);
9904 if (refs) {
9905 err = build_refs_str(&refs_str, refs, yca_id, repo, 0);
9906 if (err)
9907 goto done;
9909 printf("history forked at %s%s%s%s\n %s\n",
9910 yca_id_str,
9911 refs_str ? " (" : "", refs_str ? refs_str : "",
9912 refs_str ? ")" : "", yca_brief_str);
9914 done:
9915 free(custom_refs_str);
9916 free(new_commit_id);
9917 free(refs_str);
9918 free(yca_id);
9919 free(yca_id_str);
9920 free(yca_brief_str);
9921 if (new_commit)
9922 got_object_commit_close(new_commit);
9923 if (yca_commit)
9924 got_object_commit_close(yca_commit);
9926 return NULL;
9929 static const struct got_error *
9930 process_backup_refs(const char *backup_ref_prefix,
9931 const char *wanted_branch_name,
9932 int delete, struct got_repository *repo)
9934 const struct got_error *err;
9935 struct got_reflist_head refs, backup_refs;
9936 struct got_reflist_entry *re;
9937 const size_t backup_ref_prefix_len = strlen(backup_ref_prefix);
9938 struct got_object_id *old_commit_id = NULL;
9939 char *branch_name = NULL;
9940 struct got_commit_object *old_commit = NULL;
9941 struct got_reflist_object_id_map *refs_idmap = NULL;
9942 int wanted_branch_found = 0;
9944 TAILQ_INIT(&refs);
9945 TAILQ_INIT(&backup_refs);
9947 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
9948 if (err)
9949 return err;
9951 err = got_reflist_object_id_map_create(&refs_idmap, &refs, repo);
9952 if (err)
9953 goto done;
9955 if (wanted_branch_name) {
9956 if (strncmp(wanted_branch_name, "refs/heads/", 11) == 0)
9957 wanted_branch_name += 11;
9960 err = got_ref_list(&backup_refs, repo, backup_ref_prefix,
9961 got_ref_cmp_by_commit_timestamp_descending, repo);
9962 if (err)
9963 goto done;
9965 TAILQ_FOREACH(re, &backup_refs, entry) {
9966 const char *refname = got_ref_get_name(re->ref);
9967 char *slash;
9969 err = check_cancelled(NULL);
9970 if (err)
9971 break;
9973 err = got_ref_resolve(&old_commit_id, repo, re->ref);
9974 if (err)
9975 break;
9977 err = got_object_open_as_commit(&old_commit, repo,
9978 old_commit_id);
9979 if (err)
9980 break;
9982 if (strncmp(backup_ref_prefix, refname,
9983 backup_ref_prefix_len) == 0)
9984 refname += backup_ref_prefix_len;
9986 while (refname[0] == '/')
9987 refname++;
9989 branch_name = strdup(refname);
9990 if (branch_name == NULL) {
9991 err = got_error_from_errno("strdup");
9992 break;
9994 slash = strrchr(branch_name, '/');
9995 if (slash) {
9996 *slash = '\0';
9997 refname += strlen(branch_name) + 1;
10000 if (wanted_branch_name == NULL ||
10001 strcmp(wanted_branch_name, branch_name) == 0) {
10002 wanted_branch_found = 1;
10003 if (delete) {
10004 err = delete_backup_ref(re->ref,
10005 old_commit_id, repo);
10006 } else {
10007 err = print_backup_ref(branch_name, refname,
10008 old_commit_id, old_commit, refs_idmap,
10009 repo);
10011 if (err)
10012 break;
10015 free(old_commit_id);
10016 old_commit_id = NULL;
10017 free(branch_name);
10018 branch_name = NULL;
10019 got_object_commit_close(old_commit);
10020 old_commit = NULL;
10023 if (wanted_branch_name && !wanted_branch_found) {
10024 err = got_error_fmt(GOT_ERR_NOT_REF,
10025 "%s/%s/", backup_ref_prefix, wanted_branch_name);
10027 done:
10028 if (refs_idmap)
10029 got_reflist_object_id_map_free(refs_idmap);
10030 got_ref_list_free(&refs);
10031 got_ref_list_free(&backup_refs);
10032 free(old_commit_id);
10033 free(branch_name);
10034 if (old_commit)
10035 got_object_commit_close(old_commit);
10036 return err;
10039 static const struct got_error *
10040 abort_progress(void *arg, unsigned char status, const char *path)
10043 * Unversioned files should not clutter progress output when
10044 * an operation is aborted.
10046 if (status == GOT_STATUS_UNVERSIONED)
10047 return NULL;
10049 return update_progress(arg, status, path);
10052 static const struct got_error *
10053 cmd_rebase(int argc, char *argv[])
10055 const struct got_error *error = NULL;
10056 struct got_worktree *worktree = NULL;
10057 struct got_repository *repo = NULL;
10058 struct got_fileindex *fileindex = NULL;
10059 char *cwd = NULL, *committer = NULL, *gitconfig_path = NULL;
10060 struct got_reference *branch = NULL;
10061 struct got_reference *new_base_branch = NULL, *tmp_branch = NULL;
10062 struct got_object_id *commit_id = NULL, *parent_id = NULL;
10063 struct got_object_id *resume_commit_id = NULL;
10064 struct got_object_id *branch_head_commit_id = NULL, *yca_id = NULL;
10065 struct got_commit_object *commit = NULL;
10066 int ch, rebase_in_progress = 0, abort_rebase = 0, continue_rebase = 0;
10067 int histedit_in_progress = 0, merge_in_progress = 0;
10068 int create_backup = 1, list_backups = 0, delete_backups = 0;
10069 struct got_object_id_queue commits;
10070 struct got_pathlist_head merged_paths;
10071 const struct got_object_id_queue *parent_ids;
10072 struct got_object_qid *qid, *pid;
10073 struct got_update_progress_arg upa;
10074 int *pack_fds = NULL;
10076 STAILQ_INIT(&commits);
10077 TAILQ_INIT(&merged_paths);
10078 memset(&upa, 0, sizeof(upa));
10080 while ((ch = getopt(argc, argv, "aclX")) != -1) {
10081 switch (ch) {
10082 case 'a':
10083 abort_rebase = 1;
10084 break;
10085 case 'c':
10086 continue_rebase = 1;
10087 break;
10088 case 'l':
10089 list_backups = 1;
10090 break;
10091 case 'X':
10092 delete_backups = 1;
10093 break;
10094 default:
10095 usage_rebase();
10096 /* NOTREACHED */
10100 argc -= optind;
10101 argv += optind;
10103 #ifndef PROFILE
10104 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
10105 "unveil", NULL) == -1)
10106 err(1, "pledge");
10107 #endif
10108 if (list_backups) {
10109 if (abort_rebase)
10110 option_conflict('l', 'a');
10111 if (continue_rebase)
10112 option_conflict('l', 'c');
10113 if (delete_backups)
10114 option_conflict('l', 'X');
10115 if (argc != 0 && argc != 1)
10116 usage_rebase();
10117 } else if (delete_backups) {
10118 if (abort_rebase)
10119 option_conflict('X', 'a');
10120 if (continue_rebase)
10121 option_conflict('X', 'c');
10122 if (list_backups)
10123 option_conflict('l', 'X');
10124 if (argc != 0 && argc != 1)
10125 usage_rebase();
10126 } else {
10127 if (abort_rebase && continue_rebase)
10128 usage_rebase();
10129 else if (abort_rebase || continue_rebase) {
10130 if (argc != 0)
10131 usage_rebase();
10132 } else if (argc != 1)
10133 usage_rebase();
10136 cwd = getcwd(NULL, 0);
10137 if (cwd == NULL) {
10138 error = got_error_from_errno("getcwd");
10139 goto done;
10142 error = got_repo_pack_fds_open(&pack_fds);
10143 if (error != NULL)
10144 goto done;
10146 error = got_worktree_open(&worktree, cwd);
10147 if (error) {
10148 if (list_backups || delete_backups) {
10149 if (error->code != GOT_ERR_NOT_WORKTREE)
10150 goto done;
10151 } else {
10152 if (error->code == GOT_ERR_NOT_WORKTREE)
10153 error = wrap_not_worktree_error(error,
10154 "rebase", cwd);
10155 goto done;
10159 error = get_gitconfig_path(&gitconfig_path);
10160 if (error)
10161 goto done;
10162 error = got_repo_open(&repo,
10163 worktree ? got_worktree_get_repo_path(worktree) : cwd,
10164 gitconfig_path, pack_fds);
10165 if (error != NULL)
10166 goto done;
10168 error = get_author(&committer, repo, worktree);
10169 if (error && error->code != GOT_ERR_COMMIT_NO_AUTHOR)
10170 goto done;
10172 error = apply_unveil(got_repo_get_path(repo), 0,
10173 worktree ? got_worktree_get_root_path(worktree) : NULL);
10174 if (error)
10175 goto done;
10177 if (list_backups || delete_backups) {
10178 error = process_backup_refs(
10179 GOT_WORKTREE_REBASE_BACKUP_REF_PREFIX,
10180 argc == 1 ? argv[0] : NULL, delete_backups, repo);
10181 goto done; /* nothing else to do */
10184 error = got_worktree_histedit_in_progress(&histedit_in_progress,
10185 worktree);
10186 if (error)
10187 goto done;
10188 if (histedit_in_progress) {
10189 error = got_error(GOT_ERR_HISTEDIT_BUSY);
10190 goto done;
10193 error = got_worktree_merge_in_progress(&merge_in_progress,
10194 worktree, repo);
10195 if (error)
10196 goto done;
10197 if (merge_in_progress) {
10198 error = got_error(GOT_ERR_MERGE_BUSY);
10199 goto done;
10202 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
10203 if (error)
10204 goto done;
10206 if (abort_rebase) {
10207 if (!rebase_in_progress) {
10208 error = got_error(GOT_ERR_NOT_REBASING);
10209 goto done;
10211 error = got_worktree_rebase_continue(&resume_commit_id,
10212 &new_base_branch, &tmp_branch, &branch, &fileindex,
10213 worktree, repo);
10214 if (error)
10215 goto done;
10216 printf("Switching work tree to %s\n",
10217 got_ref_get_symref_target(new_base_branch));
10218 error = got_worktree_rebase_abort(worktree, fileindex, repo,
10219 new_base_branch, abort_progress, &upa);
10220 if (error)
10221 goto done;
10222 printf("Rebase of %s aborted\n", got_ref_get_name(branch));
10223 print_merge_progress_stats(&upa);
10224 goto done; /* nothing else to do */
10227 if (continue_rebase) {
10228 if (!rebase_in_progress) {
10229 error = got_error(GOT_ERR_NOT_REBASING);
10230 goto done;
10232 error = got_worktree_rebase_continue(&resume_commit_id,
10233 &new_base_branch, &tmp_branch, &branch, &fileindex,
10234 worktree, repo);
10235 if (error)
10236 goto done;
10238 error = rebase_commit(NULL, worktree, fileindex, tmp_branch,
10239 committer, resume_commit_id, repo);
10240 if (error)
10241 goto done;
10243 yca_id = got_object_id_dup(resume_commit_id);
10244 if (yca_id == NULL) {
10245 error = got_error_from_errno("got_object_id_dup");
10246 goto done;
10248 } else {
10249 error = got_ref_open(&branch, repo, argv[0], 0);
10250 if (error != NULL)
10251 goto done;
10252 if (strncmp(got_ref_get_name(branch), "refs/heads/", 11) != 0) {
10253 error = got_error_msg(GOT_ERR_COMMIT_BRANCH,
10254 "will not rebase a branch which lives outside "
10255 "the \"refs/heads/\" reference namespace");
10256 goto done;
10260 error = got_ref_resolve(&branch_head_commit_id, repo, branch);
10261 if (error)
10262 goto done;
10264 if (!continue_rebase) {
10265 struct got_object_id *base_commit_id;
10267 base_commit_id = got_worktree_get_base_commit_id(worktree);
10268 error = got_commit_graph_find_youngest_common_ancestor(&yca_id,
10269 base_commit_id, branch_head_commit_id, 1, repo,
10270 check_cancelled, NULL);
10271 if (error)
10272 goto done;
10273 if (yca_id == NULL) {
10274 error = got_error_msg(GOT_ERR_ANCESTRY,
10275 "specified branch shares no common ancestry "
10276 "with work tree's branch");
10277 goto done;
10280 error = check_same_branch(base_commit_id, branch, yca_id, repo);
10281 if (error) {
10282 if (error->code != GOT_ERR_ANCESTRY)
10283 goto done;
10284 error = NULL;
10285 } else {
10286 struct got_pathlist_head paths;
10287 printf("%s is already based on %s\n",
10288 got_ref_get_name(branch),
10289 got_worktree_get_head_ref_name(worktree));
10290 error = switch_head_ref(branch, branch_head_commit_id,
10291 worktree, repo);
10292 if (error)
10293 goto done;
10294 error = got_worktree_set_base_commit_id(worktree, repo,
10295 branch_head_commit_id);
10296 if (error)
10297 goto done;
10298 TAILQ_INIT(&paths);
10299 error = got_pathlist_append(&paths, "", NULL);
10300 if (error)
10301 goto done;
10302 error = got_worktree_checkout_files(worktree,
10303 &paths, repo, update_progress, &upa,
10304 check_cancelled, NULL);
10305 got_pathlist_free(&paths);
10306 if (error)
10307 goto done;
10308 if (upa.did_something) {
10309 char *id_str;
10310 error = got_object_id_str(&id_str,
10311 branch_head_commit_id);
10312 if (error)
10313 goto done;
10314 printf("Updated to %s: %s\n",
10315 got_worktree_get_head_ref_name(worktree),
10316 id_str);
10317 free(id_str);
10318 } else
10319 printf("Already up-to-date\n");
10320 print_update_progress_stats(&upa);
10321 goto done;
10325 commit_id = branch_head_commit_id;
10326 error = got_object_open_as_commit(&commit, repo, commit_id);
10327 if (error)
10328 goto done;
10330 parent_ids = got_object_commit_get_parent_ids(commit);
10331 pid = STAILQ_FIRST(parent_ids);
10332 if (pid == NULL) {
10333 error = got_error(GOT_ERR_EMPTY_REBASE);
10334 goto done;
10336 error = collect_commits(&commits, commit_id, &pid->id,
10337 yca_id, got_worktree_get_path_prefix(worktree),
10338 GOT_ERR_REBASE_PATH, repo);
10339 got_object_commit_close(commit);
10340 commit = NULL;
10341 if (error)
10342 goto done;
10344 if (!continue_rebase) {
10345 error = got_worktree_rebase_prepare(&new_base_branch,
10346 &tmp_branch, &fileindex, worktree, branch, repo);
10347 if (error)
10348 goto done;
10351 if (STAILQ_EMPTY(&commits)) {
10352 if (continue_rebase) {
10353 error = rebase_complete(worktree, fileindex,
10354 branch, new_base_branch, tmp_branch, repo,
10355 create_backup);
10356 goto done;
10357 } else {
10358 /* Fast-forward the reference of the branch. */
10359 struct got_object_id *new_head_commit_id;
10360 char *id_str;
10361 error = got_ref_resolve(&new_head_commit_id, repo,
10362 new_base_branch);
10363 if (error)
10364 goto done;
10365 error = got_object_id_str(&id_str, new_head_commit_id);
10366 if (error)
10367 goto done;
10368 printf("Forwarding %s to commit %s\n",
10369 got_ref_get_name(branch), id_str);
10370 free(id_str);
10371 error = got_ref_change_ref(branch,
10372 new_head_commit_id);
10373 if (error)
10374 goto done;
10375 /* No backup needed since objects did not change. */
10376 create_backup = 0;
10380 pid = NULL;
10381 STAILQ_FOREACH(qid, &commits, entry) {
10383 commit_id = &qid->id;
10384 parent_id = pid ? &pid->id : yca_id;
10385 pid = qid;
10387 memset(&upa, 0, sizeof(upa));
10388 error = got_worktree_rebase_merge_files(&merged_paths,
10389 worktree, fileindex, parent_id, commit_id, repo,
10390 update_progress, &upa, check_cancelled, NULL);
10391 if (error)
10392 goto done;
10394 print_merge_progress_stats(&upa);
10395 if (upa.conflicts > 0 || upa.missing > 0 ||
10396 upa.not_deleted > 0 || upa.unversioned > 0) {
10397 if (upa.conflicts > 0) {
10398 error = show_rebase_merge_conflict(&qid->id,
10399 repo);
10400 if (error)
10401 goto done;
10403 got_worktree_rebase_pathlist_free(&merged_paths);
10404 break;
10407 error = rebase_commit(&merged_paths, worktree, fileindex,
10408 tmp_branch, committer, commit_id, repo);
10409 got_worktree_rebase_pathlist_free(&merged_paths);
10410 if (error)
10411 goto done;
10414 if (upa.conflicts > 0 || upa.missing > 0 ||
10415 upa.not_deleted > 0 || upa.unversioned > 0) {
10416 error = got_worktree_rebase_postpone(worktree, fileindex);
10417 if (error)
10418 goto done;
10419 if (upa.conflicts > 0 && upa.missing == 0 &&
10420 upa.not_deleted == 0 && upa.unversioned == 0) {
10421 error = got_error_msg(GOT_ERR_CONFLICTS,
10422 "conflicts must be resolved before rebasing "
10423 "can continue");
10424 } else if (upa.conflicts > 0) {
10425 error = got_error_msg(GOT_ERR_CONFLICTS,
10426 "conflicts must be resolved before rebasing "
10427 "can continue; changes destined for some "
10428 "files were not yet merged and should be "
10429 "merged manually if required before the "
10430 "rebase operation is continued");
10431 } else {
10432 error = got_error_msg(GOT_ERR_CONFLICTS,
10433 "changes destined for some files were not "
10434 "yet merged and should be merged manually "
10435 "if required before the rebase operation "
10436 "is continued");
10438 } else
10439 error = rebase_complete(worktree, fileindex, branch,
10440 new_base_branch, tmp_branch, repo, create_backup);
10441 done:
10442 free(cwd);
10443 free(committer);
10444 free(gitconfig_path);
10445 got_object_id_queue_free(&commits);
10446 free(branch_head_commit_id);
10447 free(resume_commit_id);
10448 free(yca_id);
10449 if (commit)
10450 got_object_commit_close(commit);
10451 if (branch)
10452 got_ref_close(branch);
10453 if (new_base_branch)
10454 got_ref_close(new_base_branch);
10455 if (tmp_branch)
10456 got_ref_close(tmp_branch);
10457 if (worktree)
10458 got_worktree_close(worktree);
10459 if (repo) {
10460 const struct got_error *close_err = got_repo_close(repo);
10461 if (error == NULL)
10462 error = close_err;
10464 if (pack_fds) {
10465 const struct got_error *pack_err =
10466 got_repo_pack_fds_close(pack_fds);
10467 if (error == NULL)
10468 error = pack_err;
10470 return error;
10473 __dead static void
10474 usage_histedit(void)
10476 fprintf(stderr, "usage: %s histedit [-aceflmX] [-F histedit-script] "
10477 "[branch]\n", getprogname());
10478 exit(1);
10481 #define GOT_HISTEDIT_PICK 'p'
10482 #define GOT_HISTEDIT_EDIT 'e'
10483 #define GOT_HISTEDIT_FOLD 'f'
10484 #define GOT_HISTEDIT_DROP 'd'
10485 #define GOT_HISTEDIT_MESG 'm'
10487 static const struct got_histedit_cmd {
10488 unsigned char code;
10489 const char *name;
10490 const char *desc;
10491 } got_histedit_cmds[] = {
10492 { GOT_HISTEDIT_PICK, "pick", "use commit" },
10493 { GOT_HISTEDIT_EDIT, "edit", "use commit but stop for amending" },
10494 { GOT_HISTEDIT_FOLD, "fold", "combine with next commit that will "
10495 "be used" },
10496 { GOT_HISTEDIT_DROP, "drop", "remove commit from history" },
10497 { GOT_HISTEDIT_MESG, "mesg",
10498 "single-line log message for commit above (open editor if empty)" },
10501 struct got_histedit_list_entry {
10502 TAILQ_ENTRY(got_histedit_list_entry) entry;
10503 struct got_object_id *commit_id;
10504 const struct got_histedit_cmd *cmd;
10505 char *logmsg;
10507 TAILQ_HEAD(got_histedit_list, got_histedit_list_entry);
10509 static const struct got_error *
10510 histedit_write_commit(struct got_object_id *commit_id, const char *cmdname,
10511 FILE *f, struct got_repository *repo)
10513 const struct got_error *err = NULL;
10514 char *logmsg = NULL, *id_str = NULL;
10515 struct got_commit_object *commit = NULL;
10516 int n;
10518 err = got_object_open_as_commit(&commit, repo, commit_id);
10519 if (err)
10520 goto done;
10522 err = get_short_logmsg(&logmsg, 34, commit);
10523 if (err)
10524 goto done;
10526 err = got_object_id_str(&id_str, commit_id);
10527 if (err)
10528 goto done;
10530 n = fprintf(f, "%s %s %s\n", cmdname, id_str, logmsg);
10531 if (n < 0)
10532 err = got_ferror(f, GOT_ERR_IO);
10533 done:
10534 if (commit)
10535 got_object_commit_close(commit);
10536 free(id_str);
10537 free(logmsg);
10538 return err;
10541 static const struct got_error *
10542 histedit_write_commit_list(struct got_object_id_queue *commits,
10543 FILE *f, int edit_logmsg_only, int fold_only, int edit_only,
10544 struct got_repository *repo)
10546 const struct got_error *err = NULL;
10547 struct got_object_qid *qid;
10548 const char *histedit_cmd = NULL;
10550 if (STAILQ_EMPTY(commits))
10551 return got_error(GOT_ERR_EMPTY_HISTEDIT);
10553 STAILQ_FOREACH(qid, commits, entry) {
10554 histedit_cmd = got_histedit_cmds[0].name;
10555 if (edit_only)
10556 histedit_cmd = "edit";
10557 else if (fold_only && STAILQ_NEXT(qid, entry) != NULL)
10558 histedit_cmd = "fold";
10559 err = histedit_write_commit(&qid->id, histedit_cmd, f, repo);
10560 if (err)
10561 break;
10562 if (edit_logmsg_only) {
10563 int n = fprintf(f, "%c\n", GOT_HISTEDIT_MESG);
10564 if (n < 0) {
10565 err = got_ferror(f, GOT_ERR_IO);
10566 break;
10571 return err;
10574 static const struct got_error *
10575 write_cmd_list(FILE *f, const char *branch_name,
10576 struct got_object_id_queue *commits)
10578 const struct got_error *err = NULL;
10579 size_t i;
10580 int n;
10581 char *id_str;
10582 struct got_object_qid *qid;
10584 qid = STAILQ_FIRST(commits);
10585 err = got_object_id_str(&id_str, &qid->id);
10586 if (err)
10587 return err;
10589 n = fprintf(f,
10590 "# Editing the history of branch '%s' starting at\n"
10591 "# commit %s\n"
10592 "# Commits will be processed in order from top to "
10593 "bottom of this file.\n", branch_name, id_str);
10594 if (n < 0) {
10595 err = got_ferror(f, GOT_ERR_IO);
10596 goto done;
10599 n = fprintf(f, "# Available histedit commands:\n");
10600 if (n < 0) {
10601 err = got_ferror(f, GOT_ERR_IO);
10602 goto done;
10605 for (i = 0; i < nitems(got_histedit_cmds); i++) {
10606 const struct got_histedit_cmd *cmd = &got_histedit_cmds[i];
10607 n = fprintf(f, "# %s (%c): %s\n", cmd->name, cmd->code,
10608 cmd->desc);
10609 if (n < 0) {
10610 err = got_ferror(f, GOT_ERR_IO);
10611 break;
10614 done:
10615 free(id_str);
10616 return err;
10619 static const struct got_error *
10620 histedit_syntax_error(int lineno)
10622 static char msg[42];
10623 int ret;
10625 ret = snprintf(msg, sizeof(msg), "histedit syntax error on line %d",
10626 lineno);
10627 if (ret < 0 || (size_t)ret >= sizeof(msg))
10628 return got_error(GOT_ERR_HISTEDIT_SYNTAX);
10630 return got_error_msg(GOT_ERR_HISTEDIT_SYNTAX, msg);
10633 static const struct got_error *
10634 append_folded_commit_msg(char **new_msg, struct got_histedit_list_entry *hle,
10635 char *logmsg, struct got_repository *repo)
10637 const struct got_error *err;
10638 struct got_commit_object *folded_commit = NULL;
10639 char *id_str, *folded_logmsg = NULL;
10641 err = got_object_id_str(&id_str, hle->commit_id);
10642 if (err)
10643 return err;
10645 err = got_object_open_as_commit(&folded_commit, repo, hle->commit_id);
10646 if (err)
10647 goto done;
10649 err = got_object_commit_get_logmsg(&folded_logmsg, folded_commit);
10650 if (err)
10651 goto done;
10652 if (asprintf(new_msg, "%s%s# log message of folded commit %s: %s",
10653 logmsg ? logmsg : "", logmsg ? "\n" : "", id_str,
10654 folded_logmsg) == -1) {
10655 err = got_error_from_errno("asprintf");
10657 done:
10658 if (folded_commit)
10659 got_object_commit_close(folded_commit);
10660 free(id_str);
10661 free(folded_logmsg);
10662 return err;
10665 static struct got_histedit_list_entry *
10666 get_folded_commits(struct got_histedit_list_entry *hle)
10668 struct got_histedit_list_entry *prev, *folded = NULL;
10670 prev = TAILQ_PREV(hle, got_histedit_list, entry);
10671 while (prev && (prev->cmd->code == GOT_HISTEDIT_FOLD ||
10672 prev->cmd->code == GOT_HISTEDIT_DROP)) {
10673 if (prev->cmd->code == GOT_HISTEDIT_FOLD)
10674 folded = prev;
10675 prev = TAILQ_PREV(prev, got_histedit_list, entry);
10678 return folded;
10681 static const struct got_error *
10682 histedit_edit_logmsg(struct got_histedit_list_entry *hle,
10683 struct got_repository *repo)
10685 char *logmsg_path = NULL, *id_str = NULL, *orig_logmsg = NULL;
10686 char *logmsg = NULL, *new_msg = NULL, *editor = NULL;
10687 const struct got_error *err = NULL;
10688 struct got_commit_object *commit = NULL;
10689 int logmsg_len;
10690 int fd;
10691 struct got_histedit_list_entry *folded = NULL;
10693 err = got_object_open_as_commit(&commit, repo, hle->commit_id);
10694 if (err)
10695 return err;
10697 folded = get_folded_commits(hle);
10698 if (folded) {
10699 while (folded != hle) {
10700 if (folded->cmd->code == GOT_HISTEDIT_DROP) {
10701 folded = TAILQ_NEXT(folded, entry);
10702 continue;
10704 err = append_folded_commit_msg(&new_msg, folded,
10705 logmsg, repo);
10706 if (err)
10707 goto done;
10708 free(logmsg);
10709 logmsg = new_msg;
10710 folded = TAILQ_NEXT(folded, entry);
10714 err = got_object_id_str(&id_str, hle->commit_id);
10715 if (err)
10716 goto done;
10717 err = got_object_commit_get_logmsg(&orig_logmsg, commit);
10718 if (err)
10719 goto done;
10720 logmsg_len = asprintf(&new_msg,
10721 "%s\n# original log message of commit %s: %s",
10722 logmsg ? logmsg : "", id_str, orig_logmsg);
10723 if (logmsg_len == -1) {
10724 err = got_error_from_errno("asprintf");
10725 goto done;
10727 free(logmsg);
10728 logmsg = new_msg;
10730 err = got_object_id_str(&id_str, hle->commit_id);
10731 if (err)
10732 goto done;
10734 err = got_opentemp_named_fd(&logmsg_path, &fd,
10735 GOT_TMPDIR_STR "/got-logmsg", "");
10736 if (err)
10737 goto done;
10739 write(fd, logmsg, logmsg_len);
10740 close(fd);
10742 err = get_editor(&editor);
10743 if (err)
10744 goto done;
10746 err = edit_logmsg(&hle->logmsg, editor, logmsg_path, logmsg,
10747 logmsg_len, 0);
10748 if (err) {
10749 if (err->code != GOT_ERR_COMMIT_MSG_EMPTY)
10750 goto done;
10751 err = NULL;
10752 hle->logmsg = strdup(new_msg);
10753 if (hle->logmsg == NULL)
10754 err = got_error_from_errno("strdup");
10756 done:
10757 if (logmsg_path && unlink(logmsg_path) != 0 && err == NULL)
10758 err = got_error_from_errno2("unlink", logmsg_path);
10759 free(logmsg_path);
10760 free(logmsg);
10761 free(orig_logmsg);
10762 free(editor);
10763 if (commit)
10764 got_object_commit_close(commit);
10765 return err;
10768 static const struct got_error *
10769 histedit_parse_list(struct got_histedit_list *histedit_cmds,
10770 FILE *f, struct got_repository *repo)
10772 const struct got_error *err = NULL;
10773 char *line = NULL, *p, *end;
10774 size_t i, size;
10775 ssize_t len;
10776 int lineno = 0, lastcmd = -1;
10777 const struct got_histedit_cmd *cmd;
10778 struct got_object_id *commit_id = NULL;
10779 struct got_histedit_list_entry *hle = NULL;
10781 for (;;) {
10782 len = getline(&line, &size, f);
10783 if (len == -1) {
10784 const struct got_error *getline_err;
10785 if (feof(f))
10786 break;
10787 getline_err = got_error_from_errno("getline");
10788 err = got_ferror(f, getline_err->code);
10789 break;
10791 lineno++;
10792 p = line;
10793 while (isspace((unsigned char)p[0]))
10794 p++;
10795 if (p[0] == '#' || p[0] == '\0') {
10796 free(line);
10797 line = NULL;
10798 continue;
10800 cmd = NULL;
10801 for (i = 0; i < nitems(got_histedit_cmds); i++) {
10802 cmd = &got_histedit_cmds[i];
10803 if (strncmp(cmd->name, p, strlen(cmd->name)) == 0 &&
10804 isspace((unsigned char)p[strlen(cmd->name)])) {
10805 p += strlen(cmd->name);
10806 break;
10808 if (p[0] == cmd->code && isspace((unsigned char)p[1])) {
10809 p++;
10810 break;
10813 if (i == nitems(got_histedit_cmds)) {
10814 err = histedit_syntax_error(lineno);
10815 break;
10817 while (isspace((unsigned char)p[0]))
10818 p++;
10819 if (cmd->code == GOT_HISTEDIT_MESG) {
10820 if (lastcmd != GOT_HISTEDIT_PICK &&
10821 lastcmd != GOT_HISTEDIT_EDIT) {
10822 err = got_error(GOT_ERR_HISTEDIT_CMD);
10823 break;
10825 if (p[0] == '\0') {
10826 err = histedit_edit_logmsg(hle, repo);
10827 if (err)
10828 break;
10829 } else {
10830 hle->logmsg = strdup(p);
10831 if (hle->logmsg == NULL) {
10832 err = got_error_from_errno("strdup");
10833 break;
10836 free(line);
10837 line = NULL;
10838 lastcmd = cmd->code;
10839 continue;
10840 } else {
10841 end = p;
10842 while (end[0] && !isspace((unsigned char)end[0]))
10843 end++;
10844 *end = '\0';
10846 err = got_object_resolve_id_str(&commit_id, repo, p);
10847 if (err) {
10848 /* override error code */
10849 err = histedit_syntax_error(lineno);
10850 break;
10853 hle = malloc(sizeof(*hle));
10854 if (hle == NULL) {
10855 err = got_error_from_errno("malloc");
10856 break;
10858 hle->cmd = cmd;
10859 hle->commit_id = commit_id;
10860 hle->logmsg = NULL;
10861 commit_id = NULL;
10862 free(line);
10863 line = NULL;
10864 TAILQ_INSERT_TAIL(histedit_cmds, hle, entry);
10865 lastcmd = cmd->code;
10868 free(line);
10869 free(commit_id);
10870 return err;
10873 static const struct got_error *
10874 histedit_check_script(struct got_histedit_list *histedit_cmds,
10875 struct got_object_id_queue *commits, struct got_repository *repo)
10877 const struct got_error *err = NULL;
10878 struct got_object_qid *qid;
10879 struct got_histedit_list_entry *hle;
10880 static char msg[92];
10881 char *id_str;
10883 if (TAILQ_EMPTY(histedit_cmds))
10884 return got_error_msg(GOT_ERR_EMPTY_HISTEDIT,
10885 "histedit script contains no commands");
10886 if (STAILQ_EMPTY(commits))
10887 return got_error(GOT_ERR_EMPTY_HISTEDIT);
10889 TAILQ_FOREACH(hle, histedit_cmds, entry) {
10890 struct got_histedit_list_entry *hle2;
10891 TAILQ_FOREACH(hle2, histedit_cmds, entry) {
10892 if (hle == hle2)
10893 continue;
10894 if (got_object_id_cmp(hle->commit_id,
10895 hle2->commit_id) != 0)
10896 continue;
10897 err = got_object_id_str(&id_str, hle->commit_id);
10898 if (err)
10899 return err;
10900 snprintf(msg, sizeof(msg), "commit %s is listed "
10901 "more than once in histedit script", id_str);
10902 free(id_str);
10903 return got_error_msg(GOT_ERR_HISTEDIT_CMD, msg);
10907 STAILQ_FOREACH(qid, commits, entry) {
10908 TAILQ_FOREACH(hle, histedit_cmds, entry) {
10909 if (got_object_id_cmp(&qid->id, hle->commit_id) == 0)
10910 break;
10912 if (hle == NULL) {
10913 err = got_object_id_str(&id_str, &qid->id);
10914 if (err)
10915 return err;
10916 snprintf(msg, sizeof(msg),
10917 "commit %s missing from histedit script", id_str);
10918 free(id_str);
10919 return got_error_msg(GOT_ERR_HISTEDIT_CMD, msg);
10923 hle = TAILQ_LAST(histedit_cmds, got_histedit_list);
10924 if (hle && hle->cmd->code == GOT_HISTEDIT_FOLD)
10925 return got_error_msg(GOT_ERR_HISTEDIT_CMD,
10926 "last commit in histedit script cannot be folded");
10928 return NULL;
10931 static const struct got_error *
10932 histedit_run_editor(struct got_histedit_list *histedit_cmds,
10933 const char *path, struct got_object_id_queue *commits,
10934 struct got_repository *repo)
10936 const struct got_error *err = NULL;
10937 char *editor;
10938 FILE *f = NULL;
10940 err = get_editor(&editor);
10941 if (err)
10942 return err;
10944 if (spawn_editor(editor, path) == -1) {
10945 err = got_error_from_errno("failed spawning editor");
10946 goto done;
10949 f = fopen(path, "re");
10950 if (f == NULL) {
10951 err = got_error_from_errno("fopen");
10952 goto done;
10954 err = histedit_parse_list(histedit_cmds, f, repo);
10955 if (err)
10956 goto done;
10958 err = histedit_check_script(histedit_cmds, commits, repo);
10959 done:
10960 if (f && fclose(f) == EOF && err == NULL)
10961 err = got_error_from_errno("fclose");
10962 free(editor);
10963 return err;
10966 static const struct got_error *
10967 histedit_edit_list_retry(struct got_histedit_list *, const struct got_error *,
10968 struct got_object_id_queue *, const char *, const char *,
10969 struct got_repository *);
10971 static const struct got_error *
10972 histedit_edit_script(struct got_histedit_list *histedit_cmds,
10973 struct got_object_id_queue *commits, const char *branch_name,
10974 int edit_logmsg_only, int fold_only, int edit_only,
10975 struct got_repository *repo)
10977 const struct got_error *err;
10978 FILE *f = NULL;
10979 char *path = NULL;
10981 err = got_opentemp_named(&path, &f, "got-histedit", "");
10982 if (err)
10983 return err;
10985 err = write_cmd_list(f, branch_name, commits);
10986 if (err)
10987 goto done;
10989 err = histedit_write_commit_list(commits, f, edit_logmsg_only,
10990 fold_only, edit_only, repo);
10991 if (err)
10992 goto done;
10994 if (edit_logmsg_only || fold_only || edit_only) {
10995 rewind(f);
10996 err = histedit_parse_list(histedit_cmds, f, repo);
10997 } else {
10998 if (fclose(f) == EOF) {
10999 err = got_error_from_errno("fclose");
11000 goto done;
11002 f = NULL;
11003 err = histedit_run_editor(histedit_cmds, path, commits, repo);
11004 if (err) {
11005 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
11006 err->code != GOT_ERR_HISTEDIT_CMD)
11007 goto done;
11008 err = histedit_edit_list_retry(histedit_cmds, err,
11009 commits, path, branch_name, repo);
11012 done:
11013 if (f && fclose(f) == EOF && err == NULL)
11014 err = got_error_from_errno("fclose");
11015 if (path && unlink(path) != 0 && err == NULL)
11016 err = got_error_from_errno2("unlink", path);
11017 free(path);
11018 return err;
11021 static const struct got_error *
11022 histedit_save_list(struct got_histedit_list *histedit_cmds,
11023 struct got_worktree *worktree, struct got_repository *repo)
11025 const struct got_error *err = NULL;
11026 char *path = NULL;
11027 FILE *f = NULL;
11028 struct got_histedit_list_entry *hle;
11029 struct got_commit_object *commit = NULL;
11031 err = got_worktree_get_histedit_script_path(&path, worktree);
11032 if (err)
11033 return err;
11035 f = fopen(path, "we");
11036 if (f == NULL) {
11037 err = got_error_from_errno2("fopen", path);
11038 goto done;
11040 TAILQ_FOREACH(hle, histedit_cmds, entry) {
11041 err = histedit_write_commit(hle->commit_id, hle->cmd->name, f,
11042 repo);
11043 if (err)
11044 break;
11046 if (hle->logmsg) {
11047 int n = fprintf(f, "%c %s\n",
11048 GOT_HISTEDIT_MESG, hle->logmsg);
11049 if (n < 0) {
11050 err = got_ferror(f, GOT_ERR_IO);
11051 break;
11055 done:
11056 if (f && fclose(f) == EOF && err == NULL)
11057 err = got_error_from_errno("fclose");
11058 free(path);
11059 if (commit)
11060 got_object_commit_close(commit);
11061 return err;
11064 static void
11065 histedit_free_list(struct got_histedit_list *histedit_cmds)
11067 struct got_histedit_list_entry *hle;
11069 while ((hle = TAILQ_FIRST(histedit_cmds))) {
11070 TAILQ_REMOVE(histedit_cmds, hle, entry);
11071 free(hle);
11075 static const struct got_error *
11076 histedit_load_list(struct got_histedit_list *histedit_cmds,
11077 const char *path, struct got_repository *repo)
11079 const struct got_error *err = NULL;
11080 FILE *f = NULL;
11082 f = fopen(path, "re");
11083 if (f == NULL) {
11084 err = got_error_from_errno2("fopen", path);
11085 goto done;
11088 err = histedit_parse_list(histedit_cmds, f, repo);
11089 done:
11090 if (f && fclose(f) == EOF && err == NULL)
11091 err = got_error_from_errno("fclose");
11092 return err;
11095 static const struct got_error *
11096 histedit_edit_list_retry(struct got_histedit_list *histedit_cmds,
11097 const struct got_error *edit_err, struct got_object_id_queue *commits,
11098 const char *path, const char *branch_name, struct got_repository *repo)
11100 const struct got_error *err = NULL, *prev_err = edit_err;
11101 int resp = ' ';
11103 while (resp != 'c' && resp != 'r' && resp != 'a') {
11104 printf("%s: %s\n(c)ontinue editing, (r)estart editing, "
11105 "or (a)bort: ", getprogname(), prev_err->msg);
11106 resp = getchar();
11107 if (resp == '\n')
11108 resp = getchar();
11109 if (resp == 'c') {
11110 histedit_free_list(histedit_cmds);
11111 err = histedit_run_editor(histedit_cmds, path, commits,
11112 repo);
11113 if (err) {
11114 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
11115 err->code != GOT_ERR_HISTEDIT_CMD)
11116 break;
11117 prev_err = err;
11118 resp = ' ';
11119 continue;
11121 break;
11122 } else if (resp == 'r') {
11123 histedit_free_list(histedit_cmds);
11124 err = histedit_edit_script(histedit_cmds,
11125 commits, branch_name, 0, 0, 0, repo);
11126 if (err) {
11127 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
11128 err->code != GOT_ERR_HISTEDIT_CMD)
11129 break;
11130 prev_err = err;
11131 resp = ' ';
11132 continue;
11134 break;
11135 } else if (resp == 'a') {
11136 err = got_error(GOT_ERR_HISTEDIT_CANCEL);
11137 break;
11138 } else
11139 printf("invalid response '%c'\n", resp);
11142 return err;
11145 static const struct got_error *
11146 histedit_complete(struct got_worktree *worktree,
11147 struct got_fileindex *fileindex, struct got_reference *tmp_branch,
11148 struct got_reference *branch, struct got_repository *repo)
11150 printf("Switching work tree to %s\n",
11151 got_ref_get_symref_target(branch));
11152 return got_worktree_histedit_complete(worktree, fileindex, tmp_branch,
11153 branch, repo);
11156 static const struct got_error *
11157 show_histedit_progress(struct got_commit_object *commit,
11158 struct got_histedit_list_entry *hle, struct got_object_id *new_id)
11160 const struct got_error *err;
11161 char *old_id_str = NULL, *new_id_str = NULL, *logmsg = NULL;
11163 err = got_object_id_str(&old_id_str, hle->commit_id);
11164 if (err)
11165 goto done;
11167 if (new_id) {
11168 err = got_object_id_str(&new_id_str, new_id);
11169 if (err)
11170 goto done;
11173 old_id_str[12] = '\0';
11174 if (new_id_str)
11175 new_id_str[12] = '\0';
11177 if (hle->logmsg) {
11178 logmsg = strdup(hle->logmsg);
11179 if (logmsg == NULL) {
11180 err = got_error_from_errno("strdup");
11181 goto done;
11183 trim_logmsg(logmsg, 42);
11184 } else {
11185 err = get_short_logmsg(&logmsg, 42, commit);
11186 if (err)
11187 goto done;
11190 switch (hle->cmd->code) {
11191 case GOT_HISTEDIT_PICK:
11192 case GOT_HISTEDIT_EDIT:
11193 printf("%s -> %s: %s\n", old_id_str,
11194 new_id_str ? new_id_str : "no-op change", logmsg);
11195 break;
11196 case GOT_HISTEDIT_DROP:
11197 case GOT_HISTEDIT_FOLD:
11198 printf("%s -> %s commit: %s\n", old_id_str, hle->cmd->name,
11199 logmsg);
11200 break;
11201 default:
11202 break;
11204 done:
11205 free(old_id_str);
11206 free(new_id_str);
11207 return err;
11210 static const struct got_error *
11211 histedit_commit(struct got_pathlist_head *merged_paths,
11212 struct got_worktree *worktree, struct got_fileindex *fileindex,
11213 struct got_reference *tmp_branch, struct got_histedit_list_entry *hle,
11214 const char *committer, struct got_repository *repo)
11216 const struct got_error *err;
11217 struct got_commit_object *commit;
11218 struct got_object_id *new_commit_id;
11220 if ((hle->cmd->code == GOT_HISTEDIT_EDIT || get_folded_commits(hle))
11221 && hle->logmsg == NULL) {
11222 err = histedit_edit_logmsg(hle, repo);
11223 if (err)
11224 return err;
11227 err = got_object_open_as_commit(&commit, repo, hle->commit_id);
11228 if (err)
11229 return err;
11231 err = got_worktree_histedit_commit(&new_commit_id, merged_paths,
11232 worktree, fileindex, tmp_branch, committer, commit, hle->commit_id,
11233 hle->logmsg, repo);
11234 if (err) {
11235 if (err->code != GOT_ERR_COMMIT_NO_CHANGES)
11236 goto done;
11237 err = show_histedit_progress(commit, hle, NULL);
11238 } else {
11239 err = show_histedit_progress(commit, hle, new_commit_id);
11240 free(new_commit_id);
11242 done:
11243 got_object_commit_close(commit);
11244 return err;
11247 static const struct got_error *
11248 histedit_skip_commit(struct got_histedit_list_entry *hle,
11249 struct got_worktree *worktree, struct got_repository *repo)
11251 const struct got_error *error;
11252 struct got_commit_object *commit;
11254 error = got_worktree_histedit_skip_commit(worktree, hle->commit_id,
11255 repo);
11256 if (error)
11257 return error;
11259 error = got_object_open_as_commit(&commit, repo, hle->commit_id);
11260 if (error)
11261 return error;
11263 error = show_histedit_progress(commit, hle, NULL);
11264 got_object_commit_close(commit);
11265 return error;
11268 static const struct got_error *
11269 check_local_changes(void *arg, unsigned char status,
11270 unsigned char staged_status, const char *path,
11271 struct got_object_id *blob_id, struct got_object_id *staged_blob_id,
11272 struct got_object_id *commit_id, int dirfd, const char *de_name)
11274 int *have_local_changes = arg;
11276 switch (status) {
11277 case GOT_STATUS_ADD:
11278 case GOT_STATUS_DELETE:
11279 case GOT_STATUS_MODIFY:
11280 case GOT_STATUS_CONFLICT:
11281 *have_local_changes = 1;
11282 return got_error(GOT_ERR_CANCELLED);
11283 default:
11284 break;
11287 switch (staged_status) {
11288 case GOT_STATUS_ADD:
11289 case GOT_STATUS_DELETE:
11290 case GOT_STATUS_MODIFY:
11291 *have_local_changes = 1;
11292 return got_error(GOT_ERR_CANCELLED);
11293 default:
11294 break;
11297 return NULL;
11300 static const struct got_error *
11301 cmd_histedit(int argc, char *argv[])
11303 const struct got_error *error = NULL;
11304 struct got_worktree *worktree = NULL;
11305 struct got_fileindex *fileindex = NULL;
11306 struct got_repository *repo = NULL;
11307 char *cwd = NULL, *committer = NULL, *gitconfig_path = NULL;
11308 struct got_reference *branch = NULL;
11309 struct got_reference *tmp_branch = NULL;
11310 struct got_object_id *resume_commit_id = NULL;
11311 struct got_object_id *base_commit_id = NULL;
11312 struct got_object_id *head_commit_id = NULL;
11313 struct got_commit_object *commit = NULL;
11314 int ch, rebase_in_progress = 0, merge_in_progress = 0;
11315 struct got_update_progress_arg upa;
11316 int edit_in_progress = 0, abort_edit = 0, continue_edit = 0;
11317 int edit_logmsg_only = 0, fold_only = 0, edit_only = 0;
11318 int list_backups = 0, delete_backups = 0;
11319 const char *edit_script_path = NULL;
11320 struct got_object_id_queue commits;
11321 struct got_pathlist_head merged_paths;
11322 const struct got_object_id_queue *parent_ids;
11323 struct got_object_qid *pid;
11324 struct got_histedit_list histedit_cmds;
11325 struct got_histedit_list_entry *hle;
11326 int *pack_fds = NULL;
11328 STAILQ_INIT(&commits);
11329 TAILQ_INIT(&histedit_cmds);
11330 TAILQ_INIT(&merged_paths);
11331 memset(&upa, 0, sizeof(upa));
11333 while ((ch = getopt(argc, argv, "aceF:flmX")) != -1) {
11334 switch (ch) {
11335 case 'a':
11336 abort_edit = 1;
11337 break;
11338 case 'c':
11339 continue_edit = 1;
11340 break;
11341 case 'e':
11342 edit_only = 1;
11343 break;
11344 case 'F':
11345 edit_script_path = optarg;
11346 break;
11347 case 'f':
11348 fold_only = 1;
11349 break;
11350 case 'l':
11351 list_backups = 1;
11352 break;
11353 case 'm':
11354 edit_logmsg_only = 1;
11355 break;
11356 case 'X':
11357 delete_backups = 1;
11358 break;
11359 default:
11360 usage_histedit();
11361 /* NOTREACHED */
11365 argc -= optind;
11366 argv += optind;
11368 #ifndef PROFILE
11369 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
11370 "unveil", NULL) == -1)
11371 err(1, "pledge");
11372 #endif
11373 if (abort_edit && continue_edit)
11374 option_conflict('a', 'c');
11375 if (edit_script_path && edit_logmsg_only)
11376 option_conflict('F', 'm');
11377 if (abort_edit && edit_logmsg_only)
11378 option_conflict('a', 'm');
11379 if (continue_edit && edit_logmsg_only)
11380 option_conflict('c', 'm');
11381 if (abort_edit && fold_only)
11382 option_conflict('a', 'f');
11383 if (continue_edit && fold_only)
11384 option_conflict('c', 'f');
11385 if (fold_only && edit_logmsg_only)
11386 option_conflict('f', 'm');
11387 if (edit_script_path && fold_only)
11388 option_conflict('F', 'f');
11389 if (abort_edit && edit_only)
11390 option_conflict('a', 'e');
11391 if (continue_edit && edit_only)
11392 option_conflict('c', 'e');
11393 if (edit_only && edit_logmsg_only)
11394 option_conflict('e', 'm');
11395 if (edit_script_path && edit_only)
11396 option_conflict('F', 'e');
11397 if (list_backups) {
11398 if (abort_edit)
11399 option_conflict('l', 'a');
11400 if (continue_edit)
11401 option_conflict('l', 'c');
11402 if (edit_script_path)
11403 option_conflict('l', 'F');
11404 if (edit_logmsg_only)
11405 option_conflict('l', 'm');
11406 if (fold_only)
11407 option_conflict('l', 'f');
11408 if (edit_only)
11409 option_conflict('l', 'e');
11410 if (delete_backups)
11411 option_conflict('l', 'X');
11412 if (argc != 0 && argc != 1)
11413 usage_histedit();
11414 } else if (delete_backups) {
11415 if (abort_edit)
11416 option_conflict('X', 'a');
11417 if (continue_edit)
11418 option_conflict('X', 'c');
11419 if (edit_script_path)
11420 option_conflict('X', 'F');
11421 if (edit_logmsg_only)
11422 option_conflict('X', 'm');
11423 if (fold_only)
11424 option_conflict('X', 'f');
11425 if (edit_only)
11426 option_conflict('X', 'e');
11427 if (list_backups)
11428 option_conflict('X', 'l');
11429 if (argc != 0 && argc != 1)
11430 usage_histedit();
11431 } else if (argc != 0)
11432 usage_histedit();
11435 * This command cannot apply unveil(2) in all cases because the
11436 * user may choose to run an editor to edit the histedit script
11437 * and to edit individual commit log messages.
11438 * unveil(2) traverses exec(2); if an editor is used we have to
11439 * apply unveil after edit script and log messages have been written.
11440 * XXX TODO: Make use of unveil(2) where possible.
11443 cwd = getcwd(NULL, 0);
11444 if (cwd == NULL) {
11445 error = got_error_from_errno("getcwd");
11446 goto done;
11449 error = got_repo_pack_fds_open(&pack_fds);
11450 if (error != NULL)
11451 goto done;
11453 error = got_worktree_open(&worktree, cwd);
11454 if (error) {
11455 if (list_backups || delete_backups) {
11456 if (error->code != GOT_ERR_NOT_WORKTREE)
11457 goto done;
11458 } else {
11459 if (error->code == GOT_ERR_NOT_WORKTREE)
11460 error = wrap_not_worktree_error(error,
11461 "histedit", cwd);
11462 goto done;
11466 if (list_backups || delete_backups) {
11467 error = got_repo_open(&repo,
11468 worktree ? got_worktree_get_repo_path(worktree) : cwd,
11469 NULL, pack_fds);
11470 if (error != NULL)
11471 goto done;
11472 error = apply_unveil(got_repo_get_path(repo), 0,
11473 worktree ? got_worktree_get_root_path(worktree) : NULL);
11474 if (error)
11475 goto done;
11476 error = process_backup_refs(
11477 GOT_WORKTREE_HISTEDIT_BACKUP_REF_PREFIX,
11478 argc == 1 ? argv[0] : NULL, delete_backups, repo);
11479 goto done; /* nothing else to do */
11482 error = get_gitconfig_path(&gitconfig_path);
11483 if (error)
11484 goto done;
11485 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
11486 gitconfig_path, pack_fds);
11487 if (error != NULL)
11488 goto done;
11490 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
11491 if (error)
11492 goto done;
11493 if (rebase_in_progress) {
11494 error = got_error(GOT_ERR_REBASING);
11495 goto done;
11498 error = got_worktree_merge_in_progress(&merge_in_progress, worktree,
11499 repo);
11500 if (error)
11501 goto done;
11502 if (merge_in_progress) {
11503 error = got_error(GOT_ERR_MERGE_BUSY);
11504 goto done;
11507 error = got_worktree_histedit_in_progress(&edit_in_progress, worktree);
11508 if (error)
11509 goto done;
11511 if (edit_in_progress && edit_logmsg_only) {
11512 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
11513 "histedit operation is in progress in this "
11514 "work tree and must be continued or aborted "
11515 "before the -m option can be used");
11516 goto done;
11518 if (edit_in_progress && fold_only) {
11519 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
11520 "histedit operation is in progress in this "
11521 "work tree and must be continued or aborted "
11522 "before the -f option can be used");
11523 goto done;
11525 if (edit_in_progress && edit_only) {
11526 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
11527 "histedit operation is in progress in this "
11528 "work tree and must be continued or aborted "
11529 "before the -e option can be used");
11530 goto done;
11533 if (edit_in_progress && abort_edit) {
11534 error = got_worktree_histedit_continue(&resume_commit_id,
11535 &tmp_branch, &branch, &base_commit_id, &fileindex,
11536 worktree, repo);
11537 if (error)
11538 goto done;
11539 printf("Switching work tree to %s\n",
11540 got_ref_get_symref_target(branch));
11541 error = got_worktree_histedit_abort(worktree, fileindex, repo,
11542 branch, base_commit_id, abort_progress, &upa);
11543 if (error)
11544 goto done;
11545 printf("Histedit of %s aborted\n",
11546 got_ref_get_symref_target(branch));
11547 print_merge_progress_stats(&upa);
11548 goto done; /* nothing else to do */
11549 } else if (abort_edit) {
11550 error = got_error(GOT_ERR_NOT_HISTEDIT);
11551 goto done;
11554 error = get_author(&committer, repo, worktree);
11555 if (error)
11556 goto done;
11558 if (continue_edit) {
11559 char *path;
11561 if (!edit_in_progress) {
11562 error = got_error(GOT_ERR_NOT_HISTEDIT);
11563 goto done;
11566 error = got_worktree_get_histedit_script_path(&path, worktree);
11567 if (error)
11568 goto done;
11570 error = histedit_load_list(&histedit_cmds, path, repo);
11571 free(path);
11572 if (error)
11573 goto done;
11575 error = got_worktree_histedit_continue(&resume_commit_id,
11576 &tmp_branch, &branch, &base_commit_id, &fileindex,
11577 worktree, repo);
11578 if (error)
11579 goto done;
11581 error = got_ref_resolve(&head_commit_id, repo, branch);
11582 if (error)
11583 goto done;
11585 error = got_object_open_as_commit(&commit, repo,
11586 head_commit_id);
11587 if (error)
11588 goto done;
11589 parent_ids = got_object_commit_get_parent_ids(commit);
11590 pid = STAILQ_FIRST(parent_ids);
11591 if (pid == NULL) {
11592 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
11593 goto done;
11595 error = collect_commits(&commits, head_commit_id, &pid->id,
11596 base_commit_id, got_worktree_get_path_prefix(worktree),
11597 GOT_ERR_HISTEDIT_PATH, repo);
11598 got_object_commit_close(commit);
11599 commit = NULL;
11600 if (error)
11601 goto done;
11602 } else {
11603 if (edit_in_progress) {
11604 error = got_error(GOT_ERR_HISTEDIT_BUSY);
11605 goto done;
11608 error = got_ref_open(&branch, repo,
11609 got_worktree_get_head_ref_name(worktree), 0);
11610 if (error != NULL)
11611 goto done;
11613 if (strncmp(got_ref_get_name(branch), "refs/heads/", 11) != 0) {
11614 error = got_error_msg(GOT_ERR_COMMIT_BRANCH,
11615 "will not edit commit history of a branch outside "
11616 "the \"refs/heads/\" reference namespace");
11617 goto done;
11620 error = got_ref_resolve(&head_commit_id, repo, branch);
11621 got_ref_close(branch);
11622 branch = NULL;
11623 if (error)
11624 goto done;
11626 error = got_object_open_as_commit(&commit, repo,
11627 head_commit_id);
11628 if (error)
11629 goto done;
11630 parent_ids = got_object_commit_get_parent_ids(commit);
11631 pid = STAILQ_FIRST(parent_ids);
11632 if (pid == NULL) {
11633 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
11634 goto done;
11636 error = collect_commits(&commits, head_commit_id, &pid->id,
11637 got_worktree_get_base_commit_id(worktree),
11638 got_worktree_get_path_prefix(worktree),
11639 GOT_ERR_HISTEDIT_PATH, repo);
11640 got_object_commit_close(commit);
11641 commit = NULL;
11642 if (error)
11643 goto done;
11645 if (STAILQ_EMPTY(&commits)) {
11646 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
11647 goto done;
11650 error = got_worktree_histedit_prepare(&tmp_branch, &branch,
11651 &base_commit_id, &fileindex, worktree, repo);
11652 if (error)
11653 goto done;
11655 if (edit_script_path) {
11656 error = histedit_load_list(&histedit_cmds,
11657 edit_script_path, repo);
11658 if (error) {
11659 got_worktree_histedit_abort(worktree, fileindex,
11660 repo, branch, base_commit_id,
11661 abort_progress, &upa);
11662 print_merge_progress_stats(&upa);
11663 goto done;
11665 } else {
11666 const char *branch_name;
11667 branch_name = got_ref_get_symref_target(branch);
11668 if (strncmp(branch_name, "refs/heads/", 11) == 0)
11669 branch_name += 11;
11670 error = histedit_edit_script(&histedit_cmds, &commits,
11671 branch_name, edit_logmsg_only, fold_only,
11672 edit_only, repo);
11673 if (error) {
11674 got_worktree_histedit_abort(worktree, fileindex,
11675 repo, branch, base_commit_id,
11676 abort_progress, &upa);
11677 print_merge_progress_stats(&upa);
11678 goto done;
11683 error = histedit_save_list(&histedit_cmds, worktree,
11684 repo);
11685 if (error) {
11686 got_worktree_histedit_abort(worktree, fileindex,
11687 repo, branch, base_commit_id,
11688 abort_progress, &upa);
11689 print_merge_progress_stats(&upa);
11690 goto done;
11695 error = histedit_check_script(&histedit_cmds, &commits, repo);
11696 if (error)
11697 goto done;
11699 TAILQ_FOREACH(hle, &histedit_cmds, entry) {
11700 if (resume_commit_id) {
11701 if (got_object_id_cmp(hle->commit_id,
11702 resume_commit_id) != 0)
11703 continue;
11705 resume_commit_id = NULL;
11706 if (hle->cmd->code == GOT_HISTEDIT_DROP ||
11707 hle->cmd->code == GOT_HISTEDIT_FOLD) {
11708 error = histedit_skip_commit(hle, worktree,
11709 repo);
11710 if (error)
11711 goto done;
11712 } else {
11713 struct got_pathlist_head paths;
11714 int have_changes = 0;
11716 TAILQ_INIT(&paths);
11717 error = got_pathlist_append(&paths, "", NULL);
11718 if (error)
11719 goto done;
11720 error = got_worktree_status(worktree, &paths,
11721 repo, 0, check_local_changes, &have_changes,
11722 check_cancelled, NULL);
11723 got_pathlist_free(&paths);
11724 if (error) {
11725 if (error->code != GOT_ERR_CANCELLED)
11726 goto done;
11727 if (sigint_received || sigpipe_received)
11728 goto done;
11730 if (have_changes) {
11731 error = histedit_commit(NULL, worktree,
11732 fileindex, tmp_branch, hle,
11733 committer, repo);
11734 if (error)
11735 goto done;
11736 } else {
11737 error = got_object_open_as_commit(
11738 &commit, repo, hle->commit_id);
11739 if (error)
11740 goto done;
11741 error = show_histedit_progress(commit,
11742 hle, NULL);
11743 got_object_commit_close(commit);
11744 commit = NULL;
11745 if (error)
11746 goto done;
11749 continue;
11752 if (hle->cmd->code == GOT_HISTEDIT_DROP) {
11753 error = histedit_skip_commit(hle, worktree, repo);
11754 if (error)
11755 goto done;
11756 continue;
11759 error = got_object_open_as_commit(&commit, repo,
11760 hle->commit_id);
11761 if (error)
11762 goto done;
11763 parent_ids = got_object_commit_get_parent_ids(commit);
11764 pid = STAILQ_FIRST(parent_ids);
11766 error = got_worktree_histedit_merge_files(&merged_paths,
11767 worktree, fileindex, &pid->id, hle->commit_id, repo,
11768 update_progress, &upa, check_cancelled, NULL);
11769 if (error)
11770 goto done;
11771 got_object_commit_close(commit);
11772 commit = NULL;
11774 print_merge_progress_stats(&upa);
11775 if (upa.conflicts > 0 || upa.missing > 0 ||
11776 upa.not_deleted > 0 || upa.unversioned > 0) {
11777 if (upa.conflicts > 0) {
11778 error = show_rebase_merge_conflict(
11779 hle->commit_id, repo);
11780 if (error)
11781 goto done;
11783 got_worktree_rebase_pathlist_free(&merged_paths);
11784 break;
11787 if (hle->cmd->code == GOT_HISTEDIT_EDIT) {
11788 char *id_str;
11789 error = got_object_id_str(&id_str, hle->commit_id);
11790 if (error)
11791 goto done;
11792 printf("Stopping histedit for amending commit %s\n",
11793 id_str);
11794 free(id_str);
11795 got_worktree_rebase_pathlist_free(&merged_paths);
11796 error = got_worktree_histedit_postpone(worktree,
11797 fileindex);
11798 goto done;
11801 if (hle->cmd->code == GOT_HISTEDIT_FOLD) {
11802 error = histedit_skip_commit(hle, worktree, repo);
11803 if (error)
11804 goto done;
11805 continue;
11808 error = histedit_commit(&merged_paths, worktree, fileindex,
11809 tmp_branch, hle, committer, repo);
11810 got_worktree_rebase_pathlist_free(&merged_paths);
11811 if (error)
11812 goto done;
11815 if (upa.conflicts > 0 || upa.missing > 0 ||
11816 upa.not_deleted > 0 || upa.unversioned > 0) {
11817 error = got_worktree_histedit_postpone(worktree, fileindex);
11818 if (error)
11819 goto done;
11820 if (upa.conflicts > 0 && upa.missing == 0 &&
11821 upa.not_deleted == 0 && upa.unversioned == 0) {
11822 error = got_error_msg(GOT_ERR_CONFLICTS,
11823 "conflicts must be resolved before histedit "
11824 "can continue");
11825 } else if (upa.conflicts > 0) {
11826 error = got_error_msg(GOT_ERR_CONFLICTS,
11827 "conflicts must be resolved before histedit "
11828 "can continue; changes destined for some "
11829 "files were not yet merged and should be "
11830 "merged manually if required before the "
11831 "histedit operation is continued");
11832 } else {
11833 error = got_error_msg(GOT_ERR_CONFLICTS,
11834 "changes destined for some files were not "
11835 "yet merged and should be merged manually "
11836 "if required before the histedit operation "
11837 "is continued");
11839 } else
11840 error = histedit_complete(worktree, fileindex, tmp_branch,
11841 branch, repo);
11842 done:
11843 free(cwd);
11844 free(committer);
11845 free(gitconfig_path);
11846 got_object_id_queue_free(&commits);
11847 histedit_free_list(&histedit_cmds);
11848 free(head_commit_id);
11849 free(base_commit_id);
11850 free(resume_commit_id);
11851 if (commit)
11852 got_object_commit_close(commit);
11853 if (branch)
11854 got_ref_close(branch);
11855 if (tmp_branch)
11856 got_ref_close(tmp_branch);
11857 if (worktree)
11858 got_worktree_close(worktree);
11859 if (repo) {
11860 const struct got_error *close_err = got_repo_close(repo);
11861 if (error == NULL)
11862 error = close_err;
11864 if (pack_fds) {
11865 const struct got_error *pack_err =
11866 got_repo_pack_fds_close(pack_fds);
11867 if (error == NULL)
11868 error = pack_err;
11870 return error;
11873 __dead static void
11874 usage_integrate(void)
11876 fprintf(stderr, "usage: %s integrate branch\n", getprogname());
11877 exit(1);
11880 static const struct got_error *
11881 cmd_integrate(int argc, char *argv[])
11883 const struct got_error *error = NULL;
11884 struct got_repository *repo = NULL;
11885 struct got_worktree *worktree = NULL;
11886 char *cwd = NULL, *refname = NULL, *base_refname = NULL;
11887 const char *branch_arg = NULL;
11888 struct got_reference *branch_ref = NULL, *base_branch_ref = NULL;
11889 struct got_fileindex *fileindex = NULL;
11890 struct got_object_id *commit_id = NULL, *base_commit_id = NULL;
11891 int ch;
11892 struct got_update_progress_arg upa;
11893 int *pack_fds = NULL;
11895 while ((ch = getopt(argc, argv, "")) != -1) {
11896 switch (ch) {
11897 default:
11898 usage_integrate();
11899 /* NOTREACHED */
11903 argc -= optind;
11904 argv += optind;
11906 if (argc != 1)
11907 usage_integrate();
11908 branch_arg = argv[0];
11909 #ifndef PROFILE
11910 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
11911 "unveil", NULL) == -1)
11912 err(1, "pledge");
11913 #endif
11914 cwd = getcwd(NULL, 0);
11915 if (cwd == NULL) {
11916 error = got_error_from_errno("getcwd");
11917 goto done;
11920 error = got_repo_pack_fds_open(&pack_fds);
11921 if (error != NULL)
11922 goto done;
11924 error = got_worktree_open(&worktree, cwd);
11925 if (error) {
11926 if (error->code == GOT_ERR_NOT_WORKTREE)
11927 error = wrap_not_worktree_error(error, "integrate",
11928 cwd);
11929 goto done;
11932 error = check_rebase_or_histedit_in_progress(worktree);
11933 if (error)
11934 goto done;
11936 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
11937 NULL, pack_fds);
11938 if (error != NULL)
11939 goto done;
11941 error = apply_unveil(got_repo_get_path(repo), 0,
11942 got_worktree_get_root_path(worktree));
11943 if (error)
11944 goto done;
11946 error = check_merge_in_progress(worktree, repo);
11947 if (error)
11948 goto done;
11950 if (asprintf(&refname, "refs/heads/%s", branch_arg) == -1) {
11951 error = got_error_from_errno("asprintf");
11952 goto done;
11955 error = got_worktree_integrate_prepare(&fileindex, &branch_ref,
11956 &base_branch_ref, worktree, refname, repo);
11957 if (error)
11958 goto done;
11960 refname = strdup(got_ref_get_name(branch_ref));
11961 if (refname == NULL) {
11962 error = got_error_from_errno("strdup");
11963 got_worktree_integrate_abort(worktree, fileindex, repo,
11964 branch_ref, base_branch_ref);
11965 goto done;
11967 base_refname = strdup(got_ref_get_name(base_branch_ref));
11968 if (base_refname == NULL) {
11969 error = got_error_from_errno("strdup");
11970 got_worktree_integrate_abort(worktree, fileindex, repo,
11971 branch_ref, base_branch_ref);
11972 goto done;
11974 if (strncmp(base_refname, "refs/heads/", 11) != 0) {
11975 error = got_error(GOT_ERR_INTEGRATE_BRANCH);
11976 got_worktree_integrate_abort(worktree, fileindex, repo,
11977 branch_ref, base_branch_ref);
11978 goto done;
11981 error = got_ref_resolve(&commit_id, repo, branch_ref);
11982 if (error)
11983 goto done;
11985 error = got_ref_resolve(&base_commit_id, repo, base_branch_ref);
11986 if (error)
11987 goto done;
11989 if (got_object_id_cmp(commit_id, base_commit_id) == 0) {
11990 error = got_error_msg(GOT_ERR_SAME_BRANCH,
11991 "specified branch has already been integrated");
11992 got_worktree_integrate_abort(worktree, fileindex, repo,
11993 branch_ref, base_branch_ref);
11994 goto done;
11997 error = check_linear_ancestry(commit_id, base_commit_id, 1, repo);
11998 if (error) {
11999 if (error->code == GOT_ERR_ANCESTRY)
12000 error = got_error(GOT_ERR_REBASE_REQUIRED);
12001 got_worktree_integrate_abort(worktree, fileindex, repo,
12002 branch_ref, base_branch_ref);
12003 goto done;
12006 memset(&upa, 0, sizeof(upa));
12007 error = got_worktree_integrate_continue(worktree, fileindex, repo,
12008 branch_ref, base_branch_ref, update_progress, &upa,
12009 check_cancelled, NULL);
12010 if (error)
12011 goto done;
12013 printf("Integrated %s into %s\n", refname, base_refname);
12014 print_update_progress_stats(&upa);
12015 done:
12016 if (repo) {
12017 const struct got_error *close_err = got_repo_close(repo);
12018 if (error == NULL)
12019 error = close_err;
12021 if (worktree)
12022 got_worktree_close(worktree);
12023 if (pack_fds) {
12024 const struct got_error *pack_err =
12025 got_repo_pack_fds_close(pack_fds);
12026 if (error == NULL)
12027 error = pack_err;
12029 free(cwd);
12030 free(base_commit_id);
12031 free(commit_id);
12032 free(refname);
12033 free(base_refname);
12034 return error;
12037 __dead static void
12038 usage_merge(void)
12040 fprintf(stderr, "usage: %s merge [-acn] [branch]\n", getprogname());
12041 exit(1);
12044 static const struct got_error *
12045 cmd_merge(int argc, char *argv[])
12047 const struct got_error *error = NULL;
12048 struct got_worktree *worktree = NULL;
12049 struct got_repository *repo = NULL;
12050 struct got_fileindex *fileindex = NULL;
12051 char *cwd = NULL, *id_str = NULL, *author = NULL;
12052 struct got_reference *branch = NULL, *wt_branch = NULL;
12053 struct got_object_id *branch_tip = NULL, *yca_id = NULL;
12054 struct got_object_id *wt_branch_tip = NULL;
12055 int ch, merge_in_progress = 0, abort_merge = 0, continue_merge = 0;
12056 int interrupt_merge = 0;
12057 struct got_update_progress_arg upa;
12058 struct got_object_id *merge_commit_id = NULL;
12059 char *branch_name = NULL;
12060 int *pack_fds = NULL;
12062 memset(&upa, 0, sizeof(upa));
12064 while ((ch = getopt(argc, argv, "acn")) != -1) {
12065 switch (ch) {
12066 case 'a':
12067 abort_merge = 1;
12068 break;
12069 case 'c':
12070 continue_merge = 1;
12071 break;
12072 case 'n':
12073 interrupt_merge = 1;
12074 break;
12075 default:
12076 usage_rebase();
12077 /* NOTREACHED */
12081 argc -= optind;
12082 argv += optind;
12084 #ifndef PROFILE
12085 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
12086 "unveil", NULL) == -1)
12087 err(1, "pledge");
12088 #endif
12090 if (abort_merge && continue_merge)
12091 option_conflict('a', 'c');
12092 if (abort_merge || continue_merge) {
12093 if (argc != 0)
12094 usage_merge();
12095 } else if (argc != 1)
12096 usage_merge();
12098 cwd = getcwd(NULL, 0);
12099 if (cwd == NULL) {
12100 error = got_error_from_errno("getcwd");
12101 goto done;
12104 error = got_repo_pack_fds_open(&pack_fds);
12105 if (error != NULL)
12106 goto done;
12108 error = got_worktree_open(&worktree, cwd);
12109 if (error) {
12110 if (error->code == GOT_ERR_NOT_WORKTREE)
12111 error = wrap_not_worktree_error(error,
12112 "merge", cwd);
12113 goto done;
12116 error = got_repo_open(&repo,
12117 worktree ? got_worktree_get_repo_path(worktree) : cwd, NULL,
12118 pack_fds);
12119 if (error != NULL)
12120 goto done;
12122 error = apply_unveil(got_repo_get_path(repo), 0,
12123 worktree ? got_worktree_get_root_path(worktree) : NULL);
12124 if (error)
12125 goto done;
12127 error = check_rebase_or_histedit_in_progress(worktree);
12128 if (error)
12129 goto done;
12131 error = got_worktree_merge_in_progress(&merge_in_progress, worktree,
12132 repo);
12133 if (error)
12134 goto done;
12136 if (abort_merge) {
12137 if (!merge_in_progress) {
12138 error = got_error(GOT_ERR_NOT_MERGING);
12139 goto done;
12141 error = got_worktree_merge_continue(&branch_name,
12142 &branch_tip, &fileindex, worktree, repo);
12143 if (error)
12144 goto done;
12145 error = got_worktree_merge_abort(worktree, fileindex, repo,
12146 abort_progress, &upa);
12147 if (error)
12148 goto done;
12149 printf("Merge of %s aborted\n", branch_name);
12150 goto done; /* nothing else to do */
12153 error = get_author(&author, repo, worktree);
12154 if (error)
12155 goto done;
12157 if (continue_merge) {
12158 if (!merge_in_progress) {
12159 error = got_error(GOT_ERR_NOT_MERGING);
12160 goto done;
12162 error = got_worktree_merge_continue(&branch_name,
12163 &branch_tip, &fileindex, worktree, repo);
12164 if (error)
12165 goto done;
12166 } else {
12167 error = got_ref_open(&branch, repo, argv[0], 0);
12168 if (error != NULL)
12169 goto done;
12170 branch_name = strdup(got_ref_get_name(branch));
12171 if (branch_name == NULL) {
12172 error = got_error_from_errno("strdup");
12173 goto done;
12175 error = got_ref_resolve(&branch_tip, repo, branch);
12176 if (error)
12177 goto done;
12180 error = got_ref_open(&wt_branch, repo,
12181 got_worktree_get_head_ref_name(worktree), 0);
12182 if (error)
12183 goto done;
12184 error = got_ref_resolve(&wt_branch_tip, repo, wt_branch);
12185 if (error)
12186 goto done;
12187 error = got_commit_graph_find_youngest_common_ancestor(&yca_id,
12188 wt_branch_tip, branch_tip, 0, repo,
12189 check_cancelled, NULL);
12190 if (error && error->code != GOT_ERR_ANCESTRY)
12191 goto done;
12193 if (!continue_merge) {
12194 error = check_path_prefix(wt_branch_tip, branch_tip,
12195 got_worktree_get_path_prefix(worktree),
12196 GOT_ERR_MERGE_PATH, repo);
12197 if (error)
12198 goto done;
12199 if (yca_id) {
12200 error = check_same_branch(wt_branch_tip, branch,
12201 yca_id, repo);
12202 if (error) {
12203 if (error->code != GOT_ERR_ANCESTRY)
12204 goto done;
12205 error = NULL;
12206 } else {
12207 static char msg[512];
12208 snprintf(msg, sizeof(msg),
12209 "cannot create a merge commit because "
12210 "%s is based on %s; %s can be integrated "
12211 "with 'got integrate' instead", branch_name,
12212 got_worktree_get_head_ref_name(worktree),
12213 branch_name);
12214 error = got_error_msg(GOT_ERR_SAME_BRANCH, msg);
12215 goto done;
12218 error = got_worktree_merge_prepare(&fileindex, worktree,
12219 branch, repo);
12220 if (error)
12221 goto done;
12223 error = got_worktree_merge_branch(worktree, fileindex,
12224 yca_id, branch_tip, repo, update_progress, &upa,
12225 check_cancelled, NULL);
12226 if (error)
12227 goto done;
12228 print_merge_progress_stats(&upa);
12229 if (!upa.did_something) {
12230 error = got_worktree_merge_abort(worktree, fileindex,
12231 repo, abort_progress, &upa);
12232 if (error)
12233 goto done;
12234 printf("Already up-to-date\n");
12235 goto done;
12239 if (interrupt_merge) {
12240 error = got_worktree_merge_postpone(worktree, fileindex);
12241 if (error)
12242 goto done;
12243 printf("Merge of %s interrupted on request\n", branch_name);
12244 } else if (upa.conflicts > 0 || upa.missing > 0 ||
12245 upa.not_deleted > 0 || upa.unversioned > 0) {
12246 error = got_worktree_merge_postpone(worktree, fileindex);
12247 if (error)
12248 goto done;
12249 if (upa.conflicts > 0 && upa.missing == 0 &&
12250 upa.not_deleted == 0 && upa.unversioned == 0) {
12251 error = got_error_msg(GOT_ERR_CONFLICTS,
12252 "conflicts must be resolved before merging "
12253 "can continue");
12254 } else if (upa.conflicts > 0) {
12255 error = got_error_msg(GOT_ERR_CONFLICTS,
12256 "conflicts must be resolved before merging "
12257 "can continue; changes destined for some "
12258 "files were not yet merged and "
12259 "should be merged manually if required before the "
12260 "merge operation is continued");
12261 } else {
12262 error = got_error_msg(GOT_ERR_CONFLICTS,
12263 "changes destined for some "
12264 "files were not yet merged and should be "
12265 "merged manually if required before the "
12266 "merge operation is continued");
12268 goto done;
12269 } else {
12270 error = got_worktree_merge_commit(&merge_commit_id, worktree,
12271 fileindex, author, NULL, 1, branch_tip, branch_name,
12272 repo, continue_merge ? print_status : NULL, NULL);
12273 if (error)
12274 goto done;
12275 error = got_worktree_merge_complete(worktree, fileindex, repo);
12276 if (error)
12277 goto done;
12278 error = got_object_id_str(&id_str, merge_commit_id);
12279 if (error)
12280 goto done;
12281 printf("Merged %s into %s: %s\n", branch_name,
12282 got_worktree_get_head_ref_name(worktree),
12283 id_str);
12286 done:
12287 free(id_str);
12288 free(merge_commit_id);
12289 free(author);
12290 free(branch_tip);
12291 free(branch_name);
12292 free(yca_id);
12293 if (branch)
12294 got_ref_close(branch);
12295 if (wt_branch)
12296 got_ref_close(wt_branch);
12297 if (worktree)
12298 got_worktree_close(worktree);
12299 if (repo) {
12300 const struct got_error *close_err = got_repo_close(repo);
12301 if (error == NULL)
12302 error = close_err;
12304 if (pack_fds) {
12305 const struct got_error *pack_err =
12306 got_repo_pack_fds_close(pack_fds);
12307 if (error == NULL)
12308 error = pack_err;
12310 return error;
12313 __dead static void
12314 usage_stage(void)
12316 fprintf(stderr, "usage: %s stage [-lpS] [-F response-script] "
12317 "[path ...]\n", getprogname());
12318 exit(1);
12321 static const struct got_error *
12322 print_stage(void *arg, unsigned char status, unsigned char staged_status,
12323 const char *path, struct got_object_id *blob_id,
12324 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
12325 int dirfd, const char *de_name)
12327 const struct got_error *err = NULL;
12328 char *id_str = NULL;
12330 if (staged_status != GOT_STATUS_ADD &&
12331 staged_status != GOT_STATUS_MODIFY &&
12332 staged_status != GOT_STATUS_DELETE)
12333 return NULL;
12335 if (staged_status == GOT_STATUS_ADD ||
12336 staged_status == GOT_STATUS_MODIFY)
12337 err = got_object_id_str(&id_str, staged_blob_id);
12338 else
12339 err = got_object_id_str(&id_str, blob_id);
12340 if (err)
12341 return err;
12343 printf("%s %c %s\n", id_str, staged_status, path);
12344 free(id_str);
12345 return NULL;
12348 static const struct got_error *
12349 cmd_stage(int argc, char *argv[])
12351 const struct got_error *error = NULL;
12352 struct got_repository *repo = NULL;
12353 struct got_worktree *worktree = NULL;
12354 char *cwd = NULL;
12355 struct got_pathlist_head paths;
12356 struct got_pathlist_entry *pe;
12357 int ch, list_stage = 0, pflag = 0, allow_bad_symlinks = 0;
12358 FILE *patch_script_file = NULL;
12359 const char *patch_script_path = NULL;
12360 struct choose_patch_arg cpa;
12361 int *pack_fds = NULL;
12363 TAILQ_INIT(&paths);
12365 while ((ch = getopt(argc, argv, "F:lpS")) != -1) {
12366 switch (ch) {
12367 case 'F':
12368 patch_script_path = optarg;
12369 break;
12370 case 'l':
12371 list_stage = 1;
12372 break;
12373 case 'p':
12374 pflag = 1;
12375 break;
12376 case 'S':
12377 allow_bad_symlinks = 1;
12378 break;
12379 default:
12380 usage_stage();
12381 /* NOTREACHED */
12385 argc -= optind;
12386 argv += optind;
12388 #ifndef PROFILE
12389 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
12390 "unveil", NULL) == -1)
12391 err(1, "pledge");
12392 #endif
12393 if (list_stage && (pflag || patch_script_path))
12394 errx(1, "-l option cannot be used with other options");
12395 if (patch_script_path && !pflag)
12396 errx(1, "-F option can only be used together with -p option");
12398 cwd = getcwd(NULL, 0);
12399 if (cwd == NULL) {
12400 error = got_error_from_errno("getcwd");
12401 goto done;
12404 error = got_repo_pack_fds_open(&pack_fds);
12405 if (error != NULL)
12406 goto done;
12408 error = got_worktree_open(&worktree, cwd);
12409 if (error) {
12410 if (error->code == GOT_ERR_NOT_WORKTREE)
12411 error = wrap_not_worktree_error(error, "stage", cwd);
12412 goto done;
12415 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
12416 NULL, pack_fds);
12417 if (error != NULL)
12418 goto done;
12420 if (patch_script_path) {
12421 patch_script_file = fopen(patch_script_path, "re");
12422 if (patch_script_file == NULL) {
12423 error = got_error_from_errno2("fopen",
12424 patch_script_path);
12425 goto done;
12428 error = apply_unveil(got_repo_get_path(repo), 0,
12429 got_worktree_get_root_path(worktree));
12430 if (error)
12431 goto done;
12433 error = check_merge_in_progress(worktree, repo);
12434 if (error)
12435 goto done;
12437 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
12438 if (error)
12439 goto done;
12441 if (list_stage)
12442 error = got_worktree_status(worktree, &paths, repo, 0,
12443 print_stage, NULL, check_cancelled, NULL);
12444 else {
12445 cpa.patch_script_file = patch_script_file;
12446 cpa.action = "stage";
12447 error = got_worktree_stage(worktree, &paths,
12448 pflag ? NULL : print_status, NULL,
12449 pflag ? choose_patch : NULL, &cpa,
12450 allow_bad_symlinks, repo);
12452 done:
12453 if (patch_script_file && fclose(patch_script_file) == EOF &&
12454 error == NULL)
12455 error = got_error_from_errno2("fclose", patch_script_path);
12456 if (repo) {
12457 const struct got_error *close_err = got_repo_close(repo);
12458 if (error == NULL)
12459 error = close_err;
12461 if (worktree)
12462 got_worktree_close(worktree);
12463 if (pack_fds) {
12464 const struct got_error *pack_err =
12465 got_repo_pack_fds_close(pack_fds);
12466 if (error == NULL)
12467 error = pack_err;
12469 TAILQ_FOREACH(pe, &paths, entry)
12470 free((char *)pe->path);
12471 got_pathlist_free(&paths);
12472 free(cwd);
12473 return error;
12476 __dead static void
12477 usage_unstage(void)
12479 fprintf(stderr, "usage: %s unstage [-p] [-F response-script] "
12480 "[path ...]\n", getprogname());
12481 exit(1);
12485 static const struct got_error *
12486 cmd_unstage(int argc, char *argv[])
12488 const struct got_error *error = NULL;
12489 struct got_repository *repo = NULL;
12490 struct got_worktree *worktree = NULL;
12491 char *cwd = NULL;
12492 struct got_pathlist_head paths;
12493 struct got_pathlist_entry *pe;
12494 int ch, pflag = 0;
12495 struct got_update_progress_arg upa;
12496 FILE *patch_script_file = NULL;
12497 const char *patch_script_path = NULL;
12498 struct choose_patch_arg cpa;
12499 int *pack_fds = NULL;
12501 TAILQ_INIT(&paths);
12503 while ((ch = getopt(argc, argv, "F:p")) != -1) {
12504 switch (ch) {
12505 case 'F':
12506 patch_script_path = optarg;
12507 break;
12508 case 'p':
12509 pflag = 1;
12510 break;
12511 default:
12512 usage_unstage();
12513 /* NOTREACHED */
12517 argc -= optind;
12518 argv += optind;
12520 #ifndef PROFILE
12521 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
12522 "unveil", NULL) == -1)
12523 err(1, "pledge");
12524 #endif
12525 if (patch_script_path && !pflag)
12526 errx(1, "-F option can only be used together with -p option");
12528 cwd = getcwd(NULL, 0);
12529 if (cwd == NULL) {
12530 error = got_error_from_errno("getcwd");
12531 goto done;
12534 error = got_repo_pack_fds_open(&pack_fds);
12535 if (error != NULL)
12536 goto done;
12538 error = got_worktree_open(&worktree, cwd);
12539 if (error) {
12540 if (error->code == GOT_ERR_NOT_WORKTREE)
12541 error = wrap_not_worktree_error(error, "unstage", cwd);
12542 goto done;
12545 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
12546 NULL, pack_fds);
12547 if (error != NULL)
12548 goto done;
12550 if (patch_script_path) {
12551 patch_script_file = fopen(patch_script_path, "re");
12552 if (patch_script_file == NULL) {
12553 error = got_error_from_errno2("fopen",
12554 patch_script_path);
12555 goto done;
12559 error = apply_unveil(got_repo_get_path(repo), 0,
12560 got_worktree_get_root_path(worktree));
12561 if (error)
12562 goto done;
12564 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
12565 if (error)
12566 goto done;
12568 cpa.patch_script_file = patch_script_file;
12569 cpa.action = "unstage";
12570 memset(&upa, 0, sizeof(upa));
12571 error = got_worktree_unstage(worktree, &paths, update_progress,
12572 &upa, pflag ? choose_patch : NULL, &cpa, repo);
12573 if (!error)
12574 print_merge_progress_stats(&upa);
12575 done:
12576 if (patch_script_file && fclose(patch_script_file) == EOF &&
12577 error == NULL)
12578 error = got_error_from_errno2("fclose", patch_script_path);
12579 if (repo) {
12580 const struct got_error *close_err = got_repo_close(repo);
12581 if (error == NULL)
12582 error = close_err;
12584 if (worktree)
12585 got_worktree_close(worktree);
12586 if (pack_fds) {
12587 const struct got_error *pack_err =
12588 got_repo_pack_fds_close(pack_fds);
12589 if (error == NULL)
12590 error = pack_err;
12592 TAILQ_FOREACH(pe, &paths, entry)
12593 free((char *)pe->path);
12594 got_pathlist_free(&paths);
12595 free(cwd);
12596 return error;
12599 __dead static void
12600 usage_cat(void)
12602 fprintf(stderr, "usage: %s cat [-P] [-c commit] [-r repository-path] "
12603 "arg ...\n", getprogname());
12604 exit(1);
12607 static const struct got_error *
12608 cat_blob(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
12610 const struct got_error *err;
12611 struct got_blob_object *blob;
12612 int fd = -1;
12614 fd = got_opentempfd();
12615 if (fd == -1)
12616 return got_error_from_errno("got_opentempfd");
12618 err = got_object_open_as_blob(&blob, repo, id, 8192, fd);
12619 if (err)
12620 goto done;
12622 err = got_object_blob_dump_to_file(NULL, NULL, NULL, outfile, blob);
12623 done:
12624 if (fd != -1 && close(fd) == -1 && err == NULL)
12625 err = got_error_from_errno("close");
12626 if (blob)
12627 got_object_blob_close(blob);
12628 return err;
12631 static const struct got_error *
12632 cat_tree(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
12634 const struct got_error *err;
12635 struct got_tree_object *tree;
12636 int nentries, i;
12638 err = got_object_open_as_tree(&tree, repo, id);
12639 if (err)
12640 return err;
12642 nentries = got_object_tree_get_nentries(tree);
12643 for (i = 0; i < nentries; i++) {
12644 struct got_tree_entry *te;
12645 char *id_str;
12646 if (sigint_received || sigpipe_received)
12647 break;
12648 te = got_object_tree_get_entry(tree, i);
12649 err = got_object_id_str(&id_str, got_tree_entry_get_id(te));
12650 if (err)
12651 break;
12652 fprintf(outfile, "%s %.7o %s\n", id_str,
12653 got_tree_entry_get_mode(te),
12654 got_tree_entry_get_name(te));
12655 free(id_str);
12658 got_object_tree_close(tree);
12659 return err;
12662 static const struct got_error *
12663 cat_commit(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
12665 const struct got_error *err;
12666 struct got_commit_object *commit;
12667 const struct got_object_id_queue *parent_ids;
12668 struct got_object_qid *pid;
12669 char *id_str = NULL;
12670 const char *logmsg = NULL;
12671 char gmtoff[6];
12673 err = got_object_open_as_commit(&commit, repo, id);
12674 if (err)
12675 return err;
12677 err = got_object_id_str(&id_str, got_object_commit_get_tree_id(commit));
12678 if (err)
12679 goto done;
12681 fprintf(outfile, "%s%s\n", GOT_COMMIT_LABEL_TREE, id_str);
12682 parent_ids = got_object_commit_get_parent_ids(commit);
12683 fprintf(outfile, "numparents %d\n",
12684 got_object_commit_get_nparents(commit));
12685 STAILQ_FOREACH(pid, parent_ids, entry) {
12686 char *pid_str;
12687 err = got_object_id_str(&pid_str, &pid->id);
12688 if (err)
12689 goto done;
12690 fprintf(outfile, "%s%s\n", GOT_COMMIT_LABEL_PARENT, pid_str);
12691 free(pid_str);
12693 got_date_format_gmtoff(gmtoff, sizeof(gmtoff),
12694 got_object_commit_get_author_gmtoff(commit));
12695 fprintf(outfile, "%s%s %lld %s\n", GOT_COMMIT_LABEL_AUTHOR,
12696 got_object_commit_get_author(commit),
12697 (long long)got_object_commit_get_author_time(commit),
12698 gmtoff);
12700 got_date_format_gmtoff(gmtoff, sizeof(gmtoff),
12701 got_object_commit_get_committer_gmtoff(commit));
12702 fprintf(outfile, "%s%s %lld %s\n", GOT_COMMIT_LABEL_COMMITTER,
12703 got_object_commit_get_committer(commit),
12704 (long long)got_object_commit_get_committer_time(commit),
12705 gmtoff);
12707 logmsg = got_object_commit_get_logmsg_raw(commit);
12708 fprintf(outfile, "messagelen %zd\n", strlen(logmsg));
12709 fprintf(outfile, "%s", logmsg);
12710 done:
12711 free(id_str);
12712 got_object_commit_close(commit);
12713 return err;
12716 static const struct got_error *
12717 cat_tag(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
12719 const struct got_error *err;
12720 struct got_tag_object *tag;
12721 char *id_str = NULL;
12722 const char *tagmsg = NULL;
12723 char gmtoff[6];
12725 err = got_object_open_as_tag(&tag, repo, id);
12726 if (err)
12727 return err;
12729 err = got_object_id_str(&id_str, got_object_tag_get_object_id(tag));
12730 if (err)
12731 goto done;
12733 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_OBJECT, id_str);
12735 switch (got_object_tag_get_object_type(tag)) {
12736 case GOT_OBJ_TYPE_BLOB:
12737 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
12738 GOT_OBJ_LABEL_BLOB);
12739 break;
12740 case GOT_OBJ_TYPE_TREE:
12741 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
12742 GOT_OBJ_LABEL_TREE);
12743 break;
12744 case GOT_OBJ_TYPE_COMMIT:
12745 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
12746 GOT_OBJ_LABEL_COMMIT);
12747 break;
12748 case GOT_OBJ_TYPE_TAG:
12749 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
12750 GOT_OBJ_LABEL_TAG);
12751 break;
12752 default:
12753 break;
12756 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TAG,
12757 got_object_tag_get_name(tag));
12759 got_date_format_gmtoff(gmtoff, sizeof(gmtoff),
12760 got_object_tag_get_tagger_gmtoff(tag));
12761 fprintf(outfile, "%s%s %lld %s\n", GOT_TAG_LABEL_TAGGER,
12762 got_object_tag_get_tagger(tag),
12763 (long long)got_object_tag_get_tagger_time(tag),
12764 gmtoff);
12766 tagmsg = got_object_tag_get_message(tag);
12767 fprintf(outfile, "messagelen %zd\n", strlen(tagmsg));
12768 fprintf(outfile, "%s", tagmsg);
12769 done:
12770 free(id_str);
12771 got_object_tag_close(tag);
12772 return err;
12775 static const struct got_error *
12776 cmd_cat(int argc, char *argv[])
12778 const struct got_error *error;
12779 struct got_repository *repo = NULL;
12780 struct got_worktree *worktree = NULL;
12781 char *cwd = NULL, *repo_path = NULL, *label = NULL;
12782 const char *commit_id_str = NULL;
12783 struct got_object_id *id = NULL, *commit_id = NULL;
12784 struct got_commit_object *commit = NULL;
12785 int ch, obj_type, i, force_path = 0;
12786 struct got_reflist_head refs;
12787 int *pack_fds = NULL;
12789 TAILQ_INIT(&refs);
12791 #ifndef PROFILE
12792 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
12793 NULL) == -1)
12794 err(1, "pledge");
12795 #endif
12797 while ((ch = getopt(argc, argv, "c:Pr:")) != -1) {
12798 switch (ch) {
12799 case 'c':
12800 commit_id_str = optarg;
12801 break;
12802 case 'P':
12803 force_path = 1;
12804 break;
12805 case 'r':
12806 repo_path = realpath(optarg, NULL);
12807 if (repo_path == NULL)
12808 return got_error_from_errno2("realpath",
12809 optarg);
12810 got_path_strip_trailing_slashes(repo_path);
12811 break;
12812 default:
12813 usage_cat();
12814 /* NOTREACHED */
12818 argc -= optind;
12819 argv += optind;
12821 cwd = getcwd(NULL, 0);
12822 if (cwd == NULL) {
12823 error = got_error_from_errno("getcwd");
12824 goto done;
12827 error = got_repo_pack_fds_open(&pack_fds);
12828 if (error != NULL)
12829 goto done;
12831 if (repo_path == NULL) {
12832 error = got_worktree_open(&worktree, cwd);
12833 if (error && error->code != GOT_ERR_NOT_WORKTREE)
12834 goto done;
12835 if (worktree) {
12836 repo_path = strdup(
12837 got_worktree_get_repo_path(worktree));
12838 if (repo_path == NULL) {
12839 error = got_error_from_errno("strdup");
12840 goto done;
12843 /* Release work tree lock. */
12844 got_worktree_close(worktree);
12845 worktree = NULL;
12849 if (repo_path == NULL) {
12850 repo_path = strdup(cwd);
12851 if (repo_path == NULL)
12852 return got_error_from_errno("strdup");
12855 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
12856 free(repo_path);
12857 if (error != NULL)
12858 goto done;
12860 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
12861 if (error)
12862 goto done;
12864 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
12865 if (error)
12866 goto done;
12868 if (commit_id_str == NULL)
12869 commit_id_str = GOT_REF_HEAD;
12870 error = got_repo_match_object_id(&commit_id, NULL,
12871 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
12872 if (error)
12873 goto done;
12875 error = got_object_open_as_commit(&commit, repo, commit_id);
12876 if (error)
12877 goto done;
12879 for (i = 0; i < argc; i++) {
12880 if (force_path) {
12881 error = got_object_id_by_path(&id, repo, commit,
12882 argv[i]);
12883 if (error)
12884 break;
12885 } else {
12886 error = got_repo_match_object_id(&id, &label, argv[i],
12887 GOT_OBJ_TYPE_ANY, NULL /* do not resolve tags */,
12888 repo);
12889 if (error) {
12890 if (error->code != GOT_ERR_BAD_OBJ_ID_STR &&
12891 error->code != GOT_ERR_NOT_REF)
12892 break;
12893 error = got_object_id_by_path(&id, repo,
12894 commit, argv[i]);
12895 if (error)
12896 break;
12900 error = got_object_get_type(&obj_type, repo, id);
12901 if (error)
12902 break;
12904 switch (obj_type) {
12905 case GOT_OBJ_TYPE_BLOB:
12906 error = cat_blob(id, repo, stdout);
12907 break;
12908 case GOT_OBJ_TYPE_TREE:
12909 error = cat_tree(id, repo, stdout);
12910 break;
12911 case GOT_OBJ_TYPE_COMMIT:
12912 error = cat_commit(id, repo, stdout);
12913 break;
12914 case GOT_OBJ_TYPE_TAG:
12915 error = cat_tag(id, repo, stdout);
12916 break;
12917 default:
12918 error = got_error(GOT_ERR_OBJ_TYPE);
12919 break;
12921 if (error)
12922 break;
12923 free(label);
12924 label = NULL;
12925 free(id);
12926 id = NULL;
12928 done:
12929 free(label);
12930 free(id);
12931 free(commit_id);
12932 if (commit)
12933 got_object_commit_close(commit);
12934 if (worktree)
12935 got_worktree_close(worktree);
12936 if (repo) {
12937 const struct got_error *close_err = got_repo_close(repo);
12938 if (error == NULL)
12939 error = close_err;
12941 if (pack_fds) {
12942 const struct got_error *pack_err =
12943 got_repo_pack_fds_close(pack_fds);
12944 if (error == NULL)
12945 error = pack_err;
12948 got_ref_list_free(&refs);
12949 return error;
12952 __dead static void
12953 usage_info(void)
12955 fprintf(stderr, "usage: %s info [path ...]\n",
12956 getprogname());
12957 exit(1);
12960 static const struct got_error *
12961 print_path_info(void *arg, const char *path, mode_t mode, time_t mtime,
12962 struct got_object_id *blob_id, struct got_object_id *staged_blob_id,
12963 struct got_object_id *commit_id)
12965 const struct got_error *err = NULL;
12966 char *id_str = NULL;
12967 char datebuf[128];
12968 struct tm mytm, *tm;
12969 struct got_pathlist_head *paths = arg;
12970 struct got_pathlist_entry *pe;
12973 * Clear error indication from any of the path arguments which
12974 * would cause this file index entry to be displayed.
12976 TAILQ_FOREACH(pe, paths, entry) {
12977 if (got_path_cmp(path, pe->path, strlen(path),
12978 pe->path_len) == 0 ||
12979 got_path_is_child(path, pe->path, pe->path_len))
12980 pe->data = NULL; /* no error */
12983 printf(GOT_COMMIT_SEP_STR);
12984 if (S_ISLNK(mode))
12985 printf("symlink: %s\n", path);
12986 else if (S_ISREG(mode)) {
12987 printf("file: %s\n", path);
12988 printf("mode: %o\n", mode & (S_IRWXU | S_IRWXG | S_IRWXO));
12989 } else if (S_ISDIR(mode))
12990 printf("directory: %s\n", path);
12991 else
12992 printf("something: %s\n", path);
12994 tm = localtime_r(&mtime, &mytm);
12995 if (tm == NULL)
12996 return NULL;
12997 if (strftime(datebuf, sizeof(datebuf), "%c %Z", tm) == 0)
12998 return got_error(GOT_ERR_NO_SPACE);
12999 printf("timestamp: %s\n", datebuf);
13001 if (blob_id) {
13002 err = got_object_id_str(&id_str, blob_id);
13003 if (err)
13004 return err;
13005 printf("based on blob: %s\n", id_str);
13006 free(id_str);
13009 if (staged_blob_id) {
13010 err = got_object_id_str(&id_str, staged_blob_id);
13011 if (err)
13012 return err;
13013 printf("based on staged blob: %s\n", id_str);
13014 free(id_str);
13017 if (commit_id) {
13018 err = got_object_id_str(&id_str, commit_id);
13019 if (err)
13020 return err;
13021 printf("based on commit: %s\n", id_str);
13022 free(id_str);
13025 return NULL;
13028 static const struct got_error *
13029 cmd_info(int argc, char *argv[])
13031 const struct got_error *error = NULL;
13032 struct got_worktree *worktree = NULL;
13033 char *cwd = NULL, *id_str = NULL;
13034 struct got_pathlist_head paths;
13035 struct got_pathlist_entry *pe;
13036 char *uuidstr = NULL;
13037 int ch, show_files = 0;
13039 TAILQ_INIT(&paths);
13041 while ((ch = getopt(argc, argv, "")) != -1) {
13042 switch (ch) {
13043 default:
13044 usage_info();
13045 /* NOTREACHED */
13049 argc -= optind;
13050 argv += optind;
13052 #ifndef PROFILE
13053 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
13054 NULL) == -1)
13055 err(1, "pledge");
13056 #endif
13057 cwd = getcwd(NULL, 0);
13058 if (cwd == NULL) {
13059 error = got_error_from_errno("getcwd");
13060 goto done;
13063 error = got_worktree_open(&worktree, cwd);
13064 if (error) {
13065 if (error->code == GOT_ERR_NOT_WORKTREE)
13066 error = wrap_not_worktree_error(error, "info", cwd);
13067 goto done;
13070 #ifndef PROFILE
13071 /* Remove "wpath cpath proc exec sendfd" promises. */
13072 if (pledge("stdio rpath flock unveil", NULL) == -1)
13073 err(1, "pledge");
13074 #endif
13075 error = apply_unveil(NULL, 0, got_worktree_get_root_path(worktree));
13076 if (error)
13077 goto done;
13079 if (argc >= 1) {
13080 error = get_worktree_paths_from_argv(&paths, argc, argv,
13081 worktree);
13082 if (error)
13083 goto done;
13084 show_files = 1;
13087 error = got_object_id_str(&id_str,
13088 got_worktree_get_base_commit_id(worktree));
13089 if (error)
13090 goto done;
13092 error = got_worktree_get_uuid(&uuidstr, worktree);
13093 if (error)
13094 goto done;
13096 printf("work tree: %s\n", got_worktree_get_root_path(worktree));
13097 printf("work tree base commit: %s\n", id_str);
13098 printf("work tree path prefix: %s\n",
13099 got_worktree_get_path_prefix(worktree));
13100 printf("work tree branch reference: %s\n",
13101 got_worktree_get_head_ref_name(worktree));
13102 printf("work tree UUID: %s\n", uuidstr);
13103 printf("repository: %s\n", got_worktree_get_repo_path(worktree));
13105 if (show_files) {
13106 struct got_pathlist_entry *pe;
13107 TAILQ_FOREACH(pe, &paths, entry) {
13108 if (pe->path_len == 0)
13109 continue;
13111 * Assume this path will fail. This will be corrected
13112 * in print_path_info() in case the path does suceeed.
13114 pe->data = (void *)got_error(GOT_ERR_BAD_PATH);
13116 error = got_worktree_path_info(worktree, &paths,
13117 print_path_info, &paths, check_cancelled, NULL);
13118 if (error)
13119 goto done;
13120 TAILQ_FOREACH(pe, &paths, entry) {
13121 if (pe->data != NULL) {
13122 const struct got_error *perr;
13124 perr = pe->data;
13125 error = got_error_fmt(perr->code, "%s",
13126 pe->path);
13127 break;
13131 done:
13132 if (worktree)
13133 got_worktree_close(worktree);
13134 TAILQ_FOREACH(pe, &paths, entry)
13135 free((char *)pe->path);
13136 got_pathlist_free(&paths);
13137 free(cwd);
13138 free(id_str);
13139 free(uuidstr);
13140 return error;