remove full content comparison loop from got status
[got-portable.git] / cvg / cvg.c
blobe7efb2f42607b5d2d795aaea607648b2b504eba0
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 * Copyright (C) 2023 Josh Rickmar <jrick@zettaport.com>
7 * Permission to use, copy, modify, and distribute this software for any
8 * purpose with or without fee is hereby granted, provided that the above
9 * copyright notice and this permission notice appear in all copies.
11 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
12 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
13 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
14 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
15 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
16 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
17 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
20 #include "got_compat.h"
22 #include <sys/queue.h>
23 #include <sys/time.h>
24 #include <sys/types.h>
25 #include <sys/stat.h>
26 #include <sys/wait.h>
28 #include <err.h>
29 #include <errno.h>
30 #include <fcntl.h>
31 #include <limits.h>
32 #include <locale.h>
33 #include <ctype.h>
34 #include <signal.h>
35 #include <stdio.h>
36 #include <stdlib.h>
37 #include <string.h>
38 #include <unistd.h>
39 #include <libgen.h>
40 #include <time.h>
41 #include <paths.h>
42 #include <regex.h>
43 #include <getopt.h>
45 #include "got_version.h"
46 #include "got_error.h"
47 #include "got_object.h"
48 #include "got_reference.h"
49 #include "got_repository.h"
50 #include "got_path.h"
51 #include "got_cancel.h"
52 #include "got_worktree.h"
53 #include "got_worktree_cvg.h"
54 #include "got_diff.h"
55 #include "got_commit_graph.h"
56 #include "got_fetch.h"
57 #include "got_send.h"
58 #include "got_blame.h"
59 #include "got_privsep.h"
60 #include "got_opentemp.h"
61 #include "got_gotconfig.h"
62 #include "got_dial.h"
63 #include "got_patch.h"
64 #include "got_sigs.h"
65 #include "got_date.h"
67 #ifndef nitems
68 #define nitems(_a) (sizeof((_a)) / sizeof((_a)[0]))
69 #endif
71 #ifndef GOT_DEFAULT_EDITOR
72 #define GOT_DEFAULT_EDITOR "/usr/bin/vi"
73 #endif
75 static volatile sig_atomic_t sigint_received;
76 static volatile sig_atomic_t sigpipe_received;
78 static void
79 catch_sigint(int signo)
81 sigint_received = 1;
84 static void
85 catch_sigpipe(int signo)
87 sigpipe_received = 1;
91 struct got_cmd {
92 const char *cmd_name;
93 const struct got_error *(*cmd_main)(int, char *[]);
94 void (*cmd_usage)(void);
95 const char *cmd_alias;
98 __dead static void usage(int, int);
99 __dead static void usage_import(void);
100 __dead static void usage_clone(void);
101 __dead static void usage_checkout(void);
102 __dead static void usage_update(void);
103 __dead static void usage_log(void);
104 __dead static void usage_diff(void);
105 __dead static void usage_blame(void);
106 __dead static void usage_tree(void);
107 __dead static void usage_status(void);
108 __dead static void usage_tag(void);
109 __dead static void usage_add(void);
110 __dead static void usage_remove(void);
111 __dead static void usage_patch(void);
112 __dead static void usage_revert(void);
113 __dead static void usage_commit(void);
114 __dead static void usage_cherrypick(void);
115 __dead static void usage_backout(void);
116 __dead static void usage_cat(void);
117 __dead static void usage_info(void);
119 static const struct got_error* cmd_import(int, char *[]);
120 static const struct got_error* cmd_clone(int, char *[]);
121 static const struct got_error* cmd_checkout(int, char *[]);
122 static const struct got_error* cmd_update(int, char *[]);
123 static const struct got_error* cmd_log(int, char *[]);
124 static const struct got_error* cmd_diff(int, char *[]);
125 static const struct got_error* cmd_blame(int, char *[]);
126 static const struct got_error* cmd_tree(int, char *[]);
127 static const struct got_error* cmd_status(int, char *[]);
128 static const struct got_error* cmd_tag(int, char *[]);
129 static const struct got_error* cmd_add(int, char *[]);
130 static const struct got_error* cmd_remove(int, char *[]);
131 static const struct got_error* cmd_patch(int, char *[]);
132 static const struct got_error* cmd_revert(int, char *[]);
133 static const struct got_error* cmd_commit(int, char *[]);
134 static const struct got_error* cmd_cherrypick(int, char *[]);
135 static const struct got_error* cmd_backout(int, char *[]);
136 static const struct got_error* cmd_cat(int, char *[]);
137 static const struct got_error* cmd_info(int, char *[]);
139 static const struct got_cmd got_commands[] = {
140 { "import", cmd_import, usage_import, "im" },
141 { "clone", cmd_clone, usage_clone, "cl" },
142 { "checkout", cmd_checkout, usage_checkout, "co" },
143 { "update", cmd_update, usage_update, "up" },
144 { "log", cmd_log, usage_log, "" },
145 { "diff", cmd_diff, usage_diff, "di" },
146 { "blame", cmd_blame, usage_blame, "bl" },
147 { "tree", cmd_tree, usage_tree, "tr" },
148 { "status", cmd_status, usage_status, "st" },
149 { "tag", cmd_tag, usage_tag, "" },
150 { "add", cmd_add, usage_add, "" },
151 { "remove", cmd_remove, usage_remove, "rm" },
152 { "patch", cmd_patch, usage_patch, "pa" },
153 { "revert", cmd_revert, usage_revert, "rv" },
154 { "commit", cmd_commit, usage_commit, "ci" },
155 { "cherrypick", cmd_cherrypick, usage_cherrypick, "cy" },
156 { "backout", cmd_backout, usage_backout, "bo" },
157 { "cat", cmd_cat, usage_cat, "" },
158 { "info", cmd_info, usage_info, "" },
161 static void
162 list_commands(FILE *fp)
164 size_t i;
166 fprintf(fp, "commands:");
167 for (i = 0; i < nitems(got_commands); i++) {
168 const struct got_cmd *cmd = &got_commands[i];
169 fprintf(fp, " %s", cmd->cmd_name);
171 fputc('\n', fp);
174 __dead static void
175 option_conflict(char a, char b)
177 errx(1, "-%c and -%c options are mutually exclusive", a, b);
181 main(int argc, char *argv[])
183 const struct got_cmd *cmd;
184 size_t i;
185 int ch;
186 int hflag = 0, Vflag = 0;
187 static const struct option longopts[] = {
188 { "version", no_argument, NULL, 'V' },
189 { NULL, 0, NULL, 0 }
192 setlocale(LC_CTYPE, "");
194 while ((ch = getopt_long(argc, argv, "+hV", longopts, NULL)) != -1) {
195 switch (ch) {
196 case 'h':
197 hflag = 1;
198 break;
199 case 'V':
200 Vflag = 1;
201 break;
202 default:
203 usage(hflag, 1);
204 /* NOTREACHED */
208 argc -= optind;
209 argv += optind;
210 optind = 1;
211 optreset = 1;
213 if (Vflag) {
214 got_version_print_str();
215 return 0;
218 if (argc <= 0)
219 usage(hflag, hflag ? 0 : 1);
221 signal(SIGINT, catch_sigint);
222 signal(SIGPIPE, catch_sigpipe);
224 for (i = 0; i < nitems(got_commands); i++) {
225 const struct got_error *error;
227 cmd = &got_commands[i];
229 if (strcmp(cmd->cmd_name, argv[0]) != 0 &&
230 strcmp(cmd->cmd_alias, argv[0]) != 0)
231 continue;
233 if (hflag)
234 cmd->cmd_usage();
236 error = cmd->cmd_main(argc, argv);
237 if (error && error->code != GOT_ERR_CANCELLED &&
238 error->code != GOT_ERR_PRIVSEP_EXIT &&
239 !(sigpipe_received &&
240 error->code == GOT_ERR_ERRNO && errno == EPIPE) &&
241 !(sigint_received &&
242 error->code == GOT_ERR_ERRNO && errno == EINTR)) {
243 fflush(stdout);
244 fprintf(stderr, "%s: %s\n", getprogname(), error->msg);
245 return 1;
248 return 0;
251 fprintf(stderr, "%s: unknown command '%s'\n", getprogname(), argv[0]);
252 list_commands(stderr);
253 return 1;
256 __dead static void
257 usage(int hflag, int status)
259 FILE *fp = (status == 0) ? stdout : stderr;
261 fprintf(fp, "usage: %s [-hV] command [arg ...]\n",
262 getprogname());
263 if (hflag)
264 list_commands(fp);
265 exit(status);
268 static const struct got_error *
269 get_editor(char **abspath)
271 const struct got_error *err = NULL;
272 const char *editor;
274 *abspath = NULL;
276 editor = getenv("VISUAL");
277 if (editor == NULL)
278 editor = getenv("EDITOR");
280 if (editor) {
281 err = got_path_find_prog(abspath, editor);
282 if (err)
283 return err;
286 if (*abspath == NULL) {
287 *abspath = strdup(GOT_DEFAULT_EDITOR);
288 if (*abspath == NULL)
289 return got_error_from_errno("strdup");
292 return NULL;
295 static const struct got_error *
296 apply_unveil(const char *repo_path, int repo_read_only,
297 const char *worktree_path)
299 const struct got_error *err;
301 #ifdef PROFILE
302 if (unveil("gmon.out", "rwc") != 0)
303 return got_error_from_errno2("unveil", "gmon.out");
304 #endif
305 if (repo_path && unveil(repo_path, repo_read_only ? "r" : "rwc") != 0)
306 return got_error_from_errno2("unveil", repo_path);
308 if (worktree_path && unveil(worktree_path, "rwc") != 0)
309 return got_error_from_errno2("unveil", worktree_path);
311 if (unveil(GOT_TMPDIR_STR, "rwc") != 0)
312 return got_error_from_errno2("unveil", GOT_TMPDIR_STR);
314 err = got_privsep_unveil_exec_helpers();
315 if (err != NULL)
316 return err;
318 if (unveil(NULL, NULL) != 0)
319 return got_error_from_errno("unveil");
321 return NULL;
324 __dead static void
325 usage_import(void)
327 fprintf(stderr, "usage: %s import [-b branch] [-I pattern] [-m message] "
328 "[-r repository-path] directory\n", getprogname());
329 exit(1);
332 static int
333 spawn_editor(const char *editor, const char *file)
335 pid_t pid;
336 sig_t sighup, sigint, sigquit;
337 int st = -1;
339 sighup = signal(SIGHUP, SIG_IGN);
340 sigint = signal(SIGINT, SIG_IGN);
341 sigquit = signal(SIGQUIT, SIG_IGN);
343 switch (pid = fork()) {
344 case -1:
345 goto doneediting;
346 case 0:
347 execl(editor, editor, file, (char *)NULL);
348 _exit(127);
351 while (waitpid(pid, &st, 0) == -1)
352 if (errno != EINTR)
353 break;
355 doneediting:
356 (void)signal(SIGHUP, sighup);
357 (void)signal(SIGINT, sigint);
358 (void)signal(SIGQUIT, sigquit);
360 if (!WIFEXITED(st)) {
361 errno = EINTR;
362 return -1;
365 return WEXITSTATUS(st);
368 static const struct got_error *
369 read_logmsg(char **logmsg, size_t *len, FILE *fp, size_t filesize)
371 const struct got_error *err = NULL;
372 char *line = NULL;
373 size_t linesize = 0;
375 *logmsg = NULL;
376 *len = 0;
378 if (fseeko(fp, 0L, SEEK_SET) == -1)
379 return got_error_from_errno("fseeko");
381 *logmsg = malloc(filesize + 1);
382 if (*logmsg == NULL)
383 return got_error_from_errno("malloc");
384 (*logmsg)[0] = '\0';
386 while (getline(&line, &linesize, fp) != -1) {
387 if (line[0] == '#' || (*len == 0 && line[0] == '\n'))
388 continue; /* remove comments and leading empty lines */
389 *len = strlcat(*logmsg, line, filesize + 1);
390 if (*len >= filesize + 1) {
391 err = got_error(GOT_ERR_NO_SPACE);
392 goto done;
395 if (ferror(fp)) {
396 err = got_ferror(fp, GOT_ERR_IO);
397 goto done;
400 while (*len > 0 && (*logmsg)[*len - 1] == '\n') {
401 (*logmsg)[*len - 1] = '\0';
402 (*len)--;
404 done:
405 free(line);
406 if (err) {
407 free(*logmsg);
408 *logmsg = NULL;
409 *len = 0;
411 return err;
414 static const struct got_error *
415 edit_logmsg(char **logmsg, const char *editor, const char *logmsg_path,
416 const char *initial_content, size_t initial_content_len,
417 int require_modification)
419 const struct got_error *err = NULL;
420 struct stat st, st2;
421 FILE *fp = NULL;
422 size_t logmsg_len;
424 *logmsg = NULL;
426 if (stat(logmsg_path, &st) == -1)
427 return got_error_from_errno2("stat", logmsg_path);
429 if (spawn_editor(editor, logmsg_path) == -1)
430 return got_error_from_errno("failed spawning editor");
432 if (require_modification) {
433 struct timespec timeout;
435 timeout.tv_sec = 0;
436 timeout.tv_nsec = 1;
437 nanosleep(&timeout, NULL);
440 if (stat(logmsg_path, &st2) == -1)
441 return got_error_from_errno2("stat", logmsg_path);
443 if (require_modification && st.st_size == st2.st_size &&
444 timespeccmp(&st.st_mtim, &st2.st_mtim, ==))
445 return got_error_msg(GOT_ERR_COMMIT_MSG_EMPTY,
446 "no changes made to commit message, aborting");
448 fp = fopen(logmsg_path, "re");
449 if (fp == NULL) {
450 err = got_error_from_errno("fopen");
451 goto done;
454 /* strip comments and leading/trailing newlines */
455 err = read_logmsg(logmsg, &logmsg_len, fp, st2.st_size);
456 if (err)
457 goto done;
458 if (logmsg_len == 0) {
459 err = got_error_msg(GOT_ERR_COMMIT_MSG_EMPTY,
460 "commit message cannot be empty, aborting");
461 goto done;
463 done:
464 if (fp && fclose(fp) == EOF && err == NULL)
465 err = got_error_from_errno("fclose");
466 if (err) {
467 free(*logmsg);
468 *logmsg = NULL;
470 return err;
473 static const struct got_error *
474 collect_import_msg(char **logmsg, char **logmsg_path, const char *editor,
475 const char *path_dir, const char *branch_name)
477 char *initial_content = NULL;
478 const struct got_error *err = NULL;
479 int initial_content_len;
480 int fd = -1;
482 initial_content_len = asprintf(&initial_content,
483 "\n# %s to be imported to branch %s\n", path_dir,
484 branch_name);
485 if (initial_content_len == -1)
486 return got_error_from_errno("asprintf");
488 err = got_opentemp_named_fd(logmsg_path, &fd,
489 GOT_TMPDIR_STR "/got-importmsg", "");
490 if (err)
491 goto done;
493 if (write(fd, initial_content, initial_content_len) == -1) {
494 err = got_error_from_errno2("write", *logmsg_path);
495 goto done;
497 if (close(fd) == -1) {
498 err = got_error_from_errno2("close", *logmsg_path);
499 goto done;
501 fd = -1;
503 err = edit_logmsg(logmsg, editor, *logmsg_path, initial_content,
504 initial_content_len, 1);
505 done:
506 if (fd != -1 && close(fd) == -1 && err == NULL)
507 err = got_error_from_errno2("close", *logmsg_path);
508 free(initial_content);
509 if (err) {
510 free(*logmsg_path);
511 *logmsg_path = NULL;
513 return err;
516 static const struct got_error *
517 import_progress(void *arg, const char *path)
519 printf("A %s\n", path);
520 return NULL;
523 static const struct got_error *
524 valid_author(const char *author)
526 const char *email = author;
529 * Git' expects the author (or committer) to be in the form
530 * "name <email>", which are mostly free form (see the
531 * "committer" description in git-fast-import(1)). We're only
532 * doing this to avoid git's object parser breaking on commits
533 * we create.
536 while (*author && *author != '\n' && *author != '<' && *author != '>')
537 author++;
538 if (author != email && *author == '<' && *(author - 1) != ' ')
539 return got_error_fmt(GOT_ERR_COMMIT_BAD_AUTHOR, "%s: space "
540 "between author name and email required", email);
541 if (*author++ != '<')
542 return got_error_fmt(GOT_ERR_COMMIT_NO_EMAIL, "%s", email);
543 while (*author && *author != '\n' && *author != '<' && *author != '>')
544 author++;
545 if (strcmp(author, ">") != 0)
546 return got_error_fmt(GOT_ERR_COMMIT_NO_EMAIL, "%s", email);
547 return NULL;
550 static const struct got_error *
551 get_author(char **author, struct got_repository *repo,
552 struct got_worktree *worktree)
554 const struct got_error *err = NULL;
555 const char *got_author = NULL, *name, *email;
556 const struct got_gotconfig *worktree_conf = NULL, *repo_conf = NULL;
558 *author = NULL;
560 if (worktree)
561 worktree_conf = got_worktree_get_gotconfig(worktree);
562 repo_conf = got_repo_get_gotconfig(repo);
565 * Priority of potential author information sources, from most
566 * significant to least significant:
567 * 1) work tree's .got/got.conf file
568 * 2) repository's got.conf file
569 * 3) repository's git config file
570 * 4) environment variables
571 * 5) global git config files (in user's home directory or /etc)
574 if (worktree_conf)
575 got_author = got_gotconfig_get_author(worktree_conf);
576 if (got_author == NULL)
577 got_author = got_gotconfig_get_author(repo_conf);
578 if (got_author == NULL) {
579 name = got_repo_get_gitconfig_author_name(repo);
580 email = got_repo_get_gitconfig_author_email(repo);
581 if (name && email) {
582 if (asprintf(author, "%s <%s>", name, email) == -1)
583 return got_error_from_errno("asprintf");
584 return NULL;
587 got_author = getenv("GOT_AUTHOR");
588 if (got_author == NULL) {
589 name = got_repo_get_global_gitconfig_author_name(repo);
590 email = got_repo_get_global_gitconfig_author_email(
591 repo);
592 if (name && email) {
593 if (asprintf(author, "%s <%s>", name, email)
594 == -1)
595 return got_error_from_errno("asprintf");
596 return NULL;
598 /* TODO: Look up user in password database? */
599 return got_error(GOT_ERR_COMMIT_NO_AUTHOR);
603 *author = strdup(got_author);
604 if (*author == NULL)
605 return got_error_from_errno("strdup");
607 err = valid_author(*author);
608 if (err) {
609 free(*author);
610 *author = NULL;
612 return err;
615 static const struct got_error *
616 get_allowed_signers(char **allowed_signers, struct got_repository *repo,
617 struct got_worktree *worktree)
619 const char *got_allowed_signers = NULL;
620 const struct got_gotconfig *worktree_conf = NULL, *repo_conf = NULL;
622 *allowed_signers = NULL;
624 if (worktree)
625 worktree_conf = got_worktree_get_gotconfig(worktree);
626 repo_conf = got_repo_get_gotconfig(repo);
629 * Priority of potential author information sources, from most
630 * significant to least significant:
631 * 1) work tree's .got/got.conf file
632 * 2) repository's got.conf file
635 if (worktree_conf)
636 got_allowed_signers = got_gotconfig_get_allowed_signers_file(
637 worktree_conf);
638 if (got_allowed_signers == NULL)
639 got_allowed_signers = got_gotconfig_get_allowed_signers_file(
640 repo_conf);
642 if (got_allowed_signers) {
643 *allowed_signers = strdup(got_allowed_signers);
644 if (*allowed_signers == NULL)
645 return got_error_from_errno("strdup");
647 return NULL;
650 static const struct got_error *
651 get_revoked_signers(char **revoked_signers, struct got_repository *repo,
652 struct got_worktree *worktree)
654 const char *got_revoked_signers = NULL;
655 const struct got_gotconfig *worktree_conf = NULL, *repo_conf = NULL;
657 *revoked_signers = NULL;
659 if (worktree)
660 worktree_conf = got_worktree_get_gotconfig(worktree);
661 repo_conf = got_repo_get_gotconfig(repo);
664 * Priority of potential author information sources, from most
665 * significant to least significant:
666 * 1) work tree's .got/got.conf file
667 * 2) repository's got.conf file
670 if (worktree_conf)
671 got_revoked_signers = got_gotconfig_get_revoked_signers_file(
672 worktree_conf);
673 if (got_revoked_signers == NULL)
674 got_revoked_signers = got_gotconfig_get_revoked_signers_file(
675 repo_conf);
677 if (got_revoked_signers) {
678 *revoked_signers = strdup(got_revoked_signers);
679 if (*revoked_signers == NULL)
680 return got_error_from_errno("strdup");
682 return NULL;
685 static const char *
686 get_signer_id(struct got_repository *repo, struct got_worktree *worktree)
688 const char *got_signer_id = NULL;
689 const struct got_gotconfig *worktree_conf = NULL, *repo_conf = NULL;
691 if (worktree)
692 worktree_conf = got_worktree_get_gotconfig(worktree);
693 repo_conf = got_repo_get_gotconfig(repo);
696 * Priority of potential author information sources, from most
697 * significant to least significant:
698 * 1) work tree's .got/got.conf file
699 * 2) repository's got.conf file
702 if (worktree_conf)
703 got_signer_id = got_gotconfig_get_signer_id(worktree_conf);
704 if (got_signer_id == NULL)
705 got_signer_id = got_gotconfig_get_signer_id(repo_conf);
707 return got_signer_id;
710 static const struct got_error *
711 get_gitconfig_path(char **gitconfig_path)
713 const char *homedir = getenv("HOME");
715 *gitconfig_path = NULL;
716 if (homedir) {
717 if (asprintf(gitconfig_path, "%s/.gitconfig", homedir) == -1)
718 return got_error_from_errno("asprintf");
721 return NULL;
724 static const struct got_error *
725 cmd_import(int argc, char *argv[])
727 const struct got_error *error = NULL;
728 char *path_dir = NULL, *repo_path = NULL, *logmsg = NULL;
729 char *gitconfig_path = NULL, *editor = NULL, *author = NULL;
730 const char *branch_name = NULL;
731 char *id_str = NULL, *logmsg_path = NULL;
732 char refname[PATH_MAX] = "refs/heads/";
733 struct got_repository *repo = NULL;
734 struct got_reference *branch_ref = NULL, *head_ref = NULL;
735 struct got_object_id *new_commit_id = NULL;
736 int ch, n = 0;
737 struct got_pathlist_head ignores;
738 struct got_pathlist_entry *pe;
739 int preserve_logmsg = 0;
740 int *pack_fds = NULL;
742 RB_INIT(&ignores);
744 #ifndef PROFILE
745 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
746 "unveil",
747 NULL) == -1)
748 err(1, "pledge");
749 #endif
751 while ((ch = getopt(argc, argv, "b:I:m:r:")) != -1) {
752 switch (ch) {
753 case 'b':
754 branch_name = optarg;
755 break;
756 case 'I':
757 if (optarg[0] == '\0')
758 break;
759 error = got_pathlist_insert(&pe, &ignores, optarg,
760 NULL);
761 if (error)
762 goto done;
763 break;
764 case 'm':
765 logmsg = strdup(optarg);
766 if (logmsg == NULL) {
767 error = got_error_from_errno("strdup");
768 goto done;
770 break;
771 case 'r':
772 repo_path = realpath(optarg, NULL);
773 if (repo_path == NULL) {
774 error = got_error_from_errno2("realpath",
775 optarg);
776 goto done;
778 break;
779 default:
780 usage_import();
781 /* NOTREACHED */
785 argc -= optind;
786 argv += optind;
788 if (argc != 1)
789 usage_import();
791 if (repo_path == NULL) {
792 repo_path = getcwd(NULL, 0);
793 if (repo_path == NULL) {
794 error = got_error_from_errno("getcwd");
795 goto done;
798 got_path_strip_trailing_slashes(repo_path);
799 error = get_gitconfig_path(&gitconfig_path);
800 if (error)
801 goto done;
802 error = got_repo_pack_fds_open(&pack_fds);
803 if (error != NULL)
804 goto done;
805 error = got_repo_open(&repo, repo_path, gitconfig_path, pack_fds);
806 if (error)
807 goto done;
809 error = get_author(&author, repo, NULL);
810 if (error)
811 goto done;
814 * Don't let the user create a branch name with a leading '-'.
815 * While technically a valid reference name, this case is usually
816 * an unintended typo.
818 if (branch_name && branch_name[0] == '-') {
819 error = got_error_path(branch_name, GOT_ERR_REF_NAME_MINUS);
820 goto done;
823 error = got_ref_open(&head_ref, repo, GOT_REF_HEAD, 0);
824 if (error && error->code != GOT_ERR_NOT_REF)
825 goto done;
827 if (branch_name)
828 n = strlcat(refname, branch_name, sizeof(refname));
829 else if (head_ref && got_ref_is_symbolic(head_ref))
830 n = strlcpy(refname, got_ref_get_symref_target(head_ref),
831 sizeof(refname));
832 else
833 n = strlcat(refname, "main", sizeof(refname));
834 if (n >= sizeof(refname)) {
835 error = got_error(GOT_ERR_NO_SPACE);
836 goto done;
839 error = got_ref_open(&branch_ref, repo, refname, 0);
840 if (error) {
841 if (error->code != GOT_ERR_NOT_REF)
842 goto done;
843 } else {
844 error = got_error_msg(GOT_ERR_BRANCH_EXISTS,
845 "import target branch already exists");
846 goto done;
849 path_dir = realpath(argv[0], NULL);
850 if (path_dir == NULL) {
851 error = got_error_from_errno2("realpath", argv[0]);
852 goto done;
854 got_path_strip_trailing_slashes(path_dir);
857 * unveil(2) traverses exec(2); if an editor is used we have
858 * to apply unveil after the log message has been written.
860 if (logmsg == NULL || *logmsg == '\0') {
861 error = get_editor(&editor);
862 if (error)
863 goto done;
864 free(logmsg);
865 error = collect_import_msg(&logmsg, &logmsg_path, editor,
866 path_dir, refname);
867 if (error) {
868 if (error->code != GOT_ERR_COMMIT_MSG_EMPTY &&
869 logmsg_path != NULL)
870 preserve_logmsg = 1;
871 goto done;
875 if (unveil(path_dir, "r") != 0) {
876 error = got_error_from_errno2("unveil", path_dir);
877 if (logmsg_path)
878 preserve_logmsg = 1;
879 goto done;
882 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
883 if (error) {
884 if (logmsg_path)
885 preserve_logmsg = 1;
886 goto done;
889 error = got_repo_import(&new_commit_id, path_dir, logmsg,
890 author, &ignores, repo, import_progress, NULL);
891 if (error) {
892 if (logmsg_path)
893 preserve_logmsg = 1;
894 goto done;
897 error = got_ref_alloc(&branch_ref, refname, new_commit_id);
898 if (error) {
899 if (logmsg_path)
900 preserve_logmsg = 1;
901 goto done;
904 error = got_ref_write(branch_ref, repo);
905 if (error) {
906 if (logmsg_path)
907 preserve_logmsg = 1;
908 goto done;
911 error = got_object_id_str(&id_str, new_commit_id);
912 if (error) {
913 if (logmsg_path)
914 preserve_logmsg = 1;
915 goto done;
918 error = got_ref_open(&head_ref, repo, GOT_REF_HEAD, 0);
919 if (error) {
920 if (error->code != GOT_ERR_NOT_REF) {
921 if (logmsg_path)
922 preserve_logmsg = 1;
923 goto done;
926 error = got_ref_alloc_symref(&head_ref, GOT_REF_HEAD,
927 branch_ref);
928 if (error) {
929 if (logmsg_path)
930 preserve_logmsg = 1;
931 goto done;
934 error = got_ref_write(head_ref, repo);
935 if (error) {
936 if (logmsg_path)
937 preserve_logmsg = 1;
938 goto done;
942 printf("Created branch %s with commit %s\n",
943 got_ref_get_name(branch_ref), id_str);
944 done:
945 if (pack_fds) {
946 const struct got_error *pack_err =
947 got_repo_pack_fds_close(pack_fds);
948 if (error == NULL)
949 error = pack_err;
951 if (repo) {
952 const struct got_error *close_err = got_repo_close(repo);
953 if (error == NULL)
954 error = close_err;
956 if (preserve_logmsg) {
957 fprintf(stderr, "%s: log message preserved in %s\n",
958 getprogname(), logmsg_path);
959 } else if (logmsg_path && unlink(logmsg_path) == -1 && error == NULL)
960 error = got_error_from_errno2("unlink", logmsg_path);
961 got_pathlist_free(&ignores, GOT_PATHLIST_FREE_NONE);
962 free(logmsg);
963 free(logmsg_path);
964 free(path_dir);
965 free(repo_path);
966 free(editor);
967 free(new_commit_id);
968 free(id_str);
969 free(author);
970 free(gitconfig_path);
971 if (branch_ref)
972 got_ref_close(branch_ref);
973 if (head_ref)
974 got_ref_close(head_ref);
975 return error;
978 __dead static void
979 usage_clone(void)
981 fprintf(stderr, "usage: %s clone [-almqv] [-b branch] "
982 "[-i identity-file] [-J jumphost] [-R reference] "
983 "repository-URL [directory]\n", getprogname());
984 exit(1);
987 struct got_fetch_progress_arg {
988 char last_scaled_size[FMT_SCALED_STRSIZE];
989 int last_p_indexed;
990 int last_p_resolved;
991 int verbosity;
993 struct got_repository *repo;
995 int create_configs;
996 int configs_created;
997 struct {
998 struct got_pathlist_head *symrefs;
999 struct got_pathlist_head *wanted_branches;
1000 struct got_pathlist_head *wanted_refs;
1001 const char *proto;
1002 const char *host;
1003 const char *port;
1004 const char *remote_repo_path;
1005 const char *git_url;
1006 int fetch_all_branches;
1007 int mirror_references;
1008 } config_info;
1011 /* XXX forward declaration */
1012 static const struct got_error *
1013 create_config_files(const char *proto, const char *host, const char *port,
1014 const char *remote_repo_path, const char *git_url, int fetch_all_branches,
1015 int mirror_references, struct got_pathlist_head *symrefs,
1016 struct got_pathlist_head *wanted_branches,
1017 struct got_pathlist_head *wanted_refs, struct got_repository *repo);
1019 static const struct got_error *
1020 fetch_progress(void *arg, const char *message, off_t packfile_size,
1021 int nobj_total, int nobj_indexed, int nobj_loose, int nobj_resolved)
1023 const struct got_error *err = NULL;
1024 struct got_fetch_progress_arg *a = arg;
1025 char scaled_size[FMT_SCALED_STRSIZE];
1026 int p_indexed, p_resolved;
1027 int print_size = 0, print_indexed = 0, print_resolved = 0;
1030 * In order to allow a failed clone to be resumed with 'got fetch'
1031 * we try to create configuration files as soon as possible.
1032 * Once the server has sent information about its default branch
1033 * we have all required information.
1035 if (a->create_configs && !a->configs_created &&
1036 !RB_EMPTY(a->config_info.symrefs)) {
1037 err = create_config_files(a->config_info.proto,
1038 a->config_info.host, a->config_info.port,
1039 a->config_info.remote_repo_path,
1040 a->config_info.git_url,
1041 a->config_info.fetch_all_branches,
1042 a->config_info.mirror_references,
1043 a->config_info.symrefs,
1044 a->config_info.wanted_branches,
1045 a->config_info.wanted_refs, a->repo);
1046 if (err)
1047 return err;
1048 a->configs_created = 1;
1051 if (a->verbosity < 0)
1052 return NULL;
1054 if (message && message[0] != '\0') {
1055 printf("\rserver: %s", message);
1056 fflush(stdout);
1057 return NULL;
1060 if (packfile_size > 0 || nobj_indexed > 0) {
1061 if (fmt_scaled(packfile_size, scaled_size) == 0 &&
1062 (a->last_scaled_size[0] == '\0' ||
1063 strcmp(scaled_size, a->last_scaled_size)) != 0) {
1064 print_size = 1;
1065 if (strlcpy(a->last_scaled_size, scaled_size,
1066 FMT_SCALED_STRSIZE) >= FMT_SCALED_STRSIZE)
1067 return got_error(GOT_ERR_NO_SPACE);
1069 if (nobj_indexed > 0) {
1070 p_indexed = (nobj_indexed * 100) / nobj_total;
1071 if (p_indexed != a->last_p_indexed) {
1072 a->last_p_indexed = p_indexed;
1073 print_indexed = 1;
1074 print_size = 1;
1077 if (nobj_resolved > 0) {
1078 p_resolved = (nobj_resolved * 100) /
1079 (nobj_total - nobj_loose);
1080 if (p_resolved != a->last_p_resolved) {
1081 a->last_p_resolved = p_resolved;
1082 print_resolved = 1;
1083 print_indexed = 1;
1084 print_size = 1;
1089 if (print_size || print_indexed || print_resolved)
1090 printf("\r");
1091 if (print_size)
1092 printf("%*s fetched", FMT_SCALED_STRSIZE - 2, scaled_size);
1093 if (print_indexed)
1094 printf("; indexing %d%%", p_indexed);
1095 if (print_resolved)
1096 printf("; resolving deltas %d%%", p_resolved);
1097 if (print_size || print_indexed || print_resolved)
1098 fflush(stdout);
1100 return NULL;
1103 static const struct got_error *
1104 create_symref(const char *refname, struct got_reference *target_ref,
1105 int verbosity, struct got_repository *repo)
1107 const struct got_error *err;
1108 struct got_reference *head_symref;
1110 err = got_ref_alloc_symref(&head_symref, refname, target_ref);
1111 if (err)
1112 return err;
1114 err = got_ref_write(head_symref, repo);
1115 if (err == NULL && verbosity > 0) {
1116 printf("Created reference %s: %s\n", GOT_REF_HEAD,
1117 got_ref_get_name(target_ref));
1119 got_ref_close(head_symref);
1120 return err;
1123 static const struct got_error *
1124 list_remote_refs(struct got_pathlist_head *symrefs,
1125 struct got_pathlist_head *refs)
1127 const struct got_error *err;
1128 struct got_pathlist_entry *pe;
1130 RB_FOREACH(pe, got_pathlist_head, symrefs) {
1131 const char *refname = pe->path;
1132 const char *targetref = pe->data;
1134 printf("%s: %s\n", refname, targetref);
1137 RB_FOREACH(pe, got_pathlist_head, refs) {
1138 const char *refname = pe->path;
1139 struct got_object_id *id = pe->data;
1140 char *id_str;
1142 err = got_object_id_str(&id_str, id);
1143 if (err)
1144 return err;
1145 printf("%s: %s\n", refname, id_str);
1146 free(id_str);
1149 return NULL;
1152 static const struct got_error *
1153 create_ref(const char *refname, struct got_object_id *id,
1154 int verbosity, struct got_repository *repo)
1156 const struct got_error *err = NULL;
1157 struct got_reference *ref;
1158 char *id_str;
1160 err = got_object_id_str(&id_str, id);
1161 if (err)
1162 return err;
1164 err = got_ref_alloc(&ref, refname, id);
1165 if (err)
1166 goto done;
1168 err = got_ref_write(ref, repo);
1169 got_ref_close(ref);
1171 if (err == NULL && verbosity >= 0)
1172 printf("Created reference %s: %s\n", refname, id_str);
1173 done:
1174 free(id_str);
1175 return err;
1178 static int
1179 match_wanted_ref(const char *refname, const char *wanted_ref)
1181 if (strncmp(refname, "refs/", 5) != 0)
1182 return 0;
1183 refname += 5;
1186 * Prevent fetching of references that won't make any
1187 * sense outside of the remote repository's context.
1189 if (strncmp(refname, "got/", 4) == 0)
1190 return 0;
1191 if (strncmp(refname, "remotes/", 8) == 0)
1192 return 0;
1194 if (strncmp(wanted_ref, "refs/", 5) == 0)
1195 wanted_ref += 5;
1197 /* Allow prefix match. */
1198 if (got_path_is_child(refname, wanted_ref, strlen(wanted_ref)))
1199 return 1;
1201 /* Allow exact match. */
1202 return (strcmp(refname, wanted_ref) == 0);
1205 static int
1206 is_wanted_ref(struct got_pathlist_head *wanted_refs, const char *refname)
1208 struct got_pathlist_entry *pe;
1210 RB_FOREACH(pe, got_pathlist_head, wanted_refs) {
1211 if (match_wanted_ref(refname, pe->path))
1212 return 1;
1215 return 0;
1218 static const struct got_error *
1219 create_wanted_ref(const char *refname, struct got_object_id *id,
1220 const char *remote_repo_name, int verbosity, struct got_repository *repo)
1222 const struct got_error *err;
1223 char *remote_refname;
1225 if (strncmp("refs/", refname, 5) == 0)
1226 refname += 5;
1228 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
1229 remote_repo_name, refname) == -1)
1230 return got_error_from_errno("asprintf");
1232 err = create_ref(remote_refname, id, verbosity, repo);
1233 free(remote_refname);
1234 return err;
1237 static const struct got_error *
1238 create_gotconfig(const char *proto, const char *host, const char *port,
1239 const char *remote_repo_path, const char *default_branch,
1240 int fetch_all_branches, struct got_pathlist_head *wanted_branches,
1241 struct got_pathlist_head *wanted_refs, int mirror_references,
1242 struct got_repository *repo)
1244 const struct got_error *err = NULL;
1245 char *gotconfig_path = NULL;
1246 char *gotconfig = NULL;
1247 FILE *gotconfig_file = NULL;
1248 const char *branchname = NULL;
1249 char *branches = NULL, *refs = NULL;
1250 ssize_t n;
1252 if (!fetch_all_branches && !RB_EMPTY(wanted_branches)) {
1253 struct got_pathlist_entry *pe;
1254 RB_FOREACH(pe, got_pathlist_head, wanted_branches) {
1255 char *s;
1256 branchname = pe->path;
1257 if (strncmp(branchname, "refs/heads/", 11) == 0)
1258 branchname += 11;
1259 if (asprintf(&s, "%s\"%s\" ",
1260 branches ? branches : "", branchname) == -1) {
1261 err = got_error_from_errno("asprintf");
1262 goto done;
1264 free(branches);
1265 branches = s;
1267 } else if (!fetch_all_branches && default_branch) {
1268 branchname = default_branch;
1269 if (strncmp(branchname, "refs/heads/", 11) == 0)
1270 branchname += 11;
1271 if (asprintf(&branches, "\"%s\" ", branchname) == -1) {
1272 err = got_error_from_errno("asprintf");
1273 goto done;
1276 if (!RB_EMPTY(wanted_refs)) {
1277 struct got_pathlist_entry *pe;
1278 RB_FOREACH(pe, got_pathlist_head, wanted_refs) {
1279 char *s;
1280 const char *refname = pe->path;
1281 if (strncmp(refname, "refs/", 5) == 0)
1282 branchname += 5;
1283 if (asprintf(&s, "%s\"%s\" ",
1284 refs ? refs : "", refname) == -1) {
1285 err = got_error_from_errno("asprintf");
1286 goto done;
1288 free(refs);
1289 refs = s;
1293 /* Create got.conf(5). */
1294 gotconfig_path = got_repo_get_path_gotconfig(repo);
1295 if (gotconfig_path == NULL) {
1296 err = got_error_from_errno("got_repo_get_path_gotconfig");
1297 goto done;
1299 gotconfig_file = fopen(gotconfig_path, "ae");
1300 if (gotconfig_file == NULL) {
1301 err = got_error_from_errno2("fopen", gotconfig_path);
1302 goto done;
1304 if (asprintf(&gotconfig,
1305 "remote \"%s\" {\n"
1306 "\tserver %s\n"
1307 "\tprotocol %s\n"
1308 "%s%s%s"
1309 "\trepository \"%s\"\n"
1310 "%s%s%s"
1311 "%s%s%s"
1312 "%s"
1313 "%s"
1314 "}\n",
1315 GOT_FETCH_DEFAULT_REMOTE_NAME, host, proto,
1316 port ? "\tport " : "", port ? port : "", port ? "\n" : "",
1317 remote_repo_path, branches ? "\tbranch { " : "",
1318 branches ? branches : "", branches ? "}\n" : "",
1319 refs ? "\treference { " : "", refs ? refs : "", refs ? "}\n" : "",
1320 mirror_references ? "\tmirror_references yes\n" : "",
1321 fetch_all_branches ? "\tfetch_all_branches yes\n" : "") == -1) {
1322 err = got_error_from_errno("asprintf");
1323 goto done;
1325 n = fwrite(gotconfig, 1, strlen(gotconfig), gotconfig_file);
1326 if (n != strlen(gotconfig)) {
1327 err = got_ferror(gotconfig_file, GOT_ERR_IO);
1328 goto done;
1331 done:
1332 if (gotconfig_file && fclose(gotconfig_file) == EOF && err == NULL)
1333 err = got_error_from_errno2("fclose", gotconfig_path);
1334 free(gotconfig_path);
1335 free(branches);
1336 return err;
1339 static const struct got_error *
1340 create_gitconfig(const char *git_url, const char *default_branch,
1341 int fetch_all_branches, struct got_pathlist_head *wanted_branches,
1342 struct got_pathlist_head *wanted_refs, int mirror_references,
1343 struct got_repository *repo)
1345 const struct got_error *err = NULL;
1346 char *gitconfig_path = NULL;
1347 char *gitconfig = NULL;
1348 FILE *gitconfig_file = NULL;
1349 char *branches = NULL, *refs = NULL;
1350 const char *branchname;
1351 ssize_t n;
1353 /* Create a config file Git can understand. */
1354 gitconfig_path = got_repo_get_path_gitconfig(repo);
1355 if (gitconfig_path == NULL) {
1356 err = got_error_from_errno("got_repo_get_path_gitconfig");
1357 goto done;
1359 gitconfig_file = fopen(gitconfig_path, "ae");
1360 if (gitconfig_file == NULL) {
1361 err = got_error_from_errno2("fopen", gitconfig_path);
1362 goto done;
1364 if (fetch_all_branches) {
1365 if (mirror_references) {
1366 if (asprintf(&branches,
1367 "\tfetch = refs/heads/*:refs/heads/*\n") == -1) {
1368 err = got_error_from_errno("asprintf");
1369 goto done;
1371 } else if (asprintf(&branches,
1372 "\tfetch = refs/heads/*:refs/remotes/%s/*\n",
1373 GOT_FETCH_DEFAULT_REMOTE_NAME) == -1) {
1374 err = got_error_from_errno("asprintf");
1375 goto done;
1377 } else if (!RB_EMPTY(wanted_branches)) {
1378 struct got_pathlist_entry *pe;
1379 RB_FOREACH(pe, got_pathlist_head, wanted_branches) {
1380 char *s;
1381 branchname = pe->path;
1382 if (strncmp(branchname, "refs/heads/", 11) == 0)
1383 branchname += 11;
1384 if (mirror_references) {
1385 if (asprintf(&s,
1386 "%s\tfetch = refs/heads/%s:refs/heads/%s\n",
1387 branches ? branches : "",
1388 branchname, branchname) == -1) {
1389 err = got_error_from_errno("asprintf");
1390 goto done;
1392 } else if (asprintf(&s,
1393 "%s\tfetch = refs/heads/%s:refs/remotes/%s/%s\n",
1394 branches ? branches : "",
1395 branchname, GOT_FETCH_DEFAULT_REMOTE_NAME,
1396 branchname) == -1) {
1397 err = got_error_from_errno("asprintf");
1398 goto done;
1400 free(branches);
1401 branches = s;
1403 } else {
1405 * If the server specified a default branch, use just that one.
1406 * Otherwise fall back to fetching all branches on next fetch.
1408 if (default_branch) {
1409 branchname = default_branch;
1410 if (strncmp(branchname, "refs/heads/", 11) == 0)
1411 branchname += 11;
1412 } else
1413 branchname = "*"; /* fall back to all branches */
1414 if (mirror_references) {
1415 if (asprintf(&branches,
1416 "\tfetch = refs/heads/%s:refs/heads/%s\n",
1417 branchname, branchname) == -1) {
1418 err = got_error_from_errno("asprintf");
1419 goto done;
1421 } else if (asprintf(&branches,
1422 "\tfetch = refs/heads/%s:refs/remotes/%s/%s\n",
1423 branchname, GOT_FETCH_DEFAULT_REMOTE_NAME,
1424 branchname) == -1) {
1425 err = got_error_from_errno("asprintf");
1426 goto done;
1429 if (!RB_EMPTY(wanted_refs)) {
1430 struct got_pathlist_entry *pe;
1431 RB_FOREACH(pe, got_pathlist_head, wanted_refs) {
1432 char *s;
1433 const char *refname = pe->path;
1434 if (strncmp(refname, "refs/", 5) == 0)
1435 refname += 5;
1436 if (mirror_references) {
1437 if (asprintf(&s,
1438 "%s\tfetch = refs/%s:refs/%s\n",
1439 refs ? refs : "", refname, refname) == -1) {
1440 err = got_error_from_errno("asprintf");
1441 goto done;
1443 } else if (asprintf(&s,
1444 "%s\tfetch = refs/%s:refs/remotes/%s/%s\n",
1445 refs ? refs : "",
1446 refname, GOT_FETCH_DEFAULT_REMOTE_NAME,
1447 refname) == -1) {
1448 err = got_error_from_errno("asprintf");
1449 goto done;
1451 free(refs);
1452 refs = s;
1456 if (asprintf(&gitconfig,
1457 "[remote \"%s\"]\n"
1458 "\turl = %s\n"
1459 "%s"
1460 "%s"
1461 "\tfetch = refs/tags/*:refs/tags/*\n",
1462 GOT_FETCH_DEFAULT_REMOTE_NAME, git_url, branches ? branches : "",
1463 refs ? refs : "") == -1) {
1464 err = got_error_from_errno("asprintf");
1465 goto done;
1467 n = fwrite(gitconfig, 1, strlen(gitconfig), gitconfig_file);
1468 if (n != strlen(gitconfig)) {
1469 err = got_ferror(gitconfig_file, GOT_ERR_IO);
1470 goto done;
1472 done:
1473 if (gitconfig_file && fclose(gitconfig_file) == EOF && err == NULL)
1474 err = got_error_from_errno2("fclose", gitconfig_path);
1475 free(gitconfig_path);
1476 free(branches);
1477 return err;
1480 static const struct got_error *
1481 create_config_files(const char *proto, const char *host, const char *port,
1482 const char *remote_repo_path, const char *git_url, int fetch_all_branches,
1483 int mirror_references, struct got_pathlist_head *symrefs,
1484 struct got_pathlist_head *wanted_branches,
1485 struct got_pathlist_head *wanted_refs, struct got_repository *repo)
1487 const struct got_error *err = NULL;
1488 const char *default_branch = NULL;
1489 struct got_pathlist_entry *pe;
1492 * If we asked for a set of wanted branches then use the first
1493 * one of those.
1495 if (!RB_EMPTY(wanted_branches)) {
1496 pe = RB_MIN(got_pathlist_head, wanted_branches);
1497 default_branch = pe->path;
1498 } else {
1499 /* First HEAD ref listed by server is the default branch. */
1500 RB_FOREACH(pe, got_pathlist_head, symrefs) {
1501 const char *refname = pe->path;
1502 const char *target = pe->data;
1504 if (strcmp(refname, GOT_REF_HEAD) != 0)
1505 continue;
1507 default_branch = target;
1508 break;
1512 /* Create got.conf(5). */
1513 err = create_gotconfig(proto, host, port, remote_repo_path,
1514 default_branch, fetch_all_branches, wanted_branches,
1515 wanted_refs, mirror_references, repo);
1516 if (err)
1517 return err;
1519 /* Create a config file Git can understand. */
1520 return create_gitconfig(git_url, default_branch, fetch_all_branches,
1521 wanted_branches, wanted_refs, mirror_references, repo);
1524 static const struct got_error *
1525 cmd_clone(int argc, char *argv[])
1527 const struct got_error *error = NULL;
1528 const char *uri, *dirname;
1529 char *proto, *host, *port, *repo_name, *server_path;
1530 char *default_destdir = NULL, *id_str = NULL;
1531 const char *repo_path;
1532 struct got_repository *repo = NULL;
1533 struct got_pathlist_head refs, symrefs, wanted_branches, wanted_refs;
1534 struct got_pathlist_entry *pe;
1535 struct got_object_id *pack_hash = NULL;
1536 int ch, fetchfd = -1, fetchstatus;
1537 pid_t fetchpid = -1;
1538 struct got_fetch_progress_arg fpa;
1539 char *git_url = NULL;
1540 int verbosity = 0, fetch_all_branches = 0, mirror_references = 0;
1541 int bflag = 0, list_refs_only = 0;
1542 int *pack_fds = NULL;
1543 const char *identity_file = NULL;
1544 const char *jumphost = NULL;
1546 RB_INIT(&refs);
1547 RB_INIT(&symrefs);
1548 RB_INIT(&wanted_branches);
1549 RB_INIT(&wanted_refs);
1551 while ((ch = getopt(argc, argv, "ab:i:J:lmqR:v")) != -1) {
1552 switch (ch) {
1553 case 'a':
1554 fetch_all_branches = 1;
1555 break;
1556 case 'b':
1557 error = got_pathlist_insert(NULL, &wanted_branches,
1558 optarg, NULL);
1559 if (error)
1560 return error;
1561 bflag = 1;
1562 break;
1563 case 'i':
1564 identity_file = optarg;
1565 break;
1566 case 'J':
1567 jumphost = optarg;
1568 break;
1569 case 'l':
1570 list_refs_only = 1;
1571 break;
1572 case 'm':
1573 mirror_references = 1;
1574 break;
1575 case 'q':
1576 verbosity = -1;
1577 break;
1578 case 'R':
1579 error = got_pathlist_insert(NULL, &wanted_refs,
1580 optarg, NULL);
1581 if (error)
1582 return error;
1583 break;
1584 case 'v':
1585 if (verbosity < 0)
1586 verbosity = 0;
1587 else if (verbosity < 3)
1588 verbosity++;
1589 break;
1590 default:
1591 usage_clone();
1592 break;
1595 argc -= optind;
1596 argv += optind;
1598 if (fetch_all_branches && !RB_EMPTY(&wanted_branches))
1599 option_conflict('a', 'b');
1600 if (list_refs_only) {
1601 if (!RB_EMPTY(&wanted_branches))
1602 option_conflict('l', 'b');
1603 if (fetch_all_branches)
1604 option_conflict('l', 'a');
1605 if (mirror_references)
1606 option_conflict('l', 'm');
1607 if (!RB_EMPTY(&wanted_refs))
1608 option_conflict('l', 'R');
1611 uri = argv[0];
1613 if (argc == 1)
1614 dirname = NULL;
1615 else if (argc == 2)
1616 dirname = argv[1];
1617 else
1618 usage_clone();
1620 error = got_dial_parse_uri(&proto, &host, &port, &server_path,
1621 &repo_name, uri);
1622 if (error)
1623 goto done;
1625 if (asprintf(&git_url, "%s://%s%s%s%s%s", proto,
1626 host, port ? ":" : "", port ? port : "",
1627 server_path[0] != '/' ? "/" : "", server_path) == -1) {
1628 error = got_error_from_errno("asprintf");
1629 goto done;
1632 if (strcmp(proto, "git") == 0) {
1633 #ifndef PROFILE
1634 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
1635 "sendfd dns inet unveil", NULL) == -1)
1636 err(1, "pledge");
1637 #endif
1638 } else if (strcmp(proto, "git+ssh") == 0 ||
1639 strcmp(proto, "ssh") == 0) {
1640 #ifndef PROFILE
1641 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
1642 "sendfd unveil", NULL) == -1)
1643 err(1, "pledge");
1644 #endif
1645 } else if (strcmp(proto, "http") == 0 ||
1646 strcmp(proto, "git+http") == 0) {
1647 error = got_error_path(proto, GOT_ERR_NOT_IMPL);
1648 goto done;
1649 } else {
1650 error = got_error_path(proto, GOT_ERR_BAD_PROTO);
1651 goto done;
1653 if (dirname == NULL) {
1654 if (asprintf(&default_destdir, "%s.git", repo_name) == -1) {
1655 error = got_error_from_errno("asprintf");
1656 goto done;
1658 repo_path = default_destdir;
1659 } else
1660 repo_path = dirname;
1662 if (!list_refs_only) {
1663 error = got_path_mkdir(repo_path);
1664 if (error &&
1665 (!(error->code == GOT_ERR_ERRNO && errno == EISDIR) &&
1666 !(error->code == GOT_ERR_ERRNO && errno == EEXIST)))
1667 goto done;
1668 if (!got_path_dir_is_empty(repo_path)) {
1669 error = got_error_path(repo_path,
1670 GOT_ERR_DIR_NOT_EMPTY);
1671 goto done;
1675 error = got_dial_apply_unveil(proto);
1676 if (error)
1677 goto done;
1679 error = apply_unveil(repo_path, 0, NULL);
1680 if (error)
1681 goto done;
1683 if (verbosity >= 0)
1684 printf("Connecting to %s\n", git_url);
1686 error = got_fetch_connect(&fetchpid, &fetchfd, proto, host, port,
1687 server_path, jumphost, identity_file, verbosity);
1688 if (error)
1689 goto done;
1691 if (!list_refs_only) {
1692 error = got_repo_init(repo_path, NULL, GOT_HASH_SHA1);
1693 if (error)
1694 goto done;
1695 error = got_repo_pack_fds_open(&pack_fds);
1696 if (error != NULL)
1697 goto done;
1698 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
1699 if (error)
1700 goto done;
1703 fpa.last_scaled_size[0] = '\0';
1704 fpa.last_p_indexed = -1;
1705 fpa.last_p_resolved = -1;
1706 fpa.verbosity = verbosity;
1707 fpa.create_configs = 1;
1708 fpa.configs_created = 0;
1709 fpa.repo = repo;
1710 fpa.config_info.symrefs = &symrefs;
1711 fpa.config_info.wanted_branches = &wanted_branches;
1712 fpa.config_info.wanted_refs = &wanted_refs;
1713 fpa.config_info.proto = proto;
1714 fpa.config_info.host = host;
1715 fpa.config_info.port = port;
1716 fpa.config_info.remote_repo_path = server_path;
1717 fpa.config_info.git_url = git_url;
1718 fpa.config_info.fetch_all_branches = fetch_all_branches;
1719 fpa.config_info.mirror_references = mirror_references;
1720 error = got_fetch_pack(&pack_hash, &refs, &symrefs,
1721 GOT_FETCH_DEFAULT_REMOTE_NAME, mirror_references,
1722 fetch_all_branches, &wanted_branches, &wanted_refs,
1723 list_refs_only, verbosity, fetchfd, repo, NULL, NULL, bflag,
1724 fetch_progress, &fpa);
1725 if (error)
1726 goto done;
1728 if (list_refs_only) {
1729 error = list_remote_refs(&symrefs, &refs);
1730 goto done;
1733 if (pack_hash == NULL) {
1734 error = got_error_fmt(GOT_ERR_FETCH_FAILED, "%s",
1735 "server sent an empty pack file");
1736 goto done;
1738 error = got_object_id_str(&id_str, pack_hash);
1739 if (error)
1740 goto done;
1741 if (verbosity >= 0)
1742 printf("\nFetched %s.pack\n", id_str);
1743 free(id_str);
1745 /* Set up references provided with the pack file. */
1746 RB_FOREACH(pe, got_pathlist_head, &refs) {
1747 const char *refname = pe->path;
1748 struct got_object_id *id = pe->data;
1749 char *remote_refname;
1751 if (is_wanted_ref(&wanted_refs, refname) &&
1752 !mirror_references) {
1753 error = create_wanted_ref(refname, id,
1754 GOT_FETCH_DEFAULT_REMOTE_NAME,
1755 verbosity - 1, repo);
1756 if (error)
1757 goto done;
1758 continue;
1761 error = create_ref(refname, id, verbosity - 1, repo);
1762 if (error)
1763 goto done;
1765 if (mirror_references)
1766 continue;
1768 if (strncmp("refs/heads/", refname, 11) != 0)
1769 continue;
1771 if (asprintf(&remote_refname,
1772 "refs/remotes/%s/%s", GOT_FETCH_DEFAULT_REMOTE_NAME,
1773 refname + 11) == -1) {
1774 error = got_error_from_errno("asprintf");
1775 goto done;
1777 error = create_ref(remote_refname, id, verbosity - 1, repo);
1778 free(remote_refname);
1779 if (error)
1780 goto done;
1783 /* Set the HEAD reference if the server provided one. */
1784 RB_FOREACH(pe, got_pathlist_head, &symrefs) {
1785 struct got_reference *target_ref;
1786 const char *refname = pe->path;
1787 const char *target = pe->data;
1788 char *remote_refname = NULL, *remote_target = NULL;
1790 if (strcmp(refname, GOT_REF_HEAD) != 0)
1791 continue;
1793 error = got_ref_open(&target_ref, repo, target, 0);
1794 if (error) {
1795 if (error->code == GOT_ERR_NOT_REF) {
1796 error = NULL;
1797 continue;
1799 goto done;
1802 error = create_symref(refname, target_ref, verbosity, repo);
1803 got_ref_close(target_ref);
1804 if (error)
1805 goto done;
1807 if (mirror_references)
1808 continue;
1810 if (strncmp("refs/heads/", target, 11) != 0)
1811 continue;
1813 if (asprintf(&remote_refname,
1814 "refs/remotes/%s/%s", GOT_FETCH_DEFAULT_REMOTE_NAME,
1815 refname) == -1) {
1816 error = got_error_from_errno("asprintf");
1817 goto done;
1819 if (asprintf(&remote_target,
1820 "refs/remotes/%s/%s", GOT_FETCH_DEFAULT_REMOTE_NAME,
1821 target + 11) == -1) {
1822 error = got_error_from_errno("asprintf");
1823 free(remote_refname);
1824 goto done;
1826 error = got_ref_open(&target_ref, repo, remote_target, 0);
1827 if (error) {
1828 free(remote_refname);
1829 free(remote_target);
1830 if (error->code == GOT_ERR_NOT_REF) {
1831 error = NULL;
1832 continue;
1834 goto done;
1836 error = create_symref(remote_refname, target_ref,
1837 verbosity - 1, repo);
1838 free(remote_refname);
1839 free(remote_target);
1840 got_ref_close(target_ref);
1841 if (error)
1842 goto done;
1844 if (pe == NULL) {
1846 * We failed to set the HEAD reference. If we asked for
1847 * a set of wanted branches use the first of one of those
1848 * which could be fetched instead.
1850 RB_FOREACH(pe, got_pathlist_head, &wanted_branches) {
1851 const char *target = pe->path;
1852 struct got_reference *target_ref;
1854 error = got_ref_open(&target_ref, repo, target, 0);
1855 if (error) {
1856 if (error->code == GOT_ERR_NOT_REF) {
1857 error = NULL;
1858 continue;
1860 goto done;
1863 error = create_symref(GOT_REF_HEAD, target_ref,
1864 verbosity, repo);
1865 got_ref_close(target_ref);
1866 if (error)
1867 goto done;
1868 break;
1871 if (!fpa.configs_created && pe != NULL) {
1872 error = create_config_files(fpa.config_info.proto,
1873 fpa.config_info.host, fpa.config_info.port,
1874 fpa.config_info.remote_repo_path,
1875 fpa.config_info.git_url,
1876 fpa.config_info.fetch_all_branches,
1877 fpa.config_info.mirror_references,
1878 fpa.config_info.symrefs,
1879 fpa.config_info.wanted_branches,
1880 fpa.config_info.wanted_refs, fpa.repo);
1881 if (error)
1882 goto done;
1886 if (verbosity >= 0)
1887 printf("Created %s repository '%s'\n",
1888 mirror_references ? "mirrored" : "cloned", repo_path);
1889 done:
1890 if (pack_fds) {
1891 const struct got_error *pack_err =
1892 got_repo_pack_fds_close(pack_fds);
1893 if (error == NULL)
1894 error = pack_err;
1896 if (fetchpid > 0) {
1897 if (kill(fetchpid, SIGTERM) == -1)
1898 error = got_error_from_errno("kill");
1899 if (waitpid(fetchpid, &fetchstatus, 0) == -1 && error == NULL)
1900 error = got_error_from_errno("waitpid");
1902 if (fetchfd != -1 && close(fetchfd) == -1 && error == NULL)
1903 error = got_error_from_errno("close");
1904 if (repo) {
1905 const struct got_error *close_err = got_repo_close(repo);
1906 if (error == NULL)
1907 error = close_err;
1909 got_pathlist_free(&refs, GOT_PATHLIST_FREE_ALL);
1910 got_pathlist_free(&symrefs, GOT_PATHLIST_FREE_ALL);
1911 got_pathlist_free(&wanted_branches, GOT_PATHLIST_FREE_NONE);
1912 got_pathlist_free(&wanted_refs, GOT_PATHLIST_FREE_NONE);
1913 free(pack_hash);
1914 free(proto);
1915 free(host);
1916 free(port);
1917 free(server_path);
1918 free(repo_name);
1919 free(default_destdir);
1920 free(git_url);
1921 return error;
1924 static const struct got_error *
1925 update_ref(struct got_reference *ref, struct got_object_id *new_id,
1926 int replace_tags, int verbosity, struct got_repository *repo)
1928 const struct got_error *err = NULL;
1929 char *new_id_str = NULL;
1930 struct got_object_id *old_id = NULL;
1932 err = got_object_id_str(&new_id_str, new_id);
1933 if (err)
1934 goto done;
1936 if (!replace_tags &&
1937 strncmp(got_ref_get_name(ref), "refs/tags/", 10) == 0) {
1938 err = got_ref_resolve(&old_id, repo, ref);
1939 if (err)
1940 goto done;
1941 if (got_object_id_cmp(old_id, new_id) == 0)
1942 goto done;
1943 if (verbosity >= 0) {
1944 printf("Rejecting update of existing tag %s: %s\n",
1945 got_ref_get_name(ref), new_id_str);
1947 goto done;
1950 if (got_ref_is_symbolic(ref)) {
1951 if (verbosity >= 0) {
1952 printf("Replacing reference %s: %s\n",
1953 got_ref_get_name(ref),
1954 got_ref_get_symref_target(ref));
1956 err = got_ref_change_symref_to_ref(ref, new_id);
1957 if (err)
1958 goto done;
1959 err = got_ref_write(ref, repo);
1960 if (err)
1961 goto done;
1962 } else {
1963 err = got_ref_resolve(&old_id, repo, ref);
1964 if (err)
1965 goto done;
1966 if (got_object_id_cmp(old_id, new_id) == 0)
1967 goto done;
1969 err = got_ref_change_ref(ref, new_id);
1970 if (err)
1971 goto done;
1972 err = got_ref_write(ref, repo);
1973 if (err)
1974 goto done;
1977 if (verbosity >= 0)
1978 printf("Updated %s: %s\n", got_ref_get_name(ref),
1979 new_id_str);
1980 done:
1981 free(old_id);
1982 free(new_id_str);
1983 return err;
1986 static const struct got_error *
1987 update_wanted_ref(const char *refname, struct got_object_id *id,
1988 const char *remote_repo_name, int verbosity, struct got_repository *repo)
1990 const struct got_error *err, *unlock_err;
1991 char *remote_refname;
1992 struct got_reference *ref;
1994 if (strncmp("refs/", refname, 5) == 0)
1995 refname += 5;
1997 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
1998 remote_repo_name, refname) == -1)
1999 return got_error_from_errno("asprintf");
2001 err = got_ref_open(&ref, repo, remote_refname, 1);
2002 if (err) {
2003 if (err->code != GOT_ERR_NOT_REF)
2004 goto done;
2005 err = create_ref(remote_refname, id, verbosity, repo);
2006 } else {
2007 err = update_ref(ref, id, 0, verbosity, repo);
2008 unlock_err = got_ref_unlock(ref);
2009 if (unlock_err && err == NULL)
2010 err = unlock_err;
2011 got_ref_close(ref);
2013 done:
2014 free(remote_refname);
2015 return err;
2018 __dead static void
2019 usage_checkout(void)
2021 fprintf(stderr, "usage: %s checkout [-Eq] [-b branch] [-c commit] "
2022 "[-p path-prefix] repository-path [work-tree-path]\n",
2023 getprogname());
2024 exit(1);
2027 static void
2028 show_worktree_base_ref_warning(void)
2030 fprintf(stderr, "%s: warning: could not create a reference "
2031 "to the work tree's base commit; the commit could be "
2032 "garbage-collected by Git or 'gotadmin cleanup'; making the "
2033 "repository writable and running 'got update' will prevent this\n",
2034 getprogname());
2037 struct got_checkout_progress_arg {
2038 const char *worktree_path;
2039 int had_base_commit_ref_error;
2040 int verbosity;
2043 static const struct got_error *
2044 checkout_progress(void *arg, unsigned char status, const char *path)
2046 struct got_checkout_progress_arg *a = arg;
2048 /* Base commit bump happens silently. */
2049 if (status == GOT_STATUS_BUMP_BASE)
2050 return NULL;
2052 if (status == GOT_STATUS_BASE_REF_ERR) {
2053 a->had_base_commit_ref_error = 1;
2054 return NULL;
2057 while (path[0] == '/')
2058 path++;
2060 if (a->verbosity >= 0)
2061 printf("%c %s/%s\n", status, a->worktree_path, path);
2063 return NULL;
2066 static const struct got_error *
2067 check_cancelled(void *arg)
2069 if (sigint_received || sigpipe_received)
2070 return got_error(GOT_ERR_CANCELLED);
2071 return NULL;
2074 static const struct got_error *
2075 check_linear_ancestry(struct got_object_id *commit_id,
2076 struct got_object_id *base_commit_id, int allow_forwards_in_time_only,
2077 struct got_repository *repo)
2079 const struct got_error *err = NULL;
2080 struct got_object_id *yca_id;
2082 err = got_commit_graph_find_youngest_common_ancestor(&yca_id,
2083 commit_id, base_commit_id, 1, 0, repo, check_cancelled, NULL);
2084 if (err)
2085 return err;
2087 if (yca_id == NULL)
2088 return got_error(GOT_ERR_ANCESTRY);
2091 * Require a straight line of history between the target commit
2092 * and the work tree's base commit.
2094 * Non-linear situations such as this require a rebase:
2096 * (commit) D F (base_commit)
2097 * \ /
2098 * C E
2099 * \ /
2100 * B (yca)
2104 * 'got update' only handles linear cases:
2105 * Update forwards in time: A (base/yca) - B - C - D (commit)
2106 * Update backwards in time: D (base) - C - B - A (commit/yca)
2108 if (allow_forwards_in_time_only) {
2109 if (got_object_id_cmp(base_commit_id, yca_id) != 0)
2110 return got_error(GOT_ERR_ANCESTRY);
2111 } else if (got_object_id_cmp(commit_id, yca_id) != 0 &&
2112 got_object_id_cmp(base_commit_id, yca_id) != 0)
2113 return got_error(GOT_ERR_ANCESTRY);
2115 free(yca_id);
2116 return NULL;
2119 static const struct got_error *
2120 check_same_branch(struct got_object_id *commit_id,
2121 struct got_reference *head_ref, struct got_repository *repo)
2123 const struct got_error *err = NULL;
2124 struct got_commit_graph *graph = NULL;
2125 struct got_object_id *head_commit_id = NULL;
2127 err = got_ref_resolve(&head_commit_id, repo, head_ref);
2128 if (err)
2129 goto done;
2131 if (got_object_id_cmp(head_commit_id, commit_id) == 0)
2132 goto done;
2134 err = got_commit_graph_open(&graph, "/", 1);
2135 if (err)
2136 goto done;
2138 err = got_commit_graph_bfsort(graph, head_commit_id, repo,
2139 check_cancelled, NULL);
2140 if (err)
2141 goto done;
2143 for (;;) {
2144 struct got_object_id id;
2146 err = got_commit_graph_iter_next(&id, graph, repo,
2147 check_cancelled, NULL);
2148 if (err) {
2149 if (err->code == GOT_ERR_ITER_COMPLETED)
2150 err = got_error(GOT_ERR_ANCESTRY);
2151 break;
2154 if (got_object_id_cmp(&id, commit_id) == 0)
2155 break;
2157 done:
2158 if (graph)
2159 got_commit_graph_close(graph);
2160 free(head_commit_id);
2161 return err;
2164 static const struct got_error *
2165 checkout_ancestry_error(struct got_reference *ref, const char *commit_id_str)
2167 static char msg[512];
2168 const char *branch_name;
2170 if (got_ref_is_symbolic(ref))
2171 branch_name = got_ref_get_symref_target(ref);
2172 else
2173 branch_name = got_ref_get_name(ref);
2175 if (strncmp("refs/heads/", branch_name, 11) == 0)
2176 branch_name += 11;
2178 snprintf(msg, sizeof(msg),
2179 "target commit is not contained in branch '%s'; "
2180 "the branch to use must be specified with -b; "
2181 "if necessary a new branch can be created for "
2182 "this commit with 'got branch -c %s BRANCH_NAME'",
2183 branch_name, commit_id_str);
2185 return got_error_msg(GOT_ERR_ANCESTRY, msg);
2188 static const struct got_error *
2189 cmd_checkout(int argc, char *argv[])
2191 const struct got_error *error = NULL;
2192 struct got_repository *repo = NULL;
2193 struct got_reference *head_ref = NULL, *ref = NULL;
2194 struct got_worktree *worktree = NULL;
2195 char *repo_path = NULL;
2196 char *worktree_path = NULL;
2197 const char *path_prefix = "";
2198 const char *branch_name = GOT_REF_HEAD, *refname = NULL;
2199 char *commit_id_str = NULL;
2200 struct got_object_id *commit_id = NULL;
2201 char *cwd = NULL;
2202 int ch, same_path_prefix, allow_nonempty = 0, verbosity = 0;
2203 struct got_pathlist_head paths;
2204 struct got_checkout_progress_arg cpa;
2205 int *pack_fds = NULL;
2207 RB_INIT(&paths);
2209 #ifndef PROFILE
2210 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
2211 "unveil", NULL) == -1)
2212 err(1, "pledge");
2213 #endif
2215 while ((ch = getopt(argc, argv, "b:c:Ep:q")) != -1) {
2216 switch (ch) {
2217 case 'b':
2218 branch_name = optarg;
2219 break;
2220 case 'c':
2221 commit_id_str = strdup(optarg);
2222 if (commit_id_str == NULL)
2223 return got_error_from_errno("strdup");
2224 break;
2225 case 'E':
2226 allow_nonempty = 1;
2227 break;
2228 case 'p':
2229 path_prefix = optarg;
2230 break;
2231 case 'q':
2232 verbosity = -1;
2233 break;
2234 default:
2235 usage_checkout();
2236 /* NOTREACHED */
2240 argc -= optind;
2241 argv += optind;
2243 if (argc == 1) {
2244 char *base, *dotgit;
2245 const char *path;
2246 repo_path = realpath(argv[0], NULL);
2247 if (repo_path == NULL)
2248 return got_error_from_errno2("realpath", argv[0]);
2249 cwd = getcwd(NULL, 0);
2250 if (cwd == NULL) {
2251 error = got_error_from_errno("getcwd");
2252 goto done;
2254 if (path_prefix[0])
2255 path = path_prefix;
2256 else
2257 path = repo_path;
2258 error = got_path_basename(&base, path);
2259 if (error)
2260 goto done;
2261 dotgit = strstr(base, ".git");
2262 if (dotgit)
2263 *dotgit = '\0';
2264 if (asprintf(&worktree_path, "%s/%s", cwd, base) == -1) {
2265 error = got_error_from_errno("asprintf");
2266 free(base);
2267 goto done;
2269 free(base);
2270 } else if (argc == 2) {
2271 repo_path = realpath(argv[0], NULL);
2272 if (repo_path == NULL) {
2273 error = got_error_from_errno2("realpath", argv[0]);
2274 goto done;
2276 worktree_path = realpath(argv[1], NULL);
2277 if (worktree_path == NULL) {
2278 if (errno != ENOENT) {
2279 error = got_error_from_errno2("realpath",
2280 argv[1]);
2281 goto done;
2283 worktree_path = strdup(argv[1]);
2284 if (worktree_path == NULL) {
2285 error = got_error_from_errno("strdup");
2286 goto done;
2289 } else
2290 usage_checkout();
2292 got_path_strip_trailing_slashes(repo_path);
2293 got_path_strip_trailing_slashes(worktree_path);
2295 error = got_repo_pack_fds_open(&pack_fds);
2296 if (error != NULL)
2297 goto done;
2299 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
2300 if (error != NULL)
2301 goto done;
2303 /* Pre-create work tree path for unveil(2) */
2304 error = got_path_mkdir(worktree_path);
2305 if (error) {
2306 if (!(error->code == GOT_ERR_ERRNO && errno == EISDIR) &&
2307 !(error->code == GOT_ERR_ERRNO && errno == EEXIST))
2308 goto done;
2309 if (!allow_nonempty &&
2310 !got_path_dir_is_empty(worktree_path)) {
2311 error = got_error_path(worktree_path,
2312 GOT_ERR_DIR_NOT_EMPTY);
2313 goto done;
2317 error = apply_unveil(got_repo_get_path(repo), 0, worktree_path);
2318 if (error)
2319 goto done;
2321 error = got_ref_open(&head_ref, repo, branch_name, 0);
2322 if (error != NULL)
2323 goto done;
2325 error = got_worktree_init(worktree_path, head_ref, path_prefix,
2326 GOT_WORKTREE_CVG_DIR, repo);
2327 if (error != NULL && !(error->code == GOT_ERR_ERRNO && errno == EEXIST))
2328 goto done;
2330 error = got_worktree_open(&worktree, worktree_path, GOT_WORKTREE_CVG_DIR);
2331 if (error != NULL)
2332 goto done;
2334 error = got_worktree_match_path_prefix(&same_path_prefix, worktree,
2335 path_prefix);
2336 if (error != NULL)
2337 goto done;
2338 if (!same_path_prefix) {
2339 error = got_error(GOT_ERR_PATH_PREFIX);
2340 goto done;
2343 if (commit_id_str) {
2344 struct got_reflist_head refs;
2345 TAILQ_INIT(&refs);
2346 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
2347 NULL);
2348 if (error)
2349 goto done;
2350 error = got_repo_match_object_id(&commit_id, NULL,
2351 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
2352 got_ref_list_free(&refs);
2353 if (error)
2354 goto done;
2355 error = check_linear_ancestry(commit_id,
2356 got_worktree_get_base_commit_id(worktree), 0, repo);
2357 if (error != NULL) {
2358 if (error->code == GOT_ERR_ANCESTRY) {
2359 error = checkout_ancestry_error(
2360 head_ref, commit_id_str);
2362 goto done;
2364 error = check_same_branch(commit_id, head_ref, repo);
2365 if (error) {
2366 if (error->code == GOT_ERR_ANCESTRY) {
2367 error = checkout_ancestry_error(
2368 head_ref, commit_id_str);
2370 goto done;
2372 error = got_worktree_set_base_commit_id(worktree, repo,
2373 commit_id);
2374 if (error)
2375 goto done;
2376 /* Expand potentially abbreviated commit ID string. */
2377 free(commit_id_str);
2378 error = got_object_id_str(&commit_id_str, commit_id);
2379 if (error)
2380 goto done;
2381 } else {
2382 commit_id = got_object_id_dup(
2383 got_worktree_get_base_commit_id(worktree));
2384 if (commit_id == NULL) {
2385 error = got_error_from_errno("got_object_id_dup");
2386 goto done;
2388 error = got_object_id_str(&commit_id_str, commit_id);
2389 if (error)
2390 goto done;
2393 error = got_pathlist_insert(NULL, &paths, "", NULL);
2394 if (error)
2395 goto done;
2396 cpa.worktree_path = worktree_path;
2397 cpa.had_base_commit_ref_error = 0;
2398 cpa.verbosity = verbosity;
2399 error = got_worktree_checkout_files(worktree, &paths, repo,
2400 checkout_progress, &cpa, check_cancelled, NULL);
2401 if (error != NULL)
2402 goto done;
2404 if (got_ref_is_symbolic(head_ref)) {
2405 error = got_ref_resolve_symbolic(&ref, repo, head_ref);
2406 if (error)
2407 goto done;
2408 refname = got_ref_get_name(ref);
2409 } else
2410 refname = got_ref_get_name(head_ref);
2411 printf("Checked out %s: %s\n", refname, commit_id_str);
2412 printf("Now shut up and hack\n");
2413 if (cpa.had_base_commit_ref_error)
2414 show_worktree_base_ref_warning();
2415 done:
2416 if (pack_fds) {
2417 const struct got_error *pack_err =
2418 got_repo_pack_fds_close(pack_fds);
2419 if (error == NULL)
2420 error = pack_err;
2422 if (head_ref)
2423 got_ref_close(head_ref);
2424 if (ref)
2425 got_ref_close(ref);
2426 if (repo) {
2427 const struct got_error *close_err = got_repo_close(repo);
2428 if (error == NULL)
2429 error = close_err;
2431 got_pathlist_free(&paths, GOT_PATHLIST_FREE_NONE);
2432 free(commit_id_str);
2433 free(commit_id);
2434 free(repo_path);
2435 free(worktree_path);
2436 free(cwd);
2437 return error;
2440 struct got_update_progress_arg {
2441 int did_something;
2442 int conflicts;
2443 int obstructed;
2444 int not_updated;
2445 int missing;
2446 int not_deleted;
2447 int unversioned;
2448 int verbosity;
2451 static void
2452 print_update_progress_stats(struct got_update_progress_arg *upa)
2454 if (!upa->did_something)
2455 return;
2457 if (upa->conflicts > 0)
2458 printf("Files with new merge conflicts: %d\n", upa->conflicts);
2459 if (upa->obstructed > 0)
2460 printf("File paths obstructed by a non-regular file: %d\n",
2461 upa->obstructed);
2462 if (upa->not_updated > 0)
2463 printf("Files not updated because of existing merge "
2464 "conflicts: %d\n", upa->not_updated);
2468 * The meaning of some status codes differs between merge-style operations and
2469 * update operations. For example, the ! status code means "file was missing"
2470 * if changes were merged into the work tree, and "missing file was restored"
2471 * if the work tree was updated. This function should be used by any operation
2472 * which merges changes into the work tree without updating the work tree.
2474 static void
2475 print_merge_progress_stats(struct got_update_progress_arg *upa)
2477 if (!upa->did_something)
2478 return;
2480 if (upa->conflicts > 0)
2481 printf("Files with new merge conflicts: %d\n", upa->conflicts);
2482 if (upa->obstructed > 0)
2483 printf("File paths obstructed by a non-regular file: %d\n",
2484 upa->obstructed);
2485 if (upa->missing > 0)
2486 printf("Files which had incoming changes but could not be "
2487 "found in the work tree: %d\n", upa->missing);
2488 if (upa->not_deleted > 0)
2489 printf("Files not deleted due to differences in deleted "
2490 "content: %d\n", upa->not_deleted);
2491 if (upa->unversioned > 0)
2492 printf("Files not merged because an unversioned file was "
2493 "found in the work tree: %d\n", upa->unversioned);
2496 __dead static void
2497 usage_update(void)
2499 fprintf(stderr, "usage: %s update [-qtvX] [-c commit] "
2500 "[-i identity-file] [-J jumphost] [-r remote] [path ...]\n",
2501 getprogname());
2502 exit(1);
2505 static const struct got_error *
2506 update_progress(void *arg, unsigned char status, const char *path)
2508 struct got_update_progress_arg *upa = arg;
2510 if (status == GOT_STATUS_EXISTS ||
2511 status == GOT_STATUS_BASE_REF_ERR)
2512 return NULL;
2514 upa->did_something = 1;
2516 /* Base commit bump happens silently. */
2517 if (status == GOT_STATUS_BUMP_BASE)
2518 return NULL;
2520 if (status == GOT_STATUS_CONFLICT)
2521 upa->conflicts++;
2522 if (status == GOT_STATUS_OBSTRUCTED)
2523 upa->obstructed++;
2524 if (status == GOT_STATUS_CANNOT_UPDATE)
2525 upa->not_updated++;
2526 if (status == GOT_STATUS_MISSING)
2527 upa->missing++;
2528 if (status == GOT_STATUS_CANNOT_DELETE)
2529 upa->not_deleted++;
2530 if (status == GOT_STATUS_UNVERSIONED)
2531 upa->unversioned++;
2533 while (path[0] == '/')
2534 path++;
2535 if (upa->verbosity >= 0)
2536 printf("%c %s\n", status, path);
2538 return NULL;
2541 static const struct got_error *
2542 check_rebase_or_histedit_in_progress(struct got_worktree *worktree)
2544 const struct got_error *err;
2545 int in_progress;
2547 err = got_worktree_rebase_in_progress(&in_progress, worktree);
2548 if (err)
2549 return err;
2550 if (in_progress)
2551 return got_error(GOT_ERR_REBASING);
2553 err = got_worktree_histedit_in_progress(&in_progress, worktree);
2554 if (err)
2555 return err;
2556 if (in_progress)
2557 return got_error(GOT_ERR_HISTEDIT_BUSY);
2559 return NULL;
2562 static const struct got_error *
2563 check_merge_in_progress(struct got_worktree *worktree,
2564 struct got_repository *repo)
2566 const struct got_error *err;
2567 int in_progress;
2569 err = got_worktree_merge_in_progress(&in_progress, worktree, repo);
2570 if (err)
2571 return err;
2572 if (in_progress)
2573 return got_error(GOT_ERR_MERGE_BUSY);
2575 return NULL;
2578 static const struct got_error *
2579 get_worktree_paths_from_argv(struct got_pathlist_head *paths, int argc,
2580 char *argv[], struct got_worktree *worktree)
2582 const struct got_error *err = NULL;
2583 char *path;
2584 struct got_pathlist_entry *new;
2585 int i;
2587 if (argc == 0) {
2588 path = strdup("");
2589 if (path == NULL)
2590 return got_error_from_errno("strdup");
2591 return got_pathlist_insert(NULL, paths, path, NULL);
2594 for (i = 0; i < argc; i++) {
2595 err = got_worktree_resolve_path(&path, worktree, argv[i]);
2596 if (err)
2597 break;
2598 err = got_pathlist_insert(&new, paths, path, NULL);
2599 if (err || new == NULL /* duplicate */) {
2600 free(path);
2601 if (err)
2602 break;
2606 return err;
2609 static const struct got_error *
2610 wrap_not_worktree_error(const struct got_error *orig_err,
2611 const char *cmdname, const char *path)
2613 const struct got_error *err;
2614 struct got_repository *repo;
2615 static char msg[512];
2616 int *pack_fds = NULL;
2618 err = got_repo_pack_fds_open(&pack_fds);
2619 if (err)
2620 return err;
2622 err = got_repo_open(&repo, path, NULL, pack_fds);
2623 if (err)
2624 return orig_err;
2626 snprintf(msg, sizeof(msg),
2627 "'got %s' needs a work tree in addition to a git repository\n"
2628 "Work trees can be checked out from this Git repository with "
2629 "'got checkout'.\n"
2630 "The got(1) manual page contains more information.", cmdname);
2631 err = got_error_msg(GOT_ERR_NOT_WORKTREE, msg);
2632 if (repo) {
2633 const struct got_error *close_err = got_repo_close(repo);
2634 if (err == NULL)
2635 err = close_err;
2637 if (pack_fds) {
2638 const struct got_error *pack_err =
2639 got_repo_pack_fds_close(pack_fds);
2640 if (err == NULL)
2641 err = pack_err;
2643 return err;
2646 static const struct got_error *
2647 cmd_update(int argc, char *argv[])
2649 const struct got_error *error = NULL, *unlock_err;
2650 char *worktree_path = NULL;
2651 const char *repo_path = NULL;
2652 const char *remote_name = NULL;
2653 char *proto = NULL, *host = NULL, *port = NULL;
2654 char *repo_name = NULL, *server_path = NULL;
2655 const struct got_remote_repo *remotes, *remote = NULL;
2656 int nremotes;
2657 char *id_str = NULL;
2658 struct got_repository *repo = NULL;
2659 struct got_worktree *worktree = NULL;
2660 const struct got_gotconfig *repo_conf = NULL, *worktree_conf = NULL;
2661 struct got_pathlist_head paths, refs, symrefs;
2662 struct got_pathlist_head wanted_branches, wanted_refs;
2663 struct got_pathlist_entry *pe;
2664 struct got_reflist_head remote_refs;
2665 struct got_reflist_entry *re;
2666 struct got_object_id *pack_hash = NULL;
2667 int i, ch, fetchfd = -1, fetchstatus;
2668 pid_t fetchpid = -1;
2669 struct got_fetch_progress_arg fpa;
2670 struct got_update_progress_arg upa;
2671 int verbosity = 0;
2672 int delete_remote = 0;
2673 int replace_tags = 0;
2674 int *pack_fds = NULL;
2675 const char *remote_head = NULL, *worktree_branch = NULL;
2676 struct got_object_id *commit_id = NULL;
2677 char *commit_id_str = NULL;
2678 const char *refname;
2679 struct got_reference *head_ref = NULL;
2680 const char *identity_file = NULL;
2681 const char *jumphost = NULL;
2683 RB_INIT(&paths);
2684 RB_INIT(&refs);
2685 RB_INIT(&symrefs);
2686 TAILQ_INIT(&remote_refs);
2687 RB_INIT(&wanted_branches);
2688 RB_INIT(&wanted_refs);
2690 while ((ch = getopt(argc, argv, "c:i:J:qr:vX")) != -1) {
2691 switch (ch) {
2692 case 'c':
2693 commit_id_str = strdup(optarg);
2694 if (commit_id_str == NULL)
2695 return got_error_from_errno("strdup");
2696 break;
2697 case 'i':
2698 identity_file = optarg;
2699 break;
2700 case 'J':
2701 jumphost = optarg;
2702 break;
2703 case 't':
2704 replace_tags = 1;
2705 break;
2706 case 'q':
2707 verbosity = -1;
2708 break;
2709 case 'r':
2710 remote_name = optarg;
2711 break;
2712 case 'v':
2713 if (verbosity < 0)
2714 verbosity = 0;
2715 else if (verbosity < 3)
2716 verbosity++;
2717 break;
2718 case 'X':
2719 delete_remote = 1;
2720 break;
2721 default:
2722 usage_update();
2723 break;
2726 argc -= optind;
2727 argv += optind;
2729 if (delete_remote) {
2730 if (replace_tags)
2731 option_conflict('X', 't');
2732 if (remote_name == NULL)
2733 errx(1, "-X option requires a remote name");
2735 if (remote_name == NULL)
2736 remote_name = GOT_FETCH_DEFAULT_REMOTE_NAME;
2738 worktree_path = getcwd(NULL, 0);
2739 if (worktree_path == NULL) {
2740 error = got_error_from_errno("getcwd");
2741 goto done;
2743 error = got_worktree_open(&worktree, worktree_path, GOT_WORKTREE_CVG_DIR);
2744 if (error) {
2745 if (error->code == GOT_ERR_NOT_WORKTREE)
2746 error = wrap_not_worktree_error(error, "update",
2747 worktree_path);
2748 goto done;
2750 repo_path = got_worktree_get_repo_path(worktree);
2752 error = got_repo_pack_fds_open(&pack_fds);
2753 if (error != NULL)
2754 goto done;
2756 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
2757 if (error)
2758 goto done;
2760 error = check_rebase_or_histedit_in_progress(worktree);
2761 if (error)
2762 goto done;
2763 error = check_merge_in_progress(worktree, repo);
2764 if (error)
2765 goto done;
2767 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
2768 if (error)
2769 goto done;
2771 worktree_conf = got_worktree_get_gotconfig(worktree);
2772 if (worktree_conf) {
2773 got_gotconfig_get_remotes(&nremotes, &remotes,
2774 worktree_conf);
2775 for (i = 0; i < nremotes; i++) {
2776 if (strcmp(remotes[i].name, remote_name) == 0) {
2777 remote = &remotes[i];
2778 break;
2783 if (remote == NULL) {
2784 repo_conf = got_repo_get_gotconfig(repo);
2785 if (repo_conf) {
2786 got_gotconfig_get_remotes(&nremotes, &remotes,
2787 repo_conf);
2788 for (i = 0; i < nremotes; i++) {
2789 if (strcmp(remotes[i].name, remote_name) == 0) {
2790 remote = &remotes[i];
2791 break;
2796 if (remote == NULL) {
2797 got_repo_get_gitconfig_remotes(&nremotes, &remotes, repo);
2798 for (i = 0; i < nremotes; i++) {
2799 if (strcmp(remotes[i].name, remote_name) == 0) {
2800 remote = &remotes[i];
2801 break;
2805 if (remote == NULL) {
2806 error = got_error_path(remote_name, GOT_ERR_NO_REMOTE);
2807 goto done;
2810 error = got_dial_parse_uri(&proto, &host, &port, &server_path,
2811 &repo_name, remote->fetch_url);
2812 if (error)
2813 goto done;
2815 if (strcmp(proto, "git") == 0) {
2816 #ifndef PROFILE
2817 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
2818 "sendfd dns inet unveil", NULL) == -1)
2819 err(1, "pledge");
2820 #endif
2821 } else if (strcmp(proto, "git+ssh") == 0 ||
2822 strcmp(proto, "ssh") == 0) {
2823 #ifndef PROFILE
2824 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
2825 "sendfd unveil", NULL) == -1)
2826 err(1, "pledge");
2827 #endif
2828 } else if (strcmp(proto, "http") == 0 ||
2829 strcmp(proto, "git+http") == 0) {
2830 error = got_error_path(proto, GOT_ERR_NOT_IMPL);
2831 goto done;
2832 } else {
2833 error = got_error_path(proto, GOT_ERR_BAD_PROTO);
2834 goto done;
2837 error = got_dial_apply_unveil(proto);
2838 if (error)
2839 goto done;
2841 error = apply_unveil(got_repo_get_path(repo), 0,
2842 got_worktree_get_root_path(worktree));
2843 if (error)
2844 goto done;
2846 if (verbosity >= 0) {
2847 printf("Connecting to \"%s\" %s://%s%s%s%s%s\n",
2848 remote->name, proto, host,
2849 port ? ":" : "", port ? port : "",
2850 *server_path == '/' ? "" : "/", server_path);
2853 error = got_fetch_connect(&fetchpid, &fetchfd, proto, host, port,
2854 server_path, jumphost, identity_file, verbosity);
2855 if (error)
2856 goto done;
2859 * If set, get this remote's HEAD ref target so
2860 * if it has changed on the server we can fetch it.
2862 error = got_ref_list(&remote_refs, repo, "refs/remotes",
2863 got_ref_cmp_by_name, repo);
2864 if (error)
2865 goto done;
2867 TAILQ_FOREACH(re, &remote_refs, entry) {
2868 const char *remote_refname, *remote_target;
2869 size_t remote_name_len;
2871 if (!got_ref_is_symbolic(re->ref))
2872 continue;
2874 remote_name_len = strlen(remote->name);
2875 remote_refname = got_ref_get_name(re->ref);
2877 /* we only want refs/remotes/$remote->name/HEAD */
2878 if (strncmp(remote_refname + 13, remote->name,
2879 remote_name_len) != 0)
2880 continue;
2882 if (strcmp(remote_refname + remote_name_len + 14,
2883 GOT_REF_HEAD) != 0)
2884 continue;
2887 * Take the name itself because we already
2888 * only match with refs/heads/ in fetch_pack().
2890 remote_target = got_ref_get_symref_target(re->ref);
2891 remote_head = remote_target + remote_name_len + 14;
2892 break;
2895 refname = got_worktree_get_head_ref_name(worktree);
2896 if (strncmp(refname, "refs/heads/", 11) == 0)
2897 worktree_branch = refname;
2899 fpa.last_scaled_size[0] = '\0';
2900 fpa.last_p_indexed = -1;
2901 fpa.last_p_resolved = -1;
2902 fpa.verbosity = verbosity;
2903 fpa.repo = repo;
2904 fpa.create_configs = 0;
2905 fpa.configs_created = 0;
2906 memset(&fpa.config_info, 0, sizeof(fpa.config_info));
2908 error = got_fetch_pack(&pack_hash, &refs, &symrefs, remote->name,
2909 remote->mirror_references, 0, &wanted_branches, &wanted_refs,
2910 0, verbosity, fetchfd, repo, worktree_branch, remote_head,
2911 0, fetch_progress, &fpa);
2912 if (error)
2913 goto done;
2915 if (pack_hash != NULL && verbosity >= 0) {
2916 error = got_object_id_str(&id_str, pack_hash);
2917 if (error)
2918 goto done;
2919 printf("\nFetched %s.pack\n", id_str);
2920 free(id_str);
2921 id_str = NULL;
2924 /* Update references provided with the pack file. */
2925 RB_FOREACH(pe, got_pathlist_head, &refs) {
2926 const char *refname = pe->path;
2927 struct got_object_id *id = pe->data;
2928 struct got_reference *ref;
2930 if (is_wanted_ref(&wanted_refs, refname)) {
2931 error = update_wanted_ref(refname, id,
2932 remote->name, verbosity, repo);
2933 if (error)
2934 goto done;
2935 continue;
2938 error = got_ref_open(&ref, repo, refname, 1);
2939 if (error) {
2940 if (error->code != GOT_ERR_NOT_REF)
2941 goto done;
2942 error = create_ref(refname, id, verbosity,
2943 repo);
2944 if (error)
2945 goto done;
2946 } else {
2947 error = update_ref(ref, id, replace_tags,
2948 verbosity-1, repo);
2949 unlock_err = got_ref_unlock(ref);
2950 if (unlock_err && error == NULL)
2951 error = unlock_err;
2952 got_ref_close(ref);
2953 if (error)
2954 goto done;
2958 /* Update worktree */
2959 error = got_ref_open(&head_ref, repo,
2960 got_worktree_get_head_ref_name(worktree), 0);
2961 if (error != NULL)
2962 goto done;
2963 if (commit_id_str == NULL) {
2964 error = got_ref_resolve(&commit_id, repo, head_ref);
2965 if (error != NULL)
2966 goto done;
2967 error = got_object_id_str(&commit_id_str, commit_id);
2968 if (error != NULL)
2969 goto done;
2970 } else {
2971 struct got_reflist_head refs;
2972 TAILQ_INIT(&refs);
2973 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
2974 NULL);
2975 if (error)
2976 goto done;
2977 error = got_repo_match_object_id(&commit_id, NULL,
2978 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
2979 got_ref_list_free(&refs);
2980 free(commit_id_str);
2981 commit_id_str = NULL;
2982 if (error)
2983 goto done;
2984 error = got_object_id_str(&commit_id_str, commit_id);
2985 if (error)
2986 goto done;
2990 error = check_linear_ancestry(commit_id,
2991 got_worktree_get_base_commit_id(worktree), 0, repo);
2992 if (error != NULL) {
2993 if (error->code == GOT_ERR_ANCESTRY)
2994 error = got_error(GOT_ERR_BRANCH_MOVED);
2995 goto done;
2997 error = check_same_branch(commit_id, head_ref, repo);
2998 if (error)
2999 goto done;
3001 if (got_object_id_cmp(got_worktree_get_base_commit_id(worktree),
3002 commit_id) != 0) {
3003 error = got_worktree_set_base_commit_id(worktree, repo,
3004 commit_id);
3005 if (error)
3006 goto done;
3009 memset(&upa, 0, sizeof(upa));
3010 upa.verbosity = verbosity;
3011 error = got_worktree_checkout_files(worktree, &paths, repo,
3012 update_progress, &upa, check_cancelled, NULL);
3013 if (error != NULL)
3014 goto done;
3016 if (upa.did_something) {
3017 printf("Updated to %s: %s\n",
3018 got_worktree_get_head_ref_name(worktree), commit_id_str);
3019 } else
3020 printf("Already up-to-date\n");
3022 print_update_progress_stats(&upa);
3023 done:
3024 if (fetchpid > 0) {
3025 if (kill(fetchpid, SIGTERM) == -1)
3026 error = got_error_from_errno("kill");
3027 if (waitpid(fetchpid, &fetchstatus, 0) == -1 && error == NULL)
3028 error = got_error_from_errno("waitpid");
3030 if (fetchfd != -1 && close(fetchfd) == -1 && error == NULL)
3031 error = got_error_from_errno("close");
3032 if (repo) {
3033 const struct got_error *close_err = got_repo_close(repo);
3034 if (error == NULL)
3035 error = close_err;
3037 if (worktree)
3038 got_worktree_close(worktree);
3039 if (pack_fds) {
3040 const struct got_error *pack_err =
3041 got_repo_pack_fds_close(pack_fds);
3042 if (error == NULL)
3043 error = pack_err;
3045 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
3046 got_pathlist_free(&refs, GOT_PATHLIST_FREE_ALL);
3047 got_pathlist_free(&symrefs, GOT_PATHLIST_FREE_ALL);
3048 got_pathlist_free(&wanted_branches, GOT_PATHLIST_FREE_NONE);
3049 got_pathlist_free(&wanted_refs, GOT_PATHLIST_FREE_NONE);
3050 got_ref_list_free(&remote_refs);
3051 free(id_str);
3052 free(worktree_path);
3053 free(pack_hash);
3054 free(proto);
3055 free(host);
3056 free(port);
3057 free(server_path);
3058 free(repo_name);
3059 free(commit_id);
3060 free(commit_id_str);
3061 return error;
3064 static const struct got_error *
3065 diff_blobs(struct got_object_id *blob_id1, struct got_object_id *blob_id2,
3066 const char *path, int diff_context, int ignore_whitespace,
3067 int force_text_diff, struct got_diffstat_cb_arg *dsa,
3068 struct got_repository *repo, FILE *outfile)
3070 const struct got_error *err = NULL;
3071 struct got_blob_object *blob1 = NULL, *blob2 = NULL;
3072 FILE *f1 = NULL, *f2 = NULL;
3073 int fd1 = -1, fd2 = -1;
3075 fd1 = got_opentempfd();
3076 if (fd1 == -1)
3077 return got_error_from_errno("got_opentempfd");
3078 fd2 = got_opentempfd();
3079 if (fd2 == -1) {
3080 err = got_error_from_errno("got_opentempfd");
3081 goto done;
3084 if (blob_id1) {
3085 err = got_object_open_as_blob(&blob1, repo, blob_id1, 8192,
3086 fd1);
3087 if (err)
3088 goto done;
3091 err = got_object_open_as_blob(&blob2, repo, blob_id2, 8192, fd2);
3092 if (err)
3093 goto done;
3095 f1 = got_opentemp();
3096 if (f1 == NULL) {
3097 err = got_error_from_errno("got_opentemp");
3098 goto done;
3100 f2 = got_opentemp();
3101 if (f2 == NULL) {
3102 err = got_error_from_errno("got_opentemp");
3103 goto done;
3106 while (path[0] == '/')
3107 path++;
3108 err = got_diff_blob(NULL, NULL, blob1, blob2, f1, f2, path, path,
3109 GOT_DIFF_ALGORITHM_PATIENCE, diff_context, ignore_whitespace,
3110 force_text_diff, dsa, outfile);
3111 done:
3112 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
3113 err = got_error_from_errno("close");
3114 if (blob1)
3115 got_object_blob_close(blob1);
3116 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
3117 err = got_error_from_errno("close");
3118 if (blob2)
3119 got_object_blob_close(blob2);
3120 if (f1 && fclose(f1) == EOF && err == NULL)
3121 err = got_error_from_errno("fclose");
3122 if (f2 && fclose(f2) == EOF && err == NULL)
3123 err = got_error_from_errno("fclose");
3124 return err;
3127 static const struct got_error *
3128 diff_trees(struct got_object_id *tree_id1, struct got_object_id *tree_id2,
3129 const char *path, int diff_context, int ignore_whitespace,
3130 int force_text_diff, struct got_diffstat_cb_arg *dsa,
3131 struct got_repository *repo, FILE *outfile)
3133 const struct got_error *err = NULL;
3134 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
3135 struct got_diff_blob_output_unidiff_arg arg;
3136 FILE *f1 = NULL, *f2 = NULL;
3137 int fd1 = -1, fd2 = -1;
3139 if (tree_id1) {
3140 err = got_object_open_as_tree(&tree1, repo, tree_id1);
3141 if (err)
3142 goto done;
3143 fd1 = got_opentempfd();
3144 if (fd1 == -1) {
3145 err = got_error_from_errno("got_opentempfd");
3146 goto done;
3150 err = got_object_open_as_tree(&tree2, repo, tree_id2);
3151 if (err)
3152 goto done;
3154 f1 = got_opentemp();
3155 if (f1 == NULL) {
3156 err = got_error_from_errno("got_opentemp");
3157 goto done;
3160 f2 = got_opentemp();
3161 if (f2 == NULL) {
3162 err = got_error_from_errno("got_opentemp");
3163 goto done;
3165 fd2 = got_opentempfd();
3166 if (fd2 == -1) {
3167 err = got_error_from_errno("got_opentempfd");
3168 goto done;
3170 arg.diff_context = diff_context;
3171 arg.ignore_whitespace = ignore_whitespace;
3172 arg.force_text_diff = force_text_diff;
3173 arg.diffstat = dsa;
3174 arg.diff_algo = GOT_DIFF_ALGORITHM_PATIENCE;
3175 arg.outfile = outfile;
3176 arg.lines = NULL;
3177 arg.nlines = 0;
3178 while (path[0] == '/')
3179 path++;
3180 err = got_diff_tree(tree1, tree2, f1, f2, fd1, fd2, path, path, repo,
3181 got_diff_blob_output_unidiff, &arg, 1);
3182 done:
3183 if (tree1)
3184 got_object_tree_close(tree1);
3185 if (tree2)
3186 got_object_tree_close(tree2);
3187 if (f1 && fclose(f1) == EOF && err == NULL)
3188 err = got_error_from_errno("fclose");
3189 if (f2 && fclose(f2) == EOF && err == NULL)
3190 err = got_error_from_errno("fclose");
3191 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
3192 err = got_error_from_errno("close");
3193 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
3194 err = got_error_from_errno("close");
3195 return err;
3198 static const struct got_error *
3199 get_changed_paths(struct got_pathlist_head *paths,
3200 struct got_commit_object *commit, struct got_repository *repo,
3201 struct got_diffstat_cb_arg *dsa)
3203 const struct got_error *err = NULL;
3204 struct got_object_id *tree_id1 = NULL, *tree_id2 = NULL;
3205 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
3206 struct got_object_qid *qid;
3207 got_diff_blob_cb cb = got_diff_tree_collect_changed_paths;
3208 FILE *f1 = NULL, *f2 = NULL;
3209 int fd1 = -1, fd2 = -1;
3211 if (dsa) {
3212 cb = got_diff_tree_compute_diffstat;
3214 f1 = got_opentemp();
3215 if (f1 == NULL) {
3216 err = got_error_from_errno("got_opentemp");
3217 goto done;
3219 f2 = got_opentemp();
3220 if (f2 == NULL) {
3221 err = got_error_from_errno("got_opentemp");
3222 goto done;
3224 fd1 = got_opentempfd();
3225 if (fd1 == -1) {
3226 err = got_error_from_errno("got_opentempfd");
3227 goto done;
3229 fd2 = got_opentempfd();
3230 if (fd2 == -1) {
3231 err = got_error_from_errno("got_opentempfd");
3232 goto done;
3236 qid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
3237 if (qid != NULL) {
3238 struct got_commit_object *pcommit;
3239 err = got_object_open_as_commit(&pcommit, repo,
3240 &qid->id);
3241 if (err)
3242 return err;
3244 tree_id1 = got_object_id_dup(
3245 got_object_commit_get_tree_id(pcommit));
3246 if (tree_id1 == NULL) {
3247 got_object_commit_close(pcommit);
3248 return got_error_from_errno("got_object_id_dup");
3250 got_object_commit_close(pcommit);
3254 if (tree_id1) {
3255 err = got_object_open_as_tree(&tree1, repo, tree_id1);
3256 if (err)
3257 goto done;
3260 tree_id2 = got_object_commit_get_tree_id(commit);
3261 err = got_object_open_as_tree(&tree2, repo, tree_id2);
3262 if (err)
3263 goto done;
3265 err = got_diff_tree(tree1, tree2, f1, f2, fd1, fd2, "", "", repo,
3266 cb, dsa ? (void *)dsa : paths, dsa ? 1 : 0);
3267 done:
3268 if (tree1)
3269 got_object_tree_close(tree1);
3270 if (tree2)
3271 got_object_tree_close(tree2);
3272 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
3273 err = got_error_from_errno("close");
3274 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
3275 err = got_error_from_errno("close");
3276 if (f1 && fclose(f1) == EOF && err == NULL)
3277 err = got_error_from_errno("fclose");
3278 if (f2 && fclose(f2) == EOF && err == NULL)
3279 err = got_error_from_errno("fclose");
3280 free(tree_id1);
3281 return err;
3284 static const struct got_error *
3285 print_patch(struct got_commit_object *commit, struct got_object_id *id,
3286 const char *path, int diff_context, struct got_diffstat_cb_arg *dsa,
3287 struct got_repository *repo, FILE *outfile)
3289 const struct got_error *err = NULL;
3290 struct got_commit_object *pcommit = NULL;
3291 char *id_str1 = NULL, *id_str2 = NULL;
3292 struct got_object_id *obj_id1 = NULL, *obj_id2 = NULL;
3293 struct got_object_qid *qid;
3295 qid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
3296 if (qid != NULL) {
3297 err = got_object_open_as_commit(&pcommit, repo,
3298 &qid->id);
3299 if (err)
3300 return err;
3301 err = got_object_id_str(&id_str1, &qid->id);
3302 if (err)
3303 goto done;
3306 err = got_object_id_str(&id_str2, id);
3307 if (err)
3308 goto done;
3310 if (path && path[0] != '\0') {
3311 int obj_type;
3312 err = got_object_id_by_path(&obj_id2, repo, commit, path);
3313 if (err)
3314 goto done;
3315 if (pcommit) {
3316 err = got_object_id_by_path(&obj_id1, repo,
3317 pcommit, path);
3318 if (err) {
3319 if (err->code != GOT_ERR_NO_TREE_ENTRY) {
3320 free(obj_id2);
3321 goto done;
3325 err = got_object_get_type(&obj_type, repo, obj_id2);
3326 if (err) {
3327 free(obj_id2);
3328 goto done;
3330 fprintf(outfile,
3331 "diff %s %s\n", id_str1 ? id_str1 : "/dev/null", id_str2);
3332 fprintf(outfile, "commit - %s\n",
3333 id_str1 ? id_str1 : "/dev/null");
3334 fprintf(outfile, "commit + %s\n", id_str2);
3335 switch (obj_type) {
3336 case GOT_OBJ_TYPE_BLOB:
3337 err = diff_blobs(obj_id1, obj_id2, path, diff_context,
3338 0, 0, dsa, repo, outfile);
3339 break;
3340 case GOT_OBJ_TYPE_TREE:
3341 err = diff_trees(obj_id1, obj_id2, path, diff_context,
3342 0, 0, dsa, repo, outfile);
3343 break;
3344 default:
3345 err = got_error(GOT_ERR_OBJ_TYPE);
3346 break;
3348 free(obj_id1);
3349 free(obj_id2);
3350 } else {
3351 obj_id2 = got_object_commit_get_tree_id(commit);
3352 if (pcommit)
3353 obj_id1 = got_object_commit_get_tree_id(pcommit);
3354 fprintf(outfile,
3355 "diff %s %s\n", id_str1 ? id_str1 : "/dev/null", id_str2);
3356 fprintf(outfile, "commit - %s\n",
3357 id_str1 ? id_str1 : "/dev/null");
3358 fprintf(outfile, "commit + %s\n", id_str2);
3359 err = diff_trees(obj_id1, obj_id2, "", diff_context, 0, 0,
3360 dsa, repo, outfile);
3362 done:
3363 free(id_str1);
3364 free(id_str2);
3365 if (pcommit)
3366 got_object_commit_close(pcommit);
3367 return err;
3370 static char *
3371 get_datestr(time_t *time, char *datebuf)
3373 struct tm mytm, *tm;
3374 char *p, *s;
3376 tm = gmtime_r(time, &mytm);
3377 if (tm == NULL)
3378 return NULL;
3379 s = asctime_r(tm, datebuf);
3380 if (s == NULL)
3381 return NULL;
3382 p = strchr(s, '\n');
3383 if (p)
3384 *p = '\0';
3385 return s;
3388 static const struct got_error *
3389 match_commit(int *have_match, struct got_object_id *id,
3390 struct got_commit_object *commit, regex_t *regex)
3392 const struct got_error *err = NULL;
3393 regmatch_t regmatch;
3394 char *id_str = NULL, *logmsg = NULL;
3396 *have_match = 0;
3398 err = got_object_id_str(&id_str, id);
3399 if (err)
3400 return err;
3402 err = got_object_commit_get_logmsg(&logmsg, commit);
3403 if (err)
3404 goto done;
3406 if (regexec(regex, got_object_commit_get_author(commit), 1,
3407 &regmatch, 0) == 0 ||
3408 regexec(regex, got_object_commit_get_committer(commit), 1,
3409 &regmatch, 0) == 0 ||
3410 regexec(regex, id_str, 1, &regmatch, 0) == 0 ||
3411 regexec(regex, logmsg, 1, &regmatch, 0) == 0)
3412 *have_match = 1;
3413 done:
3414 free(id_str);
3415 free(logmsg);
3416 return err;
3419 static void
3420 match_changed_paths(int *have_match, struct got_pathlist_head *changed_paths,
3421 regex_t *regex)
3423 regmatch_t regmatch;
3424 struct got_pathlist_entry *pe;
3426 *have_match = 0;
3428 RB_FOREACH(pe, got_pathlist_head, changed_paths) {
3429 if (regexec(regex, pe->path, 1, &regmatch, 0) == 0) {
3430 *have_match = 1;
3431 break;
3436 static const struct got_error *
3437 match_patch(int *have_match, struct got_commit_object *commit,
3438 struct got_object_id *id, const char *path, int diff_context,
3439 struct got_repository *repo, regex_t *regex, FILE *f)
3441 const struct got_error *err = NULL;
3442 char *line = NULL;
3443 size_t linesize = 0;
3444 regmatch_t regmatch;
3446 *have_match = 0;
3448 err = got_opentemp_truncate(f);
3449 if (err)
3450 return err;
3452 err = print_patch(commit, id, path, diff_context, NULL, repo, f);
3453 if (err)
3454 goto done;
3456 if (fseeko(f, 0L, SEEK_SET) == -1) {
3457 err = got_error_from_errno("fseeko");
3458 goto done;
3461 while (getline(&line, &linesize, f) != -1) {
3462 if (regexec(regex, line, 1, &regmatch, 0) == 0) {
3463 *have_match = 1;
3464 break;
3467 done:
3468 free(line);
3469 return err;
3472 #define GOT_COMMIT_SEP_STR "-----------------------------------------------\n"
3474 static const struct got_error*
3475 build_refs_str(char **refs_str, struct got_reflist_head *refs,
3476 struct got_object_id *id, struct got_repository *repo,
3477 int local_only)
3479 static const struct got_error *err = NULL;
3480 struct got_reflist_entry *re;
3481 char *s;
3482 const char *name;
3484 *refs_str = NULL;
3486 TAILQ_FOREACH(re, refs, entry) {
3487 struct got_tag_object *tag = NULL;
3488 struct got_object_id *ref_id;
3489 int cmp;
3491 name = got_ref_get_name(re->ref);
3492 if (strcmp(name, GOT_REF_HEAD) == 0)
3493 continue;
3494 if (strncmp(name, "refs/", 5) == 0)
3495 name += 5;
3496 if (strncmp(name, "got/", 4) == 0)
3497 continue;
3498 if (strncmp(name, "heads/", 6) == 0)
3499 name += 6;
3500 if (strncmp(name, "remotes/", 8) == 0) {
3501 if (local_only)
3502 continue;
3503 name += 8;
3504 s = strstr(name, "/" GOT_REF_HEAD);
3505 if (s != NULL && strcmp(s, "/" GOT_REF_HEAD) == 0)
3506 continue;
3508 err = got_ref_resolve(&ref_id, repo, re->ref);
3509 if (err)
3510 break;
3511 if (strncmp(name, "tags/", 5) == 0) {
3512 err = got_object_open_as_tag(&tag, repo, ref_id);
3513 if (err) {
3514 if (err->code != GOT_ERR_OBJ_TYPE) {
3515 free(ref_id);
3516 break;
3518 /* Ref points at something other than a tag. */
3519 err = NULL;
3520 tag = NULL;
3523 cmp = got_object_id_cmp(tag ?
3524 got_object_tag_get_object_id(tag) : ref_id, id);
3525 free(ref_id);
3526 if (tag)
3527 got_object_tag_close(tag);
3528 if (cmp != 0)
3529 continue;
3530 s = *refs_str;
3531 if (asprintf(refs_str, "%s%s%s", s ? s : "",
3532 s ? ", " : "", name) == -1) {
3533 err = got_error_from_errno("asprintf");
3534 free(s);
3535 *refs_str = NULL;
3536 break;
3538 free(s);
3541 return err;
3544 static const struct got_error *
3545 print_commit_oneline(struct got_commit_object *commit, struct got_object_id *id,
3546 struct got_repository *repo, struct got_reflist_object_id_map *refs_idmap)
3548 const struct got_error *err = NULL;
3549 char *ref_str = NULL, *id_str = NULL, *logmsg0 = NULL;
3550 char *comma, *s, *nl;
3551 struct got_reflist_head *refs;
3552 char datebuf[12]; /* YYYY-MM-DD + SPACE + NUL */
3553 struct tm tm;
3554 time_t committer_time;
3556 refs = got_reflist_object_id_map_lookup(refs_idmap, id);
3557 if (refs) {
3558 err = build_refs_str(&ref_str, refs, id, repo, 1);
3559 if (err)
3560 return err;
3562 /* Display the first matching ref only. */
3563 if (ref_str && (comma = strchr(ref_str, ',')) != NULL)
3564 *comma = '\0';
3567 if (ref_str == NULL) {
3568 err = got_object_id_str(&id_str, id);
3569 if (err)
3570 return err;
3573 committer_time = got_object_commit_get_committer_time(commit);
3574 if (gmtime_r(&committer_time, &tm) == NULL) {
3575 err = got_error_from_errno("gmtime_r");
3576 goto done;
3578 if (strftime(datebuf, sizeof(datebuf), "%F ", &tm) == 0) {
3579 err = got_error(GOT_ERR_NO_SPACE);
3580 goto done;
3583 err = got_object_commit_get_logmsg(&logmsg0, commit);
3584 if (err)
3585 goto done;
3587 s = logmsg0;
3588 while (isspace((unsigned char)s[0]))
3589 s++;
3591 nl = strchr(s, '\n');
3592 if (nl) {
3593 *nl = '\0';
3596 if (ref_str)
3597 printf("%s%-7s %s\n", datebuf, ref_str, s);
3598 else
3599 printf("%s%.7s %s\n", datebuf, id_str, s);
3601 if (fflush(stdout) != 0 && err == NULL)
3602 err = got_error_from_errno("fflush");
3603 done:
3604 free(id_str);
3605 free(ref_str);
3606 free(logmsg0);
3607 return err;
3610 static const struct got_error *
3611 print_diffstat(struct got_diffstat_cb_arg *dsa, const char *header)
3613 struct got_pathlist_entry *pe;
3615 if (header != NULL)
3616 printf("%s\n", header);
3618 RB_FOREACH(pe, got_pathlist_head, dsa->paths) {
3619 struct got_diff_changed_path *cp = pe->data;
3620 int pad = dsa->max_path_len - pe->path_len + 1;
3622 printf(" %c %s%*c | %*d+ %*d-\n", cp->status, pe->path, pad,
3623 ' ', dsa->add_cols + 1, cp->add, dsa->rm_cols + 1, cp->rm);
3625 printf("\n%d file%s changed, %d insertion%s(+), %d deletion%s(-)\n\n",
3626 dsa->nfiles, dsa->nfiles > 1 ? "s" : "", dsa->ins,
3627 dsa->ins != 1 ? "s" : "", dsa->del, dsa->del != 1 ? "s" : "");
3629 if (fflush(stdout) != 0)
3630 return got_error_from_errno("fflush");
3632 return NULL;
3635 static const struct got_error *
3636 printfile(FILE *f)
3638 char buf[8192];
3639 size_t r;
3641 if (fseeko(f, 0L, SEEK_SET) == -1)
3642 return got_error_from_errno("fseek");
3644 for (;;) {
3645 r = fread(buf, 1, sizeof(buf), f);
3646 if (r == 0) {
3647 if (ferror(f))
3648 return got_error_from_errno("fread");
3649 if (feof(f))
3650 break;
3652 if (fwrite(buf, 1, r, stdout) != r)
3653 return got_ferror(stdout, GOT_ERR_IO);
3656 return NULL;
3659 static const struct got_error *
3660 print_commit(struct got_commit_object *commit, struct got_object_id *id,
3661 struct got_repository *repo, const char *path,
3662 struct got_pathlist_head *changed_paths,
3663 struct got_diffstat_cb_arg *diffstat, int show_patch, int diff_context,
3664 struct got_reflist_object_id_map *refs_idmap, const char *custom_refs_str,
3665 const char *prefix)
3667 const struct got_error *err = NULL;
3668 FILE *f = NULL;
3669 char *id_str, *datestr, *logmsg0, *logmsg, *line;
3670 char datebuf[26];
3671 time_t committer_time;
3672 const char *author, *committer;
3673 char *refs_str = NULL;
3675 err = got_object_id_str(&id_str, id);
3676 if (err)
3677 return err;
3679 if (custom_refs_str == NULL) {
3680 struct got_reflist_head *refs;
3681 refs = got_reflist_object_id_map_lookup(refs_idmap, id);
3682 if (refs) {
3683 err = build_refs_str(&refs_str, refs, id, repo, 0);
3684 if (err)
3685 goto done;
3689 printf(GOT_COMMIT_SEP_STR);
3690 if (custom_refs_str)
3691 printf("%s %s (%s)\n", prefix ? prefix : "commit", id_str,
3692 custom_refs_str);
3693 else
3694 printf("%s %s%s%s%s\n", prefix ? prefix : "commit", id_str,
3695 refs_str ? " (" : "", refs_str ? refs_str : "",
3696 refs_str ? ")" : "");
3697 free(id_str);
3698 id_str = NULL;
3699 free(refs_str);
3700 refs_str = NULL;
3701 printf("from: %s\n", got_object_commit_get_author(commit));
3702 author = got_object_commit_get_author(commit);
3703 committer = got_object_commit_get_committer(commit);
3704 if (strcmp(author, committer) != 0)
3705 printf("via: %s\n", committer);
3706 committer_time = got_object_commit_get_committer_time(commit);
3707 datestr = get_datestr(&committer_time, datebuf);
3708 if (datestr)
3709 printf("date: %s UTC\n", datestr);
3710 if (got_object_commit_get_nparents(commit) > 1) {
3711 const struct got_object_id_queue *parent_ids;
3712 struct got_object_qid *qid;
3713 int n = 1;
3714 parent_ids = got_object_commit_get_parent_ids(commit);
3715 STAILQ_FOREACH(qid, parent_ids, entry) {
3716 err = got_object_id_str(&id_str, &qid->id);
3717 if (err)
3718 goto done;
3719 printf("parent %d: %s\n", n++, id_str);
3720 free(id_str);
3721 id_str = NULL;
3725 err = got_object_commit_get_logmsg(&logmsg0, commit);
3726 if (err)
3727 goto done;
3729 logmsg = logmsg0;
3730 do {
3731 line = strsep(&logmsg, "\n");
3732 if (line)
3733 printf(" %s\n", line);
3734 } while (line);
3735 free(logmsg0);
3737 if (changed_paths && diffstat == NULL) {
3738 struct got_pathlist_entry *pe;
3740 RB_FOREACH(pe, got_pathlist_head, changed_paths) {
3741 struct got_diff_changed_path *cp = pe->data;
3743 printf(" %c %s\n", cp->status, pe->path);
3745 printf("\n");
3747 if (show_patch) {
3748 if (diffstat) {
3749 f = got_opentemp();
3750 if (f == NULL) {
3751 err = got_error_from_errno("got_opentemp");
3752 goto done;
3756 err = print_patch(commit, id, path, diff_context, diffstat,
3757 repo, diffstat == NULL ? stdout : f);
3758 if (err)
3759 goto done;
3761 if (diffstat) {
3762 err = print_diffstat(diffstat, NULL);
3763 if (err)
3764 goto done;
3765 if (show_patch) {
3766 err = printfile(f);
3767 if (err)
3768 goto done;
3771 if (show_patch)
3772 printf("\n");
3774 if (fflush(stdout) != 0 && err == NULL)
3775 err = got_error_from_errno("fflush");
3776 done:
3777 if (f && fclose(f) == EOF && err == NULL)
3778 err = got_error_from_errno("fclose");
3779 free(id_str);
3780 free(refs_str);
3781 return err;
3784 static const struct got_error *
3785 print_commits(struct got_object_id *root_id, struct got_object_id *end_id,
3786 struct got_repository *repo, const char *path, int show_changed_paths,
3787 int show_diffstat, int show_patch, const char *search_pattern,
3788 int diff_context, int limit, int log_branches, int reverse_display_order,
3789 struct got_reflist_object_id_map *refs_idmap, int one_line,
3790 FILE *tmpfile)
3792 const struct got_error *err;
3793 struct got_commit_graph *graph;
3794 regex_t regex;
3795 int have_match;
3796 struct got_object_id_queue reversed_commits;
3797 struct got_object_qid *qid;
3798 struct got_commit_object *commit;
3799 struct got_pathlist_head changed_paths;
3801 STAILQ_INIT(&reversed_commits);
3802 RB_INIT(&changed_paths);
3804 if (search_pattern && regcomp(&regex, search_pattern,
3805 REG_EXTENDED | REG_NOSUB | REG_NEWLINE))
3806 return got_error_msg(GOT_ERR_REGEX, search_pattern);
3808 err = got_commit_graph_open(&graph, path, !log_branches);
3809 if (err)
3810 return err;
3811 err = got_commit_graph_bfsort(graph, root_id, repo,
3812 check_cancelled, NULL);
3813 if (err)
3814 goto done;
3815 for (;;) {
3816 struct got_object_id id;
3817 struct got_diffstat_cb_arg dsa = { 0, 0, 0, 0, 0, 0,
3818 &changed_paths, 0, 0, GOT_DIFF_ALGORITHM_PATIENCE };
3820 if (sigint_received || sigpipe_received)
3821 break;
3823 err = got_commit_graph_iter_next(&id, graph, repo,
3824 check_cancelled, NULL);
3825 if (err) {
3826 if (err->code == GOT_ERR_ITER_COMPLETED)
3827 err = NULL;
3828 break;
3831 err = got_object_open_as_commit(&commit, repo, &id);
3832 if (err)
3833 break;
3835 if ((show_changed_paths || (show_diffstat && !show_patch))
3836 && !reverse_display_order) {
3837 err = get_changed_paths(&changed_paths, commit, repo,
3838 show_diffstat ? &dsa : NULL);
3839 if (err)
3840 break;
3843 if (search_pattern) {
3844 err = match_commit(&have_match, &id, commit, &regex);
3845 if (err) {
3846 got_object_commit_close(commit);
3847 break;
3849 if (have_match == 0 && show_changed_paths)
3850 match_changed_paths(&have_match,
3851 &changed_paths, &regex);
3852 if (have_match == 0 && show_patch) {
3853 err = match_patch(&have_match, commit, &id,
3854 path, diff_context, repo, &regex, tmpfile);
3855 if (err)
3856 break;
3858 if (have_match == 0) {
3859 got_object_commit_close(commit);
3860 got_pathlist_free(&changed_paths,
3861 GOT_PATHLIST_FREE_ALL);
3862 continue;
3866 if (reverse_display_order) {
3867 err = got_object_qid_alloc(&qid, &id);
3868 if (err)
3869 break;
3870 STAILQ_INSERT_HEAD(&reversed_commits, qid, entry);
3871 got_object_commit_close(commit);
3872 } else {
3873 if (one_line)
3874 err = print_commit_oneline(commit, &id,
3875 repo, refs_idmap);
3876 else
3877 err = print_commit(commit, &id, repo, path,
3878 (show_changed_paths || show_diffstat) ?
3879 &changed_paths : NULL,
3880 show_diffstat ? &dsa : NULL, show_patch,
3881 diff_context, refs_idmap, NULL, NULL);
3882 got_object_commit_close(commit);
3883 if (err)
3884 break;
3886 if ((limit && --limit == 0) ||
3887 (end_id && got_object_id_cmp(&id, end_id) == 0))
3888 break;
3890 got_pathlist_free(&changed_paths, GOT_PATHLIST_FREE_ALL);
3892 if (reverse_display_order) {
3893 STAILQ_FOREACH(qid, &reversed_commits, entry) {
3894 struct got_diffstat_cb_arg dsa = { 0, 0, 0, 0, 0, 0,
3895 &changed_paths, 0, 0, GOT_DIFF_ALGORITHM_PATIENCE };
3897 err = got_object_open_as_commit(&commit, repo,
3898 &qid->id);
3899 if (err)
3900 break;
3901 if (show_changed_paths ||
3902 (show_diffstat && !show_patch)) {
3903 err = get_changed_paths(&changed_paths, commit,
3904 repo, show_diffstat ? &dsa : NULL);
3905 if (err)
3906 break;
3908 if (one_line)
3909 err = print_commit_oneline(commit, &qid->id,
3910 repo, refs_idmap);
3911 else
3912 err = print_commit(commit, &qid->id, repo, path,
3913 (show_changed_paths || show_diffstat) ?
3914 &changed_paths : NULL,
3915 show_diffstat ? &dsa : NULL, show_patch,
3916 diff_context, refs_idmap, NULL, NULL);
3917 got_object_commit_close(commit);
3918 if (err)
3919 break;
3920 got_pathlist_free(&changed_paths, GOT_PATHLIST_FREE_ALL);
3923 done:
3924 got_object_id_queue_free(&reversed_commits);
3925 got_pathlist_free(&changed_paths, GOT_PATHLIST_FREE_ALL);
3926 if (search_pattern)
3927 regfree(&regex);
3928 got_commit_graph_close(graph);
3929 return err;
3932 __dead static void
3933 usage_log(void)
3935 fprintf(stderr, "usage: %s log [-bdPpRs] [-C number] [-c commit] "
3936 "[-l N] [-r repository-path] [-S search-pattern] [-x commit] "
3937 "[path]\n", getprogname());
3938 exit(1);
3941 static int
3942 get_default_log_limit(void)
3944 const char *got_default_log_limit;
3945 long long n;
3946 const char *errstr;
3948 got_default_log_limit = getenv("GOT_LOG_DEFAULT_LIMIT");
3949 if (got_default_log_limit == NULL)
3950 return 0;
3951 n = strtonum(got_default_log_limit, 0, INT_MAX, &errstr);
3952 if (errstr != NULL)
3953 return 0;
3954 return n;
3957 static const struct got_error *
3958 cmd_log(int argc, char *argv[])
3960 const struct got_error *error;
3961 struct got_repository *repo = NULL;
3962 struct got_worktree *worktree = NULL;
3963 struct got_object_id *start_id = NULL, *end_id = NULL;
3964 char *repo_path = NULL, *path = NULL, *cwd = NULL, *in_repo_path = NULL;
3965 const char *start_commit = NULL, *end_commit = NULL;
3966 const char *search_pattern = NULL;
3967 int diff_context = -1, ch;
3968 int show_changed_paths = 0, show_patch = 0, limit = 0, log_branches = 0;
3969 int show_diffstat = 0, reverse_display_order = 0, one_line = 0;
3970 const char *errstr;
3971 struct got_reflist_head refs;
3972 struct got_reflist_object_id_map *refs_idmap = NULL;
3973 FILE *tmpfile = NULL;
3974 int *pack_fds = NULL;
3976 TAILQ_INIT(&refs);
3978 #ifndef PROFILE
3979 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
3980 NULL)
3981 == -1)
3982 err(1, "pledge");
3983 #endif
3985 limit = get_default_log_limit();
3987 while ((ch = getopt(argc, argv, "bC:c:dl:PpRr:S:sx:")) != -1) {
3988 switch (ch) {
3989 case 'b':
3990 log_branches = 1;
3991 break;
3992 case 'C':
3993 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
3994 &errstr);
3995 if (errstr != NULL)
3996 errx(1, "number of context lines is %s: %s",
3997 errstr, optarg);
3998 break;
3999 case 'c':
4000 start_commit = optarg;
4001 break;
4002 case 'd':
4003 show_diffstat = 1;
4004 break;
4005 case 'l':
4006 limit = strtonum(optarg, 0, INT_MAX, &errstr);
4007 if (errstr != NULL)
4008 errx(1, "number of commits is %s: %s",
4009 errstr, optarg);
4010 break;
4011 case 'P':
4012 show_changed_paths = 1;
4013 break;
4014 case 'p':
4015 show_patch = 1;
4016 break;
4017 case 'R':
4018 reverse_display_order = 1;
4019 break;
4020 case 'r':
4021 repo_path = realpath(optarg, NULL);
4022 if (repo_path == NULL)
4023 return got_error_from_errno2("realpath",
4024 optarg);
4025 got_path_strip_trailing_slashes(repo_path);
4026 break;
4027 case 'S':
4028 search_pattern = optarg;
4029 break;
4030 case 's':
4031 one_line = 1;
4032 break;
4033 case 'x':
4034 end_commit = optarg;
4035 break;
4036 default:
4037 usage_log();
4038 /* NOTREACHED */
4042 argc -= optind;
4043 argv += optind;
4045 if (diff_context == -1)
4046 diff_context = 3;
4047 else if (!show_patch)
4048 errx(1, "-C requires -p");
4050 if (one_line && (show_patch || show_changed_paths || show_diffstat))
4051 errx(1, "cannot use -s with -d, -p or -P");
4053 cwd = getcwd(NULL, 0);
4054 if (cwd == NULL) {
4055 error = got_error_from_errno("getcwd");
4056 goto done;
4059 error = got_repo_pack_fds_open(&pack_fds);
4060 if (error != NULL)
4061 goto done;
4063 if (repo_path == NULL) {
4064 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_CVG_DIR);
4065 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4066 goto done;
4067 error = NULL;
4070 if (argc == 1) {
4071 if (worktree) {
4072 error = got_worktree_resolve_path(&path, worktree,
4073 argv[0]);
4074 if (error)
4075 goto done;
4076 } else {
4077 path = strdup(argv[0]);
4078 if (path == NULL) {
4079 error = got_error_from_errno("strdup");
4080 goto done;
4083 } else if (argc != 0)
4084 usage_log();
4086 if (repo_path == NULL) {
4087 repo_path = worktree ?
4088 strdup(got_worktree_get_repo_path(worktree)) : strdup(cwd);
4090 if (repo_path == NULL) {
4091 error = got_error_from_errno("strdup");
4092 goto done;
4095 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
4096 if (error != NULL)
4097 goto done;
4099 error = apply_unveil(got_repo_get_path(repo), 1,
4100 worktree ? got_worktree_get_root_path(worktree) : NULL);
4101 if (error)
4102 goto done;
4104 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
4105 if (error)
4106 goto done;
4108 error = got_reflist_object_id_map_create(&refs_idmap, &refs, repo);
4109 if (error)
4110 goto done;
4112 if (start_commit == NULL) {
4113 struct got_reference *head_ref;
4114 struct got_commit_object *commit = NULL;
4115 error = got_ref_open(&head_ref, repo,
4116 worktree ? got_worktree_get_head_ref_name(worktree)
4117 : GOT_REF_HEAD, 0);
4118 if (error != NULL)
4119 goto done;
4120 error = got_ref_resolve(&start_id, repo, head_ref);
4121 got_ref_close(head_ref);
4122 if (error != NULL)
4123 goto done;
4124 error = got_object_open_as_commit(&commit, repo,
4125 start_id);
4126 if (error != NULL)
4127 goto done;
4128 got_object_commit_close(commit);
4129 } else {
4130 error = got_repo_match_object_id(&start_id, NULL,
4131 start_commit, GOT_OBJ_TYPE_COMMIT, &refs, repo);
4132 if (error != NULL)
4133 goto done;
4135 if (end_commit != NULL) {
4136 error = got_repo_match_object_id(&end_id, NULL,
4137 end_commit, GOT_OBJ_TYPE_COMMIT, &refs, repo);
4138 if (error != NULL)
4139 goto done;
4142 if (worktree) {
4144 * If a path was specified on the command line it was resolved
4145 * to a path in the work tree above. Prepend the work tree's
4146 * path prefix to obtain the corresponding in-repository path.
4148 if (path) {
4149 const char *prefix;
4150 prefix = got_worktree_get_path_prefix(worktree);
4151 if (asprintf(&in_repo_path, "%s%s%s", prefix,
4152 (path[0] != '\0') ? "/" : "", path) == -1) {
4153 error = got_error_from_errno("asprintf");
4154 goto done;
4157 } else
4158 error = got_repo_map_path(&in_repo_path, repo,
4159 path ? path : "");
4160 if (error != NULL)
4161 goto done;
4162 if (in_repo_path) {
4163 free(path);
4164 path = in_repo_path;
4167 if (worktree) {
4168 /* Release work tree lock. */
4169 got_worktree_close(worktree);
4170 worktree = NULL;
4173 if (search_pattern && show_patch) {
4174 tmpfile = got_opentemp();
4175 if (tmpfile == NULL) {
4176 error = got_error_from_errno("got_opentemp");
4177 goto done;
4181 error = print_commits(start_id, end_id, repo, path ? path : "",
4182 show_changed_paths, show_diffstat, show_patch, search_pattern,
4183 diff_context, limit, log_branches, reverse_display_order,
4184 refs_idmap, one_line, tmpfile);
4185 done:
4186 free(path);
4187 free(repo_path);
4188 free(cwd);
4189 free(start_id);
4190 free(end_id);
4191 if (worktree)
4192 got_worktree_close(worktree);
4193 if (repo) {
4194 const struct got_error *close_err = got_repo_close(repo);
4195 if (error == NULL)
4196 error = close_err;
4198 if (pack_fds) {
4199 const struct got_error *pack_err =
4200 got_repo_pack_fds_close(pack_fds);
4201 if (error == NULL)
4202 error = pack_err;
4204 if (refs_idmap)
4205 got_reflist_object_id_map_free(refs_idmap);
4206 if (tmpfile && fclose(tmpfile) == EOF && error == NULL)
4207 error = got_error_from_errno("fclose");
4208 got_ref_list_free(&refs);
4209 return error;
4212 __dead static void
4213 usage_diff(void)
4215 fprintf(stderr, "usage: %s diff [-adPsw] [-C number] [-c commit] "
4216 "[-r repository-path] [object1 object2 | path ...]\n",
4217 getprogname());
4218 exit(1);
4221 struct print_diff_arg {
4222 struct got_repository *repo;
4223 struct got_worktree *worktree;
4224 struct got_diffstat_cb_arg *diffstat;
4225 int diff_context;
4226 const char *id_str;
4227 int header_shown;
4228 int diff_staged;
4229 enum got_diff_algorithm diff_algo;
4230 int ignore_whitespace;
4231 int force_text_diff;
4232 FILE *f1;
4233 FILE *f2;
4234 FILE *outfile;
4238 * Create a file which contains the target path of a symlink so we can feed
4239 * it as content to the diff engine.
4241 static const struct got_error *
4242 get_symlink_target_file(int *fd, int dirfd, const char *de_name,
4243 const char *abspath)
4245 const struct got_error *err = NULL;
4246 char target_path[PATH_MAX];
4247 ssize_t target_len, outlen;
4249 *fd = -1;
4251 if (dirfd != -1) {
4252 target_len = readlinkat(dirfd, de_name, target_path, PATH_MAX);
4253 if (target_len == -1)
4254 return got_error_from_errno2("readlinkat", abspath);
4255 } else {
4256 target_len = readlink(abspath, target_path, PATH_MAX);
4257 if (target_len == -1)
4258 return got_error_from_errno2("readlink", abspath);
4261 *fd = got_opentempfd();
4262 if (*fd == -1)
4263 return got_error_from_errno("got_opentempfd");
4265 outlen = write(*fd, target_path, target_len);
4266 if (outlen == -1) {
4267 err = got_error_from_errno("got_opentempfd");
4268 goto done;
4271 if (lseek(*fd, 0, SEEK_SET) == -1) {
4272 err = got_error_from_errno2("lseek", abspath);
4273 goto done;
4275 done:
4276 if (err) {
4277 close(*fd);
4278 *fd = -1;
4280 return err;
4283 static const struct got_error *
4284 print_diff(void *arg, unsigned char status, unsigned char staged_status,
4285 const char *path, struct got_object_id *blob_id,
4286 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
4287 int dirfd, const char *de_name)
4289 struct print_diff_arg *a = arg;
4290 const struct got_error *err = NULL;
4291 struct got_blob_object *blob1 = NULL;
4292 int fd = -1, fd1 = -1, fd2 = -1;
4293 FILE *f2 = NULL;
4294 char *abspath = NULL, *label1 = NULL;
4295 struct stat sb;
4296 off_t size1 = 0;
4297 int f2_exists = 0;
4299 memset(&sb, 0, sizeof(sb));
4301 if (a->diff_staged) {
4302 if (staged_status != GOT_STATUS_MODIFY &&
4303 staged_status != GOT_STATUS_ADD &&
4304 staged_status != GOT_STATUS_DELETE)
4305 return NULL;
4306 } else {
4307 if (staged_status == GOT_STATUS_DELETE)
4308 return NULL;
4309 if (status == GOT_STATUS_NONEXISTENT)
4310 return got_error_set_errno(ENOENT, path);
4311 if (status != GOT_STATUS_MODIFY &&
4312 status != GOT_STATUS_ADD &&
4313 status != GOT_STATUS_DELETE &&
4314 status != GOT_STATUS_CONFLICT)
4315 return NULL;
4318 err = got_opentemp_truncate(a->f1);
4319 if (err)
4320 return got_error_from_errno("got_opentemp_truncate");
4321 err = got_opentemp_truncate(a->f2);
4322 if (err)
4323 return got_error_from_errno("got_opentemp_truncate");
4325 if (!a->header_shown) {
4326 if (fprintf(a->outfile, "diff %s%s\n",
4327 a->diff_staged ? "-s " : "",
4328 got_worktree_get_root_path(a->worktree)) < 0) {
4329 err = got_error_from_errno("fprintf");
4330 goto done;
4332 if (fprintf(a->outfile, "commit - %s\n", a->id_str) < 0) {
4333 err = got_error_from_errno("fprintf");
4334 goto done;
4336 if (fprintf(a->outfile, "path + %s%s\n",
4337 got_worktree_get_root_path(a->worktree),
4338 a->diff_staged ? " (staged changes)" : "") < 0) {
4339 err = got_error_from_errno("fprintf");
4340 goto done;
4342 a->header_shown = 1;
4345 if (a->diff_staged) {
4346 const char *label1 = NULL, *label2 = NULL;
4347 switch (staged_status) {
4348 case GOT_STATUS_MODIFY:
4349 label1 = path;
4350 label2 = path;
4351 break;
4352 case GOT_STATUS_ADD:
4353 label2 = path;
4354 break;
4355 case GOT_STATUS_DELETE:
4356 label1 = path;
4357 break;
4358 default:
4359 return got_error(GOT_ERR_FILE_STATUS);
4361 fd1 = got_opentempfd();
4362 if (fd1 == -1) {
4363 err = got_error_from_errno("got_opentempfd");
4364 goto done;
4366 fd2 = got_opentempfd();
4367 if (fd2 == -1) {
4368 err = got_error_from_errno("got_opentempfd");
4369 goto done;
4371 err = got_diff_objects_as_blobs(NULL, NULL, a->f1, a->f2,
4372 fd1, fd2, blob_id, staged_blob_id, label1, label2,
4373 a->diff_algo, a->diff_context, a->ignore_whitespace,
4374 a->force_text_diff, a->diffstat, a->repo, a->outfile);
4375 goto done;
4378 fd1 = got_opentempfd();
4379 if (fd1 == -1) {
4380 err = got_error_from_errno("got_opentempfd");
4381 goto done;
4384 if (staged_status == GOT_STATUS_ADD ||
4385 staged_status == GOT_STATUS_MODIFY) {
4386 char *id_str;
4387 err = got_object_open_as_blob(&blob1, a->repo, staged_blob_id,
4388 8192, fd1);
4389 if (err)
4390 goto done;
4391 err = got_object_id_str(&id_str, staged_blob_id);
4392 if (err)
4393 goto done;
4394 if (asprintf(&label1, "%s (staged)", id_str) == -1) {
4395 err = got_error_from_errno("asprintf");
4396 free(id_str);
4397 goto done;
4399 free(id_str);
4400 } else if (status != GOT_STATUS_ADD) {
4401 err = got_object_open_as_blob(&blob1, a->repo, blob_id, 8192,
4402 fd1);
4403 if (err)
4404 goto done;
4407 if (status != GOT_STATUS_DELETE) {
4408 if (asprintf(&abspath, "%s/%s",
4409 got_worktree_get_root_path(a->worktree), path) == -1) {
4410 err = got_error_from_errno("asprintf");
4411 goto done;
4414 if (dirfd != -1) {
4415 fd = openat(dirfd, de_name,
4416 O_RDONLY | O_NOFOLLOW | O_CLOEXEC);
4417 if (fd == -1) {
4418 if (!got_err_open_nofollow_on_symlink()) {
4419 err = got_error_from_errno2("openat",
4420 abspath);
4421 goto done;
4423 err = get_symlink_target_file(&fd, dirfd,
4424 de_name, abspath);
4425 if (err)
4426 goto done;
4428 } else {
4429 fd = open(abspath, O_RDONLY | O_NOFOLLOW | O_CLOEXEC);
4430 if (fd == -1) {
4431 if (!got_err_open_nofollow_on_symlink()) {
4432 err = got_error_from_errno2("open",
4433 abspath);
4434 goto done;
4436 err = get_symlink_target_file(&fd, dirfd,
4437 de_name, abspath);
4438 if (err)
4439 goto done;
4442 if (fstatat(fd, abspath, &sb, AT_SYMLINK_NOFOLLOW) == -1) {
4443 err = got_error_from_errno2("fstatat", abspath);
4444 goto done;
4446 f2 = fdopen(fd, "r");
4447 if (f2 == NULL) {
4448 err = got_error_from_errno2("fdopen", abspath);
4449 goto done;
4451 fd = -1;
4452 f2_exists = 1;
4455 if (blob1) {
4456 err = got_object_blob_dump_to_file(&size1, NULL, NULL,
4457 a->f1, blob1);
4458 if (err)
4459 goto done;
4462 err = got_diff_blob_file(NULL, NULL, blob1, a->f1, size1, label1,
4463 f2 ? f2 : a->f2, f2_exists, &sb, path, GOT_DIFF_ALGORITHM_PATIENCE,
4464 a->diff_context, a->ignore_whitespace, a->force_text_diff,
4465 a->diffstat, a->outfile);
4466 done:
4467 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
4468 err = got_error_from_errno("close");
4469 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
4470 err = got_error_from_errno("close");
4471 if (blob1)
4472 got_object_blob_close(blob1);
4473 if (fd != -1 && close(fd) == -1 && err == NULL)
4474 err = got_error_from_errno("close");
4475 if (f2 && fclose(f2) == EOF && err == NULL)
4476 err = got_error_from_errno("fclose");
4477 free(abspath);
4478 return err;
4481 static const struct got_error *
4482 cmd_diff(int argc, char *argv[])
4484 const struct got_error *error;
4485 struct got_repository *repo = NULL;
4486 struct got_worktree *worktree = NULL;
4487 char *cwd = NULL, *repo_path = NULL;
4488 const char *commit_args[2] = { NULL, NULL };
4489 int ncommit_args = 0;
4490 struct got_object_id *ids[2] = { NULL, NULL };
4491 char *labels[2] = { NULL, NULL };
4492 int type1 = GOT_OBJ_TYPE_ANY, type2 = GOT_OBJ_TYPE_ANY;
4493 int diff_context = 3, diff_staged = 0, ignore_whitespace = 0, ch, i;
4494 int force_text_diff = 0, force_path = 0, rflag = 0, show_diffstat = 0;
4495 const char *errstr;
4496 struct got_reflist_head refs;
4497 struct got_pathlist_head diffstat_paths, paths;
4498 FILE *f1 = NULL, *f2 = NULL, *outfile = NULL;
4499 int fd1 = -1, fd2 = -1;
4500 int *pack_fds = NULL;
4501 struct got_diffstat_cb_arg dsa;
4503 memset(&dsa, 0, sizeof(dsa));
4505 TAILQ_INIT(&refs);
4506 RB_INIT(&paths);
4507 RB_INIT(&diffstat_paths);
4509 #ifndef PROFILE
4510 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
4511 NULL) == -1)
4512 err(1, "pledge");
4513 #endif
4515 while ((ch = getopt(argc, argv, "aC:c:dPr:sw")) != -1) {
4516 switch (ch) {
4517 case 'a':
4518 force_text_diff = 1;
4519 break;
4520 case 'C':
4521 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
4522 &errstr);
4523 if (errstr != NULL)
4524 errx(1, "number of context lines is %s: %s",
4525 errstr, optarg);
4526 break;
4527 case 'c':
4528 if (ncommit_args >= 2)
4529 errx(1, "too many -c options used");
4530 commit_args[ncommit_args++] = optarg;
4531 break;
4532 case 'd':
4533 show_diffstat = 1;
4534 break;
4535 case 'P':
4536 force_path = 1;
4537 break;
4538 case 'r':
4539 repo_path = realpath(optarg, NULL);
4540 if (repo_path == NULL)
4541 return got_error_from_errno2("realpath",
4542 optarg);
4543 got_path_strip_trailing_slashes(repo_path);
4544 rflag = 1;
4545 break;
4546 case 's':
4547 diff_staged = 1;
4548 break;
4549 case 'w':
4550 ignore_whitespace = 1;
4551 break;
4552 default:
4553 usage_diff();
4554 /* NOTREACHED */
4558 argc -= optind;
4559 argv += optind;
4561 cwd = getcwd(NULL, 0);
4562 if (cwd == NULL) {
4563 error = got_error_from_errno("getcwd");
4564 goto done;
4567 error = got_repo_pack_fds_open(&pack_fds);
4568 if (error != NULL)
4569 goto done;
4571 if (repo_path == NULL) {
4572 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_CVG_DIR);
4573 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4574 goto done;
4575 else
4576 error = NULL;
4577 if (worktree) {
4578 repo_path =
4579 strdup(got_worktree_get_repo_path(worktree));
4580 if (repo_path == NULL) {
4581 error = got_error_from_errno("strdup");
4582 goto done;
4584 } else {
4585 repo_path = strdup(cwd);
4586 if (repo_path == NULL) {
4587 error = got_error_from_errno("strdup");
4588 goto done;
4593 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
4594 free(repo_path);
4595 if (error != NULL)
4596 goto done;
4598 if (show_diffstat) {
4599 dsa.paths = &diffstat_paths;
4600 dsa.force_text = force_text_diff;
4601 dsa.ignore_ws = ignore_whitespace;
4602 dsa.diff_algo = GOT_DIFF_ALGORITHM_PATIENCE;
4605 if (rflag || worktree == NULL || ncommit_args > 0) {
4606 if (force_path) {
4607 error = got_error_msg(GOT_ERR_NOT_IMPL,
4608 "-P option can only be used when diffing "
4609 "a work tree");
4610 goto done;
4612 if (diff_staged) {
4613 error = got_error_msg(GOT_ERR_NOT_IMPL,
4614 "-s option can only be used when diffing "
4615 "a work tree");
4616 goto done;
4620 error = apply_unveil(got_repo_get_path(repo), 1,
4621 worktree ? got_worktree_get_root_path(worktree) : NULL);
4622 if (error)
4623 goto done;
4625 if ((!force_path && argc == 2) || ncommit_args > 0) {
4626 int obj_type = (ncommit_args > 0 ?
4627 GOT_OBJ_TYPE_COMMIT : GOT_OBJ_TYPE_ANY);
4628 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
4629 NULL);
4630 if (error)
4631 goto done;
4632 for (i = 0; i < (ncommit_args > 0 ? ncommit_args : argc); i++) {
4633 const char *arg;
4634 if (ncommit_args > 0)
4635 arg = commit_args[i];
4636 else
4637 arg = argv[i];
4638 error = got_repo_match_object_id(&ids[i], &labels[i],
4639 arg, obj_type, &refs, repo);
4640 if (error) {
4641 if (error->code != GOT_ERR_NOT_REF &&
4642 error->code != GOT_ERR_NO_OBJ)
4643 goto done;
4644 if (ncommit_args > 0)
4645 goto done;
4646 error = NULL;
4647 break;
4652 f1 = got_opentemp();
4653 if (f1 == NULL) {
4654 error = got_error_from_errno("got_opentemp");
4655 goto done;
4658 f2 = got_opentemp();
4659 if (f2 == NULL) {
4660 error = got_error_from_errno("got_opentemp");
4661 goto done;
4664 outfile = got_opentemp();
4665 if (outfile == NULL) {
4666 error = got_error_from_errno("got_opentemp");
4667 goto done;
4670 if (ncommit_args == 0 && (ids[0] == NULL || ids[1] == NULL)) {
4671 struct print_diff_arg arg;
4672 char *id_str;
4674 if (worktree == NULL) {
4675 if (argc == 2 && ids[0] == NULL) {
4676 error = got_error_path(argv[0], GOT_ERR_NO_OBJ);
4677 goto done;
4678 } else if (argc == 2 && ids[1] == NULL) {
4679 error = got_error_path(argv[1], GOT_ERR_NO_OBJ);
4680 goto done;
4681 } else if (argc > 0) {
4682 error = got_error_fmt(GOT_ERR_NOT_WORKTREE,
4683 "%s", "specified paths cannot be resolved");
4684 goto done;
4685 } else {
4686 error = got_error(GOT_ERR_NOT_WORKTREE);
4687 goto done;
4691 error = get_worktree_paths_from_argv(&paths, argc, argv,
4692 worktree);
4693 if (error)
4694 goto done;
4696 error = got_object_id_str(&id_str,
4697 got_worktree_get_base_commit_id(worktree));
4698 if (error)
4699 goto done;
4700 arg.repo = repo;
4701 arg.worktree = worktree;
4702 arg.diff_algo = GOT_DIFF_ALGORITHM_PATIENCE;
4703 arg.diff_context = diff_context;
4704 arg.id_str = id_str;
4705 arg.header_shown = 0;
4706 arg.diff_staged = diff_staged;
4707 arg.ignore_whitespace = ignore_whitespace;
4708 arg.force_text_diff = force_text_diff;
4709 arg.diffstat = show_diffstat ? &dsa : NULL;
4710 arg.f1 = f1;
4711 arg.f2 = f2;
4712 arg.outfile = outfile;
4714 error = got_worktree_status(worktree, &paths, repo, 0,
4715 print_diff, &arg, check_cancelled, NULL);
4716 free(id_str);
4717 if (error)
4718 goto done;
4720 if (show_diffstat && dsa.nfiles > 0) {
4721 char *header;
4723 if (asprintf(&header, "diffstat %s%s",
4724 diff_staged ? "-s " : "",
4725 got_worktree_get_root_path(worktree)) == -1) {
4726 error = got_error_from_errno("asprintf");
4727 goto done;
4730 error = print_diffstat(&dsa, header);
4731 free(header);
4732 if (error)
4733 goto done;
4736 error = printfile(outfile);
4737 goto done;
4740 if (ncommit_args == 1) {
4741 struct got_commit_object *commit;
4742 error = got_object_open_as_commit(&commit, repo, ids[0]);
4743 if (error)
4744 goto done;
4746 labels[1] = labels[0];
4747 ids[1] = ids[0];
4748 if (got_object_commit_get_nparents(commit) > 0) {
4749 const struct got_object_id_queue *pids;
4750 struct got_object_qid *pid;
4751 pids = got_object_commit_get_parent_ids(commit);
4752 pid = STAILQ_FIRST(pids);
4753 ids[0] = got_object_id_dup(&pid->id);
4754 if (ids[0] == NULL) {
4755 error = got_error_from_errno(
4756 "got_object_id_dup");
4757 got_object_commit_close(commit);
4758 goto done;
4760 error = got_object_id_str(&labels[0], ids[0]);
4761 if (error) {
4762 got_object_commit_close(commit);
4763 goto done;
4765 } else {
4766 ids[0] = NULL;
4767 labels[0] = strdup("/dev/null");
4768 if (labels[0] == NULL) {
4769 error = got_error_from_errno("strdup");
4770 got_object_commit_close(commit);
4771 goto done;
4775 got_object_commit_close(commit);
4778 if (ncommit_args == 0 && argc > 2) {
4779 error = got_error_msg(GOT_ERR_BAD_PATH,
4780 "path arguments cannot be used when diffing two objects");
4781 goto done;
4784 if (ids[0]) {
4785 error = got_object_get_type(&type1, repo, ids[0]);
4786 if (error)
4787 goto done;
4790 error = got_object_get_type(&type2, repo, ids[1]);
4791 if (error)
4792 goto done;
4793 if (type1 != GOT_OBJ_TYPE_ANY && type1 != type2) {
4794 error = got_error(GOT_ERR_OBJ_TYPE);
4795 goto done;
4797 if (type1 == GOT_OBJ_TYPE_BLOB && argc > 2) {
4798 error = got_error_msg(GOT_ERR_OBJ_TYPE,
4799 "path arguments cannot be used when diffing blobs");
4800 goto done;
4803 for (i = 0; ncommit_args > 0 && i < argc; i++) {
4804 char *in_repo_path;
4805 struct got_pathlist_entry *new;
4806 if (worktree) {
4807 const char *prefix;
4808 char *p;
4809 error = got_worktree_resolve_path(&p, worktree,
4810 argv[i]);
4811 if (error)
4812 goto done;
4813 prefix = got_worktree_get_path_prefix(worktree);
4814 while (prefix[0] == '/')
4815 prefix++;
4816 if (asprintf(&in_repo_path, "%s%s%s", prefix,
4817 (p[0] != '\0' && prefix[0] != '\0') ? "/" : "",
4818 p) == -1) {
4819 error = got_error_from_errno("asprintf");
4820 free(p);
4821 goto done;
4823 free(p);
4824 } else {
4825 char *mapped_path, *s;
4826 error = got_repo_map_path(&mapped_path, repo, argv[i]);
4827 if (error)
4828 goto done;
4829 s = mapped_path;
4830 while (s[0] == '/')
4831 s++;
4832 in_repo_path = strdup(s);
4833 if (in_repo_path == NULL) {
4834 error = got_error_from_errno("asprintf");
4835 free(mapped_path);
4836 goto done;
4838 free(mapped_path);
4841 error = got_pathlist_insert(&new, &paths, in_repo_path, NULL);
4842 if (error || new == NULL /* duplicate */)
4843 free(in_repo_path);
4844 if (error)
4845 goto done;
4848 if (worktree) {
4849 /* Release work tree lock. */
4850 got_worktree_close(worktree);
4851 worktree = NULL;
4854 fd1 = got_opentempfd();
4855 if (fd1 == -1) {
4856 error = got_error_from_errno("got_opentempfd");
4857 goto done;
4860 fd2 = got_opentempfd();
4861 if (fd2 == -1) {
4862 error = got_error_from_errno("got_opentempfd");
4863 goto done;
4866 switch (type1 == GOT_OBJ_TYPE_ANY ? type2 : type1) {
4867 case GOT_OBJ_TYPE_BLOB:
4868 error = got_diff_objects_as_blobs(NULL, NULL, f1, f2,
4869 fd1, fd2, ids[0], ids[1], NULL, NULL,
4870 GOT_DIFF_ALGORITHM_PATIENCE, diff_context,
4871 ignore_whitespace, force_text_diff,
4872 show_diffstat ? &dsa : NULL, repo, outfile);
4873 break;
4874 case GOT_OBJ_TYPE_TREE:
4875 error = got_diff_objects_as_trees(NULL, NULL, f1, f2, fd1, fd2,
4876 ids[0], ids[1], &paths, "", "",
4877 GOT_DIFF_ALGORITHM_PATIENCE, diff_context,
4878 ignore_whitespace, force_text_diff,
4879 show_diffstat ? &dsa : NULL, repo, outfile);
4880 break;
4881 case GOT_OBJ_TYPE_COMMIT:
4882 fprintf(outfile, "diff %s %s\n", labels[0], labels[1]);
4883 error = got_diff_objects_as_commits(NULL, NULL, f1, f2,
4884 fd1, fd2, ids[0], ids[1], &paths,
4885 GOT_DIFF_ALGORITHM_PATIENCE, diff_context,
4886 ignore_whitespace, force_text_diff,
4887 show_diffstat ? &dsa : NULL, repo, outfile);
4888 break;
4889 default:
4890 error = got_error(GOT_ERR_OBJ_TYPE);
4892 if (error)
4893 goto done;
4895 if (show_diffstat && dsa.nfiles > 0) {
4896 char *header = NULL;
4898 if (asprintf(&header, "diffstat %s %s",
4899 labels[0], labels[1]) == -1) {
4900 error = got_error_from_errno("asprintf");
4901 goto done;
4904 error = print_diffstat(&dsa, header);
4905 free(header);
4906 if (error)
4907 goto done;
4910 error = printfile(outfile);
4912 done:
4913 free(labels[0]);
4914 free(labels[1]);
4915 free(ids[0]);
4916 free(ids[1]);
4917 if (worktree)
4918 got_worktree_close(worktree);
4919 if (repo) {
4920 const struct got_error *close_err = got_repo_close(repo);
4921 if (error == NULL)
4922 error = close_err;
4924 if (pack_fds) {
4925 const struct got_error *pack_err =
4926 got_repo_pack_fds_close(pack_fds);
4927 if (error == NULL)
4928 error = pack_err;
4930 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
4931 got_pathlist_free(&diffstat_paths, GOT_PATHLIST_FREE_ALL);
4932 got_ref_list_free(&refs);
4933 if (outfile && fclose(outfile) == EOF && error == NULL)
4934 error = got_error_from_errno("fclose");
4935 if (f1 && fclose(f1) == EOF && error == NULL)
4936 error = got_error_from_errno("fclose");
4937 if (f2 && fclose(f2) == EOF && error == NULL)
4938 error = got_error_from_errno("fclose");
4939 if (fd1 != -1 && close(fd1) == -1 && error == NULL)
4940 error = got_error_from_errno("close");
4941 if (fd2 != -1 && close(fd2) == -1 && error == NULL)
4942 error = got_error_from_errno("close");
4943 return error;
4946 __dead static void
4947 usage_blame(void)
4949 fprintf(stderr,
4950 "usage: %s blame [-c commit] [-r repository-path] path\n",
4951 getprogname());
4952 exit(1);
4955 struct blame_line {
4956 int annotated;
4957 char *id_str;
4958 char *committer;
4959 char datebuf[11]; /* YYYY-MM-DD + NUL */
4962 struct blame_cb_args {
4963 struct blame_line *lines;
4964 int nlines;
4965 int nlines_prec;
4966 int lineno_cur;
4967 off_t *line_offsets;
4968 FILE *f;
4969 struct got_repository *repo;
4972 static const struct got_error *
4973 blame_cb(void *arg, int nlines, int lineno,
4974 struct got_commit_object *commit, struct got_object_id *id)
4976 const struct got_error *err = NULL;
4977 struct blame_cb_args *a = arg;
4978 struct blame_line *bline;
4979 char *line = NULL;
4980 size_t linesize = 0;
4981 off_t offset;
4982 struct tm tm;
4983 time_t committer_time;
4985 if (nlines != a->nlines ||
4986 (lineno != -1 && lineno < 1) || lineno > a->nlines)
4987 return got_error(GOT_ERR_RANGE);
4989 if (sigint_received)
4990 return got_error(GOT_ERR_ITER_COMPLETED);
4992 if (lineno == -1)
4993 return NULL; /* no change in this commit */
4995 /* Annotate this line. */
4996 bline = &a->lines[lineno - 1];
4997 if (bline->annotated)
4998 return NULL;
4999 err = got_object_id_str(&bline->id_str, id);
5000 if (err)
5001 return err;
5003 bline->committer = strdup(got_object_commit_get_committer(commit));
5004 if (bline->committer == NULL) {
5005 err = got_error_from_errno("strdup");
5006 goto done;
5009 committer_time = got_object_commit_get_committer_time(commit);
5010 if (gmtime_r(&committer_time, &tm) == NULL)
5011 return got_error_from_errno("gmtime_r");
5012 if (strftime(bline->datebuf, sizeof(bline->datebuf), "%F", &tm) == 0) {
5013 err = got_error(GOT_ERR_NO_SPACE);
5014 goto done;
5016 bline->annotated = 1;
5018 /* Print lines annotated so far. */
5019 bline = &a->lines[a->lineno_cur - 1];
5020 if (!bline->annotated)
5021 goto done;
5023 offset = a->line_offsets[a->lineno_cur - 1];
5024 if (fseeko(a->f, offset, SEEK_SET) == -1) {
5025 err = got_error_from_errno("fseeko");
5026 goto done;
5029 while (a->lineno_cur <= a->nlines && bline->annotated) {
5030 char *smallerthan, *at, *nl, *committer;
5031 size_t len;
5033 if (getline(&line, &linesize, a->f) == -1) {
5034 if (ferror(a->f))
5035 err = got_error_from_errno("getline");
5036 break;
5039 committer = bline->committer;
5040 smallerthan = strchr(committer, '<');
5041 if (smallerthan && smallerthan[1] != '\0')
5042 committer = smallerthan + 1;
5043 at = strchr(committer, '@');
5044 if (at)
5045 *at = '\0';
5046 len = strlen(committer);
5047 if (len >= 9)
5048 committer[8] = '\0';
5050 nl = strchr(line, '\n');
5051 if (nl)
5052 *nl = '\0';
5053 printf("%.*d) %.8s %s %-8s %s\n", a->nlines_prec, a->lineno_cur,
5054 bline->id_str, bline->datebuf, committer, line);
5056 a->lineno_cur++;
5057 bline = &a->lines[a->lineno_cur - 1];
5059 done:
5060 free(line);
5061 return err;
5064 static const struct got_error *
5065 cmd_blame(int argc, char *argv[])
5067 const struct got_error *error;
5068 struct got_repository *repo = NULL;
5069 struct got_worktree *worktree = NULL;
5070 char *path, *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
5071 char *link_target = NULL;
5072 struct got_object_id *obj_id = NULL;
5073 struct got_object_id *commit_id = NULL;
5074 struct got_commit_object *commit = NULL;
5075 struct got_blob_object *blob = NULL;
5076 char *commit_id_str = NULL;
5077 struct blame_cb_args bca;
5078 int ch, obj_type, i, fd1 = -1, fd2 = -1, fd3 = -1;
5079 off_t filesize;
5080 int *pack_fds = NULL;
5081 FILE *f1 = NULL, *f2 = NULL;
5083 fd1 = got_opentempfd();
5084 if (fd1 == -1)
5085 return got_error_from_errno("got_opentempfd");
5087 memset(&bca, 0, sizeof(bca));
5089 #ifndef PROFILE
5090 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
5091 NULL) == -1)
5092 err(1, "pledge");
5093 #endif
5095 while ((ch = getopt(argc, argv, "c:r:")) != -1) {
5096 switch (ch) {
5097 case 'c':
5098 commit_id_str = optarg;
5099 break;
5100 case 'r':
5101 repo_path = realpath(optarg, NULL);
5102 if (repo_path == NULL)
5103 return got_error_from_errno2("realpath",
5104 optarg);
5105 got_path_strip_trailing_slashes(repo_path);
5106 break;
5107 default:
5108 usage_blame();
5109 /* NOTREACHED */
5113 argc -= optind;
5114 argv += optind;
5116 if (argc == 1)
5117 path = argv[0];
5118 else
5119 usage_blame();
5121 cwd = getcwd(NULL, 0);
5122 if (cwd == NULL) {
5123 error = got_error_from_errno("getcwd");
5124 goto done;
5127 error = got_repo_pack_fds_open(&pack_fds);
5128 if (error != NULL)
5129 goto done;
5131 if (repo_path == NULL) {
5132 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_CVG_DIR);
5133 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5134 goto done;
5135 else
5136 error = NULL;
5137 if (worktree) {
5138 repo_path =
5139 strdup(got_worktree_get_repo_path(worktree));
5140 if (repo_path == NULL) {
5141 error = got_error_from_errno("strdup");
5142 if (error)
5143 goto done;
5145 } else {
5146 repo_path = strdup(cwd);
5147 if (repo_path == NULL) {
5148 error = got_error_from_errno("strdup");
5149 goto done;
5154 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
5155 if (error != NULL)
5156 goto done;
5158 if (worktree) {
5159 const char *prefix = got_worktree_get_path_prefix(worktree);
5160 char *p;
5162 error = got_worktree_resolve_path(&p, worktree, path);
5163 if (error)
5164 goto done;
5165 if (asprintf(&in_repo_path, "%s%s%s", prefix,
5166 (p[0] != '\0' && !got_path_is_root_dir(prefix)) ? "/" : "",
5167 p) == -1) {
5168 error = got_error_from_errno("asprintf");
5169 free(p);
5170 goto done;
5172 free(p);
5173 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5174 } else {
5175 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5176 if (error)
5177 goto done;
5178 error = got_repo_map_path(&in_repo_path, repo, path);
5180 if (error)
5181 goto done;
5183 if (commit_id_str == NULL) {
5184 struct got_reference *head_ref;
5185 error = got_ref_open(&head_ref, repo, worktree ?
5186 got_worktree_get_head_ref_name(worktree) : GOT_REF_HEAD, 0);
5187 if (error != NULL)
5188 goto done;
5189 error = got_ref_resolve(&commit_id, repo, head_ref);
5190 got_ref_close(head_ref);
5191 if (error != NULL)
5192 goto done;
5193 } else {
5194 struct got_reflist_head refs;
5195 TAILQ_INIT(&refs);
5196 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
5197 NULL);
5198 if (error)
5199 goto done;
5200 error = got_repo_match_object_id(&commit_id, NULL,
5201 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
5202 got_ref_list_free(&refs);
5203 if (error)
5204 goto done;
5207 if (worktree) {
5208 /* Release work tree lock. */
5209 got_worktree_close(worktree);
5210 worktree = NULL;
5213 error = got_object_open_as_commit(&commit, repo, commit_id);
5214 if (error)
5215 goto done;
5217 error = got_object_resolve_symlinks(&link_target, in_repo_path,
5218 commit, repo);
5219 if (error)
5220 goto done;
5222 error = got_object_id_by_path(&obj_id, repo, commit,
5223 link_target ? link_target : in_repo_path);
5224 if (error)
5225 goto done;
5227 error = got_object_get_type(&obj_type, repo, obj_id);
5228 if (error)
5229 goto done;
5231 if (obj_type != GOT_OBJ_TYPE_BLOB) {
5232 error = got_error_path(link_target ? link_target : in_repo_path,
5233 GOT_ERR_OBJ_TYPE);
5234 goto done;
5237 error = got_object_open_as_blob(&blob, repo, obj_id, 8192, fd1);
5238 if (error)
5239 goto done;
5240 bca.f = got_opentemp();
5241 if (bca.f == NULL) {
5242 error = got_error_from_errno("got_opentemp");
5243 goto done;
5245 error = got_object_blob_dump_to_file(&filesize, &bca.nlines,
5246 &bca.line_offsets, bca.f, blob);
5247 if (error || bca.nlines == 0)
5248 goto done;
5250 /* Don't include \n at EOF in the blame line count. */
5251 if (bca.line_offsets[bca.nlines - 1] == filesize)
5252 bca.nlines--;
5254 bca.lines = calloc(bca.nlines, sizeof(*bca.lines));
5255 if (bca.lines == NULL) {
5256 error = got_error_from_errno("calloc");
5257 goto done;
5259 bca.lineno_cur = 1;
5260 bca.nlines_prec = 0;
5261 i = bca.nlines;
5262 while (i > 0) {
5263 i /= 10;
5264 bca.nlines_prec++;
5266 bca.repo = repo;
5268 fd2 = got_opentempfd();
5269 if (fd2 == -1) {
5270 error = got_error_from_errno("got_opentempfd");
5271 goto done;
5273 fd3 = got_opentempfd();
5274 if (fd3 == -1) {
5275 error = got_error_from_errno("got_opentempfd");
5276 goto done;
5278 f1 = got_opentemp();
5279 if (f1 == NULL) {
5280 error = got_error_from_errno("got_opentemp");
5281 goto done;
5283 f2 = got_opentemp();
5284 if (f2 == NULL) {
5285 error = got_error_from_errno("got_opentemp");
5286 goto done;
5288 error = got_blame(link_target ? link_target : in_repo_path, commit_id,
5289 repo, GOT_DIFF_ALGORITHM_PATIENCE, blame_cb, &bca,
5290 check_cancelled, NULL, fd2, fd3, f1, f2);
5291 done:
5292 free(in_repo_path);
5293 free(link_target);
5294 free(repo_path);
5295 free(cwd);
5296 free(commit_id);
5297 free(obj_id);
5298 if (commit)
5299 got_object_commit_close(commit);
5301 if (fd1 != -1 && close(fd1) == -1 && error == NULL)
5302 error = got_error_from_errno("close");
5303 if (fd2 != -1 && close(fd2) == -1 && error == NULL)
5304 error = got_error_from_errno("close");
5305 if (fd3 != -1 && close(fd3) == -1 && error == NULL)
5306 error = got_error_from_errno("close");
5307 if (f1 && fclose(f1) == EOF && error == NULL)
5308 error = got_error_from_errno("fclose");
5309 if (f2 && fclose(f2) == EOF && error == NULL)
5310 error = got_error_from_errno("fclose");
5312 if (blob)
5313 got_object_blob_close(blob);
5314 if (worktree)
5315 got_worktree_close(worktree);
5316 if (repo) {
5317 const struct got_error *close_err = got_repo_close(repo);
5318 if (error == NULL)
5319 error = close_err;
5321 if (pack_fds) {
5322 const struct got_error *pack_err =
5323 got_repo_pack_fds_close(pack_fds);
5324 if (error == NULL)
5325 error = pack_err;
5327 if (bca.lines) {
5328 for (i = 0; i < bca.nlines; i++) {
5329 struct blame_line *bline = &bca.lines[i];
5330 free(bline->id_str);
5331 free(bline->committer);
5333 free(bca.lines);
5335 free(bca.line_offsets);
5336 if (bca.f && fclose(bca.f) == EOF && error == NULL)
5337 error = got_error_from_errno("fclose");
5338 return error;
5341 __dead static void
5342 usage_tree(void)
5344 fprintf(stderr, "usage: %s tree [-iR] [-c commit] [-r repository-path] "
5345 "[path]\n", getprogname());
5346 exit(1);
5349 static const struct got_error *
5350 print_entry(struct got_tree_entry *te, const char *id, const char *path,
5351 const char *root_path, struct got_repository *repo)
5353 const struct got_error *err = NULL;
5354 int is_root_path = (strcmp(path, root_path) == 0);
5355 const char *modestr = "";
5356 mode_t mode = got_tree_entry_get_mode(te);
5357 char *link_target = NULL;
5359 path += strlen(root_path);
5360 while (path[0] == '/')
5361 path++;
5363 if (got_object_tree_entry_is_submodule(te))
5364 modestr = "$";
5365 else if (S_ISLNK(mode)) {
5366 int i;
5368 err = got_tree_entry_get_symlink_target(&link_target, te, repo);
5369 if (err)
5370 return err;
5371 for (i = 0; link_target[i] != '\0'; i++) {
5372 if (!isprint((unsigned char)link_target[i]))
5373 link_target[i] = '?';
5376 modestr = "@";
5378 else if (S_ISDIR(mode))
5379 modestr = "/";
5380 else if (mode & S_IXUSR)
5381 modestr = "*";
5383 printf("%s%s%s%s%s%s%s\n", id ? id : "", path,
5384 is_root_path ? "" : "/", got_tree_entry_get_name(te), modestr,
5385 link_target ? " -> ": "", link_target ? link_target : "");
5387 free(link_target);
5388 return NULL;
5391 static const struct got_error *
5392 print_tree(const char *path, struct got_commit_object *commit,
5393 int show_ids, int recurse, const char *root_path,
5394 struct got_repository *repo)
5396 const struct got_error *err = NULL;
5397 struct got_object_id *tree_id = NULL;
5398 struct got_tree_object *tree = NULL;
5399 int nentries, i;
5401 err = got_object_id_by_path(&tree_id, repo, commit, path);
5402 if (err)
5403 goto done;
5405 err = got_object_open_as_tree(&tree, repo, tree_id);
5406 if (err)
5407 goto done;
5408 nentries = got_object_tree_get_nentries(tree);
5409 for (i = 0; i < nentries; i++) {
5410 struct got_tree_entry *te;
5411 char *id = NULL;
5413 if (sigint_received || sigpipe_received)
5414 break;
5416 te = got_object_tree_get_entry(tree, i);
5417 if (show_ids) {
5418 char *id_str;
5419 err = got_object_id_str(&id_str,
5420 got_tree_entry_get_id(te));
5421 if (err)
5422 goto done;
5423 if (asprintf(&id, "%s ", id_str) == -1) {
5424 err = got_error_from_errno("asprintf");
5425 free(id_str);
5426 goto done;
5428 free(id_str);
5430 err = print_entry(te, id, path, root_path, repo);
5431 free(id);
5432 if (err)
5433 goto done;
5435 if (recurse && S_ISDIR(got_tree_entry_get_mode(te))) {
5436 char *child_path;
5437 if (asprintf(&child_path, "%s%s%s", path,
5438 path[0] == '/' && path[1] == '\0' ? "" : "/",
5439 got_tree_entry_get_name(te)) == -1) {
5440 err = got_error_from_errno("asprintf");
5441 goto done;
5443 err = print_tree(child_path, commit, show_ids, 1,
5444 root_path, repo);
5445 free(child_path);
5446 if (err)
5447 goto done;
5450 done:
5451 if (tree)
5452 got_object_tree_close(tree);
5453 free(tree_id);
5454 return err;
5457 static const struct got_error *
5458 cmd_tree(int argc, char *argv[])
5460 const struct got_error *error;
5461 struct got_repository *repo = NULL;
5462 struct got_worktree *worktree = NULL;
5463 const char *path, *refname = NULL;
5464 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
5465 struct got_object_id *commit_id = NULL;
5466 struct got_commit_object *commit = NULL;
5467 char *commit_id_str = NULL;
5468 int show_ids = 0, recurse = 0;
5469 int ch;
5470 int *pack_fds = NULL;
5472 #ifndef PROFILE
5473 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
5474 NULL) == -1)
5475 err(1, "pledge");
5476 #endif
5478 while ((ch = getopt(argc, argv, "c:iRr:")) != -1) {
5479 switch (ch) {
5480 case 'c':
5481 commit_id_str = optarg;
5482 break;
5483 case 'i':
5484 show_ids = 1;
5485 break;
5486 case 'R':
5487 recurse = 1;
5488 break;
5489 case 'r':
5490 repo_path = realpath(optarg, NULL);
5491 if (repo_path == NULL)
5492 return got_error_from_errno2("realpath",
5493 optarg);
5494 got_path_strip_trailing_slashes(repo_path);
5495 break;
5496 default:
5497 usage_tree();
5498 /* NOTREACHED */
5502 argc -= optind;
5503 argv += optind;
5505 if (argc == 1)
5506 path = argv[0];
5507 else if (argc > 1)
5508 usage_tree();
5509 else
5510 path = NULL;
5512 cwd = getcwd(NULL, 0);
5513 if (cwd == NULL) {
5514 error = got_error_from_errno("getcwd");
5515 goto done;
5518 error = got_repo_pack_fds_open(&pack_fds);
5519 if (error != NULL)
5520 goto done;
5522 if (repo_path == NULL) {
5523 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_CVG_DIR);
5524 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5525 goto done;
5526 else
5527 error = NULL;
5528 if (worktree) {
5529 repo_path =
5530 strdup(got_worktree_get_repo_path(worktree));
5531 if (repo_path == NULL)
5532 error = got_error_from_errno("strdup");
5533 if (error)
5534 goto done;
5535 } else {
5536 repo_path = strdup(cwd);
5537 if (repo_path == NULL) {
5538 error = got_error_from_errno("strdup");
5539 goto done;
5544 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
5545 if (error != NULL)
5546 goto done;
5548 if (worktree) {
5549 const char *prefix = got_worktree_get_path_prefix(worktree);
5550 char *p;
5552 if (path == NULL || got_path_is_root_dir(path))
5553 path = "";
5554 error = got_worktree_resolve_path(&p, worktree, path);
5555 if (error)
5556 goto done;
5557 if (asprintf(&in_repo_path, "%s%s%s", prefix,
5558 (p[0] != '\0' && !got_path_is_root_dir(prefix)) ? "/" : "",
5559 p) == -1) {
5560 error = got_error_from_errno("asprintf");
5561 free(p);
5562 goto done;
5564 free(p);
5565 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5566 if (error)
5567 goto done;
5568 } else {
5569 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5570 if (error)
5571 goto done;
5572 if (path == NULL)
5573 path = "/";
5574 error = got_repo_map_path(&in_repo_path, repo, path);
5575 if (error != NULL)
5576 goto done;
5579 if (commit_id_str == NULL) {
5580 struct got_reference *head_ref;
5581 if (worktree)
5582 refname = got_worktree_get_head_ref_name(worktree);
5583 else
5584 refname = GOT_REF_HEAD;
5585 error = got_ref_open(&head_ref, repo, refname, 0);
5586 if (error != NULL)
5587 goto done;
5588 error = got_ref_resolve(&commit_id, repo, head_ref);
5589 got_ref_close(head_ref);
5590 if (error != NULL)
5591 goto done;
5592 } else {
5593 struct got_reflist_head refs;
5594 TAILQ_INIT(&refs);
5595 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
5596 NULL);
5597 if (error)
5598 goto done;
5599 error = got_repo_match_object_id(&commit_id, NULL,
5600 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
5601 got_ref_list_free(&refs);
5602 if (error)
5603 goto done;
5606 if (worktree) {
5607 /* Release work tree lock. */
5608 got_worktree_close(worktree);
5609 worktree = NULL;
5612 error = got_object_open_as_commit(&commit, repo, commit_id);
5613 if (error)
5614 goto done;
5616 error = print_tree(in_repo_path, commit, show_ids, recurse,
5617 in_repo_path, repo);
5618 done:
5619 free(in_repo_path);
5620 free(repo_path);
5621 free(cwd);
5622 free(commit_id);
5623 if (commit)
5624 got_object_commit_close(commit);
5625 if (worktree)
5626 got_worktree_close(worktree);
5627 if (repo) {
5628 const struct got_error *close_err = got_repo_close(repo);
5629 if (error == NULL)
5630 error = close_err;
5632 if (pack_fds) {
5633 const struct got_error *pack_err =
5634 got_repo_pack_fds_close(pack_fds);
5635 if (error == NULL)
5636 error = pack_err;
5638 return error;
5641 __dead static void
5642 usage_status(void)
5644 fprintf(stderr, "usage: %s status [-I] [-S status-codes] "
5645 "[-s status-codes] [path ...]\n", getprogname());
5646 exit(1);
5649 struct got_status_arg {
5650 char *status_codes;
5651 int suppress;
5654 static const struct got_error *
5655 print_status(void *arg, unsigned char status, unsigned char staged_status,
5656 const char *path, struct got_object_id *blob_id,
5657 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
5658 int dirfd, const char *de_name)
5660 struct got_status_arg *st = arg;
5662 if (status == staged_status && (status == GOT_STATUS_DELETE))
5663 status = GOT_STATUS_NO_CHANGE;
5664 if (st != NULL && st->status_codes) {
5665 size_t ncodes = strlen(st->status_codes);
5666 int i, j = 0;
5668 for (i = 0; i < ncodes ; i++) {
5669 if (st->suppress) {
5670 if (status == st->status_codes[i] ||
5671 staged_status == st->status_codes[i]) {
5672 j++;
5673 continue;
5675 } else {
5676 if (status == st->status_codes[i] ||
5677 staged_status == st->status_codes[i])
5678 break;
5682 if (st->suppress && j == 0)
5683 goto print;
5685 if (i == ncodes)
5686 return NULL;
5688 print:
5689 printf("%c%c %s\n", status, staged_status, path);
5690 return NULL;
5693 static const struct got_error *
5694 cmd_status(int argc, char *argv[])
5696 const struct got_error *error = NULL;
5697 struct got_repository *repo = NULL;
5698 struct got_worktree *worktree = NULL;
5699 struct got_status_arg st;
5700 char *cwd = NULL;
5701 struct got_pathlist_head paths;
5702 int ch, i, no_ignores = 0;
5703 int *pack_fds = NULL;
5705 RB_INIT(&paths);
5707 memset(&st, 0, sizeof(st));
5708 st.status_codes = NULL;
5709 st.suppress = 0;
5711 #ifndef PROFILE
5712 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
5713 NULL) == -1)
5714 err(1, "pledge");
5715 #endif
5717 while ((ch = getopt(argc, argv, "IS:s:")) != -1) {
5718 switch (ch) {
5719 case 'I':
5720 no_ignores = 1;
5721 break;
5722 case 'S':
5723 if (st.status_codes != NULL && st.suppress == 0)
5724 option_conflict('S', 's');
5725 st.suppress = 1;
5726 /* fallthrough */
5727 case 's':
5728 for (i = 0; optarg[i] != '\0'; i++) {
5729 switch (optarg[i]) {
5730 case GOT_STATUS_MODIFY:
5731 case GOT_STATUS_ADD:
5732 case GOT_STATUS_DELETE:
5733 case GOT_STATUS_CONFLICT:
5734 case GOT_STATUS_MISSING:
5735 case GOT_STATUS_OBSTRUCTED:
5736 case GOT_STATUS_UNVERSIONED:
5737 case GOT_STATUS_MODE_CHANGE:
5738 case GOT_STATUS_NONEXISTENT:
5739 break;
5740 default:
5741 errx(1, "invalid status code '%c'",
5742 optarg[i]);
5745 if (ch == 's' && st.suppress)
5746 option_conflict('s', 'S');
5747 st.status_codes = optarg;
5748 break;
5749 default:
5750 usage_status();
5751 /* NOTREACHED */
5755 argc -= optind;
5756 argv += optind;
5758 cwd = getcwd(NULL, 0);
5759 if (cwd == NULL) {
5760 error = got_error_from_errno("getcwd");
5761 goto done;
5764 error = got_repo_pack_fds_open(&pack_fds);
5765 if (error != NULL)
5766 goto done;
5768 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_CVG_DIR);
5769 if (error) {
5770 if (error->code == GOT_ERR_NOT_WORKTREE)
5771 error = wrap_not_worktree_error(error, "status", cwd);
5772 goto done;
5775 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
5776 NULL, pack_fds);
5777 if (error != NULL)
5778 goto done;
5780 error = apply_unveil(got_repo_get_path(repo), 1,
5781 got_worktree_get_root_path(worktree));
5782 if (error)
5783 goto done;
5785 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
5786 if (error)
5787 goto done;
5789 error = got_worktree_status(worktree, &paths, repo, no_ignores,
5790 print_status, &st, check_cancelled, NULL);
5791 done:
5792 if (pack_fds) {
5793 const struct got_error *pack_err =
5794 got_repo_pack_fds_close(pack_fds);
5795 if (error == NULL)
5796 error = pack_err;
5798 if (repo) {
5799 const struct got_error *close_err = got_repo_close(repo);
5800 if (error == NULL)
5801 error = close_err;
5804 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
5805 free(cwd);
5806 return error;
5809 __dead static void
5810 usage_tag(void)
5812 fprintf(stderr, "usage: %s tag [-lVv] [-c commit] [-m message] "
5813 "[-r repository-path] [-s signer-id] name\n", getprogname());
5814 exit(1);
5817 #if 0
5818 static const struct got_error *
5819 sort_tags(struct got_reflist_head *sorted, struct got_reflist_head *tags)
5821 const struct got_error *err = NULL;
5822 struct got_reflist_entry *re, *se, *new;
5823 struct got_object_id *re_id, *se_id;
5824 struct got_tag_object *re_tag, *se_tag;
5825 time_t re_time, se_time;
5827 STAILQ_FOREACH(re, tags, entry) {
5828 se = STAILQ_FIRST(sorted);
5829 if (se == NULL) {
5830 err = got_reflist_entry_dup(&new, re);
5831 if (err)
5832 return err;
5833 STAILQ_INSERT_HEAD(sorted, new, entry);
5834 continue;
5835 } else {
5836 err = got_ref_resolve(&re_id, repo, re->ref);
5837 if (err)
5838 break;
5839 err = got_object_open_as_tag(&re_tag, repo, re_id);
5840 free(re_id);
5841 if (err)
5842 break;
5843 re_time = got_object_tag_get_tagger_time(re_tag);
5844 got_object_tag_close(re_tag);
5847 while (se) {
5848 err = got_ref_resolve(&se_id, repo, re->ref);
5849 if (err)
5850 break;
5851 err = got_object_open_as_tag(&se_tag, repo, se_id);
5852 free(se_id);
5853 if (err)
5854 break;
5855 se_time = got_object_tag_get_tagger_time(se_tag);
5856 got_object_tag_close(se_tag);
5858 if (se_time > re_time) {
5859 err = got_reflist_entry_dup(&new, re);
5860 if (err)
5861 return err;
5862 STAILQ_INSERT_AFTER(sorted, se, new, entry);
5863 break;
5865 se = STAILQ_NEXT(se, entry);
5866 continue;
5869 done:
5870 return err;
5872 #endif
5874 static const struct got_error *
5875 get_tag_refname(char **refname, const char *tag_name)
5877 const struct got_error *err;
5879 if (strncmp("refs/tags/", tag_name, 10) == 0) {
5880 *refname = strdup(tag_name);
5881 if (*refname == NULL)
5882 return got_error_from_errno("strdup");
5883 } else if (asprintf(refname, "refs/tags/%s", tag_name) == -1) {
5884 err = got_error_from_errno("asprintf");
5885 *refname = NULL;
5886 return err;
5889 return NULL;
5892 static const struct got_error *
5893 list_tags(struct got_repository *repo, const char *tag_name, int verify_tags,
5894 const char *allowed_signers, const char *revoked_signers, int verbosity)
5896 static const struct got_error *err = NULL;
5897 struct got_reflist_head refs;
5898 struct got_reflist_entry *re;
5899 char *wanted_refname = NULL;
5900 int bad_sigs = 0;
5902 TAILQ_INIT(&refs);
5904 err = got_ref_list(&refs, repo, "refs/tags", got_ref_cmp_tags, repo);
5905 if (err)
5906 return err;
5908 if (tag_name) {
5909 struct got_reference *ref;
5910 err = get_tag_refname(&wanted_refname, tag_name);
5911 if (err)
5912 goto done;
5913 /* Wanted tag reference should exist. */
5914 err = got_ref_open(&ref, repo, wanted_refname, 0);
5915 if (err)
5916 goto done;
5917 got_ref_close(ref);
5920 TAILQ_FOREACH(re, &refs, entry) {
5921 const char *refname;
5922 char *refstr, *tagmsg0, *tagmsg, *line, *id_str, *datestr;
5923 char datebuf[26];
5924 const char *tagger, *ssh_sig = NULL;
5925 char *sig_msg = NULL;
5926 time_t tagger_time;
5927 struct got_object_id *id;
5928 struct got_tag_object *tag;
5929 struct got_commit_object *commit = NULL;
5931 refname = got_ref_get_name(re->ref);
5932 if (strncmp(refname, "refs/tags/", 10) != 0 ||
5933 (wanted_refname && strcmp(refname, wanted_refname) != 0))
5934 continue;
5935 refname += 10;
5936 refstr = got_ref_to_str(re->ref);
5937 if (refstr == NULL) {
5938 err = got_error_from_errno("got_ref_to_str");
5939 break;
5942 err = got_ref_resolve(&id, repo, re->ref);
5943 if (err)
5944 break;
5945 err = got_object_open_as_tag(&tag, repo, id);
5946 if (err) {
5947 if (err->code != GOT_ERR_OBJ_TYPE) {
5948 free(id);
5949 break;
5951 /* "lightweight" tag */
5952 err = got_object_open_as_commit(&commit, repo, id);
5953 if (err) {
5954 free(id);
5955 break;
5957 tagger = got_object_commit_get_committer(commit);
5958 tagger_time =
5959 got_object_commit_get_committer_time(commit);
5960 err = got_object_id_str(&id_str, id);
5961 free(id);
5962 if (err)
5963 break;
5964 } else {
5965 free(id);
5966 tagger = got_object_tag_get_tagger(tag);
5967 tagger_time = got_object_tag_get_tagger_time(tag);
5968 err = got_object_id_str(&id_str,
5969 got_object_tag_get_object_id(tag));
5970 if (err)
5971 break;
5974 if (tag && verify_tags) {
5975 ssh_sig = got_sigs_get_tagmsg_ssh_signature(
5976 got_object_tag_get_message(tag));
5977 if (ssh_sig && allowed_signers == NULL) {
5978 err = got_error_msg(
5979 GOT_ERR_VERIFY_TAG_SIGNATURE,
5980 "SSH signature verification requires "
5981 "setting allowed_signers in "
5982 "got.conf(5)");
5983 break;
5987 printf("%stag %s %s\n", GOT_COMMIT_SEP_STR, refname, refstr);
5988 free(refstr);
5989 printf("from: %s\n", tagger);
5990 datestr = get_datestr(&tagger_time, datebuf);
5991 if (datestr)
5992 printf("date: %s UTC\n", datestr);
5993 if (commit)
5994 printf("object: %s %s\n", GOT_OBJ_LABEL_COMMIT, id_str);
5995 else {
5996 switch (got_object_tag_get_object_type(tag)) {
5997 case GOT_OBJ_TYPE_BLOB:
5998 printf("object: %s %s\n", GOT_OBJ_LABEL_BLOB,
5999 id_str);
6000 break;
6001 case GOT_OBJ_TYPE_TREE:
6002 printf("object: %s %s\n", GOT_OBJ_LABEL_TREE,
6003 id_str);
6004 break;
6005 case GOT_OBJ_TYPE_COMMIT:
6006 printf("object: %s %s\n", GOT_OBJ_LABEL_COMMIT,
6007 id_str);
6008 break;
6009 case GOT_OBJ_TYPE_TAG:
6010 printf("object: %s %s\n", GOT_OBJ_LABEL_TAG,
6011 id_str);
6012 break;
6013 default:
6014 break;
6017 free(id_str);
6019 if (ssh_sig) {
6020 err = got_sigs_verify_tag_ssh(&sig_msg, tag, ssh_sig,
6021 allowed_signers, revoked_signers, verbosity);
6022 if (err && err->code == GOT_ERR_BAD_TAG_SIGNATURE)
6023 bad_sigs = 1;
6024 else if (err)
6025 break;
6026 printf("signature: %s", sig_msg);
6027 free(sig_msg);
6028 sig_msg = NULL;
6031 if (commit) {
6032 err = got_object_commit_get_logmsg(&tagmsg0, commit);
6033 if (err)
6034 break;
6035 got_object_commit_close(commit);
6036 } else {
6037 tagmsg0 = strdup(got_object_tag_get_message(tag));
6038 got_object_tag_close(tag);
6039 if (tagmsg0 == NULL) {
6040 err = got_error_from_errno("strdup");
6041 break;
6045 tagmsg = tagmsg0;
6046 do {
6047 line = strsep(&tagmsg, "\n");
6048 if (line)
6049 printf(" %s\n", line);
6050 } while (line);
6051 free(tagmsg0);
6053 done:
6054 got_ref_list_free(&refs);
6055 free(wanted_refname);
6057 if (err == NULL && bad_sigs)
6058 err = got_error(GOT_ERR_BAD_TAG_SIGNATURE);
6059 return err;
6062 static const struct got_error *
6063 get_tag_message(char **tagmsg, char **tagmsg_path, const char *commit_id_str,
6064 const char *tag_name, const char *repo_path)
6066 const struct got_error *err = NULL;
6067 char *template = NULL, *initial_content = NULL;
6068 char *editor = NULL;
6069 int initial_content_len;
6070 int fd = -1;
6072 if (asprintf(&template, GOT_TMPDIR_STR "/got-tagmsg") == -1) {
6073 err = got_error_from_errno("asprintf");
6074 goto done;
6077 initial_content_len = asprintf(&initial_content,
6078 "\n# tagging commit %s as %s\n",
6079 commit_id_str, tag_name);
6080 if (initial_content_len == -1) {
6081 err = got_error_from_errno("asprintf");
6082 goto done;
6085 err = got_opentemp_named_fd(tagmsg_path, &fd, template, "");
6086 if (err)
6087 goto done;
6089 if (write(fd, initial_content, initial_content_len) == -1) {
6090 err = got_error_from_errno2("write", *tagmsg_path);
6091 goto done;
6093 if (close(fd) == -1) {
6094 err = got_error_from_errno2("close", *tagmsg_path);
6095 goto done;
6097 fd = -1;
6099 err = get_editor(&editor);
6100 if (err)
6101 goto done;
6102 err = edit_logmsg(tagmsg, editor, *tagmsg_path, initial_content,
6103 initial_content_len, 1);
6104 done:
6105 free(initial_content);
6106 free(template);
6107 free(editor);
6109 if (fd != -1 && close(fd) == -1 && err == NULL)
6110 err = got_error_from_errno2("close", *tagmsg_path);
6112 if (err) {
6113 free(*tagmsg);
6114 *tagmsg = NULL;
6116 return err;
6119 static const struct got_error *
6120 add_tag(struct got_repository *repo, const char *tagger,
6121 const char *tag_name, const char *commit_arg, const char *tagmsg_arg,
6122 const char *signer_id, int verbosity)
6124 const struct got_error *err = NULL;
6125 struct got_object_id *commit_id = NULL, *tag_id = NULL;
6126 char *label = NULL, *commit_id_str = NULL;
6127 struct got_reference *ref = NULL;
6128 char *refname = NULL, *tagmsg = NULL;
6129 char *tagmsg_path = NULL, *tag_id_str = NULL;
6130 int preserve_tagmsg = 0;
6131 struct got_reflist_head refs;
6133 TAILQ_INIT(&refs);
6136 * Don't let the user create a tag name with a leading '-'.
6137 * While technically a valid reference name, this case is usually
6138 * an unintended typo.
6140 if (tag_name[0] == '-')
6141 return got_error_path(tag_name, GOT_ERR_REF_NAME_MINUS);
6143 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
6144 if (err)
6145 goto done;
6147 err = got_repo_match_object_id(&commit_id, &label, commit_arg,
6148 GOT_OBJ_TYPE_COMMIT, &refs, repo);
6149 if (err)
6150 goto done;
6152 err = got_object_id_str(&commit_id_str, commit_id);
6153 if (err)
6154 goto done;
6156 err = get_tag_refname(&refname, tag_name);
6157 if (err)
6158 goto done;
6159 if (strncmp("refs/tags/", tag_name, 10) == 0)
6160 tag_name += 10;
6162 err = got_ref_open(&ref, repo, refname, 0);
6163 if (err == NULL) {
6164 err = got_error(GOT_ERR_TAG_EXISTS);
6165 goto done;
6166 } else if (err->code != GOT_ERR_NOT_REF)
6167 goto done;
6169 if (tagmsg_arg == NULL) {
6170 err = get_tag_message(&tagmsg, &tagmsg_path, commit_id_str,
6171 tag_name, got_repo_get_path(repo));
6172 if (err) {
6173 if (err->code != GOT_ERR_COMMIT_MSG_EMPTY &&
6174 tagmsg_path != NULL)
6175 preserve_tagmsg = 1;
6176 goto done;
6178 /* Editor is done; we can now apply unveil(2) */
6179 err = got_sigs_apply_unveil();
6180 if (err)
6181 goto done;
6182 err = apply_unveil(got_repo_get_path(repo), 0, NULL);
6183 if (err)
6184 goto done;
6187 err = got_object_tag_create(&tag_id, tag_name, commit_id,
6188 tagger, time(NULL), tagmsg ? tagmsg : tagmsg_arg, signer_id, repo,
6189 verbosity);
6190 if (err) {
6191 if (tagmsg_path)
6192 preserve_tagmsg = 1;
6193 goto done;
6196 err = got_ref_alloc(&ref, refname, tag_id);
6197 if (err) {
6198 if (tagmsg_path)
6199 preserve_tagmsg = 1;
6200 goto done;
6203 err = got_ref_write(ref, repo);
6204 if (err) {
6205 if (tagmsg_path)
6206 preserve_tagmsg = 1;
6207 goto done;
6210 err = got_object_id_str(&tag_id_str, tag_id);
6211 if (err) {
6212 if (tagmsg_path)
6213 preserve_tagmsg = 1;
6214 goto done;
6216 printf("Created tag %s\n", tag_id_str);
6217 done:
6218 if (preserve_tagmsg) {
6219 fprintf(stderr, "%s: tag message preserved in %s\n",
6220 getprogname(), tagmsg_path);
6221 } else if (tagmsg_path && unlink(tagmsg_path) == -1 && err == NULL)
6222 err = got_error_from_errno2("unlink", tagmsg_path);
6223 free(tag_id_str);
6224 if (ref)
6225 got_ref_close(ref);
6226 free(commit_id);
6227 free(commit_id_str);
6228 free(refname);
6229 free(tagmsg);
6230 free(tagmsg_path);
6231 got_ref_list_free(&refs);
6232 return err;
6235 static const struct got_error *
6236 cmd_tag(int argc, char *argv[])
6238 const struct got_error *error = NULL;
6239 struct got_repository *repo = NULL;
6240 struct got_worktree *worktree = NULL;
6241 char *cwd = NULL, *repo_path = NULL, *commit_id_str = NULL;
6242 char *gitconfig_path = NULL, *tagger = NULL;
6243 char *allowed_signers = NULL, *revoked_signers = NULL;
6244 const char *signer_id = NULL;
6245 const char *tag_name = NULL, *commit_id_arg = NULL, *tagmsg = NULL;
6246 int ch, do_list = 0, verify_tags = 0, verbosity = 0;
6247 int *pack_fds = NULL;
6249 #ifndef PROFILE
6250 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
6251 "sendfd unveil", NULL) == -1)
6252 err(1, "pledge");
6253 #endif
6255 while ((ch = getopt(argc, argv, "c:lm:r:s:Vv")) != -1) {
6256 switch (ch) {
6257 case 'c':
6258 commit_id_arg = optarg;
6259 break;
6260 case 'l':
6261 do_list = 1;
6262 break;
6263 case 'm':
6264 tagmsg = optarg;
6265 break;
6266 case 'r':
6267 repo_path = realpath(optarg, NULL);
6268 if (repo_path == NULL) {
6269 error = got_error_from_errno2("realpath",
6270 optarg);
6271 goto done;
6273 got_path_strip_trailing_slashes(repo_path);
6274 break;
6275 case 's':
6276 signer_id = optarg;
6277 break;
6278 case 'V':
6279 verify_tags = 1;
6280 break;
6281 case 'v':
6282 if (verbosity < 0)
6283 verbosity = 0;
6284 else if (verbosity < 3)
6285 verbosity++;
6286 break;
6287 default:
6288 usage_tag();
6289 /* NOTREACHED */
6293 argc -= optind;
6294 argv += optind;
6296 if (do_list || verify_tags) {
6297 if (commit_id_arg != NULL)
6298 errx(1,
6299 "-c option can only be used when creating a tag");
6300 if (tagmsg) {
6301 if (do_list)
6302 option_conflict('l', 'm');
6303 else
6304 option_conflict('V', 'm');
6306 if (signer_id) {
6307 if (do_list)
6308 option_conflict('l', 's');
6309 else
6310 option_conflict('V', 's');
6312 if (argc > 1)
6313 usage_tag();
6314 } else if (argc != 1)
6315 usage_tag();
6317 if (argc == 1)
6318 tag_name = argv[0];
6320 cwd = getcwd(NULL, 0);
6321 if (cwd == NULL) {
6322 error = got_error_from_errno("getcwd");
6323 goto done;
6326 error = got_repo_pack_fds_open(&pack_fds);
6327 if (error != NULL)
6328 goto done;
6330 if (repo_path == NULL) {
6331 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_CVG_DIR);
6332 if (error && error->code != GOT_ERR_NOT_WORKTREE)
6333 goto done;
6334 else
6335 error = NULL;
6336 if (worktree) {
6337 repo_path =
6338 strdup(got_worktree_get_repo_path(worktree));
6339 if (repo_path == NULL)
6340 error = got_error_from_errno("strdup");
6341 if (error)
6342 goto done;
6343 } else {
6344 repo_path = strdup(cwd);
6345 if (repo_path == NULL) {
6346 error = got_error_from_errno("strdup");
6347 goto done;
6352 if (do_list || verify_tags) {
6353 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
6354 if (error != NULL)
6355 goto done;
6356 error = get_allowed_signers(&allowed_signers, repo, worktree);
6357 if (error)
6358 goto done;
6359 error = get_revoked_signers(&revoked_signers, repo, worktree);
6360 if (error)
6361 goto done;
6362 if (worktree) {
6363 /* Release work tree lock. */
6364 got_worktree_close(worktree);
6365 worktree = NULL;
6369 * Remove "cpath" promise unless needed for signature tmpfile
6370 * creation.
6372 if (verify_tags)
6373 got_sigs_apply_unveil();
6374 else {
6375 #ifndef PROFILE
6376 if (pledge("stdio rpath wpath flock proc exec sendfd "
6377 "unveil", NULL) == -1)
6378 err(1, "pledge");
6379 #endif
6381 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
6382 if (error)
6383 goto done;
6384 error = list_tags(repo, tag_name, verify_tags, allowed_signers,
6385 revoked_signers, verbosity);
6386 } else {
6387 error = get_gitconfig_path(&gitconfig_path);
6388 if (error)
6389 goto done;
6390 error = got_repo_open(&repo, repo_path, gitconfig_path,
6391 pack_fds);
6392 if (error != NULL)
6393 goto done;
6395 error = get_author(&tagger, repo, worktree);
6396 if (error)
6397 goto done;
6398 if (signer_id == NULL)
6399 signer_id = get_signer_id(repo, worktree);
6401 if (tagmsg) {
6402 if (signer_id) {
6403 error = got_sigs_apply_unveil();
6404 if (error)
6405 goto done;
6407 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
6408 if (error)
6409 goto done;
6412 if (commit_id_arg == NULL) {
6413 struct got_reference *head_ref;
6414 struct got_object_id *commit_id;
6415 error = got_ref_open(&head_ref, repo,
6416 worktree ? got_worktree_get_head_ref_name(worktree)
6417 : GOT_REF_HEAD, 0);
6418 if (error)
6419 goto done;
6420 error = got_ref_resolve(&commit_id, repo, head_ref);
6421 got_ref_close(head_ref);
6422 if (error)
6423 goto done;
6424 error = got_object_id_str(&commit_id_str, commit_id);
6425 free(commit_id);
6426 if (error)
6427 goto done;
6430 if (worktree) {
6431 /* Release work tree lock. */
6432 got_worktree_close(worktree);
6433 worktree = NULL;
6436 error = add_tag(repo, tagger, tag_name,
6437 commit_id_str ? commit_id_str : commit_id_arg, tagmsg,
6438 signer_id, verbosity);
6440 done:
6441 if (repo) {
6442 const struct got_error *close_err = got_repo_close(repo);
6443 if (error == NULL)
6444 error = close_err;
6446 if (worktree)
6447 got_worktree_close(worktree);
6448 if (pack_fds) {
6449 const struct got_error *pack_err =
6450 got_repo_pack_fds_close(pack_fds);
6451 if (error == NULL)
6452 error = pack_err;
6454 free(cwd);
6455 free(repo_path);
6456 free(gitconfig_path);
6457 free(commit_id_str);
6458 free(tagger);
6459 free(allowed_signers);
6460 free(revoked_signers);
6461 return error;
6464 __dead static void
6465 usage_add(void)
6467 fprintf(stderr, "usage: %s add [-IR] path ...\n", getprogname());
6468 exit(1);
6471 static const struct got_error *
6472 add_progress(void *arg, unsigned char status, const char *path)
6474 while (path[0] == '/')
6475 path++;
6476 printf("%c %s\n", status, path);
6477 return NULL;
6480 static const struct got_error *
6481 cmd_add(int argc, char *argv[])
6483 const struct got_error *error = NULL;
6484 struct got_repository *repo = NULL;
6485 struct got_worktree *worktree = NULL;
6486 char *cwd = NULL;
6487 struct got_pathlist_head paths;
6488 struct got_pathlist_entry *pe;
6489 int ch, can_recurse = 0, no_ignores = 0;
6490 int *pack_fds = NULL;
6492 RB_INIT(&paths);
6494 #ifndef PROFILE
6495 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
6496 NULL) == -1)
6497 err(1, "pledge");
6498 #endif
6500 while ((ch = getopt(argc, argv, "IR")) != -1) {
6501 switch (ch) {
6502 case 'I':
6503 no_ignores = 1;
6504 break;
6505 case 'R':
6506 can_recurse = 1;
6507 break;
6508 default:
6509 usage_add();
6510 /* NOTREACHED */
6514 argc -= optind;
6515 argv += optind;
6517 if (argc < 1)
6518 usage_add();
6520 cwd = getcwd(NULL, 0);
6521 if (cwd == NULL) {
6522 error = got_error_from_errno("getcwd");
6523 goto done;
6526 error = got_repo_pack_fds_open(&pack_fds);
6527 if (error != NULL)
6528 goto done;
6530 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_CVG_DIR);
6531 if (error) {
6532 if (error->code == GOT_ERR_NOT_WORKTREE)
6533 error = wrap_not_worktree_error(error, "add", cwd);
6534 goto done;
6537 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
6538 NULL, pack_fds);
6539 if (error != NULL)
6540 goto done;
6542 error = apply_unveil(got_repo_get_path(repo), 1,
6543 got_worktree_get_root_path(worktree));
6544 if (error)
6545 goto done;
6547 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
6548 if (error)
6549 goto done;
6551 if (!can_recurse) {
6552 char *ondisk_path;
6553 struct stat sb;
6554 RB_FOREACH(pe, got_pathlist_head, &paths) {
6555 if (asprintf(&ondisk_path, "%s/%s",
6556 got_worktree_get_root_path(worktree),
6557 pe->path) == -1) {
6558 error = got_error_from_errno("asprintf");
6559 goto done;
6561 if (lstat(ondisk_path, &sb) == -1) {
6562 if (errno == ENOENT) {
6563 free(ondisk_path);
6564 continue;
6566 error = got_error_from_errno2("lstat",
6567 ondisk_path);
6568 free(ondisk_path);
6569 goto done;
6571 free(ondisk_path);
6572 if (S_ISDIR(sb.st_mode)) {
6573 error = got_error_msg(GOT_ERR_BAD_PATH,
6574 "adding directories requires -R option");
6575 goto done;
6580 error = got_worktree_schedule_add(worktree, &paths, add_progress,
6581 NULL, repo, no_ignores);
6582 done:
6583 if (repo) {
6584 const struct got_error *close_err = got_repo_close(repo);
6585 if (error == NULL)
6586 error = close_err;
6588 if (worktree)
6589 got_worktree_close(worktree);
6590 if (pack_fds) {
6591 const struct got_error *pack_err =
6592 got_repo_pack_fds_close(pack_fds);
6593 if (error == NULL)
6594 error = pack_err;
6596 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
6597 free(cwd);
6598 return error;
6601 __dead static void
6602 usage_remove(void)
6604 fprintf(stderr, "usage: %s remove [-fkR] [-s status-codes] path ...\n",
6605 getprogname());
6606 exit(1);
6609 static const struct got_error *
6610 print_remove_status(void *arg, unsigned char status,
6611 unsigned char staged_status, const char *path)
6613 while (path[0] == '/')
6614 path++;
6615 if (status == GOT_STATUS_NONEXISTENT)
6616 return NULL;
6617 if (status == staged_status && (status == GOT_STATUS_DELETE))
6618 status = GOT_STATUS_NO_CHANGE;
6619 printf("%c%c %s\n", status, staged_status, path);
6620 return NULL;
6623 static const struct got_error *
6624 cmd_remove(int argc, char *argv[])
6626 const struct got_error *error = NULL;
6627 struct got_worktree *worktree = NULL;
6628 struct got_repository *repo = NULL;
6629 const char *status_codes = NULL;
6630 char *cwd = NULL;
6631 struct got_pathlist_head paths;
6632 struct got_pathlist_entry *pe;
6633 int ch, delete_local_mods = 0, can_recurse = 0, keep_on_disk = 0, i;
6634 int ignore_missing_paths = 0;
6635 int *pack_fds = NULL;
6637 RB_INIT(&paths);
6639 #ifndef PROFILE
6640 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
6641 NULL) == -1)
6642 err(1, "pledge");
6643 #endif
6645 while ((ch = getopt(argc, argv, "fkRs:")) != -1) {
6646 switch (ch) {
6647 case 'f':
6648 delete_local_mods = 1;
6649 ignore_missing_paths = 1;
6650 break;
6651 case 'k':
6652 keep_on_disk = 1;
6653 break;
6654 case 'R':
6655 can_recurse = 1;
6656 break;
6657 case 's':
6658 for (i = 0; optarg[i] != '\0'; i++) {
6659 switch (optarg[i]) {
6660 case GOT_STATUS_MODIFY:
6661 delete_local_mods = 1;
6662 break;
6663 case GOT_STATUS_MISSING:
6664 ignore_missing_paths = 1;
6665 break;
6666 default:
6667 errx(1, "invalid status code '%c'",
6668 optarg[i]);
6671 status_codes = optarg;
6672 break;
6673 default:
6674 usage_remove();
6675 /* NOTREACHED */
6679 argc -= optind;
6680 argv += optind;
6682 if (argc < 1)
6683 usage_remove();
6685 cwd = getcwd(NULL, 0);
6686 if (cwd == NULL) {
6687 error = got_error_from_errno("getcwd");
6688 goto done;
6691 error = got_repo_pack_fds_open(&pack_fds);
6692 if (error != NULL)
6693 goto done;
6695 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_CVG_DIR);
6696 if (error) {
6697 if (error->code == GOT_ERR_NOT_WORKTREE)
6698 error = wrap_not_worktree_error(error, "remove", cwd);
6699 goto done;
6702 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
6703 NULL, pack_fds);
6704 if (error)
6705 goto done;
6707 error = apply_unveil(got_repo_get_path(repo), 1,
6708 got_worktree_get_root_path(worktree));
6709 if (error)
6710 goto done;
6712 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
6713 if (error)
6714 goto done;
6716 if (!can_recurse) {
6717 char *ondisk_path;
6718 struct stat sb;
6719 RB_FOREACH(pe, got_pathlist_head, &paths) {
6720 if (asprintf(&ondisk_path, "%s/%s",
6721 got_worktree_get_root_path(worktree),
6722 pe->path) == -1) {
6723 error = got_error_from_errno("asprintf");
6724 goto done;
6726 if (lstat(ondisk_path, &sb) == -1) {
6727 if (errno == ENOENT) {
6728 free(ondisk_path);
6729 continue;
6731 error = got_error_from_errno2("lstat",
6732 ondisk_path);
6733 free(ondisk_path);
6734 goto done;
6736 free(ondisk_path);
6737 if (S_ISDIR(sb.st_mode)) {
6738 error = got_error_msg(GOT_ERR_BAD_PATH,
6739 "removing directories requires -R option");
6740 goto done;
6745 error = got_worktree_schedule_delete(worktree, &paths,
6746 delete_local_mods, status_codes, print_remove_status, NULL,
6747 repo, keep_on_disk, ignore_missing_paths);
6748 done:
6749 if (repo) {
6750 const struct got_error *close_err = got_repo_close(repo);
6751 if (error == NULL)
6752 error = close_err;
6754 if (worktree)
6755 got_worktree_close(worktree);
6756 if (pack_fds) {
6757 const struct got_error *pack_err =
6758 got_repo_pack_fds_close(pack_fds);
6759 if (error == NULL)
6760 error = pack_err;
6762 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
6763 free(cwd);
6764 return error;
6767 __dead static void
6768 usage_patch(void)
6770 fprintf(stderr, "usage: %s patch [-nR] [-c commit] [-p strip-count] "
6771 "[patchfile]\n", getprogname());
6772 exit(1);
6775 static const struct got_error *
6776 patch_from_stdin(int *patchfd)
6778 const struct got_error *err = NULL;
6779 ssize_t r;
6780 char buf[BUFSIZ];
6781 sig_t sighup, sigint, sigquit;
6783 *patchfd = got_opentempfd();
6784 if (*patchfd == -1)
6785 return got_error_from_errno("got_opentempfd");
6787 sighup = signal(SIGHUP, SIG_DFL);
6788 sigint = signal(SIGINT, SIG_DFL);
6789 sigquit = signal(SIGQUIT, SIG_DFL);
6791 for (;;) {
6792 r = read(0, buf, sizeof(buf));
6793 if (r == -1) {
6794 err = got_error_from_errno("read");
6795 break;
6797 if (r == 0)
6798 break;
6799 if (write(*patchfd, buf, r) == -1) {
6800 err = got_error_from_errno("write");
6801 break;
6805 signal(SIGHUP, sighup);
6806 signal(SIGINT, sigint);
6807 signal(SIGQUIT, sigquit);
6809 if (err == NULL && lseek(*patchfd, 0, SEEK_SET) == -1)
6810 err = got_error_from_errno("lseek");
6812 if (err != NULL) {
6813 close(*patchfd);
6814 *patchfd = -1;
6817 return err;
6820 struct got_patch_progress_arg {
6821 int did_something;
6822 int conflicts;
6823 int rejects;
6826 static const struct got_error *
6827 patch_progress(void *arg, const char *old, const char *new,
6828 unsigned char status, const struct got_error *error, int old_from,
6829 int old_lines, int new_from, int new_lines, int offset,
6830 int ws_mangled, const struct got_error *hunk_err)
6832 const char *path = new == NULL ? old : new;
6833 struct got_patch_progress_arg *a = arg;
6835 while (*path == '/')
6836 path++;
6838 if (status != GOT_STATUS_NO_CHANGE &&
6839 status != 0 /* per-hunk progress */) {
6840 printf("%c %s\n", status, path);
6841 a->did_something = 1;
6844 if (hunk_err == NULL) {
6845 if (status == GOT_STATUS_CANNOT_UPDATE)
6846 a->rejects++;
6847 else if (status == GOT_STATUS_CONFLICT)
6848 a->conflicts++;
6851 if (error != NULL)
6852 fprintf(stderr, "%s: %s\n", getprogname(), error->msg);
6854 if (offset != 0 || hunk_err != NULL || ws_mangled) {
6855 printf("@@ -%d,%d +%d,%d @@ ", old_from,
6856 old_lines, new_from, new_lines);
6857 if (hunk_err != NULL)
6858 printf("%s\n", hunk_err->msg);
6859 else if (offset != 0)
6860 printf("applied with offset %d\n", offset);
6861 else
6862 printf("hunk contains mangled whitespace\n");
6865 return NULL;
6868 static void
6869 print_patch_progress_stats(struct got_patch_progress_arg *ppa)
6871 if (!ppa->did_something)
6872 return;
6874 if (ppa->conflicts > 0)
6875 printf("Files with merge conflicts: %d\n", ppa->conflicts);
6877 if (ppa->rejects > 0) {
6878 printf("Files where patch failed to apply: %d\n",
6879 ppa->rejects);
6883 static const struct got_error *
6884 cmd_patch(int argc, char *argv[])
6886 const struct got_error *error = NULL, *close_error = NULL;
6887 struct got_worktree *worktree = NULL;
6888 struct got_repository *repo = NULL;
6889 struct got_reflist_head refs;
6890 struct got_object_id *commit_id = NULL;
6891 const char *commit_id_str = NULL;
6892 struct stat sb;
6893 const char *errstr;
6894 char *cwd = NULL;
6895 int ch, nop = 0, strip = -1, reverse = 0;
6896 int patchfd;
6897 int *pack_fds = NULL;
6898 struct got_patch_progress_arg ppa;
6900 TAILQ_INIT(&refs);
6902 #ifndef PROFILE
6903 if (pledge("stdio rpath wpath cpath fattr proc exec sendfd flock "
6904 "unveil", NULL) == -1)
6905 err(1, "pledge");
6906 #endif
6908 while ((ch = getopt(argc, argv, "c:np:R")) != -1) {
6909 switch (ch) {
6910 case 'c':
6911 commit_id_str = optarg;
6912 break;
6913 case 'n':
6914 nop = 1;
6915 break;
6916 case 'p':
6917 strip = strtonum(optarg, 0, INT_MAX, &errstr);
6918 if (errstr != NULL)
6919 errx(1, "pathname strip count is %s: %s",
6920 errstr, optarg);
6921 break;
6922 case 'R':
6923 reverse = 1;
6924 break;
6925 default:
6926 usage_patch();
6927 /* NOTREACHED */
6931 argc -= optind;
6932 argv += optind;
6934 if (argc == 0) {
6935 error = patch_from_stdin(&patchfd);
6936 if (error)
6937 return error;
6938 } else if (argc == 1) {
6939 patchfd = open(argv[0], O_RDONLY);
6940 if (patchfd == -1)
6941 return got_error_from_errno2("open", argv[0]);
6942 if (fstat(patchfd, &sb) == -1) {
6943 error = got_error_from_errno2("fstat", argv[0]);
6944 goto done;
6946 if (!S_ISREG(sb.st_mode)) {
6947 error = got_error_path(argv[0], GOT_ERR_BAD_FILETYPE);
6948 goto done;
6950 } else
6951 usage_patch();
6953 if ((cwd = getcwd(NULL, 0)) == NULL) {
6954 error = got_error_from_errno("getcwd");
6955 goto done;
6958 error = got_repo_pack_fds_open(&pack_fds);
6959 if (error != NULL)
6960 goto done;
6962 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_CVG_DIR);
6963 if (error != NULL)
6964 goto done;
6966 const char *repo_path = got_worktree_get_repo_path(worktree);
6967 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
6968 if (error != NULL)
6969 goto done;
6971 error = apply_unveil(got_repo_get_path(repo), 0,
6972 got_worktree_get_root_path(worktree));
6973 if (error != NULL)
6974 goto done;
6976 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
6977 if (error)
6978 goto done;
6980 if (commit_id_str != NULL) {
6981 error = got_repo_match_object_id(&commit_id, NULL,
6982 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
6983 if (error)
6984 goto done;
6987 memset(&ppa, 0, sizeof(ppa));
6988 error = got_patch(patchfd, worktree, repo, nop, strip, reverse,
6989 commit_id, patch_progress, &ppa, check_cancelled, NULL);
6990 print_patch_progress_stats(&ppa);
6991 done:
6992 got_ref_list_free(&refs);
6993 free(commit_id);
6994 if (repo) {
6995 close_error = got_repo_close(repo);
6996 if (error == NULL)
6997 error = close_error;
6999 if (worktree != NULL) {
7000 close_error = got_worktree_close(worktree);
7001 if (error == NULL)
7002 error = close_error;
7004 if (pack_fds) {
7005 const struct got_error *pack_err =
7006 got_repo_pack_fds_close(pack_fds);
7007 if (error == NULL)
7008 error = pack_err;
7010 free(cwd);
7011 return error;
7014 __dead static void
7015 usage_revert(void)
7017 fprintf(stderr, "usage: %s revert [-pR] [-F response-script] path ...\n",
7018 getprogname());
7019 exit(1);
7022 static const struct got_error *
7023 revert_progress(void *arg, unsigned char status, const char *path)
7025 if (status == GOT_STATUS_UNVERSIONED)
7026 return NULL;
7028 while (path[0] == '/')
7029 path++;
7030 printf("%c %s\n", status, path);
7031 return NULL;
7034 struct choose_patch_arg {
7035 FILE *patch_script_file;
7036 const char *action;
7039 static const struct got_error *
7040 show_change(unsigned char status, const char *path, FILE *patch_file, int n,
7041 int nchanges, const char *action)
7043 const struct got_error *err;
7044 char *line = NULL;
7045 size_t linesize = 0;
7046 ssize_t linelen;
7048 switch (status) {
7049 case GOT_STATUS_ADD:
7050 printf("A %s\n%s this addition? [y/n] ", path, action);
7051 break;
7052 case GOT_STATUS_DELETE:
7053 printf("D %s\n%s this deletion? [y/n] ", path, action);
7054 break;
7055 case GOT_STATUS_MODIFY:
7056 if (fseek(patch_file, 0L, SEEK_SET) == -1)
7057 return got_error_from_errno("fseek");
7058 printf(GOT_COMMIT_SEP_STR);
7059 while ((linelen = getline(&line, &linesize, patch_file)) != -1)
7060 printf("%s", line);
7061 if (linelen == -1 && ferror(patch_file)) {
7062 err = got_error_from_errno("getline");
7063 free(line);
7064 return err;
7066 free(line);
7067 printf(GOT_COMMIT_SEP_STR);
7068 printf("M %s (change %d of %d)\n%s this change? [y/n/q] ",
7069 path, n, nchanges, action);
7070 break;
7071 default:
7072 return got_error_path(path, GOT_ERR_FILE_STATUS);
7075 fflush(stdout);
7076 return NULL;
7079 static const struct got_error *
7080 choose_patch(int *choice, void *arg, unsigned char status, const char *path,
7081 FILE *patch_file, int n, int nchanges)
7083 const struct got_error *err = NULL;
7084 char *line = NULL;
7085 size_t linesize = 0;
7086 ssize_t linelen;
7087 int resp = ' ';
7088 struct choose_patch_arg *a = arg;
7090 *choice = GOT_PATCH_CHOICE_NONE;
7092 if (a->patch_script_file) {
7093 char *nl;
7094 err = show_change(status, path, patch_file, n, nchanges,
7095 a->action);
7096 if (err)
7097 return err;
7098 linelen = getline(&line, &linesize, a->patch_script_file);
7099 if (linelen == -1) {
7100 if (ferror(a->patch_script_file))
7101 return got_error_from_errno("getline");
7102 return NULL;
7104 nl = strchr(line, '\n');
7105 if (nl)
7106 *nl = '\0';
7107 if (strcmp(line, "y") == 0) {
7108 *choice = GOT_PATCH_CHOICE_YES;
7109 printf("y\n");
7110 } else if (strcmp(line, "n") == 0) {
7111 *choice = GOT_PATCH_CHOICE_NO;
7112 printf("n\n");
7113 } else if (strcmp(line, "q") == 0 &&
7114 status == GOT_STATUS_MODIFY) {
7115 *choice = GOT_PATCH_CHOICE_QUIT;
7116 printf("q\n");
7117 } else
7118 printf("invalid response '%s'\n", line);
7119 free(line);
7120 return NULL;
7123 while (resp != 'y' && resp != 'n' && resp != 'q') {
7124 err = show_change(status, path, patch_file, n, nchanges,
7125 a->action);
7126 if (err)
7127 return err;
7128 resp = getchar();
7129 if (resp == '\n')
7130 resp = getchar();
7131 if (status == GOT_STATUS_MODIFY) {
7132 if (resp != 'y' && resp != 'n' && resp != 'q') {
7133 printf("invalid response '%c'\n", resp);
7134 resp = ' ';
7136 } else if (resp != 'y' && resp != 'n') {
7137 printf("invalid response '%c'\n", resp);
7138 resp = ' ';
7142 if (resp == 'y')
7143 *choice = GOT_PATCH_CHOICE_YES;
7144 else if (resp == 'n')
7145 *choice = GOT_PATCH_CHOICE_NO;
7146 else if (resp == 'q' && status == GOT_STATUS_MODIFY)
7147 *choice = GOT_PATCH_CHOICE_QUIT;
7149 return NULL;
7152 struct wt_commitable_path_arg {
7153 struct got_pathlist_head *commit_paths;
7154 int *has_changes;
7158 * Shortcut work tree status callback to determine if the set of paths scanned
7159 * has at least one versioned path that is being modified and, if not NULL, is
7160 * in the arg->commit_paths list. Set arg and return GOT_ERR_FILE_MODIFIED as
7161 * soon as a path is passed with a status that satisfies this criteria.
7163 static const struct got_error *
7164 worktree_has_commitable_path(void *arg, unsigned char status,
7165 unsigned char staged_status, const char *path,
7166 struct got_object_id *blob_id, struct got_object_id *staged_blob_id,
7167 struct got_object_id *commit_id, int dirfd, const char *de_name)
7169 struct wt_commitable_path_arg *a = arg;
7171 if (status == staged_status && (status == GOT_STATUS_DELETE))
7172 status = GOT_STATUS_NO_CHANGE;
7174 if (!(status == GOT_STATUS_NO_CHANGE ||
7175 status == GOT_STATUS_UNVERSIONED) ||
7176 staged_status != GOT_STATUS_NO_CHANGE) {
7177 if (a->commit_paths != NULL) {
7178 struct got_pathlist_entry *pe;
7180 RB_FOREACH(pe, got_pathlist_head, a->commit_paths) {
7181 if (strncmp(path, pe->path,
7182 pe->path_len) == 0) {
7183 *a->has_changes = 1;
7184 break;
7187 } else
7188 *a->has_changes = 1;
7190 if (*a->has_changes)
7191 return got_error(GOT_ERR_FILE_MODIFIED);
7194 return NULL;
7198 * Check that the changeset of the commit identified by id is
7199 * comprised of at least one modified path that is being committed.
7201 static const struct got_error *
7202 commit_path_changed_in_worktree(struct wt_commitable_path_arg *wcpa,
7203 struct got_object_id *id, struct got_worktree *worktree,
7204 struct got_repository *repo)
7206 const struct got_error *err;
7207 struct got_pathlist_head paths;
7208 struct got_commit_object *commit = NULL, *pcommit = NULL;
7209 struct got_tree_object *tree = NULL, *ptree = NULL;
7210 struct got_object_qid *pid;
7212 RB_INIT(&paths);
7214 err = got_object_open_as_commit(&commit, repo, id);
7215 if (err)
7216 goto done;
7218 err = got_object_open_as_tree(&tree, repo,
7219 got_object_commit_get_tree_id(commit));
7220 if (err)
7221 goto done;
7223 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
7224 if (pid != NULL) {
7225 err = got_object_open_as_commit(&pcommit, repo, &pid->id);
7226 if (err)
7227 goto done;
7229 err = got_object_open_as_tree(&ptree, repo,
7230 got_object_commit_get_tree_id(pcommit));
7231 if (err)
7232 goto done;
7235 err = got_diff_tree(ptree, tree, NULL, NULL, -1, -1, "", "", repo,
7236 got_diff_tree_collect_changed_paths, &paths, 0);
7237 if (err)
7238 goto done;
7240 err = got_worktree_status(worktree, &paths, repo, 0,
7241 worktree_has_commitable_path, wcpa, check_cancelled, NULL);
7242 if (err && err->code == GOT_ERR_FILE_MODIFIED) {
7244 * At least one changed path in the referenced commit is
7245 * modified in the work tree, that's all we need to know!
7247 err = NULL;
7250 done:
7251 got_pathlist_free(&paths, GOT_PATHLIST_FREE_ALL);
7252 if (commit)
7253 got_object_commit_close(commit);
7254 if (pcommit)
7255 got_object_commit_close(pcommit);
7256 if (tree)
7257 got_object_tree_close(tree);
7258 if (ptree)
7259 got_object_tree_close(ptree);
7260 return err;
7264 * Remove any "logmsg" reference comprised entirely of paths that have
7265 * been reverted in this work tree. If any path in the logmsg ref changeset
7266 * remains in a changed state in the worktree, do not remove the reference.
7268 static const struct got_error *
7269 rm_logmsg_ref(struct got_worktree *worktree, struct got_repository *repo)
7271 const struct got_error *err;
7272 struct got_reflist_head refs;
7273 struct got_reflist_entry *re;
7274 struct got_commit_object *commit = NULL;
7275 struct got_object_id *commit_id = NULL;
7276 struct wt_commitable_path_arg wcpa;
7277 char *uuidstr = NULL;
7279 TAILQ_INIT(&refs);
7281 err = got_worktree_get_uuid(&uuidstr, worktree);
7282 if (err)
7283 goto done;
7285 err = got_ref_list(&refs, repo, "refs/got/worktree",
7286 got_ref_cmp_by_name, repo);
7287 if (err)
7288 goto done;
7290 TAILQ_FOREACH(re, &refs, entry) {
7291 const char *refname;
7292 int has_changes = 0;
7294 refname = got_ref_get_name(re->ref);
7296 if (!strncmp(refname, GOT_WORKTREE_CHERRYPICK_REF_PREFIX,
7297 GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN))
7298 refname += GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN + 1;
7299 else if (!strncmp(refname, GOT_WORKTREE_BACKOUT_REF_PREFIX,
7300 GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN))
7301 refname += GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN + 1;
7302 else
7303 continue;
7305 if (strncmp(refname, uuidstr, GOT_WORKTREE_UUID_STRLEN) == 0)
7306 refname += GOT_WORKTREE_UUID_STRLEN + 1; /* skip '-' */
7307 else
7308 continue;
7310 err = got_repo_match_object_id(&commit_id, NULL, refname,
7311 GOT_OBJ_TYPE_COMMIT, NULL, repo);
7312 if (err)
7313 goto done;
7315 err = got_object_open_as_commit(&commit, repo, commit_id);
7316 if (err)
7317 goto done;
7319 wcpa.commit_paths = NULL;
7320 wcpa.has_changes = &has_changes;
7322 err = commit_path_changed_in_worktree(&wcpa, commit_id,
7323 worktree, repo);
7324 if (err)
7325 goto done;
7327 if (!has_changes) {
7328 err = got_ref_delete(re->ref, repo);
7329 if (err)
7330 goto done;
7333 got_object_commit_close(commit);
7334 commit = NULL;
7335 free(commit_id);
7336 commit_id = NULL;
7339 done:
7340 free(uuidstr);
7341 free(commit_id);
7342 got_ref_list_free(&refs);
7343 if (commit)
7344 got_object_commit_close(commit);
7345 return err;
7348 static const struct got_error *
7349 cmd_revert(int argc, char *argv[])
7351 const struct got_error *error = NULL;
7352 struct got_worktree *worktree = NULL;
7353 struct got_repository *repo = NULL;
7354 char *cwd = NULL, *path = NULL;
7355 struct got_pathlist_head paths;
7356 struct got_pathlist_entry *pe;
7357 int ch, can_recurse = 0, pflag = 0;
7358 FILE *patch_script_file = NULL;
7359 const char *patch_script_path = NULL;
7360 struct choose_patch_arg cpa;
7361 int *pack_fds = NULL;
7363 RB_INIT(&paths);
7365 #ifndef PROFILE
7366 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
7367 "unveil", NULL) == -1)
7368 err(1, "pledge");
7369 #endif
7371 while ((ch = getopt(argc, argv, "F:pR")) != -1) {
7372 switch (ch) {
7373 case 'F':
7374 patch_script_path = optarg;
7375 break;
7376 case 'p':
7377 pflag = 1;
7378 break;
7379 case 'R':
7380 can_recurse = 1;
7381 break;
7382 default:
7383 usage_revert();
7384 /* NOTREACHED */
7388 argc -= optind;
7389 argv += optind;
7391 if (argc < 1)
7392 usage_revert();
7393 if (patch_script_path && !pflag)
7394 errx(1, "-F option can only be used together with -p option");
7396 cwd = getcwd(NULL, 0);
7397 if (cwd == NULL) {
7398 error = got_error_from_errno("getcwd");
7399 goto done;
7402 error = got_repo_pack_fds_open(&pack_fds);
7403 if (error != NULL)
7404 goto done;
7406 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_CVG_DIR);
7407 if (error) {
7408 if (error->code == GOT_ERR_NOT_WORKTREE)
7409 error = wrap_not_worktree_error(error, "revert", cwd);
7410 goto done;
7413 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
7414 NULL, pack_fds);
7415 if (error != NULL)
7416 goto done;
7418 if (patch_script_path) {
7419 patch_script_file = fopen(patch_script_path, "re");
7420 if (patch_script_file == NULL) {
7421 error = got_error_from_errno2("fopen",
7422 patch_script_path);
7423 goto done;
7428 * XXX "c" perm needed on repo dir to delete merge references.
7430 error = apply_unveil(got_repo_get_path(repo), 0,
7431 got_worktree_get_root_path(worktree));
7432 if (error)
7433 goto done;
7435 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
7436 if (error)
7437 goto done;
7439 if (!can_recurse) {
7440 char *ondisk_path;
7441 struct stat sb;
7442 RB_FOREACH(pe, got_pathlist_head, &paths) {
7443 if (asprintf(&ondisk_path, "%s/%s",
7444 got_worktree_get_root_path(worktree),
7445 pe->path) == -1) {
7446 error = got_error_from_errno("asprintf");
7447 goto done;
7449 if (lstat(ondisk_path, &sb) == -1) {
7450 if (errno == ENOENT) {
7451 free(ondisk_path);
7452 continue;
7454 error = got_error_from_errno2("lstat",
7455 ondisk_path);
7456 free(ondisk_path);
7457 goto done;
7459 free(ondisk_path);
7460 if (S_ISDIR(sb.st_mode)) {
7461 error = got_error_msg(GOT_ERR_BAD_PATH,
7462 "reverting directories requires -R option");
7463 goto done;
7468 cpa.patch_script_file = patch_script_file;
7469 cpa.action = "revert";
7470 error = got_worktree_revert(worktree, &paths, revert_progress, NULL,
7471 pflag ? choose_patch : NULL, &cpa, repo);
7473 error = rm_logmsg_ref(worktree, repo);
7474 done:
7475 if (patch_script_file && fclose(patch_script_file) == EOF &&
7476 error == NULL)
7477 error = got_error_from_errno2("fclose", patch_script_path);
7478 if (repo) {
7479 const struct got_error *close_err = got_repo_close(repo);
7480 if (error == NULL)
7481 error = close_err;
7483 if (worktree)
7484 got_worktree_close(worktree);
7485 if (pack_fds) {
7486 const struct got_error *pack_err =
7487 got_repo_pack_fds_close(pack_fds);
7488 if (error == NULL)
7489 error = pack_err;
7491 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
7492 free(path);
7493 free(cwd);
7494 return error;
7497 __dead static void
7498 usage_commit(void)
7500 fprintf(stderr, "usage: %s commit [-CNnS] [-A author] "
7501 "[-i identity-file] [-J jumphost] [-F path] [-m message] "
7502 "[path ...]\n", getprogname());
7503 exit(1);
7506 struct collect_commit_logmsg_arg {
7507 const char *cmdline_log;
7508 const char *prepared_log;
7509 const char *merged_log;
7510 int non_interactive;
7511 const char *editor;
7512 const char *worktree_path;
7513 const char *repo_path;
7514 const char *dial_proto;
7515 char *logmsg_path;
7518 static const struct got_error *
7519 read_prepared_logmsg(char **logmsg, const char *path)
7521 const struct got_error *err = NULL;
7522 FILE *f = NULL;
7523 struct stat sb;
7524 size_t r;
7526 *logmsg = NULL;
7527 memset(&sb, 0, sizeof(sb));
7529 f = fopen(path, "re");
7530 if (f == NULL)
7531 return got_error_from_errno2("fopen", path);
7533 if (fstat(fileno(f), &sb) == -1) {
7534 err = got_error_from_errno2("fstat", path);
7535 goto done;
7537 if (sb.st_size == 0) {
7538 err = got_error(GOT_ERR_COMMIT_MSG_EMPTY);
7539 goto done;
7542 *logmsg = malloc(sb.st_size + 1);
7543 if (*logmsg == NULL) {
7544 err = got_error_from_errno("malloc");
7545 goto done;
7548 r = fread(*logmsg, 1, sb.st_size, f);
7549 if (r != sb.st_size) {
7550 if (ferror(f))
7551 err = got_error_from_errno2("fread", path);
7552 else
7553 err = got_error(GOT_ERR_IO);
7554 goto done;
7556 (*logmsg)[sb.st_size] = '\0';
7557 done:
7558 if (fclose(f) == EOF && err == NULL)
7559 err = got_error_from_errno2("fclose", path);
7560 if (err) {
7561 free(*logmsg);
7562 *logmsg = NULL;
7564 return err;
7567 static const struct got_error *
7568 collect_commit_logmsg(struct got_pathlist_head *commitable_paths,
7569 const char *diff_path, char **logmsg, void *arg)
7571 char *initial_content = NULL;
7572 struct got_pathlist_entry *pe;
7573 const struct got_error *err = NULL;
7574 char *template = NULL;
7575 char *prepared_msg = NULL, *merged_msg = NULL;
7576 struct collect_commit_logmsg_arg *a = arg;
7577 int initial_content_len;
7578 int fd = -1;
7579 size_t len;
7581 /* if a message was specified on the command line, just use it */
7582 if (a->cmdline_log != NULL && *a->cmdline_log != '\0') {
7583 len = strlen(a->cmdline_log) + 1;
7584 *logmsg = malloc(len + 1);
7585 if (*logmsg == NULL)
7586 return got_error_from_errno("malloc");
7587 strlcpy(*logmsg, a->cmdline_log, len);
7588 return NULL;
7589 } else if (a->prepared_log != NULL && a->non_interactive)
7590 return read_prepared_logmsg(logmsg, a->prepared_log);
7592 if (asprintf(&template, "%s/logmsg", a->worktree_path) == -1)
7593 return got_error_from_errno("asprintf");
7595 err = got_opentemp_named_fd(&a->logmsg_path, &fd, template, "");
7596 if (err)
7597 goto done;
7599 if (a->prepared_log) {
7600 err = read_prepared_logmsg(&prepared_msg, a->prepared_log);
7601 if (err)
7602 goto done;
7603 } else if (a->merged_log) {
7604 err = read_prepared_logmsg(&merged_msg, a->merged_log);
7605 if (err)
7606 goto done;
7609 initial_content_len = asprintf(&initial_content,
7610 "%s%s\n# changes to be committed:\n",
7611 prepared_msg ? prepared_msg : "",
7612 merged_msg ? merged_msg : "");
7613 if (initial_content_len == -1) {
7614 err = got_error_from_errno("asprintf");
7615 goto done;
7618 if (write(fd, initial_content, initial_content_len) == -1) {
7619 err = got_error_from_errno2("write", a->logmsg_path);
7620 goto done;
7623 RB_FOREACH(pe, got_pathlist_head, commitable_paths) {
7624 struct got_commitable *ct = pe->data;
7625 dprintf(fd, "# %c %s\n",
7626 got_commitable_get_status(ct),
7627 got_commitable_get_path(ct));
7630 if (diff_path) {
7631 dprintf(fd, "# detailed changes can be viewed in %s\n",
7632 diff_path);
7635 if (close(fd) == -1) {
7636 err = got_error_from_errno2("close", a->logmsg_path);
7637 goto done;
7639 fd = -1;
7641 err = edit_logmsg(logmsg, a->editor, a->logmsg_path, initial_content,
7642 initial_content_len, a->prepared_log ? 0 : 1);
7643 done:
7644 free(initial_content);
7645 free(template);
7646 free(prepared_msg);
7647 free(merged_msg);
7649 if (fd != -1 && close(fd) == -1 && err == NULL)
7650 err = got_error_from_errno2("close", a->logmsg_path);
7652 /* Editor is done; we can now apply unveil(2) */
7653 if (err == NULL)
7654 err = got_dial_apply_unveil(a->dial_proto);
7655 if (err == NULL)
7656 err = apply_unveil(a->repo_path, 0, a->worktree_path);
7657 if (err) {
7658 free(*logmsg);
7659 *logmsg = NULL;
7661 return err;
7664 static const struct got_error *
7665 cat_logmsg(FILE *f, struct got_commit_object *commit, const char *idstr,
7666 const char *type, int has_content)
7668 const struct got_error *err = NULL;
7669 char *logmsg = NULL;
7671 err = got_object_commit_get_logmsg(&logmsg, commit);
7672 if (err)
7673 return err;
7675 if (fprintf(f, "%s# log message of %s commit %s:%s",
7676 has_content ? "\n" : "", type, idstr, logmsg) < 0)
7677 err = got_ferror(f, GOT_ERR_IO);
7679 free(logmsg);
7680 return err;
7684 * Lookup "logmsg" references of backed-out and cherrypicked commits
7685 * belonging to the current work tree. If found, and the worktree has
7686 * at least one modified file that was changed in the referenced commit,
7687 * add its log message to a new temporary file at *logmsg_path.
7688 * Add all refs found to matched_refs to be scheduled for removal on
7689 * successful commit.
7691 static const struct got_error *
7692 lookup_logmsg_ref(char **logmsg_path, struct got_pathlist_head *paths,
7693 struct got_reflist_head *matched_refs, struct got_worktree *worktree,
7694 struct got_repository *repo)
7696 const struct got_error *err;
7697 struct got_commit_object *commit = NULL;
7698 struct got_object_id *id = NULL;
7699 struct got_reflist_head refs;
7700 struct got_reflist_entry *re, *re_match;
7701 FILE *f = NULL;
7702 char *uuidstr = NULL;
7703 int added_logmsg = 0;
7705 TAILQ_INIT(&refs);
7707 *logmsg_path = NULL;
7709 err = got_worktree_get_uuid(&uuidstr, worktree);
7710 if (err)
7711 goto done;
7713 err = got_ref_list(&refs, repo, "refs/got/worktree",
7714 got_ref_cmp_by_name, repo);
7715 if (err)
7716 goto done;
7718 TAILQ_FOREACH(re, &refs, entry) {
7719 const char *refname, *type;
7720 struct wt_commitable_path_arg wcpa;
7721 int add_logmsg = 0;
7723 refname = got_ref_get_name(re->ref);
7725 if (strncmp(refname, GOT_WORKTREE_CHERRYPICK_REF_PREFIX,
7726 GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN) == 0) {
7727 refname += GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN + 1;
7728 type = "cherrypicked";
7729 } else if (strncmp(refname, GOT_WORKTREE_BACKOUT_REF_PREFIX,
7730 GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN) == 0) {
7731 refname += GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN + 1;
7732 type = "backed-out";
7733 } else
7734 continue;
7736 if (strncmp(refname, uuidstr, GOT_WORKTREE_UUID_STRLEN) == 0)
7737 refname += GOT_WORKTREE_UUID_STRLEN + 1; /* skip '-' */
7738 else
7739 continue;
7741 err = got_repo_match_object_id(&id, NULL, refname,
7742 GOT_OBJ_TYPE_COMMIT, NULL, repo);
7743 if (err)
7744 goto done;
7746 err = got_object_open_as_commit(&commit, repo, id);
7747 if (err)
7748 goto done;
7750 wcpa.commit_paths = paths;
7751 wcpa.has_changes = &add_logmsg;
7753 err = commit_path_changed_in_worktree(&wcpa, id,
7754 worktree, repo);
7755 if (err)
7756 goto done;
7758 if (add_logmsg) {
7759 if (f == NULL) {
7760 err = got_opentemp_named(logmsg_path, &f,
7761 "got-commit-logmsg", "");
7762 if (err)
7763 goto done;
7765 err = cat_logmsg(f, commit, refname, type,
7766 added_logmsg);
7767 if (err)
7768 goto done;
7769 if (!added_logmsg)
7770 ++added_logmsg;
7772 err = got_reflist_entry_dup(&re_match, re);
7773 if (err)
7774 goto done;
7775 TAILQ_INSERT_HEAD(matched_refs, re_match, entry);
7778 got_object_commit_close(commit);
7779 commit = NULL;
7780 free(id);
7781 id = NULL;
7784 done:
7785 free(id);
7786 free(uuidstr);
7787 got_ref_list_free(&refs);
7788 if (commit)
7789 got_object_commit_close(commit);
7790 if (f && fclose(f) == EOF && err == NULL)
7791 err = got_error_from_errno("fclose");
7792 if (!added_logmsg) {
7793 if (*logmsg_path && unlink(*logmsg_path) != 0 && err == NULL)
7794 err = got_error_from_errno2("unlink", *logmsg_path);
7795 *logmsg_path = NULL;
7797 return err;
7800 static const struct got_error *
7801 cmd_commit(int argc, char *argv[])
7803 const struct got_error *error = NULL;
7804 struct got_worktree *worktree = NULL;
7805 struct got_repository *repo = NULL;
7806 char *cwd = NULL, *id_str = NULL;
7807 struct got_object_id *id = NULL;
7808 const char *logmsg = NULL;
7809 char *prepared_logmsg = NULL, *merged_logmsg = NULL;
7810 struct collect_commit_logmsg_arg cl_arg;
7811 const char *author = NULL;
7812 char *gitconfig_path = NULL, *editor = NULL, *committer = NULL;
7813 int ch, rebase_in_progress, histedit_in_progress, preserve_logmsg = 0;
7814 int allow_bad_symlinks = 0, non_interactive = 0, merge_in_progress = 0;
7815 int show_diff = 1, commit_conflicts = 0;
7816 struct got_pathlist_head paths;
7817 struct got_reflist_head refs;
7818 struct got_reflist_entry *re;
7819 int *pack_fds = NULL;
7820 const struct got_gotconfig *repo_conf = NULL, *worktree_conf = NULL;
7821 const struct got_remote_repo *remotes, *remote = NULL;
7822 int nremotes;
7823 char *proto = NULL, *host = NULL, *port = NULL;
7824 char *repo_name = NULL, *server_path = NULL;
7825 const char *remote_name, *jumphost = NULL, *identity_file = NULL;
7826 int verbosity = 0;
7827 int i;
7829 TAILQ_INIT(&refs);
7830 RB_INIT(&paths);
7831 cl_arg.logmsg_path = NULL;
7833 #ifndef PROFILE
7834 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
7835 "unveil", NULL) == -1)
7836 err(1, "pledge");
7837 #endif
7839 while ((ch = getopt(argc, argv, "A:CF:i:J:m:NnS")) != -1) {
7840 switch (ch) {
7841 case 'A':
7842 author = optarg;
7843 error = valid_author(author);
7844 if (error)
7845 return error;
7846 break;
7847 case 'C':
7848 commit_conflicts = 1;
7849 break;
7850 case 'F':
7851 if (logmsg != NULL)
7852 option_conflict('F', 'm');
7853 prepared_logmsg = realpath(optarg, NULL);
7854 if (prepared_logmsg == NULL)
7855 return got_error_from_errno2("realpath",
7856 optarg);
7857 break;
7858 case 'i':
7859 identity_file = optarg;
7860 break;
7861 case 'J':
7862 jumphost = optarg;
7863 break;
7864 case 'm':
7865 if (prepared_logmsg)
7866 option_conflict('m', 'F');
7867 logmsg = optarg;
7868 break;
7869 case 'N':
7870 non_interactive = 1;
7871 break;
7872 case 'n':
7873 show_diff = 0;
7874 break;
7875 case 'S':
7876 allow_bad_symlinks = 1;
7877 break;
7878 default:
7879 usage_commit();
7880 /* NOTREACHED */
7884 argc -= optind;
7885 argv += optind;
7887 cwd = getcwd(NULL, 0);
7888 if (cwd == NULL) {
7889 error = got_error_from_errno("getcwd");
7890 goto done;
7893 error = got_repo_pack_fds_open(&pack_fds);
7894 if (error != NULL)
7895 goto done;
7897 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_CVG_DIR);
7898 if (error) {
7899 if (error->code == GOT_ERR_NOT_WORKTREE)
7900 error = wrap_not_worktree_error(error, "commit", cwd);
7901 goto done;
7904 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
7905 if (error)
7906 goto done;
7907 if (rebase_in_progress) {
7908 error = got_error(GOT_ERR_REBASING);
7909 goto done;
7912 error = got_worktree_histedit_in_progress(&histedit_in_progress,
7913 worktree);
7914 if (error)
7915 goto done;
7917 error = get_gitconfig_path(&gitconfig_path);
7918 if (error)
7919 goto done;
7920 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
7921 gitconfig_path, pack_fds);
7922 if (error != NULL)
7923 goto done;
7925 error = got_worktree_merge_in_progress(&merge_in_progress, worktree, repo);
7926 if (error)
7927 goto done;
7928 if (merge_in_progress) {
7929 error = got_error(GOT_ERR_MERGE_BUSY);
7930 goto done;
7933 error = get_author(&committer, repo, worktree);
7934 if (error)
7935 goto done;
7937 if (author == NULL)
7938 author = committer;
7940 remote_name = GOT_SEND_DEFAULT_REMOTE_NAME;
7941 worktree_conf = got_worktree_get_gotconfig(worktree);
7942 if (worktree_conf) {
7943 got_gotconfig_get_remotes(&nremotes, &remotes,
7944 worktree_conf);
7945 for (i = 0; i < nremotes; i++) {
7946 if (strcmp(remotes[i].name, remote_name) == 0) {
7947 remote = &remotes[i];
7948 break;
7952 if (remote == NULL) {
7953 repo_conf = got_repo_get_gotconfig(repo);
7954 if (repo_conf) {
7955 got_gotconfig_get_remotes(&nremotes, &remotes,
7956 repo_conf);
7957 for (i = 0; i < nremotes; i++) {
7958 if (strcmp(remotes[i].name, remote_name) == 0) {
7959 remote = &remotes[i];
7960 break;
7965 if (remote == NULL) {
7966 got_repo_get_gitconfig_remotes(&nremotes, &remotes, repo);
7967 for (i = 0; i < nremotes; i++) {
7968 if (strcmp(remotes[i].name, remote_name) == 0) {
7969 remote = &remotes[i];
7970 break;
7974 if (remote == NULL) {
7975 error = got_error_path(remote_name, GOT_ERR_NO_REMOTE);
7976 goto done;
7979 error = got_dial_parse_uri(&proto, &host, &port, &server_path,
7980 &repo_name, remote->fetch_url);
7981 if (error)
7982 goto done;
7984 if (strcmp(proto, "git") == 0) {
7985 #ifndef PROFILE
7986 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
7987 "sendfd dns inet unveil", NULL) == -1)
7988 err(1, "pledge");
7989 #endif
7990 } else if (strcmp(proto, "git+ssh") == 0 ||
7991 strcmp(proto, "ssh") == 0) {
7992 #ifndef PROFILE
7993 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
7994 "sendfd unveil", NULL) == -1)
7995 err(1, "pledge");
7996 #endif
7997 } else if (strcmp(proto, "http") == 0 ||
7998 strcmp(proto, "git+http") == 0) {
7999 error = got_error_path(proto, GOT_ERR_NOT_IMPL);
8000 goto done;
8001 } else {
8002 error = got_error_path(proto, GOT_ERR_BAD_PROTO);
8003 goto done;
8007 /*if (verbosity >= 0) {
8008 printf("Connecting to \"%s\" %s://%s%s%s%s%s\n",
8009 remote->name, proto, host,
8010 port ? ":" : "", port ? port : "",
8011 *server_path == '/' ? "" : "/", server_path);
8015 * unveil(2) traverses exec(2); if an editor is used we have
8016 * to apply unveil after the log message has been written during
8017 * the callback.
8019 if (logmsg == NULL || strlen(logmsg) == 0)
8020 error = get_editor(&editor);
8021 else {
8022 error = got_dial_apply_unveil(proto);
8023 if (error)
8024 goto done;
8025 error = apply_unveil(got_repo_get_path(repo), 0,
8026 got_worktree_get_root_path(worktree));
8028 if (error)
8029 goto done;
8031 if (prepared_logmsg == NULL) {
8032 error = lookup_logmsg_ref(&merged_logmsg,
8033 argc > 0 ? &paths : NULL, &refs, worktree, repo);
8034 if (error)
8035 goto done;
8038 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
8039 if (error)
8040 goto done;
8042 cl_arg.editor = editor;
8043 cl_arg.cmdline_log = logmsg;
8044 cl_arg.prepared_log = prepared_logmsg;
8045 cl_arg.merged_log = merged_logmsg;
8046 cl_arg.non_interactive = non_interactive;
8047 cl_arg.worktree_path = got_worktree_get_root_path(worktree);
8048 cl_arg.repo_path = got_repo_get_path(repo);
8049 cl_arg.dial_proto = proto;
8050 error = got_worktree_cvg_commit(&id, worktree, &paths, author,
8051 committer, allow_bad_symlinks, show_diff, commit_conflicts,
8052 collect_commit_logmsg, &cl_arg, print_status, NULL, proto, host,
8053 port, server_path, jumphost, identity_file, verbosity, remote,
8054 check_cancelled, repo);
8055 if (error) {
8056 if (error->code != GOT_ERR_COMMIT_MSG_EMPTY &&
8057 cl_arg.logmsg_path != NULL)
8058 preserve_logmsg = 1;
8059 goto done;
8062 error = got_object_id_str(&id_str, id);
8063 if (error)
8064 goto done;
8065 printf("Created commit %s\n", id_str);
8067 TAILQ_FOREACH(re, &refs, entry) {
8068 error = got_ref_delete(re->ref, repo);
8069 if (error)
8070 goto done;
8073 done:
8074 if (preserve_logmsg) {
8075 fprintf(stderr, "%s: log message preserved in %s\n",
8076 getprogname(), cl_arg.logmsg_path);
8077 } else if (cl_arg.logmsg_path && unlink(cl_arg.logmsg_path) == -1 &&
8078 error == NULL)
8079 error = got_error_from_errno2("unlink", cl_arg.logmsg_path);
8080 free(cl_arg.logmsg_path);
8081 if (merged_logmsg && unlink(merged_logmsg) == -1 && error == NULL)
8082 error = got_error_from_errno2("unlink", merged_logmsg);
8083 free(merged_logmsg);
8084 if (repo) {
8085 const struct got_error *close_err = got_repo_close(repo);
8086 if (error == NULL)
8087 error = close_err;
8089 if (worktree)
8090 got_worktree_close(worktree);
8091 if (pack_fds) {
8092 const struct got_error *pack_err =
8093 got_repo_pack_fds_close(pack_fds);
8094 if (error == NULL)
8095 error = pack_err;
8097 got_ref_list_free(&refs);
8098 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
8099 free(cwd);
8100 free(id_str);
8101 free(gitconfig_path);
8102 free(editor);
8103 free(committer);
8104 free(prepared_logmsg);
8105 return error;
8109 * Print and if delete is set delete all ref_prefix references.
8110 * If wanted_ref is not NULL, only print or delete this reference.
8112 static const struct got_error *
8113 process_logmsg_refs(const char *ref_prefix, size_t prefix_len,
8114 const char *wanted_ref, int delete, struct got_worktree *worktree,
8115 struct got_repository *repo)
8117 const struct got_error *err;
8118 struct got_pathlist_head paths;
8119 struct got_reflist_head refs;
8120 struct got_reflist_entry *re;
8121 struct got_reflist_object_id_map *refs_idmap = NULL;
8122 struct got_commit_object *commit = NULL;
8123 struct got_object_id *id = NULL;
8124 const char *header_prefix;
8125 char *uuidstr = NULL;
8126 int found = 0;
8128 TAILQ_INIT(&refs);
8129 RB_INIT(&paths);
8131 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, repo);
8132 if (err)
8133 goto done;
8135 err = got_reflist_object_id_map_create(&refs_idmap, &refs, repo);
8136 if (err)
8137 goto done;
8139 if (worktree != NULL) {
8140 err = got_worktree_get_uuid(&uuidstr, worktree);
8141 if (err)
8142 goto done;
8145 if (wanted_ref) {
8146 if (strncmp(wanted_ref, "refs/heads/", 11) == 0)
8147 wanted_ref += 11;
8150 if (strcmp(ref_prefix, GOT_WORKTREE_BACKOUT_REF_PREFIX) == 0)
8151 header_prefix = "backout";
8152 else
8153 header_prefix = "cherrypick";
8155 TAILQ_FOREACH(re, &refs, entry) {
8156 const char *refname, *wt;
8158 refname = got_ref_get_name(re->ref);
8160 err = check_cancelled(NULL);
8161 if (err)
8162 goto done;
8164 if (strncmp(refname, ref_prefix, prefix_len) == 0)
8165 refname += prefix_len + 1; /* skip '-' delimiter */
8166 else
8167 continue;
8169 wt = refname;
8171 if (worktree == NULL || strncmp(refname, uuidstr,
8172 GOT_WORKTREE_UUID_STRLEN) == 0)
8173 refname += GOT_WORKTREE_UUID_STRLEN + 1; /* skip '-' */
8174 else
8175 continue;
8177 err = got_repo_match_object_id(&id, NULL, refname,
8178 GOT_OBJ_TYPE_COMMIT, NULL, repo);
8179 if (err)
8180 goto done;
8182 err = got_object_open_as_commit(&commit, repo, id);
8183 if (err)
8184 goto done;
8186 if (wanted_ref)
8187 found = strncmp(wanted_ref, refname,
8188 strlen(wanted_ref)) == 0;
8189 if (wanted_ref && !found) {
8190 struct got_reflist_head *ci_refs;
8192 ci_refs = got_reflist_object_id_map_lookup(refs_idmap,
8193 id);
8195 if (ci_refs) {
8196 char *refs_str = NULL;
8197 char const *r = NULL;
8199 err = build_refs_str(&refs_str, ci_refs, id,
8200 repo, 1);
8201 if (err)
8202 goto done;
8204 r = refs_str;
8205 while (r) {
8206 if (strncmp(r, wanted_ref,
8207 strlen(wanted_ref)) == 0) {
8208 found = 1;
8209 break;
8211 r = strchr(r, ' ');
8212 if (r)
8213 ++r;
8215 free(refs_str);
8219 if (wanted_ref == NULL || found) {
8220 if (delete) {
8221 err = got_ref_delete(re->ref, repo);
8222 if (err)
8223 goto done;
8224 printf("Deleted: ");
8225 err = print_commit_oneline(commit, id, repo,
8226 refs_idmap);
8227 } else {
8229 * Print paths modified by commit to help
8230 * associate commits with worktree changes.
8232 err = get_changed_paths(&paths, commit,
8233 repo, NULL);
8234 if (err)
8235 goto done;
8237 err = print_commit(commit, id, repo, NULL,
8238 &paths, NULL, 0, 0, refs_idmap, NULL,
8239 header_prefix);
8240 got_pathlist_free(&paths,
8241 GOT_PATHLIST_FREE_ALL);
8243 if (worktree == NULL)
8244 printf("work tree: %.*s\n\n",
8245 GOT_WORKTREE_UUID_STRLEN, wt);
8247 if (err || found)
8248 goto done;
8251 got_object_commit_close(commit);
8252 commit = NULL;
8253 free(id);
8254 id = NULL;
8257 if (wanted_ref != NULL && !found)
8258 err = got_error_fmt(GOT_ERR_NOT_REF, "%s", wanted_ref);
8260 done:
8261 free(id);
8262 free(uuidstr);
8263 got_ref_list_free(&refs);
8264 got_pathlist_free(&paths, GOT_PATHLIST_FREE_ALL);
8265 if (refs_idmap)
8266 got_reflist_object_id_map_free(refs_idmap);
8267 if (commit)
8268 got_object_commit_close(commit);
8269 return err;
8273 * Create new temp "logmsg" ref of the backed-out or cherrypicked commit
8274 * identified by id for log messages to prepopulate the editor on commit.
8276 static const struct got_error *
8277 logmsg_ref(struct got_object_id *id, const char *prefix,
8278 struct got_worktree *worktree, struct got_repository *repo)
8280 const struct got_error *err = NULL;
8281 char *idstr, *ref = NULL, *refname = NULL;
8282 int histedit_in_progress;
8283 int rebase_in_progress, merge_in_progress;
8286 * Silently refuse to create merge reference if any histedit, merge,
8287 * or rebase operation is in progress.
8289 err = got_worktree_histedit_in_progress(&histedit_in_progress,
8290 worktree);
8291 if (err)
8292 return err;
8293 if (histedit_in_progress)
8294 return NULL;
8296 err = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
8297 if (err)
8298 return err;
8299 if (rebase_in_progress)
8300 return NULL;
8302 err = got_worktree_merge_in_progress(&merge_in_progress, worktree,
8303 repo);
8304 if (err)
8305 return err;
8306 if (merge_in_progress)
8307 return NULL;
8309 err = got_object_id_str(&idstr, id);
8310 if (err)
8311 return err;
8313 err = got_worktree_get_logmsg_ref_name(&refname, worktree, prefix);
8314 if (err)
8315 goto done;
8317 if (asprintf(&ref, "%s-%s", refname, idstr) == -1) {
8318 err = got_error_from_errno("asprintf");
8319 goto done;
8322 err = create_ref(ref, got_worktree_get_base_commit_id(worktree),
8323 -1, repo);
8324 done:
8325 free(ref);
8326 free(idstr);
8327 free(refname);
8328 return err;
8331 __dead static void
8332 usage_cherrypick(void)
8334 fprintf(stderr, "usage: %s cherrypick [-lX] [commit-id]\n",
8335 getprogname());
8336 exit(1);
8339 static const struct got_error *
8340 cmd_cherrypick(int argc, char *argv[])
8342 const struct got_error *error = NULL;
8343 struct got_worktree *worktree = NULL;
8344 struct got_repository *repo = NULL;
8345 char *cwd = NULL, *commit_id_str = NULL;
8346 struct got_object_id *commit_id = NULL;
8347 struct got_commit_object *commit = NULL;
8348 struct got_object_qid *pid;
8349 int ch, list_refs = 0, remove_refs = 0;
8350 struct got_update_progress_arg upa;
8351 int *pack_fds = NULL;
8353 #ifndef PROFILE
8354 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
8355 "unveil", NULL) == -1)
8356 err(1, "pledge");
8357 #endif
8359 while ((ch = getopt(argc, argv, "lX")) != -1) {
8360 switch (ch) {
8361 case 'l':
8362 list_refs = 1;
8363 break;
8364 case 'X':
8365 remove_refs = 1;
8366 break;
8367 default:
8368 usage_cherrypick();
8369 /* NOTREACHED */
8373 argc -= optind;
8374 argv += optind;
8376 if (list_refs || remove_refs) {
8377 if (argc != 0 && argc != 1)
8378 usage_cherrypick();
8379 } else if (argc != 1)
8380 usage_cherrypick();
8381 if (list_refs && remove_refs)
8382 option_conflict('l', 'X');
8384 cwd = getcwd(NULL, 0);
8385 if (cwd == NULL) {
8386 error = got_error_from_errno("getcwd");
8387 goto done;
8390 error = got_repo_pack_fds_open(&pack_fds);
8391 if (error != NULL)
8392 goto done;
8394 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_CVG_DIR);
8395 if (error) {
8396 if (list_refs || remove_refs) {
8397 if (error->code != GOT_ERR_NOT_WORKTREE)
8398 goto done;
8399 } else {
8400 if (error->code == GOT_ERR_NOT_WORKTREE)
8401 error = wrap_not_worktree_error(error,
8402 "cherrypick", cwd);
8403 goto done;
8407 error = got_repo_open(&repo,
8408 worktree ? got_worktree_get_repo_path(worktree) : cwd,
8409 NULL, pack_fds);
8410 if (error != NULL)
8411 goto done;
8413 error = apply_unveil(got_repo_get_path(repo), 0,
8414 worktree ? got_worktree_get_root_path(worktree) : NULL);
8415 if (error)
8416 goto done;
8418 if (list_refs || remove_refs) {
8419 error = process_logmsg_refs(GOT_WORKTREE_CHERRYPICK_REF_PREFIX,
8420 GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN,
8421 argc == 1 ? argv[0] : NULL, remove_refs, worktree, repo);
8422 goto done;
8425 error = got_repo_match_object_id(&commit_id, NULL, argv[0],
8426 GOT_OBJ_TYPE_COMMIT, NULL, repo);
8427 if (error)
8428 goto done;
8429 error = got_object_id_str(&commit_id_str, commit_id);
8430 if (error)
8431 goto done;
8433 error = got_object_open_as_commit(&commit, repo, commit_id);
8434 if (error)
8435 goto done;
8436 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
8437 memset(&upa, 0, sizeof(upa));
8438 error = got_worktree_merge_files(worktree, pid ? &pid->id : NULL,
8439 commit_id, repo, update_progress, &upa, check_cancelled,
8440 NULL);
8441 if (error != NULL)
8442 goto done;
8444 if (upa.did_something) {
8445 error = logmsg_ref(commit_id,
8446 GOT_WORKTREE_CHERRYPICK_REF_PREFIX, worktree, repo);
8447 if (error)
8448 goto done;
8449 printf("Merged commit %s\n", commit_id_str);
8451 print_merge_progress_stats(&upa);
8452 done:
8453 free(cwd);
8454 if (commit)
8455 got_object_commit_close(commit);
8456 free(commit_id_str);
8457 if (worktree)
8458 got_worktree_close(worktree);
8459 if (repo) {
8460 const struct got_error *close_err = got_repo_close(repo);
8461 if (error == NULL)
8462 error = close_err;
8464 if (pack_fds) {
8465 const struct got_error *pack_err =
8466 got_repo_pack_fds_close(pack_fds);
8467 if (error == NULL)
8468 error = pack_err;
8471 return error;
8474 __dead static void
8475 usage_backout(void)
8477 fprintf(stderr, "usage: %s backout [-lX] [commit-id]\n", getprogname());
8478 exit(1);
8481 static const struct got_error *
8482 cmd_backout(int argc, char *argv[])
8484 const struct got_error *error = NULL;
8485 struct got_worktree *worktree = NULL;
8486 struct got_repository *repo = NULL;
8487 char *cwd = NULL, *commit_id_str = NULL;
8488 struct got_object_id *commit_id = NULL;
8489 struct got_commit_object *commit = NULL;
8490 struct got_object_qid *pid;
8491 int ch, list_refs = 0, remove_refs = 0;
8492 struct got_update_progress_arg upa;
8493 int *pack_fds = NULL;
8495 #ifndef PROFILE
8496 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
8497 "unveil", NULL) == -1)
8498 err(1, "pledge");
8499 #endif
8501 while ((ch = getopt(argc, argv, "lX")) != -1) {
8502 switch (ch) {
8503 case 'l':
8504 list_refs = 1;
8505 break;
8506 case 'X':
8507 remove_refs = 1;
8508 break;
8509 default:
8510 usage_backout();
8511 /* NOTREACHED */
8515 argc -= optind;
8516 argv += optind;
8518 if (list_refs || remove_refs) {
8519 if (argc != 0 && argc != 1)
8520 usage_backout();
8521 } else if (argc != 1)
8522 usage_backout();
8523 if (list_refs && remove_refs)
8524 option_conflict('l', 'X');
8526 cwd = getcwd(NULL, 0);
8527 if (cwd == NULL) {
8528 error = got_error_from_errno("getcwd");
8529 goto done;
8532 error = got_repo_pack_fds_open(&pack_fds);
8533 if (error != NULL)
8534 goto done;
8536 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_CVG_DIR);
8537 if (error) {
8538 if (list_refs || remove_refs) {
8539 if (error->code != GOT_ERR_NOT_WORKTREE)
8540 goto done;
8541 } else {
8542 if (error->code == GOT_ERR_NOT_WORKTREE)
8543 error = wrap_not_worktree_error(error,
8544 "backout", cwd);
8545 goto done;
8549 error = got_repo_open(&repo,
8550 worktree ? got_worktree_get_repo_path(worktree) : cwd,
8551 NULL, pack_fds);
8552 if (error != NULL)
8553 goto done;
8555 error = apply_unveil(got_repo_get_path(repo), 0,
8556 worktree ? got_worktree_get_root_path(worktree) : NULL);
8557 if (error)
8558 goto done;
8560 if (list_refs || remove_refs) {
8561 error = process_logmsg_refs(GOT_WORKTREE_BACKOUT_REF_PREFIX,
8562 GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN,
8563 argc == 1 ? argv[0] : NULL, remove_refs, worktree, repo);
8564 goto done;
8567 error = got_repo_match_object_id(&commit_id, NULL, argv[0],
8568 GOT_OBJ_TYPE_COMMIT, NULL, repo);
8569 if (error)
8570 goto done;
8571 error = got_object_id_str(&commit_id_str, commit_id);
8572 if (error)
8573 goto done;
8575 error = got_object_open_as_commit(&commit, repo, commit_id);
8576 if (error)
8577 goto done;
8578 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
8579 if (pid == NULL) {
8580 error = got_error(GOT_ERR_ROOT_COMMIT);
8581 goto done;
8584 memset(&upa, 0, sizeof(upa));
8585 error = got_worktree_merge_files(worktree, commit_id, &pid->id,
8586 repo, update_progress, &upa, check_cancelled, NULL);
8587 if (error != NULL)
8588 goto done;
8590 if (upa.did_something) {
8591 error = logmsg_ref(commit_id, GOT_WORKTREE_BACKOUT_REF_PREFIX,
8592 worktree, repo);
8593 if (error)
8594 goto done;
8595 printf("Backed out commit %s\n", commit_id_str);
8597 print_merge_progress_stats(&upa);
8598 done:
8599 free(cwd);
8600 if (commit)
8601 got_object_commit_close(commit);
8602 free(commit_id_str);
8603 if (worktree)
8604 got_worktree_close(worktree);
8605 if (repo) {
8606 const struct got_error *close_err = got_repo_close(repo);
8607 if (error == NULL)
8608 error = close_err;
8610 if (pack_fds) {
8611 const struct got_error *pack_err =
8612 got_repo_pack_fds_close(pack_fds);
8613 if (error == NULL)
8614 error = pack_err;
8616 return error;
8619 __dead static void
8620 usage_cat(void)
8622 fprintf(stderr, "usage: %s cat [-P] [-c commit] [-r repository-path] "
8623 "arg ...\n", getprogname());
8624 exit(1);
8627 static const struct got_error *
8628 cat_blob(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
8630 const struct got_error *err;
8631 struct got_blob_object *blob;
8632 int fd = -1;
8634 fd = got_opentempfd();
8635 if (fd == -1)
8636 return got_error_from_errno("got_opentempfd");
8638 err = got_object_open_as_blob(&blob, repo, id, 8192, fd);
8639 if (err)
8640 goto done;
8642 err = got_object_blob_dump_to_file(NULL, NULL, NULL, outfile, blob);
8643 done:
8644 if (fd != -1 && close(fd) == -1 && err == NULL)
8645 err = got_error_from_errno("close");
8646 if (blob)
8647 got_object_blob_close(blob);
8648 return err;
8651 static const struct got_error *
8652 cat_tree(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
8654 const struct got_error *err;
8655 struct got_tree_object *tree;
8656 int nentries, i;
8658 err = got_object_open_as_tree(&tree, repo, id);
8659 if (err)
8660 return err;
8662 nentries = got_object_tree_get_nentries(tree);
8663 for (i = 0; i < nentries; i++) {
8664 struct got_tree_entry *te;
8665 char *id_str;
8666 if (sigint_received || sigpipe_received)
8667 break;
8668 te = got_object_tree_get_entry(tree, i);
8669 err = got_object_id_str(&id_str, got_tree_entry_get_id(te));
8670 if (err)
8671 break;
8672 fprintf(outfile, "%s %.7o %s\n", id_str,
8673 got_tree_entry_get_mode(te),
8674 got_tree_entry_get_name(te));
8675 free(id_str);
8678 got_object_tree_close(tree);
8679 return err;
8682 static const struct got_error *
8683 cat_commit(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
8685 const struct got_error *err;
8686 struct got_commit_object *commit;
8687 const struct got_object_id_queue *parent_ids;
8688 struct got_object_qid *pid;
8689 char *id_str = NULL;
8690 const char *logmsg = NULL;
8691 char gmtoff[6];
8693 err = got_object_open_as_commit(&commit, repo, id);
8694 if (err)
8695 return err;
8697 err = got_object_id_str(&id_str, got_object_commit_get_tree_id(commit));
8698 if (err)
8699 goto done;
8701 fprintf(outfile, "%s%s\n", GOT_COMMIT_LABEL_TREE, id_str);
8702 parent_ids = got_object_commit_get_parent_ids(commit);
8703 fprintf(outfile, "numparents %d\n",
8704 got_object_commit_get_nparents(commit));
8705 STAILQ_FOREACH(pid, parent_ids, entry) {
8706 char *pid_str;
8707 err = got_object_id_str(&pid_str, &pid->id);
8708 if (err)
8709 goto done;
8710 fprintf(outfile, "%s%s\n", GOT_COMMIT_LABEL_PARENT, pid_str);
8711 free(pid_str);
8713 got_date_format_gmtoff(gmtoff, sizeof(gmtoff),
8714 got_object_commit_get_author_gmtoff(commit));
8715 fprintf(outfile, "%s%s %lld %s\n", GOT_COMMIT_LABEL_AUTHOR,
8716 got_object_commit_get_author(commit),
8717 (long long)got_object_commit_get_author_time(commit),
8718 gmtoff);
8720 got_date_format_gmtoff(gmtoff, sizeof(gmtoff),
8721 got_object_commit_get_committer_gmtoff(commit));
8722 fprintf(outfile, "%s%s %lld %s\n", GOT_COMMIT_LABEL_COMMITTER,
8723 got_object_commit_get_committer(commit),
8724 (long long)got_object_commit_get_committer_time(commit),
8725 gmtoff);
8727 logmsg = got_object_commit_get_logmsg_raw(commit);
8728 fprintf(outfile, "messagelen %zd\n", strlen(logmsg));
8729 fprintf(outfile, "%s", logmsg);
8730 done:
8731 free(id_str);
8732 got_object_commit_close(commit);
8733 return err;
8736 static const struct got_error *
8737 cat_tag(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
8739 const struct got_error *err;
8740 struct got_tag_object *tag;
8741 char *id_str = NULL;
8742 const char *tagmsg = NULL;
8743 char gmtoff[6];
8745 err = got_object_open_as_tag(&tag, repo, id);
8746 if (err)
8747 return err;
8749 err = got_object_id_str(&id_str, got_object_tag_get_object_id(tag));
8750 if (err)
8751 goto done;
8753 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_OBJECT, id_str);
8755 switch (got_object_tag_get_object_type(tag)) {
8756 case GOT_OBJ_TYPE_BLOB:
8757 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
8758 GOT_OBJ_LABEL_BLOB);
8759 break;
8760 case GOT_OBJ_TYPE_TREE:
8761 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
8762 GOT_OBJ_LABEL_TREE);
8763 break;
8764 case GOT_OBJ_TYPE_COMMIT:
8765 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
8766 GOT_OBJ_LABEL_COMMIT);
8767 break;
8768 case GOT_OBJ_TYPE_TAG:
8769 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
8770 GOT_OBJ_LABEL_TAG);
8771 break;
8772 default:
8773 break;
8776 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TAG,
8777 got_object_tag_get_name(tag));
8779 got_date_format_gmtoff(gmtoff, sizeof(gmtoff),
8780 got_object_tag_get_tagger_gmtoff(tag));
8781 fprintf(outfile, "%s%s %lld %s\n", GOT_TAG_LABEL_TAGGER,
8782 got_object_tag_get_tagger(tag),
8783 (long long)got_object_tag_get_tagger_time(tag),
8784 gmtoff);
8786 tagmsg = got_object_tag_get_message(tag);
8787 fprintf(outfile, "messagelen %zd\n", strlen(tagmsg));
8788 fprintf(outfile, "%s", tagmsg);
8789 done:
8790 free(id_str);
8791 got_object_tag_close(tag);
8792 return err;
8795 static const struct got_error *
8796 cmd_cat(int argc, char *argv[])
8798 const struct got_error *error;
8799 struct got_repository *repo = NULL;
8800 struct got_worktree *worktree = NULL;
8801 char *cwd = NULL, *repo_path = NULL, *label = NULL;
8802 const char *commit_id_str = NULL;
8803 struct got_object_id *id = NULL, *commit_id = NULL;
8804 struct got_commit_object *commit = NULL;
8805 int ch, obj_type, i, force_path = 0;
8806 struct got_reflist_head refs;
8807 int *pack_fds = NULL;
8809 TAILQ_INIT(&refs);
8811 #ifndef PROFILE
8812 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
8813 NULL) == -1)
8814 err(1, "pledge");
8815 #endif
8817 while ((ch = getopt(argc, argv, "c:Pr:")) != -1) {
8818 switch (ch) {
8819 case 'c':
8820 commit_id_str = optarg;
8821 break;
8822 case 'P':
8823 force_path = 1;
8824 break;
8825 case 'r':
8826 repo_path = realpath(optarg, NULL);
8827 if (repo_path == NULL)
8828 return got_error_from_errno2("realpath",
8829 optarg);
8830 got_path_strip_trailing_slashes(repo_path);
8831 break;
8832 default:
8833 usage_cat();
8834 /* NOTREACHED */
8838 argc -= optind;
8839 argv += optind;
8841 cwd = getcwd(NULL, 0);
8842 if (cwd == NULL) {
8843 error = got_error_from_errno("getcwd");
8844 goto done;
8847 error = got_repo_pack_fds_open(&pack_fds);
8848 if (error != NULL)
8849 goto done;
8851 if (repo_path == NULL) {
8852 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_CVG_DIR);
8853 if (error && error->code != GOT_ERR_NOT_WORKTREE)
8854 goto done;
8855 if (worktree) {
8856 repo_path = strdup(
8857 got_worktree_get_repo_path(worktree));
8858 if (repo_path == NULL) {
8859 error = got_error_from_errno("strdup");
8860 goto done;
8863 /* Release work tree lock. */
8864 got_worktree_close(worktree);
8865 worktree = NULL;
8869 if (repo_path == NULL) {
8870 repo_path = strdup(cwd);
8871 if (repo_path == NULL)
8872 return got_error_from_errno("strdup");
8875 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
8876 free(repo_path);
8877 if (error != NULL)
8878 goto done;
8880 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
8881 if (error)
8882 goto done;
8884 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
8885 if (error)
8886 goto done;
8888 if (commit_id_str == NULL)
8889 commit_id_str = GOT_REF_HEAD;
8890 error = got_repo_match_object_id(&commit_id, NULL,
8891 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
8892 if (error)
8893 goto done;
8895 error = got_object_open_as_commit(&commit, repo, commit_id);
8896 if (error)
8897 goto done;
8899 for (i = 0; i < argc; i++) {
8900 if (force_path) {
8901 error = got_object_id_by_path(&id, repo, commit,
8902 argv[i]);
8903 if (error)
8904 break;
8905 } else {
8906 error = got_repo_match_object_id(&id, &label, argv[i],
8907 GOT_OBJ_TYPE_ANY, NULL /* do not resolve tags */,
8908 repo);
8909 if (error) {
8910 if (error->code != GOT_ERR_BAD_OBJ_ID_STR &&
8911 error->code != GOT_ERR_NOT_REF)
8912 break;
8913 error = got_object_id_by_path(&id, repo,
8914 commit, argv[i]);
8915 if (error)
8916 break;
8920 error = got_object_get_type(&obj_type, repo, id);
8921 if (error)
8922 break;
8924 switch (obj_type) {
8925 case GOT_OBJ_TYPE_BLOB:
8926 error = cat_blob(id, repo, stdout);
8927 break;
8928 case GOT_OBJ_TYPE_TREE:
8929 error = cat_tree(id, repo, stdout);
8930 break;
8931 case GOT_OBJ_TYPE_COMMIT:
8932 error = cat_commit(id, repo, stdout);
8933 break;
8934 case GOT_OBJ_TYPE_TAG:
8935 error = cat_tag(id, repo, stdout);
8936 break;
8937 default:
8938 error = got_error(GOT_ERR_OBJ_TYPE);
8939 break;
8941 if (error)
8942 break;
8943 free(label);
8944 label = NULL;
8945 free(id);
8946 id = NULL;
8948 done:
8949 free(label);
8950 free(id);
8951 free(commit_id);
8952 if (commit)
8953 got_object_commit_close(commit);
8954 if (worktree)
8955 got_worktree_close(worktree);
8956 if (repo) {
8957 const struct got_error *close_err = got_repo_close(repo);
8958 if (error == NULL)
8959 error = close_err;
8961 if (pack_fds) {
8962 const struct got_error *pack_err =
8963 got_repo_pack_fds_close(pack_fds);
8964 if (error == NULL)
8965 error = pack_err;
8968 got_ref_list_free(&refs);
8969 return error;
8972 __dead static void
8973 usage_info(void)
8975 fprintf(stderr, "usage: %s info [path ...]\n",
8976 getprogname());
8977 exit(1);
8980 static const struct got_error *
8981 print_path_info(void *arg, const char *path, mode_t mode, time_t mtime,
8982 struct got_object_id *blob_id, struct got_object_id *staged_blob_id,
8983 struct got_object_id *commit_id)
8985 const struct got_error *err = NULL;
8986 char *id_str = NULL;
8987 char datebuf[128];
8988 struct tm mytm, *tm;
8989 struct got_pathlist_head *paths = arg;
8990 struct got_pathlist_entry *pe;
8993 * Clear error indication from any of the path arguments which
8994 * would cause this file index entry to be displayed.
8996 RB_FOREACH(pe, got_pathlist_head, paths) {
8997 if (got_path_cmp(path, pe->path, strlen(path),
8998 pe->path_len) == 0 ||
8999 got_path_is_child(path, pe->path, pe->path_len))
9000 pe->data = NULL; /* no error */
9003 printf(GOT_COMMIT_SEP_STR);
9004 if (S_ISLNK(mode))
9005 printf("symlink: %s\n", path);
9006 else if (S_ISREG(mode)) {
9007 printf("file: %s\n", path);
9008 printf("mode: %o\n", mode & (S_IRWXU | S_IRWXG | S_IRWXO));
9009 } else if (S_ISDIR(mode))
9010 printf("directory: %s\n", path);
9011 else
9012 printf("something: %s\n", path);
9014 tm = localtime_r(&mtime, &mytm);
9015 if (tm == NULL)
9016 return NULL;
9017 if (strftime(datebuf, sizeof(datebuf), "%c %Z", tm) == 0)
9018 return got_error(GOT_ERR_NO_SPACE);
9019 printf("timestamp: %s\n", datebuf);
9021 if (blob_id) {
9022 err = got_object_id_str(&id_str, blob_id);
9023 if (err)
9024 return err;
9025 printf("based on blob: %s\n", id_str);
9026 free(id_str);
9029 if (staged_blob_id) {
9030 err = got_object_id_str(&id_str, staged_blob_id);
9031 if (err)
9032 return err;
9033 printf("based on staged blob: %s\n", id_str);
9034 free(id_str);
9037 if (commit_id) {
9038 err = got_object_id_str(&id_str, commit_id);
9039 if (err)
9040 return err;
9041 printf("based on commit: %s\n", id_str);
9042 free(id_str);
9045 return NULL;
9048 static const struct got_error *
9049 cmd_info(int argc, char *argv[])
9051 const struct got_error *error = NULL;
9052 struct got_repository *repo = NULL;
9053 struct got_worktree *worktree = NULL;
9054 struct got_fileindex *fileindex = NULL;
9055 char *cwd = NULL, *id_str = NULL;
9056 struct got_pathlist_head paths;
9057 char *uuidstr = NULL;
9058 int ch, show_files = 0;
9059 int *pack_fds = NULL;
9061 RB_INIT(&paths);
9063 #ifndef PROFILE
9064 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
9065 NULL) == -1)
9066 err(1, "pledge");
9067 #endif
9069 while ((ch = getopt(argc, argv, "")) != -1) {
9070 switch (ch) {
9071 default:
9072 usage_info();
9073 /* NOTREACHED */
9077 argc -= optind;
9078 argv += optind;
9080 cwd = getcwd(NULL, 0);
9081 if (cwd == NULL) {
9082 error = got_error_from_errno("getcwd");
9083 goto done;
9086 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_CVG_DIR);
9087 if (error) {
9088 if (error->code == GOT_ERR_NOT_WORKTREE)
9089 error = wrap_not_worktree_error(error, "info", cwd);
9090 goto done;
9093 error = got_repo_pack_fds_open(&pack_fds);
9094 if (error != NULL)
9095 goto done;
9097 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree), NULL,
9098 pack_fds);
9099 if (error)
9100 goto done;
9102 #ifndef PROFILE
9103 /* Remove "wpath cpath proc exec sendfd" promises. */
9104 if (pledge("stdio rpath flock unveil", NULL) == -1)
9105 err(1, "pledge");
9106 #endif
9107 error = apply_unveil(NULL, 0, got_worktree_get_root_path(worktree));
9108 if (error)
9109 goto done;
9111 if (argc >= 1) {
9112 error = get_worktree_paths_from_argv(&paths, argc, argv,
9113 worktree);
9114 if (error)
9115 goto done;
9116 show_files = 1;
9119 error = got_worktree_path_info_prepare(&fileindex, worktree, repo);
9120 if (error)
9121 goto done;
9123 error = got_object_id_str(&id_str,
9124 got_worktree_get_base_commit_id(worktree));
9125 if (error)
9126 goto done;
9128 error = got_worktree_get_uuid(&uuidstr, worktree);
9129 if (error)
9130 goto done;
9132 printf("work tree: %s\n", got_worktree_get_root_path(worktree));
9133 printf("work tree base commit: %s\n", id_str);
9134 printf("work tree path prefix: %s\n",
9135 got_worktree_get_path_prefix(worktree));
9136 printf("work tree branch reference: %s\n",
9137 got_worktree_get_head_ref_name(worktree));
9138 printf("work tree UUID: %s\n", uuidstr);
9139 printf("work tree format version: %d\n",
9140 got_worktree_get_format_version(worktree));
9141 printf("file index version: %u\n",
9142 got_worktree_get_fileindex_version(fileindex));
9143 printf("repository: %s\n", got_worktree_get_repo_path(worktree));
9145 if (show_files) {
9146 struct got_pathlist_entry *pe;
9147 RB_FOREACH(pe, got_pathlist_head, &paths) {
9148 if (pe->path_len == 0)
9149 continue;
9151 * Assume this path will fail. This will be corrected
9152 * in print_path_info() in case the path does suceeed.
9154 pe->data = (void *)got_error(GOT_ERR_BAD_PATH);
9156 error = got_worktree_path_info(worktree, fileindex, &paths,
9157 print_path_info, &paths, check_cancelled, NULL);
9158 if (error)
9159 goto done;
9160 RB_FOREACH(pe, got_pathlist_head, &paths) {
9161 if (pe->data != NULL) {
9162 const struct got_error *perr;
9164 perr = pe->data;
9165 error = got_error_path(pe->path, perr->code);
9166 break;
9170 done:
9171 if (worktree) {
9172 const struct got_error *cerr;
9174 cerr = got_worktree_path_info_complete(fileindex, worktree);
9175 if (error == NULL)
9176 error = cerr;
9177 got_worktree_close(worktree);
9179 if (repo) {
9180 const struct got_error *close_err = got_repo_close(repo);
9181 if (error == NULL)
9182 error = close_err;
9184 if (pack_fds) {
9185 const struct got_error *pack_err =
9186 got_repo_pack_fds_close(pack_fds);
9187 if (error == NULL)
9188 error = pack_err;
9190 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
9191 free(cwd);
9192 free(id_str);
9193 free(uuidstr);
9194 return error;