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 *
6 * Permission to use, copy, modify, and distribute this software for any
7 * purpose with or without fee is hereby granted, provided that the above
8 * copyright notice and this permission notice appear in all copies.
9 *
10 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
11 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
12 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
13 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
14 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
15 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
16 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
17 */
19 #include "got_compat.h"
21 #include <sys/queue.h>
22 #include <sys/time.h>
23 #include <sys/types.h>
24 #include <sys/stat.h>
25 #include <sys/wait.h>
27 #include <err.h>
28 #include <errno.h>
29 #include <fcntl.h>
30 #include <limits.h>
31 #include <locale.h>
32 #include <ctype.h>
33 #include <signal.h>
34 #include <stdio.h>
35 #include <stdlib.h>
36 #include <string.h>
37 #include <unistd.h>
38 #include <libgen.h>
39 #include <time.h>
40 #include <paths.h>
41 #include <regex.h>
42 #include <getopt.h>
44 #include "got_version.h"
45 #include "got_error.h"
46 #include "got_object.h"
47 #include "got_reference.h"
48 #include "got_repository.h"
49 #include "got_path.h"
50 #include "got_cancel.h"
51 #include "got_worktree.h"
52 #include "got_diff.h"
53 #include "got_commit_graph.h"
54 #include "got_fetch.h"
55 #include "got_send.h"
56 #include "got_blame.h"
57 #include "got_privsep.h"
58 #include "got_opentemp.h"
59 #include "got_gotconfig.h"
60 #include "got_dial.h"
61 #include "got_patch.h"
62 #include "got_sigs.h"
63 #include "got_date.h"
64 #include "got_keyword.h"
66 #ifndef nitems
67 #define nitems(_a) (sizeof((_a)) / sizeof((_a)[0]))
68 #endif
70 #ifndef GOT_DEFAULT_EDITOR
71 #define GOT_DEFAULT_EDITOR "/usr/bin/vi"
72 #endif
74 static volatile sig_atomic_t sigint_received;
75 static volatile sig_atomic_t sigpipe_received;
77 static void
78 catch_sigint(int signo)
79 {
80 sigint_received = 1;
81 }
83 static void
84 catch_sigpipe(int signo)
85 {
86 sigpipe_received = 1;
87 }
90 struct got_cmd {
91 const char *cmd_name;
92 const struct got_error *(*cmd_main)(int, char *[]);
93 void (*cmd_usage)(void);
94 const char *cmd_alias;
95 };
97 __dead static void usage(int, int);
98 __dead static void usage_init(void);
99 __dead static void usage_import(void);
100 __dead static void usage_clone(void);
101 __dead static void usage_fetch(void);
102 __dead static void usage_checkout(void);
103 __dead static void usage_update(void);
104 __dead static void usage_log(void);
105 __dead static void usage_diff(void);
106 __dead static void usage_blame(void);
107 __dead static void usage_tree(void);
108 __dead static void usage_status(void);
109 __dead static void usage_ref(void);
110 __dead static void usage_branch(void);
111 __dead static void usage_tag(void);
112 __dead static void usage_add(void);
113 __dead static void usage_remove(void);
114 __dead static void usage_patch(void);
115 __dead static void usage_revert(void);
116 __dead static void usage_commit(void);
117 __dead static void usage_send(void);
118 __dead static void usage_cherrypick(void);
119 __dead static void usage_backout(void);
120 __dead static void usage_rebase(void);
121 __dead static void usage_histedit(void);
122 __dead static void usage_integrate(void);
123 __dead static void usage_merge(void);
124 __dead static void usage_stage(void);
125 __dead static void usage_unstage(void);
126 __dead static void usage_cat(void);
127 __dead static void usage_info(void);
129 static const struct got_error* cmd_init(int, char *[]);
130 static const struct got_error* cmd_import(int, char *[]);
131 static const struct got_error* cmd_clone(int, char *[]);
132 static const struct got_error* cmd_fetch(int, char *[]);
133 static const struct got_error* cmd_checkout(int, char *[]);
134 static const struct got_error* cmd_update(int, char *[]);
135 static const struct got_error* cmd_log(int, char *[]);
136 static const struct got_error* cmd_diff(int, char *[]);
137 static const struct got_error* cmd_blame(int, char *[]);
138 static const struct got_error* cmd_tree(int, char *[]);
139 static const struct got_error* cmd_status(int, char *[]);
140 static const struct got_error* cmd_ref(int, char *[]);
141 static const struct got_error* cmd_branch(int, char *[]);
142 static const struct got_error* cmd_tag(int, char *[]);
143 static const struct got_error* cmd_add(int, char *[]);
144 static const struct got_error* cmd_remove(int, char *[]);
145 static const struct got_error* cmd_patch(int, char *[]);
146 static const struct got_error* cmd_revert(int, char *[]);
147 static const struct got_error* cmd_commit(int, char *[]);
148 static const struct got_error* cmd_send(int, char *[]);
149 static const struct got_error* cmd_cherrypick(int, char *[]);
150 static const struct got_error* cmd_backout(int, char *[]);
151 static const struct got_error* cmd_rebase(int, char *[]);
152 static const struct got_error* cmd_histedit(int, char *[]);
153 static const struct got_error* cmd_integrate(int, char *[]);
154 static const struct got_error* cmd_merge(int, char *[]);
155 static const struct got_error* cmd_stage(int, char *[]);
156 static const struct got_error* cmd_unstage(int, char *[]);
157 static const struct got_error* cmd_cat(int, char *[]);
158 static const struct got_error* cmd_info(int, char *[]);
160 static const struct got_cmd got_commands[] = {
161 { "init", cmd_init, usage_init, "" },
162 { "import", cmd_import, usage_import, "im" },
163 { "clone", cmd_clone, usage_clone, "cl" },
164 { "fetch", cmd_fetch, usage_fetch, "fe" },
165 { "checkout", cmd_checkout, usage_checkout, "co" },
166 { "update", cmd_update, usage_update, "up" },
167 { "log", cmd_log, usage_log, "" },
168 { "diff", cmd_diff, usage_diff, "di" },
169 { "blame", cmd_blame, usage_blame, "bl" },
170 { "tree", cmd_tree, usage_tree, "tr" },
171 { "status", cmd_status, usage_status, "st" },
172 { "ref", cmd_ref, usage_ref, "" },
173 { "branch", cmd_branch, usage_branch, "br" },
174 { "tag", cmd_tag, usage_tag, "" },
175 { "add", cmd_add, usage_add, "" },
176 { "remove", cmd_remove, usage_remove, "rm" },
177 { "patch", cmd_patch, usage_patch, "pa" },
178 { "revert", cmd_revert, usage_revert, "rv" },
179 { "commit", cmd_commit, usage_commit, "ci" },
180 { "send", cmd_send, usage_send, "se" },
181 { "cherrypick", cmd_cherrypick, usage_cherrypick, "cy" },
182 { "backout", cmd_backout, usage_backout, "bo" },
183 { "rebase", cmd_rebase, usage_rebase, "rb" },
184 { "histedit", cmd_histedit, usage_histedit, "he" },
185 { "integrate", cmd_integrate, usage_integrate,"ig" },
186 { "merge", cmd_merge, usage_merge, "mg" },
187 { "stage", cmd_stage, usage_stage, "sg" },
188 { "unstage", cmd_unstage, usage_unstage, "ug" },
189 { "cat", cmd_cat, usage_cat, "" },
190 { "info", cmd_info, usage_info, "" },
191 };
193 static void
194 list_commands(FILE *fp)
196 size_t i;
198 fprintf(fp, "commands:");
199 for (i = 0; i < nitems(got_commands); i++) {
200 const struct got_cmd *cmd = &got_commands[i];
201 fprintf(fp, " %s", cmd->cmd_name);
203 fputc('\n', fp);
206 __dead static void
207 option_conflict(char a, char b)
209 errx(1, "-%c and -%c options are mutually exclusive", a, b);
212 int
213 main(int argc, char *argv[])
215 const struct got_cmd *cmd;
216 size_t i;
217 int ch;
218 int hflag = 0, Vflag = 0;
219 static const struct option longopts[] = {
220 { "version", no_argument, NULL, 'V' },
221 { NULL, 0, NULL, 0 }
222 };
224 setlocale(LC_CTYPE, "");
226 while ((ch = getopt_long(argc, argv, "+hV", longopts, NULL)) != -1) {
227 switch (ch) {
228 case 'h':
229 hflag = 1;
230 break;
231 case 'V':
232 Vflag = 1;
233 break;
234 default:
235 usage(hflag, 1);
236 /* NOTREACHED */
240 argc -= optind;
241 argv += optind;
242 optind = 1;
243 optreset = 1;
245 if (Vflag) {
246 got_version_print_str();
247 return 0;
250 if (argc <= 0)
251 usage(hflag, hflag ? 0 : 1);
253 signal(SIGINT, catch_sigint);
254 signal(SIGPIPE, catch_sigpipe);
256 for (i = 0; i < nitems(got_commands); i++) {
257 const struct got_error *error;
259 cmd = &got_commands[i];
261 if (strcmp(cmd->cmd_name, argv[0]) != 0 &&
262 strcmp(cmd->cmd_alias, argv[0]) != 0)
263 continue;
265 if (hflag)
266 cmd->cmd_usage();
268 error = cmd->cmd_main(argc, argv);
269 if (error && error->code != GOT_ERR_CANCELLED &&
270 error->code != GOT_ERR_PRIVSEP_EXIT &&
271 !(sigpipe_received &&
272 error->code == GOT_ERR_ERRNO && errno == EPIPE) &&
273 !(sigint_received &&
274 error->code == GOT_ERR_ERRNO && errno == EINTR)) {
275 fflush(stdout);
276 fprintf(stderr, "%s: %s\n", getprogname(), error->msg);
277 return 1;
280 return 0;
283 fprintf(stderr, "%s: unknown command '%s'\n", getprogname(), argv[0]);
284 list_commands(stderr);
285 return 1;
288 __dead static void
289 usage(int hflag, int status)
291 FILE *fp = (status == 0) ? stdout : stderr;
293 fprintf(fp, "usage: %s [-hV] command [arg ...]\n",
294 getprogname());
295 if (hflag)
296 list_commands(fp);
297 exit(status);
300 static const struct got_error *
301 get_editor(char **abspath)
303 const struct got_error *err = NULL;
304 const char *editor;
306 *abspath = NULL;
308 editor = getenv("VISUAL");
309 if (editor == NULL)
310 editor = getenv("EDITOR");
312 if (editor) {
313 err = got_path_find_prog(abspath, editor);
314 if (err)
315 return err;
318 if (*abspath == NULL) {
319 *abspath = strdup(GOT_DEFAULT_EDITOR);
320 if (*abspath == NULL)
321 return got_error_from_errno("strdup");
324 return NULL;
327 static const struct got_error *
328 apply_unveil(const char *repo_path, int repo_read_only,
329 const char *worktree_path)
331 const struct got_error *err;
333 #ifdef PROFILE
334 if (unveil("gmon.out", "rwc") != 0)
335 return got_error_from_errno2("unveil", "gmon.out");
336 #endif
337 if (repo_path && unveil(repo_path, repo_read_only ? "r" : "rwc") != 0)
338 return got_error_from_errno2("unveil", repo_path);
340 if (worktree_path && unveil(worktree_path, "rwc") != 0)
341 return got_error_from_errno2("unveil", worktree_path);
343 if (unveil(GOT_TMPDIR_STR, "rwc") != 0)
344 return got_error_from_errno2("unveil", GOT_TMPDIR_STR);
346 err = got_privsep_unveil_exec_helpers();
347 if (err != NULL)
348 return err;
350 if (unveil(NULL, NULL) != 0)
351 return got_error_from_errno("unveil");
353 return NULL;
356 __dead static void
357 usage_init(void)
359 fprintf(stderr, "usage: %s init [-b branch] repository-path\n",
360 getprogname());
361 exit(1);
364 static const struct got_error *
365 cmd_init(int argc, char *argv[])
367 const struct got_error *error = NULL;
368 const char *head_name = NULL;
369 char *repo_path = NULL;
370 int ch;
372 while ((ch = getopt(argc, argv, "b:")) != -1) {
373 switch (ch) {
374 case 'b':
375 head_name = optarg;
376 break;
377 default:
378 usage_init();
379 /* NOTREACHED */
383 argc -= optind;
384 argv += optind;
386 #ifndef PROFILE
387 if (pledge("stdio rpath wpath cpath unveil", NULL) == -1)
388 err(1, "pledge");
389 #endif
390 if (argc != 1)
391 usage_init();
393 repo_path = strdup(argv[0]);
394 if (repo_path == NULL)
395 return got_error_from_errno("strdup");
397 got_path_strip_trailing_slashes(repo_path);
399 error = got_path_mkdir(repo_path);
400 if (error &&
401 !(error->code == GOT_ERR_ERRNO && errno == EEXIST))
402 goto done;
404 error = apply_unveil(repo_path, 0, NULL);
405 if (error)
406 goto done;
408 error = got_repo_init(repo_path, head_name);
409 done:
410 free(repo_path);
411 return error;
414 __dead static void
415 usage_import(void)
417 fprintf(stderr, "usage: %s import [-b branch] [-I pattern] [-m message] "
418 "[-r repository-path] directory\n", getprogname());
419 exit(1);
422 static int
423 spawn_editor(const char *editor, const char *file)
425 pid_t pid;
426 sig_t sighup, sigint, sigquit;
427 int st = -1;
429 sighup = signal(SIGHUP, SIG_IGN);
430 sigint = signal(SIGINT, SIG_IGN);
431 sigquit = signal(SIGQUIT, SIG_IGN);
433 switch (pid = fork()) {
434 case -1:
435 goto doneediting;
436 case 0:
437 execl(editor, editor, file, (char *)NULL);
438 _exit(127);
441 while (waitpid(pid, &st, 0) == -1)
442 if (errno != EINTR)
443 break;
445 doneediting:
446 (void)signal(SIGHUP, sighup);
447 (void)signal(SIGINT, sigint);
448 (void)signal(SIGQUIT, sigquit);
450 if (!WIFEXITED(st)) {
451 errno = EINTR;
452 return -1;
455 return WEXITSTATUS(st);
458 static const struct got_error *
459 read_logmsg(char **logmsg, size_t *len, FILE *fp, size_t filesize)
461 const struct got_error *err = NULL;
462 char *line = NULL;
463 size_t linesize = 0;
465 *logmsg = NULL;
466 *len = 0;
468 if (fseeko(fp, 0L, SEEK_SET) == -1)
469 return got_error_from_errno("fseeko");
471 *logmsg = malloc(filesize + 1);
472 if (*logmsg == NULL)
473 return got_error_from_errno("malloc");
474 (*logmsg)[0] = '\0';
476 while (getline(&line, &linesize, fp) != -1) {
477 if (line[0] == '#' || (*len == 0 && line[0] == '\n'))
478 continue; /* remove comments and leading empty lines */
479 *len = strlcat(*logmsg, line, filesize + 1);
480 if (*len >= filesize + 1) {
481 err = got_error(GOT_ERR_NO_SPACE);
482 goto done;
485 if (ferror(fp)) {
486 err = got_ferror(fp, GOT_ERR_IO);
487 goto done;
490 while (*len > 0 && (*logmsg)[*len - 1] == '\n') {
491 (*logmsg)[*len - 1] = '\0';
492 (*len)--;
494 done:
495 free(line);
496 if (err) {
497 free(*logmsg);
498 *logmsg = NULL;
499 *len = 0;
501 return err;
504 static const struct got_error *
505 edit_logmsg(char **logmsg, const char *editor, const char *logmsg_path,
506 const char *initial_content, size_t initial_content_len,
507 int require_modification)
509 const struct got_error *err = NULL;
510 struct stat st, st2;
511 FILE *fp = NULL;
512 size_t logmsg_len;
514 *logmsg = NULL;
516 if (stat(logmsg_path, &st) == -1)
517 return got_error_from_errno2("stat", logmsg_path);
519 if (spawn_editor(editor, logmsg_path) == -1)
520 return got_error_from_errno("failed spawning editor");
522 if (require_modification) {
523 struct timespec timeout;
525 timeout.tv_sec = 0;
526 timeout.tv_nsec = 1;
527 nanosleep(&timeout, NULL);
530 if (stat(logmsg_path, &st2) == -1)
531 return got_error_from_errno2("stat", logmsg_path);
533 if (require_modification && st.st_size == st2.st_size &&
534 timespeccmp(&st.st_mtim, &st2.st_mtim, ==))
535 return got_error_msg(GOT_ERR_COMMIT_MSG_EMPTY,
536 "no changes made to commit message, aborting");
538 fp = fopen(logmsg_path, "re");
539 if (fp == NULL) {
540 err = got_error_from_errno("fopen");
541 goto done;
544 /* strip comments and leading/trailing newlines */
545 err = read_logmsg(logmsg, &logmsg_len, fp, st2.st_size);
546 if (err)
547 goto done;
548 if (logmsg_len == 0) {
549 err = got_error_msg(GOT_ERR_COMMIT_MSG_EMPTY,
550 "commit message cannot be empty, aborting");
551 goto done;
553 done:
554 if (fp && fclose(fp) == EOF && err == NULL)
555 err = got_error_from_errno("fclose");
556 if (err) {
557 free(*logmsg);
558 *logmsg = NULL;
560 return err;
563 static const struct got_error *
564 collect_import_msg(char **logmsg, char **logmsg_path, const char *editor,
565 const char *path_dir, const char *branch_name)
567 char *initial_content = NULL;
568 const struct got_error *err = NULL;
569 int initial_content_len;
570 int fd = -1;
572 initial_content_len = asprintf(&initial_content,
573 "\n# %s to be imported to branch %s\n", path_dir,
574 branch_name);
575 if (initial_content_len == -1)
576 return got_error_from_errno("asprintf");
578 err = got_opentemp_named_fd(logmsg_path, &fd,
579 GOT_TMPDIR_STR "/got-importmsg", "");
580 if (err)
581 goto done;
583 if (write(fd, initial_content, initial_content_len) == -1) {
584 err = got_error_from_errno2("write", *logmsg_path);
585 goto done;
587 if (close(fd) == -1) {
588 err = got_error_from_errno2("close", *logmsg_path);
589 goto done;
591 fd = -1;
593 err = edit_logmsg(logmsg, editor, *logmsg_path, initial_content,
594 initial_content_len, 1);
595 done:
596 if (fd != -1 && close(fd) == -1 && err == NULL)
597 err = got_error_from_errno2("close", *logmsg_path);
598 free(initial_content);
599 if (err) {
600 free(*logmsg_path);
601 *logmsg_path = NULL;
603 return err;
606 static const struct got_error *
607 import_progress(void *arg, const char *path)
609 printf("A %s\n", path);
610 return NULL;
613 static const struct got_error *
614 valid_author(const char *author)
616 const char *email = author;
618 /*
619 * Git' expects the author (or committer) to be in the form
620 * "name <email>", which are mostly free form (see the
621 * "committer" description in git-fast-import(1)). We're only
622 * doing this to avoid git's object parser breaking on commits
623 * we create.
624 */
626 while (*author && *author != '\n' && *author != '<' && *author != '>')
627 author++;
628 if (author != email && *author == '<' && *(author - 1) != ' ')
629 return got_error_fmt(GOT_ERR_COMMIT_BAD_AUTHOR, "%s: space "
630 "between author name and email required", email);
631 if (*author++ != '<')
632 return got_error_fmt(GOT_ERR_COMMIT_NO_EMAIL, "%s", email);
633 while (*author && *author != '\n' && *author != '<' && *author != '>')
634 author++;
635 if (strcmp(author, ">") != 0)
636 return got_error_fmt(GOT_ERR_COMMIT_NO_EMAIL, "%s", email);
637 return NULL;
640 static const struct got_error *
641 get_author(char **author, struct got_repository *repo,
642 struct got_worktree *worktree)
644 const struct got_error *err = NULL;
645 const char *got_author = NULL, *name, *email;
646 const struct got_gotconfig *worktree_conf = NULL, *repo_conf = NULL;
648 *author = NULL;
650 if (worktree)
651 worktree_conf = got_worktree_get_gotconfig(worktree);
652 repo_conf = got_repo_get_gotconfig(repo);
654 /*
655 * Priority of potential author information sources, from most
656 * significant to least significant:
657 * 1) work tree's .got/got.conf file
658 * 2) repository's got.conf file
659 * 3) repository's git config file
660 * 4) environment variables
661 * 5) global git config files (in user's home directory or /etc)
662 */
664 if (worktree_conf)
665 got_author = got_gotconfig_get_author(worktree_conf);
666 if (got_author == NULL)
667 got_author = got_gotconfig_get_author(repo_conf);
668 if (got_author == NULL) {
669 name = got_repo_get_gitconfig_author_name(repo);
670 email = got_repo_get_gitconfig_author_email(repo);
671 if (name && email) {
672 if (asprintf(author, "%s <%s>", name, email) == -1)
673 return got_error_from_errno("asprintf");
674 return NULL;
677 got_author = getenv("GOT_AUTHOR");
678 if (got_author == NULL) {
679 name = got_repo_get_global_gitconfig_author_name(repo);
680 email = got_repo_get_global_gitconfig_author_email(
681 repo);
682 if (name && email) {
683 if (asprintf(author, "%s <%s>", name, email)
684 == -1)
685 return got_error_from_errno("asprintf");
686 return NULL;
688 /* TODO: Look up user in password database? */
689 return got_error(GOT_ERR_COMMIT_NO_AUTHOR);
693 *author = strdup(got_author);
694 if (*author == NULL)
695 return got_error_from_errno("strdup");
697 err = valid_author(*author);
698 if (err) {
699 free(*author);
700 *author = NULL;
702 return err;
705 static const struct got_error *
706 get_allowed_signers(char **allowed_signers, struct got_repository *repo,
707 struct got_worktree *worktree)
709 const char *got_allowed_signers = NULL;
710 const struct got_gotconfig *worktree_conf = NULL, *repo_conf = NULL;
712 *allowed_signers = NULL;
714 if (worktree)
715 worktree_conf = got_worktree_get_gotconfig(worktree);
716 repo_conf = got_repo_get_gotconfig(repo);
718 /*
719 * Priority of potential author information sources, from most
720 * significant to least significant:
721 * 1) work tree's .got/got.conf file
722 * 2) repository's got.conf file
723 */
725 if (worktree_conf)
726 got_allowed_signers = got_gotconfig_get_allowed_signers_file(
727 worktree_conf);
728 if (got_allowed_signers == NULL)
729 got_allowed_signers = got_gotconfig_get_allowed_signers_file(
730 repo_conf);
732 if (got_allowed_signers) {
733 *allowed_signers = strdup(got_allowed_signers);
734 if (*allowed_signers == NULL)
735 return got_error_from_errno("strdup");
737 return NULL;
740 static const struct got_error *
741 get_revoked_signers(char **revoked_signers, struct got_repository *repo,
742 struct got_worktree *worktree)
744 const char *got_revoked_signers = NULL;
745 const struct got_gotconfig *worktree_conf = NULL, *repo_conf = NULL;
747 *revoked_signers = NULL;
749 if (worktree)
750 worktree_conf = got_worktree_get_gotconfig(worktree);
751 repo_conf = got_repo_get_gotconfig(repo);
753 /*
754 * Priority of potential author information sources, from most
755 * significant to least significant:
756 * 1) work tree's .got/got.conf file
757 * 2) repository's got.conf file
758 */
760 if (worktree_conf)
761 got_revoked_signers = got_gotconfig_get_revoked_signers_file(
762 worktree_conf);
763 if (got_revoked_signers == NULL)
764 got_revoked_signers = got_gotconfig_get_revoked_signers_file(
765 repo_conf);
767 if (got_revoked_signers) {
768 *revoked_signers = strdup(got_revoked_signers);
769 if (*revoked_signers == NULL)
770 return got_error_from_errno("strdup");
772 return NULL;
775 static const char *
776 get_signer_id(struct got_repository *repo, struct got_worktree *worktree)
778 const char *got_signer_id = NULL;
779 const struct got_gotconfig *worktree_conf = NULL, *repo_conf = NULL;
781 if (worktree)
782 worktree_conf = got_worktree_get_gotconfig(worktree);
783 repo_conf = got_repo_get_gotconfig(repo);
785 /*
786 * Priority of potential author information sources, from most
787 * significant to least significant:
788 * 1) work tree's .got/got.conf file
789 * 2) repository's got.conf file
790 */
792 if (worktree_conf)
793 got_signer_id = got_gotconfig_get_signer_id(worktree_conf);
794 if (got_signer_id == NULL)
795 got_signer_id = got_gotconfig_get_signer_id(repo_conf);
797 return got_signer_id;
800 static const struct got_error *
801 get_gitconfig_path(char **gitconfig_path)
803 const char *homedir = getenv("HOME");
805 *gitconfig_path = NULL;
806 if (homedir) {
807 if (asprintf(gitconfig_path, "%s/.gitconfig", homedir) == -1)
808 return got_error_from_errno("asprintf");
811 return NULL;
814 static const struct got_error *
815 cmd_import(int argc, char *argv[])
817 const struct got_error *error = NULL;
818 char *path_dir = NULL, *repo_path = NULL, *logmsg = NULL;
819 char *gitconfig_path = NULL, *editor = NULL, *author = NULL;
820 const char *branch_name = NULL;
821 char *id_str = NULL, *logmsg_path = NULL;
822 char refname[PATH_MAX] = "refs/heads/";
823 struct got_repository *repo = NULL;
824 struct got_reference *branch_ref = NULL, *head_ref = NULL;
825 struct got_object_id *new_commit_id = NULL;
826 int ch, n = 0;
827 struct got_pathlist_head ignores;
828 struct got_pathlist_entry *pe;
829 int preserve_logmsg = 0;
830 int *pack_fds = NULL;
832 TAILQ_INIT(&ignores);
834 #ifndef PROFILE
835 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
836 "unveil",
837 NULL) == -1)
838 err(1, "pledge");
839 #endif
841 while ((ch = getopt(argc, argv, "b:I:m:r:")) != -1) {
842 switch (ch) {
843 case 'b':
844 branch_name = optarg;
845 break;
846 case 'I':
847 if (optarg[0] == '\0')
848 break;
849 error = got_pathlist_insert(&pe, &ignores, optarg,
850 NULL);
851 if (error)
852 goto done;
853 break;
854 case 'm':
855 logmsg = strdup(optarg);
856 if (logmsg == NULL) {
857 error = got_error_from_errno("strdup");
858 goto done;
860 break;
861 case 'r':
862 repo_path = realpath(optarg, NULL);
863 if (repo_path == NULL) {
864 error = got_error_from_errno2("realpath",
865 optarg);
866 goto done;
868 break;
869 default:
870 usage_import();
871 /* NOTREACHED */
875 argc -= optind;
876 argv += optind;
878 if (argc != 1)
879 usage_import();
881 if (repo_path == NULL) {
882 repo_path = getcwd(NULL, 0);
883 if (repo_path == NULL)
884 return got_error_from_errno("getcwd");
886 got_path_strip_trailing_slashes(repo_path);
887 error = get_gitconfig_path(&gitconfig_path);
888 if (error)
889 goto done;
890 error = got_repo_pack_fds_open(&pack_fds);
891 if (error != NULL)
892 goto done;
893 error = got_repo_open(&repo, repo_path, gitconfig_path, pack_fds);
894 if (error)
895 goto done;
897 path_dir = realpath(argv[0], NULL);
898 if (path_dir == NULL) {
899 error = got_error_from_errno2("realpath", argv[0]);
900 goto done;
902 got_path_strip_trailing_slashes(path_dir);
904 error = get_editor(&editor);
905 if (error)
906 goto done;
908 if (unveil(path_dir, "r") != 0) {
909 error = got_error_from_errno2("unveil", path_dir);
910 goto done;
912 if (unveil(editor, "x") != 0) {
913 error = got_error_from_errno2("unveil", editor);
914 goto done;
916 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
917 if (error)
918 goto done;
920 error = get_author(&author, repo, NULL);
921 if (error)
922 return error;
924 /*
925 * Don't let the user create a branch name with a leading '-'.
926 * While technically a valid reference name, this case is usually
927 * an unintended typo.
928 */
929 if (branch_name && branch_name[0] == '-')
930 return got_error_path(branch_name, GOT_ERR_REF_NAME_MINUS);
932 error = got_ref_open(&head_ref, repo, GOT_REF_HEAD, 0);
933 if (error && error->code != GOT_ERR_NOT_REF)
934 goto done;
936 if (branch_name)
937 n = strlcat(refname, branch_name, sizeof(refname));
938 else if (head_ref && got_ref_is_symbolic(head_ref))
939 n = strlcpy(refname, got_ref_get_symref_target(head_ref),
940 sizeof(refname));
941 else
942 n = strlcat(refname, "main", sizeof(refname));
943 if (n >= sizeof(refname)) {
944 error = got_error(GOT_ERR_NO_SPACE);
945 goto done;
948 error = got_ref_open(&branch_ref, repo, refname, 0);
949 if (error) {
950 if (error->code != GOT_ERR_NOT_REF)
951 goto done;
952 } else {
953 error = got_error_msg(GOT_ERR_BRANCH_EXISTS,
954 "import target branch already exists");
955 goto done;
958 if (logmsg == NULL || *logmsg == '\0') {
959 free(logmsg);
960 error = collect_import_msg(&logmsg, &logmsg_path, editor,
961 path_dir, refname);
962 if (error) {
963 if (error->code != GOT_ERR_COMMIT_MSG_EMPTY &&
964 logmsg_path != NULL)
965 preserve_logmsg = 1;
966 goto done;
970 error = got_repo_import(&new_commit_id, path_dir, logmsg,
971 author, &ignores, repo, import_progress, NULL);
972 if (error) {
973 if (logmsg_path)
974 preserve_logmsg = 1;
975 goto done;
978 error = got_ref_alloc(&branch_ref, refname, new_commit_id);
979 if (error) {
980 if (logmsg_path)
981 preserve_logmsg = 1;
982 goto done;
985 error = got_ref_write(branch_ref, repo);
986 if (error) {
987 if (logmsg_path)
988 preserve_logmsg = 1;
989 goto done;
992 error = got_object_id_str(&id_str, new_commit_id);
993 if (error) {
994 if (logmsg_path)
995 preserve_logmsg = 1;
996 goto done;
999 error = got_ref_open(&head_ref, repo, GOT_REF_HEAD, 0);
1000 if (error) {
1001 if (error->code != GOT_ERR_NOT_REF) {
1002 if (logmsg_path)
1003 preserve_logmsg = 1;
1004 goto done;
1007 error = got_ref_alloc_symref(&head_ref, GOT_REF_HEAD,
1008 branch_ref);
1009 if (error) {
1010 if (logmsg_path)
1011 preserve_logmsg = 1;
1012 goto done;
1015 error = got_ref_write(head_ref, repo);
1016 if (error) {
1017 if (logmsg_path)
1018 preserve_logmsg = 1;
1019 goto done;
1023 printf("Created branch %s with commit %s\n",
1024 got_ref_get_name(branch_ref), id_str);
1025 done:
1026 if (pack_fds) {
1027 const struct got_error *pack_err =
1028 got_repo_pack_fds_close(pack_fds);
1029 if (error == NULL)
1030 error = pack_err;
1032 if (repo) {
1033 const struct got_error *close_err = got_repo_close(repo);
1034 if (error == NULL)
1035 error = close_err;
1037 if (preserve_logmsg) {
1038 fprintf(stderr, "%s: log message preserved in %s\n",
1039 getprogname(), logmsg_path);
1040 } else if (logmsg_path && unlink(logmsg_path) == -1 && error == NULL)
1041 error = got_error_from_errno2("unlink", logmsg_path);
1042 free(logmsg);
1043 free(logmsg_path);
1044 free(repo_path);
1045 free(editor);
1046 free(new_commit_id);
1047 free(id_str);
1048 free(author);
1049 free(gitconfig_path);
1050 if (branch_ref)
1051 got_ref_close(branch_ref);
1052 if (head_ref)
1053 got_ref_close(head_ref);
1054 return error;
1057 __dead static void
1058 usage_clone(void)
1060 fprintf(stderr, "usage: %s clone [-almqv] [-b branch] [-R reference] "
1061 "repository-URL [directory]\n", getprogname());
1062 exit(1);
1065 struct got_fetch_progress_arg {
1066 char last_scaled_size[FMT_SCALED_STRSIZE];
1067 int last_p_indexed;
1068 int last_p_resolved;
1069 int verbosity;
1071 struct got_repository *repo;
1073 int create_configs;
1074 int configs_created;
1075 struct {
1076 struct got_pathlist_head *symrefs;
1077 struct got_pathlist_head *wanted_branches;
1078 struct got_pathlist_head *wanted_refs;
1079 const char *proto;
1080 const char *host;
1081 const char *port;
1082 const char *remote_repo_path;
1083 const char *git_url;
1084 int fetch_all_branches;
1085 int mirror_references;
1086 } config_info;
1089 /* XXX forward declaration */
1090 static const struct got_error *
1091 create_config_files(const char *proto, const char *host, const char *port,
1092 const char *remote_repo_path, const char *git_url, int fetch_all_branches,
1093 int mirror_references, struct got_pathlist_head *symrefs,
1094 struct got_pathlist_head *wanted_branches,
1095 struct got_pathlist_head *wanted_refs, struct got_repository *repo);
1097 static const struct got_error *
1098 fetch_progress(void *arg, const char *message, off_t packfile_size,
1099 int nobj_total, int nobj_indexed, int nobj_loose, int nobj_resolved)
1101 const struct got_error *err = NULL;
1102 struct got_fetch_progress_arg *a = arg;
1103 char scaled_size[FMT_SCALED_STRSIZE];
1104 int p_indexed, p_resolved;
1105 int print_size = 0, print_indexed = 0, print_resolved = 0;
1108 * In order to allow a failed clone to be resumed with 'got fetch'
1109 * we try to create configuration files as soon as possible.
1110 * Once the server has sent information about its default branch
1111 * we have all required information.
1113 if (a->create_configs && !a->configs_created &&
1114 !TAILQ_EMPTY(a->config_info.symrefs)) {
1115 err = create_config_files(a->config_info.proto,
1116 a->config_info.host, a->config_info.port,
1117 a->config_info.remote_repo_path,
1118 a->config_info.git_url,
1119 a->config_info.fetch_all_branches,
1120 a->config_info.mirror_references,
1121 a->config_info.symrefs,
1122 a->config_info.wanted_branches,
1123 a->config_info.wanted_refs, a->repo);
1124 if (err)
1125 return err;
1126 a->configs_created = 1;
1129 if (a->verbosity < 0)
1130 return NULL;
1132 if (message && message[0] != '\0') {
1133 printf("\rserver: %s", message);
1134 fflush(stdout);
1135 return NULL;
1138 if (packfile_size > 0 || nobj_indexed > 0) {
1139 if (fmt_scaled(packfile_size, scaled_size) == 0 &&
1140 (a->last_scaled_size[0] == '\0' ||
1141 strcmp(scaled_size, a->last_scaled_size)) != 0) {
1142 print_size = 1;
1143 if (strlcpy(a->last_scaled_size, scaled_size,
1144 FMT_SCALED_STRSIZE) >= FMT_SCALED_STRSIZE)
1145 return got_error(GOT_ERR_NO_SPACE);
1147 if (nobj_indexed > 0) {
1148 p_indexed = (nobj_indexed * 100) / nobj_total;
1149 if (p_indexed != a->last_p_indexed) {
1150 a->last_p_indexed = p_indexed;
1151 print_indexed = 1;
1152 print_size = 1;
1155 if (nobj_resolved > 0) {
1156 p_resolved = (nobj_resolved * 100) /
1157 (nobj_total - nobj_loose);
1158 if (p_resolved != a->last_p_resolved) {
1159 a->last_p_resolved = p_resolved;
1160 print_resolved = 1;
1161 print_indexed = 1;
1162 print_size = 1;
1167 if (print_size || print_indexed || print_resolved)
1168 printf("\r");
1169 if (print_size)
1170 printf("%*s fetched", FMT_SCALED_STRSIZE - 2, scaled_size);
1171 if (print_indexed)
1172 printf("; indexing %d%%", p_indexed);
1173 if (print_resolved)
1174 printf("; resolving deltas %d%%", p_resolved);
1175 if (print_size || print_indexed || print_resolved)
1176 fflush(stdout);
1178 return NULL;
1181 static const struct got_error *
1182 create_symref(const char *refname, struct got_reference *target_ref,
1183 int verbosity, struct got_repository *repo)
1185 const struct got_error *err;
1186 struct got_reference *head_symref;
1188 err = got_ref_alloc_symref(&head_symref, refname, target_ref);
1189 if (err)
1190 return err;
1192 err = got_ref_write(head_symref, repo);
1193 if (err == NULL && verbosity > 0) {
1194 printf("Created reference %s: %s\n", GOT_REF_HEAD,
1195 got_ref_get_name(target_ref));
1197 got_ref_close(head_symref);
1198 return err;
1201 static const struct got_error *
1202 list_remote_refs(struct got_pathlist_head *symrefs,
1203 struct got_pathlist_head *refs)
1205 const struct got_error *err;
1206 struct got_pathlist_entry *pe;
1208 TAILQ_FOREACH(pe, symrefs, entry) {
1209 const char *refname = pe->path;
1210 const char *targetref = pe->data;
1212 printf("%s: %s\n", refname, targetref);
1215 TAILQ_FOREACH(pe, refs, entry) {
1216 const char *refname = pe->path;
1217 struct got_object_id *id = pe->data;
1218 char *id_str;
1220 err = got_object_id_str(&id_str, id);
1221 if (err)
1222 return err;
1223 printf("%s: %s\n", refname, id_str);
1224 free(id_str);
1227 return NULL;
1230 static const struct got_error *
1231 create_ref(const char *refname, struct got_object_id *id,
1232 int verbosity, struct got_repository *repo)
1234 const struct got_error *err = NULL;
1235 struct got_reference *ref;
1236 char *id_str;
1238 err = got_object_id_str(&id_str, id);
1239 if (err)
1240 return err;
1242 err = got_ref_alloc(&ref, refname, id);
1243 if (err)
1244 goto done;
1246 err = got_ref_write(ref, repo);
1247 got_ref_close(ref);
1249 if (err == NULL && verbosity >= 0)
1250 printf("Created reference %s: %s\n", refname, id_str);
1251 done:
1252 free(id_str);
1253 return err;
1256 static int
1257 match_wanted_ref(const char *refname, const char *wanted_ref)
1259 if (strncmp(refname, "refs/", 5) != 0)
1260 return 0;
1261 refname += 5;
1264 * Prevent fetching of references that won't make any
1265 * sense outside of the remote repository's context.
1267 if (strncmp(refname, "got/", 4) == 0)
1268 return 0;
1269 if (strncmp(refname, "remotes/", 8) == 0)
1270 return 0;
1272 if (strncmp(wanted_ref, "refs/", 5) == 0)
1273 wanted_ref += 5;
1275 /* Allow prefix match. */
1276 if (got_path_is_child(refname, wanted_ref, strlen(wanted_ref)))
1277 return 1;
1279 /* Allow exact match. */
1280 return (strcmp(refname, wanted_ref) == 0);
1283 static int
1284 is_wanted_ref(struct got_pathlist_head *wanted_refs, const char *refname)
1286 struct got_pathlist_entry *pe;
1288 TAILQ_FOREACH(pe, wanted_refs, entry) {
1289 if (match_wanted_ref(refname, pe->path))
1290 return 1;
1293 return 0;
1296 static const struct got_error *
1297 create_wanted_ref(const char *refname, struct got_object_id *id,
1298 const char *remote_repo_name, int verbosity, struct got_repository *repo)
1300 const struct got_error *err;
1301 char *remote_refname;
1303 if (strncmp("refs/", refname, 5) == 0)
1304 refname += 5;
1306 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
1307 remote_repo_name, refname) == -1)
1308 return got_error_from_errno("asprintf");
1310 err = create_ref(remote_refname, id, verbosity, repo);
1311 free(remote_refname);
1312 return err;
1315 static const struct got_error *
1316 create_gotconfig(const char *proto, const char *host, const char *port,
1317 const char *remote_repo_path, const char *default_branch,
1318 int fetch_all_branches, struct got_pathlist_head *wanted_branches,
1319 struct got_pathlist_head *wanted_refs, int mirror_references,
1320 struct got_repository *repo)
1322 const struct got_error *err = NULL;
1323 char *gotconfig_path = NULL;
1324 char *gotconfig = NULL;
1325 FILE *gotconfig_file = NULL;
1326 const char *branchname = NULL;
1327 char *branches = NULL, *refs = NULL;
1328 ssize_t n;
1330 if (!fetch_all_branches && !TAILQ_EMPTY(wanted_branches)) {
1331 struct got_pathlist_entry *pe;
1332 TAILQ_FOREACH(pe, wanted_branches, entry) {
1333 char *s;
1334 branchname = pe->path;
1335 if (strncmp(branchname, "refs/heads/", 11) == 0)
1336 branchname += 11;
1337 if (asprintf(&s, "%s\"%s\" ",
1338 branches ? branches : "", branchname) == -1) {
1339 err = got_error_from_errno("asprintf");
1340 goto done;
1342 free(branches);
1343 branches = s;
1345 } else if (!fetch_all_branches && default_branch) {
1346 branchname = default_branch;
1347 if (strncmp(branchname, "refs/heads/", 11) == 0)
1348 branchname += 11;
1349 if (asprintf(&branches, "\"%s\" ", branchname) == -1) {
1350 err = got_error_from_errno("asprintf");
1351 goto done;
1354 if (!TAILQ_EMPTY(wanted_refs)) {
1355 struct got_pathlist_entry *pe;
1356 TAILQ_FOREACH(pe, wanted_refs, entry) {
1357 char *s;
1358 const char *refname = pe->path;
1359 if (strncmp(refname, "refs/", 5) == 0)
1360 branchname += 5;
1361 if (asprintf(&s, "%s\"%s\" ",
1362 refs ? refs : "", refname) == -1) {
1363 err = got_error_from_errno("asprintf");
1364 goto done;
1366 free(refs);
1367 refs = s;
1371 /* Create got.conf(5). */
1372 gotconfig_path = got_repo_get_path_gotconfig(repo);
1373 if (gotconfig_path == NULL) {
1374 err = got_error_from_errno("got_repo_get_path_gotconfig");
1375 goto done;
1377 gotconfig_file = fopen(gotconfig_path, "ae");
1378 if (gotconfig_file == NULL) {
1379 err = got_error_from_errno2("fopen", gotconfig_path);
1380 goto done;
1382 if (asprintf(&gotconfig,
1383 "remote \"%s\" {\n"
1384 "\tserver %s\n"
1385 "\tprotocol %s\n"
1386 "%s%s%s"
1387 "\trepository \"%s\"\n"
1388 "%s%s%s"
1389 "%s%s%s"
1390 "%s"
1391 "%s"
1392 "}\n",
1393 GOT_FETCH_DEFAULT_REMOTE_NAME, host, proto,
1394 port ? "\tport " : "", port ? port : "", port ? "\n" : "",
1395 remote_repo_path, branches ? "\tbranch { " : "",
1396 branches ? branches : "", branches ? "}\n" : "",
1397 refs ? "\treference { " : "", refs ? refs : "", refs ? "}\n" : "",
1398 mirror_references ? "\tmirror_references yes\n" : "",
1399 fetch_all_branches ? "\tfetch_all_branches yes\n" : "") == -1) {
1400 err = got_error_from_errno("asprintf");
1401 goto done;
1403 n = fwrite(gotconfig, 1, strlen(gotconfig), gotconfig_file);
1404 if (n != strlen(gotconfig)) {
1405 err = got_ferror(gotconfig_file, GOT_ERR_IO);
1406 goto done;
1409 done:
1410 if (gotconfig_file && fclose(gotconfig_file) == EOF && err == NULL)
1411 err = got_error_from_errno2("fclose", gotconfig_path);
1412 free(gotconfig_path);
1413 free(branches);
1414 return err;
1417 static const struct got_error *
1418 create_gitconfig(const char *git_url, const char *default_branch,
1419 int fetch_all_branches, struct got_pathlist_head *wanted_branches,
1420 struct got_pathlist_head *wanted_refs, int mirror_references,
1421 struct got_repository *repo)
1423 const struct got_error *err = NULL;
1424 char *gitconfig_path = NULL;
1425 char *gitconfig = NULL;
1426 FILE *gitconfig_file = NULL;
1427 char *branches = NULL, *refs = NULL;
1428 const char *branchname;
1429 ssize_t n;
1431 /* Create a config file Git can understand. */
1432 gitconfig_path = got_repo_get_path_gitconfig(repo);
1433 if (gitconfig_path == NULL) {
1434 err = got_error_from_errno("got_repo_get_path_gitconfig");
1435 goto done;
1437 gitconfig_file = fopen(gitconfig_path, "ae");
1438 if (gitconfig_file == NULL) {
1439 err = got_error_from_errno2("fopen", gitconfig_path);
1440 goto done;
1442 if (fetch_all_branches) {
1443 if (mirror_references) {
1444 if (asprintf(&branches,
1445 "\tfetch = refs/heads/*:refs/heads/*\n") == -1) {
1446 err = got_error_from_errno("asprintf");
1447 goto done;
1449 } else if (asprintf(&branches,
1450 "\tfetch = refs/heads/*:refs/remotes/%s/*\n",
1451 GOT_FETCH_DEFAULT_REMOTE_NAME) == -1) {
1452 err = got_error_from_errno("asprintf");
1453 goto done;
1455 } else if (!TAILQ_EMPTY(wanted_branches)) {
1456 struct got_pathlist_entry *pe;
1457 TAILQ_FOREACH(pe, wanted_branches, entry) {
1458 char *s;
1459 branchname = pe->path;
1460 if (strncmp(branchname, "refs/heads/", 11) == 0)
1461 branchname += 11;
1462 if (mirror_references) {
1463 if (asprintf(&s,
1464 "%s\tfetch = refs/heads/%s:refs/heads/%s\n",
1465 branches ? branches : "",
1466 branchname, branchname) == -1) {
1467 err = got_error_from_errno("asprintf");
1468 goto done;
1470 } else if (asprintf(&s,
1471 "%s\tfetch = refs/heads/%s:refs/remotes/%s/%s\n",
1472 branches ? branches : "",
1473 branchname, GOT_FETCH_DEFAULT_REMOTE_NAME,
1474 branchname) == -1) {
1475 err = got_error_from_errno("asprintf");
1476 goto done;
1478 free(branches);
1479 branches = s;
1481 } else {
1483 * If the server specified a default branch, use just that one.
1484 * Otherwise fall back to fetching all branches on next fetch.
1486 if (default_branch) {
1487 branchname = default_branch;
1488 if (strncmp(branchname, "refs/heads/", 11) == 0)
1489 branchname += 11;
1490 } else
1491 branchname = "*"; /* fall back to all branches */
1492 if (mirror_references) {
1493 if (asprintf(&branches,
1494 "\tfetch = refs/heads/%s:refs/heads/%s\n",
1495 branchname, branchname) == -1) {
1496 err = got_error_from_errno("asprintf");
1497 goto done;
1499 } else if (asprintf(&branches,
1500 "\tfetch = refs/heads/%s:refs/remotes/%s/%s\n",
1501 branchname, GOT_FETCH_DEFAULT_REMOTE_NAME,
1502 branchname) == -1) {
1503 err = got_error_from_errno("asprintf");
1504 goto done;
1507 if (!TAILQ_EMPTY(wanted_refs)) {
1508 struct got_pathlist_entry *pe;
1509 TAILQ_FOREACH(pe, wanted_refs, entry) {
1510 char *s;
1511 const char *refname = pe->path;
1512 if (strncmp(refname, "refs/", 5) == 0)
1513 refname += 5;
1514 if (mirror_references) {
1515 if (asprintf(&s,
1516 "%s\tfetch = refs/%s:refs/%s\n",
1517 refs ? refs : "", refname, refname) == -1) {
1518 err = got_error_from_errno("asprintf");
1519 goto done;
1521 } else if (asprintf(&s,
1522 "%s\tfetch = refs/%s:refs/remotes/%s/%s\n",
1523 refs ? refs : "",
1524 refname, GOT_FETCH_DEFAULT_REMOTE_NAME,
1525 refname) == -1) {
1526 err = got_error_from_errno("asprintf");
1527 goto done;
1529 free(refs);
1530 refs = s;
1534 if (asprintf(&gitconfig,
1535 "[remote \"%s\"]\n"
1536 "\turl = %s\n"
1537 "%s"
1538 "%s"
1539 "\tfetch = refs/tags/*:refs/tags/*\n",
1540 GOT_FETCH_DEFAULT_REMOTE_NAME, git_url, branches ? branches : "",
1541 refs ? refs : "") == -1) {
1542 err = got_error_from_errno("asprintf");
1543 goto done;
1545 n = fwrite(gitconfig, 1, strlen(gitconfig), gitconfig_file);
1546 if (n != strlen(gitconfig)) {
1547 err = got_ferror(gitconfig_file, GOT_ERR_IO);
1548 goto done;
1550 done:
1551 if (gitconfig_file && fclose(gitconfig_file) == EOF && err == NULL)
1552 err = got_error_from_errno2("fclose", gitconfig_path);
1553 free(gitconfig_path);
1554 free(branches);
1555 return err;
1558 static const struct got_error *
1559 create_config_files(const char *proto, const char *host, const char *port,
1560 const char *remote_repo_path, const char *git_url, int fetch_all_branches,
1561 int mirror_references, struct got_pathlist_head *symrefs,
1562 struct got_pathlist_head *wanted_branches,
1563 struct got_pathlist_head *wanted_refs, struct got_repository *repo)
1565 const struct got_error *err = NULL;
1566 const char *default_branch = NULL;
1567 struct got_pathlist_entry *pe;
1570 * If we asked for a set of wanted branches then use the first
1571 * one of those.
1573 if (!TAILQ_EMPTY(wanted_branches)) {
1574 pe = TAILQ_FIRST(wanted_branches);
1575 default_branch = pe->path;
1576 } else {
1577 /* First HEAD ref listed by server is the default branch. */
1578 TAILQ_FOREACH(pe, symrefs, entry) {
1579 const char *refname = pe->path;
1580 const char *target = pe->data;
1582 if (strcmp(refname, GOT_REF_HEAD) != 0)
1583 continue;
1585 default_branch = target;
1586 break;
1590 /* Create got.conf(5). */
1591 err = create_gotconfig(proto, host, port, remote_repo_path,
1592 default_branch, fetch_all_branches, wanted_branches,
1593 wanted_refs, mirror_references, repo);
1594 if (err)
1595 return err;
1597 /* Create a config file Git can understand. */
1598 return create_gitconfig(git_url, default_branch, fetch_all_branches,
1599 wanted_branches, wanted_refs, mirror_references, repo);
1602 static const struct got_error *
1603 cmd_clone(int argc, char *argv[])
1605 const struct got_error *error = NULL;
1606 const char *uri, *dirname;
1607 char *proto, *host, *port, *repo_name, *server_path;
1608 char *default_destdir = NULL, *id_str = NULL;
1609 const char *repo_path;
1610 struct got_repository *repo = NULL;
1611 struct got_pathlist_head refs, symrefs, wanted_branches, wanted_refs;
1612 struct got_pathlist_entry *pe;
1613 struct got_object_id *pack_hash = NULL;
1614 int ch, fetchfd = -1, fetchstatus;
1615 pid_t fetchpid = -1;
1616 struct got_fetch_progress_arg fpa;
1617 char *git_url = NULL;
1618 int verbosity = 0, fetch_all_branches = 0, mirror_references = 0;
1619 int bflag = 0, list_refs_only = 0;
1620 int *pack_fds = NULL;
1622 TAILQ_INIT(&refs);
1623 TAILQ_INIT(&symrefs);
1624 TAILQ_INIT(&wanted_branches);
1625 TAILQ_INIT(&wanted_refs);
1627 while ((ch = getopt(argc, argv, "ab:lmqR:v")) != -1) {
1628 switch (ch) {
1629 case 'a':
1630 fetch_all_branches = 1;
1631 break;
1632 case 'b':
1633 error = got_pathlist_append(&wanted_branches,
1634 optarg, NULL);
1635 if (error)
1636 return error;
1637 bflag = 1;
1638 break;
1639 case 'l':
1640 list_refs_only = 1;
1641 break;
1642 case 'm':
1643 mirror_references = 1;
1644 break;
1645 case 'q':
1646 verbosity = -1;
1647 break;
1648 case 'R':
1649 error = got_pathlist_append(&wanted_refs,
1650 optarg, NULL);
1651 if (error)
1652 return error;
1653 break;
1654 case 'v':
1655 if (verbosity < 0)
1656 verbosity = 0;
1657 else if (verbosity < 3)
1658 verbosity++;
1659 break;
1660 default:
1661 usage_clone();
1662 break;
1665 argc -= optind;
1666 argv += optind;
1668 if (fetch_all_branches && !TAILQ_EMPTY(&wanted_branches))
1669 option_conflict('a', 'b');
1670 if (list_refs_only) {
1671 if (!TAILQ_EMPTY(&wanted_branches))
1672 option_conflict('l', 'b');
1673 if (fetch_all_branches)
1674 option_conflict('l', 'a');
1675 if (mirror_references)
1676 option_conflict('l', 'm');
1677 if (!TAILQ_EMPTY(&wanted_refs))
1678 option_conflict('l', 'R');
1681 uri = argv[0];
1683 if (argc == 1)
1684 dirname = NULL;
1685 else if (argc == 2)
1686 dirname = argv[1];
1687 else
1688 usage_clone();
1690 error = got_dial_parse_uri(&proto, &host, &port, &server_path,
1691 &repo_name, uri);
1692 if (error)
1693 goto done;
1695 if (asprintf(&git_url, "%s://%s%s%s%s%s", proto,
1696 host, port ? ":" : "", port ? port : "",
1697 server_path[0] != '/' ? "/" : "", server_path) == -1) {
1698 error = got_error_from_errno("asprintf");
1699 goto done;
1702 if (strcmp(proto, "git") == 0) {
1703 #ifndef PROFILE
1704 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
1705 "sendfd dns inet unveil", NULL) == -1)
1706 err(1, "pledge");
1707 #endif
1708 } else if (strcmp(proto, "git+ssh") == 0 ||
1709 strcmp(proto, "ssh") == 0 ||
1710 strcmp(proto, "git+http") == 0 ||
1711 strcmp(proto, "http") == 0 ||
1712 strcmp(proto, "git+https") == 0 ||
1713 strcmp(proto, "https") == 0) {
1714 #ifndef PROFILE
1715 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
1716 "sendfd unveil", NULL) == -1)
1717 err(1, "pledge");
1718 #endif
1719 } else {
1720 error = got_error_path(proto, GOT_ERR_BAD_PROTO);
1721 goto done;
1723 if (dirname == NULL) {
1724 if (asprintf(&default_destdir, "%s.git", repo_name) == -1) {
1725 error = got_error_from_errno("asprintf");
1726 goto done;
1728 repo_path = default_destdir;
1729 } else
1730 repo_path = dirname;
1732 if (!list_refs_only) {
1733 error = got_path_mkdir(repo_path);
1734 if (error &&
1735 (!(error->code == GOT_ERR_ERRNO && errno == EISDIR) &&
1736 !(error->code == GOT_ERR_ERRNO && errno == EEXIST)))
1737 goto done;
1738 if (!got_path_dir_is_empty(repo_path)) {
1739 error = got_error_path(repo_path,
1740 GOT_ERR_DIR_NOT_EMPTY);
1741 goto done;
1745 error = got_dial_apply_unveil(proto);
1746 if (error)
1747 goto done;
1749 error = apply_unveil(repo_path, 0, NULL);
1750 if (error)
1751 goto done;
1753 if (verbosity >= 0)
1754 printf("Connecting to %s\n", git_url);
1756 error = got_fetch_connect(&fetchpid, &fetchfd, proto, host, port,
1757 server_path, verbosity);
1758 if (error)
1759 goto done;
1761 #ifndef PROFILE
1762 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd",
1763 NULL) == -1)
1764 err(1, "pledge");
1765 #endif
1766 if (!list_refs_only) {
1767 error = got_repo_init(repo_path, NULL);
1768 if (error)
1769 goto done;
1770 error = got_repo_pack_fds_open(&pack_fds);
1771 if (error != NULL)
1772 goto done;
1773 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
1774 if (error)
1775 goto done;
1778 fpa.last_scaled_size[0] = '\0';
1779 fpa.last_p_indexed = -1;
1780 fpa.last_p_resolved = -1;
1781 fpa.verbosity = verbosity;
1782 fpa.create_configs = 1;
1783 fpa.configs_created = 0;
1784 fpa.repo = repo;
1785 fpa.config_info.symrefs = &symrefs;
1786 fpa.config_info.wanted_branches = &wanted_branches;
1787 fpa.config_info.wanted_refs = &wanted_refs;
1788 fpa.config_info.proto = proto;
1789 fpa.config_info.host = host;
1790 fpa.config_info.port = port;
1791 fpa.config_info.remote_repo_path = server_path;
1792 fpa.config_info.git_url = git_url;
1793 fpa.config_info.fetch_all_branches = fetch_all_branches;
1794 fpa.config_info.mirror_references = mirror_references;
1795 error = got_fetch_pack(&pack_hash, &refs, &symrefs,
1796 GOT_FETCH_DEFAULT_REMOTE_NAME, mirror_references,
1797 fetch_all_branches, &wanted_branches, &wanted_refs,
1798 list_refs_only, verbosity, fetchfd, repo, NULL, NULL, bflag,
1799 fetch_progress, &fpa);
1800 if (error)
1801 goto done;
1803 if (list_refs_only) {
1804 error = list_remote_refs(&symrefs, &refs);
1805 goto done;
1808 if (pack_hash == NULL) {
1809 error = got_error_fmt(GOT_ERR_FETCH_FAILED, "%s",
1810 "server sent an empty pack file");
1811 goto done;
1813 error = got_object_id_str(&id_str, pack_hash);
1814 if (error)
1815 goto done;
1816 if (verbosity >= 0)
1817 printf("\nFetched %s.pack\n", id_str);
1818 free(id_str);
1820 /* Set up references provided with the pack file. */
1821 TAILQ_FOREACH(pe, &refs, entry) {
1822 const char *refname = pe->path;
1823 struct got_object_id *id = pe->data;
1824 char *remote_refname;
1826 if (is_wanted_ref(&wanted_refs, refname) &&
1827 !mirror_references) {
1828 error = create_wanted_ref(refname, id,
1829 GOT_FETCH_DEFAULT_REMOTE_NAME,
1830 verbosity - 1, repo);
1831 if (error)
1832 goto done;
1833 continue;
1836 error = create_ref(refname, id, verbosity - 1, repo);
1837 if (error)
1838 goto done;
1840 if (mirror_references)
1841 continue;
1843 if (strncmp("refs/heads/", refname, 11) != 0)
1844 continue;
1846 if (asprintf(&remote_refname,
1847 "refs/remotes/%s/%s", GOT_FETCH_DEFAULT_REMOTE_NAME,
1848 refname + 11) == -1) {
1849 error = got_error_from_errno("asprintf");
1850 goto done;
1852 error = create_ref(remote_refname, id, verbosity - 1, repo);
1853 free(remote_refname);
1854 if (error)
1855 goto done;
1858 /* Set the HEAD reference if the server provided one. */
1859 TAILQ_FOREACH(pe, &symrefs, entry) {
1860 struct got_reference *target_ref;
1861 const char *refname = pe->path;
1862 const char *target = pe->data;
1863 char *remote_refname = NULL, *remote_target = NULL;
1865 if (strcmp(refname, GOT_REF_HEAD) != 0)
1866 continue;
1868 error = got_ref_open(&target_ref, repo, target, 0);
1869 if (error) {
1870 if (error->code == GOT_ERR_NOT_REF) {
1871 error = NULL;
1872 continue;
1874 goto done;
1877 error = create_symref(refname, target_ref, verbosity, repo);
1878 got_ref_close(target_ref);
1879 if (error)
1880 goto done;
1882 if (mirror_references)
1883 continue;
1885 if (strncmp("refs/heads/", target, 11) != 0)
1886 continue;
1888 if (asprintf(&remote_refname,
1889 "refs/remotes/%s/%s", GOT_FETCH_DEFAULT_REMOTE_NAME,
1890 refname) == -1) {
1891 error = got_error_from_errno("asprintf");
1892 goto done;
1894 if (asprintf(&remote_target,
1895 "refs/remotes/%s/%s", GOT_FETCH_DEFAULT_REMOTE_NAME,
1896 target + 11) == -1) {
1897 error = got_error_from_errno("asprintf");
1898 free(remote_refname);
1899 goto done;
1901 error = got_ref_open(&target_ref, repo, remote_target, 0);
1902 if (error) {
1903 free(remote_refname);
1904 free(remote_target);
1905 if (error->code == GOT_ERR_NOT_REF) {
1906 error = NULL;
1907 continue;
1909 goto done;
1911 error = create_symref(remote_refname, target_ref,
1912 verbosity - 1, repo);
1913 free(remote_refname);
1914 free(remote_target);
1915 got_ref_close(target_ref);
1916 if (error)
1917 goto done;
1919 if (pe == NULL) {
1921 * We failed to set the HEAD reference. If we asked for
1922 * a set of wanted branches use the first of one of those
1923 * which could be fetched instead.
1925 TAILQ_FOREACH(pe, &wanted_branches, entry) {
1926 const char *target = pe->path;
1927 struct got_reference *target_ref;
1929 error = got_ref_open(&target_ref, repo, target, 0);
1930 if (error) {
1931 if (error->code == GOT_ERR_NOT_REF) {
1932 error = NULL;
1933 continue;
1935 goto done;
1938 error = create_symref(GOT_REF_HEAD, target_ref,
1939 verbosity, repo);
1940 got_ref_close(target_ref);
1941 if (error)
1942 goto done;
1943 break;
1946 if (!fpa.configs_created && pe != NULL) {
1947 error = create_config_files(fpa.config_info.proto,
1948 fpa.config_info.host, fpa.config_info.port,
1949 fpa.config_info.remote_repo_path,
1950 fpa.config_info.git_url,
1951 fpa.config_info.fetch_all_branches,
1952 fpa.config_info.mirror_references,
1953 fpa.config_info.symrefs,
1954 fpa.config_info.wanted_branches,
1955 fpa.config_info.wanted_refs, fpa.repo);
1956 if (error)
1957 goto done;
1961 if (verbosity >= 0)
1962 printf("Created %s repository '%s'\n",
1963 mirror_references ? "mirrored" : "cloned", repo_path);
1964 done:
1965 if (pack_fds) {
1966 const struct got_error *pack_err =
1967 got_repo_pack_fds_close(pack_fds);
1968 if (error == NULL)
1969 error = pack_err;
1971 if (fetchpid > 0) {
1972 if (kill(fetchpid, SIGTERM) == -1)
1973 error = got_error_from_errno("kill");
1974 if (waitpid(fetchpid, &fetchstatus, 0) == -1 && error == NULL)
1975 error = got_error_from_errno("waitpid");
1977 if (fetchfd != -1 && close(fetchfd) == -1 && error == NULL)
1978 error = got_error_from_errno("close");
1979 if (repo) {
1980 const struct got_error *close_err = got_repo_close(repo);
1981 if (error == NULL)
1982 error = close_err;
1984 got_pathlist_free(&refs, GOT_PATHLIST_FREE_ALL);
1985 got_pathlist_free(&symrefs, GOT_PATHLIST_FREE_ALL);
1986 got_pathlist_free(&wanted_branches, GOT_PATHLIST_FREE_NONE);
1987 got_pathlist_free(&wanted_refs, GOT_PATHLIST_FREE_NONE);
1988 free(pack_hash);
1989 free(proto);
1990 free(host);
1991 free(port);
1992 free(server_path);
1993 free(repo_name);
1994 free(default_destdir);
1995 free(git_url);
1996 return error;
1999 static const struct got_error *
2000 update_ref(struct got_reference *ref, struct got_object_id *new_id,
2001 int replace_tags, int verbosity, struct got_repository *repo)
2003 const struct got_error *err = NULL;
2004 char *new_id_str = NULL;
2005 struct got_object_id *old_id = NULL;
2007 err = got_object_id_str(&new_id_str, new_id);
2008 if (err)
2009 goto done;
2011 if (!replace_tags &&
2012 strncmp(got_ref_get_name(ref), "refs/tags/", 10) == 0) {
2013 err = got_ref_resolve(&old_id, repo, ref);
2014 if (err)
2015 goto done;
2016 if (got_object_id_cmp(old_id, new_id) == 0)
2017 goto done;
2018 if (verbosity >= 0) {
2019 printf("Rejecting update of existing tag %s: %s\n",
2020 got_ref_get_name(ref), new_id_str);
2022 goto done;
2025 if (got_ref_is_symbolic(ref)) {
2026 if (verbosity >= 0) {
2027 printf("Replacing reference %s: %s\n",
2028 got_ref_get_name(ref),
2029 got_ref_get_symref_target(ref));
2031 err = got_ref_change_symref_to_ref(ref, new_id);
2032 if (err)
2033 goto done;
2034 err = got_ref_write(ref, repo);
2035 if (err)
2036 goto done;
2037 } else {
2038 err = got_ref_resolve(&old_id, repo, ref);
2039 if (err)
2040 goto done;
2041 if (got_object_id_cmp(old_id, new_id) == 0)
2042 goto done;
2044 err = got_ref_change_ref(ref, new_id);
2045 if (err)
2046 goto done;
2047 err = got_ref_write(ref, repo);
2048 if (err)
2049 goto done;
2052 if (verbosity >= 0)
2053 printf("Updated %s: %s\n", got_ref_get_name(ref),
2054 new_id_str);
2055 done:
2056 free(old_id);
2057 free(new_id_str);
2058 return err;
2061 static const struct got_error *
2062 update_symref(const char *refname, struct got_reference *target_ref,
2063 int verbosity, struct got_repository *repo)
2065 const struct got_error *err = NULL, *unlock_err;
2066 struct got_reference *symref;
2067 int symref_is_locked = 0;
2069 err = got_ref_open(&symref, repo, refname, 1);
2070 if (err) {
2071 if (err->code != GOT_ERR_NOT_REF)
2072 return err;
2073 err = got_ref_alloc_symref(&symref, refname, target_ref);
2074 if (err)
2075 goto done;
2077 err = got_ref_write(symref, repo);
2078 if (err)
2079 goto done;
2081 if (verbosity >= 0)
2082 printf("Created reference %s: %s\n",
2083 got_ref_get_name(symref),
2084 got_ref_get_symref_target(symref));
2085 } else {
2086 symref_is_locked = 1;
2088 if (strcmp(got_ref_get_symref_target(symref),
2089 got_ref_get_name(target_ref)) == 0)
2090 goto done;
2092 err = got_ref_change_symref(symref,
2093 got_ref_get_name(target_ref));
2094 if (err)
2095 goto done;
2097 err = got_ref_write(symref, repo);
2098 if (err)
2099 goto done;
2101 if (verbosity >= 0)
2102 printf("Updated %s: %s\n", got_ref_get_name(symref),
2103 got_ref_get_symref_target(symref));
2106 done:
2107 if (symref_is_locked) {
2108 unlock_err = got_ref_unlock(symref);
2109 if (unlock_err && err == NULL)
2110 err = unlock_err;
2112 got_ref_close(symref);
2113 return err;
2116 __dead static void
2117 usage_fetch(void)
2119 fprintf(stderr, "usage: %s fetch [-adlqtvX] [-b branch] "
2120 "[-R reference] [-r repository-path] [remote-repository]\n",
2121 getprogname());
2122 exit(1);
2125 static const struct got_error *
2126 delete_missing_ref(struct got_reference *ref,
2127 int verbosity, struct got_repository *repo)
2129 const struct got_error *err = NULL;
2130 struct got_object_id *id = NULL;
2131 char *id_str = NULL;
2133 if (got_ref_is_symbolic(ref)) {
2134 err = got_ref_delete(ref, repo);
2135 if (err)
2136 return err;
2137 if (verbosity >= 0) {
2138 printf("Deleted %s: %s\n",
2139 got_ref_get_name(ref),
2140 got_ref_get_symref_target(ref));
2142 } else {
2143 err = got_ref_resolve(&id, repo, ref);
2144 if (err)
2145 return err;
2146 err = got_object_id_str(&id_str, id);
2147 if (err)
2148 goto done;
2150 err = got_ref_delete(ref, repo);
2151 if (err)
2152 goto done;
2153 if (verbosity >= 0) {
2154 printf("Deleted %s: %s\n",
2155 got_ref_get_name(ref), id_str);
2158 done:
2159 free(id);
2160 free(id_str);
2161 return err;
2164 static const struct got_error *
2165 delete_missing_refs(struct got_pathlist_head *their_refs,
2166 struct got_pathlist_head *their_symrefs,
2167 const struct got_remote_repo *remote,
2168 int verbosity, struct got_repository *repo)
2170 const struct got_error *err = NULL, *unlock_err;
2171 struct got_reflist_head my_refs;
2172 struct got_reflist_entry *re;
2173 struct got_pathlist_entry *pe;
2174 char *remote_namespace = NULL;
2175 char *local_refname = NULL;
2177 TAILQ_INIT(&my_refs);
2179 if (asprintf(&remote_namespace, "refs/remotes/%s/", remote->name)
2180 == -1)
2181 return got_error_from_errno("asprintf");
2183 err = got_ref_list(&my_refs, repo, NULL, got_ref_cmp_by_name, NULL);
2184 if (err)
2185 goto done;
2187 TAILQ_FOREACH(re, &my_refs, entry) {
2188 const char *refname = got_ref_get_name(re->ref);
2189 const char *their_refname;
2191 if (remote->mirror_references) {
2192 their_refname = refname;
2193 } else {
2194 if (strncmp(refname, remote_namespace,
2195 strlen(remote_namespace)) == 0) {
2196 if (strcmp(refname + strlen(remote_namespace),
2197 GOT_REF_HEAD) == 0)
2198 continue;
2199 if (asprintf(&local_refname, "refs/heads/%s",
2200 refname + strlen(remote_namespace)) == -1) {
2201 err = got_error_from_errno("asprintf");
2202 goto done;
2204 } else if (strncmp(refname, "refs/tags/", 10) != 0)
2205 continue;
2207 their_refname = local_refname;
2210 TAILQ_FOREACH(pe, their_refs, entry) {
2211 if (strcmp(their_refname, pe->path) == 0)
2212 break;
2214 if (pe != NULL)
2215 continue;
2217 TAILQ_FOREACH(pe, their_symrefs, entry) {
2218 if (strcmp(their_refname, pe->path) == 0)
2219 break;
2221 if (pe != NULL)
2222 continue;
2224 err = delete_missing_ref(re->ref, verbosity, repo);
2225 if (err)
2226 break;
2228 if (local_refname) {
2229 struct got_reference *ref;
2230 err = got_ref_open(&ref, repo, local_refname, 1);
2231 if (err) {
2232 if (err->code != GOT_ERR_NOT_REF)
2233 break;
2234 free(local_refname);
2235 local_refname = NULL;
2236 continue;
2238 err = delete_missing_ref(ref, verbosity, repo);
2239 if (err)
2240 break;
2241 unlock_err = got_ref_unlock(ref);
2242 got_ref_close(ref);
2243 if (unlock_err && err == NULL) {
2244 err = unlock_err;
2245 break;
2248 free(local_refname);
2249 local_refname = NULL;
2252 done:
2253 got_ref_list_free(&my_refs);
2254 free(remote_namespace);
2255 free(local_refname);
2256 return err;
2259 static const struct got_error *
2260 update_wanted_ref(const char *refname, struct got_object_id *id,
2261 const char *remote_repo_name, int verbosity, struct got_repository *repo)
2263 const struct got_error *err, *unlock_err;
2264 char *remote_refname;
2265 struct got_reference *ref;
2267 if (strncmp("refs/", refname, 5) == 0)
2268 refname += 5;
2270 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
2271 remote_repo_name, refname) == -1)
2272 return got_error_from_errno("asprintf");
2274 err = got_ref_open(&ref, repo, remote_refname, 1);
2275 if (err) {
2276 if (err->code != GOT_ERR_NOT_REF)
2277 goto done;
2278 err = create_ref(remote_refname, id, verbosity, repo);
2279 } else {
2280 err = update_ref(ref, id, 0, verbosity, repo);
2281 unlock_err = got_ref_unlock(ref);
2282 if (unlock_err && err == NULL)
2283 err = unlock_err;
2284 got_ref_close(ref);
2286 done:
2287 free(remote_refname);
2288 return err;
2291 static const struct got_error *
2292 delete_ref(struct got_repository *repo, struct got_reference *ref)
2294 const struct got_error *err = NULL;
2295 struct got_object_id *id = NULL;
2296 char *id_str = NULL;
2297 const char *target;
2299 if (got_ref_is_symbolic(ref)) {
2300 target = got_ref_get_symref_target(ref);
2301 } else {
2302 err = got_ref_resolve(&id, repo, ref);
2303 if (err)
2304 goto done;
2305 err = got_object_id_str(&id_str, id);
2306 if (err)
2307 goto done;
2308 target = id_str;
2311 err = got_ref_delete(ref, repo);
2312 if (err)
2313 goto done;
2315 printf("Deleted %s: %s\n", got_ref_get_name(ref), target);
2316 done:
2317 free(id);
2318 free(id_str);
2319 return err;
2322 static const struct got_error *
2323 delete_refs_for_remote(struct got_repository *repo, const char *remote_name)
2325 const struct got_error *err = NULL;
2326 struct got_reflist_head refs;
2327 struct got_reflist_entry *re;
2328 char *prefix;
2330 TAILQ_INIT(&refs);
2332 if (asprintf(&prefix, "refs/remotes/%s", remote_name) == -1) {
2333 err = got_error_from_errno("asprintf");
2334 goto done;
2336 err = got_ref_list(&refs, repo, prefix, got_ref_cmp_by_name, NULL);
2337 if (err)
2338 goto done;
2340 TAILQ_FOREACH(re, &refs, entry)
2341 delete_ref(repo, re->ref);
2342 done:
2343 got_ref_list_free(&refs);
2344 return err;
2347 static const struct got_error *
2348 cmd_fetch(int argc, char *argv[])
2350 const struct got_error *error = NULL, *unlock_err;
2351 char *cwd = NULL, *repo_path = NULL;
2352 const char *remote_name;
2353 char *proto = NULL, *host = NULL, *port = NULL;
2354 char *repo_name = NULL, *server_path = NULL;
2355 const struct got_remote_repo *remotes;
2356 struct got_remote_repo *remote = NULL;
2357 int nremotes;
2358 char *id_str = NULL;
2359 struct got_repository *repo = NULL;
2360 struct got_worktree *worktree = NULL;
2361 const struct got_gotconfig *repo_conf = NULL, *worktree_conf = NULL;
2362 struct got_pathlist_head refs, symrefs, wanted_branches, wanted_refs;
2363 char *head_refname = NULL;
2364 struct got_pathlist_entry *pe;
2365 struct got_reflist_head remote_refs;
2366 struct got_reflist_entry *re;
2367 struct got_object_id *pack_hash = NULL;
2368 int i, ch, fetchfd = -1, fetchstatus;
2369 pid_t fetchpid = -1;
2370 struct got_fetch_progress_arg fpa;
2371 int verbosity = 0, fetch_all_branches = 0, list_refs_only = 0;
2372 int delete_refs = 0, replace_tags = 0, delete_remote = 0;
2373 int *pack_fds = NULL, have_bflag = 0;
2374 const char *remote_head = NULL, *worktree_branch = NULL;
2376 TAILQ_INIT(&refs);
2377 TAILQ_INIT(&symrefs);
2378 TAILQ_INIT(&remote_refs);
2379 TAILQ_INIT(&wanted_branches);
2380 TAILQ_INIT(&wanted_refs);
2382 while ((ch = getopt(argc, argv, "ab:dlqR:r:tvX")) != -1) {
2383 switch (ch) {
2384 case 'a':
2385 fetch_all_branches = 1;
2386 break;
2387 case 'b':
2388 error = got_pathlist_append(&wanted_branches,
2389 optarg, NULL);
2390 if (error)
2391 return error;
2392 have_bflag = 1;
2393 break;
2394 case 'd':
2395 delete_refs = 1;
2396 break;
2397 case 'l':
2398 list_refs_only = 1;
2399 break;
2400 case 'q':
2401 verbosity = -1;
2402 break;
2403 case 'R':
2404 error = got_pathlist_append(&wanted_refs,
2405 optarg, NULL);
2406 if (error)
2407 return error;
2408 break;
2409 case 'r':
2410 repo_path = realpath(optarg, NULL);
2411 if (repo_path == NULL)
2412 return got_error_from_errno2("realpath",
2413 optarg);
2414 got_path_strip_trailing_slashes(repo_path);
2415 break;
2416 case 't':
2417 replace_tags = 1;
2418 break;
2419 case 'v':
2420 if (verbosity < 0)
2421 verbosity = 0;
2422 else if (verbosity < 3)
2423 verbosity++;
2424 break;
2425 case 'X':
2426 delete_remote = 1;
2427 break;
2428 default:
2429 usage_fetch();
2430 break;
2433 argc -= optind;
2434 argv += optind;
2436 if (fetch_all_branches && !TAILQ_EMPTY(&wanted_branches))
2437 option_conflict('a', 'b');
2438 if (list_refs_only) {
2439 if (!TAILQ_EMPTY(&wanted_branches))
2440 option_conflict('l', 'b');
2441 if (fetch_all_branches)
2442 option_conflict('l', 'a');
2443 if (delete_refs)
2444 option_conflict('l', 'd');
2445 if (delete_remote)
2446 option_conflict('l', 'X');
2448 if (delete_remote) {
2449 if (fetch_all_branches)
2450 option_conflict('X', 'a');
2451 if (!TAILQ_EMPTY(&wanted_branches))
2452 option_conflict('X', 'b');
2453 if (delete_refs)
2454 option_conflict('X', 'd');
2455 if (replace_tags)
2456 option_conflict('X', 't');
2457 if (!TAILQ_EMPTY(&wanted_refs))
2458 option_conflict('X', 'R');
2461 if (argc == 0) {
2462 if (delete_remote)
2463 errx(1, "-X option requires a remote name");
2464 remote_name = GOT_FETCH_DEFAULT_REMOTE_NAME;
2465 } else if (argc == 1)
2466 remote_name = argv[0];
2467 else
2468 usage_fetch();
2470 cwd = getcwd(NULL, 0);
2471 if (cwd == NULL) {
2472 error = got_error_from_errno("getcwd");
2473 goto done;
2476 error = got_repo_pack_fds_open(&pack_fds);
2477 if (error != NULL)
2478 goto done;
2480 if (repo_path == NULL) {
2481 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
2482 if (error && error->code != GOT_ERR_NOT_WORKTREE)
2483 goto done;
2484 else
2485 error = NULL;
2486 if (worktree) {
2487 repo_path =
2488 strdup(got_worktree_get_repo_path(worktree));
2489 if (repo_path == NULL)
2490 error = got_error_from_errno("strdup");
2491 if (error)
2492 goto done;
2493 } else {
2494 repo_path = strdup(cwd);
2495 if (repo_path == NULL) {
2496 error = got_error_from_errno("strdup");
2497 goto done;
2502 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
2503 if (error)
2504 goto done;
2506 if (delete_remote) {
2507 error = delete_refs_for_remote(repo, remote_name);
2508 goto done; /* nothing else to do */
2511 if (worktree) {
2512 worktree_conf = got_worktree_get_gotconfig(worktree);
2513 if (worktree_conf) {
2514 got_gotconfig_get_remotes(&nremotes, &remotes,
2515 worktree_conf);
2516 for (i = 0; i < nremotes; i++) {
2517 if (strcmp(remotes[i].name, remote_name) == 0) {
2518 error = got_repo_remote_repo_dup(&remote,
2519 &remotes[i]);
2520 if (error)
2521 goto done;
2522 break;
2527 if (remote == NULL) {
2528 repo_conf = got_repo_get_gotconfig(repo);
2529 if (repo_conf) {
2530 got_gotconfig_get_remotes(&nremotes, &remotes,
2531 repo_conf);
2532 for (i = 0; i < nremotes; i++) {
2533 if (strcmp(remotes[i].name, remote_name) == 0) {
2534 error = got_repo_remote_repo_dup(&remote,
2535 &remotes[i]);
2536 if (error)
2537 goto done;
2538 break;
2543 if (remote == NULL) {
2544 got_repo_get_gitconfig_remotes(&nremotes, &remotes, repo);
2545 for (i = 0; i < nremotes; i++) {
2546 if (strcmp(remotes[i].name, remote_name) == 0) {
2547 error = got_repo_remote_repo_dup(&remote,
2548 &remotes[i]);
2549 if (error)
2550 goto done;
2551 break;
2555 if (remote == NULL) {
2556 error = got_error_path(remote_name, GOT_ERR_NO_REMOTE);
2557 goto done;
2560 if (TAILQ_EMPTY(&wanted_branches)) {
2561 if (!fetch_all_branches)
2562 fetch_all_branches = remote->fetch_all_branches;
2563 for (i = 0; i < remote->nfetch_branches; i++) {
2564 error = got_pathlist_append(&wanted_branches,
2565 remote->fetch_branches[i], NULL);
2566 if (error)
2567 goto done;
2570 if (TAILQ_EMPTY(&wanted_refs)) {
2571 for (i = 0; i < remote->nfetch_refs; i++) {
2572 error = got_pathlist_append(&wanted_refs,
2573 remote->fetch_refs[i], NULL);
2574 if (error)
2575 goto done;
2579 error = got_dial_parse_uri(&proto, &host, &port, &server_path,
2580 &repo_name, remote->fetch_url);
2581 if (error)
2582 goto done;
2584 if (strcmp(proto, "git") == 0) {
2585 #ifndef PROFILE
2586 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
2587 "sendfd dns inet unveil", NULL) == -1)
2588 err(1, "pledge");
2589 #endif
2590 } else if (strcmp(proto, "git+ssh") == 0 ||
2591 strcmp(proto, "ssh") == 0 ||
2592 strcmp(proto, "git+http") == 0 ||
2593 strcmp(proto, "http") == 0 ||
2594 strcmp(proto, "git+https") == 0 ||
2595 strcmp(proto, "https") == 0) {
2596 #ifndef PROFILE
2597 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
2598 "sendfd unveil", NULL) == -1)
2599 err(1, "pledge");
2600 #endif
2601 } else {
2602 error = got_error_path(proto, GOT_ERR_BAD_PROTO);
2603 goto done;
2606 error = got_dial_apply_unveil(proto);
2607 if (error)
2608 goto done;
2610 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
2611 if (error)
2612 goto done;
2614 if (worktree) {
2615 head_refname = strdup(got_worktree_get_head_ref_name(worktree));
2616 if (head_refname == NULL) {
2617 error = got_error_from_errno("strdup");
2618 goto done;
2621 /* Release work tree lock. */
2622 got_worktree_close(worktree);
2623 worktree = NULL;
2626 if (verbosity >= 0) {
2627 printf("Connecting to \"%s\" %s://%s%s%s%s%s\n",
2628 remote->name, proto, host,
2629 port ? ":" : "", port ? port : "",
2630 *server_path == '/' ? "" : "/", server_path);
2633 error = got_fetch_connect(&fetchpid, &fetchfd, proto, host, port,
2634 server_path, verbosity);
2635 if (error)
2636 goto done;
2637 #ifndef PROFILE
2638 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd",
2639 NULL) == -1)
2640 err(1, "pledge");
2641 #endif
2642 if (!have_bflag) {
2644 * If set, get this remote's HEAD ref target so
2645 * if it has changed on the server we can fetch it.
2647 error = got_ref_list(&remote_refs, repo, "refs/remotes",
2648 got_ref_cmp_by_name, repo);
2649 if (error)
2650 goto done;
2652 TAILQ_FOREACH(re, &remote_refs, entry) {
2653 const char *remote_refname, *remote_target;
2654 size_t remote_name_len;
2656 if (!got_ref_is_symbolic(re->ref))
2657 continue;
2659 remote_name_len = strlen(remote->name);
2660 remote_refname = got_ref_get_name(re->ref);
2662 /* we only want refs/remotes/$remote->name/HEAD */
2663 if (strncmp(remote_refname + 13, remote->name,
2664 remote_name_len) != 0)
2665 continue;
2667 if (strcmp(remote_refname + remote_name_len + 14,
2668 GOT_REF_HEAD) != 0)
2669 continue;
2672 * Take the name itself because we already
2673 * only match with refs/heads/ in fetch_pack().
2675 remote_target = got_ref_get_symref_target(re->ref);
2676 remote_head = remote_target + remote_name_len + 14;
2677 break;
2680 if (head_refname &&
2681 strncmp(head_refname, "refs/heads/", 11) == 0)
2682 worktree_branch = head_refname;
2685 fpa.last_scaled_size[0] = '\0';
2686 fpa.last_p_indexed = -1;
2687 fpa.last_p_resolved = -1;
2688 fpa.verbosity = verbosity;
2689 fpa.repo = repo;
2690 fpa.create_configs = 0;
2691 fpa.configs_created = 0;
2692 memset(&fpa.config_info, 0, sizeof(fpa.config_info));
2694 error = got_fetch_pack(&pack_hash, &refs, &symrefs, remote->name,
2695 remote->mirror_references, fetch_all_branches, &wanted_branches,
2696 &wanted_refs, list_refs_only, verbosity, fetchfd, repo,
2697 worktree_branch, remote_head, have_bflag, fetch_progress, &fpa);
2698 if (error)
2699 goto done;
2701 if (list_refs_only) {
2702 error = list_remote_refs(&symrefs, &refs);
2703 goto done;
2706 if (pack_hash == NULL) {
2707 if (verbosity >= 0)
2708 printf("Already up-to-date\n");
2709 } else if (verbosity >= 0) {
2710 error = got_object_id_str(&id_str, pack_hash);
2711 if (error)
2712 goto done;
2713 printf("\nFetched %s.pack\n", id_str);
2714 free(id_str);
2715 id_str = NULL;
2718 /* Update references provided with the pack file. */
2719 TAILQ_FOREACH(pe, &refs, entry) {
2720 const char *refname = pe->path;
2721 struct got_object_id *id = pe->data;
2722 struct got_reference *ref;
2723 char *remote_refname;
2725 if (is_wanted_ref(&wanted_refs, refname) &&
2726 !remote->mirror_references) {
2727 error = update_wanted_ref(refname, id,
2728 remote->name, verbosity, repo);
2729 if (error)
2730 goto done;
2731 continue;
2734 if (remote->mirror_references ||
2735 strncmp("refs/tags/", refname, 10) == 0) {
2736 error = got_ref_open(&ref, repo, refname, 1);
2737 if (error) {
2738 if (error->code != GOT_ERR_NOT_REF)
2739 goto done;
2740 error = create_ref(refname, id, verbosity,
2741 repo);
2742 if (error)
2743 goto done;
2744 } else {
2745 error = update_ref(ref, id, replace_tags,
2746 verbosity, repo);
2747 unlock_err = got_ref_unlock(ref);
2748 if (unlock_err && error == NULL)
2749 error = unlock_err;
2750 got_ref_close(ref);
2751 if (error)
2752 goto done;
2754 } else if (strncmp("refs/heads/", refname, 11) == 0) {
2755 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
2756 remote_name, refname + 11) == -1) {
2757 error = got_error_from_errno("asprintf");
2758 goto done;
2761 error = got_ref_open(&ref, repo, remote_refname, 1);
2762 if (error) {
2763 if (error->code != GOT_ERR_NOT_REF)
2764 goto done;
2765 error = create_ref(remote_refname, id,
2766 verbosity, repo);
2767 if (error)
2768 goto done;
2769 } else {
2770 error = update_ref(ref, id, replace_tags,
2771 verbosity, repo);
2772 unlock_err = got_ref_unlock(ref);
2773 if (unlock_err && error == NULL)
2774 error = unlock_err;
2775 got_ref_close(ref);
2776 if (error)
2777 goto done;
2780 /* Also create a local branch if none exists yet. */
2781 error = got_ref_open(&ref, repo, refname, 1);
2782 if (error) {
2783 if (error->code != GOT_ERR_NOT_REF)
2784 goto done;
2785 error = create_ref(refname, id, verbosity,
2786 repo);
2787 if (error)
2788 goto done;
2789 } else {
2790 unlock_err = got_ref_unlock(ref);
2791 if (unlock_err && error == NULL)
2792 error = unlock_err;
2793 got_ref_close(ref);
2797 if (delete_refs) {
2798 error = delete_missing_refs(&refs, &symrefs, remote,
2799 verbosity, repo);
2800 if (error)
2801 goto done;
2804 if (!remote->mirror_references) {
2805 /* Update remote HEAD reference if the server provided one. */
2806 TAILQ_FOREACH(pe, &symrefs, entry) {
2807 struct got_reference *target_ref;
2808 const char *refname = pe->path;
2809 const char *target = pe->data;
2810 char *remote_refname = NULL, *remote_target = NULL;
2812 if (strcmp(refname, GOT_REF_HEAD) != 0)
2813 continue;
2815 if (strncmp("refs/heads/", target, 11) != 0)
2816 continue;
2818 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
2819 remote->name, refname) == -1) {
2820 error = got_error_from_errno("asprintf");
2821 goto done;
2823 if (asprintf(&remote_target, "refs/remotes/%s/%s",
2824 remote->name, target + 11) == -1) {
2825 error = got_error_from_errno("asprintf");
2826 free(remote_refname);
2827 goto done;
2830 error = got_ref_open(&target_ref, repo, remote_target,
2831 0);
2832 if (error) {
2833 free(remote_refname);
2834 free(remote_target);
2835 if (error->code == GOT_ERR_NOT_REF) {
2836 error = NULL;
2837 continue;
2839 goto done;
2841 error = update_symref(remote_refname, target_ref,
2842 verbosity, repo);
2843 free(remote_refname);
2844 free(remote_target);
2845 got_ref_close(target_ref);
2846 if (error)
2847 goto done;
2850 done:
2851 if (fetchpid > 0) {
2852 if (kill(fetchpid, SIGTERM) == -1)
2853 error = got_error_from_errno("kill");
2854 if (waitpid(fetchpid, &fetchstatus, 0) == -1 && error == NULL)
2855 error = got_error_from_errno("waitpid");
2857 if (fetchfd != -1 && close(fetchfd) == -1 && error == NULL)
2858 error = got_error_from_errno("close");
2859 if (repo) {
2860 const struct got_error *close_err = got_repo_close(repo);
2861 if (error == NULL)
2862 error = close_err;
2864 if (worktree)
2865 got_worktree_close(worktree);
2866 if (pack_fds) {
2867 const struct got_error *pack_err =
2868 got_repo_pack_fds_close(pack_fds);
2869 if (error == NULL)
2870 error = pack_err;
2872 got_pathlist_free(&refs, GOT_PATHLIST_FREE_ALL);
2873 got_pathlist_free(&symrefs, GOT_PATHLIST_FREE_ALL);
2874 got_pathlist_free(&wanted_branches, GOT_PATHLIST_FREE_NONE);
2875 got_pathlist_free(&wanted_refs, GOT_PATHLIST_FREE_NONE);
2876 got_ref_list_free(&remote_refs);
2877 got_repo_free_remote_repo_data(remote);
2878 free(remote);
2879 free(head_refname);
2880 free(id_str);
2881 free(cwd);
2882 free(repo_path);
2883 free(pack_hash);
2884 free(proto);
2885 free(host);
2886 free(port);
2887 free(server_path);
2888 free(repo_name);
2889 return error;
2893 __dead static void
2894 usage_checkout(void)
2896 fprintf(stderr, "usage: %s checkout [-Eq] [-b branch] [-c commit] "
2897 "[-p path-prefix] repository-path [work-tree-path]\n",
2898 getprogname());
2899 exit(1);
2902 static void
2903 show_worktree_base_ref_warning(void)
2905 fprintf(stderr, "%s: warning: could not create a reference "
2906 "to the work tree's base commit; the commit could be "
2907 "garbage-collected by Git or 'gotadmin cleanup'; making the "
2908 "repository writable and running 'got update' will prevent this\n",
2909 getprogname());
2912 struct got_checkout_progress_arg {
2913 const char *worktree_path;
2914 int had_base_commit_ref_error;
2915 int verbosity;
2918 static const struct got_error *
2919 checkout_progress(void *arg, unsigned char status, const char *path)
2921 struct got_checkout_progress_arg *a = arg;
2923 /* Base commit bump happens silently. */
2924 if (status == GOT_STATUS_BUMP_BASE)
2925 return NULL;
2927 if (status == GOT_STATUS_BASE_REF_ERR) {
2928 a->had_base_commit_ref_error = 1;
2929 return NULL;
2932 while (path[0] == '/')
2933 path++;
2935 if (a->verbosity >= 0)
2936 printf("%c %s/%s\n", status, a->worktree_path, path);
2938 return NULL;
2941 static const struct got_error *
2942 check_cancelled(void *arg)
2944 if (sigint_received || sigpipe_received)
2945 return got_error(GOT_ERR_CANCELLED);
2946 return NULL;
2949 static const struct got_error *
2950 check_linear_ancestry(struct got_object_id *commit_id,
2951 struct got_object_id *base_commit_id, int allow_forwards_in_time_only,
2952 struct got_repository *repo)
2954 const struct got_error *err = NULL;
2955 struct got_object_id *yca_id;
2957 err = got_commit_graph_find_youngest_common_ancestor(&yca_id,
2958 commit_id, base_commit_id, 1, 0, repo, check_cancelled, NULL);
2959 if (err)
2960 return err;
2962 if (yca_id == NULL)
2963 return got_error(GOT_ERR_ANCESTRY);
2966 * Require a straight line of history between the target commit
2967 * and the work tree's base commit.
2969 * Non-linear situations such as this require a rebase:
2971 * (commit) D F (base_commit)
2972 * \ /
2973 * C E
2974 * \ /
2975 * B (yca)
2976 * |
2977 * A
2979 * 'got update' only handles linear cases:
2980 * Update forwards in time: A (base/yca) - B - C - D (commit)
2981 * Update backwards in time: D (base) - C - B - A (commit/yca)
2983 if (allow_forwards_in_time_only) {
2984 if (got_object_id_cmp(base_commit_id, yca_id) != 0)
2985 return got_error(GOT_ERR_ANCESTRY);
2986 } else if (got_object_id_cmp(commit_id, yca_id) != 0 &&
2987 got_object_id_cmp(base_commit_id, yca_id) != 0)
2988 return got_error(GOT_ERR_ANCESTRY);
2990 free(yca_id);
2991 return NULL;
2994 static const struct got_error *
2995 check_same_branch(struct got_object_id *commit_id,
2996 struct got_reference *head_ref, struct got_repository *repo)
2998 const struct got_error *err = NULL;
2999 struct got_commit_graph *graph = NULL;
3000 struct got_object_id *head_commit_id = NULL;
3002 err = got_ref_resolve(&head_commit_id, repo, head_ref);
3003 if (err)
3004 goto done;
3006 if (got_object_id_cmp(head_commit_id, commit_id) == 0)
3007 goto done;
3009 err = got_commit_graph_open(&graph, "/", 1);
3010 if (err)
3011 goto done;
3013 err = got_commit_graph_bfsort(graph, head_commit_id, repo,
3014 check_cancelled, NULL);
3015 if (err)
3016 goto done;
3018 for (;;) {
3019 struct got_object_id id;
3021 err = got_commit_graph_iter_next(&id, graph, repo,
3022 check_cancelled, NULL);
3023 if (err) {
3024 if (err->code == GOT_ERR_ITER_COMPLETED)
3025 err = got_error(GOT_ERR_ANCESTRY);
3026 break;
3029 if (got_object_id_cmp(&id, commit_id) == 0)
3030 break;
3032 done:
3033 if (graph)
3034 got_commit_graph_close(graph);
3035 free(head_commit_id);
3036 return err;
3039 static const struct got_error *
3040 checkout_ancestry_error(struct got_reference *ref, const char *commit_id_str)
3042 static char msg[512];
3043 const char *branch_name;
3045 if (got_ref_is_symbolic(ref))
3046 branch_name = got_ref_get_symref_target(ref);
3047 else
3048 branch_name = got_ref_get_name(ref);
3050 if (strncmp("refs/heads/", branch_name, 11) == 0)
3051 branch_name += 11;
3053 snprintf(msg, sizeof(msg),
3054 "target commit is not contained in branch '%s'; "
3055 "the branch to use must be specified with -b; "
3056 "if necessary a new branch can be created for "
3057 "this commit with 'got branch -c %s BRANCH_NAME'",
3058 branch_name, commit_id_str);
3060 return got_error_msg(GOT_ERR_ANCESTRY, msg);
3063 static const struct got_error *
3064 cmd_checkout(int argc, char *argv[])
3066 const struct got_error *close_err, *error = NULL;
3067 struct got_repository *repo = NULL;
3068 struct got_reference *head_ref = NULL, *ref = NULL;
3069 struct got_worktree *worktree = NULL;
3070 char *repo_path = NULL;
3071 char *worktree_path = NULL;
3072 const char *path_prefix = "";
3073 const char *branch_name = GOT_REF_HEAD, *refname = NULL;
3074 char *commit_id_str = NULL, *keyword_idstr = NULL;
3075 struct got_object_id *commit_id = NULL;
3076 char *cwd = NULL;
3077 int ch, same_path_prefix, allow_nonempty = 0, verbosity = 0;
3078 struct got_pathlist_head paths;
3079 struct got_checkout_progress_arg cpa;
3080 int *pack_fds = NULL;
3082 TAILQ_INIT(&paths);
3084 #ifndef PROFILE
3085 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
3086 "unveil", NULL) == -1)
3087 err(1, "pledge");
3088 #endif
3090 while ((ch = getopt(argc, argv, "b:c:Ep:q")) != -1) {
3091 switch (ch) {
3092 case 'b':
3093 branch_name = optarg;
3094 break;
3095 case 'c':
3096 commit_id_str = strdup(optarg);
3097 if (commit_id_str == NULL)
3098 return got_error_from_errno("strdup");
3099 break;
3100 case 'E':
3101 allow_nonempty = 1;
3102 break;
3103 case 'p':
3104 path_prefix = optarg;
3105 break;
3106 case 'q':
3107 verbosity = -1;
3108 break;
3109 default:
3110 usage_checkout();
3111 /* NOTREACHED */
3115 argc -= optind;
3116 argv += optind;
3118 if (argc == 1) {
3119 char *base, *dotgit;
3120 const char *path;
3121 repo_path = realpath(argv[0], NULL);
3122 if (repo_path == NULL)
3123 return got_error_from_errno2("realpath", argv[0]);
3124 cwd = getcwd(NULL, 0);
3125 if (cwd == NULL) {
3126 error = got_error_from_errno("getcwd");
3127 goto done;
3129 if (path_prefix[0])
3130 path = path_prefix;
3131 else
3132 path = repo_path;
3133 error = got_path_basename(&base, path);
3134 if (error)
3135 goto done;
3136 dotgit = strstr(base, ".git");
3137 if (dotgit)
3138 *dotgit = '\0';
3139 if (asprintf(&worktree_path, "%s/%s", cwd, base) == -1) {
3140 error = got_error_from_errno("asprintf");
3141 free(base);
3142 goto done;
3144 free(base);
3145 } else if (argc == 2) {
3146 repo_path = realpath(argv[0], NULL);
3147 if (repo_path == NULL) {
3148 error = got_error_from_errno2("realpath", argv[0]);
3149 goto done;
3151 worktree_path = realpath(argv[1], NULL);
3152 if (worktree_path == NULL) {
3153 if (errno != ENOENT) {
3154 error = got_error_from_errno2("realpath",
3155 argv[1]);
3156 goto done;
3158 worktree_path = strdup(argv[1]);
3159 if (worktree_path == NULL) {
3160 error = got_error_from_errno("strdup");
3161 goto done;
3164 } else
3165 usage_checkout();
3167 got_path_strip_trailing_slashes(repo_path);
3168 got_path_strip_trailing_slashes(worktree_path);
3170 if (got_path_is_child(worktree_path, repo_path, strlen(repo_path)) ||
3171 got_path_is_child(repo_path, worktree_path,
3172 strlen(worktree_path))) {
3173 error = got_error_fmt(GOT_ERR_BAD_PATH,
3174 "work tree and repository paths may not overlap: %s",
3175 worktree_path);
3176 goto done;
3179 error = got_repo_pack_fds_open(&pack_fds);
3180 if (error != NULL)
3181 goto done;
3183 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
3184 if (error != NULL)
3185 goto done;
3187 /* Pre-create work tree path for unveil(2) */
3188 error = got_path_mkdir(worktree_path);
3189 if (error) {
3190 if (!(error->code == GOT_ERR_ERRNO && errno == EISDIR) &&
3191 !(error->code == GOT_ERR_ERRNO && errno == EEXIST))
3192 goto done;
3193 if (!allow_nonempty &&
3194 !got_path_dir_is_empty(worktree_path)) {
3195 error = got_error_path(worktree_path,
3196 GOT_ERR_DIR_NOT_EMPTY);
3197 goto done;
3201 error = apply_unveil(got_repo_get_path(repo), 0, worktree_path);
3202 if (error)
3203 goto done;
3205 error = got_ref_open(&head_ref, repo, branch_name, 0);
3206 if (error != NULL)
3207 goto done;
3209 error = got_worktree_init(worktree_path, head_ref, path_prefix,
3210 GOT_WORKTREE_GOT_DIR, repo);
3211 if (error != NULL && !(error->code == GOT_ERR_ERRNO && errno == EEXIST))
3212 goto done;
3214 error = got_worktree_open(&worktree, worktree_path,
3215 GOT_WORKTREE_GOT_DIR);
3216 if (error != NULL)
3217 goto done;
3219 error = got_worktree_match_path_prefix(&same_path_prefix, worktree,
3220 path_prefix);
3221 if (error != NULL)
3222 goto done;
3223 if (!same_path_prefix) {
3224 error = got_error(GOT_ERR_PATH_PREFIX);
3225 goto done;
3228 if (commit_id_str) {
3229 struct got_reflist_head refs;
3230 TAILQ_INIT(&refs);
3231 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
3232 NULL);
3233 if (error)
3234 goto done;
3236 error = got_keyword_to_idstr(&keyword_idstr, commit_id_str,
3237 repo, worktree);
3238 if (error != NULL)
3239 goto done;
3240 if (keyword_idstr != NULL) {
3241 free(commit_id_str);
3242 commit_id_str = keyword_idstr;
3245 error = got_repo_match_object_id(&commit_id, NULL,
3246 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
3247 got_ref_list_free(&refs);
3248 if (error)
3249 goto done;
3250 error = check_linear_ancestry(commit_id,
3251 got_worktree_get_base_commit_id(worktree), 0, repo);
3252 if (error != NULL) {
3253 if (error->code == GOT_ERR_ANCESTRY) {
3254 error = checkout_ancestry_error(
3255 head_ref, commit_id_str);
3257 goto done;
3259 error = check_same_branch(commit_id, head_ref, repo);
3260 if (error) {
3261 if (error->code == GOT_ERR_ANCESTRY) {
3262 error = checkout_ancestry_error(
3263 head_ref, commit_id_str);
3265 goto done;
3267 error = got_worktree_set_base_commit_id(worktree, repo,
3268 commit_id);
3269 if (error)
3270 goto done;
3271 /* Expand potentially abbreviated commit ID string. */
3272 free(commit_id_str);
3273 error = got_object_id_str(&commit_id_str, commit_id);
3274 if (error)
3275 goto done;
3276 } else {
3277 commit_id = got_object_id_dup(
3278 got_worktree_get_base_commit_id(worktree));
3279 if (commit_id == NULL) {
3280 error = got_error_from_errno("got_object_id_dup");
3281 goto done;
3283 error = got_object_id_str(&commit_id_str, commit_id);
3284 if (error)
3285 goto done;
3288 error = got_pathlist_append(&paths, "", NULL);
3289 if (error)
3290 goto done;
3291 cpa.worktree_path = worktree_path;
3292 cpa.had_base_commit_ref_error = 0;
3293 cpa.verbosity = verbosity;
3294 error = got_worktree_checkout_files(worktree, &paths, repo,
3295 checkout_progress, &cpa, check_cancelled, NULL);
3296 if (error != NULL)
3297 goto done;
3299 if (got_ref_is_symbolic(head_ref)) {
3300 error = got_ref_resolve_symbolic(&ref, repo, head_ref);
3301 if (error)
3302 goto done;
3303 refname = got_ref_get_name(ref);
3304 } else
3305 refname = got_ref_get_name(head_ref);
3306 printf("Checked out %s: %s\n", refname, commit_id_str);
3307 printf("Now shut up and hack\n");
3308 if (cpa.had_base_commit_ref_error)
3309 show_worktree_base_ref_warning();
3310 done:
3311 if (pack_fds) {
3312 const struct got_error *pack_err =
3313 got_repo_pack_fds_close(pack_fds);
3314 if (error == NULL)
3315 error = pack_err;
3317 if (head_ref)
3318 got_ref_close(head_ref);
3319 if (ref)
3320 got_ref_close(ref);
3321 if (repo) {
3322 close_err = got_repo_close(repo);
3323 if (error == NULL)
3324 error = close_err;
3326 if (worktree != NULL) {
3327 close_err = got_worktree_close(worktree);
3328 if (error == NULL)
3329 error = close_err;
3331 got_pathlist_free(&paths, GOT_PATHLIST_FREE_NONE);
3332 free(commit_id_str);
3333 free(commit_id);
3334 free(repo_path);
3335 free(worktree_path);
3336 free(cwd);
3337 return error;
3340 struct got_update_progress_arg {
3341 int did_something;
3342 int conflicts;
3343 int obstructed;
3344 int not_updated;
3345 int missing;
3346 int not_deleted;
3347 int unversioned;
3348 int verbosity;
3351 static void
3352 print_update_progress_stats(struct got_update_progress_arg *upa)
3354 if (!upa->did_something)
3355 return;
3357 if (upa->conflicts > 0)
3358 printf("Files with new merge conflicts: %d\n", upa->conflicts);
3359 if (upa->obstructed > 0)
3360 printf("File paths obstructed by a non-regular file: %d\n",
3361 upa->obstructed);
3362 if (upa->not_updated > 0)
3363 printf("Files not updated because of existing merge "
3364 "conflicts: %d\n", upa->not_updated);
3368 * The meaning of some status codes differs between merge-style operations and
3369 * update operations. For example, the ! status code means "file was missing"
3370 * if changes were merged into the work tree, and "missing file was restored"
3371 * if the work tree was updated. This function should be used by any operation
3372 * which merges changes into the work tree without updating the work tree.
3374 static void
3375 print_merge_progress_stats(struct got_update_progress_arg *upa)
3377 if (!upa->did_something)
3378 return;
3380 if (upa->conflicts > 0)
3381 printf("Files with new merge conflicts: %d\n", upa->conflicts);
3382 if (upa->obstructed > 0)
3383 printf("File paths obstructed by a non-regular file: %d\n",
3384 upa->obstructed);
3385 if (upa->missing > 0)
3386 printf("Files which had incoming changes but could not be "
3387 "found in the work tree: %d\n", upa->missing);
3388 if (upa->not_deleted > 0)
3389 printf("Files not deleted due to differences in deleted "
3390 "content: %d\n", upa->not_deleted);
3391 if (upa->unversioned > 0)
3392 printf("Files not merged because an unversioned file was "
3393 "found in the work tree: %d\n", upa->unversioned);
3396 __dead static void
3397 usage_update(void)
3399 fprintf(stderr, "usage: %s update [-q] [-b branch] [-c commit] "
3400 "[path ...]\n", getprogname());
3401 exit(1);
3404 static const struct got_error *
3405 update_progress(void *arg, unsigned char status, const char *path)
3407 struct got_update_progress_arg *upa = arg;
3409 if (status == GOT_STATUS_EXISTS ||
3410 status == GOT_STATUS_BASE_REF_ERR)
3411 return NULL;
3413 upa->did_something = 1;
3415 /* Base commit bump happens silently. */
3416 if (status == GOT_STATUS_BUMP_BASE)
3417 return NULL;
3419 if (status == GOT_STATUS_CONFLICT)
3420 upa->conflicts++;
3421 if (status == GOT_STATUS_OBSTRUCTED)
3422 upa->obstructed++;
3423 if (status == GOT_STATUS_CANNOT_UPDATE)
3424 upa->not_updated++;
3425 if (status == GOT_STATUS_MISSING)
3426 upa->missing++;
3427 if (status == GOT_STATUS_CANNOT_DELETE)
3428 upa->not_deleted++;
3429 if (status == GOT_STATUS_UNVERSIONED)
3430 upa->unversioned++;
3432 while (path[0] == '/')
3433 path++;
3434 if (upa->verbosity >= 0)
3435 printf("%c %s\n", status, path);
3437 return NULL;
3440 static const struct got_error *
3441 switch_head_ref(struct got_reference *head_ref,
3442 struct got_object_id *commit_id, struct got_worktree *worktree,
3443 struct got_repository *repo)
3445 const struct got_error *err = NULL;
3446 char *base_id_str;
3447 int ref_has_moved = 0;
3449 /* Trivial case: switching between two different references. */
3450 if (strcmp(got_ref_get_name(head_ref),
3451 got_worktree_get_head_ref_name(worktree)) != 0) {
3452 printf("Switching work tree from %s to %s\n",
3453 got_worktree_get_head_ref_name(worktree),
3454 got_ref_get_name(head_ref));
3455 return got_worktree_set_head_ref(worktree, head_ref);
3458 err = check_linear_ancestry(commit_id,
3459 got_worktree_get_base_commit_id(worktree), 0, repo);
3460 if (err) {
3461 if (err->code != GOT_ERR_ANCESTRY)
3462 return err;
3463 ref_has_moved = 1;
3465 if (!ref_has_moved)
3466 return NULL;
3468 /* Switching to a rebased branch with the same reference name. */
3469 err = got_object_id_str(&base_id_str,
3470 got_worktree_get_base_commit_id(worktree));
3471 if (err)
3472 return err;
3473 printf("Reference %s now points at a different branch\n",
3474 got_worktree_get_head_ref_name(worktree));
3475 printf("Switching work tree from %s to %s\n", base_id_str,
3476 got_worktree_get_head_ref_name(worktree));
3477 return NULL;
3480 static const struct got_error *
3481 check_rebase_or_histedit_in_progress(struct got_worktree *worktree)
3483 const struct got_error *err;
3484 int in_progress;
3486 err = got_worktree_rebase_in_progress(&in_progress, worktree);
3487 if (err)
3488 return err;
3489 if (in_progress)
3490 return got_error(GOT_ERR_REBASING);
3492 err = got_worktree_histedit_in_progress(&in_progress, worktree);
3493 if (err)
3494 return err;
3495 if (in_progress)
3496 return got_error(GOT_ERR_HISTEDIT_BUSY);
3498 return NULL;
3501 static const struct got_error *
3502 check_merge_in_progress(struct got_worktree *worktree,
3503 struct got_repository *repo)
3505 const struct got_error *err;
3506 int in_progress;
3508 err = got_worktree_merge_in_progress(&in_progress, worktree, repo);
3509 if (err)
3510 return err;
3511 if (in_progress)
3512 return got_error(GOT_ERR_MERGE_BUSY);
3514 return NULL;
3517 static const struct got_error *
3518 get_worktree_paths_from_argv(struct got_pathlist_head *paths, int argc,
3519 char *argv[], struct got_worktree *worktree)
3521 const struct got_error *err = NULL;
3522 char *path;
3523 struct got_pathlist_entry *new;
3524 int i;
3526 if (argc == 0) {
3527 path = strdup("");
3528 if (path == NULL)
3529 return got_error_from_errno("strdup");
3530 return got_pathlist_append(paths, path, NULL);
3533 for (i = 0; i < argc; i++) {
3534 err = got_worktree_resolve_path(&path, worktree, argv[i]);
3535 if (err)
3536 break;
3537 err = got_pathlist_insert(&new, paths, path, NULL);
3538 if (err || new == NULL /* duplicate */) {
3539 free(path);
3540 if (err)
3541 break;
3545 return err;
3548 static const struct got_error *
3549 wrap_not_worktree_error(const struct got_error *orig_err,
3550 const char *cmdname, const char *path)
3552 const struct got_error *err;
3553 struct got_repository *repo;
3554 static char msg[512];
3555 int *pack_fds = NULL;
3557 err = got_repo_pack_fds_open(&pack_fds);
3558 if (err)
3559 return err;
3561 err = got_repo_open(&repo, path, NULL, pack_fds);
3562 if (err)
3563 return orig_err;
3565 snprintf(msg, sizeof(msg),
3566 "'got %s' needs a work tree in addition to a git repository\n"
3567 "Work trees can be checked out from this Git repository with "
3568 "'got checkout'.\n"
3569 "The got(1) manual page contains more information.", cmdname);
3570 err = got_error_msg(GOT_ERR_NOT_WORKTREE, msg);
3571 if (repo) {
3572 const struct got_error *close_err = got_repo_close(repo);
3573 if (err == NULL)
3574 err = close_err;
3576 if (pack_fds) {
3577 const struct got_error *pack_err =
3578 got_repo_pack_fds_close(pack_fds);
3579 if (err == NULL)
3580 err = pack_err;
3582 return err;
3585 static const struct got_error *
3586 cmd_update(int argc, char *argv[])
3588 const struct got_error *close_err, *error = NULL;
3589 struct got_repository *repo = NULL;
3590 struct got_worktree *worktree = NULL;
3591 char *worktree_path = NULL;
3592 struct got_object_id *commit_id = NULL;
3593 char *commit_id_str = NULL;
3594 const char *branch_name = NULL;
3595 struct got_reference *head_ref = NULL;
3596 struct got_pathlist_head paths;
3597 struct got_pathlist_entry *pe;
3598 int ch, verbosity = 0;
3599 struct got_update_progress_arg upa;
3600 int *pack_fds = NULL;
3602 TAILQ_INIT(&paths);
3604 #ifndef PROFILE
3605 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
3606 "unveil", NULL) == -1)
3607 err(1, "pledge");
3608 #endif
3610 while ((ch = getopt(argc, argv, "b:c:q")) != -1) {
3611 switch (ch) {
3612 case 'b':
3613 branch_name = optarg;
3614 break;
3615 case 'c':
3616 commit_id_str = strdup(optarg);
3617 if (commit_id_str == NULL)
3618 return got_error_from_errno("strdup");
3619 break;
3620 case 'q':
3621 verbosity = -1;
3622 break;
3623 default:
3624 usage_update();
3625 /* NOTREACHED */
3629 argc -= optind;
3630 argv += optind;
3632 worktree_path = getcwd(NULL, 0);
3633 if (worktree_path == NULL) {
3634 error = got_error_from_errno("getcwd");
3635 goto done;
3638 error = got_repo_pack_fds_open(&pack_fds);
3639 if (error != NULL)
3640 goto done;
3642 error = got_worktree_open(&worktree, worktree_path,
3643 GOT_WORKTREE_GOT_DIR);
3644 if (error) {
3645 if (error->code == GOT_ERR_NOT_WORKTREE)
3646 error = wrap_not_worktree_error(error, "update",
3647 worktree_path);
3648 goto done;
3651 error = check_rebase_or_histedit_in_progress(worktree);
3652 if (error)
3653 goto done;
3655 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
3656 NULL, pack_fds);
3657 if (error != NULL)
3658 goto done;
3660 error = apply_unveil(got_repo_get_path(repo), 0,
3661 got_worktree_get_root_path(worktree));
3662 if (error)
3663 goto done;
3665 error = check_merge_in_progress(worktree, repo);
3666 if (error)
3667 goto done;
3669 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
3670 if (error)
3671 goto done;
3673 error = got_ref_open(&head_ref, repo, branch_name ? branch_name :
3674 got_worktree_get_head_ref_name(worktree), 0);
3675 if (error != NULL)
3676 goto done;
3677 if (commit_id_str == NULL) {
3678 error = got_ref_resolve(&commit_id, repo, head_ref);
3679 if (error != NULL)
3680 goto done;
3681 error = got_object_id_str(&commit_id_str, commit_id);
3682 if (error != NULL)
3683 goto done;
3684 } else {
3685 struct got_reflist_head refs;
3686 char *keyword_idstr = NULL;
3688 TAILQ_INIT(&refs);
3690 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
3691 NULL);
3692 if (error)
3693 goto done;
3695 error = got_keyword_to_idstr(&keyword_idstr, commit_id_str,
3696 repo, worktree);
3697 if (error != NULL)
3698 goto done;
3699 if (keyword_idstr != NULL) {
3700 free(commit_id_str);
3701 commit_id_str = keyword_idstr;
3704 error = got_repo_match_object_id(&commit_id, NULL,
3705 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
3706 got_ref_list_free(&refs);
3707 free(commit_id_str);
3708 commit_id_str = NULL;
3709 if (error)
3710 goto done;
3711 error = got_object_id_str(&commit_id_str, commit_id);
3712 if (error)
3713 goto done;
3716 if (branch_name) {
3717 struct got_object_id *head_commit_id;
3718 TAILQ_FOREACH(pe, &paths, entry) {
3719 if (pe->path_len == 0)
3720 continue;
3721 error = got_error_msg(GOT_ERR_BAD_PATH,
3722 "switching between branches requires that "
3723 "the entire work tree gets updated");
3724 goto done;
3726 error = got_ref_resolve(&head_commit_id, repo, head_ref);
3727 if (error)
3728 goto done;
3729 error = check_linear_ancestry(commit_id, head_commit_id, 0,
3730 repo);
3731 free(head_commit_id);
3732 if (error != NULL)
3733 goto done;
3734 error = check_same_branch(commit_id, head_ref, repo);
3735 if (error)
3736 goto done;
3737 error = switch_head_ref(head_ref, commit_id, worktree, repo);
3738 if (error)
3739 goto done;
3740 } else {
3741 error = check_linear_ancestry(commit_id,
3742 got_worktree_get_base_commit_id(worktree), 0, repo);
3743 if (error != NULL) {
3744 if (error->code == GOT_ERR_ANCESTRY)
3745 error = got_error(GOT_ERR_BRANCH_MOVED);
3746 goto done;
3748 error = check_same_branch(commit_id, head_ref, repo);
3749 if (error)
3750 goto done;
3753 if (got_object_id_cmp(got_worktree_get_base_commit_id(worktree),
3754 commit_id) != 0) {
3755 error = got_worktree_set_base_commit_id(worktree, repo,
3756 commit_id);
3757 if (error)
3758 goto done;
3761 memset(&upa, 0, sizeof(upa));
3762 upa.verbosity = verbosity;
3763 error = got_worktree_checkout_files(worktree, &paths, repo,
3764 update_progress, &upa, check_cancelled, NULL);
3765 if (error != NULL)
3766 goto done;
3768 if (upa.did_something) {
3769 printf("Updated to %s: %s\n",
3770 got_worktree_get_head_ref_name(worktree), commit_id_str);
3771 } else
3772 printf("Already up-to-date\n");
3774 print_update_progress_stats(&upa);
3775 done:
3776 if (pack_fds) {
3777 const struct got_error *pack_err =
3778 got_repo_pack_fds_close(pack_fds);
3779 if (error == NULL)
3780 error = pack_err;
3782 if (repo) {
3783 close_err = got_repo_close(repo);
3784 if (error == NULL)
3785 error = close_err;
3787 if (worktree != NULL) {
3788 close_err = got_worktree_close(worktree);
3789 if (error == NULL)
3790 error = close_err;
3792 if (head_ref != NULL)
3793 got_ref_close(head_ref);
3794 free(worktree_path);
3795 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
3796 free(commit_id);
3797 free(commit_id_str);
3798 return error;
3801 static const struct got_error *
3802 diff_blobs(struct got_object_id *blob_id1, struct got_object_id *blob_id2,
3803 const char *path, int diff_context, int ignore_whitespace,
3804 int force_text_diff, struct got_diffstat_cb_arg *dsa,
3805 struct got_repository *repo, FILE *outfile)
3807 const struct got_error *err = NULL;
3808 struct got_blob_object *blob1 = NULL, *blob2 = NULL;
3809 FILE *f1 = NULL, *f2 = NULL;
3810 int fd1 = -1, fd2 = -1;
3812 fd1 = got_opentempfd();
3813 if (fd1 == -1)
3814 return got_error_from_errno("got_opentempfd");
3815 fd2 = got_opentempfd();
3816 if (fd2 == -1) {
3817 err = got_error_from_errno("got_opentempfd");
3818 goto done;
3821 if (blob_id1) {
3822 err = got_object_open_as_blob(&blob1, repo, blob_id1, 8192,
3823 fd1);
3824 if (err)
3825 goto done;
3828 err = got_object_open_as_blob(&blob2, repo, blob_id2, 8192, fd2);
3829 if (err)
3830 goto done;
3832 f1 = got_opentemp();
3833 if (f1 == NULL) {
3834 err = got_error_from_errno("got_opentemp");
3835 goto done;
3837 f2 = got_opentemp();
3838 if (f2 == NULL) {
3839 err = got_error_from_errno("got_opentemp");
3840 goto done;
3843 while (path[0] == '/')
3844 path++;
3845 err = got_diff_blob(NULL, NULL, blob1, blob2, f1, f2, path, path,
3846 GOT_DIFF_ALGORITHM_PATIENCE, diff_context, ignore_whitespace,
3847 force_text_diff, dsa, outfile);
3848 done:
3849 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
3850 err = got_error_from_errno("close");
3851 if (blob1)
3852 got_object_blob_close(blob1);
3853 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
3854 err = got_error_from_errno("close");
3855 if (blob2)
3856 got_object_blob_close(blob2);
3857 if (f1 && fclose(f1) == EOF && err == NULL)
3858 err = got_error_from_errno("fclose");
3859 if (f2 && fclose(f2) == EOF && err == NULL)
3860 err = got_error_from_errno("fclose");
3861 return err;
3864 static const struct got_error *
3865 diff_trees(struct got_object_id *tree_id1, struct got_object_id *tree_id2,
3866 const char *path, int diff_context, int ignore_whitespace,
3867 int force_text_diff, struct got_diffstat_cb_arg *dsa,
3868 struct got_repository *repo, FILE *outfile)
3870 const struct got_error *err = NULL;
3871 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
3872 struct got_diff_blob_output_unidiff_arg arg;
3873 FILE *f1 = NULL, *f2 = NULL;
3874 int fd1 = -1, fd2 = -1;
3876 if (tree_id1) {
3877 err = got_object_open_as_tree(&tree1, repo, tree_id1);
3878 if (err)
3879 goto done;
3880 fd1 = got_opentempfd();
3881 if (fd1 == -1) {
3882 err = got_error_from_errno("got_opentempfd");
3883 goto done;
3887 err = got_object_open_as_tree(&tree2, repo, tree_id2);
3888 if (err)
3889 goto done;
3891 f1 = got_opentemp();
3892 if (f1 == NULL) {
3893 err = got_error_from_errno("got_opentemp");
3894 goto done;
3897 f2 = got_opentemp();
3898 if (f2 == NULL) {
3899 err = got_error_from_errno("got_opentemp");
3900 goto done;
3902 fd2 = got_opentempfd();
3903 if (fd2 == -1) {
3904 err = got_error_from_errno("got_opentempfd");
3905 goto done;
3907 arg.diff_context = diff_context;
3908 arg.ignore_whitespace = ignore_whitespace;
3909 arg.force_text_diff = force_text_diff;
3910 arg.diffstat = dsa;
3911 arg.diff_algo = GOT_DIFF_ALGORITHM_PATIENCE;
3912 arg.outfile = outfile;
3913 arg.lines = NULL;
3914 arg.nlines = 0;
3915 while (path[0] == '/')
3916 path++;
3917 err = got_diff_tree(tree1, tree2, f1, f2, fd1, fd2, path, path, repo,
3918 got_diff_blob_output_unidiff, &arg, 1);
3919 done:
3920 if (tree1)
3921 got_object_tree_close(tree1);
3922 if (tree2)
3923 got_object_tree_close(tree2);
3924 if (f1 && fclose(f1) == EOF && err == NULL)
3925 err = got_error_from_errno("fclose");
3926 if (f2 && fclose(f2) == EOF && err == NULL)
3927 err = got_error_from_errno("fclose");
3928 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
3929 err = got_error_from_errno("close");
3930 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
3931 err = got_error_from_errno("close");
3932 return err;
3935 static const struct got_error *
3936 get_changed_paths(struct got_pathlist_head *paths,
3937 struct got_commit_object *commit, struct got_repository *repo,
3938 struct got_diffstat_cb_arg *dsa)
3940 const struct got_error *err = NULL;
3941 struct got_object_id *tree_id1 = NULL, *tree_id2 = NULL;
3942 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
3943 struct got_object_qid *qid;
3944 got_diff_blob_cb cb = got_diff_tree_collect_changed_paths;
3945 FILE *f1 = NULL, *f2 = NULL;
3946 int fd1 = -1, fd2 = -1;
3948 if (dsa) {
3949 cb = got_diff_tree_compute_diffstat;
3951 f1 = got_opentemp();
3952 if (f1 == NULL) {
3953 err = got_error_from_errno("got_opentemp");
3954 goto done;
3956 f2 = got_opentemp();
3957 if (f2 == NULL) {
3958 err = got_error_from_errno("got_opentemp");
3959 goto done;
3961 fd1 = got_opentempfd();
3962 if (fd1 == -1) {
3963 err = got_error_from_errno("got_opentempfd");
3964 goto done;
3966 fd2 = got_opentempfd();
3967 if (fd2 == -1) {
3968 err = got_error_from_errno("got_opentempfd");
3969 goto done;
3973 qid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
3974 if (qid != NULL) {
3975 struct got_commit_object *pcommit;
3976 err = got_object_open_as_commit(&pcommit, repo,
3977 &qid->id);
3978 if (err)
3979 return err;
3981 tree_id1 = got_object_id_dup(
3982 got_object_commit_get_tree_id(pcommit));
3983 if (tree_id1 == NULL) {
3984 got_object_commit_close(pcommit);
3985 return got_error_from_errno("got_object_id_dup");
3987 got_object_commit_close(pcommit);
3991 if (tree_id1) {
3992 err = got_object_open_as_tree(&tree1, repo, tree_id1);
3993 if (err)
3994 goto done;
3997 tree_id2 = got_object_commit_get_tree_id(commit);
3998 err = got_object_open_as_tree(&tree2, repo, tree_id2);
3999 if (err)
4000 goto done;
4002 err = got_diff_tree(tree1, tree2, f1, f2, fd1, fd2, "", "", repo,
4003 cb, dsa ? (void *)dsa : paths, dsa ? 1 : 0);
4004 done:
4005 if (tree1)
4006 got_object_tree_close(tree1);
4007 if (tree2)
4008 got_object_tree_close(tree2);
4009 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
4010 err = got_error_from_errno("close");
4011 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
4012 err = got_error_from_errno("close");
4013 if (f1 && fclose(f1) == EOF && err == NULL)
4014 err = got_error_from_errno("fclose");
4015 if (f2 && fclose(f2) == EOF && err == NULL)
4016 err = got_error_from_errno("fclose");
4017 free(tree_id1);
4018 return err;
4021 static const struct got_error *
4022 print_patch(struct got_commit_object *commit, struct got_object_id *id,
4023 const char *path, int diff_context, struct got_diffstat_cb_arg *dsa,
4024 struct got_repository *repo, FILE *outfile)
4026 const struct got_error *err = NULL;
4027 struct got_commit_object *pcommit = NULL;
4028 char *id_str1 = NULL, *id_str2 = NULL;
4029 struct got_object_id *obj_id1 = NULL, *obj_id2 = NULL;
4030 struct got_object_qid *qid;
4032 qid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
4033 if (qid != NULL) {
4034 err = got_object_open_as_commit(&pcommit, repo,
4035 &qid->id);
4036 if (err)
4037 return err;
4038 err = got_object_id_str(&id_str1, &qid->id);
4039 if (err)
4040 goto done;
4043 err = got_object_id_str(&id_str2, id);
4044 if (err)
4045 goto done;
4047 if (path && path[0] != '\0') {
4048 int obj_type;
4049 err = got_object_id_by_path(&obj_id2, repo, commit, path);
4050 if (err)
4051 goto done;
4052 if (pcommit) {
4053 err = got_object_id_by_path(&obj_id1, repo,
4054 pcommit, path);
4055 if (err) {
4056 if (err->code != GOT_ERR_NO_TREE_ENTRY) {
4057 free(obj_id2);
4058 goto done;
4062 err = got_object_get_type(&obj_type, repo, obj_id2);
4063 if (err) {
4064 free(obj_id2);
4065 goto done;
4067 fprintf(outfile,
4068 "diff %s %s\n", id_str1 ? id_str1 : "/dev/null", id_str2);
4069 fprintf(outfile, "commit - %s\n",
4070 id_str1 ? id_str1 : "/dev/null");
4071 fprintf(outfile, "commit + %s\n", id_str2);
4072 switch (obj_type) {
4073 case GOT_OBJ_TYPE_BLOB:
4074 err = diff_blobs(obj_id1, obj_id2, path, diff_context,
4075 0, 0, dsa, repo, outfile);
4076 break;
4077 case GOT_OBJ_TYPE_TREE:
4078 err = diff_trees(obj_id1, obj_id2, path, diff_context,
4079 0, 0, dsa, repo, outfile);
4080 break;
4081 default:
4082 err = got_error(GOT_ERR_OBJ_TYPE);
4083 break;
4085 free(obj_id1);
4086 free(obj_id2);
4087 } else {
4088 obj_id2 = got_object_commit_get_tree_id(commit);
4089 if (pcommit)
4090 obj_id1 = got_object_commit_get_tree_id(pcommit);
4091 fprintf(outfile,
4092 "diff %s %s\n", id_str1 ? id_str1 : "/dev/null", id_str2);
4093 fprintf(outfile, "commit - %s\n",
4094 id_str1 ? id_str1 : "/dev/null");
4095 fprintf(outfile, "commit + %s\n", id_str2);
4096 err = diff_trees(obj_id1, obj_id2, "", diff_context, 0, 0,
4097 dsa, repo, outfile);
4099 done:
4100 free(id_str1);
4101 free(id_str2);
4102 if (pcommit)
4103 got_object_commit_close(pcommit);
4104 return err;
4107 static char *
4108 get_datestr(time_t *time, char *datebuf)
4110 struct tm mytm, *tm;
4111 char *p, *s;
4113 tm = gmtime_r(time, &mytm);
4114 if (tm == NULL)
4115 return NULL;
4116 s = asctime_r(tm, datebuf);
4117 if (s == NULL)
4118 return NULL;
4119 p = strchr(s, '\n');
4120 if (p)
4121 *p = '\0';
4122 return s;
4125 static const struct got_error *
4126 match_commit(int *have_match, struct got_object_id *id,
4127 struct got_commit_object *commit, regex_t *regex)
4129 const struct got_error *err = NULL;
4130 regmatch_t regmatch;
4131 char *id_str = NULL, *logmsg = NULL;
4133 *have_match = 0;
4135 err = got_object_id_str(&id_str, id);
4136 if (err)
4137 return err;
4139 err = got_object_commit_get_logmsg(&logmsg, commit);
4140 if (err)
4141 goto done;
4143 if (regexec(regex, got_object_commit_get_author(commit), 1,
4144 &regmatch, 0) == 0 ||
4145 regexec(regex, got_object_commit_get_committer(commit), 1,
4146 &regmatch, 0) == 0 ||
4147 regexec(regex, id_str, 1, &regmatch, 0) == 0 ||
4148 regexec(regex, logmsg, 1, &regmatch, 0) == 0)
4149 *have_match = 1;
4150 done:
4151 free(id_str);
4152 free(logmsg);
4153 return err;
4156 static void
4157 match_changed_paths(int *have_match, struct got_pathlist_head *changed_paths,
4158 regex_t *regex)
4160 regmatch_t regmatch;
4161 struct got_pathlist_entry *pe;
4163 *have_match = 0;
4165 TAILQ_FOREACH(pe, changed_paths, entry) {
4166 if (regexec(regex, pe->path, 1, &regmatch, 0) == 0) {
4167 *have_match = 1;
4168 break;
4173 static const struct got_error *
4174 match_patch(int *have_match, struct got_commit_object *commit,
4175 struct got_object_id *id, const char *path, int diff_context,
4176 struct got_repository *repo, regex_t *regex, FILE *f)
4178 const struct got_error *err = NULL;
4179 char *line = NULL;
4180 size_t linesize = 0;
4181 regmatch_t regmatch;
4183 *have_match = 0;
4185 err = got_opentemp_truncate(f);
4186 if (err)
4187 return err;
4189 err = print_patch(commit, id, path, diff_context, NULL, repo, f);
4190 if (err)
4191 goto done;
4193 if (fseeko(f, 0L, SEEK_SET) == -1) {
4194 err = got_error_from_errno("fseeko");
4195 goto done;
4198 while (getline(&line, &linesize, f) != -1) {
4199 if (regexec(regex, line, 1, &regmatch, 0) == 0) {
4200 *have_match = 1;
4201 break;
4204 done:
4205 free(line);
4206 return err;
4209 #define GOT_COMMIT_SEP_STR "-----------------------------------------------\n"
4211 static const struct got_error*
4212 build_refs_str(char **refs_str, struct got_reflist_head *refs,
4213 struct got_object_id *id, struct got_repository *repo,
4214 int local_only)
4216 static const struct got_error *err = NULL;
4217 struct got_reflist_entry *re;
4218 char *s;
4219 const char *name;
4221 *refs_str = NULL;
4223 TAILQ_FOREACH(re, refs, entry) {
4224 struct got_tag_object *tag = NULL;
4225 struct got_object_id *ref_id;
4226 int cmp;
4228 name = got_ref_get_name(re->ref);
4229 if (strcmp(name, GOT_REF_HEAD) == 0)
4230 continue;
4231 if (strncmp(name, "refs/", 5) == 0)
4232 name += 5;
4233 if (strncmp(name, "got/", 4) == 0)
4234 continue;
4235 if (strncmp(name, "heads/", 6) == 0)
4236 name += 6;
4237 if (strncmp(name, "remotes/", 8) == 0) {
4238 if (local_only)
4239 continue;
4240 name += 8;
4241 s = strstr(name, "/" GOT_REF_HEAD);
4242 if (s != NULL && strcmp(s, "/" GOT_REF_HEAD) == 0)
4243 continue;
4245 err = got_ref_resolve(&ref_id, repo, re->ref);
4246 if (err)
4247 break;
4248 if (strncmp(name, "tags/", 5) == 0) {
4249 err = got_object_open_as_tag(&tag, repo, ref_id);
4250 if (err) {
4251 if (err->code != GOT_ERR_OBJ_TYPE) {
4252 free(ref_id);
4253 break;
4255 /* Ref points at something other than a tag. */
4256 err = NULL;
4257 tag = NULL;
4260 cmp = got_object_id_cmp(tag ?
4261 got_object_tag_get_object_id(tag) : ref_id, id);
4262 free(ref_id);
4263 if (tag)
4264 got_object_tag_close(tag);
4265 if (cmp != 0)
4266 continue;
4267 s = *refs_str;
4268 if (asprintf(refs_str, "%s%s%s", s ? s : "",
4269 s ? ", " : "", name) == -1) {
4270 err = got_error_from_errno("asprintf");
4271 free(s);
4272 *refs_str = NULL;
4273 break;
4275 free(s);
4278 return err;
4281 static const struct got_error *
4282 print_commit_oneline(struct got_commit_object *commit, struct got_object_id *id,
4283 struct got_repository *repo, struct got_reflist_object_id_map *refs_idmap)
4285 const struct got_error *err = NULL;
4286 char *ref_str = NULL, *id_str = NULL, *logmsg0 = NULL;
4287 char *comma, *s, *nl;
4288 struct got_reflist_head *refs;
4289 char datebuf[12]; /* YYYY-MM-DD + SPACE + NUL */
4290 struct tm tm;
4291 time_t committer_time;
4293 refs = got_reflist_object_id_map_lookup(refs_idmap, id);
4294 if (refs) {
4295 err = build_refs_str(&ref_str, refs, id, repo, 1);
4296 if (err)
4297 return err;
4299 /* Display the first matching ref only. */
4300 if (ref_str && (comma = strchr(ref_str, ',')) != NULL)
4301 *comma = '\0';
4304 if (ref_str == NULL) {
4305 err = got_object_id_str(&id_str, id);
4306 if (err)
4307 return err;
4310 committer_time = got_object_commit_get_committer_time(commit);
4311 if (gmtime_r(&committer_time, &tm) == NULL) {
4312 err = got_error_from_errno("gmtime_r");
4313 goto done;
4315 if (strftime(datebuf, sizeof(datebuf), "%F ", &tm) == 0) {
4316 err = got_error(GOT_ERR_NO_SPACE);
4317 goto done;
4320 err = got_object_commit_get_logmsg(&logmsg0, commit);
4321 if (err)
4322 goto done;
4324 s = logmsg0;
4325 while (isspace((unsigned char)s[0]))
4326 s++;
4328 nl = strchr(s, '\n');
4329 if (nl) {
4330 *nl = '\0';
4333 if (ref_str)
4334 printf("%s%-7s %s\n", datebuf, ref_str, s);
4335 else
4336 printf("%s%.7s %s\n", datebuf, id_str, s);
4338 if (fflush(stdout) != 0 && err == NULL)
4339 err = got_error_from_errno("fflush");
4340 done:
4341 free(id_str);
4342 free(ref_str);
4343 free(logmsg0);
4344 return err;
4347 static const struct got_error *
4348 print_diffstat(struct got_diffstat_cb_arg *dsa, const char *header)
4350 struct got_pathlist_entry *pe;
4352 if (header != NULL)
4353 printf("%s\n", header);
4355 TAILQ_FOREACH(pe, dsa->paths, entry) {
4356 struct got_diff_changed_path *cp = pe->data;
4357 int pad = dsa->max_path_len - pe->path_len + 1;
4359 printf(" %c %s%*c | %*d+ %*d-\n", cp->status, pe->path, pad,
4360 ' ', dsa->add_cols + 1, cp->add, dsa->rm_cols + 1, cp->rm);
4362 printf("\n%d file%s changed, %d insertion%s(+), %d deletion%s(-)\n\n",
4363 dsa->nfiles, dsa->nfiles > 1 ? "s" : "", dsa->ins,
4364 dsa->ins != 1 ? "s" : "", dsa->del, dsa->del != 1 ? "s" : "");
4366 if (fflush(stdout) != 0)
4367 return got_error_from_errno("fflush");
4369 return NULL;
4372 static const struct got_error *
4373 printfile(FILE *f)
4375 char buf[8192];
4376 size_t r;
4378 if (fseeko(f, 0L, SEEK_SET) == -1)
4379 return got_error_from_errno("fseek");
4381 for (;;) {
4382 r = fread(buf, 1, sizeof(buf), f);
4383 if (r == 0) {
4384 if (ferror(f))
4385 return got_error_from_errno("fread");
4386 if (feof(f))
4387 break;
4389 if (fwrite(buf, 1, r, stdout) != r)
4390 return got_ferror(stdout, GOT_ERR_IO);
4393 return NULL;
4396 static const struct got_error *
4397 print_commit(struct got_commit_object *commit, struct got_object_id *id,
4398 struct got_repository *repo, const char *path,
4399 struct got_pathlist_head *changed_paths,
4400 struct got_diffstat_cb_arg *diffstat, int show_patch, int diff_context,
4401 struct got_reflist_object_id_map *refs_idmap, const char *custom_refs_str,
4402 const char *prefix)
4404 const struct got_error *err = NULL;
4405 FILE *f = NULL;
4406 char *id_str, *datestr, *logmsg0, *logmsg, *line;
4407 char datebuf[26];
4408 time_t committer_time;
4409 const char *author, *committer;
4410 char *refs_str = NULL;
4412 err = got_object_id_str(&id_str, id);
4413 if (err)
4414 return err;
4416 if (custom_refs_str == NULL) {
4417 struct got_reflist_head *refs;
4418 refs = got_reflist_object_id_map_lookup(refs_idmap, id);
4419 if (refs) {
4420 err = build_refs_str(&refs_str, refs, id, repo, 0);
4421 if (err)
4422 goto done;
4426 printf(GOT_COMMIT_SEP_STR);
4427 if (custom_refs_str)
4428 printf("%s %s (%s)\n", prefix ? prefix : "commit", id_str,
4429 custom_refs_str);
4430 else
4431 printf("%s %s%s%s%s\n", prefix ? prefix : "commit", id_str,
4432 refs_str ? " (" : "", refs_str ? refs_str : "",
4433 refs_str ? ")" : "");
4434 free(id_str);
4435 id_str = NULL;
4436 free(refs_str);
4437 refs_str = NULL;
4438 printf("from: %s\n", got_object_commit_get_author(commit));
4439 author = got_object_commit_get_author(commit);
4440 committer = got_object_commit_get_committer(commit);
4441 if (strcmp(author, committer) != 0)
4442 printf("via: %s\n", committer);
4443 committer_time = got_object_commit_get_committer_time(commit);
4444 datestr = get_datestr(&committer_time, datebuf);
4445 if (datestr)
4446 printf("date: %s UTC\n", datestr);
4447 if (got_object_commit_get_nparents(commit) > 1) {
4448 const struct got_object_id_queue *parent_ids;
4449 struct got_object_qid *qid;
4450 int n = 1;
4451 parent_ids = got_object_commit_get_parent_ids(commit);
4452 STAILQ_FOREACH(qid, parent_ids, entry) {
4453 err = got_object_id_str(&id_str, &qid->id);
4454 if (err)
4455 goto done;
4456 printf("parent %d: %s\n", n++, id_str);
4457 free(id_str);
4458 id_str = NULL;
4462 err = got_object_commit_get_logmsg(&logmsg0, commit);
4463 if (err)
4464 goto done;
4466 logmsg = logmsg0;
4467 do {
4468 line = strsep(&logmsg, "\n");
4469 if (line)
4470 printf(" %s\n", line);
4471 } while (line);
4472 free(logmsg0);
4474 if (changed_paths && diffstat == NULL) {
4475 struct got_pathlist_entry *pe;
4477 TAILQ_FOREACH(pe, changed_paths, entry) {
4478 struct got_diff_changed_path *cp = pe->data;
4480 printf(" %c %s\n", cp->status, pe->path);
4482 printf("\n");
4484 if (show_patch) {
4485 if (diffstat) {
4486 f = got_opentemp();
4487 if (f == NULL) {
4488 err = got_error_from_errno("got_opentemp");
4489 goto done;
4493 err = print_patch(commit, id, path, diff_context, diffstat,
4494 repo, diffstat == NULL ? stdout : f);
4495 if (err)
4496 goto done;
4498 if (diffstat) {
4499 err = print_diffstat(diffstat, NULL);
4500 if (err)
4501 goto done;
4502 if (show_patch) {
4503 err = printfile(f);
4504 if (err)
4505 goto done;
4508 if (show_patch)
4509 printf("\n");
4511 if (fflush(stdout) != 0 && err == NULL)
4512 err = got_error_from_errno("fflush");
4513 done:
4514 if (f && fclose(f) == EOF && err == NULL)
4515 err = got_error_from_errno("fclose");
4516 free(id_str);
4517 free(refs_str);
4518 return err;
4521 static const struct got_error *
4522 print_commits(struct got_object_id *root_id, struct got_object_id *end_id,
4523 struct got_repository *repo, const char *path, int show_changed_paths,
4524 int show_diffstat, int show_patch, const char *search_pattern,
4525 int diff_context, int limit, int log_branches, int reverse_display_order,
4526 struct got_reflist_object_id_map *refs_idmap, int one_line, int toposort,
4527 FILE *tmpfile)
4529 const struct got_error *err;
4530 struct got_commit_graph *graph;
4531 regex_t regex;
4532 int have_match;
4533 struct got_object_id_queue reversed_commits;
4534 struct got_object_qid *qid;
4535 struct got_commit_object *commit;
4536 struct got_pathlist_head changed_paths;
4538 STAILQ_INIT(&reversed_commits);
4539 TAILQ_INIT(&changed_paths);
4541 if (search_pattern && regcomp(&regex, search_pattern,
4542 REG_EXTENDED | REG_NOSUB | REG_NEWLINE))
4543 return got_error_msg(GOT_ERR_REGEX, search_pattern);
4545 err = got_commit_graph_open(&graph, path, !log_branches);
4546 if (err)
4547 return err;
4548 if (log_branches && toposort) {
4549 err = got_commit_graph_toposort(graph, root_id, repo,
4550 check_cancelled, NULL);
4551 } else {
4552 err = got_commit_graph_bfsort(graph, root_id, repo,
4553 check_cancelled, NULL);
4555 if (err)
4556 goto done;
4557 for (;;) {
4558 struct got_object_id id;
4559 struct got_diffstat_cb_arg dsa = { 0, 0, 0, 0, 0, 0,
4560 &changed_paths, 0, 0, GOT_DIFF_ALGORITHM_PATIENCE };
4562 if (sigint_received || sigpipe_received)
4563 break;
4565 err = got_commit_graph_iter_next(&id, graph, repo,
4566 check_cancelled, NULL);
4567 if (err) {
4568 if (err->code == GOT_ERR_ITER_COMPLETED)
4569 err = NULL;
4570 break;
4573 err = got_object_open_as_commit(&commit, repo, &id);
4574 if (err)
4575 break;
4577 if (((show_changed_paths && !show_diffstat) ||
4578 (show_diffstat && !show_patch))
4579 && !reverse_display_order) {
4580 err = get_changed_paths(&changed_paths, commit, repo,
4581 show_diffstat ? &dsa : NULL);
4582 if (err)
4583 break;
4586 if (search_pattern) {
4587 err = match_commit(&have_match, &id, commit, &regex);
4588 if (err) {
4589 got_object_commit_close(commit);
4590 break;
4592 if (have_match == 0 && show_changed_paths)
4593 match_changed_paths(&have_match,
4594 &changed_paths, &regex);
4595 if (have_match == 0 && show_patch) {
4596 err = match_patch(&have_match, commit, &id,
4597 path, diff_context, repo, &regex, tmpfile);
4598 if (err)
4599 break;
4601 if (have_match == 0) {
4602 got_object_commit_close(commit);
4603 got_pathlist_free(&changed_paths,
4604 GOT_PATHLIST_FREE_ALL);
4605 continue;
4609 if (reverse_display_order) {
4610 err = got_object_qid_alloc(&qid, &id);
4611 if (err)
4612 break;
4613 STAILQ_INSERT_HEAD(&reversed_commits, qid, entry);
4614 got_object_commit_close(commit);
4615 } else {
4616 if (one_line)
4617 err = print_commit_oneline(commit, &id,
4618 repo, refs_idmap);
4619 else
4620 err = print_commit(commit, &id, repo, path,
4621 (show_changed_paths || show_diffstat) ?
4622 &changed_paths : NULL,
4623 show_diffstat ? &dsa : NULL, show_patch,
4624 diff_context, refs_idmap, NULL, NULL);
4625 got_object_commit_close(commit);
4626 if (err)
4627 break;
4629 if ((limit && --limit == 0) ||
4630 (end_id && got_object_id_cmp(&id, end_id) == 0))
4631 break;
4633 got_pathlist_free(&changed_paths, GOT_PATHLIST_FREE_ALL);
4635 if (reverse_display_order) {
4636 STAILQ_FOREACH(qid, &reversed_commits, entry) {
4637 struct got_diffstat_cb_arg dsa = { 0, 0, 0, 0, 0, 0,
4638 &changed_paths, 0, 0, GOT_DIFF_ALGORITHM_PATIENCE };
4640 err = got_object_open_as_commit(&commit, repo,
4641 &qid->id);
4642 if (err)
4643 break;
4644 if ((show_changed_paths && !show_diffstat) ||
4645 (show_diffstat && !show_patch)) {
4646 err = get_changed_paths(&changed_paths, commit,
4647 repo, show_diffstat ? &dsa : NULL);
4648 if (err)
4649 break;
4651 if (one_line)
4652 err = print_commit_oneline(commit, &qid->id,
4653 repo, refs_idmap);
4654 else
4655 err = print_commit(commit, &qid->id, repo, path,
4656 (show_changed_paths || show_diffstat) ?
4657 &changed_paths : NULL,
4658 show_diffstat ? &dsa : NULL, show_patch,
4659 diff_context, refs_idmap, NULL, NULL);
4660 got_object_commit_close(commit);
4661 if (err)
4662 break;
4663 got_pathlist_free(&changed_paths, GOT_PATHLIST_FREE_ALL);
4666 done:
4667 while (!STAILQ_EMPTY(&reversed_commits)) {
4668 qid = STAILQ_FIRST(&reversed_commits);
4669 STAILQ_REMOVE_HEAD(&reversed_commits, entry);
4670 got_object_qid_free(qid);
4672 got_pathlist_free(&changed_paths, GOT_PATHLIST_FREE_ALL);
4673 if (search_pattern)
4674 regfree(&regex);
4675 got_commit_graph_close(graph);
4676 return err;
4679 __dead static void
4680 usage_log(void)
4682 fprintf(stderr, "usage: %s log [-bdPpRst] [-C number] [-c commit] "
4683 "[-l N] [-r repository-path] [-S search-pattern] [-x commit] "
4684 "[path]\n", getprogname());
4685 exit(1);
4688 static int
4689 get_default_log_limit(void)
4691 const char *got_default_log_limit;
4692 long long n;
4693 const char *errstr;
4695 got_default_log_limit = getenv("GOT_LOG_DEFAULT_LIMIT");
4696 if (got_default_log_limit == NULL)
4697 return 0;
4698 n = strtonum(got_default_log_limit, 0, INT_MAX, &errstr);
4699 if (errstr != NULL)
4700 return 0;
4701 return n;
4704 static const struct got_error *
4705 cmd_log(int argc, char *argv[])
4707 const struct got_error *error;
4708 struct got_repository *repo = NULL;
4709 struct got_worktree *worktree = NULL;
4710 struct got_object_id *start_id = NULL, *end_id = NULL;
4711 char *repo_path = NULL, *path = NULL, *cwd = NULL, *in_repo_path = NULL;
4712 char *keyword_idstr = NULL;
4713 const char *start_commit = NULL, *end_commit = NULL;
4714 const char *search_pattern = NULL;
4715 int diff_context = -1, ch;
4716 int show_changed_paths = 0, show_patch = 0, limit = 0, log_branches = 0;
4717 int show_diffstat = 0, reverse_display_order = 0, one_line = 0;
4718 int toposort = 0;
4719 const char *errstr;
4720 struct got_reflist_head refs;
4721 struct got_reflist_object_id_map *refs_idmap = NULL;
4722 FILE *tmpfile = NULL;
4723 int *pack_fds = NULL;
4725 TAILQ_INIT(&refs);
4727 #ifndef PROFILE
4728 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
4729 NULL)
4730 == -1)
4731 err(1, "pledge");
4732 #endif
4734 limit = get_default_log_limit();
4736 while ((ch = getopt(argc, argv, "bC:c:dl:PpRr:S:stx:")) != -1) {
4737 switch (ch) {
4738 case 'b':
4739 log_branches = 1;
4740 break;
4741 case 'C':
4742 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
4743 &errstr);
4744 if (errstr != NULL)
4745 errx(1, "number of context lines is %s: %s",
4746 errstr, optarg);
4747 break;
4748 case 'c':
4749 start_commit = optarg;
4750 break;
4751 case 'd':
4752 show_diffstat = 1;
4753 break;
4754 case 'l':
4755 limit = strtonum(optarg, 0, INT_MAX, &errstr);
4756 if (errstr != NULL)
4757 errx(1, "number of commits is %s: %s",
4758 errstr, optarg);
4759 break;
4760 case 'P':
4761 show_changed_paths = 1;
4762 break;
4763 case 'p':
4764 show_patch = 1;
4765 break;
4766 case 'R':
4767 reverse_display_order = 1;
4768 break;
4769 case 'r':
4770 repo_path = realpath(optarg, NULL);
4771 if (repo_path == NULL)
4772 return got_error_from_errno2("realpath",
4773 optarg);
4774 got_path_strip_trailing_slashes(repo_path);
4775 break;
4776 case 'S':
4777 search_pattern = optarg;
4778 break;
4779 case 's':
4780 one_line = 1;
4781 break;
4782 case 't':
4783 toposort = 1;
4784 break;
4785 case 'x':
4786 end_commit = optarg;
4787 break;
4788 default:
4789 usage_log();
4790 /* NOTREACHED */
4794 argc -= optind;
4795 argv += optind;
4797 if (diff_context == -1)
4798 diff_context = 3;
4799 else if (!show_patch)
4800 errx(1, "-C requires -p");
4802 if (one_line && (show_patch || show_changed_paths || show_diffstat))
4803 errx(1, "cannot use -s with -d, -p or -P");
4805 cwd = getcwd(NULL, 0);
4806 if (cwd == NULL) {
4807 error = got_error_from_errno("getcwd");
4808 goto done;
4811 error = got_repo_pack_fds_open(&pack_fds);
4812 if (error != NULL)
4813 goto done;
4815 if (repo_path == NULL) {
4816 error = got_worktree_open(&worktree, cwd,
4817 GOT_WORKTREE_GOT_DIR);
4818 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4819 goto done;
4820 error = NULL;
4823 if (argc == 1) {
4824 if (worktree) {
4825 error = got_worktree_resolve_path(&path, worktree,
4826 argv[0]);
4827 if (error)
4828 goto done;
4829 } else {
4830 path = strdup(argv[0]);
4831 if (path == NULL) {
4832 error = got_error_from_errno("strdup");
4833 goto done;
4836 } else if (argc != 0)
4837 usage_log();
4839 if (repo_path == NULL) {
4840 repo_path = worktree ?
4841 strdup(got_worktree_get_repo_path(worktree)) : strdup(cwd);
4843 if (repo_path == NULL) {
4844 error = got_error_from_errno("strdup");
4845 goto done;
4848 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
4849 if (error != NULL)
4850 goto done;
4852 error = apply_unveil(got_repo_get_path(repo), 1,
4853 worktree ? got_worktree_get_root_path(worktree) : NULL);
4854 if (error)
4855 goto done;
4857 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
4858 if (error)
4859 goto done;
4861 error = got_reflist_object_id_map_create(&refs_idmap, &refs, repo);
4862 if (error)
4863 goto done;
4865 if (start_commit == NULL) {
4866 struct got_reference *head_ref;
4867 struct got_commit_object *commit = NULL;
4868 error = got_ref_open(&head_ref, repo,
4869 worktree ? got_worktree_get_head_ref_name(worktree)
4870 : GOT_REF_HEAD, 0);
4871 if (error != NULL)
4872 goto done;
4873 error = got_ref_resolve(&start_id, repo, head_ref);
4874 got_ref_close(head_ref);
4875 if (error != NULL)
4876 goto done;
4877 error = got_object_open_as_commit(&commit, repo,
4878 start_id);
4879 if (error != NULL)
4880 goto done;
4881 got_object_commit_close(commit);
4882 } else {
4883 error = got_keyword_to_idstr(&keyword_idstr, start_commit,
4884 repo, worktree);
4885 if (error != NULL)
4886 goto done;
4887 if (keyword_idstr != NULL)
4888 start_commit = keyword_idstr;
4890 error = got_repo_match_object_id(&start_id, NULL,
4891 start_commit, GOT_OBJ_TYPE_COMMIT, &refs, repo);
4892 if (error != NULL)
4893 goto done;
4895 if (end_commit != NULL) {
4896 error = got_keyword_to_idstr(&keyword_idstr, end_commit,
4897 repo, worktree);
4898 if (error != NULL)
4899 goto done;
4900 if (keyword_idstr != NULL)
4901 end_commit = keyword_idstr;
4903 error = got_repo_match_object_id(&end_id, NULL,
4904 end_commit, GOT_OBJ_TYPE_COMMIT, &refs, repo);
4905 if (error != NULL)
4906 goto done;
4909 if (worktree) {
4911 * If a path was specified on the command line it was resolved
4912 * to a path in the work tree above. Prepend the work tree's
4913 * path prefix to obtain the corresponding in-repository path.
4915 if (path) {
4916 const char *prefix;
4917 prefix = got_worktree_get_path_prefix(worktree);
4918 if (asprintf(&in_repo_path, "%s%s%s", prefix,
4919 (path[0] != '\0') ? "/" : "", path) == -1) {
4920 error = got_error_from_errno("asprintf");
4921 goto done;
4924 } else
4925 error = got_repo_map_path(&in_repo_path, repo,
4926 path ? path : "");
4927 if (error != NULL)
4928 goto done;
4929 if (in_repo_path) {
4930 free(path);
4931 path = in_repo_path;
4934 if (worktree) {
4935 /* Release work tree lock. */
4936 got_worktree_close(worktree);
4937 worktree = NULL;
4940 if (search_pattern && show_patch) {
4941 tmpfile = got_opentemp();
4942 if (tmpfile == NULL) {
4943 error = got_error_from_errno("got_opentemp");
4944 goto done;
4948 error = print_commits(start_id, end_id, repo, path ? path : "",
4949 show_changed_paths, show_diffstat, show_patch, search_pattern,
4950 diff_context, limit, log_branches, reverse_display_order,
4951 refs_idmap, one_line, toposort, tmpfile);
4952 done:
4953 free(path);
4954 free(repo_path);
4955 free(cwd);
4956 free(start_id);
4957 free(end_id);
4958 free(keyword_idstr);
4959 if (worktree)
4960 got_worktree_close(worktree);
4961 if (repo) {
4962 const struct got_error *close_err = got_repo_close(repo);
4963 if (error == NULL)
4964 error = close_err;
4966 if (pack_fds) {
4967 const struct got_error *pack_err =
4968 got_repo_pack_fds_close(pack_fds);
4969 if (error == NULL)
4970 error = pack_err;
4972 if (refs_idmap)
4973 got_reflist_object_id_map_free(refs_idmap);
4974 if (tmpfile && fclose(tmpfile) == EOF && error == NULL)
4975 error = got_error_from_errno("fclose");
4976 got_ref_list_free(&refs);
4977 return error;
4980 __dead static void
4981 usage_diff(void)
4983 fprintf(stderr, "usage: %s diff [-adPsw] [-C number] [-c commit] "
4984 "[-r repository-path] [object1 object2 | path ...]\n",
4985 getprogname());
4986 exit(1);
4989 struct print_diff_arg {
4990 struct got_repository *repo;
4991 struct got_worktree *worktree;
4992 struct got_diffstat_cb_arg *diffstat;
4993 int diff_context;
4994 const char *id_str;
4995 int header_shown;
4996 int diff_staged;
4997 enum got_diff_algorithm diff_algo;
4998 int ignore_whitespace;
4999 int force_text_diff;
5000 FILE *f1;
5001 FILE *f2;
5002 FILE *outfile;
5006 * Create a file which contains the target path of a symlink so we can feed
5007 * it as content to the diff engine.
5009 static const struct got_error *
5010 get_symlink_target_file(int *fd, int dirfd, const char *de_name,
5011 const char *abspath)
5013 const struct got_error *err = NULL;
5014 char target_path[PATH_MAX];
5015 ssize_t target_len, outlen;
5017 *fd = -1;
5019 if (dirfd != -1) {
5020 target_len = readlinkat(dirfd, de_name, target_path, PATH_MAX);
5021 if (target_len == -1)
5022 return got_error_from_errno2("readlinkat", abspath);
5023 } else {
5024 target_len = readlink(abspath, target_path, PATH_MAX);
5025 if (target_len == -1)
5026 return got_error_from_errno2("readlink", abspath);
5029 *fd = got_opentempfd();
5030 if (*fd == -1)
5031 return got_error_from_errno("got_opentempfd");
5033 outlen = write(*fd, target_path, target_len);
5034 if (outlen == -1) {
5035 err = got_error_from_errno("got_opentempfd");
5036 goto done;
5039 if (lseek(*fd, 0, SEEK_SET) == -1) {
5040 err = got_error_from_errno2("lseek", abspath);
5041 goto done;
5043 done:
5044 if (err) {
5045 close(*fd);
5046 *fd = -1;
5048 return err;
5051 static const struct got_error *
5052 print_diff(void *arg, unsigned char status, unsigned char staged_status,
5053 const char *path, struct got_object_id *blob_id,
5054 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
5055 int dirfd, const char *de_name)
5057 struct print_diff_arg *a = arg;
5058 const struct got_error *err = NULL;
5059 struct got_blob_object *blob1 = NULL;
5060 int fd = -1, fd1 = -1, fd2 = -1;
5061 FILE *f2 = NULL;
5062 char *abspath = NULL, *label1 = NULL;
5063 struct stat sb;
5064 off_t size1 = 0;
5065 int f2_exists = 0;
5067 memset(&sb, 0, sizeof(sb));
5069 if (a->diff_staged) {
5070 if (staged_status != GOT_STATUS_MODIFY &&
5071 staged_status != GOT_STATUS_ADD &&
5072 staged_status != GOT_STATUS_DELETE)
5073 return NULL;
5074 } else {
5075 if (staged_status == GOT_STATUS_DELETE)
5076 return NULL;
5077 if (status == GOT_STATUS_NONEXISTENT)
5078 return got_error_set_errno(ENOENT, path);
5079 if (status != GOT_STATUS_MODIFY &&
5080 status != GOT_STATUS_ADD &&
5081 status != GOT_STATUS_DELETE &&
5082 status != GOT_STATUS_CONFLICT)
5083 return NULL;
5086 err = got_opentemp_truncate(a->f1);
5087 if (err)
5088 return got_error_from_errno("got_opentemp_truncate");
5089 err = got_opentemp_truncate(a->f2);
5090 if (err)
5091 return got_error_from_errno("got_opentemp_truncate");
5093 if (!a->header_shown) {
5094 if (fprintf(a->outfile, "diff %s%s\n",
5095 a->diff_staged ? "-s " : "",
5096 got_worktree_get_root_path(a->worktree)) < 0) {
5097 err = got_error_from_errno("fprintf");
5098 goto done;
5100 if (fprintf(a->outfile, "commit - %s\n", a->id_str) < 0) {
5101 err = got_error_from_errno("fprintf");
5102 goto done;
5104 if (fprintf(a->outfile, "path + %s%s\n",
5105 got_worktree_get_root_path(a->worktree),
5106 a->diff_staged ? " (staged changes)" : "") < 0) {
5107 err = got_error_from_errno("fprintf");
5108 goto done;
5110 a->header_shown = 1;
5113 if (a->diff_staged) {
5114 const char *label1 = NULL, *label2 = NULL;
5115 switch (staged_status) {
5116 case GOT_STATUS_MODIFY:
5117 label1 = path;
5118 label2 = path;
5119 break;
5120 case GOT_STATUS_ADD:
5121 label2 = path;
5122 break;
5123 case GOT_STATUS_DELETE:
5124 label1 = path;
5125 break;
5126 default:
5127 return got_error(GOT_ERR_FILE_STATUS);
5129 fd1 = got_opentempfd();
5130 if (fd1 == -1) {
5131 err = got_error_from_errno("got_opentempfd");
5132 goto done;
5134 fd2 = got_opentempfd();
5135 if (fd2 == -1) {
5136 err = got_error_from_errno("got_opentempfd");
5137 goto done;
5139 err = got_diff_objects_as_blobs(NULL, NULL, a->f1, a->f2,
5140 fd1, fd2, blob_id, staged_blob_id, label1, label2,
5141 a->diff_algo, a->diff_context, a->ignore_whitespace,
5142 a->force_text_diff, a->diffstat, a->repo, a->outfile);
5143 goto done;
5146 fd1 = got_opentempfd();
5147 if (fd1 == -1) {
5148 err = got_error_from_errno("got_opentempfd");
5149 goto done;
5152 if (staged_status == GOT_STATUS_ADD ||
5153 staged_status == GOT_STATUS_MODIFY) {
5154 char *id_str;
5155 err = got_object_open_as_blob(&blob1, a->repo, staged_blob_id,
5156 8192, fd1);
5157 if (err)
5158 goto done;
5159 err = got_object_id_str(&id_str, staged_blob_id);
5160 if (err)
5161 goto done;
5162 if (asprintf(&label1, "%s (staged)", id_str) == -1) {
5163 err = got_error_from_errno("asprintf");
5164 free(id_str);
5165 goto done;
5167 free(id_str);
5168 } else if (status != GOT_STATUS_ADD) {
5169 err = got_object_open_as_blob(&blob1, a->repo, blob_id, 8192,
5170 fd1);
5171 if (err)
5172 goto done;
5175 if (status != GOT_STATUS_DELETE) {
5176 if (asprintf(&abspath, "%s/%s",
5177 got_worktree_get_root_path(a->worktree), path) == -1) {
5178 err = got_error_from_errno("asprintf");
5179 goto done;
5182 if (dirfd != -1) {
5183 fd = openat(dirfd, de_name,
5184 O_RDONLY | O_NOFOLLOW | O_CLOEXEC);
5185 if (fd == -1) {
5186 if (!got_err_open_nofollow_on_symlink()) {
5187 err = got_error_from_errno2("openat",
5188 abspath);
5189 goto done;
5191 err = get_symlink_target_file(&fd, dirfd,
5192 de_name, abspath);
5193 if (err)
5194 goto done;
5196 } else {
5197 fd = open(abspath, O_RDONLY | O_NOFOLLOW | O_CLOEXEC);
5198 if (fd == -1) {
5199 if (!got_err_open_nofollow_on_symlink()) {
5200 err = got_error_from_errno2("open",
5201 abspath);
5202 goto done;
5204 err = get_symlink_target_file(&fd, dirfd,
5205 de_name, abspath);
5206 if (err)
5207 goto done;
5210 if (fstatat(fd, abspath, &sb, AT_SYMLINK_NOFOLLOW) == -1) {
5211 err = got_error_from_errno2("fstatat", abspath);
5212 goto done;
5214 f2 = fdopen(fd, "r");
5215 if (f2 == NULL) {
5216 err = got_error_from_errno2("fdopen", abspath);
5217 goto done;
5219 fd = -1;
5220 f2_exists = 1;
5223 if (blob1) {
5224 err = got_object_blob_dump_to_file(&size1, NULL, NULL,
5225 a->f1, blob1);
5226 if (err)
5227 goto done;
5230 err = got_diff_blob_file(blob1, a->f1, size1, label1, f2 ? f2 : a->f2,
5231 f2_exists, &sb, path, GOT_DIFF_ALGORITHM_PATIENCE, a->diff_context,
5232 a->ignore_whitespace, a->force_text_diff, a->diffstat, a->outfile);
5233 done:
5234 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
5235 err = got_error_from_errno("close");
5236 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
5237 err = got_error_from_errno("close");
5238 if (blob1)
5239 got_object_blob_close(blob1);
5240 if (fd != -1 && close(fd) == -1 && err == NULL)
5241 err = got_error_from_errno("close");
5242 if (f2 && fclose(f2) == EOF && err == NULL)
5243 err = got_error_from_errno("fclose");
5244 free(abspath);
5245 return err;
5248 static const struct got_error *
5249 cmd_diff(int argc, char *argv[])
5251 const struct got_error *error;
5252 struct got_repository *repo = NULL;
5253 struct got_worktree *worktree = NULL;
5254 char *cwd = NULL, *repo_path = NULL;
5255 const char *commit_args[2] = { NULL, NULL };
5256 int ncommit_args = 0;
5257 struct got_object_id *ids[2] = { NULL, NULL };
5258 char *labels[2] = { NULL, NULL };
5259 int type1 = GOT_OBJ_TYPE_ANY, type2 = GOT_OBJ_TYPE_ANY;
5260 int diff_context = 3, diff_staged = 0, ignore_whitespace = 0, ch, i;
5261 int force_text_diff = 0, force_path = 0, rflag = 0, show_diffstat = 0;
5262 const char *errstr;
5263 struct got_reflist_head refs;
5264 struct got_pathlist_head diffstat_paths, paths;
5265 FILE *f1 = NULL, *f2 = NULL, *outfile = NULL;
5266 int fd1 = -1, fd2 = -1;
5267 int *pack_fds = NULL;
5268 struct got_diffstat_cb_arg dsa;
5270 memset(&dsa, 0, sizeof(dsa));
5272 TAILQ_INIT(&refs);
5273 TAILQ_INIT(&paths);
5274 TAILQ_INIT(&diffstat_paths);
5276 #ifndef PROFILE
5277 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
5278 NULL) == -1)
5279 err(1, "pledge");
5280 #endif
5282 while ((ch = getopt(argc, argv, "aC:c:dPr:sw")) != -1) {
5283 switch (ch) {
5284 case 'a':
5285 force_text_diff = 1;
5286 break;
5287 case 'C':
5288 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
5289 &errstr);
5290 if (errstr != NULL)
5291 errx(1, "number of context lines is %s: %s",
5292 errstr, optarg);
5293 break;
5294 case 'c':
5295 if (ncommit_args >= 2)
5296 errx(1, "too many -c options used");
5297 commit_args[ncommit_args++] = optarg;
5298 break;
5299 case 'd':
5300 show_diffstat = 1;
5301 break;
5302 case 'P':
5303 force_path = 1;
5304 break;
5305 case 'r':
5306 repo_path = realpath(optarg, NULL);
5307 if (repo_path == NULL)
5308 return got_error_from_errno2("realpath",
5309 optarg);
5310 got_path_strip_trailing_slashes(repo_path);
5311 rflag = 1;
5312 break;
5313 case 's':
5314 diff_staged = 1;
5315 break;
5316 case 'w':
5317 ignore_whitespace = 1;
5318 break;
5319 default:
5320 usage_diff();
5321 /* NOTREACHED */
5325 argc -= optind;
5326 argv += optind;
5328 cwd = getcwd(NULL, 0);
5329 if (cwd == NULL) {
5330 error = got_error_from_errno("getcwd");
5331 goto done;
5334 error = got_repo_pack_fds_open(&pack_fds);
5335 if (error != NULL)
5336 goto done;
5338 if (repo_path == NULL) {
5339 error = got_worktree_open(&worktree, cwd,
5340 GOT_WORKTREE_GOT_DIR);
5341 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5342 goto done;
5343 else
5344 error = NULL;
5345 if (worktree) {
5346 repo_path =
5347 strdup(got_worktree_get_repo_path(worktree));
5348 if (repo_path == NULL) {
5349 error = got_error_from_errno("strdup");
5350 goto done;
5352 } else {
5353 repo_path = strdup(cwd);
5354 if (repo_path == NULL) {
5355 error = got_error_from_errno("strdup");
5356 goto done;
5361 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
5362 free(repo_path);
5363 if (error != NULL)
5364 goto done;
5366 if (show_diffstat) {
5367 dsa.paths = &diffstat_paths;
5368 dsa.force_text = force_text_diff;
5369 dsa.ignore_ws = ignore_whitespace;
5370 dsa.diff_algo = GOT_DIFF_ALGORITHM_PATIENCE;
5373 if (rflag || worktree == NULL || ncommit_args > 0) {
5374 if (force_path) {
5375 error = got_error_msg(GOT_ERR_NOT_IMPL,
5376 "-P option can only be used when diffing "
5377 "a work tree");
5378 goto done;
5380 if (diff_staged) {
5381 error = got_error_msg(GOT_ERR_NOT_IMPL,
5382 "-s option can only be used when diffing "
5383 "a work tree");
5384 goto done;
5388 error = apply_unveil(got_repo_get_path(repo), 1,
5389 worktree ? got_worktree_get_root_path(worktree) : NULL);
5390 if (error)
5391 goto done;
5393 if ((!force_path && argc == 2) || ncommit_args > 0) {
5394 int obj_type = (ncommit_args > 0 ?
5395 GOT_OBJ_TYPE_COMMIT : GOT_OBJ_TYPE_ANY);
5396 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
5397 NULL);
5398 if (error)
5399 goto done;
5400 for (i = 0; i < (ncommit_args > 0 ? ncommit_args : argc); i++) {
5401 const char *arg;
5402 char *keyword_idstr = NULL;
5404 if (ncommit_args > 0)
5405 arg = commit_args[i];
5406 else
5407 arg = argv[i];
5409 error = got_keyword_to_idstr(&keyword_idstr, arg,
5410 repo, worktree);
5411 if (error != NULL)
5412 goto done;
5413 if (keyword_idstr != NULL)
5414 arg = keyword_idstr;
5416 error = got_repo_match_object_id(&ids[i], &labels[i],
5417 arg, obj_type, &refs, repo);
5418 free(keyword_idstr);
5419 if (error) {
5420 if (error->code != GOT_ERR_NOT_REF &&
5421 error->code != GOT_ERR_NO_OBJ)
5422 goto done;
5423 if (ncommit_args > 0)
5424 goto done;
5425 error = NULL;
5426 break;
5431 f1 = got_opentemp();
5432 if (f1 == NULL) {
5433 error = got_error_from_errno("got_opentemp");
5434 goto done;
5437 f2 = got_opentemp();
5438 if (f2 == NULL) {
5439 error = got_error_from_errno("got_opentemp");
5440 goto done;
5443 outfile = got_opentemp();
5444 if (outfile == NULL) {
5445 error = got_error_from_errno("got_opentemp");
5446 goto done;
5449 if (ncommit_args == 0 && (ids[0] == NULL || ids[1] == NULL)) {
5450 struct print_diff_arg arg;
5451 char *id_str;
5453 if (worktree == NULL) {
5454 if (argc == 2 && ids[0] == NULL) {
5455 error = got_error_path(argv[0], GOT_ERR_NO_OBJ);
5456 goto done;
5457 } else if (argc == 2 && ids[1] == NULL) {
5458 error = got_error_path(argv[1], GOT_ERR_NO_OBJ);
5459 goto done;
5460 } else if (argc > 0) {
5461 error = got_error_fmt(GOT_ERR_NOT_WORKTREE,
5462 "%s", "specified paths cannot be resolved");
5463 goto done;
5464 } else {
5465 error = got_error(GOT_ERR_NOT_WORKTREE);
5466 goto done;
5470 error = get_worktree_paths_from_argv(&paths, argc, argv,
5471 worktree);
5472 if (error)
5473 goto done;
5475 error = got_object_id_str(&id_str,
5476 got_worktree_get_base_commit_id(worktree));
5477 if (error)
5478 goto done;
5479 arg.repo = repo;
5480 arg.worktree = worktree;
5481 arg.diff_algo = GOT_DIFF_ALGORITHM_PATIENCE;
5482 arg.diff_context = diff_context;
5483 arg.id_str = id_str;
5484 arg.header_shown = 0;
5485 arg.diff_staged = diff_staged;
5486 arg.ignore_whitespace = ignore_whitespace;
5487 arg.force_text_diff = force_text_diff;
5488 arg.diffstat = show_diffstat ? &dsa : NULL;
5489 arg.f1 = f1;
5490 arg.f2 = f2;
5491 arg.outfile = outfile;
5493 error = got_worktree_status(worktree, &paths, repo, 0,
5494 print_diff, &arg, check_cancelled, NULL);
5495 free(id_str);
5496 if (error)
5497 goto done;
5499 if (show_diffstat && dsa.nfiles > 0) {
5500 char *header;
5502 if (asprintf(&header, "diffstat %s%s",
5503 diff_staged ? "-s " : "",
5504 got_worktree_get_root_path(worktree)) == -1) {
5505 error = got_error_from_errno("asprintf");
5506 goto done;
5509 error = print_diffstat(&dsa, header);
5510 free(header);
5511 if (error)
5512 goto done;
5515 error = printfile(outfile);
5516 goto done;
5519 if (ncommit_args == 1) {
5520 struct got_commit_object *commit;
5521 error = got_object_open_as_commit(&commit, repo, ids[0]);
5522 if (error)
5523 goto done;
5525 labels[1] = labels[0];
5526 ids[1] = ids[0];
5527 if (got_object_commit_get_nparents(commit) > 0) {
5528 const struct got_object_id_queue *pids;
5529 struct got_object_qid *pid;
5530 pids = got_object_commit_get_parent_ids(commit);
5531 pid = STAILQ_FIRST(pids);
5532 ids[0] = got_object_id_dup(&pid->id);
5533 if (ids[0] == NULL) {
5534 error = got_error_from_errno(
5535 "got_object_id_dup");
5536 got_object_commit_close(commit);
5537 goto done;
5539 error = got_object_id_str(&labels[0], ids[0]);
5540 if (error) {
5541 got_object_commit_close(commit);
5542 goto done;
5544 } else {
5545 ids[0] = NULL;
5546 labels[0] = strdup("/dev/null");
5547 if (labels[0] == NULL) {
5548 error = got_error_from_errno("strdup");
5549 got_object_commit_close(commit);
5550 goto done;
5554 got_object_commit_close(commit);
5557 if (ncommit_args == 0 && argc > 2) {
5558 error = got_error_msg(GOT_ERR_BAD_PATH,
5559 "path arguments cannot be used when diffing two objects");
5560 goto done;
5563 if (ids[0]) {
5564 error = got_object_get_type(&type1, repo, ids[0]);
5565 if (error)
5566 goto done;
5569 error = got_object_get_type(&type2, repo, ids[1]);
5570 if (error)
5571 goto done;
5572 if (type1 != GOT_OBJ_TYPE_ANY && type1 != type2) {
5573 error = got_error(GOT_ERR_OBJ_TYPE);
5574 goto done;
5576 if (type1 == GOT_OBJ_TYPE_BLOB && argc > 2) {
5577 error = got_error_msg(GOT_ERR_OBJ_TYPE,
5578 "path arguments cannot be used when diffing blobs");
5579 goto done;
5582 for (i = 0; ncommit_args > 0 && i < argc; i++) {
5583 char *in_repo_path;
5584 struct got_pathlist_entry *new;
5585 if (worktree) {
5586 const char *prefix;
5587 char *p;
5588 error = got_worktree_resolve_path(&p, worktree,
5589 argv[i]);
5590 if (error)
5591 goto done;
5592 prefix = got_worktree_get_path_prefix(worktree);
5593 while (prefix[0] == '/')
5594 prefix++;
5595 if (asprintf(&in_repo_path, "%s%s%s", prefix,
5596 (p[0] != '\0' && prefix[0] != '\0') ? "/" : "",
5597 p) == -1) {
5598 error = got_error_from_errno("asprintf");
5599 free(p);
5600 goto done;
5602 free(p);
5603 } else {
5604 char *mapped_path, *s;
5605 error = got_repo_map_path(&mapped_path, repo, argv[i]);
5606 if (error)
5607 goto done;
5608 s = mapped_path;
5609 while (s[0] == '/')
5610 s++;
5611 in_repo_path = strdup(s);
5612 if (in_repo_path == NULL) {
5613 error = got_error_from_errno("asprintf");
5614 free(mapped_path);
5615 goto done;
5617 free(mapped_path);
5620 error = got_pathlist_insert(&new, &paths, in_repo_path, NULL);
5621 if (error || new == NULL /* duplicate */)
5622 free(in_repo_path);
5623 if (error)
5624 goto done;
5627 if (worktree) {
5628 /* Release work tree lock. */
5629 got_worktree_close(worktree);
5630 worktree = NULL;
5633 fd1 = got_opentempfd();
5634 if (fd1 == -1) {
5635 error = got_error_from_errno("got_opentempfd");
5636 goto done;
5639 fd2 = got_opentempfd();
5640 if (fd2 == -1) {
5641 error = got_error_from_errno("got_opentempfd");
5642 goto done;
5645 switch (type1 == GOT_OBJ_TYPE_ANY ? type2 : type1) {
5646 case GOT_OBJ_TYPE_BLOB:
5647 error = got_diff_objects_as_blobs(NULL, NULL, f1, f2,
5648 fd1, fd2, ids[0], ids[1], NULL, NULL,
5649 GOT_DIFF_ALGORITHM_PATIENCE, diff_context,
5650 ignore_whitespace, force_text_diff,
5651 show_diffstat ? &dsa : NULL, repo, outfile);
5652 break;
5653 case GOT_OBJ_TYPE_TREE:
5654 error = got_diff_objects_as_trees(NULL, NULL, f1, f2, fd1, fd2,
5655 ids[0], ids[1], &paths, "", "",
5656 GOT_DIFF_ALGORITHM_PATIENCE, diff_context,
5657 ignore_whitespace, force_text_diff,
5658 show_diffstat ? &dsa : NULL, repo, outfile);
5659 break;
5660 case GOT_OBJ_TYPE_COMMIT:
5661 fprintf(outfile, "diff %s %s\n", labels[0], labels[1]);
5662 error = got_diff_objects_as_commits(NULL, NULL, f1, f2,
5663 fd1, fd2, ids[0], ids[1], &paths,
5664 GOT_DIFF_ALGORITHM_PATIENCE, diff_context,
5665 ignore_whitespace, force_text_diff,
5666 show_diffstat ? &dsa : NULL, repo, outfile);
5667 break;
5668 default:
5669 error = got_error(GOT_ERR_OBJ_TYPE);
5671 if (error)
5672 goto done;
5674 if (show_diffstat && dsa.nfiles > 0) {
5675 char *header = NULL;
5677 if (asprintf(&header, "diffstat %s %s",
5678 labels[0], labels[1]) == -1) {
5679 error = got_error_from_errno("asprintf");
5680 goto done;
5683 error = print_diffstat(&dsa, header);
5684 free(header);
5685 if (error)
5686 goto done;
5689 error = printfile(outfile);
5691 done:
5692 free(cwd);
5693 free(labels[0]);
5694 free(labels[1]);
5695 free(ids[0]);
5696 free(ids[1]);
5697 if (worktree)
5698 got_worktree_close(worktree);
5699 if (repo) {
5700 const struct got_error *close_err = got_repo_close(repo);
5701 if (error == NULL)
5702 error = close_err;
5704 if (pack_fds) {
5705 const struct got_error *pack_err =
5706 got_repo_pack_fds_close(pack_fds);
5707 if (error == NULL)
5708 error = pack_err;
5710 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
5711 got_pathlist_free(&diffstat_paths, GOT_PATHLIST_FREE_ALL);
5712 got_ref_list_free(&refs);
5713 if (outfile && fclose(outfile) == EOF && error == NULL)
5714 error = got_error_from_errno("fclose");
5715 if (f1 && fclose(f1) == EOF && error == NULL)
5716 error = got_error_from_errno("fclose");
5717 if (f2 && fclose(f2) == EOF && error == NULL)
5718 error = got_error_from_errno("fclose");
5719 if (fd1 != -1 && close(fd1) == -1 && error == NULL)
5720 error = got_error_from_errno("close");
5721 if (fd2 != -1 && close(fd2) == -1 && error == NULL)
5722 error = got_error_from_errno("close");
5723 return error;
5726 __dead static void
5727 usage_blame(void)
5729 fprintf(stderr,
5730 "usage: %s blame [-c commit] [-r repository-path] path\n",
5731 getprogname());
5732 exit(1);
5735 struct blame_line {
5736 int annotated;
5737 char *id_str;
5738 char *committer;
5739 char datebuf[11]; /* YYYY-MM-DD + NUL */
5742 struct blame_cb_args {
5743 struct blame_line *lines;
5744 int nlines;
5745 int nlines_prec;
5746 int lineno_cur;
5747 off_t *line_offsets;
5748 FILE *f;
5749 struct got_repository *repo;
5752 static const struct got_error *
5753 blame_cb(void *arg, int nlines, int lineno,
5754 struct got_commit_object *commit, struct got_object_id *id)
5756 const struct got_error *err = NULL;
5757 struct blame_cb_args *a = arg;
5758 struct blame_line *bline;
5759 char *line = NULL;
5760 size_t linesize = 0;
5761 off_t offset;
5762 struct tm tm;
5763 time_t committer_time;
5765 if (nlines != a->nlines ||
5766 (lineno != -1 && lineno < 1) || lineno > a->nlines)
5767 return got_error(GOT_ERR_RANGE);
5769 if (sigint_received)
5770 return got_error(GOT_ERR_ITER_COMPLETED);
5772 if (lineno == -1)
5773 return NULL; /* no change in this commit */
5775 /* Annotate this line. */
5776 bline = &a->lines[lineno - 1];
5777 if (bline->annotated)
5778 return NULL;
5779 err = got_object_id_str(&bline->id_str, id);
5780 if (err)
5781 return err;
5783 bline->committer = strdup(got_object_commit_get_committer(commit));
5784 if (bline->committer == NULL) {
5785 err = got_error_from_errno("strdup");
5786 goto done;
5789 committer_time = got_object_commit_get_committer_time(commit);
5790 if (gmtime_r(&committer_time, &tm) == NULL)
5791 return got_error_from_errno("gmtime_r");
5792 if (strftime(bline->datebuf, sizeof(bline->datebuf), "%F", &tm) == 0) {
5793 err = got_error(GOT_ERR_NO_SPACE);
5794 goto done;
5796 bline->annotated = 1;
5798 /* Print lines annotated so far. */
5799 bline = &a->lines[a->lineno_cur - 1];
5800 if (!bline->annotated)
5801 goto done;
5803 offset = a->line_offsets[a->lineno_cur - 1];
5804 if (fseeko(a->f, offset, SEEK_SET) == -1) {
5805 err = got_error_from_errno("fseeko");
5806 goto done;
5809 while (a->lineno_cur <= a->nlines && bline->annotated) {
5810 char *smallerthan, *at, *nl, *committer;
5811 size_t len;
5813 if (getline(&line, &linesize, a->f) == -1) {
5814 if (ferror(a->f))
5815 err = got_error_from_errno("getline");
5816 break;
5819 committer = bline->committer;
5820 smallerthan = strchr(committer, '<');
5821 if (smallerthan && smallerthan[1] != '\0')
5822 committer = smallerthan + 1;
5823 at = strchr(committer, '@');
5824 if (at)
5825 *at = '\0';
5826 len = strlen(committer);
5827 if (len >= 9)
5828 committer[8] = '\0';
5830 nl = strchr(line, '\n');
5831 if (nl)
5832 *nl = '\0';
5833 printf("%.*d) %.8s %s %-8s %s\n", a->nlines_prec, a->lineno_cur,
5834 bline->id_str, bline->datebuf, committer, line);
5836 a->lineno_cur++;
5837 bline = &a->lines[a->lineno_cur - 1];
5839 done:
5840 free(line);
5841 return err;
5844 static const struct got_error *
5845 cmd_blame(int argc, char *argv[])
5847 const struct got_error *error;
5848 struct got_repository *repo = NULL;
5849 struct got_worktree *worktree = NULL;
5850 char *path, *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
5851 char *link_target = NULL;
5852 struct got_object_id *obj_id = NULL;
5853 struct got_object_id *commit_id = NULL;
5854 struct got_commit_object *commit = NULL;
5855 struct got_blob_object *blob = NULL;
5856 char *commit_id_str = NULL, *keyword_idstr = NULL;
5857 struct blame_cb_args bca;
5858 int ch, obj_type, i, fd1 = -1, fd2 = -1, fd3 = -1;
5859 off_t filesize;
5860 int *pack_fds = NULL;
5861 FILE *f1 = NULL, *f2 = NULL;
5863 fd1 = got_opentempfd();
5864 if (fd1 == -1)
5865 return got_error_from_errno("got_opentempfd");
5867 memset(&bca, 0, sizeof(bca));
5869 #ifndef PROFILE
5870 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
5871 NULL) == -1)
5872 err(1, "pledge");
5873 #endif
5875 while ((ch = getopt(argc, argv, "c:r:")) != -1) {
5876 switch (ch) {
5877 case 'c':
5878 commit_id_str = optarg;
5879 break;
5880 case 'r':
5881 repo_path = realpath(optarg, NULL);
5882 if (repo_path == NULL)
5883 return got_error_from_errno2("realpath",
5884 optarg);
5885 got_path_strip_trailing_slashes(repo_path);
5886 break;
5887 default:
5888 usage_blame();
5889 /* NOTREACHED */
5893 argc -= optind;
5894 argv += optind;
5896 if (argc == 1)
5897 path = argv[0];
5898 else
5899 usage_blame();
5901 cwd = getcwd(NULL, 0);
5902 if (cwd == NULL) {
5903 error = got_error_from_errno("getcwd");
5904 goto done;
5907 error = got_repo_pack_fds_open(&pack_fds);
5908 if (error != NULL)
5909 goto done;
5911 if (repo_path == NULL) {
5912 error = got_worktree_open(&worktree, cwd,
5913 GOT_WORKTREE_GOT_DIR);
5914 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5915 goto done;
5916 else
5917 error = NULL;
5918 if (worktree) {
5919 repo_path =
5920 strdup(got_worktree_get_repo_path(worktree));
5921 if (repo_path == NULL) {
5922 error = got_error_from_errno("strdup");
5923 if (error)
5924 goto done;
5926 } else {
5927 repo_path = strdup(cwd);
5928 if (repo_path == NULL) {
5929 error = got_error_from_errno("strdup");
5930 goto done;
5935 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
5936 if (error != NULL)
5937 goto done;
5939 if (worktree) {
5940 const char *prefix = got_worktree_get_path_prefix(worktree);
5941 char *p;
5943 error = got_worktree_resolve_path(&p, worktree, path);
5944 if (error)
5945 goto done;
5946 if (asprintf(&in_repo_path, "%s%s%s", prefix,
5947 (p[0] != '\0' && !got_path_is_root_dir(prefix)) ? "/" : "",
5948 p) == -1) {
5949 error = got_error_from_errno("asprintf");
5950 free(p);
5951 goto done;
5953 free(p);
5954 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5955 } else {
5956 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5957 if (error)
5958 goto done;
5959 error = got_repo_map_path(&in_repo_path, repo, path);
5961 if (error)
5962 goto done;
5964 if (commit_id_str == NULL) {
5965 struct got_reference *head_ref;
5966 error = got_ref_open(&head_ref, repo, worktree ?
5967 got_worktree_get_head_ref_name(worktree) : GOT_REF_HEAD, 0);
5968 if (error != NULL)
5969 goto done;
5970 error = got_ref_resolve(&commit_id, repo, head_ref);
5971 got_ref_close(head_ref);
5972 if (error != NULL)
5973 goto done;
5974 } else {
5975 struct got_reflist_head refs;
5977 TAILQ_INIT(&refs);
5978 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
5979 NULL);
5980 if (error)
5981 goto done;
5983 error = got_keyword_to_idstr(&keyword_idstr, commit_id_str,
5984 repo, worktree);
5985 if (error != NULL)
5986 goto done;
5987 if (keyword_idstr != NULL)
5988 commit_id_str = keyword_idstr;
5990 error = got_repo_match_object_id(&commit_id, NULL,
5991 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
5992 got_ref_list_free(&refs);
5993 if (error)
5994 goto done;
5997 if (worktree) {
5998 /* Release work tree lock. */
5999 got_worktree_close(worktree);
6000 worktree = NULL;
6003 error = got_object_open_as_commit(&commit, repo, commit_id);
6004 if (error)
6005 goto done;
6007 error = got_object_resolve_symlinks(&link_target, in_repo_path,
6008 commit, repo);
6009 if (error)
6010 goto done;
6012 error = got_object_id_by_path(&obj_id, repo, commit,
6013 link_target ? link_target : in_repo_path);
6014 if (error)
6015 goto done;
6017 error = got_object_get_type(&obj_type, repo, obj_id);
6018 if (error)
6019 goto done;
6021 if (obj_type != GOT_OBJ_TYPE_BLOB) {
6022 error = got_error_path(link_target ? link_target : in_repo_path,
6023 GOT_ERR_OBJ_TYPE);
6024 goto done;
6027 error = got_object_open_as_blob(&blob, repo, obj_id, 8192, fd1);
6028 if (error)
6029 goto done;
6030 bca.f = got_opentemp();
6031 if (bca.f == NULL) {
6032 error = got_error_from_errno("got_opentemp");
6033 goto done;
6035 error = got_object_blob_dump_to_file(&filesize, &bca.nlines,
6036 &bca.line_offsets, bca.f, blob);
6037 if (error || bca.nlines == 0)
6038 goto done;
6040 /* Don't include \n at EOF in the blame line count. */
6041 if (bca.line_offsets[bca.nlines - 1] == filesize)
6042 bca.nlines--;
6044 bca.lines = calloc(bca.nlines, sizeof(*bca.lines));
6045 if (bca.lines == NULL) {
6046 error = got_error_from_errno("calloc");
6047 goto done;
6049 bca.lineno_cur = 1;
6050 bca.nlines_prec = 0;
6051 i = bca.nlines;
6052 while (i > 0) {
6053 i /= 10;
6054 bca.nlines_prec++;
6056 bca.repo = repo;
6058 fd2 = got_opentempfd();
6059 if (fd2 == -1) {
6060 error = got_error_from_errno("got_opentempfd");
6061 goto done;
6063 fd3 = got_opentempfd();
6064 if (fd3 == -1) {
6065 error = got_error_from_errno("got_opentempfd");
6066 goto done;
6068 f1 = got_opentemp();
6069 if (f1 == NULL) {
6070 error = got_error_from_errno("got_opentemp");
6071 goto done;
6073 f2 = got_opentemp();
6074 if (f2 == NULL) {
6075 error = got_error_from_errno("got_opentemp");
6076 goto done;
6078 error = got_blame(link_target ? link_target : in_repo_path, commit_id,
6079 repo, GOT_DIFF_ALGORITHM_PATIENCE, blame_cb, &bca,
6080 check_cancelled, NULL, fd2, fd3, f1, f2);
6081 done:
6082 free(keyword_idstr);
6083 free(in_repo_path);
6084 free(link_target);
6085 free(repo_path);
6086 free(cwd);
6087 free(commit_id);
6088 free(obj_id);
6089 if (commit)
6090 got_object_commit_close(commit);
6092 if (fd1 != -1 && close(fd1) == -1 && error == NULL)
6093 error = got_error_from_errno("close");
6094 if (fd2 != -1 && close(fd2) == -1 && error == NULL)
6095 error = got_error_from_errno("close");
6096 if (fd3 != -1 && close(fd3) == -1 && error == NULL)
6097 error = got_error_from_errno("close");
6098 if (f1 && fclose(f1) == EOF && error == NULL)
6099 error = got_error_from_errno("fclose");
6100 if (f2 && fclose(f2) == EOF && error == NULL)
6101 error = got_error_from_errno("fclose");
6103 if (blob)
6104 got_object_blob_close(blob);
6105 if (worktree)
6106 got_worktree_close(worktree);
6107 if (repo) {
6108 const struct got_error *close_err = got_repo_close(repo);
6109 if (error == NULL)
6110 error = close_err;
6112 if (pack_fds) {
6113 const struct got_error *pack_err =
6114 got_repo_pack_fds_close(pack_fds);
6115 if (error == NULL)
6116 error = pack_err;
6118 if (bca.lines) {
6119 for (i = 0; i < bca.nlines; i++) {
6120 struct blame_line *bline = &bca.lines[i];
6121 free(bline->id_str);
6122 free(bline->committer);
6124 free(bca.lines);
6126 free(bca.line_offsets);
6127 if (bca.f && fclose(bca.f) == EOF && error == NULL)
6128 error = got_error_from_errno("fclose");
6129 return error;
6132 __dead static void
6133 usage_tree(void)
6135 fprintf(stderr, "usage: %s tree [-iR] [-c commit] [-r repository-path] "
6136 "[path]\n", getprogname());
6137 exit(1);
6140 static const struct got_error *
6141 print_entry(struct got_tree_entry *te, const char *id, const char *path,
6142 const char *root_path, struct got_repository *repo)
6144 const struct got_error *err = NULL;
6145 int is_root_path = (strcmp(path, root_path) == 0);
6146 const char *modestr = "";
6147 mode_t mode = got_tree_entry_get_mode(te);
6148 char *link_target = NULL;
6150 path += strlen(root_path);
6151 while (path[0] == '/')
6152 path++;
6154 if (got_object_tree_entry_is_submodule(te))
6155 modestr = "$";
6156 else if (S_ISLNK(mode)) {
6157 int i;
6159 err = got_tree_entry_get_symlink_target(&link_target, te, repo);
6160 if (err)
6161 return err;
6162 for (i = 0; link_target[i] != '\0'; i++) {
6163 if (!isprint((unsigned char)link_target[i]))
6164 link_target[i] = '?';
6167 modestr = "@";
6169 else if (S_ISDIR(mode))
6170 modestr = "/";
6171 else if (mode & S_IXUSR)
6172 modestr = "*";
6174 printf("%s%s%s%s%s%s%s\n", id ? id : "", path,
6175 is_root_path ? "" : "/", got_tree_entry_get_name(te), modestr,
6176 link_target ? " -> ": "", link_target ? link_target : "");
6178 free(link_target);
6179 return NULL;
6182 static const struct got_error *
6183 print_tree(const char *path, struct got_commit_object *commit,
6184 int show_ids, int recurse, const char *root_path,
6185 struct got_repository *repo)
6187 const struct got_error *err = NULL;
6188 struct got_object_id *tree_id = NULL;
6189 struct got_tree_object *tree = NULL;
6190 int nentries, i;
6192 err = got_object_id_by_path(&tree_id, repo, commit, path);
6193 if (err)
6194 goto done;
6196 err = got_object_open_as_tree(&tree, repo, tree_id);
6197 if (err)
6198 goto done;
6199 nentries = got_object_tree_get_nentries(tree);
6200 for (i = 0; i < nentries; i++) {
6201 struct got_tree_entry *te;
6202 char *id = NULL;
6204 if (sigint_received || sigpipe_received)
6205 break;
6207 te = got_object_tree_get_entry(tree, i);
6208 if (show_ids) {
6209 char *id_str;
6210 err = got_object_id_str(&id_str,
6211 got_tree_entry_get_id(te));
6212 if (err)
6213 goto done;
6214 if (asprintf(&id, "%s ", id_str) == -1) {
6215 err = got_error_from_errno("asprintf");
6216 free(id_str);
6217 goto done;
6219 free(id_str);
6221 err = print_entry(te, id, path, root_path, repo);
6222 free(id);
6223 if (err)
6224 goto done;
6226 if (recurse && S_ISDIR(got_tree_entry_get_mode(te))) {
6227 char *child_path;
6228 if (asprintf(&child_path, "%s%s%s", path,
6229 path[0] == '/' && path[1] == '\0' ? "" : "/",
6230 got_tree_entry_get_name(te)) == -1) {
6231 err = got_error_from_errno("asprintf");
6232 goto done;
6234 err = print_tree(child_path, commit, show_ids, 1,
6235 root_path, repo);
6236 free(child_path);
6237 if (err)
6238 goto done;
6241 done:
6242 if (tree)
6243 got_object_tree_close(tree);
6244 free(tree_id);
6245 return err;
6248 static const struct got_error *
6249 cmd_tree(int argc, char *argv[])
6251 const struct got_error *error;
6252 struct got_repository *repo = NULL;
6253 struct got_worktree *worktree = NULL;
6254 const char *path, *refname = NULL;
6255 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
6256 struct got_object_id *commit_id = NULL;
6257 struct got_commit_object *commit = NULL;
6258 char *commit_id_str = NULL, *keyword_idstr = NULL;
6259 int show_ids = 0, recurse = 0;
6260 int ch;
6261 int *pack_fds = NULL;
6263 #ifndef PROFILE
6264 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
6265 NULL) == -1)
6266 err(1, "pledge");
6267 #endif
6269 while ((ch = getopt(argc, argv, "c:iRr:")) != -1) {
6270 switch (ch) {
6271 case 'c':
6272 commit_id_str = optarg;
6273 break;
6274 case 'i':
6275 show_ids = 1;
6276 break;
6277 case 'R':
6278 recurse = 1;
6279 break;
6280 case 'r':
6281 repo_path = realpath(optarg, NULL);
6282 if (repo_path == NULL)
6283 return got_error_from_errno2("realpath",
6284 optarg);
6285 got_path_strip_trailing_slashes(repo_path);
6286 break;
6287 default:
6288 usage_tree();
6289 /* NOTREACHED */
6293 argc -= optind;
6294 argv += optind;
6296 if (argc == 1)
6297 path = argv[0];
6298 else if (argc > 1)
6299 usage_tree();
6300 else
6301 path = NULL;
6303 cwd = getcwd(NULL, 0);
6304 if (cwd == NULL) {
6305 error = got_error_from_errno("getcwd");
6306 goto done;
6309 error = got_repo_pack_fds_open(&pack_fds);
6310 if (error != NULL)
6311 goto done;
6313 if (repo_path == NULL) {
6314 error = got_worktree_open(&worktree, cwd,
6315 GOT_WORKTREE_GOT_DIR);
6316 if (error && error->code != GOT_ERR_NOT_WORKTREE)
6317 goto done;
6318 else
6319 error = NULL;
6320 if (worktree) {
6321 repo_path =
6322 strdup(got_worktree_get_repo_path(worktree));
6323 if (repo_path == NULL)
6324 error = got_error_from_errno("strdup");
6325 if (error)
6326 goto done;
6327 } else {
6328 repo_path = strdup(cwd);
6329 if (repo_path == NULL) {
6330 error = got_error_from_errno("strdup");
6331 goto done;
6336 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
6337 if (error != NULL)
6338 goto done;
6340 if (worktree) {
6341 const char *prefix = got_worktree_get_path_prefix(worktree);
6342 char *p;
6344 if (path == NULL || got_path_is_root_dir(path))
6345 path = "";
6346 error = got_worktree_resolve_path(&p, worktree, path);
6347 if (error)
6348 goto done;
6349 if (asprintf(&in_repo_path, "%s%s%s", prefix,
6350 (p[0] != '\0' && !got_path_is_root_dir(prefix)) ? "/" : "",
6351 p) == -1) {
6352 error = got_error_from_errno("asprintf");
6353 free(p);
6354 goto done;
6356 free(p);
6357 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
6358 if (error)
6359 goto done;
6360 } else {
6361 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
6362 if (error)
6363 goto done;
6364 if (path == NULL)
6365 path = "/";
6366 error = got_repo_map_path(&in_repo_path, repo, path);
6367 if (error != NULL)
6368 goto done;
6371 if (commit_id_str == NULL) {
6372 struct got_reference *head_ref;
6373 if (worktree)
6374 refname = got_worktree_get_head_ref_name(worktree);
6375 else
6376 refname = GOT_REF_HEAD;
6377 error = got_ref_open(&head_ref, repo, refname, 0);
6378 if (error != NULL)
6379 goto done;
6380 error = got_ref_resolve(&commit_id, repo, head_ref);
6381 got_ref_close(head_ref);
6382 if (error != NULL)
6383 goto done;
6384 } else {
6385 struct got_reflist_head refs;
6387 TAILQ_INIT(&refs);
6388 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
6389 NULL);
6390 if (error)
6391 goto done;
6393 error = got_keyword_to_idstr(&keyword_idstr, commit_id_str,
6394 repo, worktree);
6395 if (error != NULL)
6396 goto done;
6397 if (keyword_idstr != NULL)
6398 commit_id_str = keyword_idstr;
6400 error = got_repo_match_object_id(&commit_id, NULL,
6401 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
6402 got_ref_list_free(&refs);
6403 if (error)
6404 goto done;
6407 if (worktree) {
6408 /* Release work tree lock. */
6409 got_worktree_close(worktree);
6410 worktree = NULL;
6413 error = got_object_open_as_commit(&commit, repo, commit_id);
6414 if (error)
6415 goto done;
6417 error = print_tree(in_repo_path, commit, show_ids, recurse,
6418 in_repo_path, repo);
6419 done:
6420 free(keyword_idstr);
6421 free(in_repo_path);
6422 free(repo_path);
6423 free(cwd);
6424 free(commit_id);
6425 if (commit)
6426 got_object_commit_close(commit);
6427 if (worktree)
6428 got_worktree_close(worktree);
6429 if (repo) {
6430 const struct got_error *close_err = got_repo_close(repo);
6431 if (error == NULL)
6432 error = close_err;
6434 if (pack_fds) {
6435 const struct got_error *pack_err =
6436 got_repo_pack_fds_close(pack_fds);
6437 if (error == NULL)
6438 error = pack_err;
6440 return error;
6443 __dead static void
6444 usage_status(void)
6446 fprintf(stderr, "usage: %s status [-I] [-S status-codes] "
6447 "[-s status-codes] [path ...]\n", getprogname());
6448 exit(1);
6451 struct got_status_arg {
6452 char *status_codes;
6453 int suppress;
6456 static const struct got_error *
6457 print_status(void *arg, unsigned char status, unsigned char staged_status,
6458 const char *path, struct got_object_id *blob_id,
6459 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
6460 int dirfd, const char *de_name)
6462 struct got_status_arg *st = arg;
6464 if (status == staged_status && (status == GOT_STATUS_DELETE))
6465 status = GOT_STATUS_NO_CHANGE;
6466 if (st != NULL && st->status_codes) {
6467 size_t ncodes = strlen(st->status_codes);
6468 int i, j = 0;
6470 for (i = 0; i < ncodes ; i++) {
6471 if (st->suppress) {
6472 if (status == st->status_codes[i] ||
6473 staged_status == st->status_codes[i]) {
6474 j++;
6475 continue;
6477 } else {
6478 if (status == st->status_codes[i] ||
6479 staged_status == st->status_codes[i])
6480 break;
6484 if (st->suppress && j == 0)
6485 goto print;
6487 if (i == ncodes)
6488 return NULL;
6490 print:
6491 printf("%c%c %s\n", status, staged_status, path);
6492 return NULL;
6495 static const struct got_error *
6496 show_operation_in_progress(struct got_worktree *worktree,
6497 struct got_repository *repo)
6499 const struct got_error *err;
6500 char *new_base_branch_name = NULL;
6501 char *branch_name = NULL;
6502 int rebase_in_progress, histedit_in_progress, merge_in_progress;
6504 err = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
6505 if (err)
6506 return err;
6507 if (rebase_in_progress) {
6508 err = got_worktree_rebase_info(&new_base_branch_name,
6509 &branch_name, worktree, repo);
6510 if (err)
6511 return err;
6512 printf("Work tree is rebasing %s onto %s\n",
6513 branch_name, new_base_branch_name);
6516 err = got_worktree_histedit_in_progress(&histedit_in_progress,
6517 worktree);
6518 if (err)
6519 return err;
6520 if (histedit_in_progress) {
6521 err = got_worktree_histedit_info(&branch_name, worktree, repo);
6522 if (err)
6523 return err;
6524 printf("Work tree is editing the history of %s\n", branch_name);
6527 err = got_worktree_merge_in_progress(&merge_in_progress,
6528 worktree, repo);
6529 if (err)
6530 return err;
6531 if (merge_in_progress) {
6532 err = got_worktree_merge_info(&branch_name, worktree,
6533 repo);
6534 if (err)
6535 return err;
6536 printf("Work tree is merging %s into %s\n", branch_name,
6537 got_worktree_get_head_ref_name(worktree));
6540 free(new_base_branch_name);
6541 free(branch_name);
6542 return NULL;
6545 static const struct got_error *
6546 cmd_status(int argc, char *argv[])
6548 const struct got_error *close_err, *error = NULL;
6549 struct got_repository *repo = NULL;
6550 struct got_worktree *worktree = NULL;
6551 struct got_status_arg st;
6552 char *cwd = NULL;
6553 struct got_pathlist_head paths;
6554 int ch, i, no_ignores = 0;
6555 int *pack_fds = NULL;
6557 TAILQ_INIT(&paths);
6559 memset(&st, 0, sizeof(st));
6560 st.status_codes = NULL;
6561 st.suppress = 0;
6563 #ifndef PROFILE
6564 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
6565 NULL) == -1)
6566 err(1, "pledge");
6567 #endif
6569 while ((ch = getopt(argc, argv, "IS:s:")) != -1) {
6570 switch (ch) {
6571 case 'I':
6572 no_ignores = 1;
6573 break;
6574 case 'S':
6575 if (st.status_codes != NULL && st.suppress == 0)
6576 option_conflict('S', 's');
6577 st.suppress = 1;
6578 /* fallthrough */
6579 case 's':
6580 for (i = 0; optarg[i] != '\0'; i++) {
6581 switch (optarg[i]) {
6582 case GOT_STATUS_MODIFY:
6583 case GOT_STATUS_ADD:
6584 case GOT_STATUS_DELETE:
6585 case GOT_STATUS_CONFLICT:
6586 case GOT_STATUS_MISSING:
6587 case GOT_STATUS_OBSTRUCTED:
6588 case GOT_STATUS_UNVERSIONED:
6589 case GOT_STATUS_MODE_CHANGE:
6590 case GOT_STATUS_NONEXISTENT:
6591 break;
6592 default:
6593 errx(1, "invalid status code '%c'",
6594 optarg[i]);
6597 if (ch == 's' && st.suppress)
6598 option_conflict('s', 'S');
6599 st.status_codes = optarg;
6600 break;
6601 default:
6602 usage_status();
6603 /* NOTREACHED */
6607 argc -= optind;
6608 argv += optind;
6610 cwd = getcwd(NULL, 0);
6611 if (cwd == NULL) {
6612 error = got_error_from_errno("getcwd");
6613 goto done;
6616 error = got_repo_pack_fds_open(&pack_fds);
6617 if (error != NULL)
6618 goto done;
6620 error = got_worktree_open(&worktree, cwd,
6621 GOT_WORKTREE_GOT_DIR);
6622 if (error) {
6623 if (error->code == GOT_ERR_NOT_WORKTREE)
6624 error = wrap_not_worktree_error(error, "status", cwd);
6625 goto done;
6628 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
6629 NULL, pack_fds);
6630 if (error != NULL)
6631 goto done;
6633 error = apply_unveil(got_repo_get_path(repo), 1,
6634 got_worktree_get_root_path(worktree));
6635 if (error)
6636 goto done;
6638 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
6639 if (error)
6640 goto done;
6642 error = got_worktree_status(worktree, &paths, repo, no_ignores,
6643 print_status, &st, check_cancelled, NULL);
6644 if (error)
6645 goto done;
6647 error = show_operation_in_progress(worktree, repo);
6648 done:
6649 if (pack_fds) {
6650 const struct got_error *pack_err =
6651 got_repo_pack_fds_close(pack_fds);
6652 if (error == NULL)
6653 error = pack_err;
6655 if (repo) {
6656 close_err = got_repo_close(repo);
6657 if (error == NULL)
6658 error = close_err;
6660 if (worktree != NULL) {
6661 close_err = got_worktree_close(worktree);
6662 if (error == NULL)
6663 error = close_err;
6666 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
6667 free(cwd);
6668 return error;
6671 __dead static void
6672 usage_ref(void)
6674 fprintf(stderr, "usage: %s ref [-dlt] [-c object] [-r repository-path] "
6675 "[-s reference] [name]\n", getprogname());
6676 exit(1);
6679 static const struct got_error *
6680 list_refs(struct got_repository *repo, const char *refname, int sort_by_time)
6682 static const struct got_error *err = NULL;
6683 struct got_reflist_head refs;
6684 struct got_reflist_entry *re;
6686 TAILQ_INIT(&refs);
6687 err = got_ref_list(&refs, repo, refname, sort_by_time ?
6688 got_ref_cmp_by_commit_timestamp_descending : got_ref_cmp_by_name,
6689 repo);
6690 if (err)
6691 return err;
6693 TAILQ_FOREACH(re, &refs, entry) {
6694 char *refstr;
6695 refstr = got_ref_to_str(re->ref);
6696 if (refstr == NULL) {
6697 err = got_error_from_errno("got_ref_to_str");
6698 break;
6700 printf("%s: %s\n", got_ref_get_name(re->ref), refstr);
6701 free(refstr);
6704 got_ref_list_free(&refs);
6705 return err;
6708 static const struct got_error *
6709 delete_ref_by_name(struct got_repository *repo, const char *refname)
6711 const struct got_error *err;
6712 struct got_reference *ref;
6714 err = got_ref_open(&ref, repo, refname, 0);
6715 if (err)
6716 return err;
6718 err = delete_ref(repo, ref);
6719 got_ref_close(ref);
6720 return err;
6723 static const struct got_error *
6724 add_ref(struct got_repository *repo, const char *refname, const char *target)
6726 const struct got_error *err = NULL;
6727 struct got_object_id *id = NULL;
6728 struct got_reference *ref = NULL;
6729 struct got_reflist_head refs;
6732 * Don't let the user create a reference name with a leading '-'.
6733 * While technically a valid reference name, this case is usually
6734 * an unintended typo.
6736 if (refname[0] == '-')
6737 return got_error_path(refname, GOT_ERR_REF_NAME_MINUS);
6739 TAILQ_INIT(&refs);
6740 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
6741 if (err)
6742 goto done;
6743 err = got_repo_match_object_id(&id, NULL, target, GOT_OBJ_TYPE_ANY,
6744 &refs, repo);
6745 got_ref_list_free(&refs);
6746 if (err)
6747 goto done;
6749 err = got_ref_alloc(&ref, refname, id);
6750 if (err)
6751 goto done;
6753 err = got_ref_write(ref, repo);
6754 done:
6755 if (ref)
6756 got_ref_close(ref);
6757 free(id);
6758 return err;
6761 static const struct got_error *
6762 add_symref(struct got_repository *repo, const char *refname, const char *target)
6764 const struct got_error *err = NULL;
6765 struct got_reference *ref = NULL;
6766 struct got_reference *target_ref = NULL;
6769 * Don't let the user create a reference name with a leading '-'.
6770 * While technically a valid reference name, this case is usually
6771 * an unintended typo.
6773 if (refname[0] == '-')
6774 return got_error_path(refname, GOT_ERR_REF_NAME_MINUS);
6776 err = got_ref_open(&target_ref, repo, target, 0);
6777 if (err)
6778 return err;
6780 err = got_ref_alloc_symref(&ref, refname, target_ref);
6781 if (err)
6782 goto done;
6784 err = got_ref_write(ref, repo);
6785 done:
6786 if (target_ref)
6787 got_ref_close(target_ref);
6788 if (ref)
6789 got_ref_close(ref);
6790 return err;
6793 static const struct got_error *
6794 cmd_ref(int argc, char *argv[])
6796 const struct got_error *error = NULL;
6797 struct got_repository *repo = NULL;
6798 struct got_worktree *worktree = NULL;
6799 char *cwd = NULL, *repo_path = NULL;
6800 int ch, do_list = 0, do_delete = 0, sort_by_time = 0;
6801 const char *obj_arg = NULL, *symref_target= NULL;
6802 char *refname = NULL, *keyword_idstr = NULL;
6803 int *pack_fds = NULL;
6805 #ifndef PROFILE
6806 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
6807 "sendfd unveil", NULL) == -1)
6808 err(1, "pledge");
6809 #endif
6811 while ((ch = getopt(argc, argv, "c:dlr:s:t")) != -1) {
6812 switch (ch) {
6813 case 'c':
6814 obj_arg = optarg;
6815 break;
6816 case 'd':
6817 do_delete = 1;
6818 break;
6819 case 'l':
6820 do_list = 1;
6821 break;
6822 case 'r':
6823 repo_path = realpath(optarg, NULL);
6824 if (repo_path == NULL)
6825 return got_error_from_errno2("realpath",
6826 optarg);
6827 got_path_strip_trailing_slashes(repo_path);
6828 break;
6829 case 's':
6830 symref_target = optarg;
6831 break;
6832 case 't':
6833 sort_by_time = 1;
6834 break;
6835 default:
6836 usage_ref();
6837 /* NOTREACHED */
6841 if (obj_arg && do_list)
6842 option_conflict('c', 'l');
6843 if (obj_arg && do_delete)
6844 option_conflict('c', 'd');
6845 if (obj_arg && symref_target)
6846 option_conflict('c', 's');
6847 if (symref_target && do_delete)
6848 option_conflict('s', 'd');
6849 if (symref_target && do_list)
6850 option_conflict('s', 'l');
6851 if (do_delete && do_list)
6852 option_conflict('d', 'l');
6853 if (sort_by_time && !do_list)
6854 errx(1, "-t option requires -l option");
6856 argc -= optind;
6857 argv += optind;
6859 if (do_list) {
6860 if (argc != 0 && argc != 1)
6861 usage_ref();
6862 if (argc == 1) {
6863 refname = strdup(argv[0]);
6864 if (refname == NULL) {
6865 error = got_error_from_errno("strdup");
6866 goto done;
6869 } else {
6870 if (argc != 1)
6871 usage_ref();
6872 refname = strdup(argv[0]);
6873 if (refname == NULL) {
6874 error = got_error_from_errno("strdup");
6875 goto done;
6879 if (refname)
6880 got_path_strip_trailing_slashes(refname);
6882 cwd = getcwd(NULL, 0);
6883 if (cwd == NULL) {
6884 error = got_error_from_errno("getcwd");
6885 goto done;
6888 error = got_repo_pack_fds_open(&pack_fds);
6889 if (error != NULL)
6890 goto done;
6892 if (repo_path == NULL) {
6893 error = got_worktree_open(&worktree, cwd,
6894 GOT_WORKTREE_GOT_DIR);
6895 if (error && error->code != GOT_ERR_NOT_WORKTREE)
6896 goto done;
6897 else
6898 error = NULL;
6899 if (worktree) {
6900 repo_path =
6901 strdup(got_worktree_get_repo_path(worktree));
6902 if (repo_path == NULL)
6903 error = got_error_from_errno("strdup");
6904 if (error)
6905 goto done;
6906 } else {
6907 repo_path = strdup(cwd);
6908 if (repo_path == NULL) {
6909 error = got_error_from_errno("strdup");
6910 goto done;
6915 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
6916 if (error != NULL)
6917 goto done;
6919 #ifndef PROFILE
6920 if (do_list) {
6921 /* Remove "cpath" promise. */
6922 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
6923 NULL) == -1)
6924 err(1, "pledge");
6926 #endif
6928 error = apply_unveil(got_repo_get_path(repo), do_list,
6929 worktree ? got_worktree_get_root_path(worktree) : NULL);
6930 if (error)
6931 goto done;
6933 if (do_list)
6934 error = list_refs(repo, refname, sort_by_time);
6935 else if (do_delete)
6936 error = delete_ref_by_name(repo, refname);
6937 else if (symref_target)
6938 error = add_symref(repo, refname, symref_target);
6939 else {
6940 if (obj_arg == NULL)
6941 usage_ref();
6943 error = got_keyword_to_idstr(&keyword_idstr, obj_arg,
6944 repo, worktree);
6945 if (error != NULL)
6946 goto done;
6947 if (keyword_idstr != NULL)
6948 obj_arg = keyword_idstr;
6950 error = add_ref(repo, refname, obj_arg);
6952 done:
6953 free(refname);
6954 if (repo) {
6955 const struct got_error *close_err = got_repo_close(repo);
6956 if (error == NULL)
6957 error = close_err;
6959 if (worktree)
6960 got_worktree_close(worktree);
6961 if (pack_fds) {
6962 const struct got_error *pack_err =
6963 got_repo_pack_fds_close(pack_fds);
6964 if (error == NULL)
6965 error = pack_err;
6967 free(cwd);
6968 free(repo_path);
6969 free(keyword_idstr);
6970 return error;
6973 __dead static void
6974 usage_branch(void)
6976 fprintf(stderr, "usage: %s branch [-lnt] [-c commit] [-d name] "
6977 "[-r repository-path] [name]\n", getprogname());
6978 exit(1);
6981 static const struct got_error *
6982 list_branch(struct got_repository *repo, struct got_worktree *worktree,
6983 struct got_reference *ref)
6985 const struct got_error *err = NULL;
6986 const char *refname;
6987 char *refstr;
6988 char marker = ' ';
6990 refname = got_ref_get_name(ref);
6991 if (worktree && strcmp(refname,
6992 got_worktree_get_head_ref_name(worktree)) == 0) {
6993 err = got_worktree_get_state(&marker, repo, worktree,
6994 check_cancelled, NULL);
6995 if (err != NULL)
6996 return err;
6999 if (strncmp(refname, "refs/heads/", 11) == 0)
7000 refname += 11;
7001 if (strncmp(refname, "refs/got/worktree/", 18) == 0)
7002 refname += 18;
7003 if (strncmp(refname, "refs/remotes/", 13) == 0)
7004 refname += 13;
7006 refstr = got_ref_to_str(ref);
7007 if (refstr == NULL)
7008 return got_error_from_errno("got_ref_to_str");
7010 printf("%c %s: %s\n", marker, refname, refstr);
7011 free(refstr);
7012 return NULL;
7015 static const struct got_error *
7016 show_current_branch(struct got_repository *repo, struct got_worktree *worktree)
7018 const char *refname;
7020 if (worktree == NULL)
7021 return got_error(GOT_ERR_NOT_WORKTREE);
7023 refname = got_worktree_get_head_ref_name(worktree);
7025 if (strncmp(refname, "refs/heads/", 11) == 0)
7026 refname += 11;
7027 if (strncmp(refname, "refs/got/worktree/", 18) == 0)
7028 refname += 18;
7030 printf("%s\n", refname);
7032 return NULL;
7035 static const struct got_error *
7036 list_branches(struct got_repository *repo, struct got_worktree *worktree,
7037 int sort_by_time)
7039 static const struct got_error *err = NULL;
7040 struct got_reflist_head refs;
7041 struct got_reflist_entry *re;
7042 struct got_reference *temp_ref = NULL;
7043 int rebase_in_progress, histedit_in_progress;
7045 TAILQ_INIT(&refs);
7047 if (worktree) {
7048 err = got_worktree_rebase_in_progress(&rebase_in_progress,
7049 worktree);
7050 if (err)
7051 return err;
7053 err = got_worktree_histedit_in_progress(&histedit_in_progress,
7054 worktree);
7055 if (err)
7056 return err;
7058 if (rebase_in_progress || histedit_in_progress) {
7059 err = got_ref_open(&temp_ref, repo,
7060 got_worktree_get_head_ref_name(worktree), 0);
7061 if (err)
7062 return err;
7063 list_branch(repo, worktree, temp_ref);
7064 got_ref_close(temp_ref);
7068 err = got_ref_list(&refs, repo, "refs/heads", sort_by_time ?
7069 got_ref_cmp_by_commit_timestamp_descending : got_ref_cmp_by_name,
7070 repo);
7071 if (err)
7072 return err;
7074 TAILQ_FOREACH(re, &refs, entry)
7075 list_branch(repo, worktree, re->ref);
7077 got_ref_list_free(&refs);
7079 err = got_ref_list(&refs, repo, "refs/remotes", sort_by_time ?
7080 got_ref_cmp_by_commit_timestamp_descending : got_ref_cmp_by_name,
7081 repo);
7082 if (err)
7083 return err;
7085 TAILQ_FOREACH(re, &refs, entry)
7086 list_branch(repo, worktree, re->ref);
7088 got_ref_list_free(&refs);
7090 return NULL;
7093 static const struct got_error *
7094 delete_branch(struct got_repository *repo, struct got_worktree *worktree,
7095 const char *branch_name)
7097 const struct got_error *err = NULL;
7098 struct got_reference *ref = NULL;
7099 char *refname, *remote_refname = NULL;
7101 if (strncmp(branch_name, "refs/", 5) == 0)
7102 branch_name += 5;
7103 if (strncmp(branch_name, "heads/", 6) == 0)
7104 branch_name += 6;
7105 else if (strncmp(branch_name, "remotes/", 8) == 0)
7106 branch_name += 8;
7108 if (asprintf(&refname, "refs/heads/%s", branch_name) == -1)
7109 return got_error_from_errno("asprintf");
7111 if (asprintf(&remote_refname, "refs/remotes/%s",
7112 branch_name) == -1) {
7113 err = got_error_from_errno("asprintf");
7114 goto done;
7117 err = got_ref_open(&ref, repo, refname, 0);
7118 if (err) {
7119 const struct got_error *err2;
7120 if (err->code != GOT_ERR_NOT_REF)
7121 goto done;
7123 * Keep 'err' intact such that if neither branch exists
7124 * we report "refs/heads" rather than "refs/remotes" in
7125 * our error message.
7127 err2 = got_ref_open(&ref, repo, remote_refname, 0);
7128 if (err2)
7129 goto done;
7130 err = NULL;
7133 if (worktree &&
7134 strcmp(got_worktree_get_head_ref_name(worktree),
7135 got_ref_get_name(ref)) == 0) {
7136 err = got_error_msg(GOT_ERR_SAME_BRANCH,
7137 "will not delete this work tree's current branch");
7138 goto done;
7141 err = delete_ref(repo, ref);
7142 done:
7143 if (ref)
7144 got_ref_close(ref);
7145 free(refname);
7146 free(remote_refname);
7147 return err;
7150 static const struct got_error *
7151 add_branch(struct got_repository *repo, const char *branch_name,
7152 struct got_object_id *base_commit_id)
7154 const struct got_error *err = NULL;
7155 struct got_reference *ref = NULL;
7156 char *refname = NULL;
7159 * Don't let the user create a branch name with a leading '-'.
7160 * While technically a valid reference name, this case is usually
7161 * an unintended typo.
7163 if (branch_name[0] == '-')
7164 return got_error_path(branch_name, GOT_ERR_REF_NAME_MINUS);
7166 if (strncmp(branch_name, "refs/heads/", 11) == 0)
7167 branch_name += 11;
7169 if (asprintf(&refname, "refs/heads/%s", branch_name) == -1) {
7170 err = got_error_from_errno("asprintf");
7171 goto done;
7174 err = got_ref_open(&ref, repo, refname, 0);
7175 if (err == NULL) {
7176 err = got_error(GOT_ERR_BRANCH_EXISTS);
7177 goto done;
7178 } else if (err->code != GOT_ERR_NOT_REF)
7179 goto done;
7181 err = got_ref_alloc(&ref, refname, base_commit_id);
7182 if (err)
7183 goto done;
7185 err = got_ref_write(ref, repo);
7186 done:
7187 if (ref)
7188 got_ref_close(ref);
7189 free(refname);
7190 return err;
7193 static const struct got_error *
7194 cmd_branch(int argc, char *argv[])
7196 const struct got_error *error = NULL;
7197 struct got_repository *repo = NULL;
7198 struct got_worktree *worktree = NULL;
7199 char *cwd = NULL, *repo_path = NULL;
7200 int ch, do_list = 0, do_show = 0, do_update = 1, sort_by_time = 0;
7201 const char *delref = NULL, *commit_id_arg = NULL;
7202 struct got_reference *ref = NULL;
7203 struct got_pathlist_head paths;
7204 struct got_object_id *commit_id = NULL;
7205 char *commit_id_str = NULL, *keyword_idstr = NULL;;
7206 int *pack_fds = NULL;
7208 TAILQ_INIT(&paths);
7210 #ifndef PROFILE
7211 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
7212 "sendfd unveil", NULL) == -1)
7213 err(1, "pledge");
7214 #endif
7216 while ((ch = getopt(argc, argv, "c:d:lnr:t")) != -1) {
7217 switch (ch) {
7218 case 'c':
7219 commit_id_arg = optarg;
7220 break;
7221 case 'd':
7222 delref = optarg;
7223 break;
7224 case 'l':
7225 do_list = 1;
7226 break;
7227 case 'n':
7228 do_update = 0;
7229 break;
7230 case 'r':
7231 repo_path = realpath(optarg, NULL);
7232 if (repo_path == NULL)
7233 return got_error_from_errno2("realpath",
7234 optarg);
7235 got_path_strip_trailing_slashes(repo_path);
7236 break;
7237 case 't':
7238 sort_by_time = 1;
7239 break;
7240 default:
7241 usage_branch();
7242 /* NOTREACHED */
7246 if (do_list && delref)
7247 option_conflict('l', 'd');
7248 if (sort_by_time && !do_list)
7249 errx(1, "-t option requires -l option");
7251 argc -= optind;
7252 argv += optind;
7254 if (!do_list && !delref && argc == 0)
7255 do_show = 1;
7257 if ((do_list || delref || do_show) && commit_id_arg != NULL)
7258 errx(1, "-c option can only be used when creating a branch");
7260 if (do_list || delref) {
7261 if (argc > 0)
7262 usage_branch();
7263 } else if (!do_show && argc != 1)
7264 usage_branch();
7266 cwd = getcwd(NULL, 0);
7267 if (cwd == NULL) {
7268 error = got_error_from_errno("getcwd");
7269 goto done;
7272 error = got_repo_pack_fds_open(&pack_fds);
7273 if (error != NULL)
7274 goto done;
7276 if (repo_path == NULL) {
7277 error = got_worktree_open(&worktree, cwd,
7278 GOT_WORKTREE_GOT_DIR);
7279 if (error && error->code != GOT_ERR_NOT_WORKTREE)
7280 goto done;
7281 else
7282 error = NULL;
7283 if (worktree) {
7284 repo_path =
7285 strdup(got_worktree_get_repo_path(worktree));
7286 if (repo_path == NULL)
7287 error = got_error_from_errno("strdup");
7288 if (error)
7289 goto done;
7290 } else {
7291 repo_path = strdup(cwd);
7292 if (repo_path == NULL) {
7293 error = got_error_from_errno("strdup");
7294 goto done;
7299 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
7300 if (error != NULL)
7301 goto done;
7303 #ifndef PROFILE
7304 if (do_list || do_show) {
7305 /* Remove "cpath" promise. */
7306 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
7307 NULL) == -1)
7308 err(1, "pledge");
7310 #endif
7312 error = apply_unveil(got_repo_get_path(repo), do_list,
7313 worktree ? got_worktree_get_root_path(worktree) : NULL);
7314 if (error)
7315 goto done;
7317 if (do_show)
7318 error = show_current_branch(repo, worktree);
7319 else if (do_list)
7320 error = list_branches(repo, worktree, sort_by_time);
7321 else if (delref)
7322 error = delete_branch(repo, worktree, delref);
7323 else {
7324 struct got_reflist_head refs;
7325 TAILQ_INIT(&refs);
7326 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
7327 NULL);
7328 if (error)
7329 goto done;
7330 if (commit_id_arg == NULL)
7331 commit_id_arg = worktree ?
7332 got_worktree_get_head_ref_name(worktree) :
7333 GOT_REF_HEAD;
7334 else {
7335 error = got_keyword_to_idstr(&keyword_idstr,
7336 commit_id_arg, repo, worktree);
7337 if (error != NULL)
7338 goto done;
7339 if (keyword_idstr != NULL)
7340 commit_id_arg = keyword_idstr;
7342 error = got_repo_match_object_id(&commit_id, NULL,
7343 commit_id_arg, GOT_OBJ_TYPE_COMMIT, &refs, repo);
7344 got_ref_list_free(&refs);
7345 if (error)
7346 goto done;
7347 error = add_branch(repo, argv[0], commit_id);
7348 if (error)
7349 goto done;
7350 if (worktree && do_update) {
7351 struct got_update_progress_arg upa;
7352 char *branch_refname = NULL;
7354 error = got_object_id_str(&commit_id_str, commit_id);
7355 if (error)
7356 goto done;
7357 error = get_worktree_paths_from_argv(&paths, 0, NULL,
7358 worktree);
7359 if (error)
7360 goto done;
7361 if (asprintf(&branch_refname, "refs/heads/%s", argv[0])
7362 == -1) {
7363 error = got_error_from_errno("asprintf");
7364 goto done;
7366 error = got_ref_open(&ref, repo, branch_refname, 0);
7367 free(branch_refname);
7368 if (error)
7369 goto done;
7370 error = switch_head_ref(ref, commit_id, worktree,
7371 repo);
7372 if (error)
7373 goto done;
7374 error = got_worktree_set_base_commit_id(worktree, repo,
7375 commit_id);
7376 if (error)
7377 goto done;
7378 memset(&upa, 0, sizeof(upa));
7379 error = got_worktree_checkout_files(worktree, &paths,
7380 repo, update_progress, &upa, check_cancelled,
7381 NULL);
7382 if (error)
7383 goto done;
7384 if (upa.did_something) {
7385 printf("Updated to %s: %s\n",
7386 got_worktree_get_head_ref_name(worktree),
7387 commit_id_str);
7389 print_update_progress_stats(&upa);
7392 done:
7393 free(keyword_idstr);
7394 if (ref)
7395 got_ref_close(ref);
7396 if (repo) {
7397 const struct got_error *close_err = got_repo_close(repo);
7398 if (error == NULL)
7399 error = close_err;
7401 if (worktree)
7402 got_worktree_close(worktree);
7403 if (pack_fds) {
7404 const struct got_error *pack_err =
7405 got_repo_pack_fds_close(pack_fds);
7406 if (error == NULL)
7407 error = pack_err;
7409 free(cwd);
7410 free(repo_path);
7411 free(commit_id);
7412 free(commit_id_str);
7413 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
7414 return error;
7418 __dead static void
7419 usage_tag(void)
7421 fprintf(stderr, "usage: %s tag [-lVv] [-c commit] [-m message] "
7422 "[-r repository-path] [-s signer-id] name\n", getprogname());
7423 exit(1);
7426 #if 0
7427 static const struct got_error *
7428 sort_tags(struct got_reflist_head *sorted, struct got_reflist_head *tags)
7430 const struct got_error *err = NULL;
7431 struct got_reflist_entry *re, *se, *new;
7432 struct got_object_id *re_id, *se_id;
7433 struct got_tag_object *re_tag, *se_tag;
7434 time_t re_time, se_time;
7436 STAILQ_FOREACH(re, tags, entry) {
7437 se = STAILQ_FIRST(sorted);
7438 if (se == NULL) {
7439 err = got_reflist_entry_dup(&new, re);
7440 if (err)
7441 return err;
7442 STAILQ_INSERT_HEAD(sorted, new, entry);
7443 continue;
7444 } else {
7445 err = got_ref_resolve(&re_id, repo, re->ref);
7446 if (err)
7447 break;
7448 err = got_object_open_as_tag(&re_tag, repo, re_id);
7449 free(re_id);
7450 if (err)
7451 break;
7452 re_time = got_object_tag_get_tagger_time(re_tag);
7453 got_object_tag_close(re_tag);
7456 while (se) {
7457 err = got_ref_resolve(&se_id, repo, re->ref);
7458 if (err)
7459 break;
7460 err = got_object_open_as_tag(&se_tag, repo, se_id);
7461 free(se_id);
7462 if (err)
7463 break;
7464 se_time = got_object_tag_get_tagger_time(se_tag);
7465 got_object_tag_close(se_tag);
7467 if (se_time > re_time) {
7468 err = got_reflist_entry_dup(&new, re);
7469 if (err)
7470 return err;
7471 STAILQ_INSERT_AFTER(sorted, se, new, entry);
7472 break;
7474 se = STAILQ_NEXT(se, entry);
7475 continue;
7478 done:
7479 return err;
7481 #endif
7483 static const struct got_error *
7484 get_tag_refname(char **refname, const char *tag_name)
7486 const struct got_error *err;
7488 if (strncmp("refs/tags/", tag_name, 10) == 0) {
7489 *refname = strdup(tag_name);
7490 if (*refname == NULL)
7491 return got_error_from_errno("strdup");
7492 } else if (asprintf(refname, "refs/tags/%s", tag_name) == -1) {
7493 err = got_error_from_errno("asprintf");
7494 *refname = NULL;
7495 return err;
7498 return NULL;
7501 static const struct got_error *
7502 list_tags(struct got_repository *repo, const char *tag_name, int verify_tags,
7503 const char *allowed_signers, const char *revoked_signers, int verbosity)
7505 static const struct got_error *err = NULL;
7506 struct got_reflist_head refs;
7507 struct got_reflist_entry *re;
7508 char *wanted_refname = NULL;
7509 int bad_sigs = 0;
7511 TAILQ_INIT(&refs);
7513 err = got_ref_list(&refs, repo, "refs/tags", got_ref_cmp_tags, repo);
7514 if (err)
7515 return err;
7517 if (tag_name) {
7518 struct got_reference *ref;
7519 err = get_tag_refname(&wanted_refname, tag_name);
7520 if (err)
7521 goto done;
7522 /* Wanted tag reference should exist. */
7523 err = got_ref_open(&ref, repo, wanted_refname, 0);
7524 if (err)
7525 goto done;
7526 got_ref_close(ref);
7529 TAILQ_FOREACH(re, &refs, entry) {
7530 const char *refname;
7531 char *refstr, *tagmsg0, *tagmsg, *line, *id_str, *datestr;
7532 char datebuf[26];
7533 const char *tagger, *ssh_sig = NULL;
7534 char *sig_msg = NULL;
7535 time_t tagger_time;
7536 struct got_object_id *id;
7537 struct got_tag_object *tag;
7538 struct got_commit_object *commit = NULL;
7540 refname = got_ref_get_name(re->ref);
7541 if (strncmp(refname, "refs/tags/", 10) != 0 ||
7542 (wanted_refname && strcmp(refname, wanted_refname) != 0))
7543 continue;
7544 refname += 10;
7545 refstr = got_ref_to_str(re->ref);
7546 if (refstr == NULL) {
7547 err = got_error_from_errno("got_ref_to_str");
7548 break;
7551 err = got_ref_resolve(&id, repo, re->ref);
7552 if (err)
7553 break;
7554 err = got_object_open_as_tag(&tag, repo, id);
7555 if (err) {
7556 if (err->code != GOT_ERR_OBJ_TYPE) {
7557 free(id);
7558 break;
7560 /* "lightweight" tag */
7561 err = got_object_open_as_commit(&commit, repo, id);
7562 if (err) {
7563 free(id);
7564 break;
7566 tagger = got_object_commit_get_committer(commit);
7567 tagger_time =
7568 got_object_commit_get_committer_time(commit);
7569 err = got_object_id_str(&id_str, id);
7570 free(id);
7571 if (err)
7572 break;
7573 } else {
7574 free(id);
7575 tagger = got_object_tag_get_tagger(tag);
7576 tagger_time = got_object_tag_get_tagger_time(tag);
7577 err = got_object_id_str(&id_str,
7578 got_object_tag_get_object_id(tag));
7579 if (err)
7580 break;
7583 if (tag && verify_tags) {
7584 ssh_sig = got_sigs_get_tagmsg_ssh_signature(
7585 got_object_tag_get_message(tag));
7586 if (ssh_sig && allowed_signers == NULL) {
7587 err = got_error_msg(
7588 GOT_ERR_VERIFY_TAG_SIGNATURE,
7589 "SSH signature verification requires "
7590 "setting allowed_signers in "
7591 "got.conf(5)");
7592 break;
7596 printf("%stag %s %s\n", GOT_COMMIT_SEP_STR, refname, refstr);
7597 free(refstr);
7598 printf("from: %s\n", tagger);
7599 datestr = get_datestr(&tagger_time, datebuf);
7600 if (datestr)
7601 printf("date: %s UTC\n", datestr);
7602 if (commit)
7603 printf("object: %s %s\n", GOT_OBJ_LABEL_COMMIT, id_str);
7604 else {
7605 switch (got_object_tag_get_object_type(tag)) {
7606 case GOT_OBJ_TYPE_BLOB:
7607 printf("object: %s %s\n", GOT_OBJ_LABEL_BLOB,
7608 id_str);
7609 break;
7610 case GOT_OBJ_TYPE_TREE:
7611 printf("object: %s %s\n", GOT_OBJ_LABEL_TREE,
7612 id_str);
7613 break;
7614 case GOT_OBJ_TYPE_COMMIT:
7615 printf("object: %s %s\n", GOT_OBJ_LABEL_COMMIT,
7616 id_str);
7617 break;
7618 case GOT_OBJ_TYPE_TAG:
7619 printf("object: %s %s\n", GOT_OBJ_LABEL_TAG,
7620 id_str);
7621 break;
7622 default:
7623 break;
7626 free(id_str);
7628 if (ssh_sig) {
7629 err = got_sigs_verify_tag_ssh(&sig_msg, tag, ssh_sig,
7630 allowed_signers, revoked_signers, verbosity);
7631 if (err && err->code == GOT_ERR_BAD_TAG_SIGNATURE)
7632 bad_sigs = 1;
7633 else if (err)
7634 break;
7635 printf("signature: %s", sig_msg);
7636 free(sig_msg);
7637 sig_msg = NULL;
7640 if (commit) {
7641 err = got_object_commit_get_logmsg(&tagmsg0, commit);
7642 if (err)
7643 break;
7644 got_object_commit_close(commit);
7645 } else {
7646 tagmsg0 = strdup(got_object_tag_get_message(tag));
7647 got_object_tag_close(tag);
7648 if (tagmsg0 == NULL) {
7649 err = got_error_from_errno("strdup");
7650 break;
7654 tagmsg = tagmsg0;
7655 do {
7656 line = strsep(&tagmsg, "\n");
7657 if (line)
7658 printf(" %s\n", line);
7659 } while (line);
7660 free(tagmsg0);
7662 done:
7663 got_ref_list_free(&refs);
7664 free(wanted_refname);
7666 if (err == NULL && bad_sigs)
7667 err = got_error(GOT_ERR_BAD_TAG_SIGNATURE);
7668 return err;
7671 static const struct got_error *
7672 get_tag_message(char **tagmsg, char **tagmsg_path, const char *commit_id_str,
7673 const char *tag_name, const char *editor, const char *repo_path)
7675 const struct got_error *err = NULL;
7676 char *template = NULL, *initial_content = NULL;
7677 int initial_content_len;
7678 int fd = -1;
7680 if (asprintf(&template, GOT_TMPDIR_STR "/got-tagmsg") == -1) {
7681 err = got_error_from_errno("asprintf");
7682 goto done;
7685 initial_content_len = asprintf(&initial_content,
7686 "\n# tagging commit %s as %s\n",
7687 commit_id_str, tag_name);
7688 if (initial_content_len == -1) {
7689 err = got_error_from_errno("asprintf");
7690 goto done;
7693 err = got_opentemp_named_fd(tagmsg_path, &fd, template, "");
7694 if (err)
7695 goto done;
7697 if (write(fd, initial_content, initial_content_len) == -1) {
7698 err = got_error_from_errno2("write", *tagmsg_path);
7699 goto done;
7701 if (close(fd) == -1) {
7702 err = got_error_from_errno2("close", *tagmsg_path);
7703 goto done;
7705 fd = -1;
7707 err = edit_logmsg(tagmsg, editor, *tagmsg_path, initial_content,
7708 initial_content_len, 1);
7709 done:
7710 free(initial_content);
7711 free(template);
7713 if (fd != -1 && close(fd) == -1 && err == NULL)
7714 err = got_error_from_errno2("close", *tagmsg_path);
7716 if (err) {
7717 free(*tagmsg);
7718 *tagmsg = NULL;
7720 return err;
7723 static const struct got_error *
7724 add_tag(struct got_repository *repo, const char *tagger,
7725 const char *tag_name, const char *commit_arg, const char *tagmsg_arg,
7726 const char *signer_id, const char *editor, int verbosity)
7728 const struct got_error *err = NULL;
7729 struct got_object_id *commit_id = NULL, *tag_id = NULL;
7730 char *label = NULL, *commit_id_str = NULL;
7731 struct got_reference *ref = NULL;
7732 char *refname = NULL, *tagmsg = NULL;
7733 char *tagmsg_path = NULL, *tag_id_str = NULL;
7734 int preserve_tagmsg = 0;
7735 struct got_reflist_head refs;
7737 TAILQ_INIT(&refs);
7740 * Don't let the user create a tag name with a leading '-'.
7741 * While technically a valid reference name, this case is usually
7742 * an unintended typo.
7744 if (tag_name[0] == '-')
7745 return got_error_path(tag_name, GOT_ERR_REF_NAME_MINUS);
7747 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
7748 if (err)
7749 goto done;
7751 err = got_repo_match_object_id(&commit_id, &label, commit_arg,
7752 GOT_OBJ_TYPE_COMMIT, &refs, repo);
7753 if (err)
7754 goto done;
7756 err = got_object_id_str(&commit_id_str, commit_id);
7757 if (err)
7758 goto done;
7760 err = get_tag_refname(&refname, tag_name);
7761 if (err)
7762 goto done;
7763 if (strncmp("refs/tags/", tag_name, 10) == 0)
7764 tag_name += 10;
7766 err = got_ref_open(&ref, repo, refname, 0);
7767 if (err == NULL) {
7768 err = got_error(GOT_ERR_TAG_EXISTS);
7769 goto done;
7770 } else if (err->code != GOT_ERR_NOT_REF)
7771 goto done;
7773 if (tagmsg_arg == NULL) {
7774 err = get_tag_message(&tagmsg, &tagmsg_path, commit_id_str,
7775 tag_name, editor, got_repo_get_path(repo));
7776 if (err) {
7777 if (err->code != GOT_ERR_COMMIT_MSG_EMPTY &&
7778 tagmsg_path != NULL)
7779 preserve_tagmsg = 1;
7780 goto done;
7784 err = got_object_tag_create(&tag_id, tag_name, commit_id,
7785 tagger, time(NULL), tagmsg ? tagmsg : tagmsg_arg, signer_id, repo,
7786 verbosity);
7787 if (err) {
7788 if (tagmsg_path)
7789 preserve_tagmsg = 1;
7790 goto done;
7793 err = got_ref_alloc(&ref, refname, tag_id);
7794 if (err) {
7795 if (tagmsg_path)
7796 preserve_tagmsg = 1;
7797 goto done;
7800 err = got_ref_write(ref, repo);
7801 if (err) {
7802 if (tagmsg_path)
7803 preserve_tagmsg = 1;
7804 goto done;
7807 err = got_object_id_str(&tag_id_str, tag_id);
7808 if (err) {
7809 if (tagmsg_path)
7810 preserve_tagmsg = 1;
7811 goto done;
7813 printf("Created tag %s\n", tag_id_str);
7814 done:
7815 if (preserve_tagmsg) {
7816 fprintf(stderr, "%s: tag message preserved in %s\n",
7817 getprogname(), tagmsg_path);
7818 } else if (tagmsg_path && unlink(tagmsg_path) == -1 && err == NULL)
7819 err = got_error_from_errno2("unlink", tagmsg_path);
7820 free(tag_id_str);
7821 if (ref)
7822 got_ref_close(ref);
7823 free(commit_id);
7824 free(commit_id_str);
7825 free(refname);
7826 free(tagmsg);
7827 free(tagmsg_path);
7828 got_ref_list_free(&refs);
7829 return err;
7832 static const struct got_error *
7833 cmd_tag(int argc, char *argv[])
7835 const struct got_error *error = NULL;
7836 struct got_repository *repo = NULL;
7837 struct got_worktree *worktree = NULL;
7838 char *cwd = NULL, *repo_path = NULL, *commit_id_str = NULL;
7839 char *gitconfig_path = NULL, *tagger = NULL, *keyword_idstr = NULL;
7840 char *allowed_signers = NULL, *revoked_signers = NULL, *editor = NULL;
7841 const char *signer_id = NULL;
7842 const char *tag_name = NULL, *commit_id_arg = NULL, *tagmsg = NULL;
7843 int ch, do_list = 0, verify_tags = 0, verbosity = 0;
7844 int *pack_fds = NULL;
7846 #ifndef PROFILE
7847 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
7848 "sendfd unveil", NULL) == -1)
7849 err(1, "pledge");
7850 #endif
7852 while ((ch = getopt(argc, argv, "c:lm:r:s:Vv")) != -1) {
7853 switch (ch) {
7854 case 'c':
7855 commit_id_arg = optarg;
7856 break;
7857 case 'l':
7858 do_list = 1;
7859 break;
7860 case 'm':
7861 tagmsg = optarg;
7862 break;
7863 case 'r':
7864 repo_path = realpath(optarg, NULL);
7865 if (repo_path == NULL) {
7866 error = got_error_from_errno2("realpath",
7867 optarg);
7868 goto done;
7870 got_path_strip_trailing_slashes(repo_path);
7871 break;
7872 case 's':
7873 signer_id = optarg;
7874 break;
7875 case 'V':
7876 verify_tags = 1;
7877 break;
7878 case 'v':
7879 if (verbosity < 0)
7880 verbosity = 0;
7881 else if (verbosity < 3)
7882 verbosity++;
7883 break;
7884 default:
7885 usage_tag();
7886 /* NOTREACHED */
7890 argc -= optind;
7891 argv += optind;
7893 if (do_list || verify_tags) {
7894 if (commit_id_arg != NULL)
7895 errx(1,
7896 "-c option can only be used when creating a tag");
7897 if (tagmsg) {
7898 if (do_list)
7899 option_conflict('l', 'm');
7900 else
7901 option_conflict('V', 'm');
7903 if (signer_id) {
7904 if (do_list)
7905 option_conflict('l', 's');
7906 else
7907 option_conflict('V', 's');
7909 if (argc > 1)
7910 usage_tag();
7911 } else if (argc != 1)
7912 usage_tag();
7914 if (argc == 1)
7915 tag_name = argv[0];
7917 cwd = getcwd(NULL, 0);
7918 if (cwd == NULL) {
7919 error = got_error_from_errno("getcwd");
7920 goto done;
7923 error = got_repo_pack_fds_open(&pack_fds);
7924 if (error != NULL)
7925 goto done;
7927 if (repo_path == NULL) {
7928 error = got_worktree_open(&worktree, cwd,
7929 GOT_WORKTREE_GOT_DIR);
7930 if (error && error->code != GOT_ERR_NOT_WORKTREE)
7931 goto done;
7932 else
7933 error = NULL;
7934 if (worktree) {
7935 repo_path =
7936 strdup(got_worktree_get_repo_path(worktree));
7937 if (repo_path == NULL)
7938 error = got_error_from_errno("strdup");
7939 if (error)
7940 goto done;
7941 } else {
7942 repo_path = strdup(cwd);
7943 if (repo_path == NULL) {
7944 error = got_error_from_errno("strdup");
7945 goto done;
7950 if (do_list || verify_tags) {
7951 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
7952 if (error != NULL)
7953 goto done;
7954 error = get_allowed_signers(&allowed_signers, repo, worktree);
7955 if (error)
7956 goto done;
7957 error = get_revoked_signers(&revoked_signers, repo, worktree);
7958 if (error)
7959 goto done;
7960 if (worktree) {
7961 /* Release work tree lock. */
7962 got_worktree_close(worktree);
7963 worktree = NULL;
7967 * Remove "cpath" promise unless needed for signature tmpfile
7968 * creation.
7970 if (verify_tags)
7971 got_sigs_apply_unveil();
7972 else {
7973 #ifndef PROFILE
7974 if (pledge("stdio rpath wpath flock proc exec sendfd "
7975 "unveil", NULL) == -1)
7976 err(1, "pledge");
7977 #endif
7979 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
7980 if (error)
7981 goto done;
7982 error = list_tags(repo, tag_name, verify_tags, allowed_signers,
7983 revoked_signers, verbosity);
7984 } else {
7985 error = get_gitconfig_path(&gitconfig_path);
7986 if (error)
7987 goto done;
7988 error = got_repo_open(&repo, repo_path, gitconfig_path,
7989 pack_fds);
7990 if (error != NULL)
7991 goto done;
7993 error = get_author(&tagger, repo, worktree);
7994 if (error)
7995 goto done;
7996 if (signer_id == NULL)
7997 signer_id = get_signer_id(repo, worktree);
7999 if (tagmsg == NULL) {
8000 error = get_editor(&editor);
8001 if (error)
8002 goto done;
8003 if (unveil(editor, "x") != 0) {
8004 error = got_error_from_errno2("unveil", editor);
8005 goto done;
8008 if (signer_id) {
8009 error = got_sigs_apply_unveil();
8010 if (error)
8011 goto done;
8013 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
8014 if (error)
8015 goto done;
8017 if (commit_id_arg == NULL) {
8018 struct got_reference *head_ref;
8019 struct got_object_id *commit_id;
8020 error = got_ref_open(&head_ref, repo,
8021 worktree ? got_worktree_get_head_ref_name(worktree)
8022 : GOT_REF_HEAD, 0);
8023 if (error)
8024 goto done;
8025 error = got_ref_resolve(&commit_id, repo, head_ref);
8026 got_ref_close(head_ref);
8027 if (error)
8028 goto done;
8029 error = got_object_id_str(&commit_id_str, commit_id);
8030 free(commit_id);
8031 if (error)
8032 goto done;
8033 } else {
8034 error = got_keyword_to_idstr(&keyword_idstr,
8035 commit_id_arg, repo, worktree);
8036 if (error != NULL)
8037 goto done;
8038 commit_id_str = keyword_idstr;
8041 if (worktree) {
8042 /* Release work tree lock. */
8043 got_worktree_close(worktree);
8044 worktree = NULL;
8047 error = add_tag(repo, tagger, tag_name,
8048 commit_id_str ? commit_id_str : commit_id_arg, tagmsg,
8049 signer_id, editor, verbosity);
8051 done:
8052 if (repo) {
8053 const struct got_error *close_err = got_repo_close(repo);
8054 if (error == NULL)
8055 error = close_err;
8057 if (worktree)
8058 got_worktree_close(worktree);
8059 if (pack_fds) {
8060 const struct got_error *pack_err =
8061 got_repo_pack_fds_close(pack_fds);
8062 if (error == NULL)
8063 error = pack_err;
8065 free(cwd);
8066 free(editor);
8067 free(repo_path);
8068 free(gitconfig_path);
8069 free(commit_id_str);
8070 free(tagger);
8071 free(allowed_signers);
8072 free(revoked_signers);
8073 return error;
8076 __dead static void
8077 usage_add(void)
8079 fprintf(stderr, "usage: %s add [-IR] path ...\n", getprogname());
8080 exit(1);
8083 static const struct got_error *
8084 add_progress(void *arg, unsigned char status, const char *path)
8086 while (path[0] == '/')
8087 path++;
8088 printf("%c %s\n", status, path);
8089 return NULL;
8092 static const struct got_error *
8093 cmd_add(int argc, char *argv[])