Blob


1 /*
2 * Copyright (c) 2017 Martin Pieuchot <mpi@openbsd.org>
3 * Copyright (c) 2018, 2019, 2020 Stefan Sperling <stsp@openbsd.org>
4 * Copyright (c) 2020 Ori Bernstein <ori@openbsd.org>
5 *
6 * Permission to use, copy, modify, and distribute this software for any
7 * purpose with or without fee is hereby granted, provided that the above
8 * copyright notice and this permission notice appear in all copies.
9 *
10 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
11 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
12 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
13 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
14 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
15 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
16 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
17 */
19 #include <sys/queue.h>
20 #include <sys/time.h>
21 #include <sys/types.h>
22 #include <sys/stat.h>
23 #include <sys/wait.h>
25 #include <err.h>
26 #include <errno.h>
27 #include <fcntl.h>
28 #include <limits.h>
29 #include <locale.h>
30 #include <ctype.h>
31 #include <sha1.h>
32 #include <signal.h>
33 #include <stdio.h>
34 #include <stdlib.h>
35 #include <string.h>
36 #include <unistd.h>
37 #include <libgen.h>
38 #include <time.h>
39 #include <paths.h>
40 #include <regex.h>
41 #include <getopt.h>
42 #include <util.h>
44 #include "got_version.h"
45 #include "got_error.h"
46 #include "got_object.h"
47 #include "got_reference.h"
48 #include "got_repository.h"
49 #include "got_path.h"
50 #include "got_cancel.h"
51 #include "got_worktree.h"
52 #include "got_diff.h"
53 #include "got_commit_graph.h"
54 #include "got_fetch.h"
55 #include "got_send.h"
56 #include "got_blame.h"
57 #include "got_privsep.h"
58 #include "got_opentemp.h"
59 #include "got_gotconfig.h"
60 #include "got_dial.h"
61 #include "got_patch.h"
62 #include "got_sigs.h"
63 #include "got_date.h"
65 #ifndef nitems
66 #define nitems(_a) (sizeof((_a)) / sizeof((_a)[0]))
67 #endif
69 static volatile sig_atomic_t sigint_received;
70 static volatile sig_atomic_t sigpipe_received;
72 static void
73 catch_sigint(int signo)
74 {
75 sigint_received = 1;
76 }
78 static void
79 catch_sigpipe(int signo)
80 {
81 sigpipe_received = 1;
82 }
85 struct got_cmd {
86 const char *cmd_name;
87 const struct got_error *(*cmd_main)(int, char *[]);
88 void (*cmd_usage)(void);
89 const char *cmd_alias;
90 };
92 __dead static void usage(int, int);
93 __dead static void usage_import(void);
94 __dead static void usage_clone(void);
95 __dead static void usage_fetch(void);
96 __dead static void usage_checkout(void);
97 __dead static void usage_update(void);
98 __dead static void usage_log(void);
99 __dead static void usage_diff(void);
100 __dead static void usage_blame(void);
101 __dead static void usage_tree(void);
102 __dead static void usage_status(void);
103 __dead static void usage_ref(void);
104 __dead static void usage_branch(void);
105 __dead static void usage_tag(void);
106 __dead static void usage_add(void);
107 __dead static void usage_remove(void);
108 __dead static void usage_patch(void);
109 __dead static void usage_revert(void);
110 __dead static void usage_commit(void);
111 __dead static void usage_send(void);
112 __dead static void usage_cherrypick(void);
113 __dead static void usage_backout(void);
114 __dead static void usage_rebase(void);
115 __dead static void usage_histedit(void);
116 __dead static void usage_integrate(void);
117 __dead static void usage_merge(void);
118 __dead static void usage_stage(void);
119 __dead static void usage_unstage(void);
120 __dead static void usage_cat(void);
121 __dead static void usage_info(void);
123 static const struct got_error* cmd_import(int, char *[]);
124 static const struct got_error* cmd_clone(int, char *[]);
125 static const struct got_error* cmd_fetch(int, char *[]);
126 static const struct got_error* cmd_checkout(int, char *[]);
127 static const struct got_error* cmd_update(int, char *[]);
128 static const struct got_error* cmd_log(int, char *[]);
129 static const struct got_error* cmd_diff(int, char *[]);
130 static const struct got_error* cmd_blame(int, char *[]);
131 static const struct got_error* cmd_tree(int, char *[]);
132 static const struct got_error* cmd_status(int, char *[]);
133 static const struct got_error* cmd_ref(int, char *[]);
134 static const struct got_error* cmd_branch(int, char *[]);
135 static const struct got_error* cmd_tag(int, char *[]);
136 static const struct got_error* cmd_add(int, char *[]);
137 static const struct got_error* cmd_remove(int, char *[]);
138 static const struct got_error* cmd_patch(int, char *[]);
139 static const struct got_error* cmd_revert(int, char *[]);
140 static const struct got_error* cmd_commit(int, char *[]);
141 static const struct got_error* cmd_send(int, char *[]);
142 static const struct got_error* cmd_cherrypick(int, char *[]);
143 static const struct got_error* cmd_backout(int, char *[]);
144 static const struct got_error* cmd_rebase(int, char *[]);
145 static const struct got_error* cmd_histedit(int, char *[]);
146 static const struct got_error* cmd_integrate(int, char *[]);
147 static const struct got_error* cmd_merge(int, char *[]);
148 static const struct got_error* cmd_stage(int, char *[]);
149 static const struct got_error* cmd_unstage(int, char *[]);
150 static const struct got_error* cmd_cat(int, char *[]);
151 static const struct got_error* cmd_info(int, char *[]);
153 static const struct got_cmd got_commands[] = {
154 { "import", cmd_import, usage_import, "im" },
155 { "clone", cmd_clone, usage_clone, "cl" },
156 { "fetch", cmd_fetch, usage_fetch, "fe" },
157 { "checkout", cmd_checkout, usage_checkout, "co" },
158 { "update", cmd_update, usage_update, "up" },
159 { "log", cmd_log, usage_log, "" },
160 { "diff", cmd_diff, usage_diff, "di" },
161 { "blame", cmd_blame, usage_blame, "bl" },
162 { "tree", cmd_tree, usage_tree, "tr" },
163 { "status", cmd_status, usage_status, "st" },
164 { "ref", cmd_ref, usage_ref, "" },
165 { "branch", cmd_branch, usage_branch, "br" },
166 { "tag", cmd_tag, usage_tag, "" },
167 { "add", cmd_add, usage_add, "" },
168 { "remove", cmd_remove, usage_remove, "rm" },
169 { "patch", cmd_patch, usage_patch, "pa" },
170 { "revert", cmd_revert, usage_revert, "rv" },
171 { "commit", cmd_commit, usage_commit, "ci" },
172 { "send", cmd_send, usage_send, "se" },
173 { "cherrypick", cmd_cherrypick, usage_cherrypick, "cy" },
174 { "backout", cmd_backout, usage_backout, "bo" },
175 { "rebase", cmd_rebase, usage_rebase, "rb" },
176 { "histedit", cmd_histedit, usage_histedit, "he" },
177 { "integrate", cmd_integrate, usage_integrate,"ig" },
178 { "merge", cmd_merge, usage_merge, "mg" },
179 { "stage", cmd_stage, usage_stage, "sg" },
180 { "unstage", cmd_unstage, usage_unstage, "ug" },
181 { "cat", cmd_cat, usage_cat, "" },
182 { "info", cmd_info, usage_info, "" },
183 };
185 static void
186 list_commands(FILE *fp)
188 size_t i;
190 fprintf(fp, "commands:");
191 for (i = 0; i < nitems(got_commands); i++) {
192 const struct got_cmd *cmd = &got_commands[i];
193 fprintf(fp, " %s", cmd->cmd_name);
195 fputc('\n', fp);
198 __dead static void
199 option_conflict(char a, char b)
201 errx(1, "-%c and -%c options are mutually exclusive", a, b);
204 int
205 main(int argc, char *argv[])
207 const struct got_cmd *cmd;
208 size_t i;
209 int ch;
210 int hflag = 0, Vflag = 0;
211 static const struct option longopts[] = {
212 { "version", no_argument, NULL, 'V' },
213 { NULL, 0, NULL, 0 }
214 };
216 setlocale(LC_CTYPE, "");
218 while ((ch = getopt_long(argc, argv, "+hV", longopts, NULL)) != -1) {
219 switch (ch) {
220 case 'h':
221 hflag = 1;
222 break;
223 case 'V':
224 Vflag = 1;
225 break;
226 default:
227 usage(hflag, 1);
228 /* NOTREACHED */
232 argc -= optind;
233 argv += optind;
234 optind = 1;
235 optreset = 1;
237 if (Vflag) {
238 got_version_print_str();
239 return 0;
242 if (argc <= 0)
243 usage(hflag, hflag ? 0 : 1);
245 signal(SIGINT, catch_sigint);
246 signal(SIGPIPE, catch_sigpipe);
248 for (i = 0; i < nitems(got_commands); i++) {
249 const struct got_error *error;
251 cmd = &got_commands[i];
253 if (strcmp(cmd->cmd_name, argv[0]) != 0 &&
254 strcmp(cmd->cmd_alias, argv[0]) != 0)
255 continue;
257 if (hflag)
258 cmd->cmd_usage();
260 error = cmd->cmd_main(argc, argv);
261 if (error && error->code != GOT_ERR_CANCELLED &&
262 error->code != GOT_ERR_PRIVSEP_EXIT &&
263 !(sigpipe_received &&
264 error->code == GOT_ERR_ERRNO && errno == EPIPE) &&
265 !(sigint_received &&
266 error->code == GOT_ERR_ERRNO && errno == EINTR)) {
267 fprintf(stderr, "%s: %s\n", getprogname(), error->msg);
268 return 1;
271 return 0;
274 fprintf(stderr, "%s: unknown command '%s'\n", getprogname(), argv[0]);
275 list_commands(stderr);
276 return 1;
279 __dead static void
280 usage(int hflag, int status)
282 FILE *fp = (status == 0) ? stdout : stderr;
284 fprintf(fp, "usage: %s [-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");
420 /*
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.
424 */
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;
555 /*
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.
561 */
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);
591 /*
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)
599 */
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);
655 /*
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
660 */
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);
690 /*
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
695 */
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);
725 /*
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
730 */
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;
845 /*
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.
849 */
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);
886 /*
887 * unveil(2) traverses exec(2); if an editor is used we have
888 * to apply unveil after the log message has been written.
889 */
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;
1885 if (!fpa.configs_created && pe != NULL) {
1886 error = create_config_files(fpa.config_info.proto,
1887 fpa.config_info.host, fpa.config_info.port,
1888 fpa.config_info.remote_repo_path,
1889 fpa.config_info.git_url,
1890 fpa.config_info.fetch_all_branches,
1891 fpa.config_info.mirror_references,
1892 fpa.config_info.symrefs,
1893 fpa.config_info.wanted_branches,
1894 fpa.config_info.wanted_refs, fpa.repo);
1895 if (error)
1896 goto done;
1900 if (verbosity >= 0)
1901 printf("Created %s repository '%s'\n",
1902 mirror_references ? "mirrored" : "cloned", repo_path);
1903 done:
1904 if (pack_fds) {
1905 const struct got_error *pack_err =
1906 got_repo_pack_fds_close(pack_fds);
1907 if (error == NULL)
1908 error = pack_err;
1910 if (fetchpid > 0) {
1911 if (kill(fetchpid, SIGTERM) == -1)
1912 error = got_error_from_errno("kill");
1913 if (waitpid(fetchpid, &fetchstatus, 0) == -1 && error == NULL)
1914 error = got_error_from_errno("waitpid");
1916 if (fetchfd != -1 && close(fetchfd) == -1 && error == NULL)
1917 error = got_error_from_errno("close");
1918 if (repo) {
1919 const struct got_error *close_err = got_repo_close(repo);
1920 if (error == NULL)
1921 error = close_err;
1923 TAILQ_FOREACH(pe, &refs, entry) {
1924 free((void *)pe->path);
1925 free(pe->data);
1927 got_pathlist_free(&refs);
1928 TAILQ_FOREACH(pe, &symrefs, entry) {
1929 free((void *)pe->path);
1930 free(pe->data);
1932 got_pathlist_free(&symrefs);
1933 got_pathlist_free(&wanted_branches);
1934 got_pathlist_free(&wanted_refs);
1935 free(pack_hash);
1936 free(proto);
1937 free(host);
1938 free(port);
1939 free(server_path);
1940 free(repo_name);
1941 free(default_destdir);
1942 free(git_url);
1943 return error;
1946 static const struct got_error *
1947 update_ref(struct got_reference *ref, struct got_object_id *new_id,
1948 int replace_tags, int verbosity, struct got_repository *repo)
1950 const struct got_error *err = NULL;
1951 char *new_id_str = NULL;
1952 struct got_object_id *old_id = NULL;
1954 err = got_object_id_str(&new_id_str, new_id);
1955 if (err)
1956 goto done;
1958 if (!replace_tags &&
1959 strncmp(got_ref_get_name(ref), "refs/tags/", 10) == 0) {
1960 err = got_ref_resolve(&old_id, repo, ref);
1961 if (err)
1962 goto done;
1963 if (got_object_id_cmp(old_id, new_id) == 0)
1964 goto done;
1965 if (verbosity >= 0) {
1966 printf("Rejecting update of existing tag %s: %s\n",
1967 got_ref_get_name(ref), new_id_str);
1969 goto done;
1972 if (got_ref_is_symbolic(ref)) {
1973 if (verbosity >= 0) {
1974 printf("Replacing reference %s: %s\n",
1975 got_ref_get_name(ref),
1976 got_ref_get_symref_target(ref));
1978 err = got_ref_change_symref_to_ref(ref, new_id);
1979 if (err)
1980 goto done;
1981 err = got_ref_write(ref, repo);
1982 if (err)
1983 goto done;
1984 } else {
1985 err = got_ref_resolve(&old_id, repo, ref);
1986 if (err)
1987 goto done;
1988 if (got_object_id_cmp(old_id, new_id) == 0)
1989 goto done;
1991 err = got_ref_change_ref(ref, new_id);
1992 if (err)
1993 goto done;
1994 err = got_ref_write(ref, repo);
1995 if (err)
1996 goto done;
1999 if (verbosity >= 0)
2000 printf("Updated %s: %s\n", got_ref_get_name(ref),
2001 new_id_str);
2002 done:
2003 free(old_id);
2004 free(new_id_str);
2005 return err;
2008 static const struct got_error *
2009 update_symref(const char *refname, struct got_reference *target_ref,
2010 int verbosity, struct got_repository *repo)
2012 const struct got_error *err = NULL, *unlock_err;
2013 struct got_reference *symref;
2014 int symref_is_locked = 0;
2016 err = got_ref_open(&symref, repo, refname, 1);
2017 if (err) {
2018 if (err->code != GOT_ERR_NOT_REF)
2019 return err;
2020 err = got_ref_alloc_symref(&symref, refname, target_ref);
2021 if (err)
2022 goto done;
2024 err = got_ref_write(symref, repo);
2025 if (err)
2026 goto done;
2028 if (verbosity >= 0)
2029 printf("Created reference %s: %s\n",
2030 got_ref_get_name(symref),
2031 got_ref_get_symref_target(symref));
2032 } else {
2033 symref_is_locked = 1;
2035 if (strcmp(got_ref_get_symref_target(symref),
2036 got_ref_get_name(target_ref)) == 0)
2037 goto done;
2039 err = got_ref_change_symref(symref,
2040 got_ref_get_name(target_ref));
2041 if (err)
2042 goto done;
2044 err = got_ref_write(symref, repo);
2045 if (err)
2046 goto done;
2048 if (verbosity >= 0)
2049 printf("Updated %s: %s\n", got_ref_get_name(symref),
2050 got_ref_get_symref_target(symref));
2053 done:
2054 if (symref_is_locked) {
2055 unlock_err = got_ref_unlock(symref);
2056 if (unlock_err && err == NULL)
2057 err = unlock_err;
2059 got_ref_close(symref);
2060 return err;
2063 __dead static void
2064 usage_fetch(void)
2066 fprintf(stderr, "usage: %s fetch [-adlqtvX] [-b branch] "
2067 "[-R reference] [-r repository-path] [remote-repository]\n",
2068 getprogname());
2069 exit(1);
2072 static const struct got_error *
2073 delete_missing_ref(struct got_reference *ref,
2074 int verbosity, struct got_repository *repo)
2076 const struct got_error *err = NULL;
2077 struct got_object_id *id = NULL;
2078 char *id_str = NULL;
2080 if (got_ref_is_symbolic(ref)) {
2081 err = got_ref_delete(ref, repo);
2082 if (err)
2083 return err;
2084 if (verbosity >= 0) {
2085 printf("Deleted %s: %s\n",
2086 got_ref_get_name(ref),
2087 got_ref_get_symref_target(ref));
2089 } else {
2090 err = got_ref_resolve(&id, repo, ref);
2091 if (err)
2092 return err;
2093 err = got_object_id_str(&id_str, id);
2094 if (err)
2095 goto done;
2097 err = got_ref_delete(ref, repo);
2098 if (err)
2099 goto done;
2100 if (verbosity >= 0) {
2101 printf("Deleted %s: %s\n",
2102 got_ref_get_name(ref), id_str);
2105 done:
2106 free(id);
2107 free(id_str);
2108 return NULL;
2111 static const struct got_error *
2112 delete_missing_refs(struct got_pathlist_head *their_refs,
2113 struct got_pathlist_head *their_symrefs,
2114 const struct got_remote_repo *remote,
2115 int verbosity, struct got_repository *repo)
2117 const struct got_error *err = NULL, *unlock_err;
2118 struct got_reflist_head my_refs;
2119 struct got_reflist_entry *re;
2120 struct got_pathlist_entry *pe;
2121 char *remote_namespace = NULL;
2122 char *local_refname = NULL;
2124 TAILQ_INIT(&my_refs);
2126 if (asprintf(&remote_namespace, "refs/remotes/%s/", remote->name)
2127 == -1)
2128 return got_error_from_errno("asprintf");
2130 err = got_ref_list(&my_refs, repo, NULL, got_ref_cmp_by_name, NULL);
2131 if (err)
2132 goto done;
2134 TAILQ_FOREACH(re, &my_refs, entry) {
2135 const char *refname = got_ref_get_name(re->ref);
2136 const char *their_refname;
2138 if (remote->mirror_references) {
2139 their_refname = refname;
2140 } else {
2141 if (strncmp(refname, remote_namespace,
2142 strlen(remote_namespace)) == 0) {
2143 if (strcmp(refname + strlen(remote_namespace),
2144 GOT_REF_HEAD) == 0)
2145 continue;
2146 if (asprintf(&local_refname, "refs/heads/%s",
2147 refname + strlen(remote_namespace)) == -1) {
2148 err = got_error_from_errno("asprintf");
2149 goto done;
2151 } else if (strncmp(refname, "refs/tags/", 10) != 0)
2152 continue;
2154 their_refname = local_refname;
2157 TAILQ_FOREACH(pe, their_refs, entry) {
2158 if (strcmp(their_refname, pe->path) == 0)
2159 break;
2161 if (pe != NULL)
2162 continue;
2164 TAILQ_FOREACH(pe, their_symrefs, entry) {
2165 if (strcmp(their_refname, pe->path) == 0)
2166 break;
2168 if (pe != NULL)
2169 continue;
2171 err = delete_missing_ref(re->ref, verbosity, repo);
2172 if (err)
2173 break;
2175 if (local_refname) {
2176 struct got_reference *ref;
2177 err = got_ref_open(&ref, repo, local_refname, 1);
2178 if (err) {
2179 if (err->code != GOT_ERR_NOT_REF)
2180 break;
2181 free(local_refname);
2182 local_refname = NULL;
2183 continue;
2185 err = delete_missing_ref(ref, verbosity, repo);
2186 if (err)
2187 break;
2188 unlock_err = got_ref_unlock(ref);
2189 got_ref_close(ref);
2190 if (unlock_err && err == NULL) {
2191 err = unlock_err;
2192 break;
2195 free(local_refname);
2196 local_refname = NULL;
2199 done:
2200 got_ref_list_free(&my_refs);
2201 free(remote_namespace);
2202 free(local_refname);
2203 return err;
2206 static const struct got_error *
2207 update_wanted_ref(const char *refname, struct got_object_id *id,
2208 const char *remote_repo_name, int verbosity, struct got_repository *repo)
2210 const struct got_error *err, *unlock_err;
2211 char *remote_refname;
2212 struct got_reference *ref;
2214 if (strncmp("refs/", refname, 5) == 0)
2215 refname += 5;
2217 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
2218 remote_repo_name, refname) == -1)
2219 return got_error_from_errno("asprintf");
2221 err = got_ref_open(&ref, repo, remote_refname, 1);
2222 if (err) {
2223 if (err->code != GOT_ERR_NOT_REF)
2224 goto done;
2225 err = create_ref(remote_refname, id, verbosity, repo);
2226 } else {
2227 err = update_ref(ref, id, 0, verbosity, repo);
2228 unlock_err = got_ref_unlock(ref);
2229 if (unlock_err && err == NULL)
2230 err = unlock_err;
2231 got_ref_close(ref);
2233 done:
2234 free(remote_refname);
2235 return err;
2238 static const struct got_error *
2239 delete_ref(struct got_repository *repo, struct got_reference *ref)
2241 const struct got_error *err = NULL;
2242 struct got_object_id *id = NULL;
2243 char *id_str = NULL;
2244 const char *target;
2246 if (got_ref_is_symbolic(ref)) {
2247 target = got_ref_get_symref_target(ref);
2248 } else {
2249 err = got_ref_resolve(&id, repo, ref);
2250 if (err)
2251 goto done;
2252 err = got_object_id_str(&id_str, id);
2253 if (err)
2254 goto done;
2255 target = id_str;
2258 err = got_ref_delete(ref, repo);
2259 if (err)
2260 goto done;
2262 printf("Deleted %s: %s\n", got_ref_get_name(ref), target);
2263 done:
2264 free(id);
2265 free(id_str);
2266 return err;
2269 static const struct got_error *
2270 delete_refs_for_remote(struct got_repository *repo, const char *remote_name)
2272 const struct got_error *err = NULL;
2273 struct got_reflist_head refs;
2274 struct got_reflist_entry *re;
2275 char *prefix;
2277 TAILQ_INIT(&refs);
2279 if (asprintf(&prefix, "refs/remotes/%s", remote_name) == -1) {
2280 err = got_error_from_errno("asprintf");
2281 goto done;
2283 err = got_ref_list(&refs, repo, prefix, got_ref_cmp_by_name, NULL);
2284 if (err)
2285 goto done;
2287 TAILQ_FOREACH(re, &refs, entry)
2288 delete_ref(repo, re->ref);
2289 done:
2290 got_ref_list_free(&refs);
2291 return err;
2294 static const struct got_error *
2295 cmd_fetch(int argc, char *argv[])
2297 const struct got_error *error = NULL, *unlock_err;
2298 char *cwd = NULL, *repo_path = NULL;
2299 const char *remote_name;
2300 char *proto = NULL, *host = NULL, *port = NULL;
2301 char *repo_name = NULL, *server_path = NULL;
2302 const struct got_remote_repo *remotes, *remote = NULL;
2303 int nremotes;
2304 char *id_str = NULL;
2305 struct got_repository *repo = NULL;
2306 struct got_worktree *worktree = NULL;
2307 const struct got_gotconfig *repo_conf = NULL, *worktree_conf = NULL;
2308 struct got_pathlist_head refs, symrefs, wanted_branches, wanted_refs;
2309 struct got_pathlist_entry *pe;
2310 struct got_object_id *pack_hash = NULL;
2311 int i, ch, fetchfd = -1, fetchstatus;
2312 pid_t fetchpid = -1;
2313 struct got_fetch_progress_arg fpa;
2314 int verbosity = 0, fetch_all_branches = 0, list_refs_only = 0;
2315 int delete_refs = 0, replace_tags = 0, delete_remote = 0;
2316 int *pack_fds = NULL;
2318 TAILQ_INIT(&refs);
2319 TAILQ_INIT(&symrefs);
2320 TAILQ_INIT(&wanted_branches);
2321 TAILQ_INIT(&wanted_refs);
2323 while ((ch = getopt(argc, argv, "ab:dlqR:r:tvX")) != -1) {
2324 switch (ch) {
2325 case 'a':
2326 fetch_all_branches = 1;
2327 break;
2328 case 'b':
2329 error = got_pathlist_append(&wanted_branches,
2330 optarg, NULL);
2331 if (error)
2332 return error;
2333 break;
2334 case 'd':
2335 delete_refs = 1;
2336 break;
2337 case 'l':
2338 list_refs_only = 1;
2339 break;
2340 case 'q':
2341 verbosity = -1;
2342 break;
2343 case 'R':
2344 error = got_pathlist_append(&wanted_refs,
2345 optarg, NULL);
2346 if (error)
2347 return error;
2348 break;
2349 case 'r':
2350 repo_path = realpath(optarg, NULL);
2351 if (repo_path == NULL)
2352 return got_error_from_errno2("realpath",
2353 optarg);
2354 got_path_strip_trailing_slashes(repo_path);
2355 break;
2356 case 't':
2357 replace_tags = 1;
2358 break;
2359 case 'v':
2360 if (verbosity < 0)
2361 verbosity = 0;
2362 else if (verbosity < 3)
2363 verbosity++;
2364 break;
2365 case 'X':
2366 delete_remote = 1;
2367 break;
2368 default:
2369 usage_fetch();
2370 break;
2373 argc -= optind;
2374 argv += optind;
2376 if (fetch_all_branches && !TAILQ_EMPTY(&wanted_branches))
2377 option_conflict('a', 'b');
2378 if (list_refs_only) {
2379 if (!TAILQ_EMPTY(&wanted_branches))
2380 option_conflict('l', 'b');
2381 if (fetch_all_branches)
2382 option_conflict('l', 'a');
2383 if (delete_refs)
2384 option_conflict('l', 'd');
2385 if (delete_remote)
2386 option_conflict('l', 'X');
2388 if (delete_remote) {
2389 if (fetch_all_branches)
2390 option_conflict('X', 'a');
2391 if (!TAILQ_EMPTY(&wanted_branches))
2392 option_conflict('X', 'b');
2393 if (delete_refs)
2394 option_conflict('X', 'd');
2395 if (replace_tags)
2396 option_conflict('X', 't');
2397 if (!TAILQ_EMPTY(&wanted_refs))
2398 option_conflict('X', 'R');
2401 if (argc == 0) {
2402 if (delete_remote)
2403 errx(1, "-X option requires a remote name");
2404 remote_name = GOT_FETCH_DEFAULT_REMOTE_NAME;
2405 } else if (argc == 1)
2406 remote_name = argv[0];
2407 else
2408 usage_fetch();
2410 cwd = getcwd(NULL, 0);
2411 if (cwd == NULL) {
2412 error = got_error_from_errno("getcwd");
2413 goto done;
2416 error = got_repo_pack_fds_open(&pack_fds);
2417 if (error != NULL)
2418 goto done;
2420 if (repo_path == NULL) {
2421 error = got_worktree_open(&worktree, cwd);
2422 if (error && error->code != GOT_ERR_NOT_WORKTREE)
2423 goto done;
2424 else
2425 error = NULL;
2426 if (worktree) {
2427 repo_path =
2428 strdup(got_worktree_get_repo_path(worktree));
2429 if (repo_path == NULL)
2430 error = got_error_from_errno("strdup");
2431 if (error)
2432 goto done;
2433 } else {
2434 repo_path = strdup(cwd);
2435 if (repo_path == NULL) {
2436 error = got_error_from_errno("strdup");
2437 goto done;
2442 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
2443 if (error)
2444 goto done;
2446 if (delete_remote) {
2447 error = delete_refs_for_remote(repo, remote_name);
2448 goto done; /* nothing else to do */
2451 if (worktree) {
2452 worktree_conf = got_worktree_get_gotconfig(worktree);
2453 if (worktree_conf) {
2454 got_gotconfig_get_remotes(&nremotes, &remotes,
2455 worktree_conf);
2456 for (i = 0; i < nremotes; i++) {
2457 if (strcmp(remotes[i].name, remote_name) == 0) {
2458 remote = &remotes[i];
2459 break;
2464 if (remote == NULL) {
2465 repo_conf = got_repo_get_gotconfig(repo);
2466 if (repo_conf) {
2467 got_gotconfig_get_remotes(&nremotes, &remotes,
2468 repo_conf);
2469 for (i = 0; i < nremotes; i++) {
2470 if (strcmp(remotes[i].name, remote_name) == 0) {
2471 remote = &remotes[i];
2472 break;
2477 if (remote == NULL) {
2478 got_repo_get_gitconfig_remotes(&nremotes, &remotes, repo);
2479 for (i = 0; i < nremotes; i++) {
2480 if (strcmp(remotes[i].name, remote_name) == 0) {
2481 remote = &remotes[i];
2482 break;
2486 if (remote == NULL) {
2487 error = got_error_path(remote_name, GOT_ERR_NO_REMOTE);
2488 goto done;
2491 if (TAILQ_EMPTY(&wanted_branches)) {
2492 if (!fetch_all_branches)
2493 fetch_all_branches = remote->fetch_all_branches;
2494 for (i = 0; i < remote->nfetch_branches; i++) {
2495 got_pathlist_append(&wanted_branches,
2496 remote->fetch_branches[i], NULL);
2499 if (TAILQ_EMPTY(&wanted_refs)) {
2500 for (i = 0; i < remote->nfetch_refs; i++) {
2501 got_pathlist_append(&wanted_refs,
2502 remote->fetch_refs[i], NULL);
2506 error = got_dial_parse_uri(&proto, &host, &port, &server_path,
2507 &repo_name, remote->fetch_url);
2508 if (error)
2509 goto done;
2511 if (strcmp(proto, "git") == 0) {
2512 #ifndef PROFILE
2513 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
2514 "sendfd dns inet unveil", NULL) == -1)
2515 err(1, "pledge");
2516 #endif
2517 } else if (strcmp(proto, "git+ssh") == 0 ||
2518 strcmp(proto, "ssh") == 0) {
2519 #ifndef PROFILE
2520 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
2521 "sendfd unveil", NULL) == -1)
2522 err(1, "pledge");
2523 #endif
2524 } else if (strcmp(proto, "http") == 0 ||
2525 strcmp(proto, "git+http") == 0) {
2526 error = got_error_path(proto, GOT_ERR_NOT_IMPL);
2527 goto done;
2528 } else {
2529 error = got_error_path(proto, GOT_ERR_BAD_PROTO);
2530 goto done;
2533 error = got_dial_apply_unveil(proto);
2534 if (error)
2535 goto done;
2537 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
2538 if (error)
2539 goto done;
2541 if (verbosity >= 0)
2542 printf("Connecting to \"%s\" %s%s%s\n", remote->name, host,
2543 port ? ":" : "", port ? port : "");
2545 error = got_fetch_connect(&fetchpid, &fetchfd, proto, host, port,
2546 server_path, verbosity);
2547 if (error)
2548 goto done;
2550 fpa.last_scaled_size[0] = '\0';
2551 fpa.last_p_indexed = -1;
2552 fpa.last_p_resolved = -1;
2553 fpa.verbosity = verbosity;
2554 fpa.repo = repo;
2555 fpa.create_configs = 0;
2556 fpa.configs_created = 0;
2557 memset(&fpa.config_info, 0, sizeof(fpa.config_info));
2558 error = got_fetch_pack(&pack_hash, &refs, &symrefs, remote->name,
2559 remote->mirror_references, fetch_all_branches, &wanted_branches,
2560 &wanted_refs, list_refs_only, verbosity, fetchfd, repo,
2561 fetch_progress, &fpa);
2562 if (error)
2563 goto done;
2565 if (list_refs_only) {
2566 error = list_remote_refs(&symrefs, &refs);
2567 goto done;
2570 if (pack_hash == NULL) {
2571 if (verbosity >= 0)
2572 printf("Already up-to-date\n");
2573 } else if (verbosity >= 0) {
2574 error = got_object_id_str(&id_str, pack_hash);
2575 if (error)
2576 goto done;
2577 printf("\nFetched %s.pack\n", id_str);
2578 free(id_str);
2579 id_str = NULL;
2582 /* Update references provided with the pack file. */
2583 TAILQ_FOREACH(pe, &refs, entry) {
2584 const char *refname = pe->path;
2585 struct got_object_id *id = pe->data;
2586 struct got_reference *ref;
2587 char *remote_refname;
2589 if (is_wanted_ref(&wanted_refs, refname) &&
2590 !remote->mirror_references) {
2591 error = update_wanted_ref(refname, id,
2592 remote->name, verbosity, repo);
2593 if (error)
2594 goto done;
2595 continue;
2598 if (remote->mirror_references ||
2599 strncmp("refs/tags/", refname, 10) == 0) {
2600 error = got_ref_open(&ref, repo, refname, 1);
2601 if (error) {
2602 if (error->code != GOT_ERR_NOT_REF)
2603 goto done;
2604 error = create_ref(refname, id, verbosity,
2605 repo);
2606 if (error)
2607 goto done;
2608 } else {
2609 error = update_ref(ref, id, replace_tags,
2610 verbosity, repo);
2611 unlock_err = got_ref_unlock(ref);
2612 if (unlock_err && error == NULL)
2613 error = unlock_err;
2614 got_ref_close(ref);
2615 if (error)
2616 goto done;
2618 } else if (strncmp("refs/heads/", refname, 11) == 0) {
2619 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
2620 remote_name, refname + 11) == -1) {
2621 error = got_error_from_errno("asprintf");
2622 goto done;
2625 error = got_ref_open(&ref, repo, remote_refname, 1);
2626 if (error) {
2627 if (error->code != GOT_ERR_NOT_REF)
2628 goto done;
2629 error = create_ref(remote_refname, id,
2630 verbosity, repo);
2631 if (error)
2632 goto done;
2633 } else {
2634 error = update_ref(ref, id, replace_tags,
2635 verbosity, repo);
2636 unlock_err = got_ref_unlock(ref);
2637 if (unlock_err && error == NULL)
2638 error = unlock_err;
2639 got_ref_close(ref);
2640 if (error)
2641 goto done;
2644 /* Also create a local branch if none exists yet. */
2645 error = got_ref_open(&ref, repo, refname, 1);
2646 if (error) {
2647 if (error->code != GOT_ERR_NOT_REF)
2648 goto done;
2649 error = create_ref(refname, id, verbosity,
2650 repo);
2651 if (error)
2652 goto done;
2653 } else {
2654 unlock_err = got_ref_unlock(ref);
2655 if (unlock_err && error == NULL)
2656 error = unlock_err;
2657 got_ref_close(ref);
2661 if (delete_refs) {
2662 error = delete_missing_refs(&refs, &symrefs, remote,
2663 verbosity, repo);
2664 if (error)
2665 goto done;
2668 if (!remote->mirror_references) {
2669 /* Update remote HEAD reference if the server provided one. */
2670 TAILQ_FOREACH(pe, &symrefs, entry) {
2671 struct got_reference *target_ref;
2672 const char *refname = pe->path;
2673 const char *target = pe->data;
2674 char *remote_refname = NULL, *remote_target = NULL;
2676 if (strcmp(refname, GOT_REF_HEAD) != 0)
2677 continue;
2679 if (strncmp("refs/heads/", target, 11) != 0)
2680 continue;
2682 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
2683 remote->name, refname) == -1) {
2684 error = got_error_from_errno("asprintf");
2685 goto done;
2687 if (asprintf(&remote_target, "refs/remotes/%s/%s",
2688 remote->name, target + 11) == -1) {
2689 error = got_error_from_errno("asprintf");
2690 free(remote_refname);
2691 goto done;
2694 error = got_ref_open(&target_ref, repo, remote_target,
2695 0);
2696 if (error) {
2697 free(remote_refname);
2698 free(remote_target);
2699 if (error->code == GOT_ERR_NOT_REF) {
2700 error = NULL;
2701 continue;
2703 goto done;
2705 error = update_symref(remote_refname, target_ref,
2706 verbosity, repo);
2707 free(remote_refname);
2708 free(remote_target);
2709 got_ref_close(target_ref);
2710 if (error)
2711 goto done;
2714 done:
2715 if (fetchpid > 0) {
2716 if (kill(fetchpid, SIGTERM) == -1)
2717 error = got_error_from_errno("kill");
2718 if (waitpid(fetchpid, &fetchstatus, 0) == -1 && error == NULL)
2719 error = got_error_from_errno("waitpid");
2721 if (fetchfd != -1 && close(fetchfd) == -1 && error == NULL)
2722 error = got_error_from_errno("close");
2723 if (repo) {
2724 const struct got_error *close_err = got_repo_close(repo);
2725 if (error == NULL)
2726 error = close_err;
2728 if (worktree)
2729 got_worktree_close(worktree);
2730 if (pack_fds) {
2731 const struct got_error *pack_err =
2732 got_repo_pack_fds_close(pack_fds);
2733 if (error == NULL)
2734 error = pack_err;
2736 TAILQ_FOREACH(pe, &refs, entry) {
2737 free((void *)pe->path);
2738 free(pe->data);
2740 got_pathlist_free(&refs);
2741 TAILQ_FOREACH(pe, &symrefs, entry) {
2742 free((void *)pe->path);
2743 free(pe->data);
2745 got_pathlist_free(&symrefs);
2746 got_pathlist_free(&wanted_branches);
2747 got_pathlist_free(&wanted_refs);
2748 free(id_str);
2749 free(cwd);
2750 free(repo_path);
2751 free(pack_hash);
2752 free(proto);
2753 free(host);
2754 free(port);
2755 free(server_path);
2756 free(repo_name);
2757 return error;
2761 __dead static void
2762 usage_checkout(void)
2764 fprintf(stderr, "usage: %s checkout [-Eq] [-b branch] [-c commit] "
2765 "[-p path-prefix] repository-path [work-tree-path]\n",
2766 getprogname());
2767 exit(1);
2770 static void
2771 show_worktree_base_ref_warning(void)
2773 fprintf(stderr, "%s: warning: could not create a reference "
2774 "to the work tree's base commit; the commit could be "
2775 "garbage-collected by Git or 'gotadmin cleanup'; making the "
2776 "repository writable and running 'got update' will prevent this\n",
2777 getprogname());
2780 struct got_checkout_progress_arg {
2781 const char *worktree_path;
2782 int had_base_commit_ref_error;
2783 int verbosity;
2786 static const struct got_error *
2787 checkout_progress(void *arg, unsigned char status, const char *path)
2789 struct got_checkout_progress_arg *a = arg;
2791 /* Base commit bump happens silently. */
2792 if (status == GOT_STATUS_BUMP_BASE)
2793 return NULL;
2795 if (status == GOT_STATUS_BASE_REF_ERR) {
2796 a->had_base_commit_ref_error = 1;
2797 return NULL;
2800 while (path[0] == '/')
2801 path++;
2803 if (a->verbosity >= 0)
2804 printf("%c %s/%s\n", status, a->worktree_path, path);
2806 return NULL;
2809 static const struct got_error *
2810 check_cancelled(void *arg)
2812 if (sigint_received || sigpipe_received)
2813 return got_error(GOT_ERR_CANCELLED);
2814 return NULL;
2817 static const struct got_error *
2818 check_linear_ancestry(struct got_object_id *commit_id,
2819 struct got_object_id *base_commit_id, int allow_forwards_in_time_only,
2820 struct got_repository *repo)
2822 const struct got_error *err = NULL;
2823 struct got_object_id *yca_id;
2825 err = got_commit_graph_find_youngest_common_ancestor(&yca_id,
2826 commit_id, base_commit_id, 1, repo, check_cancelled, NULL);
2827 if (err)
2828 return err;
2830 if (yca_id == NULL)
2831 return got_error(GOT_ERR_ANCESTRY);
2834 * Require a straight line of history between the target commit
2835 * and the work tree's base commit.
2837 * Non-linear situations such as this require a rebase:
2839 * (commit) D F (base_commit)
2840 * \ /
2841 * C E
2842 * \ /
2843 * B (yca)
2844 * |
2845 * A
2847 * 'got update' only handles linear cases:
2848 * Update forwards in time: A (base/yca) - B - C - D (commit)
2849 * Update backwards in time: D (base) - C - B - A (commit/yca)
2851 if (allow_forwards_in_time_only) {
2852 if (got_object_id_cmp(base_commit_id, yca_id) != 0)
2853 return got_error(GOT_ERR_ANCESTRY);
2854 } else if (got_object_id_cmp(commit_id, yca_id) != 0 &&
2855 got_object_id_cmp(base_commit_id, yca_id) != 0)
2856 return got_error(GOT_ERR_ANCESTRY);
2858 free(yca_id);
2859 return NULL;
2862 static const struct got_error *
2863 check_same_branch(struct got_object_id *commit_id,
2864 struct got_reference *head_ref, struct got_object_id *yca_id,
2865 struct got_repository *repo)
2867 const struct got_error *err = NULL;
2868 struct got_commit_graph *graph = NULL;
2869 struct got_object_id *head_commit_id = NULL;
2870 int is_same_branch = 0;
2872 err = got_ref_resolve(&head_commit_id, repo, head_ref);
2873 if (err)
2874 goto done;
2876 if (got_object_id_cmp(head_commit_id, commit_id) == 0) {
2877 is_same_branch = 1;
2878 goto done;
2880 if (yca_id && got_object_id_cmp(commit_id, yca_id) == 0) {
2881 is_same_branch = 1;
2882 goto done;
2885 err = got_commit_graph_open(&graph, "/", 1);
2886 if (err)
2887 goto done;
2889 err = got_commit_graph_iter_start(graph, head_commit_id, repo,
2890 check_cancelled, NULL);
2891 if (err)
2892 goto done;
2894 for (;;) {
2895 struct got_object_id id;
2897 err = got_commit_graph_iter_next(&id, graph, repo,
2898 check_cancelled, NULL);
2899 if (err) {
2900 if (err->code == GOT_ERR_ITER_COMPLETED)
2901 err = NULL;
2902 break;
2905 if (yca_id && got_object_id_cmp(&id, yca_id) == 0)
2906 break;
2907 if (got_object_id_cmp(&id, commit_id) == 0) {
2908 is_same_branch = 1;
2909 break;
2912 done:
2913 if (graph)
2914 got_commit_graph_close(graph);
2915 free(head_commit_id);
2916 if (!err && !is_same_branch)
2917 err = got_error(GOT_ERR_ANCESTRY);
2918 return err;
2921 static const struct got_error *
2922 checkout_ancestry_error(struct got_reference *ref, const char *commit_id_str)
2924 static char msg[512];
2925 const char *branch_name;
2927 if (got_ref_is_symbolic(ref))
2928 branch_name = got_ref_get_symref_target(ref);
2929 else
2930 branch_name = got_ref_get_name(ref);
2932 if (strncmp("refs/heads/", branch_name, 11) == 0)
2933 branch_name += 11;
2935 snprintf(msg, sizeof(msg),
2936 "target commit is not contained in branch '%s'; "
2937 "the branch to use must be specified with -b; "
2938 "if necessary a new branch can be created for "
2939 "this commit with 'got branch -c %s BRANCH_NAME'",
2940 branch_name, commit_id_str);
2942 return got_error_msg(GOT_ERR_ANCESTRY, msg);
2945 static const struct got_error *
2946 cmd_checkout(int argc, char *argv[])
2948 const struct got_error *error = NULL;
2949 struct got_repository *repo = NULL;
2950 struct got_reference *head_ref = NULL, *ref = NULL;
2951 struct got_worktree *worktree = NULL;
2952 char *repo_path = NULL;
2953 char *worktree_path = NULL;
2954 const char *path_prefix = "";
2955 const char *branch_name = GOT_REF_HEAD, *refname = NULL;
2956 char *commit_id_str = NULL;
2957 struct got_object_id *commit_id = NULL;
2958 char *cwd = NULL;
2959 int ch, same_path_prefix, allow_nonempty = 0, verbosity = 0;
2960 struct got_pathlist_head paths;
2961 struct got_checkout_progress_arg cpa;
2962 int *pack_fds = NULL;
2964 TAILQ_INIT(&paths);
2966 while ((ch = getopt(argc, argv, "b:c:Ep:q")) != -1) {
2967 switch (ch) {
2968 case 'b':
2969 branch_name = optarg;
2970 break;
2971 case 'c':
2972 commit_id_str = strdup(optarg);
2973 if (commit_id_str == NULL)
2974 return got_error_from_errno("strdup");
2975 break;
2976 case 'E':
2977 allow_nonempty = 1;
2978 break;
2979 case 'p':
2980 path_prefix = optarg;
2981 break;
2982 case 'q':
2983 verbosity = -1;
2984 break;
2985 default:
2986 usage_checkout();
2987 /* NOTREACHED */
2991 argc -= optind;
2992 argv += optind;
2994 #ifndef PROFILE
2995 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
2996 "unveil", NULL) == -1)
2997 err(1, "pledge");
2998 #endif
2999 if (argc == 1) {
3000 char *base, *dotgit;
3001 const char *path;
3002 repo_path = realpath(argv[0], NULL);
3003 if (repo_path == NULL)
3004 return got_error_from_errno2("realpath", argv[0]);
3005 cwd = getcwd(NULL, 0);
3006 if (cwd == NULL) {
3007 error = got_error_from_errno("getcwd");
3008 goto done;
3010 if (path_prefix[0])
3011 path = path_prefix;
3012 else
3013 path = repo_path;
3014 error = got_path_basename(&base, path);
3015 if (error)
3016 goto done;
3017 dotgit = strstr(base, ".git");
3018 if (dotgit)
3019 *dotgit = '\0';
3020 if (asprintf(&worktree_path, "%s/%s", cwd, base) == -1) {
3021 error = got_error_from_errno("asprintf");
3022 free(base);
3023 goto done;
3025 free(base);
3026 } else if (argc == 2) {
3027 repo_path = realpath(argv[0], NULL);
3028 if (repo_path == NULL) {
3029 error = got_error_from_errno2("realpath", argv[0]);
3030 goto done;
3032 worktree_path = realpath(argv[1], NULL);
3033 if (worktree_path == NULL) {
3034 if (errno != ENOENT) {
3035 error = got_error_from_errno2("realpath",
3036 argv[1]);
3037 goto done;
3039 worktree_path = strdup(argv[1]);
3040 if (worktree_path == NULL) {
3041 error = got_error_from_errno("strdup");
3042 goto done;
3045 } else
3046 usage_checkout();
3048 got_path_strip_trailing_slashes(repo_path);
3049 got_path_strip_trailing_slashes(worktree_path);
3051 error = got_repo_pack_fds_open(&pack_fds);
3052 if (error != NULL)
3053 goto done;
3055 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
3056 if (error != NULL)
3057 goto done;
3059 /* Pre-create work tree path for unveil(2) */
3060 error = got_path_mkdir(worktree_path);
3061 if (error) {
3062 if (!(error->code == GOT_ERR_ERRNO && errno == EISDIR) &&
3063 !(error->code == GOT_ERR_ERRNO && errno == EEXIST))
3064 goto done;
3065 if (!allow_nonempty &&
3066 !got_path_dir_is_empty(worktree_path)) {
3067 error = got_error_path(worktree_path,
3068 GOT_ERR_DIR_NOT_EMPTY);
3069 goto done;
3073 error = apply_unveil(got_repo_get_path(repo), 0, worktree_path);
3074 if (error)
3075 goto done;
3077 error = got_ref_open(&head_ref, repo, branch_name, 0);
3078 if (error != NULL)
3079 goto done;
3081 error = got_worktree_init(worktree_path, head_ref, path_prefix, repo);
3082 if (error != NULL && !(error->code == GOT_ERR_ERRNO && errno == EEXIST))
3083 goto done;
3085 error = got_worktree_open(&worktree, worktree_path);
3086 if (error != NULL)
3087 goto done;
3089 error = got_worktree_match_path_prefix(&same_path_prefix, worktree,
3090 path_prefix);
3091 if (error != NULL)
3092 goto done;
3093 if (!same_path_prefix) {
3094 error = got_error(GOT_ERR_PATH_PREFIX);
3095 goto done;
3098 if (commit_id_str) {
3099 struct got_reflist_head refs;
3100 TAILQ_INIT(&refs);
3101 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
3102 NULL);
3103 if (error)
3104 goto done;
3105 error = got_repo_match_object_id(&commit_id, NULL,
3106 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
3107 got_ref_list_free(&refs);
3108 if (error)
3109 goto done;
3110 error = check_linear_ancestry(commit_id,
3111 got_worktree_get_base_commit_id(worktree), 0, repo);
3112 if (error != NULL) {
3113 if (error->code == GOT_ERR_ANCESTRY) {
3114 error = checkout_ancestry_error(
3115 head_ref, commit_id_str);
3117 goto done;
3119 error = check_same_branch(commit_id, head_ref, NULL, repo);
3120 if (error) {
3121 if (error->code == GOT_ERR_ANCESTRY) {
3122 error = checkout_ancestry_error(
3123 head_ref, commit_id_str);
3125 goto done;
3127 error = got_worktree_set_base_commit_id(worktree, repo,
3128 commit_id);
3129 if (error)
3130 goto done;
3131 /* Expand potentially abbreviated commit ID string. */
3132 free(commit_id_str);
3133 error = got_object_id_str(&commit_id_str, commit_id);
3134 if (error)
3135 goto done;
3136 } else {
3137 commit_id = got_object_id_dup(
3138 got_worktree_get_base_commit_id(worktree));
3139 if (commit_id == NULL) {
3140 error = got_error_from_errno("got_object_id_dup");
3141 goto done;
3143 error = got_object_id_str(&commit_id_str, commit_id);
3144 if (error)
3145 goto done;
3148 error = got_pathlist_append(&paths, "", NULL);
3149 if (error)
3150 goto done;
3151 cpa.worktree_path = worktree_path;
3152 cpa.had_base_commit_ref_error = 0;
3153 cpa.verbosity = verbosity;
3154 error = got_worktree_checkout_files(worktree, &paths, repo,
3155 checkout_progress, &cpa, check_cancelled, NULL);
3156 if (error != NULL)
3157 goto done;
3159 if (got_ref_is_symbolic(head_ref)) {
3160 error = got_ref_resolve_symbolic(&ref, repo, head_ref);
3161 if (error)
3162 goto done;
3163 refname = got_ref_get_name(ref);
3164 } else
3165 refname = got_ref_get_name(head_ref);
3166 printf("Checked out %s: %s\n", refname, commit_id_str);
3167 printf("Now shut up and hack\n");
3168 if (cpa.had_base_commit_ref_error)
3169 show_worktree_base_ref_warning();
3170 done:
3171 if (pack_fds) {
3172 const struct got_error *pack_err =
3173 got_repo_pack_fds_close(pack_fds);
3174 if (error == NULL)
3175 error = pack_err;
3177 if (head_ref)
3178 got_ref_close(head_ref);
3179 if (ref)
3180 got_ref_close(ref);
3181 got_pathlist_free(&paths);
3182 free(commit_id_str);
3183 free(commit_id);
3184 free(repo_path);
3185 free(worktree_path);
3186 free(cwd);
3187 return error;
3190 struct got_update_progress_arg {
3191 int did_something;
3192 int conflicts;
3193 int obstructed;
3194 int not_updated;
3195 int missing;
3196 int not_deleted;
3197 int unversioned;
3198 int verbosity;
3201 static void
3202 print_update_progress_stats(struct got_update_progress_arg *upa)
3204 if (!upa->did_something)
3205 return;
3207 if (upa->conflicts > 0)
3208 printf("Files with new merge conflicts: %d\n", upa->conflicts);
3209 if (upa->obstructed > 0)
3210 printf("File paths obstructed by a non-regular file: %d\n",
3211 upa->obstructed);
3212 if (upa->not_updated > 0)
3213 printf("Files not updated because of existing merge "
3214 "conflicts: %d\n", upa->not_updated);
3218 * The meaning of some status codes differs between merge-style operations and
3219 * update operations. For example, the ! status code means "file was missing"
3220 * if changes were merged into the work tree, and "missing file was restored"
3221 * if the work tree was updated. This function should be used by any operation
3222 * which merges changes into the work tree without updating the work tree.
3224 static void
3225 print_merge_progress_stats(struct got_update_progress_arg *upa)
3227 if (!upa->did_something)
3228 return;
3230 if (upa->conflicts > 0)
3231 printf("Files with new merge conflicts: %d\n", upa->conflicts);
3232 if (upa->obstructed > 0)
3233 printf("File paths obstructed by a non-regular file: %d\n",
3234 upa->obstructed);
3235 if (upa->missing > 0)
3236 printf("Files which had incoming changes but could not be "
3237 "found in the work tree: %d\n", upa->missing);
3238 if (upa->not_deleted > 0)
3239 printf("Files not deleted due to differences in deleted "
3240 "content: %d\n", upa->not_deleted);
3241 if (upa->unversioned > 0)
3242 printf("Files not merged because an unversioned file was "
3243 "found in the work tree: %d\n", upa->unversioned);
3246 __dead static void
3247 usage_update(void)
3249 fprintf(stderr, "usage: %s update [-q] [-b branch] [-c commit] "
3250 "[path ...]\n", getprogname());
3251 exit(1);
3254 static const struct got_error *
3255 update_progress(void *arg, unsigned char status, const char *path)
3257 struct got_update_progress_arg *upa = arg;
3259 if (status == GOT_STATUS_EXISTS ||
3260 status == GOT_STATUS_BASE_REF_ERR)
3261 return NULL;
3263 upa->did_something = 1;
3265 /* Base commit bump happens silently. */
3266 if (status == GOT_STATUS_BUMP_BASE)
3267 return NULL;
3269 if (status == GOT_STATUS_CONFLICT)
3270 upa->conflicts++;
3271 if (status == GOT_STATUS_OBSTRUCTED)
3272 upa->obstructed++;
3273 if (status == GOT_STATUS_CANNOT_UPDATE)
3274 upa->not_updated++;
3275 if (status == GOT_STATUS_MISSING)
3276 upa->missing++;
3277 if (status == GOT_STATUS_CANNOT_DELETE)
3278 upa->not_deleted++;
3279 if (status == GOT_STATUS_UNVERSIONED)
3280 upa->unversioned++;
3282 while (path[0] == '/')
3283 path++;
3284 if (upa->verbosity >= 0)
3285 printf("%c %s\n", status, path);
3287 return NULL;
3290 static const struct got_error *
3291 switch_head_ref(struct got_reference *head_ref,
3292 struct got_object_id *commit_id, struct got_worktree *worktree,
3293 struct got_repository *repo)
3295 const struct got_error *err = NULL;
3296 char *base_id_str;
3297 int ref_has_moved = 0;
3299 /* Trivial case: switching between two different references. */
3300 if (strcmp(got_ref_get_name(head_ref),
3301 got_worktree_get_head_ref_name(worktree)) != 0) {
3302 printf("Switching work tree from %s to %s\n",
3303 got_worktree_get_head_ref_name(worktree),
3304 got_ref_get_name(head_ref));
3305 return got_worktree_set_head_ref(worktree, head_ref);
3308 err = check_linear_ancestry(commit_id,
3309 got_worktree_get_base_commit_id(worktree), 0, repo);
3310 if (err) {
3311 if (err->code != GOT_ERR_ANCESTRY)
3312 return err;
3313 ref_has_moved = 1;
3315 if (!ref_has_moved)
3316 return NULL;
3318 /* Switching to a rebased branch with the same reference name. */
3319 err = got_object_id_str(&base_id_str,
3320 got_worktree_get_base_commit_id(worktree));
3321 if (err)
3322 return err;
3323 printf("Reference %s now points at a different branch\n",
3324 got_worktree_get_head_ref_name(worktree));
3325 printf("Switching work tree from %s to %s\n", base_id_str,
3326 got_worktree_get_head_ref_name(worktree));
3327 return NULL;
3330 static const struct got_error *
3331 check_rebase_or_histedit_in_progress(struct got_worktree *worktree)
3333 const struct got_error *err;
3334 int in_progress;
3336 err = got_worktree_rebase_in_progress(&in_progress, worktree);
3337 if (err)
3338 return err;
3339 if (in_progress)
3340 return got_error(GOT_ERR_REBASING);
3342 err = got_worktree_histedit_in_progress(&in_progress, worktree);
3343 if (err)
3344 return err;
3345 if (in_progress)
3346 return got_error(GOT_ERR_HISTEDIT_BUSY);
3348 return NULL;
3351 static const struct got_error *
3352 check_merge_in_progress(struct got_worktree *worktree,
3353 struct got_repository *repo)
3355 const struct got_error *err;
3356 int in_progress;
3358 err = got_worktree_merge_in_progress(&in_progress, worktree, repo);
3359 if (err)
3360 return err;
3361 if (in_progress)
3362 return got_error(GOT_ERR_MERGE_BUSY);
3364 return NULL;
3367 static const struct got_error *
3368 get_worktree_paths_from_argv(struct got_pathlist_head *paths, int argc,
3369 char *argv[], struct got_worktree *worktree)
3371 const struct got_error *err = NULL;
3372 char *path;
3373 struct got_pathlist_entry *new;
3374 int i;
3376 if (argc == 0) {
3377 path = strdup("");
3378 if (path == NULL)
3379 return got_error_from_errno("strdup");
3380 return got_pathlist_append(paths, path, NULL);
3383 for (i = 0; i < argc; i++) {
3384 err = got_worktree_resolve_path(&path, worktree, argv[i]);
3385 if (err)
3386 break;
3387 err = got_pathlist_insert(&new, paths, path, NULL);
3388 if (err || new == NULL /* duplicate */) {
3389 free(path);
3390 if (err)
3391 break;
3395 return err;
3398 static const struct got_error *
3399 wrap_not_worktree_error(const struct got_error *orig_err,
3400 const char *cmdname, const char *path)
3402 const struct got_error *err;
3403 struct got_repository *repo;
3404 static char msg[512];
3405 int *pack_fds = NULL;
3407 err = got_repo_pack_fds_open(&pack_fds);
3408 if (err)
3409 return err;
3411 err = got_repo_open(&repo, path, NULL, pack_fds);
3412 if (err)
3413 return orig_err;
3415 snprintf(msg, sizeof(msg),
3416 "'got %s' needs a work tree in addition to a git repository\n"
3417 "Work trees can be checked out from this Git repository with "
3418 "'got checkout'.\n"
3419 "The got(1) manual page contains more information.", cmdname);
3420 err = got_error_msg(GOT_ERR_NOT_WORKTREE, msg);
3421 got_repo_close(repo);
3422 if (pack_fds) {
3423 const struct got_error *pack_err =
3424 got_repo_pack_fds_close(pack_fds);
3425 if (err == NULL)
3426 err = pack_err;
3428 return err;
3431 static const struct got_error *
3432 cmd_update(int argc, char *argv[])
3434 const struct got_error *error = NULL;
3435 struct got_repository *repo = NULL;
3436 struct got_worktree *worktree = NULL;
3437 char *worktree_path = NULL;
3438 struct got_object_id *commit_id = NULL;
3439 char *commit_id_str = NULL;
3440 const char *branch_name = NULL;
3441 struct got_reference *head_ref = NULL;
3442 struct got_pathlist_head paths;
3443 struct got_pathlist_entry *pe;
3444 int ch, verbosity = 0;
3445 struct got_update_progress_arg upa;
3446 int *pack_fds = NULL;
3448 TAILQ_INIT(&paths);
3450 while ((ch = getopt(argc, argv, "b:c:q")) != -1) {
3451 switch (ch) {
3452 case 'b':
3453 branch_name = optarg;
3454 break;
3455 case 'c':
3456 commit_id_str = strdup(optarg);
3457 if (commit_id_str == NULL)
3458 return got_error_from_errno("strdup");
3459 break;
3460 case 'q':
3461 verbosity = -1;
3462 break;
3463 default:
3464 usage_update();
3465 /* NOTREACHED */
3469 argc -= optind;
3470 argv += optind;
3472 #ifndef PROFILE
3473 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
3474 "unveil", NULL) == -1)
3475 err(1, "pledge");
3476 #endif
3477 worktree_path = getcwd(NULL, 0);
3478 if (worktree_path == NULL) {
3479 error = got_error_from_errno("getcwd");
3480 goto done;
3483 error = got_repo_pack_fds_open(&pack_fds);
3484 if (error != NULL)
3485 goto done;
3487 error = got_worktree_open(&worktree, worktree_path);
3488 if (error) {
3489 if (error->code == GOT_ERR_NOT_WORKTREE)
3490 error = wrap_not_worktree_error(error, "update",
3491 worktree_path);
3492 goto done;
3495 error = check_rebase_or_histedit_in_progress(worktree);
3496 if (error)
3497 goto done;
3499 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
3500 NULL, pack_fds);
3501 if (error != NULL)
3502 goto done;
3504 error = apply_unveil(got_repo_get_path(repo), 0,
3505 got_worktree_get_root_path(worktree));
3506 if (error)
3507 goto done;
3509 error = check_merge_in_progress(worktree, repo);
3510 if (error)
3511 goto done;
3513 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
3514 if (error)
3515 goto done;
3517 error = got_ref_open(&head_ref, repo, branch_name ? branch_name :
3518 got_worktree_get_head_ref_name(worktree), 0);
3519 if (error != NULL)
3520 goto done;
3521 if (commit_id_str == NULL) {
3522 error = got_ref_resolve(&commit_id, repo, head_ref);
3523 if (error != NULL)
3524 goto done;
3525 error = got_object_id_str(&commit_id_str, commit_id);
3526 if (error != NULL)
3527 goto done;
3528 } else {
3529 struct got_reflist_head refs;
3530 TAILQ_INIT(&refs);
3531 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
3532 NULL);
3533 if (error)
3534 goto done;
3535 error = got_repo_match_object_id(&commit_id, NULL,
3536 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
3537 got_ref_list_free(&refs);
3538 free(commit_id_str);
3539 commit_id_str = NULL;
3540 if (error)
3541 goto done;
3542 error = got_object_id_str(&commit_id_str, commit_id);
3543 if (error)
3544 goto done;
3547 if (branch_name) {
3548 struct got_object_id *head_commit_id;
3549 TAILQ_FOREACH(pe, &paths, entry) {
3550 if (pe->path_len == 0)
3551 continue;
3552 error = got_error_msg(GOT_ERR_BAD_PATH,
3553 "switching between branches requires that "
3554 "the entire work tree gets updated");
3555 goto done;
3557 error = got_ref_resolve(&head_commit_id, repo, head_ref);
3558 if (error)
3559 goto done;
3560 error = check_linear_ancestry(commit_id, head_commit_id, 0,
3561 repo);
3562 free(head_commit_id);
3563 if (error != NULL)
3564 goto done;
3565 error = check_same_branch(commit_id, head_ref, NULL, repo);
3566 if (error)
3567 goto done;
3568 error = switch_head_ref(head_ref, commit_id, worktree, repo);
3569 if (error)
3570 goto done;
3571 } else {
3572 error = check_linear_ancestry(commit_id,
3573 got_worktree_get_base_commit_id(worktree), 0, repo);
3574 if (error != NULL) {
3575 if (error->code == GOT_ERR_ANCESTRY)
3576 error = got_error(GOT_ERR_BRANCH_MOVED);
3577 goto done;
3579 error = check_same_branch(commit_id, head_ref, NULL, repo);
3580 if (error)
3581 goto done;
3584 if (got_object_id_cmp(got_worktree_get_base_commit_id(worktree),
3585 commit_id) != 0) {
3586 error = got_worktree_set_base_commit_id(worktree, repo,
3587 commit_id);
3588 if (error)
3589 goto done;
3592 memset(&upa, 0, sizeof(upa));
3593 upa.verbosity = verbosity;
3594 error = got_worktree_checkout_files(worktree, &paths, repo,
3595 update_progress, &upa, check_cancelled, NULL);
3596 if (error != NULL)
3597 goto done;
3599 if (upa.did_something) {
3600 printf("Updated to %s: %s\n",
3601 got_worktree_get_head_ref_name(worktree), commit_id_str);
3602 } else
3603 printf("Already up-to-date\n");
3605 print_update_progress_stats(&upa);
3606 done:
3607 if (pack_fds) {
3608 const struct got_error *pack_err =
3609 got_repo_pack_fds_close(pack_fds);
3610 if (error == NULL)
3611 error = pack_err;
3613 free(worktree_path);
3614 TAILQ_FOREACH(pe, &paths, entry)
3615 free((char *)pe->path);
3616 got_pathlist_free(&paths);
3617 free(commit_id);
3618 free(commit_id_str);
3619 return error;
3622 static const struct got_error *
3623 diff_blobs(struct got_object_id *blob_id1, struct got_object_id *blob_id2,
3624 const char *path, int diff_context, int ignore_whitespace,
3625 int force_text_diff, struct got_repository *repo, FILE *outfile)
3627 const struct got_error *err = NULL;
3628 struct got_blob_object *blob1 = NULL, *blob2 = NULL;
3629 FILE *f1 = NULL, *f2 = NULL;
3630 int fd1 = -1, fd2 = -1;
3632 fd1 = got_opentempfd();
3633 if (fd1 == -1)
3634 return got_error_from_errno("got_opentempfd");
3635 fd2 = got_opentempfd();
3636 if (fd2 == -1) {
3637 err = got_error_from_errno("got_opentempfd");
3638 goto done;
3641 if (blob_id1) {
3642 err = got_object_open_as_blob(&blob1, repo, blob_id1, 8192,
3643 fd1);
3644 if (err)
3645 goto done;
3648 err = got_object_open_as_blob(&blob2, repo, blob_id2, 8192, fd2);
3649 if (err)
3650 goto done;
3652 f1 = got_opentemp();
3653 if (f1 == NULL) {
3654 err = got_error_from_errno("got_opentemp");
3655 goto done;
3657 f2 = got_opentemp();
3658 if (f2 == NULL) {
3659 err = got_error_from_errno("got_opentemp");
3660 goto done;
3663 while (path[0] == '/')
3664 path++;
3665 err = got_diff_blob(NULL, NULL, blob1, blob2, f1, f2, path, path,
3666 GOT_DIFF_ALGORITHM_PATIENCE, diff_context, ignore_whitespace,
3667 force_text_diff, outfile);
3668 done:
3669 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
3670 err = got_error_from_errno("close");
3671 if (blob1)
3672 got_object_blob_close(blob1);
3673 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
3674 err = got_error_from_errno("close");
3675 got_object_blob_close(blob2);
3676 if (f1 && fclose(f1) == EOF && err == NULL)
3677 err = got_error_from_errno("fclose");
3678 if (f2 && fclose(f2) == EOF && err == NULL)
3679 err = got_error_from_errno("fclose");
3680 return err;
3683 static const struct got_error *
3684 diff_trees(struct got_object_id *tree_id1, struct got_object_id *tree_id2,
3685 const char *path, int diff_context, int ignore_whitespace,
3686 int force_text_diff, struct got_repository *repo, FILE *outfile)
3688 const struct got_error *err = NULL;
3689 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
3690 struct got_diff_blob_output_unidiff_arg arg;
3691 FILE *f1 = NULL, *f2 = NULL;
3692 int fd1 = -1, fd2 = -1;
3694 if (tree_id1) {
3695 err = got_object_open_as_tree(&tree1, repo, tree_id1);
3696 if (err)
3697 goto done;
3698 fd1 = got_opentempfd();
3699 if (fd1 == -1) {
3700 err = got_error_from_errno("got_opentempfd");
3701 goto done;
3705 err = got_object_open_as_tree(&tree2, repo, tree_id2);
3706 if (err)
3707 goto done;
3709 f1 = got_opentemp();
3710 if (f1 == NULL) {
3711 err = got_error_from_errno("got_opentemp");
3712 goto done;
3715 f2 = got_opentemp();
3716 if (f2 == NULL) {
3717 err = got_error_from_errno("got_opentemp");
3718 goto done;
3720 fd2 = got_opentempfd();
3721 if (fd2 == -1) {
3722 err = got_error_from_errno("got_opentempfd");
3723 goto done;
3725 arg.diff_context = diff_context;
3726 arg.ignore_whitespace = ignore_whitespace;
3727 arg.force_text_diff = force_text_diff;
3728 arg.diff_algo = GOT_DIFF_ALGORITHM_PATIENCE;
3729 arg.outfile = outfile;
3730 arg.lines = NULL;
3731 arg.nlines = 0;
3732 while (path[0] == '/')
3733 path++;
3734 err = got_diff_tree(tree1, tree2, f1, f2, fd1, fd2, path, path, repo,
3735 got_diff_blob_output_unidiff, &arg, 1);
3736 done:
3737 if (tree1)
3738 got_object_tree_close(tree1);
3739 if (tree2)
3740 got_object_tree_close(tree2);
3741 if (f1 && fclose(f1) == EOF && err == NULL)
3742 err = got_error_from_errno("fclose");
3743 if (f2 && fclose(f2) == EOF && err == NULL)
3744 err = got_error_from_errno("fclose");
3745 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
3746 err = got_error_from_errno("close");
3747 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
3748 err = got_error_from_errno("close");
3749 return err;
3752 static const struct got_error *
3753 get_changed_paths(struct got_pathlist_head *paths,
3754 struct got_commit_object *commit, struct got_repository *repo)
3756 const struct got_error *err = NULL;
3757 struct got_object_id *tree_id1 = NULL, *tree_id2 = NULL;
3758 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
3759 struct got_object_qid *qid;
3761 qid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
3762 if (qid != NULL) {
3763 struct got_commit_object *pcommit;
3764 err = got_object_open_as_commit(&pcommit, repo,
3765 &qid->id);
3766 if (err)
3767 return err;
3769 tree_id1 = got_object_id_dup(
3770 got_object_commit_get_tree_id(pcommit));
3771 if (tree_id1 == NULL) {
3772 got_object_commit_close(pcommit);
3773 return got_error_from_errno("got_object_id_dup");
3775 got_object_commit_close(pcommit);
3779 if (tree_id1) {
3780 err = got_object_open_as_tree(&tree1, repo, tree_id1);
3781 if (err)
3782 goto done;
3785 tree_id2 = got_object_commit_get_tree_id(commit);
3786 err = got_object_open_as_tree(&tree2, repo, tree_id2);
3787 if (err)
3788 goto done;
3790 err = got_diff_tree(tree1, tree2, NULL, NULL, -1, -1, "", "", repo,
3791 got_diff_tree_collect_changed_paths, paths, 0);
3792 done:
3793 if (tree1)
3794 got_object_tree_close(tree1);
3795 if (tree2)
3796 got_object_tree_close(tree2);
3797 free(tree_id1);
3798 return err;
3801 static const struct got_error *
3802 print_patch(struct got_commit_object *commit, struct got_object_id *id,
3803 const char *path, int diff_context, struct got_repository *repo,
3804 FILE *outfile)
3806 const struct got_error *err = NULL;
3807 struct got_commit_object *pcommit = NULL;
3808 char *id_str1 = NULL, *id_str2 = NULL;
3809 struct got_object_id *obj_id1 = NULL, *obj_id2 = NULL;
3810 struct got_object_qid *qid;
3812 qid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
3813 if (qid != NULL) {
3814 err = got_object_open_as_commit(&pcommit, repo,
3815 &qid->id);
3816 if (err)
3817 return err;
3818 err = got_object_id_str(&id_str1, &qid->id);
3819 if (err)
3820 goto done;
3823 err = got_object_id_str(&id_str2, id);
3824 if (err)
3825 goto done;
3827 if (path && path[0] != '\0') {
3828 int obj_type;
3829 err = got_object_id_by_path(&obj_id2, repo, commit, path);
3830 if (err)
3831 goto done;
3832 if (pcommit) {
3833 err = got_object_id_by_path(&obj_id1, repo,
3834 pcommit, path);
3835 if (err) {
3836 if (err->code != GOT_ERR_NO_TREE_ENTRY) {
3837 free(obj_id2);
3838 goto done;
3842 err = got_object_get_type(&obj_type, repo, obj_id2);
3843 if (err) {
3844 free(obj_id2);
3845 goto done;
3847 fprintf(outfile,
3848 "diff %s %s\n", id_str1 ? id_str1 : "/dev/null", id_str2);
3849 fprintf(outfile, "commit - %s\n",
3850 id_str1 ? id_str1 : "/dev/null");
3851 fprintf(outfile, "commit + %s\n", id_str2);
3852 switch (obj_type) {
3853 case GOT_OBJ_TYPE_BLOB:
3854 err = diff_blobs(obj_id1, obj_id2, path, diff_context,
3855 0, 0, repo, outfile);
3856 break;
3857 case GOT_OBJ_TYPE_TREE:
3858 err = diff_trees(obj_id1, obj_id2, path, diff_context,
3859 0, 0, repo, outfile);
3860 break;
3861 default:
3862 err = got_error(GOT_ERR_OBJ_TYPE);
3863 break;
3865 free(obj_id1);
3866 free(obj_id2);
3867 } else {
3868 obj_id2 = got_object_commit_get_tree_id(commit);
3869 if (pcommit)
3870 obj_id1 = got_object_commit_get_tree_id(pcommit);
3871 fprintf(outfile,
3872 "diff %s %s\n", id_str1 ? id_str1 : "/dev/null", id_str2);
3873 fprintf(outfile, "commit - %s\n",
3874 id_str1 ? id_str1 : "/dev/null");
3875 fprintf(outfile, "commit + %s\n", id_str2);
3876 err = diff_trees(obj_id1, obj_id2, "", diff_context, 0, 0,
3877 repo, outfile);
3879 done:
3880 free(id_str1);
3881 free(id_str2);
3882 if (pcommit)
3883 got_object_commit_close(pcommit);
3884 return err;
3887 static char *
3888 get_datestr(time_t *time, char *datebuf)
3890 struct tm mytm, *tm;
3891 char *p, *s;
3893 tm = gmtime_r(time, &mytm);
3894 if (tm == NULL)
3895 return NULL;
3896 s = asctime_r(tm, datebuf);
3897 if (s == NULL)
3898 return NULL;
3899 p = strchr(s, '\n');
3900 if (p)
3901 *p = '\0';
3902 return s;
3905 static const struct got_error *
3906 match_commit(int *have_match, struct got_object_id *id,
3907 struct got_commit_object *commit, regex_t *regex)
3909 const struct got_error *err = NULL;
3910 regmatch_t regmatch;
3911 char *id_str = NULL, *logmsg = NULL;
3913 *have_match = 0;
3915 err = got_object_id_str(&id_str, id);
3916 if (err)
3917 return err;
3919 err = got_object_commit_get_logmsg(&logmsg, commit);
3920 if (err)
3921 goto done;
3923 if (regexec(regex, got_object_commit_get_author(commit), 1,
3924 &regmatch, 0) == 0 ||
3925 regexec(regex, got_object_commit_get_committer(commit), 1,
3926 &regmatch, 0) == 0 ||
3927 regexec(regex, id_str, 1, &regmatch, 0) == 0 ||
3928 regexec(regex, logmsg, 1, &regmatch, 0) == 0)
3929 *have_match = 1;
3930 done:
3931 free(id_str);
3932 free(logmsg);
3933 return err;
3936 static void
3937 match_changed_paths(int *have_match, struct got_pathlist_head *changed_paths,
3938 regex_t *regex)
3940 regmatch_t regmatch;
3941 struct got_pathlist_entry *pe;
3943 *have_match = 0;
3945 TAILQ_FOREACH(pe, changed_paths, entry) {
3946 if (regexec(regex, pe->path, 1, &regmatch, 0) == 0) {
3947 *have_match = 1;
3948 break;
3953 static const struct got_error *
3954 match_patch(int *have_match, struct got_commit_object *commit,
3955 struct got_object_id *id, const char *path, int diff_context,
3956 struct got_repository *repo, regex_t *regex, FILE *f)
3958 const struct got_error *err = NULL;
3959 char *line = NULL;
3960 size_t linesize = 0;
3961 regmatch_t regmatch;
3963 *have_match = 0;
3965 err = got_opentemp_truncate(f);
3966 if (err)
3967 return err;
3969 err = print_patch(commit, id, path, diff_context, repo, f);
3970 if (err)
3971 goto done;
3973 if (fseeko(f, 0L, SEEK_SET) == -1) {
3974 err = got_error_from_errno("fseeko");
3975 goto done;
3978 while (getline(&line, &linesize, f) != -1) {
3979 if (regexec(regex, line, 1, &regmatch, 0) == 0) {
3980 *have_match = 1;
3981 break;
3984 done:
3985 free(line);
3986 return err;
3989 #define GOT_COMMIT_SEP_STR "-----------------------------------------------\n"
3991 static const struct got_error*
3992 build_refs_str(char **refs_str, struct got_reflist_head *refs,
3993 struct got_object_id *id, struct got_repository *repo,
3994 int local_only)
3996 static const struct got_error *err = NULL;
3997 struct got_reflist_entry *re;
3998 char *s;
3999 const char *name;
4001 *refs_str = NULL;
4003 TAILQ_FOREACH(re, refs, entry) {
4004 struct got_tag_object *tag = NULL;
4005 struct got_object_id *ref_id;
4006 int cmp;
4008 name = got_ref_get_name(re->ref);
4009 if (strcmp(name, GOT_REF_HEAD) == 0)
4010 continue;
4011 if (strncmp(name, "refs/", 5) == 0)
4012 name += 5;
4013 if (strncmp(name, "got/", 4) == 0)
4014 continue;
4015 if (strncmp(name, "heads/", 6) == 0)
4016 name += 6;
4017 if (strncmp(name, "remotes/", 8) == 0) {
4018 if (local_only)
4019 continue;
4020 name += 8;
4021 s = strstr(name, "/" GOT_REF_HEAD);
4022 if (s != NULL && s[strlen(s)] == '\0')
4023 continue;
4025 err = got_ref_resolve(&ref_id, repo, re->ref);
4026 if (err)
4027 break;
4028 if (strncmp(name, "tags/", 5) == 0) {
4029 err = got_object_open_as_tag(&tag, repo, ref_id);
4030 if (err) {
4031 if (err->code != GOT_ERR_OBJ_TYPE) {
4032 free(ref_id);
4033 break;
4035 /* Ref points at something other than a tag. */
4036 err = NULL;
4037 tag = NULL;
4040 cmp = got_object_id_cmp(tag ?
4041 got_object_tag_get_object_id(tag) : ref_id, id);
4042 free(ref_id);
4043 if (tag)
4044 got_object_tag_close(tag);
4045 if (cmp != 0)
4046 continue;
4047 s = *refs_str;
4048 if (asprintf(refs_str, "%s%s%s", s ? s : "",
4049 s ? ", " : "", name) == -1) {
4050 err = got_error_from_errno("asprintf");
4051 free(s);
4052 *refs_str = NULL;
4053 break;
4055 free(s);
4058 return err;
4061 static const struct got_error *
4062 print_commit_oneline(struct got_commit_object *commit, struct got_object_id *id,
4063 struct got_repository *repo, struct got_reflist_object_id_map *refs_idmap)
4065 const struct got_error *err = NULL;
4066 char *ref_str = NULL, *id_str = NULL, *logmsg0 = NULL;
4067 char *comma, *s, *nl;
4068 struct got_reflist_head *refs;
4069 char datebuf[12]; /* YYYY-MM-DD + SPACE + NUL */
4070 struct tm tm;
4071 time_t committer_time;
4073 refs = got_reflist_object_id_map_lookup(refs_idmap, id);
4074 if (refs) {
4075 err = build_refs_str(&ref_str, refs, id, repo, 1);
4076 if (err)
4077 return err;
4079 /* Display the first matching ref only. */
4080 if (ref_str && (comma = strchr(ref_str, ',')) != NULL)
4081 *comma = '\0';
4084 if (ref_str == NULL) {
4085 err = got_object_id_str(&id_str, id);
4086 if (err)
4087 return err;
4090 committer_time = got_object_commit_get_committer_time(commit);
4091 if (gmtime_r(&committer_time, &tm) == NULL) {
4092 err = got_error_from_errno("gmtime_r");
4093 goto done;
4095 if (strftime(datebuf, sizeof(datebuf), "%G-%m-%d ", &tm) == 0) {
4096 err = got_error(GOT_ERR_NO_SPACE);
4097 goto done;
4100 err = got_object_commit_get_logmsg(&logmsg0, commit);
4101 if (err)
4102 goto done;
4104 s = logmsg0;
4105 while (isspace((unsigned char)s[0]))
4106 s++;
4108 nl = strchr(s, '\n');
4109 if (nl) {
4110 *nl = '\0';
4113 if (ref_str)
4114 printf("%s%-7s %s\n", datebuf, ref_str, s);
4115 else
4116 printf("%s%.7s %s\n", datebuf, id_str, s);
4118 if (fflush(stdout) != 0 && err == NULL)
4119 err = got_error_from_errno("fflush");
4120 done:
4121 free(id_str);
4122 free(ref_str);
4123 free(logmsg0);
4124 return err;
4127 static const struct got_error *
4128 print_commit(struct got_commit_object *commit, struct got_object_id *id,
4129 struct got_repository *repo, const char *path,
4130 struct got_pathlist_head *changed_paths, int show_patch,
4131 int diff_context, struct got_reflist_object_id_map *refs_idmap,
4132 const char *custom_refs_str)
4134 const struct got_error *err = NULL;
4135 char *id_str, *datestr, *logmsg0, *logmsg, *line;
4136 char datebuf[26];
4137 time_t committer_time;
4138 const char *author, *committer;
4139 char *refs_str = NULL;
4141 err = got_object_id_str(&id_str, id);
4142 if (err)
4143 return err;
4145 if (custom_refs_str == NULL) {
4146 struct got_reflist_head *refs;
4147 refs = got_reflist_object_id_map_lookup(refs_idmap, id);
4148 if (refs) {
4149 err = build_refs_str(&refs_str, refs, id, repo, 0);
4150 if (err)
4151 goto done;
4155 printf(GOT_COMMIT_SEP_STR);
4156 if (custom_refs_str)
4157 printf("commit %s (%s)\n", id_str, custom_refs_str);
4158 else
4159 printf("commit %s%s%s%s\n", id_str, refs_str ? " (" : "",
4160 refs_str ? refs_str : "", refs_str ? ")" : "");
4161 free(id_str);
4162 id_str = NULL;
4163 free(refs_str);
4164 refs_str = NULL;
4165 printf("from: %s\n", got_object_commit_get_author(commit));
4166 committer_time = got_object_commit_get_committer_time(commit);
4167 datestr = get_datestr(&committer_time, datebuf);
4168 if (datestr)
4169 printf("date: %s UTC\n", datestr);
4170 author = got_object_commit_get_author(commit);
4171 committer = got_object_commit_get_committer(commit);
4172 if (strcmp(author, committer) != 0)
4173 printf("via: %s\n", committer);
4174 if (got_object_commit_get_nparents(commit) > 1) {
4175 const struct got_object_id_queue *parent_ids;
4176 struct got_object_qid *qid;
4177 int n = 1;
4178 parent_ids = got_object_commit_get_parent_ids(commit);
4179 STAILQ_FOREACH(qid, parent_ids, entry) {
4180 err = got_object_id_str(&id_str, &qid->id);
4181 if (err)
4182 goto done;
4183 printf("parent %d: %s\n", n++, id_str);
4184 free(id_str);
4185 id_str = NULL;
4189 err = got_object_commit_get_logmsg(&logmsg0, commit);
4190 if (err)
4191 goto done;
4193 logmsg = logmsg0;
4194 do {
4195 line = strsep(&logmsg, "\n");
4196 if (line)
4197 printf(" %s\n", line);
4198 } while (line);
4199 free(logmsg0);
4201 if (changed_paths) {
4202 struct got_pathlist_entry *pe;
4203 TAILQ_FOREACH(pe, changed_paths, entry) {
4204 struct got_diff_changed_path *cp = pe->data;
4205 printf(" %c %s\n", cp->status, pe->path);
4207 printf("\n");
4209 if (show_patch) {
4210 err = print_patch(commit, id, path, diff_context, repo, stdout);
4211 if (err == 0)
4212 printf("\n");
4215 if (fflush(stdout) != 0 && err == NULL)
4216 err = got_error_from_errno("fflush");
4217 done:
4218 free(id_str);
4219 free(refs_str);
4220 return err;
4223 static const struct got_error *
4224 print_commits(struct got_object_id *root_id, struct got_object_id *end_id,
4225 struct got_repository *repo, const char *path, int show_changed_paths,
4226 int show_patch, const char *search_pattern, int diff_context, int limit,
4227 int log_branches, int reverse_display_order,
4228 struct got_reflist_object_id_map *refs_idmap, int one_line,
4229 FILE *tmpfile)
4231 const struct got_error *err;
4232 struct got_commit_graph *graph;
4233 regex_t regex;
4234 int have_match;
4235 struct got_object_id_queue reversed_commits;
4236 struct got_object_qid *qid;
4237 struct got_commit_object *commit;
4238 struct got_pathlist_head changed_paths;
4239 struct got_pathlist_entry *pe;
4241 STAILQ_INIT(&reversed_commits);
4242 TAILQ_INIT(&changed_paths);
4244 if (search_pattern && regcomp(&regex, search_pattern,
4245 REG_EXTENDED | REG_NOSUB | REG_NEWLINE))
4246 return got_error_msg(GOT_ERR_REGEX, search_pattern);
4248 err = got_commit_graph_open(&graph, path, !log_branches);
4249 if (err)
4250 return err;
4251 err = got_commit_graph_iter_start(graph, root_id, repo,
4252 check_cancelled, NULL);
4253 if (err)
4254 goto done;
4255 for (;;) {
4256 struct got_object_id id;
4258 if (sigint_received || sigpipe_received)
4259 break;
4261 err = got_commit_graph_iter_next(&id, graph, repo,
4262 check_cancelled, NULL);
4263 if (err) {
4264 if (err->code == GOT_ERR_ITER_COMPLETED)
4265 err = NULL;
4266 break;
4269 err = got_object_open_as_commit(&commit, repo, &id);
4270 if (err)
4271 break;
4273 if (show_changed_paths && !reverse_display_order) {
4274 err = get_changed_paths(&changed_paths, commit, repo);
4275 if (err)
4276 break;
4279 if (search_pattern) {
4280 err = match_commit(&have_match, &id, commit, &regex);
4281 if (err) {
4282 got_object_commit_close(commit);
4283 break;
4285 if (have_match == 0 && show_changed_paths)
4286 match_changed_paths(&have_match,
4287 &changed_paths, &regex);
4288 if (have_match == 0 && show_patch) {
4289 err = match_patch(&have_match, commit, &id,
4290 path, diff_context, repo, &regex,
4291 tmpfile);
4292 if (err)
4293 break;
4295 if (have_match == 0) {
4296 got_object_commit_close(commit);
4297 TAILQ_FOREACH(pe, &changed_paths, entry) {
4298 free((char *)pe->path);
4299 free(pe->data);
4301 got_pathlist_free(&changed_paths);
4302 continue;
4306 if (reverse_display_order) {
4307 err = got_object_qid_alloc(&qid, &id);
4308 if (err)
4309 break;
4310 STAILQ_INSERT_HEAD(&reversed_commits, qid, entry);
4311 got_object_commit_close(commit);
4312 } else {
4313 if (one_line)
4314 err = print_commit_oneline(commit, &id,
4315 repo, refs_idmap);
4316 else
4317 err = print_commit(commit, &id, repo, path,
4318 show_changed_paths ? &changed_paths : NULL,
4319 show_patch, diff_context, refs_idmap, NULL);
4320 got_object_commit_close(commit);
4321 if (err)
4322 break;
4324 if ((limit && --limit == 0) ||
4325 (end_id && got_object_id_cmp(&id, end_id) == 0))
4326 break;
4328 TAILQ_FOREACH(pe, &changed_paths, entry) {
4329 free((char *)pe->path);
4330 free(pe->data);
4332 got_pathlist_free(&changed_paths);
4334 if (reverse_display_order) {
4335 STAILQ_FOREACH(qid, &reversed_commits, entry) {
4336 err = got_object_open_as_commit(&commit, repo,
4337 &qid->id);
4338 if (err)
4339 break;
4340 if (show_changed_paths) {
4341 err = get_changed_paths(&changed_paths,
4342 commit, repo);
4343 if (err)
4344 break;
4346 if (one_line)
4347 err = print_commit_oneline(commit, &qid->id,
4348 repo, refs_idmap);
4349 else
4350 err = print_commit(commit, &qid->id, repo, path,
4351 show_changed_paths ? &changed_paths : NULL,
4352 show_patch, diff_context, refs_idmap, NULL);
4353 got_object_commit_close(commit);
4354 if (err)
4355 break;
4356 TAILQ_FOREACH(pe, &changed_paths, entry) {
4357 free((char *)pe->path);
4358 free(pe->data);
4360 got_pathlist_free(&changed_paths);
4363 done:
4364 while (!STAILQ_EMPTY(&reversed_commits)) {
4365 qid = STAILQ_FIRST(&reversed_commits);
4366 STAILQ_REMOVE_HEAD(&reversed_commits, entry);
4367 got_object_qid_free(qid);
4369 TAILQ_FOREACH(pe, &changed_paths, entry) {
4370 free((char *)pe->path);
4371 free(pe->data);
4373 got_pathlist_free(&changed_paths);
4374 if (search_pattern)
4375 regfree(&regex);
4376 got_commit_graph_close(graph);
4377 return err;
4380 __dead static void
4381 usage_log(void)
4383 fprintf(stderr, "usage: %s log [-bPpRs] [-C number] [-c commit] [-l N] "
4384 "[-r repository-path] [-S search-pattern] [-x commit] [path]\n",
4385 getprogname());
4386 exit(1);
4389 static int
4390 get_default_log_limit(void)
4392 const char *got_default_log_limit;
4393 long long n;
4394 const char *errstr;
4396 got_default_log_limit = getenv("GOT_LOG_DEFAULT_LIMIT");
4397 if (got_default_log_limit == NULL)
4398 return 0;
4399 n = strtonum(got_default_log_limit, 0, INT_MAX, &errstr);
4400 if (errstr != NULL)
4401 return 0;
4402 return n;
4405 static const struct got_error *
4406 cmd_log(int argc, char *argv[])
4408 const struct got_error *error;
4409 struct got_repository *repo = NULL;
4410 struct got_worktree *worktree = NULL;
4411 struct got_object_id *start_id = NULL, *end_id = NULL;
4412 char *repo_path = NULL, *path = NULL, *cwd = NULL, *in_repo_path = NULL;
4413 const char *start_commit = NULL, *end_commit = NULL;
4414 const char *search_pattern = NULL;
4415 int diff_context = -1, ch;
4416 int show_changed_paths = 0, show_patch = 0, limit = 0, log_branches = 0;
4417 int reverse_display_order = 0, one_line = 0;
4418 const char *errstr;
4419 struct got_reflist_head refs;
4420 struct got_reflist_object_id_map *refs_idmap = NULL;
4421 FILE *tmpfile = NULL;
4422 int *pack_fds = NULL;
4424 TAILQ_INIT(&refs);
4426 #ifndef PROFILE
4427 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
4428 NULL)
4429 == -1)
4430 err(1, "pledge");
4431 #endif
4433 limit = get_default_log_limit();
4435 while ((ch = getopt(argc, argv, "bC:c:l:PpRr:S:sx:")) != -1) {
4436 switch (ch) {
4437 case 'b':
4438 log_branches = 1;
4439 break;
4440 case 'C':
4441 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
4442 &errstr);
4443 if (errstr != NULL)
4444 errx(1, "number of context lines is %s: %s",
4445 errstr, optarg);
4446 break;
4447 case 'c':
4448 start_commit = optarg;
4449 break;
4450 case 'l':
4451 limit = strtonum(optarg, 0, INT_MAX, &errstr);
4452 if (errstr != NULL)
4453 errx(1, "number of commits is %s: %s",
4454 errstr, optarg);
4455 break;
4456 case 'P':
4457 show_changed_paths = 1;
4458 break;
4459 case 'p':
4460 show_patch = 1;
4461 break;
4462 case 'R':
4463 reverse_display_order = 1;
4464 break;
4465 case 'r':
4466 repo_path = realpath(optarg, NULL);
4467 if (repo_path == NULL)
4468 return got_error_from_errno2("realpath",
4469 optarg);
4470 got_path_strip_trailing_slashes(repo_path);
4471 break;
4472 case 'S':
4473 search_pattern = optarg;
4474 break;
4475 case 's':
4476 one_line = 1;
4477 break;
4478 case 'x':
4479 end_commit = optarg;
4480 break;
4481 default:
4482 usage_log();
4483 /* NOTREACHED */
4487 argc -= optind;
4488 argv += optind;
4490 if (diff_context == -1)
4491 diff_context = 3;
4492 else if (!show_patch)
4493 errx(1, "-C requires -p");
4495 if (one_line && (show_patch || show_changed_paths))
4496 errx(1, "cannot use -s with -p or -P");
4498 cwd = getcwd(NULL, 0);
4499 if (cwd == NULL) {
4500 error = got_error_from_errno("getcwd");
4501 goto done;
4504 error = got_repo_pack_fds_open(&pack_fds);
4505 if (error != NULL)
4506 goto done;
4508 if (repo_path == NULL) {
4509 error = got_worktree_open(&worktree, cwd);
4510 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4511 goto done;
4512 error = NULL;
4515 if (argc == 1) {
4516 if (worktree) {
4517 error = got_worktree_resolve_path(&path, worktree,
4518 argv[0]);
4519 if (error)
4520 goto done;
4521 } else {
4522 path = strdup(argv[0]);
4523 if (path == NULL) {
4524 error = got_error_from_errno("strdup");
4525 goto done;
4528 } else if (argc != 0)
4529 usage_log();
4531 if (repo_path == NULL) {
4532 repo_path = worktree ?
4533 strdup(got_worktree_get_repo_path(worktree)) : strdup(cwd);
4535 if (repo_path == NULL) {
4536 error = got_error_from_errno("strdup");
4537 goto done;
4540 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
4541 if (error != NULL)
4542 goto done;
4544 error = apply_unveil(got_repo_get_path(repo), 1,
4545 worktree ? got_worktree_get_root_path(worktree) : NULL);
4546 if (error)
4547 goto done;
4549 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
4550 if (error)
4551 goto done;
4553 error = got_reflist_object_id_map_create(&refs_idmap, &refs, repo);
4554 if (error)
4555 goto done;
4557 if (start_commit == NULL) {
4558 struct got_reference *head_ref;
4559 struct got_commit_object *commit = NULL;
4560 error = got_ref_open(&head_ref, repo,
4561 worktree ? got_worktree_get_head_ref_name(worktree)
4562 : GOT_REF_HEAD, 0);
4563 if (error != NULL)
4564 goto done;
4565 error = got_ref_resolve(&start_id, repo, head_ref);
4566 got_ref_close(head_ref);
4567 if (error != NULL)
4568 goto done;
4569 error = got_object_open_as_commit(&commit, repo,
4570 start_id);
4571 if (error != NULL)
4572 goto done;
4573 got_object_commit_close(commit);
4574 } else {
4575 error = got_repo_match_object_id(&start_id, NULL,
4576 start_commit, GOT_OBJ_TYPE_COMMIT, &refs, repo);
4577 if (error != NULL)
4578 goto done;
4580 if (end_commit != NULL) {
4581 error = got_repo_match_object_id(&end_id, NULL,
4582 end_commit, GOT_OBJ_TYPE_COMMIT, &refs, repo);
4583 if (error != NULL)
4584 goto done;
4587 if (worktree) {
4589 * If a path was specified on the command line it was resolved
4590 * to a path in the work tree above. Prepend the work tree's
4591 * path prefix to obtain the corresponding in-repository path.
4593 if (path) {
4594 const char *prefix;
4595 prefix = got_worktree_get_path_prefix(worktree);
4596 if (asprintf(&in_repo_path, "%s%s%s", prefix,
4597 (path[0] != '\0') ? "/" : "", path) == -1) {
4598 error = got_error_from_errno("asprintf");
4599 goto done;
4602 } else
4603 error = got_repo_map_path(&in_repo_path, repo,
4604 path ? path : "");
4605 if (error != NULL)
4606 goto done;
4607 if (in_repo_path) {
4608 free(path);
4609 path = in_repo_path;
4612 if (worktree) {
4613 /* Release work tree lock. */
4614 got_worktree_close(worktree);
4615 worktree = NULL;
4618 if (search_pattern && show_patch) {
4619 tmpfile = got_opentemp();
4620 if (tmpfile == NULL) {
4621 error = got_error_from_errno("got_opentemp");
4622 goto done;
4626 error = print_commits(start_id, end_id, repo, path ? path : "",
4627 show_changed_paths, show_patch, search_pattern, diff_context,
4628 limit, log_branches, reverse_display_order, refs_idmap, one_line,
4629 tmpfile);
4630 done:
4631 free(path);
4632 free(repo_path);
4633 free(cwd);
4634 if (worktree)
4635 got_worktree_close(worktree);
4636 if (repo) {
4637 const struct got_error *close_err = got_repo_close(repo);
4638 if (error == NULL)
4639 error = close_err;
4641 if (pack_fds) {
4642 const struct got_error *pack_err =
4643 got_repo_pack_fds_close(pack_fds);
4644 if (error == NULL)
4645 error = pack_err;
4647 if (refs_idmap)
4648 got_reflist_object_id_map_free(refs_idmap);
4649 if (tmpfile && fclose(tmpfile) == EOF && error == NULL)
4650 error = got_error_from_errno("fclose");
4651 got_ref_list_free(&refs);
4652 return error;
4655 __dead static void
4656 usage_diff(void)
4658 fprintf(stderr, "usage: %s diff [-aPsw] [-C number] [-c commit] "
4659 "[-r repository-path] [object1 object2 | path ...]\n",
4660 getprogname());
4661 exit(1);
4664 struct print_diff_arg {
4665 struct got_repository *repo;
4666 struct got_worktree *worktree;
4667 int diff_context;
4668 const char *id_str;
4669 int header_shown;
4670 int diff_staged;
4671 enum got_diff_algorithm diff_algo;
4672 int ignore_whitespace;
4673 int force_text_diff;
4674 FILE *f1;
4675 FILE *f2;
4679 * Create a file which contains the target path of a symlink so we can feed
4680 * it as content to the diff engine.
4682 static const struct got_error *
4683 get_symlink_target_file(int *fd, int dirfd, const char *de_name,
4684 const char *abspath)
4686 const struct got_error *err = NULL;
4687 char target_path[PATH_MAX];
4688 ssize_t target_len, outlen;
4690 *fd = -1;
4692 if (dirfd != -1) {
4693 target_len = readlinkat(dirfd, de_name, target_path, PATH_MAX);
4694 if (target_len == -1)
4695 return got_error_from_errno2("readlinkat", abspath);
4696 } else {
4697 target_len = readlink(abspath, target_path, PATH_MAX);
4698 if (target_len == -1)
4699 return got_error_from_errno2("readlink", abspath);
4702 *fd = got_opentempfd();
4703 if (*fd == -1)
4704 return got_error_from_errno("got_opentempfd");
4706 outlen = write(*fd, target_path, target_len);
4707 if (outlen == -1) {
4708 err = got_error_from_errno("got_opentempfd");
4709 goto done;
4712 if (lseek(*fd, 0, SEEK_SET) == -1) {
4713 err = got_error_from_errno2("lseek", abspath);
4714 goto done;
4716 done:
4717 if (err) {
4718 close(*fd);
4719 *fd = -1;
4721 return err;
4724 static const struct got_error *
4725 print_diff(void *arg, unsigned char status, unsigned char staged_status,
4726 const char *path, struct got_object_id *blob_id,
4727 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
4728 int dirfd, const char *de_name)
4730 struct print_diff_arg *a = arg;
4731 const struct got_error *err = NULL;
4732 struct got_blob_object *blob1 = NULL;
4733 int fd = -1, fd1 = -1, fd2 = -1;
4734 FILE *f2 = NULL;
4735 char *abspath = NULL, *label1 = NULL;
4736 struct stat sb;
4737 off_t size1 = 0;
4738 int f2_exists = 0;
4740 memset(&sb, 0, sizeof(sb));
4742 if (a->diff_staged) {
4743 if (staged_status != GOT_STATUS_MODIFY &&
4744 staged_status != GOT_STATUS_ADD &&
4745 staged_status != GOT_STATUS_DELETE)
4746 return NULL;
4747 } else {
4748 if (staged_status == GOT_STATUS_DELETE)
4749 return NULL;
4750 if (status == GOT_STATUS_NONEXISTENT)
4751 return got_error_set_errno(ENOENT, path);
4752 if (status != GOT_STATUS_MODIFY &&
4753 status != GOT_STATUS_ADD &&
4754 status != GOT_STATUS_DELETE &&
4755 status != GOT_STATUS_CONFLICT)
4756 return NULL;
4759 err = got_opentemp_truncate(a->f1);
4760 if (err)
4761 return got_error_from_errno("got_opentemp_truncate");
4762 err = got_opentemp_truncate(a->f2);
4763 if (err)
4764 return got_error_from_errno("got_opentemp_truncate");
4766 if (!a->header_shown) {
4767 printf("diff %s%s\n", a->diff_staged ? "-s " : "",
4768 got_worktree_get_root_path(a->worktree));
4769 printf("commit - %s\n", a->id_str);
4770 printf("path + %s%s\n",
4771 got_worktree_get_root_path(a->worktree),
4772 a->diff_staged ? " (staged changes)" : "");
4773 a->header_shown = 1;
4776 if (a->diff_staged) {
4777 const char *label1 = NULL, *label2 = NULL;
4778 switch (staged_status) {
4779 case GOT_STATUS_MODIFY:
4780 label1 = path;
4781 label2 = path;
4782 break;
4783 case GOT_STATUS_ADD:
4784 label2 = path;
4785 break;
4786 case GOT_STATUS_DELETE:
4787 label1 = path;
4788 break;
4789 default:
4790 return got_error(GOT_ERR_FILE_STATUS);
4792 fd1 = got_opentempfd();
4793 if (fd1 == -1) {
4794 err = got_error_from_errno("got_opentempfd");
4795 goto done;
4797 fd2 = got_opentempfd();
4798 if (fd2 == -1) {
4799 err = got_error_from_errno("got_opentempfd");
4800 goto done;
4802 err = got_diff_objects_as_blobs(NULL, NULL, a->f1, a->f2,
4803 fd1, fd2, blob_id, staged_blob_id, label1, label2,
4804 a->diff_algo, a->diff_context, a->ignore_whitespace,
4805 a->force_text_diff, a->repo, stdout);
4806 goto done;
4809 fd1 = got_opentempfd();
4810 if (fd1 == -1) {
4811 err = got_error_from_errno("got_opentempfd");
4812 goto done;
4815 if (staged_status == GOT_STATUS_ADD ||
4816 staged_status == GOT_STATUS_MODIFY) {
4817 char *id_str;
4818 err = got_object_open_as_blob(&blob1, a->repo, staged_blob_id,
4819 8192, fd1);
4820 if (err)
4821 goto done;
4822 err = got_object_id_str(&id_str, staged_blob_id);
4823 if (err)
4824 goto done;
4825 if (asprintf(&label1, "%s (staged)", id_str) == -1) {
4826 err = got_error_from_errno("asprintf");
4827 free(id_str);
4828 goto done;
4830 free(id_str);
4831 } else if (status != GOT_STATUS_ADD) {
4832 err = got_object_open_as_blob(&blob1, a->repo, blob_id, 8192,
4833 fd1);
4834 if (err)
4835 goto done;
4838 if (status != GOT_STATUS_DELETE) {
4839 if (asprintf(&abspath, "%s/%s",
4840 got_worktree_get_root_path(a->worktree), path) == -1) {
4841 err = got_error_from_errno("asprintf");
4842 goto done;
4845 if (dirfd != -1) {
4846 fd = openat(dirfd, de_name,
4847 O_RDONLY | O_NOFOLLOW | O_CLOEXEC);
4848 if (fd == -1) {
4849 if (!got_err_open_nofollow_on_symlink()) {
4850 err = got_error_from_errno2("openat",
4851 abspath);
4852 goto done;
4854 err = get_symlink_target_file(&fd, dirfd,
4855 de_name, abspath);
4856 if (err)
4857 goto done;
4859 } else {
4860 fd = open(abspath, O_RDONLY | O_NOFOLLOW | O_CLOEXEC);
4861 if (fd == -1) {
4862 if (!got_err_open_nofollow_on_symlink()) {
4863 err = got_error_from_errno2("open",
4864 abspath);
4865 goto done;
4867 err = get_symlink_target_file(&fd, dirfd,
4868 de_name, abspath);
4869 if (err)
4870 goto done;
4873 if (fstatat(fd, abspath, &sb, AT_SYMLINK_NOFOLLOW) == -1) {
4874 err = got_error_from_errno2("fstatat", abspath);
4875 goto done;
4877 f2 = fdopen(fd, "r");
4878 if (f2 == NULL) {
4879 err = got_error_from_errno2("fdopen", abspath);
4880 goto done;
4882 fd = -1;
4883 f2_exists = 1;
4886 if (blob1) {
4887 err = got_object_blob_dump_to_file(&size1, NULL, NULL,
4888 a->f1, blob1);
4889 if (err)
4890 goto done;
4893 err = got_diff_blob_file(blob1, a->f1, size1, label1, f2 ? f2 : a->f2,
4894 f2_exists, &sb, path, GOT_DIFF_ALGORITHM_PATIENCE, a->diff_context,
4895 a->ignore_whitespace, a->force_text_diff, stdout);
4896 done:
4897 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
4898 err = got_error_from_errno("close");
4899 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
4900 err = got_error_from_errno("close");
4901 if (blob1)
4902 got_object_blob_close(blob1);
4903 if (fd != -1 && close(fd) == -1 && err == NULL)
4904 err = got_error_from_errno("close");
4905 if (f2 && fclose(f2) == EOF && err == NULL)
4906 err = got_error_from_errno("fclose");
4907 free(abspath);
4908 return err;
4911 static const struct got_error *
4912 cmd_diff(int argc, char *argv[])
4914 const struct got_error *error;
4915 struct got_repository *repo = NULL;
4916 struct got_worktree *worktree = NULL;
4917 char *cwd = NULL, *repo_path = NULL;
4918 const char *commit_args[2] = { NULL, NULL };
4919 int ncommit_args = 0;
4920 struct got_object_id *ids[2] = { NULL, NULL };
4921 char *labels[2] = { NULL, NULL };
4922 int type1 = GOT_OBJ_TYPE_ANY, type2 = GOT_OBJ_TYPE_ANY;
4923 int diff_context = 3, diff_staged = 0, ignore_whitespace = 0, ch, i;
4924 int force_text_diff = 0, force_path = 0, rflag = 0;
4925 const char *errstr;
4926 struct got_reflist_head refs;
4927 struct got_pathlist_head paths;
4928 struct got_pathlist_entry *pe;
4929 FILE *f1 = NULL, *f2 = NULL;
4930 int fd1 = -1, fd2 = -1;
4931 int *pack_fds = NULL;
4933 TAILQ_INIT(&refs);
4934 TAILQ_INIT(&paths);
4936 #ifndef PROFILE
4937 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
4938 NULL) == -1)
4939 err(1, "pledge");
4940 #endif
4942 while ((ch = getopt(argc, argv, "aC:c:Pr:sw")) != -1) {
4943 switch (ch) {
4944 case 'a':
4945 force_text_diff = 1;
4946 break;
4947 case 'C':
4948 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
4949 &errstr);
4950 if (errstr != NULL)
4951 errx(1, "number of context lines is %s: %s",
4952 errstr, optarg);
4953 break;
4954 case 'c':
4955 if (ncommit_args >= 2)
4956 errx(1, "too many -c options used");
4957 commit_args[ncommit_args++] = optarg;
4958 break;
4959 case 'P':
4960 force_path = 1;
4961 break;
4962 case 'r':
4963 repo_path = realpath(optarg, NULL);
4964 if (repo_path == NULL)
4965 return got_error_from_errno2("realpath",
4966 optarg);
4967 got_path_strip_trailing_slashes(repo_path);
4968 rflag = 1;
4969 break;
4970 case 's':
4971 diff_staged = 1;
4972 break;
4973 case 'w':
4974 ignore_whitespace = 1;
4975 break;
4976 default:
4977 usage_diff();
4978 /* NOTREACHED */
4982 argc -= optind;
4983 argv += optind;
4985 cwd = getcwd(NULL, 0);
4986 if (cwd == NULL) {
4987 error = got_error_from_errno("getcwd");
4988 goto done;
4991 error = got_repo_pack_fds_open(&pack_fds);
4992 if (error != NULL)
4993 goto done;
4995 if (repo_path == NULL) {
4996 error = got_worktree_open(&worktree, cwd);
4997 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4998 goto done;
4999 else
5000 error = NULL;
5001 if (worktree) {
5002 repo_path =
5003 strdup(got_worktree_get_repo_path(worktree));
5004 if (repo_path == NULL) {
5005 error = got_error_from_errno("strdup");
5006 goto done;
5008 } else {
5009 repo_path = strdup(cwd);
5010 if (repo_path == NULL) {
5011 error = got_error_from_errno("strdup");
5012 goto done;
5017 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
5018 free(repo_path);
5019 if (error != NULL)
5020 goto done;
5022 if (rflag || worktree == NULL || ncommit_args > 0) {
5023 if (force_path) {
5024 error = got_error_msg(GOT_ERR_NOT_IMPL,
5025 "-P option can only be used when diffing "
5026 "a work tree");
5027 goto done;
5029 if (diff_staged) {
5030 error = got_error_msg(GOT_ERR_NOT_IMPL,
5031 "-s option can only be used when diffing "
5032 "a work tree");
5033 goto done;
5037 error = apply_unveil(got_repo_get_path(repo), 1,
5038 worktree ? got_worktree_get_root_path(worktree) : NULL);
5039 if (error)
5040 goto done;
5042 if ((!force_path && argc == 2) || ncommit_args > 0) {
5043 int obj_type = (ncommit_args > 0 ?
5044 GOT_OBJ_TYPE_COMMIT : GOT_OBJ_TYPE_ANY);
5045 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
5046 NULL);
5047 if (error)
5048 goto done;
5049 for (i = 0; i < (ncommit_args > 0 ? ncommit_args : argc); i++) {
5050 const char *arg;
5051 if (ncommit_args > 0)
5052 arg = commit_args[i];
5053 else
5054 arg = argv[i];
5055 error = got_repo_match_object_id(&ids[i], &labels[i],
5056 arg, obj_type, &refs, repo);
5057 if (error) {
5058 if (error->code != GOT_ERR_NOT_REF &&
5059 error->code != GOT_ERR_NO_OBJ)
5060 goto done;
5061 if (ncommit_args > 0)
5062 goto done;
5063 error = NULL;
5064 break;
5069 f1 = got_opentemp();
5070 if (f1 == NULL) {
5071 error = got_error_from_errno("got_opentemp");
5072 goto done;
5075 f2 = got_opentemp();
5076 if (f2 == NULL) {
5077 error = got_error_from_errno("got_opentemp");
5078 goto done;
5081 if (ncommit_args == 0 && (ids[0] == NULL || ids[1] == NULL)) {
5082 struct print_diff_arg arg;
5083 char *id_str;
5085 if (worktree == NULL) {
5086 if (argc == 2 && ids[0] == NULL) {
5087 error = got_error_path(argv[0], GOT_ERR_NO_OBJ);
5088 goto done;
5089 } else if (argc == 2 && ids[1] == NULL) {
5090 error = got_error_path(argv[1], GOT_ERR_NO_OBJ);
5091 goto done;
5092 } else if (argc > 0) {
5093 error = got_error_fmt(GOT_ERR_NOT_WORKTREE,
5094 "%s", "specified paths cannot be resolved");
5095 goto done;
5096 } else {
5097 error = got_error(GOT_ERR_NOT_WORKTREE);
5098 goto done;
5102 error = get_worktree_paths_from_argv(&paths, argc, argv,
5103 worktree);
5104 if (error)
5105 goto done;
5107 error = got_object_id_str(&id_str,
5108 got_worktree_get_base_commit_id(worktree));
5109 if (error)
5110 goto done;
5111 arg.repo = repo;
5112 arg.worktree = worktree;
5113 arg.diff_algo = GOT_DIFF_ALGORITHM_PATIENCE;
5114 arg.diff_context = diff_context;
5115 arg.id_str = id_str;
5116 arg.header_shown = 0;
5117 arg.diff_staged = diff_staged;
5118 arg.ignore_whitespace = ignore_whitespace;
5119 arg.force_text_diff = force_text_diff;
5120 arg.f1 = f1;
5121 arg.f2 = f2;
5123 error = got_worktree_status(worktree, &paths, repo, 0,
5124 print_diff, &arg, check_cancelled, NULL);
5125 free(id_str);
5126 goto done;
5129 if (ncommit_args == 1) {
5130 struct got_commit_object *commit;
5131 error = got_object_open_as_commit(&commit, repo, ids[0]);
5132 if (error)
5133 goto done;
5135 labels[1] = labels[0];
5136 ids[1] = ids[0];
5137 if (got_object_commit_get_nparents(commit) > 0) {
5138 const struct got_object_id_queue *pids;
5139 struct got_object_qid *pid;
5140 pids = got_object_commit_get_parent_ids(commit);
5141 pid = STAILQ_FIRST(pids);
5142 ids[0] = got_object_id_dup(&pid->id);
5143 if (ids[0] == NULL) {
5144 error = got_error_from_errno(
5145 "got_object_id_dup");
5146 got_object_commit_close(commit);
5147 goto done;
5149 error = got_object_id_str(&labels[0], ids[0]);
5150 if (error) {
5151 got_object_commit_close(commit);
5152 goto done;
5154 } else {
5155 ids[0] = NULL;
5156 labels[0] = strdup("/dev/null");
5157 if (labels[0] == NULL) {
5158 error = got_error_from_errno("strdup");
5159 got_object_commit_close(commit);
5160 goto done;
5164 got_object_commit_close(commit);
5167 if (ncommit_args == 0 && argc > 2) {
5168 error = got_error_msg(GOT_ERR_BAD_PATH,
5169 "path arguments cannot be used when diffing two objects");
5170 goto done;
5173 if (ids[0]) {
5174 error = got_object_get_type(&type1, repo, ids[0]);
5175 if (error)
5176 goto done;
5179 error = got_object_get_type(&type2, repo, ids[1]);
5180 if (error)
5181 goto done;
5182 if (type1 != GOT_OBJ_TYPE_ANY && type1 != type2) {
5183 error = got_error(GOT_ERR_OBJ_TYPE);
5184 goto done;
5186 if (type1 == GOT_OBJ_TYPE_BLOB && argc > 2) {
5187 error = got_error_msg(GOT_ERR_OBJ_TYPE,
5188 "path arguments cannot be used when diffing blobs");
5189 goto done;
5192 for (i = 0; ncommit_args > 0 && i < argc; i++) {
5193 char *in_repo_path;
5194 struct got_pathlist_entry *new;
5195 if (worktree) {
5196 const char *prefix;
5197 char *p;
5198 error = got_worktree_resolve_path(&p, worktree,
5199 argv[i]);
5200 if (error)
5201 goto done;
5202 prefix = got_worktree_get_path_prefix(worktree);
5203 while (prefix[0] == '/')
5204 prefix++;
5205 if (asprintf(&in_repo_path, "%s%s%s", prefix,
5206 (p[0] != '\0' && prefix[0] != '\0') ? "/" : "",
5207 p) == -1) {
5208 error = got_error_from_errno("asprintf");
5209 free(p);
5210 goto done;
5212 free(p);
5213 } else {
5214 char *mapped_path, *s;
5215 error = got_repo_map_path(&mapped_path, repo, argv[i]);
5216 if (error)
5217 goto done;
5218 s = mapped_path;
5219 while (s[0] == '/')
5220 s++;
5221 in_repo_path = strdup(s);
5222 if (in_repo_path == NULL) {
5223 error = got_error_from_errno("asprintf");
5224 free(mapped_path);
5225 goto done;
5227 free(mapped_path);
5230 error = got_pathlist_insert(&new, &paths, in_repo_path, NULL);
5231 if (error || new == NULL /* duplicate */)
5232 free(in_repo_path);
5233 if (error)
5234 goto done;
5237 if (worktree) {
5238 /* Release work tree lock. */
5239 got_worktree_close(worktree);
5240 worktree = NULL;
5243 fd1 = got_opentempfd();
5244 if (fd1 == -1) {
5245 error = got_error_from_errno("got_opentempfd");
5246 goto done;
5249 fd2 = got_opentempfd();
5250 if (fd2 == -1) {
5251 error = got_error_from_errno("got_opentempfd");
5252 goto done;
5255 switch (type1 == GOT_OBJ_TYPE_ANY ? type2 : type1) {
5256 case GOT_OBJ_TYPE_BLOB:
5257 error = got_diff_objects_as_blobs(NULL, NULL, f1, f2,
5258 fd1, fd2, ids[0], ids[1], NULL, NULL,
5259 GOT_DIFF_ALGORITHM_PATIENCE, diff_context,
5260 ignore_whitespace, force_text_diff, repo, stdout);
5261 break;
5262 case GOT_OBJ_TYPE_TREE:
5263 error = got_diff_objects_as_trees(NULL, NULL, f1, f2, fd1, fd2,
5264 ids[0], ids[1], &paths, "", "",
5265 GOT_DIFF_ALGORITHM_PATIENCE, diff_context,
5266 ignore_whitespace, force_text_diff, repo, stdout);
5267 break;
5268 case GOT_OBJ_TYPE_COMMIT:
5269 printf("diff %s %s\n", labels[0], labels[1]);
5270 error = got_diff_objects_as_commits(NULL, NULL, f1, f2,
5271 fd1, fd2, ids[0], ids[1], &paths,
5272 GOT_DIFF_ALGORITHM_PATIENCE, diff_context,
5273 ignore_whitespace, force_text_diff, repo, stdout);
5274 break;
5275 default:
5276 error = got_error(GOT_ERR_OBJ_TYPE);
5278 done:
5279 free(labels[0]);
5280 free(labels[1]);
5281 free(ids[0]);
5282 free(ids[1]);
5283 if (worktree)
5284 got_worktree_close(worktree);
5285 if (repo) {
5286 const struct got_error *close_err = got_repo_close(repo);
5287 if (error == NULL)
5288 error = close_err;
5290 if (pack_fds) {
5291 const struct got_error *pack_err =
5292 got_repo_pack_fds_close(pack_fds);
5293 if (error == NULL)
5294 error = pack_err;
5296 TAILQ_FOREACH(pe, &paths, entry)
5297 free((char *)pe->path);
5298 got_pathlist_free(&paths);
5299 got_ref_list_free(&refs);
5300 if (f1 && fclose(f1) == EOF && error == NULL)
5301 error = got_error_from_errno("fclose");
5302 if (f2 && fclose(f2) == EOF && error == NULL)
5303 error = got_error_from_errno("fclose");
5304 if (fd1 != -1 && close(fd1) == -1 && error == NULL)
5305 error = got_error_from_errno("close");
5306 if (fd2 != -1 && close(fd2) == -1 && error == NULL)
5307 error = got_error_from_errno("close");
5308 return error;
5311 __dead static void
5312 usage_blame(void)
5314 fprintf(stderr,
5315 "usage: %s blame [-c commit] [-r repository-path] path\n",
5316 getprogname());
5317 exit(1);
5320 struct blame_line {
5321 int annotated;
5322 char *id_str;
5323 char *committer;
5324 char datebuf[11]; /* YYYY-MM-DD + NUL */
5327 struct blame_cb_args {
5328 struct blame_line *lines;
5329 int nlines;
5330 int nlines_prec;
5331 int lineno_cur;
5332 off_t *line_offsets;
5333 FILE *f;
5334 struct got_repository *repo;
5337 static const struct got_error *
5338 blame_cb(void *arg, int nlines, int lineno,
5339 struct got_commit_object *commit, struct got_object_id *id)
5341 const struct got_error *err = NULL;
5342 struct blame_cb_args *a = arg;
5343 struct blame_line *bline;
5344 char *line = NULL;
5345 size_t linesize = 0;
5346 off_t offset;
5347 struct tm tm;
5348 time_t committer_time;
5350 if (nlines != a->nlines ||
5351 (lineno != -1 && lineno < 1) || lineno > a->nlines)
5352 return got_error(GOT_ERR_RANGE);
5354 if (sigint_received)
5355 return got_error(GOT_ERR_ITER_COMPLETED);
5357 if (lineno == -1)
5358 return NULL; /* no change in this commit */
5360 /* Annotate this line. */
5361 bline = &a->lines[lineno - 1];
5362 if (bline->annotated)
5363 return NULL;
5364 err = got_object_id_str(&bline->id_str, id);
5365 if (err)
5366 return err;
5368 bline->committer = strdup(got_object_commit_get_committer(commit));
5369 if (bline->committer == NULL) {
5370 err = got_error_from_errno("strdup");
5371 goto done;
5374 committer_time = got_object_commit_get_committer_time(commit);
5375 if (gmtime_r(&committer_time, &tm) == NULL)
5376 return got_error_from_errno("gmtime_r");
5377 if (strftime(bline->datebuf, sizeof(bline->datebuf), "%G-%m-%d",
5378 &tm) == 0) {
5379 err = got_error(GOT_ERR_NO_SPACE);
5380 goto done;
5382 bline->annotated = 1;
5384 /* Print lines annotated so far. */
5385 bline = &a->lines[a->lineno_cur - 1];
5386 if (!bline->annotated)
5387 goto done;
5389 offset = a->line_offsets[a->lineno_cur - 1];
5390 if (fseeko(a->f, offset, SEEK_SET) == -1) {
5391 err = got_error_from_errno("fseeko");
5392 goto done;
5395 while (a->lineno_cur <= a->nlines && bline->annotated) {
5396 char *smallerthan, *at, *nl, *committer;
5397 size_t len;
5399 if (getline(&line, &linesize, a->f) == -1) {
5400 if (ferror(a->f))
5401 err = got_error_from_errno("getline");
5402 break;
5405 committer = bline->committer;
5406 smallerthan = strchr(committer, '<');
5407 if (smallerthan && smallerthan[1] != '\0')
5408 committer = smallerthan + 1;
5409 at = strchr(committer, '@');
5410 if (at)
5411 *at = '\0';
5412 len = strlen(committer);
5413 if (len >= 9)
5414 committer[8] = '\0';
5416 nl = strchr(line, '\n');
5417 if (nl)
5418 *nl = '\0';
5419 printf("%.*d) %.8s %s %-8s %s\n", a->nlines_prec, a->lineno_cur,
5420 bline->id_str, bline->datebuf, committer, line);
5422 a->lineno_cur++;
5423 bline = &a->lines[a->lineno_cur - 1];
5425 done:
5426 free(line);
5427 return err;
5430 static const struct got_error *
5431 cmd_blame(int argc, char *argv[])
5433 const struct got_error *error;
5434 struct got_repository *repo = NULL;
5435 struct got_worktree *worktree = NULL;
5436 char *path, *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
5437 char *link_target = NULL;
5438 struct got_object_id *obj_id = NULL;
5439 struct got_object_id *commit_id = NULL;
5440 struct got_commit_object *commit = NULL;
5441 struct got_blob_object *blob = NULL;
5442 char *commit_id_str = NULL;
5443 struct blame_cb_args bca;
5444 int ch, obj_type, i, fd1 = -1, fd2 = -1, fd3 = -1;
5445 off_t filesize;
5446 int *pack_fds = NULL;
5447 FILE *f1 = NULL, *f2 = NULL;
5449 fd1 = got_opentempfd();
5450 if (fd1 == -1)
5451 return got_error_from_errno("got_opentempfd");
5453 memset(&bca, 0, sizeof(bca));
5455 #ifndef PROFILE
5456 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
5457 NULL) == -1)
5458 err(1, "pledge");
5459 #endif
5461 while ((ch = getopt(argc, argv, "c:r:")) != -1) {
5462 switch (ch) {
5463 case 'c':
5464 commit_id_str = optarg;
5465 break;
5466 case 'r':
5467 repo_path = realpath(optarg, NULL);
5468 if (repo_path == NULL)
5469 return got_error_from_errno2("realpath",
5470 optarg);
5471 got_path_strip_trailing_slashes(repo_path);
5472 break;
5473 default:
5474 usage_blame();
5475 /* NOTREACHED */
5479 argc -= optind;
5480 argv += optind;
5482 if (argc == 1)
5483 path = argv[0];
5484 else
5485 usage_blame();
5487 cwd = getcwd(NULL, 0);
5488 if (cwd == NULL) {
5489 error = got_error_from_errno("getcwd");
5490 goto done;
5493 error = got_repo_pack_fds_open(&pack_fds);
5494 if (error != NULL)
5495 goto done;
5497 if (repo_path == NULL) {
5498 error = got_worktree_open(&worktree, cwd);
5499 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5500 goto done;
5501 else
5502 error = NULL;
5503 if (worktree) {
5504 repo_path =
5505 strdup(got_worktree_get_repo_path(worktree));
5506 if (repo_path == NULL) {
5507 error = got_error_from_errno("strdup");
5508 if (error)
5509 goto done;
5511 } else {
5512 repo_path = strdup(cwd);
5513 if (repo_path == NULL) {
5514 error = got_error_from_errno("strdup");
5515 goto done;
5520 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
5521 if (error != NULL)
5522 goto done;
5524 if (worktree) {
5525 const char *prefix = got_worktree_get_path_prefix(worktree);
5526 char *p;
5528 error = got_worktree_resolve_path(&p, worktree, path);
5529 if (error)
5530 goto done;
5531 if (asprintf(&in_repo_path, "%s%s%s", prefix,
5532 (p[0] != '\0' && !got_path_is_root_dir(prefix)) ? "/" : "",
5533 p) == -1) {
5534 error = got_error_from_errno("asprintf");
5535 free(p);
5536 goto done;
5538 free(p);
5539 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5540 } else {
5541 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5542 if (error)
5543 goto done;
5544 error = got_repo_map_path(&in_repo_path, repo, path);
5546 if (error)
5547 goto done;
5549 if (commit_id_str == NULL) {
5550 struct got_reference *head_ref;
5551 error = got_ref_open(&head_ref, repo, worktree ?
5552 got_worktree_get_head_ref_name(worktree) : GOT_REF_HEAD, 0);
5553 if (error != NULL)
5554 goto done;
5555 error = got_ref_resolve(&commit_id, repo, head_ref);
5556 got_ref_close(head_ref);
5557 if (error != NULL)
5558 goto done;
5559 } else {
5560 struct got_reflist_head refs;
5561 TAILQ_INIT(&refs);
5562 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
5563 NULL);
5564 if (error)
5565 goto done;
5566 error = got_repo_match_object_id(&commit_id, NULL,
5567 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
5568 got_ref_list_free(&refs);
5569 if (error)
5570 goto done;
5573 if (worktree) {
5574 /* Release work tree lock. */
5575 got_worktree_close(worktree);
5576 worktree = NULL;
5579 error = got_object_open_as_commit(&commit, repo, commit_id);
5580 if (error)
5581 goto done;
5583 error = got_object_resolve_symlinks(&link_target, in_repo_path,
5584 commit, repo);
5585 if (error)
5586 goto done;
5588 error = got_object_id_by_path(&obj_id, repo, commit,
5589 link_target ? link_target : in_repo_path);
5590 if (error)
5591 goto done;
5593 error = got_object_get_type(&obj_type, repo, obj_id);
5594 if (error)
5595 goto done;
5597 if (obj_type != GOT_OBJ_TYPE_BLOB) {
5598 error = got_error_path(link_target ? link_target : in_repo_path,
5599 GOT_ERR_OBJ_TYPE);
5600 goto done;
5603 error = got_object_open_as_blob(&blob, repo, obj_id, 8192, fd1);
5604 if (error)
5605 goto done;
5606 bca.f = got_opentemp();
5607 if (bca.f == NULL) {
5608 error = got_error_from_errno("got_opentemp");
5609 goto done;
5611 error = got_object_blob_dump_to_file(&filesize, &bca.nlines,
5612 &bca.line_offsets, bca.f, blob);
5613 if (error || bca.nlines == 0)
5614 goto done;
5616 /* Don't include \n at EOF in the blame line count. */
5617 if (bca.line_offsets[bca.nlines - 1] == filesize)
5618 bca.nlines--;
5620 bca.lines = calloc(bca.nlines, sizeof(*bca.lines));
5621 if (bca.lines == NULL) {
5622 error = got_error_from_errno("calloc");
5623 goto done;
5625 bca.lineno_cur = 1;
5626 bca.nlines_prec = 0;
5627 i = bca.nlines;
5628 while (i > 0) {
5629 i /= 10;
5630 bca.nlines_prec++;
5632 bca.repo = repo;
5634 fd2 = got_opentempfd();
5635 if (fd2 == -1) {
5636 error = got_error_from_errno("got_opentempfd");
5637 goto done;
5639 fd3 = got_opentempfd();
5640 if (fd3 == -1) {
5641 error = got_error_from_errno("got_opentempfd");
5642 goto done;
5644 f1 = got_opentemp();
5645 if (f1 == NULL) {
5646 error = got_error_from_errno("got_opentemp");
5647 goto done;
5649 f2 = got_opentemp();
5650 if (f2 == NULL) {
5651 error = got_error_from_errno("got_opentemp");
5652 goto done;
5654 error = got_blame(link_target ? link_target : in_repo_path, commit_id,
5655 repo, GOT_DIFF_ALGORITHM_PATIENCE, blame_cb, &bca,
5656 check_cancelled, NULL, fd2, fd3, f1, f2);
5657 done:
5658 free(in_repo_path);
5659 free(link_target);
5660 free(repo_path);
5661 free(cwd);
5662 free(commit_id);
5663 free(obj_id);
5664 if (commit)
5665 got_object_commit_close(commit);
5667 if (fd1 != -1 && close(fd1) == -1 && error == NULL)
5668 error = got_error_from_errno("close");
5669 if (fd2 != -1 && close(fd2) == -1 && error == NULL)
5670 error = got_error_from_errno("close");
5671 if (fd3 != -1 && close(fd3) == -1 && error == NULL)
5672 error = got_error_from_errno("close");
5673 if (f1 && fclose(f1) == EOF && error == NULL)
5674 error = got_error_from_errno("fclose");
5675 if (f2 && fclose(f2) == EOF && error == NULL)
5676 error = got_error_from_errno("fclose");
5678 if (blob)
5679 got_object_blob_close(blob);
5680 if (worktree)
5681 got_worktree_close(worktree);
5682 if (repo) {
5683 const struct got_error *close_err = got_repo_close(repo);
5684 if (error == NULL)
5685 error = close_err;
5687 if (pack_fds) {
5688 const struct got_error *pack_err =
5689 got_repo_pack_fds_close(pack_fds);
5690 if (error == NULL)
5691 error = pack_err;
5693 if (bca.lines) {
5694 for (i = 0; i < bca.nlines; i++) {
5695 struct blame_line *bline = &bca.lines[i];
5696 free(bline->id_str);
5697 free(bline->committer);
5699 free(bca.lines);
5701 free(bca.line_offsets);
5702 if (bca.f && fclose(bca.f) == EOF && error == NULL)
5703 error = got_error_from_errno("fclose");
5704 return error;
5707 __dead static void
5708 usage_tree(void)
5710 fprintf(stderr, "usage: %s tree [-iR] [-c commit] [-r repository-path] "
5711 "[path]\n", getprogname());
5712 exit(1);
5715 static const struct got_error *
5716 print_entry(struct got_tree_entry *te, const char *id, const char *path,
5717 const char *root_path, struct got_repository *repo)
5719 const struct got_error *err = NULL;
5720 int is_root_path = (strcmp(path, root_path) == 0);
5721 const char *modestr = "";
5722 mode_t mode = got_tree_entry_get_mode(te);
5723 char *link_target = NULL;
5725 path += strlen(root_path);
5726 while (path[0] == '/')
5727 path++;
5729 if (got_object_tree_entry_is_submodule(te))
5730 modestr = "$";
5731 else if (S_ISLNK(mode)) {
5732 int i;
5734 err = got_tree_entry_get_symlink_target(&link_target, te, repo);
5735 if (err)
5736 return err;
5737 for (i = 0; i < strlen(link_target); i++) {
5738 if (!isprint((unsigned char)link_target[i]))
5739 link_target[i] = '?';
5742 modestr = "@";
5744 else if (S_ISDIR(mode))
5745 modestr = "/";
5746 else if (mode & S_IXUSR)
5747 modestr = "*";
5749 printf("%s%s%s%s%s%s%s\n", id ? id : "", path,
5750 is_root_path ? "" : "/", got_tree_entry_get_name(te), modestr,
5751 link_target ? " -> ": "", link_target ? link_target : "");
5753 free(link_target);
5754 return NULL;
5757 static const struct got_error *
5758 print_tree(const char *path, struct got_commit_object *commit,
5759 int show_ids, int recurse, const char *root_path,
5760 struct got_repository *repo)
5762 const struct got_error *err = NULL;
5763 struct got_object_id *tree_id = NULL;
5764 struct got_tree_object *tree = NULL;
5765 int nentries, i;
5767 err = got_object_id_by_path(&tree_id, repo, commit, path);
5768 if (err)
5769 goto done;
5771 err = got_object_open_as_tree(&tree, repo, tree_id);
5772 if (err)
5773 goto done;
5774 nentries = got_object_tree_get_nentries(tree);
5775 for (i = 0; i < nentries; i++) {
5776 struct got_tree_entry *te;
5777 char *id = NULL;
5779 if (sigint_received || sigpipe_received)
5780 break;
5782 te = got_object_tree_get_entry(tree, i);
5783 if (show_ids) {
5784 char *id_str;
5785 err = got_object_id_str(&id_str,
5786 got_tree_entry_get_id(te));
5787 if (err)
5788 goto done;
5789 if (asprintf(&id, "%s ", id_str) == -1) {
5790 err = got_error_from_errno("asprintf");
5791 free(id_str);
5792 goto done;
5794 free(id_str);
5796 err = print_entry(te, id, path, root_path, repo);
5797 free(id);
5798 if (err)
5799 goto done;
5801 if (recurse && S_ISDIR(got_tree_entry_get_mode(te))) {
5802 char *child_path;
5803 if (asprintf(&child_path, "%s%s%s", path,
5804 path[0] == '/' && path[1] == '\0' ? "" : "/",
5805 got_tree_entry_get_name(te)) == -1) {
5806 err = got_error_from_errno("asprintf");
5807 goto done;
5809 err = print_tree(child_path, commit, show_ids, 1,
5810 root_path, repo);
5811 free(child_path);
5812 if (err)
5813 goto done;
5816 done:
5817 if (tree)
5818 got_object_tree_close(tree);
5819 free(tree_id);
5820 return err;
5823 static const struct got_error *
5824 cmd_tree(int argc, char *argv[])
5826 const struct got_error *error;
5827 struct got_repository *repo = NULL;
5828 struct got_worktree *worktree = NULL;
5829 const char *path, *refname = NULL;
5830 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
5831 struct got_object_id *commit_id = NULL;
5832 struct got_commit_object *commit = NULL;
5833 char *commit_id_str = NULL;
5834 int show_ids = 0, recurse = 0;
5835 int ch;
5836 int *pack_fds = NULL;
5838 #ifndef PROFILE
5839 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
5840 NULL) == -1)
5841 err(1, "pledge");
5842 #endif
5844 while ((ch = getopt(argc, argv, "c:iRr:")) != -1) {
5845 switch (ch) {
5846 case 'c':
5847 commit_id_str = optarg;
5848 break;
5849 case 'i':
5850 show_ids = 1;
5851 break;
5852 case 'R':
5853 recurse = 1;
5854 break;
5855 case 'r':
5856 repo_path = realpath(optarg, NULL);
5857 if (repo_path == NULL)
5858 return got_error_from_errno2("realpath",
5859 optarg);
5860 got_path_strip_trailing_slashes(repo_path);
5861 break;
5862 default:
5863 usage_tree();
5864 /* NOTREACHED */
5868 argc -= optind;
5869 argv += optind;
5871 if (argc == 1)
5872 path = argv[0];
5873 else if (argc > 1)
5874 usage_tree();
5875 else
5876 path = NULL;
5878 cwd = getcwd(NULL, 0);
5879 if (cwd == NULL) {
5880 error = got_error_from_errno("getcwd");
5881 goto done;
5884 error = got_repo_pack_fds_open(&pack_fds);
5885 if (error != NULL)
5886 goto done;
5888 if (repo_path == NULL) {
5889 error = got_worktree_open(&worktree, cwd);
5890 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5891 goto done;
5892 else
5893 error = NULL;
5894 if (worktree) {
5895 repo_path =
5896 strdup(got_worktree_get_repo_path(worktree));
5897 if (repo_path == NULL)
5898 error = got_error_from_errno("strdup");
5899 if (error)
5900 goto done;
5901 } else {
5902 repo_path = strdup(cwd);
5903 if (repo_path == NULL) {
5904 error = got_error_from_errno("strdup");
5905 goto done;
5910 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
5911 if (error != NULL)
5912 goto done;
5914 if (worktree) {
5915 const char *prefix = got_worktree_get_path_prefix(worktree);
5916 char *p;
5918 if (path == NULL)
5919 path = "";
5920 error = got_worktree_resolve_path(&p, worktree, path);
5921 if (error)
5922 goto done;
5923 if (asprintf(&in_repo_path, "%s%s%s", prefix,
5924 (p[0] != '\0' && !got_path_is_root_dir(prefix)) ? "/" : "",
5925 p) == -1) {
5926 error = got_error_from_errno("asprintf");
5927 free(p);
5928 goto done;
5930 free(p);
5931 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5932 if (error)
5933 goto done;
5934 } else {
5935 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5936 if (error)
5937 goto done;
5938 if (path == NULL)
5939 path = "/";
5940 error = got_repo_map_path(&in_repo_path, repo, path);
5941 if (error != NULL)
5942 goto done;
5945 if (commit_id_str == NULL) {
5946 struct got_reference *head_ref;
5947 if (worktree)
5948 refname = got_worktree_get_head_ref_name(worktree);
5949 else
5950 refname = GOT_REF_HEAD;
5951 error = got_ref_open(&head_ref, repo, refname, 0);
5952 if (error != NULL)
5953 goto done;
5954 error = got_ref_resolve(&commit_id, repo, head_ref);
5955 got_ref_close(head_ref);
5956 if (error != NULL)
5957 goto done;
5958 } else {
5959 struct got_reflist_head refs;
5960 TAILQ_INIT(&refs);
5961 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
5962 NULL);
5963 if (error)
5964 goto done;
5965 error = got_repo_match_object_id(&commit_id, NULL,
5966 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
5967 got_ref_list_free(&refs);
5968 if (error)
5969 goto done;
5972 if (worktree) {
5973 /* Release work tree lock. */
5974 got_worktree_close(worktree);
5975 worktree = NULL;
5978 error = got_object_open_as_commit(&commit, repo, commit_id);
5979 if (error)
5980 goto done;
5982 error = print_tree(in_repo_path, commit, show_ids, recurse,
5983 in_repo_path, repo);
5984 done:
5985 free(in_repo_path);
5986 free(repo_path);
5987 free(cwd);
5988 free(commit_id);
5989 if (commit)
5990 got_object_commit_close(commit);
5991 if (worktree)
5992 got_worktree_close(worktree);
5993 if (repo) {
5994 const struct got_error *close_err = got_repo_close(repo);
5995 if (error == NULL)
5996 error = close_err;
5998 if (pack_fds) {
5999 const struct got_error *pack_err =
6000 got_repo_pack_fds_close(pack_fds);
6001 if (error == NULL)
6002 error = pack_err;
6004 return error;
6007 __dead static void
6008 usage_status(void)
6010 fprintf(stderr, "usage: %s status [-I] [-S status-codes] "
6011 "[-s status-codes] [path ...]\n", getprogname());
6012 exit(1);
6015 struct got_status_arg {
6016 char *status_codes;
6017 int suppress;
6020 static const struct got_error *
6021 print_status(void *arg, unsigned char status, unsigned char staged_status,
6022 const char *path, struct got_object_id *blob_id,
6023 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
6024 int dirfd, const char *de_name)
6026 struct got_status_arg *st = arg;
6028 if (status == staged_status && (status == GOT_STATUS_DELETE))
6029 status = GOT_STATUS_NO_CHANGE;
6030 if (st != NULL && st->status_codes) {
6031 size_t ncodes = strlen(st->status_codes);
6032 int i, j = 0;
6034 for (i = 0; i < ncodes ; i++) {
6035 if (st->suppress) {
6036 if (status == st->status_codes[i] ||
6037 staged_status == st->status_codes[i]) {
6038 j++;
6039 continue;
6041 } else {
6042 if (status == st->status_codes[i] ||
6043 staged_status == st->status_codes[i])
6044 break;
6048 if (st->suppress && j == 0)
6049 goto print;
6051 if (i == ncodes)
6052 return NULL;
6054 print:
6055 printf("%c%c %s\n", status, staged_status, path);
6056 return NULL;
6059 static const struct got_error *
6060 cmd_status(int argc, char *argv[])
6062 const struct got_error *error = NULL;
6063 struct got_repository *repo = NULL;
6064 struct got_worktree *worktree = NULL;
6065 struct got_status_arg st;
6066 char *cwd = NULL;
6067 struct got_pathlist_head paths;
6068 struct got_pathlist_entry *pe;
6069 int ch, i, no_ignores = 0;
6070 int *pack_fds = NULL;
6072 TAILQ_INIT(&paths);
6074 memset(&st, 0, sizeof(st));
6075 st.status_codes = NULL;
6076 st.suppress = 0;
6078 while ((ch = getopt(argc, argv, "IS:s:")) != -1) {
6079 switch (ch) {
6080 case 'I':
6081 no_ignores = 1;
6082 break;
6083 case 'S':
6084 if (st.status_codes != NULL && st.suppress == 0)
6085 option_conflict('S', 's');
6086 st.suppress = 1;
6087 /* fallthrough */
6088 case 's':
6089 for (i = 0; i < strlen(optarg); i++) {
6090 switch (optarg[i]) {
6091 case GOT_STATUS_MODIFY:
6092 case GOT_STATUS_ADD:
6093 case GOT_STATUS_DELETE:
6094 case GOT_STATUS_CONFLICT:
6095 case GOT_STATUS_MISSING:
6096 case GOT_STATUS_OBSTRUCTED:
6097 case GOT_STATUS_UNVERSIONED:
6098 case GOT_STATUS_MODE_CHANGE:
6099 case GOT_STATUS_NONEXISTENT:
6100 break;
6101 default:
6102 errx(1, "invalid status code '%c'",
6103 optarg[i]);
6106 if (ch == 's' && st.suppress)
6107 option_conflict('s', 'S');
6108 st.status_codes = optarg;
6109 break;
6110 default:
6111 usage_status();
6112 /* NOTREACHED */
6116 argc -= optind;
6117 argv += optind;
6119 #ifndef PROFILE
6120 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
6121 NULL) == -1)
6122 err(1, "pledge");
6123 #endif
6124 cwd = getcwd(NULL, 0);
6125 if (cwd == NULL) {
6126 error = got_error_from_errno("getcwd");
6127 goto done;
6130 error = got_repo_pack_fds_open(&pack_fds);
6131 if (error != NULL)
6132 goto done;
6134 error = got_worktree_open(&worktree, cwd);
6135 if (error) {
6136 if (error->code == GOT_ERR_NOT_WORKTREE)
6137 error = wrap_not_worktree_error(error, "status", cwd);
6138 goto done;
6141 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
6142 NULL, pack_fds);
6143 if (error != NULL)
6144 goto done;
6146 error = apply_unveil(got_repo_get_path(repo), 1,
6147 got_worktree_get_root_path(worktree));
6148 if (error)
6149 goto done;
6151 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
6152 if (error)
6153 goto done;
6155 error = got_worktree_status(worktree, &paths, repo, no_ignores,
6156 print_status, &st, check_cancelled, NULL);
6157 done:
6158 if (pack_fds) {
6159 const struct got_error *pack_err =
6160 got_repo_pack_fds_close(pack_fds);
6161 if (error == NULL)
6162 error = pack_err;
6165 TAILQ_FOREACH(pe, &paths, entry)
6166 free((char *)pe->path);
6167 got_pathlist_free(&paths);
6168 free(cwd);
6169 return error;
6172 __dead static void
6173 usage_ref(void)
6175 fprintf(stderr, "usage: %s ref [-dlt] [-c object] [-r repository-path] "
6176 "[-s reference] [name]\n", getprogname());
6177 exit(1);
6180 static const struct got_error *
6181 list_refs(struct got_repository *repo, const char *refname, int sort_by_time)
6183 static const struct got_error *err = NULL;
6184 struct got_reflist_head refs;
6185 struct got_reflist_entry *re;
6187 TAILQ_INIT(&refs);
6188 err = got_ref_list(&refs, repo, refname, sort_by_time ?
6189 got_ref_cmp_by_commit_timestamp_descending : got_ref_cmp_by_name,
6190 repo);
6191 if (err)
6192 return err;
6194 TAILQ_FOREACH(re, &refs, entry) {
6195 char *refstr;
6196 refstr = got_ref_to_str(re->ref);
6197 if (refstr == NULL) {
6198 err = got_error_from_errno("got_ref_to_str");
6199 break;
6201 printf("%s: %s\n", got_ref_get_name(re->ref), refstr);
6202 free(refstr);
6205 got_ref_list_free(&refs);
6206 return err;
6209 static const struct got_error *
6210 delete_ref_by_name(struct got_repository *repo, const char *refname)
6212 const struct got_error *err;
6213 struct got_reference *ref;
6215 err = got_ref_open(&ref, repo, refname, 0);
6216 if (err)
6217 return err;
6219 err = delete_ref(repo, ref);
6220 got_ref_close(ref);
6221 return err;
6224 static const struct got_error *
6225 add_ref(struct got_repository *repo, const char *refname, const char *target)
6227 const struct got_error *err = NULL;
6228 struct got_object_id *id = NULL;
6229 struct got_reference *ref = NULL;
6230 struct got_reflist_head refs;
6233 * Don't let the user create a reference name with a leading '-'.
6234 * While technically a valid reference name, this case is usually
6235 * an unintended typo.
6237 if (refname[0] == '-')
6238 return got_error_path(refname, GOT_ERR_REF_NAME_MINUS);
6240 TAILQ_INIT(&refs);
6241 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
6242 if (err)
6243 goto done;
6244 err = got_repo_match_object_id(&id, NULL, target, GOT_OBJ_TYPE_ANY,
6245 &refs, repo);
6246 got_ref_list_free(&refs);
6247 if (err)
6248 goto done;
6250 err = got_ref_alloc(&ref, refname, id);
6251 if (err)
6252 goto done;
6254 err = got_ref_write(ref, repo);
6255 done:
6256 if (ref)
6257 got_ref_close(ref);
6258 free(id);
6259 return err;
6262 static const struct got_error *
6263 add_symref(struct got_repository *repo, const char *refname, const char *target)
6265 const struct got_error *err = NULL;
6266 struct got_reference *ref = NULL;
6267 struct got_reference *target_ref = NULL;
6270 * Don't let the user create a reference name with a leading '-'.
6271 * While technically a valid reference name, this case is usually
6272 * an unintended typo.
6274 if (refname[0] == '-')
6275 return got_error_path(refname, GOT_ERR_REF_NAME_MINUS);
6277 err = got_ref_open(&target_ref, repo, target, 0);
6278 if (err)
6279 return err;
6281 err = got_ref_alloc_symref(&ref, refname, target_ref);
6282 if (err)
6283 goto done;
6285 err = got_ref_write(ref, repo);
6286 done:
6287 if (target_ref)
6288 got_ref_close(target_ref);
6289 if (ref)
6290 got_ref_close(ref);
6291 return err;
6294 static const struct got_error *
6295 cmd_ref(int argc, char *argv[])
6297 const struct got_error *error = NULL;
6298 struct got_repository *repo = NULL;
6299 struct got_worktree *worktree = NULL;
6300 char *cwd = NULL, *repo_path = NULL;
6301 int ch, do_list = 0, do_delete = 0, sort_by_time = 0;
6302 const char *obj_arg = NULL, *symref_target= NULL;
6303 char *refname = NULL;
6304 int *pack_fds = NULL;
6306 while ((ch = getopt(argc, argv, "c:dlr:s:t")) != -1) {
6307 switch (ch) {
6308 case 'c':
6309 obj_arg = optarg;
6310 break;
6311 case 'd':
6312 do_delete = 1;
6313 break;
6314 case 'l':
6315 do_list = 1;
6316 break;
6317 case 'r':
6318 repo_path = realpath(optarg, NULL);
6319 if (repo_path == NULL)
6320 return got_error_from_errno2("realpath",
6321 optarg);
6322 got_path_strip_trailing_slashes(repo_path);
6323 break;
6324 case 's':
6325 symref_target = optarg;
6326 break;
6327 case 't':
6328 sort_by_time = 1;
6329 break;
6330 default:
6331 usage_ref();
6332 /* NOTREACHED */
6336 if (obj_arg && do_list)
6337 option_conflict('c', 'l');
6338 if (obj_arg && do_delete)
6339 option_conflict('c', 'd');
6340 if (obj_arg && symref_target)
6341 option_conflict('c', 's');
6342 if (symref_target && do_delete)
6343 option_conflict('s', 'd');
6344 if (symref_target && do_list)
6345 option_conflict('s', 'l');
6346 if (do_delete && do_list)
6347 option_conflict('d', 'l');
6348 if (sort_by_time && !do_list)
6349 errx(1, "-t option requires -l option");
6351 argc -= optind;
6352 argv += optind;
6354 if (do_list) {
6355 if (argc != 0 && argc != 1)
6356 usage_ref();
6357 if (argc == 1) {
6358 refname = strdup(argv[0]);
6359 if (refname == NULL) {
6360 error = got_error_from_errno("strdup");
6361 goto done;
6364 } else {
6365 if (argc != 1)
6366 usage_ref();
6367 refname = strdup(argv[0]);
6368 if (refname == NULL) {
6369 error = got_error_from_errno("strdup");
6370 goto done;
6374 if (refname)
6375 got_path_strip_trailing_slashes(refname);
6377 #ifndef PROFILE
6378 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
6379 "sendfd unveil", NULL) == -1)
6380 err(1, "pledge");
6381 #endif
6382 cwd = getcwd(NULL, 0);
6383 if (cwd == NULL) {
6384 error = got_error_from_errno("getcwd");
6385 goto done;
6388 error = got_repo_pack_fds_open(&pack_fds);
6389 if (error != NULL)
6390 goto done;
6392 if (repo_path == NULL) {
6393 error = got_worktree_open(&worktree, cwd);
6394 if (error && error->code != GOT_ERR_NOT_WORKTREE)
6395 goto done;
6396 else
6397 error = NULL;
6398 if (worktree) {
6399 repo_path =
6400 strdup(got_worktree_get_repo_path(worktree));
6401 if (repo_path == NULL)
6402 error = got_error_from_errno("strdup");
6403 if (error)
6404 goto done;
6405 } else {
6406 repo_path = strdup(cwd);
6407 if (repo_path == NULL) {
6408 error = got_error_from_errno("strdup");
6409 goto done;
6414 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
6415 if (error != NULL)
6416 goto done;
6418 #ifndef PROFILE
6419 if (do_list) {
6420 /* Remove "cpath" promise. */
6421 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
6422 NULL) == -1)
6423 err(1, "pledge");
6425 #endif
6427 error = apply_unveil(got_repo_get_path(repo), do_list,
6428 worktree ? got_worktree_get_root_path(worktree) : NULL);
6429 if (error)
6430 goto done;
6432 if (do_list)
6433 error = list_refs(repo, refname, sort_by_time);
6434 else if (do_delete)
6435 error = delete_ref_by_name(repo, refname);
6436 else if (symref_target)
6437 error = add_symref(repo, refname, symref_target);
6438 else {
6439 if (obj_arg == NULL)
6440 usage_ref();
6441 error = add_ref(repo, refname, obj_arg);
6443 done:
6444 free(refname);
6445 if (repo) {
6446 const struct got_error *close_err = got_repo_close(repo);
6447 if (error == NULL)
6448 error = close_err;
6450 if (worktree)
6451 got_worktree_close(worktree);
6452 if (pack_fds) {
6453 const struct got_error *pack_err =
6454 got_repo_pack_fds_close(pack_fds);
6455 if (error == NULL)
6456 error = pack_err;
6458 free(cwd);
6459 free(repo_path);
6460 return error;
6463 __dead static void
6464 usage_branch(void)
6466 fprintf(stderr, "usage: %s branch [-lnt] [-c commit] [-d name] "
6467 "[-r repository-path] [name]\n", getprogname());
6468 exit(1);
6471 static const struct got_error *
6472 list_branch(struct got_repository *repo, struct got_worktree *worktree,
6473 struct got_reference *ref)
6475 const struct got_error *err = NULL;
6476 const char *refname, *marker = " ";
6477 char *refstr;
6479 refname = got_ref_get_name(ref);
6480 if (worktree && strcmp(refname,
6481 got_worktree_get_head_ref_name(worktree)) == 0) {
6482 struct got_object_id *id = NULL;
6484 err = got_ref_resolve(&id, repo, ref);
6485 if (err)
6486 return err;
6487 if (got_object_id_cmp(id,
6488 got_worktree_get_base_commit_id(worktree)) == 0)
6489 marker = "* ";
6490 else
6491 marker = "~ ";
6492 free(id);
6495 if (strncmp(refname, "refs/heads/", 11) == 0)
6496 refname += 11;
6497 if (strncmp(refname, "refs/got/worktree/", 18) == 0)
6498 refname += 18;
6499 if (strncmp(refname, "refs/remotes/", 13) == 0)
6500 refname += 13;
6502 refstr = got_ref_to_str(ref);
6503 if (refstr == NULL)
6504 return got_error_from_errno("got_ref_to_str");
6506 printf("%s%s: %s\n", marker, refname, refstr);
6507 free(refstr);
6508 return NULL;
6511 static const struct got_error *
6512 show_current_branch(struct got_repository *repo, struct got_worktree *worktree)
6514 const char *refname;
6516 if (worktree == NULL)
6517 return got_error(GOT_ERR_NOT_WORKTREE);
6519 refname = got_worktree_get_head_ref_name(worktree);
6521 if (strncmp(refname, "refs/heads/", 11) == 0)
6522 refname += 11;
6523 if (strncmp(refname, "refs/got/worktree/", 18) == 0)
6524 refname += 18;
6526 printf("%s\n", refname);
6528 return NULL;
6531 static const struct got_error *
6532 list_branches(struct got_repository *repo, struct got_worktree *worktree,
6533 int sort_by_time)
6535 static const struct got_error *err = NULL;
6536 struct got_reflist_head refs;
6537 struct got_reflist_entry *re;
6538 struct got_reference *temp_ref = NULL;
6539 int rebase_in_progress, histedit_in_progress;
6541 TAILQ_INIT(&refs);
6543 if (worktree) {
6544 err = got_worktree_rebase_in_progress(&rebase_in_progress,
6545 worktree);
6546 if (err)
6547 return err;
6549 err = got_worktree_histedit_in_progress(&histedit_in_progress,
6550 worktree);
6551 if (err)
6552 return err;
6554 if (rebase_in_progress || histedit_in_progress) {
6555 err = got_ref_open(&temp_ref, repo,
6556 got_worktree_get_head_ref_name(worktree), 0);
6557 if (err)
6558 return err;
6559 list_branch(repo, worktree, temp_ref);
6560 got_ref_close(temp_ref);
6564 err = got_ref_list(&refs, repo, "refs/heads", sort_by_time ?
6565 got_ref_cmp_by_commit_timestamp_descending : got_ref_cmp_by_name,
6566 repo);
6567 if (err)
6568 return err;
6570 TAILQ_FOREACH(re, &refs, entry)
6571 list_branch(repo, worktree, re->ref);
6573 got_ref_list_free(&refs);
6575 err = got_ref_list(&refs, repo, "refs/remotes", sort_by_time ?
6576 got_ref_cmp_by_commit_timestamp_descending : got_ref_cmp_by_name,
6577 repo);
6578 if (err)
6579 return err;
6581 TAILQ_FOREACH(re, &refs, entry)
6582 list_branch(repo, worktree, re->ref);
6584 got_ref_list_free(&refs);
6586 return NULL;
6589 static const struct got_error *
6590 delete_branch(struct got_repository *repo, struct got_worktree *worktree,
6591 const char *branch_name)
6593 const struct got_error *err = NULL;
6594 struct got_reference *ref = NULL;
6595 char *refname, *remote_refname = NULL;
6597 if (strncmp(branch_name, "refs/", 5) == 0)
6598 branch_name += 5;
6599 if (strncmp(branch_name, "heads/", 6) == 0)
6600 branch_name += 6;
6601 else if (strncmp(branch_name, "remotes/", 8) == 0)
6602 branch_name += 8;
6604 if (asprintf(&refname, "refs/heads/%s", branch_name) == -1)
6605 return got_error_from_errno("asprintf");
6607 if (asprintf(&remote_refname, "refs/remotes/%s",
6608 branch_name) == -1) {
6609 err = got_error_from_errno("asprintf");
6610 goto done;
6613 err = got_ref_open(&ref, repo, refname, 0);
6614 if (err) {
6615 const struct got_error *err2;
6616 if (err->code != GOT_ERR_NOT_REF)
6617 goto done;
6619 * Keep 'err' intact such that if neither branch exists
6620 * we report "refs/heads" rather than "refs/remotes" in
6621 * our error message.
6623 err2 = got_ref_open(&ref, repo, remote_refname, 0);
6624 if (err2)
6625 goto done;
6626 err = NULL;
6629 if (worktree &&
6630 strcmp(got_worktree_get_head_ref_name(worktree),
6631 got_ref_get_name(ref)) == 0) {
6632 err = got_error_msg(GOT_ERR_SAME_BRANCH,
6633 "will not delete this work tree's current branch");
6634 goto done;
6637 err = delete_ref(repo, ref);
6638 done:
6639 if (ref)
6640 got_ref_close(ref);
6641 free(refname);
6642 free(remote_refname);
6643 return err;
6646 static const struct got_error *
6647 add_branch(struct got_repository *repo, const char *branch_name,
6648 struct got_object_id *base_commit_id)
6650 const struct got_error *err = NULL;
6651 struct got_reference *ref = NULL;
6652 char *base_refname = NULL, *refname = NULL;
6655 * Don't let the user create a branch name with a leading '-'.
6656 * While technically a valid reference name, this case is usually
6657 * an unintended typo.
6659 if (branch_name[0] == '-')
6660 return got_error_path(branch_name, GOT_ERR_REF_NAME_MINUS);
6662 if (strncmp(branch_name, "refs/heads/", 11) == 0)
6663 branch_name += 11;
6665 if (asprintf(&refname, "refs/heads/%s", branch_name) == -1) {
6666 err = got_error_from_errno("asprintf");
6667 goto done;
6670 err = got_ref_open(&ref, repo, refname, 0);
6671 if (err == NULL) {
6672 err = got_error(GOT_ERR_BRANCH_EXISTS);
6673 goto done;
6674 } else if (err->code != GOT_ERR_NOT_REF)
6675 goto done;
6677 err = got_ref_alloc(&ref, refname, base_commit_id);
6678 if (err)
6679 goto done;
6681 err = got_ref_write(ref, repo);
6682 done:
6683 if (ref)
6684 got_ref_close(ref);
6685 free(base_refname);
6686 free(refname);
6687 return err;
6690 static const struct got_error *
6691 cmd_branch(int argc, char *argv[])
6693 const struct got_error *error = NULL;
6694 struct got_repository *repo = NULL;
6695 struct got_worktree *worktree = NULL;
6696 char *cwd = NULL, *repo_path = NULL;
6697 int ch, do_list = 0, do_show = 0, do_update = 1, sort_by_time = 0;
6698 const char *delref = NULL, *commit_id_arg = NULL;
6699 struct got_reference *ref = NULL;
6700 struct got_pathlist_head paths;
6701 struct got_pathlist_entry *pe;
6702 struct got_object_id *commit_id = NULL;
6703 char *commit_id_str = NULL;
6704 int *pack_fds = NULL;
6706 TAILQ_INIT(&paths);
6708 while ((ch = getopt(argc, argv, "c:d:lnr:t")) != -1) {
6709 switch (ch) {
6710 case 'c':
6711 commit_id_arg = optarg;
6712 break;
6713 case 'd':
6714 delref = optarg;
6715 break;
6716 case 'l':
6717 do_list = 1;
6718 break;
6719 case 'n':
6720 do_update = 0;
6721 break;
6722 case 'r':
6723 repo_path = realpath(optarg, NULL);
6724 if (repo_path == NULL)
6725 return got_error_from_errno2("realpath",
6726 optarg);
6727 got_path_strip_trailing_slashes(repo_path);
6728 break;
6729 case 't':
6730 sort_by_time = 1;
6731 break;
6732 default:
6733 usage_branch();
6734 /* NOTREACHED */
6738 if (do_list && delref)
6739 option_conflict('l', 'd');
6740 if (sort_by_time && !do_list)
6741 errx(1, "-t option requires -l option");
6743 argc -= optind;
6744 argv += optind;
6746 if (!do_list && !delref && argc == 0)
6747 do_show = 1;
6749 if ((do_list || delref || do_show) && commit_id_arg != NULL)
6750 errx(1, "-c option can only be used when creating a branch");
6752 if (do_list || delref) {
6753 if (argc > 0)
6754 usage_branch();
6755 } else if (!do_show && argc != 1)
6756 usage_branch();
6758 #ifndef PROFILE
6759 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
6760 "sendfd unveil", NULL) == -1)
6761 err(1, "pledge");
6762 #endif
6763 cwd = getcwd(NULL, 0);
6764 if (cwd == NULL) {
6765 error = got_error_from_errno("getcwd");
6766 goto done;
6769 error = got_repo_pack_fds_open(&pack_fds);
6770 if (error != NULL)
6771 goto done;
6773 if (repo_path == NULL) {
6774 error = got_worktree_open(&worktree, cwd);
6775 if (error && error->code != GOT_ERR_NOT_WORKTREE)
6776 goto done;
6777 else
6778 error = NULL;
6779 if (worktree) {
6780 repo_path =
6781 strdup(got_worktree_get_repo_path(worktree));
6782 if (repo_path == NULL)
6783 error = got_error_from_errno("strdup");
6784 if (error)
6785 goto done;
6786 } else {
6787 repo_path = strdup(cwd);
6788 if (repo_path == NULL) {
6789 error = got_error_from_errno("strdup");
6790 goto done;
6795 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
6796 if (error != NULL)
6797 goto done;
6799 #ifndef PROFILE
6800 if (do_list || do_show) {
6801 /* Remove "cpath" promise. */
6802 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
6803 NULL) == -1)
6804 err(1, "pledge");
6806 #endif
6808 error = apply_unveil(got_repo_get_path(repo), do_list,
6809 worktree ? got_worktree_get_root_path(worktree) : NULL);
6810 if (error)
6811 goto done;
6813 if (do_show)
6814 error = show_current_branch(repo, worktree);
6815 else if (do_list)
6816 error = list_branches(repo, worktree, sort_by_time);
6817 else if (delref)
6818 error = delete_branch(repo, worktree, delref);
6819 else {
6820 struct got_reflist_head refs;
6821 TAILQ_INIT(&refs);
6822 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
6823 NULL);
6824 if (error)
6825 goto done;
6826 if (commit_id_arg == NULL)
6827 commit_id_arg = worktree ?
6828 got_worktree_get_head_ref_name(worktree) :
6829 GOT_REF_HEAD;
6830 error = got_repo_match_object_id(&commit_id, NULL,
6831 commit_id_arg, GOT_OBJ_TYPE_COMMIT, &refs, repo);
6832 got_ref_list_free(&refs);
6833 if (error)
6834 goto done;
6835 error = add_branch(repo, argv[0], commit_id);
6836 if (error)
6837 goto done;
6838 if (worktree && do_update) {
6839 struct got_update_progress_arg upa;
6840 char *branch_refname = NULL;
6842 error = got_object_id_str(&commit_id_str, commit_id);
6843 if (error)
6844 goto done;
6845 error = get_worktree_paths_from_argv(&paths, 0, NULL,
6846 worktree);
6847 if (error)
6848 goto done;
6849 if (asprintf(&branch_refname, "refs/heads/%s", argv[0])
6850 == -1) {
6851 error = got_error_from_errno("asprintf");
6852 goto done;
6854 error = got_ref_open(&ref, repo, branch_refname, 0);
6855 free(branch_refname);
6856 if (error)
6857 goto done;
6858 error = switch_head_ref(ref, commit_id, worktree,
6859 repo);
6860 if (error)
6861 goto done;
6862 error = got_worktree_set_base_commit_id(worktree, repo,
6863 commit_id);
6864 if (error)
6865 goto done;
6866 memset(&upa, 0, sizeof(upa));
6867 error = got_worktree_checkout_files(worktree, &paths,
6868 repo, update_progress, &upa, check_cancelled,
6869 NULL);
6870 if (error)
6871 goto done;
6872 if (upa.did_something) {
6873 printf("Updated to %s: %s\n",
6874 got_worktree_get_head_ref_name(worktree),
6875 commit_id_str);
6877 print_update_progress_stats(&upa);
6880 done:
6881 if (ref)
6882 got_ref_close(ref);
6883 if (repo) {
6884 const struct got_error *close_err = got_repo_close(repo);
6885 if (error == NULL)
6886 error = close_err;
6888 if (worktree)
6889 got_worktree_close(worktree);
6890 if (pack_fds) {
6891 const struct got_error *pack_err =
6892 got_repo_pack_fds_close(pack_fds);
6893 if (error == NULL)
6894 error = pack_err;
6896 free(cwd);
6897 free(repo_path);
6898 free(commit_id);
6899 free(commit_id_str);
6900 TAILQ_FOREACH(pe, &paths, entry)
6901 free((char *)pe->path);
6902 got_pathlist_free(&paths);
6903 return error;
6907 __dead static void
6908 usage_tag(void)
6910 fprintf(stderr, "usage: %s tag [-lVv] [-c commit] [-m message] "
6911 "[-r repository-path] [-s signer-id] name\n", getprogname());
6912 exit(1);
6915 #if 0
6916 static const struct got_error *
6917 sort_tags(struct got_reflist_head *sorted, struct got_reflist_head *tags)
6919 const struct got_error *err = NULL;
6920 struct got_reflist_entry *re, *se, *new;
6921 struct got_object_id *re_id, *se_id;
6922 struct got_tag_object *re_tag, *se_tag;
6923 time_t re_time, se_time;
6925 STAILQ_FOREACH(re, tags, entry) {
6926 se = STAILQ_FIRST(sorted);
6927 if (se == NULL) {
6928 err = got_reflist_entry_dup(&new, re);
6929 if (err)
6930 return err;
6931 STAILQ_INSERT_HEAD(sorted, new, entry);
6932 continue;
6933 } else {
6934 err = got_ref_resolve(&re_id, repo, re->ref);
6935 if (err)
6936 break;
6937 err = got_object_open_as_tag(&re_tag, repo, re_id);
6938 free(re_id);
6939 if (err)
6940 break;
6941 re_time = got_object_tag_get_tagger_time(re_tag);
6942 got_object_tag_close(re_tag);
6945 while (se) {
6946 err = got_ref_resolve(&se_id, repo, re->ref);
6947 if (err)
6948 break;
6949 err = got_object_open_as_tag(&se_tag, repo, se_id);
6950 free(se_id);
6951 if (err)
6952 break;
6953 se_time = got_object_tag_get_tagger_time(se_tag);
6954 got_object_tag_close(se_tag);
6956 if (se_time > re_time) {
6957 err = got_reflist_entry_dup(&new, re);
6958 if (err)
6959 return err;
6960 STAILQ_INSERT_AFTER(sorted, se, new, entry);
6961 break;
6963 se = STAILQ_NEXT(se, entry);
6964 continue;
6967 done:
6968 return err;
6970 #endif
6972 static const struct got_error *
6973 get_tag_refname(char **refname, const char *tag_name)
6975 const struct got_error *err;
6977 if (strncmp("refs/tags/", tag_name, 10) == 0) {
6978 *refname = strdup(tag_name);
6979 if (*refname == NULL)
6980 return got_error_from_errno("strdup");
6981 } else if (asprintf(refname, "refs/tags/%s", tag_name) == -1) {
6982 err = got_error_from_errno("asprintf");
6983 *refname = NULL;
6984 return err;
6987 return NULL;
6990 static const struct got_error *
6991 list_tags(struct got_repository *repo, const char *tag_name, int verify_tags,
6992 const char *allowed_signers, const char *revoked_signers, int verbosity)
6994 static const struct got_error *err = NULL;
6995 struct got_reflist_head refs;
6996 struct got_reflist_entry *re;
6997 char *wanted_refname = NULL;
6998 int bad_sigs = 0;
7000 TAILQ_INIT(&refs);
7002 err = got_ref_list(&refs, repo, "refs/tags", got_ref_cmp_tags, repo);
7003 if (err)
7004 return err;
7006 if (tag_name) {
7007 struct got_reference *ref;
7008 err = get_tag_refname(&wanted_refname, tag_name);
7009 if (err)
7010 goto done;
7011 /* Wanted tag reference should exist. */
7012 err = got_ref_open(&ref, repo, wanted_refname, 0);
7013 if (err)
7014 goto done;
7015 got_ref_close(ref);
7018 TAILQ_FOREACH(re, &refs, entry) {
7019 const char *refname;
7020 char *refstr, *tagmsg0, *tagmsg, *line, *id_str, *datestr;
7021 char datebuf[26];
7022 const char *tagger, *ssh_sig = NULL;
7023 char *sig_msg = NULL;
7024 time_t tagger_time;
7025 struct got_object_id *id;
7026 struct got_tag_object *tag;
7027 struct got_commit_object *commit = NULL;
7029 refname = got_ref_get_name(re->ref);
7030 if (strncmp(refname, "refs/tags/", 10) != 0 ||
7031 (wanted_refname && strcmp(refname, wanted_refname) != 0))
7032 continue;
7033 refname += 10;
7034 refstr = got_ref_to_str(re->ref);
7035 if (refstr == NULL) {
7036 err = got_error_from_errno("got_ref_to_str");
7037 break;
7040 err = got_ref_resolve(&id, repo, re->ref);
7041 if (err)
7042 break;
7043 err = got_object_open_as_tag(&tag, repo, id);
7044 if (err) {
7045 if (err->code != GOT_ERR_OBJ_TYPE) {
7046 free(id);
7047 break;
7049 /* "lightweight" tag */
7050 err = got_object_open_as_commit(&commit, repo, id);
7051 if (err) {
7052 free(id);
7053 break;
7055 tagger = got_object_commit_get_committer(commit);
7056 tagger_time =
7057 got_object_commit_get_committer_time(commit);
7058 err = got_object_id_str(&id_str, id);
7059 free(id);
7060 if (err)
7061 break;
7062 } else {
7063 free(id);
7064 tagger = got_object_tag_get_tagger(tag);
7065 tagger_time = got_object_tag_get_tagger_time(tag);
7066 err = got_object_id_str(&id_str,
7067 got_object_tag_get_object_id(tag));
7068 if (err)
7069 break;
7072 if (tag && verify_tags) {
7073 ssh_sig = got_sigs_get_tagmsg_ssh_signature(
7074 got_object_tag_get_message(tag));
7075 if (ssh_sig && allowed_signers == NULL) {
7076 err = got_error_msg(
7077 GOT_ERR_VERIFY_TAG_SIGNATURE,
7078 "SSH signature verification requires "
7079 "setting allowed_signers in "
7080 "got.conf(5)");
7081 break;
7085 printf("%stag %s %s\n", GOT_COMMIT_SEP_STR, refname, refstr);
7086 free(refstr);
7087 printf("from: %s\n", tagger);
7088 datestr = get_datestr(&tagger_time, datebuf);
7089 if (datestr)
7090 printf("date: %s UTC\n", datestr);
7091 if (commit)
7092 printf("object: %s %s\n", GOT_OBJ_LABEL_COMMIT, id_str);
7093 else {
7094 switch (got_object_tag_get_object_type(tag)) {
7095 case GOT_OBJ_TYPE_BLOB:
7096 printf("object: %s %s\n", GOT_OBJ_LABEL_BLOB,
7097 id_str);
7098 break;
7099 case GOT_OBJ_TYPE_TREE:
7100 printf("object: %s %s\n", GOT_OBJ_LABEL_TREE,
7101 id_str);
7102 break;
7103 case GOT_OBJ_TYPE_COMMIT:
7104 printf("object: %s %s\n", GOT_OBJ_LABEL_COMMIT,
7105 id_str);
7106 break;
7107 case GOT_OBJ_TYPE_TAG:
7108 printf("object: %s %s\n", GOT_OBJ_LABEL_TAG,
7109 id_str);
7110 break;
7111 default:
7112 break;
7115 free(id_str);
7117 if (ssh_sig) {
7118 err = got_sigs_verify_tag_ssh(&sig_msg, tag, ssh_sig,
7119 allowed_signers, revoked_signers, verbosity);
7120 if (err && err->code == GOT_ERR_BAD_TAG_SIGNATURE)
7121 bad_sigs = 1;
7122 else if (err)
7123 break;
7124 printf("signature: %s", sig_msg);
7125 free(sig_msg);
7126 sig_msg = NULL;
7129 if (commit) {
7130 err = got_object_commit_get_logmsg(&tagmsg0, commit);
7131 if (err)
7132 break;
7133 got_object_commit_close(commit);
7134 } else {
7135 tagmsg0 = strdup(got_object_tag_get_message(tag));
7136 got_object_tag_close(tag);
7137 if (tagmsg0 == NULL) {
7138 err = got_error_from_errno("strdup");
7139 break;
7143 tagmsg = tagmsg0;
7144 do {
7145 line = strsep(&tagmsg, "\n");
7146 if (line)
7147 printf(" %s\n", line);
7148 } while (line);
7149 free(tagmsg0);
7151 done:
7152 got_ref_list_free(&refs);
7153 free(wanted_refname);
7155 if (err == NULL && bad_sigs)
7156 err = got_error(GOT_ERR_BAD_TAG_SIGNATURE);
7157 return err;
7160 static const struct got_error *
7161 get_tag_message(char **tagmsg, char **tagmsg_path, const char *commit_id_str,
7162 const char *tag_name, const char *repo_path)
7164 const struct got_error *err = NULL;
7165 char *template = NULL, *initial_content = NULL;
7166 char *editor = NULL;
7167 int initial_content_len;
7168 int fd = -1;
7170 if (asprintf(&template, GOT_TMPDIR_STR "/got-tagmsg") == -1) {
7171 err = got_error_from_errno("asprintf");
7172 goto done;
7175 initial_content_len = asprintf(&initial_content,
7176 "\n# tagging commit %s as %s\n",
7177 commit_id_str, tag_name);
7178 if (initial_content_len == -1) {
7179 err = got_error_from_errno("asprintf");
7180 goto done;
7183 err = got_opentemp_named_fd(tagmsg_path, &fd, template, "");
7184 if (err)
7185 goto done;
7187 if (write(fd, initial_content, initial_content_len) == -1) {
7188 err = got_error_from_errno2("write", *tagmsg_path);
7189 goto done;
7192 err = get_editor(&editor);
7193 if (err)
7194 goto done;
7195 err = edit_logmsg(tagmsg, editor, *tagmsg_path, initial_content,
7196 initial_content_len, 1);
7197 done:
7198 free(initial_content);
7199 free(template);
7200 free(editor);
7202 if (fd != -1 && close(fd) == -1 && err == NULL)
7203 err = got_error_from_errno2("close", *tagmsg_path);
7205 if (err) {
7206 free(*tagmsg);
7207 *tagmsg = NULL;
7209 return err;
7212 static const struct got_error *
7213 add_tag(struct got_repository *repo, const char *tagger,
7214 const char *tag_name, const char *commit_arg, const char *tagmsg_arg,
7215 const char *signer_id, int verbosity)
7217 const struct got_error *err = NULL;
7218 struct got_object_id *commit_id = NULL, *tag_id = NULL;
7219 char *label = NULL, *commit_id_str = NULL;
7220 struct got_reference *ref = NULL;
7221 char *refname = NULL, *tagmsg = NULL;
7222 char *tagmsg_path = NULL, *tag_id_str = NULL;
7223 int preserve_tagmsg = 0;
7224 struct got_reflist_head refs;
7226 TAILQ_INIT(&refs);
7229 * Don't let the user create a tag name with a leading '-'.
7230 * While technically a valid reference name, this case is usually
7231 * an unintended typo.
7233 if (tag_name[0] == '-')
7234 return got_error_path(tag_name, GOT_ERR_REF_NAME_MINUS);
7236 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
7237 if (err)
7238 goto done;
7240 err = got_repo_match_object_id(&commit_id, &label, commit_arg,
7241 GOT_OBJ_TYPE_COMMIT, &refs, repo);
7242 if (err)
7243 goto done;
7245 err = got_object_id_str(&commit_id_str, commit_id);
7246 if (err)
7247 goto done;
7249 err = get_tag_refname(&refname, tag_name);
7250 if (err)
7251 goto done;
7252 if (strncmp("refs/tags/", tag_name, 10) == 0)
7253 tag_name += 10;
7255 err = got_ref_open(&ref, repo, refname, 0);
7256 if (err == NULL) {
7257 err = got_error(GOT_ERR_TAG_EXISTS);
7258 goto done;
7259 } else if (err->code != GOT_ERR_NOT_REF)
7260 goto done;
7262 if (tagmsg_arg == NULL) {
7263 err = get_tag_message(&tagmsg, &tagmsg_path, commit_id_str,
7264 tag_name, got_repo_get_path(repo));
7265 if (err) {
7266 if (err->code != GOT_ERR_COMMIT_MSG_EMPTY &&
7267 tagmsg_path != NULL)
7268 preserve_tagmsg = 1;
7269 goto done;
7271 /* Editor is done; we can now apply unveil(2) */
7272 err = got_sigs_apply_unveil();
7273 if (err)
7274 goto done;
7275 err = apply_unveil(got_repo_get_path(repo), 0, NULL);
7276 if (err)
7277 goto done;
7280 err = got_object_tag_create(&tag_id, tag_name, commit_id,
7281 tagger, time(NULL), tagmsg ? tagmsg : tagmsg_arg, signer_id, repo,
7282 verbosity);
7283 if (err) {
7284 if (tagmsg_path)
7285 preserve_tagmsg = 1;
7286 goto done;
7289 err = got_ref_alloc(&ref, refname, tag_id);
7290 if (err) {
7291 if (tagmsg_path)
7292 preserve_tagmsg = 1;
7293 goto done;
7296 err = got_ref_write(ref, repo);
7297 if (err) {
7298 if (tagmsg_path)
7299 preserve_tagmsg = 1;
7300 goto done;
7303 err = got_object_id_str(&tag_id_str, tag_id);
7304 if (err) {
7305 if (tagmsg_path)
7306 preserve_tagmsg = 1;
7307 goto done;
7309 printf("Created tag %s\n", tag_id_str);
7310 done:
7311 if (preserve_tagmsg) {
7312 fprintf(stderr, "%s: tag message preserved in %s\n",
7313 getprogname(), tagmsg_path);
7314 } else if (tagmsg_path && unlink(tagmsg_path) == -1 && err == NULL)
7315 err = got_error_from_errno2("unlink", tagmsg_path);
7316 free(tag_id_str);
7317 if (ref)
7318 got_ref_close(ref);
7319 free(commit_id);
7320 free(commit_id_str);
7321 free(refname);
7322 free(tagmsg);
7323 free(tagmsg_path);
7324 got_ref_list_free(&refs);
7325 return err;
7328 static const struct got_error *
7329 cmd_tag(int argc, char *argv[])
7331 const struct got_error *error = NULL;
7332 struct got_repository *repo = NULL;
7333 struct got_worktree *worktree = NULL;
7334 char *cwd = NULL, *repo_path = NULL, *commit_id_str = NULL;
7335 char *gitconfig_path = NULL, *tagger = NULL;
7336 char *allowed_signers = NULL, *revoked_signers = NULL;
7337 char *signer_id = NULL;
7338 const char *tag_name = NULL, *commit_id_arg = NULL, *tagmsg = NULL;
7339 int ch, do_list = 0, verify_tags = 0, verbosity = 0;
7340 int *pack_fds = NULL;
7342 while ((ch = getopt(argc, argv, "c:lm:r:s:Vv")) != -1) {
7343 switch (ch) {
7344 case 'c':
7345 commit_id_arg = optarg;
7346 break;
7347 case 'l':
7348 do_list = 1;
7349 break;
7350 case 'm':
7351 tagmsg = optarg;
7352 break;
7353 case 'r':
7354 repo_path = realpath(optarg, NULL);
7355 if (repo_path == NULL) {
7356 error = got_error_from_errno2("realpath",
7357 optarg);
7358 goto done;
7360 got_path_strip_trailing_slashes(repo_path);
7361 break;
7362 case 's':
7363 signer_id = strdup(optarg);
7364 if (signer_id == NULL) {
7365 error = got_error_from_errno("strdup");
7366 goto done;
7368 break;
7369 case 'V':
7370 verify_tags = 1;
7371 break;
7372 case 'v':
7373 if (verbosity < 0)
7374 verbosity = 0;
7375 else if (verbosity < 3)
7376 verbosity++;
7377 break;
7378 default:
7379 usage_tag();
7380 /* NOTREACHED */
7384 argc -= optind;
7385 argv += optind;
7387 if (do_list || verify_tags) {
7388 if (commit_id_arg != NULL)
7389 errx(1,
7390 "-c option can only be used when creating a tag");
7391 if (tagmsg) {
7392 if (do_list)
7393 option_conflict('l', 'm');
7394 else
7395 option_conflict('V', 'm');
7397 if (signer_id) {
7398 if (do_list)
7399 option_conflict('l', 's');
7400 else
7401 option_conflict('V', 's');
7403 if (argc > 1)
7404 usage_tag();
7405 } else if (argc != 1)
7406 usage_tag();
7408 if (argc == 1)
7409 tag_name = argv[0];
7411 #ifndef PROFILE
7412 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
7413 "sendfd unveil", NULL) == -1)
7414 err(1, "pledge");
7415 #endif
7416 cwd = getcwd(NULL, 0);
7417 if (cwd == NULL) {
7418 error = got_error_from_errno("getcwd");
7419 goto done;
7422 error = got_repo_pack_fds_open(&pack_fds);
7423 if (error != NULL)
7424 goto done;
7426 if (repo_path == NULL) {
7427 error = got_worktree_open(&worktree, cwd);
7428 if (error && error->code != GOT_ERR_NOT_WORKTREE)
7429 goto done;
7430 else
7431 error = NULL;
7432 if (worktree) {
7433 repo_path =
7434 strdup(got_worktree_get_repo_path(worktree));
7435 if (repo_path == NULL)
7436 error = got_error_from_errno("strdup");
7437 if (error)
7438 goto done;
7439 } else {
7440 repo_path = strdup(cwd);
7441 if (repo_path == NULL) {
7442 error = got_error_from_errno("strdup");
7443 goto done;
7448 if (do_list || verify_tags) {
7449 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
7450 if (error != NULL)
7451 goto done;
7452 error = get_allowed_signers(&allowed_signers, repo, worktree);
7453 if (error)
7454 goto done;
7455 error = get_revoked_signers(&revoked_signers, repo, worktree);
7456 if (error)
7457 goto done;
7458 if (worktree) {
7459 /* Release work tree lock. */
7460 got_worktree_close(worktree);
7461 worktree = NULL;
7465 * Remove "cpath" promise unless needed for signature tmpfile
7466 * creation.
7468 if (verify_tags)
7469 got_sigs_apply_unveil();
7470 else {
7471 #ifndef PROFILE
7472 if (pledge("stdio rpath wpath flock proc exec sendfd "
7473 "unveil", NULL) == -1)
7474 err(1, "pledge");
7475 #endif
7477 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
7478 if (error)
7479 goto done;
7480 error = list_tags(repo, tag_name, verify_tags, allowed_signers,
7481 revoked_signers, verbosity);
7482 } else {
7483 error = get_gitconfig_path(&gitconfig_path);
7484 if (error)
7485 goto done;
7486 error = got_repo_open(&repo, repo_path, gitconfig_path,
7487 pack_fds);
7488 if (error != NULL)
7489 goto done;
7491 error = get_author(&tagger, repo, worktree);
7492 if (error)
7493 goto done;
7494 if (signer_id == NULL) {
7495 error = get_signer_id(&signer_id, repo, worktree);
7496 if (error)
7497 goto done;
7500 if (tagmsg) {
7501 if (signer_id) {
7502 error = got_sigs_apply_unveil();
7503 if (error)
7504 goto done;
7506 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
7507 if (error)
7508 goto done;
7511 if (commit_id_arg == NULL) {
7512 struct got_reference *head_ref;
7513 struct got_object_id *commit_id;
7514 error = got_ref_open(&head_ref, repo,
7515 worktree ? got_worktree_get_head_ref_name(worktree)
7516 : GOT_REF_HEAD, 0);
7517 if (error)
7518 goto done;
7519 error = got_ref_resolve(&commit_id, repo, head_ref);
7520 got_ref_close(head_ref);
7521 if (error)
7522 goto done;
7523 error = got_object_id_str(&commit_id_str, commit_id);
7524 free(commit_id);
7525 if (error)
7526 goto done;
7529 if (worktree) {
7530 /* Release work tree lock. */
7531 got_worktree_close(worktree);
7532 worktree = NULL;
7535 error = add_tag(repo, tagger, tag_name,
7536 commit_id_str ? commit_id_str : commit_id_arg, tagmsg,
7537 signer_id, verbosity);
7539 done:
7540 if (repo) {
7541 const struct got_error *close_err = got_repo_close(repo);
7542 if (error == NULL)
7543 error = close_err;
7545 if (worktree)
7546 got_worktree_close(worktree);
7547 if (pack_fds) {
7548 const struct got_error *pack_err =
7549 got_repo_pack_fds_close(pack_fds);
7550 if (error == NULL)
7551 error = pack_err;
7553 free(cwd);
7554 free(repo_path);
7555 free(gitconfig_path);
7556 free(commit_id_str);
7557 free(tagger);
7558 free(allowed_signers);
7559 free(revoked_signers);
7560 free(signer_id);
7561 return error;
7564 __dead static void
7565 usage_add(void)
7567 fprintf(stderr, "usage: %s add [-IR] path ...\n", getprogname());
7568 exit(1);
7571 static const struct got_error *
7572 add_progress(void *arg, unsigned char status, const char *path)
7574 while (path[0] == '/')
7575 path++;
7576 printf("%c %s\n", status, path);
7577 return NULL;
7580 static const struct got_error *
7581 cmd_add(int argc, char *argv[])
7583 const struct got_error *error = NULL;
7584 struct got_repository *repo = NULL;
7585 struct got_worktree *worktree = NULL;
7586 char *cwd = NULL;
7587 struct got_pathlist_head paths;
7588 struct got_pathlist_entry *pe;
7589 int ch, can_recurse = 0, no_ignores = 0;
7590 int *pack_fds = NULL;
7592 TAILQ_INIT(&paths);
7594 while ((ch = getopt(argc, argv, "IR")) != -1) {
7595 switch (ch) {
7596 case 'I':
7597 no_ignores = 1;
7598 break;
7599 case 'R':
7600 can_recurse = 1;
7601 break;
7602 default:
7603 usage_add();
7604 /* NOTREACHED */
7608 argc -= optind;
7609 argv += optind;
7611 #ifndef PROFILE
7612 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
7613 NULL) == -1)
7614 err(1, "pledge");
7615 #endif
7616 if (argc < 1)
7617 usage_add();
7619 cwd = getcwd(NULL, 0);
7620 if (cwd == NULL) {
7621 error = got_error_from_errno("getcwd");
7622 goto done;
7625 error = got_repo_pack_fds_open(&pack_fds);
7626 if (error != NULL)
7627 goto done;
7629 error = got_worktree_open(&worktree, cwd);
7630 if (error) {
7631 if (error->code == GOT_ERR_NOT_WORKTREE)
7632 error = wrap_not_worktree_error(error, "add", cwd);
7633 goto done;
7636 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
7637 NULL, pack_fds);
7638 if (error != NULL)
7639 goto done;
7641 error = apply_unveil(got_repo_get_path(repo), 1,
7642 got_worktree_get_root_path(worktree));
7643 if (error)
7644 goto done;
7646 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
7647 if (error)
7648 goto done;
7650 if (!can_recurse) {
7651 char *ondisk_path;
7652 struct stat sb;
7653 TAILQ_FOREACH(pe, &paths, entry) {
7654 if (asprintf(&ondisk_path, "%s/%s",
7655 got_worktree_get_root_path(worktree),
7656 pe->path) == -1) {
7657 error = got_error_from_errno("asprintf");
7658 goto done;
7660 if (lstat(ondisk_path, &sb) == -1) {
7661 if (errno == ENOENT) {
7662 free(ondisk_path);
7663 continue;
7665 error = got_error_from_errno2("lstat",
7666 ondisk_path);
7667 free(ondisk_path);
7668 goto done;
7670 free(ondisk_path);
7671 if (S_ISDIR(sb.st_mode)) {
7672 error = got_error_msg(GOT_ERR_BAD_PATH,
7673 "adding directories requires -R option");
7674 goto done;
7679 error = got_worktree_schedule_add(worktree, &paths, add_progress,
7680 NULL, repo, no_ignores);
7681 done:
7682 if (repo) {
7683 const struct got_error *close_err = got_repo_close(repo);
7684 if (error == NULL)
7685 error = close_err;
7687 if (worktree)
7688 got_worktree_close(worktree);
7689 if (pack_fds) {
7690 const struct got_error *pack_err =
7691 got_repo_pack_fds_close(pack_fds);
7692 if (error == NULL)
7693 error = pack_err;
7695 TAILQ_FOREACH(pe, &paths, entry)
7696 free((char *)pe->path);
7697 got_pathlist_free(&paths);
7698 free(cwd);
7699 return error;
7702 __dead static void
7703 usage_remove(void)
7705 fprintf(stderr, "usage: %s remove [-fkR] [-s status-codes] path ...\n",
7706 getprogname());
7707 exit(1);
7710 static const struct got_error *
7711 print_remove_status(void *arg, unsigned char status,
7712 unsigned char staged_status, const char *path)
7714 while (path[0] == '/')
7715 path++;
7716 if (status == GOT_STATUS_NONEXISTENT)
7717 return NULL;
7718 if (status == staged_status && (status == GOT_STATUS_DELETE))
7719 status = GOT_STATUS_NO_CHANGE;
7720 printf("%c%c %s\n", status, staged_status, path);
7721 return NULL;
7724 static const struct got_error *
7725 cmd_remove(int argc, char *argv[])
7727 const struct got_error *error = NULL;
7728 struct got_worktree *worktree = NULL;
7729 struct got_repository *repo = NULL;
7730 const char *status_codes = NULL;
7731 char *cwd = NULL;
7732 struct got_pathlist_head paths;
7733 struct got_pathlist_entry *pe;
7734 int ch, delete_local_mods = 0, can_recurse = 0, keep_on_disk = 0, i;
7735 int ignore_missing_paths = 0;
7736 int *pack_fds = NULL;
7738 TAILQ_INIT(&paths);
7740 while ((ch = getopt(argc, argv, "fkRs:")) != -1) {
7741 switch (ch) {
7742 case 'f':
7743 delete_local_mods = 1;
7744 ignore_missing_paths = 1;
7745 break;
7746 case 'k':
7747 keep_on_disk = 1;
7748 break;
7749 case 'R':
7750 can_recurse = 1;
7751 break;
7752 case 's':
7753 for (i = 0; i < strlen(optarg); i++) {
7754 switch (optarg[i]) {
7755 case GOT_STATUS_MODIFY:
7756 delete_local_mods = 1;
7757 break;
7758 case GOT_STATUS_MISSING:
7759 ignore_missing_paths = 1;
7760 break;
7761 default:
7762 errx(1, "invalid status code '%c'",
7763 optarg[i]);
7766 status_codes = optarg;
7767 break;
7768 default:
7769 usage_remove();
7770 /* NOTREACHED */
7774 argc -= optind;
7775 argv += optind;
7777 #ifndef PROFILE
7778 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
7779 NULL) == -1)
7780 err(1, "pledge");
7781 #endif
7782 if (argc < 1)
7783 usage_remove();
7785 cwd = getcwd(NULL, 0);
7786 if (cwd == NULL) {
7787 error = got_error_from_errno("getcwd");
7788 goto done;
7791 error = got_repo_pack_fds_open(&pack_fds);
7792 if (error != NULL)
7793 goto done;
7795 error = got_worktree_open(&worktree, cwd);
7796 if (error) {
7797 if (error->code == GOT_ERR_NOT_WORKTREE)
7798 error = wrap_not_worktree_error(error, "remove", cwd);
7799 goto done;
7802 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
7803 NULL, pack_fds);
7804 if (error)
7805 goto done;
7807 error = apply_unveil(got_repo_get_path(repo), 1,
7808 got_worktree_get_root_path(worktree));
7809 if (error)
7810 goto done;
7812 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
7813 if (error)
7814 goto done;
7816 if (!can_recurse) {
7817 char *ondisk_path;
7818 struct stat sb;
7819 TAILQ_FOREACH(pe, &paths, entry) {
7820 if (asprintf(&ondisk_path, "%s/%s",
7821 got_worktree_get_root_path(worktree),
7822 pe->path) == -1) {
7823 error = got_error_from_errno("asprintf");
7824 goto done;
7826 if (lstat(ondisk_path, &sb) == -1) {
7827 if (errno == ENOENT) {
7828 free(ondisk_path);
7829 continue;
7831 error = got_error_from_errno2("lstat",
7832 ondisk_path);
7833 free(ondisk_path);
7834 goto done;
7836 free(ondisk_path);
7837 if (S_ISDIR(sb.st_mode)) {
7838 error = got_error_msg(GOT_ERR_BAD_PATH,
7839 "removing directories requires -R option");
7840 goto done;
7845 error = got_worktree_schedule_delete(worktree, &paths,
7846 delete_local_mods, status_codes, print_remove_status, NULL,
7847 repo, keep_on_disk, ignore_missing_paths);
7848 done:
7849 if (repo) {
7850 const struct got_error *close_err = got_repo_close(repo);
7851 if (error == NULL)
7852 error = close_err;
7854 if (worktree)
7855 got_worktree_close(worktree);
7856 if (pack_fds) {
7857 const struct got_error *pack_err =
7858 got_repo_pack_fds_close(pack_fds);
7859 if (error == NULL)
7860 error = pack_err;
7862 TAILQ_FOREACH(pe, &paths, entry)
7863 free((char *)pe->path);
7864 got_pathlist_free(&paths);
7865 free(cwd);
7866 return error;
7869 __dead static void
7870 usage_patch(void)
7872 fprintf(stderr, "usage: %s patch [-nR] [-c commit] [-p strip-count] "
7873 "[patchfile]\n", getprogname());
7874 exit(1);
7877 static const struct got_error *
7878 patch_from_stdin(int *patchfd)
7880 const struct got_error *err = NULL;
7881 ssize_t r;
7882 char buf[BUFSIZ];
7883 sig_t sighup, sigint, sigquit;
7885 *patchfd = got_opentempfd();
7886 if (*patchfd == -1)
7887 return got_error_from_errno("got_opentempfd");
7889 sighup = signal(SIGHUP, SIG_DFL);
7890 sigint = signal(SIGINT, SIG_DFL);
7891 sigquit = signal(SIGQUIT, SIG_DFL);
7893 for (;;) {
7894 r = read(0, buf, sizeof(buf));
7895 if (r == -1) {
7896 err = got_error_from_errno("read");
7897 break;
7899 if (r == 0)
7900 break;
7901 if (write(*patchfd, buf, r) == -1) {
7902 err = got_error_from_errno("write");
7903 break;
7907 signal(SIGHUP, sighup);
7908 signal(SIGINT, sigint);
7909 signal(SIGQUIT, sigquit);
7911 if (err == NULL && lseek(*patchfd, 0, SEEK_SET) == -1)
7912 err = got_error_from_errno("lseek");
7914 if (err != NULL) {
7915 close(*patchfd);
7916 *patchfd = -1;
7919 return err;
7922 static const struct got_error *
7923 patch_progress(void *arg, const char *old, const char *new,
7924 unsigned char status, const struct got_error *error, int old_from,
7925 int old_lines, int new_from, int new_lines, int offset,
7926 int ws_mangled, const struct got_error *hunk_err)
7928 const char *path = new == NULL ? old : new;
7930 while (*path == '/')
7931 path++;
7933 if (status != 0)
7934 printf("%c %s\n", status, path);
7936 if (error != NULL)
7937 fprintf(stderr, "%s: %s\n", getprogname(), error->msg);
7939 if (offset != 0 || hunk_err != NULL || ws_mangled) {
7940 printf("@@ -%d,%d +%d,%d @@ ", old_from,
7941 old_lines, new_from, new_lines);
7942 if (hunk_err != NULL)
7943 printf("%s\n", hunk_err->msg);
7944 else if (offset != 0)
7945 printf("applied with offset %d\n", offset);
7946 else
7947 printf("hunk contains mangled whitespace\n");
7950 return NULL;
7953 static const struct got_error *
7954 cmd_patch(int argc, char *argv[])
7956 const struct got_error *error = NULL, *close_error = NULL;
7957 struct got_worktree *worktree = NULL;
7958 struct got_repository *repo = NULL;
7959 struct got_reflist_head refs;
7960 struct got_object_id *commit_id = NULL;
7961 const char *commit_id_str = NULL;
7962 struct stat sb;
7963 const char *errstr;
7964 char *cwd = NULL;
7965 int ch, nop = 0, strip = -1, reverse = 0;
7966 int patchfd;
7967 int *pack_fds = NULL;
7969 TAILQ_INIT(&refs);
7971 #ifndef PROFILE
7972 if (pledge("stdio rpath wpath cpath fattr proc exec sendfd flock "
7973 "unveil", NULL) == -1)
7974 err(1, "pledge");
7975 #endif
7977 while ((ch = getopt(argc, argv, "c:np:R")) != -1) {
7978 switch (ch) {
7979 case 'c':
7980 commit_id_str = optarg;
7981 break;
7982 case 'n':
7983 nop = 1;
7984 break;
7985 case 'p':
7986 strip = strtonum(optarg, 0, INT_MAX, &errstr);
7987 if (errstr != NULL)
7988 errx(1, "pathname strip count is %s: %s",
7989 errstr, optarg);
7990 break;
7991 case 'R':
7992 reverse = 1;
7993 break;
7994 default:
7995 usage_patch();
7996 /* NOTREACHED */
8000 argc -= optind;
8001 argv += optind;
8003 if (argc == 0) {
8004 error = patch_from_stdin(&patchfd);
8005 if (error)
8006 return error;
8007 } else if (argc == 1) {
8008 patchfd = open(argv[0], O_RDONLY);
8009 if (patchfd == -1) {
8010 error = got_error_from_errno2("open", argv[0]);
8011 return error;
8013 if (fstat(patchfd, &sb) == -1) {
8014 error = got_error_from_errno2("fstat", argv[0]);
8015 goto done;
8017 if (!S_ISREG(sb.st_mode)) {
8018 error = got_error_path(argv[0], GOT_ERR_BAD_FILETYPE);
8019 goto done;
8021 } else
8022 usage_patch();
8024 if ((cwd = getcwd(NULL, 0)) == NULL) {
8025 error = got_error_from_errno("getcwd");
8026 goto done;
8029 error = got_repo_pack_fds_open(&pack_fds);
8030 if (error != NULL)
8031 goto done;
8033 error = got_worktree_open(&worktree, cwd);
8034 if (error != NULL)
8035 goto done;
8037 const char *repo_path = got_worktree_get_repo_path(worktree);
8038 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
8039 if (error != NULL)
8040 goto done;
8042 error = apply_unveil(got_repo_get_path(repo), 0,
8043 got_worktree_get_root_path(worktree));
8044 if (error != NULL)
8045 goto done;
8047 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
8048 if (error)
8049 goto done;
8051 if (commit_id_str != NULL) {
8052 error = got_repo_match_object_id(&commit_id, NULL,
8053 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
8054 if (error)
8055 goto done;
8058 error = got_patch(patchfd, worktree, repo, nop, strip, reverse,
8059 commit_id, &patch_progress, NULL, check_cancelled, NULL);
8061 done:
8062 got_ref_list_free(&refs);
8063 free(commit_id);
8064 if (repo) {
8065 close_error = got_repo_close(repo);
8066 if (error == NULL)
8067 error = close_error;
8069 if (worktree != NULL) {
8070 close_error = got_worktree_close(worktree);
8071 if (error == NULL)
8072 error = close_error;
8074 if (pack_fds) {
8075 const struct got_error *pack_err =
8076 got_repo_pack_fds_close(pack_fds);
8077 if (error == NULL)
8078 error = pack_err;
8080 free(cwd);
8081 return error;
8084 __dead static void
8085 usage_revert(void)
8087 fprintf(stderr, "usage: %s revert [-pR] [-F response-script] path ...\n",
8088 getprogname());
8089 exit(1);
8092 static const struct got_error *
8093 revert_progress(void *arg, unsigned char status, const char *path)
8095 if (status == GOT_STATUS_UNVERSIONED)
8096 return NULL;
8098 while (path[0] == '/')
8099 path++;
8100 printf("%c %s\n", status, path);
8101 return NULL;
8104 struct choose_patch_arg {
8105 FILE *patch_script_file;
8106 const char *action;
8109 static const struct got_error *
8110 show_change(unsigned char status, const char *path, FILE *patch_file, int n,
8111 int nchanges, const char *action)
8113 const struct got_error *err;
8114 char *line = NULL;
8115 size_t linesize = 0;
8116 ssize_t linelen;
8118 switch (status) {
8119 case GOT_STATUS_ADD:
8120 printf("A %s\n%s this addition? [y/n] ", path, action);
8121 break;
8122 case GOT_STATUS_DELETE:
8123 printf("D %s\n%s this deletion? [y/n] ", path, action);
8124 break;
8125 case GOT_STATUS_MODIFY:
8126 if (fseek(patch_file, 0L, SEEK_SET) == -1)
8127 return got_error_from_errno("fseek");
8128 printf(GOT_COMMIT_SEP_STR);
8129 while ((linelen = getline(&line, &linesize, patch_file)) != -1)
8130 printf("%s", line);
8131 if (linelen == -1 && ferror(patch_file)) {
8132 err = got_error_from_errno("getline");
8133 free(line);
8134 return err;
8136 free(line);
8137 printf(GOT_COMMIT_SEP_STR);
8138 printf("M %s (change %d of %d)\n%s this change? [y/n/q] ",
8139 path, n, nchanges, action);
8140 break;
8141 default:
8142 return got_error_path(path, GOT_ERR_FILE_STATUS);
8145 fflush(stdout);
8146 return NULL;
8149 static const struct got_error *
8150 choose_patch(int *choice, void *arg, unsigned char status, const char *path,
8151 FILE *patch_file, int n, int nchanges)
8153 const struct got_error *err = NULL;
8154 char *line = NULL;
8155 size_t linesize = 0;
8156 ssize_t linelen;
8157 int resp = ' ';
8158 struct choose_patch_arg *a = arg;
8160 *choice = GOT_PATCH_CHOICE_NONE;
8162 if (a->patch_script_file) {
8163 char *nl;
8164 err = show_change(status, path, patch_file, n, nchanges,
8165 a->action);
8166 if (err)
8167 return err;
8168 linelen = getline(&line, &linesize, a->patch_script_file);
8169 if (linelen == -1) {
8170 if (ferror(a->patch_script_file))
8171 return got_error_from_errno("getline");
8172 return NULL;
8174 nl = strchr(line, '\n');
8175 if (nl)
8176 *nl = '\0';
8177 if (strcmp(line, "y") == 0) {
8178 *choice = GOT_PATCH_CHOICE_YES;
8179 printf("y\n");
8180 } else if (strcmp(line, "n") == 0) {
8181 *choice = GOT_PATCH_CHOICE_NO;
8182 printf("n\n");
8183 } else if (strcmp(line, "q") == 0 &&
8184 status == GOT_STATUS_MODIFY) {
8185 *choice = GOT_PATCH_CHOICE_QUIT;
8186 printf("q\n");
8187 } else
8188 printf("invalid response '%s'\n", line);
8189 free(line);
8190 return NULL;
8193 while (resp != 'y' && resp != 'n' && resp != 'q') {
8194 err = show_change(status, path, patch_file, n, nchanges,
8195 a->action);
8196 if (err)
8197 return err;
8198 resp = getchar();
8199 if (resp == '\n')
8200 resp = getchar();
8201 if (status == GOT_STATUS_MODIFY) {
8202 if (resp != 'y' && resp != 'n' && resp != 'q') {
8203 printf("invalid response '%c'\n", resp);
8204 resp = ' ';
8206 } else if (resp != 'y' && resp != 'n') {
8207 printf("invalid response '%c'\n", resp);
8208 resp = ' ';
8212 if (resp == 'y')
8213 *choice = GOT_PATCH_CHOICE_YES;
8214 else if (resp == 'n')
8215 *choice = GOT_PATCH_CHOICE_NO;
8216 else if (resp == 'q' && status == GOT_STATUS_MODIFY)
8217 *choice = GOT_PATCH_CHOICE_QUIT;
8219 return NULL;
8222 static const struct got_error *
8223 cmd_revert(int argc, char *argv[])
8225 const struct got_error *error = NULL;
8226 struct got_worktree *worktree = NULL;
8227 struct got_repository *repo = NULL;
8228 char *cwd = NULL, *path = NULL;
8229 struct got_pathlist_head paths;
8230 struct got_pathlist_entry *pe;
8231 int ch, can_recurse = 0, pflag = 0;
8232 FILE *patch_script_file = NULL;
8233 const char *patch_script_path = NULL;
8234 struct choose_patch_arg cpa;
8235 int *pack_fds = NULL;
8237 TAILQ_INIT(&paths);
8239 while ((ch = getopt(argc, argv, "F:pR")) != -1) {
8240 switch (ch) {
8241 case 'F':
8242 patch_script_path = optarg;
8243 break;
8244 case 'p':
8245 pflag = 1;
8246 break;
8247 case 'R':
8248 can_recurse = 1;
8249 break;
8250 default:
8251 usage_revert();
8252 /* NOTREACHED */
8256 argc -= optind;
8257 argv += optind;
8259 #ifndef PROFILE
8260 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
8261 "unveil", NULL) == -1)
8262 err(1, "pledge");
8263 #endif
8264 if (argc < 1)
8265 usage_revert();
8266 if (patch_script_path && !pflag)
8267 errx(1, "-F option can only be used together with -p option");
8269 cwd = getcwd(NULL, 0);
8270 if (cwd == NULL) {
8271 error = got_error_from_errno("getcwd");
8272 goto done;
8275 error = got_repo_pack_fds_open(&pack_fds);
8276 if (error != NULL)
8277 goto done;
8279 error = got_worktree_open(&worktree, cwd);
8280 if (error) {
8281 if (error->code == GOT_ERR_NOT_WORKTREE)
8282 error = wrap_not_worktree_error(error, "revert", cwd);
8283 goto done;
8286 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
8287 NULL, pack_fds);
8288 if (error != NULL)
8289 goto done;
8291 if (patch_script_path) {
8292 patch_script_file = fopen(patch_script_path, "re");
8293 if (patch_script_file == NULL) {
8294 error = got_error_from_errno2("fopen",
8295 patch_script_path);
8296 goto done;
8299 error = apply_unveil(got_repo_get_path(repo), 1,
8300 got_worktree_get_root_path(worktree));
8301 if (error)
8302 goto done;
8304 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
8305 if (error)
8306 goto done;
8308 if (!can_recurse) {
8309 char *ondisk_path;
8310 struct stat sb;
8311 TAILQ_FOREACH(pe, &paths, entry) {
8312 if (asprintf(&ondisk_path, "%s/%s",
8313 got_worktree_get_root_path(worktree),
8314 pe->path) == -1) {
8315 error = got_error_from_errno("asprintf");
8316 goto done;
8318 if (lstat(ondisk_path, &sb) == -1) {
8319 if (errno == ENOENT) {
8320 free(ondisk_path);
8321 continue;
8323 error = got_error_from_errno2("lstat",
8324 ondisk_path);
8325 free(ondisk_path);
8326 goto done;
8328 free(ondisk_path);
8329 if (S_ISDIR(sb.st_mode)) {
8330 error = got_error_msg(GOT_ERR_BAD_PATH,
8331 "reverting directories requires -R option");
8332 goto done;
8337 cpa.patch_script_file = patch_script_file;
8338 cpa.action = "revert";
8339 error = got_worktree_revert(worktree, &paths, revert_progress, NULL,
8340 pflag ? choose_patch : NULL, &cpa, repo);
8341 done:
8342 if (patch_script_file && fclose(patch_script_file) == EOF &&
8343 error == NULL)
8344 error = got_error_from_errno2("fclose", patch_script_path);
8345 if (repo) {
8346 const struct got_error *close_err = got_repo_close(repo);
8347 if (error == NULL)
8348 error = close_err;
8350 if (worktree)
8351 got_worktree_close(worktree);
8352 if (pack_fds) {
8353 const struct got_error *pack_err =
8354 got_repo_pack_fds_close(pack_fds);
8355 if (error == NULL)
8356 error = pack_err;
8358 free(path);
8359 free(cwd);
8360 return error;
8363 __dead static void
8364 usage_commit(void)
8366 fprintf(stderr, "usage: %s commit [-NS] [-A author] [-F path] "
8367 "[-m message] [path ...]\n", getprogname());
8368 exit(1);
8371 struct collect_commit_logmsg_arg {
8372 const char *cmdline_log;
8373 const char *prepared_log;
8374 int non_interactive;
8375 const char *editor;
8376 const char *worktree_path;
8377 const char *branch_name;
8378 const char *repo_path;
8379 char *logmsg_path;
8383 static const struct got_error *
8384 read_prepared_logmsg(char **logmsg, const char *path)
8386 const struct got_error *err = NULL;
8387 FILE *f = NULL;
8388 struct stat sb;
8389 size_t r;
8391 *logmsg = NULL;
8392 memset(&sb, 0, sizeof(sb));
8394 f = fopen(path, "re");
8395 if (f == NULL)
8396 return got_error_from_errno2("fopen", path);
8398 if (fstat(fileno(f), &sb) == -1) {
8399 err = got_error_from_errno2("fstat", path);
8400 goto done;
8402 if (sb.st_size == 0) {
8403 err = got_error(GOT_ERR_COMMIT_MSG_EMPTY);
8404 goto done;
8407 *logmsg = malloc(sb.st_size + 1);
8408 if (*logmsg == NULL) {
8409 err = got_error_from_errno("malloc");
8410 goto done;
8413 r = fread(*logmsg, 1, sb.st_size, f);
8414 if (r != sb.st_size) {
8415 if (ferror(f))
8416 err = got_error_from_errno2("fread", path);
8417 else
8418 err = got_error(GOT_ERR_IO);
8419 goto done;
8421 (*logmsg)[sb.st_size] = '\0';
8422 done:
8423 if (fclose(f) == EOF && err == NULL)
8424 err = got_error_from_errno2("fclose", path);
8425 if (err) {
8426 free(*logmsg);
8427 *logmsg = NULL;
8429 return err;
8432 static const struct got_error *
8433 collect_commit_logmsg(struct got_pathlist_head *commitable_paths,
8434 const char *diff_path, char **logmsg, void *arg)
8436 char *initial_content = NULL;
8437 struct got_pathlist_entry *pe;
8438 const struct got_error *err = NULL;
8439 char *template = NULL;
8440 struct collect_commit_logmsg_arg *a = arg;
8441 int initial_content_len;
8442 int fd = -1;
8443 size_t len;
8445 /* if a message was specified on the command line, just use it */
8446 if (a->cmdline_log != NULL && strlen(a->cmdline_log) != 0) {
8447 len = strlen(a->cmdline_log) + 1;
8448 *logmsg = malloc(len + 1);
8449 if (*logmsg == NULL)
8450 return got_error_from_errno("malloc");
8451 strlcpy(*logmsg, a->cmdline_log, len);
8452 return NULL;
8453 } else if (a->prepared_log != NULL && a->non_interactive)
8454 return read_prepared_logmsg(logmsg, a->prepared_log);
8456 if (asprintf(&template, "%s/logmsg", a->worktree_path) == -1)
8457 return got_error_from_errno("asprintf");
8459 err = got_opentemp_named_fd(&a->logmsg_path, &fd, template, "");
8460 if (err)
8461 goto done;
8463 if (a->prepared_log) {
8464 char *msg;
8465 err = read_prepared_logmsg(&msg, a->prepared_log);
8466 if (err)
8467 goto done;
8468 if (write(fd, msg, strlen(msg)) == -1) {
8469 err = got_error_from_errno2("write", a->logmsg_path);
8470 free(msg);
8471 goto done;
8473 free(msg);
8476 initial_content_len = asprintf(&initial_content,
8477 "\n# changes to be committed on branch %s:\n",
8478 a->branch_name);
8479 if (initial_content_len == -1) {
8480 err = got_error_from_errno("asprintf");
8481 goto done;
8484 if (write(fd, initial_content, initial_content_len) == -1) {
8485 err = got_error_from_errno2("write", a->logmsg_path);
8486 goto done;
8489 TAILQ_FOREACH(pe, commitable_paths, entry) {
8490 struct got_commitable *ct = pe->data;
8491 dprintf(fd, "# %c %s\n",
8492 got_commitable_get_status(ct),
8493 got_commitable_get_path(ct));
8496 if (diff_path) {
8497 dprintf(fd, "# detailed changes can be viewed in %s\n",
8498 diff_path);
8501 err = edit_logmsg(logmsg, a->editor, a->logmsg_path, initial_content,
8502 initial_content_len, a->prepared_log ? 0 : 1);
8503 done:
8504 free(initial_content);
8505 free(template);
8507 if (fd != -1 && close(fd) == -1 && err == NULL)
8508 err = got_error_from_errno2("close", a->logmsg_path);
8510 /* Editor is done; we can now apply unveil(2) */
8511 if (err == NULL)
8512 err = apply_unveil(a->repo_path, 0, a->worktree_path);
8513 if (err) {
8514 free(*logmsg);
8515 *logmsg = NULL;
8517 return err;
8520 static const struct got_error *
8521 cmd_commit(int argc, char *argv[])
8523 const struct got_error *error = NULL;
8524 struct got_worktree *worktree = NULL;
8525 struct got_repository *repo = NULL;
8526 char *cwd = NULL, *id_str = NULL;
8527 struct got_object_id *id = NULL;
8528 const char *logmsg = NULL;
8529 char *prepared_logmsg = NULL;
8530 struct collect_commit_logmsg_arg cl_arg;
8531 const char *author = NULL;
8532 char *gitconfig_path = NULL, *editor = NULL, *committer = NULL;
8533 int ch, rebase_in_progress, histedit_in_progress, preserve_logmsg = 0;
8534 int allow_bad_symlinks = 0, non_interactive = 0, merge_in_progress = 0;
8535 int show_diff = 1;
8536 struct got_pathlist_head paths;
8537 int *pack_fds = NULL;
8539 TAILQ_INIT(&paths);
8540 cl_arg.logmsg_path = NULL;
8542 while ((ch = getopt(argc, argv, "A:F:m:NnS")) != -1) {
8543 switch (ch) {
8544 case 'A':
8545 author = optarg;
8546 error = valid_author(author);
8547 if (error)
8548 return error;
8549 break;
8550 case 'F':
8551 if (logmsg != NULL)
8552 option_conflict('F', 'm');
8553 prepared_logmsg = realpath(optarg, NULL);
8554 if (prepared_logmsg == NULL)
8555 return got_error_from_errno2("realpath",
8556 optarg);
8557 break;
8558 case 'm':
8559 if (prepared_logmsg)
8560 option_conflict('m', 'F');
8561 logmsg = optarg;
8562 break;
8563 case 'N':
8564 non_interactive = 1;
8565 break;
8566 case 'n':
8567 show_diff = 0;
8568 break;
8569 case 'S':
8570 allow_bad_symlinks = 1;
8571 break;
8572 default:
8573 usage_commit();
8574 /* NOTREACHED */
8578 argc -= optind;
8579 argv += optind;
8581 #ifndef PROFILE
8582 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
8583 "unveil", NULL) == -1)
8584 err(1, "pledge");
8585 #endif
8586 cwd = getcwd(NULL, 0);
8587 if (cwd == NULL) {
8588 error = got_error_from_errno("getcwd");
8589 goto done;
8592 error = got_repo_pack_fds_open(&pack_fds);
8593 if (error != NULL)
8594 goto done;
8596 error = got_worktree_open(&worktree, cwd);
8597 if (error) {
8598 if (error->code == GOT_ERR_NOT_WORKTREE)
8599 error = wrap_not_worktree_error(error, "commit", cwd);
8600 goto done;
8603 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
8604 if (error)
8605 goto done;
8606 if (rebase_in_progress) {
8607 error = got_error(GOT_ERR_REBASING);
8608 goto done;
8611 error = got_worktree_histedit_in_progress(&histedit_in_progress,
8612 worktree);
8613 if (error)
8614 goto done;
8616 error = get_gitconfig_path(&gitconfig_path);
8617 if (error)
8618 goto done;
8619 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
8620 gitconfig_path, pack_fds);
8621 if (error != NULL)
8622 goto done;
8624 error = got_worktree_merge_in_progress(&merge_in_progress, worktree, repo);
8625 if (error)
8626 goto done;
8627 if (merge_in_progress) {
8628 error = got_error(GOT_ERR_MERGE_BUSY);
8629 goto done;
8632 error = get_author(&committer, repo, worktree);
8633 if (error)
8634 goto done;
8636 if (author != NULL && !strcmp(committer, author)) {
8637 error = got_error(GOT_ERR_COMMIT_REDUNDANT_AUTHOR);
8638 goto done;
8641 if (author == NULL)
8642 author = committer;
8645 * unveil(2) traverses exec(2); if an editor is used we have
8646 * to apply unveil after the log message has been written.
8648 if (logmsg == NULL || strlen(logmsg) == 0)
8649 error = get_editor(&editor);
8650 else
8651 error = apply_unveil(got_repo_get_path(repo), 0,
8652 got_worktree_get_root_path(worktree));
8653 if (error)
8654 goto done;
8656 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
8657 if (error)
8658 goto done;
8660 cl_arg.editor = editor;
8661 cl_arg.cmdline_log = logmsg;
8662 cl_arg.prepared_log = prepared_logmsg;
8663 cl_arg.non_interactive = non_interactive;
8664 cl_arg.worktree_path = got_worktree_get_root_path(worktree);
8665 cl_arg.branch_name = got_worktree_get_head_ref_name(worktree);
8666 if (!histedit_in_progress) {
8667 if (strncmp(cl_arg.branch_name, "refs/heads/", 11) != 0) {
8668 error = got_error(GOT_ERR_COMMIT_BRANCH);
8669 goto done;
8671 cl_arg.branch_name += 11;
8673 cl_arg.repo_path = got_repo_get_path(repo);
8674 error = got_worktree_commit(&id, worktree, &paths, author, committer,
8675 allow_bad_symlinks, show_diff, collect_commit_logmsg, &cl_arg,
8676 print_status, NULL, repo);
8677 if (error) {
8678 if (error->code != GOT_ERR_COMMIT_MSG_EMPTY &&
8679 cl_arg.logmsg_path != NULL)
8680 preserve_logmsg = 1;
8681 goto done;
8684 error = got_object_id_str(&id_str, id);
8685 if (error)
8686 goto done;
8687 printf("Created commit %s\n", id_str);
8688 done:
8689 if (preserve_logmsg) {
8690 fprintf(stderr, "%s: log message preserved in %s\n",
8691 getprogname(), cl_arg.logmsg_path);
8692 } else if (cl_arg.logmsg_path && unlink(cl_arg.logmsg_path) == -1 &&
8693 error == NULL)
8694 error = got_error_from_errno2("unlink", cl_arg.logmsg_path);
8695 free(cl_arg.logmsg_path);
8696 if (repo) {
8697 const struct got_error *close_err = got_repo_close(repo);
8698 if (error == NULL)
8699 error = close_err;
8701 if (worktree)
8702 got_worktree_close(worktree);
8703 if (pack_fds) {
8704 const struct got_error *pack_err =
8705 got_repo_pack_fds_close(pack_fds);
8706 if (error == NULL)
8707 error = pack_err;
8709 free(cwd);
8710 free(id_str);
8711 free(gitconfig_path);
8712 free(editor);
8713 free(committer);
8714 free(prepared_logmsg);
8715 return error;
8718 __dead static void
8719 usage_send(void)
8721 fprintf(stderr, "usage: %s send [-afqTv] [-b branch] [-d branch] "
8722 "[-r repository-path] [-t tag] [remote-repository]\n",
8723 getprogname());
8724 exit(1);
8727 static void
8728 print_load_info(int print_colored, int print_found, int print_trees,
8729 int ncolored, int nfound, int ntrees)
8731 if (print_colored) {
8732 printf("%d commit%s colored", ncolored,
8733 ncolored == 1 ? "" : "s");
8735 if (print_found) {
8736 printf("%s%d object%s found",
8737 ncolored > 0 ? "; " : "",
8738 nfound, nfound == 1 ? "" : "s");
8740 if (print_trees) {
8741 printf("; %d tree%s scanned", ntrees,
8742 ntrees == 1 ? "" : "s");
8746 struct got_send_progress_arg {
8747 char last_scaled_packsize[FMT_SCALED_STRSIZE];
8748 int verbosity;
8749 int last_ncolored;
8750 int last_nfound;
8751 int last_ntrees;
8752 int loading_done;
8753 int last_ncommits;
8754 int last_nobj_total;
8755 int last_p_deltify;
8756 int last_p_written;
8757 int last_p_sent;
8758 int printed_something;
8759 int sent_something;
8760 struct got_pathlist_head *delete_branches;
8763 static const struct got_error *
8764 send_progress(void *arg, int ncolored, int nfound, int ntrees,
8765 off_t packfile_size, int ncommits, int nobj_total, int nobj_deltify,
8766 int nobj_written, off_t bytes_sent, const char *refname, int success)
8768 struct got_send_progress_arg *a = arg;
8769 char scaled_packsize[FMT_SCALED_STRSIZE];
8770 char scaled_sent[FMT_SCALED_STRSIZE];
8771 int p_deltify = 0, p_written = 0, p_sent = 0;
8772 int print_colored = 0, print_found = 0, print_trees = 0;
8773 int print_searching = 0, print_total = 0;
8774 int print_deltify = 0, print_written = 0, print_sent = 0;
8776 if (a->verbosity < 0)
8777 return NULL;
8779 if (refname) {
8780 const char *status = success ? "accepted" : "rejected";
8782 if (success) {
8783 struct got_pathlist_entry *pe;
8784 TAILQ_FOREACH(pe, a->delete_branches, entry) {
8785 const char *branchname = pe->path;
8786 if (got_path_cmp(branchname, refname,
8787 strlen(branchname), strlen(refname)) == 0) {
8788 status = "deleted";
8789 a->sent_something = 1;
8790 break;
8795 if (a->printed_something)
8796 putchar('\n');
8797 printf("Server has %s %s", status, refname);
8798 a->printed_something = 1;
8799 return NULL;
8802 if (a->last_ncolored != ncolored) {
8803 print_colored = 1;
8804 a->last_ncolored = ncolored;
8807 if (a->last_nfound != nfound) {
8808 print_colored = 1;
8809 print_found = 1;
8810 a->last_nfound = nfound;
8813 if (a->last_ntrees != ntrees) {
8814 print_colored = 1;
8815 print_found = 1;
8816 print_trees = 1;
8817 a->last_ntrees = ntrees;
8820 if ((print_colored || print_found || print_trees) &&
8821 !a->loading_done) {
8822 printf("\r");
8823 print_load_info(print_colored, print_found, print_trees,
8824 ncolored, nfound, ntrees);
8825 a->printed_something = 1;
8826 fflush(stdout);
8827 return NULL;
8828 } else if (!a->loading_done) {
8829 printf("\r");
8830 print_load_info(1, 1, 1, ncolored, nfound, ntrees);
8831 printf("\n");
8832 a->loading_done = 1;
8835 if (fmt_scaled(packfile_size, scaled_packsize) == -1)
8836 return got_error_from_errno("fmt_scaled");
8837 if (fmt_scaled(bytes_sent, scaled_sent) == -1)
8838 return got_error_from_errno("fmt_scaled");
8840 if (a->last_ncommits != ncommits) {
8841 print_searching = 1;
8842 a->last_ncommits = ncommits;
8845 if (a->last_nobj_total != nobj_total) {
8846 print_searching = 1;
8847 print_total = 1;
8848 a->last_nobj_total = nobj_total;
8851 if (packfile_size > 0 && (a->last_scaled_packsize[0] == '\0' ||
8852 strcmp(scaled_packsize, a->last_scaled_packsize)) != 0) {
8853 if (strlcpy(a->last_scaled_packsize, scaled_packsize,
8854 FMT_SCALED_STRSIZE) >= FMT_SCALED_STRSIZE)
8855 return got_error(GOT_ERR_NO_SPACE);
8858 if (nobj_deltify > 0 || nobj_written > 0) {
8859 if (nobj_deltify > 0) {
8860 p_deltify = (nobj_deltify * 100) / nobj_total;
8861 if (p_deltify != a->last_p_deltify) {
8862 a->last_p_deltify = p_deltify;
8863 print_searching = 1;
8864 print_total = 1;
8865 print_deltify = 1;
8868 if (nobj_written > 0) {
8869 p_written = (nobj_written * 100) / nobj_total;
8870 if (p_written != a->last_p_written) {
8871 a->last_p_written = p_written;
8872 print_searching = 1;
8873 print_total = 1;
8874 print_deltify = 1;
8875 print_written = 1;
8880 if (bytes_sent > 0) {
8881 p_sent = (bytes_sent * 100) / packfile_size;
8882 if (p_sent != a->last_p_sent) {
8883 a->last_p_sent = p_sent;
8884 print_searching = 1;
8885 print_total = 1;
8886 print_deltify = 1;
8887 print_written = 1;
8888 print_sent = 1;
8890 a->sent_something = 1;
8893 if (print_searching || print_total || print_deltify || print_written ||
8894 print_sent)
8895 printf("\r");
8896 if (print_searching)
8897 printf("packing %d reference%s", ncommits,
8898 ncommits == 1 ? "" : "s");
8899 if (print_total)
8900 printf("; %d object%s", nobj_total,
8901 nobj_total == 1 ? "" : "s");
8902 if (print_deltify)
8903 printf("; deltify: %d%%", p_deltify);
8904 if (print_sent)
8905 printf("; uploading pack: %*s %d%%", FMT_SCALED_STRSIZE - 2,
8906 scaled_packsize, p_sent);
8907 else if (print_written)
8908 printf("; writing pack: %*s %d%%", FMT_SCALED_STRSIZE - 2,
8909 scaled_packsize, p_written);
8910 if (print_searching || print_total || print_deltify ||
8911 print_written || print_sent) {
8912 a->printed_something = 1;
8913 fflush(stdout);
8915 return NULL;
8918 static const struct got_error *
8919 cmd_send(int argc, char *argv[])
8921 const struct got_error *error = NULL;
8922 char *cwd = NULL, *repo_path = NULL;
8923 const char *remote_name;
8924 char *proto = NULL, *host = NULL, *port = NULL;
8925 char *repo_name = NULL, *server_path = NULL;
8926 const struct got_remote_repo *remotes, *remote = NULL;
8927 int nremotes, nbranches = 0, ndelete_branches = 0;
8928 struct got_repository *repo = NULL;
8929 struct got_worktree *worktree = NULL;
8930 const struct got_gotconfig *repo_conf = NULL, *worktree_conf = NULL;
8931 struct got_pathlist_head branches;
8932 struct got_pathlist_head tags;
8933 struct got_reflist_head all_branches;
8934 struct got_reflist_head all_tags;
8935 struct got_pathlist_head delete_args;
8936 struct got_pathlist_head delete_branches;
8937 struct got_reflist_entry *re;
8938 struct got_pathlist_entry *pe;
8939 int i, ch, sendfd = -1, sendstatus;
8940 pid_t sendpid = -1;
8941 struct got_send_progress_arg spa;
8942 int verbosity = 0, overwrite_refs = 0;
8943 int send_all_branches = 0, send_all_tags = 0;
8944 struct got_reference *ref = NULL;
8945 int *pack_fds = NULL;
8947 TAILQ_INIT(&branches);
8948 TAILQ_INIT(&tags);
8949 TAILQ_INIT(&all_branches);
8950 TAILQ_INIT(&all_tags);
8951 TAILQ_INIT(&delete_args);
8952 TAILQ_INIT(&delete_branches);
8954 while ((ch = getopt(argc, argv, "ab:d:fqr:Tt:v")) != -1) {
8955 switch (ch) {
8956 case 'a':
8957 send_all_branches = 1;
8958 break;
8959 case 'b':
8960 error = got_pathlist_append(&branches, optarg, NULL);
8961 if (error)
8962 return error;
8963 nbranches++;
8964 break;
8965 case 'd':
8966 error = got_pathlist_append(&delete_args, optarg, NULL);
8967 if (error)
8968 return error;
8969 break;
8970 case 'f':
8971 overwrite_refs = 1;
8972 break;
8973 case 'q':
8974 verbosity = -1;
8975 break;
8976 case 'r':
8977 repo_path = realpath(optarg, NULL);
8978 if (repo_path == NULL)
8979 return got_error_from_errno2("realpath",
8980 optarg);
8981 got_path_strip_trailing_slashes(repo_path);
8982 break;
8983 case 'T':
8984 send_all_tags = 1;
8985 break;
8986 case 't':
8987 error = got_pathlist_append(&tags, optarg, NULL);
8988 if (error)
8989 return error;
8990 break;
8991 case 'v':
8992 if (verbosity < 0)
8993 verbosity = 0;
8994 else if (verbosity < 3)
8995 verbosity++;
8996 break;
8997 default:
8998 usage_send();
8999 /* NOTREACHED */
9002 argc -= optind;
9003 argv += optind;
9005 if (send_all_branches && !TAILQ_EMPTY(&branches))
9006 option_conflict('a', 'b');
9007 if (send_all_tags && !TAILQ_EMPTY(&tags))
9008 option_conflict('T', 't');
9011 if (argc == 0)
9012 remote_name = GOT_SEND_DEFAULT_REMOTE_NAME;
9013 else if (argc == 1)
9014 remote_name = argv[0];
9015 else
9016 usage_send();
9018 cwd = getcwd(NULL, 0);
9019 if (cwd == NULL) {
9020 error = got_error_from_errno("getcwd");
9021 goto done;
9024 error = got_repo_pack_fds_open(&pack_fds);
9025 if (error != NULL)
9026 goto done;
9028 if (repo_path == NULL) {
9029 error = got_worktree_open(&worktree, cwd);
9030 if (error && error->code != GOT_ERR_NOT_WORKTREE)
9031 goto done;
9032 else
9033 error = NULL;
9034 if (worktree) {
9035 repo_path =
9036 strdup(got_worktree_get_repo_path(worktree));
9037 if (repo_path == NULL)
9038 error = got_error_from_errno("strdup");
9039 if (error)
9040 goto done;
9041 } else {
9042 repo_path = strdup(cwd);
9043 if (repo_path == NULL) {
9044 error = got_error_from_errno("strdup");
9045 goto done;
9050 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
9051 if (error)
9052 goto done;
9054 if (worktree) {
9055 worktree_conf = got_worktree_get_gotconfig(worktree);
9056 if (worktree_conf) {
9057 got_gotconfig_get_remotes(&nremotes, &remotes,
9058 worktree_conf);
9059 for (i = 0; i < nremotes; i++) {
9060 if (strcmp(remotes[i].name, remote_name) == 0) {
9061 remote = &remotes[i];
9062 break;
9067 if (remote == NULL) {
9068 repo_conf = got_repo_get_gotconfig(repo);
9069 if (repo_conf) {
9070 got_gotconfig_get_remotes(&nremotes, &remotes,
9071 repo_conf);
9072 for (i = 0; i < nremotes; i++) {
9073 if (strcmp(remotes[i].name, remote_name) == 0) {
9074 remote = &remotes[i];
9075 break;
9080 if (remote == NULL) {
9081 got_repo_get_gitconfig_remotes(&nremotes, &remotes, repo);
9082 for (i = 0; i < nremotes; i++) {
9083 if (strcmp(remotes[i].name, remote_name) == 0) {
9084 remote = &remotes[i];
9085 break;
9089 if (remote == NULL) {
9090 error = got_error_path(remote_name, GOT_ERR_NO_REMOTE);
9091 goto done;
9094 error = got_dial_parse_uri(&proto, &host, &port, &server_path,
9095 &repo_name, remote->send_url);
9096 if (error)
9097 goto done;
9099 if (strcmp(proto, "git") == 0) {
9100 #ifndef PROFILE
9101 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
9102 "sendfd dns inet unveil", NULL) == -1)
9103 err(1, "pledge");
9104 #endif
9105 } else if (strcmp(proto, "git+ssh") == 0 ||
9106 strcmp(proto, "ssh") == 0) {
9107 #ifndef PROFILE
9108 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
9109 "sendfd unveil", NULL) == -1)
9110 err(1, "pledge");
9111 #endif
9112 } else if (strcmp(proto, "http") == 0 ||
9113 strcmp(proto, "git+http") == 0) {
9114 error = got_error_path(proto, GOT_ERR_NOT_IMPL);
9115 goto done;
9116 } else {
9117 error = got_error_path(proto, GOT_ERR_BAD_PROTO);
9118 goto done;
9121 error = got_dial_apply_unveil(proto);
9122 if (error)
9123 goto done;
9125 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
9126 if (error)
9127 goto done;
9129 if (send_all_branches) {
9130 error = got_ref_list(&all_branches, repo, "refs/heads",
9131 got_ref_cmp_by_name, NULL);
9132 if (error)
9133 goto done;
9134 TAILQ_FOREACH(re, &all_branches, entry) {
9135 const char *branchname = got_ref_get_name(re->ref);
9136 error = got_pathlist_append(&branches,
9137 branchname, NULL);
9138 if (error)
9139 goto done;
9140 nbranches++;
9142 } else if (nbranches == 0) {
9143 for (i = 0; i < remote->nsend_branches; i++) {
9144 got_pathlist_append(&branches,
9145 remote->send_branches[i], NULL);
9149 if (send_all_tags) {
9150 error = got_ref_list(&all_tags, repo, "refs/tags",
9151 got_ref_cmp_by_name, NULL);
9152 if (error)
9153 goto done;
9154 TAILQ_FOREACH(re, &all_tags, entry) {
9155 const char *tagname = got_ref_get_name(re->ref);
9156 error = got_pathlist_append(&tags,
9157 tagname, NULL);
9158 if (error)
9159 goto done;
9164 * To prevent accidents only branches in refs/heads/ can be deleted
9165 * with 'got send -d'.
9166 * Deleting anything else requires local repository access or Git.
9168 TAILQ_FOREACH(pe, &delete_args, entry) {
9169 const char *branchname = pe->path;
9170 char *s;
9171 struct got_pathlist_entry *new;
9172 if (strncmp(branchname, "refs/heads/", 11) == 0) {
9173 s = strdup(branchname);
9174 if (s == NULL) {
9175 error = got_error_from_errno("strdup");
9176 goto done;
9178 } else {
9179 if (asprintf(&s, "refs/heads/%s", branchname) == -1) {
9180 error = got_error_from_errno("asprintf");
9181 goto done;
9184 error = got_pathlist_insert(&new, &delete_branches, s, NULL);
9185 if (error || new == NULL /* duplicate */)
9186 free(s);
9187 if (error)
9188 goto done;
9189 ndelete_branches++;
9192 if (nbranches == 0 && ndelete_branches == 0) {
9193 struct got_reference *head_ref;
9194 if (worktree)
9195 error = got_ref_open(&head_ref, repo,
9196 got_worktree_get_head_ref_name(worktree), 0);
9197 else
9198 error = got_ref_open(&head_ref, repo, GOT_REF_HEAD, 0);
9199 if (error)
9200 goto done;
9201 if (got_ref_is_symbolic(head_ref)) {
9202 error = got_ref_resolve_symbolic(&ref, repo, head_ref);
9203 got_ref_close(head_ref);
9204 if (error)
9205 goto done;
9206 } else
9207 ref = head_ref;
9208 error = got_pathlist_append(&branches, got_ref_get_name(ref),
9209 NULL);
9210 if (error)
9211 goto done;
9212 nbranches++;
9215 if (verbosity >= 0)
9216 printf("Connecting to \"%s\" %s%s%s\n", remote->name, host,
9217 port ? ":" : "", port ? port : "");
9219 error = got_send_connect(&sendpid, &sendfd, proto, host, port,
9220 server_path, verbosity);
9221 if (error)
9222 goto done;
9224 memset(&spa, 0, sizeof(spa));
9225 spa.last_scaled_packsize[0] = '\0';
9226 spa.last_p_deltify = -1;
9227 spa.last_p_written = -1;
9228 spa.verbosity = verbosity;
9229 spa.delete_branches = &delete_branches;
9230 error = got_send_pack(remote_name, &branches, &tags, &delete_branches,
9231 verbosity, overwrite_refs, sendfd, repo, send_progress, &spa,
9232 check_cancelled, NULL);
9233 if (spa.printed_something)
9234 putchar('\n');
9235 if (error)
9236 goto done;
9237 if (!spa.sent_something && verbosity >= 0)
9238 printf("Already up-to-date\n");
9239 done:
9240 if (sendpid > 0) {
9241 if (kill(sendpid, SIGTERM) == -1)
9242 error = got_error_from_errno("kill");
9243 if (waitpid(sendpid, &sendstatus, 0) == -1 && error == NULL)
9244 error = got_error_from_errno("waitpid");
9246 if (sendfd != -1 && close(sendfd) == -1 && error == NULL)
9247 error = got_error_from_errno("close");
9248 if (repo) {
9249 const struct got_error *close_err = got_repo_close(repo);
9250 if (error == NULL)
9251 error = close_err;
9253 if (worktree)
9254 got_worktree_close(worktree);
9255 if (pack_fds) {
9256 const struct got_error *pack_err =
9257 got_repo_pack_fds_close(pack_fds);
9258 if (error == NULL)
9259 error = pack_err;
9261 if (ref)
9262 got_ref_close(ref);
9263 got_pathlist_free(&branches);
9264 got_pathlist_free(&tags);
9265 got_ref_list_free(&all_branches);
9266 got_ref_list_free(&all_tags);
9267 got_pathlist_free(&delete_args);
9268 TAILQ_FOREACH(pe, &delete_branches, entry)
9269 free((char *)pe->path);
9270 got_pathlist_free(&delete_branches);
9271 free(cwd);
9272 free(repo_path);
9273 free(proto);
9274 free(host);
9275 free(port);
9276 free(server_path);
9277 free(repo_name);
9278 return error;
9281 __dead static void
9282 usage_cherrypick(void)
9284 fprintf(stderr, "usage: %s cherrypick commit-id\n", getprogname());
9285 exit(1);
9288 static const struct got_error *
9289 cmd_cherrypick(int argc, char *argv[])
9291 const struct got_error *error = NULL;
9292 struct got_worktree *worktree = NULL;
9293 struct got_repository *repo = NULL;
9294 char *cwd = NULL, *commit_id_str = NULL;
9295 struct got_object_id *commit_id = NULL;
9296 struct got_commit_object *commit = NULL;
9297 struct got_object_qid *pid;
9298 int ch;
9299 struct got_update_progress_arg upa;
9300 int *pack_fds = NULL;
9302 while ((ch = getopt(argc, argv, "")) != -1) {
9303 switch (ch) {
9304 default:
9305 usage_cherrypick();
9306 /* NOTREACHED */
9310 argc -= optind;
9311 argv += optind;
9313 #ifndef PROFILE
9314 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
9315 "unveil", NULL) == -1)
9316 err(1, "pledge");
9317 #endif
9318 if (argc != 1)
9319 usage_cherrypick();
9321 cwd = getcwd(NULL, 0);
9322 if (cwd == NULL) {
9323 error = got_error_from_errno("getcwd");
9324 goto done;
9327 error = got_repo_pack_fds_open(&pack_fds);
9328 if (error != NULL)
9329 goto done;
9331 error = got_worktree_open(&worktree, cwd);
9332 if (error) {
9333 if (error->code == GOT_ERR_NOT_WORKTREE)
9334 error = wrap_not_worktree_error(error, "cherrypick",
9335 cwd);
9336 goto done;
9339 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
9340 NULL, pack_fds);
9341 if (error != NULL)
9342 goto done;
9344 error = apply_unveil(got_repo_get_path(repo), 0,
9345 got_worktree_get_root_path(worktree));
9346 if (error)
9347 goto done;
9349 error = got_repo_match_object_id(&commit_id, NULL, argv[0],
9350 GOT_OBJ_TYPE_COMMIT, NULL, repo);
9351 if (error)
9352 goto done;
9353 error = got_object_id_str(&commit_id_str, commit_id);
9354 if (error)
9355 goto done;
9357 error = got_object_open_as_commit(&commit, repo, commit_id);
9358 if (error)
9359 goto done;
9360 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
9361 memset(&upa, 0, sizeof(upa));
9362 error = got_worktree_merge_files(worktree, pid ? &pid->id : NULL,
9363 commit_id, repo, update_progress, &upa, check_cancelled,
9364 NULL);
9365 if (error != NULL)
9366 goto done;
9368 if (upa.did_something)
9369 printf("Merged commit %s\n", commit_id_str);
9370 print_merge_progress_stats(&upa);
9371 done:
9372 if (commit)
9373 got_object_commit_close(commit);
9374 free(commit_id_str);
9375 if (worktree)
9376 got_worktree_close(worktree);
9377 if (repo) {
9378 const struct got_error *close_err = got_repo_close(repo);
9379 if (error == NULL)
9380 error = close_err;
9382 if (pack_fds) {
9383 const struct got_error *pack_err =
9384 got_repo_pack_fds_close(pack_fds);
9385 if (error == NULL)
9386 error = pack_err;
9389 return error;
9392 __dead static void
9393 usage_backout(void)
9395 fprintf(stderr, "usage: %s backout commit-id\n", getprogname());
9396 exit(1);
9399 static const struct got_error *
9400 cmd_backout(int argc, char *argv[])
9402 const struct got_error *error = NULL;
9403 struct got_worktree *worktree = NULL;
9404 struct got_repository *repo = NULL;
9405 char *cwd = NULL, *commit_id_str = NULL;
9406 struct got_object_id *commit_id = NULL;
9407 struct got_commit_object *commit = NULL;
9408 struct got_object_qid *pid;
9409 int ch;
9410 struct got_update_progress_arg upa;
9411 int *pack_fds = NULL;
9413 while ((ch = getopt(argc, argv, "")) != -1) {
9414 switch (ch) {
9415 default:
9416 usage_backout();
9417 /* NOTREACHED */
9421 argc -= optind;
9422 argv += optind;
9424 #ifndef PROFILE
9425 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
9426 "unveil", NULL) == -1)
9427 err(1, "pledge");
9428 #endif
9429 if (argc != 1)
9430 usage_backout();
9432 cwd = getcwd(NULL, 0);
9433 if (cwd == NULL) {
9434 error = got_error_from_errno("getcwd");
9435 goto done;
9438 error = got_repo_pack_fds_open(&pack_fds);
9439 if (error != NULL)
9440 goto done;
9442 error = got_worktree_open(&worktree, cwd);
9443 if (error) {
9444 if (error->code == GOT_ERR_NOT_WORKTREE)
9445 error = wrap_not_worktree_error(error, "backout", cwd);
9446 goto done;
9449 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
9450 NULL, pack_fds);
9451 if (error != NULL)
9452 goto done;
9454 error = apply_unveil(got_repo_get_path(repo), 0,
9455 got_worktree_get_root_path(worktree));
9456 if (error)
9457 goto done;
9459 error = got_repo_match_object_id(&commit_id, NULL, argv[0],
9460 GOT_OBJ_TYPE_COMMIT, NULL, repo);
9461 if (error)
9462 goto done;
9463 error = got_object_id_str(&commit_id_str, commit_id);
9464 if (error)
9465 goto done;
9467 error = got_object_open_as_commit(&commit, repo, commit_id);
9468 if (error)
9469 goto done;
9470 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
9471 if (pid == NULL) {
9472 error = got_error(GOT_ERR_ROOT_COMMIT);
9473 goto done;
9476 memset(&upa, 0, sizeof(upa));
9477 error = got_worktree_merge_files(worktree, commit_id, &pid->id,
9478 repo, update_progress, &upa, check_cancelled, NULL);
9479 if (error != NULL)
9480 goto done;
9482 if (upa.did_something)
9483 printf("Backed out commit %s\n", commit_id_str);
9484 print_merge_progress_stats(&upa);
9485 done:
9486 if (commit)
9487 got_object_commit_close(commit);
9488 free(commit_id_str);
9489 if (worktree)
9490 got_worktree_close(worktree);
9491 if (repo) {
9492 const struct got_error *close_err = got_repo_close(repo);
9493 if (error == NULL)
9494 error = close_err;
9496 if (pack_fds) {
9497 const struct got_error *pack_err =
9498 got_repo_pack_fds_close(pack_fds);
9499 if (error == NULL)
9500 error = pack_err;
9502 return error;
9505 __dead static void
9506 usage_rebase(void)
9508 fprintf(stderr, "usage: %s rebase [-aclX] [branch]\n", getprogname());
9509 exit(1);
9512 static void
9513 trim_logmsg(char *logmsg, int limit)
9515 char *nl;
9516 size_t len;
9518 len = strlen(logmsg);
9519 if (len > limit)
9520 len = limit;
9521 logmsg[len] = '\0';
9522 nl = strchr(logmsg, '\n');
9523 if (nl)
9524 *nl = '\0';
9527 static const struct got_error *
9528 get_short_logmsg(char **logmsg, int limit, struct got_commit_object *commit)
9530 const struct got_error *err;
9531 char *logmsg0 = NULL;
9532 const char *s;
9534 err = got_object_commit_get_logmsg(&logmsg0, commit);
9535 if (err)
9536 return err;
9538 s = logmsg0;
9539 while (isspace((unsigned char)s[0]))
9540 s++;
9542 *logmsg = strdup(s);
9543 if (*logmsg == NULL) {
9544 err = got_error_from_errno("strdup");
9545 goto done;
9548 trim_logmsg(*logmsg, limit);
9549 done:
9550 free(logmsg0);
9551 return err;
9554 static const struct got_error *
9555 show_rebase_merge_conflict(struct got_object_id *id,
9556 struct got_repository *repo)
9558 const struct got_error *err;
9559 struct got_commit_object *commit = NULL;
9560 char *id_str = NULL, *logmsg = NULL;
9562 err = got_object_open_as_commit(&commit, repo, id);
9563 if (err)
9564 return err;
9566 err = got_object_id_str(&id_str, id);
9567 if (err)
9568 goto done;
9570 id_str[12] = '\0';
9572 err = get_short_logmsg(&logmsg, 42, commit);
9573 if (err)
9574 goto done;
9576 printf("%s -> merge conflict: %s\n", id_str, logmsg);
9577 done:
9578 free(id_str);
9579 got_object_commit_close(commit);
9580 free(logmsg);
9581 return err;
9584 static const struct got_error *
9585 show_rebase_progress(struct got_commit_object *commit,
9586 struct got_object_id *old_id, struct got_object_id *new_id)
9588 const struct got_error *err;
9589 char *old_id_str = NULL, *new_id_str = NULL, *logmsg = NULL;
9591 err = got_object_id_str(&old_id_str, old_id);
9592 if (err)
9593 goto done;
9595 if (new_id) {
9596 err = got_object_id_str(&new_id_str, new_id);
9597 if (err)
9598 goto done;
9601 old_id_str[12] = '\0';
9602 if (new_id_str)
9603 new_id_str[12] = '\0';
9605 err = get_short_logmsg(&logmsg, 42, commit);
9606 if (err)
9607 goto done;
9609 printf("%s -> %s: %s\n", old_id_str,
9610 new_id_str ? new_id_str : "no-op change", logmsg);
9611 done:
9612 free(old_id_str);
9613 free(new_id_str);
9614 free(logmsg);
9615 return err;
9618 static const struct got_error *
9619 rebase_complete(struct got_worktree *worktree, struct got_fileindex *fileindex,
9620 struct got_reference *branch, struct got_reference *new_base_branch,
9621 struct got_reference *tmp_branch, struct got_repository *repo,
9622 int create_backup)
9624 printf("Switching work tree to %s\n", got_ref_get_name(branch));
9625 return got_worktree_rebase_complete(worktree, fileindex,
9626 new_base_branch, tmp_branch, branch, repo, create_backup);
9629 static const struct got_error *
9630 rebase_commit(struct got_pathlist_head *merged_paths,
9631 struct got_worktree *worktree, struct got_fileindex *fileindex,
9632 struct got_reference *tmp_branch, const char *committer,
9633 struct got_object_id *commit_id, struct got_repository *repo)
9635 const struct got_error *error;
9636 struct got_commit_object *commit;
9637 struct got_object_id *new_commit_id;
9639 error = got_object_open_as_commit(&commit, repo, commit_id);
9640 if (error)
9641 return error;
9643 error = got_worktree_rebase_commit(&new_commit_id, merged_paths,
9644 worktree, fileindex, tmp_branch, committer, commit, commit_id,
9645 repo);
9646 if (error) {
9647 if (error->code != GOT_ERR_COMMIT_NO_CHANGES)
9648 goto done;
9649 error = show_rebase_progress(commit, commit_id, NULL);
9650 } else {
9651 error = show_rebase_progress(commit, commit_id, new_commit_id);
9652 free(new_commit_id);
9654 done:
9655 got_object_commit_close(commit);
9656 return error;
9659 struct check_path_prefix_arg {
9660 const char *path_prefix;
9661 size_t len;
9662 int errcode;
9665 static const struct got_error *
9666 check_path_prefix_in_diff(void *arg, struct got_blob_object *blob1,
9667 struct got_blob_object *blob2, FILE *f1, FILE *f2,
9668 struct got_object_id *id1, struct got_object_id *id2,
9669 const char *path1, const char *path2,
9670 mode_t mode1, mode_t mode2, struct got_repository *repo)
9672 struct check_path_prefix_arg *a = arg;
9674 if ((path1 && !got_path_is_child(path1, a->path_prefix, a->len)) ||
9675 (path2 && !got_path_is_child(path2, a->path_prefix, a->len)))
9676 return got_error(a->errcode);
9678 return NULL;
9681 static const struct got_error *
9682 check_path_prefix(struct got_object_id *parent_id,
9683 struct got_object_id *commit_id, const char *path_prefix,
9684 int errcode, struct got_repository *repo)
9686 const struct got_error *err;
9687 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
9688 struct got_commit_object *commit = NULL, *parent_commit = NULL;
9689 struct check_path_prefix_arg cpp_arg;
9691 if (got_path_is_root_dir(path_prefix))
9692 return NULL;
9694 err = got_object_open_as_commit(&commit, repo, commit_id);
9695 if (err)
9696 goto done;
9698 err = got_object_open_as_commit(&parent_commit, repo, parent_id);
9699 if (err)
9700 goto done;
9702 err = got_object_open_as_tree(&tree1, repo,
9703 got_object_commit_get_tree_id(parent_commit));
9704 if (err)
9705 goto done;
9707 err = got_object_open_as_tree(&tree2, repo,
9708 got_object_commit_get_tree_id(commit));
9709 if (err)
9710 goto done;
9712 cpp_arg.path_prefix = path_prefix;
9713 while (cpp_arg.path_prefix[0] == '/')
9714 cpp_arg.path_prefix++;
9715 cpp_arg.len = strlen(cpp_arg.path_prefix);
9716 cpp_arg.errcode = errcode;
9717 err = got_diff_tree(tree1, tree2, NULL, NULL, -1, -1, "", "", repo,
9718 check_path_prefix_in_diff, &cpp_arg, 0);
9719 done:
9720 if (tree1)
9721 got_object_tree_close(tree1);
9722 if (tree2)
9723 got_object_tree_close(tree2);
9724 if (commit)
9725 got_object_commit_close(commit);
9726 if (parent_commit)
9727 got_object_commit_close(parent_commit);
9728 return err;
9731 static const struct got_error *
9732 collect_commits(struct got_object_id_queue *commits,
9733 struct got_object_id *initial_commit_id,
9734 struct got_object_id *iter_start_id, struct got_object_id *iter_stop_id,
9735 const char *path_prefix, int path_prefix_errcode,
9736 struct got_repository *repo)
9738 const struct got_error *err = NULL;
9739 struct got_commit_graph *graph = NULL;
9740 struct got_object_id parent_id, commit_id;
9741 struct got_object_qid *qid;
9743 err = got_commit_graph_open(&graph, "/", 1);
9744 if (err)
9745 return err;
9747 err = got_commit_graph_iter_start(graph, iter_start_id, repo,
9748 check_cancelled, NULL);
9749 if (err)
9750 goto done;
9752 memcpy(&commit_id, initial_commit_id, sizeof(commit_id));
9753 while (got_object_id_cmp(&commit_id, iter_stop_id) != 0) {
9754 err = got_commit_graph_iter_next(&parent_id, graph, repo,
9755 check_cancelled, NULL);
9756 if (err) {
9757 if (err->code == GOT_ERR_ITER_COMPLETED) {
9758 err = got_error_msg(GOT_ERR_ANCESTRY,
9759 "ran out of commits to rebase before "
9760 "youngest common ancestor commit has "
9761 "been reached?!?");
9763 goto done;
9764 } else {
9765 err = check_path_prefix(&parent_id, &commit_id,
9766 path_prefix, path_prefix_errcode, repo);
9767 if (err)
9768 goto done;
9770 err = got_object_qid_alloc(&qid, &commit_id);
9771 if (err)
9772 goto done;
9773 STAILQ_INSERT_HEAD(commits, qid, entry);
9775 memcpy(&commit_id, &parent_id, sizeof(commit_id));
9778 done:
9779 got_commit_graph_close(graph);
9780 return err;
9783 static const struct got_error *
9784 get_commit_brief_str(char **brief_str, struct got_commit_object *commit)
9786 const struct got_error *err = NULL;
9787 time_t committer_time;
9788 struct tm tm;
9789 char datebuf[11]; /* YYYY-MM-DD + NUL */
9790 char *author0 = NULL, *author, *smallerthan;
9791 char *logmsg0 = NULL, *logmsg, *newline;
9793 committer_time = got_object_commit_get_committer_time(commit);
9794 if (gmtime_r(&committer_time, &tm) == NULL)
9795 return got_error_from_errno("gmtime_r");
9796 if (strftime(datebuf, sizeof(datebuf), "%G-%m-%d", &tm) == 0)
9797 return got_error(GOT_ERR_NO_SPACE);
9799 author0 = strdup(got_object_commit_get_author(commit));
9800 if (author0 == NULL)
9801 return got_error_from_errno("strdup");
9802 author = author0;
9803 smallerthan = strchr(author, '<');
9804 if (smallerthan && smallerthan[1] != '\0')
9805 author = smallerthan + 1;
9806 author[strcspn(author, "@>")] = '\0';
9808 err = got_object_commit_get_logmsg(&logmsg0, commit);
9809 if (err)
9810 goto done;
9811 logmsg = logmsg0;
9812 while (*logmsg == '\n')
9813 logmsg++;
9814 newline = strchr(logmsg, '\n');
9815 if (newline)
9816 *newline = '\0';
9818 if (asprintf(brief_str, "%s %s %s",
9819 datebuf, author, logmsg) == -1)
9820 err = got_error_from_errno("asprintf");
9821 done:
9822 free(author0);
9823 free(logmsg0);
9824 return err;
9827 static const struct got_error *
9828 delete_backup_ref(struct got_reference *ref, struct got_object_id *id,
9829 struct got_repository *repo)
9831 const struct got_error *err;
9832 char *id_str;
9834 err = got_object_id_str(&id_str, id);
9835 if (err)
9836 return err;
9838 err = got_ref_delete(ref, repo);
9839 if (err)
9840 goto done;
9842 printf("Deleted %s: %s\n", got_ref_get_name(ref), id_str);
9843 done:
9844 free(id_str);
9845 return err;
9848 static const struct got_error *
9849 print_backup_ref(const char *branch_name, const char *new_id_str,
9850 struct got_object_id *old_commit_id, struct got_commit_object *old_commit,
9851 struct got_reflist_object_id_map *refs_idmap,
9852 struct got_repository *repo)
9854 const struct got_error *err = NULL;
9855 struct got_reflist_head *refs;
9856 char *refs_str = NULL;
9857 struct got_object_id *new_commit_id = NULL;
9858 struct got_commit_object *new_commit = NULL;
9859 char *new_commit_brief_str = NULL;
9860 struct got_object_id *yca_id = NULL;
9861 struct got_commit_object *yca_commit = NULL;
9862 char *yca_id_str = NULL, *yca_brief_str = NULL;
9863 char *custom_refs_str;
9865 if (asprintf(&custom_refs_str, "formerly %s", branch_name) == -1)
9866 return got_error_from_errno("asprintf");
9868 err = print_commit(old_commit, old_commit_id, repo, NULL, NULL,
9869 0, 0, refs_idmap, custom_refs_str);
9870 if (err)
9871 goto done;
9873 err = got_object_resolve_id_str(&new_commit_id, repo, new_id_str);
9874 if (err)
9875 goto done;
9877 refs = got_reflist_object_id_map_lookup(refs_idmap, new_commit_id);
9878 if (refs) {
9879 err = build_refs_str(&refs_str, refs, new_commit_id, repo, 0);
9880 if (err)
9881 goto done;
9884 err = got_object_open_as_commit(&new_commit, repo, new_commit_id);
9885 if (err)
9886 goto done;
9888 err = get_commit_brief_str(&new_commit_brief_str, new_commit);
9889 if (err)
9890 goto done;
9892 err = got_commit_graph_find_youngest_common_ancestor(&yca_id,
9893 old_commit_id, new_commit_id, 1, repo, check_cancelled, NULL);
9894 if (err)
9895 goto done;
9897 printf("has become commit %s%s%s%s\n %s\n", new_id_str,
9898 refs_str ? " (" : "", refs_str ? refs_str : "",
9899 refs_str ? ")" : "", new_commit_brief_str);
9900 if (yca_id && got_object_id_cmp(yca_id, new_commit_id) != 0 &&
9901 got_object_id_cmp(yca_id, old_commit_id) != 0) {
9902 free(refs_str);
9903 refs_str = NULL;
9905 err = got_object_open_as_commit(&yca_commit, repo, yca_id);
9906 if (err)
9907 goto done;
9909 err = get_commit_brief_str(&yca_brief_str, yca_commit);
9910 if (err)
9911 goto done;
9913 err = got_object_id_str(&yca_id_str, yca_id);
9914 if (err)
9915 goto done;
9917 refs = got_reflist_object_id_map_lookup(refs_idmap, yca_id);
9918 if (refs) {
9919 err = build_refs_str(&refs_str, refs, yca_id, repo, 0);
9920 if (err)
9921 goto done;
9923 printf("history forked at %s%s%s%s\n %s\n",
9924 yca_id_str,
9925 refs_str ? " (" : "", refs_str ? refs_str : "",
9926 refs_str ? ")" : "", yca_brief_str);
9928 done:
9929 free(custom_refs_str);
9930 free(new_commit_id);
9931 free(refs_str);
9932 free(yca_id);
9933 free(yca_id_str);
9934 free(yca_brief_str);
9935 if (new_commit)
9936 got_object_commit_close(new_commit);
9937 if (yca_commit)
9938 got_object_commit_close(yca_commit);
9940 return NULL;
9943 static const struct got_error *
9944 process_backup_refs(const char *backup_ref_prefix,
9945 const char *wanted_branch_name,
9946 int delete, struct got_repository *repo)
9948 const struct got_error *err;
9949 struct got_reflist_head refs, backup_refs;
9950 struct got_reflist_entry *re;
9951 const size_t backup_ref_prefix_len = strlen(backup_ref_prefix);
9952 struct got_object_id *old_commit_id = NULL;
9953 char *branch_name = NULL;
9954 struct got_commit_object *old_commit = NULL;
9955 struct got_reflist_object_id_map *refs_idmap = NULL;
9956 int wanted_branch_found = 0;
9958 TAILQ_INIT(&refs);
9959 TAILQ_INIT(&backup_refs);
9961 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
9962 if (err)
9963 return err;
9965 err = got_reflist_object_id_map_create(&refs_idmap, &refs, repo);
9966 if (err)
9967 goto done;
9969 if (wanted_branch_name) {
9970 if (strncmp(wanted_branch_name, "refs/heads/", 11) == 0)
9971 wanted_branch_name += 11;
9974 err = got_ref_list(&backup_refs, repo, backup_ref_prefix,
9975 got_ref_cmp_by_commit_timestamp_descending, repo);
9976 if (err)
9977 goto done;
9979 TAILQ_FOREACH(re, &backup_refs, entry) {
9980 const char *refname = got_ref_get_name(re->ref);
9981 char *slash;
9983 err = check_cancelled(NULL);
9984 if (err)
9985 break;
9987 err = got_ref_resolve(&old_commit_id, repo, re->ref);
9988 if (err)
9989 break;
9991 err = got_object_open_as_commit(&old_commit, repo,
9992 old_commit_id);
9993 if (err)
9994 break;
9996 if (strncmp(backup_ref_prefix, refname,
9997 backup_ref_prefix_len) == 0)
9998 refname += backup_ref_prefix_len;
10000 while (refname[0] == '/')
10001 refname++;
10003 branch_name = strdup(refname);
10004 if (branch_name == NULL) {
10005 err = got_error_from_errno("strdup");
10006 break;
10008 slash = strrchr(branch_name, '/');
10009 if (slash) {
10010 *slash = '\0';
10011 refname += strlen(branch_name) + 1;
10014 if (wanted_branch_name == NULL ||
10015 strcmp(wanted_branch_name, branch_name) == 0) {
10016 wanted_branch_found = 1;
10017 if (delete) {
10018 err = delete_backup_ref(re->ref,
10019 old_commit_id, repo);
10020 } else {
10021 err = print_backup_ref(branch_name, refname,
10022 old_commit_id, old_commit, refs_idmap,
10023 repo);
10025 if (err)
10026 break;
10029 free(old_commit_id);
10030 old_commit_id = NULL;
10031 free(branch_name);
10032 branch_name = NULL;
10033 got_object_commit_close(old_commit);
10034 old_commit = NULL;
10037 if (wanted_branch_name && !wanted_branch_found) {
10038 err = got_error_fmt(GOT_ERR_NOT_REF,
10039 "%s/%s/", backup_ref_prefix, wanted_branch_name);
10041 done:
10042 if (refs_idmap)
10043 got_reflist_object_id_map_free(refs_idmap);
10044 got_ref_list_free(&refs);
10045 got_ref_list_free(&backup_refs);
10046 free(old_commit_id);
10047 free(branch_name);
10048 if (old_commit)
10049 got_object_commit_close(old_commit);
10050 return err;
10053 static const struct got_error *
10054 abort_progress(void *arg, unsigned char status, const char *path)
10057 * Unversioned files should not clutter progress output when
10058 * an operation is aborted.
10060 if (status == GOT_STATUS_UNVERSIONED)
10061 return NULL;
10063 return update_progress(arg, status, path);
10066 static const struct got_error *
10067 cmd_rebase(int argc, char *argv[])
10069 const struct got_error *error = NULL;
10070 struct got_worktree *worktree = NULL;
10071 struct got_repository *repo = NULL;
10072 struct got_fileindex *fileindex = NULL;
10073 char *cwd = NULL, *committer = NULL, *gitconfig_path = NULL;
10074 struct got_reference *branch = NULL;
10075 struct got_reference *new_base_branch = NULL, *tmp_branch = NULL;
10076 struct got_object_id *commit_id = NULL, *parent_id = NULL;
10077 struct got_object_id *resume_commit_id = NULL;
10078 struct got_object_id *branch_head_commit_id = NULL, *yca_id = NULL;
10079 struct got_commit_object *commit = NULL;
10080 int ch, rebase_in_progress = 0, abort_rebase = 0, continue_rebase = 0;
10081 int histedit_in_progress = 0, merge_in_progress = 0;
10082 int create_backup = 1, list_backups = 0, delete_backups = 0;
10083 struct got_object_id_queue commits;
10084 struct got_pathlist_head merged_paths;
10085 const struct got_object_id_queue *parent_ids;
10086 struct got_object_qid *qid, *pid;
10087 struct got_update_progress_arg upa;
10088 int *pack_fds = NULL;
10090 STAILQ_INIT(&commits);
10091 TAILQ_INIT(&merged_paths);
10092 memset(&upa, 0, sizeof(upa));
10094 while ((ch = getopt(argc, argv, "aclX")) != -1) {
10095 switch (ch) {
10096 case 'a':
10097 abort_rebase = 1;
10098 break;
10099 case 'c':
10100 continue_rebase = 1;
10101 break;
10102 case 'l':
10103 list_backups = 1;
10104 break;
10105 case 'X':
10106 delete_backups = 1;
10107 break;
10108 default:
10109 usage_rebase();
10110 /* NOTREACHED */
10114 argc -= optind;
10115 argv += optind;
10117 #ifndef PROFILE
10118 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
10119 "unveil", NULL) == -1)
10120 err(1, "pledge");
10121 #endif
10122 if (list_backups) {
10123 if (abort_rebase)
10124 option_conflict('l', 'a');
10125 if (continue_rebase)
10126 option_conflict('l', 'c');
10127 if (delete_backups)
10128 option_conflict('l', 'X');
10129 if (argc != 0 && argc != 1)
10130 usage_rebase();
10131 } else if (delete_backups) {
10132 if (abort_rebase)
10133 option_conflict('X', 'a');
10134 if (continue_rebase)
10135 option_conflict('X', 'c');
10136 if (list_backups)
10137 option_conflict('l', 'X');
10138 if (argc != 0 && argc != 1)
10139 usage_rebase();
10140 } else {
10141 if (abort_rebase && continue_rebase)
10142 usage_rebase();
10143 else if (abort_rebase || continue_rebase) {
10144 if (argc != 0)
10145 usage_rebase();
10146 } else if (argc != 1)
10147 usage_rebase();
10150 cwd = getcwd(NULL, 0);
10151 if (cwd == NULL) {
10152 error = got_error_from_errno("getcwd");
10153 goto done;
10156 error = got_repo_pack_fds_open(&pack_fds);
10157 if (error != NULL)
10158 goto done;
10160 error = got_worktree_open(&worktree, cwd);
10161 if (error) {
10162 if (list_backups || delete_backups) {
10163 if (error->code != GOT_ERR_NOT_WORKTREE)
10164 goto done;
10165 } else {
10166 if (error->code == GOT_ERR_NOT_WORKTREE)
10167 error = wrap_not_worktree_error(error,
10168 "rebase", cwd);
10169 goto done;
10173 error = get_gitconfig_path(&gitconfig_path);
10174 if (error)
10175 goto done;
10176 error = got_repo_open(&repo,
10177 worktree ? got_worktree_get_repo_path(worktree) : cwd,
10178 gitconfig_path, pack_fds);
10179 if (error != NULL)
10180 goto done;
10182 error = get_author(&committer, repo, worktree);
10183 if (error && error->code != GOT_ERR_COMMIT_NO_AUTHOR)
10184 goto done;
10186 error = apply_unveil(got_repo_get_path(repo), 0,
10187 worktree ? got_worktree_get_root_path(worktree) : NULL);
10188 if (error)
10189 goto done;
10191 if (list_backups || delete_backups) {
10192 error = process_backup_refs(
10193 GOT_WORKTREE_REBASE_BACKUP_REF_PREFIX,
10194 argc == 1 ? argv[0] : NULL, delete_backups, repo);
10195 goto done; /* nothing else to do */
10198 error = got_worktree_histedit_in_progress(&histedit_in_progress,
10199 worktree);
10200 if (error)
10201 goto done;
10202 if (histedit_in_progress) {
10203 error = got_error(GOT_ERR_HISTEDIT_BUSY);
10204 goto done;
10207 error = got_worktree_merge_in_progress(&merge_in_progress,
10208 worktree, repo);
10209 if (error)
10210 goto done;
10211 if (merge_in_progress) {
10212 error = got_error(GOT_ERR_MERGE_BUSY);
10213 goto done;
10216 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
10217 if (error)
10218 goto done;
10220 if (abort_rebase) {
10221 if (!rebase_in_progress) {
10222 error = got_error(GOT_ERR_NOT_REBASING);
10223 goto done;
10225 error = got_worktree_rebase_continue(&resume_commit_id,
10226 &new_base_branch, &tmp_branch, &branch, &fileindex,
10227 worktree, repo);
10228 if (error)
10229 goto done;
10230 printf("Switching work tree to %s\n",
10231 got_ref_get_symref_target(new_base_branch));
10232 error = got_worktree_rebase_abort(worktree, fileindex, repo,
10233 new_base_branch, abort_progress, &upa);
10234 if (error)
10235 goto done;
10236 printf("Rebase of %s aborted\n", got_ref_get_name(branch));
10237 print_merge_progress_stats(&upa);
10238 goto done; /* nothing else to do */
10241 if (continue_rebase) {
10242 if (!rebase_in_progress) {
10243 error = got_error(GOT_ERR_NOT_REBASING);
10244 goto done;
10246 error = got_worktree_rebase_continue(&resume_commit_id,
10247 &new_base_branch, &tmp_branch, &branch, &fileindex,
10248 worktree, repo);
10249 if (error)
10250 goto done;
10252 error = rebase_commit(NULL, worktree, fileindex, tmp_branch,
10253 committer, resume_commit_id, repo);
10254 if (error)
10255 goto done;
10257 yca_id = got_object_id_dup(resume_commit_id);
10258 if (yca_id == NULL) {
10259 error = got_error_from_errno("got_object_id_dup");
10260 goto done;
10262 } else {
10263 error = got_ref_open(&branch, repo, argv[0], 0);
10264 if (error != NULL)
10265 goto done;
10266 if (strncmp(got_ref_get_name(branch), "refs/heads/", 11) != 0) {
10267 error = got_error_msg(GOT_ERR_COMMIT_BRANCH,
10268 "will not rebase a branch which lives outside "
10269 "the \"refs/heads/\" reference namespace");
10270 goto done;
10274 error = got_ref_resolve(&branch_head_commit_id, repo, branch);
10275 if (error)
10276 goto done;
10278 if (!continue_rebase) {
10279 struct got_object_id *base_commit_id;
10281 base_commit_id = got_worktree_get_base_commit_id(worktree);
10282 error = got_commit_graph_find_youngest_common_ancestor(&yca_id,
10283 base_commit_id, branch_head_commit_id, 1, repo,
10284 check_cancelled, NULL);
10285 if (error)
10286 goto done;
10287 if (yca_id == NULL) {
10288 error = got_error_msg(GOT_ERR_ANCESTRY,
10289 "specified branch shares no common ancestry "
10290 "with work tree's branch");
10291 goto done;
10294 error = check_same_branch(base_commit_id, branch, yca_id, repo);
10295 if (error) {
10296 if (error->code != GOT_ERR_ANCESTRY)
10297 goto done;
10298 error = NULL;
10299 } else {
10300 struct got_pathlist_head paths;
10301 printf("%s is already based on %s\n",
10302 got_ref_get_name(branch),
10303 got_worktree_get_head_ref_name(worktree));
10304 error = switch_head_ref(branch, branch_head_commit_id,
10305 worktree, repo);
10306 if (error)
10307 goto done;
10308 error = got_worktree_set_base_commit_id(worktree, repo,
10309 branch_head_commit_id);
10310 if (error)
10311 goto done;
10312 TAILQ_INIT(&paths);
10313 error = got_pathlist_append(&paths, "", NULL);
10314 if (error)
10315 goto done;
10316 error = got_worktree_checkout_files(worktree,
10317 &paths, repo, update_progress, &upa,
10318 check_cancelled, NULL);
10319 got_pathlist_free(&paths);
10320 if (error)
10321 goto done;
10322 if (upa.did_something) {
10323 char *id_str;
10324 error = got_object_id_str(&id_str,
10325 branch_head_commit_id);
10326 if (error)
10327 goto done;
10328 printf("Updated to %s: %s\n",
10329 got_worktree_get_head_ref_name(worktree),
10330 id_str);
10331 free(id_str);
10332 } else
10333 printf("Already up-to-date\n");
10334 print_update_progress_stats(&upa);
10335 goto done;
10339 commit_id = branch_head_commit_id;
10340 error = got_object_open_as_commit(&commit, repo, commit_id);
10341 if (error)
10342 goto done;
10344 parent_ids = got_object_commit_get_parent_ids(commit);
10345 pid = STAILQ_FIRST(parent_ids);
10346 if (pid == NULL) {
10347 error = got_error(GOT_ERR_EMPTY_REBASE);
10348 goto done;
10350 error = collect_commits(&commits, commit_id, &pid->id,
10351 yca_id, got_worktree_get_path_prefix(worktree),
10352 GOT_ERR_REBASE_PATH, repo);
10353 got_object_commit_close(commit);
10354 commit = NULL;
10355 if (error)
10356 goto done;
10358 if (!continue_rebase) {
10359 error = got_worktree_rebase_prepare(&new_base_branch,
10360 &tmp_branch, &fileindex, worktree, branch, repo);
10361 if (error)
10362 goto done;
10365 if (STAILQ_EMPTY(&commits)) {
10366 if (continue_rebase) {
10367 error = rebase_complete(worktree, fileindex,
10368 branch, new_base_branch, tmp_branch, repo,
10369 create_backup);
10370 goto done;
10371 } else {
10372 /* Fast-forward the reference of the branch. */
10373 struct got_object_id *new_head_commit_id;
10374 char *id_str;
10375 error = got_ref_resolve(&new_head_commit_id, repo,
10376 new_base_branch);
10377 if (error)
10378 goto done;
10379 error = got_object_id_str(&id_str, new_head_commit_id);
10380 if (error)
10381 goto done;
10382 printf("Forwarding %s to commit %s\n",
10383 got_ref_get_name(branch), id_str);
10384 free(id_str);
10385 error = got_ref_change_ref(branch,
10386 new_head_commit_id);
10387 if (error)
10388 goto done;
10389 /* No backup needed since objects did not change. */
10390 create_backup = 0;
10394 pid = NULL;
10395 STAILQ_FOREACH(qid, &commits, entry) {
10397 commit_id = &qid->id;
10398 parent_id = pid ? &pid->id : yca_id;
10399 pid = qid;
10401 memset(&upa, 0, sizeof(upa));
10402 error = got_worktree_rebase_merge_files(&merged_paths,
10403 worktree, fileindex, parent_id, commit_id, repo,
10404 update_progress, &upa, check_cancelled, NULL);
10405 if (error)
10406 goto done;
10408 print_merge_progress_stats(&upa);
10409 if (upa.conflicts > 0 || upa.missing > 0 ||
10410 upa.not_deleted > 0 || upa.unversioned > 0) {
10411 if (upa.conflicts > 0) {
10412 error = show_rebase_merge_conflict(&qid->id,
10413 repo);
10414 if (error)
10415 goto done;
10417 got_worktree_rebase_pathlist_free(&merged_paths);
10418 break;
10421 error = rebase_commit(&merged_paths, worktree, fileindex,
10422 tmp_branch, committer, commit_id, repo);
10423 got_worktree_rebase_pathlist_free(&merged_paths);
10424 if (error)
10425 goto done;
10428 if (upa.conflicts > 0 || upa.missing > 0 ||
10429 upa.not_deleted > 0 || upa.unversioned > 0) {
10430 error = got_worktree_rebase_postpone(worktree, fileindex);
10431 if (error)
10432 goto done;
10433 if (upa.conflicts > 0 && upa.missing == 0 &&
10434 upa.not_deleted == 0 && upa.unversioned == 0) {
10435 error = got_error_msg(GOT_ERR_CONFLICTS,
10436 "conflicts must be resolved before rebasing "
10437 "can continue");
10438 } else if (upa.conflicts > 0) {
10439 error = got_error_msg(GOT_ERR_CONFLICTS,
10440 "conflicts must be resolved before rebasing "
10441 "can continue; changes destined for some "
10442 "files were not yet merged and should be "
10443 "merged manually if required before the "
10444 "rebase operation is continued");
10445 } else {
10446 error = got_error_msg(GOT_ERR_CONFLICTS,
10447 "changes destined for some files were not "
10448 "yet merged and should be merged manually "
10449 "if required before the rebase operation "
10450 "is continued");
10452 } else
10453 error = rebase_complete(worktree, fileindex, branch,
10454 new_base_branch, tmp_branch, repo, create_backup);
10455 done:
10456 free(cwd);
10457 free(committer);
10458 free(gitconfig_path);
10459 got_object_id_queue_free(&commits);
10460 free(branch_head_commit_id);
10461 free(resume_commit_id);
10462 free(yca_id);
10463 if (commit)
10464 got_object_commit_close(commit);
10465 if (branch)
10466 got_ref_close(branch);
10467 if (new_base_branch)
10468 got_ref_close(new_base_branch);
10469 if (tmp_branch)
10470 got_ref_close(tmp_branch);
10471 if (worktree)
10472 got_worktree_close(worktree);
10473 if (repo) {
10474 const struct got_error *close_err = got_repo_close(repo);
10475 if (error == NULL)
10476 error = close_err;
10478 if (pack_fds) {
10479 const struct got_error *pack_err =
10480 got_repo_pack_fds_close(pack_fds);
10481 if (error == NULL)
10482 error = pack_err;
10484 return error;
10487 __dead static void
10488 usage_histedit(void)
10490 fprintf(stderr, "usage: %s histedit [-aceflmX] [-F histedit-script] "
10491 "[branch]\n", getprogname());
10492 exit(1);
10495 #define GOT_HISTEDIT_PICK 'p'
10496 #define GOT_HISTEDIT_EDIT 'e'
10497 #define GOT_HISTEDIT_FOLD 'f'
10498 #define GOT_HISTEDIT_DROP 'd'
10499 #define GOT_HISTEDIT_MESG 'm'
10501 static const struct got_histedit_cmd {
10502 unsigned char code;
10503 const char *name;
10504 const char *desc;
10505 } got_histedit_cmds[] = {
10506 { GOT_HISTEDIT_PICK, "pick", "use commit" },
10507 { GOT_HISTEDIT_EDIT, "edit", "use commit but stop for amending" },
10508 { GOT_HISTEDIT_FOLD, "fold", "combine with next commit that will "
10509 "be used" },
10510 { GOT_HISTEDIT_DROP, "drop", "remove commit from history" },
10511 { GOT_HISTEDIT_MESG, "mesg",
10512 "single-line log message for commit above (open editor if empty)" },
10515 struct got_histedit_list_entry {
10516 TAILQ_ENTRY(got_histedit_list_entry) entry;
10517 struct got_object_id *commit_id;
10518 const struct got_histedit_cmd *cmd;
10519 char *logmsg;
10521 TAILQ_HEAD(got_histedit_list, got_histedit_list_entry);
10523 static const struct got_error *
10524 histedit_write_commit(struct got_object_id *commit_id, const char *cmdname,
10525 FILE *f, struct got_repository *repo)
10527 const struct got_error *err = NULL;
10528 char *logmsg = NULL, *id_str = NULL;
10529 struct got_commit_object *commit = NULL;
10530 int n;
10532 err = got_object_open_as_commit(&commit, repo, commit_id);
10533 if (err)
10534 goto done;
10536 err = get_short_logmsg(&logmsg, 34, commit);
10537 if (err)
10538 goto done;
10540 err = got_object_id_str(&id_str, commit_id);
10541 if (err)
10542 goto done;
10544 n = fprintf(f, "%s %s %s\n", cmdname, id_str, logmsg);
10545 if (n < 0)
10546 err = got_ferror(f, GOT_ERR_IO);
10547 done:
10548 if (commit)
10549 got_object_commit_close(commit);
10550 free(id_str);
10551 free(logmsg);
10552 return err;
10555 static const struct got_error *
10556 histedit_write_commit_list(struct got_object_id_queue *commits,
10557 FILE *f, int edit_logmsg_only, int fold_only, int edit_only,
10558 struct got_repository *repo)
10560 const struct got_error *err = NULL;
10561 struct got_object_qid *qid;
10562 const char *histedit_cmd = NULL;
10564 if (STAILQ_EMPTY(commits))
10565 return got_error(GOT_ERR_EMPTY_HISTEDIT);
10567 STAILQ_FOREACH(qid, commits, entry) {
10568 histedit_cmd = got_histedit_cmds[0].name;
10569 if (edit_only)
10570 histedit_cmd = "edit";
10571 else if (fold_only && STAILQ_NEXT(qid, entry) != NULL)
10572 histedit_cmd = "fold";
10573 err = histedit_write_commit(&qid->id, histedit_cmd, f, repo);
10574 if (err)
10575 break;
10576 if (edit_logmsg_only) {
10577 int n = fprintf(f, "%c\n", GOT_HISTEDIT_MESG);
10578 if (n < 0) {
10579 err = got_ferror(f, GOT_ERR_IO);
10580 break;
10585 return err;
10588 static const struct got_error *
10589 write_cmd_list(FILE *f, const char *branch_name,
10590 struct got_object_id_queue *commits)
10592 const struct got_error *err = NULL;
10593 size_t i;
10594 int n;
10595 char *id_str;
10596 struct got_object_qid *qid;
10598 qid = STAILQ_FIRST(commits);
10599 err = got_object_id_str(&id_str, &qid->id);
10600 if (err)
10601 return err;
10603 n = fprintf(f,
10604 "# Editing the history of branch '%s' starting at\n"
10605 "# commit %s\n"
10606 "# Commits will be processed in order from top to "
10607 "bottom of this file.\n", branch_name, id_str);
10608 if (n < 0) {
10609 err = got_ferror(f, GOT_ERR_IO);
10610 goto done;
10613 n = fprintf(f, "# Available histedit commands:\n");
10614 if (n < 0) {
10615 err = got_ferror(f, GOT_ERR_IO);
10616 goto done;
10619 for (i = 0; i < nitems(got_histedit_cmds); i++) {
10620 const struct got_histedit_cmd *cmd = &got_histedit_cmds[i];
10621 n = fprintf(f, "# %s (%c): %s\n", cmd->name, cmd->code,
10622 cmd->desc);
10623 if (n < 0) {
10624 err = got_ferror(f, GOT_ERR_IO);
10625 break;
10628 done:
10629 free(id_str);
10630 return err;
10633 static const struct got_error *
10634 histedit_syntax_error(int lineno)
10636 static char msg[42];
10637 int ret;
10639 ret = snprintf(msg, sizeof(msg), "histedit syntax error on line %d",
10640 lineno);
10641 if (ret < 0 || (size_t)ret >= sizeof(msg))
10642 return got_error(GOT_ERR_HISTEDIT_SYNTAX);
10644 return got_error_msg(GOT_ERR_HISTEDIT_SYNTAX, msg);
10647 static const struct got_error *
10648 append_folded_commit_msg(char **new_msg, struct got_histedit_list_entry *hle,
10649 char *logmsg, struct got_repository *repo)
10651 const struct got_error *err;
10652 struct got_commit_object *folded_commit = NULL;
10653 char *id_str, *folded_logmsg = NULL;
10655 err = got_object_id_str(&id_str, hle->commit_id);
10656 if (err)
10657 return err;
10659 err = got_object_open_as_commit(&folded_commit, repo, hle->commit_id);
10660 if (err)
10661 goto done;
10663 err = got_object_commit_get_logmsg(&folded_logmsg, folded_commit);
10664 if (err)
10665 goto done;
10666 if (asprintf(new_msg, "%s%s# log message of folded commit %s: %s",
10667 logmsg ? logmsg : "", logmsg ? "\n" : "", id_str,
10668 folded_logmsg) == -1) {
10669 err = got_error_from_errno("asprintf");
10671 done:
10672 if (folded_commit)
10673 got_object_commit_close(folded_commit);
10674 free(id_str);
10675 free(folded_logmsg);
10676 return err;
10679 static struct got_histedit_list_entry *
10680 get_folded_commits(struct got_histedit_list_entry *hle)
10682 struct got_histedit_list_entry *prev, *folded = NULL;
10684 prev = TAILQ_PREV(hle, got_histedit_list, entry);
10685 while (prev && (prev->cmd->code == GOT_HISTEDIT_FOLD ||
10686 prev->cmd->code == GOT_HISTEDIT_DROP)) {
10687 if (prev->cmd->code == GOT_HISTEDIT_FOLD)
10688 folded = prev;
10689 prev = TAILQ_PREV(prev, got_histedit_list, entry);
10692 return folded;
10695 static const struct got_error *
10696 histedit_edit_logmsg(struct got_histedit_list_entry *hle,
10697 struct got_repository *repo)
10699 char *logmsg_path = NULL, *id_str = NULL, *orig_logmsg = NULL;
10700 char *logmsg = NULL, *new_msg = NULL, *editor = NULL;
10701 const struct got_error *err = NULL;
10702 struct got_commit_object *commit = NULL;
10703 int logmsg_len;
10704 int fd;
10705 struct got_histedit_list_entry *folded = NULL;
10707 err = got_object_open_as_commit(&commit, repo, hle->commit_id);
10708 if (err)
10709 return err;
10711 folded = get_folded_commits(hle);
10712 if (folded) {
10713 while (folded != hle) {
10714 if (folded->cmd->code == GOT_HISTEDIT_DROP) {
10715 folded = TAILQ_NEXT(folded, entry);
10716 continue;
10718 err = append_folded_commit_msg(&new_msg, folded,
10719 logmsg, repo);
10720 if (err)
10721 goto done;
10722 free(logmsg);
10723 logmsg = new_msg;
10724 folded = TAILQ_NEXT(folded, entry);
10728 err = got_object_id_str(&id_str, hle->commit_id);
10729 if (err)
10730 goto done;
10731 err = got_object_commit_get_logmsg(&orig_logmsg, commit);
10732 if (err)
10733 goto done;
10734 logmsg_len = asprintf(&new_msg,
10735 "%s\n# original log message of commit %s: %s",
10736 logmsg ? logmsg : "", id_str, orig_logmsg);
10737 if (logmsg_len == -1) {
10738 err = got_error_from_errno("asprintf");
10739 goto done;
10741 free(logmsg);
10742 logmsg = new_msg;
10744 err = got_object_id_str(&id_str, hle->commit_id);
10745 if (err)
10746 goto done;
10748 err = got_opentemp_named_fd(&logmsg_path, &fd,
10749 GOT_TMPDIR_STR "/got-logmsg", "");
10750 if (err)
10751 goto done;
10753 write(fd, logmsg, logmsg_len);
10754 close(fd);
10756 err = get_editor(&editor);
10757 if (err)
10758 goto done;
10760 err = edit_logmsg(&hle->logmsg, editor, logmsg_path, logmsg,
10761 logmsg_len, 0);
10762 if (err) {
10763 if (err->code != GOT_ERR_COMMIT_MSG_EMPTY)
10764 goto done;
10765 err = NULL;
10766 hle->logmsg = strdup(new_msg);
10767 if (hle->logmsg == NULL)
10768 err = got_error_from_errno("strdup");
10770 done:
10771 if (logmsg_path && unlink(logmsg_path) != 0 && err == NULL)
10772 err = got_error_from_errno2("unlink", logmsg_path);
10773 free(logmsg_path);
10774 free(logmsg);
10775 free(orig_logmsg);
10776 free(editor);
10777 if (commit)
10778 got_object_commit_close(commit);
10779 return err;
10782 static const struct got_error *
10783 histedit_parse_list(struct got_histedit_list *histedit_cmds,
10784 FILE *f, struct got_repository *repo)
10786 const struct got_error *err = NULL;
10787 char *line = NULL, *p, *end;
10788 size_t i, size;
10789 ssize_t len;
10790 int lineno = 0, lastcmd = -1;
10791 const struct got_histedit_cmd *cmd;
10792 struct got_object_id *commit_id = NULL;
10793 struct got_histedit_list_entry *hle = NULL;
10795 for (;;) {
10796 len = getline(&line, &size, f);
10797 if (len == -1) {
10798 const struct got_error *getline_err;
10799 if (feof(f))
10800 break;
10801 getline_err = got_error_from_errno("getline");
10802 err = got_ferror(f, getline_err->code);
10803 break;
10805 lineno++;
10806 p = line;
10807 while (isspace((unsigned char)p[0]))
10808 p++;
10809 if (p[0] == '#' || p[0] == '\0') {
10810 free(line);
10811 line = NULL;
10812 continue;
10814 cmd = NULL;
10815 for (i = 0; i < nitems(got_histedit_cmds); i++) {
10816 cmd = &got_histedit_cmds[i];
10817 if (strncmp(cmd->name, p, strlen(cmd->name)) == 0 &&
10818 isspace((unsigned char)p[strlen(cmd->name)])) {
10819 p += strlen(cmd->name);
10820 break;
10822 if (p[0] == cmd->code && isspace((unsigned char)p[1])) {
10823 p++;
10824 break;
10827 if (i == nitems(got_histedit_cmds)) {
10828 err = histedit_syntax_error(lineno);
10829 break;
10831 while (isspace((unsigned char)p[0]))
10832 p++;
10833 if (cmd->code == GOT_HISTEDIT_MESG) {
10834 if (lastcmd != GOT_HISTEDIT_PICK &&
10835 lastcmd != GOT_HISTEDIT_EDIT) {
10836 err = got_error(GOT_ERR_HISTEDIT_CMD);
10837 break;
10839 if (p[0] == '\0') {
10840 err = histedit_edit_logmsg(hle, repo);
10841 if (err)
10842 break;
10843 } else {
10844 hle->logmsg = strdup(p);
10845 if (hle->logmsg == NULL) {
10846 err = got_error_from_errno("strdup");
10847 break;
10850 free(line);
10851 line = NULL;
10852 lastcmd = cmd->code;
10853 continue;
10854 } else {
10855 end = p;
10856 while (end[0] && !isspace((unsigned char)end[0]))
10857 end++;
10858 *end = '\0';
10860 err = got_object_resolve_id_str(&commit_id, repo, p);
10861 if (err) {
10862 /* override error code */
10863 err = histedit_syntax_error(lineno);
10864 break;
10867 hle = malloc(sizeof(*hle));
10868 if (hle == NULL) {
10869 err = got_error_from_errno("malloc");
10870 break;
10872 hle->cmd = cmd;
10873 hle->commit_id = commit_id;
10874 hle->logmsg = NULL;
10875 commit_id = NULL;
10876 free(line);
10877 line = NULL;
10878 TAILQ_INSERT_TAIL(histedit_cmds, hle, entry);
10879 lastcmd = cmd->code;
10882 free(line);
10883 free(commit_id);
10884 return err;
10887 static const struct got_error *
10888 histedit_check_script(struct got_histedit_list *histedit_cmds,
10889 struct got_object_id_queue *commits, struct got_repository *repo)
10891 const struct got_error *err = NULL;
10892 struct got_object_qid *qid;
10893 struct got_histedit_list_entry *hle;
10894 static char msg[92];
10895 char *id_str;
10897 if (TAILQ_EMPTY(histedit_cmds))
10898 return got_error_msg(GOT_ERR_EMPTY_HISTEDIT,
10899 "histedit script contains no commands");
10900 if (STAILQ_EMPTY(commits))
10901 return got_error(GOT_ERR_EMPTY_HISTEDIT);
10903 TAILQ_FOREACH(hle, histedit_cmds, entry) {
10904 struct got_histedit_list_entry *hle2;
10905 TAILQ_FOREACH(hle2, histedit_cmds, entry) {
10906 if (hle == hle2)
10907 continue;
10908 if (got_object_id_cmp(hle->commit_id,
10909 hle2->commit_id) != 0)
10910 continue;
10911 err = got_object_id_str(&id_str, hle->commit_id);
10912 if (err)
10913 return err;
10914 snprintf(msg, sizeof(msg), "commit %s is listed "
10915 "more than once in histedit script", id_str);
10916 free(id_str);
10917 return got_error_msg(GOT_ERR_HISTEDIT_CMD, msg);
10921 STAILQ_FOREACH(qid, commits, entry) {
10922 TAILQ_FOREACH(hle, histedit_cmds, entry) {
10923 if (got_object_id_cmp(&qid->id, hle->commit_id) == 0)
10924 break;
10926 if (hle == NULL) {
10927 err = got_object_id_str(&id_str, &qid->id);
10928 if (err)
10929 return err;
10930 snprintf(msg, sizeof(msg),
10931 "commit %s missing from histedit script", id_str);
10932 free(id_str);
10933 return got_error_msg(GOT_ERR_HISTEDIT_CMD, msg);
10937 hle = TAILQ_LAST(histedit_cmds, got_histedit_list);
10938 if (hle && hle->cmd->code == GOT_HISTEDIT_FOLD)
10939 return got_error_msg(GOT_ERR_HISTEDIT_CMD,
10940 "last commit in histedit script cannot be folded");
10942 return NULL;
10945 static const struct got_error *
10946 histedit_run_editor(struct got_histedit_list *histedit_cmds,
10947 const char *path, struct got_object_id_queue *commits,
10948 struct got_repository *repo)
10950 const struct got_error *err = NULL;
10951 char *editor;
10952 FILE *f = NULL;
10954 err = get_editor(&editor);
10955 if (err)
10956 return err;
10958 if (spawn_editor(editor, path) == -1) {
10959 err = got_error_from_errno("failed spawning editor");
10960 goto done;
10963 f = fopen(path, "re");
10964 if (f == NULL) {
10965 err = got_error_from_errno("fopen");
10966 goto done;
10968 err = histedit_parse_list(histedit_cmds, f, repo);
10969 if (err)
10970 goto done;
10972 err = histedit_check_script(histedit_cmds, commits, repo);
10973 done:
10974 if (f && fclose(f) == EOF && err == NULL)
10975 err = got_error_from_errno("fclose");
10976 free(editor);
10977 return err;
10980 static const struct got_error *
10981 histedit_edit_list_retry(struct got_histedit_list *, const struct got_error *,
10982 struct got_object_id_queue *, const char *, const char *,
10983 struct got_repository *);
10985 static const struct got_error *
10986 histedit_edit_script(struct got_histedit_list *histedit_cmds,
10987 struct got_object_id_queue *commits, const char *branch_name,
10988 int edit_logmsg_only, int fold_only, int edit_only,
10989 struct got_repository *repo)
10991 const struct got_error *err;
10992 FILE *f = NULL;
10993 char *path = NULL;
10995 err = got_opentemp_named(&path, &f, "got-histedit", "");
10996 if (err)
10997 return err;
10999 err = write_cmd_list(f, branch_name, commits);
11000 if (err)
11001 goto done;
11003 err = histedit_write_commit_list(commits, f, edit_logmsg_only,
11004 fold_only, edit_only, repo);
11005 if (err)
11006 goto done;
11008 if (edit_logmsg_only || fold_only || edit_only) {
11009 rewind(f);
11010 err = histedit_parse_list(histedit_cmds, f, repo);
11011 } else {
11012 if (fclose(f) == EOF) {
11013 err = got_error_from_errno("fclose");
11014 goto done;
11016 f = NULL;
11017 err = histedit_run_editor(histedit_cmds, path, commits, repo);
11018 if (err) {
11019 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
11020 err->code != GOT_ERR_HISTEDIT_CMD)
11021 goto done;
11022 err = histedit_edit_list_retry(histedit_cmds, err,
11023 commits, path, branch_name, repo);
11026 done:
11027 if (f && fclose(f) == EOF && err == NULL)
11028 err = got_error_from_errno("fclose");
11029 if (path && unlink(path) != 0 && err == NULL)
11030 err = got_error_from_errno2("unlink", path);
11031 free(path);
11032 return err;
11035 static const struct got_error *
11036 histedit_save_list(struct got_histedit_list *histedit_cmds,
11037 struct got_worktree *worktree, struct got_repository *repo)
11039 const struct got_error *err = NULL;
11040 char *path = NULL;
11041 FILE *f = NULL;
11042 struct got_histedit_list_entry *hle;
11043 struct got_commit_object *commit = NULL;
11045 err = got_worktree_get_histedit_script_path(&path, worktree);
11046 if (err)
11047 return err;
11049 f = fopen(path, "we");
11050 if (f == NULL) {
11051 err = got_error_from_errno2("fopen", path);
11052 goto done;
11054 TAILQ_FOREACH(hle, histedit_cmds, entry) {
11055 err = histedit_write_commit(hle->commit_id, hle->cmd->name, f,
11056 repo);
11057 if (err)
11058 break;
11060 if (hle->logmsg) {
11061 int n = fprintf(f, "%c %s\n",
11062 GOT_HISTEDIT_MESG, hle->logmsg);
11063 if (n < 0) {
11064 err = got_ferror(f, GOT_ERR_IO);
11065 break;
11069 done:
11070 if (f && fclose(f) == EOF && err == NULL)
11071 err = got_error_from_errno("fclose");
11072 free(path);
11073 if (commit)
11074 got_object_commit_close(commit);
11075 return err;
11078 static void
11079 histedit_free_list(struct got_histedit_list *histedit_cmds)
11081 struct got_histedit_list_entry *hle;
11083 while ((hle = TAILQ_FIRST(histedit_cmds))) {
11084 TAILQ_REMOVE(histedit_cmds, hle, entry);
11085 free(hle);
11089 static const struct got_error *
11090 histedit_load_list(struct got_histedit_list *histedit_cmds,
11091 const char *path, struct got_repository *repo)
11093 const struct got_error *err = NULL;
11094 FILE *f = NULL;
11096 f = fopen(path, "re");
11097 if (f == NULL) {
11098 err = got_error_from_errno2("fopen", path);
11099 goto done;
11102 err = histedit_parse_list(histedit_cmds, f, repo);
11103 done:
11104 if (f && fclose(f) == EOF && err == NULL)
11105 err = got_error_from_errno("fclose");
11106 return err;
11109 static const struct got_error *
11110 histedit_edit_list_retry(struct got_histedit_list *histedit_cmds,
11111 const struct got_error *edit_err, struct got_object_id_queue *commits,
11112 const char *path, const char *branch_name, struct got_repository *repo)
11114 const struct got_error *err = NULL, *prev_err = edit_err;
11115 int resp = ' ';
11117 while (resp != 'c' && resp != 'r' && resp != 'a') {
11118 printf("%s: %s\n(c)ontinue editing, (r)estart editing, "
11119 "or (a)bort: ", getprogname(), prev_err->msg);
11120 resp = getchar();
11121 if (resp == '\n')
11122 resp = getchar();
11123 if (resp == 'c') {
11124 histedit_free_list(histedit_cmds);
11125 err = histedit_run_editor(histedit_cmds, path, commits,
11126 repo);
11127 if (err) {
11128 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
11129 err->code != GOT_ERR_HISTEDIT_CMD)
11130 break;
11131 prev_err = err;
11132 resp = ' ';
11133 continue;
11135 break;
11136 } else if (resp == 'r') {
11137 histedit_free_list(histedit_cmds);
11138 err = histedit_edit_script(histedit_cmds,
11139 commits, branch_name, 0, 0, 0, repo);
11140 if (err) {
11141 if (err->code != GOT_ERR_HISTEDIT_SYNTAX &&
11142 err->code != GOT_ERR_HISTEDIT_CMD)
11143 break;
11144 prev_err = err;
11145 resp = ' ';
11146 continue;
11148 break;
11149 } else if (resp == 'a') {
11150 err = got_error(GOT_ERR_HISTEDIT_CANCEL);
11151 break;
11152 } else
11153 printf("invalid response '%c'\n", resp);
11156 return err;
11159 static const struct got_error *
11160 histedit_complete(struct got_worktree *worktree,
11161 struct got_fileindex *fileindex, struct got_reference *tmp_branch,
11162 struct got_reference *branch, struct got_repository *repo)
11164 printf("Switching work tree to %s\n",
11165 got_ref_get_symref_target(branch));
11166 return got_worktree_histedit_complete(worktree, fileindex, tmp_branch,
11167 branch, repo);
11170 static const struct got_error *
11171 show_histedit_progress(struct got_commit_object *commit,
11172 struct got_histedit_list_entry *hle, struct got_object_id *new_id)
11174 const struct got_error *err;
11175 char *old_id_str = NULL, *new_id_str = NULL, *logmsg = NULL;
11177 err = got_object_id_str(&old_id_str, hle->commit_id);
11178 if (err)
11179 goto done;
11181 if (new_id) {
11182 err = got_object_id_str(&new_id_str, new_id);
11183 if (err)
11184 goto done;
11187 old_id_str[12] = '\0';
11188 if (new_id_str)
11189 new_id_str[12] = '\0';
11191 if (hle->logmsg) {
11192 logmsg = strdup(hle->logmsg);
11193 if (logmsg == NULL) {
11194 err = got_error_from_errno("strdup");
11195 goto done;
11197 trim_logmsg(logmsg, 42);
11198 } else {
11199 err = get_short_logmsg(&logmsg, 42, commit);
11200 if (err)
11201 goto done;
11204 switch (hle->cmd->code) {
11205 case GOT_HISTEDIT_PICK:
11206 case GOT_HISTEDIT_EDIT:
11207 printf("%s -> %s: %s\n", old_id_str,
11208 new_id_str ? new_id_str : "no-op change", logmsg);
11209 break;
11210 case GOT_HISTEDIT_DROP:
11211 case GOT_HISTEDIT_FOLD:
11212 printf("%s -> %s commit: %s\n", old_id_str, hle->cmd->name,
11213 logmsg);
11214 break;
11215 default:
11216 break;
11218 done:
11219 free(old_id_str);
11220 free(new_id_str);
11221 return err;
11224 static const struct got_error *
11225 histedit_commit(struct got_pathlist_head *merged_paths,
11226 struct got_worktree *worktree, struct got_fileindex *fileindex,
11227 struct got_reference *tmp_branch, struct got_histedit_list_entry *hle,
11228 const char *committer, struct got_repository *repo)
11230 const struct got_error *err;
11231 struct got_commit_object *commit;
11232 struct got_object_id *new_commit_id;
11234 if ((hle->cmd->code == GOT_HISTEDIT_EDIT || get_folded_commits(hle))
11235 && hle->logmsg == NULL) {
11236 err = histedit_edit_logmsg(hle, repo);
11237 if (err)
11238 return err;
11241 err = got_object_open_as_commit(&commit, repo, hle->commit_id);
11242 if (err)
11243 return err;
11245 err = got_worktree_histedit_commit(&new_commit_id, merged_paths,
11246 worktree, fileindex, tmp_branch, committer, commit, hle->commit_id,
11247 hle->logmsg, repo);
11248 if (err) {
11249 if (err->code != GOT_ERR_COMMIT_NO_CHANGES)
11250 goto done;
11251 err = show_histedit_progress(commit, hle, NULL);
11252 } else {
11253 err = show_histedit_progress(commit, hle, new_commit_id);
11254 free(new_commit_id);
11256 done:
11257 got_object_commit_close(commit);
11258 return err;
11261 static const struct got_error *
11262 histedit_skip_commit(struct got_histedit_list_entry *hle,
11263 struct got_worktree *worktree, struct got_repository *repo)
11265 const struct got_error *error;
11266 struct got_commit_object *commit;
11268 error = got_worktree_histedit_skip_commit(worktree, hle->commit_id,
11269 repo);
11270 if (error)
11271 return error;
11273 error = got_object_open_as_commit(&commit, repo, hle->commit_id);
11274 if (error)
11275 return error;
11277 error = show_histedit_progress(commit, hle, NULL);
11278 got_object_commit_close(commit);
11279 return error;
11282 static const struct got_error *
11283 check_local_changes(void *arg, unsigned char status,
11284 unsigned char staged_status, const char *path,
11285 struct got_object_id *blob_id, struct got_object_id *staged_blob_id,
11286 struct got_object_id *commit_id, int dirfd, const char *de_name)
11288 int *have_local_changes = arg;
11290 switch (status) {
11291 case GOT_STATUS_ADD:
11292 case GOT_STATUS_DELETE:
11293 case GOT_STATUS_MODIFY:
11294 case GOT_STATUS_CONFLICT:
11295 *have_local_changes = 1;
11296 return got_error(GOT_ERR_CANCELLED);
11297 default:
11298 break;
11301 switch (staged_status) {
11302 case GOT_STATUS_ADD:
11303 case GOT_STATUS_DELETE:
11304 case GOT_STATUS_MODIFY:
11305 *have_local_changes = 1;
11306 return got_error(GOT_ERR_CANCELLED);
11307 default:
11308 break;
11311 return NULL;
11314 static const struct got_error *
11315 cmd_histedit(int argc, char *argv[])
11317 const struct got_error *error = NULL;
11318 struct got_worktree *worktree = NULL;
11319 struct got_fileindex *fileindex = NULL;
11320 struct got_repository *repo = NULL;
11321 char *cwd = NULL, *committer = NULL, *gitconfig_path = NULL;
11322 struct got_reference *branch = NULL;
11323 struct got_reference *tmp_branch = NULL;
11324 struct got_object_id *resume_commit_id = NULL;
11325 struct got_object_id *base_commit_id = NULL;
11326 struct got_object_id *head_commit_id = NULL;
11327 struct got_commit_object *commit = NULL;
11328 int ch, rebase_in_progress = 0, merge_in_progress = 0;
11329 struct got_update_progress_arg upa;
11330 int edit_in_progress = 0, abort_edit = 0, continue_edit = 0;
11331 int edit_logmsg_only = 0, fold_only = 0, edit_only = 0;
11332 int list_backups = 0, delete_backups = 0;
11333 const char *edit_script_path = NULL;
11334 struct got_object_id_queue commits;
11335 struct got_pathlist_head merged_paths;
11336 const struct got_object_id_queue *parent_ids;
11337 struct got_object_qid *pid;
11338 struct got_histedit_list histedit_cmds;
11339 struct got_histedit_list_entry *hle;
11340 int *pack_fds = NULL;
11342 STAILQ_INIT(&commits);
11343 TAILQ_INIT(&histedit_cmds);
11344 TAILQ_INIT(&merged_paths);
11345 memset(&upa, 0, sizeof(upa));
11347 while ((ch = getopt(argc, argv, "aceF:flmX")) != -1) {
11348 switch (ch) {
11349 case 'a':
11350 abort_edit = 1;
11351 break;
11352 case 'c':
11353 continue_edit = 1;
11354 break;
11355 case 'e':
11356 edit_only = 1;
11357 break;
11358 case 'F':
11359 edit_script_path = optarg;
11360 break;
11361 case 'f':
11362 fold_only = 1;
11363 break;
11364 case 'l':
11365 list_backups = 1;
11366 break;
11367 case 'm':
11368 edit_logmsg_only = 1;
11369 break;
11370 case 'X':
11371 delete_backups = 1;
11372 break;
11373 default:
11374 usage_histedit();
11375 /* NOTREACHED */
11379 argc -= optind;
11380 argv += optind;
11382 #ifndef PROFILE
11383 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
11384 "unveil", NULL) == -1)
11385 err(1, "pledge");
11386 #endif
11387 if (abort_edit && continue_edit)
11388 option_conflict('a', 'c');
11389 if (edit_script_path && edit_logmsg_only)
11390 option_conflict('F', 'm');
11391 if (abort_edit && edit_logmsg_only)
11392 option_conflict('a', 'm');
11393 if (continue_edit && edit_logmsg_only)
11394 option_conflict('c', 'm');
11395 if (abort_edit && fold_only)
11396 option_conflict('a', 'f');
11397 if (continue_edit && fold_only)
11398 option_conflict('c', 'f');
11399 if (fold_only && edit_logmsg_only)
11400 option_conflict('f', 'm');
11401 if (edit_script_path && fold_only)
11402 option_conflict('F', 'f');
11403 if (abort_edit && edit_only)
11404 option_conflict('a', 'e');
11405 if (continue_edit && edit_only)
11406 option_conflict('c', 'e');
11407 if (edit_only && edit_logmsg_only)
11408 option_conflict('e', 'm');
11409 if (edit_script_path && edit_only)
11410 option_conflict('F', 'e');
11411 if (list_backups) {
11412 if (abort_edit)
11413 option_conflict('l', 'a');
11414 if (continue_edit)
11415 option_conflict('l', 'c');
11416 if (edit_script_path)
11417 option_conflict('l', 'F');
11418 if (edit_logmsg_only)
11419 option_conflict('l', 'm');
11420 if (fold_only)
11421 option_conflict('l', 'f');
11422 if (edit_only)
11423 option_conflict('l', 'e');
11424 if (delete_backups)
11425 option_conflict('l', 'X');
11426 if (argc != 0 && argc != 1)
11427 usage_histedit();
11428 } else if (delete_backups) {
11429 if (abort_edit)
11430 option_conflict('X', 'a');
11431 if (continue_edit)
11432 option_conflict('X', 'c');
11433 if (edit_script_path)
11434 option_conflict('X', 'F');
11435 if (edit_logmsg_only)
11436 option_conflict('X', 'm');
11437 if (fold_only)
11438 option_conflict('X', 'f');
11439 if (edit_only)
11440 option_conflict('X', 'e');
11441 if (list_backups)
11442 option_conflict('X', 'l');
11443 if (argc != 0 && argc != 1)
11444 usage_histedit();
11445 } else if (argc != 0)
11446 usage_histedit();
11449 * This command cannot apply unveil(2) in all cases because the
11450 * user may choose to run an editor to edit the histedit script
11451 * and to edit individual commit log messages.
11452 * unveil(2) traverses exec(2); if an editor is used we have to
11453 * apply unveil after edit script and log messages have been written.
11454 * XXX TODO: Make use of unveil(2) where possible.
11457 cwd = getcwd(NULL, 0);
11458 if (cwd == NULL) {
11459 error = got_error_from_errno("getcwd");
11460 goto done;
11463 error = got_repo_pack_fds_open(&pack_fds);
11464 if (error != NULL)
11465 goto done;
11467 error = got_worktree_open(&worktree, cwd);
11468 if (error) {
11469 if (list_backups || delete_backups) {
11470 if (error->code != GOT_ERR_NOT_WORKTREE)
11471 goto done;
11472 } else {
11473 if (error->code == GOT_ERR_NOT_WORKTREE)
11474 error = wrap_not_worktree_error(error,
11475 "histedit", cwd);
11476 goto done;
11480 if (list_backups || delete_backups) {
11481 error = got_repo_open(&repo,
11482 worktree ? got_worktree_get_repo_path(worktree) : cwd,
11483 NULL, pack_fds);
11484 if (error != NULL)
11485 goto done;
11486 error = apply_unveil(got_repo_get_path(repo), 0,
11487 worktree ? got_worktree_get_root_path(worktree) : NULL);
11488 if (error)
11489 goto done;
11490 error = process_backup_refs(
11491 GOT_WORKTREE_HISTEDIT_BACKUP_REF_PREFIX,
11492 argc == 1 ? argv[0] : NULL, delete_backups, repo);
11493 goto done; /* nothing else to do */
11496 error = get_gitconfig_path(&gitconfig_path);
11497 if (error)
11498 goto done;
11499 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
11500 gitconfig_path, pack_fds);
11501 if (error != NULL)
11502 goto done;
11504 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
11505 if (error)
11506 goto done;
11507 if (rebase_in_progress) {
11508 error = got_error(GOT_ERR_REBASING);
11509 goto done;
11512 error = got_worktree_merge_in_progress(&merge_in_progress, worktree,
11513 repo);
11514 if (error)
11515 goto done;
11516 if (merge_in_progress) {
11517 error = got_error(GOT_ERR_MERGE_BUSY);
11518 goto done;
11521 error = got_worktree_histedit_in_progress(&edit_in_progress, worktree);
11522 if (error)
11523 goto done;
11525 if (edit_in_progress && edit_logmsg_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 -m option can be used");
11530 goto done;
11532 if (edit_in_progress && fold_only) {
11533 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
11534 "histedit operation is in progress in this "
11535 "work tree and must be continued or aborted "
11536 "before the -f option can be used");
11537 goto done;
11539 if (edit_in_progress && edit_only) {
11540 error = got_error_msg(GOT_ERR_HISTEDIT_BUSY,
11541 "histedit operation is in progress in this "
11542 "work tree and must be continued or aborted "
11543 "before the -e option can be used");
11544 goto done;
11547 if (edit_in_progress && abort_edit) {
11548 error = got_worktree_histedit_continue(&resume_commit_id,
11549 &tmp_branch, &branch, &base_commit_id, &fileindex,
11550 worktree, repo);
11551 if (error)
11552 goto done;
11553 printf("Switching work tree to %s\n",
11554 got_ref_get_symref_target(branch));
11555 error = got_worktree_histedit_abort(worktree, fileindex, repo,
11556 branch, base_commit_id, abort_progress, &upa);
11557 if (error)
11558 goto done;
11559 printf("Histedit of %s aborted\n",
11560 got_ref_get_symref_target(branch));
11561 print_merge_progress_stats(&upa);
11562 goto done; /* nothing else to do */
11563 } else if (abort_edit) {
11564 error = got_error(GOT_ERR_NOT_HISTEDIT);
11565 goto done;
11568 error = get_author(&committer, repo, worktree);
11569 if (error)
11570 goto done;
11572 if (continue_edit) {
11573 char *path;
11575 if (!edit_in_progress) {
11576 error = got_error(GOT_ERR_NOT_HISTEDIT);
11577 goto done;
11580 error = got_worktree_get_histedit_script_path(&path, worktree);
11581 if (error)
11582 goto done;
11584 error = histedit_load_list(&histedit_cmds, path, repo);
11585 free(path);
11586 if (error)
11587 goto done;
11589 error = got_worktree_histedit_continue(&resume_commit_id,
11590 &tmp_branch, &branch, &base_commit_id, &fileindex,
11591 worktree, repo);
11592 if (error)
11593 goto done;
11595 error = got_ref_resolve(&head_commit_id, repo, branch);
11596 if (error)
11597 goto done;
11599 error = got_object_open_as_commit(&commit, repo,
11600 head_commit_id);
11601 if (error)
11602 goto done;
11603 parent_ids = got_object_commit_get_parent_ids(commit);
11604 pid = STAILQ_FIRST(parent_ids);
11605 if (pid == NULL) {
11606 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
11607 goto done;
11609 error = collect_commits(&commits, head_commit_id, &pid->id,
11610 base_commit_id, got_worktree_get_path_prefix(worktree),
11611 GOT_ERR_HISTEDIT_PATH, repo);
11612 got_object_commit_close(commit);
11613 commit = NULL;
11614 if (error)
11615 goto done;
11616 } else {
11617 if (edit_in_progress) {
11618 error = got_error(GOT_ERR_HISTEDIT_BUSY);
11619 goto done;
11622 error = got_ref_open(&branch, repo,
11623 got_worktree_get_head_ref_name(worktree), 0);
11624 if (error != NULL)
11625 goto done;
11627 if (strncmp(got_ref_get_name(branch), "refs/heads/", 11) != 0) {
11628 error = got_error_msg(GOT_ERR_COMMIT_BRANCH,
11629 "will not edit commit history of a branch outside "
11630 "the \"refs/heads/\" reference namespace");
11631 goto done;
11634 error = got_ref_resolve(&head_commit_id, repo, branch);
11635 got_ref_close(branch);
11636 branch = NULL;
11637 if (error)
11638 goto done;
11640 error = got_object_open_as_commit(&commit, repo,
11641 head_commit_id);
11642 if (error)
11643 goto done;
11644 parent_ids = got_object_commit_get_parent_ids(commit);
11645 pid = STAILQ_FIRST(parent_ids);
11646 if (pid == NULL) {
11647 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
11648 goto done;
11650 error = collect_commits(&commits, head_commit_id, &pid->id,
11651 got_worktree_get_base_commit_id(worktree),
11652 got_worktree_get_path_prefix(worktree),
11653 GOT_ERR_HISTEDIT_PATH, repo);
11654 got_object_commit_close(commit);
11655 commit = NULL;
11656 if (error)
11657 goto done;
11659 if (STAILQ_EMPTY(&commits)) {
11660 error = got_error(GOT_ERR_EMPTY_HISTEDIT);
11661 goto done;
11664 error = got_worktree_histedit_prepare(&tmp_branch, &branch,
11665 &base_commit_id, &fileindex, worktree, repo);
11666 if (error)
11667 goto done;
11669 if (edit_script_path) {
11670 error = histedit_load_list(&histedit_cmds,
11671 edit_script_path, repo);
11672 if (error) {
11673 got_worktree_histedit_abort(worktree, fileindex,
11674 repo, branch, base_commit_id,
11675 abort_progress, &upa);
11676 print_merge_progress_stats(&upa);
11677 goto done;
11679 } else {
11680 const char *branch_name;
11681 branch_name = got_ref_get_symref_target(branch);
11682 if (strncmp(branch_name, "refs/heads/", 11) == 0)
11683 branch_name += 11;
11684 error = histedit_edit_script(&histedit_cmds, &commits,
11685 branch_name, edit_logmsg_only, fold_only,
11686 edit_only, repo);
11687 if (error) {
11688 got_worktree_histedit_abort(worktree, fileindex,
11689 repo, branch, base_commit_id,
11690 abort_progress, &upa);
11691 print_merge_progress_stats(&upa);
11692 goto done;
11697 error = histedit_save_list(&histedit_cmds, worktree,
11698 repo);
11699 if (error) {
11700 got_worktree_histedit_abort(worktree, fileindex,
11701 repo, branch, base_commit_id,
11702 abort_progress, &upa);
11703 print_merge_progress_stats(&upa);
11704 goto done;
11709 error = histedit_check_script(&histedit_cmds, &commits, repo);
11710 if (error)
11711 goto done;
11713 TAILQ_FOREACH(hle, &histedit_cmds, entry) {
11714 if (resume_commit_id) {
11715 if (got_object_id_cmp(hle->commit_id,
11716 resume_commit_id) != 0)
11717 continue;
11719 resume_commit_id = NULL;
11720 if (hle->cmd->code == GOT_HISTEDIT_DROP ||
11721 hle->cmd->code == GOT_HISTEDIT_FOLD) {
11722 error = histedit_skip_commit(hle, worktree,
11723 repo);
11724 if (error)
11725 goto done;
11726 } else {
11727 struct got_pathlist_head paths;
11728 int have_changes = 0;
11730 TAILQ_INIT(&paths);
11731 error = got_pathlist_append(&paths, "", NULL);
11732 if (error)
11733 goto done;
11734 error = got_worktree_status(worktree, &paths,
11735 repo, 0, check_local_changes, &have_changes,
11736 check_cancelled, NULL);
11737 got_pathlist_free(&paths);
11738 if (error) {
11739 if (error->code != GOT_ERR_CANCELLED)
11740 goto done;
11741 if (sigint_received || sigpipe_received)
11742 goto done;
11744 if (have_changes) {
11745 error = histedit_commit(NULL, worktree,
11746 fileindex, tmp_branch, hle,
11747 committer, repo);
11748 if (error)
11749 goto done;
11750 } else {
11751 error = got_object_open_as_commit(
11752 &commit, repo, hle->commit_id);
11753 if (error)
11754 goto done;
11755 error = show_histedit_progress(commit,
11756 hle, NULL);
11757 got_object_commit_close(commit);
11758 commit = NULL;
11759 if (error)
11760 goto done;
11763 continue;
11766 if (hle->cmd->code == GOT_HISTEDIT_DROP) {
11767 error = histedit_skip_commit(hle, worktree, repo);
11768 if (error)
11769 goto done;
11770 continue;
11773 error = got_object_open_as_commit(&commit, repo,
11774 hle->commit_id);
11775 if (error)
11776 goto done;
11777 parent_ids = got_object_commit_get_parent_ids(commit);
11778 pid = STAILQ_FIRST(parent_ids);
11780 error = got_worktree_histedit_merge_files(&merged_paths,
11781 worktree, fileindex, &pid->id, hle->commit_id, repo,
11782 update_progress, &upa, check_cancelled, NULL);
11783 if (error)
11784 goto done;
11785 got_object_commit_close(commit);
11786 commit = NULL;
11788 print_merge_progress_stats(&upa);
11789 if (upa.conflicts > 0 || upa.missing > 0 ||
11790 upa.not_deleted > 0 || upa.unversioned > 0) {
11791 if (upa.conflicts > 0) {
11792 error = show_rebase_merge_conflict(
11793 hle->commit_id, repo);
11794 if (error)
11795 goto done;
11797 got_worktree_rebase_pathlist_free(&merged_paths);
11798 break;
11801 if (hle->cmd->code == GOT_HISTEDIT_EDIT) {
11802 char *id_str;
11803 error = got_object_id_str(&id_str, hle->commit_id);
11804 if (error)
11805 goto done;
11806 printf("Stopping histedit for amending commit %s\n",
11807 id_str);
11808 free(id_str);
11809 got_worktree_rebase_pathlist_free(&merged_paths);
11810 error = got_worktree_histedit_postpone(worktree,
11811 fileindex);
11812 goto done;
11815 if (hle->cmd->code == GOT_HISTEDIT_FOLD) {
11816 error = histedit_skip_commit(hle, worktree, repo);
11817 if (error)
11818 goto done;
11819 continue;
11822 error = histedit_commit(&merged_paths, worktree, fileindex,
11823 tmp_branch, hle, committer, repo);
11824 got_worktree_rebase_pathlist_free(&merged_paths);
11825 if (error)
11826 goto done;
11829 if (upa.conflicts > 0 || upa.missing > 0 ||
11830 upa.not_deleted > 0 || upa.unversioned > 0) {
11831 error = got_worktree_histedit_postpone(worktree, fileindex);
11832 if (error)
11833 goto done;
11834 if (upa.conflicts > 0 && upa.missing == 0 &&
11835 upa.not_deleted == 0 && upa.unversioned == 0) {
11836 error = got_error_msg(GOT_ERR_CONFLICTS,
11837 "conflicts must be resolved before histedit "
11838 "can continue");
11839 } else if (upa.conflicts > 0) {
11840 error = got_error_msg(GOT_ERR_CONFLICTS,
11841 "conflicts must be resolved before histedit "
11842 "can continue; changes destined for some "
11843 "files were not yet merged and should be "
11844 "merged manually if required before the "
11845 "histedit operation is continued");
11846 } else {
11847 error = got_error_msg(GOT_ERR_CONFLICTS,
11848 "changes destined for some files were not "
11849 "yet merged and should be merged manually "
11850 "if required before the histedit operation "
11851 "is continued");
11853 } else
11854 error = histedit_complete(worktree, fileindex, tmp_branch,
11855 branch, repo);
11856 done:
11857 free(cwd);
11858 free(committer);
11859 free(gitconfig_path);
11860 got_object_id_queue_free(&commits);
11861 histedit_free_list(&histedit_cmds);
11862 free(head_commit_id);
11863 free(base_commit_id);
11864 free(resume_commit_id);
11865 if (commit)
11866 got_object_commit_close(commit);
11867 if (branch)
11868 got_ref_close(branch);
11869 if (tmp_branch)
11870 got_ref_close(tmp_branch);
11871 if (worktree)
11872 got_worktree_close(worktree);
11873 if (repo) {
11874 const struct got_error *close_err = got_repo_close(repo);
11875 if (error == NULL)
11876 error = close_err;
11878 if (pack_fds) {
11879 const struct got_error *pack_err =
11880 got_repo_pack_fds_close(pack_fds);
11881 if (error == NULL)
11882 error = pack_err;
11884 return error;
11887 __dead static void
11888 usage_integrate(void)
11890 fprintf(stderr, "usage: %s integrate branch\n", getprogname());
11891 exit(1);
11894 static const struct got_error *
11895 cmd_integrate(int argc, char *argv[])
11897 const struct got_error *error = NULL;
11898 struct got_repository *repo = NULL;
11899 struct got_worktree *worktree = NULL;
11900 char *cwd = NULL, *refname = NULL, *base_refname = NULL;
11901 const char *branch_arg = NULL;
11902 struct got_reference *branch_ref = NULL, *base_branch_ref = NULL;
11903 struct got_fileindex *fileindex = NULL;
11904 struct got_object_id *commit_id = NULL, *base_commit_id = NULL;
11905 int ch;
11906 struct got_update_progress_arg upa;
11907 int *pack_fds = NULL;
11909 while ((ch = getopt(argc, argv, "")) != -1) {
11910 switch (ch) {
11911 default:
11912 usage_integrate();
11913 /* NOTREACHED */
11917 argc -= optind;
11918 argv += optind;
11920 if (argc != 1)
11921 usage_integrate();
11922 branch_arg = argv[0];
11923 #ifndef PROFILE
11924 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
11925 "unveil", NULL) == -1)
11926 err(1, "pledge");
11927 #endif
11928 cwd = getcwd(NULL, 0);
11929 if (cwd == NULL) {
11930 error = got_error_from_errno("getcwd");
11931 goto done;
11934 error = got_repo_pack_fds_open(&pack_fds);
11935 if (error != NULL)
11936 goto done;
11938 error = got_worktree_open(&worktree, cwd);
11939 if (error) {
11940 if (error->code == GOT_ERR_NOT_WORKTREE)
11941 error = wrap_not_worktree_error(error, "integrate",
11942 cwd);
11943 goto done;
11946 error = check_rebase_or_histedit_in_progress(worktree);
11947 if (error)
11948 goto done;
11950 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
11951 NULL, pack_fds);
11952 if (error != NULL)
11953 goto done;
11955 error = apply_unveil(got_repo_get_path(repo), 0,
11956 got_worktree_get_root_path(worktree));
11957 if (error)
11958 goto done;
11960 error = check_merge_in_progress(worktree, repo);
11961 if (error)
11962 goto done;
11964 if (asprintf(&refname, "refs/heads/%s", branch_arg) == -1) {
11965 error = got_error_from_errno("asprintf");
11966 goto done;
11969 error = got_worktree_integrate_prepare(&fileindex, &branch_ref,
11970 &base_branch_ref, worktree, refname, repo);
11971 if (error)
11972 goto done;
11974 refname = strdup(got_ref_get_name(branch_ref));
11975 if (refname == NULL) {
11976 error = got_error_from_errno("strdup");
11977 got_worktree_integrate_abort(worktree, fileindex, repo,
11978 branch_ref, base_branch_ref);
11979 goto done;
11981 base_refname = strdup(got_ref_get_name(base_branch_ref));
11982 if (base_refname == NULL) {
11983 error = got_error_from_errno("strdup");
11984 got_worktree_integrate_abort(worktree, fileindex, repo,
11985 branch_ref, base_branch_ref);
11986 goto done;
11988 if (strncmp(base_refname, "refs/heads/", 11) != 0) {
11989 error = got_error(GOT_ERR_INTEGRATE_BRANCH);
11990 got_worktree_integrate_abort(worktree, fileindex, repo,
11991 branch_ref, base_branch_ref);
11992 goto done;
11995 error = got_ref_resolve(&commit_id, repo, branch_ref);
11996 if (error)
11997 goto done;
11999 error = got_ref_resolve(&base_commit_id, repo, base_branch_ref);
12000 if (error)
12001 goto done;
12003 if (got_object_id_cmp(commit_id, base_commit_id) == 0) {
12004 error = got_error_msg(GOT_ERR_SAME_BRANCH,
12005 "specified branch has already been integrated");
12006 got_worktree_integrate_abort(worktree, fileindex, repo,
12007 branch_ref, base_branch_ref);
12008 goto done;
12011 error = check_linear_ancestry(commit_id, base_commit_id, 1, repo);
12012 if (error) {
12013 if (error->code == GOT_ERR_ANCESTRY)
12014 error = got_error(GOT_ERR_REBASE_REQUIRED);
12015 got_worktree_integrate_abort(worktree, fileindex, repo,
12016 branch_ref, base_branch_ref);
12017 goto done;
12020 memset(&upa, 0, sizeof(upa));
12021 error = got_worktree_integrate_continue(worktree, fileindex, repo,
12022 branch_ref, base_branch_ref, update_progress, &upa,
12023 check_cancelled, NULL);
12024 if (error)
12025 goto done;
12027 printf("Integrated %s into %s\n", refname, base_refname);
12028 print_update_progress_stats(&upa);
12029 done:
12030 if (repo) {
12031 const struct got_error *close_err = got_repo_close(repo);
12032 if (error == NULL)
12033 error = close_err;
12035 if (worktree)
12036 got_worktree_close(worktree);
12037 if (pack_fds) {
12038 const struct got_error *pack_err =
12039 got_repo_pack_fds_close(pack_fds);
12040 if (error == NULL)
12041 error = pack_err;
12043 free(cwd);
12044 free(base_commit_id);
12045 free(commit_id);
12046 free(refname);
12047 free(base_refname);
12048 return error;
12051 __dead static void
12052 usage_merge(void)
12054 fprintf(stderr, "usage: %s merge [-acn] [branch]\n", getprogname());
12055 exit(1);
12058 static const struct got_error *
12059 cmd_merge(int argc, char *argv[])
12061 const struct got_error *error = NULL;
12062 struct got_worktree *worktree = NULL;
12063 struct got_repository *repo = NULL;
12064 struct got_fileindex *fileindex = NULL;
12065 char *cwd = NULL, *id_str = NULL, *author = NULL;
12066 struct got_reference *branch = NULL, *wt_branch = NULL;
12067 struct got_object_id *branch_tip = NULL, *yca_id = NULL;
12068 struct got_object_id *wt_branch_tip = NULL;
12069 int ch, merge_in_progress = 0, abort_merge = 0, continue_merge = 0;
12070 int interrupt_merge = 0;
12071 struct got_update_progress_arg upa;
12072 struct got_object_id *merge_commit_id = NULL;
12073 char *branch_name = NULL;
12074 int *pack_fds = NULL;
12076 memset(&upa, 0, sizeof(upa));
12078 while ((ch = getopt(argc, argv, "acn")) != -1) {
12079 switch (ch) {
12080 case 'a':
12081 abort_merge = 1;
12082 break;
12083 case 'c':
12084 continue_merge = 1;
12085 break;
12086 case 'n':
12087 interrupt_merge = 1;
12088 break;
12089 default:
12090 usage_rebase();
12091 /* NOTREACHED */
12095 argc -= optind;
12096 argv += optind;
12098 #ifndef PROFILE
12099 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
12100 "unveil", NULL) == -1)
12101 err(1, "pledge");
12102 #endif
12104 if (abort_merge && continue_merge)
12105 option_conflict('a', 'c');
12106 if (abort_merge || continue_merge) {
12107 if (argc != 0)
12108 usage_merge();
12109 } else if (argc != 1)
12110 usage_merge();
12112 cwd = getcwd(NULL, 0);
12113 if (cwd == NULL) {
12114 error = got_error_from_errno("getcwd");
12115 goto done;
12118 error = got_repo_pack_fds_open(&pack_fds);
12119 if (error != NULL)
12120 goto done;
12122 error = got_worktree_open(&worktree, cwd);
12123 if (error) {
12124 if (error->code == GOT_ERR_NOT_WORKTREE)
12125 error = wrap_not_worktree_error(error,
12126 "merge", cwd);
12127 goto done;
12130 error = got_repo_open(&repo,
12131 worktree ? got_worktree_get_repo_path(worktree) : cwd, NULL,
12132 pack_fds);
12133 if (error != NULL)
12134 goto done;
12136 error = apply_unveil(got_repo_get_path(repo), 0,
12137 worktree ? got_worktree_get_root_path(worktree) : NULL);
12138 if (error)
12139 goto done;
12141 error = check_rebase_or_histedit_in_progress(worktree);
12142 if (error)
12143 goto done;
12145 error = got_worktree_merge_in_progress(&merge_in_progress, worktree,
12146 repo);
12147 if (error)
12148 goto done;
12150 if (abort_merge) {
12151 if (!merge_in_progress) {
12152 error = got_error(GOT_ERR_NOT_MERGING);
12153 goto done;
12155 error = got_worktree_merge_continue(&branch_name,
12156 &branch_tip, &fileindex, worktree, repo);
12157 if (error)
12158 goto done;
12159 error = got_worktree_merge_abort(worktree, fileindex, repo,
12160 abort_progress, &upa);
12161 if (error)
12162 goto done;
12163 printf("Merge of %s aborted\n", branch_name);
12164 goto done; /* nothing else to do */
12167 error = get_author(&author, repo, worktree);
12168 if (error)
12169 goto done;
12171 if (continue_merge) {
12172 if (!merge_in_progress) {
12173 error = got_error(GOT_ERR_NOT_MERGING);
12174 goto done;
12176 error = got_worktree_merge_continue(&branch_name,
12177 &branch_tip, &fileindex, worktree, repo);
12178 if (error)
12179 goto done;
12180 } else {
12181 error = got_ref_open(&branch, repo, argv[0], 0);
12182 if (error != NULL)
12183 goto done;
12184 branch_name = strdup(got_ref_get_name(branch));
12185 if (branch_name == NULL) {
12186 error = got_error_from_errno("strdup");
12187 goto done;
12189 error = got_ref_resolve(&branch_tip, repo, branch);
12190 if (error)
12191 goto done;
12194 error = got_ref_open(&wt_branch, repo,
12195 got_worktree_get_head_ref_name(worktree), 0);
12196 if (error)
12197 goto done;
12198 error = got_ref_resolve(&wt_branch_tip, repo, wt_branch);
12199 if (error)
12200 goto done;
12201 error = got_commit_graph_find_youngest_common_ancestor(&yca_id,
12202 wt_branch_tip, branch_tip, 0, repo,
12203 check_cancelled, NULL);
12204 if (error && error->code != GOT_ERR_ANCESTRY)
12205 goto done;
12207 if (!continue_merge) {
12208 error = check_path_prefix(wt_branch_tip, branch_tip,
12209 got_worktree_get_path_prefix(worktree),
12210 GOT_ERR_MERGE_PATH, repo);
12211 if (error)
12212 goto done;
12213 if (yca_id) {
12214 error = check_same_branch(wt_branch_tip, branch,
12215 yca_id, repo);
12216 if (error) {
12217 if (error->code != GOT_ERR_ANCESTRY)
12218 goto done;
12219 error = NULL;
12220 } else {
12221 static char msg[512];
12222 snprintf(msg, sizeof(msg),
12223 "cannot create a merge commit because "
12224 "%s is based on %s; %s can be integrated "
12225 "with 'got integrate' instead", branch_name,
12226 got_worktree_get_head_ref_name(worktree),
12227 branch_name);
12228 error = got_error_msg(GOT_ERR_SAME_BRANCH, msg);
12229 goto done;
12232 error = got_worktree_merge_prepare(&fileindex, worktree,
12233 branch, repo);
12234 if (error)
12235 goto done;
12237 error = got_worktree_merge_branch(worktree, fileindex,
12238 yca_id, branch_tip, repo, update_progress, &upa,
12239 check_cancelled, NULL);
12240 if (error)
12241 goto done;
12242 print_merge_progress_stats(&upa);
12243 if (!upa.did_something) {
12244 error = got_worktree_merge_abort(worktree, fileindex,
12245 repo, abort_progress, &upa);
12246 if (error)
12247 goto done;
12248 printf("Already up-to-date\n");
12249 goto done;
12253 if (interrupt_merge) {
12254 error = got_worktree_merge_postpone(worktree, fileindex);
12255 if (error)
12256 goto done;
12257 printf("Merge of %s interrupted on request\n", branch_name);
12258 } else if (upa.conflicts > 0 || upa.missing > 0 ||
12259 upa.not_deleted > 0 || upa.unversioned > 0) {
12260 error = got_worktree_merge_postpone(worktree, fileindex);
12261 if (error)
12262 goto done;
12263 if (upa.conflicts > 0 && upa.missing == 0 &&
12264 upa.not_deleted == 0 && upa.unversioned == 0) {
12265 error = got_error_msg(GOT_ERR_CONFLICTS,
12266 "conflicts must be resolved before merging "
12267 "can continue");
12268 } else if (upa.conflicts > 0) {
12269 error = got_error_msg(GOT_ERR_CONFLICTS,
12270 "conflicts must be resolved before merging "
12271 "can continue; changes destined for some "
12272 "files were not yet merged and "
12273 "should be merged manually if required before the "
12274 "merge operation is continued");
12275 } else {
12276 error = got_error_msg(GOT_ERR_CONFLICTS,
12277 "changes destined for some "
12278 "files were not yet merged and should be "
12279 "merged manually if required before the "
12280 "merge operation is continued");
12282 goto done;
12283 } else {
12284 error = got_worktree_merge_commit(&merge_commit_id, worktree,
12285 fileindex, author, NULL, 1, branch_tip, branch_name,
12286 repo, continue_merge ? print_status : NULL, NULL);
12287 if (error)
12288 goto done;
12289 error = got_worktree_merge_complete(worktree, fileindex, repo);
12290 if (error)
12291 goto done;
12292 error = got_object_id_str(&id_str, merge_commit_id);
12293 if (error)
12294 goto done;
12295 printf("Merged %s into %s: %s\n", branch_name,
12296 got_worktree_get_head_ref_name(worktree),
12297 id_str);
12300 done:
12301 free(id_str);
12302 free(merge_commit_id);
12303 free(author);
12304 free(branch_tip);
12305 free(branch_name);
12306 free(yca_id);
12307 if (branch)
12308 got_ref_close(branch);
12309 if (wt_branch)
12310 got_ref_close(wt_branch);
12311 if (worktree)
12312 got_worktree_close(worktree);
12313 if (repo) {
12314 const struct got_error *close_err = got_repo_close(repo);
12315 if (error == NULL)
12316 error = close_err;
12318 if (pack_fds) {
12319 const struct got_error *pack_err =
12320 got_repo_pack_fds_close(pack_fds);
12321 if (error == NULL)
12322 error = pack_err;
12324 return error;
12327 __dead static void
12328 usage_stage(void)
12330 fprintf(stderr, "usage: %s stage [-lpS] [-F response-script] "
12331 "[path ...]\n", getprogname());
12332 exit(1);
12335 static const struct got_error *
12336 print_stage(void *arg, unsigned char status, unsigned char staged_status,
12337 const char *path, struct got_object_id *blob_id,
12338 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
12339 int dirfd, const char *de_name)
12341 const struct got_error *err = NULL;
12342 char *id_str = NULL;
12344 if (staged_status != GOT_STATUS_ADD &&
12345 staged_status != GOT_STATUS_MODIFY &&
12346 staged_status != GOT_STATUS_DELETE)
12347 return NULL;
12349 if (staged_status == GOT_STATUS_ADD ||
12350 staged_status == GOT_STATUS_MODIFY)
12351 err = got_object_id_str(&id_str, staged_blob_id);
12352 else
12353 err = got_object_id_str(&id_str, blob_id);
12354 if (err)
12355 return err;
12357 printf("%s %c %s\n", id_str, staged_status, path);
12358 free(id_str);
12359 return NULL;
12362 static const struct got_error *
12363 cmd_stage(int argc, char *argv[])
12365 const struct got_error *error = NULL;
12366 struct got_repository *repo = NULL;
12367 struct got_worktree *worktree = NULL;
12368 char *cwd = NULL;
12369 struct got_pathlist_head paths;
12370 struct got_pathlist_entry *pe;
12371 int ch, list_stage = 0, pflag = 0, allow_bad_symlinks = 0;
12372 FILE *patch_script_file = NULL;
12373 const char *patch_script_path = NULL;
12374 struct choose_patch_arg cpa;
12375 int *pack_fds = NULL;
12377 TAILQ_INIT(&paths);
12379 while ((ch = getopt(argc, argv, "F:lpS")) != -1) {
12380 switch (ch) {
12381 case 'F':
12382 patch_script_path = optarg;
12383 break;
12384 case 'l':
12385 list_stage = 1;
12386 break;
12387 case 'p':
12388 pflag = 1;
12389 break;
12390 case 'S':
12391 allow_bad_symlinks = 1;
12392 break;
12393 default:
12394 usage_stage();
12395 /* NOTREACHED */
12399 argc -= optind;
12400 argv += optind;
12402 #ifndef PROFILE
12403 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
12404 "unveil", NULL) == -1)
12405 err(1, "pledge");
12406 #endif
12407 if (list_stage && (pflag || patch_script_path))
12408 errx(1, "-l option cannot be used with other options");
12409 if (patch_script_path && !pflag)
12410 errx(1, "-F option can only be used together with -p option");
12412 cwd = getcwd(NULL, 0);
12413 if (cwd == NULL) {
12414 error = got_error_from_errno("getcwd");
12415 goto done;
12418 error = got_repo_pack_fds_open(&pack_fds);
12419 if (error != NULL)
12420 goto done;
12422 error = got_worktree_open(&worktree, cwd);
12423 if (error) {
12424 if (error->code == GOT_ERR_NOT_WORKTREE)
12425 error = wrap_not_worktree_error(error, "stage", cwd);
12426 goto done;
12429 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
12430 NULL, pack_fds);
12431 if (error != NULL)
12432 goto done;
12434 if (patch_script_path) {
12435 patch_script_file = fopen(patch_script_path, "re");
12436 if (patch_script_file == NULL) {
12437 error = got_error_from_errno2("fopen",
12438 patch_script_path);
12439 goto done;
12442 error = apply_unveil(got_repo_get_path(repo), 0,
12443 got_worktree_get_root_path(worktree));
12444 if (error)
12445 goto done;
12447 error = check_merge_in_progress(worktree, repo);
12448 if (error)
12449 goto done;
12451 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
12452 if (error)
12453 goto done;
12455 if (list_stage)
12456 error = got_worktree_status(worktree, &paths, repo, 0,
12457 print_stage, NULL, check_cancelled, NULL);
12458 else {
12459 cpa.patch_script_file = patch_script_file;
12460 cpa.action = "stage";
12461 error = got_worktree_stage(worktree, &paths,
12462 pflag ? NULL : print_status, NULL,
12463 pflag ? choose_patch : NULL, &cpa,
12464 allow_bad_symlinks, repo);
12466 done:
12467 if (patch_script_file && fclose(patch_script_file) == EOF &&
12468 error == NULL)
12469 error = got_error_from_errno2("fclose", patch_script_path);
12470 if (repo) {
12471 const struct got_error *close_err = got_repo_close(repo);
12472 if (error == NULL)
12473 error = close_err;
12475 if (worktree)
12476 got_worktree_close(worktree);
12477 if (pack_fds) {
12478 const struct got_error *pack_err =
12479 got_repo_pack_fds_close(pack_fds);
12480 if (error == NULL)
12481 error = pack_err;
12483 TAILQ_FOREACH(pe, &paths, entry)
12484 free((char *)pe->path);
12485 got_pathlist_free(&paths);
12486 free(cwd);
12487 return error;
12490 __dead static void
12491 usage_unstage(void)
12493 fprintf(stderr, "usage: %s unstage [-p] [-F response-script] "
12494 "[path ...]\n", getprogname());
12495 exit(1);
12499 static const struct got_error *
12500 cmd_unstage(int argc, char *argv[])
12502 const struct got_error *error = NULL;
12503 struct got_repository *repo = NULL;
12504 struct got_worktree *worktree = NULL;
12505 char *cwd = NULL;
12506 struct got_pathlist_head paths;
12507 struct got_pathlist_entry *pe;
12508 int ch, pflag = 0;
12509 struct got_update_progress_arg upa;
12510 FILE *patch_script_file = NULL;
12511 const char *patch_script_path = NULL;
12512 struct choose_patch_arg cpa;
12513 int *pack_fds = NULL;
12515 TAILQ_INIT(&paths);
12517 while ((ch = getopt(argc, argv, "F:p")) != -1) {
12518 switch (ch) {
12519 case 'F':
12520 patch_script_path = optarg;
12521 break;
12522 case 'p':
12523 pflag = 1;
12524 break;
12525 default:
12526 usage_unstage();
12527 /* NOTREACHED */
12531 argc -= optind;
12532 argv += optind;
12534 #ifndef PROFILE
12535 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
12536 "unveil", NULL) == -1)
12537 err(1, "pledge");
12538 #endif
12539 if (patch_script_path && !pflag)
12540 errx(1, "-F option can only be used together with -p option");
12542 cwd = getcwd(NULL, 0);
12543 if (cwd == NULL) {
12544 error = got_error_from_errno("getcwd");
12545 goto done;
12548 error = got_repo_pack_fds_open(&pack_fds);
12549 if (error != NULL)
12550 goto done;
12552 error = got_worktree_open(&worktree, cwd);
12553 if (error) {
12554 if (error->code == GOT_ERR_NOT_WORKTREE)
12555 error = wrap_not_worktree_error(error, "unstage", cwd);
12556 goto done;
12559 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
12560 NULL, pack_fds);
12561 if (error != NULL)
12562 goto done;
12564 if (patch_script_path) {
12565 patch_script_file = fopen(patch_script_path, "re");
12566 if (patch_script_file == NULL) {
12567 error = got_error_from_errno2("fopen",
12568 patch_script_path);
12569 goto done;
12573 error = apply_unveil(got_repo_get_path(repo), 0,
12574 got_worktree_get_root_path(worktree));
12575 if (error)
12576 goto done;
12578 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
12579 if (error)
12580 goto done;
12582 cpa.patch_script_file = patch_script_file;
12583 cpa.action = "unstage";
12584 memset(&upa, 0, sizeof(upa));
12585 error = got_worktree_unstage(worktree, &paths, update_progress,
12586 &upa, pflag ? choose_patch : NULL, &cpa, repo);
12587 if (!error)
12588 print_merge_progress_stats(&upa);
12589 done:
12590 if (patch_script_file && fclose(patch_script_file) == EOF &&
12591 error == NULL)
12592 error = got_error_from_errno2("fclose", patch_script_path);
12593 if (repo) {
12594 const struct got_error *close_err = got_repo_close(repo);
12595 if (error == NULL)
12596 error = close_err;
12598 if (worktree)
12599 got_worktree_close(worktree);
12600 if (pack_fds) {
12601 const struct got_error *pack_err =
12602 got_repo_pack_fds_close(pack_fds);
12603 if (error == NULL)
12604 error = pack_err;
12606 TAILQ_FOREACH(pe, &paths, entry)
12607 free((char *)pe->path);
12608 got_pathlist_free(&paths);
12609 free(cwd);
12610 return error;
12613 __dead static void
12614 usage_cat(void)
12616 fprintf(stderr, "usage: %s cat [-P] [-c commit] [-r repository-path] "
12617 "arg ...\n", getprogname());
12618 exit(1);
12621 static const struct got_error *
12622 cat_blob(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
12624 const struct got_error *err;
12625 struct got_blob_object *blob;
12626 int fd = -1;
12628 fd = got_opentempfd();
12629 if (fd == -1)
12630 return got_error_from_errno("got_opentempfd");
12632 err = got_object_open_as_blob(&blob, repo, id, 8192, fd);
12633 if (err)
12634 goto done;
12636 err = got_object_blob_dump_to_file(NULL, NULL, NULL, outfile, blob);
12637 done:
12638 if (fd != -1 && close(fd) == -1 && err == NULL)
12639 err = got_error_from_errno("close");
12640 if (blob)
12641 got_object_blob_close(blob);
12642 return err;
12645 static const struct got_error *
12646 cat_tree(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
12648 const struct got_error *err;
12649 struct got_tree_object *tree;
12650 int nentries, i;
12652 err = got_object_open_as_tree(&tree, repo, id);
12653 if (err)
12654 return err;
12656 nentries = got_object_tree_get_nentries(tree);
12657 for (i = 0; i < nentries; i++) {
12658 struct got_tree_entry *te;
12659 char *id_str;
12660 if (sigint_received || sigpipe_received)
12661 break;
12662 te = got_object_tree_get_entry(tree, i);
12663 err = got_object_id_str(&id_str, got_tree_entry_get_id(te));
12664 if (err)
12665 break;
12666 fprintf(outfile, "%s %.7o %s\n", id_str,
12667 got_tree_entry_get_mode(te),
12668 got_tree_entry_get_name(te));
12669 free(id_str);
12672 got_object_tree_close(tree);
12673 return err;
12676 static const struct got_error *
12677 cat_commit(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
12679 const struct got_error *err;
12680 struct got_commit_object *commit;
12681 const struct got_object_id_queue *parent_ids;
12682 struct got_object_qid *pid;
12683 char *id_str = NULL;
12684 const char *logmsg = NULL;
12685 char gmtoff[6];
12687 err = got_object_open_as_commit(&commit, repo, id);
12688 if (err)
12689 return err;
12691 err = got_object_id_str(&id_str, got_object_commit_get_tree_id(commit));
12692 if (err)
12693 goto done;
12695 fprintf(outfile, "%s%s\n", GOT_COMMIT_LABEL_TREE, id_str);
12696 parent_ids = got_object_commit_get_parent_ids(commit);
12697 fprintf(outfile, "numparents %d\n",
12698 got_object_commit_get_nparents(commit));
12699 STAILQ_FOREACH(pid, parent_ids, entry) {
12700 char *pid_str;
12701 err = got_object_id_str(&pid_str, &pid->id);
12702 if (err)
12703 goto done;
12704 fprintf(outfile, "%s%s\n", GOT_COMMIT_LABEL_PARENT, pid_str);
12705 free(pid_str);
12707 got_date_format_gmtoff(gmtoff, sizeof(gmtoff),
12708 got_object_commit_get_author_gmtoff(commit));
12709 fprintf(outfile, "%s%s %lld %s\n", GOT_COMMIT_LABEL_AUTHOR,
12710 got_object_commit_get_author(commit),
12711 (long long)got_object_commit_get_author_time(commit),
12712 gmtoff);
12714 got_date_format_gmtoff(gmtoff, sizeof(gmtoff),
12715 got_object_commit_get_committer_gmtoff(commit));
12716 fprintf(outfile, "%s%s %lld %s\n", GOT_COMMIT_LABEL_COMMITTER,
12717 got_object_commit_get_committer(commit),
12718 (long long)got_object_commit_get_committer_time(commit),
12719 gmtoff);
12721 logmsg = got_object_commit_get_logmsg_raw(commit);
12722 fprintf(outfile, "messagelen %zd\n", strlen(logmsg));
12723 fprintf(outfile, "%s", logmsg);
12724 done:
12725 free(id_str);
12726 got_object_commit_close(commit);
12727 return err;
12730 static const struct got_error *
12731 cat_tag(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
12733 const struct got_error *err;
12734 struct got_tag_object *tag;
12735 char *id_str = NULL;
12736 const char *tagmsg = NULL;
12737 char gmtoff[6];
12739 err = got_object_open_as_tag(&tag, repo, id);
12740 if (err)
12741 return err;
12743 err = got_object_id_str(&id_str, got_object_tag_get_object_id(tag));
12744 if (err)
12745 goto done;
12747 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_OBJECT, id_str);
12749 switch (got_object_tag_get_object_type(tag)) {
12750 case GOT_OBJ_TYPE_BLOB:
12751 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
12752 GOT_OBJ_LABEL_BLOB);
12753 break;
12754 case GOT_OBJ_TYPE_TREE:
12755 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
12756 GOT_OBJ_LABEL_TREE);
12757 break;
12758 case GOT_OBJ_TYPE_COMMIT:
12759 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
12760 GOT_OBJ_LABEL_COMMIT);
12761 break;
12762 case GOT_OBJ_TYPE_TAG:
12763 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
12764 GOT_OBJ_LABEL_TAG);
12765 break;
12766 default:
12767 break;
12770 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TAG,
12771 got_object_tag_get_name(tag));
12773 got_date_format_gmtoff(gmtoff, sizeof(gmtoff),
12774 got_object_tag_get_tagger_gmtoff(tag));
12775 fprintf(outfile, "%s%s %lld %s\n", GOT_TAG_LABEL_TAGGER,
12776 got_object_tag_get_tagger(tag),
12777 (long long)got_object_tag_get_tagger_time(tag),
12778 gmtoff);
12780 tagmsg = got_object_tag_get_message(tag);
12781 fprintf(outfile, "messagelen %zd\n", strlen(tagmsg));
12782 fprintf(outfile, "%s", tagmsg);
12783 done:
12784 free(id_str);
12785 got_object_tag_close(tag);
12786 return err;
12789 static const struct got_error *
12790 cmd_cat(int argc, char *argv[])
12792 const struct got_error *error;
12793 struct got_repository *repo = NULL;
12794 struct got_worktree *worktree = NULL;
12795 char *cwd = NULL, *repo_path = NULL, *label = NULL;
12796 const char *commit_id_str = NULL;
12797 struct got_object_id *id = NULL, *commit_id = NULL;
12798 struct got_commit_object *commit = NULL;
12799 int ch, obj_type, i, force_path = 0;
12800 struct got_reflist_head refs;
12801 int *pack_fds = NULL;
12803 TAILQ_INIT(&refs);
12805 #ifndef PROFILE
12806 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
12807 NULL) == -1)
12808 err(1, "pledge");
12809 #endif
12811 while ((ch = getopt(argc, argv, "c:Pr:")) != -1) {
12812 switch (ch) {
12813 case 'c':
12814 commit_id_str = optarg;
12815 break;
12816 case 'P':
12817 force_path = 1;
12818 break;
12819 case 'r':
12820 repo_path = realpath(optarg, NULL);
12821 if (repo_path == NULL)
12822 return got_error_from_errno2("realpath",
12823 optarg);
12824 got_path_strip_trailing_slashes(repo_path);
12825 break;
12826 default:
12827 usage_cat();
12828 /* NOTREACHED */
12832 argc -= optind;
12833 argv += optind;
12835 cwd = getcwd(NULL, 0);
12836 if (cwd == NULL) {
12837 error = got_error_from_errno("getcwd");
12838 goto done;
12841 error = got_repo_pack_fds_open(&pack_fds);
12842 if (error != NULL)
12843 goto done;
12845 if (repo_path == NULL) {
12846 error = got_worktree_open(&worktree, cwd);
12847 if (error && error->code != GOT_ERR_NOT_WORKTREE)
12848 goto done;
12849 if (worktree) {
12850 repo_path = strdup(
12851 got_worktree_get_repo_path(worktree));
12852 if (repo_path == NULL) {
12853 error = got_error_from_errno("strdup");
12854 goto done;
12857 /* Release work tree lock. */
12858 got_worktree_close(worktree);
12859 worktree = NULL;
12863 if (repo_path == NULL) {
12864 repo_path = strdup(cwd);
12865 if (repo_path == NULL)
12866 return got_error_from_errno("strdup");
12869 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
12870 free(repo_path);
12871 if (error != NULL)
12872 goto done;
12874 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
12875 if (error)
12876 goto done;
12878 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
12879 if (error)
12880 goto done;
12882 if (commit_id_str == NULL)
12883 commit_id_str = GOT_REF_HEAD;
12884 error = got_repo_match_object_id(&commit_id, NULL,
12885 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
12886 if (error)
12887 goto done;
12889 error = got_object_open_as_commit(&commit, repo, commit_id);
12890 if (error)
12891 goto done;
12893 for (i = 0; i < argc; i++) {
12894 if (force_path) {
12895 error = got_object_id_by_path(&id, repo, commit,
12896 argv[i]);
12897 if (error)
12898 break;
12899 } else {
12900 error = got_repo_match_object_id(&id, &label, argv[i],
12901 GOT_OBJ_TYPE_ANY, NULL /* do not resolve tags */,
12902 repo);
12903 if (error) {
12904 if (error->code != GOT_ERR_BAD_OBJ_ID_STR &&
12905 error->code != GOT_ERR_NOT_REF)
12906 break;
12907 error = got_object_id_by_path(&id, repo,
12908 commit, argv[i]);
12909 if (error)
12910 break;
12914 error = got_object_get_type(&obj_type, repo, id);
12915 if (error)
12916 break;
12918 switch (obj_type) {
12919 case GOT_OBJ_TYPE_BLOB:
12920 error = cat_blob(id, repo, stdout);
12921 break;
12922 case GOT_OBJ_TYPE_TREE:
12923 error = cat_tree(id, repo, stdout);
12924 break;
12925 case GOT_OBJ_TYPE_COMMIT:
12926 error = cat_commit(id, repo, stdout);
12927 break;
12928 case GOT_OBJ_TYPE_TAG:
12929 error = cat_tag(id, repo, stdout);
12930 break;
12931 default:
12932 error = got_error(GOT_ERR_OBJ_TYPE);
12933 break;
12935 if (error)
12936 break;
12937 free(label);
12938 label = NULL;
12939 free(id);
12940 id = NULL;
12942 done:
12943 free(label);
12944 free(id);
12945 free(commit_id);
12946 if (commit)
12947 got_object_commit_close(commit);
12948 if (worktree)
12949 got_worktree_close(worktree);
12950 if (repo) {
12951 const struct got_error *close_err = got_repo_close(repo);
12952 if (error == NULL)
12953 error = close_err;
12955 if (pack_fds) {
12956 const struct got_error *pack_err =
12957 got_repo_pack_fds_close(pack_fds);
12958 if (error == NULL)
12959 error = pack_err;
12962 got_ref_list_free(&refs);
12963 return error;
12966 __dead static void
12967 usage_info(void)
12969 fprintf(stderr, "usage: %s info [path ...]\n",
12970 getprogname());
12971 exit(1);
12974 static const struct got_error *
12975 print_path_info(void *arg, const char *path, mode_t mode, time_t mtime,
12976 struct got_object_id *blob_id, struct got_object_id *staged_blob_id,
12977 struct got_object_id *commit_id)
12979 const struct got_error *err = NULL;
12980 char *id_str = NULL;
12981 char datebuf[128];
12982 struct tm mytm, *tm;
12983 struct got_pathlist_head *paths = arg;
12984 struct got_pathlist_entry *pe;
12987 * Clear error indication from any of the path arguments which
12988 * would cause this file index entry to be displayed.
12990 TAILQ_FOREACH(pe, paths, entry) {
12991 if (got_path_cmp(path, pe->path, strlen(path),
12992 pe->path_len) == 0 ||
12993 got_path_is_child(path, pe->path, pe->path_len))
12994 pe->data = NULL; /* no error */
12997 printf(GOT_COMMIT_SEP_STR);
12998 if (S_ISLNK(mode))
12999 printf("symlink: %s\n", path);
13000 else if (S_ISREG(mode)) {
13001 printf("file: %s\n", path);
13002 printf("mode: %o\n", mode & (S_IRWXU | S_IRWXG | S_IRWXO));
13003 } else if (S_ISDIR(mode))
13004 printf("directory: %s\n", path);
13005 else
13006 printf("something: %s\n", path);
13008 tm = localtime_r(&mtime, &mytm);
13009 if (tm == NULL)
13010 return NULL;
13011 if (strftime(datebuf, sizeof(datebuf), "%c %Z", tm) == 0)
13012 return got_error(GOT_ERR_NO_SPACE);
13013 printf("timestamp: %s\n", datebuf);
13015 if (blob_id) {
13016 err = got_object_id_str(&id_str, blob_id);
13017 if (err)
13018 return err;
13019 printf("based on blob: %s\n", id_str);
13020 free(id_str);
13023 if (staged_blob_id) {
13024 err = got_object_id_str(&id_str, staged_blob_id);
13025 if (err)
13026 return err;
13027 printf("based on staged blob: %s\n", id_str);
13028 free(id_str);
13031 if (commit_id) {
13032 err = got_object_id_str(&id_str, commit_id);
13033 if (err)
13034 return err;
13035 printf("based on commit: %s\n", id_str);
13036 free(id_str);
13039 return NULL;
13042 static const struct got_error *
13043 cmd_info(int argc, char *argv[])
13045 const struct got_error *error = NULL;
13046 struct got_worktree *worktree = NULL;
13047 char *cwd = NULL, *id_str = NULL;
13048 struct got_pathlist_head paths;
13049 struct got_pathlist_entry *pe;
13050 char *uuidstr = NULL;
13051 int ch, show_files = 0;
13053 TAILQ_INIT(&paths);
13055 while ((ch = getopt(argc, argv, "")) != -1) {
13056 switch (ch) {
13057 default:
13058 usage_info();
13059 /* NOTREACHED */
13063 argc -= optind;
13064 argv += optind;
13066 #ifndef PROFILE
13067 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
13068 NULL) == -1)
13069 err(1, "pledge");
13070 #endif
13071 cwd = getcwd(NULL, 0);
13072 if (cwd == NULL) {
13073 error = got_error_from_errno("getcwd");
13074 goto done;
13077 error = got_worktree_open(&worktree, cwd);
13078 if (error) {
13079 if (error->code == GOT_ERR_NOT_WORKTREE)
13080 error = wrap_not_worktree_error(error, "info", cwd);
13081 goto done;
13084 #ifndef PROFILE
13085 /* Remove "wpath cpath proc exec sendfd" promises. */
13086 if (pledge("stdio rpath flock unveil", NULL) == -1)
13087 err(1, "pledge");
13088 #endif
13089 error = apply_unveil(NULL, 0, got_worktree_get_root_path(worktree));
13090 if (error)
13091 goto done;
13093 if (argc >= 1) {
13094 error = get_worktree_paths_from_argv(&paths, argc, argv,
13095 worktree);
13096 if (error)
13097 goto done;
13098 show_files = 1;
13101 error = got_object_id_str(&id_str,
13102 got_worktree_get_base_commit_id(worktree));
13103 if (error)
13104 goto done;
13106 error = got_worktree_get_uuid(&uuidstr, worktree);
13107 if (error)
13108 goto done;
13110 printf("work tree: %s\n", got_worktree_get_root_path(worktree));
13111 printf("work tree base commit: %s\n", id_str);
13112 printf("work tree path prefix: %s\n",
13113 got_worktree_get_path_prefix(worktree));
13114 printf("work tree branch reference: %s\n",
13115 got_worktree_get_head_ref_name(worktree));
13116 printf("work tree UUID: %s\n", uuidstr);
13117 printf("repository: %s\n", got_worktree_get_repo_path(worktree));
13119 if (show_files) {
13120 struct got_pathlist_entry *pe;
13121 TAILQ_FOREACH(pe, &paths, entry) {
13122 if (pe->path_len == 0)
13123 continue;
13125 * Assume this path will fail. This will be corrected
13126 * in print_path_info() in case the path does suceeed.
13128 pe->data = (void *)got_error(GOT_ERR_BAD_PATH);
13130 error = got_worktree_path_info(worktree, &paths,
13131 print_path_info, &paths, check_cancelled, NULL);
13132 if (error)
13133 goto done;
13134 TAILQ_FOREACH(pe, &paths, entry) {
13135 if (pe->data != NULL) {
13136 const struct got_error *perr;
13138 perr = pe->data;
13139 error = got_error_fmt(perr->code, "%s",
13140 pe->path);
13141 break;
13145 done:
13146 if (worktree)
13147 got_worktree_close(worktree);
13148 TAILQ_FOREACH(pe, &paths, entry)
13149 free((char *)pe->path);
13150 got_pathlist_free(&paths);
13151 free(cwd);
13152 free(id_str);
13153 free(uuidstr);
13154 return error;