Blob


1 /*
2 * Copyright (c) 2017 Martin Pieuchot <mpi@openbsd.org>
3 * Copyright (c) 2018, 2019, 2020 Stefan Sperling <stsp@openbsd.org>
4 * Copyright (c) 2020 Ori Bernstein <ori@openbsd.org>
5 * Copyright (C) 2023 Josh Rickmar <jrick@zettaport.com>
6 *
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.
10 *
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.
18 */
20 #include <sys/queue.h>
21 #include <sys/time.h>
22 #include <sys/types.h>
23 #include <sys/stat.h>
24 #include <sys/wait.h>
26 #include <err.h>
27 #include <errno.h>
28 #include <fcntl.h>
29 #include <limits.h>
30 #include <locale.h>
31 #include <ctype.h>
32 #include <sha1.h>
33 #include <sha2.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>
44 #include <util.h>
46 #include "got_version.h"
47 #include "got_error.h"
48 #include "got_object.h"
49 #include "got_reference.h"
50 #include "got_repository.h"
51 #include "got_path.h"
52 #include "got_cancel.h"
53 #include "got_worktree.h"
54 #include "got_worktree_cvg.h"
55 #include "got_diff.h"
56 #include "got_commit_graph.h"
57 #include "got_fetch.h"
58 #include "got_send.h"
59 #include "got_blame.h"
60 #include "got_privsep.h"
61 #include "got_opentemp.h"
62 #include "got_gotconfig.h"
63 #include "got_dial.h"
64 #include "got_patch.h"
65 #include "got_sigs.h"
66 #include "got_date.h"
68 #ifndef nitems
69 #define nitems(_a) (sizeof((_a)) / sizeof((_a)[0]))
70 #endif
72 #ifndef GOT_DEFAULT_EDITOR
73 #define GOT_DEFAULT_EDITOR "/usr/bin/vi"
74 #endif
76 static volatile sig_atomic_t sigint_received;
77 static volatile sig_atomic_t sigpipe_received;
79 static void
80 catch_sigint(int signo)
81 {
82 sigint_received = 1;
83 }
85 static void
86 catch_sigpipe(int signo)
87 {
88 sigpipe_received = 1;
89 }
92 struct got_cmd {
93 const char *cmd_name;
94 const struct got_error *(*cmd_main)(int, char *[]);
95 void (*cmd_usage)(void);
96 const char *cmd_alias;
97 };
99 __dead static void usage(int, int);
100 __dead static void usage_import(void);
101 __dead static void usage_clone(void);
102 __dead static void usage_checkout(void);
103 __dead static void usage_update(void);
104 __dead static void usage_log(void);
105 __dead static void usage_diff(void);
106 __dead static void usage_blame(void);
107 __dead static void usage_tree(void);
108 __dead static void usage_status(void);
109 __dead static void usage_tag(void);
110 __dead static void usage_add(void);
111 __dead static void usage_remove(void);
112 __dead static void usage_patch(void);
113 __dead static void usage_revert(void);
114 __dead static void usage_commit(void);
115 __dead static void usage_cherrypick(void);
116 __dead static void usage_backout(void);
117 __dead static void usage_cat(void);
118 __dead static void usage_info(void);
120 static const struct got_error* cmd_import(int, char *[]);
121 static const struct got_error* cmd_clone(int, char *[]);
122 static const struct got_error* cmd_checkout(int, char *[]);
123 static const struct got_error* cmd_update(int, char *[]);
124 static const struct got_error* cmd_log(int, char *[]);
125 static const struct got_error* cmd_diff(int, char *[]);
126 static const struct got_error* cmd_blame(int, char *[]);
127 static const struct got_error* cmd_tree(int, char *[]);
128 static const struct got_error* cmd_status(int, char *[]);
129 static const struct got_error* cmd_tag(int, char *[]);
130 static const struct got_error* cmd_add(int, char *[]);
131 static const struct got_error* cmd_remove(int, char *[]);
132 static const struct got_error* cmd_patch(int, char *[]);
133 static const struct got_error* cmd_revert(int, char *[]);
134 static const struct got_error* cmd_commit(int, char *[]);
135 static const struct got_error* cmd_cherrypick(int, char *[]);
136 static const struct got_error* cmd_backout(int, char *[]);
137 static const struct got_error* cmd_cat(int, char *[]);
138 static const struct got_error* cmd_info(int, char *[]);
140 static const struct got_cmd got_commands[] = {
141 { "import", cmd_import, usage_import, "im" },
142 { "clone", cmd_clone, usage_clone, "cl" },
143 { "checkout", cmd_checkout, usage_checkout, "co" },
144 { "update", cmd_update, usage_update, "up" },
145 { "log", cmd_log, usage_log, "" },
146 { "diff", cmd_diff, usage_diff, "di" },
147 { "blame", cmd_blame, usage_blame, "bl" },
148 { "tree", cmd_tree, usage_tree, "tr" },
149 { "status", cmd_status, usage_status, "st" },
150 { "tag", cmd_tag, usage_tag, "" },
151 { "add", cmd_add, usage_add, "" },
152 { "remove", cmd_remove, usage_remove, "rm" },
153 { "patch", cmd_patch, usage_patch, "pa" },
154 { "revert", cmd_revert, usage_revert, "rv" },
155 { "commit", cmd_commit, usage_commit, "ci" },
156 { "cherrypick", cmd_cherrypick, usage_cherrypick, "cy" },
157 { "backout", cmd_backout, usage_backout, "bo" },
158 { "cat", cmd_cat, usage_cat, "" },
159 { "info", cmd_info, usage_info, "" },
160 };
162 static void
163 list_commands(FILE *fp)
165 size_t i;
167 fprintf(fp, "commands:");
168 for (i = 0; i < nitems(got_commands); i++) {
169 const struct got_cmd *cmd = &got_commands[i];
170 fprintf(fp, " %s", cmd->cmd_name);
172 fputc('\n', fp);
175 __dead static void
176 option_conflict(char a, char b)
178 errx(1, "-%c and -%c options are mutually exclusive", a, b);
181 int
182 main(int argc, char *argv[])
184 const struct got_cmd *cmd;
185 size_t i;
186 int ch;
187 int hflag = 0, Vflag = 0;
188 static const struct option longopts[] = {
189 { "version", no_argument, NULL, 'V' },
190 { NULL, 0, NULL, 0 }
191 };
193 setlocale(LC_CTYPE, "");
195 while ((ch = getopt_long(argc, argv, "+hV", longopts, NULL)) != -1) {
196 switch (ch) {
197 case 'h':
198 hflag = 1;
199 break;
200 case 'V':
201 Vflag = 1;
202 break;
203 default:
204 usage(hflag, 1);
205 /* NOTREACHED */
209 argc -= optind;
210 argv += optind;
211 optind = 1;
212 optreset = 1;
214 if (Vflag) {
215 got_version_print_str();
216 return 0;
219 if (argc <= 0)
220 usage(hflag, hflag ? 0 : 1);
222 signal(SIGINT, catch_sigint);
223 signal(SIGPIPE, catch_sigpipe);
225 for (i = 0; i < nitems(got_commands); i++) {
226 const struct got_error *error;
228 cmd = &got_commands[i];
230 if (strcmp(cmd->cmd_name, argv[0]) != 0 &&
231 strcmp(cmd->cmd_alias, argv[0]) != 0)
232 continue;
234 if (hflag)
235 cmd->cmd_usage();
237 error = cmd->cmd_main(argc, argv);
238 if (error && error->code != GOT_ERR_CANCELLED &&
239 error->code != GOT_ERR_PRIVSEP_EXIT &&
240 !(sigpipe_received &&
241 error->code == GOT_ERR_ERRNO && errno == EPIPE) &&
242 !(sigint_received &&
243 error->code == GOT_ERR_ERRNO && errno == EINTR)) {
244 fflush(stdout);
245 fprintf(stderr, "%s: %s\n", getprogname(), error->msg);
246 return 1;
249 return 0;
252 fprintf(stderr, "%s: unknown command '%s'\n", getprogname(), argv[0]);
253 list_commands(stderr);
254 return 1;
257 __dead static void
258 usage(int hflag, int status)
260 FILE *fp = (status == 0) ? stdout : stderr;
262 fprintf(fp, "usage: %s [-hV] command [arg ...]\n",
263 getprogname());
264 if (hflag)
265 list_commands(fp);
266 exit(status);
269 static const struct got_error *
270 get_editor(char **abspath)
272 const struct got_error *err = NULL;
273 const char *editor;
275 *abspath = NULL;
277 editor = getenv("VISUAL");
278 if (editor == NULL)
279 editor = getenv("EDITOR");
281 if (editor) {
282 err = got_path_find_prog(abspath, editor);
283 if (err)
284 return err;
287 if (*abspath == NULL) {
288 *abspath = strdup(GOT_DEFAULT_EDITOR);
289 if (*abspath == NULL)
290 return got_error_from_errno("strdup");
293 return NULL;
296 static const struct got_error *
297 apply_unveil(const char *repo_path, int repo_read_only,
298 const char *worktree_path)
300 const struct got_error *err;
302 #ifdef PROFILE
303 if (unveil("gmon.out", "rwc") != 0)
304 return got_error_from_errno2("unveil", "gmon.out");
305 #endif
306 if (repo_path && unveil(repo_path, repo_read_only ? "r" : "rwc") != 0)
307 return got_error_from_errno2("unveil", repo_path);
309 if (worktree_path && unveil(worktree_path, "rwc") != 0)
310 return got_error_from_errno2("unveil", worktree_path);
312 if (unveil(GOT_TMPDIR_STR, "rwc") != 0)
313 return got_error_from_errno2("unveil", GOT_TMPDIR_STR);
315 err = got_privsep_unveil_exec_helpers();
316 if (err != NULL)
317 return err;
319 if (unveil(NULL, NULL) != 0)
320 return got_error_from_errno("unveil");
322 return NULL;
325 __dead static void
326 usage_import(void)
328 fprintf(stderr, "usage: %s import [-b branch] [-I pattern] [-m message] "
329 "[-r repository-path] directory\n", getprogname());
330 exit(1);
333 static int
334 spawn_editor(const char *editor, const char *file)
336 pid_t pid;
337 sig_t sighup, sigint, sigquit;
338 int st = -1;
340 sighup = signal(SIGHUP, SIG_IGN);
341 sigint = signal(SIGINT, SIG_IGN);
342 sigquit = signal(SIGQUIT, SIG_IGN);
344 switch (pid = fork()) {
345 case -1:
346 goto doneediting;
347 case 0:
348 execl(editor, editor, file, (char *)NULL);
349 _exit(127);
352 while (waitpid(pid, &st, 0) == -1)
353 if (errno != EINTR)
354 break;
356 doneediting:
357 (void)signal(SIGHUP, sighup);
358 (void)signal(SIGINT, sigint);
359 (void)signal(SIGQUIT, sigquit);
361 if (!WIFEXITED(st)) {
362 errno = EINTR;
363 return -1;
366 return WEXITSTATUS(st);
369 static const struct got_error *
370 read_logmsg(char **logmsg, size_t *len, FILE *fp, size_t filesize)
372 const struct got_error *err = NULL;
373 char *line = NULL;
374 size_t linesize = 0;
376 *logmsg = NULL;
377 *len = 0;
379 if (fseeko(fp, 0L, SEEK_SET) == -1)
380 return got_error_from_errno("fseeko");
382 *logmsg = malloc(filesize + 1);
383 if (*logmsg == NULL)
384 return got_error_from_errno("malloc");
385 (*logmsg)[0] = '\0';
387 while (getline(&line, &linesize, fp) != -1) {
388 if (line[0] == '#' || (*len == 0 && line[0] == '\n'))
389 continue; /* remove comments and leading empty lines */
390 *len = strlcat(*logmsg, line, filesize + 1);
391 if (*len >= filesize + 1) {
392 err = got_error(GOT_ERR_NO_SPACE);
393 goto done;
396 if (ferror(fp)) {
397 err = got_ferror(fp, GOT_ERR_IO);
398 goto done;
401 while (*len > 0 && (*logmsg)[*len - 1] == '\n') {
402 (*logmsg)[*len - 1] = '\0';
403 (*len)--;
405 done:
406 free(line);
407 if (err) {
408 free(*logmsg);
409 *logmsg = NULL;
410 *len = 0;
412 return err;
415 static const struct got_error *
416 edit_logmsg(char **logmsg, const char *editor, const char *logmsg_path,
417 const char *initial_content, size_t initial_content_len,
418 int require_modification)
420 const struct got_error *err = NULL;
421 struct stat st, st2;
422 FILE *fp = NULL;
423 size_t logmsg_len;
425 *logmsg = NULL;
427 if (stat(logmsg_path, &st) == -1)
428 return got_error_from_errno2("stat", logmsg_path);
430 if (spawn_editor(editor, logmsg_path) == -1)
431 return got_error_from_errno("failed spawning editor");
433 if (require_modification) {
434 struct timespec timeout;
436 timeout.tv_sec = 0;
437 timeout.tv_nsec = 1;
438 nanosleep(&timeout, NULL);
441 if (stat(logmsg_path, &st2) == -1)
442 return got_error_from_errno2("stat", logmsg_path);
444 if (require_modification && st.st_size == st2.st_size &&
445 timespeccmp(&st.st_mtim, &st2.st_mtim, ==))
446 return got_error_msg(GOT_ERR_COMMIT_MSG_EMPTY,
447 "no changes made to commit message, aborting");
449 fp = fopen(logmsg_path, "re");
450 if (fp == NULL) {
451 err = got_error_from_errno("fopen");
452 goto done;
455 /* strip comments and leading/trailing newlines */
456 err = read_logmsg(logmsg, &logmsg_len, fp, st2.st_size);
457 if (err)
458 goto done;
459 if (logmsg_len == 0) {
460 err = got_error_msg(GOT_ERR_COMMIT_MSG_EMPTY,
461 "commit message cannot be empty, aborting");
462 goto done;
464 done:
465 if (fp && fclose(fp) == EOF && err == NULL)
466 err = got_error_from_errno("fclose");
467 if (err) {
468 free(*logmsg);
469 *logmsg = NULL;
471 return err;
474 static const struct got_error *
475 collect_import_msg(char **logmsg, char **logmsg_path, const char *editor,
476 const char *path_dir, const char *branch_name)
478 char *initial_content = NULL;
479 const struct got_error *err = NULL;
480 int initial_content_len;
481 int fd = -1;
483 initial_content_len = asprintf(&initial_content,
484 "\n# %s to be imported to branch %s\n", path_dir,
485 branch_name);
486 if (initial_content_len == -1)
487 return got_error_from_errno("asprintf");
489 err = got_opentemp_named_fd(logmsg_path, &fd,
490 GOT_TMPDIR_STR "/got-importmsg", "");
491 if (err)
492 goto done;
494 if (write(fd, initial_content, initial_content_len) == -1) {
495 err = got_error_from_errno2("write", *logmsg_path);
496 goto done;
498 if (close(fd) == -1) {
499 err = got_error_from_errno2("close", *logmsg_path);
500 goto done;
502 fd = -1;
504 err = edit_logmsg(logmsg, editor, *logmsg_path, initial_content,
505 initial_content_len, 1);
506 done:
507 if (fd != -1 && close(fd) == -1 && err == NULL)
508 err = got_error_from_errno2("close", *logmsg_path);
509 free(initial_content);
510 if (err) {
511 free(*logmsg_path);
512 *logmsg_path = NULL;
514 return err;
517 static const struct got_error *
518 import_progress(void *arg, const char *path)
520 printf("A %s\n", path);
521 return NULL;
524 static const struct got_error *
525 valid_author(const char *author)
527 const char *email = author;
529 /*
530 * Git' expects the author (or committer) to be in the form
531 * "name <email>", which are mostly free form (see the
532 * "committer" description in git-fast-import(1)). We're only
533 * doing this to avoid git's object parser breaking on commits
534 * we create.
535 */
537 while (*author && *author != '\n' && *author != '<' && *author != '>')
538 author++;
539 if (author != email && *author == '<' && *(author - 1) != ' ')
540 return got_error_fmt(GOT_ERR_COMMIT_BAD_AUTHOR, "%s: space "
541 "between author name and email required", email);
542 if (*author++ != '<')
543 return got_error_fmt(GOT_ERR_COMMIT_NO_EMAIL, "%s", email);
544 while (*author && *author != '\n' && *author != '<' && *author != '>')
545 author++;
546 if (strcmp(author, ">") != 0)
547 return got_error_fmt(GOT_ERR_COMMIT_NO_EMAIL, "%s", email);
548 return NULL;
551 static const struct got_error *
552 get_author(char **author, struct got_repository *repo,
553 struct got_worktree *worktree)
555 const struct got_error *err = NULL;
556 const char *got_author = NULL, *name, *email;
557 const struct got_gotconfig *worktree_conf = NULL, *repo_conf = NULL;
559 *author = NULL;
561 if (worktree)
562 worktree_conf = got_worktree_get_gotconfig(worktree);
563 repo_conf = got_repo_get_gotconfig(repo);
565 /*
566 * Priority of potential author information sources, from most
567 * significant to least significant:
568 * 1) work tree's .got/got.conf file
569 * 2) repository's got.conf file
570 * 3) repository's git config file
571 * 4) environment variables
572 * 5) global git config files (in user's home directory or /etc)
573 */
575 if (worktree_conf)
576 got_author = got_gotconfig_get_author(worktree_conf);
577 if (got_author == NULL)
578 got_author = got_gotconfig_get_author(repo_conf);
579 if (got_author == NULL) {
580 name = got_repo_get_gitconfig_author_name(repo);
581 email = got_repo_get_gitconfig_author_email(repo);
582 if (name && email) {
583 if (asprintf(author, "%s <%s>", name, email) == -1)
584 return got_error_from_errno("asprintf");
585 return NULL;
588 got_author = getenv("GOT_AUTHOR");
589 if (got_author == NULL) {
590 name = got_repo_get_global_gitconfig_author_name(repo);
591 email = got_repo_get_global_gitconfig_author_email(
592 repo);
593 if (name && email) {
594 if (asprintf(author, "%s <%s>", name, email)
595 == -1)
596 return got_error_from_errno("asprintf");
597 return NULL;
599 /* TODO: Look up user in password database? */
600 return got_error(GOT_ERR_COMMIT_NO_AUTHOR);
604 *author = strdup(got_author);
605 if (*author == NULL)
606 return got_error_from_errno("strdup");
608 err = valid_author(*author);
609 if (err) {
610 free(*author);
611 *author = NULL;
613 return err;
616 static const struct got_error *
617 get_allowed_signers(char **allowed_signers, struct got_repository *repo,
618 struct got_worktree *worktree)
620 const char *got_allowed_signers = NULL;
621 const struct got_gotconfig *worktree_conf = NULL, *repo_conf = NULL;
623 *allowed_signers = NULL;
625 if (worktree)
626 worktree_conf = got_worktree_get_gotconfig(worktree);
627 repo_conf = got_repo_get_gotconfig(repo);
629 /*
630 * Priority of potential author information sources, from most
631 * significant to least significant:
632 * 1) work tree's .got/got.conf file
633 * 2) repository's got.conf file
634 */
636 if (worktree_conf)
637 got_allowed_signers = got_gotconfig_get_allowed_signers_file(
638 worktree_conf);
639 if (got_allowed_signers == NULL)
640 got_allowed_signers = got_gotconfig_get_allowed_signers_file(
641 repo_conf);
643 if (got_allowed_signers) {
644 *allowed_signers = strdup(got_allowed_signers);
645 if (*allowed_signers == NULL)
646 return got_error_from_errno("strdup");
648 return NULL;
651 static const struct got_error *
652 get_revoked_signers(char **revoked_signers, struct got_repository *repo,
653 struct got_worktree *worktree)
655 const char *got_revoked_signers = NULL;
656 const struct got_gotconfig *worktree_conf = NULL, *repo_conf = NULL;
658 *revoked_signers = NULL;
660 if (worktree)
661 worktree_conf = got_worktree_get_gotconfig(worktree);
662 repo_conf = got_repo_get_gotconfig(repo);
664 /*
665 * Priority of potential author information sources, from most
666 * significant to least significant:
667 * 1) work tree's .got/got.conf file
668 * 2) repository's got.conf file
669 */
671 if (worktree_conf)
672 got_revoked_signers = got_gotconfig_get_revoked_signers_file(
673 worktree_conf);
674 if (got_revoked_signers == NULL)
675 got_revoked_signers = got_gotconfig_get_revoked_signers_file(
676 repo_conf);
678 if (got_revoked_signers) {
679 *revoked_signers = strdup(got_revoked_signers);
680 if (*revoked_signers == NULL)
681 return got_error_from_errno("strdup");
683 return NULL;
686 static const char *
687 get_signer_id(struct got_repository *repo, struct got_worktree *worktree)
689 const char *got_signer_id = NULL;
690 const struct got_gotconfig *worktree_conf = NULL, *repo_conf = NULL;
692 if (worktree)
693 worktree_conf = got_worktree_get_gotconfig(worktree);
694 repo_conf = got_repo_get_gotconfig(repo);
696 /*
697 * Priority of potential author information sources, from most
698 * significant to least significant:
699 * 1) work tree's .got/got.conf file
700 * 2) repository's got.conf file
701 */
703 if (worktree_conf)
704 got_signer_id = got_gotconfig_get_signer_id(worktree_conf);
705 if (got_signer_id == NULL)
706 got_signer_id = got_gotconfig_get_signer_id(repo_conf);
708 return got_signer_id;
711 static const struct got_error *
712 get_gitconfig_path(char **gitconfig_path)
714 const char *homedir = getenv("HOME");
716 *gitconfig_path = NULL;
717 if (homedir) {
718 if (asprintf(gitconfig_path, "%s/.gitconfig", homedir) == -1)
719 return got_error_from_errno("asprintf");
722 return NULL;
725 static const struct got_error *
726 cmd_import(int argc, char *argv[])
728 const struct got_error *error = NULL;
729 char *path_dir = NULL, *repo_path = NULL, *logmsg = NULL;
730 char *gitconfig_path = NULL, *editor = NULL, *author = NULL;
731 const char *branch_name = NULL;
732 char *id_str = NULL, *logmsg_path = NULL;
733 char refname[PATH_MAX] = "refs/heads/";
734 struct got_repository *repo = NULL;
735 struct got_reference *branch_ref = NULL, *head_ref = NULL;
736 struct got_object_id *new_commit_id = NULL;
737 int ch, n = 0;
738 struct got_pathlist_head ignores;
739 struct got_pathlist_entry *pe;
740 int preserve_logmsg = 0;
741 int *pack_fds = NULL;
743 TAILQ_INIT(&ignores);
745 #ifndef PROFILE
746 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
747 "unveil",
748 NULL) == -1)
749 err(1, "pledge");
750 #endif
752 while ((ch = getopt(argc, argv, "b:I:m:r:")) != -1) {
753 switch (ch) {
754 case 'b':
755 branch_name = optarg;
756 break;
757 case 'I':
758 if (optarg[0] == '\0')
759 break;
760 error = got_pathlist_insert(&pe, &ignores, optarg,
761 NULL);
762 if (error)
763 goto done;
764 break;
765 case 'm':
766 logmsg = strdup(optarg);
767 if (logmsg == NULL) {
768 error = got_error_from_errno("strdup");
769 goto done;
771 break;
772 case 'r':
773 repo_path = realpath(optarg, NULL);
774 if (repo_path == NULL) {
775 error = got_error_from_errno2("realpath",
776 optarg);
777 goto done;
779 break;
780 default:
781 usage_import();
782 /* NOTREACHED */
786 argc -= optind;
787 argv += optind;
789 if (argc != 1)
790 usage_import();
792 if (repo_path == NULL) {
793 repo_path = getcwd(NULL, 0);
794 if (repo_path == NULL)
795 return got_error_from_errno("getcwd");
797 got_path_strip_trailing_slashes(repo_path);
798 error = get_gitconfig_path(&gitconfig_path);
799 if (error)
800 goto done;
801 error = got_repo_pack_fds_open(&pack_fds);
802 if (error != NULL)
803 goto done;
804 error = got_repo_open(&repo, repo_path, gitconfig_path, pack_fds);
805 if (error)
806 goto done;
808 error = get_author(&author, repo, NULL);
809 if (error)
810 return error;
812 /*
813 * Don't let the user create a branch name with a leading '-'.
814 * While technically a valid reference name, this case is usually
815 * an unintended typo.
816 */
817 if (branch_name && branch_name[0] == '-')
818 return got_error_path(branch_name, GOT_ERR_REF_NAME_MINUS);
820 error = got_ref_open(&head_ref, repo, GOT_REF_HEAD, 0);
821 if (error && error->code != GOT_ERR_NOT_REF)
822 goto done;
824 if (branch_name)
825 n = strlcat(refname, branch_name, sizeof(refname));
826 else if (head_ref && got_ref_is_symbolic(head_ref))
827 n = strlcpy(refname, got_ref_get_symref_target(head_ref),
828 sizeof(refname));
829 else
830 n = strlcat(refname, "main", sizeof(refname));
831 if (n >= sizeof(refname)) {
832 error = got_error(GOT_ERR_NO_SPACE);
833 goto done;
836 error = got_ref_open(&branch_ref, repo, refname, 0);
837 if (error) {
838 if (error->code != GOT_ERR_NOT_REF)
839 goto done;
840 } else {
841 error = got_error_msg(GOT_ERR_BRANCH_EXISTS,
842 "import target branch already exists");
843 goto done;
846 path_dir = realpath(argv[0], NULL);
847 if (path_dir == NULL) {
848 error = got_error_from_errno2("realpath", argv[0]);
849 goto done;
851 got_path_strip_trailing_slashes(path_dir);
853 /*
854 * unveil(2) traverses exec(2); if an editor is used we have
855 * to apply unveil after the log message has been written.
856 */
857 if (logmsg == NULL || *logmsg == '\0') {
858 error = get_editor(&editor);
859 if (error)
860 goto done;
861 free(logmsg);
862 error = collect_import_msg(&logmsg, &logmsg_path, editor,
863 path_dir, refname);
864 if (error) {
865 if (error->code != GOT_ERR_COMMIT_MSG_EMPTY &&
866 logmsg_path != NULL)
867 preserve_logmsg = 1;
868 goto done;
872 if (unveil(path_dir, "r") != 0) {
873 error = got_error_from_errno2("unveil", path_dir);
874 if (logmsg_path)
875 preserve_logmsg = 1;
876 goto done;
879 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
880 if (error) {
881 if (logmsg_path)
882 preserve_logmsg = 1;
883 goto done;
886 error = got_repo_import(&new_commit_id, path_dir, logmsg,
887 author, &ignores, repo, import_progress, NULL);
888 if (error) {
889 if (logmsg_path)
890 preserve_logmsg = 1;
891 goto done;
894 error = got_ref_alloc(&branch_ref, refname, new_commit_id);
895 if (error) {
896 if (logmsg_path)
897 preserve_logmsg = 1;
898 goto done;
901 error = got_ref_write(branch_ref, repo);
902 if (error) {
903 if (logmsg_path)
904 preserve_logmsg = 1;
905 goto done;
908 error = got_object_id_str(&id_str, new_commit_id);
909 if (error) {
910 if (logmsg_path)
911 preserve_logmsg = 1;
912 goto done;
915 error = got_ref_open(&head_ref, repo, GOT_REF_HEAD, 0);
916 if (error) {
917 if (error->code != GOT_ERR_NOT_REF) {
918 if (logmsg_path)
919 preserve_logmsg = 1;
920 goto done;
923 error = got_ref_alloc_symref(&head_ref, GOT_REF_HEAD,
924 branch_ref);
925 if (error) {
926 if (logmsg_path)
927 preserve_logmsg = 1;
928 goto done;
931 error = got_ref_write(head_ref, repo);
932 if (error) {
933 if (logmsg_path)
934 preserve_logmsg = 1;
935 goto done;
939 printf("Created branch %s with commit %s\n",
940 got_ref_get_name(branch_ref), id_str);
941 done:
942 if (pack_fds) {
943 const struct got_error *pack_err =
944 got_repo_pack_fds_close(pack_fds);
945 if (error == NULL)
946 error = pack_err;
948 if (repo) {
949 const struct got_error *close_err = got_repo_close(repo);
950 if (error == NULL)
951 error = close_err;
953 if (preserve_logmsg) {
954 fprintf(stderr, "%s: log message preserved in %s\n",
955 getprogname(), logmsg_path);
956 } else if (logmsg_path && unlink(logmsg_path) == -1 && error == NULL)
957 error = got_error_from_errno2("unlink", logmsg_path);
958 free(logmsg);
959 free(logmsg_path);
960 free(repo_path);
961 free(editor);
962 free(new_commit_id);
963 free(id_str);
964 free(author);
965 free(gitconfig_path);
966 if (branch_ref)
967 got_ref_close(branch_ref);
968 if (head_ref)
969 got_ref_close(head_ref);
970 return error;
973 __dead static void
974 usage_clone(void)
976 fprintf(stderr, "usage: %s clone [-almqv] [-b branch] [-R reference] "
977 "repository-URL [directory]\n", getprogname());
978 exit(1);
981 struct got_fetch_progress_arg {
982 char last_scaled_size[FMT_SCALED_STRSIZE];
983 int last_p_indexed;
984 int last_p_resolved;
985 int verbosity;
987 struct got_repository *repo;
989 int create_configs;
990 int configs_created;
991 struct {
992 struct got_pathlist_head *symrefs;
993 struct got_pathlist_head *wanted_branches;
994 struct got_pathlist_head *wanted_refs;
995 const char *proto;
996 const char *host;
997 const char *port;
998 const char *remote_repo_path;
999 const char *git_url;
1000 int fetch_all_branches;
1001 int mirror_references;
1002 } config_info;
1005 /* XXX forward declaration */
1006 static const struct got_error *
1007 create_config_files(const char *proto, const char *host, const char *port,
1008 const char *remote_repo_path, const char *git_url, int fetch_all_branches,
1009 int mirror_references, struct got_pathlist_head *symrefs,
1010 struct got_pathlist_head *wanted_branches,
1011 struct got_pathlist_head *wanted_refs, struct got_repository *repo);
1013 static const struct got_error *
1014 fetch_progress(void *arg, const char *message, off_t packfile_size,
1015 int nobj_total, int nobj_indexed, int nobj_loose, int nobj_resolved)
1017 const struct got_error *err = NULL;
1018 struct got_fetch_progress_arg *a = arg;
1019 char scaled_size[FMT_SCALED_STRSIZE];
1020 int p_indexed, p_resolved;
1021 int print_size = 0, print_indexed = 0, print_resolved = 0;
1024 * In order to allow a failed clone to be resumed with 'got fetch'
1025 * we try to create configuration files as soon as possible.
1026 * Once the server has sent information about its default branch
1027 * we have all required information.
1029 if (a->create_configs && !a->configs_created &&
1030 !TAILQ_EMPTY(a->config_info.symrefs)) {
1031 err = create_config_files(a->config_info.proto,
1032 a->config_info.host, a->config_info.port,
1033 a->config_info.remote_repo_path,
1034 a->config_info.git_url,
1035 a->config_info.fetch_all_branches,
1036 a->config_info.mirror_references,
1037 a->config_info.symrefs,
1038 a->config_info.wanted_branches,
1039 a->config_info.wanted_refs, a->repo);
1040 if (err)
1041 return err;
1042 a->configs_created = 1;
1045 if (a->verbosity < 0)
1046 return NULL;
1048 if (message && message[0] != '\0') {
1049 printf("\rserver: %s", message);
1050 fflush(stdout);
1051 return NULL;
1054 if (packfile_size > 0 || nobj_indexed > 0) {
1055 if (fmt_scaled(packfile_size, scaled_size) == 0 &&
1056 (a->last_scaled_size[0] == '\0' ||
1057 strcmp(scaled_size, a->last_scaled_size)) != 0) {
1058 print_size = 1;
1059 if (strlcpy(a->last_scaled_size, scaled_size,
1060 FMT_SCALED_STRSIZE) >= FMT_SCALED_STRSIZE)
1061 return got_error(GOT_ERR_NO_SPACE);
1063 if (nobj_indexed > 0) {
1064 p_indexed = (nobj_indexed * 100) / nobj_total;
1065 if (p_indexed != a->last_p_indexed) {
1066 a->last_p_indexed = p_indexed;
1067 print_indexed = 1;
1068 print_size = 1;
1071 if (nobj_resolved > 0) {
1072 p_resolved = (nobj_resolved * 100) /
1073 (nobj_total - nobj_loose);
1074 if (p_resolved != a->last_p_resolved) {
1075 a->last_p_resolved = p_resolved;
1076 print_resolved = 1;
1077 print_indexed = 1;
1078 print_size = 1;
1083 if (print_size || print_indexed || print_resolved)
1084 printf("\r");
1085 if (print_size)
1086 printf("%*s fetched", FMT_SCALED_STRSIZE - 2, scaled_size);
1087 if (print_indexed)
1088 printf("; indexing %d%%", p_indexed);
1089 if (print_resolved)
1090 printf("; resolving deltas %d%%", p_resolved);
1091 if (print_size || print_indexed || print_resolved)
1092 fflush(stdout);
1094 return NULL;
1097 static const struct got_error *
1098 create_symref(const char *refname, struct got_reference *target_ref,
1099 int verbosity, struct got_repository *repo)
1101 const struct got_error *err;
1102 struct got_reference *head_symref;
1104 err = got_ref_alloc_symref(&head_symref, refname, target_ref);
1105 if (err)
1106 return err;
1108 err = got_ref_write(head_symref, repo);
1109 if (err == NULL && verbosity > 0) {
1110 printf("Created reference %s: %s\n", GOT_REF_HEAD,
1111 got_ref_get_name(target_ref));
1113 got_ref_close(head_symref);
1114 return err;
1117 static const struct got_error *
1118 list_remote_refs(struct got_pathlist_head *symrefs,
1119 struct got_pathlist_head *refs)
1121 const struct got_error *err;
1122 struct got_pathlist_entry *pe;
1124 TAILQ_FOREACH(pe, symrefs, entry) {
1125 const char *refname = pe->path;
1126 const char *targetref = pe->data;
1128 printf("%s: %s\n", refname, targetref);
1131 TAILQ_FOREACH(pe, refs, entry) {
1132 const char *refname = pe->path;
1133 struct got_object_id *id = pe->data;
1134 char *id_str;
1136 err = got_object_id_str(&id_str, id);
1137 if (err)
1138 return err;
1139 printf("%s: %s\n", refname, id_str);
1140 free(id_str);
1143 return NULL;
1146 static const struct got_error *
1147 create_ref(const char *refname, struct got_object_id *id,
1148 int verbosity, struct got_repository *repo)
1150 const struct got_error *err = NULL;
1151 struct got_reference *ref;
1152 char *id_str;
1154 err = got_object_id_str(&id_str, id);
1155 if (err)
1156 return err;
1158 err = got_ref_alloc(&ref, refname, id);
1159 if (err)
1160 goto done;
1162 err = got_ref_write(ref, repo);
1163 got_ref_close(ref);
1165 if (err == NULL && verbosity >= 0)
1166 printf("Created reference %s: %s\n", refname, id_str);
1167 done:
1168 free(id_str);
1169 return err;
1172 static int
1173 match_wanted_ref(const char *refname, const char *wanted_ref)
1175 if (strncmp(refname, "refs/", 5) != 0)
1176 return 0;
1177 refname += 5;
1180 * Prevent fetching of references that won't make any
1181 * sense outside of the remote repository's context.
1183 if (strncmp(refname, "got/", 4) == 0)
1184 return 0;
1185 if (strncmp(refname, "remotes/", 8) == 0)
1186 return 0;
1188 if (strncmp(wanted_ref, "refs/", 5) == 0)
1189 wanted_ref += 5;
1191 /* Allow prefix match. */
1192 if (got_path_is_child(refname, wanted_ref, strlen(wanted_ref)))
1193 return 1;
1195 /* Allow exact match. */
1196 return (strcmp(refname, wanted_ref) == 0);
1199 static int
1200 is_wanted_ref(struct got_pathlist_head *wanted_refs, const char *refname)
1202 struct got_pathlist_entry *pe;
1204 TAILQ_FOREACH(pe, wanted_refs, entry) {
1205 if (match_wanted_ref(refname, pe->path))
1206 return 1;
1209 return 0;
1212 static const struct got_error *
1213 create_wanted_ref(const char *refname, struct got_object_id *id,
1214 const char *remote_repo_name, int verbosity, struct got_repository *repo)
1216 const struct got_error *err;
1217 char *remote_refname;
1219 if (strncmp("refs/", refname, 5) == 0)
1220 refname += 5;
1222 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
1223 remote_repo_name, refname) == -1)
1224 return got_error_from_errno("asprintf");
1226 err = create_ref(remote_refname, id, verbosity, repo);
1227 free(remote_refname);
1228 return err;
1231 static const struct got_error *
1232 create_gotconfig(const char *proto, const char *host, const char *port,
1233 const char *remote_repo_path, const char *default_branch,
1234 int fetch_all_branches, struct got_pathlist_head *wanted_branches,
1235 struct got_pathlist_head *wanted_refs, int mirror_references,
1236 struct got_repository *repo)
1238 const struct got_error *err = NULL;
1239 char *gotconfig_path = NULL;
1240 char *gotconfig = NULL;
1241 FILE *gotconfig_file = NULL;
1242 const char *branchname = NULL;
1243 char *branches = NULL, *refs = NULL;
1244 ssize_t n;
1246 if (!fetch_all_branches && !TAILQ_EMPTY(wanted_branches)) {
1247 struct got_pathlist_entry *pe;
1248 TAILQ_FOREACH(pe, wanted_branches, entry) {
1249 char *s;
1250 branchname = pe->path;
1251 if (strncmp(branchname, "refs/heads/", 11) == 0)
1252 branchname += 11;
1253 if (asprintf(&s, "%s\"%s\" ",
1254 branches ? branches : "", branchname) == -1) {
1255 err = got_error_from_errno("asprintf");
1256 goto done;
1258 free(branches);
1259 branches = s;
1261 } else if (!fetch_all_branches && default_branch) {
1262 branchname = default_branch;
1263 if (strncmp(branchname, "refs/heads/", 11) == 0)
1264 branchname += 11;
1265 if (asprintf(&branches, "\"%s\" ", branchname) == -1) {
1266 err = got_error_from_errno("asprintf");
1267 goto done;
1270 if (!TAILQ_EMPTY(wanted_refs)) {
1271 struct got_pathlist_entry *pe;
1272 TAILQ_FOREACH(pe, wanted_refs, entry) {
1273 char *s;
1274 const char *refname = pe->path;
1275 if (strncmp(refname, "refs/", 5) == 0)
1276 branchname += 5;
1277 if (asprintf(&s, "%s\"%s\" ",
1278 refs ? refs : "", refname) == -1) {
1279 err = got_error_from_errno("asprintf");
1280 goto done;
1282 free(refs);
1283 refs = s;
1287 /* Create got.conf(5). */
1288 gotconfig_path = got_repo_get_path_gotconfig(repo);
1289 if (gotconfig_path == NULL) {
1290 err = got_error_from_errno("got_repo_get_path_gotconfig");
1291 goto done;
1293 gotconfig_file = fopen(gotconfig_path, "ae");
1294 if (gotconfig_file == NULL) {
1295 err = got_error_from_errno2("fopen", gotconfig_path);
1296 goto done;
1298 if (asprintf(&gotconfig,
1299 "remote \"%s\" {\n"
1300 "\tserver %s\n"
1301 "\tprotocol %s\n"
1302 "%s%s%s"
1303 "\trepository \"%s\"\n"
1304 "%s%s%s"
1305 "%s%s%s"
1306 "%s"
1307 "%s"
1308 "}\n",
1309 GOT_FETCH_DEFAULT_REMOTE_NAME, host, proto,
1310 port ? "\tport " : "", port ? port : "", port ? "\n" : "",
1311 remote_repo_path, branches ? "\tbranch { " : "",
1312 branches ? branches : "", branches ? "}\n" : "",
1313 refs ? "\treference { " : "", refs ? refs : "", refs ? "}\n" : "",
1314 mirror_references ? "\tmirror_references yes\n" : "",
1315 fetch_all_branches ? "\tfetch_all_branches yes\n" : "") == -1) {
1316 err = got_error_from_errno("asprintf");
1317 goto done;
1319 n = fwrite(gotconfig, 1, strlen(gotconfig), gotconfig_file);
1320 if (n != strlen(gotconfig)) {
1321 err = got_ferror(gotconfig_file, GOT_ERR_IO);
1322 goto done;
1325 done:
1326 if (gotconfig_file && fclose(gotconfig_file) == EOF && err == NULL)
1327 err = got_error_from_errno2("fclose", gotconfig_path);
1328 free(gotconfig_path);
1329 free(branches);
1330 return err;
1333 static const struct got_error *
1334 create_gitconfig(const char *git_url, const char *default_branch,
1335 int fetch_all_branches, struct got_pathlist_head *wanted_branches,
1336 struct got_pathlist_head *wanted_refs, int mirror_references,
1337 struct got_repository *repo)
1339 const struct got_error *err = NULL;
1340 char *gitconfig_path = NULL;
1341 char *gitconfig = NULL;
1342 FILE *gitconfig_file = NULL;
1343 char *branches = NULL, *refs = NULL;
1344 const char *branchname;
1345 ssize_t n;
1347 /* Create a config file Git can understand. */
1348 gitconfig_path = got_repo_get_path_gitconfig(repo);
1349 if (gitconfig_path == NULL) {
1350 err = got_error_from_errno("got_repo_get_path_gitconfig");
1351 goto done;
1353 gitconfig_file = fopen(gitconfig_path, "ae");
1354 if (gitconfig_file == NULL) {
1355 err = got_error_from_errno2("fopen", gitconfig_path);
1356 goto done;
1358 if (fetch_all_branches) {
1359 if (mirror_references) {
1360 if (asprintf(&branches,
1361 "\tfetch = refs/heads/*:refs/heads/*\n") == -1) {
1362 err = got_error_from_errno("asprintf");
1363 goto done;
1365 } else if (asprintf(&branches,
1366 "\tfetch = refs/heads/*:refs/remotes/%s/*\n",
1367 GOT_FETCH_DEFAULT_REMOTE_NAME) == -1) {
1368 err = got_error_from_errno("asprintf");
1369 goto done;
1371 } else if (!TAILQ_EMPTY(wanted_branches)) {
1372 struct got_pathlist_entry *pe;
1373 TAILQ_FOREACH(pe, wanted_branches, entry) {
1374 char *s;
1375 branchname = pe->path;
1376 if (strncmp(branchname, "refs/heads/", 11) == 0)
1377 branchname += 11;
1378 if (mirror_references) {
1379 if (asprintf(&s,
1380 "%s\tfetch = refs/heads/%s:refs/heads/%s\n",
1381 branches ? branches : "",
1382 branchname, branchname) == -1) {
1383 err = got_error_from_errno("asprintf");
1384 goto done;
1386 } else if (asprintf(&s,
1387 "%s\tfetch = refs/heads/%s:refs/remotes/%s/%s\n",
1388 branches ? branches : "",
1389 branchname, GOT_FETCH_DEFAULT_REMOTE_NAME,
1390 branchname) == -1) {
1391 err = got_error_from_errno("asprintf");
1392 goto done;
1394 free(branches);
1395 branches = s;
1397 } else {
1399 * If the server specified a default branch, use just that one.
1400 * Otherwise fall back to fetching all branches on next fetch.
1402 if (default_branch) {
1403 branchname = default_branch;
1404 if (strncmp(branchname, "refs/heads/", 11) == 0)
1405 branchname += 11;
1406 } else
1407 branchname = "*"; /* fall back to all branches */
1408 if (mirror_references) {
1409 if (asprintf(&branches,
1410 "\tfetch = refs/heads/%s:refs/heads/%s\n",
1411 branchname, branchname) == -1) {
1412 err = got_error_from_errno("asprintf");
1413 goto done;
1415 } else if (asprintf(&branches,
1416 "\tfetch = refs/heads/%s:refs/remotes/%s/%s\n",
1417 branchname, GOT_FETCH_DEFAULT_REMOTE_NAME,
1418 branchname) == -1) {
1419 err = got_error_from_errno("asprintf");
1420 goto done;
1423 if (!TAILQ_EMPTY(wanted_refs)) {
1424 struct got_pathlist_entry *pe;
1425 TAILQ_FOREACH(pe, wanted_refs, entry) {
1426 char *s;
1427 const char *refname = pe->path;
1428 if (strncmp(refname, "refs/", 5) == 0)
1429 refname += 5;
1430 if (mirror_references) {
1431 if (asprintf(&s,
1432 "%s\tfetch = refs/%s:refs/%s\n",
1433 refs ? refs : "", refname, refname) == -1) {
1434 err = got_error_from_errno("asprintf");
1435 goto done;
1437 } else if (asprintf(&s,
1438 "%s\tfetch = refs/%s:refs/remotes/%s/%s\n",
1439 refs ? refs : "",
1440 refname, GOT_FETCH_DEFAULT_REMOTE_NAME,
1441 refname) == -1) {
1442 err = got_error_from_errno("asprintf");
1443 goto done;
1445 free(refs);
1446 refs = s;
1450 if (asprintf(&gitconfig,
1451 "[remote \"%s\"]\n"
1452 "\turl = %s\n"
1453 "%s"
1454 "%s"
1455 "\tfetch = refs/tags/*:refs/tags/*\n",
1456 GOT_FETCH_DEFAULT_REMOTE_NAME, git_url, branches ? branches : "",
1457 refs ? refs : "") == -1) {
1458 err = got_error_from_errno("asprintf");
1459 goto done;
1461 n = fwrite(gitconfig, 1, strlen(gitconfig), gitconfig_file);
1462 if (n != strlen(gitconfig)) {
1463 err = got_ferror(gitconfig_file, GOT_ERR_IO);
1464 goto done;
1466 done:
1467 if (gitconfig_file && fclose(gitconfig_file) == EOF && err == NULL)
1468 err = got_error_from_errno2("fclose", gitconfig_path);
1469 free(gitconfig_path);
1470 free(branches);
1471 return err;
1474 static const struct got_error *
1475 create_config_files(const char *proto, const char *host, const char *port,
1476 const char *remote_repo_path, const char *git_url, int fetch_all_branches,
1477 int mirror_references, struct got_pathlist_head *symrefs,
1478 struct got_pathlist_head *wanted_branches,
1479 struct got_pathlist_head *wanted_refs, struct got_repository *repo)
1481 const struct got_error *err = NULL;
1482 const char *default_branch = NULL;
1483 struct got_pathlist_entry *pe;
1486 * If we asked for a set of wanted branches then use the first
1487 * one of those.
1489 if (!TAILQ_EMPTY(wanted_branches)) {
1490 pe = TAILQ_FIRST(wanted_branches);
1491 default_branch = pe->path;
1492 } else {
1493 /* First HEAD ref listed by server is the default branch. */
1494 TAILQ_FOREACH(pe, symrefs, entry) {
1495 const char *refname = pe->path;
1496 const char *target = pe->data;
1498 if (strcmp(refname, GOT_REF_HEAD) != 0)
1499 continue;
1501 default_branch = target;
1502 break;
1506 /* Create got.conf(5). */
1507 err = create_gotconfig(proto, host, port, remote_repo_path,
1508 default_branch, fetch_all_branches, wanted_branches,
1509 wanted_refs, mirror_references, repo);
1510 if (err)
1511 return err;
1513 /* Create a config file Git can understand. */
1514 return create_gitconfig(git_url, default_branch, fetch_all_branches,
1515 wanted_branches, wanted_refs, mirror_references, repo);
1518 static const struct got_error *
1519 cmd_clone(int argc, char *argv[])
1521 const struct got_error *error = NULL;
1522 const char *uri, *dirname;
1523 char *proto, *host, *port, *repo_name, *server_path;
1524 char *default_destdir = NULL, *id_str = NULL;
1525 const char *repo_path;
1526 struct got_repository *repo = NULL;
1527 struct got_pathlist_head refs, symrefs, wanted_branches, wanted_refs;
1528 struct got_pathlist_entry *pe;
1529 struct got_object_id *pack_hash = NULL;
1530 int ch, fetchfd = -1, fetchstatus;
1531 pid_t fetchpid = -1;
1532 struct got_fetch_progress_arg fpa;
1533 char *git_url = NULL;
1534 int verbosity = 0, fetch_all_branches = 0, mirror_references = 0;
1535 int bflag = 0, list_refs_only = 0;
1536 int *pack_fds = NULL;
1538 TAILQ_INIT(&refs);
1539 TAILQ_INIT(&symrefs);
1540 TAILQ_INIT(&wanted_branches);
1541 TAILQ_INIT(&wanted_refs);
1543 while ((ch = getopt(argc, argv, "ab:lmqR:v")) != -1) {
1544 switch (ch) {
1545 case 'a':
1546 fetch_all_branches = 1;
1547 break;
1548 case 'b':
1549 error = got_pathlist_append(&wanted_branches,
1550 optarg, NULL);
1551 if (error)
1552 return error;
1553 bflag = 1;
1554 break;
1555 case 'l':
1556 list_refs_only = 1;
1557 break;
1558 case 'm':
1559 mirror_references = 1;
1560 break;
1561 case 'q':
1562 verbosity = -1;
1563 break;
1564 case 'R':
1565 error = got_pathlist_append(&wanted_refs,
1566 optarg, NULL);
1567 if (error)
1568 return error;
1569 break;
1570 case 'v':
1571 if (verbosity < 0)
1572 verbosity = 0;
1573 else if (verbosity < 3)
1574 verbosity++;
1575 break;
1576 default:
1577 usage_clone();
1578 break;
1581 argc -= optind;
1582 argv += optind;
1584 if (fetch_all_branches && !TAILQ_EMPTY(&wanted_branches))
1585 option_conflict('a', 'b');
1586 if (list_refs_only) {
1587 if (!TAILQ_EMPTY(&wanted_branches))
1588 option_conflict('l', 'b');
1589 if (fetch_all_branches)
1590 option_conflict('l', 'a');
1591 if (mirror_references)
1592 option_conflict('l', 'm');
1593 if (!TAILQ_EMPTY(&wanted_refs))
1594 option_conflict('l', 'R');
1597 uri = argv[0];
1599 if (argc == 1)
1600 dirname = NULL;
1601 else if (argc == 2)
1602 dirname = argv[1];
1603 else
1604 usage_clone();
1606 error = got_dial_parse_uri(&proto, &host, &port, &server_path,
1607 &repo_name, uri);
1608 if (error)
1609 goto done;
1611 if (asprintf(&git_url, "%s://%s%s%s%s%s", proto,
1612 host, port ? ":" : "", port ? port : "",
1613 server_path[0] != '/' ? "/" : "", server_path) == -1) {
1614 error = got_error_from_errno("asprintf");
1615 goto done;
1618 if (strcmp(proto, "git") == 0) {
1619 #ifndef PROFILE
1620 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
1621 "sendfd dns inet unveil", NULL) == -1)
1622 err(1, "pledge");
1623 #endif
1624 } else if (strcmp(proto, "git+ssh") == 0 ||
1625 strcmp(proto, "ssh") == 0) {
1626 #ifndef PROFILE
1627 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
1628 "sendfd unveil", NULL) == -1)
1629 err(1, "pledge");
1630 #endif
1631 } else if (strcmp(proto, "http") == 0 ||
1632 strcmp(proto, "git+http") == 0) {
1633 error = got_error_path(proto, GOT_ERR_NOT_IMPL);
1634 goto done;
1635 } else {
1636 error = got_error_path(proto, GOT_ERR_BAD_PROTO);
1637 goto done;
1639 if (dirname == NULL) {
1640 if (asprintf(&default_destdir, "%s.git", repo_name) == -1) {
1641 error = got_error_from_errno("asprintf");
1642 goto done;
1644 repo_path = default_destdir;
1645 } else
1646 repo_path = dirname;
1648 if (!list_refs_only) {
1649 error = got_path_mkdir(repo_path);
1650 if (error &&
1651 (!(error->code == GOT_ERR_ERRNO && errno == EISDIR) &&
1652 !(error->code == GOT_ERR_ERRNO && errno == EEXIST)))
1653 goto done;
1654 if (!got_path_dir_is_empty(repo_path)) {
1655 error = got_error_path(repo_path,
1656 GOT_ERR_DIR_NOT_EMPTY);
1657 goto done;
1661 error = got_dial_apply_unveil(proto);
1662 if (error)
1663 goto done;
1665 error = apply_unveil(repo_path, 0, NULL);
1666 if (error)
1667 goto done;
1669 if (verbosity >= 0)
1670 printf("Connecting to %s\n", git_url);
1672 error = got_fetch_connect(&fetchpid, &fetchfd, proto, host, port,
1673 server_path, verbosity);
1674 if (error)
1675 goto done;
1677 if (!list_refs_only) {
1678 error = got_repo_init(repo_path, NULL);
1679 if (error)
1680 goto done;
1681 error = got_repo_pack_fds_open(&pack_fds);
1682 if (error != NULL)
1683 goto done;
1684 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
1685 if (error)
1686 goto done;
1689 fpa.last_scaled_size[0] = '\0';
1690 fpa.last_p_indexed = -1;
1691 fpa.last_p_resolved = -1;
1692 fpa.verbosity = verbosity;
1693 fpa.create_configs = 1;
1694 fpa.configs_created = 0;
1695 fpa.repo = repo;
1696 fpa.config_info.symrefs = &symrefs;
1697 fpa.config_info.wanted_branches = &wanted_branches;
1698 fpa.config_info.wanted_refs = &wanted_refs;
1699 fpa.config_info.proto = proto;
1700 fpa.config_info.host = host;
1701 fpa.config_info.port = port;
1702 fpa.config_info.remote_repo_path = server_path;
1703 fpa.config_info.git_url = git_url;
1704 fpa.config_info.fetch_all_branches = fetch_all_branches;
1705 fpa.config_info.mirror_references = mirror_references;
1706 error = got_fetch_pack(&pack_hash, &refs, &symrefs,
1707 GOT_FETCH_DEFAULT_REMOTE_NAME, mirror_references,
1708 fetch_all_branches, &wanted_branches, &wanted_refs,
1709 list_refs_only, verbosity, fetchfd, repo, NULL, NULL, bflag,
1710 fetch_progress, &fpa);
1711 if (error)
1712 goto done;
1714 if (list_refs_only) {
1715 error = list_remote_refs(&symrefs, &refs);
1716 goto done;
1719 if (pack_hash == NULL) {
1720 error = got_error_fmt(GOT_ERR_FETCH_FAILED, "%s",
1721 "server sent an empty pack file");
1722 goto done;
1724 error = got_object_id_str(&id_str, pack_hash);
1725 if (error)
1726 goto done;
1727 if (verbosity >= 0)
1728 printf("\nFetched %s.pack\n", id_str);
1729 free(id_str);
1731 /* Set up references provided with the pack file. */
1732 TAILQ_FOREACH(pe, &refs, entry) {
1733 const char *refname = pe->path;
1734 struct got_object_id *id = pe->data;
1735 char *remote_refname;
1737 if (is_wanted_ref(&wanted_refs, refname) &&
1738 !mirror_references) {
1739 error = create_wanted_ref(refname, id,
1740 GOT_FETCH_DEFAULT_REMOTE_NAME,
1741 verbosity - 1, repo);
1742 if (error)
1743 goto done;
1744 continue;
1747 error = create_ref(refname, id, verbosity - 1, repo);
1748 if (error)
1749 goto done;
1751 if (mirror_references)
1752 continue;
1754 if (strncmp("refs/heads/", refname, 11) != 0)
1755 continue;
1757 if (asprintf(&remote_refname,
1758 "refs/remotes/%s/%s", GOT_FETCH_DEFAULT_REMOTE_NAME,
1759 refname + 11) == -1) {
1760 error = got_error_from_errno("asprintf");
1761 goto done;
1763 error = create_ref(remote_refname, id, verbosity - 1, repo);
1764 free(remote_refname);
1765 if (error)
1766 goto done;
1769 /* Set the HEAD reference if the server provided one. */
1770 TAILQ_FOREACH(pe, &symrefs, entry) {
1771 struct got_reference *target_ref;
1772 const char *refname = pe->path;
1773 const char *target = pe->data;
1774 char *remote_refname = NULL, *remote_target = NULL;
1776 if (strcmp(refname, GOT_REF_HEAD) != 0)
1777 continue;
1779 error = got_ref_open(&target_ref, repo, target, 0);
1780 if (error) {
1781 if (error->code == GOT_ERR_NOT_REF) {
1782 error = NULL;
1783 continue;
1785 goto done;
1788 error = create_symref(refname, target_ref, verbosity, repo);
1789 got_ref_close(target_ref);
1790 if (error)
1791 goto done;
1793 if (mirror_references)
1794 continue;
1796 if (strncmp("refs/heads/", target, 11) != 0)
1797 continue;
1799 if (asprintf(&remote_refname,
1800 "refs/remotes/%s/%s", GOT_FETCH_DEFAULT_REMOTE_NAME,
1801 refname) == -1) {
1802 error = got_error_from_errno("asprintf");
1803 goto done;
1805 if (asprintf(&remote_target,
1806 "refs/remotes/%s/%s", GOT_FETCH_DEFAULT_REMOTE_NAME,
1807 target + 11) == -1) {
1808 error = got_error_from_errno("asprintf");
1809 free(remote_refname);
1810 goto done;
1812 error = got_ref_open(&target_ref, repo, remote_target, 0);
1813 if (error) {
1814 free(remote_refname);
1815 free(remote_target);
1816 if (error->code == GOT_ERR_NOT_REF) {
1817 error = NULL;
1818 continue;
1820 goto done;
1822 error = create_symref(remote_refname, target_ref,
1823 verbosity - 1, repo);
1824 free(remote_refname);
1825 free(remote_target);
1826 got_ref_close(target_ref);
1827 if (error)
1828 goto done;
1830 if (pe == NULL) {
1832 * We failed to set the HEAD reference. If we asked for
1833 * a set of wanted branches use the first of one of those
1834 * which could be fetched instead.
1836 TAILQ_FOREACH(pe, &wanted_branches, entry) {
1837 const char *target = pe->path;
1838 struct got_reference *target_ref;
1840 error = got_ref_open(&target_ref, repo, target, 0);
1841 if (error) {
1842 if (error->code == GOT_ERR_NOT_REF) {
1843 error = NULL;
1844 continue;
1846 goto done;
1849 error = create_symref(GOT_REF_HEAD, target_ref,
1850 verbosity, repo);
1851 got_ref_close(target_ref);
1852 if (error)
1853 goto done;
1854 break;
1857 if (!fpa.configs_created && pe != NULL) {
1858 error = create_config_files(fpa.config_info.proto,
1859 fpa.config_info.host, fpa.config_info.port,
1860 fpa.config_info.remote_repo_path,
1861 fpa.config_info.git_url,
1862 fpa.config_info.fetch_all_branches,
1863 fpa.config_info.mirror_references,
1864 fpa.config_info.symrefs,
1865 fpa.config_info.wanted_branches,
1866 fpa.config_info.wanted_refs, fpa.repo);
1867 if (error)
1868 goto done;
1872 if (verbosity >= 0)
1873 printf("Created %s repository '%s'\n",
1874 mirror_references ? "mirrored" : "cloned", repo_path);
1875 done:
1876 if (pack_fds) {
1877 const struct got_error *pack_err =
1878 got_repo_pack_fds_close(pack_fds);
1879 if (error == NULL)
1880 error = pack_err;
1882 if (fetchpid > 0) {
1883 if (kill(fetchpid, SIGTERM) == -1)
1884 error = got_error_from_errno("kill");
1885 if (waitpid(fetchpid, &fetchstatus, 0) == -1 && error == NULL)
1886 error = got_error_from_errno("waitpid");
1888 if (fetchfd != -1 && close(fetchfd) == -1 && error == NULL)
1889 error = got_error_from_errno("close");
1890 if (repo) {
1891 const struct got_error *close_err = got_repo_close(repo);
1892 if (error == NULL)
1893 error = close_err;
1895 got_pathlist_free(&refs, GOT_PATHLIST_FREE_ALL);
1896 got_pathlist_free(&symrefs, GOT_PATHLIST_FREE_ALL);
1897 got_pathlist_free(&wanted_branches, GOT_PATHLIST_FREE_NONE);
1898 got_pathlist_free(&wanted_refs, GOT_PATHLIST_FREE_NONE);
1899 free(pack_hash);
1900 free(proto);
1901 free(host);
1902 free(port);
1903 free(server_path);
1904 free(repo_name);
1905 free(default_destdir);
1906 free(git_url);
1907 return error;
1910 static const struct got_error *
1911 update_ref(struct got_reference *ref, struct got_object_id *new_id,
1912 int replace_tags, int verbosity, struct got_repository *repo)
1914 const struct got_error *err = NULL;
1915 char *new_id_str = NULL;
1916 struct got_object_id *old_id = NULL;
1918 err = got_object_id_str(&new_id_str, new_id);
1919 if (err)
1920 goto done;
1922 if (!replace_tags &&
1923 strncmp(got_ref_get_name(ref), "refs/tags/", 10) == 0) {
1924 err = got_ref_resolve(&old_id, repo, ref);
1925 if (err)
1926 goto done;
1927 if (got_object_id_cmp(old_id, new_id) == 0)
1928 goto done;
1929 if (verbosity >= 0) {
1930 printf("Rejecting update of existing tag %s: %s\n",
1931 got_ref_get_name(ref), new_id_str);
1933 goto done;
1936 if (got_ref_is_symbolic(ref)) {
1937 if (verbosity >= 0) {
1938 printf("Replacing reference %s: %s\n",
1939 got_ref_get_name(ref),
1940 got_ref_get_symref_target(ref));
1942 err = got_ref_change_symref_to_ref(ref, new_id);
1943 if (err)
1944 goto done;
1945 err = got_ref_write(ref, repo);
1946 if (err)
1947 goto done;
1948 } else {
1949 err = got_ref_resolve(&old_id, repo, ref);
1950 if (err)
1951 goto done;
1952 if (got_object_id_cmp(old_id, new_id) == 0)
1953 goto done;
1955 err = got_ref_change_ref(ref, new_id);
1956 if (err)
1957 goto done;
1958 err = got_ref_write(ref, repo);
1959 if (err)
1960 goto done;
1963 if (verbosity >= 0)
1964 printf("Updated %s: %s\n", got_ref_get_name(ref),
1965 new_id_str);
1966 done:
1967 free(old_id);
1968 free(new_id_str);
1969 return err;
1972 static const struct got_error *
1973 update_wanted_ref(const char *refname, struct got_object_id *id,
1974 const char *remote_repo_name, int verbosity, struct got_repository *repo)
1976 const struct got_error *err, *unlock_err;
1977 char *remote_refname;
1978 struct got_reference *ref;
1980 if (strncmp("refs/", refname, 5) == 0)
1981 refname += 5;
1983 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
1984 remote_repo_name, refname) == -1)
1985 return got_error_from_errno("asprintf");
1987 err = got_ref_open(&ref, repo, remote_refname, 1);
1988 if (err) {
1989 if (err->code != GOT_ERR_NOT_REF)
1990 goto done;
1991 err = create_ref(remote_refname, id, verbosity, repo);
1992 } else {
1993 err = update_ref(ref, id, 0, verbosity, repo);
1994 unlock_err = got_ref_unlock(ref);
1995 if (unlock_err && err == NULL)
1996 err = unlock_err;
1997 got_ref_close(ref);
1999 done:
2000 free(remote_refname);
2001 return err;
2004 __dead static void
2005 usage_checkout(void)
2007 fprintf(stderr, "usage: %s checkout [-Eq] [-b branch] [-c commit] "
2008 "[-p path-prefix] repository-path [work-tree-path]\n",
2009 getprogname());
2010 exit(1);
2013 static void
2014 show_worktree_base_ref_warning(void)
2016 fprintf(stderr, "%s: warning: could not create a reference "
2017 "to the work tree's base commit; the commit could be "
2018 "garbage-collected by Git or 'gotadmin cleanup'; making the "
2019 "repository writable and running 'got update' will prevent this\n",
2020 getprogname());
2023 struct got_checkout_progress_arg {
2024 const char *worktree_path;
2025 int had_base_commit_ref_error;
2026 int verbosity;
2029 static const struct got_error *
2030 checkout_progress(void *arg, unsigned char status, const char *path)
2032 struct got_checkout_progress_arg *a = arg;
2034 /* Base commit bump happens silently. */
2035 if (status == GOT_STATUS_BUMP_BASE)
2036 return NULL;
2038 if (status == GOT_STATUS_BASE_REF_ERR) {
2039 a->had_base_commit_ref_error = 1;
2040 return NULL;
2043 while (path[0] == '/')
2044 path++;
2046 if (a->verbosity >= 0)
2047 printf("%c %s/%s\n", status, a->worktree_path, path);
2049 return NULL;
2052 static const struct got_error *
2053 check_cancelled(void *arg)
2055 if (sigint_received || sigpipe_received)
2056 return got_error(GOT_ERR_CANCELLED);
2057 return NULL;
2060 static const struct got_error *
2061 check_linear_ancestry(struct got_object_id *commit_id,
2062 struct got_object_id *base_commit_id, int allow_forwards_in_time_only,
2063 struct got_repository *repo)
2065 const struct got_error *err = NULL;
2066 struct got_object_id *yca_id;
2068 err = got_commit_graph_find_youngest_common_ancestor(&yca_id,
2069 commit_id, base_commit_id, 1, 0, repo, check_cancelled, NULL);
2070 if (err)
2071 return err;
2073 if (yca_id == NULL)
2074 return got_error(GOT_ERR_ANCESTRY);
2077 * Require a straight line of history between the target commit
2078 * and the work tree's base commit.
2080 * Non-linear situations such as this require a rebase:
2082 * (commit) D F (base_commit)
2083 * \ /
2084 * C E
2085 * \ /
2086 * B (yca)
2087 * |
2088 * A
2090 * 'got update' only handles linear cases:
2091 * Update forwards in time: A (base/yca) - B - C - D (commit)
2092 * Update backwards in time: D (base) - C - B - A (commit/yca)
2094 if (allow_forwards_in_time_only) {
2095 if (got_object_id_cmp(base_commit_id, yca_id) != 0)
2096 return got_error(GOT_ERR_ANCESTRY);
2097 } else if (got_object_id_cmp(commit_id, yca_id) != 0 &&
2098 got_object_id_cmp(base_commit_id, yca_id) != 0)
2099 return got_error(GOT_ERR_ANCESTRY);
2101 free(yca_id);
2102 return NULL;
2105 static const struct got_error *
2106 check_same_branch(struct got_object_id *commit_id,
2107 struct got_reference *head_ref, struct got_repository *repo)
2109 const struct got_error *err = NULL;
2110 struct got_commit_graph *graph = NULL;
2111 struct got_object_id *head_commit_id = NULL;
2113 err = got_ref_resolve(&head_commit_id, repo, head_ref);
2114 if (err)
2115 goto done;
2117 if (got_object_id_cmp(head_commit_id, commit_id) == 0)
2118 goto done;
2120 err = got_commit_graph_open(&graph, "/", 1);
2121 if (err)
2122 goto done;
2124 err = got_commit_graph_bfsort(graph, head_commit_id, repo,
2125 check_cancelled, NULL);
2126 if (err)
2127 goto done;
2129 for (;;) {
2130 struct got_object_id id;
2132 err = got_commit_graph_iter_next(&id, graph, repo,
2133 check_cancelled, NULL);
2134 if (err) {
2135 if (err->code == GOT_ERR_ITER_COMPLETED)
2136 err = got_error(GOT_ERR_ANCESTRY);
2137 break;
2140 if (got_object_id_cmp(&id, commit_id) == 0)
2141 break;
2143 done:
2144 if (graph)
2145 got_commit_graph_close(graph);
2146 free(head_commit_id);
2147 return err;
2150 static const struct got_error *
2151 checkout_ancestry_error(struct got_reference *ref, const char *commit_id_str)
2153 static char msg[512];
2154 const char *branch_name;
2156 if (got_ref_is_symbolic(ref))
2157 branch_name = got_ref_get_symref_target(ref);
2158 else
2159 branch_name = got_ref_get_name(ref);
2161 if (strncmp("refs/heads/", branch_name, 11) == 0)
2162 branch_name += 11;
2164 snprintf(msg, sizeof(msg),
2165 "target commit is not contained in branch '%s'; "
2166 "the branch to use must be specified with -b; "
2167 "if necessary a new branch can be created for "
2168 "this commit with 'got branch -c %s BRANCH_NAME'",
2169 branch_name, commit_id_str);
2171 return got_error_msg(GOT_ERR_ANCESTRY, msg);
2174 static const struct got_error *
2175 cmd_checkout(int argc, char *argv[])
2177 const struct got_error *error = NULL;
2178 struct got_repository *repo = NULL;
2179 struct got_reference *head_ref = NULL, *ref = NULL;
2180 struct got_worktree *worktree = NULL;
2181 char *repo_path = NULL;
2182 char *worktree_path = NULL;
2183 const char *path_prefix = "";
2184 const char *branch_name = GOT_REF_HEAD, *refname = NULL;
2185 char *commit_id_str = NULL;
2186 struct got_object_id *commit_id = NULL;
2187 char *cwd = NULL;
2188 int ch, same_path_prefix, allow_nonempty = 0, verbosity = 0;
2189 struct got_pathlist_head paths;
2190 struct got_checkout_progress_arg cpa;
2191 int *pack_fds = NULL;
2193 TAILQ_INIT(&paths);
2195 #ifndef PROFILE
2196 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
2197 "unveil", NULL) == -1)
2198 err(1, "pledge");
2199 #endif
2201 while ((ch = getopt(argc, argv, "b:c:Ep:q")) != -1) {
2202 switch (ch) {
2203 case 'b':
2204 branch_name = optarg;
2205 break;
2206 case 'c':
2207 commit_id_str = strdup(optarg);
2208 if (commit_id_str == NULL)
2209 return got_error_from_errno("strdup");
2210 break;
2211 case 'E':
2212 allow_nonempty = 1;
2213 break;
2214 case 'p':
2215 path_prefix = optarg;
2216 break;
2217 case 'q':
2218 verbosity = -1;
2219 break;
2220 default:
2221 usage_checkout();
2222 /* NOTREACHED */
2226 argc -= optind;
2227 argv += optind;
2229 if (argc == 1) {
2230 char *base, *dotgit;
2231 const char *path;
2232 repo_path = realpath(argv[0], NULL);
2233 if (repo_path == NULL)
2234 return got_error_from_errno2("realpath", argv[0]);
2235 cwd = getcwd(NULL, 0);
2236 if (cwd == NULL) {
2237 error = got_error_from_errno("getcwd");
2238 goto done;
2240 if (path_prefix[0])
2241 path = path_prefix;
2242 else
2243 path = repo_path;
2244 error = got_path_basename(&base, path);
2245 if (error)
2246 goto done;
2247 dotgit = strstr(base, ".git");
2248 if (dotgit)
2249 *dotgit = '\0';
2250 if (asprintf(&worktree_path, "%s/%s", cwd, base) == -1) {
2251 error = got_error_from_errno("asprintf");
2252 free(base);
2253 goto done;
2255 free(base);
2256 } else if (argc == 2) {
2257 repo_path = realpath(argv[0], NULL);
2258 if (repo_path == NULL) {
2259 error = got_error_from_errno2("realpath", argv[0]);
2260 goto done;
2262 worktree_path = realpath(argv[1], NULL);
2263 if (worktree_path == NULL) {
2264 if (errno != ENOENT) {
2265 error = got_error_from_errno2("realpath",
2266 argv[1]);
2267 goto done;
2269 worktree_path = strdup(argv[1]);
2270 if (worktree_path == NULL) {
2271 error = got_error_from_errno("strdup");
2272 goto done;
2275 } else
2276 usage_checkout();
2278 got_path_strip_trailing_slashes(repo_path);
2279 got_path_strip_trailing_slashes(worktree_path);
2281 error = got_repo_pack_fds_open(&pack_fds);
2282 if (error != NULL)
2283 goto done;
2285 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
2286 if (error != NULL)
2287 goto done;
2289 /* Pre-create work tree path for unveil(2) */
2290 error = got_path_mkdir(worktree_path);
2291 if (error) {
2292 if (!(error->code == GOT_ERR_ERRNO && errno == EISDIR) &&
2293 !(error->code == GOT_ERR_ERRNO && errno == EEXIST))
2294 goto done;
2295 if (!allow_nonempty &&
2296 !got_path_dir_is_empty(worktree_path)) {
2297 error = got_error_path(worktree_path,
2298 GOT_ERR_DIR_NOT_EMPTY);
2299 goto done;
2303 error = apply_unveil(got_repo_get_path(repo), 0, worktree_path);
2304 if (error)
2305 goto done;
2307 error = got_ref_open(&head_ref, repo, branch_name, 0);
2308 if (error != NULL)
2309 goto done;
2311 error = got_worktree_init(worktree_path, head_ref, path_prefix,
2312 GOT_WORKTREE_CVG_DIR, repo);
2313 if (error != NULL && !(error->code == GOT_ERR_ERRNO && errno == EEXIST))
2314 goto done;
2316 error = got_worktree_open(&worktree, worktree_path, GOT_WORKTREE_CVG_DIR);
2317 if (error != NULL)
2318 goto done;
2320 error = got_worktree_match_path_prefix(&same_path_prefix, worktree,
2321 path_prefix);
2322 if (error != NULL)
2323 goto done;
2324 if (!same_path_prefix) {
2325 error = got_error(GOT_ERR_PATH_PREFIX);
2326 goto done;
2329 if (commit_id_str) {
2330 struct got_reflist_head refs;
2331 TAILQ_INIT(&refs);
2332 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
2333 NULL);
2334 if (error)
2335 goto done;
2336 error = got_repo_match_object_id(&commit_id, NULL,
2337 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
2338 got_ref_list_free(&refs);
2339 if (error)
2340 goto done;
2341 error = check_linear_ancestry(commit_id,
2342 got_worktree_get_base_commit_id(worktree), 0, repo);
2343 if (error != NULL) {
2344 if (error->code == GOT_ERR_ANCESTRY) {
2345 error = checkout_ancestry_error(
2346 head_ref, commit_id_str);
2348 goto done;
2350 error = check_same_branch(commit_id, head_ref, repo);
2351 if (error) {
2352 if (error->code == GOT_ERR_ANCESTRY) {
2353 error = checkout_ancestry_error(
2354 head_ref, commit_id_str);
2356 goto done;
2358 error = got_worktree_set_base_commit_id(worktree, repo,
2359 commit_id);
2360 if (error)
2361 goto done;
2362 /* Expand potentially abbreviated commit ID string. */
2363 free(commit_id_str);
2364 error = got_object_id_str(&commit_id_str, commit_id);
2365 if (error)
2366 goto done;
2367 } else {
2368 commit_id = got_object_id_dup(
2369 got_worktree_get_base_commit_id(worktree));
2370 if (commit_id == NULL) {
2371 error = got_error_from_errno("got_object_id_dup");
2372 goto done;
2374 error = got_object_id_str(&commit_id_str, commit_id);
2375 if (error)
2376 goto done;
2379 error = got_pathlist_append(&paths, "", NULL);
2380 if (error)
2381 goto done;
2382 cpa.worktree_path = worktree_path;
2383 cpa.had_base_commit_ref_error = 0;
2384 cpa.verbosity = verbosity;
2385 error = got_worktree_checkout_files(worktree, &paths, repo,
2386 checkout_progress, &cpa, check_cancelled, NULL);
2387 if (error != NULL)
2388 goto done;
2390 if (got_ref_is_symbolic(head_ref)) {
2391 error = got_ref_resolve_symbolic(&ref, repo, head_ref);
2392 if (error)
2393 goto done;
2394 refname = got_ref_get_name(ref);
2395 } else
2396 refname = got_ref_get_name(head_ref);
2397 printf("Checked out %s: %s\n", refname, commit_id_str);
2398 printf("Now shut up and hack\n");
2399 if (cpa.had_base_commit_ref_error)
2400 show_worktree_base_ref_warning();
2401 done:
2402 if (pack_fds) {
2403 const struct got_error *pack_err =
2404 got_repo_pack_fds_close(pack_fds);
2405 if (error == NULL)
2406 error = pack_err;
2408 if (head_ref)
2409 got_ref_close(head_ref);
2410 if (ref)
2411 got_ref_close(ref);
2412 if (repo) {
2413 const struct got_error *close_err = got_repo_close(repo);
2414 if (error == NULL)
2415 error = close_err;
2417 got_pathlist_free(&paths, GOT_PATHLIST_FREE_NONE);
2418 free(commit_id_str);
2419 free(commit_id);
2420 free(repo_path);
2421 free(worktree_path);
2422 free(cwd);
2423 return error;
2426 struct got_update_progress_arg {
2427 int did_something;
2428 int conflicts;
2429 int obstructed;
2430 int not_updated;
2431 int missing;
2432 int not_deleted;
2433 int unversioned;
2434 int verbosity;
2437 static void
2438 print_update_progress_stats(struct got_update_progress_arg *upa)
2440 if (!upa->did_something)
2441 return;
2443 if (upa->conflicts > 0)
2444 printf("Files with new merge conflicts: %d\n", upa->conflicts);
2445 if (upa->obstructed > 0)
2446 printf("File paths obstructed by a non-regular file: %d\n",
2447 upa->obstructed);
2448 if (upa->not_updated > 0)
2449 printf("Files not updated because of existing merge "
2450 "conflicts: %d\n", upa->not_updated);
2454 * The meaning of some status codes differs between merge-style operations and
2455 * update operations. For example, the ! status code means "file was missing"
2456 * if changes were merged into the work tree, and "missing file was restored"
2457 * if the work tree was updated. This function should be used by any operation
2458 * which merges changes into the work tree without updating the work tree.
2460 static void
2461 print_merge_progress_stats(struct got_update_progress_arg *upa)
2463 if (!upa->did_something)
2464 return;
2466 if (upa->conflicts > 0)
2467 printf("Files with new merge conflicts: %d\n", upa->conflicts);
2468 if (upa->obstructed > 0)
2469 printf("File paths obstructed by a non-regular file: %d\n",
2470 upa->obstructed);
2471 if (upa->missing > 0)
2472 printf("Files which had incoming changes but could not be "
2473 "found in the work tree: %d\n", upa->missing);
2474 if (upa->not_deleted > 0)
2475 printf("Files not deleted due to differences in deleted "
2476 "content: %d\n", upa->not_deleted);
2477 if (upa->unversioned > 0)
2478 printf("Files not merged because an unversioned file was "
2479 "found in the work tree: %d\n", upa->unversioned);
2482 __dead static void
2483 usage_update(void)
2485 fprintf(stderr, "usage: %s update [-qtvX] [-c commit] [-r remote] "
2486 "[path ...]\n", getprogname());
2487 exit(1);
2490 static const struct got_error *
2491 update_progress(void *arg, unsigned char status, const char *path)
2493 struct got_update_progress_arg *upa = arg;
2495 if (status == GOT_STATUS_EXISTS ||
2496 status == GOT_STATUS_BASE_REF_ERR)
2497 return NULL;
2499 upa->did_something = 1;
2501 /* Base commit bump happens silently. */
2502 if (status == GOT_STATUS_BUMP_BASE)
2503 return NULL;
2505 if (status == GOT_STATUS_CONFLICT)
2506 upa->conflicts++;
2507 if (status == GOT_STATUS_OBSTRUCTED)
2508 upa->obstructed++;
2509 if (status == GOT_STATUS_CANNOT_UPDATE)
2510 upa->not_updated++;
2511 if (status == GOT_STATUS_MISSING)
2512 upa->missing++;
2513 if (status == GOT_STATUS_CANNOT_DELETE)
2514 upa->not_deleted++;
2515 if (status == GOT_STATUS_UNVERSIONED)
2516 upa->unversioned++;
2518 while (path[0] == '/')
2519 path++;
2520 if (upa->verbosity >= 0)
2521 printf("%c %s\n", status, path);
2523 return NULL;
2526 static const struct got_error *
2527 check_rebase_or_histedit_in_progress(struct got_worktree *worktree)
2529 const struct got_error *err;
2530 int in_progress;
2532 err = got_worktree_rebase_in_progress(&in_progress, worktree);
2533 if (err)
2534 return err;
2535 if (in_progress)
2536 return got_error(GOT_ERR_REBASING);
2538 err = got_worktree_histedit_in_progress(&in_progress, worktree);
2539 if (err)
2540 return err;
2541 if (in_progress)
2542 return got_error(GOT_ERR_HISTEDIT_BUSY);
2544 return NULL;
2547 static const struct got_error *
2548 check_merge_in_progress(struct got_worktree *worktree,
2549 struct got_repository *repo)
2551 const struct got_error *err;
2552 int in_progress;
2554 err = got_worktree_merge_in_progress(&in_progress, worktree, repo);
2555 if (err)
2556 return err;
2557 if (in_progress)
2558 return got_error(GOT_ERR_MERGE_BUSY);
2560 return NULL;
2563 static const struct got_error *
2564 get_worktree_paths_from_argv(struct got_pathlist_head *paths, int argc,
2565 char *argv[], struct got_worktree *worktree)
2567 const struct got_error *err = NULL;
2568 char *path;
2569 struct got_pathlist_entry *new;
2570 int i;
2572 if (argc == 0) {
2573 path = strdup("");
2574 if (path == NULL)
2575 return got_error_from_errno("strdup");
2576 return got_pathlist_append(paths, path, NULL);
2579 for (i = 0; i < argc; i++) {
2580 err = got_worktree_resolve_path(&path, worktree, argv[i]);
2581 if (err)
2582 break;
2583 err = got_pathlist_insert(&new, paths, path, NULL);
2584 if (err || new == NULL /* duplicate */) {
2585 free(path);
2586 if (err)
2587 break;
2591 return err;
2594 static const struct got_error *
2595 wrap_not_worktree_error(const struct got_error *orig_err,
2596 const char *cmdname, const char *path)
2598 const struct got_error *err;
2599 struct got_repository *repo;
2600 static char msg[512];
2601 int *pack_fds = NULL;
2603 err = got_repo_pack_fds_open(&pack_fds);
2604 if (err)
2605 return err;
2607 err = got_repo_open(&repo, path, NULL, pack_fds);
2608 if (err)
2609 return orig_err;
2611 snprintf(msg, sizeof(msg),
2612 "'got %s' needs a work tree in addition to a git repository\n"
2613 "Work trees can be checked out from this Git repository with "
2614 "'got checkout'.\n"
2615 "The got(1) manual page contains more information.", cmdname);
2616 err = got_error_msg(GOT_ERR_NOT_WORKTREE, msg);
2617 if (repo) {
2618 const struct got_error *close_err = got_repo_close(repo);
2619 if (err == NULL)
2620 err = close_err;
2622 if (pack_fds) {
2623 const struct got_error *pack_err =
2624 got_repo_pack_fds_close(pack_fds);
2625 if (err == NULL)
2626 err = pack_err;
2628 return err;
2631 static const struct got_error *
2632 cmd_update(int argc, char *argv[])
2634 const struct got_error *error = NULL, *unlock_err;
2635 char *worktree_path = NULL;
2636 const char *repo_path = NULL;
2637 const char *remote_name = NULL;
2638 char *proto = NULL, *host = NULL, *port = NULL;
2639 char *repo_name = NULL, *server_path = NULL;
2640 const struct got_remote_repo *remotes, *remote = NULL;
2641 int nremotes;
2642 char *id_str = NULL;
2643 struct got_repository *repo = NULL;
2644 struct got_worktree *worktree = NULL;
2645 const struct got_gotconfig *repo_conf = NULL, *worktree_conf = NULL;
2646 struct got_pathlist_head paths, refs, symrefs;
2647 struct got_pathlist_head wanted_branches, wanted_refs;
2648 struct got_pathlist_entry *pe;
2649 struct got_reflist_head remote_refs;
2650 struct got_reflist_entry *re;
2651 struct got_object_id *pack_hash = NULL;
2652 int i, ch, fetchfd = -1, fetchstatus;
2653 pid_t fetchpid = -1;
2654 struct got_fetch_progress_arg fpa;
2655 struct got_update_progress_arg upa;
2656 int verbosity = 0;
2657 int delete_remote = 0;
2658 int replace_tags = 0;
2659 int *pack_fds = NULL;
2660 const char *remote_head = NULL, *worktree_branch = NULL;
2661 struct got_object_id *commit_id = NULL;
2662 char *commit_id_str = NULL;
2663 const char *refname;
2664 struct got_reference *head_ref = NULL;
2666 TAILQ_INIT(&paths);
2667 TAILQ_INIT(&refs);
2668 TAILQ_INIT(&symrefs);
2669 TAILQ_INIT(&remote_refs);
2670 TAILQ_INIT(&wanted_branches);
2671 TAILQ_INIT(&wanted_refs);
2673 while ((ch = getopt(argc, argv, "c:qr:vX")) != -1) {
2674 switch (ch) {
2675 case 'c':
2676 commit_id_str = strdup(optarg);
2677 if (commit_id_str == NULL)
2678 return got_error_from_errno("strdup");
2679 break;
2680 case 't':
2681 replace_tags = 1;
2682 break;
2683 case 'q':
2684 verbosity = -1;
2685 break;
2686 case 'r':
2687 remote_name = optarg;
2688 break;
2689 case 'v':
2690 if (verbosity < 0)
2691 verbosity = 0;
2692 else if (verbosity < 3)
2693 verbosity++;
2694 break;
2695 case 'X':
2696 delete_remote = 1;
2697 break;
2698 default:
2699 usage_update();
2700 break;
2703 argc -= optind;
2704 argv += optind;
2706 if (delete_remote) {
2707 if (replace_tags)
2708 option_conflict('X', 't');
2709 if (remote_name == NULL)
2710 errx(1, "-X option requires a remote name");
2712 if (remote_name == NULL)
2713 remote_name = GOT_FETCH_DEFAULT_REMOTE_NAME;
2715 worktree_path = getcwd(NULL, 0);
2716 if (worktree_path == NULL) {
2717 error = got_error_from_errno("getcwd");
2718 goto done;
2720 error = got_worktree_open(&worktree, worktree_path, GOT_WORKTREE_CVG_DIR);
2721 if (error) {
2722 if (error->code == GOT_ERR_NOT_WORKTREE)
2723 error = wrap_not_worktree_error(error, "update",
2724 worktree_path);
2725 goto done;
2727 repo_path = got_worktree_get_repo_path(worktree);
2729 error = got_repo_pack_fds_open(&pack_fds);
2730 if (error != NULL)
2731 goto done;
2733 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
2734 if (error)
2735 goto done;
2737 error = check_rebase_or_histedit_in_progress(worktree);
2738 if (error)
2739 goto done;
2740 error = check_merge_in_progress(worktree, repo);
2741 if (error)
2742 goto done;
2744 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
2745 if (error)
2746 goto done;
2748 worktree_conf = got_worktree_get_gotconfig(worktree);
2749 if (worktree_conf) {
2750 got_gotconfig_get_remotes(&nremotes, &remotes,
2751 worktree_conf);
2752 for (i = 0; i < nremotes; i++) {
2753 if (strcmp(remotes[i].name, remote_name) == 0) {
2754 remote = &remotes[i];
2755 break;
2760 if (remote == NULL) {
2761 repo_conf = got_repo_get_gotconfig(repo);
2762 if (repo_conf) {
2763 got_gotconfig_get_remotes(&nremotes, &remotes,
2764 repo_conf);
2765 for (i = 0; i < nremotes; i++) {
2766 if (strcmp(remotes[i].name, remote_name) == 0) {
2767 remote = &remotes[i];
2768 break;
2773 if (remote == NULL) {
2774 got_repo_get_gitconfig_remotes(&nremotes, &remotes, repo);
2775 for (i = 0; i < nremotes; i++) {
2776 if (strcmp(remotes[i].name, remote_name) == 0) {
2777 remote = &remotes[i];
2778 break;
2782 if (remote == NULL) {
2783 error = got_error_path(remote_name, GOT_ERR_NO_REMOTE);
2784 goto done;
2787 error = got_dial_parse_uri(&proto, &host, &port, &server_path,
2788 &repo_name, remote->fetch_url);
2789 if (error)
2790 goto done;
2792 if (strcmp(proto, "git") == 0) {
2793 #ifndef PROFILE
2794 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
2795 "sendfd dns inet unveil", NULL) == -1)
2796 err(1, "pledge");
2797 #endif
2798 } else if (strcmp(proto, "git+ssh") == 0 ||
2799 strcmp(proto, "ssh") == 0) {
2800 #ifndef PROFILE
2801 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
2802 "sendfd unveil", NULL) == -1)
2803 err(1, "pledge");
2804 #endif
2805 } else if (strcmp(proto, "http") == 0 ||
2806 strcmp(proto, "git+http") == 0) {
2807 error = got_error_path(proto, GOT_ERR_NOT_IMPL);
2808 goto done;
2809 } else {
2810 error = got_error_path(proto, GOT_ERR_BAD_PROTO);
2811 goto done;
2814 error = got_dial_apply_unveil(proto);
2815 if (error)
2816 goto done;
2818 error = apply_unveil(got_repo_get_path(repo), 0,
2819 got_worktree_get_root_path(worktree));
2820 if (error)
2821 goto done;
2823 if (verbosity >= 0) {
2824 printf("Connecting to \"%s\" %s://%s%s%s%s%s\n",
2825 remote->name, proto, host,
2826 port ? ":" : "", port ? port : "",
2827 *server_path == '/' ? "" : "/", server_path);
2830 error = got_fetch_connect(&fetchpid, &fetchfd, proto, host, port,
2831 server_path, verbosity);
2832 if (error)
2833 goto done;
2836 * If set, get this remote's HEAD ref target so
2837 * if it has changed on the server we can fetch it.
2839 error = got_ref_list(&remote_refs, repo, "refs/remotes",
2840 got_ref_cmp_by_name, repo);
2841 if (error)
2842 goto done;
2844 TAILQ_FOREACH(re, &remote_refs, entry) {
2845 const char *remote_refname, *remote_target;
2846 size_t remote_name_len;
2848 if (!got_ref_is_symbolic(re->ref))
2849 continue;
2851 remote_name_len = strlen(remote->name);
2852 remote_refname = got_ref_get_name(re->ref);
2854 /* we only want refs/remotes/$remote->name/HEAD */
2855 if (strncmp(remote_refname + 13, remote->name,
2856 remote_name_len) != 0)
2857 continue;
2859 if (strcmp(remote_refname + remote_name_len + 14,
2860 GOT_REF_HEAD) != 0)
2861 continue;
2864 * Take the name itself because we already
2865 * only match with refs/heads/ in fetch_pack().
2867 remote_target = got_ref_get_symref_target(re->ref);
2868 remote_head = remote_target + remote_name_len + 14;
2869 break;
2872 refname = got_worktree_get_head_ref_name(worktree);
2873 if (strncmp(refname, "refs/heads/", 11) == 0)
2874 worktree_branch = refname;
2876 fpa.last_scaled_size[0] = '\0';
2877 fpa.last_p_indexed = -1;
2878 fpa.last_p_resolved = -1;
2879 fpa.verbosity = verbosity;
2880 fpa.repo = repo;
2881 fpa.create_configs = 0;
2882 fpa.configs_created = 0;
2883 memset(&fpa.config_info, 0, sizeof(fpa.config_info));
2885 error = got_fetch_pack(&pack_hash, &refs, &symrefs, remote->name,
2886 remote->mirror_references, 0, &wanted_branches, &wanted_refs,
2887 0, verbosity, fetchfd, repo, worktree_branch, remote_head,
2888 0, fetch_progress, &fpa);
2889 if (error)
2890 goto done;
2892 if (pack_hash != NULL && verbosity >= 0) {
2893 error = got_object_id_str(&id_str, pack_hash);
2894 if (error)
2895 goto done;
2896 printf("\nFetched %s.pack\n", id_str);
2897 free(id_str);
2898 id_str = NULL;
2901 /* Update references provided with the pack file. */
2902 TAILQ_FOREACH(pe, &refs, entry) {
2903 const char *refname = pe->path;
2904 struct got_object_id *id = pe->data;
2905 struct got_reference *ref;
2907 if (is_wanted_ref(&wanted_refs, refname)) {
2908 error = update_wanted_ref(refname, id,
2909 remote->name, verbosity, repo);
2910 if (error)
2911 goto done;
2912 continue;
2915 error = got_ref_open(&ref, repo, refname, 1);
2916 if (error) {
2917 if (error->code != GOT_ERR_NOT_REF)
2918 goto done;
2919 error = create_ref(refname, id, verbosity,
2920 repo);
2921 if (error)
2922 goto done;
2923 } else {
2924 error = update_ref(ref, id, replace_tags,
2925 verbosity-1, repo);
2926 unlock_err = got_ref_unlock(ref);
2927 if (unlock_err && error == NULL)
2928 error = unlock_err;
2929 got_ref_close(ref);
2930 if (error)
2931 goto done;
2935 /* Update worktree */
2936 error = got_ref_open(&head_ref, repo,
2937 got_worktree_get_head_ref_name(worktree), 0);
2938 if (error != NULL)
2939 goto done;
2940 if (commit_id_str == NULL) {
2941 error = got_ref_resolve(&commit_id, repo, head_ref);
2942 if (error != NULL)
2943 goto done;
2944 error = got_object_id_str(&commit_id_str, commit_id);
2945 if (error != NULL)
2946 goto done;
2947 } else {
2948 struct got_reflist_head refs;
2949 TAILQ_INIT(&refs);
2950 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
2951 NULL);
2952 if (error)
2953 goto done;
2954 error = got_repo_match_object_id(&commit_id, NULL,
2955 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
2956 got_ref_list_free(&refs);
2957 free(commit_id_str);
2958 commit_id_str = NULL;
2959 if (error)
2960 goto done;
2961 error = got_object_id_str(&commit_id_str, commit_id);
2962 if (error)
2963 goto done;
2967 error = check_linear_ancestry(commit_id,
2968 got_worktree_get_base_commit_id(worktree), 0, repo);
2969 if (error != NULL) {
2970 if (error->code == GOT_ERR_ANCESTRY)
2971 error = got_error(GOT_ERR_BRANCH_MOVED);
2972 goto done;
2974 error = check_same_branch(commit_id, head_ref, repo);
2975 if (error)
2976 goto done;
2978 if (got_object_id_cmp(got_worktree_get_base_commit_id(worktree),
2979 commit_id) != 0) {
2980 error = got_worktree_set_base_commit_id(worktree, repo,
2981 commit_id);
2982 if (error)
2983 goto done;
2986 memset(&upa, 0, sizeof(upa));
2987 upa.verbosity = verbosity;
2988 error = got_worktree_checkout_files(worktree, &paths, repo,
2989 update_progress, &upa, check_cancelled, NULL);
2990 if (error != NULL)
2991 goto done;
2993 if (upa.did_something) {
2994 printf("Updated to %s: %s\n",
2995 got_worktree_get_head_ref_name(worktree), commit_id_str);
2996 } else
2997 printf("Already up-to-date\n");
2999 print_update_progress_stats(&upa);
3000 done:
3001 if (fetchpid > 0) {
3002 if (kill(fetchpid, SIGTERM) == -1)
3003 error = got_error_from_errno("kill");
3004 if (waitpid(fetchpid, &fetchstatus, 0) == -1 && error == NULL)
3005 error = got_error_from_errno("waitpid");
3007 if (fetchfd != -1 && close(fetchfd) == -1 && error == NULL)
3008 error = got_error_from_errno("close");
3009 if (repo) {
3010 const struct got_error *close_err = got_repo_close(repo);
3011 if (error == NULL)
3012 error = close_err;
3014 if (worktree)
3015 got_worktree_close(worktree);
3016 if (pack_fds) {
3017 const struct got_error *pack_err =
3018 got_repo_pack_fds_close(pack_fds);
3019 if (error == NULL)
3020 error = pack_err;
3022 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
3023 got_pathlist_free(&refs, GOT_PATHLIST_FREE_ALL);
3024 got_pathlist_free(&symrefs, GOT_PATHLIST_FREE_ALL);
3025 got_pathlist_free(&wanted_branches, GOT_PATHLIST_FREE_NONE);
3026 got_pathlist_free(&wanted_refs, GOT_PATHLIST_FREE_NONE);
3027 got_ref_list_free(&remote_refs);
3028 free(id_str);
3029 free(worktree_path);
3030 free(pack_hash);
3031 free(proto);
3032 free(host);
3033 free(port);
3034 free(server_path);
3035 free(repo_name);
3036 free(commit_id);
3037 free(commit_id_str);
3038 return error;
3041 static const struct got_error *
3042 diff_blobs(struct got_object_id *blob_id1, struct got_object_id *blob_id2,
3043 const char *path, int diff_context, int ignore_whitespace,
3044 int force_text_diff, struct got_diffstat_cb_arg *dsa,
3045 struct got_repository *repo, FILE *outfile)
3047 const struct got_error *err = NULL;
3048 struct got_blob_object *blob1 = NULL, *blob2 = NULL;
3049 FILE *f1 = NULL, *f2 = NULL;
3050 int fd1 = -1, fd2 = -1;
3052 fd1 = got_opentempfd();
3053 if (fd1 == -1)
3054 return got_error_from_errno("got_opentempfd");
3055 fd2 = got_opentempfd();
3056 if (fd2 == -1) {
3057 err = got_error_from_errno("got_opentempfd");
3058 goto done;
3061 if (blob_id1) {
3062 err = got_object_open_as_blob(&blob1, repo, blob_id1, 8192,
3063 fd1);
3064 if (err)
3065 goto done;
3068 err = got_object_open_as_blob(&blob2, repo, blob_id2, 8192, fd2);
3069 if (err)
3070 goto done;
3072 f1 = got_opentemp();
3073 if (f1 == NULL) {
3074 err = got_error_from_errno("got_opentemp");
3075 goto done;
3077 f2 = got_opentemp();
3078 if (f2 == NULL) {
3079 err = got_error_from_errno("got_opentemp");
3080 goto done;
3083 while (path[0] == '/')
3084 path++;
3085 err = got_diff_blob(NULL, NULL, blob1, blob2, f1, f2, path, path,
3086 GOT_DIFF_ALGORITHM_PATIENCE, diff_context, ignore_whitespace,
3087 force_text_diff, dsa, outfile);
3088 done:
3089 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
3090 err = got_error_from_errno("close");
3091 if (blob1)
3092 got_object_blob_close(blob1);
3093 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
3094 err = got_error_from_errno("close");
3095 if (blob2)
3096 got_object_blob_close(blob2);
3097 if (f1 && fclose(f1) == EOF && err == NULL)
3098 err = got_error_from_errno("fclose");
3099 if (f2 && fclose(f2) == EOF && err == NULL)
3100 err = got_error_from_errno("fclose");
3101 return err;
3104 static const struct got_error *
3105 diff_trees(struct got_object_id *tree_id1, struct got_object_id *tree_id2,
3106 const char *path, int diff_context, int ignore_whitespace,
3107 int force_text_diff, struct got_diffstat_cb_arg *dsa,
3108 struct got_repository *repo, FILE *outfile)
3110 const struct got_error *err = NULL;
3111 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
3112 struct got_diff_blob_output_unidiff_arg arg;
3113 FILE *f1 = NULL, *f2 = NULL;
3114 int fd1 = -1, fd2 = -1;
3116 if (tree_id1) {
3117 err = got_object_open_as_tree(&tree1, repo, tree_id1);
3118 if (err)
3119 goto done;
3120 fd1 = got_opentempfd();
3121 if (fd1 == -1) {
3122 err = got_error_from_errno("got_opentempfd");
3123 goto done;
3127 err = got_object_open_as_tree(&tree2, repo, tree_id2);
3128 if (err)
3129 goto done;
3131 f1 = got_opentemp();
3132 if (f1 == NULL) {
3133 err = got_error_from_errno("got_opentemp");
3134 goto done;
3137 f2 = got_opentemp();
3138 if (f2 == NULL) {
3139 err = got_error_from_errno("got_opentemp");
3140 goto done;
3142 fd2 = got_opentempfd();
3143 if (fd2 == -1) {
3144 err = got_error_from_errno("got_opentempfd");
3145 goto done;
3147 arg.diff_context = diff_context;
3148 arg.ignore_whitespace = ignore_whitespace;
3149 arg.force_text_diff = force_text_diff;
3150 arg.diffstat = dsa;
3151 arg.diff_algo = GOT_DIFF_ALGORITHM_PATIENCE;
3152 arg.outfile = outfile;
3153 arg.lines = NULL;
3154 arg.nlines = 0;
3155 while (path[0] == '/')
3156 path++;
3157 err = got_diff_tree(tree1, tree2, f1, f2, fd1, fd2, path, path, repo,
3158 got_diff_blob_output_unidiff, &arg, 1);
3159 done:
3160 if (tree1)
3161 got_object_tree_close(tree1);
3162 if (tree2)
3163 got_object_tree_close(tree2);
3164 if (f1 && fclose(f1) == EOF && err == NULL)
3165 err = got_error_from_errno("fclose");
3166 if (f2 && fclose(f2) == EOF && err == NULL)
3167 err = got_error_from_errno("fclose");
3168 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
3169 err = got_error_from_errno("close");
3170 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
3171 err = got_error_from_errno("close");
3172 return err;
3175 static const struct got_error *
3176 get_changed_paths(struct got_pathlist_head *paths,
3177 struct got_commit_object *commit, struct got_repository *repo,
3178 struct got_diffstat_cb_arg *dsa)
3180 const struct got_error *err = NULL;
3181 struct got_object_id *tree_id1 = NULL, *tree_id2 = NULL;
3182 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
3183 struct got_object_qid *qid;
3184 got_diff_blob_cb cb = got_diff_tree_collect_changed_paths;
3185 FILE *f1 = NULL, *f2 = NULL;
3186 int fd1 = -1, fd2 = -1;
3188 if (dsa) {
3189 cb = got_diff_tree_compute_diffstat;
3191 f1 = got_opentemp();
3192 if (f1 == NULL) {
3193 err = got_error_from_errno("got_opentemp");
3194 goto done;
3196 f2 = got_opentemp();
3197 if (f2 == NULL) {
3198 err = got_error_from_errno("got_opentemp");
3199 goto done;
3201 fd1 = got_opentempfd();
3202 if (fd1 == -1) {
3203 err = got_error_from_errno("got_opentempfd");
3204 goto done;
3206 fd2 = got_opentempfd();
3207 if (fd2 == -1) {
3208 err = got_error_from_errno("got_opentempfd");
3209 goto done;
3213 qid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
3214 if (qid != NULL) {
3215 struct got_commit_object *pcommit;
3216 err = got_object_open_as_commit(&pcommit, repo,
3217 &qid->id);
3218 if (err)
3219 return err;
3221 tree_id1 = got_object_id_dup(
3222 got_object_commit_get_tree_id(pcommit));
3223 if (tree_id1 == NULL) {
3224 got_object_commit_close(pcommit);
3225 return got_error_from_errno("got_object_id_dup");
3227 got_object_commit_close(pcommit);
3231 if (tree_id1) {
3232 err = got_object_open_as_tree(&tree1, repo, tree_id1);
3233 if (err)
3234 goto done;
3237 tree_id2 = got_object_commit_get_tree_id(commit);
3238 err = got_object_open_as_tree(&tree2, repo, tree_id2);
3239 if (err)
3240 goto done;
3242 err = got_diff_tree(tree1, tree2, f1, f2, fd1, fd2, "", "", repo,
3243 cb, dsa ? (void *)dsa : paths, dsa ? 1 : 0);
3244 done:
3245 if (tree1)
3246 got_object_tree_close(tree1);
3247 if (tree2)
3248 got_object_tree_close(tree2);
3249 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
3250 err = got_error_from_errno("close");
3251 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
3252 err = got_error_from_errno("close");
3253 if (f1 && fclose(f1) == EOF && err == NULL)
3254 err = got_error_from_errno("fclose");
3255 if (f2 && fclose(f2) == EOF && err == NULL)
3256 err = got_error_from_errno("fclose");
3257 free(tree_id1);
3258 return err;
3261 static const struct got_error *
3262 print_patch(struct got_commit_object *commit, struct got_object_id *id,
3263 const char *path, int diff_context, struct got_diffstat_cb_arg *dsa,
3264 struct got_repository *repo, FILE *outfile)
3266 const struct got_error *err = NULL;
3267 struct got_commit_object *pcommit = NULL;
3268 char *id_str1 = NULL, *id_str2 = NULL;
3269 struct got_object_id *obj_id1 = NULL, *obj_id2 = NULL;
3270 struct got_object_qid *qid;
3272 qid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
3273 if (qid != NULL) {
3274 err = got_object_open_as_commit(&pcommit, repo,
3275 &qid->id);
3276 if (err)
3277 return err;
3278 err = got_object_id_str(&id_str1, &qid->id);
3279 if (err)
3280 goto done;
3283 err = got_object_id_str(&id_str2, id);
3284 if (err)
3285 goto done;
3287 if (path && path[0] != '\0') {
3288 int obj_type;
3289 err = got_object_id_by_path(&obj_id2, repo, commit, path);
3290 if (err)
3291 goto done;
3292 if (pcommit) {
3293 err = got_object_id_by_path(&obj_id1, repo,
3294 pcommit, path);
3295 if (err) {
3296 if (err->code != GOT_ERR_NO_TREE_ENTRY) {
3297 free(obj_id2);
3298 goto done;
3302 err = got_object_get_type(&obj_type, repo, obj_id2);
3303 if (err) {
3304 free(obj_id2);
3305 goto done;
3307 fprintf(outfile,
3308 "diff %s %s\n", id_str1 ? id_str1 : "/dev/null", id_str2);
3309 fprintf(outfile, "commit - %s\n",
3310 id_str1 ? id_str1 : "/dev/null");
3311 fprintf(outfile, "commit + %s\n", id_str2);
3312 switch (obj_type) {
3313 case GOT_OBJ_TYPE_BLOB:
3314 err = diff_blobs(obj_id1, obj_id2, path, diff_context,
3315 0, 0, dsa, repo, outfile);
3316 break;
3317 case GOT_OBJ_TYPE_TREE:
3318 err = diff_trees(obj_id1, obj_id2, path, diff_context,
3319 0, 0, dsa, repo, outfile);
3320 break;
3321 default:
3322 err = got_error(GOT_ERR_OBJ_TYPE);
3323 break;
3325 free(obj_id1);
3326 free(obj_id2);
3327 } else {
3328 obj_id2 = got_object_commit_get_tree_id(commit);
3329 if (pcommit)
3330 obj_id1 = got_object_commit_get_tree_id(pcommit);
3331 fprintf(outfile,
3332 "diff %s %s\n", id_str1 ? id_str1 : "/dev/null", id_str2);
3333 fprintf(outfile, "commit - %s\n",
3334 id_str1 ? id_str1 : "/dev/null");
3335 fprintf(outfile, "commit + %s\n", id_str2);
3336 err = diff_trees(obj_id1, obj_id2, "", diff_context, 0, 0,
3337 dsa, repo, outfile);
3339 done:
3340 free(id_str1);
3341 free(id_str2);
3342 if (pcommit)
3343 got_object_commit_close(pcommit);
3344 return err;
3347 static char *
3348 get_datestr(time_t *time, char *datebuf)
3350 struct tm mytm, *tm;
3351 char *p, *s;
3353 tm = gmtime_r(time, &mytm);
3354 if (tm == NULL)
3355 return NULL;
3356 s = asctime_r(tm, datebuf);
3357 if (s == NULL)
3358 return NULL;
3359 p = strchr(s, '\n');
3360 if (p)
3361 *p = '\0';
3362 return s;
3365 static const struct got_error *
3366 match_commit(int *have_match, struct got_object_id *id,
3367 struct got_commit_object *commit, regex_t *regex)
3369 const struct got_error *err = NULL;
3370 regmatch_t regmatch;
3371 char *id_str = NULL, *logmsg = NULL;
3373 *have_match = 0;
3375 err = got_object_id_str(&id_str, id);
3376 if (err)
3377 return err;
3379 err = got_object_commit_get_logmsg(&logmsg, commit);
3380 if (err)
3381 goto done;
3383 if (regexec(regex, got_object_commit_get_author(commit), 1,
3384 &regmatch, 0) == 0 ||
3385 regexec(regex, got_object_commit_get_committer(commit), 1,
3386 &regmatch, 0) == 0 ||
3387 regexec(regex, id_str, 1, &regmatch, 0) == 0 ||
3388 regexec(regex, logmsg, 1, &regmatch, 0) == 0)
3389 *have_match = 1;
3390 done:
3391 free(id_str);
3392 free(logmsg);
3393 return err;
3396 static void
3397 match_changed_paths(int *have_match, struct got_pathlist_head *changed_paths,
3398 regex_t *regex)
3400 regmatch_t regmatch;
3401 struct got_pathlist_entry *pe;
3403 *have_match = 0;
3405 TAILQ_FOREACH(pe, changed_paths, entry) {
3406 if (regexec(regex, pe->path, 1, &regmatch, 0) == 0) {
3407 *have_match = 1;
3408 break;
3413 static const struct got_error *
3414 match_patch(int *have_match, struct got_commit_object *commit,
3415 struct got_object_id *id, const char *path, int diff_context,
3416 struct got_repository *repo, regex_t *regex, FILE *f)
3418 const struct got_error *err = NULL;
3419 char *line = NULL;
3420 size_t linesize = 0;
3421 regmatch_t regmatch;
3423 *have_match = 0;
3425 err = got_opentemp_truncate(f);
3426 if (err)
3427 return err;
3429 err = print_patch(commit, id, path, diff_context, NULL, repo, f);
3430 if (err)
3431 goto done;
3433 if (fseeko(f, 0L, SEEK_SET) == -1) {
3434 err = got_error_from_errno("fseeko");
3435 goto done;
3438 while (getline(&line, &linesize, f) != -1) {
3439 if (regexec(regex, line, 1, &regmatch, 0) == 0) {
3440 *have_match = 1;
3441 break;
3444 done:
3445 free(line);
3446 return err;
3449 #define GOT_COMMIT_SEP_STR "-----------------------------------------------\n"
3451 static const struct got_error*
3452 build_refs_str(char **refs_str, struct got_reflist_head *refs,
3453 struct got_object_id *id, struct got_repository *repo,
3454 int local_only)
3456 static const struct got_error *err = NULL;
3457 struct got_reflist_entry *re;
3458 char *s;
3459 const char *name;
3461 *refs_str = NULL;
3463 TAILQ_FOREACH(re, refs, entry) {
3464 struct got_tag_object *tag = NULL;
3465 struct got_object_id *ref_id;
3466 int cmp;
3468 name = got_ref_get_name(re->ref);
3469 if (strcmp(name, GOT_REF_HEAD) == 0)
3470 continue;
3471 if (strncmp(name, "refs/", 5) == 0)
3472 name += 5;
3473 if (strncmp(name, "got/", 4) == 0)
3474 continue;
3475 if (strncmp(name, "heads/", 6) == 0)
3476 name += 6;
3477 if (strncmp(name, "remotes/", 8) == 0) {
3478 if (local_only)
3479 continue;
3480 name += 8;
3481 s = strstr(name, "/" GOT_REF_HEAD);
3482 if (s != NULL && strcmp(s, "/" GOT_REF_HEAD) == 0)
3483 continue;
3485 err = got_ref_resolve(&ref_id, repo, re->ref);
3486 if (err)
3487 break;
3488 if (strncmp(name, "tags/", 5) == 0) {
3489 err = got_object_open_as_tag(&tag, repo, ref_id);
3490 if (err) {
3491 if (err->code != GOT_ERR_OBJ_TYPE) {
3492 free(ref_id);
3493 break;
3495 /* Ref points at something other than a tag. */
3496 err = NULL;
3497 tag = NULL;
3500 cmp = got_object_id_cmp(tag ?
3501 got_object_tag_get_object_id(tag) : ref_id, id);
3502 free(ref_id);
3503 if (tag)
3504 got_object_tag_close(tag);
3505 if (cmp != 0)
3506 continue;
3507 s = *refs_str;
3508 if (asprintf(refs_str, "%s%s%s", s ? s : "",
3509 s ? ", " : "", name) == -1) {
3510 err = got_error_from_errno("asprintf");
3511 free(s);
3512 *refs_str = NULL;
3513 break;
3515 free(s);
3518 return err;
3521 static const struct got_error *
3522 print_commit_oneline(struct got_commit_object *commit, struct got_object_id *id,
3523 struct got_repository *repo, struct got_reflist_object_id_map *refs_idmap)
3525 const struct got_error *err = NULL;
3526 char *ref_str = NULL, *id_str = NULL, *logmsg0 = NULL;
3527 char *comma, *s, *nl;
3528 struct got_reflist_head *refs;
3529 char datebuf[12]; /* YYYY-MM-DD + SPACE + NUL */
3530 struct tm tm;
3531 time_t committer_time;
3533 refs = got_reflist_object_id_map_lookup(refs_idmap, id);
3534 if (refs) {
3535 err = build_refs_str(&ref_str, refs, id, repo, 1);
3536 if (err)
3537 return err;
3539 /* Display the first matching ref only. */
3540 if (ref_str && (comma = strchr(ref_str, ',')) != NULL)
3541 *comma = '\0';
3544 if (ref_str == NULL) {
3545 err = got_object_id_str(&id_str, id);
3546 if (err)
3547 return err;
3550 committer_time = got_object_commit_get_committer_time(commit);
3551 if (gmtime_r(&committer_time, &tm) == NULL) {
3552 err = got_error_from_errno("gmtime_r");
3553 goto done;
3555 if (strftime(datebuf, sizeof(datebuf), "%G-%m-%d ", &tm) == 0) {
3556 err = got_error(GOT_ERR_NO_SPACE);
3557 goto done;
3560 err = got_object_commit_get_logmsg(&logmsg0, commit);
3561 if (err)
3562 goto done;
3564 s = logmsg0;
3565 while (isspace((unsigned char)s[0]))
3566 s++;
3568 nl = strchr(s, '\n');
3569 if (nl) {
3570 *nl = '\0';
3573 if (ref_str)
3574 printf("%s%-7s %s\n", datebuf, ref_str, s);
3575 else
3576 printf("%s%.7s %s\n", datebuf, id_str, s);
3578 if (fflush(stdout) != 0 && err == NULL)
3579 err = got_error_from_errno("fflush");
3580 done:
3581 free(id_str);
3582 free(ref_str);
3583 free(logmsg0);
3584 return err;
3587 static const struct got_error *
3588 print_diffstat(struct got_diffstat_cb_arg *dsa, const char *header)
3590 struct got_pathlist_entry *pe;
3592 if (header != NULL)
3593 printf("%s\n", header);
3595 TAILQ_FOREACH(pe, dsa->paths, entry) {
3596 struct got_diff_changed_path *cp = pe->data;
3597 int pad = dsa->max_path_len - pe->path_len + 1;
3599 printf(" %c %s%*c | %*d+ %*d-\n", cp->status, pe->path, pad,
3600 ' ', dsa->add_cols + 1, cp->add, dsa->rm_cols + 1, cp->rm);
3602 printf("\n%d file%s changed, %d insertion%s(+), %d deletion%s(-)\n\n",
3603 dsa->nfiles, dsa->nfiles > 1 ? "s" : "", dsa->ins,
3604 dsa->ins != 1 ? "s" : "", dsa->del, dsa->del != 1 ? "s" : "");
3606 if (fflush(stdout) != 0)
3607 return got_error_from_errno("fflush");
3609 return NULL;
3612 static const struct got_error *
3613 printfile(FILE *f)
3615 char buf[8192];
3616 size_t r;
3618 if (fseeko(f, 0L, SEEK_SET) == -1)
3619 return got_error_from_errno("fseek");
3621 for (;;) {
3622 r = fread(buf, 1, sizeof(buf), f);
3623 if (r == 0) {
3624 if (ferror(f))
3625 return got_error_from_errno("fread");
3626 if (feof(f))
3627 break;
3629 if (fwrite(buf, 1, r, stdout) != r)
3630 return got_ferror(stdout, GOT_ERR_IO);
3633 return NULL;
3636 static const struct got_error *
3637 print_commit(struct got_commit_object *commit, struct got_object_id *id,
3638 struct got_repository *repo, const char *path,
3639 struct got_pathlist_head *changed_paths,
3640 struct got_diffstat_cb_arg *diffstat, int show_patch, int diff_context,
3641 struct got_reflist_object_id_map *refs_idmap, const char *custom_refs_str,
3642 const char *prefix)
3644 const struct got_error *err = NULL;
3645 FILE *f = NULL;
3646 char *id_str, *datestr, *logmsg0, *logmsg, *line;
3647 char datebuf[26];
3648 time_t committer_time;
3649 const char *author, *committer;
3650 char *refs_str = NULL;
3652 err = got_object_id_str(&id_str, id);
3653 if (err)
3654 return err;
3656 if (custom_refs_str == NULL) {
3657 struct got_reflist_head *refs;
3658 refs = got_reflist_object_id_map_lookup(refs_idmap, id);
3659 if (refs) {
3660 err = build_refs_str(&refs_str, refs, id, repo, 0);
3661 if (err)
3662 goto done;
3666 printf(GOT_COMMIT_SEP_STR);
3667 if (custom_refs_str)
3668 printf("%s %s (%s)\n", prefix ? prefix : "commit", id_str,
3669 custom_refs_str);
3670 else
3671 printf("%s %s%s%s%s\n", prefix ? prefix : "commit", id_str,
3672 refs_str ? " (" : "", refs_str ? refs_str : "",
3673 refs_str ? ")" : "");
3674 free(id_str);
3675 id_str = NULL;
3676 free(refs_str);
3677 refs_str = NULL;
3678 printf("from: %s\n", got_object_commit_get_author(commit));
3679 author = got_object_commit_get_author(commit);
3680 committer = got_object_commit_get_committer(commit);
3681 if (strcmp(author, committer) != 0)
3682 printf("via: %s\n", committer);
3683 committer_time = got_object_commit_get_committer_time(commit);
3684 datestr = get_datestr(&committer_time, datebuf);
3685 if (datestr)
3686 printf("date: %s UTC\n", datestr);
3687 if (got_object_commit_get_nparents(commit) > 1) {
3688 const struct got_object_id_queue *parent_ids;
3689 struct got_object_qid *qid;
3690 int n = 1;
3691 parent_ids = got_object_commit_get_parent_ids(commit);
3692 STAILQ_FOREACH(qid, parent_ids, entry) {
3693 err = got_object_id_str(&id_str, &qid->id);
3694 if (err)
3695 goto done;
3696 printf("parent %d: %s\n", n++, id_str);
3697 free(id_str);
3698 id_str = NULL;
3702 err = got_object_commit_get_logmsg(&logmsg0, commit);
3703 if (err)
3704 goto done;
3706 logmsg = logmsg0;
3707 do {
3708 line = strsep(&logmsg, "\n");
3709 if (line)
3710 printf(" %s\n", line);
3711 } while (line);
3712 free(logmsg0);
3714 if (changed_paths && diffstat == NULL) {
3715 struct got_pathlist_entry *pe;
3717 TAILQ_FOREACH(pe, changed_paths, entry) {
3718 struct got_diff_changed_path *cp = pe->data;
3720 printf(" %c %s\n", cp->status, pe->path);
3722 printf("\n");
3724 if (show_patch) {
3725 if (diffstat) {
3726 f = got_opentemp();
3727 if (f == NULL) {
3728 err = got_error_from_errno("got_opentemp");
3729 goto done;
3733 err = print_patch(commit, id, path, diff_context, diffstat,
3734 repo, diffstat == NULL ? stdout : f);
3735 if (err)
3736 goto done;
3738 if (diffstat) {
3739 err = print_diffstat(diffstat, NULL);
3740 if (err)
3741 goto done;
3742 if (show_patch) {
3743 err = printfile(f);
3744 if (err)
3745 goto done;
3748 if (show_patch)
3749 printf("\n");
3751 if (fflush(stdout) != 0 && err == NULL)
3752 err = got_error_from_errno("fflush");
3753 done:
3754 if (f && fclose(f) == EOF && err == NULL)
3755 err = got_error_from_errno("fclose");
3756 free(id_str);
3757 free(refs_str);
3758 return err;
3761 static const struct got_error *
3762 print_commits(struct got_object_id *root_id, struct got_object_id *end_id,
3763 struct got_repository *repo, const char *path, int show_changed_paths,
3764 int show_diffstat, int show_patch, const char *search_pattern,
3765 int diff_context, int limit, int log_branches, int reverse_display_order,
3766 struct got_reflist_object_id_map *refs_idmap, int one_line,
3767 FILE *tmpfile)
3769 const struct got_error *err;
3770 struct got_commit_graph *graph;
3771 regex_t regex;
3772 int have_match;
3773 struct got_object_id_queue reversed_commits;
3774 struct got_object_qid *qid;
3775 struct got_commit_object *commit;
3776 struct got_pathlist_head changed_paths;
3778 STAILQ_INIT(&reversed_commits);
3779 TAILQ_INIT(&changed_paths);
3781 if (search_pattern && regcomp(&regex, search_pattern,
3782 REG_EXTENDED | REG_NOSUB | REG_NEWLINE))
3783 return got_error_msg(GOT_ERR_REGEX, search_pattern);
3785 err = got_commit_graph_open(&graph, path, !log_branches);
3786 if (err)
3787 return err;
3788 err = got_commit_graph_bfsort(graph, root_id, repo,
3789 check_cancelled, NULL);
3790 if (err)
3791 goto done;
3792 for (;;) {
3793 struct got_object_id id;
3794 struct got_diffstat_cb_arg dsa = { 0, 0, 0, 0, 0, 0,
3795 &changed_paths, 0, 0, GOT_DIFF_ALGORITHM_PATIENCE };
3797 if (sigint_received || sigpipe_received)
3798 break;
3800 err = got_commit_graph_iter_next(&id, graph, repo,
3801 check_cancelled, NULL);
3802 if (err) {
3803 if (err->code == GOT_ERR_ITER_COMPLETED)
3804 err = NULL;
3805 break;
3808 err = got_object_open_as_commit(&commit, repo, &id);
3809 if (err)
3810 break;
3812 if ((show_changed_paths || (show_diffstat && !show_patch))
3813 && !reverse_display_order) {
3814 err = get_changed_paths(&changed_paths, commit, repo,
3815 show_diffstat ? &dsa : NULL);
3816 if (err)
3817 break;
3820 if (search_pattern) {
3821 err = match_commit(&have_match, &id, commit, &regex);
3822 if (err) {
3823 got_object_commit_close(commit);
3824 break;
3826 if (have_match == 0 && show_changed_paths)
3827 match_changed_paths(&have_match,
3828 &changed_paths, &regex);
3829 if (have_match == 0 && show_patch) {
3830 err = match_patch(&have_match, commit, &id,
3831 path, diff_context, repo, &regex, tmpfile);
3832 if (err)
3833 break;
3835 if (have_match == 0) {
3836 got_object_commit_close(commit);
3837 got_pathlist_free(&changed_paths,
3838 GOT_PATHLIST_FREE_ALL);
3839 continue;
3843 if (reverse_display_order) {
3844 err = got_object_qid_alloc(&qid, &id);
3845 if (err)
3846 break;
3847 STAILQ_INSERT_HEAD(&reversed_commits, qid, entry);
3848 got_object_commit_close(commit);
3849 } else {
3850 if (one_line)
3851 err = print_commit_oneline(commit, &id,
3852 repo, refs_idmap);
3853 else
3854 err = print_commit(commit, &id, repo, path,
3855 (show_changed_paths || show_diffstat) ?
3856 &changed_paths : NULL,
3857 show_diffstat ? &dsa : NULL, show_patch,
3858 diff_context, refs_idmap, NULL, NULL);
3859 got_object_commit_close(commit);
3860 if (err)
3861 break;
3863 if ((limit && --limit == 0) ||
3864 (end_id && got_object_id_cmp(&id, end_id) == 0))
3865 break;
3867 got_pathlist_free(&changed_paths, GOT_PATHLIST_FREE_ALL);
3869 if (reverse_display_order) {
3870 STAILQ_FOREACH(qid, &reversed_commits, entry) {
3871 struct got_diffstat_cb_arg dsa = { 0, 0, 0, 0, 0, 0,
3872 &changed_paths, 0, 0, GOT_DIFF_ALGORITHM_PATIENCE };
3874 err = got_object_open_as_commit(&commit, repo,
3875 &qid->id);
3876 if (err)
3877 break;
3878 if (show_changed_paths ||
3879 (show_diffstat && !show_patch)) {
3880 err = get_changed_paths(&changed_paths, commit,
3881 repo, show_diffstat ? &dsa : NULL);
3882 if (err)
3883 break;
3885 if (one_line)
3886 err = print_commit_oneline(commit, &qid->id,
3887 repo, refs_idmap);
3888 else
3889 err = print_commit(commit, &qid->id, repo, path,
3890 (show_changed_paths || show_diffstat) ?
3891 &changed_paths : NULL,
3892 show_diffstat ? &dsa : NULL, show_patch,
3893 diff_context, refs_idmap, NULL, NULL);
3894 got_object_commit_close(commit);
3895 if (err)
3896 break;
3897 got_pathlist_free(&changed_paths, GOT_PATHLIST_FREE_ALL);
3900 done:
3901 while (!STAILQ_EMPTY(&reversed_commits)) {
3902 qid = STAILQ_FIRST(&reversed_commits);
3903 STAILQ_REMOVE_HEAD(&reversed_commits, entry);
3904 got_object_qid_free(qid);
3906 got_pathlist_free(&changed_paths, GOT_PATHLIST_FREE_ALL);
3907 if (search_pattern)
3908 regfree(&regex);
3909 got_commit_graph_close(graph);
3910 return err;
3913 __dead static void
3914 usage_log(void)
3916 fprintf(stderr, "usage: %s log [-bdPpRs] [-C number] [-c commit] "
3917 "[-l N] [-r repository-path] [-S search-pattern] [-x commit] "
3918 "[path]\n", getprogname());
3919 exit(1);
3922 static int
3923 get_default_log_limit(void)
3925 const char *got_default_log_limit;
3926 long long n;
3927 const char *errstr;
3929 got_default_log_limit = getenv("GOT_LOG_DEFAULT_LIMIT");
3930 if (got_default_log_limit == NULL)
3931 return 0;
3932 n = strtonum(got_default_log_limit, 0, INT_MAX, &errstr);
3933 if (errstr != NULL)
3934 return 0;
3935 return n;
3938 static const struct got_error *
3939 cmd_log(int argc, char *argv[])
3941 const struct got_error *error;
3942 struct got_repository *repo = NULL;
3943 struct got_worktree *worktree = NULL;
3944 struct got_object_id *start_id = NULL, *end_id = NULL;
3945 char *repo_path = NULL, *path = NULL, *cwd = NULL, *in_repo_path = NULL;
3946 const char *start_commit = NULL, *end_commit = NULL;
3947 const char *search_pattern = NULL;
3948 int diff_context = -1, ch;
3949 int show_changed_paths = 0, show_patch = 0, limit = 0, log_branches = 0;
3950 int show_diffstat = 0, reverse_display_order = 0, one_line = 0;
3951 const char *errstr;
3952 struct got_reflist_head refs;
3953 struct got_reflist_object_id_map *refs_idmap = NULL;
3954 FILE *tmpfile = NULL;
3955 int *pack_fds = NULL;
3957 TAILQ_INIT(&refs);
3959 #ifndef PROFILE
3960 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
3961 NULL)
3962 == -1)
3963 err(1, "pledge");
3964 #endif
3966 limit = get_default_log_limit();
3968 while ((ch = getopt(argc, argv, "bC:c:dl:PpRr:S:sx:")) != -1) {
3969 switch (ch) {
3970 case 'b':
3971 log_branches = 1;
3972 break;
3973 case 'C':
3974 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
3975 &errstr);
3976 if (errstr != NULL)
3977 errx(1, "number of context lines is %s: %s",
3978 errstr, optarg);
3979 break;
3980 case 'c':
3981 start_commit = optarg;
3982 break;
3983 case 'd':
3984 show_diffstat = 1;
3985 break;
3986 case 'l':
3987 limit = strtonum(optarg, 0, INT_MAX, &errstr);
3988 if (errstr != NULL)
3989 errx(1, "number of commits is %s: %s",
3990 errstr, optarg);
3991 break;
3992 case 'P':
3993 show_changed_paths = 1;
3994 break;
3995 case 'p':
3996 show_patch = 1;
3997 break;
3998 case 'R':
3999 reverse_display_order = 1;
4000 break;
4001 case 'r':
4002 repo_path = realpath(optarg, NULL);
4003 if (repo_path == NULL)
4004 return got_error_from_errno2("realpath",
4005 optarg);
4006 got_path_strip_trailing_slashes(repo_path);
4007 break;
4008 case 'S':
4009 search_pattern = optarg;
4010 break;
4011 case 's':
4012 one_line = 1;
4013 break;
4014 case 'x':
4015 end_commit = optarg;
4016 break;
4017 default:
4018 usage_log();
4019 /* NOTREACHED */
4023 argc -= optind;
4024 argv += optind;
4026 if (diff_context == -1)
4027 diff_context = 3;
4028 else if (!show_patch)
4029 errx(1, "-C requires -p");
4031 if (one_line && (show_patch || show_changed_paths || show_diffstat))
4032 errx(1, "cannot use -s with -d, -p or -P");
4034 cwd = getcwd(NULL, 0);
4035 if (cwd == NULL) {
4036 error = got_error_from_errno("getcwd");
4037 goto done;
4040 error = got_repo_pack_fds_open(&pack_fds);
4041 if (error != NULL)
4042 goto done;
4044 if (repo_path == NULL) {
4045 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_CVG_DIR);
4046 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4047 goto done;
4048 error = NULL;
4051 if (argc == 1) {
4052 if (worktree) {
4053 error = got_worktree_resolve_path(&path, worktree,
4054 argv[0]);
4055 if (error)
4056 goto done;
4057 } else {
4058 path = strdup(argv[0]);
4059 if (path == NULL) {
4060 error = got_error_from_errno("strdup");
4061 goto done;
4064 } else if (argc != 0)
4065 usage_log();
4067 if (repo_path == NULL) {
4068 repo_path = worktree ?
4069 strdup(got_worktree_get_repo_path(worktree)) : strdup(cwd);
4071 if (repo_path == NULL) {
4072 error = got_error_from_errno("strdup");
4073 goto done;
4076 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
4077 if (error != NULL)
4078 goto done;
4080 error = apply_unveil(got_repo_get_path(repo), 1,
4081 worktree ? got_worktree_get_root_path(worktree) : NULL);
4082 if (error)
4083 goto done;
4085 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
4086 if (error)
4087 goto done;
4089 error = got_reflist_object_id_map_create(&refs_idmap, &refs, repo);
4090 if (error)
4091 goto done;
4093 if (start_commit == NULL) {
4094 struct got_reference *head_ref;
4095 struct got_commit_object *commit = NULL;
4096 error = got_ref_open(&head_ref, repo,
4097 worktree ? got_worktree_get_head_ref_name(worktree)
4098 : GOT_REF_HEAD, 0);
4099 if (error != NULL)
4100 goto done;
4101 error = got_ref_resolve(&start_id, repo, head_ref);
4102 got_ref_close(head_ref);
4103 if (error != NULL)
4104 goto done;
4105 error = got_object_open_as_commit(&commit, repo,
4106 start_id);
4107 if (error != NULL)
4108 goto done;
4109 got_object_commit_close(commit);
4110 } else {
4111 error = got_repo_match_object_id(&start_id, NULL,
4112 start_commit, GOT_OBJ_TYPE_COMMIT, &refs, repo);
4113 if (error != NULL)
4114 goto done;
4116 if (end_commit != NULL) {
4117 error = got_repo_match_object_id(&end_id, NULL,
4118 end_commit, GOT_OBJ_TYPE_COMMIT, &refs, repo);
4119 if (error != NULL)
4120 goto done;
4123 if (worktree) {
4125 * If a path was specified on the command line it was resolved
4126 * to a path in the work tree above. Prepend the work tree's
4127 * path prefix to obtain the corresponding in-repository path.
4129 if (path) {
4130 const char *prefix;
4131 prefix = got_worktree_get_path_prefix(worktree);
4132 if (asprintf(&in_repo_path, "%s%s%s", prefix,
4133 (path[0] != '\0') ? "/" : "", path) == -1) {
4134 error = got_error_from_errno("asprintf");
4135 goto done;
4138 } else
4139 error = got_repo_map_path(&in_repo_path, repo,
4140 path ? path : "");
4141 if (error != NULL)
4142 goto done;
4143 if (in_repo_path) {
4144 free(path);
4145 path = in_repo_path;
4148 if (worktree) {
4149 /* Release work tree lock. */
4150 got_worktree_close(worktree);
4151 worktree = NULL;
4154 if (search_pattern && show_patch) {
4155 tmpfile = got_opentemp();
4156 if (tmpfile == NULL) {
4157 error = got_error_from_errno("got_opentemp");
4158 goto done;
4162 error = print_commits(start_id, end_id, repo, path ? path : "",
4163 show_changed_paths, show_diffstat, show_patch, search_pattern,
4164 diff_context, limit, log_branches, reverse_display_order,
4165 refs_idmap, one_line, tmpfile);
4166 done:
4167 free(path);
4168 free(repo_path);
4169 free(cwd);
4170 free(start_id);
4171 free(end_id);
4172 if (worktree)
4173 got_worktree_close(worktree);
4174 if (repo) {
4175 const struct got_error *close_err = got_repo_close(repo);
4176 if (error == NULL)
4177 error = close_err;
4179 if (pack_fds) {
4180 const struct got_error *pack_err =
4181 got_repo_pack_fds_close(pack_fds);
4182 if (error == NULL)
4183 error = pack_err;
4185 if (refs_idmap)
4186 got_reflist_object_id_map_free(refs_idmap);
4187 if (tmpfile && fclose(tmpfile) == EOF && error == NULL)
4188 error = got_error_from_errno("fclose");
4189 got_ref_list_free(&refs);
4190 return error;
4193 __dead static void
4194 usage_diff(void)
4196 fprintf(stderr, "usage: %s diff [-adPsw] [-C number] [-c commit] "
4197 "[-r repository-path] [object1 object2 | path ...]\n",
4198 getprogname());
4199 exit(1);
4202 struct print_diff_arg {
4203 struct got_repository *repo;
4204 struct got_worktree *worktree;
4205 struct got_diffstat_cb_arg *diffstat;
4206 int diff_context;
4207 const char *id_str;
4208 int header_shown;
4209 int diff_staged;
4210 enum got_diff_algorithm diff_algo;
4211 int ignore_whitespace;
4212 int force_text_diff;
4213 FILE *f1;
4214 FILE *f2;
4215 FILE *outfile;
4219 * Create a file which contains the target path of a symlink so we can feed
4220 * it as content to the diff engine.
4222 static const struct got_error *
4223 get_symlink_target_file(int *fd, int dirfd, const char *de_name,
4224 const char *abspath)
4226 const struct got_error *err = NULL;
4227 char target_path[PATH_MAX];
4228 ssize_t target_len, outlen;
4230 *fd = -1;
4232 if (dirfd != -1) {
4233 target_len = readlinkat(dirfd, de_name, target_path, PATH_MAX);
4234 if (target_len == -1)
4235 return got_error_from_errno2("readlinkat", abspath);
4236 } else {
4237 target_len = readlink(abspath, target_path, PATH_MAX);
4238 if (target_len == -1)
4239 return got_error_from_errno2("readlink", abspath);
4242 *fd = got_opentempfd();
4243 if (*fd == -1)
4244 return got_error_from_errno("got_opentempfd");
4246 outlen = write(*fd, target_path, target_len);
4247 if (outlen == -1) {
4248 err = got_error_from_errno("got_opentempfd");
4249 goto done;
4252 if (lseek(*fd, 0, SEEK_SET) == -1) {
4253 err = got_error_from_errno2("lseek", abspath);
4254 goto done;
4256 done:
4257 if (err) {
4258 close(*fd);
4259 *fd = -1;
4261 return err;
4264 static const struct got_error *
4265 print_diff(void *arg, unsigned char status, unsigned char staged_status,
4266 const char *path, struct got_object_id *blob_id,
4267 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
4268 int dirfd, const char *de_name)
4270 struct print_diff_arg *a = arg;
4271 const struct got_error *err = NULL;
4272 struct got_blob_object *blob1 = NULL;
4273 int fd = -1, fd1 = -1, fd2 = -1;
4274 FILE *f2 = NULL;
4275 char *abspath = NULL, *label1 = NULL;
4276 struct stat sb;
4277 off_t size1 = 0;
4278 int f2_exists = 0;
4280 memset(&sb, 0, sizeof(sb));
4282 if (a->diff_staged) {
4283 if (staged_status != GOT_STATUS_MODIFY &&
4284 staged_status != GOT_STATUS_ADD &&
4285 staged_status != GOT_STATUS_DELETE)
4286 return NULL;
4287 } else {
4288 if (staged_status == GOT_STATUS_DELETE)
4289 return NULL;
4290 if (status == GOT_STATUS_NONEXISTENT)
4291 return got_error_set_errno(ENOENT, path);
4292 if (status != GOT_STATUS_MODIFY &&
4293 status != GOT_STATUS_ADD &&
4294 status != GOT_STATUS_DELETE &&
4295 status != GOT_STATUS_CONFLICT)
4296 return NULL;
4299 err = got_opentemp_truncate(a->f1);
4300 if (err)
4301 return got_error_from_errno("got_opentemp_truncate");
4302 err = got_opentemp_truncate(a->f2);
4303 if (err)
4304 return got_error_from_errno("got_opentemp_truncate");
4306 if (!a->header_shown) {
4307 if (fprintf(a->outfile, "diff %s%s\n",
4308 a->diff_staged ? "-s " : "",
4309 got_worktree_get_root_path(a->worktree)) < 0) {
4310 err = got_error_from_errno("fprintf");
4311 goto done;
4313 if (fprintf(a->outfile, "commit - %s\n", a->id_str) < 0) {
4314 err = got_error_from_errno("fprintf");
4315 goto done;
4317 if (fprintf(a->outfile, "path + %s%s\n",
4318 got_worktree_get_root_path(a->worktree),
4319 a->diff_staged ? " (staged changes)" : "") < 0) {
4320 err = got_error_from_errno("fprintf");
4321 goto done;
4323 a->header_shown = 1;
4326 if (a->diff_staged) {
4327 const char *label1 = NULL, *label2 = NULL;
4328 switch (staged_status) {
4329 case GOT_STATUS_MODIFY:
4330 label1 = path;
4331 label2 = path;
4332 break;
4333 case GOT_STATUS_ADD:
4334 label2 = path;
4335 break;
4336 case GOT_STATUS_DELETE:
4337 label1 = path;
4338 break;
4339 default:
4340 return got_error(GOT_ERR_FILE_STATUS);
4342 fd1 = got_opentempfd();
4343 if (fd1 == -1) {
4344 err = got_error_from_errno("got_opentempfd");
4345 goto done;
4347 fd2 = got_opentempfd();
4348 if (fd2 == -1) {
4349 err = got_error_from_errno("got_opentempfd");
4350 goto done;
4352 err = got_diff_objects_as_blobs(NULL, NULL, a->f1, a->f2,
4353 fd1, fd2, blob_id, staged_blob_id, label1, label2,
4354 a->diff_algo, a->diff_context, a->ignore_whitespace,
4355 a->force_text_diff, a->diffstat, a->repo, a->outfile);
4356 goto done;
4359 fd1 = got_opentempfd();
4360 if (fd1 == -1) {
4361 err = got_error_from_errno("got_opentempfd");
4362 goto done;
4365 if (staged_status == GOT_STATUS_ADD ||
4366 staged_status == GOT_STATUS_MODIFY) {
4367 char *id_str;
4368 err = got_object_open_as_blob(&blob1, a->repo, staged_blob_id,
4369 8192, fd1);
4370 if (err)
4371 goto done;
4372 err = got_object_id_str(&id_str, staged_blob_id);
4373 if (err)
4374 goto done;
4375 if (asprintf(&label1, "%s (staged)", id_str) == -1) {
4376 err = got_error_from_errno("asprintf");
4377 free(id_str);
4378 goto done;
4380 free(id_str);
4381 } else if (status != GOT_STATUS_ADD) {
4382 err = got_object_open_as_blob(&blob1, a->repo, blob_id, 8192,
4383 fd1);
4384 if (err)
4385 goto done;
4388 if (status != GOT_STATUS_DELETE) {
4389 if (asprintf(&abspath, "%s/%s",
4390 got_worktree_get_root_path(a->worktree), path) == -1) {
4391 err = got_error_from_errno("asprintf");
4392 goto done;
4395 if (dirfd != -1) {
4396 fd = openat(dirfd, de_name,
4397 O_RDONLY | O_NOFOLLOW | O_CLOEXEC);
4398 if (fd == -1) {
4399 if (!got_err_open_nofollow_on_symlink()) {
4400 err = got_error_from_errno2("openat",
4401 abspath);
4402 goto done;
4404 err = get_symlink_target_file(&fd, dirfd,
4405 de_name, abspath);
4406 if (err)
4407 goto done;
4409 } else {
4410 fd = open(abspath, O_RDONLY | O_NOFOLLOW | O_CLOEXEC);
4411 if (fd == -1) {
4412 if (!got_err_open_nofollow_on_symlink()) {
4413 err = got_error_from_errno2("open",
4414 abspath);
4415 goto done;
4417 err = get_symlink_target_file(&fd, dirfd,
4418 de_name, abspath);
4419 if (err)
4420 goto done;
4423 if (fstatat(fd, abspath, &sb, AT_SYMLINK_NOFOLLOW) == -1) {
4424 err = got_error_from_errno2("fstatat", abspath);
4425 goto done;
4427 f2 = fdopen(fd, "r");
4428 if (f2 == NULL) {
4429 err = got_error_from_errno2("fdopen", abspath);
4430 goto done;
4432 fd = -1;
4433 f2_exists = 1;
4436 if (blob1) {
4437 err = got_object_blob_dump_to_file(&size1, NULL, NULL,
4438 a->f1, blob1);
4439 if (err)
4440 goto done;
4443 err = got_diff_blob_file(blob1, a->f1, size1, label1, f2 ? f2 : a->f2,
4444 f2_exists, &sb, path, GOT_DIFF_ALGORITHM_PATIENCE, a->diff_context,
4445 a->ignore_whitespace, a->force_text_diff, a->diffstat, a->outfile);
4446 done:
4447 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
4448 err = got_error_from_errno("close");
4449 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
4450 err = got_error_from_errno("close");
4451 if (blob1)
4452 got_object_blob_close(blob1);
4453 if (fd != -1 && close(fd) == -1 && err == NULL)
4454 err = got_error_from_errno("close");
4455 if (f2 && fclose(f2) == EOF && err == NULL)
4456 err = got_error_from_errno("fclose");
4457 free(abspath);
4458 return err;
4461 static const struct got_error *
4462 cmd_diff(int argc, char *argv[])
4464 const struct got_error *error;
4465 struct got_repository *repo = NULL;
4466 struct got_worktree *worktree = NULL;
4467 char *cwd = NULL, *repo_path = NULL;
4468 const char *commit_args[2] = { NULL, NULL };
4469 int ncommit_args = 0;
4470 struct got_object_id *ids[2] = { NULL, NULL };
4471 char *labels[2] = { NULL, NULL };
4472 int type1 = GOT_OBJ_TYPE_ANY, type2 = GOT_OBJ_TYPE_ANY;
4473 int diff_context = 3, diff_staged = 0, ignore_whitespace = 0, ch, i;
4474 int force_text_diff = 0, force_path = 0, rflag = 0, show_diffstat = 0;
4475 const char *errstr;
4476 struct got_reflist_head refs;
4477 struct got_pathlist_head diffstat_paths, paths;
4478 FILE *f1 = NULL, *f2 = NULL, *outfile = NULL;
4479 int fd1 = -1, fd2 = -1;
4480 int *pack_fds = NULL;
4481 struct got_diffstat_cb_arg dsa;
4483 memset(&dsa, 0, sizeof(dsa));
4485 TAILQ_INIT(&refs);
4486 TAILQ_INIT(&paths);
4487 TAILQ_INIT(&diffstat_paths);
4489 #ifndef PROFILE
4490 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
4491 NULL) == -1)
4492 err(1, "pledge");
4493 #endif
4495 while ((ch = getopt(argc, argv, "aC:c:dPr:sw")) != -1) {
4496 switch (ch) {
4497 case 'a':
4498 force_text_diff = 1;
4499 break;
4500 case 'C':
4501 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
4502 &errstr);
4503 if (errstr != NULL)
4504 errx(1, "number of context lines is %s: %s",
4505 errstr, optarg);
4506 break;
4507 case 'c':
4508 if (ncommit_args >= 2)
4509 errx(1, "too many -c options used");
4510 commit_args[ncommit_args++] = optarg;
4511 break;
4512 case 'd':
4513 show_diffstat = 1;
4514 break;
4515 case 'P':
4516 force_path = 1;
4517 break;
4518 case 'r':
4519 repo_path = realpath(optarg, NULL);
4520 if (repo_path == NULL)
4521 return got_error_from_errno2("realpath",
4522 optarg);
4523 got_path_strip_trailing_slashes(repo_path);
4524 rflag = 1;
4525 break;
4526 case 's':
4527 diff_staged = 1;
4528 break;
4529 case 'w':
4530 ignore_whitespace = 1;
4531 break;
4532 default:
4533 usage_diff();
4534 /* NOTREACHED */
4538 argc -= optind;
4539 argv += optind;
4541 cwd = getcwd(NULL, 0);
4542 if (cwd == NULL) {
4543 error = got_error_from_errno("getcwd");
4544 goto done;
4547 error = got_repo_pack_fds_open(&pack_fds);
4548 if (error != NULL)
4549 goto done;
4551 if (repo_path == NULL) {
4552 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_CVG_DIR);
4553 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4554 goto done;
4555 else
4556 error = NULL;
4557 if (worktree) {
4558 repo_path =
4559 strdup(got_worktree_get_repo_path(worktree));
4560 if (repo_path == NULL) {
4561 error = got_error_from_errno("strdup");
4562 goto done;
4564 } else {
4565 repo_path = strdup(cwd);
4566 if (repo_path == NULL) {
4567 error = got_error_from_errno("strdup");
4568 goto done;
4573 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
4574 free(repo_path);
4575 if (error != NULL)
4576 goto done;
4578 if (show_diffstat) {
4579 dsa.paths = &diffstat_paths;
4580 dsa.force_text = force_text_diff;
4581 dsa.ignore_ws = ignore_whitespace;
4582 dsa.diff_algo = GOT_DIFF_ALGORITHM_PATIENCE;
4585 if (rflag || worktree == NULL || ncommit_args > 0) {
4586 if (force_path) {
4587 error = got_error_msg(GOT_ERR_NOT_IMPL,
4588 "-P option can only be used when diffing "
4589 "a work tree");
4590 goto done;
4592 if (diff_staged) {
4593 error = got_error_msg(GOT_ERR_NOT_IMPL,
4594 "-s option can only be used when diffing "
4595 "a work tree");
4596 goto done;
4600 error = apply_unveil(got_repo_get_path(repo), 1,
4601 worktree ? got_worktree_get_root_path(worktree) : NULL);
4602 if (error)
4603 goto done;
4605 if ((!force_path && argc == 2) || ncommit_args > 0) {
4606 int obj_type = (ncommit_args > 0 ?
4607 GOT_OBJ_TYPE_COMMIT : GOT_OBJ_TYPE_ANY);
4608 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
4609 NULL);
4610 if (error)
4611 goto done;
4612 for (i = 0; i < (ncommit_args > 0 ? ncommit_args : argc); i++) {
4613 const char *arg;
4614 if (ncommit_args > 0)
4615 arg = commit_args[i];
4616 else
4617 arg = argv[i];
4618 error = got_repo_match_object_id(&ids[i], &labels[i],
4619 arg, obj_type, &refs, repo);
4620 if (error) {
4621 if (error->code != GOT_ERR_NOT_REF &&
4622 error->code != GOT_ERR_NO_OBJ)
4623 goto done;
4624 if (ncommit_args > 0)
4625 goto done;
4626 error = NULL;
4627 break;
4632 f1 = got_opentemp();
4633 if (f1 == NULL) {
4634 error = got_error_from_errno("got_opentemp");
4635 goto done;
4638 f2 = got_opentemp();
4639 if (f2 == NULL) {
4640 error = got_error_from_errno("got_opentemp");
4641 goto done;
4644 outfile = got_opentemp();
4645 if (outfile == NULL) {
4646 error = got_error_from_errno("got_opentemp");
4647 goto done;
4650 if (ncommit_args == 0 && (ids[0] == NULL || ids[1] == NULL)) {
4651 struct print_diff_arg arg;
4652 char *id_str;
4654 if (worktree == NULL) {
4655 if (argc == 2 && ids[0] == NULL) {
4656 error = got_error_path(argv[0], GOT_ERR_NO_OBJ);
4657 goto done;
4658 } else if (argc == 2 && ids[1] == NULL) {
4659 error = got_error_path(argv[1], GOT_ERR_NO_OBJ);
4660 goto done;
4661 } else if (argc > 0) {
4662 error = got_error_fmt(GOT_ERR_NOT_WORKTREE,
4663 "%s", "specified paths cannot be resolved");
4664 goto done;
4665 } else {
4666 error = got_error(GOT_ERR_NOT_WORKTREE);
4667 goto done;
4671 error = get_worktree_paths_from_argv(&paths, argc, argv,
4672 worktree);
4673 if (error)
4674 goto done;
4676 error = got_object_id_str(&id_str,
4677 got_worktree_get_base_commit_id(worktree));
4678 if (error)
4679 goto done;
4680 arg.repo = repo;
4681 arg.worktree = worktree;
4682 arg.diff_algo = GOT_DIFF_ALGORITHM_PATIENCE;
4683 arg.diff_context = diff_context;
4684 arg.id_str = id_str;
4685 arg.header_shown = 0;
4686 arg.diff_staged = diff_staged;
4687 arg.ignore_whitespace = ignore_whitespace;
4688 arg.force_text_diff = force_text_diff;
4689 arg.diffstat = show_diffstat ? &dsa : NULL;
4690 arg.f1 = f1;
4691 arg.f2 = f2;
4692 arg.outfile = outfile;
4694 error = got_worktree_status(worktree, &paths, repo, 0,
4695 print_diff, &arg, check_cancelled, NULL);
4696 free(id_str);
4697 if (error)
4698 goto done;
4700 if (show_diffstat && dsa.nfiles > 0) {
4701 char *header;
4703 if (asprintf(&header, "diffstat %s%s",
4704 diff_staged ? "-s " : "",
4705 got_worktree_get_root_path(worktree)) == -1) {
4706 error = got_error_from_errno("asprintf");
4707 goto done;
4710 error = print_diffstat(&dsa, header);
4711 free(header);
4712 if (error)
4713 goto done;
4716 error = printfile(outfile);
4717 goto done;
4720 if (ncommit_args == 1) {
4721 struct got_commit_object *commit;
4722 error = got_object_open_as_commit(&commit, repo, ids[0]);
4723 if (error)
4724 goto done;
4726 labels[1] = labels[0];
4727 ids[1] = ids[0];
4728 if (got_object_commit_get_nparents(commit) > 0) {
4729 const struct got_object_id_queue *pids;
4730 struct got_object_qid *pid;
4731 pids = got_object_commit_get_parent_ids(commit);
4732 pid = STAILQ_FIRST(pids);
4733 ids[0] = got_object_id_dup(&pid->id);
4734 if (ids[0] == NULL) {
4735 error = got_error_from_errno(
4736 "got_object_id_dup");
4737 got_object_commit_close(commit);
4738 goto done;
4740 error = got_object_id_str(&labels[0], ids[0]);
4741 if (error) {
4742 got_object_commit_close(commit);
4743 goto done;
4745 } else {
4746 ids[0] = NULL;
4747 labels[0] = strdup("/dev/null");
4748 if (labels[0] == NULL) {
4749 error = got_error_from_errno("strdup");
4750 got_object_commit_close(commit);
4751 goto done;
4755 got_object_commit_close(commit);
4758 if (ncommit_args == 0 && argc > 2) {
4759 error = got_error_msg(GOT_ERR_BAD_PATH,
4760 "path arguments cannot be used when diffing two objects");
4761 goto done;
4764 if (ids[0]) {
4765 error = got_object_get_type(&type1, repo, ids[0]);
4766 if (error)
4767 goto done;
4770 error = got_object_get_type(&type2, repo, ids[1]);
4771 if (error)
4772 goto done;
4773 if (type1 != GOT_OBJ_TYPE_ANY && type1 != type2) {
4774 error = got_error(GOT_ERR_OBJ_TYPE);
4775 goto done;
4777 if (type1 == GOT_OBJ_TYPE_BLOB && argc > 2) {
4778 error = got_error_msg(GOT_ERR_OBJ_TYPE,
4779 "path arguments cannot be used when diffing blobs");
4780 goto done;
4783 for (i = 0; ncommit_args > 0 && i < argc; i++) {
4784 char *in_repo_path;
4785 struct got_pathlist_entry *new;
4786 if (worktree) {
4787 const char *prefix;
4788 char *p;
4789 error = got_worktree_resolve_path(&p, worktree,
4790 argv[i]);
4791 if (error)
4792 goto done;
4793 prefix = got_worktree_get_path_prefix(worktree);
4794 while (prefix[0] == '/')
4795 prefix++;
4796 if (asprintf(&in_repo_path, "%s%s%s", prefix,
4797 (p[0] != '\0' && prefix[0] != '\0') ? "/" : "",
4798 p) == -1) {
4799 error = got_error_from_errno("asprintf");
4800 free(p);
4801 goto done;
4803 free(p);
4804 } else {
4805 char *mapped_path, *s;
4806 error = got_repo_map_path(&mapped_path, repo, argv[i]);
4807 if (error)
4808 goto done;
4809 s = mapped_path;
4810 while (s[0] == '/')
4811 s++;
4812 in_repo_path = strdup(s);
4813 if (in_repo_path == NULL) {
4814 error = got_error_from_errno("asprintf");
4815 free(mapped_path);
4816 goto done;
4818 free(mapped_path);
4821 error = got_pathlist_insert(&new, &paths, in_repo_path, NULL);
4822 if (error || new == NULL /* duplicate */)
4823 free(in_repo_path);
4824 if (error)
4825 goto done;
4828 if (worktree) {
4829 /* Release work tree lock. */
4830 got_worktree_close(worktree);
4831 worktree = NULL;
4834 fd1 = got_opentempfd();
4835 if (fd1 == -1) {
4836 error = got_error_from_errno("got_opentempfd");
4837 goto done;
4840 fd2 = got_opentempfd();
4841 if (fd2 == -1) {
4842 error = got_error_from_errno("got_opentempfd");
4843 goto done;
4846 switch (type1 == GOT_OBJ_TYPE_ANY ? type2 : type1) {
4847 case GOT_OBJ_TYPE_BLOB:
4848 error = got_diff_objects_as_blobs(NULL, NULL, f1, f2,
4849 fd1, fd2, ids[0], ids[1], NULL, NULL,
4850 GOT_DIFF_ALGORITHM_PATIENCE, diff_context,
4851 ignore_whitespace, force_text_diff,
4852 show_diffstat ? &dsa : NULL, repo, outfile);
4853 break;
4854 case GOT_OBJ_TYPE_TREE:
4855 error = got_diff_objects_as_trees(NULL, NULL, f1, f2, fd1, fd2,
4856 ids[0], ids[1], &paths, "", "",
4857 GOT_DIFF_ALGORITHM_PATIENCE, diff_context,
4858 ignore_whitespace, force_text_diff,
4859 show_diffstat ? &dsa : NULL, repo, outfile);
4860 break;
4861 case GOT_OBJ_TYPE_COMMIT:
4862 fprintf(outfile, "diff %s %s\n", labels[0], labels[1]);
4863 error = got_diff_objects_as_commits(NULL, NULL, f1, f2,
4864 fd1, fd2, ids[0], ids[1], &paths,
4865 GOT_DIFF_ALGORITHM_PATIENCE, diff_context,
4866 ignore_whitespace, force_text_diff,
4867 show_diffstat ? &dsa : NULL, repo, outfile);
4868 break;
4869 default:
4870 error = got_error(GOT_ERR_OBJ_TYPE);
4872 if (error)
4873 goto done;
4875 if (show_diffstat && dsa.nfiles > 0) {
4876 char *header = NULL;
4878 if (asprintf(&header, "diffstat %s %s",
4879 labels[0], labels[1]) == -1) {
4880 error = got_error_from_errno("asprintf");
4881 goto done;
4884 error = print_diffstat(&dsa, header);
4885 free(header);
4886 if (error)
4887 goto done;
4890 error = printfile(outfile);
4892 done:
4893 free(labels[0]);
4894 free(labels[1]);
4895 free(ids[0]);
4896 free(ids[1]);
4897 if (worktree)
4898 got_worktree_close(worktree);
4899 if (repo) {
4900 const struct got_error *close_err = got_repo_close(repo);
4901 if (error == NULL)
4902 error = close_err;
4904 if (pack_fds) {
4905 const struct got_error *pack_err =
4906 got_repo_pack_fds_close(pack_fds);
4907 if (error == NULL)
4908 error = pack_err;
4910 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
4911 got_pathlist_free(&diffstat_paths, GOT_PATHLIST_FREE_ALL);
4912 got_ref_list_free(&refs);
4913 if (outfile && fclose(outfile) == EOF && error == NULL)
4914 error = got_error_from_errno("fclose");
4915 if (f1 && fclose(f1) == EOF && error == NULL)
4916 error = got_error_from_errno("fclose");
4917 if (f2 && fclose(f2) == EOF && error == NULL)
4918 error = got_error_from_errno("fclose");
4919 if (fd1 != -1 && close(fd1) == -1 && error == NULL)
4920 error = got_error_from_errno("close");
4921 if (fd2 != -1 && close(fd2) == -1 && error == NULL)
4922 error = got_error_from_errno("close");
4923 return error;
4926 __dead static void
4927 usage_blame(void)
4929 fprintf(stderr,
4930 "usage: %s blame [-c commit] [-r repository-path] path\n",
4931 getprogname());
4932 exit(1);
4935 struct blame_line {
4936 int annotated;
4937 char *id_str;
4938 char *committer;
4939 char datebuf[11]; /* YYYY-MM-DD + NUL */
4942 struct blame_cb_args {
4943 struct blame_line *lines;
4944 int nlines;
4945 int nlines_prec;
4946 int lineno_cur;
4947 off_t *line_offsets;
4948 FILE *f;
4949 struct got_repository *repo;
4952 static const struct got_error *
4953 blame_cb(void *arg, int nlines, int lineno,
4954 struct got_commit_object *commit, struct got_object_id *id)
4956 const struct got_error *err = NULL;
4957 struct blame_cb_args *a = arg;
4958 struct blame_line *bline;
4959 char *line = NULL;
4960 size_t linesize = 0;
4961 off_t offset;
4962 struct tm tm;
4963 time_t committer_time;
4965 if (nlines != a->nlines ||
4966 (lineno != -1 && lineno < 1) || lineno > a->nlines)
4967 return got_error(GOT_ERR_RANGE);
4969 if (sigint_received)
4970 return got_error(GOT_ERR_ITER_COMPLETED);
4972 if (lineno == -1)
4973 return NULL; /* no change in this commit */
4975 /* Annotate this line. */
4976 bline = &a->lines[lineno - 1];
4977 if (bline->annotated)
4978 return NULL;
4979 err = got_object_id_str(&bline->id_str, id);
4980 if (err)
4981 return err;
4983 bline->committer = strdup(got_object_commit_get_committer(commit));
4984 if (bline->committer == NULL) {
4985 err = got_error_from_errno("strdup");
4986 goto done;
4989 committer_time = got_object_commit_get_committer_time(commit);
4990 if (gmtime_r(&committer_time, &tm) == NULL)
4991 return got_error_from_errno("gmtime_r");
4992 if (strftime(bline->datebuf, sizeof(bline->datebuf), "%G-%m-%d",
4993 &tm) == 0) {
4994 err = got_error(GOT_ERR_NO_SPACE);
4995 goto done;
4997 bline->annotated = 1;
4999 /* Print lines annotated so far. */
5000 bline = &a->lines[a->lineno_cur - 1];
5001 if (!bline->annotated)
5002 goto done;
5004 offset = a->line_offsets[a->lineno_cur - 1];
5005 if (fseeko(a->f, offset, SEEK_SET) == -1) {
5006 err = got_error_from_errno("fseeko");
5007 goto done;
5010 while (a->lineno_cur <= a->nlines && bline->annotated) {
5011 char *smallerthan, *at, *nl, *committer;
5012 size_t len;
5014 if (getline(&line, &linesize, a->f) == -1) {
5015 if (ferror(a->f))
5016 err = got_error_from_errno("getline");
5017 break;
5020 committer = bline->committer;
5021 smallerthan = strchr(committer, '<');
5022 if (smallerthan && smallerthan[1] != '\0')
5023 committer = smallerthan + 1;
5024 at = strchr(committer, '@');
5025 if (at)
5026 *at = '\0';
5027 len = strlen(committer);
5028 if (len >= 9)
5029 committer[8] = '\0';
5031 nl = strchr(line, '\n');
5032 if (nl)
5033 *nl = '\0';
5034 printf("%.*d) %.8s %s %-8s %s\n", a->nlines_prec, a->lineno_cur,
5035 bline->id_str, bline->datebuf, committer, line);
5037 a->lineno_cur++;
5038 bline = &a->lines[a->lineno_cur - 1];
5040 done:
5041 free(line);
5042 return err;
5045 static const struct got_error *
5046 cmd_blame(int argc, char *argv[])
5048 const struct got_error *error;
5049 struct got_repository *repo = NULL;
5050 struct got_worktree *worktree = NULL;
5051 char *path, *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
5052 char *link_target = NULL;
5053 struct got_object_id *obj_id = NULL;
5054 struct got_object_id *commit_id = NULL;
5055 struct got_commit_object *commit = NULL;
5056 struct got_blob_object *blob = NULL;
5057 char *commit_id_str = NULL;
5058 struct blame_cb_args bca;
5059 int ch, obj_type, i, fd1 = -1, fd2 = -1, fd3 = -1;
5060 off_t filesize;
5061 int *pack_fds = NULL;
5062 FILE *f1 = NULL, *f2 = NULL;
5064 fd1 = got_opentempfd();
5065 if (fd1 == -1)
5066 return got_error_from_errno("got_opentempfd");
5068 memset(&bca, 0, sizeof(bca));
5070 #ifndef PROFILE
5071 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
5072 NULL) == -1)
5073 err(1, "pledge");
5074 #endif
5076 while ((ch = getopt(argc, argv, "c:r:")) != -1) {
5077 switch (ch) {
5078 case 'c':
5079 commit_id_str = optarg;
5080 break;
5081 case 'r':
5082 repo_path = realpath(optarg, NULL);
5083 if (repo_path == NULL)
5084 return got_error_from_errno2("realpath",
5085 optarg);
5086 got_path_strip_trailing_slashes(repo_path);
5087 break;
5088 default:
5089 usage_blame();
5090 /* NOTREACHED */
5094 argc -= optind;
5095 argv += optind;
5097 if (argc == 1)
5098 path = argv[0];
5099 else
5100 usage_blame();
5102 cwd = getcwd(NULL, 0);
5103 if (cwd == NULL) {
5104 error = got_error_from_errno("getcwd");
5105 goto done;
5108 error = got_repo_pack_fds_open(&pack_fds);
5109 if (error != NULL)
5110 goto done;
5112 if (repo_path == NULL) {
5113 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_CVG_DIR);
5114 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5115 goto done;
5116 else
5117 error = NULL;
5118 if (worktree) {
5119 repo_path =
5120 strdup(got_worktree_get_repo_path(worktree));
5121 if (repo_path == NULL) {
5122 error = got_error_from_errno("strdup");
5123 if (error)
5124 goto done;
5126 } else {
5127 repo_path = strdup(cwd);
5128 if (repo_path == NULL) {
5129 error = got_error_from_errno("strdup");
5130 goto done;
5135 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
5136 if (error != NULL)
5137 goto done;
5139 if (worktree) {
5140 const char *prefix = got_worktree_get_path_prefix(worktree);
5141 char *p;
5143 error = got_worktree_resolve_path(&p, worktree, path);
5144 if (error)
5145 goto done;
5146 if (asprintf(&in_repo_path, "%s%s%s", prefix,
5147 (p[0] != '\0' && !got_path_is_root_dir(prefix)) ? "/" : "",
5148 p) == -1) {
5149 error = got_error_from_errno("asprintf");
5150 free(p);
5151 goto done;
5153 free(p);
5154 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5155 } else {
5156 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5157 if (error)
5158 goto done;
5159 error = got_repo_map_path(&in_repo_path, repo, path);
5161 if (error)
5162 goto done;
5164 if (commit_id_str == NULL) {
5165 struct got_reference *head_ref;
5166 error = got_ref_open(&head_ref, repo, worktree ?
5167 got_worktree_get_head_ref_name(worktree) : GOT_REF_HEAD, 0);
5168 if (error != NULL)
5169 goto done;
5170 error = got_ref_resolve(&commit_id, repo, head_ref);
5171 got_ref_close(head_ref);
5172 if (error != NULL)
5173 goto done;
5174 } else {
5175 struct got_reflist_head refs;
5176 TAILQ_INIT(&refs);
5177 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
5178 NULL);
5179 if (error)
5180 goto done;
5181 error = got_repo_match_object_id(&commit_id, NULL,
5182 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
5183 got_ref_list_free(&refs);
5184 if (error)
5185 goto done;
5188 if (worktree) {
5189 /* Release work tree lock. */
5190 got_worktree_close(worktree);
5191 worktree = NULL;
5194 error = got_object_open_as_commit(&commit, repo, commit_id);
5195 if (error)
5196 goto done;
5198 error = got_object_resolve_symlinks(&link_target, in_repo_path,
5199 commit, repo);
5200 if (error)
5201 goto done;
5203 error = got_object_id_by_path(&obj_id, repo, commit,
5204 link_target ? link_target : in_repo_path);
5205 if (error)
5206 goto done;
5208 error = got_object_get_type(&obj_type, repo, obj_id);
5209 if (error)
5210 goto done;
5212 if (obj_type != GOT_OBJ_TYPE_BLOB) {
5213 error = got_error_path(link_target ? link_target : in_repo_path,
5214 GOT_ERR_OBJ_TYPE);
5215 goto done;
5218 error = got_object_open_as_blob(&blob, repo, obj_id, 8192, fd1);
5219 if (error)
5220 goto done;
5221 bca.f = got_opentemp();
5222 if (bca.f == NULL) {
5223 error = got_error_from_errno("got_opentemp");
5224 goto done;
5226 error = got_object_blob_dump_to_file(&filesize, &bca.nlines,
5227 &bca.line_offsets, bca.f, blob);
5228 if (error || bca.nlines == 0)
5229 goto done;
5231 /* Don't include \n at EOF in the blame line count. */
5232 if (bca.line_offsets[bca.nlines - 1] == filesize)
5233 bca.nlines--;
5235 bca.lines = calloc(bca.nlines, sizeof(*bca.lines));
5236 if (bca.lines == NULL) {
5237 error = got_error_from_errno("calloc");
5238 goto done;
5240 bca.lineno_cur = 1;
5241 bca.nlines_prec = 0;
5242 i = bca.nlines;
5243 while (i > 0) {
5244 i /= 10;
5245 bca.nlines_prec++;
5247 bca.repo = repo;
5249 fd2 = got_opentempfd();
5250 if (fd2 == -1) {
5251 error = got_error_from_errno("got_opentempfd");
5252 goto done;
5254 fd3 = got_opentempfd();
5255 if (fd3 == -1) {
5256 error = got_error_from_errno("got_opentempfd");
5257 goto done;
5259 f1 = got_opentemp();
5260 if (f1 == NULL) {
5261 error = got_error_from_errno("got_opentemp");
5262 goto done;
5264 f2 = got_opentemp();
5265 if (f2 == NULL) {
5266 error = got_error_from_errno("got_opentemp");
5267 goto done;
5269 error = got_blame(link_target ? link_target : in_repo_path, commit_id,
5270 repo, GOT_DIFF_ALGORITHM_PATIENCE, blame_cb, &bca,
5271 check_cancelled, NULL, fd2, fd3, f1, f2);
5272 done:
5273 free(in_repo_path);
5274 free(link_target);
5275 free(repo_path);
5276 free(cwd);
5277 free(commit_id);
5278 free(obj_id);
5279 if (commit)
5280 got_object_commit_close(commit);
5282 if (fd1 != -1 && close(fd1) == -1 && error == NULL)
5283 error = got_error_from_errno("close");
5284 if (fd2 != -1 && close(fd2) == -1 && error == NULL)
5285 error = got_error_from_errno("close");
5286 if (fd3 != -1 && close(fd3) == -1 && error == NULL)
5287 error = got_error_from_errno("close");
5288 if (f1 && fclose(f1) == EOF && error == NULL)
5289 error = got_error_from_errno("fclose");
5290 if (f2 && fclose(f2) == EOF && error == NULL)
5291 error = got_error_from_errno("fclose");
5293 if (blob)
5294 got_object_blob_close(blob);
5295 if (worktree)
5296 got_worktree_close(worktree);
5297 if (repo) {
5298 const struct got_error *close_err = got_repo_close(repo);
5299 if (error == NULL)
5300 error = close_err;
5302 if (pack_fds) {
5303 const struct got_error *pack_err =
5304 got_repo_pack_fds_close(pack_fds);
5305 if (error == NULL)
5306 error = pack_err;
5308 if (bca.lines) {
5309 for (i = 0; i < bca.nlines; i++) {
5310 struct blame_line *bline = &bca.lines[i];
5311 free(bline->id_str);
5312 free(bline->committer);
5314 free(bca.lines);
5316 free(bca.line_offsets);
5317 if (bca.f && fclose(bca.f) == EOF && error == NULL)
5318 error = got_error_from_errno("fclose");
5319 return error;
5322 __dead static void
5323 usage_tree(void)
5325 fprintf(stderr, "usage: %s tree [-iR] [-c commit] [-r repository-path] "
5326 "[path]\n", getprogname());
5327 exit(1);
5330 static const struct got_error *
5331 print_entry(struct got_tree_entry *te, const char *id, const char *path,
5332 const char *root_path, struct got_repository *repo)
5334 const struct got_error *err = NULL;
5335 int is_root_path = (strcmp(path, root_path) == 0);
5336 const char *modestr = "";
5337 mode_t mode = got_tree_entry_get_mode(te);
5338 char *link_target = NULL;
5340 path += strlen(root_path);
5341 while (path[0] == '/')
5342 path++;
5344 if (got_object_tree_entry_is_submodule(te))
5345 modestr = "$";
5346 else if (S_ISLNK(mode)) {
5347 int i;
5349 err = got_tree_entry_get_symlink_target(&link_target, te, repo);
5350 if (err)
5351 return err;
5352 for (i = 0; link_target[i] != '\0'; i++) {
5353 if (!isprint((unsigned char)link_target[i]))
5354 link_target[i] = '?';
5357 modestr = "@";
5359 else if (S_ISDIR(mode))
5360 modestr = "/";
5361 else if (mode & S_IXUSR)
5362 modestr = "*";
5364 printf("%s%s%s%s%s%s%s\n", id ? id : "", path,
5365 is_root_path ? "" : "/", got_tree_entry_get_name(te), modestr,
5366 link_target ? " -> ": "", link_target ? link_target : "");
5368 free(link_target);
5369 return NULL;
5372 static const struct got_error *
5373 print_tree(const char *path, struct got_commit_object *commit,
5374 int show_ids, int recurse, const char *root_path,
5375 struct got_repository *repo)
5377 const struct got_error *err = NULL;
5378 struct got_object_id *tree_id = NULL;
5379 struct got_tree_object *tree = NULL;
5380 int nentries, i;
5382 err = got_object_id_by_path(&tree_id, repo, commit, path);
5383 if (err)
5384 goto done;
5386 err = got_object_open_as_tree(&tree, repo, tree_id);
5387 if (err)
5388 goto done;
5389 nentries = got_object_tree_get_nentries(tree);
5390 for (i = 0; i < nentries; i++) {
5391 struct got_tree_entry *te;
5392 char *id = NULL;
5394 if (sigint_received || sigpipe_received)
5395 break;
5397 te = got_object_tree_get_entry(tree, i);
5398 if (show_ids) {
5399 char *id_str;
5400 err = got_object_id_str(&id_str,
5401 got_tree_entry_get_id(te));
5402 if (err)
5403 goto done;
5404 if (asprintf(&id, "%s ", id_str) == -1) {
5405 err = got_error_from_errno("asprintf");
5406 free(id_str);
5407 goto done;
5409 free(id_str);
5411 err = print_entry(te, id, path, root_path, repo);
5412 free(id);
5413 if (err)
5414 goto done;
5416 if (recurse && S_ISDIR(got_tree_entry_get_mode(te))) {
5417 char *child_path;
5418 if (asprintf(&child_path, "%s%s%s", path,
5419 path[0] == '/' && path[1] == '\0' ? "" : "/",
5420 got_tree_entry_get_name(te)) == -1) {
5421 err = got_error_from_errno("asprintf");
5422 goto done;
5424 err = print_tree(child_path, commit, show_ids, 1,
5425 root_path, repo);
5426 free(child_path);
5427 if (err)
5428 goto done;
5431 done:
5432 if (tree)
5433 got_object_tree_close(tree);
5434 free(tree_id);
5435 return err;
5438 static const struct got_error *
5439 cmd_tree(int argc, char *argv[])
5441 const struct got_error *error;
5442 struct got_repository *repo = NULL;
5443 struct got_worktree *worktree = NULL;
5444 const char *path, *refname = NULL;
5445 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
5446 struct got_object_id *commit_id = NULL;
5447 struct got_commit_object *commit = NULL;
5448 char *commit_id_str = NULL;
5449 int show_ids = 0, recurse = 0;
5450 int ch;
5451 int *pack_fds = NULL;
5453 #ifndef PROFILE
5454 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
5455 NULL) == -1)
5456 err(1, "pledge");
5457 #endif
5459 while ((ch = getopt(argc, argv, "c:iRr:")) != -1) {
5460 switch (ch) {
5461 case 'c':
5462 commit_id_str = optarg;
5463 break;
5464 case 'i':
5465 show_ids = 1;
5466 break;
5467 case 'R':
5468 recurse = 1;
5469 break;
5470 case 'r':
5471 repo_path = realpath(optarg, NULL);
5472 if (repo_path == NULL)
5473 return got_error_from_errno2("realpath",
5474 optarg);
5475 got_path_strip_trailing_slashes(repo_path);
5476 break;
5477 default:
5478 usage_tree();
5479 /* NOTREACHED */
5483 argc -= optind;
5484 argv += optind;
5486 if (argc == 1)
5487 path = argv[0];
5488 else if (argc > 1)
5489 usage_tree();
5490 else
5491 path = NULL;
5493 cwd = getcwd(NULL, 0);
5494 if (cwd == NULL) {
5495 error = got_error_from_errno("getcwd");
5496 goto done;
5499 error = got_repo_pack_fds_open(&pack_fds);
5500 if (error != NULL)
5501 goto done;
5503 if (repo_path == NULL) {
5504 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_CVG_DIR);
5505 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5506 goto done;
5507 else
5508 error = NULL;
5509 if (worktree) {
5510 repo_path =
5511 strdup(got_worktree_get_repo_path(worktree));
5512 if (repo_path == NULL)
5513 error = got_error_from_errno("strdup");
5514 if (error)
5515 goto done;
5516 } else {
5517 repo_path = strdup(cwd);
5518 if (repo_path == NULL) {
5519 error = got_error_from_errno("strdup");
5520 goto done;
5525 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
5526 if (error != NULL)
5527 goto done;
5529 if (worktree) {
5530 const char *prefix = got_worktree_get_path_prefix(worktree);
5531 char *p;
5533 if (path == NULL || got_path_is_root_dir(path))
5534 path = "";
5535 error = got_worktree_resolve_path(&p, worktree, path);
5536 if (error)
5537 goto done;
5538 if (asprintf(&in_repo_path, "%s%s%s", prefix,
5539 (p[0] != '\0' && !got_path_is_root_dir(prefix)) ? "/" : "",
5540 p) == -1) {
5541 error = got_error_from_errno("asprintf");
5542 free(p);
5543 goto done;
5545 free(p);
5546 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5547 if (error)
5548 goto done;
5549 } else {
5550 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5551 if (error)
5552 goto done;
5553 if (path == NULL)
5554 path = "/";
5555 error = got_repo_map_path(&in_repo_path, repo, path);
5556 if (error != NULL)
5557 goto done;
5560 if (commit_id_str == NULL) {
5561 struct got_reference *head_ref;
5562 if (worktree)
5563 refname = got_worktree_get_head_ref_name(worktree);
5564 else
5565 refname = GOT_REF_HEAD;
5566 error = got_ref_open(&head_ref, repo, refname, 0);
5567 if (error != NULL)
5568 goto done;
5569 error = got_ref_resolve(&commit_id, repo, head_ref);
5570 got_ref_close(head_ref);
5571 if (error != NULL)
5572 goto done;
5573 } else {
5574 struct got_reflist_head refs;
5575 TAILQ_INIT(&refs);
5576 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
5577 NULL);
5578 if (error)
5579 goto done;
5580 error = got_repo_match_object_id(&commit_id, NULL,
5581 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
5582 got_ref_list_free(&refs);
5583 if (error)
5584 goto done;
5587 if (worktree) {
5588 /* Release work tree lock. */
5589 got_worktree_close(worktree);
5590 worktree = NULL;
5593 error = got_object_open_as_commit(&commit, repo, commit_id);
5594 if (error)
5595 goto done;
5597 error = print_tree(in_repo_path, commit, show_ids, recurse,
5598 in_repo_path, repo);
5599 done:
5600 free(in_repo_path);
5601 free(repo_path);
5602 free(cwd);
5603 free(commit_id);
5604 if (commit)
5605 got_object_commit_close(commit);
5606 if (worktree)
5607 got_worktree_close(worktree);
5608 if (repo) {
5609 const struct got_error *close_err = got_repo_close(repo);
5610 if (error == NULL)
5611 error = close_err;
5613 if (pack_fds) {
5614 const struct got_error *pack_err =
5615 got_repo_pack_fds_close(pack_fds);
5616 if (error == NULL)
5617 error = pack_err;
5619 return error;
5622 __dead static void
5623 usage_status(void)
5625 fprintf(stderr, "usage: %s status [-I] [-S status-codes] "
5626 "[-s status-codes] [path ...]\n", getprogname());
5627 exit(1);
5630 struct got_status_arg {
5631 char *status_codes;
5632 int suppress;
5635 static const struct got_error *
5636 print_status(void *arg, unsigned char status, unsigned char staged_status,
5637 const char *path, struct got_object_id *blob_id,
5638 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
5639 int dirfd, const char *de_name)
5641 struct got_status_arg *st = arg;
5643 if (status == staged_status && (status == GOT_STATUS_DELETE))
5644 status = GOT_STATUS_NO_CHANGE;
5645 if (st != NULL && st->status_codes) {
5646 size_t ncodes = strlen(st->status_codes);
5647 int i, j = 0;
5649 for (i = 0; i < ncodes ; i++) {
5650 if (st->suppress) {
5651 if (status == st->status_codes[i] ||
5652 staged_status == st->status_codes[i]) {
5653 j++;
5654 continue;
5656 } else {
5657 if (status == st->status_codes[i] ||
5658 staged_status == st->status_codes[i])
5659 break;
5663 if (st->suppress && j == 0)
5664 goto print;
5666 if (i == ncodes)
5667 return NULL;
5669 print:
5670 printf("%c%c %s\n", status, staged_status, path);
5671 return NULL;
5674 static const struct got_error *
5675 cmd_status(int argc, char *argv[])
5677 const struct got_error *error = NULL;
5678 struct got_repository *repo = NULL;
5679 struct got_worktree *worktree = NULL;
5680 struct got_status_arg st;
5681 char *cwd = NULL;
5682 struct got_pathlist_head paths;
5683 int ch, i, no_ignores = 0;
5684 int *pack_fds = NULL;
5686 TAILQ_INIT(&paths);
5688 memset(&st, 0, sizeof(st));
5689 st.status_codes = NULL;
5690 st.suppress = 0;
5692 #ifndef PROFILE
5693 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
5694 NULL) == -1)
5695 err(1, "pledge");
5696 #endif
5698 while ((ch = getopt(argc, argv, "IS:s:")) != -1) {
5699 switch (ch) {
5700 case 'I':
5701 no_ignores = 1;
5702 break;
5703 case 'S':
5704 if (st.status_codes != NULL && st.suppress == 0)
5705 option_conflict('S', 's');
5706 st.suppress = 1;
5707 /* fallthrough */
5708 case 's':
5709 for (i = 0; optarg[i] != '\0'; i++) {
5710 switch (optarg[i]) {
5711 case GOT_STATUS_MODIFY:
5712 case GOT_STATUS_ADD:
5713 case GOT_STATUS_DELETE:
5714 case GOT_STATUS_CONFLICT:
5715 case GOT_STATUS_MISSING:
5716 case GOT_STATUS_OBSTRUCTED:
5717 case GOT_STATUS_UNVERSIONED:
5718 case GOT_STATUS_MODE_CHANGE:
5719 case GOT_STATUS_NONEXISTENT:
5720 break;
5721 default:
5722 errx(1, "invalid status code '%c'",
5723 optarg[i]);
5726 if (ch == 's' && st.suppress)
5727 option_conflict('s', 'S');
5728 st.status_codes = optarg;
5729 break;
5730 default:
5731 usage_status();
5732 /* NOTREACHED */
5736 argc -= optind;
5737 argv += optind;
5739 cwd = getcwd(NULL, 0);
5740 if (cwd == NULL) {
5741 error = got_error_from_errno("getcwd");
5742 goto done;
5745 error = got_repo_pack_fds_open(&pack_fds);
5746 if (error != NULL)
5747 goto done;
5749 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_CVG_DIR);
5750 if (error) {
5751 if (error->code == GOT_ERR_NOT_WORKTREE)
5752 error = wrap_not_worktree_error(error, "status", cwd);
5753 goto done;
5756 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
5757 NULL, pack_fds);
5758 if (error != NULL)
5759 goto done;
5761 error = apply_unveil(got_repo_get_path(repo), 1,
5762 got_worktree_get_root_path(worktree));
5763 if (error)
5764 goto done;
5766 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
5767 if (error)
5768 goto done;
5770 error = got_worktree_status(worktree, &paths, repo, no_ignores,
5771 print_status, &st, check_cancelled, NULL);
5772 done:
5773 if (pack_fds) {
5774 const struct got_error *pack_err =
5775 got_repo_pack_fds_close(pack_fds);
5776 if (error == NULL)
5777 error = pack_err;
5779 if (repo) {
5780 const struct got_error *close_err = got_repo_close(repo);
5781 if (error == NULL)
5782 error = close_err;
5785 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
5786 free(cwd);
5787 return error;
5790 __dead static void
5791 usage_tag(void)
5793 fprintf(stderr, "usage: %s tag [-lVv] [-c commit] [-m message] "
5794 "[-r repository-path] [-s signer-id] name\n", getprogname());
5795 exit(1);
5798 #if 0
5799 static const struct got_error *
5800 sort_tags(struct got_reflist_head *sorted, struct got_reflist_head *tags)
5802 const struct got_error *err = NULL;
5803 struct got_reflist_entry *re, *se, *new;
5804 struct got_object_id *re_id, *se_id;
5805 struct got_tag_object *re_tag, *se_tag;
5806 time_t re_time, se_time;
5808 STAILQ_FOREACH(re, tags, entry) {
5809 se = STAILQ_FIRST(sorted);
5810 if (se == NULL) {
5811 err = got_reflist_entry_dup(&new, re);
5812 if (err)
5813 return err;
5814 STAILQ_INSERT_HEAD(sorted, new, entry);
5815 continue;
5816 } else {
5817 err = got_ref_resolve(&re_id, repo, re->ref);
5818 if (err)
5819 break;
5820 err = got_object_open_as_tag(&re_tag, repo, re_id);
5821 free(re_id);
5822 if (err)
5823 break;
5824 re_time = got_object_tag_get_tagger_time(re_tag);
5825 got_object_tag_close(re_tag);
5828 while (se) {
5829 err = got_ref_resolve(&se_id, repo, re->ref);
5830 if (err)
5831 break;
5832 err = got_object_open_as_tag(&se_tag, repo, se_id);
5833 free(se_id);
5834 if (err)
5835 break;
5836 se_time = got_object_tag_get_tagger_time(se_tag);
5837 got_object_tag_close(se_tag);
5839 if (se_time > re_time) {
5840 err = got_reflist_entry_dup(&new, re);
5841 if (err)
5842 return err;
5843 STAILQ_INSERT_AFTER(sorted, se, new, entry);
5844 break;
5846 se = STAILQ_NEXT(se, entry);
5847 continue;
5850 done:
5851 return err;
5853 #endif
5855 static const struct got_error *
5856 get_tag_refname(char **refname, const char *tag_name)
5858 const struct got_error *err;
5860 if (strncmp("refs/tags/", tag_name, 10) == 0) {
5861 *refname = strdup(tag_name);
5862 if (*refname == NULL)
5863 return got_error_from_errno("strdup");
5864 } else if (asprintf(refname, "refs/tags/%s", tag_name) == -1) {
5865 err = got_error_from_errno("asprintf");
5866 *refname = NULL;
5867 return err;
5870 return NULL;
5873 static const struct got_error *
5874 list_tags(struct got_repository *repo, const char *tag_name, int verify_tags,
5875 const char *allowed_signers, const char *revoked_signers, int verbosity)
5877 static const struct got_error *err = NULL;
5878 struct got_reflist_head refs;
5879 struct got_reflist_entry *re;
5880 char *wanted_refname = NULL;
5881 int bad_sigs = 0;
5883 TAILQ_INIT(&refs);
5885 err = got_ref_list(&refs, repo, "refs/tags", got_ref_cmp_tags, repo);
5886 if (err)
5887 return err;
5889 if (tag_name) {
5890 struct got_reference *ref;
5891 err = get_tag_refname(&wanted_refname, tag_name);
5892 if (err)
5893 goto done;
5894 /* Wanted tag reference should exist. */
5895 err = got_ref_open(&ref, repo, wanted_refname, 0);
5896 if (err)
5897 goto done;
5898 got_ref_close(ref);
5901 TAILQ_FOREACH(re, &refs, entry) {
5902 const char *refname;
5903 char *refstr, *tagmsg0, *tagmsg, *line, *id_str, *datestr;
5904 char datebuf[26];
5905 const char *tagger, *ssh_sig = NULL;
5906 char *sig_msg = NULL;
5907 time_t tagger_time;
5908 struct got_object_id *id;
5909 struct got_tag_object *tag;
5910 struct got_commit_object *commit = NULL;
5912 refname = got_ref_get_name(re->ref);
5913 if (strncmp(refname, "refs/tags/", 10) != 0 ||
5914 (wanted_refname && strcmp(refname, wanted_refname) != 0))
5915 continue;
5916 refname += 10;
5917 refstr = got_ref_to_str(re->ref);
5918 if (refstr == NULL) {
5919 err = got_error_from_errno("got_ref_to_str");
5920 break;
5923 err = got_ref_resolve(&id, repo, re->ref);
5924 if (err)
5925 break;
5926 err = got_object_open_as_tag(&tag, repo, id);
5927 if (err) {
5928 if (err->code != GOT_ERR_OBJ_TYPE) {
5929 free(id);
5930 break;
5932 /* "lightweight" tag */
5933 err = got_object_open_as_commit(&commit, repo, id);
5934 if (err) {
5935 free(id);
5936 break;
5938 tagger = got_object_commit_get_committer(commit);
5939 tagger_time =
5940 got_object_commit_get_committer_time(commit);
5941 err = got_object_id_str(&id_str, id);
5942 free(id);
5943 if (err)
5944 break;
5945 } else {
5946 free(id);
5947 tagger = got_object_tag_get_tagger(tag);
5948 tagger_time = got_object_tag_get_tagger_time(tag);
5949 err = got_object_id_str(&id_str,
5950 got_object_tag_get_object_id(tag));
5951 if (err)
5952 break;
5955 if (tag && verify_tags) {
5956 ssh_sig = got_sigs_get_tagmsg_ssh_signature(
5957 got_object_tag_get_message(tag));
5958 if (ssh_sig && allowed_signers == NULL) {
5959 err = got_error_msg(
5960 GOT_ERR_VERIFY_TAG_SIGNATURE,
5961 "SSH signature verification requires "
5962 "setting allowed_signers in "
5963 "got.conf(5)");
5964 break;
5968 printf("%stag %s %s\n", GOT_COMMIT_SEP_STR, refname, refstr);
5969 free(refstr);
5970 printf("from: %s\n", tagger);
5971 datestr = get_datestr(&tagger_time, datebuf);
5972 if (datestr)
5973 printf("date: %s UTC\n", datestr);
5974 if (commit)
5975 printf("object: %s %s\n", GOT_OBJ_LABEL_COMMIT, id_str);
5976 else {
5977 switch (got_object_tag_get_object_type(tag)) {
5978 case GOT_OBJ_TYPE_BLOB:
5979 printf("object: %s %s\n", GOT_OBJ_LABEL_BLOB,
5980 id_str);
5981 break;
5982 case GOT_OBJ_TYPE_TREE:
5983 printf("object: %s %s\n", GOT_OBJ_LABEL_TREE,
5984 id_str);
5985 break;
5986 case GOT_OBJ_TYPE_COMMIT:
5987 printf("object: %s %s\n", GOT_OBJ_LABEL_COMMIT,
5988 id_str);
5989 break;
5990 case GOT_OBJ_TYPE_TAG:
5991 printf("object: %s %s\n", GOT_OBJ_LABEL_TAG,
5992 id_str);
5993 break;
5994 default:
5995 break;
5998 free(id_str);
6000 if (ssh_sig) {
6001 err = got_sigs_verify_tag_ssh(&sig_msg, tag, ssh_sig,
6002 allowed_signers, revoked_signers, verbosity);
6003 if (err && err->code == GOT_ERR_BAD_TAG_SIGNATURE)
6004 bad_sigs = 1;
6005 else if (err)
6006 break;
6007 printf("signature: %s", sig_msg);
6008 free(sig_msg);
6009 sig_msg = NULL;
6012 if (commit) {
6013 err = got_object_commit_get_logmsg(&tagmsg0, commit);
6014 if (err)
6015 break;
6016 got_object_commit_close(commit);
6017 } else {
6018 tagmsg0 = strdup(got_object_tag_get_message(tag));
6019 got_object_tag_close(tag);
6020 if (tagmsg0 == NULL) {
6021 err = got_error_from_errno("strdup");
6022 break;
6026 tagmsg = tagmsg0;
6027 do {
6028 line = strsep(&tagmsg, "\n");
6029 if (line)
6030 printf(" %s\n", line);
6031 } while (line);
6032 free(tagmsg0);
6034 done:
6035 got_ref_list_free(&refs);
6036 free(wanted_refname);
6038 if (err == NULL && bad_sigs)
6039 err = got_error(GOT_ERR_BAD_TAG_SIGNATURE);
6040 return err;
6043 static const struct got_error *
6044 get_tag_message(char **tagmsg, char **tagmsg_path, const char *commit_id_str,
6045 const char *tag_name, const char *repo_path)
6047 const struct got_error *err = NULL;
6048 char *template = NULL, *initial_content = NULL;
6049 char *editor = NULL;
6050 int initial_content_len;
6051 int fd = -1;
6053 if (asprintf(&template, GOT_TMPDIR_STR "/got-tagmsg") == -1) {
6054 err = got_error_from_errno("asprintf");
6055 goto done;
6058 initial_content_len = asprintf(&initial_content,
6059 "\n# tagging commit %s as %s\n",
6060 commit_id_str, tag_name);
6061 if (initial_content_len == -1) {
6062 err = got_error_from_errno("asprintf");
6063 goto done;
6066 err = got_opentemp_named_fd(tagmsg_path, &fd, template, "");
6067 if (err)
6068 goto done;
6070 if (write(fd, initial_content, initial_content_len) == -1) {
6071 err = got_error_from_errno2("write", *tagmsg_path);
6072 goto done;
6074 if (close(fd) == -1) {
6075 err = got_error_from_errno2("close", *tagmsg_path);
6076 goto done;
6078 fd = -1;
6080 err = get_editor(&editor);
6081 if (err)
6082 goto done;
6083 err = edit_logmsg(tagmsg, editor, *tagmsg_path, initial_content,
6084 initial_content_len, 1);
6085 done:
6086 free(initial_content);
6087 free(template);
6088 free(editor);
6090 if (fd != -1 && close(fd) == -1 && err == NULL)
6091 err = got_error_from_errno2("close", *tagmsg_path);
6093 if (err) {
6094 free(*tagmsg);
6095 *tagmsg = NULL;
6097 return err;
6100 static const struct got_error *
6101 add_tag(struct got_repository *repo, const char *tagger,
6102 const char *tag_name, const char *commit_arg, const char *tagmsg_arg,
6103 const char *signer_id, int verbosity)
6105 const struct got_error *err = NULL;
6106 struct got_object_id *commit_id = NULL, *tag_id = NULL;
6107 char *label = NULL, *commit_id_str = NULL;
6108 struct got_reference *ref = NULL;
6109 char *refname = NULL, *tagmsg = NULL;
6110 char *tagmsg_path = NULL, *tag_id_str = NULL;
6111 int preserve_tagmsg = 0;
6112 struct got_reflist_head refs;
6114 TAILQ_INIT(&refs);
6117 * Don't let the user create a tag name with a leading '-'.
6118 * While technically a valid reference name, this case is usually
6119 * an unintended typo.
6121 if (tag_name[0] == '-')
6122 return got_error_path(tag_name, GOT_ERR_REF_NAME_MINUS);
6124 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
6125 if (err)
6126 goto done;
6128 err = got_repo_match_object_id(&commit_id, &label, commit_arg,
6129 GOT_OBJ_TYPE_COMMIT, &refs, repo);
6130 if (err)
6131 goto done;
6133 err = got_object_id_str(&commit_id_str, commit_id);
6134 if (err)
6135 goto done;
6137 err = get_tag_refname(&refname, tag_name);
6138 if (err)
6139 goto done;
6140 if (strncmp("refs/tags/", tag_name, 10) == 0)
6141 tag_name += 10;
6143 err = got_ref_open(&ref, repo, refname, 0);
6144 if (err == NULL) {
6145 err = got_error(GOT_ERR_TAG_EXISTS);
6146 goto done;
6147 } else if (err->code != GOT_ERR_NOT_REF)
6148 goto done;
6150 if (tagmsg_arg == NULL) {
6151 err = get_tag_message(&tagmsg, &tagmsg_path, commit_id_str,
6152 tag_name, got_repo_get_path(repo));
6153 if (err) {
6154 if (err->code != GOT_ERR_COMMIT_MSG_EMPTY &&
6155 tagmsg_path != NULL)
6156 preserve_tagmsg = 1;
6157 goto done;
6159 /* Editor is done; we can now apply unveil(2) */
6160 err = got_sigs_apply_unveil();
6161 if (err)
6162 goto done;
6163 err = apply_unveil(got_repo_get_path(repo), 0, NULL);
6164 if (err)
6165 goto done;
6168 err = got_object_tag_create(&tag_id, tag_name, commit_id,
6169 tagger, time(NULL), tagmsg ? tagmsg : tagmsg_arg, signer_id, repo,
6170 verbosity);
6171 if (err) {
6172 if (tagmsg_path)
6173 preserve_tagmsg = 1;
6174 goto done;
6177 err = got_ref_alloc(&ref, refname, tag_id);
6178 if (err) {
6179 if (tagmsg_path)
6180 preserve_tagmsg = 1;
6181 goto done;
6184 err = got_ref_write(ref, repo);
6185 if (err) {
6186 if (tagmsg_path)
6187 preserve_tagmsg = 1;
6188 goto done;
6191 err = got_object_id_str(&tag_id_str, tag_id);
6192 if (err) {
6193 if (tagmsg_path)
6194 preserve_tagmsg = 1;
6195 goto done;
6197 printf("Created tag %s\n", tag_id_str);
6198 done:
6199 if (preserve_tagmsg) {
6200 fprintf(stderr, "%s: tag message preserved in %s\n",
6201 getprogname(), tagmsg_path);
6202 } else if (tagmsg_path && unlink(tagmsg_path) == -1 && err == NULL)
6203 err = got_error_from_errno2("unlink", tagmsg_path);
6204 free(tag_id_str);
6205 if (ref)
6206 got_ref_close(ref);
6207 free(commit_id);
6208 free(commit_id_str);
6209 free(refname);
6210 free(tagmsg);
6211 free(tagmsg_path);
6212 got_ref_list_free(&refs);
6213 return err;
6216 static const struct got_error *
6217 cmd_tag(int argc, char *argv[])
6219 const struct got_error *error = NULL;
6220 struct got_repository *repo = NULL;
6221 struct got_worktree *worktree = NULL;
6222 char *cwd = NULL, *repo_path = NULL, *commit_id_str = NULL;
6223 char *gitconfig_path = NULL, *tagger = NULL;
6224 char *allowed_signers = NULL, *revoked_signers = NULL;
6225 const char *signer_id = NULL;
6226 const char *tag_name = NULL, *commit_id_arg = NULL, *tagmsg = NULL;
6227 int ch, do_list = 0, verify_tags = 0, verbosity = 0;
6228 int *pack_fds = NULL;
6230 #ifndef PROFILE
6231 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
6232 "sendfd unveil", NULL) == -1)
6233 err(1, "pledge");
6234 #endif
6236 while ((ch = getopt(argc, argv, "c:lm:r:s:Vv")) != -1) {
6237 switch (ch) {
6238 case 'c':
6239 commit_id_arg = optarg;
6240 break;
6241 case 'l':
6242 do_list = 1;
6243 break;
6244 case 'm':
6245 tagmsg = optarg;
6246 break;
6247 case 'r':
6248 repo_path = realpath(optarg, NULL);
6249 if (repo_path == NULL) {
6250 error = got_error_from_errno2("realpath",
6251 optarg);
6252 goto done;
6254 got_path_strip_trailing_slashes(repo_path);
6255 break;
6256 case 's':
6257 signer_id = optarg;
6258 break;
6259 case 'V':
6260 verify_tags = 1;
6261 break;
6262 case 'v':
6263 if (verbosity < 0)
6264 verbosity = 0;
6265 else if (verbosity < 3)
6266 verbosity++;
6267 break;
6268 default:
6269 usage_tag();
6270 /* NOTREACHED */
6274 argc -= optind;
6275 argv += optind;
6277 if (do_list || verify_tags) {
6278 if (commit_id_arg != NULL)
6279 errx(1,
6280 "-c option can only be used when creating a tag");
6281 if (tagmsg) {
6282 if (do_list)
6283 option_conflict('l', 'm');
6284 else
6285 option_conflict('V', 'm');
6287 if (signer_id) {
6288 if (do_list)
6289 option_conflict('l', 's');
6290 else
6291 option_conflict('V', 's');
6293 if (argc > 1)
6294 usage_tag();
6295 } else if (argc != 1)
6296 usage_tag();
6298 if (argc == 1)
6299 tag_name = argv[0];
6301 cwd = getcwd(NULL, 0);
6302 if (cwd == NULL) {
6303 error = got_error_from_errno("getcwd");
6304 goto done;
6307 error = got_repo_pack_fds_open(&pack_fds);
6308 if (error != NULL)
6309 goto done;
6311 if (repo_path == NULL) {
6312 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_CVG_DIR);
6313 if (error && error->code != GOT_ERR_NOT_WORKTREE)
6314 goto done;
6315 else
6316 error = NULL;
6317 if (worktree) {
6318 repo_path =
6319 strdup(got_worktree_get_repo_path(worktree));
6320 if (repo_path == NULL)
6321 error = got_error_from_errno("strdup");
6322 if (error)
6323 goto done;
6324 } else {
6325 repo_path = strdup(cwd);
6326 if (repo_path == NULL) {
6327 error = got_error_from_errno("strdup");
6328 goto done;
6333 if (do_list || verify_tags) {
6334 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
6335 if (error != NULL)
6336 goto done;
6337 error = get_allowed_signers(&allowed_signers, repo, worktree);
6338 if (error)
6339 goto done;
6340 error = get_revoked_signers(&revoked_signers, repo, worktree);
6341 if (error)
6342 goto done;
6343 if (worktree) {
6344 /* Release work tree lock. */
6345 got_worktree_close(worktree);
6346 worktree = NULL;
6350 * Remove "cpath" promise unless needed for signature tmpfile
6351 * creation.
6353 if (verify_tags)
6354 got_sigs_apply_unveil();
6355 else {
6356 #ifndef PROFILE
6357 if (pledge("stdio rpath wpath flock proc exec sendfd "
6358 "unveil", NULL) == -1)
6359 err(1, "pledge");
6360 #endif
6362 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
6363 if (error)
6364 goto done;
6365 error = list_tags(repo, tag_name, verify_tags, allowed_signers,
6366 revoked_signers, verbosity);
6367 } else {
6368 error = get_gitconfig_path(&gitconfig_path);
6369 if (error)
6370 goto done;
6371 error = got_repo_open(&repo, repo_path, gitconfig_path,
6372 pack_fds);
6373 if (error != NULL)
6374 goto done;
6376 error = get_author(&tagger, repo, worktree);
6377 if (error)
6378 goto done;
6379 if (signer_id == NULL)
6380 signer_id = get_signer_id(repo, worktree);
6382 if (tagmsg) {
6383 if (signer_id) {
6384 error = got_sigs_apply_unveil();
6385 if (error)
6386 goto done;
6388 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
6389 if (error)
6390 goto done;
6393 if (commit_id_arg == NULL) {
6394 struct got_reference *head_ref;
6395 struct got_object_id *commit_id;
6396 error = got_ref_open(&head_ref, repo,
6397 worktree ? got_worktree_get_head_ref_name(worktree)
6398 : GOT_REF_HEAD, 0);
6399 if (error)
6400 goto done;
6401 error = got_ref_resolve(&commit_id, repo, head_ref);
6402 got_ref_close(head_ref);
6403 if (error)
6404 goto done;
6405 error = got_object_id_str(&commit_id_str, commit_id);
6406 free(commit_id);
6407 if (error)
6408 goto done;
6411 if (worktree) {
6412 /* Release work tree lock. */
6413 got_worktree_close(worktree);
6414 worktree = NULL;
6417 error = add_tag(repo, tagger, tag_name,
6418 commit_id_str ? commit_id_str : commit_id_arg, tagmsg,
6419 signer_id, verbosity);
6421 done:
6422 if (repo) {
6423 const struct got_error *close_err = got_repo_close(repo);
6424 if (error == NULL)
6425 error = close_err;
6427 if (worktree)
6428 got_worktree_close(worktree);
6429 if (pack_fds) {
6430 const struct got_error *pack_err =
6431 got_repo_pack_fds_close(pack_fds);
6432 if (error == NULL)
6433 error = pack_err;
6435 free(cwd);
6436 free(repo_path);
6437 free(gitconfig_path);
6438 free(commit_id_str);
6439 free(tagger);
6440 free(allowed_signers);
6441 free(revoked_signers);
6442 return error;
6445 __dead static void
6446 usage_add(void)
6448 fprintf(stderr, "usage: %s add [-IR] path ...\n", getprogname());
6449 exit(1);
6452 static const struct got_error *
6453 add_progress(void *arg, unsigned char status, const char *path)
6455 while (path[0] == '/')
6456 path++;
6457 printf("%c %s\n", status, path);
6458 return NULL;
6461 static const struct got_error *
6462 cmd_add(int argc, char *argv[])
6464 const struct got_error *error = NULL;
6465 struct got_repository *repo = NULL;
6466 struct got_worktree *worktree = NULL;
6467 char *cwd = NULL;
6468 struct got_pathlist_head paths;
6469 struct got_pathlist_entry *pe;
6470 int ch, can_recurse = 0, no_ignores = 0;
6471 int *pack_fds = NULL;
6473 TAILQ_INIT(&paths);
6475 #ifndef PROFILE
6476 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
6477 NULL) == -1)
6478 err(1, "pledge");
6479 #endif
6481 while ((ch = getopt(argc, argv, "IR")) != -1) {
6482 switch (ch) {
6483 case 'I':
6484 no_ignores = 1;
6485 break;
6486 case 'R':
6487 can_recurse = 1;
6488 break;
6489 default:
6490 usage_add();
6491 /* NOTREACHED */
6495 argc -= optind;
6496 argv += optind;
6498 if (argc < 1)
6499 usage_add();
6501 cwd = getcwd(NULL, 0);
6502 if (cwd == NULL) {
6503 error = got_error_from_errno("getcwd");
6504 goto done;
6507 error = got_repo_pack_fds_open(&pack_fds);
6508 if (error != NULL)
6509 goto done;
6511 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_CVG_DIR);
6512 if (error) {
6513 if (error->code == GOT_ERR_NOT_WORKTREE)
6514 error = wrap_not_worktree_error(error, "add", cwd);
6515 goto done;
6518 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
6519 NULL, pack_fds);
6520 if (error != NULL)
6521 goto done;
6523 error = apply_unveil(got_repo_get_path(repo), 1,
6524 got_worktree_get_root_path(worktree));
6525 if (error)
6526 goto done;
6528 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
6529 if (error)
6530 goto done;
6532 if (!can_recurse) {
6533 char *ondisk_path;
6534 struct stat sb;
6535 TAILQ_FOREACH(pe, &paths, entry) {
6536 if (asprintf(&ondisk_path, "%s/%s",
6537 got_worktree_get_root_path(worktree),
6538 pe->path) == -1) {
6539 error = got_error_from_errno("asprintf");
6540 goto done;
6542 if (lstat(ondisk_path, &sb) == -1) {
6543 if (errno == ENOENT) {
6544 free(ondisk_path);
6545 continue;
6547 error = got_error_from_errno2("lstat",
6548 ondisk_path);
6549 free(ondisk_path);
6550 goto done;
6552 free(ondisk_path);
6553 if (S_ISDIR(sb.st_mode)) {
6554 error = got_error_msg(GOT_ERR_BAD_PATH,
6555 "adding directories requires -R option");
6556 goto done;
6561 error = got_worktree_schedule_add(worktree, &paths, add_progress,
6562 NULL, repo, no_ignores);
6563 done:
6564 if (repo) {
6565 const struct got_error *close_err = got_repo_close(repo);
6566 if (error == NULL)
6567 error = close_err;
6569 if (worktree)
6570 got_worktree_close(worktree);
6571 if (pack_fds) {
6572 const struct got_error *pack_err =
6573 got_repo_pack_fds_close(pack_fds);
6574 if (error == NULL)
6575 error = pack_err;
6577 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
6578 free(cwd);
6579 return error;
6582 __dead static void
6583 usage_remove(void)
6585 fprintf(stderr, "usage: %s remove [-fkR] [-s status-codes] path ...\n",
6586 getprogname());
6587 exit(1);
6590 static const struct got_error *
6591 print_remove_status(void *arg, unsigned char status,
6592 unsigned char staged_status, const char *path)
6594 while (path[0] == '/')
6595 path++;
6596 if (status == GOT_STATUS_NONEXISTENT)
6597 return NULL;
6598 if (status == staged_status && (status == GOT_STATUS_DELETE))
6599 status = GOT_STATUS_NO_CHANGE;
6600 printf("%c%c %s\n", status, staged_status, path);
6601 return NULL;
6604 static const struct got_error *
6605 cmd_remove(int argc, char *argv[])
6607 const struct got_error *error = NULL;
6608 struct got_worktree *worktree = NULL;
6609 struct got_repository *repo = NULL;
6610 const char *status_codes = NULL;
6611 char *cwd = NULL;
6612 struct got_pathlist_head paths;
6613 struct got_pathlist_entry *pe;
6614 int ch, delete_local_mods = 0, can_recurse = 0, keep_on_disk = 0, i;
6615 int ignore_missing_paths = 0;
6616 int *pack_fds = NULL;
6618 TAILQ_INIT(&paths);
6620 #ifndef PROFILE
6621 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
6622 NULL) == -1)
6623 err(1, "pledge");
6624 #endif
6626 while ((ch = getopt(argc, argv, "fkRs:")) != -1) {
6627 switch (ch) {
6628 case 'f':
6629 delete_local_mods = 1;
6630 ignore_missing_paths = 1;
6631 break;
6632 case 'k':
6633 keep_on_disk = 1;
6634 break;
6635 case 'R':
6636 can_recurse = 1;
6637 break;
6638 case 's':
6639 for (i = 0; optarg[i] != '\0'; i++) {
6640 switch (optarg[i]) {
6641 case GOT_STATUS_MODIFY:
6642 delete_local_mods = 1;
6643 break;
6644 case GOT_STATUS_MISSING:
6645 ignore_missing_paths = 1;
6646 break;
6647 default:
6648 errx(1, "invalid status code '%c'",
6649 optarg[i]);
6652 status_codes = optarg;
6653 break;
6654 default:
6655 usage_remove();
6656 /* NOTREACHED */
6660 argc -= optind;
6661 argv += optind;
6663 if (argc < 1)
6664 usage_remove();
6666 cwd = getcwd(NULL, 0);
6667 if (cwd == NULL) {
6668 error = got_error_from_errno("getcwd");
6669 goto done;
6672 error = got_repo_pack_fds_open(&pack_fds);
6673 if (error != NULL)
6674 goto done;
6676 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_CVG_DIR);
6677 if (error) {
6678 if (error->code == GOT_ERR_NOT_WORKTREE)
6679 error = wrap_not_worktree_error(error, "remove", cwd);
6680 goto done;
6683 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
6684 NULL, pack_fds);
6685 if (error)
6686 goto done;
6688 error = apply_unveil(got_repo_get_path(repo), 1,
6689 got_worktree_get_root_path(worktree));
6690 if (error)
6691 goto done;
6693 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
6694 if (error)
6695 goto done;
6697 if (!can_recurse) {
6698 char *ondisk_path;
6699 struct stat sb;
6700 TAILQ_FOREACH(pe, &paths, entry) {
6701 if (asprintf(&ondisk_path, "%s/%s",
6702 got_worktree_get_root_path(worktree),
6703 pe->path) == -1) {
6704 error = got_error_from_errno("asprintf");
6705 goto done;
6707 if (lstat(ondisk_path, &sb) == -1) {
6708 if (errno == ENOENT) {
6709 free(ondisk_path);
6710 continue;
6712 error = got_error_from_errno2("lstat",
6713 ondisk_path);
6714 free(ondisk_path);
6715 goto done;
6717 free(ondisk_path);
6718 if (S_ISDIR(sb.st_mode)) {
6719 error = got_error_msg(GOT_ERR_BAD_PATH,
6720 "removing directories requires -R option");
6721 goto done;
6726 error = got_worktree_schedule_delete(worktree, &paths,
6727 delete_local_mods, status_codes, print_remove_status, NULL,
6728 repo, keep_on_disk, ignore_missing_paths);
6729 done:
6730 if (repo) {
6731 const struct got_error *close_err = got_repo_close(repo);
6732 if (error == NULL)
6733 error = close_err;
6735 if (worktree)
6736 got_worktree_close(worktree);
6737 if (pack_fds) {
6738 const struct got_error *pack_err =
6739 got_repo_pack_fds_close(pack_fds);
6740 if (error == NULL)
6741 error = pack_err;
6743 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
6744 free(cwd);
6745 return error;
6748 __dead static void
6749 usage_patch(void)
6751 fprintf(stderr, "usage: %s patch [-nR] [-c commit] [-p strip-count] "
6752 "[patchfile]\n", getprogname());
6753 exit(1);
6756 static const struct got_error *
6757 patch_from_stdin(int *patchfd)
6759 const struct got_error *err = NULL;
6760 ssize_t r;
6761 char buf[BUFSIZ];
6762 sig_t sighup, sigint, sigquit;
6764 *patchfd = got_opentempfd();
6765 if (*patchfd == -1)
6766 return got_error_from_errno("got_opentempfd");
6768 sighup = signal(SIGHUP, SIG_DFL);
6769 sigint = signal(SIGINT, SIG_DFL);
6770 sigquit = signal(SIGQUIT, SIG_DFL);
6772 for (;;) {
6773 r = read(0, buf, sizeof(buf));
6774 if (r == -1) {
6775 err = got_error_from_errno("read");
6776 break;
6778 if (r == 0)
6779 break;
6780 if (write(*patchfd, buf, r) == -1) {
6781 err = got_error_from_errno("write");
6782 break;
6786 signal(SIGHUP, sighup);
6787 signal(SIGINT, sigint);
6788 signal(SIGQUIT, sigquit);
6790 if (err == NULL && lseek(*patchfd, 0, SEEK_SET) == -1)
6791 err = got_error_from_errno("lseek");
6793 if (err != NULL) {
6794 close(*patchfd);
6795 *patchfd = -1;
6798 return err;
6801 struct got_patch_progress_arg {
6802 int did_something;
6803 int conflicts;
6804 int rejects;
6807 static const struct got_error *
6808 patch_progress(void *arg, const char *old, const char *new,
6809 unsigned char status, const struct got_error *error, int old_from,
6810 int old_lines, int new_from, int new_lines, int offset,
6811 int ws_mangled, const struct got_error *hunk_err)
6813 const char *path = new == NULL ? old : new;
6814 struct got_patch_progress_arg *a = arg;
6816 while (*path == '/')
6817 path++;
6819 if (status != GOT_STATUS_NO_CHANGE &&
6820 status != 0 /* per-hunk progress */) {
6821 printf("%c %s\n", status, path);
6822 a->did_something = 1;
6825 if (hunk_err == NULL) {
6826 if (status == GOT_STATUS_CANNOT_UPDATE)
6827 a->rejects++;
6828 else if (status == GOT_STATUS_CONFLICT)
6829 a->conflicts++;
6832 if (error != NULL)
6833 fprintf(stderr, "%s: %s\n", getprogname(), error->msg);
6835 if (offset != 0 || hunk_err != NULL || ws_mangled) {
6836 printf("@@ -%d,%d +%d,%d @@ ", old_from,
6837 old_lines, new_from, new_lines);
6838 if (hunk_err != NULL)
6839 printf("%s\n", hunk_err->msg);
6840 else if (offset != 0)
6841 printf("applied with offset %d\n", offset);
6842 else
6843 printf("hunk contains mangled whitespace\n");
6846 return NULL;
6849 static void
6850 print_patch_progress_stats(struct got_patch_progress_arg *ppa)
6852 if (!ppa->did_something)
6853 return;
6855 if (ppa->conflicts > 0)
6856 printf("Files with merge conflicts: %d\n", ppa->conflicts);
6858 if (ppa->rejects > 0) {
6859 printf("Files where patch failed to apply: %d\n",
6860 ppa->rejects);
6864 static const struct got_error *
6865 cmd_patch(int argc, char *argv[])
6867 const struct got_error *error = NULL, *close_error = NULL;
6868 struct got_worktree *worktree = NULL;
6869 struct got_repository *repo = NULL;
6870 struct got_reflist_head refs;
6871 struct got_object_id *commit_id = NULL;
6872 const char *commit_id_str = NULL;
6873 struct stat sb;
6874 const char *errstr;
6875 char *cwd = NULL;
6876 int ch, nop = 0, strip = -1, reverse = 0;
6877 int patchfd;
6878 int *pack_fds = NULL;
6879 struct got_patch_progress_arg ppa;
6881 TAILQ_INIT(&refs);
6883 #ifndef PROFILE
6884 if (pledge("stdio rpath wpath cpath fattr proc exec sendfd flock "
6885 "unveil", NULL) == -1)
6886 err(1, "pledge");
6887 #endif
6889 while ((ch = getopt(argc, argv, "c:np:R")) != -1) {
6890 switch (ch) {
6891 case 'c':
6892 commit_id_str = optarg;
6893 break;
6894 case 'n':
6895 nop = 1;
6896 break;
6897 case 'p':
6898 strip = strtonum(optarg, 0, INT_MAX, &errstr);
6899 if (errstr != NULL)
6900 errx(1, "pathname strip count is %s: %s",
6901 errstr, optarg);
6902 break;
6903 case 'R':
6904 reverse = 1;
6905 break;
6906 default:
6907 usage_patch();
6908 /* NOTREACHED */
6912 argc -= optind;
6913 argv += optind;
6915 if (argc == 0) {
6916 error = patch_from_stdin(&patchfd);
6917 if (error)
6918 return error;
6919 } else if (argc == 1) {
6920 patchfd = open(argv[0], O_RDONLY);
6921 if (patchfd == -1) {
6922 error = got_error_from_errno2("open", argv[0]);
6923 return error;
6925 if (fstat(patchfd, &sb) == -1) {
6926 error = got_error_from_errno2("fstat", argv[0]);
6927 goto done;
6929 if (!S_ISREG(sb.st_mode)) {
6930 error = got_error_path(argv[0], GOT_ERR_BAD_FILETYPE);
6931 goto done;
6933 } else
6934 usage_patch();
6936 if ((cwd = getcwd(NULL, 0)) == NULL) {
6937 error = got_error_from_errno("getcwd");
6938 goto done;
6941 error = got_repo_pack_fds_open(&pack_fds);
6942 if (error != NULL)
6943 goto done;
6945 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_CVG_DIR);
6946 if (error != NULL)
6947 goto done;
6949 const char *repo_path = got_worktree_get_repo_path(worktree);
6950 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
6951 if (error != NULL)
6952 goto done;
6954 error = apply_unveil(got_repo_get_path(repo), 0,
6955 got_worktree_get_root_path(worktree));
6956 if (error != NULL)
6957 goto done;
6959 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
6960 if (error)
6961 goto done;
6963 if (commit_id_str != NULL) {
6964 error = got_repo_match_object_id(&commit_id, NULL,
6965 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
6966 if (error)
6967 goto done;
6970 memset(&ppa, 0, sizeof(ppa));
6971 error = got_patch(patchfd, worktree, repo, nop, strip, reverse,
6972 commit_id, patch_progress, &ppa, check_cancelled, NULL);
6973 print_patch_progress_stats(&ppa);
6974 done:
6975 got_ref_list_free(&refs);
6976 free(commit_id);
6977 if (repo) {
6978 close_error = got_repo_close(repo);
6979 if (error == NULL)
6980 error = close_error;
6982 if (worktree != NULL) {
6983 close_error = got_worktree_close(worktree);
6984 if (error == NULL)
6985 error = close_error;
6987 if (pack_fds) {
6988 const struct got_error *pack_err =
6989 got_repo_pack_fds_close(pack_fds);
6990 if (error == NULL)
6991 error = pack_err;
6993 free(cwd);
6994 return error;
6997 __dead static void
6998 usage_revert(void)
7000 fprintf(stderr, "usage: %s revert [-pR] [-F response-script] path ...\n",
7001 getprogname());
7002 exit(1);
7005 static const struct got_error *
7006 revert_progress(void *arg, unsigned char status, const char *path)
7008 if (status == GOT_STATUS_UNVERSIONED)
7009 return NULL;
7011 while (path[0] == '/')
7012 path++;
7013 printf("%c %s\n", status, path);
7014 return NULL;
7017 struct choose_patch_arg {
7018 FILE *patch_script_file;
7019 const char *action;
7022 static const struct got_error *
7023 show_change(unsigned char status, const char *path, FILE *patch_file, int n,
7024 int nchanges, const char *action)
7026 const struct got_error *err;
7027 char *line = NULL;
7028 size_t linesize = 0;
7029 ssize_t linelen;
7031 switch (status) {
7032 case GOT_STATUS_ADD:
7033 printf("A %s\n%s this addition? [y/n] ", path, action);
7034 break;
7035 case GOT_STATUS_DELETE:
7036 printf("D %s\n%s this deletion? [y/n] ", path, action);
7037 break;
7038 case GOT_STATUS_MODIFY:
7039 if (fseek(patch_file, 0L, SEEK_SET) == -1)
7040 return got_error_from_errno("fseek");
7041 printf(GOT_COMMIT_SEP_STR);
7042 while ((linelen = getline(&line, &linesize, patch_file)) != -1)
7043 printf("%s", line);
7044 if (linelen == -1 && ferror(patch_file)) {
7045 err = got_error_from_errno("getline");
7046 free(line);
7047 return err;
7049 free(line);
7050 printf(GOT_COMMIT_SEP_STR);
7051 printf("M %s (change %d of %d)\n%s this change? [y/n/q] ",
7052 path, n, nchanges, action);
7053 break;
7054 default:
7055 return got_error_path(path, GOT_ERR_FILE_STATUS);
7058 fflush(stdout);
7059 return NULL;
7062 static const struct got_error *
7063 choose_patch(int *choice, void *arg, unsigned char status, const char *path,
7064 FILE *patch_file, int n, int nchanges)
7066 const struct got_error *err = NULL;
7067 char *line = NULL;
7068 size_t linesize = 0;
7069 ssize_t linelen;
7070 int resp = ' ';
7071 struct choose_patch_arg *a = arg;
7073 *choice = GOT_PATCH_CHOICE_NONE;
7075 if (a->patch_script_file) {
7076 char *nl;
7077 err = show_change(status, path, patch_file, n, nchanges,
7078 a->action);
7079 if (err)
7080 return err;
7081 linelen = getline(&line, &linesize, a->patch_script_file);
7082 if (linelen == -1) {
7083 if (ferror(a->patch_script_file))
7084 return got_error_from_errno("getline");
7085 return NULL;
7087 nl = strchr(line, '\n');
7088 if (nl)
7089 *nl = '\0';
7090 if (strcmp(line, "y") == 0) {
7091 *choice = GOT_PATCH_CHOICE_YES;
7092 printf("y\n");
7093 } else if (strcmp(line, "n") == 0) {
7094 *choice = GOT_PATCH_CHOICE_NO;
7095 printf("n\n");
7096 } else if (strcmp(line, "q") == 0 &&
7097 status == GOT_STATUS_MODIFY) {
7098 *choice = GOT_PATCH_CHOICE_QUIT;
7099 printf("q\n");
7100 } else
7101 printf("invalid response '%s'\n", line);
7102 free(line);
7103 return NULL;
7106 while (resp != 'y' && resp != 'n' && resp != 'q') {
7107 err = show_change(status, path, patch_file, n, nchanges,
7108 a->action);
7109 if (err)
7110 return err;
7111 resp = getchar();
7112 if (resp == '\n')
7113 resp = getchar();
7114 if (status == GOT_STATUS_MODIFY) {
7115 if (resp != 'y' && resp != 'n' && resp != 'q') {
7116 printf("invalid response '%c'\n", resp);
7117 resp = ' ';
7119 } else if (resp != 'y' && resp != 'n') {
7120 printf("invalid response '%c'\n", resp);
7121 resp = ' ';
7125 if (resp == 'y')
7126 *choice = GOT_PATCH_CHOICE_YES;
7127 else if (resp == 'n')
7128 *choice = GOT_PATCH_CHOICE_NO;
7129 else if (resp == 'q' && status == GOT_STATUS_MODIFY)
7130 *choice = GOT_PATCH_CHOICE_QUIT;
7132 return NULL;
7135 struct wt_commitable_path_arg {
7136 struct got_pathlist_head *commit_paths;
7137 int *has_changes;
7141 * Shortcut work tree status callback to determine if the set of paths scanned
7142 * has at least one versioned path that is being modified and, if not NULL, is
7143 * in the arg->commit_paths list. Set arg and return GOT_ERR_FILE_MODIFIED as
7144 * soon as a path is passed with a status that satisfies this criteria.
7146 static const struct got_error *
7147 worktree_has_commitable_path(void *arg, unsigned char status,
7148 unsigned char staged_status, const char *path,
7149 struct got_object_id *blob_id, struct got_object_id *staged_blob_id,
7150 struct got_object_id *commit_id, int dirfd, const char *de_name)
7152 struct wt_commitable_path_arg *a = arg;
7154 if (status == staged_status && (status == GOT_STATUS_DELETE))
7155 status = GOT_STATUS_NO_CHANGE;
7157 if (!(status == GOT_STATUS_NO_CHANGE ||
7158 status == GOT_STATUS_UNVERSIONED) ||
7159 staged_status != GOT_STATUS_NO_CHANGE) {
7160 if (a->commit_paths != NULL) {
7161 struct got_pathlist_entry *pe;
7163 TAILQ_FOREACH(pe, a->commit_paths, entry) {
7164 if (strncmp(path, pe->path,
7165 pe->path_len) == 0) {
7166 *a->has_changes = 1;
7167 break;
7170 } else
7171 *a->has_changes = 1;
7173 if (*a->has_changes)
7174 return got_error(GOT_ERR_FILE_MODIFIED);
7177 return NULL;
7181 * Check that the changeset of the commit identified by id is
7182 * comprised of at least one modified path that is being committed.
7184 static const struct got_error *
7185 commit_path_changed_in_worktree(struct wt_commitable_path_arg *wcpa,
7186 struct got_object_id *id, struct got_worktree *worktree,
7187 struct got_repository *repo)
7189 const struct got_error *err;
7190 struct got_pathlist_head paths;
7191 struct got_commit_object *commit = NULL, *pcommit = NULL;
7192 struct got_tree_object *tree = NULL, *ptree = NULL;
7193 struct got_object_qid *pid;
7195 TAILQ_INIT(&paths);
7197 err = got_object_open_as_commit(&commit, repo, id);
7198 if (err)
7199 goto done;
7201 err = got_object_open_as_tree(&tree, repo,
7202 got_object_commit_get_tree_id(commit));
7203 if (err)
7204 goto done;
7206 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
7207 if (pid != NULL) {
7208 err = got_object_open_as_commit(&pcommit, repo, &pid->id);
7209 if (err)
7210 goto done;
7212 err = got_object_open_as_tree(&ptree, repo,
7213 got_object_commit_get_tree_id(pcommit));
7214 if (err)
7215 goto done;
7218 err = got_diff_tree(ptree, tree, NULL, NULL, -1, -1, "", "", repo,
7219 got_diff_tree_collect_changed_paths, &paths, 0);
7220 if (err)
7221 goto done;
7223 err = got_worktree_status(worktree, &paths, repo, 0,
7224 worktree_has_commitable_path, wcpa, check_cancelled, NULL);
7225 if (err && err->code == GOT_ERR_FILE_MODIFIED) {
7227 * At least one changed path in the referenced commit is
7228 * modified in the work tree, that's all we need to know!
7230 err = NULL;
7233 done:
7234 got_pathlist_free(&paths, GOT_PATHLIST_FREE_ALL);
7235 if (commit)
7236 got_object_commit_close(commit);
7237 if (pcommit)
7238 got_object_commit_close(pcommit);
7239 if (tree)
7240 got_object_tree_close(tree);
7241 if (ptree)
7242 got_object_tree_close(ptree);
7243 return err;
7247 * Remove any "logmsg" reference comprised entirely of paths that have
7248 * been reverted in this work tree. If any path in the logmsg ref changeset
7249 * remains in a changed state in the worktree, do not remove the reference.
7251 static const struct got_error *
7252 rm_logmsg_ref(struct got_worktree *worktree, struct got_repository *repo)
7254 const struct got_error *err;
7255 struct got_reflist_head refs;
7256 struct got_reflist_entry *re;
7257 struct got_commit_object *commit = NULL;
7258 struct got_object_id *commit_id = NULL;
7259 struct wt_commitable_path_arg wcpa;
7260 char *uuidstr = NULL;
7262 TAILQ_INIT(&refs);
7264 err = got_worktree_get_uuid(&uuidstr, worktree);
7265 if (err)
7266 goto done;
7268 err = got_ref_list(&refs, repo, "refs/got/worktree",
7269 got_ref_cmp_by_name, repo);
7270 if (err)
7271 goto done;
7273 TAILQ_FOREACH(re, &refs, entry) {
7274 const char *refname;
7275 int has_changes = 0;
7277 refname = got_ref_get_name(re->ref);
7279 if (!strncmp(refname, GOT_WORKTREE_CHERRYPICK_REF_PREFIX,
7280 GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN))
7281 refname += GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN + 1;
7282 else if (!strncmp(refname, GOT_WORKTREE_BACKOUT_REF_PREFIX,
7283 GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN))
7284 refname += GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN + 1;
7285 else
7286 continue;
7288 if (strncmp(refname, uuidstr, GOT_WORKTREE_UUID_STRLEN) == 0)
7289 refname += GOT_WORKTREE_UUID_STRLEN + 1; /* skip '-' */
7290 else
7291 continue;
7293 err = got_repo_match_object_id(&commit_id, NULL, refname,
7294 GOT_OBJ_TYPE_COMMIT, NULL, repo);
7295 if (err)
7296 goto done;
7298 err = got_object_open_as_commit(&commit, repo, commit_id);
7299 if (err)
7300 goto done;
7302 wcpa.commit_paths = NULL;
7303 wcpa.has_changes = &has_changes;
7305 err = commit_path_changed_in_worktree(&wcpa, commit_id,
7306 worktree, repo);
7307 if (err)
7308 goto done;
7310 if (!has_changes) {
7311 err = got_ref_delete(re->ref, repo);
7312 if (err)
7313 goto done;
7316 got_object_commit_close(commit);
7317 commit = NULL;
7318 free(commit_id);
7319 commit_id = NULL;
7322 done:
7323 free(uuidstr);
7324 free(commit_id);
7325 got_ref_list_free(&refs);
7326 if (commit)
7327 got_object_commit_close(commit);
7328 return err;
7331 static const struct got_error *
7332 cmd_revert(int argc, char *argv[])
7334 const struct got_error *error = NULL;
7335 struct got_worktree *worktree = NULL;
7336 struct got_repository *repo = NULL;
7337 char *cwd = NULL, *path = NULL;
7338 struct got_pathlist_head paths;
7339 struct got_pathlist_entry *pe;
7340 int ch, can_recurse = 0, pflag = 0;
7341 FILE *patch_script_file = NULL;
7342 const char *patch_script_path = NULL;
7343 struct choose_patch_arg cpa;
7344 int *pack_fds = NULL;
7346 TAILQ_INIT(&paths);
7348 #ifndef PROFILE
7349 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
7350 "unveil", NULL) == -1)
7351 err(1, "pledge");
7352 #endif
7354 while ((ch = getopt(argc, argv, "F:pR")) != -1) {
7355 switch (ch) {
7356 case 'F':
7357 patch_script_path = optarg;
7358 break;
7359 case 'p':
7360 pflag = 1;
7361 break;
7362 case 'R':
7363 can_recurse = 1;
7364 break;
7365 default:
7366 usage_revert();
7367 /* NOTREACHED */
7371 argc -= optind;
7372 argv += optind;
7374 if (argc < 1)
7375 usage_revert();
7376 if (patch_script_path && !pflag)
7377 errx(1, "-F option can only be used together with -p option");
7379 cwd = getcwd(NULL, 0);
7380 if (cwd == NULL) {
7381 error = got_error_from_errno("getcwd");
7382 goto done;
7385 error = got_repo_pack_fds_open(&pack_fds);
7386 if (error != NULL)
7387 goto done;
7389 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_CVG_DIR);
7390 if (error) {
7391 if (error->code == GOT_ERR_NOT_WORKTREE)
7392 error = wrap_not_worktree_error(error, "revert", cwd);
7393 goto done;
7396 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
7397 NULL, pack_fds);
7398 if (error != NULL)
7399 goto done;
7401 if (patch_script_path) {
7402 patch_script_file = fopen(patch_script_path, "re");
7403 if (patch_script_file == NULL) {
7404 error = got_error_from_errno2("fopen",
7405 patch_script_path);
7406 goto done;
7411 * XXX "c" perm needed on repo dir to delete merge references.
7413 error = apply_unveil(got_repo_get_path(repo), 0,
7414 got_worktree_get_root_path(worktree));
7415 if (error)
7416 goto done;
7418 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
7419 if (error)
7420 goto done;
7422 if (!can_recurse) {
7423 char *ondisk_path;
7424 struct stat sb;
7425 TAILQ_FOREACH(pe, &paths, entry) {
7426 if (asprintf(&ondisk_path, "%s/%s",
7427 got_worktree_get_root_path(worktree),
7428 pe->path) == -1) {
7429 error = got_error_from_errno("asprintf");
7430 goto done;
7432 if (lstat(ondisk_path, &sb) == -1) {
7433 if (errno == ENOENT) {
7434 free(ondisk_path);
7435 continue;
7437 error = got_error_from_errno2("lstat",
7438 ondisk_path);
7439 free(ondisk_path);
7440 goto done;
7442 free(ondisk_path);
7443 if (S_ISDIR(sb.st_mode)) {
7444 error = got_error_msg(GOT_ERR_BAD_PATH,
7445 "reverting directories requires -R option");
7446 goto done;
7451 cpa.patch_script_file = patch_script_file;
7452 cpa.action = "revert";
7453 error = got_worktree_revert(worktree, &paths, revert_progress, NULL,
7454 pflag ? choose_patch : NULL, &cpa, repo);
7456 error = rm_logmsg_ref(worktree, repo);
7457 done:
7458 if (patch_script_file && fclose(patch_script_file) == EOF &&
7459 error == NULL)
7460 error = got_error_from_errno2("fclose", patch_script_path);
7461 if (repo) {
7462 const struct got_error *close_err = got_repo_close(repo);
7463 if (error == NULL)
7464 error = close_err;
7466 if (worktree)
7467 got_worktree_close(worktree);
7468 if (pack_fds) {
7469 const struct got_error *pack_err =
7470 got_repo_pack_fds_close(pack_fds);
7471 if (error == NULL)
7472 error = pack_err;
7474 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
7475 free(path);
7476 free(cwd);
7477 return error;
7480 __dead static void
7481 usage_commit(void)
7483 fprintf(stderr, "usage: %s commit [-CNnS] [-A author] [-F path] "
7484 "[-m message] [path ...]\n", getprogname());
7485 exit(1);
7488 struct collect_commit_logmsg_arg {
7489 const char *cmdline_log;
7490 const char *prepared_log;
7491 const char *merged_log;
7492 int non_interactive;
7493 const char *editor;
7494 const char *worktree_path;
7495 const char *repo_path;
7496 const char *dial_proto;
7497 char *logmsg_path;
7500 static const struct got_error *
7501 read_prepared_logmsg(char **logmsg, const char *path)
7503 const struct got_error *err = NULL;
7504 FILE *f = NULL;
7505 struct stat sb;
7506 size_t r;
7508 *logmsg = NULL;
7509 memset(&sb, 0, sizeof(sb));
7511 f = fopen(path, "re");
7512 if (f == NULL)
7513 return got_error_from_errno2("fopen", path);
7515 if (fstat(fileno(f), &sb) == -1) {
7516 err = got_error_from_errno2("fstat", path);
7517 goto done;
7519 if (sb.st_size == 0) {
7520 err = got_error(GOT_ERR_COMMIT_MSG_EMPTY);
7521 goto done;
7524 *logmsg = malloc(sb.st_size + 1);
7525 if (*logmsg == NULL) {
7526 err = got_error_from_errno("malloc");
7527 goto done;
7530 r = fread(*logmsg, 1, sb.st_size, f);
7531 if (r != sb.st_size) {
7532 if (ferror(f))
7533 err = got_error_from_errno2("fread", path);
7534 else
7535 err = got_error(GOT_ERR_IO);
7536 goto done;
7538 (*logmsg)[sb.st_size] = '\0';
7539 done:
7540 if (fclose(f) == EOF && err == NULL)
7541 err = got_error_from_errno2("fclose", path);
7542 if (err) {
7543 free(*logmsg);
7544 *logmsg = NULL;
7546 return err;
7549 static const struct got_error *
7550 collect_commit_logmsg(struct got_pathlist_head *commitable_paths,
7551 const char *diff_path, char **logmsg, void *arg)
7553 char *initial_content = NULL;
7554 struct got_pathlist_entry *pe;
7555 const struct got_error *err = NULL;
7556 char *template = NULL;
7557 char *prepared_msg = NULL, *merged_msg = NULL;
7558 struct collect_commit_logmsg_arg *a = arg;
7559 int initial_content_len;
7560 int fd = -1;
7561 size_t len;
7563 /* if a message was specified on the command line, just use it */
7564 if (a->cmdline_log != NULL && *a->cmdline_log != '\0') {
7565 len = strlen(a->cmdline_log) + 1;
7566 *logmsg = malloc(len + 1);
7567 if (*logmsg == NULL)
7568 return got_error_from_errno("malloc");
7569 strlcpy(*logmsg, a->cmdline_log, len);
7570 return NULL;
7571 } else if (a->prepared_log != NULL && a->non_interactive)
7572 return read_prepared_logmsg(logmsg, a->prepared_log);
7574 if (asprintf(&template, "%s/logmsg", a->worktree_path) == -1)
7575 return got_error_from_errno("asprintf");
7577 err = got_opentemp_named_fd(&a->logmsg_path, &fd, template, "");
7578 if (err)
7579 goto done;
7581 if (a->prepared_log) {
7582 err = read_prepared_logmsg(&prepared_msg, a->prepared_log);
7583 if (err)
7584 goto done;
7585 } else if (a->merged_log) {
7586 err = read_prepared_logmsg(&merged_msg, a->merged_log);
7587 if (err)
7588 goto done;
7591 initial_content_len = asprintf(&initial_content,
7592 "%s%s\n# changes to be committed:\n",
7593 prepared_msg ? prepared_msg : "",
7594 merged_msg ? merged_msg : "");
7595 if (initial_content_len == -1) {
7596 err = got_error_from_errno("asprintf");
7597 goto done;
7600 if (write(fd, initial_content, initial_content_len) == -1) {
7601 err = got_error_from_errno2("write", a->logmsg_path);
7602 goto done;
7605 TAILQ_FOREACH(pe, commitable_paths, entry) {
7606 struct got_commitable *ct = pe->data;
7607 dprintf(fd, "# %c %s\n",
7608 got_commitable_get_status(ct),
7609 got_commitable_get_path(ct));
7612 if (diff_path) {
7613 dprintf(fd, "# detailed changes can be viewed in %s\n",
7614 diff_path);
7617 if (close(fd) == -1) {
7618 err = got_error_from_errno2("close", a->logmsg_path);
7619 goto done;
7621 fd = -1;
7623 err = edit_logmsg(logmsg, a->editor, a->logmsg_path, initial_content,
7624 initial_content_len, a->prepared_log ? 0 : 1);
7625 done:
7626 free(initial_content);
7627 free(template);
7628 free(prepared_msg);
7629 free(merged_msg);
7631 if (fd != -1 && close(fd) == -1 && err == NULL)
7632 err = got_error_from_errno2("close", a->logmsg_path);
7634 /* Editor is done; we can now apply unveil(2) */
7635 if (err == NULL)
7636 err = got_dial_apply_unveil(a->dial_proto);
7637 if (err == NULL)
7638 err = apply_unveil(a->repo_path, 0, a->worktree_path);
7639 if (err) {
7640 free(*logmsg);
7641 *logmsg = NULL;
7643 return err;
7646 static const struct got_error *
7647 cat_logmsg(FILE *f, struct got_commit_object *commit, const char *idstr,
7648 const char *type, int has_content)
7650 const struct got_error *err = NULL;
7651 char *logmsg = NULL;
7653 err = got_object_commit_get_logmsg(&logmsg, commit);
7654 if (err)
7655 return err;
7657 if (fprintf(f, "%s# log message of %s commit %s:%s",
7658 has_content ? "\n" : "", type, idstr, logmsg) < 0)
7659 err = got_ferror(f, GOT_ERR_IO);
7661 free(logmsg);
7662 return err;
7666 * Lookup "logmsg" references of backed-out and cherrypicked commits
7667 * belonging to the current work tree. If found, and the worktree has
7668 * at least one modified file that was changed in the referenced commit,
7669 * add its log message to a new temporary file at *logmsg_path.
7670 * Add all refs found to matched_refs to be scheduled for removal on
7671 * successful commit.
7673 static const struct got_error *
7674 lookup_logmsg_ref(char **logmsg_path, struct got_pathlist_head *paths,
7675 struct got_reflist_head *matched_refs, struct got_worktree *worktree,
7676 struct got_repository *repo)
7678 const struct got_error *err;
7679 struct got_commit_object *commit = NULL;
7680 struct got_object_id *id = NULL;
7681 struct got_reflist_head refs;
7682 struct got_reflist_entry *re, *re_match;
7683 FILE *f = NULL;
7684 char *uuidstr = NULL;
7685 int added_logmsg = 0;
7687 TAILQ_INIT(&refs);
7689 *logmsg_path = NULL;
7691 err = got_worktree_get_uuid(&uuidstr, worktree);
7692 if (err)
7693 goto done;
7695 err = got_ref_list(&refs, repo, "refs/got/worktree",
7696 got_ref_cmp_by_name, repo);
7697 if (err)
7698 goto done;
7700 TAILQ_FOREACH(re, &refs, entry) {
7701 const char *refname, *type;
7702 struct wt_commitable_path_arg wcpa;
7703 int add_logmsg = 0;
7705 refname = got_ref_get_name(re->ref);
7707 if (strncmp(refname, GOT_WORKTREE_CHERRYPICK_REF_PREFIX,
7708 GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN) == 0) {
7709 refname += GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN + 1;
7710 type = "cherrypicked";
7711 } else if (strncmp(refname, GOT_WORKTREE_BACKOUT_REF_PREFIX,
7712 GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN) == 0) {
7713 refname += GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN + 1;
7714 type = "backed-out";
7715 } else
7716 continue;
7718 if (strncmp(refname, uuidstr, GOT_WORKTREE_UUID_STRLEN) == 0)
7719 refname += GOT_WORKTREE_UUID_STRLEN + 1; /* skip '-' */
7720 else
7721 continue;
7723 err = got_repo_match_object_id(&id, NULL, refname,
7724 GOT_OBJ_TYPE_COMMIT, NULL, repo);
7725 if (err)
7726 goto done;
7728 err = got_object_open_as_commit(&commit, repo, id);
7729 if (err)
7730 goto done;
7732 wcpa.commit_paths = paths;
7733 wcpa.has_changes = &add_logmsg;
7735 err = commit_path_changed_in_worktree(&wcpa, id,
7736 worktree, repo);
7737 if (err)
7738 goto done;
7740 if (add_logmsg) {
7741 if (f == NULL) {
7742 err = got_opentemp_named(logmsg_path, &f,
7743 "got-commit-logmsg", "");
7744 if (err)
7745 goto done;
7747 err = cat_logmsg(f, commit, refname, type,
7748 added_logmsg);
7749 if (err)
7750 goto done;
7751 if (!added_logmsg)
7752 ++added_logmsg;
7754 err = got_reflist_entry_dup(&re_match, re);
7755 if (err)
7756 goto done;
7757 TAILQ_INSERT_HEAD(matched_refs, re_match, entry);
7760 got_object_commit_close(commit);
7761 commit = NULL;
7762 free(id);
7763 id = NULL;
7766 done:
7767 free(id);
7768 free(uuidstr);
7769 got_ref_list_free(&refs);
7770 if (commit)
7771 got_object_commit_close(commit);
7772 if (f && fclose(f) == EOF && err == NULL)
7773 err = got_error_from_errno("fclose");
7774 if (!added_logmsg) {
7775 if (*logmsg_path && unlink(*logmsg_path) != 0 && err == NULL)
7776 err = got_error_from_errno2("unlink", *logmsg_path);
7777 *logmsg_path = NULL;
7779 return err;
7782 static const struct got_error *
7783 cmd_commit(int argc, char *argv[])
7785 const struct got_error *error = NULL;
7786 struct got_worktree *worktree = NULL;
7787 struct got_repository *repo = NULL;
7788 char *cwd = NULL, *id_str = NULL;
7789 struct got_object_id *id = NULL;
7790 const char *logmsg = NULL;
7791 char *prepared_logmsg = NULL, *merged_logmsg = NULL;
7792 struct collect_commit_logmsg_arg cl_arg;
7793 const char *author = NULL;
7794 char *gitconfig_path = NULL, *editor = NULL, *committer = NULL;
7795 int ch, rebase_in_progress, histedit_in_progress, preserve_logmsg = 0;
7796 int allow_bad_symlinks = 0, non_interactive = 0, merge_in_progress = 0;
7797 int show_diff = 1, commit_conflicts = 0;
7798 struct got_pathlist_head paths;
7799 struct got_reflist_head refs;
7800 struct got_reflist_entry *re;
7801 int *pack_fds = NULL;
7802 const struct got_gotconfig *repo_conf = NULL, *worktree_conf = NULL;
7803 const struct got_remote_repo *remotes, *remote = NULL;
7804 int nremotes;
7805 char *proto = NULL, *host = NULL, *port = NULL;
7806 char *repo_name = NULL, *server_path = NULL;
7807 const char *remote_name;
7808 int verbosity = 0;
7809 int i;
7811 TAILQ_INIT(&refs);
7812 TAILQ_INIT(&paths);
7813 cl_arg.logmsg_path = NULL;
7815 #ifndef PROFILE
7816 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
7817 "unveil", NULL) == -1)
7818 err(1, "pledge");
7819 #endif
7821 while ((ch = getopt(argc, argv, "A:CF:m:NnS")) != -1) {
7822 switch (ch) {
7823 case 'A':
7824 author = optarg;
7825 error = valid_author(author);
7826 if (error)
7827 return error;
7828 break;
7829 case 'C':
7830 commit_conflicts = 1;
7831 break;
7832 case 'F':
7833 if (logmsg != NULL)
7834 option_conflict('F', 'm');
7835 prepared_logmsg = realpath(optarg, NULL);
7836 if (prepared_logmsg == NULL)
7837 return got_error_from_errno2("realpath",
7838 optarg);
7839 break;
7840 case 'm':
7841 if (prepared_logmsg)
7842 option_conflict('m', 'F');
7843 logmsg = optarg;
7844 break;
7845 case 'N':
7846 non_interactive = 1;
7847 break;
7848 case 'n':
7849 show_diff = 0;
7850 break;
7851 case 'S':
7852 allow_bad_symlinks = 1;
7853 break;
7854 default:
7855 usage_commit();
7856 /* NOTREACHED */
7860 argc -= optind;
7861 argv += optind;
7863 cwd = getcwd(NULL, 0);
7864 if (cwd == NULL) {
7865 error = got_error_from_errno("getcwd");
7866 goto done;
7869 error = got_repo_pack_fds_open(&pack_fds);
7870 if (error != NULL)
7871 goto done;
7873 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_CVG_DIR);
7874 if (error) {
7875 if (error->code == GOT_ERR_NOT_WORKTREE)
7876 error = wrap_not_worktree_error(error, "commit", cwd);
7877 goto done;
7880 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
7881 if (error)
7882 goto done;
7883 if (rebase_in_progress) {
7884 error = got_error(GOT_ERR_REBASING);
7885 goto done;
7888 error = got_worktree_histedit_in_progress(&histedit_in_progress,
7889 worktree);
7890 if (error)
7891 goto done;
7893 error = get_gitconfig_path(&gitconfig_path);
7894 if (error)
7895 goto done;
7896 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
7897 gitconfig_path, pack_fds);
7898 if (error != NULL)
7899 goto done;
7901 error = got_worktree_merge_in_progress(&merge_in_progress, worktree, repo);
7902 if (error)
7903 goto done;
7904 if (merge_in_progress) {
7905 error = got_error(GOT_ERR_MERGE_BUSY);
7906 goto done;
7909 error = get_author(&committer, repo, worktree);
7910 if (error)
7911 goto done;
7913 if (author == NULL)
7914 author = committer;
7916 remote_name = GOT_SEND_DEFAULT_REMOTE_NAME;
7917 worktree_conf = got_worktree_get_gotconfig(worktree);
7918 if (worktree_conf) {
7919 got_gotconfig_get_remotes(&nremotes, &remotes,
7920 worktree_conf);
7921 for (i = 0; i < nremotes; i++) {
7922 if (strcmp(remotes[i].name, remote_name) == 0) {
7923 remote = &remotes[i];
7924 break;
7928 if (remote == NULL) {
7929 repo_conf = got_repo_get_gotconfig(repo);
7930 if (repo_conf) {
7931 got_gotconfig_get_remotes(&nremotes, &remotes,
7932 repo_conf);
7933 for (i = 0; i < nremotes; i++) {
7934 if (strcmp(remotes[i].name, remote_name) == 0) {
7935 remote = &remotes[i];
7936 break;
7941 if (remote == NULL) {
7942 got_repo_get_gitconfig_remotes(&nremotes, &remotes, repo);
7943 for (i = 0; i < nremotes; i++) {
7944 if (strcmp(remotes[i].name, remote_name) == 0) {
7945 remote = &remotes[i];
7946 break;
7950 if (remote == NULL) {
7951 error = got_error_path(remote_name, GOT_ERR_NO_REMOTE);
7952 goto done;
7955 error = got_dial_parse_uri(&proto, &host, &port, &server_path,
7956 &repo_name, remote->fetch_url);
7957 if (error)
7958 goto done;
7960 if (strcmp(proto, "git") == 0) {
7961 #ifndef PROFILE
7962 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
7963 "sendfd dns inet unveil", NULL) == -1)
7964 err(1, "pledge");
7965 #endif
7966 } else if (strcmp(proto, "git+ssh") == 0 ||
7967 strcmp(proto, "ssh") == 0) {
7968 #ifndef PROFILE
7969 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
7970 "sendfd unveil", NULL) == -1)
7971 err(1, "pledge");
7972 #endif
7973 } else if (strcmp(proto, "http") == 0 ||
7974 strcmp(proto, "git+http") == 0) {
7975 error = got_error_path(proto, GOT_ERR_NOT_IMPL);
7976 goto done;
7977 } else {
7978 error = got_error_path(proto, GOT_ERR_BAD_PROTO);
7979 goto done;
7983 /*if (verbosity >= 0) {
7984 printf("Connecting to \"%s\" %s://%s%s%s%s%s\n",
7985 remote->name, proto, host,
7986 port ? ":" : "", port ? port : "",
7987 *server_path == '/' ? "" : "/", server_path);
7988 }*/
7991 * unveil(2) traverses exec(2); if an editor is used we have
7992 * to apply unveil after the log message has been written during
7993 * the callback.
7995 if (logmsg == NULL || strlen(logmsg) == 0)
7996 error = get_editor(&editor);
7997 else {
7998 error = got_dial_apply_unveil(proto);
7999 if (error)
8000 goto done;
8001 error = apply_unveil(got_repo_get_path(repo), 0,
8002 got_worktree_get_root_path(worktree));
8004 if (error)
8005 goto done;
8007 if (prepared_logmsg == NULL) {
8008 error = lookup_logmsg_ref(&merged_logmsg,
8009 argc > 0 ? &paths : NULL, &refs, worktree, repo);
8010 if (error)
8011 goto done;
8014 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
8015 if (error)
8016 goto done;
8018 cl_arg.editor = editor;
8019 cl_arg.cmdline_log = logmsg;
8020 cl_arg.prepared_log = prepared_logmsg;
8021 cl_arg.merged_log = merged_logmsg;
8022 cl_arg.non_interactive = non_interactive;
8023 cl_arg.worktree_path = got_worktree_get_root_path(worktree);
8024 cl_arg.repo_path = got_repo_get_path(repo);
8025 cl_arg.dial_proto = proto;
8026 error = got_worktree_cvg_commit(&id, worktree, &paths, author,
8027 committer, allow_bad_symlinks, show_diff, commit_conflicts,
8028 collect_commit_logmsg, &cl_arg, print_status, NULL, proto, host,
8029 port, server_path, verbosity, remote, check_cancelled, repo);
8030 if (error) {
8031 if (error->code != GOT_ERR_COMMIT_MSG_EMPTY &&
8032 cl_arg.logmsg_path != NULL)
8033 preserve_logmsg = 1;
8034 goto done;
8037 error = got_object_id_str(&id_str, id);
8038 if (error)
8039 goto done;
8040 printf("Created commit %s\n", id_str);
8042 TAILQ_FOREACH(re, &refs, entry) {
8043 error = got_ref_delete(re->ref, repo);
8044 if (error)
8045 goto done;
8048 done:
8049 if (preserve_logmsg) {
8050 fprintf(stderr, "%s: log message preserved in %s\n",
8051 getprogname(), cl_arg.logmsg_path);
8052 } else if (cl_arg.logmsg_path && unlink(cl_arg.logmsg_path) == -1 &&
8053 error == NULL)
8054 error = got_error_from_errno2("unlink", cl_arg.logmsg_path);
8055 free(cl_arg.logmsg_path);
8056 if (merged_logmsg && unlink(merged_logmsg) == -1 && error == NULL)
8057 error = got_error_from_errno2("unlink", merged_logmsg);
8058 free(merged_logmsg);
8059 if (repo) {
8060 const struct got_error *close_err = got_repo_close(repo);
8061 if (error == NULL)
8062 error = close_err;
8064 if (worktree)
8065 got_worktree_close(worktree);
8066 if (pack_fds) {
8067 const struct got_error *pack_err =
8068 got_repo_pack_fds_close(pack_fds);
8069 if (error == NULL)
8070 error = pack_err;
8072 got_ref_list_free(&refs);
8073 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
8074 free(cwd);
8075 free(id_str);
8076 free(gitconfig_path);
8077 free(editor);
8078 free(committer);
8079 free(prepared_logmsg);
8080 return error;
8084 * Print and if delete is set delete all ref_prefix references.
8085 * If wanted_ref is not NULL, only print or delete this reference.
8087 static const struct got_error *
8088 process_logmsg_refs(const char *ref_prefix, size_t prefix_len,
8089 const char *wanted_ref, int delete, struct got_worktree *worktree,
8090 struct got_repository *repo)
8092 const struct got_error *err;
8093 struct got_pathlist_head paths;
8094 struct got_reflist_head refs;
8095 struct got_reflist_entry *re;
8096 struct got_reflist_object_id_map *refs_idmap = NULL;
8097 struct got_commit_object *commit = NULL;
8098 struct got_object_id *id = NULL;
8099 const char *header_prefix;
8100 char *uuidstr = NULL;
8101 int found = 0;
8103 TAILQ_INIT(&refs);
8104 TAILQ_INIT(&paths);
8106 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, repo);
8107 if (err)
8108 goto done;
8110 err = got_reflist_object_id_map_create(&refs_idmap, &refs, repo);
8111 if (err)
8112 goto done;
8114 if (worktree != NULL) {
8115 err = got_worktree_get_uuid(&uuidstr, worktree);
8116 if (err)
8117 goto done;
8120 if (wanted_ref) {
8121 if (strncmp(wanted_ref, "refs/heads/", 11) == 0)
8122 wanted_ref += 11;
8125 if (strcmp(ref_prefix, GOT_WORKTREE_BACKOUT_REF_PREFIX) == 0)
8126 header_prefix = "backout";
8127 else
8128 header_prefix = "cherrypick";
8130 TAILQ_FOREACH(re, &refs, entry) {
8131 const char *refname, *wt;
8133 refname = got_ref_get_name(re->ref);
8135 err = check_cancelled(NULL);
8136 if (err)
8137 goto done;
8139 if (strncmp(refname, ref_prefix, prefix_len) == 0)
8140 refname += prefix_len + 1; /* skip '-' delimiter */
8141 else
8142 continue;
8144 wt = refname;
8146 if (worktree == NULL || strncmp(refname, uuidstr,
8147 GOT_WORKTREE_UUID_STRLEN) == 0)
8148 refname += GOT_WORKTREE_UUID_STRLEN + 1; /* skip '-' */
8149 else
8150 continue;
8152 err = got_repo_match_object_id(&id, NULL, refname,
8153 GOT_OBJ_TYPE_COMMIT, NULL, repo);
8154 if (err)
8155 goto done;
8157 err = got_object_open_as_commit(&commit, repo, id);
8158 if (err)
8159 goto done;
8161 if (wanted_ref)
8162 found = strncmp(wanted_ref, refname,
8163 strlen(wanted_ref)) == 0;
8164 if (wanted_ref && !found) {
8165 struct got_reflist_head *ci_refs;
8167 ci_refs = got_reflist_object_id_map_lookup(refs_idmap,
8168 id);
8170 if (ci_refs) {
8171 char *refs_str = NULL;
8172 char const *r = NULL;
8174 err = build_refs_str(&refs_str, ci_refs, id,
8175 repo, 1);
8176 if (err)
8177 goto done;
8179 r = refs_str;
8180 while (r) {
8181 if (strncmp(r, wanted_ref,
8182 strlen(wanted_ref)) == 0) {
8183 found = 1;
8184 break;
8186 r = strchr(r, ' ');
8187 if (r)
8188 ++r;
8190 free(refs_str);
8194 if (wanted_ref == NULL || found) {
8195 if (delete) {
8196 err = got_ref_delete(re->ref, repo);
8197 if (err)
8198 goto done;
8199 printf("Deleted: ");
8200 err = print_commit_oneline(commit, id, repo,
8201 refs_idmap);
8202 } else {
8204 * Print paths modified by commit to help
8205 * associate commits with worktree changes.
8207 err = get_changed_paths(&paths, commit,
8208 repo, NULL);
8209 if (err)
8210 goto done;
8212 err = print_commit(commit, id, repo, NULL,
8213 &paths, NULL, 0, 0, refs_idmap, NULL,
8214 header_prefix);
8215 got_pathlist_free(&paths,
8216 GOT_PATHLIST_FREE_ALL);
8218 if (worktree == NULL)
8219 printf("work tree: %.*s\n\n",
8220 GOT_WORKTREE_UUID_STRLEN, wt);
8222 if (err || found)
8223 goto done;
8226 got_object_commit_close(commit);
8227 commit = NULL;
8228 free(id);
8229 id = NULL;
8232 if (wanted_ref != NULL && !found)
8233 err = got_error_fmt(GOT_ERR_NOT_REF, "%s", wanted_ref);
8235 done:
8236 free(id);
8237 free(uuidstr);
8238 got_ref_list_free(&refs);
8239 got_pathlist_free(&paths, GOT_PATHLIST_FREE_ALL);
8240 if (refs_idmap)
8241 got_reflist_object_id_map_free(refs_idmap);
8242 if (commit)
8243 got_object_commit_close(commit);
8244 return err;
8248 * Create new temp "logmsg" ref of the backed-out or cherrypicked commit
8249 * identified by id for log messages to prepopulate the editor on commit.
8251 static const struct got_error *
8252 logmsg_ref(struct got_object_id *id, const char *prefix,
8253 struct got_worktree *worktree, struct got_repository *repo)
8255 const struct got_error *err = NULL;
8256 char *idstr, *ref = NULL, *refname = NULL;
8257 int histedit_in_progress;
8258 int rebase_in_progress, merge_in_progress;
8261 * Silenty refuse to create merge reference if any histedit, merge,
8262 * or rebase operation is in progress.
8264 err = got_worktree_histedit_in_progress(&histedit_in_progress,
8265 worktree);
8266 if (err)
8267 return err;
8268 if (histedit_in_progress)
8269 return NULL;
8271 err = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
8272 if (err)
8273 return err;
8274 if (rebase_in_progress)
8275 return NULL;
8277 err = got_worktree_merge_in_progress(&merge_in_progress, worktree,
8278 repo);
8279 if (err)
8280 return err;
8281 if (merge_in_progress)
8282 return NULL;
8284 err = got_object_id_str(&idstr, id);
8285 if (err)
8286 return err;
8288 err = got_worktree_get_logmsg_ref_name(&refname, worktree, prefix);
8289 if (err)
8290 goto done;
8292 if (asprintf(&ref, "%s-%s", refname, idstr) == -1) {
8293 err = got_error_from_errno("asprintf");
8294 goto done;
8297 err = create_ref(ref, got_worktree_get_base_commit_id(worktree),
8298 -1, repo);
8299 done:
8300 free(ref);
8301 free(idstr);
8302 free(refname);
8303 return err;
8306 __dead static void
8307 usage_cherrypick(void)
8309 fprintf(stderr, "usage: %s cherrypick [-lX] [commit-id]\n",
8310 getprogname());
8311 exit(1);
8314 static const struct got_error *
8315 cmd_cherrypick(int argc, char *argv[])
8317 const struct got_error *error = NULL;
8318 struct got_worktree *worktree = NULL;
8319 struct got_repository *repo = NULL;
8320 char *cwd = NULL, *commit_id_str = NULL;
8321 struct got_object_id *commit_id = NULL;
8322 struct got_commit_object *commit = NULL;
8323 struct got_object_qid *pid;
8324 int ch, list_refs = 0, remove_refs = 0;
8325 struct got_update_progress_arg upa;
8326 int *pack_fds = NULL;
8328 #ifndef PROFILE
8329 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
8330 "unveil", NULL) == -1)
8331 err(1, "pledge");
8332 #endif
8334 while ((ch = getopt(argc, argv, "lX")) != -1) {
8335 switch (ch) {
8336 case 'l':
8337 list_refs = 1;
8338 break;
8339 case 'X':
8340 remove_refs = 1;
8341 break;
8342 default:
8343 usage_cherrypick();
8344 /* NOTREACHED */
8348 argc -= optind;
8349 argv += optind;
8351 if (list_refs || remove_refs) {
8352 if (argc != 0 && argc != 1)
8353 usage_cherrypick();
8354 } else if (argc != 1)
8355 usage_cherrypick();
8356 if (list_refs && remove_refs)
8357 option_conflict('l', 'X');
8359 cwd = getcwd(NULL, 0);
8360 if (cwd == NULL) {
8361 error = got_error_from_errno("getcwd");
8362 goto done;
8365 error = got_repo_pack_fds_open(&pack_fds);
8366 if (error != NULL)
8367 goto done;
8369 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_CVG_DIR);
8370 if (error) {
8371 if (list_refs || remove_refs) {
8372 if (error->code != GOT_ERR_NOT_WORKTREE)
8373 goto done;
8374 } else {
8375 if (error->code == GOT_ERR_NOT_WORKTREE)
8376 error = wrap_not_worktree_error(error,
8377 "cherrypick", cwd);
8378 goto done;
8382 error = got_repo_open(&repo,
8383 worktree ? got_worktree_get_repo_path(worktree) : cwd,
8384 NULL, pack_fds);
8385 if (error != NULL)
8386 goto done;
8388 error = apply_unveil(got_repo_get_path(repo), 0,
8389 worktree ? got_worktree_get_root_path(worktree) : NULL);
8390 if (error)
8391 goto done;
8393 if (list_refs || remove_refs) {
8394 error = process_logmsg_refs(GOT_WORKTREE_CHERRYPICK_REF_PREFIX,
8395 GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN,
8396 argc == 1 ? argv[0] : NULL, remove_refs, worktree, repo);
8397 goto done;
8400 error = got_repo_match_object_id(&commit_id, NULL, argv[0],
8401 GOT_OBJ_TYPE_COMMIT, NULL, repo);
8402 if (error)
8403 goto done;
8404 error = got_object_id_str(&commit_id_str, commit_id);
8405 if (error)
8406 goto done;
8408 error = got_object_open_as_commit(&commit, repo, commit_id);
8409 if (error)
8410 goto done;
8411 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
8412 memset(&upa, 0, sizeof(upa));
8413 error = got_worktree_merge_files(worktree, pid ? &pid->id : NULL,
8414 commit_id, repo, update_progress, &upa, check_cancelled,
8415 NULL);
8416 if (error != NULL)
8417 goto done;
8419 if (upa.did_something) {
8420 error = logmsg_ref(commit_id,
8421 GOT_WORKTREE_CHERRYPICK_REF_PREFIX, worktree, repo);
8422 if (error)
8423 goto done;
8424 printf("Merged commit %s\n", commit_id_str);
8426 print_merge_progress_stats(&upa);
8427 done:
8428 free(cwd);
8429 if (commit)
8430 got_object_commit_close(commit);
8431 free(commit_id_str);
8432 if (worktree)
8433 got_worktree_close(worktree);
8434 if (repo) {
8435 const struct got_error *close_err = got_repo_close(repo);
8436 if (error == NULL)
8437 error = close_err;
8439 if (pack_fds) {
8440 const struct got_error *pack_err =
8441 got_repo_pack_fds_close(pack_fds);
8442 if (error == NULL)
8443 error = pack_err;
8446 return error;
8449 __dead static void
8450 usage_backout(void)
8452 fprintf(stderr, "usage: %s backout [-lX] [commit-id]\n", getprogname());
8453 exit(1);
8456 static const struct got_error *
8457 cmd_backout(int argc, char *argv[])
8459 const struct got_error *error = NULL;
8460 struct got_worktree *worktree = NULL;
8461 struct got_repository *repo = NULL;
8462 char *cwd = NULL, *commit_id_str = NULL;
8463 struct got_object_id *commit_id = NULL;
8464 struct got_commit_object *commit = NULL;
8465 struct got_object_qid *pid;
8466 int ch, list_refs = 0, remove_refs = 0;
8467 struct got_update_progress_arg upa;
8468 int *pack_fds = NULL;
8470 #ifndef PROFILE
8471 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
8472 "unveil", NULL) == -1)
8473 err(1, "pledge");
8474 #endif
8476 while ((ch = getopt(argc, argv, "lX")) != -1) {
8477 switch (ch) {
8478 case 'l':
8479 list_refs = 1;
8480 break;
8481 case 'X':
8482 remove_refs = 1;
8483 break;
8484 default:
8485 usage_backout();
8486 /* NOTREACHED */
8490 argc -= optind;
8491 argv += optind;
8493 if (list_refs || remove_refs) {
8494 if (argc != 0 && argc != 1)
8495 usage_backout();
8496 } else if (argc != 1)
8497 usage_backout();
8498 if (list_refs && remove_refs)
8499 option_conflict('l', 'X');
8501 cwd = getcwd(NULL, 0);
8502 if (cwd == NULL) {
8503 error = got_error_from_errno("getcwd");
8504 goto done;
8507 error = got_repo_pack_fds_open(&pack_fds);
8508 if (error != NULL)
8509 goto done;
8511 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_CVG_DIR);
8512 if (error) {
8513 if (list_refs || remove_refs) {
8514 if (error->code != GOT_ERR_NOT_WORKTREE)
8515 goto done;
8516 } else {
8517 if (error->code == GOT_ERR_NOT_WORKTREE)
8518 error = wrap_not_worktree_error(error,
8519 "backout", cwd);
8520 goto done;
8524 error = got_repo_open(&repo,
8525 worktree ? got_worktree_get_repo_path(worktree) : cwd,
8526 NULL, pack_fds);
8527 if (error != NULL)
8528 goto done;
8530 error = apply_unveil(got_repo_get_path(repo), 0,
8531 worktree ? got_worktree_get_root_path(worktree) : NULL);
8532 if (error)
8533 goto done;
8535 if (list_refs || remove_refs) {
8536 error = process_logmsg_refs(GOT_WORKTREE_BACKOUT_REF_PREFIX,
8537 GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN,
8538 argc == 1 ? argv[0] : NULL, remove_refs, worktree, repo);
8539 goto done;
8542 error = got_repo_match_object_id(&commit_id, NULL, argv[0],
8543 GOT_OBJ_TYPE_COMMIT, NULL, repo);
8544 if (error)
8545 goto done;
8546 error = got_object_id_str(&commit_id_str, commit_id);
8547 if (error)
8548 goto done;
8550 error = got_object_open_as_commit(&commit, repo, commit_id);
8551 if (error)
8552 goto done;
8553 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
8554 if (pid == NULL) {
8555 error = got_error(GOT_ERR_ROOT_COMMIT);
8556 goto done;
8559 memset(&upa, 0, sizeof(upa));
8560 error = got_worktree_merge_files(worktree, commit_id, &pid->id,
8561 repo, update_progress, &upa, check_cancelled, NULL);
8562 if (error != NULL)
8563 goto done;
8565 if (upa.did_something) {
8566 error = logmsg_ref(commit_id, GOT_WORKTREE_BACKOUT_REF_PREFIX,
8567 worktree, repo);
8568 if (error)
8569 goto done;
8570 printf("Backed out commit %s\n", commit_id_str);
8572 print_merge_progress_stats(&upa);
8573 done:
8574 free(cwd);
8575 if (commit)
8576 got_object_commit_close(commit);
8577 free(commit_id_str);
8578 if (worktree)
8579 got_worktree_close(worktree);
8580 if (repo) {
8581 const struct got_error *close_err = got_repo_close(repo);
8582 if (error == NULL)
8583 error = close_err;
8585 if (pack_fds) {
8586 const struct got_error *pack_err =
8587 got_repo_pack_fds_close(pack_fds);
8588 if (error == NULL)
8589 error = pack_err;
8591 return error;
8594 __dead static void
8595 usage_cat(void)
8597 fprintf(stderr, "usage: %s cat [-P] [-c commit] [-r repository-path] "
8598 "arg ...\n", getprogname());
8599 exit(1);
8602 static const struct got_error *
8603 cat_blob(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
8605 const struct got_error *err;
8606 struct got_blob_object *blob;
8607 int fd = -1;
8609 fd = got_opentempfd();
8610 if (fd == -1)
8611 return got_error_from_errno("got_opentempfd");
8613 err = got_object_open_as_blob(&blob, repo, id, 8192, fd);
8614 if (err)
8615 goto done;
8617 err = got_object_blob_dump_to_file(NULL, NULL, NULL, outfile, blob);
8618 done:
8619 if (fd != -1 && close(fd) == -1 && err == NULL)
8620 err = got_error_from_errno("close");
8621 if (blob)
8622 got_object_blob_close(blob);
8623 return err;
8626 static const struct got_error *
8627 cat_tree(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
8629 const struct got_error *err;
8630 struct got_tree_object *tree;
8631 int nentries, i;
8633 err = got_object_open_as_tree(&tree, repo, id);
8634 if (err)
8635 return err;
8637 nentries = got_object_tree_get_nentries(tree);
8638 for (i = 0; i < nentries; i++) {
8639 struct got_tree_entry *te;
8640 char *id_str;
8641 if (sigint_received || sigpipe_received)
8642 break;
8643 te = got_object_tree_get_entry(tree, i);
8644 err = got_object_id_str(&id_str, got_tree_entry_get_id(te));
8645 if (err)
8646 break;
8647 fprintf(outfile, "%s %.7o %s\n", id_str,
8648 got_tree_entry_get_mode(te),
8649 got_tree_entry_get_name(te));
8650 free(id_str);
8653 got_object_tree_close(tree);
8654 return err;
8657 static const struct got_error *
8658 cat_commit(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
8660 const struct got_error *err;
8661 struct got_commit_object *commit;
8662 const struct got_object_id_queue *parent_ids;
8663 struct got_object_qid *pid;
8664 char *id_str = NULL;
8665 const char *logmsg = NULL;
8666 char gmtoff[6];
8668 err = got_object_open_as_commit(&commit, repo, id);
8669 if (err)
8670 return err;
8672 err = got_object_id_str(&id_str, got_object_commit_get_tree_id(commit));
8673 if (err)
8674 goto done;
8676 fprintf(outfile, "%s%s\n", GOT_COMMIT_LABEL_TREE, id_str);
8677 parent_ids = got_object_commit_get_parent_ids(commit);
8678 fprintf(outfile, "numparents %d\n",
8679 got_object_commit_get_nparents(commit));
8680 STAILQ_FOREACH(pid, parent_ids, entry) {
8681 char *pid_str;
8682 err = got_object_id_str(&pid_str, &pid->id);
8683 if (err)
8684 goto done;
8685 fprintf(outfile, "%s%s\n", GOT_COMMIT_LABEL_PARENT, pid_str);
8686 free(pid_str);
8688 got_date_format_gmtoff(gmtoff, sizeof(gmtoff),
8689 got_object_commit_get_author_gmtoff(commit));
8690 fprintf(outfile, "%s%s %lld %s\n", GOT_COMMIT_LABEL_AUTHOR,
8691 got_object_commit_get_author(commit),
8692 (long long)got_object_commit_get_author_time(commit),
8693 gmtoff);
8695 got_date_format_gmtoff(gmtoff, sizeof(gmtoff),
8696 got_object_commit_get_committer_gmtoff(commit));
8697 fprintf(outfile, "%s%s %lld %s\n", GOT_COMMIT_LABEL_COMMITTER,
8698 got_object_commit_get_committer(commit),
8699 (long long)got_object_commit_get_committer_time(commit),
8700 gmtoff);
8702 logmsg = got_object_commit_get_logmsg_raw(commit);
8703 fprintf(outfile, "messagelen %zd\n", strlen(logmsg));
8704 fprintf(outfile, "%s", logmsg);
8705 done:
8706 free(id_str);
8707 got_object_commit_close(commit);
8708 return err;
8711 static const struct got_error *
8712 cat_tag(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
8714 const struct got_error *err;
8715 struct got_tag_object *tag;
8716 char *id_str = NULL;
8717 const char *tagmsg = NULL;
8718 char gmtoff[6];
8720 err = got_object_open_as_tag(&tag, repo, id);
8721 if (err)
8722 return err;
8724 err = got_object_id_str(&id_str, got_object_tag_get_object_id(tag));
8725 if (err)
8726 goto done;
8728 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_OBJECT, id_str);
8730 switch (got_object_tag_get_object_type(tag)) {
8731 case GOT_OBJ_TYPE_BLOB:
8732 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
8733 GOT_OBJ_LABEL_BLOB);
8734 break;
8735 case GOT_OBJ_TYPE_TREE:
8736 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
8737 GOT_OBJ_LABEL_TREE);
8738 break;
8739 case GOT_OBJ_TYPE_COMMIT:
8740 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
8741 GOT_OBJ_LABEL_COMMIT);
8742 break;
8743 case GOT_OBJ_TYPE_TAG:
8744 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
8745 GOT_OBJ_LABEL_TAG);
8746 break;
8747 default:
8748 break;
8751 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TAG,
8752 got_object_tag_get_name(tag));
8754 got_date_format_gmtoff(gmtoff, sizeof(gmtoff),
8755 got_object_tag_get_tagger_gmtoff(tag));
8756 fprintf(outfile, "%s%s %lld %s\n", GOT_TAG_LABEL_TAGGER,
8757 got_object_tag_get_tagger(tag),
8758 (long long)got_object_tag_get_tagger_time(tag),
8759 gmtoff);
8761 tagmsg = got_object_tag_get_message(tag);
8762 fprintf(outfile, "messagelen %zd\n", strlen(tagmsg));
8763 fprintf(outfile, "%s", tagmsg);
8764 done:
8765 free(id_str);
8766 got_object_tag_close(tag);
8767 return err;
8770 static const struct got_error *
8771 cmd_cat(int argc, char *argv[])
8773 const struct got_error *error;
8774 struct got_repository *repo = NULL;
8775 struct got_worktree *worktree = NULL;
8776 char *cwd = NULL, *repo_path = NULL, *label = NULL;
8777 const char *commit_id_str = NULL;
8778 struct got_object_id *id = NULL, *commit_id = NULL;
8779 struct got_commit_object *commit = NULL;
8780 int ch, obj_type, i, force_path = 0;
8781 struct got_reflist_head refs;
8782 int *pack_fds = NULL;
8784 TAILQ_INIT(&refs);
8786 #ifndef PROFILE
8787 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
8788 NULL) == -1)
8789 err(1, "pledge");
8790 #endif
8792 while ((ch = getopt(argc, argv, "c:Pr:")) != -1) {
8793 switch (ch) {
8794 case 'c':
8795 commit_id_str = optarg;
8796 break;
8797 case 'P':
8798 force_path = 1;
8799 break;
8800 case 'r':
8801 repo_path = realpath(optarg, NULL);
8802 if (repo_path == NULL)
8803 return got_error_from_errno2("realpath",
8804 optarg);
8805 got_path_strip_trailing_slashes(repo_path);
8806 break;
8807 default:
8808 usage_cat();
8809 /* NOTREACHED */
8813 argc -= optind;
8814 argv += optind;
8816 cwd = getcwd(NULL, 0);
8817 if (cwd == NULL) {
8818 error = got_error_from_errno("getcwd");
8819 goto done;
8822 error = got_repo_pack_fds_open(&pack_fds);
8823 if (error != NULL)
8824 goto done;
8826 if (repo_path == NULL) {
8827 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_CVG_DIR);
8828 if (error && error->code != GOT_ERR_NOT_WORKTREE)
8829 goto done;
8830 if (worktree) {
8831 repo_path = strdup(
8832 got_worktree_get_repo_path(worktree));
8833 if (repo_path == NULL) {
8834 error = got_error_from_errno("strdup");
8835 goto done;
8838 /* Release work tree lock. */
8839 got_worktree_close(worktree);
8840 worktree = NULL;
8844 if (repo_path == NULL) {
8845 repo_path = strdup(cwd);
8846 if (repo_path == NULL)
8847 return got_error_from_errno("strdup");
8850 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
8851 free(repo_path);
8852 if (error != NULL)
8853 goto done;
8855 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
8856 if (error)
8857 goto done;
8859 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
8860 if (error)
8861 goto done;
8863 if (commit_id_str == NULL)
8864 commit_id_str = GOT_REF_HEAD;
8865 error = got_repo_match_object_id(&commit_id, NULL,
8866 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
8867 if (error)
8868 goto done;
8870 error = got_object_open_as_commit(&commit, repo, commit_id);
8871 if (error)
8872 goto done;
8874 for (i = 0; i < argc; i++) {
8875 if (force_path) {
8876 error = got_object_id_by_path(&id, repo, commit,
8877 argv[i]);
8878 if (error)
8879 break;
8880 } else {
8881 error = got_repo_match_object_id(&id, &label, argv[i],
8882 GOT_OBJ_TYPE_ANY, NULL /* do not resolve tags */,
8883 repo);
8884 if (error) {
8885 if (error->code != GOT_ERR_BAD_OBJ_ID_STR &&
8886 error->code != GOT_ERR_NOT_REF)
8887 break;
8888 error = got_object_id_by_path(&id, repo,
8889 commit, argv[i]);
8890 if (error)
8891 break;
8895 error = got_object_get_type(&obj_type, repo, id);
8896 if (error)
8897 break;
8899 switch (obj_type) {
8900 case GOT_OBJ_TYPE_BLOB:
8901 error = cat_blob(id, repo, stdout);
8902 break;
8903 case GOT_OBJ_TYPE_TREE:
8904 error = cat_tree(id, repo, stdout);
8905 break;
8906 case GOT_OBJ_TYPE_COMMIT:
8907 error = cat_commit(id, repo, stdout);
8908 break;
8909 case GOT_OBJ_TYPE_TAG:
8910 error = cat_tag(id, repo, stdout);
8911 break;
8912 default:
8913 error = got_error(GOT_ERR_OBJ_TYPE);
8914 break;
8916 if (error)
8917 break;
8918 free(label);
8919 label = NULL;
8920 free(id);
8921 id = NULL;
8923 done:
8924 free(label);
8925 free(id);
8926 free(commit_id);
8927 if (commit)
8928 got_object_commit_close(commit);
8929 if (worktree)
8930 got_worktree_close(worktree);
8931 if (repo) {
8932 const struct got_error *close_err = got_repo_close(repo);
8933 if (error == NULL)
8934 error = close_err;
8936 if (pack_fds) {
8937 const struct got_error *pack_err =
8938 got_repo_pack_fds_close(pack_fds);
8939 if (error == NULL)
8940 error = pack_err;
8943 got_ref_list_free(&refs);
8944 return error;
8947 __dead static void
8948 usage_info(void)
8950 fprintf(stderr, "usage: %s info [path ...]\n",
8951 getprogname());
8952 exit(1);
8955 static const struct got_error *
8956 print_path_info(void *arg, const char *path, mode_t mode, time_t mtime,
8957 struct got_object_id *blob_id, struct got_object_id *staged_blob_id,
8958 struct got_object_id *commit_id)
8960 const struct got_error *err = NULL;
8961 char *id_str = NULL;
8962 char datebuf[128];
8963 struct tm mytm, *tm;
8964 struct got_pathlist_head *paths = arg;
8965 struct got_pathlist_entry *pe;
8968 * Clear error indication from any of the path arguments which
8969 * would cause this file index entry to be displayed.
8971 TAILQ_FOREACH(pe, paths, entry) {
8972 if (got_path_cmp(path, pe->path, strlen(path),
8973 pe->path_len) == 0 ||
8974 got_path_is_child(path, pe->path, pe->path_len))
8975 pe->data = NULL; /* no error */
8978 printf(GOT_COMMIT_SEP_STR);
8979 if (S_ISLNK(mode))
8980 printf("symlink: %s\n", path);
8981 else if (S_ISREG(mode)) {
8982 printf("file: %s\n", path);
8983 printf("mode: %o\n", mode & (S_IRWXU | S_IRWXG | S_IRWXO));
8984 } else if (S_ISDIR(mode))
8985 printf("directory: %s\n", path);
8986 else
8987 printf("something: %s\n", path);
8989 tm = localtime_r(&mtime, &mytm);
8990 if (tm == NULL)
8991 return NULL;
8992 if (strftime(datebuf, sizeof(datebuf), "%c %Z", tm) == 0)
8993 return got_error(GOT_ERR_NO_SPACE);
8994 printf("timestamp: %s\n", datebuf);
8996 if (blob_id) {
8997 err = got_object_id_str(&id_str, blob_id);
8998 if (err)
8999 return err;
9000 printf("based on blob: %s\n", id_str);
9001 free(id_str);
9004 if (staged_blob_id) {
9005 err = got_object_id_str(&id_str, staged_blob_id);
9006 if (err)
9007 return err;
9008 printf("based on staged blob: %s\n", id_str);
9009 free(id_str);
9012 if (commit_id) {
9013 err = got_object_id_str(&id_str, commit_id);
9014 if (err)
9015 return err;
9016 printf("based on commit: %s\n", id_str);
9017 free(id_str);
9020 return NULL;
9023 static const struct got_error *
9024 cmd_info(int argc, char *argv[])
9026 const struct got_error *error = NULL;
9027 struct got_worktree *worktree = NULL;
9028 char *cwd = NULL, *id_str = NULL;
9029 struct got_pathlist_head paths;
9030 char *uuidstr = NULL;
9031 int ch, show_files = 0;
9033 TAILQ_INIT(&paths);
9035 #ifndef PROFILE
9036 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
9037 NULL) == -1)
9038 err(1, "pledge");
9039 #endif
9041 while ((ch = getopt(argc, argv, "")) != -1) {
9042 switch (ch) {
9043 default:
9044 usage_info();
9045 /* NOTREACHED */
9049 argc -= optind;
9050 argv += optind;
9052 cwd = getcwd(NULL, 0);
9053 if (cwd == NULL) {
9054 error = got_error_from_errno("getcwd");
9055 goto done;
9058 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_CVG_DIR);
9059 if (error) {
9060 if (error->code == GOT_ERR_NOT_WORKTREE)
9061 error = wrap_not_worktree_error(error, "info", cwd);
9062 goto done;
9065 #ifndef PROFILE
9066 /* Remove "wpath cpath proc exec sendfd" promises. */
9067 if (pledge("stdio rpath flock unveil", NULL) == -1)
9068 err(1, "pledge");
9069 #endif
9070 error = apply_unveil(NULL, 0, got_worktree_get_root_path(worktree));
9071 if (error)
9072 goto done;
9074 if (argc >= 1) {
9075 error = get_worktree_paths_from_argv(&paths, argc, argv,
9076 worktree);
9077 if (error)
9078 goto done;
9079 show_files = 1;
9082 error = got_object_id_str(&id_str,
9083 got_worktree_get_base_commit_id(worktree));
9084 if (error)
9085 goto done;
9087 error = got_worktree_get_uuid(&uuidstr, worktree);
9088 if (error)
9089 goto done;
9091 printf("work tree: %s\n", got_worktree_get_root_path(worktree));
9092 printf("work tree base commit: %s\n", id_str);
9093 printf("work tree path prefix: %s\n",
9094 got_worktree_get_path_prefix(worktree));
9095 printf("work tree branch reference: %s\n",
9096 got_worktree_get_head_ref_name(worktree));
9097 printf("work tree UUID: %s\n", uuidstr);
9098 printf("repository: %s\n", got_worktree_get_repo_path(worktree));
9100 if (show_files) {
9101 struct got_pathlist_entry *pe;
9102 TAILQ_FOREACH(pe, &paths, entry) {
9103 if (pe->path_len == 0)
9104 continue;
9106 * Assume this path will fail. This will be corrected
9107 * in print_path_info() in case the path does suceeed.
9109 pe->data = (void *)got_error(GOT_ERR_BAD_PATH);
9111 error = got_worktree_path_info(worktree, &paths,
9112 print_path_info, &paths, check_cancelled, NULL);
9113 if (error)
9114 goto done;
9115 TAILQ_FOREACH(pe, &paths, entry) {
9116 if (pe->data != NULL) {
9117 const struct got_error *perr;
9119 perr = pe->data;
9120 error = got_error_fmt(perr->code, "%s",
9121 pe->path);
9122 break;
9126 done:
9127 if (worktree)
9128 got_worktree_close(worktree);
9129 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
9130 free(cwd);
9131 free(id_str);
9132 free(uuidstr);
9133 return error;