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), "%F ", &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), "%F", &tm) == 0) {
4993 err = got_error(GOT_ERR_NO_SPACE);
4994 goto done;
4996 bline->annotated = 1;
4998 /* Print lines annotated so far. */
4999 bline = &a->lines[a->lineno_cur - 1];
5000 if (!bline->annotated)
5001 goto done;
5003 offset = a->line_offsets[a->lineno_cur - 1];
5004 if (fseeko(a->f, offset, SEEK_SET) == -1) {
5005 err = got_error_from_errno("fseeko");
5006 goto done;
5009 while (a->lineno_cur <= a->nlines && bline->annotated) {
5010 char *smallerthan, *at, *nl, *committer;
5011 size_t len;
5013 if (getline(&line, &linesize, a->f) == -1) {
5014 if (ferror(a->f))
5015 err = got_error_from_errno("getline");
5016 break;
5019 committer = bline->committer;
5020 smallerthan = strchr(committer, '<');
5021 if (smallerthan && smallerthan[1] != '\0')
5022 committer = smallerthan + 1;
5023 at = strchr(committer, '@');
5024 if (at)
5025 *at = '\0';
5026 len = strlen(committer);
5027 if (len >= 9)
5028 committer[8] = '\0';
5030 nl = strchr(line, '\n');
5031 if (nl)
5032 *nl = '\0';
5033 printf("%.*d) %.8s %s %-8s %s\n", a->nlines_prec, a->lineno_cur,
5034 bline->id_str, bline->datebuf, committer, line);
5036 a->lineno_cur++;
5037 bline = &a->lines[a->lineno_cur - 1];
5039 done:
5040 free(line);
5041 return err;
5044 static const struct got_error *
5045 cmd_blame(int argc, char *argv[])
5047 const struct got_error *error;
5048 struct got_repository *repo = NULL;
5049 struct got_worktree *worktree = NULL;
5050 char *path, *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
5051 char *link_target = NULL;
5052 struct got_object_id *obj_id = NULL;
5053 struct got_object_id *commit_id = NULL;
5054 struct got_commit_object *commit = NULL;
5055 struct got_blob_object *blob = NULL;
5056 char *commit_id_str = NULL;
5057 struct blame_cb_args bca;
5058 int ch, obj_type, i, fd1 = -1, fd2 = -1, fd3 = -1;
5059 off_t filesize;
5060 int *pack_fds = NULL;
5061 FILE *f1 = NULL, *f2 = NULL;
5063 fd1 = got_opentempfd();
5064 if (fd1 == -1)
5065 return got_error_from_errno("got_opentempfd");
5067 memset(&bca, 0, sizeof(bca));
5069 #ifndef PROFILE
5070 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
5071 NULL) == -1)
5072 err(1, "pledge");
5073 #endif
5075 while ((ch = getopt(argc, argv, "c:r:")) != -1) {
5076 switch (ch) {
5077 case 'c':
5078 commit_id_str = optarg;
5079 break;
5080 case 'r':
5081 repo_path = realpath(optarg, NULL);
5082 if (repo_path == NULL)
5083 return got_error_from_errno2("realpath",
5084 optarg);
5085 got_path_strip_trailing_slashes(repo_path);
5086 break;
5087 default:
5088 usage_blame();
5089 /* NOTREACHED */
5093 argc -= optind;
5094 argv += optind;
5096 if (argc == 1)
5097 path = argv[0];
5098 else
5099 usage_blame();
5101 cwd = getcwd(NULL, 0);
5102 if (cwd == NULL) {
5103 error = got_error_from_errno("getcwd");
5104 goto done;
5107 error = got_repo_pack_fds_open(&pack_fds);
5108 if (error != NULL)
5109 goto done;
5111 if (repo_path == NULL) {
5112 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_CVG_DIR);
5113 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5114 goto done;
5115 else
5116 error = NULL;
5117 if (worktree) {
5118 repo_path =
5119 strdup(got_worktree_get_repo_path(worktree));
5120 if (repo_path == NULL) {
5121 error = got_error_from_errno("strdup");
5122 if (error)
5123 goto done;
5125 } else {
5126 repo_path = strdup(cwd);
5127 if (repo_path == NULL) {
5128 error = got_error_from_errno("strdup");
5129 goto done;
5134 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
5135 if (error != NULL)
5136 goto done;
5138 if (worktree) {
5139 const char *prefix = got_worktree_get_path_prefix(worktree);
5140 char *p;
5142 error = got_worktree_resolve_path(&p, worktree, path);
5143 if (error)
5144 goto done;
5145 if (asprintf(&in_repo_path, "%s%s%s", prefix,
5146 (p[0] != '\0' && !got_path_is_root_dir(prefix)) ? "/" : "",
5147 p) == -1) {
5148 error = got_error_from_errno("asprintf");
5149 free(p);
5150 goto done;
5152 free(p);
5153 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5154 } else {
5155 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5156 if (error)
5157 goto done;
5158 error = got_repo_map_path(&in_repo_path, repo, path);
5160 if (error)
5161 goto done;
5163 if (commit_id_str == NULL) {
5164 struct got_reference *head_ref;
5165 error = got_ref_open(&head_ref, repo, worktree ?
5166 got_worktree_get_head_ref_name(worktree) : GOT_REF_HEAD, 0);
5167 if (error != NULL)
5168 goto done;
5169 error = got_ref_resolve(&commit_id, repo, head_ref);
5170 got_ref_close(head_ref);
5171 if (error != NULL)
5172 goto done;
5173 } else {
5174 struct got_reflist_head refs;
5175 TAILQ_INIT(&refs);
5176 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
5177 NULL);
5178 if (error)
5179 goto done;
5180 error = got_repo_match_object_id(&commit_id, NULL,
5181 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
5182 got_ref_list_free(&refs);
5183 if (error)
5184 goto done;
5187 if (worktree) {
5188 /* Release work tree lock. */
5189 got_worktree_close(worktree);
5190 worktree = NULL;
5193 error = got_object_open_as_commit(&commit, repo, commit_id);
5194 if (error)
5195 goto done;
5197 error = got_object_resolve_symlinks(&link_target, in_repo_path,
5198 commit, repo);
5199 if (error)
5200 goto done;
5202 error = got_object_id_by_path(&obj_id, repo, commit,
5203 link_target ? link_target : in_repo_path);
5204 if (error)
5205 goto done;
5207 error = got_object_get_type(&obj_type, repo, obj_id);
5208 if (error)
5209 goto done;
5211 if (obj_type != GOT_OBJ_TYPE_BLOB) {
5212 error = got_error_path(link_target ? link_target : in_repo_path,
5213 GOT_ERR_OBJ_TYPE);
5214 goto done;
5217 error = got_object_open_as_blob(&blob, repo, obj_id, 8192, fd1);
5218 if (error)
5219 goto done;
5220 bca.f = got_opentemp();
5221 if (bca.f == NULL) {
5222 error = got_error_from_errno("got_opentemp");
5223 goto done;
5225 error = got_object_blob_dump_to_file(&filesize, &bca.nlines,
5226 &bca.line_offsets, bca.f, blob);
5227 if (error || bca.nlines == 0)
5228 goto done;
5230 /* Don't include \n at EOF in the blame line count. */
5231 if (bca.line_offsets[bca.nlines - 1] == filesize)
5232 bca.nlines--;
5234 bca.lines = calloc(bca.nlines, sizeof(*bca.lines));
5235 if (bca.lines == NULL) {
5236 error = got_error_from_errno("calloc");
5237 goto done;
5239 bca.lineno_cur = 1;
5240 bca.nlines_prec = 0;
5241 i = bca.nlines;
5242 while (i > 0) {
5243 i /= 10;
5244 bca.nlines_prec++;
5246 bca.repo = repo;
5248 fd2 = got_opentempfd();
5249 if (fd2 == -1) {
5250 error = got_error_from_errno("got_opentempfd");
5251 goto done;
5253 fd3 = got_opentempfd();
5254 if (fd3 == -1) {
5255 error = got_error_from_errno("got_opentempfd");
5256 goto done;
5258 f1 = got_opentemp();
5259 if (f1 == NULL) {
5260 error = got_error_from_errno("got_opentemp");
5261 goto done;
5263 f2 = got_opentemp();
5264 if (f2 == NULL) {
5265 error = got_error_from_errno("got_opentemp");
5266 goto done;
5268 error = got_blame(link_target ? link_target : in_repo_path, commit_id,
5269 repo, GOT_DIFF_ALGORITHM_PATIENCE, blame_cb, &bca,
5270 check_cancelled, NULL, fd2, fd3, f1, f2);
5271 done:
5272 free(in_repo_path);
5273 free(link_target);
5274 free(repo_path);
5275 free(cwd);
5276 free(commit_id);
5277 free(obj_id);
5278 if (commit)
5279 got_object_commit_close(commit);
5281 if (fd1 != -1 && close(fd1) == -1 && error == NULL)
5282 error = got_error_from_errno("close");
5283 if (fd2 != -1 && close(fd2) == -1 && error == NULL)
5284 error = got_error_from_errno("close");
5285 if (fd3 != -1 && close(fd3) == -1 && error == NULL)
5286 error = got_error_from_errno("close");
5287 if (f1 && fclose(f1) == EOF && error == NULL)
5288 error = got_error_from_errno("fclose");
5289 if (f2 && fclose(f2) == EOF && error == NULL)
5290 error = got_error_from_errno("fclose");
5292 if (blob)
5293 got_object_blob_close(blob);
5294 if (worktree)
5295 got_worktree_close(worktree);
5296 if (repo) {
5297 const struct got_error *close_err = got_repo_close(repo);
5298 if (error == NULL)
5299 error = close_err;
5301 if (pack_fds) {
5302 const struct got_error *pack_err =
5303 got_repo_pack_fds_close(pack_fds);
5304 if (error == NULL)
5305 error = pack_err;
5307 if (bca.lines) {
5308 for (i = 0; i < bca.nlines; i++) {
5309 struct blame_line *bline = &bca.lines[i];
5310 free(bline->id_str);
5311 free(bline->committer);
5313 free(bca.lines);
5315 free(bca.line_offsets);
5316 if (bca.f && fclose(bca.f) == EOF && error == NULL)
5317 error = got_error_from_errno("fclose");
5318 return error;
5321 __dead static void
5322 usage_tree(void)
5324 fprintf(stderr, "usage: %s tree [-iR] [-c commit] [-r repository-path] "
5325 "[path]\n", getprogname());
5326 exit(1);
5329 static const struct got_error *
5330 print_entry(struct got_tree_entry *te, const char *id, const char *path,
5331 const char *root_path, struct got_repository *repo)
5333 const struct got_error *err = NULL;
5334 int is_root_path = (strcmp(path, root_path) == 0);
5335 const char *modestr = "";
5336 mode_t mode = got_tree_entry_get_mode(te);
5337 char *link_target = NULL;
5339 path += strlen(root_path);
5340 while (path[0] == '/')
5341 path++;
5343 if (got_object_tree_entry_is_submodule(te))
5344 modestr = "$";
5345 else if (S_ISLNK(mode)) {
5346 int i;
5348 err = got_tree_entry_get_symlink_target(&link_target, te, repo);
5349 if (err)
5350 return err;
5351 for (i = 0; link_target[i] != '\0'; i++) {
5352 if (!isprint((unsigned char)link_target[i]))
5353 link_target[i] = '?';
5356 modestr = "@";
5358 else if (S_ISDIR(mode))
5359 modestr = "/";
5360 else if (mode & S_IXUSR)
5361 modestr = "*";
5363 printf("%s%s%s%s%s%s%s\n", id ? id : "", path,
5364 is_root_path ? "" : "/", got_tree_entry_get_name(te), modestr,
5365 link_target ? " -> ": "", link_target ? link_target : "");
5367 free(link_target);
5368 return NULL;
5371 static const struct got_error *
5372 print_tree(const char *path, struct got_commit_object *commit,
5373 int show_ids, int recurse, const char *root_path,
5374 struct got_repository *repo)
5376 const struct got_error *err = NULL;
5377 struct got_object_id *tree_id = NULL;
5378 struct got_tree_object *tree = NULL;
5379 int nentries, i;
5381 err = got_object_id_by_path(&tree_id, repo, commit, path);
5382 if (err)
5383 goto done;
5385 err = got_object_open_as_tree(&tree, repo, tree_id);
5386 if (err)
5387 goto done;
5388 nentries = got_object_tree_get_nentries(tree);
5389 for (i = 0; i < nentries; i++) {
5390 struct got_tree_entry *te;
5391 char *id = NULL;
5393 if (sigint_received || sigpipe_received)
5394 break;
5396 te = got_object_tree_get_entry(tree, i);
5397 if (show_ids) {
5398 char *id_str;
5399 err = got_object_id_str(&id_str,
5400 got_tree_entry_get_id(te));
5401 if (err)
5402 goto done;
5403 if (asprintf(&id, "%s ", id_str) == -1) {
5404 err = got_error_from_errno("asprintf");
5405 free(id_str);
5406 goto done;
5408 free(id_str);
5410 err = print_entry(te, id, path, root_path, repo);
5411 free(id);
5412 if (err)
5413 goto done;
5415 if (recurse && S_ISDIR(got_tree_entry_get_mode(te))) {
5416 char *child_path;
5417 if (asprintf(&child_path, "%s%s%s", path,
5418 path[0] == '/' && path[1] == '\0' ? "" : "/",
5419 got_tree_entry_get_name(te)) == -1) {
5420 err = got_error_from_errno("asprintf");
5421 goto done;
5423 err = print_tree(child_path, commit, show_ids, 1,
5424 root_path, repo);
5425 free(child_path);
5426 if (err)
5427 goto done;
5430 done:
5431 if (tree)
5432 got_object_tree_close(tree);
5433 free(tree_id);
5434 return err;
5437 static const struct got_error *
5438 cmd_tree(int argc, char *argv[])
5440 const struct got_error *error;
5441 struct got_repository *repo = NULL;
5442 struct got_worktree *worktree = NULL;
5443 const char *path, *refname = NULL;
5444 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
5445 struct got_object_id *commit_id = NULL;
5446 struct got_commit_object *commit = NULL;
5447 char *commit_id_str = NULL;
5448 int show_ids = 0, recurse = 0;
5449 int ch;
5450 int *pack_fds = NULL;
5452 #ifndef PROFILE
5453 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
5454 NULL) == -1)
5455 err(1, "pledge");
5456 #endif
5458 while ((ch = getopt(argc, argv, "c:iRr:")) != -1) {
5459 switch (ch) {
5460 case 'c':
5461 commit_id_str = optarg;
5462 break;
5463 case 'i':
5464 show_ids = 1;
5465 break;
5466 case 'R':
5467 recurse = 1;
5468 break;
5469 case 'r':
5470 repo_path = realpath(optarg, NULL);
5471 if (repo_path == NULL)
5472 return got_error_from_errno2("realpath",
5473 optarg);
5474 got_path_strip_trailing_slashes(repo_path);
5475 break;
5476 default:
5477 usage_tree();
5478 /* NOTREACHED */
5482 argc -= optind;
5483 argv += optind;
5485 if (argc == 1)
5486 path = argv[0];
5487 else if (argc > 1)
5488 usage_tree();
5489 else
5490 path = NULL;
5492 cwd = getcwd(NULL, 0);
5493 if (cwd == NULL) {
5494 error = got_error_from_errno("getcwd");
5495 goto done;
5498 error = got_repo_pack_fds_open(&pack_fds);
5499 if (error != NULL)
5500 goto done;
5502 if (repo_path == NULL) {
5503 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_CVG_DIR);
5504 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5505 goto done;
5506 else
5507 error = NULL;
5508 if (worktree) {
5509 repo_path =
5510 strdup(got_worktree_get_repo_path(worktree));
5511 if (repo_path == NULL)
5512 error = got_error_from_errno("strdup");
5513 if (error)
5514 goto done;
5515 } else {
5516 repo_path = strdup(cwd);
5517 if (repo_path == NULL) {
5518 error = got_error_from_errno("strdup");
5519 goto done;
5524 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
5525 if (error != NULL)
5526 goto done;
5528 if (worktree) {
5529 const char *prefix = got_worktree_get_path_prefix(worktree);
5530 char *p;
5532 if (path == NULL || got_path_is_root_dir(path))
5533 path = "";
5534 error = got_worktree_resolve_path(&p, worktree, path);
5535 if (error)
5536 goto done;
5537 if (asprintf(&in_repo_path, "%s%s%s", prefix,
5538 (p[0] != '\0' && !got_path_is_root_dir(prefix)) ? "/" : "",
5539 p) == -1) {
5540 error = got_error_from_errno("asprintf");
5541 free(p);
5542 goto done;
5544 free(p);
5545 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5546 if (error)
5547 goto done;
5548 } else {
5549 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5550 if (error)
5551 goto done;
5552 if (path == NULL)
5553 path = "/";
5554 error = got_repo_map_path(&in_repo_path, repo, path);
5555 if (error != NULL)
5556 goto done;
5559 if (commit_id_str == NULL) {
5560 struct got_reference *head_ref;
5561 if (worktree)
5562 refname = got_worktree_get_head_ref_name(worktree);
5563 else
5564 refname = GOT_REF_HEAD;
5565 error = got_ref_open(&head_ref, repo, refname, 0);
5566 if (error != NULL)
5567 goto done;
5568 error = got_ref_resolve(&commit_id, repo, head_ref);
5569 got_ref_close(head_ref);
5570 if (error != NULL)
5571 goto done;
5572 } else {
5573 struct got_reflist_head refs;
5574 TAILQ_INIT(&refs);
5575 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
5576 NULL);
5577 if (error)
5578 goto done;
5579 error = got_repo_match_object_id(&commit_id, NULL,
5580 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
5581 got_ref_list_free(&refs);
5582 if (error)
5583 goto done;
5586 if (worktree) {
5587 /* Release work tree lock. */
5588 got_worktree_close(worktree);
5589 worktree = NULL;
5592 error = got_object_open_as_commit(&commit, repo, commit_id);
5593 if (error)
5594 goto done;
5596 error = print_tree(in_repo_path, commit, show_ids, recurse,
5597 in_repo_path, repo);
5598 done:
5599 free(in_repo_path);
5600 free(repo_path);
5601 free(cwd);
5602 free(commit_id);
5603 if (commit)
5604 got_object_commit_close(commit);
5605 if (worktree)
5606 got_worktree_close(worktree);
5607 if (repo) {
5608 const struct got_error *close_err = got_repo_close(repo);
5609 if (error == NULL)
5610 error = close_err;
5612 if (pack_fds) {
5613 const struct got_error *pack_err =
5614 got_repo_pack_fds_close(pack_fds);
5615 if (error == NULL)
5616 error = pack_err;
5618 return error;
5621 __dead static void
5622 usage_status(void)
5624 fprintf(stderr, "usage: %s status [-I] [-S status-codes] "
5625 "[-s status-codes] [path ...]\n", getprogname());
5626 exit(1);
5629 struct got_status_arg {
5630 char *status_codes;
5631 int suppress;
5634 static const struct got_error *
5635 print_status(void *arg, unsigned char status, unsigned char staged_status,
5636 const char *path, struct got_object_id *blob_id,
5637 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
5638 int dirfd, const char *de_name)
5640 struct got_status_arg *st = arg;
5642 if (status == staged_status && (status == GOT_STATUS_DELETE))
5643 status = GOT_STATUS_NO_CHANGE;
5644 if (st != NULL && st->status_codes) {
5645 size_t ncodes = strlen(st->status_codes);
5646 int i, j = 0;
5648 for (i = 0; i < ncodes ; i++) {
5649 if (st->suppress) {
5650 if (status == st->status_codes[i] ||
5651 staged_status == st->status_codes[i]) {
5652 j++;
5653 continue;
5655 } else {
5656 if (status == st->status_codes[i] ||
5657 staged_status == st->status_codes[i])
5658 break;
5662 if (st->suppress && j == 0)
5663 goto print;
5665 if (i == ncodes)
5666 return NULL;
5668 print:
5669 printf("%c%c %s\n", status, staged_status, path);
5670 return NULL;
5673 static const struct got_error *
5674 cmd_status(int argc, char *argv[])
5676 const struct got_error *error = NULL;
5677 struct got_repository *repo = NULL;
5678 struct got_worktree *worktree = NULL;
5679 struct got_status_arg st;
5680 char *cwd = NULL;
5681 struct got_pathlist_head paths;
5682 int ch, i, no_ignores = 0;
5683 int *pack_fds = NULL;
5685 TAILQ_INIT(&paths);
5687 memset(&st, 0, sizeof(st));
5688 st.status_codes = NULL;
5689 st.suppress = 0;
5691 #ifndef PROFILE
5692 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
5693 NULL) == -1)
5694 err(1, "pledge");
5695 #endif
5697 while ((ch = getopt(argc, argv, "IS:s:")) != -1) {
5698 switch (ch) {
5699 case 'I':
5700 no_ignores = 1;
5701 break;
5702 case 'S':
5703 if (st.status_codes != NULL && st.suppress == 0)
5704 option_conflict('S', 's');
5705 st.suppress = 1;
5706 /* fallthrough */
5707 case 's':
5708 for (i = 0; optarg[i] != '\0'; i++) {
5709 switch (optarg[i]) {
5710 case GOT_STATUS_MODIFY:
5711 case GOT_STATUS_ADD:
5712 case GOT_STATUS_DELETE:
5713 case GOT_STATUS_CONFLICT:
5714 case GOT_STATUS_MISSING:
5715 case GOT_STATUS_OBSTRUCTED:
5716 case GOT_STATUS_UNVERSIONED:
5717 case GOT_STATUS_MODE_CHANGE:
5718 case GOT_STATUS_NONEXISTENT:
5719 break;
5720 default:
5721 errx(1, "invalid status code '%c'",
5722 optarg[i]);
5725 if (ch == 's' && st.suppress)
5726 option_conflict('s', 'S');
5727 st.status_codes = optarg;
5728 break;
5729 default:
5730 usage_status();
5731 /* NOTREACHED */
5735 argc -= optind;
5736 argv += optind;
5738 cwd = getcwd(NULL, 0);
5739 if (cwd == NULL) {
5740 error = got_error_from_errno("getcwd");
5741 goto done;
5744 error = got_repo_pack_fds_open(&pack_fds);
5745 if (error != NULL)
5746 goto done;
5748 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_CVG_DIR);
5749 if (error) {
5750 if (error->code == GOT_ERR_NOT_WORKTREE)
5751 error = wrap_not_worktree_error(error, "status", cwd);
5752 goto done;
5755 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
5756 NULL, pack_fds);
5757 if (error != NULL)
5758 goto done;
5760 error = apply_unveil(got_repo_get_path(repo), 1,
5761 got_worktree_get_root_path(worktree));
5762 if (error)
5763 goto done;
5765 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
5766 if (error)
5767 goto done;
5769 error = got_worktree_status(worktree, &paths, repo, no_ignores,
5770 print_status, &st, check_cancelled, NULL);
5771 done:
5772 if (pack_fds) {
5773 const struct got_error *pack_err =
5774 got_repo_pack_fds_close(pack_fds);
5775 if (error == NULL)
5776 error = pack_err;
5778 if (repo) {
5779 const struct got_error *close_err = got_repo_close(repo);
5780 if (error == NULL)
5781 error = close_err;
5784 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
5785 free(cwd);
5786 return error;
5789 __dead static void
5790 usage_tag(void)
5792 fprintf(stderr, "usage: %s tag [-lVv] [-c commit] [-m message] "
5793 "[-r repository-path] [-s signer-id] name\n", getprogname());
5794 exit(1);
5797 #if 0
5798 static const struct got_error *
5799 sort_tags(struct got_reflist_head *sorted, struct got_reflist_head *tags)
5801 const struct got_error *err = NULL;
5802 struct got_reflist_entry *re, *se, *new;
5803 struct got_object_id *re_id, *se_id;
5804 struct got_tag_object *re_tag, *se_tag;
5805 time_t re_time, se_time;
5807 STAILQ_FOREACH(re, tags, entry) {
5808 se = STAILQ_FIRST(sorted);
5809 if (se == NULL) {
5810 err = got_reflist_entry_dup(&new, re);
5811 if (err)
5812 return err;
5813 STAILQ_INSERT_HEAD(sorted, new, entry);
5814 continue;
5815 } else {
5816 err = got_ref_resolve(&re_id, repo, re->ref);
5817 if (err)
5818 break;
5819 err = got_object_open_as_tag(&re_tag, repo, re_id);
5820 free(re_id);
5821 if (err)
5822 break;
5823 re_time = got_object_tag_get_tagger_time(re_tag);
5824 got_object_tag_close(re_tag);
5827 while (se) {
5828 err = got_ref_resolve(&se_id, repo, re->ref);
5829 if (err)
5830 break;
5831 err = got_object_open_as_tag(&se_tag, repo, se_id);
5832 free(se_id);
5833 if (err)
5834 break;
5835 se_time = got_object_tag_get_tagger_time(se_tag);
5836 got_object_tag_close(se_tag);
5838 if (se_time > re_time) {
5839 err = got_reflist_entry_dup(&new, re);
5840 if (err)
5841 return err;
5842 STAILQ_INSERT_AFTER(sorted, se, new, entry);
5843 break;
5845 se = STAILQ_NEXT(se, entry);
5846 continue;
5849 done:
5850 return err;
5852 #endif
5854 static const struct got_error *
5855 get_tag_refname(char **refname, const char *tag_name)
5857 const struct got_error *err;
5859 if (strncmp("refs/tags/", tag_name, 10) == 0) {
5860 *refname = strdup(tag_name);
5861 if (*refname == NULL)
5862 return got_error_from_errno("strdup");
5863 } else if (asprintf(refname, "refs/tags/%s", tag_name) == -1) {
5864 err = got_error_from_errno("asprintf");
5865 *refname = NULL;
5866 return err;
5869 return NULL;
5872 static const struct got_error *
5873 list_tags(struct got_repository *repo, const char *tag_name, int verify_tags,
5874 const char *allowed_signers, const char *revoked_signers, int verbosity)
5876 static const struct got_error *err = NULL;
5877 struct got_reflist_head refs;
5878 struct got_reflist_entry *re;
5879 char *wanted_refname = NULL;
5880 int bad_sigs = 0;
5882 TAILQ_INIT(&refs);
5884 err = got_ref_list(&refs, repo, "refs/tags", got_ref_cmp_tags, repo);
5885 if (err)
5886 return err;
5888 if (tag_name) {
5889 struct got_reference *ref;
5890 err = get_tag_refname(&wanted_refname, tag_name);
5891 if (err)
5892 goto done;
5893 /* Wanted tag reference should exist. */
5894 err = got_ref_open(&ref, repo, wanted_refname, 0);
5895 if (err)
5896 goto done;
5897 got_ref_close(ref);
5900 TAILQ_FOREACH(re, &refs, entry) {
5901 const char *refname;
5902 char *refstr, *tagmsg0, *tagmsg, *line, *id_str, *datestr;
5903 char datebuf[26];
5904 const char *tagger, *ssh_sig = NULL;
5905 char *sig_msg = NULL;
5906 time_t tagger_time;
5907 struct got_object_id *id;
5908 struct got_tag_object *tag;
5909 struct got_commit_object *commit = NULL;
5911 refname = got_ref_get_name(re->ref);
5912 if (strncmp(refname, "refs/tags/", 10) != 0 ||
5913 (wanted_refname && strcmp(refname, wanted_refname) != 0))
5914 continue;
5915 refname += 10;
5916 refstr = got_ref_to_str(re->ref);
5917 if (refstr == NULL) {
5918 err = got_error_from_errno("got_ref_to_str");
5919 break;
5922 err = got_ref_resolve(&id, repo, re->ref);
5923 if (err)
5924 break;
5925 err = got_object_open_as_tag(&tag, repo, id);
5926 if (err) {
5927 if (err->code != GOT_ERR_OBJ_TYPE) {
5928 free(id);
5929 break;
5931 /* "lightweight" tag */
5932 err = got_object_open_as_commit(&commit, repo, id);
5933 if (err) {
5934 free(id);
5935 break;
5937 tagger = got_object_commit_get_committer(commit);
5938 tagger_time =
5939 got_object_commit_get_committer_time(commit);
5940 err = got_object_id_str(&id_str, id);
5941 free(id);
5942 if (err)
5943 break;
5944 } else {
5945 free(id);
5946 tagger = got_object_tag_get_tagger(tag);
5947 tagger_time = got_object_tag_get_tagger_time(tag);
5948 err = got_object_id_str(&id_str,
5949 got_object_tag_get_object_id(tag));
5950 if (err)
5951 break;
5954 if (tag && verify_tags) {
5955 ssh_sig = got_sigs_get_tagmsg_ssh_signature(
5956 got_object_tag_get_message(tag));
5957 if (ssh_sig && allowed_signers == NULL) {
5958 err = got_error_msg(
5959 GOT_ERR_VERIFY_TAG_SIGNATURE,
5960 "SSH signature verification requires "
5961 "setting allowed_signers in "
5962 "got.conf(5)");
5963 break;
5967 printf("%stag %s %s\n", GOT_COMMIT_SEP_STR, refname, refstr);
5968 free(refstr);
5969 printf("from: %s\n", tagger);
5970 datestr = get_datestr(&tagger_time, datebuf);
5971 if (datestr)
5972 printf("date: %s UTC\n", datestr);
5973 if (commit)
5974 printf("object: %s %s\n", GOT_OBJ_LABEL_COMMIT, id_str);
5975 else {
5976 switch (got_object_tag_get_object_type(tag)) {
5977 case GOT_OBJ_TYPE_BLOB:
5978 printf("object: %s %s\n", GOT_OBJ_LABEL_BLOB,
5979 id_str);
5980 break;
5981 case GOT_OBJ_TYPE_TREE:
5982 printf("object: %s %s\n", GOT_OBJ_LABEL_TREE,
5983 id_str);
5984 break;
5985 case GOT_OBJ_TYPE_COMMIT:
5986 printf("object: %s %s\n", GOT_OBJ_LABEL_COMMIT,
5987 id_str);
5988 break;
5989 case GOT_OBJ_TYPE_TAG:
5990 printf("object: %s %s\n", GOT_OBJ_LABEL_TAG,
5991 id_str);
5992 break;
5993 default:
5994 break;
5997 free(id_str);
5999 if (ssh_sig) {
6000 err = got_sigs_verify_tag_ssh(&sig_msg, tag, ssh_sig,
6001 allowed_signers, revoked_signers, verbosity);
6002 if (err && err->code == GOT_ERR_BAD_TAG_SIGNATURE)
6003 bad_sigs = 1;
6004 else if (err)
6005 break;
6006 printf("signature: %s", sig_msg);
6007 free(sig_msg);
6008 sig_msg = NULL;
6011 if (commit) {
6012 err = got_object_commit_get_logmsg(&tagmsg0, commit);
6013 if (err)
6014 break;
6015 got_object_commit_close(commit);
6016 } else {
6017 tagmsg0 = strdup(got_object_tag_get_message(tag));
6018 got_object_tag_close(tag);
6019 if (tagmsg0 == NULL) {
6020 err = got_error_from_errno("strdup");
6021 break;
6025 tagmsg = tagmsg0;
6026 do {
6027 line = strsep(&tagmsg, "\n");
6028 if (line)
6029 printf(" %s\n", line);
6030 } while (line);
6031 free(tagmsg0);
6033 done:
6034 got_ref_list_free(&refs);
6035 free(wanted_refname);
6037 if (err == NULL && bad_sigs)
6038 err = got_error(GOT_ERR_BAD_TAG_SIGNATURE);
6039 return err;
6042 static const struct got_error *
6043 get_tag_message(char **tagmsg, char **tagmsg_path, const char *commit_id_str,
6044 const char *tag_name, const char *repo_path)
6046 const struct got_error *err = NULL;
6047 char *template = NULL, *initial_content = NULL;
6048 char *editor = NULL;
6049 int initial_content_len;
6050 int fd = -1;
6052 if (asprintf(&template, GOT_TMPDIR_STR "/got-tagmsg") == -1) {
6053 err = got_error_from_errno("asprintf");
6054 goto done;
6057 initial_content_len = asprintf(&initial_content,
6058 "\n# tagging commit %s as %s\n",
6059 commit_id_str, tag_name);
6060 if (initial_content_len == -1) {
6061 err = got_error_from_errno("asprintf");
6062 goto done;
6065 err = got_opentemp_named_fd(tagmsg_path, &fd, template, "");
6066 if (err)
6067 goto done;
6069 if (write(fd, initial_content, initial_content_len) == -1) {
6070 err = got_error_from_errno2("write", *tagmsg_path);
6071 goto done;
6073 if (close(fd) == -1) {
6074 err = got_error_from_errno2("close", *tagmsg_path);
6075 goto done;
6077 fd = -1;
6079 err = get_editor(&editor);
6080 if (err)
6081 goto done;
6082 err = edit_logmsg(tagmsg, editor, *tagmsg_path, initial_content,
6083 initial_content_len, 1);
6084 done:
6085 free(initial_content);
6086 free(template);
6087 free(editor);
6089 if (fd != -1 && close(fd) == -1 && err == NULL)
6090 err = got_error_from_errno2("close", *tagmsg_path);
6092 if (err) {
6093 free(*tagmsg);
6094 *tagmsg = NULL;
6096 return err;
6099 static const struct got_error *
6100 add_tag(struct got_repository *repo, const char *tagger,
6101 const char *tag_name, const char *commit_arg, const char *tagmsg_arg,
6102 const char *signer_id, int verbosity)
6104 const struct got_error *err = NULL;
6105 struct got_object_id *commit_id = NULL, *tag_id = NULL;
6106 char *label = NULL, *commit_id_str = NULL;
6107 struct got_reference *ref = NULL;
6108 char *refname = NULL, *tagmsg = NULL;
6109 char *tagmsg_path = NULL, *tag_id_str = NULL;
6110 int preserve_tagmsg = 0;
6111 struct got_reflist_head refs;
6113 TAILQ_INIT(&refs);
6116 * Don't let the user create a tag name with a leading '-'.
6117 * While technically a valid reference name, this case is usually
6118 * an unintended typo.
6120 if (tag_name[0] == '-')
6121 return got_error_path(tag_name, GOT_ERR_REF_NAME_MINUS);
6123 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
6124 if (err)
6125 goto done;
6127 err = got_repo_match_object_id(&commit_id, &label, commit_arg,
6128 GOT_OBJ_TYPE_COMMIT, &refs, repo);
6129 if (err)
6130 goto done;
6132 err = got_object_id_str(&commit_id_str, commit_id);
6133 if (err)
6134 goto done;
6136 err = get_tag_refname(&refname, tag_name);
6137 if (err)
6138 goto done;
6139 if (strncmp("refs/tags/", tag_name, 10) == 0)
6140 tag_name += 10;
6142 err = got_ref_open(&ref, repo, refname, 0);
6143 if (err == NULL) {
6144 err = got_error(GOT_ERR_TAG_EXISTS);
6145 goto done;
6146 } else if (err->code != GOT_ERR_NOT_REF)
6147 goto done;
6149 if (tagmsg_arg == NULL) {
6150 err = get_tag_message(&tagmsg, &tagmsg_path, commit_id_str,
6151 tag_name, got_repo_get_path(repo));
6152 if (err) {
6153 if (err->code != GOT_ERR_COMMIT_MSG_EMPTY &&
6154 tagmsg_path != NULL)
6155 preserve_tagmsg = 1;
6156 goto done;
6158 /* Editor is done; we can now apply unveil(2) */
6159 err = got_sigs_apply_unveil();
6160 if (err)
6161 goto done;
6162 err = apply_unveil(got_repo_get_path(repo), 0, NULL);
6163 if (err)
6164 goto done;
6167 err = got_object_tag_create(&tag_id, tag_name, commit_id,
6168 tagger, time(NULL), tagmsg ? tagmsg : tagmsg_arg, signer_id, repo,
6169 verbosity);
6170 if (err) {
6171 if (tagmsg_path)
6172 preserve_tagmsg = 1;
6173 goto done;
6176 err = got_ref_alloc(&ref, refname, tag_id);
6177 if (err) {
6178 if (tagmsg_path)
6179 preserve_tagmsg = 1;
6180 goto done;
6183 err = got_ref_write(ref, repo);
6184 if (err) {
6185 if (tagmsg_path)
6186 preserve_tagmsg = 1;
6187 goto done;
6190 err = got_object_id_str(&tag_id_str, tag_id);
6191 if (err) {
6192 if (tagmsg_path)
6193 preserve_tagmsg = 1;
6194 goto done;
6196 printf("Created tag %s\n", tag_id_str);
6197 done:
6198 if (preserve_tagmsg) {
6199 fprintf(stderr, "%s: tag message preserved in %s\n",
6200 getprogname(), tagmsg_path);
6201 } else if (tagmsg_path && unlink(tagmsg_path) == -1 && err == NULL)
6202 err = got_error_from_errno2("unlink", tagmsg_path);
6203 free(tag_id_str);
6204 if (ref)
6205 got_ref_close(ref);
6206 free(commit_id);
6207 free(commit_id_str);
6208 free(refname);
6209 free(tagmsg);
6210 free(tagmsg_path);
6211 got_ref_list_free(&refs);
6212 return err;
6215 static const struct got_error *
6216 cmd_tag(int argc, char *argv[])
6218 const struct got_error *error = NULL;
6219 struct got_repository *repo = NULL;
6220 struct got_worktree *worktree = NULL;
6221 char *cwd = NULL, *repo_path = NULL, *commit_id_str = NULL;
6222 char *gitconfig_path = NULL, *tagger = NULL;
6223 char *allowed_signers = NULL, *revoked_signers = NULL;
6224 const char *signer_id = NULL;
6225 const char *tag_name = NULL, *commit_id_arg = NULL, *tagmsg = NULL;
6226 int ch, do_list = 0, verify_tags = 0, verbosity = 0;
6227 int *pack_fds = NULL;
6229 #ifndef PROFILE
6230 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
6231 "sendfd unveil", NULL) == -1)
6232 err(1, "pledge");
6233 #endif
6235 while ((ch = getopt(argc, argv, "c:lm:r:s:Vv")) != -1) {
6236 switch (ch) {
6237 case 'c':
6238 commit_id_arg = optarg;
6239 break;
6240 case 'l':
6241 do_list = 1;
6242 break;
6243 case 'm':
6244 tagmsg = optarg;
6245 break;
6246 case 'r':
6247 repo_path = realpath(optarg, NULL);
6248 if (repo_path == NULL) {
6249 error = got_error_from_errno2("realpath",
6250 optarg);
6251 goto done;
6253 got_path_strip_trailing_slashes(repo_path);
6254 break;
6255 case 's':
6256 signer_id = optarg;
6257 break;
6258 case 'V':
6259 verify_tags = 1;
6260 break;
6261 case 'v':
6262 if (verbosity < 0)
6263 verbosity = 0;
6264 else if (verbosity < 3)
6265 verbosity++;
6266 break;
6267 default:
6268 usage_tag();
6269 /* NOTREACHED */
6273 argc -= optind;
6274 argv += optind;
6276 if (do_list || verify_tags) {
6277 if (commit_id_arg != NULL)
6278 errx(1,
6279 "-c option can only be used when creating a tag");
6280 if (tagmsg) {
6281 if (do_list)
6282 option_conflict('l', 'm');
6283 else
6284 option_conflict('V', 'm');
6286 if (signer_id) {
6287 if (do_list)
6288 option_conflict('l', 's');
6289 else
6290 option_conflict('V', 's');
6292 if (argc > 1)
6293 usage_tag();
6294 } else if (argc != 1)
6295 usage_tag();
6297 if (argc == 1)
6298 tag_name = argv[0];
6300 cwd = getcwd(NULL, 0);
6301 if (cwd == NULL) {
6302 error = got_error_from_errno("getcwd");
6303 goto done;
6306 error = got_repo_pack_fds_open(&pack_fds);
6307 if (error != NULL)
6308 goto done;
6310 if (repo_path == NULL) {
6311 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_CVG_DIR);
6312 if (error && error->code != GOT_ERR_NOT_WORKTREE)
6313 goto done;
6314 else
6315 error = NULL;
6316 if (worktree) {
6317 repo_path =
6318 strdup(got_worktree_get_repo_path(worktree));
6319 if (repo_path == NULL)
6320 error = got_error_from_errno("strdup");
6321 if (error)
6322 goto done;
6323 } else {
6324 repo_path = strdup(cwd);
6325 if (repo_path == NULL) {
6326 error = got_error_from_errno("strdup");
6327 goto done;
6332 if (do_list || verify_tags) {
6333 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
6334 if (error != NULL)
6335 goto done;
6336 error = get_allowed_signers(&allowed_signers, repo, worktree);
6337 if (error)
6338 goto done;
6339 error = get_revoked_signers(&revoked_signers, repo, worktree);
6340 if (error)
6341 goto done;
6342 if (worktree) {
6343 /* Release work tree lock. */
6344 got_worktree_close(worktree);
6345 worktree = NULL;
6349 * Remove "cpath" promise unless needed for signature tmpfile
6350 * creation.
6352 if (verify_tags)
6353 got_sigs_apply_unveil();
6354 else {
6355 #ifndef PROFILE
6356 if (pledge("stdio rpath wpath flock proc exec sendfd "
6357 "unveil", NULL) == -1)
6358 err(1, "pledge");
6359 #endif
6361 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
6362 if (error)
6363 goto done;
6364 error = list_tags(repo, tag_name, verify_tags, allowed_signers,
6365 revoked_signers, verbosity);
6366 } else {
6367 error = get_gitconfig_path(&gitconfig_path);
6368 if (error)
6369 goto done;
6370 error = got_repo_open(&repo, repo_path, gitconfig_path,
6371 pack_fds);
6372 if (error != NULL)
6373 goto done;
6375 error = get_author(&tagger, repo, worktree);
6376 if (error)
6377 goto done;
6378 if (signer_id == NULL)
6379 signer_id = get_signer_id(repo, worktree);
6381 if (tagmsg) {
6382 if (signer_id) {
6383 error = got_sigs_apply_unveil();
6384 if (error)
6385 goto done;
6387 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
6388 if (error)
6389 goto done;
6392 if (commit_id_arg == NULL) {
6393 struct got_reference *head_ref;
6394 struct got_object_id *commit_id;
6395 error = got_ref_open(&head_ref, repo,
6396 worktree ? got_worktree_get_head_ref_name(worktree)
6397 : GOT_REF_HEAD, 0);
6398 if (error)
6399 goto done;
6400 error = got_ref_resolve(&commit_id, repo, head_ref);
6401 got_ref_close(head_ref);
6402 if (error)
6403 goto done;
6404 error = got_object_id_str(&commit_id_str, commit_id);
6405 free(commit_id);
6406 if (error)
6407 goto done;
6410 if (worktree) {
6411 /* Release work tree lock. */
6412 got_worktree_close(worktree);
6413 worktree = NULL;
6416 error = add_tag(repo, tagger, tag_name,
6417 commit_id_str ? commit_id_str : commit_id_arg, tagmsg,
6418 signer_id, verbosity);
6420 done:
6421 if (repo) {
6422 const struct got_error *close_err = got_repo_close(repo);
6423 if (error == NULL)
6424 error = close_err;
6426 if (worktree)
6427 got_worktree_close(worktree);
6428 if (pack_fds) {
6429 const struct got_error *pack_err =
6430 got_repo_pack_fds_close(pack_fds);
6431 if (error == NULL)
6432 error = pack_err;
6434 free(cwd);
6435 free(repo_path);
6436 free(gitconfig_path);
6437 free(commit_id_str);
6438 free(tagger);
6439 free(allowed_signers);
6440 free(revoked_signers);
6441 return error;
6444 __dead static void
6445 usage_add(void)
6447 fprintf(stderr, "usage: %s add [-IR] path ...\n", getprogname());
6448 exit(1);
6451 static const struct got_error *
6452 add_progress(void *arg, unsigned char status, const char *path)
6454 while (path[0] == '/')
6455 path++;
6456 printf("%c %s\n", status, path);
6457 return NULL;
6460 static const struct got_error *
6461 cmd_add(int argc, char *argv[])
6463 const struct got_error *error = NULL;
6464 struct got_repository *repo = NULL;
6465 struct got_worktree *worktree = NULL;
6466 char *cwd = NULL;
6467 struct got_pathlist_head paths;
6468 struct got_pathlist_entry *pe;
6469 int ch, can_recurse = 0, no_ignores = 0;
6470 int *pack_fds = NULL;
6472 TAILQ_INIT(&paths);
6474 #ifndef PROFILE
6475 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
6476 NULL) == -1)
6477 err(1, "pledge");
6478 #endif
6480 while ((ch = getopt(argc, argv, "IR")) != -1) {
6481 switch (ch) {
6482 case 'I':
6483 no_ignores = 1;
6484 break;
6485 case 'R':
6486 can_recurse = 1;
6487 break;
6488 default:
6489 usage_add();
6490 /* NOTREACHED */
6494 argc -= optind;
6495 argv += optind;
6497 if (argc < 1)
6498 usage_add();
6500 cwd = getcwd(NULL, 0);
6501 if (cwd == NULL) {
6502 error = got_error_from_errno("getcwd");
6503 goto done;
6506 error = got_repo_pack_fds_open(&pack_fds);
6507 if (error != NULL)
6508 goto done;
6510 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_CVG_DIR);
6511 if (error) {
6512 if (error->code == GOT_ERR_NOT_WORKTREE)
6513 error = wrap_not_worktree_error(error, "add", cwd);
6514 goto done;
6517 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
6518 NULL, pack_fds);
6519 if (error != NULL)
6520 goto done;
6522 error = apply_unveil(got_repo_get_path(repo), 1,
6523 got_worktree_get_root_path(worktree));
6524 if (error)
6525 goto done;
6527 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
6528 if (error)
6529 goto done;
6531 if (!can_recurse) {
6532 char *ondisk_path;
6533 struct stat sb;
6534 TAILQ_FOREACH(pe, &paths, entry) {
6535 if (asprintf(&ondisk_path, "%s/%s",
6536 got_worktree_get_root_path(worktree),
6537 pe->path) == -1) {
6538 error = got_error_from_errno("asprintf");
6539 goto done;
6541 if (lstat(ondisk_path, &sb) == -1) {
6542 if (errno == ENOENT) {
6543 free(ondisk_path);
6544 continue;
6546 error = got_error_from_errno2("lstat",
6547 ondisk_path);
6548 free(ondisk_path);
6549 goto done;
6551 free(ondisk_path);
6552 if (S_ISDIR(sb.st_mode)) {
6553 error = got_error_msg(GOT_ERR_BAD_PATH,
6554 "adding directories requires -R option");
6555 goto done;
6560 error = got_worktree_schedule_add(worktree, &paths, add_progress,
6561 NULL, repo, no_ignores);
6562 done:
6563 if (repo) {
6564 const struct got_error *close_err = got_repo_close(repo);
6565 if (error == NULL)
6566 error = close_err;
6568 if (worktree)
6569 got_worktree_close(worktree);
6570 if (pack_fds) {
6571 const struct got_error *pack_err =
6572 got_repo_pack_fds_close(pack_fds);
6573 if (error == NULL)
6574 error = pack_err;
6576 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
6577 free(cwd);
6578 return error;
6581 __dead static void
6582 usage_remove(void)
6584 fprintf(stderr, "usage: %s remove [-fkR] [-s status-codes] path ...\n",
6585 getprogname());
6586 exit(1);
6589 static const struct got_error *
6590 print_remove_status(void *arg, unsigned char status,
6591 unsigned char staged_status, const char *path)
6593 while (path[0] == '/')
6594 path++;
6595 if (status == GOT_STATUS_NONEXISTENT)
6596 return NULL;
6597 if (status == staged_status && (status == GOT_STATUS_DELETE))
6598 status = GOT_STATUS_NO_CHANGE;
6599 printf("%c%c %s\n", status, staged_status, path);
6600 return NULL;
6603 static const struct got_error *
6604 cmd_remove(int argc, char *argv[])
6606 const struct got_error *error = NULL;
6607 struct got_worktree *worktree = NULL;
6608 struct got_repository *repo = NULL;
6609 const char *status_codes = NULL;
6610 char *cwd = NULL;
6611 struct got_pathlist_head paths;
6612 struct got_pathlist_entry *pe;
6613 int ch, delete_local_mods = 0, can_recurse = 0, keep_on_disk = 0, i;
6614 int ignore_missing_paths = 0;
6615 int *pack_fds = NULL;
6617 TAILQ_INIT(&paths);
6619 #ifndef PROFILE
6620 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
6621 NULL) == -1)
6622 err(1, "pledge");
6623 #endif
6625 while ((ch = getopt(argc, argv, "fkRs:")) != -1) {
6626 switch (ch) {
6627 case 'f':
6628 delete_local_mods = 1;
6629 ignore_missing_paths = 1;
6630 break;
6631 case 'k':
6632 keep_on_disk = 1;
6633 break;
6634 case 'R':
6635 can_recurse = 1;
6636 break;
6637 case 's':
6638 for (i = 0; optarg[i] != '\0'; i++) {
6639 switch (optarg[i]) {
6640 case GOT_STATUS_MODIFY:
6641 delete_local_mods = 1;
6642 break;
6643 case GOT_STATUS_MISSING:
6644 ignore_missing_paths = 1;
6645 break;
6646 default:
6647 errx(1, "invalid status code '%c'",
6648 optarg[i]);
6651 status_codes = optarg;
6652 break;
6653 default:
6654 usage_remove();
6655 /* NOTREACHED */
6659 argc -= optind;
6660 argv += optind;
6662 if (argc < 1)
6663 usage_remove();
6665 cwd = getcwd(NULL, 0);
6666 if (cwd == NULL) {
6667 error = got_error_from_errno("getcwd");
6668 goto done;
6671 error = got_repo_pack_fds_open(&pack_fds);
6672 if (error != NULL)
6673 goto done;
6675 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_CVG_DIR);
6676 if (error) {
6677 if (error->code == GOT_ERR_NOT_WORKTREE)
6678 error = wrap_not_worktree_error(error, "remove", cwd);
6679 goto done;
6682 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
6683 NULL, pack_fds);
6684 if (error)
6685 goto done;
6687 error = apply_unveil(got_repo_get_path(repo), 1,
6688 got_worktree_get_root_path(worktree));
6689 if (error)
6690 goto done;
6692 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
6693 if (error)
6694 goto done;
6696 if (!can_recurse) {
6697 char *ondisk_path;
6698 struct stat sb;
6699 TAILQ_FOREACH(pe, &paths, entry) {
6700 if (asprintf(&ondisk_path, "%s/%s",
6701 got_worktree_get_root_path(worktree),
6702 pe->path) == -1) {
6703 error = got_error_from_errno("asprintf");
6704 goto done;
6706 if (lstat(ondisk_path, &sb) == -1) {
6707 if (errno == ENOENT) {
6708 free(ondisk_path);
6709 continue;
6711 error = got_error_from_errno2("lstat",
6712 ondisk_path);
6713 free(ondisk_path);
6714 goto done;
6716 free(ondisk_path);
6717 if (S_ISDIR(sb.st_mode)) {
6718 error = got_error_msg(GOT_ERR_BAD_PATH,
6719 "removing directories requires -R option");
6720 goto done;
6725 error = got_worktree_schedule_delete(worktree, &paths,
6726 delete_local_mods, status_codes, print_remove_status, NULL,
6727 repo, keep_on_disk, ignore_missing_paths);
6728 done:
6729 if (repo) {
6730 const struct got_error *close_err = got_repo_close(repo);
6731 if (error == NULL)
6732 error = close_err;
6734 if (worktree)
6735 got_worktree_close(worktree);
6736 if (pack_fds) {
6737 const struct got_error *pack_err =
6738 got_repo_pack_fds_close(pack_fds);
6739 if (error == NULL)
6740 error = pack_err;
6742 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
6743 free(cwd);
6744 return error;
6747 __dead static void
6748 usage_patch(void)
6750 fprintf(stderr, "usage: %s patch [-nR] [-c commit] [-p strip-count] "
6751 "[patchfile]\n", getprogname());
6752 exit(1);
6755 static const struct got_error *
6756 patch_from_stdin(int *patchfd)
6758 const struct got_error *err = NULL;
6759 ssize_t r;
6760 char buf[BUFSIZ];
6761 sig_t sighup, sigint, sigquit;
6763 *patchfd = got_opentempfd();
6764 if (*patchfd == -1)
6765 return got_error_from_errno("got_opentempfd");
6767 sighup = signal(SIGHUP, SIG_DFL);
6768 sigint = signal(SIGINT, SIG_DFL);
6769 sigquit = signal(SIGQUIT, SIG_DFL);
6771 for (;;) {
6772 r = read(0, buf, sizeof(buf));
6773 if (r == -1) {
6774 err = got_error_from_errno("read");
6775 break;
6777 if (r == 0)
6778 break;
6779 if (write(*patchfd, buf, r) == -1) {
6780 err = got_error_from_errno("write");
6781 break;
6785 signal(SIGHUP, sighup);
6786 signal(SIGINT, sigint);
6787 signal(SIGQUIT, sigquit);
6789 if (err == NULL && lseek(*patchfd, 0, SEEK_SET) == -1)
6790 err = got_error_from_errno("lseek");
6792 if (err != NULL) {
6793 close(*patchfd);
6794 *patchfd = -1;
6797 return err;
6800 struct got_patch_progress_arg {
6801 int did_something;
6802 int conflicts;
6803 int rejects;
6806 static const struct got_error *
6807 patch_progress(void *arg, const char *old, const char *new,
6808 unsigned char status, const struct got_error *error, int old_from,
6809 int old_lines, int new_from, int new_lines, int offset,
6810 int ws_mangled, const struct got_error *hunk_err)
6812 const char *path = new == NULL ? old : new;
6813 struct got_patch_progress_arg *a = arg;
6815 while (*path == '/')
6816 path++;
6818 if (status != GOT_STATUS_NO_CHANGE &&
6819 status != 0 /* per-hunk progress */) {
6820 printf("%c %s\n", status, path);
6821 a->did_something = 1;
6824 if (hunk_err == NULL) {
6825 if (status == GOT_STATUS_CANNOT_UPDATE)
6826 a->rejects++;
6827 else if (status == GOT_STATUS_CONFLICT)
6828 a->conflicts++;
6831 if (error != NULL)
6832 fprintf(stderr, "%s: %s\n", getprogname(), error->msg);
6834 if (offset != 0 || hunk_err != NULL || ws_mangled) {
6835 printf("@@ -%d,%d +%d,%d @@ ", old_from,
6836 old_lines, new_from, new_lines);
6837 if (hunk_err != NULL)
6838 printf("%s\n", hunk_err->msg);
6839 else if (offset != 0)
6840 printf("applied with offset %d\n", offset);
6841 else
6842 printf("hunk contains mangled whitespace\n");
6845 return NULL;
6848 static void
6849 print_patch_progress_stats(struct got_patch_progress_arg *ppa)
6851 if (!ppa->did_something)
6852 return;
6854 if (ppa->conflicts > 0)
6855 printf("Files with merge conflicts: %d\n", ppa->conflicts);
6857 if (ppa->rejects > 0) {
6858 printf("Files where patch failed to apply: %d\n",
6859 ppa->rejects);
6863 static const struct got_error *
6864 cmd_patch(int argc, char *argv[])
6866 const struct got_error *error = NULL, *close_error = NULL;
6867 struct got_worktree *worktree = NULL;
6868 struct got_repository *repo = NULL;
6869 struct got_reflist_head refs;
6870 struct got_object_id *commit_id = NULL;
6871 const char *commit_id_str = NULL;
6872 struct stat sb;
6873 const char *errstr;
6874 char *cwd = NULL;
6875 int ch, nop = 0, strip = -1, reverse = 0;
6876 int patchfd;
6877 int *pack_fds = NULL;
6878 struct got_patch_progress_arg ppa;
6880 TAILQ_INIT(&refs);
6882 #ifndef PROFILE
6883 if (pledge("stdio rpath wpath cpath fattr proc exec sendfd flock "
6884 "unveil", NULL) == -1)
6885 err(1, "pledge");
6886 #endif
6888 while ((ch = getopt(argc, argv, "c:np:R")) != -1) {
6889 switch (ch) {
6890 case 'c':
6891 commit_id_str = optarg;
6892 break;
6893 case 'n':
6894 nop = 1;
6895 break;
6896 case 'p':
6897 strip = strtonum(optarg, 0, INT_MAX, &errstr);
6898 if (errstr != NULL)
6899 errx(1, "pathname strip count is %s: %s",
6900 errstr, optarg);
6901 break;
6902 case 'R':
6903 reverse = 1;
6904 break;
6905 default:
6906 usage_patch();
6907 /* NOTREACHED */
6911 argc -= optind;
6912 argv += optind;
6914 if (argc == 0) {
6915 error = patch_from_stdin(&patchfd);
6916 if (error)
6917 return error;
6918 } else if (argc == 1) {
6919 patchfd = open(argv[0], O_RDONLY);
6920 if (patchfd == -1) {
6921 error = got_error_from_errno2("open", argv[0]);
6922 return error;
6924 if (fstat(patchfd, &sb) == -1) {
6925 error = got_error_from_errno2("fstat", argv[0]);
6926 goto done;
6928 if (!S_ISREG(sb.st_mode)) {
6929 error = got_error_path(argv[0], GOT_ERR_BAD_FILETYPE);
6930 goto done;
6932 } else
6933 usage_patch();
6935 if ((cwd = getcwd(NULL, 0)) == NULL) {
6936 error = got_error_from_errno("getcwd");
6937 goto done;
6940 error = got_repo_pack_fds_open(&pack_fds);
6941 if (error != NULL)
6942 goto done;
6944 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_CVG_DIR);
6945 if (error != NULL)
6946 goto done;
6948 const char *repo_path = got_worktree_get_repo_path(worktree);
6949 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
6950 if (error != NULL)
6951 goto done;
6953 error = apply_unveil(got_repo_get_path(repo), 0,
6954 got_worktree_get_root_path(worktree));
6955 if (error != NULL)
6956 goto done;
6958 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
6959 if (error)
6960 goto done;
6962 if (commit_id_str != NULL) {
6963 error = got_repo_match_object_id(&commit_id, NULL,
6964 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
6965 if (error)
6966 goto done;
6969 memset(&ppa, 0, sizeof(ppa));
6970 error = got_patch(patchfd, worktree, repo, nop, strip, reverse,
6971 commit_id, patch_progress, &ppa, check_cancelled, NULL);
6972 print_patch_progress_stats(&ppa);
6973 done:
6974 got_ref_list_free(&refs);
6975 free(commit_id);
6976 if (repo) {
6977 close_error = got_repo_close(repo);
6978 if (error == NULL)
6979 error = close_error;
6981 if (worktree != NULL) {
6982 close_error = got_worktree_close(worktree);
6983 if (error == NULL)
6984 error = close_error;
6986 if (pack_fds) {
6987 const struct got_error *pack_err =
6988 got_repo_pack_fds_close(pack_fds);
6989 if (error == NULL)
6990 error = pack_err;
6992 free(cwd);
6993 return error;
6996 __dead static void
6997 usage_revert(void)
6999 fprintf(stderr, "usage: %s revert [-pR] [-F response-script] path ...\n",
7000 getprogname());
7001 exit(1);
7004 static const struct got_error *
7005 revert_progress(void *arg, unsigned char status, const char *path)
7007 if (status == GOT_STATUS_UNVERSIONED)
7008 return NULL;
7010 while (path[0] == '/')
7011 path++;
7012 printf("%c %s\n", status, path);
7013 return NULL;
7016 struct choose_patch_arg {
7017 FILE *patch_script_file;
7018 const char *action;
7021 static const struct got_error *
7022 show_change(unsigned char status, const char *path, FILE *patch_file, int n,
7023 int nchanges, const char *action)
7025 const struct got_error *err;
7026 char *line = NULL;
7027 size_t linesize = 0;
7028 ssize_t linelen;
7030 switch (status) {
7031 case GOT_STATUS_ADD:
7032 printf("A %s\n%s this addition? [y/n] ", path, action);
7033 break;
7034 case GOT_STATUS_DELETE:
7035 printf("D %s\n%s this deletion? [y/n] ", path, action);
7036 break;
7037 case GOT_STATUS_MODIFY:
7038 if (fseek(patch_file, 0L, SEEK_SET) == -1)
7039 return got_error_from_errno("fseek");
7040 printf(GOT_COMMIT_SEP_STR);
7041 while ((linelen = getline(&line, &linesize, patch_file)) != -1)
7042 printf("%s", line);
7043 if (linelen == -1 && ferror(patch_file)) {
7044 err = got_error_from_errno("getline");
7045 free(line);
7046 return err;
7048 free(line);
7049 printf(GOT_COMMIT_SEP_STR);
7050 printf("M %s (change %d of %d)\n%s this change? [y/n/q] ",
7051 path, n, nchanges, action);
7052 break;
7053 default:
7054 return got_error_path(path, GOT_ERR_FILE_STATUS);
7057 fflush(stdout);
7058 return NULL;
7061 static const struct got_error *
7062 choose_patch(int *choice, void *arg, unsigned char status, const char *path,
7063 FILE *patch_file, int n, int nchanges)
7065 const struct got_error *err = NULL;
7066 char *line = NULL;
7067 size_t linesize = 0;
7068 ssize_t linelen;
7069 int resp = ' ';
7070 struct choose_patch_arg *a = arg;
7072 *choice = GOT_PATCH_CHOICE_NONE;
7074 if (a->patch_script_file) {
7075 char *nl;
7076 err = show_change(status, path, patch_file, n, nchanges,
7077 a->action);
7078 if (err)
7079 return err;
7080 linelen = getline(&line, &linesize, a->patch_script_file);
7081 if (linelen == -1) {
7082 if (ferror(a->patch_script_file))
7083 return got_error_from_errno("getline");
7084 return NULL;
7086 nl = strchr(line, '\n');
7087 if (nl)
7088 *nl = '\0';
7089 if (strcmp(line, "y") == 0) {
7090 *choice = GOT_PATCH_CHOICE_YES;
7091 printf("y\n");
7092 } else if (strcmp(line, "n") == 0) {
7093 *choice = GOT_PATCH_CHOICE_NO;
7094 printf("n\n");
7095 } else if (strcmp(line, "q") == 0 &&
7096 status == GOT_STATUS_MODIFY) {
7097 *choice = GOT_PATCH_CHOICE_QUIT;
7098 printf("q\n");
7099 } else
7100 printf("invalid response '%s'\n", line);
7101 free(line);
7102 return NULL;
7105 while (resp != 'y' && resp != 'n' && resp != 'q') {
7106 err = show_change(status, path, patch_file, n, nchanges,
7107 a->action);
7108 if (err)
7109 return err;
7110 resp = getchar();
7111 if (resp == '\n')
7112 resp = getchar();
7113 if (status == GOT_STATUS_MODIFY) {
7114 if (resp != 'y' && resp != 'n' && resp != 'q') {
7115 printf("invalid response '%c'\n", resp);
7116 resp = ' ';
7118 } else if (resp != 'y' && resp != 'n') {
7119 printf("invalid response '%c'\n", resp);
7120 resp = ' ';
7124 if (resp == 'y')
7125 *choice = GOT_PATCH_CHOICE_YES;
7126 else if (resp == 'n')
7127 *choice = GOT_PATCH_CHOICE_NO;
7128 else if (resp == 'q' && status == GOT_STATUS_MODIFY)
7129 *choice = GOT_PATCH_CHOICE_QUIT;
7131 return NULL;
7134 struct wt_commitable_path_arg {
7135 struct got_pathlist_head *commit_paths;
7136 int *has_changes;
7140 * Shortcut work tree status callback to determine if the set of paths scanned
7141 * has at least one versioned path that is being modified and, if not NULL, is
7142 * in the arg->commit_paths list. Set arg and return GOT_ERR_FILE_MODIFIED as
7143 * soon as a path is passed with a status that satisfies this criteria.
7145 static const struct got_error *
7146 worktree_has_commitable_path(void *arg, unsigned char status,
7147 unsigned char staged_status, const char *path,
7148 struct got_object_id *blob_id, struct got_object_id *staged_blob_id,
7149 struct got_object_id *commit_id, int dirfd, const char *de_name)
7151 struct wt_commitable_path_arg *a = arg;
7153 if (status == staged_status && (status == GOT_STATUS_DELETE))
7154 status = GOT_STATUS_NO_CHANGE;
7156 if (!(status == GOT_STATUS_NO_CHANGE ||
7157 status == GOT_STATUS_UNVERSIONED) ||
7158 staged_status != GOT_STATUS_NO_CHANGE) {
7159 if (a->commit_paths != NULL) {
7160 struct got_pathlist_entry *pe;
7162 TAILQ_FOREACH(pe, a->commit_paths, entry) {
7163 if (strncmp(path, pe->path,
7164 pe->path_len) == 0) {
7165 *a->has_changes = 1;
7166 break;
7169 } else
7170 *a->has_changes = 1;
7172 if (*a->has_changes)
7173 return got_error(GOT_ERR_FILE_MODIFIED);
7176 return NULL;
7180 * Check that the changeset of the commit identified by id is
7181 * comprised of at least one modified path that is being committed.
7183 static const struct got_error *
7184 commit_path_changed_in_worktree(struct wt_commitable_path_arg *wcpa,
7185 struct got_object_id *id, struct got_worktree *worktree,
7186 struct got_repository *repo)
7188 const struct got_error *err;
7189 struct got_pathlist_head paths;
7190 struct got_commit_object *commit = NULL, *pcommit = NULL;
7191 struct got_tree_object *tree = NULL, *ptree = NULL;
7192 struct got_object_qid *pid;
7194 TAILQ_INIT(&paths);
7196 err = got_object_open_as_commit(&commit, repo, id);
7197 if (err)
7198 goto done;
7200 err = got_object_open_as_tree(&tree, repo,
7201 got_object_commit_get_tree_id(commit));
7202 if (err)
7203 goto done;
7205 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
7206 if (pid != NULL) {
7207 err = got_object_open_as_commit(&pcommit, repo, &pid->id);
7208 if (err)
7209 goto done;
7211 err = got_object_open_as_tree(&ptree, repo,
7212 got_object_commit_get_tree_id(pcommit));
7213 if (err)
7214 goto done;
7217 err = got_diff_tree(ptree, tree, NULL, NULL, -1, -1, "", "", repo,
7218 got_diff_tree_collect_changed_paths, &paths, 0);
7219 if (err)
7220 goto done;
7222 err = got_worktree_status(worktree, &paths, repo, 0,
7223 worktree_has_commitable_path, wcpa, check_cancelled, NULL);
7224 if (err && err->code == GOT_ERR_FILE_MODIFIED) {
7226 * At least one changed path in the referenced commit is
7227 * modified in the work tree, that's all we need to know!
7229 err = NULL;
7232 done:
7233 got_pathlist_free(&paths, GOT_PATHLIST_FREE_ALL);
7234 if (commit)
7235 got_object_commit_close(commit);
7236 if (pcommit)
7237 got_object_commit_close(pcommit);
7238 if (tree)
7239 got_object_tree_close(tree);
7240 if (ptree)
7241 got_object_tree_close(ptree);
7242 return err;
7246 * Remove any "logmsg" reference comprised entirely of paths that have
7247 * been reverted in this work tree. If any path in the logmsg ref changeset
7248 * remains in a changed state in the worktree, do not remove the reference.
7250 static const struct got_error *
7251 rm_logmsg_ref(struct got_worktree *worktree, struct got_repository *repo)
7253 const struct got_error *err;
7254 struct got_reflist_head refs;
7255 struct got_reflist_entry *re;
7256 struct got_commit_object *commit = NULL;
7257 struct got_object_id *commit_id = NULL;
7258 struct wt_commitable_path_arg wcpa;
7259 char *uuidstr = NULL;
7261 TAILQ_INIT(&refs);
7263 err = got_worktree_get_uuid(&uuidstr, worktree);
7264 if (err)
7265 goto done;
7267 err = got_ref_list(&refs, repo, "refs/got/worktree",
7268 got_ref_cmp_by_name, repo);
7269 if (err)
7270 goto done;
7272 TAILQ_FOREACH(re, &refs, entry) {
7273 const char *refname;
7274 int has_changes = 0;
7276 refname = got_ref_get_name(re->ref);
7278 if (!strncmp(refname, GOT_WORKTREE_CHERRYPICK_REF_PREFIX,
7279 GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN))
7280 refname += GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN + 1;
7281 else if (!strncmp(refname, GOT_WORKTREE_BACKOUT_REF_PREFIX,
7282 GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN))
7283 refname += GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN + 1;
7284 else
7285 continue;
7287 if (strncmp(refname, uuidstr, GOT_WORKTREE_UUID_STRLEN) == 0)
7288 refname += GOT_WORKTREE_UUID_STRLEN + 1; /* skip '-' */
7289 else
7290 continue;
7292 err = got_repo_match_object_id(&commit_id, NULL, refname,
7293 GOT_OBJ_TYPE_COMMIT, NULL, repo);
7294 if (err)
7295 goto done;
7297 err = got_object_open_as_commit(&commit, repo, commit_id);
7298 if (err)
7299 goto done;
7301 wcpa.commit_paths = NULL;
7302 wcpa.has_changes = &has_changes;
7304 err = commit_path_changed_in_worktree(&wcpa, commit_id,
7305 worktree, repo);
7306 if (err)
7307 goto done;
7309 if (!has_changes) {
7310 err = got_ref_delete(re->ref, repo);
7311 if (err)
7312 goto done;
7315 got_object_commit_close(commit);
7316 commit = NULL;
7317 free(commit_id);
7318 commit_id = NULL;
7321 done:
7322 free(uuidstr);
7323 free(commit_id);
7324 got_ref_list_free(&refs);
7325 if (commit)
7326 got_object_commit_close(commit);
7327 return err;
7330 static const struct got_error *
7331 cmd_revert(int argc, char *argv[])
7333 const struct got_error *error = NULL;
7334 struct got_worktree *worktree = NULL;
7335 struct got_repository *repo = NULL;
7336 char *cwd = NULL, *path = NULL;
7337 struct got_pathlist_head paths;
7338 struct got_pathlist_entry *pe;
7339 int ch, can_recurse = 0, pflag = 0;
7340 FILE *patch_script_file = NULL;
7341 const char *patch_script_path = NULL;
7342 struct choose_patch_arg cpa;
7343 int *pack_fds = NULL;
7345 TAILQ_INIT(&paths);
7347 #ifndef PROFILE
7348 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
7349 "unveil", NULL) == -1)
7350 err(1, "pledge");
7351 #endif
7353 while ((ch = getopt(argc, argv, "F:pR")) != -1) {
7354 switch (ch) {
7355 case 'F':
7356 patch_script_path = optarg;
7357 break;
7358 case 'p':
7359 pflag = 1;
7360 break;
7361 case 'R':
7362 can_recurse = 1;
7363 break;
7364 default:
7365 usage_revert();
7366 /* NOTREACHED */
7370 argc -= optind;
7371 argv += optind;
7373 if (argc < 1)
7374 usage_revert();
7375 if (patch_script_path && !pflag)
7376 errx(1, "-F option can only be used together with -p option");
7378 cwd = getcwd(NULL, 0);
7379 if (cwd == NULL) {
7380 error = got_error_from_errno("getcwd");
7381 goto done;
7384 error = got_repo_pack_fds_open(&pack_fds);
7385 if (error != NULL)
7386 goto done;
7388 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_CVG_DIR);
7389 if (error) {
7390 if (error->code == GOT_ERR_NOT_WORKTREE)
7391 error = wrap_not_worktree_error(error, "revert", cwd);
7392 goto done;
7395 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
7396 NULL, pack_fds);
7397 if (error != NULL)
7398 goto done;
7400 if (patch_script_path) {
7401 patch_script_file = fopen(patch_script_path, "re");
7402 if (patch_script_file == NULL) {
7403 error = got_error_from_errno2("fopen",
7404 patch_script_path);
7405 goto done;
7410 * XXX "c" perm needed on repo dir to delete merge references.
7412 error = apply_unveil(got_repo_get_path(repo), 0,
7413 got_worktree_get_root_path(worktree));
7414 if (error)
7415 goto done;
7417 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
7418 if (error)
7419 goto done;
7421 if (!can_recurse) {
7422 char *ondisk_path;
7423 struct stat sb;
7424 TAILQ_FOREACH(pe, &paths, entry) {
7425 if (asprintf(&ondisk_path, "%s/%s",
7426 got_worktree_get_root_path(worktree),
7427 pe->path) == -1) {
7428 error = got_error_from_errno("asprintf");
7429 goto done;
7431 if (lstat(ondisk_path, &sb) == -1) {
7432 if (errno == ENOENT) {
7433 free(ondisk_path);
7434 continue;
7436 error = got_error_from_errno2("lstat",
7437 ondisk_path);
7438 free(ondisk_path);
7439 goto done;
7441 free(ondisk_path);
7442 if (S_ISDIR(sb.st_mode)) {
7443 error = got_error_msg(GOT_ERR_BAD_PATH,
7444 "reverting directories requires -R option");
7445 goto done;
7450 cpa.patch_script_file = patch_script_file;
7451 cpa.action = "revert";
7452 error = got_worktree_revert(worktree, &paths, revert_progress, NULL,
7453 pflag ? choose_patch : NULL, &cpa, repo);
7455 error = rm_logmsg_ref(worktree, repo);
7456 done:
7457 if (patch_script_file && fclose(patch_script_file) == EOF &&
7458 error == NULL)
7459 error = got_error_from_errno2("fclose", patch_script_path);
7460 if (repo) {
7461 const struct got_error *close_err = got_repo_close(repo);
7462 if (error == NULL)
7463 error = close_err;
7465 if (worktree)
7466 got_worktree_close(worktree);
7467 if (pack_fds) {
7468 const struct got_error *pack_err =
7469 got_repo_pack_fds_close(pack_fds);
7470 if (error == NULL)
7471 error = pack_err;
7473 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
7474 free(path);
7475 free(cwd);
7476 return error;
7479 __dead static void
7480 usage_commit(void)
7482 fprintf(stderr, "usage: %s commit [-CNnS] [-A author] [-F path] "
7483 "[-m message] [path ...]\n", getprogname());
7484 exit(1);
7487 struct collect_commit_logmsg_arg {
7488 const char *cmdline_log;
7489 const char *prepared_log;
7490 const char *merged_log;
7491 int non_interactive;
7492 const char *editor;
7493 const char *worktree_path;
7494 const char *repo_path;
7495 const char *dial_proto;
7496 char *logmsg_path;
7499 static const struct got_error *
7500 read_prepared_logmsg(char **logmsg, const char *path)
7502 const struct got_error *err = NULL;
7503 FILE *f = NULL;
7504 struct stat sb;
7505 size_t r;
7507 *logmsg = NULL;
7508 memset(&sb, 0, sizeof(sb));
7510 f = fopen(path, "re");
7511 if (f == NULL)
7512 return got_error_from_errno2("fopen", path);
7514 if (fstat(fileno(f), &sb) == -1) {
7515 err = got_error_from_errno2("fstat", path);
7516 goto done;
7518 if (sb.st_size == 0) {
7519 err = got_error(GOT_ERR_COMMIT_MSG_EMPTY);
7520 goto done;
7523 *logmsg = malloc(sb.st_size + 1);
7524 if (*logmsg == NULL) {
7525 err = got_error_from_errno("malloc");
7526 goto done;
7529 r = fread(*logmsg, 1, sb.st_size, f);
7530 if (r != sb.st_size) {
7531 if (ferror(f))
7532 err = got_error_from_errno2("fread", path);
7533 else
7534 err = got_error(GOT_ERR_IO);
7535 goto done;
7537 (*logmsg)[sb.st_size] = '\0';
7538 done:
7539 if (fclose(f) == EOF && err == NULL)
7540 err = got_error_from_errno2("fclose", path);
7541 if (err) {
7542 free(*logmsg);
7543 *logmsg = NULL;
7545 return err;
7548 static const struct got_error *
7549 collect_commit_logmsg(struct got_pathlist_head *commitable_paths,
7550 const char *diff_path, char **logmsg, void *arg)
7552 char *initial_content = NULL;
7553 struct got_pathlist_entry *pe;
7554 const struct got_error *err = NULL;
7555 char *template = NULL;
7556 char *prepared_msg = NULL, *merged_msg = NULL;
7557 struct collect_commit_logmsg_arg *a = arg;
7558 int initial_content_len;
7559 int fd = -1;
7560 size_t len;
7562 /* if a message was specified on the command line, just use it */
7563 if (a->cmdline_log != NULL && *a->cmdline_log != '\0') {
7564 len = strlen(a->cmdline_log) + 1;
7565 *logmsg = malloc(len + 1);
7566 if (*logmsg == NULL)
7567 return got_error_from_errno("malloc");
7568 strlcpy(*logmsg, a->cmdline_log, len);
7569 return NULL;
7570 } else if (a->prepared_log != NULL && a->non_interactive)
7571 return read_prepared_logmsg(logmsg, a->prepared_log);
7573 if (asprintf(&template, "%s/logmsg", a->worktree_path) == -1)
7574 return got_error_from_errno("asprintf");
7576 err = got_opentemp_named_fd(&a->logmsg_path, &fd, template, "");
7577 if (err)
7578 goto done;
7580 if (a->prepared_log) {
7581 err = read_prepared_logmsg(&prepared_msg, a->prepared_log);
7582 if (err)
7583 goto done;
7584 } else if (a->merged_log) {
7585 err = read_prepared_logmsg(&merged_msg, a->merged_log);
7586 if (err)
7587 goto done;
7590 initial_content_len = asprintf(&initial_content,
7591 "%s%s\n# changes to be committed:\n",
7592 prepared_msg ? prepared_msg : "",
7593 merged_msg ? merged_msg : "");
7594 if (initial_content_len == -1) {
7595 err = got_error_from_errno("asprintf");
7596 goto done;
7599 if (write(fd, initial_content, initial_content_len) == -1) {
7600 err = got_error_from_errno2("write", a->logmsg_path);
7601 goto done;
7604 TAILQ_FOREACH(pe, commitable_paths, entry) {
7605 struct got_commitable *ct = pe->data;
7606 dprintf(fd, "# %c %s\n",
7607 got_commitable_get_status(ct),
7608 got_commitable_get_path(ct));
7611 if (diff_path) {
7612 dprintf(fd, "# detailed changes can be viewed in %s\n",
7613 diff_path);
7616 if (close(fd) == -1) {
7617 err = got_error_from_errno2("close", a->logmsg_path);
7618 goto done;
7620 fd = -1;
7622 err = edit_logmsg(logmsg, a->editor, a->logmsg_path, initial_content,
7623 initial_content_len, a->prepared_log ? 0 : 1);
7624 done:
7625 free(initial_content);
7626 free(template);
7627 free(prepared_msg);
7628 free(merged_msg);
7630 if (fd != -1 && close(fd) == -1 && err == NULL)
7631 err = got_error_from_errno2("close", a->logmsg_path);
7633 /* Editor is done; we can now apply unveil(2) */
7634 if (err == NULL)
7635 err = got_dial_apply_unveil(a->dial_proto);
7636 if (err == NULL)
7637 err = apply_unveil(a->repo_path, 0, a->worktree_path);
7638 if (err) {
7639 free(*logmsg);
7640 *logmsg = NULL;
7642 return err;
7645 static const struct got_error *
7646 cat_logmsg(FILE *f, struct got_commit_object *commit, const char *idstr,
7647 const char *type, int has_content)
7649 const struct got_error *err = NULL;
7650 char *logmsg = NULL;
7652 err = got_object_commit_get_logmsg(&logmsg, commit);
7653 if (err)
7654 return err;
7656 if (fprintf(f, "%s# log message of %s commit %s:%s",
7657 has_content ? "\n" : "", type, idstr, logmsg) < 0)
7658 err = got_ferror(f, GOT_ERR_IO);
7660 free(logmsg);
7661 return err;
7665 * Lookup "logmsg" references of backed-out and cherrypicked commits
7666 * belonging to the current work tree. If found, and the worktree has
7667 * at least one modified file that was changed in the referenced commit,
7668 * add its log message to a new temporary file at *logmsg_path.
7669 * Add all refs found to matched_refs to be scheduled for removal on
7670 * successful commit.
7672 static const struct got_error *
7673 lookup_logmsg_ref(char **logmsg_path, struct got_pathlist_head *paths,
7674 struct got_reflist_head *matched_refs, struct got_worktree *worktree,
7675 struct got_repository *repo)
7677 const struct got_error *err;
7678 struct got_commit_object *commit = NULL;
7679 struct got_object_id *id = NULL;
7680 struct got_reflist_head refs;
7681 struct got_reflist_entry *re, *re_match;
7682 FILE *f = NULL;
7683 char *uuidstr = NULL;
7684 int added_logmsg = 0;
7686 TAILQ_INIT(&refs);
7688 *logmsg_path = NULL;
7690 err = got_worktree_get_uuid(&uuidstr, worktree);
7691 if (err)
7692 goto done;
7694 err = got_ref_list(&refs, repo, "refs/got/worktree",
7695 got_ref_cmp_by_name, repo);
7696 if (err)
7697 goto done;
7699 TAILQ_FOREACH(re, &refs, entry) {
7700 const char *refname, *type;
7701 struct wt_commitable_path_arg wcpa;
7702 int add_logmsg = 0;
7704 refname = got_ref_get_name(re->ref);
7706 if (strncmp(refname, GOT_WORKTREE_CHERRYPICK_REF_PREFIX,
7707 GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN) == 0) {
7708 refname += GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN + 1;
7709 type = "cherrypicked";
7710 } else if (strncmp(refname, GOT_WORKTREE_BACKOUT_REF_PREFIX,
7711 GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN) == 0) {
7712 refname += GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN + 1;
7713 type = "backed-out";
7714 } else
7715 continue;
7717 if (strncmp(refname, uuidstr, GOT_WORKTREE_UUID_STRLEN) == 0)
7718 refname += GOT_WORKTREE_UUID_STRLEN + 1; /* skip '-' */
7719 else
7720 continue;
7722 err = got_repo_match_object_id(&id, NULL, refname,
7723 GOT_OBJ_TYPE_COMMIT, NULL, repo);
7724 if (err)
7725 goto done;
7727 err = got_object_open_as_commit(&commit, repo, id);
7728 if (err)
7729 goto done;
7731 wcpa.commit_paths = paths;
7732 wcpa.has_changes = &add_logmsg;
7734 err = commit_path_changed_in_worktree(&wcpa, id,
7735 worktree, repo);
7736 if (err)
7737 goto done;
7739 if (add_logmsg) {
7740 if (f == NULL) {
7741 err = got_opentemp_named(logmsg_path, &f,
7742 "got-commit-logmsg", "");
7743 if (err)
7744 goto done;
7746 err = cat_logmsg(f, commit, refname, type,
7747 added_logmsg);
7748 if (err)
7749 goto done;
7750 if (!added_logmsg)
7751 ++added_logmsg;
7753 err = got_reflist_entry_dup(&re_match, re);
7754 if (err)
7755 goto done;
7756 TAILQ_INSERT_HEAD(matched_refs, re_match, entry);
7759 got_object_commit_close(commit);
7760 commit = NULL;
7761 free(id);
7762 id = NULL;
7765 done:
7766 free(id);
7767 free(uuidstr);
7768 got_ref_list_free(&refs);
7769 if (commit)
7770 got_object_commit_close(commit);
7771 if (f && fclose(f) == EOF && err == NULL)
7772 err = got_error_from_errno("fclose");
7773 if (!added_logmsg) {
7774 if (*logmsg_path && unlink(*logmsg_path) != 0 && err == NULL)
7775 err = got_error_from_errno2("unlink", *logmsg_path);
7776 *logmsg_path = NULL;
7778 return err;
7781 static const struct got_error *
7782 cmd_commit(int argc, char *argv[])
7784 const struct got_error *error = NULL;
7785 struct got_worktree *worktree = NULL;
7786 struct got_repository *repo = NULL;
7787 char *cwd = NULL, *id_str = NULL;
7788 struct got_object_id *id = NULL;
7789 const char *logmsg = NULL;
7790 char *prepared_logmsg = NULL, *merged_logmsg = NULL;
7791 struct collect_commit_logmsg_arg cl_arg;
7792 const char *author = NULL;
7793 char *gitconfig_path = NULL, *editor = NULL, *committer = NULL;
7794 int ch, rebase_in_progress, histedit_in_progress, preserve_logmsg = 0;
7795 int allow_bad_symlinks = 0, non_interactive = 0, merge_in_progress = 0;
7796 int show_diff = 1, commit_conflicts = 0;
7797 struct got_pathlist_head paths;
7798 struct got_reflist_head refs;
7799 struct got_reflist_entry *re;
7800 int *pack_fds = NULL;
7801 const struct got_gotconfig *repo_conf = NULL, *worktree_conf = NULL;
7802 const struct got_remote_repo *remotes, *remote = NULL;
7803 int nremotes;
7804 char *proto = NULL, *host = NULL, *port = NULL;
7805 char *repo_name = NULL, *server_path = NULL;
7806 const char *remote_name;
7807 int verbosity = 0;
7808 int i;
7810 TAILQ_INIT(&refs);
7811 TAILQ_INIT(&paths);
7812 cl_arg.logmsg_path = NULL;
7814 #ifndef PROFILE
7815 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
7816 "unveil", NULL) == -1)
7817 err(1, "pledge");
7818 #endif
7820 while ((ch = getopt(argc, argv, "A:CF:m:NnS")) != -1) {
7821 switch (ch) {
7822 case 'A':
7823 author = optarg;
7824 error = valid_author(author);
7825 if (error)
7826 return error;
7827 break;
7828 case 'C':
7829 commit_conflicts = 1;
7830 break;
7831 case 'F':
7832 if (logmsg != NULL)
7833 option_conflict('F', 'm');
7834 prepared_logmsg = realpath(optarg, NULL);
7835 if (prepared_logmsg == NULL)
7836 return got_error_from_errno2("realpath",
7837 optarg);
7838 break;
7839 case 'm':
7840 if (prepared_logmsg)
7841 option_conflict('m', 'F');
7842 logmsg = optarg;
7843 break;
7844 case 'N':
7845 non_interactive = 1;
7846 break;
7847 case 'n':
7848 show_diff = 0;
7849 break;
7850 case 'S':
7851 allow_bad_symlinks = 1;
7852 break;
7853 default:
7854 usage_commit();
7855 /* NOTREACHED */
7859 argc -= optind;
7860 argv += optind;
7862 cwd = getcwd(NULL, 0);
7863 if (cwd == NULL) {
7864 error = got_error_from_errno("getcwd");
7865 goto done;
7868 error = got_repo_pack_fds_open(&pack_fds);
7869 if (error != NULL)
7870 goto done;
7872 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_CVG_DIR);
7873 if (error) {
7874 if (error->code == GOT_ERR_NOT_WORKTREE)
7875 error = wrap_not_worktree_error(error, "commit", cwd);
7876 goto done;
7879 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
7880 if (error)
7881 goto done;
7882 if (rebase_in_progress) {
7883 error = got_error(GOT_ERR_REBASING);
7884 goto done;
7887 error = got_worktree_histedit_in_progress(&histedit_in_progress,
7888 worktree);
7889 if (error)
7890 goto done;
7892 error = get_gitconfig_path(&gitconfig_path);
7893 if (error)
7894 goto done;
7895 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
7896 gitconfig_path, pack_fds);
7897 if (error != NULL)
7898 goto done;
7900 error = got_worktree_merge_in_progress(&merge_in_progress, worktree, repo);
7901 if (error)
7902 goto done;
7903 if (merge_in_progress) {
7904 error = got_error(GOT_ERR_MERGE_BUSY);
7905 goto done;
7908 error = get_author(&committer, repo, worktree);
7909 if (error)
7910 goto done;
7912 if (author == NULL)
7913 author = committer;
7915 remote_name = GOT_SEND_DEFAULT_REMOTE_NAME;
7916 worktree_conf = got_worktree_get_gotconfig(worktree);
7917 if (worktree_conf) {
7918 got_gotconfig_get_remotes(&nremotes, &remotes,
7919 worktree_conf);
7920 for (i = 0; i < nremotes; i++) {
7921 if (strcmp(remotes[i].name, remote_name) == 0) {
7922 remote = &remotes[i];
7923 break;
7927 if (remote == NULL) {
7928 repo_conf = got_repo_get_gotconfig(repo);
7929 if (repo_conf) {
7930 got_gotconfig_get_remotes(&nremotes, &remotes,
7931 repo_conf);
7932 for (i = 0; i < nremotes; i++) {
7933 if (strcmp(remotes[i].name, remote_name) == 0) {
7934 remote = &remotes[i];
7935 break;
7940 if (remote == NULL) {
7941 got_repo_get_gitconfig_remotes(&nremotes, &remotes, repo);
7942 for (i = 0; i < nremotes; i++) {
7943 if (strcmp(remotes[i].name, remote_name) == 0) {
7944 remote = &remotes[i];
7945 break;
7949 if (remote == NULL) {
7950 error = got_error_path(remote_name, GOT_ERR_NO_REMOTE);
7951 goto done;
7954 error = got_dial_parse_uri(&proto, &host, &port, &server_path,
7955 &repo_name, remote->fetch_url);
7956 if (error)
7957 goto done;
7959 if (strcmp(proto, "git") == 0) {
7960 #ifndef PROFILE
7961 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
7962 "sendfd dns inet unveil", NULL) == -1)
7963 err(1, "pledge");
7964 #endif
7965 } else if (strcmp(proto, "git+ssh") == 0 ||
7966 strcmp(proto, "ssh") == 0) {
7967 #ifndef PROFILE
7968 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
7969 "sendfd unveil", NULL) == -1)
7970 err(1, "pledge");
7971 #endif
7972 } else if (strcmp(proto, "http") == 0 ||
7973 strcmp(proto, "git+http") == 0) {
7974 error = got_error_path(proto, GOT_ERR_NOT_IMPL);
7975 goto done;
7976 } else {
7977 error = got_error_path(proto, GOT_ERR_BAD_PROTO);
7978 goto done;
7982 /*if (verbosity >= 0) {
7983 printf("Connecting to \"%s\" %s://%s%s%s%s%s\n",
7984 remote->name, proto, host,
7985 port ? ":" : "", port ? port : "",
7986 *server_path == '/' ? "" : "/", server_path);
7987 }*/
7990 * unveil(2) traverses exec(2); if an editor is used we have
7991 * to apply unveil after the log message has been written during
7992 * the callback.
7994 if (logmsg == NULL || strlen(logmsg) == 0)
7995 error = get_editor(&editor);
7996 else {
7997 error = got_dial_apply_unveil(proto);
7998 if (error)
7999 goto done;
8000 error = apply_unveil(got_repo_get_path(repo), 0,
8001 got_worktree_get_root_path(worktree));
8003 if (error)
8004 goto done;
8006 if (prepared_logmsg == NULL) {
8007 error = lookup_logmsg_ref(&merged_logmsg,
8008 argc > 0 ? &paths : NULL, &refs, worktree, repo);
8009 if (error)
8010 goto done;
8013 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
8014 if (error)
8015 goto done;
8017 cl_arg.editor = editor;
8018 cl_arg.cmdline_log = logmsg;
8019 cl_arg.prepared_log = prepared_logmsg;
8020 cl_arg.merged_log = merged_logmsg;
8021 cl_arg.non_interactive = non_interactive;
8022 cl_arg.worktree_path = got_worktree_get_root_path(worktree);
8023 cl_arg.repo_path = got_repo_get_path(repo);
8024 cl_arg.dial_proto = proto;
8025 error = got_worktree_cvg_commit(&id, worktree, &paths, author,
8026 committer, allow_bad_symlinks, show_diff, commit_conflicts,
8027 collect_commit_logmsg, &cl_arg, print_status, NULL, proto, host,
8028 port, server_path, verbosity, remote, check_cancelled, repo);
8029 if (error) {
8030 if (error->code != GOT_ERR_COMMIT_MSG_EMPTY &&
8031 cl_arg.logmsg_path != NULL)
8032 preserve_logmsg = 1;
8033 goto done;
8036 error = got_object_id_str(&id_str, id);
8037 if (error)
8038 goto done;
8039 printf("Created commit %s\n", id_str);
8041 TAILQ_FOREACH(re, &refs, entry) {
8042 error = got_ref_delete(re->ref, repo);
8043 if (error)
8044 goto done;
8047 done:
8048 if (preserve_logmsg) {
8049 fprintf(stderr, "%s: log message preserved in %s\n",
8050 getprogname(), cl_arg.logmsg_path);
8051 } else if (cl_arg.logmsg_path && unlink(cl_arg.logmsg_path) == -1 &&
8052 error == NULL)
8053 error = got_error_from_errno2("unlink", cl_arg.logmsg_path);
8054 free(cl_arg.logmsg_path);
8055 if (merged_logmsg && unlink(merged_logmsg) == -1 && error == NULL)
8056 error = got_error_from_errno2("unlink", merged_logmsg);
8057 free(merged_logmsg);
8058 if (repo) {
8059 const struct got_error *close_err = got_repo_close(repo);
8060 if (error == NULL)
8061 error = close_err;
8063 if (worktree)
8064 got_worktree_close(worktree);
8065 if (pack_fds) {
8066 const struct got_error *pack_err =
8067 got_repo_pack_fds_close(pack_fds);
8068 if (error == NULL)
8069 error = pack_err;
8071 got_ref_list_free(&refs);
8072 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
8073 free(cwd);
8074 free(id_str);
8075 free(gitconfig_path);
8076 free(editor);
8077 free(committer);
8078 free(prepared_logmsg);
8079 return error;
8083 * Print and if delete is set delete all ref_prefix references.
8084 * If wanted_ref is not NULL, only print or delete this reference.
8086 static const struct got_error *
8087 process_logmsg_refs(const char *ref_prefix, size_t prefix_len,
8088 const char *wanted_ref, int delete, struct got_worktree *worktree,
8089 struct got_repository *repo)
8091 const struct got_error *err;
8092 struct got_pathlist_head paths;
8093 struct got_reflist_head refs;
8094 struct got_reflist_entry *re;
8095 struct got_reflist_object_id_map *refs_idmap = NULL;
8096 struct got_commit_object *commit = NULL;
8097 struct got_object_id *id = NULL;
8098 const char *header_prefix;
8099 char *uuidstr = NULL;
8100 int found = 0;
8102 TAILQ_INIT(&refs);
8103 TAILQ_INIT(&paths);
8105 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, repo);
8106 if (err)
8107 goto done;
8109 err = got_reflist_object_id_map_create(&refs_idmap, &refs, repo);
8110 if (err)
8111 goto done;
8113 if (worktree != NULL) {
8114 err = got_worktree_get_uuid(&uuidstr, worktree);
8115 if (err)
8116 goto done;
8119 if (wanted_ref) {
8120 if (strncmp(wanted_ref, "refs/heads/", 11) == 0)
8121 wanted_ref += 11;
8124 if (strcmp(ref_prefix, GOT_WORKTREE_BACKOUT_REF_PREFIX) == 0)
8125 header_prefix = "backout";
8126 else
8127 header_prefix = "cherrypick";
8129 TAILQ_FOREACH(re, &refs, entry) {
8130 const char *refname, *wt;
8132 refname = got_ref_get_name(re->ref);
8134 err = check_cancelled(NULL);
8135 if (err)
8136 goto done;
8138 if (strncmp(refname, ref_prefix, prefix_len) == 0)
8139 refname += prefix_len + 1; /* skip '-' delimiter */
8140 else
8141 continue;
8143 wt = refname;
8145 if (worktree == NULL || strncmp(refname, uuidstr,
8146 GOT_WORKTREE_UUID_STRLEN) == 0)
8147 refname += GOT_WORKTREE_UUID_STRLEN + 1; /* skip '-' */
8148 else
8149 continue;
8151 err = got_repo_match_object_id(&id, NULL, refname,
8152 GOT_OBJ_TYPE_COMMIT, NULL, repo);
8153 if (err)
8154 goto done;
8156 err = got_object_open_as_commit(&commit, repo, id);
8157 if (err)
8158 goto done;
8160 if (wanted_ref)
8161 found = strncmp(wanted_ref, refname,
8162 strlen(wanted_ref)) == 0;
8163 if (wanted_ref && !found) {
8164 struct got_reflist_head *ci_refs;
8166 ci_refs = got_reflist_object_id_map_lookup(refs_idmap,
8167 id);
8169 if (ci_refs) {
8170 char *refs_str = NULL;
8171 char const *r = NULL;
8173 err = build_refs_str(&refs_str, ci_refs, id,
8174 repo, 1);
8175 if (err)
8176 goto done;
8178 r = refs_str;
8179 while (r) {
8180 if (strncmp(r, wanted_ref,
8181 strlen(wanted_ref)) == 0) {
8182 found = 1;
8183 break;
8185 r = strchr(r, ' ');
8186 if (r)
8187 ++r;
8189 free(refs_str);
8193 if (wanted_ref == NULL || found) {
8194 if (delete) {
8195 err = got_ref_delete(re->ref, repo);
8196 if (err)
8197 goto done;
8198 printf("Deleted: ");
8199 err = print_commit_oneline(commit, id, repo,
8200 refs_idmap);
8201 } else {
8203 * Print paths modified by commit to help
8204 * associate commits with worktree changes.
8206 err = get_changed_paths(&paths, commit,
8207 repo, NULL);
8208 if (err)
8209 goto done;
8211 err = print_commit(commit, id, repo, NULL,
8212 &paths, NULL, 0, 0, refs_idmap, NULL,
8213 header_prefix);
8214 got_pathlist_free(&paths,
8215 GOT_PATHLIST_FREE_ALL);
8217 if (worktree == NULL)
8218 printf("work tree: %.*s\n\n",
8219 GOT_WORKTREE_UUID_STRLEN, wt);
8221 if (err || found)
8222 goto done;
8225 got_object_commit_close(commit);
8226 commit = NULL;
8227 free(id);
8228 id = NULL;
8231 if (wanted_ref != NULL && !found)
8232 err = got_error_fmt(GOT_ERR_NOT_REF, "%s", wanted_ref);
8234 done:
8235 free(id);
8236 free(uuidstr);
8237 got_ref_list_free(&refs);
8238 got_pathlist_free(&paths, GOT_PATHLIST_FREE_ALL);
8239 if (refs_idmap)
8240 got_reflist_object_id_map_free(refs_idmap);
8241 if (commit)
8242 got_object_commit_close(commit);
8243 return err;
8247 * Create new temp "logmsg" ref of the backed-out or cherrypicked commit
8248 * identified by id for log messages to prepopulate the editor on commit.
8250 static const struct got_error *
8251 logmsg_ref(struct got_object_id *id, const char *prefix,
8252 struct got_worktree *worktree, struct got_repository *repo)
8254 const struct got_error *err = NULL;
8255 char *idstr, *ref = NULL, *refname = NULL;
8256 int histedit_in_progress;
8257 int rebase_in_progress, merge_in_progress;
8260 * Silenty refuse to create merge reference if any histedit, merge,
8261 * or rebase operation is in progress.
8263 err = got_worktree_histedit_in_progress(&histedit_in_progress,
8264 worktree);
8265 if (err)
8266 return err;
8267 if (histedit_in_progress)
8268 return NULL;
8270 err = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
8271 if (err)
8272 return err;
8273 if (rebase_in_progress)
8274 return NULL;
8276 err = got_worktree_merge_in_progress(&merge_in_progress, worktree,
8277 repo);
8278 if (err)
8279 return err;
8280 if (merge_in_progress)
8281 return NULL;
8283 err = got_object_id_str(&idstr, id);
8284 if (err)
8285 return err;
8287 err = got_worktree_get_logmsg_ref_name(&refname, worktree, prefix);
8288 if (err)
8289 goto done;
8291 if (asprintf(&ref, "%s-%s", refname, idstr) == -1) {
8292 err = got_error_from_errno("asprintf");
8293 goto done;
8296 err = create_ref(ref, got_worktree_get_base_commit_id(worktree),
8297 -1, repo);
8298 done:
8299 free(ref);
8300 free(idstr);
8301 free(refname);
8302 return err;
8305 __dead static void
8306 usage_cherrypick(void)
8308 fprintf(stderr, "usage: %s cherrypick [-lX] [commit-id]\n",
8309 getprogname());
8310 exit(1);
8313 static const struct got_error *
8314 cmd_cherrypick(int argc, char *argv[])
8316 const struct got_error *error = NULL;
8317 struct got_worktree *worktree = NULL;
8318 struct got_repository *repo = NULL;
8319 char *cwd = NULL, *commit_id_str = NULL;
8320 struct got_object_id *commit_id = NULL;
8321 struct got_commit_object *commit = NULL;
8322 struct got_object_qid *pid;
8323 int ch, list_refs = 0, remove_refs = 0;
8324 struct got_update_progress_arg upa;
8325 int *pack_fds = NULL;
8327 #ifndef PROFILE
8328 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
8329 "unveil", NULL) == -1)
8330 err(1, "pledge");
8331 #endif
8333 while ((ch = getopt(argc, argv, "lX")) != -1) {
8334 switch (ch) {
8335 case 'l':
8336 list_refs = 1;
8337 break;
8338 case 'X':
8339 remove_refs = 1;
8340 break;
8341 default:
8342 usage_cherrypick();
8343 /* NOTREACHED */
8347 argc -= optind;
8348 argv += optind;
8350 if (list_refs || remove_refs) {
8351 if (argc != 0 && argc != 1)
8352 usage_cherrypick();
8353 } else if (argc != 1)
8354 usage_cherrypick();
8355 if (list_refs && remove_refs)
8356 option_conflict('l', 'X');
8358 cwd = getcwd(NULL, 0);
8359 if (cwd == NULL) {
8360 error = got_error_from_errno("getcwd");
8361 goto done;
8364 error = got_repo_pack_fds_open(&pack_fds);
8365 if (error != NULL)
8366 goto done;
8368 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_CVG_DIR);
8369 if (error) {
8370 if (list_refs || remove_refs) {
8371 if (error->code != GOT_ERR_NOT_WORKTREE)
8372 goto done;
8373 } else {
8374 if (error->code == GOT_ERR_NOT_WORKTREE)
8375 error = wrap_not_worktree_error(error,
8376 "cherrypick", cwd);
8377 goto done;
8381 error = got_repo_open(&repo,
8382 worktree ? got_worktree_get_repo_path(worktree) : cwd,
8383 NULL, pack_fds);
8384 if (error != NULL)
8385 goto done;
8387 error = apply_unveil(got_repo_get_path(repo), 0,
8388 worktree ? got_worktree_get_root_path(worktree) : NULL);
8389 if (error)
8390 goto done;
8392 if (list_refs || remove_refs) {
8393 error = process_logmsg_refs(GOT_WORKTREE_CHERRYPICK_REF_PREFIX,
8394 GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN,
8395 argc == 1 ? argv[0] : NULL, remove_refs, worktree, repo);
8396 goto done;
8399 error = got_repo_match_object_id(&commit_id, NULL, argv[0],
8400 GOT_OBJ_TYPE_COMMIT, NULL, repo);
8401 if (error)
8402 goto done;
8403 error = got_object_id_str(&commit_id_str, commit_id);
8404 if (error)
8405 goto done;
8407 error = got_object_open_as_commit(&commit, repo, commit_id);
8408 if (error)
8409 goto done;
8410 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
8411 memset(&upa, 0, sizeof(upa));
8412 error = got_worktree_merge_files(worktree, pid ? &pid->id : NULL,
8413 commit_id, repo, update_progress, &upa, check_cancelled,
8414 NULL);
8415 if (error != NULL)
8416 goto done;
8418 if (upa.did_something) {
8419 error = logmsg_ref(commit_id,
8420 GOT_WORKTREE_CHERRYPICK_REF_PREFIX, worktree, repo);
8421 if (error)
8422 goto done;
8423 printf("Merged commit %s\n", commit_id_str);
8425 print_merge_progress_stats(&upa);
8426 done:
8427 free(cwd);
8428 if (commit)
8429 got_object_commit_close(commit);
8430 free(commit_id_str);
8431 if (worktree)
8432 got_worktree_close(worktree);
8433 if (repo) {
8434 const struct got_error *close_err = got_repo_close(repo);
8435 if (error == NULL)
8436 error = close_err;
8438 if (pack_fds) {
8439 const struct got_error *pack_err =
8440 got_repo_pack_fds_close(pack_fds);
8441 if (error == NULL)
8442 error = pack_err;
8445 return error;
8448 __dead static void
8449 usage_backout(void)
8451 fprintf(stderr, "usage: %s backout [-lX] [commit-id]\n", getprogname());
8452 exit(1);
8455 static const struct got_error *
8456 cmd_backout(int argc, char *argv[])
8458 const struct got_error *error = NULL;
8459 struct got_worktree *worktree = NULL;
8460 struct got_repository *repo = NULL;
8461 char *cwd = NULL, *commit_id_str = NULL;
8462 struct got_object_id *commit_id = NULL;
8463 struct got_commit_object *commit = NULL;
8464 struct got_object_qid *pid;
8465 int ch, list_refs = 0, remove_refs = 0;
8466 struct got_update_progress_arg upa;
8467 int *pack_fds = NULL;
8469 #ifndef PROFILE
8470 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
8471 "unveil", NULL) == -1)
8472 err(1, "pledge");
8473 #endif
8475 while ((ch = getopt(argc, argv, "lX")) != -1) {
8476 switch (ch) {
8477 case 'l':
8478 list_refs = 1;
8479 break;
8480 case 'X':
8481 remove_refs = 1;
8482 break;
8483 default:
8484 usage_backout();
8485 /* NOTREACHED */
8489 argc -= optind;
8490 argv += optind;
8492 if (list_refs || remove_refs) {
8493 if (argc != 0 && argc != 1)
8494 usage_backout();
8495 } else if (argc != 1)
8496 usage_backout();
8497 if (list_refs && remove_refs)
8498 option_conflict('l', 'X');
8500 cwd = getcwd(NULL, 0);
8501 if (cwd == NULL) {
8502 error = got_error_from_errno("getcwd");
8503 goto done;
8506 error = got_repo_pack_fds_open(&pack_fds);
8507 if (error != NULL)
8508 goto done;
8510 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_CVG_DIR);
8511 if (error) {
8512 if (list_refs || remove_refs) {
8513 if (error->code != GOT_ERR_NOT_WORKTREE)
8514 goto done;
8515 } else {
8516 if (error->code == GOT_ERR_NOT_WORKTREE)
8517 error = wrap_not_worktree_error(error,
8518 "backout", cwd);
8519 goto done;
8523 error = got_repo_open(&repo,
8524 worktree ? got_worktree_get_repo_path(worktree) : cwd,
8525 NULL, pack_fds);
8526 if (error != NULL)
8527 goto done;
8529 error = apply_unveil(got_repo_get_path(repo), 0,
8530 worktree ? got_worktree_get_root_path(worktree) : NULL);
8531 if (error)
8532 goto done;
8534 if (list_refs || remove_refs) {
8535 error = process_logmsg_refs(GOT_WORKTREE_BACKOUT_REF_PREFIX,
8536 GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN,
8537 argc == 1 ? argv[0] : NULL, remove_refs, worktree, repo);
8538 goto done;
8541 error = got_repo_match_object_id(&commit_id, NULL, argv[0],
8542 GOT_OBJ_TYPE_COMMIT, NULL, repo);
8543 if (error)
8544 goto done;
8545 error = got_object_id_str(&commit_id_str, commit_id);
8546 if (error)
8547 goto done;
8549 error = got_object_open_as_commit(&commit, repo, commit_id);
8550 if (error)
8551 goto done;
8552 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
8553 if (pid == NULL) {
8554 error = got_error(GOT_ERR_ROOT_COMMIT);
8555 goto done;
8558 memset(&upa, 0, sizeof(upa));
8559 error = got_worktree_merge_files(worktree, commit_id, &pid->id,
8560 repo, update_progress, &upa, check_cancelled, NULL);
8561 if (error != NULL)
8562 goto done;
8564 if (upa.did_something) {
8565 error = logmsg_ref(commit_id, GOT_WORKTREE_BACKOUT_REF_PREFIX,
8566 worktree, repo);
8567 if (error)
8568 goto done;
8569 printf("Backed out commit %s\n", commit_id_str);
8571 print_merge_progress_stats(&upa);
8572 done:
8573 free(cwd);
8574 if (commit)
8575 got_object_commit_close(commit);
8576 free(commit_id_str);
8577 if (worktree)
8578 got_worktree_close(worktree);
8579 if (repo) {
8580 const struct got_error *close_err = got_repo_close(repo);
8581 if (error == NULL)
8582 error = close_err;
8584 if (pack_fds) {
8585 const struct got_error *pack_err =
8586 got_repo_pack_fds_close(pack_fds);
8587 if (error == NULL)
8588 error = pack_err;
8590 return error;
8593 __dead static void
8594 usage_cat(void)
8596 fprintf(stderr, "usage: %s cat [-P] [-c commit] [-r repository-path] "
8597 "arg ...\n", getprogname());
8598 exit(1);
8601 static const struct got_error *
8602 cat_blob(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
8604 const struct got_error *err;
8605 struct got_blob_object *blob;
8606 int fd = -1;
8608 fd = got_opentempfd();
8609 if (fd == -1)
8610 return got_error_from_errno("got_opentempfd");
8612 err = got_object_open_as_blob(&blob, repo, id, 8192, fd);
8613 if (err)
8614 goto done;
8616 err = got_object_blob_dump_to_file(NULL, NULL, NULL, outfile, blob);
8617 done:
8618 if (fd != -1 && close(fd) == -1 && err == NULL)
8619 err = got_error_from_errno("close");
8620 if (blob)
8621 got_object_blob_close(blob);
8622 return err;
8625 static const struct got_error *
8626 cat_tree(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
8628 const struct got_error *err;
8629 struct got_tree_object *tree;
8630 int nentries, i;
8632 err = got_object_open_as_tree(&tree, repo, id);
8633 if (err)
8634 return err;
8636 nentries = got_object_tree_get_nentries(tree);
8637 for (i = 0; i < nentries; i++) {
8638 struct got_tree_entry *te;
8639 char *id_str;
8640 if (sigint_received || sigpipe_received)
8641 break;
8642 te = got_object_tree_get_entry(tree, i);
8643 err = got_object_id_str(&id_str, got_tree_entry_get_id(te));
8644 if (err)
8645 break;
8646 fprintf(outfile, "%s %.7o %s\n", id_str,
8647 got_tree_entry_get_mode(te),
8648 got_tree_entry_get_name(te));
8649 free(id_str);
8652 got_object_tree_close(tree);
8653 return err;
8656 static const struct got_error *
8657 cat_commit(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
8659 const struct got_error *err;
8660 struct got_commit_object *commit;
8661 const struct got_object_id_queue *parent_ids;
8662 struct got_object_qid *pid;
8663 char *id_str = NULL;
8664 const char *logmsg = NULL;
8665 char gmtoff[6];
8667 err = got_object_open_as_commit(&commit, repo, id);
8668 if (err)
8669 return err;
8671 err = got_object_id_str(&id_str, got_object_commit_get_tree_id(commit));
8672 if (err)
8673 goto done;
8675 fprintf(outfile, "%s%s\n", GOT_COMMIT_LABEL_TREE, id_str);
8676 parent_ids = got_object_commit_get_parent_ids(commit);
8677 fprintf(outfile, "numparents %d\n",
8678 got_object_commit_get_nparents(commit));
8679 STAILQ_FOREACH(pid, parent_ids, entry) {
8680 char *pid_str;
8681 err = got_object_id_str(&pid_str, &pid->id);
8682 if (err)
8683 goto done;
8684 fprintf(outfile, "%s%s\n", GOT_COMMIT_LABEL_PARENT, pid_str);
8685 free(pid_str);
8687 got_date_format_gmtoff(gmtoff, sizeof(gmtoff),
8688 got_object_commit_get_author_gmtoff(commit));
8689 fprintf(outfile, "%s%s %lld %s\n", GOT_COMMIT_LABEL_AUTHOR,
8690 got_object_commit_get_author(commit),
8691 (long long)got_object_commit_get_author_time(commit),
8692 gmtoff);
8694 got_date_format_gmtoff(gmtoff, sizeof(gmtoff),
8695 got_object_commit_get_committer_gmtoff(commit));
8696 fprintf(outfile, "%s%s %lld %s\n", GOT_COMMIT_LABEL_COMMITTER,
8697 got_object_commit_get_committer(commit),
8698 (long long)got_object_commit_get_committer_time(commit),
8699 gmtoff);
8701 logmsg = got_object_commit_get_logmsg_raw(commit);
8702 fprintf(outfile, "messagelen %zd\n", strlen(logmsg));
8703 fprintf(outfile, "%s", logmsg);
8704 done:
8705 free(id_str);
8706 got_object_commit_close(commit);
8707 return err;
8710 static const struct got_error *
8711 cat_tag(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
8713 const struct got_error *err;
8714 struct got_tag_object *tag;
8715 char *id_str = NULL;
8716 const char *tagmsg = NULL;
8717 char gmtoff[6];
8719 err = got_object_open_as_tag(&tag, repo, id);
8720 if (err)
8721 return err;
8723 err = got_object_id_str(&id_str, got_object_tag_get_object_id(tag));
8724 if (err)
8725 goto done;
8727 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_OBJECT, id_str);
8729 switch (got_object_tag_get_object_type(tag)) {
8730 case GOT_OBJ_TYPE_BLOB:
8731 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
8732 GOT_OBJ_LABEL_BLOB);
8733 break;
8734 case GOT_OBJ_TYPE_TREE:
8735 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
8736 GOT_OBJ_LABEL_TREE);
8737 break;
8738 case GOT_OBJ_TYPE_COMMIT:
8739 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
8740 GOT_OBJ_LABEL_COMMIT);
8741 break;
8742 case GOT_OBJ_TYPE_TAG:
8743 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
8744 GOT_OBJ_LABEL_TAG);
8745 break;
8746 default:
8747 break;
8750 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TAG,
8751 got_object_tag_get_name(tag));
8753 got_date_format_gmtoff(gmtoff, sizeof(gmtoff),
8754 got_object_tag_get_tagger_gmtoff(tag));
8755 fprintf(outfile, "%s%s %lld %s\n", GOT_TAG_LABEL_TAGGER,
8756 got_object_tag_get_tagger(tag),
8757 (long long)got_object_tag_get_tagger_time(tag),
8758 gmtoff);
8760 tagmsg = got_object_tag_get_message(tag);
8761 fprintf(outfile, "messagelen %zd\n", strlen(tagmsg));
8762 fprintf(outfile, "%s", tagmsg);
8763 done:
8764 free(id_str);
8765 got_object_tag_close(tag);
8766 return err;
8769 static const struct got_error *
8770 cmd_cat(int argc, char *argv[])
8772 const struct got_error *error;
8773 struct got_repository *repo = NULL;
8774 struct got_worktree *worktree = NULL;
8775 char *cwd = NULL, *repo_path = NULL, *label = NULL;
8776 const char *commit_id_str = NULL;
8777 struct got_object_id *id = NULL, *commit_id = NULL;
8778 struct got_commit_object *commit = NULL;
8779 int ch, obj_type, i, force_path = 0;
8780 struct got_reflist_head refs;
8781 int *pack_fds = NULL;
8783 TAILQ_INIT(&refs);
8785 #ifndef PROFILE
8786 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
8787 NULL) == -1)
8788 err(1, "pledge");
8789 #endif
8791 while ((ch = getopt(argc, argv, "c:Pr:")) != -1) {
8792 switch (ch) {
8793 case 'c':
8794 commit_id_str = optarg;
8795 break;
8796 case 'P':
8797 force_path = 1;
8798 break;
8799 case 'r':
8800 repo_path = realpath(optarg, NULL);
8801 if (repo_path == NULL)
8802 return got_error_from_errno2("realpath",
8803 optarg);
8804 got_path_strip_trailing_slashes(repo_path);
8805 break;
8806 default:
8807 usage_cat();
8808 /* NOTREACHED */
8812 argc -= optind;
8813 argv += optind;
8815 cwd = getcwd(NULL, 0);
8816 if (cwd == NULL) {
8817 error = got_error_from_errno("getcwd");
8818 goto done;
8821 error = got_repo_pack_fds_open(&pack_fds);
8822 if (error != NULL)
8823 goto done;
8825 if (repo_path == NULL) {
8826 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_CVG_DIR);
8827 if (error && error->code != GOT_ERR_NOT_WORKTREE)
8828 goto done;
8829 if (worktree) {
8830 repo_path = strdup(
8831 got_worktree_get_repo_path(worktree));
8832 if (repo_path == NULL) {
8833 error = got_error_from_errno("strdup");
8834 goto done;
8837 /* Release work tree lock. */
8838 got_worktree_close(worktree);
8839 worktree = NULL;
8843 if (repo_path == NULL) {
8844 repo_path = strdup(cwd);
8845 if (repo_path == NULL)
8846 return got_error_from_errno("strdup");
8849 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
8850 free(repo_path);
8851 if (error != NULL)
8852 goto done;
8854 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
8855 if (error)
8856 goto done;
8858 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
8859 if (error)
8860 goto done;
8862 if (commit_id_str == NULL)
8863 commit_id_str = GOT_REF_HEAD;
8864 error = got_repo_match_object_id(&commit_id, NULL,
8865 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
8866 if (error)
8867 goto done;
8869 error = got_object_open_as_commit(&commit, repo, commit_id);
8870 if (error)
8871 goto done;
8873 for (i = 0; i < argc; i++) {
8874 if (force_path) {
8875 error = got_object_id_by_path(&id, repo, commit,
8876 argv[i]);
8877 if (error)
8878 break;
8879 } else {
8880 error = got_repo_match_object_id(&id, &label, argv[i],
8881 GOT_OBJ_TYPE_ANY, NULL /* do not resolve tags */,
8882 repo);
8883 if (error) {
8884 if (error->code != GOT_ERR_BAD_OBJ_ID_STR &&
8885 error->code != GOT_ERR_NOT_REF)
8886 break;
8887 error = got_object_id_by_path(&id, repo,
8888 commit, argv[i]);
8889 if (error)
8890 break;
8894 error = got_object_get_type(&obj_type, repo, id);
8895 if (error)
8896 break;
8898 switch (obj_type) {
8899 case GOT_OBJ_TYPE_BLOB:
8900 error = cat_blob(id, repo, stdout);
8901 break;
8902 case GOT_OBJ_TYPE_TREE:
8903 error = cat_tree(id, repo, stdout);
8904 break;
8905 case GOT_OBJ_TYPE_COMMIT:
8906 error = cat_commit(id, repo, stdout);
8907 break;
8908 case GOT_OBJ_TYPE_TAG:
8909 error = cat_tag(id, repo, stdout);
8910 break;
8911 default:
8912 error = got_error(GOT_ERR_OBJ_TYPE);
8913 break;
8915 if (error)
8916 break;
8917 free(label);
8918 label = NULL;
8919 free(id);
8920 id = NULL;
8922 done:
8923 free(label);
8924 free(id);
8925 free(commit_id);
8926 if (commit)
8927 got_object_commit_close(commit);
8928 if (worktree)
8929 got_worktree_close(worktree);
8930 if (repo) {
8931 const struct got_error *close_err = got_repo_close(repo);
8932 if (error == NULL)
8933 error = close_err;
8935 if (pack_fds) {
8936 const struct got_error *pack_err =
8937 got_repo_pack_fds_close(pack_fds);
8938 if (error == NULL)
8939 error = pack_err;
8942 got_ref_list_free(&refs);
8943 return error;
8946 __dead static void
8947 usage_info(void)
8949 fprintf(stderr, "usage: %s info [path ...]\n",
8950 getprogname());
8951 exit(1);
8954 static const struct got_error *
8955 print_path_info(void *arg, const char *path, mode_t mode, time_t mtime,
8956 struct got_object_id *blob_id, struct got_object_id *staged_blob_id,
8957 struct got_object_id *commit_id)
8959 const struct got_error *err = NULL;
8960 char *id_str = NULL;
8961 char datebuf[128];
8962 struct tm mytm, *tm;
8963 struct got_pathlist_head *paths = arg;
8964 struct got_pathlist_entry *pe;
8967 * Clear error indication from any of the path arguments which
8968 * would cause this file index entry to be displayed.
8970 TAILQ_FOREACH(pe, paths, entry) {
8971 if (got_path_cmp(path, pe->path, strlen(path),
8972 pe->path_len) == 0 ||
8973 got_path_is_child(path, pe->path, pe->path_len))
8974 pe->data = NULL; /* no error */
8977 printf(GOT_COMMIT_SEP_STR);
8978 if (S_ISLNK(mode))
8979 printf("symlink: %s\n", path);
8980 else if (S_ISREG(mode)) {
8981 printf("file: %s\n", path);
8982 printf("mode: %o\n", mode & (S_IRWXU | S_IRWXG | S_IRWXO));
8983 } else if (S_ISDIR(mode))
8984 printf("directory: %s\n", path);
8985 else
8986 printf("something: %s\n", path);
8988 tm = localtime_r(&mtime, &mytm);
8989 if (tm == NULL)
8990 return NULL;
8991 if (strftime(datebuf, sizeof(datebuf), "%c %Z", tm) == 0)
8992 return got_error(GOT_ERR_NO_SPACE);
8993 printf("timestamp: %s\n", datebuf);
8995 if (blob_id) {
8996 err = got_object_id_str(&id_str, blob_id);
8997 if (err)
8998 return err;
8999 printf("based on blob: %s\n", id_str);
9000 free(id_str);
9003 if (staged_blob_id) {
9004 err = got_object_id_str(&id_str, staged_blob_id);
9005 if (err)
9006 return err;
9007 printf("based on staged blob: %s\n", id_str);
9008 free(id_str);
9011 if (commit_id) {
9012 err = got_object_id_str(&id_str, commit_id);
9013 if (err)
9014 return err;
9015 printf("based on commit: %s\n", id_str);
9016 free(id_str);
9019 return NULL;
9022 static const struct got_error *
9023 cmd_info(int argc, char *argv[])
9025 const struct got_error *error = NULL;
9026 struct got_worktree *worktree = NULL;
9027 char *cwd = NULL, *id_str = NULL;
9028 struct got_pathlist_head paths;
9029 char *uuidstr = NULL;
9030 int ch, show_files = 0;
9032 TAILQ_INIT(&paths);
9034 #ifndef PROFILE
9035 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
9036 NULL) == -1)
9037 err(1, "pledge");
9038 #endif
9040 while ((ch = getopt(argc, argv, "")) != -1) {
9041 switch (ch) {
9042 default:
9043 usage_info();
9044 /* NOTREACHED */
9048 argc -= optind;
9049 argv += optind;
9051 cwd = getcwd(NULL, 0);
9052 if (cwd == NULL) {
9053 error = got_error_from_errno("getcwd");
9054 goto done;
9057 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_CVG_DIR);
9058 if (error) {
9059 if (error->code == GOT_ERR_NOT_WORKTREE)
9060 error = wrap_not_worktree_error(error, "info", cwd);
9061 goto done;
9064 #ifndef PROFILE
9065 /* Remove "wpath cpath proc exec sendfd" promises. */
9066 if (pledge("stdio rpath flock unveil", NULL) == -1)
9067 err(1, "pledge");
9068 #endif
9069 error = apply_unveil(NULL, 0, got_worktree_get_root_path(worktree));
9070 if (error)
9071 goto done;
9073 if (argc >= 1) {
9074 error = get_worktree_paths_from_argv(&paths, argc, argv,
9075 worktree);
9076 if (error)
9077 goto done;
9078 show_files = 1;
9081 error = got_object_id_str(&id_str,
9082 got_worktree_get_base_commit_id(worktree));
9083 if (error)
9084 goto done;
9086 error = got_worktree_get_uuid(&uuidstr, worktree);
9087 if (error)
9088 goto done;
9090 printf("work tree: %s\n", got_worktree_get_root_path(worktree));
9091 printf("work tree base commit: %s\n", id_str);
9092 printf("work tree path prefix: %s\n",
9093 got_worktree_get_path_prefix(worktree));
9094 printf("work tree branch reference: %s\n",
9095 got_worktree_get_head_ref_name(worktree));
9096 printf("work tree UUID: %s\n", uuidstr);
9097 printf("repository: %s\n", got_worktree_get_repo_path(worktree));
9099 if (show_files) {
9100 struct got_pathlist_entry *pe;
9101 TAILQ_FOREACH(pe, &paths, entry) {
9102 if (pe->path_len == 0)
9103 continue;
9105 * Assume this path will fail. This will be corrected
9106 * in print_path_info() in case the path does suceeed.
9108 pe->data = (void *)got_error(GOT_ERR_BAD_PATH);
9110 error = got_worktree_path_info(worktree, &paths,
9111 print_path_info, &paths, check_cancelled, NULL);
9112 if (error)
9113 goto done;
9114 TAILQ_FOREACH(pe, &paths, entry) {
9115 if (pe->data != NULL) {
9116 const struct got_error *perr;
9118 perr = pe->data;
9119 error = got_error_fmt(perr->code, "%s",
9120 pe->path);
9121 break;
9125 done:
9126 if (worktree)
9127 got_worktree_close(worktree);
9128 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
9129 free(cwd);
9130 free(id_str);
9131 free(uuidstr);
9132 return error;