Blob


1 /*
2 * Copyright (c) 2017 Martin Pieuchot <mpi@openbsd.org>
3 * Copyright (c) 2018, 2019, 2020 Stefan Sperling <stsp@openbsd.org>
4 * Copyright (c) 2020 Ori Bernstein <ori@openbsd.org>
5 * Copyright (C) 2023 Josh Rickmar <jrick@zettaport.com>
6 *
7 * Permission to use, copy, modify, and distribute this software for any
8 * purpose with or without fee is hereby granted, provided that the above
9 * copyright notice and this permission notice appear in all copies.
10 *
11 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
12 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
13 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
14 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
15 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
16 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
17 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
18 */
20 #include <sys/queue.h>
21 #include <sys/time.h>
22 #include <sys/types.h>
23 #include <sys/stat.h>
24 #include <sys/wait.h>
26 #include <err.h>
27 #include <errno.h>
28 #include <fcntl.h>
29 #include <limits.h>
30 #include <locale.h>
31 #include <ctype.h>
32 #include <sha1.h>
33 #include <sha2.h>
34 #include <signal.h>
35 #include <stdio.h>
36 #include <stdlib.h>
37 #include <string.h>
38 #include <unistd.h>
39 #include <libgen.h>
40 #include <time.h>
41 #include <paths.h>
42 #include <regex.h>
43 #include <getopt.h>
44 #include <util.h>
46 #include "got_version.h"
47 #include "got_error.h"
48 #include "got_object.h"
49 #include "got_reference.h"
50 #include "got_repository.h"
51 #include "got_path.h"
52 #include "got_cancel.h"
53 #include "got_worktree.h"
54 #include "got_worktree_cvg.h"
55 #include "got_diff.h"
56 #include "got_commit_graph.h"
57 #include "got_fetch.h"
58 #include "got_send.h"
59 #include "got_blame.h"
60 #include "got_privsep.h"
61 #include "got_opentemp.h"
62 #include "got_gotconfig.h"
63 #include "got_dial.h"
64 #include "got_patch.h"
65 #include "got_sigs.h"
66 #include "got_date.h"
68 #ifndef nitems
69 #define nitems(_a) (sizeof((_a)) / sizeof((_a)[0]))
70 #endif
72 static volatile sig_atomic_t sigint_received;
73 static volatile sig_atomic_t sigpipe_received;
75 static void
76 catch_sigint(int signo)
77 {
78 sigint_received = 1;
79 }
81 static void
82 catch_sigpipe(int signo)
83 {
84 sigpipe_received = 1;
85 }
88 struct got_cmd {
89 const char *cmd_name;
90 const struct got_error *(*cmd_main)(int, char *[]);
91 void (*cmd_usage)(void);
92 const char *cmd_alias;
93 };
95 __dead static void usage(int, int);
96 __dead static void usage_import(void);
97 __dead static void usage_clone(void);
98 __dead static void usage_checkout(void);
99 __dead static void usage_update(void);
100 __dead static void usage_log(void);
101 __dead static void usage_diff(void);
102 __dead static void usage_blame(void);
103 __dead static void usage_tree(void);
104 __dead static void usage_status(void);
105 __dead static void usage_tag(void);
106 __dead static void usage_add(void);
107 __dead static void usage_remove(void);
108 __dead static void usage_patch(void);
109 __dead static void usage_revert(void);
110 __dead static void usage_commit(void);
111 __dead static void usage_cherrypick(void);
112 __dead static void usage_backout(void);
113 __dead static void usage_cat(void);
114 __dead static void usage_info(void);
116 static const struct got_error* cmd_import(int, char *[]);
117 static const struct got_error* cmd_clone(int, char *[]);
118 static const struct got_error* cmd_checkout(int, char *[]);
119 static const struct got_error* cmd_update(int, char *[]);
120 static const struct got_error* cmd_log(int, char *[]);
121 static const struct got_error* cmd_diff(int, char *[]);
122 static const struct got_error* cmd_blame(int, char *[]);
123 static const struct got_error* cmd_tree(int, char *[]);
124 static const struct got_error* cmd_status(int, char *[]);
125 static const struct got_error* cmd_tag(int, char *[]);
126 static const struct got_error* cmd_add(int, char *[]);
127 static const struct got_error* cmd_remove(int, char *[]);
128 static const struct got_error* cmd_patch(int, char *[]);
129 static const struct got_error* cmd_revert(int, char *[]);
130 static const struct got_error* cmd_commit(int, char *[]);
131 static const struct got_error* cmd_cherrypick(int, char *[]);
132 static const struct got_error* cmd_backout(int, char *[]);
133 static const struct got_error* cmd_cat(int, char *[]);
134 static const struct got_error* cmd_info(int, char *[]);
136 static const struct got_cmd got_commands[] = {
137 { "import", cmd_import, usage_import, "im" },
138 { "clone", cmd_clone, usage_clone, "cl" },
139 { "checkout", cmd_checkout, usage_checkout, "co" },
140 { "update", cmd_update, usage_update, "up" },
141 { "log", cmd_log, usage_log, "" },
142 { "diff", cmd_diff, usage_diff, "di" },
143 { "blame", cmd_blame, usage_blame, "bl" },
144 { "tree", cmd_tree, usage_tree, "tr" },
145 { "status", cmd_status, usage_status, "st" },
146 { "tag", cmd_tag, usage_tag, "" },
147 { "add", cmd_add, usage_add, "" },
148 { "remove", cmd_remove, usage_remove, "rm" },
149 { "patch", cmd_patch, usage_patch, "pa" },
150 { "revert", cmd_revert, usage_revert, "rv" },
151 { "commit", cmd_commit, usage_commit, "ci" },
152 { "cherrypick", cmd_cherrypick, usage_cherrypick, "cy" },
153 { "backout", cmd_backout, usage_backout, "bo" },
154 { "cat", cmd_cat, usage_cat, "" },
155 { "info", cmd_info, usage_info, "" },
156 };
158 static void
159 list_commands(FILE *fp)
161 size_t i;
163 fprintf(fp, "commands:");
164 for (i = 0; i < nitems(got_commands); i++) {
165 const struct got_cmd *cmd = &got_commands[i];
166 fprintf(fp, " %s", cmd->cmd_name);
168 fputc('\n', fp);
171 __dead static void
172 option_conflict(char a, char b)
174 errx(1, "-%c and -%c options are mutually exclusive", a, b);
177 int
178 main(int argc, char *argv[])
180 const struct got_cmd *cmd;
181 size_t i;
182 int ch;
183 int hflag = 0, Vflag = 0;
184 static const struct option longopts[] = {
185 { "version", no_argument, NULL, 'V' },
186 { NULL, 0, NULL, 0 }
187 };
189 setlocale(LC_CTYPE, "");
191 while ((ch = getopt_long(argc, argv, "+hV", longopts, NULL)) != -1) {
192 switch (ch) {
193 case 'h':
194 hflag = 1;
195 break;
196 case 'V':
197 Vflag = 1;
198 break;
199 default:
200 usage(hflag, 1);
201 /* NOTREACHED */
205 argc -= optind;
206 argv += optind;
207 optind = 1;
208 optreset = 1;
210 if (Vflag) {
211 got_version_print_str();
212 return 0;
215 if (argc <= 0)
216 usage(hflag, hflag ? 0 : 1);
218 signal(SIGINT, catch_sigint);
219 signal(SIGPIPE, catch_sigpipe);
221 for (i = 0; i < nitems(got_commands); i++) {
222 const struct got_error *error;
224 cmd = &got_commands[i];
226 if (strcmp(cmd->cmd_name, argv[0]) != 0 &&
227 strcmp(cmd->cmd_alias, argv[0]) != 0)
228 continue;
230 if (hflag)
231 cmd->cmd_usage();
233 error = cmd->cmd_main(argc, argv);
234 if (error && error->code != GOT_ERR_CANCELLED &&
235 error->code != GOT_ERR_PRIVSEP_EXIT &&
236 !(sigpipe_received &&
237 error->code == GOT_ERR_ERRNO && errno == EPIPE) &&
238 !(sigint_received &&
239 error->code == GOT_ERR_ERRNO && errno == EINTR)) {
240 fflush(stdout);
241 fprintf(stderr, "%s: %s\n", getprogname(), error->msg);
242 return 1;
245 return 0;
248 fprintf(stderr, "%s: unknown command '%s'\n", getprogname(), argv[0]);
249 list_commands(stderr);
250 return 1;
253 __dead static void
254 usage(int hflag, int status)
256 FILE *fp = (status == 0) ? stdout : stderr;
258 fprintf(fp, "usage: %s [-hV] command [arg ...]\n",
259 getprogname());
260 if (hflag)
261 list_commands(fp);
262 exit(status);
265 static const struct got_error *
266 get_editor(char **abspath)
268 const struct got_error *err = NULL;
269 const char *editor;
271 *abspath = NULL;
273 editor = getenv("VISUAL");
274 if (editor == NULL)
275 editor = getenv("EDITOR");
277 if (editor) {
278 err = got_path_find_prog(abspath, editor);
279 if (err)
280 return err;
283 if (*abspath == NULL) {
284 *abspath = strdup("/usr/bin/vi");
285 if (*abspath == NULL)
286 return got_error_from_errno("strdup");
289 return NULL;
292 static const struct got_error *
293 apply_unveil(const char *repo_path, int repo_read_only,
294 const char *worktree_path)
296 const struct got_error *err;
298 #ifdef PROFILE
299 if (unveil("gmon.out", "rwc") != 0)
300 return got_error_from_errno2("unveil", "gmon.out");
301 #endif
302 if (repo_path && unveil(repo_path, repo_read_only ? "r" : "rwc") != 0)
303 return got_error_from_errno2("unveil", repo_path);
305 if (worktree_path && unveil(worktree_path, "rwc") != 0)
306 return got_error_from_errno2("unveil", worktree_path);
308 if (unveil(GOT_TMPDIR_STR, "rwc") != 0)
309 return got_error_from_errno2("unveil", GOT_TMPDIR_STR);
311 err = got_privsep_unveil_exec_helpers();
312 if (err != NULL)
313 return err;
315 if (unveil(NULL, NULL) != 0)
316 return got_error_from_errno("unveil");
318 return NULL;
321 __dead static void
322 usage_import(void)
324 fprintf(stderr, "usage: %s import [-b branch] [-I pattern] [-m message] "
325 "[-r repository-path] directory\n", getprogname());
326 exit(1);
329 static int
330 spawn_editor(const char *editor, const char *file)
332 pid_t pid;
333 sig_t sighup, sigint, sigquit;
334 int st = -1;
336 sighup = signal(SIGHUP, SIG_IGN);
337 sigint = signal(SIGINT, SIG_IGN);
338 sigquit = signal(SIGQUIT, SIG_IGN);
340 switch (pid = fork()) {
341 case -1:
342 goto doneediting;
343 case 0:
344 execl(editor, editor, file, (char *)NULL);
345 _exit(127);
348 while (waitpid(pid, &st, 0) == -1)
349 if (errno != EINTR)
350 break;
352 doneediting:
353 (void)signal(SIGHUP, sighup);
354 (void)signal(SIGINT, sigint);
355 (void)signal(SIGQUIT, sigquit);
357 if (!WIFEXITED(st)) {
358 errno = EINTR;
359 return -1;
362 return WEXITSTATUS(st);
365 static const struct got_error *
366 read_logmsg(char **logmsg, size_t *len, FILE *fp, size_t filesize)
368 const struct got_error *err = NULL;
369 char *line = NULL;
370 size_t linesize = 0;
372 *logmsg = NULL;
373 *len = 0;
375 if (fseeko(fp, 0L, SEEK_SET) == -1)
376 return got_error_from_errno("fseeko");
378 *logmsg = malloc(filesize + 1);
379 if (*logmsg == NULL)
380 return got_error_from_errno("malloc");
381 (*logmsg)[0] = '\0';
383 while (getline(&line, &linesize, fp) != -1) {
384 if (line[0] == '#' || (*len == 0 && line[0] == '\n'))
385 continue; /* remove comments and leading empty lines */
386 *len = strlcat(*logmsg, line, filesize + 1);
387 if (*len >= filesize + 1) {
388 err = got_error(GOT_ERR_NO_SPACE);
389 goto done;
392 if (ferror(fp)) {
393 err = got_ferror(fp, GOT_ERR_IO);
394 goto done;
397 while (*len > 0 && (*logmsg)[*len - 1] == '\n') {
398 (*logmsg)[*len - 1] = '\0';
399 (*len)--;
401 done:
402 free(line);
403 if (err) {
404 free(*logmsg);
405 *logmsg = NULL;
406 *len = 0;
408 return err;
411 static const struct got_error *
412 edit_logmsg(char **logmsg, const char *editor, const char *logmsg_path,
413 const char *initial_content, size_t initial_content_len,
414 int require_modification)
416 const struct got_error *err = NULL;
417 struct stat st, st2;
418 FILE *fp = NULL;
419 size_t logmsg_len;
421 *logmsg = NULL;
423 if (stat(logmsg_path, &st) == -1)
424 return got_error_from_errno2("stat", logmsg_path);
426 if (spawn_editor(editor, logmsg_path) == -1)
427 return got_error_from_errno("failed spawning editor");
429 if (require_modification) {
430 struct timespec timeout;
432 timeout.tv_sec = 0;
433 timeout.tv_nsec = 1;
434 nanosleep(&timeout, NULL);
437 if (stat(logmsg_path, &st2) == -1)
438 return got_error_from_errno2("stat", logmsg_path);
440 if (require_modification && st.st_size == st2.st_size &&
441 timespeccmp(&st.st_mtim, &st2.st_mtim, ==))
442 return got_error_msg(GOT_ERR_COMMIT_MSG_EMPTY,
443 "no changes made to commit message, aborting");
445 fp = fopen(logmsg_path, "re");
446 if (fp == NULL) {
447 err = got_error_from_errno("fopen");
448 goto done;
451 /* strip comments and leading/trailing newlines */
452 err = read_logmsg(logmsg, &logmsg_len, fp, st2.st_size);
453 if (err)
454 goto done;
455 if (logmsg_len == 0) {
456 err = got_error_msg(GOT_ERR_COMMIT_MSG_EMPTY,
457 "commit message cannot be empty, aborting");
458 goto done;
460 done:
461 if (fp && fclose(fp) == EOF && err == NULL)
462 err = got_error_from_errno("fclose");
463 if (err) {
464 free(*logmsg);
465 *logmsg = NULL;
467 return err;
470 static const struct got_error *
471 collect_import_msg(char **logmsg, char **logmsg_path, const char *editor,
472 const char *path_dir, const char *branch_name)
474 char *initial_content = NULL;
475 const struct got_error *err = NULL;
476 int initial_content_len;
477 int fd = -1;
479 initial_content_len = asprintf(&initial_content,
480 "\n# %s to be imported to branch %s\n", path_dir,
481 branch_name);
482 if (initial_content_len == -1)
483 return got_error_from_errno("asprintf");
485 err = got_opentemp_named_fd(logmsg_path, &fd,
486 GOT_TMPDIR_STR "/got-importmsg", "");
487 if (err)
488 goto done;
490 if (write(fd, initial_content, initial_content_len) == -1) {
491 err = got_error_from_errno2("write", *logmsg_path);
492 goto done;
494 if (close(fd) == -1) {
495 err = got_error_from_errno2("close", *logmsg_path);
496 goto done;
498 fd = -1;
500 err = edit_logmsg(logmsg, editor, *logmsg_path, initial_content,
501 initial_content_len, 1);
502 done:
503 if (fd != -1 && close(fd) == -1 && err == NULL)
504 err = got_error_from_errno2("close", *logmsg_path);
505 free(initial_content);
506 if (err) {
507 free(*logmsg_path);
508 *logmsg_path = NULL;
510 return err;
513 static const struct got_error *
514 import_progress(void *arg, const char *path)
516 printf("A %s\n", path);
517 return NULL;
520 static const struct got_error *
521 valid_author(const char *author)
523 const char *email = author;
525 /*
526 * Git' expects the author (or committer) to be in the form
527 * "name <email>", which are mostly free form (see the
528 * "committer" description in git-fast-import(1)). We're only
529 * doing this to avoid git's object parser breaking on commits
530 * we create.
531 */
533 while (*author && *author != '\n' && *author != '<' && *author != '>')
534 author++;
535 if (author != email && *author == '<' && *(author - 1) != ' ')
536 return got_error_fmt(GOT_ERR_COMMIT_BAD_AUTHOR, "%s: space "
537 "between author name and email required", email);
538 if (*author++ != '<')
539 return got_error_fmt(GOT_ERR_COMMIT_NO_EMAIL, "%s", email);
540 while (*author && *author != '\n' && *author != '<' && *author != '>')
541 author++;
542 if (strcmp(author, ">") != 0)
543 return got_error_fmt(GOT_ERR_COMMIT_NO_EMAIL, "%s", email);
544 return NULL;
547 static const struct got_error *
548 get_author(char **author, struct got_repository *repo,
549 struct got_worktree *worktree)
551 const struct got_error *err = NULL;
552 const char *got_author = NULL, *name, *email;
553 const struct got_gotconfig *worktree_conf = NULL, *repo_conf = NULL;
555 *author = NULL;
557 if (worktree)
558 worktree_conf = got_worktree_get_gotconfig(worktree);
559 repo_conf = got_repo_get_gotconfig(repo);
561 /*
562 * Priority of potential author information sources, from most
563 * significant to least significant:
564 * 1) work tree's .got/got.conf file
565 * 2) repository's got.conf file
566 * 3) repository's git config file
567 * 4) environment variables
568 * 5) global git config files (in user's home directory or /etc)
569 */
571 if (worktree_conf)
572 got_author = got_gotconfig_get_author(worktree_conf);
573 if (got_author == NULL)
574 got_author = got_gotconfig_get_author(repo_conf);
575 if (got_author == NULL) {
576 name = got_repo_get_gitconfig_author_name(repo);
577 email = got_repo_get_gitconfig_author_email(repo);
578 if (name && email) {
579 if (asprintf(author, "%s <%s>", name, email) == -1)
580 return got_error_from_errno("asprintf");
581 return NULL;
584 got_author = getenv("GOT_AUTHOR");
585 if (got_author == NULL) {
586 name = got_repo_get_global_gitconfig_author_name(repo);
587 email = got_repo_get_global_gitconfig_author_email(
588 repo);
589 if (name && email) {
590 if (asprintf(author, "%s <%s>", name, email)
591 == -1)
592 return got_error_from_errno("asprintf");
593 return NULL;
595 /* TODO: Look up user in password database? */
596 return got_error(GOT_ERR_COMMIT_NO_AUTHOR);
600 *author = strdup(got_author);
601 if (*author == NULL)
602 return got_error_from_errno("strdup");
604 err = valid_author(*author);
605 if (err) {
606 free(*author);
607 *author = NULL;
609 return err;
612 static const struct got_error *
613 get_allowed_signers(char **allowed_signers, struct got_repository *repo,
614 struct got_worktree *worktree)
616 const char *got_allowed_signers = NULL;
617 const struct got_gotconfig *worktree_conf = NULL, *repo_conf = NULL;
619 *allowed_signers = NULL;
621 if (worktree)
622 worktree_conf = got_worktree_get_gotconfig(worktree);
623 repo_conf = got_repo_get_gotconfig(repo);
625 /*
626 * Priority of potential author information sources, from most
627 * significant to least significant:
628 * 1) work tree's .got/got.conf file
629 * 2) repository's got.conf file
630 */
632 if (worktree_conf)
633 got_allowed_signers = got_gotconfig_get_allowed_signers_file(
634 worktree_conf);
635 if (got_allowed_signers == NULL)
636 got_allowed_signers = got_gotconfig_get_allowed_signers_file(
637 repo_conf);
639 if (got_allowed_signers) {
640 *allowed_signers = strdup(got_allowed_signers);
641 if (*allowed_signers == NULL)
642 return got_error_from_errno("strdup");
644 return NULL;
647 static const struct got_error *
648 get_revoked_signers(char **revoked_signers, struct got_repository *repo,
649 struct got_worktree *worktree)
651 const char *got_revoked_signers = NULL;
652 const struct got_gotconfig *worktree_conf = NULL, *repo_conf = NULL;
654 *revoked_signers = NULL;
656 if (worktree)
657 worktree_conf = got_worktree_get_gotconfig(worktree);
658 repo_conf = got_repo_get_gotconfig(repo);
660 /*
661 * Priority of potential author information sources, from most
662 * significant to least significant:
663 * 1) work tree's .got/got.conf file
664 * 2) repository's got.conf file
665 */
667 if (worktree_conf)
668 got_revoked_signers = got_gotconfig_get_revoked_signers_file(
669 worktree_conf);
670 if (got_revoked_signers == NULL)
671 got_revoked_signers = got_gotconfig_get_revoked_signers_file(
672 repo_conf);
674 if (got_revoked_signers) {
675 *revoked_signers = strdup(got_revoked_signers);
676 if (*revoked_signers == NULL)
677 return got_error_from_errno("strdup");
679 return NULL;
682 static const char *
683 get_signer_id(struct got_repository *repo, struct got_worktree *worktree)
685 const char *got_signer_id = NULL;
686 const struct got_gotconfig *worktree_conf = NULL, *repo_conf = NULL;
688 if (worktree)
689 worktree_conf = got_worktree_get_gotconfig(worktree);
690 repo_conf = got_repo_get_gotconfig(repo);
692 /*
693 * Priority of potential author information sources, from most
694 * significant to least significant:
695 * 1) work tree's .got/got.conf file
696 * 2) repository's got.conf file
697 */
699 if (worktree_conf)
700 got_signer_id = got_gotconfig_get_signer_id(worktree_conf);
701 if (got_signer_id == NULL)
702 got_signer_id = got_gotconfig_get_signer_id(repo_conf);
704 return got_signer_id;
707 static const struct got_error *
708 get_gitconfig_path(char **gitconfig_path)
710 const char *homedir = getenv("HOME");
712 *gitconfig_path = NULL;
713 if (homedir) {
714 if (asprintf(gitconfig_path, "%s/.gitconfig", homedir) == -1)
715 return got_error_from_errno("asprintf");
718 return NULL;
721 static const struct got_error *
722 cmd_import(int argc, char *argv[])
724 const struct got_error *error = NULL;
725 char *path_dir = NULL, *repo_path = NULL, *logmsg = NULL;
726 char *gitconfig_path = NULL, *editor = NULL, *author = NULL;
727 const char *branch_name = NULL;
728 char *id_str = NULL, *logmsg_path = NULL;
729 char refname[PATH_MAX] = "refs/heads/";
730 struct got_repository *repo = NULL;
731 struct got_reference *branch_ref = NULL, *head_ref = NULL;
732 struct got_object_id *new_commit_id = NULL;
733 int ch, n = 0;
734 struct got_pathlist_head ignores;
735 struct got_pathlist_entry *pe;
736 int preserve_logmsg = 0;
737 int *pack_fds = NULL;
739 TAILQ_INIT(&ignores);
741 #ifndef PROFILE
742 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
743 "unveil",
744 NULL) == -1)
745 err(1, "pledge");
746 #endif
748 while ((ch = getopt(argc, argv, "b:I:m:r:")) != -1) {
749 switch (ch) {
750 case 'b':
751 branch_name = optarg;
752 break;
753 case 'I':
754 if (optarg[0] == '\0')
755 break;
756 error = got_pathlist_insert(&pe, &ignores, optarg,
757 NULL);
758 if (error)
759 goto done;
760 break;
761 case 'm':
762 logmsg = strdup(optarg);
763 if (logmsg == NULL) {
764 error = got_error_from_errno("strdup");
765 goto done;
767 break;
768 case 'r':
769 repo_path = realpath(optarg, NULL);
770 if (repo_path == NULL) {
771 error = got_error_from_errno2("realpath",
772 optarg);
773 goto done;
775 break;
776 default:
777 usage_import();
778 /* NOTREACHED */
782 argc -= optind;
783 argv += optind;
785 if (argc != 1)
786 usage_import();
788 if (repo_path == NULL) {
789 repo_path = getcwd(NULL, 0);
790 if (repo_path == NULL)
791 return got_error_from_errno("getcwd");
793 got_path_strip_trailing_slashes(repo_path);
794 error = get_gitconfig_path(&gitconfig_path);
795 if (error)
796 goto done;
797 error = got_repo_pack_fds_open(&pack_fds);
798 if (error != NULL)
799 goto done;
800 error = got_repo_open(&repo, repo_path, gitconfig_path, pack_fds);
801 if (error)
802 goto done;
804 error = get_author(&author, repo, NULL);
805 if (error)
806 return error;
808 /*
809 * Don't let the user create a branch name with a leading '-'.
810 * While technically a valid reference name, this case is usually
811 * an unintended typo.
812 */
813 if (branch_name && branch_name[0] == '-')
814 return got_error_path(branch_name, GOT_ERR_REF_NAME_MINUS);
816 error = got_ref_open(&head_ref, repo, GOT_REF_HEAD, 0);
817 if (error && error->code != GOT_ERR_NOT_REF)
818 goto done;
820 if (branch_name)
821 n = strlcat(refname, branch_name, sizeof(refname));
822 else if (head_ref && got_ref_is_symbolic(head_ref))
823 n = strlcpy(refname, got_ref_get_symref_target(head_ref),
824 sizeof(refname));
825 else
826 n = strlcat(refname, "main", sizeof(refname));
827 if (n >= sizeof(refname)) {
828 error = got_error(GOT_ERR_NO_SPACE);
829 goto done;
832 error = got_ref_open(&branch_ref, repo, refname, 0);
833 if (error) {
834 if (error->code != GOT_ERR_NOT_REF)
835 goto done;
836 } else {
837 error = got_error_msg(GOT_ERR_BRANCH_EXISTS,
838 "import target branch already exists");
839 goto done;
842 path_dir = realpath(argv[0], NULL);
843 if (path_dir == NULL) {
844 error = got_error_from_errno2("realpath", argv[0]);
845 goto done;
847 got_path_strip_trailing_slashes(path_dir);
849 /*
850 * unveil(2) traverses exec(2); if an editor is used we have
851 * to apply unveil after the log message has been written.
852 */
853 if (logmsg == NULL || *logmsg == '\0') {
854 error = get_editor(&editor);
855 if (error)
856 goto done;
857 free(logmsg);
858 error = collect_import_msg(&logmsg, &logmsg_path, editor,
859 path_dir, refname);
860 if (error) {
861 if (error->code != GOT_ERR_COMMIT_MSG_EMPTY &&
862 logmsg_path != NULL)
863 preserve_logmsg = 1;
864 goto done;
868 if (unveil(path_dir, "r") != 0) {
869 error = got_error_from_errno2("unveil", path_dir);
870 if (logmsg_path)
871 preserve_logmsg = 1;
872 goto done;
875 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
876 if (error) {
877 if (logmsg_path)
878 preserve_logmsg = 1;
879 goto done;
882 error = got_repo_import(&new_commit_id, path_dir, logmsg,
883 author, &ignores, repo, import_progress, NULL);
884 if (error) {
885 if (logmsg_path)
886 preserve_logmsg = 1;
887 goto done;
890 error = got_ref_alloc(&branch_ref, refname, new_commit_id);
891 if (error) {
892 if (logmsg_path)
893 preserve_logmsg = 1;
894 goto done;
897 error = got_ref_write(branch_ref, repo);
898 if (error) {
899 if (logmsg_path)
900 preserve_logmsg = 1;
901 goto done;
904 error = got_object_id_str(&id_str, new_commit_id);
905 if (error) {
906 if (logmsg_path)
907 preserve_logmsg = 1;
908 goto done;
911 error = got_ref_open(&head_ref, repo, GOT_REF_HEAD, 0);
912 if (error) {
913 if (error->code != GOT_ERR_NOT_REF) {
914 if (logmsg_path)
915 preserve_logmsg = 1;
916 goto done;
919 error = got_ref_alloc_symref(&head_ref, GOT_REF_HEAD,
920 branch_ref);
921 if (error) {
922 if (logmsg_path)
923 preserve_logmsg = 1;
924 goto done;
927 error = got_ref_write(head_ref, repo);
928 if (error) {
929 if (logmsg_path)
930 preserve_logmsg = 1;
931 goto done;
935 printf("Created branch %s with commit %s\n",
936 got_ref_get_name(branch_ref), id_str);
937 done:
938 if (pack_fds) {
939 const struct got_error *pack_err =
940 got_repo_pack_fds_close(pack_fds);
941 if (error == NULL)
942 error = pack_err;
944 if (repo) {
945 const struct got_error *close_err = got_repo_close(repo);
946 if (error == NULL)
947 error = close_err;
949 if (preserve_logmsg) {
950 fprintf(stderr, "%s: log message preserved in %s\n",
951 getprogname(), logmsg_path);
952 } else if (logmsg_path && unlink(logmsg_path) == -1 && error == NULL)
953 error = got_error_from_errno2("unlink", logmsg_path);
954 free(logmsg);
955 free(logmsg_path);
956 free(repo_path);
957 free(editor);
958 free(new_commit_id);
959 free(id_str);
960 free(author);
961 free(gitconfig_path);
962 if (branch_ref)
963 got_ref_close(branch_ref);
964 if (head_ref)
965 got_ref_close(head_ref);
966 return error;
969 __dead static void
970 usage_clone(void)
972 fprintf(stderr, "usage: %s clone [-almqv] [-b branch] [-R reference] "
973 "repository-URL [directory]\n", getprogname());
974 exit(1);
977 struct got_fetch_progress_arg {
978 char last_scaled_size[FMT_SCALED_STRSIZE];
979 int last_p_indexed;
980 int last_p_resolved;
981 int verbosity;
983 struct got_repository *repo;
985 int create_configs;
986 int configs_created;
987 struct {
988 struct got_pathlist_head *symrefs;
989 struct got_pathlist_head *wanted_branches;
990 struct got_pathlist_head *wanted_refs;
991 const char *proto;
992 const char *host;
993 const char *port;
994 const char *remote_repo_path;
995 const char *git_url;
996 int fetch_all_branches;
997 int mirror_references;
998 } config_info;
999 };
1001 /* XXX forward declaration */
1002 static const struct got_error *
1003 create_config_files(const char *proto, const char *host, const char *port,
1004 const char *remote_repo_path, const char *git_url, int fetch_all_branches,
1005 int mirror_references, struct got_pathlist_head *symrefs,
1006 struct got_pathlist_head *wanted_branches,
1007 struct got_pathlist_head *wanted_refs, struct got_repository *repo);
1009 static const struct got_error *
1010 fetch_progress(void *arg, const char *message, off_t packfile_size,
1011 int nobj_total, int nobj_indexed, int nobj_loose, int nobj_resolved)
1013 const struct got_error *err = NULL;
1014 struct got_fetch_progress_arg *a = arg;
1015 char scaled_size[FMT_SCALED_STRSIZE];
1016 int p_indexed, p_resolved;
1017 int print_size = 0, print_indexed = 0, print_resolved = 0;
1020 * In order to allow a failed clone to be resumed with 'got fetch'
1021 * we try to create configuration files as soon as possible.
1022 * Once the server has sent information about its default branch
1023 * we have all required information.
1025 if (a->create_configs && !a->configs_created &&
1026 !TAILQ_EMPTY(a->config_info.symrefs)) {
1027 err = create_config_files(a->config_info.proto,
1028 a->config_info.host, a->config_info.port,
1029 a->config_info.remote_repo_path,
1030 a->config_info.git_url,
1031 a->config_info.fetch_all_branches,
1032 a->config_info.mirror_references,
1033 a->config_info.symrefs,
1034 a->config_info.wanted_branches,
1035 a->config_info.wanted_refs, a->repo);
1036 if (err)
1037 return err;
1038 a->configs_created = 1;
1041 if (a->verbosity < 0)
1042 return NULL;
1044 if (message && message[0] != '\0') {
1045 printf("\rserver: %s", message);
1046 fflush(stdout);
1047 return NULL;
1050 if (packfile_size > 0 || nobj_indexed > 0) {
1051 if (fmt_scaled(packfile_size, scaled_size) == 0 &&
1052 (a->last_scaled_size[0] == '\0' ||
1053 strcmp(scaled_size, a->last_scaled_size)) != 0) {
1054 print_size = 1;
1055 if (strlcpy(a->last_scaled_size, scaled_size,
1056 FMT_SCALED_STRSIZE) >= FMT_SCALED_STRSIZE)
1057 return got_error(GOT_ERR_NO_SPACE);
1059 if (nobj_indexed > 0) {
1060 p_indexed = (nobj_indexed * 100) / nobj_total;
1061 if (p_indexed != a->last_p_indexed) {
1062 a->last_p_indexed = p_indexed;
1063 print_indexed = 1;
1064 print_size = 1;
1067 if (nobj_resolved > 0) {
1068 p_resolved = (nobj_resolved * 100) /
1069 (nobj_total - nobj_loose);
1070 if (p_resolved != a->last_p_resolved) {
1071 a->last_p_resolved = p_resolved;
1072 print_resolved = 1;
1073 print_indexed = 1;
1074 print_size = 1;
1079 if (print_size || print_indexed || print_resolved)
1080 printf("\r");
1081 if (print_size)
1082 printf("%*s fetched", FMT_SCALED_STRSIZE - 2, scaled_size);
1083 if (print_indexed)
1084 printf("; indexing %d%%", p_indexed);
1085 if (print_resolved)
1086 printf("; resolving deltas %d%%", p_resolved);
1087 if (print_size || print_indexed || print_resolved)
1088 fflush(stdout);
1090 return NULL;
1093 static const struct got_error *
1094 create_symref(const char *refname, struct got_reference *target_ref,
1095 int verbosity, struct got_repository *repo)
1097 const struct got_error *err;
1098 struct got_reference *head_symref;
1100 err = got_ref_alloc_symref(&head_symref, refname, target_ref);
1101 if (err)
1102 return err;
1104 err = got_ref_write(head_symref, repo);
1105 if (err == NULL && verbosity > 0) {
1106 printf("Created reference %s: %s\n", GOT_REF_HEAD,
1107 got_ref_get_name(target_ref));
1109 got_ref_close(head_symref);
1110 return err;
1113 static const struct got_error *
1114 list_remote_refs(struct got_pathlist_head *symrefs,
1115 struct got_pathlist_head *refs)
1117 const struct got_error *err;
1118 struct got_pathlist_entry *pe;
1120 TAILQ_FOREACH(pe, symrefs, entry) {
1121 const char *refname = pe->path;
1122 const char *targetref = pe->data;
1124 printf("%s: %s\n", refname, targetref);
1127 TAILQ_FOREACH(pe, refs, entry) {
1128 const char *refname = pe->path;
1129 struct got_object_id *id = pe->data;
1130 char *id_str;
1132 err = got_object_id_str(&id_str, id);
1133 if (err)
1134 return err;
1135 printf("%s: %s\n", refname, id_str);
1136 free(id_str);
1139 return NULL;
1142 static const struct got_error *
1143 create_ref(const char *refname, struct got_object_id *id,
1144 int verbosity, struct got_repository *repo)
1146 const struct got_error *err = NULL;
1147 struct got_reference *ref;
1148 char *id_str;
1150 err = got_object_id_str(&id_str, id);
1151 if (err)
1152 return err;
1154 err = got_ref_alloc(&ref, refname, id);
1155 if (err)
1156 goto done;
1158 err = got_ref_write(ref, repo);
1159 got_ref_close(ref);
1161 if (err == NULL && verbosity >= 0)
1162 printf("Created reference %s: %s\n", refname, id_str);
1163 done:
1164 free(id_str);
1165 return err;
1168 static int
1169 match_wanted_ref(const char *refname, const char *wanted_ref)
1171 if (strncmp(refname, "refs/", 5) != 0)
1172 return 0;
1173 refname += 5;
1176 * Prevent fetching of references that won't make any
1177 * sense outside of the remote repository's context.
1179 if (strncmp(refname, "got/", 4) == 0)
1180 return 0;
1181 if (strncmp(refname, "remotes/", 8) == 0)
1182 return 0;
1184 if (strncmp(wanted_ref, "refs/", 5) == 0)
1185 wanted_ref += 5;
1187 /* Allow prefix match. */
1188 if (got_path_is_child(refname, wanted_ref, strlen(wanted_ref)))
1189 return 1;
1191 /* Allow exact match. */
1192 return (strcmp(refname, wanted_ref) == 0);
1195 static int
1196 is_wanted_ref(struct got_pathlist_head *wanted_refs, const char *refname)
1198 struct got_pathlist_entry *pe;
1200 TAILQ_FOREACH(pe, wanted_refs, entry) {
1201 if (match_wanted_ref(refname, pe->path))
1202 return 1;
1205 return 0;
1208 static const struct got_error *
1209 create_wanted_ref(const char *refname, struct got_object_id *id,
1210 const char *remote_repo_name, int verbosity, struct got_repository *repo)
1212 const struct got_error *err;
1213 char *remote_refname;
1215 if (strncmp("refs/", refname, 5) == 0)
1216 refname += 5;
1218 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
1219 remote_repo_name, refname) == -1)
1220 return got_error_from_errno("asprintf");
1222 err = create_ref(remote_refname, id, verbosity, repo);
1223 free(remote_refname);
1224 return err;
1227 static const struct got_error *
1228 create_gotconfig(const char *proto, const char *host, const char *port,
1229 const char *remote_repo_path, const char *default_branch,
1230 int fetch_all_branches, struct got_pathlist_head *wanted_branches,
1231 struct got_pathlist_head *wanted_refs, int mirror_references,
1232 struct got_repository *repo)
1234 const struct got_error *err = NULL;
1235 char *gotconfig_path = NULL;
1236 char *gotconfig = NULL;
1237 FILE *gotconfig_file = NULL;
1238 const char *branchname = NULL;
1239 char *branches = NULL, *refs = NULL;
1240 ssize_t n;
1242 if (!fetch_all_branches && !TAILQ_EMPTY(wanted_branches)) {
1243 struct got_pathlist_entry *pe;
1244 TAILQ_FOREACH(pe, wanted_branches, entry) {
1245 char *s;
1246 branchname = pe->path;
1247 if (strncmp(branchname, "refs/heads/", 11) == 0)
1248 branchname += 11;
1249 if (asprintf(&s, "%s\"%s\" ",
1250 branches ? branches : "", branchname) == -1) {
1251 err = got_error_from_errno("asprintf");
1252 goto done;
1254 free(branches);
1255 branches = s;
1257 } else if (!fetch_all_branches && default_branch) {
1258 branchname = default_branch;
1259 if (strncmp(branchname, "refs/heads/", 11) == 0)
1260 branchname += 11;
1261 if (asprintf(&branches, "\"%s\" ", branchname) == -1) {
1262 err = got_error_from_errno("asprintf");
1263 goto done;
1266 if (!TAILQ_EMPTY(wanted_refs)) {
1267 struct got_pathlist_entry *pe;
1268 TAILQ_FOREACH(pe, wanted_refs, entry) {
1269 char *s;
1270 const char *refname = pe->path;
1271 if (strncmp(refname, "refs/", 5) == 0)
1272 branchname += 5;
1273 if (asprintf(&s, "%s\"%s\" ",
1274 refs ? refs : "", refname) == -1) {
1275 err = got_error_from_errno("asprintf");
1276 goto done;
1278 free(refs);
1279 refs = s;
1283 /* Create got.conf(5). */
1284 gotconfig_path = got_repo_get_path_gotconfig(repo);
1285 if (gotconfig_path == NULL) {
1286 err = got_error_from_errno("got_repo_get_path_gotconfig");
1287 goto done;
1289 gotconfig_file = fopen(gotconfig_path, "ae");
1290 if (gotconfig_file == NULL) {
1291 err = got_error_from_errno2("fopen", gotconfig_path);
1292 goto done;
1294 if (asprintf(&gotconfig,
1295 "remote \"%s\" {\n"
1296 "\tserver %s\n"
1297 "\tprotocol %s\n"
1298 "%s%s%s"
1299 "\trepository \"%s\"\n"
1300 "%s%s%s"
1301 "%s%s%s"
1302 "%s"
1303 "%s"
1304 "}\n",
1305 GOT_FETCH_DEFAULT_REMOTE_NAME, host, proto,
1306 port ? "\tport " : "", port ? port : "", port ? "\n" : "",
1307 remote_repo_path, branches ? "\tbranch { " : "",
1308 branches ? branches : "", branches ? "}\n" : "",
1309 refs ? "\treference { " : "", refs ? refs : "", refs ? "}\n" : "",
1310 mirror_references ? "\tmirror_references yes\n" : "",
1311 fetch_all_branches ? "\tfetch_all_branches yes\n" : "") == -1) {
1312 err = got_error_from_errno("asprintf");
1313 goto done;
1315 n = fwrite(gotconfig, 1, strlen(gotconfig), gotconfig_file);
1316 if (n != strlen(gotconfig)) {
1317 err = got_ferror(gotconfig_file, GOT_ERR_IO);
1318 goto done;
1321 done:
1322 if (gotconfig_file && fclose(gotconfig_file) == EOF && err == NULL)
1323 err = got_error_from_errno2("fclose", gotconfig_path);
1324 free(gotconfig_path);
1325 free(branches);
1326 return err;
1329 static const struct got_error *
1330 create_gitconfig(const char *git_url, const char *default_branch,
1331 int fetch_all_branches, struct got_pathlist_head *wanted_branches,
1332 struct got_pathlist_head *wanted_refs, int mirror_references,
1333 struct got_repository *repo)
1335 const struct got_error *err = NULL;
1336 char *gitconfig_path = NULL;
1337 char *gitconfig = NULL;
1338 FILE *gitconfig_file = NULL;
1339 char *branches = NULL, *refs = NULL;
1340 const char *branchname;
1341 ssize_t n;
1343 /* Create a config file Git can understand. */
1344 gitconfig_path = got_repo_get_path_gitconfig(repo);
1345 if (gitconfig_path == NULL) {
1346 err = got_error_from_errno("got_repo_get_path_gitconfig");
1347 goto done;
1349 gitconfig_file = fopen(gitconfig_path, "ae");
1350 if (gitconfig_file == NULL) {
1351 err = got_error_from_errno2("fopen", gitconfig_path);
1352 goto done;
1354 if (fetch_all_branches) {
1355 if (mirror_references) {
1356 if (asprintf(&branches,
1357 "\tfetch = refs/heads/*:refs/heads/*\n") == -1) {
1358 err = got_error_from_errno("asprintf");
1359 goto done;
1361 } else if (asprintf(&branches,
1362 "\tfetch = refs/heads/*:refs/remotes/%s/*\n",
1363 GOT_FETCH_DEFAULT_REMOTE_NAME) == -1) {
1364 err = got_error_from_errno("asprintf");
1365 goto done;
1367 } else if (!TAILQ_EMPTY(wanted_branches)) {
1368 struct got_pathlist_entry *pe;
1369 TAILQ_FOREACH(pe, wanted_branches, entry) {
1370 char *s;
1371 branchname = pe->path;
1372 if (strncmp(branchname, "refs/heads/", 11) == 0)
1373 branchname += 11;
1374 if (mirror_references) {
1375 if (asprintf(&s,
1376 "%s\tfetch = refs/heads/%s:refs/heads/%s\n",
1377 branches ? branches : "",
1378 branchname, branchname) == -1) {
1379 err = got_error_from_errno("asprintf");
1380 goto done;
1382 } else if (asprintf(&s,
1383 "%s\tfetch = refs/heads/%s:refs/remotes/%s/%s\n",
1384 branches ? branches : "",
1385 branchname, GOT_FETCH_DEFAULT_REMOTE_NAME,
1386 branchname) == -1) {
1387 err = got_error_from_errno("asprintf");
1388 goto done;
1390 free(branches);
1391 branches = s;
1393 } else {
1395 * If the server specified a default branch, use just that one.
1396 * Otherwise fall back to fetching all branches on next fetch.
1398 if (default_branch) {
1399 branchname = default_branch;
1400 if (strncmp(branchname, "refs/heads/", 11) == 0)
1401 branchname += 11;
1402 } else
1403 branchname = "*"; /* fall back to all branches */
1404 if (mirror_references) {
1405 if (asprintf(&branches,
1406 "\tfetch = refs/heads/%s:refs/heads/%s\n",
1407 branchname, branchname) == -1) {
1408 err = got_error_from_errno("asprintf");
1409 goto done;
1411 } else if (asprintf(&branches,
1412 "\tfetch = refs/heads/%s:refs/remotes/%s/%s\n",
1413 branchname, GOT_FETCH_DEFAULT_REMOTE_NAME,
1414 branchname) == -1) {
1415 err = got_error_from_errno("asprintf");
1416 goto done;
1419 if (!TAILQ_EMPTY(wanted_refs)) {
1420 struct got_pathlist_entry *pe;
1421 TAILQ_FOREACH(pe, wanted_refs, entry) {
1422 char *s;
1423 const char *refname = pe->path;
1424 if (strncmp(refname, "refs/", 5) == 0)
1425 refname += 5;
1426 if (mirror_references) {
1427 if (asprintf(&s,
1428 "%s\tfetch = refs/%s:refs/%s\n",
1429 refs ? refs : "", refname, refname) == -1) {
1430 err = got_error_from_errno("asprintf");
1431 goto done;
1433 } else if (asprintf(&s,
1434 "%s\tfetch = refs/%s:refs/remotes/%s/%s\n",
1435 refs ? refs : "",
1436 refname, GOT_FETCH_DEFAULT_REMOTE_NAME,
1437 refname) == -1) {
1438 err = got_error_from_errno("asprintf");
1439 goto done;
1441 free(refs);
1442 refs = s;
1446 if (asprintf(&gitconfig,
1447 "[remote \"%s\"]\n"
1448 "\turl = %s\n"
1449 "%s"
1450 "%s"
1451 "\tfetch = refs/tags/*:refs/tags/*\n",
1452 GOT_FETCH_DEFAULT_REMOTE_NAME, git_url, branches ? branches : "",
1453 refs ? refs : "") == -1) {
1454 err = got_error_from_errno("asprintf");
1455 goto done;
1457 n = fwrite(gitconfig, 1, strlen(gitconfig), gitconfig_file);
1458 if (n != strlen(gitconfig)) {
1459 err = got_ferror(gitconfig_file, GOT_ERR_IO);
1460 goto done;
1462 done:
1463 if (gitconfig_file && fclose(gitconfig_file) == EOF && err == NULL)
1464 err = got_error_from_errno2("fclose", gitconfig_path);
1465 free(gitconfig_path);
1466 free(branches);
1467 return err;
1470 static const struct got_error *
1471 create_config_files(const char *proto, const char *host, const char *port,
1472 const char *remote_repo_path, const char *git_url, int fetch_all_branches,
1473 int mirror_references, struct got_pathlist_head *symrefs,
1474 struct got_pathlist_head *wanted_branches,
1475 struct got_pathlist_head *wanted_refs, struct got_repository *repo)
1477 const struct got_error *err = NULL;
1478 const char *default_branch = NULL;
1479 struct got_pathlist_entry *pe;
1482 * If we asked for a set of wanted branches then use the first
1483 * one of those.
1485 if (!TAILQ_EMPTY(wanted_branches)) {
1486 pe = TAILQ_FIRST(wanted_branches);
1487 default_branch = pe->path;
1488 } else {
1489 /* First HEAD ref listed by server is the default branch. */
1490 TAILQ_FOREACH(pe, symrefs, entry) {
1491 const char *refname = pe->path;
1492 const char *target = pe->data;
1494 if (strcmp(refname, GOT_REF_HEAD) != 0)
1495 continue;
1497 default_branch = target;
1498 break;
1502 /* Create got.conf(5). */
1503 err = create_gotconfig(proto, host, port, remote_repo_path,
1504 default_branch, fetch_all_branches, wanted_branches,
1505 wanted_refs, mirror_references, repo);
1506 if (err)
1507 return err;
1509 /* Create a config file Git can understand. */
1510 return create_gitconfig(git_url, default_branch, fetch_all_branches,
1511 wanted_branches, wanted_refs, mirror_references, repo);
1514 static const struct got_error *
1515 cmd_clone(int argc, char *argv[])
1517 const struct got_error *error = NULL;
1518 const char *uri, *dirname;
1519 char *proto, *host, *port, *repo_name, *server_path;
1520 char *default_destdir = NULL, *id_str = NULL;
1521 const char *repo_path;
1522 struct got_repository *repo = NULL;
1523 struct got_pathlist_head refs, symrefs, wanted_branches, wanted_refs;
1524 struct got_pathlist_entry *pe;
1525 struct got_object_id *pack_hash = NULL;
1526 int ch, fetchfd = -1, fetchstatus;
1527 pid_t fetchpid = -1;
1528 struct got_fetch_progress_arg fpa;
1529 char *git_url = NULL;
1530 int verbosity = 0, fetch_all_branches = 0, mirror_references = 0;
1531 int bflag = 0, list_refs_only = 0;
1532 int *pack_fds = NULL;
1534 TAILQ_INIT(&refs);
1535 TAILQ_INIT(&symrefs);
1536 TAILQ_INIT(&wanted_branches);
1537 TAILQ_INIT(&wanted_refs);
1539 while ((ch = getopt(argc, argv, "ab:lmqR:v")) != -1) {
1540 switch (ch) {
1541 case 'a':
1542 fetch_all_branches = 1;
1543 break;
1544 case 'b':
1545 error = got_pathlist_append(&wanted_branches,
1546 optarg, NULL);
1547 if (error)
1548 return error;
1549 bflag = 1;
1550 break;
1551 case 'l':
1552 list_refs_only = 1;
1553 break;
1554 case 'm':
1555 mirror_references = 1;
1556 break;
1557 case 'q':
1558 verbosity = -1;
1559 break;
1560 case 'R':
1561 error = got_pathlist_append(&wanted_refs,
1562 optarg, NULL);
1563 if (error)
1564 return error;
1565 break;
1566 case 'v':
1567 if (verbosity < 0)
1568 verbosity = 0;
1569 else if (verbosity < 3)
1570 verbosity++;
1571 break;
1572 default:
1573 usage_clone();
1574 break;
1577 argc -= optind;
1578 argv += optind;
1580 if (fetch_all_branches && !TAILQ_EMPTY(&wanted_branches))
1581 option_conflict('a', 'b');
1582 if (list_refs_only) {
1583 if (!TAILQ_EMPTY(&wanted_branches))
1584 option_conflict('l', 'b');
1585 if (fetch_all_branches)
1586 option_conflict('l', 'a');
1587 if (mirror_references)
1588 option_conflict('l', 'm');
1589 if (!TAILQ_EMPTY(&wanted_refs))
1590 option_conflict('l', 'R');
1593 uri = argv[0];
1595 if (argc == 1)
1596 dirname = NULL;
1597 else if (argc == 2)
1598 dirname = argv[1];
1599 else
1600 usage_clone();
1602 error = got_dial_parse_uri(&proto, &host, &port, &server_path,
1603 &repo_name, uri);
1604 if (error)
1605 goto done;
1607 if (asprintf(&git_url, "%s://%s%s%s%s%s", proto,
1608 host, port ? ":" : "", port ? port : "",
1609 server_path[0] != '/' ? "/" : "", server_path) == -1) {
1610 error = got_error_from_errno("asprintf");
1611 goto done;
1614 if (strcmp(proto, "git") == 0) {
1615 #ifndef PROFILE
1616 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
1617 "sendfd dns inet unveil", NULL) == -1)
1618 err(1, "pledge");
1619 #endif
1620 } else if (strcmp(proto, "git+ssh") == 0 ||
1621 strcmp(proto, "ssh") == 0) {
1622 #ifndef PROFILE
1623 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
1624 "sendfd unveil", NULL) == -1)
1625 err(1, "pledge");
1626 #endif
1627 } else if (strcmp(proto, "http") == 0 ||
1628 strcmp(proto, "git+http") == 0) {
1629 error = got_error_path(proto, GOT_ERR_NOT_IMPL);
1630 goto done;
1631 } else {
1632 error = got_error_path(proto, GOT_ERR_BAD_PROTO);
1633 goto done;
1635 if (dirname == NULL) {
1636 if (asprintf(&default_destdir, "%s.git", repo_name) == -1) {
1637 error = got_error_from_errno("asprintf");
1638 goto done;
1640 repo_path = default_destdir;
1641 } else
1642 repo_path = dirname;
1644 if (!list_refs_only) {
1645 error = got_path_mkdir(repo_path);
1646 if (error &&
1647 (!(error->code == GOT_ERR_ERRNO && errno == EISDIR) &&
1648 !(error->code == GOT_ERR_ERRNO && errno == EEXIST)))
1649 goto done;
1650 if (!got_path_dir_is_empty(repo_path)) {
1651 error = got_error_path(repo_path,
1652 GOT_ERR_DIR_NOT_EMPTY);
1653 goto done;
1657 error = got_dial_apply_unveil(proto);
1658 if (error)
1659 goto done;
1661 error = apply_unveil(repo_path, 0, NULL);
1662 if (error)
1663 goto done;
1665 if (verbosity >= 0)
1666 printf("Connecting to %s\n", git_url);
1668 error = got_fetch_connect(&fetchpid, &fetchfd, proto, host, port,
1669 server_path, verbosity);
1670 if (error)
1671 goto done;
1673 if (!list_refs_only) {
1674 error = got_repo_init(repo_path, NULL);
1675 if (error)
1676 goto done;
1677 error = got_repo_pack_fds_open(&pack_fds);
1678 if (error != NULL)
1679 goto done;
1680 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
1681 if (error)
1682 goto done;
1685 fpa.last_scaled_size[0] = '\0';
1686 fpa.last_p_indexed = -1;
1687 fpa.last_p_resolved = -1;
1688 fpa.verbosity = verbosity;
1689 fpa.create_configs = 1;
1690 fpa.configs_created = 0;
1691 fpa.repo = repo;
1692 fpa.config_info.symrefs = &symrefs;
1693 fpa.config_info.wanted_branches = &wanted_branches;
1694 fpa.config_info.wanted_refs = &wanted_refs;
1695 fpa.config_info.proto = proto;
1696 fpa.config_info.host = host;
1697 fpa.config_info.port = port;
1698 fpa.config_info.remote_repo_path = server_path;
1699 fpa.config_info.git_url = git_url;
1700 fpa.config_info.fetch_all_branches = fetch_all_branches;
1701 fpa.config_info.mirror_references = mirror_references;
1702 error = got_fetch_pack(&pack_hash, &refs, &symrefs,
1703 GOT_FETCH_DEFAULT_REMOTE_NAME, mirror_references,
1704 fetch_all_branches, &wanted_branches, &wanted_refs,
1705 list_refs_only, verbosity, fetchfd, repo, NULL, NULL, bflag,
1706 fetch_progress, &fpa);
1707 if (error)
1708 goto done;
1710 if (list_refs_only) {
1711 error = list_remote_refs(&symrefs, &refs);
1712 goto done;
1715 if (pack_hash == NULL) {
1716 error = got_error_fmt(GOT_ERR_FETCH_FAILED, "%s",
1717 "server sent an empty pack file");
1718 goto done;
1720 error = got_object_id_str(&id_str, pack_hash);
1721 if (error)
1722 goto done;
1723 if (verbosity >= 0)
1724 printf("\nFetched %s.pack\n", id_str);
1725 free(id_str);
1727 /* Set up references provided with the pack file. */
1728 TAILQ_FOREACH(pe, &refs, entry) {
1729 const char *refname = pe->path;
1730 struct got_object_id *id = pe->data;
1731 char *remote_refname;
1733 if (is_wanted_ref(&wanted_refs, refname) &&
1734 !mirror_references) {
1735 error = create_wanted_ref(refname, id,
1736 GOT_FETCH_DEFAULT_REMOTE_NAME,
1737 verbosity - 1, repo);
1738 if (error)
1739 goto done;
1740 continue;
1743 error = create_ref(refname, id, verbosity - 1, repo);
1744 if (error)
1745 goto done;
1747 if (mirror_references)
1748 continue;
1750 if (strncmp("refs/heads/", refname, 11) != 0)
1751 continue;
1753 if (asprintf(&remote_refname,
1754 "refs/remotes/%s/%s", GOT_FETCH_DEFAULT_REMOTE_NAME,
1755 refname + 11) == -1) {
1756 error = got_error_from_errno("asprintf");
1757 goto done;
1759 error = create_ref(remote_refname, id, verbosity - 1, repo);
1760 free(remote_refname);
1761 if (error)
1762 goto done;
1765 /* Set the HEAD reference if the server provided one. */
1766 TAILQ_FOREACH(pe, &symrefs, entry) {
1767 struct got_reference *target_ref;
1768 const char *refname = pe->path;
1769 const char *target = pe->data;
1770 char *remote_refname = NULL, *remote_target = NULL;
1772 if (strcmp(refname, GOT_REF_HEAD) != 0)
1773 continue;
1775 error = got_ref_open(&target_ref, repo, target, 0);
1776 if (error) {
1777 if (error->code == GOT_ERR_NOT_REF) {
1778 error = NULL;
1779 continue;
1781 goto done;
1784 error = create_symref(refname, target_ref, verbosity, repo);
1785 got_ref_close(target_ref);
1786 if (error)
1787 goto done;
1789 if (mirror_references)
1790 continue;
1792 if (strncmp("refs/heads/", target, 11) != 0)
1793 continue;
1795 if (asprintf(&remote_refname,
1796 "refs/remotes/%s/%s", GOT_FETCH_DEFAULT_REMOTE_NAME,
1797 refname) == -1) {
1798 error = got_error_from_errno("asprintf");
1799 goto done;
1801 if (asprintf(&remote_target,
1802 "refs/remotes/%s/%s", GOT_FETCH_DEFAULT_REMOTE_NAME,
1803 target + 11) == -1) {
1804 error = got_error_from_errno("asprintf");
1805 free(remote_refname);
1806 goto done;
1808 error = got_ref_open(&target_ref, repo, remote_target, 0);
1809 if (error) {
1810 free(remote_refname);
1811 free(remote_target);
1812 if (error->code == GOT_ERR_NOT_REF) {
1813 error = NULL;
1814 continue;
1816 goto done;
1818 error = create_symref(remote_refname, target_ref,
1819 verbosity - 1, repo);
1820 free(remote_refname);
1821 free(remote_target);
1822 got_ref_close(target_ref);
1823 if (error)
1824 goto done;
1826 if (pe == NULL) {
1828 * We failed to set the HEAD reference. If we asked for
1829 * a set of wanted branches use the first of one of those
1830 * which could be fetched instead.
1832 TAILQ_FOREACH(pe, &wanted_branches, entry) {
1833 const char *target = pe->path;
1834 struct got_reference *target_ref;
1836 error = got_ref_open(&target_ref, repo, target, 0);
1837 if (error) {
1838 if (error->code == GOT_ERR_NOT_REF) {
1839 error = NULL;
1840 continue;
1842 goto done;
1845 error = create_symref(GOT_REF_HEAD, target_ref,
1846 verbosity, repo);
1847 got_ref_close(target_ref);
1848 if (error)
1849 goto done;
1850 break;
1853 if (!fpa.configs_created && pe != NULL) {
1854 error = create_config_files(fpa.config_info.proto,
1855 fpa.config_info.host, fpa.config_info.port,
1856 fpa.config_info.remote_repo_path,
1857 fpa.config_info.git_url,
1858 fpa.config_info.fetch_all_branches,
1859 fpa.config_info.mirror_references,
1860 fpa.config_info.symrefs,
1861 fpa.config_info.wanted_branches,
1862 fpa.config_info.wanted_refs, fpa.repo);
1863 if (error)
1864 goto done;
1868 if (verbosity >= 0)
1869 printf("Created %s repository '%s'\n",
1870 mirror_references ? "mirrored" : "cloned", repo_path);
1871 done:
1872 if (pack_fds) {
1873 const struct got_error *pack_err =
1874 got_repo_pack_fds_close(pack_fds);
1875 if (error == NULL)
1876 error = pack_err;
1878 if (fetchpid > 0) {
1879 if (kill(fetchpid, SIGTERM) == -1)
1880 error = got_error_from_errno("kill");
1881 if (waitpid(fetchpid, &fetchstatus, 0) == -1 && error == NULL)
1882 error = got_error_from_errno("waitpid");
1884 if (fetchfd != -1 && close(fetchfd) == -1 && error == NULL)
1885 error = got_error_from_errno("close");
1886 if (repo) {
1887 const struct got_error *close_err = got_repo_close(repo);
1888 if (error == NULL)
1889 error = close_err;
1891 got_pathlist_free(&refs, GOT_PATHLIST_FREE_ALL);
1892 got_pathlist_free(&symrefs, GOT_PATHLIST_FREE_ALL);
1893 got_pathlist_free(&wanted_branches, GOT_PATHLIST_FREE_NONE);
1894 got_pathlist_free(&wanted_refs, GOT_PATHLIST_FREE_NONE);
1895 free(pack_hash);
1896 free(proto);
1897 free(host);
1898 free(port);
1899 free(server_path);
1900 free(repo_name);
1901 free(default_destdir);
1902 free(git_url);
1903 return error;
1906 static const struct got_error *
1907 update_ref(struct got_reference *ref, struct got_object_id *new_id,
1908 int replace_tags, int verbosity, struct got_repository *repo)
1910 const struct got_error *err = NULL;
1911 char *new_id_str = NULL;
1912 struct got_object_id *old_id = NULL;
1914 err = got_object_id_str(&new_id_str, new_id);
1915 if (err)
1916 goto done;
1918 if (!replace_tags &&
1919 strncmp(got_ref_get_name(ref), "refs/tags/", 10) == 0) {
1920 err = got_ref_resolve(&old_id, repo, ref);
1921 if (err)
1922 goto done;
1923 if (got_object_id_cmp(old_id, new_id) == 0)
1924 goto done;
1925 if (verbosity >= 0) {
1926 printf("Rejecting update of existing tag %s: %s\n",
1927 got_ref_get_name(ref), new_id_str);
1929 goto done;
1932 if (got_ref_is_symbolic(ref)) {
1933 if (verbosity >= 0) {
1934 printf("Replacing reference %s: %s\n",
1935 got_ref_get_name(ref),
1936 got_ref_get_symref_target(ref));
1938 err = got_ref_change_symref_to_ref(ref, new_id);
1939 if (err)
1940 goto done;
1941 err = got_ref_write(ref, repo);
1942 if (err)
1943 goto done;
1944 } else {
1945 err = got_ref_resolve(&old_id, repo, ref);
1946 if (err)
1947 goto done;
1948 if (got_object_id_cmp(old_id, new_id) == 0)
1949 goto done;
1951 err = got_ref_change_ref(ref, new_id);
1952 if (err)
1953 goto done;
1954 err = got_ref_write(ref, repo);
1955 if (err)
1956 goto done;
1959 if (verbosity >= 0)
1960 printf("Updated %s: %s\n", got_ref_get_name(ref),
1961 new_id_str);
1962 done:
1963 free(old_id);
1964 free(new_id_str);
1965 return err;
1968 static const struct got_error *
1969 update_wanted_ref(const char *refname, struct got_object_id *id,
1970 const char *remote_repo_name, int verbosity, struct got_repository *repo)
1972 const struct got_error *err, *unlock_err;
1973 char *remote_refname;
1974 struct got_reference *ref;
1976 if (strncmp("refs/", refname, 5) == 0)
1977 refname += 5;
1979 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
1980 remote_repo_name, refname) == -1)
1981 return got_error_from_errno("asprintf");
1983 err = got_ref_open(&ref, repo, remote_refname, 1);
1984 if (err) {
1985 if (err->code != GOT_ERR_NOT_REF)
1986 goto done;
1987 err = create_ref(remote_refname, id, verbosity, repo);
1988 } else {
1989 err = update_ref(ref, id, 0, verbosity, repo);
1990 unlock_err = got_ref_unlock(ref);
1991 if (unlock_err && err == NULL)
1992 err = unlock_err;
1993 got_ref_close(ref);
1995 done:
1996 free(remote_refname);
1997 return err;
2000 __dead static void
2001 usage_checkout(void)
2003 fprintf(stderr, "usage: %s checkout [-Eq] [-b branch] [-c commit] "
2004 "[-p path-prefix] repository-path [work-tree-path]\n",
2005 getprogname());
2006 exit(1);
2009 static void
2010 show_worktree_base_ref_warning(void)
2012 fprintf(stderr, "%s: warning: could not create a reference "
2013 "to the work tree's base commit; the commit could be "
2014 "garbage-collected by Git or 'gotadmin cleanup'; making the "
2015 "repository writable and running 'got update' will prevent this\n",
2016 getprogname());
2019 struct got_checkout_progress_arg {
2020 const char *worktree_path;
2021 int had_base_commit_ref_error;
2022 int verbosity;
2025 static const struct got_error *
2026 checkout_progress(void *arg, unsigned char status, const char *path)
2028 struct got_checkout_progress_arg *a = arg;
2030 /* Base commit bump happens silently. */
2031 if (status == GOT_STATUS_BUMP_BASE)
2032 return NULL;
2034 if (status == GOT_STATUS_BASE_REF_ERR) {
2035 a->had_base_commit_ref_error = 1;
2036 return NULL;
2039 while (path[0] == '/')
2040 path++;
2042 if (a->verbosity >= 0)
2043 printf("%c %s/%s\n", status, a->worktree_path, path);
2045 return NULL;
2048 static const struct got_error *
2049 check_cancelled(void *arg)
2051 if (sigint_received || sigpipe_received)
2052 return got_error(GOT_ERR_CANCELLED);
2053 return NULL;
2056 static const struct got_error *
2057 check_linear_ancestry(struct got_object_id *commit_id,
2058 struct got_object_id *base_commit_id, int allow_forwards_in_time_only,
2059 struct got_repository *repo)
2061 const struct got_error *err = NULL;
2062 struct got_object_id *yca_id;
2064 err = got_commit_graph_find_youngest_common_ancestor(&yca_id,
2065 commit_id, base_commit_id, 1, repo, check_cancelled, NULL);
2066 if (err)
2067 return err;
2069 if (yca_id == NULL)
2070 return got_error(GOT_ERR_ANCESTRY);
2073 * Require a straight line of history between the target commit
2074 * and the work tree's base commit.
2076 * Non-linear situations such as this require a rebase:
2078 * (commit) D F (base_commit)
2079 * \ /
2080 * C E
2081 * \ /
2082 * B (yca)
2083 * |
2084 * A
2086 * 'got update' only handles linear cases:
2087 * Update forwards in time: A (base/yca) - B - C - D (commit)
2088 * Update backwards in time: D (base) - C - B - A (commit/yca)
2090 if (allow_forwards_in_time_only) {
2091 if (got_object_id_cmp(base_commit_id, yca_id) != 0)
2092 return got_error(GOT_ERR_ANCESTRY);
2093 } else if (got_object_id_cmp(commit_id, yca_id) != 0 &&
2094 got_object_id_cmp(base_commit_id, yca_id) != 0)
2095 return got_error(GOT_ERR_ANCESTRY);
2097 free(yca_id);
2098 return NULL;
2101 static const struct got_error *
2102 check_same_branch(struct got_object_id *commit_id,
2103 struct got_reference *head_ref, struct got_repository *repo)
2105 const struct got_error *err = NULL;
2106 struct got_commit_graph *graph = NULL;
2107 struct got_object_id *head_commit_id = NULL;
2109 err = got_ref_resolve(&head_commit_id, repo, head_ref);
2110 if (err)
2111 goto done;
2113 if (got_object_id_cmp(head_commit_id, commit_id) == 0)
2114 goto done;
2116 err = got_commit_graph_open(&graph, "/", 1);
2117 if (err)
2118 goto done;
2120 err = got_commit_graph_iter_start(graph, head_commit_id, repo,
2121 check_cancelled, NULL);
2122 if (err)
2123 goto done;
2125 for (;;) {
2126 struct got_object_id id;
2128 err = got_commit_graph_iter_next(&id, graph, repo,
2129 check_cancelled, NULL);
2130 if (err) {
2131 if (err->code == GOT_ERR_ITER_COMPLETED)
2132 err = got_error(GOT_ERR_ANCESTRY);
2133 break;
2136 if (got_object_id_cmp(&id, commit_id) == 0)
2137 break;
2139 done:
2140 if (graph)
2141 got_commit_graph_close(graph);
2142 free(head_commit_id);
2143 return err;
2146 static const struct got_error *
2147 checkout_ancestry_error(struct got_reference *ref, const char *commit_id_str)
2149 static char msg[512];
2150 const char *branch_name;
2152 if (got_ref_is_symbolic(ref))
2153 branch_name = got_ref_get_symref_target(ref);
2154 else
2155 branch_name = got_ref_get_name(ref);
2157 if (strncmp("refs/heads/", branch_name, 11) == 0)
2158 branch_name += 11;
2160 snprintf(msg, sizeof(msg),
2161 "target commit is not contained in branch '%s'; "
2162 "the branch to use must be specified with -b; "
2163 "if necessary a new branch can be created for "
2164 "this commit with 'got branch -c %s BRANCH_NAME'",
2165 branch_name, commit_id_str);
2167 return got_error_msg(GOT_ERR_ANCESTRY, msg);
2170 static const struct got_error *
2171 cmd_checkout(int argc, char *argv[])
2173 const struct got_error *error = NULL;
2174 struct got_repository *repo = NULL;
2175 struct got_reference *head_ref = NULL, *ref = NULL;
2176 struct got_worktree *worktree = NULL;
2177 char *repo_path = NULL;
2178 char *worktree_path = NULL;
2179 const char *path_prefix = "";
2180 const char *branch_name = GOT_REF_HEAD, *refname = NULL;
2181 char *commit_id_str = NULL;
2182 struct got_object_id *commit_id = NULL;
2183 char *cwd = NULL;
2184 int ch, same_path_prefix, allow_nonempty = 0, verbosity = 0;
2185 struct got_pathlist_head paths;
2186 struct got_checkout_progress_arg cpa;
2187 int *pack_fds = NULL;
2189 TAILQ_INIT(&paths);
2191 #ifndef PROFILE
2192 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
2193 "unveil", NULL) == -1)
2194 err(1, "pledge");
2195 #endif
2197 while ((ch = getopt(argc, argv, "b:c:Ep:q")) != -1) {
2198 switch (ch) {
2199 case 'b':
2200 branch_name = optarg;
2201 break;
2202 case 'c':
2203 commit_id_str = strdup(optarg);
2204 if (commit_id_str == NULL)
2205 return got_error_from_errno("strdup");
2206 break;
2207 case 'E':
2208 allow_nonempty = 1;
2209 break;
2210 case 'p':
2211 path_prefix = optarg;
2212 break;
2213 case 'q':
2214 verbosity = -1;
2215 break;
2216 default:
2217 usage_checkout();
2218 /* NOTREACHED */
2222 argc -= optind;
2223 argv += optind;
2225 if (argc == 1) {
2226 char *base, *dotgit;
2227 const char *path;
2228 repo_path = realpath(argv[0], NULL);
2229 if (repo_path == NULL)
2230 return got_error_from_errno2("realpath", argv[0]);
2231 cwd = getcwd(NULL, 0);
2232 if (cwd == NULL) {
2233 error = got_error_from_errno("getcwd");
2234 goto done;
2236 if (path_prefix[0])
2237 path = path_prefix;
2238 else
2239 path = repo_path;
2240 error = got_path_basename(&base, path);
2241 if (error)
2242 goto done;
2243 dotgit = strstr(base, ".git");
2244 if (dotgit)
2245 *dotgit = '\0';
2246 if (asprintf(&worktree_path, "%s/%s", cwd, base) == -1) {
2247 error = got_error_from_errno("asprintf");
2248 free(base);
2249 goto done;
2251 free(base);
2252 } else if (argc == 2) {
2253 repo_path = realpath(argv[0], NULL);
2254 if (repo_path == NULL) {
2255 error = got_error_from_errno2("realpath", argv[0]);
2256 goto done;
2258 worktree_path = realpath(argv[1], NULL);
2259 if (worktree_path == NULL) {
2260 if (errno != ENOENT) {
2261 error = got_error_from_errno2("realpath",
2262 argv[1]);
2263 goto done;
2265 worktree_path = strdup(argv[1]);
2266 if (worktree_path == NULL) {
2267 error = got_error_from_errno("strdup");
2268 goto done;
2271 } else
2272 usage_checkout();
2274 got_path_strip_trailing_slashes(repo_path);
2275 got_path_strip_trailing_slashes(worktree_path);
2277 error = got_repo_pack_fds_open(&pack_fds);
2278 if (error != NULL)
2279 goto done;
2281 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
2282 if (error != NULL)
2283 goto done;
2285 /* Pre-create work tree path for unveil(2) */
2286 error = got_path_mkdir(worktree_path);
2287 if (error) {
2288 if (!(error->code == GOT_ERR_ERRNO && errno == EISDIR) &&
2289 !(error->code == GOT_ERR_ERRNO && errno == EEXIST))
2290 goto done;
2291 if (!allow_nonempty &&
2292 !got_path_dir_is_empty(worktree_path)) {
2293 error = got_error_path(worktree_path,
2294 GOT_ERR_DIR_NOT_EMPTY);
2295 goto done;
2299 error = apply_unveil(got_repo_get_path(repo), 0, worktree_path);
2300 if (error)
2301 goto done;
2303 error = got_ref_open(&head_ref, repo, branch_name, 0);
2304 if (error != NULL)
2305 goto done;
2307 error = got_worktree_init(worktree_path, head_ref, path_prefix,
2308 GOT_WORKTREE_CVG_DIR, repo);
2309 if (error != NULL && !(error->code == GOT_ERR_ERRNO && errno == EEXIST))
2310 goto done;
2312 error = got_worktree_open(&worktree, worktree_path, GOT_WORKTREE_CVG_DIR);
2313 if (error != NULL)
2314 goto done;
2316 error = got_worktree_match_path_prefix(&same_path_prefix, worktree,
2317 path_prefix);
2318 if (error != NULL)
2319 goto done;
2320 if (!same_path_prefix) {
2321 error = got_error(GOT_ERR_PATH_PREFIX);
2322 goto done;
2325 if (commit_id_str) {
2326 struct got_reflist_head refs;
2327 TAILQ_INIT(&refs);
2328 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
2329 NULL);
2330 if (error)
2331 goto done;
2332 error = got_repo_match_object_id(&commit_id, NULL,
2333 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
2334 got_ref_list_free(&refs);
2335 if (error)
2336 goto done;
2337 error = check_linear_ancestry(commit_id,
2338 got_worktree_get_base_commit_id(worktree), 0, repo);
2339 if (error != NULL) {
2340 if (error->code == GOT_ERR_ANCESTRY) {
2341 error = checkout_ancestry_error(
2342 head_ref, commit_id_str);
2344 goto done;
2346 error = check_same_branch(commit_id, head_ref, repo);
2347 if (error) {
2348 if (error->code == GOT_ERR_ANCESTRY) {
2349 error = checkout_ancestry_error(
2350 head_ref, commit_id_str);
2352 goto done;
2354 error = got_worktree_set_base_commit_id(worktree, repo,
2355 commit_id);
2356 if (error)
2357 goto done;
2358 /* Expand potentially abbreviated commit ID string. */
2359 free(commit_id_str);
2360 error = got_object_id_str(&commit_id_str, commit_id);
2361 if (error)
2362 goto done;
2363 } else {
2364 commit_id = got_object_id_dup(
2365 got_worktree_get_base_commit_id(worktree));
2366 if (commit_id == NULL) {
2367 error = got_error_from_errno("got_object_id_dup");
2368 goto done;
2370 error = got_object_id_str(&commit_id_str, commit_id);
2371 if (error)
2372 goto done;
2375 error = got_pathlist_append(&paths, "", NULL);
2376 if (error)
2377 goto done;
2378 cpa.worktree_path = worktree_path;
2379 cpa.had_base_commit_ref_error = 0;
2380 cpa.verbosity = verbosity;
2381 error = got_worktree_checkout_files(worktree, &paths, repo,
2382 checkout_progress, &cpa, check_cancelled, NULL);
2383 if (error != NULL)
2384 goto done;
2386 if (got_ref_is_symbolic(head_ref)) {
2387 error = got_ref_resolve_symbolic(&ref, repo, head_ref);
2388 if (error)
2389 goto done;
2390 refname = got_ref_get_name(ref);
2391 } else
2392 refname = got_ref_get_name(head_ref);
2393 printf("Checked out %s: %s\n", refname, commit_id_str);
2394 printf("Now shut up and hack\n");
2395 if (cpa.had_base_commit_ref_error)
2396 show_worktree_base_ref_warning();
2397 done:
2398 if (pack_fds) {
2399 const struct got_error *pack_err =
2400 got_repo_pack_fds_close(pack_fds);
2401 if (error == NULL)
2402 error = pack_err;
2404 if (head_ref)
2405 got_ref_close(head_ref);
2406 if (ref)
2407 got_ref_close(ref);
2408 if (repo) {
2409 const struct got_error *close_err = got_repo_close(repo);
2410 if (error == NULL)
2411 error = close_err;
2413 got_pathlist_free(&paths, GOT_PATHLIST_FREE_NONE);
2414 free(commit_id_str);
2415 free(commit_id);
2416 free(repo_path);
2417 free(worktree_path);
2418 free(cwd);
2419 return error;
2422 struct got_update_progress_arg {
2423 int did_something;
2424 int conflicts;
2425 int obstructed;
2426 int not_updated;
2427 int missing;
2428 int not_deleted;
2429 int unversioned;
2430 int verbosity;
2433 static void
2434 print_update_progress_stats(struct got_update_progress_arg *upa)
2436 if (!upa->did_something)
2437 return;
2439 if (upa->conflicts > 0)
2440 printf("Files with new merge conflicts: %d\n", upa->conflicts);
2441 if (upa->obstructed > 0)
2442 printf("File paths obstructed by a non-regular file: %d\n",
2443 upa->obstructed);
2444 if (upa->not_updated > 0)
2445 printf("Files not updated because of existing merge "
2446 "conflicts: %d\n", upa->not_updated);
2450 * The meaning of some status codes differs between merge-style operations and
2451 * update operations. For example, the ! status code means "file was missing"
2452 * if changes were merged into the work tree, and "missing file was restored"
2453 * if the work tree was updated. This function should be used by any operation
2454 * which merges changes into the work tree without updating the work tree.
2456 static void
2457 print_merge_progress_stats(struct got_update_progress_arg *upa)
2459 if (!upa->did_something)
2460 return;
2462 if (upa->conflicts > 0)
2463 printf("Files with new merge conflicts: %d\n", upa->conflicts);
2464 if (upa->obstructed > 0)
2465 printf("File paths obstructed by a non-regular file: %d\n",
2466 upa->obstructed);
2467 if (upa->missing > 0)
2468 printf("Files which had incoming changes but could not be "
2469 "found in the work tree: %d\n", upa->missing);
2470 if (upa->not_deleted > 0)
2471 printf("Files not deleted due to differences in deleted "
2472 "content: %d\n", upa->not_deleted);
2473 if (upa->unversioned > 0)
2474 printf("Files not merged because an unversioned file was "
2475 "found in the work tree: %d\n", upa->unversioned);
2478 __dead static void
2479 usage_update(void)
2481 fprintf(stderr, "usage: %s update [-qtvX] [-c commit] [-r remote] "
2482 "[path ...]\n", getprogname());
2483 exit(1);
2486 static const struct got_error *
2487 update_progress(void *arg, unsigned char status, const char *path)
2489 struct got_update_progress_arg *upa = arg;
2491 if (status == GOT_STATUS_EXISTS ||
2492 status == GOT_STATUS_BASE_REF_ERR)
2493 return NULL;
2495 upa->did_something = 1;
2497 /* Base commit bump happens silently. */
2498 if (status == GOT_STATUS_BUMP_BASE)
2499 return NULL;
2501 if (status == GOT_STATUS_CONFLICT)
2502 upa->conflicts++;
2503 if (status == GOT_STATUS_OBSTRUCTED)
2504 upa->obstructed++;
2505 if (status == GOT_STATUS_CANNOT_UPDATE)
2506 upa->not_updated++;
2507 if (status == GOT_STATUS_MISSING)
2508 upa->missing++;
2509 if (status == GOT_STATUS_CANNOT_DELETE)
2510 upa->not_deleted++;
2511 if (status == GOT_STATUS_UNVERSIONED)
2512 upa->unversioned++;
2514 while (path[0] == '/')
2515 path++;
2516 if (upa->verbosity >= 0)
2517 printf("%c %s\n", status, path);
2519 return NULL;
2522 static const struct got_error *
2523 check_rebase_or_histedit_in_progress(struct got_worktree *worktree)
2525 const struct got_error *err;
2526 int in_progress;
2528 err = got_worktree_rebase_in_progress(&in_progress, worktree);
2529 if (err)
2530 return err;
2531 if (in_progress)
2532 return got_error(GOT_ERR_REBASING);
2534 err = got_worktree_histedit_in_progress(&in_progress, worktree);
2535 if (err)
2536 return err;
2537 if (in_progress)
2538 return got_error(GOT_ERR_HISTEDIT_BUSY);
2540 return NULL;
2543 static const struct got_error *
2544 check_merge_in_progress(struct got_worktree *worktree,
2545 struct got_repository *repo)
2547 const struct got_error *err;
2548 int in_progress;
2550 err = got_worktree_merge_in_progress(&in_progress, worktree, repo);
2551 if (err)
2552 return err;
2553 if (in_progress)
2554 return got_error(GOT_ERR_MERGE_BUSY);
2556 return NULL;
2559 static const struct got_error *
2560 get_worktree_paths_from_argv(struct got_pathlist_head *paths, int argc,
2561 char *argv[], struct got_worktree *worktree)
2563 const struct got_error *err = NULL;
2564 char *path;
2565 struct got_pathlist_entry *new;
2566 int i;
2568 if (argc == 0) {
2569 path = strdup("");
2570 if (path == NULL)
2571 return got_error_from_errno("strdup");
2572 return got_pathlist_append(paths, path, NULL);
2575 for (i = 0; i < argc; i++) {
2576 err = got_worktree_resolve_path(&path, worktree, argv[i]);
2577 if (err)
2578 break;
2579 err = got_pathlist_insert(&new, paths, path, NULL);
2580 if (err || new == NULL /* duplicate */) {
2581 free(path);
2582 if (err)
2583 break;
2587 return err;
2590 static const struct got_error *
2591 wrap_not_worktree_error(const struct got_error *orig_err,
2592 const char *cmdname, const char *path)
2594 const struct got_error *err;
2595 struct got_repository *repo;
2596 static char msg[512];
2597 int *pack_fds = NULL;
2599 err = got_repo_pack_fds_open(&pack_fds);
2600 if (err)
2601 return err;
2603 err = got_repo_open(&repo, path, NULL, pack_fds);
2604 if (err)
2605 return orig_err;
2607 snprintf(msg, sizeof(msg),
2608 "'got %s' needs a work tree in addition to a git repository\n"
2609 "Work trees can be checked out from this Git repository with "
2610 "'got checkout'.\n"
2611 "The got(1) manual page contains more information.", cmdname);
2612 err = got_error_msg(GOT_ERR_NOT_WORKTREE, msg);
2613 if (repo) {
2614 const struct got_error *close_err = got_repo_close(repo);
2615 if (err == NULL)
2616 err = close_err;
2618 if (pack_fds) {
2619 const struct got_error *pack_err =
2620 got_repo_pack_fds_close(pack_fds);
2621 if (err == NULL)
2622 err = pack_err;
2624 return err;
2627 static const struct got_error *
2628 cmd_update(int argc, char *argv[])
2630 const struct got_error *error = NULL, *unlock_err;
2631 char *worktree_path = NULL;
2632 const char *repo_path = NULL;
2633 const char *remote_name = NULL;
2634 char *proto = NULL, *host = NULL, *port = NULL;
2635 char *repo_name = NULL, *server_path = NULL;
2636 const struct got_remote_repo *remotes, *remote = NULL;
2637 int nremotes;
2638 char *id_str = NULL;
2639 struct got_repository *repo = NULL;
2640 struct got_worktree *worktree = NULL;
2641 const struct got_gotconfig *repo_conf = NULL, *worktree_conf = NULL;
2642 struct got_pathlist_head paths, refs, symrefs;
2643 struct got_pathlist_head wanted_branches, wanted_refs;
2644 struct got_pathlist_entry *pe;
2645 struct got_reflist_head remote_refs;
2646 struct got_reflist_entry *re;
2647 struct got_object_id *pack_hash = NULL;
2648 int i, ch, fetchfd = -1, fetchstatus;
2649 pid_t fetchpid = -1;
2650 struct got_fetch_progress_arg fpa;
2651 struct got_update_progress_arg upa;
2652 int verbosity = 0;
2653 int delete_remote = 0;
2654 int replace_tags = 0;
2655 int *pack_fds = NULL;
2656 const char *remote_head = NULL, *worktree_branch = NULL;
2657 struct got_object_id *commit_id = NULL;
2658 char *commit_id_str = NULL;
2659 const char *refname;
2660 struct got_reference *head_ref = NULL;
2662 TAILQ_INIT(&paths);
2663 TAILQ_INIT(&refs);
2664 TAILQ_INIT(&symrefs);
2665 TAILQ_INIT(&remote_refs);
2666 TAILQ_INIT(&wanted_branches);
2667 TAILQ_INIT(&wanted_refs);
2669 while ((ch = getopt(argc, argv, "c:qr:vX")) != -1) {
2670 switch (ch) {
2671 case 'c':
2672 commit_id_str = strdup(optarg);
2673 if (commit_id_str == NULL)
2674 return got_error_from_errno("strdup");
2675 break;
2676 case 't':
2677 replace_tags = 1;
2678 break;
2679 case 'q':
2680 verbosity = -1;
2681 break;
2682 case 'r':
2683 remote_name = optarg;
2684 break;
2685 case 'v':
2686 if (verbosity < 0)
2687 verbosity = 0;
2688 else if (verbosity < 3)
2689 verbosity++;
2690 break;
2691 case 'X':
2692 delete_remote = 1;
2693 break;
2694 default:
2695 usage_update();
2696 break;
2699 argc -= optind;
2700 argv += optind;
2702 if (delete_remote) {
2703 if (replace_tags)
2704 option_conflict('X', 't');
2705 if (remote_name == NULL)
2706 errx(1, "-X option requires a remote name");
2708 if (remote_name == NULL)
2709 remote_name = GOT_FETCH_DEFAULT_REMOTE_NAME;
2711 worktree_path = getcwd(NULL, 0);
2712 if (worktree_path == NULL) {
2713 error = got_error_from_errno("getcwd");
2714 goto done;
2716 error = got_worktree_open(&worktree, worktree_path, GOT_WORKTREE_CVG_DIR);
2717 if (error) {
2718 if (error->code == GOT_ERR_NOT_WORKTREE)
2719 error = wrap_not_worktree_error(error, "update",
2720 worktree_path);
2721 goto done;
2723 repo_path = got_worktree_get_repo_path(worktree);
2725 error = got_repo_pack_fds_open(&pack_fds);
2726 if (error != NULL)
2727 goto done;
2729 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
2730 if (error)
2731 goto done;
2733 error = check_rebase_or_histedit_in_progress(worktree);
2734 if (error)
2735 goto done;
2736 error = check_merge_in_progress(worktree, repo);
2737 if (error)
2738 goto done;
2740 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
2741 if (error)
2742 goto done;
2744 worktree_conf = got_worktree_get_gotconfig(worktree);
2745 if (worktree_conf) {
2746 got_gotconfig_get_remotes(&nremotes, &remotes,
2747 worktree_conf);
2748 for (i = 0; i < nremotes; i++) {
2749 if (strcmp(remotes[i].name, remote_name) == 0) {
2750 remote = &remotes[i];
2751 break;
2756 if (remote == NULL) {
2757 repo_conf = got_repo_get_gotconfig(repo);
2758 if (repo_conf) {
2759 got_gotconfig_get_remotes(&nremotes, &remotes,
2760 repo_conf);
2761 for (i = 0; i < nremotes; i++) {
2762 if (strcmp(remotes[i].name, remote_name) == 0) {
2763 remote = &remotes[i];
2764 break;
2769 if (remote == NULL) {
2770 got_repo_get_gitconfig_remotes(&nremotes, &remotes, repo);
2771 for (i = 0; i < nremotes; i++) {
2772 if (strcmp(remotes[i].name, remote_name) == 0) {
2773 remote = &remotes[i];
2774 break;
2778 if (remote == NULL) {
2779 error = got_error_path(remote_name, GOT_ERR_NO_REMOTE);
2780 goto done;
2783 error = got_dial_parse_uri(&proto, &host, &port, &server_path,
2784 &repo_name, remote->fetch_url);
2785 if (error)
2786 goto done;
2788 if (strcmp(proto, "git") == 0) {
2789 #ifndef PROFILE
2790 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
2791 "sendfd dns inet unveil", NULL) == -1)
2792 err(1, "pledge");
2793 #endif
2794 } else if (strcmp(proto, "git+ssh") == 0 ||
2795 strcmp(proto, "ssh") == 0) {
2796 #ifndef PROFILE
2797 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
2798 "sendfd unveil", NULL) == -1)
2799 err(1, "pledge");
2800 #endif
2801 } else if (strcmp(proto, "http") == 0 ||
2802 strcmp(proto, "git+http") == 0) {
2803 error = got_error_path(proto, GOT_ERR_NOT_IMPL);
2804 goto done;
2805 } else {
2806 error = got_error_path(proto, GOT_ERR_BAD_PROTO);
2807 goto done;
2810 error = got_dial_apply_unveil(proto);
2811 if (error)
2812 goto done;
2814 error = apply_unveil(got_repo_get_path(repo), 0,
2815 got_worktree_get_root_path(worktree));
2816 if (error)
2817 goto done;
2819 if (verbosity >= 0) {
2820 printf("Connecting to \"%s\" %s://%s%s%s%s%s\n",
2821 remote->name, proto, host,
2822 port ? ":" : "", port ? port : "",
2823 *server_path == '/' ? "" : "/", server_path);
2826 error = got_fetch_connect(&fetchpid, &fetchfd, proto, host, port,
2827 server_path, verbosity);
2828 if (error)
2829 goto done;
2832 * If set, get this remote's HEAD ref target so
2833 * if it has changed on the server we can fetch it.
2835 error = got_ref_list(&remote_refs, repo, "refs/remotes",
2836 got_ref_cmp_by_name, repo);
2837 if (error)
2838 goto done;
2840 TAILQ_FOREACH(re, &remote_refs, entry) {
2841 const char *remote_refname, *remote_target;
2842 size_t remote_name_len;
2844 if (!got_ref_is_symbolic(re->ref))
2845 continue;
2847 remote_name_len = strlen(remote->name);
2848 remote_refname = got_ref_get_name(re->ref);
2850 /* we only want refs/remotes/$remote->name/HEAD */
2851 if (strncmp(remote_refname + 13, remote->name,
2852 remote_name_len) != 0)
2853 continue;
2855 if (strcmp(remote_refname + remote_name_len + 14,
2856 GOT_REF_HEAD) != 0)
2857 continue;
2860 * Take the name itself because we already
2861 * only match with refs/heads/ in fetch_pack().
2863 remote_target = got_ref_get_symref_target(re->ref);
2864 remote_head = remote_target + remote_name_len + 14;
2865 break;
2868 refname = got_worktree_get_head_ref_name(worktree);
2869 if (strncmp(refname, "refs/heads/", 11) == 0)
2870 worktree_branch = refname;
2872 fpa.last_scaled_size[0] = '\0';
2873 fpa.last_p_indexed = -1;
2874 fpa.last_p_resolved = -1;
2875 fpa.verbosity = verbosity;
2876 fpa.repo = repo;
2877 fpa.create_configs = 0;
2878 fpa.configs_created = 0;
2879 memset(&fpa.config_info, 0, sizeof(fpa.config_info));
2881 error = got_fetch_pack(&pack_hash, &refs, &symrefs, remote->name,
2882 remote->mirror_references, 0, &wanted_branches, &wanted_refs,
2883 0, verbosity, fetchfd, repo, worktree_branch, remote_head,
2884 0, fetch_progress, &fpa);
2885 if (error)
2886 goto done;
2888 if (pack_hash != NULL && verbosity >= 0) {
2889 error = got_object_id_str(&id_str, pack_hash);
2890 if (error)
2891 goto done;
2892 printf("\nFetched %s.pack\n", id_str);
2893 free(id_str);
2894 id_str = NULL;
2897 /* Update references provided with the pack file. */
2898 TAILQ_FOREACH(pe, &refs, entry) {
2899 const char *refname = pe->path;
2900 struct got_object_id *id = pe->data;
2901 struct got_reference *ref;
2903 if (is_wanted_ref(&wanted_refs, refname)) {
2904 error = update_wanted_ref(refname, id,
2905 remote->name, verbosity, repo);
2906 if (error)
2907 goto done;
2908 continue;
2911 error = got_ref_open(&ref, repo, refname, 1);
2912 if (error) {
2913 if (error->code != GOT_ERR_NOT_REF)
2914 goto done;
2915 error = create_ref(refname, id, verbosity,
2916 repo);
2917 if (error)
2918 goto done;
2919 } else {
2920 error = update_ref(ref, id, replace_tags,
2921 verbosity-1, repo);
2922 unlock_err = got_ref_unlock(ref);
2923 if (unlock_err && error == NULL)
2924 error = unlock_err;
2925 got_ref_close(ref);
2926 if (error)
2927 goto done;
2931 /* Update worktree */
2932 error = got_ref_open(&head_ref, repo,
2933 got_worktree_get_head_ref_name(worktree), 0);
2934 if (error != NULL)
2935 goto done;
2936 if (commit_id_str == NULL) {
2937 error = got_ref_resolve(&commit_id, repo, head_ref);
2938 if (error != NULL)
2939 goto done;
2940 error = got_object_id_str(&commit_id_str, commit_id);
2941 if (error != NULL)
2942 goto done;
2943 } else {
2944 struct got_reflist_head refs;
2945 TAILQ_INIT(&refs);
2946 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
2947 NULL);
2948 if (error)
2949 goto done;
2950 error = got_repo_match_object_id(&commit_id, NULL,
2951 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
2952 got_ref_list_free(&refs);
2953 free(commit_id_str);
2954 commit_id_str = NULL;
2955 if (error)
2956 goto done;
2957 error = got_object_id_str(&commit_id_str, commit_id);
2958 if (error)
2959 goto done;
2963 error = check_linear_ancestry(commit_id,
2964 got_worktree_get_base_commit_id(worktree), 0, repo);
2965 if (error != NULL) {
2966 if (error->code == GOT_ERR_ANCESTRY)
2967 error = got_error(GOT_ERR_BRANCH_MOVED);
2968 goto done;
2970 error = check_same_branch(commit_id, head_ref, repo);
2971 if (error)
2972 goto done;
2974 if (got_object_id_cmp(got_worktree_get_base_commit_id(worktree),
2975 commit_id) != 0) {
2976 error = got_worktree_set_base_commit_id(worktree, repo,
2977 commit_id);
2978 if (error)
2979 goto done;
2982 memset(&upa, 0, sizeof(upa));
2983 upa.verbosity = verbosity;
2984 error = got_worktree_checkout_files(worktree, &paths, repo,
2985 update_progress, &upa, check_cancelled, NULL);
2986 if (error != NULL)
2987 goto done;
2989 if (upa.did_something) {
2990 printf("Updated to %s: %s\n",
2991 got_worktree_get_head_ref_name(worktree), commit_id_str);
2992 } else
2993 printf("Already up-to-date\n");
2995 print_update_progress_stats(&upa);
2996 done:
2997 if (fetchpid > 0) {
2998 if (kill(fetchpid, SIGTERM) == -1)
2999 error = got_error_from_errno("kill");
3000 if (waitpid(fetchpid, &fetchstatus, 0) == -1 && error == NULL)
3001 error = got_error_from_errno("waitpid");
3003 if (fetchfd != -1 && close(fetchfd) == -1 && error == NULL)
3004 error = got_error_from_errno("close");
3005 if (repo) {
3006 const struct got_error *close_err = got_repo_close(repo);
3007 if (error == NULL)
3008 error = close_err;
3010 if (worktree)
3011 got_worktree_close(worktree);
3012 if (pack_fds) {
3013 const struct got_error *pack_err =
3014 got_repo_pack_fds_close(pack_fds);
3015 if (error == NULL)
3016 error = pack_err;
3018 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
3019 got_pathlist_free(&refs, GOT_PATHLIST_FREE_ALL);
3020 got_pathlist_free(&symrefs, GOT_PATHLIST_FREE_ALL);
3021 got_pathlist_free(&wanted_branches, GOT_PATHLIST_FREE_NONE);
3022 got_pathlist_free(&wanted_refs, GOT_PATHLIST_FREE_NONE);
3023 got_ref_list_free(&remote_refs);
3024 free(id_str);
3025 free(worktree_path);
3026 free(pack_hash);
3027 free(proto);
3028 free(host);
3029 free(port);
3030 free(server_path);
3031 free(repo_name);
3032 free(commit_id);
3033 free(commit_id_str);
3034 return error;
3037 static const struct got_error *
3038 diff_blobs(struct got_object_id *blob_id1, struct got_object_id *blob_id2,
3039 const char *path, int diff_context, int ignore_whitespace,
3040 int force_text_diff, struct got_diffstat_cb_arg *dsa,
3041 struct got_repository *repo, FILE *outfile)
3043 const struct got_error *err = NULL;
3044 struct got_blob_object *blob1 = NULL, *blob2 = NULL;
3045 FILE *f1 = NULL, *f2 = NULL;
3046 int fd1 = -1, fd2 = -1;
3048 fd1 = got_opentempfd();
3049 if (fd1 == -1)
3050 return got_error_from_errno("got_opentempfd");
3051 fd2 = got_opentempfd();
3052 if (fd2 == -1) {
3053 err = got_error_from_errno("got_opentempfd");
3054 goto done;
3057 if (blob_id1) {
3058 err = got_object_open_as_blob(&blob1, repo, blob_id1, 8192,
3059 fd1);
3060 if (err)
3061 goto done;
3064 err = got_object_open_as_blob(&blob2, repo, blob_id2, 8192, fd2);
3065 if (err)
3066 goto done;
3068 f1 = got_opentemp();
3069 if (f1 == NULL) {
3070 err = got_error_from_errno("got_opentemp");
3071 goto done;
3073 f2 = got_opentemp();
3074 if (f2 == NULL) {
3075 err = got_error_from_errno("got_opentemp");
3076 goto done;
3079 while (path[0] == '/')
3080 path++;
3081 err = got_diff_blob(NULL, NULL, blob1, blob2, f1, f2, path, path,
3082 GOT_DIFF_ALGORITHM_PATIENCE, diff_context, ignore_whitespace,
3083 force_text_diff, dsa, outfile);
3084 done:
3085 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
3086 err = got_error_from_errno("close");
3087 if (blob1)
3088 got_object_blob_close(blob1);
3089 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
3090 err = got_error_from_errno("close");
3091 if (blob2)
3092 got_object_blob_close(blob2);
3093 if (f1 && fclose(f1) == EOF && err == NULL)
3094 err = got_error_from_errno("fclose");
3095 if (f2 && fclose(f2) == EOF && err == NULL)
3096 err = got_error_from_errno("fclose");
3097 return err;
3100 static const struct got_error *
3101 diff_trees(struct got_object_id *tree_id1, struct got_object_id *tree_id2,
3102 const char *path, int diff_context, int ignore_whitespace,
3103 int force_text_diff, struct got_diffstat_cb_arg *dsa,
3104 struct got_repository *repo, FILE *outfile)
3106 const struct got_error *err = NULL;
3107 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
3108 struct got_diff_blob_output_unidiff_arg arg;
3109 FILE *f1 = NULL, *f2 = NULL;
3110 int fd1 = -1, fd2 = -1;
3112 if (tree_id1) {
3113 err = got_object_open_as_tree(&tree1, repo, tree_id1);
3114 if (err)
3115 goto done;
3116 fd1 = got_opentempfd();
3117 if (fd1 == -1) {
3118 err = got_error_from_errno("got_opentempfd");
3119 goto done;
3123 err = got_object_open_as_tree(&tree2, repo, tree_id2);
3124 if (err)
3125 goto done;
3127 f1 = got_opentemp();
3128 if (f1 == NULL) {
3129 err = got_error_from_errno("got_opentemp");
3130 goto done;
3133 f2 = got_opentemp();
3134 if (f2 == NULL) {
3135 err = got_error_from_errno("got_opentemp");
3136 goto done;
3138 fd2 = got_opentempfd();
3139 if (fd2 == -1) {
3140 err = got_error_from_errno("got_opentempfd");
3141 goto done;
3143 arg.diff_context = diff_context;
3144 arg.ignore_whitespace = ignore_whitespace;
3145 arg.force_text_diff = force_text_diff;
3146 arg.diffstat = dsa;
3147 arg.diff_algo = GOT_DIFF_ALGORITHM_PATIENCE;
3148 arg.outfile = outfile;
3149 arg.lines = NULL;
3150 arg.nlines = 0;
3151 while (path[0] == '/')
3152 path++;
3153 err = got_diff_tree(tree1, tree2, f1, f2, fd1, fd2, path, path, repo,
3154 got_diff_blob_output_unidiff, &arg, 1);
3155 done:
3156 if (tree1)
3157 got_object_tree_close(tree1);
3158 if (tree2)
3159 got_object_tree_close(tree2);
3160 if (f1 && fclose(f1) == EOF && err == NULL)
3161 err = got_error_from_errno("fclose");
3162 if (f2 && fclose(f2) == EOF && err == NULL)
3163 err = got_error_from_errno("fclose");
3164 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
3165 err = got_error_from_errno("close");
3166 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
3167 err = got_error_from_errno("close");
3168 return err;
3171 static const struct got_error *
3172 get_changed_paths(struct got_pathlist_head *paths,
3173 struct got_commit_object *commit, struct got_repository *repo,
3174 struct got_diffstat_cb_arg *dsa)
3176 const struct got_error *err = NULL;
3177 struct got_object_id *tree_id1 = NULL, *tree_id2 = NULL;
3178 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
3179 struct got_object_qid *qid;
3180 got_diff_blob_cb cb = got_diff_tree_collect_changed_paths;
3181 FILE *f1 = NULL, *f2 = NULL;
3182 int fd1 = -1, fd2 = -1;
3184 if (dsa) {
3185 cb = got_diff_tree_compute_diffstat;
3187 f1 = got_opentemp();
3188 if (f1 == NULL) {
3189 err = got_error_from_errno("got_opentemp");
3190 goto done;
3192 f2 = got_opentemp();
3193 if (f2 == NULL) {
3194 err = got_error_from_errno("got_opentemp");
3195 goto done;
3197 fd1 = got_opentempfd();
3198 if (fd1 == -1) {
3199 err = got_error_from_errno("got_opentempfd");
3200 goto done;
3202 fd2 = got_opentempfd();
3203 if (fd2 == -1) {
3204 err = got_error_from_errno("got_opentempfd");
3205 goto done;
3209 qid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
3210 if (qid != NULL) {
3211 struct got_commit_object *pcommit;
3212 err = got_object_open_as_commit(&pcommit, repo,
3213 &qid->id);
3214 if (err)
3215 return err;
3217 tree_id1 = got_object_id_dup(
3218 got_object_commit_get_tree_id(pcommit));
3219 if (tree_id1 == NULL) {
3220 got_object_commit_close(pcommit);
3221 return got_error_from_errno("got_object_id_dup");
3223 got_object_commit_close(pcommit);
3227 if (tree_id1) {
3228 err = got_object_open_as_tree(&tree1, repo, tree_id1);
3229 if (err)
3230 goto done;
3233 tree_id2 = got_object_commit_get_tree_id(commit);
3234 err = got_object_open_as_tree(&tree2, repo, tree_id2);
3235 if (err)
3236 goto done;
3238 err = got_diff_tree(tree1, tree2, f1, f2, fd1, fd2, "", "", repo,
3239 cb, dsa ? (void *)dsa : paths, dsa ? 1 : 0);
3240 done:
3241 if (tree1)
3242 got_object_tree_close(tree1);
3243 if (tree2)
3244 got_object_tree_close(tree2);
3245 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
3246 err = got_error_from_errno("close");
3247 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
3248 err = got_error_from_errno("close");
3249 if (f1 && fclose(f1) == EOF && err == NULL)
3250 err = got_error_from_errno("fclose");
3251 if (f2 && fclose(f2) == EOF && err == NULL)
3252 err = got_error_from_errno("fclose");
3253 free(tree_id1);
3254 return err;
3257 static const struct got_error *
3258 print_patch(struct got_commit_object *commit, struct got_object_id *id,
3259 const char *path, int diff_context, struct got_diffstat_cb_arg *dsa,
3260 struct got_repository *repo, FILE *outfile)
3262 const struct got_error *err = NULL;
3263 struct got_commit_object *pcommit = NULL;
3264 char *id_str1 = NULL, *id_str2 = NULL;
3265 struct got_object_id *obj_id1 = NULL, *obj_id2 = NULL;
3266 struct got_object_qid *qid;
3268 qid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
3269 if (qid != NULL) {
3270 err = got_object_open_as_commit(&pcommit, repo,
3271 &qid->id);
3272 if (err)
3273 return err;
3274 err = got_object_id_str(&id_str1, &qid->id);
3275 if (err)
3276 goto done;
3279 err = got_object_id_str(&id_str2, id);
3280 if (err)
3281 goto done;
3283 if (path && path[0] != '\0') {
3284 int obj_type;
3285 err = got_object_id_by_path(&obj_id2, repo, commit, path);
3286 if (err)
3287 goto done;
3288 if (pcommit) {
3289 err = got_object_id_by_path(&obj_id1, repo,
3290 pcommit, path);
3291 if (err) {
3292 if (err->code != GOT_ERR_NO_TREE_ENTRY) {
3293 free(obj_id2);
3294 goto done;
3298 err = got_object_get_type(&obj_type, repo, obj_id2);
3299 if (err) {
3300 free(obj_id2);
3301 goto done;
3303 fprintf(outfile,
3304 "diff %s %s\n", id_str1 ? id_str1 : "/dev/null", id_str2);
3305 fprintf(outfile, "commit - %s\n",
3306 id_str1 ? id_str1 : "/dev/null");
3307 fprintf(outfile, "commit + %s\n", id_str2);
3308 switch (obj_type) {
3309 case GOT_OBJ_TYPE_BLOB:
3310 err = diff_blobs(obj_id1, obj_id2, path, diff_context,
3311 0, 0, dsa, repo, outfile);
3312 break;
3313 case GOT_OBJ_TYPE_TREE:
3314 err = diff_trees(obj_id1, obj_id2, path, diff_context,
3315 0, 0, dsa, repo, outfile);
3316 break;
3317 default:
3318 err = got_error(GOT_ERR_OBJ_TYPE);
3319 break;
3321 free(obj_id1);
3322 free(obj_id2);
3323 } else {
3324 obj_id2 = got_object_commit_get_tree_id(commit);
3325 if (pcommit)
3326 obj_id1 = got_object_commit_get_tree_id(pcommit);
3327 fprintf(outfile,
3328 "diff %s %s\n", id_str1 ? id_str1 : "/dev/null", id_str2);
3329 fprintf(outfile, "commit - %s\n",
3330 id_str1 ? id_str1 : "/dev/null");
3331 fprintf(outfile, "commit + %s\n", id_str2);
3332 err = diff_trees(obj_id1, obj_id2, "", diff_context, 0, 0,
3333 dsa, repo, outfile);
3335 done:
3336 free(id_str1);
3337 free(id_str2);
3338 if (pcommit)
3339 got_object_commit_close(pcommit);
3340 return err;
3343 static char *
3344 get_datestr(time_t *time, char *datebuf)
3346 struct tm mytm, *tm;
3347 char *p, *s;
3349 tm = gmtime_r(time, &mytm);
3350 if (tm == NULL)
3351 return NULL;
3352 s = asctime_r(tm, datebuf);
3353 if (s == NULL)
3354 return NULL;
3355 p = strchr(s, '\n');
3356 if (p)
3357 *p = '\0';
3358 return s;
3361 static const struct got_error *
3362 match_commit(int *have_match, struct got_object_id *id,
3363 struct got_commit_object *commit, regex_t *regex)
3365 const struct got_error *err = NULL;
3366 regmatch_t regmatch;
3367 char *id_str = NULL, *logmsg = NULL;
3369 *have_match = 0;
3371 err = got_object_id_str(&id_str, id);
3372 if (err)
3373 return err;
3375 err = got_object_commit_get_logmsg(&logmsg, commit);
3376 if (err)
3377 goto done;
3379 if (regexec(regex, got_object_commit_get_author(commit), 1,
3380 &regmatch, 0) == 0 ||
3381 regexec(regex, got_object_commit_get_committer(commit), 1,
3382 &regmatch, 0) == 0 ||
3383 regexec(regex, id_str, 1, &regmatch, 0) == 0 ||
3384 regexec(regex, logmsg, 1, &regmatch, 0) == 0)
3385 *have_match = 1;
3386 done:
3387 free(id_str);
3388 free(logmsg);
3389 return err;
3392 static void
3393 match_changed_paths(int *have_match, struct got_pathlist_head *changed_paths,
3394 regex_t *regex)
3396 regmatch_t regmatch;
3397 struct got_pathlist_entry *pe;
3399 *have_match = 0;
3401 TAILQ_FOREACH(pe, changed_paths, entry) {
3402 if (regexec(regex, pe->path, 1, &regmatch, 0) == 0) {
3403 *have_match = 1;
3404 break;
3409 static const struct got_error *
3410 match_patch(int *have_match, struct got_commit_object *commit,
3411 struct got_object_id *id, const char *path, int diff_context,
3412 struct got_repository *repo, regex_t *regex, FILE *f)
3414 const struct got_error *err = NULL;
3415 char *line = NULL;
3416 size_t linesize = 0;
3417 regmatch_t regmatch;
3419 *have_match = 0;
3421 err = got_opentemp_truncate(f);
3422 if (err)
3423 return err;
3425 err = print_patch(commit, id, path, diff_context, NULL, repo, f);
3426 if (err)
3427 goto done;
3429 if (fseeko(f, 0L, SEEK_SET) == -1) {
3430 err = got_error_from_errno("fseeko");
3431 goto done;
3434 while (getline(&line, &linesize, f) != -1) {
3435 if (regexec(regex, line, 1, &regmatch, 0) == 0) {
3436 *have_match = 1;
3437 break;
3440 done:
3441 free(line);
3442 return err;
3445 #define GOT_COMMIT_SEP_STR "-----------------------------------------------\n"
3447 static const struct got_error*
3448 build_refs_str(char **refs_str, struct got_reflist_head *refs,
3449 struct got_object_id *id, struct got_repository *repo,
3450 int local_only)
3452 static const struct got_error *err = NULL;
3453 struct got_reflist_entry *re;
3454 char *s;
3455 const char *name;
3457 *refs_str = NULL;
3459 TAILQ_FOREACH(re, refs, entry) {
3460 struct got_tag_object *tag = NULL;
3461 struct got_object_id *ref_id;
3462 int cmp;
3464 name = got_ref_get_name(re->ref);
3465 if (strcmp(name, GOT_REF_HEAD) == 0)
3466 continue;
3467 if (strncmp(name, "refs/", 5) == 0)
3468 name += 5;
3469 if (strncmp(name, "got/", 4) == 0)
3470 continue;
3471 if (strncmp(name, "heads/", 6) == 0)
3472 name += 6;
3473 if (strncmp(name, "remotes/", 8) == 0) {
3474 if (local_only)
3475 continue;
3476 name += 8;
3477 s = strstr(name, "/" GOT_REF_HEAD);
3478 if (s != NULL && strcmp(s, "/" GOT_REF_HEAD) == 0)
3479 continue;
3481 err = got_ref_resolve(&ref_id, repo, re->ref);
3482 if (err)
3483 break;
3484 if (strncmp(name, "tags/", 5) == 0) {
3485 err = got_object_open_as_tag(&tag, repo, ref_id);
3486 if (err) {
3487 if (err->code != GOT_ERR_OBJ_TYPE) {
3488 free(ref_id);
3489 break;
3491 /* Ref points at something other than a tag. */
3492 err = NULL;
3493 tag = NULL;
3496 cmp = got_object_id_cmp(tag ?
3497 got_object_tag_get_object_id(tag) : ref_id, id);
3498 free(ref_id);
3499 if (tag)
3500 got_object_tag_close(tag);
3501 if (cmp != 0)
3502 continue;
3503 s = *refs_str;
3504 if (asprintf(refs_str, "%s%s%s", s ? s : "",
3505 s ? ", " : "", name) == -1) {
3506 err = got_error_from_errno("asprintf");
3507 free(s);
3508 *refs_str = NULL;
3509 break;
3511 free(s);
3514 return err;
3517 static const struct got_error *
3518 print_commit_oneline(struct got_commit_object *commit, struct got_object_id *id,
3519 struct got_repository *repo, struct got_reflist_object_id_map *refs_idmap)
3521 const struct got_error *err = NULL;
3522 char *ref_str = NULL, *id_str = NULL, *logmsg0 = NULL;
3523 char *comma, *s, *nl;
3524 struct got_reflist_head *refs;
3525 char datebuf[12]; /* YYYY-MM-DD + SPACE + NUL */
3526 struct tm tm;
3527 time_t committer_time;
3529 refs = got_reflist_object_id_map_lookup(refs_idmap, id);
3530 if (refs) {
3531 err = build_refs_str(&ref_str, refs, id, repo, 1);
3532 if (err)
3533 return err;
3535 /* Display the first matching ref only. */
3536 if (ref_str && (comma = strchr(ref_str, ',')) != NULL)
3537 *comma = '\0';
3540 if (ref_str == NULL) {
3541 err = got_object_id_str(&id_str, id);
3542 if (err)
3543 return err;
3546 committer_time = got_object_commit_get_committer_time(commit);
3547 if (gmtime_r(&committer_time, &tm) == NULL) {
3548 err = got_error_from_errno("gmtime_r");
3549 goto done;
3551 if (strftime(datebuf, sizeof(datebuf), "%G-%m-%d ", &tm) == 0) {
3552 err = got_error(GOT_ERR_NO_SPACE);
3553 goto done;
3556 err = got_object_commit_get_logmsg(&logmsg0, commit);
3557 if (err)
3558 goto done;
3560 s = logmsg0;
3561 while (isspace((unsigned char)s[0]))
3562 s++;
3564 nl = strchr(s, '\n');
3565 if (nl) {
3566 *nl = '\0';
3569 if (ref_str)
3570 printf("%s%-7s %s\n", datebuf, ref_str, s);
3571 else
3572 printf("%s%.7s %s\n", datebuf, id_str, s);
3574 if (fflush(stdout) != 0 && err == NULL)
3575 err = got_error_from_errno("fflush");
3576 done:
3577 free(id_str);
3578 free(ref_str);
3579 free(logmsg0);
3580 return err;
3583 static const struct got_error *
3584 print_diffstat(struct got_diffstat_cb_arg *dsa, const char *header)
3586 struct got_pathlist_entry *pe;
3588 if (header != NULL)
3589 printf("%s\n", header);
3591 TAILQ_FOREACH(pe, dsa->paths, entry) {
3592 struct got_diff_changed_path *cp = pe->data;
3593 int pad = dsa->max_path_len - pe->path_len + 1;
3595 printf(" %c %s%*c | %*d+ %*d-\n", cp->status, pe->path, pad,
3596 ' ', dsa->add_cols + 1, cp->add, dsa->rm_cols + 1, cp->rm);
3598 printf("\n%d file%s changed, %d insertion%s(+), %d deletion%s(-)\n\n",
3599 dsa->nfiles, dsa->nfiles > 1 ? "s" : "", dsa->ins,
3600 dsa->ins != 1 ? "s" : "", dsa->del, dsa->del != 1 ? "s" : "");
3602 if (fflush(stdout) != 0)
3603 return got_error_from_errno("fflush");
3605 return NULL;
3608 static const struct got_error *
3609 printfile(FILE *f)
3611 char buf[8192];
3612 size_t r;
3614 if (fseeko(f, 0L, SEEK_SET) == -1)
3615 return got_error_from_errno("fseek");
3617 for (;;) {
3618 r = fread(buf, 1, sizeof(buf), f);
3619 if (r == 0) {
3620 if (ferror(f))
3621 return got_error_from_errno("fread");
3622 if (feof(f))
3623 break;
3625 if (fwrite(buf, 1, r, stdout) != r)
3626 return got_ferror(stdout, GOT_ERR_IO);
3629 return NULL;
3632 static const struct got_error *
3633 print_commit(struct got_commit_object *commit, struct got_object_id *id,
3634 struct got_repository *repo, const char *path,
3635 struct got_pathlist_head *changed_paths,
3636 struct got_diffstat_cb_arg *diffstat, int show_patch, int diff_context,
3637 struct got_reflist_object_id_map *refs_idmap, const char *custom_refs_str,
3638 const char *prefix)
3640 const struct got_error *err = NULL;
3641 FILE *f = NULL;
3642 char *id_str, *datestr, *logmsg0, *logmsg, *line;
3643 char datebuf[26];
3644 time_t committer_time;
3645 const char *author, *committer;
3646 char *refs_str = NULL;
3648 err = got_object_id_str(&id_str, id);
3649 if (err)
3650 return err;
3652 if (custom_refs_str == NULL) {
3653 struct got_reflist_head *refs;
3654 refs = got_reflist_object_id_map_lookup(refs_idmap, id);
3655 if (refs) {
3656 err = build_refs_str(&refs_str, refs, id, repo, 0);
3657 if (err)
3658 goto done;
3662 printf(GOT_COMMIT_SEP_STR);
3663 if (custom_refs_str)
3664 printf("%s %s (%s)\n", prefix ? prefix : "commit", id_str,
3665 custom_refs_str);
3666 else
3667 printf("%s %s%s%s%s\n", prefix ? prefix : "commit", id_str,
3668 refs_str ? " (" : "", refs_str ? refs_str : "",
3669 refs_str ? ")" : "");
3670 free(id_str);
3671 id_str = NULL;
3672 free(refs_str);
3673 refs_str = NULL;
3674 printf("from: %s\n", got_object_commit_get_author(commit));
3675 author = got_object_commit_get_author(commit);
3676 committer = got_object_commit_get_committer(commit);
3677 if (strcmp(author, committer) != 0)
3678 printf("via: %s\n", committer);
3679 committer_time = got_object_commit_get_committer_time(commit);
3680 datestr = get_datestr(&committer_time, datebuf);
3681 if (datestr)
3682 printf("date: %s UTC\n", datestr);
3683 if (got_object_commit_get_nparents(commit) > 1) {
3684 const struct got_object_id_queue *parent_ids;
3685 struct got_object_qid *qid;
3686 int n = 1;
3687 parent_ids = got_object_commit_get_parent_ids(commit);
3688 STAILQ_FOREACH(qid, parent_ids, entry) {
3689 err = got_object_id_str(&id_str, &qid->id);
3690 if (err)
3691 goto done;
3692 printf("parent %d: %s\n", n++, id_str);
3693 free(id_str);
3694 id_str = NULL;
3698 err = got_object_commit_get_logmsg(&logmsg0, commit);
3699 if (err)
3700 goto done;
3702 logmsg = logmsg0;
3703 do {
3704 line = strsep(&logmsg, "\n");
3705 if (line)
3706 printf(" %s\n", line);
3707 } while (line);
3708 free(logmsg0);
3710 if (changed_paths && diffstat == NULL) {
3711 struct got_pathlist_entry *pe;
3713 TAILQ_FOREACH(pe, changed_paths, entry) {
3714 struct got_diff_changed_path *cp = pe->data;
3716 printf(" %c %s\n", cp->status, pe->path);
3718 printf("\n");
3720 if (show_patch) {
3721 if (diffstat) {
3722 f = got_opentemp();
3723 if (f == NULL) {
3724 err = got_error_from_errno("got_opentemp");
3725 goto done;
3729 err = print_patch(commit, id, path, diff_context, diffstat,
3730 repo, diffstat == NULL ? stdout : f);
3731 if (err)
3732 goto done;
3734 if (diffstat) {
3735 err = print_diffstat(diffstat, NULL);
3736 if (err)
3737 goto done;
3738 if (show_patch) {
3739 err = printfile(f);
3740 if (err)
3741 goto done;
3744 if (show_patch)
3745 printf("\n");
3747 if (fflush(stdout) != 0 && err == NULL)
3748 err = got_error_from_errno("fflush");
3749 done:
3750 if (f && fclose(f) == EOF && err == NULL)
3751 err = got_error_from_errno("fclose");
3752 free(id_str);
3753 free(refs_str);
3754 return err;
3757 static const struct got_error *
3758 print_commits(struct got_object_id *root_id, struct got_object_id *end_id,
3759 struct got_repository *repo, const char *path, int show_changed_paths,
3760 int show_diffstat, int show_patch, const char *search_pattern,
3761 int diff_context, int limit, int log_branches, int reverse_display_order,
3762 struct got_reflist_object_id_map *refs_idmap, int one_line,
3763 FILE *tmpfile)
3765 const struct got_error *err;
3766 struct got_commit_graph *graph;
3767 regex_t regex;
3768 int have_match;
3769 struct got_object_id_queue reversed_commits;
3770 struct got_object_qid *qid;
3771 struct got_commit_object *commit;
3772 struct got_pathlist_head changed_paths;
3774 STAILQ_INIT(&reversed_commits);
3775 TAILQ_INIT(&changed_paths);
3777 if (search_pattern && regcomp(&regex, search_pattern,
3778 REG_EXTENDED | REG_NOSUB | REG_NEWLINE))
3779 return got_error_msg(GOT_ERR_REGEX, search_pattern);
3781 err = got_commit_graph_open(&graph, path, !log_branches);
3782 if (err)
3783 return err;
3784 err = got_commit_graph_iter_start(graph, root_id, repo,
3785 check_cancelled, NULL);
3786 if (err)
3787 goto done;
3788 for (;;) {
3789 struct got_object_id id;
3790 struct got_diffstat_cb_arg dsa = { 0, 0, 0, 0, 0, 0,
3791 &changed_paths, 0, 0, GOT_DIFF_ALGORITHM_PATIENCE };
3793 if (sigint_received || sigpipe_received)
3794 break;
3796 err = got_commit_graph_iter_next(&id, graph, repo,
3797 check_cancelled, NULL);
3798 if (err) {
3799 if (err->code == GOT_ERR_ITER_COMPLETED)
3800 err = NULL;
3801 break;
3804 err = got_object_open_as_commit(&commit, repo, &id);
3805 if (err)
3806 break;
3808 if ((show_changed_paths || (show_diffstat && !show_patch))
3809 && !reverse_display_order) {
3810 err = get_changed_paths(&changed_paths, commit, repo,
3811 show_diffstat ? &dsa : NULL);
3812 if (err)
3813 break;
3816 if (search_pattern) {
3817 err = match_commit(&have_match, &id, commit, &regex);
3818 if (err) {
3819 got_object_commit_close(commit);
3820 break;
3822 if (have_match == 0 && show_changed_paths)
3823 match_changed_paths(&have_match,
3824 &changed_paths, &regex);
3825 if (have_match == 0 && show_patch) {
3826 err = match_patch(&have_match, commit, &id,
3827 path, diff_context, repo, &regex, tmpfile);
3828 if (err)
3829 break;
3831 if (have_match == 0) {
3832 got_object_commit_close(commit);
3833 got_pathlist_free(&changed_paths,
3834 GOT_PATHLIST_FREE_ALL);
3835 continue;
3839 if (reverse_display_order) {
3840 err = got_object_qid_alloc(&qid, &id);
3841 if (err)
3842 break;
3843 STAILQ_INSERT_HEAD(&reversed_commits, qid, entry);
3844 got_object_commit_close(commit);
3845 } else {
3846 if (one_line)
3847 err = print_commit_oneline(commit, &id,
3848 repo, refs_idmap);
3849 else
3850 err = print_commit(commit, &id, repo, path,
3851 (show_changed_paths || show_diffstat) ?
3852 &changed_paths : NULL,
3853 show_diffstat ? &dsa : NULL, show_patch,
3854 diff_context, refs_idmap, NULL, NULL);
3855 got_object_commit_close(commit);
3856 if (err)
3857 break;
3859 if ((limit && --limit == 0) ||
3860 (end_id && got_object_id_cmp(&id, end_id) == 0))
3861 break;
3863 got_pathlist_free(&changed_paths, GOT_PATHLIST_FREE_ALL);
3865 if (reverse_display_order) {
3866 STAILQ_FOREACH(qid, &reversed_commits, entry) {
3867 struct got_diffstat_cb_arg dsa = { 0, 0, 0, 0, 0, 0,
3868 &changed_paths, 0, 0, GOT_DIFF_ALGORITHM_PATIENCE };
3870 err = got_object_open_as_commit(&commit, repo,
3871 &qid->id);
3872 if (err)
3873 break;
3874 if (show_changed_paths ||
3875 (show_diffstat && !show_patch)) {
3876 err = get_changed_paths(&changed_paths, commit,
3877 repo, show_diffstat ? &dsa : NULL);
3878 if (err)
3879 break;
3881 if (one_line)
3882 err = print_commit_oneline(commit, &qid->id,
3883 repo, refs_idmap);
3884 else
3885 err = print_commit(commit, &qid->id, repo, path,
3886 (show_changed_paths || show_diffstat) ?
3887 &changed_paths : NULL,
3888 show_diffstat ? &dsa : NULL, show_patch,
3889 diff_context, refs_idmap, NULL, NULL);
3890 got_object_commit_close(commit);
3891 if (err)
3892 break;
3893 got_pathlist_free(&changed_paths, GOT_PATHLIST_FREE_ALL);
3896 done:
3897 while (!STAILQ_EMPTY(&reversed_commits)) {
3898 qid = STAILQ_FIRST(&reversed_commits);
3899 STAILQ_REMOVE_HEAD(&reversed_commits, entry);
3900 got_object_qid_free(qid);
3902 got_pathlist_free(&changed_paths, GOT_PATHLIST_FREE_ALL);
3903 if (search_pattern)
3904 regfree(&regex);
3905 got_commit_graph_close(graph);
3906 return err;
3909 __dead static void
3910 usage_log(void)
3912 fprintf(stderr, "usage: %s log [-bdPpRs] [-C number] [-c commit] "
3913 "[-l N] [-r repository-path] [-S search-pattern] [-x commit] "
3914 "[path]\n", getprogname());
3915 exit(1);
3918 static int
3919 get_default_log_limit(void)
3921 const char *got_default_log_limit;
3922 long long n;
3923 const char *errstr;
3925 got_default_log_limit = getenv("GOT_LOG_DEFAULT_LIMIT");
3926 if (got_default_log_limit == NULL)
3927 return 0;
3928 n = strtonum(got_default_log_limit, 0, INT_MAX, &errstr);
3929 if (errstr != NULL)
3930 return 0;
3931 return n;
3934 static const struct got_error *
3935 cmd_log(int argc, char *argv[])
3937 const struct got_error *error;
3938 struct got_repository *repo = NULL;
3939 struct got_worktree *worktree = NULL;
3940 struct got_object_id *start_id = NULL, *end_id = NULL;
3941 char *repo_path = NULL, *path = NULL, *cwd = NULL, *in_repo_path = NULL;
3942 const char *start_commit = NULL, *end_commit = NULL;
3943 const char *search_pattern = NULL;
3944 int diff_context = -1, ch;
3945 int show_changed_paths = 0, show_patch = 0, limit = 0, log_branches = 0;
3946 int show_diffstat = 0, reverse_display_order = 0, one_line = 0;
3947 const char *errstr;
3948 struct got_reflist_head refs;
3949 struct got_reflist_object_id_map *refs_idmap = NULL;
3950 FILE *tmpfile = NULL;
3951 int *pack_fds = NULL;
3953 TAILQ_INIT(&refs);
3955 #ifndef PROFILE
3956 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
3957 NULL)
3958 == -1)
3959 err(1, "pledge");
3960 #endif
3962 limit = get_default_log_limit();
3964 while ((ch = getopt(argc, argv, "bC:c:dl:PpRr:S:sx:")) != -1) {
3965 switch (ch) {
3966 case 'b':
3967 log_branches = 1;
3968 break;
3969 case 'C':
3970 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
3971 &errstr);
3972 if (errstr != NULL)
3973 errx(1, "number of context lines is %s: %s",
3974 errstr, optarg);
3975 break;
3976 case 'c':
3977 start_commit = optarg;
3978 break;
3979 case 'd':
3980 show_diffstat = 1;
3981 break;
3982 case 'l':
3983 limit = strtonum(optarg, 0, INT_MAX, &errstr);
3984 if (errstr != NULL)
3985 errx(1, "number of commits is %s: %s",
3986 errstr, optarg);
3987 break;
3988 case 'P':
3989 show_changed_paths = 1;
3990 break;
3991 case 'p':
3992 show_patch = 1;
3993 break;
3994 case 'R':
3995 reverse_display_order = 1;
3996 break;
3997 case 'r':
3998 repo_path = realpath(optarg, NULL);
3999 if (repo_path == NULL)
4000 return got_error_from_errno2("realpath",
4001 optarg);
4002 got_path_strip_trailing_slashes(repo_path);
4003 break;
4004 case 'S':
4005 search_pattern = optarg;
4006 break;
4007 case 's':
4008 one_line = 1;
4009 break;
4010 case 'x':
4011 end_commit = optarg;
4012 break;
4013 default:
4014 usage_log();
4015 /* NOTREACHED */
4019 argc -= optind;
4020 argv += optind;
4022 if (diff_context == -1)
4023 diff_context = 3;
4024 else if (!show_patch)
4025 errx(1, "-C requires -p");
4027 if (one_line && (show_patch || show_changed_paths || show_diffstat))
4028 errx(1, "cannot use -s with -d, -p or -P");
4030 cwd = getcwd(NULL, 0);
4031 if (cwd == NULL) {
4032 error = got_error_from_errno("getcwd");
4033 goto done;
4036 error = got_repo_pack_fds_open(&pack_fds);
4037 if (error != NULL)
4038 goto done;
4040 if (repo_path == NULL) {
4041 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_CVG_DIR);
4042 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4043 goto done;
4044 error = NULL;
4047 if (argc == 1) {
4048 if (worktree) {
4049 error = got_worktree_resolve_path(&path, worktree,
4050 argv[0]);
4051 if (error)
4052 goto done;
4053 } else {
4054 path = strdup(argv[0]);
4055 if (path == NULL) {
4056 error = got_error_from_errno("strdup");
4057 goto done;
4060 } else if (argc != 0)
4061 usage_log();
4063 if (repo_path == NULL) {
4064 repo_path = worktree ?
4065 strdup(got_worktree_get_repo_path(worktree)) : strdup(cwd);
4067 if (repo_path == NULL) {
4068 error = got_error_from_errno("strdup");
4069 goto done;
4072 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
4073 if (error != NULL)
4074 goto done;
4076 error = apply_unveil(got_repo_get_path(repo), 1,
4077 worktree ? got_worktree_get_root_path(worktree) : NULL);
4078 if (error)
4079 goto done;
4081 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
4082 if (error)
4083 goto done;
4085 error = got_reflist_object_id_map_create(&refs_idmap, &refs, repo);
4086 if (error)
4087 goto done;
4089 if (start_commit == NULL) {
4090 struct got_reference *head_ref;
4091 struct got_commit_object *commit = NULL;
4092 error = got_ref_open(&head_ref, repo,
4093 worktree ? got_worktree_get_head_ref_name(worktree)
4094 : GOT_REF_HEAD, 0);
4095 if (error != NULL)
4096 goto done;
4097 error = got_ref_resolve(&start_id, repo, head_ref);
4098 got_ref_close(head_ref);
4099 if (error != NULL)
4100 goto done;
4101 error = got_object_open_as_commit(&commit, repo,
4102 start_id);
4103 if (error != NULL)
4104 goto done;
4105 got_object_commit_close(commit);
4106 } else {
4107 error = got_repo_match_object_id(&start_id, NULL,
4108 start_commit, GOT_OBJ_TYPE_COMMIT, &refs, repo);
4109 if (error != NULL)
4110 goto done;
4112 if (end_commit != NULL) {
4113 error = got_repo_match_object_id(&end_id, NULL,
4114 end_commit, GOT_OBJ_TYPE_COMMIT, &refs, repo);
4115 if (error != NULL)
4116 goto done;
4119 if (worktree) {
4121 * If a path was specified on the command line it was resolved
4122 * to a path in the work tree above. Prepend the work tree's
4123 * path prefix to obtain the corresponding in-repository path.
4125 if (path) {
4126 const char *prefix;
4127 prefix = got_worktree_get_path_prefix(worktree);
4128 if (asprintf(&in_repo_path, "%s%s%s", prefix,
4129 (path[0] != '\0') ? "/" : "", path) == -1) {
4130 error = got_error_from_errno("asprintf");
4131 goto done;
4134 } else
4135 error = got_repo_map_path(&in_repo_path, repo,
4136 path ? path : "");
4137 if (error != NULL)
4138 goto done;
4139 if (in_repo_path) {
4140 free(path);
4141 path = in_repo_path;
4144 if (worktree) {
4145 /* Release work tree lock. */
4146 got_worktree_close(worktree);
4147 worktree = NULL;
4150 if (search_pattern && show_patch) {
4151 tmpfile = got_opentemp();
4152 if (tmpfile == NULL) {
4153 error = got_error_from_errno("got_opentemp");
4154 goto done;
4158 error = print_commits(start_id, end_id, repo, path ? path : "",
4159 show_changed_paths, show_diffstat, show_patch, search_pattern,
4160 diff_context, limit, log_branches, reverse_display_order,
4161 refs_idmap, one_line, tmpfile);
4162 done:
4163 free(path);
4164 free(repo_path);
4165 free(cwd);
4166 free(start_id);
4167 free(end_id);
4168 if (worktree)
4169 got_worktree_close(worktree);
4170 if (repo) {
4171 const struct got_error *close_err = got_repo_close(repo);
4172 if (error == NULL)
4173 error = close_err;
4175 if (pack_fds) {
4176 const struct got_error *pack_err =
4177 got_repo_pack_fds_close(pack_fds);
4178 if (error == NULL)
4179 error = pack_err;
4181 if (refs_idmap)
4182 got_reflist_object_id_map_free(refs_idmap);
4183 if (tmpfile && fclose(tmpfile) == EOF && error == NULL)
4184 error = got_error_from_errno("fclose");
4185 got_ref_list_free(&refs);
4186 return error;
4189 __dead static void
4190 usage_diff(void)
4192 fprintf(stderr, "usage: %s diff [-adPsw] [-C number] [-c commit] "
4193 "[-r repository-path] [object1 object2 | path ...]\n",
4194 getprogname());
4195 exit(1);
4198 struct print_diff_arg {
4199 struct got_repository *repo;
4200 struct got_worktree *worktree;
4201 struct got_diffstat_cb_arg *diffstat;
4202 int diff_context;
4203 const char *id_str;
4204 int header_shown;
4205 int diff_staged;
4206 enum got_diff_algorithm diff_algo;
4207 int ignore_whitespace;
4208 int force_text_diff;
4209 FILE *f1;
4210 FILE *f2;
4211 FILE *outfile;
4215 * Create a file which contains the target path of a symlink so we can feed
4216 * it as content to the diff engine.
4218 static const struct got_error *
4219 get_symlink_target_file(int *fd, int dirfd, const char *de_name,
4220 const char *abspath)
4222 const struct got_error *err = NULL;
4223 char target_path[PATH_MAX];
4224 ssize_t target_len, outlen;
4226 *fd = -1;
4228 if (dirfd != -1) {
4229 target_len = readlinkat(dirfd, de_name, target_path, PATH_MAX);
4230 if (target_len == -1)
4231 return got_error_from_errno2("readlinkat", abspath);
4232 } else {
4233 target_len = readlink(abspath, target_path, PATH_MAX);
4234 if (target_len == -1)
4235 return got_error_from_errno2("readlink", abspath);
4238 *fd = got_opentempfd();
4239 if (*fd == -1)
4240 return got_error_from_errno("got_opentempfd");
4242 outlen = write(*fd, target_path, target_len);
4243 if (outlen == -1) {
4244 err = got_error_from_errno("got_opentempfd");
4245 goto done;
4248 if (lseek(*fd, 0, SEEK_SET) == -1) {
4249 err = got_error_from_errno2("lseek", abspath);
4250 goto done;
4252 done:
4253 if (err) {
4254 close(*fd);
4255 *fd = -1;
4257 return err;
4260 static const struct got_error *
4261 print_diff(void *arg, unsigned char status, unsigned char staged_status,
4262 const char *path, struct got_object_id *blob_id,
4263 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
4264 int dirfd, const char *de_name)
4266 struct print_diff_arg *a = arg;
4267 const struct got_error *err = NULL;
4268 struct got_blob_object *blob1 = NULL;
4269 int fd = -1, fd1 = -1, fd2 = -1;
4270 FILE *f2 = NULL;
4271 char *abspath = NULL, *label1 = NULL;
4272 struct stat sb;
4273 off_t size1 = 0;
4274 int f2_exists = 0;
4276 memset(&sb, 0, sizeof(sb));
4278 if (a->diff_staged) {
4279 if (staged_status != GOT_STATUS_MODIFY &&
4280 staged_status != GOT_STATUS_ADD &&
4281 staged_status != GOT_STATUS_DELETE)
4282 return NULL;
4283 } else {
4284 if (staged_status == GOT_STATUS_DELETE)
4285 return NULL;
4286 if (status == GOT_STATUS_NONEXISTENT)
4287 return got_error_set_errno(ENOENT, path);
4288 if (status != GOT_STATUS_MODIFY &&
4289 status != GOT_STATUS_ADD &&
4290 status != GOT_STATUS_DELETE &&
4291 status != GOT_STATUS_CONFLICT)
4292 return NULL;
4295 err = got_opentemp_truncate(a->f1);
4296 if (err)
4297 return got_error_from_errno("got_opentemp_truncate");
4298 err = got_opentemp_truncate(a->f2);
4299 if (err)
4300 return got_error_from_errno("got_opentemp_truncate");
4302 if (!a->header_shown) {
4303 if (fprintf(a->outfile, "diff %s%s\n",
4304 a->diff_staged ? "-s " : "",
4305 got_worktree_get_root_path(a->worktree)) < 0) {
4306 err = got_error_from_errno("fprintf");
4307 goto done;
4309 if (fprintf(a->outfile, "commit - %s\n", a->id_str) < 0) {
4310 err = got_error_from_errno("fprintf");
4311 goto done;
4313 if (fprintf(a->outfile, "path + %s%s\n",
4314 got_worktree_get_root_path(a->worktree),
4315 a->diff_staged ? " (staged changes)" : "") < 0) {
4316 err = got_error_from_errno("fprintf");
4317 goto done;
4319 a->header_shown = 1;
4322 if (a->diff_staged) {
4323 const char *label1 = NULL, *label2 = NULL;
4324 switch (staged_status) {
4325 case GOT_STATUS_MODIFY:
4326 label1 = path;
4327 label2 = path;
4328 break;
4329 case GOT_STATUS_ADD:
4330 label2 = path;
4331 break;
4332 case GOT_STATUS_DELETE:
4333 label1 = path;
4334 break;
4335 default:
4336 return got_error(GOT_ERR_FILE_STATUS);
4338 fd1 = got_opentempfd();
4339 if (fd1 == -1) {
4340 err = got_error_from_errno("got_opentempfd");
4341 goto done;
4343 fd2 = got_opentempfd();
4344 if (fd2 == -1) {
4345 err = got_error_from_errno("got_opentempfd");
4346 goto done;
4348 err = got_diff_objects_as_blobs(NULL, NULL, a->f1, a->f2,
4349 fd1, fd2, blob_id, staged_blob_id, label1, label2,
4350 a->diff_algo, a->diff_context, a->ignore_whitespace,
4351 a->force_text_diff, a->diffstat, a->repo, a->outfile);
4352 goto done;
4355 fd1 = got_opentempfd();
4356 if (fd1 == -1) {
4357 err = got_error_from_errno("got_opentempfd");
4358 goto done;
4361 if (staged_status == GOT_STATUS_ADD ||
4362 staged_status == GOT_STATUS_MODIFY) {
4363 char *id_str;
4364 err = got_object_open_as_blob(&blob1, a->repo, staged_blob_id,
4365 8192, fd1);
4366 if (err)
4367 goto done;
4368 err = got_object_id_str(&id_str, staged_blob_id);
4369 if (err)
4370 goto done;
4371 if (asprintf(&label1, "%s (staged)", id_str) == -1) {
4372 err = got_error_from_errno("asprintf");
4373 free(id_str);
4374 goto done;
4376 free(id_str);
4377 } else if (status != GOT_STATUS_ADD) {
4378 err = got_object_open_as_blob(&blob1, a->repo, blob_id, 8192,
4379 fd1);
4380 if (err)
4381 goto done;
4384 if (status != GOT_STATUS_DELETE) {
4385 if (asprintf(&abspath, "%s/%s",
4386 got_worktree_get_root_path(a->worktree), path) == -1) {
4387 err = got_error_from_errno("asprintf");
4388 goto done;
4391 if (dirfd != -1) {
4392 fd = openat(dirfd, de_name,
4393 O_RDONLY | O_NOFOLLOW | O_CLOEXEC);
4394 if (fd == -1) {
4395 if (!got_err_open_nofollow_on_symlink()) {
4396 err = got_error_from_errno2("openat",
4397 abspath);
4398 goto done;
4400 err = get_symlink_target_file(&fd, dirfd,
4401 de_name, abspath);
4402 if (err)
4403 goto done;
4405 } else {
4406 fd = open(abspath, O_RDONLY | O_NOFOLLOW | O_CLOEXEC);
4407 if (fd == -1) {
4408 if (!got_err_open_nofollow_on_symlink()) {
4409 err = got_error_from_errno2("open",
4410 abspath);
4411 goto done;
4413 err = get_symlink_target_file(&fd, dirfd,
4414 de_name, abspath);
4415 if (err)
4416 goto done;
4419 if (fstatat(fd, abspath, &sb, AT_SYMLINK_NOFOLLOW) == -1) {
4420 err = got_error_from_errno2("fstatat", abspath);
4421 goto done;
4423 f2 = fdopen(fd, "r");
4424 if (f2 == NULL) {
4425 err = got_error_from_errno2("fdopen", abspath);
4426 goto done;
4428 fd = -1;
4429 f2_exists = 1;
4432 if (blob1) {
4433 err = got_object_blob_dump_to_file(&size1, NULL, NULL,
4434 a->f1, blob1);
4435 if (err)
4436 goto done;
4439 err = got_diff_blob_file(blob1, a->f1, size1, label1, f2 ? f2 : a->f2,
4440 f2_exists, &sb, path, GOT_DIFF_ALGORITHM_PATIENCE, a->diff_context,
4441 a->ignore_whitespace, a->force_text_diff, a->diffstat, a->outfile);
4442 done:
4443 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
4444 err = got_error_from_errno("close");
4445 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
4446 err = got_error_from_errno("close");
4447 if (blob1)
4448 got_object_blob_close(blob1);
4449 if (fd != -1 && close(fd) == -1 && err == NULL)
4450 err = got_error_from_errno("close");
4451 if (f2 && fclose(f2) == EOF && err == NULL)
4452 err = got_error_from_errno("fclose");
4453 free(abspath);
4454 return err;
4457 static const struct got_error *
4458 cmd_diff(int argc, char *argv[])
4460 const struct got_error *error;
4461 struct got_repository *repo = NULL;
4462 struct got_worktree *worktree = NULL;
4463 char *cwd = NULL, *repo_path = NULL;
4464 const char *commit_args[2] = { NULL, NULL };
4465 int ncommit_args = 0;
4466 struct got_object_id *ids[2] = { NULL, NULL };
4467 char *labels[2] = { NULL, NULL };
4468 int type1 = GOT_OBJ_TYPE_ANY, type2 = GOT_OBJ_TYPE_ANY;
4469 int diff_context = 3, diff_staged = 0, ignore_whitespace = 0, ch, i;
4470 int force_text_diff = 0, force_path = 0, rflag = 0, show_diffstat = 0;
4471 const char *errstr;
4472 struct got_reflist_head refs;
4473 struct got_pathlist_head diffstat_paths, paths;
4474 FILE *f1 = NULL, *f2 = NULL, *outfile = NULL;
4475 int fd1 = -1, fd2 = -1;
4476 int *pack_fds = NULL;
4477 struct got_diffstat_cb_arg dsa;
4479 memset(&dsa, 0, sizeof(dsa));
4481 TAILQ_INIT(&refs);
4482 TAILQ_INIT(&paths);
4483 TAILQ_INIT(&diffstat_paths);
4485 #ifndef PROFILE
4486 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
4487 NULL) == -1)
4488 err(1, "pledge");
4489 #endif
4491 while ((ch = getopt(argc, argv, "aC:c:dPr:sw")) != -1) {
4492 switch (ch) {
4493 case 'a':
4494 force_text_diff = 1;
4495 break;
4496 case 'C':
4497 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
4498 &errstr);
4499 if (errstr != NULL)
4500 errx(1, "number of context lines is %s: %s",
4501 errstr, optarg);
4502 break;
4503 case 'c':
4504 if (ncommit_args >= 2)
4505 errx(1, "too many -c options used");
4506 commit_args[ncommit_args++] = optarg;
4507 break;
4508 case 'd':
4509 show_diffstat = 1;
4510 break;
4511 case 'P':
4512 force_path = 1;
4513 break;
4514 case 'r':
4515 repo_path = realpath(optarg, NULL);
4516 if (repo_path == NULL)
4517 return got_error_from_errno2("realpath",
4518 optarg);
4519 got_path_strip_trailing_slashes(repo_path);
4520 rflag = 1;
4521 break;
4522 case 's':
4523 diff_staged = 1;
4524 break;
4525 case 'w':
4526 ignore_whitespace = 1;
4527 break;
4528 default:
4529 usage_diff();
4530 /* NOTREACHED */
4534 argc -= optind;
4535 argv += optind;
4537 cwd = getcwd(NULL, 0);
4538 if (cwd == NULL) {
4539 error = got_error_from_errno("getcwd");
4540 goto done;
4543 error = got_repo_pack_fds_open(&pack_fds);
4544 if (error != NULL)
4545 goto done;
4547 if (repo_path == NULL) {
4548 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_CVG_DIR);
4549 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4550 goto done;
4551 else
4552 error = NULL;
4553 if (worktree) {
4554 repo_path =
4555 strdup(got_worktree_get_repo_path(worktree));
4556 if (repo_path == NULL) {
4557 error = got_error_from_errno("strdup");
4558 goto done;
4560 } else {
4561 repo_path = strdup(cwd);
4562 if (repo_path == NULL) {
4563 error = got_error_from_errno("strdup");
4564 goto done;
4569 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
4570 free(repo_path);
4571 if (error != NULL)
4572 goto done;
4574 if (show_diffstat) {
4575 dsa.paths = &diffstat_paths;
4576 dsa.force_text = force_text_diff;
4577 dsa.ignore_ws = ignore_whitespace;
4578 dsa.diff_algo = GOT_DIFF_ALGORITHM_PATIENCE;
4581 if (rflag || worktree == NULL || ncommit_args > 0) {
4582 if (force_path) {
4583 error = got_error_msg(GOT_ERR_NOT_IMPL,
4584 "-P option can only be used when diffing "
4585 "a work tree");
4586 goto done;
4588 if (diff_staged) {
4589 error = got_error_msg(GOT_ERR_NOT_IMPL,
4590 "-s option can only be used when diffing "
4591 "a work tree");
4592 goto done;
4596 error = apply_unveil(got_repo_get_path(repo), 1,
4597 worktree ? got_worktree_get_root_path(worktree) : NULL);
4598 if (error)
4599 goto done;
4601 if ((!force_path && argc == 2) || ncommit_args > 0) {
4602 int obj_type = (ncommit_args > 0 ?
4603 GOT_OBJ_TYPE_COMMIT : GOT_OBJ_TYPE_ANY);
4604 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
4605 NULL);
4606 if (error)
4607 goto done;
4608 for (i = 0; i < (ncommit_args > 0 ? ncommit_args : argc); i++) {
4609 const char *arg;
4610 if (ncommit_args > 0)
4611 arg = commit_args[i];
4612 else
4613 arg = argv[i];
4614 error = got_repo_match_object_id(&ids[i], &labels[i],
4615 arg, obj_type, &refs, repo);
4616 if (error) {
4617 if (error->code != GOT_ERR_NOT_REF &&
4618 error->code != GOT_ERR_NO_OBJ)
4619 goto done;
4620 if (ncommit_args > 0)
4621 goto done;
4622 error = NULL;
4623 break;
4628 f1 = got_opentemp();
4629 if (f1 == NULL) {
4630 error = got_error_from_errno("got_opentemp");
4631 goto done;
4634 f2 = got_opentemp();
4635 if (f2 == NULL) {
4636 error = got_error_from_errno("got_opentemp");
4637 goto done;
4640 outfile = got_opentemp();
4641 if (outfile == NULL) {
4642 error = got_error_from_errno("got_opentemp");
4643 goto done;
4646 if (ncommit_args == 0 && (ids[0] == NULL || ids[1] == NULL)) {
4647 struct print_diff_arg arg;
4648 char *id_str;
4650 if (worktree == NULL) {
4651 if (argc == 2 && ids[0] == NULL) {
4652 error = got_error_path(argv[0], GOT_ERR_NO_OBJ);
4653 goto done;
4654 } else if (argc == 2 && ids[1] == NULL) {
4655 error = got_error_path(argv[1], GOT_ERR_NO_OBJ);
4656 goto done;
4657 } else if (argc > 0) {
4658 error = got_error_fmt(GOT_ERR_NOT_WORKTREE,
4659 "%s", "specified paths cannot be resolved");
4660 goto done;
4661 } else {
4662 error = got_error(GOT_ERR_NOT_WORKTREE);
4663 goto done;
4667 error = get_worktree_paths_from_argv(&paths, argc, argv,
4668 worktree);
4669 if (error)
4670 goto done;
4672 error = got_object_id_str(&id_str,
4673 got_worktree_get_base_commit_id(worktree));
4674 if (error)
4675 goto done;
4676 arg.repo = repo;
4677 arg.worktree = worktree;
4678 arg.diff_algo = GOT_DIFF_ALGORITHM_PATIENCE;
4679 arg.diff_context = diff_context;
4680 arg.id_str = id_str;
4681 arg.header_shown = 0;
4682 arg.diff_staged = diff_staged;
4683 arg.ignore_whitespace = ignore_whitespace;
4684 arg.force_text_diff = force_text_diff;
4685 arg.diffstat = show_diffstat ? &dsa : NULL;
4686 arg.f1 = f1;
4687 arg.f2 = f2;
4688 arg.outfile = outfile;
4690 error = got_worktree_status(worktree, &paths, repo, 0,
4691 print_diff, &arg, check_cancelled, NULL);
4692 free(id_str);
4693 if (error)
4694 goto done;
4696 if (show_diffstat && dsa.nfiles > 0) {
4697 char *header;
4699 if (asprintf(&header, "diffstat %s%s",
4700 diff_staged ? "-s " : "",
4701 got_worktree_get_root_path(worktree)) == -1) {
4702 error = got_error_from_errno("asprintf");
4703 goto done;
4706 error = print_diffstat(&dsa, header);
4707 free(header);
4708 if (error)
4709 goto done;
4712 error = printfile(outfile);
4713 goto done;
4716 if (ncommit_args == 1) {
4717 struct got_commit_object *commit;
4718 error = got_object_open_as_commit(&commit, repo, ids[0]);
4719 if (error)
4720 goto done;
4722 labels[1] = labels[0];
4723 ids[1] = ids[0];
4724 if (got_object_commit_get_nparents(commit) > 0) {
4725 const struct got_object_id_queue *pids;
4726 struct got_object_qid *pid;
4727 pids = got_object_commit_get_parent_ids(commit);
4728 pid = STAILQ_FIRST(pids);
4729 ids[0] = got_object_id_dup(&pid->id);
4730 if (ids[0] == NULL) {
4731 error = got_error_from_errno(
4732 "got_object_id_dup");
4733 got_object_commit_close(commit);
4734 goto done;
4736 error = got_object_id_str(&labels[0], ids[0]);
4737 if (error) {
4738 got_object_commit_close(commit);
4739 goto done;
4741 } else {
4742 ids[0] = NULL;
4743 labels[0] = strdup("/dev/null");
4744 if (labels[0] == NULL) {
4745 error = got_error_from_errno("strdup");
4746 got_object_commit_close(commit);
4747 goto done;
4751 got_object_commit_close(commit);
4754 if (ncommit_args == 0 && argc > 2) {
4755 error = got_error_msg(GOT_ERR_BAD_PATH,
4756 "path arguments cannot be used when diffing two objects");
4757 goto done;
4760 if (ids[0]) {
4761 error = got_object_get_type(&type1, repo, ids[0]);
4762 if (error)
4763 goto done;
4766 error = got_object_get_type(&type2, repo, ids[1]);
4767 if (error)
4768 goto done;
4769 if (type1 != GOT_OBJ_TYPE_ANY && type1 != type2) {
4770 error = got_error(GOT_ERR_OBJ_TYPE);
4771 goto done;
4773 if (type1 == GOT_OBJ_TYPE_BLOB && argc > 2) {
4774 error = got_error_msg(GOT_ERR_OBJ_TYPE,
4775 "path arguments cannot be used when diffing blobs");
4776 goto done;
4779 for (i = 0; ncommit_args > 0 && i < argc; i++) {
4780 char *in_repo_path;
4781 struct got_pathlist_entry *new;
4782 if (worktree) {
4783 const char *prefix;
4784 char *p;
4785 error = got_worktree_resolve_path(&p, worktree,
4786 argv[i]);
4787 if (error)
4788 goto done;
4789 prefix = got_worktree_get_path_prefix(worktree);
4790 while (prefix[0] == '/')
4791 prefix++;
4792 if (asprintf(&in_repo_path, "%s%s%s", prefix,
4793 (p[0] != '\0' && prefix[0] != '\0') ? "/" : "",
4794 p) == -1) {
4795 error = got_error_from_errno("asprintf");
4796 free(p);
4797 goto done;
4799 free(p);
4800 } else {
4801 char *mapped_path, *s;
4802 error = got_repo_map_path(&mapped_path, repo, argv[i]);
4803 if (error)
4804 goto done;
4805 s = mapped_path;
4806 while (s[0] == '/')
4807 s++;
4808 in_repo_path = strdup(s);
4809 if (in_repo_path == NULL) {
4810 error = got_error_from_errno("asprintf");
4811 free(mapped_path);
4812 goto done;
4814 free(mapped_path);
4817 error = got_pathlist_insert(&new, &paths, in_repo_path, NULL);
4818 if (error || new == NULL /* duplicate */)
4819 free(in_repo_path);
4820 if (error)
4821 goto done;
4824 if (worktree) {
4825 /* Release work tree lock. */
4826 got_worktree_close(worktree);
4827 worktree = NULL;
4830 fd1 = got_opentempfd();
4831 if (fd1 == -1) {
4832 error = got_error_from_errno("got_opentempfd");
4833 goto done;
4836 fd2 = got_opentempfd();
4837 if (fd2 == -1) {
4838 error = got_error_from_errno("got_opentempfd");
4839 goto done;
4842 switch (type1 == GOT_OBJ_TYPE_ANY ? type2 : type1) {
4843 case GOT_OBJ_TYPE_BLOB:
4844 error = got_diff_objects_as_blobs(NULL, NULL, f1, f2,
4845 fd1, fd2, ids[0], ids[1], NULL, NULL,
4846 GOT_DIFF_ALGORITHM_PATIENCE, diff_context,
4847 ignore_whitespace, force_text_diff,
4848 show_diffstat ? &dsa : NULL, repo, outfile);
4849 break;
4850 case GOT_OBJ_TYPE_TREE:
4851 error = got_diff_objects_as_trees(NULL, NULL, f1, f2, fd1, fd2,
4852 ids[0], ids[1], &paths, "", "",
4853 GOT_DIFF_ALGORITHM_PATIENCE, diff_context,
4854 ignore_whitespace, force_text_diff,
4855 show_diffstat ? &dsa : NULL, repo, outfile);
4856 break;
4857 case GOT_OBJ_TYPE_COMMIT:
4858 fprintf(outfile, "diff %s %s\n", labels[0], labels[1]);
4859 error = got_diff_objects_as_commits(NULL, NULL, f1, f2,
4860 fd1, fd2, ids[0], ids[1], &paths,
4861 GOT_DIFF_ALGORITHM_PATIENCE, diff_context,
4862 ignore_whitespace, force_text_diff,
4863 show_diffstat ? &dsa : NULL, repo, outfile);
4864 break;
4865 default:
4866 error = got_error(GOT_ERR_OBJ_TYPE);
4868 if (error)
4869 goto done;
4871 if (show_diffstat && dsa.nfiles > 0) {
4872 char *header = NULL;
4874 if (asprintf(&header, "diffstat %s %s",
4875 labels[0], labels[1]) == -1) {
4876 error = got_error_from_errno("asprintf");
4877 goto done;
4880 error = print_diffstat(&dsa, header);
4881 free(header);
4882 if (error)
4883 goto done;
4886 error = printfile(outfile);
4888 done:
4889 free(labels[0]);
4890 free(labels[1]);
4891 free(ids[0]);
4892 free(ids[1]);
4893 if (worktree)
4894 got_worktree_close(worktree);
4895 if (repo) {
4896 const struct got_error *close_err = got_repo_close(repo);
4897 if (error == NULL)
4898 error = close_err;
4900 if (pack_fds) {
4901 const struct got_error *pack_err =
4902 got_repo_pack_fds_close(pack_fds);
4903 if (error == NULL)
4904 error = pack_err;
4906 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
4907 got_pathlist_free(&diffstat_paths, GOT_PATHLIST_FREE_ALL);
4908 got_ref_list_free(&refs);
4909 if (outfile && fclose(outfile) == EOF && error == NULL)
4910 error = got_error_from_errno("fclose");
4911 if (f1 && fclose(f1) == EOF && error == NULL)
4912 error = got_error_from_errno("fclose");
4913 if (f2 && fclose(f2) == EOF && error == NULL)
4914 error = got_error_from_errno("fclose");
4915 if (fd1 != -1 && close(fd1) == -1 && error == NULL)
4916 error = got_error_from_errno("close");
4917 if (fd2 != -1 && close(fd2) == -1 && error == NULL)
4918 error = got_error_from_errno("close");
4919 return error;
4922 __dead static void
4923 usage_blame(void)
4925 fprintf(stderr,
4926 "usage: %s blame [-c commit] [-r repository-path] path\n",
4927 getprogname());
4928 exit(1);
4931 struct blame_line {
4932 int annotated;
4933 char *id_str;
4934 char *committer;
4935 char datebuf[11]; /* YYYY-MM-DD + NUL */
4938 struct blame_cb_args {
4939 struct blame_line *lines;
4940 int nlines;
4941 int nlines_prec;
4942 int lineno_cur;
4943 off_t *line_offsets;
4944 FILE *f;
4945 struct got_repository *repo;
4948 static const struct got_error *
4949 blame_cb(void *arg, int nlines, int lineno,
4950 struct got_commit_object *commit, struct got_object_id *id)
4952 const struct got_error *err = NULL;
4953 struct blame_cb_args *a = arg;
4954 struct blame_line *bline;
4955 char *line = NULL;
4956 size_t linesize = 0;
4957 off_t offset;
4958 struct tm tm;
4959 time_t committer_time;
4961 if (nlines != a->nlines ||
4962 (lineno != -1 && lineno < 1) || lineno > a->nlines)
4963 return got_error(GOT_ERR_RANGE);
4965 if (sigint_received)
4966 return got_error(GOT_ERR_ITER_COMPLETED);
4968 if (lineno == -1)
4969 return NULL; /* no change in this commit */
4971 /* Annotate this line. */
4972 bline = &a->lines[lineno - 1];
4973 if (bline->annotated)
4974 return NULL;
4975 err = got_object_id_str(&bline->id_str, id);
4976 if (err)
4977 return err;
4979 bline->committer = strdup(got_object_commit_get_committer(commit));
4980 if (bline->committer == NULL) {
4981 err = got_error_from_errno("strdup");
4982 goto done;
4985 committer_time = got_object_commit_get_committer_time(commit);
4986 if (gmtime_r(&committer_time, &tm) == NULL)
4987 return got_error_from_errno("gmtime_r");
4988 if (strftime(bline->datebuf, sizeof(bline->datebuf), "%G-%m-%d",
4989 &tm) == 0) {
4990 err = got_error(GOT_ERR_NO_SPACE);
4991 goto done;
4993 bline->annotated = 1;
4995 /* Print lines annotated so far. */
4996 bline = &a->lines[a->lineno_cur - 1];
4997 if (!bline->annotated)
4998 goto done;
5000 offset = a->line_offsets[a->lineno_cur - 1];
5001 if (fseeko(a->f, offset, SEEK_SET) == -1) {
5002 err = got_error_from_errno("fseeko");
5003 goto done;
5006 while (a->lineno_cur <= a->nlines && bline->annotated) {
5007 char *smallerthan, *at, *nl, *committer;
5008 size_t len;
5010 if (getline(&line, &linesize, a->f) == -1) {
5011 if (ferror(a->f))
5012 err = got_error_from_errno("getline");
5013 break;
5016 committer = bline->committer;
5017 smallerthan = strchr(committer, '<');
5018 if (smallerthan && smallerthan[1] != '\0')
5019 committer = smallerthan + 1;
5020 at = strchr(committer, '@');
5021 if (at)
5022 *at = '\0';
5023 len = strlen(committer);
5024 if (len >= 9)
5025 committer[8] = '\0';
5027 nl = strchr(line, '\n');
5028 if (nl)
5029 *nl = '\0';
5030 printf("%.*d) %.8s %s %-8s %s\n", a->nlines_prec, a->lineno_cur,
5031 bline->id_str, bline->datebuf, committer, line);
5033 a->lineno_cur++;
5034 bline = &a->lines[a->lineno_cur - 1];
5036 done:
5037 free(line);
5038 return err;
5041 static const struct got_error *
5042 cmd_blame(int argc, char *argv[])
5044 const struct got_error *error;
5045 struct got_repository *repo = NULL;
5046 struct got_worktree *worktree = NULL;
5047 char *path, *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
5048 char *link_target = NULL;
5049 struct got_object_id *obj_id = NULL;
5050 struct got_object_id *commit_id = NULL;
5051 struct got_commit_object *commit = NULL;
5052 struct got_blob_object *blob = NULL;
5053 char *commit_id_str = NULL;
5054 struct blame_cb_args bca;
5055 int ch, obj_type, i, fd1 = -1, fd2 = -1, fd3 = -1;
5056 off_t filesize;
5057 int *pack_fds = NULL;
5058 FILE *f1 = NULL, *f2 = NULL;
5060 fd1 = got_opentempfd();
5061 if (fd1 == -1)
5062 return got_error_from_errno("got_opentempfd");
5064 memset(&bca, 0, sizeof(bca));
5066 #ifndef PROFILE
5067 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
5068 NULL) == -1)
5069 err(1, "pledge");
5070 #endif
5072 while ((ch = getopt(argc, argv, "c:r:")) != -1) {
5073 switch (ch) {
5074 case 'c':
5075 commit_id_str = optarg;
5076 break;
5077 case 'r':
5078 repo_path = realpath(optarg, NULL);
5079 if (repo_path == NULL)
5080 return got_error_from_errno2("realpath",
5081 optarg);
5082 got_path_strip_trailing_slashes(repo_path);
5083 break;
5084 default:
5085 usage_blame();
5086 /* NOTREACHED */
5090 argc -= optind;
5091 argv += optind;
5093 if (argc == 1)
5094 path = argv[0];
5095 else
5096 usage_blame();
5098 cwd = getcwd(NULL, 0);
5099 if (cwd == NULL) {
5100 error = got_error_from_errno("getcwd");
5101 goto done;
5104 error = got_repo_pack_fds_open(&pack_fds);
5105 if (error != NULL)
5106 goto done;
5108 if (repo_path == NULL) {
5109 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_CVG_DIR);
5110 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5111 goto done;
5112 else
5113 error = NULL;
5114 if (worktree) {
5115 repo_path =
5116 strdup(got_worktree_get_repo_path(worktree));
5117 if (repo_path == NULL) {
5118 error = got_error_from_errno("strdup");
5119 if (error)
5120 goto done;
5122 } else {
5123 repo_path = strdup(cwd);
5124 if (repo_path == NULL) {
5125 error = got_error_from_errno("strdup");
5126 goto done;
5131 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
5132 if (error != NULL)
5133 goto done;
5135 if (worktree) {
5136 const char *prefix = got_worktree_get_path_prefix(worktree);
5137 char *p;
5139 error = got_worktree_resolve_path(&p, worktree, path);
5140 if (error)
5141 goto done;
5142 if (asprintf(&in_repo_path, "%s%s%s", prefix,
5143 (p[0] != '\0' && !got_path_is_root_dir(prefix)) ? "/" : "",
5144 p) == -1) {
5145 error = got_error_from_errno("asprintf");
5146 free(p);
5147 goto done;
5149 free(p);
5150 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5151 } else {
5152 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5153 if (error)
5154 goto done;
5155 error = got_repo_map_path(&in_repo_path, repo, path);
5157 if (error)
5158 goto done;
5160 if (commit_id_str == NULL) {
5161 struct got_reference *head_ref;
5162 error = got_ref_open(&head_ref, repo, worktree ?
5163 got_worktree_get_head_ref_name(worktree) : GOT_REF_HEAD, 0);
5164 if (error != NULL)
5165 goto done;
5166 error = got_ref_resolve(&commit_id, repo, head_ref);
5167 got_ref_close(head_ref);
5168 if (error != NULL)
5169 goto done;
5170 } else {
5171 struct got_reflist_head refs;
5172 TAILQ_INIT(&refs);
5173 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
5174 NULL);
5175 if (error)
5176 goto done;
5177 error = got_repo_match_object_id(&commit_id, NULL,
5178 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
5179 got_ref_list_free(&refs);
5180 if (error)
5181 goto done;
5184 if (worktree) {
5185 /* Release work tree lock. */
5186 got_worktree_close(worktree);
5187 worktree = NULL;
5190 error = got_object_open_as_commit(&commit, repo, commit_id);
5191 if (error)
5192 goto done;
5194 error = got_object_resolve_symlinks(&link_target, in_repo_path,
5195 commit, repo);
5196 if (error)
5197 goto done;
5199 error = got_object_id_by_path(&obj_id, repo, commit,
5200 link_target ? link_target : in_repo_path);
5201 if (error)
5202 goto done;
5204 error = got_object_get_type(&obj_type, repo, obj_id);
5205 if (error)
5206 goto done;
5208 if (obj_type != GOT_OBJ_TYPE_BLOB) {
5209 error = got_error_path(link_target ? link_target : in_repo_path,
5210 GOT_ERR_OBJ_TYPE);
5211 goto done;
5214 error = got_object_open_as_blob(&blob, repo, obj_id, 8192, fd1);
5215 if (error)
5216 goto done;
5217 bca.f = got_opentemp();
5218 if (bca.f == NULL) {
5219 error = got_error_from_errno("got_opentemp");
5220 goto done;
5222 error = got_object_blob_dump_to_file(&filesize, &bca.nlines,
5223 &bca.line_offsets, bca.f, blob);
5224 if (error || bca.nlines == 0)
5225 goto done;
5227 /* Don't include \n at EOF in the blame line count. */
5228 if (bca.line_offsets[bca.nlines - 1] == filesize)
5229 bca.nlines--;
5231 bca.lines = calloc(bca.nlines, sizeof(*bca.lines));
5232 if (bca.lines == NULL) {
5233 error = got_error_from_errno("calloc");
5234 goto done;
5236 bca.lineno_cur = 1;
5237 bca.nlines_prec = 0;
5238 i = bca.nlines;
5239 while (i > 0) {
5240 i /= 10;
5241 bca.nlines_prec++;
5243 bca.repo = repo;
5245 fd2 = got_opentempfd();
5246 if (fd2 == -1) {
5247 error = got_error_from_errno("got_opentempfd");
5248 goto done;
5250 fd3 = got_opentempfd();
5251 if (fd3 == -1) {
5252 error = got_error_from_errno("got_opentempfd");
5253 goto done;
5255 f1 = got_opentemp();
5256 if (f1 == NULL) {
5257 error = got_error_from_errno("got_opentemp");
5258 goto done;
5260 f2 = got_opentemp();
5261 if (f2 == NULL) {
5262 error = got_error_from_errno("got_opentemp");
5263 goto done;
5265 error = got_blame(link_target ? link_target : in_repo_path, commit_id,
5266 repo, GOT_DIFF_ALGORITHM_PATIENCE, blame_cb, &bca,
5267 check_cancelled, NULL, fd2, fd3, f1, f2);
5268 done:
5269 free(in_repo_path);
5270 free(link_target);
5271 free(repo_path);
5272 free(cwd);
5273 free(commit_id);
5274 free(obj_id);
5275 if (commit)
5276 got_object_commit_close(commit);
5278 if (fd1 != -1 && close(fd1) == -1 && error == NULL)
5279 error = got_error_from_errno("close");
5280 if (fd2 != -1 && close(fd2) == -1 && error == NULL)
5281 error = got_error_from_errno("close");
5282 if (fd3 != -1 && close(fd3) == -1 && error == NULL)
5283 error = got_error_from_errno("close");
5284 if (f1 && fclose(f1) == EOF && error == NULL)
5285 error = got_error_from_errno("fclose");
5286 if (f2 && fclose(f2) == EOF && error == NULL)
5287 error = got_error_from_errno("fclose");
5289 if (blob)
5290 got_object_blob_close(blob);
5291 if (worktree)
5292 got_worktree_close(worktree);
5293 if (repo) {
5294 const struct got_error *close_err = got_repo_close(repo);
5295 if (error == NULL)
5296 error = close_err;
5298 if (pack_fds) {
5299 const struct got_error *pack_err =
5300 got_repo_pack_fds_close(pack_fds);
5301 if (error == NULL)
5302 error = pack_err;
5304 if (bca.lines) {
5305 for (i = 0; i < bca.nlines; i++) {
5306 struct blame_line *bline = &bca.lines[i];
5307 free(bline->id_str);
5308 free(bline->committer);
5310 free(bca.lines);
5312 free(bca.line_offsets);
5313 if (bca.f && fclose(bca.f) == EOF && error == NULL)
5314 error = got_error_from_errno("fclose");
5315 return error;
5318 __dead static void
5319 usage_tree(void)
5321 fprintf(stderr, "usage: %s tree [-iR] [-c commit] [-r repository-path] "
5322 "[path]\n", getprogname());
5323 exit(1);
5326 static const struct got_error *
5327 print_entry(struct got_tree_entry *te, const char *id, const char *path,
5328 const char *root_path, struct got_repository *repo)
5330 const struct got_error *err = NULL;
5331 int is_root_path = (strcmp(path, root_path) == 0);
5332 const char *modestr = "";
5333 mode_t mode = got_tree_entry_get_mode(te);
5334 char *link_target = NULL;
5336 path += strlen(root_path);
5337 while (path[0] == '/')
5338 path++;
5340 if (got_object_tree_entry_is_submodule(te))
5341 modestr = "$";
5342 else if (S_ISLNK(mode)) {
5343 int i;
5345 err = got_tree_entry_get_symlink_target(&link_target, te, repo);
5346 if (err)
5347 return err;
5348 for (i = 0; link_target[i] != '\0'; i++) {
5349 if (!isprint((unsigned char)link_target[i]))
5350 link_target[i] = '?';
5353 modestr = "@";
5355 else if (S_ISDIR(mode))
5356 modestr = "/";
5357 else if (mode & S_IXUSR)
5358 modestr = "*";
5360 printf("%s%s%s%s%s%s%s\n", id ? id : "", path,
5361 is_root_path ? "" : "/", got_tree_entry_get_name(te), modestr,
5362 link_target ? " -> ": "", link_target ? link_target : "");
5364 free(link_target);
5365 return NULL;
5368 static const struct got_error *
5369 print_tree(const char *path, struct got_commit_object *commit,
5370 int show_ids, int recurse, const char *root_path,
5371 struct got_repository *repo)
5373 const struct got_error *err = NULL;
5374 struct got_object_id *tree_id = NULL;
5375 struct got_tree_object *tree = NULL;
5376 int nentries, i;
5378 err = got_object_id_by_path(&tree_id, repo, commit, path);
5379 if (err)
5380 goto done;
5382 err = got_object_open_as_tree(&tree, repo, tree_id);
5383 if (err)
5384 goto done;
5385 nentries = got_object_tree_get_nentries(tree);
5386 for (i = 0; i < nentries; i++) {
5387 struct got_tree_entry *te;
5388 char *id = NULL;
5390 if (sigint_received || sigpipe_received)
5391 break;
5393 te = got_object_tree_get_entry(tree, i);
5394 if (show_ids) {
5395 char *id_str;
5396 err = got_object_id_str(&id_str,
5397 got_tree_entry_get_id(te));
5398 if (err)
5399 goto done;
5400 if (asprintf(&id, "%s ", id_str) == -1) {
5401 err = got_error_from_errno("asprintf");
5402 free(id_str);
5403 goto done;
5405 free(id_str);
5407 err = print_entry(te, id, path, root_path, repo);
5408 free(id);
5409 if (err)
5410 goto done;
5412 if (recurse && S_ISDIR(got_tree_entry_get_mode(te))) {
5413 char *child_path;
5414 if (asprintf(&child_path, "%s%s%s", path,
5415 path[0] == '/' && path[1] == '\0' ? "" : "/",
5416 got_tree_entry_get_name(te)) == -1) {
5417 err = got_error_from_errno("asprintf");
5418 goto done;
5420 err = print_tree(child_path, commit, show_ids, 1,
5421 root_path, repo);
5422 free(child_path);
5423 if (err)
5424 goto done;
5427 done:
5428 if (tree)
5429 got_object_tree_close(tree);
5430 free(tree_id);
5431 return err;
5434 static const struct got_error *
5435 cmd_tree(int argc, char *argv[])
5437 const struct got_error *error;
5438 struct got_repository *repo = NULL;
5439 struct got_worktree *worktree = NULL;
5440 const char *path, *refname = NULL;
5441 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
5442 struct got_object_id *commit_id = NULL;
5443 struct got_commit_object *commit = NULL;
5444 char *commit_id_str = NULL;
5445 int show_ids = 0, recurse = 0;
5446 int ch;
5447 int *pack_fds = NULL;
5449 #ifndef PROFILE
5450 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
5451 NULL) == -1)
5452 err(1, "pledge");
5453 #endif
5455 while ((ch = getopt(argc, argv, "c:iRr:")) != -1) {
5456 switch (ch) {
5457 case 'c':
5458 commit_id_str = optarg;
5459 break;
5460 case 'i':
5461 show_ids = 1;
5462 break;
5463 case 'R':
5464 recurse = 1;
5465 break;
5466 case 'r':
5467 repo_path = realpath(optarg, NULL);
5468 if (repo_path == NULL)
5469 return got_error_from_errno2("realpath",
5470 optarg);
5471 got_path_strip_trailing_slashes(repo_path);
5472 break;
5473 default:
5474 usage_tree();
5475 /* NOTREACHED */
5479 argc -= optind;
5480 argv += optind;
5482 if (argc == 1)
5483 path = argv[0];
5484 else if (argc > 1)
5485 usage_tree();
5486 else
5487 path = NULL;
5489 cwd = getcwd(NULL, 0);
5490 if (cwd == NULL) {
5491 error = got_error_from_errno("getcwd");
5492 goto done;
5495 error = got_repo_pack_fds_open(&pack_fds);
5496 if (error != NULL)
5497 goto done;
5499 if (repo_path == NULL) {
5500 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_CVG_DIR);
5501 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5502 goto done;
5503 else
5504 error = NULL;
5505 if (worktree) {
5506 repo_path =
5507 strdup(got_worktree_get_repo_path(worktree));
5508 if (repo_path == NULL)
5509 error = got_error_from_errno("strdup");
5510 if (error)
5511 goto done;
5512 } else {
5513 repo_path = strdup(cwd);
5514 if (repo_path == NULL) {
5515 error = got_error_from_errno("strdup");
5516 goto done;
5521 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
5522 if (error != NULL)
5523 goto done;
5525 if (worktree) {
5526 const char *prefix = got_worktree_get_path_prefix(worktree);
5527 char *p;
5529 if (path == NULL || got_path_is_root_dir(path))
5530 path = "";
5531 error = got_worktree_resolve_path(&p, worktree, path);
5532 if (error)
5533 goto done;
5534 if (asprintf(&in_repo_path, "%s%s%s", prefix,
5535 (p[0] != '\0' && !got_path_is_root_dir(prefix)) ? "/" : "",
5536 p) == -1) {
5537 error = got_error_from_errno("asprintf");
5538 free(p);
5539 goto done;
5541 free(p);
5542 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5543 if (error)
5544 goto done;
5545 } else {
5546 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5547 if (error)
5548 goto done;
5549 if (path == NULL)
5550 path = "/";
5551 error = got_repo_map_path(&in_repo_path, repo, path);
5552 if (error != NULL)
5553 goto done;
5556 if (commit_id_str == NULL) {
5557 struct got_reference *head_ref;
5558 if (worktree)
5559 refname = got_worktree_get_head_ref_name(worktree);
5560 else
5561 refname = GOT_REF_HEAD;
5562 error = got_ref_open(&head_ref, repo, refname, 0);
5563 if (error != NULL)
5564 goto done;
5565 error = got_ref_resolve(&commit_id, repo, head_ref);
5566 got_ref_close(head_ref);
5567 if (error != NULL)
5568 goto done;
5569 } else {
5570 struct got_reflist_head refs;
5571 TAILQ_INIT(&refs);
5572 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
5573 NULL);
5574 if (error)
5575 goto done;
5576 error = got_repo_match_object_id(&commit_id, NULL,
5577 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
5578 got_ref_list_free(&refs);
5579 if (error)
5580 goto done;
5583 if (worktree) {
5584 /* Release work tree lock. */
5585 got_worktree_close(worktree);
5586 worktree = NULL;
5589 error = got_object_open_as_commit(&commit, repo, commit_id);
5590 if (error)
5591 goto done;
5593 error = print_tree(in_repo_path, commit, show_ids, recurse,
5594 in_repo_path, repo);
5595 done:
5596 free(in_repo_path);
5597 free(repo_path);
5598 free(cwd);
5599 free(commit_id);
5600 if (commit)
5601 got_object_commit_close(commit);
5602 if (worktree)
5603 got_worktree_close(worktree);
5604 if (repo) {
5605 const struct got_error *close_err = got_repo_close(repo);
5606 if (error == NULL)
5607 error = close_err;
5609 if (pack_fds) {
5610 const struct got_error *pack_err =
5611 got_repo_pack_fds_close(pack_fds);
5612 if (error == NULL)
5613 error = pack_err;
5615 return error;
5618 __dead static void
5619 usage_status(void)
5621 fprintf(stderr, "usage: %s status [-I] [-S status-codes] "
5622 "[-s status-codes] [path ...]\n", getprogname());
5623 exit(1);
5626 struct got_status_arg {
5627 char *status_codes;
5628 int suppress;
5631 static const struct got_error *
5632 print_status(void *arg, unsigned char status, unsigned char staged_status,
5633 const char *path, struct got_object_id *blob_id,
5634 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
5635 int dirfd, const char *de_name)
5637 struct got_status_arg *st = arg;
5639 if (status == staged_status && (status == GOT_STATUS_DELETE))
5640 status = GOT_STATUS_NO_CHANGE;
5641 if (st != NULL && st->status_codes) {
5642 size_t ncodes = strlen(st->status_codes);
5643 int i, j = 0;
5645 for (i = 0; i < ncodes ; i++) {
5646 if (st->suppress) {
5647 if (status == st->status_codes[i] ||
5648 staged_status == st->status_codes[i]) {
5649 j++;
5650 continue;
5652 } else {
5653 if (status == st->status_codes[i] ||
5654 staged_status == st->status_codes[i])
5655 break;
5659 if (st->suppress && j == 0)
5660 goto print;
5662 if (i == ncodes)
5663 return NULL;
5665 print:
5666 printf("%c%c %s\n", status, staged_status, path);
5667 return NULL;
5670 static const struct got_error *
5671 cmd_status(int argc, char *argv[])
5673 const struct got_error *error = NULL;
5674 struct got_repository *repo = NULL;
5675 struct got_worktree *worktree = NULL;
5676 struct got_status_arg st;
5677 char *cwd = NULL;
5678 struct got_pathlist_head paths;
5679 int ch, i, no_ignores = 0;
5680 int *pack_fds = NULL;
5682 TAILQ_INIT(&paths);
5684 memset(&st, 0, sizeof(st));
5685 st.status_codes = NULL;
5686 st.suppress = 0;
5688 #ifndef PROFILE
5689 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
5690 NULL) == -1)
5691 err(1, "pledge");
5692 #endif
5694 while ((ch = getopt(argc, argv, "IS:s:")) != -1) {
5695 switch (ch) {
5696 case 'I':
5697 no_ignores = 1;
5698 break;
5699 case 'S':
5700 if (st.status_codes != NULL && st.suppress == 0)
5701 option_conflict('S', 's');
5702 st.suppress = 1;
5703 /* fallthrough */
5704 case 's':
5705 for (i = 0; optarg[i] != '\0'; i++) {
5706 switch (optarg[i]) {
5707 case GOT_STATUS_MODIFY:
5708 case GOT_STATUS_ADD:
5709 case GOT_STATUS_DELETE:
5710 case GOT_STATUS_CONFLICT:
5711 case GOT_STATUS_MISSING:
5712 case GOT_STATUS_OBSTRUCTED:
5713 case GOT_STATUS_UNVERSIONED:
5714 case GOT_STATUS_MODE_CHANGE:
5715 case GOT_STATUS_NONEXISTENT:
5716 break;
5717 default:
5718 errx(1, "invalid status code '%c'",
5719 optarg[i]);
5722 if (ch == 's' && st.suppress)
5723 option_conflict('s', 'S');
5724 st.status_codes = optarg;
5725 break;
5726 default:
5727 usage_status();
5728 /* NOTREACHED */
5732 argc -= optind;
5733 argv += optind;
5735 cwd = getcwd(NULL, 0);
5736 if (cwd == NULL) {
5737 error = got_error_from_errno("getcwd");
5738 goto done;
5741 error = got_repo_pack_fds_open(&pack_fds);
5742 if (error != NULL)
5743 goto done;
5745 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_CVG_DIR);
5746 if (error) {
5747 if (error->code == GOT_ERR_NOT_WORKTREE)
5748 error = wrap_not_worktree_error(error, "status", cwd);
5749 goto done;
5752 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
5753 NULL, pack_fds);
5754 if (error != NULL)
5755 goto done;
5757 error = apply_unveil(got_repo_get_path(repo), 1,
5758 got_worktree_get_root_path(worktree));
5759 if (error)
5760 goto done;
5762 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
5763 if (error)
5764 goto done;
5766 error = got_worktree_status(worktree, &paths, repo, no_ignores,
5767 print_status, &st, check_cancelled, NULL);
5768 done:
5769 if (pack_fds) {
5770 const struct got_error *pack_err =
5771 got_repo_pack_fds_close(pack_fds);
5772 if (error == NULL)
5773 error = pack_err;
5775 if (repo) {
5776 const struct got_error *close_err = got_repo_close(repo);
5777 if (error == NULL)
5778 error = close_err;
5781 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
5782 free(cwd);
5783 return error;
5786 __dead static void
5787 usage_tag(void)
5789 fprintf(stderr, "usage: %s tag [-lVv] [-c commit] [-m message] "
5790 "[-r repository-path] [-s signer-id] name\n", getprogname());
5791 exit(1);
5794 #if 0
5795 static const struct got_error *
5796 sort_tags(struct got_reflist_head *sorted, struct got_reflist_head *tags)
5798 const struct got_error *err = NULL;
5799 struct got_reflist_entry *re, *se, *new;
5800 struct got_object_id *re_id, *se_id;
5801 struct got_tag_object *re_tag, *se_tag;
5802 time_t re_time, se_time;
5804 STAILQ_FOREACH(re, tags, entry) {
5805 se = STAILQ_FIRST(sorted);
5806 if (se == NULL) {
5807 err = got_reflist_entry_dup(&new, re);
5808 if (err)
5809 return err;
5810 STAILQ_INSERT_HEAD(sorted, new, entry);
5811 continue;
5812 } else {
5813 err = got_ref_resolve(&re_id, repo, re->ref);
5814 if (err)
5815 break;
5816 err = got_object_open_as_tag(&re_tag, repo, re_id);
5817 free(re_id);
5818 if (err)
5819 break;
5820 re_time = got_object_tag_get_tagger_time(re_tag);
5821 got_object_tag_close(re_tag);
5824 while (se) {
5825 err = got_ref_resolve(&se_id, repo, re->ref);
5826 if (err)
5827 break;
5828 err = got_object_open_as_tag(&se_tag, repo, se_id);
5829 free(se_id);
5830 if (err)
5831 break;
5832 se_time = got_object_tag_get_tagger_time(se_tag);
5833 got_object_tag_close(se_tag);
5835 if (se_time > re_time) {
5836 err = got_reflist_entry_dup(&new, re);
5837 if (err)
5838 return err;
5839 STAILQ_INSERT_AFTER(sorted, se, new, entry);
5840 break;
5842 se = STAILQ_NEXT(se, entry);
5843 continue;
5846 done:
5847 return err;
5849 #endif
5851 static const struct got_error *
5852 get_tag_refname(char **refname, const char *tag_name)
5854 const struct got_error *err;
5856 if (strncmp("refs/tags/", tag_name, 10) == 0) {
5857 *refname = strdup(tag_name);
5858 if (*refname == NULL)
5859 return got_error_from_errno("strdup");
5860 } else if (asprintf(refname, "refs/tags/%s", tag_name) == -1) {
5861 err = got_error_from_errno("asprintf");
5862 *refname = NULL;
5863 return err;
5866 return NULL;
5869 static const struct got_error *
5870 list_tags(struct got_repository *repo, const char *tag_name, int verify_tags,
5871 const char *allowed_signers, const char *revoked_signers, int verbosity)
5873 static const struct got_error *err = NULL;
5874 struct got_reflist_head refs;
5875 struct got_reflist_entry *re;
5876 char *wanted_refname = NULL;
5877 int bad_sigs = 0;
5879 TAILQ_INIT(&refs);
5881 err = got_ref_list(&refs, repo, "refs/tags", got_ref_cmp_tags, repo);
5882 if (err)
5883 return err;
5885 if (tag_name) {
5886 struct got_reference *ref;
5887 err = get_tag_refname(&wanted_refname, tag_name);
5888 if (err)
5889 goto done;
5890 /* Wanted tag reference should exist. */
5891 err = got_ref_open(&ref, repo, wanted_refname, 0);
5892 if (err)
5893 goto done;
5894 got_ref_close(ref);
5897 TAILQ_FOREACH(re, &refs, entry) {
5898 const char *refname;
5899 char *refstr, *tagmsg0, *tagmsg, *line, *id_str, *datestr;
5900 char datebuf[26];
5901 const char *tagger, *ssh_sig = NULL;
5902 char *sig_msg = NULL;
5903 time_t tagger_time;
5904 struct got_object_id *id;
5905 struct got_tag_object *tag;
5906 struct got_commit_object *commit = NULL;
5908 refname = got_ref_get_name(re->ref);
5909 if (strncmp(refname, "refs/tags/", 10) != 0 ||
5910 (wanted_refname && strcmp(refname, wanted_refname) != 0))
5911 continue;
5912 refname += 10;
5913 refstr = got_ref_to_str(re->ref);
5914 if (refstr == NULL) {
5915 err = got_error_from_errno("got_ref_to_str");
5916 break;
5919 err = got_ref_resolve(&id, repo, re->ref);
5920 if (err)
5921 break;
5922 err = got_object_open_as_tag(&tag, repo, id);
5923 if (err) {
5924 if (err->code != GOT_ERR_OBJ_TYPE) {
5925 free(id);
5926 break;
5928 /* "lightweight" tag */
5929 err = got_object_open_as_commit(&commit, repo, id);
5930 if (err) {
5931 free(id);
5932 break;
5934 tagger = got_object_commit_get_committer(commit);
5935 tagger_time =
5936 got_object_commit_get_committer_time(commit);
5937 err = got_object_id_str(&id_str, id);
5938 free(id);
5939 if (err)
5940 break;
5941 } else {
5942 free(id);
5943 tagger = got_object_tag_get_tagger(tag);
5944 tagger_time = got_object_tag_get_tagger_time(tag);
5945 err = got_object_id_str(&id_str,
5946 got_object_tag_get_object_id(tag));
5947 if (err)
5948 break;
5951 if (tag && verify_tags) {
5952 ssh_sig = got_sigs_get_tagmsg_ssh_signature(
5953 got_object_tag_get_message(tag));
5954 if (ssh_sig && allowed_signers == NULL) {
5955 err = got_error_msg(
5956 GOT_ERR_VERIFY_TAG_SIGNATURE,
5957 "SSH signature verification requires "
5958 "setting allowed_signers in "
5959 "got.conf(5)");
5960 break;
5964 printf("%stag %s %s\n", GOT_COMMIT_SEP_STR, refname, refstr);
5965 free(refstr);
5966 printf("from: %s\n", tagger);
5967 datestr = get_datestr(&tagger_time, datebuf);
5968 if (datestr)
5969 printf("date: %s UTC\n", datestr);
5970 if (commit)
5971 printf("object: %s %s\n", GOT_OBJ_LABEL_COMMIT, id_str);
5972 else {
5973 switch (got_object_tag_get_object_type(tag)) {
5974 case GOT_OBJ_TYPE_BLOB:
5975 printf("object: %s %s\n", GOT_OBJ_LABEL_BLOB,
5976 id_str);
5977 break;
5978 case GOT_OBJ_TYPE_TREE:
5979 printf("object: %s %s\n", GOT_OBJ_LABEL_TREE,
5980 id_str);
5981 break;
5982 case GOT_OBJ_TYPE_COMMIT:
5983 printf("object: %s %s\n", GOT_OBJ_LABEL_COMMIT,
5984 id_str);
5985 break;
5986 case GOT_OBJ_TYPE_TAG:
5987 printf("object: %s %s\n", GOT_OBJ_LABEL_TAG,
5988 id_str);
5989 break;
5990 default:
5991 break;
5994 free(id_str);
5996 if (ssh_sig) {
5997 err = got_sigs_verify_tag_ssh(&sig_msg, tag, ssh_sig,
5998 allowed_signers, revoked_signers, verbosity);
5999 if (err && err->code == GOT_ERR_BAD_TAG_SIGNATURE)
6000 bad_sigs = 1;
6001 else if (err)
6002 break;
6003 printf("signature: %s", sig_msg);
6004 free(sig_msg);
6005 sig_msg = NULL;
6008 if (commit) {
6009 err = got_object_commit_get_logmsg(&tagmsg0, commit);
6010 if (err)
6011 break;
6012 got_object_commit_close(commit);
6013 } else {
6014 tagmsg0 = strdup(got_object_tag_get_message(tag));
6015 got_object_tag_close(tag);
6016 if (tagmsg0 == NULL) {
6017 err = got_error_from_errno("strdup");
6018 break;
6022 tagmsg = tagmsg0;
6023 do {
6024 line = strsep(&tagmsg, "\n");
6025 if (line)
6026 printf(" %s\n", line);
6027 } while (line);
6028 free(tagmsg0);
6030 done:
6031 got_ref_list_free(&refs);
6032 free(wanted_refname);
6034 if (err == NULL && bad_sigs)
6035 err = got_error(GOT_ERR_BAD_TAG_SIGNATURE);
6036 return err;
6039 static const struct got_error *
6040 get_tag_message(char **tagmsg, char **tagmsg_path, const char *commit_id_str,
6041 const char *tag_name, const char *repo_path)
6043 const struct got_error *err = NULL;
6044 char *template = NULL, *initial_content = NULL;
6045 char *editor = NULL;
6046 int initial_content_len;
6047 int fd = -1;
6049 if (asprintf(&template, GOT_TMPDIR_STR "/got-tagmsg") == -1) {
6050 err = got_error_from_errno("asprintf");
6051 goto done;
6054 initial_content_len = asprintf(&initial_content,
6055 "\n# tagging commit %s as %s\n",
6056 commit_id_str, tag_name);
6057 if (initial_content_len == -1) {
6058 err = got_error_from_errno("asprintf");
6059 goto done;
6062 err = got_opentemp_named_fd(tagmsg_path, &fd, template, "");
6063 if (err)
6064 goto done;
6066 if (write(fd, initial_content, initial_content_len) == -1) {
6067 err = got_error_from_errno2("write", *tagmsg_path);
6068 goto done;
6070 if (close(fd) == -1) {
6071 err = got_error_from_errno2("close", *tagmsg_path);
6072 goto done;
6074 fd = -1;
6076 err = get_editor(&editor);
6077 if (err)
6078 goto done;
6079 err = edit_logmsg(tagmsg, editor, *tagmsg_path, initial_content,
6080 initial_content_len, 1);
6081 done:
6082 free(initial_content);
6083 free(template);
6084 free(editor);
6086 if (fd != -1 && close(fd) == -1 && err == NULL)
6087 err = got_error_from_errno2("close", *tagmsg_path);
6089 if (err) {
6090 free(*tagmsg);
6091 *tagmsg = NULL;
6093 return err;
6096 static const struct got_error *
6097 add_tag(struct got_repository *repo, const char *tagger,
6098 const char *tag_name, const char *commit_arg, const char *tagmsg_arg,
6099 const char *signer_id, int verbosity)
6101 const struct got_error *err = NULL;
6102 struct got_object_id *commit_id = NULL, *tag_id = NULL;
6103 char *label = NULL, *commit_id_str = NULL;
6104 struct got_reference *ref = NULL;
6105 char *refname = NULL, *tagmsg = NULL;
6106 char *tagmsg_path = NULL, *tag_id_str = NULL;
6107 int preserve_tagmsg = 0;
6108 struct got_reflist_head refs;
6110 TAILQ_INIT(&refs);
6113 * Don't let the user create a tag name with a leading '-'.
6114 * While technically a valid reference name, this case is usually
6115 * an unintended typo.
6117 if (tag_name[0] == '-')
6118 return got_error_path(tag_name, GOT_ERR_REF_NAME_MINUS);
6120 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
6121 if (err)
6122 goto done;
6124 err = got_repo_match_object_id(&commit_id, &label, commit_arg,
6125 GOT_OBJ_TYPE_COMMIT, &refs, repo);
6126 if (err)
6127 goto done;
6129 err = got_object_id_str(&commit_id_str, commit_id);
6130 if (err)
6131 goto done;
6133 err = get_tag_refname(&refname, tag_name);
6134 if (err)
6135 goto done;
6136 if (strncmp("refs/tags/", tag_name, 10) == 0)
6137 tag_name += 10;
6139 err = got_ref_open(&ref, repo, refname, 0);
6140 if (err == NULL) {
6141 err = got_error(GOT_ERR_TAG_EXISTS);
6142 goto done;
6143 } else if (err->code != GOT_ERR_NOT_REF)
6144 goto done;
6146 if (tagmsg_arg == NULL) {
6147 err = get_tag_message(&tagmsg, &tagmsg_path, commit_id_str,
6148 tag_name, got_repo_get_path(repo));
6149 if (err) {
6150 if (err->code != GOT_ERR_COMMIT_MSG_EMPTY &&
6151 tagmsg_path != NULL)
6152 preserve_tagmsg = 1;
6153 goto done;
6155 /* Editor is done; we can now apply unveil(2) */
6156 err = got_sigs_apply_unveil();
6157 if (err)
6158 goto done;
6159 err = apply_unveil(got_repo_get_path(repo), 0, NULL);
6160 if (err)
6161 goto done;
6164 err = got_object_tag_create(&tag_id, tag_name, commit_id,
6165 tagger, time(NULL), tagmsg ? tagmsg : tagmsg_arg, signer_id, repo,
6166 verbosity);
6167 if (err) {
6168 if (tagmsg_path)
6169 preserve_tagmsg = 1;
6170 goto done;
6173 err = got_ref_alloc(&ref, refname, tag_id);
6174 if (err) {
6175 if (tagmsg_path)
6176 preserve_tagmsg = 1;
6177 goto done;
6180 err = got_ref_write(ref, repo);
6181 if (err) {
6182 if (tagmsg_path)
6183 preserve_tagmsg = 1;
6184 goto done;
6187 err = got_object_id_str(&tag_id_str, tag_id);
6188 if (err) {
6189 if (tagmsg_path)
6190 preserve_tagmsg = 1;
6191 goto done;
6193 printf("Created tag %s\n", tag_id_str);
6194 done:
6195 if (preserve_tagmsg) {
6196 fprintf(stderr, "%s: tag message preserved in %s\n",
6197 getprogname(), tagmsg_path);
6198 } else if (tagmsg_path && unlink(tagmsg_path) == -1 && err == NULL)
6199 err = got_error_from_errno2("unlink", tagmsg_path);
6200 free(tag_id_str);
6201 if (ref)
6202 got_ref_close(ref);
6203 free(commit_id);
6204 free(commit_id_str);
6205 free(refname);
6206 free(tagmsg);
6207 free(tagmsg_path);
6208 got_ref_list_free(&refs);
6209 return err;
6212 static const struct got_error *
6213 cmd_tag(int argc, char *argv[])
6215 const struct got_error *error = NULL;
6216 struct got_repository *repo = NULL;
6217 struct got_worktree *worktree = NULL;
6218 char *cwd = NULL, *repo_path = NULL, *commit_id_str = NULL;
6219 char *gitconfig_path = NULL, *tagger = NULL;
6220 char *allowed_signers = NULL, *revoked_signers = NULL;
6221 const char *signer_id = NULL;
6222 const char *tag_name = NULL, *commit_id_arg = NULL, *tagmsg = NULL;
6223 int ch, do_list = 0, verify_tags = 0, verbosity = 0;
6224 int *pack_fds = NULL;
6226 #ifndef PROFILE
6227 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
6228 "sendfd unveil", NULL) == -1)
6229 err(1, "pledge");
6230 #endif
6232 while ((ch = getopt(argc, argv, "c:lm:r:s:Vv")) != -1) {
6233 switch (ch) {
6234 case 'c':
6235 commit_id_arg = optarg;
6236 break;
6237 case 'l':
6238 do_list = 1;
6239 break;
6240 case 'm':
6241 tagmsg = optarg;
6242 break;
6243 case 'r':
6244 repo_path = realpath(optarg, NULL);
6245 if (repo_path == NULL) {
6246 error = got_error_from_errno2("realpath",
6247 optarg);
6248 goto done;
6250 got_path_strip_trailing_slashes(repo_path);
6251 break;
6252 case 's':
6253 signer_id = optarg;
6254 break;
6255 case 'V':
6256 verify_tags = 1;
6257 break;
6258 case 'v':
6259 if (verbosity < 0)
6260 verbosity = 0;
6261 else if (verbosity < 3)
6262 verbosity++;
6263 break;
6264 default:
6265 usage_tag();
6266 /* NOTREACHED */
6270 argc -= optind;
6271 argv += optind;
6273 if (do_list || verify_tags) {
6274 if (commit_id_arg != NULL)
6275 errx(1,
6276 "-c option can only be used when creating a tag");
6277 if (tagmsg) {
6278 if (do_list)
6279 option_conflict('l', 'm');
6280 else
6281 option_conflict('V', 'm');
6283 if (signer_id) {
6284 if (do_list)
6285 option_conflict('l', 's');
6286 else
6287 option_conflict('V', 's');
6289 if (argc > 1)
6290 usage_tag();
6291 } else if (argc != 1)
6292 usage_tag();
6294 if (argc == 1)
6295 tag_name = argv[0];
6297 cwd = getcwd(NULL, 0);
6298 if (cwd == NULL) {
6299 error = got_error_from_errno("getcwd");
6300 goto done;
6303 error = got_repo_pack_fds_open(&pack_fds);
6304 if (error != NULL)
6305 goto done;
6307 if (repo_path == NULL) {
6308 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_CVG_DIR);
6309 if (error && error->code != GOT_ERR_NOT_WORKTREE)
6310 goto done;
6311 else
6312 error = NULL;
6313 if (worktree) {
6314 repo_path =
6315 strdup(got_worktree_get_repo_path(worktree));
6316 if (repo_path == NULL)
6317 error = got_error_from_errno("strdup");
6318 if (error)
6319 goto done;
6320 } else {
6321 repo_path = strdup(cwd);
6322 if (repo_path == NULL) {
6323 error = got_error_from_errno("strdup");
6324 goto done;
6329 if (do_list || verify_tags) {
6330 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
6331 if (error != NULL)
6332 goto done;
6333 error = get_allowed_signers(&allowed_signers, repo, worktree);
6334 if (error)
6335 goto done;
6336 error = get_revoked_signers(&revoked_signers, repo, worktree);
6337 if (error)
6338 goto done;
6339 if (worktree) {
6340 /* Release work tree lock. */
6341 got_worktree_close(worktree);
6342 worktree = NULL;
6346 * Remove "cpath" promise unless needed for signature tmpfile
6347 * creation.
6349 if (verify_tags)
6350 got_sigs_apply_unveil();
6351 else {
6352 #ifndef PROFILE
6353 if (pledge("stdio rpath wpath flock proc exec sendfd "
6354 "unveil", NULL) == -1)
6355 err(1, "pledge");
6356 #endif
6358 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
6359 if (error)
6360 goto done;
6361 error = list_tags(repo, tag_name, verify_tags, allowed_signers,
6362 revoked_signers, verbosity);
6363 } else {
6364 error = get_gitconfig_path(&gitconfig_path);
6365 if (error)
6366 goto done;
6367 error = got_repo_open(&repo, repo_path, gitconfig_path,
6368 pack_fds);
6369 if (error != NULL)
6370 goto done;
6372 error = get_author(&tagger, repo, worktree);
6373 if (error)
6374 goto done;
6375 if (signer_id == NULL)
6376 signer_id = get_signer_id(repo, worktree);
6378 if (tagmsg) {
6379 if (signer_id) {
6380 error = got_sigs_apply_unveil();
6381 if (error)
6382 goto done;
6384 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
6385 if (error)
6386 goto done;
6389 if (commit_id_arg == NULL) {
6390 struct got_reference *head_ref;
6391 struct got_object_id *commit_id;
6392 error = got_ref_open(&head_ref, repo,
6393 worktree ? got_worktree_get_head_ref_name(worktree)
6394 : GOT_REF_HEAD, 0);
6395 if (error)
6396 goto done;
6397 error = got_ref_resolve(&commit_id, repo, head_ref);
6398 got_ref_close(head_ref);
6399 if (error)
6400 goto done;
6401 error = got_object_id_str(&commit_id_str, commit_id);
6402 free(commit_id);
6403 if (error)
6404 goto done;
6407 if (worktree) {
6408 /* Release work tree lock. */
6409 got_worktree_close(worktree);
6410 worktree = NULL;
6413 error = add_tag(repo, tagger, tag_name,
6414 commit_id_str ? commit_id_str : commit_id_arg, tagmsg,
6415 signer_id, verbosity);
6417 done:
6418 if (repo) {
6419 const struct got_error *close_err = got_repo_close(repo);
6420 if (error == NULL)
6421 error = close_err;
6423 if (worktree)
6424 got_worktree_close(worktree);
6425 if (pack_fds) {
6426 const struct got_error *pack_err =
6427 got_repo_pack_fds_close(pack_fds);
6428 if (error == NULL)
6429 error = pack_err;
6431 free(cwd);
6432 free(repo_path);
6433 free(gitconfig_path);
6434 free(commit_id_str);
6435 free(tagger);
6436 free(allowed_signers);
6437 free(revoked_signers);
6438 return error;
6441 __dead static void
6442 usage_add(void)
6444 fprintf(stderr, "usage: %s add [-IR] path ...\n", getprogname());
6445 exit(1);
6448 static const struct got_error *
6449 add_progress(void *arg, unsigned char status, const char *path)
6451 while (path[0] == '/')
6452 path++;
6453 printf("%c %s\n", status, path);
6454 return NULL;
6457 static const struct got_error *
6458 cmd_add(int argc, char *argv[])
6460 const struct got_error *error = NULL;
6461 struct got_repository *repo = NULL;
6462 struct got_worktree *worktree = NULL;
6463 char *cwd = NULL;
6464 struct got_pathlist_head paths;
6465 struct got_pathlist_entry *pe;
6466 int ch, can_recurse = 0, no_ignores = 0;
6467 int *pack_fds = NULL;
6469 TAILQ_INIT(&paths);
6471 #ifndef PROFILE
6472 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
6473 NULL) == -1)
6474 err(1, "pledge");
6475 #endif
6477 while ((ch = getopt(argc, argv, "IR")) != -1) {
6478 switch (ch) {
6479 case 'I':
6480 no_ignores = 1;
6481 break;
6482 case 'R':
6483 can_recurse = 1;
6484 break;
6485 default:
6486 usage_add();
6487 /* NOTREACHED */
6491 argc -= optind;
6492 argv += optind;
6494 if (argc < 1)
6495 usage_add();
6497 cwd = getcwd(NULL, 0);
6498 if (cwd == NULL) {
6499 error = got_error_from_errno("getcwd");
6500 goto done;
6503 error = got_repo_pack_fds_open(&pack_fds);
6504 if (error != NULL)
6505 goto done;
6507 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_CVG_DIR);
6508 if (error) {
6509 if (error->code == GOT_ERR_NOT_WORKTREE)
6510 error = wrap_not_worktree_error(error, "add", cwd);
6511 goto done;
6514 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
6515 NULL, pack_fds);
6516 if (error != NULL)
6517 goto done;
6519 error = apply_unveil(got_repo_get_path(repo), 1,
6520 got_worktree_get_root_path(worktree));
6521 if (error)
6522 goto done;
6524 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
6525 if (error)
6526 goto done;
6528 if (!can_recurse) {
6529 char *ondisk_path;
6530 struct stat sb;
6531 TAILQ_FOREACH(pe, &paths, entry) {
6532 if (asprintf(&ondisk_path, "%s/%s",
6533 got_worktree_get_root_path(worktree),
6534 pe->path) == -1) {
6535 error = got_error_from_errno("asprintf");
6536 goto done;
6538 if (lstat(ondisk_path, &sb) == -1) {
6539 if (errno == ENOENT) {
6540 free(ondisk_path);
6541 continue;
6543 error = got_error_from_errno2("lstat",
6544 ondisk_path);
6545 free(ondisk_path);
6546 goto done;
6548 free(ondisk_path);
6549 if (S_ISDIR(sb.st_mode)) {
6550 error = got_error_msg(GOT_ERR_BAD_PATH,
6551 "adding directories requires -R option");
6552 goto done;
6557 error = got_worktree_schedule_add(worktree, &paths, add_progress,
6558 NULL, repo, no_ignores);
6559 done:
6560 if (repo) {
6561 const struct got_error *close_err = got_repo_close(repo);
6562 if (error == NULL)
6563 error = close_err;
6565 if (worktree)
6566 got_worktree_close(worktree);
6567 if (pack_fds) {
6568 const struct got_error *pack_err =
6569 got_repo_pack_fds_close(pack_fds);
6570 if (error == NULL)
6571 error = pack_err;
6573 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
6574 free(cwd);
6575 return error;
6578 __dead static void
6579 usage_remove(void)
6581 fprintf(stderr, "usage: %s remove [-fkR] [-s status-codes] path ...\n",
6582 getprogname());
6583 exit(1);
6586 static const struct got_error *
6587 print_remove_status(void *arg, unsigned char status,
6588 unsigned char staged_status, const char *path)
6590 while (path[0] == '/')
6591 path++;
6592 if (status == GOT_STATUS_NONEXISTENT)
6593 return NULL;
6594 if (status == staged_status && (status == GOT_STATUS_DELETE))
6595 status = GOT_STATUS_NO_CHANGE;
6596 printf("%c%c %s\n", status, staged_status, path);
6597 return NULL;
6600 static const struct got_error *
6601 cmd_remove(int argc, char *argv[])
6603 const struct got_error *error = NULL;
6604 struct got_worktree *worktree = NULL;
6605 struct got_repository *repo = NULL;
6606 const char *status_codes = NULL;
6607 char *cwd = NULL;
6608 struct got_pathlist_head paths;
6609 struct got_pathlist_entry *pe;
6610 int ch, delete_local_mods = 0, can_recurse = 0, keep_on_disk = 0, i;
6611 int ignore_missing_paths = 0;
6612 int *pack_fds = NULL;
6614 TAILQ_INIT(&paths);
6616 #ifndef PROFILE
6617 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
6618 NULL) == -1)
6619 err(1, "pledge");
6620 #endif
6622 while ((ch = getopt(argc, argv, "fkRs:")) != -1) {
6623 switch (ch) {
6624 case 'f':
6625 delete_local_mods = 1;
6626 ignore_missing_paths = 1;
6627 break;
6628 case 'k':
6629 keep_on_disk = 1;
6630 break;
6631 case 'R':
6632 can_recurse = 1;
6633 break;
6634 case 's':
6635 for (i = 0; optarg[i] != '\0'; i++) {
6636 switch (optarg[i]) {
6637 case GOT_STATUS_MODIFY:
6638 delete_local_mods = 1;
6639 break;
6640 case GOT_STATUS_MISSING:
6641 ignore_missing_paths = 1;
6642 break;
6643 default:
6644 errx(1, "invalid status code '%c'",
6645 optarg[i]);
6648 status_codes = optarg;
6649 break;
6650 default:
6651 usage_remove();
6652 /* NOTREACHED */
6656 argc -= optind;
6657 argv += optind;
6659 if (argc < 1)
6660 usage_remove();
6662 cwd = getcwd(NULL, 0);
6663 if (cwd == NULL) {
6664 error = got_error_from_errno("getcwd");
6665 goto done;
6668 error = got_repo_pack_fds_open(&pack_fds);
6669 if (error != NULL)
6670 goto done;
6672 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_CVG_DIR);
6673 if (error) {
6674 if (error->code == GOT_ERR_NOT_WORKTREE)
6675 error = wrap_not_worktree_error(error, "remove", cwd);
6676 goto done;
6679 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
6680 NULL, pack_fds);
6681 if (error)
6682 goto done;
6684 error = apply_unveil(got_repo_get_path(repo), 1,
6685 got_worktree_get_root_path(worktree));
6686 if (error)
6687 goto done;
6689 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
6690 if (error)
6691 goto done;
6693 if (!can_recurse) {
6694 char *ondisk_path;
6695 struct stat sb;
6696 TAILQ_FOREACH(pe, &paths, entry) {
6697 if (asprintf(&ondisk_path, "%s/%s",
6698 got_worktree_get_root_path(worktree),
6699 pe->path) == -1) {
6700 error = got_error_from_errno("asprintf");
6701 goto done;
6703 if (lstat(ondisk_path, &sb) == -1) {
6704 if (errno == ENOENT) {
6705 free(ondisk_path);
6706 continue;
6708 error = got_error_from_errno2("lstat",
6709 ondisk_path);
6710 free(ondisk_path);
6711 goto done;
6713 free(ondisk_path);
6714 if (S_ISDIR(sb.st_mode)) {
6715 error = got_error_msg(GOT_ERR_BAD_PATH,
6716 "removing directories requires -R option");
6717 goto done;
6722 error = got_worktree_schedule_delete(worktree, &paths,
6723 delete_local_mods, status_codes, print_remove_status, NULL,
6724 repo, keep_on_disk, ignore_missing_paths);
6725 done:
6726 if (repo) {
6727 const struct got_error *close_err = got_repo_close(repo);
6728 if (error == NULL)
6729 error = close_err;
6731 if (worktree)
6732 got_worktree_close(worktree);
6733 if (pack_fds) {
6734 const struct got_error *pack_err =
6735 got_repo_pack_fds_close(pack_fds);
6736 if (error == NULL)
6737 error = pack_err;
6739 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
6740 free(cwd);
6741 return error;
6744 __dead static void
6745 usage_patch(void)
6747 fprintf(stderr, "usage: %s patch [-nR] [-c commit] [-p strip-count] "
6748 "[patchfile]\n", getprogname());
6749 exit(1);
6752 static const struct got_error *
6753 patch_from_stdin(int *patchfd)
6755 const struct got_error *err = NULL;
6756 ssize_t r;
6757 char buf[BUFSIZ];
6758 sig_t sighup, sigint, sigquit;
6760 *patchfd = got_opentempfd();
6761 if (*patchfd == -1)
6762 return got_error_from_errno("got_opentempfd");
6764 sighup = signal(SIGHUP, SIG_DFL);
6765 sigint = signal(SIGINT, SIG_DFL);
6766 sigquit = signal(SIGQUIT, SIG_DFL);
6768 for (;;) {
6769 r = read(0, buf, sizeof(buf));
6770 if (r == -1) {
6771 err = got_error_from_errno("read");
6772 break;
6774 if (r == 0)
6775 break;
6776 if (write(*patchfd, buf, r) == -1) {
6777 err = got_error_from_errno("write");
6778 break;
6782 signal(SIGHUP, sighup);
6783 signal(SIGINT, sigint);
6784 signal(SIGQUIT, sigquit);
6786 if (err == NULL && lseek(*patchfd, 0, SEEK_SET) == -1)
6787 err = got_error_from_errno("lseek");
6789 if (err != NULL) {
6790 close(*patchfd);
6791 *patchfd = -1;
6794 return err;
6797 struct got_patch_progress_arg {
6798 int did_something;
6799 int conflicts;
6800 int rejects;
6803 static const struct got_error *
6804 patch_progress(void *arg, const char *old, const char *new,
6805 unsigned char status, const struct got_error *error, int old_from,
6806 int old_lines, int new_from, int new_lines, int offset,
6807 int ws_mangled, const struct got_error *hunk_err)
6809 const char *path = new == NULL ? old : new;
6810 struct got_patch_progress_arg *a = arg;
6812 while (*path == '/')
6813 path++;
6815 if (status != GOT_STATUS_NO_CHANGE &&
6816 status != 0 /* per-hunk progress */) {
6817 printf("%c %s\n", status, path);
6818 a->did_something = 1;
6821 if (hunk_err == NULL) {
6822 if (status == GOT_STATUS_CANNOT_UPDATE)
6823 a->rejects++;
6824 else if (status == GOT_STATUS_CONFLICT)
6825 a->conflicts++;
6828 if (error != NULL)
6829 fprintf(stderr, "%s: %s\n", getprogname(), error->msg);
6831 if (offset != 0 || hunk_err != NULL || ws_mangled) {
6832 printf("@@ -%d,%d +%d,%d @@ ", old_from,
6833 old_lines, new_from, new_lines);
6834 if (hunk_err != NULL)
6835 printf("%s\n", hunk_err->msg);
6836 else if (offset != 0)
6837 printf("applied with offset %d\n", offset);
6838 else
6839 printf("hunk contains mangled whitespace\n");
6842 return NULL;
6845 static void
6846 print_patch_progress_stats(struct got_patch_progress_arg *ppa)
6848 if (!ppa->did_something)
6849 return;
6851 if (ppa->conflicts > 0)
6852 printf("Files with merge conflicts: %d\n", ppa->conflicts);
6854 if (ppa->rejects > 0) {
6855 printf("Files where patch failed to apply: %d\n",
6856 ppa->rejects);
6860 static const struct got_error *
6861 cmd_patch(int argc, char *argv[])
6863 const struct got_error *error = NULL, *close_error = NULL;
6864 struct got_worktree *worktree = NULL;
6865 struct got_repository *repo = NULL;
6866 struct got_reflist_head refs;
6867 struct got_object_id *commit_id = NULL;
6868 const char *commit_id_str = NULL;
6869 struct stat sb;
6870 const char *errstr;
6871 char *cwd = NULL;
6872 int ch, nop = 0, strip = -1, reverse = 0;
6873 int patchfd;
6874 int *pack_fds = NULL;
6875 struct got_patch_progress_arg ppa;
6877 TAILQ_INIT(&refs);
6879 #ifndef PROFILE
6880 if (pledge("stdio rpath wpath cpath fattr proc exec sendfd flock "
6881 "unveil", NULL) == -1)
6882 err(1, "pledge");
6883 #endif
6885 while ((ch = getopt(argc, argv, "c:np:R")) != -1) {
6886 switch (ch) {
6887 case 'c':
6888 commit_id_str = optarg;
6889 break;
6890 case 'n':
6891 nop = 1;
6892 break;
6893 case 'p':
6894 strip = strtonum(optarg, 0, INT_MAX, &errstr);
6895 if (errstr != NULL)
6896 errx(1, "pathname strip count is %s: %s",
6897 errstr, optarg);
6898 break;
6899 case 'R':
6900 reverse = 1;
6901 break;
6902 default:
6903 usage_patch();
6904 /* NOTREACHED */
6908 argc -= optind;
6909 argv += optind;
6911 if (argc == 0) {
6912 error = patch_from_stdin(&patchfd);
6913 if (error)
6914 return error;
6915 } else if (argc == 1) {
6916 patchfd = open(argv[0], O_RDONLY);
6917 if (patchfd == -1) {
6918 error = got_error_from_errno2("open", argv[0]);
6919 return error;
6921 if (fstat(patchfd, &sb) == -1) {
6922 error = got_error_from_errno2("fstat", argv[0]);
6923 goto done;
6925 if (!S_ISREG(sb.st_mode)) {
6926 error = got_error_path(argv[0], GOT_ERR_BAD_FILETYPE);
6927 goto done;
6929 } else
6930 usage_patch();
6932 if ((cwd = getcwd(NULL, 0)) == NULL) {
6933 error = got_error_from_errno("getcwd");
6934 goto done;
6937 error = got_repo_pack_fds_open(&pack_fds);
6938 if (error != NULL)
6939 goto done;
6941 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_CVG_DIR);
6942 if (error != NULL)
6943 goto done;
6945 const char *repo_path = got_worktree_get_repo_path(worktree);
6946 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
6947 if (error != NULL)
6948 goto done;
6950 error = apply_unveil(got_repo_get_path(repo), 0,
6951 got_worktree_get_root_path(worktree));
6952 if (error != NULL)
6953 goto done;
6955 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
6956 if (error)
6957 goto done;
6959 if (commit_id_str != NULL) {
6960 error = got_repo_match_object_id(&commit_id, NULL,
6961 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
6962 if (error)
6963 goto done;
6966 memset(&ppa, 0, sizeof(ppa));
6967 error = got_patch(patchfd, worktree, repo, nop, strip, reverse,
6968 commit_id, patch_progress, &ppa, check_cancelled, NULL);
6969 print_patch_progress_stats(&ppa);
6970 done:
6971 got_ref_list_free(&refs);
6972 free(commit_id);
6973 if (repo) {
6974 close_error = got_repo_close(repo);
6975 if (error == NULL)
6976 error = close_error;
6978 if (worktree != NULL) {
6979 close_error = got_worktree_close(worktree);
6980 if (error == NULL)
6981 error = close_error;
6983 if (pack_fds) {
6984 const struct got_error *pack_err =
6985 got_repo_pack_fds_close(pack_fds);
6986 if (error == NULL)
6987 error = pack_err;
6989 free(cwd);
6990 return error;
6993 __dead static void
6994 usage_revert(void)
6996 fprintf(stderr, "usage: %s revert [-pR] [-F response-script] path ...\n",
6997 getprogname());
6998 exit(1);
7001 static const struct got_error *
7002 revert_progress(void *arg, unsigned char status, const char *path)
7004 if (status == GOT_STATUS_UNVERSIONED)
7005 return NULL;
7007 while (path[0] == '/')
7008 path++;
7009 printf("%c %s\n", status, path);
7010 return NULL;
7013 struct choose_patch_arg {
7014 FILE *patch_script_file;
7015 const char *action;
7018 static const struct got_error *
7019 show_change(unsigned char status, const char *path, FILE *patch_file, int n,
7020 int nchanges, const char *action)
7022 const struct got_error *err;
7023 char *line = NULL;
7024 size_t linesize = 0;
7025 ssize_t linelen;
7027 switch (status) {
7028 case GOT_STATUS_ADD:
7029 printf("A %s\n%s this addition? [y/n] ", path, action);
7030 break;
7031 case GOT_STATUS_DELETE:
7032 printf("D %s\n%s this deletion? [y/n] ", path, action);
7033 break;
7034 case GOT_STATUS_MODIFY:
7035 if (fseek(patch_file, 0L, SEEK_SET) == -1)
7036 return got_error_from_errno("fseek");
7037 printf(GOT_COMMIT_SEP_STR);
7038 while ((linelen = getline(&line, &linesize, patch_file)) != -1)
7039 printf("%s", line);
7040 if (linelen == -1 && ferror(patch_file)) {
7041 err = got_error_from_errno("getline");
7042 free(line);
7043 return err;
7045 free(line);
7046 printf(GOT_COMMIT_SEP_STR);
7047 printf("M %s (change %d of %d)\n%s this change? [y/n/q] ",
7048 path, n, nchanges, action);
7049 break;
7050 default:
7051 return got_error_path(path, GOT_ERR_FILE_STATUS);
7054 fflush(stdout);
7055 return NULL;
7058 static const struct got_error *
7059 choose_patch(int *choice, void *arg, unsigned char status, const char *path,
7060 FILE *patch_file, int n, int nchanges)
7062 const struct got_error *err = NULL;
7063 char *line = NULL;
7064 size_t linesize = 0;
7065 ssize_t linelen;
7066 int resp = ' ';
7067 struct choose_patch_arg *a = arg;
7069 *choice = GOT_PATCH_CHOICE_NONE;
7071 if (a->patch_script_file) {
7072 char *nl;
7073 err = show_change(status, path, patch_file, n, nchanges,
7074 a->action);
7075 if (err)
7076 return err;
7077 linelen = getline(&line, &linesize, a->patch_script_file);
7078 if (linelen == -1) {
7079 if (ferror(a->patch_script_file))
7080 return got_error_from_errno("getline");
7081 return NULL;
7083 nl = strchr(line, '\n');
7084 if (nl)
7085 *nl = '\0';
7086 if (strcmp(line, "y") == 0) {
7087 *choice = GOT_PATCH_CHOICE_YES;
7088 printf("y\n");
7089 } else if (strcmp(line, "n") == 0) {
7090 *choice = GOT_PATCH_CHOICE_NO;
7091 printf("n\n");
7092 } else if (strcmp(line, "q") == 0 &&
7093 status == GOT_STATUS_MODIFY) {
7094 *choice = GOT_PATCH_CHOICE_QUIT;
7095 printf("q\n");
7096 } else
7097 printf("invalid response '%s'\n", line);
7098 free(line);
7099 return NULL;
7102 while (resp != 'y' && resp != 'n' && resp != 'q') {
7103 err = show_change(status, path, patch_file, n, nchanges,
7104 a->action);
7105 if (err)
7106 return err;
7107 resp = getchar();
7108 if (resp == '\n')
7109 resp = getchar();
7110 if (status == GOT_STATUS_MODIFY) {
7111 if (resp != 'y' && resp != 'n' && resp != 'q') {
7112 printf("invalid response '%c'\n", resp);
7113 resp = ' ';
7115 } else if (resp != 'y' && resp != 'n') {
7116 printf("invalid response '%c'\n", resp);
7117 resp = ' ';
7121 if (resp == 'y')
7122 *choice = GOT_PATCH_CHOICE_YES;
7123 else if (resp == 'n')
7124 *choice = GOT_PATCH_CHOICE_NO;
7125 else if (resp == 'q' && status == GOT_STATUS_MODIFY)
7126 *choice = GOT_PATCH_CHOICE_QUIT;
7128 return NULL;
7131 struct wt_commitable_path_arg {
7132 struct got_pathlist_head *commit_paths;
7133 int *has_changes;
7137 * Shortcut work tree status callback to determine if the set of paths scanned
7138 * has at least one versioned path that is being modified and, if not NULL, is
7139 * in the arg->commit_paths list. Set arg and return GOT_ERR_FILE_MODIFIED as
7140 * soon as a path is passed with a status that satisfies this criteria.
7142 static const struct got_error *
7143 worktree_has_commitable_path(void *arg, unsigned char status,
7144 unsigned char staged_status, const char *path,
7145 struct got_object_id *blob_id, struct got_object_id *staged_blob_id,
7146 struct got_object_id *commit_id, int dirfd, const char *de_name)
7148 struct wt_commitable_path_arg *a = arg;
7150 if (status == staged_status && (status == GOT_STATUS_DELETE))
7151 status = GOT_STATUS_NO_CHANGE;
7153 if (!(status == GOT_STATUS_NO_CHANGE ||
7154 status == GOT_STATUS_UNVERSIONED) ||
7155 staged_status != GOT_STATUS_NO_CHANGE) {
7156 if (a->commit_paths != NULL) {
7157 struct got_pathlist_entry *pe;
7159 TAILQ_FOREACH(pe, a->commit_paths, entry) {
7160 if (strncmp(path, pe->path,
7161 pe->path_len) == 0) {
7162 *a->has_changes = 1;
7163 break;
7166 } else
7167 *a->has_changes = 1;
7169 if (*a->has_changes)
7170 return got_error(GOT_ERR_FILE_MODIFIED);
7173 return NULL;
7177 * Check that the changeset of the commit identified by id is
7178 * comprised of at least one modified path that is being committed.
7180 static const struct got_error *
7181 commit_path_changed_in_worktree(struct wt_commitable_path_arg *wcpa,
7182 struct got_object_id *id, struct got_worktree *worktree,
7183 struct got_repository *repo)
7185 const struct got_error *err;
7186 struct got_pathlist_head paths;
7187 struct got_commit_object *commit = NULL, *pcommit = NULL;
7188 struct got_tree_object *tree = NULL, *ptree = NULL;
7189 struct got_object_qid *pid;
7191 TAILQ_INIT(&paths);
7193 err = got_object_open_as_commit(&commit, repo, id);
7194 if (err)
7195 goto done;
7197 err = got_object_open_as_tree(&tree, repo,
7198 got_object_commit_get_tree_id(commit));
7199 if (err)
7200 goto done;
7202 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
7203 if (pid != NULL) {
7204 err = got_object_open_as_commit(&pcommit, repo, &pid->id);
7205 if (err)
7206 goto done;
7208 err = got_object_open_as_tree(&ptree, repo,
7209 got_object_commit_get_tree_id(pcommit));
7210 if (err)
7211 goto done;
7214 err = got_diff_tree(ptree, tree, NULL, NULL, -1, -1, "", "", repo,
7215 got_diff_tree_collect_changed_paths, &paths, 0);
7216 if (err)
7217 goto done;
7219 err = got_worktree_status(worktree, &paths, repo, 0,
7220 worktree_has_commitable_path, wcpa, check_cancelled, NULL);
7221 if (err && err->code == GOT_ERR_FILE_MODIFIED) {
7223 * At least one changed path in the referenced commit is
7224 * modified in the work tree, that's all we need to know!
7226 err = NULL;
7229 done:
7230 got_pathlist_free(&paths, GOT_PATHLIST_FREE_ALL);
7231 if (commit)
7232 got_object_commit_close(commit);
7233 if (pcommit)
7234 got_object_commit_close(pcommit);
7235 if (tree)
7236 got_object_tree_close(tree);
7237 if (ptree)
7238 got_object_tree_close(ptree);
7239 return err;
7243 * Remove any "logmsg" reference comprised entirely of paths that have
7244 * been reverted in this work tree. If any path in the logmsg ref changeset
7245 * remains in a changed state in the worktree, do not remove the reference.
7247 static const struct got_error *
7248 rm_logmsg_ref(struct got_worktree *worktree, struct got_repository *repo)
7250 const struct got_error *err;
7251 struct got_reflist_head refs;
7252 struct got_reflist_entry *re;
7253 struct got_commit_object *commit = NULL;
7254 struct got_object_id *commit_id = NULL;
7255 struct wt_commitable_path_arg wcpa;
7256 char *uuidstr = NULL;
7258 TAILQ_INIT(&refs);
7260 err = got_worktree_get_uuid(&uuidstr, worktree);
7261 if (err)
7262 goto done;
7264 err = got_ref_list(&refs, repo, "refs/got/worktree",
7265 got_ref_cmp_by_name, repo);
7266 if (err)
7267 goto done;
7269 TAILQ_FOREACH(re, &refs, entry) {
7270 const char *refname;
7271 int has_changes = 0;
7273 refname = got_ref_get_name(re->ref);
7275 if (!strncmp(refname, GOT_WORKTREE_CHERRYPICK_REF_PREFIX,
7276 GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN))
7277 refname += GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN + 1;
7278 else if (!strncmp(refname, GOT_WORKTREE_BACKOUT_REF_PREFIX,
7279 GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN))
7280 refname += GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN + 1;
7281 else
7282 continue;
7284 if (strncmp(refname, uuidstr, GOT_WORKTREE_UUID_STRLEN) == 0)
7285 refname += GOT_WORKTREE_UUID_STRLEN + 1; /* skip '-' */
7286 else
7287 continue;
7289 err = got_repo_match_object_id(&commit_id, NULL, refname,
7290 GOT_OBJ_TYPE_COMMIT, NULL, repo);
7291 if (err)
7292 goto done;
7294 err = got_object_open_as_commit(&commit, repo, commit_id);
7295 if (err)
7296 goto done;
7298 wcpa.commit_paths = NULL;
7299 wcpa.has_changes = &has_changes;
7301 err = commit_path_changed_in_worktree(&wcpa, commit_id,
7302 worktree, repo);
7303 if (err)
7304 goto done;
7306 if (!has_changes) {
7307 err = got_ref_delete(re->ref, repo);
7308 if (err)
7309 goto done;
7312 got_object_commit_close(commit);
7313 commit = NULL;
7314 free(commit_id);
7315 commit_id = NULL;
7318 done:
7319 free(uuidstr);
7320 free(commit_id);
7321 got_ref_list_free(&refs);
7322 if (commit)
7323 got_object_commit_close(commit);
7324 return err;
7327 static const struct got_error *
7328 cmd_revert(int argc, char *argv[])
7330 const struct got_error *error = NULL;
7331 struct got_worktree *worktree = NULL;
7332 struct got_repository *repo = NULL;
7333 char *cwd = NULL, *path = NULL;
7334 struct got_pathlist_head paths;
7335 struct got_pathlist_entry *pe;
7336 int ch, can_recurse = 0, pflag = 0;
7337 FILE *patch_script_file = NULL;
7338 const char *patch_script_path = NULL;
7339 struct choose_patch_arg cpa;
7340 int *pack_fds = NULL;
7342 TAILQ_INIT(&paths);
7344 #ifndef PROFILE
7345 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
7346 "unveil", NULL) == -1)
7347 err(1, "pledge");
7348 #endif
7350 while ((ch = getopt(argc, argv, "F:pR")) != -1) {
7351 switch (ch) {
7352 case 'F':
7353 patch_script_path = optarg;
7354 break;
7355 case 'p':
7356 pflag = 1;
7357 break;
7358 case 'R':
7359 can_recurse = 1;
7360 break;
7361 default:
7362 usage_revert();
7363 /* NOTREACHED */
7367 argc -= optind;
7368 argv += optind;
7370 if (argc < 1)
7371 usage_revert();
7372 if (patch_script_path && !pflag)
7373 errx(1, "-F option can only be used together with -p option");
7375 cwd = getcwd(NULL, 0);
7376 if (cwd == NULL) {
7377 error = got_error_from_errno("getcwd");
7378 goto done;
7381 error = got_repo_pack_fds_open(&pack_fds);
7382 if (error != NULL)
7383 goto done;
7385 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_CVG_DIR);
7386 if (error) {
7387 if (error->code == GOT_ERR_NOT_WORKTREE)
7388 error = wrap_not_worktree_error(error, "revert", cwd);
7389 goto done;
7392 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
7393 NULL, pack_fds);
7394 if (error != NULL)
7395 goto done;
7397 if (patch_script_path) {
7398 patch_script_file = fopen(patch_script_path, "re");
7399 if (patch_script_file == NULL) {
7400 error = got_error_from_errno2("fopen",
7401 patch_script_path);
7402 goto done;
7407 * XXX "c" perm needed on repo dir to delete merge references.
7409 error = apply_unveil(got_repo_get_path(repo), 0,
7410 got_worktree_get_root_path(worktree));
7411 if (error)
7412 goto done;
7414 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
7415 if (error)
7416 goto done;
7418 if (!can_recurse) {
7419 char *ondisk_path;
7420 struct stat sb;
7421 TAILQ_FOREACH(pe, &paths, entry) {
7422 if (asprintf(&ondisk_path, "%s/%s",
7423 got_worktree_get_root_path(worktree),
7424 pe->path) == -1) {
7425 error = got_error_from_errno("asprintf");
7426 goto done;
7428 if (lstat(ondisk_path, &sb) == -1) {
7429 if (errno == ENOENT) {
7430 free(ondisk_path);
7431 continue;
7433 error = got_error_from_errno2("lstat",
7434 ondisk_path);
7435 free(ondisk_path);
7436 goto done;
7438 free(ondisk_path);
7439 if (S_ISDIR(sb.st_mode)) {
7440 error = got_error_msg(GOT_ERR_BAD_PATH,
7441 "reverting directories requires -R option");
7442 goto done;
7447 cpa.patch_script_file = patch_script_file;
7448 cpa.action = "revert";
7449 error = got_worktree_revert(worktree, &paths, revert_progress, NULL,
7450 pflag ? choose_patch : NULL, &cpa, repo);
7452 error = rm_logmsg_ref(worktree, repo);
7453 done:
7454 if (patch_script_file && fclose(patch_script_file) == EOF &&
7455 error == NULL)
7456 error = got_error_from_errno2("fclose", patch_script_path);
7457 if (repo) {
7458 const struct got_error *close_err = got_repo_close(repo);
7459 if (error == NULL)
7460 error = close_err;
7462 if (worktree)
7463 got_worktree_close(worktree);
7464 if (pack_fds) {
7465 const struct got_error *pack_err =
7466 got_repo_pack_fds_close(pack_fds);
7467 if (error == NULL)
7468 error = pack_err;
7470 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
7471 free(path);
7472 free(cwd);
7473 return error;
7476 __dead static void
7477 usage_commit(void)
7479 fprintf(stderr, "usage: %s commit [-CNnS] [-A author] [-F path] "
7480 "[-m message] [path ...]\n", getprogname());
7481 exit(1);
7484 struct collect_commit_logmsg_arg {
7485 const char *cmdline_log;
7486 const char *prepared_log;
7487 const char *merged_log;
7488 int non_interactive;
7489 const char *editor;
7490 const char *worktree_path;
7491 const char *repo_path;
7492 const char *dial_proto;
7493 char *logmsg_path;
7496 static const struct got_error *
7497 read_prepared_logmsg(char **logmsg, const char *path)
7499 const struct got_error *err = NULL;
7500 FILE *f = NULL;
7501 struct stat sb;
7502 size_t r;
7504 *logmsg = NULL;
7505 memset(&sb, 0, sizeof(sb));
7507 f = fopen(path, "re");
7508 if (f == NULL)
7509 return got_error_from_errno2("fopen", path);
7511 if (fstat(fileno(f), &sb) == -1) {
7512 err = got_error_from_errno2("fstat", path);
7513 goto done;
7515 if (sb.st_size == 0) {
7516 err = got_error(GOT_ERR_COMMIT_MSG_EMPTY);
7517 goto done;
7520 *logmsg = malloc(sb.st_size + 1);
7521 if (*logmsg == NULL) {
7522 err = got_error_from_errno("malloc");
7523 goto done;
7526 r = fread(*logmsg, 1, sb.st_size, f);
7527 if (r != sb.st_size) {
7528 if (ferror(f))
7529 err = got_error_from_errno2("fread", path);
7530 else
7531 err = got_error(GOT_ERR_IO);
7532 goto done;
7534 (*logmsg)[sb.st_size] = '\0';
7535 done:
7536 if (fclose(f) == EOF && err == NULL)
7537 err = got_error_from_errno2("fclose", path);
7538 if (err) {
7539 free(*logmsg);
7540 *logmsg = NULL;
7542 return err;
7545 static const struct got_error *
7546 collect_commit_logmsg(struct got_pathlist_head *commitable_paths,
7547 const char *diff_path, char **logmsg, void *arg)
7549 char *initial_content = NULL;
7550 struct got_pathlist_entry *pe;
7551 const struct got_error *err = NULL;
7552 char *template = NULL;
7553 char *prepared_msg = NULL, *merged_msg = NULL;
7554 struct collect_commit_logmsg_arg *a = arg;
7555 int initial_content_len;
7556 int fd = -1;
7557 size_t len;
7559 /* if a message was specified on the command line, just use it */
7560 if (a->cmdline_log != NULL && *a->cmdline_log != '\0') {
7561 len = strlen(a->cmdline_log) + 1;
7562 *logmsg = malloc(len + 1);
7563 if (*logmsg == NULL)
7564 return got_error_from_errno("malloc");
7565 strlcpy(*logmsg, a->cmdline_log, len);
7566 return NULL;
7567 } else if (a->prepared_log != NULL && a->non_interactive)
7568 return read_prepared_logmsg(logmsg, a->prepared_log);
7570 if (asprintf(&template, "%s/logmsg", a->worktree_path) == -1)
7571 return got_error_from_errno("asprintf");
7573 err = got_opentemp_named_fd(&a->logmsg_path, &fd, template, "");
7574 if (err)
7575 goto done;
7577 if (a->prepared_log) {
7578 err = read_prepared_logmsg(&prepared_msg, a->prepared_log);
7579 if (err)
7580 goto done;
7581 } else if (a->merged_log) {
7582 err = read_prepared_logmsg(&merged_msg, a->merged_log);
7583 if (err)
7584 goto done;
7587 initial_content_len = asprintf(&initial_content,
7588 "%s%s\n# changes to be committed:\n",
7589 prepared_msg ? prepared_msg : "",
7590 merged_msg ? merged_msg : "");
7591 if (initial_content_len == -1) {
7592 err = got_error_from_errno("asprintf");
7593 goto done;
7596 if (write(fd, initial_content, initial_content_len) == -1) {
7597 err = got_error_from_errno2("write", a->logmsg_path);
7598 goto done;
7601 TAILQ_FOREACH(pe, commitable_paths, entry) {
7602 struct got_commitable *ct = pe->data;
7603 dprintf(fd, "# %c %s\n",
7604 got_commitable_get_status(ct),
7605 got_commitable_get_path(ct));
7608 if (diff_path) {
7609 dprintf(fd, "# detailed changes can be viewed in %s\n",
7610 diff_path);
7613 if (close(fd) == -1) {
7614 err = got_error_from_errno2("close", a->logmsg_path);
7615 goto done;
7617 fd = -1;
7619 err = edit_logmsg(logmsg, a->editor, a->logmsg_path, initial_content,
7620 initial_content_len, a->prepared_log ? 0 : 1);
7621 done:
7622 free(initial_content);
7623 free(template);
7624 free(prepared_msg);
7625 free(merged_msg);
7627 if (fd != -1 && close(fd) == -1 && err == NULL)
7628 err = got_error_from_errno2("close", a->logmsg_path);
7630 /* Editor is done; we can now apply unveil(2) */
7631 if (err == NULL)
7632 err = got_dial_apply_unveil(a->dial_proto);
7633 if (err == NULL)
7634 err = apply_unveil(a->repo_path, 0, a->worktree_path);
7635 if (err) {
7636 free(*logmsg);
7637 *logmsg = NULL;
7639 return err;
7642 static const struct got_error *
7643 cat_logmsg(FILE *f, struct got_commit_object *commit, const char *idstr,
7644 const char *type, int has_content)
7646 const struct got_error *err = NULL;
7647 char *logmsg = NULL;
7649 err = got_object_commit_get_logmsg(&logmsg, commit);
7650 if (err)
7651 return err;
7653 if (fprintf(f, "%s# log message of %s commit %s:%s",
7654 has_content ? "\n" : "", type, idstr, logmsg) < 0)
7655 err = got_ferror(f, GOT_ERR_IO);
7657 free(logmsg);
7658 return err;
7662 * Lookup "logmsg" references of backed-out and cherrypicked commits
7663 * belonging to the current work tree. If found, and the worktree has
7664 * at least one modified file that was changed in the referenced commit,
7665 * add its log message to a new temporary file at *logmsg_path.
7666 * Add all refs found to matched_refs to be scheduled for removal on
7667 * successful commit.
7669 static const struct got_error *
7670 lookup_logmsg_ref(char **logmsg_path, struct got_pathlist_head *paths,
7671 struct got_reflist_head *matched_refs, struct got_worktree *worktree,
7672 struct got_repository *repo)
7674 const struct got_error *err;
7675 struct got_commit_object *commit = NULL;
7676 struct got_object_id *id = NULL;
7677 struct got_reflist_head refs;
7678 struct got_reflist_entry *re, *re_match;
7679 FILE *f = NULL;
7680 char *uuidstr = NULL;
7681 int added_logmsg = 0;
7683 TAILQ_INIT(&refs);
7685 *logmsg_path = NULL;
7687 err = got_worktree_get_uuid(&uuidstr, worktree);
7688 if (err)
7689 goto done;
7691 err = got_ref_list(&refs, repo, "refs/got/worktree",
7692 got_ref_cmp_by_name, repo);
7693 if (err)
7694 goto done;
7696 TAILQ_FOREACH(re, &refs, entry) {
7697 const char *refname, *type;
7698 struct wt_commitable_path_arg wcpa;
7699 int add_logmsg = 0;
7701 refname = got_ref_get_name(re->ref);
7703 if (strncmp(refname, GOT_WORKTREE_CHERRYPICK_REF_PREFIX,
7704 GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN) == 0) {
7705 refname += GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN + 1;
7706 type = "cherrypicked";
7707 } else if (strncmp(refname, GOT_WORKTREE_BACKOUT_REF_PREFIX,
7708 GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN) == 0) {
7709 refname += GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN + 1;
7710 type = "backed-out";
7711 } else
7712 continue;
7714 if (strncmp(refname, uuidstr, GOT_WORKTREE_UUID_STRLEN) == 0)
7715 refname += GOT_WORKTREE_UUID_STRLEN + 1; /* skip '-' */
7716 else
7717 continue;
7719 err = got_repo_match_object_id(&id, NULL, refname,
7720 GOT_OBJ_TYPE_COMMIT, NULL, repo);
7721 if (err)
7722 goto done;
7724 err = got_object_open_as_commit(&commit, repo, id);
7725 if (err)
7726 goto done;
7728 wcpa.commit_paths = paths;
7729 wcpa.has_changes = &add_logmsg;
7731 err = commit_path_changed_in_worktree(&wcpa, id,
7732 worktree, repo);
7733 if (err)
7734 goto done;
7736 if (add_logmsg) {
7737 if (f == NULL) {
7738 err = got_opentemp_named(logmsg_path, &f,
7739 "got-commit-logmsg", "");
7740 if (err)
7741 goto done;
7743 err = cat_logmsg(f, commit, refname, type,
7744 added_logmsg);
7745 if (err)
7746 goto done;
7747 if (!added_logmsg)
7748 ++added_logmsg;
7750 err = got_reflist_entry_dup(&re_match, re);
7751 if (err)
7752 goto done;
7753 TAILQ_INSERT_HEAD(matched_refs, re_match, entry);
7756 got_object_commit_close(commit);
7757 commit = NULL;
7758 free(id);
7759 id = NULL;
7762 done:
7763 free(id);
7764 free(uuidstr);
7765 got_ref_list_free(&refs);
7766 if (commit)
7767 got_object_commit_close(commit);
7768 if (f && fclose(f) == EOF && err == NULL)
7769 err = got_error_from_errno("fclose");
7770 if (!added_logmsg) {
7771 if (*logmsg_path && unlink(*logmsg_path) != 0 && err == NULL)
7772 err = got_error_from_errno2("unlink", *logmsg_path);
7773 *logmsg_path = NULL;
7775 return err;
7778 static const struct got_error *
7779 cmd_commit(int argc, char *argv[])
7781 const struct got_error *error = NULL;
7782 struct got_worktree *worktree = NULL;
7783 struct got_repository *repo = NULL;
7784 char *cwd = NULL, *id_str = NULL;
7785 struct got_object_id *id = NULL;
7786 const char *logmsg = NULL;
7787 char *prepared_logmsg = NULL, *merged_logmsg = NULL;
7788 struct collect_commit_logmsg_arg cl_arg;
7789 const char *author = NULL;
7790 char *gitconfig_path = NULL, *editor = NULL, *committer = NULL;
7791 int ch, rebase_in_progress, histedit_in_progress, preserve_logmsg = 0;
7792 int allow_bad_symlinks = 0, non_interactive = 0, merge_in_progress = 0;
7793 int show_diff = 1, commit_conflicts = 0;
7794 struct got_pathlist_head paths;
7795 struct got_reflist_head refs;
7796 struct got_reflist_entry *re;
7797 int *pack_fds = NULL;
7798 const struct got_gotconfig *repo_conf = NULL, *worktree_conf = NULL;
7799 const struct got_remote_repo *remotes, *remote = NULL;
7800 int nremotes;
7801 char *proto = NULL, *host = NULL, *port = NULL;
7802 char *repo_name = NULL, *server_path = NULL;
7803 const char *remote_name;
7804 int verbosity = 0;
7805 int i;
7807 TAILQ_INIT(&refs);
7808 TAILQ_INIT(&paths);
7809 cl_arg.logmsg_path = NULL;
7811 #ifndef PROFILE
7812 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
7813 "unveil", NULL) == -1)
7814 err(1, "pledge");
7815 #endif
7817 while ((ch = getopt(argc, argv, "A:CF:m:NnS")) != -1) {
7818 switch (ch) {
7819 case 'A':
7820 author = optarg;
7821 error = valid_author(author);
7822 if (error)
7823 return error;
7824 break;
7825 case 'C':
7826 commit_conflicts = 1;
7827 break;
7828 case 'F':
7829 if (logmsg != NULL)
7830 option_conflict('F', 'm');
7831 prepared_logmsg = realpath(optarg, NULL);
7832 if (prepared_logmsg == NULL)
7833 return got_error_from_errno2("realpath",
7834 optarg);
7835 break;
7836 case 'm':
7837 if (prepared_logmsg)
7838 option_conflict('m', 'F');
7839 logmsg = optarg;
7840 break;
7841 case 'N':
7842 non_interactive = 1;
7843 break;
7844 case 'n':
7845 show_diff = 0;
7846 break;
7847 case 'S':
7848 allow_bad_symlinks = 1;
7849 break;
7850 default:
7851 usage_commit();
7852 /* NOTREACHED */
7856 argc -= optind;
7857 argv += optind;
7859 cwd = getcwd(NULL, 0);
7860 if (cwd == NULL) {
7861 error = got_error_from_errno("getcwd");
7862 goto done;
7865 error = got_repo_pack_fds_open(&pack_fds);
7866 if (error != NULL)
7867 goto done;
7869 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_CVG_DIR);
7870 if (error) {
7871 if (error->code == GOT_ERR_NOT_WORKTREE)
7872 error = wrap_not_worktree_error(error, "commit", cwd);
7873 goto done;
7876 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
7877 if (error)
7878 goto done;
7879 if (rebase_in_progress) {
7880 error = got_error(GOT_ERR_REBASING);
7881 goto done;
7884 error = got_worktree_histedit_in_progress(&histedit_in_progress,
7885 worktree);
7886 if (error)
7887 goto done;
7889 error = get_gitconfig_path(&gitconfig_path);
7890 if (error)
7891 goto done;
7892 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
7893 gitconfig_path, pack_fds);
7894 if (error != NULL)
7895 goto done;
7897 error = got_worktree_merge_in_progress(&merge_in_progress, worktree, repo);
7898 if (error)
7899 goto done;
7900 if (merge_in_progress) {
7901 error = got_error(GOT_ERR_MERGE_BUSY);
7902 goto done;
7905 error = get_author(&committer, repo, worktree);
7906 if (error)
7907 goto done;
7909 if (author == NULL)
7910 author = committer;
7912 remote_name = GOT_SEND_DEFAULT_REMOTE_NAME;
7913 worktree_conf = got_worktree_get_gotconfig(worktree);
7914 if (worktree_conf) {
7915 got_gotconfig_get_remotes(&nremotes, &remotes,
7916 worktree_conf);
7917 for (i = 0; i < nremotes; i++) {
7918 if (strcmp(remotes[i].name, remote_name) == 0) {
7919 remote = &remotes[i];
7920 break;
7924 if (remote == NULL) {
7925 repo_conf = got_repo_get_gotconfig(repo);
7926 if (repo_conf) {
7927 got_gotconfig_get_remotes(&nremotes, &remotes,
7928 repo_conf);
7929 for (i = 0; i < nremotes; i++) {
7930 if (strcmp(remotes[i].name, remote_name) == 0) {
7931 remote = &remotes[i];
7932 break;
7937 if (remote == NULL) {
7938 got_repo_get_gitconfig_remotes(&nremotes, &remotes, repo);
7939 for (i = 0; i < nremotes; i++) {
7940 if (strcmp(remotes[i].name, remote_name) == 0) {
7941 remote = &remotes[i];
7942 break;
7946 if (remote == NULL) {
7947 error = got_error_path(remote_name, GOT_ERR_NO_REMOTE);
7948 goto done;
7951 error = got_dial_parse_uri(&proto, &host, &port, &server_path,
7952 &repo_name, remote->fetch_url);
7953 if (error)
7954 goto done;
7956 if (strcmp(proto, "git") == 0) {
7957 #ifndef PROFILE
7958 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
7959 "sendfd dns inet unveil", NULL) == -1)
7960 err(1, "pledge");
7961 #endif
7962 } else if (strcmp(proto, "git+ssh") == 0 ||
7963 strcmp(proto, "ssh") == 0) {
7964 #ifndef PROFILE
7965 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
7966 "sendfd unveil", NULL) == -1)
7967 err(1, "pledge");
7968 #endif
7969 } else if (strcmp(proto, "http") == 0 ||
7970 strcmp(proto, "git+http") == 0) {
7971 error = got_error_path(proto, GOT_ERR_NOT_IMPL);
7972 goto done;
7973 } else {
7974 error = got_error_path(proto, GOT_ERR_BAD_PROTO);
7975 goto done;
7979 /*if (verbosity >= 0) {
7980 printf("Connecting to \"%s\" %s://%s%s%s%s%s\n",
7981 remote->name, proto, host,
7982 port ? ":" : "", port ? port : "",
7983 *server_path == '/' ? "" : "/", server_path);
7984 }*/
7987 * unveil(2) traverses exec(2); if an editor is used we have
7988 * to apply unveil after the log message has been written during
7989 * the callback.
7991 if (logmsg == NULL || strlen(logmsg) == 0)
7992 error = get_editor(&editor);
7993 else {
7994 error = got_dial_apply_unveil(proto);
7995 if (error)
7996 goto done;
7997 error = apply_unveil(got_repo_get_path(repo), 0,
7998 got_worktree_get_root_path(worktree));
8000 if (error)
8001 goto done;
8003 if (prepared_logmsg == NULL) {
8004 error = lookup_logmsg_ref(&merged_logmsg,
8005 argc > 0 ? &paths : NULL, &refs, worktree, repo);
8006 if (error)
8007 goto done;
8010 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
8011 if (error)
8012 goto done;
8014 cl_arg.editor = editor;
8015 cl_arg.cmdline_log = logmsg;
8016 cl_arg.prepared_log = prepared_logmsg;
8017 cl_arg.merged_log = merged_logmsg;
8018 cl_arg.non_interactive = non_interactive;
8019 cl_arg.worktree_path = got_worktree_get_root_path(worktree);
8020 cl_arg.repo_path = got_repo_get_path(repo);
8021 cl_arg.dial_proto = proto;
8022 error = got_worktree_cvg_commit(&id, worktree, &paths, author,
8023 committer, allow_bad_symlinks, show_diff, commit_conflicts,
8024 collect_commit_logmsg, &cl_arg, print_status, NULL, proto, host,
8025 port, server_path, verbosity, remote, check_cancelled, repo);
8026 if (error) {
8027 if (error->code != GOT_ERR_COMMIT_MSG_EMPTY &&
8028 cl_arg.logmsg_path != NULL)
8029 preserve_logmsg = 1;
8030 goto done;
8033 error = got_object_id_str(&id_str, id);
8034 if (error)
8035 goto done;
8036 printf("Created commit %s\n", id_str);
8038 TAILQ_FOREACH(re, &refs, entry) {
8039 error = got_ref_delete(re->ref, repo);
8040 if (error)
8041 goto done;
8044 done:
8045 if (preserve_logmsg) {
8046 fprintf(stderr, "%s: log message preserved in %s\n",
8047 getprogname(), cl_arg.logmsg_path);
8048 } else if (cl_arg.logmsg_path && unlink(cl_arg.logmsg_path) == -1 &&
8049 error == NULL)
8050 error = got_error_from_errno2("unlink", cl_arg.logmsg_path);
8051 free(cl_arg.logmsg_path);
8052 if (merged_logmsg && unlink(merged_logmsg) == -1 && error == NULL)
8053 error = got_error_from_errno2("unlink", merged_logmsg);
8054 free(merged_logmsg);
8055 if (repo) {
8056 const struct got_error *close_err = got_repo_close(repo);
8057 if (error == NULL)
8058 error = close_err;
8060 if (worktree)
8061 got_worktree_close(worktree);
8062 if (pack_fds) {
8063 const struct got_error *pack_err =
8064 got_repo_pack_fds_close(pack_fds);
8065 if (error == NULL)
8066 error = pack_err;
8068 got_ref_list_free(&refs);
8069 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
8070 free(cwd);
8071 free(id_str);
8072 free(gitconfig_path);
8073 free(editor);
8074 free(committer);
8075 free(prepared_logmsg);
8076 return error;
8080 * Print and if delete is set delete all ref_prefix references.
8081 * If wanted_ref is not NULL, only print or delete this reference.
8083 static const struct got_error *
8084 process_logmsg_refs(const char *ref_prefix, size_t prefix_len,
8085 const char *wanted_ref, int delete, struct got_worktree *worktree,
8086 struct got_repository *repo)
8088 const struct got_error *err;
8089 struct got_pathlist_head paths;
8090 struct got_reflist_head refs;
8091 struct got_reflist_entry *re;
8092 struct got_reflist_object_id_map *refs_idmap = NULL;
8093 struct got_commit_object *commit = NULL;
8094 struct got_object_id *id = NULL;
8095 const char *header_prefix;
8096 char *uuidstr = NULL;
8097 int found = 0;
8099 TAILQ_INIT(&refs);
8100 TAILQ_INIT(&paths);
8102 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, repo);
8103 if (err)
8104 goto done;
8106 err = got_reflist_object_id_map_create(&refs_idmap, &refs, repo);
8107 if (err)
8108 goto done;
8110 if (worktree != NULL) {
8111 err = got_worktree_get_uuid(&uuidstr, worktree);
8112 if (err)
8113 goto done;
8116 if (wanted_ref) {
8117 if (strncmp(wanted_ref, "refs/heads/", 11) == 0)
8118 wanted_ref += 11;
8121 if (strcmp(ref_prefix, GOT_WORKTREE_BACKOUT_REF_PREFIX) == 0)
8122 header_prefix = "backout";
8123 else
8124 header_prefix = "cherrypick";
8126 TAILQ_FOREACH(re, &refs, entry) {
8127 const char *refname, *wt;
8129 refname = got_ref_get_name(re->ref);
8131 err = check_cancelled(NULL);
8132 if (err)
8133 goto done;
8135 if (strncmp(refname, ref_prefix, prefix_len) == 0)
8136 refname += prefix_len + 1; /* skip '-' delimiter */
8137 else
8138 continue;
8140 wt = refname;
8142 if (worktree == NULL || strncmp(refname, uuidstr,
8143 GOT_WORKTREE_UUID_STRLEN) == 0)
8144 refname += GOT_WORKTREE_UUID_STRLEN + 1; /* skip '-' */
8145 else
8146 continue;
8148 err = got_repo_match_object_id(&id, NULL, refname,
8149 GOT_OBJ_TYPE_COMMIT, NULL, repo);
8150 if (err)
8151 goto done;
8153 err = got_object_open_as_commit(&commit, repo, id);
8154 if (err)
8155 goto done;
8157 if (wanted_ref)
8158 found = strncmp(wanted_ref, refname,
8159 strlen(wanted_ref)) == 0;
8160 if (wanted_ref && !found) {
8161 struct got_reflist_head *ci_refs;
8163 ci_refs = got_reflist_object_id_map_lookup(refs_idmap,
8164 id);
8166 if (ci_refs) {
8167 char *refs_str = NULL;
8168 char const *r = NULL;
8170 err = build_refs_str(&refs_str, ci_refs, id,
8171 repo, 1);
8172 if (err)
8173 goto done;
8175 r = refs_str;
8176 while (r) {
8177 if (strncmp(r, wanted_ref,
8178 strlen(wanted_ref)) == 0) {
8179 found = 1;
8180 break;
8182 r = strchr(r, ' ');
8183 if (r)
8184 ++r;
8186 free(refs_str);
8190 if (wanted_ref == NULL || found) {
8191 if (delete) {
8192 err = got_ref_delete(re->ref, repo);
8193 if (err)
8194 goto done;
8195 printf("Deleted: ");
8196 err = print_commit_oneline(commit, id, repo,
8197 refs_idmap);
8198 } else {
8200 * Print paths modified by commit to help
8201 * associate commits with worktree changes.
8203 err = get_changed_paths(&paths, commit,
8204 repo, NULL);
8205 if (err)
8206 goto done;
8208 err = print_commit(commit, id, repo, NULL,
8209 &paths, NULL, 0, 0, refs_idmap, NULL,
8210 header_prefix);
8211 got_pathlist_free(&paths,
8212 GOT_PATHLIST_FREE_ALL);
8214 if (worktree == NULL)
8215 printf("work tree: %.*s\n\n",
8216 GOT_WORKTREE_UUID_STRLEN, wt);
8218 if (err || found)
8219 goto done;
8222 got_object_commit_close(commit);
8223 commit = NULL;
8224 free(id);
8225 id = NULL;
8228 if (wanted_ref != NULL && !found)
8229 err = got_error_fmt(GOT_ERR_NOT_REF, "%s", wanted_ref);
8231 done:
8232 free(id);
8233 free(uuidstr);
8234 got_ref_list_free(&refs);
8235 got_pathlist_free(&paths, GOT_PATHLIST_FREE_ALL);
8236 if (refs_idmap)
8237 got_reflist_object_id_map_free(refs_idmap);
8238 if (commit)
8239 got_object_commit_close(commit);
8240 return err;
8244 * Create new temp "logmsg" ref of the backed-out or cherrypicked commit
8245 * identified by id for log messages to prepopulate the editor on commit.
8247 static const struct got_error *
8248 logmsg_ref(struct got_object_id *id, const char *prefix,
8249 struct got_worktree *worktree, struct got_repository *repo)
8251 const struct got_error *err = NULL;
8252 char *idstr, *ref = NULL, *refname = NULL;
8253 int histedit_in_progress;
8254 int rebase_in_progress, merge_in_progress;
8257 * Silenty refuse to create merge reference if any histedit, merge,
8258 * or rebase operation is in progress.
8260 err = got_worktree_histedit_in_progress(&histedit_in_progress,
8261 worktree);
8262 if (err)
8263 return err;
8264 if (histedit_in_progress)
8265 return NULL;
8267 err = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
8268 if (err)
8269 return err;
8270 if (rebase_in_progress)
8271 return NULL;
8273 err = got_worktree_merge_in_progress(&merge_in_progress, worktree,
8274 repo);
8275 if (err)
8276 return err;
8277 if (merge_in_progress)
8278 return NULL;
8280 err = got_object_id_str(&idstr, id);
8281 if (err)
8282 return err;
8284 err = got_worktree_get_logmsg_ref_name(&refname, worktree, prefix);
8285 if (err)
8286 goto done;
8288 if (asprintf(&ref, "%s-%s", refname, idstr) == -1) {
8289 err = got_error_from_errno("asprintf");
8290 goto done;
8293 err = create_ref(ref, got_worktree_get_base_commit_id(worktree),
8294 -1, repo);
8295 done:
8296 free(ref);
8297 free(idstr);
8298 free(refname);
8299 return err;
8302 __dead static void
8303 usage_cherrypick(void)
8305 fprintf(stderr, "usage: %s cherrypick [-lX] [commit-id]\n",
8306 getprogname());
8307 exit(1);
8310 static const struct got_error *
8311 cmd_cherrypick(int argc, char *argv[])
8313 const struct got_error *error = NULL;
8314 struct got_worktree *worktree = NULL;
8315 struct got_repository *repo = NULL;
8316 char *cwd = NULL, *commit_id_str = NULL;
8317 struct got_object_id *commit_id = NULL;
8318 struct got_commit_object *commit = NULL;
8319 struct got_object_qid *pid;
8320 int ch, list_refs = 0, remove_refs = 0;
8321 struct got_update_progress_arg upa;
8322 int *pack_fds = NULL;
8324 #ifndef PROFILE
8325 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
8326 "unveil", NULL) == -1)
8327 err(1, "pledge");
8328 #endif
8330 while ((ch = getopt(argc, argv, "lX")) != -1) {
8331 switch (ch) {
8332 case 'l':
8333 list_refs = 1;
8334 break;
8335 case 'X':
8336 remove_refs = 1;
8337 break;
8338 default:
8339 usage_cherrypick();
8340 /* NOTREACHED */
8344 argc -= optind;
8345 argv += optind;
8347 if (list_refs || remove_refs) {
8348 if (argc != 0 && argc != 1)
8349 usage_cherrypick();
8350 } else if (argc != 1)
8351 usage_cherrypick();
8352 if (list_refs && remove_refs)
8353 option_conflict('l', 'X');
8355 cwd = getcwd(NULL, 0);
8356 if (cwd == NULL) {
8357 error = got_error_from_errno("getcwd");
8358 goto done;
8361 error = got_repo_pack_fds_open(&pack_fds);
8362 if (error != NULL)
8363 goto done;
8365 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_CVG_DIR);
8366 if (error) {
8367 if (list_refs || remove_refs) {
8368 if (error->code != GOT_ERR_NOT_WORKTREE)
8369 goto done;
8370 } else {
8371 if (error->code == GOT_ERR_NOT_WORKTREE)
8372 error = wrap_not_worktree_error(error,
8373 "cherrypick", cwd);
8374 goto done;
8378 error = got_repo_open(&repo,
8379 worktree ? got_worktree_get_repo_path(worktree) : cwd,
8380 NULL, pack_fds);
8381 if (error != NULL)
8382 goto done;
8384 error = apply_unveil(got_repo_get_path(repo), 0,
8385 worktree ? got_worktree_get_root_path(worktree) : NULL);
8386 if (error)
8387 goto done;
8389 if (list_refs || remove_refs) {
8390 error = process_logmsg_refs(GOT_WORKTREE_CHERRYPICK_REF_PREFIX,
8391 GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN,
8392 argc == 1 ? argv[0] : NULL, remove_refs, worktree, repo);
8393 goto done;
8396 error = got_repo_match_object_id(&commit_id, NULL, argv[0],
8397 GOT_OBJ_TYPE_COMMIT, NULL, repo);
8398 if (error)
8399 goto done;
8400 error = got_object_id_str(&commit_id_str, commit_id);
8401 if (error)
8402 goto done;
8404 error = got_object_open_as_commit(&commit, repo, commit_id);
8405 if (error)
8406 goto done;
8407 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
8408 memset(&upa, 0, sizeof(upa));
8409 error = got_worktree_merge_files(worktree, pid ? &pid->id : NULL,
8410 commit_id, repo, update_progress, &upa, check_cancelled,
8411 NULL);
8412 if (error != NULL)
8413 goto done;
8415 if (upa.did_something) {
8416 error = logmsg_ref(commit_id,
8417 GOT_WORKTREE_CHERRYPICK_REF_PREFIX, worktree, repo);
8418 if (error)
8419 goto done;
8420 printf("Merged commit %s\n", commit_id_str);
8422 print_merge_progress_stats(&upa);
8423 done:
8424 free(cwd);
8425 if (commit)
8426 got_object_commit_close(commit);
8427 free(commit_id_str);
8428 if (worktree)
8429 got_worktree_close(worktree);
8430 if (repo) {
8431 const struct got_error *close_err = got_repo_close(repo);
8432 if (error == NULL)
8433 error = close_err;
8435 if (pack_fds) {
8436 const struct got_error *pack_err =
8437 got_repo_pack_fds_close(pack_fds);
8438 if (error == NULL)
8439 error = pack_err;
8442 return error;
8445 __dead static void
8446 usage_backout(void)
8448 fprintf(stderr, "usage: %s backout [-lX] [commit-id]\n", getprogname());
8449 exit(1);
8452 static const struct got_error *
8453 cmd_backout(int argc, char *argv[])
8455 const struct got_error *error = NULL;
8456 struct got_worktree *worktree = NULL;
8457 struct got_repository *repo = NULL;
8458 char *cwd = NULL, *commit_id_str = NULL;
8459 struct got_object_id *commit_id = NULL;
8460 struct got_commit_object *commit = NULL;
8461 struct got_object_qid *pid;
8462 int ch, list_refs = 0, remove_refs = 0;
8463 struct got_update_progress_arg upa;
8464 int *pack_fds = NULL;
8466 #ifndef PROFILE
8467 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
8468 "unveil", NULL) == -1)
8469 err(1, "pledge");
8470 #endif
8472 while ((ch = getopt(argc, argv, "lX")) != -1) {
8473 switch (ch) {
8474 case 'l':
8475 list_refs = 1;
8476 break;
8477 case 'X':
8478 remove_refs = 1;
8479 break;
8480 default:
8481 usage_backout();
8482 /* NOTREACHED */
8486 argc -= optind;
8487 argv += optind;
8489 if (list_refs || remove_refs) {
8490 if (argc != 0 && argc != 1)
8491 usage_backout();
8492 } else if (argc != 1)
8493 usage_backout();
8494 if (list_refs && remove_refs)
8495 option_conflict('l', 'X');
8497 cwd = getcwd(NULL, 0);
8498 if (cwd == NULL) {
8499 error = got_error_from_errno("getcwd");
8500 goto done;
8503 error = got_repo_pack_fds_open(&pack_fds);
8504 if (error != NULL)
8505 goto done;
8507 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_CVG_DIR);
8508 if (error) {
8509 if (list_refs || remove_refs) {
8510 if (error->code != GOT_ERR_NOT_WORKTREE)
8511 goto done;
8512 } else {
8513 if (error->code == GOT_ERR_NOT_WORKTREE)
8514 error = wrap_not_worktree_error(error,
8515 "backout", cwd);
8516 goto done;
8520 error = got_repo_open(&repo,
8521 worktree ? got_worktree_get_repo_path(worktree) : cwd,
8522 NULL, pack_fds);
8523 if (error != NULL)
8524 goto done;
8526 error = apply_unveil(got_repo_get_path(repo), 0,
8527 worktree ? got_worktree_get_root_path(worktree) : NULL);
8528 if (error)
8529 goto done;
8531 if (list_refs || remove_refs) {
8532 error = process_logmsg_refs(GOT_WORKTREE_BACKOUT_REF_PREFIX,
8533 GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN,
8534 argc == 1 ? argv[0] : NULL, remove_refs, worktree, repo);
8535 goto done;
8538 error = got_repo_match_object_id(&commit_id, NULL, argv[0],
8539 GOT_OBJ_TYPE_COMMIT, NULL, repo);
8540 if (error)
8541 goto done;
8542 error = got_object_id_str(&commit_id_str, commit_id);
8543 if (error)
8544 goto done;
8546 error = got_object_open_as_commit(&commit, repo, commit_id);
8547 if (error)
8548 goto done;
8549 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
8550 if (pid == NULL) {
8551 error = got_error(GOT_ERR_ROOT_COMMIT);
8552 goto done;
8555 memset(&upa, 0, sizeof(upa));
8556 error = got_worktree_merge_files(worktree, commit_id, &pid->id,
8557 repo, update_progress, &upa, check_cancelled, NULL);
8558 if (error != NULL)
8559 goto done;
8561 if (upa.did_something) {
8562 error = logmsg_ref(commit_id, GOT_WORKTREE_BACKOUT_REF_PREFIX,
8563 worktree, repo);
8564 if (error)
8565 goto done;
8566 printf("Backed out commit %s\n", commit_id_str);
8568 print_merge_progress_stats(&upa);
8569 done:
8570 free(cwd);
8571 if (commit)
8572 got_object_commit_close(commit);
8573 free(commit_id_str);
8574 if (worktree)
8575 got_worktree_close(worktree);
8576 if (repo) {
8577 const struct got_error *close_err = got_repo_close(repo);
8578 if (error == NULL)
8579 error = close_err;
8581 if (pack_fds) {
8582 const struct got_error *pack_err =
8583 got_repo_pack_fds_close(pack_fds);
8584 if (error == NULL)
8585 error = pack_err;
8587 return error;
8590 __dead static void
8591 usage_cat(void)
8593 fprintf(stderr, "usage: %s cat [-P] [-c commit] [-r repository-path] "
8594 "arg ...\n", getprogname());
8595 exit(1);
8598 static const struct got_error *
8599 cat_blob(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
8601 const struct got_error *err;
8602 struct got_blob_object *blob;
8603 int fd = -1;
8605 fd = got_opentempfd();
8606 if (fd == -1)
8607 return got_error_from_errno("got_opentempfd");
8609 err = got_object_open_as_blob(&blob, repo, id, 8192, fd);
8610 if (err)
8611 goto done;
8613 err = got_object_blob_dump_to_file(NULL, NULL, NULL, outfile, blob);
8614 done:
8615 if (fd != -1 && close(fd) == -1 && err == NULL)
8616 err = got_error_from_errno("close");
8617 if (blob)
8618 got_object_blob_close(blob);
8619 return err;
8622 static const struct got_error *
8623 cat_tree(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
8625 const struct got_error *err;
8626 struct got_tree_object *tree;
8627 int nentries, i;
8629 err = got_object_open_as_tree(&tree, repo, id);
8630 if (err)
8631 return err;
8633 nentries = got_object_tree_get_nentries(tree);
8634 for (i = 0; i < nentries; i++) {
8635 struct got_tree_entry *te;
8636 char *id_str;
8637 if (sigint_received || sigpipe_received)
8638 break;
8639 te = got_object_tree_get_entry(tree, i);
8640 err = got_object_id_str(&id_str, got_tree_entry_get_id(te));
8641 if (err)
8642 break;
8643 fprintf(outfile, "%s %.7o %s\n", id_str,
8644 got_tree_entry_get_mode(te),
8645 got_tree_entry_get_name(te));
8646 free(id_str);
8649 got_object_tree_close(tree);
8650 return err;
8653 static const struct got_error *
8654 cat_commit(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
8656 const struct got_error *err;
8657 struct got_commit_object *commit;
8658 const struct got_object_id_queue *parent_ids;
8659 struct got_object_qid *pid;
8660 char *id_str = NULL;
8661 const char *logmsg = NULL;
8662 char gmtoff[6];
8664 err = got_object_open_as_commit(&commit, repo, id);
8665 if (err)
8666 return err;
8668 err = got_object_id_str(&id_str, got_object_commit_get_tree_id(commit));
8669 if (err)
8670 goto done;
8672 fprintf(outfile, "%s%s\n", GOT_COMMIT_LABEL_TREE, id_str);
8673 parent_ids = got_object_commit_get_parent_ids(commit);
8674 fprintf(outfile, "numparents %d\n",
8675 got_object_commit_get_nparents(commit));
8676 STAILQ_FOREACH(pid, parent_ids, entry) {
8677 char *pid_str;
8678 err = got_object_id_str(&pid_str, &pid->id);
8679 if (err)
8680 goto done;
8681 fprintf(outfile, "%s%s\n", GOT_COMMIT_LABEL_PARENT, pid_str);
8682 free(pid_str);
8684 got_date_format_gmtoff(gmtoff, sizeof(gmtoff),
8685 got_object_commit_get_author_gmtoff(commit));
8686 fprintf(outfile, "%s%s %lld %s\n", GOT_COMMIT_LABEL_AUTHOR,
8687 got_object_commit_get_author(commit),
8688 (long long)got_object_commit_get_author_time(commit),
8689 gmtoff);
8691 got_date_format_gmtoff(gmtoff, sizeof(gmtoff),
8692 got_object_commit_get_committer_gmtoff(commit));
8693 fprintf(outfile, "%s%s %lld %s\n", GOT_COMMIT_LABEL_COMMITTER,
8694 got_object_commit_get_committer(commit),
8695 (long long)got_object_commit_get_committer_time(commit),
8696 gmtoff);
8698 logmsg = got_object_commit_get_logmsg_raw(commit);
8699 fprintf(outfile, "messagelen %zd\n", strlen(logmsg));
8700 fprintf(outfile, "%s", logmsg);
8701 done:
8702 free(id_str);
8703 got_object_commit_close(commit);
8704 return err;
8707 static const struct got_error *
8708 cat_tag(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
8710 const struct got_error *err;
8711 struct got_tag_object *tag;
8712 char *id_str = NULL;
8713 const char *tagmsg = NULL;
8714 char gmtoff[6];
8716 err = got_object_open_as_tag(&tag, repo, id);
8717 if (err)
8718 return err;
8720 err = got_object_id_str(&id_str, got_object_tag_get_object_id(tag));
8721 if (err)
8722 goto done;
8724 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_OBJECT, id_str);
8726 switch (got_object_tag_get_object_type(tag)) {
8727 case GOT_OBJ_TYPE_BLOB:
8728 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
8729 GOT_OBJ_LABEL_BLOB);
8730 break;
8731 case GOT_OBJ_TYPE_TREE:
8732 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
8733 GOT_OBJ_LABEL_TREE);
8734 break;
8735 case GOT_OBJ_TYPE_COMMIT:
8736 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
8737 GOT_OBJ_LABEL_COMMIT);
8738 break;
8739 case GOT_OBJ_TYPE_TAG:
8740 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
8741 GOT_OBJ_LABEL_TAG);
8742 break;
8743 default:
8744 break;
8747 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TAG,
8748 got_object_tag_get_name(tag));
8750 got_date_format_gmtoff(gmtoff, sizeof(gmtoff),
8751 got_object_tag_get_tagger_gmtoff(tag));
8752 fprintf(outfile, "%s%s %lld %s\n", GOT_TAG_LABEL_TAGGER,
8753 got_object_tag_get_tagger(tag),
8754 (long long)got_object_tag_get_tagger_time(tag),
8755 gmtoff);
8757 tagmsg = got_object_tag_get_message(tag);
8758 fprintf(outfile, "messagelen %zd\n", strlen(tagmsg));
8759 fprintf(outfile, "%s", tagmsg);
8760 done:
8761 free(id_str);
8762 got_object_tag_close(tag);
8763 return err;
8766 static const struct got_error *
8767 cmd_cat(int argc, char *argv[])
8769 const struct got_error *error;
8770 struct got_repository *repo = NULL;
8771 struct got_worktree *worktree = NULL;
8772 char *cwd = NULL, *repo_path = NULL, *label = NULL;
8773 const char *commit_id_str = NULL;
8774 struct got_object_id *id = NULL, *commit_id = NULL;
8775 struct got_commit_object *commit = NULL;
8776 int ch, obj_type, i, force_path = 0;
8777 struct got_reflist_head refs;
8778 int *pack_fds = NULL;
8780 TAILQ_INIT(&refs);
8782 #ifndef PROFILE
8783 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
8784 NULL) == -1)
8785 err(1, "pledge");
8786 #endif
8788 while ((ch = getopt(argc, argv, "c:Pr:")) != -1) {
8789 switch (ch) {
8790 case 'c':
8791 commit_id_str = optarg;
8792 break;
8793 case 'P':
8794 force_path = 1;
8795 break;
8796 case 'r':
8797 repo_path = realpath(optarg, NULL);
8798 if (repo_path == NULL)
8799 return got_error_from_errno2("realpath",
8800 optarg);
8801 got_path_strip_trailing_slashes(repo_path);
8802 break;
8803 default:
8804 usage_cat();
8805 /* NOTREACHED */
8809 argc -= optind;
8810 argv += optind;
8812 cwd = getcwd(NULL, 0);
8813 if (cwd == NULL) {
8814 error = got_error_from_errno("getcwd");
8815 goto done;
8818 error = got_repo_pack_fds_open(&pack_fds);
8819 if (error != NULL)
8820 goto done;
8822 if (repo_path == NULL) {
8823 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_CVG_DIR);
8824 if (error && error->code != GOT_ERR_NOT_WORKTREE)
8825 goto done;
8826 if (worktree) {
8827 repo_path = strdup(
8828 got_worktree_get_repo_path(worktree));
8829 if (repo_path == NULL) {
8830 error = got_error_from_errno("strdup");
8831 goto done;
8834 /* Release work tree lock. */
8835 got_worktree_close(worktree);
8836 worktree = NULL;
8840 if (repo_path == NULL) {
8841 repo_path = strdup(cwd);
8842 if (repo_path == NULL)
8843 return got_error_from_errno("strdup");
8846 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
8847 free(repo_path);
8848 if (error != NULL)
8849 goto done;
8851 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
8852 if (error)
8853 goto done;
8855 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
8856 if (error)
8857 goto done;
8859 if (commit_id_str == NULL)
8860 commit_id_str = GOT_REF_HEAD;
8861 error = got_repo_match_object_id(&commit_id, NULL,
8862 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
8863 if (error)
8864 goto done;
8866 error = got_object_open_as_commit(&commit, repo, commit_id);
8867 if (error)
8868 goto done;
8870 for (i = 0; i < argc; i++) {
8871 if (force_path) {
8872 error = got_object_id_by_path(&id, repo, commit,
8873 argv[i]);
8874 if (error)
8875 break;
8876 } else {
8877 error = got_repo_match_object_id(&id, &label, argv[i],
8878 GOT_OBJ_TYPE_ANY, NULL /* do not resolve tags */,
8879 repo);
8880 if (error) {
8881 if (error->code != GOT_ERR_BAD_OBJ_ID_STR &&
8882 error->code != GOT_ERR_NOT_REF)
8883 break;
8884 error = got_object_id_by_path(&id, repo,
8885 commit, argv[i]);
8886 if (error)
8887 break;
8891 error = got_object_get_type(&obj_type, repo, id);
8892 if (error)
8893 break;
8895 switch (obj_type) {
8896 case GOT_OBJ_TYPE_BLOB:
8897 error = cat_blob(id, repo, stdout);
8898 break;
8899 case GOT_OBJ_TYPE_TREE:
8900 error = cat_tree(id, repo, stdout);
8901 break;
8902 case GOT_OBJ_TYPE_COMMIT:
8903 error = cat_commit(id, repo, stdout);
8904 break;
8905 case GOT_OBJ_TYPE_TAG:
8906 error = cat_tag(id, repo, stdout);
8907 break;
8908 default:
8909 error = got_error(GOT_ERR_OBJ_TYPE);
8910 break;
8912 if (error)
8913 break;
8914 free(label);
8915 label = NULL;
8916 free(id);
8917 id = NULL;
8919 done:
8920 free(label);
8921 free(id);
8922 free(commit_id);
8923 if (commit)
8924 got_object_commit_close(commit);
8925 if (worktree)
8926 got_worktree_close(worktree);
8927 if (repo) {
8928 const struct got_error *close_err = got_repo_close(repo);
8929 if (error == NULL)
8930 error = close_err;
8932 if (pack_fds) {
8933 const struct got_error *pack_err =
8934 got_repo_pack_fds_close(pack_fds);
8935 if (error == NULL)
8936 error = pack_err;
8939 got_ref_list_free(&refs);
8940 return error;
8943 __dead static void
8944 usage_info(void)
8946 fprintf(stderr, "usage: %s info [path ...]\n",
8947 getprogname());
8948 exit(1);
8951 static const struct got_error *
8952 print_path_info(void *arg, const char *path, mode_t mode, time_t mtime,
8953 struct got_object_id *blob_id, struct got_object_id *staged_blob_id,
8954 struct got_object_id *commit_id)
8956 const struct got_error *err = NULL;
8957 char *id_str = NULL;
8958 char datebuf[128];
8959 struct tm mytm, *tm;
8960 struct got_pathlist_head *paths = arg;
8961 struct got_pathlist_entry *pe;
8964 * Clear error indication from any of the path arguments which
8965 * would cause this file index entry to be displayed.
8967 TAILQ_FOREACH(pe, paths, entry) {
8968 if (got_path_cmp(path, pe->path, strlen(path),
8969 pe->path_len) == 0 ||
8970 got_path_is_child(path, pe->path, pe->path_len))
8971 pe->data = NULL; /* no error */
8974 printf(GOT_COMMIT_SEP_STR);
8975 if (S_ISLNK(mode))
8976 printf("symlink: %s\n", path);
8977 else if (S_ISREG(mode)) {
8978 printf("file: %s\n", path);
8979 printf("mode: %o\n", mode & (S_IRWXU | S_IRWXG | S_IRWXO));
8980 } else if (S_ISDIR(mode))
8981 printf("directory: %s\n", path);
8982 else
8983 printf("something: %s\n", path);
8985 tm = localtime_r(&mtime, &mytm);
8986 if (tm == NULL)
8987 return NULL;
8988 if (strftime(datebuf, sizeof(datebuf), "%c %Z", tm) == 0)
8989 return got_error(GOT_ERR_NO_SPACE);
8990 printf("timestamp: %s\n", datebuf);
8992 if (blob_id) {
8993 err = got_object_id_str(&id_str, blob_id);
8994 if (err)
8995 return err;
8996 printf("based on blob: %s\n", id_str);
8997 free(id_str);
9000 if (staged_blob_id) {
9001 err = got_object_id_str(&id_str, staged_blob_id);
9002 if (err)
9003 return err;
9004 printf("based on staged blob: %s\n", id_str);
9005 free(id_str);
9008 if (commit_id) {
9009 err = got_object_id_str(&id_str, commit_id);
9010 if (err)
9011 return err;
9012 printf("based on commit: %s\n", id_str);
9013 free(id_str);
9016 return NULL;
9019 static const struct got_error *
9020 cmd_info(int argc, char *argv[])
9022 const struct got_error *error = NULL;
9023 struct got_worktree *worktree = NULL;
9024 char *cwd = NULL, *id_str = NULL;
9025 struct got_pathlist_head paths;
9026 char *uuidstr = NULL;
9027 int ch, show_files = 0;
9029 TAILQ_INIT(&paths);
9031 #ifndef PROFILE
9032 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
9033 NULL) == -1)
9034 err(1, "pledge");
9035 #endif
9037 while ((ch = getopt(argc, argv, "")) != -1) {
9038 switch (ch) {
9039 default:
9040 usage_info();
9041 /* NOTREACHED */
9045 argc -= optind;
9046 argv += optind;
9048 cwd = getcwd(NULL, 0);
9049 if (cwd == NULL) {
9050 error = got_error_from_errno("getcwd");
9051 goto done;
9054 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_CVG_DIR);
9055 if (error) {
9056 if (error->code == GOT_ERR_NOT_WORKTREE)
9057 error = wrap_not_worktree_error(error, "info", cwd);
9058 goto done;
9061 #ifndef PROFILE
9062 /* Remove "wpath cpath proc exec sendfd" promises. */
9063 if (pledge("stdio rpath flock unveil", NULL) == -1)
9064 err(1, "pledge");
9065 #endif
9066 error = apply_unveil(NULL, 0, got_worktree_get_root_path(worktree));
9067 if (error)
9068 goto done;
9070 if (argc >= 1) {
9071 error = get_worktree_paths_from_argv(&paths, argc, argv,
9072 worktree);
9073 if (error)
9074 goto done;
9075 show_files = 1;
9078 error = got_object_id_str(&id_str,
9079 got_worktree_get_base_commit_id(worktree));
9080 if (error)
9081 goto done;
9083 error = got_worktree_get_uuid(&uuidstr, worktree);
9084 if (error)
9085 goto done;
9087 printf("work tree: %s\n", got_worktree_get_root_path(worktree));
9088 printf("work tree base commit: %s\n", id_str);
9089 printf("work tree path prefix: %s\n",
9090 got_worktree_get_path_prefix(worktree));
9091 printf("work tree branch reference: %s\n",
9092 got_worktree_get_head_ref_name(worktree));
9093 printf("work tree UUID: %s\n", uuidstr);
9094 printf("repository: %s\n", got_worktree_get_repo_path(worktree));
9096 if (show_files) {
9097 struct got_pathlist_entry *pe;
9098 TAILQ_FOREACH(pe, &paths, entry) {
9099 if (pe->path_len == 0)
9100 continue;
9102 * Assume this path will fail. This will be corrected
9103 * in print_path_info() in case the path does suceeed.
9105 pe->data = (void *)got_error(GOT_ERR_BAD_PATH);
9107 error = got_worktree_path_info(worktree, &paths,
9108 print_path_info, &paths, check_cancelled, NULL);
9109 if (error)
9110 goto done;
9111 TAILQ_FOREACH(pe, &paths, entry) {
9112 if (pe->data != NULL) {
9113 const struct got_error *perr;
9115 perr = pe->data;
9116 error = got_error_fmt(perr->code, "%s",
9117 pe->path);
9118 break;
9122 done:
9123 if (worktree)
9124 got_worktree_close(worktree);
9125 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
9126 free(cwd);
9127 free(id_str);
9128 free(uuidstr);
9129 return error;