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 "got_compat.h"
22 #include <sys/time.h>
23 #include <sys/types.h>
24 #include <sys/stat.h>
25 #include <sys/wait.h>
27 #include <err.h>
28 #include <errno.h>
29 #include <fcntl.h>
30 #include <limits.h>
31 #include <locale.h>
32 #include <ctype.h>
33 #include <signal.h>
34 #include <stdio.h>
35 #include <stdlib.h>
36 #include <string.h>
37 #include <unistd.h>
38 #include <libgen.h>
39 #include <time.h>
40 #include <paths.h>
41 #include <regex.h>
42 #include <getopt.h>
44 #include "got_version.h"
45 #include "got_error.h"
46 #include "got_object.h"
47 #include "got_reference.h"
48 #include "got_repository.h"
49 #include "got_path.h"
50 #include "got_cancel.h"
51 #include "got_worktree.h"
52 #include "got_worktree_cvg.h"
53 #include "got_diff.h"
54 #include "got_commit_graph.h"
55 #include "got_fetch.h"
56 #include "got_send.h"
57 #include "got_blame.h"
58 #include "got_privsep.h"
59 #include "got_opentemp.h"
60 #include "got_gotconfig.h"
61 #include "got_dial.h"
62 #include "got_patch.h"
63 #include "got_sigs.h"
64 #include "got_date.h"
66 #ifndef nitems
67 #define nitems(_a) (sizeof((_a)) / sizeof((_a)[0]))
68 #endif
70 #ifndef GOT_DEFAULT_EDITOR
71 #define GOT_DEFAULT_EDITOR "/usr/bin/vi"
72 #endif
74 static volatile sig_atomic_t sigint_received;
75 static volatile sig_atomic_t sigpipe_received;
77 static void
78 catch_sigint(int signo)
79 {
80 sigint_received = 1;
81 }
83 static void
84 catch_sigpipe(int signo)
85 {
86 sigpipe_received = 1;
87 }
90 struct got_cmd {
91 const char *cmd_name;
92 const struct got_error *(*cmd_main)(int, char *[]);
93 void (*cmd_usage)(void);
94 const char *cmd_alias;
95 };
97 __dead static void usage(int, int);
98 __dead static void usage_import(void);
99 __dead static void usage_clone(void);
100 __dead static void usage_checkout(void);
101 __dead static void usage_update(void);
102 __dead static void usage_log(void);
103 __dead static void usage_diff(void);
104 __dead static void usage_blame(void);
105 __dead static void usage_tree(void);
106 __dead static void usage_status(void);
107 __dead static void usage_tag(void);
108 __dead static void usage_add(void);
109 __dead static void usage_remove(void);
110 __dead static void usage_patch(void);
111 __dead static void usage_revert(void);
112 __dead static void usage_commit(void);
113 __dead static void usage_cherrypick(void);
114 __dead static void usage_backout(void);
115 __dead static void usage_cat(void);
116 __dead static void usage_info(void);
118 static const struct got_error* cmd_import(int, char *[]);
119 static const struct got_error* cmd_clone(int, char *[]);
120 static const struct got_error* cmd_checkout(int, char *[]);
121 static const struct got_error* cmd_update(int, char *[]);
122 static const struct got_error* cmd_log(int, char *[]);
123 static const struct got_error* cmd_diff(int, char *[]);
124 static const struct got_error* cmd_blame(int, char *[]);
125 static const struct got_error* cmd_tree(int, char *[]);
126 static const struct got_error* cmd_status(int, char *[]);
127 static const struct got_error* cmd_tag(int, char *[]);
128 static const struct got_error* cmd_add(int, char *[]);
129 static const struct got_error* cmd_remove(int, char *[]);
130 static const struct got_error* cmd_patch(int, char *[]);
131 static const struct got_error* cmd_revert(int, char *[]);
132 static const struct got_error* cmd_commit(int, char *[]);
133 static const struct got_error* cmd_cherrypick(int, char *[]);
134 static const struct got_error* cmd_backout(int, char *[]);
135 static const struct got_error* cmd_cat(int, char *[]);
136 static const struct got_error* cmd_info(int, char *[]);
138 static const struct got_cmd got_commands[] = {
139 { "import", cmd_import, usage_import, "im" },
140 { "clone", cmd_clone, usage_clone, "cl" },
141 { "checkout", cmd_checkout, usage_checkout, "co" },
142 { "update", cmd_update, usage_update, "up" },
143 { "log", cmd_log, usage_log, "" },
144 { "diff", cmd_diff, usage_diff, "di" },
145 { "blame", cmd_blame, usage_blame, "bl" },
146 { "tree", cmd_tree, usage_tree, "tr" },
147 { "status", cmd_status, usage_status, "st" },
148 { "tag", cmd_tag, usage_tag, "" },
149 { "add", cmd_add, usage_add, "" },
150 { "remove", cmd_remove, usage_remove, "rm" },
151 { "patch", cmd_patch, usage_patch, "pa" },
152 { "revert", cmd_revert, usage_revert, "rv" },
153 { "commit", cmd_commit, usage_commit, "ci" },
154 { "cherrypick", cmd_cherrypick, usage_cherrypick, "cy" },
155 { "backout", cmd_backout, usage_backout, "bo" },
156 { "cat", cmd_cat, usage_cat, "" },
157 { "info", cmd_info, usage_info, "" },
158 };
160 static void
161 list_commands(FILE *fp)
163 size_t i;
165 fprintf(fp, "commands:");
166 for (i = 0; i < nitems(got_commands); i++) {
167 const struct got_cmd *cmd = &got_commands[i];
168 fprintf(fp, " %s", cmd->cmd_name);
170 fputc('\n', fp);
173 __dead static void
174 option_conflict(char a, char b)
176 errx(1, "-%c and -%c options are mutually exclusive", a, b);
179 int
180 main(int argc, char *argv[])
182 const struct got_cmd *cmd;
183 size_t i;
184 int ch;
185 int hflag = 0, Vflag = 0;
186 static const struct option longopts[] = {
187 { "version", no_argument, NULL, 'V' },
188 { NULL, 0, NULL, 0 }
189 };
191 setlocale(LC_CTYPE, "");
193 while ((ch = getopt_long(argc, argv, "+hV", longopts, NULL)) != -1) {
194 switch (ch) {
195 case 'h':
196 hflag = 1;
197 break;
198 case 'V':
199 Vflag = 1;
200 break;
201 default:
202 usage(hflag, 1);
203 /* NOTREACHED */
207 argc -= optind;
208 argv += optind;
209 optind = 1;
210 optreset = 1;
212 if (Vflag) {
213 got_version_print_str();
214 return 0;
217 if (argc <= 0)
218 usage(hflag, hflag ? 0 : 1);
220 signal(SIGINT, catch_sigint);
221 signal(SIGPIPE, catch_sigpipe);
223 for (i = 0; i < nitems(got_commands); i++) {
224 const struct got_error *error;
226 cmd = &got_commands[i];
228 if (strcmp(cmd->cmd_name, argv[0]) != 0 &&
229 strcmp(cmd->cmd_alias, argv[0]) != 0)
230 continue;
232 if (hflag)
233 cmd->cmd_usage();
235 error = cmd->cmd_main(argc, argv);
236 if (error && error->code != GOT_ERR_CANCELLED &&
237 error->code != GOT_ERR_PRIVSEP_EXIT &&
238 !(sigpipe_received &&
239 error->code == GOT_ERR_ERRNO && errno == EPIPE) &&
240 !(sigint_received &&
241 error->code == GOT_ERR_ERRNO && errno == EINTR)) {
242 fflush(stdout);
243 fprintf(stderr, "%s: %s\n", getprogname(), error->msg);
244 return 1;
247 return 0;
250 fprintf(stderr, "%s: unknown command '%s'\n", getprogname(), argv[0]);
251 list_commands(stderr);
252 return 1;
255 __dead static void
256 usage(int hflag, int status)
258 FILE *fp = (status == 0) ? stdout : stderr;
260 fprintf(fp, "usage: %s [-hV] command [arg ...]\n",
261 getprogname());
262 if (hflag)
263 list_commands(fp);
264 exit(status);
267 static const struct got_error *
268 get_editor(char **abspath)
270 const struct got_error *err = NULL;
271 const char *editor;
273 *abspath = NULL;
275 editor = getenv("VISUAL");
276 if (editor == NULL)
277 editor = getenv("EDITOR");
279 if (editor) {
280 err = got_path_find_prog(abspath, editor);
281 if (err)
282 return err;
285 if (*abspath == NULL) {
286 *abspath = strdup(GOT_DEFAULT_EDITOR);
287 if (*abspath == NULL)
288 return got_error_from_errno("strdup");
291 return NULL;
294 static const struct got_error *
295 apply_unveil(const char *repo_path, int repo_read_only,
296 const char *worktree_path)
298 const struct got_error *err;
300 #ifdef PROFILE
301 if (unveil("gmon.out", "rwc") != 0)
302 return got_error_from_errno2("unveil", "gmon.out");
303 #endif
304 if (repo_path && unveil(repo_path, repo_read_only ? "r" : "rwc") != 0)
305 return got_error_from_errno2("unveil", repo_path);
307 if (worktree_path && unveil(worktree_path, "rwc") != 0)
308 return got_error_from_errno2("unveil", worktree_path);
310 if (unveil(GOT_TMPDIR_STR, "rwc") != 0)
311 return got_error_from_errno2("unveil", GOT_TMPDIR_STR);
313 err = got_privsep_unveil_exec_helpers();
314 if (err != NULL)
315 return err;
317 if (unveil(NULL, NULL) != 0)
318 return got_error_from_errno("unveil");
320 return NULL;
323 __dead static void
324 usage_import(void)
326 fprintf(stderr, "usage: %s import [-b branch] [-I pattern] [-m message] "
327 "[-r repository-path] directory\n", getprogname());
328 exit(1);
331 static int
332 spawn_editor(const char *editor, const char *file)
334 pid_t pid;
335 sig_t sighup, sigint, sigquit;
336 int st = -1;
338 sighup = signal(SIGHUP, SIG_IGN);
339 sigint = signal(SIGINT, SIG_IGN);
340 sigquit = signal(SIGQUIT, SIG_IGN);
342 switch (pid = fork()) {
343 case -1:
344 goto doneediting;
345 case 0:
346 execl(editor, editor, file, (char *)NULL);
347 _exit(127);
350 while (waitpid(pid, &st, 0) == -1)
351 if (errno != EINTR)
352 break;
354 doneediting:
355 (void)signal(SIGHUP, sighup);
356 (void)signal(SIGINT, sigint);
357 (void)signal(SIGQUIT, sigquit);
359 if (!WIFEXITED(st)) {
360 errno = EINTR;
361 return -1;
364 return WEXITSTATUS(st);
367 static const struct got_error *
368 read_logmsg(char **logmsg, size_t *len, FILE *fp, size_t filesize)
370 const struct got_error *err = NULL;
371 char *line = NULL;
372 size_t linesize = 0;
374 *logmsg = NULL;
375 *len = 0;
377 if (fseeko(fp, 0L, SEEK_SET) == -1)
378 return got_error_from_errno("fseeko");
380 *logmsg = malloc(filesize + 1);
381 if (*logmsg == NULL)
382 return got_error_from_errno("malloc");
383 (*logmsg)[0] = '\0';
385 while (getline(&line, &linesize, fp) != -1) {
386 if (line[0] == '#' || (*len == 0 && line[0] == '\n'))
387 continue; /* remove comments and leading empty lines */
388 *len = strlcat(*logmsg, line, filesize + 1);
389 if (*len >= filesize + 1) {
390 err = got_error(GOT_ERR_NO_SPACE);
391 goto done;
394 if (ferror(fp)) {
395 err = got_ferror(fp, GOT_ERR_IO);
396 goto done;
399 while (*len > 0 && (*logmsg)[*len - 1] == '\n') {
400 (*logmsg)[*len - 1] = '\0';
401 (*len)--;
403 done:
404 free(line);
405 if (err) {
406 free(*logmsg);
407 *logmsg = NULL;
408 *len = 0;
410 return err;
413 static const struct got_error *
414 edit_logmsg(char **logmsg, const char *editor, const char *logmsg_path,
415 const char *initial_content, size_t initial_content_len,
416 int require_modification)
418 const struct got_error *err = NULL;
419 struct stat st, st2;
420 FILE *fp = NULL;
421 size_t logmsg_len;
423 *logmsg = NULL;
425 if (stat(logmsg_path, &st) == -1)
426 return got_error_from_errno2("stat", logmsg_path);
428 if (spawn_editor(editor, logmsg_path) == -1)
429 return got_error_from_errno("failed spawning editor");
431 if (require_modification) {
432 struct timespec timeout;
434 timeout.tv_sec = 0;
435 timeout.tv_nsec = 1;
436 nanosleep(&timeout, NULL);
439 if (stat(logmsg_path, &st2) == -1)
440 return got_error_from_errno2("stat", logmsg_path);
442 if (require_modification && st.st_size == st2.st_size &&
443 timespeccmp(&st.st_mtim, &st2.st_mtim, ==))
444 return got_error_msg(GOT_ERR_COMMIT_MSG_EMPTY,
445 "no changes made to commit message, aborting");
447 fp = fopen(logmsg_path, "re");
448 if (fp == NULL) {
449 err = got_error_from_errno("fopen");
450 goto done;
453 /* strip comments and leading/trailing newlines */
454 err = read_logmsg(logmsg, &logmsg_len, fp, st2.st_size);
455 if (err)
456 goto done;
457 if (logmsg_len == 0) {
458 err = got_error_msg(GOT_ERR_COMMIT_MSG_EMPTY,
459 "commit message cannot be empty, aborting");
460 goto done;
462 done:
463 if (fp && fclose(fp) == EOF && err == NULL)
464 err = got_error_from_errno("fclose");
465 if (err) {
466 free(*logmsg);
467 *logmsg = NULL;
469 return err;
472 static const struct got_error *
473 collect_import_msg(char **logmsg, char **logmsg_path, const char *editor,
474 const char *path_dir, const char *branch_name)
476 char *initial_content = NULL;
477 const struct got_error *err = NULL;
478 int initial_content_len;
479 int fd = -1;
481 initial_content_len = asprintf(&initial_content,
482 "\n# %s to be imported to branch %s\n", path_dir,
483 branch_name);
484 if (initial_content_len == -1)
485 return got_error_from_errno("asprintf");
487 err = got_opentemp_named_fd(logmsg_path, &fd,
488 GOT_TMPDIR_STR "/got-importmsg", "");
489 if (err)
490 goto done;
492 if (write(fd, initial_content, initial_content_len) == -1) {
493 err = got_error_from_errno2("write", *logmsg_path);
494 goto done;
496 if (close(fd) == -1) {
497 err = got_error_from_errno2("close", *logmsg_path);
498 goto done;
500 fd = -1;
502 err = edit_logmsg(logmsg, editor, *logmsg_path, initial_content,
503 initial_content_len, 1);
504 done:
505 if (fd != -1 && close(fd) == -1 && err == NULL)
506 err = got_error_from_errno2("close", *logmsg_path);
507 free(initial_content);
508 if (err) {
509 free(*logmsg_path);
510 *logmsg_path = NULL;
512 return err;
515 static const struct got_error *
516 import_progress(void *arg, const char *path)
518 printf("A %s\n", path);
519 return NULL;
522 static const struct got_error *
523 valid_author(const char *author)
525 const char *email = author;
527 /*
528 * Git' expects the author (or committer) to be in the form
529 * "name <email>", which are mostly free form (see the
530 * "committer" description in git-fast-import(1)). We're only
531 * doing this to avoid git's object parser breaking on commits
532 * we create.
533 */
535 while (*author && *author != '\n' && *author != '<' && *author != '>')
536 author++;
537 if (author != email && *author == '<' && *(author - 1) != ' ')
538 return got_error_fmt(GOT_ERR_COMMIT_BAD_AUTHOR, "%s: space "
539 "between author name and email required", email);
540 if (*author++ != '<')
541 return got_error_fmt(GOT_ERR_COMMIT_NO_EMAIL, "%s", email);
542 while (*author && *author != '\n' && *author != '<' && *author != '>')
543 author++;
544 if (strcmp(author, ">") != 0)
545 return got_error_fmt(GOT_ERR_COMMIT_NO_EMAIL, "%s", email);
546 return NULL;
549 static const struct got_error *
550 get_author(char **author, struct got_repository *repo,
551 struct got_worktree *worktree)
553 const struct got_error *err = NULL;
554 const char *got_author = NULL, *name, *email;
555 const struct got_gotconfig *worktree_conf = NULL, *repo_conf = NULL;
557 *author = NULL;
559 if (worktree)
560 worktree_conf = got_worktree_get_gotconfig(worktree);
561 repo_conf = got_repo_get_gotconfig(repo);
563 /*
564 * Priority of potential author information sources, from most
565 * significant to least significant:
566 * 1) work tree's .got/got.conf file
567 * 2) repository's got.conf file
568 * 3) repository's git config file
569 * 4) environment variables
570 * 5) global git config files (in user's home directory or /etc)
571 */
573 if (worktree_conf)
574 got_author = got_gotconfig_get_author(worktree_conf);
575 if (got_author == NULL)
576 got_author = got_gotconfig_get_author(repo_conf);
577 if (got_author == NULL) {
578 name = got_repo_get_gitconfig_author_name(repo);
579 email = got_repo_get_gitconfig_author_email(repo);
580 if (name && email) {
581 if (asprintf(author, "%s <%s>", name, email) == -1)
582 return got_error_from_errno("asprintf");
583 return NULL;
586 got_author = getenv("GOT_AUTHOR");
587 if (got_author == NULL) {
588 name = got_repo_get_global_gitconfig_author_name(repo);
589 email = got_repo_get_global_gitconfig_author_email(
590 repo);
591 if (name && email) {
592 if (asprintf(author, "%s <%s>", name, email)
593 == -1)
594 return got_error_from_errno("asprintf");
595 return NULL;
597 /* TODO: Look up user in password database? */
598 return got_error(GOT_ERR_COMMIT_NO_AUTHOR);
602 *author = strdup(got_author);
603 if (*author == NULL)
604 return got_error_from_errno("strdup");
606 err = valid_author(*author);
607 if (err) {
608 free(*author);
609 *author = NULL;
611 return err;
614 static const struct got_error *
615 get_allowed_signers(char **allowed_signers, struct got_repository *repo,
616 struct got_worktree *worktree)
618 const char *got_allowed_signers = NULL;
619 const struct got_gotconfig *worktree_conf = NULL, *repo_conf = NULL;
621 *allowed_signers = NULL;
623 if (worktree)
624 worktree_conf = got_worktree_get_gotconfig(worktree);
625 repo_conf = got_repo_get_gotconfig(repo);
627 /*
628 * Priority of potential author information sources, from most
629 * significant to least significant:
630 * 1) work tree's .got/got.conf file
631 * 2) repository's got.conf file
632 */
634 if (worktree_conf)
635 got_allowed_signers = got_gotconfig_get_allowed_signers_file(
636 worktree_conf);
637 if (got_allowed_signers == NULL)
638 got_allowed_signers = got_gotconfig_get_allowed_signers_file(
639 repo_conf);
641 if (got_allowed_signers) {
642 *allowed_signers = strdup(got_allowed_signers);
643 if (*allowed_signers == NULL)
644 return got_error_from_errno("strdup");
646 return NULL;
649 static const struct got_error *
650 get_revoked_signers(char **revoked_signers, struct got_repository *repo,
651 struct got_worktree *worktree)
653 const char *got_revoked_signers = NULL;
654 const struct got_gotconfig *worktree_conf = NULL, *repo_conf = NULL;
656 *revoked_signers = NULL;
658 if (worktree)
659 worktree_conf = got_worktree_get_gotconfig(worktree);
660 repo_conf = got_repo_get_gotconfig(repo);
662 /*
663 * Priority of potential author information sources, from most
664 * significant to least significant:
665 * 1) work tree's .got/got.conf file
666 * 2) repository's got.conf file
667 */
669 if (worktree_conf)
670 got_revoked_signers = got_gotconfig_get_revoked_signers_file(
671 worktree_conf);
672 if (got_revoked_signers == NULL)
673 got_revoked_signers = got_gotconfig_get_revoked_signers_file(
674 repo_conf);
676 if (got_revoked_signers) {
677 *revoked_signers = strdup(got_revoked_signers);
678 if (*revoked_signers == NULL)
679 return got_error_from_errno("strdup");
681 return NULL;
684 static const char *
685 get_signer_id(struct got_repository *repo, struct got_worktree *worktree)
687 const char *got_signer_id = NULL;
688 const struct got_gotconfig *worktree_conf = NULL, *repo_conf = NULL;
690 if (worktree)
691 worktree_conf = got_worktree_get_gotconfig(worktree);
692 repo_conf = got_repo_get_gotconfig(repo);
694 /*
695 * Priority of potential author information sources, from most
696 * significant to least significant:
697 * 1) work tree's .got/got.conf file
698 * 2) repository's got.conf file
699 */
701 if (worktree_conf)
702 got_signer_id = got_gotconfig_get_signer_id(worktree_conf);
703 if (got_signer_id == NULL)
704 got_signer_id = got_gotconfig_get_signer_id(repo_conf);
706 return got_signer_id;
709 static const struct got_error *
710 get_gitconfig_path(char **gitconfig_path)
712 const char *homedir = getenv("HOME");
714 *gitconfig_path = NULL;
715 if (homedir) {
716 if (asprintf(gitconfig_path, "%s/.gitconfig", homedir) == -1)
717 return got_error_from_errno("asprintf");
720 return NULL;
723 static const struct got_error *
724 cmd_import(int argc, char *argv[])
726 const struct got_error *error = NULL;
727 char *path_dir = NULL, *repo_path = NULL, *logmsg = NULL;
728 char *gitconfig_path = NULL, *editor = NULL, *author = NULL;
729 const char *branch_name = NULL;
730 char *id_str = NULL, *logmsg_path = NULL;
731 char refname[PATH_MAX] = "refs/heads/";
732 struct got_repository *repo = NULL;
733 struct got_reference *branch_ref = NULL, *head_ref = NULL;
734 struct got_object_id *new_commit_id = NULL;
735 int ch, n = 0;
736 struct got_pathlist_head ignores;
737 struct got_pathlist_entry *pe;
738 int preserve_logmsg = 0;
739 int *pack_fds = NULL;
741 TAILQ_INIT(&ignores);
743 #ifndef PROFILE
744 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
745 "unveil",
746 NULL) == -1)
747 err(1, "pledge");
748 #endif
750 while ((ch = getopt(argc, argv, "b:I:m:r:")) != -1) {
751 switch (ch) {
752 case 'b':
753 branch_name = optarg;
754 break;
755 case 'I':
756 if (optarg[0] == '\0')
757 break;
758 error = got_pathlist_insert(&pe, &ignores, optarg,
759 NULL);
760 if (error)
761 goto done;
762 break;
763 case 'm':
764 logmsg = strdup(optarg);
765 if (logmsg == NULL) {
766 error = got_error_from_errno("strdup");
767 goto done;
769 break;
770 case 'r':
771 repo_path = realpath(optarg, NULL);
772 if (repo_path == NULL) {
773 error = got_error_from_errno2("realpath",
774 optarg);
775 goto done;
777 break;
778 default:
779 usage_import();
780 /* NOTREACHED */
784 argc -= optind;
785 argv += optind;
787 if (argc != 1)
788 usage_import();
790 if (repo_path == NULL) {
791 repo_path = getcwd(NULL, 0);
792 if (repo_path == NULL)
793 return got_error_from_errno("getcwd");
795 got_path_strip_trailing_slashes(repo_path);
796 error = get_gitconfig_path(&gitconfig_path);
797 if (error)
798 goto done;
799 error = got_repo_pack_fds_open(&pack_fds);
800 if (error != NULL)
801 goto done;
802 error = got_repo_open(&repo, repo_path, gitconfig_path, pack_fds);
803 if (error)
804 goto done;
806 error = get_author(&author, repo, NULL);
807 if (error)
808 return error;
810 /*
811 * Don't let the user create a branch name with a leading '-'.
812 * While technically a valid reference name, this case is usually
813 * an unintended typo.
814 */
815 if (branch_name && branch_name[0] == '-')
816 return got_error_path(branch_name, GOT_ERR_REF_NAME_MINUS);
818 error = got_ref_open(&head_ref, repo, GOT_REF_HEAD, 0);
819 if (error && error->code != GOT_ERR_NOT_REF)
820 goto done;
822 if (branch_name)
823 n = strlcat(refname, branch_name, sizeof(refname));
824 else if (head_ref && got_ref_is_symbolic(head_ref))
825 n = strlcpy(refname, got_ref_get_symref_target(head_ref),
826 sizeof(refname));
827 else
828 n = strlcat(refname, "main", sizeof(refname));
829 if (n >= sizeof(refname)) {
830 error = got_error(GOT_ERR_NO_SPACE);
831 goto done;
834 error = got_ref_open(&branch_ref, repo, refname, 0);
835 if (error) {
836 if (error->code != GOT_ERR_NOT_REF)
837 goto done;
838 } else {
839 error = got_error_msg(GOT_ERR_BRANCH_EXISTS,
840 "import target branch already exists");
841 goto done;
844 path_dir = realpath(argv[0], NULL);
845 if (path_dir == NULL) {
846 error = got_error_from_errno2("realpath", argv[0]);
847 goto done;
849 got_path_strip_trailing_slashes(path_dir);
851 /*
852 * unveil(2) traverses exec(2); if an editor is used we have
853 * to apply unveil after the log message has been written.
854 */
855 if (logmsg == NULL || *logmsg == '\0') {
856 error = get_editor(&editor);
857 if (error)
858 goto done;
859 free(logmsg);
860 error = collect_import_msg(&logmsg, &logmsg_path, editor,
861 path_dir, refname);
862 if (error) {
863 if (error->code != GOT_ERR_COMMIT_MSG_EMPTY &&
864 logmsg_path != NULL)
865 preserve_logmsg = 1;
866 goto done;
870 if (unveil(path_dir, "r") != 0) {
871 error = got_error_from_errno2("unveil", path_dir);
872 if (logmsg_path)
873 preserve_logmsg = 1;
874 goto done;
877 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
878 if (error) {
879 if (logmsg_path)
880 preserve_logmsg = 1;
881 goto done;
884 error = got_repo_import(&new_commit_id, path_dir, logmsg,
885 author, &ignores, repo, import_progress, NULL);
886 if (error) {
887 if (logmsg_path)
888 preserve_logmsg = 1;
889 goto done;
892 error = got_ref_alloc(&branch_ref, refname, new_commit_id);
893 if (error) {
894 if (logmsg_path)
895 preserve_logmsg = 1;
896 goto done;
899 error = got_ref_write(branch_ref, repo);
900 if (error) {
901 if (logmsg_path)
902 preserve_logmsg = 1;
903 goto done;
906 error = got_object_id_str(&id_str, new_commit_id);
907 if (error) {
908 if (logmsg_path)
909 preserve_logmsg = 1;
910 goto done;
913 error = got_ref_open(&head_ref, repo, GOT_REF_HEAD, 0);
914 if (error) {
915 if (error->code != GOT_ERR_NOT_REF) {
916 if (logmsg_path)
917 preserve_logmsg = 1;
918 goto done;
921 error = got_ref_alloc_symref(&head_ref, GOT_REF_HEAD,
922 branch_ref);
923 if (error) {
924 if (logmsg_path)
925 preserve_logmsg = 1;
926 goto done;
929 error = got_ref_write(head_ref, repo);
930 if (error) {
931 if (logmsg_path)
932 preserve_logmsg = 1;
933 goto done;
937 printf("Created branch %s with commit %s\n",
938 got_ref_get_name(branch_ref), id_str);
939 done:
940 if (pack_fds) {
941 const struct got_error *pack_err =
942 got_repo_pack_fds_close(pack_fds);
943 if (error == NULL)
944 error = pack_err;
946 if (repo) {
947 const struct got_error *close_err = got_repo_close(repo);
948 if (error == NULL)
949 error = close_err;
951 if (preserve_logmsg) {
952 fprintf(stderr, "%s: log message preserved in %s\n",
953 getprogname(), logmsg_path);
954 } else if (logmsg_path && unlink(logmsg_path) == -1 && error == NULL)
955 error = got_error_from_errno2("unlink", logmsg_path);
956 free(logmsg);
957 free(logmsg_path);
958 free(repo_path);
959 free(editor);
960 free(new_commit_id);
961 free(id_str);
962 free(author);
963 free(gitconfig_path);
964 if (branch_ref)
965 got_ref_close(branch_ref);
966 if (head_ref)
967 got_ref_close(head_ref);
968 return error;
971 __dead static void
972 usage_clone(void)
974 fprintf(stderr, "usage: %s clone [-almqv] [-b branch] [-R reference] "
975 "repository-URL [directory]\n", getprogname());
976 exit(1);
979 struct got_fetch_progress_arg {
980 char last_scaled_size[FMT_SCALED_STRSIZE];
981 int last_p_indexed;
982 int last_p_resolved;
983 int verbosity;
985 struct got_repository *repo;
987 int create_configs;
988 int configs_created;
989 struct {
990 struct got_pathlist_head *symrefs;
991 struct got_pathlist_head *wanted_branches;
992 struct got_pathlist_head *wanted_refs;
993 const char *proto;
994 const char *host;
995 const char *port;
996 const char *remote_repo_path;
997 const char *git_url;
998 int fetch_all_branches;
999 int mirror_references;
1000 } config_info;
1003 /* XXX forward declaration */
1004 static const struct got_error *
1005 create_config_files(const char *proto, const char *host, const char *port,
1006 const char *remote_repo_path, const char *git_url, int fetch_all_branches,
1007 int mirror_references, struct got_pathlist_head *symrefs,
1008 struct got_pathlist_head *wanted_branches,
1009 struct got_pathlist_head *wanted_refs, struct got_repository *repo);
1011 static const struct got_error *
1012 fetch_progress(void *arg, const char *message, off_t packfile_size,
1013 int nobj_total, int nobj_indexed, int nobj_loose, int nobj_resolved)
1015 const struct got_error *err = NULL;
1016 struct got_fetch_progress_arg *a = arg;
1017 char scaled_size[FMT_SCALED_STRSIZE];
1018 int p_indexed, p_resolved;
1019 int print_size = 0, print_indexed = 0, print_resolved = 0;
1022 * In order to allow a failed clone to be resumed with 'got fetch'
1023 * we try to create configuration files as soon as possible.
1024 * Once the server has sent information about its default branch
1025 * we have all required information.
1027 if (a->create_configs && !a->configs_created &&
1028 !TAILQ_EMPTY(a->config_info.symrefs)) {
1029 err = create_config_files(a->config_info.proto,
1030 a->config_info.host, a->config_info.port,
1031 a->config_info.remote_repo_path,
1032 a->config_info.git_url,
1033 a->config_info.fetch_all_branches,
1034 a->config_info.mirror_references,
1035 a->config_info.symrefs,
1036 a->config_info.wanted_branches,
1037 a->config_info.wanted_refs, a->repo);
1038 if (err)
1039 return err;
1040 a->configs_created = 1;
1043 if (a->verbosity < 0)
1044 return NULL;
1046 if (message && message[0] != '\0') {
1047 printf("\rserver: %s", message);
1048 fflush(stdout);
1049 return NULL;
1052 if (packfile_size > 0 || nobj_indexed > 0) {
1053 if (fmt_scaled(packfile_size, scaled_size) == 0 &&
1054 (a->last_scaled_size[0] == '\0' ||
1055 strcmp(scaled_size, a->last_scaled_size)) != 0) {
1056 print_size = 1;
1057 if (strlcpy(a->last_scaled_size, scaled_size,
1058 FMT_SCALED_STRSIZE) >= FMT_SCALED_STRSIZE)
1059 return got_error(GOT_ERR_NO_SPACE);
1061 if (nobj_indexed > 0) {
1062 p_indexed = (nobj_indexed * 100) / nobj_total;
1063 if (p_indexed != a->last_p_indexed) {
1064 a->last_p_indexed = p_indexed;
1065 print_indexed = 1;
1066 print_size = 1;
1069 if (nobj_resolved > 0) {
1070 p_resolved = (nobj_resolved * 100) /
1071 (nobj_total - nobj_loose);
1072 if (p_resolved != a->last_p_resolved) {
1073 a->last_p_resolved = p_resolved;
1074 print_resolved = 1;
1075 print_indexed = 1;
1076 print_size = 1;
1081 if (print_size || print_indexed || print_resolved)
1082 printf("\r");
1083 if (print_size)
1084 printf("%*s fetched", FMT_SCALED_STRSIZE - 2, scaled_size);
1085 if (print_indexed)
1086 printf("; indexing %d%%", p_indexed);
1087 if (print_resolved)
1088 printf("; resolving deltas %d%%", p_resolved);
1089 if (print_size || print_indexed || print_resolved)
1090 fflush(stdout);
1092 return NULL;
1095 static const struct got_error *
1096 create_symref(const char *refname, struct got_reference *target_ref,
1097 int verbosity, struct got_repository *repo)
1099 const struct got_error *err;
1100 struct got_reference *head_symref;
1102 err = got_ref_alloc_symref(&head_symref, refname, target_ref);
1103 if (err)
1104 return err;
1106 err = got_ref_write(head_symref, repo);
1107 if (err == NULL && verbosity > 0) {
1108 printf("Created reference %s: %s\n", GOT_REF_HEAD,
1109 got_ref_get_name(target_ref));
1111 got_ref_close(head_symref);
1112 return err;
1115 static const struct got_error *
1116 list_remote_refs(struct got_pathlist_head *symrefs,
1117 struct got_pathlist_head *refs)
1119 const struct got_error *err;
1120 struct got_pathlist_entry *pe;
1122 TAILQ_FOREACH(pe, symrefs, entry) {
1123 const char *refname = pe->path;
1124 const char *targetref = pe->data;
1126 printf("%s: %s\n", refname, targetref);
1129 TAILQ_FOREACH(pe, refs, entry) {
1130 const char *refname = pe->path;
1131 struct got_object_id *id = pe->data;
1132 char *id_str;
1134 err = got_object_id_str(&id_str, id);
1135 if (err)
1136 return err;
1137 printf("%s: %s\n", refname, id_str);
1138 free(id_str);
1141 return NULL;
1144 static const struct got_error *
1145 create_ref(const char *refname, struct got_object_id *id,
1146 int verbosity, struct got_repository *repo)
1148 const struct got_error *err = NULL;
1149 struct got_reference *ref;
1150 char *id_str;
1152 err = got_object_id_str(&id_str, id);
1153 if (err)
1154 return err;
1156 err = got_ref_alloc(&ref, refname, id);
1157 if (err)
1158 goto done;
1160 err = got_ref_write(ref, repo);
1161 got_ref_close(ref);
1163 if (err == NULL && verbosity >= 0)
1164 printf("Created reference %s: %s\n", refname, id_str);
1165 done:
1166 free(id_str);
1167 return err;
1170 static int
1171 match_wanted_ref(const char *refname, const char *wanted_ref)
1173 if (strncmp(refname, "refs/", 5) != 0)
1174 return 0;
1175 refname += 5;
1178 * Prevent fetching of references that won't make any
1179 * sense outside of the remote repository's context.
1181 if (strncmp(refname, "got/", 4) == 0)
1182 return 0;
1183 if (strncmp(refname, "remotes/", 8) == 0)
1184 return 0;
1186 if (strncmp(wanted_ref, "refs/", 5) == 0)
1187 wanted_ref += 5;
1189 /* Allow prefix match. */
1190 if (got_path_is_child(refname, wanted_ref, strlen(wanted_ref)))
1191 return 1;
1193 /* Allow exact match. */
1194 return (strcmp(refname, wanted_ref) == 0);
1197 static int
1198 is_wanted_ref(struct got_pathlist_head *wanted_refs, const char *refname)
1200 struct got_pathlist_entry *pe;
1202 TAILQ_FOREACH(pe, wanted_refs, entry) {
1203 if (match_wanted_ref(refname, pe->path))
1204 return 1;
1207 return 0;
1210 static const struct got_error *
1211 create_wanted_ref(const char *refname, struct got_object_id *id,
1212 const char *remote_repo_name, int verbosity, struct got_repository *repo)
1214 const struct got_error *err;
1215 char *remote_refname;
1217 if (strncmp("refs/", refname, 5) == 0)
1218 refname += 5;
1220 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
1221 remote_repo_name, refname) == -1)
1222 return got_error_from_errno("asprintf");
1224 err = create_ref(remote_refname, id, verbosity, repo);
1225 free(remote_refname);
1226 return err;
1229 static const struct got_error *
1230 create_gotconfig(const char *proto, const char *host, const char *port,
1231 const char *remote_repo_path, const char *default_branch,
1232 int fetch_all_branches, struct got_pathlist_head *wanted_branches,
1233 struct got_pathlist_head *wanted_refs, int mirror_references,
1234 struct got_repository *repo)
1236 const struct got_error *err = NULL;
1237 char *gotconfig_path = NULL;
1238 char *gotconfig = NULL;
1239 FILE *gotconfig_file = NULL;
1240 const char *branchname = NULL;
1241 char *branches = NULL, *refs = NULL;
1242 ssize_t n;
1244 if (!fetch_all_branches && !TAILQ_EMPTY(wanted_branches)) {
1245 struct got_pathlist_entry *pe;
1246 TAILQ_FOREACH(pe, wanted_branches, entry) {
1247 char *s;
1248 branchname = pe->path;
1249 if (strncmp(branchname, "refs/heads/", 11) == 0)
1250 branchname += 11;
1251 if (asprintf(&s, "%s\"%s\" ",
1252 branches ? branches : "", branchname) == -1) {
1253 err = got_error_from_errno("asprintf");
1254 goto done;
1256 free(branches);
1257 branches = s;
1259 } else if (!fetch_all_branches && default_branch) {
1260 branchname = default_branch;
1261 if (strncmp(branchname, "refs/heads/", 11) == 0)
1262 branchname += 11;
1263 if (asprintf(&branches, "\"%s\" ", branchname) == -1) {
1264 err = got_error_from_errno("asprintf");
1265 goto done;
1268 if (!TAILQ_EMPTY(wanted_refs)) {
1269 struct got_pathlist_entry *pe;
1270 TAILQ_FOREACH(pe, wanted_refs, entry) {
1271 char *s;
1272 const char *refname = pe->path;
1273 if (strncmp(refname, "refs/", 5) == 0)
1274 branchname += 5;
1275 if (asprintf(&s, "%s\"%s\" ",
1276 refs ? refs : "", refname) == -1) {
1277 err = got_error_from_errno("asprintf");
1278 goto done;
1280 free(refs);
1281 refs = s;
1285 /* Create got.conf(5). */
1286 gotconfig_path = got_repo_get_path_gotconfig(repo);
1287 if (gotconfig_path == NULL) {
1288 err = got_error_from_errno("got_repo_get_path_gotconfig");
1289 goto done;
1291 gotconfig_file = fopen(gotconfig_path, "ae");
1292 if (gotconfig_file == NULL) {
1293 err = got_error_from_errno2("fopen", gotconfig_path);
1294 goto done;
1296 if (asprintf(&gotconfig,
1297 "remote \"%s\" {\n"
1298 "\tserver %s\n"
1299 "\tprotocol %s\n"
1300 "%s%s%s"
1301 "\trepository \"%s\"\n"
1302 "%s%s%s"
1303 "%s%s%s"
1304 "%s"
1305 "%s"
1306 "}\n",
1307 GOT_FETCH_DEFAULT_REMOTE_NAME, host, proto,
1308 port ? "\tport " : "", port ? port : "", port ? "\n" : "",
1309 remote_repo_path, branches ? "\tbranch { " : "",
1310 branches ? branches : "", branches ? "}\n" : "",
1311 refs ? "\treference { " : "", refs ? refs : "", refs ? "}\n" : "",
1312 mirror_references ? "\tmirror_references yes\n" : "",
1313 fetch_all_branches ? "\tfetch_all_branches yes\n" : "") == -1) {
1314 err = got_error_from_errno("asprintf");
1315 goto done;
1317 n = fwrite(gotconfig, 1, strlen(gotconfig), gotconfig_file);
1318 if (n != strlen(gotconfig)) {
1319 err = got_ferror(gotconfig_file, GOT_ERR_IO);
1320 goto done;
1323 done:
1324 if (gotconfig_file && fclose(gotconfig_file) == EOF && err == NULL)
1325 err = got_error_from_errno2("fclose", gotconfig_path);
1326 free(gotconfig_path);
1327 free(branches);
1328 return err;
1331 static const struct got_error *
1332 create_gitconfig(const char *git_url, const char *default_branch,
1333 int fetch_all_branches, struct got_pathlist_head *wanted_branches,
1334 struct got_pathlist_head *wanted_refs, int mirror_references,
1335 struct got_repository *repo)
1337 const struct got_error *err = NULL;
1338 char *gitconfig_path = NULL;
1339 char *gitconfig = NULL;
1340 FILE *gitconfig_file = NULL;
1341 char *branches = NULL, *refs = NULL;
1342 const char *branchname;
1343 ssize_t n;
1345 /* Create a config file Git can understand. */
1346 gitconfig_path = got_repo_get_path_gitconfig(repo);
1347 if (gitconfig_path == NULL) {
1348 err = got_error_from_errno("got_repo_get_path_gitconfig");
1349 goto done;
1351 gitconfig_file = fopen(gitconfig_path, "ae");
1352 if (gitconfig_file == NULL) {
1353 err = got_error_from_errno2("fopen", gitconfig_path);
1354 goto done;
1356 if (fetch_all_branches) {
1357 if (mirror_references) {
1358 if (asprintf(&branches,
1359 "\tfetch = refs/heads/*:refs/heads/*\n") == -1) {
1360 err = got_error_from_errno("asprintf");
1361 goto done;
1363 } else if (asprintf(&branches,
1364 "\tfetch = refs/heads/*:refs/remotes/%s/*\n",
1365 GOT_FETCH_DEFAULT_REMOTE_NAME) == -1) {
1366 err = got_error_from_errno("asprintf");
1367 goto done;
1369 } else if (!TAILQ_EMPTY(wanted_branches)) {
1370 struct got_pathlist_entry *pe;
1371 TAILQ_FOREACH(pe, wanted_branches, entry) {
1372 char *s;
1373 branchname = pe->path;
1374 if (strncmp(branchname, "refs/heads/", 11) == 0)
1375 branchname += 11;
1376 if (mirror_references) {
1377 if (asprintf(&s,
1378 "%s\tfetch = refs/heads/%s:refs/heads/%s\n",
1379 branches ? branches : "",
1380 branchname, branchname) == -1) {
1381 err = got_error_from_errno("asprintf");
1382 goto done;
1384 } else if (asprintf(&s,
1385 "%s\tfetch = refs/heads/%s:refs/remotes/%s/%s\n",
1386 branches ? branches : "",
1387 branchname, GOT_FETCH_DEFAULT_REMOTE_NAME,
1388 branchname) == -1) {
1389 err = got_error_from_errno("asprintf");
1390 goto done;
1392 free(branches);
1393 branches = s;
1395 } else {
1397 * If the server specified a default branch, use just that one.
1398 * Otherwise fall back to fetching all branches on next fetch.
1400 if (default_branch) {
1401 branchname = default_branch;
1402 if (strncmp(branchname, "refs/heads/", 11) == 0)
1403 branchname += 11;
1404 } else
1405 branchname = "*"; /* fall back to all branches */
1406 if (mirror_references) {
1407 if (asprintf(&branches,
1408 "\tfetch = refs/heads/%s:refs/heads/%s\n",
1409 branchname, branchname) == -1) {
1410 err = got_error_from_errno("asprintf");
1411 goto done;
1413 } else if (asprintf(&branches,
1414 "\tfetch = refs/heads/%s:refs/remotes/%s/%s\n",
1415 branchname, GOT_FETCH_DEFAULT_REMOTE_NAME,
1416 branchname) == -1) {
1417 err = got_error_from_errno("asprintf");
1418 goto done;
1421 if (!TAILQ_EMPTY(wanted_refs)) {
1422 struct got_pathlist_entry *pe;
1423 TAILQ_FOREACH(pe, wanted_refs, entry) {
1424 char *s;
1425 const char *refname = pe->path;
1426 if (strncmp(refname, "refs/", 5) == 0)
1427 refname += 5;
1428 if (mirror_references) {
1429 if (asprintf(&s,
1430 "%s\tfetch = refs/%s:refs/%s\n",
1431 refs ? refs : "", refname, refname) == -1) {
1432 err = got_error_from_errno("asprintf");
1433 goto done;
1435 } else if (asprintf(&s,
1436 "%s\tfetch = refs/%s:refs/remotes/%s/%s\n",
1437 refs ? refs : "",
1438 refname, GOT_FETCH_DEFAULT_REMOTE_NAME,
1439 refname) == -1) {
1440 err = got_error_from_errno("asprintf");
1441 goto done;
1443 free(refs);
1444 refs = s;
1448 if (asprintf(&gitconfig,
1449 "[remote \"%s\"]\n"
1450 "\turl = %s\n"
1451 "%s"
1452 "%s"
1453 "\tfetch = refs/tags/*:refs/tags/*\n",
1454 GOT_FETCH_DEFAULT_REMOTE_NAME, git_url, branches ? branches : "",
1455 refs ? refs : "") == -1) {
1456 err = got_error_from_errno("asprintf");
1457 goto done;
1459 n = fwrite(gitconfig, 1, strlen(gitconfig), gitconfig_file);
1460 if (n != strlen(gitconfig)) {
1461 err = got_ferror(gitconfig_file, GOT_ERR_IO);
1462 goto done;
1464 done:
1465 if (gitconfig_file && fclose(gitconfig_file) == EOF && err == NULL)
1466 err = got_error_from_errno2("fclose", gitconfig_path);
1467 free(gitconfig_path);
1468 free(branches);
1469 return err;
1472 static const struct got_error *
1473 create_config_files(const char *proto, const char *host, const char *port,
1474 const char *remote_repo_path, const char *git_url, int fetch_all_branches,
1475 int mirror_references, struct got_pathlist_head *symrefs,
1476 struct got_pathlist_head *wanted_branches,
1477 struct got_pathlist_head *wanted_refs, struct got_repository *repo)
1479 const struct got_error *err = NULL;
1480 const char *default_branch = NULL;
1481 struct got_pathlist_entry *pe;
1484 * If we asked for a set of wanted branches then use the first
1485 * one of those.
1487 if (!TAILQ_EMPTY(wanted_branches)) {
1488 pe = TAILQ_FIRST(wanted_branches);
1489 default_branch = pe->path;
1490 } else {
1491 /* First HEAD ref listed by server is the default branch. */
1492 TAILQ_FOREACH(pe, symrefs, entry) {
1493 const char *refname = pe->path;
1494 const char *target = pe->data;
1496 if (strcmp(refname, GOT_REF_HEAD) != 0)
1497 continue;
1499 default_branch = target;
1500 break;
1504 /* Create got.conf(5). */
1505 err = create_gotconfig(proto, host, port, remote_repo_path,
1506 default_branch, fetch_all_branches, wanted_branches,
1507 wanted_refs, mirror_references, repo);
1508 if (err)
1509 return err;
1511 /* Create a config file Git can understand. */
1512 return create_gitconfig(git_url, default_branch, fetch_all_branches,
1513 wanted_branches, wanted_refs, mirror_references, repo);
1516 static const struct got_error *
1517 cmd_clone(int argc, char *argv[])
1519 const struct got_error *error = NULL;
1520 const char *uri, *dirname;
1521 char *proto, *host, *port, *repo_name, *server_path;
1522 char *default_destdir = NULL, *id_str = NULL;
1523 const char *repo_path;
1524 struct got_repository *repo = NULL;
1525 struct got_pathlist_head refs, symrefs, wanted_branches, wanted_refs;
1526 struct got_pathlist_entry *pe;
1527 struct got_object_id *pack_hash = NULL;
1528 int ch, fetchfd = -1, fetchstatus;
1529 pid_t fetchpid = -1;
1530 struct got_fetch_progress_arg fpa;
1531 char *git_url = NULL;
1532 int verbosity = 0, fetch_all_branches = 0, mirror_references = 0;
1533 int bflag = 0, list_refs_only = 0;
1534 int *pack_fds = NULL;
1536 TAILQ_INIT(&refs);
1537 TAILQ_INIT(&symrefs);
1538 TAILQ_INIT(&wanted_branches);
1539 TAILQ_INIT(&wanted_refs);
1541 while ((ch = getopt(argc, argv, "ab:lmqR:v")) != -1) {
1542 switch (ch) {
1543 case 'a':
1544 fetch_all_branches = 1;
1545 break;
1546 case 'b':
1547 error = got_pathlist_append(&wanted_branches,
1548 optarg, NULL);
1549 if (error)
1550 return error;
1551 bflag = 1;
1552 break;
1553 case 'l':
1554 list_refs_only = 1;
1555 break;
1556 case 'm':
1557 mirror_references = 1;
1558 break;
1559 case 'q':
1560 verbosity = -1;
1561 break;
1562 case 'R':
1563 error = got_pathlist_append(&wanted_refs,
1564 optarg, NULL);
1565 if (error)
1566 return error;
1567 break;
1568 case 'v':
1569 if (verbosity < 0)
1570 verbosity = 0;
1571 else if (verbosity < 3)
1572 verbosity++;
1573 break;
1574 default:
1575 usage_clone();
1576 break;
1579 argc -= optind;
1580 argv += optind;
1582 if (fetch_all_branches && !TAILQ_EMPTY(&wanted_branches))
1583 option_conflict('a', 'b');
1584 if (list_refs_only) {
1585 if (!TAILQ_EMPTY(&wanted_branches))
1586 option_conflict('l', 'b');
1587 if (fetch_all_branches)
1588 option_conflict('l', 'a');
1589 if (mirror_references)
1590 option_conflict('l', 'm');
1591 if (!TAILQ_EMPTY(&wanted_refs))
1592 option_conflict('l', 'R');
1595 uri = argv[0];
1597 if (argc == 1)
1598 dirname = NULL;
1599 else if (argc == 2)
1600 dirname = argv[1];
1601 else
1602 usage_clone();
1604 error = got_dial_parse_uri(&proto, &host, &port, &server_path,
1605 &repo_name, uri);
1606 if (error)
1607 goto done;
1609 if (asprintf(&git_url, "%s://%s%s%s%s%s", proto,
1610 host, port ? ":" : "", port ? port : "",
1611 server_path[0] != '/' ? "/" : "", server_path) == -1) {
1612 error = got_error_from_errno("asprintf");
1613 goto done;
1616 if (strcmp(proto, "git") == 0) {
1617 #ifndef PROFILE
1618 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
1619 "sendfd dns inet unveil", NULL) == -1)
1620 err(1, "pledge");
1621 #endif
1622 } else if (strcmp(proto, "git+ssh") == 0 ||
1623 strcmp(proto, "ssh") == 0) {
1624 #ifndef PROFILE
1625 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
1626 "sendfd unveil", NULL) == -1)
1627 err(1, "pledge");
1628 #endif
1629 } else if (strcmp(proto, "http") == 0 ||
1630 strcmp(proto, "git+http") == 0) {
1631 error = got_error_path(proto, GOT_ERR_NOT_IMPL);
1632 goto done;
1633 } else {
1634 error = got_error_path(proto, GOT_ERR_BAD_PROTO);
1635 goto done;
1637 if (dirname == NULL) {
1638 if (asprintf(&default_destdir, "%s.git", repo_name) == -1) {
1639 error = got_error_from_errno("asprintf");
1640 goto done;
1642 repo_path = default_destdir;
1643 } else
1644 repo_path = dirname;
1646 if (!list_refs_only) {
1647 error = got_path_mkdir(repo_path);
1648 if (error &&
1649 (!(error->code == GOT_ERR_ERRNO && errno == EISDIR) &&
1650 !(error->code == GOT_ERR_ERRNO && errno == EEXIST)))
1651 goto done;
1652 if (!got_path_dir_is_empty(repo_path)) {
1653 error = got_error_path(repo_path,
1654 GOT_ERR_DIR_NOT_EMPTY);
1655 goto done;
1659 error = got_dial_apply_unveil(proto);
1660 if (error)
1661 goto done;
1663 error = apply_unveil(repo_path, 0, NULL);
1664 if (error)
1665 goto done;
1667 if (verbosity >= 0)
1668 printf("Connecting to %s\n", git_url);
1670 error = got_fetch_connect(&fetchpid, &fetchfd, proto, host, port,
1671 server_path, verbosity);
1672 if (error)
1673 goto done;
1675 if (!list_refs_only) {
1676 error = got_repo_init(repo_path, NULL);
1677 if (error)
1678 goto done;
1679 error = got_repo_pack_fds_open(&pack_fds);
1680 if (error != NULL)
1681 goto done;
1682 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
1683 if (error)
1684 goto done;
1687 fpa.last_scaled_size[0] = '\0';
1688 fpa.last_p_indexed = -1;
1689 fpa.last_p_resolved = -1;
1690 fpa.verbosity = verbosity;
1691 fpa.create_configs = 1;
1692 fpa.configs_created = 0;
1693 fpa.repo = repo;
1694 fpa.config_info.symrefs = &symrefs;
1695 fpa.config_info.wanted_branches = &wanted_branches;
1696 fpa.config_info.wanted_refs = &wanted_refs;
1697 fpa.config_info.proto = proto;
1698 fpa.config_info.host = host;
1699 fpa.config_info.port = port;
1700 fpa.config_info.remote_repo_path = server_path;
1701 fpa.config_info.git_url = git_url;
1702 fpa.config_info.fetch_all_branches = fetch_all_branches;
1703 fpa.config_info.mirror_references = mirror_references;
1704 error = got_fetch_pack(&pack_hash, &refs, &symrefs,
1705 GOT_FETCH_DEFAULT_REMOTE_NAME, mirror_references,
1706 fetch_all_branches, &wanted_branches, &wanted_refs,
1707 list_refs_only, verbosity, fetchfd, repo, NULL, NULL, bflag,
1708 fetch_progress, &fpa);
1709 if (error)
1710 goto done;
1712 if (list_refs_only) {
1713 error = list_remote_refs(&symrefs, &refs);
1714 goto done;
1717 if (pack_hash == NULL) {
1718 error = got_error_fmt(GOT_ERR_FETCH_FAILED, "%s",
1719 "server sent an empty pack file");
1720 goto done;
1722 error = got_object_id_str(&id_str, pack_hash);
1723 if (error)
1724 goto done;
1725 if (verbosity >= 0)
1726 printf("\nFetched %s.pack\n", id_str);
1727 free(id_str);
1729 /* Set up references provided with the pack file. */
1730 TAILQ_FOREACH(pe, &refs, entry) {
1731 const char *refname = pe->path;
1732 struct got_object_id *id = pe->data;
1733 char *remote_refname;
1735 if (is_wanted_ref(&wanted_refs, refname) &&
1736 !mirror_references) {
1737 error = create_wanted_ref(refname, id,
1738 GOT_FETCH_DEFAULT_REMOTE_NAME,
1739 verbosity - 1, repo);
1740 if (error)
1741 goto done;
1742 continue;
1745 error = create_ref(refname, id, verbosity - 1, repo);
1746 if (error)
1747 goto done;
1749 if (mirror_references)
1750 continue;
1752 if (strncmp("refs/heads/", refname, 11) != 0)
1753 continue;
1755 if (asprintf(&remote_refname,
1756 "refs/remotes/%s/%s", GOT_FETCH_DEFAULT_REMOTE_NAME,
1757 refname + 11) == -1) {
1758 error = got_error_from_errno("asprintf");
1759 goto done;
1761 error = create_ref(remote_refname, id, verbosity - 1, repo);
1762 free(remote_refname);
1763 if (error)
1764 goto done;
1767 /* Set the HEAD reference if the server provided one. */
1768 TAILQ_FOREACH(pe, &symrefs, entry) {
1769 struct got_reference *target_ref;
1770 const char *refname = pe->path;
1771 const char *target = pe->data;
1772 char *remote_refname = NULL, *remote_target = NULL;
1774 if (strcmp(refname, GOT_REF_HEAD) != 0)
1775 continue;
1777 error = got_ref_open(&target_ref, repo, target, 0);
1778 if (error) {
1779 if (error->code == GOT_ERR_NOT_REF) {
1780 error = NULL;
1781 continue;
1783 goto done;
1786 error = create_symref(refname, target_ref, verbosity, repo);
1787 got_ref_close(target_ref);
1788 if (error)
1789 goto done;
1791 if (mirror_references)
1792 continue;
1794 if (strncmp("refs/heads/", target, 11) != 0)
1795 continue;
1797 if (asprintf(&remote_refname,
1798 "refs/remotes/%s/%s", GOT_FETCH_DEFAULT_REMOTE_NAME,
1799 refname) == -1) {
1800 error = got_error_from_errno("asprintf");
1801 goto done;
1803 if (asprintf(&remote_target,
1804 "refs/remotes/%s/%s", GOT_FETCH_DEFAULT_REMOTE_NAME,
1805 target + 11) == -1) {
1806 error = got_error_from_errno("asprintf");
1807 free(remote_refname);
1808 goto done;
1810 error = got_ref_open(&target_ref, repo, remote_target, 0);
1811 if (error) {
1812 free(remote_refname);
1813 free(remote_target);
1814 if (error->code == GOT_ERR_NOT_REF) {
1815 error = NULL;
1816 continue;
1818 goto done;
1820 error = create_symref(remote_refname, target_ref,
1821 verbosity - 1, repo);
1822 free(remote_refname);
1823 free(remote_target);
1824 got_ref_close(target_ref);
1825 if (error)
1826 goto done;
1828 if (pe == NULL) {
1830 * We failed to set the HEAD reference. If we asked for
1831 * a set of wanted branches use the first of one of those
1832 * which could be fetched instead.
1834 TAILQ_FOREACH(pe, &wanted_branches, entry) {
1835 const char *target = pe->path;
1836 struct got_reference *target_ref;
1838 error = got_ref_open(&target_ref, repo, target, 0);
1839 if (error) {
1840 if (error->code == GOT_ERR_NOT_REF) {
1841 error = NULL;
1842 continue;
1844 goto done;
1847 error = create_symref(GOT_REF_HEAD, target_ref,
1848 verbosity, repo);
1849 got_ref_close(target_ref);
1850 if (error)
1851 goto done;
1852 break;
1855 if (!fpa.configs_created && pe != NULL) {
1856 error = create_config_files(fpa.config_info.proto,
1857 fpa.config_info.host, fpa.config_info.port,
1858 fpa.config_info.remote_repo_path,
1859 fpa.config_info.git_url,
1860 fpa.config_info.fetch_all_branches,
1861 fpa.config_info.mirror_references,
1862 fpa.config_info.symrefs,
1863 fpa.config_info.wanted_branches,
1864 fpa.config_info.wanted_refs, fpa.repo);
1865 if (error)
1866 goto done;
1870 if (verbosity >= 0)
1871 printf("Created %s repository '%s'\n",
1872 mirror_references ? "mirrored" : "cloned", repo_path);
1873 done:
1874 if (pack_fds) {
1875 const struct got_error *pack_err =
1876 got_repo_pack_fds_close(pack_fds);
1877 if (error == NULL)
1878 error = pack_err;
1880 if (fetchpid > 0) {
1881 if (kill(fetchpid, SIGTERM) == -1)
1882 error = got_error_from_errno("kill");
1883 if (waitpid(fetchpid, &fetchstatus, 0) == -1 && error == NULL)
1884 error = got_error_from_errno("waitpid");
1886 if (fetchfd != -1 && close(fetchfd) == -1 && error == NULL)
1887 error = got_error_from_errno("close");
1888 if (repo) {
1889 const struct got_error *close_err = got_repo_close(repo);
1890 if (error == NULL)
1891 error = close_err;
1893 got_pathlist_free(&refs, GOT_PATHLIST_FREE_ALL);
1894 got_pathlist_free(&symrefs, GOT_PATHLIST_FREE_ALL);
1895 got_pathlist_free(&wanted_branches, GOT_PATHLIST_FREE_NONE);
1896 got_pathlist_free(&wanted_refs, GOT_PATHLIST_FREE_NONE);
1897 free(pack_hash);
1898 free(proto);
1899 free(host);
1900 free(port);
1901 free(server_path);
1902 free(repo_name);
1903 free(default_destdir);
1904 free(git_url);
1905 return error;
1908 static const struct got_error *
1909 update_ref(struct got_reference *ref, struct got_object_id *new_id,
1910 int replace_tags, int verbosity, struct got_repository *repo)
1912 const struct got_error *err = NULL;
1913 char *new_id_str = NULL;
1914 struct got_object_id *old_id = NULL;
1916 err = got_object_id_str(&new_id_str, new_id);
1917 if (err)
1918 goto done;
1920 if (!replace_tags &&
1921 strncmp(got_ref_get_name(ref), "refs/tags/", 10) == 0) {
1922 err = got_ref_resolve(&old_id, repo, ref);
1923 if (err)
1924 goto done;
1925 if (got_object_id_cmp(old_id, new_id) == 0)
1926 goto done;
1927 if (verbosity >= 0) {
1928 printf("Rejecting update of existing tag %s: %s\n",
1929 got_ref_get_name(ref), new_id_str);
1931 goto done;
1934 if (got_ref_is_symbolic(ref)) {
1935 if (verbosity >= 0) {
1936 printf("Replacing reference %s: %s\n",
1937 got_ref_get_name(ref),
1938 got_ref_get_symref_target(ref));
1940 err = got_ref_change_symref_to_ref(ref, new_id);
1941 if (err)
1942 goto done;
1943 err = got_ref_write(ref, repo);
1944 if (err)
1945 goto done;
1946 } else {
1947 err = got_ref_resolve(&old_id, repo, ref);
1948 if (err)
1949 goto done;
1950 if (got_object_id_cmp(old_id, new_id) == 0)
1951 goto done;
1953 err = got_ref_change_ref(ref, new_id);
1954 if (err)
1955 goto done;
1956 err = got_ref_write(ref, repo);
1957 if (err)
1958 goto done;
1961 if (verbosity >= 0)
1962 printf("Updated %s: %s\n", got_ref_get_name(ref),
1963 new_id_str);
1964 done:
1965 free(old_id);
1966 free(new_id_str);
1967 return err;
1970 static const struct got_error *
1971 update_wanted_ref(const char *refname, struct got_object_id *id,
1972 const char *remote_repo_name, int verbosity, struct got_repository *repo)
1974 const struct got_error *err, *unlock_err;
1975 char *remote_refname;
1976 struct got_reference *ref;
1978 if (strncmp("refs/", refname, 5) == 0)
1979 refname += 5;
1981 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
1982 remote_repo_name, refname) == -1)
1983 return got_error_from_errno("asprintf");
1985 err = got_ref_open(&ref, repo, remote_refname, 1);
1986 if (err) {
1987 if (err->code != GOT_ERR_NOT_REF)
1988 goto done;
1989 err = create_ref(remote_refname, id, verbosity, repo);
1990 } else {
1991 err = update_ref(ref, id, 0, verbosity, repo);
1992 unlock_err = got_ref_unlock(ref);
1993 if (unlock_err && err == NULL)
1994 err = unlock_err;
1995 got_ref_close(ref);
1997 done:
1998 free(remote_refname);
1999 return err;
2002 __dead static void
2003 usage_checkout(void)
2005 fprintf(stderr, "usage: %s checkout [-Eq] [-b branch] [-c commit] "
2006 "[-p path-prefix] repository-path [work-tree-path]\n",
2007 getprogname());
2008 exit(1);
2011 static void
2012 show_worktree_base_ref_warning(void)
2014 fprintf(stderr, "%s: warning: could not create a reference "
2015 "to the work tree's base commit; the commit could be "
2016 "garbage-collected by Git or 'gotadmin cleanup'; making the "
2017 "repository writable and running 'got update' will prevent this\n",
2018 getprogname());
2021 struct got_checkout_progress_arg {
2022 const char *worktree_path;
2023 int had_base_commit_ref_error;
2024 int verbosity;
2027 static const struct got_error *
2028 checkout_progress(void *arg, unsigned char status, const char *path)
2030 struct got_checkout_progress_arg *a = arg;
2032 /* Base commit bump happens silently. */
2033 if (status == GOT_STATUS_BUMP_BASE)
2034 return NULL;
2036 if (status == GOT_STATUS_BASE_REF_ERR) {
2037 a->had_base_commit_ref_error = 1;
2038 return NULL;
2041 while (path[0] == '/')
2042 path++;
2044 if (a->verbosity >= 0)
2045 printf("%c %s/%s\n", status, a->worktree_path, path);
2047 return NULL;
2050 static const struct got_error *
2051 check_cancelled(void *arg)
2053 if (sigint_received || sigpipe_received)
2054 return got_error(GOT_ERR_CANCELLED);
2055 return NULL;
2058 static const struct got_error *
2059 check_linear_ancestry(struct got_object_id *commit_id,
2060 struct got_object_id *base_commit_id, int allow_forwards_in_time_only,
2061 struct got_repository *repo)
2063 const struct got_error *err = NULL;
2064 struct got_object_id *yca_id;
2066 err = got_commit_graph_find_youngest_common_ancestor(&yca_id,
2067 commit_id, base_commit_id, 1, 0, repo, check_cancelled, NULL);
2068 if (err)
2069 return err;
2071 if (yca_id == NULL)
2072 return got_error(GOT_ERR_ANCESTRY);
2075 * Require a straight line of history between the target commit
2076 * and the work tree's base commit.
2078 * Non-linear situations such as this require a rebase:
2080 * (commit) D F (base_commit)
2081 * \ /
2082 * C E
2083 * \ /
2084 * B (yca)
2085 * |
2086 * A
2088 * 'got update' only handles linear cases:
2089 * Update forwards in time: A (base/yca) - B - C - D (commit)
2090 * Update backwards in time: D (base) - C - B - A (commit/yca)
2092 if (allow_forwards_in_time_only) {
2093 if (got_object_id_cmp(base_commit_id, yca_id) != 0)
2094 return got_error(GOT_ERR_ANCESTRY);
2095 } else if (got_object_id_cmp(commit_id, yca_id) != 0 &&
2096 got_object_id_cmp(base_commit_id, yca_id) != 0)
2097 return got_error(GOT_ERR_ANCESTRY);
2099 free(yca_id);
2100 return NULL;
2103 static const struct got_error *
2104 check_same_branch(struct got_object_id *commit_id,
2105 struct got_reference *head_ref, struct got_repository *repo)
2107 const struct got_error *err = NULL;
2108 struct got_commit_graph *graph = NULL;
2109 struct got_object_id *head_commit_id = NULL;
2111 err = got_ref_resolve(&head_commit_id, repo, head_ref);
2112 if (err)
2113 goto done;
2115 if (got_object_id_cmp(head_commit_id, commit_id) == 0)
2116 goto done;
2118 err = got_commit_graph_open(&graph, "/", 1);
2119 if (err)
2120 goto done;
2122 err = got_commit_graph_bfsort(graph, head_commit_id, repo,
2123 check_cancelled, NULL);
2124 if (err)
2125 goto done;
2127 for (;;) {
2128 struct got_object_id id;
2130 err = got_commit_graph_iter_next(&id, graph, repo,
2131 check_cancelled, NULL);
2132 if (err) {
2133 if (err->code == GOT_ERR_ITER_COMPLETED)
2134 err = got_error(GOT_ERR_ANCESTRY);
2135 break;
2138 if (got_object_id_cmp(&id, commit_id) == 0)
2139 break;
2141 done:
2142 if (graph)
2143 got_commit_graph_close(graph);
2144 free(head_commit_id);
2145 return err;
2148 static const struct got_error *
2149 checkout_ancestry_error(struct got_reference *ref, const char *commit_id_str)
2151 static char msg[512];
2152 const char *branch_name;
2154 if (got_ref_is_symbolic(ref))
2155 branch_name = got_ref_get_symref_target(ref);
2156 else
2157 branch_name = got_ref_get_name(ref);
2159 if (strncmp("refs/heads/", branch_name, 11) == 0)
2160 branch_name += 11;
2162 snprintf(msg, sizeof(msg),
2163 "target commit is not contained in branch '%s'; "
2164 "the branch to use must be specified with -b; "
2165 "if necessary a new branch can be created for "
2166 "this commit with 'got branch -c %s BRANCH_NAME'",
2167 branch_name, commit_id_str);
2169 return got_error_msg(GOT_ERR_ANCESTRY, msg);
2172 static const struct got_error *
2173 cmd_checkout(int argc, char *argv[])
2175 const struct got_error *error = NULL;
2176 struct got_repository *repo = NULL;
2177 struct got_reference *head_ref = NULL, *ref = NULL;
2178 struct got_worktree *worktree = NULL;
2179 char *repo_path = NULL;
2180 char *worktree_path = NULL;
2181 const char *path_prefix = "";
2182 const char *branch_name = GOT_REF_HEAD, *refname = NULL;
2183 char *commit_id_str = NULL;
2184 struct got_object_id *commit_id = NULL;
2185 char *cwd = NULL;
2186 int ch, same_path_prefix, allow_nonempty = 0, verbosity = 0;
2187 struct got_pathlist_head paths;
2188 struct got_checkout_progress_arg cpa;
2189 int *pack_fds = NULL;
2191 TAILQ_INIT(&paths);
2193 #ifndef PROFILE
2194 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
2195 "unveil", NULL) == -1)
2196 err(1, "pledge");
2197 #endif
2199 while ((ch = getopt(argc, argv, "b:c:Ep:q")) != -1) {
2200 switch (ch) {
2201 case 'b':
2202 branch_name = optarg;
2203 break;
2204 case 'c':
2205 commit_id_str = strdup(optarg);
2206 if (commit_id_str == NULL)
2207 return got_error_from_errno("strdup");
2208 break;
2209 case 'E':
2210 allow_nonempty = 1;
2211 break;
2212 case 'p':
2213 path_prefix = optarg;
2214 break;
2215 case 'q':
2216 verbosity = -1;
2217 break;
2218 default:
2219 usage_checkout();
2220 /* NOTREACHED */
2224 argc -= optind;
2225 argv += optind;
2227 if (argc == 1) {
2228 char *base, *dotgit;
2229 const char *path;
2230 repo_path = realpath(argv[0], NULL);
2231 if (repo_path == NULL)
2232 return got_error_from_errno2("realpath", argv[0]);
2233 cwd = getcwd(NULL, 0);
2234 if (cwd == NULL) {
2235 error = got_error_from_errno("getcwd");
2236 goto done;
2238 if (path_prefix[0])
2239 path = path_prefix;
2240 else
2241 path = repo_path;
2242 error = got_path_basename(&base, path);
2243 if (error)
2244 goto done;
2245 dotgit = strstr(base, ".git");
2246 if (dotgit)
2247 *dotgit = '\0';
2248 if (asprintf(&worktree_path, "%s/%s", cwd, base) == -1) {
2249 error = got_error_from_errno("asprintf");
2250 free(base);
2251 goto done;
2253 free(base);
2254 } else if (argc == 2) {
2255 repo_path = realpath(argv[0], NULL);
2256 if (repo_path == NULL) {
2257 error = got_error_from_errno2("realpath", argv[0]);
2258 goto done;
2260 worktree_path = realpath(argv[1], NULL);
2261 if (worktree_path == NULL) {
2262 if (errno != ENOENT) {
2263 error = got_error_from_errno2("realpath",
2264 argv[1]);
2265 goto done;
2267 worktree_path = strdup(argv[1]);
2268 if (worktree_path == NULL) {
2269 error = got_error_from_errno("strdup");
2270 goto done;
2273 } else
2274 usage_checkout();
2276 got_path_strip_trailing_slashes(repo_path);
2277 got_path_strip_trailing_slashes(worktree_path);
2279 error = got_repo_pack_fds_open(&pack_fds);
2280 if (error != NULL)
2281 goto done;
2283 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
2284 if (error != NULL)
2285 goto done;
2287 /* Pre-create work tree path for unveil(2) */
2288 error = got_path_mkdir(worktree_path);
2289 if (error) {
2290 if (!(error->code == GOT_ERR_ERRNO && errno == EISDIR) &&
2291 !(error->code == GOT_ERR_ERRNO && errno == EEXIST))
2292 goto done;
2293 if (!allow_nonempty &&
2294 !got_path_dir_is_empty(worktree_path)) {
2295 error = got_error_path(worktree_path,
2296 GOT_ERR_DIR_NOT_EMPTY);
2297 goto done;
2301 error = apply_unveil(got_repo_get_path(repo), 0, worktree_path);
2302 if (error)
2303 goto done;
2305 error = got_ref_open(&head_ref, repo, branch_name, 0);
2306 if (error != NULL)
2307 goto done;
2309 error = got_worktree_init(worktree_path, head_ref, path_prefix,
2310 GOT_WORKTREE_CVG_DIR, repo);
2311 if (error != NULL && !(error->code == GOT_ERR_ERRNO && errno == EEXIST))
2312 goto done;
2314 error = got_worktree_open(&worktree, worktree_path, GOT_WORKTREE_CVG_DIR);
2315 if (error != NULL)
2316 goto done;
2318 error = got_worktree_match_path_prefix(&same_path_prefix, worktree,
2319 path_prefix);
2320 if (error != NULL)
2321 goto done;
2322 if (!same_path_prefix) {
2323 error = got_error(GOT_ERR_PATH_PREFIX);
2324 goto done;
2327 if (commit_id_str) {
2328 struct got_reflist_head refs;
2329 TAILQ_INIT(&refs);
2330 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
2331 NULL);
2332 if (error)
2333 goto done;
2334 error = got_repo_match_object_id(&commit_id, NULL,
2335 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
2336 got_ref_list_free(&refs);
2337 if (error)
2338 goto done;
2339 error = check_linear_ancestry(commit_id,
2340 got_worktree_get_base_commit_id(worktree), 0, repo);
2341 if (error != NULL) {
2342 if (error->code == GOT_ERR_ANCESTRY) {
2343 error = checkout_ancestry_error(
2344 head_ref, commit_id_str);
2346 goto done;
2348 error = check_same_branch(commit_id, head_ref, repo);
2349 if (error) {
2350 if (error->code == GOT_ERR_ANCESTRY) {
2351 error = checkout_ancestry_error(
2352 head_ref, commit_id_str);
2354 goto done;
2356 error = got_worktree_set_base_commit_id(worktree, repo,
2357 commit_id);
2358 if (error)
2359 goto done;
2360 /* Expand potentially abbreviated commit ID string. */
2361 free(commit_id_str);
2362 error = got_object_id_str(&commit_id_str, commit_id);
2363 if (error)
2364 goto done;
2365 } else {
2366 commit_id = got_object_id_dup(
2367 got_worktree_get_base_commit_id(worktree));
2368 if (commit_id == NULL) {
2369 error = got_error_from_errno("got_object_id_dup");
2370 goto done;
2372 error = got_object_id_str(&commit_id_str, commit_id);
2373 if (error)
2374 goto done;
2377 error = got_pathlist_append(&paths, "", NULL);
2378 if (error)
2379 goto done;
2380 cpa.worktree_path = worktree_path;
2381 cpa.had_base_commit_ref_error = 0;
2382 cpa.verbosity = verbosity;
2383 error = got_worktree_checkout_files(worktree, &paths, repo,
2384 checkout_progress, &cpa, check_cancelled, NULL);
2385 if (error != NULL)
2386 goto done;
2388 if (got_ref_is_symbolic(head_ref)) {
2389 error = got_ref_resolve_symbolic(&ref, repo, head_ref);
2390 if (error)
2391 goto done;
2392 refname = got_ref_get_name(ref);
2393 } else
2394 refname = got_ref_get_name(head_ref);
2395 printf("Checked out %s: %s\n", refname, commit_id_str);
2396 printf("Now shut up and hack\n");
2397 if (cpa.had_base_commit_ref_error)
2398 show_worktree_base_ref_warning();
2399 done:
2400 if (pack_fds) {
2401 const struct got_error *pack_err =
2402 got_repo_pack_fds_close(pack_fds);
2403 if (error == NULL)
2404 error = pack_err;
2406 if (head_ref)
2407 got_ref_close(head_ref);
2408 if (ref)
2409 got_ref_close(ref);
2410 if (repo) {
2411 const struct got_error *close_err = got_repo_close(repo);
2412 if (error == NULL)
2413 error = close_err;
2415 got_pathlist_free(&paths, GOT_PATHLIST_FREE_NONE);
2416 free(commit_id_str);
2417 free(commit_id);
2418 free(repo_path);
2419 free(worktree_path);
2420 free(cwd);
2421 return error;
2424 struct got_update_progress_arg {
2425 int did_something;
2426 int conflicts;
2427 int obstructed;
2428 int not_updated;
2429 int missing;
2430 int not_deleted;
2431 int unversioned;
2432 int verbosity;
2435 static void
2436 print_update_progress_stats(struct got_update_progress_arg *upa)
2438 if (!upa->did_something)
2439 return;
2441 if (upa->conflicts > 0)
2442 printf("Files with new merge conflicts: %d\n", upa->conflicts);
2443 if (upa->obstructed > 0)
2444 printf("File paths obstructed by a non-regular file: %d\n",
2445 upa->obstructed);
2446 if (upa->not_updated > 0)
2447 printf("Files not updated because of existing merge "
2448 "conflicts: %d\n", upa->not_updated);
2452 * The meaning of some status codes differs between merge-style operations and
2453 * update operations. For example, the ! status code means "file was missing"
2454 * if changes were merged into the work tree, and "missing file was restored"
2455 * if the work tree was updated. This function should be used by any operation
2456 * which merges changes into the work tree without updating the work tree.
2458 static void
2459 print_merge_progress_stats(struct got_update_progress_arg *upa)
2461 if (!upa->did_something)
2462 return;
2464 if (upa->conflicts > 0)
2465 printf("Files with new merge conflicts: %d\n", upa->conflicts);
2466 if (upa->obstructed > 0)
2467 printf("File paths obstructed by a non-regular file: %d\n",
2468 upa->obstructed);
2469 if (upa->missing > 0)
2470 printf("Files which had incoming changes but could not be "
2471 "found in the work tree: %d\n", upa->missing);
2472 if (upa->not_deleted > 0)
2473 printf("Files not deleted due to differences in deleted "
2474 "content: %d\n", upa->not_deleted);
2475 if (upa->unversioned > 0)
2476 printf("Files not merged because an unversioned file was "
2477 "found in the work tree: %d\n", upa->unversioned);
2480 __dead static void
2481 usage_update(void)
2483 fprintf(stderr, "usage: %s update [-qtvX] [-c commit] [-r remote] "
2484 "[path ...]\n", getprogname());
2485 exit(1);
2488 static const struct got_error *
2489 update_progress(void *arg, unsigned char status, const char *path)
2491 struct got_update_progress_arg *upa = arg;
2493 if (status == GOT_STATUS_EXISTS ||
2494 status == GOT_STATUS_BASE_REF_ERR)
2495 return NULL;
2497 upa->did_something = 1;
2499 /* Base commit bump happens silently. */
2500 if (status == GOT_STATUS_BUMP_BASE)
2501 return NULL;
2503 if (status == GOT_STATUS_CONFLICT)
2504 upa->conflicts++;
2505 if (status == GOT_STATUS_OBSTRUCTED)
2506 upa->obstructed++;
2507 if (status == GOT_STATUS_CANNOT_UPDATE)
2508 upa->not_updated++;
2509 if (status == GOT_STATUS_MISSING)
2510 upa->missing++;
2511 if (status == GOT_STATUS_CANNOT_DELETE)
2512 upa->not_deleted++;
2513 if (status == GOT_STATUS_UNVERSIONED)
2514 upa->unversioned++;
2516 while (path[0] == '/')
2517 path++;
2518 if (upa->verbosity >= 0)
2519 printf("%c %s\n", status, path);
2521 return NULL;
2524 static const struct got_error *
2525 check_rebase_or_histedit_in_progress(struct got_worktree *worktree)
2527 const struct got_error *err;
2528 int in_progress;
2530 err = got_worktree_rebase_in_progress(&in_progress, worktree);
2531 if (err)
2532 return err;
2533 if (in_progress)
2534 return got_error(GOT_ERR_REBASING);
2536 err = got_worktree_histedit_in_progress(&in_progress, worktree);
2537 if (err)
2538 return err;
2539 if (in_progress)
2540 return got_error(GOT_ERR_HISTEDIT_BUSY);
2542 return NULL;
2545 static const struct got_error *
2546 check_merge_in_progress(struct got_worktree *worktree,
2547 struct got_repository *repo)
2549 const struct got_error *err;
2550 int in_progress;
2552 err = got_worktree_merge_in_progress(&in_progress, worktree, repo);
2553 if (err)
2554 return err;
2555 if (in_progress)
2556 return got_error(GOT_ERR_MERGE_BUSY);
2558 return NULL;
2561 static const struct got_error *
2562 get_worktree_paths_from_argv(struct got_pathlist_head *paths, int argc,
2563 char *argv[], struct got_worktree *worktree)
2565 const struct got_error *err = NULL;
2566 char *path;
2567 struct got_pathlist_entry *new;
2568 int i;
2570 if (argc == 0) {
2571 path = strdup("");
2572 if (path == NULL)
2573 return got_error_from_errno("strdup");
2574 return got_pathlist_append(paths, path, NULL);
2577 for (i = 0; i < argc; i++) {
2578 err = got_worktree_resolve_path(&path, worktree, argv[i]);
2579 if (err)
2580 break;
2581 err = got_pathlist_insert(&new, paths, path, NULL);
2582 if (err || new == NULL /* duplicate */) {
2583 free(path);
2584 if (err)
2585 break;
2589 return err;
2592 static const struct got_error *
2593 wrap_not_worktree_error(const struct got_error *orig_err,
2594 const char *cmdname, const char *path)
2596 const struct got_error *err;
2597 struct got_repository *repo;
2598 static char msg[512];
2599 int *pack_fds = NULL;
2601 err = got_repo_pack_fds_open(&pack_fds);
2602 if (err)
2603 return err;
2605 err = got_repo_open(&repo, path, NULL, pack_fds);
2606 if (err)
2607 return orig_err;
2609 snprintf(msg, sizeof(msg),
2610 "'got %s' needs a work tree in addition to a git repository\n"
2611 "Work trees can be checked out from this Git repository with "
2612 "'got checkout'.\n"
2613 "The got(1) manual page contains more information.", cmdname);
2614 err = got_error_msg(GOT_ERR_NOT_WORKTREE, msg);
2615 if (repo) {
2616 const struct got_error *close_err = got_repo_close(repo);
2617 if (err == NULL)
2618 err = close_err;
2620 if (pack_fds) {
2621 const struct got_error *pack_err =
2622 got_repo_pack_fds_close(pack_fds);
2623 if (err == NULL)
2624 err = pack_err;
2626 return err;
2629 static const struct got_error *
2630 cmd_update(int argc, char *argv[])
2632 const struct got_error *error = NULL, *unlock_err;
2633 char *worktree_path = NULL;
2634 const char *repo_path = NULL;
2635 const char *remote_name = NULL;
2636 char *proto = NULL, *host = NULL, *port = NULL;
2637 char *repo_name = NULL, *server_path = NULL;
2638 const struct got_remote_repo *remotes, *remote = NULL;
2639 int nremotes;
2640 char *id_str = NULL;
2641 struct got_repository *repo = NULL;
2642 struct got_worktree *worktree = NULL;
2643 const struct got_gotconfig *repo_conf = NULL, *worktree_conf = NULL;
2644 struct got_pathlist_head paths, refs, symrefs;
2645 struct got_pathlist_head wanted_branches, wanted_refs;
2646 struct got_pathlist_entry *pe;
2647 struct got_reflist_head remote_refs;
2648 struct got_reflist_entry *re;
2649 struct got_object_id *pack_hash = NULL;
2650 int i, ch, fetchfd = -1, fetchstatus;
2651 pid_t fetchpid = -1;
2652 struct got_fetch_progress_arg fpa;
2653 struct got_update_progress_arg upa;
2654 int verbosity = 0;
2655 int delete_remote = 0;
2656 int replace_tags = 0;
2657 int *pack_fds = NULL;
2658 const char *remote_head = NULL, *worktree_branch = NULL;
2659 struct got_object_id *commit_id = NULL;
2660 char *commit_id_str = NULL;
2661 const char *refname;
2662 struct got_reference *head_ref = NULL;
2664 TAILQ_INIT(&paths);
2665 TAILQ_INIT(&refs);
2666 TAILQ_INIT(&symrefs);
2667 TAILQ_INIT(&remote_refs);
2668 TAILQ_INIT(&wanted_branches);
2669 TAILQ_INIT(&wanted_refs);
2671 while ((ch = getopt(argc, argv, "c:qr:vX")) != -1) {
2672 switch (ch) {
2673 case 'c':
2674 commit_id_str = strdup(optarg);
2675 if (commit_id_str == NULL)
2676 return got_error_from_errno("strdup");
2677 break;
2678 case 't':
2679 replace_tags = 1;
2680 break;
2681 case 'q':
2682 verbosity = -1;
2683 break;
2684 case 'r':
2685 remote_name = optarg;
2686 break;
2687 case 'v':
2688 if (verbosity < 0)
2689 verbosity = 0;
2690 else if (verbosity < 3)
2691 verbosity++;
2692 break;
2693 case 'X':
2694 delete_remote = 1;
2695 break;
2696 default:
2697 usage_update();
2698 break;
2701 argc -= optind;
2702 argv += optind;
2704 if (delete_remote) {
2705 if (replace_tags)
2706 option_conflict('X', 't');
2707 if (remote_name == NULL)
2708 errx(1, "-X option requires a remote name");
2710 if (remote_name == NULL)
2711 remote_name = GOT_FETCH_DEFAULT_REMOTE_NAME;
2713 worktree_path = getcwd(NULL, 0);
2714 if (worktree_path == NULL) {
2715 error = got_error_from_errno("getcwd");
2716 goto done;
2718 error = got_worktree_open(&worktree, worktree_path, GOT_WORKTREE_CVG_DIR);
2719 if (error) {
2720 if (error->code == GOT_ERR_NOT_WORKTREE)
2721 error = wrap_not_worktree_error(error, "update",
2722 worktree_path);
2723 goto done;
2725 repo_path = got_worktree_get_repo_path(worktree);
2727 error = got_repo_pack_fds_open(&pack_fds);
2728 if (error != NULL)
2729 goto done;
2731 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
2732 if (error)
2733 goto done;
2735 error = check_rebase_or_histedit_in_progress(worktree);
2736 if (error)
2737 goto done;
2738 error = check_merge_in_progress(worktree, repo);
2739 if (error)
2740 goto done;
2742 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
2743 if (error)
2744 goto done;
2746 worktree_conf = got_worktree_get_gotconfig(worktree);
2747 if (worktree_conf) {
2748 got_gotconfig_get_remotes(&nremotes, &remotes,
2749 worktree_conf);
2750 for (i = 0; i < nremotes; i++) {
2751 if (strcmp(remotes[i].name, remote_name) == 0) {
2752 remote = &remotes[i];
2753 break;
2758 if (remote == NULL) {
2759 repo_conf = got_repo_get_gotconfig(repo);
2760 if (repo_conf) {
2761 got_gotconfig_get_remotes(&nremotes, &remotes,
2762 repo_conf);
2763 for (i = 0; i < nremotes; i++) {
2764 if (strcmp(remotes[i].name, remote_name) == 0) {
2765 remote = &remotes[i];
2766 break;
2771 if (remote == NULL) {
2772 got_repo_get_gitconfig_remotes(&nremotes, &remotes, repo);
2773 for (i = 0; i < nremotes; i++) {
2774 if (strcmp(remotes[i].name, remote_name) == 0) {
2775 remote = &remotes[i];
2776 break;
2780 if (remote == NULL) {
2781 error = got_error_path(remote_name, GOT_ERR_NO_REMOTE);
2782 goto done;
2785 error = got_dial_parse_uri(&proto, &host, &port, &server_path,
2786 &repo_name, remote->fetch_url);
2787 if (error)
2788 goto done;
2790 if (strcmp(proto, "git") == 0) {
2791 #ifndef PROFILE
2792 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
2793 "sendfd dns inet unveil", NULL) == -1)
2794 err(1, "pledge");
2795 #endif
2796 } else if (strcmp(proto, "git+ssh") == 0 ||
2797 strcmp(proto, "ssh") == 0) {
2798 #ifndef PROFILE
2799 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
2800 "sendfd unveil", NULL) == -1)
2801 err(1, "pledge");
2802 #endif
2803 } else if (strcmp(proto, "http") == 0 ||
2804 strcmp(proto, "git+http") == 0) {
2805 error = got_error_path(proto, GOT_ERR_NOT_IMPL);
2806 goto done;
2807 } else {
2808 error = got_error_path(proto, GOT_ERR_BAD_PROTO);
2809 goto done;
2812 error = got_dial_apply_unveil(proto);
2813 if (error)
2814 goto done;
2816 error = apply_unveil(got_repo_get_path(repo), 0,
2817 got_worktree_get_root_path(worktree));
2818 if (error)
2819 goto done;
2821 if (verbosity >= 0) {
2822 printf("Connecting to \"%s\" %s://%s%s%s%s%s\n",
2823 remote->name, proto, host,
2824 port ? ":" : "", port ? port : "",
2825 *server_path == '/' ? "" : "/", server_path);
2828 error = got_fetch_connect(&fetchpid, &fetchfd, proto, host, port,
2829 server_path, verbosity);
2830 if (error)
2831 goto done;
2834 * If set, get this remote's HEAD ref target so
2835 * if it has changed on the server we can fetch it.
2837 error = got_ref_list(&remote_refs, repo, "refs/remotes",
2838 got_ref_cmp_by_name, repo);
2839 if (error)
2840 goto done;
2842 TAILQ_FOREACH(re, &remote_refs, entry) {
2843 const char *remote_refname, *remote_target;
2844 size_t remote_name_len;
2846 if (!got_ref_is_symbolic(re->ref))
2847 continue;
2849 remote_name_len = strlen(remote->name);
2850 remote_refname = got_ref_get_name(re->ref);
2852 /* we only want refs/remotes/$remote->name/HEAD */
2853 if (strncmp(remote_refname + 13, remote->name,
2854 remote_name_len) != 0)
2855 continue;
2857 if (strcmp(remote_refname + remote_name_len + 14,
2858 GOT_REF_HEAD) != 0)
2859 continue;
2862 * Take the name itself because we already
2863 * only match with refs/heads/ in fetch_pack().
2865 remote_target = got_ref_get_symref_target(re->ref);
2866 remote_head = remote_target + remote_name_len + 14;
2867 break;
2870 refname = got_worktree_get_head_ref_name(worktree);
2871 if (strncmp(refname, "refs/heads/", 11) == 0)
2872 worktree_branch = refname;
2874 fpa.last_scaled_size[0] = '\0';
2875 fpa.last_p_indexed = -1;
2876 fpa.last_p_resolved = -1;
2877 fpa.verbosity = verbosity;
2878 fpa.repo = repo;
2879 fpa.create_configs = 0;
2880 fpa.configs_created = 0;
2881 memset(&fpa.config_info, 0, sizeof(fpa.config_info));
2883 error = got_fetch_pack(&pack_hash, &refs, &symrefs, remote->name,
2884 remote->mirror_references, 0, &wanted_branches, &wanted_refs,
2885 0, verbosity, fetchfd, repo, worktree_branch, remote_head,
2886 0, fetch_progress, &fpa);
2887 if (error)
2888 goto done;
2890 if (pack_hash != NULL && verbosity >= 0) {
2891 error = got_object_id_str(&id_str, pack_hash);
2892 if (error)
2893 goto done;
2894 printf("\nFetched %s.pack\n", id_str);
2895 free(id_str);
2896 id_str = NULL;
2899 /* Update references provided with the pack file. */
2900 TAILQ_FOREACH(pe, &refs, entry) {
2901 const char *refname = pe->path;
2902 struct got_object_id *id = pe->data;
2903 struct got_reference *ref;
2905 if (is_wanted_ref(&wanted_refs, refname)) {
2906 error = update_wanted_ref(refname, id,
2907 remote->name, verbosity, repo);
2908 if (error)
2909 goto done;
2910 continue;
2913 error = got_ref_open(&ref, repo, refname, 1);
2914 if (error) {
2915 if (error->code != GOT_ERR_NOT_REF)
2916 goto done;
2917 error = create_ref(refname, id, verbosity,
2918 repo);
2919 if (error)
2920 goto done;
2921 } else {
2922 error = update_ref(ref, id, replace_tags,
2923 verbosity-1, repo);
2924 unlock_err = got_ref_unlock(ref);
2925 if (unlock_err && error == NULL)
2926 error = unlock_err;
2927 got_ref_close(ref);
2928 if (error)
2929 goto done;
2933 /* Update worktree */
2934 error = got_ref_open(&head_ref, repo,
2935 got_worktree_get_head_ref_name(worktree), 0);
2936 if (error != NULL)
2937 goto done;
2938 if (commit_id_str == NULL) {
2939 error = got_ref_resolve(&commit_id, repo, head_ref);
2940 if (error != NULL)
2941 goto done;
2942 error = got_object_id_str(&commit_id_str, commit_id);
2943 if (error != NULL)
2944 goto done;
2945 } else {
2946 struct got_reflist_head refs;
2947 TAILQ_INIT(&refs);
2948 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
2949 NULL);
2950 if (error)
2951 goto done;
2952 error = got_repo_match_object_id(&commit_id, NULL,
2953 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
2954 got_ref_list_free(&refs);
2955 free(commit_id_str);
2956 commit_id_str = NULL;
2957 if (error)
2958 goto done;
2959 error = got_object_id_str(&commit_id_str, commit_id);
2960 if (error)
2961 goto done;
2965 error = check_linear_ancestry(commit_id,
2966 got_worktree_get_base_commit_id(worktree), 0, repo);
2967 if (error != NULL) {
2968 if (error->code == GOT_ERR_ANCESTRY)
2969 error = got_error(GOT_ERR_BRANCH_MOVED);
2970 goto done;
2972 error = check_same_branch(commit_id, head_ref, repo);
2973 if (error)
2974 goto done;
2976 if (got_object_id_cmp(got_worktree_get_base_commit_id(worktree),
2977 commit_id) != 0) {
2978 error = got_worktree_set_base_commit_id(worktree, repo,
2979 commit_id);
2980 if (error)
2981 goto done;
2984 memset(&upa, 0, sizeof(upa));
2985 upa.verbosity = verbosity;
2986 error = got_worktree_checkout_files(worktree, &paths, repo,
2987 update_progress, &upa, check_cancelled, NULL);
2988 if (error != NULL)
2989 goto done;
2991 if (upa.did_something) {
2992 printf("Updated to %s: %s\n",
2993 got_worktree_get_head_ref_name(worktree), commit_id_str);
2994 } else
2995 printf("Already up-to-date\n");
2997 print_update_progress_stats(&upa);
2998 done:
2999 if (fetchpid > 0) {
3000 if (kill(fetchpid, SIGTERM) == -1)
3001 error = got_error_from_errno("kill");
3002 if (waitpid(fetchpid, &fetchstatus, 0) == -1 && error == NULL)
3003 error = got_error_from_errno("waitpid");
3005 if (fetchfd != -1 && close(fetchfd) == -1 && error == NULL)
3006 error = got_error_from_errno("close");
3007 if (repo) {
3008 const struct got_error *close_err = got_repo_close(repo);
3009 if (error == NULL)
3010 error = close_err;
3012 if (worktree)
3013 got_worktree_close(worktree);
3014 if (pack_fds) {
3015 const struct got_error *pack_err =
3016 got_repo_pack_fds_close(pack_fds);
3017 if (error == NULL)
3018 error = pack_err;
3020 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
3021 got_pathlist_free(&refs, GOT_PATHLIST_FREE_ALL);
3022 got_pathlist_free(&symrefs, GOT_PATHLIST_FREE_ALL);
3023 got_pathlist_free(&wanted_branches, GOT_PATHLIST_FREE_NONE);
3024 got_pathlist_free(&wanted_refs, GOT_PATHLIST_FREE_NONE);
3025 got_ref_list_free(&remote_refs);
3026 free(id_str);
3027 free(worktree_path);
3028 free(pack_hash);
3029 free(proto);
3030 free(host);
3031 free(port);
3032 free(server_path);
3033 free(repo_name);
3034 free(commit_id);
3035 free(commit_id_str);
3036 return error;
3039 static const struct got_error *
3040 diff_blobs(struct got_object_id *blob_id1, struct got_object_id *blob_id2,
3041 const char *path, int diff_context, int ignore_whitespace,
3042 int force_text_diff, struct got_diffstat_cb_arg *dsa,
3043 struct got_repository *repo, FILE *outfile)
3045 const struct got_error *err = NULL;
3046 struct got_blob_object *blob1 = NULL, *blob2 = NULL;
3047 FILE *f1 = NULL, *f2 = NULL;
3048 int fd1 = -1, fd2 = -1;
3050 fd1 = got_opentempfd();
3051 if (fd1 == -1)
3052 return got_error_from_errno("got_opentempfd");
3053 fd2 = got_opentempfd();
3054 if (fd2 == -1) {
3055 err = got_error_from_errno("got_opentempfd");
3056 goto done;
3059 if (blob_id1) {
3060 err = got_object_open_as_blob(&blob1, repo, blob_id1, 8192,
3061 fd1);
3062 if (err)
3063 goto done;
3066 err = got_object_open_as_blob(&blob2, repo, blob_id2, 8192, fd2);
3067 if (err)
3068 goto done;
3070 f1 = got_opentemp();
3071 if (f1 == NULL) {
3072 err = got_error_from_errno("got_opentemp");
3073 goto done;
3075 f2 = got_opentemp();
3076 if (f2 == NULL) {
3077 err = got_error_from_errno("got_opentemp");
3078 goto done;
3081 while (path[0] == '/')
3082 path++;
3083 err = got_diff_blob(NULL, NULL, blob1, blob2, f1, f2, path, path,
3084 GOT_DIFF_ALGORITHM_PATIENCE, diff_context, ignore_whitespace,
3085 force_text_diff, dsa, outfile);
3086 done:
3087 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
3088 err = got_error_from_errno("close");
3089 if (blob1)
3090 got_object_blob_close(blob1);
3091 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
3092 err = got_error_from_errno("close");
3093 if (blob2)
3094 got_object_blob_close(blob2);
3095 if (f1 && fclose(f1) == EOF && err == NULL)
3096 err = got_error_from_errno("fclose");
3097 if (f2 && fclose(f2) == EOF && err == NULL)
3098 err = got_error_from_errno("fclose");
3099 return err;
3102 static const struct got_error *
3103 diff_trees(struct got_object_id *tree_id1, struct got_object_id *tree_id2,
3104 const char *path, int diff_context, int ignore_whitespace,
3105 int force_text_diff, struct got_diffstat_cb_arg *dsa,
3106 struct got_repository *repo, FILE *outfile)
3108 const struct got_error *err = NULL;
3109 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
3110 struct got_diff_blob_output_unidiff_arg arg;
3111 FILE *f1 = NULL, *f2 = NULL;
3112 int fd1 = -1, fd2 = -1;
3114 if (tree_id1) {
3115 err = got_object_open_as_tree(&tree1, repo, tree_id1);
3116 if (err)
3117 goto done;
3118 fd1 = got_opentempfd();
3119 if (fd1 == -1) {
3120 err = got_error_from_errno("got_opentempfd");
3121 goto done;
3125 err = got_object_open_as_tree(&tree2, repo, tree_id2);
3126 if (err)
3127 goto done;
3129 f1 = got_opentemp();
3130 if (f1 == NULL) {
3131 err = got_error_from_errno("got_opentemp");
3132 goto done;
3135 f2 = got_opentemp();
3136 if (f2 == NULL) {
3137 err = got_error_from_errno("got_opentemp");
3138 goto done;
3140 fd2 = got_opentempfd();
3141 if (fd2 == -1) {
3142 err = got_error_from_errno("got_opentempfd");
3143 goto done;
3145 arg.diff_context = diff_context;
3146 arg.ignore_whitespace = ignore_whitespace;
3147 arg.force_text_diff = force_text_diff;
3148 arg.diffstat = dsa;
3149 arg.diff_algo = GOT_DIFF_ALGORITHM_PATIENCE;
3150 arg.outfile = outfile;
3151 arg.lines = NULL;
3152 arg.nlines = 0;
3153 while (path[0] == '/')
3154 path++;
3155 err = got_diff_tree(tree1, tree2, f1, f2, fd1, fd2, path, path, repo,
3156 got_diff_blob_output_unidiff, &arg, 1);
3157 done:
3158 if (tree1)
3159 got_object_tree_close(tree1);
3160 if (tree2)
3161 got_object_tree_close(tree2);
3162 if (f1 && fclose(f1) == EOF && err == NULL)
3163 err = got_error_from_errno("fclose");
3164 if (f2 && fclose(f2) == EOF && err == NULL)
3165 err = got_error_from_errno("fclose");
3166 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
3167 err = got_error_from_errno("close");
3168 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
3169 err = got_error_from_errno("close");
3170 return err;
3173 static const struct got_error *
3174 get_changed_paths(struct got_pathlist_head *paths,
3175 struct got_commit_object *commit, struct got_repository *repo,
3176 struct got_diffstat_cb_arg *dsa)
3178 const struct got_error *err = NULL;
3179 struct got_object_id *tree_id1 = NULL, *tree_id2 = NULL;
3180 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
3181 struct got_object_qid *qid;
3182 got_diff_blob_cb cb = got_diff_tree_collect_changed_paths;
3183 FILE *f1 = NULL, *f2 = NULL;
3184 int fd1 = -1, fd2 = -1;
3186 if (dsa) {
3187 cb = got_diff_tree_compute_diffstat;
3189 f1 = got_opentemp();
3190 if (f1 == NULL) {
3191 err = got_error_from_errno("got_opentemp");
3192 goto done;
3194 f2 = got_opentemp();
3195 if (f2 == NULL) {
3196 err = got_error_from_errno("got_opentemp");
3197 goto done;
3199 fd1 = got_opentempfd();
3200 if (fd1 == -1) {
3201 err = got_error_from_errno("got_opentempfd");
3202 goto done;
3204 fd2 = got_opentempfd();
3205 if (fd2 == -1) {
3206 err = got_error_from_errno("got_opentempfd");
3207 goto done;
3211 qid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
3212 if (qid != NULL) {
3213 struct got_commit_object *pcommit;
3214 err = got_object_open_as_commit(&pcommit, repo,
3215 &qid->id);
3216 if (err)
3217 return err;
3219 tree_id1 = got_object_id_dup(
3220 got_object_commit_get_tree_id(pcommit));
3221 if (tree_id1 == NULL) {
3222 got_object_commit_close(pcommit);
3223 return got_error_from_errno("got_object_id_dup");
3225 got_object_commit_close(pcommit);
3229 if (tree_id1) {
3230 err = got_object_open_as_tree(&tree1, repo, tree_id1);
3231 if (err)
3232 goto done;
3235 tree_id2 = got_object_commit_get_tree_id(commit);
3236 err = got_object_open_as_tree(&tree2, repo, tree_id2);
3237 if (err)
3238 goto done;
3240 err = got_diff_tree(tree1, tree2, f1, f2, fd1, fd2, "", "", repo,
3241 cb, dsa ? (void *)dsa : paths, dsa ? 1 : 0);
3242 done:
3243 if (tree1)
3244 got_object_tree_close(tree1);
3245 if (tree2)
3246 got_object_tree_close(tree2);
3247 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
3248 err = got_error_from_errno("close");
3249 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
3250 err = got_error_from_errno("close");
3251 if (f1 && fclose(f1) == EOF && err == NULL)
3252 err = got_error_from_errno("fclose");
3253 if (f2 && fclose(f2) == EOF && err == NULL)
3254 err = got_error_from_errno("fclose");
3255 free(tree_id1);
3256 return err;
3259 static const struct got_error *
3260 print_patch(struct got_commit_object *commit, struct got_object_id *id,
3261 const char *path, int diff_context, struct got_diffstat_cb_arg *dsa,
3262 struct got_repository *repo, FILE *outfile)
3264 const struct got_error *err = NULL;
3265 struct got_commit_object *pcommit = NULL;
3266 char *id_str1 = NULL, *id_str2 = NULL;
3267 struct got_object_id *obj_id1 = NULL, *obj_id2 = NULL;
3268 struct got_object_qid *qid;
3270 qid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
3271 if (qid != NULL) {
3272 err = got_object_open_as_commit(&pcommit, repo,
3273 &qid->id);
3274 if (err)
3275 return err;
3276 err = got_object_id_str(&id_str1, &qid->id);
3277 if (err)
3278 goto done;
3281 err = got_object_id_str(&id_str2, id);
3282 if (err)
3283 goto done;
3285 if (path && path[0] != '\0') {
3286 int obj_type;
3287 err = got_object_id_by_path(&obj_id2, repo, commit, path);
3288 if (err)
3289 goto done;
3290 if (pcommit) {
3291 err = got_object_id_by_path(&obj_id1, repo,
3292 pcommit, path);
3293 if (err) {
3294 if (err->code != GOT_ERR_NO_TREE_ENTRY) {
3295 free(obj_id2);
3296 goto done;
3300 err = got_object_get_type(&obj_type, repo, obj_id2);
3301 if (err) {
3302 free(obj_id2);
3303 goto done;
3305 fprintf(outfile,
3306 "diff %s %s\n", id_str1 ? id_str1 : "/dev/null", id_str2);
3307 fprintf(outfile, "commit - %s\n",
3308 id_str1 ? id_str1 : "/dev/null");
3309 fprintf(outfile, "commit + %s\n", id_str2);
3310 switch (obj_type) {
3311 case GOT_OBJ_TYPE_BLOB:
3312 err = diff_blobs(obj_id1, obj_id2, path, diff_context,
3313 0, 0, dsa, repo, outfile);
3314 break;
3315 case GOT_OBJ_TYPE_TREE:
3316 err = diff_trees(obj_id1, obj_id2, path, diff_context,
3317 0, 0, dsa, repo, outfile);
3318 break;
3319 default:
3320 err = got_error(GOT_ERR_OBJ_TYPE);
3321 break;
3323 free(obj_id1);
3324 free(obj_id2);
3325 } else {
3326 obj_id2 = got_object_commit_get_tree_id(commit);
3327 if (pcommit)
3328 obj_id1 = got_object_commit_get_tree_id(pcommit);
3329 fprintf(outfile,
3330 "diff %s %s\n", id_str1 ? id_str1 : "/dev/null", id_str2);
3331 fprintf(outfile, "commit - %s\n",
3332 id_str1 ? id_str1 : "/dev/null");
3333 fprintf(outfile, "commit + %s\n", id_str2);
3334 err = diff_trees(obj_id1, obj_id2, "", diff_context, 0, 0,
3335 dsa, repo, outfile);
3337 done:
3338 free(id_str1);
3339 free(id_str2);
3340 if (pcommit)
3341 got_object_commit_close(pcommit);
3342 return err;
3345 static char *
3346 get_datestr(time_t *time, char *datebuf)
3348 struct tm mytm, *tm;
3349 char *p, *s;
3351 tm = gmtime_r(time, &mytm);
3352 if (tm == NULL)
3353 return NULL;
3354 s = asctime_r(tm, datebuf);
3355 if (s == NULL)
3356 return NULL;
3357 p = strchr(s, '\n');
3358 if (p)
3359 *p = '\0';
3360 return s;
3363 static const struct got_error *
3364 match_commit(int *have_match, struct got_object_id *id,
3365 struct got_commit_object *commit, regex_t *regex)
3367 const struct got_error *err = NULL;
3368 regmatch_t regmatch;
3369 char *id_str = NULL, *logmsg = NULL;
3371 *have_match = 0;
3373 err = got_object_id_str(&id_str, id);
3374 if (err)
3375 return err;
3377 err = got_object_commit_get_logmsg(&logmsg, commit);
3378 if (err)
3379 goto done;
3381 if (regexec(regex, got_object_commit_get_author(commit), 1,
3382 &regmatch, 0) == 0 ||
3383 regexec(regex, got_object_commit_get_committer(commit), 1,
3384 &regmatch, 0) == 0 ||
3385 regexec(regex, id_str, 1, &regmatch, 0) == 0 ||
3386 regexec(regex, logmsg, 1, &regmatch, 0) == 0)
3387 *have_match = 1;
3388 done:
3389 free(id_str);
3390 free(logmsg);
3391 return err;
3394 static void
3395 match_changed_paths(int *have_match, struct got_pathlist_head *changed_paths,
3396 regex_t *regex)
3398 regmatch_t regmatch;
3399 struct got_pathlist_entry *pe;
3401 *have_match = 0;
3403 TAILQ_FOREACH(pe, changed_paths, entry) {
3404 if (regexec(regex, pe->path, 1, &regmatch, 0) == 0) {
3405 *have_match = 1;
3406 break;
3411 static const struct got_error *
3412 match_patch(int *have_match, struct got_commit_object *commit,
3413 struct got_object_id *id, const char *path, int diff_context,
3414 struct got_repository *repo, regex_t *regex, FILE *f)
3416 const struct got_error *err = NULL;
3417 char *line = NULL;
3418 size_t linesize = 0;
3419 regmatch_t regmatch;
3421 *have_match = 0;
3423 err = got_opentemp_truncate(f);
3424 if (err)
3425 return err;
3427 err = print_patch(commit, id, path, diff_context, NULL, repo, f);
3428 if (err)
3429 goto done;
3431 if (fseeko(f, 0L, SEEK_SET) == -1) {
3432 err = got_error_from_errno("fseeko");
3433 goto done;
3436 while (getline(&line, &linesize, f) != -1) {
3437 if (regexec(regex, line, 1, &regmatch, 0) == 0) {
3438 *have_match = 1;
3439 break;
3442 done:
3443 free(line);
3444 return err;
3447 #define GOT_COMMIT_SEP_STR "-----------------------------------------------\n"
3449 static const struct got_error*
3450 build_refs_str(char **refs_str, struct got_reflist_head *refs,
3451 struct got_object_id *id, struct got_repository *repo,
3452 int local_only)
3454 static const struct got_error *err = NULL;
3455 struct got_reflist_entry *re;
3456 char *s;
3457 const char *name;
3459 *refs_str = NULL;
3461 TAILQ_FOREACH(re, refs, entry) {
3462 struct got_tag_object *tag = NULL;
3463 struct got_object_id *ref_id;
3464 int cmp;
3466 name = got_ref_get_name(re->ref);
3467 if (strcmp(name, GOT_REF_HEAD) == 0)
3468 continue;
3469 if (strncmp(name, "refs/", 5) == 0)
3470 name += 5;
3471 if (strncmp(name, "got/", 4) == 0)
3472 continue;
3473 if (strncmp(name, "heads/", 6) == 0)
3474 name += 6;
3475 if (strncmp(name, "remotes/", 8) == 0) {
3476 if (local_only)
3477 continue;
3478 name += 8;
3479 s = strstr(name, "/" GOT_REF_HEAD);
3480 if (s != NULL && strcmp(s, "/" GOT_REF_HEAD) == 0)
3481 continue;
3483 err = got_ref_resolve(&ref_id, repo, re->ref);
3484 if (err)
3485 break;
3486 if (strncmp(name, "tags/", 5) == 0) {
3487 err = got_object_open_as_tag(&tag, repo, ref_id);
3488 if (err) {
3489 if (err->code != GOT_ERR_OBJ_TYPE) {
3490 free(ref_id);
3491 break;
3493 /* Ref points at something other than a tag. */
3494 err = NULL;
3495 tag = NULL;
3498 cmp = got_object_id_cmp(tag ?
3499 got_object_tag_get_object_id(tag) : ref_id, id);
3500 free(ref_id);
3501 if (tag)
3502 got_object_tag_close(tag);
3503 if (cmp != 0)
3504 continue;
3505 s = *refs_str;
3506 if (asprintf(refs_str, "%s%s%s", s ? s : "",
3507 s ? ", " : "", name) == -1) {
3508 err = got_error_from_errno("asprintf");
3509 free(s);
3510 *refs_str = NULL;
3511 break;
3513 free(s);
3516 return err;
3519 static const struct got_error *
3520 print_commit_oneline(struct got_commit_object *commit, struct got_object_id *id,
3521 struct got_repository *repo, struct got_reflist_object_id_map *refs_idmap)
3523 const struct got_error *err = NULL;
3524 char *ref_str = NULL, *id_str = NULL, *logmsg0 = NULL;
3525 char *comma, *s, *nl;
3526 struct got_reflist_head *refs;
3527 char datebuf[12]; /* YYYY-MM-DD + SPACE + NUL */
3528 struct tm tm;
3529 time_t committer_time;
3531 refs = got_reflist_object_id_map_lookup(refs_idmap, id);
3532 if (refs) {
3533 err = build_refs_str(&ref_str, refs, id, repo, 1);
3534 if (err)
3535 return err;
3537 /* Display the first matching ref only. */
3538 if (ref_str && (comma = strchr(ref_str, ',')) != NULL)
3539 *comma = '\0';
3542 if (ref_str == NULL) {
3543 err = got_object_id_str(&id_str, id);
3544 if (err)
3545 return err;
3548 committer_time = got_object_commit_get_committer_time(commit);
3549 if (gmtime_r(&committer_time, &tm) == NULL) {
3550 err = got_error_from_errno("gmtime_r");
3551 goto done;
3553 if (strftime(datebuf, sizeof(datebuf), "%G-%m-%d ", &tm) == 0) {
3554 err = got_error(GOT_ERR_NO_SPACE);
3555 goto done;
3558 err = got_object_commit_get_logmsg(&logmsg0, commit);
3559 if (err)
3560 goto done;
3562 s = logmsg0;
3563 while (isspace((unsigned char)s[0]))
3564 s++;
3566 nl = strchr(s, '\n');
3567 if (nl) {
3568 *nl = '\0';
3571 if (ref_str)
3572 printf("%s%-7s %s\n", datebuf, ref_str, s);
3573 else
3574 printf("%s%.7s %s\n", datebuf, id_str, s);
3576 if (fflush(stdout) != 0 && err == NULL)
3577 err = got_error_from_errno("fflush");
3578 done:
3579 free(id_str);
3580 free(ref_str);
3581 free(logmsg0);
3582 return err;
3585 static const struct got_error *
3586 print_diffstat(struct got_diffstat_cb_arg *dsa, const char *header)
3588 struct got_pathlist_entry *pe;
3590 if (header != NULL)
3591 printf("%s\n", header);
3593 TAILQ_FOREACH(pe, dsa->paths, entry) {
3594 struct got_diff_changed_path *cp = pe->data;
3595 int pad = dsa->max_path_len - pe->path_len + 1;
3597 printf(" %c %s%*c | %*d+ %*d-\n", cp->status, pe->path, pad,
3598 ' ', dsa->add_cols + 1, cp->add, dsa->rm_cols + 1, cp->rm);
3600 printf("\n%d file%s changed, %d insertion%s(+), %d deletion%s(-)\n\n",
3601 dsa->nfiles, dsa->nfiles > 1 ? "s" : "", dsa->ins,
3602 dsa->ins != 1 ? "s" : "", dsa->del, dsa->del != 1 ? "s" : "");
3604 if (fflush(stdout) != 0)
3605 return got_error_from_errno("fflush");
3607 return NULL;
3610 static const struct got_error *
3611 printfile(FILE *f)
3613 char buf[8192];
3614 size_t r;
3616 if (fseeko(f, 0L, SEEK_SET) == -1)
3617 return got_error_from_errno("fseek");
3619 for (;;) {
3620 r = fread(buf, 1, sizeof(buf), f);
3621 if (r == 0) {
3622 if (ferror(f))
3623 return got_error_from_errno("fread");
3624 if (feof(f))
3625 break;
3627 if (fwrite(buf, 1, r, stdout) != r)
3628 return got_ferror(stdout, GOT_ERR_IO);
3631 return NULL;
3634 static const struct got_error *
3635 print_commit(struct got_commit_object *commit, struct got_object_id *id,
3636 struct got_repository *repo, const char *path,
3637 struct got_pathlist_head *changed_paths,
3638 struct got_diffstat_cb_arg *diffstat, int show_patch, int diff_context,
3639 struct got_reflist_object_id_map *refs_idmap, const char *custom_refs_str,
3640 const char *prefix)
3642 const struct got_error *err = NULL;
3643 FILE *f = NULL;
3644 char *id_str, *datestr, *logmsg0, *logmsg, *line;
3645 char datebuf[26];
3646 time_t committer_time;
3647 const char *author, *committer;
3648 char *refs_str = NULL;
3650 err = got_object_id_str(&id_str, id);
3651 if (err)
3652 return err;
3654 if (custom_refs_str == NULL) {
3655 struct got_reflist_head *refs;
3656 refs = got_reflist_object_id_map_lookup(refs_idmap, id);
3657 if (refs) {
3658 err = build_refs_str(&refs_str, refs, id, repo, 0);
3659 if (err)
3660 goto done;
3664 printf(GOT_COMMIT_SEP_STR);
3665 if (custom_refs_str)
3666 printf("%s %s (%s)\n", prefix ? prefix : "commit", id_str,
3667 custom_refs_str);
3668 else
3669 printf("%s %s%s%s%s\n", prefix ? prefix : "commit", id_str,
3670 refs_str ? " (" : "", refs_str ? refs_str : "",
3671 refs_str ? ")" : "");
3672 free(id_str);
3673 id_str = NULL;
3674 free(refs_str);
3675 refs_str = NULL;
3676 printf("from: %s\n", got_object_commit_get_author(commit));
3677 author = got_object_commit_get_author(commit);
3678 committer = got_object_commit_get_committer(commit);
3679 if (strcmp(author, committer) != 0)
3680 printf("via: %s\n", committer);
3681 committer_time = got_object_commit_get_committer_time(commit);
3682 datestr = get_datestr(&committer_time, datebuf);
3683 if (datestr)
3684 printf("date: %s UTC\n", datestr);
3685 if (got_object_commit_get_nparents(commit) > 1) {
3686 const struct got_object_id_queue *parent_ids;
3687 struct got_object_qid *qid;
3688 int n = 1;
3689 parent_ids = got_object_commit_get_parent_ids(commit);
3690 STAILQ_FOREACH(qid, parent_ids, entry) {
3691 err = got_object_id_str(&id_str, &qid->id);
3692 if (err)
3693 goto done;
3694 printf("parent %d: %s\n", n++, id_str);
3695 free(id_str);
3696 id_str = NULL;
3700 err = got_object_commit_get_logmsg(&logmsg0, commit);
3701 if (err)
3702 goto done;
3704 logmsg = logmsg0;
3705 do {
3706 line = strsep(&logmsg, "\n");
3707 if (line)
3708 printf(" %s\n", line);
3709 } while (line);
3710 free(logmsg0);
3712 if (changed_paths && diffstat == NULL) {
3713 struct got_pathlist_entry *pe;
3715 TAILQ_FOREACH(pe, changed_paths, entry) {
3716 struct got_diff_changed_path *cp = pe->data;
3718 printf(" %c %s\n", cp->status, pe->path);
3720 printf("\n");
3722 if (show_patch) {
3723 if (diffstat) {
3724 f = got_opentemp();
3725 if (f == NULL) {
3726 err = got_error_from_errno("got_opentemp");
3727 goto done;
3731 err = print_patch(commit, id, path, diff_context, diffstat,
3732 repo, diffstat == NULL ? stdout : f);
3733 if (err)
3734 goto done;
3736 if (diffstat) {
3737 err = print_diffstat(diffstat, NULL);
3738 if (err)
3739 goto done;
3740 if (show_patch) {
3741 err = printfile(f);
3742 if (err)
3743 goto done;
3746 if (show_patch)
3747 printf("\n");
3749 if (fflush(stdout) != 0 && err == NULL)
3750 err = got_error_from_errno("fflush");
3751 done:
3752 if (f && fclose(f) == EOF && err == NULL)
3753 err = got_error_from_errno("fclose");
3754 free(id_str);
3755 free(refs_str);
3756 return err;
3759 static const struct got_error *
3760 print_commits(struct got_object_id *root_id, struct got_object_id *end_id,
3761 struct got_repository *repo, const char *path, int show_changed_paths,
3762 int show_diffstat, int show_patch, const char *search_pattern,
3763 int diff_context, int limit, int log_branches, int reverse_display_order,
3764 struct got_reflist_object_id_map *refs_idmap, int one_line,
3765 FILE *tmpfile)
3767 const struct got_error *err;
3768 struct got_commit_graph *graph;
3769 regex_t regex;
3770 int have_match;
3771 struct got_object_id_queue reversed_commits;
3772 struct got_object_qid *qid;
3773 struct got_commit_object *commit;
3774 struct got_pathlist_head changed_paths;
3776 STAILQ_INIT(&reversed_commits);
3777 TAILQ_INIT(&changed_paths);
3779 if (search_pattern && regcomp(&regex, search_pattern,
3780 REG_EXTENDED | REG_NOSUB | REG_NEWLINE))
3781 return got_error_msg(GOT_ERR_REGEX, search_pattern);
3783 err = got_commit_graph_open(&graph, path, !log_branches);
3784 if (err)
3785 return err;
3786 err = got_commit_graph_bfsort(graph, root_id, repo,
3787 check_cancelled, NULL);
3788 if (err)
3789 goto done;
3790 for (;;) {
3791 struct got_object_id id;
3792 struct got_diffstat_cb_arg dsa = { 0, 0, 0, 0, 0, 0,
3793 &changed_paths, 0, 0, GOT_DIFF_ALGORITHM_PATIENCE };
3795 if (sigint_received || sigpipe_received)
3796 break;
3798 err = got_commit_graph_iter_next(&id, graph, repo,
3799 check_cancelled, NULL);
3800 if (err) {
3801 if (err->code == GOT_ERR_ITER_COMPLETED)
3802 err = NULL;
3803 break;
3806 err = got_object_open_as_commit(&commit, repo, &id);
3807 if (err)
3808 break;
3810 if ((show_changed_paths || (show_diffstat && !show_patch))
3811 && !reverse_display_order) {
3812 err = get_changed_paths(&changed_paths, commit, repo,
3813 show_diffstat ? &dsa : NULL);
3814 if (err)
3815 break;
3818 if (search_pattern) {
3819 err = match_commit(&have_match, &id, commit, &regex);
3820 if (err) {
3821 got_object_commit_close(commit);
3822 break;
3824 if (have_match == 0 && show_changed_paths)
3825 match_changed_paths(&have_match,
3826 &changed_paths, &regex);
3827 if (have_match == 0 && show_patch) {
3828 err = match_patch(&have_match, commit, &id,
3829 path, diff_context, repo, &regex, tmpfile);
3830 if (err)
3831 break;
3833 if (have_match == 0) {
3834 got_object_commit_close(commit);
3835 got_pathlist_free(&changed_paths,
3836 GOT_PATHLIST_FREE_ALL);
3837 continue;
3841 if (reverse_display_order) {
3842 err = got_object_qid_alloc(&qid, &id);
3843 if (err)
3844 break;
3845 STAILQ_INSERT_HEAD(&reversed_commits, qid, entry);
3846 got_object_commit_close(commit);
3847 } else {
3848 if (one_line)
3849 err = print_commit_oneline(commit, &id,
3850 repo, refs_idmap);
3851 else
3852 err = print_commit(commit, &id, repo, path,
3853 (show_changed_paths || show_diffstat) ?
3854 &changed_paths : NULL,
3855 show_diffstat ? &dsa : NULL, show_patch,
3856 diff_context, refs_idmap, NULL, NULL);
3857 got_object_commit_close(commit);
3858 if (err)
3859 break;
3861 if ((limit && --limit == 0) ||
3862 (end_id && got_object_id_cmp(&id, end_id) == 0))
3863 break;
3865 got_pathlist_free(&changed_paths, GOT_PATHLIST_FREE_ALL);
3867 if (reverse_display_order) {
3868 STAILQ_FOREACH(qid, &reversed_commits, entry) {
3869 struct got_diffstat_cb_arg dsa = { 0, 0, 0, 0, 0, 0,
3870 &changed_paths, 0, 0, GOT_DIFF_ALGORITHM_PATIENCE };
3872 err = got_object_open_as_commit(&commit, repo,
3873 &qid->id);
3874 if (err)
3875 break;
3876 if (show_changed_paths ||
3877 (show_diffstat && !show_patch)) {
3878 err = get_changed_paths(&changed_paths, commit,
3879 repo, show_diffstat ? &dsa : NULL);
3880 if (err)
3881 break;
3883 if (one_line)
3884 err = print_commit_oneline(commit, &qid->id,
3885 repo, refs_idmap);
3886 else
3887 err = print_commit(commit, &qid->id, repo, path,
3888 (show_changed_paths || show_diffstat) ?
3889 &changed_paths : NULL,
3890 show_diffstat ? &dsa : NULL, show_patch,
3891 diff_context, refs_idmap, NULL, NULL);
3892 got_object_commit_close(commit);
3893 if (err)
3894 break;
3895 got_pathlist_free(&changed_paths, GOT_PATHLIST_FREE_ALL);
3898 done:
3899 while (!STAILQ_EMPTY(&reversed_commits)) {
3900 qid = STAILQ_FIRST(&reversed_commits);
3901 STAILQ_REMOVE_HEAD(&reversed_commits, entry);
3902 got_object_qid_free(qid);
3904 got_pathlist_free(&changed_paths, GOT_PATHLIST_FREE_ALL);
3905 if (search_pattern)
3906 regfree(&regex);
3907 got_commit_graph_close(graph);
3908 return err;
3911 __dead static void
3912 usage_log(void)
3914 fprintf(stderr, "usage: %s log [-bdPpRs] [-C number] [-c commit] "
3915 "[-l N] [-r repository-path] [-S search-pattern] [-x commit] "
3916 "[path]\n", getprogname());
3917 exit(1);
3920 static int
3921 get_default_log_limit(void)
3923 const char *got_default_log_limit;
3924 long long n;
3925 const char *errstr;
3927 got_default_log_limit = getenv("GOT_LOG_DEFAULT_LIMIT");
3928 if (got_default_log_limit == NULL)
3929 return 0;
3930 n = strtonum(got_default_log_limit, 0, INT_MAX, &errstr);
3931 if (errstr != NULL)
3932 return 0;
3933 return n;
3936 static const struct got_error *
3937 cmd_log(int argc, char *argv[])
3939 const struct got_error *error;
3940 struct got_repository *repo = NULL;
3941 struct got_worktree *worktree = NULL;
3942 struct got_object_id *start_id = NULL, *end_id = NULL;
3943 char *repo_path = NULL, *path = NULL, *cwd = NULL, *in_repo_path = NULL;
3944 const char *start_commit = NULL, *end_commit = NULL;
3945 const char *search_pattern = NULL;
3946 int diff_context = -1, ch;
3947 int show_changed_paths = 0, show_patch = 0, limit = 0, log_branches = 0;
3948 int show_diffstat = 0, reverse_display_order = 0, one_line = 0;
3949 const char *errstr;
3950 struct got_reflist_head refs;
3951 struct got_reflist_object_id_map *refs_idmap = NULL;
3952 FILE *tmpfile = NULL;
3953 int *pack_fds = NULL;
3955 TAILQ_INIT(&refs);
3957 #ifndef PROFILE
3958 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
3959 NULL)
3960 == -1)
3961 err(1, "pledge");
3962 #endif
3964 limit = get_default_log_limit();
3966 while ((ch = getopt(argc, argv, "bC:c:dl:PpRr:S:sx:")) != -1) {
3967 switch (ch) {
3968 case 'b':
3969 log_branches = 1;
3970 break;
3971 case 'C':
3972 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
3973 &errstr);
3974 if (errstr != NULL)
3975 errx(1, "number of context lines is %s: %s",
3976 errstr, optarg);
3977 break;
3978 case 'c':
3979 start_commit = optarg;
3980 break;
3981 case 'd':
3982 show_diffstat = 1;
3983 break;
3984 case 'l':
3985 limit = strtonum(optarg, 0, INT_MAX, &errstr);
3986 if (errstr != NULL)
3987 errx(1, "number of commits is %s: %s",
3988 errstr, optarg);
3989 break;
3990 case 'P':
3991 show_changed_paths = 1;
3992 break;
3993 case 'p':
3994 show_patch = 1;
3995 break;
3996 case 'R':
3997 reverse_display_order = 1;
3998 break;
3999 case 'r':
4000 repo_path = realpath(optarg, NULL);
4001 if (repo_path == NULL)
4002 return got_error_from_errno2("realpath",
4003 optarg);
4004 got_path_strip_trailing_slashes(repo_path);
4005 break;
4006 case 'S':
4007 search_pattern = optarg;
4008 break;
4009 case 's':
4010 one_line = 1;
4011 break;
4012 case 'x':
4013 end_commit = optarg;
4014 break;
4015 default:
4016 usage_log();
4017 /* NOTREACHED */
4021 argc -= optind;
4022 argv += optind;
4024 if (diff_context == -1)
4025 diff_context = 3;
4026 else if (!show_patch)
4027 errx(1, "-C requires -p");
4029 if (one_line && (show_patch || show_changed_paths || show_diffstat))
4030 errx(1, "cannot use -s with -d, -p or -P");
4032 cwd = getcwd(NULL, 0);
4033 if (cwd == NULL) {
4034 error = got_error_from_errno("getcwd");
4035 goto done;
4038 error = got_repo_pack_fds_open(&pack_fds);
4039 if (error != NULL)
4040 goto done;
4042 if (repo_path == NULL) {
4043 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_CVG_DIR);
4044 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4045 goto done;
4046 error = NULL;
4049 if (argc == 1) {
4050 if (worktree) {
4051 error = got_worktree_resolve_path(&path, worktree,
4052 argv[0]);
4053 if (error)
4054 goto done;
4055 } else {
4056 path = strdup(argv[0]);
4057 if (path == NULL) {
4058 error = got_error_from_errno("strdup");
4059 goto done;
4062 } else if (argc != 0)
4063 usage_log();
4065 if (repo_path == NULL) {
4066 repo_path = worktree ?
4067 strdup(got_worktree_get_repo_path(worktree)) : strdup(cwd);
4069 if (repo_path == NULL) {
4070 error = got_error_from_errno("strdup");
4071 goto done;
4074 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
4075 if (error != NULL)
4076 goto done;
4078 error = apply_unveil(got_repo_get_path(repo), 1,
4079 worktree ? got_worktree_get_root_path(worktree) : NULL);
4080 if (error)
4081 goto done;
4083 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
4084 if (error)
4085 goto done;
4087 error = got_reflist_object_id_map_create(&refs_idmap, &refs, repo);
4088 if (error)
4089 goto done;
4091 if (start_commit == NULL) {
4092 struct got_reference *head_ref;
4093 struct got_commit_object *commit = NULL;
4094 error = got_ref_open(&head_ref, repo,
4095 worktree ? got_worktree_get_head_ref_name(worktree)
4096 : GOT_REF_HEAD, 0);
4097 if (error != NULL)
4098 goto done;
4099 error = got_ref_resolve(&start_id, repo, head_ref);
4100 got_ref_close(head_ref);
4101 if (error != NULL)
4102 goto done;
4103 error = got_object_open_as_commit(&commit, repo,
4104 start_id);
4105 if (error != NULL)
4106 goto done;
4107 got_object_commit_close(commit);
4108 } else {
4109 error = got_repo_match_object_id(&start_id, NULL,
4110 start_commit, GOT_OBJ_TYPE_COMMIT, &refs, repo);
4111 if (error != NULL)
4112 goto done;
4114 if (end_commit != NULL) {
4115 error = got_repo_match_object_id(&end_id, NULL,
4116 end_commit, GOT_OBJ_TYPE_COMMIT, &refs, repo);
4117 if (error != NULL)
4118 goto done;
4121 if (worktree) {
4123 * If a path was specified on the command line it was resolved
4124 * to a path in the work tree above. Prepend the work tree's
4125 * path prefix to obtain the corresponding in-repository path.
4127 if (path) {
4128 const char *prefix;
4129 prefix = got_worktree_get_path_prefix(worktree);
4130 if (asprintf(&in_repo_path, "%s%s%s", prefix,
4131 (path[0] != '\0') ? "/" : "", path) == -1) {
4132 error = got_error_from_errno("asprintf");
4133 goto done;
4136 } else
4137 error = got_repo_map_path(&in_repo_path, repo,
4138 path ? path : "");
4139 if (error != NULL)
4140 goto done;
4141 if (in_repo_path) {
4142 free(path);
4143 path = in_repo_path;
4146 if (worktree) {
4147 /* Release work tree lock. */
4148 got_worktree_close(worktree);
4149 worktree = NULL;
4152 if (search_pattern && show_patch) {
4153 tmpfile = got_opentemp();
4154 if (tmpfile == NULL) {
4155 error = got_error_from_errno("got_opentemp");
4156 goto done;
4160 error = print_commits(start_id, end_id, repo, path ? path : "",
4161 show_changed_paths, show_diffstat, show_patch, search_pattern,
4162 diff_context, limit, log_branches, reverse_display_order,
4163 refs_idmap, one_line, tmpfile);
4164 done:
4165 free(path);
4166 free(repo_path);
4167 free(cwd);
4168 free(start_id);
4169 free(end_id);
4170 if (worktree)
4171 got_worktree_close(worktree);
4172 if (repo) {
4173 const struct got_error *close_err = got_repo_close(repo);
4174 if (error == NULL)
4175 error = close_err;
4177 if (pack_fds) {
4178 const struct got_error *pack_err =
4179 got_repo_pack_fds_close(pack_fds);
4180 if (error == NULL)
4181 error = pack_err;
4183 if (refs_idmap)
4184 got_reflist_object_id_map_free(refs_idmap);
4185 if (tmpfile && fclose(tmpfile) == EOF && error == NULL)
4186 error = got_error_from_errno("fclose");
4187 got_ref_list_free(&refs);
4188 return error;
4191 __dead static void
4192 usage_diff(void)
4194 fprintf(stderr, "usage: %s diff [-adPsw] [-C number] [-c commit] "
4195 "[-r repository-path] [object1 object2 | path ...]\n",
4196 getprogname());
4197 exit(1);
4200 struct print_diff_arg {
4201 struct got_repository *repo;
4202 struct got_worktree *worktree;
4203 struct got_diffstat_cb_arg *diffstat;
4204 int diff_context;
4205 const char *id_str;
4206 int header_shown;
4207 int diff_staged;
4208 enum got_diff_algorithm diff_algo;
4209 int ignore_whitespace;
4210 int force_text_diff;
4211 FILE *f1;
4212 FILE *f2;
4213 FILE *outfile;
4217 * Create a file which contains the target path of a symlink so we can feed
4218 * it as content to the diff engine.
4220 static const struct got_error *
4221 get_symlink_target_file(int *fd, int dirfd, const char *de_name,
4222 const char *abspath)
4224 const struct got_error *err = NULL;
4225 char target_path[PATH_MAX];
4226 ssize_t target_len, outlen;
4228 *fd = -1;
4230 if (dirfd != -1) {
4231 target_len = readlinkat(dirfd, de_name, target_path, PATH_MAX);
4232 if (target_len == -1)
4233 return got_error_from_errno2("readlinkat", abspath);
4234 } else {
4235 target_len = readlink(abspath, target_path, PATH_MAX);
4236 if (target_len == -1)
4237 return got_error_from_errno2("readlink", abspath);
4240 *fd = got_opentempfd();
4241 if (*fd == -1)
4242 return got_error_from_errno("got_opentempfd");
4244 outlen = write(*fd, target_path, target_len);
4245 if (outlen == -1) {
4246 err = got_error_from_errno("got_opentempfd");
4247 goto done;
4250 if (lseek(*fd, 0, SEEK_SET) == -1) {
4251 err = got_error_from_errno2("lseek", abspath);
4252 goto done;
4254 done:
4255 if (err) {
4256 close(*fd);
4257 *fd = -1;
4259 return err;
4262 static const struct got_error *
4263 print_diff(void *arg, unsigned char status, unsigned char staged_status,
4264 const char *path, struct got_object_id *blob_id,
4265 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
4266 int dirfd, const char *de_name)
4268 struct print_diff_arg *a = arg;
4269 const struct got_error *err = NULL;
4270 struct got_blob_object *blob1 = NULL;
4271 int fd = -1, fd1 = -1, fd2 = -1;
4272 FILE *f2 = NULL;
4273 char *abspath = NULL, *label1 = NULL;
4274 struct stat sb;
4275 off_t size1 = 0;
4276 int f2_exists = 0;
4278 memset(&sb, 0, sizeof(sb));
4280 if (a->diff_staged) {
4281 if (staged_status != GOT_STATUS_MODIFY &&
4282 staged_status != GOT_STATUS_ADD &&
4283 staged_status != GOT_STATUS_DELETE)
4284 return NULL;
4285 } else {
4286 if (staged_status == GOT_STATUS_DELETE)
4287 return NULL;
4288 if (status == GOT_STATUS_NONEXISTENT)
4289 return got_error_set_errno(ENOENT, path);
4290 if (status != GOT_STATUS_MODIFY &&
4291 status != GOT_STATUS_ADD &&
4292 status != GOT_STATUS_DELETE &&
4293 status != GOT_STATUS_CONFLICT)
4294 return NULL;
4297 err = got_opentemp_truncate(a->f1);
4298 if (err)
4299 return got_error_from_errno("got_opentemp_truncate");
4300 err = got_opentemp_truncate(a->f2);
4301 if (err)
4302 return got_error_from_errno("got_opentemp_truncate");
4304 if (!a->header_shown) {
4305 if (fprintf(a->outfile, "diff %s%s\n",
4306 a->diff_staged ? "-s " : "",
4307 got_worktree_get_root_path(a->worktree)) < 0) {
4308 err = got_error_from_errno("fprintf");
4309 goto done;
4311 if (fprintf(a->outfile, "commit - %s\n", a->id_str) < 0) {
4312 err = got_error_from_errno("fprintf");
4313 goto done;
4315 if (fprintf(a->outfile, "path + %s%s\n",
4316 got_worktree_get_root_path(a->worktree),
4317 a->diff_staged ? " (staged changes)" : "") < 0) {
4318 err = got_error_from_errno("fprintf");
4319 goto done;
4321 a->header_shown = 1;
4324 if (a->diff_staged) {
4325 const char *label1 = NULL, *label2 = NULL;
4326 switch (staged_status) {
4327 case GOT_STATUS_MODIFY:
4328 label1 = path;
4329 label2 = path;
4330 break;
4331 case GOT_STATUS_ADD:
4332 label2 = path;
4333 break;
4334 case GOT_STATUS_DELETE:
4335 label1 = path;
4336 break;
4337 default:
4338 return got_error(GOT_ERR_FILE_STATUS);
4340 fd1 = got_opentempfd();
4341 if (fd1 == -1) {
4342 err = got_error_from_errno("got_opentempfd");
4343 goto done;
4345 fd2 = got_opentempfd();
4346 if (fd2 == -1) {
4347 err = got_error_from_errno("got_opentempfd");
4348 goto done;
4350 err = got_diff_objects_as_blobs(NULL, NULL, a->f1, a->f2,
4351 fd1, fd2, blob_id, staged_blob_id, label1, label2,
4352 a->diff_algo, a->diff_context, a->ignore_whitespace,
4353 a->force_text_diff, a->diffstat, a->repo, a->outfile);
4354 goto done;
4357 fd1 = got_opentempfd();
4358 if (fd1 == -1) {
4359 err = got_error_from_errno("got_opentempfd");
4360 goto done;
4363 if (staged_status == GOT_STATUS_ADD ||
4364 staged_status == GOT_STATUS_MODIFY) {
4365 char *id_str;
4366 err = got_object_open_as_blob(&blob1, a->repo, staged_blob_id,
4367 8192, fd1);
4368 if (err)
4369 goto done;
4370 err = got_object_id_str(&id_str, staged_blob_id);
4371 if (err)
4372 goto done;
4373 if (asprintf(&label1, "%s (staged)", id_str) == -1) {
4374 err = got_error_from_errno("asprintf");
4375 free(id_str);
4376 goto done;
4378 free(id_str);
4379 } else if (status != GOT_STATUS_ADD) {
4380 err = got_object_open_as_blob(&blob1, a->repo, blob_id, 8192,
4381 fd1);
4382 if (err)
4383 goto done;
4386 if (status != GOT_STATUS_DELETE) {
4387 if (asprintf(&abspath, "%s/%s",
4388 got_worktree_get_root_path(a->worktree), path) == -1) {
4389 err = got_error_from_errno("asprintf");
4390 goto done;
4393 if (dirfd != -1) {
4394 fd = openat(dirfd, de_name,
4395 O_RDONLY | O_NOFOLLOW | O_CLOEXEC);
4396 if (fd == -1) {
4397 if (!got_err_open_nofollow_on_symlink()) {
4398 err = got_error_from_errno2("openat",
4399 abspath);
4400 goto done;
4402 err = get_symlink_target_file(&fd, dirfd,
4403 de_name, abspath);
4404 if (err)
4405 goto done;
4407 } else {
4408 fd = open(abspath, O_RDONLY | O_NOFOLLOW | O_CLOEXEC);
4409 if (fd == -1) {
4410 if (!got_err_open_nofollow_on_symlink()) {
4411 err = got_error_from_errno2("open",
4412 abspath);
4413 goto done;
4415 err = get_symlink_target_file(&fd, dirfd,
4416 de_name, abspath);
4417 if (err)
4418 goto done;
4421 if (fstatat(fd, abspath, &sb, AT_SYMLINK_NOFOLLOW) == -1) {
4422 err = got_error_from_errno2("fstatat", abspath);
4423 goto done;
4425 f2 = fdopen(fd, "r");
4426 if (f2 == NULL) {
4427 err = got_error_from_errno2("fdopen", abspath);
4428 goto done;
4430 fd = -1;
4431 f2_exists = 1;
4434 if (blob1) {
4435 err = got_object_blob_dump_to_file(&size1, NULL, NULL,
4436 a->f1, blob1);
4437 if (err)
4438 goto done;
4441 err = got_diff_blob_file(blob1, a->f1, size1, label1, f2 ? f2 : a->f2,
4442 f2_exists, &sb, path, GOT_DIFF_ALGORITHM_PATIENCE, a->diff_context,
4443 a->ignore_whitespace, a->force_text_diff, a->diffstat, a->outfile);
4444 done:
4445 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
4446 err = got_error_from_errno("close");
4447 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
4448 err = got_error_from_errno("close");
4449 if (blob1)
4450 got_object_blob_close(blob1);
4451 if (fd != -1 && close(fd) == -1 && err == NULL)
4452 err = got_error_from_errno("close");
4453 if (f2 && fclose(f2) == EOF && err == NULL)
4454 err = got_error_from_errno("fclose");
4455 free(abspath);
4456 return err;
4459 static const struct got_error *
4460 cmd_diff(int argc, char *argv[])
4462 const struct got_error *error;
4463 struct got_repository *repo = NULL;
4464 struct got_worktree *worktree = NULL;
4465 char *cwd = NULL, *repo_path = NULL;
4466 const char *commit_args[2] = { NULL, NULL };
4467 int ncommit_args = 0;
4468 struct got_object_id *ids[2] = { NULL, NULL };
4469 char *labels[2] = { NULL, NULL };
4470 int type1 = GOT_OBJ_TYPE_ANY, type2 = GOT_OBJ_TYPE_ANY;
4471 int diff_context = 3, diff_staged = 0, ignore_whitespace = 0, ch, i;
4472 int force_text_diff = 0, force_path = 0, rflag = 0, show_diffstat = 0;
4473 const char *errstr;
4474 struct got_reflist_head refs;
4475 struct got_pathlist_head diffstat_paths, paths;
4476 FILE *f1 = NULL, *f2 = NULL, *outfile = NULL;
4477 int fd1 = -1, fd2 = -1;
4478 int *pack_fds = NULL;
4479 struct got_diffstat_cb_arg dsa;
4481 memset(&dsa, 0, sizeof(dsa));
4483 TAILQ_INIT(&refs);
4484 TAILQ_INIT(&paths);
4485 TAILQ_INIT(&diffstat_paths);
4487 #ifndef PROFILE
4488 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
4489 NULL) == -1)
4490 err(1, "pledge");
4491 #endif
4493 while ((ch = getopt(argc, argv, "aC:c:dPr:sw")) != -1) {
4494 switch (ch) {
4495 case 'a':
4496 force_text_diff = 1;
4497 break;
4498 case 'C':
4499 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
4500 &errstr);
4501 if (errstr != NULL)
4502 errx(1, "number of context lines is %s: %s",
4503 errstr, optarg);
4504 break;
4505 case 'c':
4506 if (ncommit_args >= 2)
4507 errx(1, "too many -c options used");
4508 commit_args[ncommit_args++] = optarg;
4509 break;
4510 case 'd':
4511 show_diffstat = 1;
4512 break;
4513 case 'P':
4514 force_path = 1;
4515 break;
4516 case 'r':
4517 repo_path = realpath(optarg, NULL);
4518 if (repo_path == NULL)
4519 return got_error_from_errno2("realpath",
4520 optarg);
4521 got_path_strip_trailing_slashes(repo_path);
4522 rflag = 1;
4523 break;
4524 case 's':
4525 diff_staged = 1;
4526 break;
4527 case 'w':
4528 ignore_whitespace = 1;
4529 break;
4530 default:
4531 usage_diff();
4532 /* NOTREACHED */
4536 argc -= optind;
4537 argv += optind;
4539 cwd = getcwd(NULL, 0);
4540 if (cwd == NULL) {
4541 error = got_error_from_errno("getcwd");
4542 goto done;
4545 error = got_repo_pack_fds_open(&pack_fds);
4546 if (error != NULL)
4547 goto done;
4549 if (repo_path == NULL) {
4550 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_CVG_DIR);
4551 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4552 goto done;
4553 else
4554 error = NULL;
4555 if (worktree) {
4556 repo_path =
4557 strdup(got_worktree_get_repo_path(worktree));
4558 if (repo_path == NULL) {
4559 error = got_error_from_errno("strdup");
4560 goto done;
4562 } else {
4563 repo_path = strdup(cwd);
4564 if (repo_path == NULL) {
4565 error = got_error_from_errno("strdup");
4566 goto done;
4571 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
4572 free(repo_path);
4573 if (error != NULL)
4574 goto done;
4576 if (show_diffstat) {
4577 dsa.paths = &diffstat_paths;
4578 dsa.force_text = force_text_diff;
4579 dsa.ignore_ws = ignore_whitespace;
4580 dsa.diff_algo = GOT_DIFF_ALGORITHM_PATIENCE;
4583 if (rflag || worktree == NULL || ncommit_args > 0) {
4584 if (force_path) {
4585 error = got_error_msg(GOT_ERR_NOT_IMPL,
4586 "-P option can only be used when diffing "
4587 "a work tree");
4588 goto done;
4590 if (diff_staged) {
4591 error = got_error_msg(GOT_ERR_NOT_IMPL,
4592 "-s option can only be used when diffing "
4593 "a work tree");
4594 goto done;
4598 error = apply_unveil(got_repo_get_path(repo), 1,
4599 worktree ? got_worktree_get_root_path(worktree) : NULL);
4600 if (error)
4601 goto done;
4603 if ((!force_path && argc == 2) || ncommit_args > 0) {
4604 int obj_type = (ncommit_args > 0 ?
4605 GOT_OBJ_TYPE_COMMIT : GOT_OBJ_TYPE_ANY);
4606 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
4607 NULL);
4608 if (error)
4609 goto done;
4610 for (i = 0; i < (ncommit_args > 0 ? ncommit_args : argc); i++) {
4611 const char *arg;
4612 if (ncommit_args > 0)
4613 arg = commit_args[i];
4614 else
4615 arg = argv[i];
4616 error = got_repo_match_object_id(&ids[i], &labels[i],
4617 arg, obj_type, &refs, repo);
4618 if (error) {
4619 if (error->code != GOT_ERR_NOT_REF &&
4620 error->code != GOT_ERR_NO_OBJ)
4621 goto done;
4622 if (ncommit_args > 0)
4623 goto done;
4624 error = NULL;
4625 break;
4630 f1 = got_opentemp();
4631 if (f1 == NULL) {
4632 error = got_error_from_errno("got_opentemp");
4633 goto done;
4636 f2 = got_opentemp();
4637 if (f2 == NULL) {
4638 error = got_error_from_errno("got_opentemp");
4639 goto done;
4642 outfile = got_opentemp();
4643 if (outfile == NULL) {
4644 error = got_error_from_errno("got_opentemp");
4645 goto done;
4648 if (ncommit_args == 0 && (ids[0] == NULL || ids[1] == NULL)) {
4649 struct print_diff_arg arg;
4650 char *id_str;
4652 if (worktree == NULL) {
4653 if (argc == 2 && ids[0] == NULL) {
4654 error = got_error_path(argv[0], GOT_ERR_NO_OBJ);
4655 goto done;
4656 } else if (argc == 2 && ids[1] == NULL) {
4657 error = got_error_path(argv[1], GOT_ERR_NO_OBJ);
4658 goto done;
4659 } else if (argc > 0) {
4660 error = got_error_fmt(GOT_ERR_NOT_WORKTREE,
4661 "%s", "specified paths cannot be resolved");
4662 goto done;
4663 } else {
4664 error = got_error(GOT_ERR_NOT_WORKTREE);
4665 goto done;
4669 error = get_worktree_paths_from_argv(&paths, argc, argv,
4670 worktree);
4671 if (error)
4672 goto done;
4674 error = got_object_id_str(&id_str,
4675 got_worktree_get_base_commit_id(worktree));
4676 if (error)
4677 goto done;
4678 arg.repo = repo;
4679 arg.worktree = worktree;
4680 arg.diff_algo = GOT_DIFF_ALGORITHM_PATIENCE;
4681 arg.diff_context = diff_context;
4682 arg.id_str = id_str;
4683 arg.header_shown = 0;
4684 arg.diff_staged = diff_staged;
4685 arg.ignore_whitespace = ignore_whitespace;
4686 arg.force_text_diff = force_text_diff;
4687 arg.diffstat = show_diffstat ? &dsa : NULL;
4688 arg.f1 = f1;
4689 arg.f2 = f2;
4690 arg.outfile = outfile;
4692 error = got_worktree_status(worktree, &paths, repo, 0,
4693 print_diff, &arg, check_cancelled, NULL);
4694 free(id_str);
4695 if (error)
4696 goto done;
4698 if (show_diffstat && dsa.nfiles > 0) {
4699 char *header;
4701 if (asprintf(&header, "diffstat %s%s",
4702 diff_staged ? "-s " : "",
4703 got_worktree_get_root_path(worktree)) == -1) {
4704 error = got_error_from_errno("asprintf");
4705 goto done;
4708 error = print_diffstat(&dsa, header);
4709 free(header);
4710 if (error)
4711 goto done;
4714 error = printfile(outfile);
4715 goto done;
4718 if (ncommit_args == 1) {
4719 struct got_commit_object *commit;
4720 error = got_object_open_as_commit(&commit, repo, ids[0]);
4721 if (error)
4722 goto done;
4724 labels[1] = labels[0];
4725 ids[1] = ids[0];
4726 if (got_object_commit_get_nparents(commit) > 0) {
4727 const struct got_object_id_queue *pids;
4728 struct got_object_qid *pid;
4729 pids = got_object_commit_get_parent_ids(commit);
4730 pid = STAILQ_FIRST(pids);
4731 ids[0] = got_object_id_dup(&pid->id);
4732 if (ids[0] == NULL) {
4733 error = got_error_from_errno(
4734 "got_object_id_dup");
4735 got_object_commit_close(commit);
4736 goto done;
4738 error = got_object_id_str(&labels[0], ids[0]);
4739 if (error) {
4740 got_object_commit_close(commit);
4741 goto done;
4743 } else {
4744 ids[0] = NULL;
4745 labels[0] = strdup("/dev/null");
4746 if (labels[0] == NULL) {
4747 error = got_error_from_errno("strdup");
4748 got_object_commit_close(commit);
4749 goto done;
4753 got_object_commit_close(commit);
4756 if (ncommit_args == 0 && argc > 2) {
4757 error = got_error_msg(GOT_ERR_BAD_PATH,
4758 "path arguments cannot be used when diffing two objects");
4759 goto done;
4762 if (ids[0]) {
4763 error = got_object_get_type(&type1, repo, ids[0]);
4764 if (error)
4765 goto done;
4768 error = got_object_get_type(&type2, repo, ids[1]);
4769 if (error)
4770 goto done;
4771 if (type1 != GOT_OBJ_TYPE_ANY && type1 != type2) {
4772 error = got_error(GOT_ERR_OBJ_TYPE);
4773 goto done;
4775 if (type1 == GOT_OBJ_TYPE_BLOB && argc > 2) {
4776 error = got_error_msg(GOT_ERR_OBJ_TYPE,
4777 "path arguments cannot be used when diffing blobs");
4778 goto done;
4781 for (i = 0; ncommit_args > 0 && i < argc; i++) {
4782 char *in_repo_path;
4783 struct got_pathlist_entry *new;
4784 if (worktree) {
4785 const char *prefix;
4786 char *p;
4787 error = got_worktree_resolve_path(&p, worktree,
4788 argv[i]);
4789 if (error)
4790 goto done;
4791 prefix = got_worktree_get_path_prefix(worktree);
4792 while (prefix[0] == '/')
4793 prefix++;
4794 if (asprintf(&in_repo_path, "%s%s%s", prefix,
4795 (p[0] != '\0' && prefix[0] != '\0') ? "/" : "",
4796 p) == -1) {
4797 error = got_error_from_errno("asprintf");
4798 free(p);
4799 goto done;
4801 free(p);
4802 } else {
4803 char *mapped_path, *s;
4804 error = got_repo_map_path(&mapped_path, repo, argv[i]);
4805 if (error)
4806 goto done;
4807 s = mapped_path;
4808 while (s[0] == '/')
4809 s++;
4810 in_repo_path = strdup(s);
4811 if (in_repo_path == NULL) {
4812 error = got_error_from_errno("asprintf");
4813 free(mapped_path);
4814 goto done;
4816 free(mapped_path);
4819 error = got_pathlist_insert(&new, &paths, in_repo_path, NULL);
4820 if (error || new == NULL /* duplicate */)
4821 free(in_repo_path);
4822 if (error)
4823 goto done;
4826 if (worktree) {
4827 /* Release work tree lock. */
4828 got_worktree_close(worktree);
4829 worktree = NULL;
4832 fd1 = got_opentempfd();
4833 if (fd1 == -1) {
4834 error = got_error_from_errno("got_opentempfd");
4835 goto done;
4838 fd2 = got_opentempfd();
4839 if (fd2 == -1) {
4840 error = got_error_from_errno("got_opentempfd");
4841 goto done;
4844 switch (type1 == GOT_OBJ_TYPE_ANY ? type2 : type1) {
4845 case GOT_OBJ_TYPE_BLOB:
4846 error = got_diff_objects_as_blobs(NULL, NULL, f1, f2,
4847 fd1, fd2, ids[0], ids[1], NULL, NULL,
4848 GOT_DIFF_ALGORITHM_PATIENCE, diff_context,
4849 ignore_whitespace, force_text_diff,
4850 show_diffstat ? &dsa : NULL, repo, outfile);
4851 break;
4852 case GOT_OBJ_TYPE_TREE:
4853 error = got_diff_objects_as_trees(NULL, NULL, f1, f2, fd1, fd2,
4854 ids[0], ids[1], &paths, "", "",
4855 GOT_DIFF_ALGORITHM_PATIENCE, diff_context,
4856 ignore_whitespace, force_text_diff,
4857 show_diffstat ? &dsa : NULL, repo, outfile);
4858 break;
4859 case GOT_OBJ_TYPE_COMMIT:
4860 fprintf(outfile, "diff %s %s\n", labels[0], labels[1]);
4861 error = got_diff_objects_as_commits(NULL, NULL, f1, f2,
4862 fd1, fd2, ids[0], ids[1], &paths,
4863 GOT_DIFF_ALGORITHM_PATIENCE, diff_context,
4864 ignore_whitespace, force_text_diff,
4865 show_diffstat ? &dsa : NULL, repo, outfile);
4866 break;
4867 default:
4868 error = got_error(GOT_ERR_OBJ_TYPE);
4870 if (error)
4871 goto done;
4873 if (show_diffstat && dsa.nfiles > 0) {
4874 char *header = NULL;
4876 if (asprintf(&header, "diffstat %s %s",
4877 labels[0], labels[1]) == -1) {
4878 error = got_error_from_errno("asprintf");
4879 goto done;
4882 error = print_diffstat(&dsa, header);
4883 free(header);
4884 if (error)
4885 goto done;
4888 error = printfile(outfile);
4890 done:
4891 free(labels[0]);
4892 free(labels[1]);
4893 free(ids[0]);
4894 free(ids[1]);
4895 if (worktree)
4896 got_worktree_close(worktree);
4897 if (repo) {
4898 const struct got_error *close_err = got_repo_close(repo);
4899 if (error == NULL)
4900 error = close_err;
4902 if (pack_fds) {
4903 const struct got_error *pack_err =
4904 got_repo_pack_fds_close(pack_fds);
4905 if (error == NULL)
4906 error = pack_err;
4908 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
4909 got_pathlist_free(&diffstat_paths, GOT_PATHLIST_FREE_ALL);
4910 got_ref_list_free(&refs);
4911 if (outfile && fclose(outfile) == EOF && error == NULL)
4912 error = got_error_from_errno("fclose");
4913 if (f1 && fclose(f1) == EOF && error == NULL)
4914 error = got_error_from_errno("fclose");
4915 if (f2 && fclose(f2) == EOF && error == NULL)
4916 error = got_error_from_errno("fclose");
4917 if (fd1 != -1 && close(fd1) == -1 && error == NULL)
4918 error = got_error_from_errno("close");
4919 if (fd2 != -1 && close(fd2) == -1 && error == NULL)
4920 error = got_error_from_errno("close");
4921 return error;
4924 __dead static void
4925 usage_blame(void)
4927 fprintf(stderr,
4928 "usage: %s blame [-c commit] [-r repository-path] path\n",
4929 getprogname());
4930 exit(1);
4933 struct blame_line {
4934 int annotated;
4935 char *id_str;
4936 char *committer;
4937 char datebuf[11]; /* YYYY-MM-DD + NUL */
4940 struct blame_cb_args {
4941 struct blame_line *lines;
4942 int nlines;
4943 int nlines_prec;
4944 int lineno_cur;
4945 off_t *line_offsets;
4946 FILE *f;
4947 struct got_repository *repo;
4950 static const struct got_error *
4951 blame_cb(void *arg, int nlines, int lineno,
4952 struct got_commit_object *commit, struct got_object_id *id)
4954 const struct got_error *err = NULL;
4955 struct blame_cb_args *a = arg;
4956 struct blame_line *bline;
4957 char *line = NULL;
4958 size_t linesize = 0;
4959 off_t offset;
4960 struct tm tm;
4961 time_t committer_time;
4963 if (nlines != a->nlines ||
4964 (lineno != -1 && lineno < 1) || lineno > a->nlines)
4965 return got_error(GOT_ERR_RANGE);
4967 if (sigint_received)
4968 return got_error(GOT_ERR_ITER_COMPLETED);
4970 if (lineno == -1)
4971 return NULL; /* no change in this commit */
4973 /* Annotate this line. */
4974 bline = &a->lines[lineno - 1];
4975 if (bline->annotated)
4976 return NULL;
4977 err = got_object_id_str(&bline->id_str, id);
4978 if (err)
4979 return err;
4981 bline->committer = strdup(got_object_commit_get_committer(commit));
4982 if (bline->committer == NULL) {
4983 err = got_error_from_errno("strdup");
4984 goto done;
4987 committer_time = got_object_commit_get_committer_time(commit);
4988 if (gmtime_r(&committer_time, &tm) == NULL)
4989 return got_error_from_errno("gmtime_r");
4990 if (strftime(bline->datebuf, sizeof(bline->datebuf), "%G-%m-%d",
4991 &tm) == 0) {
4992 err = got_error(GOT_ERR_NO_SPACE);
4993 goto done;
4995 bline->annotated = 1;
4997 /* Print lines annotated so far. */
4998 bline = &a->lines[a->lineno_cur - 1];
4999 if (!bline->annotated)
5000 goto done;
5002 offset = a->line_offsets[a->lineno_cur - 1];
5003 if (fseeko(a->f, offset, SEEK_SET) == -1) {
5004 err = got_error_from_errno("fseeko");
5005 goto done;
5008 while (a->lineno_cur <= a->nlines && bline->annotated) {
5009 char *smallerthan, *at, *nl, *committer;
5010 size_t len;
5012 if (getline(&line, &linesize, a->f) == -1) {
5013 if (ferror(a->f))
5014 err = got_error_from_errno("getline");
5015 break;
5018 committer = bline->committer;
5019 smallerthan = strchr(committer, '<');
5020 if (smallerthan && smallerthan[1] != '\0')
5021 committer = smallerthan + 1;
5022 at = strchr(committer, '@');
5023 if (at)
5024 *at = '\0';
5025 len = strlen(committer);
5026 if (len >= 9)
5027 committer[8] = '\0';
5029 nl = strchr(line, '\n');
5030 if (nl)
5031 *nl = '\0';
5032 printf("%.*d) %.8s %s %-8s %s\n", a->nlines_prec, a->lineno_cur,
5033 bline->id_str, bline->datebuf, committer, line);
5035 a->lineno_cur++;
5036 bline = &a->lines[a->lineno_cur - 1];
5038 done:
5039 free(line);
5040 return err;
5043 static const struct got_error *
5044 cmd_blame(int argc, char *argv[])
5046 const struct got_error *error;
5047 struct got_repository *repo = NULL;
5048 struct got_worktree *worktree = NULL;
5049 char *path, *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
5050 char *link_target = NULL;
5051 struct got_object_id *obj_id = NULL;
5052 struct got_object_id *commit_id = NULL;
5053 struct got_commit_object *commit = NULL;
5054 struct got_blob_object *blob = NULL;
5055 char *commit_id_str = NULL;
5056 struct blame_cb_args bca;
5057 int ch, obj_type, i, fd1 = -1, fd2 = -1, fd3 = -1;
5058 off_t filesize;
5059 int *pack_fds = NULL;
5060 FILE *f1 = NULL, *f2 = NULL;
5062 fd1 = got_opentempfd();
5063 if (fd1 == -1)
5064 return got_error_from_errno("got_opentempfd");
5066 memset(&bca, 0, sizeof(bca));
5068 #ifndef PROFILE
5069 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
5070 NULL) == -1)
5071 err(1, "pledge");
5072 #endif
5074 while ((ch = getopt(argc, argv, "c:r:")) != -1) {
5075 switch (ch) {
5076 case 'c':
5077 commit_id_str = optarg;
5078 break;
5079 case 'r':
5080 repo_path = realpath(optarg, NULL);
5081 if (repo_path == NULL)
5082 return got_error_from_errno2("realpath",
5083 optarg);
5084 got_path_strip_trailing_slashes(repo_path);
5085 break;
5086 default:
5087 usage_blame();
5088 /* NOTREACHED */
5092 argc -= optind;
5093 argv += optind;
5095 if (argc == 1)
5096 path = argv[0];
5097 else
5098 usage_blame();
5100 cwd = getcwd(NULL, 0);
5101 if (cwd == NULL) {
5102 error = got_error_from_errno("getcwd");
5103 goto done;
5106 error = got_repo_pack_fds_open(&pack_fds);
5107 if (error != NULL)
5108 goto done;
5110 if (repo_path == NULL) {
5111 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_CVG_DIR);
5112 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5113 goto done;
5114 else
5115 error = NULL;
5116 if (worktree) {
5117 repo_path =
5118 strdup(got_worktree_get_repo_path(worktree));
5119 if (repo_path == NULL) {
5120 error = got_error_from_errno("strdup");
5121 if (error)
5122 goto done;
5124 } else {
5125 repo_path = strdup(cwd);
5126 if (repo_path == NULL) {
5127 error = got_error_from_errno("strdup");
5128 goto done;
5133 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
5134 if (error != NULL)
5135 goto done;
5137 if (worktree) {
5138 const char *prefix = got_worktree_get_path_prefix(worktree);
5139 char *p;
5141 error = got_worktree_resolve_path(&p, worktree, path);
5142 if (error)
5143 goto done;
5144 if (asprintf(&in_repo_path, "%s%s%s", prefix,
5145 (p[0] != '\0' && !got_path_is_root_dir(prefix)) ? "/" : "",
5146 p) == -1) {
5147 error = got_error_from_errno("asprintf");
5148 free(p);
5149 goto done;
5151 free(p);
5152 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5153 } else {
5154 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5155 if (error)
5156 goto done;
5157 error = got_repo_map_path(&in_repo_path, repo, path);
5159 if (error)
5160 goto done;
5162 if (commit_id_str == NULL) {
5163 struct got_reference *head_ref;
5164 error = got_ref_open(&head_ref, repo, worktree ?
5165 got_worktree_get_head_ref_name(worktree) : GOT_REF_HEAD, 0);
5166 if (error != NULL)
5167 goto done;
5168 error = got_ref_resolve(&commit_id, repo, head_ref);
5169 got_ref_close(head_ref);
5170 if (error != NULL)
5171 goto done;
5172 } else {
5173 struct got_reflist_head refs;
5174 TAILQ_INIT(&refs);
5175 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
5176 NULL);
5177 if (error)
5178 goto done;
5179 error = got_repo_match_object_id(&commit_id, NULL,
5180 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
5181 got_ref_list_free(&refs);
5182 if (error)
5183 goto done;
5186 if (worktree) {
5187 /* Release work tree lock. */
5188 got_worktree_close(worktree);
5189 worktree = NULL;
5192 error = got_object_open_as_commit(&commit, repo, commit_id);
5193 if (error)
5194 goto done;
5196 error = got_object_resolve_symlinks(&link_target, in_repo_path,
5197 commit, repo);
5198 if (error)
5199 goto done;
5201 error = got_object_id_by_path(&obj_id, repo, commit,
5202 link_target ? link_target : in_repo_path);
5203 if (error)
5204 goto done;
5206 error = got_object_get_type(&obj_type, repo, obj_id);
5207 if (error)
5208 goto done;
5210 if (obj_type != GOT_OBJ_TYPE_BLOB) {
5211 error = got_error_path(link_target ? link_target : in_repo_path,
5212 GOT_ERR_OBJ_TYPE);
5213 goto done;
5216 error = got_object_open_as_blob(&blob, repo, obj_id, 8192, fd1);
5217 if (error)
5218 goto done;
5219 bca.f = got_opentemp();
5220 if (bca.f == NULL) {
5221 error = got_error_from_errno("got_opentemp");
5222 goto done;
5224 error = got_object_blob_dump_to_file(&filesize, &bca.nlines,
5225 &bca.line_offsets, bca.f, blob);
5226 if (error || bca.nlines == 0)
5227 goto done;
5229 /* Don't include \n at EOF in the blame line count. */
5230 if (bca.line_offsets[bca.nlines - 1] == filesize)
5231 bca.nlines--;
5233 bca.lines = calloc(bca.nlines, sizeof(*bca.lines));
5234 if (bca.lines == NULL) {
5235 error = got_error_from_errno("calloc");
5236 goto done;
5238 bca.lineno_cur = 1;
5239 bca.nlines_prec = 0;
5240 i = bca.nlines;
5241 while (i > 0) {
5242 i /= 10;
5243 bca.nlines_prec++;
5245 bca.repo = repo;
5247 fd2 = got_opentempfd();
5248 if (fd2 == -1) {
5249 error = got_error_from_errno("got_opentempfd");
5250 goto done;
5252 fd3 = got_opentempfd();
5253 if (fd3 == -1) {
5254 error = got_error_from_errno("got_opentempfd");
5255 goto done;
5257 f1 = got_opentemp();
5258 if (f1 == NULL) {
5259 error = got_error_from_errno("got_opentemp");
5260 goto done;
5262 f2 = got_opentemp();
5263 if (f2 == NULL) {
5264 error = got_error_from_errno("got_opentemp");
5265 goto done;
5267 error = got_blame(link_target ? link_target : in_repo_path, commit_id,
5268 repo, GOT_DIFF_ALGORITHM_PATIENCE, blame_cb, &bca,
5269 check_cancelled, NULL, fd2, fd3, f1, f2);
5270 done:
5271 free(in_repo_path);
5272 free(link_target);
5273 free(repo_path);
5274 free(cwd);
5275 free(commit_id);
5276 free(obj_id);
5277 if (commit)
5278 got_object_commit_close(commit);
5280 if (fd1 != -1 && close(fd1) == -1 && error == NULL)
5281 error = got_error_from_errno("close");
5282 if (fd2 != -1 && close(fd2) == -1 && error == NULL)
5283 error = got_error_from_errno("close");
5284 if (fd3 != -1 && close(fd3) == -1 && error == NULL)
5285 error = got_error_from_errno("close");
5286 if (f1 && fclose(f1) == EOF && error == NULL)
5287 error = got_error_from_errno("fclose");
5288 if (f2 && fclose(f2) == EOF && error == NULL)
5289 error = got_error_from_errno("fclose");
5291 if (blob)
5292 got_object_blob_close(blob);
5293 if (worktree)
5294 got_worktree_close(worktree);
5295 if (repo) {
5296 const struct got_error *close_err = got_repo_close(repo);
5297 if (error == NULL)
5298 error = close_err;
5300 if (pack_fds) {
5301 const struct got_error *pack_err =
5302 got_repo_pack_fds_close(pack_fds);
5303 if (error == NULL)
5304 error = pack_err;
5306 if (bca.lines) {
5307 for (i = 0; i < bca.nlines; i++) {
5308 struct blame_line *bline = &bca.lines[i];
5309 free(bline->id_str);
5310 free(bline->committer);
5312 free(bca.lines);
5314 free(bca.line_offsets);
5315 if (bca.f && fclose(bca.f) == EOF && error == NULL)
5316 error = got_error_from_errno("fclose");
5317 return error;
5320 __dead static void
5321 usage_tree(void)
5323 fprintf(stderr, "usage: %s tree [-iR] [-c commit] [-r repository-path] "
5324 "[path]\n", getprogname());
5325 exit(1);
5328 static const struct got_error *
5329 print_entry(struct got_tree_entry *te, const char *id, const char *path,
5330 const char *root_path, struct got_repository *repo)
5332 const struct got_error *err = NULL;
5333 int is_root_path = (strcmp(path, root_path) == 0);
5334 const char *modestr = "";
5335 mode_t mode = got_tree_entry_get_mode(te);
5336 char *link_target = NULL;
5338 path += strlen(root_path);
5339 while (path[0] == '/')
5340 path++;
5342 if (got_object_tree_entry_is_submodule(te))
5343 modestr = "$";
5344 else if (S_ISLNK(mode)) {
5345 int i;
5347 err = got_tree_entry_get_symlink_target(&link_target, te, repo);
5348 if (err)
5349 return err;
5350 for (i = 0; link_target[i] != '\0'; i++) {
5351 if (!isprint((unsigned char)link_target[i]))
5352 link_target[i] = '?';
5355 modestr = "@";
5357 else if (S_ISDIR(mode))
5358 modestr = "/";
5359 else if (mode & S_IXUSR)
5360 modestr = "*";
5362 printf("%s%s%s%s%s%s%s\n", id ? id : "", path,
5363 is_root_path ? "" : "/", got_tree_entry_get_name(te), modestr,
5364 link_target ? " -> ": "", link_target ? link_target : "");
5366 free(link_target);
5367 return NULL;
5370 static const struct got_error *
5371 print_tree(const char *path, struct got_commit_object *commit,
5372 int show_ids, int recurse, const char *root_path,
5373 struct got_repository *repo)
5375 const struct got_error *err = NULL;
5376 struct got_object_id *tree_id = NULL;
5377 struct got_tree_object *tree = NULL;
5378 int nentries, i;
5380 err = got_object_id_by_path(&tree_id, repo, commit, path);
5381 if (err)
5382 goto done;
5384 err = got_object_open_as_tree(&tree, repo, tree_id);
5385 if (err)
5386 goto done;
5387 nentries = got_object_tree_get_nentries(tree);
5388 for (i = 0; i < nentries; i++) {
5389 struct got_tree_entry *te;
5390 char *id = NULL;
5392 if (sigint_received || sigpipe_received)
5393 break;
5395 te = got_object_tree_get_entry(tree, i);
5396 if (show_ids) {
5397 char *id_str;
5398 err = got_object_id_str(&id_str,
5399 got_tree_entry_get_id(te));
5400 if (err)
5401 goto done;
5402 if (asprintf(&id, "%s ", id_str) == -1) {
5403 err = got_error_from_errno("asprintf");
5404 free(id_str);
5405 goto done;
5407 free(id_str);
5409 err = print_entry(te, id, path, root_path, repo);
5410 free(id);
5411 if (err)
5412 goto done;
5414 if (recurse && S_ISDIR(got_tree_entry_get_mode(te))) {
5415 char *child_path;
5416 if (asprintf(&child_path, "%s%s%s", path,
5417 path[0] == '/' && path[1] == '\0' ? "" : "/",
5418 got_tree_entry_get_name(te)) == -1) {
5419 err = got_error_from_errno("asprintf");
5420 goto done;
5422 err = print_tree(child_path, commit, show_ids, 1,
5423 root_path, repo);
5424 free(child_path);
5425 if (err)
5426 goto done;
5429 done:
5430 if (tree)
5431 got_object_tree_close(tree);
5432 free(tree_id);
5433 return err;
5436 static const struct got_error *
5437 cmd_tree(int argc, char *argv[])
5439 const struct got_error *error;
5440 struct got_repository *repo = NULL;
5441 struct got_worktree *worktree = NULL;
5442 const char *path, *refname = NULL;
5443 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
5444 struct got_object_id *commit_id = NULL;
5445 struct got_commit_object *commit = NULL;
5446 char *commit_id_str = NULL;
5447 int show_ids = 0, recurse = 0;
5448 int ch;
5449 int *pack_fds = NULL;
5451 #ifndef PROFILE
5452 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
5453 NULL) == -1)
5454 err(1, "pledge");
5455 #endif
5457 while ((ch = getopt(argc, argv, "c:iRr:")) != -1) {
5458 switch (ch) {
5459 case 'c':
5460 commit_id_str = optarg;
5461 break;
5462 case 'i':
5463 show_ids = 1;
5464 break;
5465 case 'R':
5466 recurse = 1;
5467 break;
5468 case 'r':
5469 repo_path = realpath(optarg, NULL);
5470 if (repo_path == NULL)
5471 return got_error_from_errno2("realpath",
5472 optarg);
5473 got_path_strip_trailing_slashes(repo_path);
5474 break;
5475 default:
5476 usage_tree();
5477 /* NOTREACHED */
5481 argc -= optind;
5482 argv += optind;
5484 if (argc == 1)
5485 path = argv[0];
5486 else if (argc > 1)
5487 usage_tree();
5488 else
5489 path = NULL;
5491 cwd = getcwd(NULL, 0);
5492 if (cwd == NULL) {
5493 error = got_error_from_errno("getcwd");
5494 goto done;
5497 error = got_repo_pack_fds_open(&pack_fds);
5498 if (error != NULL)
5499 goto done;
5501 if (repo_path == NULL) {
5502 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_CVG_DIR);
5503 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5504 goto done;
5505 else
5506 error = NULL;
5507 if (worktree) {
5508 repo_path =
5509 strdup(got_worktree_get_repo_path(worktree));
5510 if (repo_path == NULL)
5511 error = got_error_from_errno("strdup");
5512 if (error)
5513 goto done;
5514 } else {
5515 repo_path = strdup(cwd);
5516 if (repo_path == NULL) {
5517 error = got_error_from_errno("strdup");
5518 goto done;
5523 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
5524 if (error != NULL)
5525 goto done;
5527 if (worktree) {
5528 const char *prefix = got_worktree_get_path_prefix(worktree);
5529 char *p;
5531 if (path == NULL || got_path_is_root_dir(path))
5532 path = "";
5533 error = got_worktree_resolve_path(&p, worktree, path);
5534 if (error)
5535 goto done;
5536 if (asprintf(&in_repo_path, "%s%s%s", prefix,
5537 (p[0] != '\0' && !got_path_is_root_dir(prefix)) ? "/" : "",
5538 p) == -1) {
5539 error = got_error_from_errno("asprintf");
5540 free(p);
5541 goto done;
5543 free(p);
5544 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5545 if (error)
5546 goto done;
5547 } else {
5548 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5549 if (error)
5550 goto done;
5551 if (path == NULL)
5552 path = "/";
5553 error = got_repo_map_path(&in_repo_path, repo, path);
5554 if (error != NULL)
5555 goto done;
5558 if (commit_id_str == NULL) {
5559 struct got_reference *head_ref;
5560 if (worktree)
5561 refname = got_worktree_get_head_ref_name(worktree);
5562 else
5563 refname = GOT_REF_HEAD;
5564 error = got_ref_open(&head_ref, repo, refname, 0);
5565 if (error != NULL)
5566 goto done;
5567 error = got_ref_resolve(&commit_id, repo, head_ref);
5568 got_ref_close(head_ref);
5569 if (error != NULL)
5570 goto done;
5571 } else {
5572 struct got_reflist_head refs;
5573 TAILQ_INIT(&refs);
5574 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
5575 NULL);
5576 if (error)
5577 goto done;
5578 error = got_repo_match_object_id(&commit_id, NULL,
5579 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
5580 got_ref_list_free(&refs);
5581 if (error)
5582 goto done;
5585 if (worktree) {
5586 /* Release work tree lock. */
5587 got_worktree_close(worktree);
5588 worktree = NULL;
5591 error = got_object_open_as_commit(&commit, repo, commit_id);
5592 if (error)
5593 goto done;
5595 error = print_tree(in_repo_path, commit, show_ids, recurse,
5596 in_repo_path, repo);
5597 done:
5598 free(in_repo_path);
5599 free(repo_path);
5600 free(cwd);
5601 free(commit_id);
5602 if (commit)
5603 got_object_commit_close(commit);
5604 if (worktree)
5605 got_worktree_close(worktree);
5606 if (repo) {
5607 const struct got_error *close_err = got_repo_close(repo);
5608 if (error == NULL)
5609 error = close_err;
5611 if (pack_fds) {
5612 const struct got_error *pack_err =
5613 got_repo_pack_fds_close(pack_fds);
5614 if (error == NULL)
5615 error = pack_err;
5617 return error;
5620 __dead static void
5621 usage_status(void)
5623 fprintf(stderr, "usage: %s status [-I] [-S status-codes] "
5624 "[-s status-codes] [path ...]\n", getprogname());
5625 exit(1);
5628 struct got_status_arg {
5629 char *status_codes;
5630 int suppress;
5633 static const struct got_error *
5634 print_status(void *arg, unsigned char status, unsigned char staged_status,
5635 const char *path, struct got_object_id *blob_id,
5636 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
5637 int dirfd, const char *de_name)
5639 struct got_status_arg *st = arg;
5641 if (status == staged_status && (status == GOT_STATUS_DELETE))
5642 status = GOT_STATUS_NO_CHANGE;
5643 if (st != NULL && st->status_codes) {
5644 size_t ncodes = strlen(st->status_codes);
5645 int i, j = 0;
5647 for (i = 0; i < ncodes ; i++) {
5648 if (st->suppress) {
5649 if (status == st->status_codes[i] ||
5650 staged_status == st->status_codes[i]) {
5651 j++;
5652 continue;
5654 } else {
5655 if (status == st->status_codes[i] ||
5656 staged_status == st->status_codes[i])
5657 break;
5661 if (st->suppress && j == 0)
5662 goto print;
5664 if (i == ncodes)
5665 return NULL;
5667 print:
5668 printf("%c%c %s\n", status, staged_status, path);
5669 return NULL;
5672 static const struct got_error *
5673 cmd_status(int argc, char *argv[])
5675 const struct got_error *error = NULL;
5676 struct got_repository *repo = NULL;
5677 struct got_worktree *worktree = NULL;
5678 struct got_status_arg st;
5679 char *cwd = NULL;
5680 struct got_pathlist_head paths;
5681 int ch, i, no_ignores = 0;
5682 int *pack_fds = NULL;
5684 TAILQ_INIT(&paths);
5686 memset(&st, 0, sizeof(st));
5687 st.status_codes = NULL;
5688 st.suppress = 0;
5690 #ifndef PROFILE
5691 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
5692 NULL) == -1)
5693 err(1, "pledge");
5694 #endif
5696 while ((ch = getopt(argc, argv, "IS:s:")) != -1) {
5697 switch (ch) {
5698 case 'I':
5699 no_ignores = 1;
5700 break;
5701 case 'S':
5702 if (st.status_codes != NULL && st.suppress == 0)
5703 option_conflict('S', 's');
5704 st.suppress = 1;
5705 /* fallthrough */
5706 case 's':
5707 for (i = 0; optarg[i] != '\0'; i++) {
5708 switch (optarg[i]) {
5709 case GOT_STATUS_MODIFY:
5710 case GOT_STATUS_ADD:
5711 case GOT_STATUS_DELETE:
5712 case GOT_STATUS_CONFLICT:
5713 case GOT_STATUS_MISSING:
5714 case GOT_STATUS_OBSTRUCTED:
5715 case GOT_STATUS_UNVERSIONED:
5716 case GOT_STATUS_MODE_CHANGE:
5717 case GOT_STATUS_NONEXISTENT:
5718 break;
5719 default:
5720 errx(1, "invalid status code '%c'",
5721 optarg[i]);
5724 if (ch == 's' && st.suppress)
5725 option_conflict('s', 'S');
5726 st.status_codes = optarg;
5727 break;
5728 default:
5729 usage_status();
5730 /* NOTREACHED */
5734 argc -= optind;
5735 argv += optind;
5737 cwd = getcwd(NULL, 0);
5738 if (cwd == NULL) {
5739 error = got_error_from_errno("getcwd");
5740 goto done;
5743 error = got_repo_pack_fds_open(&pack_fds);
5744 if (error != NULL)
5745 goto done;
5747 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_CVG_DIR);
5748 if (error) {
5749 if (error->code == GOT_ERR_NOT_WORKTREE)
5750 error = wrap_not_worktree_error(error, "status", cwd);
5751 goto done;
5754 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
5755 NULL, pack_fds);
5756 if (error != NULL)
5757 goto done;
5759 error = apply_unveil(got_repo_get_path(repo), 1,
5760 got_worktree_get_root_path(worktree));
5761 if (error)
5762 goto done;
5764 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
5765 if (error)
5766 goto done;
5768 error = got_worktree_status(worktree, &paths, repo, no_ignores,
5769 print_status, &st, check_cancelled, NULL);
5770 done:
5771 if (pack_fds) {
5772 const struct got_error *pack_err =
5773 got_repo_pack_fds_close(pack_fds);
5774 if (error == NULL)
5775 error = pack_err;
5777 if (repo) {
5778 const struct got_error *close_err = got_repo_close(repo);
5779 if (error == NULL)
5780 error = close_err;
5783 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
5784 free(cwd);
5785 return error;
5788 __dead static void
5789 usage_tag(void)
5791 fprintf(stderr, "usage: %s tag [-lVv] [-c commit] [-m message] "
5792 "[-r repository-path] [-s signer-id] name\n", getprogname());
5793 exit(1);
5796 #if 0
5797 static const struct got_error *
5798 sort_tags(struct got_reflist_head *sorted, struct got_reflist_head *tags)
5800 const struct got_error *err = NULL;
5801 struct got_reflist_entry *re, *se, *new;
5802 struct got_object_id *re_id, *se_id;
5803 struct got_tag_object *re_tag, *se_tag;
5804 time_t re_time, se_time;
5806 STAILQ_FOREACH(re, tags, entry) {
5807 se = STAILQ_FIRST(sorted);
5808 if (se == NULL) {
5809 err = got_reflist_entry_dup(&new, re);
5810 if (err)
5811 return err;
5812 STAILQ_INSERT_HEAD(sorted, new, entry);
5813 continue;
5814 } else {
5815 err = got_ref_resolve(&re_id, repo, re->ref);
5816 if (err)
5817 break;
5818 err = got_object_open_as_tag(&re_tag, repo, re_id);
5819 free(re_id);
5820 if (err)
5821 break;
5822 re_time = got_object_tag_get_tagger_time(re_tag);
5823 got_object_tag_close(re_tag);
5826 while (se) {
5827 err = got_ref_resolve(&se_id, repo, re->ref);
5828 if (err)
5829 break;
5830 err = got_object_open_as_tag(&se_tag, repo, se_id);
5831 free(se_id);
5832 if (err)
5833 break;
5834 se_time = got_object_tag_get_tagger_time(se_tag);
5835 got_object_tag_close(se_tag);
5837 if (se_time > re_time) {
5838 err = got_reflist_entry_dup(&new, re);
5839 if (err)
5840 return err;
5841 STAILQ_INSERT_AFTER(sorted, se, new, entry);
5842 break;
5844 se = STAILQ_NEXT(se, entry);
5845 continue;
5848 done:
5849 return err;
5851 #endif
5853 static const struct got_error *
5854 get_tag_refname(char **refname, const char *tag_name)
5856 const struct got_error *err;
5858 if (strncmp("refs/tags/", tag_name, 10) == 0) {
5859 *refname = strdup(tag_name);
5860 if (*refname == NULL)
5861 return got_error_from_errno("strdup");
5862 } else if (asprintf(refname, "refs/tags/%s", tag_name) == -1) {
5863 err = got_error_from_errno("asprintf");
5864 *refname = NULL;
5865 return err;
5868 return NULL;
5871 static const struct got_error *
5872 list_tags(struct got_repository *repo, const char *tag_name, int verify_tags,
5873 const char *allowed_signers, const char *revoked_signers, int verbosity)
5875 static const struct got_error *err = NULL;
5876 struct got_reflist_head refs;
5877 struct got_reflist_entry *re;
5878 char *wanted_refname = NULL;
5879 int bad_sigs = 0;
5881 TAILQ_INIT(&refs);
5883 err = got_ref_list(&refs, repo, "refs/tags", got_ref_cmp_tags, repo);
5884 if (err)
5885 return err;
5887 if (tag_name) {
5888 struct got_reference *ref;
5889 err = get_tag_refname(&wanted_refname, tag_name);
5890 if (err)
5891 goto done;
5892 /* Wanted tag reference should exist. */
5893 err = got_ref_open(&ref, repo, wanted_refname, 0);
5894 if (err)
5895 goto done;
5896 got_ref_close(ref);
5899 TAILQ_FOREACH(re, &refs, entry) {
5900 const char *refname;
5901 char *refstr, *tagmsg0, *tagmsg, *line, *id_str, *datestr;
5902 char datebuf[26];
5903 const char *tagger, *ssh_sig = NULL;
5904 char *sig_msg = NULL;
5905 time_t tagger_time;
5906 struct got_object_id *id;
5907 struct got_tag_object *tag;
5908 struct got_commit_object *commit = NULL;
5910 refname = got_ref_get_name(re->ref);
5911 if (strncmp(refname, "refs/tags/", 10) != 0 ||
5912 (wanted_refname && strcmp(refname, wanted_refname) != 0))
5913 continue;
5914 refname += 10;
5915 refstr = got_ref_to_str(re->ref);
5916 if (refstr == NULL) {
5917 err = got_error_from_errno("got_ref_to_str");
5918 break;
5921 err = got_ref_resolve(&id, repo, re->ref);
5922 if (err)
5923 break;
5924 err = got_object_open_as_tag(&tag, repo, id);
5925 if (err) {
5926 if (err->code != GOT_ERR_OBJ_TYPE) {
5927 free(id);
5928 break;
5930 /* "lightweight" tag */
5931 err = got_object_open_as_commit(&commit, repo, id);
5932 if (err) {
5933 free(id);
5934 break;
5936 tagger = got_object_commit_get_committer(commit);
5937 tagger_time =
5938 got_object_commit_get_committer_time(commit);
5939 err = got_object_id_str(&id_str, id);
5940 free(id);
5941 if (err)
5942 break;
5943 } else {
5944 free(id);
5945 tagger = got_object_tag_get_tagger(tag);
5946 tagger_time = got_object_tag_get_tagger_time(tag);
5947 err = got_object_id_str(&id_str,
5948 got_object_tag_get_object_id(tag));
5949 if (err)
5950 break;
5953 if (tag && verify_tags) {
5954 ssh_sig = got_sigs_get_tagmsg_ssh_signature(
5955 got_object_tag_get_message(tag));
5956 if (ssh_sig && allowed_signers == NULL) {
5957 err = got_error_msg(
5958 GOT_ERR_VERIFY_TAG_SIGNATURE,
5959 "SSH signature verification requires "
5960 "setting allowed_signers in "
5961 "got.conf(5)");
5962 break;
5966 printf("%stag %s %s\n", GOT_COMMIT_SEP_STR, refname, refstr);
5967 free(refstr);
5968 printf("from: %s\n", tagger);
5969 datestr = get_datestr(&tagger_time, datebuf);
5970 if (datestr)
5971 printf("date: %s UTC\n", datestr);
5972 if (commit)
5973 printf("object: %s %s\n", GOT_OBJ_LABEL_COMMIT, id_str);
5974 else {
5975 switch (got_object_tag_get_object_type(tag)) {
5976 case GOT_OBJ_TYPE_BLOB:
5977 printf("object: %s %s\n", GOT_OBJ_LABEL_BLOB,
5978 id_str);
5979 break;
5980 case GOT_OBJ_TYPE_TREE:
5981 printf("object: %s %s\n", GOT_OBJ_LABEL_TREE,
5982 id_str);
5983 break;
5984 case GOT_OBJ_TYPE_COMMIT:
5985 printf("object: %s %s\n", GOT_OBJ_LABEL_COMMIT,
5986 id_str);
5987 break;
5988 case GOT_OBJ_TYPE_TAG:
5989 printf("object: %s %s\n", GOT_OBJ_LABEL_TAG,
5990 id_str);
5991 break;
5992 default:
5993 break;
5996 free(id_str);
5998 if (ssh_sig) {
5999 err = got_sigs_verify_tag_ssh(&sig_msg, tag, ssh_sig,
6000 allowed_signers, revoked_signers, verbosity);
6001 if (err && err->code == GOT_ERR_BAD_TAG_SIGNATURE)
6002 bad_sigs = 1;
6003 else if (err)
6004 break;
6005 printf("signature: %s", sig_msg);
6006 free(sig_msg);
6007 sig_msg = NULL;
6010 if (commit) {
6011 err = got_object_commit_get_logmsg(&tagmsg0, commit);
6012 if (err)
6013 break;
6014 got_object_commit_close(commit);
6015 } else {
6016 tagmsg0 = strdup(got_object_tag_get_message(tag));
6017 got_object_tag_close(tag);
6018 if (tagmsg0 == NULL) {
6019 err = got_error_from_errno("strdup");
6020 break;
6024 tagmsg = tagmsg0;
6025 do {
6026 line = strsep(&tagmsg, "\n");
6027 if (line)
6028 printf(" %s\n", line);
6029 } while (line);
6030 free(tagmsg0);
6032 done:
6033 got_ref_list_free(&refs);
6034 free(wanted_refname);
6036 if (err == NULL && bad_sigs)
6037 err = got_error(GOT_ERR_BAD_TAG_SIGNATURE);
6038 return err;
6041 static const struct got_error *
6042 get_tag_message(char **tagmsg, char **tagmsg_path, const char *commit_id_str,
6043 const char *tag_name, const char *repo_path)
6045 const struct got_error *err = NULL;
6046 char *template = NULL, *initial_content = NULL;
6047 char *editor = NULL;
6048 int initial_content_len;
6049 int fd = -1;
6051 if (asprintf(&template, GOT_TMPDIR_STR "/got-tagmsg") == -1) {
6052 err = got_error_from_errno("asprintf");
6053 goto done;
6056 initial_content_len = asprintf(&initial_content,
6057 "\n# tagging commit %s as %s\n",
6058 commit_id_str, tag_name);
6059 if (initial_content_len == -1) {
6060 err = got_error_from_errno("asprintf");
6061 goto done;
6064 err = got_opentemp_named_fd(tagmsg_path, &fd, template, "");
6065 if (err)
6066 goto done;
6068 if (write(fd, initial_content, initial_content_len) == -1) {
6069 err = got_error_from_errno2("write", *tagmsg_path);
6070 goto done;
6072 if (close(fd) == -1) {
6073 err = got_error_from_errno2("close", *tagmsg_path);
6074 goto done;
6076 fd = -1;
6078 err = get_editor(&editor);
6079 if (err)
6080 goto done;
6081 err = edit_logmsg(tagmsg, editor, *tagmsg_path, initial_content,
6082 initial_content_len, 1);
6083 done:
6084 free(initial_content);
6085 free(template);
6086 free(editor);
6088 if (fd != -1 && close(fd) == -1 && err == NULL)
6089 err = got_error_from_errno2("close", *tagmsg_path);
6091 if (err) {
6092 free(*tagmsg);
6093 *tagmsg = NULL;
6095 return err;
6098 static const struct got_error *
6099 add_tag(struct got_repository *repo, const char *tagger,
6100 const char *tag_name, const char *commit_arg, const char *tagmsg_arg,
6101 const char *signer_id, int verbosity)
6103 const struct got_error *err = NULL;
6104 struct got_object_id *commit_id = NULL, *tag_id = NULL;
6105 char *label = NULL, *commit_id_str = NULL;
6106 struct got_reference *ref = NULL;
6107 char *refname = NULL, *tagmsg = NULL;
6108 char *tagmsg_path = NULL, *tag_id_str = NULL;
6109 int preserve_tagmsg = 0;
6110 struct got_reflist_head refs;
6112 TAILQ_INIT(&refs);
6115 * Don't let the user create a tag name with a leading '-'.
6116 * While technically a valid reference name, this case is usually
6117 * an unintended typo.
6119 if (tag_name[0] == '-')
6120 return got_error_path(tag_name, GOT_ERR_REF_NAME_MINUS);
6122 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
6123 if (err)
6124 goto done;
6126 err = got_repo_match_object_id(&commit_id, &label, commit_arg,
6127 GOT_OBJ_TYPE_COMMIT, &refs, repo);
6128 if (err)
6129 goto done;
6131 err = got_object_id_str(&commit_id_str, commit_id);
6132 if (err)
6133 goto done;
6135 err = get_tag_refname(&refname, tag_name);
6136 if (err)
6137 goto done;
6138 if (strncmp("refs/tags/", tag_name, 10) == 0)
6139 tag_name += 10;
6141 err = got_ref_open(&ref, repo, refname, 0);
6142 if (err == NULL) {
6143 err = got_error(GOT_ERR_TAG_EXISTS);
6144 goto done;
6145 } else if (err->code != GOT_ERR_NOT_REF)
6146 goto done;
6148 if (tagmsg_arg == NULL) {
6149 err = get_tag_message(&tagmsg, &tagmsg_path, commit_id_str,
6150 tag_name, got_repo_get_path(repo));
6151 if (err) {
6152 if (err->code != GOT_ERR_COMMIT_MSG_EMPTY &&
6153 tagmsg_path != NULL)
6154 preserve_tagmsg = 1;
6155 goto done;
6157 /* Editor is done; we can now apply unveil(2) */
6158 err = got_sigs_apply_unveil();
6159 if (err)
6160 goto done;
6161 err = apply_unveil(got_repo_get_path(repo), 0, NULL);
6162 if (err)
6163 goto done;
6166 err = got_object_tag_create(&tag_id, tag_name, commit_id,
6167 tagger, time(NULL), tagmsg ? tagmsg : tagmsg_arg, signer_id, repo,
6168 verbosity);
6169 if (err) {
6170 if (tagmsg_path)
6171 preserve_tagmsg = 1;
6172 goto done;
6175 err = got_ref_alloc(&ref, refname, tag_id);
6176 if (err) {
6177 if (tagmsg_path)
6178 preserve_tagmsg = 1;
6179 goto done;
6182 err = got_ref_write(ref, repo);
6183 if (err) {
6184 if (tagmsg_path)
6185 preserve_tagmsg = 1;
6186 goto done;
6189 err = got_object_id_str(&tag_id_str, tag_id);
6190 if (err) {
6191 if (tagmsg_path)
6192 preserve_tagmsg = 1;
6193 goto done;
6195 printf("Created tag %s\n", tag_id_str);
6196 done:
6197 if (preserve_tagmsg) {
6198 fprintf(stderr, "%s: tag message preserved in %s\n",
6199 getprogname(), tagmsg_path);
6200 } else if (tagmsg_path && unlink(tagmsg_path) == -1 && err == NULL)
6201 err = got_error_from_errno2("unlink", tagmsg_path);
6202 free(tag_id_str);
6203 if (ref)
6204 got_ref_close(ref);
6205 free(commit_id);
6206 free(commit_id_str);
6207 free(refname);
6208 free(tagmsg);
6209 free(tagmsg_path);
6210 got_ref_list_free(&refs);
6211 return err;
6214 static const struct got_error *
6215 cmd_tag(int argc, char *argv[])
6217 const struct got_error *error = NULL;
6218 struct got_repository *repo = NULL;
6219 struct got_worktree *worktree = NULL;
6220 char *cwd = NULL, *repo_path = NULL, *commit_id_str = NULL;
6221 char *gitconfig_path = NULL, *tagger = NULL;
6222 char *allowed_signers = NULL, *revoked_signers = NULL;
6223 const char *signer_id = NULL;
6224 const char *tag_name = NULL, *commit_id_arg = NULL, *tagmsg = NULL;
6225 int ch, do_list = 0, verify_tags = 0, verbosity = 0;
6226 int *pack_fds = NULL;
6228 #ifndef PROFILE
6229 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
6230 "sendfd unveil", NULL) == -1)
6231 err(1, "pledge");
6232 #endif
6234 while ((ch = getopt(argc, argv, "c:lm:r:s:Vv")) != -1) {
6235 switch (ch) {
6236 case 'c':
6237 commit_id_arg = optarg;
6238 break;
6239 case 'l':
6240 do_list = 1;
6241 break;
6242 case 'm':
6243 tagmsg = optarg;
6244 break;
6245 case 'r':
6246 repo_path = realpath(optarg, NULL);
6247 if (repo_path == NULL) {
6248 error = got_error_from_errno2("realpath",
6249 optarg);
6250 goto done;
6252 got_path_strip_trailing_slashes(repo_path);
6253 break;
6254 case 's':
6255 signer_id = optarg;
6256 break;
6257 case 'V':
6258 verify_tags = 1;
6259 break;
6260 case 'v':
6261 if (verbosity < 0)
6262 verbosity = 0;
6263 else if (verbosity < 3)
6264 verbosity++;
6265 break;
6266 default:
6267 usage_tag();
6268 /* NOTREACHED */
6272 argc -= optind;
6273 argv += optind;
6275 if (do_list || verify_tags) {
6276 if (commit_id_arg != NULL)
6277 errx(1,
6278 "-c option can only be used when creating a tag");
6279 if (tagmsg) {
6280 if (do_list)
6281 option_conflict('l', 'm');
6282 else
6283 option_conflict('V', 'm');
6285 if (signer_id) {
6286 if (do_list)
6287 option_conflict('l', 's');
6288 else
6289 option_conflict('V', 's');
6291 if (argc > 1)
6292 usage_tag();
6293 } else if (argc != 1)
6294 usage_tag();
6296 if (argc == 1)
6297 tag_name = argv[0];
6299 cwd = getcwd(NULL, 0);
6300 if (cwd == NULL) {
6301 error = got_error_from_errno("getcwd");
6302 goto done;
6305 error = got_repo_pack_fds_open(&pack_fds);
6306 if (error != NULL)
6307 goto done;
6309 if (repo_path == NULL) {
6310 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_CVG_DIR);
6311 if (error && error->code != GOT_ERR_NOT_WORKTREE)
6312 goto done;
6313 else
6314 error = NULL;
6315 if (worktree) {
6316 repo_path =
6317 strdup(got_worktree_get_repo_path(worktree));
6318 if (repo_path == NULL)
6319 error = got_error_from_errno("strdup");
6320 if (error)
6321 goto done;
6322 } else {
6323 repo_path = strdup(cwd);
6324 if (repo_path == NULL) {
6325 error = got_error_from_errno("strdup");
6326 goto done;
6331 if (do_list || verify_tags) {
6332 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
6333 if (error != NULL)
6334 goto done;
6335 error = get_allowed_signers(&allowed_signers, repo, worktree);
6336 if (error)
6337 goto done;
6338 error = get_revoked_signers(&revoked_signers, repo, worktree);
6339 if (error)
6340 goto done;
6341 if (worktree) {
6342 /* Release work tree lock. */
6343 got_worktree_close(worktree);
6344 worktree = NULL;
6348 * Remove "cpath" promise unless needed for signature tmpfile
6349 * creation.
6351 if (verify_tags)
6352 got_sigs_apply_unveil();
6353 else {
6354 #ifndef PROFILE
6355 if (pledge("stdio rpath wpath flock proc exec sendfd "
6356 "unveil", NULL) == -1)
6357 err(1, "pledge");
6358 #endif
6360 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
6361 if (error)
6362 goto done;
6363 error = list_tags(repo, tag_name, verify_tags, allowed_signers,
6364 revoked_signers, verbosity);
6365 } else {
6366 error = get_gitconfig_path(&gitconfig_path);
6367 if (error)
6368 goto done;
6369 error = got_repo_open(&repo, repo_path, gitconfig_path,
6370 pack_fds);
6371 if (error != NULL)
6372 goto done;
6374 error = get_author(&tagger, repo, worktree);
6375 if (error)
6376 goto done;
6377 if (signer_id == NULL)
6378 signer_id = get_signer_id(repo, worktree);
6380 if (tagmsg) {
6381 if (signer_id) {
6382 error = got_sigs_apply_unveil();
6383 if (error)
6384 goto done;
6386 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
6387 if (error)
6388 goto done;
6391 if (commit_id_arg == NULL) {
6392 struct got_reference *head_ref;
6393 struct got_object_id *commit_id;
6394 error = got_ref_open(&head_ref, repo,
6395 worktree ? got_worktree_get_head_ref_name(worktree)
6396 : GOT_REF_HEAD, 0);
6397 if (error)
6398 goto done;
6399 error = got_ref_resolve(&commit_id, repo, head_ref);
6400 got_ref_close(head_ref);
6401 if (error)
6402 goto done;
6403 error = got_object_id_str(&commit_id_str, commit_id);
6404 free(commit_id);
6405 if (error)
6406 goto done;
6409 if (worktree) {
6410 /* Release work tree lock. */
6411 got_worktree_close(worktree);
6412 worktree = NULL;
6415 error = add_tag(repo, tagger, tag_name,
6416 commit_id_str ? commit_id_str : commit_id_arg, tagmsg,
6417 signer_id, verbosity);
6419 done:
6420 if (repo) {
6421 const struct got_error *close_err = got_repo_close(repo);
6422 if (error == NULL)
6423 error = close_err;
6425 if (worktree)
6426 got_worktree_close(worktree);
6427 if (pack_fds) {
6428 const struct got_error *pack_err =
6429 got_repo_pack_fds_close(pack_fds);
6430 if (error == NULL)
6431 error = pack_err;
6433 free(cwd);
6434 free(repo_path);
6435 free(gitconfig_path);
6436 free(commit_id_str);
6437 free(tagger);
6438 free(allowed_signers);
6439 free(revoked_signers);
6440 return error;
6443 __dead static void
6444 usage_add(void)
6446 fprintf(stderr, "usage: %s add [-IR] path ...\n", getprogname());
6447 exit(1);
6450 static const struct got_error *
6451 add_progress(void *arg, unsigned char status, const char *path)
6453 while (path[0] == '/')
6454 path++;
6455 printf("%c %s\n", status, path);
6456 return NULL;
6459 static const struct got_error *
6460 cmd_add(int argc, char *argv[])
6462 const struct got_error *error = NULL;
6463 struct got_repository *repo = NULL;
6464 struct got_worktree *worktree = NULL;
6465 char *cwd = NULL;
6466 struct got_pathlist_head paths;
6467 struct got_pathlist_entry *pe;
6468 int ch, can_recurse = 0, no_ignores = 0;
6469 int *pack_fds = NULL;
6471 TAILQ_INIT(&paths);
6473 #ifndef PROFILE
6474 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
6475 NULL) == -1)
6476 err(1, "pledge");
6477 #endif
6479 while ((ch = getopt(argc, argv, "IR")) != -1) {
6480 switch (ch) {
6481 case 'I':
6482 no_ignores = 1;
6483 break;
6484 case 'R':
6485 can_recurse = 1;
6486 break;
6487 default:
6488 usage_add();
6489 /* NOTREACHED */
6493 argc -= optind;
6494 argv += optind;
6496 if (argc < 1)
6497 usage_add();
6499 cwd = getcwd(NULL, 0);
6500 if (cwd == NULL) {
6501 error = got_error_from_errno("getcwd");
6502 goto done;
6505 error = got_repo_pack_fds_open(&pack_fds);
6506 if (error != NULL)
6507 goto done;
6509 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_CVG_DIR);
6510 if (error) {
6511 if (error->code == GOT_ERR_NOT_WORKTREE)
6512 error = wrap_not_worktree_error(error, "add", cwd);
6513 goto done;
6516 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
6517 NULL, pack_fds);
6518 if (error != NULL)
6519 goto done;
6521 error = apply_unveil(got_repo_get_path(repo), 1,
6522 got_worktree_get_root_path(worktree));
6523 if (error)
6524 goto done;
6526 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
6527 if (error)
6528 goto done;
6530 if (!can_recurse) {
6531 char *ondisk_path;
6532 struct stat sb;
6533 TAILQ_FOREACH(pe, &paths, entry) {
6534 if (asprintf(&ondisk_path, "%s/%s",
6535 got_worktree_get_root_path(worktree),
6536 pe->path) == -1) {
6537 error = got_error_from_errno("asprintf");
6538 goto done;
6540 if (lstat(ondisk_path, &sb) == -1) {
6541 if (errno == ENOENT) {
6542 free(ondisk_path);
6543 continue;
6545 error = got_error_from_errno2("lstat",
6546 ondisk_path);
6547 free(ondisk_path);
6548 goto done;
6550 free(ondisk_path);
6551 if (S_ISDIR(sb.st_mode)) {
6552 error = got_error_msg(GOT_ERR_BAD_PATH,
6553 "adding directories requires -R option");
6554 goto done;
6559 error = got_worktree_schedule_add(worktree, &paths, add_progress,
6560 NULL, repo, no_ignores);
6561 done:
6562 if (repo) {
6563 const struct got_error *close_err = got_repo_close(repo);
6564 if (error == NULL)
6565 error = close_err;
6567 if (worktree)
6568 got_worktree_close(worktree);
6569 if (pack_fds) {
6570 const struct got_error *pack_err =
6571 got_repo_pack_fds_close(pack_fds);
6572 if (error == NULL)
6573 error = pack_err;
6575 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
6576 free(cwd);
6577 return error;
6580 __dead static void
6581 usage_remove(void)
6583 fprintf(stderr, "usage: %s remove [-fkR] [-s status-codes] path ...\n",
6584 getprogname());
6585 exit(1);
6588 static const struct got_error *
6589 print_remove_status(void *arg, unsigned char status,
6590 unsigned char staged_status, const char *path)
6592 while (path[0] == '/')
6593 path++;
6594 if (status == GOT_STATUS_NONEXISTENT)
6595 return NULL;
6596 if (status == staged_status && (status == GOT_STATUS_DELETE))
6597 status = GOT_STATUS_NO_CHANGE;
6598 printf("%c%c %s\n", status, staged_status, path);
6599 return NULL;
6602 static const struct got_error *
6603 cmd_remove(int argc, char *argv[])
6605 const struct got_error *error = NULL;
6606 struct got_worktree *worktree = NULL;
6607 struct got_repository *repo = NULL;
6608 const char *status_codes = NULL;
6609 char *cwd = NULL;
6610 struct got_pathlist_head paths;
6611 struct got_pathlist_entry *pe;
6612 int ch, delete_local_mods = 0, can_recurse = 0, keep_on_disk = 0, i;
6613 int ignore_missing_paths = 0;
6614 int *pack_fds = NULL;
6616 TAILQ_INIT(&paths);
6618 #ifndef PROFILE
6619 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
6620 NULL) == -1)
6621 err(1, "pledge");
6622 #endif
6624 while ((ch = getopt(argc, argv, "fkRs:")) != -1) {
6625 switch (ch) {
6626 case 'f':
6627 delete_local_mods = 1;
6628 ignore_missing_paths = 1;
6629 break;
6630 case 'k':
6631 keep_on_disk = 1;
6632 break;
6633 case 'R':
6634 can_recurse = 1;
6635 break;
6636 case 's':
6637 for (i = 0; optarg[i] != '\0'; i++) {
6638 switch (optarg[i]) {
6639 case GOT_STATUS_MODIFY:
6640 delete_local_mods = 1;
6641 break;
6642 case GOT_STATUS_MISSING:
6643 ignore_missing_paths = 1;
6644 break;
6645 default:
6646 errx(1, "invalid status code '%c'",
6647 optarg[i]);
6650 status_codes = optarg;
6651 break;
6652 default:
6653 usage_remove();
6654 /* NOTREACHED */
6658 argc -= optind;
6659 argv += optind;
6661 if (argc < 1)
6662 usage_remove();
6664 cwd = getcwd(NULL, 0);
6665 if (cwd == NULL) {
6666 error = got_error_from_errno("getcwd");
6667 goto done;
6670 error = got_repo_pack_fds_open(&pack_fds);
6671 if (error != NULL)
6672 goto done;
6674 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_CVG_DIR);
6675 if (error) {
6676 if (error->code == GOT_ERR_NOT_WORKTREE)
6677 error = wrap_not_worktree_error(error, "remove", cwd);
6678 goto done;
6681 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
6682 NULL, pack_fds);
6683 if (error)
6684 goto done;
6686 error = apply_unveil(got_repo_get_path(repo), 1,
6687 got_worktree_get_root_path(worktree));
6688 if (error)
6689 goto done;
6691 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
6692 if (error)
6693 goto done;
6695 if (!can_recurse) {
6696 char *ondisk_path;
6697 struct stat sb;
6698 TAILQ_FOREACH(pe, &paths, entry) {
6699 if (asprintf(&ondisk_path, "%s/%s",
6700 got_worktree_get_root_path(worktree),
6701 pe->path) == -1) {
6702 error = got_error_from_errno("asprintf");
6703 goto done;
6705 if (lstat(ondisk_path, &sb) == -1) {
6706 if (errno == ENOENT) {
6707 free(ondisk_path);
6708 continue;
6710 error = got_error_from_errno2("lstat",
6711 ondisk_path);
6712 free(ondisk_path);
6713 goto done;
6715 free(ondisk_path);
6716 if (S_ISDIR(sb.st_mode)) {
6717 error = got_error_msg(GOT_ERR_BAD_PATH,
6718 "removing directories requires -R option");
6719 goto done;
6724 error = got_worktree_schedule_delete(worktree, &paths,
6725 delete_local_mods, status_codes, print_remove_status, NULL,
6726 repo, keep_on_disk, ignore_missing_paths);
6727 done:
6728 if (repo) {
6729 const struct got_error *close_err = got_repo_close(repo);
6730 if (error == NULL)
6731 error = close_err;
6733 if (worktree)
6734 got_worktree_close(worktree);
6735 if (pack_fds) {
6736 const struct got_error *pack_err =
6737 got_repo_pack_fds_close(pack_fds);
6738 if (error == NULL)
6739 error = pack_err;
6741 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
6742 free(cwd);
6743 return error;
6746 __dead static void
6747 usage_patch(void)
6749 fprintf(stderr, "usage: %s patch [-nR] [-c commit] [-p strip-count] "
6750 "[patchfile]\n", getprogname());
6751 exit(1);
6754 static const struct got_error *
6755 patch_from_stdin(int *patchfd)
6757 const struct got_error *err = NULL;
6758 ssize_t r;
6759 char buf[BUFSIZ];
6760 sig_t sighup, sigint, sigquit;
6762 *patchfd = got_opentempfd();
6763 if (*patchfd == -1)
6764 return got_error_from_errno("got_opentempfd");
6766 sighup = signal(SIGHUP, SIG_DFL);
6767 sigint = signal(SIGINT, SIG_DFL);
6768 sigquit = signal(SIGQUIT, SIG_DFL);
6770 for (;;) {
6771 r = read(0, buf, sizeof(buf));
6772 if (r == -1) {
6773 err = got_error_from_errno("read");
6774 break;
6776 if (r == 0)
6777 break;
6778 if (write(*patchfd, buf, r) == -1) {
6779 err = got_error_from_errno("write");
6780 break;
6784 signal(SIGHUP, sighup);
6785 signal(SIGINT, sigint);
6786 signal(SIGQUIT, sigquit);
6788 if (err == NULL && lseek(*patchfd, 0, SEEK_SET) == -1)
6789 err = got_error_from_errno("lseek");
6791 if (err != NULL) {
6792 close(*patchfd);
6793 *patchfd = -1;
6796 return err;
6799 struct got_patch_progress_arg {
6800 int did_something;
6801 int conflicts;
6802 int rejects;
6805 static const struct got_error *
6806 patch_progress(void *arg, const char *old, const char *new,
6807 unsigned char status, const struct got_error *error, int old_from,
6808 int old_lines, int new_from, int new_lines, int offset,
6809 int ws_mangled, const struct got_error *hunk_err)
6811 const char *path = new == NULL ? old : new;
6812 struct got_patch_progress_arg *a = arg;
6814 while (*path == '/')
6815 path++;
6817 if (status != GOT_STATUS_NO_CHANGE &&
6818 status != 0 /* per-hunk progress */) {
6819 printf("%c %s\n", status, path);
6820 a->did_something = 1;
6823 if (hunk_err == NULL) {
6824 if (status == GOT_STATUS_CANNOT_UPDATE)
6825 a->rejects++;
6826 else if (status == GOT_STATUS_CONFLICT)
6827 a->conflicts++;
6830 if (error != NULL)
6831 fprintf(stderr, "%s: %s\n", getprogname(), error->msg);
6833 if (offset != 0 || hunk_err != NULL || ws_mangled) {
6834 printf("@@ -%d,%d +%d,%d @@ ", old_from,
6835 old_lines, new_from, new_lines);
6836 if (hunk_err != NULL)
6837 printf("%s\n", hunk_err->msg);
6838 else if (offset != 0)
6839 printf("applied with offset %d\n", offset);
6840 else
6841 printf("hunk contains mangled whitespace\n");
6844 return NULL;
6847 static void
6848 print_patch_progress_stats(struct got_patch_progress_arg *ppa)
6850 if (!ppa->did_something)
6851 return;
6853 if (ppa->conflicts > 0)
6854 printf("Files with merge conflicts: %d\n", ppa->conflicts);
6856 if (ppa->rejects > 0) {
6857 printf("Files where patch failed to apply: %d\n",
6858 ppa->rejects);
6862 static const struct got_error *
6863 cmd_patch(int argc, char *argv[])
6865 const struct got_error *error = NULL, *close_error = NULL;
6866 struct got_worktree *worktree = NULL;
6867 struct got_repository *repo = NULL;
6868 struct got_reflist_head refs;
6869 struct got_object_id *commit_id = NULL;
6870 const char *commit_id_str = NULL;
6871 struct stat sb;
6872 const char *errstr;
6873 char *cwd = NULL;
6874 int ch, nop = 0, strip = -1, reverse = 0;
6875 int patchfd;
6876 int *pack_fds = NULL;
6877 struct got_patch_progress_arg ppa;
6879 TAILQ_INIT(&refs);
6881 #ifndef PROFILE
6882 if (pledge("stdio rpath wpath cpath fattr proc exec sendfd flock "
6883 "unveil", NULL) == -1)
6884 err(1, "pledge");
6885 #endif
6887 while ((ch = getopt(argc, argv, "c:np:R")) != -1) {
6888 switch (ch) {
6889 case 'c':
6890 commit_id_str = optarg;
6891 break;
6892 case 'n':
6893 nop = 1;
6894 break;
6895 case 'p':
6896 strip = strtonum(optarg, 0, INT_MAX, &errstr);
6897 if (errstr != NULL)
6898 errx(1, "pathname strip count is %s: %s",
6899 errstr, optarg);
6900 break;
6901 case 'R':
6902 reverse = 1;
6903 break;
6904 default:
6905 usage_patch();
6906 /* NOTREACHED */
6910 argc -= optind;
6911 argv += optind;
6913 if (argc == 0) {
6914 error = patch_from_stdin(&patchfd);
6915 if (error)
6916 return error;
6917 } else if (argc == 1) {
6918 patchfd = open(argv[0], O_RDONLY);
6919 if (patchfd == -1) {
6920 error = got_error_from_errno2("open", argv[0]);
6921 return error;
6923 if (fstat(patchfd, &sb) == -1) {
6924 error = got_error_from_errno2("fstat", argv[0]);
6925 goto done;
6927 if (!S_ISREG(sb.st_mode)) {
6928 error = got_error_path(argv[0], GOT_ERR_BAD_FILETYPE);
6929 goto done;
6931 } else
6932 usage_patch();
6934 if ((cwd = getcwd(NULL, 0)) == NULL) {
6935 error = got_error_from_errno("getcwd");
6936 goto done;
6939 error = got_repo_pack_fds_open(&pack_fds);
6940 if (error != NULL)
6941 goto done;
6943 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_CVG_DIR);
6944 if (error != NULL)
6945 goto done;
6947 const char *repo_path = got_worktree_get_repo_path(worktree);
6948 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
6949 if (error != NULL)
6950 goto done;
6952 error = apply_unveil(got_repo_get_path(repo), 0,
6953 got_worktree_get_root_path(worktree));
6954 if (error != NULL)
6955 goto done;
6957 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
6958 if (error)
6959 goto done;
6961 if (commit_id_str != NULL) {
6962 error = got_repo_match_object_id(&commit_id, NULL,
6963 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
6964 if (error)
6965 goto done;
6968 memset(&ppa, 0, sizeof(ppa));
6969 error = got_patch(patchfd, worktree, repo, nop, strip, reverse,
6970 commit_id, patch_progress, &ppa, check_cancelled, NULL);
6971 print_patch_progress_stats(&ppa);
6972 done:
6973 got_ref_list_free(&refs);
6974 free(commit_id);
6975 if (repo) {
6976 close_error = got_repo_close(repo);
6977 if (error == NULL)
6978 error = close_error;
6980 if (worktree != NULL) {
6981 close_error = got_worktree_close(worktree);
6982 if (error == NULL)
6983 error = close_error;
6985 if (pack_fds) {
6986 const struct got_error *pack_err =
6987 got_repo_pack_fds_close(pack_fds);
6988 if (error == NULL)
6989 error = pack_err;
6991 free(cwd);
6992 return error;
6995 __dead static void
6996 usage_revert(void)
6998 fprintf(stderr, "usage: %s revert [-pR] [-F response-script] path ...\n",
6999 getprogname());
7000 exit(1);
7003 static const struct got_error *
7004 revert_progress(void *arg, unsigned char status, const char *path)
7006 if (status == GOT_STATUS_UNVERSIONED)
7007 return NULL;
7009 while (path[0] == '/')
7010 path++;
7011 printf("%c %s\n", status, path);
7012 return NULL;
7015 struct choose_patch_arg {
7016 FILE *patch_script_file;
7017 const char *action;
7020 static const struct got_error *
7021 show_change(unsigned char status, const char *path, FILE *patch_file, int n,
7022 int nchanges, const char *action)
7024 const struct got_error *err;
7025 char *line = NULL;
7026 size_t linesize = 0;
7027 ssize_t linelen;
7029 switch (status) {
7030 case GOT_STATUS_ADD:
7031 printf("A %s\n%s this addition? [y/n] ", path, action);
7032 break;
7033 case GOT_STATUS_DELETE:
7034 printf("D %s\n%s this deletion? [y/n] ", path, action);
7035 break;
7036 case GOT_STATUS_MODIFY:
7037 if (fseek(patch_file, 0L, SEEK_SET) == -1)
7038 return got_error_from_errno("fseek");
7039 printf(GOT_COMMIT_SEP_STR);
7040 while ((linelen = getline(&line, &linesize, patch_file)) != -1)
7041 printf("%s", line);
7042 if (linelen == -1 && ferror(patch_file)) {
7043 err = got_error_from_errno("getline");
7044 free(line);
7045 return err;
7047 free(line);
7048 printf(GOT_COMMIT_SEP_STR);
7049 printf("M %s (change %d of %d)\n%s this change? [y/n/q] ",
7050 path, n, nchanges, action);
7051 break;
7052 default:
7053 return got_error_path(path, GOT_ERR_FILE_STATUS);
7056 fflush(stdout);
7057 return NULL;
7060 static const struct got_error *
7061 choose_patch(int *choice, void *arg, unsigned char status, const char *path,
7062 FILE *patch_file, int n, int nchanges)
7064 const struct got_error *err = NULL;
7065 char *line = NULL;
7066 size_t linesize = 0;
7067 ssize_t linelen;
7068 int resp = ' ';
7069 struct choose_patch_arg *a = arg;
7071 *choice = GOT_PATCH_CHOICE_NONE;
7073 if (a->patch_script_file) {
7074 char *nl;
7075 err = show_change(status, path, patch_file, n, nchanges,
7076 a->action);
7077 if (err)
7078 return err;
7079 linelen = getline(&line, &linesize, a->patch_script_file);
7080 if (linelen == -1) {
7081 if (ferror(a->patch_script_file))
7082 return got_error_from_errno("getline");
7083 return NULL;
7085 nl = strchr(line, '\n');
7086 if (nl)
7087 *nl = '\0';
7088 if (strcmp(line, "y") == 0) {
7089 *choice = GOT_PATCH_CHOICE_YES;
7090 printf("y\n");
7091 } else if (strcmp(line, "n") == 0) {
7092 *choice = GOT_PATCH_CHOICE_NO;
7093 printf("n\n");
7094 } else if (strcmp(line, "q") == 0 &&
7095 status == GOT_STATUS_MODIFY) {
7096 *choice = GOT_PATCH_CHOICE_QUIT;
7097 printf("q\n");
7098 } else
7099 printf("invalid response '%s'\n", line);
7100 free(line);
7101 return NULL;
7104 while (resp != 'y' && resp != 'n' && resp != 'q') {
7105 err = show_change(status, path, patch_file, n, nchanges,
7106 a->action);
7107 if (err)
7108 return err;
7109 resp = getchar();
7110 if (resp == '\n')
7111 resp = getchar();
7112 if (status == GOT_STATUS_MODIFY) {
7113 if (resp != 'y' && resp != 'n' && resp != 'q') {
7114 printf("invalid response '%c'\n", resp);
7115 resp = ' ';
7117 } else if (resp != 'y' && resp != 'n') {
7118 printf("invalid response '%c'\n", resp);
7119 resp = ' ';
7123 if (resp == 'y')
7124 *choice = GOT_PATCH_CHOICE_YES;
7125 else if (resp == 'n')
7126 *choice = GOT_PATCH_CHOICE_NO;
7127 else if (resp == 'q' && status == GOT_STATUS_MODIFY)
7128 *choice = GOT_PATCH_CHOICE_QUIT;
7130 return NULL;
7133 struct wt_commitable_path_arg {
7134 struct got_pathlist_head *commit_paths;
7135 int *has_changes;
7139 * Shortcut work tree status callback to determine if the set of paths scanned
7140 * has at least one versioned path that is being modified and, if not NULL, is
7141 * in the arg->commit_paths list. Set arg and return GOT_ERR_FILE_MODIFIED as
7142 * soon as a path is passed with a status that satisfies this criteria.
7144 static const struct got_error *
7145 worktree_has_commitable_path(void *arg, unsigned char status,
7146 unsigned char staged_status, const char *path,
7147 struct got_object_id *blob_id, struct got_object_id *staged_blob_id,
7148 struct got_object_id *commit_id, int dirfd, const char *de_name)
7150 struct wt_commitable_path_arg *a = arg;
7152 if (status == staged_status && (status == GOT_STATUS_DELETE))
7153 status = GOT_STATUS_NO_CHANGE;
7155 if (!(status == GOT_STATUS_NO_CHANGE ||
7156 status == GOT_STATUS_UNVERSIONED) ||
7157 staged_status != GOT_STATUS_NO_CHANGE) {
7158 if (a->commit_paths != NULL) {
7159 struct got_pathlist_entry *pe;
7161 TAILQ_FOREACH(pe, a->commit_paths, entry) {
7162 if (strncmp(path, pe->path,
7163 pe->path_len) == 0) {
7164 *a->has_changes = 1;
7165 break;
7168 } else
7169 *a->has_changes = 1;
7171 if (*a->has_changes)
7172 return got_error(GOT_ERR_FILE_MODIFIED);
7175 return NULL;
7179 * Check that the changeset of the commit identified by id is
7180 * comprised of at least one modified path that is being committed.
7182 static const struct got_error *
7183 commit_path_changed_in_worktree(struct wt_commitable_path_arg *wcpa,
7184 struct got_object_id *id, struct got_worktree *worktree,
7185 struct got_repository *repo)
7187 const struct got_error *err;
7188 struct got_pathlist_head paths;
7189 struct got_commit_object *commit = NULL, *pcommit = NULL;
7190 struct got_tree_object *tree = NULL, *ptree = NULL;
7191 struct got_object_qid *pid;
7193 TAILQ_INIT(&paths);
7195 err = got_object_open_as_commit(&commit, repo, id);
7196 if (err)
7197 goto done;
7199 err = got_object_open_as_tree(&tree, repo,
7200 got_object_commit_get_tree_id(commit));
7201 if (err)
7202 goto done;
7204 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
7205 if (pid != NULL) {
7206 err = got_object_open_as_commit(&pcommit, repo, &pid->id);
7207 if (err)
7208 goto done;
7210 err = got_object_open_as_tree(&ptree, repo,
7211 got_object_commit_get_tree_id(pcommit));
7212 if (err)
7213 goto done;
7216 err = got_diff_tree(ptree, tree, NULL, NULL, -1, -1, "", "", repo,
7217 got_diff_tree_collect_changed_paths, &paths, 0);
7218 if (err)
7219 goto done;
7221 err = got_worktree_status(worktree, &paths, repo, 0,
7222 worktree_has_commitable_path, wcpa, check_cancelled, NULL);
7223 if (err && err->code == GOT_ERR_FILE_MODIFIED) {
7225 * At least one changed path in the referenced commit is
7226 * modified in the work tree, that's all we need to know!
7228 err = NULL;
7231 done:
7232 got_pathlist_free(&paths, GOT_PATHLIST_FREE_ALL);
7233 if (commit)
7234 got_object_commit_close(commit);
7235 if (pcommit)
7236 got_object_commit_close(pcommit);
7237 if (tree)
7238 got_object_tree_close(tree);
7239 if (ptree)
7240 got_object_tree_close(ptree);
7241 return err;
7245 * Remove any "logmsg" reference comprised entirely of paths that have
7246 * been reverted in this work tree. If any path in the logmsg ref changeset
7247 * remains in a changed state in the worktree, do not remove the reference.
7249 static const struct got_error *
7250 rm_logmsg_ref(struct got_worktree *worktree, struct got_repository *repo)
7252 const struct got_error *err;
7253 struct got_reflist_head refs;
7254 struct got_reflist_entry *re;
7255 struct got_commit_object *commit = NULL;
7256 struct got_object_id *commit_id = NULL;
7257 struct wt_commitable_path_arg wcpa;
7258 char *uuidstr = NULL;
7260 TAILQ_INIT(&refs);
7262 err = got_worktree_get_uuid(&uuidstr, worktree);
7263 if (err)
7264 goto done;
7266 err = got_ref_list(&refs, repo, "refs/got/worktree",
7267 got_ref_cmp_by_name, repo);
7268 if (err)
7269 goto done;
7271 TAILQ_FOREACH(re, &refs, entry) {
7272 const char *refname;
7273 int has_changes = 0;
7275 refname = got_ref_get_name(re->ref);
7277 if (!strncmp(refname, GOT_WORKTREE_CHERRYPICK_REF_PREFIX,
7278 GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN))
7279 refname += GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN + 1;
7280 else if (!strncmp(refname, GOT_WORKTREE_BACKOUT_REF_PREFIX,
7281 GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN))
7282 refname += GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN + 1;
7283 else
7284 continue;
7286 if (strncmp(refname, uuidstr, GOT_WORKTREE_UUID_STRLEN) == 0)
7287 refname += GOT_WORKTREE_UUID_STRLEN + 1; /* skip '-' */
7288 else
7289 continue;
7291 err = got_repo_match_object_id(&commit_id, NULL, refname,
7292 GOT_OBJ_TYPE_COMMIT, NULL, repo);
7293 if (err)
7294 goto done;
7296 err = got_object_open_as_commit(&commit, repo, commit_id);
7297 if (err)
7298 goto done;
7300 wcpa.commit_paths = NULL;
7301 wcpa.has_changes = &has_changes;
7303 err = commit_path_changed_in_worktree(&wcpa, commit_id,
7304 worktree, repo);
7305 if (err)
7306 goto done;
7308 if (!has_changes) {
7309 err = got_ref_delete(re->ref, repo);
7310 if (err)
7311 goto done;
7314 got_object_commit_close(commit);
7315 commit = NULL;
7316 free(commit_id);
7317 commit_id = NULL;
7320 done:
7321 free(uuidstr);
7322 free(commit_id);
7323 got_ref_list_free(&refs);
7324 if (commit)
7325 got_object_commit_close(commit);
7326 return err;
7329 static const struct got_error *
7330 cmd_revert(int argc, char *argv[])
7332 const struct got_error *error = NULL;
7333 struct got_worktree *worktree = NULL;
7334 struct got_repository *repo = NULL;
7335 char *cwd = NULL, *path = NULL;
7336 struct got_pathlist_head paths;
7337 struct got_pathlist_entry *pe;
7338 int ch, can_recurse = 0, pflag = 0;
7339 FILE *patch_script_file = NULL;
7340 const char *patch_script_path = NULL;
7341 struct choose_patch_arg cpa;
7342 int *pack_fds = NULL;
7344 TAILQ_INIT(&paths);
7346 #ifndef PROFILE
7347 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
7348 "unveil", NULL) == -1)
7349 err(1, "pledge");
7350 #endif
7352 while ((ch = getopt(argc, argv, "F:pR")) != -1) {
7353 switch (ch) {
7354 case 'F':
7355 patch_script_path = optarg;
7356 break;
7357 case 'p':
7358 pflag = 1;
7359 break;
7360 case 'R':
7361 can_recurse = 1;
7362 break;
7363 default:
7364 usage_revert();
7365 /* NOTREACHED */
7369 argc -= optind;
7370 argv += optind;
7372 if (argc < 1)
7373 usage_revert();
7374 if (patch_script_path && !pflag)
7375 errx(1, "-F option can only be used together with -p option");
7377 cwd = getcwd(NULL, 0);
7378 if (cwd == NULL) {
7379 error = got_error_from_errno("getcwd");
7380 goto done;
7383 error = got_repo_pack_fds_open(&pack_fds);
7384 if (error != NULL)
7385 goto done;
7387 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_CVG_DIR);
7388 if (error) {
7389 if (error->code == GOT_ERR_NOT_WORKTREE)
7390 error = wrap_not_worktree_error(error, "revert", cwd);
7391 goto done;
7394 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
7395 NULL, pack_fds);
7396 if (error != NULL)
7397 goto done;
7399 if (patch_script_path) {
7400 patch_script_file = fopen(patch_script_path, "re");
7401 if (patch_script_file == NULL) {
7402 error = got_error_from_errno2("fopen",
7403 patch_script_path);
7404 goto done;
7409 * XXX "c" perm needed on repo dir to delete merge references.
7411 error = apply_unveil(got_repo_get_path(repo), 0,
7412 got_worktree_get_root_path(worktree));
7413 if (error)
7414 goto done;
7416 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
7417 if (error)
7418 goto done;
7420 if (!can_recurse) {
7421 char *ondisk_path;
7422 struct stat sb;
7423 TAILQ_FOREACH(pe, &paths, entry) {
7424 if (asprintf(&ondisk_path, "%s/%s",
7425 got_worktree_get_root_path(worktree),
7426 pe->path) == -1) {
7427 error = got_error_from_errno("asprintf");
7428 goto done;
7430 if (lstat(ondisk_path, &sb) == -1) {
7431 if (errno == ENOENT) {
7432 free(ondisk_path);
7433 continue;
7435 error = got_error_from_errno2("lstat",
7436 ondisk_path);
7437 free(ondisk_path);
7438 goto done;
7440 free(ondisk_path);
7441 if (S_ISDIR(sb.st_mode)) {
7442 error = got_error_msg(GOT_ERR_BAD_PATH,
7443 "reverting directories requires -R option");
7444 goto done;
7449 cpa.patch_script_file = patch_script_file;
7450 cpa.action = "revert";
7451 error = got_worktree_revert(worktree, &paths, revert_progress, NULL,
7452 pflag ? choose_patch : NULL, &cpa, repo);
7454 error = rm_logmsg_ref(worktree, repo);
7455 done:
7456 if (patch_script_file && fclose(patch_script_file) == EOF &&
7457 error == NULL)
7458 error = got_error_from_errno2("fclose", patch_script_path);
7459 if (repo) {
7460 const struct got_error *close_err = got_repo_close(repo);
7461 if (error == NULL)
7462 error = close_err;
7464 if (worktree)
7465 got_worktree_close(worktree);
7466 if (pack_fds) {
7467 const struct got_error *pack_err =
7468 got_repo_pack_fds_close(pack_fds);
7469 if (error == NULL)
7470 error = pack_err;
7472 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
7473 free(path);
7474 free(cwd);
7475 return error;
7478 __dead static void
7479 usage_commit(void)
7481 fprintf(stderr, "usage: %s commit [-CNnS] [-A author] [-F path] "
7482 "[-m message] [path ...]\n", getprogname());
7483 exit(1);
7486 struct collect_commit_logmsg_arg {
7487 const char *cmdline_log;
7488 const char *prepared_log;
7489 const char *merged_log;
7490 int non_interactive;
7491 const char *editor;
7492 const char *worktree_path;
7493 const char *repo_path;
7494 const char *dial_proto;
7495 char *logmsg_path;
7498 static const struct got_error *
7499 read_prepared_logmsg(char **logmsg, const char *path)
7501 const struct got_error *err = NULL;
7502 FILE *f = NULL;
7503 struct stat sb;
7504 size_t r;
7506 *logmsg = NULL;
7507 memset(&sb, 0, sizeof(sb));
7509 f = fopen(path, "re");
7510 if (f == NULL)
7511 return got_error_from_errno2("fopen", path);
7513 if (fstat(fileno(f), &sb) == -1) {
7514 err = got_error_from_errno2("fstat", path);
7515 goto done;
7517 if (sb.st_size == 0) {
7518 err = got_error(GOT_ERR_COMMIT_MSG_EMPTY);
7519 goto done;
7522 *logmsg = malloc(sb.st_size + 1);
7523 if (*logmsg == NULL) {
7524 err = got_error_from_errno("malloc");
7525 goto done;
7528 r = fread(*logmsg, 1, sb.st_size, f);
7529 if (r != sb.st_size) {
7530 if (ferror(f))
7531 err = got_error_from_errno2("fread", path);
7532 else
7533 err = got_error(GOT_ERR_IO);
7534 goto done;
7536 (*logmsg)[sb.st_size] = '\0';
7537 done:
7538 if (fclose(f) == EOF && err == NULL)
7539 err = got_error_from_errno2("fclose", path);
7540 if (err) {
7541 free(*logmsg);
7542 *logmsg = NULL;
7544 return err;
7547 static const struct got_error *
7548 collect_commit_logmsg(struct got_pathlist_head *commitable_paths,
7549 const char *diff_path, char **logmsg, void *arg)
7551 char *initial_content = NULL;
7552 struct got_pathlist_entry *pe;
7553 const struct got_error *err = NULL;
7554 char *template = NULL;
7555 char *prepared_msg = NULL, *merged_msg = NULL;
7556 struct collect_commit_logmsg_arg *a = arg;
7557 int initial_content_len;
7558 int fd = -1;
7559 size_t len;
7561 /* if a message was specified on the command line, just use it */
7562 if (a->cmdline_log != NULL && *a->cmdline_log != '\0') {
7563 len = strlen(a->cmdline_log) + 1;
7564 *logmsg = malloc(len + 1);
7565 if (*logmsg == NULL)
7566 return got_error_from_errno("malloc");
7567 strlcpy(*logmsg, a->cmdline_log, len);
7568 return NULL;
7569 } else if (a->prepared_log != NULL && a->non_interactive)
7570 return read_prepared_logmsg(logmsg, a->prepared_log);
7572 if (asprintf(&template, "%s/logmsg", a->worktree_path) == -1)
7573 return got_error_from_errno("asprintf");
7575 err = got_opentemp_named_fd(&a->logmsg_path, &fd, template, "");
7576 if (err)
7577 goto done;
7579 if (a->prepared_log) {
7580 err = read_prepared_logmsg(&prepared_msg, a->prepared_log);
7581 if (err)
7582 goto done;
7583 } else if (a->merged_log) {
7584 err = read_prepared_logmsg(&merged_msg, a->merged_log);
7585 if (err)
7586 goto done;
7589 initial_content_len = asprintf(&initial_content,
7590 "%s%s\n# changes to be committed:\n",
7591 prepared_msg ? prepared_msg : "",
7592 merged_msg ? merged_msg : "");
7593 if (initial_content_len == -1) {
7594 err = got_error_from_errno("asprintf");
7595 goto done;
7598 if (write(fd, initial_content, initial_content_len) == -1) {
7599 err = got_error_from_errno2("write", a->logmsg_path);
7600 goto done;
7603 TAILQ_FOREACH(pe, commitable_paths, entry) {
7604 struct got_commitable *ct = pe->data;
7605 dprintf(fd, "# %c %s\n",
7606 got_commitable_get_status(ct),
7607 got_commitable_get_path(ct));
7610 if (diff_path) {
7611 dprintf(fd, "# detailed changes can be viewed in %s\n",
7612 diff_path);
7615 if (close(fd) == -1) {
7616 err = got_error_from_errno2("close", a->logmsg_path);
7617 goto done;
7619 fd = -1;
7621 err = edit_logmsg(logmsg, a->editor, a->logmsg_path, initial_content,
7622 initial_content_len, a->prepared_log ? 0 : 1);
7623 done:
7624 free(initial_content);
7625 free(template);
7626 free(prepared_msg);
7627 free(merged_msg);
7629 if (fd != -1 && close(fd) == -1 && err == NULL)
7630 err = got_error_from_errno2("close", a->logmsg_path);
7632 /* Editor is done; we can now apply unveil(2) */
7633 if (err == NULL)
7634 err = got_dial_apply_unveil(a->dial_proto);
7635 if (err == NULL)
7636 err = apply_unveil(a->repo_path, 0, a->worktree_path);
7637 if (err) {
7638 free(*logmsg);
7639 *logmsg = NULL;
7641 return err;
7644 static const struct got_error *
7645 cat_logmsg(FILE *f, struct got_commit_object *commit, const char *idstr,
7646 const char *type, int has_content)
7648 const struct got_error *err = NULL;
7649 char *logmsg = NULL;
7651 err = got_object_commit_get_logmsg(&logmsg, commit);
7652 if (err)
7653 return err;
7655 if (fprintf(f, "%s# log message of %s commit %s:%s",
7656 has_content ? "\n" : "", type, idstr, logmsg) < 0)
7657 err = got_ferror(f, GOT_ERR_IO);
7659 free(logmsg);
7660 return err;
7664 * Lookup "logmsg" references of backed-out and cherrypicked commits
7665 * belonging to the current work tree. If found, and the worktree has
7666 * at least one modified file that was changed in the referenced commit,
7667 * add its log message to a new temporary file at *logmsg_path.
7668 * Add all refs found to matched_refs to be scheduled for removal on
7669 * successful commit.
7671 static const struct got_error *
7672 lookup_logmsg_ref(char **logmsg_path, struct got_pathlist_head *paths,
7673 struct got_reflist_head *matched_refs, struct got_worktree *worktree,
7674 struct got_repository *repo)
7676 const struct got_error *err;
7677 struct got_commit_object *commit = NULL;
7678 struct got_object_id *id = NULL;
7679 struct got_reflist_head refs;
7680 struct got_reflist_entry *re, *re_match;
7681 FILE *f = NULL;
7682 char *uuidstr = NULL;
7683 int added_logmsg = 0;
7685 TAILQ_INIT(&refs);
7687 *logmsg_path = NULL;
7689 err = got_worktree_get_uuid(&uuidstr, worktree);
7690 if (err)
7691 goto done;
7693 err = got_ref_list(&refs, repo, "refs/got/worktree",
7694 got_ref_cmp_by_name, repo);
7695 if (err)
7696 goto done;
7698 TAILQ_FOREACH(re, &refs, entry) {
7699 const char *refname, *type;
7700 struct wt_commitable_path_arg wcpa;
7701 int add_logmsg = 0;
7703 refname = got_ref_get_name(re->ref);
7705 if (strncmp(refname, GOT_WORKTREE_CHERRYPICK_REF_PREFIX,
7706 GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN) == 0) {
7707 refname += GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN + 1;
7708 type = "cherrypicked";
7709 } else if (strncmp(refname, GOT_WORKTREE_BACKOUT_REF_PREFIX,
7710 GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN) == 0) {
7711 refname += GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN + 1;
7712 type = "backed-out";
7713 } else
7714 continue;
7716 if (strncmp(refname, uuidstr, GOT_WORKTREE_UUID_STRLEN) == 0)
7717 refname += GOT_WORKTREE_UUID_STRLEN + 1; /* skip '-' */
7718 else
7719 continue;
7721 err = got_repo_match_object_id(&id, NULL, refname,
7722 GOT_OBJ_TYPE_COMMIT, NULL, repo);
7723 if (err)
7724 goto done;
7726 err = got_object_open_as_commit(&commit, repo, id);
7727 if (err)
7728 goto done;
7730 wcpa.commit_paths = paths;
7731 wcpa.has_changes = &add_logmsg;
7733 err = commit_path_changed_in_worktree(&wcpa, id,
7734 worktree, repo);
7735 if (err)
7736 goto done;
7738 if (add_logmsg) {
7739 if (f == NULL) {
7740 err = got_opentemp_named(logmsg_path, &f,
7741 "got-commit-logmsg", "");
7742 if (err)
7743 goto done;
7745 err = cat_logmsg(f, commit, refname, type,
7746 added_logmsg);
7747 if (err)
7748 goto done;
7749 if (!added_logmsg)
7750 ++added_logmsg;
7752 err = got_reflist_entry_dup(&re_match, re);
7753 if (err)
7754 goto done;
7755 TAILQ_INSERT_HEAD(matched_refs, re_match, entry);
7758 got_object_commit_close(commit);
7759 commit = NULL;
7760 free(id);
7761 id = NULL;
7764 done:
7765 free(id);
7766 free(uuidstr);
7767 got_ref_list_free(&refs);
7768 if (commit)
7769 got_object_commit_close(commit);
7770 if (f && fclose(f) == EOF && err == NULL)
7771 err = got_error_from_errno("fclose");
7772 if (!added_logmsg) {
7773 if (*logmsg_path && unlink(*logmsg_path) != 0 && err == NULL)
7774 err = got_error_from_errno2("unlink", *logmsg_path);
7775 *logmsg_path = NULL;
7777 return err;
7780 static const struct got_error *
7781 cmd_commit(int argc, char *argv[])
7783 const struct got_error *error = NULL;
7784 struct got_worktree *worktree = NULL;
7785 struct got_repository *repo = NULL;
7786 char *cwd = NULL, *id_str = NULL;
7787 struct got_object_id *id = NULL;
7788 const char *logmsg = NULL;
7789 char *prepared_logmsg = NULL, *merged_logmsg = NULL;
7790 struct collect_commit_logmsg_arg cl_arg;
7791 const char *author = NULL;
7792 char *gitconfig_path = NULL, *editor = NULL, *committer = NULL;
7793 int ch, rebase_in_progress, histedit_in_progress, preserve_logmsg = 0;
7794 int allow_bad_symlinks = 0, non_interactive = 0, merge_in_progress = 0;
7795 int show_diff = 1, commit_conflicts = 0;
7796 struct got_pathlist_head paths;
7797 struct got_reflist_head refs;
7798 struct got_reflist_entry *re;
7799 int *pack_fds = NULL;
7800 const struct got_gotconfig *repo_conf = NULL, *worktree_conf = NULL;
7801 const struct got_remote_repo *remotes, *remote = NULL;
7802 int nremotes;
7803 char *proto = NULL, *host = NULL, *port = NULL;
7804 char *repo_name = NULL, *server_path = NULL;
7805 const char *remote_name;
7806 int verbosity = 0;
7807 int i;
7809 TAILQ_INIT(&refs);
7810 TAILQ_INIT(&paths);
7811 cl_arg.logmsg_path = NULL;
7813 #ifndef PROFILE
7814 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
7815 "unveil", NULL) == -1)
7816 err(1, "pledge");
7817 #endif
7819 while ((ch = getopt(argc, argv, "A:CF:m:NnS")) != -1) {
7820 switch (ch) {
7821 case 'A':
7822 author = optarg;
7823 error = valid_author(author);
7824 if (error)
7825 return error;
7826 break;
7827 case 'C':
7828 commit_conflicts = 1;
7829 break;
7830 case 'F':
7831 if (logmsg != NULL)
7832 option_conflict('F', 'm');
7833 prepared_logmsg = realpath(optarg, NULL);
7834 if (prepared_logmsg == NULL)
7835 return got_error_from_errno2("realpath",
7836 optarg);
7837 break;
7838 case 'm':
7839 if (prepared_logmsg)
7840 option_conflict('m', 'F');
7841 logmsg = optarg;
7842 break;
7843 case 'N':
7844 non_interactive = 1;
7845 break;
7846 case 'n':
7847 show_diff = 0;
7848 break;
7849 case 'S':
7850 allow_bad_symlinks = 1;
7851 break;
7852 default:
7853 usage_commit();
7854 /* NOTREACHED */
7858 argc -= optind;
7859 argv += optind;
7861 cwd = getcwd(NULL, 0);
7862 if (cwd == NULL) {
7863 error = got_error_from_errno("getcwd");
7864 goto done;
7867 error = got_repo_pack_fds_open(&pack_fds);
7868 if (error != NULL)
7869 goto done;
7871 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_CVG_DIR);
7872 if (error) {
7873 if (error->code == GOT_ERR_NOT_WORKTREE)
7874 error = wrap_not_worktree_error(error, "commit", cwd);
7875 goto done;
7878 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
7879 if (error)
7880 goto done;
7881 if (rebase_in_progress) {
7882 error = got_error(GOT_ERR_REBASING);
7883 goto done;
7886 error = got_worktree_histedit_in_progress(&histedit_in_progress,
7887 worktree);
7888 if (error)
7889 goto done;
7891 error = get_gitconfig_path(&gitconfig_path);
7892 if (error)
7893 goto done;
7894 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
7895 gitconfig_path, pack_fds);
7896 if (error != NULL)
7897 goto done;
7899 error = got_worktree_merge_in_progress(&merge_in_progress, worktree, repo);
7900 if (error)
7901 goto done;
7902 if (merge_in_progress) {
7903 error = got_error(GOT_ERR_MERGE_BUSY);
7904 goto done;
7907 error = get_author(&committer, repo, worktree);
7908 if (error)
7909 goto done;
7911 if (author == NULL)
7912 author = committer;
7914 remote_name = GOT_SEND_DEFAULT_REMOTE_NAME;
7915 worktree_conf = got_worktree_get_gotconfig(worktree);
7916 if (worktree_conf) {
7917 got_gotconfig_get_remotes(&nremotes, &remotes,
7918 worktree_conf);
7919 for (i = 0; i < nremotes; i++) {
7920 if (strcmp(remotes[i].name, remote_name) == 0) {
7921 remote = &remotes[i];
7922 break;
7926 if (remote == NULL) {
7927 repo_conf = got_repo_get_gotconfig(repo);
7928 if (repo_conf) {
7929 got_gotconfig_get_remotes(&nremotes, &remotes,
7930 repo_conf);
7931 for (i = 0; i < nremotes; i++) {
7932 if (strcmp(remotes[i].name, remote_name) == 0) {
7933 remote = &remotes[i];
7934 break;
7939 if (remote == NULL) {
7940 got_repo_get_gitconfig_remotes(&nremotes, &remotes, repo);
7941 for (i = 0; i < nremotes; i++) {
7942 if (strcmp(remotes[i].name, remote_name) == 0) {
7943 remote = &remotes[i];
7944 break;
7948 if (remote == NULL) {
7949 error = got_error_path(remote_name, GOT_ERR_NO_REMOTE);
7950 goto done;
7953 error = got_dial_parse_uri(&proto, &host, &port, &server_path,
7954 &repo_name, remote->fetch_url);
7955 if (error)
7956 goto done;
7958 if (strcmp(proto, "git") == 0) {
7959 #ifndef PROFILE
7960 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
7961 "sendfd dns inet unveil", NULL) == -1)
7962 err(1, "pledge");
7963 #endif
7964 } else if (strcmp(proto, "git+ssh") == 0 ||
7965 strcmp(proto, "ssh") == 0) {
7966 #ifndef PROFILE
7967 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
7968 "sendfd unveil", NULL) == -1)
7969 err(1, "pledge");
7970 #endif
7971 } else if (strcmp(proto, "http") == 0 ||
7972 strcmp(proto, "git+http") == 0) {
7973 error = got_error_path(proto, GOT_ERR_NOT_IMPL);
7974 goto done;
7975 } else {
7976 error = got_error_path(proto, GOT_ERR_BAD_PROTO);
7977 goto done;
7981 /*if (verbosity >= 0) {
7982 printf("Connecting to \"%s\" %s://%s%s%s%s%s\n",
7983 remote->name, proto, host,
7984 port ? ":" : "", port ? port : "",
7985 *server_path == '/' ? "" : "/", server_path);
7986 }*/
7989 * unveil(2) traverses exec(2); if an editor is used we have
7990 * to apply unveil after the log message has been written during
7991 * the callback.
7993 if (logmsg == NULL || strlen(logmsg) == 0)
7994 error = get_editor(&editor);
7995 else {
7996 error = got_dial_apply_unveil(proto);
7997 if (error)
7998 goto done;
7999 error = apply_unveil(got_repo_get_path(repo), 0,
8000 got_worktree_get_root_path(worktree));
8002 if (error)
8003 goto done;
8005 if (prepared_logmsg == NULL) {
8006 error = lookup_logmsg_ref(&merged_logmsg,
8007 argc > 0 ? &paths : NULL, &refs, worktree, repo);
8008 if (error)
8009 goto done;
8012 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
8013 if (error)
8014 goto done;
8016 cl_arg.editor = editor;
8017 cl_arg.cmdline_log = logmsg;
8018 cl_arg.prepared_log = prepared_logmsg;
8019 cl_arg.merged_log = merged_logmsg;
8020 cl_arg.non_interactive = non_interactive;
8021 cl_arg.worktree_path = got_worktree_get_root_path(worktree);
8022 cl_arg.repo_path = got_repo_get_path(repo);
8023 cl_arg.dial_proto = proto;
8024 error = got_worktree_cvg_commit(&id, worktree, &paths, author,
8025 committer, allow_bad_symlinks, show_diff, commit_conflicts,
8026 collect_commit_logmsg, &cl_arg, print_status, NULL, proto, host,
8027 port, server_path, verbosity, remote, check_cancelled, repo);
8028 if (error) {
8029 if (error->code != GOT_ERR_COMMIT_MSG_EMPTY &&
8030 cl_arg.logmsg_path != NULL)
8031 preserve_logmsg = 1;
8032 goto done;
8035 error = got_object_id_str(&id_str, id);
8036 if (error)
8037 goto done;
8038 printf("Created commit %s\n", id_str);
8040 TAILQ_FOREACH(re, &refs, entry) {
8041 error = got_ref_delete(re->ref, repo);
8042 if (error)
8043 goto done;
8046 done:
8047 if (preserve_logmsg) {
8048 fprintf(stderr, "%s: log message preserved in %s\n",
8049 getprogname(), cl_arg.logmsg_path);
8050 } else if (cl_arg.logmsg_path && unlink(cl_arg.logmsg_path) == -1 &&
8051 error == NULL)
8052 error = got_error_from_errno2("unlink", cl_arg.logmsg_path);
8053 free(cl_arg.logmsg_path);
8054 if (merged_logmsg && unlink(merged_logmsg) == -1 && error == NULL)
8055 error = got_error_from_errno2("unlink", merged_logmsg);
8056 free(merged_logmsg);
8057 if (repo) {
8058 const struct got_error *close_err = got_repo_close(repo);
8059 if (error == NULL)
8060 error = close_err;
8062 if (worktree)
8063 got_worktree_close(worktree);
8064 if (pack_fds) {
8065 const struct got_error *pack_err =
8066 got_repo_pack_fds_close(pack_fds);
8067 if (error == NULL)
8068 error = pack_err;
8070 got_ref_list_free(&refs);
8071 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
8072 free(cwd);
8073 free(id_str);
8074 free(gitconfig_path);
8075 free(editor);
8076 free(committer);
8077 free(prepared_logmsg);
8078 return error;
8082 * Print and if delete is set delete all ref_prefix references.
8083 * If wanted_ref is not NULL, only print or delete this reference.
8085 static const struct got_error *
8086 process_logmsg_refs(const char *ref_prefix, size_t prefix_len,
8087 const char *wanted_ref, int delete, struct got_worktree *worktree,
8088 struct got_repository *repo)
8090 const struct got_error *err;
8091 struct got_pathlist_head paths;
8092 struct got_reflist_head refs;
8093 struct got_reflist_entry *re;
8094 struct got_reflist_object_id_map *refs_idmap = NULL;
8095 struct got_commit_object *commit = NULL;
8096 struct got_object_id *id = NULL;
8097 const char *header_prefix;
8098 char *uuidstr = NULL;
8099 int found = 0;
8101 TAILQ_INIT(&refs);
8102 TAILQ_INIT(&paths);
8104 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, repo);
8105 if (err)
8106 goto done;
8108 err = got_reflist_object_id_map_create(&refs_idmap, &refs, repo);
8109 if (err)
8110 goto done;
8112 if (worktree != NULL) {
8113 err = got_worktree_get_uuid(&uuidstr, worktree);
8114 if (err)
8115 goto done;
8118 if (wanted_ref) {
8119 if (strncmp(wanted_ref, "refs/heads/", 11) == 0)
8120 wanted_ref += 11;
8123 if (strcmp(ref_prefix, GOT_WORKTREE_BACKOUT_REF_PREFIX) == 0)
8124 header_prefix = "backout";
8125 else
8126 header_prefix = "cherrypick";
8128 TAILQ_FOREACH(re, &refs, entry) {
8129 const char *refname, *wt;
8131 refname = got_ref_get_name(re->ref);
8133 err = check_cancelled(NULL);
8134 if (err)
8135 goto done;
8137 if (strncmp(refname, ref_prefix, prefix_len) == 0)
8138 refname += prefix_len + 1; /* skip '-' delimiter */
8139 else
8140 continue;
8142 wt = refname;
8144 if (worktree == NULL || strncmp(refname, uuidstr,
8145 GOT_WORKTREE_UUID_STRLEN) == 0)
8146 refname += GOT_WORKTREE_UUID_STRLEN + 1; /* skip '-' */
8147 else
8148 continue;
8150 err = got_repo_match_object_id(&id, NULL, refname,
8151 GOT_OBJ_TYPE_COMMIT, NULL, repo);
8152 if (err)
8153 goto done;
8155 err = got_object_open_as_commit(&commit, repo, id);
8156 if (err)
8157 goto done;
8159 if (wanted_ref)
8160 found = strncmp(wanted_ref, refname,
8161 strlen(wanted_ref)) == 0;
8162 if (wanted_ref && !found) {
8163 struct got_reflist_head *ci_refs;
8165 ci_refs = got_reflist_object_id_map_lookup(refs_idmap,
8166 id);
8168 if (ci_refs) {
8169 char *refs_str = NULL;
8170 char const *r = NULL;
8172 err = build_refs_str(&refs_str, ci_refs, id,
8173 repo, 1);
8174 if (err)
8175 goto done;
8177 r = refs_str;
8178 while (r) {
8179 if (strncmp(r, wanted_ref,
8180 strlen(wanted_ref)) == 0) {
8181 found = 1;
8182 break;
8184 r = strchr(r, ' ');
8185 if (r)
8186 ++r;
8188 free(refs_str);
8192 if (wanted_ref == NULL || found) {
8193 if (delete) {
8194 err = got_ref_delete(re->ref, repo);
8195 if (err)
8196 goto done;
8197 printf("Deleted: ");
8198 err = print_commit_oneline(commit, id, repo,
8199 refs_idmap);
8200 } else {
8202 * Print paths modified by commit to help
8203 * associate commits with worktree changes.
8205 err = get_changed_paths(&paths, commit,
8206 repo, NULL);
8207 if (err)
8208 goto done;
8210 err = print_commit(commit, id, repo, NULL,
8211 &paths, NULL, 0, 0, refs_idmap, NULL,
8212 header_prefix);
8213 got_pathlist_free(&paths,
8214 GOT_PATHLIST_FREE_ALL);
8216 if (worktree == NULL)
8217 printf("work tree: %.*s\n\n",
8218 GOT_WORKTREE_UUID_STRLEN, wt);
8220 if (err || found)
8221 goto done;
8224 got_object_commit_close(commit);
8225 commit = NULL;
8226 free(id);
8227 id = NULL;
8230 if (wanted_ref != NULL && !found)
8231 err = got_error_fmt(GOT_ERR_NOT_REF, "%s", wanted_ref);
8233 done:
8234 free(id);
8235 free(uuidstr);
8236 got_ref_list_free(&refs);
8237 got_pathlist_free(&paths, GOT_PATHLIST_FREE_ALL);
8238 if (refs_idmap)
8239 got_reflist_object_id_map_free(refs_idmap);
8240 if (commit)
8241 got_object_commit_close(commit);
8242 return err;
8246 * Create new temp "logmsg" ref of the backed-out or cherrypicked commit
8247 * identified by id for log messages to prepopulate the editor on commit.
8249 static const struct got_error *
8250 logmsg_ref(struct got_object_id *id, const char *prefix,
8251 struct got_worktree *worktree, struct got_repository *repo)
8253 const struct got_error *err = NULL;
8254 char *idstr, *ref = NULL, *refname = NULL;
8255 int histedit_in_progress;
8256 int rebase_in_progress, merge_in_progress;
8259 * Silenty refuse to create merge reference if any histedit, merge,
8260 * or rebase operation is in progress.
8262 err = got_worktree_histedit_in_progress(&histedit_in_progress,
8263 worktree);
8264 if (err)
8265 return err;
8266 if (histedit_in_progress)
8267 return NULL;
8269 err = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
8270 if (err)
8271 return err;
8272 if (rebase_in_progress)
8273 return NULL;
8275 err = got_worktree_merge_in_progress(&merge_in_progress, worktree,
8276 repo);
8277 if (err)
8278 return err;
8279 if (merge_in_progress)
8280 return NULL;
8282 err = got_object_id_str(&idstr, id);
8283 if (err)
8284 return err;
8286 err = got_worktree_get_logmsg_ref_name(&refname, worktree, prefix);
8287 if (err)
8288 goto done;
8290 if (asprintf(&ref, "%s-%s", refname, idstr) == -1) {
8291 err = got_error_from_errno("asprintf");
8292 goto done;
8295 err = create_ref(ref, got_worktree_get_base_commit_id(worktree),
8296 -1, repo);
8297 done:
8298 free(ref);
8299 free(idstr);
8300 free(refname);
8301 return err;
8304 __dead static void
8305 usage_cherrypick(void)
8307 fprintf(stderr, "usage: %s cherrypick [-lX] [commit-id]\n",
8308 getprogname());
8309 exit(1);
8312 static const struct got_error *
8313 cmd_cherrypick(int argc, char *argv[])
8315 const struct got_error *error = NULL;
8316 struct got_worktree *worktree = NULL;
8317 struct got_repository *repo = NULL;
8318 char *cwd = NULL, *commit_id_str = NULL;
8319 struct got_object_id *commit_id = NULL;
8320 struct got_commit_object *commit = NULL;
8321 struct got_object_qid *pid;
8322 int ch, list_refs = 0, remove_refs = 0;
8323 struct got_update_progress_arg upa;
8324 int *pack_fds = NULL;
8326 #ifndef PROFILE
8327 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
8328 "unveil", NULL) == -1)
8329 err(1, "pledge");
8330 #endif
8332 while ((ch = getopt(argc, argv, "lX")) != -1) {
8333 switch (ch) {
8334 case 'l':
8335 list_refs = 1;
8336 break;
8337 case 'X':
8338 remove_refs = 1;
8339 break;
8340 default:
8341 usage_cherrypick();
8342 /* NOTREACHED */
8346 argc -= optind;
8347 argv += optind;
8349 if (list_refs || remove_refs) {
8350 if (argc != 0 && argc != 1)
8351 usage_cherrypick();
8352 } else if (argc != 1)
8353 usage_cherrypick();
8354 if (list_refs && remove_refs)
8355 option_conflict('l', 'X');
8357 cwd = getcwd(NULL, 0);
8358 if (cwd == NULL) {
8359 error = got_error_from_errno("getcwd");
8360 goto done;
8363 error = got_repo_pack_fds_open(&pack_fds);
8364 if (error != NULL)
8365 goto done;
8367 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_CVG_DIR);
8368 if (error) {
8369 if (list_refs || remove_refs) {
8370 if (error->code != GOT_ERR_NOT_WORKTREE)
8371 goto done;
8372 } else {
8373 if (error->code == GOT_ERR_NOT_WORKTREE)
8374 error = wrap_not_worktree_error(error,
8375 "cherrypick", cwd);
8376 goto done;
8380 error = got_repo_open(&repo,
8381 worktree ? got_worktree_get_repo_path(worktree) : cwd,
8382 NULL, pack_fds);
8383 if (error != NULL)
8384 goto done;
8386 error = apply_unveil(got_repo_get_path(repo), 0,
8387 worktree ? got_worktree_get_root_path(worktree) : NULL);
8388 if (error)
8389 goto done;
8391 if (list_refs || remove_refs) {
8392 error = process_logmsg_refs(GOT_WORKTREE_CHERRYPICK_REF_PREFIX,
8393 GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN,
8394 argc == 1 ? argv[0] : NULL, remove_refs, worktree, repo);
8395 goto done;
8398 error = got_repo_match_object_id(&commit_id, NULL, argv[0],
8399 GOT_OBJ_TYPE_COMMIT, NULL, repo);
8400 if (error)
8401 goto done;
8402 error = got_object_id_str(&commit_id_str, commit_id);
8403 if (error)
8404 goto done;
8406 error = got_object_open_as_commit(&commit, repo, commit_id);
8407 if (error)
8408 goto done;
8409 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
8410 memset(&upa, 0, sizeof(upa));
8411 error = got_worktree_merge_files(worktree, pid ? &pid->id : NULL,
8412 commit_id, repo, update_progress, &upa, check_cancelled,
8413 NULL);
8414 if (error != NULL)
8415 goto done;
8417 if (upa.did_something) {
8418 error = logmsg_ref(commit_id,
8419 GOT_WORKTREE_CHERRYPICK_REF_PREFIX, worktree, repo);
8420 if (error)
8421 goto done;
8422 printf("Merged commit %s\n", commit_id_str);
8424 print_merge_progress_stats(&upa);
8425 done:
8426 free(cwd);
8427 if (commit)
8428 got_object_commit_close(commit);
8429 free(commit_id_str);
8430 if (worktree)
8431 got_worktree_close(worktree);
8432 if (repo) {
8433 const struct got_error *close_err = got_repo_close(repo);
8434 if (error == NULL)
8435 error = close_err;
8437 if (pack_fds) {
8438 const struct got_error *pack_err =
8439 got_repo_pack_fds_close(pack_fds);
8440 if (error == NULL)
8441 error = pack_err;
8444 return error;
8447 __dead static void
8448 usage_backout(void)
8450 fprintf(stderr, "usage: %s backout [-lX] [commit-id]\n", getprogname());
8451 exit(1);
8454 static const struct got_error *
8455 cmd_backout(int argc, char *argv[])
8457 const struct got_error *error = NULL;
8458 struct got_worktree *worktree = NULL;
8459 struct got_repository *repo = NULL;
8460 char *cwd = NULL, *commit_id_str = NULL;
8461 struct got_object_id *commit_id = NULL;
8462 struct got_commit_object *commit = NULL;
8463 struct got_object_qid *pid;
8464 int ch, list_refs = 0, remove_refs = 0;
8465 struct got_update_progress_arg upa;
8466 int *pack_fds = NULL;
8468 #ifndef PROFILE
8469 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
8470 "unveil", NULL) == -1)
8471 err(1, "pledge");
8472 #endif
8474 while ((ch = getopt(argc, argv, "lX")) != -1) {
8475 switch (ch) {
8476 case 'l':
8477 list_refs = 1;
8478 break;
8479 case 'X':
8480 remove_refs = 1;
8481 break;
8482 default:
8483 usage_backout();
8484 /* NOTREACHED */
8488 argc -= optind;
8489 argv += optind;
8491 if (list_refs || remove_refs) {
8492 if (argc != 0 && argc != 1)
8493 usage_backout();
8494 } else if (argc != 1)
8495 usage_backout();
8496 if (list_refs && remove_refs)
8497 option_conflict('l', 'X');
8499 cwd = getcwd(NULL, 0);
8500 if (cwd == NULL) {
8501 error = got_error_from_errno("getcwd");
8502 goto done;
8505 error = got_repo_pack_fds_open(&pack_fds);
8506 if (error != NULL)
8507 goto done;
8509 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_CVG_DIR);
8510 if (error) {
8511 if (list_refs || remove_refs) {
8512 if (error->code != GOT_ERR_NOT_WORKTREE)
8513 goto done;
8514 } else {
8515 if (error->code == GOT_ERR_NOT_WORKTREE)
8516 error = wrap_not_worktree_error(error,
8517 "backout", cwd);
8518 goto done;
8522 error = got_repo_open(&repo,
8523 worktree ? got_worktree_get_repo_path(worktree) : cwd,
8524 NULL, pack_fds);
8525 if (error != NULL)
8526 goto done;
8528 error = apply_unveil(got_repo_get_path(repo), 0,
8529 worktree ? got_worktree_get_root_path(worktree) : NULL);
8530 if (error)
8531 goto done;
8533 if (list_refs || remove_refs) {
8534 error = process_logmsg_refs(GOT_WORKTREE_BACKOUT_REF_PREFIX,
8535 GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN,
8536 argc == 1 ? argv[0] : NULL, remove_refs, worktree, repo);
8537 goto done;
8540 error = got_repo_match_object_id(&commit_id, NULL, argv[0],
8541 GOT_OBJ_TYPE_COMMIT, NULL, repo);
8542 if (error)
8543 goto done;
8544 error = got_object_id_str(&commit_id_str, commit_id);
8545 if (error)
8546 goto done;
8548 error = got_object_open_as_commit(&commit, repo, commit_id);
8549 if (error)
8550 goto done;
8551 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
8552 if (pid == NULL) {
8553 error = got_error(GOT_ERR_ROOT_COMMIT);
8554 goto done;
8557 memset(&upa, 0, sizeof(upa));
8558 error = got_worktree_merge_files(worktree, commit_id, &pid->id,
8559 repo, update_progress, &upa, check_cancelled, NULL);
8560 if (error != NULL)
8561 goto done;
8563 if (upa.did_something) {
8564 error = logmsg_ref(commit_id, GOT_WORKTREE_BACKOUT_REF_PREFIX,
8565 worktree, repo);
8566 if (error)
8567 goto done;
8568 printf("Backed out commit %s\n", commit_id_str);
8570 print_merge_progress_stats(&upa);
8571 done:
8572 free(cwd);
8573 if (commit)
8574 got_object_commit_close(commit);
8575 free(commit_id_str);
8576 if (worktree)
8577 got_worktree_close(worktree);
8578 if (repo) {
8579 const struct got_error *close_err = got_repo_close(repo);
8580 if (error == NULL)
8581 error = close_err;
8583 if (pack_fds) {
8584 const struct got_error *pack_err =
8585 got_repo_pack_fds_close(pack_fds);
8586 if (error == NULL)
8587 error = pack_err;
8589 return error;
8592 __dead static void
8593 usage_cat(void)
8595 fprintf(stderr, "usage: %s cat [-P] [-c commit] [-r repository-path] "
8596 "arg ...\n", getprogname());
8597 exit(1);
8600 static const struct got_error *
8601 cat_blob(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
8603 const struct got_error *err;
8604 struct got_blob_object *blob;
8605 int fd = -1;
8607 fd = got_opentempfd();
8608 if (fd == -1)
8609 return got_error_from_errno("got_opentempfd");
8611 err = got_object_open_as_blob(&blob, repo, id, 8192, fd);
8612 if (err)
8613 goto done;
8615 err = got_object_blob_dump_to_file(NULL, NULL, NULL, outfile, blob);
8616 done:
8617 if (fd != -1 && close(fd) == -1 && err == NULL)
8618 err = got_error_from_errno("close");
8619 if (blob)
8620 got_object_blob_close(blob);
8621 return err;
8624 static const struct got_error *
8625 cat_tree(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
8627 const struct got_error *err;
8628 struct got_tree_object *tree;
8629 int nentries, i;
8631 err = got_object_open_as_tree(&tree, repo, id);
8632 if (err)
8633 return err;
8635 nentries = got_object_tree_get_nentries(tree);
8636 for (i = 0; i < nentries; i++) {
8637 struct got_tree_entry *te;
8638 char *id_str;
8639 if (sigint_received || sigpipe_received)
8640 break;
8641 te = got_object_tree_get_entry(tree, i);
8642 err = got_object_id_str(&id_str, got_tree_entry_get_id(te));
8643 if (err)
8644 break;
8645 fprintf(outfile, "%s %.7o %s\n", id_str,
8646 got_tree_entry_get_mode(te),
8647 got_tree_entry_get_name(te));
8648 free(id_str);
8651 got_object_tree_close(tree);
8652 return err;
8655 static const struct got_error *
8656 cat_commit(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
8658 const struct got_error *err;
8659 struct got_commit_object *commit;
8660 const struct got_object_id_queue *parent_ids;
8661 struct got_object_qid *pid;
8662 char *id_str = NULL;
8663 const char *logmsg = NULL;
8664 char gmtoff[6];
8666 err = got_object_open_as_commit(&commit, repo, id);
8667 if (err)
8668 return err;
8670 err = got_object_id_str(&id_str, got_object_commit_get_tree_id(commit));
8671 if (err)
8672 goto done;
8674 fprintf(outfile, "%s%s\n", GOT_COMMIT_LABEL_TREE, id_str);
8675 parent_ids = got_object_commit_get_parent_ids(commit);
8676 fprintf(outfile, "numparents %d\n",
8677 got_object_commit_get_nparents(commit));
8678 STAILQ_FOREACH(pid, parent_ids, entry) {
8679 char *pid_str;
8680 err = got_object_id_str(&pid_str, &pid->id);
8681 if (err)
8682 goto done;
8683 fprintf(outfile, "%s%s\n", GOT_COMMIT_LABEL_PARENT, pid_str);
8684 free(pid_str);
8686 got_date_format_gmtoff(gmtoff, sizeof(gmtoff),
8687 got_object_commit_get_author_gmtoff(commit));
8688 fprintf(outfile, "%s%s %lld %s\n", GOT_COMMIT_LABEL_AUTHOR,
8689 got_object_commit_get_author(commit),
8690 (long long)got_object_commit_get_author_time(commit),
8691 gmtoff);
8693 got_date_format_gmtoff(gmtoff, sizeof(gmtoff),
8694 got_object_commit_get_committer_gmtoff(commit));
8695 fprintf(outfile, "%s%s %lld %s\n", GOT_COMMIT_LABEL_COMMITTER,
8696 got_object_commit_get_committer(commit),
8697 (long long)got_object_commit_get_committer_time(commit),
8698 gmtoff);
8700 logmsg = got_object_commit_get_logmsg_raw(commit);
8701 fprintf(outfile, "messagelen %zd\n", strlen(logmsg));
8702 fprintf(outfile, "%s", logmsg);
8703 done:
8704 free(id_str);
8705 got_object_commit_close(commit);
8706 return err;
8709 static const struct got_error *
8710 cat_tag(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
8712 const struct got_error *err;
8713 struct got_tag_object *tag;
8714 char *id_str = NULL;
8715 const char *tagmsg = NULL;
8716 char gmtoff[6];
8718 err = got_object_open_as_tag(&tag, repo, id);
8719 if (err)
8720 return err;
8722 err = got_object_id_str(&id_str, got_object_tag_get_object_id(tag));
8723 if (err)
8724 goto done;
8726 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_OBJECT, id_str);
8728 switch (got_object_tag_get_object_type(tag)) {
8729 case GOT_OBJ_TYPE_BLOB:
8730 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
8731 GOT_OBJ_LABEL_BLOB);
8732 break;
8733 case GOT_OBJ_TYPE_TREE:
8734 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
8735 GOT_OBJ_LABEL_TREE);
8736 break;
8737 case GOT_OBJ_TYPE_COMMIT:
8738 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
8739 GOT_OBJ_LABEL_COMMIT);
8740 break;
8741 case GOT_OBJ_TYPE_TAG:
8742 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
8743 GOT_OBJ_LABEL_TAG);
8744 break;
8745 default:
8746 break;
8749 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TAG,
8750 got_object_tag_get_name(tag));
8752 got_date_format_gmtoff(gmtoff, sizeof(gmtoff),
8753 got_object_tag_get_tagger_gmtoff(tag));
8754 fprintf(outfile, "%s%s %lld %s\n", GOT_TAG_LABEL_TAGGER,
8755 got_object_tag_get_tagger(tag),
8756 (long long)got_object_tag_get_tagger_time(tag),
8757 gmtoff);
8759 tagmsg = got_object_tag_get_message(tag);
8760 fprintf(outfile, "messagelen %zd\n", strlen(tagmsg));
8761 fprintf(outfile, "%s", tagmsg);
8762 done:
8763 free(id_str);
8764 got_object_tag_close(tag);
8765 return err;
8768 static const struct got_error *
8769 cmd_cat(int argc, char *argv[])
8771 const struct got_error *error;
8772 struct got_repository *repo = NULL;
8773 struct got_worktree *worktree = NULL;
8774 char *cwd = NULL, *repo_path = NULL, *label = NULL;
8775 const char *commit_id_str = NULL;
8776 struct got_object_id *id = NULL, *commit_id = NULL;
8777 struct got_commit_object *commit = NULL;
8778 int ch, obj_type, i, force_path = 0;
8779 struct got_reflist_head refs;
8780 int *pack_fds = NULL;
8782 TAILQ_INIT(&refs);
8784 #ifndef PROFILE
8785 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
8786 NULL) == -1)
8787 err(1, "pledge");
8788 #endif
8790 while ((ch = getopt(argc, argv, "c:Pr:")) != -1) {
8791 switch (ch) {
8792 case 'c':
8793 commit_id_str = optarg;
8794 break;
8795 case 'P':
8796 force_path = 1;
8797 break;
8798 case 'r':
8799 repo_path = realpath(optarg, NULL);
8800 if (repo_path == NULL)
8801 return got_error_from_errno2("realpath",
8802 optarg);
8803 got_path_strip_trailing_slashes(repo_path);
8804 break;
8805 default:
8806 usage_cat();
8807 /* NOTREACHED */
8811 argc -= optind;
8812 argv += optind;
8814 cwd = getcwd(NULL, 0);
8815 if (cwd == NULL) {
8816 error = got_error_from_errno("getcwd");
8817 goto done;
8820 error = got_repo_pack_fds_open(&pack_fds);
8821 if (error != NULL)
8822 goto done;
8824 if (repo_path == NULL) {
8825 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_CVG_DIR);
8826 if (error && error->code != GOT_ERR_NOT_WORKTREE)
8827 goto done;
8828 if (worktree) {
8829 repo_path = strdup(
8830 got_worktree_get_repo_path(worktree));
8831 if (repo_path == NULL) {
8832 error = got_error_from_errno("strdup");
8833 goto done;
8836 /* Release work tree lock. */
8837 got_worktree_close(worktree);
8838 worktree = NULL;
8842 if (repo_path == NULL) {
8843 repo_path = strdup(cwd);
8844 if (repo_path == NULL)
8845 return got_error_from_errno("strdup");
8848 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
8849 free(repo_path);
8850 if (error != NULL)
8851 goto done;
8853 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
8854 if (error)
8855 goto done;
8857 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
8858 if (error)
8859 goto done;
8861 if (commit_id_str == NULL)
8862 commit_id_str = GOT_REF_HEAD;
8863 error = got_repo_match_object_id(&commit_id, NULL,
8864 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
8865 if (error)
8866 goto done;
8868 error = got_object_open_as_commit(&commit, repo, commit_id);
8869 if (error)
8870 goto done;
8872 for (i = 0; i < argc; i++) {
8873 if (force_path) {
8874 error = got_object_id_by_path(&id, repo, commit,
8875 argv[i]);
8876 if (error)
8877 break;
8878 } else {
8879 error = got_repo_match_object_id(&id, &label, argv[i],
8880 GOT_OBJ_TYPE_ANY, NULL /* do not resolve tags */,
8881 repo);
8882 if (error) {
8883 if (error->code != GOT_ERR_BAD_OBJ_ID_STR &&
8884 error->code != GOT_ERR_NOT_REF)
8885 break;
8886 error = got_object_id_by_path(&id, repo,
8887 commit, argv[i]);
8888 if (error)
8889 break;
8893 error = got_object_get_type(&obj_type, repo, id);
8894 if (error)
8895 break;
8897 switch (obj_type) {
8898 case GOT_OBJ_TYPE_BLOB:
8899 error = cat_blob(id, repo, stdout);
8900 break;
8901 case GOT_OBJ_TYPE_TREE:
8902 error = cat_tree(id, repo, stdout);
8903 break;
8904 case GOT_OBJ_TYPE_COMMIT:
8905 error = cat_commit(id, repo, stdout);
8906 break;
8907 case GOT_OBJ_TYPE_TAG:
8908 error = cat_tag(id, repo, stdout);
8909 break;
8910 default:
8911 error = got_error(GOT_ERR_OBJ_TYPE);
8912 break;
8914 if (error)
8915 break;
8916 free(label);
8917 label = NULL;
8918 free(id);
8919 id = NULL;
8921 done:
8922 free(label);
8923 free(id);
8924 free(commit_id);
8925 if (commit)
8926 got_object_commit_close(commit);
8927 if (worktree)
8928 got_worktree_close(worktree);
8929 if (repo) {
8930 const struct got_error *close_err = got_repo_close(repo);
8931 if (error == NULL)
8932 error = close_err;
8934 if (pack_fds) {
8935 const struct got_error *pack_err =
8936 got_repo_pack_fds_close(pack_fds);
8937 if (error == NULL)
8938 error = pack_err;
8941 got_ref_list_free(&refs);
8942 return error;
8945 __dead static void
8946 usage_info(void)
8948 fprintf(stderr, "usage: %s info [path ...]\n",
8949 getprogname());
8950 exit(1);
8953 static const struct got_error *
8954 print_path_info(void *arg, const char *path, mode_t mode, time_t mtime,
8955 struct got_object_id *blob_id, struct got_object_id *staged_blob_id,
8956 struct got_object_id *commit_id)
8958 const struct got_error *err = NULL;
8959 char *id_str = NULL;
8960 char datebuf[128];
8961 struct tm mytm, *tm;
8962 struct got_pathlist_head *paths = arg;
8963 struct got_pathlist_entry *pe;
8966 * Clear error indication from any of the path arguments which
8967 * would cause this file index entry to be displayed.
8969 TAILQ_FOREACH(pe, paths, entry) {
8970 if (got_path_cmp(path, pe->path, strlen(path),
8971 pe->path_len) == 0 ||
8972 got_path_is_child(path, pe->path, pe->path_len))
8973 pe->data = NULL; /* no error */
8976 printf(GOT_COMMIT_SEP_STR);
8977 if (S_ISLNK(mode))
8978 printf("symlink: %s\n", path);
8979 else if (S_ISREG(mode)) {
8980 printf("file: %s\n", path);
8981 printf("mode: %o\n", mode & (S_IRWXU | S_IRWXG | S_IRWXO));
8982 } else if (S_ISDIR(mode))
8983 printf("directory: %s\n", path);
8984 else
8985 printf("something: %s\n", path);
8987 tm = localtime_r(&mtime, &mytm);
8988 if (tm == NULL)
8989 return NULL;
8990 if (strftime(datebuf, sizeof(datebuf), "%c %Z", tm) == 0)
8991 return got_error(GOT_ERR_NO_SPACE);
8992 printf("timestamp: %s\n", datebuf);
8994 if (blob_id) {
8995 err = got_object_id_str(&id_str, blob_id);
8996 if (err)
8997 return err;
8998 printf("based on blob: %s\n", id_str);
8999 free(id_str);
9002 if (staged_blob_id) {
9003 err = got_object_id_str(&id_str, staged_blob_id);
9004 if (err)
9005 return err;
9006 printf("based on staged blob: %s\n", id_str);
9007 free(id_str);
9010 if (commit_id) {
9011 err = got_object_id_str(&id_str, commit_id);
9012 if (err)
9013 return err;
9014 printf("based on commit: %s\n", id_str);
9015 free(id_str);
9018 return NULL;
9021 static const struct got_error *
9022 cmd_info(int argc, char *argv[])
9024 const struct got_error *error = NULL;
9025 struct got_worktree *worktree = NULL;
9026 char *cwd = NULL, *id_str = NULL;
9027 struct got_pathlist_head paths;
9028 char *uuidstr = NULL;
9029 int ch, show_files = 0;
9031 TAILQ_INIT(&paths);
9033 #ifndef PROFILE
9034 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
9035 NULL) == -1)
9036 err(1, "pledge");
9037 #endif
9039 while ((ch = getopt(argc, argv, "")) != -1) {
9040 switch (ch) {
9041 default:
9042 usage_info();
9043 /* NOTREACHED */
9047 argc -= optind;
9048 argv += optind;
9050 cwd = getcwd(NULL, 0);
9051 if (cwd == NULL) {
9052 error = got_error_from_errno("getcwd");
9053 goto done;
9056 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_CVG_DIR);
9057 if (error) {
9058 if (error->code == GOT_ERR_NOT_WORKTREE)
9059 error = wrap_not_worktree_error(error, "info", cwd);
9060 goto done;
9063 #ifndef PROFILE
9064 /* Remove "wpath cpath proc exec sendfd" promises. */
9065 if (pledge("stdio rpath flock unveil", NULL) == -1)
9066 err(1, "pledge");
9067 #endif
9068 error = apply_unveil(NULL, 0, got_worktree_get_root_path(worktree));
9069 if (error)
9070 goto done;
9072 if (argc >= 1) {
9073 error = get_worktree_paths_from_argv(&paths, argc, argv,
9074 worktree);
9075 if (error)
9076 goto done;
9077 show_files = 1;
9080 error = got_object_id_str(&id_str,
9081 got_worktree_get_base_commit_id(worktree));
9082 if (error)
9083 goto done;
9085 error = got_worktree_get_uuid(&uuidstr, worktree);
9086 if (error)
9087 goto done;
9089 printf("work tree: %s\n", got_worktree_get_root_path(worktree));
9090 printf("work tree base commit: %s\n", id_str);
9091 printf("work tree path prefix: %s\n",
9092 got_worktree_get_path_prefix(worktree));
9093 printf("work tree branch reference: %s\n",
9094 got_worktree_get_head_ref_name(worktree));
9095 printf("work tree UUID: %s\n", uuidstr);
9096 printf("repository: %s\n", got_worktree_get_repo_path(worktree));
9098 if (show_files) {
9099 struct got_pathlist_entry *pe;
9100 TAILQ_FOREACH(pe, &paths, entry) {
9101 if (pe->path_len == 0)
9102 continue;
9104 * Assume this path will fail. This will be corrected
9105 * in print_path_info() in case the path does suceeed.
9107 pe->data = (void *)got_error(GOT_ERR_BAD_PATH);
9109 error = got_worktree_path_info(worktree, &paths,
9110 print_path_info, &paths, check_cancelled, NULL);
9111 if (error)
9112 goto done;
9113 TAILQ_FOREACH(pe, &paths, entry) {
9114 if (pe->data != NULL) {
9115 const struct got_error *perr;
9117 perr = pe->data;
9118 error = got_error_fmt(perr->code, "%s",
9119 pe->path);
9120 break;
9124 done:
9125 if (worktree)
9126 got_worktree_close(worktree);
9127 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
9128 free(cwd);
9129 free(id_str);
9130 free(uuidstr);
9131 return error;