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, repo);
2308 if (error != NULL && !(error->code == GOT_ERR_ERRNO && errno == EEXIST))
2309 goto done;
2311 error = got_worktree_open(&worktree, worktree_path);
2312 if (error != NULL)
2313 goto done;
2315 error = got_worktree_match_path_prefix(&same_path_prefix, worktree,
2316 path_prefix);
2317 if (error != NULL)
2318 goto done;
2319 if (!same_path_prefix) {
2320 error = got_error(GOT_ERR_PATH_PREFIX);
2321 goto done;
2324 if (commit_id_str) {
2325 struct got_reflist_head refs;
2326 TAILQ_INIT(&refs);
2327 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
2328 NULL);
2329 if (error)
2330 goto done;
2331 error = got_repo_match_object_id(&commit_id, NULL,
2332 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
2333 got_ref_list_free(&refs);
2334 if (error)
2335 goto done;
2336 error = check_linear_ancestry(commit_id,
2337 got_worktree_get_base_commit_id(worktree), 0, repo);
2338 if (error != NULL) {
2339 if (error->code == GOT_ERR_ANCESTRY) {
2340 error = checkout_ancestry_error(
2341 head_ref, commit_id_str);
2343 goto done;
2345 error = check_same_branch(commit_id, head_ref, repo);
2346 if (error) {
2347 if (error->code == GOT_ERR_ANCESTRY) {
2348 error = checkout_ancestry_error(
2349 head_ref, commit_id_str);
2351 goto done;
2353 error = got_worktree_set_base_commit_id(worktree, repo,
2354 commit_id);
2355 if (error)
2356 goto done;
2357 /* Expand potentially abbreviated commit ID string. */
2358 free(commit_id_str);
2359 error = got_object_id_str(&commit_id_str, commit_id);
2360 if (error)
2361 goto done;
2362 } else {
2363 commit_id = got_object_id_dup(
2364 got_worktree_get_base_commit_id(worktree));
2365 if (commit_id == NULL) {
2366 error = got_error_from_errno("got_object_id_dup");
2367 goto done;
2369 error = got_object_id_str(&commit_id_str, commit_id);
2370 if (error)
2371 goto done;
2374 error = got_pathlist_append(&paths, "", NULL);
2375 if (error)
2376 goto done;
2377 cpa.worktree_path = worktree_path;
2378 cpa.had_base_commit_ref_error = 0;
2379 cpa.verbosity = verbosity;
2380 error = got_worktree_checkout_files(worktree, &paths, repo,
2381 checkout_progress, &cpa, check_cancelled, NULL);
2382 if (error != NULL)
2383 goto done;
2385 if (got_ref_is_symbolic(head_ref)) {
2386 error = got_ref_resolve_symbolic(&ref, repo, head_ref);
2387 if (error)
2388 goto done;
2389 refname = got_ref_get_name(ref);
2390 } else
2391 refname = got_ref_get_name(head_ref);
2392 printf("Checked out %s: %s\n", refname, commit_id_str);
2393 printf("Now shut up and hack\n");
2394 if (cpa.had_base_commit_ref_error)
2395 show_worktree_base_ref_warning();
2396 done:
2397 if (pack_fds) {
2398 const struct got_error *pack_err =
2399 got_repo_pack_fds_close(pack_fds);
2400 if (error == NULL)
2401 error = pack_err;
2403 if (head_ref)
2404 got_ref_close(head_ref);
2405 if (ref)
2406 got_ref_close(ref);
2407 if (repo) {
2408 const struct got_error *close_err = got_repo_close(repo);
2409 if (error == NULL)
2410 error = close_err;
2412 got_pathlist_free(&paths, GOT_PATHLIST_FREE_NONE);
2413 free(commit_id_str);
2414 free(commit_id);
2415 free(repo_path);
2416 free(worktree_path);
2417 free(cwd);
2418 return error;
2421 struct got_update_progress_arg {
2422 int did_something;
2423 int conflicts;
2424 int obstructed;
2425 int not_updated;
2426 int missing;
2427 int not_deleted;
2428 int unversioned;
2429 int verbosity;
2432 static void
2433 print_update_progress_stats(struct got_update_progress_arg *upa)
2435 if (!upa->did_something)
2436 return;
2438 if (upa->conflicts > 0)
2439 printf("Files with new merge conflicts: %d\n", upa->conflicts);
2440 if (upa->obstructed > 0)
2441 printf("File paths obstructed by a non-regular file: %d\n",
2442 upa->obstructed);
2443 if (upa->not_updated > 0)
2444 printf("Files not updated because of existing merge "
2445 "conflicts: %d\n", upa->not_updated);
2449 * The meaning of some status codes differs between merge-style operations and
2450 * update operations. For example, the ! status code means "file was missing"
2451 * if changes were merged into the work tree, and "missing file was restored"
2452 * if the work tree was updated. This function should be used by any operation
2453 * which merges changes into the work tree without updating the work tree.
2455 static void
2456 print_merge_progress_stats(struct got_update_progress_arg *upa)
2458 if (!upa->did_something)
2459 return;
2461 if (upa->conflicts > 0)
2462 printf("Files with new merge conflicts: %d\n", upa->conflicts);
2463 if (upa->obstructed > 0)
2464 printf("File paths obstructed by a non-regular file: %d\n",
2465 upa->obstructed);
2466 if (upa->missing > 0)
2467 printf("Files which had incoming changes but could not be "
2468 "found in the work tree: %d\n", upa->missing);
2469 if (upa->not_deleted > 0)
2470 printf("Files not deleted due to differences in deleted "
2471 "content: %d\n", upa->not_deleted);
2472 if (upa->unversioned > 0)
2473 printf("Files not merged because an unversioned file was "
2474 "found in the work tree: %d\n", upa->unversioned);
2477 __dead static void
2478 usage_update(void)
2480 fprintf(stderr, "usage: %s update [-qtvX] [-c commit] [-r remote] "
2481 "[path ...]\n", getprogname());
2482 exit(1);
2485 static const struct got_error *
2486 update_progress(void *arg, unsigned char status, const char *path)
2488 struct got_update_progress_arg *upa = arg;
2490 if (status == GOT_STATUS_EXISTS ||
2491 status == GOT_STATUS_BASE_REF_ERR)
2492 return NULL;
2494 upa->did_something = 1;
2496 /* Base commit bump happens silently. */
2497 if (status == GOT_STATUS_BUMP_BASE)
2498 return NULL;
2500 if (status == GOT_STATUS_CONFLICT)
2501 upa->conflicts++;
2502 if (status == GOT_STATUS_OBSTRUCTED)
2503 upa->obstructed++;
2504 if (status == GOT_STATUS_CANNOT_UPDATE)
2505 upa->not_updated++;
2506 if (status == GOT_STATUS_MISSING)
2507 upa->missing++;
2508 if (status == GOT_STATUS_CANNOT_DELETE)
2509 upa->not_deleted++;
2510 if (status == GOT_STATUS_UNVERSIONED)
2511 upa->unversioned++;
2513 while (path[0] == '/')
2514 path++;
2515 if (upa->verbosity >= 0)
2516 printf("%c %s\n", status, path);
2518 return NULL;
2521 static const struct got_error *
2522 check_rebase_or_histedit_in_progress(struct got_worktree *worktree)
2524 const struct got_error *err;
2525 int in_progress;
2527 err = got_worktree_rebase_in_progress(&in_progress, worktree);
2528 if (err)
2529 return err;
2530 if (in_progress)
2531 return got_error(GOT_ERR_REBASING);
2533 err = got_worktree_histedit_in_progress(&in_progress, worktree);
2534 if (err)
2535 return err;
2536 if (in_progress)
2537 return got_error(GOT_ERR_HISTEDIT_BUSY);
2539 return NULL;
2542 static const struct got_error *
2543 check_merge_in_progress(struct got_worktree *worktree,
2544 struct got_repository *repo)
2546 const struct got_error *err;
2547 int in_progress;
2549 err = got_worktree_merge_in_progress(&in_progress, worktree, repo);
2550 if (err)
2551 return err;
2552 if (in_progress)
2553 return got_error(GOT_ERR_MERGE_BUSY);
2555 return NULL;
2558 static const struct got_error *
2559 get_worktree_paths_from_argv(struct got_pathlist_head *paths, int argc,
2560 char *argv[], struct got_worktree *worktree)
2562 const struct got_error *err = NULL;
2563 char *path;
2564 struct got_pathlist_entry *new;
2565 int i;
2567 if (argc == 0) {
2568 path = strdup("");
2569 if (path == NULL)
2570 return got_error_from_errno("strdup");
2571 return got_pathlist_append(paths, path, NULL);
2574 for (i = 0; i < argc; i++) {
2575 err = got_worktree_resolve_path(&path, worktree, argv[i]);
2576 if (err)
2577 break;
2578 err = got_pathlist_insert(&new, paths, path, NULL);
2579 if (err || new == NULL /* duplicate */) {
2580 free(path);
2581 if (err)
2582 break;
2586 return err;
2589 static const struct got_error *
2590 wrap_not_worktree_error(const struct got_error *orig_err,
2591 const char *cmdname, const char *path)
2593 const struct got_error *err;
2594 struct got_repository *repo;
2595 static char msg[512];
2596 int *pack_fds = NULL;
2598 err = got_repo_pack_fds_open(&pack_fds);
2599 if (err)
2600 return err;
2602 err = got_repo_open(&repo, path, NULL, pack_fds);
2603 if (err)
2604 return orig_err;
2606 snprintf(msg, sizeof(msg),
2607 "'got %s' needs a work tree in addition to a git repository\n"
2608 "Work trees can be checked out from this Git repository with "
2609 "'got checkout'.\n"
2610 "The got(1) manual page contains more information.", cmdname);
2611 err = got_error_msg(GOT_ERR_NOT_WORKTREE, msg);
2612 if (repo) {
2613 const struct got_error *close_err = got_repo_close(repo);
2614 if (err == NULL)
2615 err = close_err;
2617 if (pack_fds) {
2618 const struct got_error *pack_err =
2619 got_repo_pack_fds_close(pack_fds);
2620 if (err == NULL)
2621 err = pack_err;
2623 return err;
2626 static const struct got_error *
2627 cmd_update(int argc, char *argv[])
2629 const struct got_error *error = NULL, *unlock_err;
2630 char *worktree_path = NULL;
2631 const char *repo_path = NULL;
2632 const char *remote_name = NULL;
2633 char *proto = NULL, *host = NULL, *port = NULL;
2634 char *repo_name = NULL, *server_path = NULL;
2635 const struct got_remote_repo *remotes, *remote = NULL;
2636 int nremotes;
2637 char *id_str = NULL;
2638 struct got_repository *repo = NULL;
2639 struct got_worktree *worktree = NULL;
2640 const struct got_gotconfig *repo_conf = NULL, *worktree_conf = NULL;
2641 struct got_pathlist_head paths, refs, symrefs;
2642 struct got_pathlist_head wanted_branches, wanted_refs;
2643 struct got_pathlist_entry *pe;
2644 struct got_reflist_head remote_refs;
2645 struct got_reflist_entry *re;
2646 struct got_object_id *pack_hash = NULL;
2647 int i, ch, fetchfd = -1, fetchstatus;
2648 pid_t fetchpid = -1;
2649 struct got_fetch_progress_arg fpa;
2650 struct got_update_progress_arg upa;
2651 int verbosity = 0;
2652 int delete_remote = 0;
2653 int replace_tags = 0;
2654 int *pack_fds = NULL;
2655 const char *remote_head = NULL, *worktree_branch = NULL;
2656 struct got_object_id *commit_id = NULL;
2657 char *commit_id_str = NULL;
2658 const char *refname;
2659 struct got_reference *head_ref = NULL;
2661 TAILQ_INIT(&paths);
2662 TAILQ_INIT(&refs);
2663 TAILQ_INIT(&symrefs);
2664 TAILQ_INIT(&remote_refs);
2665 TAILQ_INIT(&wanted_branches);
2666 TAILQ_INIT(&wanted_refs);
2668 while ((ch = getopt(argc, argv, "c:qr:vX")) != -1) {
2669 switch (ch) {
2670 case 'c':
2671 commit_id_str = strdup(optarg);
2672 if (commit_id_str == NULL)
2673 return got_error_from_errno("strdup");
2674 break;
2675 case 't':
2676 replace_tags = 1;
2677 break;
2678 case 'q':
2679 verbosity = -1;
2680 break;
2681 case 'r':
2682 remote_name = optarg;
2683 break;
2684 case 'v':
2685 if (verbosity < 0)
2686 verbosity = 0;
2687 else if (verbosity < 3)
2688 verbosity++;
2689 break;
2690 case 'X':
2691 delete_remote = 1;
2692 break;
2693 default:
2694 usage_update();
2695 break;
2698 argc -= optind;
2699 argv += optind;
2701 if (delete_remote) {
2702 if (replace_tags)
2703 option_conflict('X', 't');
2704 if (remote_name == NULL)
2705 errx(1, "-X option requires a remote name");
2707 if (remote_name == NULL)
2708 remote_name = GOT_FETCH_DEFAULT_REMOTE_NAME;
2710 worktree_path = getcwd(NULL, 0);
2711 if (worktree_path == NULL) {
2712 error = got_error_from_errno("getcwd");
2713 goto done;
2715 error = got_worktree_open(&worktree, worktree_path);
2716 if (error) {
2717 if (error->code == GOT_ERR_NOT_WORKTREE)
2718 error = wrap_not_worktree_error(error, "update",
2719 worktree_path);
2720 goto done;
2722 repo_path = got_worktree_get_repo_path(worktree);
2724 error = got_repo_pack_fds_open(&pack_fds);
2725 if (error != NULL)
2726 goto done;
2728 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
2729 if (error)
2730 goto done;
2732 error = check_rebase_or_histedit_in_progress(worktree);
2733 if (error)
2734 goto done;
2735 error = check_merge_in_progress(worktree, repo);
2736 if (error)
2737 goto done;
2739 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
2740 if (error)
2741 goto done;
2743 worktree_conf = got_worktree_get_gotconfig(worktree);
2744 if (worktree_conf) {
2745 got_gotconfig_get_remotes(&nremotes, &remotes,
2746 worktree_conf);
2747 for (i = 0; i < nremotes; i++) {
2748 if (strcmp(remotes[i].name, remote_name) == 0) {
2749 remote = &remotes[i];
2750 break;
2755 if (remote == NULL) {
2756 repo_conf = got_repo_get_gotconfig(repo);
2757 if (repo_conf) {
2758 got_gotconfig_get_remotes(&nremotes, &remotes,
2759 repo_conf);
2760 for (i = 0; i < nremotes; i++) {
2761 if (strcmp(remotes[i].name, remote_name) == 0) {
2762 remote = &remotes[i];
2763 break;
2768 if (remote == NULL) {
2769 got_repo_get_gitconfig_remotes(&nremotes, &remotes, repo);
2770 for (i = 0; i < nremotes; i++) {
2771 if (strcmp(remotes[i].name, remote_name) == 0) {
2772 remote = &remotes[i];
2773 break;
2777 if (remote == NULL) {
2778 error = got_error_path(remote_name, GOT_ERR_NO_REMOTE);
2779 goto done;
2782 error = got_dial_parse_uri(&proto, &host, &port, &server_path,
2783 &repo_name, remote->fetch_url);
2784 if (error)
2785 goto done;
2787 if (strcmp(proto, "git") == 0) {
2788 #ifndef PROFILE
2789 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
2790 "sendfd dns inet unveil", NULL) == -1)
2791 err(1, "pledge");
2792 #endif
2793 } else if (strcmp(proto, "git+ssh") == 0 ||
2794 strcmp(proto, "ssh") == 0) {
2795 #ifndef PROFILE
2796 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
2797 "sendfd unveil", NULL) == -1)
2798 err(1, "pledge");
2799 #endif
2800 } else if (strcmp(proto, "http") == 0 ||
2801 strcmp(proto, "git+http") == 0) {
2802 error = got_error_path(proto, GOT_ERR_NOT_IMPL);
2803 goto done;
2804 } else {
2805 error = got_error_path(proto, GOT_ERR_BAD_PROTO);
2806 goto done;
2809 error = got_dial_apply_unveil(proto);
2810 if (error)
2811 goto done;
2813 error = apply_unveil(got_repo_get_path(repo), 0,
2814 got_worktree_get_root_path(worktree));
2815 if (error)
2816 goto done;
2818 if (verbosity >= 0) {
2819 printf("Connecting to \"%s\" %s://%s%s%s%s%s\n",
2820 remote->name, proto, host,
2821 port ? ":" : "", port ? port : "",
2822 *server_path == '/' ? "" : "/", server_path);
2825 error = got_fetch_connect(&fetchpid, &fetchfd, proto, host, port,
2826 server_path, verbosity);
2827 if (error)
2828 goto done;
2831 * If set, get this remote's HEAD ref target so
2832 * if it has changed on the server we can fetch it.
2834 error = got_ref_list(&remote_refs, repo, "refs/remotes",
2835 got_ref_cmp_by_name, repo);
2836 if (error)
2837 goto done;
2839 TAILQ_FOREACH(re, &remote_refs, entry) {
2840 const char *remote_refname, *remote_target;
2841 size_t remote_name_len;
2843 if (!got_ref_is_symbolic(re->ref))
2844 continue;
2846 remote_name_len = strlen(remote->name);
2847 remote_refname = got_ref_get_name(re->ref);
2849 /* we only want refs/remotes/$remote->name/HEAD */
2850 if (strncmp(remote_refname + 13, remote->name,
2851 remote_name_len) != 0)
2852 continue;
2854 if (strcmp(remote_refname + remote_name_len + 14,
2855 GOT_REF_HEAD) != 0)
2856 continue;
2859 * Take the name itself because we already
2860 * only match with refs/heads/ in fetch_pack().
2862 remote_target = got_ref_get_symref_target(re->ref);
2863 remote_head = remote_target + remote_name_len + 14;
2864 break;
2867 refname = got_worktree_get_head_ref_name(worktree);
2868 if (strncmp(refname, "refs/heads/", 11) == 0)
2869 worktree_branch = refname;
2871 fpa.last_scaled_size[0] = '\0';
2872 fpa.last_p_indexed = -1;
2873 fpa.last_p_resolved = -1;
2874 fpa.verbosity = verbosity;
2875 fpa.repo = repo;
2876 fpa.create_configs = 0;
2877 fpa.configs_created = 0;
2878 memset(&fpa.config_info, 0, sizeof(fpa.config_info));
2880 error = got_fetch_pack(&pack_hash, &refs, &symrefs, remote->name,
2881 remote->mirror_references, 0, &wanted_branches, &wanted_refs,
2882 0, verbosity, fetchfd, repo, worktree_branch, remote_head,
2883 0, fetch_progress, &fpa);
2884 if (error)
2885 goto done;
2887 if (pack_hash != NULL && verbosity >= 0) {
2888 error = got_object_id_str(&id_str, pack_hash);
2889 if (error)
2890 goto done;
2891 printf("\nFetched %s.pack\n", id_str);
2892 free(id_str);
2893 id_str = NULL;
2896 /* Update references provided with the pack file. */
2897 TAILQ_FOREACH(pe, &refs, entry) {
2898 const char *refname = pe->path;
2899 struct got_object_id *id = pe->data;
2900 struct got_reference *ref;
2902 if (is_wanted_ref(&wanted_refs, refname)) {
2903 error = update_wanted_ref(refname, id,
2904 remote->name, verbosity, repo);
2905 if (error)
2906 goto done;
2907 continue;
2910 error = got_ref_open(&ref, repo, refname, 1);
2911 if (error) {
2912 if (error->code != GOT_ERR_NOT_REF)
2913 goto done;
2914 error = create_ref(refname, id, verbosity,
2915 repo);
2916 if (error)
2917 goto done;
2918 } else {
2919 error = update_ref(ref, id, replace_tags,
2920 verbosity-1, repo);
2921 unlock_err = got_ref_unlock(ref);
2922 if (unlock_err && error == NULL)
2923 error = unlock_err;
2924 got_ref_close(ref);
2925 if (error)
2926 goto done;
2930 /* Update worktree */
2931 error = got_ref_open(&head_ref, repo,
2932 got_worktree_get_head_ref_name(worktree), 0);
2933 if (error != NULL)
2934 goto done;
2935 if (commit_id_str == NULL) {
2936 error = got_ref_resolve(&commit_id, repo, head_ref);
2937 if (error != NULL)
2938 goto done;
2939 error = got_object_id_str(&commit_id_str, commit_id);
2940 if (error != NULL)
2941 goto done;
2942 } else {
2943 struct got_reflist_head refs;
2944 TAILQ_INIT(&refs);
2945 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
2946 NULL);
2947 if (error)
2948 goto done;
2949 error = got_repo_match_object_id(&commit_id, NULL,
2950 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
2951 got_ref_list_free(&refs);
2952 free(commit_id_str);
2953 commit_id_str = NULL;
2954 if (error)
2955 goto done;
2956 error = got_object_id_str(&commit_id_str, commit_id);
2957 if (error)
2958 goto done;
2962 error = check_linear_ancestry(commit_id,
2963 got_worktree_get_base_commit_id(worktree), 0, repo);
2964 if (error != NULL) {
2965 if (error->code == GOT_ERR_ANCESTRY)
2966 error = got_error(GOT_ERR_BRANCH_MOVED);
2967 goto done;
2969 error = check_same_branch(commit_id, head_ref, repo);
2970 if (error)
2971 goto done;
2973 if (got_object_id_cmp(got_worktree_get_base_commit_id(worktree),
2974 commit_id) != 0) {
2975 error = got_worktree_set_base_commit_id(worktree, repo,
2976 commit_id);
2977 if (error)
2978 goto done;
2981 memset(&upa, 0, sizeof(upa));
2982 upa.verbosity = verbosity;
2983 error = got_worktree_checkout_files(worktree, &paths, repo,
2984 update_progress, &upa, check_cancelled, NULL);
2985 if (error != NULL)
2986 goto done;
2988 if (upa.did_something) {
2989 printf("Updated to %s: %s\n",
2990 got_worktree_get_head_ref_name(worktree), commit_id_str);
2991 } else
2992 printf("Already up-to-date\n");
2994 print_update_progress_stats(&upa);
2995 done:
2996 if (fetchpid > 0) {
2997 if (kill(fetchpid, SIGTERM) == -1)
2998 error = got_error_from_errno("kill");
2999 if (waitpid(fetchpid, &fetchstatus, 0) == -1 && error == NULL)
3000 error = got_error_from_errno("waitpid");
3002 if (fetchfd != -1 && close(fetchfd) == -1 && error == NULL)
3003 error = got_error_from_errno("close");
3004 if (repo) {
3005 const struct got_error *close_err = got_repo_close(repo);
3006 if (error == NULL)
3007 error = close_err;
3009 if (worktree)
3010 got_worktree_close(worktree);
3011 if (pack_fds) {
3012 const struct got_error *pack_err =
3013 got_repo_pack_fds_close(pack_fds);
3014 if (error == NULL)
3015 error = pack_err;
3017 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
3018 got_pathlist_free(&refs, GOT_PATHLIST_FREE_ALL);
3019 got_pathlist_free(&symrefs, GOT_PATHLIST_FREE_ALL);
3020 got_pathlist_free(&wanted_branches, GOT_PATHLIST_FREE_NONE);
3021 got_pathlist_free(&wanted_refs, GOT_PATHLIST_FREE_NONE);
3022 got_ref_list_free(&remote_refs);
3023 free(id_str);
3024 free(worktree_path);
3025 free(pack_hash);
3026 free(proto);
3027 free(host);
3028 free(port);
3029 free(server_path);
3030 free(repo_name);
3031 free(commit_id);
3032 free(commit_id_str);
3033 return error;
3036 static const struct got_error *
3037 diff_blobs(struct got_object_id *blob_id1, struct got_object_id *blob_id2,
3038 const char *path, int diff_context, int ignore_whitespace,
3039 int force_text_diff, struct got_diffstat_cb_arg *dsa,
3040 struct got_repository *repo, FILE *outfile)
3042 const struct got_error *err = NULL;
3043 struct got_blob_object *blob1 = NULL, *blob2 = NULL;
3044 FILE *f1 = NULL, *f2 = NULL;
3045 int fd1 = -1, fd2 = -1;
3047 fd1 = got_opentempfd();
3048 if (fd1 == -1)
3049 return got_error_from_errno("got_opentempfd");
3050 fd2 = got_opentempfd();
3051 if (fd2 == -1) {
3052 err = got_error_from_errno("got_opentempfd");
3053 goto done;
3056 if (blob_id1) {
3057 err = got_object_open_as_blob(&blob1, repo, blob_id1, 8192,
3058 fd1);
3059 if (err)
3060 goto done;
3063 err = got_object_open_as_blob(&blob2, repo, blob_id2, 8192, fd2);
3064 if (err)
3065 goto done;
3067 f1 = got_opentemp();
3068 if (f1 == NULL) {
3069 err = got_error_from_errno("got_opentemp");
3070 goto done;
3072 f2 = got_opentemp();
3073 if (f2 == NULL) {
3074 err = got_error_from_errno("got_opentemp");
3075 goto done;
3078 while (path[0] == '/')
3079 path++;
3080 err = got_diff_blob(NULL, NULL, blob1, blob2, f1, f2, path, path,
3081 GOT_DIFF_ALGORITHM_PATIENCE, diff_context, ignore_whitespace,
3082 force_text_diff, dsa, outfile);
3083 done:
3084 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
3085 err = got_error_from_errno("close");
3086 if (blob1)
3087 got_object_blob_close(blob1);
3088 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
3089 err = got_error_from_errno("close");
3090 if (blob2)
3091 got_object_blob_close(blob2);
3092 if (f1 && fclose(f1) == EOF && err == NULL)
3093 err = got_error_from_errno("fclose");
3094 if (f2 && fclose(f2) == EOF && err == NULL)
3095 err = got_error_from_errno("fclose");
3096 return err;
3099 static const struct got_error *
3100 diff_trees(struct got_object_id *tree_id1, struct got_object_id *tree_id2,
3101 const char *path, int diff_context, int ignore_whitespace,
3102 int force_text_diff, struct got_diffstat_cb_arg *dsa,
3103 struct got_repository *repo, FILE *outfile)
3105 const struct got_error *err = NULL;
3106 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
3107 struct got_diff_blob_output_unidiff_arg arg;
3108 FILE *f1 = NULL, *f2 = NULL;
3109 int fd1 = -1, fd2 = -1;
3111 if (tree_id1) {
3112 err = got_object_open_as_tree(&tree1, repo, tree_id1);
3113 if (err)
3114 goto done;
3115 fd1 = got_opentempfd();
3116 if (fd1 == -1) {
3117 err = got_error_from_errno("got_opentempfd");
3118 goto done;
3122 err = got_object_open_as_tree(&tree2, repo, tree_id2);
3123 if (err)
3124 goto done;
3126 f1 = got_opentemp();
3127 if (f1 == NULL) {
3128 err = got_error_from_errno("got_opentemp");
3129 goto done;
3132 f2 = got_opentemp();
3133 if (f2 == NULL) {
3134 err = got_error_from_errno("got_opentemp");
3135 goto done;
3137 fd2 = got_opentempfd();
3138 if (fd2 == -1) {
3139 err = got_error_from_errno("got_opentempfd");
3140 goto done;
3142 arg.diff_context = diff_context;
3143 arg.ignore_whitespace = ignore_whitespace;
3144 arg.force_text_diff = force_text_diff;
3145 arg.diffstat = dsa;
3146 arg.diff_algo = GOT_DIFF_ALGORITHM_PATIENCE;
3147 arg.outfile = outfile;
3148 arg.lines = NULL;
3149 arg.nlines = 0;
3150 while (path[0] == '/')
3151 path++;
3152 err = got_diff_tree(tree1, tree2, f1, f2, fd1, fd2, path, path, repo,
3153 got_diff_blob_output_unidiff, &arg, 1);
3154 done:
3155 if (tree1)
3156 got_object_tree_close(tree1);
3157 if (tree2)
3158 got_object_tree_close(tree2);
3159 if (f1 && fclose(f1) == EOF && err == NULL)
3160 err = got_error_from_errno("fclose");
3161 if (f2 && fclose(f2) == EOF && err == NULL)
3162 err = got_error_from_errno("fclose");
3163 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
3164 err = got_error_from_errno("close");
3165 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
3166 err = got_error_from_errno("close");
3167 return err;
3170 static const struct got_error *
3171 get_changed_paths(struct got_pathlist_head *paths,
3172 struct got_commit_object *commit, struct got_repository *repo,
3173 struct got_diffstat_cb_arg *dsa)
3175 const struct got_error *err = NULL;
3176 struct got_object_id *tree_id1 = NULL, *tree_id2 = NULL;
3177 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
3178 struct got_object_qid *qid;
3179 got_diff_blob_cb cb = got_diff_tree_collect_changed_paths;
3180 FILE *f1 = NULL, *f2 = NULL;
3181 int fd1 = -1, fd2 = -1;
3183 if (dsa) {
3184 cb = got_diff_tree_compute_diffstat;
3186 f1 = got_opentemp();
3187 if (f1 == NULL) {
3188 err = got_error_from_errno("got_opentemp");
3189 goto done;
3191 f2 = got_opentemp();
3192 if (f2 == NULL) {
3193 err = got_error_from_errno("got_opentemp");
3194 goto done;
3196 fd1 = got_opentempfd();
3197 if (fd1 == -1) {
3198 err = got_error_from_errno("got_opentempfd");
3199 goto done;
3201 fd2 = got_opentempfd();
3202 if (fd2 == -1) {
3203 err = got_error_from_errno("got_opentempfd");
3204 goto done;
3208 qid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
3209 if (qid != NULL) {
3210 struct got_commit_object *pcommit;
3211 err = got_object_open_as_commit(&pcommit, repo,
3212 &qid->id);
3213 if (err)
3214 return err;
3216 tree_id1 = got_object_id_dup(
3217 got_object_commit_get_tree_id(pcommit));
3218 if (tree_id1 == NULL) {
3219 got_object_commit_close(pcommit);
3220 return got_error_from_errno("got_object_id_dup");
3222 got_object_commit_close(pcommit);
3226 if (tree_id1) {
3227 err = got_object_open_as_tree(&tree1, repo, tree_id1);
3228 if (err)
3229 goto done;
3232 tree_id2 = got_object_commit_get_tree_id(commit);
3233 err = got_object_open_as_tree(&tree2, repo, tree_id2);
3234 if (err)
3235 goto done;
3237 err = got_diff_tree(tree1, tree2, f1, f2, fd1, fd2, "", "", repo,
3238 cb, dsa ? (void *)dsa : paths, dsa ? 1 : 0);
3239 done:
3240 if (tree1)
3241 got_object_tree_close(tree1);
3242 if (tree2)
3243 got_object_tree_close(tree2);
3244 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
3245 err = got_error_from_errno("close");
3246 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
3247 err = got_error_from_errno("close");
3248 if (f1 && fclose(f1) == EOF && err == NULL)
3249 err = got_error_from_errno("fclose");
3250 if (f2 && fclose(f2) == EOF && err == NULL)
3251 err = got_error_from_errno("fclose");
3252 free(tree_id1);
3253 return err;
3256 static const struct got_error *
3257 print_patch(struct got_commit_object *commit, struct got_object_id *id,
3258 const char *path, int diff_context, struct got_diffstat_cb_arg *dsa,
3259 struct got_repository *repo, FILE *outfile)
3261 const struct got_error *err = NULL;
3262 struct got_commit_object *pcommit = NULL;
3263 char *id_str1 = NULL, *id_str2 = NULL;
3264 struct got_object_id *obj_id1 = NULL, *obj_id2 = NULL;
3265 struct got_object_qid *qid;
3267 qid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
3268 if (qid != NULL) {
3269 err = got_object_open_as_commit(&pcommit, repo,
3270 &qid->id);
3271 if (err)
3272 return err;
3273 err = got_object_id_str(&id_str1, &qid->id);
3274 if (err)
3275 goto done;
3278 err = got_object_id_str(&id_str2, id);
3279 if (err)
3280 goto done;
3282 if (path && path[0] != '\0') {
3283 int obj_type;
3284 err = got_object_id_by_path(&obj_id2, repo, commit, path);
3285 if (err)
3286 goto done;
3287 if (pcommit) {
3288 err = got_object_id_by_path(&obj_id1, repo,
3289 pcommit, path);
3290 if (err) {
3291 if (err->code != GOT_ERR_NO_TREE_ENTRY) {
3292 free(obj_id2);
3293 goto done;
3297 err = got_object_get_type(&obj_type, repo, obj_id2);
3298 if (err) {
3299 free(obj_id2);
3300 goto done;
3302 fprintf(outfile,
3303 "diff %s %s\n", id_str1 ? id_str1 : "/dev/null", id_str2);
3304 fprintf(outfile, "commit - %s\n",
3305 id_str1 ? id_str1 : "/dev/null");
3306 fprintf(outfile, "commit + %s\n", id_str2);
3307 switch (obj_type) {
3308 case GOT_OBJ_TYPE_BLOB:
3309 err = diff_blobs(obj_id1, obj_id2, path, diff_context,
3310 0, 0, dsa, repo, outfile);
3311 break;
3312 case GOT_OBJ_TYPE_TREE:
3313 err = diff_trees(obj_id1, obj_id2, path, diff_context,
3314 0, 0, dsa, repo, outfile);
3315 break;
3316 default:
3317 err = got_error(GOT_ERR_OBJ_TYPE);
3318 break;
3320 free(obj_id1);
3321 free(obj_id2);
3322 } else {
3323 obj_id2 = got_object_commit_get_tree_id(commit);
3324 if (pcommit)
3325 obj_id1 = got_object_commit_get_tree_id(pcommit);
3326 fprintf(outfile,
3327 "diff %s %s\n", id_str1 ? id_str1 : "/dev/null", id_str2);
3328 fprintf(outfile, "commit - %s\n",
3329 id_str1 ? id_str1 : "/dev/null");
3330 fprintf(outfile, "commit + %s\n", id_str2);
3331 err = diff_trees(obj_id1, obj_id2, "", diff_context, 0, 0,
3332 dsa, repo, outfile);
3334 done:
3335 free(id_str1);
3336 free(id_str2);
3337 if (pcommit)
3338 got_object_commit_close(pcommit);
3339 return err;
3342 static char *
3343 get_datestr(time_t *time, char *datebuf)
3345 struct tm mytm, *tm;
3346 char *p, *s;
3348 tm = gmtime_r(time, &mytm);
3349 if (tm == NULL)
3350 return NULL;
3351 s = asctime_r(tm, datebuf);
3352 if (s == NULL)
3353 return NULL;
3354 p = strchr(s, '\n');
3355 if (p)
3356 *p = '\0';
3357 return s;
3360 static const struct got_error *
3361 match_commit(int *have_match, struct got_object_id *id,
3362 struct got_commit_object *commit, regex_t *regex)
3364 const struct got_error *err = NULL;
3365 regmatch_t regmatch;
3366 char *id_str = NULL, *logmsg = NULL;
3368 *have_match = 0;
3370 err = got_object_id_str(&id_str, id);
3371 if (err)
3372 return err;
3374 err = got_object_commit_get_logmsg(&logmsg, commit);
3375 if (err)
3376 goto done;
3378 if (regexec(regex, got_object_commit_get_author(commit), 1,
3379 &regmatch, 0) == 0 ||
3380 regexec(regex, got_object_commit_get_committer(commit), 1,
3381 &regmatch, 0) == 0 ||
3382 regexec(regex, id_str, 1, &regmatch, 0) == 0 ||
3383 regexec(regex, logmsg, 1, &regmatch, 0) == 0)
3384 *have_match = 1;
3385 done:
3386 free(id_str);
3387 free(logmsg);
3388 return err;
3391 static void
3392 match_changed_paths(int *have_match, struct got_pathlist_head *changed_paths,
3393 regex_t *regex)
3395 regmatch_t regmatch;
3396 struct got_pathlist_entry *pe;
3398 *have_match = 0;
3400 TAILQ_FOREACH(pe, changed_paths, entry) {
3401 if (regexec(regex, pe->path, 1, &regmatch, 0) == 0) {
3402 *have_match = 1;
3403 break;
3408 static const struct got_error *
3409 match_patch(int *have_match, struct got_commit_object *commit,
3410 struct got_object_id *id, const char *path, int diff_context,
3411 struct got_repository *repo, regex_t *regex, FILE *f)
3413 const struct got_error *err = NULL;
3414 char *line = NULL;
3415 size_t linesize = 0;
3416 regmatch_t regmatch;
3418 *have_match = 0;
3420 err = got_opentemp_truncate(f);
3421 if (err)
3422 return err;
3424 err = print_patch(commit, id, path, diff_context, NULL, repo, f);
3425 if (err)
3426 goto done;
3428 if (fseeko(f, 0L, SEEK_SET) == -1) {
3429 err = got_error_from_errno("fseeko");
3430 goto done;
3433 while (getline(&line, &linesize, f) != -1) {
3434 if (regexec(regex, line, 1, &regmatch, 0) == 0) {
3435 *have_match = 1;
3436 break;
3439 done:
3440 free(line);
3441 return err;
3444 #define GOT_COMMIT_SEP_STR "-----------------------------------------------\n"
3446 static const struct got_error*
3447 build_refs_str(char **refs_str, struct got_reflist_head *refs,
3448 struct got_object_id *id, struct got_repository *repo,
3449 int local_only)
3451 static const struct got_error *err = NULL;
3452 struct got_reflist_entry *re;
3453 char *s;
3454 const char *name;
3456 *refs_str = NULL;
3458 TAILQ_FOREACH(re, refs, entry) {
3459 struct got_tag_object *tag = NULL;
3460 struct got_object_id *ref_id;
3461 int cmp;
3463 name = got_ref_get_name(re->ref);
3464 if (strcmp(name, GOT_REF_HEAD) == 0)
3465 continue;
3466 if (strncmp(name, "refs/", 5) == 0)
3467 name += 5;
3468 if (strncmp(name, "got/", 4) == 0)
3469 continue;
3470 if (strncmp(name, "heads/", 6) == 0)
3471 name += 6;
3472 if (strncmp(name, "remotes/", 8) == 0) {
3473 if (local_only)
3474 continue;
3475 name += 8;
3476 s = strstr(name, "/" GOT_REF_HEAD);
3477 if (s != NULL && strcmp(s, "/" GOT_REF_HEAD) == 0)
3478 continue;
3480 err = got_ref_resolve(&ref_id, repo, re->ref);
3481 if (err)
3482 break;
3483 if (strncmp(name, "tags/", 5) == 0) {
3484 err = got_object_open_as_tag(&tag, repo, ref_id);
3485 if (err) {
3486 if (err->code != GOT_ERR_OBJ_TYPE) {
3487 free(ref_id);
3488 break;
3490 /* Ref points at something other than a tag. */
3491 err = NULL;
3492 tag = NULL;
3495 cmp = got_object_id_cmp(tag ?
3496 got_object_tag_get_object_id(tag) : ref_id, id);
3497 free(ref_id);
3498 if (tag)
3499 got_object_tag_close(tag);
3500 if (cmp != 0)
3501 continue;
3502 s = *refs_str;
3503 if (asprintf(refs_str, "%s%s%s", s ? s : "",
3504 s ? ", " : "", name) == -1) {
3505 err = got_error_from_errno("asprintf");
3506 free(s);
3507 *refs_str = NULL;
3508 break;
3510 free(s);
3513 return err;
3516 static const struct got_error *
3517 print_commit_oneline(struct got_commit_object *commit, struct got_object_id *id,
3518 struct got_repository *repo, struct got_reflist_object_id_map *refs_idmap)
3520 const struct got_error *err = NULL;
3521 char *ref_str = NULL, *id_str = NULL, *logmsg0 = NULL;
3522 char *comma, *s, *nl;
3523 struct got_reflist_head *refs;
3524 char datebuf[12]; /* YYYY-MM-DD + SPACE + NUL */
3525 struct tm tm;
3526 time_t committer_time;
3528 refs = got_reflist_object_id_map_lookup(refs_idmap, id);
3529 if (refs) {
3530 err = build_refs_str(&ref_str, refs, id, repo, 1);
3531 if (err)
3532 return err;
3534 /* Display the first matching ref only. */
3535 if (ref_str && (comma = strchr(ref_str, ',')) != NULL)
3536 *comma = '\0';
3539 if (ref_str == NULL) {
3540 err = got_object_id_str(&id_str, id);
3541 if (err)
3542 return err;
3545 committer_time = got_object_commit_get_committer_time(commit);
3546 if (gmtime_r(&committer_time, &tm) == NULL) {
3547 err = got_error_from_errno("gmtime_r");
3548 goto done;
3550 if (strftime(datebuf, sizeof(datebuf), "%G-%m-%d ", &tm) == 0) {
3551 err = got_error(GOT_ERR_NO_SPACE);
3552 goto done;
3555 err = got_object_commit_get_logmsg(&logmsg0, commit);
3556 if (err)
3557 goto done;
3559 s = logmsg0;
3560 while (isspace((unsigned char)s[0]))
3561 s++;
3563 nl = strchr(s, '\n');
3564 if (nl) {
3565 *nl = '\0';
3568 if (ref_str)
3569 printf("%s%-7s %s\n", datebuf, ref_str, s);
3570 else
3571 printf("%s%.7s %s\n", datebuf, id_str, s);
3573 if (fflush(stdout) != 0 && err == NULL)
3574 err = got_error_from_errno("fflush");
3575 done:
3576 free(id_str);
3577 free(ref_str);
3578 free(logmsg0);
3579 return err;
3582 static const struct got_error *
3583 print_diffstat(struct got_diffstat_cb_arg *dsa, const char *header)
3585 struct got_pathlist_entry *pe;
3587 if (header != NULL)
3588 printf("%s\n", header);
3590 TAILQ_FOREACH(pe, dsa->paths, entry) {
3591 struct got_diff_changed_path *cp = pe->data;
3592 int pad = dsa->max_path_len - pe->path_len + 1;
3594 printf(" %c %s%*c | %*d+ %*d-\n", cp->status, pe->path, pad,
3595 ' ', dsa->add_cols + 1, cp->add, dsa->rm_cols + 1, cp->rm);
3597 printf("\n%d file%s changed, %d insertion%s(+), %d deletion%s(-)\n\n",
3598 dsa->nfiles, dsa->nfiles > 1 ? "s" : "", dsa->ins,
3599 dsa->ins != 1 ? "s" : "", dsa->del, dsa->del != 1 ? "s" : "");
3601 if (fflush(stdout) != 0)
3602 return got_error_from_errno("fflush");
3604 return NULL;
3607 static const struct got_error *
3608 printfile(FILE *f)
3610 char buf[8192];
3611 size_t r;
3613 if (fseeko(f, 0L, SEEK_SET) == -1)
3614 return got_error_from_errno("fseek");
3616 for (;;) {
3617 r = fread(buf, 1, sizeof(buf), f);
3618 if (r == 0) {
3619 if (ferror(f))
3620 return got_error_from_errno("fread");
3621 if (feof(f))
3622 break;
3624 if (fwrite(buf, 1, r, stdout) != r)
3625 return got_ferror(stdout, GOT_ERR_IO);
3628 return NULL;
3631 static const struct got_error *
3632 print_commit(struct got_commit_object *commit, struct got_object_id *id,
3633 struct got_repository *repo, const char *path,
3634 struct got_pathlist_head *changed_paths,
3635 struct got_diffstat_cb_arg *diffstat, int show_patch, int diff_context,
3636 struct got_reflist_object_id_map *refs_idmap, const char *custom_refs_str,
3637 const char *prefix)
3639 const struct got_error *err = NULL;
3640 FILE *f = NULL;
3641 char *id_str, *datestr, *logmsg0, *logmsg, *line;
3642 char datebuf[26];
3643 time_t committer_time;
3644 const char *author, *committer;
3645 char *refs_str = NULL;
3647 err = got_object_id_str(&id_str, id);
3648 if (err)
3649 return err;
3651 if (custom_refs_str == NULL) {
3652 struct got_reflist_head *refs;
3653 refs = got_reflist_object_id_map_lookup(refs_idmap, id);
3654 if (refs) {
3655 err = build_refs_str(&refs_str, refs, id, repo, 0);
3656 if (err)
3657 goto done;
3661 printf(GOT_COMMIT_SEP_STR);
3662 if (custom_refs_str)
3663 printf("%s %s (%s)\n", prefix ? prefix : "commit", id_str,
3664 custom_refs_str);
3665 else
3666 printf("%s %s%s%s%s\n", prefix ? prefix : "commit", id_str,
3667 refs_str ? " (" : "", refs_str ? refs_str : "",
3668 refs_str ? ")" : "");
3669 free(id_str);
3670 id_str = NULL;
3671 free(refs_str);
3672 refs_str = NULL;
3673 printf("from: %s\n", got_object_commit_get_author(commit));
3674 author = got_object_commit_get_author(commit);
3675 committer = got_object_commit_get_committer(commit);
3676 if (strcmp(author, committer) != 0)
3677 printf("via: %s\n", committer);
3678 committer_time = got_object_commit_get_committer_time(commit);
3679 datestr = get_datestr(&committer_time, datebuf);
3680 if (datestr)
3681 printf("date: %s UTC\n", datestr);
3682 if (got_object_commit_get_nparents(commit) > 1) {
3683 const struct got_object_id_queue *parent_ids;
3684 struct got_object_qid *qid;
3685 int n = 1;
3686 parent_ids = got_object_commit_get_parent_ids(commit);
3687 STAILQ_FOREACH(qid, parent_ids, entry) {
3688 err = got_object_id_str(&id_str, &qid->id);
3689 if (err)
3690 goto done;
3691 printf("parent %d: %s\n", n++, id_str);
3692 free(id_str);
3693 id_str = NULL;
3697 err = got_object_commit_get_logmsg(&logmsg0, commit);
3698 if (err)
3699 goto done;
3701 logmsg = logmsg0;
3702 do {
3703 line = strsep(&logmsg, "\n");
3704 if (line)
3705 printf(" %s\n", line);
3706 } while (line);
3707 free(logmsg0);
3709 if (changed_paths && diffstat == NULL) {
3710 struct got_pathlist_entry *pe;
3712 TAILQ_FOREACH(pe, changed_paths, entry) {
3713 struct got_diff_changed_path *cp = pe->data;
3715 printf(" %c %s\n", cp->status, pe->path);
3717 printf("\n");
3719 if (show_patch) {
3720 if (diffstat) {
3721 f = got_opentemp();
3722 if (f == NULL) {
3723 err = got_error_from_errno("got_opentemp");
3724 goto done;
3728 err = print_patch(commit, id, path, diff_context, diffstat,
3729 repo, diffstat == NULL ? stdout : f);
3730 if (err)
3731 goto done;
3733 if (diffstat) {
3734 err = print_diffstat(diffstat, NULL);
3735 if (err)
3736 goto done;
3737 if (show_patch) {
3738 err = printfile(f);
3739 if (err)
3740 goto done;
3743 if (show_patch)
3744 printf("\n");
3746 if (fflush(stdout) != 0 && err == NULL)
3747 err = got_error_from_errno("fflush");
3748 done:
3749 if (f && fclose(f) == EOF && err == NULL)
3750 err = got_error_from_errno("fclose");
3751 free(id_str);
3752 free(refs_str);
3753 return err;
3756 static const struct got_error *
3757 print_commits(struct got_object_id *root_id, struct got_object_id *end_id,
3758 struct got_repository *repo, const char *path, int show_changed_paths,
3759 int show_diffstat, int show_patch, const char *search_pattern,
3760 int diff_context, int limit, int log_branches, int reverse_display_order,
3761 struct got_reflist_object_id_map *refs_idmap, int one_line,
3762 FILE *tmpfile)
3764 const struct got_error *err;
3765 struct got_commit_graph *graph;
3766 regex_t regex;
3767 int have_match;
3768 struct got_object_id_queue reversed_commits;
3769 struct got_object_qid *qid;
3770 struct got_commit_object *commit;
3771 struct got_pathlist_head changed_paths;
3773 STAILQ_INIT(&reversed_commits);
3774 TAILQ_INIT(&changed_paths);
3776 if (search_pattern && regcomp(&regex, search_pattern,
3777 REG_EXTENDED | REG_NOSUB | REG_NEWLINE))
3778 return got_error_msg(GOT_ERR_REGEX, search_pattern);
3780 err = got_commit_graph_open(&graph, path, !log_branches);
3781 if (err)
3782 return err;
3783 err = got_commit_graph_iter_start(graph, root_id, repo,
3784 check_cancelled, NULL);
3785 if (err)
3786 goto done;
3787 for (;;) {
3788 struct got_object_id id;
3789 struct got_diffstat_cb_arg dsa = { 0, 0, 0, 0, 0, 0,
3790 &changed_paths, 0, 0, GOT_DIFF_ALGORITHM_PATIENCE };
3792 if (sigint_received || sigpipe_received)
3793 break;
3795 err = got_commit_graph_iter_next(&id, graph, repo,
3796 check_cancelled, NULL);
3797 if (err) {
3798 if (err->code == GOT_ERR_ITER_COMPLETED)
3799 err = NULL;
3800 break;
3803 err = got_object_open_as_commit(&commit, repo, &id);
3804 if (err)
3805 break;
3807 if ((show_changed_paths || (show_diffstat && !show_patch))
3808 && !reverse_display_order) {
3809 err = get_changed_paths(&changed_paths, commit, repo,
3810 show_diffstat ? &dsa : NULL);
3811 if (err)
3812 break;
3815 if (search_pattern) {
3816 err = match_commit(&have_match, &id, commit, &regex);
3817 if (err) {
3818 got_object_commit_close(commit);
3819 break;
3821 if (have_match == 0 && show_changed_paths)
3822 match_changed_paths(&have_match,
3823 &changed_paths, &regex);
3824 if (have_match == 0 && show_patch) {
3825 err = match_patch(&have_match, commit, &id,
3826 path, diff_context, repo, &regex, tmpfile);
3827 if (err)
3828 break;
3830 if (have_match == 0) {
3831 got_object_commit_close(commit);
3832 got_pathlist_free(&changed_paths,
3833 GOT_PATHLIST_FREE_ALL);
3834 continue;
3838 if (reverse_display_order) {
3839 err = got_object_qid_alloc(&qid, &id);
3840 if (err)
3841 break;
3842 STAILQ_INSERT_HEAD(&reversed_commits, qid, entry);
3843 got_object_commit_close(commit);
3844 } else {
3845 if (one_line)
3846 err = print_commit_oneline(commit, &id,
3847 repo, refs_idmap);
3848 else
3849 err = print_commit(commit, &id, repo, path,
3850 (show_changed_paths || show_diffstat) ?
3851 &changed_paths : NULL,
3852 show_diffstat ? &dsa : NULL, show_patch,
3853 diff_context, refs_idmap, NULL, NULL);
3854 got_object_commit_close(commit);
3855 if (err)
3856 break;
3858 if ((limit && --limit == 0) ||
3859 (end_id && got_object_id_cmp(&id, end_id) == 0))
3860 break;
3862 got_pathlist_free(&changed_paths, GOT_PATHLIST_FREE_ALL);
3864 if (reverse_display_order) {
3865 STAILQ_FOREACH(qid, &reversed_commits, entry) {
3866 struct got_diffstat_cb_arg dsa = { 0, 0, 0, 0, 0, 0,
3867 &changed_paths, 0, 0, GOT_DIFF_ALGORITHM_PATIENCE };
3869 err = got_object_open_as_commit(&commit, repo,
3870 &qid->id);
3871 if (err)
3872 break;
3873 if (show_changed_paths ||
3874 (show_diffstat && !show_patch)) {
3875 err = get_changed_paths(&changed_paths, commit,
3876 repo, show_diffstat ? &dsa : NULL);
3877 if (err)
3878 break;
3880 if (one_line)
3881 err = print_commit_oneline(commit, &qid->id,
3882 repo, refs_idmap);
3883 else
3884 err = print_commit(commit, &qid->id, repo, path,
3885 (show_changed_paths || show_diffstat) ?
3886 &changed_paths : NULL,
3887 show_diffstat ? &dsa : NULL, show_patch,
3888 diff_context, refs_idmap, NULL, NULL);
3889 got_object_commit_close(commit);
3890 if (err)
3891 break;
3892 got_pathlist_free(&changed_paths, GOT_PATHLIST_FREE_ALL);
3895 done:
3896 while (!STAILQ_EMPTY(&reversed_commits)) {
3897 qid = STAILQ_FIRST(&reversed_commits);
3898 STAILQ_REMOVE_HEAD(&reversed_commits, entry);
3899 got_object_qid_free(qid);
3901 got_pathlist_free(&changed_paths, GOT_PATHLIST_FREE_ALL);
3902 if (search_pattern)
3903 regfree(&regex);
3904 got_commit_graph_close(graph);
3905 return err;
3908 __dead static void
3909 usage_log(void)
3911 fprintf(stderr, "usage: %s log [-bdPpRs] [-C number] [-c commit] "
3912 "[-l N] [-r repository-path] [-S search-pattern] [-x commit] "
3913 "[path]\n", getprogname());
3914 exit(1);
3917 static int
3918 get_default_log_limit(void)
3920 const char *got_default_log_limit;
3921 long long n;
3922 const char *errstr;
3924 got_default_log_limit = getenv("GOT_LOG_DEFAULT_LIMIT");
3925 if (got_default_log_limit == NULL)
3926 return 0;
3927 n = strtonum(got_default_log_limit, 0, INT_MAX, &errstr);
3928 if (errstr != NULL)
3929 return 0;
3930 return n;
3933 static const struct got_error *
3934 cmd_log(int argc, char *argv[])
3936 const struct got_error *error;
3937 struct got_repository *repo = NULL;
3938 struct got_worktree *worktree = NULL;
3939 struct got_object_id *start_id = NULL, *end_id = NULL;
3940 char *repo_path = NULL, *path = NULL, *cwd = NULL, *in_repo_path = NULL;
3941 const char *start_commit = NULL, *end_commit = NULL;
3942 const char *search_pattern = NULL;
3943 int diff_context = -1, ch;
3944 int show_changed_paths = 0, show_patch = 0, limit = 0, log_branches = 0;
3945 int show_diffstat = 0, reverse_display_order = 0, one_line = 0;
3946 const char *errstr;
3947 struct got_reflist_head refs;
3948 struct got_reflist_object_id_map *refs_idmap = NULL;
3949 FILE *tmpfile = NULL;
3950 int *pack_fds = NULL;
3952 TAILQ_INIT(&refs);
3954 #ifndef PROFILE
3955 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
3956 NULL)
3957 == -1)
3958 err(1, "pledge");
3959 #endif
3961 limit = get_default_log_limit();
3963 while ((ch = getopt(argc, argv, "bC:c:dl:PpRr:S:sx:")) != -1) {
3964 switch (ch) {
3965 case 'b':
3966 log_branches = 1;
3967 break;
3968 case 'C':
3969 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
3970 &errstr);
3971 if (errstr != NULL)
3972 errx(1, "number of context lines is %s: %s",
3973 errstr, optarg);
3974 break;
3975 case 'c':
3976 start_commit = optarg;
3977 break;
3978 case 'd':
3979 show_diffstat = 1;
3980 break;
3981 case 'l':
3982 limit = strtonum(optarg, 0, INT_MAX, &errstr);
3983 if (errstr != NULL)
3984 errx(1, "number of commits is %s: %s",
3985 errstr, optarg);
3986 break;
3987 case 'P':
3988 show_changed_paths = 1;
3989 break;
3990 case 'p':
3991 show_patch = 1;
3992 break;
3993 case 'R':
3994 reverse_display_order = 1;
3995 break;
3996 case 'r':
3997 repo_path = realpath(optarg, NULL);
3998 if (repo_path == NULL)
3999 return got_error_from_errno2("realpath",
4000 optarg);
4001 got_path_strip_trailing_slashes(repo_path);
4002 break;
4003 case 'S':
4004 search_pattern = optarg;
4005 break;
4006 case 's':
4007 one_line = 1;
4008 break;
4009 case 'x':
4010 end_commit = optarg;
4011 break;
4012 default:
4013 usage_log();
4014 /* NOTREACHED */
4018 argc -= optind;
4019 argv += optind;
4021 if (diff_context == -1)
4022 diff_context = 3;
4023 else if (!show_patch)
4024 errx(1, "-C requires -p");
4026 if (one_line && (show_patch || show_changed_paths || show_diffstat))
4027 errx(1, "cannot use -s with -d, -p or -P");
4029 cwd = getcwd(NULL, 0);
4030 if (cwd == NULL) {
4031 error = got_error_from_errno("getcwd");
4032 goto done;
4035 error = got_repo_pack_fds_open(&pack_fds);
4036 if (error != NULL)
4037 goto done;
4039 if (repo_path == NULL) {
4040 error = got_worktree_open(&worktree, cwd);
4041 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4042 goto done;
4043 error = NULL;
4046 if (argc == 1) {
4047 if (worktree) {
4048 error = got_worktree_resolve_path(&path, worktree,
4049 argv[0]);
4050 if (error)
4051 goto done;
4052 } else {
4053 path = strdup(argv[0]);
4054 if (path == NULL) {
4055 error = got_error_from_errno("strdup");
4056 goto done;
4059 } else if (argc != 0)
4060 usage_log();
4062 if (repo_path == NULL) {
4063 repo_path = worktree ?
4064 strdup(got_worktree_get_repo_path(worktree)) : strdup(cwd);
4066 if (repo_path == NULL) {
4067 error = got_error_from_errno("strdup");
4068 goto done;
4071 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
4072 if (error != NULL)
4073 goto done;
4075 error = apply_unveil(got_repo_get_path(repo), 1,
4076 worktree ? got_worktree_get_root_path(worktree) : NULL);
4077 if (error)
4078 goto done;
4080 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
4081 if (error)
4082 goto done;
4084 error = got_reflist_object_id_map_create(&refs_idmap, &refs, repo);
4085 if (error)
4086 goto done;
4088 if (start_commit == NULL) {
4089 struct got_reference *head_ref;
4090 struct got_commit_object *commit = NULL;
4091 error = got_ref_open(&head_ref, repo,
4092 worktree ? got_worktree_get_head_ref_name(worktree)
4093 : GOT_REF_HEAD, 0);
4094 if (error != NULL)
4095 goto done;
4096 error = got_ref_resolve(&start_id, repo, head_ref);
4097 got_ref_close(head_ref);
4098 if (error != NULL)
4099 goto done;
4100 error = got_object_open_as_commit(&commit, repo,
4101 start_id);
4102 if (error != NULL)
4103 goto done;
4104 got_object_commit_close(commit);
4105 } else {
4106 error = got_repo_match_object_id(&start_id, NULL,
4107 start_commit, GOT_OBJ_TYPE_COMMIT, &refs, repo);
4108 if (error != NULL)
4109 goto done;
4111 if (end_commit != NULL) {
4112 error = got_repo_match_object_id(&end_id, NULL,
4113 end_commit, GOT_OBJ_TYPE_COMMIT, &refs, repo);
4114 if (error != NULL)
4115 goto done;
4118 if (worktree) {
4120 * If a path was specified on the command line it was resolved
4121 * to a path in the work tree above. Prepend the work tree's
4122 * path prefix to obtain the corresponding in-repository path.
4124 if (path) {
4125 const char *prefix;
4126 prefix = got_worktree_get_path_prefix(worktree);
4127 if (asprintf(&in_repo_path, "%s%s%s", prefix,
4128 (path[0] != '\0') ? "/" : "", path) == -1) {
4129 error = got_error_from_errno("asprintf");
4130 goto done;
4133 } else
4134 error = got_repo_map_path(&in_repo_path, repo,
4135 path ? path : "");
4136 if (error != NULL)
4137 goto done;
4138 if (in_repo_path) {
4139 free(path);
4140 path = in_repo_path;
4143 if (worktree) {
4144 /* Release work tree lock. */
4145 got_worktree_close(worktree);
4146 worktree = NULL;
4149 if (search_pattern && show_patch) {
4150 tmpfile = got_opentemp();
4151 if (tmpfile == NULL) {
4152 error = got_error_from_errno("got_opentemp");
4153 goto done;
4157 error = print_commits(start_id, end_id, repo, path ? path : "",
4158 show_changed_paths, show_diffstat, show_patch, search_pattern,
4159 diff_context, limit, log_branches, reverse_display_order,
4160 refs_idmap, one_line, tmpfile);
4161 done:
4162 free(path);
4163 free(repo_path);
4164 free(cwd);
4165 free(start_id);
4166 free(end_id);
4167 if (worktree)
4168 got_worktree_close(worktree);
4169 if (repo) {
4170 const struct got_error *close_err = got_repo_close(repo);
4171 if (error == NULL)
4172 error = close_err;
4174 if (pack_fds) {
4175 const struct got_error *pack_err =
4176 got_repo_pack_fds_close(pack_fds);
4177 if (error == NULL)
4178 error = pack_err;
4180 if (refs_idmap)
4181 got_reflist_object_id_map_free(refs_idmap);
4182 if (tmpfile && fclose(tmpfile) == EOF && error == NULL)
4183 error = got_error_from_errno("fclose");
4184 got_ref_list_free(&refs);
4185 return error;
4188 __dead static void
4189 usage_diff(void)
4191 fprintf(stderr, "usage: %s diff [-adPsw] [-C number] [-c commit] "
4192 "[-r repository-path] [object1 object2 | path ...]\n",
4193 getprogname());
4194 exit(1);
4197 struct print_diff_arg {
4198 struct got_repository *repo;
4199 struct got_worktree *worktree;
4200 struct got_diffstat_cb_arg *diffstat;
4201 int diff_context;
4202 const char *id_str;
4203 int header_shown;
4204 int diff_staged;
4205 enum got_diff_algorithm diff_algo;
4206 int ignore_whitespace;
4207 int force_text_diff;
4208 FILE *f1;
4209 FILE *f2;
4210 FILE *outfile;
4214 * Create a file which contains the target path of a symlink so we can feed
4215 * it as content to the diff engine.
4217 static const struct got_error *
4218 get_symlink_target_file(int *fd, int dirfd, const char *de_name,
4219 const char *abspath)
4221 const struct got_error *err = NULL;
4222 char target_path[PATH_MAX];
4223 ssize_t target_len, outlen;
4225 *fd = -1;
4227 if (dirfd != -1) {
4228 target_len = readlinkat(dirfd, de_name, target_path, PATH_MAX);
4229 if (target_len == -1)
4230 return got_error_from_errno2("readlinkat", abspath);
4231 } else {
4232 target_len = readlink(abspath, target_path, PATH_MAX);
4233 if (target_len == -1)
4234 return got_error_from_errno2("readlink", abspath);
4237 *fd = got_opentempfd();
4238 if (*fd == -1)
4239 return got_error_from_errno("got_opentempfd");
4241 outlen = write(*fd, target_path, target_len);
4242 if (outlen == -1) {
4243 err = got_error_from_errno("got_opentempfd");
4244 goto done;
4247 if (lseek(*fd, 0, SEEK_SET) == -1) {
4248 err = got_error_from_errno2("lseek", abspath);
4249 goto done;
4251 done:
4252 if (err) {
4253 close(*fd);
4254 *fd = -1;
4256 return err;
4259 static const struct got_error *
4260 print_diff(void *arg, unsigned char status, unsigned char staged_status,
4261 const char *path, struct got_object_id *blob_id,
4262 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
4263 int dirfd, const char *de_name)
4265 struct print_diff_arg *a = arg;
4266 const struct got_error *err = NULL;
4267 struct got_blob_object *blob1 = NULL;
4268 int fd = -1, fd1 = -1, fd2 = -1;
4269 FILE *f2 = NULL;
4270 char *abspath = NULL, *label1 = NULL;
4271 struct stat sb;
4272 off_t size1 = 0;
4273 int f2_exists = 0;
4275 memset(&sb, 0, sizeof(sb));
4277 if (a->diff_staged) {
4278 if (staged_status != GOT_STATUS_MODIFY &&
4279 staged_status != GOT_STATUS_ADD &&
4280 staged_status != GOT_STATUS_DELETE)
4281 return NULL;
4282 } else {
4283 if (staged_status == GOT_STATUS_DELETE)
4284 return NULL;
4285 if (status == GOT_STATUS_NONEXISTENT)
4286 return got_error_set_errno(ENOENT, path);
4287 if (status != GOT_STATUS_MODIFY &&
4288 status != GOT_STATUS_ADD &&
4289 status != GOT_STATUS_DELETE &&
4290 status != GOT_STATUS_CONFLICT)
4291 return NULL;
4294 err = got_opentemp_truncate(a->f1);
4295 if (err)
4296 return got_error_from_errno("got_opentemp_truncate");
4297 err = got_opentemp_truncate(a->f2);
4298 if (err)
4299 return got_error_from_errno("got_opentemp_truncate");
4301 if (!a->header_shown) {
4302 if (fprintf(a->outfile, "diff %s%s\n",
4303 a->diff_staged ? "-s " : "",
4304 got_worktree_get_root_path(a->worktree)) < 0) {
4305 err = got_error_from_errno("fprintf");
4306 goto done;
4308 if (fprintf(a->outfile, "commit - %s\n", a->id_str) < 0) {
4309 err = got_error_from_errno("fprintf");
4310 goto done;
4312 if (fprintf(a->outfile, "path + %s%s\n",
4313 got_worktree_get_root_path(a->worktree),
4314 a->diff_staged ? " (staged changes)" : "") < 0) {
4315 err = got_error_from_errno("fprintf");
4316 goto done;
4318 a->header_shown = 1;
4321 if (a->diff_staged) {
4322 const char *label1 = NULL, *label2 = NULL;
4323 switch (staged_status) {
4324 case GOT_STATUS_MODIFY:
4325 label1 = path;
4326 label2 = path;
4327 break;
4328 case GOT_STATUS_ADD:
4329 label2 = path;
4330 break;
4331 case GOT_STATUS_DELETE:
4332 label1 = path;
4333 break;
4334 default:
4335 return got_error(GOT_ERR_FILE_STATUS);
4337 fd1 = got_opentempfd();
4338 if (fd1 == -1) {
4339 err = got_error_from_errno("got_opentempfd");
4340 goto done;
4342 fd2 = got_opentempfd();
4343 if (fd2 == -1) {
4344 err = got_error_from_errno("got_opentempfd");
4345 goto done;
4347 err = got_diff_objects_as_blobs(NULL, NULL, a->f1, a->f2,
4348 fd1, fd2, blob_id, staged_blob_id, label1, label2,
4349 a->diff_algo, a->diff_context, a->ignore_whitespace,
4350 a->force_text_diff, a->diffstat, a->repo, a->outfile);
4351 goto done;
4354 fd1 = got_opentempfd();
4355 if (fd1 == -1) {
4356 err = got_error_from_errno("got_opentempfd");
4357 goto done;
4360 if (staged_status == GOT_STATUS_ADD ||
4361 staged_status == GOT_STATUS_MODIFY) {
4362 char *id_str;
4363 err = got_object_open_as_blob(&blob1, a->repo, staged_blob_id,
4364 8192, fd1);
4365 if (err)
4366 goto done;
4367 err = got_object_id_str(&id_str, staged_blob_id);
4368 if (err)
4369 goto done;
4370 if (asprintf(&label1, "%s (staged)", id_str) == -1) {
4371 err = got_error_from_errno("asprintf");
4372 free(id_str);
4373 goto done;
4375 free(id_str);
4376 } else if (status != GOT_STATUS_ADD) {
4377 err = got_object_open_as_blob(&blob1, a->repo, blob_id, 8192,
4378 fd1);
4379 if (err)
4380 goto done;
4383 if (status != GOT_STATUS_DELETE) {
4384 if (asprintf(&abspath, "%s/%s",
4385 got_worktree_get_root_path(a->worktree), path) == -1) {
4386 err = got_error_from_errno("asprintf");
4387 goto done;
4390 if (dirfd != -1) {
4391 fd = openat(dirfd, de_name,
4392 O_RDONLY | O_NOFOLLOW | O_CLOEXEC);
4393 if (fd == -1) {
4394 if (!got_err_open_nofollow_on_symlink()) {
4395 err = got_error_from_errno2("openat",
4396 abspath);
4397 goto done;
4399 err = get_symlink_target_file(&fd, dirfd,
4400 de_name, abspath);
4401 if (err)
4402 goto done;
4404 } else {
4405 fd = open(abspath, O_RDONLY | O_NOFOLLOW | O_CLOEXEC);
4406 if (fd == -1) {
4407 if (!got_err_open_nofollow_on_symlink()) {
4408 err = got_error_from_errno2("open",
4409 abspath);
4410 goto done;
4412 err = get_symlink_target_file(&fd, dirfd,
4413 de_name, abspath);
4414 if (err)
4415 goto done;
4418 if (fstatat(fd, abspath, &sb, AT_SYMLINK_NOFOLLOW) == -1) {
4419 err = got_error_from_errno2("fstatat", abspath);
4420 goto done;
4422 f2 = fdopen(fd, "r");
4423 if (f2 == NULL) {
4424 err = got_error_from_errno2("fdopen", abspath);
4425 goto done;
4427 fd = -1;
4428 f2_exists = 1;
4431 if (blob1) {
4432 err = got_object_blob_dump_to_file(&size1, NULL, NULL,
4433 a->f1, blob1);
4434 if (err)
4435 goto done;
4438 err = got_diff_blob_file(blob1, a->f1, size1, label1, f2 ? f2 : a->f2,
4439 f2_exists, &sb, path, GOT_DIFF_ALGORITHM_PATIENCE, a->diff_context,
4440 a->ignore_whitespace, a->force_text_diff, a->diffstat, a->outfile);
4441 done:
4442 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
4443 err = got_error_from_errno("close");
4444 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
4445 err = got_error_from_errno("close");
4446 if (blob1)
4447 got_object_blob_close(blob1);
4448 if (fd != -1 && close(fd) == -1 && err == NULL)
4449 err = got_error_from_errno("close");
4450 if (f2 && fclose(f2) == EOF && err == NULL)
4451 err = got_error_from_errno("fclose");
4452 free(abspath);
4453 return err;
4456 static const struct got_error *
4457 cmd_diff(int argc, char *argv[])
4459 const struct got_error *error;
4460 struct got_repository *repo = NULL;
4461 struct got_worktree *worktree = NULL;
4462 char *cwd = NULL, *repo_path = NULL;
4463 const char *commit_args[2] = { NULL, NULL };
4464 int ncommit_args = 0;
4465 struct got_object_id *ids[2] = { NULL, NULL };
4466 char *labels[2] = { NULL, NULL };
4467 int type1 = GOT_OBJ_TYPE_ANY, type2 = GOT_OBJ_TYPE_ANY;
4468 int diff_context = 3, diff_staged = 0, ignore_whitespace = 0, ch, i;
4469 int force_text_diff = 0, force_path = 0, rflag = 0, show_diffstat = 0;
4470 const char *errstr;
4471 struct got_reflist_head refs;
4472 struct got_pathlist_head diffstat_paths, paths;
4473 FILE *f1 = NULL, *f2 = NULL, *outfile = NULL;
4474 int fd1 = -1, fd2 = -1;
4475 int *pack_fds = NULL;
4476 struct got_diffstat_cb_arg dsa;
4478 memset(&dsa, 0, sizeof(dsa));
4480 TAILQ_INIT(&refs);
4481 TAILQ_INIT(&paths);
4482 TAILQ_INIT(&diffstat_paths);
4484 #ifndef PROFILE
4485 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
4486 NULL) == -1)
4487 err(1, "pledge");
4488 #endif
4490 while ((ch = getopt(argc, argv, "aC:c:dPr:sw")) != -1) {
4491 switch (ch) {
4492 case 'a':
4493 force_text_diff = 1;
4494 break;
4495 case 'C':
4496 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
4497 &errstr);
4498 if (errstr != NULL)
4499 errx(1, "number of context lines is %s: %s",
4500 errstr, optarg);
4501 break;
4502 case 'c':
4503 if (ncommit_args >= 2)
4504 errx(1, "too many -c options used");
4505 commit_args[ncommit_args++] = optarg;
4506 break;
4507 case 'd':
4508 show_diffstat = 1;
4509 break;
4510 case 'P':
4511 force_path = 1;
4512 break;
4513 case 'r':
4514 repo_path = realpath(optarg, NULL);
4515 if (repo_path == NULL)
4516 return got_error_from_errno2("realpath",
4517 optarg);
4518 got_path_strip_trailing_slashes(repo_path);
4519 rflag = 1;
4520 break;
4521 case 's':
4522 diff_staged = 1;
4523 break;
4524 case 'w':
4525 ignore_whitespace = 1;
4526 break;
4527 default:
4528 usage_diff();
4529 /* NOTREACHED */
4533 argc -= optind;
4534 argv += optind;
4536 cwd = getcwd(NULL, 0);
4537 if (cwd == NULL) {
4538 error = got_error_from_errno("getcwd");
4539 goto done;
4542 error = got_repo_pack_fds_open(&pack_fds);
4543 if (error != NULL)
4544 goto done;
4546 if (repo_path == NULL) {
4547 error = got_worktree_open(&worktree, cwd);
4548 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4549 goto done;
4550 else
4551 error = NULL;
4552 if (worktree) {
4553 repo_path =
4554 strdup(got_worktree_get_repo_path(worktree));
4555 if (repo_path == NULL) {
4556 error = got_error_from_errno("strdup");
4557 goto done;
4559 } else {
4560 repo_path = strdup(cwd);
4561 if (repo_path == NULL) {
4562 error = got_error_from_errno("strdup");
4563 goto done;
4568 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
4569 free(repo_path);
4570 if (error != NULL)
4571 goto done;
4573 if (show_diffstat) {
4574 dsa.paths = &diffstat_paths;
4575 dsa.force_text = force_text_diff;
4576 dsa.ignore_ws = ignore_whitespace;
4577 dsa.diff_algo = GOT_DIFF_ALGORITHM_PATIENCE;
4580 if (rflag || worktree == NULL || ncommit_args > 0) {
4581 if (force_path) {
4582 error = got_error_msg(GOT_ERR_NOT_IMPL,
4583 "-P option can only be used when diffing "
4584 "a work tree");
4585 goto done;
4587 if (diff_staged) {
4588 error = got_error_msg(GOT_ERR_NOT_IMPL,
4589 "-s option can only be used when diffing "
4590 "a work tree");
4591 goto done;
4595 error = apply_unveil(got_repo_get_path(repo), 1,
4596 worktree ? got_worktree_get_root_path(worktree) : NULL);
4597 if (error)
4598 goto done;
4600 if ((!force_path && argc == 2) || ncommit_args > 0) {
4601 int obj_type = (ncommit_args > 0 ?
4602 GOT_OBJ_TYPE_COMMIT : GOT_OBJ_TYPE_ANY);
4603 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
4604 NULL);
4605 if (error)
4606 goto done;
4607 for (i = 0; i < (ncommit_args > 0 ? ncommit_args : argc); i++) {
4608 const char *arg;
4609 if (ncommit_args > 0)
4610 arg = commit_args[i];
4611 else
4612 arg = argv[i];
4613 error = got_repo_match_object_id(&ids[i], &labels[i],
4614 arg, obj_type, &refs, repo);
4615 if (error) {
4616 if (error->code != GOT_ERR_NOT_REF &&
4617 error->code != GOT_ERR_NO_OBJ)
4618 goto done;
4619 if (ncommit_args > 0)
4620 goto done;
4621 error = NULL;
4622 break;
4627 f1 = got_opentemp();
4628 if (f1 == NULL) {
4629 error = got_error_from_errno("got_opentemp");
4630 goto done;
4633 f2 = got_opentemp();
4634 if (f2 == NULL) {
4635 error = got_error_from_errno("got_opentemp");
4636 goto done;
4639 outfile = got_opentemp();
4640 if (outfile == NULL) {
4641 error = got_error_from_errno("got_opentemp");
4642 goto done;
4645 if (ncommit_args == 0 && (ids[0] == NULL || ids[1] == NULL)) {
4646 struct print_diff_arg arg;
4647 char *id_str;
4649 if (worktree == NULL) {
4650 if (argc == 2 && ids[0] == NULL) {
4651 error = got_error_path(argv[0], GOT_ERR_NO_OBJ);
4652 goto done;
4653 } else if (argc == 2 && ids[1] == NULL) {
4654 error = got_error_path(argv[1], GOT_ERR_NO_OBJ);
4655 goto done;
4656 } else if (argc > 0) {
4657 error = got_error_fmt(GOT_ERR_NOT_WORKTREE,
4658 "%s", "specified paths cannot be resolved");
4659 goto done;
4660 } else {
4661 error = got_error(GOT_ERR_NOT_WORKTREE);
4662 goto done;
4666 error = get_worktree_paths_from_argv(&paths, argc, argv,
4667 worktree);
4668 if (error)
4669 goto done;
4671 error = got_object_id_str(&id_str,
4672 got_worktree_get_base_commit_id(worktree));
4673 if (error)
4674 goto done;
4675 arg.repo = repo;
4676 arg.worktree = worktree;
4677 arg.diff_algo = GOT_DIFF_ALGORITHM_PATIENCE;
4678 arg.diff_context = diff_context;
4679 arg.id_str = id_str;
4680 arg.header_shown = 0;
4681 arg.diff_staged = diff_staged;
4682 arg.ignore_whitespace = ignore_whitespace;
4683 arg.force_text_diff = force_text_diff;
4684 arg.diffstat = show_diffstat ? &dsa : NULL;
4685 arg.f1 = f1;
4686 arg.f2 = f2;
4687 arg.outfile = outfile;
4689 error = got_worktree_status(worktree, &paths, repo, 0,
4690 print_diff, &arg, check_cancelled, NULL);
4691 free(id_str);
4692 if (error)
4693 goto done;
4695 if (show_diffstat && dsa.nfiles > 0) {
4696 char *header;
4698 if (asprintf(&header, "diffstat %s%s",
4699 diff_staged ? "-s " : "",
4700 got_worktree_get_root_path(worktree)) == -1) {
4701 error = got_error_from_errno("asprintf");
4702 goto done;
4705 error = print_diffstat(&dsa, header);
4706 free(header);
4707 if (error)
4708 goto done;
4711 error = printfile(outfile);
4712 goto done;
4715 if (ncommit_args == 1) {
4716 struct got_commit_object *commit;
4717 error = got_object_open_as_commit(&commit, repo, ids[0]);
4718 if (error)
4719 goto done;
4721 labels[1] = labels[0];
4722 ids[1] = ids[0];
4723 if (got_object_commit_get_nparents(commit) > 0) {
4724 const struct got_object_id_queue *pids;
4725 struct got_object_qid *pid;
4726 pids = got_object_commit_get_parent_ids(commit);
4727 pid = STAILQ_FIRST(pids);
4728 ids[0] = got_object_id_dup(&pid->id);
4729 if (ids[0] == NULL) {
4730 error = got_error_from_errno(
4731 "got_object_id_dup");
4732 got_object_commit_close(commit);
4733 goto done;
4735 error = got_object_id_str(&labels[0], ids[0]);
4736 if (error) {
4737 got_object_commit_close(commit);
4738 goto done;
4740 } else {
4741 ids[0] = NULL;
4742 labels[0] = strdup("/dev/null");
4743 if (labels[0] == NULL) {
4744 error = got_error_from_errno("strdup");
4745 got_object_commit_close(commit);
4746 goto done;
4750 got_object_commit_close(commit);
4753 if (ncommit_args == 0 && argc > 2) {
4754 error = got_error_msg(GOT_ERR_BAD_PATH,
4755 "path arguments cannot be used when diffing two objects");
4756 goto done;
4759 if (ids[0]) {
4760 error = got_object_get_type(&type1, repo, ids[0]);
4761 if (error)
4762 goto done;
4765 error = got_object_get_type(&type2, repo, ids[1]);
4766 if (error)
4767 goto done;
4768 if (type1 != GOT_OBJ_TYPE_ANY && type1 != type2) {
4769 error = got_error(GOT_ERR_OBJ_TYPE);
4770 goto done;
4772 if (type1 == GOT_OBJ_TYPE_BLOB && argc > 2) {
4773 error = got_error_msg(GOT_ERR_OBJ_TYPE,
4774 "path arguments cannot be used when diffing blobs");
4775 goto done;
4778 for (i = 0; ncommit_args > 0 && i < argc; i++) {
4779 char *in_repo_path;
4780 struct got_pathlist_entry *new;
4781 if (worktree) {
4782 const char *prefix;
4783 char *p;
4784 error = got_worktree_resolve_path(&p, worktree,
4785 argv[i]);
4786 if (error)
4787 goto done;
4788 prefix = got_worktree_get_path_prefix(worktree);
4789 while (prefix[0] == '/')
4790 prefix++;
4791 if (asprintf(&in_repo_path, "%s%s%s", prefix,
4792 (p[0] != '\0' && prefix[0] != '\0') ? "/" : "",
4793 p) == -1) {
4794 error = got_error_from_errno("asprintf");
4795 free(p);
4796 goto done;
4798 free(p);
4799 } else {
4800 char *mapped_path, *s;
4801 error = got_repo_map_path(&mapped_path, repo, argv[i]);
4802 if (error)
4803 goto done;
4804 s = mapped_path;
4805 while (s[0] == '/')
4806 s++;
4807 in_repo_path = strdup(s);
4808 if (in_repo_path == NULL) {
4809 error = got_error_from_errno("asprintf");
4810 free(mapped_path);
4811 goto done;
4813 free(mapped_path);
4816 error = got_pathlist_insert(&new, &paths, in_repo_path, NULL);
4817 if (error || new == NULL /* duplicate */)
4818 free(in_repo_path);
4819 if (error)
4820 goto done;
4823 if (worktree) {
4824 /* Release work tree lock. */
4825 got_worktree_close(worktree);
4826 worktree = NULL;
4829 fd1 = got_opentempfd();
4830 if (fd1 == -1) {
4831 error = got_error_from_errno("got_opentempfd");
4832 goto done;
4835 fd2 = got_opentempfd();
4836 if (fd2 == -1) {
4837 error = got_error_from_errno("got_opentempfd");
4838 goto done;
4841 switch (type1 == GOT_OBJ_TYPE_ANY ? type2 : type1) {
4842 case GOT_OBJ_TYPE_BLOB:
4843 error = got_diff_objects_as_blobs(NULL, NULL, f1, f2,
4844 fd1, fd2, ids[0], ids[1], NULL, NULL,
4845 GOT_DIFF_ALGORITHM_PATIENCE, diff_context,
4846 ignore_whitespace, force_text_diff,
4847 show_diffstat ? &dsa : NULL, repo, outfile);
4848 break;
4849 case GOT_OBJ_TYPE_TREE:
4850 error = got_diff_objects_as_trees(NULL, NULL, f1, f2, fd1, fd2,
4851 ids[0], ids[1], &paths, "", "",
4852 GOT_DIFF_ALGORITHM_PATIENCE, diff_context,
4853 ignore_whitespace, force_text_diff,
4854 show_diffstat ? &dsa : NULL, repo, outfile);
4855 break;
4856 case GOT_OBJ_TYPE_COMMIT:
4857 fprintf(outfile, "diff %s %s\n", labels[0], labels[1]);
4858 error = got_diff_objects_as_commits(NULL, NULL, f1, f2,
4859 fd1, fd2, ids[0], ids[1], &paths,
4860 GOT_DIFF_ALGORITHM_PATIENCE, diff_context,
4861 ignore_whitespace, force_text_diff,
4862 show_diffstat ? &dsa : NULL, repo, outfile);
4863 break;
4864 default:
4865 error = got_error(GOT_ERR_OBJ_TYPE);
4867 if (error)
4868 goto done;
4870 if (show_diffstat && dsa.nfiles > 0) {
4871 char *header = NULL;
4873 if (asprintf(&header, "diffstat %s %s",
4874 labels[0], labels[1]) == -1) {
4875 error = got_error_from_errno("asprintf");
4876 goto done;
4879 error = print_diffstat(&dsa, header);
4880 free(header);
4881 if (error)
4882 goto done;
4885 error = printfile(outfile);
4887 done:
4888 free(labels[0]);
4889 free(labels[1]);
4890 free(ids[0]);
4891 free(ids[1]);
4892 if (worktree)
4893 got_worktree_close(worktree);
4894 if (repo) {
4895 const struct got_error *close_err = got_repo_close(repo);
4896 if (error == NULL)
4897 error = close_err;
4899 if (pack_fds) {
4900 const struct got_error *pack_err =
4901 got_repo_pack_fds_close(pack_fds);
4902 if (error == NULL)
4903 error = pack_err;
4905 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
4906 got_pathlist_free(&diffstat_paths, GOT_PATHLIST_FREE_ALL);
4907 got_ref_list_free(&refs);
4908 if (outfile && fclose(outfile) == EOF && error == NULL)
4909 error = got_error_from_errno("fclose");
4910 if (f1 && fclose(f1) == EOF && error == NULL)
4911 error = got_error_from_errno("fclose");
4912 if (f2 && fclose(f2) == EOF && error == NULL)
4913 error = got_error_from_errno("fclose");
4914 if (fd1 != -1 && close(fd1) == -1 && error == NULL)
4915 error = got_error_from_errno("close");
4916 if (fd2 != -1 && close(fd2) == -1 && error == NULL)
4917 error = got_error_from_errno("close");
4918 return error;
4921 __dead static void
4922 usage_blame(void)
4924 fprintf(stderr,
4925 "usage: %s blame [-c commit] [-r repository-path] path\n",
4926 getprogname());
4927 exit(1);
4930 struct blame_line {
4931 int annotated;
4932 char *id_str;
4933 char *committer;
4934 char datebuf[11]; /* YYYY-MM-DD + NUL */
4937 struct blame_cb_args {
4938 struct blame_line *lines;
4939 int nlines;
4940 int nlines_prec;
4941 int lineno_cur;
4942 off_t *line_offsets;
4943 FILE *f;
4944 struct got_repository *repo;
4947 static const struct got_error *
4948 blame_cb(void *arg, int nlines, int lineno,
4949 struct got_commit_object *commit, struct got_object_id *id)
4951 const struct got_error *err = NULL;
4952 struct blame_cb_args *a = arg;
4953 struct blame_line *bline;
4954 char *line = NULL;
4955 size_t linesize = 0;
4956 off_t offset;
4957 struct tm tm;
4958 time_t committer_time;
4960 if (nlines != a->nlines ||
4961 (lineno != -1 && lineno < 1) || lineno > a->nlines)
4962 return got_error(GOT_ERR_RANGE);
4964 if (sigint_received)
4965 return got_error(GOT_ERR_ITER_COMPLETED);
4967 if (lineno == -1)
4968 return NULL; /* no change in this commit */
4970 /* Annotate this line. */
4971 bline = &a->lines[lineno - 1];
4972 if (bline->annotated)
4973 return NULL;
4974 err = got_object_id_str(&bline->id_str, id);
4975 if (err)
4976 return err;
4978 bline->committer = strdup(got_object_commit_get_committer(commit));
4979 if (bline->committer == NULL) {
4980 err = got_error_from_errno("strdup");
4981 goto done;
4984 committer_time = got_object_commit_get_committer_time(commit);
4985 if (gmtime_r(&committer_time, &tm) == NULL)
4986 return got_error_from_errno("gmtime_r");
4987 if (strftime(bline->datebuf, sizeof(bline->datebuf), "%G-%m-%d",
4988 &tm) == 0) {
4989 err = got_error(GOT_ERR_NO_SPACE);
4990 goto done;
4992 bline->annotated = 1;
4994 /* Print lines annotated so far. */
4995 bline = &a->lines[a->lineno_cur - 1];
4996 if (!bline->annotated)
4997 goto done;
4999 offset = a->line_offsets[a->lineno_cur - 1];
5000 if (fseeko(a->f, offset, SEEK_SET) == -1) {
5001 err = got_error_from_errno("fseeko");
5002 goto done;
5005 while (a->lineno_cur <= a->nlines && bline->annotated) {
5006 char *smallerthan, *at, *nl, *committer;
5007 size_t len;
5009 if (getline(&line, &linesize, a->f) == -1) {
5010 if (ferror(a->f))
5011 err = got_error_from_errno("getline");
5012 break;
5015 committer = bline->committer;
5016 smallerthan = strchr(committer, '<');
5017 if (smallerthan && smallerthan[1] != '\0')
5018 committer = smallerthan + 1;
5019 at = strchr(committer, '@');
5020 if (at)
5021 *at = '\0';
5022 len = strlen(committer);
5023 if (len >= 9)
5024 committer[8] = '\0';
5026 nl = strchr(line, '\n');
5027 if (nl)
5028 *nl = '\0';
5029 printf("%.*d) %.8s %s %-8s %s\n", a->nlines_prec, a->lineno_cur,
5030 bline->id_str, bline->datebuf, committer, line);
5032 a->lineno_cur++;
5033 bline = &a->lines[a->lineno_cur - 1];
5035 done:
5036 free(line);
5037 return err;
5040 static const struct got_error *
5041 cmd_blame(int argc, char *argv[])
5043 const struct got_error *error;
5044 struct got_repository *repo = NULL;
5045 struct got_worktree *worktree = NULL;
5046 char *path, *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
5047 char *link_target = NULL;
5048 struct got_object_id *obj_id = NULL;
5049 struct got_object_id *commit_id = NULL;
5050 struct got_commit_object *commit = NULL;
5051 struct got_blob_object *blob = NULL;
5052 char *commit_id_str = NULL;
5053 struct blame_cb_args bca;
5054 int ch, obj_type, i, fd1 = -1, fd2 = -1, fd3 = -1;
5055 off_t filesize;
5056 int *pack_fds = NULL;
5057 FILE *f1 = NULL, *f2 = NULL;
5059 fd1 = got_opentempfd();
5060 if (fd1 == -1)
5061 return got_error_from_errno("got_opentempfd");
5063 memset(&bca, 0, sizeof(bca));
5065 #ifndef PROFILE
5066 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
5067 NULL) == -1)
5068 err(1, "pledge");
5069 #endif
5071 while ((ch = getopt(argc, argv, "c:r:")) != -1) {
5072 switch (ch) {
5073 case 'c':
5074 commit_id_str = optarg;
5075 break;
5076 case 'r':
5077 repo_path = realpath(optarg, NULL);
5078 if (repo_path == NULL)
5079 return got_error_from_errno2("realpath",
5080 optarg);
5081 got_path_strip_trailing_slashes(repo_path);
5082 break;
5083 default:
5084 usage_blame();
5085 /* NOTREACHED */
5089 argc -= optind;
5090 argv += optind;
5092 if (argc == 1)
5093 path = argv[0];
5094 else
5095 usage_blame();
5097 cwd = getcwd(NULL, 0);
5098 if (cwd == NULL) {
5099 error = got_error_from_errno("getcwd");
5100 goto done;
5103 error = got_repo_pack_fds_open(&pack_fds);
5104 if (error != NULL)
5105 goto done;
5107 if (repo_path == NULL) {
5108 error = got_worktree_open(&worktree, cwd);
5109 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5110 goto done;
5111 else
5112 error = NULL;
5113 if (worktree) {
5114 repo_path =
5115 strdup(got_worktree_get_repo_path(worktree));
5116 if (repo_path == NULL) {
5117 error = got_error_from_errno("strdup");
5118 if (error)
5119 goto done;
5121 } else {
5122 repo_path = strdup(cwd);
5123 if (repo_path == NULL) {
5124 error = got_error_from_errno("strdup");
5125 goto done;
5130 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
5131 if (error != NULL)
5132 goto done;
5134 if (worktree) {
5135 const char *prefix = got_worktree_get_path_prefix(worktree);
5136 char *p;
5138 error = got_worktree_resolve_path(&p, worktree, path);
5139 if (error)
5140 goto done;
5141 if (asprintf(&in_repo_path, "%s%s%s", prefix,
5142 (p[0] != '\0' && !got_path_is_root_dir(prefix)) ? "/" : "",
5143 p) == -1) {
5144 error = got_error_from_errno("asprintf");
5145 free(p);
5146 goto done;
5148 free(p);
5149 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5150 } else {
5151 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5152 if (error)
5153 goto done;
5154 error = got_repo_map_path(&in_repo_path, repo, path);
5156 if (error)
5157 goto done;
5159 if (commit_id_str == NULL) {
5160 struct got_reference *head_ref;
5161 error = got_ref_open(&head_ref, repo, worktree ?
5162 got_worktree_get_head_ref_name(worktree) : GOT_REF_HEAD, 0);
5163 if (error != NULL)
5164 goto done;
5165 error = got_ref_resolve(&commit_id, repo, head_ref);
5166 got_ref_close(head_ref);
5167 if (error != NULL)
5168 goto done;
5169 } else {
5170 struct got_reflist_head refs;
5171 TAILQ_INIT(&refs);
5172 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
5173 NULL);
5174 if (error)
5175 goto done;
5176 error = got_repo_match_object_id(&commit_id, NULL,
5177 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
5178 got_ref_list_free(&refs);
5179 if (error)
5180 goto done;
5183 if (worktree) {
5184 /* Release work tree lock. */
5185 got_worktree_close(worktree);
5186 worktree = NULL;
5189 error = got_object_open_as_commit(&commit, repo, commit_id);
5190 if (error)
5191 goto done;
5193 error = got_object_resolve_symlinks(&link_target, in_repo_path,
5194 commit, repo);
5195 if (error)
5196 goto done;
5198 error = got_object_id_by_path(&obj_id, repo, commit,
5199 link_target ? link_target : in_repo_path);
5200 if (error)
5201 goto done;
5203 error = got_object_get_type(&obj_type, repo, obj_id);
5204 if (error)
5205 goto done;
5207 if (obj_type != GOT_OBJ_TYPE_BLOB) {
5208 error = got_error_path(link_target ? link_target : in_repo_path,
5209 GOT_ERR_OBJ_TYPE);
5210 goto done;
5213 error = got_object_open_as_blob(&blob, repo, obj_id, 8192, fd1);
5214 if (error)
5215 goto done;
5216 bca.f = got_opentemp();
5217 if (bca.f == NULL) {
5218 error = got_error_from_errno("got_opentemp");
5219 goto done;
5221 error = got_object_blob_dump_to_file(&filesize, &bca.nlines,
5222 &bca.line_offsets, bca.f, blob);
5223 if (error || bca.nlines == 0)
5224 goto done;
5226 /* Don't include \n at EOF in the blame line count. */
5227 if (bca.line_offsets[bca.nlines - 1] == filesize)
5228 bca.nlines--;
5230 bca.lines = calloc(bca.nlines, sizeof(*bca.lines));
5231 if (bca.lines == NULL) {
5232 error = got_error_from_errno("calloc");
5233 goto done;
5235 bca.lineno_cur = 1;
5236 bca.nlines_prec = 0;
5237 i = bca.nlines;
5238 while (i > 0) {
5239 i /= 10;
5240 bca.nlines_prec++;
5242 bca.repo = repo;
5244 fd2 = got_opentempfd();
5245 if (fd2 == -1) {
5246 error = got_error_from_errno("got_opentempfd");
5247 goto done;
5249 fd3 = got_opentempfd();
5250 if (fd3 == -1) {
5251 error = got_error_from_errno("got_opentempfd");
5252 goto done;
5254 f1 = got_opentemp();
5255 if (f1 == NULL) {
5256 error = got_error_from_errno("got_opentemp");
5257 goto done;
5259 f2 = got_opentemp();
5260 if (f2 == NULL) {
5261 error = got_error_from_errno("got_opentemp");
5262 goto done;
5264 error = got_blame(link_target ? link_target : in_repo_path, commit_id,
5265 repo, GOT_DIFF_ALGORITHM_PATIENCE, blame_cb, &bca,
5266 check_cancelled, NULL, fd2, fd3, f1, f2);
5267 done:
5268 free(in_repo_path);
5269 free(link_target);
5270 free(repo_path);
5271 free(cwd);
5272 free(commit_id);
5273 free(obj_id);
5274 if (commit)
5275 got_object_commit_close(commit);
5277 if (fd1 != -1 && close(fd1) == -1 && error == NULL)
5278 error = got_error_from_errno("close");
5279 if (fd2 != -1 && close(fd2) == -1 && error == NULL)
5280 error = got_error_from_errno("close");
5281 if (fd3 != -1 && close(fd3) == -1 && error == NULL)
5282 error = got_error_from_errno("close");
5283 if (f1 && fclose(f1) == EOF && error == NULL)
5284 error = got_error_from_errno("fclose");
5285 if (f2 && fclose(f2) == EOF && error == NULL)
5286 error = got_error_from_errno("fclose");
5288 if (blob)
5289 got_object_blob_close(blob);
5290 if (worktree)
5291 got_worktree_close(worktree);
5292 if (repo) {
5293 const struct got_error *close_err = got_repo_close(repo);
5294 if (error == NULL)
5295 error = close_err;
5297 if (pack_fds) {
5298 const struct got_error *pack_err =
5299 got_repo_pack_fds_close(pack_fds);
5300 if (error == NULL)
5301 error = pack_err;
5303 if (bca.lines) {
5304 for (i = 0; i < bca.nlines; i++) {
5305 struct blame_line *bline = &bca.lines[i];
5306 free(bline->id_str);
5307 free(bline->committer);
5309 free(bca.lines);
5311 free(bca.line_offsets);
5312 if (bca.f && fclose(bca.f) == EOF && error == NULL)
5313 error = got_error_from_errno("fclose");
5314 return error;
5317 __dead static void
5318 usage_tree(void)
5320 fprintf(stderr, "usage: %s tree [-iR] [-c commit] [-r repository-path] "
5321 "[path]\n", getprogname());
5322 exit(1);
5325 static const struct got_error *
5326 print_entry(struct got_tree_entry *te, const char *id, const char *path,
5327 const char *root_path, struct got_repository *repo)
5329 const struct got_error *err = NULL;
5330 int is_root_path = (strcmp(path, root_path) == 0);
5331 const char *modestr = "";
5332 mode_t mode = got_tree_entry_get_mode(te);
5333 char *link_target = NULL;
5335 path += strlen(root_path);
5336 while (path[0] == '/')
5337 path++;
5339 if (got_object_tree_entry_is_submodule(te))
5340 modestr = "$";
5341 else if (S_ISLNK(mode)) {
5342 int i;
5344 err = got_tree_entry_get_symlink_target(&link_target, te, repo);
5345 if (err)
5346 return err;
5347 for (i = 0; link_target[i] != '\0'; i++) {
5348 if (!isprint((unsigned char)link_target[i]))
5349 link_target[i] = '?';
5352 modestr = "@";
5354 else if (S_ISDIR(mode))
5355 modestr = "/";
5356 else if (mode & S_IXUSR)
5357 modestr = "*";
5359 printf("%s%s%s%s%s%s%s\n", id ? id : "", path,
5360 is_root_path ? "" : "/", got_tree_entry_get_name(te), modestr,
5361 link_target ? " -> ": "", link_target ? link_target : "");
5363 free(link_target);
5364 return NULL;
5367 static const struct got_error *
5368 print_tree(const char *path, struct got_commit_object *commit,
5369 int show_ids, int recurse, const char *root_path,
5370 struct got_repository *repo)
5372 const struct got_error *err = NULL;
5373 struct got_object_id *tree_id = NULL;
5374 struct got_tree_object *tree = NULL;
5375 int nentries, i;
5377 err = got_object_id_by_path(&tree_id, repo, commit, path);
5378 if (err)
5379 goto done;
5381 err = got_object_open_as_tree(&tree, repo, tree_id);
5382 if (err)
5383 goto done;
5384 nentries = got_object_tree_get_nentries(tree);
5385 for (i = 0; i < nentries; i++) {
5386 struct got_tree_entry *te;
5387 char *id = NULL;
5389 if (sigint_received || sigpipe_received)
5390 break;
5392 te = got_object_tree_get_entry(tree, i);
5393 if (show_ids) {
5394 char *id_str;
5395 err = got_object_id_str(&id_str,
5396 got_tree_entry_get_id(te));
5397 if (err)
5398 goto done;
5399 if (asprintf(&id, "%s ", id_str) == -1) {
5400 err = got_error_from_errno("asprintf");
5401 free(id_str);
5402 goto done;
5404 free(id_str);
5406 err = print_entry(te, id, path, root_path, repo);
5407 free(id);
5408 if (err)
5409 goto done;
5411 if (recurse && S_ISDIR(got_tree_entry_get_mode(te))) {
5412 char *child_path;
5413 if (asprintf(&child_path, "%s%s%s", path,
5414 path[0] == '/' && path[1] == '\0' ? "" : "/",
5415 got_tree_entry_get_name(te)) == -1) {
5416 err = got_error_from_errno("asprintf");
5417 goto done;
5419 err = print_tree(child_path, commit, show_ids, 1,
5420 root_path, repo);
5421 free(child_path);
5422 if (err)
5423 goto done;
5426 done:
5427 if (tree)
5428 got_object_tree_close(tree);
5429 free(tree_id);
5430 return err;
5433 static const struct got_error *
5434 cmd_tree(int argc, char *argv[])
5436 const struct got_error *error;
5437 struct got_repository *repo = NULL;
5438 struct got_worktree *worktree = NULL;
5439 const char *path, *refname = NULL;
5440 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
5441 struct got_object_id *commit_id = NULL;
5442 struct got_commit_object *commit = NULL;
5443 char *commit_id_str = NULL;
5444 int show_ids = 0, recurse = 0;
5445 int ch;
5446 int *pack_fds = NULL;
5448 #ifndef PROFILE
5449 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
5450 NULL) == -1)
5451 err(1, "pledge");
5452 #endif
5454 while ((ch = getopt(argc, argv, "c:iRr:")) != -1) {
5455 switch (ch) {
5456 case 'c':
5457 commit_id_str = optarg;
5458 break;
5459 case 'i':
5460 show_ids = 1;
5461 break;
5462 case 'R':
5463 recurse = 1;
5464 break;
5465 case 'r':
5466 repo_path = realpath(optarg, NULL);
5467 if (repo_path == NULL)
5468 return got_error_from_errno2("realpath",
5469 optarg);
5470 got_path_strip_trailing_slashes(repo_path);
5471 break;
5472 default:
5473 usage_tree();
5474 /* NOTREACHED */
5478 argc -= optind;
5479 argv += optind;
5481 if (argc == 1)
5482 path = argv[0];
5483 else if (argc > 1)
5484 usage_tree();
5485 else
5486 path = NULL;
5488 cwd = getcwd(NULL, 0);
5489 if (cwd == NULL) {
5490 error = got_error_from_errno("getcwd");
5491 goto done;
5494 error = got_repo_pack_fds_open(&pack_fds);
5495 if (error != NULL)
5496 goto done;
5498 if (repo_path == NULL) {
5499 error = got_worktree_open(&worktree, cwd);
5500 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5501 goto done;
5502 else
5503 error = NULL;
5504 if (worktree) {
5505 repo_path =
5506 strdup(got_worktree_get_repo_path(worktree));
5507 if (repo_path == NULL)
5508 error = got_error_from_errno("strdup");
5509 if (error)
5510 goto done;
5511 } else {
5512 repo_path = strdup(cwd);
5513 if (repo_path == NULL) {
5514 error = got_error_from_errno("strdup");
5515 goto done;
5520 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
5521 if (error != NULL)
5522 goto done;
5524 if (worktree) {
5525 const char *prefix = got_worktree_get_path_prefix(worktree);
5526 char *p;
5528 if (path == NULL || got_path_is_root_dir(path))
5529 path = "";
5530 error = got_worktree_resolve_path(&p, worktree, path);
5531 if (error)
5532 goto done;
5533 if (asprintf(&in_repo_path, "%s%s%s", prefix,
5534 (p[0] != '\0' && !got_path_is_root_dir(prefix)) ? "/" : "",
5535 p) == -1) {
5536 error = got_error_from_errno("asprintf");
5537 free(p);
5538 goto done;
5540 free(p);
5541 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5542 if (error)
5543 goto done;
5544 } else {
5545 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5546 if (error)
5547 goto done;
5548 if (path == NULL)
5549 path = "/";
5550 error = got_repo_map_path(&in_repo_path, repo, path);
5551 if (error != NULL)
5552 goto done;
5555 if (commit_id_str == NULL) {
5556 struct got_reference *head_ref;
5557 if (worktree)
5558 refname = got_worktree_get_head_ref_name(worktree);
5559 else
5560 refname = GOT_REF_HEAD;
5561 error = got_ref_open(&head_ref, repo, refname, 0);
5562 if (error != NULL)
5563 goto done;
5564 error = got_ref_resolve(&commit_id, repo, head_ref);
5565 got_ref_close(head_ref);
5566 if (error != NULL)
5567 goto done;
5568 } else {
5569 struct got_reflist_head refs;
5570 TAILQ_INIT(&refs);
5571 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
5572 NULL);
5573 if (error)
5574 goto done;
5575 error = got_repo_match_object_id(&commit_id, NULL,
5576 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
5577 got_ref_list_free(&refs);
5578 if (error)
5579 goto done;
5582 if (worktree) {
5583 /* Release work tree lock. */
5584 got_worktree_close(worktree);
5585 worktree = NULL;
5588 error = got_object_open_as_commit(&commit, repo, commit_id);
5589 if (error)
5590 goto done;
5592 error = print_tree(in_repo_path, commit, show_ids, recurse,
5593 in_repo_path, repo);
5594 done:
5595 free(in_repo_path);
5596 free(repo_path);
5597 free(cwd);
5598 free(commit_id);
5599 if (commit)
5600 got_object_commit_close(commit);
5601 if (worktree)
5602 got_worktree_close(worktree);
5603 if (repo) {
5604 const struct got_error *close_err = got_repo_close(repo);
5605 if (error == NULL)
5606 error = close_err;
5608 if (pack_fds) {
5609 const struct got_error *pack_err =
5610 got_repo_pack_fds_close(pack_fds);
5611 if (error == NULL)
5612 error = pack_err;
5614 return error;
5617 __dead static void
5618 usage_status(void)
5620 fprintf(stderr, "usage: %s status [-I] [-S status-codes] "
5621 "[-s status-codes] [path ...]\n", getprogname());
5622 exit(1);
5625 struct got_status_arg {
5626 char *status_codes;
5627 int suppress;
5630 static const struct got_error *
5631 print_status(void *arg, unsigned char status, unsigned char staged_status,
5632 const char *path, struct got_object_id *blob_id,
5633 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
5634 int dirfd, const char *de_name)
5636 struct got_status_arg *st = arg;
5638 if (status == staged_status && (status == GOT_STATUS_DELETE))
5639 status = GOT_STATUS_NO_CHANGE;
5640 if (st != NULL && st->status_codes) {
5641 size_t ncodes = strlen(st->status_codes);
5642 int i, j = 0;
5644 for (i = 0; i < ncodes ; i++) {
5645 if (st->suppress) {
5646 if (status == st->status_codes[i] ||
5647 staged_status == st->status_codes[i]) {
5648 j++;
5649 continue;
5651 } else {
5652 if (status == st->status_codes[i] ||
5653 staged_status == st->status_codes[i])
5654 break;
5658 if (st->suppress && j == 0)
5659 goto print;
5661 if (i == ncodes)
5662 return NULL;
5664 print:
5665 printf("%c%c %s\n", status, staged_status, path);
5666 return NULL;
5669 static const struct got_error *
5670 cmd_status(int argc, char *argv[])
5672 const struct got_error *error = NULL;
5673 struct got_repository *repo = NULL;
5674 struct got_worktree *worktree = NULL;
5675 struct got_status_arg st;
5676 char *cwd = NULL;
5677 struct got_pathlist_head paths;
5678 int ch, i, no_ignores = 0;
5679 int *pack_fds = NULL;
5681 TAILQ_INIT(&paths);
5683 memset(&st, 0, sizeof(st));
5684 st.status_codes = NULL;
5685 st.suppress = 0;
5687 #ifndef PROFILE
5688 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
5689 NULL) == -1)
5690 err(1, "pledge");
5691 #endif
5693 while ((ch = getopt(argc, argv, "IS:s:")) != -1) {
5694 switch (ch) {
5695 case 'I':
5696 no_ignores = 1;
5697 break;
5698 case 'S':
5699 if (st.status_codes != NULL && st.suppress == 0)
5700 option_conflict('S', 's');
5701 st.suppress = 1;
5702 /* fallthrough */
5703 case 's':
5704 for (i = 0; optarg[i] != '\0'; i++) {
5705 switch (optarg[i]) {
5706 case GOT_STATUS_MODIFY:
5707 case GOT_STATUS_ADD:
5708 case GOT_STATUS_DELETE:
5709 case GOT_STATUS_CONFLICT:
5710 case GOT_STATUS_MISSING:
5711 case GOT_STATUS_OBSTRUCTED:
5712 case GOT_STATUS_UNVERSIONED:
5713 case GOT_STATUS_MODE_CHANGE:
5714 case GOT_STATUS_NONEXISTENT:
5715 break;
5716 default:
5717 errx(1, "invalid status code '%c'",
5718 optarg[i]);
5721 if (ch == 's' && st.suppress)
5722 option_conflict('s', 'S');
5723 st.status_codes = optarg;
5724 break;
5725 default:
5726 usage_status();
5727 /* NOTREACHED */
5731 argc -= optind;
5732 argv += optind;
5734 cwd = getcwd(NULL, 0);
5735 if (cwd == NULL) {
5736 error = got_error_from_errno("getcwd");
5737 goto done;
5740 error = got_repo_pack_fds_open(&pack_fds);
5741 if (error != NULL)
5742 goto done;
5744 error = got_worktree_open(&worktree, cwd);
5745 if (error) {
5746 if (error->code == GOT_ERR_NOT_WORKTREE)
5747 error = wrap_not_worktree_error(error, "status", cwd);
5748 goto done;
5751 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
5752 NULL, pack_fds);
5753 if (error != NULL)
5754 goto done;
5756 error = apply_unveil(got_repo_get_path(repo), 1,
5757 got_worktree_get_root_path(worktree));
5758 if (error)
5759 goto done;
5761 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
5762 if (error)
5763 goto done;
5765 error = got_worktree_status(worktree, &paths, repo, no_ignores,
5766 print_status, &st, check_cancelled, NULL);
5767 done:
5768 if (pack_fds) {
5769 const struct got_error *pack_err =
5770 got_repo_pack_fds_close(pack_fds);
5771 if (error == NULL)
5772 error = pack_err;
5774 if (repo) {
5775 const struct got_error *close_err = got_repo_close(repo);
5776 if (error == NULL)
5777 error = close_err;
5780 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
5781 free(cwd);
5782 return error;
5785 __dead static void
5786 usage_tag(void)
5788 fprintf(stderr, "usage: %s tag [-lVv] [-c commit] [-m message] "
5789 "[-r repository-path] [-s signer-id] name\n", getprogname());
5790 exit(1);
5793 #if 0
5794 static const struct got_error *
5795 sort_tags(struct got_reflist_head *sorted, struct got_reflist_head *tags)
5797 const struct got_error *err = NULL;
5798 struct got_reflist_entry *re, *se, *new;
5799 struct got_object_id *re_id, *se_id;
5800 struct got_tag_object *re_tag, *se_tag;
5801 time_t re_time, se_time;
5803 STAILQ_FOREACH(re, tags, entry) {
5804 se = STAILQ_FIRST(sorted);
5805 if (se == NULL) {
5806 err = got_reflist_entry_dup(&new, re);
5807 if (err)
5808 return err;
5809 STAILQ_INSERT_HEAD(sorted, new, entry);
5810 continue;
5811 } else {
5812 err = got_ref_resolve(&re_id, repo, re->ref);
5813 if (err)
5814 break;
5815 err = got_object_open_as_tag(&re_tag, repo, re_id);
5816 free(re_id);
5817 if (err)
5818 break;
5819 re_time = got_object_tag_get_tagger_time(re_tag);
5820 got_object_tag_close(re_tag);
5823 while (se) {
5824 err = got_ref_resolve(&se_id, repo, re->ref);
5825 if (err)
5826 break;
5827 err = got_object_open_as_tag(&se_tag, repo, se_id);
5828 free(se_id);
5829 if (err)
5830 break;
5831 se_time = got_object_tag_get_tagger_time(se_tag);
5832 got_object_tag_close(se_tag);
5834 if (se_time > re_time) {
5835 err = got_reflist_entry_dup(&new, re);
5836 if (err)
5837 return err;
5838 STAILQ_INSERT_AFTER(sorted, se, new, entry);
5839 break;
5841 se = STAILQ_NEXT(se, entry);
5842 continue;
5845 done:
5846 return err;
5848 #endif
5850 static const struct got_error *
5851 get_tag_refname(char **refname, const char *tag_name)
5853 const struct got_error *err;
5855 if (strncmp("refs/tags/", tag_name, 10) == 0) {
5856 *refname = strdup(tag_name);
5857 if (*refname == NULL)
5858 return got_error_from_errno("strdup");
5859 } else if (asprintf(refname, "refs/tags/%s", tag_name) == -1) {
5860 err = got_error_from_errno("asprintf");
5861 *refname = NULL;
5862 return err;
5865 return NULL;
5868 static const struct got_error *
5869 list_tags(struct got_repository *repo, const char *tag_name, int verify_tags,
5870 const char *allowed_signers, const char *revoked_signers, int verbosity)
5872 static const struct got_error *err = NULL;
5873 struct got_reflist_head refs;
5874 struct got_reflist_entry *re;
5875 char *wanted_refname = NULL;
5876 int bad_sigs = 0;
5878 TAILQ_INIT(&refs);
5880 err = got_ref_list(&refs, repo, "refs/tags", got_ref_cmp_tags, repo);
5881 if (err)
5882 return err;
5884 if (tag_name) {
5885 struct got_reference *ref;
5886 err = get_tag_refname(&wanted_refname, tag_name);
5887 if (err)
5888 goto done;
5889 /* Wanted tag reference should exist. */
5890 err = got_ref_open(&ref, repo, wanted_refname, 0);
5891 if (err)
5892 goto done;
5893 got_ref_close(ref);
5896 TAILQ_FOREACH(re, &refs, entry) {
5897 const char *refname;
5898 char *refstr, *tagmsg0, *tagmsg, *line, *id_str, *datestr;
5899 char datebuf[26];
5900 const char *tagger, *ssh_sig = NULL;
5901 char *sig_msg = NULL;
5902 time_t tagger_time;
5903 struct got_object_id *id;
5904 struct got_tag_object *tag;
5905 struct got_commit_object *commit = NULL;
5907 refname = got_ref_get_name(re->ref);
5908 if (strncmp(refname, "refs/tags/", 10) != 0 ||
5909 (wanted_refname && strcmp(refname, wanted_refname) != 0))
5910 continue;
5911 refname += 10;
5912 refstr = got_ref_to_str(re->ref);
5913 if (refstr == NULL) {
5914 err = got_error_from_errno("got_ref_to_str");
5915 break;
5918 err = got_ref_resolve(&id, repo, re->ref);
5919 if (err)
5920 break;
5921 err = got_object_open_as_tag(&tag, repo, id);
5922 if (err) {
5923 if (err->code != GOT_ERR_OBJ_TYPE) {
5924 free(id);
5925 break;
5927 /* "lightweight" tag */
5928 err = got_object_open_as_commit(&commit, repo, id);
5929 if (err) {
5930 free(id);
5931 break;
5933 tagger = got_object_commit_get_committer(commit);
5934 tagger_time =
5935 got_object_commit_get_committer_time(commit);
5936 err = got_object_id_str(&id_str, id);
5937 free(id);
5938 if (err)
5939 break;
5940 } else {
5941 free(id);
5942 tagger = got_object_tag_get_tagger(tag);
5943 tagger_time = got_object_tag_get_tagger_time(tag);
5944 err = got_object_id_str(&id_str,
5945 got_object_tag_get_object_id(tag));
5946 if (err)
5947 break;
5950 if (tag && verify_tags) {
5951 ssh_sig = got_sigs_get_tagmsg_ssh_signature(
5952 got_object_tag_get_message(tag));
5953 if (ssh_sig && allowed_signers == NULL) {
5954 err = got_error_msg(
5955 GOT_ERR_VERIFY_TAG_SIGNATURE,
5956 "SSH signature verification requires "
5957 "setting allowed_signers in "
5958 "got.conf(5)");
5959 break;
5963 printf("%stag %s %s\n", GOT_COMMIT_SEP_STR, refname, refstr);
5964 free(refstr);
5965 printf("from: %s\n", tagger);
5966 datestr = get_datestr(&tagger_time, datebuf);
5967 if (datestr)
5968 printf("date: %s UTC\n", datestr);
5969 if (commit)
5970 printf("object: %s %s\n", GOT_OBJ_LABEL_COMMIT, id_str);
5971 else {
5972 switch (got_object_tag_get_object_type(tag)) {
5973 case GOT_OBJ_TYPE_BLOB:
5974 printf("object: %s %s\n", GOT_OBJ_LABEL_BLOB,
5975 id_str);
5976 break;
5977 case GOT_OBJ_TYPE_TREE:
5978 printf("object: %s %s\n", GOT_OBJ_LABEL_TREE,
5979 id_str);
5980 break;
5981 case GOT_OBJ_TYPE_COMMIT:
5982 printf("object: %s %s\n", GOT_OBJ_LABEL_COMMIT,
5983 id_str);
5984 break;
5985 case GOT_OBJ_TYPE_TAG:
5986 printf("object: %s %s\n", GOT_OBJ_LABEL_TAG,
5987 id_str);
5988 break;
5989 default:
5990 break;
5993 free(id_str);
5995 if (ssh_sig) {
5996 err = got_sigs_verify_tag_ssh(&sig_msg, tag, ssh_sig,
5997 allowed_signers, revoked_signers, verbosity);
5998 if (err && err->code == GOT_ERR_BAD_TAG_SIGNATURE)
5999 bad_sigs = 1;
6000 else if (err)
6001 break;
6002 printf("signature: %s", sig_msg);
6003 free(sig_msg);
6004 sig_msg = NULL;
6007 if (commit) {
6008 err = got_object_commit_get_logmsg(&tagmsg0, commit);
6009 if (err)
6010 break;
6011 got_object_commit_close(commit);
6012 } else {
6013 tagmsg0 = strdup(got_object_tag_get_message(tag));
6014 got_object_tag_close(tag);
6015 if (tagmsg0 == NULL) {
6016 err = got_error_from_errno("strdup");
6017 break;
6021 tagmsg = tagmsg0;
6022 do {
6023 line = strsep(&tagmsg, "\n");
6024 if (line)
6025 printf(" %s\n", line);
6026 } while (line);
6027 free(tagmsg0);
6029 done:
6030 got_ref_list_free(&refs);
6031 free(wanted_refname);
6033 if (err == NULL && bad_sigs)
6034 err = got_error(GOT_ERR_BAD_TAG_SIGNATURE);
6035 return err;
6038 static const struct got_error *
6039 get_tag_message(char **tagmsg, char **tagmsg_path, const char *commit_id_str,
6040 const char *tag_name, const char *repo_path)
6042 const struct got_error *err = NULL;
6043 char *template = NULL, *initial_content = NULL;
6044 char *editor = NULL;
6045 int initial_content_len;
6046 int fd = -1;
6048 if (asprintf(&template, GOT_TMPDIR_STR "/got-tagmsg") == -1) {
6049 err = got_error_from_errno("asprintf");
6050 goto done;
6053 initial_content_len = asprintf(&initial_content,
6054 "\n# tagging commit %s as %s\n",
6055 commit_id_str, tag_name);
6056 if (initial_content_len == -1) {
6057 err = got_error_from_errno("asprintf");
6058 goto done;
6061 err = got_opentemp_named_fd(tagmsg_path, &fd, template, "");
6062 if (err)
6063 goto done;
6065 if (write(fd, initial_content, initial_content_len) == -1) {
6066 err = got_error_from_errno2("write", *tagmsg_path);
6067 goto done;
6069 if (close(fd) == -1) {
6070 err = got_error_from_errno2("close", *tagmsg_path);
6071 goto done;
6073 fd = -1;
6075 err = get_editor(&editor);
6076 if (err)
6077 goto done;
6078 err = edit_logmsg(tagmsg, editor, *tagmsg_path, initial_content,
6079 initial_content_len, 1);
6080 done:
6081 free(initial_content);
6082 free(template);
6083 free(editor);
6085 if (fd != -1 && close(fd) == -1 && err == NULL)
6086 err = got_error_from_errno2("close", *tagmsg_path);
6088 if (err) {
6089 free(*tagmsg);
6090 *tagmsg = NULL;
6092 return err;
6095 static const struct got_error *
6096 add_tag(struct got_repository *repo, const char *tagger,
6097 const char *tag_name, const char *commit_arg, const char *tagmsg_arg,
6098 const char *signer_id, int verbosity)
6100 const struct got_error *err = NULL;
6101 struct got_object_id *commit_id = NULL, *tag_id = NULL;
6102 char *label = NULL, *commit_id_str = NULL;
6103 struct got_reference *ref = NULL;
6104 char *refname = NULL, *tagmsg = NULL;
6105 char *tagmsg_path = NULL, *tag_id_str = NULL;
6106 int preserve_tagmsg = 0;
6107 struct got_reflist_head refs;
6109 TAILQ_INIT(&refs);
6112 * Don't let the user create a tag name with a leading '-'.
6113 * While technically a valid reference name, this case is usually
6114 * an unintended typo.
6116 if (tag_name[0] == '-')
6117 return got_error_path(tag_name, GOT_ERR_REF_NAME_MINUS);
6119 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
6120 if (err)
6121 goto done;
6123 err = got_repo_match_object_id(&commit_id, &label, commit_arg,
6124 GOT_OBJ_TYPE_COMMIT, &refs, repo);
6125 if (err)
6126 goto done;
6128 err = got_object_id_str(&commit_id_str, commit_id);
6129 if (err)
6130 goto done;
6132 err = get_tag_refname(&refname, tag_name);
6133 if (err)
6134 goto done;
6135 if (strncmp("refs/tags/", tag_name, 10) == 0)
6136 tag_name += 10;
6138 err = got_ref_open(&ref, repo, refname, 0);
6139 if (err == NULL) {
6140 err = got_error(GOT_ERR_TAG_EXISTS);
6141 goto done;
6142 } else if (err->code != GOT_ERR_NOT_REF)
6143 goto done;
6145 if (tagmsg_arg == NULL) {
6146 err = get_tag_message(&tagmsg, &tagmsg_path, commit_id_str,
6147 tag_name, got_repo_get_path(repo));
6148 if (err) {
6149 if (err->code != GOT_ERR_COMMIT_MSG_EMPTY &&
6150 tagmsg_path != NULL)
6151 preserve_tagmsg = 1;
6152 goto done;
6154 /* Editor is done; we can now apply unveil(2) */
6155 err = got_sigs_apply_unveil();
6156 if (err)
6157 goto done;
6158 err = apply_unveil(got_repo_get_path(repo), 0, NULL);
6159 if (err)
6160 goto done;
6163 err = got_object_tag_create(&tag_id, tag_name, commit_id,
6164 tagger, time(NULL), tagmsg ? tagmsg : tagmsg_arg, signer_id, repo,
6165 verbosity);
6166 if (err) {
6167 if (tagmsg_path)
6168 preserve_tagmsg = 1;
6169 goto done;
6172 err = got_ref_alloc(&ref, refname, tag_id);
6173 if (err) {
6174 if (tagmsg_path)
6175 preserve_tagmsg = 1;
6176 goto done;
6179 err = got_ref_write(ref, repo);
6180 if (err) {
6181 if (tagmsg_path)
6182 preserve_tagmsg = 1;
6183 goto done;
6186 err = got_object_id_str(&tag_id_str, tag_id);
6187 if (err) {
6188 if (tagmsg_path)
6189 preserve_tagmsg = 1;
6190 goto done;
6192 printf("Created tag %s\n", tag_id_str);
6193 done:
6194 if (preserve_tagmsg) {
6195 fprintf(stderr, "%s: tag message preserved in %s\n",
6196 getprogname(), tagmsg_path);
6197 } else if (tagmsg_path && unlink(tagmsg_path) == -1 && err == NULL)
6198 err = got_error_from_errno2("unlink", tagmsg_path);
6199 free(tag_id_str);
6200 if (ref)
6201 got_ref_close(ref);
6202 free(commit_id);
6203 free(commit_id_str);
6204 free(refname);
6205 free(tagmsg);
6206 free(tagmsg_path);
6207 got_ref_list_free(&refs);
6208 return err;
6211 static const struct got_error *
6212 cmd_tag(int argc, char *argv[])
6214 const struct got_error *error = NULL;
6215 struct got_repository *repo = NULL;
6216 struct got_worktree *worktree = NULL;
6217 char *cwd = NULL, *repo_path = NULL, *commit_id_str = NULL;
6218 char *gitconfig_path = NULL, *tagger = NULL;
6219 char *allowed_signers = NULL, *revoked_signers = NULL;
6220 const char *signer_id = NULL;
6221 const char *tag_name = NULL, *commit_id_arg = NULL, *tagmsg = NULL;
6222 int ch, do_list = 0, verify_tags = 0, verbosity = 0;
6223 int *pack_fds = NULL;
6225 #ifndef PROFILE
6226 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
6227 "sendfd unveil", NULL) == -1)
6228 err(1, "pledge");
6229 #endif
6231 while ((ch = getopt(argc, argv, "c:lm:r:s:Vv")) != -1) {
6232 switch (ch) {
6233 case 'c':
6234 commit_id_arg = optarg;
6235 break;
6236 case 'l':
6237 do_list = 1;
6238 break;
6239 case 'm':
6240 tagmsg = optarg;
6241 break;
6242 case 'r':
6243 repo_path = realpath(optarg, NULL);
6244 if (repo_path == NULL) {
6245 error = got_error_from_errno2("realpath",
6246 optarg);
6247 goto done;
6249 got_path_strip_trailing_slashes(repo_path);
6250 break;
6251 case 's':
6252 signer_id = optarg;
6253 break;
6254 case 'V':
6255 verify_tags = 1;
6256 break;
6257 case 'v':
6258 if (verbosity < 0)
6259 verbosity = 0;
6260 else if (verbosity < 3)
6261 verbosity++;
6262 break;
6263 default:
6264 usage_tag();
6265 /* NOTREACHED */
6269 argc -= optind;
6270 argv += optind;
6272 if (do_list || verify_tags) {
6273 if (commit_id_arg != NULL)
6274 errx(1,
6275 "-c option can only be used when creating a tag");
6276 if (tagmsg) {
6277 if (do_list)
6278 option_conflict('l', 'm');
6279 else
6280 option_conflict('V', 'm');
6282 if (signer_id) {
6283 if (do_list)
6284 option_conflict('l', 's');
6285 else
6286 option_conflict('V', 's');
6288 if (argc > 1)
6289 usage_tag();
6290 } else if (argc != 1)
6291 usage_tag();
6293 if (argc == 1)
6294 tag_name = argv[0];
6296 cwd = getcwd(NULL, 0);
6297 if (cwd == NULL) {
6298 error = got_error_from_errno("getcwd");
6299 goto done;
6302 error = got_repo_pack_fds_open(&pack_fds);
6303 if (error != NULL)
6304 goto done;
6306 if (repo_path == NULL) {
6307 error = got_worktree_open(&worktree, cwd);
6308 if (error && error->code != GOT_ERR_NOT_WORKTREE)
6309 goto done;
6310 else
6311 error = NULL;
6312 if (worktree) {
6313 repo_path =
6314 strdup(got_worktree_get_repo_path(worktree));
6315 if (repo_path == NULL)
6316 error = got_error_from_errno("strdup");
6317 if (error)
6318 goto done;
6319 } else {
6320 repo_path = strdup(cwd);
6321 if (repo_path == NULL) {
6322 error = got_error_from_errno("strdup");
6323 goto done;
6328 if (do_list || verify_tags) {
6329 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
6330 if (error != NULL)
6331 goto done;
6332 error = get_allowed_signers(&allowed_signers, repo, worktree);
6333 if (error)
6334 goto done;
6335 error = get_revoked_signers(&revoked_signers, repo, worktree);
6336 if (error)
6337 goto done;
6338 if (worktree) {
6339 /* Release work tree lock. */
6340 got_worktree_close(worktree);
6341 worktree = NULL;
6345 * Remove "cpath" promise unless needed for signature tmpfile
6346 * creation.
6348 if (verify_tags)
6349 got_sigs_apply_unveil();
6350 else {
6351 #ifndef PROFILE
6352 if (pledge("stdio rpath wpath flock proc exec sendfd "
6353 "unveil", NULL) == -1)
6354 err(1, "pledge");
6355 #endif
6357 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
6358 if (error)
6359 goto done;
6360 error = list_tags(repo, tag_name, verify_tags, allowed_signers,
6361 revoked_signers, verbosity);
6362 } else {
6363 error = get_gitconfig_path(&gitconfig_path);
6364 if (error)
6365 goto done;
6366 error = got_repo_open(&repo, repo_path, gitconfig_path,
6367 pack_fds);
6368 if (error != NULL)
6369 goto done;
6371 error = get_author(&tagger, repo, worktree);
6372 if (error)
6373 goto done;
6374 if (signer_id == NULL)
6375 signer_id = get_signer_id(repo, worktree);
6377 if (tagmsg) {
6378 if (signer_id) {
6379 error = got_sigs_apply_unveil();
6380 if (error)
6381 goto done;
6383 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
6384 if (error)
6385 goto done;
6388 if (commit_id_arg == NULL) {
6389 struct got_reference *head_ref;
6390 struct got_object_id *commit_id;
6391 error = got_ref_open(&head_ref, repo,
6392 worktree ? got_worktree_get_head_ref_name(worktree)
6393 : GOT_REF_HEAD, 0);
6394 if (error)
6395 goto done;
6396 error = got_ref_resolve(&commit_id, repo, head_ref);
6397 got_ref_close(head_ref);
6398 if (error)
6399 goto done;
6400 error = got_object_id_str(&commit_id_str, commit_id);
6401 free(commit_id);
6402 if (error)
6403 goto done;
6406 if (worktree) {
6407 /* Release work tree lock. */
6408 got_worktree_close(worktree);
6409 worktree = NULL;
6412 error = add_tag(repo, tagger, tag_name,
6413 commit_id_str ? commit_id_str : commit_id_arg, tagmsg,
6414 signer_id, verbosity);
6416 done:
6417 if (repo) {
6418 const struct got_error *close_err = got_repo_close(repo);
6419 if (error == NULL)
6420 error = close_err;
6422 if (worktree)
6423 got_worktree_close(worktree);
6424 if (pack_fds) {
6425 const struct got_error *pack_err =
6426 got_repo_pack_fds_close(pack_fds);
6427 if (error == NULL)
6428 error = pack_err;
6430 free(cwd);
6431 free(repo_path);
6432 free(gitconfig_path);
6433 free(commit_id_str);
6434 free(tagger);
6435 free(allowed_signers);
6436 free(revoked_signers);
6437 return error;
6440 __dead static void
6441 usage_add(void)
6443 fprintf(stderr, "usage: %s add [-IR] path ...\n", getprogname());
6444 exit(1);
6447 static const struct got_error *
6448 add_progress(void *arg, unsigned char status, const char *path)
6450 while (path[0] == '/')
6451 path++;
6452 printf("%c %s\n", status, path);
6453 return NULL;
6456 static const struct got_error *
6457 cmd_add(int argc, char *argv[])
6459 const struct got_error *error = NULL;
6460 struct got_repository *repo = NULL;
6461 struct got_worktree *worktree = NULL;
6462 char *cwd = NULL;
6463 struct got_pathlist_head paths;
6464 struct got_pathlist_entry *pe;
6465 int ch, can_recurse = 0, no_ignores = 0;
6466 int *pack_fds = NULL;
6468 TAILQ_INIT(&paths);
6470 #ifndef PROFILE
6471 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
6472 NULL) == -1)
6473 err(1, "pledge");
6474 #endif
6476 while ((ch = getopt(argc, argv, "IR")) != -1) {
6477 switch (ch) {
6478 case 'I':
6479 no_ignores = 1;
6480 break;
6481 case 'R':
6482 can_recurse = 1;
6483 break;
6484 default:
6485 usage_add();
6486 /* NOTREACHED */
6490 argc -= optind;
6491 argv += optind;
6493 if (argc < 1)
6494 usage_add();
6496 cwd = getcwd(NULL, 0);
6497 if (cwd == NULL) {
6498 error = got_error_from_errno("getcwd");
6499 goto done;
6502 error = got_repo_pack_fds_open(&pack_fds);
6503 if (error != NULL)
6504 goto done;
6506 error = got_worktree_open(&worktree, cwd);
6507 if (error) {
6508 if (error->code == GOT_ERR_NOT_WORKTREE)
6509 error = wrap_not_worktree_error(error, "add", cwd);
6510 goto done;
6513 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
6514 NULL, pack_fds);
6515 if (error != NULL)
6516 goto done;
6518 error = apply_unveil(got_repo_get_path(repo), 1,
6519 got_worktree_get_root_path(worktree));
6520 if (error)
6521 goto done;
6523 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
6524 if (error)
6525 goto done;
6527 if (!can_recurse) {
6528 char *ondisk_path;
6529 struct stat sb;
6530 TAILQ_FOREACH(pe, &paths, entry) {
6531 if (asprintf(&ondisk_path, "%s/%s",
6532 got_worktree_get_root_path(worktree),
6533 pe->path) == -1) {
6534 error = got_error_from_errno("asprintf");
6535 goto done;
6537 if (lstat(ondisk_path, &sb) == -1) {
6538 if (errno == ENOENT) {
6539 free(ondisk_path);
6540 continue;
6542 error = got_error_from_errno2("lstat",
6543 ondisk_path);
6544 free(ondisk_path);
6545 goto done;
6547 free(ondisk_path);
6548 if (S_ISDIR(sb.st_mode)) {
6549 error = got_error_msg(GOT_ERR_BAD_PATH,
6550 "adding directories requires -R option");
6551 goto done;
6556 error = got_worktree_schedule_add(worktree, &paths, add_progress,
6557 NULL, repo, no_ignores);
6558 done:
6559 if (repo) {
6560 const struct got_error *close_err = got_repo_close(repo);
6561 if (error == NULL)
6562 error = close_err;
6564 if (worktree)
6565 got_worktree_close(worktree);
6566 if (pack_fds) {
6567 const struct got_error *pack_err =
6568 got_repo_pack_fds_close(pack_fds);
6569 if (error == NULL)
6570 error = pack_err;
6572 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
6573 free(cwd);
6574 return error;
6577 __dead static void
6578 usage_remove(void)
6580 fprintf(stderr, "usage: %s remove [-fkR] [-s status-codes] path ...\n",
6581 getprogname());
6582 exit(1);
6585 static const struct got_error *
6586 print_remove_status(void *arg, unsigned char status,
6587 unsigned char staged_status, const char *path)
6589 while (path[0] == '/')
6590 path++;
6591 if (status == GOT_STATUS_NONEXISTENT)
6592 return NULL;
6593 if (status == staged_status && (status == GOT_STATUS_DELETE))
6594 status = GOT_STATUS_NO_CHANGE;
6595 printf("%c%c %s\n", status, staged_status, path);
6596 return NULL;
6599 static const struct got_error *
6600 cmd_remove(int argc, char *argv[])
6602 const struct got_error *error = NULL;
6603 struct got_worktree *worktree = NULL;
6604 struct got_repository *repo = NULL;
6605 const char *status_codes = NULL;
6606 char *cwd = NULL;
6607 struct got_pathlist_head paths;
6608 struct got_pathlist_entry *pe;
6609 int ch, delete_local_mods = 0, can_recurse = 0, keep_on_disk = 0, i;
6610 int ignore_missing_paths = 0;
6611 int *pack_fds = NULL;
6613 TAILQ_INIT(&paths);
6615 #ifndef PROFILE
6616 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
6617 NULL) == -1)
6618 err(1, "pledge");
6619 #endif
6621 while ((ch = getopt(argc, argv, "fkRs:")) != -1) {
6622 switch (ch) {
6623 case 'f':
6624 delete_local_mods = 1;
6625 ignore_missing_paths = 1;
6626 break;
6627 case 'k':
6628 keep_on_disk = 1;
6629 break;
6630 case 'R':
6631 can_recurse = 1;
6632 break;
6633 case 's':
6634 for (i = 0; optarg[i] != '\0'; i++) {
6635 switch (optarg[i]) {
6636 case GOT_STATUS_MODIFY:
6637 delete_local_mods = 1;
6638 break;
6639 case GOT_STATUS_MISSING:
6640 ignore_missing_paths = 1;
6641 break;
6642 default:
6643 errx(1, "invalid status code '%c'",
6644 optarg[i]);
6647 status_codes = optarg;
6648 break;
6649 default:
6650 usage_remove();
6651 /* NOTREACHED */
6655 argc -= optind;
6656 argv += optind;
6658 if (argc < 1)
6659 usage_remove();
6661 cwd = getcwd(NULL, 0);
6662 if (cwd == NULL) {
6663 error = got_error_from_errno("getcwd");
6664 goto done;
6667 error = got_repo_pack_fds_open(&pack_fds);
6668 if (error != NULL)
6669 goto done;
6671 error = got_worktree_open(&worktree, cwd);
6672 if (error) {
6673 if (error->code == GOT_ERR_NOT_WORKTREE)
6674 error = wrap_not_worktree_error(error, "remove", cwd);
6675 goto done;
6678 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
6679 NULL, pack_fds);
6680 if (error)
6681 goto done;
6683 error = apply_unveil(got_repo_get_path(repo), 1,
6684 got_worktree_get_root_path(worktree));
6685 if (error)
6686 goto done;
6688 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
6689 if (error)
6690 goto done;
6692 if (!can_recurse) {
6693 char *ondisk_path;
6694 struct stat sb;
6695 TAILQ_FOREACH(pe, &paths, entry) {
6696 if (asprintf(&ondisk_path, "%s/%s",
6697 got_worktree_get_root_path(worktree),
6698 pe->path) == -1) {
6699 error = got_error_from_errno("asprintf");
6700 goto done;
6702 if (lstat(ondisk_path, &sb) == -1) {
6703 if (errno == ENOENT) {
6704 free(ondisk_path);
6705 continue;
6707 error = got_error_from_errno2("lstat",
6708 ondisk_path);
6709 free(ondisk_path);
6710 goto done;
6712 free(ondisk_path);
6713 if (S_ISDIR(sb.st_mode)) {
6714 error = got_error_msg(GOT_ERR_BAD_PATH,
6715 "removing directories requires -R option");
6716 goto done;
6721 error = got_worktree_schedule_delete(worktree, &paths,
6722 delete_local_mods, status_codes, print_remove_status, NULL,
6723 repo, keep_on_disk, ignore_missing_paths);
6724 done:
6725 if (repo) {
6726 const struct got_error *close_err = got_repo_close(repo);
6727 if (error == NULL)
6728 error = close_err;
6730 if (worktree)
6731 got_worktree_close(worktree);
6732 if (pack_fds) {
6733 const struct got_error *pack_err =
6734 got_repo_pack_fds_close(pack_fds);
6735 if (error == NULL)
6736 error = pack_err;
6738 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
6739 free(cwd);
6740 return error;
6743 __dead static void
6744 usage_patch(void)
6746 fprintf(stderr, "usage: %s patch [-nR] [-c commit] [-p strip-count] "
6747 "[patchfile]\n", getprogname());
6748 exit(1);
6751 static const struct got_error *
6752 patch_from_stdin(int *patchfd)
6754 const struct got_error *err = NULL;
6755 ssize_t r;
6756 char buf[BUFSIZ];
6757 sig_t sighup, sigint, sigquit;
6759 *patchfd = got_opentempfd();
6760 if (*patchfd == -1)
6761 return got_error_from_errno("got_opentempfd");
6763 sighup = signal(SIGHUP, SIG_DFL);
6764 sigint = signal(SIGINT, SIG_DFL);
6765 sigquit = signal(SIGQUIT, SIG_DFL);
6767 for (;;) {
6768 r = read(0, buf, sizeof(buf));
6769 if (r == -1) {
6770 err = got_error_from_errno("read");
6771 break;
6773 if (r == 0)
6774 break;
6775 if (write(*patchfd, buf, r) == -1) {
6776 err = got_error_from_errno("write");
6777 break;
6781 signal(SIGHUP, sighup);
6782 signal(SIGINT, sigint);
6783 signal(SIGQUIT, sigquit);
6785 if (err == NULL && lseek(*patchfd, 0, SEEK_SET) == -1)
6786 err = got_error_from_errno("lseek");
6788 if (err != NULL) {
6789 close(*patchfd);
6790 *patchfd = -1;
6793 return err;
6796 struct got_patch_progress_arg {
6797 int did_something;
6798 int conflicts;
6799 int rejects;
6802 static const struct got_error *
6803 patch_progress(void *arg, const char *old, const char *new,
6804 unsigned char status, const struct got_error *error, int old_from,
6805 int old_lines, int new_from, int new_lines, int offset,
6806 int ws_mangled, const struct got_error *hunk_err)
6808 const char *path = new == NULL ? old : new;
6809 struct got_patch_progress_arg *a = arg;
6811 while (*path == '/')
6812 path++;
6814 if (status != GOT_STATUS_NO_CHANGE &&
6815 status != 0 /* per-hunk progress */) {
6816 printf("%c %s\n", status, path);
6817 a->did_something = 1;
6820 if (hunk_err == NULL) {
6821 if (status == GOT_STATUS_CANNOT_UPDATE)
6822 a->rejects++;
6823 else if (status == GOT_STATUS_CONFLICT)
6824 a->conflicts++;
6827 if (error != NULL)
6828 fprintf(stderr, "%s: %s\n", getprogname(), error->msg);
6830 if (offset != 0 || hunk_err != NULL || ws_mangled) {
6831 printf("@@ -%d,%d +%d,%d @@ ", old_from,
6832 old_lines, new_from, new_lines);
6833 if (hunk_err != NULL)
6834 printf("%s\n", hunk_err->msg);
6835 else if (offset != 0)
6836 printf("applied with offset %d\n", offset);
6837 else
6838 printf("hunk contains mangled whitespace\n");
6841 return NULL;
6844 static void
6845 print_patch_progress_stats(struct got_patch_progress_arg *ppa)
6847 if (!ppa->did_something)
6848 return;
6850 if (ppa->conflicts > 0)
6851 printf("Files with merge conflicts: %d\n", ppa->conflicts);
6853 if (ppa->rejects > 0) {
6854 printf("Files where patch failed to apply: %d\n",
6855 ppa->rejects);
6859 static const struct got_error *
6860 cmd_patch(int argc, char *argv[])
6862 const struct got_error *error = NULL, *close_error = NULL;
6863 struct got_worktree *worktree = NULL;
6864 struct got_repository *repo = NULL;
6865 struct got_reflist_head refs;
6866 struct got_object_id *commit_id = NULL;
6867 const char *commit_id_str = NULL;
6868 struct stat sb;
6869 const char *errstr;
6870 char *cwd = NULL;
6871 int ch, nop = 0, strip = -1, reverse = 0;
6872 int patchfd;
6873 int *pack_fds = NULL;
6874 struct got_patch_progress_arg ppa;
6876 TAILQ_INIT(&refs);
6878 #ifndef PROFILE
6879 if (pledge("stdio rpath wpath cpath fattr proc exec sendfd flock "
6880 "unveil", NULL) == -1)
6881 err(1, "pledge");
6882 #endif
6884 while ((ch = getopt(argc, argv, "c:np:R")) != -1) {
6885 switch (ch) {
6886 case 'c':
6887 commit_id_str = optarg;
6888 break;
6889 case 'n':
6890 nop = 1;
6891 break;
6892 case 'p':
6893 strip = strtonum(optarg, 0, INT_MAX, &errstr);
6894 if (errstr != NULL)
6895 errx(1, "pathname strip count is %s: %s",
6896 errstr, optarg);
6897 break;
6898 case 'R':
6899 reverse = 1;
6900 break;
6901 default:
6902 usage_patch();
6903 /* NOTREACHED */
6907 argc -= optind;
6908 argv += optind;
6910 if (argc == 0) {
6911 error = patch_from_stdin(&patchfd);
6912 if (error)
6913 return error;
6914 } else if (argc == 1) {
6915 patchfd = open(argv[0], O_RDONLY);
6916 if (patchfd == -1) {
6917 error = got_error_from_errno2("open", argv[0]);
6918 return error;
6920 if (fstat(patchfd, &sb) == -1) {
6921 error = got_error_from_errno2("fstat", argv[0]);
6922 goto done;
6924 if (!S_ISREG(sb.st_mode)) {
6925 error = got_error_path(argv[0], GOT_ERR_BAD_FILETYPE);
6926 goto done;
6928 } else
6929 usage_patch();
6931 if ((cwd = getcwd(NULL, 0)) == NULL) {
6932 error = got_error_from_errno("getcwd");
6933 goto done;
6936 error = got_repo_pack_fds_open(&pack_fds);
6937 if (error != NULL)
6938 goto done;
6940 error = got_worktree_open(&worktree, cwd);
6941 if (error != NULL)
6942 goto done;
6944 const char *repo_path = got_worktree_get_repo_path(worktree);
6945 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
6946 if (error != NULL)
6947 goto done;
6949 error = apply_unveil(got_repo_get_path(repo), 0,
6950 got_worktree_get_root_path(worktree));
6951 if (error != NULL)
6952 goto done;
6954 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
6955 if (error)
6956 goto done;
6958 if (commit_id_str != NULL) {
6959 error = got_repo_match_object_id(&commit_id, NULL,
6960 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
6961 if (error)
6962 goto done;
6965 memset(&ppa, 0, sizeof(ppa));
6966 error = got_patch(patchfd, worktree, repo, nop, strip, reverse,
6967 commit_id, patch_progress, &ppa, check_cancelled, NULL);
6968 print_patch_progress_stats(&ppa);
6969 done:
6970 got_ref_list_free(&refs);
6971 free(commit_id);
6972 if (repo) {
6973 close_error = got_repo_close(repo);
6974 if (error == NULL)
6975 error = close_error;
6977 if (worktree != NULL) {
6978 close_error = got_worktree_close(worktree);
6979 if (error == NULL)
6980 error = close_error;
6982 if (pack_fds) {
6983 const struct got_error *pack_err =
6984 got_repo_pack_fds_close(pack_fds);
6985 if (error == NULL)
6986 error = pack_err;
6988 free(cwd);
6989 return error;
6992 __dead static void
6993 usage_revert(void)
6995 fprintf(stderr, "usage: %s revert [-pR] [-F response-script] path ...\n",
6996 getprogname());
6997 exit(1);
7000 static const struct got_error *
7001 revert_progress(void *arg, unsigned char status, const char *path)
7003 if (status == GOT_STATUS_UNVERSIONED)
7004 return NULL;
7006 while (path[0] == '/')
7007 path++;
7008 printf("%c %s\n", status, path);
7009 return NULL;
7012 struct choose_patch_arg {
7013 FILE *patch_script_file;
7014 const char *action;
7017 static const struct got_error *
7018 show_change(unsigned char status, const char *path, FILE *patch_file, int n,
7019 int nchanges, const char *action)
7021 const struct got_error *err;
7022 char *line = NULL;
7023 size_t linesize = 0;
7024 ssize_t linelen;
7026 switch (status) {
7027 case GOT_STATUS_ADD:
7028 printf("A %s\n%s this addition? [y/n] ", path, action);
7029 break;
7030 case GOT_STATUS_DELETE:
7031 printf("D %s\n%s this deletion? [y/n] ", path, action);
7032 break;
7033 case GOT_STATUS_MODIFY:
7034 if (fseek(patch_file, 0L, SEEK_SET) == -1)
7035 return got_error_from_errno("fseek");
7036 printf(GOT_COMMIT_SEP_STR);
7037 while ((linelen = getline(&line, &linesize, patch_file)) != -1)
7038 printf("%s", line);
7039 if (linelen == -1 && ferror(patch_file)) {
7040 err = got_error_from_errno("getline");
7041 free(line);
7042 return err;
7044 free(line);
7045 printf(GOT_COMMIT_SEP_STR);
7046 printf("M %s (change %d of %d)\n%s this change? [y/n/q] ",
7047 path, n, nchanges, action);
7048 break;
7049 default:
7050 return got_error_path(path, GOT_ERR_FILE_STATUS);
7053 fflush(stdout);
7054 return NULL;
7057 static const struct got_error *
7058 choose_patch(int *choice, void *arg, unsigned char status, const char *path,
7059 FILE *patch_file, int n, int nchanges)
7061 const struct got_error *err = NULL;
7062 char *line = NULL;
7063 size_t linesize = 0;
7064 ssize_t linelen;
7065 int resp = ' ';
7066 struct choose_patch_arg *a = arg;
7068 *choice = GOT_PATCH_CHOICE_NONE;
7070 if (a->patch_script_file) {
7071 char *nl;
7072 err = show_change(status, path, patch_file, n, nchanges,
7073 a->action);
7074 if (err)
7075 return err;
7076 linelen = getline(&line, &linesize, a->patch_script_file);
7077 if (linelen == -1) {
7078 if (ferror(a->patch_script_file))
7079 return got_error_from_errno("getline");
7080 return NULL;
7082 nl = strchr(line, '\n');
7083 if (nl)
7084 *nl = '\0';
7085 if (strcmp(line, "y") == 0) {
7086 *choice = GOT_PATCH_CHOICE_YES;
7087 printf("y\n");
7088 } else if (strcmp(line, "n") == 0) {
7089 *choice = GOT_PATCH_CHOICE_NO;
7090 printf("n\n");
7091 } else if (strcmp(line, "q") == 0 &&
7092 status == GOT_STATUS_MODIFY) {
7093 *choice = GOT_PATCH_CHOICE_QUIT;
7094 printf("q\n");
7095 } else
7096 printf("invalid response '%s'\n", line);
7097 free(line);
7098 return NULL;
7101 while (resp != 'y' && resp != 'n' && resp != 'q') {
7102 err = show_change(status, path, patch_file, n, nchanges,
7103 a->action);
7104 if (err)
7105 return err;
7106 resp = getchar();
7107 if (resp == '\n')
7108 resp = getchar();
7109 if (status == GOT_STATUS_MODIFY) {
7110 if (resp != 'y' && resp != 'n' && resp != 'q') {
7111 printf("invalid response '%c'\n", resp);
7112 resp = ' ';
7114 } else if (resp != 'y' && resp != 'n') {
7115 printf("invalid response '%c'\n", resp);
7116 resp = ' ';
7120 if (resp == 'y')
7121 *choice = GOT_PATCH_CHOICE_YES;
7122 else if (resp == 'n')
7123 *choice = GOT_PATCH_CHOICE_NO;
7124 else if (resp == 'q' && status == GOT_STATUS_MODIFY)
7125 *choice = GOT_PATCH_CHOICE_QUIT;
7127 return NULL;
7130 struct wt_commitable_path_arg {
7131 struct got_pathlist_head *commit_paths;
7132 int *has_changes;
7136 * Shortcut work tree status callback to determine if the set of paths scanned
7137 * has at least one versioned path that is being modified and, if not NULL, is
7138 * in the arg->commit_paths list. Set arg and return GOT_ERR_FILE_MODIFIED as
7139 * soon as a path is passed with a status that satisfies this criteria.
7141 static const struct got_error *
7142 worktree_has_commitable_path(void *arg, unsigned char status,
7143 unsigned char staged_status, const char *path,
7144 struct got_object_id *blob_id, struct got_object_id *staged_blob_id,
7145 struct got_object_id *commit_id, int dirfd, const char *de_name)
7147 struct wt_commitable_path_arg *a = arg;
7149 if (status == staged_status && (status == GOT_STATUS_DELETE))
7150 status = GOT_STATUS_NO_CHANGE;
7152 if (!(status == GOT_STATUS_NO_CHANGE ||
7153 status == GOT_STATUS_UNVERSIONED) ||
7154 staged_status != GOT_STATUS_NO_CHANGE) {
7155 if (a->commit_paths != NULL) {
7156 struct got_pathlist_entry *pe;
7158 TAILQ_FOREACH(pe, a->commit_paths, entry) {
7159 if (strncmp(path, pe->path,
7160 pe->path_len) == 0) {
7161 *a->has_changes = 1;
7162 break;
7165 } else
7166 *a->has_changes = 1;
7168 if (*a->has_changes)
7169 return got_error(GOT_ERR_FILE_MODIFIED);
7172 return NULL;
7176 * Check that the changeset of the commit identified by id is
7177 * comprised of at least one modified path that is being committed.
7179 static const struct got_error *
7180 commit_path_changed_in_worktree(struct wt_commitable_path_arg *wcpa,
7181 struct got_object_id *id, struct got_worktree *worktree,
7182 struct got_repository *repo)
7184 const struct got_error *err;
7185 struct got_pathlist_head paths;
7186 struct got_commit_object *commit = NULL, *pcommit = NULL;
7187 struct got_tree_object *tree = NULL, *ptree = NULL;
7188 struct got_object_qid *pid;
7190 TAILQ_INIT(&paths);
7192 err = got_object_open_as_commit(&commit, repo, id);
7193 if (err)
7194 goto done;
7196 err = got_object_open_as_tree(&tree, repo,
7197 got_object_commit_get_tree_id(commit));
7198 if (err)
7199 goto done;
7201 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
7202 if (pid != NULL) {
7203 err = got_object_open_as_commit(&pcommit, repo, &pid->id);
7204 if (err)
7205 goto done;
7207 err = got_object_open_as_tree(&ptree, repo,
7208 got_object_commit_get_tree_id(pcommit));
7209 if (err)
7210 goto done;
7213 err = got_diff_tree(ptree, tree, NULL, NULL, -1, -1, "", "", repo,
7214 got_diff_tree_collect_changed_paths, &paths, 0);
7215 if (err)
7216 goto done;
7218 err = got_worktree_status(worktree, &paths, repo, 0,
7219 worktree_has_commitable_path, wcpa, check_cancelled, NULL);
7220 if (err && err->code == GOT_ERR_FILE_MODIFIED) {
7222 * At least one changed path in the referenced commit is
7223 * modified in the work tree, that's all we need to know!
7225 err = NULL;
7228 done:
7229 got_pathlist_free(&paths, GOT_PATHLIST_FREE_ALL);
7230 if (commit)
7231 got_object_commit_close(commit);
7232 if (pcommit)
7233 got_object_commit_close(pcommit);
7234 if (tree)
7235 got_object_tree_close(tree);
7236 if (ptree)
7237 got_object_tree_close(ptree);
7238 return err;
7242 * Remove any "logmsg" reference comprised entirely of paths that have
7243 * been reverted in this work tree. If any path in the logmsg ref changeset
7244 * remains in a changed state in the worktree, do not remove the reference.
7246 static const struct got_error *
7247 rm_logmsg_ref(struct got_worktree *worktree, struct got_repository *repo)
7249 const struct got_error *err;
7250 struct got_reflist_head refs;
7251 struct got_reflist_entry *re;
7252 struct got_commit_object *commit = NULL;
7253 struct got_object_id *commit_id = NULL;
7254 struct wt_commitable_path_arg wcpa;
7255 char *uuidstr = NULL;
7257 TAILQ_INIT(&refs);
7259 err = got_worktree_get_uuid(&uuidstr, worktree);
7260 if (err)
7261 goto done;
7263 err = got_ref_list(&refs, repo, "refs/got/worktree",
7264 got_ref_cmp_by_name, repo);
7265 if (err)
7266 goto done;
7268 TAILQ_FOREACH(re, &refs, entry) {
7269 const char *refname;
7270 int has_changes = 0;
7272 refname = got_ref_get_name(re->ref);
7274 if (!strncmp(refname, GOT_WORKTREE_CHERRYPICK_REF_PREFIX,
7275 GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN))
7276 refname += GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN + 1;
7277 else if (!strncmp(refname, GOT_WORKTREE_BACKOUT_REF_PREFIX,
7278 GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN))
7279 refname += GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN + 1;
7280 else
7281 continue;
7283 if (strncmp(refname, uuidstr, GOT_WORKTREE_UUID_STRLEN) == 0)
7284 refname += GOT_WORKTREE_UUID_STRLEN + 1; /* skip '-' */
7285 else
7286 continue;
7288 err = got_repo_match_object_id(&commit_id, NULL, refname,
7289 GOT_OBJ_TYPE_COMMIT, NULL, repo);
7290 if (err)
7291 goto done;
7293 err = got_object_open_as_commit(&commit, repo, commit_id);
7294 if (err)
7295 goto done;
7297 wcpa.commit_paths = NULL;
7298 wcpa.has_changes = &has_changes;
7300 err = commit_path_changed_in_worktree(&wcpa, commit_id,
7301 worktree, repo);
7302 if (err)
7303 goto done;
7305 if (!has_changes) {
7306 err = got_ref_delete(re->ref, repo);
7307 if (err)
7308 goto done;
7311 got_object_commit_close(commit);
7312 commit = NULL;
7313 free(commit_id);
7314 commit_id = NULL;
7317 done:
7318 free(uuidstr);
7319 free(commit_id);
7320 got_ref_list_free(&refs);
7321 if (commit)
7322 got_object_commit_close(commit);
7323 return err;
7326 static const struct got_error *
7327 cmd_revert(int argc, char *argv[])
7329 const struct got_error *error = NULL;
7330 struct got_worktree *worktree = NULL;
7331 struct got_repository *repo = NULL;
7332 char *cwd = NULL, *path = NULL;
7333 struct got_pathlist_head paths;
7334 struct got_pathlist_entry *pe;
7335 int ch, can_recurse = 0, pflag = 0;
7336 FILE *patch_script_file = NULL;
7337 const char *patch_script_path = NULL;
7338 struct choose_patch_arg cpa;
7339 int *pack_fds = NULL;
7341 TAILQ_INIT(&paths);
7343 #ifndef PROFILE
7344 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
7345 "unveil", NULL) == -1)
7346 err(1, "pledge");
7347 #endif
7349 while ((ch = getopt(argc, argv, "F:pR")) != -1) {
7350 switch (ch) {
7351 case 'F':
7352 patch_script_path = optarg;
7353 break;
7354 case 'p':
7355 pflag = 1;
7356 break;
7357 case 'R':
7358 can_recurse = 1;
7359 break;
7360 default:
7361 usage_revert();
7362 /* NOTREACHED */
7366 argc -= optind;
7367 argv += optind;
7369 if (argc < 1)
7370 usage_revert();
7371 if (patch_script_path && !pflag)
7372 errx(1, "-F option can only be used together with -p option");
7374 cwd = getcwd(NULL, 0);
7375 if (cwd == NULL) {
7376 error = got_error_from_errno("getcwd");
7377 goto done;
7380 error = got_repo_pack_fds_open(&pack_fds);
7381 if (error != NULL)
7382 goto done;
7384 error = got_worktree_open(&worktree, cwd);
7385 if (error) {
7386 if (error->code == GOT_ERR_NOT_WORKTREE)
7387 error = wrap_not_worktree_error(error, "revert", cwd);
7388 goto done;
7391 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
7392 NULL, pack_fds);
7393 if (error != NULL)
7394 goto done;
7396 if (patch_script_path) {
7397 patch_script_file = fopen(patch_script_path, "re");
7398 if (patch_script_file == NULL) {
7399 error = got_error_from_errno2("fopen",
7400 patch_script_path);
7401 goto done;
7406 * XXX "c" perm needed on repo dir to delete merge references.
7408 error = apply_unveil(got_repo_get_path(repo), 0,
7409 got_worktree_get_root_path(worktree));
7410 if (error)
7411 goto done;
7413 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
7414 if (error)
7415 goto done;
7417 if (!can_recurse) {
7418 char *ondisk_path;
7419 struct stat sb;
7420 TAILQ_FOREACH(pe, &paths, entry) {
7421 if (asprintf(&ondisk_path, "%s/%s",
7422 got_worktree_get_root_path(worktree),
7423 pe->path) == -1) {
7424 error = got_error_from_errno("asprintf");
7425 goto done;
7427 if (lstat(ondisk_path, &sb) == -1) {
7428 if (errno == ENOENT) {
7429 free(ondisk_path);
7430 continue;
7432 error = got_error_from_errno2("lstat",
7433 ondisk_path);
7434 free(ondisk_path);
7435 goto done;
7437 free(ondisk_path);
7438 if (S_ISDIR(sb.st_mode)) {
7439 error = got_error_msg(GOT_ERR_BAD_PATH,
7440 "reverting directories requires -R option");
7441 goto done;
7446 cpa.patch_script_file = patch_script_file;
7447 cpa.action = "revert";
7448 error = got_worktree_revert(worktree, &paths, revert_progress, NULL,
7449 pflag ? choose_patch : NULL, &cpa, repo);
7451 error = rm_logmsg_ref(worktree, repo);
7452 done:
7453 if (patch_script_file && fclose(patch_script_file) == EOF &&
7454 error == NULL)
7455 error = got_error_from_errno2("fclose", patch_script_path);
7456 if (repo) {
7457 const struct got_error *close_err = got_repo_close(repo);
7458 if (error == NULL)
7459 error = close_err;
7461 if (worktree)
7462 got_worktree_close(worktree);
7463 if (pack_fds) {
7464 const struct got_error *pack_err =
7465 got_repo_pack_fds_close(pack_fds);
7466 if (error == NULL)
7467 error = pack_err;
7469 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
7470 free(path);
7471 free(cwd);
7472 return error;
7475 __dead static void
7476 usage_commit(void)
7478 fprintf(stderr, "usage: %s commit [-CNnS] [-A author] [-F path] "
7479 "[-m message] [path ...]\n", getprogname());
7480 exit(1);
7483 struct collect_commit_logmsg_arg {
7484 const char *cmdline_log;
7485 const char *prepared_log;
7486 const char *merged_log;
7487 int non_interactive;
7488 const char *editor;
7489 const char *worktree_path;
7490 const char *repo_path;
7491 const char *dial_proto;
7492 char *logmsg_path;
7495 static const struct got_error *
7496 read_prepared_logmsg(char **logmsg, const char *path)
7498 const struct got_error *err = NULL;
7499 FILE *f = NULL;
7500 struct stat sb;
7501 size_t r;
7503 *logmsg = NULL;
7504 memset(&sb, 0, sizeof(sb));
7506 f = fopen(path, "re");
7507 if (f == NULL)
7508 return got_error_from_errno2("fopen", path);
7510 if (fstat(fileno(f), &sb) == -1) {
7511 err = got_error_from_errno2("fstat", path);
7512 goto done;
7514 if (sb.st_size == 0) {
7515 err = got_error(GOT_ERR_COMMIT_MSG_EMPTY);
7516 goto done;
7519 *logmsg = malloc(sb.st_size + 1);
7520 if (*logmsg == NULL) {
7521 err = got_error_from_errno("malloc");
7522 goto done;
7525 r = fread(*logmsg, 1, sb.st_size, f);
7526 if (r != sb.st_size) {
7527 if (ferror(f))
7528 err = got_error_from_errno2("fread", path);
7529 else
7530 err = got_error(GOT_ERR_IO);
7531 goto done;
7533 (*logmsg)[sb.st_size] = '\0';
7534 done:
7535 if (fclose(f) == EOF && err == NULL)
7536 err = got_error_from_errno2("fclose", path);
7537 if (err) {
7538 free(*logmsg);
7539 *logmsg = NULL;
7541 return err;
7544 static const struct got_error *
7545 collect_commit_logmsg(struct got_pathlist_head *commitable_paths,
7546 const char *diff_path, char **logmsg, void *arg)
7548 char *initial_content = NULL;
7549 struct got_pathlist_entry *pe;
7550 const struct got_error *err = NULL;
7551 char *template = NULL;
7552 char *prepared_msg = NULL, *merged_msg = NULL;
7553 struct collect_commit_logmsg_arg *a = arg;
7554 int initial_content_len;
7555 int fd = -1;
7556 size_t len;
7558 /* if a message was specified on the command line, just use it */
7559 if (a->cmdline_log != NULL && *a->cmdline_log != '\0') {
7560 len = strlen(a->cmdline_log) + 1;
7561 *logmsg = malloc(len + 1);
7562 if (*logmsg == NULL)
7563 return got_error_from_errno("malloc");
7564 strlcpy(*logmsg, a->cmdline_log, len);
7565 return NULL;
7566 } else if (a->prepared_log != NULL && a->non_interactive)
7567 return read_prepared_logmsg(logmsg, a->prepared_log);
7569 if (asprintf(&template, "%s/logmsg", a->worktree_path) == -1)
7570 return got_error_from_errno("asprintf");
7572 err = got_opentemp_named_fd(&a->logmsg_path, &fd, template, "");
7573 if (err)
7574 goto done;
7576 if (a->prepared_log) {
7577 err = read_prepared_logmsg(&prepared_msg, a->prepared_log);
7578 if (err)
7579 goto done;
7580 } else if (a->merged_log) {
7581 err = read_prepared_logmsg(&merged_msg, a->merged_log);
7582 if (err)
7583 goto done;
7586 initial_content_len = asprintf(&initial_content,
7587 "%s%s\n# changes to be committed:\n",
7588 prepared_msg ? prepared_msg : "",
7589 merged_msg ? merged_msg : "");
7590 if (initial_content_len == -1) {
7591 err = got_error_from_errno("asprintf");
7592 goto done;
7595 if (write(fd, initial_content, initial_content_len) == -1) {
7596 err = got_error_from_errno2("write", a->logmsg_path);
7597 goto done;
7600 TAILQ_FOREACH(pe, commitable_paths, entry) {
7601 struct got_commitable *ct = pe->data;
7602 dprintf(fd, "# %c %s\n",
7603 got_commitable_get_status(ct),
7604 got_commitable_get_path(ct));
7607 if (diff_path) {
7608 dprintf(fd, "# detailed changes can be viewed in %s\n",
7609 diff_path);
7612 if (close(fd) == -1) {
7613 err = got_error_from_errno2("close", a->logmsg_path);
7614 goto done;
7616 fd = -1;
7618 err = edit_logmsg(logmsg, a->editor, a->logmsg_path, initial_content,
7619 initial_content_len, a->prepared_log ? 0 : 1);
7620 done:
7621 free(initial_content);
7622 free(template);
7623 free(prepared_msg);
7624 free(merged_msg);
7626 if (fd != -1 && close(fd) == -1 && err == NULL)
7627 err = got_error_from_errno2("close", a->logmsg_path);
7629 /* Editor is done; we can now apply unveil(2) */
7630 if (err == NULL)
7631 err = got_dial_apply_unveil(a->dial_proto);
7632 if (err == NULL)
7633 err = apply_unveil(a->repo_path, 0, a->worktree_path);
7634 if (err) {
7635 free(*logmsg);
7636 *logmsg = NULL;
7638 return err;
7641 static const struct got_error *
7642 cat_logmsg(FILE *f, struct got_commit_object *commit, const char *idstr,
7643 const char *type, int has_content)
7645 const struct got_error *err = NULL;
7646 char *logmsg = NULL;
7648 err = got_object_commit_get_logmsg(&logmsg, commit);
7649 if (err)
7650 return err;
7652 if (fprintf(f, "%s# log message of %s commit %s:%s",
7653 has_content ? "\n" : "", type, idstr, logmsg) < 0)
7654 err = got_ferror(f, GOT_ERR_IO);
7656 free(logmsg);
7657 return err;
7661 * Lookup "logmsg" references of backed-out and cherrypicked commits
7662 * belonging to the current work tree. If found, and the worktree has
7663 * at least one modified file that was changed in the referenced commit,
7664 * add its log message to a new temporary file at *logmsg_path.
7665 * Add all refs found to matched_refs to be scheduled for removal on
7666 * successful commit.
7668 static const struct got_error *
7669 lookup_logmsg_ref(char **logmsg_path, struct got_pathlist_head *paths,
7670 struct got_reflist_head *matched_refs, struct got_worktree *worktree,
7671 struct got_repository *repo)
7673 const struct got_error *err;
7674 struct got_commit_object *commit = NULL;
7675 struct got_object_id *id = NULL;
7676 struct got_reflist_head refs;
7677 struct got_reflist_entry *re, *re_match;
7678 FILE *f = NULL;
7679 char *uuidstr = NULL;
7680 int added_logmsg = 0;
7682 TAILQ_INIT(&refs);
7684 *logmsg_path = NULL;
7686 err = got_worktree_get_uuid(&uuidstr, worktree);
7687 if (err)
7688 goto done;
7690 err = got_ref_list(&refs, repo, "refs/got/worktree",
7691 got_ref_cmp_by_name, repo);
7692 if (err)
7693 goto done;
7695 TAILQ_FOREACH(re, &refs, entry) {
7696 const char *refname, *type;
7697 struct wt_commitable_path_arg wcpa;
7698 int add_logmsg = 0;
7700 refname = got_ref_get_name(re->ref);
7702 if (strncmp(refname, GOT_WORKTREE_CHERRYPICK_REF_PREFIX,
7703 GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN) == 0) {
7704 refname += GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN + 1;
7705 type = "cherrypicked";
7706 } else if (strncmp(refname, GOT_WORKTREE_BACKOUT_REF_PREFIX,
7707 GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN) == 0) {
7708 refname += GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN + 1;
7709 type = "backed-out";
7710 } else
7711 continue;
7713 if (strncmp(refname, uuidstr, GOT_WORKTREE_UUID_STRLEN) == 0)
7714 refname += GOT_WORKTREE_UUID_STRLEN + 1; /* skip '-' */
7715 else
7716 continue;
7718 err = got_repo_match_object_id(&id, NULL, refname,
7719 GOT_OBJ_TYPE_COMMIT, NULL, repo);
7720 if (err)
7721 goto done;
7723 err = got_object_open_as_commit(&commit, repo, id);
7724 if (err)
7725 goto done;
7727 wcpa.commit_paths = paths;
7728 wcpa.has_changes = &add_logmsg;
7730 err = commit_path_changed_in_worktree(&wcpa, id,
7731 worktree, repo);
7732 if (err)
7733 goto done;
7735 if (add_logmsg) {
7736 if (f == NULL) {
7737 err = got_opentemp_named(logmsg_path, &f,
7738 "got-commit-logmsg", "");
7739 if (err)
7740 goto done;
7742 err = cat_logmsg(f, commit, refname, type,
7743 added_logmsg);
7744 if (err)
7745 goto done;
7746 if (!added_logmsg)
7747 ++added_logmsg;
7749 err = got_reflist_entry_dup(&re_match, re);
7750 if (err)
7751 goto done;
7752 TAILQ_INSERT_HEAD(matched_refs, re_match, entry);
7755 got_object_commit_close(commit);
7756 commit = NULL;
7757 free(id);
7758 id = NULL;
7761 done:
7762 free(id);
7763 free(uuidstr);
7764 got_ref_list_free(&refs);
7765 if (commit)
7766 got_object_commit_close(commit);
7767 if (f && fclose(f) == EOF && err == NULL)
7768 err = got_error_from_errno("fclose");
7769 if (!added_logmsg) {
7770 if (*logmsg_path && unlink(*logmsg_path) != 0 && err == NULL)
7771 err = got_error_from_errno2("unlink", *logmsg_path);
7772 *logmsg_path = NULL;
7774 return err;
7777 static const struct got_error *
7778 cmd_commit(int argc, char *argv[])
7780 const struct got_error *error = NULL;
7781 struct got_worktree *worktree = NULL;
7782 struct got_repository *repo = NULL;
7783 char *cwd = NULL, *id_str = NULL;
7784 struct got_object_id *id = NULL;
7785 const char *logmsg = NULL;
7786 char *prepared_logmsg = NULL, *merged_logmsg = NULL;
7787 struct collect_commit_logmsg_arg cl_arg;
7788 const char *author = NULL;
7789 char *gitconfig_path = NULL, *editor = NULL, *committer = NULL;
7790 int ch, rebase_in_progress, histedit_in_progress, preserve_logmsg = 0;
7791 int allow_bad_symlinks = 0, non_interactive = 0, merge_in_progress = 0;
7792 int show_diff = 1, commit_conflicts = 0;
7793 struct got_pathlist_head paths;
7794 struct got_reflist_head refs;
7795 struct got_reflist_entry *re;
7796 int *pack_fds = NULL;
7797 const struct got_gotconfig *repo_conf = NULL, *worktree_conf = NULL;
7798 const struct got_remote_repo *remotes, *remote = NULL;
7799 int nremotes;
7800 char *proto = NULL, *host = NULL, *port = NULL;
7801 char *repo_name = NULL, *server_path = NULL;
7802 const char *remote_name;
7803 int verbosity = 0;
7804 int i;
7806 TAILQ_INIT(&refs);
7807 TAILQ_INIT(&paths);
7808 cl_arg.logmsg_path = NULL;
7810 #ifndef PROFILE
7811 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
7812 "unveil", NULL) == -1)
7813 err(1, "pledge");
7814 #endif
7816 while ((ch = getopt(argc, argv, "A:CF:m:NnS")) != -1) {
7817 switch (ch) {
7818 case 'A':
7819 author = optarg;
7820 error = valid_author(author);
7821 if (error)
7822 return error;
7823 break;
7824 case 'C':
7825 commit_conflicts = 1;
7826 break;
7827 case 'F':
7828 if (logmsg != NULL)
7829 option_conflict('F', 'm');
7830 prepared_logmsg = realpath(optarg, NULL);
7831 if (prepared_logmsg == NULL)
7832 return got_error_from_errno2("realpath",
7833 optarg);
7834 break;
7835 case 'm':
7836 if (prepared_logmsg)
7837 option_conflict('m', 'F');
7838 logmsg = optarg;
7839 break;
7840 case 'N':
7841 non_interactive = 1;
7842 break;
7843 case 'n':
7844 show_diff = 0;
7845 break;
7846 case 'S':
7847 allow_bad_symlinks = 1;
7848 break;
7849 default:
7850 usage_commit();
7851 /* NOTREACHED */
7855 argc -= optind;
7856 argv += optind;
7858 cwd = getcwd(NULL, 0);
7859 if (cwd == NULL) {
7860 error = got_error_from_errno("getcwd");
7861 goto done;
7864 error = got_repo_pack_fds_open(&pack_fds);
7865 if (error != NULL)
7866 goto done;
7868 error = got_worktree_open(&worktree, cwd);
7869 if (error) {
7870 if (error->code == GOT_ERR_NOT_WORKTREE)
7871 error = wrap_not_worktree_error(error, "commit", cwd);
7872 goto done;
7875 error = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
7876 if (error)
7877 goto done;
7878 if (rebase_in_progress) {
7879 error = got_error(GOT_ERR_REBASING);
7880 goto done;
7883 error = got_worktree_histedit_in_progress(&histedit_in_progress,
7884 worktree);
7885 if (error)
7886 goto done;
7888 error = get_gitconfig_path(&gitconfig_path);
7889 if (error)
7890 goto done;
7891 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
7892 gitconfig_path, pack_fds);
7893 if (error != NULL)
7894 goto done;
7896 error = got_worktree_merge_in_progress(&merge_in_progress, worktree, repo);
7897 if (error)
7898 goto done;
7899 if (merge_in_progress) {
7900 error = got_error(GOT_ERR_MERGE_BUSY);
7901 goto done;
7904 error = get_author(&committer, repo, worktree);
7905 if (error)
7906 goto done;
7908 if (author == NULL)
7909 author = committer;
7911 remote_name = GOT_SEND_DEFAULT_REMOTE_NAME;
7912 worktree_conf = got_worktree_get_gotconfig(worktree);
7913 if (worktree_conf) {
7914 got_gotconfig_get_remotes(&nremotes, &remotes,
7915 worktree_conf);
7916 for (i = 0; i < nremotes; i++) {
7917 if (strcmp(remotes[i].name, remote_name) == 0) {
7918 remote = &remotes[i];
7919 break;
7923 if (remote == NULL) {
7924 repo_conf = got_repo_get_gotconfig(repo);
7925 if (repo_conf) {
7926 got_gotconfig_get_remotes(&nremotes, &remotes,
7927 repo_conf);
7928 for (i = 0; i < nremotes; i++) {
7929 if (strcmp(remotes[i].name, remote_name) == 0) {
7930 remote = &remotes[i];
7931 break;
7936 if (remote == NULL) {
7937 got_repo_get_gitconfig_remotes(&nremotes, &remotes, repo);
7938 for (i = 0; i < nremotes; i++) {
7939 if (strcmp(remotes[i].name, remote_name) == 0) {
7940 remote = &remotes[i];
7941 break;
7945 if (remote == NULL) {
7946 error = got_error_path(remote_name, GOT_ERR_NO_REMOTE);
7947 goto done;
7950 error = got_dial_parse_uri(&proto, &host, &port, &server_path,
7951 &repo_name, remote->fetch_url);
7952 if (error)
7953 goto done;
7955 if (strcmp(proto, "git") == 0) {
7956 #ifndef PROFILE
7957 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
7958 "sendfd dns inet unveil", NULL) == -1)
7959 err(1, "pledge");
7960 #endif
7961 } else if (strcmp(proto, "git+ssh") == 0 ||
7962 strcmp(proto, "ssh") == 0) {
7963 #ifndef PROFILE
7964 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
7965 "sendfd unveil", NULL) == -1)
7966 err(1, "pledge");
7967 #endif
7968 } else if (strcmp(proto, "http") == 0 ||
7969 strcmp(proto, "git+http") == 0) {
7970 error = got_error_path(proto, GOT_ERR_NOT_IMPL);
7971 goto done;
7972 } else {
7973 error = got_error_path(proto, GOT_ERR_BAD_PROTO);
7974 goto done;
7978 /*if (verbosity >= 0) {
7979 printf("Connecting to \"%s\" %s://%s%s%s%s%s\n",
7980 remote->name, proto, host,
7981 port ? ":" : "", port ? port : "",
7982 *server_path == '/' ? "" : "/", server_path);
7983 }*/
7986 * unveil(2) traverses exec(2); if an editor is used we have
7987 * to apply unveil after the log message has been written during
7988 * the callback.
7990 if (logmsg == NULL || strlen(logmsg) == 0)
7991 error = get_editor(&editor);
7992 else {
7993 error = got_dial_apply_unveil(proto);
7994 if (error)
7995 goto done;
7996 error = apply_unveil(got_repo_get_path(repo), 0,
7997 got_worktree_get_root_path(worktree));
7999 if (error)
8000 goto done;
8002 if (prepared_logmsg == NULL) {
8003 error = lookup_logmsg_ref(&merged_logmsg,
8004 argc > 0 ? &paths : NULL, &refs, worktree, repo);
8005 if (error)
8006 goto done;
8009 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
8010 if (error)
8011 goto done;
8013 cl_arg.editor = editor;
8014 cl_arg.cmdline_log = logmsg;
8015 cl_arg.prepared_log = prepared_logmsg;
8016 cl_arg.merged_log = merged_logmsg;
8017 cl_arg.non_interactive = non_interactive;
8018 cl_arg.worktree_path = got_worktree_get_root_path(worktree);
8019 cl_arg.repo_path = got_repo_get_path(repo);
8020 cl_arg.dial_proto = proto;
8021 error = got_worktree_cvg_commit(&id, worktree, &paths, author,
8022 committer, allow_bad_symlinks, show_diff, commit_conflicts,
8023 collect_commit_logmsg, &cl_arg, print_status, NULL, proto, host,
8024 port, server_path, verbosity, remote, check_cancelled, repo);
8025 if (error) {
8026 if (error->code != GOT_ERR_COMMIT_MSG_EMPTY &&
8027 cl_arg.logmsg_path != NULL)
8028 preserve_logmsg = 1;
8029 goto done;
8032 error = got_object_id_str(&id_str, id);
8033 if (error)
8034 goto done;
8035 printf("Created commit %s\n", id_str);
8037 TAILQ_FOREACH(re, &refs, entry) {
8038 error = got_ref_delete(re->ref, repo);
8039 if (error)
8040 goto done;
8043 done:
8044 if (preserve_logmsg) {
8045 fprintf(stderr, "%s: log message preserved in %s\n",
8046 getprogname(), cl_arg.logmsg_path);
8047 } else if (cl_arg.logmsg_path && unlink(cl_arg.logmsg_path) == -1 &&
8048 error == NULL)
8049 error = got_error_from_errno2("unlink", cl_arg.logmsg_path);
8050 free(cl_arg.logmsg_path);
8051 if (merged_logmsg && unlink(merged_logmsg) == -1 && error == NULL)
8052 error = got_error_from_errno2("unlink", merged_logmsg);
8053 free(merged_logmsg);
8054 if (repo) {
8055 const struct got_error *close_err = got_repo_close(repo);
8056 if (error == NULL)
8057 error = close_err;
8059 if (worktree)
8060 got_worktree_close(worktree);
8061 if (pack_fds) {
8062 const struct got_error *pack_err =
8063 got_repo_pack_fds_close(pack_fds);
8064 if (error == NULL)
8065 error = pack_err;
8067 got_ref_list_free(&refs);
8068 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
8069 free(cwd);
8070 free(id_str);
8071 free(gitconfig_path);
8072 free(editor);
8073 free(committer);
8074 free(prepared_logmsg);
8075 return error;
8079 * Print and if delete is set delete all ref_prefix references.
8080 * If wanted_ref is not NULL, only print or delete this reference.
8082 static const struct got_error *
8083 process_logmsg_refs(const char *ref_prefix, size_t prefix_len,
8084 const char *wanted_ref, int delete, struct got_worktree *worktree,
8085 struct got_repository *repo)
8087 const struct got_error *err;
8088 struct got_pathlist_head paths;
8089 struct got_reflist_head refs;
8090 struct got_reflist_entry *re;
8091 struct got_reflist_object_id_map *refs_idmap = NULL;
8092 struct got_commit_object *commit = NULL;
8093 struct got_object_id *id = NULL;
8094 const char *header_prefix;
8095 char *uuidstr = NULL;
8096 int found = 0;
8098 TAILQ_INIT(&refs);
8099 TAILQ_INIT(&paths);
8101 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, repo);
8102 if (err)
8103 goto done;
8105 err = got_reflist_object_id_map_create(&refs_idmap, &refs, repo);
8106 if (err)
8107 goto done;
8109 if (worktree != NULL) {
8110 err = got_worktree_get_uuid(&uuidstr, worktree);
8111 if (err)
8112 goto done;
8115 if (wanted_ref) {
8116 if (strncmp(wanted_ref, "refs/heads/", 11) == 0)
8117 wanted_ref += 11;
8120 if (strcmp(ref_prefix, GOT_WORKTREE_BACKOUT_REF_PREFIX) == 0)
8121 header_prefix = "backout";
8122 else
8123 header_prefix = "cherrypick";
8125 TAILQ_FOREACH(re, &refs, entry) {
8126 const char *refname, *wt;
8128 refname = got_ref_get_name(re->ref);
8130 err = check_cancelled(NULL);
8131 if (err)
8132 goto done;
8134 if (strncmp(refname, ref_prefix, prefix_len) == 0)
8135 refname += prefix_len + 1; /* skip '-' delimiter */
8136 else
8137 continue;
8139 wt = refname;
8141 if (worktree == NULL || strncmp(refname, uuidstr,
8142 GOT_WORKTREE_UUID_STRLEN) == 0)
8143 refname += GOT_WORKTREE_UUID_STRLEN + 1; /* skip '-' */
8144 else
8145 continue;
8147 err = got_repo_match_object_id(&id, NULL, refname,
8148 GOT_OBJ_TYPE_COMMIT, NULL, repo);
8149 if (err)
8150 goto done;
8152 err = got_object_open_as_commit(&commit, repo, id);
8153 if (err)
8154 goto done;
8156 if (wanted_ref)
8157 found = strncmp(wanted_ref, refname,
8158 strlen(wanted_ref)) == 0;
8159 if (wanted_ref && !found) {
8160 struct got_reflist_head *ci_refs;
8162 ci_refs = got_reflist_object_id_map_lookup(refs_idmap,
8163 id);
8165 if (ci_refs) {
8166 char *refs_str = NULL;
8167 char const *r = NULL;
8169 err = build_refs_str(&refs_str, ci_refs, id,
8170 repo, 1);
8171 if (err)
8172 goto done;
8174 r = refs_str;
8175 while (r) {
8176 if (strncmp(r, wanted_ref,
8177 strlen(wanted_ref)) == 0) {
8178 found = 1;
8179 break;
8181 r = strchr(r, ' ');
8182 if (r)
8183 ++r;
8185 free(refs_str);
8189 if (wanted_ref == NULL || found) {
8190 if (delete) {
8191 err = got_ref_delete(re->ref, repo);
8192 if (err)
8193 goto done;
8194 printf("Deleted: ");
8195 err = print_commit_oneline(commit, id, repo,
8196 refs_idmap);
8197 } else {
8199 * Print paths modified by commit to help
8200 * associate commits with worktree changes.
8202 err = get_changed_paths(&paths, commit,
8203 repo, NULL);
8204 if (err)
8205 goto done;
8207 err = print_commit(commit, id, repo, NULL,
8208 &paths, NULL, 0, 0, refs_idmap, NULL,
8209 header_prefix);
8210 got_pathlist_free(&paths,
8211 GOT_PATHLIST_FREE_ALL);
8213 if (worktree == NULL)
8214 printf("work tree: %.*s\n\n",
8215 GOT_WORKTREE_UUID_STRLEN, wt);
8217 if (err || found)
8218 goto done;
8221 got_object_commit_close(commit);
8222 commit = NULL;
8223 free(id);
8224 id = NULL;
8227 if (wanted_ref != NULL && !found)
8228 err = got_error_fmt(GOT_ERR_NOT_REF, "%s", wanted_ref);
8230 done:
8231 free(id);
8232 free(uuidstr);
8233 got_ref_list_free(&refs);
8234 got_pathlist_free(&paths, GOT_PATHLIST_FREE_ALL);
8235 if (refs_idmap)
8236 got_reflist_object_id_map_free(refs_idmap);
8237 if (commit)
8238 got_object_commit_close(commit);
8239 return err;
8243 * Create new temp "logmsg" ref of the backed-out or cherrypicked commit
8244 * identified by id for log messages to prepopulate the editor on commit.
8246 static const struct got_error *
8247 logmsg_ref(struct got_object_id *id, const char *prefix,
8248 struct got_worktree *worktree, struct got_repository *repo)
8250 const struct got_error *err = NULL;
8251 char *idstr, *ref = NULL, *refname = NULL;
8252 int histedit_in_progress;
8253 int rebase_in_progress, merge_in_progress;
8256 * Silenty refuse to create merge reference if any histedit, merge,
8257 * or rebase operation is in progress.
8259 err = got_worktree_histedit_in_progress(&histedit_in_progress,
8260 worktree);
8261 if (err)
8262 return err;
8263 if (histedit_in_progress)
8264 return NULL;
8266 err = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
8267 if (err)
8268 return err;
8269 if (rebase_in_progress)
8270 return NULL;
8272 err = got_worktree_merge_in_progress(&merge_in_progress, worktree,
8273 repo);
8274 if (err)
8275 return err;
8276 if (merge_in_progress)
8277 return NULL;
8279 err = got_object_id_str(&idstr, id);
8280 if (err)
8281 return err;
8283 err = got_worktree_get_logmsg_ref_name(&refname, worktree, prefix);
8284 if (err)
8285 goto done;
8287 if (asprintf(&ref, "%s-%s", refname, idstr) == -1) {
8288 err = got_error_from_errno("asprintf");
8289 goto done;
8292 err = create_ref(ref, got_worktree_get_base_commit_id(worktree),
8293 -1, repo);
8294 done:
8295 free(ref);
8296 free(idstr);
8297 free(refname);
8298 return err;
8301 __dead static void
8302 usage_cherrypick(void)
8304 fprintf(stderr, "usage: %s cherrypick [-lX] [commit-id]\n",
8305 getprogname());
8306 exit(1);
8309 static const struct got_error *
8310 cmd_cherrypick(int argc, char *argv[])
8312 const struct got_error *error = NULL;
8313 struct got_worktree *worktree = NULL;
8314 struct got_repository *repo = NULL;
8315 char *cwd = NULL, *commit_id_str = NULL;
8316 struct got_object_id *commit_id = NULL;
8317 struct got_commit_object *commit = NULL;
8318 struct got_object_qid *pid;
8319 int ch, list_refs = 0, remove_refs = 0;
8320 struct got_update_progress_arg upa;
8321 int *pack_fds = NULL;
8323 #ifndef PROFILE
8324 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
8325 "unveil", NULL) == -1)
8326 err(1, "pledge");
8327 #endif
8329 while ((ch = getopt(argc, argv, "lX")) != -1) {
8330 switch (ch) {
8331 case 'l':
8332 list_refs = 1;
8333 break;
8334 case 'X':
8335 remove_refs = 1;
8336 break;
8337 default:
8338 usage_cherrypick();
8339 /* NOTREACHED */
8343 argc -= optind;
8344 argv += optind;
8346 if (list_refs || remove_refs) {
8347 if (argc != 0 && argc != 1)
8348 usage_cherrypick();
8349 } else if (argc != 1)
8350 usage_cherrypick();
8351 if (list_refs && remove_refs)
8352 option_conflict('l', 'X');
8354 cwd = getcwd(NULL, 0);
8355 if (cwd == NULL) {
8356 error = got_error_from_errno("getcwd");
8357 goto done;
8360 error = got_repo_pack_fds_open(&pack_fds);
8361 if (error != NULL)
8362 goto done;
8364 error = got_worktree_open(&worktree, cwd);
8365 if (error) {
8366 if (list_refs || remove_refs) {
8367 if (error->code != GOT_ERR_NOT_WORKTREE)
8368 goto done;
8369 } else {
8370 if (error->code == GOT_ERR_NOT_WORKTREE)
8371 error = wrap_not_worktree_error(error,
8372 "cherrypick", cwd);
8373 goto done;
8377 error = got_repo_open(&repo,
8378 worktree ? got_worktree_get_repo_path(worktree) : cwd,
8379 NULL, pack_fds);
8380 if (error != NULL)
8381 goto done;
8383 error = apply_unveil(got_repo_get_path(repo), 0,
8384 worktree ? got_worktree_get_root_path(worktree) : NULL);
8385 if (error)
8386 goto done;
8388 if (list_refs || remove_refs) {
8389 error = process_logmsg_refs(GOT_WORKTREE_CHERRYPICK_REF_PREFIX,
8390 GOT_WORKTREE_CHERRYPICK_REF_PREFIX_LEN,
8391 argc == 1 ? argv[0] : NULL, remove_refs, worktree, repo);
8392 goto done;
8395 error = got_repo_match_object_id(&commit_id, NULL, argv[0],
8396 GOT_OBJ_TYPE_COMMIT, NULL, repo);
8397 if (error)
8398 goto done;
8399 error = got_object_id_str(&commit_id_str, commit_id);
8400 if (error)
8401 goto done;
8403 error = got_object_open_as_commit(&commit, repo, commit_id);
8404 if (error)
8405 goto done;
8406 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
8407 memset(&upa, 0, sizeof(upa));
8408 error = got_worktree_merge_files(worktree, pid ? &pid->id : NULL,
8409 commit_id, repo, update_progress, &upa, check_cancelled,
8410 NULL);
8411 if (error != NULL)
8412 goto done;
8414 if (upa.did_something) {
8415 error = logmsg_ref(commit_id,
8416 GOT_WORKTREE_CHERRYPICK_REF_PREFIX, worktree, repo);
8417 if (error)
8418 goto done;
8419 printf("Merged commit %s\n", commit_id_str);
8421 print_merge_progress_stats(&upa);
8422 done:
8423 free(cwd);
8424 if (commit)
8425 got_object_commit_close(commit);
8426 free(commit_id_str);
8427 if (worktree)
8428 got_worktree_close(worktree);
8429 if (repo) {
8430 const struct got_error *close_err = got_repo_close(repo);
8431 if (error == NULL)
8432 error = close_err;
8434 if (pack_fds) {
8435 const struct got_error *pack_err =
8436 got_repo_pack_fds_close(pack_fds);
8437 if (error == NULL)
8438 error = pack_err;
8441 return error;
8444 __dead static void
8445 usage_backout(void)
8447 fprintf(stderr, "usage: %s backout [-lX] [commit-id]\n", getprogname());
8448 exit(1);
8451 static const struct got_error *
8452 cmd_backout(int argc, char *argv[])
8454 const struct got_error *error = NULL;
8455 struct got_worktree *worktree = NULL;
8456 struct got_repository *repo = NULL;
8457 char *cwd = NULL, *commit_id_str = NULL;
8458 struct got_object_id *commit_id = NULL;
8459 struct got_commit_object *commit = NULL;
8460 struct got_object_qid *pid;
8461 int ch, list_refs = 0, remove_refs = 0;
8462 struct got_update_progress_arg upa;
8463 int *pack_fds = NULL;
8465 #ifndef PROFILE
8466 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
8467 "unveil", NULL) == -1)
8468 err(1, "pledge");
8469 #endif
8471 while ((ch = getopt(argc, argv, "lX")) != -1) {
8472 switch (ch) {
8473 case 'l':
8474 list_refs = 1;
8475 break;
8476 case 'X':
8477 remove_refs = 1;
8478 break;
8479 default:
8480 usage_backout();
8481 /* NOTREACHED */
8485 argc -= optind;
8486 argv += optind;
8488 if (list_refs || remove_refs) {
8489 if (argc != 0 && argc != 1)
8490 usage_backout();
8491 } else if (argc != 1)
8492 usage_backout();
8493 if (list_refs && remove_refs)
8494 option_conflict('l', 'X');
8496 cwd = getcwd(NULL, 0);
8497 if (cwd == NULL) {
8498 error = got_error_from_errno("getcwd");
8499 goto done;
8502 error = got_repo_pack_fds_open(&pack_fds);
8503 if (error != NULL)
8504 goto done;
8506 error = got_worktree_open(&worktree, cwd);
8507 if (error) {
8508 if (list_refs || remove_refs) {
8509 if (error->code != GOT_ERR_NOT_WORKTREE)
8510 goto done;
8511 } else {
8512 if (error->code == GOT_ERR_NOT_WORKTREE)
8513 error = wrap_not_worktree_error(error,
8514 "backout", cwd);
8515 goto done;
8519 error = got_repo_open(&repo,
8520 worktree ? got_worktree_get_repo_path(worktree) : cwd,
8521 NULL, pack_fds);
8522 if (error != NULL)
8523 goto done;
8525 error = apply_unveil(got_repo_get_path(repo), 0,
8526 worktree ? got_worktree_get_root_path(worktree) : NULL);
8527 if (error)
8528 goto done;
8530 if (list_refs || remove_refs) {
8531 error = process_logmsg_refs(GOT_WORKTREE_BACKOUT_REF_PREFIX,
8532 GOT_WORKTREE_BACKOUT_REF_PREFIX_LEN,
8533 argc == 1 ? argv[0] : NULL, remove_refs, worktree, repo);
8534 goto done;
8537 error = got_repo_match_object_id(&commit_id, NULL, argv[0],
8538 GOT_OBJ_TYPE_COMMIT, NULL, repo);
8539 if (error)
8540 goto done;
8541 error = got_object_id_str(&commit_id_str, commit_id);
8542 if (error)
8543 goto done;
8545 error = got_object_open_as_commit(&commit, repo, commit_id);
8546 if (error)
8547 goto done;
8548 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
8549 if (pid == NULL) {
8550 error = got_error(GOT_ERR_ROOT_COMMIT);
8551 goto done;
8554 memset(&upa, 0, sizeof(upa));
8555 error = got_worktree_merge_files(worktree, commit_id, &pid->id,
8556 repo, update_progress, &upa, check_cancelled, NULL);
8557 if (error != NULL)
8558 goto done;
8560 if (upa.did_something) {
8561 error = logmsg_ref(commit_id, GOT_WORKTREE_BACKOUT_REF_PREFIX,
8562 worktree, repo);
8563 if (error)
8564 goto done;
8565 printf("Backed out commit %s\n", commit_id_str);
8567 print_merge_progress_stats(&upa);
8568 done:
8569 free(cwd);
8570 if (commit)
8571 got_object_commit_close(commit);
8572 free(commit_id_str);
8573 if (worktree)
8574 got_worktree_close(worktree);
8575 if (repo) {
8576 const struct got_error *close_err = got_repo_close(repo);
8577 if (error == NULL)
8578 error = close_err;
8580 if (pack_fds) {
8581 const struct got_error *pack_err =
8582 got_repo_pack_fds_close(pack_fds);
8583 if (error == NULL)
8584 error = pack_err;
8586 return error;
8589 __dead static void
8590 usage_cat(void)
8592 fprintf(stderr, "usage: %s cat [-P] [-c commit] [-r repository-path] "
8593 "arg ...\n", getprogname());
8594 exit(1);
8597 static const struct got_error *
8598 cat_blob(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
8600 const struct got_error *err;
8601 struct got_blob_object *blob;
8602 int fd = -1;
8604 fd = got_opentempfd();
8605 if (fd == -1)
8606 return got_error_from_errno("got_opentempfd");
8608 err = got_object_open_as_blob(&blob, repo, id, 8192, fd);
8609 if (err)
8610 goto done;
8612 err = got_object_blob_dump_to_file(NULL, NULL, NULL, outfile, blob);
8613 done:
8614 if (fd != -1 && close(fd) == -1 && err == NULL)
8615 err = got_error_from_errno("close");
8616 if (blob)
8617 got_object_blob_close(blob);
8618 return err;
8621 static const struct got_error *
8622 cat_tree(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
8624 const struct got_error *err;
8625 struct got_tree_object *tree;
8626 int nentries, i;
8628 err = got_object_open_as_tree(&tree, repo, id);
8629 if (err)
8630 return err;
8632 nentries = got_object_tree_get_nentries(tree);
8633 for (i = 0; i < nentries; i++) {
8634 struct got_tree_entry *te;
8635 char *id_str;
8636 if (sigint_received || sigpipe_received)
8637 break;
8638 te = got_object_tree_get_entry(tree, i);
8639 err = got_object_id_str(&id_str, got_tree_entry_get_id(te));
8640 if (err)
8641 break;
8642 fprintf(outfile, "%s %.7o %s\n", id_str,
8643 got_tree_entry_get_mode(te),
8644 got_tree_entry_get_name(te));
8645 free(id_str);
8648 got_object_tree_close(tree);
8649 return err;
8652 static const struct got_error *
8653 cat_commit(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
8655 const struct got_error *err;
8656 struct got_commit_object *commit;
8657 const struct got_object_id_queue *parent_ids;
8658 struct got_object_qid *pid;
8659 char *id_str = NULL;
8660 const char *logmsg = NULL;
8661 char gmtoff[6];
8663 err = got_object_open_as_commit(&commit, repo, id);
8664 if (err)
8665 return err;
8667 err = got_object_id_str(&id_str, got_object_commit_get_tree_id(commit));
8668 if (err)
8669 goto done;
8671 fprintf(outfile, "%s%s\n", GOT_COMMIT_LABEL_TREE, id_str);
8672 parent_ids = got_object_commit_get_parent_ids(commit);
8673 fprintf(outfile, "numparents %d\n",
8674 got_object_commit_get_nparents(commit));
8675 STAILQ_FOREACH(pid, parent_ids, entry) {
8676 char *pid_str;
8677 err = got_object_id_str(&pid_str, &pid->id);
8678 if (err)
8679 goto done;
8680 fprintf(outfile, "%s%s\n", GOT_COMMIT_LABEL_PARENT, pid_str);
8681 free(pid_str);
8683 got_date_format_gmtoff(gmtoff, sizeof(gmtoff),
8684 got_object_commit_get_author_gmtoff(commit));
8685 fprintf(outfile, "%s%s %lld %s\n", GOT_COMMIT_LABEL_AUTHOR,
8686 got_object_commit_get_author(commit),
8687 (long long)got_object_commit_get_author_time(commit),
8688 gmtoff);
8690 got_date_format_gmtoff(gmtoff, sizeof(gmtoff),
8691 got_object_commit_get_committer_gmtoff(commit));
8692 fprintf(outfile, "%s%s %lld %s\n", GOT_COMMIT_LABEL_COMMITTER,
8693 got_object_commit_get_committer(commit),
8694 (long long)got_object_commit_get_committer_time(commit),
8695 gmtoff);
8697 logmsg = got_object_commit_get_logmsg_raw(commit);
8698 fprintf(outfile, "messagelen %zd\n", strlen(logmsg));
8699 fprintf(outfile, "%s", logmsg);
8700 done:
8701 free(id_str);
8702 got_object_commit_close(commit);
8703 return err;
8706 static const struct got_error *
8707 cat_tag(struct got_object_id *id, struct got_repository *repo, FILE *outfile)
8709 const struct got_error *err;
8710 struct got_tag_object *tag;
8711 char *id_str = NULL;
8712 const char *tagmsg = NULL;
8713 char gmtoff[6];
8715 err = got_object_open_as_tag(&tag, repo, id);
8716 if (err)
8717 return err;
8719 err = got_object_id_str(&id_str, got_object_tag_get_object_id(tag));
8720 if (err)
8721 goto done;
8723 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_OBJECT, id_str);
8725 switch (got_object_tag_get_object_type(tag)) {
8726 case GOT_OBJ_TYPE_BLOB:
8727 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
8728 GOT_OBJ_LABEL_BLOB);
8729 break;
8730 case GOT_OBJ_TYPE_TREE:
8731 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
8732 GOT_OBJ_LABEL_TREE);
8733 break;
8734 case GOT_OBJ_TYPE_COMMIT:
8735 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
8736 GOT_OBJ_LABEL_COMMIT);
8737 break;
8738 case GOT_OBJ_TYPE_TAG:
8739 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TYPE,
8740 GOT_OBJ_LABEL_TAG);
8741 break;
8742 default:
8743 break;
8746 fprintf(outfile, "%s%s\n", GOT_TAG_LABEL_TAG,
8747 got_object_tag_get_name(tag));
8749 got_date_format_gmtoff(gmtoff, sizeof(gmtoff),
8750 got_object_tag_get_tagger_gmtoff(tag));
8751 fprintf(outfile, "%s%s %lld %s\n", GOT_TAG_LABEL_TAGGER,
8752 got_object_tag_get_tagger(tag),
8753 (long long)got_object_tag_get_tagger_time(tag),
8754 gmtoff);
8756 tagmsg = got_object_tag_get_message(tag);
8757 fprintf(outfile, "messagelen %zd\n", strlen(tagmsg));
8758 fprintf(outfile, "%s", tagmsg);
8759 done:
8760 free(id_str);
8761 got_object_tag_close(tag);
8762 return err;
8765 static const struct got_error *
8766 cmd_cat(int argc, char *argv[])
8768 const struct got_error *error;
8769 struct got_repository *repo = NULL;
8770 struct got_worktree *worktree = NULL;
8771 char *cwd = NULL, *repo_path = NULL, *label = NULL;
8772 const char *commit_id_str = NULL;
8773 struct got_object_id *id = NULL, *commit_id = NULL;
8774 struct got_commit_object *commit = NULL;
8775 int ch, obj_type, i, force_path = 0;
8776 struct got_reflist_head refs;
8777 int *pack_fds = NULL;
8779 TAILQ_INIT(&refs);
8781 #ifndef PROFILE
8782 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
8783 NULL) == -1)
8784 err(1, "pledge");
8785 #endif
8787 while ((ch = getopt(argc, argv, "c:Pr:")) != -1) {
8788 switch (ch) {
8789 case 'c':
8790 commit_id_str = optarg;
8791 break;
8792 case 'P':
8793 force_path = 1;
8794 break;
8795 case 'r':
8796 repo_path = realpath(optarg, NULL);
8797 if (repo_path == NULL)
8798 return got_error_from_errno2("realpath",
8799 optarg);
8800 got_path_strip_trailing_slashes(repo_path);
8801 break;
8802 default:
8803 usage_cat();
8804 /* NOTREACHED */
8808 argc -= optind;
8809 argv += optind;
8811 cwd = getcwd(NULL, 0);
8812 if (cwd == NULL) {
8813 error = got_error_from_errno("getcwd");
8814 goto done;
8817 error = got_repo_pack_fds_open(&pack_fds);
8818 if (error != NULL)
8819 goto done;
8821 if (repo_path == NULL) {
8822 error = got_worktree_open(&worktree, cwd);
8823 if (error && error->code != GOT_ERR_NOT_WORKTREE)
8824 goto done;
8825 if (worktree) {
8826 repo_path = strdup(
8827 got_worktree_get_repo_path(worktree));
8828 if (repo_path == NULL) {
8829 error = got_error_from_errno("strdup");
8830 goto done;
8833 /* Release work tree lock. */
8834 got_worktree_close(worktree);
8835 worktree = NULL;
8839 if (repo_path == NULL) {
8840 repo_path = strdup(cwd);
8841 if (repo_path == NULL)
8842 return got_error_from_errno("strdup");
8845 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
8846 free(repo_path);
8847 if (error != NULL)
8848 goto done;
8850 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
8851 if (error)
8852 goto done;
8854 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
8855 if (error)
8856 goto done;
8858 if (commit_id_str == NULL)
8859 commit_id_str = GOT_REF_HEAD;
8860 error = got_repo_match_object_id(&commit_id, NULL,
8861 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
8862 if (error)
8863 goto done;
8865 error = got_object_open_as_commit(&commit, repo, commit_id);
8866 if (error)
8867 goto done;
8869 for (i = 0; i < argc; i++) {
8870 if (force_path) {
8871 error = got_object_id_by_path(&id, repo, commit,
8872 argv[i]);
8873 if (error)
8874 break;
8875 } else {
8876 error = got_repo_match_object_id(&id, &label, argv[i],
8877 GOT_OBJ_TYPE_ANY, NULL /* do not resolve tags */,
8878 repo);
8879 if (error) {
8880 if (error->code != GOT_ERR_BAD_OBJ_ID_STR &&
8881 error->code != GOT_ERR_NOT_REF)
8882 break;
8883 error = got_object_id_by_path(&id, repo,
8884 commit, argv[i]);
8885 if (error)
8886 break;
8890 error = got_object_get_type(&obj_type, repo, id);
8891 if (error)
8892 break;
8894 switch (obj_type) {
8895 case GOT_OBJ_TYPE_BLOB:
8896 error = cat_blob(id, repo, stdout);
8897 break;
8898 case GOT_OBJ_TYPE_TREE:
8899 error = cat_tree(id, repo, stdout);
8900 break;
8901 case GOT_OBJ_TYPE_COMMIT:
8902 error = cat_commit(id, repo, stdout);
8903 break;
8904 case GOT_OBJ_TYPE_TAG:
8905 error = cat_tag(id, repo, stdout);
8906 break;
8907 default:
8908 error = got_error(GOT_ERR_OBJ_TYPE);
8909 break;
8911 if (error)
8912 break;
8913 free(label);
8914 label = NULL;
8915 free(id);
8916 id = NULL;
8918 done:
8919 free(label);
8920 free(id);
8921 free(commit_id);
8922 if (commit)
8923 got_object_commit_close(commit);
8924 if (worktree)
8925 got_worktree_close(worktree);
8926 if (repo) {
8927 const struct got_error *close_err = got_repo_close(repo);
8928 if (error == NULL)
8929 error = close_err;
8931 if (pack_fds) {
8932 const struct got_error *pack_err =
8933 got_repo_pack_fds_close(pack_fds);
8934 if (error == NULL)
8935 error = pack_err;
8938 got_ref_list_free(&refs);
8939 return error;
8942 __dead static void
8943 usage_info(void)
8945 fprintf(stderr, "usage: %s info [path ...]\n",
8946 getprogname());
8947 exit(1);
8950 static const struct got_error *
8951 print_path_info(void *arg, const char *path, mode_t mode, time_t mtime,
8952 struct got_object_id *blob_id, struct got_object_id *staged_blob_id,
8953 struct got_object_id *commit_id)
8955 const struct got_error *err = NULL;
8956 char *id_str = NULL;
8957 char datebuf[128];
8958 struct tm mytm, *tm;
8959 struct got_pathlist_head *paths = arg;
8960 struct got_pathlist_entry *pe;
8963 * Clear error indication from any of the path arguments which
8964 * would cause this file index entry to be displayed.
8966 TAILQ_FOREACH(pe, paths, entry) {
8967 if (got_path_cmp(path, pe->path, strlen(path),
8968 pe->path_len) == 0 ||
8969 got_path_is_child(path, pe->path, pe->path_len))
8970 pe->data = NULL; /* no error */
8973 printf(GOT_COMMIT_SEP_STR);
8974 if (S_ISLNK(mode))
8975 printf("symlink: %s\n", path);
8976 else if (S_ISREG(mode)) {
8977 printf("file: %s\n", path);
8978 printf("mode: %o\n", mode & (S_IRWXU | S_IRWXG | S_IRWXO));
8979 } else if (S_ISDIR(mode))
8980 printf("directory: %s\n", path);
8981 else
8982 printf("something: %s\n", path);
8984 tm = localtime_r(&mtime, &mytm);
8985 if (tm == NULL)
8986 return NULL;
8987 if (strftime(datebuf, sizeof(datebuf), "%c %Z", tm) == 0)
8988 return got_error(GOT_ERR_NO_SPACE);
8989 printf("timestamp: %s\n", datebuf);
8991 if (blob_id) {
8992 err = got_object_id_str(&id_str, blob_id);
8993 if (err)
8994 return err;
8995 printf("based on blob: %s\n", id_str);
8996 free(id_str);
8999 if (staged_blob_id) {
9000 err = got_object_id_str(&id_str, staged_blob_id);
9001 if (err)
9002 return err;
9003 printf("based on staged blob: %s\n", id_str);
9004 free(id_str);
9007 if (commit_id) {
9008 err = got_object_id_str(&id_str, commit_id);
9009 if (err)
9010 return err;
9011 printf("based on commit: %s\n", id_str);
9012 free(id_str);
9015 return NULL;
9018 static const struct got_error *
9019 cmd_info(int argc, char *argv[])
9021 const struct got_error *error = NULL;
9022 struct got_worktree *worktree = NULL;
9023 char *cwd = NULL, *id_str = NULL;
9024 struct got_pathlist_head paths;
9025 char *uuidstr = NULL;
9026 int ch, show_files = 0;
9028 TAILQ_INIT(&paths);
9030 #ifndef PROFILE
9031 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
9032 NULL) == -1)
9033 err(1, "pledge");
9034 #endif
9036 while ((ch = getopt(argc, argv, "")) != -1) {
9037 switch (ch) {
9038 default:
9039 usage_info();
9040 /* NOTREACHED */
9044 argc -= optind;
9045 argv += optind;
9047 cwd = getcwd(NULL, 0);
9048 if (cwd == NULL) {
9049 error = got_error_from_errno("getcwd");
9050 goto done;
9053 error = got_worktree_open(&worktree, cwd);
9054 if (error) {
9055 if (error->code == GOT_ERR_NOT_WORKTREE)
9056 error = wrap_not_worktree_error(error, "info", cwd);
9057 goto done;
9060 #ifndef PROFILE
9061 /* Remove "wpath cpath proc exec sendfd" promises. */
9062 if (pledge("stdio rpath flock unveil", NULL) == -1)
9063 err(1, "pledge");
9064 #endif
9065 error = apply_unveil(NULL, 0, got_worktree_get_root_path(worktree));
9066 if (error)
9067 goto done;
9069 if (argc >= 1) {
9070 error = get_worktree_paths_from_argv(&paths, argc, argv,
9071 worktree);
9072 if (error)
9073 goto done;
9074 show_files = 1;
9077 error = got_object_id_str(&id_str,
9078 got_worktree_get_base_commit_id(worktree));
9079 if (error)
9080 goto done;
9082 error = got_worktree_get_uuid(&uuidstr, worktree);
9083 if (error)
9084 goto done;
9086 printf("work tree: %s\n", got_worktree_get_root_path(worktree));
9087 printf("work tree base commit: %s\n", id_str);
9088 printf("work tree path prefix: %s\n",
9089 got_worktree_get_path_prefix(worktree));
9090 printf("work tree branch reference: %s\n",
9091 got_worktree_get_head_ref_name(worktree));
9092 printf("work tree UUID: %s\n", uuidstr);
9093 printf("repository: %s\n", got_worktree_get_repo_path(worktree));
9095 if (show_files) {
9096 struct got_pathlist_entry *pe;
9097 TAILQ_FOREACH(pe, &paths, entry) {
9098 if (pe->path_len == 0)
9099 continue;
9101 * Assume this path will fail. This will be corrected
9102 * in print_path_info() in case the path does suceeed.
9104 pe->data = (void *)got_error(GOT_ERR_BAD_PATH);
9106 error = got_worktree_path_info(worktree, &paths,
9107 print_path_info, &paths, check_cancelled, NULL);
9108 if (error)
9109 goto done;
9110 TAILQ_FOREACH(pe, &paths, entry) {
9111 if (pe->data != NULL) {
9112 const struct got_error *perr;
9114 perr = pe->data;
9115 error = got_error_fmt(perr->code, "%s",
9116 pe->path);
9117 break;
9121 done:
9122 if (worktree)
9123 got_worktree_close(worktree);
9124 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
9125 free(cwd);
9126 free(id_str);
9127 free(uuidstr);
9128 return error;