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 <sys/queue.h>
20 #include <sys/time.h>
21 #include <sys/types.h>
22 #include <sys/stat.h>
23 #include <sys/wait.h>
25 #include <err.h>
26 #include <errno.h>
27 #include <fcntl.h>
28 #include <limits.h>
29 #include <locale.h>
30 #include <ctype.h>
31 #include <sha1.h>
32 #include <sha2.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>
43 #include <util.h>
45 #include "got_version.h"
46 #include "got_error.h"
47 #include "got_object.h"
48 #include "got_reference.h"
49 #include "got_repository.h"
50 #include "got_path.h"
51 #include "got_cancel.h"
52 #include "got_worktree.h"
53 #include "got_diff.h"
54 #include "got_commit_graph.h"
55 #include "got_fetch.h"
56 #include "got_send.h"
57 #include "got_blame.h"
58 #include "got_privsep.h"
59 #include "got_opentemp.h"
60 #include "got_gotconfig.h"
61 #include "got_dial.h"
62 #include "got_patch.h"
63 #include "got_sigs.h"
64 #include "got_date.h"
65 #include "got_keyword.h"
67 #ifndef nitems
68 #define nitems(_a) (sizeof((_a)) / sizeof((_a)[0]))
69 #endif
71 #ifndef GOT_DEFAULT_EDITOR
72 #define GOT_DEFAULT_EDITOR "/usr/bin/vi"
73 #endif
75 static volatile sig_atomic_t sigint_received;
76 static volatile sig_atomic_t sigpipe_received;
78 static void
79 catch_sigint(int signo)
80 {
81 sigint_received = 1;
82 }
84 static void
85 catch_sigpipe(int signo)
86 {
87 sigpipe_received = 1;
88 }
91 struct got_cmd {
92 const char *cmd_name;
93 const struct got_error *(*cmd_main)(int, char *[]);
94 void (*cmd_usage)(void);
95 const char *cmd_alias;
96 };
98 __dead static void usage(int, int);
99 __dead static void usage_init(void);
100 __dead static void usage_import(void);
101 __dead static void usage_clone(void);
102 __dead static void usage_fetch(void);
103 __dead static void usage_checkout(void);
104 __dead static void usage_update(void);
105 __dead static void usage_log(void);
106 __dead static void usage_diff(void);
107 __dead static void usage_blame(void);
108 __dead static void usage_tree(void);
109 __dead static void usage_status(void);
110 __dead static void usage_ref(void);
111 __dead static void usage_branch(void);
112 __dead static void usage_tag(void);
113 __dead static void usage_add(void);
114 __dead static void usage_remove(void);
115 __dead static void usage_patch(void);
116 __dead static void usage_revert(void);
117 __dead static void usage_commit(void);
118 __dead static void usage_send(void);
119 __dead static void usage_cherrypick(void);
120 __dead static void usage_backout(void);
121 __dead static void usage_rebase(void);
122 __dead static void usage_histedit(void);
123 __dead static void usage_integrate(void);
124 __dead static void usage_merge(void);
125 __dead static void usage_stage(void);
126 __dead static void usage_unstage(void);
127 __dead static void usage_cat(void);
128 __dead static void usage_info(void);
130 static const struct got_error* cmd_init(int, char *[]);
131 static const struct got_error* cmd_import(int, char *[]);
132 static const struct got_error* cmd_clone(int, char *[]);
133 static const struct got_error* cmd_fetch(int, char *[]);
134 static const struct got_error* cmd_checkout(int, char *[]);
135 static const struct got_error* cmd_update(int, char *[]);
136 static const struct got_error* cmd_log(int, char *[]);
137 static const struct got_error* cmd_diff(int, char *[]);
138 static const struct got_error* cmd_blame(int, char *[]);
139 static const struct got_error* cmd_tree(int, char *[]);
140 static const struct got_error* cmd_status(int, char *[]);
141 static const struct got_error* cmd_ref(int, char *[]);
142 static const struct got_error* cmd_branch(int, char *[]);
143 static const struct got_error* cmd_tag(int, char *[]);
144 static const struct got_error* cmd_add(int, char *[]);
145 static const struct got_error* cmd_remove(int, char *[]);
146 static const struct got_error* cmd_patch(int, char *[]);
147 static const struct got_error* cmd_revert(int, char *[]);
148 static const struct got_error* cmd_commit(int, char *[]);
149 static const struct got_error* cmd_send(int, char *[]);
150 static const struct got_error* cmd_cherrypick(int, char *[]);
151 static const struct got_error* cmd_backout(int, char *[]);
152 static const struct got_error* cmd_rebase(int, char *[]);
153 static const struct got_error* cmd_histedit(int, char *[]);
154 static const struct got_error* cmd_integrate(int, char *[]);
155 static const struct got_error* cmd_merge(int, char *[]);
156 static const struct got_error* cmd_stage(int, char *[]);
157 static const struct got_error* cmd_unstage(int, char *[]);
158 static const struct got_error* cmd_cat(int, char *[]);
159 static const struct got_error* cmd_info(int, char *[]);
161 static const struct got_cmd got_commands[] = {
162 { "init", cmd_init, usage_init, "" },
163 { "import", cmd_import, usage_import, "im" },
164 { "clone", cmd_clone, usage_clone, "cl" },
165 { "fetch", cmd_fetch, usage_fetch, "fe" },
166 { "checkout", cmd_checkout, usage_checkout, "co" },
167 { "update", cmd_update, usage_update, "up" },
168 { "log", cmd_log, usage_log, "" },
169 { "diff", cmd_diff, usage_diff, "di" },
170 { "blame", cmd_blame, usage_blame, "bl" },
171 { "tree", cmd_tree, usage_tree, "tr" },
172 { "status", cmd_status, usage_status, "st" },
173 { "ref", cmd_ref, usage_ref, "" },
174 { "branch", cmd_branch, usage_branch, "br" },
175 { "tag", cmd_tag, usage_tag, "" },
176 { "add", cmd_add, usage_add, "" },
177 { "remove", cmd_remove, usage_remove, "rm" },
178 { "patch", cmd_patch, usage_patch, "pa" },
179 { "revert", cmd_revert, usage_revert, "rv" },
180 { "commit", cmd_commit, usage_commit, "ci" },
181 { "send", cmd_send, usage_send, "se" },
182 { "cherrypick", cmd_cherrypick, usage_cherrypick, "cy" },
183 { "backout", cmd_backout, usage_backout, "bo" },
184 { "rebase", cmd_rebase, usage_rebase, "rb" },
185 { "histedit", cmd_histedit, usage_histedit, "he" },
186 { "integrate", cmd_integrate, usage_integrate,"ig" },
187 { "merge", cmd_merge, usage_merge, "mg" },
188 { "stage", cmd_stage, usage_stage, "sg" },
189 { "unstage", cmd_unstage, usage_unstage, "ug" },
190 { "cat", cmd_cat, usage_cat, "" },
191 { "info", cmd_info, usage_info, "" },
192 };
194 static void
195 list_commands(FILE *fp)
197 size_t i;
199 fprintf(fp, "commands:");
200 for (i = 0; i < nitems(got_commands); i++) {
201 const struct got_cmd *cmd = &got_commands[i];
202 fprintf(fp, " %s", cmd->cmd_name);
204 fputc('\n', fp);
207 __dead static void
208 option_conflict(char a, char b)
210 errx(1, "-%c and -%c options are mutually exclusive", a, b);
213 int
214 main(int argc, char *argv[])
216 const struct got_cmd *cmd;
217 size_t i;
218 int ch;
219 int hflag = 0, Vflag = 0;
220 static const struct option longopts[] = {
221 { "version", no_argument, NULL, 'V' },
222 { NULL, 0, NULL, 0 }
223 };
225 setlocale(LC_CTYPE, "");
227 while ((ch = getopt_long(argc, argv, "+hV", longopts, NULL)) != -1) {
228 switch (ch) {
229 case 'h':
230 hflag = 1;
231 break;
232 case 'V':
233 Vflag = 1;
234 break;
235 default:
236 usage(hflag, 1);
237 /* NOTREACHED */
241 argc -= optind;
242 argv += optind;
243 optind = 1;
244 optreset = 1;
246 if (Vflag) {
247 got_version_print_str();
248 return 0;
251 if (argc <= 0)
252 usage(hflag, hflag ? 0 : 1);
254 signal(SIGINT, catch_sigint);
255 signal(SIGPIPE, catch_sigpipe);
257 for (i = 0; i < nitems(got_commands); i++) {
258 const struct got_error *error;
260 cmd = &got_commands[i];
262 if (strcmp(cmd->cmd_name, argv[0]) != 0 &&
263 strcmp(cmd->cmd_alias, argv[0]) != 0)
264 continue;
266 if (hflag)
267 cmd->cmd_usage();
269 error = cmd->cmd_main(argc, argv);
270 if (error && error->code != GOT_ERR_CANCELLED &&
271 error->code != GOT_ERR_PRIVSEP_EXIT &&
272 !(sigpipe_received &&
273 error->code == GOT_ERR_ERRNO && errno == EPIPE) &&
274 !(sigint_received &&
275 error->code == GOT_ERR_ERRNO && errno == EINTR)) {
276 fflush(stdout);
277 fprintf(stderr, "%s: %s\n", getprogname(), error->msg);
278 return 1;
281 return 0;
284 fprintf(stderr, "%s: unknown command '%s'\n", getprogname(), argv[0]);
285 list_commands(stderr);
286 return 1;
289 __dead static void
290 usage(int hflag, int status)
292 FILE *fp = (status == 0) ? stdout : stderr;
294 fprintf(fp, "usage: %s [-hV] command [arg ...]\n",
295 getprogname());
296 if (hflag)
297 list_commands(fp);
298 exit(status);
301 static const struct got_error *
302 get_editor(char **abspath)
304 const struct got_error *err = NULL;
305 const char *editor;
307 *abspath = NULL;
309 editor = getenv("VISUAL");
310 if (editor == NULL)
311 editor = getenv("EDITOR");
313 if (editor) {
314 err = got_path_find_prog(abspath, editor);
315 if (err)
316 return err;
319 if (*abspath == NULL) {
320 *abspath = strdup(GOT_DEFAULT_EDITOR);
321 if (*abspath == NULL)
322 return got_error_from_errno("strdup");
325 return NULL;
328 static const struct got_error *
329 apply_unveil(const char *repo_path, int repo_read_only,
330 const char *worktree_path)
332 const struct got_error *err;
334 #ifdef PROFILE
335 if (unveil("gmon.out", "rwc") != 0)
336 return got_error_from_errno2("unveil", "gmon.out");
337 #endif
338 if (repo_path && unveil(repo_path, repo_read_only ? "r" : "rwc") != 0)
339 return got_error_from_errno2("unveil", repo_path);
341 if (worktree_path && unveil(worktree_path, "rwc") != 0)
342 return got_error_from_errno2("unveil", worktree_path);
344 if (unveil(GOT_TMPDIR_STR, "rwc") != 0)
345 return got_error_from_errno2("unveil", GOT_TMPDIR_STR);
347 err = got_privsep_unveil_exec_helpers();
348 if (err != NULL)
349 return err;
351 if (unveil(NULL, NULL) != 0)
352 return got_error_from_errno("unveil");
354 return NULL;
357 __dead static void
358 usage_init(void)
360 fprintf(stderr, "usage: %s init [-b branch] repository-path\n",
361 getprogname());
362 exit(1);
365 static const struct got_error *
366 cmd_init(int argc, char *argv[])
368 const struct got_error *error = NULL;
369 const char *head_name = NULL;
370 char *repo_path = NULL;
371 int ch;
373 while ((ch = getopt(argc, argv, "b:")) != -1) {
374 switch (ch) {
375 case 'b':
376 head_name = optarg;
377 break;
378 default:
379 usage_init();
380 /* NOTREACHED */
384 argc -= optind;
385 argv += optind;
387 #ifndef PROFILE
388 if (pledge("stdio rpath wpath cpath unveil", NULL) == -1)
389 err(1, "pledge");
390 #endif
391 if (argc != 1)
392 usage_init();
394 repo_path = strdup(argv[0]);
395 if (repo_path == NULL)
396 return got_error_from_errno("strdup");
398 got_path_strip_trailing_slashes(repo_path);
400 error = got_path_mkdir(repo_path);
401 if (error &&
402 !(error->code == GOT_ERR_ERRNO && errno == EEXIST))
403 goto done;
405 error = apply_unveil(repo_path, 0, NULL);
406 if (error)
407 goto done;
409 error = got_repo_init(repo_path, head_name);
410 done:
411 free(repo_path);
412 return error;
415 __dead static void
416 usage_import(void)
418 fprintf(stderr, "usage: %s import [-b branch] [-I pattern] [-m message] "
419 "[-r repository-path] directory\n", getprogname());
420 exit(1);
423 static int
424 spawn_editor(const char *editor, const char *file)
426 pid_t pid;
427 sig_t sighup, sigint, sigquit;
428 int st = -1;
430 sighup = signal(SIGHUP, SIG_IGN);
431 sigint = signal(SIGINT, SIG_IGN);
432 sigquit = signal(SIGQUIT, SIG_IGN);
434 switch (pid = fork()) {
435 case -1:
436 goto doneediting;
437 case 0:
438 execl(editor, editor, file, (char *)NULL);
439 _exit(127);
442 while (waitpid(pid, &st, 0) == -1)
443 if (errno != EINTR)
444 break;
446 doneediting:
447 (void)signal(SIGHUP, sighup);
448 (void)signal(SIGINT, sigint);
449 (void)signal(SIGQUIT, sigquit);
451 if (!WIFEXITED(st)) {
452 errno = EINTR;
453 return -1;
456 return WEXITSTATUS(st);
459 static const struct got_error *
460 read_logmsg(char **logmsg, size_t *len, FILE *fp, size_t filesize)
462 const struct got_error *err = NULL;
463 char *line = NULL;
464 size_t linesize = 0;
466 *logmsg = NULL;
467 *len = 0;
469 if (fseeko(fp, 0L, SEEK_SET) == -1)
470 return got_error_from_errno("fseeko");
472 *logmsg = malloc(filesize + 1);
473 if (*logmsg == NULL)
474 return got_error_from_errno("malloc");
475 (*logmsg)[0] = '\0';
477 while (getline(&line, &linesize, fp) != -1) {
478 if (line[0] == '#' || (*len == 0 && line[0] == '\n'))
479 continue; /* remove comments and leading empty lines */
480 *len = strlcat(*logmsg, line, filesize + 1);
481 if (*len >= filesize + 1) {
482 err = got_error(GOT_ERR_NO_SPACE);
483 goto done;
486 if (ferror(fp)) {
487 err = got_ferror(fp, GOT_ERR_IO);
488 goto done;
491 while (*len > 0 && (*logmsg)[*len - 1] == '\n') {
492 (*logmsg)[*len - 1] = '\0';
493 (*len)--;
495 done:
496 free(line);
497 if (err) {
498 free(*logmsg);
499 *logmsg = NULL;
500 *len = 0;
502 return err;
505 static const struct got_error *
506 edit_logmsg(char **logmsg, const char *editor, const char *logmsg_path,
507 const char *initial_content, size_t initial_content_len,
508 int require_modification)
510 const struct got_error *err = NULL;
511 struct stat st, st2;
512 FILE *fp = NULL;
513 size_t logmsg_len;
515 *logmsg = NULL;
517 if (stat(logmsg_path, &st) == -1)
518 return got_error_from_errno2("stat", logmsg_path);
520 if (spawn_editor(editor, logmsg_path) == -1)
521 return got_error_from_errno("failed spawning editor");
523 if (require_modification) {
524 struct timespec timeout;
526 timeout.tv_sec = 0;
527 timeout.tv_nsec = 1;
528 nanosleep(&timeout, NULL);
531 if (stat(logmsg_path, &st2) == -1)
532 return got_error_from_errno2("stat", logmsg_path);
534 if (require_modification && st.st_size == st2.st_size &&
535 timespeccmp(&st.st_mtim, &st2.st_mtim, ==))
536 return got_error_msg(GOT_ERR_COMMIT_MSG_EMPTY,
537 "no changes made to commit message, aborting");
539 fp = fopen(logmsg_path, "re");
540 if (fp == NULL) {
541 err = got_error_from_errno("fopen");
542 goto done;
545 /* strip comments and leading/trailing newlines */
546 err = read_logmsg(logmsg, &logmsg_len, fp, st2.st_size);
547 if (err)
548 goto done;
549 if (logmsg_len == 0) {
550 err = got_error_msg(GOT_ERR_COMMIT_MSG_EMPTY,
551 "commit message cannot be empty, aborting");
552 goto done;
554 done:
555 if (fp && fclose(fp) == EOF && err == NULL)
556 err = got_error_from_errno("fclose");
557 if (err) {
558 free(*logmsg);
559 *logmsg = NULL;
561 return err;
564 static const struct got_error *
565 collect_import_msg(char **logmsg, char **logmsg_path, const char *editor,
566 const char *path_dir, const char *branch_name)
568 char *initial_content = NULL;
569 const struct got_error *err = NULL;
570 int initial_content_len;
571 int fd = -1;
573 initial_content_len = asprintf(&initial_content,
574 "\n# %s to be imported to branch %s\n", path_dir,
575 branch_name);
576 if (initial_content_len == -1)
577 return got_error_from_errno("asprintf");
579 err = got_opentemp_named_fd(logmsg_path, &fd,
580 GOT_TMPDIR_STR "/got-importmsg", "");
581 if (err)
582 goto done;
584 if (write(fd, initial_content, initial_content_len) == -1) {
585 err = got_error_from_errno2("write", *logmsg_path);
586 goto done;
588 if (close(fd) == -1) {
589 err = got_error_from_errno2("close", *logmsg_path);
590 goto done;
592 fd = -1;
594 err = edit_logmsg(logmsg, editor, *logmsg_path, initial_content,
595 initial_content_len, 1);
596 done:
597 if (fd != -1 && close(fd) == -1 && err == NULL)
598 err = got_error_from_errno2("close", *logmsg_path);
599 free(initial_content);
600 if (err) {
601 free(*logmsg_path);
602 *logmsg_path = NULL;
604 return err;
607 static const struct got_error *
608 import_progress(void *arg, const char *path)
610 printf("A %s\n", path);
611 return NULL;
614 static const struct got_error *
615 valid_author(const char *author)
617 const char *email = author;
619 /*
620 * Git' expects the author (or committer) to be in the form
621 * "name <email>", which are mostly free form (see the
622 * "committer" description in git-fast-import(1)). We're only
623 * doing this to avoid git's object parser breaking on commits
624 * we create.
625 */
627 while (*author && *author != '\n' && *author != '<' && *author != '>')
628 author++;
629 if (author != email && *author == '<' && *(author - 1) != ' ')
630 return got_error_fmt(GOT_ERR_COMMIT_BAD_AUTHOR, "%s: space "
631 "between author name and email required", email);
632 if (*author++ != '<')
633 return got_error_fmt(GOT_ERR_COMMIT_NO_EMAIL, "%s", email);
634 while (*author && *author != '\n' && *author != '<' && *author != '>')
635 author++;
636 if (strcmp(author, ">") != 0)
637 return got_error_fmt(GOT_ERR_COMMIT_NO_EMAIL, "%s", email);
638 return NULL;
641 static const struct got_error *
642 get_author(char **author, struct got_repository *repo,
643 struct got_worktree *worktree)
645 const struct got_error *err = NULL;
646 const char *got_author = NULL, *name, *email;
647 const struct got_gotconfig *worktree_conf = NULL, *repo_conf = NULL;
649 *author = NULL;
651 if (worktree)
652 worktree_conf = got_worktree_get_gotconfig(worktree);
653 repo_conf = got_repo_get_gotconfig(repo);
655 /*
656 * Priority of potential author information sources, from most
657 * significant to least significant:
658 * 1) work tree's .got/got.conf file
659 * 2) repository's got.conf file
660 * 3) repository's git config file
661 * 4) environment variables
662 * 5) global git config files (in user's home directory or /etc)
663 */
665 if (worktree_conf)
666 got_author = got_gotconfig_get_author(worktree_conf);
667 if (got_author == NULL)
668 got_author = got_gotconfig_get_author(repo_conf);
669 if (got_author == NULL) {
670 name = got_repo_get_gitconfig_author_name(repo);
671 email = got_repo_get_gitconfig_author_email(repo);
672 if (name && email) {
673 if (asprintf(author, "%s <%s>", name, email) == -1)
674 return got_error_from_errno("asprintf");
675 return NULL;
678 got_author = getenv("GOT_AUTHOR");
679 if (got_author == NULL) {
680 name = got_repo_get_global_gitconfig_author_name(repo);
681 email = got_repo_get_global_gitconfig_author_email(
682 repo);
683 if (name && email) {
684 if (asprintf(author, "%s <%s>", name, email)
685 == -1)
686 return got_error_from_errno("asprintf");
687 return NULL;
689 /* TODO: Look up user in password database? */
690 return got_error(GOT_ERR_COMMIT_NO_AUTHOR);
694 *author = strdup(got_author);
695 if (*author == NULL)
696 return got_error_from_errno("strdup");
698 err = valid_author(*author);
699 if (err) {
700 free(*author);
701 *author = NULL;
703 return err;
706 static const struct got_error *
707 get_allowed_signers(char **allowed_signers, struct got_repository *repo,
708 struct got_worktree *worktree)
710 const char *got_allowed_signers = NULL;
711 const struct got_gotconfig *worktree_conf = NULL, *repo_conf = NULL;
713 *allowed_signers = NULL;
715 if (worktree)
716 worktree_conf = got_worktree_get_gotconfig(worktree);
717 repo_conf = got_repo_get_gotconfig(repo);
719 /*
720 * Priority of potential author information sources, from most
721 * significant to least significant:
722 * 1) work tree's .got/got.conf file
723 * 2) repository's got.conf file
724 */
726 if (worktree_conf)
727 got_allowed_signers = got_gotconfig_get_allowed_signers_file(
728 worktree_conf);
729 if (got_allowed_signers == NULL)
730 got_allowed_signers = got_gotconfig_get_allowed_signers_file(
731 repo_conf);
733 if (got_allowed_signers) {
734 *allowed_signers = strdup(got_allowed_signers);
735 if (*allowed_signers == NULL)
736 return got_error_from_errno("strdup");
738 return NULL;
741 static const struct got_error *
742 get_revoked_signers(char **revoked_signers, struct got_repository *repo,
743 struct got_worktree *worktree)
745 const char *got_revoked_signers = NULL;
746 const struct got_gotconfig *worktree_conf = NULL, *repo_conf = NULL;
748 *revoked_signers = NULL;
750 if (worktree)
751 worktree_conf = got_worktree_get_gotconfig(worktree);
752 repo_conf = got_repo_get_gotconfig(repo);
754 /*
755 * Priority of potential author information sources, from most
756 * significant to least significant:
757 * 1) work tree's .got/got.conf file
758 * 2) repository's got.conf file
759 */
761 if (worktree_conf)
762 got_revoked_signers = got_gotconfig_get_revoked_signers_file(
763 worktree_conf);
764 if (got_revoked_signers == NULL)
765 got_revoked_signers = got_gotconfig_get_revoked_signers_file(
766 repo_conf);
768 if (got_revoked_signers) {
769 *revoked_signers = strdup(got_revoked_signers);
770 if (*revoked_signers == NULL)
771 return got_error_from_errno("strdup");
773 return NULL;
776 static const char *
777 get_signer_id(struct got_repository *repo, struct got_worktree *worktree)
779 const char *got_signer_id = NULL;
780 const struct got_gotconfig *worktree_conf = NULL, *repo_conf = NULL;
782 if (worktree)
783 worktree_conf = got_worktree_get_gotconfig(worktree);
784 repo_conf = got_repo_get_gotconfig(repo);
786 /*
787 * Priority of potential author information sources, from most
788 * significant to least significant:
789 * 1) work tree's .got/got.conf file
790 * 2) repository's got.conf file
791 */
793 if (worktree_conf)
794 got_signer_id = got_gotconfig_get_signer_id(worktree_conf);
795 if (got_signer_id == NULL)
796 got_signer_id = got_gotconfig_get_signer_id(repo_conf);
798 return got_signer_id;
801 static const struct got_error *
802 get_gitconfig_path(char **gitconfig_path)
804 const char *homedir = getenv("HOME");
806 *gitconfig_path = NULL;
807 if (homedir) {
808 if (asprintf(gitconfig_path, "%s/.gitconfig", homedir) == -1)
809 return got_error_from_errno("asprintf");
812 return NULL;
815 static const struct got_error *
816 cmd_import(int argc, char *argv[])
818 const struct got_error *error = NULL;
819 char *path_dir = NULL, *repo_path = NULL, *logmsg = NULL;
820 char *gitconfig_path = NULL, *editor = NULL, *author = NULL;
821 const char *branch_name = NULL;
822 char *id_str = NULL, *logmsg_path = NULL;
823 char refname[PATH_MAX] = "refs/heads/";
824 struct got_repository *repo = NULL;
825 struct got_reference *branch_ref = NULL, *head_ref = NULL;
826 struct got_object_id *new_commit_id = NULL;
827 int ch, n = 0;
828 struct got_pathlist_head ignores;
829 struct got_pathlist_entry *pe;
830 int preserve_logmsg = 0;
831 int *pack_fds = NULL;
833 TAILQ_INIT(&ignores);
835 #ifndef PROFILE
836 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
837 "unveil",
838 NULL) == -1)
839 err(1, "pledge");
840 #endif
842 while ((ch = getopt(argc, argv, "b:I:m:r:")) != -1) {
843 switch (ch) {
844 case 'b':
845 branch_name = optarg;
846 break;
847 case 'I':
848 if (optarg[0] == '\0')
849 break;
850 error = got_pathlist_insert(&pe, &ignores, optarg,
851 NULL);
852 if (error)
853 goto done;
854 break;
855 case 'm':
856 logmsg = strdup(optarg);
857 if (logmsg == NULL) {
858 error = got_error_from_errno("strdup");
859 goto done;
861 break;
862 case 'r':
863 repo_path = realpath(optarg, NULL);
864 if (repo_path == NULL) {
865 error = got_error_from_errno2("realpath",
866 optarg);
867 goto done;
869 break;
870 default:
871 usage_import();
872 /* NOTREACHED */
876 argc -= optind;
877 argv += optind;
879 if (argc != 1)
880 usage_import();
882 if (repo_path == NULL) {
883 repo_path = getcwd(NULL, 0);
884 if (repo_path == NULL)
885 return got_error_from_errno("getcwd");
887 got_path_strip_trailing_slashes(repo_path);
888 error = get_gitconfig_path(&gitconfig_path);
889 if (error)
890 goto done;
891 error = got_repo_pack_fds_open(&pack_fds);
892 if (error != NULL)
893 goto done;
894 error = got_repo_open(&repo, repo_path, gitconfig_path, pack_fds);
895 if (error)
896 goto done;
898 path_dir = realpath(argv[0], NULL);
899 if (path_dir == NULL) {
900 error = got_error_from_errno2("realpath", argv[0]);
901 goto done;
903 got_path_strip_trailing_slashes(path_dir);
905 error = get_editor(&editor);
906 if (error)
907 goto done;
909 if (unveil(path_dir, "r") != 0) {
910 error = got_error_from_errno2("unveil", path_dir);
911 goto done;
913 if (unveil(editor, "x") != 0) {
914 error = got_error_from_errno2("unveil", editor);
915 goto done;
917 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
918 if (error)
919 goto done;
921 error = get_author(&author, repo, NULL);
922 if (error)
923 return error;
925 /*
926 * Don't let the user create a branch name with a leading '-'.
927 * While technically a valid reference name, this case is usually
928 * an unintended typo.
929 */
930 if (branch_name && branch_name[0] == '-')
931 return got_error_path(branch_name, GOT_ERR_REF_NAME_MINUS);
933 error = got_ref_open(&head_ref, repo, GOT_REF_HEAD, 0);
934 if (error && error->code != GOT_ERR_NOT_REF)
935 goto done;
937 if (branch_name)
938 n = strlcat(refname, branch_name, sizeof(refname));
939 else if (head_ref && got_ref_is_symbolic(head_ref))
940 n = strlcpy(refname, got_ref_get_symref_target(head_ref),
941 sizeof(refname));
942 else
943 n = strlcat(refname, "main", sizeof(refname));
944 if (n >= sizeof(refname)) {
945 error = got_error(GOT_ERR_NO_SPACE);
946 goto done;
949 error = got_ref_open(&branch_ref, repo, refname, 0);
950 if (error) {
951 if (error->code != GOT_ERR_NOT_REF)
952 goto done;
953 } else {
954 error = got_error_msg(GOT_ERR_BRANCH_EXISTS,
955 "import target branch already exists");
956 goto done;
959 if (logmsg == NULL || *logmsg == '\0') {
960 free(logmsg);
961 error = collect_import_msg(&logmsg, &logmsg_path, editor,
962 path_dir, refname);
963 if (error) {
964 if (error->code != GOT_ERR_COMMIT_MSG_EMPTY &&
965 logmsg_path != NULL)
966 preserve_logmsg = 1;
967 goto done;
971 error = got_repo_import(&new_commit_id, path_dir, logmsg,
972 author, &ignores, repo, import_progress, NULL);
973 if (error) {
974 if (logmsg_path)
975 preserve_logmsg = 1;
976 goto done;
979 error = got_ref_alloc(&branch_ref, refname, new_commit_id);
980 if (error) {
981 if (logmsg_path)
982 preserve_logmsg = 1;
983 goto done;
986 error = got_ref_write(branch_ref, repo);
987 if (error) {
988 if (logmsg_path)
989 preserve_logmsg = 1;
990 goto done;
993 error = got_object_id_str(&id_str, new_commit_id);
994 if (error) {
995 if (logmsg_path)
996 preserve_logmsg = 1;
997 goto done;
1000 error = got_ref_open(&head_ref, repo, GOT_REF_HEAD, 0);
1001 if (error) {
1002 if (error->code != GOT_ERR_NOT_REF) {
1003 if (logmsg_path)
1004 preserve_logmsg = 1;
1005 goto done;
1008 error = got_ref_alloc_symref(&head_ref, GOT_REF_HEAD,
1009 branch_ref);
1010 if (error) {
1011 if (logmsg_path)
1012 preserve_logmsg = 1;
1013 goto done;
1016 error = got_ref_write(head_ref, repo);
1017 if (error) {
1018 if (logmsg_path)
1019 preserve_logmsg = 1;
1020 goto done;
1024 printf("Created branch %s with commit %s\n",
1025 got_ref_get_name(branch_ref), id_str);
1026 done:
1027 if (pack_fds) {
1028 const struct got_error *pack_err =
1029 got_repo_pack_fds_close(pack_fds);
1030 if (error == NULL)
1031 error = pack_err;
1033 if (repo) {
1034 const struct got_error *close_err = got_repo_close(repo);
1035 if (error == NULL)
1036 error = close_err;
1038 if (preserve_logmsg) {
1039 fprintf(stderr, "%s: log message preserved in %s\n",
1040 getprogname(), logmsg_path);
1041 } else if (logmsg_path && unlink(logmsg_path) == -1 && error == NULL)
1042 error = got_error_from_errno2("unlink", logmsg_path);
1043 free(logmsg);
1044 free(logmsg_path);
1045 free(repo_path);
1046 free(editor);
1047 free(new_commit_id);
1048 free(id_str);
1049 free(author);
1050 free(gitconfig_path);
1051 if (branch_ref)
1052 got_ref_close(branch_ref);
1053 if (head_ref)
1054 got_ref_close(head_ref);
1055 return error;
1058 __dead static void
1059 usage_clone(void)
1061 fprintf(stderr, "usage: %s clone [-almqv] [-b branch] [-R reference] "
1062 "repository-URL [directory]\n", getprogname());
1063 exit(1);
1066 struct got_fetch_progress_arg {
1067 char last_scaled_size[FMT_SCALED_STRSIZE];
1068 int last_p_indexed;
1069 int last_p_resolved;
1070 int verbosity;
1072 struct got_repository *repo;
1074 int create_configs;
1075 int configs_created;
1076 struct {
1077 struct got_pathlist_head *symrefs;
1078 struct got_pathlist_head *wanted_branches;
1079 struct got_pathlist_head *wanted_refs;
1080 const char *proto;
1081 const char *host;
1082 const char *port;
1083 const char *remote_repo_path;
1084 const char *git_url;
1085 int fetch_all_branches;
1086 int mirror_references;
1087 } config_info;
1090 /* XXX forward declaration */
1091 static const struct got_error *
1092 create_config_files(const char *proto, const char *host, const char *port,
1093 const char *remote_repo_path, const char *git_url, int fetch_all_branches,
1094 int mirror_references, struct got_pathlist_head *symrefs,
1095 struct got_pathlist_head *wanted_branches,
1096 struct got_pathlist_head *wanted_refs, struct got_repository *repo);
1098 static const struct got_error *
1099 fetch_progress(void *arg, const char *message, off_t packfile_size,
1100 int nobj_total, int nobj_indexed, int nobj_loose, int nobj_resolved)
1102 const struct got_error *err = NULL;
1103 struct got_fetch_progress_arg *a = arg;
1104 char scaled_size[FMT_SCALED_STRSIZE];
1105 int p_indexed, p_resolved;
1106 int print_size = 0, print_indexed = 0, print_resolved = 0;
1109 * In order to allow a failed clone to be resumed with 'got fetch'
1110 * we try to create configuration files as soon as possible.
1111 * Once the server has sent information about its default branch
1112 * we have all required information.
1114 if (a->create_configs && !a->configs_created &&
1115 !TAILQ_EMPTY(a->config_info.symrefs)) {
1116 err = create_config_files(a->config_info.proto,
1117 a->config_info.host, a->config_info.port,
1118 a->config_info.remote_repo_path,
1119 a->config_info.git_url,
1120 a->config_info.fetch_all_branches,
1121 a->config_info.mirror_references,
1122 a->config_info.symrefs,
1123 a->config_info.wanted_branches,
1124 a->config_info.wanted_refs, a->repo);
1125 if (err)
1126 return err;
1127 a->configs_created = 1;
1130 if (a->verbosity < 0)
1131 return NULL;
1133 if (message && message[0] != '\0') {
1134 printf("\rserver: %s", message);
1135 fflush(stdout);
1136 return NULL;
1139 if (packfile_size > 0 || nobj_indexed > 0) {
1140 if (fmt_scaled(packfile_size, scaled_size) == 0 &&
1141 (a->last_scaled_size[0] == '\0' ||
1142 strcmp(scaled_size, a->last_scaled_size)) != 0) {
1143 print_size = 1;
1144 if (strlcpy(a->last_scaled_size, scaled_size,
1145 FMT_SCALED_STRSIZE) >= FMT_SCALED_STRSIZE)
1146 return got_error(GOT_ERR_NO_SPACE);
1148 if (nobj_indexed > 0) {
1149 p_indexed = (nobj_indexed * 100) / nobj_total;
1150 if (p_indexed != a->last_p_indexed) {
1151 a->last_p_indexed = p_indexed;
1152 print_indexed = 1;
1153 print_size = 1;
1156 if (nobj_resolved > 0) {
1157 p_resolved = (nobj_resolved * 100) /
1158 (nobj_total - nobj_loose);
1159 if (p_resolved != a->last_p_resolved) {
1160 a->last_p_resolved = p_resolved;
1161 print_resolved = 1;
1162 print_indexed = 1;
1163 print_size = 1;
1168 if (print_size || print_indexed || print_resolved)
1169 printf("\r");
1170 if (print_size)
1171 printf("%*s fetched", FMT_SCALED_STRSIZE - 2, scaled_size);
1172 if (print_indexed)
1173 printf("; indexing %d%%", p_indexed);
1174 if (print_resolved)
1175 printf("; resolving deltas %d%%", p_resolved);
1176 if (print_size || print_indexed || print_resolved)
1177 fflush(stdout);
1179 return NULL;
1182 static const struct got_error *
1183 create_symref(const char *refname, struct got_reference *target_ref,
1184 int verbosity, struct got_repository *repo)
1186 const struct got_error *err;
1187 struct got_reference *head_symref;
1189 err = got_ref_alloc_symref(&head_symref, refname, target_ref);
1190 if (err)
1191 return err;
1193 err = got_ref_write(head_symref, repo);
1194 if (err == NULL && verbosity > 0) {
1195 printf("Created reference %s: %s\n", GOT_REF_HEAD,
1196 got_ref_get_name(target_ref));
1198 got_ref_close(head_symref);
1199 return err;
1202 static const struct got_error *
1203 list_remote_refs(struct got_pathlist_head *symrefs,
1204 struct got_pathlist_head *refs)
1206 const struct got_error *err;
1207 struct got_pathlist_entry *pe;
1209 TAILQ_FOREACH(pe, symrefs, entry) {
1210 const char *refname = pe->path;
1211 const char *targetref = pe->data;
1213 printf("%s: %s\n", refname, targetref);
1216 TAILQ_FOREACH(pe, refs, entry) {
1217 const char *refname = pe->path;
1218 struct got_object_id *id = pe->data;
1219 char *id_str;
1221 err = got_object_id_str(&id_str, id);
1222 if (err)
1223 return err;
1224 printf("%s: %s\n", refname, id_str);
1225 free(id_str);
1228 return NULL;
1231 static const struct got_error *
1232 create_ref(const char *refname, struct got_object_id *id,
1233 int verbosity, struct got_repository *repo)
1235 const struct got_error *err = NULL;
1236 struct got_reference *ref;
1237 char *id_str;
1239 err = got_object_id_str(&id_str, id);
1240 if (err)
1241 return err;
1243 err = got_ref_alloc(&ref, refname, id);
1244 if (err)
1245 goto done;
1247 err = got_ref_write(ref, repo);
1248 got_ref_close(ref);
1250 if (err == NULL && verbosity >= 0)
1251 printf("Created reference %s: %s\n", refname, id_str);
1252 done:
1253 free(id_str);
1254 return err;
1257 static int
1258 match_wanted_ref(const char *refname, const char *wanted_ref)
1260 if (strncmp(refname, "refs/", 5) != 0)
1261 return 0;
1262 refname += 5;
1265 * Prevent fetching of references that won't make any
1266 * sense outside of the remote repository's context.
1268 if (strncmp(refname, "got/", 4) == 0)
1269 return 0;
1270 if (strncmp(refname, "remotes/", 8) == 0)
1271 return 0;
1273 if (strncmp(wanted_ref, "refs/", 5) == 0)
1274 wanted_ref += 5;
1276 /* Allow prefix match. */
1277 if (got_path_is_child(refname, wanted_ref, strlen(wanted_ref)))
1278 return 1;
1280 /* Allow exact match. */
1281 return (strcmp(refname, wanted_ref) == 0);
1284 static int
1285 is_wanted_ref(struct got_pathlist_head *wanted_refs, const char *refname)
1287 struct got_pathlist_entry *pe;
1289 TAILQ_FOREACH(pe, wanted_refs, entry) {
1290 if (match_wanted_ref(refname, pe->path))
1291 return 1;
1294 return 0;
1297 static const struct got_error *
1298 create_wanted_ref(const char *refname, struct got_object_id *id,
1299 const char *remote_repo_name, int verbosity, struct got_repository *repo)
1301 const struct got_error *err;
1302 char *remote_refname;
1304 if (strncmp("refs/", refname, 5) == 0)
1305 refname += 5;
1307 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
1308 remote_repo_name, refname) == -1)
1309 return got_error_from_errno("asprintf");
1311 err = create_ref(remote_refname, id, verbosity, repo);
1312 free(remote_refname);
1313 return err;
1316 static const struct got_error *
1317 create_gotconfig(const char *proto, const char *host, const char *port,
1318 const char *remote_repo_path, const char *default_branch,
1319 int fetch_all_branches, struct got_pathlist_head *wanted_branches,
1320 struct got_pathlist_head *wanted_refs, int mirror_references,
1321 struct got_repository *repo)
1323 const struct got_error *err = NULL;
1324 char *gotconfig_path = NULL;
1325 char *gotconfig = NULL;
1326 FILE *gotconfig_file = NULL;
1327 const char *branchname = NULL;
1328 char *branches = NULL, *refs = NULL;
1329 ssize_t n;
1331 if (!fetch_all_branches && !TAILQ_EMPTY(wanted_branches)) {
1332 struct got_pathlist_entry *pe;
1333 TAILQ_FOREACH(pe, wanted_branches, entry) {
1334 char *s;
1335 branchname = pe->path;
1336 if (strncmp(branchname, "refs/heads/", 11) == 0)
1337 branchname += 11;
1338 if (asprintf(&s, "%s\"%s\" ",
1339 branches ? branches : "", branchname) == -1) {
1340 err = got_error_from_errno("asprintf");
1341 goto done;
1343 free(branches);
1344 branches = s;
1346 } else if (!fetch_all_branches && default_branch) {
1347 branchname = default_branch;
1348 if (strncmp(branchname, "refs/heads/", 11) == 0)
1349 branchname += 11;
1350 if (asprintf(&branches, "\"%s\" ", branchname) == -1) {
1351 err = got_error_from_errno("asprintf");
1352 goto done;
1355 if (!TAILQ_EMPTY(wanted_refs)) {
1356 struct got_pathlist_entry *pe;
1357 TAILQ_FOREACH(pe, wanted_refs, entry) {
1358 char *s;
1359 const char *refname = pe->path;
1360 if (strncmp(refname, "refs/", 5) == 0)
1361 branchname += 5;
1362 if (asprintf(&s, "%s\"%s\" ",
1363 refs ? refs : "", refname) == -1) {
1364 err = got_error_from_errno("asprintf");
1365 goto done;
1367 free(refs);
1368 refs = s;
1372 /* Create got.conf(5). */
1373 gotconfig_path = got_repo_get_path_gotconfig(repo);
1374 if (gotconfig_path == NULL) {
1375 err = got_error_from_errno("got_repo_get_path_gotconfig");
1376 goto done;
1378 gotconfig_file = fopen(gotconfig_path, "ae");
1379 if (gotconfig_file == NULL) {
1380 err = got_error_from_errno2("fopen", gotconfig_path);
1381 goto done;
1383 if (asprintf(&gotconfig,
1384 "remote \"%s\" {\n"
1385 "\tserver %s\n"
1386 "\tprotocol %s\n"
1387 "%s%s%s"
1388 "\trepository \"%s\"\n"
1389 "%s%s%s"
1390 "%s%s%s"
1391 "%s"
1392 "%s"
1393 "}\n",
1394 GOT_FETCH_DEFAULT_REMOTE_NAME, host, proto,
1395 port ? "\tport " : "", port ? port : "", port ? "\n" : "",
1396 remote_repo_path, branches ? "\tbranch { " : "",
1397 branches ? branches : "", branches ? "}\n" : "",
1398 refs ? "\treference { " : "", refs ? refs : "", refs ? "}\n" : "",
1399 mirror_references ? "\tmirror_references yes\n" : "",
1400 fetch_all_branches ? "\tfetch_all_branches yes\n" : "") == -1) {
1401 err = got_error_from_errno("asprintf");
1402 goto done;
1404 n = fwrite(gotconfig, 1, strlen(gotconfig), gotconfig_file);
1405 if (n != strlen(gotconfig)) {
1406 err = got_ferror(gotconfig_file, GOT_ERR_IO);
1407 goto done;
1410 done:
1411 if (gotconfig_file && fclose(gotconfig_file) == EOF && err == NULL)
1412 err = got_error_from_errno2("fclose", gotconfig_path);
1413 free(gotconfig_path);
1414 free(branches);
1415 return err;
1418 static const struct got_error *
1419 create_gitconfig(const char *git_url, const char *default_branch,
1420 int fetch_all_branches, struct got_pathlist_head *wanted_branches,
1421 struct got_pathlist_head *wanted_refs, int mirror_references,
1422 struct got_repository *repo)
1424 const struct got_error *err = NULL;
1425 char *gitconfig_path = NULL;
1426 char *gitconfig = NULL;
1427 FILE *gitconfig_file = NULL;
1428 char *branches = NULL, *refs = NULL;
1429 const char *branchname;
1430 ssize_t n;
1432 /* Create a config file Git can understand. */
1433 gitconfig_path = got_repo_get_path_gitconfig(repo);
1434 if (gitconfig_path == NULL) {
1435 err = got_error_from_errno("got_repo_get_path_gitconfig");
1436 goto done;
1438 gitconfig_file = fopen(gitconfig_path, "ae");
1439 if (gitconfig_file == NULL) {
1440 err = got_error_from_errno2("fopen", gitconfig_path);
1441 goto done;
1443 if (fetch_all_branches) {
1444 if (mirror_references) {
1445 if (asprintf(&branches,
1446 "\tfetch = refs/heads/*:refs/heads/*\n") == -1) {
1447 err = got_error_from_errno("asprintf");
1448 goto done;
1450 } else if (asprintf(&branches,
1451 "\tfetch = refs/heads/*:refs/remotes/%s/*\n",
1452 GOT_FETCH_DEFAULT_REMOTE_NAME) == -1) {
1453 err = got_error_from_errno("asprintf");
1454 goto done;
1456 } else if (!TAILQ_EMPTY(wanted_branches)) {
1457 struct got_pathlist_entry *pe;
1458 TAILQ_FOREACH(pe, wanted_branches, entry) {
1459 char *s;
1460 branchname = pe->path;
1461 if (strncmp(branchname, "refs/heads/", 11) == 0)
1462 branchname += 11;
1463 if (mirror_references) {
1464 if (asprintf(&s,
1465 "%s\tfetch = refs/heads/%s:refs/heads/%s\n",
1466 branches ? branches : "",
1467 branchname, branchname) == -1) {
1468 err = got_error_from_errno("asprintf");
1469 goto done;
1471 } else if (asprintf(&s,
1472 "%s\tfetch = refs/heads/%s:refs/remotes/%s/%s\n",
1473 branches ? branches : "",
1474 branchname, GOT_FETCH_DEFAULT_REMOTE_NAME,
1475 branchname) == -1) {
1476 err = got_error_from_errno("asprintf");
1477 goto done;
1479 free(branches);
1480 branches = s;
1482 } else {
1484 * If the server specified a default branch, use just that one.
1485 * Otherwise fall back to fetching all branches on next fetch.
1487 if (default_branch) {
1488 branchname = default_branch;
1489 if (strncmp(branchname, "refs/heads/", 11) == 0)
1490 branchname += 11;
1491 } else
1492 branchname = "*"; /* fall back to all branches */
1493 if (mirror_references) {
1494 if (asprintf(&branches,
1495 "\tfetch = refs/heads/%s:refs/heads/%s\n",
1496 branchname, branchname) == -1) {
1497 err = got_error_from_errno("asprintf");
1498 goto done;
1500 } else if (asprintf(&branches,
1501 "\tfetch = refs/heads/%s:refs/remotes/%s/%s\n",
1502 branchname, GOT_FETCH_DEFAULT_REMOTE_NAME,
1503 branchname) == -1) {
1504 err = got_error_from_errno("asprintf");
1505 goto done;
1508 if (!TAILQ_EMPTY(wanted_refs)) {
1509 struct got_pathlist_entry *pe;
1510 TAILQ_FOREACH(pe, wanted_refs, entry) {
1511 char *s;
1512 const char *refname = pe->path;
1513 if (strncmp(refname, "refs/", 5) == 0)
1514 refname += 5;
1515 if (mirror_references) {
1516 if (asprintf(&s,
1517 "%s\tfetch = refs/%s:refs/%s\n",
1518 refs ? refs : "", refname, refname) == -1) {
1519 err = got_error_from_errno("asprintf");
1520 goto done;
1522 } else if (asprintf(&s,
1523 "%s\tfetch = refs/%s:refs/remotes/%s/%s\n",
1524 refs ? refs : "",
1525 refname, GOT_FETCH_DEFAULT_REMOTE_NAME,
1526 refname) == -1) {
1527 err = got_error_from_errno("asprintf");
1528 goto done;
1530 free(refs);
1531 refs = s;
1535 if (asprintf(&gitconfig,
1536 "[remote \"%s\"]\n"
1537 "\turl = %s\n"
1538 "%s"
1539 "%s"
1540 "\tfetch = refs/tags/*:refs/tags/*\n",
1541 GOT_FETCH_DEFAULT_REMOTE_NAME, git_url, branches ? branches : "",
1542 refs ? refs : "") == -1) {
1543 err = got_error_from_errno("asprintf");
1544 goto done;
1546 n = fwrite(gitconfig, 1, strlen(gitconfig), gitconfig_file);
1547 if (n != strlen(gitconfig)) {
1548 err = got_ferror(gitconfig_file, GOT_ERR_IO);
1549 goto done;
1551 done:
1552 if (gitconfig_file && fclose(gitconfig_file) == EOF && err == NULL)
1553 err = got_error_from_errno2("fclose", gitconfig_path);
1554 free(gitconfig_path);
1555 free(branches);
1556 return err;
1559 static const struct got_error *
1560 create_config_files(const char *proto, const char *host, const char *port,
1561 const char *remote_repo_path, const char *git_url, int fetch_all_branches,
1562 int mirror_references, struct got_pathlist_head *symrefs,
1563 struct got_pathlist_head *wanted_branches,
1564 struct got_pathlist_head *wanted_refs, struct got_repository *repo)
1566 const struct got_error *err = NULL;
1567 const char *default_branch = NULL;
1568 struct got_pathlist_entry *pe;
1571 * If we asked for a set of wanted branches then use the first
1572 * one of those.
1574 if (!TAILQ_EMPTY(wanted_branches)) {
1575 pe = TAILQ_FIRST(wanted_branches);
1576 default_branch = pe->path;
1577 } else {
1578 /* First HEAD ref listed by server is the default branch. */
1579 TAILQ_FOREACH(pe, symrefs, entry) {
1580 const char *refname = pe->path;
1581 const char *target = pe->data;
1583 if (strcmp(refname, GOT_REF_HEAD) != 0)
1584 continue;
1586 default_branch = target;
1587 break;
1591 /* Create got.conf(5). */
1592 err = create_gotconfig(proto, host, port, remote_repo_path,
1593 default_branch, fetch_all_branches, wanted_branches,
1594 wanted_refs, mirror_references, repo);
1595 if (err)
1596 return err;
1598 /* Create a config file Git can understand. */
1599 return create_gitconfig(git_url, default_branch, fetch_all_branches,
1600 wanted_branches, wanted_refs, mirror_references, repo);
1603 static const struct got_error *
1604 cmd_clone(int argc, char *argv[])
1606 const struct got_error *error = NULL;
1607 const char *uri, *dirname;
1608 char *proto, *host, *port, *repo_name, *server_path;
1609 char *default_destdir = NULL, *id_str = NULL;
1610 const char *repo_path;
1611 struct got_repository *repo = NULL;
1612 struct got_pathlist_head refs, symrefs, wanted_branches, wanted_refs;
1613 struct got_pathlist_entry *pe;
1614 struct got_object_id *pack_hash = NULL;
1615 int ch, fetchfd = -1, fetchstatus;
1616 pid_t fetchpid = -1;
1617 struct got_fetch_progress_arg fpa;
1618 char *git_url = NULL;
1619 int verbosity = 0, fetch_all_branches = 0, mirror_references = 0;
1620 int bflag = 0, list_refs_only = 0;
1621 int *pack_fds = NULL;
1623 TAILQ_INIT(&refs);
1624 TAILQ_INIT(&symrefs);
1625 TAILQ_INIT(&wanted_branches);
1626 TAILQ_INIT(&wanted_refs);
1628 while ((ch = getopt(argc, argv, "ab:lmqR:v")) != -1) {
1629 switch (ch) {
1630 case 'a':
1631 fetch_all_branches = 1;
1632 break;
1633 case 'b':
1634 error = got_pathlist_append(&wanted_branches,
1635 optarg, NULL);
1636 if (error)
1637 return error;
1638 bflag = 1;
1639 break;
1640 case 'l':
1641 list_refs_only = 1;
1642 break;
1643 case 'm':
1644 mirror_references = 1;
1645 break;
1646 case 'q':
1647 verbosity = -1;
1648 break;
1649 case 'R':
1650 error = got_pathlist_append(&wanted_refs,
1651 optarg, NULL);
1652 if (error)
1653 return error;
1654 break;
1655 case 'v':
1656 if (verbosity < 0)
1657 verbosity = 0;
1658 else if (verbosity < 3)
1659 verbosity++;
1660 break;
1661 default:
1662 usage_clone();
1663 break;
1666 argc -= optind;
1667 argv += optind;
1669 if (fetch_all_branches && !TAILQ_EMPTY(&wanted_branches))
1670 option_conflict('a', 'b');
1671 if (list_refs_only) {
1672 if (!TAILQ_EMPTY(&wanted_branches))
1673 option_conflict('l', 'b');
1674 if (fetch_all_branches)
1675 option_conflict('l', 'a');
1676 if (mirror_references)
1677 option_conflict('l', 'm');
1678 if (!TAILQ_EMPTY(&wanted_refs))
1679 option_conflict('l', 'R');
1682 uri = argv[0];
1684 if (argc == 1)
1685 dirname = NULL;
1686 else if (argc == 2)
1687 dirname = argv[1];
1688 else
1689 usage_clone();
1691 error = got_dial_parse_uri(&proto, &host, &port, &server_path,
1692 &repo_name, uri);
1693 if (error)
1694 goto done;
1696 if (asprintf(&git_url, "%s://%s%s%s%s%s", proto,
1697 host, port ? ":" : "", port ? port : "",
1698 server_path[0] != '/' ? "/" : "", server_path) == -1) {
1699 error = got_error_from_errno("asprintf");
1700 goto done;
1703 if (strcmp(proto, "git") == 0) {
1704 #ifndef PROFILE
1705 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
1706 "sendfd dns inet unveil", NULL) == -1)
1707 err(1, "pledge");
1708 #endif
1709 } else if (strcmp(proto, "git+ssh") == 0 ||
1710 strcmp(proto, "ssh") == 0 ||
1711 strcmp(proto, "git+http") == 0 ||
1712 strcmp(proto, "http") == 0 ||
1713 strcmp(proto, "git+https") == 0 ||
1714 strcmp(proto, "https") == 0) {
1715 #ifndef PROFILE
1716 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
1717 "sendfd unveil", NULL) == -1)
1718 err(1, "pledge");
1719 #endif
1720 } else {
1721 error = got_error_path(proto, GOT_ERR_BAD_PROTO);
1722 goto done;
1724 if (dirname == NULL) {
1725 if (asprintf(&default_destdir, "%s.git", repo_name) == -1) {
1726 error = got_error_from_errno("asprintf");
1727 goto done;
1729 repo_path = default_destdir;
1730 } else
1731 repo_path = dirname;
1733 if (!list_refs_only) {
1734 error = got_path_mkdir(repo_path);
1735 if (error &&
1736 (!(error->code == GOT_ERR_ERRNO && errno == EISDIR) &&
1737 !(error->code == GOT_ERR_ERRNO && errno == EEXIST)))
1738 goto done;
1739 if (!got_path_dir_is_empty(repo_path)) {
1740 error = got_error_path(repo_path,
1741 GOT_ERR_DIR_NOT_EMPTY);
1742 goto done;
1746 error = got_dial_apply_unveil(proto);
1747 if (error)
1748 goto done;
1750 error = apply_unveil(repo_path, 0, NULL);
1751 if (error)
1752 goto done;
1754 if (verbosity >= 0)
1755 printf("Connecting to %s\n", git_url);
1757 error = got_fetch_connect(&fetchpid, &fetchfd, proto, host, port,
1758 server_path, verbosity);
1759 if (error)
1760 goto done;
1762 #ifndef PROFILE
1763 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd",
1764 NULL) == -1)
1765 err(1, "pledge");
1766 #endif
1767 if (!list_refs_only) {
1768 error = got_repo_init(repo_path, NULL);
1769 if (error)
1770 goto done;
1771 error = got_repo_pack_fds_open(&pack_fds);
1772 if (error != NULL)
1773 goto done;
1774 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
1775 if (error)
1776 goto done;
1779 fpa.last_scaled_size[0] = '\0';
1780 fpa.last_p_indexed = -1;
1781 fpa.last_p_resolved = -1;
1782 fpa.verbosity = verbosity;
1783 fpa.create_configs = 1;
1784 fpa.configs_created = 0;
1785 fpa.repo = repo;
1786 fpa.config_info.symrefs = &symrefs;
1787 fpa.config_info.wanted_branches = &wanted_branches;
1788 fpa.config_info.wanted_refs = &wanted_refs;
1789 fpa.config_info.proto = proto;
1790 fpa.config_info.host = host;
1791 fpa.config_info.port = port;
1792 fpa.config_info.remote_repo_path = server_path;
1793 fpa.config_info.git_url = git_url;
1794 fpa.config_info.fetch_all_branches = fetch_all_branches;
1795 fpa.config_info.mirror_references = mirror_references;
1796 error = got_fetch_pack(&pack_hash, &refs, &symrefs,
1797 GOT_FETCH_DEFAULT_REMOTE_NAME, mirror_references,
1798 fetch_all_branches, &wanted_branches, &wanted_refs,
1799 list_refs_only, verbosity, fetchfd, repo, NULL, NULL, bflag,
1800 fetch_progress, &fpa);
1801 if (error)
1802 goto done;
1804 if (list_refs_only) {
1805 error = list_remote_refs(&symrefs, &refs);
1806 goto done;
1809 if (pack_hash == NULL) {
1810 error = got_error_fmt(GOT_ERR_FETCH_FAILED, "%s",
1811 "server sent an empty pack file");
1812 goto done;
1814 error = got_object_id_str(&id_str, pack_hash);
1815 if (error)
1816 goto done;
1817 if (verbosity >= 0)
1818 printf("\nFetched %s.pack\n", id_str);
1819 free(id_str);
1821 /* Set up references provided with the pack file. */
1822 TAILQ_FOREACH(pe, &refs, entry) {
1823 const char *refname = pe->path;
1824 struct got_object_id *id = pe->data;
1825 char *remote_refname;
1827 if (is_wanted_ref(&wanted_refs, refname) &&
1828 !mirror_references) {
1829 error = create_wanted_ref(refname, id,
1830 GOT_FETCH_DEFAULT_REMOTE_NAME,
1831 verbosity - 1, repo);
1832 if (error)
1833 goto done;
1834 continue;
1837 error = create_ref(refname, id, verbosity - 1, repo);
1838 if (error)
1839 goto done;
1841 if (mirror_references)
1842 continue;
1844 if (strncmp("refs/heads/", refname, 11) != 0)
1845 continue;
1847 if (asprintf(&remote_refname,
1848 "refs/remotes/%s/%s", GOT_FETCH_DEFAULT_REMOTE_NAME,
1849 refname + 11) == -1) {
1850 error = got_error_from_errno("asprintf");
1851 goto done;
1853 error = create_ref(remote_refname, id, verbosity - 1, repo);
1854 free(remote_refname);
1855 if (error)
1856 goto done;
1859 /* Set the HEAD reference if the server provided one. */
1860 TAILQ_FOREACH(pe, &symrefs, entry) {
1861 struct got_reference *target_ref;
1862 const char *refname = pe->path;
1863 const char *target = pe->data;
1864 char *remote_refname = NULL, *remote_target = NULL;
1866 if (strcmp(refname, GOT_REF_HEAD) != 0)
1867 continue;
1869 error = got_ref_open(&target_ref, repo, target, 0);
1870 if (error) {
1871 if (error->code == GOT_ERR_NOT_REF) {
1872 error = NULL;
1873 continue;
1875 goto done;
1878 error = create_symref(refname, target_ref, verbosity, repo);
1879 got_ref_close(target_ref);
1880 if (error)
1881 goto done;
1883 if (mirror_references)
1884 continue;
1886 if (strncmp("refs/heads/", target, 11) != 0)
1887 continue;
1889 if (asprintf(&remote_refname,
1890 "refs/remotes/%s/%s", GOT_FETCH_DEFAULT_REMOTE_NAME,
1891 refname) == -1) {
1892 error = got_error_from_errno("asprintf");
1893 goto done;
1895 if (asprintf(&remote_target,
1896 "refs/remotes/%s/%s", GOT_FETCH_DEFAULT_REMOTE_NAME,
1897 target + 11) == -1) {
1898 error = got_error_from_errno("asprintf");
1899 free(remote_refname);
1900 goto done;
1902 error = got_ref_open(&target_ref, repo, remote_target, 0);
1903 if (error) {
1904 free(remote_refname);
1905 free(remote_target);
1906 if (error->code == GOT_ERR_NOT_REF) {
1907 error = NULL;
1908 continue;
1910 goto done;
1912 error = create_symref(remote_refname, target_ref,
1913 verbosity - 1, repo);
1914 free(remote_refname);
1915 free(remote_target);
1916 got_ref_close(target_ref);
1917 if (error)
1918 goto done;
1920 if (pe == NULL) {
1922 * We failed to set the HEAD reference. If we asked for
1923 * a set of wanted branches use the first of one of those
1924 * which could be fetched instead.
1926 TAILQ_FOREACH(pe, &wanted_branches, entry) {
1927 const char *target = pe->path;
1928 struct got_reference *target_ref;
1930 error = got_ref_open(&target_ref, repo, target, 0);
1931 if (error) {
1932 if (error->code == GOT_ERR_NOT_REF) {
1933 error = NULL;
1934 continue;
1936 goto done;
1939 error = create_symref(GOT_REF_HEAD, target_ref,
1940 verbosity, repo);
1941 got_ref_close(target_ref);
1942 if (error)
1943 goto done;
1944 break;
1947 if (!fpa.configs_created && pe != NULL) {
1948 error = create_config_files(fpa.config_info.proto,
1949 fpa.config_info.host, fpa.config_info.port,
1950 fpa.config_info.remote_repo_path,
1951 fpa.config_info.git_url,
1952 fpa.config_info.fetch_all_branches,
1953 fpa.config_info.mirror_references,
1954 fpa.config_info.symrefs,
1955 fpa.config_info.wanted_branches,
1956 fpa.config_info.wanted_refs, fpa.repo);
1957 if (error)
1958 goto done;
1962 if (verbosity >= 0)
1963 printf("Created %s repository '%s'\n",
1964 mirror_references ? "mirrored" : "cloned", repo_path);
1965 done:
1966 if (pack_fds) {
1967 const struct got_error *pack_err =
1968 got_repo_pack_fds_close(pack_fds);
1969 if (error == NULL)
1970 error = pack_err;
1972 if (fetchpid > 0) {
1973 if (kill(fetchpid, SIGTERM) == -1)
1974 error = got_error_from_errno("kill");
1975 if (waitpid(fetchpid, &fetchstatus, 0) == -1 && error == NULL)
1976 error = got_error_from_errno("waitpid");
1978 if (fetchfd != -1 && close(fetchfd) == -1 && error == NULL)
1979 error = got_error_from_errno("close");
1980 if (repo) {
1981 const struct got_error *close_err = got_repo_close(repo);
1982 if (error == NULL)
1983 error = close_err;
1985 got_pathlist_free(&refs, GOT_PATHLIST_FREE_ALL);
1986 got_pathlist_free(&symrefs, GOT_PATHLIST_FREE_ALL);
1987 got_pathlist_free(&wanted_branches, GOT_PATHLIST_FREE_NONE);
1988 got_pathlist_free(&wanted_refs, GOT_PATHLIST_FREE_NONE);
1989 free(pack_hash);
1990 free(proto);
1991 free(host);
1992 free(port);
1993 free(server_path);
1994 free(repo_name);
1995 free(default_destdir);
1996 free(git_url);
1997 return error;
2000 static const struct got_error *
2001 update_ref(struct got_reference *ref, struct got_object_id *new_id,
2002 int replace_tags, int verbosity, struct got_repository *repo)
2004 const struct got_error *err = NULL;
2005 char *new_id_str = NULL;
2006 struct got_object_id *old_id = NULL;
2008 err = got_object_id_str(&new_id_str, new_id);
2009 if (err)
2010 goto done;
2012 if (!replace_tags &&
2013 strncmp(got_ref_get_name(ref), "refs/tags/", 10) == 0) {
2014 err = got_ref_resolve(&old_id, repo, ref);
2015 if (err)
2016 goto done;
2017 if (got_object_id_cmp(old_id, new_id) == 0)
2018 goto done;
2019 if (verbosity >= 0) {
2020 printf("Rejecting update of existing tag %s: %s\n",
2021 got_ref_get_name(ref), new_id_str);
2023 goto done;
2026 if (got_ref_is_symbolic(ref)) {
2027 if (verbosity >= 0) {
2028 printf("Replacing reference %s: %s\n",
2029 got_ref_get_name(ref),
2030 got_ref_get_symref_target(ref));
2032 err = got_ref_change_symref_to_ref(ref, new_id);
2033 if (err)
2034 goto done;
2035 err = got_ref_write(ref, repo);
2036 if (err)
2037 goto done;
2038 } else {
2039 err = got_ref_resolve(&old_id, repo, ref);
2040 if (err)
2041 goto done;
2042 if (got_object_id_cmp(old_id, new_id) == 0)
2043 goto done;
2045 err = got_ref_change_ref(ref, new_id);
2046 if (err)
2047 goto done;
2048 err = got_ref_write(ref, repo);
2049 if (err)
2050 goto done;
2053 if (verbosity >= 0)
2054 printf("Updated %s: %s\n", got_ref_get_name(ref),
2055 new_id_str);
2056 done:
2057 free(old_id);
2058 free(new_id_str);
2059 return err;
2062 static const struct got_error *
2063 update_symref(const char *refname, struct got_reference *target_ref,
2064 int verbosity, struct got_repository *repo)
2066 const struct got_error *err = NULL, *unlock_err;
2067 struct got_reference *symref;
2068 int symref_is_locked = 0;
2070 err = got_ref_open(&symref, repo, refname, 1);
2071 if (err) {
2072 if (err->code != GOT_ERR_NOT_REF)
2073 return err;
2074 err = got_ref_alloc_symref(&symref, refname, target_ref);
2075 if (err)
2076 goto done;
2078 err = got_ref_write(symref, repo);
2079 if (err)
2080 goto done;
2082 if (verbosity >= 0)
2083 printf("Created reference %s: %s\n",
2084 got_ref_get_name(symref),
2085 got_ref_get_symref_target(symref));
2086 } else {
2087 symref_is_locked = 1;
2089 if (strcmp(got_ref_get_symref_target(symref),
2090 got_ref_get_name(target_ref)) == 0)
2091 goto done;
2093 err = got_ref_change_symref(symref,
2094 got_ref_get_name(target_ref));
2095 if (err)
2096 goto done;
2098 err = got_ref_write(symref, repo);
2099 if (err)
2100 goto done;
2102 if (verbosity >= 0)
2103 printf("Updated %s: %s\n", got_ref_get_name(symref),
2104 got_ref_get_symref_target(symref));
2107 done:
2108 if (symref_is_locked) {
2109 unlock_err = got_ref_unlock(symref);
2110 if (unlock_err && err == NULL)
2111 err = unlock_err;
2113 got_ref_close(symref);
2114 return err;
2117 __dead static void
2118 usage_fetch(void)
2120 fprintf(stderr, "usage: %s fetch [-adlqtvX] [-b branch] "
2121 "[-R reference] [-r repository-path] [remote-repository]\n",
2122 getprogname());
2123 exit(1);
2126 static const struct got_error *
2127 delete_missing_ref(struct got_reference *ref,
2128 int verbosity, struct got_repository *repo)
2130 const struct got_error *err = NULL;
2131 struct got_object_id *id = NULL;
2132 char *id_str = NULL;
2134 if (got_ref_is_symbolic(ref)) {
2135 err = got_ref_delete(ref, repo);
2136 if (err)
2137 return err;
2138 if (verbosity >= 0) {
2139 printf("Deleted %s: %s\n",
2140 got_ref_get_name(ref),
2141 got_ref_get_symref_target(ref));
2143 } else {
2144 err = got_ref_resolve(&id, repo, ref);
2145 if (err)
2146 return err;
2147 err = got_object_id_str(&id_str, id);
2148 if (err)
2149 goto done;
2151 err = got_ref_delete(ref, repo);
2152 if (err)
2153 goto done;
2154 if (verbosity >= 0) {
2155 printf("Deleted %s: %s\n",
2156 got_ref_get_name(ref), id_str);
2159 done:
2160 free(id);
2161 free(id_str);
2162 return err;
2165 static const struct got_error *
2166 delete_missing_refs(struct got_pathlist_head *their_refs,
2167 struct got_pathlist_head *their_symrefs,
2168 const struct got_remote_repo *remote,
2169 int verbosity, struct got_repository *repo)
2171 const struct got_error *err = NULL, *unlock_err;
2172 struct got_reflist_head my_refs;
2173 struct got_reflist_entry *re;
2174 struct got_pathlist_entry *pe;
2175 char *remote_namespace = NULL;
2176 char *local_refname = NULL;
2178 TAILQ_INIT(&my_refs);
2180 if (asprintf(&remote_namespace, "refs/remotes/%s/", remote->name)
2181 == -1)
2182 return got_error_from_errno("asprintf");
2184 err = got_ref_list(&my_refs, repo, NULL, got_ref_cmp_by_name, NULL);
2185 if (err)
2186 goto done;
2188 TAILQ_FOREACH(re, &my_refs, entry) {
2189 const char *refname = got_ref_get_name(re->ref);
2190 const char *their_refname;
2192 if (remote->mirror_references) {
2193 their_refname = refname;
2194 } else {
2195 if (strncmp(refname, remote_namespace,
2196 strlen(remote_namespace)) == 0) {
2197 if (strcmp(refname + strlen(remote_namespace),
2198 GOT_REF_HEAD) == 0)
2199 continue;
2200 if (asprintf(&local_refname, "refs/heads/%s",
2201 refname + strlen(remote_namespace)) == -1) {
2202 err = got_error_from_errno("asprintf");
2203 goto done;
2205 } else if (strncmp(refname, "refs/tags/", 10) != 0)
2206 continue;
2208 their_refname = local_refname;
2211 TAILQ_FOREACH(pe, their_refs, entry) {
2212 if (strcmp(their_refname, pe->path) == 0)
2213 break;
2215 if (pe != NULL)
2216 continue;
2218 TAILQ_FOREACH(pe, their_symrefs, entry) {
2219 if (strcmp(their_refname, pe->path) == 0)
2220 break;
2222 if (pe != NULL)
2223 continue;
2225 err = delete_missing_ref(re->ref, verbosity, repo);
2226 if (err)
2227 break;
2229 if (local_refname) {
2230 struct got_reference *ref;
2231 err = got_ref_open(&ref, repo, local_refname, 1);
2232 if (err) {
2233 if (err->code != GOT_ERR_NOT_REF)
2234 break;
2235 free(local_refname);
2236 local_refname = NULL;
2237 continue;
2239 err = delete_missing_ref(ref, verbosity, repo);
2240 if (err)
2241 break;
2242 unlock_err = got_ref_unlock(ref);
2243 got_ref_close(ref);
2244 if (unlock_err && err == NULL) {
2245 err = unlock_err;
2246 break;
2249 free(local_refname);
2250 local_refname = NULL;
2253 done:
2254 got_ref_list_free(&my_refs);
2255 free(remote_namespace);
2256 free(local_refname);
2257 return err;
2260 static const struct got_error *
2261 update_wanted_ref(const char *refname, struct got_object_id *id,
2262 const char *remote_repo_name, int verbosity, struct got_repository *repo)
2264 const struct got_error *err, *unlock_err;
2265 char *remote_refname;
2266 struct got_reference *ref;
2268 if (strncmp("refs/", refname, 5) == 0)
2269 refname += 5;
2271 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
2272 remote_repo_name, refname) == -1)
2273 return got_error_from_errno("asprintf");
2275 err = got_ref_open(&ref, repo, remote_refname, 1);
2276 if (err) {
2277 if (err->code != GOT_ERR_NOT_REF)
2278 goto done;
2279 err = create_ref(remote_refname, id, verbosity, repo);
2280 } else {
2281 err = update_ref(ref, id, 0, verbosity, repo);
2282 unlock_err = got_ref_unlock(ref);
2283 if (unlock_err && err == NULL)
2284 err = unlock_err;
2285 got_ref_close(ref);
2287 done:
2288 free(remote_refname);
2289 return err;
2292 static const struct got_error *
2293 delete_ref(struct got_repository *repo, struct got_reference *ref)
2295 const struct got_error *err = NULL;
2296 struct got_object_id *id = NULL;
2297 char *id_str = NULL;
2298 const char *target;
2300 if (got_ref_is_symbolic(ref)) {
2301 target = got_ref_get_symref_target(ref);
2302 } else {
2303 err = got_ref_resolve(&id, repo, ref);
2304 if (err)
2305 goto done;
2306 err = got_object_id_str(&id_str, id);
2307 if (err)
2308 goto done;
2309 target = id_str;
2312 err = got_ref_delete(ref, repo);
2313 if (err)
2314 goto done;
2316 printf("Deleted %s: %s\n", got_ref_get_name(ref), target);
2317 done:
2318 free(id);
2319 free(id_str);
2320 return err;
2323 static const struct got_error *
2324 delete_refs_for_remote(struct got_repository *repo, const char *remote_name)
2326 const struct got_error *err = NULL;
2327 struct got_reflist_head refs;
2328 struct got_reflist_entry *re;
2329 char *prefix;
2331 TAILQ_INIT(&refs);
2333 if (asprintf(&prefix, "refs/remotes/%s", remote_name) == -1) {
2334 err = got_error_from_errno("asprintf");
2335 goto done;
2337 err = got_ref_list(&refs, repo, prefix, got_ref_cmp_by_name, NULL);
2338 if (err)
2339 goto done;
2341 TAILQ_FOREACH(re, &refs, entry)
2342 delete_ref(repo, re->ref);
2343 done:
2344 got_ref_list_free(&refs);
2345 return err;
2348 static const struct got_error *
2349 cmd_fetch(int argc, char *argv[])
2351 const struct got_error *error = NULL, *unlock_err;
2352 char *cwd = NULL, *repo_path = NULL;
2353 const char *remote_name;
2354 char *proto = NULL, *host = NULL, *port = NULL;
2355 char *repo_name = NULL, *server_path = NULL;
2356 const struct got_remote_repo *remotes;
2357 struct got_remote_repo *remote = NULL;
2358 int nremotes;
2359 char *id_str = NULL;
2360 struct got_repository *repo = NULL;
2361 struct got_worktree *worktree = NULL;
2362 const struct got_gotconfig *repo_conf = NULL, *worktree_conf = NULL;
2363 struct got_pathlist_head refs, symrefs, wanted_branches, wanted_refs;
2364 char *head_refname = NULL;
2365 struct got_pathlist_entry *pe;
2366 struct got_reflist_head remote_refs;
2367 struct got_reflist_entry *re;
2368 struct got_object_id *pack_hash = NULL;
2369 int i, ch, fetchfd = -1, fetchstatus;
2370 pid_t fetchpid = -1;
2371 struct got_fetch_progress_arg fpa;
2372 int verbosity = 0, fetch_all_branches = 0, list_refs_only = 0;
2373 int delete_refs = 0, replace_tags = 0, delete_remote = 0;
2374 int *pack_fds = NULL, have_bflag = 0;
2375 const char *remote_head = NULL, *worktree_branch = NULL;
2377 TAILQ_INIT(&refs);
2378 TAILQ_INIT(&symrefs);
2379 TAILQ_INIT(&remote_refs);
2380 TAILQ_INIT(&wanted_branches);
2381 TAILQ_INIT(&wanted_refs);
2383 while ((ch = getopt(argc, argv, "ab:dlqR:r:tvX")) != -1) {
2384 switch (ch) {
2385 case 'a':
2386 fetch_all_branches = 1;
2387 break;
2388 case 'b':
2389 error = got_pathlist_append(&wanted_branches,
2390 optarg, NULL);
2391 if (error)
2392 return error;
2393 have_bflag = 1;
2394 break;
2395 case 'd':
2396 delete_refs = 1;
2397 break;
2398 case 'l':
2399 list_refs_only = 1;
2400 break;
2401 case 'q':
2402 verbosity = -1;
2403 break;
2404 case 'R':
2405 error = got_pathlist_append(&wanted_refs,
2406 optarg, NULL);
2407 if (error)
2408 return error;
2409 break;
2410 case 'r':
2411 repo_path = realpath(optarg, NULL);
2412 if (repo_path == NULL)
2413 return got_error_from_errno2("realpath",
2414 optarg);
2415 got_path_strip_trailing_slashes(repo_path);
2416 break;
2417 case 't':
2418 replace_tags = 1;
2419 break;
2420 case 'v':
2421 if (verbosity < 0)
2422 verbosity = 0;
2423 else if (verbosity < 3)
2424 verbosity++;
2425 break;
2426 case 'X':
2427 delete_remote = 1;
2428 break;
2429 default:
2430 usage_fetch();
2431 break;
2434 argc -= optind;
2435 argv += optind;
2437 if (fetch_all_branches && !TAILQ_EMPTY(&wanted_branches))
2438 option_conflict('a', 'b');
2439 if (list_refs_only) {
2440 if (!TAILQ_EMPTY(&wanted_branches))
2441 option_conflict('l', 'b');
2442 if (fetch_all_branches)
2443 option_conflict('l', 'a');
2444 if (delete_refs)
2445 option_conflict('l', 'd');
2446 if (delete_remote)
2447 option_conflict('l', 'X');
2449 if (delete_remote) {
2450 if (fetch_all_branches)
2451 option_conflict('X', 'a');
2452 if (!TAILQ_EMPTY(&wanted_branches))
2453 option_conflict('X', 'b');
2454 if (delete_refs)
2455 option_conflict('X', 'd');
2456 if (replace_tags)
2457 option_conflict('X', 't');
2458 if (!TAILQ_EMPTY(&wanted_refs))
2459 option_conflict('X', 'R');
2462 if (argc == 0) {
2463 if (delete_remote)
2464 errx(1, "-X option requires a remote name");
2465 remote_name = GOT_FETCH_DEFAULT_REMOTE_NAME;
2466 } else if (argc == 1)
2467 remote_name = argv[0];
2468 else
2469 usage_fetch();
2471 cwd = getcwd(NULL, 0);
2472 if (cwd == NULL) {
2473 error = got_error_from_errno("getcwd");
2474 goto done;
2477 error = got_repo_pack_fds_open(&pack_fds);
2478 if (error != NULL)
2479 goto done;
2481 if (repo_path == NULL) {
2482 error = got_worktree_open(&worktree, cwd, GOT_WORKTREE_GOT_DIR);
2483 if (error && error->code != GOT_ERR_NOT_WORKTREE)
2484 goto done;
2485 else
2486 error = NULL;
2487 if (worktree) {
2488 repo_path =
2489 strdup(got_worktree_get_repo_path(worktree));
2490 if (repo_path == NULL)
2491 error = got_error_from_errno("strdup");
2492 if (error)
2493 goto done;
2494 } else {
2495 repo_path = strdup(cwd);
2496 if (repo_path == NULL) {
2497 error = got_error_from_errno("strdup");
2498 goto done;
2503 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
2504 if (error)
2505 goto done;
2507 if (delete_remote) {
2508 error = delete_refs_for_remote(repo, remote_name);
2509 goto done; /* nothing else to do */
2512 if (worktree) {
2513 worktree_conf = got_worktree_get_gotconfig(worktree);
2514 if (worktree_conf) {
2515 got_gotconfig_get_remotes(&nremotes, &remotes,
2516 worktree_conf);
2517 for (i = 0; i < nremotes; i++) {
2518 if (strcmp(remotes[i].name, remote_name) == 0) {
2519 error = got_repo_remote_repo_dup(&remote,
2520 &remotes[i]);
2521 if (error)
2522 goto done;
2523 break;
2528 if (remote == NULL) {
2529 repo_conf = got_repo_get_gotconfig(repo);
2530 if (repo_conf) {
2531 got_gotconfig_get_remotes(&nremotes, &remotes,
2532 repo_conf);
2533 for (i = 0; i < nremotes; i++) {
2534 if (strcmp(remotes[i].name, remote_name) == 0) {
2535 error = got_repo_remote_repo_dup(&remote,
2536 &remotes[i]);
2537 if (error)
2538 goto done;
2539 break;
2544 if (remote == NULL) {
2545 got_repo_get_gitconfig_remotes(&nremotes, &remotes, repo);
2546 for (i = 0; i < nremotes; i++) {
2547 if (strcmp(remotes[i].name, remote_name) == 0) {
2548 error = got_repo_remote_repo_dup(&remote,
2549 &remotes[i]);
2550 if (error)
2551 goto done;
2552 break;
2556 if (remote == NULL) {
2557 error = got_error_path(remote_name, GOT_ERR_NO_REMOTE);
2558 goto done;
2561 if (TAILQ_EMPTY(&wanted_branches)) {
2562 if (!fetch_all_branches)
2563 fetch_all_branches = remote->fetch_all_branches;
2564 for (i = 0; i < remote->nfetch_branches; i++) {
2565 error = got_pathlist_append(&wanted_branches,
2566 remote->fetch_branches[i], NULL);
2567 if (error)
2568 goto done;
2571 if (TAILQ_EMPTY(&wanted_refs)) {
2572 for (i = 0; i < remote->nfetch_refs; i++) {
2573 error = got_pathlist_append(&wanted_refs,
2574 remote->fetch_refs[i], NULL);
2575 if (error)
2576 goto done;
2580 error = got_dial_parse_uri(&proto, &host, &port, &server_path,
2581 &repo_name, remote->fetch_url);
2582 if (error)
2583 goto done;
2585 if (strcmp(proto, "git") == 0) {
2586 #ifndef PROFILE
2587 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
2588 "sendfd dns inet unveil", NULL) == -1)
2589 err(1, "pledge");
2590 #endif
2591 } else if (strcmp(proto, "git+ssh") == 0 ||
2592 strcmp(proto, "ssh") == 0 ||
2593 strcmp(proto, "git+http") == 0 ||
2594 strcmp(proto, "http") == 0 ||
2595 strcmp(proto, "git+https") == 0 ||
2596 strcmp(proto, "https") == 0) {
2597 #ifndef PROFILE
2598 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
2599 "sendfd unveil", NULL) == -1)
2600 err(1, "pledge");
2601 #endif
2602 } else {
2603 error = got_error_path(proto, GOT_ERR_BAD_PROTO);
2604 goto done;
2607 error = got_dial_apply_unveil(proto);
2608 if (error)
2609 goto done;
2611 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
2612 if (error)
2613 goto done;
2615 if (worktree) {
2616 head_refname = strdup(got_worktree_get_head_ref_name(worktree));
2617 if (head_refname == NULL) {
2618 error = got_error_from_errno("strdup");
2619 goto done;
2622 /* Release work tree lock. */
2623 got_worktree_close(worktree);
2624 worktree = NULL;
2627 if (verbosity >= 0) {
2628 printf("Connecting to \"%s\" %s://%s%s%s%s%s\n",
2629 remote->name, proto, host,
2630 port ? ":" : "", port ? port : "",
2631 *server_path == '/' ? "" : "/", server_path);
2634 error = got_fetch_connect(&fetchpid, &fetchfd, proto, host, port,
2635 server_path, verbosity);
2636 if (error)
2637 goto done;
2638 #ifndef PROFILE
2639 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd",
2640 NULL) == -1)
2641 err(1, "pledge");
2642 #endif
2643 if (!have_bflag) {
2645 * If set, get this remote's HEAD ref target so
2646 * if it has changed on the server we can fetch it.
2648 error = got_ref_list(&remote_refs, repo, "refs/remotes",
2649 got_ref_cmp_by_name, repo);
2650 if (error)
2651 goto done;
2653 TAILQ_FOREACH(re, &remote_refs, entry) {
2654 const char *remote_refname, *remote_target;
2655 size_t remote_name_len;
2657 if (!got_ref_is_symbolic(re->ref))
2658 continue;
2660 remote_name_len = strlen(remote->name);
2661 remote_refname = got_ref_get_name(re->ref);
2663 /* we only want refs/remotes/$remote->name/HEAD */
2664 if (strncmp(remote_refname + 13, remote->name,
2665 remote_name_len) != 0)
2666 continue;
2668 if (strcmp(remote_refname + remote_name_len + 14,
2669 GOT_REF_HEAD) != 0)
2670 continue;
2673 * Take the name itself because we already
2674 * only match with refs/heads/ in fetch_pack().
2676 remote_target = got_ref_get_symref_target(re->ref);
2677 remote_head = remote_target + remote_name_len + 14;
2678 break;
2681 if (head_refname &&
2682 strncmp(head_refname, "refs/heads/", 11) == 0)
2683 worktree_branch = head_refname;
2686 fpa.last_scaled_size[0] = '\0';
2687 fpa.last_p_indexed = -1;
2688 fpa.last_p_resolved = -1;
2689 fpa.verbosity = verbosity;
2690 fpa.repo = repo;
2691 fpa.create_configs = 0;
2692 fpa.configs_created = 0;
2693 memset(&fpa.config_info, 0, sizeof(fpa.config_info));
2695 error = got_fetch_pack(&pack_hash, &refs, &symrefs, remote->name,
2696 remote->mirror_references, fetch_all_branches, &wanted_branches,
2697 &wanted_refs, list_refs_only, verbosity, fetchfd, repo,
2698 worktree_branch, remote_head, have_bflag, fetch_progress, &fpa);
2699 if (error)
2700 goto done;
2702 if (list_refs_only) {
2703 error = list_remote_refs(&symrefs, &refs);
2704 goto done;
2707 if (pack_hash == NULL) {
2708 if (verbosity >= 0)
2709 printf("Already up-to-date\n");
2710 } else if (verbosity >= 0) {
2711 error = got_object_id_str(&id_str, pack_hash);
2712 if (error)
2713 goto done;
2714 printf("\nFetched %s.pack\n", id_str);
2715 free(id_str);
2716 id_str = NULL;
2719 /* Update references provided with the pack file. */
2720 TAILQ_FOREACH(pe, &refs, entry) {
2721 const char *refname = pe->path;
2722 struct got_object_id *id = pe->data;
2723 struct got_reference *ref;
2724 char *remote_refname;
2726 if (is_wanted_ref(&wanted_refs, refname) &&
2727 !remote->mirror_references) {
2728 error = update_wanted_ref(refname, id,
2729 remote->name, verbosity, repo);
2730 if (error)
2731 goto done;
2732 continue;
2735 if (remote->mirror_references ||
2736 strncmp("refs/tags/", refname, 10) == 0) {
2737 error = got_ref_open(&ref, repo, refname, 1);
2738 if (error) {
2739 if (error->code != GOT_ERR_NOT_REF)
2740 goto done;
2741 error = create_ref(refname, id, verbosity,
2742 repo);
2743 if (error)
2744 goto done;
2745 } else {
2746 error = update_ref(ref, id, replace_tags,
2747 verbosity, repo);
2748 unlock_err = got_ref_unlock(ref);
2749 if (unlock_err && error == NULL)
2750 error = unlock_err;
2751 got_ref_close(ref);
2752 if (error)
2753 goto done;
2755 } else if (strncmp("refs/heads/", refname, 11) == 0) {
2756 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
2757 remote_name, refname + 11) == -1) {
2758 error = got_error_from_errno("asprintf");
2759 goto done;
2762 error = got_ref_open(&ref, repo, remote_refname, 1);
2763 if (error) {
2764 if (error->code != GOT_ERR_NOT_REF)
2765 goto done;
2766 error = create_ref(remote_refname, id,
2767 verbosity, repo);
2768 if (error)
2769 goto done;
2770 } else {
2771 error = update_ref(ref, id, replace_tags,
2772 verbosity, repo);
2773 unlock_err = got_ref_unlock(ref);
2774 if (unlock_err && error == NULL)
2775 error = unlock_err;
2776 got_ref_close(ref);
2777 if (error)
2778 goto done;
2781 /* Also create a local branch if none exists yet. */
2782 error = got_ref_open(&ref, repo, refname, 1);
2783 if (error) {
2784 if (error->code != GOT_ERR_NOT_REF)
2785 goto done;
2786 error = create_ref(refname, id, verbosity,
2787 repo);
2788 if (error)
2789 goto done;
2790 } else {
2791 unlock_err = got_ref_unlock(ref);
2792 if (unlock_err && error == NULL)
2793 error = unlock_err;
2794 got_ref_close(ref);
2798 if (delete_refs) {
2799 error = delete_missing_refs(&refs, &symrefs, remote,
2800 verbosity, repo);
2801 if (error)
2802 goto done;
2805 if (!remote->mirror_references) {
2806 /* Update remote HEAD reference if the server provided one. */
2807 TAILQ_FOREACH(pe, &symrefs, entry) {
2808 struct got_reference *target_ref;
2809 const char *refname = pe->path;
2810 const char *target = pe->data;
2811 char *remote_refname = NULL, *remote_target = NULL;
2813 if (strcmp(refname, GOT_REF_HEAD) != 0)
2814 continue;
2816 if (strncmp("refs/heads/", target, 11) != 0)
2817 continue;
2819 if (asprintf(&remote_refname, "refs/remotes/%s/%s",
2820 remote->name, refname) == -1) {
2821 error = got_error_from_errno("asprintf");
2822 goto done;
2824 if (asprintf(&remote_target, "refs/remotes/%s/%s",
2825 remote->name, target + 11) == -1) {
2826 error = got_error_from_errno("asprintf");
2827 free(remote_refname);
2828 goto done;
2831 error = got_ref_open(&target_ref, repo, remote_target,
2832 0);
2833 if (error) {
2834 free(remote_refname);
2835 free(remote_target);
2836 if (error->code == GOT_ERR_NOT_REF) {
2837 error = NULL;
2838 continue;
2840 goto done;
2842 error = update_symref(remote_refname, target_ref,
2843 verbosity, repo);
2844 free(remote_refname);
2845 free(remote_target);
2846 got_ref_close(target_ref);
2847 if (error)
2848 goto done;
2851 done:
2852 if (fetchpid > 0) {
2853 if (kill(fetchpid, SIGTERM) == -1)
2854 error = got_error_from_errno("kill");
2855 if (waitpid(fetchpid, &fetchstatus, 0) == -1 && error == NULL)
2856 error = got_error_from_errno("waitpid");
2858 if (fetchfd != -1 && close(fetchfd) == -1 && error == NULL)
2859 error = got_error_from_errno("close");
2860 if (repo) {
2861 const struct got_error *close_err = got_repo_close(repo);
2862 if (error == NULL)
2863 error = close_err;
2865 if (worktree)
2866 got_worktree_close(worktree);
2867 if (pack_fds) {
2868 const struct got_error *pack_err =
2869 got_repo_pack_fds_close(pack_fds);
2870 if (error == NULL)
2871 error = pack_err;
2873 got_pathlist_free(&refs, GOT_PATHLIST_FREE_ALL);
2874 got_pathlist_free(&symrefs, GOT_PATHLIST_FREE_ALL);
2875 got_pathlist_free(&wanted_branches, GOT_PATHLIST_FREE_NONE);
2876 got_pathlist_free(&wanted_refs, GOT_PATHLIST_FREE_NONE);
2877 got_ref_list_free(&remote_refs);
2878 got_repo_free_remote_repo_data(remote);
2879 free(remote);
2880 free(head_refname);
2881 free(id_str);
2882 free(cwd);
2883 free(repo_path);
2884 free(pack_hash);
2885 free(proto);
2886 free(host);
2887 free(port);
2888 free(server_path);
2889 free(repo_name);
2890 return error;
2894 __dead static void
2895 usage_checkout(void)
2897 fprintf(stderr, "usage: %s checkout [-Eq] [-b branch] [-c commit] "
2898 "[-p path-prefix] repository-path [work-tree-path]\n",
2899 getprogname());
2900 exit(1);
2903 static void
2904 show_worktree_base_ref_warning(void)
2906 fprintf(stderr, "%s: warning: could not create a reference "
2907 "to the work tree's base commit; the commit could be "
2908 "garbage-collected by Git or 'gotadmin cleanup'; making the "
2909 "repository writable and running 'got update' will prevent this\n",
2910 getprogname());
2913 struct got_checkout_progress_arg {
2914 const char *worktree_path;
2915 int had_base_commit_ref_error;
2916 int verbosity;
2919 static const struct got_error *
2920 checkout_progress(void *arg, unsigned char status, const char *path)
2922 struct got_checkout_progress_arg *a = arg;
2924 /* Base commit bump happens silently. */
2925 if (status == GOT_STATUS_BUMP_BASE)
2926 return NULL;
2928 if (status == GOT_STATUS_BASE_REF_ERR) {
2929 a->had_base_commit_ref_error = 1;
2930 return NULL;
2933 while (path[0] == '/')
2934 path++;
2936 if (a->verbosity >= 0)
2937 printf("%c %s/%s\n", status, a->worktree_path, path);
2939 return NULL;
2942 static const struct got_error *
2943 check_cancelled(void *arg)
2945 if (sigint_received || sigpipe_received)
2946 return got_error(GOT_ERR_CANCELLED);
2947 return NULL;
2950 static const struct got_error *
2951 check_linear_ancestry(struct got_object_id *commit_id,
2952 struct got_object_id *base_commit_id, int allow_forwards_in_time_only,
2953 struct got_repository *repo)
2955 const struct got_error *err = NULL;
2956 struct got_object_id *yca_id;
2958 err = got_commit_graph_find_youngest_common_ancestor(&yca_id,
2959 commit_id, base_commit_id, 1, 0, repo, check_cancelled, NULL);
2960 if (err)
2961 return err;
2963 if (yca_id == NULL)
2964 return got_error(GOT_ERR_ANCESTRY);
2967 * Require a straight line of history between the target commit
2968 * and the work tree's base commit.
2970 * Non-linear situations such as this require a rebase:
2972 * (commit) D F (base_commit)
2973 * \ /
2974 * C E
2975 * \ /
2976 * B (yca)
2977 * |
2978 * A
2980 * 'got update' only handles linear cases:
2981 * Update forwards in time: A (base/yca) - B - C - D (commit)
2982 * Update backwards in time: D (base) - C - B - A (commit/yca)
2984 if (allow_forwards_in_time_only) {
2985 if (got_object_id_cmp(base_commit_id, yca_id) != 0)
2986 return got_error(GOT_ERR_ANCESTRY);
2987 } else if (got_object_id_cmp(commit_id, yca_id) != 0 &&
2988 got_object_id_cmp(base_commit_id, yca_id) != 0)
2989 return got_error(GOT_ERR_ANCESTRY);
2991 free(yca_id);
2992 return NULL;
2995 static const struct got_error *
2996 check_same_branch(struct got_object_id *commit_id,
2997 struct got_reference *head_ref, struct got_repository *repo)
2999 const struct got_error *err = NULL;
3000 struct got_commit_graph *graph = NULL;
3001 struct got_object_id *head_commit_id = NULL;
3003 err = got_ref_resolve(&head_commit_id, repo, head_ref);
3004 if (err)
3005 goto done;
3007 if (got_object_id_cmp(head_commit_id, commit_id) == 0)
3008 goto done;
3010 err = got_commit_graph_open(&graph, "/", 1);
3011 if (err)
3012 goto done;
3014 err = got_commit_graph_bfsort(graph, head_commit_id, repo,
3015 check_cancelled, NULL);
3016 if (err)
3017 goto done;
3019 for (;;) {
3020 struct got_object_id id;
3022 err = got_commit_graph_iter_next(&id, graph, repo,
3023 check_cancelled, NULL);
3024 if (err) {
3025 if (err->code == GOT_ERR_ITER_COMPLETED)
3026 err = got_error(GOT_ERR_ANCESTRY);
3027 break;
3030 if (got_object_id_cmp(&id, commit_id) == 0)
3031 break;
3033 done:
3034 if (graph)
3035 got_commit_graph_close(graph);
3036 free(head_commit_id);
3037 return err;
3040 static const struct got_error *
3041 checkout_ancestry_error(struct got_reference *ref, const char *commit_id_str)
3043 static char msg[512];
3044 const char *branch_name;
3046 if (got_ref_is_symbolic(ref))
3047 branch_name = got_ref_get_symref_target(ref);
3048 else
3049 branch_name = got_ref_get_name(ref);
3051 if (strncmp("refs/heads/", branch_name, 11) == 0)
3052 branch_name += 11;
3054 snprintf(msg, sizeof(msg),
3055 "target commit is not contained in branch '%s'; "
3056 "the branch to use must be specified with -b; "
3057 "if necessary a new branch can be created for "
3058 "this commit with 'got branch -c %s BRANCH_NAME'",
3059 branch_name, commit_id_str);
3061 return got_error_msg(GOT_ERR_ANCESTRY, msg);
3064 static const struct got_error *
3065 cmd_checkout(int argc, char *argv[])
3067 const struct got_error *close_err, *error = NULL;
3068 struct got_repository *repo = NULL;
3069 struct got_reference *head_ref = NULL, *ref = NULL;
3070 struct got_worktree *worktree = NULL;
3071 char *repo_path = NULL;
3072 char *worktree_path = NULL;
3073 const char *path_prefix = "";
3074 const char *branch_name = GOT_REF_HEAD, *refname = NULL;
3075 char *commit_id_str = NULL, *keyword_idstr = NULL;
3076 struct got_object_id *commit_id = NULL;
3077 char *cwd = NULL;
3078 int ch, same_path_prefix, allow_nonempty = 0, verbosity = 0;
3079 struct got_pathlist_head paths;
3080 struct got_checkout_progress_arg cpa;
3081 int *pack_fds = NULL;
3083 TAILQ_INIT(&paths);
3085 #ifndef PROFILE
3086 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
3087 "unveil", NULL) == -1)
3088 err(1, "pledge");
3089 #endif
3091 while ((ch = getopt(argc, argv, "b:c:Ep:q")) != -1) {
3092 switch (ch) {
3093 case 'b':
3094 branch_name = optarg;
3095 break;
3096 case 'c':
3097 commit_id_str = strdup(optarg);
3098 if (commit_id_str == NULL)
3099 return got_error_from_errno("strdup");
3100 break;
3101 case 'E':
3102 allow_nonempty = 1;
3103 break;
3104 case 'p':
3105 path_prefix = optarg;
3106 break;
3107 case 'q':
3108 verbosity = -1;
3109 break;
3110 default:
3111 usage_checkout();
3112 /* NOTREACHED */
3116 argc -= optind;
3117 argv += optind;
3119 if (argc == 1) {
3120 char *base, *dotgit;
3121 const char *path;
3122 repo_path = realpath(argv[0], NULL);
3123 if (repo_path == NULL)
3124 return got_error_from_errno2("realpath", argv[0]);
3125 cwd = getcwd(NULL, 0);
3126 if (cwd == NULL) {
3127 error = got_error_from_errno("getcwd");
3128 goto done;
3130 if (path_prefix[0])
3131 path = path_prefix;
3132 else
3133 path = repo_path;
3134 error = got_path_basename(&base, path);
3135 if (error)
3136 goto done;
3137 dotgit = strstr(base, ".git");
3138 if (dotgit)
3139 *dotgit = '\0';
3140 if (asprintf(&worktree_path, "%s/%s", cwd, base) == -1) {
3141 error = got_error_from_errno("asprintf");
3142 free(base);
3143 goto done;
3145 free(base);
3146 } else if (argc == 2) {
3147 repo_path = realpath(argv[0], NULL);
3148 if (repo_path == NULL) {
3149 error = got_error_from_errno2("realpath", argv[0]);
3150 goto done;
3152 worktree_path = realpath(argv[1], NULL);
3153 if (worktree_path == NULL) {
3154 if (errno != ENOENT) {
3155 error = got_error_from_errno2("realpath",
3156 argv[1]);
3157 goto done;
3159 worktree_path = strdup(argv[1]);
3160 if (worktree_path == NULL) {
3161 error = got_error_from_errno("strdup");
3162 goto done;
3165 } else
3166 usage_checkout();
3168 got_path_strip_trailing_slashes(repo_path);
3169 got_path_strip_trailing_slashes(worktree_path);
3171 if (got_path_is_child(worktree_path, repo_path, strlen(repo_path)) ||
3172 got_path_is_child(repo_path, worktree_path,
3173 strlen(worktree_path))) {
3174 error = got_error_fmt(GOT_ERR_BAD_PATH,
3175 "work tree and repository paths may not overlap: %s",
3176 worktree_path);
3177 goto done;
3180 error = got_repo_pack_fds_open(&pack_fds);
3181 if (error != NULL)
3182 goto done;
3184 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
3185 if (error != NULL)
3186 goto done;
3188 /* Pre-create work tree path for unveil(2) */
3189 error = got_path_mkdir(worktree_path);
3190 if (error) {
3191 if (!(error->code == GOT_ERR_ERRNO && errno == EISDIR) &&
3192 !(error->code == GOT_ERR_ERRNO && errno == EEXIST))
3193 goto done;
3194 if (!allow_nonempty &&
3195 !got_path_dir_is_empty(worktree_path)) {
3196 error = got_error_path(worktree_path,
3197 GOT_ERR_DIR_NOT_EMPTY);
3198 goto done;
3202 error = apply_unveil(got_repo_get_path(repo), 0, worktree_path);
3203 if (error)
3204 goto done;
3206 error = got_ref_open(&head_ref, repo, branch_name, 0);
3207 if (error != NULL)
3208 goto done;
3210 error = got_worktree_init(worktree_path, head_ref, path_prefix,
3211 GOT_WORKTREE_GOT_DIR, repo);
3212 if (error != NULL && !(error->code == GOT_ERR_ERRNO && errno == EEXIST))
3213 goto done;
3215 error = got_worktree_open(&worktree, worktree_path,
3216 GOT_WORKTREE_GOT_DIR);
3217 if (error != NULL)
3218 goto done;
3220 error = got_worktree_match_path_prefix(&same_path_prefix, worktree,
3221 path_prefix);
3222 if (error != NULL)
3223 goto done;
3224 if (!same_path_prefix) {
3225 error = got_error(GOT_ERR_PATH_PREFIX);
3226 goto done;
3229 if (commit_id_str) {
3230 struct got_reflist_head refs;
3231 TAILQ_INIT(&refs);
3232 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
3233 NULL);
3234 if (error)
3235 goto done;
3237 error = got_keyword_to_idstr(&keyword_idstr, commit_id_str,
3238 repo, worktree);
3239 if (error != NULL)
3240 goto done;
3241 if (keyword_idstr != NULL) {
3242 free(commit_id_str);
3243 commit_id_str = keyword_idstr;
3246 error = got_repo_match_object_id(&commit_id, NULL,
3247 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
3248 got_ref_list_free(&refs);
3249 if (error)
3250 goto done;
3251 error = check_linear_ancestry(commit_id,
3252 got_worktree_get_base_commit_id(worktree), 0, repo);
3253 if (error != NULL) {
3254 if (error->code == GOT_ERR_ANCESTRY) {
3255 error = checkout_ancestry_error(
3256 head_ref, commit_id_str);
3258 goto done;
3260 error = check_same_branch(commit_id, head_ref, repo);
3261 if (error) {
3262 if (error->code == GOT_ERR_ANCESTRY) {
3263 error = checkout_ancestry_error(
3264 head_ref, commit_id_str);
3266 goto done;
3268 error = got_worktree_set_base_commit_id(worktree, repo,
3269 commit_id);
3270 if (error)
3271 goto done;
3272 /* Expand potentially abbreviated commit ID string. */
3273 free(commit_id_str);
3274 error = got_object_id_str(&commit_id_str, commit_id);
3275 if (error)
3276 goto done;
3277 } else {
3278 commit_id = got_object_id_dup(
3279 got_worktree_get_base_commit_id(worktree));
3280 if (commit_id == NULL) {
3281 error = got_error_from_errno("got_object_id_dup");
3282 goto done;
3284 error = got_object_id_str(&commit_id_str, commit_id);
3285 if (error)
3286 goto done;
3289 error = got_pathlist_append(&paths, "", NULL);
3290 if (error)
3291 goto done;
3292 cpa.worktree_path = worktree_path;
3293 cpa.had_base_commit_ref_error = 0;
3294 cpa.verbosity = verbosity;
3295 error = got_worktree_checkout_files(worktree, &paths, repo,
3296 checkout_progress, &cpa, check_cancelled, NULL);
3297 if (error != NULL)
3298 goto done;
3300 if (got_ref_is_symbolic(head_ref)) {
3301 error = got_ref_resolve_symbolic(&ref, repo, head_ref);
3302 if (error)
3303 goto done;
3304 refname = got_ref_get_name(ref);
3305 } else
3306 refname = got_ref_get_name(head_ref);
3307 printf("Checked out %s: %s\n", refname, commit_id_str);
3308 printf("Now shut up and hack\n");
3309 if (cpa.had_base_commit_ref_error)
3310 show_worktree_base_ref_warning();
3311 done:
3312 if (pack_fds) {
3313 const struct got_error *pack_err =
3314 got_repo_pack_fds_close(pack_fds);
3315 if (error == NULL)
3316 error = pack_err;
3318 if (head_ref)
3319 got_ref_close(head_ref);
3320 if (ref)
3321 got_ref_close(ref);
3322 if (repo) {
3323 close_err = got_repo_close(repo);
3324 if (error == NULL)
3325 error = close_err;
3327 if (worktree != NULL) {
3328 close_err = got_worktree_close(worktree);
3329 if (error == NULL)
3330 error = close_err;
3332 got_pathlist_free(&paths, GOT_PATHLIST_FREE_NONE);
3333 free(commit_id_str);
3334 free(commit_id);
3335 free(repo_path);
3336 free(worktree_path);
3337 free(cwd);
3338 return error;
3341 struct got_update_progress_arg {
3342 int did_something;
3343 int conflicts;
3344 int obstructed;
3345 int not_updated;
3346 int missing;
3347 int not_deleted;
3348 int unversioned;
3349 int verbosity;
3352 static void
3353 print_update_progress_stats(struct got_update_progress_arg *upa)
3355 if (!upa->did_something)
3356 return;
3358 if (upa->conflicts > 0)
3359 printf("Files with new merge conflicts: %d\n", upa->conflicts);
3360 if (upa->obstructed > 0)
3361 printf("File paths obstructed by a non-regular file: %d\n",
3362 upa->obstructed);
3363 if (upa->not_updated > 0)
3364 printf("Files not updated because of existing merge "
3365 "conflicts: %d\n", upa->not_updated);
3369 * The meaning of some status codes differs between merge-style operations and
3370 * update operations. For example, the ! status code means "file was missing"
3371 * if changes were merged into the work tree, and "missing file was restored"
3372 * if the work tree was updated. This function should be used by any operation
3373 * which merges changes into the work tree without updating the work tree.
3375 static void
3376 print_merge_progress_stats(struct got_update_progress_arg *upa)
3378 if (!upa->did_something)
3379 return;
3381 if (upa->conflicts > 0)
3382 printf("Files with new merge conflicts: %d\n", upa->conflicts);
3383 if (upa->obstructed > 0)
3384 printf("File paths obstructed by a non-regular file: %d\n",
3385 upa->obstructed);
3386 if (upa->missing > 0)
3387 printf("Files which had incoming changes but could not be "
3388 "found in the work tree: %d\n", upa->missing);
3389 if (upa->not_deleted > 0)
3390 printf("Files not deleted due to differences in deleted "
3391 "content: %d\n", upa->not_deleted);
3392 if (upa->unversioned > 0)
3393 printf("Files not merged because an unversioned file was "
3394 "found in the work tree: %d\n", upa->unversioned);
3397 __dead static void
3398 usage_update(void)
3400 fprintf(stderr, "usage: %s update [-q] [-b branch] [-c commit] "
3401 "[path ...]\n", getprogname());
3402 exit(1);
3405 static const struct got_error *
3406 update_progress(void *arg, unsigned char status, const char *path)
3408 struct got_update_progress_arg *upa = arg;
3410 if (status == GOT_STATUS_EXISTS ||
3411 status == GOT_STATUS_BASE_REF_ERR)
3412 return NULL;
3414 upa->did_something = 1;
3416 /* Base commit bump happens silently. */
3417 if (status == GOT_STATUS_BUMP_BASE)
3418 return NULL;
3420 if (status == GOT_STATUS_CONFLICT)
3421 upa->conflicts++;
3422 if (status == GOT_STATUS_OBSTRUCTED)
3423 upa->obstructed++;
3424 if (status == GOT_STATUS_CANNOT_UPDATE)
3425 upa->not_updated++;
3426 if (status == GOT_STATUS_MISSING)
3427 upa->missing++;
3428 if (status == GOT_STATUS_CANNOT_DELETE)
3429 upa->not_deleted++;
3430 if (status == GOT_STATUS_UNVERSIONED)
3431 upa->unversioned++;
3433 while (path[0] == '/')
3434 path++;
3435 if (upa->verbosity >= 0)
3436 printf("%c %s\n", status, path);
3438 return NULL;
3441 static const struct got_error *
3442 switch_head_ref(struct got_reference *head_ref,
3443 struct got_object_id *commit_id, struct got_worktree *worktree,
3444 struct got_repository *repo)
3446 const struct got_error *err = NULL;
3447 char *base_id_str;
3448 int ref_has_moved = 0;
3450 /* Trivial case: switching between two different references. */
3451 if (strcmp(got_ref_get_name(head_ref),
3452 got_worktree_get_head_ref_name(worktree)) != 0) {
3453 printf("Switching work tree from %s to %s\n",
3454 got_worktree_get_head_ref_name(worktree),
3455 got_ref_get_name(head_ref));
3456 return got_worktree_set_head_ref(worktree, head_ref);
3459 err = check_linear_ancestry(commit_id,
3460 got_worktree_get_base_commit_id(worktree), 0, repo);
3461 if (err) {
3462 if (err->code != GOT_ERR_ANCESTRY)
3463 return err;
3464 ref_has_moved = 1;
3466 if (!ref_has_moved)
3467 return NULL;
3469 /* Switching to a rebased branch with the same reference name. */
3470 err = got_object_id_str(&base_id_str,
3471 got_worktree_get_base_commit_id(worktree));
3472 if (err)
3473 return err;
3474 printf("Reference %s now points at a different branch\n",
3475 got_worktree_get_head_ref_name(worktree));
3476 printf("Switching work tree from %s to %s\n", base_id_str,
3477 got_worktree_get_head_ref_name(worktree));
3478 return NULL;
3481 static const struct got_error *
3482 check_rebase_or_histedit_in_progress(struct got_worktree *worktree)
3484 const struct got_error *err;
3485 int in_progress;
3487 err = got_worktree_rebase_in_progress(&in_progress, worktree);
3488 if (err)
3489 return err;
3490 if (in_progress)
3491 return got_error(GOT_ERR_REBASING);
3493 err = got_worktree_histedit_in_progress(&in_progress, worktree);
3494 if (err)
3495 return err;
3496 if (in_progress)
3497 return got_error(GOT_ERR_HISTEDIT_BUSY);
3499 return NULL;
3502 static const struct got_error *
3503 check_merge_in_progress(struct got_worktree *worktree,
3504 struct got_repository *repo)
3506 const struct got_error *err;
3507 int in_progress;
3509 err = got_worktree_merge_in_progress(&in_progress, worktree, repo);
3510 if (err)
3511 return err;
3512 if (in_progress)
3513 return got_error(GOT_ERR_MERGE_BUSY);
3515 return NULL;
3518 static const struct got_error *
3519 get_worktree_paths_from_argv(struct got_pathlist_head *paths, int argc,
3520 char *argv[], struct got_worktree *worktree)
3522 const struct got_error *err = NULL;
3523 char *path;
3524 struct got_pathlist_entry *new;
3525 int i;
3527 if (argc == 0) {
3528 path = strdup("");
3529 if (path == NULL)
3530 return got_error_from_errno("strdup");
3531 return got_pathlist_append(paths, path, NULL);
3534 for (i = 0; i < argc; i++) {
3535 err = got_worktree_resolve_path(&path, worktree, argv[i]);
3536 if (err)
3537 break;
3538 err = got_pathlist_insert(&new, paths, path, NULL);
3539 if (err || new == NULL /* duplicate */) {
3540 free(path);
3541 if (err)
3542 break;
3546 return err;
3549 static const struct got_error *
3550 wrap_not_worktree_error(const struct got_error *orig_err,
3551 const char *cmdname, const char *path)
3553 const struct got_error *err;
3554 struct got_repository *repo;
3555 static char msg[512];
3556 int *pack_fds = NULL;
3558 err = got_repo_pack_fds_open(&pack_fds);
3559 if (err)
3560 return err;
3562 err = got_repo_open(&repo, path, NULL, pack_fds);
3563 if (err)
3564 return orig_err;
3566 snprintf(msg, sizeof(msg),
3567 "'got %s' needs a work tree in addition to a git repository\n"
3568 "Work trees can be checked out from this Git repository with "
3569 "'got checkout'.\n"
3570 "The got(1) manual page contains more information.", cmdname);
3571 err = got_error_msg(GOT_ERR_NOT_WORKTREE, msg);
3572 if (repo) {
3573 const struct got_error *close_err = got_repo_close(repo);
3574 if (err == NULL)
3575 err = close_err;
3577 if (pack_fds) {
3578 const struct got_error *pack_err =
3579 got_repo_pack_fds_close(pack_fds);
3580 if (err == NULL)
3581 err = pack_err;
3583 return err;
3586 static const struct got_error *
3587 cmd_update(int argc, char *argv[])
3589 const struct got_error *close_err, *error = NULL;
3590 struct got_repository *repo = NULL;
3591 struct got_worktree *worktree = NULL;
3592 char *worktree_path = NULL;
3593 struct got_object_id *commit_id = NULL;
3594 char *commit_id_str = NULL;
3595 const char *branch_name = NULL;
3596 struct got_reference *head_ref = NULL;
3597 struct got_pathlist_head paths;
3598 struct got_pathlist_entry *pe;
3599 int ch, verbosity = 0;
3600 struct got_update_progress_arg upa;
3601 int *pack_fds = NULL;
3603 TAILQ_INIT(&paths);
3605 #ifndef PROFILE
3606 if (pledge("stdio rpath wpath cpath fattr flock proc exec sendfd "
3607 "unveil", NULL) == -1)
3608 err(1, "pledge");
3609 #endif
3611 while ((ch = getopt(argc, argv, "b:c:q")) != -1) {
3612 switch (ch) {
3613 case 'b':
3614 branch_name = optarg;
3615 break;
3616 case 'c':
3617 commit_id_str = strdup(optarg);
3618 if (commit_id_str == NULL)
3619 return got_error_from_errno("strdup");
3620 break;
3621 case 'q':
3622 verbosity = -1;
3623 break;
3624 default:
3625 usage_update();
3626 /* NOTREACHED */
3630 argc -= optind;
3631 argv += optind;
3633 worktree_path = getcwd(NULL, 0);
3634 if (worktree_path == NULL) {
3635 error = got_error_from_errno("getcwd");
3636 goto done;
3639 error = got_repo_pack_fds_open(&pack_fds);
3640 if (error != NULL)
3641 goto done;
3643 error = got_worktree_open(&worktree, worktree_path,
3644 GOT_WORKTREE_GOT_DIR);
3645 if (error) {
3646 if (error->code == GOT_ERR_NOT_WORKTREE)
3647 error = wrap_not_worktree_error(error, "update",
3648 worktree_path);
3649 goto done;
3652 error = check_rebase_or_histedit_in_progress(worktree);
3653 if (error)
3654 goto done;
3656 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
3657 NULL, pack_fds);
3658 if (error != NULL)
3659 goto done;
3661 error = apply_unveil(got_repo_get_path(repo), 0,
3662 got_worktree_get_root_path(worktree));
3663 if (error)
3664 goto done;
3666 error = check_merge_in_progress(worktree, repo);
3667 if (error)
3668 goto done;
3670 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
3671 if (error)
3672 goto done;
3674 error = got_ref_open(&head_ref, repo, branch_name ? branch_name :
3675 got_worktree_get_head_ref_name(worktree), 0);
3676 if (error != NULL)
3677 goto done;
3678 if (commit_id_str == NULL) {
3679 error = got_ref_resolve(&commit_id, repo, head_ref);
3680 if (error != NULL)
3681 goto done;
3682 error = got_object_id_str(&commit_id_str, commit_id);
3683 if (error != NULL)
3684 goto done;
3685 } else {
3686 struct got_reflist_head refs;
3687 char *keyword_idstr = NULL;
3689 TAILQ_INIT(&refs);
3691 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
3692 NULL);
3693 if (error)
3694 goto done;
3696 error = got_keyword_to_idstr(&keyword_idstr, commit_id_str,
3697 repo, worktree);
3698 if (error != NULL)
3699 goto done;
3700 if (keyword_idstr != NULL) {
3701 free(commit_id_str);
3702 commit_id_str = keyword_idstr;
3705 error = got_repo_match_object_id(&commit_id, NULL,
3706 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
3707 got_ref_list_free(&refs);
3708 free(commit_id_str);
3709 commit_id_str = NULL;
3710 if (error)
3711 goto done;
3712 error = got_object_id_str(&commit_id_str, commit_id);
3713 if (error)
3714 goto done;
3717 if (branch_name) {
3718 struct got_object_id *head_commit_id;
3719 TAILQ_FOREACH(pe, &paths, entry) {
3720 if (pe->path_len == 0)
3721 continue;
3722 error = got_error_msg(GOT_ERR_BAD_PATH,
3723 "switching between branches requires that "
3724 "the entire work tree gets updated");
3725 goto done;
3727 error = got_ref_resolve(&head_commit_id, repo, head_ref);
3728 if (error)
3729 goto done;
3730 error = check_linear_ancestry(commit_id, head_commit_id, 0,
3731 repo);
3732 free(head_commit_id);
3733 if (error != NULL)
3734 goto done;
3735 error = check_same_branch(commit_id, head_ref, repo);
3736 if (error)
3737 goto done;
3738 error = switch_head_ref(head_ref, commit_id, worktree, repo);
3739 if (error)
3740 goto done;
3741 } else {
3742 error = check_linear_ancestry(commit_id,
3743 got_worktree_get_base_commit_id(worktree), 0, repo);
3744 if (error != NULL) {
3745 if (error->code == GOT_ERR_ANCESTRY)
3746 error = got_error(GOT_ERR_BRANCH_MOVED);
3747 goto done;
3749 error = check_same_branch(commit_id, head_ref, repo);
3750 if (error)
3751 goto done;
3754 if (got_object_id_cmp(got_worktree_get_base_commit_id(worktree),
3755 commit_id) != 0) {
3756 error = got_worktree_set_base_commit_id(worktree, repo,
3757 commit_id);
3758 if (error)
3759 goto done;
3762 memset(&upa, 0, sizeof(upa));
3763 upa.verbosity = verbosity;
3764 error = got_worktree_checkout_files(worktree, &paths, repo,
3765 update_progress, &upa, check_cancelled, NULL);
3766 if (error != NULL)
3767 goto done;
3769 if (upa.did_something) {
3770 printf("Updated to %s: %s\n",
3771 got_worktree_get_head_ref_name(worktree), commit_id_str);
3772 } else
3773 printf("Already up-to-date\n");
3775 print_update_progress_stats(&upa);
3776 done:
3777 if (pack_fds) {
3778 const struct got_error *pack_err =
3779 got_repo_pack_fds_close(pack_fds);
3780 if (error == NULL)
3781 error = pack_err;
3783 if (repo) {
3784 close_err = got_repo_close(repo);
3785 if (error == NULL)
3786 error = close_err;
3788 if (worktree != NULL) {
3789 close_err = got_worktree_close(worktree);
3790 if (error == NULL)
3791 error = close_err;
3793 if (head_ref != NULL)
3794 got_ref_close(head_ref);
3795 free(worktree_path);
3796 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
3797 free(commit_id);
3798 free(commit_id_str);
3799 return error;
3802 static const struct got_error *
3803 diff_blobs(struct got_object_id *blob_id1, struct got_object_id *blob_id2,
3804 const char *path, int diff_context, int ignore_whitespace,
3805 int force_text_diff, struct got_diffstat_cb_arg *dsa,
3806 struct got_repository *repo, FILE *outfile)
3808 const struct got_error *err = NULL;
3809 struct got_blob_object *blob1 = NULL, *blob2 = NULL;
3810 FILE *f1 = NULL, *f2 = NULL;
3811 int fd1 = -1, fd2 = -1;
3813 fd1 = got_opentempfd();
3814 if (fd1 == -1)
3815 return got_error_from_errno("got_opentempfd");
3816 fd2 = got_opentempfd();
3817 if (fd2 == -1) {
3818 err = got_error_from_errno("got_opentempfd");
3819 goto done;
3822 if (blob_id1) {
3823 err = got_object_open_as_blob(&blob1, repo, blob_id1, 8192,
3824 fd1);
3825 if (err)
3826 goto done;
3829 err = got_object_open_as_blob(&blob2, repo, blob_id2, 8192, fd2);
3830 if (err)
3831 goto done;
3833 f1 = got_opentemp();
3834 if (f1 == NULL) {
3835 err = got_error_from_errno("got_opentemp");
3836 goto done;
3838 f2 = got_opentemp();
3839 if (f2 == NULL) {
3840 err = got_error_from_errno("got_opentemp");
3841 goto done;
3844 while (path[0] == '/')
3845 path++;
3846 err = got_diff_blob(NULL, NULL, blob1, blob2, f1, f2, path, path,
3847 GOT_DIFF_ALGORITHM_PATIENCE, diff_context, ignore_whitespace,
3848 force_text_diff, dsa, outfile);
3849 done:
3850 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
3851 err = got_error_from_errno("close");
3852 if (blob1)
3853 got_object_blob_close(blob1);
3854 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
3855 err = got_error_from_errno("close");
3856 if (blob2)
3857 got_object_blob_close(blob2);
3858 if (f1 && fclose(f1) == EOF && err == NULL)
3859 err = got_error_from_errno("fclose");
3860 if (f2 && fclose(f2) == EOF && err == NULL)
3861 err = got_error_from_errno("fclose");
3862 return err;
3865 static const struct got_error *
3866 diff_trees(struct got_object_id *tree_id1, struct got_object_id *tree_id2,
3867 const char *path, int diff_context, int ignore_whitespace,
3868 int force_text_diff, struct got_diffstat_cb_arg *dsa,
3869 struct got_repository *repo, FILE *outfile)
3871 const struct got_error *err = NULL;
3872 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
3873 struct got_diff_blob_output_unidiff_arg arg;
3874 FILE *f1 = NULL, *f2 = NULL;
3875 int fd1 = -1, fd2 = -1;
3877 if (tree_id1) {
3878 err = got_object_open_as_tree(&tree1, repo, tree_id1);
3879 if (err)
3880 goto done;
3881 fd1 = got_opentempfd();
3882 if (fd1 == -1) {
3883 err = got_error_from_errno("got_opentempfd");
3884 goto done;
3888 err = got_object_open_as_tree(&tree2, repo, tree_id2);
3889 if (err)
3890 goto done;
3892 f1 = got_opentemp();
3893 if (f1 == NULL) {
3894 err = got_error_from_errno("got_opentemp");
3895 goto done;
3898 f2 = got_opentemp();
3899 if (f2 == NULL) {
3900 err = got_error_from_errno("got_opentemp");
3901 goto done;
3903 fd2 = got_opentempfd();
3904 if (fd2 == -1) {
3905 err = got_error_from_errno("got_opentempfd");
3906 goto done;
3908 arg.diff_context = diff_context;
3909 arg.ignore_whitespace = ignore_whitespace;
3910 arg.force_text_diff = force_text_diff;
3911 arg.diffstat = dsa;
3912 arg.diff_algo = GOT_DIFF_ALGORITHM_PATIENCE;
3913 arg.outfile = outfile;
3914 arg.lines = NULL;
3915 arg.nlines = 0;
3916 while (path[0] == '/')
3917 path++;
3918 err = got_diff_tree(tree1, tree2, f1, f2, fd1, fd2, path, path, repo,
3919 got_diff_blob_output_unidiff, &arg, 1);
3920 done:
3921 if (tree1)
3922 got_object_tree_close(tree1);
3923 if (tree2)
3924 got_object_tree_close(tree2);
3925 if (f1 && fclose(f1) == EOF && err == NULL)
3926 err = got_error_from_errno("fclose");
3927 if (f2 && fclose(f2) == EOF && err == NULL)
3928 err = got_error_from_errno("fclose");
3929 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
3930 err = got_error_from_errno("close");
3931 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
3932 err = got_error_from_errno("close");
3933 return err;
3936 static const struct got_error *
3937 get_changed_paths(struct got_pathlist_head *paths,
3938 struct got_commit_object *commit, struct got_repository *repo,
3939 struct got_diffstat_cb_arg *dsa)
3941 const struct got_error *err = NULL;
3942 struct got_object_id *tree_id1 = NULL, *tree_id2 = NULL;
3943 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
3944 struct got_object_qid *qid;
3945 got_diff_blob_cb cb = got_diff_tree_collect_changed_paths;
3946 FILE *f1 = NULL, *f2 = NULL;
3947 int fd1 = -1, fd2 = -1;
3949 if (dsa) {
3950 cb = got_diff_tree_compute_diffstat;
3952 f1 = got_opentemp();
3953 if (f1 == NULL) {
3954 err = got_error_from_errno("got_opentemp");
3955 goto done;
3957 f2 = got_opentemp();
3958 if (f2 == NULL) {
3959 err = got_error_from_errno("got_opentemp");
3960 goto done;
3962 fd1 = got_opentempfd();
3963 if (fd1 == -1) {
3964 err = got_error_from_errno("got_opentempfd");
3965 goto done;
3967 fd2 = got_opentempfd();
3968 if (fd2 == -1) {
3969 err = got_error_from_errno("got_opentempfd");
3970 goto done;
3974 qid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
3975 if (qid != NULL) {
3976 struct got_commit_object *pcommit;
3977 err = got_object_open_as_commit(&pcommit, repo,
3978 &qid->id);
3979 if (err)
3980 return err;
3982 tree_id1 = got_object_id_dup(
3983 got_object_commit_get_tree_id(pcommit));
3984 if (tree_id1 == NULL) {
3985 got_object_commit_close(pcommit);
3986 return got_error_from_errno("got_object_id_dup");
3988 got_object_commit_close(pcommit);
3992 if (tree_id1) {
3993 err = got_object_open_as_tree(&tree1, repo, tree_id1);
3994 if (err)
3995 goto done;
3998 tree_id2 = got_object_commit_get_tree_id(commit);
3999 err = got_object_open_as_tree(&tree2, repo, tree_id2);
4000 if (err)
4001 goto done;
4003 err = got_diff_tree(tree1, tree2, f1, f2, fd1, fd2, "", "", repo,
4004 cb, dsa ? (void *)dsa : paths, dsa ? 1 : 0);
4005 done:
4006 if (tree1)
4007 got_object_tree_close(tree1);
4008 if (tree2)
4009 got_object_tree_close(tree2);
4010 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
4011 err = got_error_from_errno("close");
4012 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
4013 err = got_error_from_errno("close");
4014 if (f1 && fclose(f1) == EOF && err == NULL)
4015 err = got_error_from_errno("fclose");
4016 if (f2 && fclose(f2) == EOF && err == NULL)
4017 err = got_error_from_errno("fclose");
4018 free(tree_id1);
4019 return err;
4022 static const struct got_error *
4023 print_patch(struct got_commit_object *commit, struct got_object_id *id,
4024 const char *path, int diff_context, struct got_diffstat_cb_arg *dsa,
4025 struct got_repository *repo, FILE *outfile)
4027 const struct got_error *err = NULL;
4028 struct got_commit_object *pcommit = NULL;
4029 char *id_str1 = NULL, *id_str2 = NULL;
4030 struct got_object_id *obj_id1 = NULL, *obj_id2 = NULL;
4031 struct got_object_qid *qid;
4033 qid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
4034 if (qid != NULL) {
4035 err = got_object_open_as_commit(&pcommit, repo,
4036 &qid->id);
4037 if (err)
4038 return err;
4039 err = got_object_id_str(&id_str1, &qid->id);
4040 if (err)
4041 goto done;
4044 err = got_object_id_str(&id_str2, id);
4045 if (err)
4046 goto done;
4048 if (path && path[0] != '\0') {
4049 int obj_type;
4050 err = got_object_id_by_path(&obj_id2, repo, commit, path);
4051 if (err)
4052 goto done;
4053 if (pcommit) {
4054 err = got_object_id_by_path(&obj_id1, repo,
4055 pcommit, path);
4056 if (err) {
4057 if (err->code != GOT_ERR_NO_TREE_ENTRY) {
4058 free(obj_id2);
4059 goto done;
4063 err = got_object_get_type(&obj_type, repo, obj_id2);
4064 if (err) {
4065 free(obj_id2);
4066 goto done;
4068 fprintf(outfile,
4069 "diff %s %s\n", id_str1 ? id_str1 : "/dev/null", id_str2);
4070 fprintf(outfile, "commit - %s\n",
4071 id_str1 ? id_str1 : "/dev/null");
4072 fprintf(outfile, "commit + %s\n", id_str2);
4073 switch (obj_type) {
4074 case GOT_OBJ_TYPE_BLOB:
4075 err = diff_blobs(obj_id1, obj_id2, path, diff_context,
4076 0, 0, dsa, repo, outfile);
4077 break;
4078 case GOT_OBJ_TYPE_TREE:
4079 err = diff_trees(obj_id1, obj_id2, path, diff_context,
4080 0, 0, dsa, repo, outfile);
4081 break;
4082 default:
4083 err = got_error(GOT_ERR_OBJ_TYPE);
4084 break;
4086 free(obj_id1);
4087 free(obj_id2);
4088 } else {
4089 obj_id2 = got_object_commit_get_tree_id(commit);
4090 if (pcommit)
4091 obj_id1 = got_object_commit_get_tree_id(pcommit);
4092 fprintf(outfile,
4093 "diff %s %s\n", id_str1 ? id_str1 : "/dev/null", id_str2);
4094 fprintf(outfile, "commit - %s\n",
4095 id_str1 ? id_str1 : "/dev/null");
4096 fprintf(outfile, "commit + %s\n", id_str2);
4097 err = diff_trees(obj_id1, obj_id2, "", diff_context, 0, 0,
4098 dsa, repo, outfile);
4100 done:
4101 free(id_str1);
4102 free(id_str2);
4103 if (pcommit)
4104 got_object_commit_close(pcommit);
4105 return err;
4108 static char *
4109 get_datestr(time_t *time, char *datebuf)
4111 struct tm mytm, *tm;
4112 char *p, *s;
4114 tm = gmtime_r(time, &mytm);
4115 if (tm == NULL)
4116 return NULL;
4117 s = asctime_r(tm, datebuf);
4118 if (s == NULL)
4119 return NULL;
4120 p = strchr(s, '\n');
4121 if (p)
4122 *p = '\0';
4123 return s;
4126 static const struct got_error *
4127 match_commit(int *have_match, struct got_object_id *id,
4128 struct got_commit_object *commit, regex_t *regex)
4130 const struct got_error *err = NULL;
4131 regmatch_t regmatch;
4132 char *id_str = NULL, *logmsg = NULL;
4134 *have_match = 0;
4136 err = got_object_id_str(&id_str, id);
4137 if (err)
4138 return err;
4140 err = got_object_commit_get_logmsg(&logmsg, commit);
4141 if (err)
4142 goto done;
4144 if (regexec(regex, got_object_commit_get_author(commit), 1,
4145 &regmatch, 0) == 0 ||
4146 regexec(regex, got_object_commit_get_committer(commit), 1,
4147 &regmatch, 0) == 0 ||
4148 regexec(regex, id_str, 1, &regmatch, 0) == 0 ||
4149 regexec(regex, logmsg, 1, &regmatch, 0) == 0)
4150 *have_match = 1;
4151 done:
4152 free(id_str);
4153 free(logmsg);
4154 return err;
4157 static void
4158 match_changed_paths(int *have_match, struct got_pathlist_head *changed_paths,
4159 regex_t *regex)
4161 regmatch_t regmatch;
4162 struct got_pathlist_entry *pe;
4164 *have_match = 0;
4166 TAILQ_FOREACH(pe, changed_paths, entry) {
4167 if (regexec(regex, pe->path, 1, &regmatch, 0) == 0) {
4168 *have_match = 1;
4169 break;
4174 static const struct got_error *
4175 match_patch(int *have_match, struct got_commit_object *commit,
4176 struct got_object_id *id, const char *path, int diff_context,
4177 struct got_repository *repo, regex_t *regex, FILE *f)
4179 const struct got_error *err = NULL;
4180 char *line = NULL;
4181 size_t linesize = 0;
4182 regmatch_t regmatch;
4184 *have_match = 0;
4186 err = got_opentemp_truncate(f);
4187 if (err)
4188 return err;
4190 err = print_patch(commit, id, path, diff_context, NULL, repo, f);
4191 if (err)
4192 goto done;
4194 if (fseeko(f, 0L, SEEK_SET) == -1) {
4195 err = got_error_from_errno("fseeko");
4196 goto done;
4199 while (getline(&line, &linesize, f) != -1) {
4200 if (regexec(regex, line, 1, &regmatch, 0) == 0) {
4201 *have_match = 1;
4202 break;
4205 done:
4206 free(line);
4207 return err;
4210 #define GOT_COMMIT_SEP_STR "-----------------------------------------------\n"
4212 static const struct got_error*
4213 build_refs_str(char **refs_str, struct got_reflist_head *refs,
4214 struct got_object_id *id, struct got_repository *repo,
4215 int local_only)
4217 static const struct got_error *err = NULL;
4218 struct got_reflist_entry *re;
4219 char *s;
4220 const char *name;
4222 *refs_str = NULL;
4224 TAILQ_FOREACH(re, refs, entry) {
4225 struct got_tag_object *tag = NULL;
4226 struct got_object_id *ref_id;
4227 int cmp;
4229 name = got_ref_get_name(re->ref);
4230 if (strcmp(name, GOT_REF_HEAD) == 0)
4231 continue;
4232 if (strncmp(name, "refs/", 5) == 0)
4233 name += 5;
4234 if (strncmp(name, "got/", 4) == 0)
4235 continue;
4236 if (strncmp(name, "heads/", 6) == 0)
4237 name += 6;
4238 if (strncmp(name, "remotes/", 8) == 0) {
4239 if (local_only)
4240 continue;
4241 name += 8;
4242 s = strstr(name, "/" GOT_REF_HEAD);
4243 if (s != NULL && strcmp(s, "/" GOT_REF_HEAD) == 0)
4244 continue;
4246 err = got_ref_resolve(&ref_id, repo, re->ref);
4247 if (err)
4248 break;
4249 if (strncmp(name, "tags/", 5) == 0) {
4250 err = got_object_open_as_tag(&tag, repo, ref_id);
4251 if (err) {
4252 if (err->code != GOT_ERR_OBJ_TYPE) {
4253 free(ref_id);
4254 break;
4256 /* Ref points at something other than a tag. */
4257 err = NULL;
4258 tag = NULL;
4261 cmp = got_object_id_cmp(tag ?
4262 got_object_tag_get_object_id(tag) : ref_id, id);
4263 free(ref_id);
4264 if (tag)
4265 got_object_tag_close(tag);
4266 if (cmp != 0)
4267 continue;
4268 s = *refs_str;
4269 if (asprintf(refs_str, "%s%s%s", s ? s : "",
4270 s ? ", " : "", name) == -1) {
4271 err = got_error_from_errno("asprintf");
4272 free(s);
4273 *refs_str = NULL;
4274 break;
4276 free(s);
4279 return err;
4282 static const struct got_error *
4283 print_commit_oneline(struct got_commit_object *commit, struct got_object_id *id,
4284 struct got_repository *repo, struct got_reflist_object_id_map *refs_idmap)
4286 const struct got_error *err = NULL;
4287 char *ref_str = NULL, *id_str = NULL, *logmsg0 = NULL;
4288 char *comma, *s, *nl;
4289 struct got_reflist_head *refs;
4290 char datebuf[12]; /* YYYY-MM-DD + SPACE + NUL */
4291 struct tm tm;
4292 time_t committer_time;
4294 refs = got_reflist_object_id_map_lookup(refs_idmap, id);
4295 if (refs) {
4296 err = build_refs_str(&ref_str, refs, id, repo, 1);
4297 if (err)
4298 return err;
4300 /* Display the first matching ref only. */
4301 if (ref_str && (comma = strchr(ref_str, ',')) != NULL)
4302 *comma = '\0';
4305 if (ref_str == NULL) {
4306 err = got_object_id_str(&id_str, id);
4307 if (err)
4308 return err;
4311 committer_time = got_object_commit_get_committer_time(commit);
4312 if (gmtime_r(&committer_time, &tm) == NULL) {
4313 err = got_error_from_errno("gmtime_r");
4314 goto done;
4316 if (strftime(datebuf, sizeof(datebuf), "%F ", &tm) == 0) {
4317 err = got_error(GOT_ERR_NO_SPACE);
4318 goto done;
4321 err = got_object_commit_get_logmsg(&logmsg0, commit);
4322 if (err)
4323 goto done;
4325 s = logmsg0;
4326 while (isspace((unsigned char)s[0]))
4327 s++;
4329 nl = strchr(s, '\n');
4330 if (nl) {
4331 *nl = '\0';
4334 if (ref_str)
4335 printf("%s%-7s %s\n", datebuf, ref_str, s);
4336 else
4337 printf("%s%.7s %s\n", datebuf, id_str, s);
4339 if (fflush(stdout) != 0 && err == NULL)
4340 err = got_error_from_errno("fflush");
4341 done:
4342 free(id_str);
4343 free(ref_str);
4344 free(logmsg0);
4345 return err;
4348 static const struct got_error *
4349 print_diffstat(struct got_diffstat_cb_arg *dsa, const char *header)
4351 struct got_pathlist_entry *pe;
4353 if (header != NULL)
4354 printf("%s\n", header);
4356 TAILQ_FOREACH(pe, dsa->paths, entry) {
4357 struct got_diff_changed_path *cp = pe->data;
4358 int pad = dsa->max_path_len - pe->path_len + 1;
4360 printf(" %c %s%*c | %*d+ %*d-\n", cp->status, pe->path, pad,
4361 ' ', dsa->add_cols + 1, cp->add, dsa->rm_cols + 1, cp->rm);
4363 printf("\n%d file%s changed, %d insertion%s(+), %d deletion%s(-)\n\n",
4364 dsa->nfiles, dsa->nfiles > 1 ? "s" : "", dsa->ins,
4365 dsa->ins != 1 ? "s" : "", dsa->del, dsa->del != 1 ? "s" : "");
4367 if (fflush(stdout) != 0)
4368 return got_error_from_errno("fflush");
4370 return NULL;
4373 static const struct got_error *
4374 printfile(FILE *f)
4376 char buf[8192];
4377 size_t r;
4379 if (fseeko(f, 0L, SEEK_SET) == -1)
4380 return got_error_from_errno("fseek");
4382 for (;;) {
4383 r = fread(buf, 1, sizeof(buf), f);
4384 if (r == 0) {
4385 if (ferror(f))
4386 return got_error_from_errno("fread");
4387 if (feof(f))
4388 break;
4390 if (fwrite(buf, 1, r, stdout) != r)
4391 return got_ferror(stdout, GOT_ERR_IO);
4394 return NULL;
4397 static const struct got_error *
4398 print_commit(struct got_commit_object *commit, struct got_object_id *id,
4399 struct got_repository *repo, const char *path,
4400 struct got_pathlist_head *changed_paths,
4401 struct got_diffstat_cb_arg *diffstat, int show_patch, int diff_context,
4402 struct got_reflist_object_id_map *refs_idmap, const char *custom_refs_str,
4403 const char *prefix)
4405 const struct got_error *err = NULL;
4406 FILE *f = NULL;
4407 char *id_str, *datestr, *logmsg0, *logmsg, *line;
4408 char datebuf[26];
4409 time_t committer_time;
4410 const char *author, *committer;
4411 char *refs_str = NULL;
4413 err = got_object_id_str(&id_str, id);
4414 if (err)
4415 return err;
4417 if (custom_refs_str == NULL) {
4418 struct got_reflist_head *refs;
4419 refs = got_reflist_object_id_map_lookup(refs_idmap, id);
4420 if (refs) {
4421 err = build_refs_str(&refs_str, refs, id, repo, 0);
4422 if (err)
4423 goto done;
4427 printf(GOT_COMMIT_SEP_STR);
4428 if (custom_refs_str)
4429 printf("%s %s (%s)\n", prefix ? prefix : "commit", id_str,
4430 custom_refs_str);
4431 else
4432 printf("%s %s%s%s%s\n", prefix ? prefix : "commit", id_str,
4433 refs_str ? " (" : "", refs_str ? refs_str : "",
4434 refs_str ? ")" : "");
4435 free(id_str);
4436 id_str = NULL;
4437 free(refs_str);
4438 refs_str = NULL;
4439 printf("from: %s\n", got_object_commit_get_author(commit));
4440 author = got_object_commit_get_author(commit);
4441 committer = got_object_commit_get_committer(commit);
4442 if (strcmp(author, committer) != 0)
4443 printf("via: %s\n", committer);
4444 committer_time = got_object_commit_get_committer_time(commit);
4445 datestr = get_datestr(&committer_time, datebuf);
4446 if (datestr)
4447 printf("date: %s UTC\n", datestr);
4448 if (got_object_commit_get_nparents(commit) > 1) {
4449 const struct got_object_id_queue *parent_ids;
4450 struct got_object_qid *qid;
4451 int n = 1;
4452 parent_ids = got_object_commit_get_parent_ids(commit);
4453 STAILQ_FOREACH(qid, parent_ids, entry) {
4454 err = got_object_id_str(&id_str, &qid->id);
4455 if (err)
4456 goto done;
4457 printf("parent %d: %s\n", n++, id_str);
4458 free(id_str);
4459 id_str = NULL;
4463 err = got_object_commit_get_logmsg(&logmsg0, commit);
4464 if (err)
4465 goto done;
4467 logmsg = logmsg0;
4468 do {
4469 line = strsep(&logmsg, "\n");
4470 if (line)
4471 printf(" %s\n", line);
4472 } while (line);
4473 free(logmsg0);
4475 if (changed_paths && diffstat == NULL) {
4476 struct got_pathlist_entry *pe;
4478 TAILQ_FOREACH(pe, changed_paths, entry) {
4479 struct got_diff_changed_path *cp = pe->data;
4481 printf(" %c %s\n", cp->status, pe->path);
4483 printf("\n");
4485 if (show_patch) {
4486 if (diffstat) {
4487 f = got_opentemp();
4488 if (f == NULL) {
4489 err = got_error_from_errno("got_opentemp");
4490 goto done;
4494 err = print_patch(commit, id, path, diff_context, diffstat,
4495 repo, diffstat == NULL ? stdout : f);
4496 if (err)
4497 goto done;
4499 if (diffstat) {
4500 err = print_diffstat(diffstat, NULL);
4501 if (err)
4502 goto done;
4503 if (show_patch) {
4504 err = printfile(f);
4505 if (err)
4506 goto done;
4509 if (show_patch)
4510 printf("\n");
4512 if (fflush(stdout) != 0 && err == NULL)
4513 err = got_error_from_errno("fflush");
4514 done:
4515 if (f && fclose(f) == EOF && err == NULL)
4516 err = got_error_from_errno("fclose");
4517 free(id_str);
4518 free(refs_str);
4519 return err;
4522 static const struct got_error *
4523 print_commits(struct got_object_id *root_id, struct got_object_id *end_id,
4524 struct got_repository *repo, const char *path, int show_changed_paths,
4525 int show_diffstat, int show_patch, const char *search_pattern,
4526 int diff_context, int limit, int log_branches, int reverse_display_order,
4527 struct got_reflist_object_id_map *refs_idmap, int one_line, int toposort,
4528 FILE *tmpfile)
4530 const struct got_error *err;
4531 struct got_commit_graph *graph;
4532 regex_t regex;
4533 int have_match;
4534 struct got_object_id_queue reversed_commits;
4535 struct got_object_qid *qid;
4536 struct got_commit_object *commit;
4537 struct got_pathlist_head changed_paths;
4539 STAILQ_INIT(&reversed_commits);
4540 TAILQ_INIT(&changed_paths);
4542 if (search_pattern && regcomp(&regex, search_pattern,
4543 REG_EXTENDED | REG_NOSUB | REG_NEWLINE))
4544 return got_error_msg(GOT_ERR_REGEX, search_pattern);
4546 err = got_commit_graph_open(&graph, path, !log_branches);
4547 if (err)
4548 return err;
4549 if (log_branches && toposort) {
4550 err = got_commit_graph_toposort(graph, root_id, repo,
4551 check_cancelled, NULL);
4552 } else {
4553 err = got_commit_graph_bfsort(graph, root_id, repo,
4554 check_cancelled, NULL);
4556 if (err)
4557 goto done;
4558 for (;;) {
4559 struct got_object_id id;
4560 struct got_diffstat_cb_arg dsa = { 0, 0, 0, 0, 0, 0,
4561 &changed_paths, 0, 0, GOT_DIFF_ALGORITHM_PATIENCE };
4563 if (sigint_received || sigpipe_received)
4564 break;
4566 err = got_commit_graph_iter_next(&id, graph, repo,
4567 check_cancelled, NULL);
4568 if (err) {
4569 if (err->code == GOT_ERR_ITER_COMPLETED)
4570 err = NULL;
4571 break;
4574 err = got_object_open_as_commit(&commit, repo, &id);
4575 if (err)
4576 break;
4578 if (((show_changed_paths && !show_diffstat) ||
4579 (show_diffstat && !show_patch))
4580 && !reverse_display_order) {
4581 err = get_changed_paths(&changed_paths, commit, repo,
4582 show_diffstat ? &dsa : NULL);
4583 if (err)
4584 break;
4587 if (search_pattern) {
4588 err = match_commit(&have_match, &id, commit, &regex);
4589 if (err) {
4590 got_object_commit_close(commit);
4591 break;
4593 if (have_match == 0 && show_changed_paths)
4594 match_changed_paths(&have_match,
4595 &changed_paths, &regex);
4596 if (have_match == 0 && show_patch) {
4597 err = match_patch(&have_match, commit, &id,
4598 path, diff_context, repo, &regex, tmpfile);
4599 if (err)
4600 break;
4602 if (have_match == 0) {
4603 got_object_commit_close(commit);
4604 got_pathlist_free(&changed_paths,
4605 GOT_PATHLIST_FREE_ALL);
4606 continue;
4610 if (reverse_display_order) {
4611 err = got_object_qid_alloc(&qid, &id);
4612 if (err)
4613 break;
4614 STAILQ_INSERT_HEAD(&reversed_commits, qid, entry);
4615 got_object_commit_close(commit);
4616 } else {
4617 if (one_line)
4618 err = print_commit_oneline(commit, &id,
4619 repo, refs_idmap);
4620 else
4621 err = print_commit(commit, &id, repo, path,
4622 (show_changed_paths || show_diffstat) ?
4623 &changed_paths : NULL,
4624 show_diffstat ? &dsa : NULL, show_patch,
4625 diff_context, refs_idmap, NULL, NULL);
4626 got_object_commit_close(commit);
4627 if (err)
4628 break;
4630 if ((limit && --limit == 0) ||
4631 (end_id && got_object_id_cmp(&id, end_id) == 0))
4632 break;
4634 got_pathlist_free(&changed_paths, GOT_PATHLIST_FREE_ALL);
4636 if (reverse_display_order) {
4637 STAILQ_FOREACH(qid, &reversed_commits, entry) {
4638 struct got_diffstat_cb_arg dsa = { 0, 0, 0, 0, 0, 0,
4639 &changed_paths, 0, 0, GOT_DIFF_ALGORITHM_PATIENCE };
4641 err = got_object_open_as_commit(&commit, repo,
4642 &qid->id);
4643 if (err)
4644 break;
4645 if ((show_changed_paths && !show_diffstat) ||
4646 (show_diffstat && !show_patch)) {
4647 err = get_changed_paths(&changed_paths, commit,
4648 repo, show_diffstat ? &dsa : NULL);
4649 if (err)
4650 break;
4652 if (one_line)
4653 err = print_commit_oneline(commit, &qid->id,
4654 repo, refs_idmap);
4655 else
4656 err = print_commit(commit, &qid->id, repo, path,
4657 (show_changed_paths || show_diffstat) ?
4658 &changed_paths : NULL,
4659 show_diffstat ? &dsa : NULL, show_patch,
4660 diff_context, refs_idmap, NULL, NULL);
4661 got_object_commit_close(commit);
4662 if (err)
4663 break;
4664 got_pathlist_free(&changed_paths, GOT_PATHLIST_FREE_ALL);
4667 done:
4668 while (!STAILQ_EMPTY(&reversed_commits)) {
4669 qid = STAILQ_FIRST(&reversed_commits);
4670 STAILQ_REMOVE_HEAD(&reversed_commits, entry);
4671 got_object_qid_free(qid);
4673 got_pathlist_free(&changed_paths, GOT_PATHLIST_FREE_ALL);
4674 if (search_pattern)
4675 regfree(&regex);
4676 got_commit_graph_close(graph);
4677 return err;
4680 __dead static void
4681 usage_log(void)
4683 fprintf(stderr, "usage: %s log [-bdPpRst] [-C number] [-c commit] "
4684 "[-l N] [-r repository-path] [-S search-pattern] [-x commit] "
4685 "[path]\n", getprogname());
4686 exit(1);
4689 static int
4690 get_default_log_limit(void)
4692 const char *got_default_log_limit;
4693 long long n;
4694 const char *errstr;
4696 got_default_log_limit = getenv("GOT_LOG_DEFAULT_LIMIT");
4697 if (got_default_log_limit == NULL)
4698 return 0;
4699 n = strtonum(got_default_log_limit, 0, INT_MAX, &errstr);
4700 if (errstr != NULL)
4701 return 0;
4702 return n;
4705 static const struct got_error *
4706 cmd_log(int argc, char *argv[])
4708 const struct got_error *error;
4709 struct got_repository *repo = NULL;
4710 struct got_worktree *worktree = NULL;
4711 struct got_object_id *start_id = NULL, *end_id = NULL;
4712 char *repo_path = NULL, *path = NULL, *cwd = NULL, *in_repo_path = NULL;
4713 char *keyword_idstr = NULL;
4714 const char *start_commit = NULL, *end_commit = NULL;
4715 const char *search_pattern = NULL;
4716 int diff_context = -1, ch;
4717 int show_changed_paths = 0, show_patch = 0, limit = 0, log_branches = 0;
4718 int show_diffstat = 0, reverse_display_order = 0, one_line = 0;
4719 int toposort = 0;
4720 const char *errstr;
4721 struct got_reflist_head refs;
4722 struct got_reflist_object_id_map *refs_idmap = NULL;
4723 FILE *tmpfile = NULL;
4724 int *pack_fds = NULL;
4726 TAILQ_INIT(&refs);
4728 #ifndef PROFILE
4729 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
4730 NULL)
4731 == -1)
4732 err(1, "pledge");
4733 #endif
4735 limit = get_default_log_limit();
4737 while ((ch = getopt(argc, argv, "bC:c:dl:PpRr:S:stx:")) != -1) {
4738 switch (ch) {
4739 case 'b':
4740 log_branches = 1;
4741 break;
4742 case 'C':
4743 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
4744 &errstr);
4745 if (errstr != NULL)
4746 errx(1, "number of context lines is %s: %s",
4747 errstr, optarg);
4748 break;
4749 case 'c':
4750 start_commit = optarg;
4751 break;
4752 case 'd':
4753 show_diffstat = 1;
4754 break;
4755 case 'l':
4756 limit = strtonum(optarg, 0, INT_MAX, &errstr);
4757 if (errstr != NULL)
4758 errx(1, "number of commits is %s: %s",
4759 errstr, optarg);
4760 break;
4761 case 'P':
4762 show_changed_paths = 1;
4763 break;
4764 case 'p':
4765 show_patch = 1;
4766 break;
4767 case 'R':
4768 reverse_display_order = 1;
4769 break;
4770 case 'r':
4771 repo_path = realpath(optarg, NULL);
4772 if (repo_path == NULL)
4773 return got_error_from_errno2("realpath",
4774 optarg);
4775 got_path_strip_trailing_slashes(repo_path);
4776 break;
4777 case 'S':
4778 search_pattern = optarg;
4779 break;
4780 case 's':
4781 one_line = 1;
4782 break;
4783 case 't':
4784 toposort = 1;
4785 break;
4786 case 'x':
4787 end_commit = optarg;
4788 break;
4789 default:
4790 usage_log();
4791 /* NOTREACHED */
4795 argc -= optind;
4796 argv += optind;
4798 if (diff_context == -1)
4799 diff_context = 3;
4800 else if (!show_patch)
4801 errx(1, "-C requires -p");
4803 if (one_line && (show_patch || show_changed_paths || show_diffstat))
4804 errx(1, "cannot use -s with -d, -p or -P");
4806 cwd = getcwd(NULL, 0);
4807 if (cwd == NULL) {
4808 error = got_error_from_errno("getcwd");
4809 goto done;
4812 error = got_repo_pack_fds_open(&pack_fds);
4813 if (error != NULL)
4814 goto done;
4816 if (repo_path == NULL) {
4817 error = got_worktree_open(&worktree, cwd,
4818 GOT_WORKTREE_GOT_DIR);
4819 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4820 goto done;
4821 error = NULL;
4824 if (argc == 1) {
4825 if (worktree) {
4826 error = got_worktree_resolve_path(&path, worktree,
4827 argv[0]);
4828 if (error)
4829 goto done;
4830 } else {
4831 path = strdup(argv[0]);
4832 if (path == NULL) {
4833 error = got_error_from_errno("strdup");
4834 goto done;
4837 } else if (argc != 0)
4838 usage_log();
4840 if (repo_path == NULL) {
4841 repo_path = worktree ?
4842 strdup(got_worktree_get_repo_path(worktree)) : strdup(cwd);
4844 if (repo_path == NULL) {
4845 error = got_error_from_errno("strdup");
4846 goto done;
4849 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
4850 if (error != NULL)
4851 goto done;
4853 error = apply_unveil(got_repo_get_path(repo), 1,
4854 worktree ? got_worktree_get_root_path(worktree) : NULL);
4855 if (error)
4856 goto done;
4858 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
4859 if (error)
4860 goto done;
4862 error = got_reflist_object_id_map_create(&refs_idmap, &refs, repo);
4863 if (error)
4864 goto done;
4866 if (start_commit == NULL) {
4867 struct got_reference *head_ref;
4868 struct got_commit_object *commit = NULL;
4869 error = got_ref_open(&head_ref, repo,
4870 worktree ? got_worktree_get_head_ref_name(worktree)
4871 : GOT_REF_HEAD, 0);
4872 if (error != NULL)
4873 goto done;
4874 error = got_ref_resolve(&start_id, repo, head_ref);
4875 got_ref_close(head_ref);
4876 if (error != NULL)
4877 goto done;
4878 error = got_object_open_as_commit(&commit, repo,
4879 start_id);
4880 if (error != NULL)
4881 goto done;
4882 got_object_commit_close(commit);
4883 } else {
4884 error = got_keyword_to_idstr(&keyword_idstr, start_commit,
4885 repo, worktree);
4886 if (error != NULL)
4887 goto done;
4888 if (keyword_idstr != NULL)
4889 start_commit = keyword_idstr;
4891 error = got_repo_match_object_id(&start_id, NULL,
4892 start_commit, GOT_OBJ_TYPE_COMMIT, &refs, repo);
4893 if (error != NULL)
4894 goto done;
4896 if (end_commit != NULL) {
4897 error = got_keyword_to_idstr(&keyword_idstr, end_commit,
4898 repo, worktree);
4899 if (error != NULL)
4900 goto done;
4901 if (keyword_idstr != NULL)
4902 end_commit = keyword_idstr;
4904 error = got_repo_match_object_id(&end_id, NULL,
4905 end_commit, GOT_OBJ_TYPE_COMMIT, &refs, repo);
4906 if (error != NULL)
4907 goto done;
4910 if (worktree) {
4912 * If a path was specified on the command line it was resolved
4913 * to a path in the work tree above. Prepend the work tree's
4914 * path prefix to obtain the corresponding in-repository path.
4916 if (path) {
4917 const char *prefix;
4918 prefix = got_worktree_get_path_prefix(worktree);
4919 if (asprintf(&in_repo_path, "%s%s%s", prefix,
4920 (path[0] != '\0') ? "/" : "", path) == -1) {
4921 error = got_error_from_errno("asprintf");
4922 goto done;
4925 } else
4926 error = got_repo_map_path(&in_repo_path, repo,
4927 path ? path : "");
4928 if (error != NULL)
4929 goto done;
4930 if (in_repo_path) {
4931 free(path);
4932 path = in_repo_path;
4935 if (worktree) {
4936 /* Release work tree lock. */
4937 got_worktree_close(worktree);
4938 worktree = NULL;
4941 if (search_pattern && show_patch) {
4942 tmpfile = got_opentemp();
4943 if (tmpfile == NULL) {
4944 error = got_error_from_errno("got_opentemp");
4945 goto done;
4949 error = print_commits(start_id, end_id, repo, path ? path : "",
4950 show_changed_paths, show_diffstat, show_patch, search_pattern,
4951 diff_context, limit, log_branches, reverse_display_order,
4952 refs_idmap, one_line, toposort, tmpfile);
4953 done:
4954 free(path);
4955 free(repo_path);
4956 free(cwd);
4957 free(start_id);
4958 free(end_id);
4959 free(keyword_idstr);
4960 if (worktree)
4961 got_worktree_close(worktree);
4962 if (repo) {
4963 const struct got_error *close_err = got_repo_close(repo);
4964 if (error == NULL)
4965 error = close_err;
4967 if (pack_fds) {
4968 const struct got_error *pack_err =
4969 got_repo_pack_fds_close(pack_fds);
4970 if (error == NULL)
4971 error = pack_err;
4973 if (refs_idmap)
4974 got_reflist_object_id_map_free(refs_idmap);
4975 if (tmpfile && fclose(tmpfile) == EOF && error == NULL)
4976 error = got_error_from_errno("fclose");
4977 got_ref_list_free(&refs);
4978 return error;
4981 __dead static void
4982 usage_diff(void)
4984 fprintf(stderr, "usage: %s diff [-adPsw] [-C number] [-c commit] "
4985 "[-r repository-path] [object1 object2 | path ...]\n",
4986 getprogname());
4987 exit(1);
4990 struct print_diff_arg {
4991 struct got_repository *repo;
4992 struct got_worktree *worktree;
4993 struct got_diffstat_cb_arg *diffstat;
4994 int diff_context;
4995 const char *id_str;
4996 int header_shown;
4997 int diff_staged;
4998 enum got_diff_algorithm diff_algo;
4999 int ignore_whitespace;
5000 int force_text_diff;
5001 FILE *f1;
5002 FILE *f2;
5003 FILE *outfile;
5007 * Create a file which contains the target path of a symlink so we can feed
5008 * it as content to the diff engine.
5010 static const struct got_error *
5011 get_symlink_target_file(int *fd, int dirfd, const char *de_name,
5012 const char *abspath)
5014 const struct got_error *err = NULL;
5015 char target_path[PATH_MAX];
5016 ssize_t target_len, outlen;
5018 *fd = -1;
5020 if (dirfd != -1) {
5021 target_len = readlinkat(dirfd, de_name, target_path, PATH_MAX);
5022 if (target_len == -1)
5023 return got_error_from_errno2("readlinkat", abspath);
5024 } else {
5025 target_len = readlink(abspath, target_path, PATH_MAX);
5026 if (target_len == -1)
5027 return got_error_from_errno2("readlink", abspath);
5030 *fd = got_opentempfd();
5031 if (*fd == -1)
5032 return got_error_from_errno("got_opentempfd");
5034 outlen = write(*fd, target_path, target_len);
5035 if (outlen == -1) {
5036 err = got_error_from_errno("got_opentempfd");
5037 goto done;
5040 if (lseek(*fd, 0, SEEK_SET) == -1) {
5041 err = got_error_from_errno2("lseek", abspath);
5042 goto done;
5044 done:
5045 if (err) {
5046 close(*fd);
5047 *fd = -1;
5049 return err;
5052 static const struct got_error *
5053 print_diff(void *arg, unsigned char status, unsigned char staged_status,
5054 const char *path, struct got_object_id *blob_id,
5055 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
5056 int dirfd, const char *de_name)
5058 struct print_diff_arg *a = arg;
5059 const struct got_error *err = NULL;
5060 struct got_blob_object *blob1 = NULL;
5061 int fd = -1, fd1 = -1, fd2 = -1;
5062 FILE *f2 = NULL;
5063 char *abspath = NULL, *label1 = NULL;
5064 struct stat sb;
5065 off_t size1 = 0;
5066 int f2_exists = 0;
5068 memset(&sb, 0, sizeof(sb));
5070 if (a->diff_staged) {
5071 if (staged_status != GOT_STATUS_MODIFY &&
5072 staged_status != GOT_STATUS_ADD &&
5073 staged_status != GOT_STATUS_DELETE)
5074 return NULL;
5075 } else {
5076 if (staged_status == GOT_STATUS_DELETE)
5077 return NULL;
5078 if (status == GOT_STATUS_NONEXISTENT)
5079 return got_error_set_errno(ENOENT, path);
5080 if (status != GOT_STATUS_MODIFY &&
5081 status != GOT_STATUS_ADD &&
5082 status != GOT_STATUS_DELETE &&
5083 status != GOT_STATUS_CONFLICT)
5084 return NULL;
5087 err = got_opentemp_truncate(a->f1);
5088 if (err)
5089 return got_error_from_errno("got_opentemp_truncate");
5090 err = got_opentemp_truncate(a->f2);
5091 if (err)
5092 return got_error_from_errno("got_opentemp_truncate");
5094 if (!a->header_shown) {
5095 if (fprintf(a->outfile, "diff %s%s\n",
5096 a->diff_staged ? "-s " : "",
5097 got_worktree_get_root_path(a->worktree)) < 0) {
5098 err = got_error_from_errno("fprintf");
5099 goto done;
5101 if (fprintf(a->outfile, "commit - %s\n", a->id_str) < 0) {
5102 err = got_error_from_errno("fprintf");
5103 goto done;
5105 if (fprintf(a->outfile, "path + %s%s\n",
5106 got_worktree_get_root_path(a->worktree),
5107 a->diff_staged ? " (staged changes)" : "") < 0) {
5108 err = got_error_from_errno("fprintf");
5109 goto done;
5111 a->header_shown = 1;
5114 if (a->diff_staged) {
5115 const char *label1 = NULL, *label2 = NULL;
5116 switch (staged_status) {
5117 case GOT_STATUS_MODIFY:
5118 label1 = path;
5119 label2 = path;
5120 break;
5121 case GOT_STATUS_ADD:
5122 label2 = path;
5123 break;
5124 case GOT_STATUS_DELETE:
5125 label1 = path;
5126 break;
5127 default:
5128 return got_error(GOT_ERR_FILE_STATUS);
5130 fd1 = got_opentempfd();
5131 if (fd1 == -1) {
5132 err = got_error_from_errno("got_opentempfd");
5133 goto done;
5135 fd2 = got_opentempfd();
5136 if (fd2 == -1) {
5137 err = got_error_from_errno("got_opentempfd");
5138 goto done;
5140 err = got_diff_objects_as_blobs(NULL, NULL, a->f1, a->f2,
5141 fd1, fd2, blob_id, staged_blob_id, label1, label2,
5142 a->diff_algo, a->diff_context, a->ignore_whitespace,
5143 a->force_text_diff, a->diffstat, a->repo, a->outfile);
5144 goto done;
5147 fd1 = got_opentempfd();
5148 if (fd1 == -1) {
5149 err = got_error_from_errno("got_opentempfd");
5150 goto done;
5153 if (staged_status == GOT_STATUS_ADD ||
5154 staged_status == GOT_STATUS_MODIFY) {
5155 char *id_str;
5156 err = got_object_open_as_blob(&blob1, a->repo, staged_blob_id,
5157 8192, fd1);
5158 if (err)
5159 goto done;
5160 err = got_object_id_str(&id_str, staged_blob_id);
5161 if (err)
5162 goto done;
5163 if (asprintf(&label1, "%s (staged)", id_str) == -1) {
5164 err = got_error_from_errno("asprintf");
5165 free(id_str);
5166 goto done;
5168 free(id_str);
5169 } else if (status != GOT_STATUS_ADD) {
5170 err = got_object_open_as_blob(&blob1, a->repo, blob_id, 8192,
5171 fd1);
5172 if (err)
5173 goto done;
5176 if (status != GOT_STATUS_DELETE) {
5177 if (asprintf(&abspath, "%s/%s",
5178 got_worktree_get_root_path(a->worktree), path) == -1) {
5179 err = got_error_from_errno("asprintf");
5180 goto done;
5183 if (dirfd != -1) {
5184 fd = openat(dirfd, de_name,
5185 O_RDONLY | O_NOFOLLOW | O_CLOEXEC);
5186 if (fd == -1) {
5187 if (!got_err_open_nofollow_on_symlink()) {
5188 err = got_error_from_errno2("openat",
5189 abspath);
5190 goto done;
5192 err = get_symlink_target_file(&fd, dirfd,
5193 de_name, abspath);
5194 if (err)
5195 goto done;
5197 } else {
5198 fd = open(abspath, O_RDONLY | O_NOFOLLOW | O_CLOEXEC);
5199 if (fd == -1) {
5200 if (!got_err_open_nofollow_on_symlink()) {
5201 err = got_error_from_errno2("open",
5202 abspath);
5203 goto done;
5205 err = get_symlink_target_file(&fd, dirfd,
5206 de_name, abspath);
5207 if (err)
5208 goto done;
5211 if (fstatat(fd, abspath, &sb, AT_SYMLINK_NOFOLLOW) == -1) {
5212 err = got_error_from_errno2("fstatat", abspath);
5213 goto done;
5215 f2 = fdopen(fd, "r");
5216 if (f2 == NULL) {
5217 err = got_error_from_errno2("fdopen", abspath);
5218 goto done;
5220 fd = -1;
5221 f2_exists = 1;
5224 if (blob1) {
5225 err = got_object_blob_dump_to_file(&size1, NULL, NULL,
5226 a->f1, blob1);
5227 if (err)
5228 goto done;
5231 err = got_diff_blob_file(blob1, a->f1, size1, label1, f2 ? f2 : a->f2,
5232 f2_exists, &sb, path, GOT_DIFF_ALGORITHM_PATIENCE, a->diff_context,
5233 a->ignore_whitespace, a->force_text_diff, a->diffstat, a->outfile);
5234 done:
5235 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
5236 err = got_error_from_errno("close");
5237 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
5238 err = got_error_from_errno("close");
5239 if (blob1)
5240 got_object_blob_close(blob1);
5241 if (fd != -1 && close(fd) == -1 && err == NULL)
5242 err = got_error_from_errno("close");
5243 if (f2 && fclose(f2) == EOF && err == NULL)
5244 err = got_error_from_errno("fclose");
5245 free(abspath);
5246 return err;
5249 static const struct got_error *
5250 cmd_diff(int argc, char *argv[])
5252 const struct got_error *error;
5253 struct got_repository *repo = NULL;
5254 struct got_worktree *worktree = NULL;
5255 char *cwd = NULL, *repo_path = NULL;
5256 const char *commit_args[2] = { NULL, NULL };
5257 int ncommit_args = 0;
5258 struct got_object_id *ids[2] = { NULL, NULL };
5259 char *labels[2] = { NULL, NULL };
5260 int type1 = GOT_OBJ_TYPE_ANY, type2 = GOT_OBJ_TYPE_ANY;
5261 int diff_context = 3, diff_staged = 0, ignore_whitespace = 0, ch, i;
5262 int force_text_diff = 0, force_path = 0, rflag = 0, show_diffstat = 0;
5263 const char *errstr;
5264 struct got_reflist_head refs;
5265 struct got_pathlist_head diffstat_paths, paths;
5266 FILE *f1 = NULL, *f2 = NULL, *outfile = NULL;
5267 int fd1 = -1, fd2 = -1;
5268 int *pack_fds = NULL;
5269 struct got_diffstat_cb_arg dsa;
5271 memset(&dsa, 0, sizeof(dsa));
5273 TAILQ_INIT(&refs);
5274 TAILQ_INIT(&paths);
5275 TAILQ_INIT(&diffstat_paths);
5277 #ifndef PROFILE
5278 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
5279 NULL) == -1)
5280 err(1, "pledge");
5281 #endif
5283 while ((ch = getopt(argc, argv, "aC:c:dPr:sw")) != -1) {
5284 switch (ch) {
5285 case 'a':
5286 force_text_diff = 1;
5287 break;
5288 case 'C':
5289 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
5290 &errstr);
5291 if (errstr != NULL)
5292 errx(1, "number of context lines is %s: %s",
5293 errstr, optarg);
5294 break;
5295 case 'c':
5296 if (ncommit_args >= 2)
5297 errx(1, "too many -c options used");
5298 commit_args[ncommit_args++] = optarg;
5299 break;
5300 case 'd':
5301 show_diffstat = 1;
5302 break;
5303 case 'P':
5304 force_path = 1;
5305 break;
5306 case 'r':
5307 repo_path = realpath(optarg, NULL);
5308 if (repo_path == NULL)
5309 return got_error_from_errno2("realpath",
5310 optarg);
5311 got_path_strip_trailing_slashes(repo_path);
5312 rflag = 1;
5313 break;
5314 case 's':
5315 diff_staged = 1;
5316 break;
5317 case 'w':
5318 ignore_whitespace = 1;
5319 break;
5320 default:
5321 usage_diff();
5322 /* NOTREACHED */
5326 argc -= optind;
5327 argv += optind;
5329 cwd = getcwd(NULL, 0);
5330 if (cwd == NULL) {
5331 error = got_error_from_errno("getcwd");
5332 goto done;
5335 error = got_repo_pack_fds_open(&pack_fds);
5336 if (error != NULL)
5337 goto done;
5339 if (repo_path == NULL) {
5340 error = got_worktree_open(&worktree, cwd,
5341 GOT_WORKTREE_GOT_DIR);
5342 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5343 goto done;
5344 else
5345 error = NULL;
5346 if (worktree) {
5347 repo_path =
5348 strdup(got_worktree_get_repo_path(worktree));
5349 if (repo_path == NULL) {
5350 error = got_error_from_errno("strdup");
5351 goto done;
5353 } else {
5354 repo_path = strdup(cwd);
5355 if (repo_path == NULL) {
5356 error = got_error_from_errno("strdup");
5357 goto done;
5362 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
5363 free(repo_path);
5364 if (error != NULL)
5365 goto done;
5367 if (show_diffstat) {
5368 dsa.paths = &diffstat_paths;
5369 dsa.force_text = force_text_diff;
5370 dsa.ignore_ws = ignore_whitespace;
5371 dsa.diff_algo = GOT_DIFF_ALGORITHM_PATIENCE;
5374 if (rflag || worktree == NULL || ncommit_args > 0) {
5375 if (force_path) {
5376 error = got_error_msg(GOT_ERR_NOT_IMPL,
5377 "-P option can only be used when diffing "
5378 "a work tree");
5379 goto done;
5381 if (diff_staged) {
5382 error = got_error_msg(GOT_ERR_NOT_IMPL,
5383 "-s option can only be used when diffing "
5384 "a work tree");
5385 goto done;
5389 error = apply_unveil(got_repo_get_path(repo), 1,
5390 worktree ? got_worktree_get_root_path(worktree) : NULL);
5391 if (error)
5392 goto done;
5394 if ((!force_path && argc == 2) || ncommit_args > 0) {
5395 int obj_type = (ncommit_args > 0 ?
5396 GOT_OBJ_TYPE_COMMIT : GOT_OBJ_TYPE_ANY);
5397 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
5398 NULL);
5399 if (error)
5400 goto done;
5401 for (i = 0; i < (ncommit_args > 0 ? ncommit_args : argc); i++) {
5402 const char *arg;
5403 char *keyword_idstr = NULL;
5405 if (ncommit_args > 0)
5406 arg = commit_args[i];
5407 else
5408 arg = argv[i];
5410 error = got_keyword_to_idstr(&keyword_idstr, arg,
5411 repo, worktree);
5412 if (error != NULL)
5413 goto done;
5414 if (keyword_idstr != NULL)
5415 arg = keyword_idstr;
5417 error = got_repo_match_object_id(&ids[i], &labels[i],
5418 arg, obj_type, &refs, repo);
5419 free(keyword_idstr);
5420 if (error) {
5421 if (error->code != GOT_ERR_NOT_REF &&
5422 error->code != GOT_ERR_NO_OBJ)
5423 goto done;
5424 if (ncommit_args > 0)
5425 goto done;
5426 error = NULL;
5427 break;
5432 f1 = got_opentemp();
5433 if (f1 == NULL) {
5434 error = got_error_from_errno("got_opentemp");
5435 goto done;
5438 f2 = got_opentemp();
5439 if (f2 == NULL) {
5440 error = got_error_from_errno("got_opentemp");
5441 goto done;
5444 outfile = got_opentemp();
5445 if (outfile == NULL) {
5446 error = got_error_from_errno("got_opentemp");
5447 goto done;
5450 if (ncommit_args == 0 && (ids[0] == NULL || ids[1] == NULL)) {
5451 struct print_diff_arg arg;
5452 char *id_str;
5454 if (worktree == NULL) {
5455 if (argc == 2 && ids[0] == NULL) {
5456 error = got_error_path(argv[0], GOT_ERR_NO_OBJ);
5457 goto done;
5458 } else if (argc == 2 && ids[1] == NULL) {
5459 error = got_error_path(argv[1], GOT_ERR_NO_OBJ);
5460 goto done;
5461 } else if (argc > 0) {
5462 error = got_error_fmt(GOT_ERR_NOT_WORKTREE,
5463 "%s", "specified paths cannot be resolved");
5464 goto done;
5465 } else {
5466 error = got_error(GOT_ERR_NOT_WORKTREE);
5467 goto done;
5471 error = get_worktree_paths_from_argv(&paths, argc, argv,
5472 worktree);
5473 if (error)
5474 goto done;
5476 error = got_object_id_str(&id_str,
5477 got_worktree_get_base_commit_id(worktree));
5478 if (error)
5479 goto done;
5480 arg.repo = repo;
5481 arg.worktree = worktree;
5482 arg.diff_algo = GOT_DIFF_ALGORITHM_PATIENCE;
5483 arg.diff_context = diff_context;
5484 arg.id_str = id_str;
5485 arg.header_shown = 0;
5486 arg.diff_staged = diff_staged;
5487 arg.ignore_whitespace = ignore_whitespace;
5488 arg.force_text_diff = force_text_diff;
5489 arg.diffstat = show_diffstat ? &dsa : NULL;
5490 arg.f1 = f1;
5491 arg.f2 = f2;
5492 arg.outfile = outfile;
5494 error = got_worktree_status(worktree, &paths, repo, 0,
5495 print_diff, &arg, check_cancelled, NULL);
5496 free(id_str);
5497 if (error)
5498 goto done;
5500 if (show_diffstat && dsa.nfiles > 0) {
5501 char *header;
5503 if (asprintf(&header, "diffstat %s%s",
5504 diff_staged ? "-s " : "",
5505 got_worktree_get_root_path(worktree)) == -1) {
5506 error = got_error_from_errno("asprintf");
5507 goto done;
5510 error = print_diffstat(&dsa, header);
5511 free(header);
5512 if (error)
5513 goto done;
5516 error = printfile(outfile);
5517 goto done;
5520 if (ncommit_args == 1) {
5521 struct got_commit_object *commit;
5522 error = got_object_open_as_commit(&commit, repo, ids[0]);
5523 if (error)
5524 goto done;
5526 labels[1] = labels[0];
5527 ids[1] = ids[0];
5528 if (got_object_commit_get_nparents(commit) > 0) {
5529 const struct got_object_id_queue *pids;
5530 struct got_object_qid *pid;
5531 pids = got_object_commit_get_parent_ids(commit);
5532 pid = STAILQ_FIRST(pids);
5533 ids[0] = got_object_id_dup(&pid->id);
5534 if (ids[0] == NULL) {
5535 error = got_error_from_errno(
5536 "got_object_id_dup");
5537 got_object_commit_close(commit);
5538 goto done;
5540 error = got_object_id_str(&labels[0], ids[0]);
5541 if (error) {
5542 got_object_commit_close(commit);
5543 goto done;
5545 } else {
5546 ids[0] = NULL;
5547 labels[0] = strdup("/dev/null");
5548 if (labels[0] == NULL) {
5549 error = got_error_from_errno("strdup");
5550 got_object_commit_close(commit);
5551 goto done;
5555 got_object_commit_close(commit);
5558 if (ncommit_args == 0 && argc > 2) {
5559 error = got_error_msg(GOT_ERR_BAD_PATH,
5560 "path arguments cannot be used when diffing two objects");
5561 goto done;
5564 if (ids[0]) {
5565 error = got_object_get_type(&type1, repo, ids[0]);
5566 if (error)
5567 goto done;
5570 error = got_object_get_type(&type2, repo, ids[1]);
5571 if (error)
5572 goto done;
5573 if (type1 != GOT_OBJ_TYPE_ANY && type1 != type2) {
5574 error = got_error(GOT_ERR_OBJ_TYPE);
5575 goto done;
5577 if (type1 == GOT_OBJ_TYPE_BLOB && argc > 2) {
5578 error = got_error_msg(GOT_ERR_OBJ_TYPE,
5579 "path arguments cannot be used when diffing blobs");
5580 goto done;
5583 for (i = 0; ncommit_args > 0 && i < argc; i++) {
5584 char *in_repo_path;
5585 struct got_pathlist_entry *new;
5586 if (worktree) {
5587 const char *prefix;
5588 char *p;
5589 error = got_worktree_resolve_path(&p, worktree,
5590 argv[i]);
5591 if (error)
5592 goto done;
5593 prefix = got_worktree_get_path_prefix(worktree);
5594 while (prefix[0] == '/')
5595 prefix++;
5596 if (asprintf(&in_repo_path, "%s%s%s", prefix,
5597 (p[0] != '\0' && prefix[0] != '\0') ? "/" : "",
5598 p) == -1) {
5599 error = got_error_from_errno("asprintf");
5600 free(p);
5601 goto done;
5603 free(p);
5604 } else {
5605 char *mapped_path, *s;
5606 error = got_repo_map_path(&mapped_path, repo, argv[i]);
5607 if (error)
5608 goto done;
5609 s = mapped_path;
5610 while (s[0] == '/')
5611 s++;
5612 in_repo_path = strdup(s);
5613 if (in_repo_path == NULL) {
5614 error = got_error_from_errno("asprintf");
5615 free(mapped_path);
5616 goto done;
5618 free(mapped_path);
5621 error = got_pathlist_insert(&new, &paths, in_repo_path, NULL);
5622 if (error || new == NULL /* duplicate */)
5623 free(in_repo_path);
5624 if (error)
5625 goto done;
5628 if (worktree) {
5629 /* Release work tree lock. */
5630 got_worktree_close(worktree);
5631 worktree = NULL;
5634 fd1 = got_opentempfd();
5635 if (fd1 == -1) {
5636 error = got_error_from_errno("got_opentempfd");
5637 goto done;
5640 fd2 = got_opentempfd();
5641 if (fd2 == -1) {
5642 error = got_error_from_errno("got_opentempfd");
5643 goto done;
5646 switch (type1 == GOT_OBJ_TYPE_ANY ? type2 : type1) {
5647 case GOT_OBJ_TYPE_BLOB:
5648 error = got_diff_objects_as_blobs(NULL, NULL, f1, f2,
5649 fd1, fd2, ids[0], ids[1], NULL, NULL,
5650 GOT_DIFF_ALGORITHM_PATIENCE, diff_context,
5651 ignore_whitespace, force_text_diff,
5652 show_diffstat ? &dsa : NULL, repo, outfile);
5653 break;
5654 case GOT_OBJ_TYPE_TREE:
5655 error = got_diff_objects_as_trees(NULL, NULL, f1, f2, fd1, fd2,
5656 ids[0], ids[1], &paths, "", "",
5657 GOT_DIFF_ALGORITHM_PATIENCE, diff_context,
5658 ignore_whitespace, force_text_diff,
5659 show_diffstat ? &dsa : NULL, repo, outfile);
5660 break;
5661 case GOT_OBJ_TYPE_COMMIT:
5662 fprintf(outfile, "diff %s %s\n", labels[0], labels[1]);
5663 error = got_diff_objects_as_commits(NULL, NULL, f1, f2,
5664 fd1, fd2, ids[0], ids[1], &paths,
5665 GOT_DIFF_ALGORITHM_PATIENCE, diff_context,
5666 ignore_whitespace, force_text_diff,
5667 show_diffstat ? &dsa : NULL, repo, outfile);
5668 break;
5669 default:
5670 error = got_error(GOT_ERR_OBJ_TYPE);
5672 if (error)
5673 goto done;
5675 if (show_diffstat && dsa.nfiles > 0) {
5676 char *header = NULL;
5678 if (asprintf(&header, "diffstat %s %s",
5679 labels[0], labels[1]) == -1) {
5680 error = got_error_from_errno("asprintf");
5681 goto done;
5684 error = print_diffstat(&dsa, header);
5685 free(header);
5686 if (error)
5687 goto done;
5690 error = printfile(outfile);
5692 done:
5693 free(cwd);
5694 free(labels[0]);
5695 free(labels[1]);
5696 free(ids[0]);
5697 free(ids[1]);
5698 if (worktree)
5699 got_worktree_close(worktree);
5700 if (repo) {
5701 const struct got_error *close_err = got_repo_close(repo);
5702 if (error == NULL)
5703 error = close_err;
5705 if (pack_fds) {
5706 const struct got_error *pack_err =
5707 got_repo_pack_fds_close(pack_fds);
5708 if (error == NULL)
5709 error = pack_err;
5711 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
5712 got_pathlist_free(&diffstat_paths, GOT_PATHLIST_FREE_ALL);
5713 got_ref_list_free(&refs);
5714 if (outfile && fclose(outfile) == EOF && error == NULL)
5715 error = got_error_from_errno("fclose");
5716 if (f1 && fclose(f1) == EOF && error == NULL)
5717 error = got_error_from_errno("fclose");
5718 if (f2 && fclose(f2) == EOF && error == NULL)
5719 error = got_error_from_errno("fclose");
5720 if (fd1 != -1 && close(fd1) == -1 && error == NULL)
5721 error = got_error_from_errno("close");
5722 if (fd2 != -1 && close(fd2) == -1 && error == NULL)
5723 error = got_error_from_errno("close");
5724 return error;
5727 __dead static void
5728 usage_blame(void)
5730 fprintf(stderr,
5731 "usage: %s blame [-c commit] [-r repository-path] path\n",
5732 getprogname());
5733 exit(1);
5736 struct blame_line {
5737 int annotated;
5738 char *id_str;
5739 char *committer;
5740 char datebuf[11]; /* YYYY-MM-DD + NUL */
5743 struct blame_cb_args {
5744 struct blame_line *lines;
5745 int nlines;
5746 int nlines_prec;
5747 int lineno_cur;
5748 off_t *line_offsets;
5749 FILE *f;
5750 struct got_repository *repo;
5753 static const struct got_error *
5754 blame_cb(void *arg, int nlines, int lineno,
5755 struct got_commit_object *commit, struct got_object_id *id)
5757 const struct got_error *err = NULL;
5758 struct blame_cb_args *a = arg;
5759 struct blame_line *bline;
5760 char *line = NULL;
5761 size_t linesize = 0;
5762 off_t offset;
5763 struct tm tm;
5764 time_t committer_time;
5766 if (nlines != a->nlines ||
5767 (lineno != -1 && lineno < 1) || lineno > a->nlines)
5768 return got_error(GOT_ERR_RANGE);
5770 if (sigint_received)
5771 return got_error(GOT_ERR_ITER_COMPLETED);
5773 if (lineno == -1)
5774 return NULL; /* no change in this commit */
5776 /* Annotate this line. */
5777 bline = &a->lines[lineno - 1];
5778 if (bline->annotated)
5779 return NULL;
5780 err = got_object_id_str(&bline->id_str, id);
5781 if (err)
5782 return err;
5784 bline->committer = strdup(got_object_commit_get_committer(commit));
5785 if (bline->committer == NULL) {
5786 err = got_error_from_errno("strdup");
5787 goto done;
5790 committer_time = got_object_commit_get_committer_time(commit);
5791 if (gmtime_r(&committer_time, &tm) == NULL)
5792 return got_error_from_errno("gmtime_r");
5793 if (strftime(bline->datebuf, sizeof(bline->datebuf), "%F", &tm) == 0) {
5794 err = got_error(GOT_ERR_NO_SPACE);
5795 goto done;
5797 bline->annotated = 1;
5799 /* Print lines annotated so far. */
5800 bline = &a->lines[a->lineno_cur - 1];
5801 if (!bline->annotated)
5802 goto done;
5804 offset = a->line_offsets[a->lineno_cur - 1];
5805 if (fseeko(a->f, offset, SEEK_SET) == -1) {
5806 err = got_error_from_errno("fseeko");
5807 goto done;
5810 while (a->lineno_cur <= a->nlines && bline->annotated) {
5811 char *smallerthan, *at, *nl, *committer;
5812 size_t len;
5814 if (getline(&line, &linesize, a->f) == -1) {
5815 if (ferror(a->f))
5816 err = got_error_from_errno("getline");
5817 break;
5820 committer = bline->committer;
5821 smallerthan = strchr(committer, '<');
5822 if (smallerthan && smallerthan[1] != '\0')
5823 committer = smallerthan + 1;
5824 at = strchr(committer, '@');
5825 if (at)
5826 *at = '\0';
5827 len = strlen(committer);
5828 if (len >= 9)
5829 committer[8] = '\0';
5831 nl = strchr(line, '\n');
5832 if (nl)
5833 *nl = '\0';
5834 printf("%.*d) %.8s %s %-8s %s\n", a->nlines_prec, a->lineno_cur,
5835 bline->id_str, bline->datebuf, committer, line);
5837 a->lineno_cur++;
5838 bline = &a->lines[a->lineno_cur - 1];
5840 done:
5841 free(line);
5842 return err;
5845 static const struct got_error *
5846 cmd_blame(int argc, char *argv[])
5848 const struct got_error *error;
5849 struct got_repository *repo = NULL;
5850 struct got_worktree *worktree = NULL;
5851 char *path, *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
5852 char *link_target = NULL;
5853 struct got_object_id *obj_id = NULL;
5854 struct got_object_id *commit_id = NULL;
5855 struct got_commit_object *commit = NULL;
5856 struct got_blob_object *blob = NULL;
5857 char *commit_id_str = NULL, *keyword_idstr = NULL;
5858 struct blame_cb_args bca;
5859 int ch, obj_type, i, fd1 = -1, fd2 = -1, fd3 = -1;
5860 off_t filesize;
5861 int *pack_fds = NULL;
5862 FILE *f1 = NULL, *f2 = NULL;
5864 fd1 = got_opentempfd();
5865 if (fd1 == -1)
5866 return got_error_from_errno("got_opentempfd");
5868 memset(&bca, 0, sizeof(bca));
5870 #ifndef PROFILE
5871 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
5872 NULL) == -1)
5873 err(1, "pledge");
5874 #endif
5876 while ((ch = getopt(argc, argv, "c:r:")) != -1) {
5877 switch (ch) {
5878 case 'c':
5879 commit_id_str = optarg;
5880 break;
5881 case 'r':
5882 repo_path = realpath(optarg, NULL);
5883 if (repo_path == NULL)
5884 return got_error_from_errno2("realpath",
5885 optarg);
5886 got_path_strip_trailing_slashes(repo_path);
5887 break;
5888 default:
5889 usage_blame();
5890 /* NOTREACHED */
5894 argc -= optind;
5895 argv += optind;
5897 if (argc == 1)
5898 path = argv[0];
5899 else
5900 usage_blame();
5902 cwd = getcwd(NULL, 0);
5903 if (cwd == NULL) {
5904 error = got_error_from_errno("getcwd");
5905 goto done;
5908 error = got_repo_pack_fds_open(&pack_fds);
5909 if (error != NULL)
5910 goto done;
5912 if (repo_path == NULL) {
5913 error = got_worktree_open(&worktree, cwd,
5914 GOT_WORKTREE_GOT_DIR);
5915 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5916 goto done;
5917 else
5918 error = NULL;
5919 if (worktree) {
5920 repo_path =
5921 strdup(got_worktree_get_repo_path(worktree));
5922 if (repo_path == NULL) {
5923 error = got_error_from_errno("strdup");
5924 if (error)
5925 goto done;
5927 } else {
5928 repo_path = strdup(cwd);
5929 if (repo_path == NULL) {
5930 error = got_error_from_errno("strdup");
5931 goto done;
5936 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
5937 if (error != NULL)
5938 goto done;
5940 if (worktree) {
5941 const char *prefix = got_worktree_get_path_prefix(worktree);
5942 char *p;
5944 error = got_worktree_resolve_path(&p, worktree, path);
5945 if (error)
5946 goto done;
5947 if (asprintf(&in_repo_path, "%s%s%s", prefix,
5948 (p[0] != '\0' && !got_path_is_root_dir(prefix)) ? "/" : "",
5949 p) == -1) {
5950 error = got_error_from_errno("asprintf");
5951 free(p);
5952 goto done;
5954 free(p);
5955 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5956 } else {
5957 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
5958 if (error)
5959 goto done;
5960 error = got_repo_map_path(&in_repo_path, repo, path);
5962 if (error)
5963 goto done;
5965 if (commit_id_str == NULL) {
5966 struct got_reference *head_ref;
5967 error = got_ref_open(&head_ref, repo, worktree ?
5968 got_worktree_get_head_ref_name(worktree) : GOT_REF_HEAD, 0);
5969 if (error != NULL)
5970 goto done;
5971 error = got_ref_resolve(&commit_id, repo, head_ref);
5972 got_ref_close(head_ref);
5973 if (error != NULL)
5974 goto done;
5975 } else {
5976 struct got_reflist_head refs;
5978 TAILQ_INIT(&refs);
5979 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
5980 NULL);
5981 if (error)
5982 goto done;
5984 error = got_keyword_to_idstr(&keyword_idstr, commit_id_str,
5985 repo, worktree);
5986 if (error != NULL)
5987 goto done;
5988 if (keyword_idstr != NULL)
5989 commit_id_str = keyword_idstr;
5991 error = got_repo_match_object_id(&commit_id, NULL,
5992 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
5993 got_ref_list_free(&refs);
5994 if (error)
5995 goto done;
5998 if (worktree) {
5999 /* Release work tree lock. */
6000 got_worktree_close(worktree);
6001 worktree = NULL;
6004 error = got_object_open_as_commit(&commit, repo, commit_id);
6005 if (error)
6006 goto done;
6008 error = got_object_resolve_symlinks(&link_target, in_repo_path,
6009 commit, repo);
6010 if (error)
6011 goto done;
6013 error = got_object_id_by_path(&obj_id, repo, commit,
6014 link_target ? link_target : in_repo_path);
6015 if (error)
6016 goto done;
6018 error = got_object_get_type(&obj_type, repo, obj_id);
6019 if (error)
6020 goto done;
6022 if (obj_type != GOT_OBJ_TYPE_BLOB) {
6023 error = got_error_path(link_target ? link_target : in_repo_path,
6024 GOT_ERR_OBJ_TYPE);
6025 goto done;
6028 error = got_object_open_as_blob(&blob, repo, obj_id, 8192, fd1);
6029 if (error)
6030 goto done;
6031 bca.f = got_opentemp();
6032 if (bca.f == NULL) {
6033 error = got_error_from_errno("got_opentemp");
6034 goto done;
6036 error = got_object_blob_dump_to_file(&filesize, &bca.nlines,
6037 &bca.line_offsets, bca.f, blob);
6038 if (error || bca.nlines == 0)
6039 goto done;
6041 /* Don't include \n at EOF in the blame line count. */
6042 if (bca.line_offsets[bca.nlines - 1] == filesize)
6043 bca.nlines--;
6045 bca.lines = calloc(bca.nlines, sizeof(*bca.lines));
6046 if (bca.lines == NULL) {
6047 error = got_error_from_errno("calloc");
6048 goto done;
6050 bca.lineno_cur = 1;
6051 bca.nlines_prec = 0;
6052 i = bca.nlines;
6053 while (i > 0) {
6054 i /= 10;
6055 bca.nlines_prec++;
6057 bca.repo = repo;
6059 fd2 = got_opentempfd();
6060 if (fd2 == -1) {
6061 error = got_error_from_errno("got_opentempfd");
6062 goto done;
6064 fd3 = got_opentempfd();
6065 if (fd3 == -1) {
6066 error = got_error_from_errno("got_opentempfd");
6067 goto done;
6069 f1 = got_opentemp();
6070 if (f1 == NULL) {
6071 error = got_error_from_errno("got_opentemp");
6072 goto done;
6074 f2 = got_opentemp();
6075 if (f2 == NULL) {
6076 error = got_error_from_errno("got_opentemp");
6077 goto done;
6079 error = got_blame(link_target ? link_target : in_repo_path, commit_id,
6080 repo, GOT_DIFF_ALGORITHM_PATIENCE, blame_cb, &bca,
6081 check_cancelled, NULL, fd2, fd3, f1, f2);
6082 done:
6083 free(keyword_idstr);
6084 free(in_repo_path);
6085 free(link_target);
6086 free(repo_path);
6087 free(cwd);
6088 free(commit_id);
6089 free(obj_id);
6090 if (commit)
6091 got_object_commit_close(commit);
6093 if (fd1 != -1 && close(fd1) == -1 && error == NULL)
6094 error = got_error_from_errno("close");
6095 if (fd2 != -1 && close(fd2) == -1 && error == NULL)
6096 error = got_error_from_errno("close");
6097 if (fd3 != -1 && close(fd3) == -1 && error == NULL)
6098 error = got_error_from_errno("close");
6099 if (f1 && fclose(f1) == EOF && error == NULL)
6100 error = got_error_from_errno("fclose");
6101 if (f2 && fclose(f2) == EOF && error == NULL)
6102 error = got_error_from_errno("fclose");
6104 if (blob)
6105 got_object_blob_close(blob);
6106 if (worktree)
6107 got_worktree_close(worktree);
6108 if (repo) {
6109 const struct got_error *close_err = got_repo_close(repo);
6110 if (error == NULL)
6111 error = close_err;
6113 if (pack_fds) {
6114 const struct got_error *pack_err =
6115 got_repo_pack_fds_close(pack_fds);
6116 if (error == NULL)
6117 error = pack_err;
6119 if (bca.lines) {
6120 for (i = 0; i < bca.nlines; i++) {
6121 struct blame_line *bline = &bca.lines[i];
6122 free(bline->id_str);
6123 free(bline->committer);
6125 free(bca.lines);
6127 free(bca.line_offsets);
6128 if (bca.f && fclose(bca.f) == EOF && error == NULL)
6129 error = got_error_from_errno("fclose");
6130 return error;
6133 __dead static void
6134 usage_tree(void)
6136 fprintf(stderr, "usage: %s tree [-iR] [-c commit] [-r repository-path] "
6137 "[path]\n", getprogname());
6138 exit(1);
6141 static const struct got_error *
6142 print_entry(struct got_tree_entry *te, const char *id, const char *path,
6143 const char *root_path, struct got_repository *repo)
6145 const struct got_error *err = NULL;
6146 int is_root_path = (strcmp(path, root_path) == 0);
6147 const char *modestr = "";
6148 mode_t mode = got_tree_entry_get_mode(te);
6149 char *link_target = NULL;
6151 path += strlen(root_path);
6152 while (path[0] == '/')
6153 path++;
6155 if (got_object_tree_entry_is_submodule(te))
6156 modestr = "$";
6157 else if (S_ISLNK(mode)) {
6158 int i;
6160 err = got_tree_entry_get_symlink_target(&link_target, te, repo);
6161 if (err)
6162 return err;
6163 for (i = 0; link_target[i] != '\0'; i++) {
6164 if (!isprint((unsigned char)link_target[i]))
6165 link_target[i] = '?';
6168 modestr = "@";
6170 else if (S_ISDIR(mode))
6171 modestr = "/";
6172 else if (mode & S_IXUSR)
6173 modestr = "*";
6175 printf("%s%s%s%s%s%s%s\n", id ? id : "", path,
6176 is_root_path ? "" : "/", got_tree_entry_get_name(te), modestr,
6177 link_target ? " -> ": "", link_target ? link_target : "");
6179 free(link_target);
6180 return NULL;
6183 static const struct got_error *
6184 print_tree(const char *path, struct got_commit_object *commit,
6185 int show_ids, int recurse, const char *root_path,
6186 struct got_repository *repo)
6188 const struct got_error *err = NULL;
6189 struct got_object_id *tree_id = NULL;
6190 struct got_tree_object *tree = NULL;
6191 int nentries, i;
6193 err = got_object_id_by_path(&tree_id, repo, commit, path);
6194 if (err)
6195 goto done;
6197 err = got_object_open_as_tree(&tree, repo, tree_id);
6198 if (err)
6199 goto done;
6200 nentries = got_object_tree_get_nentries(tree);
6201 for (i = 0; i < nentries; i++) {
6202 struct got_tree_entry *te;
6203 char *id = NULL;
6205 if (sigint_received || sigpipe_received)
6206 break;
6208 te = got_object_tree_get_entry(tree, i);
6209 if (show_ids) {
6210 char *id_str;
6211 err = got_object_id_str(&id_str,
6212 got_tree_entry_get_id(te));
6213 if (err)
6214 goto done;
6215 if (asprintf(&id, "%s ", id_str) == -1) {
6216 err = got_error_from_errno("asprintf");
6217 free(id_str);
6218 goto done;
6220 free(id_str);
6222 err = print_entry(te, id, path, root_path, repo);
6223 free(id);
6224 if (err)
6225 goto done;
6227 if (recurse && S_ISDIR(got_tree_entry_get_mode(te))) {
6228 char *child_path;
6229 if (asprintf(&child_path, "%s%s%s", path,
6230 path[0] == '/' && path[1] == '\0' ? "" : "/",
6231 got_tree_entry_get_name(te)) == -1) {
6232 err = got_error_from_errno("asprintf");
6233 goto done;
6235 err = print_tree(child_path, commit, show_ids, 1,
6236 root_path, repo);
6237 free(child_path);
6238 if (err)
6239 goto done;
6242 done:
6243 if (tree)
6244 got_object_tree_close(tree);
6245 free(tree_id);
6246 return err;
6249 static const struct got_error *
6250 cmd_tree(int argc, char *argv[])
6252 const struct got_error *error;
6253 struct got_repository *repo = NULL;
6254 struct got_worktree *worktree = NULL;
6255 const char *path, *refname = NULL;
6256 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
6257 struct got_object_id *commit_id = NULL;
6258 struct got_commit_object *commit = NULL;
6259 char *commit_id_str = NULL, *keyword_idstr = NULL;
6260 int show_ids = 0, recurse = 0;
6261 int ch;
6262 int *pack_fds = NULL;
6264 #ifndef PROFILE
6265 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
6266 NULL) == -1)
6267 err(1, "pledge");
6268 #endif
6270 while ((ch = getopt(argc, argv, "c:iRr:")) != -1) {
6271 switch (ch) {
6272 case 'c':
6273 commit_id_str = optarg;
6274 break;
6275 case 'i':
6276 show_ids = 1;
6277 break;
6278 case 'R':
6279 recurse = 1;
6280 break;
6281 case 'r':
6282 repo_path = realpath(optarg, NULL);
6283 if (repo_path == NULL)
6284 return got_error_from_errno2("realpath",
6285 optarg);
6286 got_path_strip_trailing_slashes(repo_path);
6287 break;
6288 default:
6289 usage_tree();
6290 /* NOTREACHED */
6294 argc -= optind;
6295 argv += optind;
6297 if (argc == 1)
6298 path = argv[0];
6299 else if (argc > 1)
6300 usage_tree();
6301 else
6302 path = NULL;
6304 cwd = getcwd(NULL, 0);
6305 if (cwd == NULL) {
6306 error = got_error_from_errno("getcwd");
6307 goto done;
6310 error = got_repo_pack_fds_open(&pack_fds);
6311 if (error != NULL)
6312 goto done;
6314 if (repo_path == NULL) {
6315 error = got_worktree_open(&worktree, cwd,
6316 GOT_WORKTREE_GOT_DIR);
6317 if (error && error->code != GOT_ERR_NOT_WORKTREE)
6318 goto done;
6319 else
6320 error = NULL;
6321 if (worktree) {
6322 repo_path =
6323 strdup(got_worktree_get_repo_path(worktree));
6324 if (repo_path == NULL)
6325 error = got_error_from_errno("strdup");
6326 if (error)
6327 goto done;
6328 } else {
6329 repo_path = strdup(cwd);
6330 if (repo_path == NULL) {
6331 error = got_error_from_errno("strdup");
6332 goto done;
6337 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
6338 if (error != NULL)
6339 goto done;
6341 if (worktree) {
6342 const char *prefix = got_worktree_get_path_prefix(worktree);
6343 char *p;
6345 if (path == NULL || got_path_is_root_dir(path))
6346 path = "";
6347 error = got_worktree_resolve_path(&p, worktree, path);
6348 if (error)
6349 goto done;
6350 if (asprintf(&in_repo_path, "%s%s%s", prefix,
6351 (p[0] != '\0' && !got_path_is_root_dir(prefix)) ? "/" : "",
6352 p) == -1) {
6353 error = got_error_from_errno("asprintf");
6354 free(p);
6355 goto done;
6357 free(p);
6358 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
6359 if (error)
6360 goto done;
6361 } else {
6362 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
6363 if (error)
6364 goto done;
6365 if (path == NULL)
6366 path = "/";
6367 error = got_repo_map_path(&in_repo_path, repo, path);
6368 if (error != NULL)
6369 goto done;
6372 if (commit_id_str == NULL) {
6373 struct got_reference *head_ref;
6374 if (worktree)
6375 refname = got_worktree_get_head_ref_name(worktree);
6376 else
6377 refname = GOT_REF_HEAD;
6378 error = got_ref_open(&head_ref, repo, refname, 0);
6379 if (error != NULL)
6380 goto done;
6381 error = got_ref_resolve(&commit_id, repo, head_ref);
6382 got_ref_close(head_ref);
6383 if (error != NULL)
6384 goto done;
6385 } else {
6386 struct got_reflist_head refs;
6388 TAILQ_INIT(&refs);
6389 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
6390 NULL);
6391 if (error)
6392 goto done;
6394 error = got_keyword_to_idstr(&keyword_idstr, commit_id_str,
6395 repo, worktree);
6396 if (error != NULL)
6397 goto done;
6398 if (keyword_idstr != NULL)
6399 commit_id_str = keyword_idstr;
6401 error = got_repo_match_object_id(&commit_id, NULL,
6402 commit_id_str, GOT_OBJ_TYPE_COMMIT, &refs, repo);
6403 got_ref_list_free(&refs);
6404 if (error)
6405 goto done;
6408 if (worktree) {
6409 /* Release work tree lock. */
6410 got_worktree_close(worktree);
6411 worktree = NULL;
6414 error = got_object_open_as_commit(&commit, repo, commit_id);
6415 if (error)
6416 goto done;
6418 error = print_tree(in_repo_path, commit, show_ids, recurse,
6419 in_repo_path, repo);
6420 done:
6421 free(keyword_idstr);
6422 free(in_repo_path);
6423 free(repo_path);
6424 free(cwd);
6425 free(commit_id);
6426 if (commit)
6427 got_object_commit_close(commit);
6428 if (worktree)
6429 got_worktree_close(worktree);
6430 if (repo) {
6431 const struct got_error *close_err = got_repo_close(repo);
6432 if (error == NULL)
6433 error = close_err;
6435 if (pack_fds) {
6436 const struct got_error *pack_err =
6437 got_repo_pack_fds_close(pack_fds);
6438 if (error == NULL)
6439 error = pack_err;
6441 return error;
6444 __dead static void
6445 usage_status(void)
6447 fprintf(stderr, "usage: %s status [-I] [-S status-codes] "
6448 "[-s status-codes] [path ...]\n", getprogname());
6449 exit(1);
6452 struct got_status_arg {
6453 char *status_codes;
6454 int suppress;
6457 static const struct got_error *
6458 print_status(void *arg, unsigned char status, unsigned char staged_status,
6459 const char *path, struct got_object_id *blob_id,
6460 struct got_object_id *staged_blob_id, struct got_object_id *commit_id,
6461 int dirfd, const char *de_name)
6463 struct got_status_arg *st = arg;
6465 if (status == staged_status && (status == GOT_STATUS_DELETE))
6466 status = GOT_STATUS_NO_CHANGE;
6467 if (st != NULL && st->status_codes) {
6468 size_t ncodes = strlen(st->status_codes);
6469 int i, j = 0;
6471 for (i = 0; i < ncodes ; i++) {
6472 if (st->suppress) {
6473 if (status == st->status_codes[i] ||
6474 staged_status == st->status_codes[i]) {
6475 j++;
6476 continue;
6478 } else {
6479 if (status == st->status_codes[i] ||
6480 staged_status == st->status_codes[i])
6481 break;
6485 if (st->suppress && j == 0)
6486 goto print;
6488 if (i == ncodes)
6489 return NULL;
6491 print:
6492 printf("%c%c %s\n", status, staged_status, path);
6493 return NULL;
6496 static const struct got_error *
6497 show_operation_in_progress(struct got_worktree *worktree,
6498 struct got_repository *repo)
6500 const struct got_error *err;
6501 char *new_base_branch_name = NULL;
6502 char *branch_name = NULL;
6503 int rebase_in_progress, histedit_in_progress, merge_in_progress;
6505 err = got_worktree_rebase_in_progress(&rebase_in_progress, worktree);
6506 if (err)
6507 return err;
6508 if (rebase_in_progress) {
6509 err = got_worktree_rebase_info(&new_base_branch_name,
6510 &branch_name, worktree, repo);
6511 if (err)
6512 return err;
6513 printf("Work tree is rebasing %s onto %s\n",
6514 branch_name, new_base_branch_name);
6517 err = got_worktree_histedit_in_progress(&histedit_in_progress,
6518 worktree);
6519 if (err)
6520 return err;
6521 if (histedit_in_progress) {
6522 err = got_worktree_histedit_info(&branch_name, worktree, repo);
6523 if (err)
6524 return err;
6525 printf("Work tree is editing the history of %s\n", branch_name);
6528 err = got_worktree_merge_in_progress(&merge_in_progress,
6529 worktree, repo);
6530 if (err)
6531 return err;
6532 if (merge_in_progress) {
6533 err = got_worktree_merge_info(&branch_name, worktree,
6534 repo);
6535 if (err)
6536 return err;
6537 printf("Work tree is merging %s into %s\n", branch_name,
6538 got_worktree_get_head_ref_name(worktree));
6541 free(new_base_branch_name);
6542 free(branch_name);
6543 return NULL;
6546 static const struct got_error *
6547 cmd_status(int argc, char *argv[])
6549 const struct got_error *close_err, *error = NULL;
6550 struct got_repository *repo = NULL;
6551 struct got_worktree *worktree = NULL;
6552 struct got_status_arg st;
6553 char *cwd = NULL;
6554 struct got_pathlist_head paths;
6555 int ch, i, no_ignores = 0;
6556 int *pack_fds = NULL;
6558 TAILQ_INIT(&paths);
6560 memset(&st, 0, sizeof(st));
6561 st.status_codes = NULL;
6562 st.suppress = 0;
6564 #ifndef PROFILE
6565 if (pledge("stdio rpath wpath cpath flock proc exec sendfd unveil",
6566 NULL) == -1)
6567 err(1, "pledge");
6568 #endif
6570 while ((ch = getopt(argc, argv, "IS:s:")) != -1) {
6571 switch (ch) {
6572 case 'I':
6573 no_ignores = 1;
6574 break;
6575 case 'S':
6576 if (st.status_codes != NULL && st.suppress == 0)
6577 option_conflict('S', 's');
6578 st.suppress = 1;
6579 /* fallthrough */
6580 case 's':
6581 for (i = 0; optarg[i] != '\0'; i++) {
6582 switch (optarg[i]) {
6583 case GOT_STATUS_MODIFY:
6584 case GOT_STATUS_ADD:
6585 case GOT_STATUS_DELETE:
6586 case GOT_STATUS_CONFLICT:
6587 case GOT_STATUS_MISSING:
6588 case GOT_STATUS_OBSTRUCTED:
6589 case GOT_STATUS_UNVERSIONED:
6590 case GOT_STATUS_MODE_CHANGE:
6591 case GOT_STATUS_NONEXISTENT:
6592 break;
6593 default:
6594 errx(1, "invalid status code '%c'",
6595 optarg[i]);
6598 if (ch == 's' && st.suppress)
6599 option_conflict('s', 'S');
6600 st.status_codes = optarg;
6601 break;
6602 default:
6603 usage_status();
6604 /* NOTREACHED */
6608 argc -= optind;
6609 argv += optind;
6611 cwd = getcwd(NULL, 0);
6612 if (cwd == NULL) {
6613 error = got_error_from_errno("getcwd");
6614 goto done;
6617 error = got_repo_pack_fds_open(&pack_fds);
6618 if (error != NULL)
6619 goto done;
6621 error = got_worktree_open(&worktree, cwd,
6622 GOT_WORKTREE_GOT_DIR);
6623 if (error) {
6624 if (error->code == GOT_ERR_NOT_WORKTREE)
6625 error = wrap_not_worktree_error(error, "status", cwd);
6626 goto done;
6629 error = got_repo_open(&repo, got_worktree_get_repo_path(worktree),
6630 NULL, pack_fds);
6631 if (error != NULL)
6632 goto done;
6634 error = apply_unveil(got_repo_get_path(repo), 1,
6635 got_worktree_get_root_path(worktree));
6636 if (error)
6637 goto done;
6639 error = get_worktree_paths_from_argv(&paths, argc, argv, worktree);
6640 if (error)
6641 goto done;
6643 error = got_worktree_status(worktree, &paths, repo, no_ignores,
6644 print_status, &st, check_cancelled, NULL);
6645 if (error)
6646 goto done;
6648 error = show_operation_in_progress(worktree, repo);
6649 done:
6650 if (pack_fds) {
6651 const struct got_error *pack_err =
6652 got_repo_pack_fds_close(pack_fds);
6653 if (error == NULL)
6654 error = pack_err;
6656 if (repo) {
6657 close_err = got_repo_close(repo);
6658 if (error == NULL)
6659 error = close_err;
6661 if (worktree != NULL) {
6662 close_err = got_worktree_close(worktree);
6663 if (error == NULL)
6664 error = close_err;
6667 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
6668 free(cwd);
6669 return error;
6672 __dead static void
6673 usage_ref(void)
6675 fprintf(stderr, "usage: %s ref [-dlt] [-c object] [-r repository-path] "
6676 "[-s reference] [name]\n", getprogname());
6677 exit(1);
6680 static const struct got_error *
6681 list_refs(struct got_repository *repo, const char *refname, int sort_by_time)
6683 static const struct got_error *err = NULL;
6684 struct got_reflist_head refs;
6685 struct got_reflist_entry *re;
6687 TAILQ_INIT(&refs);
6688 err = got_ref_list(&refs, repo, refname, sort_by_time ?
6689 got_ref_cmp_by_commit_timestamp_descending : got_ref_cmp_by_name,
6690 repo);
6691 if (err)
6692 return err;
6694 TAILQ_FOREACH(re, &refs, entry) {
6695 char *refstr;
6696 refstr = got_ref_to_str(re->ref);
6697 if (refstr == NULL) {
6698 err = got_error_from_errno("got_ref_to_str");
6699 break;
6701 printf("%s: %s\n", got_ref_get_name(re->ref), refstr);
6702 free(refstr);
6705 got_ref_list_free(&refs);
6706 return err;
6709 static const struct got_error *
6710 delete_ref_by_name(struct got_repository *repo, const char *refname)
6712 const struct got_error *err;
6713 struct got_reference *ref;
6715 err = got_ref_open(&ref, repo, refname, 0);
6716 if (err)
6717 return err;
6719 err = delete_ref(repo, ref);
6720 got_ref_close(ref);
6721 return err;
6724 static const struct got_error *
6725 add_ref(struct got_repository *repo, const char *refname, const char *target)
6727 const struct got_error *err = NULL;
6728 struct got_object_id *id = NULL;
6729 struct got_reference *ref = NULL;
6730 struct got_reflist_head refs;
6733 * Don't let the user create a reference name with a leading '-'.
6734 * While technically a valid reference name, this case is usually
6735 * an unintended typo.
6737 if (refname[0] == '-')
6738 return got_error_path(refname, GOT_ERR_REF_NAME_MINUS);
6740 TAILQ_INIT(&refs);
6741 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
6742 if (err)
6743 goto done;
6744 err = got_repo_match_object_id(&id, NULL, target, GOT_OBJ_TYPE_ANY,
6745 &refs, repo);
6746 got_ref_list_free(&refs);
6747 if (err)
6748 goto done;
6750 err = got_ref_alloc(&ref, refname, id);
6751 if (err)
6752 goto done;
6754 err = got_ref_write(ref, repo);
6755 done:
6756 if (ref)
6757 got_ref_close(ref);
6758 free(id);
6759 return err;
6762 static const struct got_error *
6763 add_symref(struct got_repository *repo, const char *refname, const char *target)
6765 const struct got_error *err = NULL;
6766 struct got_reference *ref = NULL;
6767 struct got_reference *target_ref = NULL;
6770 * Don't let the user create a reference name with a leading '-'.
6771 * While technically a valid reference name, this case is usually
6772 * an unintended typo.
6774 if (refname[0] == '-')
6775 return got_error_path(refname, GOT_ERR_REF_NAME_MINUS);
6777 err = got_ref_open(&target_ref, repo, target, 0);
6778 if (err)
6779 return err;
6781 err = got_ref_alloc_symref(&ref, refname, target_ref);
6782 if (err)
6783 goto done;
6785 err = got_ref_write(ref, repo);
6786 done:
6787 if (target_ref)
6788 got_ref_close(target_ref);
6789 if (ref)
6790 got_ref_close(ref);
6791 return err;
6794 static const struct got_error *
6795 cmd_ref(int argc, char *argv[])
6797 const struct got_error *error = NULL;
6798 struct got_repository *repo = NULL;
6799 struct got_worktree *worktree = NULL;
6800 char *cwd = NULL, *repo_path = NULL;
6801 int ch, do_list = 0, do_delete = 0, sort_by_time = 0;
6802 const char *obj_arg = NULL, *symref_target= NULL;
6803 char *refname = NULL, *keyword_idstr = NULL;
6804 int *pack_fds = NULL;
6806 #ifndef PROFILE
6807 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
6808 "sendfd unveil", NULL) == -1)
6809 err(1, "pledge");
6810 #endif
6812 while ((ch = getopt(argc, argv, "c:dlr:s:t")) != -1) {
6813 switch (ch) {
6814 case 'c':
6815 obj_arg = optarg;
6816 break;
6817 case 'd':
6818 do_delete = 1;
6819 break;
6820 case 'l':
6821 do_list = 1;
6822 break;
6823 case 'r':
6824 repo_path = realpath(optarg, NULL);
6825 if (repo_path == NULL)
6826 return got_error_from_errno2("realpath",
6827 optarg);
6828 got_path_strip_trailing_slashes(repo_path);
6829 break;
6830 case 's':
6831 symref_target = optarg;
6832 break;
6833 case 't':
6834 sort_by_time = 1;
6835 break;
6836 default:
6837 usage_ref();
6838 /* NOTREACHED */
6842 if (obj_arg && do_list)
6843 option_conflict('c', 'l');
6844 if (obj_arg && do_delete)
6845 option_conflict('c', 'd');
6846 if (obj_arg && symref_target)
6847 option_conflict('c', 's');
6848 if (symref_target && do_delete)
6849 option_conflict('s', 'd');
6850 if (symref_target && do_list)
6851 option_conflict('s', 'l');
6852 if (do_delete && do_list)
6853 option_conflict('d', 'l');
6854 if (sort_by_time && !do_list)
6855 errx(1, "-t option requires -l option");
6857 argc -= optind;
6858 argv += optind;
6860 if (do_list) {
6861 if (argc != 0 && argc != 1)
6862 usage_ref();
6863 if (argc == 1) {
6864 refname = strdup(argv[0]);
6865 if (refname == NULL) {
6866 error = got_error_from_errno("strdup");
6867 goto done;
6870 } else {
6871 if (argc != 1)
6872 usage_ref();
6873 refname = strdup(argv[0]);
6874 if (refname == NULL) {
6875 error = got_error_from_errno("strdup");
6876 goto done;
6880 if (refname)
6881 got_path_strip_trailing_slashes(refname);
6883 cwd = getcwd(NULL, 0);
6884 if (cwd == NULL) {
6885 error = got_error_from_errno("getcwd");
6886 goto done;
6889 error = got_repo_pack_fds_open(&pack_fds);
6890 if (error != NULL)
6891 goto done;
6893 if (repo_path == NULL) {
6894 error = got_worktree_open(&worktree, cwd,
6895 GOT_WORKTREE_GOT_DIR);
6896 if (error && error->code != GOT_ERR_NOT_WORKTREE)
6897 goto done;
6898 else
6899 error = NULL;
6900 if (worktree) {
6901 repo_path =
6902 strdup(got_worktree_get_repo_path(worktree));
6903 if (repo_path == NULL)
6904 error = got_error_from_errno("strdup");
6905 if (error)
6906 goto done;
6907 } else {
6908 repo_path = strdup(cwd);
6909 if (repo_path == NULL) {
6910 error = got_error_from_errno("strdup");
6911 goto done;
6916 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
6917 if (error != NULL)
6918 goto done;
6920 #ifndef PROFILE
6921 if (do_list) {
6922 /* Remove "cpath" promise. */
6923 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
6924 NULL) == -1)
6925 err(1, "pledge");
6927 #endif
6929 error = apply_unveil(got_repo_get_path(repo), do_list,
6930 worktree ? got_worktree_get_root_path(worktree) : NULL);
6931 if (error)
6932 goto done;
6934 if (do_list)
6935 error = list_refs(repo, refname, sort_by_time);
6936 else if (do_delete)
6937 error = delete_ref_by_name(repo, refname);
6938 else if (symref_target)
6939 error = add_symref(repo, refname, symref_target);
6940 else {
6941 if (obj_arg == NULL)
6942 usage_ref();
6944 error = got_keyword_to_idstr(&keyword_idstr, obj_arg,
6945 repo, worktree);
6946 if (error != NULL)
6947 goto done;
6948 if (keyword_idstr != NULL)
6949 obj_arg = keyword_idstr;
6951 error = add_ref(repo, refname, obj_arg);
6953 done:
6954 free(refname);
6955 if (repo) {
6956 const struct got_error *close_err = got_repo_close(repo);
6957 if (error == NULL)
6958 error = close_err;
6960 if (worktree)
6961 got_worktree_close(worktree);
6962 if (pack_fds) {
6963 const struct got_error *pack_err =
6964 got_repo_pack_fds_close(pack_fds);
6965 if (error == NULL)
6966 error = pack_err;
6968 free(cwd);
6969 free(repo_path);
6970 free(keyword_idstr);
6971 return error;
6974 __dead static void
6975 usage_branch(void)
6977 fprintf(stderr, "usage: %s branch [-lnt] [-c commit] [-d name] "
6978 "[-r repository-path] [name]\n", getprogname());
6979 exit(1);
6982 static const struct got_error *
6983 list_branch(struct got_repository *repo, struct got_worktree *worktree,
6984 struct got_reference *ref)
6986 const struct got_error *err = NULL;
6987 const char *refname;
6988 char *refstr;
6989 char marker = ' ';
6991 refname = got_ref_get_name(ref);
6992 if (worktree && strcmp(refname,
6993 got_worktree_get_head_ref_name(worktree)) == 0) {
6994 err = got_worktree_get_state(&marker, repo, worktree,
6995 check_cancelled, NULL);
6996 if (err != NULL)
6997 return err;
7000 if (strncmp(refname, "refs/heads/", 11) == 0)
7001 refname += 11;
7002 if (strncmp(refname, "refs/got/worktree/", 18) == 0)
7003 refname += 18;
7004 if (strncmp(refname, "refs/remotes/", 13) == 0)
7005 refname += 13;
7007 refstr = got_ref_to_str(ref);
7008 if (refstr == NULL)
7009 return got_error_from_errno("got_ref_to_str");
7011 printf("%c %s: %s\n", marker, refname, refstr);
7012 free(refstr);
7013 return NULL;
7016 static const struct got_error *
7017 show_current_branch(struct got_repository *repo, struct got_worktree *worktree)
7019 const char *refname;
7021 if (worktree == NULL)
7022 return got_error(GOT_ERR_NOT_WORKTREE);
7024 refname = got_worktree_get_head_ref_name(worktree);
7026 if (strncmp(refname, "refs/heads/", 11) == 0)
7027 refname += 11;
7028 if (strncmp(refname, "refs/got/worktree/", 18) == 0)
7029 refname += 18;
7031 printf("%s\n", refname);
7033 return NULL;
7036 static const struct got_error *
7037 list_branches(struct got_repository *repo, struct got_worktree *worktree,
7038 int sort_by_time)
7040 static const struct got_error *err = NULL;
7041 struct got_reflist_head refs;
7042 struct got_reflist_entry *re;
7043 struct got_reference *temp_ref = NULL;
7044 int rebase_in_progress, histedit_in_progress;
7046 TAILQ_INIT(&refs);
7048 if (worktree) {
7049 err = got_worktree_rebase_in_progress(&rebase_in_progress,
7050 worktree);
7051 if (err)
7052 return err;
7054 err = got_worktree_histedit_in_progress(&histedit_in_progress,
7055 worktree);
7056 if (err)
7057 return err;
7059 if (rebase_in_progress || histedit_in_progress) {
7060 err = got_ref_open(&temp_ref, repo,
7061 got_worktree_get_head_ref_name(worktree), 0);
7062 if (err)
7063 return err;
7064 list_branch(repo, worktree, temp_ref);
7065 got_ref_close(temp_ref);
7069 err = got_ref_list(&refs, repo, "refs/heads", sort_by_time ?
7070 got_ref_cmp_by_commit_timestamp_descending : got_ref_cmp_by_name,
7071 repo);
7072 if (err)
7073 return err;
7075 TAILQ_FOREACH(re, &refs, entry)
7076 list_branch(repo, worktree, re->ref);
7078 got_ref_list_free(&refs);
7080 err = got_ref_list(&refs, repo, "refs/remotes", sort_by_time ?
7081 got_ref_cmp_by_commit_timestamp_descending : got_ref_cmp_by_name,
7082 repo);
7083 if (err)
7084 return err;
7086 TAILQ_FOREACH(re, &refs, entry)
7087 list_branch(repo, worktree, re->ref);
7089 got_ref_list_free(&refs);
7091 return NULL;
7094 static const struct got_error *
7095 delete_branch(struct got_repository *repo, struct got_worktree *worktree,
7096 const char *branch_name)
7098 const struct got_error *err = NULL;
7099 struct got_reference *ref = NULL;
7100 char *refname, *remote_refname = NULL;
7102 if (strncmp(branch_name, "refs/", 5) == 0)
7103 branch_name += 5;
7104 if (strncmp(branch_name, "heads/", 6) == 0)
7105 branch_name += 6;
7106 else if (strncmp(branch_name, "remotes/", 8) == 0)
7107 branch_name += 8;
7109 if (asprintf(&refname, "refs/heads/%s", branch_name) == -1)
7110 return got_error_from_errno("asprintf");
7112 if (asprintf(&remote_refname, "refs/remotes/%s",
7113 branch_name) == -1) {
7114 err = got_error_from_errno("asprintf");
7115 goto done;
7118 err = got_ref_open(&ref, repo, refname, 0);
7119 if (err) {
7120 const struct got_error *err2;
7121 if (err->code != GOT_ERR_NOT_REF)
7122 goto done;
7124 * Keep 'err' intact such that if neither branch exists
7125 * we report "refs/heads" rather than "refs/remotes" in
7126 * our error message.
7128 err2 = got_ref_open(&ref, repo, remote_refname, 0);
7129 if (err2)
7130 goto done;
7131 err = NULL;
7134 if (worktree &&
7135 strcmp(got_worktree_get_head_ref_name(worktree),
7136 got_ref_get_name(ref)) == 0) {
7137 err = got_error_msg(GOT_ERR_SAME_BRANCH,
7138 "will not delete this work tree's current branch");
7139 goto done;
7142 err = delete_ref(repo, ref);
7143 done:
7144 if (ref)
7145 got_ref_close(ref);
7146 free(refname);
7147 free(remote_refname);
7148 return err;
7151 static const struct got_error *
7152 add_branch(struct got_repository *repo, const char *branch_name,
7153 struct got_object_id *base_commit_id)
7155 const struct got_error *err = NULL;
7156 struct got_reference *ref = NULL;
7157 char *refname = NULL;
7160 * Don't let the user create a branch name with a leading '-'.
7161 * While technically a valid reference name, this case is usually
7162 * an unintended typo.
7164 if (branch_name[0] == '-')
7165 return got_error_path(branch_name, GOT_ERR_REF_NAME_MINUS);
7167 if (strncmp(branch_name, "refs/heads/", 11) == 0)
7168 branch_name += 11;
7170 if (asprintf(&refname, "refs/heads/%s", branch_name) == -1) {
7171 err = got_error_from_errno("asprintf");
7172 goto done;
7175 err = got_ref_open(&ref, repo, refname, 0);
7176 if (err == NULL) {
7177 err = got_error(GOT_ERR_BRANCH_EXISTS);
7178 goto done;
7179 } else if (err->code != GOT_ERR_NOT_REF)
7180 goto done;
7182 err = got_ref_alloc(&ref, refname, base_commit_id);
7183 if (err)
7184 goto done;
7186 err = got_ref_write(ref, repo);
7187 done:
7188 if (ref)
7189 got_ref_close(ref);
7190 free(refname);
7191 return err;
7194 static const struct got_error *
7195 cmd_branch(int argc, char *argv[])
7197 const struct got_error *error = NULL;
7198 struct got_repository *repo = NULL;
7199 struct got_worktree *worktree = NULL;
7200 char *cwd = NULL, *repo_path = NULL;
7201 int ch, do_list = 0, do_show = 0, do_update = 1, sort_by_time = 0;
7202 const char *delref = NULL, *commit_id_arg = NULL;
7203 struct got_reference *ref = NULL;
7204 struct got_pathlist_head paths;
7205 struct got_object_id *commit_id = NULL;
7206 char *commit_id_str = NULL, *keyword_idstr = NULL;;
7207 int *pack_fds = NULL;
7209 TAILQ_INIT(&paths);
7211 #ifndef PROFILE
7212 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
7213 "sendfd unveil", NULL) == -1)
7214 err(1, "pledge");
7215 #endif
7217 while ((ch = getopt(argc, argv, "c:d:lnr:t")) != -1) {
7218 switch (ch) {
7219 case 'c':
7220 commit_id_arg = optarg;
7221 break;
7222 case 'd':
7223 delref = optarg;
7224 break;
7225 case 'l':
7226 do_list = 1;
7227 break;
7228 case 'n':
7229 do_update = 0;
7230 break;
7231 case 'r':
7232 repo_path = realpath(optarg, NULL);
7233 if (repo_path == NULL)
7234 return got_error_from_errno2("realpath",
7235 optarg);
7236 got_path_strip_trailing_slashes(repo_path);
7237 break;
7238 case 't':
7239 sort_by_time = 1;
7240 break;
7241 default:
7242 usage_branch();
7243 /* NOTREACHED */
7247 if (do_list && delref)
7248 option_conflict('l', 'd');
7249 if (sort_by_time && !do_list)
7250 errx(1, "-t option requires -l option");
7252 argc -= optind;
7253 argv += optind;
7255 if (!do_list && !delref && argc == 0)
7256 do_show = 1;
7258 if ((do_list || delref || do_show) && commit_id_arg != NULL)
7259 errx(1, "-c option can only be used when creating a branch");
7261 if (do_list || delref) {
7262 if (argc > 0)
7263 usage_branch();
7264 } else if (!do_show && argc != 1)
7265 usage_branch();
7267 cwd = getcwd(NULL, 0);
7268 if (cwd == NULL) {
7269 error = got_error_from_errno("getcwd");
7270 goto done;
7273 error = got_repo_pack_fds_open(&pack_fds);
7274 if (error != NULL)
7275 goto done;
7277 if (repo_path == NULL) {
7278 error = got_worktree_open(&worktree, cwd,
7279 GOT_WORKTREE_GOT_DIR);
7280 if (error && error->code != GOT_ERR_NOT_WORKTREE)
7281 goto done;
7282 else
7283 error = NULL;
7284 if (worktree) {
7285 repo_path =
7286 strdup(got_worktree_get_repo_path(worktree));
7287 if (repo_path == NULL)
7288 error = got_error_from_errno("strdup");
7289 if (error)
7290 goto done;
7291 } else {
7292 repo_path = strdup(cwd);
7293 if (repo_path == NULL) {
7294 error = got_error_from_errno("strdup");
7295 goto done;
7300 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
7301 if (error != NULL)
7302 goto done;
7304 #ifndef PROFILE
7305 if (do_list || do_show) {
7306 /* Remove "cpath" promise. */
7307 if (pledge("stdio rpath wpath flock proc exec sendfd unveil",
7308 NULL) == -1)
7309 err(1, "pledge");
7311 #endif
7313 error = apply_unveil(got_repo_get_path(repo), do_list,
7314 worktree ? got_worktree_get_root_path(worktree) : NULL);
7315 if (error)
7316 goto done;
7318 if (do_show)
7319 error = show_current_branch(repo, worktree);
7320 else if (do_list)
7321 error = list_branches(repo, worktree, sort_by_time);
7322 else if (delref)
7323 error = delete_branch(repo, worktree, delref);
7324 else {
7325 struct got_reflist_head refs;
7326 TAILQ_INIT(&refs);
7327 error = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name,
7328 NULL);
7329 if (error)
7330 goto done;
7331 if (commit_id_arg == NULL)
7332 commit_id_arg = worktree ?
7333 got_worktree_get_head_ref_name(worktree) :
7334 GOT_REF_HEAD;
7335 else {
7336 error = got_keyword_to_idstr(&keyword_idstr,
7337 commit_id_arg, repo, worktree);
7338 if (error != NULL)
7339 goto done;
7340 if (keyword_idstr != NULL)
7341 commit_id_arg = keyword_idstr;
7343 error = got_repo_match_object_id(&commit_id, NULL,
7344 commit_id_arg, GOT_OBJ_TYPE_COMMIT, &refs, repo);
7345 got_ref_list_free(&refs);
7346 if (error)
7347 goto done;
7348 error = add_branch(repo, argv[0], commit_id);
7349 if (error)
7350 goto done;
7351 if (worktree && do_update) {
7352 struct got_update_progress_arg upa;
7353 char *branch_refname = NULL;
7355 error = got_object_id_str(&commit_id_str, commit_id);
7356 if (error)
7357 goto done;
7358 error = get_worktree_paths_from_argv(&paths, 0, NULL,
7359 worktree);
7360 if (error)
7361 goto done;
7362 if (asprintf(&branch_refname, "refs/heads/%s", argv[0])
7363 == -1) {
7364 error = got_error_from_errno("asprintf");
7365 goto done;
7367 error = got_ref_open(&ref, repo, branch_refname, 0);
7368 free(branch_refname);
7369 if (error)
7370 goto done;
7371 error = switch_head_ref(ref, commit_id, worktree,
7372 repo);
7373 if (error)
7374 goto done;
7375 error = got_worktree_set_base_commit_id(worktree, repo,
7376 commit_id);
7377 if (error)
7378 goto done;
7379 memset(&upa, 0, sizeof(upa));
7380 error = got_worktree_checkout_files(worktree, &paths,
7381 repo, update_progress, &upa, check_cancelled,
7382 NULL);
7383 if (error)
7384 goto done;
7385 if (upa.did_something) {
7386 printf("Updated to %s: %s\n",
7387 got_worktree_get_head_ref_name(worktree),
7388 commit_id_str);
7390 print_update_progress_stats(&upa);
7393 done:
7394 free(keyword_idstr);
7395 if (ref)
7396 got_ref_close(ref);
7397 if (repo) {
7398 const struct got_error *close_err = got_repo_close(repo);
7399 if (error == NULL)
7400 error = close_err;
7402 if (worktree)
7403 got_worktree_close(worktree);
7404 if (pack_fds) {
7405 const struct got_error *pack_err =
7406 got_repo_pack_fds_close(pack_fds);
7407 if (error == NULL)
7408 error = pack_err;
7410 free(cwd);
7411 free(repo_path);
7412 free(commit_id);
7413 free(commit_id_str);
7414 got_pathlist_free(&paths, GOT_PATHLIST_FREE_PATH);
7415 return error;
7419 __dead static void
7420 usage_tag(void)
7422 fprintf(stderr, "usage: %s tag [-lVv] [-c commit] [-m message] "
7423 "[-r repository-path] [-s signer-id] name\n", getprogname());
7424 exit(1);
7427 #if 0
7428 static const struct got_error *
7429 sort_tags(struct got_reflist_head *sorted, struct got_reflist_head *tags)
7431 const struct got_error *err = NULL;
7432 struct got_reflist_entry *re, *se, *new;
7433 struct got_object_id *re_id, *se_id;
7434 struct got_tag_object *re_tag, *se_tag;
7435 time_t re_time, se_time;
7437 STAILQ_FOREACH(re, tags, entry) {
7438 se = STAILQ_FIRST(sorted);
7439 if (se == NULL) {
7440 err = got_reflist_entry_dup(&new, re);
7441 if (err)
7442 return err;
7443 STAILQ_INSERT_HEAD(sorted, new, entry);
7444 continue;
7445 } else {
7446 err = got_ref_resolve(&re_id, repo, re->ref);
7447 if (err)
7448 break;
7449 err = got_object_open_as_tag(&re_tag, repo, re_id);
7450 free(re_id);
7451 if (err)
7452 break;
7453 re_time = got_object_tag_get_tagger_time(re_tag);
7454 got_object_tag_close(re_tag);
7457 while (se) {
7458 err = got_ref_resolve(&se_id, repo, re->ref);
7459 if (err)
7460 break;
7461 err = got_object_open_as_tag(&se_tag, repo, se_id);
7462 free(se_id);
7463 if (err)
7464 break;
7465 se_time = got_object_tag_get_tagger_time(se_tag);
7466 got_object_tag_close(se_tag);
7468 if (se_time > re_time) {
7469 err = got_reflist_entry_dup(&new, re);
7470 if (err)
7471 return err;
7472 STAILQ_INSERT_AFTER(sorted, se, new, entry);
7473 break;
7475 se = STAILQ_NEXT(se, entry);
7476 continue;
7479 done:
7480 return err;
7482 #endif
7484 static const struct got_error *
7485 get_tag_refname(char **refname, const char *tag_name)
7487 const struct got_error *err;
7489 if (strncmp("refs/tags/", tag_name, 10) == 0) {
7490 *refname = strdup(tag_name);
7491 if (*refname == NULL)
7492 return got_error_from_errno("strdup");
7493 } else if (asprintf(refname, "refs/tags/%s", tag_name) == -1) {
7494 err = got_error_from_errno("asprintf");
7495 *refname = NULL;
7496 return err;
7499 return NULL;
7502 static const struct got_error *
7503 list_tags(struct got_repository *repo, const char *tag_name, int verify_tags,
7504 const char *allowed_signers, const char *revoked_signers, int verbosity)
7506 static const struct got_error *err = NULL;
7507 struct got_reflist_head refs;
7508 struct got_reflist_entry *re;
7509 char *wanted_refname = NULL;
7510 int bad_sigs = 0;
7512 TAILQ_INIT(&refs);
7514 err = got_ref_list(&refs, repo, "refs/tags", got_ref_cmp_tags, repo);
7515 if (err)
7516 return err;
7518 if (tag_name) {
7519 struct got_reference *ref;
7520 err = get_tag_refname(&wanted_refname, tag_name);
7521 if (err)
7522 goto done;
7523 /* Wanted tag reference should exist. */
7524 err = got_ref_open(&ref, repo, wanted_refname, 0);
7525 if (err)
7526 goto done;
7527 got_ref_close(ref);
7530 TAILQ_FOREACH(re, &refs, entry) {
7531 const char *refname;
7532 char *refstr, *tagmsg0, *tagmsg, *line, *id_str, *datestr;
7533 char datebuf[26];
7534 const char *tagger, *ssh_sig = NULL;
7535 char *sig_msg = NULL;
7536 time_t tagger_time;
7537 struct got_object_id *id;
7538 struct got_tag_object *tag;
7539 struct got_commit_object *commit = NULL;
7541 refname = got_ref_get_name(re->ref);
7542 if (strncmp(refname, "refs/tags/", 10) != 0 ||
7543 (wanted_refname && strcmp(refname, wanted_refname) != 0))
7544 continue;
7545 refname += 10;
7546 refstr = got_ref_to_str(re->ref);
7547 if (refstr == NULL) {
7548 err = got_error_from_errno("got_ref_to_str");
7549 break;
7552 err = got_ref_resolve(&id, repo, re->ref);
7553 if (err)
7554 break;
7555 err = got_object_open_as_tag(&tag, repo, id);
7556 if (err) {
7557 if (err->code != GOT_ERR_OBJ_TYPE) {
7558 free(id);
7559 break;
7561 /* "lightweight" tag */
7562 err = got_object_open_as_commit(&commit, repo, id);
7563 if (err) {
7564 free(id);
7565 break;
7567 tagger = got_object_commit_get_committer(commit);
7568 tagger_time =
7569 got_object_commit_get_committer_time(commit);
7570 err = got_object_id_str(&id_str, id);
7571 free(id);
7572 if (err)
7573 break;
7574 } else {
7575 free(id);
7576 tagger = got_object_tag_get_tagger(tag);
7577 tagger_time = got_object_tag_get_tagger_time(tag);
7578 err = got_object_id_str(&id_str,
7579 got_object_tag_get_object_id(tag));
7580 if (err)
7581 break;
7584 if (tag && verify_tags) {
7585 ssh_sig = got_sigs_get_tagmsg_ssh_signature(
7586 got_object_tag_get_message(tag));
7587 if (ssh_sig && allowed_signers == NULL) {
7588 err = got_error_msg(
7589 GOT_ERR_VERIFY_TAG_SIGNATURE,
7590 "SSH signature verification requires "
7591 "setting allowed_signers in "
7592 "got.conf(5)");
7593 break;
7597 printf("%stag %s %s\n", GOT_COMMIT_SEP_STR, refname, refstr);
7598 free(refstr);
7599 printf("from: %s\n", tagger);
7600 datestr = get_datestr(&tagger_time, datebuf);
7601 if (datestr)
7602 printf("date: %s UTC\n", datestr);
7603 if (commit)
7604 printf("object: %s %s\n", GOT_OBJ_LABEL_COMMIT, id_str);
7605 else {
7606 switch (got_object_tag_get_object_type(tag)) {
7607 case GOT_OBJ_TYPE_BLOB:
7608 printf("object: %s %s\n", GOT_OBJ_LABEL_BLOB,
7609 id_str);
7610 break;
7611 case GOT_OBJ_TYPE_TREE:
7612 printf("object: %s %s\n", GOT_OBJ_LABEL_TREE,
7613 id_str);
7614 break;
7615 case GOT_OBJ_TYPE_COMMIT:
7616 printf("object: %s %s\n", GOT_OBJ_LABEL_COMMIT,
7617 id_str);
7618 break;
7619 case GOT_OBJ_TYPE_TAG:
7620 printf("object: %s %s\n", GOT_OBJ_LABEL_TAG,
7621 id_str);
7622 break;
7623 default:
7624 break;
7627 free(id_str);
7629 if (ssh_sig) {
7630 err = got_sigs_verify_tag_ssh(&sig_msg, tag, ssh_sig,
7631 allowed_signers, revoked_signers, verbosity);
7632 if (err && err->code == GOT_ERR_BAD_TAG_SIGNATURE)
7633 bad_sigs = 1;
7634 else if (err)
7635 break;
7636 printf("signature: %s", sig_msg);
7637 free(sig_msg);
7638 sig_msg = NULL;
7641 if (commit) {
7642 err = got_object_commit_get_logmsg(&tagmsg0, commit);
7643 if (err)
7644 break;
7645 got_object_commit_close(commit);
7646 } else {
7647 tagmsg0 = strdup(got_object_tag_get_message(tag));
7648 got_object_tag_close(tag);
7649 if (tagmsg0 == NULL) {
7650 err = got_error_from_errno("strdup");
7651 break;
7655 tagmsg = tagmsg0;
7656 do {
7657 line = strsep(&tagmsg, "\n");
7658 if (line)
7659 printf(" %s\n", line);
7660 } while (line);
7661 free(tagmsg0);
7663 done:
7664 got_ref_list_free(&refs);
7665 free(wanted_refname);
7667 if (err == NULL && bad_sigs)
7668 err = got_error(GOT_ERR_BAD_TAG_SIGNATURE);
7669 return err;
7672 static const struct got_error *
7673 get_tag_message(char **tagmsg, char **tagmsg_path, const char *commit_id_str,
7674 const char *tag_name, const char *editor, const char *repo_path)
7676 const struct got_error *err = NULL;
7677 char *template = NULL, *initial_content = NULL;
7678 int initial_content_len;
7679 int fd = -1;
7681 if (asprintf(&template, GOT_TMPDIR_STR "/got-tagmsg") == -1) {
7682 err = got_error_from_errno("asprintf");
7683 goto done;
7686 initial_content_len = asprintf(&initial_content,
7687 "\n# tagging commit %s as %s\n",
7688 commit_id_str, tag_name);
7689 if (initial_content_len == -1) {
7690 err = got_error_from_errno("asprintf");
7691 goto done;
7694 err = got_opentemp_named_fd(tagmsg_path, &fd, template, "");
7695 if (err)
7696 goto done;
7698 if (write(fd, initial_content, initial_content_len) == -1) {
7699 err = got_error_from_errno2("write", *tagmsg_path);
7700 goto done;
7702 if (close(fd) == -1) {
7703 err = got_error_from_errno2("close", *tagmsg_path);
7704 goto done;
7706 fd = -1;
7708 err = edit_logmsg(tagmsg, editor, *tagmsg_path, initial_content,
7709 initial_content_len, 1);
7710 done:
7711 free(initial_content);
7712 free(template);
7714 if (fd != -1 && close(fd) == -1 && err == NULL)
7715 err = got_error_from_errno2("close", *tagmsg_path);
7717 if (err) {
7718 free(*tagmsg);
7719 *tagmsg = NULL;
7721 return err;
7724 static const struct got_error *
7725 add_tag(struct got_repository *repo, const char *tagger,
7726 const char *tag_name, const char *commit_arg, const char *tagmsg_arg,
7727 const char *signer_id, const char *editor, int verbosity)
7729 const struct got_error *err = NULL;
7730 struct got_object_id *commit_id = NULL, *tag_id = NULL;
7731 char *label = NULL, *commit_id_str = NULL;
7732 struct got_reference *ref = NULL;
7733 char *refname = NULL, *tagmsg = NULL;
7734 char *tagmsg_path = NULL, *tag_id_str = NULL;
7735 int preserve_tagmsg = 0;
7736 struct got_reflist_head refs;
7738 TAILQ_INIT(&refs);
7741 * Don't let the user create a tag name with a leading '-'.
7742 * While technically a valid reference name, this case is usually
7743 * an unintended typo.
7745 if (tag_name[0] == '-')
7746 return got_error_path(tag_name, GOT_ERR_REF_NAME_MINUS);
7748 err = got_ref_list(&refs, repo, NULL, got_ref_cmp_by_name, NULL);
7749 if (err)
7750 goto done;
7752 err = got_repo_match_object_id(&commit_id, &label, commit_arg,
7753 GOT_OBJ_TYPE_COMMIT, &refs, repo);
7754 if (err)
7755 goto done;
7757 err = got_object_id_str(&commit_id_str, commit_id);
7758 if (err)
7759 goto done;
7761 err = get_tag_refname(&refname, tag_name);
7762 if (err)
7763 goto done;
7764 if (strncmp("refs/tags/", tag_name, 10) == 0)
7765 tag_name += 10;
7767 err = got_ref_open(&ref, repo, refname, 0);
7768 if (err == NULL) {
7769 err = got_error(GOT_ERR_TAG_EXISTS);
7770 goto done;
7771 } else if (err->code != GOT_ERR_NOT_REF)
7772 goto done;
7774 if (tagmsg_arg == NULL) {
7775 err = get_tag_message(&tagmsg, &tagmsg_path, commit_id_str,
7776 tag_name, editor, got_repo_get_path(repo));
7777 if (err) {
7778 if (err->code != GOT_ERR_COMMIT_MSG_EMPTY &&
7779 tagmsg_path != NULL)
7780 preserve_tagmsg = 1;
7781 goto done;
7785 err = got_object_tag_create(&tag_id, tag_name, commit_id,
7786 tagger, time(NULL), tagmsg ? tagmsg : tagmsg_arg, signer_id, repo,
7787 verbosity);
7788 if (err) {
7789 if (tagmsg_path)
7790 preserve_tagmsg = 1;
7791 goto done;
7794 err = got_ref_alloc(&ref, refname, tag_id);
7795 if (err) {
7796 if (tagmsg_path)
7797 preserve_tagmsg = 1;
7798 goto done;
7801 err = got_ref_write(ref, repo);
7802 if (err) {
7803 if (tagmsg_path)
7804 preserve_tagmsg = 1;
7805 goto done;
7808 err = got_object_id_str(&tag_id_str, tag_id);
7809 if (err) {
7810 if (tagmsg_path)
7811 preserve_tagmsg = 1;
7812 goto done;
7814 printf("Created tag %s\n", tag_id_str);
7815 done:
7816 if (preserve_tagmsg) {
7817 fprintf(stderr, "%s: tag message preserved in %s\n",
7818 getprogname(), tagmsg_path);
7819 } else if (tagmsg_path && unlink(tagmsg_path) == -1 && err == NULL)
7820 err = got_error_from_errno2("unlink", tagmsg_path);
7821 free(tag_id_str);
7822 if (ref)
7823 got_ref_close(ref);
7824 free(commit_id);
7825 free(commit_id_str);
7826 free(refname);
7827 free(tagmsg);
7828 free(tagmsg_path);
7829 got_ref_list_free(&refs);
7830 return err;
7833 static const struct got_error *
7834 cmd_tag(int argc, char *argv[])
7836 const struct got_error *error = NULL;
7837 struct got_repository *repo = NULL;
7838 struct got_worktree *worktree = NULL;
7839 char *cwd = NULL, *repo_path = NULL, *commit_id_str = NULL;
7840 char *gitconfig_path = NULL, *tagger = NULL, *keyword_idstr = NULL;
7841 char *allowed_signers = NULL, *revoked_signers = NULL, *editor = NULL;
7842 const char *signer_id = NULL;
7843 const char *tag_name = NULL, *commit_id_arg = NULL, *tagmsg = NULL;
7844 int ch, do_list = 0, verify_tags = 0, verbosity = 0;
7845 int *pack_fds = NULL;
7847 #ifndef PROFILE
7848 if (pledge("stdio rpath wpath cpath fattr flock proc exec "
7849 "sendfd unveil", NULL) == -1)
7850 err(1, "pledge");
7851 #endif
7853 while ((ch = getopt(argc, argv, "c:lm:r:s:Vv")) != -1) {
7854 switch (ch) {
7855 case 'c':
7856 commit_id_arg = optarg;
7857 break;
7858 case 'l':
7859 do_list = 1;
7860 break;
7861 case 'm':
7862 tagmsg = optarg;
7863 break;
7864 case 'r':
7865 repo_path = realpath(optarg, NULL);
7866 if (repo_path == NULL) {
7867 error = got_error_from_errno2("realpath",
7868 optarg);
7869 goto done;
7871 got_path_strip_trailing_slashes(repo_path);
7872 break;
7873 case 's':
7874 signer_id = optarg;
7875 break;
7876 case 'V':
7877 verify_tags = 1;
7878 break;
7879 case 'v':
7880 if (verbosity < 0)
7881 verbosity = 0;
7882 else if (verbosity < 3)
7883 verbosity++;
7884 break;
7885 default:
7886 usage_tag();
7887 /* NOTREACHED */
7891 argc -= optind;
7892 argv += optind;
7894 if (do_list || verify_tags) {
7895 if (commit_id_arg != NULL)
7896 errx(1,
7897 "-c option can only be used when creating a tag");
7898 if (tagmsg) {
7899 if (do_list)
7900 option_conflict('l', 'm');
7901 else
7902 option_conflict('V', 'm');
7904 if (signer_id) {
7905 if (do_list)
7906 option_conflict('l', 's');
7907 else
7908 option_conflict('V', 's');
7910 if (argc > 1)
7911 usage_tag();
7912 } else if (argc != 1)
7913 usage_tag();
7915 if (argc == 1)
7916 tag_name = argv[0];
7918 cwd = getcwd(NULL, 0);
7919 if (cwd == NULL) {
7920 error = got_error_from_errno("getcwd");
7921 goto done;
7924 error = got_repo_pack_fds_open(&pack_fds);
7925 if (error != NULL)
7926 goto done;
7928 if (repo_path == NULL) {
7929 error = got_worktree_open(&worktree, cwd,
7930 GOT_WORKTREE_GOT_DIR);
7931 if (error && error->code != GOT_ERR_NOT_WORKTREE)
7932 goto done;
7933 else
7934 error = NULL;
7935 if (worktree) {
7936 repo_path =
7937 strdup(got_worktree_get_repo_path(worktree));
7938 if (repo_path == NULL)
7939 error = got_error_from_errno("strdup");
7940 if (error)
7941 goto done;
7942 } else {
7943 repo_path = strdup(cwd);
7944 if (repo_path == NULL) {
7945 error = got_error_from_errno("strdup");
7946 goto done;
7951 if (do_list || verify_tags) {
7952 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
7953 if (error != NULL)
7954 goto done;
7955 error = get_allowed_signers(&allowed_signers, repo, worktree);
7956 if (error)
7957 goto done;
7958 error = get_revoked_signers(&revoked_signers, repo, worktree);
7959 if (error)
7960 goto done;
7961 if (worktree) {
7962 /* Release work tree lock. */
7963 got_worktree_close(worktree);
7964 worktree = NULL;
7968 * Remove "cpath" promise unless needed for signature tmpfile
7969 * creation.
7971 if (verify_tags)
7972 got_sigs_apply_unveil();
7973 else {
7974 #ifndef PROFILE
7975 if (pledge("stdio rpath wpath flock proc exec sendfd "
7976 "unveil", NULL) == -1)
7977 err(1, "pledge");
7978 #endif
7980 error = apply_unveil(got_repo_get_path(repo), 1, NULL);
7981 if (error)
7982 goto done;
7983 error = list_tags(repo, tag_name, verify_tags, allowed_signers,
7984 revoked_signers, verbosity);
7985 } else {
7986 error = get_gitconfig_path(&gitconfig_path);
7987 if (error)
7988 goto done;
7989 error = got_repo_open(&repo, repo_path, gitconfig_path,
7990 pack_fds);
7991 if (error != NULL)
7992 goto done;
7994 error = get_author(&tagger, repo, worktree);
7995 if (error)
7996 goto done;
7997 if (signer_id == NULL)
7998 signer_id = get_signer_id(repo, worktree);
8000 if (tagmsg == NULL) {
8001 error = get_editor(&editor);
8002 if (error)
8003 goto done;
8004 if (unveil(editor, "x") != 0) {
8005 error = got_error_from_errno2("unveil", editor);
8006 goto done;
8009 if (signer_id) {
8010 error = got_sigs_apply_unveil();
8011 if (error)
8012 goto done;
8014 error = apply_unveil(got_repo_get_path(repo), 0, NULL);
8015 if (error)
8016 goto done;
8018 if (commit_id_arg == NULL) {
8019 struct got_reference *head_ref;
8020 struct got_object_id *commit_id;
8021 error = got_ref_open(&head_ref, repo,
8022 worktree ? got_worktree_get_head_ref_name(worktree)
8023 : GOT_REF_HEAD, 0);
8024 if (error)
8025 goto done;
8026 error = got_ref_resolve(&commit_id, repo, head_ref);
8027 got_ref_close(head_ref);
8028 if (error)
8029 goto done;
8030 error = got_object_id_str(&commit_id_str, commit_id);
8031 free(commit_id);
8032 if (error)
8033 goto done;
8034 } else {
8035 error = got_keyword_to_idstr(&keyword_idstr,
8036 commit_id_arg, repo, worktree);
8037 if (error != NULL)
8038 goto done;
8039 commit_id_str = keyword_idstr;
8042 if (worktree) {
8043 /* Release work tree lock. */
8044 got_worktree_close(worktree);
8045 worktree = NULL;
8048 error = add_tag(repo, tagger, tag_name,
8049 commit_id_str ? commit_id_str : commit_id_arg, tagmsg,
8050 signer_id, editor, verbosity);
8052 done:
8053 if (repo) {
8054 const struct got_error *close_err = got_repo_close(repo);
8055 if (error == NULL)
8056 error = close_err;
8058 if (worktree)
8059 got_worktree_close(worktree);
8060 if (pack_fds) {
8061 const struct got_error *pack_err =
8062 got_repo_pack_fds_close(pack_fds);
8063 if (error == NULL)
8064 error = pack_err;
8066 free(cwd);
8067 free(editor);
8068 free(repo_path);
8069 free(gitconfig_path);
8070 free(commit_id_str);
8071 free(tagger);
8072 free(allowed_signers);
8073 free(revoked_signers);
8074 return error;
8077 __dead static void
8078 usage_add(void)
8080 fprintf(stderr, "usage: %s add [-IR] path ...\n", getprogname());
8081 exit(1);
8084 static const struct got_error *
8085 add_progress(void *arg, unsigned char status, const char *path)
8087 while (path[0] == '/')
8088 path++;
8089 printf("%c %s\n", status, path);
8090 return NULL;
8093 static const struct got_error *